rosetack 0.1.2 → 0.1.4
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/deploy/cloudflare/functions/[[path]].ts +61 -0
- package/deploy/cloudflare/wrangler.toml +14 -0
- package/deploy/netlify/functions/rosetack.ts +38 -0
- package/deploy/netlify.toml +17 -0
- package/devtools/devtools.html +7 -0
- package/devtools/devtools.js +1 -0
- package/devtools/manifest.json +8 -0
- package/devtools/panel.html +28 -0
- package/devtools/panel.js +54 -0
- package/dist-cli/compiler.mjs +2194 -561
- package/dist-cli/edge.mjs +159 -48
- package/dist-cli/rosetack.mjs +2899 -739
- package/dist-cli/runtime.mjs +305 -43
- package/dist-cli/test.mjs +2332 -630
- package/package.json +4 -3
- package/src/FRAMEWORK_VERSION +1 -1
- package/src/cli/content.ts +186 -0
- package/src/cli/edge.ts +78 -62
- package/src/cli/image-size.ts +83 -0
- package/src/cli/index.ts +391 -334
- package/src/cli/prod-server.ts +324 -0
- package/src/cli/prompt.ts +51 -20
- package/src/cli/shell.ts +105 -74
- package/src/cli/test.ts +9 -70
- package/src/compiler/index.ts +2107 -913
- package/src/runtime/index.ts +367 -168
- package/src/types/rosetack.d.ts +16 -66
- package/templates/admin/package.json +14 -0
- package/templates/admin/rosetack.config.js +1 -0
- package/templates/admin/src/pages/_middleware.rose +33 -0
- package/templates/admin/src/pages/api/items.rose +37 -0
- package/templates/admin/src/pages/api/login.rose +25 -0
- package/templates/admin/src/pages/index.rose +79 -0
- package/templates/api/package.json +14 -0
- package/templates/api/rosetack.config.js +1 -0
- package/templates/api/src/pages/api/health.rose +7 -0
- package/templates/api/src/pages/api/items.rose +46 -0
- package/templates/api/src/pages/api/login.rose +24 -0
- package/templates/api/src/pages/index.rose +25 -0
- package/templates/blog/package.json +14 -0
- package/templates/blog/rosetack.config.js +1 -0
- package/templates/blog/src/pages/404.rose +2 -0
- package/templates/blog/src/pages/_layout.rose +42 -0
- package/templates/blog/src/pages/_middleware.rose +74 -0
- package/templates/blog/src/pages/admin.rose +85 -0
- package/templates/blog/src/pages/api/login.rose +46 -0
- package/templates/blog/src/pages/api/posts/[id].rose +37 -0
- package/templates/blog/src/pages/api/posts.rose +72 -0
- package/templates/blog/src/pages/index.rose +31 -0
- package/templates/blog/src/pages/post/[id].rose +36 -0
- package/templates/site/package.json +14 -0
- package/templates/site/rosetack.config.js +1 -0
- package/templates/site/src/pages/404.rose +2 -0
- package/templates/site/src/pages/_layout.rose +40 -0
- package/templates/site/src/pages/about.rose +6 -0
- package/templates/site/src/pages/index.rose +13 -0
- package/templates/site/src/pages/pricing.rose +8 -0
package/src/runtime/index.ts
CHANGED
|
@@ -1,9 +1,4 @@
|
|
|
1
|
-
|
|
2
|
-
* rosetack Runtime - Zero-hydration, compile-time reactivity
|
|
3
|
-
* Target: < 2KB gzipped
|
|
4
|
-
*/
|
|
5
|
-
|
|
6
|
-
// === Reactive Primitives ===
|
|
1
|
+
// rosetack Runtime - Zero-hydration, compile-time reactivity Target: < 2KB gzipped
|
|
7
2
|
|
|
8
3
|
type Subscriber = () => void;
|
|
9
4
|
type Cleanup = () => void;
|
|
@@ -11,12 +6,10 @@ type SignalEntry = { value: unknown; subs: Set<Subscriber> };
|
|
|
11
6
|
|
|
12
7
|
let currentEffect: (() => void) | null = null;
|
|
13
8
|
|
|
14
|
-
// Trade-off: global signal map, shared across all inlined modules
|
|
15
9
|
let signalMap: Map<string, SignalEntry> =
|
|
16
10
|
(globalThis as any).__rosetack_signalMap ?? new Map();
|
|
17
11
|
(globalThis as any).__rosetack_signalMap = signalMap;
|
|
18
12
|
|
|
19
|
-
// One get-or-create helper shared by state / setState / resumeState.
|
|
20
13
|
function entry(key: string, initial: unknown): { value: unknown; subs: Set<Subscriber> } {
|
|
21
14
|
const e = signalMap.get(key) ?? { value: initial, subs: new Set<Subscriber>() };
|
|
22
15
|
signalMap.set(key, e);
|
|
@@ -24,6 +17,7 @@ function entry(key: string, initial: unknown): { value: unknown; subs: Set<Subsc
|
|
|
24
17
|
}
|
|
25
18
|
|
|
26
19
|
export function state<T>(key: string, initial: T): [() => T, (v: T) => void] {
|
|
20
|
+
ownerKeys()?.add(key);
|
|
27
21
|
const e = entry(key, initial);
|
|
28
22
|
|
|
29
23
|
const getter = () => {
|
|
@@ -34,6 +28,7 @@ export function state<T>(key: string, initial: T): [() => T, (v: T) => void] {
|
|
|
34
28
|
const setter = (v: T) => {
|
|
35
29
|
e.value = v;
|
|
36
30
|
e.subs.forEach((fn: Subscriber) => fn());
|
|
31
|
+
if (persistedKeys.has(key)) writeStorage(key, v);
|
|
37
32
|
};
|
|
38
33
|
|
|
39
34
|
return [getter, setter];
|
|
@@ -47,18 +42,89 @@ export function setState<T>(key: string, value: T): void {
|
|
|
47
42
|
const e = entry(key, value);
|
|
48
43
|
e.value = value;
|
|
49
44
|
e.subs.forEach((fn: Subscriber) => fn());
|
|
45
|
+
if (persistedKeys.has(key)) writeStorage(key, value);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const persistedKeys = new Set<string>();
|
|
49
|
+
|
|
50
|
+
function writeStorage(key: string, v: unknown): void {
|
|
51
|
+
try {
|
|
52
|
+
(globalThis as { localStorage?: Storage }).localStorage?.setItem('rosetack:' + key, JSON.stringify(v));
|
|
53
|
+
} catch { /* no storage / private mode / quota: persistence is best-effort */ }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// F9 ($persist): `let theme = $persist('dark')` — like $state, but the value survives reloads.
|
|
57
|
+
export function persistState<T>(key: string, initial: T): [() => T, (v: T) => void] {
|
|
58
|
+
persistedKeys.add(key);
|
|
59
|
+
let seeded = initial;
|
|
60
|
+
let hasStored = false;
|
|
61
|
+
try {
|
|
62
|
+
const raw = (globalThis as { localStorage?: Storage }).localStorage?.getItem('rosetack:' + key);
|
|
63
|
+
if (raw != null) {
|
|
64
|
+
seeded = JSON.parse(raw) as T;
|
|
65
|
+
hasStored = true;
|
|
66
|
+
}
|
|
67
|
+
} catch { }
|
|
68
|
+
const [get, set] = state(key, seeded);
|
|
69
|
+
if (hasStored) set(seeded);
|
|
70
|
+
return [get, set];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
let lastBoundaryError: Error | null = null;
|
|
74
|
+
|
|
75
|
+
export function $setBoundaryError(e: unknown): void {
|
|
76
|
+
lastBoundaryError = e instanceof Error ? e : new Error(String(e));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function $boundaryError(): Error | null {
|
|
80
|
+
return lastBoundaryError;
|
|
50
81
|
}
|
|
51
82
|
|
|
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
83
|
const cleanups = new Set<Cleanup>();
|
|
55
84
|
|
|
85
|
+
let fxOwner: object | null = null;
|
|
86
|
+
const fxByOwner = new WeakMap<object, Set<Cleanup>>();
|
|
87
|
+
const keysByOwner = new WeakMap<object, Set<string>>();
|
|
88
|
+
const fxSet = (): Set<Cleanup> => {
|
|
89
|
+
if (!fxOwner) return cleanups;
|
|
90
|
+
let s = fxByOwner.get(fxOwner);
|
|
91
|
+
if (!s) { s = new Set(); fxByOwner.set(fxOwner, s); }
|
|
92
|
+
return s;
|
|
93
|
+
};
|
|
94
|
+
const ownerKeys = (): Set<string> | null => {
|
|
95
|
+
if (!fxOwner) return null;
|
|
96
|
+
let s = keysByOwner.get(fxOwner);
|
|
97
|
+
if (!s) { s = new Set(); keysByOwner.set(fxOwner, s); }
|
|
98
|
+
return s;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
// Attribute everything the current render creates to `container` (null = the document's global bookkeeping).
|
|
102
|
+
export function setFxOwner(container: object | null): void {
|
|
103
|
+
fxOwner = container;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Dispose everything ONE container created - its effects, its onCleanups, the state keys its render seeded.
|
|
107
|
+
export function resetContainerFx(container: object): void {
|
|
108
|
+
const set = fxByOwner.get(container);
|
|
109
|
+
if (set) {
|
|
110
|
+
set.forEach((fn: Cleanup) => fn());
|
|
111
|
+
fxByOwner.delete(container);
|
|
112
|
+
}
|
|
113
|
+
const keys = keysByOwner.get(container);
|
|
114
|
+
if (keys) {
|
|
115
|
+
keys.forEach((k: string) => signalMap.delete(k));
|
|
116
|
+
keysByOwner.delete(container);
|
|
117
|
+
}
|
|
118
|
+
dataCache.clear();
|
|
119
|
+
pendingDeltas.clear();
|
|
120
|
+
}
|
|
121
|
+
|
|
56
122
|
export function effect(fn: () => void): Cleanup {
|
|
57
123
|
const wrapped: Subscriber = () => {
|
|
58
124
|
try {
|
|
59
125
|
fn();
|
|
60
126
|
} catch {
|
|
61
|
-
|
|
127
|
+
|
|
62
128
|
}
|
|
63
129
|
};
|
|
64
130
|
const prev = currentEffect;
|
|
@@ -67,14 +133,12 @@ export function effect(fn: () => void): Cleanup {
|
|
|
67
133
|
currentEffect = prev;
|
|
68
134
|
const cleanup: Cleanup = () => {
|
|
69
135
|
signalMap.forEach((e: { subs: Set<Subscriber> }) => e.subs.delete(wrapped));
|
|
70
|
-
|
|
136
|
+
fxSet().delete(cleanup);
|
|
71
137
|
};
|
|
72
|
-
|
|
138
|
+
fxSet().add(cleanup);
|
|
73
139
|
return cleanup;
|
|
74
140
|
}
|
|
75
141
|
|
|
76
|
-
// === HTML escaping (server-side interpolation safety) ===
|
|
77
|
-
|
|
78
142
|
const ESC_MAP: Record<string, string> = {
|
|
79
143
|
'&': '&',
|
|
80
144
|
'<': '<',
|
|
@@ -87,19 +151,29 @@ export function esc(v: unknown): string {
|
|
|
87
151
|
return String(v).replace(/[&<>"']/g, (c) => ESC_MAP[c]);
|
|
88
152
|
}
|
|
89
153
|
|
|
90
|
-
// === Generated-code marker helpers === Every reactive marker in every generated module is
|
|
91
|
-
// emitted through these five functions …
|
|
92
|
-
|
|
93
154
|
type Close = (s?: unknown) => unknown;
|
|
94
155
|
|
|
95
156
|
export function textMark(closes: Close[], fn: Close, pair?: boolean, arg?: unknown): string {
|
|
96
157
|
const i = closes.push(fn) - 1;
|
|
97
|
-
return `<!--\u27e6m:${i}\u27e7-->` + esc(
|
|
158
|
+
return `<!--\u27e6m:${i}\u27e7-->` + esc(fn(arg)) + (pair ? `<!--\u27e6/m:${i}\u27e7-->` : '');
|
|
98
159
|
}
|
|
99
160
|
|
|
100
161
|
export function attrMark(closes: Close[], fn: Close, name: string, arg?: unknown): string {
|
|
101
162
|
const i = closes.push(fn) - 1;
|
|
102
|
-
return `${name}="${esc(
|
|
163
|
+
return `${name}="${esc(fn(arg))}" data-b${i}="${name}"`;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Boolean attributes (F1): presence IS the value - `checked="false"` still
|
|
168
|
+
* checks the box, so a reactive boolean attr can never ride attrMark. The
|
|
169
|
+
* SSR side emits the bare attribute only when truthy, plus an index-suffixed
|
|
170
|
+
* marker either way; wire()'s boolean branch flips the PROPERTY (the one
|
|
171
|
+
* thing a live DOM obeys after user interaction) and mirrors the attribute
|
|
172
|
+
* for no-JS parity.
|
|
173
|
+
*/
|
|
174
|
+
export function boolAttrMark(closes: Close[], fn: Close, name: string, arg?: unknown): string {
|
|
175
|
+
const i = closes.push(fn) - 1;
|
|
176
|
+
return (fn(arg) ? ` ${name}=""` : '') + ` data-b${i}="!${name}"`;
|
|
103
177
|
}
|
|
104
178
|
|
|
105
179
|
export function ifMark(
|
|
@@ -108,31 +182,25 @@ export function ifMark(
|
|
|
108
182
|
fn: (s: unknown, c: Close[]) => unknown,
|
|
109
183
|
scope?: unknown
|
|
110
184
|
): string {
|
|
111
|
-
const i = closes.length;
|
|
112
|
-
// The content renders the FIRST time the block shows, never before: the eager version
|
|
113
|
-
// crashed `{#if user()}{user().name}{/if}` …
|
|
114
185
|
let snap: { html: string; closes: Close[] } | null = null;
|
|
115
|
-
closes.push(() => {
|
|
186
|
+
const i = closes.push(() => {
|
|
116
187
|
if (!cond()) {
|
|
117
188
|
snap = null;
|
|
118
189
|
return null;
|
|
119
190
|
}
|
|
120
191
|
if (!snap) {
|
|
121
|
-
|
|
122
|
-
snap = { html: String(fn(scope, c)), closes: c };
|
|
192
|
+
snap = { html: String(fn(scope, closes)), closes };
|
|
123
193
|
}
|
|
124
194
|
return snap;
|
|
125
|
-
});
|
|
195
|
+
}) - 1;
|
|
126
196
|
const r = closes[i]() as { html: string } | null;
|
|
127
197
|
return `<!--\u27e6i:${i}\u27e7-->` + (r ? r.html : '') + `<!--\u27e6/i:${i}\u27e7-->`;
|
|
128
198
|
}
|
|
129
199
|
|
|
130
200
|
export function eachMark(closes: Close[], items: Close, fn: (s: unknown, c: Close[]) => unknown): string {
|
|
131
|
-
const i = closes.
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
return { html: String(fn(v, c)), closes: c, scope: v };
|
|
135
|
-
}));
|
|
201
|
+
const i = closes.push(() => (items() as unknown[]).map((v, vi) => {
|
|
202
|
+
return { html: String(fn(v, closes, vi)), closes, scope: v };
|
|
203
|
+
})) - 1;
|
|
136
204
|
let h = `<!--\u27e6l:${i}\u27e7-->`;
|
|
137
205
|
for (const r of closes[i]() as Array<{ html: string }>) h += r.html;
|
|
138
206
|
return h + `<!--\u27e6/l:${i}\u27e7-->`;
|
|
@@ -154,28 +222,47 @@ export function headMark(closes: Close[], fn: Close): string {
|
|
|
154
222
|
* changes. Reusing that machinery costs this function and nothing else: no
|
|
155
223
|
* new marker kind, no new wire branch, no bytes in a document that never
|
|
156
224
|
* uses it. The close returns the same {html, closes} shape an {#if} block
|
|
157
|
-
* does, with
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
*
|
|
225
|
+
* does, with the RENDER's array - trusted html is usually opaque markup
|
|
226
|
+
* with no markers inside, but when a loader's value was itself rendered
|
|
227
|
+
* inside this same pass (a theme skin built from another composable) the
|
|
228
|
+
* markers it carries belong to this array, and a nested wire() pass must be
|
|
229
|
+
* able to resolve them. `arg` is the enclosing block's scope value, exactly
|
|
230
|
+
* as textMark takes it: a `{@html row.body}` inside an {#each} resolves
|
|
231
|
+
* against the row.
|
|
161
232
|
*/
|
|
162
233
|
export function rawMark(closes: Close[], fn: Close, arg?: unknown): string {
|
|
163
|
-
const i = closes.push((s?: unknown) => ({ html: String((fn as (a?: unknown) => unknown)(s) ?? ''), closes
|
|
234
|
+
const i = closes.push((s?: unknown) => ({ html: String((fn as (a?: unknown) => unknown)(s) ?? ''), closes })) - 1;
|
|
164
235
|
const r = closes[i](arg) as { html: string };
|
|
165
236
|
return `<!--\u27e6i:${i}\u27e7-->` + r.html + `<!--\u27e6/i:${i}\u27e7-->`;
|
|
166
237
|
}
|
|
167
238
|
|
|
168
|
-
|
|
239
|
+
/**
|
|
240
|
+
* A named slot's block. The child rendered its slot content into the
|
|
241
|
+
* render's shared array scoped to the slot object; the block wraps it in
|
|
242
|
+
* markers from the SAME index space, so the ids stay unique across the whole
|
|
243
|
+
* composition (a plain <slot/> inlines the children html directly and needs
|
|
244
|
+
* none of this). Lives here rather than in the compiler's emitted helper
|
|
245
|
+
* string so the array is the one the rest of the render uses.
|
|
246
|
+
*/
|
|
247
|
+
export function slotBlockMark(
|
|
248
|
+
closes: Close[],
|
|
249
|
+
hit: { o: Record<string, unknown>; fn: (o: unknown, c: Close[]) => unknown } | null
|
|
250
|
+
): string {
|
|
251
|
+
if (!hit) return '';
|
|
252
|
+
const i = closes.push(() => {
|
|
253
|
+
if (!hit) return null;
|
|
254
|
+
return { html: String(hit.fn(hit.o, closes)), closes, scope: hit.o };
|
|
255
|
+
}) - 1;
|
|
256
|
+
return `<!--\u27e6i:${i}\u27e7-->` + String(hit.fn(hit.o, closes)) + `<!--\u27e6/i:${i}\u27e7-->`;
|
|
257
|
+
}
|
|
169
258
|
|
|
170
259
|
const MARK_RE = /^\u27e6([milh]):(\d+)\u27e7$/;
|
|
171
|
-
// `m` ends a text marker whose value is followed by literal text:
|
|
172
|
-
// the pair bounds exactly the value, so patching it cannot eat the prose.
|
|
173
260
|
const END_RE = /^\u27e6\/([milh]):(\d+)\u27e7$/;
|
|
174
261
|
|
|
175
|
-
// Comments already handled by a nested wire() pass (e.g. inside an adopted {#if} block)
|
|
176
|
-
// must not be re-processed by the outer pass with the wrong closes array.
|
|
177
262
|
const wired = new WeakSet<Node>();
|
|
178
263
|
|
|
264
|
+
const pendingIslandObservers = new Set<IntersectionObserver>();
|
|
265
|
+
|
|
179
266
|
/** Parse an html string into a DocumentFragment. */
|
|
180
267
|
export function tpl(html: string): DocumentFragment {
|
|
181
268
|
const t = document.createElement('template');
|
|
@@ -183,17 +270,33 @@ export function tpl(html: string): DocumentFragment {
|
|
|
183
270
|
return t.content;
|
|
184
271
|
}
|
|
185
272
|
|
|
186
|
-
// === Document head (<head> blocks) ===
|
|
187
|
-
|
|
188
|
-
// Marks the head elements rosetack manages, so stale ones can be removed when a route's
|
|
189
|
-
// head changes and user-authored <head> content is never touched.
|
|
190
273
|
const HEAD_ATTR = 'data-rosetack-head';
|
|
191
274
|
|
|
192
|
-
// The delegated-event handler registry: every compiled module registers its handlers here
|
|
193
|
-
// (Object.assign(handlers, { ...
|
|
194
275
|
export const handlers: Record<string, (e: Event) => void> =
|
|
195
276
|
(globalThis as { __rosetack_handlers?: Record<string, (e: Event) => void> }).__rosetack_handlers ??= {};
|
|
196
277
|
|
|
278
|
+
let actionDispatch: ((name: string, e: Event) => void) | null = null;
|
|
279
|
+
export function setActionDispatcher(fn: (name: string, e: Event) => void): void {
|
|
280
|
+
actionDispatch = fn;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const directBound = new WeakMap<Element, Set<string>>();
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* F5: `use:NAME` element actions - the plugin point for DOM behaviors
|
|
287
|
+
* (tooltips, dropdowns, canvas glue) that themes and plugins register once
|
|
288
|
+
* per module: directives.tooltip = (el) => { ...; return cleanup? }. wire()
|
|
289
|
+
* invokes each action for its element when the route adopts; the returned
|
|
290
|
+
* cleanup (if any) rides the same disposal set as every other effect.
|
|
291
|
+
* Parameters travel as data-* attributes the action reads - keeping them out
|
|
292
|
+
* of the reactive graph keeps the action contract one argument.
|
|
293
|
+
*/
|
|
294
|
+
export const directives: Record<string, (el: Element, param?: unknown) => void | (() => void) | { update?: (p: unknown) => void; destroy?: () => void }> =
|
|
295
|
+
(globalThis as { __rosetack_directives?: Record<string, (el: Element, param?: unknown) => void | (() => void) | { update?: (p: unknown) => void; destroy?: () => void }> })
|
|
296
|
+
.__rosetack_directives ??= {};
|
|
297
|
+
|
|
298
|
+
const actionRecords = new WeakMap<Element, { update?: (p: unknown) => void; destroy?: () => void }>();
|
|
299
|
+
|
|
197
300
|
/**
|
|
198
301
|
* Apply one route's whole <head> (every block of its chain, page first) to the
|
|
199
302
|
* document: <title> replaces the title, <meta>/<link>/<base> are matched by
|
|
@@ -208,14 +311,10 @@ export const handlers: Record<string, (e: Event) => void> =
|
|
|
208
311
|
*/
|
|
209
312
|
export function applyHead(html: string): void {
|
|
210
313
|
const seen = new Set<string>();
|
|
211
|
-
// tag -> how many unkeyed elements of that tag came before (the server's
|
|
212
|
-
// mergeHeadBlocks counts the same way over the same block order)
|
|
213
314
|
const positional = new Map<string, number>();
|
|
214
315
|
const frag = tpl(html);
|
|
215
316
|
const title = frag.querySelector('title');
|
|
216
317
|
if (title) {
|
|
217
|
-
// Manage the title element directly: the document.title setter would update the FIRST
|
|
218
|
-
// title element in tree order …
|
|
219
318
|
let cur = document.head.querySelector('title');
|
|
220
319
|
if (!cur) {
|
|
221
320
|
cur = document.createElement('title');
|
|
@@ -227,8 +326,6 @@ export function applyHead(html: string): void {
|
|
|
227
326
|
for (const el of Array.from(frag.children)) {
|
|
228
327
|
if (el.tagName === 'TITLE') continue;
|
|
229
328
|
const tag = el.tagName.toLowerCase();
|
|
230
|
-
// Bug report 2026.9.22 11:46: a head element with no name/property/rel/ charset
|
|
231
|
-
// attribute used to be dropped here in silence …
|
|
232
329
|
const identity = el.getAttribute('name')
|
|
233
330
|
?? el.getAttribute('property')
|
|
234
331
|
?? el.getAttribute('rel')
|
|
@@ -241,7 +338,7 @@ export function applyHead(html: string): void {
|
|
|
241
338
|
positional.set(tag, n + 1);
|
|
242
339
|
managed = `${tag}:#${n}`;
|
|
243
340
|
}
|
|
244
|
-
if (seen.has(managed)) continue;
|
|
341
|
+
if (seen.has(managed)) continue;
|
|
245
342
|
seen.add(managed);
|
|
246
343
|
el.setAttribute(HEAD_ATTR, managed);
|
|
247
344
|
document.head.appendChild(el);
|
|
@@ -261,7 +358,6 @@ export function clearHead(): void {
|
|
|
261
358
|
export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Cleanup {
|
|
262
359
|
let holder: Node = root;
|
|
263
360
|
if (root.nodeType === 11) {
|
|
264
|
-
// DocumentFragment: wrap so querySelectorAll sees the root element too
|
|
265
361
|
const div = document.createElement('div');
|
|
266
362
|
div.appendChild(root);
|
|
267
363
|
holder = div;
|
|
@@ -274,13 +370,12 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
|
|
|
274
370
|
const walker = document.createTreeWalker(holder, NodeFilter.SHOW_COMMENT);
|
|
275
371
|
while (walker.nextNode()) comments.push(walker.currentNode as Comment);
|
|
276
372
|
|
|
277
|
-
// Comments that live INSIDE an {#if}/{#each}/slot block belong to that block's OWN wire
|
|
278
|
-
// pass …
|
|
279
373
|
const nested = new Set<Comment>();
|
|
280
|
-
const
|
|
374
|
+
const headPair = new Set<Comment>();
|
|
375
|
+
const open: number[] = [];
|
|
281
376
|
for (let i = 0; i < comments.length; i++) {
|
|
282
377
|
const m = (comments[i].nodeValue ?? '').match(MARK_RE);
|
|
283
|
-
if (m && (m[1] === 'i' || m[1] === 'l')) {
|
|
378
|
+
if (m && (m[1] === 'i' || m[1] === 'l' || m[1] === 'h')) {
|
|
284
379
|
open.push(i);
|
|
285
380
|
continue;
|
|
286
381
|
}
|
|
@@ -292,10 +387,16 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
|
|
|
292
387
|
const om = (comments[open[k]].nodeValue ?? '').match(MARK_RE)!;
|
|
293
388
|
if (om[1] + om[2] === key) { at = k; break; }
|
|
294
389
|
}
|
|
295
|
-
if (at < 0) continue;
|
|
390
|
+
if (at < 0) continue;
|
|
391
|
+
const om = (comments[open[at]].nodeValue ?? '').match(MARK_RE)!;
|
|
392
|
+
if (om[1] === 'h') {
|
|
393
|
+
headPair.add(comments[open[at]]);
|
|
394
|
+
headPair.add(comments[i]);
|
|
395
|
+
}
|
|
296
396
|
for (let k = open[at] + 1; k < i; k++) nested.add(comments[k]);
|
|
297
|
-
open.length = at;
|
|
397
|
+
open.length = at;
|
|
298
398
|
}
|
|
399
|
+
for (const c of headPair) nested.delete(c);
|
|
299
400
|
|
|
300
401
|
const ends = new Map<number, Comment>();
|
|
301
402
|
for (const c of comments) {
|
|
@@ -304,21 +405,50 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
|
|
|
304
405
|
if (m) ends.set(+m[2], c);
|
|
305
406
|
}
|
|
306
407
|
|
|
307
|
-
// Head blocks are collected during the walk and applied afterwards as ONE effect over the
|
|
308
|
-
// whole route's head: the blocks render in document order …
|
|
309
408
|
const headBlocks: Array<{ idx: number; start: Comment; end: Comment; nodes: ChildNode[] }> = [];
|
|
310
409
|
|
|
410
|
+
const ownsHead = root === document.getElementById('app');
|
|
411
|
+
|
|
412
|
+
let islandSkip = false;
|
|
413
|
+
if (ownsHead) {
|
|
414
|
+
const islandEls = Array.from(
|
|
415
|
+
(holder as Element).querySelectorAll('[data-rv-island]')
|
|
416
|
+
).filter((el) => !(el.parentElement && el.parentElement.closest('[data-rv-island]')));
|
|
417
|
+
islandSkip = islandEls.length > 0;
|
|
418
|
+
for (const isl of islandEls) {
|
|
419
|
+
const fire = () => wire(isl, closes, scope);
|
|
420
|
+
const mode = isl.getAttribute('data-rv-island-hydrate');
|
|
421
|
+
if (mode === 'visible' && typeof IntersectionObserver !== 'undefined') {
|
|
422
|
+
const io = new IntersectionObserver((entries) => {
|
|
423
|
+
if (entries.some((en) => en.isIntersecting)) {
|
|
424
|
+
io.disconnect();
|
|
425
|
+
pendingIslandObservers.delete(io);
|
|
426
|
+
fire();
|
|
427
|
+
}
|
|
428
|
+
});
|
|
429
|
+
io.observe(isl);
|
|
430
|
+
pendingIslandObservers.add(io);
|
|
431
|
+
} else if (mode === 'idle' && typeof (globalThis as { requestIdleCallback?: unknown }).requestIdleCallback === 'function') {
|
|
432
|
+
(globalThis as { requestIdleCallback: (cb: () => void) => void }).requestIdleCallback(() => fire());
|
|
433
|
+
} else {
|
|
434
|
+
fire();
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
311
439
|
for (const c of comments) {
|
|
312
440
|
if (nested.has(c) || wired.has(c) || !c.parentNode) continue;
|
|
313
|
-
wired.add(c);
|
|
314
441
|
const m = (c.nodeValue ?? '').match(MARK_RE);
|
|
315
442
|
if (!m) continue;
|
|
316
443
|
const kind = m[1];
|
|
317
444
|
const idx = +m[2];
|
|
318
445
|
|
|
446
|
+
if (islandSkip && kind !== 'h' && (c.parentNode as Element).closest?.('[data-rv-island]')) continue;
|
|
447
|
+
|
|
448
|
+
if (kind === 'h' && !ownsHead) continue;
|
|
449
|
+
wired.add(c);
|
|
450
|
+
|
|
319
451
|
if (kind === 'h') {
|
|
320
|
-
// Document head: the closure re-renders the <head> block (no inner
|
|
321
|
-
// markers), so one effect drives title/meta for this route.
|
|
322
452
|
const end = ends.get(idx);
|
|
323
453
|
if (!end) continue;
|
|
324
454
|
const nodes: ChildNode[] = [];
|
|
@@ -330,8 +460,6 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
|
|
|
330
460
|
}
|
|
331
461
|
headBlocks.push({ idx, start: c, end, nodes });
|
|
332
462
|
} else if (kind === 'm') {
|
|
333
|
-
// Text: update the text node that follows the marker comment. When the marker is a
|
|
334
|
-
// PAIR (value followed by literal text) …
|
|
335
463
|
let target = c.nextSibling;
|
|
336
464
|
if (!target || target.nodeType !== 3) {
|
|
337
465
|
target = document.createTextNode('');
|
|
@@ -351,8 +479,6 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
|
|
|
351
479
|
tn.nodeValue = String((closes[idx] as (s?: unknown) => unknown)(scope));
|
|
352
480
|
});
|
|
353
481
|
} else if (kind === 'i') {
|
|
354
|
-
// Conditional block: first run adopts the server-rendered content in
|
|
355
|
-
// place (node identity preserved); later runs swap in a fresh clone.
|
|
356
482
|
const anchor = c;
|
|
357
483
|
const end = ends.get(idx);
|
|
358
484
|
if (!end) continue;
|
|
@@ -365,13 +491,9 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
|
|
|
365
491
|
}
|
|
366
492
|
const r = (closes[idx] as (s?: unknown) => unknown)(scope) as { html: string; closes: unknown[] } | null;
|
|
367
493
|
if (!r) {
|
|
368
|
-
// Hidden. The client has now evaluated this block once, so from here on whatever
|
|
369
|
-
// sits between the anchors is client-rendered: a block the server left hidden …
|
|
370
494
|
st.__ever = true;
|
|
371
495
|
return;
|
|
372
496
|
}
|
|
373
|
-
// First run adopts the server-rendered content (move out, wire, move back -
|
|
374
|
-
// identity preserved); later runs clone the block template.
|
|
375
497
|
let frag: DocumentFragment;
|
|
376
498
|
if (st.__ever) {
|
|
377
499
|
frag = tpl(r.html);
|
|
@@ -385,16 +507,13 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
|
|
|
385
507
|
n = nx;
|
|
386
508
|
}
|
|
387
509
|
}
|
|
388
|
-
// r.scope is set by a named slot's block: its content is scoped to the object the child
|
|
389
|
-
// passed in, exactly like a list item.
|
|
390
510
|
const disp = wire(frag, r.closes, (r as { scope?: unknown }).scope ?? scope);
|
|
391
511
|
const nodes = Array.from(frag.childNodes);
|
|
392
512
|
const parent = anchor.parentNode!;
|
|
393
|
-
for (const nd of nodes) parent.insertBefore(nd,
|
|
513
|
+
for (const nd of nodes) parent.insertBefore(nd, end);
|
|
394
514
|
st.__st = { nodes, disp };
|
|
395
515
|
});
|
|
396
516
|
} else {
|
|
397
|
-
// List: rebuild items between the start and end anchors
|
|
398
517
|
const start = c;
|
|
399
518
|
const end = ends.get(idx);
|
|
400
519
|
if (!end) continue;
|
|
@@ -423,36 +542,131 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
|
|
|
423
542
|
}
|
|
424
543
|
}
|
|
425
544
|
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
545
|
+
if (root === document.getElementById('app')) {
|
|
546
|
+
if (headBlocks.length > 0) {
|
|
547
|
+
const blocks = headBlocks;
|
|
548
|
+
weff(() => {
|
|
549
|
+
let html = '';
|
|
550
|
+
for (const b of blocks) html += String((closes[b.idx] as (s?: unknown) => unknown)(scope));
|
|
551
|
+
applyHead(html);
|
|
552
|
+
});
|
|
553
|
+
for (const b of blocks) {
|
|
554
|
+
b.nodes.forEach((nd) => nd.remove());
|
|
555
|
+
b.start.remove();
|
|
556
|
+
b.end.remove();
|
|
557
|
+
}
|
|
558
|
+
} else if (root.nodeType !== 11) clearHead();
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
const all = (holder as Element).querySelectorAll('*');
|
|
562
|
+
all.forEach((el) => {
|
|
563
|
+
if (islandSkip && el.closest('[data-rv-island]')) return;
|
|
564
|
+
for (const an of el.getAttributeNames()) {
|
|
565
|
+
if (!an.startsWith('data-b')) continue;
|
|
566
|
+
const idx = Number(an.slice(6));
|
|
567
|
+
if (!Number.isFinite(idx)) continue;
|
|
568
|
+
const attr = el.getAttribute(an)!;
|
|
569
|
+
el.removeAttribute(an);
|
|
570
|
+
const effect = () => String((closes[idx] as (s?: unknown) => unknown)(scope));
|
|
571
|
+
if (attr === 'data-use-param') {
|
|
572
|
+
weff(() => {
|
|
573
|
+
const raw = effect();
|
|
574
|
+
let p: unknown = raw;
|
|
575
|
+
try { p = JSON.parse(raw); } catch { /* string param */ }
|
|
576
|
+
actionRecords.get(el)?.update?.(p);
|
|
577
|
+
});
|
|
578
|
+
continue;
|
|
579
|
+
}
|
|
580
|
+
if (attr === 'value') {
|
|
581
|
+
weff(() => {
|
|
582
|
+
const v = effect();
|
|
583
|
+
const inp = el as unknown as HTMLInputElement;
|
|
584
|
+
if (inp.value !== v) inp.value = v;
|
|
585
|
+
});
|
|
586
|
+
} else if (attr.startsWith('!')) {
|
|
587
|
+
const name = attr.slice(1);
|
|
588
|
+
weff(() => {
|
|
589
|
+
const v = (closes[idx] as (s?: unknown) => unknown)(scope);
|
|
590
|
+
const live = !(v === false || v == null || v === '' || v === 'false' || v === 0);
|
|
591
|
+
const target = el as unknown as Record<string, unknown>;
|
|
592
|
+
if (target[name] !== live) target[name] = live;
|
|
593
|
+
if (live) el.setAttribute(name, '');
|
|
594
|
+
else el.removeAttribute(name);
|
|
595
|
+
});
|
|
596
|
+
} else {
|
|
597
|
+
weff(() => { el.setAttribute(attr, effect()); });
|
|
598
|
+
}
|
|
440
599
|
}
|
|
441
|
-
} else if (root.nodeType !== 11) clearHead();
|
|
442
|
-
|
|
443
|
-
// Attributes: data-b="K:attrName"
|
|
444
|
-
const els = (holder as Element).querySelectorAll('[data-b]');
|
|
445
|
-
els.forEach((el) => {
|
|
446
|
-
const spec = el.getAttribute('data-b')!;
|
|
447
|
-
const sep = spec.indexOf(':');
|
|
448
|
-
const idx = +spec.slice(0, sep);
|
|
449
|
-
const attr = spec.slice(sep + 1);
|
|
450
|
-
el.removeAttribute('data-b');
|
|
451
|
-
weff(() => {
|
|
452
|
-
el.setAttribute(attr, String((closes[idx] as (s?: unknown) => unknown)(scope)));
|
|
453
|
-
});
|
|
454
600
|
});
|
|
455
601
|
|
|
602
|
+
const uses = (holder as Element).querySelectorAll('[data-use]');
|
|
603
|
+
uses.forEach((el) => {
|
|
604
|
+
if (islandSkip && el.closest('[data-rv-island]')) return;
|
|
605
|
+
const name = el.getAttribute('data-use')!;
|
|
606
|
+
const fn = directives[name];
|
|
607
|
+
if (!fn) {
|
|
608
|
+
console.warn(`rosetack: use:${name} has no registered action (directives.${name}?)`);
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
const rawParam = el.getAttribute('data-use-param');
|
|
612
|
+
let initial: unknown = rawParam ?? undefined;
|
|
613
|
+
if (typeof initial === 'string') {
|
|
614
|
+
try { initial = JSON.parse(initial); } catch { /* plain string param */ }
|
|
615
|
+
}
|
|
616
|
+
const ret = fn(el, initial);
|
|
617
|
+
if (typeof ret === 'function') created.push(ret);
|
|
618
|
+
else if (ret && typeof ret === 'object') {
|
|
619
|
+
actionRecords.set(el, { update: ret.update, destroy: ret.destroy });
|
|
620
|
+
if (ret.destroy) created.push(ret.destroy);
|
|
621
|
+
}
|
|
622
|
+
});
|
|
623
|
+
|
|
624
|
+
const refs = (holder as Element).querySelectorAll('[data-bind-this]');
|
|
625
|
+
refs.forEach((el) => {
|
|
626
|
+
if (islandSkip && el.closest('[data-rv-island]')) return;
|
|
627
|
+
const key = el.getAttribute('data-bind-this')!;
|
|
628
|
+
setState(key, el);
|
|
629
|
+
created.push(() => setState(key, null));
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
const DELEGATED_SET = new Set(['click', 'input', 'change', 'submit']);
|
|
633
|
+
const evRoot = holder as Element;
|
|
634
|
+
const evTargets = [evRoot, ...Array.from(evRoot.querySelectorAll('*'))];
|
|
635
|
+
for (const el of evTargets) {
|
|
636
|
+
if (!el.getAttributeNames) continue;
|
|
637
|
+
if (islandSkip && el.closest && el.closest('[data-rv-island]')) continue;
|
|
638
|
+
for (const an of el.getAttributeNames()) {
|
|
639
|
+
const mm = /^data-on(w|d)?-(.+)$/.exec(an);
|
|
640
|
+
if (!mm) continue;
|
|
641
|
+
const ev = mm[2];
|
|
642
|
+
if (!mm[1] && DELEGATED_SET.has(ev)) continue;
|
|
643
|
+
const g = globalThis as { window?: EventTarget; document?: { defaultView?: EventTarget } & EventTarget };
|
|
644
|
+
const win = g.window ?? g.document?.defaultView;
|
|
645
|
+
const target: EventTarget | undefined = mm[1] === 'w' ? win : mm[1] === 'd' ? (g.document as EventTarget) : el;
|
|
646
|
+
if (!target) continue;
|
|
647
|
+
let seen = directBound.get(el);
|
|
648
|
+
if (!seen) directBound.set(el, (seen = new Set()));
|
|
649
|
+
if (seen.has(ev)) continue;
|
|
650
|
+
seen.add(ev);
|
|
651
|
+
const spec = el.getAttribute(an)!;
|
|
652
|
+
const listener = (e: Event) => {
|
|
653
|
+
if (!el.hasAttribute(an)) return;
|
|
654
|
+
if (spec.startsWith('$action:')) {
|
|
655
|
+
if (actionDispatch) actionDispatch(spec.slice('$action:'.length), e);
|
|
656
|
+
return;
|
|
657
|
+
}
|
|
658
|
+
const h = handlers[spec];
|
|
659
|
+
if (h) h(e);
|
|
660
|
+
};
|
|
661
|
+
target.addEventListener(ev, listener);
|
|
662
|
+
created.push(() => {
|
|
663
|
+
target.removeEventListener(ev, listener);
|
|
664
|
+
const s = directBound.get(el);
|
|
665
|
+
if (s) s.delete(ev);
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
|
|
456
670
|
if (holder !== root) {
|
|
457
671
|
while (holder.firstChild) root.appendChild(holder.firstChild);
|
|
458
672
|
}
|
|
@@ -463,12 +677,10 @@ export function wire(root: Node, closes: Array<unknown>, scope?: unknown): Clean
|
|
|
463
677
|
export function resetEffects(): void {
|
|
464
678
|
cleanups.forEach((fn) => fn());
|
|
465
679
|
cleanups.clear();
|
|
680
|
+
pendingIslandObservers.forEach((io) => io.disconnect());
|
|
681
|
+
pendingIslandObservers.clear();
|
|
466
682
|
}
|
|
467
683
|
|
|
468
|
-
// === Server Data Fetching ($data) ===
|
|
469
|
-
|
|
470
|
-
// Trade-off: cache keyed by function source, cleared per request/navigation.
|
|
471
|
-
// Upgrade path: explicit keys if two $data calls share identical source.
|
|
472
684
|
let dataCache = new Map<string, Promise<unknown>>();
|
|
473
685
|
|
|
474
686
|
export function $data<T>(fn: () => T | Promise<T>): Promise<T> {
|
|
@@ -481,16 +693,12 @@ export function $data<T>(fn: () => T | Promise<T>): Promise<T> {
|
|
|
481
693
|
return p as Promise<T>;
|
|
482
694
|
}
|
|
483
695
|
|
|
484
|
-
// Per-request isolation: state + data cache reset before each SSR render. The request
|
|
485
|
-
// context bag is NOT reset here: it is owned by the middleware pass (runMiddleware) …
|
|
486
696
|
export function clearRequestState(): void {
|
|
487
697
|
signalMap.clear();
|
|
488
698
|
dataCache.clear();
|
|
489
699
|
pendingDeltas.clear();
|
|
490
700
|
}
|
|
491
701
|
|
|
492
|
-
// === Request query (P0-1) === The parsed query string of the request being rendered
|
|
493
|
-
// (?page=2&q=x -> {page:'2',q:'x'}) …
|
|
494
702
|
let requestQuery: Record<string, string> = {};
|
|
495
703
|
let prefetchOverride: Record<string, string> | null = null;
|
|
496
704
|
|
|
@@ -512,8 +720,6 @@ export function setPrefetchOverride(q: Record<string, string> | null): void {
|
|
|
512
720
|
prefetchOverride = q;
|
|
513
721
|
}
|
|
514
722
|
|
|
515
|
-
// === Request context === A per-request bag: pages/_middleware.rose fills it
|
|
516
|
-
// (getContext().user = ...) and $data, server actions and api handlers read it.
|
|
517
723
|
let requestContext: Record<string, unknown> = {};
|
|
518
724
|
|
|
519
725
|
export function getContext(): Record<string, unknown> {
|
|
@@ -547,7 +753,7 @@ export async function isolateStateAsync<T>(
|
|
|
547
753
|
): Promise<{ result: T; state: Map<string, SignalEntry>; mounts: Array<() => void>; cleanups: Set<Cleanup> }> {
|
|
548
754
|
const savedSignals = signalMap;
|
|
549
755
|
const savedData = dataCache;
|
|
550
|
-
const savedDeltas = new Map(pendingDeltas);
|
|
756
|
+
const savedDeltas = new Map(pendingDeltas);
|
|
551
757
|
pendingDeltas.clear();
|
|
552
758
|
const savedMounts = mountQueue.splice(0, mountQueue.length);
|
|
553
759
|
const savedCleanups = new Set(cleanups);
|
|
@@ -566,8 +772,8 @@ export async function isolateStateAsync<T>(
|
|
|
566
772
|
signalMap = savedSignals;
|
|
567
773
|
dataCache = savedData;
|
|
568
774
|
pendingDeltas.clear();
|
|
569
|
-
savedDeltas.forEach((d, k) => pendingDeltas.set(k, d));
|
|
570
|
-
mountQueue.splice(0, 0, ...savedMounts);
|
|
775
|
+
savedDeltas.forEach((d, k) => pendingDeltas.set(k, d));
|
|
776
|
+
mountQueue.splice(0, 0, ...savedMounts);
|
|
571
777
|
cleanups.clear();
|
|
572
778
|
savedCleanups.forEach((fn: Cleanup) => cleanups.add(fn));
|
|
573
779
|
}
|
|
@@ -579,8 +785,6 @@ export function restoreState(entries: Map<string, SignalEntry>): void {
|
|
|
579
785
|
entries.forEach((e: SignalEntry, k: string) => signalMap.set(k, e));
|
|
580
786
|
}
|
|
581
787
|
|
|
582
|
-
// === Serialization (for zero-hydration resume) ===
|
|
583
|
-
|
|
584
788
|
export function serializeState(): string {
|
|
585
789
|
const obj: Record<string, unknown> = {};
|
|
586
790
|
signalMap.forEach((v: { value: unknown }, k: string) => (obj[k] = v.value));
|
|
@@ -598,8 +802,6 @@ export function resumeState(json: string): void {
|
|
|
598
802
|
}
|
|
599
803
|
}
|
|
600
804
|
|
|
601
|
-
// === Client-side route refresh === The client entry registers the re-render here at boot;
|
|
602
|
-
// components import refresh() like state() and call it from any handler …
|
|
603
805
|
let refreshHook: (() => Promise<void>) | null = null;
|
|
604
806
|
|
|
605
807
|
export function setRefreshHook(fn: () => Promise<void>): void {
|
|
@@ -610,12 +812,10 @@ export function refresh(): Promise<void> {
|
|
|
610
812
|
return refreshHook ? refreshHook() : Promise.resolve();
|
|
611
813
|
}
|
|
612
814
|
|
|
613
|
-
// === Lifecycle === Client-only. onMount queues a callback; the client entry flushes the
|
|
614
|
-
// queue after wire() completes - initial adoption, client-side navigation, prefetch paint …
|
|
615
815
|
const mountQueue: Array<() => void> = [];
|
|
616
816
|
|
|
617
817
|
export function onMount(fn: () => void): void {
|
|
618
|
-
if (typeof document === 'undefined') return;
|
|
818
|
+
if (typeof document === 'undefined') return;
|
|
619
819
|
mountQueue.push(fn);
|
|
620
820
|
}
|
|
621
821
|
|
|
@@ -632,7 +832,7 @@ export function flushMounts(): void {
|
|
|
632
832
|
|
|
633
833
|
/** Register a disposer for the current render (the effects' cleanup channel). */
|
|
634
834
|
export function onCleanup(fn: Cleanup): void {
|
|
635
|
-
|
|
835
|
+
fxSet().add(fn);
|
|
636
836
|
}
|
|
637
837
|
|
|
638
838
|
/**
|
|
@@ -645,12 +845,8 @@ export function adoptCleanups(fns: Iterable<Cleanup>): void {
|
|
|
645
845
|
for (const fn of fns) cleanups.add(fn);
|
|
646
846
|
}
|
|
647
847
|
|
|
648
|
-
// === i18n: localized routes === Every JSON file in src/locales/ is a language: { "key":
|
|
649
|
-
// "string" }.
|
|
650
848
|
let LOCALES: Record<string, Record<string, string>> = {};
|
|
651
849
|
let DEFAULT_LOCALE = 'en';
|
|
652
|
-
// The locales this build did NOT bake in: they live at /locales/<lang>.json and
|
|
653
|
-
// ensureLocale() fetches one on first use.
|
|
654
850
|
let LOCALE_PACKS: string[] = [];
|
|
655
851
|
|
|
656
852
|
export function setLocales(dicts: Record<string, Record<string, string>>, def: string): void {
|
|
@@ -691,8 +887,6 @@ export function localeList(): string[] {
|
|
|
691
887
|
}
|
|
692
888
|
|
|
693
889
|
export function isLocale(lang: string): boolean {
|
|
694
|
-
// A pack counts as a known locale BEFORE it loads: the client router must
|
|
695
|
-
// not 404 /ar/about while /locales/ar.json is still in flight.
|
|
696
890
|
return Object.hasOwn(LOCALES, lang) || LOCALE_PACKS.includes(lang);
|
|
697
891
|
}
|
|
698
892
|
|
|
@@ -713,6 +907,42 @@ export function bestLocale(header: string | null | undefined): string | null {
|
|
|
713
907
|
return null;
|
|
714
908
|
}
|
|
715
909
|
|
|
910
|
+
/** The signal `redirect()` throws. */
|
|
911
|
+
export class RoseRedirect extends Error {
|
|
912
|
+
readonly __rosetack = 'redirect';
|
|
913
|
+
constructor(readonly path: string, readonly status = 307) {
|
|
914
|
+
super(`redirect to ${path}`);
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
/** The signal `notFound()` throws. */
|
|
919
|
+
export class RoseNotFound extends Error {
|
|
920
|
+
readonly __rosetack = 'notFound';
|
|
921
|
+
constructor() {
|
|
922
|
+
super('notFound()');
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
/**
|
|
927
|
+
* Send the visitor somewhere else: the response becomes a 30x with this
|
|
928
|
+
* Location. Call it from a page's `$data` body (a wall, a renamed slug, a
|
|
929
|
+
* canonical URL) or from an api handler. A route that calls it is buffered by
|
|
930
|
+
* the compiler, so the status can still be set.
|
|
931
|
+
*/
|
|
932
|
+
export function redirect(path: string, status = 307): never {
|
|
933
|
+
throw new RoseRedirect(path, status);
|
|
934
|
+
}
|
|
935
|
+
|
|
936
|
+
/**
|
|
937
|
+
* Answer 404 with the app's own 404 route (pages/404.rose) instead of the
|
|
938
|
+
* built-in page. Call it from a page's `$data` body when the slug resolves to
|
|
939
|
+
* nothing - the status is a real 404 and the body is the app's design, which
|
|
940
|
+
* is the one thing a middleware wall cannot do from outside the render.
|
|
941
|
+
*/
|
|
942
|
+
export function notFound(): never {
|
|
943
|
+
throw new RoseNotFound();
|
|
944
|
+
}
|
|
945
|
+
|
|
716
946
|
/**
|
|
717
947
|
* Reading direction of a locale. The set of right-to-left scripts is closed
|
|
718
948
|
* (Arabic, Hebrew and their relatives), so a base-tag test covers every
|
|
@@ -727,8 +957,6 @@ export function localeDir(lang: string): string {
|
|
|
727
957
|
return RTL_RE.test(lang) ? 'rtl' : '';
|
|
728
958
|
}
|
|
729
959
|
|
|
730
|
-
// --- ICU MessageFormat, the subset real apps use --------------------- {count, plural, =0
|
|
731
|
-
// {No signatures yet} one {# item} other {# items}} {n, selectordinal …
|
|
732
960
|
const ICU_RE = /\{([\w$]+),\s*(plural|selectordinal|select),\s*((?:\s*[=\w]+\s*\{(?:[^{}]|\{[^{}]*\})*\})*)\}/g;
|
|
733
961
|
const BRANCH_RE = /([=\w]+)\s*\{((?:[^{}]|\{[^{}]*\})*)\}/g;
|
|
734
962
|
|
|
@@ -737,7 +965,7 @@ function pluralCategory(locale: string, ordinal: boolean, n: number): string | n
|
|
|
737
965
|
try {
|
|
738
966
|
return new Intl.PluralRules(locale, ordinal ? { type: 'ordinal' } : undefined).select(n);
|
|
739
967
|
} catch {
|
|
740
|
-
return null;
|
|
968
|
+
return null;
|
|
741
969
|
}
|
|
742
970
|
}
|
|
743
971
|
|
|
@@ -746,12 +974,10 @@ function expandIcu(msg: string, vars: Record<string, string | number> | undefine
|
|
|
746
974
|
return msg.replace(ICU_RE, (whole, arg: string, kind: string, branchText: string) => {
|
|
747
975
|
const branches: Record<string, string> = {};
|
|
748
976
|
for (const m of branchText.matchAll(BRANCH_RE)) branches[m[1]] = m[2];
|
|
749
|
-
if (!branches.other) return whole;
|
|
977
|
+
if (!branches.other) return whole;
|
|
750
978
|
const v = vars?.[arg];
|
|
751
979
|
if (kind === 'select') return branches[typeof v === 'string' && branches[v] ? v : 'other'];
|
|
752
980
|
const num = typeof v === 'number' ? v : Number(v);
|
|
753
|
-
// An =N arm wins over the category; a value with no number in it has no category at
|
|
754
|
-
// all, so it takes the other arm - and # prints the value as given …
|
|
755
981
|
const cat = isFinite(num)
|
|
756
982
|
? (branches['=' + num] ? '=' + num : pluralCategory(locale, kind === 'selectordinal', num) ?? 'other')
|
|
757
983
|
: 'other';
|
|
@@ -774,10 +1000,6 @@ export function $t(key: string, vars?: Record<string, string | number>): string
|
|
|
774
1000
|
return out;
|
|
775
1001
|
}
|
|
776
1002
|
|
|
777
|
-
// --- the shared server store ---------------------------------------- Module scope
|
|
778
|
-
// (`export const store = {...}`) is per-PROCESS: under the cluster every worker holds its
|
|
779
|
-
// own …
|
|
780
|
-
|
|
781
1003
|
const STORES = new Map<string, { value: unknown }>();
|
|
782
1004
|
let storeTransport: ((name: string, value: unknown) => void) | null = null;
|
|
783
1005
|
|
|
@@ -827,22 +1049,6 @@ export function $store<T>(name: string, initial: T): { get(): T; set(v: T): void
|
|
|
827
1049
|
};
|
|
828
1050
|
}
|
|
829
1051
|
|
|
830
|
-
// --- server action errors, guards and incremental patches -----------
|
|
831
|
-
//
|
|
832
|
-
// The action model's three gaps, closed with one request-scoped mechanism.
|
|
833
|
-
//
|
|
834
|
-
// 1. A standardized failure object. An action that cannot do its job (bad
|
|
835
|
-
// input, not signed in, a duplicate) throws ActionError; the dispatch
|
|
836
|
-
// catches it, seeds the page's state with it and re-renders, so the page
|
|
837
|
-
// answers with the failure VISIBLE (status = the error's code) instead of
|
|
838
|
-
// a 500 or a silent no-op. A bug still propagates to the 500 page.
|
|
839
|
-
// 2. A guard. `export async function beforeAction(name, form)` runs before
|
|
840
|
-
// every action of its page and vetoes with an ActionError - the
|
|
841
|
-
// action-level permission check (a redirect stays the middleware's job).
|
|
842
|
-
// 3. Incremental patches. A patch value may be an OPERATION ($append and
|
|
843
|
-
// friends) instead of a whole replacement, so growing a large list costs
|
|
844
|
-
// one row instead of a second copy of the list.
|
|
845
|
-
|
|
846
1052
|
export class ActionError extends Error {
|
|
847
1053
|
/** the HTTP status the response carries (400/401/403/409/422/...) */
|
|
848
1054
|
code: number;
|
|
@@ -871,7 +1077,7 @@ export type ActionErrorInfo = { action: string; message: string; code: number; f
|
|
|
871
1077
|
export function $actionError(): ActionErrorInfo | null {
|
|
872
1078
|
const e = signalMap.get('actionError');
|
|
873
1079
|
if (!e) return null;
|
|
874
|
-
if (currentEffect) e.subs.add(currentEffect);
|
|
1080
|
+
if (currentEffect) e.subs.add(currentEffect);
|
|
875
1081
|
return (e.value as ActionErrorInfo | null) ?? null;
|
|
876
1082
|
}
|
|
877
1083
|
|
|
@@ -892,8 +1098,6 @@ export function $boundaryFallback(err: unknown): string {
|
|
|
892
1098
|
return '<p>This section failed to render.</p>';
|
|
893
1099
|
}
|
|
894
1100
|
|
|
895
|
-
// An incremental patch: an action's return value may map a key to an OPERATION instead of a
|
|
896
|
-
// whole replacement value …
|
|
897
1101
|
export type StateDeltaOp = 'append' | 'prepend' | 'merge';
|
|
898
1102
|
|
|
899
1103
|
export class StateDelta {
|
|
@@ -943,9 +1147,6 @@ export function applyStateDelta(key: string, delta: StateDelta): void {
|
|
|
943
1147
|
setState(key, merged);
|
|
944
1148
|
}
|
|
945
1149
|
|
|
946
|
-
// --- cookie helpers ------------------------------------------------- Sessions are the
|
|
947
|
-
// first thing every real app needs and the easiest thing to get subtly wrong …
|
|
948
|
-
|
|
949
1150
|
/**
|
|
950
1151
|
* Parse the cookies of a request (server) or of this document (client, where
|
|
951
1152
|
* HttpOnly cookies are invisible by design - that is the point of HttpOnly).
|
|
@@ -987,8 +1188,6 @@ export function $sessionCookie(
|
|
|
987
1188
|
].filter(Boolean).join('; ');
|
|
988
1189
|
}
|
|
989
1190
|
|
|
990
|
-
// === Client observability: the web-vitals hook === A framework that sells TTFB, one
|
|
991
|
-
// request and zero hydration owes the app a way to prove it in production.
|
|
992
1191
|
export function reportVitals(): void {
|
|
993
1192
|
if (typeof window === 'undefined' || typeof performance === 'undefined') return;
|
|
994
1193
|
const live: Record<string, number> = {};
|
|
@@ -1003,7 +1202,7 @@ export function reportVitals(): void {
|
|
|
1003
1202
|
const fcp = paints.find((p) => p.name === 'first-contentful-paint');
|
|
1004
1203
|
if (fcp) send('fcp', Math.round(fcp.startTime));
|
|
1005
1204
|
const PO = (window as unknown as { PerformanceObserver?: typeof PerformanceObserver }).PerformanceObserver;
|
|
1006
|
-
if (!PO) return;
|
|
1205
|
+
if (!PO) return;
|
|
1007
1206
|
let cls = 0;
|
|
1008
1207
|
let inp = 0;
|
|
1009
1208
|
const flush = () => {
|