@sigil-dev/grimoire 0.9.3 → 0.9.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/index.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  export { Head } from "./src/rendering/head";
2
+ // server loads call depends() to register invalidation keys
3
+ export { depends } from "./src/client/deps";
2
4
  // registerSSRPlugin is server-only — import from "@sigil-dev/grimoire/bun"
3
5
  export type { RouteFile, RouteTree } from "./src/routing/scanner";
4
6
  export type { ErrorResult } from "./src/sentinels/error.ts";
package/package.json CHANGED
@@ -4,12 +4,13 @@
4
4
  "module": "index.ts",
5
5
  "type": "module",
6
6
  "private": false,
7
- "version": "0.9.3",
7
+ "version": "0.9.4",
8
8
  "exports": {
9
9
  ".": "./index.ts",
10
10
  "./server": "./server.ts",
11
11
  "./coordinator": "./src/server/coordinator.ts",
12
12
  "./client": "./src/client/enhance.ts",
13
+ "./client/router": "./src/client/router.ts",
13
14
  "./headers": "./src/headers.ts",
14
15
  "./hooks": "./src/server/hooks.ts",
15
16
  "./vite": "./src/integrations/vite.ts",
@@ -18,27 +19,23 @@
18
19
  "./env/private": "./src/env/private.ts",
19
20
  "./logger": "./src/logger/index.ts"
20
21
  },
21
- "bin": {
22
- "grimoire": "src/sync.ts"
23
- },
24
22
  "scripts": {
25
- "sync": "bun src/sync.ts",
26
23
  "test": "bun test"
27
24
  },
28
25
  "dependencies": {
29
- "@sigil-dev/compiler": "0.9.3",
30
- "@sigil-dev/runtime": "0.9.3",
26
+ "@sigil-dev/compiler": "0.9.4",
27
+ "@sigil-dev/runtime": "0.9.4",
31
28
  "vite": "^8.0.16"
32
29
  },
33
30
  "peerDependencies": {
34
31
  "typescript": "^5"
35
32
  },
36
33
  "devDependencies": {
37
- "@babel/core": "^8.0.0-rc.6",
38
- "@babel/plugin-syntax-jsx": "^8.0.0-rc.6",
39
- "@babel/plugin-syntax-typescript": "^8.0.0-rc.6",
40
- "@babel/preset-typescript": "^8.0.0-rc.6",
41
- "@babel/types": "^8.0.0-rc.6",
34
+ "@babel/core": "8.0.0-rc.6",
35
+ "@babel/plugin-syntax-jsx": "8.0.0-rc.6",
36
+ "@babel/plugin-syntax-typescript": "8.0.0-rc.6",
37
+ "@babel/preset-typescript": "8.0.0-rc.6",
38
+ "@babel/types": "8.0.0-rc.6",
42
39
  "@types/bun": "latest"
43
40
  }
44
41
  }
@@ -4,16 +4,33 @@ let _collecting: Set<string> | null = null;
4
4
  export function startCollecting(): void {
5
5
  _collecting = new Set();
6
6
  }
7
- export function stopCollecting(pattern: string): void {
8
- if (_collecting) routeDeps.set(pattern, _collecting);
7
+
8
+ /** Stop collecting and return the keys gathered. When `pattern` is given,
9
+ * the keys are also recorded as that route's dependency set. */
10
+ export function stopCollecting(pattern?: string): string[] {
11
+ const keys = _collecting ? [..._collecting] : [];
12
+ if (_collecting && pattern) routeDeps.set(pattern, new Set(keys));
9
13
  _collecting = null;
14
+ return keys;
10
15
  }
16
+
11
17
  export function depends(key: string): void {
12
18
  _collecting?.add(key);
13
19
  }
20
+
14
21
  export function hasDep(pattern: string, key: string): boolean {
15
22
  return routeDeps.get(pattern)?.has(key) ?? false;
16
23
  }
24
+
17
25
  export function clearDeps(pattern: string): void {
18
26
  routeDeps.delete(pattern);
19
27
  }
28
+
29
+ /** Seed a route's dependency set (e.g. from server-rendered state). */
30
+ export function setDeps(pattern: string, keys: string[]): void {
31
+ routeDeps.set(pattern, new Set(keys));
32
+ }
33
+
34
+ export function getDeps(pattern: string): Set<string> | undefined {
35
+ return routeDeps.get(pattern);
36
+ }
@@ -42,8 +42,12 @@ export function enhance(
42
42
  e.preventDefault();
43
43
 
44
44
  const formData = new FormData(form);
45
- const url =
45
+ const resolved =
46
46
  action ?? form.getAttribute("action") ?? window.location.pathname;
47
+ // SvelteKit-style named action: "?/create" submits to the current path
48
+ const url = resolved.startsWith("?/")
49
+ ? window.location.pathname + resolved
50
+ : resolved;
47
51
 
48
52
  try {
49
53
  const res = await fetch(url, {
@@ -1,5 +1,5 @@
1
- // @ts-expect-error Compiler generated/linked
2
- import { layouts, routes } from "#grimoire-routes";
3
- import { initRouter } from "./router.ts";
4
-
5
- initRouter(routes, layouts);
1
+ // @ts-expect-error Compiler generated/linked
2
+ import { layouts, matchers, routes } from "#grimoire-routes";
3
+ import { initRouter } from "./router.ts";
4
+
5
+ initRouter(routes, layouts, undefined, { matchers });
@@ -1,18 +1,16 @@
1
1
  import { popHydrationNodes, pushHydrationNodes } from "@sigil-dev/runtime";
2
+ import {
3
+ clearDeps,
4
+ depends,
5
+ getDeps,
6
+ setDeps,
7
+ startCollecting,
8
+ stopCollecting,
9
+ } from "./deps";
2
10
  import { withEffectScope } from "./scope";
3
11
 
4
- // ── Dependency tracking ──────────────────────────────────────────────────────
5
- const routeDeps = new Map<string, Set<string>>(); // pattern → dep keys
6
- let _collectingDeps: Set<string> | null = null;
7
-
8
- /**
9
- * Call from inside a load() function to register a dependency key.
10
- * When invalidate(key) is called, any route that depends on that key
11
- * will refetch if it's the current route.
12
- */
13
- export function depends(key: string): void {
14
- _collectingDeps?.add(key);
15
- }
12
+ // re-exported for app code that imports depends() from the router module
13
+ export { depends };
16
14
 
17
15
  async function refetchCurrent(): Promise<void> {
18
16
  if (!lastState) return;
@@ -22,9 +20,11 @@ async function refetchCurrent(): Promise<void> {
22
20
  export async function invalidate(...keys: string[]): Promise<void> {
23
21
  const current = lastState?.pattern;
24
22
  if (!current) return;
25
- const deps = routeDeps.get(current);
26
- if (!deps) return;
27
- if (keys.some((k) => deps.has(k))) await refetchCurrent();
23
+ const deps = getDeps(current);
24
+ // no recorded deps → conservative refetch; otherwise only on intersection
25
+ if (!deps || deps.size === 0 || keys.some((k) => deps.has(k))) {
26
+ await refetchCurrent();
27
+ }
28
28
  }
29
29
 
30
30
  export async function invalidateAll(): Promise<void> {
@@ -38,7 +38,9 @@ type PageComponent = ((props: any) => any) & {
38
38
  };
39
39
  /** Manifest entries are lazy (`{ __lazy: () => import(...) }`); plain
40
40
  * component functions are also accepted (tests, HMR replacements). */
41
- type RouteEntry = PageComponent | { __lazy: () => Promise<{ default: PageComponent }> };
41
+ type RouteEntry =
42
+ | PageComponent
43
+ | { __lazy: () => Promise<{ default: PageComponent }> };
42
44
 
43
45
  let routeMap: Record<string, RouteEntry> = {};
44
46
  const resolvedRoutes: Record<string, PageComponent> = {};
@@ -106,12 +108,15 @@ function saveScrollPosition(): void {
106
108
  }
107
109
 
108
110
  function restoreScrollPosition(path: string): void {
109
- const saved = scrollPositions.get(path);
110
- if (saved !== undefined) {
111
- requestAnimationFrame(() => window.scrollTo(0, saved));
112
- } else {
113
- requestAnimationFrame(() => window.scrollTo(0, 0));
114
- }
111
+ const y = scrollPositions.get(path) ?? 0;
112
+ window.scrollTo(0, y);
113
+ // re-assert after layout settles (late effects/images can shift content)
114
+ requestAnimationFrame(() => window.scrollTo(0, y));
115
+ }
116
+
117
+ function scrollToTop(): void {
118
+ window.scrollTo(0, 0);
119
+ requestAnimationFrame(() => window.scrollTo(0, 0));
115
120
  }
116
121
 
117
122
  // C3: Preloading
@@ -124,12 +129,20 @@ function setupPreload(): void {
124
129
  const href = a.getAttribute("href");
125
130
  if (!href) return;
126
131
  if (/^(https?:\/\/|\/\/|#|mailto:|tel:)/.test(href)) return;
132
+ if (a.getAttribute("data-sigil-preload") === "off") return;
133
+
134
+ // Only prefetch links that resolve to a known client route — external
135
+ // pages and non-page endpoints (API routes, redirects) are skipped.
136
+ try {
137
+ const url = new URL(href, location.origin);
138
+ if (!findPattern(url.pathname)) return;
139
+ } catch {
140
+ return;
141
+ }
127
142
 
128
- const preloadData = a.hasAttribute("data-sigil-preload-data");
129
143
  const preloadCode = a.hasAttribute("data-sigil-preload-code");
130
- if (!preloadData && !preloadCode) return;
131
144
 
132
- if (preloadTimer) clearTimeout(preloadTimer);
145
+ clearTimeout(preloadTimer);
133
146
  preloadTimer = setTimeout(() => {
134
147
  if (preloadCode) {
135
148
  const link = document.createElement("link");
@@ -137,20 +150,19 @@ function setupPreload(): void {
137
150
  link.href = href;
138
151
  document.head.appendChild(link);
139
152
  }
140
- if (preloadData) {
141
- fetch(href, {
142
- headers: { "x-grimoire-navigate": "1" },
143
- redirect: "manual",
144
- priority: "low",
145
- }).catch(() => {});
146
- }
153
+ // data prefetch is the default; -code is the explicit escalation
154
+ fetch(href, {
155
+ headers: { "x-grimoire-navigate": "1" },
156
+ redirect: "manual",
157
+ priority: "low",
158
+ }).catch(() => {});
147
159
  }, 80);
148
160
  });
149
161
 
150
162
  document.addEventListener("mouseout", (e) => {
151
163
  const a = (e.target as Element).closest("a");
152
164
  if (!a) return;
153
- if (preloadTimer) clearTimeout(preloadTimer);
165
+ clearTimeout(preloadTimer);
154
166
  });
155
167
  }
156
168
 
@@ -203,16 +215,24 @@ function matchClientPattern(pattern: string, pathname: string): boolean {
203
215
  // haha pp and ph
204
216
  const pp = pattern.split("/").filter(Boolean);
205
217
  const ph = pathname.split("/").filter(Boolean);
206
- let pi = 0,
207
- pj = 0;
208
- while (pi < pp.length) {
209
- if (pp[pi]!.startsWith("*")) return true;
210
- if (pj >= ph.length) return false;
211
- if (!pp[pi]!.startsWith(":") && pp[pi] !== ph[pj]) return false;
212
- pi++;
213
- pj++;
218
+
219
+ // Depth-first walk; optional segments (:x?) try consuming one segment
220
+ // before consuming zero, mirroring the server's matchPattern.
221
+ function walk(pi: number, pj: number): boolean {
222
+ if (pi === pp.length) return pj === ph.length;
223
+ const part = pp[pi]!;
224
+ if (part.startsWith("*")) return true;
225
+ const optional = part.startsWith(":") && part.endsWith("?");
226
+ if (optional && pj < ph.length && walk(pi + 1, pj + 1)) return true;
227
+ if (!optional) {
228
+ if (pj >= ph.length) return false;
229
+ if (!part.startsWith(":") && part !== ph[pj]) return false;
230
+ return walk(pi + 1, pj + 1);
231
+ }
232
+ return walk(pi + 1, pj);
214
233
  }
215
- return pj === ph.length;
234
+
235
+ return walk(0, 0);
216
236
  }
217
237
 
218
238
  function findPattern(pathname: string): string | null {
@@ -272,7 +292,10 @@ export async function navigate(
272
292
  else document.getElementById("grimoire-root")?.replaceChildren(loadingNode);
273
293
  }
274
294
 
275
- const res = await fetch(path, { headers: { "x-grimoire-navigate": "1" }, redirect: "manual" });
295
+ const res = await fetch(path, {
296
+ headers: { "x-grimoire-navigate": "1" },
297
+ redirect: "manual",
298
+ });
276
299
  if (navId !== navigationId) return;
277
300
  const contentType = res.headers.get("content-type") ?? "";
278
301
  if (!contentType.includes("application/json")) {
@@ -281,7 +304,7 @@ export async function navigate(
281
304
  }
282
305
  const json = await res.json();
283
306
  if (navId !== navigationId) return;
284
- const { data, layoutData, params, pattern, head } = json;
307
+ const { data, layoutData, params, pattern, head, deps } = json;
285
308
  const Page = await resolveRoute(pattern);
286
309
  if (navId !== navigationId) return;
287
310
  if (!Page) {
@@ -292,24 +315,43 @@ export async function navigate(
292
315
  let mergedData = data;
293
316
  if (Page.load) {
294
317
  try {
295
- _collectingDeps = new Set();
318
+ startCollecting();
296
319
  const clientData = await Page.load({
297
320
  params,
298
321
  url,
299
322
  request: new Request(url),
323
+ // layout loads run server-side; their data arrives in layoutData —
324
+ // parent() merges it outermost-first, mirroring the server context
325
+ parent: async () =>
326
+ Object.assign(
327
+ {},
328
+ ...(Array.isArray(layoutData) ? layoutData : []).filter(
329
+ (d) => d && typeof d === "object",
330
+ ),
331
+ ),
300
332
  });
301
- routeDeps.set(pattern, _collectingDeps);
302
- _collectingDeps = null;
333
+ // merge server-collected keys (page/layout server loads) with
334
+ // whatever this client-side load itself registered
335
+ setDeps(pattern, [
336
+ ...(Array.isArray(deps) ? deps : []),
337
+ ...stopCollecting(),
338
+ ]);
303
339
  mergedData = { ...clientData, ...data };
304
- } catch (e: any) {
305
- _collectingDeps = null;
306
- if (e?.location) {
307
- window.location.href = e.location;
340
+ } catch (e: unknown) {
341
+ stopCollecting();
342
+ if (e && typeof e === "object" && "location" in e) {
343
+ window.location.href = String(
344
+ (e as { location: unknown }).location,
345
+ );
308
346
  return;
309
347
  }
310
348
  console.error("[grimoire] universal load error:", e);
311
349
  }
312
350
  if (navId !== navigationId) return;
351
+ } else if (Array.isArray(deps)) {
352
+ // no client-side load to run — the server's collected depends() keys
353
+ // (from +page.server.ts / +layout.server.ts) are the whole story
354
+ setDeps(pattern, deps);
313
355
  }
314
356
 
315
357
  // track state for HMR rerender
@@ -330,7 +372,23 @@ export async function navigate(
330
372
  popHydrationNodes();
331
373
 
332
374
  updateHead(head);
333
- document.getElementById("grimoire-root")?.replaceChildren(rootNode);
375
+ // View transitions: animate the swap when the browser supports it and the
376
+ // user hasn't asked for reduced motion. The callback must stay synchronous.
377
+ const doSwap = () => {
378
+ document.getElementById("grimoire-root")?.replaceChildren(rootNode);
379
+ };
380
+ const doc = document as Document & {
381
+ startViewTransition?: (cb: () => void) => unknown;
382
+ };
383
+ if (
384
+ typeof doc.startViewTransition === "function" &&
385
+ !window.matchMedia("(prefers-reduced-motion: reduce)").matches
386
+ ) {
387
+ doc.startViewTransition(doSwap);
388
+ } else {
389
+ doSwap();
390
+ }
391
+ const isRefetch = url.pathname === currentPath;
334
392
  currentPath = url.pathname;
335
393
 
336
394
  if (historyMode !== "none") {
@@ -343,23 +401,43 @@ export async function navigate(
343
401
  if (url.hash) {
344
402
  const target = document.getElementById(url.hash.slice(1));
345
403
  if (target) requestAnimationFrame(() => target.scrollIntoView());
346
- else restoreScrollPosition(url.pathname);
347
- } else {
404
+ else scrollToTop();
405
+ } else if (historyMode === "none") {
406
+ // popstate: the browser already moved through history — restore what
407
+ // we saved for this path (back/forward semantics)
348
408
  restoreScrollPosition(url.pathname);
409
+ } else if (!isRefetch) {
410
+ // fresh navigation: the new page starts at the top
411
+ scrollToTop();
349
412
  }
413
+ // same-path replace (invalidate/refetch): keep the current scroll
350
414
  afterNavigateCb?.(url);
351
415
  }
352
416
 
417
+ export interface RouterExtensions {
418
+ /** [param=matcher] validators from src/params/*.ts (manifest-generated). */
419
+ matchers?: Record<string, (value: string) => boolean>;
420
+ /** Server-collected depends() keys per route pattern (from SSR state). */
421
+ deps?: Record<string, string[]>;
422
+ }
423
+
424
+ let paramMatcherFns: Record<string, (value: string) => boolean> = {};
425
+
353
426
  export function initRouter(
354
427
  routes: Record<string, RouteEntry>,
355
428
  layouts: any[] = [],
356
429
  initialDispose?: () => void,
430
+ ext?: RouterExtensions,
357
431
  ) {
432
+ paramMatcherFns = ext?.matchers ?? {};
358
433
  routeMap = routes;
359
434
  layoutList = layouts;
360
435
  disposeCurrentPage = initialDispose ?? null;
361
436
  currentPath = location.pathname;
362
437
 
438
+ // the app owns scroll: the browser's automatic restoration fires after
439
+ // the router's own scroll and clobbers scroll-to-top / saved positions
440
+ if ("scrollRestoration" in history) history.scrollRestoration = "manual";
363
441
  // set initial HMR state from SSR
364
442
  const stateEl = document.getElementById("__grimoire_state__");
365
443
  if (stateEl) {
@@ -370,13 +448,19 @@ export function initRouter(
370
448
  params: state.params,
371
449
  pattern: state.pattern,
372
450
  };
373
- (globalThis as any).__grimoire_current_pattern__ = state.pattern;
374
- (globalThis as any).__grimoire_routes__ = routeMap;
375
- (globalThis as any).__grimoire_rerender__ = hmrRerender;
376
- (globalThis as any).__grimoire_navigate__ = (
377
- path: string,
378
- replace?: boolean,
379
- ) => navigate(path, replace ?? false);
451
+ if (Array.isArray(state.deps)) {
452
+ setDeps(state.pattern, state.deps);
453
+ }
454
+ (globalThis as unknown as { __grimoire_current_pattern__: string }).__grimoire_current_pattern__ =
455
+ state.pattern;
456
+ (globalThis as unknown as { __grimoire_routes__: Record<string, RouteEntry> }).__grimoire_routes__ =
457
+ routeMap;
458
+ (globalThis as unknown as { __grimoire_rerender__: () => Promise<void> }).__grimoire_rerender__ =
459
+ hmrRerender;
460
+ (globalThis as unknown as {
461
+ __grimoire_navigate__: (path: string, replace?: boolean) => void;
462
+ }).__grimoire_navigate__ = (path: string, replace?: boolean) =>
463
+ navigate(path, replace ?? false);
380
464
  }
381
465
 
382
466
  saveScrollPosition();