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

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.
@@ -62,10 +62,16 @@ const timer = setTimeout(() => {
62
62
  }, 30_000);
63
63
  try {
64
64
  if (integration) {
65
- const addon: { createWebDevelopment: () => WebDevelopment } = await import(
66
- pathToFileURL(integration).href
67
- );
68
- web = addon.createWebDevelopment();
65
+ const addon: {
66
+ createDevelopment?: () => WebDevelopment;
67
+ createWebDevelopment?: () => WebDevelopment;
68
+ } = await import(pathToFileURL(integration).href);
69
+ // Desktop integrations export createDevelopment; web-dev keeps its published name.
70
+ const create = addon.createDevelopment ?? addon.createWebDevelopment;
71
+ if (!create) {
72
+ throw new Error("Invalid development integration.");
73
+ }
74
+ web = create();
69
75
  }
70
76
  const { listen } = BunAdapter;
71
77
  if (!listen) {
package/src/cli/dev.ts CHANGED
@@ -5,6 +5,36 @@ import { loadCliConfig } from "./config";
5
5
 
6
6
  const PORT = /^\d+$/;
7
7
 
8
+ /** The hot worker serves the backend; the desktop integration owns the native shell. */
9
+ async function desktopIntegration(cwd: string, openBrowser: boolean) {
10
+ let entry: string;
11
+ let integration: string;
12
+ try {
13
+ entry = Bun.resolveSync("@teyik0/furin-electrobun/dev", cwd);
14
+ integration = Bun.resolveSync("@teyik0/furin-electrobun/desktop-dev", cwd);
15
+ } catch (cause) {
16
+ throw new Error("Install @teyik0/furin-electrobun to run this desktop configuration.", {
17
+ cause,
18
+ });
19
+ }
20
+ const addon: {
21
+ prepareDesktopDevelopment: (
22
+ cwd: string,
23
+ openBrowser: boolean
24
+ ) => Promise<{ [name: string]: string }>;
25
+ } = await import(pathToFileURL(entry).href);
26
+ return { integration, env: await addon.prepareDesktopDevelopment(cwd, openBrowser) };
27
+ }
28
+
29
+ function webIntegration(cwd: string): { integration: string; env: { [name: string]: string } } {
30
+ try {
31
+ return { integration: Bun.resolveSync("@teyik0/furin-electrobun/web-dev", cwd), env: {} };
32
+ } catch {
33
+ // Web-only apps can run without the optional desktop integration installed.
34
+ return { integration: "", env: {} };
35
+ }
36
+ }
37
+
8
38
  export async function runDevelopment(cwd: string, args: string[]): Promise<void> {
9
39
  const { values } = parseArgs({
10
40
  args: args.filter((arg) => arg !== "--"),
@@ -16,36 +46,20 @@ export async function runDevelopment(cwd: string, args: string[]): Promise<void>
16
46
  }
17
47
  const config = await loadCliConfig(cwd);
18
48
  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) {
49
+ if (values.desktop && !hasDesktop) {
37
50
  throw new Error("Add desktop to furin.config.ts before using --desktop.");
38
51
  }
39
- const port = values.port ?? process.env.PORT;
52
+ const desktop = hasDesktop && !values.web;
53
+ if (desktop && values.port !== undefined) {
54
+ throw new Error("--port is only available with --web.");
55
+ }
56
+ const port = desktop ? undefined : (values.port ?? process.env.PORT);
40
57
  if (port !== undefined && (!PORT.test(port) || Number(port) > 65_535)) {
41
58
  throw new Error("Invalid development port.");
42
59
  }
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
- }
60
+ const { integration, env } = desktop
61
+ ? await desktopIntegration(cwd, !values.desktop)
62
+ : webIntegration(cwd);
49
63
  const child = Bun.spawn(
50
64
  [
51
65
  process.execPath,
@@ -53,10 +67,11 @@ export async function runDevelopment(cwd: string, args: string[]): Promise<void>
53
67
  join(import.meta.dir, "dev-worker.ts"),
54
68
  resolve(config.rootDir, config.serverEntry ?? "src/server.ts"),
55
69
  port ?? "",
56
- webDevelopment,
70
+ integration,
57
71
  ],
58
72
  {
59
73
  cwd: config.rootDir,
74
+ env: { ...process.env, ...env },
60
75
  stdin: "inherit",
61
76
  stdout: "inherit",
62
77
  stderr: "inherit",
@@ -160,16 +160,15 @@ function LinkInteractive<To extends RouteTo>({
160
160
  if (target !== null) {
161
161
  prefetch(target, { staleTime: effectiveStaleTime });
162
162
  }
163
- // react-doctor-disable-next-line react-doctor/exhaustive-deps
164
- }, [prefetch, logicalHref, effectiveStaleTime, router.basePath]);
163
+ }, [prefetch, effectiveStaleTime, router.basePath]);
165
164
 
166
- // "render": preload immediately on mount
165
+ // "render": preload immediately on mount, and again when the target changes.
167
166
  useEffect(() => {
168
167
  if (effectivePreload === "render") {
169
168
  triggerPrefetch();
170
169
  }
171
170
  // react-doctor-disable-next-line react-doctor/exhaustive-deps
172
- }, [effectivePreload, triggerPrefetch]);
171
+ }, [effectivePreload, triggerPrefetch, logicalHref]);
173
172
 
174
173
  // "viewport": preload when link enters viewport
175
174
  useEffect(() => {
@@ -188,7 +187,7 @@ function LinkInteractive<To extends RouteTo>({
188
187
  observer.observe(anchorRef.current);
189
188
  return () => observer.disconnect();
190
189
  // react-doctor-disable-next-line react-doctor/exhaustive-deps
191
- }, [effectivePreload, triggerPrefetch]);
190
+ }, [effectivePreload, triggerPrefetch, logicalHref]);
192
191
 
193
192
  // Clear any pending intent prefetch timer on unmount to avoid leaking
194
193
  // setTimeout callbacks between test cases (or across re-renders).
@@ -232,7 +231,7 @@ function LinkInteractive<To extends RouteTo>({
232
231
  // When there is no RouterProvider, fall back to a full-page navigation so
233
232
  // the link is still functional (e.g. in storybooks or third-party pages).
234
233
  if (typeof window !== "undefined" && router.navigate === CLIENT_FALLBACK_ROUTER.navigate) {
235
- window.location.href = href;
234
+ window.location.assign(href);
236
235
  return;
237
236
  }
238
237
  // navigate() expects the logical href (no basePath prefix).
@@ -261,22 +260,22 @@ function LinkInteractive<To extends RouteTo>({
261
260
  }
262
261
  };
263
262
 
264
- return createElement(
265
- "a",
266
- {
267
- "data-furin-link": true,
268
- href,
269
- onClick: handleClick,
270
- onFocus: handleFocus,
271
- onMouseEnter: handleMouseEnter,
272
- onMouseLeave: handleMouseLeave,
273
- ref: anchorRef,
274
- ...(isActive ? { "data-status": "active" } : {}),
275
- ...anchorProps,
276
- ...extraProps,
277
- ...(disabled ? { "aria-disabled": true } : {}),
278
- },
279
- resolvedChildren
263
+ return (
264
+ <a
265
+ data-furin-link
266
+ href={href}
267
+ onClick={handleClick}
268
+ onFocus={handleFocus}
269
+ onMouseEnter={handleMouseEnter}
270
+ onMouseLeave={handleMouseLeave}
271
+ ref={anchorRef}
272
+ {...(isActive ? { "data-status": "active" } : {})}
273
+ {...anchorProps}
274
+ {...extraProps}
275
+ {...(disabled ? { "aria-disabled": true } : {})}
276
+ >
277
+ {resolvedChildren}
278
+ </a>
280
279
  );
281
280
  }
282
281
 
@@ -81,9 +81,10 @@ export function useRouterStore(): RouterStore {
81
81
  }
82
82
 
83
83
  export function useTypedNavigation(context: StableRouter): Pick<Router, "navigate" | "prefetch"> {
84
+ const { navigate: navigateHref, prefetch: prefetchHref, searchRoutes } = context;
84
85
  const navigate: RouterNavigate = useCallback(
85
86
  (next: string | (RuntimeRouteTarget & NavigationOptions), opts?: NavigationOptions) => {
86
- const href = typeof next === "string" ? next : resolveRouteTarget(next, context.searchRoutes);
87
+ const href = typeof next === "string" ? next : resolveRouteTarget(next, searchRoutes);
87
88
  const policy = navigationHrefPolicy(
88
89
  href,
89
90
  typeof window === "undefined" ? undefined : window.location.origin
@@ -96,22 +97,22 @@ export function useTypedNavigation(context: StableRouter): Pick<Router, "navigat
96
97
  return Promise.resolve();
97
98
  }
98
99
  if (typeof next === "string") {
99
- return context.navigate(href, opts);
100
+ return navigateHref(href, opts);
100
101
  }
101
102
  const options =
102
103
  next.replace === undefined && next.resetScroll === undefined
103
104
  ? undefined
104
105
  : { replace: next.replace, resetScroll: next.resetScroll };
105
- return context.navigate(href, options);
106
+ return navigateHref(href, options);
106
107
  },
107
- [context.navigate, context.searchRoutes]
108
+ [navigateHref, searchRoutes]
108
109
  );
109
110
  const prefetch: Prefetch = useCallback(
110
111
  (
111
112
  next: string | (RuntimeRouteTarget & { staleTime?: number }),
112
113
  opts?: { staleTime?: number }
113
114
  ) => {
114
- const href = typeof next === "string" ? next : resolveRouteTarget(next, context.searchRoutes);
115
+ const href = typeof next === "string" ? next : resolveRouteTarget(next, searchRoutes);
115
116
  const policy = navigationHrefPolicy(
116
117
  href,
117
118
  typeof window === "undefined" ? undefined : window.location.origin
@@ -119,9 +120,9 @@ export function useTypedNavigation(context: StableRouter): Pick<Router, "navigat
119
120
  if (policy !== "internal") {
120
121
  return;
121
122
  }
122
- context.prefetch(href, typeof next === "string" ? opts : { staleTime: next.staleTime });
123
+ prefetchHref(href, typeof next === "string" ? opts : { staleTime: next.staleTime });
123
124
  },
124
- [context.prefetch, context.searchRoutes]
125
+ [prefetchHref, searchRoutes]
125
126
  );
126
127
  return { navigate, prefetch };
127
128
  }
@@ -127,6 +127,7 @@ export function RouterProvider({
127
127
  const syncResponse = useRef<
128
128
  ((response: Response | undefined, optimistic: boolean) => void) | undefined
129
129
  >(undefined);
130
+ // biome-ignore lint/nursery/useReactCompiler: the runtime reads these refs only from its callbacks, after render.
130
131
  const [optimisticRuntime] = useState(() =>
131
132
  createOptimisticRuntime({
132
133
  basePath,
@@ -366,6 +367,8 @@ export function RouterProvider({
366
367
  });
367
368
  useSyncStream({ autoRefresh, basePath, controller, invalidationRefresh, queries, syncPath });
368
369
 
370
+ // The query store and resolved deferred promises are mutable sources outside
371
+ // React; queryRevision and deferredRevision are the keys that invalidate them.
369
372
  const queryData = useMemo(
370
373
  () =>
371
374
  projectDeferredQueryData(
@@ -380,8 +383,10 @@ export function RouterProvider({
380
383
  }
381
384
  return queries.snapshot(seed.url).data;
382
385
  },
386
+ // biome-ignore lint/nursery/useReactCompiler: deferredRevision invalidates this read.
383
387
  resolvedQueries.current
384
388
  ),
389
+ // biome-ignore lint/nursery/useReactCompiler: revisions intentionally key reads of external mutable sources.
385
390
  [queries, state.data, state.querySeeds, queryRevision, deferredRevision]
386
391
  );
387
392
  const renderedData = optimisticRuntime.project(queryData, currentHref);
@@ -1,6 +1,5 @@
1
1
  // biome-ignore-all lint/performance/noBarrelFile: intentional barrel for public API
2
2
 
3
- export { streamToString } from "./assemble.ts";
4
3
  export { renderToHTML } from "./buffered-render.ts";
5
4
  export { buildErrorElement } from "./element.tsx";
6
5
  export { handleISR } from "./isr.ts";
@@ -1,4 +1,4 @@
1
- import type { HeadOptions, MetaDescriptor } from "../../client.ts";
1
+ import type { MetaDescriptor } from "../../client.ts";
2
2
 
3
3
  export function extractTitle(meta?: MetaDescriptor[]): string | undefined {
4
4
  if (!meta) {
@@ -11,15 +11,6 @@ export function extractTitle(meta?: MetaDescriptor[]): string | undefined {
11
11
  }
12
12
  }
13
13
 
14
- export function isMetaTag(entry: MetaDescriptor): boolean {
15
- return !(
16
- "title" in entry ||
17
- "charSet" in entry ||
18
- "script:ld+json" in entry ||
19
- "tagName" in entry
20
- );
21
- }
22
-
23
14
  export function escapeHtml(str: string): string {
24
15
  return str
25
16
  .replace(/&/g, "&amp;")
@@ -37,86 +28,6 @@ export function safeJson(value: unknown): string {
37
28
  .replace(/\u2029/g, "\\u2029");
38
29
  }
39
30
 
40
- export function renderAttrs(obj: Record<string, string | undefined>): string {
41
- const parts: string[] = [];
42
- for (const [k, v] of Object.entries(obj)) {
43
- if (v !== undefined) {
44
- parts.push(`${k}="${escapeHtml(String(v))}"`);
45
- }
46
- }
47
- return parts.join(" ");
48
- }
49
-
50
- // ---------------------------------------------------------------------------
51
- // Head injection helpers
52
- // ---------------------------------------------------------------------------
53
-
54
- export function buildMetaParts(meta: MetaDescriptor[]): string[] {
55
- const parts: string[] = [];
56
- const title = extractTitle(meta);
57
- if (title) {
58
- parts.push(`<title>${escapeHtml(title)}</title>`);
59
- }
60
- for (const m of meta) {
61
- if (isMetaTag(m)) {
62
- parts.push(`<meta ${renderAttrs(m as Record<string, string>)} />`);
63
- }
64
- if ("script:ld+json" in m) {
65
- parts.push(`<script type="application/ld+json">${safeJson(m["script:ld+json"])}</script>`);
66
- }
67
- }
68
- return parts;
69
- }
70
-
71
- export function buildLinkParts(links: NonNullable<HeadOptions["links"]>): string[] {
72
- return links.map((link) => `<link ${renderAttrs(link)} />`);
73
- }
74
-
75
- export function buildScriptParts(scripts: NonNullable<HeadOptions["scripts"]>): string[] {
76
- return scripts.map((script) => {
77
- const { children, ...rest } = script;
78
- const attrs = renderAttrs(rest as Record<string, string | undefined>);
79
- if (children) {
80
- return `<script ${attrs}>${children}</script>`;
81
- }
82
- return `<script ${attrs}></script>`;
83
- });
84
- }
85
-
86
- export function buildStyleParts(styles: NonNullable<HeadOptions["styles"]>): string[] {
87
- return styles.map((style) => {
88
- const typeAttr = style.type ? ` type="${escapeHtml(style.type)}"` : "";
89
- return `<style${typeAttr}>${style.children}</style>`;
90
- });
91
- }
92
-
93
- /**
94
- * Builds the string to inject into the <!--ssr-head--> placeholder.
95
- * Handles title, meta tags, links, inline scripts, and inline styles from
96
- * the page's `head()` function. CSS is handled by Bun (imported in user files).
97
- */
98
- export function buildHeadInjection(headData: HeadOptions | undefined): string {
99
- const parts: string[] = [];
100
-
101
- if (headData?.meta) {
102
- parts.push(...buildMetaParts(headData.meta));
103
- }
104
-
105
- if (headData?.links) {
106
- parts.push(...buildLinkParts(headData.links));
107
- }
108
-
109
- if (headData?.scripts) {
110
- parts.push(...buildScriptParts(headData.scripts));
111
- }
112
-
113
- if (headData?.styles) {
114
- parts.push(...buildStyleParts(headData.styles));
115
- }
116
-
117
- return parts.length > 0 ? `\n ${parts.join("\n ")}\n` : "";
118
- }
119
-
120
31
  export function generateIndexHtml(): string {
121
32
  return `<!DOCTYPE html>
122
33
  <html lang="en">
@@ -26,7 +26,7 @@ export class FurinNotFoundError extends Error {
26
26
  }
27
27
  }
28
28
 
29
- export function notFound(options: NotFoundOptions | undefined): never {
29
+ export function notFound(options?: NotFoundOptions): never {
30
30
  throw new FurinNotFoundError(options);
31
31
  }
32
32