@krate/runtime 0.4.0-rc.4 → 0.4.0-rc.5

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.
@@ -1,4 +1,4 @@
1
- // @krate/runtime/server-renderer — Node.js HTTP server for SSR/ISR/Streaming
1
+ // @krate/runtime/server-renderer - Node.js HTTP server for SSR/ISR/Streaming
2
2
  // Receives render requests from the Go server and returns HTML.
3
3
  import http from "node:http";
4
4
  import fs from "node:fs";
@@ -14,7 +14,7 @@ function setupStream(res) {
14
14
  socket.setNoDelay(true);
15
15
  }
16
16
  }
17
- // ── ISR Cache (variant-aware, SWR, persisted) ────────────────────────────────
17
+ // ISR Cache (variant-aware, SWR, persisted)
18
18
  // A page's cache key is the route plus its per-request variant (params +
19
19
  // query). Two dynamic-route requests (e.g. /video/a and /video/b) render
20
20
  // different HTML, so they must never share a cache slot.
@@ -117,7 +117,7 @@ function withRenderTimeout(p) {
117
117
  p.then((v) => { clearTimeout(timer); resolve(v); }, (e) => { clearTimeout(timer); reject(e); });
118
118
  });
119
119
  }
120
- // ISR cache persistence — survives renderer restarts so a bounce doesn't
120
+ // ISR cache persistence - survives renderer restarts so a bounce doesn't
121
121
  // cold-render every ISR variant. Written debounced (coalesced) to the build
122
122
  // output dir (.krate/isr-cache.json), overridable via KRATE_ISR_CACHE.
123
123
  let isrCacheFile = process.env.KRATE_ISR_CACHE || "";
@@ -156,7 +156,7 @@ function loadIsrCache() {
156
156
  console.error("[krate-ssr] ISR cache load failed:", err.message);
157
157
  }
158
158
  }
159
- // ── Page Module Loader ───────────────────────────────────────────────────────
159
+ // Page Module Loader
160
160
  const moduleCache = new Map();
161
161
  async function loadPageModule(page) {
162
162
  // Prefer pre-compiled server bundle over raw source
@@ -184,7 +184,7 @@ async function loadPageModule(page) {
184
184
  throw err;
185
185
  }
186
186
  }
187
- // ── Renderer ─────────────────────────────────────────────────────────────────
187
+ // Renderer
188
188
  let manifest = null;
189
189
  let projectRoot = "";
190
190
  function findPage(route) {
@@ -213,7 +213,7 @@ function buildProps(req) {
213
213
  props.query = req.query;
214
214
  return props;
215
215
  }
216
- // renderFresh renders a page component and — for ISR pages — stores the result.
216
+ // renderFresh renders a page component and - for ISR pages - stores the result.
217
217
  // Extracted so background revalidation shares exactly the same render path.
218
218
  async function renderFresh(page, req) {
219
219
  try {
@@ -275,7 +275,7 @@ function revalidateInBackground(page, req) {
275
275
  // keeping the entries in place. This is the non-destructive counterpart of
276
276
  // /__krate/ssr/revalidate (which clears a route). The Go server's periodic ISR
277
277
  // timer calls this so cached pages stay fresh without evicting dynamic
278
- // variants — eviction would turn a request that should be a HIT into a MISS.
278
+ // variants - eviction would turn a request that should be a HIT into a MISS.
279
279
  const inFlightRouteRefreshes = new Map();
280
280
  function refreshRouteVariants(page) {
281
281
  const running = inFlightRouteRefreshes.get(page.route);
@@ -344,12 +344,11 @@ async function renderPage(req) {
344
344
  response.cacheStatus = "miss";
345
345
  return response;
346
346
  }
347
- // ── Region rendering (static-first) ──────────────────────────────────────────
348
- //
347
+ // Region rendering (static-first)
349
348
  // The Go server owns the page: it serves the build-time static shell with the
350
- // <!—suspense:ID—> markers and baked fallbacks, then asks the sidecar to render
349
+ // <!-suspense:ID-> markers and baked fallbacks, then asks the sidecar to render
351
350
  // ONLY the page's dynamic regions. Each region is rendered by its compiled
352
- // runtime component bundle (server-components/<Name>.runtime.js — an IIFE that
351
+ // runtime component bundle (server-components/<Name>.runtime.js - an IIFE that
353
352
  // defines globalThis.__krate_render(propsJSON)) with the build-time baked props,
354
353
  // so nothing is re-derived at request time.
355
354
  const runtimeBundleCache = new Map();
@@ -512,7 +511,7 @@ function extractTitle(html) {
512
511
  const match = html.match(/<title[^>]*>([\s\S]*?)<\/title>/i);
513
512
  return match ? match[1].trim() : "";
514
513
  }
515
- // ── HTTP Server ──────────────────────────────────────────────────────────────
514
+ // HTTP Server
516
515
  const PORT = parseInt(process.env.KRATE_SSR_PORT || "3100", 10);
517
516
  const manifestPath = process.env.KRATE_MANIFEST || "";
518
517
  const root = process.env.KRATE_ROOT || process.cwd();
@@ -623,7 +622,7 @@ const server = http.createServer(async (req, res) => {
623
622
  }
624
623
  return;
625
624
  }
626
- // ── /__krate/regions — render ONLY a page's dynamic regions ───────────────
625
+ // /__krate/regions - render ONLY a page's dynamic regions
627
626
  // One NDJSON frame per region, written as its own chunk so the Go server
628
627
  // forwards each region progressively and splices it into the static shell.
629
628
  // The Go server sends the splice markers it parsed from the shell; the
@@ -671,7 +670,7 @@ const server = http.createServer(async (req, res) => {
671
670
  writeJsonLine(res, await renderRegion(page, region, renderReq));
672
671
  }
673
672
  else {
674
- // Unknown region id — keep the baked content by sending no frame.
673
+ // Unknown region id - keep the baked content by sending no frame.
675
674
  writeJsonLine(res, { type: "skip", id: r.id });
676
675
  }
677
676
  }
@@ -685,7 +684,7 @@ const server = http.createServer(async (req, res) => {
685
684
  res.end();
686
685
  return;
687
686
  }
688
- // ── Direct page requests (non-proxied) ──────────────────────────────────
687
+ // Direct page requests (non-proxied)
689
688
  // Collect request headers
690
689
  const headers = {};
691
690
  for (const [key, value] of Object.entries(req.headers)) {
package/dist/server.js CHANGED
@@ -1,6 +1,6 @@
1
- // @krate/runtime/server — Server-side rendering runtime
1
+ // @krate/runtime/server - Server-side rendering runtime
2
2
  // Provides the same API as the client runtime but renders to HTML strings.
3
- // ── Signal (server: returns initial value, no reactivity) ──────────────────────
3
+ // Signal (server: returns initial value, no reactivity)
4
4
  export function createSignal(initial) {
5
5
  let value = initial;
6
6
  const read = () => value;
@@ -10,7 +10,7 @@ export function createSignal(initial) {
10
10
  return [read, write];
11
11
  }
12
12
  export function createEffect(_fn) {
13
- // No-op on server — effects only run on client
13
+ // No-op on server - effects only run on client
14
14
  return () => { };
15
15
  }
16
16
  export function createMemo(fn) {
@@ -46,7 +46,7 @@ export function jsx(type, props, _key) {
46
46
  return { type, props: rest, children: childArray };
47
47
  }
48
48
  export const jsxs = jsx;
49
- // ── HTML Rendering ────────────────────────────────────────────────────────────
49
+ // HTML Rendering
50
50
  const VOID_ELEMENTS = new Set([
51
51
  "area", "base", "br", "col", "embed", "hr", "img", "input",
52
52
  "link", "meta", "param", "source", "track", "wbr",
@@ -114,7 +114,7 @@ function renderElement(el) {
114
114
  const inner = children.map(renderNode).join("");
115
115
  return `<${tag}${attrs}>${inner}</${tag}>`;
116
116
  }
117
- // ── Streaming SSR via Suspense ────────────────────────────────────────────────
117
+ // Streaming SSR via Suspense
118
118
  // Use globalThis for boundary counter so it's shared between the unbundled
119
119
  // server-renderer and esbuild-bundled page components (each gets its own copy).
120
120
  export function setStreamingResolved(v) {
@@ -144,24 +144,24 @@ export function Suspense(props) {
144
144
  return raw(`<span data-suspense="${id}">${fallback}</span>` +
145
145
  `<template data-suspense="${id}">${inner}</template>`);
146
146
  }
147
- // ── Built-in Components (server stubs) ────────────────────────────────────────
148
- // Head — renders children into the page head at build time.
147
+ // Built-in Components (server stubs)
148
+ // Head - renders children into the page head at build time.
149
149
  // On the server, we just render children; the build pipeline extracts them.
150
150
  export function Head(props) {
151
151
  return props.children ?? "";
152
152
  }
153
- // Script — renders a <script> tag.
153
+ // Script - renders a <script> tag.
154
154
  export function Script(props) {
155
155
  if (props.src) {
156
156
  return `<script src="${escapeHTML(props.src)}"></script>`;
157
157
  }
158
158
  return `<script>${props.children ?? ""}</script>`;
159
159
  }
160
- // Style — renders a <style> tag.
160
+ // Style - renders a <style> tag.
161
161
  export function Style(props) {
162
162
  return `<style>${props.children ?? ""}</style>`;
163
163
  }
164
- // Link — renders an <a> tag wired for SPA navigation (server renderer).
164
+ // Link - renders an <a> tag wired for SPA navigation (server renderer).
165
165
  export function Link(props) {
166
166
  const { href = "", prefetch, replace, scroll, children, ...rest } = props;
167
167
  const attrs = [];
@@ -195,7 +195,7 @@ export function Link(props) {
195
195
  const inner = children != null ? renderNode(children) : "";
196
196
  return raw(`<a ${attrs.join(" ")}>${inner}</a>`);
197
197
  }
198
- // Image — renders an <img> tag (server stub; Go compiler handles full responsive output at build time).
198
+ // Image - renders an <img> tag (server stub; Go compiler handles full responsive output at build time).
199
199
  export function Image(props) {
200
200
  const { src = "", alt = "", width, height, ...rest } = props;
201
201
  const attrs = [];
@@ -209,11 +209,11 @@ export function Image(props) {
209
209
  attrs.push(`height="${height}"`);
210
210
  return raw(`<img ${attrs.join(" ")} />`);
211
211
  }
212
- // Icon — renders an empty span placeholder (Go compiler handles SVG fetching at build time).
212
+ // Icon - renders an empty span placeholder (Go compiler handles SVG fetching at build time).
213
213
  export function Icon(_props) {
214
214
  return raw("<span></span>");
215
215
  }
216
- // SyntaxHighlight — renders a <pre><code> block (Go compiler handles chroma highlighting at build time).
216
+ // SyntaxHighlight - renders a <pre><code> block (Go compiler handles chroma highlighting at build time).
217
217
  export function SyntaxHighlight(props) {
218
218
  const lang = props.lang || "";
219
219
  const code = props.children != null ? String(props.children) : "";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,26 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { jsx, renderToString } from './server';
3
+ describe('renderToString', () => {
4
+ it('renders nested elements and escapes text', () => {
5
+ const node = jsx('div', { class: 'x', children: [jsx('span', { children: 'a & b' })] });
6
+ expect(renderToString(node)).toBe('<div class="x"><span>a &amp; b</span></div>');
7
+ });
8
+ it('renders void elements without a close tag', () => {
9
+ expect(renderToString(jsx('img', { src: '/x.png', alt: 'y' }))).toBe('<img src="/x.png" alt="y">');
10
+ });
11
+ it('invokes function components', () => {
12
+ const Comp = () => jsx('p', { children: 'hi' });
13
+ expect(renderToString(jsx(Comp, {}))).toBe('<p>hi</p>');
14
+ });
15
+ it('drops event and internal props', () => {
16
+ const node = jsx('button', { onClick: () => undefined, children: 'x' });
17
+ expect(renderToString(node)).toBe('<button>x</button>');
18
+ });
19
+ it('omits null/false-valued attributes', () => {
20
+ expect(renderToString(jsx('input', { disabled: false, value: null }))).toBe('<input>');
21
+ expect(renderToString(jsx('input', { disabled: true }))).toBe('<input disabled>');
22
+ });
23
+ it('passes raw HTML through without escaping', () => {
24
+ expect(renderToString({ __raw: '<b>hi</b>' })).toBe('<b>hi</b>');
25
+ });
26
+ });
package/dist/signal.d.ts CHANGED
@@ -42,7 +42,7 @@ export interface CSSPrimitiveOptions<T extends string | number> extends CSSARIAO
42
42
  * every `createCSSChoice` declaration at build time into hidden radio inputs +
43
43
  * `:has()` CSS, so it is **never** emitted to the client at runtime. Reading the
44
44
  * getter as JSX text (`{tab()}`) compiles to a live value driven by the
45
- * inherited `--krate-current` custom property — still zero JS. Custom `vars`
45
+ * inherited `--krate-current` custom property - still zero JS. Custom `vars`
46
46
  * publish more inheritable properties for computed text/themes.
47
47
  *
48
48
  * If a component cannot be compiled to CSS the build does not fall back; it
@@ -53,7 +53,7 @@ export interface CSSPrimitiveOptions<T extends string | number> extends CSSARIAO
53
53
  * (`{ options, as, aria, vars, label }`). When omitted, the compiler infers
54
54
  * options from every literal the setter is called with.
55
55
  */
56
- export declare function createCSSChoice<T extends string | number>(initial: T, _options?: readonly T[] | CSSPrimitiveOptions<T>): [() => T, (next: T) => void];
56
+ export declare function createCSSChoice<T extends string | number>(initial: T, _options?: readonly T[] | CSSPrimitiveOptions<T>): CSSScope<T>;
57
57
  /**
58
58
  * Zero-JS boolean state (a single checkbox). Compiler-erased like
59
59
  * `createCSSChoice`; the runtime body only exists so type-checking and any
@@ -65,23 +65,31 @@ export declare function createCSSToggle(initial: boolean, _options?: CSSARIAOpti
65
65
  on?: string;
66
66
  off?: string;
67
67
  };
68
- }): [() => boolean, (next: boolean) => void];
68
+ }): CSSScope<boolean>;
69
69
  /**
70
70
  * Zero-JS independent boolean flags (`createCSSFlags(['a','b'])`). Returns a
71
71
  * getter object keyed by flag name plus a setter. Compiler-erased like
72
72
  * `createCSSChoice`.
73
73
  */
74
+ export type CSSFlagsScope<K extends string> = [
75
+ Record<K, () => boolean>,
76
+ (flag: K, value: boolean) => void
77
+ ] & {
78
+ trigger: (flag: K) => Record<string, unknown>;
79
+ panel: (flag: K) => Record<string, unknown>;
80
+ close: () => Record<string, unknown>;
81
+ };
74
82
  export declare function createCSSFlags<K extends string>(flags: readonly K[], _options?: CSSARIAOptions & {
75
83
  vars?: Record<string, Partial<Record<K, string>>>;
76
- }): [Record<K, () => boolean>, (flag: K, value: boolean) => void];
84
+ }): CSSFlagsScope<K>;
77
85
  /**
78
- * Zero-JS optional radio group (`createCSSGroup`) — an accordion, disclosure,
86
+ * Zero-JS optional radio group (`createCSSGroup`) - an accordion, disclosure,
79
87
  * dialog, menu, or popover. `null` means "closed". Compiler-erased like the
80
88
  * other CSS primitives; the runtime body is a type-checking shim only.
81
89
  */
82
- export declare function createCSSGroup<T extends string | number>(initial: T | null, _options?: readonly T[] | CSSPrimitiveOptions<T>): [() => T | null, (next: T | null) => void];
90
+ export declare function createCSSGroup<T extends string | number>(initial: T | null, _options?: readonly T[] | CSSPrimitiveOptions<T>): CSSScope<T | null>;
83
91
  /**
84
- * Zero-JS discrete range (`createCSSRange`) — a stepped slider, stepper, or
92
+ * Zero-JS discrete range (`createCSSRange`) - a stepped slider, stepper, or
85
93
  * progress indicator. Values are integers from `min` to `max` by `step`.
86
94
  * Compiler-erased; the runtime body is a type-checking shim only.
87
95
  */
@@ -89,7 +97,33 @@ export declare function createCSSRange(initial: number, _options: CSSARIAOptions
89
97
  min?: number;
90
98
  max?: number;
91
99
  step?: number;
92
- }): [() => number, (next: number) => void];
100
+ }): CSSScope<number>;
101
+ /**
102
+ * A first-class CSS-scope handle. It is the `[getter, setter]` tuple returned by
103
+ * the CSS primitives (so destructuring keeps working) with helpers that the Krate
104
+ * compiler expands inline, anywhere in any component:
105
+ *
106
+ * ```tsx
107
+ * const tab = createCSSChoice('a', ['a', 'b']);
108
+ * <button {...tab.trigger('a')}>A</button>
109
+ * <div {...tab.panel('a')}>Panel A</div>
110
+ * <button {...tab.close()}>Close</button>
111
+ * ```
112
+ *
113
+ * The helpers return a marker spread at runtime; the compiler rewrites them to
114
+ * the `<label for>` / `:has()`-toggled wrapper markup. A handle is a plain
115
+ * value, so it can be passed to child components as a prop.
116
+ */
117
+ export type CSSScope<T> = [() => T, (next: T) => void] & {
118
+ /** Spread on the trigger element; selects `value`. */
119
+ trigger: (value?: T) => Record<string, unknown>;
120
+ /** Spread on a panel element; shows it when `value` is selected. */
121
+ panel: (value?: T) => Record<string, unknown>;
122
+ /** Spread on an element that closes the scope (groups/dialogs/popovers). */
123
+ close: () => Record<string, unknown>;
124
+ /** The current selected value (live, via `--krate-current`). */
125
+ current: () => T;
126
+ };
93
127
  /** Actions destructured from a `createCSSStack` result. */
94
128
  export interface CSSStackActions<K extends string> {
95
129
  push: (node: K) => void;
@@ -97,7 +131,7 @@ export interface CSSStackActions<K extends string> {
97
131
  clear: () => void;
98
132
  }
99
133
  /**
100
- * Zero-JS navigation stack (`createCSSStack`) — a declared tree of nested
134
+ * Zero-JS navigation stack (`createCSSStack`) - a declared tree of nested
101
135
  * panels for drill-down menus and multi-level drawers. The compiler infers the
102
136
  * tree from where each literal `push('node')` appears; `top()` reads the
103
137
  * deepest open node. Compiler-erased; the runtime body is a shim only.
@@ -113,7 +147,7 @@ export declare function onMount(fn: () => void): void;
113
147
  export declare function createMemo<T>(fn: () => T): () => T;
114
148
  /**
115
149
  * Reducer state primitive: a `createSignal` whose setter applies a reducer.
116
- * Returns `[getter, dispatch]` — the getter contract matches `createSignal`, so
150
+ * Returns `[getter, dispatch]` - the getter contract matches `createSignal`, so
117
151
  * compiler slot bindings read it as `getter()` and hydration treats it like any
118
152
  * other signal. Used both directly and as the lowering target for React's
119
153
  * `useReducer`.
package/dist/signal.js CHANGED
@@ -57,7 +57,7 @@ export function disposeAll() {
57
57
  * every `createCSSChoice` declaration at build time into hidden radio inputs +
58
58
  * `:has()` CSS, so it is **never** emitted to the client at runtime. Reading the
59
59
  * getter as JSX text (`{tab()}`) compiles to a live value driven by the
60
- * inherited `--krate-current` custom property — still zero JS. Custom `vars`
60
+ * inherited `--krate-current` custom property - still zero JS. Custom `vars`
61
61
  * publish more inheritable properties for computed text/themes.
62
62
  *
63
63
  * If a component cannot be compiled to CSS the build does not fall back; it
@@ -69,7 +69,7 @@ export function disposeAll() {
69
69
  * options from every literal the setter is called with.
70
70
  */
71
71
  export function createCSSChoice(initial, _options) {
72
- return createSignal(initial);
72
+ return withScopeHelpers(createSignal(initial));
73
73
  }
74
74
  /**
75
75
  * Zero-JS boolean state (a single checkbox). Compiler-erased like
@@ -78,13 +78,8 @@ export function createCSSChoice(initial, _options) {
78
78
  * `--krate-current` property ("on"/"off").
79
79
  */
80
80
  export function createCSSToggle(initial, _options) {
81
- return createSignal(initial);
81
+ return withScopeHelpers(createSignal(initial));
82
82
  }
83
- /**
84
- * Zero-JS independent boolean flags (`createCSSFlags(['a','b'])`). Returns a
85
- * getter object keyed by flag name plus a setter. Compiler-erased like
86
- * `createCSSChoice`.
87
- */
88
83
  export function createCSSFlags(flags, _options) {
89
84
  const getters = {};
90
85
  for (const flag of flags) {
@@ -94,26 +89,38 @@ export function createCSSFlags(flags, _options) {
94
89
  // No-op: the compiler compiles flags to checkboxes, so this body is only a
95
90
  // type-checking/server-evaluation shim.
96
91
  const set = (_flag, _value) => { };
97
- return [getters, set];
92
+ const scope = [getters, set];
93
+ scope.trigger = (flag) => ({ 'data-krate-scope': 'trigger', value: flag });
94
+ scope.panel = (flag) => ({ 'data-krate-scope': 'panel', value: flag });
95
+ scope.close = () => ({ 'data-krate-scope': 'close' });
96
+ return scope;
98
97
  }
99
98
  /**
100
- * Zero-JS optional radio group (`createCSSGroup`) — an accordion, disclosure,
99
+ * Zero-JS optional radio group (`createCSSGroup`) - an accordion, disclosure,
101
100
  * dialog, menu, or popover. `null` means "closed". Compiler-erased like the
102
101
  * other CSS primitives; the runtime body is a type-checking shim only.
103
102
  */
104
103
  export function createCSSGroup(initial, _options) {
105
- return createSignal(initial);
104
+ return withScopeHelpers(createSignal(initial));
106
105
  }
107
106
  /**
108
- * Zero-JS discrete range (`createCSSRange`) — a stepped slider, stepper, or
107
+ * Zero-JS discrete range (`createCSSRange`) - a stepped slider, stepper, or
109
108
  * progress indicator. Values are integers from `min` to `max` by `step`.
110
109
  * Compiler-erased; the runtime body is a type-checking shim only.
111
110
  */
112
111
  export function createCSSRange(initial, _options) {
113
- return createSignal(initial);
112
+ return withScopeHelpers(createSignal(initial));
113
+ }
114
+ function withScopeHelpers(result) {
115
+ const scope = result;
116
+ scope.trigger = (value) => ({ 'data-krate-scope': 'trigger', value });
117
+ scope.panel = (value) => ({ 'data-krate-scope': 'panel', value });
118
+ scope.close = () => ({ 'data-krate-scope': 'close' });
119
+ scope.current = () => result[0]();
120
+ return scope;
114
121
  }
115
122
  /**
116
- * Zero-JS navigation stack (`createCSSStack`) — a declared tree of nested
123
+ * Zero-JS navigation stack (`createCSSStack`) - a declared tree of nested
117
124
  * panels for drill-down menus and multi-level drawers. The compiler infers the
118
125
  * tree from where each literal `push('node')` appears; `top()` reads the
119
126
  * deepest open node. Compiler-erased; the runtime body is a shim only.
@@ -314,7 +321,7 @@ export function createMemo(fn) {
314
321
  }
315
322
  /**
316
323
  * Reducer state primitive: a `createSignal` whose setter applies a reducer.
317
- * Returns `[getter, dispatch]` — the getter contract matches `createSignal`, so
324
+ * Returns `[getter, dispatch]` - the getter contract matches `createSignal`, so
318
325
  * compiler slot bindings read it as `getter()` and hydration treats it like any
319
326
  * other signal. Used both directly and as the lowering target for React's
320
327
  * `useReducer`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@krate/runtime",
3
- "version": "0.4.0-rc.4",
3
+ "version": "0.4.0-rc.5",
4
4
  "description": "Client-side runtime for Krate — signals, hydration, SPA router, resources, and context.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",