@teyik0/furin 0.2.0-alpha.1 → 0.2.0-alpha.2

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 (119) hide show
  1. package/package.json +8 -3
  2. package/src/adapter/static.ts +23 -6
  3. package/src/build/client.ts +5 -2
  4. package/src/build/hydrate.ts +7 -1
  5. package/src/build/route-types.ts +37 -7
  6. package/src/build/shared.ts +1 -0
  7. package/src/build/ssg-cache.ts +3 -2
  8. package/src/client/link.tsx +13 -4
  9. package/src/client/router/context.ts +2 -0
  10. package/src/client/router/index.ts +9 -0
  11. package/src/client/router/link-utils.ts +5 -8
  12. package/src/client/router/navigation.ts +61 -0
  13. package/src/client/router/provider.tsx +59 -23
  14. package/src/client/router/search/index.ts +99 -0
  15. package/src/client/router/search-store.ts +86 -0
  16. package/src/client/router/types.ts +12 -4
  17. package/src/furin.ts +11 -4
  18. package/src/server/render/isr.ts +29 -7
  19. package/src/server/render/not-found.ts +2 -0
  20. package/src/server/render/ssg.ts +15 -4
  21. package/src/server/render/ssr.ts +47 -9
  22. package/src/server/router/hmr.ts +14 -10
  23. package/src/server/router/index.ts +1 -2
  24. package/src/server/router/patterns.ts +5 -0
  25. package/src/server/router/plugin.ts +28 -45
  26. package/src/server/router/schemas.ts +172 -57
  27. package/src/shared/search-params.ts +182 -0
  28. package/dist/adapter/bun.d.ts +0 -3
  29. package/dist/adapter/static.d.ts +0 -3
  30. package/dist/build/client.d.ts +0 -25
  31. package/dist/build/compile-entry.d.ts +0 -9
  32. package/dist/build/compile-entry.ts +0 -109
  33. package/dist/build/entry-template.d.ts +0 -38
  34. package/dist/build/entry-template.ts +0 -156
  35. package/dist/build/hydrate.d.ts +0 -24
  36. package/dist/build/index.d.ts +0 -8
  37. package/dist/build/index.js +0 -7069
  38. package/dist/build/route-types.d.ts +0 -21
  39. package/dist/build/scan-server.d.ts +0 -8
  40. package/dist/build/server-routes-entry.d.ts +0 -13
  41. package/dist/build/server-routes-entry.ts +0 -36
  42. package/dist/build/shared.d.ts +0 -11
  43. package/dist/build/ssg-cache.d.ts +0 -4
  44. package/dist/build/types.d.ts +0 -80
  45. package/dist/cli/config.d.ts +0 -9
  46. package/dist/cli/index.d.ts +0 -2
  47. package/dist/cli/index.js +0 -7082
  48. package/dist/client/boundaries.d.ts +0 -117
  49. package/dist/client/default-screens.d.ts +0 -17
  50. package/dist/client/link.d.ts +0 -22
  51. package/dist/client/link.js +0 -3450
  52. package/dist/client/router/boundary-tree.d.ts +0 -26
  53. package/dist/client/router/context.d.ts +0 -8
  54. package/dist/client/router/history.d.ts +0 -9
  55. package/dist/client/router/index.d.ts +0 -7
  56. package/dist/client/router/link-utils.d.ts +0 -51
  57. package/dist/client/router/provider.d.ts +0 -4
  58. package/dist/client/router/spa-response.d.ts +0 -58
  59. package/dist/client/router/types.d.ts +0 -279
  60. package/dist/client/server-error.d.ts +0 -12
  61. package/dist/client.d.ts +0 -242
  62. package/dist/client.js +0 -96
  63. package/dist/config.d.ts +0 -57
  64. package/dist/config.js +0 -29
  65. package/dist/env.d.ts +0 -50
  66. package/dist/furin.d.ts +0 -69
  67. package/dist/furin.js +0 -7373
  68. package/dist/plugin/index.d.ts +0 -20
  69. package/dist/plugin/index.js +0 -1500
  70. package/dist/plugin/transform-client.d.ts +0 -10
  71. package/dist/server/auto-invalidate/index.d.ts +0 -4
  72. package/dist/server/auto-invalidate/plugin.d.ts +0 -38
  73. package/dist/server/auto-invalidate/registry.d.ts +0 -9
  74. package/dist/server/auto-invalidate/runtime.d.ts +0 -9
  75. package/dist/server/auto-invalidate/types.d.ts +0 -12
  76. package/dist/server/cache/dev-loader.d.ts +0 -28
  77. package/dist/server/cache/index.d.ts +0 -10
  78. package/dist/server/cache/invalidation.d.ts +0 -12
  79. package/dist/server/cache/isr-ssg.d.ts +0 -26
  80. package/dist/server/cache/isr.d.ts +0 -6
  81. package/dist/server/cache/registry.d.ts +0 -5
  82. package/dist/server/cache/route-cache.d.ts +0 -26
  83. package/dist/server/cache/ssg.d.ts +0 -5
  84. package/dist/server/context-logger.d.ts +0 -28
  85. package/dist/server/dev-inspector.d.ts +0 -89
  86. package/dist/server/dev-page-plugin.d.ts +0 -109
  87. package/dist/server/internal.d.ts +0 -35
  88. package/dist/server/internal.js +0 -17
  89. package/dist/server/lang-detect.d.ts +0 -5
  90. package/dist/server/render/assemble.d.ts +0 -47
  91. package/dist/server/render/element.d.ts +0 -24
  92. package/dist/server/render/index.d.ts +0 -7
  93. package/dist/server/render/index.ts +0 -22
  94. package/dist/server/render/isr.d.ts +0 -3
  95. package/dist/server/render/loaders.d.ts +0 -64
  96. package/dist/server/render/not-found.d.ts +0 -6
  97. package/dist/server/render/shell.d.ts +0 -39
  98. package/dist/server/render/shell.ts +0 -202
  99. package/dist/server/render/ssg.d.ts +0 -8
  100. package/dist/server/render/ssr.d.ts +0 -107
  101. package/dist/server/render/template.d.ts +0 -6
  102. package/dist/server/router/discovery.d.ts +0 -16
  103. package/dist/server/router/hmr.d.ts +0 -64
  104. package/dist/server/router/index.d.ts +0 -6
  105. package/dist/server/router/index.js +0 -28
  106. package/dist/server/router/index.ts +0 -29
  107. package/dist/server/router/patterns.d.ts +0 -40
  108. package/dist/server/router/plugin.d.ts +0 -20
  109. package/dist/server/router/schemas.d.ts +0 -51
  110. package/dist/server/router/types.d.ts +0 -60
  111. package/dist/server/runtime-env.d.ts +0 -3
  112. package/dist/server/runtime-env.js +0 -10
  113. package/dist/shared/await.d.ts +0 -67
  114. package/dist/shared/deferred-ndjson.d.ts +0 -32
  115. package/dist/shared/digest.d.ts +0 -16
  116. package/dist/shared/error.d.ts +0 -37
  117. package/dist/shared/not-found.d.ts +0 -19
  118. package/dist/shared/utils/ast-walk.d.ts +0 -18
  119. package/dist/shared/utils/index.d.ts +0 -13
@@ -2,6 +2,7 @@ import { type AnyElysia, type Context, Elysia, t } from "elysia";
2
2
  import type { AnySchema } from "elysia/types";
3
3
  import { toCrossJSON, toCrossJSONAsync } from "seroval";
4
4
  import { computeErrorDigest } from "../../shared/digest.ts";
5
+ import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
5
6
  import { autoInvalidateRegistry } from "../auto-invalidate/registry.ts";
6
7
  import { useLogger } from "../context-logger.ts";
7
8
  import { resolvePath } from "../render/assemble.ts";
@@ -18,22 +19,27 @@ import { handleDevRequest } from "./hmr.ts";
18
19
  import { buildRouteMatcher } from "./patterns.ts";
19
20
  import {
20
21
  applySchemaDefaults,
21
- detectQueryDefaultRedirect,
22
22
  mergeRouteSchemas,
23
23
  parseDataEndpointPath,
24
- queryDefaultRedirectHook,
24
+ parseRouteQuery,
25
25
  } from "./schemas.ts";
26
26
  import type { ResolvedRoute, RootLayout } from "./types.ts";
27
27
 
28
+ type SyntheticDataContext = Omit<Context, "params" | "query"> & {
29
+ params: Record<string, string>;
30
+ query: SearchParamsInput;
31
+ };
32
+
28
33
  /** @internal Handles a production SSG route — sets ETags, Cache-Control, and Cache-Tag. */
29
34
  async function handleSSGRequest(
30
35
  route: ResolvedRoute,
31
36
  ctx: Context,
32
37
  root: RootLayout,
33
- buildId: string
38
+ buildId: string,
39
+ searchRoutes: SearchRouteMetadata[] | undefined
34
40
  ): Promise<unknown> {
35
41
  const origin = new URL(ctx.request.url).origin;
36
- const entry = await prerenderSSG(route, ctx.params, root, origin, undefined);
42
+ const entry = await prerenderSSG(route, ctx.params, root, origin, undefined, searchRoutes);
37
43
 
38
44
  // Loader issued a redirect — forward it directly to the client.
39
45
  if (entry instanceof Response) {
@@ -63,14 +69,14 @@ async function handleSSGRequest(
63
69
  export function createRoutePlugin(
64
70
  route: ResolvedRoute,
65
71
  root: RootLayout,
66
- buildId?: string
72
+ buildId?: string,
73
+ searchRoutes?: SearchRouteMetadata[]
67
74
  ): AnyElysia {
68
75
  const resolvedBuildId = buildId ?? "";
69
76
  const { pattern, routeChain } = route;
70
77
 
71
78
  const allParams = mergeRouteSchemas(routeChain, "params");
72
79
  const allQuery = mergeRouteSchemas(routeChain, "query");
73
- const hasQuerySchema = !!allQuery;
74
80
 
75
81
  // Guard and handler MUST live in the same Elysia scope so that validation
76
82
  // (including default-filling) applies to the route handler's ctx.query.
@@ -84,14 +90,6 @@ export function createRoutePlugin(
84
90
  }
85
91
 
86
92
  plugin.get(pattern, (ctx) => {
87
- // Redirect when Elysia applied query defaults (validator-agnostic)
88
- if (hasQuerySchema) {
89
- const redirect = queryDefaultRedirectHook(ctx);
90
- if (redirect) {
91
- return redirect;
92
- }
93
- }
94
-
95
93
  // Dev mode: re-imports page + layouts on every request via the
96
94
  // ?furin-server cache-buster, then dispatches into one of:
97
95
  // - renderDevISRWithLoaderCache (mode === "isr")
@@ -105,19 +103,19 @@ export function createRoutePlugin(
105
103
  // cache is invalidated source-aware via `isDevLoaderCacheValid`
106
104
  // (mtime-checked dependency walk on every read).
107
105
  if (IS_DEV) {
108
- return handleDevRequest(route, ctx, root);
106
+ return handleDevRequest(route, ctx, root, searchRoutes);
109
107
  }
110
108
 
111
109
  if (route.mode === "ssg") {
112
- return handleSSGRequest(route, ctx, root, resolvedBuildId);
110
+ return handleSSGRequest(route, ctx, root, resolvedBuildId, searchRoutes);
113
111
  }
114
112
 
115
113
  if (route.mode === "isr") {
116
114
  ctx.set.headers["cache-tag"] = resolvePath(route.pattern, ctx.params ?? {});
117
- return handleISR(route, ctx, root, resolvedBuildId);
115
+ return handleISR(route, ctx, root, resolvedBuildId, searchRoutes);
118
116
  }
119
117
 
120
- return renderSSR(route, ctx, root, undefined);
118
+ return renderSSR(route, ctx, root, undefined, searchRoutes);
121
119
  });
122
120
 
123
121
  return plugin;
@@ -145,7 +143,6 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
145
143
 
146
144
  plugin.get(
147
145
  "/_furin/data",
148
- // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: data endpoint handler validates path, resolves loaders, handles deferred/SPA/ISR modes — each branch is a distinct protocol case; splitting would spread context across many functions
149
146
  async (ctx) => {
150
147
  const rawPath = ctx.query.path;
151
148
  if (!rawPath || typeof rawPath !== "string") {
@@ -185,7 +182,7 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
185
182
  // foreign origin into `syntheticRequest.url`.
186
183
  const syntheticRequest = new Request(new URL(pathname + url.search, ctx.request.url));
187
184
  const syntheticSet = { headers: {} as Record<string, string>, status: 200 as number };
188
- const syntheticCtx = {
185
+ const syntheticCtx: SyntheticDataContext = {
189
186
  request: syntheticRequest,
190
187
  params: matched.params,
191
188
  query: Object.fromEntries(url.searchParams),
@@ -201,42 +198,28 @@ export function createDataEndpoint(routes: ResolvedRoute[]): AnyElysia {
201
198
  // Synthetic `status` helper: numeric codes only. Callers that reach
202
199
  // this endpoint never dispatch a string-keyed status; rejecting them
203
200
  // is safer than coercing via `Number(code)` and silently producing
204
- // `NaN`. Query-default redirects no longer flow through this helper —
205
- // they are detected via `detectQueryDefaultRedirect` below.
201
+ // `NaN`.
206
202
  status: (code: number) => new Response(null, { status: code }),
207
- } as unknown as Context;
203
+ } as unknown as SyntheticDataContext;
208
204
 
209
205
  // Normalize params and query through the same merged schemas used by
210
206
  // createRoutePlugin so loaders see identical typed/defaulted inputs.
211
207
  const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
212
208
  const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
209
+ const parsedQuery = await parseRouteQuery(url, mergedQuery);
210
+ if (!parsedQuery.ok) {
211
+ return Response.json(
212
+ { errors: parsedQuery.errors, message: "Invalid query", type: "validation" },
213
+ { status: 422 }
214
+ );
215
+ }
213
216
  syntheticCtx.params = applySchemaDefaults(
214
217
  mergedParams as Record<string, unknown> | undefined,
215
218
  syntheticCtx.params as Record<string, unknown>
216
219
  ) as Record<string, string>;
217
- syntheticCtx.query = applySchemaDefaults(
218
- mergedQuery as Record<string, unknown> | undefined,
219
- syntheticCtx.query as Record<string, unknown>
220
- ) as Record<string, string>;
221
-
222
- // Query-default redirect: detect via the pure helper so we can emit the
223
- // NDJSON `__furinRedirect` sentinel (the SPA client cannot parse a real
224
- // HTTP 302 — it never sees one because `parseDeferredNdjson` reads the
225
- // body, not the redirect chain).
226
- if (mergedQuery) {
227
- const redirectLocation = detectQueryDefaultRedirect(
228
- syntheticRequest,
229
- syntheticCtx.query as Record<string, unknown>
230
- );
231
- if (redirectLocation) {
232
- const serialized = await toCrossJSONAsync({ __furinRedirect: redirectLocation });
233
- return new Response(`${JSON.stringify(serialized)}\n`, {
234
- headers: { "content-type": "application/x-ndjson" },
235
- });
236
- }
237
- }
220
+ syntheticCtx.query = parsedQuery.query as SearchParamsInput;
238
221
 
239
- const result = await runLoaders(matched.route, syntheticCtx);
222
+ const result = await runLoaders(matched.route, syntheticCtx as unknown as Context);
240
223
 
241
224
  // Keep the auto-invalidate registry in sync with whatever path was just
242
225
  // served, so subsequent `revalidateTag(...)` calls (e.g. from a mutation
@@ -1,54 +1,21 @@
1
- import type { Context } from "elysia";
2
1
  import { t } from "elysia";
2
+ import { parseQueryFromURL, parseQueryStandardSchema } from "elysia/parse-query";
3
+ import { getSchemaValidator } from "elysia/schema";
3
4
  import type { AnySchema } from "elysia/types";
4
5
  import type { RuntimeRoute } from "../../client.ts";
6
+ import {
7
+ collectSearchDefaults,
8
+ type SearchParamsInput,
9
+ type SearchRouteMetadata,
10
+ } from "../../shared/search-params.ts";
11
+ import { buildRouteRegex } from "./patterns.ts";
5
12
 
6
- // ── Query-default redirect ──────────────────────────────────────────────────
7
- // Validator-agnostic: after Elysia applies defaults (TypeBox, Zod, Valibot…),
8
- // compare the raw URL query keys with the resolved ctx.query keys. If ctx.query
9
- // contains keys absent from the URL, defaults were applied → 302 redirect to
10
- // the canonical URL so the address bar always reflects the actual app state.
11
-
12
- /**
13
- * Detects whether a validator filled in default query values that the original
14
- * URL did not carry, and returns the canonical `pathname + search` to redirect
15
- * to — or `undefined` when the URL already reflects the resolved query.
16
- *
17
- * Pure helper extracted from `queryDefaultRedirectHook` so the `/_furin/data`
18
- * NDJSON endpoint can detect the same condition without going through
19
- * Elysia's `status()` shim (which only emits HTTP 302s, unparseable by the
20
- * SPA client).
21
- *
22
- * @internal Exported for unit testing.
23
- */
24
- export function detectQueryDefaultRedirect(
25
- request: Request,
26
- resolvedQuery: Record<string, unknown>
27
- ): string | undefined {
28
- const queryKeys = Object.keys(resolvedQuery);
29
- if (queryKeys.length === 0) {
30
- return;
31
- }
32
-
33
- const rawParams = new URL(request.url).searchParams;
34
- let needsRedirect = false;
35
- for (const key of queryKeys) {
36
- if (!rawParams.has(key) && resolvedQuery[key] != null) {
37
- needsRedirect = true;
38
- break;
39
- }
40
- }
41
- if (!needsRedirect) {
42
- return;
43
- }
13
+ interface UnknownObject {
14
+ [key: string]: unknown;
15
+ }
44
16
 
45
- const url = new URL(request.url);
46
- for (const [k, v] of Object.entries(resolvedQuery)) {
47
- if (v != null) {
48
- url.searchParams.set(k, String(v));
49
- }
50
- }
51
- return url.pathname + url.search;
17
+ interface QueryKeyMap {
18
+ [key: string]: 1;
52
19
  }
53
20
 
54
21
  /**
@@ -80,19 +47,143 @@ export function parseDataEndpointPath(rawPath: string): { url: URL; pathname: st
80
47
  return { url, pathname: url.pathname };
81
48
  }
82
49
 
83
- /** @internal Exported for unit testing. */
84
- export function queryDefaultRedirectHook({ request, query, status, set }: Context) {
85
- const location = detectQueryDefaultRedirect(request, query as Record<string, unknown>);
86
- if (!location) {
50
+ function isObjectSchema(schema: unknown): schema is UnknownObject {
51
+ return !!schema && typeof schema === "object";
52
+ }
53
+
54
+ function isStandardSchema(schema: unknown): boolean {
55
+ return isObjectSchema(schema) && "~standard" in schema;
56
+ }
57
+
58
+ function collectQueryArrayKeys(schema: unknown): QueryKeyMap | undefined {
59
+ if (!(isObjectSchema(schema) && isObjectSchema(schema.properties))) {
60
+ return;
61
+ }
62
+
63
+ const keys: QueryKeyMap = {};
64
+ for (const [key, value] of Object.entries(schema.properties)) {
65
+ const effectiveSchema = findEffectiveAnyOfMember(value, "array") ?? value;
66
+ if (isObjectSchema(effectiveSchema) && effectiveSchema.type === "array") {
67
+ keys[key] = 1;
68
+ }
69
+ }
70
+
71
+ return Object.keys(keys).length > 0 ? keys : undefined;
72
+ }
73
+
74
+ function collectQueryObjectKeys(schema: unknown): QueryKeyMap | undefined {
75
+ if (!(isObjectSchema(schema) && isObjectSchema(schema.properties))) {
87
76
  return;
88
77
  }
89
- set.headers.location = location;
90
- return status("Found");
78
+
79
+ const keys: QueryKeyMap = {};
80
+ for (const [key, value] of Object.entries(schema.properties)) {
81
+ const effectiveSchema = findEffectiveAnyOfMember(value, "object") ?? value;
82
+ if (isObjectSchema(effectiveSchema) && effectiveSchema.type === "object") {
83
+ keys[key] = 1;
84
+ }
85
+ }
86
+
87
+ return Object.keys(keys).length > 0 ? keys : undefined;
88
+ }
89
+
90
+ function findEffectiveAnyOfMember(
91
+ schema: unknown,
92
+ type: "array" | "object"
93
+ ): UnknownObject | undefined {
94
+ if (!(isObjectSchema(schema) && Array.isArray(schema.anyOf))) {
95
+ return;
96
+ }
97
+
98
+ for (const member of schema.anyOf) {
99
+ if (isObjectSchema(member) && member.type === type) {
100
+ return member;
101
+ }
102
+ }
103
+ }
104
+
105
+ function parseJsonQueryObjects(
106
+ query: UnknownObject,
107
+ objectKeys: QueryKeyMap | undefined
108
+ ): UnknownObject {
109
+ if (!objectKeys) {
110
+ return query;
111
+ }
112
+
113
+ const parsed = { ...query };
114
+ for (const key of Object.keys(objectKeys)) {
115
+ const value = parsed[key];
116
+ if (typeof value !== "string") {
117
+ continue;
118
+ }
119
+ try {
120
+ parsed[key] = JSON.parse(value);
121
+ } catch {
122
+ parsed[key] = value;
123
+ }
124
+ }
125
+ return parsed;
126
+ }
127
+
128
+ export type ParseRouteQueryResult =
129
+ | { ok: true; query: SearchParamsInput }
130
+ | { errors: unknown; ok: false };
131
+
132
+ /**
133
+ * Parses and validates a logical route URL's search string for the synthetic
134
+ * `/_furin/data` request path. This keeps SPA navigations aligned with the
135
+ * Elysia guard used by the full SSR route.
136
+ *
137
+ * @internal Exported for unit testing.
138
+ */
139
+ export async function parseRouteQuery(
140
+ url: URL,
141
+ schema: AnySchema | undefined
142
+ ): Promise<ParseRouteQueryResult> {
143
+ if (!schema) {
144
+ return { ok: true, query: parseQueryFromURL(url.search, 1) as SearchParamsInput };
145
+ }
146
+
147
+ if (isStandardSchema(schema)) {
148
+ const rawQuery = parseQueryStandardSchema(url.search, 1) as UnknownObject;
149
+ const validator = getSchemaValidator(schema, { dynamic: true });
150
+ const checked = await validator?.Check(rawQuery);
151
+ if (checked && typeof checked === "object" && "issues" in checked) {
152
+ return { errors: checked.issues, ok: false };
153
+ }
154
+ if (checked && typeof checked === "object" && "value" in checked) {
155
+ return { ok: true, query: checked.value as SearchParamsInput };
156
+ }
157
+ return { ok: true, query: rawQuery as SearchParamsInput };
158
+ }
159
+
160
+ const rawQuery = parseJsonQueryObjects(
161
+ parseQueryFromURL(url.search, 1, collectQueryArrayKeys(schema)) as UnknownObject,
162
+ collectQueryObjectKeys(schema)
163
+ );
164
+ const queryWithDefaults = applySchemaDefaults(schema as UnknownObject, rawQuery);
165
+ const validator = getSchemaValidator(schema, { coerce: true, dynamic: true });
166
+ if (validator?.Check(queryWithDefaults) === false) {
167
+ return { errors: [...(validator?.Errors(queryWithDefaults) ?? [])], ok: false };
168
+ }
169
+
170
+ return {
171
+ ok: true,
172
+ query: (validator?.parse(queryWithDefaults) ?? queryWithDefaults) as SearchParamsInput,
173
+ };
91
174
  }
92
175
 
93
176
  // Standard structural keys on a TObject — everything else is a user-supplied option
94
177
  // (e.g. additionalProperties, $id, description, title) and must be preserved.
95
178
  const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
179
+ const TYPEBOX_KIND = Symbol.for("TypeBox.Kind");
180
+
181
+ function isTypeBoxObjectSchema(schema: unknown): schema is UnknownObject {
182
+ return (
183
+ isObjectSchema(schema) &&
184
+ (schema as UnknownObject & { [key: symbol]: unknown })[TYPEBOX_KIND] === "Object"
185
+ );
186
+ }
96
187
 
97
188
  /**
98
189
  * Merges TObject schemas from all routeChain entries for a given key.
@@ -116,6 +207,12 @@ export function mergeRouteSchemas(
116
207
  return schemas[0] as AnySchema;
117
208
  }
118
209
 
210
+ if (schemas.some((s) => !isTypeBoxObjectSchema(s))) {
211
+ throw new Error(
212
+ `[furin] Merging ${key} schemas across the route chain requires TypeBox in V1. Use TypeBox for parent/child ${key}, or define ${key} only on leaf routes.`
213
+ );
214
+ }
215
+
119
216
  const mergedProperties = Object.assign(
120
217
  {},
121
218
  ...schemas.map((s) => (s.properties as Record<string, unknown>) ?? {})
@@ -131,24 +228,42 @@ export function mergeRouteSchemas(
131
228
  return t.Object(mergedProperties, mergedOptions) as AnySchema;
132
229
  }
133
230
 
231
+ export function createSearchRouteMetadata(
232
+ routes: Array<{ pattern: string; routeChain: RuntimeRoute[] }>
233
+ ): SearchRouteMetadata[] {
234
+ const metadata: SearchRouteMetadata[] = [];
235
+ for (const route of routes) {
236
+ const searchDefaults = collectSearchDefaults(mergeRouteSchemas(route.routeChain, "query"));
237
+ if (!searchDefaults) {
238
+ continue;
239
+ }
240
+ metadata.push({
241
+ pattern: route.pattern,
242
+ regex: buildRouteRegex(route.pattern).regex,
243
+ searchDefaults,
244
+ });
245
+ }
246
+ return metadata;
247
+ }
248
+
134
249
  /**
135
250
  * Applies top-level `default` values from a TypeBox TObject schema to a
136
251
  * values record. Used in the `/_furin/data` endpoint so loaders see the same
137
252
  * defaulted query objects that the SSR path produces via Elysia's guard.
138
253
  */
139
254
  export function applySchemaDefaults(
140
- schema: Record<string, unknown> | undefined,
141
- values: Record<string, unknown>
142
- ): Record<string, unknown> {
255
+ schema: UnknownObject | undefined,
256
+ values: UnknownObject
257
+ ): UnknownObject {
143
258
  if (!schema || typeof schema !== "object") {
144
259
  return values;
145
260
  }
146
- const s = schema as Record<string, unknown>;
261
+ const s = schema;
147
262
  if (s.type !== "object" || !s.properties || typeof s.properties !== "object") {
148
263
  return values;
149
264
  }
150
265
  const result = { ...values };
151
- const properties = s.properties as Record<string, Record<string, unknown>>;
266
+ const properties = s.properties as { [key: string]: UnknownObject };
152
267
  for (const [key, propSchema] of Object.entries(properties)) {
153
268
  if (
154
269
  !(key in result) &&
@@ -0,0 +1,182 @@
1
+ export type SearchParamValue =
2
+ | string
3
+ | number
4
+ | boolean
5
+ | null
6
+ | undefined
7
+ | SearchParamValue[]
8
+ | { [key: string]: SearchParamValue };
9
+
10
+ export interface SearchParamsInput {
11
+ [key: string]: SearchParamValue;
12
+ }
13
+
14
+ export interface SearchRouteMetadata {
15
+ pattern: string;
16
+ regex: RegExp;
17
+ searchDefaults?: SearchParamsInput;
18
+ }
19
+
20
+ function routeSegmentSpecificity(segment: string): number {
21
+ if (segment === "*") {
22
+ return 1;
23
+ }
24
+ if (segment.startsWith(":")) {
25
+ return 2;
26
+ }
27
+ return 3;
28
+ }
29
+
30
+ function compareSearchRouteSpecificity(a: string, b: string): number {
31
+ const aSegments = a.split("/").filter((segment) => segment.length > 0);
32
+ const bSegments = b.split("/").filter((segment) => segment.length > 0);
33
+ const length = Math.max(aSegments.length, bSegments.length);
34
+ for (let i = 0; i < length; i++) {
35
+ const aSegment = aSegments[i];
36
+ const bSegment = bSegments[i];
37
+ if (aSegment === undefined) {
38
+ return -1;
39
+ }
40
+ if (bSegment === undefined) {
41
+ return 1;
42
+ }
43
+ const diff = routeSegmentSpecificity(aSegment) - routeSegmentSpecificity(bSegment);
44
+ if (diff !== 0) {
45
+ return diff;
46
+ }
47
+ }
48
+ return 0;
49
+ }
50
+
51
+ function isObject(value: unknown): value is { [key: string]: unknown } {
52
+ return !!value && typeof value === "object" && !Array.isArray(value);
53
+ }
54
+
55
+ function arraysDeepEqual(a: unknown[], b: unknown[]): boolean {
56
+ if (a.length !== b.length) {
57
+ return false;
58
+ }
59
+ for (let i = 0; i < a.length; i++) {
60
+ if (!deepEqual(a[i], b[i])) {
61
+ return false;
62
+ }
63
+ }
64
+ return true;
65
+ }
66
+
67
+ function objectsDeepEqual(a: { [key: string]: unknown }, b: { [key: string]: unknown }): boolean {
68
+ const aKeys = Object.keys(a);
69
+ if (aKeys.length !== Object.keys(b).length) {
70
+ return false;
71
+ }
72
+ for (const key of aKeys) {
73
+ if (!(Object.hasOwn(b, key) && deepEqual(a[key], b[key]))) {
74
+ return false;
75
+ }
76
+ }
77
+ return true;
78
+ }
79
+
80
+ function deepEqual(a: unknown, b: unknown): boolean {
81
+ if (Object.is(a, b)) {
82
+ return true;
83
+ }
84
+ if (Array.isArray(a) && Array.isArray(b)) {
85
+ return arraysDeepEqual(a, b);
86
+ }
87
+ if (isObject(a) && isObject(b)) {
88
+ return objectsDeepEqual(a, b);
89
+ }
90
+ return false;
91
+ }
92
+
93
+ export function stripSearchDefaults(
94
+ search: SearchParamsInput,
95
+ defaults: SearchParamsInput | undefined
96
+ ): SearchParamsInput {
97
+ if (!defaults) {
98
+ return search;
99
+ }
100
+ const stripped: SearchParamsInput = {};
101
+ for (const [key, value] of Object.entries(search)) {
102
+ if (Object.hasOwn(defaults, key) && deepEqual(value, defaults[key])) {
103
+ continue;
104
+ }
105
+ stripped[key] = value;
106
+ }
107
+ return stripped;
108
+ }
109
+
110
+ export function appendSearchParamValue(params: URLSearchParams, key: string, value: unknown): void {
111
+ if (value == null) {
112
+ return;
113
+ }
114
+
115
+ if (Array.isArray(value)) {
116
+ for (const item of value) {
117
+ if (item != null) {
118
+ params.append(key, typeof item === "object" ? JSON.stringify(item) : String(item));
119
+ }
120
+ }
121
+ return;
122
+ }
123
+
124
+ params.set(key, typeof value === "object" ? JSON.stringify(value) : String(value));
125
+ }
126
+
127
+ export function buildSearchParams(
128
+ search: SearchParamsInput,
129
+ defaults?: SearchParamsInput
130
+ ): URLSearchParams {
131
+ const params = new URLSearchParams();
132
+ for (const [key, value] of Object.entries(stripSearchDefaults(search, defaults))) {
133
+ appendSearchParamValue(params, key, value);
134
+ }
135
+ return params;
136
+ }
137
+
138
+ export function collectSearchDefaults(schema: unknown): SearchParamsInput | undefined {
139
+ if (!(isObject(schema) && isObject(schema.properties))) {
140
+ return;
141
+ }
142
+
143
+ const defaults: SearchParamsInput = {};
144
+ for (const [key, value] of Object.entries(schema.properties)) {
145
+ if (isObject(value) && Object.hasOwn(value, "default") && value.default != null) {
146
+ defaults[key] = value.default as SearchParamValue;
147
+ }
148
+ }
149
+
150
+ return Object.keys(defaults).length > 0 ? defaults : undefined;
151
+ }
152
+
153
+ export function findSearchDefaults(
154
+ pathname: string,
155
+ routes: readonly SearchRouteMetadata[]
156
+ ): SearchParamsInput | undefined {
157
+ let match: SearchRouteMetadata | undefined;
158
+ for (const route of routes) {
159
+ if (!route.regex.test(pathname)) {
160
+ continue;
161
+ }
162
+ if (!match || compareSearchRouteSpecificity(route.pattern, match.pattern) > 0) {
163
+ match = route;
164
+ }
165
+ }
166
+ return match?.searchDefaults;
167
+ }
168
+
169
+ export function findSearchDefaultsForRouteTarget(
170
+ to: string,
171
+ routes: readonly SearchRouteMetadata[]
172
+ ): SearchParamsInput | undefined {
173
+ if (to.startsWith("http://") || to.startsWith("https://") || to.startsWith("//")) {
174
+ return;
175
+ }
176
+ try {
177
+ const pathname = new URL(to, "http://furin.local").pathname;
178
+ return findSearchDefaults(pathname, routes);
179
+ } catch {
180
+ return;
181
+ }
182
+ }
@@ -1,3 +0,0 @@
1
- import type { BuildAppOptions, TargetBuildManifest } from "../build/types.ts";
2
- import type { ResolvedRoute, RootLayout } from "../server/router/index.ts";
3
- export declare function buildBunTarget(routes: ResolvedRoute[], rootDir: string, buildRoot: string, root: RootLayout, serverEntry: string | null, options: BuildAppOptions): Promise<TargetBuildManifest>;
@@ -1,3 +0,0 @@
1
- import type { BuildAppOptions, StaticTargetBuildManifest } from "../build/types.ts";
2
- import type { ResolvedRoute, RootLayout } from "../server/router/index.ts";
3
- export declare function buildStaticTarget(routes: ResolvedRoute[], rootDir: string, buildRoot: string, root: RootLayout, options: BuildAppOptions): Promise<StaticTargetBuildManifest>;
@@ -1,25 +0,0 @@
1
- import type { ResolvedRoute } from "../server/router/index.ts";
2
- import type { BuildClientOptions } from "./types";
3
- export interface BuildClientResult {
4
- /** Public paths of all CSS chunks, e.g. `["/_client/chunk-abc.css"]` */
5
- cssChunks: string[];
6
- /** Public path of the JS entry chunk, e.g. `/_client/chunk-abc.js` */
7
- entryChunk: string;
8
- }
9
- /**
10
- * Builds the production client bundle via Bun.build() using _hydrate.tsx as
11
- * the JS entrypoint (NOT an HTML entrypoint). Bun produces:
12
- * <outDir>/client/chunk-*.js — code-split bundles
13
- * <outDir>/client/chunk-*.css — extracted CSS (if imported)
14
- *
15
- * Returns the chunk paths so the caller can compute a `buildId` and write
16
- * `index.html` with the correct meta tag. Using an HTML entrypoint with
17
- * code-splitting causes a Bun bug where the output index.html references a
18
- * leaf chunk instead of the actual entry chunk, preventing React from mounting
19
- * in production.
20
- *
21
- * The output index.html is NOT served to browsers directly. The server reads
22
- * it as an SSR template, injects the pre-rendered React HTML into
23
- * <!--ssr-outlet-->, and sends the complete page.
24
- */
25
- export declare function buildClient(routes: ResolvedRoute[], { outDir, rootLayout, plugins, publicPath, basePath, clientLogging }: BuildClientOptions): Promise<BuildClientResult>;
@@ -1,9 +0,0 @@
1
- import { type BuildEntryOptions } from "./entry-template";
2
- /**
3
- * Generates a single `_compile-entry.ts` that:
4
- * 1. Statically imports every page module so Bun bundles them into the binary
5
- * 2. Optionally embeds client assets via `with { type: "file" }` (embed mode)
6
- * 3. Sets production mode and registers everything in a single CompileContext
7
- * 4. Dynamically imports server.ts to boot the app
8
- */
9
- export declare function generateCompileEntry(options: BuildEntryOptions): string;