@sbuilder/cli 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin/sb.js CHANGED
@@ -10,7 +10,7 @@ import { lstat } from 'node:fs/promises';
10
10
  import { realpathSync } from 'node:fs';
11
11
  import { homedir, userInfo } from 'node:os';
12
12
  import { resolve } from 'node:path';
13
- import { init, nextSteps, InitError } from '../src/init.js';
13
+ import { init, nextSteps, normalizeName, InitError } from '../src/init.js';
14
14
  import { readConfig, watchAndUpload, DevError } from '../src/dev.js';
15
15
  import { deploy, submit, DeployStopped } from '../src/deploy.js';
16
16
  import { readPair, storedAuth } from '../src/auth.js';
@@ -19,11 +19,12 @@ import { pull, push, ROOT_LINKED } from '../src/code.js';
19
19
  import { agent } from '../src/agent.js';
20
20
  import { servicePlan, install, uninstall, status } from '../src/service.js';
21
21
  import { newSite } from '../src/new.js';
22
- import { exportNext, ExportError } from '../src/export.js';
23
22
  import { pull as sitePull, push as sitePush, publish as sitePublish, blocks as siteBlocks, } from '../src/site.js';
24
23
  import { initSite, nextSteps as siteNextSteps, buildPrompt } from '../src/siteinit.js';
25
24
  import { mcp, siteEnv } from '../src/repo.js';
26
25
  import { initNext } from '../src/next.js';
26
+ import { route, SUBCOMMANDS } from '../src/route.js';
27
+ import { createApp, createdSteps } from '../src/appcreate.js';
27
28
  import { VERSION } from '../src/login.js';
28
29
  import { spawnSync } from 'node:child_process';
29
30
  import { createInterface } from 'node:readline/promises';
@@ -34,7 +35,21 @@ Start
34
35
  repo for one of your sites, or an app (same as
35
36
  npm create sbuilder-app)
36
37
 
38
+ Account
39
+ sb login sign in through the browser: opens <editor>/device,
40
+ where you type the code it prints; stores a
41
+ credential that renews itself
42
+ sb logout sign this machine out and forget the credential
43
+ sb whoami which account (and platform) this CLI acts as
44
+
37
45
  Sites
46
+ sb site new "<description>" [--dir <path>] [--github] [--editor]
47
+ make a site from one sentence: creates it and a repo
48
+ for it, then offers to start Claude Code there with
49
+ your description. --github also creates the private
50
+ repo (gh). --editor builds it in the editor instead:
51
+ opens it and the assistant starts building, on this
52
+ machine's Claude Code login when it can.
38
53
  sb site init [dir] [--site <id>] [--github]
39
54
  a repo holding one site's pages: picks the site,
40
55
  pulls it, adds a GitHub workflow that syncs both
@@ -50,21 +65,32 @@ Sites
50
65
  with the line to paste into a page file
51
66
  sb site next make the repo a Next.js app serving its pages, rendered
52
67
  by the platform's own renderer (npm run dev to preview)
53
- sb code pull [--site <id>] [--dir <path>] [--force]
68
+ sb site code pull [--site <id>] [--dir <path>] [--force]
54
69
  mirror a site's Code Dock files into ./code
55
- sb code push [--site <id>] [--dir <path>] [--force] [--dry-run] [--delete]
70
+ sb site code push [--site <id>] [--dir <path>] [--force] [--dry-run] [--delete]
56
71
  send local edits back; refuses a file changed
57
72
  in the Code Dock since your pull unless --force
58
- sb new "<what to build>" make a site from one sentence: opens the editor
59
- and the assistant starts building, on this
60
- machine's Claude Code login when it can. Signs
61
- you in first if needed.
62
- sb export next <site-url> [--dir <path>]
63
- turn a published site into a Next.js repo: each
64
- page as published, cart/checkout served by the
65
- live site. Writes into ./<host> by default.
73
+ sb site mcp the Store Builder MCP server, with this repo's key
74
+ from .env — what the repo's .mcp.json starts
75
+
76
+ Apps (for developers building on the platform)
77
+ sb app init [name] [--port 3000] [--with-block]
78
+ scaffold an app that runs, registers, and opens
79
+ inside a merchant's admin. --with-block adds a
80
+ block and its island a merchant can drag onto a page.
81
+ sb app create "<name>" [--site <id>] [--org <id>] [--yes]
82
+ create the app in your organization, a draft version
83
+ pointing at localhost, and a sandbox install on one
84
+ of your stores; writes .env and sb.json
85
+ sb app dev upload an island's code to your DRAFT version
86
+ every time you save it (not hot reload — you
87
+ refresh). Reads sb.json; needs sb login or SB_TOKEN.
88
+ sb app deploy [--submit] push the version's payload in dependency order.
89
+ Not one write: if it stops it says where, and
90
+ running it again is safe. --submit then sends
91
+ it for review.
66
92
 
67
- AI assistant
93
+ AI
68
94
  sb agent [--codex] run the editor's AI assistant on THIS machine's
69
95
  Claude Code login — no API key (--codex also
70
96
  lets Codex run, which can READ your files). Pick
@@ -75,26 +101,6 @@ AI assistant
75
101
  at login, restarts if it stops (launchd / systemd).
76
102
  Needs a global install (npm i -g @sbuilder/cli).
77
103
  sb agent uninstall | status remove it, or say whether it is running
78
- sb mcp the Store Builder MCP server, with this repo's key
79
- from .env — what the repo's .mcp.json starts
80
-
81
- Apps (for developers building on the platform)
82
- sb init [name] [--port 3000] scaffold an app that runs, registers, and opens
83
- inside a merchant's admin
84
- sb dev upload an island's code to your DRAFT version
85
- every time you save it (not hot reload — you
86
- refresh). Reads sb.json; needs sb login or SB_TOKEN.
87
- sb deploy [--submit] push the version's payload in dependency order.
88
- Not one write: if it stops it says where, and
89
- running it again is safe. --submit then sends
90
- it for review.
91
-
92
- Account
93
- sb login sign in through the browser: opens <editor>/device,
94
- where you type the code it prints; stores a
95
- credential that renews itself
96
- sb whoami which account (and platform) this CLI acts as
97
- sb logout sign this machine out and forget the credential
98
104
 
99
105
  Docs: /cli-docs (this tool) · /app-docs (building an app) · /block-docs (contributing
100
106
  to the editor)`;
@@ -132,6 +138,18 @@ function parse(argv) {
132
138
  else if (a === '--all') {
133
139
  args.all = true;
134
140
  }
141
+ else if (a === '--editor') {
142
+ args.editor = true;
143
+ }
144
+ else if (a === '--with-block') {
145
+ args.withBlock = true;
146
+ }
147
+ else if (a === '--yes') {
148
+ args.yes = true;
149
+ }
150
+ else if (a === '--org') {
151
+ args.org = argv[++i];
152
+ }
135
153
  else if (a === '-h' || a === '--help') {
136
154
  args.help = true;
137
155
  }
@@ -161,18 +179,22 @@ async function ask(question) {
161
179
  rl.close();
162
180
  }
163
181
  }
164
- async function pickSite(sites) {
182
+ async function pickFrom(what, items, flag) {
165
183
  if (!process.stdin.isTTY) {
166
- throw new DevError('Which site? Pass --site <id>:\n' + sites.map((s) => ` ${s.id} ${s.name}`).join('\n'));
184
+ throw new DevError(`Which ${what}? Pass ${flag} <id>:\n` + items.map((s) => ` ${s.id} ${s.name}`).join('\n'));
167
185
  }
168
- console.log('Your sites:');
169
- sites.forEach((s, i) => console.log(` ${i + 1}) ${s.name}${s.publicUrl ? ` ${s.publicUrl}` : ''}`));
186
+ console.log(`Your ${what}s:`);
187
+ items.forEach((s, i) => {
188
+ const url = s.publicUrl;
189
+ console.log(` ${i + 1}) ${s.name}${url ? ` ${url}` : ''}`);
190
+ });
170
191
  for (;;) {
171
- const n = Number(await ask(`Choose 1-${sites.length}: `));
172
- if (Number.isInteger(n) && n >= 1 && n <= sites.length)
173
- return sites[n - 1];
192
+ const n = Number(await ask(`Choose 1-${items.length}: `));
193
+ if (Number.isInteger(n) && n >= 1 && n <= items.length)
194
+ return items[n - 1];
174
195
  }
175
196
  }
197
+ const pickSite = (sites) => pickFrom('site', sites, '--site');
176
198
  /** A folder name from a site name: lower case, no diacritics, dashes. */
177
199
  function slug(name) {
178
200
  return (name
@@ -229,368 +251,399 @@ async function startSiteRepo(o) {
229
251
  console.log(' (Cursor / VS Code work too — the Store Builder tools are set up in the folder.)');
230
252
  return res.code;
231
253
  }
232
- async function main(argv) {
233
- const args = parse(argv);
234
- const cmd = args._[0];
235
- if (args.help || !cmd) {
236
- console.log(USAGE);
237
- return 0;
254
+ /** A site name from its description: the first words, cut at a word boundary. */
255
+ function siteName(description) {
256
+ const words = description.trim().replace(/\s+/g, ' ');
257
+ if (words.length <= 40)
258
+ return words;
259
+ const cut = words.slice(0, 40);
260
+ return cut.slice(0, Math.max(cut.lastIndexOf(' '), 1)).replace(/[\s,.;:-]+$/, '');
261
+ }
262
+ /**
263
+ * `sb site new "<description>"` and menu choice 1: create the site and its repo,
264
+ * then offer Claude Code with the description.
265
+ */
266
+ function siteNew(o) {
267
+ const name = o.name || siteName(o.description);
268
+ return startSiteRepo({
269
+ dir: o.dir ?? slug(name),
270
+ create: name,
271
+ github: o.github,
272
+ description: o.description,
273
+ });
274
+ }
275
+ /** `sb site new --editor` (the old `sb new`): the editor opens and the assistant builds. */
276
+ async function siteNewEditor(prompt) {
277
+ const api = apiBase();
278
+ if (!prompt.trim()) {
279
+ console.error('Say what to build: sb site new --editor "a shop selling handmade candles"');
280
+ return 1;
238
281
  }
239
- if (cmd === 'dev') {
240
- try {
241
- const cfg = await readConfig();
242
- const api = apiBase();
243
- const token = await credential(api);
244
- if (!token) {
245
- console.error(NOT_SIGNED_IN);
246
- return 1;
247
- }
248
- const w = watchAndUpload({ ...cfg, api, token });
249
- console.log(`watching ${cfg.entry} — save it and this uploads to version ${cfg.versionId}.`);
250
- console.log('This is not hot reload: after each upload, refresh the page.');
251
- await w.send(); // upload once now rather than waiting for the first save
252
- // Runs until interrupted. No resolve: the watcher IS the program.
253
- await new Promise(() => { });
254
- return 0;
255
- }
256
- catch (err) {
257
- if (err instanceof DevError) {
258
- console.error(err.message);
259
- return 1;
260
- }
261
- throw err;
262
- }
282
+ if (!(await credential(api)))
283
+ await login({ api });
284
+ const token = await credential(api);
285
+ if (!token) {
286
+ console.error(NOT_SIGNED_IN);
287
+ return 1;
263
288
  }
264
- if (cmd === 'deploy') {
265
- try {
266
- const cfg = await readConfig();
267
- const api = apiBase();
268
- const token = await credential(api);
269
- if (!token) {
270
- console.error(NOT_SIGNED_IN);
271
- return 1;
272
- }
273
- console.log(`deploying to version ${cfg.versionId}:`);
274
- await deploy({ api, token, cfg, log: (l) => console.log(l) });
275
- console.log('done.');
276
- if (args.submit) {
277
- await submit({ api, token, cfg });
278
- console.log('submitted for review.');
279
- }
280
- return 0;
281
- }
282
- catch (err) {
283
- if (err instanceof DeployStopped || err instanceof DevError) {
284
- console.error(err.message);
285
- return 1;
286
- }
287
- throw err;
288
- }
289
+ // After login, whose wait a Ctrl-C has to be able to end.
290
+ const stop = new AbortController();
291
+ process.once('SIGINT', () => stop.abort());
292
+ await newSite({ api, token, prompt, log: (l) => console.log(l), signal: stop.signal });
293
+ return 0;
294
+ }
295
+ /** `sb app create` and the menu's offer after the scaffold: sign in if needed, then create. */
296
+ async function appCreate(o) {
297
+ // Before sign-in: a missing name should not cost a browser round trip.
298
+ if (!o.name.trim()) {
299
+ console.error('Name the app: sb app create "My app"');
300
+ return 1;
289
301
  }
290
- if (cmd === 'code') {
291
- const sub = args._[1];
292
- if (sub !== 'pull' && sub !== 'push') {
293
- console.error('usage: sb code pull|push [--site <id>] [--dir <path>] [--force] [--dry-run] [--delete]');
294
- return 1;
295
- }
296
- // A committed `code` link would re-root the sync; typing --dir is the deliberate act.
297
- // lstat checks only the final component, and an absent ./code (a first pull) is not a link.
298
- if (args.dir === undefined &&
299
- (await lstat(resolve('code')).catch(() => undefined))?.isSymbolicLink()) {
300
- console.error(ROOT_LINKED);
301
- return 1;
302
- }
303
- // Inside a site repo its .env (the repo's own key) fills what the shell leaves unset.
304
- const env = siteEnv();
305
- const api = env.SB_API || apiBase();
306
- try {
307
- return await (sub === 'pull' ? pull : push)({
308
- api,
309
- token: env.SB_TOKEN || (await credential(api)),
310
- dir: resolve(args.dir ?? 'code'),
311
- site: args.site,
312
- force: args.force,
313
- dryRun: args.dryRun,
314
- delete: args.delete,
315
- log: (l) => console.log(l),
316
- warn: (l) => console.error(l),
317
- });
318
- }
319
- catch (err) {
320
- if (err instanceof DevError) {
321
- console.error(err.message);
322
- return 1;
323
- }
324
- throw err;
325
- }
302
+ const api = apiBase();
303
+ let token = await credential(api);
304
+ if (!token) {
305
+ await login({ api });
306
+ token = await credential(api);
326
307
  }
327
- if (cmd === 'mcp') {
328
- return mcp(args.dir);
308
+ if (!token) {
309
+ console.error(NOT_SIGNED_IN);
310
+ return 1;
329
311
  }
330
- if (cmd === 'site') {
331
- const sub = args._[1];
332
- if (sub !== 'pull' &&
333
- sub !== 'push' &&
334
- sub !== 'init' &&
335
- sub !== 'publish' &&
336
- sub !== 'next' &&
337
- sub !== 'blocks') {
338
- console.error('usage: sb site init|pull|push|publish|next|blocks [--site <id>] [--dir <path>] [--force] [--dry-run] [--all]');
339
- return 1;
340
- }
341
- try {
342
- if (sub === 'init') {
343
- return await startSiteRepo({
344
- dir: args.dir ?? args._[2] ?? 'my-site',
345
- site: args.site,
346
- github: args.github,
347
- });
348
- }
349
- if (sub === 'next') {
350
- const minor = VERSION.split('.').slice(0, 2).join('.');
351
- await initNext({
352
- dir: resolve(args.dir ?? '.'),
353
- cliRange: `^${minor}.0`,
354
- renderRange: '^0.1.0',
355
- });
356
- return 0;
357
- }
358
- // Inside a site repo its .env (the repo's own key) fills what the shell leaves unset.
359
- const dir = resolve(args.dir ?? '.');
360
- const env = siteEnv(dir);
361
- const api = env.SB_API || apiBase();
362
- const opts = {
363
- api,
364
- token: env.SB_TOKEN || (await credential(api)),
365
- dir,
366
- site: args.site,
367
- force: args.force,
368
- dryRun: args.dryRun,
369
- log: (l) => console.log(l),
370
- warn: (l) => console.error(l),
371
- };
372
- if (sub === 'blocks')
373
- return await siteBlocks(opts);
374
- if (sub === 'publish')
375
- return await sitePublish({ ...opts, files: args._.slice(2), all: args.all });
376
- return await (sub === 'pull' ? sitePull : sitePush)(opts);
377
- }
378
- catch (err) {
379
- if (err instanceof DevError) {
380
- console.error(err.message);
381
- return 1;
312
+ const tty = !!process.stdin.isTTY;
313
+ const r = await createApp({
314
+ api,
315
+ token,
316
+ name: o.name,
317
+ dir: resolve(o.dir),
318
+ port: o.port,
319
+ site: o.site,
320
+ org: o.org,
321
+ yes: o.yes,
322
+ confirm: tty
323
+ ? async () => {
324
+ return /^y/i.test(await ask('Create the app and install it with these? [y/N]: '));
382
325
  }
383
- throw err;
384
- }
326
+ : undefined,
327
+ pickOrg: tty ? (orgs) => pickFrom('organization', orgs, '--org') : undefined,
328
+ pickSite: tty ? (sites) => pickFrom('store', sites, '--site') : undefined,
329
+ log: (l) => console.log(l),
330
+ });
331
+ for (const l of createdSteps(r))
332
+ console.log(l);
333
+ return 0;
334
+ }
335
+ async function appInit(o) {
336
+ if (!Number.isFinite(o.port) || o.port <= 0) {
337
+ console.error('--port must be a number');
338
+ return 1;
339
+ }
340
+ try {
341
+ const res = await init({ name: o.name, port: o.port, withBlock: o.withBlock });
342
+ console.log(nextSteps({ name: res.name, port: o.port, withBlock: o.withBlock }));
343
+ return 0;
385
344
  }
386
- if (cmd === 'export') {
387
- const url = args._[2];
388
- if (args._[1] !== 'next' || !url) {
389
- console.error('Usage: sb export next <site-url> [--dir <path>]');
345
+ catch (err) {
346
+ // An InitError is a refusal the developer can act on — print it plainly.
347
+ // Anything else is a bug in this tool and gets its stack, because a
348
+ // scaffolder that swallows its own failures is one nobody can report.
349
+ if (err instanceof InitError) {
350
+ console.error(err.message);
390
351
  return 1;
391
352
  }
392
- try {
393
- const dir = resolve(args.dir ?? (URL.canParse(url) ? new URL(url).hostname : 'site'));
394
- console.log(`Exporting ${url} into ${dir}`);
395
- const r = await exportNext(url, dir);
396
- for (const s of r.skipped)
397
- console.error(` skipped ${s.path}: ${s.reason}`);
398
- console.log(`${r.written.length} page(s) written. Next: cd ${dir} && npm install && npm run dev`);
399
- return 0;
400
- }
401
- catch (err) {
402
- if (err instanceof ExportError || err instanceof TypeError) {
403
- console.error(err instanceof TypeError
404
- ? `could not reach ${url}: ${err.cause?.code ?? err.message}`
405
- : err.message);
406
- return 1;
407
- }
408
- throw err;
409
- }
353
+ throw err;
410
354
  }
411
- if (cmd === 'new') {
412
- const api = apiBase();
413
- try {
414
- const prompt = args._.slice(1).join(' ');
415
- if (!prompt.trim()) {
416
- console.error('Say what to build: sb new "a shop selling handmade candles"');
417
- return 1;
418
- }
419
- if (!(await credential(api)))
420
- await login({ api });
421
- const token = await credential(api);
422
- if (!token) {
423
- console.error(NOT_SIGNED_IN);
424
- return 1;
425
- }
426
- // After login, whose wait a Ctrl-C has to be able to end.
427
- const stop = new AbortController();
428
- process.once('SIGINT', () => stop.abort());
429
- await newSite({ api, token, prompt, log: (l) => console.log(l), signal: stop.signal });
430
- return 0;
431
- }
432
- catch (err) {
433
- if (err instanceof DevError) {
434
- console.error(err.message);
435
- return 1;
436
- }
437
- throw err;
438
- }
355
+ }
356
+ /** The menu: `sb init` with no arguments on a terminal. */
357
+ async function menu(args) {
358
+ const choice = await ask('What do you want to start?\n' +
359
+ ' 1) A new website, built by AI — describe it, an AI agent builds it\n' +
360
+ ' 2) A repo for one of your sites — edit it with AI, synced with GitHub\n' +
361
+ " 3) An app — runs inside a merchant's admin\n" +
362
+ 'Choose 1-3 [1]: ');
363
+ if (choice === '' || choice === '1') {
364
+ let description = '';
365
+ while (!description)
366
+ description = await ask('Describe the website (any language): ');
367
+ const name = (await ask('Site name [My shop]: ')) || 'My shop';
368
+ const dir = (await ask(`Folder [${slug(name)}]: `)) || slug(name);
369
+ const github = /^y/i.test(await ask('Also create a private GitHub repo with gh? [y/N]: '));
370
+ return siteNew({ description, name, dir, github });
439
371
  }
440
- if (cmd === 'agent') {
441
- const api = apiBase();
442
- const sub = args._[1];
443
- if (sub === 'install' || sub === 'uninstall' || sub === 'status') {
444
- try {
445
- // A service cannot answer a browser sign-in: it must start signed in.
446
- if (sub === 'install' && !(await credential(api))) {
447
- console.error(NOT_SIGNED_IN);
448
- return 1;
449
- }
450
- const plan = servicePlan({
451
- platform: process.platform,
452
- home: homedir(),
453
- uid: userInfo().uid,
454
- node: process.execPath,
455
- script: realpathSync(process.argv[1]),
456
- codex: args.codex === true,
457
- env: { PATH: process.env.PATH, SB_API: process.env.SB_API },
458
- });
459
- const say = sub === 'install' ? install : sub === 'uninstall' ? uninstall : status;
460
- for (const l of say(plan))
461
- console.log(l);
462
- return 0;
463
- }
464
- catch (err) {
465
- if (err instanceof DevError) {
466
- console.error(err.message);
467
- return 1;
468
- }
469
- throw err;
470
- }
471
- }
472
- if (sub !== undefined) {
473
- console.error(`unknown: sb agent ${sub} (install, uninstall or status)`);
474
- return 1;
475
- }
476
- const token = await credential(api);
477
- if (!token) {
478
- console.error(NOT_SIGNED_IN);
479
- return 1;
480
- }
481
- console.log('sb agent: Claude Code runs here with its tools off.');
482
- if (args.codex) {
483
- console.log('--codex: Codex may run too. It can READ files on this machine through read-only');
484
- console.log('shell commands, steered by page content other editors of the site wrote.');
485
- }
486
- else {
487
- console.log('Codex jobs are refused (a co-editor could pick Codex for a site); add --codex to allow.');
488
- }
489
- const stop = new AbortController();
490
- process.once('SIGINT', () => stop.abort());
491
- try {
492
- await agent({
493
- api,
494
- token,
495
- log: (l) => console.log(l),
496
- signal: stop.signal,
497
- allowCodex: args.codex === true,
498
- });
499
- return 0;
500
- }
501
- catch (err) {
502
- if (err instanceof DevError) {
503
- console.error(err.message);
504
- return 1;
505
- }
506
- throw err;
507
- }
372
+ if (choice === '2') {
373
+ const dir = (await ask('Folder [my-site]: ')) || 'my-site';
374
+ const github = /^y/i.test(await ask('Also create a private GitHub repo with gh? [y/N]: '));
375
+ return startSiteRepo({ dir, github });
508
376
  }
509
- if (cmd === 'whoami') {
510
- const api = apiBase();
511
- const cred = await credential(api);
512
- const where = new URL(api).origin;
513
- if (!cred) {
514
- console.log(`Not signed in to ${where}. Run sb login.`);
377
+ const name = (await ask('App name [my-app]: ')) || 'my-app';
378
+ const withBlock = /^y/i.test(await ask('Include an example block and island? [y/N]: '));
379
+ const code = await appInit({ name, port: args.port, withBlock });
380
+ if (code !== 0)
381
+ return code;
382
+ const create = await ask('Create the app on the platform now (a draft version and a sandbox install on one of your stores)? [Y/n]: ');
383
+ if (/^n/i.test(create))
384
+ return 0;
385
+ return appCreate({ name, dir: normalizeName(name), port: args.port });
386
+ }
387
+ async function appDev() {
388
+ const cfg = await readConfig();
389
+ const api = apiBase();
390
+ const token = await credential(api);
391
+ if (!token) {
392
+ console.error(NOT_SIGNED_IN);
393
+ return 1;
394
+ }
395
+ const w = watchAndUpload({ ...cfg, api, token });
396
+ console.log(`watching ${cfg.entry} — save it and this uploads to version ${cfg.versionId}.`);
397
+ console.log('This is not hot reload: after each upload, refresh the page.');
398
+ await w.send(); // upload once now rather than waiting for the first save
399
+ // Runs until interrupted. No resolve: the watcher IS the program.
400
+ await new Promise(() => { });
401
+ return 0;
402
+ }
403
+ async function appDeploy(args) {
404
+ const cfg = await readConfig();
405
+ const api = apiBase();
406
+ const token = await credential(api);
407
+ if (!token) {
408
+ console.error(NOT_SIGNED_IN);
409
+ return 1;
410
+ }
411
+ console.log(`deploying to version ${cfg.versionId}:`);
412
+ await deploy({ api, token, cfg, log: (l) => console.log(l) });
413
+ console.log('done.');
414
+ if (args.submit) {
415
+ await submit({ api, token, cfg });
416
+ console.log('submitted for review.');
417
+ }
418
+ return 0;
419
+ }
420
+ /** `sb app …` */
421
+ async function appCommand(args) {
422
+ const sub = args._[1];
423
+ if (sub === 'init') {
424
+ return appInit({ name: args._[2], port: args.port, withBlock: args.withBlock });
425
+ }
426
+ if (sub === 'create') {
427
+ return appCreate({
428
+ name: args._.slice(2).join(' '),
429
+ dir: args.dir ?? '.',
430
+ port: args.port,
431
+ site: args.site,
432
+ org: args.org,
433
+ yes: args.yes,
434
+ });
435
+ }
436
+ if (sub === 'dev')
437
+ return appDev();
438
+ if (sub === 'deploy')
439
+ return appDeploy(args);
440
+ console.error(`usage: sb app ${SUBCOMMANDS.app.join('|')}`);
441
+ return 1;
442
+ }
443
+ /** `sb site code pull|push` (the old `sb code`). */
444
+ async function siteCode(args) {
445
+ const sub = args._[2];
446
+ if (!sub || !SUBCOMMANDS['site code'].includes(sub)) {
447
+ console.error('usage: sb site code pull|push [--site <id>] [--dir <path>] [--force] [--dry-run] [--delete]');
448
+ return 1;
449
+ }
450
+ // A committed `code` link would re-root the sync; typing --dir is the deliberate act.
451
+ // lstat checks only the final component, and an absent ./code (a first pull) is not a link.
452
+ if (args.dir === undefined &&
453
+ (await lstat(resolve('code')).catch(() => undefined))?.isSymbolicLink()) {
454
+ console.error(ROOT_LINKED);
455
+ return 1;
456
+ }
457
+ // Inside a site repo its .env (the repo's own key) fills what the shell leaves unset.
458
+ const env = siteEnv();
459
+ const api = env.SB_API || apiBase();
460
+ return (sub === 'pull' ? pull : push)({
461
+ api,
462
+ token: env.SB_TOKEN || (await credential(api)),
463
+ dir: resolve(args.dir ?? 'code'),
464
+ site: args.site,
465
+ force: args.force,
466
+ dryRun: args.dryRun,
467
+ delete: args.delete,
468
+ log: (l) => console.log(l),
469
+ warn: (l) => console.error(l),
470
+ });
471
+ }
472
+ /** `sb site …` */
473
+ async function siteCommand(args) {
474
+ const sub = args._[1];
475
+ if (sub === 'new') {
476
+ const description = args._.slice(2).join(' ').trim();
477
+ if (args.editor)
478
+ return siteNewEditor(description);
479
+ if (!description) {
480
+ console.error('Say what to build: sb site new "a shop selling handmade candles"');
515
481
  return 1;
516
482
  }
517
- if (typeof cred === 'string' && /^(wbk|sbdk)_/.test(cred)) {
518
- console.log(`Using the ${cred.startsWith('wbk_') ? 'API key' : 'deploy key'} in SB_TOKEN, on ${where}.`);
519
- return 0;
520
- }
521
- const email = await whoIs(api, cred);
522
- if (!email) {
523
- console.log(`Signed in to ${where}, but the server would not say as whom — run sb login again.`);
483
+ return siteNew({ description, dir: args.dir, github: args.github });
484
+ }
485
+ if (sub === 'code')
486
+ return siteCode(args);
487
+ if (sub === 'mcp')
488
+ return mcp(args.dir);
489
+ if (!sub || !SUBCOMMANDS.site.includes(sub)) {
490
+ console.error('usage: sb site new|init|pull|push|publish|next|blocks|code|mcp [--site <id>] [--dir <path>] [--force] [--dry-run] [--all]');
491
+ return 1;
492
+ }
493
+ if (sub === 'init') {
494
+ return startSiteRepo({
495
+ dir: args.dir ?? args._[2] ?? 'my-site',
496
+ site: args.site,
497
+ github: args.github,
498
+ });
499
+ }
500
+ if (sub === 'next') {
501
+ const minor = VERSION.split('.').slice(0, 2).join('.');
502
+ await initNext({
503
+ dir: resolve(args.dir ?? '.'),
504
+ cliRange: `^${minor}.0`,
505
+ renderRange: '^0.1.0',
506
+ });
507
+ return 0;
508
+ }
509
+ // Inside a site repo its .env (the repo's own key) fills what the shell leaves unset.
510
+ const dir = resolve(args.dir ?? '.');
511
+ const env = siteEnv(dir);
512
+ const api = env.SB_API || apiBase();
513
+ const opts = {
514
+ api,
515
+ token: env.SB_TOKEN || (await credential(api)),
516
+ dir,
517
+ site: args.site,
518
+ force: args.force,
519
+ dryRun: args.dryRun,
520
+ log: (l) => console.log(l),
521
+ warn: (l) => console.error(l),
522
+ };
523
+ if (sub === 'blocks')
524
+ return siteBlocks(opts);
525
+ if (sub === 'publish')
526
+ return sitePublish({ ...opts, files: args._.slice(2), all: args.all });
527
+ return (sub === 'pull' ? sitePull : sitePush)(opts);
528
+ }
529
+ /** `sb agent …` */
530
+ async function agentCommand(args) {
531
+ const api = apiBase();
532
+ const sub = args._[1];
533
+ if (sub && SUBCOMMANDS.agent.includes(sub)) {
534
+ // A service cannot answer a browser sign-in: it must start signed in.
535
+ if (sub === 'install' && !(await credential(api))) {
536
+ console.error(NOT_SIGNED_IN);
524
537
  return 1;
525
538
  }
526
- console.log(`${email} on ${where}`);
539
+ const plan = servicePlan({
540
+ platform: process.platform,
541
+ home: homedir(),
542
+ uid: userInfo().uid,
543
+ node: process.execPath,
544
+ script: realpathSync(process.argv[1]),
545
+ codex: args.codex === true,
546
+ env: { PATH: process.env.PATH, SB_API: process.env.SB_API },
547
+ });
548
+ const say = sub === 'install' ? install : sub === 'uninstall' ? uninstall : status;
549
+ for (const l of say(plan))
550
+ console.log(l);
527
551
  return 0;
528
552
  }
529
- if (cmd === 'login' || cmd === 'logout') {
530
- const api = apiBase();
531
- try {
532
- await (cmd === 'login' ? login({ api }) : logout({ api }));
533
- return 0;
534
- }
535
- catch (err) {
536
- if (err instanceof DevError) {
537
- console.error(err.message);
538
- return 1;
539
- }
540
- throw err;
541
- }
553
+ if (sub !== undefined) {
554
+ console.error(`unknown: sb agent ${sub} (${SUBCOMMANDS.agent.join(', ')})`);
555
+ return 1;
542
556
  }
543
- if (cmd !== 'init') {
544
- console.error(`unknown command: ${cmd}\n`);
545
- console.error(USAGE);
557
+ const token = await credential(api);
558
+ if (!token) {
559
+ console.error(NOT_SIGNED_IN);
546
560
  return 1;
547
561
  }
548
- if (!Number.isFinite(args.port) || args.port <= 0) {
549
- console.error('--port must be a number');
562
+ console.log('sb agent: Claude Code runs here with its tools off.');
563
+ if (args.codex) {
564
+ console.log('--codex: Codex may run too. It can READ files on this machine through read-only');
565
+ console.log('shell commands, steered by page content other editors of the site wrote.');
566
+ }
567
+ else {
568
+ console.log('Codex jobs are refused (a co-editor could pick Codex for a site); add --codex to allow.');
569
+ }
570
+ const stop = new AbortController();
571
+ process.once('SIGINT', () => stop.abort());
572
+ await agent({
573
+ api,
574
+ token,
575
+ log: (l) => console.log(l),
576
+ signal: stop.signal,
577
+ allowCodex: args.codex === true,
578
+ });
579
+ return 0;
580
+ }
581
+ async function whoami() {
582
+ const api = apiBase();
583
+ const cred = await credential(api);
584
+ const where = new URL(api).origin;
585
+ if (!cred) {
586
+ console.log(`Not signed in to ${where}. Run sb login.`);
550
587
  return 1;
551
588
  }
552
- if (args._.length === 1 && process.stdin.isTTY && process.stdout.isTTY) {
553
- const choice = await ask('What do you want to start?\n' +
554
- ' 1) A new website, built by AI — describe it, an AI agent builds it\n' +
555
- ' 2) A repo for one of your sites — edit it with AI, synced with GitHub\n' +
556
- " 3) An app — runs inside a merchant's admin\n" +
557
- 'Choose 1-3 [1]: ');
558
- try {
559
- if (choice === '' || choice === '1') {
560
- let description = '';
561
- while (!description)
562
- description = await ask('Describe the website (any language): ');
563
- const name = (await ask('Site name [My shop]: ')) || 'My shop';
564
- const dir = (await ask(`Folder [${slug(name)}]: `)) || slug(name);
565
- const github = /^y/i.test(await ask('Also create a private GitHub repo with gh? [y/N]: '));
566
- return await startSiteRepo({ dir, create: name, github, description });
567
- }
568
- if (choice === '2') {
569
- const dir = (await ask('Folder [my-site]: ')) || 'my-site';
570
- const github = /^y/i.test(await ask('Also create a private GitHub repo with gh? [y/N]: '));
571
- return await startSiteRepo({ dir, github });
589
+ if (typeof cred === 'string' && /^(wbk|sbdk)_/.test(cred)) {
590
+ console.log(`Using the ${cred.startsWith('wbk_') ? 'API key' : 'deploy key'} in SB_TOKEN, on ${where}.`);
591
+ return 0;
592
+ }
593
+ const email = await whoIs(api, cred);
594
+ if (!email) {
595
+ console.log(`Signed in to ${where}, but the server would not say as whom — run sb login again.`);
596
+ return 1;
597
+ }
598
+ console.log(`${email} on ${where}`);
599
+ return 0;
600
+ }
601
+ /**
602
+ * Dispatch. Old names are rewritten first (route.ts) and their one-line note goes
603
+ * to STDERR — stdout is untouched, because `sb mcp` is an MCP stream.
604
+ */
605
+ async function main(rawArgv) {
606
+ const { argv, note } = route(rawArgv);
607
+ if (note)
608
+ console.error(note);
609
+ const args = parse(argv);
610
+ const cmd = args._[0];
611
+ if (args.help || !cmd) {
612
+ console.log(USAGE);
613
+ return 0;
614
+ }
615
+ try {
616
+ switch (cmd) {
617
+ case 'site':
618
+ return await siteCommand(args);
619
+ case 'app':
620
+ return await appCommand(args);
621
+ case 'agent':
622
+ return await agentCommand(args);
623
+ case 'whoami':
624
+ return await whoami();
625
+ case 'login':
626
+ case 'logout': {
627
+ const api = apiBase();
628
+ await (cmd === 'login' ? login({ api }) : logout({ api }));
629
+ return 0;
572
630
  }
573
- }
574
- catch (err) {
575
- if (err instanceof DevError) {
576
- console.error(err.message);
631
+ case 'export':
632
+ console.error("`sb export next` was removed in 0.9 — use `sb site next` (a Next.js app rendered by the platform's own renderer).");
633
+ return 1;
634
+ case 'init':
635
+ if (args._.length === 1 && process.stdin.isTTY && process.stdout.isTTY)
636
+ return await menu(args);
637
+ // A bare `sb init` off a terminal is what it always was: the app scaffold, `my-app`.
638
+ return await appInit({ port: args.port, withBlock: args.withBlock });
639
+ default:
640
+ console.error(`unknown command: ${cmd}\n`);
641
+ console.error(USAGE);
577
642
  return 1;
578
- }
579
- throw err;
580
643
  }
581
- const name = (await ask('App name [my-app]: ')) || 'my-app';
582
- args._.push(name);
583
- }
584
- try {
585
- const res = await init({ name: args._[1], port: args.port });
586
- console.log(nextSteps({ name: res.name, port: args.port }));
587
- return 0;
588
644
  }
589
645
  catch (err) {
590
- // An InitError is a refusal the developer can act on — print it plainly.
591
- // Anything else is a bug in this tool and gets its stack, because a
592
- // scaffolder that swallows its own failures is one nobody can report.
593
- if (err instanceof InitError) {
646
+ if (err instanceof DevError || err instanceof DeployStopped) {
594
647
  console.error(err.message);
595
648
  return 1;
596
649
  }