rosetack 0.1.0 → 0.1.1

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 (49) hide show
  1. package/dist-cli/compiler.mjs +2302 -0
  2. package/dist-cli/edge.mjs +297 -0
  3. package/dist-cli/rosetack.mjs +3411 -0
  4. package/dist-cli/runtime.mjs +619 -0
  5. package/dist-cli/test.mjs +2696 -0
  6. package/pack.mjs +49 -0
  7. package/package.json +25 -7
  8. package/src/FRAMEWORK_VERSION +1 -1
  9. package/src/cli/edge.ts +58 -23
  10. package/src/cli/index.ts +521 -65
  11. package/src/cli/shell.ts +75 -22
  12. package/src/cli/test.ts +400 -0
  13. package/src/compiler/index.ts +1277 -191
  14. package/src/runtime/index.ts +356 -65
  15. package/src/types/rosetack.d.ts +142 -0
  16. package/.github/workflows/ci.yml +0 -72
  17. package/.github/workflows/release.yml +0 -122
  18. package/benchmark.ts +0 -227
  19. package/example/public/favicon.ico +0 -0
  20. package/example/public/logo.svg +0 -148
  21. package/example/public/rose-mark-black.png +0 -0
  22. package/example/public/rose-mark.png +0 -0
  23. package/example/public/rose-mono.png +0 -0
  24. package/example/rosetack.config.js +0 -10
  25. package/example/src/locales/en.json +0 -8
  26. package/example/src/locales/zh.json +0 -8
  27. package/example/src/pages/404.rose +0 -15
  28. package/example/src/pages/500.rose +0 -10
  29. package/example/src/pages/[lang]/about.rose +0 -40
  30. package/example/src/pages/_layout.rose +0 -33
  31. package/example/src/pages/_middleware.rose +0 -37
  32. package/example/src/pages/about.rose +0 -67
  33. package/example/src/pages/admin.rose +0 -27
  34. package/example/src/pages/api/hello.rose +0 -19
  35. package/example/src/pages/api/login.rose +0 -55
  36. package/example/src/pages/api/posts.rose +0 -80
  37. package/example/src/pages/api/secret.rose +0 -14
  38. package/example/src/pages/blog/[id].rose +0 -25
  39. package/example/src/pages/broken.rose +0 -16
  40. package/example/src/pages/fresh.rose +0 -22
  41. package/example/src/pages/garden.rose +0 -27
  42. package/example/src/pages/index.rose +0 -84
  43. package/example/src/pages/sign.rose +0 -45
  44. package/example/src/pages/thorn.rose +0 -23
  45. package/example/src/pages/vault.rose +0 -14
  46. package/go.mod +0 -3
  47. package/main.go +0 -470
  48. package/tools/release-notes.mjs +0 -113
  49. package/tsconfig.json +0 -17
@@ -0,0 +1,142 @@
1
+ /**
2
+ * rosetack - the globals a `.rose` <script> block can call.
3
+ *
4
+ * This file is the framework's public script surface, declared once so an
5
+ * editor and `rosetack check` (which runs the project's own TypeScript over
6
+ * every extracted script block) both see the same truth the runtime
7
+ * implements. The signatures mirror src/runtime/index.ts exactly - when one
8
+ * changes, this file changes with it.
9
+ *
10
+ * It ships with the package. A project picks it up with a `rosetack-env.d.ts`
11
+ * holding `/// <reference types="rosetack" />` (what `rosetack new` writes for
12
+ * you); `rosetack check` references it by path, so it works in a source
13
+ * checkout too. No imports, no exports: every declaration here is global,
14
+ * because that is exactly how a `.rose` script sees them.
15
+ */
16
+ /// <reference lib="dom" />
17
+
18
+ /**
19
+ * A reactive getter. The compiler turns `let count = $state(0)` into a
20
+ * getter/setter pair named after your declaration, so in a `.rose` script
21
+ * the name you wrote IS this function - `count()` reads it, and
22
+ * `$setState('count', v)` (or the generated setter) writes it.
23
+ */
24
+ type Getter<T> = () => T;
25
+
26
+ /** A store shared by every request in this process (and, with a transport, every worker). */
27
+ interface Store<T> {
28
+ get(): T;
29
+ set(v: T): void;
30
+ update(fn: (v: T) => T): void;
31
+ }
32
+
33
+ /** Declare reactive state. Server-rendered into the document, resumed by the client with zero hydration. */
34
+ declare function $state<T>(initial: T): Getter<T>;
35
+
36
+ /** Write reactive state by key - the same write the generated setter performs. */
37
+ declare function $setState<T>(key: string, value: T): void;
38
+
39
+ /**
40
+ * Server data. The body runs on the server per request (and ships to the
41
+ * client, where it re-runs on a client-side navigation), the result lands in
42
+ * the same state map as `$state` - so `post()` is a getter like any other.
43
+ * The await is the compiler's, not yours.
44
+ */
45
+ declare function $data<T>(fn: () => T | Promise<T>): Getter<T>;
46
+
47
+ /** The per-request bag filled by `pages/_middleware.rose` (auth, db, cache). */
48
+ declare function getContext<T = Record<string, unknown>>(): T;
49
+
50
+ /**
51
+ * Translate a key from src/locales/<lang>.json.
52
+ *
53
+ * Values are either plain strings with `{name}` holes or ICU MessageFormat:
54
+ * `{count, plural, one {# item} other {# items}}`, `{n, selectordinal, ...}`,
55
+ * `{who, select, ...}` - so `vars` carries numbers for counts and strings for
56
+ * names and select arms. A missing key renders the key itself.
57
+ */
58
+ declare function $t(key: string, vars?: Record<string, string | number>): string;
59
+
60
+ /** 'rtl' for a right-to-left locale (ar, he, fa, ur, ...), 'ltr' otherwise. */
61
+ declare function localeDir(lang: string): string;
62
+
63
+ /**
64
+ * Resolve once a locale's dictionary is present: immediately for a baked one,
65
+ * after one fetch of /locales/<lang>.json for a runtime pack (a locale the
66
+ * build left out of the bundle via i18n.preload). The client router awaits
67
+ * this on every navigation, so a page rarely needs to call it directly.
68
+ */
69
+ declare function ensureLocale(lang: string): Promise<void>;
70
+
71
+ /** Merge a dictionary that arrived at runtime (a fetched pack, or your own import()). */
72
+ declare function loadLocale(lang: string, dict: Record<string, string>): void;
73
+
74
+ /** A named, process-wide store. Values must be JSON-serializable. */
75
+ declare function $store<T>(name: string, initial: T): Store<T>;
76
+
77
+ /** Parse the request's cookies (server) or this document's (client). */
78
+ declare function $cookies(request?: Request): Record<string, string>;
79
+
80
+ /** Build a Set-Cookie value with the safe defaults: HttpOnly, SameSite=Lax, Path=/, 7 days. */
81
+ declare function $sessionCookie(
82
+ name: string,
83
+ value: string,
84
+ opts?: { path?: string; maxAge?: number; sameSite?: 'Strict' | 'Lax' | 'None'; secure?: boolean; httpOnly?: boolean }
85
+ ): string;
86
+
87
+ /** Run once after the client has adopted the server's DOM. */
88
+ declare function onMount(fn: () => void): void;
89
+
90
+ /** Register a teardown for the next navigation. */
91
+ declare function onCleanup(fn: () => void): void;
92
+
93
+ /** Re-render the current route in place - `$data` re-runs, zero requests. */
94
+ declare function refresh(): Promise<void>;
95
+
96
+ /** HTML-escape a value into a string (the same escape the template markers use). */
97
+ declare function esc(v: unknown): string;
98
+
99
+ /** Call a server action by name; the response is adopted in place. */
100
+ declare function $action(name: string, e?: Event): Promise<void>;
101
+
102
+ /**
103
+ * The standardized failure a server action throws for a BUSINESS error (bad
104
+ * input, not signed in, a duplicate) - as opposed to a bug, which still goes
105
+ * to the 500 page. `code` becomes the response status; `field` names the
106
+ * offending form input.
107
+ */
108
+ declare class ActionError extends Error {
109
+ code: number;
110
+ field?: string;
111
+ constructor(message: string, code?: number, field?: string);
112
+ }
113
+
114
+ /** What the dispatch seeds into state when an action fails (what `$actionError()` returns). */
115
+ interface ActionErrorInfo {
116
+ action: string;
117
+ message: string;
118
+ code: number;
119
+ field?: string;
120
+ }
121
+
122
+ /**
123
+ * The failure of the action that produced the response being rendered, or
124
+ * null. Render it (`{#if $actionError()}<p>{$actionError().message}</p>{/if}`)
125
+ * or contain it with a `{#boundary}` around the action's widget.
126
+ */
127
+ declare function $actionError(): ActionErrorInfo | null;
128
+
129
+ /**
130
+ * An incremental patch: an action's return value may map a state key to an
131
+ * OPERATION instead of a whole replacement, so growing a large list costs one
132
+ * row rather than a second copy of the list.
133
+ */
134
+ declare function $append(value: unknown): unknown;
135
+ declare function $prepend(value: unknown): unknown;
136
+ declare function $merge(value: Record<string, unknown>): unknown;
137
+
138
+ /** Whether a state key already holds a value (what `$data` checks before fetching). */
139
+ declare function hasState(key: string): boolean;
140
+
141
+ /** The best dictionary for an Accept-Language header (null when none matches). */
142
+ declare function bestLocale(header: string | null | undefined): string | null;
@@ -1,72 +0,0 @@
1
- name: CI
2
-
3
- on:
4
- push:
5
- branches: [main]
6
- pull_request:
7
- workflow_dispatch:
8
-
9
- permissions:
10
- contents: read
11
-
12
- concurrency:
13
- group: ci-${{ github.workflow }}-${{ github.ref }}
14
- cancel-in-progress: true
15
-
16
- # One gate, invoked the same way at every revision this repository has ever shipped. The
17
- # suites that exist at that revision run; the ones that do not are not pretended to run.
18
- jobs:
19
- suite:
20
- name: suite
21
- runs-on: ubuntu-latest
22
- timeout-minutes: 60
23
- steps:
24
- - uses: actions/checkout@v4
25
-
26
- - uses: actions/setup-node@v4
27
- with:
28
- node-version: 22
29
-
30
- - name: Install dependencies
31
- run: npm install --no-audit --no-fund
32
-
33
- - name: Run the suites this revision ships
34
- shell: bash
35
- run: |
36
- set -euo pipefail
37
- if [ -f tests/test-all.mjs ]; then
38
- echo "runner: tests/test-all.mjs"
39
- node tests/test-all.mjs
40
- exit 0
41
- fi
42
- if [ -d tests ] && node -e "const s=require('./package.json').scripts||{};process.exit(s.test?0:1)"; then
43
- echo "runner: npm test"
44
- npm test
45
- exit 0
46
- fi
47
- echo "no suite entry point at this revision"
48
-
49
- - name: Platform exports
50
- if: ${{ hashFiles('tests/test-platforms.ts') != '' }}
51
- shell: bash
52
- run: |
53
- set -euo pipefail
54
- for group in miniprogram mobile desktop rust webview deploy; do
55
- echo "export group: $group"
56
- npx tsx tests/test-platforms.ts "$group"
57
- done
58
-
59
- - uses: actions/setup-go@v5
60
- if: ${{ hashFiles('main.go') != '' }}
61
- with:
62
- go-version: '1.22'
63
- cache: false
64
-
65
- - name: Build the single binary
66
- if: ${{ hashFiles('main.go') != '' }}
67
- continue-on-error: true
68
- shell: bash
69
- run: |
70
- set -euo pipefail
71
- npx tsx src/cli/index.ts build example
72
- go build -o rosetack-server .
@@ -1,122 +0,0 @@
1
- name: Release
2
-
3
- # A tag is the only thing that publishes. No branch push, no schedule, no side effect of a
4
- # merge: the release starts when the maintainer types `git tag` and pushes it …
5
- on:
6
- push:
7
- tags: ['v*']
8
- workflow_dispatch:
9
- inputs:
10
- tag:
11
- description: 'existing tag to publish (for example v0.1.0)'
12
- required: true
13
- type: string
14
-
15
- permissions:
16
- contents: write
17
- id-token: write
18
-
19
- concurrency:
20
- group: release-${{ github.event.inputs.tag || github.ref_name }}
21
- cancel-in-progress: false
22
-
23
- jobs:
24
- publish:
25
- runs-on: ubuntu-latest
26
- timeout-minutes: 45
27
- steps:
28
- - uses: actions/checkout@v4
29
- with:
30
- fetch-depth: 0
31
- ref: ${{ github.event.inputs.tag || github.ref }}
32
-
33
- - uses: actions/setup-node@v4
34
- with:
35
- node-version: 22
36
-
37
- # Trusted publishing needs npm >= 11.5.1; a repository token does not care which npm
38
- # runs it, so the upgrade is best effort and never blocks a token-based release.
39
- - name: Upgrade npm for trusted publishing
40
- continue-on-error: true
41
- run: npm install -g npm@11
42
-
43
- # A tag that disagrees with package.json stages a version nobody asked for; a tag
44
- # that disagrees with the package name publishes somebody else's package.
45
- - name: Check the tag against package.json
46
- shell: bash
47
- run: |
48
- set -euo pipefail
49
- tag="${{ github.event.inputs.tag || github.ref_name }}"
50
- name="$(node -p "require('./package.json').name")"
51
- version="$(node -p "require('./package.json').version")"
52
- test "$name" = "rosetack" || { echo "package.json name is $name, not rosetack"; exit 1; }
53
- test "v$version" = "$tag" || { echo "tag $tag but package.json says $version"; exit 1; }
54
- echo "publishing $name@$version from $tag"
55
-
56
- - name: Install dependencies
57
- run: npm install --no-audit --no-fund
58
-
59
- # The tarball is built explicitly, because every revision below 0.1.2
60
- # predates the `pack` script and must still publish what it has.
61
- - name: Build the published files
62
- shell: bash
63
- run: |
64
- set -euo pipefail
65
- if node -e "process.exit((require('./package.json').scripts||{}).pack?0:1)"; then
66
- npm run pack
67
- elif node -e "process.exit((require('./package.json').scripts||{}).prepack?0:1)"; then
68
- npm run prepack
69
- else
70
- echo "this revision ships without a pack step"
71
- fi
72
-
73
- # Staged publishing: the tarball lands in npm's staging area and only becomes
74
- # installable when a maintainer approves it with 2FA - nothing goes live from CI
75
- # alone.
76
- - name: Stage the package on npm
77
- shell: bash
78
- env:
79
- NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
80
- run: |
81
- set -euo pipefail
82
- version="$(node -p "require('./package.json').version")"
83
- if npm view "rosetack@$version" version >/dev/null 2>&1; then
84
- echo "rosetack@$version is already live on npm - nothing to stage"
85
- exit 0
86
- fi
87
- if npm stage list rosetack 2>/dev/null | grep -F "$version" >/dev/null 2>&1; then
88
- echo "rosetack@$version is already staged - approve or reject it first"
89
- exit 0
90
- fi
91
- if [ -n "${NODE_AUTH_TOKEN:-}" ]; then
92
- echo "auth: repository token"
93
- npm stage publish --tag stage --access public --ignore-scripts
94
- else
95
- echo "auth: OIDC trusted publishing"
96
- npm stage publish --tag stage --access public --ignore-scripts --provenance
97
- fi
98
-
99
- # The release body is generated from the tag's commit range, not from GitHub's
100
- # `--generate-notes`: one bullet per commit …
101
- - name: Generate the release body
102
- shell: bash
103
- run: |
104
- set -euo pipefail
105
- tag="${{ github.event.inputs.tag || github.ref_name }}"
106
- node tools/release-notes.mjs "$tag" > release-notes.md
107
- echo "notes: $(wc -c < release-notes.md) bytes, $(grep -c '^- ' release-notes.md || true) entries"
108
-
109
- # Re-runs are the normal case (a tag pushed twice, a manual dispatch): an
110
- # existing release is edited instead of failing the job.
111
- - name: Attach a GitHub release
112
- continue-on-error: true
113
- env:
114
- GH_TOKEN: ${{ github.token }}
115
- shell: bash
116
- run: |
117
- tag="${{ github.event.inputs.tag || github.ref_name }}"
118
- if gh release view "$tag" >/dev/null 2>&1; then
119
- gh release edit "$tag" --title "rosetack $tag" --notes-file release-notes.md
120
- exit 0
121
- fi
122
- gh release create "$tag" --title "rosetack $tag" --notes-file release-notes.md --prerelease
package/benchmark.ts DELETED
@@ -1,227 +0,0 @@
1
- /**
2
- * rosetack Performance Benchmark
3
- * Measures: SSR render time, SSR throughput (renders/sec), client bundle
4
- * size (raw + gzip), network requests, and live HTTP throughput of the Go
5
- * single binary (requires `go` on PATH - the binary is built and spawned
6
- * here, so the number is measured every run, never quoted).
7
- */
8
-
9
- import { readFileSync, statSync } from 'fs';
10
- import { join } from 'path';
11
- import { gzipSync, brotliCompressSync } from 'zlib';
12
-
13
- const ROOT = join(process.cwd(), 'dist');
14
- const START = Date.now();
15
-
16
- // 1. Measure SSR render time
17
- import { renderPage, matchRoute } from './dist/server.js';
18
-
19
- const ssrStart = Date.now();
20
- const page = await renderPage('/');
21
- const ssrTime = Date.now() - ssrStart;
22
-
23
- console.log(`\n🌹 rosetack Performance Benchmark`);
24
- console.log('===============================');
25
- console.log(`SSR render time: ${ssrTime}ms`);
26
- // Buffer.byteLength: page.html is a string, .length would count CHARACTERS
27
- console.log(`HTML length: ${Buffer.byteLength(page.html, 'utf-8')} bytes`);
28
-
29
- // 1b. SSR throughput: renders/sec per route (warm up first for JIT fairness)
30
- async function throughput(pathname: string, n: number): Promise<number> {
31
- for (let i = 0; i < 100; i++) await renderPage(pathname); // warm-up
32
- const t0 = performance.now();
33
- for (let i = 0; i < n; i++) await renderPage(pathname);
34
- return n / ((performance.now() - t0) / 1000);
35
- }
36
- const N = 2000;
37
- const rpsHome = await throughput('/', N);
38
- const rpsAbout = await throughput('/about', N);
39
- const rpsDynamic = await throughput('/blog/1', N);
40
- console.log(`\nSSR throughput (single core, after warm-up):`);
41
- console.log(` / (static): ${rpsHome.toFixed(0)} renders/sec`);
42
- console.log(` /about ($data): ${rpsAbout.toFixed(0)} renders/sec`);
43
- console.log(` /blog/:id (param): ${rpsDynamic.toFixed(0)} renders/sec`);
44
-
45
- // 2. Measure client bundle size (raw + gzip)
46
- const clientRaw = statSync(join(ROOT, 'client.js')).size;
47
- const clientGzip = gzipSync(readFileSync(join(ROOT, 'client.js'))).length;
48
- const ssrSize = statSync(join(ROOT, 'server.js')).size;
49
-
50
- console.log(`\nBundle sizes:`);
51
- console.log(` client.js: ${(clientRaw / 1024).toFixed(2)} KB raw / ${(clientGzip / 1024).toFixed(2)} KB gzip`);
52
- console.log(` server.js: ${(ssrSize / 1024).toFixed(2)} KB`);
53
-
54
- // 3. Count network requests for a full page load.
55
- // The client bundle is inlined into the HTML shell, so the document itself is
56
- // the only request - count any external asset references to prove it.
57
- import { getHtmlShell } from './src/cli/shell.js';
58
-
59
- const shell = getHtmlShell(page.html, page.state, page.head);
60
- const externalRefs = [...shell.matchAll(/<(?:script|link|img)[^>]*(?:src|href)="([^"]+)"/g)]
61
- .map((m) => m[1])
62
- .filter((u) => !u.startsWith('#') && !u.startsWith('data:'));
63
- const totalRequests = 1 + externalRefs.length;
64
-
65
- console.log(`\nNetwork requests for full page load:`);
66
- console.log(` Total: ${totalRequests} (HTML document only - client bundle AND all component styles inlined)`);
67
- if (externalRefs.length > 0) console.log(` external refs: ${externalRefs.join(', ')}`);
68
-
69
- // 4. Framework floor: smallest possible app (fair vs SvelteKit's runtime core)
70
- import * as fs from 'fs';
71
- import * as os from 'os';
72
- import * as path from 'path';
73
- import { buildProject } from './src/compiler/index.js';
74
-
75
- const FLOOR = path.join(os.tmpdir(), 'rosetack-floor');
76
- try {
77
- fs.rmSync(FLOOR, { recursive: true, force: true });
78
- fs.mkdirSync(path.join(FLOOR, 'src'), { recursive: true });
79
- fs.mkdirSync(path.join(FLOOR, 'example', 'src', 'pages'), { recursive: true });
80
- fs.cpSync(path.join(process.cwd(), 'src', 'runtime'), path.join(FLOOR, 'src', 'runtime'), { recursive: true });
81
- fs.writeFileSync(
82
- path.join(FLOOR, 'example', 'src', 'pages', 'index.rose'),
83
- `<script>\n let count = $state(0);\n function inc() { $setState('count', count() + 1); }\n</script>\n\n<div>\n <h1>hi</h1>\n <p>{count()}</p>\n <button on:click={inc}>+1</button>\n</div>\n`
84
- );
85
- await buildProject(path.join(FLOOR, 'example'), path.join(FLOOR, 'dist'));
86
- const floorRaw = fs.statSync(path.join(FLOOR, 'dist', 'client.js')).size;
87
- const floorGzip = gzipSync(fs.readFileSync(path.join(FLOOR, 'dist', 'client.js'))).length;
88
- console.log(`\nFramework floor (1 page, 1 state, 1 event - no layouts, no $data):`);
89
- console.log(` client.js: ${(floorRaw / 1024).toFixed(2)} KB raw / ${(floorGzip / 1024).toFixed(2)} KB gzip`);
90
- console.log(` (this is the fair comparison against SvelteKit's ~2 KB runtime core)`);
91
- } finally {
92
- fs.rmSync(FLOOR, { recursive: true, force: true });
93
- }
94
-
95
- // 5. Prerendered static routes: served from disk, zero server work
96
- const staticRoutes = ['/', '/about', '/blog/1', '/blog/2', '/sign', '/fresh', '/garden', '/thorn', '/en/about', '/zh/about'];
97
- const prerendered = staticRoutes.filter((r) => fs.existsSync(path.join(ROOT, r === '/' ? 'index.html' : `${r.slice(1)}/index.html`)));
98
- console.log(`\nPrerendered static routes (served from disk, zero server work):`);
99
- prerendered.forEach((r) => {
100
- const file = path.join(ROOT, r === '/' ? 'index.html' : `${r.slice(1)}/index.html`);
101
- const html = fs.readFileSync(file);
102
- // self-contained = the document requests nothing external. A csr = false
103
- // route (innovation #25) passes trivially: it ships no script at all.
104
- const ok = !/<script[^>]*src="\//.test(html.toString('utf-8'));
105
- // Buffer.length = bytes on the wire (a utf-8 read would count CHARACTERS:
106
- // the ⟦m:K⟧ markers, the 🌹 and the em dashes are multi-byte)
107
- console.log(` ${r} -> ${path.relative(ROOT, file)} (${html.length} bytes, self-contained: ${ok})`);
108
- });
109
- console.log(` dynamic routes outside params (e.g. /blog/3): streamed SSR on demand (shell flushes first)`);
110
- // the zero-JS routes: no bundle, no state script, no hydration - a content page that runs
111
- // no JavaScript at all.
112
- const gardenFile = path.join(ROOT, 'garden', 'index.html');
113
- const gardenBytes = fs.readFileSync(gardenFile);
114
- console.log(` /garden (csr = false): ${gardenBytes.length} bytes raw / ${(gzipSync(gardenBytes).length / 1024).toFixed(2)} KB gzip, ZERO JavaScript`);
115
- // the per-route-header route (export const headers = {...}, innovation #26):
116
- // same zero-JS document, now answering default-src 'none' + x-robots-tag
117
- const thornFile = path.join(ROOT, 'thorn', 'index.html');
118
- const thornBytes = fs.readFileSync(thornFile);
119
- console.log(` /thorn (csr = false + headers): ${thornBytes.length} bytes raw / ${(gzipSync(thornBytes).length / 1024).toFixed(2)} KB gzip, ZERO JavaScript, strict per-route CSP`);
120
- // the localized routes (innovation #27): one baked file per dictionary, so
121
- // the Go binary serves them as plain static files with zero Node
122
- const zhFile = path.join(ROOT, 'zh', 'about', 'index.html');
123
- const zhBytes = fs.readFileSync(zhFile);
124
- console.log(` /zh/about (i18n): ${zhBytes.length} bytes raw / ${(gzipSync(zhBytes).length / 1024).toFixed(2)} KB gzip, served from disk, ZERO extra requests`);
125
- // the auto zero-JS content routes (innovation #29): the compiler found nothing needing the
126
- // client, so these documents ship no runtime - the developer exported nothing
127
- const blog1File = path.join(ROOT, 'blog', '1', 'index.html');
128
- const blog1Bytes = fs.readFileSync(blog1File);
129
- console.log(` /blog/1 (auto zero-JS): ${blog1Bytes.length} bytes raw / ${(gzipSync(blog1Bytes).length / 1024).toFixed(2)} KB gzip, ZERO JavaScript - no export, no runtime, no state script`);
130
- const freshFile = path.join(ROOT, 'fresh', 'index.html');
131
- const freshBytes = fs.readFileSync(freshFile);
132
- console.log(` /fresh (auto zero-JS): ${freshBytes.length} bytes raw / ${(gzipSync(freshBytes).length / 1024).toFixed(2)} KB gzip, ZERO JavaScript`);
133
-
134
- // 6. Route matching sanity check
135
- const routeChecks: Array<[string, boolean]> = [
136
- ['/', matchRoute('/', '/')],
137
- ['/about', matchRoute('/about', '/about')],
138
- ['/blog/:id', matchRoute('/blog/:id', '/blog/1')],
139
- ['/blog/:id', !matchRoute('/blog/:id', '/about')],
140
- ];
141
- const routeOk = routeChecks.every(([, ok]) => ok);
142
-
143
- console.log(`\nRoute matching: ${routeOk ? 'OK' : 'FAIL'}`);
144
-
145
- // 7. Comparison - MEASURED, not quoted (2026-09-20, this machine, Node v22).
146
- // Same minimal app (heading + counter + button) built with each framework's
147
- // current release; total transfer = gzip(html) + gzip(all JS the page loads).
148
- console.log(`\nComparison (measured 2026-09-20, same machine, same minimal app):`);
149
- console.log(` Next.js 15.5: 8 requests, 142.35 KB gzip total (140.74 KB JS)`);
150
- console.log(` SvelteKit 2.70: 10 requests, 31.14 KB gzip total ( 30.65 KB JS)`);
151
- console.log(` Qwik City 1.20: 5 requests, 24.23 KB gzip total ( 23.53 KB JS)`);
152
- console.log(` SolidStart v2: 6 requests, 24.73 KB gzip total ( 20.98 KB JS + 3.16 KB CSS)`);
153
- console.log(` Go + HTMX 2.0.10: 2 requests, 16.42 KB gzip total ( 16.20 KB JS - page not interactive until 2nd response)`);
154
- console.log(` Django 5.2 + HTMX: 2 requests, 16.42 KB gzip total ( 16.20 KB JS - page not interactive until 2nd response)`);
155
- console.log(` rosetack: ${totalRequests} request, ${(gzipSync(Buffer.from(shell)).length / 1024).toFixed(2)} KB gzip total (${(clientGzip / 1024).toFixed(2)} KB JS, ALL routes, 11-route demo)`);
156
- console.log(` rosetack zero-JS: ${totalRequests} request, ${(gzipSync(gardenBytes).length / 1024).toFixed(2)} KB gzip total, 0.00 KB JS (a csr = false content page - no runtime, no state script, no hydration)`);
157
- console.log(` rosetack auto 0-JS: ${totalRequests} request, ${(gzipSync(blog1Bytes).length / 1024).toFixed(2)} KB gzip total, 0.00 KB JS (a content route the COMPILER decided needs no client - no export at all)`);
158
- console.log(` rosetack (brotli): ${totalRequests} request, ${(brotliCompressSync(Buffer.from(shell)).length / 1024).toFixed(2)} KB brotli total - the Node server negotiates br > gzip on the wire, like the Go binary`);
159
- console.log(` (rosetack demo carries 11 routes + nested layouts + link prefetch + per-route <head> blocks + progressive-enhancement forms + server actions from any event + scoped component styles + client-side refresh + api routes + component lifecycle + middleware + ISR revalidation + error boundaries + zero-JS content routes + per-route response headers with a strict CSP hashed over the exact inlined bytes + localized i18n routes and still delivers ~${(16.42 * 1024 / gzipSync(Buffer.from(shell)).length).toFixed(1)}x fewer bytes than the smallest competitor)`);
160
- console.log(` (the bootstrap - navigation, prefetch listeners, view transitions, form interception - is minified once at module load and inlined into every document)`);
161
-
162
- // 8. HTTP page-load throughput - MEASURED LIVE against the Go single binary
163
- // (this benchmark builds and spawns it; requires `go` on PATH). Same
164
- // harness shape as the reference rows: 8 parallel keep-alive connections,
165
- // 8000 GETs, a browser's Accept-Encoding (br, gzip). The htmx/Django rows
166
- // are documented history - those reference apps are not part of this
167
- // repo; they were measured on this machine on 2026-09-21 with this same
168
- // harness. The rosetack number is never stale: it is re-measured every run.
169
- import { spawn, execSync } from 'child_process';
170
- import { request, Agent } from 'http';
171
-
172
- const GO_PORT = 8124;
173
- const goBin = process.platform === 'win32' ? 'rosetack-server-go.exe' : 'rosetack-server-go';
174
- execSync(`go build -o ${goBin} .`, { stdio: 'ignore' });
175
- const goProc = spawn(join(process.cwd(), goBin), [], {
176
- env: { ...process.env, PORT: String(GO_PORT) },
177
- stdio: 'ignore'
178
- });
179
- const goBase = `http://localhost:${GO_PORT}`;
180
- const goAgent = new Agent({ keepAlive: true, maxSockets: 8 });
181
- const wireGet = (pathname: string) =>
182
- new Promise<number>((resolve, reject) => {
183
- const req = request(
184
- { host: 'localhost', port: GO_PORT, path: pathname, agent: goAgent, headers: { 'accept-encoding': 'br, gzip' } },
185
- (res) => {
186
- let bytes = 0;
187
- res.on('data', (c: Buffer) => { bytes += c.length; });
188
- res.on('end', () => resolve(bytes));
189
- }
190
- );
191
- req.on('error', reject);
192
- req.end();
193
- });
194
- try {
195
- let up = false;
196
- for (let i = 0; i < 100 && !up; i++) {
197
- try { await fetch(goBase + '/'); up = true; } catch { await new Promise((r) => setTimeout(r, 100)); }
198
- }
199
- if (!up) throw new Error('the Go single-binary server did not start');
200
- const hammer = async (pathname: string, total: number) => {
201
- const t0 = performance.now();
202
- // each worker sums its own bytes: a shared `bytes += await ...` across
203
- // concurrent workers loses updates (read-modify-write is not atomic)
204
- const per = await Promise.all(Array.from({ length: 8 }, async () => {
205
- let bytes = 0;
206
- for (let i = 0; i < total / 8; i++) bytes += await wireGet(pathname);
207
- return bytes;
208
- }));
209
- return { rps: total / ((performance.now() - t0) / 1000), bytes: per.reduce((a, b) => a + b, 0) / total };
210
- };
211
- const goPage = await hammer('/', 8000);
212
- const goAsset = await hammer('/styles.css', 8000);
213
- console.log(`\nHTTP throughput (8 parallel keep-alive, 8000 GETs each, this machine):`);
214
- console.log(` rosetack Go binary: ${goPage.rps.toFixed(0)} req/sec (${(goPage.bytes / 1024).toFixed(2)} KB brotli per page - the self-contained app, precompressed at build time)`);
215
- console.log(` same binary, asset: ${goAsset.rps.toFixed(0)} req/sec (${(goAsset.bytes / 1024).toFixed(2)} KB brotli - the bare-Go ceiling for this server)`);
216
- console.log(` Go + HTMX: 6653 req/sec (311 B shell; interactive only after a 2nd 16.2 KB request)`);
217
- console.log(` Django + HTMX: 611 req/sec (1.64 ms/page, DEBUG dev server)`);
218
- } finally {
219
- goProc.kill();
220
- goAgent.destroy();
221
- }
222
-
223
- const totalTime = Date.now() - START;
224
- console.log(`\nBenchmark completed in ${totalTime}ms`);
225
- console.log('===============================\n');
226
-
227
- if (!routeOk) process.exit(1);
Binary file