@yannosay/sinth 5.3.2 → 5.3.4

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 (46) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +16 -4
  3. package/dist/browser/sinth.js +630 -81
  4. package/dist/cli/index.js +52 -10
  5. package/dist/cli/skill.d.ts +10 -0
  6. package/dist/cli/skill.js +106 -0
  7. package/dist/cli/templates.js +1 -1
  8. package/dist/compiler/codegen.js +42 -5
  9. package/dist/compiler/elements.d.ts +6 -0
  10. package/dist/compiler/elements.js +12 -0
  11. package/dist/compiler/html.d.ts +2 -0
  12. package/dist/compiler/html.js +7 -0
  13. package/dist/compiler/prerender.js +5 -3
  14. package/dist/deploy/cloudflare.d.ts +2 -0
  15. package/dist/deploy/cloudflare.js +103 -18
  16. package/dist/deploy/platforms.d.ts +20 -0
  17. package/dist/deploy/platforms.js +212 -0
  18. package/dist/deploy/redirects.d.ts +31 -0
  19. package/dist/deploy/redirects.js +102 -0
  20. package/dist/project/build.js +104 -18
  21. package/dist/project/config.d.ts +19 -0
  22. package/dist/project/config.js +66 -8
  23. package/dist/project/env.d.ts +11 -0
  24. package/dist/project/env.js +84 -0
  25. package/dist/project/project.d.ts +7 -1
  26. package/dist/project/project.js +37 -10
  27. package/dist/runtime/index.js +48 -8
  28. package/dist/runtime/router.js +17 -1
  29. package/dist/server/dev.d.ts +4 -0
  30. package/dist/server/dev.js +35 -11
  31. package/dist/server/functions-router.d.ts +60 -0
  32. package/dist/server/functions-router.js +161 -0
  33. package/dist/server/functions.d.ts +8 -12
  34. package/dist/server/functions.js +43 -133
  35. package/dist/server/preview.d.ts +3 -0
  36. package/dist/server/preview.js +8 -1
  37. package/dist/server/static.d.ts +9 -0
  38. package/dist/server/static.js +24 -1
  39. package/lib/ui/index.sinth +533 -24
  40. package/package.json +2 -1
  41. package/schema/sinth.config.schema.json +30 -1
  42. package/skills/agents.md +62 -0
  43. package/skills/sinth/SKILL.md +125 -0
  44. package/skills/sinth/references/language.md +175 -0
  45. package/skills/sinth/references/project-and-deploy.md +87 -0
  46. package/skills/sinth/references/ui.md +95 -0
package/dist/cli/index.js CHANGED
@@ -47,6 +47,7 @@ const preview_1 = require("../server/preview");
47
47
  const args_1 = require("./args");
48
48
  const templates_1 = require("./templates");
49
49
  const ui_1 = require("./ui");
50
+ const skill_1 = require("./skill");
50
51
  const update_check_1 = require("./update-check");
51
52
  const VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "..", "package.json"), "utf-8")).version;
52
53
  const ROOT_FLAG = {
@@ -67,6 +68,12 @@ function openProject(args, mode) {
67
68
  config.minify = !!args.flags.minify;
68
69
  if (args.flags.sourcemap !== undefined)
69
70
  config.sourcemap = !!args.flags.sourcemap;
71
+ if (typeof args.flags.platform === "string") {
72
+ const platform = args.flags.platform;
73
+ if (!config_1.PLATFORMS.includes(platform))
74
+ throw new diagnostics_1.SinthError("E0900", `Unknown platform '${args.flags.platform}'`, undefined, `Use one of: ${config_1.PLATFORMS.join(", ")}`);
75
+ config.platform = platform;
76
+ }
70
77
  return new project_1.Project(root, config, mode === "development");
71
78
  }
72
79
  const commands = {
@@ -98,13 +105,14 @@ const commands = {
98
105
  },
99
106
  build: {
100
107
  summary: "Build the site for production",
101
- usage: "sinth build [--out dist] [--no-minify] [--sourcemap]",
108
+ usage: "sinth build [--out dist] [--platform name] [--no-minify] [--sourcemap]",
102
109
  flags: {
103
110
  ...ROOT_FLAG,
104
111
  out: { type: "string", description: "Output directory" },
105
112
  minify: { type: "boolean", description: "Minify output (default: on)" },
106
113
  sourcemap: { type: "boolean", description: "Emit source maps" },
107
114
  verbose: { type: "boolean", description: "List every page, even on large sites" },
115
+ platform: { type: "string", description: "Override \"platform\" from sinth.config.json" },
108
116
  },
109
117
  async run(args) {
110
118
  console.log(`\n ${(0, ui_1.brand)("build", VERSION)}\n`);
@@ -158,18 +166,21 @@ const commands = {
158
166
  open: !!args.flags.open,
159
167
  base: project.config.base,
160
168
  root: project.root,
169
+ redirects: project.config.redirects,
170
+ allowedHosts: project.config.allowedHosts,
161
171
  });
162
172
  return -1;
163
173
  },
164
174
  },
165
175
  deploy: {
166
- summary: "Build and deploy to Cloudflare Pages",
167
- usage: "sinth deploy [--preview] [--branch name] [--project name] [--create] [--skip-build]",
176
+ summary: "Build and deploy (Cloudflare Pages or Workers, Vercel, Netlify)",
177
+ usage: "sinth deploy [--platform name] [--preview] [--branch name] [--project name] [--create] [--skip-build]",
168
178
  flags: {
169
179
  ...ROOT_FLAG,
170
180
  preview: { type: "boolean", description: "Deploy to a preview URL instead of production" },
171
181
  branch: { type: "string", description: "Branch name for the deployment" },
172
- project: { type: "string", description: "Cloudflare Pages project name" },
182
+ project: { type: "string", description: "Cloudflare Pages project or Worker name" },
183
+ platform: { type: "string", description: "Override \"platform\" from sinth.config.json" },
173
184
  create: { type: "boolean", description: "Create the Pages project first" },
174
185
  "skip-build": { type: "boolean", description: "Deploy the existing build without rebuilding" },
175
186
  },
@@ -182,7 +193,7 @@ const commands = {
182
193
  (0, ui_1.printDiagnostic)(w);
183
194
  ui_1.log.success(`Built ${out.pages.length} page(s) in ${(0, ui_1.formatMs)(out.durationMs)}`);
184
195
  }
185
- await (0, cloudflare_1.deployToCloudflare)(project.root, project.config.outDir, project.config, {
196
+ await (0, cloudflare_1.deploy)(project.root, project.config, {
186
197
  preview: !!args.flags.preview,
187
198
  branch: args.flags.branch,
188
199
  projectName: args.flags.project,
@@ -193,15 +204,20 @@ const commands = {
193
204
  },
194
205
  check: {
195
206
  summary: "Type-check every page without writing output",
196
- usage: "sinth check [--json]",
197
- flags: { ...ROOT_FLAG, json: { type: "boolean", description: "Print diagnostics as JSON (for editors)" } },
207
+ usage: "sinth check [--json] [--max-warnings n]",
208
+ flags: {
209
+ ...ROOT_FLAG,
210
+ json: { type: "boolean", description: "Print diagnostics as JSON (for editors and AI agents)" },
211
+ "max-warnings": { type: "number", description: "Fail when there are more warnings than this (use 0 in CI)" },
212
+ },
198
213
  async run(args) {
214
+ const maxWarnings = args.flags["max-warnings"] === undefined ? Infinity : Number(args.flags["max-warnings"]);
199
215
  if (args.flags.json) {
200
216
  const root = projectRoot(args);
201
217
  const { config } = (0, config_1.loadConfig)(root, "production");
202
218
  const result = (0, build_1.checkProject)(new project_1.Project(root, config, false));
203
219
  process.stdout.write(JSON.stringify({ version: 1, errors: result.errors.map(e => e.diagnostic), warnings: result.warnings }) + "\n");
204
- return result.errors.length ? 1 : 0;
220
+ return result.errors.length || result.warnings.length > maxWarnings ? 1 : 0;
205
221
  }
206
222
  console.log(`\n ${(0, ui_1.brand)("check", VERSION)}\n`);
207
223
  const project = openProject(args, "production");
@@ -215,10 +231,33 @@ const commands = {
215
231
  ui_1.log.error(`${result.errors.length} error(s) in ${result.pages.length} page(s)`);
216
232
  return 1;
217
233
  }
234
+ if (result.warnings.length > maxWarnings) {
235
+ ui_1.log.error(`${result.warnings.length} warning(s), more than the allowed ${maxWarnings}`);
236
+ return 1;
237
+ }
218
238
  ui_1.log.success(`${result.pages.length} page(s) checked, no errors${result.warnings.length ? `, ${result.warnings.length} warning(s)` : ""} ${ui_1.c.gray((0, ui_1.formatMs)(Date.now() - started))}`);
219
239
  return 0;
220
240
  },
221
241
  },
242
+ skill: {
243
+ summary: "Teach your AI coding agent Sinth (installs the Sinth skill)",
244
+ usage: "sinth skill [--claude | --agents] [--global]",
245
+ flags: {
246
+ ...ROOT_FLAG,
247
+ claude: { type: "boolean", description: "Install for Claude Code (.claude/skills/sinth)" },
248
+ agents: { type: "boolean", description: "Install for other agents (.agents/skills/sinth and AGENTS.md)" },
249
+ global: { type: "boolean", description: "Install for all projects (~/.claude/skills/sinth)" },
250
+ },
251
+ async run(args) {
252
+ console.log(`\n ${(0, ui_1.brand)("skill", VERSION)}\n`);
253
+ const result = (0, skill_1.installSkill)(projectRoot(args), {
254
+ claude: !!args.flags.claude, agents: !!args.flags.agents, global: !!args.flags.global,
255
+ }, VERSION);
256
+ for (const line of result)
257
+ console.log(line);
258
+ return 0;
259
+ },
260
+ },
222
261
  create: {
223
262
  summary: "Create a new Sinth project",
224
263
  usage: "sinth create [name] [--template starter|minimal|blank] [--yes]",
@@ -250,7 +289,8 @@ const commands = {
250
289
  if (kind === "component" && name) {
251
290
  if (!/^[A-Z][A-Za-z0-9]*$/.test(name))
252
291
  throw new diagnostics_1.SinthError("E1301", `Component names must be PascalCase, like 'ProductCard'`);
253
- writeNew(path.join(root, "components", name + ".sinth"), (0, templates_1.componentTemplate)(name));
292
+ const { config } = (0, config_1.loadConfig)(root, "development");
293
+ writeNew(path.join(config.srcDir, "components", name + ".sinth"), (0, templates_1.componentTemplate)(name));
254
294
  return 0;
255
295
  }
256
296
  throw new diagnostics_1.SinthError("E1302", "Usage: sinth new page <path> | sinth new component <Name>");
@@ -277,7 +317,8 @@ const commands = {
277
317
  ["Platform", `${process.platform} ${process.arch}`],
278
318
  ["Project", root],
279
319
  ["Config", file ? path.relative(root, file) : ui_1.c.gray("none (defaults)")],
280
- ["Pages", `${pages} in ${path.relative(root, config.pagesDir) || "."}`],
320
+ ["Source", path.relative(root, config.srcDir) || "."],
321
+ ["Pages", `${pages} in ${path.relative(root, fs.existsSync(config.pagesDir) ? config.pagesDir : config.srcDir) || "."}`],
281
322
  ["Output", path.relative(root, config.outDir)],
282
323
  ].map(([k, v]) => [ui_1.c.gray(k), v])));
283
324
  return 0;
@@ -381,6 +422,7 @@ async function createProject(args) {
381
422
  console.log(` cd ${path.relative(process.cwd(), dir)}`);
382
423
  console.log(" npm install");
383
424
  console.log(` ${ui_1.c.cyan("npm run dev")}\n`);
425
+ console.log(` ${ui_1.c.gray("Building with an AI agent? Run")} npx sinth skill ${ui_1.c.gray("to teach it Sinth.")}\n`);
384
426
  return 0;
385
427
  }
386
428
  function printHelp(command) {
@@ -0,0 +1,10 @@
1
+ export interface SkillOptions {
2
+ claude: boolean;
3
+ agents: boolean;
4
+ global: boolean;
5
+ }
6
+ /**
7
+ * Installs the Sinth skill that ships with this package, so it always matches the installed
8
+ * compiler. Returns the lines to print.
9
+ */
10
+ export declare function installSkill(root: string, opts: SkillOptions, version: string): string[];
@@ -0,0 +1,106 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.installSkill = installSkill;
37
+ const fs = __importStar(require("fs"));
38
+ const os = __importStar(require("os"));
39
+ const path = __importStar(require("path"));
40
+ const diagnostics_1 = require("../compiler/diagnostics");
41
+ const project_1 = require("../project/project");
42
+ const ui_1 = require("./ui");
43
+ const SKILL_SOURCE = path.join(project_1.PACKAGE_ROOT, "skills", "sinth");
44
+ const AGENTS_SECTION = [
45
+ "## Sinth",
46
+ "",
47
+ "This project uses Sinth (.sinth files). Before working on it, read `.agents/skills/sinth/SKILL.md` and follow it. More detail is in `.agents/skills/sinth/references/`.",
48
+ "",
49
+ ].join("\n");
50
+ function copyDir(from, to) {
51
+ let count = 0;
52
+ fs.mkdirSync(to, { recursive: true });
53
+ for (const e of fs.readdirSync(from, { withFileTypes: true })) {
54
+ const src = path.join(from, e.name);
55
+ const dest = path.join(to, e.name);
56
+ if (e.isDirectory())
57
+ count += copyDir(src, dest);
58
+ else {
59
+ fs.copyFileSync(src, dest);
60
+ count++;
61
+ }
62
+ }
63
+ return count;
64
+ }
65
+ /** Adds or replaces the "## Sinth" section of AGENTS.md, which Codex, Cursor, Copilot and others read. */
66
+ function writeAgentsSection(file) {
67
+ const existing = fs.existsSync(file) ? fs.readFileSync(file, "utf-8") : "";
68
+ const start = existing.search(/^## Sinth\s*$/m);
69
+ let next;
70
+ if (start === -1)
71
+ next = (existing.trim() ? existing.replace(/\s*$/, "\n\n") : "# Agent instructions\n\n") + AGENTS_SECTION;
72
+ else {
73
+ const rest = existing.slice(start + 1);
74
+ const end = rest.search(/^## /m);
75
+ next = existing.slice(0, start) + AGENTS_SECTION + (end === -1 ? "" : "\n" + rest.slice(end));
76
+ }
77
+ fs.writeFileSync(file, next);
78
+ }
79
+ /**
80
+ * Installs the Sinth skill that ships with this package, so it always matches the installed
81
+ * compiler. Returns the lines to print.
82
+ */
83
+ function installSkill(root, opts, version) {
84
+ if (!fs.existsSync(path.join(SKILL_SOURCE, "SKILL.md")))
85
+ throw new diagnostics_1.SinthError("E1310", "The Sinth skill is missing from this installation", undefined, "Reinstall @yannosay/sinth");
86
+ const forClaude = opts.global || opts.claude || (!opts.agents && (fs.existsSync(path.join(root, ".claude")) || fs.existsSync(path.join(root, "CLAUDE.md"))));
87
+ const targets = [];
88
+ if (opts.global)
89
+ targets.push({ label: "Claude Code (all projects)", dir: path.join(os.homedir(), ".claude", "skills", "sinth") });
90
+ else if (forClaude)
91
+ targets.push({ label: "Claude Code", dir: path.join(root, ".claude", "skills", "sinth") });
92
+ if (opts.agents || (!forClaude && !opts.global))
93
+ targets.push({ label: "AGENTS.md agents (Codex, Cursor, Copilot, Gemini, ...)", dir: path.join(root, ".agents", "skills", "sinth") });
94
+ const out = [];
95
+ const show = (p) => (p.startsWith(root + path.sep) ? path.relative(root, p) : p.startsWith(os.homedir()) ? "~" + p.slice(os.homedir().length) : p).replace(/\\/g, "/");
96
+ for (const t of targets) {
97
+ copyDir(SKILL_SOURCE, t.dir);
98
+ out.push(` ${ui_1.c.green("✓")} ${ui_1.c.bold(`Sinth skill ${version}`)} installed for ${t.label}`, ` ${ui_1.c.gray(show(t.dir))}`);
99
+ if (t.dir.includes(`${path.sep}.agents${path.sep}`)) {
100
+ writeAgentsSection(path.join(root, "AGENTS.md"));
101
+ out.push(` ${ui_1.c.gray("AGENTS.md points your agent to it")}`);
102
+ }
103
+ }
104
+ out.push("", " Your agent now knows Sinth's syntax and components, checks each change with", ` ${ui_1.c.cyan("sinth check")} and keeps code small by reaching for ${ui_1.c.cyan("sinth:ui")} first.`, "", ` ${ui_1.c.bold("Try asking it")}`, ` ${ui_1.c.gray("›")} Add a contact form with validation to the home page`, ` ${ui_1.c.gray("›")} Build a dashboard page with a sortable table and a settings modal`, ` ${ui_1.c.gray("›")} Deploy this site to Cloudflare`, "", ` ${ui_1.c.gray("Run this again after updating Sinth to refresh the skill.")}`, "");
105
+ return out;
106
+ }
@@ -24,7 +24,7 @@ function templateFiles(template, name, version) {
24
24
  scripts: { dev: "sinth dev", build: "sinth build", preview: "sinth preview", check: "sinth check", deploy: "sinth deploy" },
25
25
  devDependencies: { "@yannosay/sinth": `^${version.replace(/-.*$/, "")}` },
26
26
  }, null, 2) + "\n",
27
- ".gitignore": "node_modules/\ndist/\n.sinth/\n.wrangler/\n.dev.vars\n.env\n",
27
+ ".gitignore": "node_modules/\ndist/\n.sinth/\n.wrangler/\n.vercel/\n.dev.vars\n.env\n.env.local\n.env.*.local\n",
28
28
  "README.md": `# ${name}\n\nBuilt with [Sinth](https://sinth.yannosay.com).\n\n\`\`\`bash\nnpm install\nnpm run dev # http://localhost:3000\nnpm run build # production build in dist/\nnpm run deploy # deploy to Cloudflare Pages\n\`\`\`\n`,
29
29
  "public/robots.txt": "User-agent: *\nAllow: /\n",
30
30
  };
@@ -79,6 +79,15 @@ function collectExports(file) {
79
79
  return exports;
80
80
  }
81
81
  const EVENT_NAME_MAP = { doubleclick: "dblclick", dblclick: "dblclick" };
82
+ /** Common DOM events, used to suggest a fix for typos like onClik. Other names still work as custom events. */
83
+ const KNOWN_EVENTS = [
84
+ "Click", "DoubleClick", "Dblclick", "ContextMenu", "MouseDown", "MouseUp", "MouseMove", "MouseEnter", "MouseLeave", "MouseOver", "MouseOut",
85
+ "PointerDown", "PointerUp", "PointerMove", "PointerEnter", "PointerLeave", "PointerCancel", "TouchStart", "TouchEnd", "TouchMove",
86
+ "KeyDown", "KeyUp", "KeyPress", "Input", "Change", "Submit", "Reset", "Focus", "Blur", "FocusIn", "FocusOut", "Scroll", "Wheel",
87
+ "DragStart", "Drag", "DragEnd", "DragEnter", "DragLeave", "DragOver", "Drop", "Load", "Error", "Resize", "Select", "Invalid",
88
+ "Play", "Pause", "Ended", "TimeUpdate", "Toggle", "Close", "Cancel", "AnimationEnd", "TransitionEnd", "Copy", "Cut", "Paste",
89
+ ].map(e => "on" + e);
90
+ const KNOWN_EVENT_SET = new Set(KNOWN_EVENTS.map(e => e.toLowerCase()));
82
91
  function eventName(attr) {
83
92
  const raw = attr.slice(2).toLowerCase();
84
93
  return EVENT_NAME_MAP[raw] ?? raw;
@@ -480,8 +489,10 @@ class ModuleCompiler {
480
489
  switch (node.k) {
481
490
  case "text":
482
491
  return this.genText(node.expr, parent, ctx);
483
- case "element":
484
- return this.genElement(node, parent, ctx, roots);
492
+ case "element": {
493
+ const value = (0, elements_1.bareValueRef)(node, n => { const b = ctx.scope.lookup(n); return !!b && b.kind !== "component"; });
494
+ return value ? this.genText(value, parent, ctx) : this.genElement(node, parent, ctx, roots);
495
+ }
485
496
  case "if":
486
497
  return this.genIf(node, parent, ctx, !!roots);
487
498
  case "for":
@@ -552,11 +563,25 @@ class ModuleCompiler {
552
563
  }
553
564
  return node.children.every(c => this.isStaticNode(c, ctx));
554
565
  }
566
+ /**
567
+ * Void elements (Input, Img, ...) cannot have children. Static markup used to drop them silently,
568
+ * so there it stays a warning to keep existing builds working; dynamic elements were always an error.
569
+ */
570
+ checkVoidChildren(node, ctx, strict) {
571
+ if (!node.children.length || !elements_1.VOID_TAGS.has(this.elementShape(node, ctx).tag))
572
+ return;
573
+ const message = `${node.name} is a void element and cannot have children`;
574
+ const hint = node.name === "Input" || node.name === "Checkbox" || node.name === "Radio" ? "Put the text in a Label next to it, e.g. Label { Checkbox(model: done) \" Done\" }" : undefined;
575
+ if (strict)
576
+ this.fail("E0331", message, node.loc, hint);
577
+ this.diagnostics.warn("W0331", message + " (they are ignored)", node.loc, hint);
578
+ }
555
579
  staticHtml(node, ctx) {
556
580
  if (node.k === "text")
557
581
  return node.expr.k === "lit" && node.expr.value !== null ? (0, html_1.escapeHtml)(String(node.expr.value)) : "";
558
582
  if (node.k !== "element")
559
583
  return "";
584
+ this.checkVoidChildren(node, ctx, false);
560
585
  const { tag, attrs } = this.elementShape(node, ctx);
561
586
  const attrStr = Object.entries(attrs).map(([k, v]) => (v === "" && elements_1.BOOLEAN_ATTRS.has(k) ? ` ${k}` : ` ${k}="${(0, html_1.escapeAttr)(v)}"`)).join("");
562
587
  if (elements_1.VOID_TAGS.has(tag))
@@ -647,6 +672,8 @@ class ModuleCompiler {
647
672
  }
648
673
  if (node.slots.length)
649
674
  this.fail("E0311", "slot(...) fills can only be used inside components that declare $slot", node.slots[0].loc);
675
+ if (!this.isStaticNode(node, ctx))
676
+ this.checkVoidChildren(node, ctx, true);
650
677
  if (this.isStaticNode(node, ctx)) {
651
678
  const html = this.staticHtml(node, ctx);
652
679
  if (roots) {
@@ -664,15 +691,17 @@ class ModuleCompiler {
664
691
  lines.push(`const ${v} = ${isSvg ? `$$.svg(${JSON.stringify(tag)})` : `$$.el(${JSON.stringify(tag)})`};`);
665
692
  for (const [k, val] of Object.entries(attrs))
666
693
  lines.push(`${v}.setAttribute(${JSON.stringify(k)}, ${JSON.stringify(val)});`);
667
- lines.push(...this.genDynamicAttrs(node, v, tag, ctx));
694
+ const dynamic = this.genDynamicAttrs(node, v, tag, ctx);
695
+ // A <select>'s value can only be set once its options exist, so it is bound after the children.
696
+ const afterChildren = tag === "select" ? dynamic.filter(l => l.startsWith("$$.model(") || l.startsWith(`$$.prop(${v}, "value"`)) : [];
697
+ lines.push(...dynamic.filter(l => !afterChildren.includes(l)));
668
698
  const childCtx = { ...ctx, svg: isSvg && tag !== "foreignObject" };
669
699
  const htmlAttr = node.attrs.find(a => a.name === "html");
670
700
  if (htmlAttr && node.children.length)
671
701
  this.fail("E0330", "An element with 'html' cannot also have children", htmlAttr.loc);
672
- if (elements_1.VOID_TAGS.has(tag) && node.children.length)
673
- this.fail("E0331", `<${tag}> is a void element and cannot have children`, node.loc);
674
702
  if (node.children.length)
675
703
  lines.push(this.genNodes(node.children, v, childCtx));
704
+ lines.push(...afterChildren);
676
705
  lines.push(`${parent}.appendChild(${v});`);
677
706
  return lines.filter(Boolean).join("\n");
678
707
  }
@@ -693,6 +722,11 @@ class ModuleCompiler {
693
722
  continue;
694
723
  if (a.handler) {
695
724
  this.interactive = true;
725
+ if (!KNOWN_EVENT_SET.has(a.name.toLowerCase())) {
726
+ const s = (0, diagnostics_1.suggest)(a.name, KNOWN_EVENTS);
727
+ if (s)
728
+ this.diagnostics.warn("W0302", `Unknown event '${a.name}'`, a.loc, `Did you mean '${s}'? Other names listen for custom events`);
729
+ }
696
730
  lines.push(`$$.on(${v}, ${JSON.stringify(eventName(a.name))}, ${this.genHandler(a, scope)}${a.modifiers.length ? ", " + JSON.stringify(a.modifiers) : ""});`);
697
731
  continue;
698
732
  }
@@ -767,6 +801,9 @@ class ModuleCompiler {
767
801
  const ex = stmts[0].expr;
768
802
  if (ex.k === "arrow")
769
803
  return this.expr(ex, scope);
804
+ if (ex.k === "lit" && typeof ex.value !== "string") {
805
+ this.fail("E0352", `Event handlers must be code, not ${ex.value === null ? "null" : typeof ex.value}`, ex.loc, `Write the handler as code, e.g. ${a.name}: count += 1`);
806
+ }
770
807
  if (ex.k === "lit" || ex.k === "tpl") {
771
808
  const raw = ex.k === "lit" ? String(ex.value) : "";
772
809
  const name = raw.replace(/\(\s*\)\s*;?$/, "");
@@ -1,3 +1,4 @@
1
+ import type { ElementNode, Expr } from "./ast";
1
2
  export interface ElementInfo {
2
3
  tag: string;
3
4
  className?: string;
@@ -12,3 +13,8 @@ export declare const INLINE_STYLE_PROPS: ReadonlySet<string>;
12
13
  export declare const URL_ATTRS: ReadonlySet<string>;
13
14
  export declare const BOOLEAN_ATTRS: ReadonlySet<string>;
14
15
  export declare function attrNameToHtml(name: string): string;
16
+ /**
17
+ * A capitalized name written as a child, like `P { API_URL }`, parses as an element. When it is not
18
+ * an element but a value in scope (a constant, an import from sinth:env, ...), it is text instead.
19
+ */
20
+ export declare function bareValueRef(node: ElementNode, isValue: (name: string) => boolean): Expr | null;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BOOLEAN_ATTRS = exports.URL_ATTRS = exports.INLINE_STYLE_PROPS = exports.VOID_TAGS = exports.SPECIAL_ELEMENTS = exports.ELEMENTS = void 0;
4
4
  exports.attrNameToHtml = attrNameToHtml;
5
+ exports.bareValueRef = bareValueRef;
5
6
  const e = (tag, extra = {}) => ({ tag, ...extra });
6
7
  exports.ELEMENTS = {
7
8
  Main: e("main"), Header: e("header"), Footer: e("footer"), Nav: e("nav"), Section: e("section"), Article: e("article"),
@@ -76,3 +77,14 @@ function attrNameToHtml(name) {
76
77
  };
77
78
  return map[name] ?? name;
78
79
  }
80
+ /**
81
+ * A capitalized name written as a child, like `P { API_URL }`, parses as an element. When it is not
82
+ * an element but a value in scope (a constant, an import from sinth:env, ...), it is text instead.
83
+ */
84
+ function bareValueRef(node, isValue) {
85
+ if (node.attrs.length || node.children.length || node.slots.length || node.hasBody || node.name.includes("."))
86
+ return null;
87
+ if (exports.ELEMENTS[node.name] || exports.SPECIAL_ELEMENTS.has(node.name) || !isValue(node.name))
88
+ return null;
89
+ return { k: "id", name: node.name, loc: node.loc };
90
+ }
@@ -1,6 +1,8 @@
1
1
  import { MetaEntry } from "./ast";
2
2
  export declare function escapeHtml(s: string): string;
3
3
  export declare function escapeAttr(s: string): string;
4
+ /** True for URLs that run script when followed (javascript:, vbscript:, data:text/html, ...). Mirrors the runtime check. */
5
+ export declare function isUnsafeUrl(value: string): boolean;
4
6
  export declare function hashString(s: string): string;
5
7
  export interface HeadData {
6
8
  title?: string;
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.escapeHtml = escapeHtml;
4
4
  exports.escapeAttr = escapeAttr;
5
+ exports.isUnsafeUrl = isUnsafeUrl;
5
6
  exports.hashString = hashString;
6
7
  exports.buildHead = buildHead;
7
8
  exports.renderDocument = renderDocument;
@@ -12,6 +13,12 @@ function escapeHtml(s) {
12
13
  function escapeAttr(s) {
13
14
  return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/'/g, "&#39;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
14
15
  }
16
+ const UNSAFE_URL = /^(javascript:|vbscript:|data:(?!image\/(png|gif|jpe?g|webp|avif|svg\+xml)[;,]|video\/|audio\/))/i;
17
+ /** True for URLs that run script when followed (javascript:, vbscript:, data:text/html, ...). Mirrors the runtime check. */
18
+ function isUnsafeUrl(value) {
19
+ // eslint-disable-next-line no-control-regex
20
+ return UNSAFE_URL.test(value.replace(/[\u0000- \u007f]/g, ""));
21
+ }
15
22
  function hashString(s) {
16
23
  let h1 = 0x811c9dc5;
17
24
  let h2 = 0x01000193;
@@ -521,8 +521,10 @@ class Prerenderer {
521
521
  }
522
522
  return (0, html_1.escapeHtml)(toText(v));
523
523
  }
524
- case "element":
525
- return this.renderElement(node, scope);
524
+ case "element": {
525
+ const value = (0, elements_1.bareValueRef)(node, n => !this.components(scope.file).has(n) && !!scope.env.find(n));
526
+ return value ? this.renderNode({ k: "text", expr: value, loc: node.loc }, scope) : this.renderElement(node, scope);
527
+ }
526
528
  case "if": {
527
529
  for (const br of node.branches) {
528
530
  const t = br.test ? this.eval(br.test, scope.env, scope.file) : true;
@@ -684,7 +686,7 @@ class Prerenderer {
684
686
  if (/^on/i.test(name))
685
687
  continue;
686
688
  const str = v === true ? "" : typeof v === "object" ? JSON.stringify(v) : String(v);
687
- attrs.set(name, /^(href|src|action|formaction|poster)$/.test(name) && /^\s*(javascript|vbscript):/i.test(str) ? "about:blank#blocked" : str);
689
+ attrs.set(name, elements_1.URL_ATTRS.has(name) && (0, html_1.isUnsafeUrl)(str) ? "about:blank#blocked" : str);
688
690
  }
689
691
  const cls = classes.filter(Boolean).join(" ");
690
692
  if (cls)
@@ -6,4 +6,6 @@ export interface DeployOptions {
6
6
  projectName?: string;
7
7
  }
8
8
  export declare function defaultProjectName(root: string): string;
9
+ /** Uploads a finished build to the host set by `platform`. */
10
+ export declare function deploy(root: string, config: SinthConfig, opts: DeployOptions): Promise<void>;
9
11
  export declare function deployToCloudflare(root: string, outDir: string, config: SinthConfig, opts: DeployOptions): Promise<void>;