@krate/runtime 0.1.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/dist/server.js ADDED
@@ -0,0 +1,214 @@
1
+ // @krate/runtime/server — Server-side rendering runtime
2
+ // Provides the same API as the client runtime but renders to HTML strings.
3
+ // ── Signal (server: returns initial value, no reactivity) ──────────────────────
4
+ export function createSignal(initial) {
5
+ let value = initial;
6
+ const read = () => value;
7
+ const write = (v) => {
8
+ value = typeof v === "function" ? v(value) : v;
9
+ };
10
+ return [read, write];
11
+ }
12
+ export function createEffect(_fn) {
13
+ // No-op on server — effects only run on client
14
+ return () => { };
15
+ }
16
+ export function createMemo(fn) {
17
+ let cached;
18
+ let dirty = true;
19
+ return () => {
20
+ if (dirty) {
21
+ cached = fn();
22
+ dirty = false;
23
+ }
24
+ return cached;
25
+ };
26
+ }
27
+ export function onCleanup(_fn) {
28
+ // No-op on server
29
+ }
30
+ export function onMount(fn) {
31
+ // On server, run immediately (synchronous)
32
+ fn();
33
+ }
34
+ function raw(html) { return { __raw: html }; }
35
+ export function Fragment(_props) {
36
+ return _props.children ?? [];
37
+ }
38
+ export function jsx(type, props, _key) {
39
+ const { children, ...rest } = props ?? {};
40
+ const childArray = Array.isArray(children)
41
+ ? children.flat(Infinity)
42
+ : children != null
43
+ ? [children]
44
+ : [];
45
+ return { type, props: rest, children: childArray };
46
+ }
47
+ export const jsxs = jsx;
48
+ // ── HTML Rendering ────────────────────────────────────────────────────────────
49
+ const VOID_ELEMENTS = new Set([
50
+ "area", "base", "br", "col", "embed", "hr", "img", "input",
51
+ "link", "meta", "param", "source", "track", "wbr",
52
+ ]);
53
+ function escapeHTML(str) {
54
+ return str
55
+ .replace(/&/g, "&")
56
+ .replace(/</g, "&lt;")
57
+ .replace(/>/g, "&gt;")
58
+ .replace(/"/g, "&quot;")
59
+ .replace(/'/g, "&#39;");
60
+ }
61
+ function renderNode(node) {
62
+ if (node == null || node === false)
63
+ return "";
64
+ if (typeof node === "string")
65
+ return escapeHTML(node);
66
+ if (typeof node === "number")
67
+ return String(node);
68
+ if (typeof node === "boolean")
69
+ return "";
70
+ if (Array.isArray(node))
71
+ return node.map(renderNode).join("");
72
+ if (typeof node === "object" && "__raw" in node)
73
+ return node.__raw;
74
+ if (typeof node === "object" && "type" in node)
75
+ return renderElement(node);
76
+ return "";
77
+ }
78
+ function setAttr(key, val) {
79
+ if (val == null || val === false)
80
+ return "";
81
+ if (val === true)
82
+ return ` ${key}`;
83
+ if (key === "class")
84
+ return ` class="${escapeHTML(String(val))}"`;
85
+ if (key === "style" && typeof val === "object") {
86
+ const css = Object.entries(val)
87
+ .map(([k, v]) => `${k}:${v}`)
88
+ .join(";");
89
+ return ` style="${escapeHTML(css)}"`;
90
+ }
91
+ if (key.startsWith("on") || key.startsWith("__"))
92
+ return "";
93
+ return ` ${key}="${escapeHTML(String(val))}"`;
94
+ }
95
+ export function renderToString(node) {
96
+ return renderNode(node);
97
+ }
98
+ function renderElement(el) {
99
+ const { type, props, children } = el;
100
+ // Component
101
+ if (typeof type === "function") {
102
+ const result = type({ ...props, children });
103
+ return renderNode(result);
104
+ }
105
+ // HTML element
106
+ const tag = type;
107
+ const attrs = Object.entries(props)
108
+ .map(([k, v]) => setAttr(k, v))
109
+ .join("");
110
+ if (VOID_ELEMENTS.has(tag)) {
111
+ return `<${tag}${attrs}>`;
112
+ }
113
+ const inner = children.map(renderNode).join("");
114
+ return `<${tag}${attrs}>${inner}</${tag}>`;
115
+ }
116
+ // ── Streaming SSR via Suspense ────────────────────────────────────────────────
117
+ // Use globalThis for boundary counter so it's shared between the unbundled
118
+ // server-renderer and esbuild-bundled page components (each gets its own copy).
119
+ export function setStreamingResolved(v) {
120
+ globalThis.__krate_streaming_resolved = v;
121
+ }
122
+ export function resetBoundaryCounter() {
123
+ globalThis.__krate_boundary_counter = 0;
124
+ }
125
+ function nextBoundaryId() {
126
+ const g = globalThis;
127
+ if (g.__krate_boundary_counter == null)
128
+ g.__krate_boundary_counter = 0;
129
+ return g.__krate_boundary_counter++;
130
+ }
131
+ // Suspense component for streaming SSR.
132
+ // Phase 1 (resolved=false): renders fallback in a <span>, children placeholder in a <template>
133
+ // Phase 2 (resolved=true): renders just the raw children with extraction markers
134
+ export function Suspense(props) {
135
+ const id = nextBoundaryId();
136
+ if (globalThis.__krate_streaming_resolved) {
137
+ // Phase 2: output resolved children wrapped in markers for extraction
138
+ const inner = renderNode(props.children);
139
+ return raw(`<!--suspense-resolved:${id}-->${inner}<!--/suspense-resolved:${id}-->`);
140
+ }
141
+ const inner = renderNode(props.children);
142
+ const fallback = renderNode(props.fallback);
143
+ return raw(`<span data-suspense="${id}">${fallback}</span>` +
144
+ `<template data-suspense="${id}">${inner}</template>`);
145
+ }
146
+ // ── Built-in Components (server stubs) ────────────────────────────────────────
147
+ // Head — renders children into the page head at build time.
148
+ // On the server, we just render children; the build pipeline extracts them.
149
+ export function Head(props) {
150
+ return props.children ?? "";
151
+ }
152
+ // Script — renders a <script> tag.
153
+ export function Script(props) {
154
+ if (props.src) {
155
+ return `<script src="${escapeHTML(props.src)}"></script>`;
156
+ }
157
+ return `<script>${props.children ?? ""}</script>`;
158
+ }
159
+ // Style — renders a <style> tag.
160
+ export function Style(props) {
161
+ return `<style>${props.children ?? ""}</style>`;
162
+ }
163
+ // Link — renders an <a> tag wired for SPA navigation (server renderer).
164
+ export function Link(props) {
165
+ const { href = "", prefetch, replace, scroll, children, ...rest } = props;
166
+ const attrs = [];
167
+ if (href)
168
+ attrs.push(`href="${escapeHTML(href)}"`);
169
+ const external = /^(https?:|mailto:|tel:|#|javascript:)/.test(href) ||
170
+ href.startsWith("//") ||
171
+ rest.target === "_blank" ||
172
+ rest.download !== undefined;
173
+ if (external) {
174
+ attrs.push("data-krate-external");
175
+ }
176
+ else {
177
+ attrs.push("data-krate-link");
178
+ if (prefetch !== false)
179
+ attrs.push("data-prefetch");
180
+ if (replace)
181
+ attrs.push("data-krate-replace");
182
+ if (scroll === false)
183
+ attrs.push('data-krate-scroll="false"');
184
+ }
185
+ for (const key of ["target", "rel", "title", "id", "aria-label"]) {
186
+ const v = rest[key];
187
+ if (v !== undefined && v !== null)
188
+ attrs.push(`${key}="${escapeHTML(String(v))}"`);
189
+ }
190
+ if (rest.target === "_blank" && rest.rel === undefined)
191
+ attrs.push('rel="noopener noreferrer"');
192
+ if (rest.className)
193
+ attrs.push(`class="${escapeHTML(String(rest.className))}"`);
194
+ const inner = children != null ? renderNode(children) : "";
195
+ return raw(`<a ${attrs.join(" ")}>${inner}</a>`);
196
+ }
197
+ // Image — renders an <img> tag (server stub; Go compiler handles full responsive output at build time).
198
+ export function Image(props) {
199
+ const { src = "", alt = "", width, height, ...rest } = props;
200
+ const attrs = [];
201
+ if (src)
202
+ attrs.push(`src="${escapeHTML(src)}"`);
203
+ if (alt)
204
+ attrs.push(`alt="${escapeHTML(alt)}"`);
205
+ if (width)
206
+ attrs.push(`width="${width}"`);
207
+ if (height)
208
+ attrs.push(`height="${height}"`);
209
+ return raw(`<img ${attrs.join(" ")} />`);
210
+ }
211
+ // Icon — renders an empty span placeholder (Go compiler handles SVG fetching at build time).
212
+ export function Icon(_props) {
213
+ return raw("<span></span>");
214
+ }
@@ -0,0 +1,9 @@
1
+ export declare function disposeAll(): void;
2
+ export declare function createSignal<T>(initial: T): [() => T, (next: T | ((prev: T) => T)) => void];
3
+ export declare function createEffect(fn: () => void): () => void;
4
+ export declare function onCleanup(fn: () => void): void;
5
+ export declare function onMount(fn: () => void): void;
6
+ export declare function createMemo<T>(fn: () => T): () => T;
7
+ export declare function forwardRef<P>(renderFn: (props: P, ref: (el: Element) => void) => Node | null | undefined): (props: P & {
8
+ ref?: (el: Element) => void;
9
+ }) => Node | null | undefined;
package/dist/signal.js ADDED
@@ -0,0 +1,178 @@
1
+ const context = [];
2
+ const mountQueue = [];
3
+ let mountScheduled = false;
4
+ const allEffects = new Set();
5
+ // Pending effects scheduled to re-run in the next microtask. Writes batch
6
+ // subscriber re-runs into a single flush so N writes in a loop (or one write
7
+ // fanning out) produce one pass instead of N synchronous effect runs.
8
+ const pending = [];
9
+ let flushScheduled = false;
10
+ function newEffectState(fn) {
11
+ return { fn, cleanups: [], disposed: false, sources: new Set(), running: false, rerun: false, queued: false };
12
+ }
13
+ function disposeEffect(effect) {
14
+ if (!effect.disposed) {
15
+ effect.disposed = true;
16
+ // Detach from every signal subscriber Set so a long-lived signal never
17
+ // retains a disposed effect (and its closure graph).
18
+ for (const set of effect.sources) {
19
+ set.delete(effect);
20
+ }
21
+ effect.sources.clear();
22
+ for (const cleanup of effect.cleanups) {
23
+ cleanup();
24
+ }
25
+ effect.cleanups.length = 0;
26
+ }
27
+ }
28
+ export function disposeAll() {
29
+ for (const effect of allEffects) {
30
+ disposeEffect(effect);
31
+ }
32
+ allEffects.clear();
33
+ pending.length = 0;
34
+ flushScheduled = false;
35
+ }
36
+ export function createSignal(initial) {
37
+ let value = initial;
38
+ const subs = new Set();
39
+ const read = () => {
40
+ const current = context[context.length - 1];
41
+ if (current && !current.disposed) {
42
+ subs.add(current);
43
+ current.sources.add(subs);
44
+ }
45
+ return value;
46
+ };
47
+ const write = (next) => {
48
+ const resolved = typeof next === 'function' ? next(value) : next;
49
+ if (resolved !== value) {
50
+ value = resolved;
51
+ const list = Array.from(subs);
52
+ for (const effect of list) {
53
+ if (effect.disposed) {
54
+ // Lazy cleanup for effects that were disposed without unsubscribing.
55
+ subs.delete(effect);
56
+ continue;
57
+ }
58
+ if (effect.running) {
59
+ // A feedback loop that writes its own dependencies gets one
60
+ // re-run after the current run; further iterations are dropped to
61
+ // guarantee termination.
62
+ effect.rerun = true;
63
+ continue;
64
+ }
65
+ if (!effect.queued) {
66
+ effect.queued = true;
67
+ pending.push(effect);
68
+ }
69
+ }
70
+ scheduleFlush();
71
+ }
72
+ };
73
+ return [read, write];
74
+ }
75
+ function scheduleFlush() {
76
+ if (!flushScheduled) {
77
+ flushScheduled = true;
78
+ queueMicrotask(flushEffects);
79
+ }
80
+ }
81
+ function flushEffects() {
82
+ flushScheduled = false;
83
+ const effects = pending.splice(0);
84
+ for (const effect of effects) {
85
+ if (effect.disposed) {
86
+ continue;
87
+ }
88
+ effect.queued = false;
89
+ effect.rerun = false;
90
+ runEffect(effect);
91
+ if (effect.rerun && !effect.disposed) {
92
+ effect.rerun = false;
93
+ runEffect(effect);
94
+ }
95
+ }
96
+ }
97
+ function runEffect(effect) {
98
+ effect.running = true;
99
+ // Run cleanups from previous execution
100
+ for (const cleanup of effect.cleanups) {
101
+ cleanup();
102
+ }
103
+ effect.cleanups.length = 0;
104
+ context.push(effect);
105
+ try {
106
+ // Support Solid-style `return () => {...}` cleanup functions. Many
107
+ // components (Slider, Dropdown, Dialog, Tooltip) register their document
108
+ // listeners in an effect and return a cleanup that removes them; without
109
+ // capturing the return value those listeners leak and the component never
110
+ // "unsubscribes" (e.g. a slider that can't stop dragging).
111
+ const ret = effect.fn();
112
+ if (typeof ret === 'function') {
113
+ effect.cleanups.push(ret);
114
+ }
115
+ }
116
+ finally {
117
+ context.pop();
118
+ effect.running = false;
119
+ }
120
+ }
121
+ export function createEffect(fn) {
122
+ const effect = newEffectState(fn);
123
+ allEffects.add(effect);
124
+ runEffect(effect);
125
+ return () => {
126
+ disposeEffect(effect);
127
+ allEffects.delete(effect);
128
+ };
129
+ }
130
+ export function onCleanup(fn) {
131
+ const current = context[context.length - 1];
132
+ if (current) {
133
+ current.cleanups.push(fn);
134
+ }
135
+ }
136
+ export function onMount(fn) {
137
+ mountQueue.push(fn);
138
+ if (!mountScheduled) {
139
+ mountScheduled = true;
140
+ queueMicrotask(flushMounts);
141
+ }
142
+ }
143
+ function flushMounts() {
144
+ mountScheduled = false;
145
+ const queue = mountQueue.splice(0);
146
+ for (const fn of queue) {
147
+ fn();
148
+ }
149
+ }
150
+ // createMemo computes a derived value. Its computation effect is registered
151
+ // with the current parent context so it is disposed when the parent re-runs or
152
+ // is disposed (prevents leaks). A value-equality check suppresses propagation
153
+ // when the recomputed value is unchanged, avoiding thundering re-renders.
154
+ export function createMemo(fn) {
155
+ const [get, set] = createSignal(undefined);
156
+ const effect = newEffectState(() => {
157
+ const next = fn();
158
+ set(next);
159
+ });
160
+ allEffects.add(effect);
161
+ // Run the effect to establish subscriptions (pushes to context briefly for tracking)
162
+ runEffect(effect);
163
+ // Register cleanup on the parent context so this memo effect is disposed
164
+ // when the parent re-runs or is disposed.
165
+ const parent = context[context.length - 1];
166
+ if (parent) {
167
+ parent.cleanups.push(() => {
168
+ if (!effect.disposed) {
169
+ disposeEffect(effect);
170
+ allEffects.delete(effect);
171
+ }
172
+ });
173
+ }
174
+ return get;
175
+ }
176
+ export function forwardRef(renderFn) {
177
+ return (props) => renderFn(props, props.ref || (() => { }));
178
+ }
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@krate/runtime",
3
+ "version": "0.1.0",
4
+ "description": "Client-side runtime for Krate — signals, hydration, SPA router, resources, and context.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "homepage": "https://github.com/kratejs/krate",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "https://github.com/kratejs/krate.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/kratejs/krate/issues"
14
+ },
15
+ "keywords": [
16
+ "signals",
17
+ "reactive",
18
+ "ssg",
19
+ "hydration",
20
+ "jsx-runtime",
21
+ "state"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "main": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "default": "./dist/index.js"
32
+ },
33
+ "./server": {
34
+ "types": "./dist/server.d.ts",
35
+ "default": "./dist/server.js"
36
+ },
37
+ "./server/jsx-runtime": {
38
+ "types": "./dist/server-jsx-runtime.d.ts",
39
+ "default": "./dist/server-jsx-runtime.js"
40
+ },
41
+ "./jsx-runtime": {
42
+ "types": "./dist/jsx-runtime.d.ts",
43
+ "default": "./dist/jsx-runtime.js"
44
+ },
45
+ "./jsx-dev-runtime": {
46
+ "types": "./dist/jsx-dev-runtime.d.ts",
47
+ "default": "./dist/jsx-dev-runtime.js"
48
+ },
49
+ "./jsx-types": {
50
+ "types": "./dist/jsx-types.d.ts",
51
+ "default": "./dist/jsx-types.js"
52
+ }
53
+ },
54
+ "files": [
55
+ "dist"
56
+ ],
57
+ "devDependencies": {
58
+ "@types/node": "^26.2.0",
59
+ "esbuild": "^0.25.0",
60
+ "typescript": "^5.5.0"
61
+ },
62
+ "scripts": {
63
+ "build": "tsc && node bundle.cjs",
64
+ "dev": "tsc --watch"
65
+ }
66
+ }