@teyik0/furin 0.4.0-alpha.2 → 0.5.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 (129) hide show
  1. package/dist/build/compile-entry.d.ts +2 -1
  2. package/dist/build/compile-entry.ts +17 -13
  3. package/dist/build/elysia-aot.d.ts +9 -0
  4. package/dist/build/entry-template.d.ts +5 -1
  5. package/dist/build/entry-template.ts +27 -6
  6. package/dist/build/index.js +969 -528
  7. package/dist/build/private-server-sourcemaps.d.ts +2 -0
  8. package/dist/build/server-app-entry.d.ts +12 -0
  9. package/dist/build/types.d.ts +2 -0
  10. package/dist/cache.d.ts +1 -0
  11. package/dist/cache.js +185 -0
  12. package/dist/cli/index.js +983 -541
  13. package/dist/client/document.d.ts +2 -0
  14. package/dist/client/internal/runtime-types.d.ts +8 -1
  15. package/dist/client/link.js +232 -11
  16. package/dist/client/sync.d.ts +1 -0
  17. package/dist/client.js +11 -0
  18. package/dist/config.d.ts +28 -22
  19. package/dist/config.js +25 -2
  20. package/dist/define-route.d.ts +273 -1009
  21. package/dist/furin.d.ts +20 -5
  22. package/dist/furin.js +6431 -5457
  23. package/dist/plugin/routes.d.ts +6 -0
  24. package/dist/rsc-client.js +9 -1
  25. package/dist/rsc.js +19 -7
  26. package/dist/server/assets/production.d.ts +3 -0
  27. package/dist/server/auto-invalidate/plugin.d.ts +8 -24
  28. package/dist/server/auto-invalidate/runtime.d.ts +2 -2
  29. package/dist/server/browser-events/shutdown.d.ts +3 -0
  30. package/dist/server/cache/invalidation.d.ts +1 -1
  31. package/dist/server/cache/page-cache-state.d.ts +5 -0
  32. package/dist/server/cache/page-cache.d.ts +53 -0
  33. package/dist/server/cache/redis/index.d.ts +41 -0
  34. package/dist/server/cache/redis/index.js +451 -0
  35. package/dist/server/cache/redis/scripts.d.ts +6 -0
  36. package/dist/server/context-logger.d.ts +2 -2
  37. package/dist/server/dev/plugin.d.ts +1 -0
  38. package/dist/server/dev/runtime.production.d.ts +1 -0
  39. package/dist/server/dev-page-plugin.d.ts +7 -0
  40. package/dist/server/evlog.d.ts +14 -0
  41. package/dist/server/internal.d.ts +6 -0
  42. package/dist/server/internal.js +2539 -0
  43. package/dist/server/production-server.d.ts +13 -0
  44. package/dist/server/production-server.js +2906 -0
  45. package/dist/server/render/not-found.d.ts +1 -1
  46. package/dist/server/render/ssg.d.ts +5 -0
  47. package/dist/server/render/static-params.d.ts +4 -0
  48. package/dist/server/router/defined-route.d.ts +1 -1
  49. package/dist/server/router/hmr.d.ts +6 -0
  50. package/dist/server/router/hmr.production.d.ts +5 -0
  51. package/dist/server/router/plugin.d.ts +5 -1
  52. package/dist/server/router/schemas.d.ts +1 -0
  53. package/dist/server/sync/index.js +798 -117
  54. package/dist/server/sync/plugin.d.ts +31 -158
  55. package/dist/server/sync/stream.d.ts +38 -49
  56. package/dist/shared/elysia-contract.d.ts +8 -14
  57. package/dist/shared/production-build.d.ts +2 -0
  58. package/package.json +19 -8
  59. package/src/adapter/README.md +9 -2
  60. package/src/adapter/bun.ts +146 -41
  61. package/src/adapter/package.ts +6 -2
  62. package/src/adapter/runtime-build.ts +11 -4
  63. package/src/adapter/static.ts +8 -6
  64. package/src/adapter/vercel.ts +64 -31
  65. package/src/build/client.ts +18 -1
  66. package/src/build/compile-entry.ts +17 -13
  67. package/src/build/elysia-aot.ts +102 -0
  68. package/src/build/entry-template.ts +27 -6
  69. package/src/build/hydrate.ts +5 -1
  70. package/src/build/index.ts +5 -5
  71. package/src/build/private-server-sourcemaps.ts +20 -0
  72. package/src/build/production-instrumentation.ts +2 -2
  73. package/src/build/server-app-entry.ts +61 -0
  74. package/src/build/shared.ts +3 -1
  75. package/src/build/ssg-cache.ts +5 -10
  76. package/src/build/types.ts +2 -0
  77. package/src/build/virtual-entry.ts +5 -4
  78. package/src/cache.ts +12 -0
  79. package/src/cli/config.ts +3 -3
  80. package/src/cli/index.ts +6 -2
  81. package/src/client/document.tsx +19 -0
  82. package/src/client/internal/runtime-types.ts +10 -1
  83. package/src/client/sync.ts +1 -0
  84. package/src/config.ts +33 -4
  85. package/src/define-route.ts +266 -128
  86. package/src/furin.ts +168 -154
  87. package/src/plugin/route-config-autofix.ts +11 -2
  88. package/src/plugin/routes.ts +85 -29
  89. package/src/rsc/codec.ts +11 -6
  90. package/src/rsc/render-error.ts +3 -1
  91. package/src/server/assets/production.ts +99 -0
  92. package/src/server/auto-invalidate/plugin.ts +4 -4
  93. package/src/server/auto-invalidate/runtime.ts +74 -42
  94. package/src/server/browser-events/plugin.ts +13 -1
  95. package/src/server/browser-events/shutdown.ts +32 -0
  96. package/src/server/cache/invalidation.ts +61 -20
  97. package/src/server/cache/page-cache-state.ts +22 -0
  98. package/src/server/cache/page-cache.ts +300 -0
  99. package/src/server/cache/redis/index.ts +367 -0
  100. package/src/server/cache/redis/scripts.ts +200 -0
  101. package/src/server/context-logger.ts +5 -5
  102. package/src/server/dev/plugin.ts +10 -1
  103. package/src/server/dev/runtime.production.ts +4 -0
  104. package/src/server/dev-page-plugin.ts +54 -10
  105. package/src/server/evlog.ts +106 -0
  106. package/src/server/internal.ts +7 -0
  107. package/src/server/production-server.ts +135 -0
  108. package/src/server/render/document.tsx +7 -1
  109. package/src/server/render/isr.ts +480 -132
  110. package/src/server/render/loaders.ts +18 -12
  111. package/src/server/render/not-found.ts +4 -4
  112. package/src/server/render/ppr-document.ts +2 -2
  113. package/src/server/render/ppr-route.ts +193 -7
  114. package/src/server/render/ssg.ts +148 -4
  115. package/src/server/render/ssr.ts +6 -7
  116. package/src/server/render/static-params.ts +174 -0
  117. package/src/server/render/template.ts +5 -1
  118. package/src/server/router/defined-route.ts +2 -1
  119. package/src/server/router/discovery.ts +3 -1
  120. package/src/server/router/hmr.production.ts +11 -0
  121. package/src/server/router/hmr.ts +85 -76
  122. package/src/server/router/plugin.ts +118 -50
  123. package/src/server/router/schema-merge.ts +10 -3
  124. package/src/server/router/schemas.ts +174 -61
  125. package/src/server/sync/plugin.ts +14 -10
  126. package/src/server/sync/response.ts +3 -3
  127. package/src/server/sync/stream.ts +43 -2
  128. package/src/shared/elysia-contract.ts +23 -25
  129. package/src/shared/production-build.ts +20 -0
@@ -1,11 +1,11 @@
1
- import { type AnyElysia, type Context, Elysia, t } from "elysia";
1
+ import { type AnyElysia, type Context, Elysia, problem } from "elysia";
2
2
  import { toCrossJSONAsync } from "seroval";
3
3
  import type { HeadOptions } from "../../client.ts";
4
4
  import { computeErrorDigest } from "../../shared/digest.ts";
5
5
  import type { FurinSchema } from "../../shared/elysia-contract.ts";
6
6
  import { containsRscSource } from "../../shared/route-frame.ts";
7
7
  import type { SearchParamsInput, SearchRouteMetadata } from "../../shared/search-params.ts";
8
- import { useLogger } from "../context-logger.ts";
8
+ import { getLogger } from "../context-logger.ts";
9
9
  import {
10
10
  currentInstrumentationRequest,
11
11
  emitPayloadSerialized,
@@ -24,10 +24,10 @@ import {
24
24
  import { renderPprRoute, runPprPublicLoaders } from "../render/ppr-route.ts";
25
25
  import { createDeferredRouteFrameStream } from "../render/route-frame-transport.ts";
26
26
  import { extractTitle } from "../render/shell.ts";
27
- import { prerenderRoute, prerenderSSG } from "../render/ssg.ts";
27
+ import { prerenderRoute, prerenderRuntimeSSG } from "../render/ssg.ts";
28
28
  import { renderSSR, serializeLoaderDataNdjson } from "../render/ssr.ts";
29
29
  import { IS_DEV } from "../runtime-env.ts";
30
- import { handleDevRequest } from "./hmr.ts";
30
+ import { handleDevRequest, reportDevRouteFailure } from "./hmr.ts";
31
31
  import { buildRouteMatcher, resolveRouteRevalidate } from "./patterns.ts";
32
32
  import { mergeRouteSchemas } from "./schema-merge.ts";
33
33
  import {
@@ -43,6 +43,12 @@ const MAX_NAVIGATION_HEAD_BYTES = 64 * 1024;
43
43
  type DataResolvedRoutesSource =
44
44
  | ResolvedRoutesSource
45
45
  | ((request: Request) => Promise<ResolvedRoute[]>);
46
+ type RefreshDevRoute = (
47
+ route: ResolvedRoute
48
+ ) => Promise<{ route: ResolvedRoute; root: RootLayout }>;
49
+ type DataRouteResolver = (
50
+ route: ResolvedRoute
51
+ ) => Promise<{ route: ResolvedRoute; root: RootLayout | undefined }>;
46
52
 
47
53
  interface DataRouteParamsInput {
48
54
  [key: string]: unknown;
@@ -207,6 +213,48 @@ async function createRouteDataErrorResponse(
207
213
  });
208
214
  }
209
215
 
216
+ async function resolveDataRoute(
217
+ route: ResolvedRoute,
218
+ resolveRoute: DataRouteResolver
219
+ ): Promise<{ route: ResolvedRoute; root: RootLayout | undefined } | Response> {
220
+ try {
221
+ return await resolveRoute(route);
222
+ } catch (error) {
223
+ getLogger().error(error instanceof Error ? error : new Error(String(error)));
224
+ if (IS_DEV) {
225
+ reportDevRouteFailure(error, route);
226
+ }
227
+ return createRouteDataErrorResponse(error, "Something went wrong", 500, undefined);
228
+ }
229
+ }
230
+
231
+ async function resolveDataRoutes(
232
+ routesSource: DataResolvedRoutesSource,
233
+ request: Request
234
+ ): Promise<ResolvedRoute[] | Response> {
235
+ try {
236
+ return typeof routesSource === "function" ? await routesSource(request) : routesSource;
237
+ } catch (error) {
238
+ getLogger().error(error instanceof Error ? error : new Error(String(error)));
239
+ return createRouteDataErrorResponse(error, "Something went wrong", 500, undefined);
240
+ }
241
+ }
242
+
243
+ function resolvedSearchRoutes(
244
+ routes: ResolvedRoute[],
245
+ matchedRoute: ResolvedRoute,
246
+ currentRoute: ResolvedRoute,
247
+ searchRoutes: SearchRouteMetadata[],
248
+ refreshDevRoute: RefreshDevRoute | undefined
249
+ ): SearchRouteMetadata[] {
250
+ if (refreshDevRoute === undefined) {
251
+ return searchRoutes;
252
+ }
253
+ return createSearchRouteMetadata(
254
+ routes.map((route) => (route === matchedRoute ? currentRoute : route))
255
+ );
256
+ }
257
+
210
258
  /** @internal Handles a production SSG route — sets ETags, Cache-Control, and Cache-Tag. */
211
259
  async function handleSSGRequest(
212
260
  route: ResolvedRoute,
@@ -217,9 +265,23 @@ async function handleSSGRequest(
217
265
  ): Promise<unknown> {
218
266
  const { origin } = new URL(ctx.request.url);
219
267
  const params = ctx.params ?? {};
220
- const entry = isExternalPrerenderRequest(ctx.request)
221
- ? await prerenderRoute(route, params, root, origin, "ssg", undefined, searchRoutes, ctx)
222
- : await prerenderSSG(route, params, root, origin, undefined, searchRoutes);
268
+ const externalPrerender = isExternalPrerenderRequest(ctx.request);
269
+ const runtimeResult = externalPrerender
270
+ ? {
271
+ cacheStored: true,
272
+ entry: await prerenderRoute(
273
+ route,
274
+ params,
275
+ root,
276
+ origin,
277
+ "ssg",
278
+ undefined,
279
+ searchRoutes,
280
+ ctx
281
+ ),
282
+ }
283
+ : await prerenderRuntimeSSG(route, params, root, origin, buildId, searchRoutes);
284
+ const { cacheStored, entry } = runtimeResult;
223
285
 
224
286
  // Loader issued a redirect — forward it directly to the client.
225
287
  if (entry instanceof Response) {
@@ -238,7 +300,9 @@ async function handleSSGRequest(
238
300
  ctx.set.headers["content-type"] = "text/html; charset=utf-8";
239
301
  // Browser: max-age=0 + must-revalidate → always validates via ETag (304 = free)
240
302
  // CDN: s-maxage=31536000 → cache for 1 year, purge via revalidatePath + purger
241
- ctx.set.headers["cache-control"] = "public, max-age=0, must-revalidate, s-maxage=31536000";
303
+ ctx.set.headers["cache-control"] = cacheStored
304
+ ? "public, max-age=0, must-revalidate, s-maxage=31536000"
305
+ : "no-store";
242
306
  if (etag) {
243
307
  ctx.set.headers.etag = etag;
244
308
  }
@@ -255,21 +319,20 @@ export function createRoutePlugin(
255
319
  const resolvedBuildId = buildId ?? "";
256
320
  const { pattern, routeChain } = route;
257
321
 
258
- const allParams = mergeRouteSchemas(routeChain, "params");
259
- const allQuery = mergeRouteSchemas(routeChain, "query");
260
-
261
- // Guard and handler MUST live in the same Elysia scope so that validation
262
- // (including default-filling) applies to the route handler's ctx.query.
263
- const plugin = new Elysia();
264
-
265
- if (allParams || allQuery) {
266
- plugin.guard({
267
- params: allParams as FurinSchema,
268
- query: allQuery as FurinSchema,
322
+ // Keep every route-chain schema in Elysia's native merge pipeline so its
323
+ // coercion and default semantics remain authoritative for document requests.
324
+ const plugin = routeChain.reduce<AnyElysia>((app, entry) => {
325
+ if (!(entry.params || entry.query)) {
326
+ return app;
327
+ }
328
+ return app.guard({
329
+ params: entry.params as FurinSchema,
330
+ query: entry.query as FurinSchema,
331
+ schema: "merge",
269
332
  });
270
- }
333
+ }, new Elysia());
271
334
 
272
- plugin.get(pattern, (ctx) =>
335
+ plugin.get(pattern, (ctx: Context) =>
273
336
  renderResolvedRoute(route, ctx, root, resolvedBuildId, searchRoutes)
274
337
  );
275
338
 
@@ -321,24 +384,30 @@ export function renderResolvedRoute(
321
384
  */
322
385
  export function createDataEndpoint(
323
386
  routesSource: DataResolvedRoutesSource,
324
- root?: RootLayout
387
+ root?: RootLayout,
388
+ refreshDevRoute?: RefreshDevRoute
325
389
  ): AnyElysia {
326
390
  const plugin = new Elysia();
327
391
  let matchedRoutes = Array.isArray(routesSource) ? routesSource : [];
328
392
  let matchRoute = buildRouteMatcher(matchedRoutes);
329
393
  let searchRoutes = createSearchRouteMetadata(matchedRoutes);
394
+ const resolveRoute: DataRouteResolver =
395
+ refreshDevRoute ?? ((route: ResolvedRoute) => Promise.resolve({ root, route }));
330
396
 
331
397
  plugin.get(
332
398
  "/_furin/data",
399
+ {
400
+ // The transport path is validated below without requiring a TypeBox schema.
401
+ },
333
402
  async (ctx) => {
334
403
  const rawPath = ctx.query.path;
335
404
  if (!rawPath || typeof rawPath !== "string") {
336
- return new Response("Missing required query param: path", { status: 400 });
405
+ return problem("Bad Request", { detail: "Missing required query param: path" });
337
406
  }
338
407
 
339
408
  const parsed = parseDataEndpointPath(rawPath);
340
409
  if (!parsed) {
341
- return new Response("Invalid path", { status: 400 });
410
+ return problem("Bad Request", { detail: "Invalid path" });
342
411
  }
343
412
  const { url, pathname } = parsed;
344
413
 
@@ -347,16 +416,12 @@ export function createDataEndpoint(
347
416
  // instead of the technical "/_furin/data" transport URL. We set this
348
417
  // before the route-match check so 404s also surface the attempted path
349
418
  // — otherwise monitoring just sees "GET /_furin/data 404" with no clue.
350
- const wideEventLog = useLogger();
419
+ const wideEventLog = getLogger();
351
420
  wideEventLog.set({ path: rawPath });
352
421
 
353
- let currentRoutes: ResolvedRoute[];
354
- try {
355
- currentRoutes =
356
- typeof routesSource === "function" ? await routesSource(ctx.request) : routesSource;
357
- } catch (error) {
358
- wideEventLog.error(error instanceof Error ? error : new Error(String(error)));
359
- return createRouteDataErrorResponse(error, "Something went wrong", 500, undefined);
422
+ const currentRoutes = await resolveDataRoutes(routesSource, ctx.request);
423
+ if (currentRoutes instanceof Response) {
424
+ return currentRoutes;
360
425
  }
361
426
  if (currentRoutes !== matchedRoutes) {
362
427
  matchedRoutes = currentRoutes;
@@ -366,13 +431,25 @@ export function createDataEndpoint(
366
431
  const matched = matchRoute(pathname);
367
432
 
368
433
  if (!matched) {
369
- return new Response("Route not found", { status: 404 });
434
+ return problem("Not Found", { detail: "Route not found" });
370
435
  }
371
436
 
372
437
  // Now that we know the matched pattern, add it as a stable aggregation
373
438
  // key for drains (e.g. "p99 latency by route").
374
439
  wideEventLog.set({ routePattern: matched.route.pattern });
375
440
 
441
+ const current = await resolveDataRoute(matched.route, resolveRoute);
442
+ if (current instanceof Response) {
443
+ return current;
444
+ }
445
+ const currentSearchRoutes = resolvedSearchRoutes(
446
+ matchedRoutes,
447
+ matched.route,
448
+ current.route,
449
+ searchRoutes,
450
+ refreshDevRoute
451
+ );
452
+
376
453
  // Build a synthetic Elysia-compatible context for the matched route.
377
454
  // Loaders receive request, params, query, set, headers, and cookie.
378
455
  // Build the synthetic URL from the parsed `pathname + search` only —
@@ -406,36 +483,27 @@ export function createDataEndpoint(
406
483
 
407
484
  // Normalize params and query through the route chain schemas so SPA and
408
485
  // document requests expose identical typed/defaulted inputs.
409
- const mergedParams = mergeRouteSchemas(matched.route.routeChain, "params");
410
- const mergedQuery = mergeRouteSchemas(matched.route.routeChain, "query");
486
+ const mergedParams = mergeRouteSchemas(current.route.routeChain, "params");
487
+ const mergedQuery = mergeRouteSchemas(current.route.routeChain, "query");
411
488
  const parsedParams = await parseRouteParams(matched.params, mergedParams);
412
489
  if (!parsedParams.ok) {
413
- return Response.json(
414
- { errors: parsedParams.errors, message: "Invalid params", type: "validation" },
415
- { status: 422 }
416
- );
490
+ return problem(422, { detail: "Invalid params", errors: parsedParams.errors });
417
491
  }
418
492
  const parsedQuery = await parseRouteQuery(url, mergedQuery);
419
493
  if (!parsedQuery.ok) {
420
- return Response.json(
421
- { errors: parsedQuery.errors, message: "Invalid query", type: "validation" },
422
- { status: 422 }
423
- );
494
+ return problem(422, { detail: "Invalid query", errors: parsedQuery.errors });
424
495
  }
425
496
  syntheticCtx.params = parsedParams.params;
426
497
  syntheticCtx.query = parsedQuery.query as SearchParamsInput;
427
498
 
428
499
  const result = await runDataEndpointLoaders(
429
- matched.route,
500
+ current.route,
430
501
  syntheticCtx as unknown as Context,
431
- root,
432
- searchRoutes
502
+ current.root,
503
+ currentSearchRoutes
433
504
  );
434
505
 
435
- return createLoaderDataResponse(result, matched.route, syntheticRequest.url, syntheticCtx);
436
- },
437
- {
438
- query: t.Object({ path: t.Optional(t.String()) }),
506
+ return createLoaderDataResponse(result, current.route, syntheticRequest.url, syntheticCtx);
439
507
  }
440
508
  );
441
509
 
@@ -1,4 +1,3 @@
1
- import { t } from "elysia";
2
1
  import type { RuntimeRoute } from "../../client/internal/runtime-types.ts";
3
2
  import { type FurinSchema, isTypeBoxObjectSchema } from "../../shared/elysia-contract.ts";
4
3
 
@@ -7,6 +6,7 @@ interface SchemaObject {
7
6
  }
8
7
 
9
8
  const TOBJECT_STRUCTURAL_KEYS = new Set(["type", "properties", "required"]);
9
+ const TYPEBOX_OPTIONAL = Symbol.for("TypeBox.Optional");
10
10
  export function mergeRouteSchemas(
11
11
  routeChain: RuntimeRoute[],
12
12
  key: "params" | "query"
@@ -21,7 +21,7 @@ export function mergeRouteSchemas(
21
21
  }
22
22
  if (schemas.some((schema) => !isTypeBoxObjectSchema(schema))) {
23
23
  throw new Error(
24
- `[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.`
24
+ `[furin] Merging ${key} schemas across the route chain requires TypeBox object schemas. Use TypeBox for parent/child ${key}, or define ${key} only on leaf routes.`
25
25
  );
26
26
  }
27
27
 
@@ -38,5 +38,12 @@ export function mergeRouteSchemas(
38
38
  )
39
39
  );
40
40
 
41
- return t.Object(properties, options) as FurinSchema;
41
+ // Match t.Object's schema shape without importing TypeBox into schema-free bundles.
42
+ const required = Object.keys(properties).filter((name) => {
43
+ const property = properties[name] as SchemaObject & { [symbolName: symbol]: unknown };
44
+ return !(property["~optional"] || property[TYPEBOX_OPTIONAL]);
45
+ });
46
+ return Object.defineProperty({ ...options, properties, required, type: "object" }, "~kind", {
47
+ value: "Object",
48
+ }) as FurinSchema;
42
49
  }
@@ -1,10 +1,5 @@
1
1
  import type { RuntimeRoute } from "../../client/internal/runtime-types.ts";
2
- import {
3
- type FurinSchema,
4
- getSchemaValidator,
5
- parseQueryFromURL,
6
- parseQueryStandardSchema,
7
- } from "../../shared/elysia-contract.ts";
2
+ import { type FurinSchema, getSchemaValidator } from "../../shared/elysia-contract.ts";
8
3
  import {
9
4
  collectSearchDefaults,
10
5
  type SearchParamsInput,
@@ -22,6 +17,59 @@ interface QueryKeyMap {
22
17
  [key: string]: 1;
23
18
  }
24
19
 
20
+ function decodeQueryPart(value: string): string {
21
+ return new URLSearchParams(`value=${value}`).get("value") ?? "";
22
+ }
23
+
24
+ function parseArrayQueryValue(raw: string, decoded: string, repeated: boolean): string[] {
25
+ const rawBracketed = raw.startsWith("[") && raw.endsWith("]");
26
+ const decodedBracketed = decoded.startsWith("[") && decoded.endsWith("]");
27
+ if (repeated && !rawBracketed && !decodedBracketed) {
28
+ return [decoded];
29
+ }
30
+ if (decoded === "[]") {
31
+ return [];
32
+ }
33
+ if (rawBracketed) {
34
+ return raw.slice(1, -1).split(",").map(decodeQueryPart);
35
+ }
36
+ if (decodedBracketed) {
37
+ return decoded.slice(1, -1).split(",");
38
+ }
39
+ return raw.includes(",") ? raw.split(",").map(decodeQueryPart) : [decoded];
40
+ }
41
+
42
+ function parseQueryFromURL(search: string, arrayKeys?: QueryKeyMap): UnknownObject {
43
+ const query: UnknownObject = Object.create(null);
44
+ if (!arrayKeys) {
45
+ for (const [key, value] of new URLSearchParams(search)) {
46
+ query[key] = value;
47
+ }
48
+ return query;
49
+ }
50
+ for (const pair of search.slice(1).split("&")) {
51
+ const entry = new URLSearchParams(pair).entries().next().value;
52
+ if (!entry) {
53
+ continue;
54
+ }
55
+ const [key, value] = entry;
56
+ if (!arrayKeys[key]) {
57
+ query[key] = value;
58
+ continue;
59
+ }
60
+ const equalIndex = pair.indexOf("=");
61
+ const rawValue = equalIndex === -1 ? "" : pair.slice(equalIndex + 1);
62
+ const previous = query[key];
63
+ const values = parseArrayQueryValue(rawValue, value, Array.isArray(previous));
64
+ if (Array.isArray(previous)) {
65
+ previous.push(...values);
66
+ } else {
67
+ query[key] = values;
68
+ }
69
+ }
70
+ return query;
71
+ }
72
+
25
73
  /**
26
74
  * Parses the `?path=` argument of `/_furin/data`, rejecting absolute /
27
75
  * protocol-relative inputs that would let a caller smuggle a foreign origin
@@ -60,50 +108,54 @@ function isStandardSchema(schema: unknown): boolean {
60
108
  }
61
109
 
62
110
  function collectQueryArrayKeys(schema: unknown): QueryKeyMap | undefined {
63
- if (!(isObjectSchema(schema) && isObjectSchema(schema.properties))) {
64
- return;
65
- }
66
-
67
- const keys: QueryKeyMap = {};
68
- for (const [key, value] of Object.entries(schema.properties)) {
69
- const effectiveSchema = findEffectiveAnyOfMember(value, "array") ?? value;
70
- if (isObjectSchema(effectiveSchema) && effectiveSchema.type === "array") {
71
- keys[key] = 1;
72
- }
73
- }
74
-
75
- return Object.keys(keys).length > 0 ? keys : undefined;
111
+ return collectQueryKeys(schema, "array");
76
112
  }
77
113
 
78
114
  function collectQueryObjectKeys(schema: unknown): QueryKeyMap | undefined {
79
- if (!(isObjectSchema(schema) && isObjectSchema(schema.properties))) {
115
+ return collectQueryKeys(schema, "object");
116
+ }
117
+
118
+ function collectQueryKeys(schema: unknown, type: "array" | "object"): QueryKeyMap | undefined {
119
+ if (!isObjectSchema(schema)) {
80
120
  return;
81
121
  }
82
122
 
83
123
  const keys: QueryKeyMap = {};
84
- for (const [key, value] of Object.entries(schema.properties)) {
85
- const effectiveSchema = findEffectiveAnyOfMember(value, "object") ?? value;
86
- if (isObjectSchema(effectiveSchema) && effectiveSchema.type === "object") {
87
- keys[key] = 1;
124
+ if (isObjectSchema(schema.properties)) {
125
+ for (const [key, value] of Object.entries(schema.properties)) {
126
+ if (hasSchemaType(value, type)) {
127
+ keys[key] = 1;
128
+ }
129
+ }
130
+ }
131
+
132
+ for (const keyword of ["allOf", "anyOf"] as const) {
133
+ const members = schema[keyword];
134
+ if (!Array.isArray(members)) {
135
+ continue;
136
+ }
137
+ for (const member of members) {
138
+ Object.assign(keys, collectQueryKeys(member, type));
88
139
  }
89
140
  }
90
141
 
91
142
  return Object.keys(keys).length > 0 ? keys : undefined;
92
143
  }
93
144
 
94
- function findEffectiveAnyOfMember(
95
- schema: unknown,
96
- type: "array" | "object"
97
- ): UnknownObject | undefined {
98
- if (!(isObjectSchema(schema) && Array.isArray(schema.anyOf))) {
99
- return;
145
+ function hasSchemaType(schema: unknown, type: "array" | "object"): boolean {
146
+ if (!isObjectSchema(schema)) {
147
+ return false;
100
148
  }
101
-
102
- for (const member of schema.anyOf) {
103
- if (isObjectSchema(member) && member.type === type) {
104
- return member;
149
+ if (schema.type === type) {
150
+ return true;
151
+ }
152
+ for (const keyword of ["allOf", "anyOf"] as const) {
153
+ const members = schema[keyword];
154
+ if (Array.isArray(members) && members.some((member) => hasSchemaType(member, type))) {
155
+ return true;
105
156
  }
106
157
  }
158
+ return false;
107
159
  }
108
160
 
109
161
  function parseJsonQueryObjects(
@@ -129,6 +181,72 @@ function parseJsonQueryObjects(
129
181
  return parsed;
130
182
  }
131
183
 
184
+ function coerceUnionValue(members: unknown[], value: unknown): unknown {
185
+ for (const member of members) {
186
+ const candidate = coerceSchemaValue(member, value);
187
+ const validator = getSchemaValidator(member as FurinSchema);
188
+ if (validator?.Check(candidate)) {
189
+ return candidate;
190
+ }
191
+ }
192
+ return value;
193
+ }
194
+
195
+ function coerceObjectValue(properties: UnknownObject, value: UnknownObject): UnknownObject {
196
+ const coerced = { ...value };
197
+ for (const [key, propertySchema] of Object.entries(properties)) {
198
+ if (key in coerced) {
199
+ coerced[key] = coerceSchemaValue(propertySchema, coerced[key]);
200
+ }
201
+ }
202
+ return coerced;
203
+ }
204
+
205
+ function coerceStringValue(schema: UnknownObject, value: string): unknown {
206
+ if (value.length === 0) {
207
+ return value;
208
+ }
209
+ if (schema.type === "boolean") {
210
+ if (value === "true") {
211
+ return true;
212
+ }
213
+ if (value === "false") {
214
+ return false;
215
+ }
216
+ return value;
217
+ }
218
+ if (schema.type === "number" || schema.type === "integer") {
219
+ const number = Number(value);
220
+ if (Number.isFinite(number) && (schema.type !== "integer" || Number.isInteger(number))) {
221
+ return number;
222
+ }
223
+ }
224
+ return value;
225
+ }
226
+
227
+ function coerceSchemaValue(schema: unknown, value: unknown): unknown {
228
+ if (!isObjectSchema(schema)) {
229
+ return value;
230
+ }
231
+ if (Array.isArray(schema.anyOf)) {
232
+ return coerceUnionValue(schema.anyOf, value);
233
+ }
234
+ if (Array.isArray(schema.allOf)) {
235
+ return schema.allOf.reduce((candidate, member) => coerceSchemaValue(member, candidate), value);
236
+ }
237
+ if (schema.type === "object" && isObjectSchema(schema.properties) && isObjectSchema(value)) {
238
+ return coerceObjectValue(schema.properties, value);
239
+ }
240
+ if (schema.type === "array" && Array.isArray(value)) {
241
+ return value.map((entry) => coerceSchemaValue(schema.items, entry));
242
+ }
243
+ return typeof value === "string" ? coerceStringValue(schema, value) : value;
244
+ }
245
+
246
+ export function coerceRouteInput(schema: FurinSchema, value: UnknownObject): UnknownObject {
247
+ return coerceSchemaValue(schema, value) as UnknownObject;
248
+ }
249
+
132
250
  export type ParseRouteQueryResult =
133
251
  | { ok: true; query: SearchParamsInput }
134
252
  | { errors: unknown; ok: false };
@@ -143,30 +261,25 @@ type RouteInputValidationResult =
143
261
 
144
262
  async function validateRouteInput(
145
263
  input: UnknownObject,
146
- schema: FurinSchema
264
+ schema: FurinSchema,
265
+ type: "params" | "query"
147
266
  ): Promise<RouteInputValidationResult> {
148
- if (isStandardSchema(schema)) {
149
- const validator = getSchemaValidator(schema, { dynamic: true });
150
- const checked = await validator?.Check(input);
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, value: checked.value as UnknownObject };
156
- }
157
- return { ok: true, value: input };
158
- }
159
-
160
- const inputWithDefaults = applySchemaDefaults(schema as UnknownObject, input);
161
- const validator = getSchemaValidator(schema, { coerce: true, dynamic: true });
162
- if (validator?.Check(inputWithDefaults) === false) {
163
- return { errors: [...(validator?.Errors(inputWithDefaults) ?? [])], ok: false };
267
+ const inputWithDefaults = isStandardSchema(schema)
268
+ ? input
269
+ : applySchemaDefaults(schema as UnknownObject, input);
270
+ const valueToValidate = isStandardSchema(schema)
271
+ ? inputWithDefaults
272
+ : coerceRouteInput(schema, inputWithDefaults);
273
+ const validator = getSchemaValidator(schema);
274
+ try {
275
+ const parsed = await validator?.parse(valueToValidate, type);
276
+ return {
277
+ ok: true,
278
+ value: (parsed ?? valueToValidate) as UnknownObject,
279
+ };
280
+ } catch {
281
+ return { errors: [...(validator?.Errors(valueToValidate) ?? [])], ok: false };
164
282
  }
165
-
166
- return {
167
- ok: true,
168
- value: (validator?.parse(inputWithDefaults) ?? inputWithDefaults) as UnknownObject,
169
- };
170
283
  }
171
284
 
172
285
  /**
@@ -181,16 +294,16 @@ export async function parseRouteQuery(
181
294
  schema: FurinSchema | undefined
182
295
  ): Promise<ParseRouteQueryResult> {
183
296
  if (!schema) {
184
- return { ok: true, query: parseQueryFromURL(url.search, 1) as SearchParamsInput };
297
+ return { ok: true, query: parseQueryFromURL(url.search) as SearchParamsInput };
185
298
  }
186
299
 
187
300
  const rawQuery = isStandardSchema(schema)
188
- ? (parseQueryStandardSchema(url.search, 1) as UnknownObject)
301
+ ? parseQueryFromURL(url.search)
189
302
  : parseJsonQueryObjects(
190
- parseQueryFromURL(url.search, 1, collectQueryArrayKeys(schema)) as UnknownObject,
303
+ parseQueryFromURL(url.search, collectQueryArrayKeys(schema)),
191
304
  collectQueryObjectKeys(schema)
192
305
  );
193
- const result = await validateRouteInput(rawQuery, schema);
306
+ const result = await validateRouteInput(rawQuery, schema, "query");
194
307
  return result.ok ? { ok: true, query: result.value as SearchParamsInput } : result;
195
308
  }
196
309
 
@@ -209,7 +322,7 @@ export async function parseRouteParams(
209
322
  return { ok: true, params };
210
323
  }
211
324
 
212
- const result = await validateRouteInput(params, schema);
325
+ const result = await validateRouteInput(params, schema, "params");
213
326
  return result.ok ? { ok: true, params: result.value } : result;
214
327
  }
215
328
 
@@ -6,6 +6,7 @@ import {
6
6
  } from "../auto-invalidate/runtime.ts";
7
7
  import type { InvalidationInput } from "../auto-invalidate/types.ts";
8
8
  import { peekPendingInvalidations } from "../cache/invalidation.ts";
9
+ import { getLogger } from "../context-logger.ts";
9
10
  import type { MutationLease, SyncInvalidation, SyncRuntimeOptions } from "./adapter.ts";
10
11
  import { createMutationFingerprint } from "./fingerprint.ts";
11
12
  import { mergeStoredResponseHeaders, replayResponse, storeResponse } from "./response.ts";
@@ -41,11 +42,7 @@ interface MutationContext {
41
42
 
42
43
  type TransportHook<TContext> = (context: TContext) => Promise<void>;
43
44
 
44
- type CompletionContext = MutationContext &
45
- Pick<Context, "set"> & {
46
- response?: unknown;
47
- responseValue?: unknown;
48
- };
45
+ type CompletionContext = MutationContext & Parameters<typeof isSuccessfulMutationResponse>[0];
49
46
  type PathInvalidation = Extract<SyncInvalidation, { kind: "path" }>;
50
47
 
51
48
  const routeMetadata = new WeakMap<Request, RouteSyncMetadata>();
@@ -213,8 +210,15 @@ export function furinSync(options: SyncRuntimeOptions) {
213
210
  const result = await storeResponse(ctx.responseValue, ctx.set);
214
211
  const manualPending = peekPendingInvalidations();
215
212
  const invalidate = routeMetadata.get(ctx.request)?.invalidate;
213
+ const logger = getLogger();
216
214
  if (invalidate) {
217
- runInvalidationRules(invalidate);
215
+ try {
216
+ await runInvalidationRules(invalidate);
217
+ } catch {
218
+ logger.warn(
219
+ "Sync cache invalidation failed after mutation; preserving the idempotent result"
220
+ );
221
+ }
218
222
  }
219
223
  const pending = appendPendingInvalidationHeader(ctx.set);
220
224
  if (pending.length > 0) {
@@ -277,6 +281,9 @@ export function furinSync(options: SyncRuntimeOptions) {
277
281
  const finishMutationHook = hideTransportResponse(finishMutation);
278
282
 
279
283
  return new Elysia({ name: "furin-sync" })
284
+ .beforeHandle("global", beginMutationHook)
285
+ .afterHandle("global", finishMutationHook)
286
+ .error("global", ({ request }) => abortMutation(request))
280
287
  .macro({
281
288
  sync(input: SyncRouteOption) {
282
289
  return {
@@ -290,8 +297,5 @@ export function furinSync(options: SyncRuntimeOptions) {
290
297
  },
291
298
  };
292
299
  },
293
- })
294
- .onBeforeHandle({ as: "global" }, beginMutationHook)
295
- .onAfterHandle({ as: "global" }, finishMutationHook)
296
- .onError({ as: "global" }, ({ request }) => abortMutation(request));
300
+ });
297
301
  }