@teyik0/furin 0.1.0-alpha.13 → 0.1.0-alpha.14

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 (58) hide show
  1. package/README.md +14 -232
  2. package/dist/await.d.ts +67 -0
  3. package/dist/build/index.js +2013 -191
  4. package/dist/cli/index.js +2007 -190
  5. package/dist/client.d.ts +33 -2
  6. package/dist/client.js +65 -1
  7. package/dist/deferred-ndjson.d.ts +32 -0
  8. package/dist/error.d.ts +14 -0
  9. package/dist/furin.d.ts +3 -0
  10. package/dist/furin.js +2684 -318
  11. package/dist/lang-detect.d.ts +5 -0
  12. package/dist/link.d.ts +1 -0
  13. package/dist/link.js +1453 -95
  14. package/dist/plugin/index.js +96 -25
  15. package/dist/plugin/transform-client.d.ts +2 -1
  16. package/dist/render/assemble.d.ts +32 -0
  17. package/dist/render/cache.d.ts +7 -0
  18. package/dist/render/element.d.ts +17 -1
  19. package/dist/render/index.d.ts +10 -1
  20. package/dist/render/index.ts +247 -44
  21. package/dist/render/loaders.d.ts +46 -3
  22. package/dist/render/shell.d.ts +16 -6
  23. package/dist/render/shell.ts +27 -12
  24. package/dist/router-provider.d.ts +86 -18
  25. package/dist/router.d.ts +63 -0
  26. package/dist/router.js +2768 -317
  27. package/dist/router.ts +543 -54
  28. package/dist/server-error.d.ts +12 -0
  29. package/dist/utils.d.ts +7 -0
  30. package/package.json +8 -7
  31. package/src/adapter/bun.ts +3 -3
  32. package/src/adapter/static.ts +73 -31
  33. package/src/await.tsx +175 -0
  34. package/src/build/client.ts +4 -8
  35. package/src/build/hydrate.ts +67 -1
  36. package/src/build/route-types.ts +5 -1
  37. package/src/build/scan-server.ts +6 -23
  38. package/src/client.ts +58 -1
  39. package/src/deferred-ndjson.ts +212 -0
  40. package/src/dev-page-plugin.ts +2 -0
  41. package/src/error.ts +18 -1
  42. package/src/furin.ts +12 -2
  43. package/src/lang-detect.ts +46 -0
  44. package/src/link.tsx +16 -3
  45. package/src/plugin/index.ts +7 -8
  46. package/src/plugin/transform-client.ts +108 -39
  47. package/src/render/assemble.ts +67 -0
  48. package/src/render/boundaries.tsx +23 -5
  49. package/src/render/cache.ts +7 -0
  50. package/src/render/default-screens.tsx +4 -11
  51. package/src/render/element.tsx +26 -3
  52. package/src/render/index.ts +247 -44
  53. package/src/render/loaders.ts +221 -18
  54. package/src/render/shell.ts +27 -12
  55. package/src/router-provider.tsx +414 -122
  56. package/src/router.ts +543 -54
  57. package/src/server-error.ts +47 -0
  58. package/src/utils.ts +31 -0
package/src/client.ts CHANGED
@@ -11,6 +11,9 @@ import type { Cookie, StatusMap } from "elysia";
11
11
  import type { AnySchema, HTTPHeaders, UnwrapSchema } from "elysia/types";
12
12
  import type { RequestLogger } from "evlog";
13
13
 
14
+ // biome-ignore lint/performance/noBarrelFile: client.ts is the canonical DX entry for furin/client consumers — not a barrel
15
+ export { Await, useAsyncError, useAsyncValue } from "./await.tsx";
16
+
14
17
  declare const UNSET: unique symbol;
15
18
  type Unset = typeof UNSET;
16
19
 
@@ -110,9 +113,12 @@ export interface HeadOptions {
110
113
  // Extracts the resolved return type from a loader function type.
111
114
  // Using ReturnType + Awaited here means TLoader is inferred as the whole function
112
115
  // first, and then we extract the data — so inference is order-independent.
116
+ // The `__isDeferred` key (DEFERRED_BRAND, see below) is stripped: a `defer()`
117
+ // return carries that runtime marker, but it must never surface as a
118
+ // component / head() prop — it is an internal implementation detail.
113
119
  type ExtractLoaderReturn<TLoader> = TLoader extends (...args: never[]) => unknown
114
120
  ? Awaited<ReturnType<TLoader>> extends object
115
- ? ToRecord<Awaited<ReturnType<TLoader>>>
121
+ ? ToRecord<Omit<Awaited<ReturnType<TLoader>>, "__isDeferred">>
116
122
  : {}
117
123
  : {};
118
124
 
@@ -276,3 +282,54 @@ export type InferProps<T> = T extends {
276
282
  : T extends Route<infer D, infer P, infer Q>
277
283
  ? D & { children: React.ReactNode } & ComponentProps<P, Q>
278
284
  : never;
285
+
286
+ // ── Deferred data ──────────────────────────────────────────────────────────────
287
+
288
+ /**
289
+ * Brand key that marks an object as deferred. Using a `const` string avoids
290
+ * a `unique symbol` that would complicate cross-module inference.
291
+ */
292
+ const DEFERRED_BRAND = "__isDeferred" as const;
293
+
294
+ /**
295
+ * A loader return value that contains a mix of synchronous scalar fields and
296
+ * lazy `Promise<T>` fields. Scalar fields are serialised into the initial HTML
297
+ * shell; Promise fields are streamed as late `<script>` resolution chunks.
298
+ *
299
+ * @example
300
+ * loader: () => defer({
301
+ * title: "My Board", // synchronous — available immediately
302
+ * stats: fetchStats(), // Promise — streamed when it resolves
303
+ * })
304
+ */
305
+ export type DeferredData<T extends Record<string, unknown>> = T & {
306
+ readonly [DEFERRED_BRAND]: true;
307
+ };
308
+
309
+ /**
310
+ * Wraps loader data so that Promise-valued fields are streamed lazily while
311
+ * scalar fields are embedded in the initial HTML shell immediately.
312
+ *
313
+ * Use inside a page loader only (not in route / layout loaders — v1 restriction).
314
+ */
315
+ export function defer<T extends Record<string, unknown>>(data: T): DeferredData<T> {
316
+ if (Object.hasOwn(data, DEFERRED_BRAND)) {
317
+ throw new Error(
318
+ `[furin] defer() received an object with a reserved key "${DEFERRED_BRAND}". Rename this field to avoid conflicts with the deferred-data runtime.`
319
+ );
320
+ }
321
+ return { ...data, [DEFERRED_BRAND]: true } as DeferredData<T>;
322
+ }
323
+
324
+ /**
325
+ * Type guard for DeferredData. Used by the render pipeline to distinguish a
326
+ * plain loader return from a deferred one.
327
+ */
328
+ export function isDeferred(v: unknown): v is DeferredData<Record<string, unknown>> {
329
+ return (
330
+ typeof v === "object" &&
331
+ v !== null &&
332
+ Object.hasOwn(v, DEFERRED_BRAND) &&
333
+ (v as Record<typeof DEFERRED_BRAND, unknown>)[DEFERRED_BRAND] === true
334
+ );
335
+ }
@@ -0,0 +1,212 @@
1
+ import type { SerovalNode } from "seroval";
2
+ import { fromCrossJSON } from "seroval";
3
+
4
+ /**
5
+ * Result returned by `parseDeferredNdjson`.
6
+ */
7
+ export interface DeferredNdjsonResult {
8
+ /**
9
+ * Deferred promises keyed by their field name. Each Promise resolves (or
10
+ * rejects) once the corresponding data is available. In the SSR case the
11
+ * promises are already settled (serialised by `toCrossJSONAsync`). For
12
+ * streaming endpoints they will settle as the server flushes resolution
13
+ * chunks.
14
+ */
15
+ deferredPromises: Record<string, Promise<unknown>>;
16
+ /** Scalar/sync values from the loader — available immediately. */
17
+ syncData: Record<string, unknown>;
18
+ }
19
+
20
+ function makeAbortError(reason: unknown): Error {
21
+ const message =
22
+ reason instanceof Error ? reason.message || "The operation was aborted." : "aborted";
23
+ const err = new Error(message);
24
+ err.name = "AbortError";
25
+ return err;
26
+ }
27
+
28
+ /**
29
+ * Parses an NDJSON stream produced by `/_furin/data`.
30
+ *
31
+ * Protocol (v1 — single-line, all-resolved):
32
+ * Line 0 — `JSON.stringify(await toCrossJSONAsync(loaderData))`
33
+ *
34
+ * The CrossJSON node is deserialised with `fromCrossJSON`. Values that are
35
+ * Promises (seroval type 12) land in `deferredPromises`; everything else
36
+ * lands in `syncData`.
37
+ *
38
+ * @param stream - A `ReadableStream<Uint8Array>` from `fetch().body`.
39
+ * @param signal - AbortSignal that, when aborted, cancels the reader and
40
+ * rejects every still-pending deferred promise with an
41
+ * `AbortError`. Pass `undefined` to opt out (no implicit
42
+ * default — see CLAUDE.md).
43
+ */
44
+ export async function parseDeferredNdjson(
45
+ stream: ReadableStream<Uint8Array>,
46
+ signal: AbortSignal | undefined
47
+ ): Promise<DeferredNdjsonResult> {
48
+ const reader = stream.getReader();
49
+ const decoder = new TextDecoder();
50
+ let buffer = "";
51
+
52
+ async function readLine(): Promise<string | undefined> {
53
+ for (;;) {
54
+ // react-doctor-disable-next-line react-doctor/js-set-map-lookups
55
+ const newlineIndex = buffer.indexOf("\n");
56
+ if (newlineIndex >= 0) {
57
+ const line = buffer.slice(0, newlineIndex).trim();
58
+ buffer = buffer.slice(newlineIndex + 1);
59
+ if (line.length > 0) {
60
+ return line;
61
+ }
62
+ continue;
63
+ }
64
+
65
+ const { done, value } = await reader.read();
66
+ if (done) {
67
+ buffer += decoder.decode();
68
+ const line = buffer.trim();
69
+ buffer = "";
70
+ return line.length > 0 ? line : undefined;
71
+ }
72
+ buffer += decoder.decode(value, { stream: true });
73
+ }
74
+ }
75
+
76
+ const firstLine = await readLine();
77
+ if (!firstLine) {
78
+ try {
79
+ reader.releaseLock();
80
+ } catch {
81
+ /* already released */
82
+ }
83
+ return { syncData: {}, deferredPromises: {} };
84
+ }
85
+
86
+ const node = JSON.parse(firstLine) as SerovalNode;
87
+ const deserialized = fromCrossJSON(node, {}) as Record<string, unknown>;
88
+
89
+ const syncData: Record<string, unknown> = {};
90
+ const deferredPromises: Record<string, Promise<unknown>> = {};
91
+ const resolvers: Record<
92
+ string,
93
+ { reject: (reason: unknown) => void; resolve: (value: unknown) => void }
94
+ > = {};
95
+ const deferredKeys = Array.isArray(deserialized.__furinDeferredKeys)
96
+ ? (deserialized.__furinDeferredKeys.filter((key) => typeof key === "string") as string[])
97
+ : [];
98
+
99
+ for (const [key, value] of Object.entries(deserialized)) {
100
+ if (key === "__furinDeferredKeys") {
101
+ continue;
102
+ }
103
+ if (value instanceof Promise) {
104
+ deferredPromises[key] = value;
105
+ } else {
106
+ syncData[key] = value;
107
+ }
108
+ }
109
+
110
+ for (const key of deferredKeys) {
111
+ if (!(key in deferredPromises)) {
112
+ deferredPromises[key] = new Promise((resolve, reject) => {
113
+ resolvers[key] = { resolve, reject };
114
+ });
115
+ }
116
+ }
117
+
118
+ if (deferredKeys.length === 0) {
119
+ try {
120
+ reader.releaseLock();
121
+ } catch {
122
+ /* already released */
123
+ }
124
+ return { syncData, deferredPromises };
125
+ }
126
+
127
+ // Reject every still-pending resolver and cancel the underlying reader. Used
128
+ // both by the AbortSignal listener and by the readDeferredLines error path.
129
+ const rejectAllPending = (reason: unknown): void => {
130
+ for (const key of Object.keys(resolvers)) {
131
+ resolvers[key]?.reject(reason);
132
+ delete resolvers[key];
133
+ }
134
+ reader.cancel(reason).catch(() => {
135
+ /* reader may already be closed */
136
+ });
137
+ };
138
+
139
+ if (signal !== undefined) {
140
+ if (signal.aborted) {
141
+ rejectAllPending(makeAbortError(signal.reason));
142
+ return { syncData, deferredPromises };
143
+ }
144
+ signal.addEventListener(
145
+ "abort",
146
+ () => {
147
+ rejectAllPending(makeAbortError(signal.reason));
148
+ },
149
+ { once: true }
150
+ );
151
+ }
152
+
153
+ readDeferredLines(readLine, resolvers)
154
+ .then(() => {
155
+ // Stream ended normally. Any resolver that never received its chunk is
156
+ // dropped without a settle event — surface a rejection so consumers
157
+ // (e.g. <Await>) don't hang forever.
158
+ for (const key of Object.keys(resolvers)) {
159
+ const err = new Error(`[furin] deferred stream closed before "${key}" was resolved`);
160
+ resolvers[key]?.reject(err);
161
+ delete resolvers[key];
162
+ }
163
+ })
164
+ .catch((err) => {
165
+ for (const resolver of Object.values(resolvers)) {
166
+ resolver.reject(err);
167
+ }
168
+ })
169
+ .finally(() => {
170
+ try {
171
+ reader.releaseLock();
172
+ } catch {
173
+ /* already released via reader.cancel() in the abort path */
174
+ }
175
+ });
176
+
177
+ return { syncData, deferredPromises };
178
+ }
179
+
180
+ async function readDeferredLines(
181
+ readLine: () => Promise<string | undefined>,
182
+ resolvers: Record<
183
+ string,
184
+ { reject: (reason: unknown) => void; resolve: (value: unknown) => void }
185
+ >
186
+ ): Promise<void> {
187
+ for (;;) {
188
+ const line = await readLine();
189
+ if (!line) {
190
+ return;
191
+ }
192
+ const entry = JSON.parse(line) as {
193
+ action?: "reject" | "resolve";
194
+ key?: string;
195
+ value?: SerovalNode;
196
+ };
197
+ if (typeof entry.key !== "string" || !entry.value) {
198
+ continue;
199
+ }
200
+ const resolver = resolvers[entry.key];
201
+ if (!resolver) {
202
+ continue;
203
+ }
204
+ const value = fromCrossJSON(entry.value, {});
205
+ if (entry.action === "reject") {
206
+ resolver.reject(value);
207
+ } else {
208
+ resolver.resolve(value);
209
+ }
210
+ delete resolvers[entry.key];
211
+ }
212
+ }
@@ -119,6 +119,7 @@ function escapeRegExp(s: string): string {
119
119
  export function rewriteSingletonImports(source: string): string {
120
120
  let result = source;
121
121
  for (const [pkg, absPath] of SINGLETON_PATHS) {
122
+ // react-doctor-disable-next-line react-doctor/js-hoist-regexp
122
123
  const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(pkg)}["']`, "g");
123
124
  result = result.replace(re, (_, g1: string) => `${g1}"${absPath}"`);
124
125
  }
@@ -280,6 +281,7 @@ export function rewriteBareImports(source: string, transpiled: string, dir: stri
280
281
  // that both import and re-export from the same package. The regex only
281
282
  // matches when the specifier is preceded by `from` or `import` so string
282
283
  // literals in non-import positions are left untouched.
284
+ // react-doctor-disable-next-line react-doctor/js-hoist-regexp
283
285
  const re = new RegExp(`((?:from|import(?:\\s+type)?)\\s+)["']${escapeRegExp(spec)}["']`, "g");
284
286
  result = result.replace(re, (_, g1: string) => `${g1}"${resolved}"`);
285
287
  }
package/src/error.ts CHANGED
@@ -11,6 +11,20 @@ export interface ErrorProps {
11
11
  * without leaking stack traces to the browser.
12
12
  */
13
13
  digest: string;
14
+ /**
15
+ * HTTP status associated with the error.
16
+ * - For thrown `Response` objects with a 4xx/5xx status: the response's
17
+ * status (e.g. 401, 403, 404, 500).
18
+ * - For all other errors (thrown `Error`, non-Error throws, shell-render
19
+ * crashes): always `500`.
20
+ *
21
+ * Always present so consumers never need a `?? 500` fallback. Note that
22
+ * `prepared.status` is honoured ONLY for loader-time errors. If a Suspense
23
+ * boundary throws AFTER the SSR shell has flushed (i.e. during streaming),
24
+ * the HTTP status cannot be changed and the user-visible status here may
25
+ * differ from the actual response code.
26
+ */
27
+ status: number;
14
28
  };
15
29
  /**
16
30
  * Clears the nearest FurinErrorBoundary's error state, remounting its
@@ -25,7 +39,10 @@ export type ErrorComponent = FC<ErrorProps>;
25
39
 
26
40
  export function getPublicErrorMessage(error: Error | unknown): string {
27
41
  const branded = error as { __furinBrand?: string } | undefined;
28
- if (branded?.__furinBrand === "FURIN_NOT_FOUND") {
42
+ if (
43
+ branded?.__furinBrand === "FURIN_NOT_FOUND" ||
44
+ branded?.__furinBrand === "FURIN_SERVER_ERROR"
45
+ ) {
29
46
  return (error as Error).message;
30
47
  }
31
48
  return "Something went wrong";
package/src/furin.ts CHANGED
@@ -15,7 +15,7 @@ import {
15
15
  } from "./render/cache.ts";
16
16
  import { renderRootNotFound, warmSSGCache } from "./render/index.ts";
17
17
  import { setProductionTemplateContent, setProductionTemplatePath } from "./render/template.ts";
18
- import { createRoutePlugin, loadProdRoutes } from "./router.ts";
18
+ import { createDataEndpoint, createRoutePlugin, loadProdRoutes } from "./router.ts";
19
19
  import { IS_DEV } from "./runtime-env.ts";
20
20
 
21
21
  function resolveClientDirFromArgv(): string {
@@ -183,8 +183,13 @@ export async function furin({
183
183
  "/_client/**",
184
184
  "/public/**",
185
185
  "/favicon.ico",
186
- "/_furin/!(ingest)",
187
186
  "/_bun_hmr_entry/**",
187
+ // Note: /_furin/data is logged with the *logical* path rewritten by
188
+ // createDataEndpoint via useLogger().set({ path }), so SPA navigations
189
+ // appear as "GET /board/123 200" — same shape as a normal SSR nav.
190
+ // /_furin/ingest is kept loggable so browser-side events show up.
191
+ // evlog's `matchesPattern` only supports `*`, `**`, `?` — extglob
192
+ // like `!(...)` matches nothing, so don't add patterns relying on it.
188
193
  ...(userExclude ?? []),
189
194
  ],
190
195
  })
@@ -277,6 +282,7 @@ export async function furin({
277
282
  : () => new Response(null, { status: 404 })
278
283
  )
279
284
  .use(createDevInspectorPlugin())
285
+ .use(createDataEndpoint(routes))
280
286
  .use((app) => {
281
287
  for (const route of routes) {
282
288
  app.use(createRoutePlugin(route, root));
@@ -363,6 +369,7 @@ export async function furin({
363
369
  return app;
364
370
  })()
365
371
  )
372
+ .use(createDataEndpoint(routes))
366
373
  .use((app) => {
367
374
  for (const route of routes) {
368
375
  app.use(createRoutePlugin(route, root, prodBuildId));
@@ -374,6 +381,9 @@ export async function furin({
374
381
 
375
382
  // ── Public API re-export ──────────────────────────────────────────────────────
376
383
  // biome-ignore-start lint/performance/noBarrelFile: intentional — furin.ts is the public package entry
384
+ export { Await, useAsyncError, useAsyncValue } from "./await.tsx";
385
+ export type { DeferredData } from "./client.ts";
386
+ export { defer, isDeferred } from "./client.ts";
377
387
  export type { ErrorComponent, ErrorProps } from "./error.ts";
378
388
  export type {
379
389
  NotFoundComponent,
@@ -0,0 +1,46 @@
1
+ import type { SourceLang } from "yuku-parser";
2
+
3
+ export function detectLangFromPath(filePath: string): SourceLang {
4
+ if (filePath.endsWith(".d.ts")) {
5
+ return "dts";
6
+ }
7
+ const ext = filePath.split(".").pop()?.toLowerCase();
8
+ switch (ext) {
9
+ case "ts":
10
+ return "ts";
11
+ case "tsx":
12
+ return "tsx";
13
+ case "jsx":
14
+ return "jsx";
15
+ default:
16
+ return "js";
17
+ }
18
+ }
19
+
20
+ interface MaybeWrappedNode {
21
+ expression?: unknown;
22
+ type: string;
23
+ }
24
+
25
+ const TS_WRAPPER_TYPES = new Set([
26
+ "TSAsExpression",
27
+ "TSSatisfiesExpression",
28
+ "TSTypeAssertion",
29
+ "TSNonNullExpression",
30
+ "TSInstantiationExpression",
31
+ "ParenthesizedExpression",
32
+ ]);
33
+
34
+ export function unwrapTSExpression<T extends { type: string }>(node: T): T {
35
+ let current: MaybeWrappedNode = node;
36
+ while (
37
+ current &&
38
+ typeof current === "object" &&
39
+ TS_WRAPPER_TYPES.has(current.type) &&
40
+ current.expression &&
41
+ typeof current.expression === "object"
42
+ ) {
43
+ current = current.expression as MaybeWrappedNode;
44
+ }
45
+ return current as T;
46
+ }
package/src/link.tsx CHANGED
@@ -103,10 +103,11 @@ function LinkInteractive<To extends RouteTo>({
103
103
  const effectiveDelay = preloadDelay ?? router.defaultPreloadDelay;
104
104
  const effectiveStaleTime = preloadStaleTime ?? router.defaultPreloadStaleTime;
105
105
 
106
+ const { prefetch } = router;
106
107
  const triggerPrefetch = useCallback(() => {
107
108
  // prefetch() expects the logical href (no basePath prefix).
108
- router.prefetch(logicalHref, { staleTime: effectiveStaleTime });
109
- }, [router, logicalHref, effectiveStaleTime]);
109
+ prefetch(logicalHref, { staleTime: effectiveStaleTime });
110
+ }, [prefetch, logicalHref, effectiveStaleTime]);
110
111
 
111
112
  // "render": preload immediately on mount
112
113
  useEffect(() => {
@@ -175,6 +176,12 @@ function LinkInteractive<To extends RouteTo>({
175
176
  return;
176
177
  }
177
178
  e.preventDefault();
179
+ // When there is no RouterProvider, fall back to a full-page navigation so
180
+ // the link is still functional (e.g. in storybooks or third-party pages).
181
+ if (typeof window !== "undefined" && router.navigate === SSR_FALLBACK_ROUTER.navigate) {
182
+ window.location.href = href;
183
+ return;
184
+ }
178
185
  // navigate() expects the logical href (no basePath prefix).
179
186
  router.navigate(logicalHref, { replace, resetScroll: resetScroll ?? true });
180
187
  };
@@ -310,7 +317,7 @@ export function Link<To extends RouteTo>(props: LinkProps<To>): React.ReactEleme
310
317
  // when link.tsx is loaded under a second React instance via the
311
318
  // furin-dev-page virtual namespace after a Bun HMR reload.
312
319
  return createElement(RouterContext.Consumer, {
313
- // biome-ignore lint/correctness/noChildrenProp: render-prop pattern requires children-as-function
320
+ // biome-ignore lint/correctness/noChildrenProp: render-prop pattern — RouterContext.Consumer requires children as a function; cannot be passed as createElement 3rd arg due to TypeScript overloads
314
321
  children: (routerCtx: RouterContextValue | null) =>
315
322
  renderLinkElement(props, routerCtx ?? SSR_FALLBACK_ROUTER),
316
323
  });
@@ -322,3 +329,9 @@ export function Link<To extends RouteTo>(props: LinkProps<To>): React.ReactEleme
322
329
  props as LinkProps<RouteTo>
323
330
  );
324
331
  }
332
+
333
+ // ── Deferred hydration helpers ─────────────────────────────────────────────────
334
+ // Re-exported here so generated `_hydrate.tsx` files can import from
335
+ // `@teyik0/furin/link` (already a client-only bundle entry) without requiring
336
+ // apps to add "seroval" as a direct dependency.
337
+ export { fromCrossJSON } from "seroval";
@@ -4,7 +4,6 @@ const ELYSIA_FILTER = /^elysia$/;
4
4
  const BUN_BUILTIN_FILTER = /^bun:/;
5
5
  const ANY_FILTER = /.*/;
6
6
  const TS_FILE_FILTER = /\.(tsx|ts)$/;
7
- const REACT_IMPORT_FILTER = /import\s+React\b/;
8
7
 
9
8
  // Minimal browser stub for elysia — `t` is only used for schema definitions
10
9
  // in params/query, which the client never validates at runtime.
@@ -62,13 +61,13 @@ const plugin: Bun.BunPlugin = {
62
61
 
63
62
  try {
64
63
  const result = transformForClient(source, args.path);
65
- let code = result.code;
66
-
67
- if (code.includes("React.createElement") && !REACT_IMPORT_FILTER.test(code)) {
68
- code = `import React from "react";\n${code}`;
69
- }
70
-
71
- return { contents: code, loader: "js" };
64
+ // Output is TS/TSX (yuku parses directly, no pre-transpile). Bun's
65
+ // bundler picks the loader from the file extension and applies the
66
+ // project tsconfig — including the JSX automatic runtime.
67
+ return {
68
+ contents: result.code,
69
+ loader: args.path.endsWith(".tsx") ? "tsx" : "ts",
70
+ };
72
71
  } catch (err) {
73
72
  console.error(`[furin] strip-plugin transform error for ${args.path}:`, err);
74
73
  return;