@teyik0/furin 0.8.0-alpha.0 → 0.9.0-alpha.0

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 (143) hide show
  1. package/README.md +37 -0
  2. package/dist/adapter/bun/app.d.ts +1 -0
  3. package/dist/adapter/bun.d.ts +3 -1
  4. package/dist/adapter/runtime-build.d.ts +8 -5
  5. package/dist/adapter/vercel.js +8 -8
  6. package/dist/build/client.d.ts +2 -2
  7. package/dist/build/discover-mounts-process.d.ts +1 -1
  8. package/dist/build/discover-pages-process.d.ts +1 -0
  9. package/dist/build/discover-pages.d.ts +11 -0
  10. package/dist/build/discovery-module.d.ts +3 -0
  11. package/dist/build/discovery-plugins.d.ts +34 -0
  12. package/dist/build/elysia-aot.d.ts +1 -1
  13. package/dist/build/entry-template.ts +6 -1
  14. package/dist/build/hydrate.d.ts +3 -2
  15. package/dist/build/index.js +7688 -8458
  16. package/dist/build/preload-manifest.d.ts +2 -2
  17. package/dist/build/route-metadata.d.ts +31 -0
  18. package/dist/build/route-types.d.ts +1 -1
  19. package/dist/build/shared.d.ts +2 -2
  20. package/dist/build/types.d.ts +11 -0
  21. package/dist/cli/dev-worker.d.ts +1 -0
  22. package/dist/cli/dev-worker.ts +123 -0
  23. package/dist/cli/dev.d.ts +1 -0
  24. package/dist/cli/index.js +7811 -8477
  25. package/dist/client/browser-events-runtime.d.ts +2 -2
  26. package/dist/client/browser-events.d.ts +2 -0
  27. package/dist/client/chunks/{client-brdfd773.js → client-rjhxgt64.js} +187 -4
  28. package/dist/client/dev-error-overlay.ts +18 -1
  29. package/dist/client/link.js +110 -156
  30. package/dist/client/query-store.d.ts +5 -0
  31. package/dist/client/router/navigation-controller.d.ts +2 -0
  32. package/dist/client/router/use-fetch-interception.d.ts +1 -1
  33. package/dist/client/router/use-sync-stream.d.ts +1 -1
  34. package/dist/client/{router/sync-catch-up.d.ts → sync-catch-up.d.ts} +5 -3
  35. package/dist/client/sync-client.d.ts +74 -0
  36. package/dist/client.d.ts +1 -0
  37. package/dist/client.js +533 -145
  38. package/dist/config.d.ts +6 -1
  39. package/dist/config.js +3 -1
  40. package/dist/define-route.d.ts +3 -3
  41. package/dist/furin.d.ts +2 -1
  42. package/dist/furin.js +1119 -346
  43. package/dist/plugin/index.js +5 -5
  44. package/dist/plugin/route-registry.d.ts +22 -2
  45. package/dist/rsc/build/index.d.ts +4 -3
  46. package/dist/server/dev/server-only-module.d.ts +5 -0
  47. package/dist/server/internal.js +201 -91
  48. package/dist/server/logging/ingest-plugin.d.ts +1 -2
  49. package/dist/server/production-server.js +36 -33
  50. package/dist/server/server-entry.d.ts +5 -0
  51. package/dist/server/server-entry.js +36 -0
  52. package/dist/server/static-export.js +201 -91
  53. package/dist/server/sync/adapter.d.ts +4 -3
  54. package/dist/server/sync/config.d.ts +7 -0
  55. package/dist/server/sync/connection.d.ts +13 -0
  56. package/dist/server/sync/drizzle/index.js +5 -4
  57. package/dist/server/sync/index.d.ts +3 -0
  58. package/dist/server/sync/index.js +1361 -243
  59. package/dist/server/sync/invalidate-sync.d.ts +6 -2
  60. package/dist/server/sync/local-client.d.ts +9 -0
  61. package/dist/server/sync/postgres/index.d.ts +1 -1
  62. package/dist/server/sync/postgres/index.js +2 -2
  63. package/dist/server/sync/prisma/index.js +2 -2
  64. package/dist/server/sync/redis/index.d.ts +1 -1
  65. package/dist/server/sync/redis/index.js +4 -3
  66. package/dist/server/sync/redis/scripts.d.ts +1 -1
  67. package/dist/server/sync/runtime.d.ts +3 -0
  68. package/dist/server/sync/sqlite/index.d.ts +1 -1
  69. package/dist/server/sync/sqlite/index.js +3 -2
  70. package/dist/shared/browser-events.d.ts +4 -0
  71. package/dist/sync-client.d.ts +3 -0
  72. package/dist/sync-client.js +1600 -0
  73. package/package.json +12 -7
  74. package/src/adapter/README.md +7 -0
  75. package/src/adapter/build.ts +34 -33
  76. package/src/adapter/bun/app.ts +5 -0
  77. package/src/adapter/bun/server.ts +2 -2
  78. package/src/adapter/bun.ts +18 -2
  79. package/src/adapter/furin-app.d.ts +1 -0
  80. package/src/adapter/package.ts +1 -0
  81. package/src/adapter/runtime-build.ts +18 -12
  82. package/src/adapter/static.ts +17 -13
  83. package/src/build/client.ts +7 -5
  84. package/src/build/discover-mounts-process.ts +5 -1
  85. package/src/build/discover-pages-process.ts +151 -0
  86. package/src/build/discover-pages.ts +69 -0
  87. package/src/build/discovery-module.ts +70 -0
  88. package/src/build/discovery-plugins.ts +101 -0
  89. package/src/build/elysia-aot-worker.ts +9 -8
  90. package/src/build/elysia-aot.ts +110 -75
  91. package/src/build/entry-template.ts +6 -1
  92. package/src/build/hydrate.ts +11 -8
  93. package/src/build/index.ts +6 -50
  94. package/src/build/preload-manifest.ts +3 -3
  95. package/src/build/route-metadata.ts +90 -0
  96. package/src/build/route-types.ts +1 -1
  97. package/src/build/shared.ts +6 -8
  98. package/src/build/types.ts +9 -0
  99. package/src/cli/config.ts +4 -0
  100. package/src/cli/dev-worker.ts +123 -0
  101. package/src/cli/dev.ts +91 -0
  102. package/src/cli/index.ts +24 -1
  103. package/src/client/browser-events-runtime.ts +97 -23
  104. package/src/client/browser-events.ts +8 -0
  105. package/src/client/dev-error-overlay.ts +18 -1
  106. package/src/client/query-store.ts +54 -3
  107. package/src/client/router/navigation-controller.ts +45 -12
  108. package/src/client/router/provider.tsx +6 -2
  109. package/src/client/router/use-fetch-interception.ts +1 -1
  110. package/src/client/router/use-sync-stream.ts +96 -44
  111. package/src/client/{router/sync-catch-up.ts → sync-catch-up.ts} +28 -12
  112. package/src/client/sync-client.ts +528 -0
  113. package/src/client/sync.ts +11 -4
  114. package/src/client.ts +10 -0
  115. package/src/config.ts +17 -10
  116. package/src/furin.ts +5 -0
  117. package/src/plugin/route-registry.ts +53 -7
  118. package/src/rsc/build/index.ts +6 -3
  119. package/src/server/browser-events/plugin.ts +79 -25
  120. package/src/server/dev/rewrite-module-specifiers.ts +2 -1
  121. package/src/server/dev/server-only-module.ts +23 -0
  122. package/src/server/dev/symbolicate.ts +4 -3
  123. package/src/server/dev-page-imports.ts +3 -1
  124. package/src/server/dev-page-plugin.ts +18 -1
  125. package/src/server/logging/ingest-plugin.ts +3 -9
  126. package/src/server/server-entry.ts +39 -0
  127. package/src/server/sync/adapter.ts +7 -3
  128. package/src/server/sync/config.ts +12 -6
  129. package/src/server/sync/connection.ts +71 -0
  130. package/src/server/sync/index.ts +3 -0
  131. package/src/server/sync/invalidate-sync.ts +30 -5
  132. package/src/server/sync/local-client.ts +84 -0
  133. package/src/server/sync/plugin.ts +27 -20
  134. package/src/server/sync/postgres/index.ts +9 -2
  135. package/src/server/sync/redis/index.ts +5 -1
  136. package/src/server/sync/redis/scripts.ts +1 -1
  137. package/src/server/sync/runtime.ts +56 -18
  138. package/src/server/sync/sqlite/index.ts +6 -2
  139. package/src/server/sync/stream.ts +17 -5
  140. package/src/shared/browser-events.ts +1 -1
  141. package/src/sync-client.ts +14 -0
  142. package/dist/server/logger.d.ts +0 -10
  143. package/src/server/logger.ts +0 -34
@@ -8,14 +8,13 @@ import type { RuntimeTargetApp } from "../adapter/runtime-build";
8
8
  import { buildStaticTarget } from "../adapter/static";
9
9
  import type { FurinAdapter } from "../adapter/types.ts";
10
10
  import { vercel } from "../adapter/vercel.ts";
11
- import { BUILD_TARGETS, type BuildTarget, type FurinPlugin, type FurinTarget } from "../config";
11
+ import { BUILD_TARGETS, type BuildTarget, type FurinTarget } from "../config";
12
12
  import { assertValidRouteConfig } from "../plugin/route-config.ts";
13
- import { isomorphicTransformPlugin } from "../plugin/transform-isomorphic.ts";
14
13
  import { normalizePrefix } from "../server/instance.ts";
15
- import { scanPages } from "../server/router/discovery.ts";
16
14
  import { assertNoPrefixSlugCollisions, assertOnePagesDirPerMount } from "../shared/prefix.ts";
17
15
  import { withProductionBuild } from "../shared/production-build.ts";
18
16
  import { discoverFurinMounts } from "./discover-mounts.ts";
17
+ import { discoverPages } from "./discover-pages.ts";
19
18
  import { writeRouteTypes } from "./route-types";
20
19
  import { ensureDir, toBuildRouteManifestEntry, toPosixPath } from "./shared";
21
20
  import type { BuildAppOptions, BuildAppResult, BuildManifest } from "./types";
@@ -59,19 +58,9 @@ function adapterFor(target: FurinAdapter | "bun" | "vercel", options: BuildAppOp
59
58
  if (typeof target !== "string") {
60
59
  return target;
61
60
  }
62
- return target === "bun" ? bun(options.compile) : vercel({});
61
+ return target === "bun" ? bun(options.compile, options.bun?.output) : vercel({});
63
62
  }
64
63
  const BUILD_OUTPUT_DIR = ".furin/build";
65
- let isomorphicRuntimePluginRegistered = false;
66
-
67
- function registerIsomorphicRuntimePlugin(): void {
68
- if (isomorphicRuntimePluginRegistered) {
69
- return;
70
- }
71
- Bun.plugin(isomorphicTransformPlugin("server"));
72
- isomorphicRuntimePluginRegistered = true;
73
- }
74
-
75
64
  /**
76
65
  * Resolves the list of apps to build, in priority order:
77
66
  * 1. explicit `apps` config (furin.config.ts),
@@ -110,43 +99,14 @@ async function resolveAppSpecs(
110
99
  }
111
100
 
112
101
  /**
113
- * Registers runtime plugins, resolves the configured apps and scans their
114
- * pages. Shared by `buildApp()` and `generateRouteTypes()`.
102
+ * Resolves and validates mounts, then evaluates their pages in a disposable
103
+ * process. Shared by `buildApp()` and `generateRouteTypes()`.
115
104
  */
116
105
  async function scanApps(
117
106
  options: RouteTypegenOptions,
118
107
  serverEntry: string | null,
119
108
  rootDir: string
120
109
  ): Promise<RuntimeTargetApp[]> {
121
- // Register user plugins as runtime module loaders BEFORE scanPages.
122
- //
123
- // scanPages() calls import() on every page file, which triggers all their
124
- // static imports (e.g. ".mdx" files). If the loader is not yet registered
125
- // at that point, Bun caches the raw/unprocessed result — and that cached
126
- // value is reused for every subsequent import(), including prerenderSSG().
127
- //
128
- // Plugins marked `buildOnly` (e.g. bun-plugin-tailwind uses onBeforeParse,
129
- // which doesn't exist in the runtime context) only affect Bun.build()
130
- // bundles. Any other registration failure would make route imports differ
131
- // from the bundle, so it fails the build.
132
- for (const plugin of options.plugins ?? []) {
133
- const { buildOnly, ...runtimePlugin } = plugin as FurinPlugin;
134
- if (buildOnly) {
135
- continue;
136
- }
137
- try {
138
- Bun.plugin(runtimePlugin);
139
- } catch (err) {
140
- throw new Error(
141
- `[furin] Plugin "${runtimePlugin.name}" could not be registered for server-side route imports: ${err instanceof Error ? err.message : String(err)}\n` +
142
- "If it only transforms the client bundle (for example bun-plugin-tailwind), mark it build-only in furin.config.ts:\n" +
143
- " plugins: [{ ...plugin, buildOnly: true }]",
144
- { cause: err }
145
- );
146
- }
147
- }
148
- registerIsomorphicRuntimePlugin();
149
-
150
110
  const appSpecs = await resolveAppSpecs(options, serverEntry, rootDir);
151
111
  const duplicatePrefix = appSpecs.find(
152
112
  (spec, index) => appSpecs.findIndex((other) => other.prefix === spec.prefix) !== index
@@ -162,14 +122,10 @@ async function scanApps(
162
122
  // one's — reject before any target writes output.
163
123
  assertNoPrefixSlugCollisions(appSpecs.map((spec) => spec.prefix));
164
124
 
165
- // scanPages throws if root.tsx is missing, so root is always defined per app.
166
- const apps: RuntimeTargetApp[] = [];
167
125
  for (const spec of appSpecs) {
168
126
  assertValidRouteConfig(spec);
169
- const { root, routes } = await scanPages(spec.pagesDir);
170
- apps.push({ pagesDir: spec.pagesDir, prefix: spec.prefix, root, routes });
171
127
  }
172
- return apps;
128
+ return discoverPages(appSpecs, rootDir, options.plugins ?? []);
173
129
  }
174
130
 
175
131
  /** `RouteMap` for the root-mounted app, `FileRoutes` for every app. */
@@ -1,7 +1,7 @@
1
1
  import { existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
2
2
  import { basename, resolve } from "node:path";
3
3
  import { clientModuleKey } from "../plugin/transform-client-module.ts";
4
- import type { ResolvedRoute } from "../server/router/types.ts";
4
+ import type { BuildRouteInput } from "./route-metadata.ts";
5
5
 
6
6
  const CLIENT_MODULE_KEY_RE = /(["'`])(__FURIN_CLIENT_MODULE_[a-z0-9]+__)\1/g;
7
7
 
@@ -14,7 +14,7 @@ export interface ClientPreloadManifest {
14
14
  }
15
15
 
16
16
  /** Client modules a route's hydration loads (mirrors the generated hydrate entry). */
17
- function routeModulePaths(route: ResolvedRoute): string[] {
17
+ function routeModulePaths(route: BuildRouteInput): string[] {
18
18
  const layouts = (route.routeChain ?? [])
19
19
  .slice(1)
20
20
  .filter((entry) => entry.layout && entry.sourcePath)
@@ -41,7 +41,7 @@ export function writeClientPreloadManifest(
41
41
  metafile: Bun.BuildMetafile,
42
42
  outputPaths: string[],
43
43
  entryChunkPath: string,
44
- routes: ResolvedRoute[],
44
+ routes: BuildRouteInput[],
45
45
  publicPrefix: string
46
46
  ): ClientPreloadManifest {
47
47
  const outputs = new Map(
@@ -0,0 +1,90 @@
1
+ import { hasMixedLoaderModes } from "../server/render/loaders.ts";
2
+ import {
3
+ resolveDocumentMode,
4
+ resolveDocumentRevalidate,
5
+ resolveRouteRevalidate,
6
+ } from "../server/router/patterns.ts";
7
+ import { mergeRouteSchemas } from "../server/router/schema-merge.ts";
8
+ import type { ResolvedRoute, RootLayout, SegmentBoundary } from "../server/router/types.ts";
9
+ import { isTypeBoxObjectSchema } from "../shared/elysia-contract.ts";
10
+ import { collectSearchDefaults, type SearchParamsInput } from "../shared/search-params.ts";
11
+
12
+ interface RouteBuildInfo {
13
+ documentMode: ResolvedRoute["mode"];
14
+ documentRevalidate: number | undefined;
15
+ hasLayout: boolean;
16
+ hasRequestLoader: boolean;
17
+ hasStaticParams: boolean;
18
+ mixed: boolean;
19
+ queryKeys: string[] | null;
20
+ revalidate: number | undefined;
21
+ searchDefaults: SearchParamsInput | undefined;
22
+ }
23
+
24
+ /** Discovery results contain data only; application closures stay in the child. */
25
+ export interface BuildRoute
26
+ extends Pick<
27
+ ResolvedRoute,
28
+ "mode" | "path" | "pattern" | "requestKeys" | "requestKeysByLoader" | "tags"
29
+ > {
30
+ build: RouteBuildInfo;
31
+ routeChain: { layout: boolean; sourcePath?: string }[];
32
+ segmentBoundaries: Pick<SegmentBoundary, "depth" | "path" | "errorPath" | "notFoundPath">[];
33
+ }
34
+
35
+ export type BuildRouteInput = BuildRoute | ResolvedRoute;
36
+ export type BuildRoot = Pick<RootLayout, "path" | "errorPath" | "notFoundPath"> & {
37
+ hasRequestLoader: boolean;
38
+ };
39
+
40
+ export function rootHasRequestLoader(root: BuildRoot | RootLayout): boolean {
41
+ return "route" in root ? root.route.requestLoader !== undefined : root.hasRequestLoader;
42
+ }
43
+
44
+ /** Also accepts live routes for the public buildClient API and dev hydration. */
45
+ export function routeBuildInfo(route: BuildRouteInput): RouteBuildInfo {
46
+ if ("build" in route) {
47
+ return route.build;
48
+ }
49
+ const chain = route.routeChain ?? [];
50
+ const query = mergeRouteSchemas(chain, "query");
51
+ let queryKeys: string[] | null = [];
52
+ if (query !== undefined) {
53
+ queryKeys = isTypeBoxObjectSchema(query) ? Object.keys(query.properties).toSorted() : null;
54
+ }
55
+ return {
56
+ documentMode: resolveDocumentMode({ ...route, routeChain: chain }),
57
+ documentRevalidate: resolveDocumentRevalidate({ ...route, routeChain: chain }),
58
+ hasLayout: chain.some((entry) => !!entry.layout),
59
+ hasRequestLoader: chain.some((entry) => entry.requestLoader !== undefined),
60
+ hasStaticParams:
61
+ route.page.staticParams !== undefined ||
62
+ chain.some((entry) => entry.staticParams !== undefined),
63
+ mixed: hasMixedLoaderModes({ ...route, routeChain: chain }),
64
+ queryKeys,
65
+ revalidate: resolveRouteRevalidate(route.page),
66
+ searchDefaults: collectSearchDefaults(query),
67
+ };
68
+ }
69
+
70
+ export function buildRouteMetadata(route: ResolvedRoute): BuildRoute {
71
+ return {
72
+ build: routeBuildInfo(route),
73
+ mode: route.mode,
74
+ path: route.path,
75
+ pattern: route.pattern,
76
+ requestKeys: route.requestKeys,
77
+ requestKeysByLoader: route.requestKeysByLoader,
78
+ routeChain: route.routeChain.map((entry) => ({
79
+ layout: !!entry.layout,
80
+ sourcePath: entry.sourcePath,
81
+ })),
82
+ segmentBoundaries: route.segmentBoundaries.map(({ depth, path, errorPath, notFoundPath }) => ({
83
+ depth,
84
+ path,
85
+ errorPath,
86
+ notFoundPath,
87
+ })),
88
+ tags: route.tags,
89
+ };
90
+ }
@@ -95,7 +95,7 @@ ${body}
95
95
  * `defineRoute(id)` accepts any id.
96
96
  */
97
97
  export function writeRouteTypes(
98
- routes: ResolvedRoute[],
98
+ routes: Pick<ResolvedRoute, "path" | "pattern" | "tags">[],
99
99
  projectRoot: string,
100
100
  apps?: readonly RouteInstanceSpec[]
101
101
  ): boolean {
@@ -1,8 +1,7 @@
1
1
  import { cpSync, existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
2
2
  import { dirname, relative } from "node:path";
3
3
  import { fileURLToPath } from "node:url";
4
- import { resolveRouteRevalidate } from "../server/router/patterns.ts";
5
- import type { ResolvedRoute } from "../server/router/types.ts";
4
+ import { type BuildRouteInput, routeBuildInfo } from "./route-metadata.ts";
6
5
  import type { BuildRouteManifestEntry } from "./types";
7
6
 
8
7
  // import.meta.dir/path/url are inlined at bundle time to the OUTPUT file's
@@ -35,17 +34,16 @@ export function copyDirRecursive(sourceDir: string, targetDir: string): void {
35
34
  }
36
35
 
37
36
  export function toBuildRouteManifestEntry(
38
- route: ResolvedRoute,
37
+ route: BuildRouteInput,
39
38
  rootDir: string
40
39
  ): BuildRouteManifestEntry {
40
+ const info = routeBuildInfo(route);
41
41
  return {
42
42
  pattern: route.pattern,
43
43
  mode: route.mode,
44
44
  pagePath: toPosixPath(relative(rootDir, route.path)),
45
- hasLayout: route.routeChain.some((entry) => !!entry.layout),
46
- hasStaticParams:
47
- route.page.staticParams !== undefined ||
48
- route.routeChain.some((entry) => entry.staticParams !== undefined),
49
- revalidate: resolveRouteRevalidate(route.page) ?? null,
45
+ hasLayout: info.hasLayout,
46
+ hasStaticParams: info.hasStaticParams,
47
+ revalidate: info.revalidate ?? null,
50
48
  };
51
49
  }
@@ -1,9 +1,12 @@
1
1
  import type { AdapterTargetManifest } from "../adapter/types.ts";
2
2
  import type { FurinTarget, StaticExportConfig } from "../config";
3
+ import type { RouteRegistrySnapshot } from "../plugin/route-registry.ts";
3
4
  import type { ResolvedRoute } from "../server/router/types.ts";
4
5
  import type { ClientBoundary } from "../rsc/build/discover.ts";
5
6
 
6
7
  export interface BuildClientOptions {
8
+ /** Route registry evaluated in the discovery process. */
9
+ routeRegistry?: RouteRegistrySnapshot;
7
10
  /**
8
11
  * Sub-path prefix for the deployment (e.g. "/furin" for GitHub Pages).
9
12
  * Passed through to the generated hydrate entry so SPA navigation uses
@@ -49,6 +52,8 @@ export interface BuildRouteManifestEntry {
49
52
  }
50
53
 
51
54
  export interface TargetBuildManifest {
55
+ /** Importable, inert Bun application; absent for listening server outputs. */
56
+ appPath?: string;
52
57
  buildId: string;
53
58
  clientDir: string | null;
54
59
  generatedAt: string;
@@ -97,6 +102,8 @@ export interface BuildManifest {
97
102
  export interface BuildAppOptions {
98
103
  /** Emit Bun metafiles for client and supported server bundle analysis. */
99
104
  analyze?: boolean;
105
+ /** Bun emits a listening server unless output is explicitly "app". */
106
+ bun?: { output?: "app" | "server" };
100
107
  /**
101
108
  * Explicit multi-app build (furin.config.ts `apps`). Overrides `pagesDir`
102
109
  * and the mounts found by evaluating the server entry.
@@ -115,6 +122,8 @@ export interface BuildAppOptions {
115
122
  reactCompiler?: boolean;
116
123
  rootDir?: string;
117
124
  serverEntry?: string;
125
+ /** Runtime packages excluded from server and RSC bundles, including their subpaths. */
126
+ serverExternalPackages?: string[];
118
127
  /** Emit server source maps outside deployable output directories. */
119
128
  serverSourceMaps?: boolean;
120
129
  /** Configuration for the `static` build target. */
package/src/cli/config.ts CHANGED
@@ -61,6 +61,10 @@ function findUnknownKey(value: unknown, schema: TSchema, path: string): string |
61
61
  if (!t.IsObject(schema) || typeof value !== "object" || value === null) {
62
62
  return;
63
63
  }
64
+ // Open objects such as `desktop` are validated by the integration that owns them.
65
+ if ("additionalProperties" in schema && schema.additionalProperties === true) {
66
+ return;
67
+ }
64
68
  const { properties } = schema;
65
69
  const validKeys = Object.keys(properties);
66
70
  for (const [key, child] of Object.entries(value)) {
@@ -0,0 +1,123 @@
1
+ import { pathToFileURL } from "node:url";
2
+ import "elysia";
3
+ import type { AnyElysia } from "elysia";
4
+ import { BunAdapter } from "elysia/adapter/bun";
5
+
6
+ interface WebDevelopment {
7
+ load: <T>(load: () => Promise<T>) => Promise<T>;
8
+ ready: (app: AnyElysia) => Promise<void>;
9
+ stop: () => Promise<void>;
10
+ }
11
+
12
+ // Bun hot reload retains the global owner, not the old imported module graph.
13
+ const key: unique symbol = Symbol.for("@teyik0/furin/web-dev");
14
+ const global = globalThis as typeof globalThis & {
15
+ [key]?: { dispose: () => Promise<void>; cancel: () => Promise<void> };
16
+ };
17
+ const previous = global[key];
18
+ if (previous) {
19
+ process.off("SIGINT", previous.cancel);
20
+ process.off("SIGTERM", previous.cancel);
21
+ process.off("message", previous.cancel);
22
+ await previous.dispose();
23
+ }
24
+ const [, , entry, port, integration] = process.argv;
25
+ if (!entry) {
26
+ throw new Error("Missing development server entry.");
27
+ }
28
+ let app: AnyElysia | undefined;
29
+ let web: WebDevelopment | undefined;
30
+ const dispose = async () => {
31
+ try {
32
+ await app?.stop(true);
33
+ } finally {
34
+ await web?.stop();
35
+ }
36
+ };
37
+ let stopping: Promise<void> | undefined;
38
+ const stop = (status: number) => {
39
+ stopping ??= (async () => {
40
+ let code = status;
41
+ const timer = setTimeout(() => process.exit(1), 5000);
42
+ try {
43
+ await dispose();
44
+ } catch (error) {
45
+ console.error(error);
46
+ code = 1;
47
+ } finally {
48
+ clearTimeout(timer);
49
+ process.exit(code);
50
+ }
51
+ })();
52
+ return stopping;
53
+ };
54
+ const cancel = () => stop(0);
55
+ global[key] = { dispose, cancel };
56
+ process.on("SIGINT", cancel);
57
+ process.on("SIGTERM", cancel);
58
+ process.on("message", cancel);
59
+ const timer = setTimeout(() => {
60
+ console.error("Web development startup exceeded 30 seconds.");
61
+ stop(1).catch(console.error);
62
+ }, 30_000);
63
+ try {
64
+ if (integration) {
65
+ const addon: { createWebDevelopment: () => WebDevelopment } = await import(
66
+ pathToFileURL(integration).href
67
+ );
68
+ web = addon.createWebDevelopment();
69
+ }
70
+ const { listen } = BunAdapter;
71
+ if (!listen) {
72
+ throw new Error("Web development requires Elysia's Bun adapter.");
73
+ }
74
+ const ready = Promise.withResolvers<void>();
75
+ // Source import can fail after a startup failure has already rejected readiness.
76
+ ready.promise.catch(() => undefined);
77
+ BunAdapter.listen = (root, options, callback) => {
78
+ if (app) {
79
+ throw new Error("Web development supports one application listener.");
80
+ }
81
+ app = root;
82
+ root.onStop(() => ready.reject(new Error("Web development startup failed.")));
83
+ if (typeof options === "object" && options.unix !== undefined) {
84
+ throw new Error("Web development requires a TCP listener.");
85
+ }
86
+ const settings = port
87
+ ? { ...(typeof options === "object" ? options : {}), unix: undefined, port: Number(port) }
88
+ : options;
89
+ return listen(root, settings, (server) => {
90
+ callback?.(server);
91
+ ready.resolve();
92
+ });
93
+ };
94
+ try {
95
+ const load = (): Promise<{ default?: AnyElysia; app?: AnyElysia }> =>
96
+ import(pathToFileURL(entry).href);
97
+ const module = await (web ? web.load(load) : load());
98
+ const exported = module.default ?? module.app;
99
+ if (app && exported && exported !== app) {
100
+ throw new Error("Default-export the listening Elysia app.");
101
+ }
102
+ if (!app) {
103
+ if (!exported || typeof exported.listen !== "function") {
104
+ throw new Error("Listen on or default-export an Elysia app.");
105
+ }
106
+ exported.listen({ hostname: "127.0.0.1", port: 3000 });
107
+ }
108
+ await ready.promise;
109
+ } finally {
110
+ BunAdapter.listen = listen;
111
+ }
112
+ const activeApp = app;
113
+ if (!activeApp) {
114
+ throw new Error("Web development did not start a listener.");
115
+ }
116
+ await web?.ready(activeApp);
117
+ clearTimeout(timer);
118
+ console.log(`[furin] Web development: ${activeApp.server?.url.origin}`);
119
+ } catch (error) {
120
+ clearTimeout(timer);
121
+ console.error(error);
122
+ await stop(1);
123
+ }
package/src/cli/dev.ts ADDED
@@ -0,0 +1,91 @@
1
+ import { join, resolve } from "node:path";
2
+ import { pathToFileURL } from "node:url";
3
+ import { parseArgs } from "node:util";
4
+ import { loadCliConfig } from "./config";
5
+
6
+ const PORT = /^\d+$/;
7
+
8
+ export async function runDevelopment(cwd: string, args: string[]): Promise<void> {
9
+ const { values } = parseArgs({
10
+ args: args.filter((arg) => arg !== "--"),
11
+ options: { web: { type: "boolean" }, desktop: { type: "boolean" }, port: { type: "string" } },
12
+ strict: true,
13
+ });
14
+ if (values.web && values.desktop) {
15
+ throw new Error("Choose --web or --desktop, not both.");
16
+ }
17
+ const config = await loadCliConfig(cwd);
18
+ const hasDesktop = config.desktop !== undefined;
19
+ if (hasDesktop && !values.web) {
20
+ if (values.port !== undefined) {
21
+ throw new Error("--port is only available with --web.");
22
+ }
23
+ let entry: string;
24
+ try {
25
+ entry = Bun.resolveSync("@teyik0/furin-electrobun/dev", cwd);
26
+ } catch (cause) {
27
+ throw new Error("Install @teyik0/furin-electrobun to run this desktop configuration.", {
28
+ cause,
29
+ });
30
+ }
31
+ const addon: { runDesktopDevelopment: (cwd: string, openBrowser: boolean) => Promise<void> } =
32
+ await import(pathToFileURL(entry).href);
33
+ await addon.runDesktopDevelopment(cwd, !values.desktop);
34
+ return;
35
+ }
36
+ if (values.desktop) {
37
+ throw new Error("Add desktop to furin.config.ts before using --desktop.");
38
+ }
39
+ const port = values.port ?? process.env.PORT;
40
+ if (port !== undefined && (!PORT.test(port) || Number(port) > 65_535)) {
41
+ throw new Error("Invalid development port.");
42
+ }
43
+ let webDevelopment = "";
44
+ try {
45
+ webDevelopment = Bun.resolveSync("@teyik0/furin-electrobun/web-dev", cwd);
46
+ } catch {
47
+ // Web-only apps can run without the optional desktop integration installed.
48
+ }
49
+ const child = Bun.spawn(
50
+ [
51
+ process.execPath,
52
+ "--hot",
53
+ join(import.meta.dir, "dev-worker.ts"),
54
+ resolve(config.rootDir, config.serverEntry ?? "src/server.ts"),
55
+ port ?? "",
56
+ webDevelopment,
57
+ ],
58
+ {
59
+ cwd: config.rootDir,
60
+ stdin: "inherit",
61
+ stdout: "inherit",
62
+ stderr: "inherit",
63
+ ipc: () => undefined,
64
+ }
65
+ );
66
+ let deadline: ReturnType<typeof setTimeout> | undefined;
67
+ const stop = () => {
68
+ if (deadline) {
69
+ return;
70
+ }
71
+ child.send("stop");
72
+ // Bound cancellation even if consumer code prevents the worker's own timer.
73
+ deadline = setTimeout(() => child.kill("SIGKILL"), 6000);
74
+ };
75
+ process.on("SIGINT", stop);
76
+ process.on("SIGTERM", stop);
77
+ try {
78
+ const code = await child.exited;
79
+ if (code !== 0) {
80
+ throw new Error(`Development server exited (${code}).`);
81
+ }
82
+ } finally {
83
+ clearTimeout(deadline);
84
+ process.off("SIGINT", stop);
85
+ process.off("SIGTERM", stop);
86
+ if (child.exitCode === null && child.signalCode === null) {
87
+ child.kill("SIGKILL");
88
+ }
89
+ await child.exited;
90
+ }
91
+ }
package/src/cli/index.ts CHANGED
@@ -6,6 +6,7 @@ import { buildApp, generateRouteTypes } from "../build/index.ts";
6
6
  import { BUILD_TARGETS, type FurinTarget } from "../config.ts";
7
7
  import { normalizePrefix } from "../server/instance.ts";
8
8
  import { loadCliConfig } from "./config.ts";
9
+ import { runDevelopment } from "./dev.ts";
9
10
  import { normalizeStaticPreviewBasePath, startStaticPreview } from "./preview.ts";
10
11
 
11
12
  const argv = process.argv.slice(2);
@@ -71,7 +72,9 @@ function extractCompileFlag(args: string[]): {
71
72
  return { compileFlag, parseableArgs };
72
73
  }
73
74
 
74
- if (command === "preview") {
75
+ if (command === "dev") {
76
+ await runDevelopment(process.cwd(), argv.slice(1));
77
+ } else if (command === "preview") {
75
78
  let rawValues: ReturnType<typeof parseArgs>["values"];
76
79
  try {
77
80
  rawValues = parseArgs({
@@ -120,6 +123,8 @@ if (command === "preview") {
120
123
  options: {
121
124
  analyze: { type: "boolean" },
122
125
  config: { type: "string" },
126
+ external: { type: "string", multiple: true },
127
+ output: { type: "string" },
123
128
  pagesDir: { type: "string" },
124
129
  prefix: { type: "string" },
125
130
  target: { type: "string" },
@@ -132,6 +137,8 @@ if (command === "preview") {
132
137
 
133
138
  const values = rawValues as {
134
139
  analyze?: boolean;
140
+ external?: string[];
141
+ output?: string;
135
142
  target?: string;
136
143
  pagesDir?: string;
137
144
  prefix?: string;
@@ -166,10 +173,22 @@ if (command === "preview") {
166
173
  const targets = Array.isArray(target) || target === "all" ? target : [target];
167
174
  const targetLabel = targets === "all" ? targets : targets.map(targetName).join(", ");
168
175
 
176
+ const output = values.output ?? config.bun?.output;
177
+ if (output !== undefined && output !== "app" && output !== "server") {
178
+ bail(`Invalid Bun output "${output}". Valid: app, server`);
179
+ }
180
+ if (values.output !== undefined && targetLabel !== "bun") {
181
+ bail("--output requires --target bun");
182
+ }
183
+ if (values.external !== undefined && targetLabel !== "bun") {
184
+ bail("--external requires --target bun");
185
+ }
186
+
169
187
  log(`Building Furin for ${targetLabel}…`);
170
188
 
171
189
  const result = await buildApp({
172
190
  analyze: values.analyze,
191
+ bun: output === undefined ? undefined : { output },
173
192
  // --pagesDir/--prefix build a single explicit app; otherwise fall back to
174
193
  // the config's `apps` list (then to server.ts scanning inside buildApp).
175
194
  // normalizePrefix here so a bad --prefix fails before buildApp starts
@@ -188,6 +207,7 @@ if (command === "preview") {
188
207
  optimizeImports: config.optimizeImports,
189
208
  pagesDir: undefined,
190
209
  plugins: config.plugins,
210
+ serverExternalPackages: values.external,
191
211
  preload: config.preload,
192
212
  reactCompiler: config.reactCompiler,
193
213
  rootDir: config.rootDir,
@@ -230,6 +250,7 @@ if (command === "preview") {
230
250
  `Furin CLI
231
251
 
232
252
  USAGE
253
+ furin dev [--web | --desktop] [--port number]
233
254
  furin build [options]
234
255
  furin preview [options]
235
256
  furin typegen [options]
@@ -241,6 +262,8 @@ BUILD OPTIONS
241
262
  --prefix Mount prefix for the built app (e.g. /admin) — pairs with --pagesDir
242
263
  --config Config file path
243
264
  --compile server | embed Compile to binary: "server" keeps client on disk, "embed" is self-contained
265
+ --output app | server Bun only: inert app.js or listening server.js (default: server)
266
+ --external Bun only: package to exclude from server/RSC bundles (repeatable)
244
267
  --analyze Write complete bundle metafiles to .furin/build/analysis
245
268
 
246
269
  TYPEGEN OPTIONS