@teyik0/furin 0.1.0-alpha.8 → 0.1.0-alpha.9

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teyik0/furin",
3
- "version": "0.1.0-alpha.8",
3
+ "version": "0.1.0-alpha.9",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist",
@@ -271,7 +271,11 @@ export async function buildStaticTarget(
271
271
  });
272
272
 
273
273
  // ── 4. Generate HTML shell template ──────────────────────────────────────
274
- const shellHtml = generateProdIndexHtml(entryChunk, cssChunks);
274
+ // Emit a <link rel="icon"> only when a favicon.ico exists in the public dir.
275
+ // This ensures the browser finds it even when the site is served from a sub-path.
276
+ const publicFavicon = join(rootDir, "public", "favicon.ico");
277
+ const faviconHref = existsSync(publicFavicon) ? `${basePath}/favicon.ico` : undefined;
278
+ const shellHtml = generateProdIndexHtml(entryChunk, cssChunks, undefined, faviconHref);
275
279
 
276
280
  // ── 5. Prime the renderer with the production shell ──────────────────────
277
281
  // Must be called before any prerenderSSG invocation.
package/src/client.ts CHANGED
@@ -9,6 +9,7 @@
9
9
 
10
10
  import type { Cookie, StatusMap } from "elysia";
11
11
  import type { AnySchema, HTTPHeaders, UnwrapSchema } from "elysia/types";
12
+ import type { RequestLogger } from "evlog";
12
13
 
13
14
  declare const UNSET: unique symbol;
14
15
  type Unset = typeof UNSET;
@@ -43,6 +44,8 @@ type PromisifyData<T extends Record<string, unknown>> = {
43
44
  export interface RouteContext<TParams = {}, TQuery = {}> {
44
45
  cookie: Record<string, Cookie<unknown>>;
45
46
  headers: Record<string, string | undefined>;
47
+ /** Request-scoped logger. Call `log.set({})` to attach fields to the wide event for this render. */
48
+ log: RequestLogger;
46
49
  params: NormalizeUnset<TParams>;
47
50
  path: string;
48
51
  query: NormalizeUnset<TQuery>;
@@ -0,0 +1,71 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import type { RequestLogger } from "evlog";
3
+ import { createLogger } from "evlog";
4
+ import { useLogger as _evlogUseLogger } from "evlog/elysia";
5
+
6
+ /**
7
+ * Fallback used when useLogger() is called completely outside any context
8
+ * (not in a live request, not in a synthetic render scope).
9
+ */
10
+ const noopLogger: RequestLogger = {
11
+ // biome-ignore lint/suspicious/noEmptyBlockStatements: intentional no-op
12
+ set: () => {},
13
+ // biome-ignore lint/suspicious/noEmptyBlockStatements: intentional no-op
14
+ error: () => {},
15
+ // biome-ignore lint/suspicious/noEmptyBlockStatements: intentional no-op
16
+ info: () => {},
17
+ // biome-ignore lint/suspicious/noEmptyBlockStatements: intentional no-op
18
+ warn: () => {},
19
+ emit: () => null,
20
+ getContext: () => ({}),
21
+ fork: (_label, fn) => fn() as undefined,
22
+ };
23
+
24
+ const syntheticRenderStorage = new AsyncLocalStorage<RequestLogger>();
25
+
26
+ /**
27
+ * Returns the current request-scoped logger.
28
+ *
29
+ * Priority:
30
+ * 1. Live Elysia request handled by the evlog() plugin → full request-scoped wide event
31
+ * 2. Synthetic render scope (ISR revalidation, SSG pre-render) → detached createLogger()
32
+ * that still drains to the configured adapter (Datadog, Axiom, etc.)
33
+ * 3. Completely outside any context → no-op
34
+ *
35
+ * Import from `@teyik0/furin` instead of `evlog/elysia` so this fallback chain
36
+ * applies in all rendering contexts.
37
+ */
38
+ export function useLogger(): RequestLogger {
39
+ try {
40
+ return _evlogUseLogger();
41
+ } catch {
42
+ return syntheticRenderStorage.getStore() ?? noopLogger;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Runs `fn` inside a synthetic render scope.
48
+ *
49
+ * Creates a detached `createLogger()` instance for the duration of `fn`.
50
+ * `useLogger()` calls inside `fn` (including user loaders) return this logger
51
+ * instead of throwing. On completion, the accumulated wide event is emitted to
52
+ * the global drain with the provided initial context (e.g. route pattern).
53
+ *
54
+ * Used by renderForPath() which drives both ISR background revalidation and
55
+ * SSG pre-renders — neither has a live Elysia request context.
56
+ */
57
+ export async function runInSyntheticRenderScope<T>(
58
+ fn: () => Promise<T> | T,
59
+ initialContext: Record<string, unknown>
60
+ ): Promise<T> {
61
+ const logger = createLogger(initialContext);
62
+ try {
63
+ const result = await syntheticRenderStorage.run(logger, () => Promise.resolve(fn()));
64
+ logger.emit();
65
+ return result;
66
+ } catch (err) {
67
+ logger.error(err instanceof Error ? err : new Error(String(err)));
68
+ logger.emit();
69
+ throw err;
70
+ }
71
+ }
package/src/link.tsx CHANGED
@@ -414,10 +414,57 @@ function handleScrollRestoration(
414
414
  });
415
415
  });
416
416
  } else {
417
- window.scrollTo(0, 0);
417
+ window.scrollTo({ top: 0, behavior: "instant" });
418
418
  }
419
419
  }
420
420
 
421
+ // ── Scroll restoration helpers ─────────────────────────────────────────────────
422
+
423
+ const SCROLL_STORAGE_KEY = "__furin_scroll__";
424
+
425
+ function getHistoryKey(state: unknown): string | undefined {
426
+ return (state as { _furinKey?: string } | null)?._furinKey;
427
+ }
428
+
429
+ function generateHistoryKey(): string {
430
+ return Math.random().toString(36).slice(2, 9);
431
+ }
432
+
433
+ function saveScrollPosition(key: string): void {
434
+ try {
435
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
436
+ const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
437
+ positions[key] = window.scrollY;
438
+ const keys = Object.keys(positions);
439
+ if (keys.length > 50) {
440
+ delete positions[keys[0] as string];
441
+ }
442
+ sessionStorage.setItem(SCROLL_STORAGE_KEY, JSON.stringify(positions));
443
+ } catch {
444
+ // sessionStorage unavailable (private mode, quota exceeded, etc.)
445
+ }
446
+ }
447
+
448
+ function restoreScrollPosition(key: string, token: number, version: { current: number }): void {
449
+ try {
450
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
451
+ const positions: Record<string, number> = raw ? JSON.parse(raw) : {};
452
+ const y = positions[key] ?? 0;
453
+ window.requestAnimationFrame(() => {
454
+ window.requestAnimationFrame(() => {
455
+ if (version.current !== token) {
456
+ return;
457
+ }
458
+ window.scrollTo({ top: y, behavior: "instant" });
459
+ });
460
+ });
461
+ } catch {
462
+ window.scrollTo({ top: 0, behavior: "instant" });
463
+ }
464
+ }
465
+
466
+ // ── Path helpers ───────────────────────────────────────────────────────────────
467
+
421
468
  /** Strips basePath prefix from a physical pathname, returning the logical path. */
422
469
  function toLogical(physicalPathname: string, basePath: string): string {
423
470
  if (
@@ -610,9 +657,22 @@ export function RouterProvider({
610
657
  // Push the PHYSICAL path to browser history.
611
658
  const physicalEffective = basePath + effectiveLogical;
612
659
  if (opts?.replace) {
613
- window.history.replaceState(null, "", physicalEffective);
660
+ // Preserve the existing key — same history entry, URL just updated.
661
+ window.history.replaceState(
662
+ {
663
+ ...((history.state as object) ?? {}),
664
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey(),
665
+ },
666
+ "",
667
+ physicalEffective
668
+ );
614
669
  } else {
615
- window.history.pushState(null, "", physicalEffective);
670
+ // Save current position before leaving, then push a fresh entry.
671
+ const currentKey = getHistoryKey(history.state);
672
+ if (currentKey) {
673
+ saveScrollPosition(currentKey);
674
+ }
675
+ window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
616
676
  }
617
677
  // Store the LOGICAL path in currentHref so Link active-state works.
618
678
  const effectiveUrl = new URL(physicalEffective, window.location.origin);
@@ -644,6 +704,9 @@ export function RouterProvider({
644
704
  );
645
705
 
646
706
  const handlePopState = useCallback(async () => {
707
+ // Capture the destination key immediately — history.state is already the
708
+ // destination entry when popstate fires, before any awaits.
709
+ const destKey = getHistoryKey(history.state);
647
710
  // Convert physical browser URL to logical href for cache lookup + fetchPageState.
648
711
  const logicalPath = toLogical(window.location.pathname, basePath);
649
712
  const logicalHref = logicalPath + window.location.search;
@@ -678,11 +741,18 @@ export function RouterProvider({
678
741
  // effectiveHref is logical (includes search); push physical to history if server redirected.
679
742
  const effectiveLogical = newState.finalHref ?? logicalHref;
680
743
  if (newState.finalHref) {
681
- window.history.replaceState(null, "", basePath + effectiveLogical);
744
+ // Preserve _furinKey so restoreScrollPosition still works after a redirect.
745
+ window.history.replaceState(history.state, "", basePath + effectiveLogical);
682
746
  }
683
747
  // effectiveLogical already contains the search params — no URL round-trip needed.
684
748
  setCurrentHref(effectiveLogical);
685
- // No scrollTo(0, 0) — browser handles scroll restoration
749
+ // Restore the saved scroll position for this history entry (double rAF waits
750
+ // for React to finish painting the new page before scrolling).
751
+ if (destKey) {
752
+ restoreScrollPosition(destKey, myVersion, navVersion);
753
+ } else {
754
+ window.scrollTo({ top: 0, behavior: "instant" });
755
+ }
686
756
  } finally {
687
757
  if (navVersion.current === myVersion) {
688
758
  setIsNavigating(false);
@@ -690,6 +760,21 @@ export function RouterProvider({
690
760
  }
691
761
  }, [fetchPageState, basePath]);
692
762
 
763
+ // Disable native scroll restoration and assign a key to the initial history entry
764
+ useEffect(() => {
765
+ const prevScrollRestoration = history.scrollRestoration;
766
+ history.scrollRestoration = "manual";
767
+ if (!getHistoryKey(history.state)) {
768
+ history.replaceState(
769
+ { ...((history.state as object) ?? {}), _furinKey: generateHistoryKey() },
770
+ ""
771
+ );
772
+ }
773
+ return () => {
774
+ history.scrollRestoration = prevScrollRestoration;
775
+ };
776
+ }, []);
777
+
693
778
  // Handle browser back/forward
694
779
  useEffect(() => {
695
780
  window.addEventListener("popstate", handlePopState);
@@ -1,8 +1,10 @@
1
- import type { RouteContext } from "../client";
2
1
  import type { buildHeadInjection } from "./shell";
3
2
  import { safeJson } from "./shell";
4
3
 
5
- export type LoaderContext = RouteContext<Record<string, string>, Record<string, string>>;
4
+ /** Minimal context passed to background / synthetic render helpers — only `request` is needed. */
5
+ export interface LoaderContext {
6
+ request: Request;
7
+ }
6
8
 
7
9
  export function resolvePath(pattern: string, params: Record<string, string>): string {
8
10
  let path = pattern;
@@ -26,6 +26,7 @@ export { type LoaderResult, runLoaders } from "./loaders.ts";
26
26
 
27
27
  import type { Context } from "elysia";
28
28
  import { useLogger } from "evlog/elysia";
29
+ import { runInSyntheticRenderScope } from "../context-logger.ts";
29
30
  import type { ResolvedRoute } from "../router.ts";
30
31
  import { IS_DEV } from "../runtime-env.ts";
31
32
  import type { LoaderContext } from "./assemble.ts";
@@ -136,7 +137,10 @@ async function renderForPath(
136
137
  path: resolvedPath,
137
138
  } as Context;
138
139
 
139
- const prepared = await prepareRender(route, ctx, root, basePath);
140
+ const prepared = await runInSyntheticRenderScope(
141
+ () => prepareRender(route, ctx, root, basePath),
142
+ { route: route.pattern }
143
+ );
140
144
  if (prepared instanceof Response) {
141
145
  throw prepared;
142
146
  }
@@ -1,5 +1,6 @@
1
1
  import type { Context } from "elysia";
2
2
  import type { RuntimeRoute } from "../client";
3
+ import { useLogger } from "../context-logger.ts";
3
4
  import type { ResolvedRoute } from "../router";
4
5
 
5
6
  export type LoaderResult =
@@ -56,8 +57,11 @@ export async function runLoaders(
56
57
  _rootLayout: RuntimeRoute
57
58
  ): Promise<LoaderResult> {
58
59
  try {
59
- // Hoist the cast once so it doesn't repeat at every createLoaderCtx call site.
60
- const ctxRecord = ctx as Record<string, unknown>;
60
+ // Inject `log` so loaders can destructure it directly as `({ log })`.
61
+ // useLogger() resolves the correct logger for every rendering context:
62
+ // live request → evlog request-scoped logger, synthetic render → detached
63
+ // createLogger() from runInSyntheticRenderScope, outside any context → no-op.
64
+ const ctxRecord = { ...(ctx as Record<string, unknown>), log: useLogger() };
61
65
  const loaderMap = new Map<RuntimeRoute, Promise<Record<string, unknown>>>();
62
66
 
63
67
  // All loaders in the chain start immediately. Each receives a Proxy where
@@ -149,11 +149,15 @@ export function generateIndexHtml(): string {
149
149
  *
150
150
  * @param buildId - Short hash identifying this specific build. Injected as a
151
151
  * `<meta name="furin-build-id">` tag so the client can detect stale deploys.
152
+ * @param faviconHref - Absolute href for the favicon (e.g. "/furin/favicon.ico").
153
+ * When provided, a `<link rel="icon">` tag is injected so browsers can locate
154
+ * the favicon even when the site is served from a sub-path.
152
155
  */
153
156
  export function generateProdIndexHtml(
154
157
  entryChunk: string,
155
158
  cssChunks: string[],
156
- buildId?: string
159
+ buildId?: string,
160
+ faviconHref?: string
157
161
  ): string {
158
162
  const cssLinks = cssChunks
159
163
  .map((c) => ` <link rel="stylesheet" crossorigin href="${c}">`)
@@ -162,6 +166,9 @@ export function generateProdIndexHtml(
162
166
  const buildIdMeta = buildId
163
167
  ? ` <meta name="furin-build-id" content="${escapeHtml(buildId)}">\n`
164
168
  : "";
169
+ const faviconLink = faviconHref
170
+ ? ` <link rel="icon" href="${escapeHtml(faviconHref)}">\n`
171
+ : "";
165
172
 
166
173
  return `<!DOCTYPE html>
167
174
  <html lang="en">
@@ -169,7 +176,7 @@ export function generateProdIndexHtml(
169
176
  <meta charset="UTF-8">
170
177
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
171
178
  ${THEME_INIT_SCRIPT}
172
- ${buildIdMeta}${cssLinks ? `${cssLinks}\n` : ""} <!--ssr-head-->
179
+ ${buildIdMeta}${faviconLink}${cssLinks ? `${cssLinks}\n` : ""} <!--ssr-head-->
173
180
  </head>
174
181
  <body>
175
182
  <div id="root"><!--ssr-outlet--></div>
package/src/router.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { readdir } from "node:fs/promises";
3
3
  import { join, parse } from "node:path";
4
- import { type AnyElysia, type Context, Elysia } from "elysia";
4
+ import { type AnyElysia, type Context, Elysia, t } from "elysia";
5
5
  import type { AnySchema } from "elysia/types";
6
6
  import type { RuntimePage, RuntimeRoute } from "./client.ts";
7
7
  import { type CompileContext, getCompileContext } from "./internal.ts";
@@ -283,13 +283,52 @@ async function handleSSGRequest(
283
283
  return entry.html;
284
284
  }
285
285
 
286
+ // Standard structural keys on a TObject — everything else is a user-supplied option
287
+ // (e.g. additionalProperties, $id, description, title) and must be preserved.
288
+ const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
289
+
290
+ /**
291
+ * Merges TObject schemas from all routeChain entries for a given key.
292
+ * Properties are spread left-to-right (leaf wins on key conflict).
293
+ * Object-level options (additionalProperties, $id, description, …) are also
294
+ * merged with the same leaf-wins semantics so they are not silently dropped.
295
+ * Returns undefined when no entry in the chain defines the key.
296
+ *
297
+ * @internal Exported for unit testing.
298
+ */
299
+ export function mergeRouteSchemas(
300
+ routeChain: RuntimeRoute[],
301
+ key: "params" | "query"
302
+ ): AnySchema | undefined {
303
+ const schemas = routeChain.map((r) => r[key]).filter(Boolean) as Record<string, unknown>[];
304
+
305
+ if (schemas.length === 0) {
306
+ return;
307
+ }
308
+ if (schemas.length === 1) {
309
+ return schemas[0] as AnySchema;
310
+ }
311
+
312
+ const mergedProperties = Object.assign(
313
+ {},
314
+ ...schemas.map((s) => (s.properties as Record<string, unknown>) ?? {})
315
+ );
316
+
317
+ const mergedOptions = Object.assign(
318
+ {},
319
+ ...schemas.map((s) =>
320
+ Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))
321
+ )
322
+ );
323
+
324
+ return t.Object(mergedProperties, mergedOptions) as AnySchema;
325
+ }
326
+
286
327
  export function createRoutePlugin(route: ResolvedRoute, root: RootLayout, buildId = ""): AnyElysia {
287
328
  const { pattern, routeChain } = route;
288
329
 
289
- // TODO: merge schemas from all routeChain entries (requires TypeBox t.Object/t.Composite)
290
- // For now, prefer the leaf route's schema (last in chain) over ancestor routes.
291
- const allParams = routeChain.findLast((r) => r.params)?.params;
292
- const allQuery = routeChain.findLast((r) => r.query)?.query;
330
+ const allParams = mergeRouteSchemas(routeChain, "params");
331
+ const allQuery = mergeRouteSchemas(routeChain, "query");
293
332
  const hasQuerySchema = !!allQuery;
294
333
 
295
334
  // Guard and handler MUST live in the same Elysia scope so that validation