@sbuilder/cli 0.11.0 → 0.13.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.
@@ -0,0 +1,792 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { lstat, mkdir, readdir, readFile, writeFile } from 'node:fs/promises';
3
+ import { createRequire } from 'node:module';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { sbJsonSite } from './code.js';
6
+ import { DevError } from './dev.js';
7
+ import { COMPONENTS_SKILL, COMPONENTS_SKILL_PATH } from './agentdocs.js';
8
+ import { errorOf, linkOn, open, put, putIfStill, recordAgentFiles, refusal, send, sha256, SITE_MANIFEST, } from './site.js';
9
+ import { parseFile, printFile } from './source/meta.js';
10
+ import { parseSource } from './source/parse.js';
11
+ import { derivedWarning } from './source/derived.js';
12
+ /**
13
+ * `sb site components` — code components: React (Preact) components a developer writes in a site
14
+ * repo's `components/` folder, bundled HERE with the repo's own esbuild and uploaded as IMMUTABLE
15
+ * versions (POST /api/v1/code-components). The CLI has no runtime dependency, so esbuild, preact and
16
+ * preact-render-to-string are the SITE REPO's devDependencies (`sb site components init` adds them).
17
+ *
18
+ * # What is built (the bundle contract, server/internal/codecomponents/codecomponents.go)
19
+ *
20
+ * SSR an IIFE that assigns `globalThis.__sbComponent = { render(props) -> string }`, react and
21
+ * react-dom aliased to preact/compat (the C0 spike's exact flags). The platform only ever
22
+ * EXECUTES this one, inside its sandbox: the platform renders every upload once with the
23
+ * schema's defaults before storing it and refuses (422 bundle_rejected) one that throws.
24
+ * The CLI never runs the bundle — it reads the props from the SOURCE (`schemaOf`).
25
+ * client an IIFE with `globalName: '__sbClient'` whose export is `{ hydrate(el, props) }`. It names
26
+ * no component and no version: the platform's serving route wraps the stored bytes and
27
+ * assigns `__sbClient` to `__sbComponentClient["<name>@<version>"]` (what
28
+ * runtime/src/nodes/code-component.ts reads), because only the platform knows the version.
29
+ * Version-agnostic bytes are also what lets identical sources dedupe by sha.
30
+ *
31
+ * The author never writes either contract: the entry stubs below are generated.
32
+ *
33
+ * Both are deterministic for the same source, so "same sha means no new version" holds.
34
+ *
35
+ * # What push does
36
+ *
37
+ * Every component is uploaded BEFORE any page, so a page pin always names a version that exists.
38
+ * The platform answers 201 for a new version and 200 (the existing one) for identical content; the
39
+ * version it assigned is printed. Nothing on any page moves: `sb site components upgrade` is the
40
+ * deliberate, local edit that does.
41
+ */
42
+ /** Pinned exactly (no ranges): the C0 spike measured these, and a bundle's sha depends on them. */
43
+ export const ESBUILD_VERSION = '0.28.2';
44
+ export const PREACT_VERSION = '11.2.0';
45
+ export const RENDER_TO_STRING_VERSION = '6.8.3';
46
+ /**
47
+ * `@sbuilder/sdk/component` landed in 0.2.0. Not imported from starter.ts: that file reaches next.ts,
48
+ * and this one is loaded by host.ts (through site.ts), which must never load next's files.
49
+ */
50
+ export const SDK_RANGE = '^0.2.0';
51
+ export const DEV_DEPENDENCIES = {
52
+ '@sbuilder/sdk': SDK_RANGE,
53
+ esbuild: ESBUILD_VERSION,
54
+ preact: PREACT_VERSION,
55
+ 'preact-render-to-string': RENDER_TO_STRING_VERSION,
56
+ };
57
+ /** The platform's caps (codecomponents.MaxSSRBytes / MaxClientBytes): refused here, by name. */
58
+ export const MAX_SSR_BYTES = 512 << 10;
59
+ export const MAX_CLIENT_BYTES = 256 << 10;
60
+ export const COMPONENTS_DIR = 'components';
61
+ const NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
62
+ export class ComponentRefused extends DevError {
63
+ }
64
+ const HERO = `import { defineProps, type Props } from '@sbuilder/sdk/component';
65
+
66
+ // The props the editor shows for this component. A length or a colour is a \`css\` prop: the
67
+ // page sets it per breakpoint as the custom property --<name>, and the markup reads it with
68
+ // var(--<name>, <default>). Its name must be lowercase kebab-case.
69
+ export const schema = defineProps({
70
+ title: { kind: 'text', default: 'Welcome' },
71
+ subtitle: { kind: 'text', default: 'Made with a code component' },
72
+ cta: { kind: 'link', default: '/' },
73
+ tone: { kind: 'enum', options: ['light', 'dark'], default: 'light' },
74
+ 'gap-size': { kind: 'css', default: '16px' },
75
+ });
76
+
77
+ export default function Hero({ title, subtitle, cta, tone }: Props<typeof schema>) {
78
+ return (
79
+ <section class={\`hero hero-\${tone}\`} style="display: grid; gap: var(--gap-size, 16px)">
80
+ <h1>{title}</h1>
81
+ <p>{subtitle}</p>
82
+ <a href={cta}>Learn more</a>
83
+ </section>
84
+ );
85
+ }
86
+ `;
87
+ const TSCONFIG = `{
88
+ "compilerOptions": {
89
+ "target": "ES2020",
90
+ "module": "ESNext",
91
+ "moduleResolution": "Bundler",
92
+ "lib": ["ES2020", "DOM"],
93
+ "jsx": "react-jsx",
94
+ "jsxImportSource": "preact",
95
+ "strict": true,
96
+ "noEmit": true,
97
+ "skipLibCheck": true,
98
+ "baseUrl": ".",
99
+ "paths": {
100
+ "react": ["../node_modules/preact/compat"],
101
+ "react-dom": ["../node_modules/preact/compat"]
102
+ }
103
+ },
104
+ "include": ["./**/*"]
105
+ }
106
+ `;
107
+ const refuseLink = async (dir, file) => {
108
+ const l = await linkOn(dir, file);
109
+ if (l)
110
+ throw new ComponentRefused(`${l} is a symbolic link — nothing was read or written. Replace it with the real file.`);
111
+ };
112
+ /** `sb site components init`: devDependencies, components/Hero.tsx, components/tsconfig.json. */
113
+ export async function componentsInit(dir, log) {
114
+ const out = { wrote: [], kept: [] };
115
+ for (const f of ['package.json', COMPONENTS_DIR, `${COMPONENTS_DIR}/Hero.tsx`])
116
+ await refuseLink(dir, f);
117
+ const pkgPath = join(dir, 'package.json');
118
+ const text = await readFile(pkgPath, 'utf8').catch(() => undefined);
119
+ let pkg = { name: 'site', private: true };
120
+ if (text !== undefined) {
121
+ try {
122
+ const parsed = JSON.parse(text);
123
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
124
+ throw new Error();
125
+ pkg = parsed;
126
+ }
127
+ catch {
128
+ throw new ComponentRefused('package.json is not a JSON object — fix it, then run sb site components init again.');
129
+ }
130
+ }
131
+ const dev = (typeof pkg.devDependencies === 'object' && pkg.devDependencies !== null
132
+ ? { ...pkg.devDependencies }
133
+ : {});
134
+ const added = [];
135
+ for (const [n, v] of Object.entries(DEV_DEPENDENCIES)) {
136
+ if (dev[n] === undefined) {
137
+ dev[n] = v;
138
+ added.push(`${n}@${v}`);
139
+ }
140
+ else if (dev[n] !== v)
141
+ log(` · ${n} stays at ${dev[n]} (this CLI was measured with ${v}; a different build changes every bundle's sha)`);
142
+ }
143
+ if (added.length) {
144
+ pkg.devDependencies = Object.fromEntries(Object.entries(dev).sort(([a], [b]) => a.localeCompare(b)));
145
+ await put(pkgPath, JSON.stringify(pkg, null, 2) + '\n');
146
+ out.wrote.push('package.json');
147
+ log(` + package.json devDependencies: ${added.join(', ')}`);
148
+ }
149
+ else
150
+ out.kept.push('package.json');
151
+ await mkdir(join(dir, COMPONENTS_DIR), { recursive: true });
152
+ for (const [file, body] of [
153
+ [`${COMPONENTS_DIR}/Hero.tsx`, HERO],
154
+ [`${COMPONENTS_DIR}/tsconfig.json`, TSCONFIG],
155
+ // What an AI agent reads before writing one (agentdocs.ts) — the same file sb site init writes.
156
+ [COMPONENTS_SKILL_PATH, COMPONENTS_SKILL],
157
+ ]) {
158
+ await refuseLink(dir, file);
159
+ await mkdir(dirname(join(dir, file)), { recursive: true });
160
+ try {
161
+ await writeFile(join(dir, file), body, { encoding: 'utf8', flag: 'wx' });
162
+ out.wrote.push(file);
163
+ log(` + ${file}`);
164
+ // Recorded in a site repo, so `sb site agents --refresh` may update it later.
165
+ if (file === COMPONENTS_SKILL_PATH && existsSync(join(dir, SITE_MANIFEST)))
166
+ await recordAgentFiles(dir, { [file]: { sha256: sha256(body) } });
167
+ }
168
+ catch (err) {
169
+ if (err.code !== 'EEXIST')
170
+ throw err;
171
+ out.kept.push(file);
172
+ log(` · ${file} exists — kept`);
173
+ }
174
+ }
175
+ log('Next: npm install, then edit components/Hero.tsx and run sb site push — it bundles and uploads each\n' +
176
+ 'component before the pages. Then drop it on a page from the editor (Code component).');
177
+ return out;
178
+ }
179
+ function loadEsbuild(dir) {
180
+ try {
181
+ return createRequire(join(dir, 'package.json'))('esbuild');
182
+ }
183
+ catch {
184
+ throw new ComponentRefused('esbuild is not installed in this repo. Run sb site components init, then npm install ' +
185
+ `(the CLI bundles with the repo's own esbuild ${ESBUILD_VERSION}).`);
186
+ }
187
+ }
188
+ /** The shared flags: the C0 spike's, so the bundle runs in the platform's sandbox as measured. */
189
+ const COMMON = {
190
+ bundle: true,
191
+ format: 'iife',
192
+ minify: true,
193
+ jsx: 'automatic',
194
+ legalComments: 'none',
195
+ write: false,
196
+ logLevel: 'silent',
197
+ target: 'es2020',
198
+ define: { 'process.env.NODE_ENV': '"production"' },
199
+ mainFields: ['module', 'main'],
200
+ conditions: ['browser'],
201
+ alias: {
202
+ react: 'preact/compat',
203
+ 'react-dom': 'preact/compat',
204
+ 'react/jsx-runtime': 'preact/jsx-runtime',
205
+ },
206
+ };
207
+ const ssrEntry = (file) => `import * as M from ${JSON.stringify(`./${COMPONENTS_DIR}/${file}`)};
208
+ import { h } from 'preact';
209
+ import { renderToString } from 'preact-render-to-string';
210
+ globalThis.__sbComponent = { render: (p) => renderToString(h(M.default, p)), schema: M.schema };
211
+ `;
212
+ const clientEntry = (file) => `import * as M from ${JSON.stringify(`./${COMPONENTS_DIR}/${file}`)};
213
+ import { h, hydrate as mount } from 'preact';
214
+ export const hydrate = (el, props) => mount(h(M.default, props), el);
215
+ `;
216
+ /**
217
+ * The props schema, read from the source WITHOUT running anything: the literal inside
218
+ * `export const schema = defineProps({ … })` (or a bare `{ … }`). A schema built by code is
219
+ * refused with the fix — the platform re-validates what is sent, and the bundle's own defineProps
220
+ * re-checks it where the platform renders the component.
221
+ */
222
+ export function schemaOf(src) {
223
+ const m = /export\s+const\s+schema\b[^=]*=\s*(?:defineProps\s*(?:<[^>]*>)?\s*\(\s*)?/.exec(src);
224
+ const start = m ? m.index + m[0].length : -1;
225
+ let end = -1;
226
+ if (start >= 0 && src[start] === '{') {
227
+ let depth = 0;
228
+ for (let i = start, q = ''; i < src.length; i++) {
229
+ const c = src[i];
230
+ if (q) {
231
+ if (c === '\\')
232
+ i++;
233
+ else if (c === q)
234
+ q = '';
235
+ }
236
+ else if (c === '"' || c === "'" || c === '`')
237
+ q = c;
238
+ else if (c === '/' && src[i + 1] === '/')
239
+ i = src.indexOf('\n', i) < 0 ? src.length : src.indexOf('\n', i);
240
+ else if (c === '/' && src[i + 1] === '*')
241
+ i = src.indexOf('*/', i) < 0 ? src.length : src.indexOf('*/', i) + 1;
242
+ else if (c === '{')
243
+ depth++;
244
+ else if (c === '}' && --depth === 0) {
245
+ end = i + 1;
246
+ break;
247
+ }
248
+ }
249
+ }
250
+ const fail = (why) => {
251
+ throw new ComponentRefused(`\`schema\` ${why}. Write it as a literal: export const schema = defineProps({ title: { kind: 'text' } });`);
252
+ };
253
+ if (end < 0)
254
+ return fail('is not a literal object');
255
+ try {
256
+ const v = parseSource(`export default (<Page id="p" />);\nexport const page = ${src.slice(start, end)};`).exports.page?.value;
257
+ if (typeof v !== 'object' || v === null || Array.isArray(v))
258
+ return fail('is not an object');
259
+ return v;
260
+ }
261
+ catch (err) {
262
+ return fail(`could not be read (${err instanceof Error ? err.message : String(err)})`);
263
+ }
264
+ }
265
+ /** Bundles one component with the repo's esbuild. Runs the repo's build tooling, never the bundle. */
266
+ export async function buildComponent(dir, file) {
267
+ const name = file.replace(/\.tsx$/, '');
268
+ const esbuild = loadEsbuild(dir);
269
+ const run = async (contents, extra) => {
270
+ try {
271
+ const r = await esbuild.build({
272
+ ...COMMON,
273
+ ...extra,
274
+ absWorkingDir: dir,
275
+ stdin: {
276
+ contents,
277
+ resolveDir: dir,
278
+ sourcefile: `${COMPONENTS_DIR}/${name}.entry.tsx`,
279
+ loader: 'tsx',
280
+ },
281
+ });
282
+ return r.outputFiles[0]?.text ?? '';
283
+ }
284
+ catch (err) {
285
+ const errors = err.errors;
286
+ throw new ComponentRefused(`${name}: the build failed — ` +
287
+ (errors?.length
288
+ ? errors
289
+ .slice(0, 5)
290
+ .map((e) => `${e.location ? `${e.location.file}:${e.location.line}:${e.location.column} ` : ''}${e.text}`)
291
+ .join('; ')
292
+ : err instanceof Error
293
+ ? err.message
294
+ : String(err)));
295
+ }
296
+ };
297
+ const ssr = await run(ssrEntry(file), { platform: 'neutral' });
298
+ const client = await run(clientEntry(file), { platform: 'browser', globalName: '__sbClient' });
299
+ let schema;
300
+ try {
301
+ schema = schemaOf(await readFile(join(dir, COMPONENTS_DIR, file), 'utf8'));
302
+ }
303
+ catch (err) {
304
+ throw new ComponentRefused(`${name}: ${err instanceof Error ? err.message : String(err)}`);
305
+ }
306
+ const kib = (n) => `${(n / 1024).toFixed(1)} KiB`;
307
+ if (Buffer.byteLength(ssr) > MAX_SSR_BYTES)
308
+ throw new ComponentRefused(`${name}: the SSR bundle is ${kib(Buffer.byteLength(ssr))}, over the ${MAX_SSR_BYTES >> 10} KiB cap — import less (a large library does not fit; the platform's sandbox runs this bundle).`);
309
+ if (Buffer.byteLength(client) > MAX_CLIENT_BYTES)
310
+ throw new ComponentRefused(`${name}: the client bundle is ${kib(Buffer.byteLength(client))}, over the ${MAX_CLIENT_BYTES >> 10} KiB cap — import less.`);
311
+ return { name, file, schema, ssr, client };
312
+ }
313
+ /**
314
+ * The components in the repo: `components/<Name>.tsx` that export a `schema`. Anything else is
315
+ * named and left alone — `components/` is also the folder a Next.js app puts its own components in,
316
+ * and uploading `Header.tsx` as a code component would be a surprise nobody asked for.
317
+ */
318
+ export async function listComponents(dir, note) {
319
+ const st = await lstat(join(dir, COMPONENTS_DIR)).catch(() => undefined);
320
+ if (!st)
321
+ return [];
322
+ await refuseLink(dir, COMPONENTS_DIR);
323
+ const out = [];
324
+ for (const f of (await readdir(join(dir, COMPONENTS_DIR))).sort()) {
325
+ if (!f.endsWith('.tsx') || f.endsWith('.d.tsx'))
326
+ continue;
327
+ const file = `${COMPONENTS_DIR}/${f}`;
328
+ await refuseLink(dir, file);
329
+ if (!NAME.test(f.slice(0, -4))) {
330
+ note(` · ${file}: not a component name (letters, digits, _; starts with a letter) — skipped`);
331
+ continue;
332
+ }
333
+ const src = await readFile(join(dir, file), 'utf8');
334
+ if (!/export\s+const\s+schema\b/.test(src)) {
335
+ note(` · ${file}: exports no \`schema\` (defineProps) — not a code component, skipped`);
336
+ continue;
337
+ }
338
+ out.push(f);
339
+ }
340
+ return out;
341
+ }
342
+ /** The two refusals a component upload waits out once (status + code), and how it waits — injectable for tests. */
343
+ const RENDER_BUSY = new Set(['429 site_render_busy', '503 renderer_busy']);
344
+ export const uploadTiming = {
345
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
346
+ };
347
+ /** Builds and uploads each component; the version the platform assigned is printed. */
348
+ export async function pushComponents(ctx, o) {
349
+ const out = { sent: 0, failed: 0 };
350
+ let files;
351
+ try {
352
+ files = await listComponents(ctx.dir, ctx.warn);
353
+ }
354
+ catch (err) {
355
+ if (!(err instanceof ComponentRefused))
356
+ throw err;
357
+ ctx.warn(` ! ${err.message}`);
358
+ return { sent: 0, failed: 1 };
359
+ }
360
+ if (!files.length)
361
+ return out;
362
+ if (!ctx.v1 && !o.dryRun) {
363
+ ctx.warn(` ! components/: uploading code components needs an API key (wbk_… with pages.write) in SB_TOKEN or .env — a browser sign-in cannot. ${files.length} component(s) not uploaded; pages were still pushed.`);
364
+ return { sent: 0, failed: files.length };
365
+ }
366
+ for (const f of files) {
367
+ const file = `${COMPONENTS_DIR}/${f}`;
368
+ let built;
369
+ try {
370
+ built = await buildComponent(ctx.dir, f);
371
+ }
372
+ catch (err) {
373
+ if (!(err instanceof ComponentRefused))
374
+ throw err;
375
+ ctx.warn(` ! ${file}: ${err.message}`);
376
+ out.failed++;
377
+ continue;
378
+ }
379
+ const sizes = `${(Buffer.byteLength(built.ssr) / 1024).toFixed(1)} KiB SSR, ${(Buffer.byteLength(built.client) / 1024).toFixed(1)} KiB client`;
380
+ if (o.dryRun) {
381
+ ctx.log(` ↑ ${file} (dry run, ${sizes})`);
382
+ out.sent++;
383
+ continue;
384
+ }
385
+ const upload = () => send(ctx, `${ctx.base}/code-components`, 'POST', {
386
+ name: built.name,
387
+ propsSchema: built.schema,
388
+ ssrBundle: built.ssr,
389
+ clientBundle: built.client,
390
+ });
391
+ let res = await upload();
392
+ let err = res.ok ? undefined : await errorOf(res);
393
+ // A slow test render cools the site's renders for a few seconds, so the NEXT upload of the same
394
+ // push can meet a busy renderer. That one case waits (Retry-After, at most 15 s) and tries ONCE
395
+ // more; anything else, or a second refusal, fails as before.
396
+ if (err && RENDER_BUSY.has(`${res.status} ${err.code}`)) {
397
+ const secs = Math.min(15, Math.max(0, Number(res.headers.get('retry-after')) || 5));
398
+ ctx.log(` … ${file}: the platform's renderer is busy (${err.code}) — waiting ${secs}s, then one retry.`);
399
+ await uploadTiming.sleep(secs * 1000);
400
+ res = await upload();
401
+ err = res.ok ? undefined : await errorOf(res);
402
+ }
403
+ if (err) {
404
+ const wait = res.headers.get('retry-after');
405
+ ctx.warn(` ! ${file}: refused (${refusal(err)})${res.status === 429 && wait ? ` — try again in ${wait}s` : ''}`);
406
+ out.failed++;
407
+ continue;
408
+ }
409
+ const v = (await res.json()).codeComponent.version;
410
+ ctx.log(` ↑ ${file} → ${built.name} version ${v} (${res.status === 201 ? 'new' : 'unchanged'}, ${sizes})`);
411
+ out.sent++;
412
+ }
413
+ ctx.log(`${out.sent} code component(s) ${o.dryRun ? 'would be ' : ''}uploaded${out.failed ? `, ${out.failed} refused` : ''}.`);
414
+ return out;
415
+ }
416
+ // ── pins ──────────────────────────────────────────────────────────────────────────────────────
417
+ const KINDS = [
418
+ ['design/pages', 'page'],
419
+ ['design/globals', 'global'],
420
+ ['design/overlays', 'overlay'],
421
+ ];
422
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
423
+ /** Every code-component node of a document: its pinned name and version. */
424
+ export function pinsOf(doc) {
425
+ const out = [];
426
+ for (const [id, n] of Object.entries(doc.nodes ?? {})) {
427
+ const data = n.data;
428
+ const sp = n.specials;
429
+ if (!isObj(data) || data.type !== 'code-component' || !isObj(sp))
430
+ continue;
431
+ if (typeof sp.component === 'string' && typeof sp.version === 'number')
432
+ out.push({ id, name: sp.component, version: sp.version });
433
+ }
434
+ return out;
435
+ }
436
+ /** Each design file that parses, with its text; unparseable ones are the doctor's `files` check. */
437
+ async function designFiles(dir) {
438
+ const out = [];
439
+ for (const [d, kind] of KINDS) {
440
+ for (const f of (await readdir(join(dir, d)).catch(() => [])).sort()) {
441
+ if (!f.endsWith('.page.tsx'))
442
+ continue;
443
+ const file = `${d}/${f}`;
444
+ if (await linkOn(dir, file))
445
+ continue;
446
+ try {
447
+ const text = await readFile(join(dir, file), 'utf8');
448
+ const { document, meta, derived } = parseFile(text, kind);
449
+ out.push({ file, kind, doc: document, meta, derived, text });
450
+ }
451
+ catch {
452
+ // said by the files check; an upgrade must not touch a file it cannot read
453
+ }
454
+ }
455
+ }
456
+ return out;
457
+ }
458
+ export async function pinsInRepo(dir) {
459
+ const pins = [];
460
+ for (const f of await designFiles(dir))
461
+ for (const p of pinsOf(f.doc))
462
+ pins.push({ file: f.file, node: p.id, name: p.name, version: p.version });
463
+ return pins;
464
+ }
465
+ const rowsOf = (body) => {
466
+ const b = body;
467
+ return b.codeComponents ?? b.versions ?? [];
468
+ };
469
+ /** `sb site components upgrade <Name> [--to N]`: rewrites the pins in page files. A local edit only. */
470
+ export async function upgrade(o) {
471
+ if (!NAME.test(o.name))
472
+ throw new ComponentRefused(`"${o.name}" is not a component name.`);
473
+ if (o.to !== undefined && (!Number.isInteger(o.to) || o.to < 1))
474
+ throw new ComponentRefused('--to takes a version number (1, 2, 3 …).');
475
+ const ctx = await open(o);
476
+ const base = `${ctx.base}/code-components/${encodeURIComponent(o.name)}`;
477
+ const res = await send(ctx, o.to === undefined ? `${base}/versions?limit=1` : `${base}/versions/${o.to}`, 'GET');
478
+ if (!res.ok) {
479
+ if (res.status === 404)
480
+ throw new ComponentRefused(o.to === undefined
481
+ ? `The platform has no component named ${o.name}. Push it first: sb site push.`
482
+ : `The platform has no ${o.name} version ${o.to}. Without --to the latest is used.`);
483
+ throw new ComponentRefused(`Reading ${o.name} failed: ${refusal(await errorOf(res))}`);
484
+ }
485
+ const body = (await res.json());
486
+ const target = o.to === undefined ? rowsOf(body)[0] : body.codeComponent;
487
+ if (!target)
488
+ throw new ComponentRefused(`The platform has no component named ${o.name}.`);
489
+ const schema = target.propsSchema ?? {};
490
+ let changed = 0;
491
+ let files = 0;
492
+ let clashed = 0;
493
+ for (const f of await designFiles(ctx.dir)) {
494
+ const nodes = Object.entries(f.doc.nodes).filter(([id]) => pinsOf(f.doc).some((p) => p.id === id && p.name === o.name && p.version !== target.version));
495
+ if (!nodes.length)
496
+ continue;
497
+ for (const [id, n] of nodes) {
498
+ const sp = n.specials;
499
+ const was = sp.version;
500
+ const dropped = isObj(sp.props)
501
+ ? Object.keys(sp.props).filter((k) => !schema[k] || schema[k]?.kind === 'css')
502
+ : [];
503
+ sp.version = target.version;
504
+ changed++;
505
+ ctx.log(` ${f.file}: ${id} ${o.name} version ${String(was)} → ${target.version}`);
506
+ if (dropped.length)
507
+ ctx.warn(` ! ${f.file}: ${id} sets ${dropped.join(', ')}, which version ${target.version} does not take — the platform drops ${dropped.length > 1 ? 'them' : 'it'} on the next save.`);
508
+ }
509
+ files++;
510
+ // The rewrite prints the document as parsed, so a hand-typed html= goes with it: say so.
511
+ for (const d of f.derived)
512
+ ctx.warn(o.dryRun
513
+ ? derivedWarning(f.file, d).replace('your edit is ignored', 'the rewrite would drop it')
514
+ : derivedWarning(f.file, d));
515
+ if (!o.dryRun) {
516
+ await refuseLink(ctx.dir, f.file);
517
+ if (!(await putIfStill(join(ctx.dir, f.file), f.text, printFile(f.kind, f.doc, f.meta)))) {
518
+ ctx.warn(` ! ${f.file}: changed while upgrading — kept yours, not rewritten. Run it again.`);
519
+ clashed++;
520
+ }
521
+ }
522
+ }
523
+ if (!changed) {
524
+ ctx.log(`No page file pins ${o.name} below version ${target.version}: nothing to change.`);
525
+ return 0;
526
+ }
527
+ ctx.log(`${changed} pin(s) in ${files} file(s) ${o.dryRun ? 'would move' : 'moved'} to ${o.name} version ${target.version}. ` +
528
+ 'html is derived: the platform re-renders it when you push. Review the diff, then sb site push (a draft).');
529
+ return clashed ? 1 : 0;
530
+ }
531
+ /**
532
+ * `sb site components preview <Name> [--props <json|@file>] [--json]`: builds the component here,
533
+ * exactly as push does, and asks the platform to render it once (POST
534
+ * /api/v1/code-components/preview) — the HTML a page save would store, with nothing uploaded and no
535
+ * page touched. A refusal (the sandbox's own error, a bad prop) is printed with its code and the
536
+ * exit is 1, so an agent can read it and fix the component. A busy platform is said with its
537
+ * Retry-After and never retried here.
538
+ */
539
+ export async function preview(o) {
540
+ if (!NAME.test(o.name))
541
+ throw new ComponentRefused(`"${o.name}" is not a component name.`);
542
+ let props;
543
+ if (o.props !== undefined) {
544
+ const raw = o.props.startsWith('@')
545
+ ? await readFile(resolve(o.props.slice(1)), 'utf8').catch(() => {
546
+ throw new ComponentRefused(`--props ${o.props}: the file could not be read.`);
547
+ })
548
+ : o.props;
549
+ let v;
550
+ try {
551
+ v = JSON.parse(raw);
552
+ }
553
+ catch (err) {
554
+ throw new ComponentRefused(`--props is not JSON (${err instanceof Error ? err.message : String(err)}). Write an object: --props '{"title":"Hi"}'`);
555
+ }
556
+ if (!isObj(v))
557
+ throw new ComponentRefused(`--props takes a JSON object: --props '{"title":"Hi"}'`);
558
+ props = v;
559
+ }
560
+ const file = `${COMPONENTS_DIR}/${o.name}.tsx`;
561
+ await refuseLink(o.dir, COMPONENTS_DIR);
562
+ await refuseLink(o.dir, file);
563
+ if (!existsSync(join(o.dir, file)))
564
+ throw new ComponentRefused(`${file} is not here — write it first (sb site components init starts one).`);
565
+ const built = await buildComponent(o.dir, `${o.name}.tsx`);
566
+ const size = `${(Buffer.byteLength(built.ssr) / 1024).toFixed(1)} KiB SSR`;
567
+ const log = o.log ?? console.log;
568
+ if (o.dryRun) {
569
+ log(` · ${file} builds (${size}); dry run — nothing sent, nothing rendered.`);
570
+ return 0;
571
+ }
572
+ const ctx = await open(o);
573
+ if (!ctx.v1)
574
+ throw new ComponentRefused('Previewing needs an API key (wbk_… with pages.write) in SB_TOKEN or .env — a browser sign-in cannot.');
575
+ const res = await send(ctx, `${ctx.base}/code-components/preview`, 'POST', {
576
+ ssrBundle: built.ssr,
577
+ propsSchema: built.schema,
578
+ ...(props ? { props } : {}),
579
+ });
580
+ if (res.ok) {
581
+ const html = (await res.json()).html ?? '';
582
+ ctx.log(o.json ? JSON.stringify({ html }) : html);
583
+ return 0;
584
+ }
585
+ const err = await errorOf(res);
586
+ const wait = res.headers.get('retry-after');
587
+ ctx.warn(res.status === 429 || res.status === 503
588
+ ? ` ! ${file}: the platform is busy (${refusal(err)})${wait ? ` — try again in ${wait}s` : ''}. Not retried.`
589
+ : ` ! ${file}: ${refusal(err)}`);
590
+ return 1;
591
+ }
592
+ const kib = (n) => `${(n / 1024).toFixed(1)} KiB`;
593
+ /**
594
+ * `sb site components list [--json]`: each component on the platform with its versions, sizes and
595
+ * dates, plus the versions THIS repo's files pin. Which pages pin a version on the platform (drafts
596
+ * and live pages) is not something the API lists; `sb site components delete` names them on refusal.
597
+ */
598
+ export async function listRemote(o) {
599
+ const ctx = await open(o);
600
+ const read = async (url, what) => {
601
+ const res = await send(ctx, url, 'GET');
602
+ if (!res.ok)
603
+ throw new ComponentRefused(`Reading ${what} failed: ${refusal(await errorOf(res))}`);
604
+ return (await res.json());
605
+ };
606
+ const latest = (await read(`${ctx.base}/code-components`, 'the code components')).codeComponents ?? [];
607
+ const pins = await pinsInRepo(ctx.dir);
608
+ const out = [];
609
+ for (const c of [...latest].sort((a, b) => a.name.localeCompare(b.name))) {
610
+ // A component holds at most 200 live versions, which is also the page ceiling: one request.
611
+ const all = await read(`${ctx.base}/code-components/${encodeURIComponent(c.name)}/versions?limit=200`, c.name);
612
+ const here = new Map();
613
+ for (const p of pins.filter((p) => p.name === c.name))
614
+ here.set(p.version, (here.get(p.version) ?? new Set()).add(p.file));
615
+ out.push({
616
+ name: c.name,
617
+ latest: c.version,
618
+ count: all.total ?? all.codeComponents?.length ?? 0,
619
+ versions: (all.codeComponents ?? []).map((v) => ({
620
+ version: v.version,
621
+ ssrSize: v.ssrSize,
622
+ clientSize: v.clientSize,
623
+ createdAt: v.createdAt,
624
+ })),
625
+ pinnedHere: [...here.keys()]
626
+ .sort((a, b) => a - b)
627
+ .map((version) => ({ version, files: [...here.get(version)].sort() })),
628
+ });
629
+ }
630
+ if (o.json) {
631
+ ctx.log(JSON.stringify({ codeComponents: out }, null, 2));
632
+ return 0;
633
+ }
634
+ if (!out.length) {
635
+ ctx.log('No code components on the platform yet. sb site components init, then sb site push.');
636
+ return 0;
637
+ }
638
+ for (const c of out) {
639
+ ctx.log(`${c.name} latest version ${c.latest}, ${c.count} version(s)`);
640
+ for (const v of c.versions) {
641
+ const pin = c.pinnedHere.find((p) => p.version === v.version);
642
+ ctx.log(` v${v.version} ${kib(v.ssrSize)} SSR, ${kib(v.clientSize)} client ${v.createdAt}` +
643
+ (pin ? ` pinned here: ${pin.files.join(', ')}` : ''));
644
+ }
645
+ for (const p of c.pinnedHere)
646
+ if (!c.versions.some((v) => v.version === p.version))
647
+ ctx.warn(` ! v${p.version} is pinned by ${p.files.join(', ')} and is not on the platform (sb site components upgrade ${c.name})`);
648
+ }
649
+ return 0;
650
+ }
651
+ /**
652
+ * `sb site components delete <Name> <version> [--yes]`: deletes one version on the platform. Asked
653
+ * first on a terminal; off one, `--yes` is required. Refused (409 version_pinned) while any draft or
654
+ * live page, shared section or overlay pins it — the pages the platform names are printed and the
655
+ * exit is non-zero. A deleted number is never reused: the next upload gets a new one.
656
+ */
657
+ export async function deleteRemote(o) {
658
+ if (!NAME.test(o.name))
659
+ throw new ComponentRefused(`"${o.name}" is not a component name.`);
660
+ if (!Number.isInteger(o.version) || o.version < 1)
661
+ throw new ComponentRefused('Name the version to delete: sb site components delete Hero 3');
662
+ const ctx = await open(o);
663
+ if (!ctx.v1)
664
+ throw new ComponentRefused('Deleting a version needs an API key (wbk_… with pages.write) in SB_TOKEN or .env — a browser sign-in cannot.');
665
+ const what = `${o.name} version ${o.version}`;
666
+ const versionURL = `${ctx.base}/code-components/${encodeURIComponent(o.name)}/versions/${o.version}`;
667
+ for (const p of (await pinsInRepo(ctx.dir)).filter((p) => p.name === o.name && p.version === o.version))
668
+ ctx.warn(` ! ${p.file}: node ${p.node} pins ${what} — once it is deleted, pushing this file renders that node empty.`);
669
+ if (o.dryRun) {
670
+ // A read, so a missing version is said as missing; whether a page pins it only the real
671
+ // DELETE can tell (the platform checks drafts and live pages then).
672
+ const got = await send(ctx, versionURL, 'GET');
673
+ if (got.status === 404) {
674
+ ctx.warn(` ! the platform has no ${what}; nothing would be deleted.`);
675
+ return 1;
676
+ }
677
+ if (!got.ok) {
678
+ ctx.warn(` ! reading ${what} failed (${refusal(await errorOf(got))}) — nothing sent.`);
679
+ return 1;
680
+ }
681
+ ctx.log(` ✗ ${what} would be deleted (dry run) — nothing sent. Only the real delete can tell whether a page still pins it.`);
682
+ return 0;
683
+ }
684
+ if (!o.yes) {
685
+ if (!o.confirm) {
686
+ ctx.warn(` ! off a terminal, deleting ${what} needs --yes; nothing deleted.`);
687
+ return 1;
688
+ }
689
+ if (!(await o.confirm(`Delete ${what} from the platform? Its number is never reused. [y/N] `))) {
690
+ ctx.log('Nothing deleted.');
691
+ return 0;
692
+ }
693
+ }
694
+ const res = await send(ctx, versionURL, 'DELETE');
695
+ if (res.ok) {
696
+ ctx.log(` ✗ ${what} deleted. Its number is never reused: the next upload gets a new one.`);
697
+ return 0;
698
+ }
699
+ const err = await errorOf(res);
700
+ if (res.status === 409 && err.code === 'version_pinned') {
701
+ const pages = err.pages ?? [];
702
+ ctx.warn(` ! ${what} is still used — not deleted. Move these off it first (sb site components upgrade ${o.name}, then sb site push):`);
703
+ // A shared section or overlay pin may come without a page id: no empty "()" for it.
704
+ for (const p of pages)
705
+ ctx.warn(` - ${p.name || p.pageId || '?'}${p.pageId ? ` (${p.pageId})` : ''}`);
706
+ if (!pages.length)
707
+ ctx.warn(` ${err.error}`);
708
+ return 1;
709
+ }
710
+ ctx.warn(res.status === 404
711
+ ? ` ! the platform has no ${what}; nothing deleted (sb site components list shows what it has).`
712
+ : ` ! ${what} was not deleted (${refusal(err)})`);
713
+ return 1;
714
+ }
715
+ // ── doctor ────────────────────────────────────────────────────────────────────────────────────
716
+ const make = (id, title) => (status, detail, fix = null) => ({
717
+ id,
718
+ title,
719
+ status,
720
+ detail,
721
+ fix,
722
+ });
723
+ /**
724
+ * `components:build` and `components:pins`. Without `build` this is STATIC and read-only: the files
725
+ * exist, each exports a literal `schema`, esbuild is installed (its package.json is looked for,
726
+ * never loaded) and GETs. With `build` (`sb doctor --build`) each component is also bundled, which
727
+ * runs the repo's own esbuild — code from this repo's node_modules, so it is opt-in.
728
+ */
729
+ export async function doctorChecks(root, api, get, canAsk, key, build = false) {
730
+ const out = [];
731
+ {
732
+ const c = make('components:build', 'components/ is ready to push');
733
+ const notes = [];
734
+ try {
735
+ const files = await listComponents(root, (l) => notes.push(l.trim()));
736
+ if (!files.length)
737
+ out.push(c('skip', 'no components/<Name>.tsx with a schema', 'sb site components init'));
738
+ else {
739
+ const bad = [];
740
+ for (const f of files) {
741
+ const file = `${COMPONENTS_DIR}/${f}`;
742
+ try {
743
+ schemaOf(await readFile(join(root, file), 'utf8'));
744
+ if (build)
745
+ await buildComponent(root, f);
746
+ }
747
+ catch (e) {
748
+ bad.push(`${file}: ${e instanceof Error ? e.message : String(e)}`);
749
+ }
750
+ }
751
+ const installed = existsSync(join(root, 'node_modules', 'esbuild', 'package.json'));
752
+ out.push(bad.length
753
+ ? c('fail', `${bad.length} of ${files.length} cannot be pushed:\n ${bad.join('\n ')}`, 'Fix the line named, then sb site push')
754
+ : !installed
755
+ ? c('fail', 'esbuild is not installed in this repo: sb site push cannot bundle', 'sb site components init, then npm install')
756
+ : c('ok', `${files.length} component(s) with a readable schema${build ? ', and they build within the size caps' : ' (sb doctor --build also bundles them, running this repo’s esbuild)'}`));
757
+ }
758
+ }
759
+ catch (err) {
760
+ out.push(c('fail', err instanceof Error ? err.message : String(err), 'Replace the symbolic link with the real folder'));
761
+ }
762
+ }
763
+ {
764
+ const c = make('components:pins', 'Pinned component versions exist');
765
+ const pins = await pinsInRepo(root);
766
+ if (!pins.length)
767
+ out.push(c('skip', 'no page file pins a code component'));
768
+ else if (!canAsk)
769
+ out.push(c('skip', 'not tested (not signed in)'));
770
+ else {
771
+ const site = key ? '' : await sbJsonSite(root);
772
+ const base = key ? `${api}/api/v1` : `${api}/api/sites/${encodeURIComponent(site ?? '')}`;
773
+ const seen = new Map();
774
+ const gone = [];
775
+ for (const p of pins) {
776
+ const k = `${p.name}@${p.version}`;
777
+ if (!seen.has(k))
778
+ seen.set(k, (await get(`${base}/code-components/${encodeURIComponent(p.name)}/versions/${p.version}`)).status);
779
+ if (seen.get(k) === 404)
780
+ gone.push(`${p.file}: ${k}`);
781
+ }
782
+ const odd = [...seen.entries()].find(([, s]) => s !== 200 && s !== 404);
783
+ out.push(gone.length
784
+ ? c('fail', `a page pins a version the platform does not have:\n ${gone.slice(0, 10).join('\n ')}`, 'sb site push uploads components/ first; or sb site components upgrade <Name> to a version that exists')
785
+ : odd
786
+ ? c('skip', `not tested (HTTP ${odd[1]} for ${odd[0]})`)
787
+ : c('ok', `${seen.size} pinned version(s) exist`));
788
+ }
789
+ }
790
+ return out;
791
+ }
792
+ //# sourceMappingURL=components.js.map