@zenera/cli 1.3.22 → 1.3.23

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 (23) hide show
  1. package/package.json +6 -6
  2. package/templates/editor/.github/skills/zen-review/scripts/check-paths.sh +1 -1
  3. package/templates/project/agents/skills/html-page/SKILL.md +96 -51
  4. package/templates/project/agents/skills/html-page/assets/app/api/items.api.py +3 -2
  5. package/templates/project/agents/skills/html-page/assets/app/app.tsx +140 -0
  6. package/templates/project/agents/skills/html-page/assets/dashboard.tsx +162 -0
  7. package/templates/project/agents/skills/html-page/kit/Chart.tsx +79 -0
  8. package/templates/project/agents/skills/html-page/kit/Table.tsx +89 -0
  9. package/templates/project/agents/skills/html-page/kit/api.ts +93 -0
  10. package/templates/project/agents/skills/html-page/kit/components.tsx +266 -0
  11. package/templates/project/agents/skills/html-page/kit/format.ts +60 -0
  12. package/templates/project/agents/skills/html-page/kit/hooks.ts +159 -0
  13. package/templates/project/agents/skills/html-page/kit/index.ts +35 -0
  14. package/templates/project/agents/skills/html-page/kit/modules.d.ts +37 -0
  15. package/templates/project/agents/skills/html-page/kit/mount.tsx +62 -0
  16. package/templates/project/agents/skills/html-page/kit/shell.html +19 -0
  17. package/templates/project/agents/skills/html-page/kit/theme.css +326 -0
  18. package/templates/project/agents/skills/html-page/references/charts-and-tables.md +105 -53
  19. package/templates/project/agents/skills/html-page/references/python-functions.md +37 -29
  20. package/templates/project/agents/skills/html-page/scripts/build.ts +825 -0
  21. package/templates/project/agents/skills/html-page/assets/api.js +0 -87
  22. package/templates/project/agents/skills/html-page/assets/app/index.html +0 -278
  23. package/templates/project/agents/skills/html-page/assets/dashboard.html +0 -423
@@ -0,0 +1,825 @@
1
+ #!/usr/bin/env node
2
+ // The html-page skill's build: a page folder's app.tsx in, one self-contained index.html out.
3
+ //
4
+ // node /skills/html-page/scripts/build.ts /workspace/pages/<page> build the page
5
+ // node /skills/html-page/scripts/build.ts /workspace/pages/<page> --check check, write nothing
6
+ //
7
+ // Every top-level .tsx with a default export is a page: app.tsx -> index.html, report.tsx ->
8
+ // report.html. The steps, each stopping the build with a list of what to fix:
9
+ // 1. types TypeScript (strict, but without asking for annotations everywhere), React,
10
+ // and the kit as `@page/kit`
11
+ // 2. rules what a sandboxed page cannot do: storage, dialogs, other hosts, raw html, ...
12
+ // 3. bundle esbuild: React, the kit and the page's modules in one script
13
+ // 4. render App rendered once in Node, so a crash on first render is caught here
14
+ // 5. write the html: shell.html with the css and js inlined, stamped with a hash of the
15
+ // sources. Nothing is written unless every step passed.
16
+ // --check runs 1, 2 and 4 and says whether each page's html is out of date with its sources.
17
+ //
18
+ // Runs where esbuild, typescript, react, react-dom and their types are installed: in the zen
19
+ // sandbox globally (NODE_PATH, which require() reads), in this repository from node_modules.
20
+ // Node runs this file as it is, stripping the types: only erasable TypeScript here.
21
+
22
+ import { spawnSync } from 'node:child_process';
23
+ import { createHash } from 'node:crypto';
24
+ import {
25
+ existsSync,
26
+ mkdtempSync,
27
+ readdirSync,
28
+ readFileSync,
29
+ realpathSync,
30
+ rmSync,
31
+ statSync,
32
+ writeFileSync,
33
+ } from 'node:fs';
34
+ import { createRequire } from 'node:module';
35
+ import { tmpdir } from 'node:os';
36
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
37
+ import { fileURLToPath, pathToFileURL } from 'node:url';
38
+ import type * as Esbuild from 'esbuild';
39
+ import type * as Typescript from 'typescript';
40
+
41
+ const SKILL = resolve(dirname(fileURLToPath(import.meta.url)), '..');
42
+ const KIT = join(SKILL, 'kit');
43
+ const KIT_INDEX = join(KIT, 'index.ts');
44
+ const KIT_MOUNT = join(KIT, 'mount.tsx');
45
+ const SHELL = join(KIT, 'shell.html');
46
+
47
+ const CDNS = ['cdn.jsdelivr.net', 'unpkg.com', 'cdnjs.cloudflare.com'];
48
+ const ECHARTS = 'https://cdn.jsdelivr.net/npm/echarts@5.6.0/dist/echarts.min.js';
49
+ const TABULATOR = 'https://cdn.jsdelivr.net/npm/tabulator-tables@6.3.1/dist/js/tabulator.min.js';
50
+ const TABULATOR_CSS =
51
+ 'https://cdn.jsdelivr.net/npm/tabulator-tables@6.3.1/dist/css/tabulator_simple.min.css';
52
+
53
+ const STAMP = /<!-- Built by the html-page skill from (\S+) \(sources ([0-9a-f]+)\)/;
54
+ const MAX_PROBLEMS = 20;
55
+ const RENDER_TIMEOUT_MS = 20_000;
56
+
57
+ interface Problem {
58
+ /** relative to the page folder, or absolute outside it; '' when about no file */
59
+ file: string;
60
+ line: number;
61
+ col: number;
62
+ message: string;
63
+ }
64
+
65
+ interface Entry {
66
+ /** the .tsx, absolute */
67
+ source: string;
68
+ /** the html it builds, absolute */
69
+ html: string;
70
+ title: string;
71
+ }
72
+
73
+ interface Tools {
74
+ ts: typeof Typescript;
75
+ esbuild: typeof Esbuild;
76
+ /** where react and react-dom are, for esbuild */
77
+ nodePaths: string[];
78
+ /** the node_modules holding react, and the @types folder holding its types */
79
+ modules: string;
80
+ types: string;
81
+ }
82
+
83
+ class Failed extends Error {
84
+ readonly problems: Problem[];
85
+ constructor(problems: Problem[]) {
86
+ super('build failed');
87
+ this.problems = problems;
88
+ }
89
+ }
90
+
91
+ function loadTools(): Tools | null {
92
+ const req = createRequire(import.meta.url);
93
+ try {
94
+ const pkg = (name: string) => dirname(req.resolve(`${name}/package.json`));
95
+ const react = pkg('react');
96
+ const reactDom = pkg('react-dom');
97
+ const types = dirname(pkg('@types/react'));
98
+ pkg('@types/react-dom');
99
+ return {
100
+ ts: req('typescript') as typeof Typescript,
101
+ esbuild: req('esbuild') as typeof Esbuild,
102
+ nodePaths: [...new Set([dirname(react), dirname(reactDom)])],
103
+ modules: dirname(react),
104
+ types,
105
+ };
106
+ } catch {
107
+ return null;
108
+ }
109
+ }
110
+
111
+ const rel = (dir: string, file: string) => {
112
+ const r = relative(dir, file);
113
+ return r.startsWith('..') || isAbsolute(r) ? file : r.split(sep).join('/');
114
+ };
115
+
116
+ /** The page's own source files: everything but dot-folders and node_modules. */
117
+ function sourcesOf(dir: string): string[] {
118
+ const out: string[] = [];
119
+ const walk = (d: string) => {
120
+ for (const e of readdirSync(d, { withFileTypes: true })) {
121
+ if (e.name.startsWith('.') || e.name === 'node_modules') continue;
122
+ const p = join(d, e.name);
123
+ if (e.isDirectory()) walk(p);
124
+ else if (/\.(tsx?|css)$/.test(e.name)) out.push(p);
125
+ }
126
+ };
127
+ walk(dir);
128
+ return out.sort();
129
+ }
130
+
131
+ function sourcesHash(dir: string, sources: string[]): string {
132
+ const hash = createHash('sha256');
133
+ for (const file of sources) {
134
+ hash.update(rel(dir, file)).update('\0').update(readFileSync(file)).update('\0');
135
+ }
136
+ return hash.digest('hex').slice(0, 16);
137
+ }
138
+
139
+ function titleOf(text: string, fallback: string): string {
140
+ const m = /export\s+const\s+title(?:\s*:\s*string)?\s*=\s*(['"`])([^'"`\n]+)\1/.exec(text);
141
+ if (m) return m[2]!;
142
+ const words = fallback.replace(/[-_]+/g, ' ').trim();
143
+ return words ? words[0]!.toUpperCase() + words.slice(1) : 'Page';
144
+ }
145
+
146
+ function entriesOf(dir: string): { entries: Entry[]; problems: Problem[] } {
147
+ const problems: Problem[] = [];
148
+ const entries: Entry[] = [];
149
+ const tsx = readdirSync(dir)
150
+ .filter((f) => f.endsWith('.tsx') && statSync(join(dir, f)).isFile())
151
+ .sort();
152
+ for (const name of tsx) {
153
+ const source = join(dir, name);
154
+ const text = readFileSync(source, 'utf8');
155
+ if (!/\bexport\s+default\b/.test(text)) {
156
+ problems.push({
157
+ file: name,
158
+ line: 1,
159
+ col: 1,
160
+ message:
161
+ 'a .tsx beside the page is a page of its own and needs `export default function App()`; ' +
162
+ 'move a component it uses into a subfolder (components/...) and import it from there',
163
+ });
164
+ continue;
165
+ }
166
+ const base = basename(name, '.tsx');
167
+ const htmlName = base === 'app' || base === 'index' ? 'index.html' : `${base}.html`;
168
+ const clash = entries.find((e) => basename(e.html) === htmlName);
169
+ if (clash) {
170
+ problems.push({
171
+ file: name,
172
+ line: 1,
173
+ col: 1,
174
+ message: `${basename(clash.source)} already builds ${htmlName}: keep one of them`,
175
+ });
176
+ continue;
177
+ }
178
+ const fallback = htmlName === 'index.html' ? basename(dir) : base;
179
+ entries.push({ source, html: join(dir, htmlName), title: titleOf(text, fallback) });
180
+ }
181
+ if (!entries.length && !problems.length) {
182
+ problems.push({
183
+ file: '',
184
+ line: 0,
185
+ col: 0,
186
+ message:
187
+ 'no page here: write app.tsx with `export default function App()`, ' +
188
+ 'or copy a template from /skills/html-page/assets',
189
+ });
190
+ }
191
+ return { entries, problems };
192
+ }
193
+
194
+ // ---------------------------------------------------------------------------------------------
195
+ // 1. Types
196
+
197
+ function typecheck(tools: Tools, dir: string, entries: Entry[]): Problem[] {
198
+ const { ts } = tools;
199
+ const options: Typescript.CompilerOptions = {
200
+ target: ts.ScriptTarget.ES2022,
201
+ module: ts.ModuleKind.ESNext,
202
+ moduleResolution: ts.ModuleResolutionKind.Bundler,
203
+ jsx: ts.JsxEmit.ReactJSX,
204
+ strict: true,
205
+ // Wrong fields and wrong calls are what matter; annotations everywhere are noise.
206
+ noImplicitAny: false,
207
+ noEmit: true,
208
+ skipLibCheck: true,
209
+ allowImportingTsExtensions: true,
210
+ isolatedModules: true,
211
+ esModuleInterop: true,
212
+ resolveJsonModule: true,
213
+ lib: ['lib.es2023.d.ts', 'lib.dom.d.ts', 'lib.dom.iterable.d.ts'],
214
+ types: [],
215
+ paths: {
216
+ '@page/kit': [KIT_INDEX],
217
+ '*': [`${tools.modules}/*`, `${tools.types}/*`],
218
+ },
219
+ };
220
+ const program = ts.createProgram(
221
+ [...entries.map((e) => e.source), join(KIT, 'modules.d.ts')],
222
+ options,
223
+ );
224
+ return ts.getPreEmitDiagnostics(program).map((d) => {
225
+ const message = ts.flattenDiagnosticMessageText(d.messageText, ' ');
226
+ if (!d.file || d.start === undefined) return { file: '', line: 0, col: 0, message };
227
+ const { line, character } = d.file.getLineAndCharacterOfPosition(d.start);
228
+ return { file: rel(dir, d.file.fileName), line: line + 1, col: character + 1, message };
229
+ });
230
+ }
231
+
232
+ // ---------------------------------------------------------------------------------------------
233
+ // 2. Rules
234
+
235
+ const STORAGE = new Set(['localStorage', 'sessionStorage', 'indexedDB']);
236
+ const DIALOGS = new Set(['alert', 'confirm', 'prompt']);
237
+ const MOUNTING = new Set(['createRoot', 'hydrateRoot', 'render']);
238
+
239
+ function hostOf(url: string): string {
240
+ try {
241
+ return new URL(url).host;
242
+ } catch {
243
+ return '';
244
+ }
245
+ }
246
+
247
+ function rules(tools: Tools, dir: string, sources: string[]): Problem[] {
248
+ const { ts } = tools;
249
+ const problems: Problem[] = [];
250
+ const checkedFiles = new Set<string>();
251
+
252
+ const checkFile = (wanted: string, at: () => Problem, api = false) => {
253
+ if (/^(https?:|data:|blob:|#)/.test(wanted) || wanted.includes('${')) return;
254
+ const path = resolve(
255
+ dir,
256
+ api ? `${wanted.replace(/\/+$/, '')}.api.py` : wanted.split(/[?#]/)[0]!,
257
+ );
258
+ if (!existsSync(path)) {
259
+ const p = at();
260
+ p.message = api
261
+ ? `api('${wanted}'): there is no ${rel(dir, path)} beside the page`
262
+ : `'${wanted}': there is no such file beside the page (paths are relative to the page's html)`;
263
+ problems.push(p);
264
+ } else if (!api && path.endsWith('.json') && !checkedFiles.has(path)) {
265
+ checkedFiles.add(path);
266
+ try {
267
+ JSON.parse(readFileSync(path, 'utf8'));
268
+ } catch (err) {
269
+ const p = at();
270
+ p.message = `'${wanted}' is not valid JSON: ${(err as Error).message}`;
271
+ problems.push(p);
272
+ }
273
+ }
274
+ };
275
+
276
+ for (const file of sources) {
277
+ if (!/\.tsx?$/.test(file) || file.endsWith('.d.ts')) continue;
278
+ const text = readFileSync(file, 'utf8');
279
+ const sf = ts.createSourceFile(
280
+ file,
281
+ text,
282
+ ts.ScriptTarget.Latest,
283
+ true,
284
+ file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS,
285
+ );
286
+ const at = (node: Typescript.Node) => (): Problem => {
287
+ const { line, character } = sf.getLineAndCharacterOfPosition(node.getStart(sf));
288
+ return { file: rel(dir, file), line: line + 1, col: character + 1, message: '' };
289
+ };
290
+ const report = (node: Typescript.Node, message: string) =>
291
+ problems.push({ ...at(node)(), message });
292
+
293
+ const visit = (node: Typescript.Node): void => {
294
+ if (ts.isIdentifier(node) && STORAGE.has(node.text)) {
295
+ report(
296
+ node,
297
+ `${node.text} is not available to pages: keep view state in hooks or useHashState, ` +
298
+ 'and what must last in the database through an api function',
299
+ );
300
+ } else if (ts.isCallExpression(node)) {
301
+ const callee = node.expression;
302
+ const name = ts.isIdentifier(callee)
303
+ ? callee.text
304
+ : ts.isPropertyAccessExpression(callee)
305
+ ? callee.name.text
306
+ : '';
307
+ const target =
308
+ ts.isPropertyAccessExpression(callee) && ts.isIdentifier(callee.expression)
309
+ ? callee.expression.text
310
+ : '';
311
+ const arg = node.arguments[0];
312
+ const literal =
313
+ arg && (ts.isStringLiteral(arg) || ts.isNoSubstitutionTemplateLiteral(arg))
314
+ ? arg.text
315
+ : undefined;
316
+ if (
317
+ DIALOGS.has(name) &&
318
+ (ts.isIdentifier(callee) || target === 'window' || target === 'globalThis')
319
+ ) {
320
+ report(
321
+ node,
322
+ `${name}() is blocked in pages: use ConfirmButton for a second-click confirm, ` +
323
+ 'or show the message on the page',
324
+ );
325
+ } else if (name === 'createRoot' || name === 'hydrateRoot') {
326
+ report(
327
+ node,
328
+ 'the build mounts the page itself: export App as default and do not call createRoot',
329
+ );
330
+ } else if (name === 'insertAdjacentHTML') {
331
+ report(
332
+ node,
333
+ 'no raw html: use JSX (it escapes), or SafeHtml for html from outside',
334
+ );
335
+ } else if (
336
+ literal !== undefined &&
337
+ (name === 'fetch' || name === 'useData' || name === 'fetchJson')
338
+ ) {
339
+ if (/^https?:\/\//.test(literal)) {
340
+ report(
341
+ node,
342
+ `${name}('${literal}'): a page reaches only its own folder; fetch other sites ` +
343
+ 'from a Python function in api/ and call it with api()',
344
+ );
345
+ } else {
346
+ checkFile(literal, at(arg!));
347
+ }
348
+ } else if (literal !== undefined && name === 'api' && ts.isIdentifier(callee)) {
349
+ checkFile(literal, at(arg!), true);
350
+ }
351
+ } else if (
352
+ ts.isPropertyAccessExpression(node) &&
353
+ node.name.text === 'cookie' &&
354
+ ts.isIdentifier(node.expression) &&
355
+ node.expression.text === 'document'
356
+ ) {
357
+ report(node, 'cookies are not available to pages');
358
+ } else if (
359
+ ts.isBinaryExpression(node) &&
360
+ node.operatorToken.kind === ts.SyntaxKind.EqualsToken &&
361
+ ts.isPropertyAccessExpression(node.left) &&
362
+ (node.left.name.text === 'innerHTML' || node.left.name.text === 'outerHTML')
363
+ ) {
364
+ report(
365
+ node,
366
+ 'no raw html: use JSX (it escapes), or SafeHtml for html from outside',
367
+ );
368
+ } else if (
369
+ ts.isJsxAttribute(node) &&
370
+ node.name.getText(sf) === 'dangerouslySetInnerHTML'
371
+ ) {
372
+ report(
373
+ node,
374
+ 'no raw html: use JSX (it escapes), or SafeHtml for html from outside',
375
+ );
376
+ } else if (
377
+ ts.isImportDeclaration(node) &&
378
+ ts.isStringLiteral(node.moduleSpecifier) &&
379
+ /^react-dom(\/client)?$/.test(node.moduleSpecifier.text)
380
+ ) {
381
+ const named = node.importClause?.namedBindings;
382
+ if (named && ts.isNamedImports(named)) {
383
+ for (const el of named.elements) {
384
+ if (MOUNTING.has((el.propertyName ?? el.name).text)) {
385
+ report(
386
+ el,
387
+ 'the build mounts the page itself: export App as default and do not import ' +
388
+ `${(el.propertyName ?? el.name).text} from ${node.moduleSpecifier.text}`,
389
+ );
390
+ }
391
+ }
392
+ }
393
+ } else if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) {
394
+ stringRules(node, node.text);
395
+ } else if (ts.isTemplateExpression(node)) {
396
+ stringRules(node, node.head.text);
397
+ }
398
+ ts.forEachChild(node, visit);
399
+ };
400
+
401
+ const stringRules = (node: Typescript.Node, value: string) => {
402
+ if (ts.isImportDeclaration(node.parent) || ts.isExportDeclaration(node.parent)) {
403
+ if (/^https?:\/\//.test(value)) {
404
+ report(
405
+ node,
406
+ 'import packages the build knows (react, @page/kit) or files of the page, not urls',
407
+ );
408
+ }
409
+ return;
410
+ }
411
+ if (/file:\/\//i.test(value)) {
412
+ report(node, 'a page loads its files by a path relative to it, never file://');
413
+ } else if (/^\/(workspace|assets|skills)(\/|$)/.test(value)) {
414
+ report(
415
+ node,
416
+ `'${value}': the page cannot see the sandbox's folders; use a path relative to the page`,
417
+ );
418
+ } else if (/\b(localhost|127\.0\.0\.1)\b/.test(value)) {
419
+ report(
420
+ node,
421
+ 'the page cannot reach localhost; call a Python function in api/ instead',
422
+ );
423
+ } else if (/^https?:\/\//.test(value)) {
424
+ const attr =
425
+ node.parent && ts.isJsxAttribute(node.parent) ? node.parent : undefined;
426
+ const attrName = attr?.name.getText(sf);
427
+ if (attr && attrName === 'href') {
428
+ const element = attr.parent.parent;
429
+ const tag =
430
+ ts.isJsxOpeningElement(element) || ts.isJsxSelfClosingElement(element)
431
+ ? element.tagName.getText(sf)
432
+ : '';
433
+ const blank = attr.parent.properties.some(
434
+ (p) =>
435
+ ts.isJsxAttribute(p) &&
436
+ p.name.getText(sf) === 'target' &&
437
+ p.initializer !== undefined &&
438
+ ts.isStringLiteral(p.initializer) &&
439
+ p.initializer.text === '_blank',
440
+ );
441
+ if (tag === 'a' && !blank) {
442
+ report(node, 'a link to another site needs target="_blank" rel="noopener"');
443
+ }
444
+ } else if (attr && attrName === 'src' && !CDNS.includes(hostOf(value))) {
445
+ report(
446
+ node,
447
+ `${hostOf(value)} is blocked: a page loads only its own files and from ${CDNS.join(', ')}`,
448
+ );
449
+ }
450
+ }
451
+ };
452
+
453
+ visit(sf);
454
+ }
455
+ const data = join(dir, 'data.json');
456
+ if (existsSync(data) && !checkedFiles.has(data)) {
457
+ try {
458
+ JSON.parse(readFileSync(data, 'utf8'));
459
+ } catch (err) {
460
+ problems.push({
461
+ file: 'data.json',
462
+ line: 0,
463
+ col: 0,
464
+ message: `not valid JSON: ${(err as Error).message}`,
465
+ });
466
+ }
467
+ }
468
+ return problems;
469
+ }
470
+
471
+ // ---------------------------------------------------------------------------------------------
472
+ // 3. Bundle
473
+
474
+ const kitPlugin: Esbuild.Plugin = {
475
+ name: 'page-kit',
476
+ setup(build) {
477
+ build.onResolve({ filter: /^@page\/kit$/ }, () => ({ path: KIT_INDEX }));
478
+ },
479
+ };
480
+
481
+ const ASSET_LOADERS: Record<string, Esbuild.Loader> = {
482
+ '.png': 'dataurl',
483
+ '.jpg': 'dataurl',
484
+ '.jpeg': 'dataurl',
485
+ '.gif': 'dataurl',
486
+ '.webp': 'dataurl',
487
+ '.svg': 'dataurl',
488
+ '.woff2': 'dataurl',
489
+ '.txt': 'text',
490
+ '.md': 'text',
491
+ };
492
+
493
+ function esbuildProblems(dir: string, err: unknown): Problem[] {
494
+ const errors = (err as { errors?: Esbuild.Message[] }).errors;
495
+ if (!errors?.length) return [{ file: '', line: 0, col: 0, message: String(err) }];
496
+ return errors.map((m) => ({
497
+ file: m.location ? rel(dir, resolve(dir, m.location.file)) : '',
498
+ line: m.location?.line ?? 0,
499
+ col: (m.location?.column ?? 0) + 1,
500
+ message: m.text,
501
+ }));
502
+ }
503
+
504
+ interface Bundle {
505
+ js: string;
506
+ css: string;
507
+ echarts: boolean;
508
+ tabulator: boolean;
509
+ }
510
+
511
+ async function bundle(tools: Tools, dir: string, entry: Entry): Promise<Bundle> {
512
+ const source = `./${basename(entry.source)}`;
513
+ let result: Esbuild.BuildResult<{ write: false }>;
514
+ try {
515
+ result = await tools.esbuild.build({
516
+ stdin: {
517
+ contents: `import { mount } from ${JSON.stringify(KIT_MOUNT)};\nimport App from ${JSON.stringify(source)};\nmount(App);\n`,
518
+ resolveDir: dir,
519
+ sourcefile: 'page-entry.tsx',
520
+ loader: 'tsx',
521
+ },
522
+ absWorkingDir: dir,
523
+ bundle: true,
524
+ write: false,
525
+ outdir: join(dir, '.build'),
526
+ format: 'esm',
527
+ platform: 'browser',
528
+ target: 'es2022',
529
+ jsx: 'automatic',
530
+ minify: true,
531
+ legalComments: 'none',
532
+ define: { 'process.env.NODE_ENV': '"production"' },
533
+ nodePaths: tools.nodePaths,
534
+ plugins: [kitPlugin],
535
+ loader: ASSET_LOADERS,
536
+ logLevel: 'silent',
537
+ });
538
+ } catch (err) {
539
+ throw new Failed(esbuildProblems(dir, err));
540
+ }
541
+ const js = result.outputFiles.find((f) => f.path.endsWith('.js'))?.text ?? '';
542
+ const css = result.outputFiles.find((f) => f.path.endsWith('.css'))?.text ?? '';
543
+ // Globals keep their names through minifying: what is left of them is what the page uses.
544
+ return {
545
+ js,
546
+ css,
547
+ echarts: /\becharts\s*\.\s*init\b/.test(js),
548
+ tabulator: /\bnew\s+Tabulator\b/.test(js),
549
+ };
550
+ }
551
+
552
+ // ---------------------------------------------------------------------------------------------
553
+ // 4. Render
554
+
555
+ // What a page may touch while it first renders, standing in for the browser's. `require` is for
556
+ // react-dom's CommonJS, which loads Node's own modules.
557
+ const RENDER_GLOBALS = `
558
+ import { createRequire as __pageRequire } from 'node:module';
559
+ const require = __pageRequire(import.meta.url);
560
+ globalThis.window ??= globalThis;
561
+ globalThis.location ??= { hash: '', href: 'http://page.local/', pathname: '/', search: '', origin: 'null', assign() {}, replace() {}, reload() {} };
562
+ globalThis.history ??= { pushState() {}, replaceState() {}, back() {}, forward() {} };
563
+ globalThis.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {} });
564
+ globalThis.addEventListener ??= () => {};
565
+ globalThis.removeEventListener ??= () => {};
566
+ `;
567
+
568
+ async function renderCheck(tools: Tools, dir: string, entry: Entry): Promise<Problem[]> {
569
+ // Real paths: the source map's paths are relative, and a symlinked tmp would skew them.
570
+ const tmp = realpathSync(mkdtempSync(join(tmpdir(), 'html-page-')));
571
+ const outfile = join(tmp, 'render.mjs');
572
+ const source = `./${basename(entry.source)}`;
573
+ try {
574
+ try {
575
+ await tools.esbuild.build({
576
+ stdin: {
577
+ contents: [
578
+ `import { renderToString } from 'react-dom/server';`,
579
+ `import { createElement } from 'react';`,
580
+ `try {`,
581
+ ` const { default: App } = await import(${JSON.stringify(source)});`,
582
+ ` renderToString(createElement(App));`,
583
+ `} catch (e) {`,
584
+ ` console.error('PAGE_RENDER_ERROR ' + JSON.stringify({ message: String(e?.message ?? e), stack: String(e?.stack ?? '') }));`,
585
+ ` process.exit(1);`,
586
+ `}`,
587
+ ].join('\n'),
588
+ resolveDir: dir,
589
+ sourcefile: 'page-render.tsx',
590
+ loader: 'tsx',
591
+ },
592
+ absWorkingDir: dir,
593
+ bundle: true,
594
+ write: true,
595
+ outfile,
596
+ format: 'esm',
597
+ platform: 'node',
598
+ target: 'node22',
599
+ jsx: 'automatic',
600
+ sourcemap: 'inline',
601
+ define: { 'process.env.NODE_ENV': '"production"' },
602
+ banner: { js: RENDER_GLOBALS },
603
+ nodePaths: tools.nodePaths,
604
+ plugins: [kitPlugin],
605
+ loader: { ...ASSET_LOADERS, '.css': 'empty' },
606
+ logLevel: 'silent',
607
+ });
608
+ } catch (err) {
609
+ return esbuildProblems(dir, err);
610
+ }
611
+ const run = spawnSync(process.execPath, ['--enable-source-maps', outfile], {
612
+ cwd: tmp,
613
+ encoding: 'utf8',
614
+ timeout: RENDER_TIMEOUT_MS,
615
+ });
616
+ if (run.error || run.signal) {
617
+ return [
618
+ {
619
+ file: rel(dir, entry.source),
620
+ line: 0,
621
+ col: 0,
622
+ message: `the first render did not finish in ${RENDER_TIMEOUT_MS / 1000} s: is there an endless loop?`,
623
+ },
624
+ ];
625
+ }
626
+ if (run.status === 0) return [];
627
+ const marker = /PAGE_RENDER_ERROR (.*)/.exec(run.stderr);
628
+ let message = run.stderr.trim().split('\n').slice(0, 3).join(' ');
629
+ let stack = '';
630
+ if (marker) {
631
+ try {
632
+ const parsed = JSON.parse(marker[1]!) as { message: string; stack: string };
633
+ message = parsed.message;
634
+ stack = parsed.stack;
635
+ } catch {
636
+ // keep the raw stderr
637
+ }
638
+ }
639
+ // The first frame in the page's own files, not React's or the kit's.
640
+ let where: Problem = { file: rel(dir, entry.source), line: 0, col: 0, message: '' };
641
+ for (const m of stack.matchAll(/\(?((?:file:\/\/)?[^\s()]+):(\d+):(\d+)\)?/g)) {
642
+ const path = m[1]!.startsWith('file://') ? fileURLToPath(m[1]!) : m[1]!;
643
+ if (resolve(path).startsWith(dir + sep) && !path.includes(`${sep}node_modules${sep}`)) {
644
+ where = {
645
+ file: rel(dir, resolve(path)),
646
+ line: Number(m[2]),
647
+ col: Number(m[3]),
648
+ message: '',
649
+ };
650
+ break;
651
+ }
652
+ }
653
+ return [
654
+ {
655
+ ...where,
656
+ message:
657
+ `the page crashed on its first render: ${message}` +
658
+ (/\b(document|navigator|ResizeObserver|IntersectionObserver)\b/.test(message)
659
+ ? ' (this check renders without a browser: touch the DOM in useEffect or in handlers, not while rendering)'
660
+ : ''),
661
+ },
662
+ ];
663
+ } finally {
664
+ rmSync(tmp, { recursive: true, force: true });
665
+ }
666
+ }
667
+
668
+ // ---------------------------------------------------------------------------------------------
669
+ // 5. Write
670
+
671
+ const escapeHtml = (s: string) =>
672
+ s.replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]!);
673
+
674
+ function pageHtml(dir: string, entry: Entry, built: Bundle, hash: string): string {
675
+ const head: string[] = [];
676
+ if (built.tabulator) head.push(`<link rel="stylesheet" href="${TABULATOR_CSS}" />`);
677
+ if (built.echarts) head.push(`<script src="${ECHARTS}"></script>`);
678
+ if (built.tabulator) head.push(`<script src="${TABULATOR}"></script>`);
679
+ const source = rel(dir, entry.source);
680
+ const stamp =
681
+ `<!-- Built by the html-page skill from ${source} (sources ${hash}). ` +
682
+ `Do not edit this file: edit ${source} and run the build again. -->`;
683
+ // Inlined, a script or style ends at the first `</script` or `</style` anywhere in it, and
684
+ // `<!--` changes how the browser looks for that end.
685
+ const js = built.js.replace(/<\/(script)/gi, '<\\/$1').replace(/<!--/g, '<\\!--');
686
+ const css = built.css.replace(/<\/(style)/gi, '<\\/$1');
687
+ const parts: Record<string, string> = {
688
+ STAMP: stamp,
689
+ TITLE: escapeHtml(entry.title),
690
+ HEAD: head.join('\n '),
691
+ CSS: css,
692
+ JS: js,
693
+ };
694
+ return readFileSync(SHELL, 'utf8').replace(
695
+ /<!--(STAMP|TITLE|HEAD|CSS|JS)-->/g,
696
+ (_, key: string) => parts[key]!,
697
+ );
698
+ }
699
+
700
+ /** The stamp of a built html: its source and the hash of the sources it was built from. */
701
+ function stampOf(file: string): { source: string; hash: string } | null {
702
+ if (!existsSync(file)) return null;
703
+ const head = readFileSync(file, 'utf8').slice(0, 2000);
704
+ const m = STAMP.exec(head);
705
+ return m ? { source: m[1]!, hash: m[2]! } : null;
706
+ }
707
+
708
+ // ---------------------------------------------------------------------------------------------
709
+
710
+ function print(dir: string, problems: Problem[]) {
711
+ const shown = problems.slice(0, MAX_PROBLEMS);
712
+ console.error(`✗ ${problems.length} problem${problems.length === 1 ? '' : 's'} in ${dir}:`);
713
+ for (const p of shown) {
714
+ const where = p.file ? (p.line ? `${p.file}:${p.line}:${p.col}` : p.file) : '';
715
+ console.error(where ? ` ${where} ${p.message}` : ` ${p.message}`);
716
+ }
717
+ if (problems.length > shown.length) {
718
+ console.error(` … and ${problems.length - shown.length} more`);
719
+ }
720
+ console.error('Nothing was written. Fix these and run the build again.');
721
+ }
722
+
723
+ async function main(argv: string[]): Promise<number> {
724
+ const check = argv.includes('--check');
725
+ const args = argv.filter((a) => !a.startsWith('--'));
726
+ const given = resolve(args[0] ?? '.');
727
+ if (!existsSync(given) || !statSync(given).isDirectory()) {
728
+ console.error(`✗ ${given} is not a folder. Usage: node build.ts <page folder> [--check]`);
729
+ return 2;
730
+ }
731
+ const dir = realpathSync(given);
732
+ const tools = loadTools();
733
+ if (!tools) {
734
+ console.error(
735
+ '✗ The page build needs esbuild, typescript, react and react-dom, which the zen sandbox ' +
736
+ 'image has. Run it with the sandbox enabled (sandbox: in agents.yaml).',
737
+ );
738
+ return 2;
739
+ }
740
+ try {
741
+ const { entries, problems } = entriesOf(dir);
742
+ const sources = sourcesOf(dir);
743
+ const found = [
744
+ ...problems,
745
+ ...(entries.length ? typecheck(tools, dir, entries) : []),
746
+ ...rules(tools, dir, sources),
747
+ ];
748
+ if (found.length) throw new Failed(found);
749
+
750
+ const hash = sourcesHash(dir, sources);
751
+ const pages: { entry: Entry; html?: string }[] = [];
752
+ for (const entry of entries) {
753
+ const target = stampOf(entry.html);
754
+ if (!check && existsSync(entry.html) && !target) {
755
+ throw new Failed([
756
+ {
757
+ file: rel(dir, entry.html),
758
+ line: 0,
759
+ col: 0,
760
+ message:
761
+ `is not a page this build wrote (it has no html-page stamp), so it is not ` +
762
+ `overwritten: move or delete it, then build again to write it from ${basename(entry.source)}`,
763
+ },
764
+ ]);
765
+ }
766
+ const rendered = await renderCheck(tools, dir, entry);
767
+ if (rendered.length) throw new Failed(rendered);
768
+ if (!check) {
769
+ pages.push({
770
+ entry,
771
+ html: pageHtml(dir, entry, await bundle(tools, dir, entry), hash),
772
+ });
773
+ } else {
774
+ pages.push({ entry });
775
+ }
776
+ }
777
+
778
+ if (check) {
779
+ const stale: Problem[] = [];
780
+ for (const { entry } of pages) {
781
+ const stamp = stampOf(entry.html);
782
+ const html = rel(dir, entry.html);
783
+ if (!stamp) {
784
+ stale.push({
785
+ file: html,
786
+ line: 0,
787
+ col: 0,
788
+ message: `not built yet: run the build`,
789
+ });
790
+ } else if (stamp.hash !== hash) {
791
+ stale.push({
792
+ file: html,
793
+ line: 0,
794
+ col: 0,
795
+ message: `out of date with ${basename(entry.source)} and the files it uses: run the build`,
796
+ });
797
+ }
798
+ }
799
+ if (stale.length) throw new Failed(stale);
800
+ console.log(`✓ ${dir}: checked, and every page is up to date`);
801
+ return 0;
802
+ }
803
+
804
+ for (const { entry, html } of pages) {
805
+ writeFileSync(entry.html, html!);
806
+ const kb = Math.round(Buffer.byteLength(html!) / 1024);
807
+ console.log(
808
+ `✓ wrote ${rel(dir, entry.html)} (${kb} KB) from ${rel(dir, entry.source)}`,
809
+ );
810
+ }
811
+ const link = pages.find((p) => basename(p.entry.html) === 'index.html') ?? pages[0]!;
812
+ console.log(
813
+ `Link it as [${link.entry.title}](${pathToFileURL(join(given, basename(link.entry.html))).href})`,
814
+ );
815
+ return 0;
816
+ } catch (err) {
817
+ if (err instanceof Failed) {
818
+ print(dir, err.problems);
819
+ return 1;
820
+ }
821
+ throw err;
822
+ }
823
+ }
824
+
825
+ process.exitCode = await main(process.argv.slice(2));