@teyik0/furin 0.2.0-alpha.4 → 0.2.0-alpha.5

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 (67) hide show
  1. package/dist/adapter/bun.d.ts +17 -1
  2. package/dist/adapter/package.d.ts +26 -0
  3. package/dist/build/client.d.ts +1 -1
  4. package/dist/build/compile-entry.d.ts +3 -3
  5. package/dist/build/compile-entry.ts +88 -83
  6. package/dist/build/entry-template.d.ts +35 -9
  7. package/dist/build/entry-template.ts +106 -56
  8. package/dist/build/hydrate.d.ts +1 -1
  9. package/dist/build/index.js +643 -247
  10. package/dist/build/scan-server.d.ts +10 -4
  11. package/dist/build/server-routes-entry.d.ts +3 -3
  12. package/dist/build/server-routes-entry.ts +5 -11
  13. package/dist/build/ssg-cache.d.ts +1 -1
  14. package/dist/build/types.d.ts +36 -1
  15. package/dist/cli/config.d.ts +6 -1
  16. package/dist/cli/index.js +662 -260
  17. package/dist/config.d.ts +11 -2
  18. package/dist/config.js +5 -1
  19. package/dist/furin.d.ts +36 -18
  20. package/dist/furin.js +630 -310
  21. package/dist/server/auto-invalidate/registry.d.ts +8 -1
  22. package/dist/server/cache/dev-loader.d.ts +3 -2
  23. package/dist/server/cache/invalidation.d.ts +19 -0
  24. package/dist/server/cache/isr.d.ts +6 -2
  25. package/dist/server/cache/registry.d.ts +3 -3
  26. package/dist/server/cache/ssg.d.ts +6 -2
  27. package/dist/server/cache/store-view.d.ts +11 -0
  28. package/dist/server/instance.d.ts +86 -0
  29. package/dist/server/internal.d.ts +16 -1
  30. package/dist/server/internal.js +72 -5
  31. package/dist/server/render/template.d.ts +3 -2
  32. package/dist/server/sync/config.d.ts +11 -0
  33. package/dist/server/sync/stream.d.ts +8 -1
  34. package/dist/shared/prefix.d.ts +15 -0
  35. package/package.json +6 -1
  36. package/src/adapter/bun.ts +113 -50
  37. package/src/adapter/package.ts +206 -0
  38. package/src/build/client.ts +9 -3
  39. package/src/build/compile-entry.ts +88 -83
  40. package/src/build/entry-template.ts +106 -56
  41. package/src/build/hydrate.ts +4 -2
  42. package/src/build/index.ts +99 -28
  43. package/src/build/scan-server.ts +23 -7
  44. package/src/build/server-routes-entry.ts +5 -11
  45. package/src/build/ssg-cache.ts +6 -2
  46. package/src/build/types.ts +37 -1
  47. package/src/cli/config.ts +9 -3
  48. package/src/cli/index.ts +21 -3
  49. package/src/config.ts +14 -1
  50. package/src/furin.ts +297 -143
  51. package/src/server/auto-invalidate/registry.ts +23 -1
  52. package/src/server/auto-invalidate/runtime.ts +29 -4
  53. package/src/server/cache/dev-loader.ts +77 -38
  54. package/src/server/cache/invalidation.ts +71 -30
  55. package/src/server/cache/isr.ts +20 -5
  56. package/src/server/cache/registry.ts +17 -20
  57. package/src/server/cache/ssg.ts +19 -4
  58. package/src/server/cache/store-view.ts +30 -0
  59. package/src/server/instance.ts +252 -0
  60. package/src/server/internal.ts +100 -5
  61. package/src/server/render/not-found.ts +9 -3
  62. package/src/server/render/ssr.ts +16 -4
  63. package/src/server/render/template.ts +57 -24
  64. package/src/server/sync/config.ts +32 -1
  65. package/src/server/sync/plugin.ts +4 -5
  66. package/src/server/sync/stream.ts +19 -9
  67. package/src/shared/prefix.ts +38 -0
@@ -1,106 +1,111 @@
1
1
  import { existsSync, writeFileSync } from "node:fs";
2
2
  import { join, relative } from "node:path";
3
- import { buildEntrySource, type BuildEntryOptions } from "./entry-template";
3
+ import { buildEntrySource, type BuildEntryOptions, type EntryAppContext } from "./entry-template";
4
4
  import { collectFilesRecursive, ensureDir, toPosixPath } from "./shared";
5
5
 
6
6
  /**
7
- * Generates a single `_compile-entry.ts` that:
8
- * 1. Statically imports every page module so Bun bundles them into the binary
9
- * 2. Optionally embeds client assets via `with { type: "file" }` (embed mode)
10
- * 3. Sets production mode and registers everything in a single CompileContext
11
- * 4. Dynamically imports server.ts to boot the app
7
+ * Builds one app's embedded-asset import lines + `embedded:` context block.
8
+ * Asset keys stay UNPREFIXED (`/_client/...`) — the instance's Elysia prefix
9
+ * strips the mount path before lookup at runtime.
12
10
  */
13
- export function generateCompileEntry(options: BuildEntryOptions): string {
14
- const {
15
- buildId,
16
- outDir,
17
- rootPath,
18
- routes,
19
- serverEntry,
20
- embed,
21
- publicDir,
22
- rootConventions,
23
- routeMetadata,
24
- ssgCache,
25
- } = options;
26
- ensureDir(outDir);
27
-
28
- // Build embedded asset imports if embed mode
11
+ function buildEmbeddedAssets(
12
+ outDir: string,
13
+ clientDir: string,
14
+ publicDir: string | undefined,
15
+ varPrefix: string
16
+ ): { extraContext: string[]; extraImports: string[] } {
17
+ if (!existsSync(clientDir)) {
18
+ throw new Error(
19
+ `[furin] Client directory not found: ${clientDir}. Run the client build first.`
20
+ );
21
+ }
22
+ const clientFiles = collectFilesRecursive(clientDir).filter((file) => !file.endsWith(".map"));
29
23
  const assetImports: string[] = [];
30
- let embeddedBlock: string[] = [];
31
- if (embed) {
32
- if (!existsSync(embed.clientDir)) {
33
- throw new Error(
34
- `[furin] Client directory not found: ${embed.clientDir}. Run the client build first.`
35
- );
36
- }
37
- const clientFiles = collectFilesRecursive(embed.clientDir).filter(
38
- (file) => !file.endsWith(".map")
24
+ const assetEntries: string[] = [];
25
+ let templateVarName: string | null = null;
26
+
27
+ let assetIndex = 0;
28
+ const importAsset = (file: string): string => {
29
+ const varName = `${varPrefix}asset${assetIndex++}`;
30
+ const relPath = toPosixPath(relative(outDir, file));
31
+ const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
32
+ assetImports.push(
33
+ `import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`
39
34
  );
40
- const assetEntries: string[] = [];
41
- let templateVarName: string | null = null;
35
+ return varName;
36
+ };
42
37
 
43
- let assetIndex = 0;
44
- for (const file of clientFiles) {
45
- const varName = `_asset${assetIndex++}`;
46
- const relPath = toPosixPath(relative(outDir, file));
47
- const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
38
+ for (const file of clientFiles) {
39
+ const varName = importAsset(file);
40
+ const clientRelativePath = toPosixPath(relative(clientDir, file));
41
+ if (clientRelativePath === "index.html") {
42
+ templateVarName = varName;
43
+ } else {
44
+ assetEntries.push(` ${JSON.stringify(`/_client/${clientRelativePath}`)}: ${varName},`);
45
+ }
46
+ }
48
47
 
49
- assetImports.push(
50
- `import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`
51
- );
48
+ if (templateVarName === null) {
49
+ throw new Error(
50
+ `[furin] Embed mode requires a client index.html at ${join(clientDir, "index.html")}. Run the client build first.`
51
+ );
52
+ }
52
53
 
53
- const clientRelativePath = toPosixPath(relative(embed.clientDir, file));
54
- if (clientRelativePath === "index.html") {
55
- templateVarName = varName;
56
- } else {
57
- assetEntries.push(` ${JSON.stringify(`/_client/${clientRelativePath}`)}: ${varName},`);
58
- }
54
+ if (publicDir && existsSync(publicDir)) {
55
+ const publicFiles = collectFilesRecursive(publicDir);
56
+ for (const file of publicFiles) {
57
+ const varName = importAsset(file);
58
+ const publicRelativePath = toPosixPath(relative(publicDir, file));
59
+ assetEntries.push(` ${JSON.stringify(`/public/${publicRelativePath}`)}: ${varName},`);
59
60
  }
61
+ }
60
62
 
61
- if (templateVarName === null) {
62
- throw new Error(
63
- `[furin] Embed mode requires a client index.html at ${join(embed.clientDir, "index.html")}. Run the client build first.`
64
- );
65
- }
63
+ const extraContext = [
64
+ " embedded: {",
65
+ ` template: ${templateVarName},`,
66
+ " assets: {",
67
+ ...assetEntries,
68
+ " },",
69
+ " },",
70
+ ];
66
71
 
67
- if (publicDir && existsSync(publicDir)) {
68
- const publicFiles = collectFilesRecursive(publicDir);
69
- for (const file of publicFiles) {
70
- const varName = `_asset${assetIndex++}`;
71
- const relPath = toPosixPath(relative(outDir, file));
72
- const importPath = relPath.startsWith(".") ? relPath : `./${relPath}`;
72
+ return { extraContext, extraImports: assetImports };
73
+ }
73
74
 
74
- assetImports.push(
75
- `import ${varName} from ${JSON.stringify(importPath)} with { type: "file" };`
76
- );
75
+ /**
76
+ * Generates a single `_compile-entry.ts` that:
77
+ * 1. Statically imports every page module of every app so Bun bundles them
78
+ * 2. Optionally embeds client assets via `with { type: "file" }` (embed mode)
79
+ * 3. Sets production mode and registers one CompileContext PER APP
80
+ * 4. Dynamically imports server.ts to boot the composed app
81
+ */
82
+ export function generateCompileEntry(options: BuildEntryOptions): string {
83
+ const { apps, outDir, serverEntry, publicDir } = options;
84
+ ensureDir(outDir);
77
85
 
78
- const publicRelativePath = toPosixPath(relative(publicDir, file));
79
- assetEntries.push(` ${JSON.stringify(`/public/${publicRelativePath}`)}: ${varName},`);
80
- }
86
+ const preparedApps: EntryAppContext[] = apps.map((app, appIndex) => {
87
+ const { embed, ...context } = app;
88
+ if (!embed) {
89
+ return context;
81
90
  }
82
-
83
- embeddedBlock = [
84
- " embedded: {",
85
- ` template: ${templateVarName},`,
86
- " assets: {",
87
- ...assetEntries,
88
- " },",
89
- " },",
90
- ];
91
- }
91
+ const varPrefix = apps.length === 1 ? "_" : `_a${appIndex}_`;
92
+ // Every app gets the project-level public/ dir: each instance serves only
93
+ // from its own `embedded.assets`, so `/public/*` (and `/favicon.ico`) would
94
+ // 404 on non-first apps otherwise. This only duplicates the string keys —
95
+ // each app imports the same file via the same relative path, and Bun
96
+ // dedupes identical `with { type: "file" }` modules into one embedded blob.
97
+ const embedded = buildEmbeddedAssets(outDir, embed.clientDir, publicDir, varPrefix);
98
+ return {
99
+ ...context,
100
+ extraContext: [...(context.extraContext ?? []), ...embedded.extraContext],
101
+ extraImports: [...(context.extraImports ?? []), ...embedded.extraImports],
102
+ };
103
+ });
92
104
 
93
105
  const source = buildEntrySource({
94
- buildId,
95
- headerComment: "// Auto-generated by furin compile — do not edit",
96
- rootPath,
97
- routes,
106
+ apps: preparedApps,
107
+ headerComment: options.headerComment ?? "// Auto-generated by furin compile — do not edit",
98
108
  serverEntry,
99
- extraImports: assetImports,
100
- extraContext: embeddedBlock,
101
- rootConventions,
102
- routeMetadata,
103
- ssgCache,
104
109
  });
105
110
 
106
111
  const entryPath = join(outDir, "_compile-entry.ts");
@@ -17,11 +17,15 @@ const _ext = _pkgSrcDir.endsWith("/src") ? ".ts" : ".js";
17
17
  const INTERNAL_MODULE_PATH = `${_pkgSrcDir}/server/internal${_ext}`;
18
18
  const RUNTIME_ENV_MODULE_PATH = `${_pkgSrcDir}/server/runtime-env${_ext}`;
19
19
 
20
- export interface EntryTemplateOptions {
20
+ /** One app's compile context payload — the generated entry can carry several. */
21
+ export interface EntryAppContext {
21
22
  buildId?: string;
23
+ /** Extra lines injected inside this app's `__setCompileContext({...})` call. */
22
24
  extraContext?: string[];
25
+ /** Extra import lines this app needs (embedded asset imports). */
23
26
  extraImports?: string[];
24
- headerComment: string;
27
+ /** Mount prefix baked into the context for runtime lookup (`""` = root). */
28
+ prefix?: string;
25
29
  rootConventions?: { errorPath?: string; notFoundPath?: string };
26
30
  rootPath: string;
27
31
  routeMetadata?: Record<
@@ -36,22 +40,47 @@ export interface EntryTemplateOptions {
36
40
  }
37
41
  >;
38
42
  routes: Array<{ mode: "ssr" | "ssg" | "isr"; path: string; pattern: string }>;
39
- serverEntry: string;
40
43
  ssgCache?: Record<string, SsgCacheEntry>;
41
44
  }
42
45
 
46
+ export interface EntryTemplateOptions {
47
+ apps: EntryAppContext[];
48
+ headerComment: string;
49
+ /**
50
+ * - "boot" (default): forces production mode and dynamically imports the
51
+ * server entry after registering contexts — the whole app's entrypoint.
52
+ * - "register": ONLY registers contexts. Emitted by `--target package` as a
53
+ * side-effect module the HOST app imports; it must not touch dev mode or
54
+ * NODE_ENV (the host decides), and it imports furin internals via the
55
+ * package specifier so the host and the register module share ONE copy of
56
+ * the context registry (`packages: "external"` keeps it unbundled).
57
+ */
58
+ mode?: "boot" | "register";
59
+ /**
60
+ * Server entry to boot after context registration. Omitted in package
61
+ * (register-module) mode where the entry only registers contexts.
62
+ */
63
+ serverEntry?: string;
64
+ }
65
+
43
66
  /** Unified options for generating a build entry (compile or disk-based). */
44
- export interface BuildEntryOptions extends Omit<EntryTemplateOptions, "headerComment"> {
45
- outDir: string;
67
+ export interface BuildEntryOptions {
68
+ apps: Array<
69
+ EntryAppContext & {
70
+ /** Embed mode: bundles this app's client assets via `with { type: "file" }`. */
71
+ embed?: { clientDir: string };
72
+ }
73
+ >;
46
74
  headerComment?: string;
47
- /** Embed mode: bundles client assets into the binary via `with { type: "file" }`. */
48
- embed?: { clientDir: string };
75
+ outDir: string;
76
+ /** Project-level public/ dir — embedded into EVERY app's assets (keys only; Bun dedupes the file payloads). */
49
77
  publicDir?: string;
78
+ serverEntry?: string;
50
79
  }
51
80
 
52
81
  function collectConventionPaths(
53
- rootConventions: EntryTemplateOptions["rootConventions"],
54
- routeMetadata: EntryTemplateOptions["routeMetadata"]
82
+ rootConventions: EntryAppContext["rootConventions"],
83
+ routeMetadata: EntryAppContext["routeMetadata"]
55
84
  ): string[] {
56
85
  const paths: string[] = [];
57
86
  if (rootConventions?.errorPath) {
@@ -75,67 +104,44 @@ function collectConventionPaths(
75
104
  return [...new Set(paths)];
76
105
  }
77
106
 
78
- export function buildEntrySource(options: EntryTemplateOptions): string {
79
- const {
80
- buildId,
81
- headerComment,
82
- rootPath,
83
- routes,
84
- serverEntry,
85
- rootConventions,
86
- routeMetadata,
87
- ssgCache,
88
- } = options;
89
- let { extraImports, extraContext } = options;
90
- if (extraImports === undefined) {
91
- extraImports = [];
92
- }
93
- if (extraContext === undefined) {
94
- extraContext = [];
95
- }
96
-
107
+ /** Emits one app's module imports + `__setCompileContext({...})` call. */
108
+ function buildAppContextBlock(
109
+ app: EntryAppContext,
110
+ varPrefix: string
111
+ ): { contextLines: string[]; importLines: string[] } {
97
112
  const allModulePaths = [
98
- rootPath,
99
- ...routes.map((r) => r.path),
100
- ...collectConventionPaths(rootConventions, routeMetadata),
113
+ app.rootPath,
114
+ ...app.routes.map((r) => r.path),
115
+ ...collectConventionPaths(app.rootConventions, app.routeMetadata),
101
116
  ];
102
- const moduleImports: string[] = [];
117
+ const importLines: string[] = [];
103
118
  const moduleEntries: string[] = [];
104
119
 
105
120
  for (let i = 0; i < allModulePaths.length; i++) {
106
121
  const absPath = (allModulePaths[i] as string).replace(/\\/g, "/");
107
- const varName = `_mod${i}`;
108
- moduleImports.push(`import * as ${varName} from ${JSON.stringify(absPath)};`);
122
+ const varName = `${varPrefix}mod${i}`;
123
+ importLines.push(`import * as ${varName} from ${JSON.stringify(absPath)};`);
109
124
  moduleEntries.push(` ${JSON.stringify(absPath)}: ${varName},`);
110
125
  }
111
126
 
112
- const routeEntries = routes.map(
127
+ const routeEntries = app.routes.map(
113
128
  (r) =>
114
129
  ` { pattern: ${JSON.stringify(r.pattern)}, path: ${JSON.stringify(r.path.replace(/\\/g, "/"))}, mode: ${JSON.stringify(r.mode)} },`
115
130
  );
116
131
 
117
- const rootConventionsLine = rootConventions
118
- ? ` rootConventions: ${JSON.stringify(rootConventions)},`
132
+ const rootConventionsLine = app.rootConventions
133
+ ? ` rootConventions: ${JSON.stringify(app.rootConventions)},`
119
134
  : "";
120
- const routeMetadataLine = routeMetadata
121
- ? ` routeMetadata: ${JSON.stringify(routeMetadata)},`
135
+ const routeMetadataLine = app.routeMetadata
136
+ ? ` routeMetadata: ${JSON.stringify(app.routeMetadata)},`
122
137
  : "";
123
- const ssgCacheLine = ssgCache ? ` ssgCache: ${JSON.stringify(ssgCache)},` : "";
138
+ const ssgCacheLine = app.ssgCache ? ` ssgCache: ${JSON.stringify(app.ssgCache)},` : "";
124
139
 
125
- const lines = [
126
- headerComment,
127
- `import { __setCompileContext } from ${JSON.stringify(INTERNAL_MODULE_PATH)};`,
128
- `import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`,
129
- ...moduleImports,
130
- ...(extraImports.length > 0 ? ["", ...extraImports] : []),
131
- "",
132
- "// Force production mode — Bun may inline process.env.NODE_ENV at bundle time.",
133
- "__setDevMode(false);",
134
- 'process.env.NODE_ENV = "production";',
135
- "",
140
+ const contextLines = [
136
141
  "__setCompileContext({",
137
- ` buildId: ${JSON.stringify(buildId ?? "")},`,
138
- ` rootPath: ${JSON.stringify(rootPath.replace(/\\/g, "/"))},`,
142
+ ` buildId: ${JSON.stringify(app.buildId ?? "")},`,
143
+ ` prefix: ${JSON.stringify(app.prefix ?? "")},`,
144
+ ` rootPath: ${JSON.stringify(app.rootPath.replace(/\\/g, "/"))},`,
139
145
  rootConventionsLine,
140
146
  " modules: {",
141
147
  ...moduleEntries,
@@ -145,11 +151,55 @@ export function buildEntrySource(options: EntryTemplateOptions): string {
145
151
  " ],",
146
152
  routeMetadataLine,
147
153
  ssgCacheLine,
148
- ...extraContext,
154
+ ...(app.extraContext ?? []),
149
155
  "});",
156
+ ];
157
+
158
+ return { contextLines, importLines };
159
+ }
160
+
161
+ export function buildEntrySource(options: EntryTemplateOptions): string {
162
+ const { apps, headerComment, serverEntry } = options;
163
+ const mode = options.mode ?? "boot";
164
+ const internalSpecifier =
165
+ mode === "register" ? "@teyik0/furin/internal" : INTERNAL_MODULE_PATH;
166
+
167
+ const importLines: string[] = [];
168
+ const contextBlocks: string[] = [];
169
+
170
+ for (let appIndex = 0; appIndex < apps.length; appIndex++) {
171
+ const app = apps[appIndex] as EntryAppContext;
172
+ // Per-app variable namespace so several apps' module/asset imports never
173
+ // collide inside the single generated entry.
174
+ const varPrefix = apps.length === 1 ? "_" : `_a${appIndex}_`;
175
+ const block = buildAppContextBlock(app, varPrefix);
176
+ importLines.push(...block.importLines);
177
+ if (app.extraImports && app.extraImports.length > 0) {
178
+ importLines.push("", ...app.extraImports);
179
+ }
180
+ contextBlocks.push("", ...block.contextLines);
181
+ }
182
+
183
+ const lines = [
184
+ headerComment,
185
+ `import { __setCompileContext } from ${JSON.stringify(internalSpecifier)};`,
186
+ ...(mode === "boot"
187
+ ? [`import { __setDevMode } from ${JSON.stringify(RUNTIME_ENV_MODULE_PATH)};`]
188
+ : []),
189
+ ...importLines,
190
+ ...(mode === "boot"
191
+ ? [
192
+ "",
193
+ "// Force production mode — Bun may inline process.env.NODE_ENV at bundle time.",
194
+ "__setDevMode(false);",
195
+ 'process.env.NODE_ENV = "production";',
196
+ ]
197
+ : []),
198
+ ...contextBlocks,
150
199
  "",
151
- `await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`,
152
- "",
200
+ ...(serverEntry
201
+ ? [`await import(${JSON.stringify(serverEntry.replace(/\\/g, "/"))});`, ""]
202
+ : []),
153
203
  ];
154
204
 
155
205
  return lines.join("\n");
@@ -311,7 +311,7 @@ const rootEl = document.getElementById("root") as HTMLElement;
311
311
  */
312
312
  export function writeDevFiles(
313
313
  routes: ResolvedRoute[],
314
- { outDir, rootLayout, basePath, clientLogging }: BuildClientOptions,
314
+ { outDir, rootLayout, basePath, clientLogging, skipRouteTypes }: BuildClientOptions,
315
315
  projectRoot: string
316
316
  ): void {
317
317
  if (!existsSync(outDir)) {
@@ -332,7 +332,9 @@ export function writeDevFiles(
332
332
  writeFileSync(indexPath, indexHtml);
333
333
  }
334
334
 
335
- writeRouteTypes(routes, projectRoot);
335
+ if (!skipRouteTypes) {
336
+ writeRouteTypes(routes, projectRoot);
337
+ }
336
338
 
337
339
  console.log(
338
340
  "[furin] Dev files written (.furin/_hydrate.tsx + .furin/index.html + furin-env.d.ts)"
@@ -1,9 +1,12 @@
1
1
  import { existsSync, writeFileSync } from "node:fs";
2
2
  import { join, relative, resolve } from "node:path";
3
- import { buildBunTarget } from "../adapter/bun";
3
+ import { buildBunTarget, type BunTargetApp } from "../adapter/bun";
4
+ import { buildPackageTarget } from "../adapter/package";
4
5
  import { buildStaticTarget } from "../adapter/static";
5
6
  import { BUILD_TARGETS, type BuildTarget, type FurinPlugin } from "../config";
7
+ import { normalizePrefix } from "../server/instance.ts";
6
8
  import { scanPages } from "../server/router/index.ts";
9
+ import { assertNoPrefixSlugCollisions } from "../shared/prefix.ts";
7
10
  import { scanFurinInstances } from "./scan-server";
8
11
  import { ensureDir, toBuildRouteManifestEntry, toPosixPath } from "./shared";
9
12
  import type { BuildAppOptions, BuildAppResult, BuildManifest } from "./types";
@@ -22,27 +25,54 @@ export type {
22
25
  TargetBuildManifest,
23
26
  } from "./types";
24
27
 
28
+ // "package" is intentionally excluded from `--target all` — it is an
29
+ // alternative packaging of ONE app, not an additional deploy target.
25
30
  const IMPLEMENTED_TARGETS = ["bun", "static"] as const satisfies BuildTarget[];
26
31
  export const BUILD_OUTPUT_DIR = ".furin/build";
27
32
 
28
- function resolvePagesDirFromServer(serverEntry: string | null, rootDir: string): string | null {
29
- if (!serverEntry) {
30
- return null;
33
+ /**
34
+ * Resolves the list of apps to build, in priority order:
35
+ * 1. explicit `apps` config (furin.config.ts),
36
+ * 2. explicit single `pagesDir` option (mounted at root),
37
+ * 3. every `furin({ pagesDir, prefix })` call detected in the server entry,
38
+ * 4. the `src/pages` default.
39
+ */
40
+ function resolveAppSpecs(
41
+ options: BuildAppOptions,
42
+ serverEntry: string | null,
43
+ rootDir: string
44
+ ): Array<{ pagesDir: string; prefix: string }> {
45
+ if (options.apps && options.apps.length > 0) {
46
+ // normalizePrefix is the choke point for config/CLI-provided prefixes:
47
+ // `"/"` → `""` (otherwise the bun target derives `publicPath: "//_client/"`,
48
+ // a protocol-relative URL), trailing slashes are trimmed, and invalid
49
+ // prefixes throw before any build output is written.
50
+ return options.apps.map((app) => ({
51
+ pagesDir: resolve(rootDir, app.pagesDir),
52
+ prefix: normalizePrefix(app.prefix),
53
+ }));
31
54
  }
32
- const detected = scanFurinInstances(serverEntry);
33
- if (detected.length === 0) {
34
- return null;
55
+ if (options.pagesDir) {
56
+ return [{ pagesDir: resolve(rootDir, options.pagesDir), prefix: "" }];
35
57
  }
36
- // Use the first detected pagesDir relative to rootDir
37
- return resolve(rootDir, detected[0] as string);
58
+ if (serverEntry) {
59
+ const detected = scanFurinInstances(serverEntry);
60
+ if (detected.length > 0) {
61
+ return detected.map((app) => ({
62
+ pagesDir: resolve(rootDir, app.pagesDir),
63
+ prefix: app.prefix,
64
+ }));
65
+ }
66
+ }
67
+ return [{ pagesDir: resolve(rootDir, "src/pages"), prefix: "" }];
38
68
  }
39
69
 
40
70
  export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult> {
41
71
  const rootDir = resolve(options.rootDir ?? process.cwd());
42
72
  const buildRoot = join(rootDir, BUILD_OUTPUT_DIR);
43
73
  const serverEntry = (() => {
44
- // Static-only builds don't need a server entry point
45
- if (options.target === "static") {
74
+ // Static and package builds don't need a server entry point
75
+ if (options.target === "static" || options.target === "package") {
46
76
  return null;
47
77
  }
48
78
  if (options.serverEntry) {
@@ -80,10 +110,19 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
80
110
  }
81
111
  }
82
112
 
83
- // Priority: explicit config > auto-detected from server entry > default
84
- const rawPagesDir =
85
- options.pagesDir ?? resolvePagesDirFromServer(serverEntry, rootDir) ?? "src/pages";
86
- const pagesDir = resolve(rootDir, rawPagesDir);
113
+ const appSpecs = resolveAppSpecs(options, serverEntry, rootDir);
114
+ const duplicatePrefix = appSpecs.find(
115
+ (spec, index) => appSpecs.findIndex((other) => other.prefix === spec.prefix) !== index
116
+ );
117
+ if (duplicatePrefix) {
118
+ throw new Error(
119
+ `[furin] Two apps are configured with the prefix "${duplicatePrefix.prefix || "/"}" — give each app a unique prefix.`
120
+ );
121
+ }
122
+ // Distinct prefixes can still slug to the same client dir (`/a-b` vs `/a/b`
123
+ // → `client-a-b`), which would let a later app's assets overwrite an earlier
124
+ // one's — reject before any target writes output.
125
+ assertNoPrefixSlugCollisions(appSpecs.map((spec) => spec.prefix));
87
126
 
88
127
  const requestedTargets =
89
128
  options.target === "all"
@@ -95,8 +134,14 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
95
134
  return target as BuildTarget;
96
135
  });
97
136
 
98
- // scanPages throws if root.tsx is missing, so root is always defined here.
99
- const { root, routes } = await scanPages(pagesDir);
137
+ // scanPages throws if root.tsx is missing, so root is always defined per app.
138
+ const apps: BunTargetApp[] = [];
139
+ for (const spec of appSpecs) {
140
+ const { root, routes } = await scanPages(spec.pagesDir);
141
+ apps.push({ pagesDir: spec.pagesDir, prefix: spec.prefix, root, routes });
142
+ }
143
+ // The root-mounted app drives single-app manifest fields and the static target.
144
+ const primaryApp = (apps.find((app) => app.prefix === "") ?? apps[0]) as BunTargetApp;
100
145
 
101
146
  ensureDir(buildRoot);
102
147
 
@@ -104,31 +149,57 @@ export async function buildApp(options: BuildAppOptions): Promise<BuildAppResult
104
149
  version: 1,
105
150
  generatedAt: new Date().toISOString(),
106
151
  rootDir: toPosixPath(rootDir),
107
- pagesDir: toPosixPath(relative(rootDir, pagesDir)),
108
- rootPath: toPosixPath(relative(rootDir, root.path)),
152
+ pagesDir: toPosixPath(relative(rootDir, primaryApp.pagesDir)),
153
+ rootPath: toPosixPath(relative(rootDir, primaryApp.root.path)),
109
154
  serverEntry: serverEntry ? toPosixPath(relative(rootDir, serverEntry)) : null,
110
- routes: routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
155
+ routes: primaryApp.routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
156
+ apps: apps.map((app) => ({
157
+ pagesDir: toPosixPath(relative(rootDir, app.pagesDir)),
158
+ prefix: app.prefix,
159
+ routes: app.routes.map((route) => toBuildRouteManifestEntry(route, rootDir)),
160
+ })),
111
161
  targets: {},
112
162
  };
113
163
 
114
164
  for (const target of requestedTargets) {
115
165
  switch (target) {
116
166
  case "bun":
117
- manifest.targets.bun = await buildBunTarget(
118
- routes,
167
+ manifest.targets.bun = await buildBunTarget(apps, rootDir, buildRoot, serverEntry, options);
168
+ break;
169
+ case "static":
170
+ if (apps.length > 1) {
171
+ console.warn(
172
+ "[furin] `--target static` exports the root-mounted app only — prefixed apps are skipped."
173
+ );
174
+ }
175
+ // The static adapter only knows about staticConfig.basePath — the mount
176
+ // prefix is a server-side concept it never sees. Exporting a prefixed
177
+ // app without a matching basePath produces root-relative asset URLs.
178
+ if (primaryApp.prefix !== "") {
179
+ console.warn(
180
+ `[furin] \`--target static\` exports an app mounted at "${primaryApp.prefix}", but the ` +
181
+ `static export ignores the mount prefix — set \`static.basePath\` to "${primaryApp.prefix}" ` +
182
+ "(or the sub-path the site is served from) so asset URLs resolve correctly."
183
+ );
184
+ }
185
+ manifest.targets.static = await buildStaticTarget(
186
+ primaryApp.routes,
119
187
  rootDir,
120
188
  buildRoot,
121
- root,
122
- serverEntry,
189
+ primaryApp.root,
123
190
  options
124
191
  );
125
192
  break;
126
- case "static":
127
- manifest.targets.static = await buildStaticTarget(
128
- routes,
193
+ case "package":
194
+ if (apps.length > 1) {
195
+ throw new Error(
196
+ "[furin] `--target package` builds exactly one app — configure a single pagesDir/prefix."
197
+ );
198
+ }
199
+ manifest.targets.package = await buildPackageTarget(
200
+ primaryApp,
129
201
  rootDir,
130
202
  buildRoot,
131
- root,
132
203
  options
133
204
  );
134
205
  break;