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

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.
@@ -1,62 +1,103 @@
1
1
  import type { Context } from "elysia";
2
- import type { LoaderDeps, RuntimeRoute } from "../client";
2
+ import type { RuntimeRoute } from "../client";
3
3
  import type { ResolvedRoute } from "../router";
4
4
 
5
5
  export type LoaderResult =
6
6
  | { type: "data"; data: Record<string, unknown>; headers: Record<string, string> }
7
7
  | { type: "redirect"; response: Response };
8
8
 
9
+ /**
10
+ * Wraps the Elysia context so that any property NOT present on `ctx` is
11
+ * returned as an individual `Promise<value>` resolved from the accumulated
12
+ * parent data. Properties that ARE present on `ctx` (request, params, set, …)
13
+ * are returned as-is.
14
+ *
15
+ * A per-prop cache ensures the same Promise instance is returned on repeated
16
+ * access of the same field (stable reference for Promise.all etc.).
17
+ */
18
+ function createLoaderCtx(
19
+ ctx: Record<string, unknown>,
20
+ accumulatedParentPromise: Promise<Record<string, unknown>>
21
+ ): Record<string, unknown> {
22
+ const cache = new Map<string, Promise<unknown>>();
23
+ return new Proxy(ctx, {
24
+ get(target, prop: string | symbol) {
25
+ if (typeof prop !== "string") {
26
+ return Reflect.get(target, prop);
27
+ }
28
+ // Short-circuit well-known Promise/serialisation introspection keys so
29
+ // the proxy is never treated as a thenable by Promise.resolve() or
30
+ // JSON.stringify(), which would cause silent infinite loops or wrong types.
31
+ if (prop === "then" || prop === "catch" || prop === "finally" || prop === "toJSON") {
32
+ return Reflect.get(target, prop);
33
+ }
34
+ // RouteContext fields (request, params, query, set, headers, cookie,
35
+ // path, redirect) are present on target — return directly.
36
+ // Use hasOwn so prototype keys (toString, constructor, …) are not
37
+ // mistaken for context fields and incorrectly hide parent loader data.
38
+ if (Object.hasOwn(target, prop)) {
39
+ return target[prop];
40
+ }
41
+ // Everything else is a parent-data field → individual lazy Promise.
42
+ let entry = cache.get(prop);
43
+ if (!entry) {
44
+ entry = accumulatedParentPromise.then((data) => data[prop]);
45
+ cache.set(prop, entry);
46
+ }
47
+ return entry;
48
+ },
49
+ });
50
+ }
51
+
52
+ // TODO: remove _rootLayout parameter in next refactor (unused; routeChain[0] is root layout)
9
53
  export async function runLoaders(
10
54
  route: ResolvedRoute,
11
55
  ctx: Context,
12
- rootLayout: RuntimeRoute
56
+ _rootLayout: RuntimeRoute
13
57
  ): Promise<LoaderResult> {
14
58
  try {
15
- // Step 1: root loader runs first — provides global context (user, auth, etc.)
16
- // Root data is merged into ctxWithRoot so all subsequent loaders receive it
17
- // automatically (backward-compatible with the previous waterfall behaviour).
18
- //
19
- // deps is defined here so it can be passed to the root loader too.
20
- // The root has no ancestors, so deps always returns an empty resolved promise.
59
+ // Hoist the cast once so it doesn't repeat at every createLoaderCtx call site.
60
+ const ctxRecord = ctx as Record<string, unknown>;
21
61
  const loaderMap = new Map<RuntimeRoute, Promise<Record<string, unknown>>>();
22
62
 
23
- const deps: LoaderDeps = (routeRef) =>
24
- loaderMap.get(routeRef as RuntimeRoute) ?? Promise.resolve({});
63
+ // All loaders in the chain start immediately. Each receives a Proxy where
64
+ // parent-data fields are individually-awaitable Promises. The loader opts
65
+ // in to waiting by doing `await user` (or `Promise.all([user, org])`);
66
+ // if it never awaits a parent field it runs in full parallel.
67
+ let accumulatedParentPromise: Promise<Record<string, unknown>> = Promise.resolve({});
25
68
 
26
- // Run root loader and store its result in loaderMap so that
27
- // deps(rootRoute) returns the actual root data (not empty {}).
28
- const rootPromise: Promise<Record<string, unknown>> = rootLayout.loader
29
- ? Promise.resolve(rootLayout.loader({ ...ctx }, deps)).then((r) => r ?? {})
30
- : Promise.resolve({});
31
- loaderMap.set(rootLayout, rootPromise);
32
- const rootData = await rootPromise;
33
- const ctxWithRoot = { ...ctx, ...rootData };
69
+ for (const r of route.routeChain) {
70
+ const parentAccum = accumulatedParentPromise; // capture for closure
34
71
 
35
- // Step 2: launch all ancestor + page loaders immediately in parallel.
36
- // Each is stored in loaderMap keyed by object identity so that deps()
37
- // can resolve a Promise for any route in the chain.
38
- //
39
- // Loaders are inserted in chain order (index 1, 2, 3 …) so when loader N
40
- // calls `await deps(routeAtIndexM)` where M < N, the Promise is already
41
- // present in the map — no deadlock is possible for backward dependencies.
72
+ if (r.loader) {
73
+ const loaderCtx = createLoaderCtx(ctxRecord, parentAccum);
74
+ const loaderPromise = Promise.resolve(r.loader(loaderCtx)).then((res) => res ?? {});
75
+ loaderMap.set(r, loaderPromise);
42
76
 
43
- for (let i = 1; i < route.routeChain.length; i++) {
44
- const ancestor = route.routeChain[i];
45
- if (ancestor?.loader) {
46
- loaderMap.set(
47
- ancestor,
48
- Promise.resolve(ancestor.loader(ctxWithRoot, deps)).then((r) => r ?? {})
49
- );
77
+ // Accumulate: previous ancestors + this loader's result.
78
+ // A void .catch() suppresses the "unhandled rejection" warning that
79
+ // fires when a sibling or child loader throws — but unlike `.catch(
80
+ // () => ({}))` it does NOT resolve the promise, so child loaders'
81
+ // field-accesses via createLoaderCtx still receive the rejection
82
+ // instead of silently resolving to undefined. The real rejection is
83
+ // re-thrown by the Promise.all below.
84
+ accumulatedParentPromise = Promise.all([parentAccum, loaderPromise]).then(([acc, own]) => ({
85
+ ...acc,
86
+ ...own,
87
+ }));
88
+ accumulatedParentPromise.catch(() => {
89
+ /* suppress unhandled-rejection warning */
90
+ });
50
91
  }
51
92
  }
52
93
 
53
- // Page loader — all ancestors are already in the map at this point.
94
+ // Page loader receives all route-chain fields as individual Promises.
95
+ const pageCtx = createLoaderCtx(ctxRecord, accumulatedParentPromise);
54
96
  const pagePromise: Promise<Record<string, unknown>> = route.page?.loader
55
- ? Promise.resolve(route.page.loader(ctxWithRoot, deps)).then((r) => r ?? {})
97
+ ? Promise.resolve(route.page.loader(pageCtx)).then((r) => r ?? {})
56
98
  : Promise.resolve({});
57
99
 
58
- // Step 3: await all in parallel, then flat-merge results.
59
- // loaderMap already contains the root promise, so we don't merge rootData separately.
100
+ // Await everything in parallel, then flat-merge (same contract as before).
60
101
  const results = await Promise.all([...loaderMap.values(), pagePromise]);
61
102
  const data = Object.assign({}, ...results);
62
103
  const headers: Record<string, string> = {};
@@ -2,14 +2,14 @@ import type { HeadOptions, MetaDescriptor } from "../client.ts";
2
2
 
3
3
  export function extractTitle(meta?: MetaDescriptor[]): string | undefined {
4
4
  if (!meta) {
5
- return undefined;
5
+ return;
6
6
  }
7
7
  for (const entry of meta) {
8
8
  if ("title" in entry) {
9
9
  return (entry as { title: string }).title;
10
10
  }
11
11
  }
12
- return undefined;
12
+ return;
13
13
  }
14
14
 
15
15
  export function isMetaTag(entry: MetaDescriptor): boolean {
package/src/router.ts CHANGED
@@ -221,11 +221,21 @@ async function handleDevRequest(
221
221
  // --hot's file watcher, then hand off to renderSSR which runs loaders,
222
222
  // renders React to HTML, and injects __FURIN_DATA__.
223
223
  try {
224
+ let currentRoot = root;
225
+ const rootMod = (await import(`${root.path}?furin-server&t=${Date.now()}`)) as Record<
226
+ string,
227
+ unknown
228
+ >;
229
+ const rootExport = rootMod.route ?? rootMod.default;
230
+ if (rootExport && isFurinRoute(rootExport) && rootExport.layout) {
231
+ currentRoot = { path: root.path, route: rootExport };
232
+ }
233
+
224
234
  const pageMod = await import(`${route.path}?furin-server&t=${Date.now()}`);
225
235
  const page = pageMod.default;
226
236
  if (page && isFurinPage(page)) {
227
237
  const chain = collectRouteChainFromRoute(page._route as RuntimeRoute);
228
- return renderSSR({ ...route, page, routeChain: chain }, ctx, root);
238
+ return renderSSR({ ...route, page, routeChain: chain }, ctx, currentRoot);
229
239
  }
230
240
  } catch (err) {
231
241
  console.error(`[furin] Dev page load error for ${route.path}:`, err);