@yannosay/sinth 5.2.2 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/CHANGELOG.md +47 -0
  2. package/README.md +38 -19
  3. package/dist/browser/compile.d.ts +35 -0
  4. package/dist/browser/compile.js +158 -0
  5. package/dist/browser/sinth.js +1492 -0
  6. package/dist/cli/index.js +3 -1
  7. package/dist/cli/templates.js +2 -2
  8. package/dist/cli/ui.d.ts +0 -1
  9. package/dist/cli/ui.js +1 -2
  10. package/dist/compiler/ast.d.ts +11 -0
  11. package/dist/compiler/codegen.d.ts +2 -87
  12. package/dist/compiler/codegen.js +49 -6
  13. package/dist/compiler/diagnostics.d.ts +0 -1
  14. package/dist/compiler/diagnostics.js +0 -4
  15. package/dist/compiler/html.d.ts +2 -0
  16. package/dist/compiler/html.js +11 -1
  17. package/dist/compiler/lexer.js +9 -2
  18. package/dist/compiler/parser.js +27 -1
  19. package/dist/compiler/prerender.js +4 -0
  20. package/dist/index.d.ts +2 -0
  21. package/dist/index.js +3 -1
  22. package/dist/project/build.d.ts +6 -0
  23. package/dist/project/build.js +69 -41
  24. package/dist/project/config.d.ts +1 -0
  25. package/dist/project/config.js +3 -2
  26. package/dist/project/project.d.ts +1 -0
  27. package/dist/project/project.js +2 -1
  28. package/dist/runtime/index.d.ts +6 -0
  29. package/dist/runtime/index.js +18 -2
  30. package/dist/runtime/router.d.ts +36 -0
  31. package/dist/runtime/router.js +215 -0
  32. package/dist/server/client.js +3 -1
  33. package/dist/server/dev.js +65 -25
  34. package/dist/server/functions.d.ts +49 -0
  35. package/dist/server/functions.js +309 -0
  36. package/dist/server/preview.d.ts +2 -0
  37. package/dist/server/preview.js +41 -18
  38. package/dist/server/static.d.ts +10 -0
  39. package/dist/server/static.js +25 -0
  40. package/package.json +20 -12
  41. package/schema/sinth.config.schema.json +2 -1
  42. package/DOCS.md +0 -1360
package/CHANGELOG.md CHANGED
@@ -1,5 +1,52 @@
1
1
  # Changelog
2
2
 
3
+ ## 5.3.0
4
+
5
+ ### Instant navigation
6
+
7
+ - Links between pages no longer reload the whole page. Sinth fetches the next page's prerendered HTML, updates the head, swaps the content and starts the page's code. Pages are prefetched on hover and focus. Back/forward, scroll positions and `#anchors` work as before, and every page is still a complete HTML file.
8
+ - Each page starts with fresh state; shared stores keep theirs across pages. A `sinth:navigate` event fires after each navigation.
9
+ - Opt out per link with `dataReload: true`, or for the whole site with `"router": false` (static pages then ship no JavaScript at all).
10
+
11
+ ### Server functions
12
+
13
+ - Files in `functions/` are API routes, following the Cloudflare Pages Functions conventions: `onRequest` / `onRequestGet` / ... handlers, `[param]` and `[[catchall]]` segments, `_middleware` files, `env` from `.dev.vars`, and `next()` / `env.ASSETS`.
14
+ - They run in `sinth dev` (reloaded on save) and `sinth preview`, and deploy with `sinth deploy` unchanged.
15
+
16
+ ### Language
17
+
18
+ - State changed from timers, promise callbacks and other callbacks in Sinth code now updates the page, e.g. `setInterval(() => { seconds += 1 }, 1000)` in `onMount`. Before, only event handlers triggered updates. Updates are batched, and code in `script` blocks still calls `sinthRender()`.
19
+ - `try` / `catch` / `finally` and `throw` in functions, handlers and lifecycle blocks.
20
+ - `x--` reports that `--` starts a comment and suggests `x -= 1`, instead of a confusing syntax error.
21
+ - `jsonLd` page metadata writes schema.org structured data.
22
+ - Pages include `<meta name="generator" content="Sinth">` (override with `generator`).
23
+
24
+ ### Custom elements
25
+
26
+ - `dist/elements/index.js` registers every element of the project at once.
27
+ - A project with only components (no pages) builds just its elements, for use in any HTML site.
28
+ - Elements are also served by the dev server.
29
+
30
+ ### Compiler API and playground
31
+
32
+ - `compileFiles()` compiles in-memory sources without a file system or bundler.
33
+ - A browser build of the compiler ships at `dist/browser/sinth.js`; it powers the new playground at sinth.yannosay.com/playground.
34
+
35
+ ### Fixes
36
+
37
+ - `"base"` (hosting in a subfolder) now works in `sinth dev` and `sinth preview`: pages, assets and hot reload are served under the base path.
38
+ - Rebuilding a site without interactive pages failed with E0801, because Sinth did not recognize its own output folder.
39
+ - `public/` dotfiles such as `.nojekyll` and `.htaccess` are copied; OS junk files (`.DS_Store`, `Thumbs.db`, `desktop.ini`) are skipped.
40
+ - The dev and preview servers accept POST, PUT, PATCH and DELETE requests for function routes.
41
+
42
+ ### Documentation
43
+
44
+ - The documentation moved into this repository (`docs/`) and was rewritten, with a tutorial and new pages for data fetching, server functions, SEO and client-side navigation. Runnable examples are compiled in CI. `DOCS.md` was replaced by it.
45
+
46
+ ## 5.2.3
47
+
48
+ - `script { }` and `style { }` blocks are now recognized on the line after a statement that ends in `)` or `]`, such as `var data = JSON.parse(text)`. Before, this failed with a confusing syntax error.
49
+
3
50
  ## 5.2.2
4
51
 
5
52
  - Documentation: clearer README and package description, working links for the VS Code extension and Sinth IDE.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/@yannosay/sinth?color=a855f7&label=npm&style=for-the-badge)](https://www.npmjs.com/package/@yannosay/sinth) [![downloads](https://img.shields.io/npm/dt/@yannosay/sinth?color=c084fc&label=downloads&style=for-the-badge)](https://www.npmjs.com/package/@yannosay/sinth) [![CI](https://img.shields.io/github/actions/workflow/status/Yannosay/sinth/ci.yml?branch=main&label=CI&style=for-the-badge)](https://github.com/Yannosay/sinth/actions) [![license](https://img.shields.io/npm/l/@yannosay/sinth?color=a78bfa&style=for-the-badge)](./LICENSE)
4
4
 
5
- **Sinth is a reactive language for building websites and web apps of any size, from a landing page to a large multi-page product.** Write pages and components in one readable syntax. The compiler type-checks your whole project and produces fast, secure HTML, CSS and JavaScript, with no framework to learn.
5
+ **Sinth is a compiled, type-checked language for websites and web apps.** Write pages and components in one readable syntax; the compiler checks the whole project and produces prerendered HTML, scoped CSS and a small amount of JavaScript. Routing, instant navigation, API routes, a component library and deployment are built in.
6
6
 
7
7
  ```sinth
8
8
  title = "Counter"
@@ -15,15 +15,7 @@ Main {
15
15
  }
16
16
  ```
17
17
 
18
- ## Why Sinth
19
-
20
- - **Easy to read, easy to learn.** Markup, state, logic and styles live together in one file with no boilerplate.
21
- - **Reactive by default.** Change a variable and exactly the affected parts of the page update.
22
- - **Built to scale.** File-based routing with dynamic routes (`pages/blog/[slug].sinth` generates one page per post), shared layouts and components, project-wide type checking, code splitting and cached chunks. Thousands of pages build in seconds.
23
- - **Fast by default.** Every page is rendered at build time, so it appears instantly and is fully indexable by search engines. Interactivity runs on a ~5 kB runtime with fine-grained updates, and pages that need no JavaScript load none.
24
- - **Catches mistakes before the browser does.** Unknown names, missing arguments, wrong types and missing component props are compile errors with "did you mean" hints.
25
- - **Secure by default.** No `eval`, escaped output, no inline handlers, strict CSP and security headers out of the box.
26
- - **Batteries included.** Dev server with hot reload that keeps state, scoped CSS, a component library (`sinth:ui`), npm packages, SCSS, JSON imports, Google Fonts, custom elements, sitemaps and one-command Cloudflare deploys.
18
+ **[Try it in the playground](https://sinth.yannosay.com/playground)** · **[Documentation](https://sinth.yannosay.com/docs)** · **[Tutorial](https://sinth.yannosay.com/docs/getting-started/tutorial)**
27
19
 
28
20
  ## Get started
29
21
 
@@ -36,6 +28,18 @@ npm run dev
36
28
 
37
29
  Requires Node.js 18.17 or newer.
38
30
 
31
+ ## Why Sinth
32
+
33
+ - **One file, everything in it.** Markup, state, functions and scoped styles live together, without boilerplate, hooks or a virtual DOM.
34
+ - **Reactive by design.** Assign to a variable and exactly the affected parts of the page update. Arrays and objects can be changed in place.
35
+ - **Errors before the browser sees them.** Unknown names, wrong types, missing arguments and missing component props are compile errors with a code frame and a "did you mean" hint.
36
+ - **Fast pages by default.** Every page is prerendered to HTML at build time. Interactive parts run on a ~5 kB runtime with fine-grained updates; static pages ship no framework code.
37
+ - **Instant navigation.** Links between pages are prefetched and swapped in place, without full reloads, while every page stays a real, indexable HTML file.
38
+ - **Full stack.** API routes in `functions/` use the standard Fetch API, run in the dev server and deploy to Cloudflare Pages Functions unchanged.
39
+ - **Scales to large sites.** File-based and dynamic routes (`pages/blog/[slug].sinth`), layouts, shared stores, code splitting and hashed assets.
40
+ - **Works with everything else.** npm packages, TypeScript files, CSS and SCSS, JSON, Google Fonts, and components exported as standard web components for any HTML page.
41
+ - **Secure by default.** No `eval`, escaped output, no inline handlers, a strict Content Security Policy and security headers.
42
+
39
43
  ## A component
40
44
 
41
45
  ```sinth
@@ -43,8 +47,8 @@ Requires Node.js 18.17 or newer.
43
47
  import { Button, Field } from "sinth:ui"
44
48
 
45
49
  component TodoList(str title = "Todos") {
50
+ persist var obj[] todos = []
46
51
  var str draft = ""
47
- var obj[] todos = []
48
52
  computed num left = todos.filter((t) => not t.done).length
49
53
 
50
54
  function add() {
@@ -77,25 +81,40 @@ component TodoList(str title = "Todos") {
77
81
  }
78
82
  ```
79
83
 
84
+ ## An API route
85
+
86
+ ```ts
87
+ // functions/api/hello.ts
88
+ export const onRequestGet = () => Response.json({ message: "Hello from the server" });
89
+ ```
90
+
91
+ ```sinth
92
+ var str message = ""
93
+ onMount { message = (await (await fetch("/api/hello")).json()).message }
94
+ Main { Paragraph { message } }
95
+ ```
96
+
80
97
  ## Commands
81
98
 
82
99
  | Command | |
83
100
  |---|---|
84
101
  | `sinth create [name]` | Scaffold a project |
85
- | `sinth dev` | Dev server with hot reload and error overlay |
102
+ | `sinth dev` | Dev server with hot reload that keeps state, and an error overlay |
86
103
  | `sinth build` | Production build in `dist/` |
87
- | `sinth preview` | Serve the build locally |
104
+ | `sinth preview` | Serve the build and `functions/` locally |
88
105
  | `sinth deploy` | Deploy to Cloudflare Pages |
89
- | `sinth check` | Type-check without building |
106
+ | `sinth check` | Type-check without building (`--json` for tools) |
90
107
  | `sinth new page/component` | Add files |
91
108
 
92
- ## Documentation
109
+ ## Tools
93
110
 
94
- - **[Full reference (DOCS.md)](./DOCS.md)**: every feature, option and error code
95
- - [Website](https://sinth.yannosay.com)
96
- - [Changelog](./CHANGELOG.md)
97
111
  - [VS Code extension](https://github.com/Yannosay/sinth/releases/latest): download `sinth-vscode-*.vsix` from the latest release and run **Extensions: Install from VSIX**
98
- - [Sinth IDE](https://github.com/Yannosay/sinth-ide/releases/latest): the desktop editor for Sinth (Windows, macOS, Linux)
112
+ - [Sinth IDE](https://github.com/Yannosay/sinth-ide/releases/latest): a desktop editor for Sinth (Windows, macOS, Linux)
113
+ - [Playground](https://sinth.yannosay.com/playground): the real compiler, in your browser
114
+
115
+ ## Documentation
116
+
117
+ The documentation lives in [docs/](./docs) and is published at [sinth.yannosay.com/docs](https://sinth.yannosay.com/docs). See also the [changelog](./CHANGELOG.md).
99
118
 
100
119
  ## Community
101
120
 
@@ -0,0 +1,35 @@
1
+ import { Diagnostic } from "../compiler/diagnostics";
2
+ /**
3
+ * Compiles a set of in-memory files without touching the file system or a bundler, for the
4
+ * playground, editor previews and other hosts that run the compiler outside Node.js.
5
+ * Paths are POSIX-style and absolute, e.g. "/pages/index.sinth".
6
+ */
7
+ export interface CompileFilesOptions {
8
+ /** Page to compile. Default: "/pages/index.sinth". */
9
+ entry?: string;
10
+ /** Sources for `sinth:` imports, e.g. { "sinth:ui": "<source of lib/ui/index.sinth>" }. */
11
+ builtins?: Record<string, string>;
12
+ /** Rewrites bare npm imports, e.g. to a CDN. Default: https://esm.sh/<name>. */
13
+ resolvePackage?: (specifier: string) => string;
14
+ dev?: boolean;
15
+ }
16
+ export interface CompiledModule {
17
+ id: string;
18
+ js: string;
19
+ /** Module ids this module imports, in dependency order. */
20
+ deps: string[];
21
+ }
22
+ export interface CompileFilesResult {
23
+ /** Every Sinth module the page needs, dependencies before dependents. Imports use the module ids. */
24
+ modules: CompiledModule[];
25
+ entry: string;
26
+ /** Combined CSS of the page, its components and imported stylesheets. */
27
+ css: string;
28
+ /** The prerendered document, as `sinth build` would write it (without scripts and styles). */
29
+ html: string;
30
+ /** External scripts and stylesheets the page imports by URL. */
31
+ externalScripts: string[];
32
+ externalStyles: string[];
33
+ warnings: Diagnostic[];
34
+ }
35
+ export declare function compileFiles(files: Record<string, string>, options?: CompileFilesOptions): CompileFilesResult;
@@ -0,0 +1,158 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.compileFiles = compileFiles;
4
+ const codegen_1 = require("../compiler/codegen");
5
+ const diagnostics_1 = require("../compiler/diagnostics");
6
+ const html_1 = require("../compiler/html");
7
+ const parser_1 = require("../compiler/parser");
8
+ const prerender_1 = require("../compiler/prerender");
9
+ function dirname(p) {
10
+ const i = p.lastIndexOf("/");
11
+ return i <= 0 ? "/" : p.slice(0, i);
12
+ }
13
+ function normalize(p) {
14
+ const out = [];
15
+ for (const part of p.split("/")) {
16
+ if (!part || part === ".")
17
+ continue;
18
+ if (part === "..")
19
+ out.pop();
20
+ else
21
+ out.push(part);
22
+ }
23
+ return "/" + out.join("/");
24
+ }
25
+ const URL_SPEC = /^(https?:)?\/\//;
26
+ function compileFiles(files, options = {}) {
27
+ const entry = normalize(options.entry ?? "/pages/index.sinth");
28
+ const builtins = options.builtins ?? {};
29
+ const resolvePackage = options.resolvePackage ?? ((s) => `https://esm.sh/${s}`);
30
+ const parsed = new Map();
31
+ const resolved = new Map();
32
+ const compiled = new Map();
33
+ const order = [];
34
+ const styles = [];
35
+ const externalScripts = [];
36
+ const externalStyles = [];
37
+ const read = (id) => (id.startsWith("sinth:") ? builtins[id] : files[id]);
38
+ const getFile = (id) => {
39
+ const cached = parsed.get(id);
40
+ if (cached)
41
+ return cached;
42
+ const source = read(id);
43
+ if (source === undefined)
44
+ throw new diagnostics_1.SinthError("E0600", `File not found: ${id}`);
45
+ const file = (0, parser_1.parseSinth)(source, id);
46
+ file.isPage = id === entry;
47
+ parsed.set(id, file);
48
+ return file;
49
+ };
50
+ const findFile = (base, exts) => [base, ...exts.map(e => base + e), ...exts.map(e => base + "/index" + e)].find(c => read(c) !== undefined);
51
+ const resolveImports = (file) => {
52
+ const cached = resolved.get(file.path);
53
+ if (cached)
54
+ return cached;
55
+ const out = [];
56
+ for (const raw of file.imports) {
57
+ let decl = raw;
58
+ if (decl.kind === "library")
59
+ decl = { ...decl, kind: "sinth", source: "sinth:ui", sideEffect: true };
60
+ const source = decl.source;
61
+ const local = source.startsWith("/") && !source.startsWith("//") ? normalize(source) : normalize(dirname(file.path) + "/" + source);
62
+ const isLocal = source.startsWith(".") || (source.startsWith("/") && !source.startsWith("//"));
63
+ const notFound = () => { throw new diagnostics_1.SinthError("E0601", `Cannot find '${source}'`, decl.loc); };
64
+ const sinth = (id) => {
65
+ const other = getFile(id);
66
+ if (other.isPage)
67
+ throw new diagnostics_1.SinthError("E0608", `Cannot import page '${source}'; pages are entry points`, decl.loc);
68
+ return { decl: { ...decl, kind: "sinth" }, kind: "sinth", specifier: id, exports: (0, codegen_1.collectExports)(other) };
69
+ };
70
+ if (source.startsWith("sinth:")) {
71
+ if (builtins[source] === undefined)
72
+ throw new diagnostics_1.SinthError("E0605", `Unknown built-in library '${source}'`, decl.loc);
73
+ out.push(sinth(source));
74
+ continue;
75
+ }
76
+ switch (decl.kind) {
77
+ case "style": {
78
+ if (URL_SPEC.test(source)) {
79
+ externalStyles.push(source);
80
+ out.push({ decl, kind: "style", specifier: source });
81
+ break;
82
+ }
83
+ const id = findFile(local, [".css"]) ?? notFound();
84
+ styles.push(read(id) ?? "");
85
+ out.push({ decl, kind: "style", specifier: source });
86
+ break;
87
+ }
88
+ case "font":
89
+ out.push({ decl, kind: "font", specifier: source });
90
+ break;
91
+ case "json": {
92
+ const id = findFile(local, []) ?? notFound();
93
+ try {
94
+ out.push({ decl, kind: "json", specifier: id, json: JSON.parse(read(id) ?? "") });
95
+ }
96
+ catch (err) {
97
+ throw new diagnostics_1.SinthError("E0606", `Invalid JSON in '${source}': ${err.message}`, decl.loc);
98
+ }
99
+ break;
100
+ }
101
+ case "script":
102
+ if (!URL_SPEC.test(source))
103
+ throw new diagnostics_1.SinthError("E0607", `Only URL scripts can be imported here: '${source}'`, decl.loc);
104
+ externalScripts.push(source);
105
+ out.push({ decl, kind: "script", specifier: source });
106
+ break;
107
+ default: {
108
+ if (URL_SPEC.test(source)) {
109
+ out.push({ decl: { ...decl, kind: "module" }, kind: "module", specifier: source });
110
+ break;
111
+ }
112
+ if (isLocal) {
113
+ const id = findFile(local, [".sinth"]);
114
+ if (id?.endsWith(".sinth")) {
115
+ out.push(sinth(id));
116
+ break;
117
+ }
118
+ throw new diagnostics_1.SinthError("E0601", `Cannot find '${source}'`, decl.loc, "Only .sinth, .css and .json files can be imported here");
119
+ }
120
+ out.push({ decl: { ...decl, kind: "module" }, kind: "module", specifier: resolvePackage(source) });
121
+ }
122
+ }
123
+ }
124
+ resolved.set(file.path, out);
125
+ return out;
126
+ };
127
+ const compile = (id, stack) => {
128
+ const cached = compiled.get(id);
129
+ if (cached)
130
+ return cached;
131
+ if (stack.includes(id))
132
+ throw new diagnostics_1.SinthError("E0609", `Circular import: ${[...stack.slice(stack.indexOf(id)), id].join(" -> ")}`);
133
+ const file = getFile(id);
134
+ const imports = resolveImports(file);
135
+ for (const imp of imports)
136
+ if (imp.kind === "sinth")
137
+ compile(imp.specifier, [...stack, id]);
138
+ const out = (0, codegen_1.compileModule)(file, imports, { runtime: "sinth-runtime", dev: !!options.dev, persistPrefix: "sinth:" + id.replace(/^\//, "").replace(/\.sinth$/, "") });
139
+ compiled.set(id, out);
140
+ order.push(id);
141
+ return out;
142
+ };
143
+ compile(entry, []);
144
+ const host = { getFile, getImports: resolveImports };
145
+ const pre = (0, prerender_1.prerenderPage)(getFile(entry), host);
146
+ const head = (0, html_1.buildHead)(pre.meta.map(m => (m.known ? m : { ...m, known: true, value: undefined })), v => v);
147
+ const modules = order.map(id => {
148
+ const out = compiled.get(id);
149
+ const deps = resolveImports(getFile(id)).filter(i => i.kind === "sinth").map(i => i.specifier);
150
+ return { id, js: out.js.replace(/^import "sinth-css:[^"]*";\n/gm, ""), deps };
151
+ });
152
+ const css = [...styles, ...order.map(id => compiled.get(id)?.css ?? "").filter(Boolean)].join("\n\n");
153
+ const warnings = order.flatMap(id => compiled.get(id)?.diagnostics.warnings ?? []);
154
+ return {
155
+ modules, entry, css, externalScripts, externalStyles, warnings,
156
+ html: (0, html_1.renderDocument)(head, pre.html, { styles: [], scripts: [], preloads: [], inlineHead: [] }),
157
+ };
158
+ }