@sbuilder/cli 0.7.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.
Files changed (42) hide show
  1. package/README.md +374 -145
  2. package/README.vi.md +361 -137
  3. package/dist/bin/sb.js +535 -219
  4. package/dist/bin/sb.js.map +1 -1
  5. package/dist/src/appblocks.js +67 -0
  6. package/dist/src/appblocks.js.map +1 -0
  7. package/dist/src/appcreate.js +279 -0
  8. package/dist/src/appcreate.js.map +1 -0
  9. package/dist/src/auth.js +1 -1
  10. package/dist/src/code.js +10 -10
  11. package/dist/src/code.js.map +1 -1
  12. package/dist/src/deploy.js +3 -3
  13. package/dist/src/deploy.js.map +1 -1
  14. package/dist/src/dev.js +9 -5
  15. package/dist/src/dev.js.map +1 -1
  16. package/dist/src/export.js +167 -0
  17. package/dist/src/export.js.map +1 -0
  18. package/dist/src/host.js +162 -0
  19. package/dist/src/host.js.map +1 -0
  20. package/dist/src/init.js +41 -13
  21. package/dist/src/init.js.map +1 -1
  22. package/dist/src/login.js +62 -8
  23. package/dist/src/login.js.map +1 -1
  24. package/dist/src/new.js +3 -3
  25. package/dist/src/new.js.map +1 -1
  26. package/dist/src/next.js +122 -0
  27. package/dist/src/next.js.map +1 -0
  28. package/dist/src/repo.js +118 -0
  29. package/dist/src/repo.js.map +1 -0
  30. package/dist/src/route.js +66 -0
  31. package/dist/src/route.js.map +1 -0
  32. package/dist/src/scaffold.js +169 -2
  33. package/dist/src/scaffold.js.map +1 -1
  34. package/dist/src/site.js +448 -0
  35. package/dist/src/site.js.map +1 -0
  36. package/dist/src/siteinit.js +326 -0
  37. package/dist/src/siteinit.js.map +1 -0
  38. package/dist/src/source/parse.js +470 -0
  39. package/dist/src/source/parse.js.map +1 -0
  40. package/dist/src/source/print.js +270 -0
  41. package/dist/src/source/print.js.map +1 -0
  42. package/package.json +6 -2
package/dist/bin/sb.js CHANGED
@@ -10,34 +10,87 @@ 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';
17
- import { login, logout, apiBase } from '../src/login.js';
17
+ import { login, logout, apiBase, whoIs } from '../src/login.js';
18
18
  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
- const USAGE = `sb — build an app for Store Builder
22
+ import { pull as sitePull, push as sitePush, publish as sitePublish, blocks as siteBlocks, } from '../src/site.js';
23
+ import { initSite, nextSteps as siteNextSteps, buildPrompt } from '../src/siteinit.js';
24
+ import { mcp, siteEnv } from '../src/repo.js';
25
+ import { initNext } from '../src/next.js';
26
+ import { route, SUBCOMMANDS } from '../src/route.js';
27
+ import { createApp, createdSteps } from '../src/appcreate.js';
28
+ import { VERSION } from '../src/login.js';
29
+ import { spawnSync } from 'node:child_process';
30
+ import { createInterface } from 'node:readline/promises';
31
+ const USAGE = `sb — the Store Builder command line
23
32
 
24
- sb init [name] [--port 3000] scaffold an app that runs, registers, and opens
25
- inside a merchant's admin
26
- sb login sign in through the browser: prints a code you
27
- type at <editor>/device, then stores a
33
+ Start
34
+ sb init ask what to start: a new website built by AI, a
35
+ repo for one of your sites, or an app (same as
36
+ npm create sbuilder-app)
37
+
38
+ Account
39
+ sb login sign in through the browser: opens <editor>/device,
40
+ where you type the code it prints; stores a
28
41
  credential that renews itself
29
42
  sb logout sign this machine out and forget the credential
30
- sb dev upload an island's code to your DRAFT version
43
+ sb whoami which account (and platform) this CLI acts as
44
+
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.
53
+ sb site init [dir] [--site <id>] [--github]
54
+ a repo holding one site's pages: picks the site,
55
+ pulls it, adds a GitHub workflow that syncs both
56
+ ways. --github also creates the private repo (gh).
57
+ sb site pull [--site <id>] [--force] [--dry-run]
58
+ take pages edited in the editor into design/pages
59
+ sb site push [--force] [--dry-run]
60
+ save edited page files as DRAFTS (never publishes);
61
+ refuses a page edited in the editor since your pull
62
+ sb site publish <file>… | --all
63
+ make pages LIVE — named files, or every page
64
+ sb site blocks the blocks your installed apps let you place, each
65
+ with the line to paste into a page file
66
+ sb site next make the repo a Next.js app serving its pages, rendered
67
+ by the platform's own renderer (npm run dev to preview)
68
+ sb site code pull [--site <id>] [--dir <path>] [--force]
69
+ mirror a site's Code Dock files into ./code
70
+ sb site code push [--site <id>] [--dir <path>] [--force] [--dry-run] [--delete]
71
+ send local edits back; refuses a file changed
72
+ in the Code Dock since your pull unless --force
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
31
86
  every time you save it (not hot reload — you
32
87
  refresh). Reads sb.json; needs sb login or SB_TOKEN.
33
- sb deploy [--submit] push the version's payload in dependency order.
88
+ sb app deploy [--submit] push the version's payload in dependency order.
34
89
  Not one write: if it stops it says where, and
35
90
  running it again is safe. --submit then sends
36
91
  it for review.
37
- sb new "<what to build>" make a site from one sentence: opens the editor
38
- and the assistant starts building, on this
39
- machine's Claude Code login when it can. Signs
40
- you in first if needed.
92
+
93
+ AI
41
94
  sb agent [--codex] run the editor's AI assistant on THIS machine's
42
95
  Claude Code login — no API key (--codex also
43
96
  lets Codex run, which can READ your files). Pick
@@ -48,11 +101,6 @@ const USAGE = `sb — build an app for Store Builder
48
101
  at login, restarts if it stops (launchd / systemd).
49
102
  Needs a global install (npm i -g @sbuilder/cli).
50
103
  sb agent uninstall | status remove it, or say whether it is running
51
- sb code pull [--site <id>] [--dir <path>] [--force]
52
- mirror a site's Code Dock files into ./code
53
- sb code push [--site <id>] [--dir <path>] [--force] [--dry-run] [--delete]
54
- send local edits back; refuses a file changed
55
- in the Code Dock since your pull unless --force
56
104
 
57
105
  Docs: /cli-docs (this tool) · /app-docs (building an app) · /block-docs (contributing
58
106
  to the editor)`;
@@ -84,6 +132,24 @@ function parse(argv) {
84
132
  else if (a === '--codex') {
85
133
  args.codex = true;
86
134
  }
135
+ else if (a === '--github') {
136
+ args.github = true;
137
+ }
138
+ else if (a === '--all') {
139
+ args.all = true;
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
+ }
87
153
  else if (a === '-h' || a === '--help') {
88
154
  args.help = true;
89
155
  }
@@ -104,230 +170,480 @@ async function credential(api) {
104
170
  return token;
105
171
  return (await readPair(api)) ? storedAuth(api) : undefined;
106
172
  }
107
- async function main(argv) {
108
- const args = parse(argv);
109
- const cmd = args._[0];
110
- if (args.help || !cmd) {
111
- console.log(USAGE);
112
- return 0;
173
+ async function ask(question) {
174
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
175
+ try {
176
+ return (await rl.question(question)).trim();
113
177
  }
114
- if (cmd === 'dev') {
115
- try {
116
- const cfg = await readConfig();
117
- const api = apiBase();
118
- const token = await credential(api);
119
- if (!token) {
120
- console.error(NOT_SIGNED_IN);
121
- return 1;
122
- }
123
- const w = watchAndUpload({ ...cfg, api, token });
124
- console.log(`watching ${cfg.entry} — save it and this uploads to version ${cfg.versionId}.`);
125
- console.log('This is not hot reload: after each upload, refresh the page.');
126
- await w.send(); // upload once now rather than waiting for the first save
127
- // Runs until interrupted. No resolve: the watcher IS the program.
128
- await new Promise(() => { });
129
- return 0;
130
- }
131
- catch (err) {
132
- if (err instanceof DevError) {
133
- console.error(err.message);
134
- return 1;
135
- }
136
- throw err;
137
- }
178
+ finally {
179
+ rl.close();
138
180
  }
139
- if (cmd === 'deploy') {
140
- try {
141
- const cfg = await readConfig();
142
- const api = apiBase();
143
- const token = await credential(api);
144
- if (!token) {
145
- console.error(NOT_SIGNED_IN);
146
- return 1;
147
- }
148
- console.log(`deploying to version ${cfg.versionId}:`);
149
- await deploy({ api, token, cfg, log: (l) => console.log(l) });
150
- console.log('done.');
151
- if (args.submit) {
152
- await submit({ api, token, cfg });
153
- console.log('submitted for review.');
154
- }
155
- return 0;
181
+ }
182
+ async function pickFrom(what, items, flag) {
183
+ if (!process.stdin.isTTY) {
184
+ throw new DevError(`Which ${what}? Pass ${flag} <id>:\n` + items.map((s) => ` ${s.id} ${s.name}`).join('\n'));
185
+ }
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
+ });
191
+ for (;;) {
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];
195
+ }
196
+ }
197
+ const pickSite = (sites) => pickFrom('site', sites, '--site');
198
+ /** A folder name from a site name: lower case, no diacritics, dashes. */
199
+ function slug(name) {
200
+ return (name
201
+ .normalize('NFD')
202
+ .replace(/[\u0300-\u036f]/g, '')
203
+ .replace(/đ/gi, 'd')
204
+ .toLowerCase()
205
+ .replace(/[^a-z0-9]+/g, '-')
206
+ .replace(/^-+|-+$/g, '') || 'my-site');
207
+ }
208
+ const hasClaude = () => process.platform !== 'win32' &&
209
+ spawnSync('claude', ['--version'], { stdio: 'ignore' }).status === 0;
210
+ /**
211
+ * `sb site init` and the menu's two site choices: sign in if needed, make the
212
+ * repo, say what to do next — and, when the site was DESCRIBED, hand the
213
+ * description to Claude Code in that folder so building starts right there.
214
+ */
215
+ async function startSiteRepo(o) {
216
+ const api = apiBase();
217
+ let token = await credential(api);
218
+ if (!token) {
219
+ await login({ api });
220
+ token = await credential(api);
221
+ }
222
+ const dir = resolve(o.dir);
223
+ const res = await initSite({
224
+ api,
225
+ token,
226
+ dir,
227
+ site: o.site,
228
+ create: o.create,
229
+ github: o.github,
230
+ pick: pickSite,
231
+ log: (l) => console.log(l),
232
+ warn: (l) => console.error(l),
233
+ });
234
+ const rel = o.dir;
235
+ if (!o.description) {
236
+ for (const l of siteNextSteps(rel, !!o.github))
237
+ console.log(l);
238
+ return res.code;
239
+ }
240
+ const prompt = buildPrompt(o.description);
241
+ if (hasClaude() && process.stdin.isTTY) {
242
+ const go = await ask('\nStart Claude Code in that folder to build it now? [Y/n]: ');
243
+ if (!/^n/i.test(go)) {
244
+ console.log('Approve the "sbuilder" tools when Claude Code asks — they are how it builds the site.\n');
245
+ return spawnSync('claude', [prompt], { cwd: dir, stdio: 'inherit' }).status ?? 0;
156
246
  }
157
- catch (err) {
158
- if (err instanceof DeployStopped || err instanceof DevError) {
159
- console.error(err.message);
160
- return 1;
247
+ }
248
+ console.log('\nTo build it, open the folder in an AI agent and give it this:');
249
+ console.log(` cd ${rel}`);
250
+ console.log(` claude '${prompt.replace(/'/g, `'\\''`)}'`);
251
+ console.log(' (Cursor / VS Code work too — the Store Builder tools are set up in the folder.)');
252
+ return res.code;
253
+ }
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;
281
+ }
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;
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;
301
+ }
302
+ const api = apiBase();
303
+ let token = await credential(api);
304
+ if (!token) {
305
+ await login({ api });
306
+ token = await credential(api);
307
+ }
308
+ if (!token) {
309
+ console.error(NOT_SIGNED_IN);
310
+ return 1;
311
+ }
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]: '));
161
325
  }
162
- throw err;
163
- }
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;
164
339
  }
165
- if (cmd === 'code') {
166
- const sub = args._[1];
167
- if (sub !== 'pull' && sub !== 'push') {
168
- console.error('usage: sb code pull|push [--site <id>] [--dir <path>] [--force] [--dry-run] [--delete]');
169
- return 1;
170
- }
171
- // A committed `code` link would re-root the sync; typing --dir is the deliberate act.
172
- // lstat checks only the final component, and an absent ./code (a first pull) is not a link.
173
- if (args.dir === undefined &&
174
- (await lstat(resolve('code')).catch(() => undefined))?.isSymbolicLink()) {
175
- console.error(ROOT_LINKED);
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;
344
+ }
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);
176
351
  return 1;
177
352
  }
178
- const api = apiBase();
179
- try {
180
- return await (sub === 'pull' ? pull : push)({
181
- api,
182
- token: await credential(api),
183
- dir: resolve(args.dir ?? 'code'),
184
- site: args.site,
185
- force: args.force,
186
- dryRun: args.dryRun,
187
- delete: args.delete,
188
- log: (l) => console.log(l),
189
- warn: (l) => console.error(l),
190
- });
191
- }
192
- catch (err) {
193
- if (err instanceof DevError) {
194
- console.error(err.message);
195
- return 1;
196
- }
197
- throw err;
198
- }
353
+ throw err;
199
354
  }
200
- if (cmd === 'new') {
201
- const api = apiBase();
202
- try {
203
- const prompt = args._.slice(1).join(' ');
204
- if (!prompt.trim()) {
205
- console.error('Say what to build: sb new "a shop selling handmade candles"');
206
- return 1;
207
- }
208
- if (!(await credential(api)))
209
- await login({ api });
210
- const token = await credential(api);
211
- if (!token) {
212
- console.error(NOT_SIGNED_IN);
213
- return 1;
214
- }
215
- // After login, whose wait a Ctrl-C has to be able to end.
216
- const stop = new AbortController();
217
- process.once('SIGINT', () => stop.abort());
218
- await newSite({ api, token, prompt, log: (l) => console.log(l), signal: stop.signal });
219
- return 0;
220
- }
221
- catch (err) {
222
- if (err instanceof DevError) {
223
- console.error(err.message);
224
- return 1;
225
- }
226
- throw err;
227
- }
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 });
228
371
  }
229
- if (cmd === 'agent') {
230
- const api = apiBase();
231
- const sub = args._[1];
232
- if (sub === 'install' || sub === 'uninstall' || sub === 'status') {
233
- try {
234
- // A service cannot answer a browser sign-in: it must start signed in.
235
- if (sub === 'install' && !(await credential(api))) {
236
- console.error(NOT_SIGNED_IN);
237
- return 1;
238
- }
239
- const plan = servicePlan({
240
- platform: process.platform,
241
- home: homedir(),
242
- uid: userInfo().uid,
243
- node: process.execPath,
244
- script: realpathSync(process.argv[1]),
245
- codex: args.codex === true,
246
- env: { PATH: process.env.PATH, SB_API: process.env.SB_API },
247
- });
248
- const say = sub === 'install' ? install : sub === 'uninstall' ? uninstall : status;
249
- for (const l of say(plan))
250
- console.log(l);
251
- return 0;
252
- }
253
- catch (err) {
254
- if (err instanceof DevError) {
255
- console.error(err.message);
256
- return 1;
257
- }
258
- throw err;
259
- }
260
- }
261
- if (sub !== undefined) {
262
- console.error(`unknown: sb agent ${sub} (install, uninstall or status)`);
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 });
376
+ }
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"');
263
481
  return 1;
264
482
  }
265
- const token = await credential(api);
266
- if (!token) {
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))) {
267
536
  console.error(NOT_SIGNED_IN);
268
537
  return 1;
269
538
  }
270
- console.log('sb agent: Claude Code runs here with its tools off.');
271
- if (args.codex) {
272
- console.log('--codex: Codex may run too. It can READ files on this machine through read-only');
273
- console.log('shell commands, steered by page content other editors of the site wrote.');
274
- }
275
- else {
276
- console.log('Codex jobs are refused (a co-editor could pick Codex for a site); add --codex to allow.');
277
- }
278
- const stop = new AbortController();
279
- process.once('SIGINT', () => stop.abort());
280
- try {
281
- await agent({
282
- api,
283
- token,
284
- log: (l) => console.log(l),
285
- signal: stop.signal,
286
- allowCodex: args.codex === true,
287
- });
288
- return 0;
289
- }
290
- catch (err) {
291
- if (err instanceof DevError) {
292
- console.error(err.message);
293
- return 1;
294
- }
295
- throw err;
296
- }
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);
551
+ return 0;
297
552
  }
298
- if (cmd === 'login' || cmd === 'logout') {
299
- const api = apiBase();
300
- try {
301
- await (cmd === 'login' ? login({ api }) : logout({ api }));
302
- return 0;
303
- }
304
- catch (err) {
305
- if (err instanceof DevError) {
306
- console.error(err.message);
307
- return 1;
308
- }
309
- throw err;
310
- }
553
+ if (sub !== undefined) {
554
+ console.error(`unknown: sb agent ${sub} (${SUBCOMMANDS.agent.join(', ')})`);
555
+ return 1;
311
556
  }
312
- if (cmd !== 'init') {
313
- console.error(`unknown command: ${cmd}\n`);
314
- console.error(USAGE);
557
+ const token = await credential(api);
558
+ if (!token) {
559
+ console.error(NOT_SIGNED_IN);
315
560
  return 1;
316
561
  }
317
- if (!Number.isFinite(args.port) || args.port <= 0) {
318
- 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.`);
319
587
  return 1;
320
588
  }
321
- try {
322
- const res = await init({ name: args._[1], port: args.port });
323
- console.log(nextSteps({ name: res.name, port: args.port }));
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);
324
613
  return 0;
325
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;
630
+ }
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);
642
+ return 1;
643
+ }
644
+ }
326
645
  catch (err) {
327
- // An InitError is a refusal the developer can act on — print it plainly.
328
- // Anything else is a bug in this tool and gets its stack, because a
329
- // scaffolder that swallows its own failures is one nobody can report.
330
- if (err instanceof InitError) {
646
+ if (err instanceof DevError || err instanceof DeployStopped) {
331
647
  console.error(err.message);
332
648
  return 1;
333
649
  }