glashjs 0.1.0 → 0.2.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.
package/README.md CHANGED
@@ -77,7 +77,22 @@ glash dev # dev server: routing + SSR + API, live route reload
77
77
  glash serve # production server over routes/ + built assets (Brotli-negotiated)
78
78
  ```
79
79
 
80
- Every response carries the secure-by-default headers; static files are served from the build with Brotli negotiation. **Honest scope:** this is real SSR of HTML (render functions) — React/JSX components with client hydration, layouts/nested routing, client-JS bundling, and HMR are the next milestones (below).
80
+ Every response carries the secure-by-default headers; static files are served from the build with Brotli negotiation.
81
+
82
+ ### JSX components + client hydration (new in 0.2)
83
+ Author pages as **JSX components**, server-render them, and **hydrate** in the browser so hooks work — real interactivity, the Next-style model. Built on **Preact** (React-compatible) + **esbuild**, added as *optional peers* (`npm i preact preact-render-to-string esbuild`); glashjs core stays zero-dep.
84
+
85
+ ```jsx
86
+ // routes/counter.jsx — SSR + hydrated, the button is interactive
87
+ import { useState } from 'preact/hooks';
88
+ export function getServerData(ctx) { return { start: Number(ctx.query.start || 0) }; } // server props
89
+ export default function Counter({ start = 0 }) {
90
+ const [n, setN] = useState(start);
91
+ return <button onClick={() => setN(n + 1)}>count is {n}</button>;
92
+ }
93
+ ```
94
+
95
+ Hydration is **CSP-safe**: server props ride in a non-executed `<script type="application/json">` and the hydration bundle is an external `'self'` module with a per-request **nonce** — so the strict CSP stays intact (no `'unsafe-inline'`). **Honest scope:** uses Preact (React-compatible via `preact/compat`), not React itself; nested layouts, HMR, and streaming are still ahead.
81
96
 
82
97
  ## Usage
83
98
 
@@ -126,8 +141,9 @@ animatedFavicon: true, // bundled animated glash mark (d
126
141
  - [x] Server-side rendering (XSS-safe `html` templates) + full-document runtime
127
142
  - [x] API routes (per-method handlers, JSON body parsing, typed `json()` responses)
128
143
  - [x] Dev/prod server with live route reload + Brotli-negotiated static serving
129
- - [ ] React/JSX components + client hydration, nested layouts, streaming SSR
130
- - [ ] Client-JS bundling + HMR (on esbuild/Vite)
144
+ - [x] JSX components + client-side hydration (Preact + esbuild) — CSP-safe with nonces
145
+ - [x] Client-JS bundling (esbuild) per route
146
+ - [ ] Nested layouts, streaming SSR, HMR (fast refresh)
131
147
  - [ ] `<Image>` / `<Video>` components that emit `<picture>`/`<source>` from the manifest
132
148
  - [ ] Edge adapter for the glashdb Worker (serve `.br`/`.avif` by `Accept`)
133
149
  - [ ] `glash deploy` → glashdb hosting in one command
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "glashjs",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "glashjs — a web framework with file-based routing, SSR, API routes, a best-in-class asset optimizer, offline PWA layer, animated favicon, and secure-by-default headers. Zero dependencies.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -19,13 +19,24 @@
19
19
  "engines": {
20
20
  "node": ">=20"
21
21
  },
22
- "dependencies": {},
23
22
  "peerDependencies": {
23
+ "esbuild": ">=0.20.0",
24
+ "preact": "^10.25.0",
25
+ "preact-render-to-string": "^6.5.0",
24
26
  "sharp": "^0.34.5"
25
27
  },
26
28
  "peerDependenciesMeta": {
27
29
  "sharp": {
28
30
  "optional": true
31
+ },
32
+ "esbuild": {
33
+ "optional": true
34
+ },
35
+ "preact": {
36
+ "optional": true
37
+ },
38
+ "preact-render-to-string": {
39
+ "optional": true
29
40
  }
30
41
  },
31
42
  "keywords": [
@@ -44,5 +55,10 @@
44
55
  "server",
45
56
  "web-framework"
46
57
  ],
47
- "license": "MIT"
58
+ "license": "MIT",
59
+ "devDependencies": {
60
+ "esbuild": "^0.28.0",
61
+ "preact": "^10.29.2",
62
+ "preact-render-to-string": "^6.7.0"
63
+ }
48
64
  }
@@ -41,14 +41,16 @@ export function renderDocument({
41
41
  favicon = '/favicon.svg',
42
42
  offline = true,
43
43
  animatedFavicon = true,
44
+ nonce = '',
44
45
  } = {}) {
45
46
  const headHtml = typeof head === 'object' && head?.__raw ? head.__raw : String(head ?? '');
46
47
  const bodyHtml = typeof body === 'object' && body?.__raw ? body.__raw : String(body ?? '');
48
+ const n = nonce ? ` nonce="${escapeHtml(nonce)}"` : '';
47
49
  const fav = animatedFavicon
48
- ? '<script type="module">try{const m=await import("/glash-favicon.mjs");m.startGlashFavicon&&m.startGlashFavicon();}catch{}</script>'
50
+ ? `<script type="module"${n}>try{const m=await import("/glash-favicon.mjs");m.startGlashFavicon&&m.startGlashFavicon();}catch{}</script>`
49
51
  : '';
50
52
  const off = offline
51
- ? '<script type="module">try{const m=await import("/glash-offline.mjs");m.registerGlashOffline&&m.registerGlashOffline();}catch{}</script>'
53
+ ? `<script type="module"${n}>try{const m=await import("/glash-offline.mjs");m.registerGlashOffline&&m.registerGlashOffline();}catch{}</script>`
52
54
  : '';
53
55
  return `<!doctype html>
54
56
  <html lang="${escapeHtml(lang)}">
@@ -0,0 +1,113 @@
1
+ // glashjs JSX + hydration engine
2
+ // ---------------------------------------------------------------------------
3
+ // This is the layer that makes glashjs a real Next.js alternative: author
4
+ // pages as JSX components, render them on the server, and HYDRATE them in the
5
+ // browser so hooks (useState/useEffect) work — true interactivity.
6
+ //
7
+ // Built on proven primitives, added as OPTIONAL peers so glashjs core stays
8
+ // zero-dependency:
9
+ // - esbuild -> compiles JSX/TSX (server module + client bundle)
10
+ // - preact -> the component runtime (React-compatible)
11
+ // - preact-render-to-string -> server-side rendering
12
+ //
13
+ // A `.jsx`/`.tsx` route exports a default component and (optionally) an async
14
+ // `getServerData(ctx)` that returns props for SSR + hydration. Plain `.mjs`
15
+ // HTML-render routes keep working with zero deps.
16
+ import { promises as fs } from 'node:fs';
17
+ import path from 'node:path';
18
+ import { createHash } from 'node:crypto';
19
+ import { pathToFileURL } from 'node:url';
20
+
21
+ const MISSING = 'JSX/TSX routes need the optional peers: npm i esbuild preact preact-render-to-string';
22
+
23
+ let _esbuild;
24
+ async function esbuild() {
25
+ if (_esbuild !== undefined) return _esbuild;
26
+ try { _esbuild = await import('esbuild'); } catch { _esbuild = null; }
27
+ return _esbuild;
28
+ }
29
+
30
+ let _h, _renderToString;
31
+ async function preactRuntime() {
32
+ if (_h) return { h: _h, renderToString: _renderToString };
33
+ const p = await import('preact').catch(() => null);
34
+ const r = await import('preact-render-to-string').catch(() => null);
35
+ if (!p || !r) return null;
36
+ _h = p.h;
37
+ _renderToString = r.renderToString || r.default;
38
+ return { h: _h, renderToString: _renderToString };
39
+ }
40
+
41
+ export function isComponentRoute(file) {
42
+ return /\.(jsx|tsx)$/.test(file);
43
+ }
44
+
45
+ export function routeId(file) {
46
+ return createHash('sha1').update(file).digest('hex').slice(0, 10);
47
+ }
48
+
49
+ const serverCache = new Map();
50
+ const clientCache = new Map();
51
+
52
+ /** Compile a JSX/TSX route for the server and import it (default component + getServerData). */
53
+ export async function loadComponentRoute(file, root, dev) {
54
+ const eb = await esbuild();
55
+ if (!eb) throw new Error(MISSING);
56
+ if (!dev && serverCache.has(file)) return serverCache.get(file);
57
+ const out = path.join(root, '.glash', 'server', routeId(file) + '.mjs');
58
+ await fs.mkdir(path.dirname(out), { recursive: true });
59
+ await eb.build({
60
+ entryPoints: [file],
61
+ bundle: true,
62
+ platform: 'node',
63
+ format: 'esm',
64
+ jsx: 'automatic',
65
+ jsxImportSource: 'preact',
66
+ // Keep preact external so the route shares the framework's preact instance
67
+ // (vnodes from the route and renderToString must come from the same preact).
68
+ external: ['preact', 'preact/*', 'preact-render-to-string'],
69
+ outfile: out,
70
+ logLevel: 'silent',
71
+ });
72
+ const mod = await import(pathToFileURL(out).href + (dev ? `?t=${Date.now()}` : ''));
73
+ if (!dev) serverCache.set(file, mod);
74
+ return mod;
75
+ }
76
+
77
+ /** Build the browser hydration bundle for a route (preact bundled in). */
78
+ export async function clientBundle(file, dev) {
79
+ const eb = await esbuild();
80
+ if (!eb) throw new Error(MISSING);
81
+ if (!dev && clientCache.has(file)) return clientCache.get(file);
82
+ // Props arrive in a non-executed <script type="application/json"> block, so
83
+ // hydration works under glashjs's strict CSP (no inline executable scripts).
84
+ const entry = `import { hydrate, h } from 'preact';
85
+ import Page from ${JSON.stringify(file)};
86
+ const el = document.getElementById('glash-root');
87
+ const pe = document.getElementById('glash-props');
88
+ let props = {};
89
+ try { props = pe ? JSON.parse(pe.textContent) : {}; } catch {}
90
+ if (el) hydrate(h(Page, props), el);`;
91
+ const res = await eb.build({
92
+ stdin: { contents: entry, resolveDir: path.dirname(file), loader: 'jsx', sourcefile: 'glash-client-entry.jsx' },
93
+ bundle: true,
94
+ platform: 'browser',
95
+ format: 'esm',
96
+ minify: !dev,
97
+ jsx: 'automatic',
98
+ jsxImportSource: 'preact',
99
+ write: false,
100
+ logLevel: 'silent',
101
+ });
102
+ const js = res.outputFiles[0].text;
103
+ if (!dev) clientCache.set(file, js);
104
+ return js;
105
+ }
106
+
107
+ /** Server-render a route component to an HTML string. */
108
+ export async function renderComponent(mod, props) {
109
+ const rt = await preactRuntime();
110
+ if (!rt) throw new Error(MISSING);
111
+ if (typeof mod.default !== 'function') throw new Error('JSX route must default-export a component');
112
+ return rt.renderToString(rt.h(mod.default, props));
113
+ }
@@ -15,7 +15,7 @@ export async function discoverRoutes(routesDir) {
15
15
  const files = [];
16
16
  await walk(root, root, files);
17
17
  const routes = files
18
- .filter((f) => /\.(mjs|js)$/.test(f.rel))
18
+ .filter((f) => /\.(mjs|js|jsx|tsx)$/.test(f.rel))
19
19
  .map((f) => toRoute(f.rel, f.file));
20
20
  // Most specific first: static segments beat params beat catch-all.
21
21
  routes.sort((a, b) => b.score - a.score);
@@ -33,7 +33,7 @@ async function walk(root, dir, out) {
33
33
  }
34
34
 
35
35
  function toRoute(rel, file) {
36
- const clean = rel.replace(/\.(mjs|js)$/, '');
36
+ const clean = rel.replace(/\.(mjs|js|jsx|tsx)$/, '');
37
37
  const isApi = clean === 'api' || clean.startsWith('api/');
38
38
  const segs = [];
39
39
  for (const part of clean.split('/').filter(Boolean)) {
@@ -7,10 +7,12 @@
7
7
  // Every response carries the secure-by-default headers.
8
8
  import http from 'node:http';
9
9
  import { promises as fs, existsSync, statSync } from 'node:fs';
10
+ import { randomBytes } from 'node:crypto';
10
11
  import path from 'node:path';
11
12
  import { pathToFileURL } from 'node:url';
12
13
  import { discoverRoutes, matchRoute } from './router.mjs';
13
14
  import { renderDocument } from './html.mjs';
15
+ import { isComponentRoute, loadComponentRoute, clientBundle, renderComponent, routeId } from './jsx.mjs';
14
16
  import { securityHeaders } from '../security/headers.mjs';
15
17
  import { loadConfig } from '../config.mjs';
16
18
 
@@ -38,15 +40,28 @@ export async function createGlashServer({ root = process.cwd(), dev = false } =
38
40
  const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
39
41
  const pathname = safeDecode(url.pathname);
40
42
  try {
41
- if (await serveStatic(res, outDir, pathname, req, secHeaders)) return;
42
43
  if (dev) routes = await discoverRoutes(routesDir);
44
+ // Client hydration bundles: /_glash/<routeId>.js
45
+ if (pathname.startsWith('/_glash/')) {
46
+ const id = pathname.slice('/_glash/'.length).replace(/\.js$/, '');
47
+ const comp = routes.find((r) => isComponentRoute(r.file) && routeId(r.file) === id);
48
+ if (!comp) return send(res, 404, 'text/plain', 'not found', secHeaders);
49
+ const js = await clientBundle(comp.file, dev);
50
+ return send(res, 200, 'text/javascript; charset=utf-8', js, { ...secHeaders, 'cache-control': dev ? 'no-store' : 'public, max-age=31536000, immutable' });
51
+ }
52
+ if (await serveStatic(res, outDir, pathname, req, secHeaders)) return;
43
53
  const match = matchRoute(routes, pathname);
44
54
  if (!match) return send(res, 404, 'text/plain; charset=utf-8', 'Not found', secHeaders);
45
- const mod = await importRoute(match.route.file);
46
55
  const ctx = makeCtx(req, url, match.params);
47
- return match.route.isApi
48
- ? await handleApi(res, mod, req, ctx, secHeaders)
49
- : await handlePage(res, mod, ctx, cfg, secHeaders);
56
+ if (match.route.isApi) {
57
+ const mod = await importRoute(match.route.file);
58
+ return await handleApi(res, mod, req, ctx, secHeaders);
59
+ }
60
+ if (isComponentRoute(match.route.file)) {
61
+ return await handleComponentPage(res, match.route, ctx, cfg, secHeaders, root, dev);
62
+ }
63
+ const mod = await importRoute(match.route.file);
64
+ return await handlePage(res, mod, ctx, cfg, secHeaders);
50
65
  } catch (err) {
51
66
  const msg = dev ? `glashjs error:\n${err?.stack || err}` : 'Internal Server Error';
52
67
  send(res, 500, 'text/plain; charset=utf-8', msg, secHeaders);
@@ -79,14 +94,49 @@ async function handlePage(res, mod, ctx, cfg, secHeaders) {
79
94
  if (typeof render !== 'function') return send(res, 500, 'text/plain', 'route has no default export', secHeaders);
80
95
  const out = await render(ctx);
81
96
  const page = typeof out === 'string' || (out && out.__raw) ? { body: out } : (out || {});
97
+ const nonce = randomBytes(16).toString('base64');
82
98
  const docHtml = renderDocument({
83
99
  title: page.title || mod.title || cfg.name,
84
100
  head: page.head || '',
85
101
  body: page.body ?? '',
86
102
  offline: cfg.offline,
87
103
  animatedFavicon: !!cfg.animatedFavicon,
104
+ nonce,
105
+ });
106
+ send(res, page.status || 200, 'text/html; charset=utf-8', docHtml, { ...pageHeaders(cfg, secHeaders, nonce), ...(page.headers || {}) });
107
+ }
108
+
109
+ async function handleComponentPage(res, route, ctx, cfg, secHeaders, root, dev) {
110
+ const mod = await loadComponentRoute(route.file, root, dev);
111
+ const props = (typeof mod.getServerData === 'function' ? await mod.getServerData(ctx) : {}) || {};
112
+ const rendered = await renderComponent(mod, props);
113
+ const id = routeId(route.file);
114
+ const nonce = randomBytes(16).toString('base64');
115
+ // Props in a non-executed JSON block (CSP-safe); hydration bundle is an
116
+ // external 'self' module — both pass the strict CSP without 'unsafe-inline'.
117
+ const head = `<script type="application/json" id="glash-props">${safeJson(props)}</script>`;
118
+ const body = `<div id="glash-root">${rendered}</div><script type="module" src="/_glash/${id}.js"></script>`;
119
+ const docHtml = renderDocument({
120
+ title: mod.title || cfg.name,
121
+ head,
122
+ body,
123
+ offline: cfg.offline,
124
+ animatedFavicon: !!cfg.animatedFavicon,
125
+ nonce,
88
126
  });
89
- send(res, page.status || 200, 'text/html; charset=utf-8', docHtml, { ...secHeaders, ...(page.headers || {}) });
127
+ send(res, 200, 'text/html; charset=utf-8', docHtml, pageHeaders(cfg, secHeaders, nonce));
128
+ }
129
+
130
+ // Per-request page headers: a fresh CSP carrying this request's script nonce, so
131
+ // the framework's own inline <script>s run while injected scripts stay blocked.
132
+ function pageHeaders(cfg, secHeaders, nonce) {
133
+ const csp = securityHeaders({ ...(cfg.security || {}), csp: { ...((cfg.security || {}).csp || {}), nonce } })['Content-Security-Policy'];
134
+ return { ...secHeaders, 'Content-Security-Policy': csp };
135
+ }
136
+
137
+ // Serialize props for inline injection without breaking out of the <script>.
138
+ function safeJson(value) {
139
+ return JSON.stringify(value ?? {}).replace(/</g, '\\u003c').replace(/-->/g, '--\\u003e');
90
140
  }
91
141
 
92
142
  async function serveStatic(res, outDir, pathname, req, secHeaders) {