rosetack 0.0.0 → 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/.github/workflows/ci.yml +72 -0
- package/.github/workflows/release.yml +122 -0
- package/LICENSE +21 -0
- package/benchmark.ts +227 -0
- package/deploy/Dockerfile.node +25 -0
- package/deploy/Dockerfile.static +34 -0
- package/deploy/api/rosetack.ts +29 -0
- package/deploy/docker-compose.yml +33 -0
- package/deploy/fly.toml +28 -0
- package/deploy/vercel.json +13 -0
- package/example/public/favicon.ico +0 -0
- package/example/public/logo.svg +148 -0
- package/example/public/rose-mark-black.png +0 -0
- package/example/public/rose-mark.png +0 -0
- package/example/public/rose-mono.png +0 -0
- package/example/rosetack.config.js +10 -0
- package/example/src/locales/en.json +8 -0
- package/example/src/locales/zh.json +8 -0
- package/example/src/pages/404.rose +15 -0
- package/example/src/pages/500.rose +10 -0
- package/example/src/pages/[lang]/about.rose +40 -0
- package/example/src/pages/_layout.rose +33 -0
- package/example/src/pages/_middleware.rose +37 -0
- package/example/src/pages/about.rose +67 -0
- package/example/src/pages/admin.rose +27 -0
- package/example/src/pages/api/hello.rose +19 -0
- package/example/src/pages/api/login.rose +55 -0
- package/example/src/pages/api/posts.rose +80 -0
- package/example/src/pages/api/secret.rose +14 -0
- package/example/src/pages/blog/[id].rose +25 -0
- package/example/src/pages/broken.rose +16 -0
- package/example/src/pages/fresh.rose +22 -0
- package/example/src/pages/garden.rose +27 -0
- package/example/src/pages/index.rose +84 -0
- package/example/src/pages/sign.rose +45 -0
- package/example/src/pages/thorn.rose +23 -0
- package/example/src/pages/vault.rose +14 -0
- package/go.mod +3 -0
- package/main.go +470 -0
- package/package.json +32 -11
- package/src/FRAMEWORK_VERSION +1 -0
- package/src/cli/edge.ts +127 -0
- package/src/cli/index.ts +777 -0
- package/src/cli/shell.ts +284 -0
- package/src/compiler/index.ts +1990 -0
- package/src/runtime/index.ts +624 -0
- package/tools/release-notes.mjs +113 -0
- package/tsconfig.json +17 -0
- package/README.md +0 -3
- package/index.js +0 -12
|
@@ -0,0 +1,624 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* rosetack Runtime - Zero-hydration, compile-time reactivity
|
|
3
|
+
* Target: < 2KB gzipped
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
// === Reactive Primitives ===
|
|
7
|
+
|
|
8
|
+
type Subscriber = () => void;
|
|
9
|
+
type Cleanup = () => void;
|
|
10
|
+
type SignalEntry = { value: unknown; subs: Set<Subscriber> };
|
|
11
|
+
|
|
12
|
+
let currentEffect: (() => void) | null = null;
|
|
13
|
+
|
|
14
|
+
// ponytail: global signal map, shared across all inlined modules
|
|
15
|
+
let signalMap: Map<string, SignalEntry> =
|
|
16
|
+
(globalThis as any).__rosetack_signalMap ?? new Map();
|
|
17
|
+
(globalThis as any).__rosetack_signalMap = signalMap;
|
|
18
|
+
|
|
19
|
+
// One get-or-create helper shared by state / setState / resumeState.
|
|
20
|
+
function entry(key: string, initial: unknown): { value: unknown; subs: Set<Subscriber> } {
|
|
21
|
+
const e = signalMap.get(key) ?? { value: initial, subs: new Set<Subscriber>() };
|
|
22
|
+
signalMap.set(key, e);
|
|
23
|
+
return e;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function state<T>(key: string, initial: T): [() => T, (v: T) => void] {
|
|
27
|
+
const e = entry(key, initial);
|
|
28
|
+
|
|
29
|
+
const getter = () => {
|
|
30
|
+
if (currentEffect) e.subs.add(currentEffect);
|
|
31
|
+
return e.value as T;
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const setter = (v: T) => {
|
|
35
|
+
e.value = v;
|
|
36
|
+
e.subs.forEach((fn: Subscriber) => fn());
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
return [getter, setter];
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function hasState(key: string): boolean {
|
|
43
|
+
return signalMap.has(key);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function setState<T>(key: string, value: T): void {
|
|
47
|
+
const e = entry(key, value);
|
|
48
|
+
e.value = value;
|
|
49
|
+
e.subs.forEach((fn: Subscriber) => fn());
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Effects are tracked so client-side navigation can dispose the old ones.
|
|
53
|
+
// Each cleanup removes itself, so locally disposed effects do not leak.
|
|
54
|
+
const cleanups = new Set<Cleanup>();
|
|
55
|
+
|
|
56
|
+
export function effect(fn: () => void): Cleanup {
|
|
57
|
+
const wrapped: Subscriber = () => {
|
|
58
|
+
try {
|
|
59
|
+
fn();
|
|
60
|
+
} catch {
|
|
61
|
+
// subscriber may be stale; ignore
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
const prev = currentEffect;
|
|
65
|
+
currentEffect = wrapped;
|
|
66
|
+
fn();
|
|
67
|
+
currentEffect = prev;
|
|
68
|
+
const cleanup: Cleanup = () => {
|
|
69
|
+
signalMap.forEach((e: { subs: Set<Subscriber> }) => e.subs.delete(wrapped));
|
|
70
|
+
cleanups.delete(cleanup);
|
|
71
|
+
};
|
|
72
|
+
cleanups.add(cleanup);
|
|
73
|
+
return cleanup;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// === HTML escaping (server-side interpolation safety) ===
|
|
77
|
+
|
|
78
|
+
const ESC_MAP: Record<string, string> = {
|
|
79
|
+
'&': '&',
|
|
80
|
+
'<': '<',
|
|
81
|
+
'>': '>',
|
|
82
|
+
'"': '"',
|
|
83
|
+
"'": ''',
|
|
84
|
+
};
|
|
85
|
+
|
|
86
|
+
export function esc(v: unknown): string {
|
|
87
|
+
return String(v).replace(/[&<>"']/g, (c) => ESC_MAP[c]);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// === Reactive DOM wiring (client) ===
|
|
91
|
+
|
|
92
|
+
const MARK_RE = /^\u27e6([milh]):(\d+)\u27e7$/;
|
|
93
|
+
const END_RE = /^\u27e6\/([ilh]):(\d+)\u27e7$/;
|
|
94
|
+
|
|
95
|
+
// Comments already handled by a nested wire() pass (e.g. inside an adopted {#if} block)
|
|
96
|
+
// must not be re-processed by the outer pass with the wrong closes array.
|
|
97
|
+
const wired = new WeakSet<Node>();
|
|
98
|
+
|
|
99
|
+
/** Parse an html string into a DocumentFragment. */
|
|
100
|
+
export function tpl(html: string): DocumentFragment {
|
|
101
|
+
const t = document.createElement('template');
|
|
102
|
+
t.innerHTML = html;
|
|
103
|
+
return t.content;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// === Document head (<head> blocks) ===
|
|
107
|
+
|
|
108
|
+
// Marks the head elements rosetack manages, so stale ones can be removed when a route's
|
|
109
|
+
// head changes and user-authored <head> content is never touched.
|
|
110
|
+
const HEAD_ATTR = 'data-rosetack-head';
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Apply one rendered <head> block to the document: <title> replaces the title,
|
|
114
|
+
* <meta>/<link>/<base> are matched by name/property/rel/charset and updated
|
|
115
|
+
* in place (or created). `provided` accumulates the keys of every block in the
|
|
116
|
+
* route's head (a page renders inside its layouts, so several blocks apply per
|
|
117
|
+
* navigation); keys it stops providing are dropped from the document.
|
|
118
|
+
*/
|
|
119
|
+
export function applyHead(html: string, provided: Set<string>): void {
|
|
120
|
+
const frag = tpl(html);
|
|
121
|
+
for (const el of Array.from(frag.children)) {
|
|
122
|
+
const tag = el.tagName.toLowerCase();
|
|
123
|
+
if (tag === 'title') {
|
|
124
|
+
// Manage the title element directly: the document.title setter would update the FIRST
|
|
125
|
+
// title element in tree order …
|
|
126
|
+
let titleEl = document.head.querySelector('title');
|
|
127
|
+
if (!titleEl) {
|
|
128
|
+
titleEl = document.createElement('title');
|
|
129
|
+
document.head.appendChild(titleEl);
|
|
130
|
+
}
|
|
131
|
+
titleEl.textContent = el.textContent ?? '';
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (tag !== 'meta' && tag !== 'link' && tag !== 'base') continue;
|
|
135
|
+
const key = el.getAttribute('name')
|
|
136
|
+
?? el.getAttribute('property')
|
|
137
|
+
?? el.getAttribute('rel')
|
|
138
|
+
?? el.getAttribute('charset');
|
|
139
|
+
if (!key) continue;
|
|
140
|
+
const managed = `${tag}:${key}`;
|
|
141
|
+
provided.add(managed);
|
|
142
|
+
let target = document.head.querySelector(`[${HEAD_ATTR}="${managed}"]`);
|
|
143
|
+
if (!target) {
|
|
144
|
+
target = document.createElement(tag);
|
|
145
|
+
target.setAttribute(HEAD_ATTR, managed);
|
|
146
|
+
document.head.appendChild(target);
|
|
147
|
+
}
|
|
148
|
+
for (const a of Array.from(el.attributes)) target.setAttribute(a.name, a.value);
|
|
149
|
+
target.textContent = el.textContent;
|
|
150
|
+
}
|
|
151
|
+
// Drop managed meta/link/base the new head no longer provides. The title
|
|
152
|
+
// persists across routes that don't declare one (standard SPA behavior).
|
|
153
|
+
document.head.querySelectorAll(`[${HEAD_ATTR}]`).forEach((el) => {
|
|
154
|
+
if (!provided.has(el.getAttribute(HEAD_ATTR)!)) el.remove();
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** Drop every rosetack-managed head element (routes without <head> blocks). */
|
|
159
|
+
export function clearHead(): void {
|
|
160
|
+
document.head.querySelectorAll(`[${HEAD_ATTR}]`).forEach((el) => el.remove());
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Wire reactive markers inside `root` to the closures in `closes`.
|
|
165
|
+
* Works on the live SSR DOM (adoption) and on freshly parsed fragments.
|
|
166
|
+
* Returns a disposer for every effect it created.
|
|
167
|
+
*/
|
|
168
|
+
export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Cleanup {
|
|
169
|
+
let holder: Node = root;
|
|
170
|
+
if (root.nodeType === 11) {
|
|
171
|
+
// DocumentFragment: wrap so querySelectorAll sees the root element too
|
|
172
|
+
const div = document.createElement('div');
|
|
173
|
+
div.appendChild(root);
|
|
174
|
+
holder = div;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const created: Cleanup[] = [];
|
|
178
|
+
const weff = (fn: () => void) => created.push(effect(fn));
|
|
179
|
+
|
|
180
|
+
const comments: Comment[] = [];
|
|
181
|
+
const walker = document.createTreeWalker(holder, NodeFilter.SHOW_COMMENT);
|
|
182
|
+
while (walker.nextNode()) comments.push(walker.currentNode as Comment);
|
|
183
|
+
|
|
184
|
+
const ends = new Map<number, Comment>();
|
|
185
|
+
for (const c of comments) {
|
|
186
|
+
const m = (c.nodeValue ?? '').match(END_RE);
|
|
187
|
+
if (m) ends.set(+m[2], c);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Head blocks are collected during the walk and applied afterwards in REVERSE document
|
|
191
|
+
// order: a page renders inside its layout's <slot/> …
|
|
192
|
+
const headBlocks: Array<{ idx: number; start: Comment; end: Comment; nodes: ChildNode[] }> = [];
|
|
193
|
+
const headProvided = new Set<string>();
|
|
194
|
+
|
|
195
|
+
for (const c of comments) {
|
|
196
|
+
if (wired.has(c) || !c.parentNode) continue;
|
|
197
|
+
wired.add(c);
|
|
198
|
+
const m = (c.nodeValue ?? '').match(MARK_RE);
|
|
199
|
+
if (!m) continue;
|
|
200
|
+
const kind = m[1];
|
|
201
|
+
const idx = +m[2];
|
|
202
|
+
|
|
203
|
+
if (kind === 'h') {
|
|
204
|
+
// Document head: the closure re-renders the <head> block (no inner
|
|
205
|
+
// markers), so one effect drives title/meta for this route.
|
|
206
|
+
const end = ends.get(idx);
|
|
207
|
+
if (!end) continue;
|
|
208
|
+
const nodes: ChildNode[] = [];
|
|
209
|
+
let n: ChildNode | null = c.nextSibling;
|
|
210
|
+
while (n && n !== end) {
|
|
211
|
+
const nx = n.nextSibling;
|
|
212
|
+
nodes.push(n);
|
|
213
|
+
n = nx;
|
|
214
|
+
}
|
|
215
|
+
headBlocks.push({ idx, start: c, end, nodes });
|
|
216
|
+
} else if (kind === 'm') {
|
|
217
|
+
// Text: update the text node that follows the marker comment
|
|
218
|
+
let target = c.nextSibling;
|
|
219
|
+
if (!target || target.nodeType !== 3) {
|
|
220
|
+
target = document.createTextNode('');
|
|
221
|
+
c.parentNode!.insertBefore(target, c.nextSibling);
|
|
222
|
+
}
|
|
223
|
+
const tn = target as Text;
|
|
224
|
+
weff(() => {
|
|
225
|
+
tn.nodeValue = String((closes[idx] as (s?: unknown) => unknown)(scope));
|
|
226
|
+
});
|
|
227
|
+
} else if (kind === 'i') {
|
|
228
|
+
// Conditional block: first run adopts the server-rendered content in
|
|
229
|
+
// place (node identity preserved); later runs swap in a fresh clone.
|
|
230
|
+
const anchor = c;
|
|
231
|
+
const end = ends.get(idx);
|
|
232
|
+
if (!end) continue;
|
|
233
|
+
const st = anchor as unknown as { __st?: { nodes: Node[]; disp: Cleanup }; __ever?: boolean };
|
|
234
|
+
weff(() => {
|
|
235
|
+
if (st.__st) {
|
|
236
|
+
st.__st.nodes.forEach((n) => (n as ChildNode).remove());
|
|
237
|
+
st.__st.disp();
|
|
238
|
+
st.__st = undefined;
|
|
239
|
+
}
|
|
240
|
+
const r = (closes[idx] as (s?: unknown) => unknown)(scope) as { html: string; closes: unknown[] } | null;
|
|
241
|
+
if (!r) return;
|
|
242
|
+
// First run adopts the server-rendered content (move out, wire, move back -
|
|
243
|
+
// identity preserved); later runs clone the block template.
|
|
244
|
+
let frag: DocumentFragment;
|
|
245
|
+
if (st.__ever) {
|
|
246
|
+
frag = tpl(r.html);
|
|
247
|
+
} else {
|
|
248
|
+
st.__ever = true;
|
|
249
|
+
frag = document.createDocumentFragment();
|
|
250
|
+
let n = anchor.nextSibling;
|
|
251
|
+
while (n && n !== end) {
|
|
252
|
+
const nx = n.nextSibling;
|
|
253
|
+
frag.appendChild(n);
|
|
254
|
+
n = nx;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
const disp = wire(frag, r.closes, scope);
|
|
258
|
+
const nodes = Array.from(frag.childNodes);
|
|
259
|
+
const parent = anchor.parentNode!;
|
|
260
|
+
for (const nd of nodes) parent.insertBefore(nd, anchor.nextSibling);
|
|
261
|
+
st.__st = { nodes, disp };
|
|
262
|
+
});
|
|
263
|
+
} else {
|
|
264
|
+
// List: rebuild items between the start and end anchors
|
|
265
|
+
const start = c;
|
|
266
|
+
const end = ends.get(idx);
|
|
267
|
+
if (!end) continue;
|
|
268
|
+
const st = start as unknown as { __disp?: Cleanup };
|
|
269
|
+
weff(() => {
|
|
270
|
+
if (st.__disp) {
|
|
271
|
+
st.__disp();
|
|
272
|
+
st.__disp = undefined;
|
|
273
|
+
}
|
|
274
|
+
const items = (closes[idx] as (s?: unknown) => unknown)(scope) as Array<{ html: string; closes: unknown[]; scope?: unknown }>;
|
|
275
|
+
let n = start.nextSibling;
|
|
276
|
+
while (n && n !== end) {
|
|
277
|
+
const nx = n.nextSibling;
|
|
278
|
+
n.remove();
|
|
279
|
+
n = nx;
|
|
280
|
+
}
|
|
281
|
+
const parent = start.parentNode!;
|
|
282
|
+
const disps: Cleanup[] = [];
|
|
283
|
+
for (const r of items) {
|
|
284
|
+
const frag = tpl(r.html);
|
|
285
|
+
disps.push(wire(frag, r.closes, r.scope));
|
|
286
|
+
for (const nd of Array.from(frag.childNodes)) parent.insertBefore(nd, end);
|
|
287
|
+
}
|
|
288
|
+
st.__disp = () => disps.forEach((d) => d());
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Apply head blocks in reverse document order (page over layout), then drop the inert
|
|
294
|
+
// placeholder nodes from the page body.
|
|
295
|
+
for (let i = headBlocks.length - 1; i >= 0; i--) {
|
|
296
|
+
const { idx, start, end, nodes } = headBlocks[i];
|
|
297
|
+
weff(() => applyHead(String((closes[idx] as (s?: unknown) => unknown)(scope)), headProvided));
|
|
298
|
+
nodes.forEach((nd) => nd.remove());
|
|
299
|
+
start.remove();
|
|
300
|
+
end.remove();
|
|
301
|
+
}
|
|
302
|
+
if (headBlocks.length === 0 && root.nodeType !== 11) clearHead();
|
|
303
|
+
|
|
304
|
+
// Attributes: data-b="K:attrName"
|
|
305
|
+
const els = (holder as Element).querySelectorAll('[data-b]');
|
|
306
|
+
els.forEach((el) => {
|
|
307
|
+
const spec = el.getAttribute('data-b')!;
|
|
308
|
+
const sep = spec.indexOf(':');
|
|
309
|
+
const idx = +spec.slice(0, sep);
|
|
310
|
+
const attr = spec.slice(sep + 1);
|
|
311
|
+
el.removeAttribute('data-b');
|
|
312
|
+
weff(() => {
|
|
313
|
+
el.setAttribute(attr, String((closes[idx] as (s?: unknown) => unknown)(scope)));
|
|
314
|
+
});
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
if (holder !== root) {
|
|
318
|
+
while (holder.firstChild) root.appendChild(holder.firstChild);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
return () => created.forEach((fn) => fn());
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
export function resetEffects(): void {
|
|
325
|
+
cleanups.forEach((fn) => fn());
|
|
326
|
+
cleanups.clear();
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
// === Server Data Fetching ($data) ===
|
|
330
|
+
|
|
331
|
+
// ponytail: cache keyed by function source, cleared per request/navigation.
|
|
332
|
+
// Upgrade path: explicit keys if two $data calls share identical source.
|
|
333
|
+
let dataCache = new Map<string, Promise<unknown>>();
|
|
334
|
+
|
|
335
|
+
export function $data<T>(fn: () => T | Promise<T>): Promise<T> {
|
|
336
|
+
const key = fn.toString();
|
|
337
|
+
let p = dataCache.get(key);
|
|
338
|
+
if (!p) {
|
|
339
|
+
p = Promise.resolve(fn());
|
|
340
|
+
dataCache.set(key, p);
|
|
341
|
+
}
|
|
342
|
+
return p as Promise<T>;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
// Per-request isolation: state + data cache reset before each SSR render. The request
|
|
346
|
+
// context bag is NOT reset here: it is owned by the middleware pass (runMiddleware) …
|
|
347
|
+
export function clearRequestState(): void {
|
|
348
|
+
signalMap.clear();
|
|
349
|
+
dataCache.clear();
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
// === Request context === A per-request bag: pages/_middleware.rose fills it
|
|
353
|
+
// (getContext().user = ...) and $data, server actions and api handlers read it.
|
|
354
|
+
let requestContext: Record<string, unknown> = {};
|
|
355
|
+
|
|
356
|
+
export function getContext(): Record<string, unknown> {
|
|
357
|
+
return requestContext;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/** Fresh bag for a new request - runMiddleware() calls this before the middleware. */
|
|
361
|
+
export function resetRequestContext(): void {
|
|
362
|
+
requestContext = {};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Run an async render against a THROWAWAY signal map + data cache + mount
|
|
367
|
+
* queue + cleanup set, returning the rendered result plus the signal entries,
|
|
368
|
+
* the onMount callbacks and the onCleanup disposers it produced.
|
|
369
|
+
*
|
|
370
|
+
* Used by link prefetch: rendering the hovered route ahead of navigation must
|
|
371
|
+
* not touch the live page's state (or queue its mounts / register its
|
|
372
|
+
* cleanups), but the paint that consumes the entry later needs exactly those
|
|
373
|
+
* things - compiled getters close over entry OBJECTS, so restoreState()
|
|
374
|
+
* transplants them wholesale instead of copying values, the captured mounts
|
|
375
|
+
* replay after the prefetched DOM is wired, and adoptCleanups() re-registers
|
|
376
|
+
* the captured disposers so the NEXT resetEffects() disposes them (a prefetch
|
|
377
|
+
* render's cleanups firing early would dispose a route that was never
|
|
378
|
+
* painted, and dropping them would leak the painted route's timers).
|
|
379
|
+
* Concurrent prefetches are queued by the caller (ponytail: hover prefetches
|
|
380
|
+
* are rare and cheap).
|
|
381
|
+
*/
|
|
382
|
+
export async function isolateStateAsync<T>(
|
|
383
|
+
fn: () => Promise<T>
|
|
384
|
+
): Promise<{ result: T; state: Map<string, SignalEntry>; mounts: Array<() => void>; cleanups: Set<Cleanup> }> {
|
|
385
|
+
const savedSignals = signalMap;
|
|
386
|
+
const savedData = dataCache;
|
|
387
|
+
const savedMounts = mountQueue.splice(0, mountQueue.length);
|
|
388
|
+
const savedCleanups = new Set(cleanups);
|
|
389
|
+
cleanups.clear();
|
|
390
|
+
signalMap = new Map();
|
|
391
|
+
dataCache = new Map();
|
|
392
|
+
try {
|
|
393
|
+
const result = await fn();
|
|
394
|
+
return {
|
|
395
|
+
result,
|
|
396
|
+
state: signalMap,
|
|
397
|
+
mounts: mountQueue.splice(0, mountQueue.length),
|
|
398
|
+
cleanups: new Set(cleanups),
|
|
399
|
+
};
|
|
400
|
+
} finally {
|
|
401
|
+
signalMap = savedSignals;
|
|
402
|
+
dataCache = savedData;
|
|
403
|
+
mountQueue.splice(0, 0, ...savedMounts); // prepend what was queued before
|
|
404
|
+
cleanups.clear();
|
|
405
|
+
savedCleanups.forEach((fn: Cleanup) => cleanups.add(fn));
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** Adopt a prefetched route's signal entries (objects keep their subs). */
|
|
410
|
+
export function restoreState(entries: Map<string, SignalEntry>): void {
|
|
411
|
+
signalMap.clear();
|
|
412
|
+
entries.forEach((e: SignalEntry, k: string) => signalMap.set(k, e));
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
// === Serialization (for zero-hydration resume) ===
|
|
416
|
+
|
|
417
|
+
export function serializeState(): string {
|
|
418
|
+
const obj: Record<string, unknown> = {};
|
|
419
|
+
signalMap.forEach((v: { value: unknown }, k: string) => (obj[k] = v.value));
|
|
420
|
+
return JSON.stringify(obj);
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
export function resumeState(json: string): void {
|
|
424
|
+
try {
|
|
425
|
+
const obj = JSON.parse(json);
|
|
426
|
+
Object.entries(obj).forEach(([k, v]) => {
|
|
427
|
+
entry(k, v).value = v;
|
|
428
|
+
});
|
|
429
|
+
} catch {
|
|
430
|
+
// ignore corrupt state
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// === Client-side route refresh === The client entry registers the re-render here at boot;
|
|
435
|
+
// components import refresh() like state() and call it from any handler …
|
|
436
|
+
let refreshHook: (() => Promise<void>) | null = null;
|
|
437
|
+
|
|
438
|
+
export function setRefreshHook(fn: () => Promise<void>): void {
|
|
439
|
+
refreshHook = fn;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
export function refresh(): Promise<void> {
|
|
443
|
+
return refreshHook ? refreshHook() : Promise.resolve();
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
// === Lifecycle === Client-only. onMount queues a callback; the client entry flushes the
|
|
447
|
+
// queue after wire() completes - initial adoption, client-side navigation, prefetch paint …
|
|
448
|
+
const mountQueue: Array<() => void> = [];
|
|
449
|
+
|
|
450
|
+
export function onMount(fn: () => void): void {
|
|
451
|
+
if (typeof document === 'undefined') return; // server render: nothing mounts
|
|
452
|
+
mountQueue.push(fn);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/** Drop queued mounts - a failed render leaves stale callbacks behind. */
|
|
456
|
+
export function clearMounts(): void {
|
|
457
|
+
mountQueue.length = 0;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** Run and clear the queue; the client entry calls this after every wire(). */
|
|
461
|
+
export function flushMounts(): void {
|
|
462
|
+
const q = mountQueue.splice(0, mountQueue.length);
|
|
463
|
+
for (const fn of q) fn();
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/** Register a disposer for the current render (the effects' cleanup channel). */
|
|
467
|
+
export function onCleanup(fn: Cleanup): void {
|
|
468
|
+
cleanups.add(fn);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
/**
|
|
472
|
+
* Adopt a prefetched route's captured onCleanup disposers after its cached
|
|
473
|
+
* paint lands: the next resetEffects() (before the following re-render) then
|
|
474
|
+
* disposes them like any live route's. Without this the prefetched paint's
|
|
475
|
+
* mounts would start timers nothing ever clears.
|
|
476
|
+
*/
|
|
477
|
+
export function adoptCleanups(fns: Iterable<Cleanup>): void {
|
|
478
|
+
for (const fn of fns) cleanups.add(fn);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// === i18n: localized routes (innovation #27) === Every JSON file in src/locales/ is a
|
|
482
|
+
// language: { "key": "string" }.
|
|
483
|
+
let LOCALES: Record<string, Record<string, string>> = {};
|
|
484
|
+
let DEFAULT_LOCALE = 'en';
|
|
485
|
+
|
|
486
|
+
export function setLocales(dicts: Record<string, Record<string, string>>, def: string): void {
|
|
487
|
+
LOCALES = dicts;
|
|
488
|
+
DEFAULT_LOCALE = def;
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
export function localeList(): string[] {
|
|
492
|
+
return Object.keys(LOCALES);
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
export function isLocale(lang: string): boolean {
|
|
496
|
+
return Object.prototype.hasOwnProperty.call(LOCALES, lang);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* Best match for an Accept-Language header among the known locales, or null
|
|
501
|
+
* when it expresses no preference (absent, empty, or the `*` wildcard - which
|
|
502
|
+
* Node's own fetch sends by default). A caller negotiates only on a real
|
|
503
|
+
* preference; everything else serves the default locale's page in place.
|
|
504
|
+
*/
|
|
505
|
+
export function bestLocale(header: string | null | undefined): string | null {
|
|
506
|
+
for (const part of (header || '').split(',')) {
|
|
507
|
+
const tag = part.split(';')[0].trim().toLowerCase();
|
|
508
|
+
if (!tag || tag === '*') continue;
|
|
509
|
+
if (isLocale(tag)) return tag;
|
|
510
|
+
const base = tag.split('-')[0];
|
|
511
|
+
if (isLocale(base)) return base;
|
|
512
|
+
}
|
|
513
|
+
return null;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/**
|
|
517
|
+
* Translate a key for the current language. The [lang] route param arrives
|
|
518
|
+
* as state before the render (the same seeding as any dynamic param), and
|
|
519
|
+
* reading it through the signal getter makes $t reactive: switching locale
|
|
520
|
+
* re-runs the marker, so only the translated nodes repaint.
|
|
521
|
+
*/
|
|
522
|
+
export function $t(key: string, vars?: Record<string, string>): string {
|
|
523
|
+
const [lang] = state('lang', DEFAULT_LOCALE);
|
|
524
|
+
const dict = LOCALES[lang()] ?? LOCALES[DEFAULT_LOCALE] ?? {};
|
|
525
|
+
let s = Object.prototype.hasOwnProperty.call(dict, key) ? dict[key] : key;
|
|
526
|
+
if (vars) for (const k in vars) s = s.split(`{${k}}`).join(vars[k]);
|
|
527
|
+
return s;
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
// --- Phase 2: the shared server store ---------------------------------------- Module
|
|
531
|
+
// scope (`export const store = {...}`) is per-PROCESS: under the cluster every worker holds …
|
|
532
|
+
|
|
533
|
+
const STORES = new Map<string, { value: unknown }>();
|
|
534
|
+
let storeTransport: ((name: string, value: unknown) => void) | null = null;
|
|
535
|
+
|
|
536
|
+
/**
|
|
537
|
+
* Install the cross-process transport. The generated server entry wires the
|
|
538
|
+
* cluster channel; a standalone process (dev, preview) installs none - one
|
|
539
|
+
* process is one copy, which is already correct. Pass null to detach.
|
|
540
|
+
*/
|
|
541
|
+
export function setStoreTransport(fn: ((name: string, value: unknown) => void) | null): void {
|
|
542
|
+
storeTransport = fn;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** Apply a patch that arrived from another process (the transport's receiver
|
|
546
|
+
* calls this; a store nobody opened yet is ignored - it has no reader). */
|
|
547
|
+
export function applyStorePatch(name: string, value: unknown): void {
|
|
548
|
+
const entry = STORES.get(name);
|
|
549
|
+
if (entry) entry.value = value;
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/**
|
|
553
|
+
* A named store shared by every request in this process - and, through the
|
|
554
|
+
* transport, by every worker. Read it inside `$data` or a server action:
|
|
555
|
+
* those are the server-only paths. A bare read in a render body is a local
|
|
556
|
+
* snapshot, and on the client (where the store map is per page load and no
|
|
557
|
+
* patch ever arrives) that snapshot is the initial value.
|
|
558
|
+
*
|
|
559
|
+
* Values must be JSON-serializable: the transport serializes them, exactly
|
|
560
|
+
* like the state patch that already rides in every document.
|
|
561
|
+
*/
|
|
562
|
+
export function $store<T>(name: string, initial: T): { get(): T; set(v: T): void; update(fn: (v: T) => T): void } {
|
|
563
|
+
let entry = STORES.get(name);
|
|
564
|
+
if (!entry) {
|
|
565
|
+
entry = { value: initial };
|
|
566
|
+
STORES.set(name, entry);
|
|
567
|
+
}
|
|
568
|
+
const box = entry;
|
|
569
|
+
return {
|
|
570
|
+
get: () => box.value as T,
|
|
571
|
+
set: (v: T) => {
|
|
572
|
+
box.value = v;
|
|
573
|
+
storeTransport?.(name, v);
|
|
574
|
+
},
|
|
575
|
+
update: (fn: (v: T) => T) => {
|
|
576
|
+
box.value = fn(box.value as T);
|
|
577
|
+
storeTransport?.(name, box.value);
|
|
578
|
+
},
|
|
579
|
+
};
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
// --- Phase 1: cookie helpers ------------------------------------------------- Sessions
|
|
583
|
+
// are the first thing every real app needs and the easiest thing to get subtly wrong …
|
|
584
|
+
|
|
585
|
+
/**
|
|
586
|
+
* Parse the cookies of a request (server) or of this document (client, where
|
|
587
|
+
* HttpOnly cookies are invisible by design - that is the point of HttpOnly).
|
|
588
|
+
*/
|
|
589
|
+
export function $cookies(request?: Request): Record<string, string> {
|
|
590
|
+
const raw = request
|
|
591
|
+
? request.headers.get('cookie')
|
|
592
|
+
: (typeof document !== 'undefined' ? document.cookie : '');
|
|
593
|
+
const out: Record<string, string> = {};
|
|
594
|
+
for (const part of (raw || '').split(';')) {
|
|
595
|
+
const eq = part.indexOf('=');
|
|
596
|
+
if (eq < 0) continue;
|
|
597
|
+
const k = part.slice(0, eq).trim();
|
|
598
|
+
if (k) out[k] = decodeURIComponent(part.slice(eq + 1).trim());
|
|
599
|
+
}
|
|
600
|
+
return out;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* Build a Set-Cookie header VALUE for a session cookie with the safe
|
|
605
|
+
* defaults: HttpOnly, SameSite=Lax, Path=/, a 7-day Max-Age. `secure` is the
|
|
606
|
+
* one attribute a helper cannot infer (it depends on the deployment's TLS),
|
|
607
|
+
* so pass it when serving over https - and SameSite=None forces Secure,
|
|
608
|
+
* because every modern browser rejects that pairing otherwise.
|
|
609
|
+
*/
|
|
610
|
+
export function $sessionCookie(
|
|
611
|
+
name: string,
|
|
612
|
+
value: string,
|
|
613
|
+
opts: { path?: string; maxAge?: number; sameSite?: 'Strict' | 'Lax' | 'None'; secure?: boolean; httpOnly?: boolean } = {}
|
|
614
|
+
): string {
|
|
615
|
+
const { path = '/', maxAge = 60 * 60 * 24 * 7, sameSite = 'Lax', secure = false, httpOnly = true } = opts;
|
|
616
|
+
return [
|
|
617
|
+
`${name}=${encodeURIComponent(value)}`,
|
|
618
|
+
`Path=${path}`,
|
|
619
|
+
`Max-Age=${maxAge}`,
|
|
620
|
+
`SameSite=${sameSite}`,
|
|
621
|
+
httpOnly ? 'HttpOnly' : '',
|
|
622
|
+
secure || sameSite === 'None' ? 'Secure' : '',
|
|
623
|
+
].filter(Boolean).join('; ');
|
|
624
|
+
}
|