@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/dist/client.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Cookie, StatusMap } from "elysia";
2
2
  import type { AnySchema, HTTPHeaders, UnwrapSchema } from "elysia/types";
3
+ import type { RequestLogger } from "evlog";
3
4
  declare const UNSET: unique symbol;
4
5
  type Unset = typeof UNSET;
5
6
  type ToRecord<T> = {
@@ -19,6 +20,8 @@ type PromisifyData<T extends Record<string, unknown>> = {
19
20
  export interface RouteContext<TParams = {}, TQuery = {}> {
20
21
  cookie: Record<string, Cookie<unknown>>;
21
22
  headers: Record<string, string | undefined>;
23
+ /** Request-scoped logger. Call `log.set({})` to attach fields to the wide event for this render. */
24
+ log: RequestLogger;
22
25
  params: NormalizeUnset<TParams>;
23
26
  path: string;
24
27
  query: NormalizeUnset<TQuery>;
@@ -0,0 +1,26 @@
1
+ import type { RequestLogger } from "evlog";
2
+ /**
3
+ * Returns the current request-scoped logger.
4
+ *
5
+ * Priority:
6
+ * 1. Live Elysia request handled by the evlog() plugin → full request-scoped wide event
7
+ * 2. Synthetic render scope (ISR revalidation, SSG pre-render) → detached createLogger()
8
+ * that still drains to the configured adapter (Datadog, Axiom, etc.)
9
+ * 3. Completely outside any context → no-op
10
+ *
11
+ * Import from `@teyik0/furin` instead of `evlog/elysia` so this fallback chain
12
+ * applies in all rendering contexts.
13
+ */
14
+ export declare function useLogger(): RequestLogger;
15
+ /**
16
+ * Runs `fn` inside a synthetic render scope.
17
+ *
18
+ * Creates a detached `createLogger()` instance for the duration of `fn`.
19
+ * `useLogger()` calls inside `fn` (including user loaders) return this logger
20
+ * instead of throwing. On completion, the accumulated wide event is emitted to
21
+ * the global drain with the provided initial context (e.g. route pattern).
22
+ *
23
+ * Used by renderForPath() which drives both ISR background revalidation and
24
+ * SSG pre-renders — neither has a live Elysia request context.
25
+ */
26
+ export declare function runInSyntheticRenderScope<T>(fn: () => Promise<T> | T, initialContext: Record<string, unknown>): Promise<T>;
package/dist/furin.js CHANGED
@@ -1409,6 +1409,43 @@ function buildElement(route, data, rootLayout) {
1409
1409
  }
1410
1410
  var init_element = () => {};
1411
1411
 
1412
+ // src/context-logger.ts
1413
+ import { AsyncLocalStorage as AsyncLocalStorage3 } from "async_hooks";
1414
+ function useLogger3() {
1415
+ try {
1416
+ return useLogger2();
1417
+ } catch {
1418
+ return syntheticRenderStorage.getStore() ?? noopLogger2;
1419
+ }
1420
+ }
1421
+ async function runInSyntheticRenderScope(fn, initialContext) {
1422
+ const logger = createLogger(initialContext);
1423
+ try {
1424
+ const result = await syntheticRenderStorage.run(logger, () => Promise.resolve(fn()));
1425
+ logger.emit();
1426
+ return result;
1427
+ } catch (err) {
1428
+ logger.error(err instanceof Error ? err : new Error(String(err)));
1429
+ logger.emit();
1430
+ throw err;
1431
+ }
1432
+ }
1433
+ var noopLogger2, syntheticRenderStorage;
1434
+ var init_context_logger = __esm(() => {
1435
+ init_dist();
1436
+ init_elysia();
1437
+ noopLogger2 = {
1438
+ set: () => {},
1439
+ error: () => {},
1440
+ info: () => {},
1441
+ warn: () => {},
1442
+ emit: () => null,
1443
+ getContext: () => ({}),
1444
+ fork: (_label, fn) => fn()
1445
+ };
1446
+ syntheticRenderStorage = new AsyncLocalStorage3;
1447
+ });
1448
+
1412
1449
  // src/render/loaders.ts
1413
1450
  function createLoaderCtx(ctx, accumulatedParentPromise) {
1414
1451
  const cache = new Map;
@@ -1434,7 +1471,7 @@ function createLoaderCtx(ctx, accumulatedParentPromise) {
1434
1471
  }
1435
1472
  async function runLoaders(route, ctx, _rootLayout) {
1436
1473
  try {
1437
- const ctxRecord = ctx;
1474
+ const ctxRecord = { ...ctx, log: useLogger3() };
1438
1475
  const loaderMap = new Map;
1439
1476
  let accumulatedParentPromise = Promise.resolve({});
1440
1477
  for (const r of route.routeChain) {
@@ -1464,6 +1501,9 @@ async function runLoaders(route, ctx, _rootLayout) {
1464
1501
  throw err;
1465
1502
  }
1466
1503
  }
1504
+ var init_loaders = __esm(() => {
1505
+ init_context_logger();
1506
+ });
1467
1507
 
1468
1508
  // src/render/template.ts
1469
1509
  import { readFileSync } from "fs";
@@ -1557,7 +1597,7 @@ async function renderForPath(route, params, root, origin, basePath) {
1557
1597
  set: { headers: {} },
1558
1598
  path: resolvedPath
1559
1599
  };
1560
- const prepared = await prepareRender(route, ctx, root, basePath);
1600
+ const prepared = await runInSyntheticRenderScope(() => prepareRender(route, ctx, root, basePath), { route: route.pattern });
1561
1601
  if (prepared instanceof Response) {
1562
1602
  throw prepared;
1563
1603
  }
@@ -1745,11 +1785,14 @@ var init_render = __esm(() => {
1745
1785
  init_assemble();
1746
1786
  init_cache();
1747
1787
  init_element();
1788
+ init_loaders();
1748
1789
  init_shell();
1749
1790
  init_template();
1750
1791
  init_assemble();
1751
1792
  init_element();
1793
+ init_loaders();
1752
1794
  init_elysia();
1795
+ init_context_logger();
1753
1796
  init_shell();
1754
1797
  pendingRevalidations = new Set;
1755
1798
  });
@@ -1802,6 +1845,7 @@ __export(exports_router, {
1802
1845
  scanPages: () => scanPages,
1803
1846
  resolveMode: () => resolveMode,
1804
1847
  queryDefaultRedirectHook: () => queryDefaultRedirectHook,
1848
+ mergeRouteSchemas: () => mergeRouteSchemas,
1805
1849
  loadProdRoutes: () => loadProdRoutes,
1806
1850
  filePathToPattern: () => filePathToPattern,
1807
1851
  createRoutePlugin: () => createRoutePlugin
@@ -1809,7 +1853,7 @@ __export(exports_router, {
1809
1853
  import { existsSync } from "fs";
1810
1854
  import { readdir } from "fs/promises";
1811
1855
  import { join, parse } from "path";
1812
- import { Elysia as Elysia2 } from "elysia";
1856
+ import { Elysia as Elysia2, t } from "elysia";
1813
1857
  function loadProdRoutes(ctx) {
1814
1858
  const rootMod = ctx.modules[ctx.rootPath];
1815
1859
  const rootExport = rootMod.route ?? rootMod.default;
@@ -1973,10 +2017,22 @@ async function handleSSGRequest(route, ctx, root, buildId) {
1973
2017
  ctx.set.headers["cache-tag"] = resolvedPath;
1974
2018
  return entry.html;
1975
2019
  }
2020
+ function mergeRouteSchemas(routeChain, key) {
2021
+ const schemas = routeChain.map((r) => r[key]).filter(Boolean);
2022
+ if (schemas.length === 0) {
2023
+ return;
2024
+ }
2025
+ if (schemas.length === 1) {
2026
+ return schemas[0];
2027
+ }
2028
+ const mergedProperties = Object.assign({}, ...schemas.map((s) => s.properties ?? {}));
2029
+ const mergedOptions = Object.assign({}, ...schemas.map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => !TOBJECT_STRUCTURAL_KEYS.has(k)))));
2030
+ return t.Object(mergedProperties, mergedOptions);
2031
+ }
1976
2032
  function createRoutePlugin(route, root, buildId = "") {
1977
2033
  const { pattern, routeChain } = route;
1978
- const allParams = routeChain.findLast((r) => r.params)?.params;
1979
- const allQuery = routeChain.findLast((r) => r.query)?.query;
2034
+ const allParams = mergeRouteSchemas(routeChain, "params");
2035
+ const allQuery = mergeRouteSchemas(routeChain, "query");
1980
2036
  const hasQuerySchema = !!allQuery;
1981
2037
  const plugin = new Elysia2;
1982
2038
  if (allParams || allQuery) {
@@ -2055,9 +2111,11 @@ function filePathToPattern(path) {
2055
2111
  }
2056
2112
  return `/${segments.join("/")}`;
2057
2113
  }
2114
+ var TOBJECT_STRUCTURAL_KEYS;
2058
2115
  var init_router = __esm(() => {
2059
2116
  init_assemble();
2060
2117
  init_render();
2118
+ TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
2061
2119
  });
2062
2120
 
2063
2121
  // src/dev-page-plugin.ts
@@ -2273,8 +2331,8 @@ var init_dev_page_plugin = __esm(() => {
2273
2331
  import { existsSync as existsSync2, readFileSync as readFileSync2, writeFileSync } from "fs";
2274
2332
  import { join as join2 } from "path";
2275
2333
  function patternToTypeString(pattern) {
2276
- const t = pattern.replace(/:[^/]+/g, "${string}").replace(/\*/g, "${string}");
2277
- return t.includes("${") ? `\`${t}\`` : `"${t}"`;
2334
+ const t2 = pattern.replace(/:[^/]+/g, "${string}").replace(/\*/g, "${string}");
2335
+ return t2.includes("${") ? `\`${t2}\`` : `"${t2}"`;
2278
2336
  }
2279
2337
  function schemaToTypeString(schema) {
2280
2338
  if (!schema || typeof schema !== "object") {
@@ -2282,7 +2340,7 @@ function schemaToTypeString(schema) {
2282
2340
  }
2283
2341
  const s = schema;
2284
2342
  if (s.anyOf && Array.isArray(s.anyOf)) {
2285
- const parts = s.anyOf.map(schemaToTypeString).filter((t) => t !== "null");
2343
+ const parts = s.anyOf.map(schemaToTypeString).filter((t2) => t2 !== "null");
2286
2344
  return parts.join(" | ") || "unknown";
2287
2345
  }
2288
2346
  switch (s.type) {
package/dist/link.js CHANGED
@@ -746,7 +746,43 @@ function handleScrollRestoration(href, navigationToken, navVersion) {
746
746
  });
747
747
  });
748
748
  } else {
749
- window.scrollTo(0, 0);
749
+ window.scrollTo({ top: 0, behavior: "instant" });
750
+ }
751
+ }
752
+ var SCROLL_STORAGE_KEY = "__furin_scroll__";
753
+ function getHistoryKey(state) {
754
+ return state?._furinKey;
755
+ }
756
+ function generateHistoryKey() {
757
+ return Math.random().toString(36).slice(2, 9);
758
+ }
759
+ function saveScrollPosition(key) {
760
+ try {
761
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
762
+ const positions = raw ? JSON.parse(raw) : {};
763
+ positions[key] = window.scrollY;
764
+ const keys = Object.keys(positions);
765
+ if (keys.length > 50) {
766
+ delete positions[keys[0]];
767
+ }
768
+ sessionStorage.setItem(SCROLL_STORAGE_KEY, JSON.stringify(positions));
769
+ } catch {}
770
+ }
771
+ function restoreScrollPosition(key, token, version) {
772
+ try {
773
+ const raw = sessionStorage.getItem(SCROLL_STORAGE_KEY);
774
+ const positions = raw ? JSON.parse(raw) : {};
775
+ const y = positions[key] ?? 0;
776
+ window.requestAnimationFrame(() => {
777
+ window.requestAnimationFrame(() => {
778
+ if (version.current !== token) {
779
+ return;
780
+ }
781
+ window.scrollTo({ top: y, behavior: "instant" });
782
+ });
783
+ });
784
+ } catch {
785
+ window.scrollTo({ top: 0, behavior: "instant" });
750
786
  }
751
787
  }
752
788
  function toLogical(physicalPathname, basePath) {
@@ -882,9 +918,16 @@ function RouterProvider({
882
918
  const effectiveLogical = newState.finalHref ?? logicalHref;
883
919
  const physicalEffective = basePath + effectiveLogical;
884
920
  if (opts?.replace) {
885
- window.history.replaceState(null, "", physicalEffective);
921
+ window.history.replaceState({
922
+ ...history.state ?? {},
923
+ _furinKey: getHistoryKey(history.state) ?? generateHistoryKey()
924
+ }, "", physicalEffective);
886
925
  } else {
887
- window.history.pushState(null, "", physicalEffective);
926
+ const currentKey = getHistoryKey(history.state);
927
+ if (currentKey) {
928
+ saveScrollPosition(currentKey);
929
+ }
930
+ window.history.pushState({ _furinKey: generateHistoryKey() }, "", physicalEffective);
888
931
  }
889
932
  const effectiveUrl = new URL(physicalEffective, window.location.origin);
890
933
  const logicalPath = toLogical(effectiveUrl.pathname, basePath);
@@ -905,6 +948,7 @@ function RouterProvider({
905
948
  await navigate(logicalHref, { replace: true, resetScroll: opts?.resetScroll ?? false });
906
949
  }, [navigate, invalidatePrefetch, basePath]);
907
950
  const handlePopState = useCallback(async () => {
951
+ const destKey = getHistoryKey(history.state);
908
952
  const logicalPath = toLogical(window.location.pathname, basePath);
909
953
  const logicalHref = logicalPath + window.location.search;
910
954
  const myVersion = ++navVersion.current;
@@ -935,15 +979,30 @@ function RouterProvider({
935
979
  }
936
980
  const effectiveLogical = newState.finalHref ?? logicalHref;
937
981
  if (newState.finalHref) {
938
- window.history.replaceState(null, "", basePath + effectiveLogical);
982
+ window.history.replaceState(history.state, "", basePath + effectiveLogical);
939
983
  }
940
984
  setCurrentHref(effectiveLogical);
985
+ if (destKey) {
986
+ restoreScrollPosition(destKey, myVersion, navVersion);
987
+ } else {
988
+ window.scrollTo({ top: 0, behavior: "instant" });
989
+ }
941
990
  } finally {
942
991
  if (navVersion.current === myVersion) {
943
992
  setIsNavigating(false);
944
993
  }
945
994
  }
946
995
  }, [fetchPageState, basePath]);
996
+ useEffect(() => {
997
+ const prevScrollRestoration = history.scrollRestoration;
998
+ history.scrollRestoration = "manual";
999
+ if (!getHistoryKey(history.state)) {
1000
+ history.replaceState({ ...history.state ?? {}, _furinKey: generateHistoryKey() }, "");
1001
+ }
1002
+ return () => {
1003
+ history.scrollRestoration = prevScrollRestoration;
1004
+ };
1005
+ }, []);
947
1006
  useEffect(() => {
948
1007
  window.addEventListener("popstate", handlePopState);
949
1008
  return () => window.removeEventListener("popstate", handlePopState);
@@ -1,6 +1,8 @@
1
- import type { RouteContext } from "../client";
2
1
  import type { buildHeadInjection } from "./shell";
3
- export type LoaderContext = RouteContext<Record<string, string>, Record<string, string>>;
2
+ /** Minimal context passed to background / synthetic render helpers — only `request` is needed. */
3
+ export interface LoaderContext {
4
+ request: Request;
5
+ }
4
6
  export declare function resolvePath(pattern: string, params: Record<string, string>): string;
5
7
  export declare function streamToString(stream: ReadableStream): Promise<string>;
6
8
  interface SplitTemplate {
@@ -22,5 +22,8 @@ export declare function generateIndexHtml(): string;
22
22
  *
23
23
  * @param buildId - Short hash identifying this specific build. Injected as a
24
24
  * `<meta name="furin-build-id">` tag so the client can detect stale deploys.
25
+ * @param faviconHref - Absolute href for the favicon (e.g. "/furin/favicon.ico").
26
+ * When provided, a `<link rel="icon">` tag is injected so browsers can locate
27
+ * the favicon even when the site is served from a sub-path.
25
28
  */
26
- export declare function generateProdIndexHtml(entryChunk: string, cssChunks: string[], buildId?: string): string;
29
+ export declare function generateProdIndexHtml(entryChunk: string, cssChunks: string[], buildId?: string, faviconHref?: string): string;
package/dist/router.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type AnyElysia, type Context } from "elysia";
2
+ import type { AnySchema } from "elysia/types";
2
3
  import type { RuntimePage, RuntimeRoute } from "./client.ts";
3
4
  import { type CompileContext } from "./internal.ts";
4
5
  export interface ResolvedRoute {
@@ -29,6 +30,16 @@ export declare function scanPages(pagesDir: string): Promise<{
29
30
  export declare function scanRootLayout(pagesDir: string): Promise<RootLayout>;
30
31
  /** @internal Exported for unit testing. */
31
32
  export declare function queryDefaultRedirectHook({ request, query, status, set }: Context): import("elysia").ElysiaCustomStatusResponse<"Found", "Found", 302> | undefined;
33
+ /**
34
+ * Merges TObject schemas from all routeChain entries for a given key.
35
+ * Properties are spread left-to-right (leaf wins on key conflict).
36
+ * Object-level options (additionalProperties, $id, description, …) are also
37
+ * merged with the same leaf-wins semantics so they are not silently dropped.
38
+ * Returns undefined when no entry in the chain defines the key.
39
+ *
40
+ * @internal Exported for unit testing.
41
+ */
42
+ export declare function mergeRouteSchemas(routeChain: RuntimeRoute[], key: "params" | "query"): AnySchema | undefined;
32
43
  export declare function createRoutePlugin(route: ResolvedRoute, root: RootLayout, buildId?: string): AnyElysia;
33
44
  export declare function resolveMode(page: RuntimePage, routeChain: RuntimeRoute[]): "ssr" | "ssg" | "isr";
34
45
  export declare function filePathToPattern(path: string): string;