@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,20 +1,17 @@
1
1
  import { existsSync, writeFileSync } from "node:fs";
2
2
  import { join, relative, resolve } from "node:path";
3
3
  import { buildBunTarget } from "../adapter/bun";
4
+ import { buildStaticTarget } from "../adapter/static";
4
5
  import { BUILD_TARGETS, type BuildTarget } from "../config";
5
6
  import { scanPages } from "../router";
6
7
  import { scanFurinInstances } from "./scan-server";
7
- import {
8
- ensureDir,
9
- toBuildRouteManifestEntry,
10
- toPosixPath,
11
- } from "./shared";
12
- import type {
13
- BuildAppOptions,
14
- BuildAppResult,
15
- BuildManifest,
16
- } from "./types";
8
+ import { ensureDir, toBuildRouteManifestEntry, toPosixPath } from "./shared";
9
+ import type { BuildAppOptions, BuildAppResult, BuildManifest } from "./types";
17
10
 
11
+ // biome-ignore lint/performance/noBarrelFile: intentional — build/index.ts is the public build API entry
12
+ export { buildClient } from "./client";
13
+ export { writeDevFiles } from "./hydrate";
14
+ export { patternToTypeString, schemaToTypeString, writeRouteTypes } from "./route-types";
18
15
  export type {
19
16
  BuildAppOptions,
20
17
  BuildAppResult,
@@ -23,17 +20,18 @@ export type {
23
20
  BuildRouteManifestEntry,
24
21
  TargetBuildManifest,
25
22
  } from "./types";
26
- export { buildClient } from "./client";
27
- export { writeDevFiles } from "./hydrate";
28
- export { patternToTypeString, schemaToTypeString, writeRouteTypes } from "./route-types";
29
23
 
30
- const IMPLEMENTED_TARGETS = ["bun"] as const satisfies BuildTarget[];
24
+ const IMPLEMENTED_TARGETS = ["bun", "static"] as const satisfies BuildTarget[];
31
25
  export const BUILD_OUTPUT_DIR = ".furin/build";
32
26
 
33
27
  function resolvePagesDirFromServer(serverEntry: string | null, rootDir: string): string | null {
34
- if (!serverEntry) return null;
28
+ if (!serverEntry) {
29
+ return null;
30
+ }
35
31
  const detected = scanFurinInstances(serverEntry);
36
- if (detected.length === 0) return null;
32
+ if (detected.length === 0) {
33
+ return null;
34
+ }
37
35
  // Use the first detected pagesDir relative to rootDir
38
36
  return resolve(rootDir, detected[0] as string);
39
37
  }
@@ -42,17 +40,45 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
42
40
  const rootDir = resolve(options.rootDir ?? process.cwd());
43
41
  const buildRoot = join(rootDir, BUILD_OUTPUT_DIR);
44
42
  const serverEntry = (() => {
43
+ // Static-only builds don't need a server entry point
44
+ if (options.target === "static") {
45
+ return null;
46
+ }
45
47
  if (options.serverEntry) {
46
48
  const resolved = resolve(rootDir, options.serverEntry);
47
- if (existsSync(resolved)) return resolved;
49
+ if (existsSync(resolved)) {
50
+ return resolved;
51
+ }
48
52
  }
49
- const serverEntry = resolve(rootDir, "src/server.ts");
50
- if (!existsSync(serverEntry)) {
53
+ const entry = resolve(rootDir, "src/server.ts");
54
+ if (!existsSync(entry)) {
51
55
  throw new Error("[furin] Entrypoint server.ts not found");
52
56
  }
53
- return serverEntry
57
+ return entry;
54
58
  })();
55
59
 
60
+ // Register user plugins as runtime module loaders BEFORE scanPages.
61
+ //
62
+ // scanPages() calls import() on every page file, which triggers all their
63
+ // static imports (e.g. ".mdx" files). If the loader is not yet registered
64
+ // at that point, Bun caches the raw/unprocessed result — and that cached
65
+ // value is reused for every subsequent import(), including prerenderSSG().
66
+ //
67
+ // Build-only plugins (e.g. bun-plugin-tailwind uses onBeforeParse which
68
+ // doesn't exist in the runtime context) are skipped silently — they only
69
+ // affect the Bun.build() client bundle, not server-side rendering.
70
+ for (const plugin of options.plugins ?? []) {
71
+ try {
72
+ Bun.plugin(plugin);
73
+ } catch (err) {
74
+ // Build-only plugins (e.g. bun-plugin-tailwind uses onBeforeParse which
75
+ // does not exist in the runtime context) are expected to throw here —
76
+ // they only affect the Bun.build() client bundle, not server-side rendering.
77
+ // Log at debug level so genuine plugin registration errors remain visible.
78
+ console.debug("[furin] Skipped build-only plugin at runtime:", err);
79
+ }
80
+ }
81
+
56
82
  // Priority: explicit config > auto-detected from server entry > default
57
83
  const rawPagesDir =
58
84
  options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
@@ -96,6 +122,15 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
96
122
  options
97
123
  );
98
124
  break;
125
+ case "static":
126
+ manifest.targets.static = await buildStaticTarget(
127
+ routes,
128
+ rootDir,
129
+ buildRoot,
130
+ root,
131
+ options
132
+ );
133
+ break;
99
134
  case "node":
100
135
  case "vercel":
101
136
  case "cloudflare":
@@ -107,7 +142,7 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
107
142
  }
108
143
  }
109
144
 
110
- writeFileSync(join(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`)
145
+ writeFileSync(join(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
111
146
 
112
147
  return {
113
148
  manifest,
@@ -26,30 +26,36 @@ export function scanFurinInstances(serverEntryPath: string): string[] {
26
26
  return results;
27
27
  }
28
28
 
29
- function walkNode(node: AstNode, out: string[]): void {
30
- if (!node || typeof node !== "object") return;
29
+ const SKIP_KEYS = new Set(["type", "start", "end"]);
31
30
 
32
- if (node.type === "CallExpression") {
33
- const callee = node.callee as AstNode | undefined;
34
- const args = node.arguments as AstNode[] | undefined;
31
+ /** Checks whether `node` is a `furin({ pagesDir: "..." })` call and, if so, pushes the value. */
32
+ function checkFurinCall(node: AstNode, out: string[]): void {
33
+ const callee = node.callee as AstNode | undefined;
34
+ const args = node.arguments as AstNode[] | undefined;
35
+ const isFurinCall =
36
+ callee?.type === "Identifier" && (callee as { name?: string }).name === "furin";
35
37
 
36
- const isFurinCall =
37
- callee?.type === "Identifier" && (callee as { name?: string }).name === "furin";
38
+ if (!(isFurinCall && Array.isArray(args)) || args.length === 0) {
39
+ return;
40
+ }
38
41
 
39
- if (isFurinCall && Array.isArray(args) && args.length > 0) {
40
- const firstArg = args[0] as AstNode;
41
- if (firstArg?.type === "ObjectExpression") {
42
- const pagesDir = extractStringProperty(firstArg, "pagesDir");
43
- if (pagesDir !== null) {
44
- out.push(pagesDir);
45
- }
46
- }
47
- }
42
+ const firstArg = args[0] as AstNode;
43
+ if (firstArg?.type !== "ObjectExpression") {
44
+ return;
48
45
  }
49
46
 
50
- // Recurse into all child node values
47
+ const pagesDir = extractStringProperty(firstArg, "pagesDir");
48
+ if (pagesDir !== null) {
49
+ out.push(pagesDir);
50
+ }
51
+ }
52
+
53
+ /** Recurses into all child AST node values (arrays and plain objects). */
54
+ function walkChildren(node: AstNode, out: string[]): void {
51
55
  for (const key of Object.keys(node)) {
52
- if (key === "type" || key === "start" || key === "end") continue;
56
+ if (SKIP_KEYS.has(key)) {
57
+ continue;
58
+ }
53
59
  const child = node[key];
54
60
  if (Array.isArray(child)) {
55
61
  for (const item of child) {
@@ -63,12 +69,26 @@ function walkNode(node: AstNode, out: string[]): void {
63
69
  }
64
70
  }
65
71
 
72
+ function walkNode(node: AstNode, out: string[]): void {
73
+ if (!node || typeof node !== "object") {
74
+ return;
75
+ }
76
+ if (node.type === "CallExpression") {
77
+ checkFurinCall(node, out);
78
+ }
79
+ walkChildren(node, out);
80
+ }
81
+
66
82
  function extractStringProperty(obj: AstNode, propName: string): string | null {
67
83
  const properties = obj.properties as AstNode[] | undefined;
68
- if (!Array.isArray(properties)) return null;
84
+ if (!Array.isArray(properties)) {
85
+ return null;
86
+ }
69
87
 
70
88
  for (const prop of properties) {
71
- if (prop.type !== "Property") continue;
89
+ if (prop.type !== "Property") {
90
+ continue;
91
+ }
72
92
  const key = prop.key as AstNode & { name?: string; value?: unknown };
73
93
  const value = prop.value as AstNode & { value?: unknown };
74
94
 
@@ -76,7 +96,9 @@ function extractStringProperty(obj: AstNode, propName: string): string | null {
76
96
  (key.type === "Identifier" && key.name === propName) ||
77
97
  (key.type === "Literal" && key.value === propName);
78
98
 
79
- if (!keyMatches) continue;
99
+ if (!keyMatches) {
100
+ continue;
101
+ }
80
102
 
81
103
  // Only accept string literals — ignore template literals, identifiers, etc.
82
104
  if (value?.type === "Literal" && typeof value.value === "string") {
@@ -1,10 +1,22 @@
1
- import type { BuildTarget } from "../config";
1
+ import type { BuildTarget, StaticExportConfig } from "../config";
2
2
  import type { ResolvedRoute } from "../router";
3
3
 
4
4
  export interface BuildClientOptions {
5
+ /**
6
+ * Sub-path prefix for the deployment (e.g. "/furin" for GitHub Pages).
7
+ * Passed through to the generated hydrate entry so SPA navigation uses
8
+ * correct physical URLs. Pass "" for root deployments.
9
+ */
10
+ basePath: string;
5
11
  outDir: string;
6
12
  pagesDir?: string;
7
13
  plugins?: Bun.BunPlugin[];
14
+ /**
15
+ * Public path prefix for all emitted JS/CSS chunks.
16
+ * Pass "/_client/" for root deployments; override for basePath deployments,
17
+ * e.g. "/furin/_client/".
18
+ */
19
+ publicPath: string;
8
20
  rootLayout: string;
9
21
  }
10
22
 
@@ -27,6 +39,8 @@ export interface TargetBuildManifest {
27
39
  templatePath: string | null;
28
40
  }
29
41
 
42
+ export type AnyTargetManifest = TargetBuildManifest | StaticTargetBuildManifest;
43
+
30
44
  export interface BuildManifest {
31
45
  generatedAt: string;
32
46
  pagesDir: string;
@@ -34,7 +48,7 @@ export interface BuildManifest {
34
48
  rootPath: string;
35
49
  routes: BuildRouteManifestEntry[];
36
50
  serverEntry: string | null;
37
- targets: Partial<Record<BuildTarget, TargetBuildManifest>>;
51
+ targets: Partial<Record<BuildTarget, AnyTargetManifest>>;
38
52
  version: 1;
39
53
  }
40
54
 
@@ -44,12 +58,23 @@ export interface BuildAppOptions {
44
58
  plugins?: Bun.BunPlugin[];
45
59
  rootDir?: string;
46
60
  serverEntry?: string;
61
+ /** Configuration for the `static` build target. */
62
+ staticConfig?: StaticExportConfig;
47
63
  target: BuildTarget | "all";
48
64
  }
49
65
 
66
+ /** Build manifest entry produced by the `static` adapter. */
67
+ export interface StaticTargetBuildManifest {
68
+ basePath: string;
69
+ generatedAt: string;
70
+ outDir: string;
71
+ renderedRoutes: string[];
72
+ skippedRoutes: string[];
73
+ }
74
+
50
75
  export interface BuildAppResult {
51
76
  manifest: BuildManifest;
52
- targets: Partial<Record<BuildTarget, TargetBuildManifest>>;
77
+ targets: Partial<Record<BuildTarget, AnyTargetManifest>>;
53
78
  }
54
79
 
55
80
  export type BunBuildAliasConfig = Bun.BuildConfig & {
package/src/cli/index.ts CHANGED
@@ -70,11 +70,18 @@ if (command === "build") {
70
70
 
71
71
  const config = await loadCliConfig(process.cwd(), values.config);
72
72
 
73
- const resolvedServerEntry = resolve(config.rootDir, config.serverEntry ?? "src/server.ts");
74
- if (!existsSync(resolvedServerEntry)) {
75
- const expected = config.serverEntry ?? "src/server.ts";
76
- throw new Error(`[furin] Entrypoint ${expected} not found`);
77
- }
73
+ const isStaticTarget = target === "static";
74
+
75
+ const resolvedServerEntry = isStaticTarget
76
+ ? undefined
77
+ : (() => {
78
+ const entry = resolve(config.rootDir, config.serverEntry ?? "src/server.ts");
79
+ if (!existsSync(entry)) {
80
+ const expected = config.serverEntry ?? "src/server.ts";
81
+ throw new Error(`[furin] Entrypoint ${expected} not found`);
82
+ }
83
+ return entry;
84
+ })();
78
85
 
79
86
  log(`Building Furin for ${target}…`);
80
87
 
@@ -85,6 +92,7 @@ if (command === "build") {
85
92
  pagesDir: values.pagesDir ?? config.pagesDir,
86
93
  serverEntry: resolvedServerEntry,
87
94
  plugins: config.plugins,
95
+ staticConfig: config.static,
88
96
  });
89
97
 
90
98
  const built = Object.keys(result.targets).join(", ") || "none";
package/src/client.ts CHANGED
@@ -31,6 +31,15 @@ type MergeSchema<TParent, TOwn> = [TParent] extends [Unset]
31
31
 
32
32
  type NormalizeUnset<T> = [T] extends [Unset] ? {} : T;
33
33
 
34
+ /**
35
+ * Transforms each key of a parent-data record into an individual `Promise<T>`.
36
+ * This is what child loaders see for inherited fields — direct values from
37
+ * `RouteContext` (request, params, set, …) remain unchanged.
38
+ */
39
+ type PromisifyData<T extends Record<string, unknown>> = {
40
+ [K in keyof T]: Promise<T[K]>;
41
+ };
42
+
34
43
  export interface RouteContext<TParams = {}, TQuery = {}> {
35
44
  cookie: Record<string, Cookie<unknown>>;
36
45
  headers: Record<string, string | undefined>;
@@ -95,8 +104,6 @@ export interface HeadOptions {
95
104
  styles?: Array<{ type?: string; children: string }>;
96
105
  }
97
106
 
98
- export type LoaderDeps = (route: { __type: string }) => Promise<Record<string, unknown>>;
99
-
100
107
  // Extracts the resolved return type from a loader function type.
101
108
  // Using ReturnType + Awaited here means TLoader is inferred as the whole function
102
109
  // first, and then we extract the data — so inference is order-independent.
@@ -115,8 +122,7 @@ export interface PageConfig<
115
122
  component: React.FC<TParentData & TPageLoaderData & ComponentProps<TParams, TQuery>>;
116
123
  head?: (ctx: ComponentProps<TParams, TQuery> & TParentData & TPageLoaderData) => HeadOptions;
117
124
  loader?: (
118
- ctx: RouteContext<TParams, TQuery> & TParentData,
119
- deps: TypedDeps
125
+ ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>
120
126
  ) => Promise<TPageLoaderData> | TPageLoaderData;
121
127
  staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
122
128
  }
@@ -124,10 +130,7 @@ export interface PageConfig<
124
130
  export interface RuntimeRoute {
125
131
  __type: "FURIN_ROUTE";
126
132
  layout?: React.FC<Record<string, unknown> & { children: React.ReactNode }>;
127
- loader?(
128
- ctx: Record<string, unknown>,
129
- deps: LoaderDeps
130
- ): Promise<Record<string, unknown>> | Record<string, unknown>;
133
+ loader?(ctx: Record<string, unknown>): Promise<Record<string, unknown>> | Record<string, unknown>;
131
134
  mode?: "ssr" | "ssg" | "isr";
132
135
  params?: unknown;
133
136
  parent?: RuntimeRoute;
@@ -140,10 +143,7 @@ export interface RuntimePage {
140
143
  _route: RuntimeRoute;
141
144
  component: React.FC<Record<string, unknown>>;
142
145
  head?(ctx: Record<string, unknown>): HeadOptions;
143
- loader?(
144
- ctx: Record<string, unknown>,
145
- deps: LoaderDeps
146
- ): Promise<Record<string, unknown>> | Record<string, unknown>;
146
+ loader?(ctx: Record<string, unknown>): Promise<Record<string, unknown>> | Record<string, unknown>;
147
147
  staticParams?(): Promise<Record<string, string>[]> | Record<string, string>[];
148
148
  }
149
149
 
@@ -167,8 +167,7 @@ interface PageResult<
167
167
  component: React.FC<TData & TPageLoaderData & ComponentProps<TParams, TQuery>>;
168
168
  head?: (ctx: ComponentProps<TParams, TQuery> & TData & TPageLoaderData) => HeadOptions;
169
169
  loader?: (
170
- ctx: RouteContext<TParams, TQuery> & TData,
171
- deps: TypedDeps
170
+ ctx: RouteContext<TParams, TQuery> & PromisifyData<TData>
172
171
  ) => Promise<TPageLoaderData> | TPageLoaderData;
173
172
  }
174
173
 
@@ -176,8 +175,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
176
175
  __type: "FURIN_ROUTE";
177
176
  layout?: React.FC<TParentData & { children: React.ReactNode } & ComponentProps<TParams, TQuery>>;
178
177
  loader?(
179
- ctx: RouteContext<TParams, TQuery> & TParentData,
180
- deps: TypedDeps
178
+ ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>
181
179
  ): Promise<TParentData> | TParentData;
182
180
  mode?: "ssr" | "ssg" | "isr";
183
181
 
@@ -186,7 +184,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
186
184
  // has no inference sites (all NoInfer) so TypeScript applies its default AFTER TLoader is
187
185
  // resolved — making declaration order of head/component irrelevant.
188
186
  page<
189
- TLoader extends (ctx: RouteContext<TParams, TQuery> & TParentData, deps: TypedDeps) => unknown,
187
+ TLoader extends (ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>) => unknown,
190
188
  TPageLoaderData extends object = ExtractLoaderReturn<TLoader>,
191
189
  >(config: {
192
190
  loader: TLoader;
@@ -217,12 +215,6 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
217
215
  revalidate?: number;
218
216
  }
219
217
 
220
- // User-facing typed deps: infers the loader data type from the route ref.
221
- type TypedDeps = <TData extends Record<string, unknown>>(
222
- // biome-ignore lint/suspicious/noExplicitAny: any needed for flexible route type inference
223
- route: Route<TData, any, any>
224
- ) => Promise<TData>;
225
-
226
218
  export function createRoute<
227
219
  TParentRef extends RouteRef | undefined = undefined,
228
220
  TParamsSchema extends AnySchema | Unset = Unset,
@@ -239,8 +231,7 @@ export function createRoute<
239
231
  Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["params"],
240
232
  Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["query"]
241
233
  > &
242
- ResolveParent<TParentRef>["data"],
243
- deps: TypedDeps
234
+ PromisifyData<ResolveParent<TParentRef>["data"]>
244
235
  ) => Promise<TLoaderData> | TLoaderData;
245
236
  layout?: React.FC<
246
237
  Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["data"] & {
package/src/config.ts CHANGED
@@ -2,10 +2,36 @@ export type { BunPlugin } from "bun";
2
2
 
3
3
  import { t } from "elysia";
4
4
 
5
- export const BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare"] as const;
5
+ export const BUILD_TARGETS = ["bun", "node", "vercel", "cloudflare", "static"] as const;
6
6
 
7
7
  export type BuildTarget = (typeof BUILD_TARGETS)[number];
8
8
 
9
+ /**
10
+ * Configuration for the `static` build target.
11
+ * Produces a fully pre-rendered directory deployable to any static host
12
+ * (GitHub Pages, Netlify, Surge.sh, …).
13
+ */
14
+ export interface StaticExportConfig {
15
+ /**
16
+ * Sub-path prefix for GitHub Pages sub-path deployments.
17
+ * e.g. "/furin" when the site is served at `https://user.github.io/furin/`.
18
+ * Must start with "/" and have no trailing slash.
19
+ * Default: "" (site served at root).
20
+ */
21
+ basePath?: string;
22
+ /**
23
+ * Behaviour when SSR or ISR routes are encountered during a static build.
24
+ * - "error" (default): throw at build time with the list of incompatible routes.
25
+ * - "skip": emit a warning and omit those routes from the output.
26
+ */
27
+ onSSR?: "error" | "skip";
28
+ /**
29
+ * Output directory for the static export.
30
+ * Default: "dist".
31
+ */
32
+ outDir?: string;
33
+ }
34
+
9
35
  const buildTargetSchema = t.Union(BUILD_TARGETS.map((v) => t.Literal(v)));
10
36
  const compileTargetSchema = t.Union([t.Literal("server"), t.Literal("embed")]);
11
37
 
@@ -19,11 +45,19 @@ export const configSchema = t.Object({
19
45
  compile: t.Optional(compileTargetSchema),
20
46
  })
21
47
  ),
48
+ static: t.Optional(
49
+ t.Object({
50
+ basePath: t.Optional(t.String()),
51
+ outDir: t.Optional(t.String()),
52
+ onSSR: t.Optional(t.Union([t.Literal("error"), t.Literal("skip")])),
53
+ })
54
+ ),
22
55
  // plugins omitted : TypeBox can't validate Bun.BunPlugin[] (functions)
23
56
  });
24
57
 
25
58
  export type FurinConfig = (typeof configSchema)["static"] & {
26
59
  plugins?: Bun.BunPlugin[];
60
+ static?: StaticExportConfig;
27
61
  };
28
62
 
29
63
  export function defineConfig(config: FurinConfig): FurinConfig {