@teyik0/furin 0.1.0-alpha.10

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.
Files changed (87) hide show
  1. package/dist/adapter/bun.d.ts +3 -0
  2. package/dist/adapter/static.d.ts +3 -0
  3. package/dist/build/client.d.ts +25 -0
  4. package/dist/build/compile-entry.d.ts +35 -0
  5. package/dist/build/entry-template.d.ts +26 -0
  6. package/dist/build/hydrate.d.ts +24 -0
  7. package/dist/build/index.d.ts +7 -0
  8. package/dist/build/index.js +4716 -0
  9. package/dist/build/route-types.d.ts +21 -0
  10. package/dist/build/scan-server.d.ts +8 -0
  11. package/dist/build/server-routes-entry.d.ts +35 -0
  12. package/dist/build/shared.d.ts +11 -0
  13. package/dist/build/types.d.ts +76 -0
  14. package/dist/cli/config.d.ts +9 -0
  15. package/dist/cli/index.d.ts +2 -0
  16. package/dist/cli/index.js +4751 -0
  17. package/dist/client.d.ts +195 -0
  18. package/dist/client.js +20 -0
  19. package/dist/config.d.ts +50 -0
  20. package/dist/config.js +28 -0
  21. package/dist/context-logger.d.ts +28 -0
  22. package/dist/dev-page-plugin.d.ts +109 -0
  23. package/dist/error.d.ts +23 -0
  24. package/dist/furin.d.ts +52 -0
  25. package/dist/furin.js +3948 -0
  26. package/dist/internal.d.ts +33 -0
  27. package/dist/link.d.ts +454 -0
  28. package/dist/link.js +1790 -0
  29. package/dist/not-found.d.ts +19 -0
  30. package/dist/plugin/index.d.ts +20 -0
  31. package/dist/plugin/index.js +1408 -0
  32. package/dist/plugin/transform-client.d.ts +9 -0
  33. package/dist/render/assemble.d.ts +15 -0
  34. package/dist/render/boundaries.d.ts +79 -0
  35. package/dist/render/cache.d.ts +96 -0
  36. package/dist/render/default-screens.d.ts +11 -0
  37. package/dist/render/digest.d.ts +16 -0
  38. package/dist/render/element.d.ts +8 -0
  39. package/dist/render/index.d.ts +53 -0
  40. package/dist/render/loaders.d.ts +21 -0
  41. package/dist/render/shell.d.ts +29 -0
  42. package/dist/render/template.d.ts +6 -0
  43. package/dist/router.d.ts +96 -0
  44. package/dist/router.js +2693 -0
  45. package/dist/runtime-env.d.ts +3 -0
  46. package/dist/utils.d.ts +6 -0
  47. package/package.json +77 -0
  48. package/src/adapter/README.md +13 -0
  49. package/src/adapter/bun.ts +239 -0
  50. package/src/adapter/static.ts +341 -0
  51. package/src/build/client.ts +153 -0
  52. package/src/build/compile-entry.ts +129 -0
  53. package/src/build/entry-template.ts +126 -0
  54. package/src/build/hydrate.ts +250 -0
  55. package/src/build/index.ts +151 -0
  56. package/src/build/route-types.ts +89 -0
  57. package/src/build/scan-server.ts +110 -0
  58. package/src/build/server-routes-entry.ts +55 -0
  59. package/src/build/shared.ts +78 -0
  60. package/src/build/types.ts +85 -0
  61. package/src/cli/config.ts +68 -0
  62. package/src/cli/index.ts +115 -0
  63. package/src/client.ts +278 -0
  64. package/src/config.ts +66 -0
  65. package/src/context-logger.ts +74 -0
  66. package/src/dev-page-plugin.ts +434 -0
  67. package/src/env.d.ts +49 -0
  68. package/src/error.ts +32 -0
  69. package/src/furin.ts +383 -0
  70. package/src/internal.ts +51 -0
  71. package/src/link.tsx +1578 -0
  72. package/src/not-found.ts +40 -0
  73. package/src/plugin/index.ts +80 -0
  74. package/src/plugin/transform-client.ts +372 -0
  75. package/src/render/assemble.ts +66 -0
  76. package/src/render/boundaries.tsx +176 -0
  77. package/src/render/cache.ts +251 -0
  78. package/src/render/default-screens.tsx +299 -0
  79. package/src/render/digest.ts +71 -0
  80. package/src/render/element.tsx +119 -0
  81. package/src/render/index.ts +867 -0
  82. package/src/render/loaders.ts +127 -0
  83. package/src/render/shell.ts +187 -0
  84. package/src/render/template.ts +55 -0
  85. package/src/router.ts +779 -0
  86. package/src/runtime-env.ts +6 -0
  87. package/src/utils.ts +68 -0
@@ -0,0 +1,151 @@
1
+ import { existsSync, writeFileSync } from "node:fs";
2
+ import { join, relative, resolve } from "node:path";
3
+ import { buildBunTarget } from "../adapter/bun";
4
+ import { buildStaticTarget } from "../adapter/static";
5
+ import { BUILD_TARGETS, type BuildTarget, type FurinPlugin } from "../config";
6
+ import { scanPages } from "../router";
7
+ import { scanFurinInstances } from "./scan-server";
8
+ import { ensureDir, toBuildRouteManifestEntry, toPosixPath } from "./shared";
9
+ import type { BuildAppOptions, BuildAppResult, BuildManifest } from "./types";
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";
15
+ export type {
16
+ BuildAppOptions,
17
+ BuildAppResult,
18
+ BuildClientOptions,
19
+ BuildManifest,
20
+ BuildRouteManifestEntry,
21
+ TargetBuildManifest,
22
+ } from "./types";
23
+
24
+ const IMPLEMENTED_TARGETS = ["bun", "static"] as const satisfies BuildTarget[];
25
+ export const BUILD_OUTPUT_DIR = ".furin/build";
26
+
27
+ function resolvePagesDirFromServer(serverEntry: string | null, rootDir: string): string | null {
28
+ if (!serverEntry) {
29
+ return null;
30
+ }
31
+ const detected = scanFurinInstances(serverEntry);
32
+ if (detected.length === 0) {
33
+ return null;
34
+ }
35
+ // Use the first detected pagesDir relative to rootDir
36
+ return resolve(rootDir, detected[0] as string);
37
+ }
38
+
39
+ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult> {
40
+ const rootDir = resolve(options.rootDir ?? process.cwd());
41
+ const buildRoot = join(rootDir, BUILD_OUTPUT_DIR);
42
+ const serverEntry = (() => {
43
+ // Static-only builds don't need a server entry point
44
+ if (options.target === "static") {
45
+ return null;
46
+ }
47
+ if (options.serverEntry) {
48
+ const resolved = resolve(rootDir, options.serverEntry);
49
+ if (existsSync(resolved)) {
50
+ return resolved;
51
+ }
52
+ }
53
+ const entry = resolve(rootDir, "src/server.ts");
54
+ if (!existsSync(entry)) {
55
+ throw new Error("[furin] Entrypoint server.ts not found");
56
+ }
57
+ return entry;
58
+ })();
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
+ const { buildOnly, ...runtimePlugin } = plugin as FurinPlugin;
72
+ if (buildOnly) {
73
+ continue;
74
+ }
75
+ try {
76
+ Bun.plugin(runtimePlugin);
77
+ } catch (err) {
78
+ console.debug("[furin] Skipped plugin at runtime:", err);
79
+ }
80
+ }
81
+
82
+ // Priority: explicit config > auto-detected from server entry > default
83
+ const rawPagesDir =
84
+ options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
85
+ const pagesDir = resolve(rootDir, rawPagesDir);
86
+
87
+ const requestedTargets =
88
+ options.target === "all"
89
+ ? [...IMPLEMENTED_TARGETS]
90
+ : [options.target].map((target) => {
91
+ if (!(BUILD_TARGETS as readonly string[]).includes(target)) {
92
+ throw new Error(`[furin] Unsupported build target "${target}"`);
93
+ }
94
+ return target as BuildTarget;
95
+ });
96
+
97
+ // scanPages throws if root.tsx is missing, so root is always defined here.
98
+ const { root, routes } = await scanPages(pagesDir);
99
+
100
+ ensureDir(buildRoot);
101
+
102
+ const manifest: BuildManifest = {
103
+ version: 1,
104
+ generatedAt: new Date().toISOString(),
105
+ rootDir: toPosixPath(rootDir),
106
+ pagesDir: toPosixPath(relative(rootDir, pagesDir)),
107
+ rootPath: toPosixPath(relative(rootDir, root.path)),
108
+ serverEntry: serverEntry ? toPosixPath(relative(rootDir, serverEntry)) : null,
109
+ routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
110
+ targets: {},
111
+ };
112
+
113
+ for (const target of requestedTargets) {
114
+ switch (target) {
115
+ case "bun":
116
+ manifest.targets.bun = await buildBunTarget(
117
+ routes,
118
+ rootDir,
119
+ buildRoot,
120
+ root,
121
+ serverEntry,
122
+ options
123
+ );
124
+ break;
125
+ case "static":
126
+ manifest.targets.static = await buildStaticTarget(
127
+ routes,
128
+ rootDir,
129
+ buildRoot,
130
+ root,
131
+ options
132
+ );
133
+ break;
134
+ case "node":
135
+ case "vercel":
136
+ case "cloudflare":
137
+ throw new Error(
138
+ `[furin] \`--target ${target}\` is planned but not implemented yet in this branch.`
139
+ );
140
+ default:
141
+ throw new Error(`[furin] Unsupported build target "${target}"`);
142
+ }
143
+ }
144
+
145
+ writeFileSync(join(buildRoot, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
146
+
147
+ return {
148
+ manifest,
149
+ targets: manifest.targets,
150
+ };
151
+ }
@@ -0,0 +1,89 @@
1
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import type { ResolvedRoute } from "../router";
4
+
5
+ /** @internal Exported for unit testing only. */
6
+ export function patternToTypeString(pattern: string): string {
7
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: intentional — generates TS template literal syntax
8
+ const t = pattern.replace(/:[^/]+/g, "${string}").replace(/\*/g, "${string}");
9
+ return t.includes("${") ? `\`${t}\`` : `"${t}"`;
10
+ }
11
+
12
+ /**
13
+ * Converts a runtime TypeBox/JSON Schema object to a TypeScript type string.
14
+ * Handles the common cases found in Elysia query schemas (string, number, boolean,
15
+ * optional fields, nullable via anyOf).
16
+ *
17
+ * @internal Exported for unit testing only.
18
+ */
19
+ export function schemaToTypeString(schema: unknown): string {
20
+ if (!schema || typeof schema !== "object") {
21
+ return "unknown";
22
+ }
23
+ const s = schema as Record<string, unknown>;
24
+ if (s.anyOf && Array.isArray(s.anyOf)) {
25
+ const parts = (s.anyOf as unknown[]).map(schemaToTypeString).filter((t) => t !== "null");
26
+ return parts.join(" | ") || "unknown";
27
+ }
28
+ switch (s.type) {
29
+ case "string":
30
+ return "string";
31
+ case "number":
32
+ case "integer":
33
+ return "number";
34
+ case "boolean":
35
+ return "boolean";
36
+ case "null":
37
+ return "null";
38
+ case "object": {
39
+ if (!s.properties || typeof s.properties !== "object") {
40
+ return "Record<string, unknown>";
41
+ }
42
+ const required = new Set<string>(Array.isArray(s.required) ? (s.required as string[]) : []);
43
+ const props = Object.entries(s.properties as Record<string, unknown>)
44
+ .map(([k, v]) => `${k}${required.has(k) ? "" : "?"}: ${schemaToTypeString(v)}`)
45
+ .join("; ");
46
+ return `{ ${props} }`;
47
+ }
48
+ default:
49
+ return "unknown";
50
+ }
51
+ }
52
+
53
+ /**
54
+ * Generates furin-env.d.ts at the project root — augments RouteManifest
55
+ * in furin/link so that <Link to="..."> has type-safe autocompletion and
56
+ * <Link search={...}> is typed per-route from the route's query schema.
57
+ *
58
+ * Written to the project root (like Next.js's next-env.d.ts) so it is
59
+ * committed to git and always available in CI without a build step.
60
+ */
61
+ /** @internal Exported for unit testing only. */
62
+ export function writeRouteTypes(routes: ResolvedRoute[], projectRoot: string): void {
63
+ const entries = routes.map((r) => {
64
+ const typeKey = patternToTypeString(r.pattern);
65
+ const isDynamic = typeKey.startsWith("`");
66
+ const querySchema = r.routeChain?.find((rt) => rt.query)?.query;
67
+ const searchType = querySchema ? schemaToTypeString(querySchema) : "never";
68
+ return isDynamic
69
+ ? ` [key: ${typeKey}]: { search?: ${searchType} }`
70
+ : ` ${typeKey}: { search?: ${searchType} }`;
71
+ });
72
+
73
+ const content = `// Auto-generated by Furin. Do not edit manually.
74
+ /// <reference types="@teyik0/furin/env" />
75
+ import "@teyik0/furin/link";
76
+
77
+ declare module "@teyik0/furin/link" {
78
+ interface RouteManifest {
79
+ ${entries.join(";\n")};
80
+ }
81
+ }
82
+ `;
83
+
84
+ const typesPath = join(projectRoot, "furin-env.d.ts");
85
+ const existing = existsSync(typesPath) ? readFileSync(typesPath, "utf8") : "";
86
+ if (content !== existing) {
87
+ writeFileSync(typesPath, content);
88
+ }
89
+ }
@@ -0,0 +1,110 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { parseSync } from "oxc-parser";
3
+
4
+ // Minimal AST node shapes — just what we need
5
+ interface AstNode {
6
+ type: string;
7
+ [key: string]: unknown;
8
+ }
9
+
10
+ /**
11
+ * Statically scans a server entry file and returns all `pagesDir` string
12
+ * literal values found inside `furin({ pagesDir: "..." })` call expressions.
13
+ *
14
+ * Dynamic paths (template literals, variables) are silently ignored.
15
+ * Returns an empty array when nothing is detected.
16
+ */
17
+ export function scanFurinInstances(serverEntryPath: string): string[] {
18
+ const code = readFileSync(serverEntryPath, "utf8");
19
+ const { program, errors } = parseSync(serverEntryPath, code);
20
+ if (errors.length > 0) {
21
+ return [];
22
+ }
23
+
24
+ const results: string[] = [];
25
+ walkNode(program as unknown as AstNode, results);
26
+ return results;
27
+ }
28
+
29
+ const SKIP_KEYS = new Set(["type", "start", "end"]);
30
+
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";
37
+
38
+ if (!(isFurinCall && Array.isArray(args)) || args.length === 0) {
39
+ return;
40
+ }
41
+
42
+ const firstArg = args[0] as AstNode;
43
+ if (firstArg?.type !== "ObjectExpression") {
44
+ return;
45
+ }
46
+
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 {
55
+ for (const key of Object.keys(node)) {
56
+ if (SKIP_KEYS.has(key)) {
57
+ continue;
58
+ }
59
+ const child = node[key];
60
+ if (Array.isArray(child)) {
61
+ for (const item of child) {
62
+ if (item && typeof item === "object") {
63
+ walkNode(item as AstNode, out);
64
+ }
65
+ }
66
+ } else if (child && typeof child === "object") {
67
+ walkNode(child as AstNode, out);
68
+ }
69
+ }
70
+ }
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
+
82
+ function extractStringProperty(obj: AstNode, propName: string): string | null {
83
+ const properties = obj.properties as AstNode[] | undefined;
84
+ if (!Array.isArray(properties)) {
85
+ return null;
86
+ }
87
+
88
+ for (const prop of properties) {
89
+ if (prop.type !== "Property") {
90
+ continue;
91
+ }
92
+ const key = prop.key as AstNode & { name?: string; value?: unknown };
93
+ const value = prop.value as AstNode & { value?: unknown };
94
+
95
+ const keyMatches =
96
+ (key.type === "Identifier" && key.name === propName) ||
97
+ (key.type === "Literal" && key.value === propName);
98
+
99
+ if (!keyMatches) {
100
+ continue;
101
+ }
102
+
103
+ // Only accept string literals — ignore template literals, identifiers, etc.
104
+ if (value?.type === "Literal" && typeof value.value === "string") {
105
+ return value.value;
106
+ }
107
+ return null; // dynamic path — silently skip
108
+ }
109
+ return null;
110
+ }
@@ -0,0 +1,55 @@
1
+ import { writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { buildEntrySource } from "./entry-template";
4
+ import { ensureDir } from "./shared";
5
+
6
+ export interface ServerRoutesEntryOptions {
7
+ buildId?: string;
8
+ outDir: string;
9
+ rootConventions?: { errorPath?: string; notFoundPath?: string };
10
+ rootPath: string;
11
+ routeMetadata?: Record<
12
+ string,
13
+ {
14
+ segmentBoundaries: Array<{
15
+ depth: number;
16
+ path: string;
17
+ errorPath?: string;
18
+ notFoundPath?: string;
19
+ }>;
20
+ }
21
+ >;
22
+ routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
23
+ serverEntry: string;
24
+ }
25
+
26
+ /**
27
+ * Generates `server.ts` — an intermediate entry used to produce `server.js`.
28
+ *
29
+ * Equivalent to `_compile-entry.ts` but for disk (non-binary) production builds:
30
+ * 1. Statically imports every page module so Bun bundles them into server.js
31
+ * 2. Sets production mode and registers everything in a single CompileContext
32
+ * 3. Imports server.ts to boot the app
33
+ *
34
+ * This file is intermediate: `adapter/bun.ts` runs `Bun.build()` on it to produce
35
+ * the self-contained `server.js` bundle, then deletes this file.
36
+ */
37
+ export function generateServerRoutesEntry(options: ServerRoutesEntryOptions): string {
38
+ const { buildId, outDir, rootPath, routes, serverEntry, rootConventions, routeMetadata } =
39
+ options;
40
+ ensureDir(outDir);
41
+ const source = buildEntrySource({
42
+ buildId,
43
+ headerComment: "// Auto-generated by furin build — do not edit",
44
+ rootPath,
45
+ routes,
46
+ serverEntry,
47
+ rootConventions,
48
+ routeMetadata,
49
+ });
50
+
51
+ // Named "server.ts" so Bun.build() outputs "server.js"
52
+ const entryPath = join(outDir, "server.ts");
53
+ writeFileSync(entryPath, source);
54
+ return entryPath;
55
+ }
@@ -0,0 +1,78 @@
1
+ import { cpSync, existsSync, mkdirSync, readdirSync, rmSync } from "node:fs";
2
+ import { join, relative } from "node:path";
3
+ import type { BuildTarget } from "../config";
4
+ import type { ResolvedRoute } from "../router";
5
+ import type { BuildRouteManifestEntry, TargetBuildManifest } from "./types";
6
+
7
+ // import.meta.dir/path/url are inlined at bundle time to the OUTPUT file's
8
+ // location — so relative paths break when bundled. import.meta.resolve() is a
9
+ // function call (not inlined), runs at runtime, and resolves through package
10
+ // exports. This is the Web-standard approach (Bun, Node 20.6+, browsers).
11
+ export const CLIENT_MODULE_PATH = new URL(import.meta.resolve("@teyik0/furin/client")).pathname;
12
+ export const LINK_MODULE_PATH = new URL(import.meta.resolve("@teyik0/furin/link")).pathname;
13
+
14
+ export function ensureDir(path: string): void {
15
+ if (!existsSync(path)) {
16
+ mkdirSync(path, { recursive: true });
17
+ }
18
+ }
19
+
20
+ export function toPosixPath(path: string): string {
21
+ return path.replace(/\\/g, "/");
22
+ }
23
+
24
+ export function collectFilesRecursive(dir: string): string[] {
25
+ const files: string[] = [];
26
+ const entries = readdirSync(dir, { withFileTypes: true });
27
+
28
+ for (const entry of entries) {
29
+ const absolutePath = join(dir, entry.name);
30
+ if (entry.isDirectory()) {
31
+ files.push(...collectFilesRecursive(absolutePath));
32
+ continue;
33
+ }
34
+ if (entry.isFile()) {
35
+ files.push(absolutePath);
36
+ }
37
+ }
38
+
39
+ return files.sort();
40
+ }
41
+
42
+ export function copyDirRecursive(sourceDir: string, targetDir: string): void {
43
+ rmSync(targetDir, { force: true, recursive: true });
44
+ cpSync(sourceDir, targetDir, { recursive: true });
45
+ }
46
+
47
+ export function toBuildRouteManifestEntry(
48
+ route: ResolvedRoute,
49
+ rootDir: string
50
+ ): BuildRouteManifestEntry {
51
+ return {
52
+ pattern: route.pattern,
53
+ mode: route.mode,
54
+ pagePath: toPosixPath(relative(rootDir, route.path)),
55
+ hasLayout: route.routeChain.some((entry) => !!entry.layout),
56
+ hasStaticParams: !!route.page?.staticParams,
57
+ revalidate: route.page?._route.revalidate ?? null,
58
+ };
59
+ }
60
+
61
+ export function buildTargetManifest(
62
+ rootDir: string,
63
+ buildRoot: string,
64
+ target: BuildTarget,
65
+ serverEntry: string | null
66
+ ): TargetBuildManifest {
67
+ const targetDir = join(buildRoot, target);
68
+
69
+ return {
70
+ buildId: "", // populated by adapter after buildClient() completes
71
+ generatedAt: new Date().toISOString(),
72
+ targetDir: toPosixPath(relative(rootDir, targetDir)),
73
+ clientDir: toPosixPath(relative(rootDir, join(targetDir, "client"))),
74
+ templatePath: toPosixPath(relative(rootDir, join(targetDir, "client", "index.html"))),
75
+ serverPath: null,
76
+ serverEntry: serverEntry ? toPosixPath(relative(rootDir, serverEntry)) : null,
77
+ };
78
+ }
@@ -0,0 +1,85 @@
1
+ import type { BuildTarget, StaticExportConfig } from "../config";
2
+ import type { ResolvedRoute } from "../router";
3
+
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;
11
+ outDir: string;
12
+ pagesDir?: string;
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;
20
+ rootLayout: string;
21
+ }
22
+
23
+ export interface BuildRouteManifestEntry {
24
+ hasLayout: boolean;
25
+ hasStaticParams: boolean;
26
+ mode: ResolvedRoute["mode"];
27
+ pagePath: string;
28
+ pattern: string;
29
+ revalidate: number | null;
30
+ }
31
+
32
+ export interface TargetBuildManifest {
33
+ buildId: string;
34
+ clientDir: string | null;
35
+ generatedAt: string;
36
+ serverEntry: string | null;
37
+ serverPath: string | null;
38
+ targetDir: string;
39
+ templatePath: string | null;
40
+ }
41
+
42
+ export type AnyTargetManifest = TargetBuildManifest | StaticTargetBuildManifest;
43
+
44
+ export interface BuildManifest {
45
+ generatedAt: string;
46
+ pagesDir: string;
47
+ rootDir: string;
48
+ rootPath: string;
49
+ routes: BuildRouteManifestEntry[];
50
+ serverEntry: string | null;
51
+ targets: Partial<Record<BuildTarget, AnyTargetManifest>>;
52
+ version: 1;
53
+ }
54
+
55
+ export interface BuildAppOptions {
56
+ compile?: "server" | "embed";
57
+ pagesDir?: string;
58
+ plugins?: Bun.BunPlugin[];
59
+ rootDir?: string;
60
+ serverEntry?: string;
61
+ /** Configuration for the `static` build target. */
62
+ staticConfig?: StaticExportConfig;
63
+ target: BuildTarget | "all";
64
+ }
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
+
75
+ export interface BuildAppResult {
76
+ manifest: BuildManifest;
77
+ targets: Partial<Record<BuildTarget, AnyTargetManifest>>;
78
+ }
79
+
80
+ export type BunBuildAliasConfig = Bun.BuildConfig & {
81
+ alias?: Record<string, string>;
82
+ outfile?: string;
83
+ packages?: "bundle" | "external";
84
+ write?: boolean;
85
+ };
@@ -0,0 +1,68 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { TypeCompiler } from "elysia/type-system";
5
+ import { configSchema, type FurinConfig } from "../config.ts";
6
+
7
+ const compiledConfigSchema = TypeCompiler.Compile(configSchema);
8
+
9
+ const DEFAULT_CONFIG_FILENAMES = [
10
+ "furin.config.ts",
11
+ "furin.config.js",
12
+ "furin.config.mjs",
13
+ ] as const;
14
+
15
+ interface ResolvedCliConfig extends FurinConfig {
16
+ configPath: string | null;
17
+ pagesDir: string;
18
+ plugins?: Bun.BunPlugin[];
19
+ rootDir: string;
20
+ }
21
+
22
+ export async function loadCliConfig(
23
+ cwd: string,
24
+ explicitConfigPath?: string
25
+ ): Promise<ResolvedCliConfig> {
26
+ const rootDir = resolve(cwd);
27
+ const configPath = explicitConfigPath
28
+ ? resolve(rootDir, explicitConfigPath)
29
+ : DEFAULT_CONFIG_FILENAMES.map((filename) => resolve(rootDir, filename)).find((path) =>
30
+ existsSync(path)
31
+ );
32
+
33
+ if (!configPath) {
34
+ return {
35
+ configPath: null,
36
+ rootDir,
37
+ pagesDir: resolve(rootDir, "src/pages"),
38
+ };
39
+ }
40
+
41
+ const imported = await import(pathToFileURL(configPath).href);
42
+ const rawConfig: FurinConfig = imported.default ?? imported;
43
+
44
+ // Extract plugins before TypeBox validation: functions cannot be JSON-schema validated
45
+ const { plugins, ...configToValidate } = rawConfig;
46
+
47
+ if (plugins !== undefined && !Array.isArray(plugins)) {
48
+ throw new Error(
49
+ `[furin] Invalid config at ${configPath}: "plugins" must be an array of BunPlugin objects`
50
+ );
51
+ }
52
+
53
+ if (!compiledConfigSchema.Check(configToValidate)) {
54
+ const [firstError] = compiledConfigSchema.Errors(configToValidate);
55
+ throw new Error(
56
+ `[furin] Invalid config at ${configPath}: ${firstError?.message ?? "unknown error"} (path: ${firstError?.path ?? "/"})`
57
+ );
58
+ }
59
+
60
+ const resolvedRootDir = resolve(rootDir, configToValidate.rootDir ?? ".");
61
+ return {
62
+ ...configToValidate,
63
+ plugins,
64
+ configPath,
65
+ rootDir: resolvedRootDir,
66
+ pagesDir: resolve(resolvedRootDir, configToValidate.pagesDir ?? "src/pages"),
67
+ };
68
+ }