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

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 (69) hide show
  1. package/README.md +14 -232
  2. package/dist/auto-invalidate/index.d.ts +4 -0
  3. package/dist/auto-invalidate/plugin.d.ts +38 -0
  4. package/dist/auto-invalidate/registry.d.ts +9 -0
  5. package/dist/auto-invalidate/runtime.d.ts +9 -0
  6. package/dist/auto-invalidate/types.d.ts +12 -0
  7. package/dist/await.d.ts +67 -0
  8. package/dist/build/index.js +2095 -185
  9. package/dist/cli/index.js +2070 -182
  10. package/dist/client.d.ts +51 -4
  11. package/dist/client.js +65 -1
  12. package/dist/deferred-ndjson.d.ts +32 -0
  13. package/dist/error.d.ts +14 -0
  14. package/dist/furin.d.ts +8 -0
  15. package/dist/furin.js +2927 -319
  16. package/dist/lang-detect.d.ts +5 -0
  17. package/dist/link.d.ts +1 -0
  18. package/dist/link.js +1453 -95
  19. package/dist/plugin/index.js +96 -25
  20. package/dist/plugin/transform-client.d.ts +2 -1
  21. package/dist/render/assemble.d.ts +32 -0
  22. package/dist/render/cache.d.ts +7 -0
  23. package/dist/render/element.d.ts +17 -1
  24. package/dist/render/index.d.ts +10 -1
  25. package/dist/render/index.ts +250 -44
  26. package/dist/render/loaders.d.ts +46 -3
  27. package/dist/render/shell.d.ts +16 -6
  28. package/dist/render/shell.ts +27 -12
  29. package/dist/router-provider.d.ts +86 -18
  30. package/dist/router.d.ts +66 -0
  31. package/dist/router.js +2909 -374
  32. package/dist/router.ts +586 -54
  33. package/dist/server-error.d.ts +12 -0
  34. package/dist/utils.d.ts +7 -0
  35. package/package.json +8 -7
  36. package/src/adapter/bun.ts +3 -3
  37. package/src/adapter/static.ts +73 -31
  38. package/src/auto-invalidate/index.ts +10 -0
  39. package/src/auto-invalidate/plugin.ts +25 -0
  40. package/src/auto-invalidate/registry.ts +60 -0
  41. package/src/auto-invalidate/runtime.ts +133 -0
  42. package/src/auto-invalidate/types.ts +16 -0
  43. package/src/await.tsx +175 -0
  44. package/src/build/client.ts +4 -8
  45. package/src/build/hydrate.ts +67 -1
  46. package/src/build/route-types.ts +29 -3
  47. package/src/build/scan-server.ts +6 -23
  48. package/src/client.ts +80 -3
  49. package/src/deferred-ndjson.ts +212 -0
  50. package/src/dev-page-plugin.ts +2 -0
  51. package/src/error.ts +18 -1
  52. package/src/furin.ts +19 -2
  53. package/src/lang-detect.ts +46 -0
  54. package/src/link.tsx +16 -3
  55. package/src/plugin/index.ts +7 -8
  56. package/src/plugin/transform-client.ts +108 -39
  57. package/src/render/assemble.ts +67 -0
  58. package/src/render/boundaries.tsx +23 -5
  59. package/src/render/cache.ts +14 -0
  60. package/src/render/default-screens.tsx +4 -11
  61. package/src/render/dev-cache.ts +5 -0
  62. package/src/render/element.tsx +26 -3
  63. package/src/render/index.ts +250 -44
  64. package/src/render/loaders.ts +219 -18
  65. package/src/render/shell.ts +27 -12
  66. package/src/router-provider.tsx +414 -122
  67. package/src/router.ts +586 -54
  68. package/src/server-error.ts +47 -0
  69. package/src/utils.ts +31 -0
package/dist/client.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { Cookie, StatusMap } from "elysia";
2
2
  import type { AnySchema, HTTPHeaders, UnwrapSchema } from "elysia/types";
3
3
  import type { RequestLogger } from "evlog";
4
+ export { Await, useAsyncError, useAsyncValue } from "./await.tsx";
4
5
  declare const UNSET: unique symbol;
5
6
  type Unset = typeof UNSET;
6
7
  type ToRecord<T> = {
@@ -13,9 +14,15 @@ type NormalizeUnset<T> = [T] extends [Unset] ? {} : T;
13
14
  * Transforms each key of a parent-data record into an individual `Promise<T>`.
14
15
  * This is what child loaders see for inherited fields — direct values from
15
16
  * `RouteContext` (request, params, set, …) remain unchanged.
17
+ *
18
+ * `Awaited<T[K]>` mirrors the JS Promise-chaining auto-flatten used by
19
+ * `createLoaderCtx`: when an ancestor wrapped a field with `defer()` (so the
20
+ * raw value is itself a `Promise<U>`), the type collapses to `Promise<U>`
21
+ * instead of `Promise<Promise<U>>`. Otherwise TypeScript would force a
22
+ * redundant `await await ctx.field` dance.
16
23
  */
17
24
  type PromisifyData<T extends Record<string, unknown>> = {
18
- [K in keyof T]: Promise<T[K]>;
25
+ [K in keyof T]: Promise<Awaited<T[K]>>;
19
26
  };
20
27
  export interface RouteContext<TParams = {}, TQuery = {}> {
21
28
  cookie: Record<string, Cookie<unknown>>;
@@ -47,7 +54,7 @@ type ResolveParent<T> = T extends RouteRef<infer D, infer P, infer Q> ? {
47
54
  query: Unset;
48
55
  };
49
56
  interface Resolved<TParentRef, TLoaderData, TParamsSchema = Unset, TQuerySchema = Unset> {
50
- data: ToRecord<ResolveParent<TParentRef>["data"] & TLoaderData>;
57
+ data: ToRecord<ResolveParent<TParentRef>["data"] & Omit<TLoaderData, "__isDeferred">>;
51
58
  params: MergeSchema<ResolveParent<TParentRef>["params"], ResolvedSchema<TParamsSchema>>;
52
59
  query: MergeSchema<ResolveParent<TParentRef>["query"], ResolvedSchema<TQuerySchema>>;
53
60
  }
@@ -100,12 +107,13 @@ export interface HeadOptions {
100
107
  children: string;
101
108
  }>;
102
109
  }
103
- type ExtractLoaderReturn<TLoader> = TLoader extends (...args: never[]) => unknown ? Awaited<ReturnType<TLoader>> extends object ? ToRecord<Awaited<ReturnType<TLoader>>> : {} : {};
110
+ type ExtractLoaderReturn<TLoader> = TLoader extends (...args: never[]) => unknown ? Awaited<ReturnType<TLoader>> extends object ? ToRecord<Omit<Awaited<ReturnType<TLoader>>, "__isDeferred">> : {} : {};
104
111
  export interface PageConfig<TParentData extends Record<string, unknown>, TParams, TQuery, TPageLoaderData extends object = {}> {
105
112
  component: React.FC<TParentData & TPageLoaderData & ComponentProps<TParams, TQuery>>;
106
113
  head?: (ctx: ComponentProps<TParams, TQuery> & TParentData & TPageLoaderData) => HeadOptions;
107
114
  loader?: (ctx: RouteContext<TParams, TQuery> & PromisifyData<TParentData>) => Promise<TPageLoaderData> | TPageLoaderData;
108
115
  staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
116
+ tags?: string[];
109
117
  }
110
118
  export interface RuntimeRoute {
111
119
  __type: "FURIN_ROUTE";
@@ -118,6 +126,7 @@ export interface RuntimeRoute {
118
126
  parent?: RuntimeRoute;
119
127
  query?: unknown;
120
128
  revalidate?: number;
129
+ tags?: string[];
121
130
  }
122
131
  export interface RuntimePage {
123
132
  __type: "FURIN_PAGE";
@@ -126,6 +135,7 @@ export interface RuntimePage {
126
135
  head?(ctx: Record<string, unknown>): HeadOptions;
127
136
  loader?(ctx: Record<string, unknown>): Promise<Record<string, unknown>> | Record<string, unknown>;
128
137
  staticParams?(): Promise<Record<string, string>[]> | Record<string, string>[];
138
+ tags?: string[];
129
139
  }
130
140
  export interface RouteRef<TData extends Record<string, unknown> = Record<string, unknown>, TParams = unknown, TQuery = unknown> {
131
141
  readonly __brand: "FURIN_ROUTE_REF";
@@ -141,6 +151,7 @@ interface PageResult<TData extends Record<string, unknown>, TParams, TQuery, TPa
141
151
  component: React.FC<TData & TPageLoaderData & ComponentProps<TParams, TQuery>>;
142
152
  head?: (ctx: ComponentProps<TParams, TQuery> & TData & TPageLoaderData) => HeadOptions;
143
153
  loader?: (ctx: RouteContext<TParams, TQuery> & PromisifyData<TData>) => Promise<TPageLoaderData> | TPageLoaderData;
154
+ tags?: string[];
144
155
  }
145
156
  export interface Route<TParentData extends Record<string, unknown>, TParams, TQuery> {
146
157
  __type: "FURIN_ROUTE";
@@ -154,6 +165,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
154
165
  mode?: "ssr" | "ssg" | "isr";
155
166
  revalidate?: number;
156
167
  staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
168
+ tags?: string[];
157
169
  component: React.FC<NoInfer<TParentData & TPageLoaderData & ComponentProps<TParams, TQuery>>>;
158
170
  head?: (ctx: NoInfer<ComponentProps<TParams, TQuery> & TParentData & TPageLoaderData>) => HeadOptions;
159
171
  }): PageResult<TParentData, TParams, TQuery, TPageLoaderData>;
@@ -161,6 +173,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
161
173
  mode?: "ssr" | "ssg" | "isr";
162
174
  revalidate?: number;
163
175
  staticParams?: () => Promise<NormalizeUnset<TParams>[]> | NormalizeUnset<TParams>[];
176
+ tags?: string[];
164
177
  component: React.FC<TParentData & ComponentProps<TParams, TQuery>>;
165
178
  head?: (ctx: ComponentProps<TParams, TQuery> & TParentData) => HeadOptions;
166
179
  }): PageResult<TParentData, TParams, TQuery, {}>;
@@ -170,6 +183,7 @@ export interface Route<TParentData extends Record<string, unknown>, TParams, TQu
170
183
  /** Branded ref for type inference when used as a parent. */
171
184
  ref: RouteRef<TParentData, TParams, TQuery>;
172
185
  revalidate?: number;
186
+ tags?: string[];
173
187
  }
174
188
  export declare function createRoute<TParentRef extends RouteRef | undefined = undefined, TParamsSchema extends AnySchema | Unset = Unset, TQuerySchema extends AnySchema | Unset = Unset, TLoaderData extends object = {}>(config?: {
175
189
  parent?: {
@@ -181,6 +195,7 @@ export declare function createRoute<TParentRef extends RouteRef | undefined = un
181
195
  revalidate?: number;
182
196
  params?: TParamsSchema;
183
197
  query?: TQuerySchema;
198
+ tags?: string[];
184
199
  loader?: (ctx: RouteContext<Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["params"], Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["query"]> & PromisifyData<ResolveParent<TParentRef>["data"]>) => Promise<TLoaderData> | TLoaderData;
185
200
  layout?: React.FC<Resolved<TParentRef, TLoaderData, TParamsSchema, TQuerySchema>["data"] & {
186
201
  children: React.ReactNode;
@@ -192,4 +207,36 @@ export type InferProps<T> = T extends {
192
207
  } ? P : T extends Route<infer D, infer P, infer Q> ? D & {
193
208
  children: React.ReactNode;
194
209
  } & ComponentProps<P, Q> : never;
195
- export {};
210
+ /**
211
+ * Brand key that marks an object as deferred. Using a `const` string avoids
212
+ * a `unique symbol` that would complicate cross-module inference.
213
+ */
214
+ declare const DEFERRED_BRAND: "__isDeferred";
215
+ /**
216
+ * A loader return value that contains a mix of synchronous scalar fields and
217
+ * lazy `Promise<T>` fields. Scalar fields are serialised into the initial HTML
218
+ * shell; Promise fields are streamed as late `<script>` resolution chunks.
219
+ *
220
+ * @example
221
+ * loader: () => defer({
222
+ * title: "My Board", // synchronous — available immediately
223
+ * stats: fetchStats(), // Promise — streamed when it resolves
224
+ * })
225
+ */
226
+ export type DeferredData<T extends Record<string, unknown>> = T & {
227
+ readonly [DEFERRED_BRAND]: true;
228
+ };
229
+ /**
230
+ * Wraps loader data so that Promise-valued fields are streamed lazily while
231
+ * scalar fields are embedded in the initial HTML shell immediately.
232
+ *
233
+ * Use in any loader — page (`route.page({ loader })`) or route/layout
234
+ * (`createRoute({ loader })`). Promise-valued fields are streamed lazily;
235
+ * scalar fields are embedded in the initial HTML shell.
236
+ */
237
+ export declare function defer<T extends Record<string, unknown>>(data: T): DeferredData<T>;
238
+ /**
239
+ * Type guard for DeferredData. Used by the render pipeline to distinguish a
240
+ * plain loader return from a deferred one.
241
+ */
242
+ export declare function isDeferred(v: unknown): v is DeferredData<Record<string, unknown>>;
package/dist/client.js CHANGED
@@ -1,4 +1,53 @@
1
1
  // @bun
2
+ // src/await.tsx
3
+ import { Component, createContext, createElement, use } from "react";
4
+ var AsyncErrorContext = createContext(undefined);
5
+ function useAsyncError() {
6
+ return use(AsyncErrorContext);
7
+ }
8
+ function useAsyncValue() {
9
+ const ctx = use(AwaitValueContext);
10
+ if (!ctx) {
11
+ throw new Error("useAsyncValue must be used inside <Await> children");
12
+ }
13
+ return use(ctx.promise);
14
+ }
15
+ var AwaitValueContext = createContext(undefined);
16
+
17
+ class AsyncErrorBoundary extends Component {
18
+ constructor(props) {
19
+ super(props);
20
+ this.state = { hasError: false, error: undefined, resolve: props.resolve };
21
+ }
22
+ static getDerivedStateFromProps(props, state) {
23
+ if (props.resolve !== state.resolve) {
24
+ return { hasError: false, error: undefined, resolve: props.resolve };
25
+ }
26
+ return null;
27
+ }
28
+ static getDerivedStateFromError(error) {
29
+ return { hasError: true, error };
30
+ }
31
+ render() {
32
+ const { hasError, error } = this.state;
33
+ const { children, errorElement } = this.props;
34
+ if (hasError) {
35
+ if (errorElement === undefined) {
36
+ throw error;
37
+ }
38
+ return createElement(AsyncErrorContext.Provider, { value: error }, errorElement);
39
+ }
40
+ return children;
41
+ }
42
+ }
43
+ function Await({ resolve, errorElement, children }) {
44
+ return createElement(AsyncErrorBoundary, { errorElement, resolve }, createElement(AwaitInner, { resolve, children }));
45
+ }
46
+ function AwaitInner({ resolve, children }) {
47
+ const value = use(resolve);
48
+ return createElement(AwaitValueContext.Provider, { value: { promise: resolve } }, children ? children(value) : null);
49
+ }
50
+
2
51
  // src/client.ts
3
52
  function createRoute(config) {
4
53
  const route = {
@@ -15,6 +64,21 @@ function createRoute(config) {
15
64
  };
16
65
  return route;
17
66
  }
67
+ var DEFERRED_BRAND = "__isDeferred";
68
+ function defer(data) {
69
+ if (Object.hasOwn(data, DEFERRED_BRAND)) {
70
+ throw new Error(`[furin] defer() received an object with a reserved key "${DEFERRED_BRAND}". Rename this field to avoid conflicts with the deferred-data runtime.`);
71
+ }
72
+ return { ...data, [DEFERRED_BRAND]: true };
73
+ }
74
+ function isDeferred(v) {
75
+ return typeof v === "object" && v !== null && Object.hasOwn(v, DEFERRED_BRAND) && v[DEFERRED_BRAND] === true;
76
+ }
18
77
  export {
19
- createRoute
78
+ useAsyncValue,
79
+ useAsyncError,
80
+ isDeferred,
81
+ defer,
82
+ createRoute,
83
+ Await
20
84
  };
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Result returned by `parseDeferredNdjson`.
3
+ */
4
+ export interface DeferredNdjsonResult {
5
+ /**
6
+ * Deferred promises keyed by their field name. Each Promise resolves (or
7
+ * rejects) once the corresponding data is available. In the SSR case the
8
+ * promises are already settled (serialised by `toCrossJSONAsync`). For
9
+ * streaming endpoints they will settle as the server flushes resolution
10
+ * chunks.
11
+ */
12
+ deferredPromises: Record<string, Promise<unknown>>;
13
+ /** Scalar/sync values from the loader — available immediately. */
14
+ syncData: Record<string, unknown>;
15
+ }
16
+ /**
17
+ * Parses an NDJSON stream produced by `/_furin/data`.
18
+ *
19
+ * Protocol (v1 — single-line, all-resolved):
20
+ * Line 0 — `JSON.stringify(await toCrossJSONAsync(loaderData))`
21
+ *
22
+ * The CrossJSON node is deserialised with `fromCrossJSON`. Values that are
23
+ * Promises (seroval type 12) land in `deferredPromises`; everything else
24
+ * lands in `syncData`.
25
+ *
26
+ * @param stream - A `ReadableStream<Uint8Array>` from `fetch().body`.
27
+ * @param signal - AbortSignal that, when aborted, cancels the reader and
28
+ * rejects every still-pending deferred promise with an
29
+ * `AbortError`. Pass `undefined` to opt out (no implicit
30
+ * default — see CLAUDE.md).
31
+ */
32
+ export declare function parseDeferredNdjson(stream: ReadableStream<Uint8Array>, signal: AbortSignal | undefined): Promise<DeferredNdjsonResult>;
package/dist/error.d.ts CHANGED
@@ -10,6 +10,20 @@ export interface ErrorProps {
10
10
  * without leaking stack traces to the browser.
11
11
  */
12
12
  digest: string;
13
+ /**
14
+ * HTTP status associated with the error.
15
+ * - For thrown `Response` objects with a 4xx/5xx status: the response's
16
+ * status (e.g. 401, 403, 404, 500).
17
+ * - For all other errors (thrown `Error`, non-Error throws, shell-render
18
+ * crashes): always `500`.
19
+ *
20
+ * Always present so consumers never need a `?? 500` fallback. Note that
21
+ * `prepared.status` is honoured ONLY for loader-time errors. If a Suspense
22
+ * boundary throws AFTER the SSR shell has flushed (i.e. during streaming),
23
+ * the HTTP status cannot be changed and the user-visible status here may
24
+ * differ from the actual response code.
25
+ */
26
+ status: number;
13
27
  };
14
28
  /**
15
29
  * Clears the nearest FurinErrorBoundary's error state, remounting its
package/dist/furin.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  import { Elysia } from "elysia";
2
2
  import { type EvlogElysiaOptions } from "evlog/elysia";
3
+ export interface FurinCacheTags {
4
+ }
5
+ export type CacheTag = keyof FurinCacheTags extends never ? string : keyof FurinCacheTags;
3
6
  /**
4
7
  * Main Furin plugin.
5
8
  *
@@ -45,6 +48,11 @@ export declare function furin({ pagesDir, logger, }: {
45
48
  standaloneSchema: {};
46
49
  response: {};
47
50
  }>>;
51
+ export type { InvalidationInput, InvalidationRule } from "./auto-invalidate/index.ts";
52
+ export { furinInvalidate, revalidateTag } from "./auto-invalidate/index.ts";
53
+ export { Await, useAsyncError, useAsyncValue } from "./await.tsx";
54
+ export type { DeferredData } from "./client.ts";
55
+ export { defer, isDeferred } from "./client.ts";
48
56
  export type { ErrorComponent, ErrorProps } from "./error.ts";
49
57
  export type { NotFoundComponent, NotFoundOptions, NotFoundProps, } from "./not-found.ts";
50
58
  export { isNotFoundError, notFound } from "./not-found.ts";