@krate/runtime 0.5.0-alpha.2 → 0.5.0-alpha.3

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 (85) hide show
  1. package/dist/action-context.d.ts +49 -0
  2. package/dist/action-context.js +37 -0
  3. package/dist/action-context.test.d.ts +1 -0
  4. package/dist/action-context.test.js +47 -0
  5. package/dist/actions.d.ts +120 -0
  6. package/dist/actions.js +533 -0
  7. package/dist/actions.test.d.ts +1 -0
  8. package/dist/actions.test.js +391 -0
  9. package/dist/boundary.d.ts +121 -0
  10. package/dist/boundary.js +429 -0
  11. package/dist/class-component.d.ts +66 -0
  12. package/dist/class-component.js +633 -0
  13. package/dist/class-component.test.d.ts +1 -0
  14. package/dist/class-component.test.js +411 -0
  15. package/dist/context.d.ts +13 -0
  16. package/dist/context.js +58 -32
  17. package/dist/context.test.d.ts +1 -0
  18. package/dist/context.test.js +57 -0
  19. package/dist/derived.test.d.ts +1 -0
  20. package/dist/derived.test.js +140 -0
  21. package/dist/discrete.test.d.ts +1 -0
  22. package/dist/discrete.test.js +100 -0
  23. package/dist/dom.d.ts +55 -0
  24. package/dist/dom.js +414 -63
  25. package/dist/effects.d.ts +88 -0
  26. package/dist/effects.js +719 -0
  27. package/dist/effects.test.d.ts +1 -0
  28. package/dist/effects.test.js +485 -0
  29. package/dist/events.d.ts +58 -0
  30. package/dist/events.js +503 -0
  31. package/dist/events.test.d.ts +1 -0
  32. package/dist/events.test.js +447 -0
  33. package/dist/index.d.ts +12 -2
  34. package/dist/index.js +8 -2
  35. package/dist/jsx-types.d.ts +2 -0
  36. package/dist/krate-hydrate-lite.js +7 -1
  37. package/dist/krate-hydrate.js +7 -1
  38. package/dist/krate-runtime.js +7 -1
  39. package/dist/krate-suspense.js +2 -0
  40. package/dist/lanes.test.d.ts +1 -0
  41. package/dist/lanes.test.js +59 -0
  42. package/dist/list.d.ts +20 -0
  43. package/dist/list.js +466 -0
  44. package/dist/list.test.d.ts +1 -0
  45. package/dist/list.test.js +344 -0
  46. package/dist/optimistic-lanes.test.d.ts +1 -0
  47. package/dist/optimistic-lanes.test.js +45 -0
  48. package/dist/portal.d.ts +43 -0
  49. package/dist/portal.js +178 -0
  50. package/dist/portal.test.d.ts +1 -0
  51. package/dist/portal.test.js +99 -0
  52. package/dist/react-effects.test.d.ts +1 -0
  53. package/dist/react-effects.test.js +96 -0
  54. package/dist/react-suspense.test.d.ts +1 -0
  55. package/dist/react-suspense.test.js +194 -0
  56. package/dist/react.d.ts +132 -32
  57. package/dist/react.js +335 -81
  58. package/dist/react.test.js +12 -2
  59. package/dist/reconcile.js +13 -0
  60. package/dist/refs.d.ts +33 -0
  61. package/dist/refs.js +142 -0
  62. package/dist/refs.test.d.ts +1 -0
  63. package/dist/refs.test.js +257 -0
  64. package/dist/resource.js +20 -1
  65. package/dist/server-renderer.js +39 -1
  66. package/dist/server.d.ts +4 -1
  67. package/dist/server.js +30 -1
  68. package/dist/server.test.js +20 -0
  69. package/dist/signal-lanes.test.d.ts +1 -0
  70. package/dist/signal-lanes.test.js +32 -0
  71. package/dist/signal.d.ts +150 -1
  72. package/dist/signal.js +750 -65
  73. package/dist/slots.d.ts +18 -0
  74. package/dist/slots.js +108 -0
  75. package/dist/slots.test.d.ts +1 -0
  76. package/dist/slots.test.js +169 -0
  77. package/dist/snapshots.test.d.ts +1 -0
  78. package/dist/snapshots.test.js +208 -0
  79. package/dist/suspense-actions.test.d.ts +1 -0
  80. package/dist/suspense-actions.test.js +72 -0
  81. package/dist/suspense.d.ts +220 -0
  82. package/dist/suspense.js +901 -0
  83. package/dist/suspense.test.d.ts +1 -0
  84. package/dist/suspense.test.js +518 -0
  85. package/package.json +1 -1
package/dist/refs.js ADDED
@@ -0,0 +1,142 @@
1
+ /**
2
+ * React ref semantics for elements and imperative handles.
3
+ *
4
+ * - Object refs get `current = node` on attach and `current = null` on detach.
5
+ * - Callback refs are called with the node on attach. On detach, a React 19
6
+ * cleanup function returned by the callback is called instead; otherwise the
7
+ * callback is called with null.
8
+ * - A ref that is neither (a plain variable target) uses the `assign` setter.
9
+ *
10
+ * Every attached element ref is registered so a conditional branch swapped out
11
+ * of the document detaches its refs and swapping it back re-attaches them
12
+ * (krateRefsLeave / krateRefsEnter). Refs are called untracked, so a callback
13
+ * reading signals never subscribes the surrounding effect.
14
+ */
15
+ import { createEffect } from './signal.js';
16
+ const live = new Set();
17
+ function untracked(fn) {
18
+ // A throwaway effect gives fn its own (discarded) tracking scope.
19
+ let err;
20
+ let failed = false;
21
+ createEffect(() => {
22
+ try {
23
+ fn();
24
+ }
25
+ catch (x) {
26
+ err = x;
27
+ failed = true;
28
+ }
29
+ })();
30
+ if (failed)
31
+ throw err;
32
+ }
33
+ function attach(e) {
34
+ if (e.on)
35
+ return;
36
+ e.on = true;
37
+ const r = e.ref;
38
+ untracked(() => {
39
+ if (typeof r === 'function') {
40
+ const ret = r(e.el);
41
+ e.undo = typeof ret === 'function' ? ret : () => r(null);
42
+ }
43
+ else if (r && typeof r === 'object') {
44
+ r.current = e.el;
45
+ e.undo = () => {
46
+ r.current = null;
47
+ };
48
+ }
49
+ else if (e.assign) {
50
+ const set = e.assign;
51
+ set(e.el);
52
+ e.undo = () => set(null);
53
+ }
54
+ else {
55
+ e.undo = null;
56
+ }
57
+ });
58
+ }
59
+ function detach(e) {
60
+ if (!e.on)
61
+ return;
62
+ e.on = false;
63
+ const undo = e.undo;
64
+ e.undo = null;
65
+ if (undo)
66
+ untracked(undo);
67
+ }
68
+ /**
69
+ * Attaches `value` (an element or an imperative handle) to `ref` and returns
70
+ * the detach function. Used by useImperativeHandle.
71
+ */
72
+ export function krateSetRef(ref, value) {
73
+ const e = { el: value, ref, on: false, undo: null };
74
+ attach(e);
75
+ return () => detach(e);
76
+ }
77
+ // Hydration refs waiting for krateRefsFlush; null when no hydration script is
78
+ // holding them.
79
+ let deferred = null;
80
+ /**
81
+ * Starts holding hydration refs (called at the start of a page's hydration
82
+ * script) until krateRefsFlush. Components mounted later attach at once.
83
+ */
84
+ export function krateRefsHold() {
85
+ if (deferred)
86
+ return;
87
+ deferred = [];
88
+ // Safety net if the script stops before its flush.
89
+ queueMicrotask(krateRefsFlush);
90
+ }
91
+ /**
92
+ * Attaches the hydration refs queued so far whose element is in the
93
+ * document. The hydration script calls it after every component has bound its
94
+ * DOM (and before the effect commit), so a ref on server-rendered content that
95
+ * a binding replaced (a re-rendered list) is never attached, as in React.
96
+ */
97
+ export function krateRefsFlush() {
98
+ const list = deferred;
99
+ deferred = null;
100
+ if (!list)
101
+ return;
102
+ for (const e of list) {
103
+ if (live.has(e) && e.el.isConnected)
104
+ attach(e);
105
+ }
106
+ }
107
+ /**
108
+ * Registers an element ref. mode 'now' attaches immediately (a node built by
109
+ * h() that is about to be inserted); 'defer' queues it for krateRefsFlush
110
+ * while a hydration script holds refs (krateRefsHold); otherwise it attaches when the element is in the document. A
111
+ * ref on a detached node waits until a conditional branch holding it is
112
+ * shown. Returns the release function (detach plus unregister), safe to call
113
+ * more than once.
114
+ */
115
+ export function krateAttachRef(el, ref, assign, mode) {
116
+ const e = { el, ref, assign, on: false, undo: null };
117
+ live.add(e);
118
+ if (mode === 'defer' && deferred) {
119
+ deferred.push(e);
120
+ }
121
+ else if (mode === 'now' || el.isConnected) {
122
+ attach(e);
123
+ }
124
+ return () => {
125
+ live.delete(e);
126
+ detach(e);
127
+ };
128
+ }
129
+ /** Detaches refs of registered elements inside `root` (a branch leaving the document). */
130
+ export function krateRefsLeave(root) {
131
+ for (const e of live) {
132
+ if (e.on && root.contains(e.el))
133
+ detach(e);
134
+ }
135
+ }
136
+ /** Attaches registered refs whose element is now in the document. */
137
+ export function krateRefsEnter() {
138
+ for (const e of live) {
139
+ if (!e.on && e.el.isConnected)
140
+ attach(e);
141
+ }
142
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,257 @@
1
+ import { describe, it, expect, beforeEach } from 'vitest';
2
+ import { readFileSync } from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { dirname, resolve } from 'node:path';
5
+ import { krateAttachRef, krateSetRef, krateRefsFlush, krateRefsHold } from './refs';
6
+ import { krateBindRef, h, disposeNode, krateOn, krateControl } from './dom';
7
+ import { createSignal, createEffect, onCleanup, disposeAll } from './signal';
8
+ import { krateCondSwap, krateCondDetached, krateCondReset, krateSanitizeAttr } from './slots';
9
+ import { useImperativeHandle, createRef } from './react';
10
+ const tick = () => new Promise((r) => setTimeout(r, 0));
11
+ function bootstrap() {
12
+ const here = dirname(fileURLToPath(import.meta.url));
13
+ const src = readFileSync(resolve(here, '../../compiler/internal/renderer/newhydrate.go'), 'utf8');
14
+ const start = src.indexOf('const HydrationBootstrapJS = `') + 'const HydrationBootstrapJS = `'.length;
15
+ const end = src.indexOf('`\n', start);
16
+ new Function(src.slice(start, end))();
17
+ }
18
+ describe('element refs', () => {
19
+ beforeEach(() => {
20
+ document.body.innerHTML = '<div id="root"><input id="i"></div>';
21
+ });
22
+ it('sets and clears object refs', () => {
23
+ const el = document.getElementById('i');
24
+ const ref = { current: null };
25
+ const release = krateAttachRef(el, ref);
26
+ expect(ref.current).toBe(el);
27
+ release();
28
+ expect(ref.current).toBe(null);
29
+ });
30
+ it('calls callback refs with the node, then null', () => {
31
+ const el = document.getElementById('i');
32
+ const calls = [];
33
+ const release = krateAttachRef(el, (n) => {
34
+ calls.push(n);
35
+ });
36
+ release();
37
+ release();
38
+ expect(calls).toEqual([el, null]);
39
+ });
40
+ it('calls a React 19 cleanup function instead of null', () => {
41
+ const el = document.getElementById('i');
42
+ const log = [];
43
+ const release = krateAttachRef(el, () => {
44
+ log.push('attach');
45
+ return () => log.push('cleanup');
46
+ });
47
+ release();
48
+ expect(log).toEqual(['attach', 'cleanup']);
49
+ });
50
+ it('re-binds when the callback identity changes', async () => {
51
+ const el = document.getElementById('i');
52
+ const log = [];
53
+ const a = (n) => log.push('a ' + (n ? 'node' : 'null'));
54
+ const b = (n) => log.push('b ' + (n ? 'node' : 'null'));
55
+ const [which, setWhich] = createSignal(a);
56
+ const dispose = krateBindRef(el, () => which());
57
+ krateRefsFlush();
58
+ setWhich(() => b);
59
+ await tick();
60
+ dispose();
61
+ expect(log).toEqual(['a node', 'a null', 'b node', 'b null']);
62
+ });
63
+ it('does not subscribe to signals read inside a callback ref', async () => {
64
+ const el = document.getElementById('i');
65
+ const [n, setN] = createSignal(0);
66
+ let calls = 0;
67
+ krateBindRef(el, () => () => {
68
+ calls++;
69
+ n();
70
+ });
71
+ setN(1);
72
+ await tick();
73
+ expect(calls).toBe(1);
74
+ });
75
+ it('assigns plain variable targets through the setter', () => {
76
+ const el = document.getElementById('i');
77
+ let target = undefined;
78
+ krateRefsHold();
79
+ const dispose = krateBindRef(el, () => undefined, (v) => {
80
+ target = v;
81
+ });
82
+ // Hydration binds queue until the flush at the end of the page script.
83
+ expect(target).toBe(undefined);
84
+ krateRefsFlush();
85
+ expect(target).toBe(el);
86
+ dispose();
87
+ expect(target).toBe(null);
88
+ });
89
+ it('keeps the right element per list item and detaches removed items', async () => {
90
+ const root = document.getElementById('root');
91
+ const refs = new Map();
92
+ const [items, setItems] = createSignal([1, 2, 3]);
93
+ const ul = document.createElement('ul');
94
+ root.appendChild(ul);
95
+ createEffect(() => {
96
+ while (ul.firstChild) {
97
+ disposeNode(ul.firstChild);
98
+ ul.removeChild(ul.firstChild);
99
+ }
100
+ for (const i of items()) {
101
+ ul.appendChild(h('li', { ref: (el) => (el ? refs.set(i, el) : refs.delete(i)) }, String(i)));
102
+ }
103
+ });
104
+ expect([...refs.keys()]).toEqual([1, 2, 3]);
105
+ expect(refs.get(2).textContent).toBe('2');
106
+ setItems([1, 3]);
107
+ await tick();
108
+ expect([...refs.keys()].sort()).toEqual([1, 3]);
109
+ expect(refs.get(3).textContent).toBe('3');
110
+ });
111
+ it('releases h() refs when the node is disposed', () => {
112
+ const ref = { current: null };
113
+ const el = h('div', { ref });
114
+ expect(ref.current).toBe(el);
115
+ disposeNode(el);
116
+ expect(ref.current).toBe(null);
117
+ });
118
+ });
119
+ describe('imperative handles', () => {
120
+ it('attaches the handle and re-creates it when deps change', async () => {
121
+ const ref = createRef();
122
+ const [n, setN] = createSignal(1);
123
+ let creates = 0;
124
+ const [other, setOther] = createSignal(0);
125
+ createEffect(() => {
126
+ useImperativeHandle(ref, () => {
127
+ creates++;
128
+ other();
129
+ return { v: n() };
130
+ }, () => [n()]);
131
+ });
132
+ // Handles attach in the layout phase of the commit (a microtask).
133
+ expect(ref.current).toBe(null);
134
+ await Promise.resolve();
135
+ expect(ref.current).toEqual({ v: 1 });
136
+ setOther(1);
137
+ await tick();
138
+ expect(creates).toBe(1);
139
+ setN(2);
140
+ await tick();
141
+ expect(ref.current).toEqual({ v: 2 });
142
+ expect(creates).toBe(2);
143
+ });
144
+ it('gives callback refs the handle and cleans up', () => {
145
+ const log = [];
146
+ const undo = krateSetRef((v) => {
147
+ log.push(v);
148
+ }, { focus: 1 });
149
+ undo();
150
+ expect(log).toEqual([{ focus: 1 }, null]);
151
+ });
152
+ });
153
+ describe('hydration bootstrap refs and events', () => {
154
+ beforeEach(() => {
155
+ const w = window;
156
+ Object.assign(w, {
157
+ createEffect,
158
+ onCleanup,
159
+ createSignal,
160
+ krateCondSwap,
161
+ krateCondDetached,
162
+ krateCondReset,
163
+ krateSanitizeAttr,
164
+ krateBindRef,
165
+ krateOn,
166
+ krateControl,
167
+ });
168
+ });
169
+ it('attaches refs before queued effects and detaches on teardown', () => {
170
+ document.body.innerHTML = '<div id="root"><input data-k="k:i"></div>';
171
+ bootstrap();
172
+ const w = window;
173
+ const ref = { current: null };
174
+ const log = [];
175
+ w.kbindRef('i', () => ref, (v) => (ref.current = v));
176
+ krateRefsFlush();
177
+ createEffect(() => {
178
+ log.push(ref.current);
179
+ });
180
+ expect(log[0]).toBe(document.querySelector('input'));
181
+ disposeAll();
182
+ expect(ref.current).toBe(null);
183
+ });
184
+ it('detaches refs of a hidden conditional branch and re-attaches when shown', async () => {
185
+ document.body.innerHTML =
186
+ '<div id="root"><p><!--k:c--><span data-k="k:s">on</span><!--/k:c--></p>' +
187
+ '<template data-kc="c" data-kb="a"><i data-k="k:o">off</i></template></div>';
188
+ bootstrap();
189
+ const w = window;
190
+ const log = [];
191
+ const [on, setOn] = createSignal(true);
192
+ w.kbindCond('c', () => on());
193
+ w.kbindRef('s', () => (el) => log.push('s ' + (el ? el.tagName : 'null')));
194
+ w.kbindRef('o', () => (el) => log.push('o ' + (el ? el.tagName : 'null')));
195
+ krateRefsFlush();
196
+ expect(log).toEqual(['s SPAN']);
197
+ setOn(false);
198
+ await tick();
199
+ expect(log).toEqual(['s SPAN', 's null', 'o I']);
200
+ setOn(true);
201
+ await tick();
202
+ expect(log).toEqual(['s SPAN', 's null', 'o I', 'o null', 's SPAN']);
203
+ disposeAll();
204
+ });
205
+ it('stringifies boolean aria-* and data-* attribute bindings', async () => {
206
+ document.body.innerHTML = '<div id="root"><input data-k="k:i"></div>';
207
+ bootstrap();
208
+ const [bad, setBad] = createSignal(false);
209
+ window.kbindAttr('i', 'aria-invalid', () => bad());
210
+ const input = document.querySelector('input');
211
+ expect(input.getAttribute('aria-invalid')).toBe('false');
212
+ setBad(true);
213
+ await tick();
214
+ expect(input.getAttribute('aria-invalid')).toBe('true');
215
+ disposeAll();
216
+ });
217
+ it('binds handlers and controlled values', () => {
218
+ document.body.innerHTML = '<div id="root"><input data-k="k:i" value="a"></div>';
219
+ bootstrap();
220
+ const w = window;
221
+ const log = [];
222
+ w.kbindHandler('i', 'onChange', (e) => log.push(e.type + ' ' + e.target.value));
223
+ w.kbindProp('i', 'value', () => 'a');
224
+ const input = document.querySelector('input');
225
+ input.value = 'ab';
226
+ input.dispatchEvent(new Event('input', { bubbles: true }));
227
+ expect(log).toEqual(['change ab']);
228
+ expect(input.value).toBe('a');
229
+ disposeAll();
230
+ });
231
+ });
232
+ describe('hydration ref queue', () => {
233
+ it('never attaches refs of server-rendered nodes replaced before the flush', () => {
234
+ document.body.innerHTML = '<div id="root"><ul><li id="ssr">a</li></ul></div>';
235
+ const log = [];
236
+ const ssr = document.getElementById('ssr');
237
+ krateRefsHold();
238
+ krateBindRef(ssr, () => (n) => {
239
+ log.push('ssr ' + (n ? 'node' : 'null'));
240
+ });
241
+ // A list binding replaces the server-rendered item before the flush.
242
+ disposeNode(ssr);
243
+ ssr.remove();
244
+ const fresh = h('li', { ref: (n) => log.push('fresh ' + (n ? 'node' : 'null')) });
245
+ document.querySelector('ul').appendChild(fresh);
246
+ krateRefsFlush();
247
+ expect(log).toEqual(['fresh node']);
248
+ });
249
+ });
250
+ describe('refs outside hydration', () => {
251
+ it('attach at once for a component mounted after hydration', () => {
252
+ document.body.innerHTML = '<div id="root"><input id="late"></div>';
253
+ const ref = { current: null };
254
+ krateBindRef(document.getElementById('late'), () => ref);
255
+ expect(ref.current).toBe(document.getElementById('late'));
256
+ });
257
+ });
package/dist/resource.js CHANGED
@@ -1,4 +1,7 @@
1
1
  import { createSignal, createEffect, onCleanup } from './signal.js';
2
+ function suspenseHook() {
3
+ return globalThis.__krateSuspenseHook;
4
+ }
2
5
  export function createResource(source, fetcher) {
3
6
  const [data, setData] = createSignal(undefined);
4
7
  const [loading, setLoading] = createSignal(true);
@@ -6,10 +9,22 @@ export function createResource(source, fetcher) {
6
9
  const [state, setState] = createSignal('unresolved');
7
10
  const [version, setVersion] = createSignal(0);
8
11
  let abortController;
12
+ const owner = suspenseHook()?.current() ?? null;
13
+ let inflight = null;
14
+ let notified = null;
9
15
  const getSourceValue = () => {
10
16
  return typeof source === 'function' ? source() : source;
11
17
  };
12
- const fetch = async () => {
18
+ const fetch = () => {
19
+ const run = doFetch();
20
+ inflight = run;
21
+ run.then(() => {
22
+ if (inflight === run)
23
+ inflight = null;
24
+ });
25
+ return run;
26
+ };
27
+ const doFetch = async () => {
13
28
  if (abortController) {
14
29
  abortController.abort();
15
30
  }
@@ -61,6 +76,10 @@ export function createResource(source, fetcher) {
61
76
  // as a plain data property, snapshotting state/loading/error once at creation
62
77
  // so they never track reactive updates. defineProperties installs live accessors.
63
78
  const resource = function () {
79
+ if (owner && inflight && notified !== inflight) {
80
+ notified = inflight;
81
+ suspenseHook()?.suspend(owner, inflight);
82
+ }
64
83
  return data();
65
84
  };
66
85
  Object.defineProperties(resource, {
@@ -16,9 +16,21 @@ const isClusterPrimary = SSR_WORKERS > 1 && cluster.isPrimary;
16
16
  if (isClusterPrimary) {
17
17
  for (let i = 0; i < SSR_WORKERS; i++)
18
18
  cluster.fork();
19
+ // Restart a worker that dies, after a short delay, but give up when they
20
+ // keep dying (a port that stays unbindable, a broken bundle) instead of
21
+ // forking forever. The delay also gives a briefly busy port time to free up.
22
+ const exits = [];
19
23
  cluster.on("exit", (worker) => {
20
24
  console.log(`[krate-ssr] worker ${worker.process.pid} exited; restarting`);
21
- cluster.fork();
25
+ const now = Date.now();
26
+ exits.push(now);
27
+ while (exits.length && now - exits[0] > 60000)
28
+ exits.shift();
29
+ if (exits.length > 100) {
30
+ console.error("[krate-ssr] workers keep exiting; giving up");
31
+ process.exit(1);
32
+ }
33
+ setTimeout(() => cluster.fork(), 100);
22
34
  });
23
35
  console.log(`[krate-ssr] primary supervising ${SSR_WORKERS} workers`);
24
36
  }
@@ -765,6 +777,32 @@ if (isClusterPrimary) {
765
777
  // The primary only supervises; workers own the listening socket.
766
778
  }
767
779
  else {
780
+ // The port was free when Go chose it, but a bind can still fail with
781
+ // EADDRINUSE: any socket holding that local port blocks the wildcard bind,
782
+ // including a short-lived outgoing connection. A clustered worker exits
783
+ // quietly so the primary respawns it after a delay (listening again after a
784
+ // failed cluster listen trips a Node assertion on Windows); a standalone
785
+ // server retries the bind for a few seconds.
786
+ let bindRetries = 100;
787
+ server.on("error", (err) => {
788
+ if (err.code === "EADDRINUSE") {
789
+ if (cluster.isWorker)
790
+ process.exit(1);
791
+ if (bindRetries-- > 0) {
792
+ setTimeout(() => {
793
+ try {
794
+ server.close();
795
+ }
796
+ catch {
797
+ // not listening yet
798
+ }
799
+ server.listen(PORT);
800
+ }, 100);
801
+ return;
802
+ }
803
+ }
804
+ throw err;
805
+ });
768
806
  server.listen(PORT, () => {
769
807
  console.log(`[krate-ssr] Renderer server listening on port ${PORT}`);
770
808
  });
package/dist/server.d.ts CHANGED
@@ -1,6 +1,10 @@
1
+ export { getActionContext, headers, cookies, redirect } from './action-context.js';
2
+ export type { ActionContext, ActionCookies, ActionCookieOptions } from './action-context.js';
1
3
  export declare function createSignal<T>(initial: T): [() => T, (v: T | ((prev: T) => T)) => void];
2
4
  export declare function createEffect(_fn: () => void): () => void;
3
5
  export declare function createMemo<T>(fn: () => T): () => T;
6
+ export declare function krateDerived<T>(fn: () => T, _triggers?: () => unknown): () => T;
7
+ export declare function krateHook<T>(value: T | (() => T)): () => T;
4
8
  export declare function onCleanup(_fn: () => void): void;
5
9
  export declare function onMount(_fn: () => void): void;
6
10
  interface RawHTML {
@@ -59,4 +63,3 @@ export declare function SyntaxHighlight(props: {
59
63
  lang?: string;
60
64
  children?: any;
61
65
  }): JSXNode;
62
- export {};
package/dist/server.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // @krate/runtime/server - Server-side rendering runtime
2
2
  // Provides the same API as the client runtime but renders to HTML strings.
3
+ export { getActionContext, headers, cookies, redirect } from './action-context.js';
3
4
  // Signal (server: returns initial value, no reactivity)
4
5
  export function createSignal(initial) {
5
6
  let value = initial;
@@ -24,6 +25,19 @@ export function createMemo(fn) {
24
25
  return cached;
25
26
  };
26
27
  }
28
+ // Derived render values (krateDerived) and custom hook results (krateHook)
29
+ // have no dependencies to track on the server: each read recomputes.
30
+ const derivedGetters = new WeakSet();
31
+ export function krateDerived(fn, _triggers) {
32
+ const read = () => fn();
33
+ derivedGetters.add(read);
34
+ return read;
35
+ }
36
+ export function krateHook(value) {
37
+ if (typeof value === "function" && derivedGetters.has(value))
38
+ return value;
39
+ return () => value;
40
+ }
27
41
  export function onCleanup(_fn) {
28
42
  // No-op on server
29
43
  }
@@ -107,11 +121,23 @@ function renderNode(node) {
107
121
  return renderElement(node);
108
122
  return "";
109
123
  }
124
+ function isServerAction(v) {
125
+ return typeof v === "function" && typeof v.actionUrl === "string";
126
+ }
110
127
  function setAttr(key, val) {
111
128
  if (val == null || val === false)
112
129
  return "";
113
130
  if (val === true)
114
131
  return ` ${key}`;
132
+ if (key === "action" && isServerAction(val)) {
133
+ return ` action="${escapeHTML(val.actionUrl)}" data-krate-action`;
134
+ }
135
+ if ((key === "formAction" || key === "formaction") && isServerAction(val)) {
136
+ return ` formaction="${escapeHTML(val.actionUrl)}" formmethod="post" data-krate-action`;
137
+ }
138
+ // Client function actions run only after hydration; they have no HTML form.
139
+ if (typeof val === "function")
140
+ return "";
115
141
  if (key === "class")
116
142
  return ` class="${escapeHTML(String(val))}"`;
117
143
  if (key === "style" && typeof val === "object") {
@@ -136,7 +162,10 @@ function renderElement(el) {
136
162
  }
137
163
  // HTML element
138
164
  const tag = type;
139
- const attrs = Object.entries(props)
165
+ const renderProps = tag === "form" && isServerAction(props.action) && props.method == null
166
+ ? { ...props, method: "post" }
167
+ : props;
168
+ const attrs = Object.entries(renderProps)
140
169
  .map(([k, v]) => setAttr(k, v))
141
170
  .join("");
142
171
  if (VOID_ELEMENTS.has(tag)) {
@@ -46,3 +46,23 @@ describe('goComponent', () => {
46
46
  expect(renderToString(node)).toMatch(/^<!--krate-go:Badge:0:/);
47
47
  });
48
48
  });
49
+ describe('server actions', () => {
50
+ it('renders an action function as a POST form endpoint', () => {
51
+ const action = Object.assign(() => undefined, {
52
+ actionUrl: '/base/__krate/action/a123',
53
+ });
54
+ const html = renderToString(jsx('form', { action, children: [] }));
55
+ expect(html).toContain('action="/base/__krate/action/a123"');
56
+ expect(html).toContain('method="post"');
57
+ expect(html).toContain('data-krate-action');
58
+ });
59
+ it('renders a formAction function as a POST submit endpoint', () => {
60
+ const action = Object.assign(() => undefined, {
61
+ actionUrl: '/__krate/action/a456',
62
+ });
63
+ const html = renderToString(jsx('button', { formAction: action, children: 'go' }));
64
+ expect(html).toContain('formaction="/__krate/action/a456"');
65
+ expect(html).toContain('formmethod="post"');
66
+ expect(html).toContain('data-krate-action');
67
+ });
68
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,32 @@
1
+ import { describe, it, expect, beforeEach } from 'vitest';
2
+ // Only signal.ts: the commit snapshot of React state must not depend on the
3
+ // effect scheduler (effects.ts) being loaded.
4
+ import { createSignal, createEffect, disposeAll, krateHookState } from './signal';
5
+ const tick = () => new Promise((r) => setTimeout(r, 0));
6
+ async function settle() {
7
+ for (let i = 0; i < 4; i++)
8
+ await tick();
9
+ }
10
+ describe('React state commits without the effect scheduler', () => {
11
+ beforeEach(() => disposeAll());
12
+ it('keeps a promise-driven state write when a plain signal is written in a later microtask', async () => {
13
+ const [user, setUser] = createSignal('nobody', krateHookState);
14
+ const [flag, setFlag] = createSignal(false);
15
+ const seen = [];
16
+ createEffect(() => void seen.push(user() + '/' + flag()));
17
+ await Promise.resolve().then(() => {
18
+ setUser('grace');
19
+ queueMicrotask(() => setFlag(true));
20
+ });
21
+ await settle();
22
+ // Read outside rendering: the committed value.
23
+ expect(user()).toBe('grace');
24
+ expect(seen[seen.length - 1]).toBe('grace/true');
25
+ });
26
+ it('commits a state write made outside any event', async () => {
27
+ const [n, setN] = createSignal(0, krateHookState);
28
+ setTimeout(() => setN(4), 0);
29
+ await settle();
30
+ expect(n()).toBe(4);
31
+ });
32
+ });