@fragno-dev/core 0.1.11 → 0.2.0

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/.turbo/turbo-build.log +50 -42
  2. package/CHANGELOG.md +51 -0
  3. package/dist/api/api.d.ts +19 -1
  4. package/dist/api/api.d.ts.map +1 -1
  5. package/dist/api/api.js.map +1 -1
  6. package/dist/api/fragment-definition-builder.d.ts +17 -7
  7. package/dist/api/fragment-definition-builder.d.ts.map +1 -1
  8. package/dist/api/fragment-definition-builder.js +3 -2
  9. package/dist/api/fragment-definition-builder.js.map +1 -1
  10. package/dist/api/fragment-instantiator.d.ts +23 -16
  11. package/dist/api/fragment-instantiator.d.ts.map +1 -1
  12. package/dist/api/fragment-instantiator.js +163 -19
  13. package/dist/api/fragment-instantiator.js.map +1 -1
  14. package/dist/api/request-input-context.d.ts +57 -1
  15. package/dist/api/request-input-context.d.ts.map +1 -1
  16. package/dist/api/request-input-context.js +67 -0
  17. package/dist/api/request-input-context.js.map +1 -1
  18. package/dist/api/request-middleware.d.ts +1 -1
  19. package/dist/api/request-middleware.d.ts.map +1 -1
  20. package/dist/api/request-middleware.js.map +1 -1
  21. package/dist/api/route.d.ts +7 -7
  22. package/dist/api/route.d.ts.map +1 -1
  23. package/dist/api/route.js.map +1 -1
  24. package/dist/client/client.d.ts +4 -3
  25. package/dist/client/client.d.ts.map +1 -1
  26. package/dist/client/client.js +103 -7
  27. package/dist/client/client.js.map +1 -1
  28. package/dist/client/vue.d.ts +7 -3
  29. package/dist/client/vue.d.ts.map +1 -1
  30. package/dist/client/vue.js +16 -1
  31. package/dist/client/vue.js.map +1 -1
  32. package/dist/internal/trace-context.d.ts +23 -0
  33. package/dist/internal/trace-context.d.ts.map +1 -0
  34. package/dist/internal/trace-context.js +14 -0
  35. package/dist/internal/trace-context.js.map +1 -0
  36. package/dist/mod-client.d.ts +3 -17
  37. package/dist/mod-client.d.ts.map +1 -1
  38. package/dist/mod-client.js +20 -10
  39. package/dist/mod-client.js.map +1 -1
  40. package/dist/mod.d.ts +3 -2
  41. package/dist/mod.js +2 -1
  42. package/dist/runtime.d.ts +15 -0
  43. package/dist/runtime.d.ts.map +1 -0
  44. package/dist/runtime.js +33 -0
  45. package/dist/runtime.js.map +1 -0
  46. package/dist/test/test.d.ts +2 -2
  47. package/dist/test/test.d.ts.map +1 -1
  48. package/dist/test/test.js.map +1 -1
  49. package/package.json +23 -17
  50. package/src/api/api.ts +22 -0
  51. package/src/api/fragment-definition-builder.ts +36 -17
  52. package/src/api/fragment-instantiator.test.ts +286 -0
  53. package/src/api/fragment-instantiator.ts +338 -31
  54. package/src/api/internal/path-runtime.test.ts +7 -0
  55. package/src/api/request-input-context.test.ts +152 -0
  56. package/src/api/request-input-context.ts +85 -0
  57. package/src/api/request-middleware.test.ts +47 -1
  58. package/src/api/request-middleware.ts +1 -1
  59. package/src/api/route.ts +7 -2
  60. package/src/client/client.test.ts +195 -0
  61. package/src/client/client.ts +185 -10
  62. package/src/client/vue.test.ts +253 -3
  63. package/src/client/vue.ts +44 -1
  64. package/src/internal/trace-context.ts +35 -0
  65. package/src/mod-client.ts +51 -7
  66. package/src/mod.ts +6 -1
  67. package/src/runtime.ts +48 -0
  68. package/src/test/test.ts +13 -4
  69. package/tsdown.config.ts +1 -0
@@ -9,14 +9,66 @@ import { RequestMiddlewareInputContext, RequestMiddlewareOutputContext } from ".
9
9
  import { parseFragnoResponse } from "./fragno-response.js";
10
10
  import { RequestContextStorage } from "./request-context-storage.js";
11
11
  import { bindServicesToContext } from "./bind-services.js";
12
+ import { recordTraceEvent } from "../internal/trace-context.js";
12
13
  import { addRoute, createRouter, findRoute } from "rou3";
13
14
 
14
15
  //#region src/api/fragment-instantiator.ts
16
+ const serializeHeadersForTrace = (headers) => Array.from(headers.entries()).sort(([a], [b]) => a.localeCompare(b));
17
+ const serializeQueryForTrace = (query) => Array.from(query.entries()).sort(([a], [b]) => a.localeCompare(b));
18
+ const serializeBodyForTrace = (body) => {
19
+ if (body instanceof FormData) return {
20
+ type: "form-data",
21
+ entries: Array.from(body.entries()).map(([key, value]) => {
22
+ if (value instanceof Blob) return [key, {
23
+ type: "blob",
24
+ size: value.size,
25
+ mime: value.type
26
+ }];
27
+ return [key, value];
28
+ })
29
+ };
30
+ if (body instanceof Blob) return {
31
+ type: "blob",
32
+ size: body.size,
33
+ mime: body.type
34
+ };
35
+ if (body instanceof ReadableStream) return { type: "stream" };
36
+ return body;
37
+ };
38
+ const INTERNAL_LINKED_FRAGMENT_NAME = "_fragno_internal";
39
+ const INTERNAL_ROUTE_PREFIX = "/_internal";
40
+ function normalizeRoutePrefix(prefix) {
41
+ if (!prefix.startsWith("/")) prefix = `/${prefix}`;
42
+ return prefix.endsWith("/") && prefix.length > 1 ? prefix.slice(0, -1) : prefix;
43
+ }
44
+ function joinRoutePath(prefix, path) {
45
+ const normalizedPrefix = normalizeRoutePrefix(prefix);
46
+ if (!path || path === "/") return normalizedPrefix;
47
+ return `${normalizedPrefix}${path.startsWith("/") ? path : `/${path}`}`;
48
+ }
49
+ function collectLinkedFragmentRoutes(linkedFragments) {
50
+ const linkedRoutes = [];
51
+ for (const [name, fragment] of Object.entries(linkedFragments)) {
52
+ if (name !== INTERNAL_LINKED_FRAGMENT_NAME) continue;
53
+ const internalRoutes = fragment.routes ?? [];
54
+ if (internalRoutes.length === 0) continue;
55
+ for (const route of internalRoutes) linkedRoutes.push({
56
+ ...route,
57
+ path: joinRoutePath(INTERNAL_ROUTE_PREFIX, route.path),
58
+ __internal: {
59
+ fragment,
60
+ originalPath: route.path,
61
+ routes: internalRoutes
62
+ }
63
+ });
64
+ }
65
+ return linkedRoutes;
66
+ }
15
67
  /**
16
68
  * Instantiated fragment class with encapsulated state.
17
69
  * Provides the same public API as the old FragnoInstantiatedFragment but with better encapsulation.
18
70
  */
19
- var FragnoInstantiatedFragment = class {
71
+ var FragnoInstantiatedFragment = class FragnoInstantiatedFragment {
20
72
  [instantiatedFragmentFakeSymbol] = instantiatedFragmentFakeSymbol;
21
73
  #name;
22
74
  #routes;
@@ -31,6 +83,7 @@ var FragnoInstantiatedFragment = class {
31
83
  #createRequestStorage;
32
84
  #options;
33
85
  #linkedFragments;
86
+ #internalData;
34
87
  constructor(params) {
35
88
  this.#name = params.name;
36
89
  this.#routes = params.routes;
@@ -43,6 +96,7 @@ var FragnoInstantiatedFragment = class {
43
96
  this.#createRequestStorage = params.createRequestStorage;
44
97
  this.#options = params.options;
45
98
  this.#linkedFragments = params.linkedFragments ?? {};
99
+ this.#internalData = params.internalData ?? {};
46
100
  this.#router = createRouter();
47
101
  for (const routeConfig of this.#routes) addRoute(this.#router, routeConfig.method.toUpperCase(), routeConfig.path, routeConfig);
48
102
  this.handler = this.handler.bind(this);
@@ -66,7 +120,8 @@ var FragnoInstantiatedFragment = class {
66
120
  return {
67
121
  deps: this.#deps,
68
122
  options: this.#options,
69
- linkedFragments: this.#linkedFragments
123
+ linkedFragments: this.#linkedFragments,
124
+ ...this.#internalData
70
125
  };
71
126
  }
72
127
  /**
@@ -160,26 +215,65 @@ var FragnoInstantiatedFragment = class {
160
215
  error: `Fragno: Route for '${this.#name}' not found`,
161
216
  code: "ROUTE_NOT_FOUND"
162
217
  }, { status: 404 });
218
+ const routeConfig = route.data;
219
+ const expectedContentType = routeConfig.contentType ?? "application/json";
163
220
  let requestBody = void 0;
164
221
  let rawBody = void 0;
165
222
  if (req.body instanceof ReadableStream) {
166
- rawBody = await req.clone().text();
167
- if (rawBody) try {
168
- requestBody = JSON.parse(rawBody);
169
- } catch {
170
- requestBody = void 0;
223
+ const requestContentType = (req.headers.get("content-type") ?? "").toLowerCase();
224
+ if (expectedContentType === "multipart/form-data") {
225
+ if (!requestContentType.includes("multipart/form-data")) return Response.json({
226
+ error: `This endpoint expects multipart/form-data, but received: ${requestContentType || "no content-type"}`,
227
+ code: "UNSUPPORTED_MEDIA_TYPE"
228
+ }, { status: 415 });
229
+ try {
230
+ requestBody = await req.formData();
231
+ } catch {
232
+ return Response.json({
233
+ error: "Failed to parse multipart form data",
234
+ code: "INVALID_REQUEST_BODY"
235
+ }, { status: 400 });
236
+ }
237
+ } else if (expectedContentType === "application/octet-stream") {
238
+ if (!requestContentType.includes("application/octet-stream")) return Response.json({
239
+ error: `This endpoint expects application/octet-stream, but received: ${requestContentType || "no content-type"}`,
240
+ code: "UNSUPPORTED_MEDIA_TYPE"
241
+ }, { status: 415 });
242
+ requestBody = req.body ?? new ReadableStream();
243
+ } else {
244
+ if (requestContentType.includes("multipart/form-data")) return Response.json({
245
+ error: `This endpoint expects JSON, but received multipart/form-data. Use a route with contentType: "multipart/form-data" for file uploads.`,
246
+ code: "UNSUPPORTED_MEDIA_TYPE"
247
+ }, { status: 415 });
248
+ rawBody = await req.clone().text();
249
+ if (rawBody) try {
250
+ requestBody = JSON.parse(rawBody);
251
+ } catch {
252
+ requestBody = void 0;
253
+ }
171
254
  }
172
255
  }
256
+ const decodedRouteParams = {};
257
+ for (const [key, value] of Object.entries(route.params ?? {})) decodedRouteParams[key] = decodeURIComponent(value);
173
258
  const requestState = new MutableRequestState({
174
- pathParams: route.params ?? {},
259
+ pathParams: decodedRouteParams,
175
260
  searchParams: url.searchParams,
176
261
  body: requestBody,
177
262
  headers: new Headers(req.headers)
178
263
  });
179
264
  const executeRequest = async () => {
180
- if (this.#middlewareHandler) {
181
- const middlewareResult = await this.#executeMiddleware(req, route, requestState);
182
- if (middlewareResult !== void 0) return middlewareResult;
265
+ const middlewareResult = await this.#executeMiddleware(req, route, requestState);
266
+ if (middlewareResult !== void 0) return middlewareResult;
267
+ const internalMeta = routeConfig.__internal;
268
+ if (internalMeta) {
269
+ const internalResult = await FragnoInstantiatedFragment.#runMiddlewareForFragment(internalMeta.fragment, {
270
+ req,
271
+ method: routeConfig.method,
272
+ path: internalMeta.originalPath,
273
+ requestState,
274
+ routes: internalMeta.routes
275
+ });
276
+ if (internalResult !== void 0) return internalResult;
183
277
  }
184
278
  return this.#executeHandler(req, route, requestState, rawBody);
185
279
  };
@@ -215,6 +309,15 @@ var FragnoInstantiatedFragment = class {
215
309
  inputSchema: route.inputSchema,
216
310
  shouldValidateInput: true
217
311
  });
312
+ recordTraceEvent({
313
+ type: "route-input",
314
+ method: route.method,
315
+ path: route.path,
316
+ pathParams: pathParams ?? {},
317
+ queryParams: serializeQueryForTrace(searchParams),
318
+ headers: serializeHeadersForTrace(requestHeaders),
319
+ body: serializeBodyForTrace(body)
320
+ });
218
321
  const outputContext = new RequestOutputContext(route.outputSchema);
219
322
  const executeHandler = async () => {
220
323
  try {
@@ -236,20 +339,43 @@ var FragnoInstantiatedFragment = class {
236
339
  * Returns undefined if middleware allows the request to continue to the handler.
237
340
  */
238
341
  async #executeMiddleware(req, route, requestState) {
239
- if (!this.#middlewareHandler || !route) return;
342
+ if (!route) return;
240
343
  const { path } = route.data;
241
- const middlewareInputContext = new RequestMiddlewareInputContext(this.#routes, {
344
+ return FragnoInstantiatedFragment.#runMiddlewareForFragment(this, {
345
+ req,
242
346
  method: req.method,
243
347
  path,
244
- request: req,
245
- state: requestState
348
+ requestState
349
+ });
350
+ }
351
+ static async #runMiddlewareForFragment(fragment, options) {
352
+ if (!fragment.#middlewareHandler) return;
353
+ const middlewareInputContext = new RequestMiddlewareInputContext(options.routes ?? fragment.#routes, {
354
+ method: options.method,
355
+ path: options.path,
356
+ request: options.req,
357
+ state: options.requestState
246
358
  });
247
- const middlewareOutputContext = new RequestMiddlewareOutputContext(this.#deps, this.#services);
359
+ const middlewareOutputContext = new RequestMiddlewareOutputContext(fragment.#deps, fragment.#services);
248
360
  try {
249
- const middlewareResult = await this.#middlewareHandler(middlewareInputContext, middlewareOutputContext);
361
+ const middlewareResult = await fragment.#middlewareHandler(middlewareInputContext, middlewareOutputContext);
362
+ recordTraceEvent({
363
+ type: "middleware-decision",
364
+ method: options.method,
365
+ path: options.path,
366
+ outcome: middlewareResult ? "deny" : "allow",
367
+ status: middlewareResult?.status
368
+ });
250
369
  if (middlewareResult !== void 0) return middlewareResult;
251
370
  } catch (error) {
252
371
  console.error("Error in middleware", error);
372
+ recordTraceEvent({
373
+ type: "middleware-decision",
374
+ method: options.method,
375
+ path: options.path,
376
+ outcome: "deny",
377
+ status: error instanceof FragnoApiError ? error.status : 500
378
+ });
253
379
  if (error instanceof FragnoApiError) return error.toResponse();
254
380
  return Response.json({
255
381
  error: "Internal server error",
@@ -275,6 +401,15 @@ var FragnoInstantiatedFragment = class {
275
401
  state: requestState,
276
402
  rawBody
277
403
  });
404
+ recordTraceEvent({
405
+ type: "route-input",
406
+ method: req.method,
407
+ path,
408
+ pathParams: inputContext.pathParams,
409
+ queryParams: serializeQueryForTrace(requestState.searchParams),
410
+ headers: serializeHeadersForTrace(requestState.headers),
411
+ body: serializeBodyForTrace(requestState.body)
412
+ });
278
413
  const outputContext = new RequestOutputContext(outputSchema);
279
414
  try {
280
415
  const contextForHandler = this.#handlerThisContext ?? {};
@@ -397,6 +532,12 @@ function instantiateFragment(definition, config, routesOrFactories, options, ser
397
532
  });
398
533
  const serviceContext = contexts?.serviceContext;
399
534
  const handlerContext = contexts?.handlerContext;
535
+ const internalData = definition.internalDataFactory?.({
536
+ config,
537
+ options,
538
+ deps,
539
+ linkedFragments: linkedFragmentInstances
540
+ }) ?? {};
400
541
  const boundServices = serviceContext ? bindServicesToContext(services, serviceContext) : services;
401
542
  const routes = resolveRouteFactories({
402
543
  config,
@@ -404,6 +545,8 @@ function instantiateFragment(definition, config, routesOrFactories, options, ser
404
545
  services: boundServices,
405
546
  serviceDeps: serviceImplementations ?? {}
406
547
  }, routesOrFactories);
548
+ const linkedRoutes = collectLinkedFragmentRoutes(linkedFragmentInstances);
549
+ const finalRoutes = linkedRoutes.length > 0 ? [...routes, ...linkedRoutes] : routes;
407
550
  const mountRoute = getMountRoute({
408
551
  name: definition.name,
409
552
  mountRoute: options.mountRoute
@@ -415,7 +558,7 @@ function instantiateFragment(definition, config, routesOrFactories, options, ser
415
558
  }) : void 0;
416
559
  return new FragnoInstantiatedFragment({
417
560
  name: definition.name,
418
- routes,
561
+ routes: finalRoutes,
419
562
  deps,
420
563
  services: boundServices,
421
564
  mountRoute,
@@ -424,7 +567,8 @@ function instantiateFragment(definition, config, routesOrFactories, options, ser
424
567
  storage,
425
568
  createRequestStorage: createRequestStorageWithContext,
426
569
  options,
427
- linkedFragments: linkedFragmentInstances
570
+ linkedFragments: linkedFragmentInstances,
571
+ internalData
428
572
  });
429
573
  }
430
574
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"fragment-instantiator.js","names":["#name","#routes","#deps","#services","#mountRoute","#serviceThisContext","#handlerThisContext","#contextStorage","#createRequestStorage","#options","#linkedFragments","#router","#middlewareHandler","#withRequestStorage","requestBody: RequestBodyType","rawBody: string | undefined","#executeMiddleware","#executeHandler","deps: TDeps","linkedFragmentServices: Record<string, unknown>","services","baseServices: TBaseServices","#definition","#config"],"sources":["../../src/api/fragment-instantiator.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { type FragnoRouteConfig, type HTTPMethod, type RequestThisContext } from \"./api\";\nimport { FragnoApiError } from \"./error\";\nimport { getMountRoute } from \"./internal/route\";\nimport { addRoute, createRouter, findRoute } from \"rou3\";\nimport { RequestInputContext, type RequestBodyType } from \"./request-input-context\";\nimport type { ExtractPathParams } from \"./internal/path\";\nimport { RequestOutputContext } from \"./request-output-context\";\nimport {\n type AnyFragnoRouteConfig,\n type AnyRouteOrFactory,\n type FlattenRouteFactories,\n resolveRouteFactories,\n} from \"./route\";\nimport {\n RequestMiddlewareInputContext,\n RequestMiddlewareOutputContext,\n type FragnoMiddlewareCallback,\n} from \"./request-middleware\";\nimport { MutableRequestState } from \"./mutable-request-state\";\nimport type { RouteHandlerInputOptions } from \"./route-handler-input-options\";\nimport type { ExtractRouteByPath, ExtractRoutePath } from \"../client/client\";\nimport { type FragnoResponse, parseFragnoResponse } from \"./fragno-response\";\nimport type { InferOrUnknown } from \"../util/types-util\";\nimport type { FragmentDefinition } from \"./fragment-definition-builder\";\nimport type { FragnoPublicConfig } from \"./shared-types\";\nimport { RequestContextStorage } from \"./request-context-storage\";\nimport { bindServicesToContext, type BoundServices } from \"./bind-services\";\nimport { instantiatedFragmentFakeSymbol } from \"../internal/symbols\";\n\n// Re-export types needed by consumers\nexport type { BoundServices };\n\n/**\n * Helper type to extract the instantiated fragment type from a fragment definition.\n * This is useful for typing functions that accept instantiated fragments based on their definition.\n *\n * @example\n * ```typescript\n * const myFragmentDef = defineFragment(\"my-fragment\").build();\n * type MyInstantiatedFragment = InstantiatedFragmentFromDefinition<typeof myFragmentDef>;\n * ```\n */\nexport type InstantiatedFragmentFromDefinition<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TDef extends FragmentDefinition<any, any, any, any, any, any, any, any, any, any, any>,\n> =\n TDef extends FragmentDefinition<\n infer _TConfig,\n infer TOptions,\n infer TDeps,\n infer TBaseServices,\n infer TServices,\n infer _TServiceDependencies,\n infer _TPrivateServices,\n infer TServiceThisContext,\n infer THandlerThisContext,\n infer TRequestStorage,\n infer TLinkedFragments\n >\n ? FragnoInstantiatedFragment<\n readonly AnyFragnoRouteConfig[], // Routes are dynamic, so we use a generic array\n TDeps,\n BoundServices<TBaseServices & TServices>,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TOptions,\n TLinkedFragments\n >\n : never;\n\ntype AstroHandlers = {\n ALL: (req: Request) => Promise<Response>;\n};\n\ntype ReactRouterHandlers = {\n loader: (args: { request: Request }) => Promise<Response>;\n action: (args: { request: Request }) => Promise<Response>;\n};\n\ntype SolidStartHandlers = {\n GET: (args: { request: Request }) => Promise<Response>;\n POST: (args: { request: Request }) => Promise<Response>;\n PUT: (args: { request: Request }) => Promise<Response>;\n DELETE: (args: { request: Request }) => Promise<Response>;\n PATCH: (args: { request: Request }) => Promise<Response>;\n HEAD: (args: { request: Request }) => Promise<Response>;\n OPTIONS: (args: { request: Request }) => Promise<Response>;\n};\n\ntype TanStackStartHandlers = SolidStartHandlers;\n\ntype StandardHandlers = {\n GET: (req: Request) => Promise<Response>;\n POST: (req: Request) => Promise<Response>;\n PUT: (req: Request) => Promise<Response>;\n DELETE: (req: Request) => Promise<Response>;\n PATCH: (req: Request) => Promise<Response>;\n HEAD: (req: Request) => Promise<Response>;\n OPTIONS: (req: Request) => Promise<Response>;\n};\n\ntype HandlersByFramework = {\n astro: AstroHandlers;\n \"react-router\": ReactRouterHandlers;\n \"next-js\": StandardHandlers;\n \"svelte-kit\": StandardHandlers;\n \"solid-start\": SolidStartHandlers;\n \"tanstack-start\": TanStackStartHandlers;\n};\n\ntype FullstackFrameworks = keyof HandlersByFramework;\n\nexport type AnyFragnoInstantiatedFragment = FragnoInstantiatedFragment<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\nexport interface FragnoFragmentSharedConfig<\n TRoutes extends readonly FragnoRouteConfig<\n HTTPMethod,\n string,\n StandardSchemaV1 | undefined,\n StandardSchemaV1 | undefined,\n string,\n string\n >[],\n> {\n name: string;\n routes: TRoutes;\n}\n\n/**\n * Instantiated fragment class with encapsulated state.\n * Provides the same public API as the old FragnoInstantiatedFragment but with better encapsulation.\n */\nexport class FragnoInstantiatedFragment<\n TRoutes extends readonly AnyFragnoRouteConfig[],\n TDeps,\n TServices extends Record<string, unknown>,\n TServiceThisContext extends RequestThisContext,\n THandlerThisContext extends RequestThisContext,\n TRequestStorage = {},\n TOptions extends FragnoPublicConfig = FragnoPublicConfig,\n TLinkedFragments extends Record<string, AnyFragnoInstantiatedFragment> = {},\n> implements IFragnoInstantiatedFragment\n{\n readonly [instantiatedFragmentFakeSymbol] = instantiatedFragmentFakeSymbol;\n\n // Private fields\n #name: string;\n #routes: TRoutes;\n #deps: TDeps;\n #services: TServices;\n #mountRoute: string;\n #router: ReturnType<typeof createRouter>;\n #middlewareHandler?: FragnoMiddlewareCallback<TRoutes, TDeps, TServices>;\n #serviceThisContext?: TServiceThisContext; // Context for services (may have restricted capabilities)\n #handlerThisContext?: THandlerThisContext; // Context for handlers (full capabilities)\n #contextStorage: RequestContextStorage<TRequestStorage>;\n #createRequestStorage?: () => TRequestStorage;\n #options: TOptions;\n #linkedFragments: TLinkedFragments;\n\n constructor(params: {\n name: string;\n routes: TRoutes;\n deps: TDeps;\n services: TServices;\n mountRoute: string;\n serviceThisContext?: TServiceThisContext;\n handlerThisContext?: THandlerThisContext;\n storage: RequestContextStorage<TRequestStorage>;\n createRequestStorage?: () => TRequestStorage;\n options: TOptions;\n linkedFragments?: TLinkedFragments;\n }) {\n this.#name = params.name;\n this.#routes = params.routes;\n this.#deps = params.deps;\n this.#services = params.services;\n this.#mountRoute = params.mountRoute;\n this.#serviceThisContext = params.serviceThisContext;\n this.#handlerThisContext = params.handlerThisContext;\n this.#contextStorage = params.storage;\n this.#createRequestStorage = params.createRequestStorage;\n this.#options = params.options;\n this.#linkedFragments = params.linkedFragments ?? ({} as TLinkedFragments);\n\n // Build router\n this.#router =\n createRouter<\n FragnoRouteConfig<\n HTTPMethod,\n string,\n StandardSchemaV1 | undefined,\n StandardSchemaV1 | undefined,\n string,\n string,\n RequestThisContext\n >\n >();\n\n for (const routeConfig of this.#routes) {\n addRoute(this.#router, routeConfig.method.toUpperCase(), routeConfig.path, routeConfig);\n }\n\n // Bind handler method to maintain 'this' context\n this.handler = this.handler.bind(this);\n }\n\n // Public getters\n get name(): string {\n return this.#name;\n }\n\n get routes(): TRoutes {\n return this.#routes;\n }\n\n get services(): TServices {\n return this.#services;\n }\n\n get mountRoute(): string {\n return this.#mountRoute;\n }\n\n /**\n * @internal\n */\n get $internal() {\n return {\n deps: this.#deps,\n options: this.#options,\n linkedFragments: this.#linkedFragments,\n };\n }\n\n /**\n * Add middleware to this fragment.\n * Middleware can inspect and modify requests before they reach handlers.\n */\n withMiddleware(handler: FragnoMiddlewareCallback<TRoutes, TDeps, TServices>): this {\n if (this.#middlewareHandler) {\n throw new Error(\"Middleware already set\");\n }\n this.#middlewareHandler = handler;\n return this;\n }\n\n /**\n * Run a callback within the fragment's request context with initialized storage.\n * This is a shared helper used by inContext(), handler(), and callRouteRaw().\n * @private\n */\n #withRequestStorage<T>(callback: () => T): T;\n #withRequestStorage<T>(callback: () => Promise<T>): Promise<T>;\n #withRequestStorage<T>(callback: () => T | Promise<T>): T | Promise<T> {\n if (!this.#serviceThisContext && !this.#handlerThisContext) {\n // No request context configured - just run callback directly\n return callback();\n }\n\n // Initialize storage with fresh data for this request\n const storageData = this.#createRequestStorage\n ? this.#createRequestStorage()\n : ({} as TRequestStorage);\n return this.#contextStorage.run(storageData, callback);\n }\n\n /**\n * Execute a callback within a request context.\n * Establishes an async context for the duration of the callback, allowing services\n * to access the `this` context. The callback's `this` will be bound to the fragment's\n * handler context (with full capabilities including execute methods).\n * Useful for calling services outside of route handlers (e.g., in tests, background jobs).\n *\n * @param callback - The callback to run within the context\n *\n * @example\n * ```typescript\n * const result = await fragment.inContext(function () {\n * // `this` is bound to the handler context (can call execute methods)\n * await this.getUnitOfWork().executeRetrieve();\n * return this.someContextMethod();\n * });\n * ```\n */\n inContext<T>(callback: (this: THandlerThisContext) => T): T;\n inContext<T>(callback: (this: THandlerThisContext) => Promise<T>): Promise<T>;\n inContext<T>(callback: (this: THandlerThisContext) => T | Promise<T>): T | Promise<T> {\n // Always use handler context for inContext - it has full capabilities\n if (this.#handlerThisContext) {\n const boundCallback = callback.bind(this.#handlerThisContext);\n return this.#withRequestStorage(boundCallback);\n }\n return this.#withRequestStorage(callback);\n }\n\n /**\n * Get framework-specific handlers for this fragment.\n * Use this to integrate the fragment with different fullstack frameworks.\n */\n handlersFor<T extends FullstackFrameworks>(framework: T): HandlersByFramework[T] {\n const handler = this.handler.bind(this);\n\n // LLMs hallucinate these values sometimes, solution isn't obvious so we throw this error\n // @ts-expect-error TS2367\n if (framework === \"h3\" || framework === \"nuxt\") {\n throw new Error(`To get handlers for h3, use the 'fromWebHandler' utility function:\n import { fromWebHandler } from \"h3\";\n export default fromWebHandler(myFragment().handler);`);\n }\n\n const allHandlers = {\n astro: { ALL: handler },\n \"react-router\": {\n loader: ({ request }: { request: Request }) => handler(request),\n action: ({ request }: { request: Request }) => handler(request),\n },\n \"next-js\": {\n GET: handler,\n POST: handler,\n PUT: handler,\n DELETE: handler,\n PATCH: handler,\n HEAD: handler,\n OPTIONS: handler,\n },\n \"svelte-kit\": {\n GET: handler,\n POST: handler,\n PUT: handler,\n DELETE: handler,\n PATCH: handler,\n HEAD: handler,\n OPTIONS: handler,\n },\n \"solid-start\": {\n GET: ({ request }: { request: Request }) => handler(request),\n POST: ({ request }: { request: Request }) => handler(request),\n PUT: ({ request }: { request: Request }) => handler(request),\n DELETE: ({ request }: { request: Request }) => handler(request),\n PATCH: ({ request }: { request: Request }) => handler(request),\n HEAD: ({ request }: { request: Request }) => handler(request),\n OPTIONS: ({ request }: { request: Request }) => handler(request),\n },\n \"tanstack-start\": {\n GET: ({ request }: { request: Request }) => handler(request),\n POST: ({ request }: { request: Request }) => handler(request),\n PUT: ({ request }: { request: Request }) => handler(request),\n DELETE: ({ request }: { request: Request }) => handler(request),\n PATCH: ({ request }: { request: Request }) => handler(request),\n HEAD: ({ request }: { request: Request }) => handler(request),\n OPTIONS: ({ request }: { request: Request }) => handler(request),\n },\n } satisfies HandlersByFramework;\n\n return allHandlers[framework];\n }\n\n /**\n * Main request handler for this fragment.\n * Handles routing, middleware, and error handling.\n */\n async handler(req: Request): Promise<Response> {\n const url = new URL(req.url);\n const pathname = url.pathname;\n\n // Match route\n const matchRoute = pathname.startsWith(this.#mountRoute)\n ? pathname.slice(this.#mountRoute.length)\n : null;\n\n if (matchRoute === null) {\n return Response.json(\n {\n error:\n `Fragno: Route for '${this.#name}' not found. Is the fragment mounted on the right route? ` +\n `Expecting: '${this.#mountRoute}'.`,\n code: \"ROUTE_NOT_FOUND\",\n },\n { status: 404 },\n );\n }\n\n const route = findRoute(this.#router, req.method, matchRoute);\n\n if (!route) {\n return Response.json(\n { error: `Fragno: Route for '${this.#name}' not found`, code: \"ROUTE_NOT_FOUND\" },\n { status: 404 },\n );\n }\n\n // Parse request body\n let requestBody: RequestBodyType = undefined;\n let rawBody: string | undefined = undefined;\n\n if (req.body instanceof ReadableStream) {\n // Clone request to make sure we don't consume body stream\n const clonedReq = req.clone();\n\n // Get raw text\n rawBody = await clonedReq.text();\n\n // Parse JSON if body is not empty\n if (rawBody) {\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n // If JSON parsing fails, keep body as undefined\n // This handles cases where body is not JSON\n requestBody = undefined;\n }\n }\n }\n\n const requestState = new MutableRequestState({\n pathParams: route.params ?? {},\n searchParams: url.searchParams,\n body: requestBody,\n headers: new Headers(req.headers),\n });\n\n // Execute middleware and handler\n const executeRequest = async (): Promise<Response> => {\n // Middleware execution (if present)\n if (this.#middlewareHandler) {\n const middlewareResult = await this.#executeMiddleware(req, route, requestState);\n if (middlewareResult !== undefined) {\n return middlewareResult;\n }\n }\n\n // Handler execution\n return this.#executeHandler(req, route, requestState, rawBody);\n };\n\n // Wrap with request storage context if provided\n return this.#withRequestStorage(executeRequest);\n }\n\n /**\n * Call a route directly with typed inputs and outputs.\n * Useful for testing and server-side route calls.\n */\n async callRoute<TMethod extends HTTPMethod, TPath extends ExtractRoutePath<TRoutes, TMethod>>(\n method: TMethod,\n path: TPath,\n inputOptions?: RouteHandlerInputOptions<\n TPath,\n ExtractRouteByPath<TRoutes, TPath, TMethod>[\"inputSchema\"]\n >,\n ): Promise<\n FragnoResponse<\n InferOrUnknown<NonNullable<ExtractRouteByPath<TRoutes, TPath, TMethod>[\"outputSchema\"]>>\n >\n > {\n const response = await this.callRouteRaw(method, path, inputOptions);\n return parseFragnoResponse(response);\n }\n\n /**\n * Call a route directly and get the raw Response object.\n * Useful for testing and server-side route calls.\n */\n async callRouteRaw<TMethod extends HTTPMethod, TPath extends ExtractRoutePath<TRoutes, TMethod>>(\n method: TMethod,\n path: TPath,\n inputOptions?: RouteHandlerInputOptions<\n TPath,\n ExtractRouteByPath<TRoutes, TPath, TMethod>[\"inputSchema\"]\n >,\n ): Promise<Response> {\n // Find route in this.#routes\n const route = this.#routes.find((r) => r.method === method && r.path === path);\n\n if (!route) {\n return Response.json(\n {\n error: `Route ${method} ${path} not found`,\n code: \"ROUTE_NOT_FOUND\",\n },\n { status: 404 },\n );\n }\n\n const { pathParams = {}, body, query, headers } = inputOptions || {};\n\n // Convert query to URLSearchParams if needed\n const searchParams =\n query instanceof URLSearchParams\n ? query\n : query\n ? new URLSearchParams(query)\n : new URLSearchParams();\n\n const requestHeaders =\n headers instanceof Headers ? headers : headers ? new Headers(headers) : new Headers();\n\n // Construct RequestInputContext\n const inputContext = new RequestInputContext({\n path: route.path,\n method: route.method,\n pathParams: pathParams as ExtractPathParams<typeof route.path>,\n searchParams,\n headers: requestHeaders,\n parsedBody: body,\n inputSchema: route.inputSchema,\n shouldValidateInput: true, // Enable validation for production use\n });\n\n // Construct RequestOutputContext\n const outputContext = new RequestOutputContext(route.outputSchema);\n\n // Execute handler\n const executeHandler = async (): Promise<Response> => {\n try {\n // Use handler context (full capabilities)\n const thisContext = this.#handlerThisContext ?? ({} as RequestThisContext);\n return await route.handler.call(thisContext, inputContext, outputContext);\n } catch (error) {\n console.error(\"Error in callRoute handler\", error);\n\n if (error instanceof FragnoApiError) {\n return error.toResponse();\n }\n\n return Response.json(\n { error: \"Internal server error\", code: \"INTERNAL_SERVER_ERROR\" },\n { status: 500 },\n );\n }\n };\n\n // Wrap with request storage context if provided\n return this.#withRequestStorage(executeHandler);\n }\n\n /**\n * Execute middleware for a request.\n * Returns undefined if middleware allows the request to continue to the handler.\n */\n async #executeMiddleware(\n req: Request,\n route: ReturnType<typeof findRoute>,\n requestState: MutableRequestState,\n ): Promise<Response | undefined> {\n if (!this.#middlewareHandler || !route) {\n return undefined;\n }\n\n const { path } = route.data as AnyFragnoRouteConfig;\n\n const middlewareInputContext = new RequestMiddlewareInputContext(this.#routes, {\n method: req.method as HTTPMethod,\n path,\n request: req,\n state: requestState,\n });\n\n const middlewareOutputContext = new RequestMiddlewareOutputContext(this.#deps, this.#services);\n\n try {\n const middlewareResult = await this.#middlewareHandler(\n middlewareInputContext,\n middlewareOutputContext,\n );\n if (middlewareResult !== undefined) {\n return middlewareResult;\n }\n } catch (error) {\n console.error(\"Error in middleware\", error);\n\n if (error instanceof FragnoApiError) {\n return error.toResponse();\n }\n\n return Response.json(\n { error: \"Internal server error\", code: \"INTERNAL_SERVER_ERROR\" },\n { status: 500 },\n );\n }\n\n return undefined;\n }\n\n /**\n * Execute a route handler with proper error handling.\n */\n async #executeHandler(\n req: Request,\n route: ReturnType<typeof findRoute>,\n requestState: MutableRequestState,\n rawBody?: string,\n ): Promise<Response> {\n if (!route) {\n return Response.json({ error: \"Route not found\", code: \"ROUTE_NOT_FOUND\" }, { status: 404 });\n }\n\n const { handler, inputSchema, outputSchema, path } = route.data as AnyFragnoRouteConfig;\n\n const inputContext = await RequestInputContext.fromRequest({\n request: req,\n method: req.method,\n path,\n pathParams: (route.params ?? {}) as ExtractPathParams<typeof path>,\n inputSchema,\n state: requestState,\n rawBody,\n });\n\n const outputContext = new RequestOutputContext(outputSchema);\n\n try {\n // Note: We don't call .run() here because the storage should already be initialized\n // by the handler() method or inContext() method before this point\n // Use handler context (full capabilities)\n const contextForHandler = this.#handlerThisContext ?? ({} as RequestThisContext);\n const result = await handler.call(contextForHandler, inputContext, outputContext);\n return result;\n } catch (error) {\n console.error(\"Error in handler\", error);\n\n if (error instanceof FragnoApiError) {\n return error.toResponse();\n }\n\n return Response.json(\n { error: \"Internal server error\", code: \"INTERNAL_SERVER_ERROR\" },\n { status: 500 },\n );\n }\n }\n}\n\n/**\n * Options for fragment instantiation.\n */\nexport interface InstantiationOptions {\n /**\n * If true, catches errors during initialization and returns stub implementations.\n * This is useful for CLI tools that need to extract metadata (like database schemas)\n * without requiring all dependencies to be fully initialized.\n */\n dryRun?: boolean;\n}\n\n/**\n * Core instantiation function that creates a fragment instance from a definition.\n * This function validates dependencies, calls all callbacks, and wires everything together.\n */\nexport function instantiateFragment<\n const TConfig,\n const TOptions extends FragnoPublicConfig,\n const TDeps,\n const TBaseServices extends Record<string, unknown>,\n const TServices extends Record<string, unknown>,\n const TServiceDependencies,\n const TPrivateServices extends Record<string, unknown>,\n const TServiceThisContext extends RequestThisContext,\n const THandlerThisContext extends RequestThisContext,\n const TRequestStorage,\n const TRoutesOrFactories extends readonly AnyRouteOrFactory[],\n const TLinkedFragments extends Record<string, AnyFragnoInstantiatedFragment>,\n>(\n definition: FragmentDefinition<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TLinkedFragments\n >,\n config: TConfig,\n routesOrFactories: TRoutesOrFactories,\n options: TOptions,\n serviceImplementations?: TServiceDependencies,\n instantiationOptions?: InstantiationOptions,\n): FragnoInstantiatedFragment<\n FlattenRouteFactories<TRoutesOrFactories>,\n TDeps,\n BoundServices<TBaseServices & TServices>,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TOptions,\n TLinkedFragments\n> {\n const { dryRun = false } = instantiationOptions ?? {};\n\n // 1. Validate service dependencies\n const serviceDependencies = definition.serviceDependencies;\n if (serviceDependencies) {\n for (const [serviceName, meta] of Object.entries(serviceDependencies)) {\n const metadata = meta as { name: string; required: boolean };\n const implementation = serviceImplementations?.[serviceName as keyof TServiceDependencies];\n if (metadata.required && !implementation) {\n throw new Error(\n `Fragment '${definition.name}' requires service '${metadata.name}' but it was not provided`,\n );\n }\n }\n }\n\n // 2. Call dependencies callback\n let deps: TDeps;\n try {\n deps = definition.dependencies?.({ config, options }) ?? ({} as TDeps);\n } catch (error) {\n if (dryRun) {\n console.warn(\n \"Warning: Failed to initialize dependencies in dry run mode:\",\n error instanceof Error ? error.message : String(error),\n );\n // Return empty deps - database fragments will add implicit deps later\n deps = {} as TDeps;\n } else {\n throw error;\n }\n }\n\n // 3. Instantiate linked fragments FIRST (before any services)\n // Their services will be merged into private services\n const linkedFragmentInstances = {} as TLinkedFragments;\n const linkedFragmentServices: Record<string, unknown> = {};\n\n if (definition.linkedFragments) {\n for (const [name, callback] of Object.entries(definition.linkedFragments)) {\n const linkedFragment = callback({\n config,\n options,\n serviceDependencies: serviceImplementations,\n });\n (linkedFragmentInstances as Record<string, AnyFragnoInstantiatedFragment>)[name] =\n linkedFragment;\n\n // Merge all services from linked fragment into private services directly by their service name\n const services = linkedFragment.services as Record<string, unknown>;\n for (const [serviceName, service] of Object.entries(services)) {\n linkedFragmentServices[serviceName] = service;\n }\n }\n }\n\n // Identity function for service definition (used to set 'this' context)\n const defineService = <T>(services: T & ThisType<TServiceThisContext>): T => services;\n\n // 4. Call privateServices factories\n // Private services are instantiated in order, so earlier ones are available to later ones\n // Start with linked fragment services, then add explicitly defined private services\n const privateServices = { ...linkedFragmentServices } as TPrivateServices;\n if (definition.privateServices) {\n for (const [serviceName, factory] of Object.entries(definition.privateServices)) {\n const serviceFactory = factory as (context: {\n config: TConfig;\n options: TOptions;\n deps: TDeps;\n serviceDeps: TServiceDependencies;\n privateServices: TPrivateServices;\n defineService: <T>(svc: T & ThisType<TServiceThisContext>) => T;\n }) => unknown;\n\n try {\n (privateServices as Record<string, unknown>)[serviceName] = serviceFactory({\n config,\n options,\n deps,\n serviceDeps: (serviceImplementations ?? {}) as TServiceDependencies,\n privateServices, // Pass the current state of private services (earlier ones are available)\n defineService,\n });\n } catch (error) {\n if (dryRun) {\n console.warn(\n `Warning: Failed to initialize private service '${serviceName}' in dry run mode:`,\n error instanceof Error ? error.message : String(error),\n );\n (privateServices as Record<string, unknown>)[serviceName] = {};\n } else {\n throw error;\n }\n }\n }\n }\n\n // 5. Call baseServices callback (with access to private services including linked fragment services)\n let baseServices: TBaseServices;\n try {\n baseServices =\n definition.baseServices?.({\n config,\n options,\n deps,\n serviceDeps: (serviceImplementations ?? {}) as TServiceDependencies,\n privateServices,\n defineService,\n }) ?? ({} as TBaseServices);\n } catch (error) {\n if (dryRun) {\n console.warn(\n \"Warning: Failed to initialize base services in dry run mode:\",\n error instanceof Error ? error.message : String(error),\n );\n baseServices = {} as TBaseServices;\n } else {\n throw error;\n }\n }\n\n // 6. Call namedServices factories (with access to private services including linked fragment services)\n const namedServices = {} as TServices;\n if (definition.namedServices) {\n for (const [serviceName, factory] of Object.entries(definition.namedServices)) {\n const serviceFactory = factory as (context: {\n config: TConfig;\n options: TOptions;\n deps: TDeps;\n serviceDeps: TServiceDependencies;\n privateServices: TPrivateServices;\n defineService: <T>(svc: T & ThisType<TServiceThisContext>) => T;\n }) => unknown;\n\n try {\n (namedServices as Record<string, unknown>)[serviceName] = serviceFactory({\n config,\n options,\n deps,\n serviceDeps: (serviceImplementations ?? {}) as TServiceDependencies,\n privateServices,\n defineService,\n });\n } catch (error) {\n if (dryRun) {\n console.warn(\n `Warning: Failed to initialize service '${serviceName}' in dry run mode:`,\n error instanceof Error ? error.message : String(error),\n );\n (namedServices as Record<string, unknown>)[serviceName] = {};\n } else {\n throw error;\n }\n }\n }\n }\n\n // 7. Merge public services (NOT including private services)\n const services = {\n ...baseServices,\n ...namedServices,\n };\n\n // 8. Create request context storage and both service & handler contexts\n // Use external storage if provided, otherwise create new storage\n const storage = definition.getExternalStorage\n ? definition.getExternalStorage({ config, options, deps })\n : new RequestContextStorage<TRequestStorage>();\n\n // Create both contexts using createThisContext (returns { serviceContext, handlerContext })\n const contexts = definition.createThisContext?.({\n config,\n options,\n deps,\n storage,\n });\n\n const serviceContext = contexts?.serviceContext;\n const handlerContext = contexts?.handlerContext;\n\n // 9. Bind services to serviceContext (restricted)\n // Services get the restricted context (for database fragments, this excludes execute methods)\n const boundServices = serviceContext ? bindServicesToContext(services, serviceContext) : services;\n\n // 10. Resolve routes with bound services\n const context = {\n config,\n deps,\n services: boundServices,\n serviceDeps: serviceImplementations ?? ({} as TServiceDependencies),\n };\n const routes = resolveRouteFactories(context, routesOrFactories);\n\n // 11. Calculate mount route\n const mountRoute = getMountRoute({\n name: definition.name,\n mountRoute: options.mountRoute,\n });\n\n // 12. Wrap createRequestStorage to capture context\n const createRequestStorageWithContext = definition.createRequestStorage\n ? () => definition.createRequestStorage!({ config, options, deps })\n : undefined;\n\n // 13. Create and return fragment instance\n // Pass bound services so they have access to serviceContext via 'this'\n // Handlers get handlerContext which may have more capabilities than serviceContext\n return new FragnoInstantiatedFragment({\n name: definition.name,\n routes,\n deps,\n services: boundServices as BoundServices<TBaseServices & TServices>,\n mountRoute,\n serviceThisContext: serviceContext,\n handlerThisContext: handlerContext,\n storage,\n createRequestStorage: createRequestStorageWithContext,\n options,\n linkedFragments: linkedFragmentInstances,\n });\n}\n\n/**\n * Interface that defines the public API for a fragment instantiation builder.\n * Used to ensure consistency between real implementations and stubs.\n */\ninterface IFragmentInstantiationBuilder {\n /**\n * Get the fragment definition\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get definition(): any;\n\n /**\n * Get the configured routes\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get routes(): any;\n\n /**\n * Get the configuration\n */\n get config(): unknown;\n\n /**\n * Get the options\n */\n get options(): unknown;\n\n /**\n * Set the configuration for the fragment\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withConfig(config: any): unknown;\n\n /**\n * Set the routes for the fragment\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withRoutes(routes: any): unknown;\n\n /**\n * Set the options for the fragment (e.g., mountRoute, databaseAdapter)\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withOptions(options: any): unknown;\n\n /**\n * Provide implementations for services that this fragment uses\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withServices(services: any): unknown;\n\n /**\n * Build and return the instantiated fragment\n */\n build(): IFragnoInstantiatedFragment;\n}\n\n/**\n * Interface that defines the public API for an instantiated fragment.\n * Used to ensure consistency between real implementations and stubs.\n */\ninterface IFragnoInstantiatedFragment {\n readonly [instantiatedFragmentFakeSymbol]: typeof instantiatedFragmentFakeSymbol;\n\n get name(): string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get routes(): any;\n get services(): Record<string, unknown>;\n get mountRoute(): string;\n get $internal(): {\n deps: unknown;\n options: unknown;\n linkedFragments: unknown;\n };\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withMiddleware(handler: any): this;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inContext<T>(callback: any): T;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inContext<T>(callback: any): Promise<T>;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handlersFor(framework: FullstackFrameworks): any;\n\n handler(req: Request): Promise<Response>;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callRoute(method: HTTPMethod, path: string, inputOptions?: any): Promise<any>;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callRouteRaw(method: HTTPMethod, path: string, inputOptions?: any): Promise<Response>;\n}\n\n/**\n * Fluent builder for instantiating fragments.\n * Provides a type-safe API for configuring and building fragment instances.\n */\nexport class FragmentInstantiationBuilder<\n TConfig,\n TOptions extends FragnoPublicConfig,\n TDeps,\n TBaseServices extends Record<string, unknown>,\n TServices extends Record<string, unknown>,\n TServiceDependencies,\n TPrivateServices extends Record<string, unknown>,\n TServiceThisContext extends RequestThisContext,\n THandlerThisContext extends RequestThisContext,\n TRequestStorage,\n TRoutesOrFactories extends readonly AnyRouteOrFactory[],\n TLinkedFragments extends Record<string, AnyFragnoInstantiatedFragment>,\n> implements IFragmentInstantiationBuilder\n{\n #definition: FragmentDefinition<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TLinkedFragments\n >;\n #config?: TConfig;\n #routes?: TRoutesOrFactories;\n #options?: TOptions;\n #services?: TServiceDependencies;\n\n constructor(\n definition: FragmentDefinition<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TLinkedFragments\n >,\n routes?: TRoutesOrFactories,\n ) {\n this.#definition = definition;\n this.#routes = routes;\n }\n\n /**\n * Get the fragment definition\n */\n get definition(): FragmentDefinition<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TLinkedFragments\n > {\n return this.#definition;\n }\n\n /**\n * Get the configured routes\n */\n get routes(): TRoutesOrFactories {\n return this.#routes ?? ([] as const as unknown as TRoutesOrFactories);\n }\n\n /**\n * Get the configuration\n */\n get config(): TConfig | undefined {\n return this.#config;\n }\n\n /**\n * Get the options\n */\n get options(): TOptions | undefined {\n return this.#options;\n }\n\n /**\n * Set the configuration for the fragment\n */\n withConfig(config: TConfig): this {\n this.#config = config;\n return this;\n }\n\n /**\n * Set the routes for the fragment\n */\n withRoutes<const TNewRoutes extends readonly AnyRouteOrFactory[]>(\n routes: TNewRoutes,\n ): FragmentInstantiationBuilder<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TNewRoutes,\n TLinkedFragments\n > {\n const newBuilder = new FragmentInstantiationBuilder(this.#definition, routes);\n // Preserve config, options, and services from the current instance\n newBuilder.#config = this.#config;\n newBuilder.#options = this.#options;\n newBuilder.#services = this.#services;\n return newBuilder;\n }\n\n /**\n * Set the options for the fragment (e.g., mountRoute, databaseAdapter)\n */\n withOptions(options: TOptions): this {\n this.#options = options;\n return this;\n }\n\n /**\n * Provide implementations for services that this fragment uses\n */\n withServices(services: TServiceDependencies): this {\n this.#services = services;\n return this;\n }\n\n /**\n * Build and return the instantiated fragment\n */\n build(): FragnoInstantiatedFragment<\n FlattenRouteFactories<TRoutesOrFactories>,\n TDeps,\n BoundServices<TBaseServices & TServices>,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TOptions,\n TLinkedFragments\n > {\n // This variable is set by the frango-cli when extracting database schemas\n const dryRun = process.env[\"FRAGNO_INIT_DRY_RUN\"] === \"true\";\n\n return instantiateFragment(\n this.#definition,\n this.#config ?? ({} as TConfig),\n this.#routes ?? ([] as const as unknown as TRoutesOrFactories),\n this.#options ?? ({} as TOptions),\n this.#services,\n { dryRun },\n );\n }\n}\n\n/**\n * Create a fluent builder for instantiating a fragment.\n *\n * @example\n * ```ts\n * const fragment = instantiate(myFragmentDefinition)\n * .withConfig({ apiKey: \"key\" })\n * .withRoutes([route1, route2])\n * .withOptions({ mountRoute: \"/api\" })\n * .build();\n * ```\n */\nexport function instantiate<\n TConfig,\n TOptions extends FragnoPublicConfig,\n TDeps,\n TBaseServices extends Record<string, unknown>,\n TServices extends Record<string, unknown>,\n TServiceDependencies,\n TPrivateServices extends Record<string, unknown>,\n TServiceThisContext extends RequestThisContext,\n THandlerThisContext extends RequestThisContext,\n TRequestStorage,\n TLinkedFragments extends Record<string, AnyFragnoInstantiatedFragment>,\n>(\n definition: FragmentDefinition<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TLinkedFragments\n >,\n): FragmentInstantiationBuilder<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n readonly [],\n TLinkedFragments\n> {\n return new FragmentInstantiationBuilder(definition);\n}\n\n// Export interfaces for stub implementations\nexport type { IFragmentInstantiationBuilder, IFragnoInstantiatedFragment };\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuJA,IAAa,6BAAb,MAUA;CACE,CAAU,kCAAkC;CAG5C;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA,YAAY,QAYT;AACD,QAAKA,OAAQ,OAAO;AACpB,QAAKC,SAAU,OAAO;AACtB,QAAKC,OAAQ,OAAO;AACpB,QAAKC,WAAY,OAAO;AACxB,QAAKC,aAAc,OAAO;AAC1B,QAAKC,qBAAsB,OAAO;AAClC,QAAKC,qBAAsB,OAAO;AAClC,QAAKC,iBAAkB,OAAO;AAC9B,QAAKC,uBAAwB,OAAO;AACpC,QAAKC,UAAW,OAAO;AACvB,QAAKC,kBAAmB,OAAO,mBAAoB,EAAE;AAGrD,QAAKC,SACH,cAUG;AAEL,OAAK,MAAM,eAAe,MAAKV,OAC7B,UAAS,MAAKU,QAAS,YAAY,OAAO,aAAa,EAAE,YAAY,MAAM,YAAY;AAIzF,OAAK,UAAU,KAAK,QAAQ,KAAK,KAAK;;CAIxC,IAAI,OAAe;AACjB,SAAO,MAAKX;;CAGd,IAAI,SAAkB;AACpB,SAAO,MAAKC;;CAGd,IAAI,WAAsB;AACxB,SAAO,MAAKE;;CAGd,IAAI,aAAqB;AACvB,SAAO,MAAKC;;;;;CAMd,IAAI,YAAY;AACd,SAAO;GACL,MAAM,MAAKF;GACX,SAAS,MAAKO;GACd,iBAAiB,MAAKC;GACvB;;;;;;CAOH,eAAe,SAAoE;AACjF,MAAI,MAAKE,kBACP,OAAM,IAAI,MAAM,yBAAyB;AAE3C,QAAKA,oBAAqB;AAC1B,SAAO;;CAUT,oBAAuB,UAAgD;AACrE,MAAI,CAAC,MAAKP,sBAAuB,CAAC,MAAKC,mBAErC,QAAO,UAAU;EAInB,MAAM,cAAc,MA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E;AAKJ,QAAO,IAAI,2BAA2B;EACpC,MAAM,WAAW;EACjB;EACA;EACA,UAAU;EACV;EACA,oBAAoB;EACpB,oBAAoB;EACpB;EACA,sBAAsB;EACtB;EACA,iBAAiB;EAClB,CAAC;;;;;;AAsGJ,IAAa,+BAAb,MAAa,6BAcb;CACE;CAaA;CACA;CACA;CACA;CAEA,YACE,YAaA,QACA;AACA,QAAKC,aAAc;AACnB,QAAKrB,SAAU;;;;;CAMjB,IAAI,aAYF;AACA,SAAO,MAAKqB;;;;;CAMd,IAAI,SAA6B;AAC/B,SAAO,MAAKrB,UAAY,EAAE;;;;;CAM5B,IAAI,SAA8B;AAChC,SAAO,MAAKsB;;;;;CAMd,IAAI,UAAgC;AAClC,SAAO,MAAKd;;;;;CAMd,WAAW,QAAuB;AAChC,QAAKc,SAAU;AACf,SAAO;;;;;CAMT,WACE,QAcA;EACA,MAAM,aAAa,IAAI,6BAA6B,MAAKD,YAAa,OAAO;AAE7E,cAAWC,SAAU,MAAKA;AAC1B,cAAWd,UAAW,MAAKA;AAC3B,cAAWN,WAAY,MAAKA;AAC5B,SAAO;;;;;CAMT,YAAY,SAAyB;AACnC,QAAKM,UAAW;AAChB,SAAO;;;;;CAMT,aAAa,UAAsC;AACjD,QAAKN,WAAY;AACjB,SAAO;;;;;CAMT,QASE;EAEA,MAAM,SAAS,QAAQ,IAAI,2BAA2B;AAEtD,SAAO,oBACL,MAAKmB,YACL,MAAKC,UAAY,EAAE,EACnB,MAAKtB,UAAY,EAAE,EACnB,MAAKQ,WAAa,EAAE,EACpB,MAAKN,UACL,EAAE,QAAQ,CACX;;;;;;;;;;;;;;;AAgBL,SAAgB,YAad,YA0BA;AACA,QAAO,IAAI,6BAA6B,WAAW"}
1
+ {"version":3,"file":"fragment-instantiator.js","names":["linkedRoutes: InternalLinkedRouteConfig[]","#name","#routes","#deps","#services","#mountRoute","#serviceThisContext","#handlerThisContext","#contextStorage","#createRequestStorage","#options","#linkedFragments","#internalData","#router","#middlewareHandler","#withRequestStorage","requestBody: RequestBodyType","rawBody: string | undefined","decodedRouteParams: Record<string, string>","#executeMiddleware","#runMiddlewareForFragment","#executeHandler","deps: TDeps","linkedFragmentServices: Record<string, unknown>","services","baseServices: TBaseServices","#definition","#config"],"sources":["../../src/api/fragment-instantiator.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"@standard-schema/spec\";\nimport { type FragnoRouteConfig, type HTTPMethod, type RequestThisContext } from \"./api\";\nimport { FragnoApiError } from \"./error\";\nimport { getMountRoute } from \"./internal/route\";\nimport { addRoute, createRouter, findRoute } from \"rou3\";\nimport { RequestInputContext, type RequestBodyType } from \"./request-input-context\";\nimport type { ExtractPathParams } from \"./internal/path\";\nimport { RequestOutputContext } from \"./request-output-context\";\nimport {\n type AnyFragnoRouteConfig,\n type AnyRouteOrFactory,\n type FlattenRouteFactories,\n resolveRouteFactories,\n} from \"./route\";\nimport {\n RequestMiddlewareInputContext,\n RequestMiddlewareOutputContext,\n type FragnoMiddlewareCallback,\n} from \"./request-middleware\";\nimport { MutableRequestState } from \"./mutable-request-state\";\nimport type { RouteHandlerInputOptions } from \"./route-handler-input-options\";\nimport type { ExtractRouteByPath, ExtractRoutePath } from \"../client/client\";\nimport { type FragnoResponse, parseFragnoResponse } from \"./fragno-response\";\nimport type { InferOrUnknown } from \"../util/types-util\";\nimport type { FragmentDefinition } from \"./fragment-definition-builder\";\nimport type { FragnoPublicConfig } from \"./shared-types\";\nimport { RequestContextStorage } from \"./request-context-storage\";\nimport { bindServicesToContext, type BoundServices } from \"./bind-services\";\nimport { instantiatedFragmentFakeSymbol } from \"../internal/symbols\";\nimport { recordTraceEvent } from \"../internal/trace-context\";\n\n// Re-export types needed by consumers\nexport type { BoundServices };\n\ntype InternalRoutePrefix = \"/_internal\";\n\ntype JoinInternalRoutePath<TPath extends string> = TPath extends \"\" | \"/\"\n ? InternalRoutePrefix\n : TPath extends `/${string}`\n ? `${InternalRoutePrefix}${TPath}`\n : `${InternalRoutePrefix}/${TPath}`;\n\ntype PrefixInternalRoute<TRoute> =\n TRoute extends FragnoRouteConfig<\n infer TMethod,\n infer TPath,\n infer TInputSchema,\n infer TOutputSchema,\n infer TErrorCode,\n infer TQueryParameters,\n infer TThisContext\n >\n ? FragnoRouteConfig<\n TMethod,\n JoinInternalRoutePath<TPath>,\n TInputSchema,\n TOutputSchema,\n TErrorCode,\n TQueryParameters,\n TThisContext\n >\n : never;\n\ntype PrefixInternalRoutes<TRoutes extends readonly AnyFragnoRouteConfig[]> =\n TRoutes extends readonly [...infer TRoutesTuple]\n ? { [K in keyof TRoutesTuple]: PrefixInternalRoute<TRoutesTuple[K]> }\n : readonly AnyFragnoRouteConfig[];\n\ntype ExtractRoutesFromFragment<T> =\n T extends FragnoInstantiatedFragment<\n infer TRoutes,\n infer _TDeps,\n infer _TServices,\n infer _TServiceThisContext,\n infer _THandlerThisContext,\n infer _TRequestStorage,\n infer _TOptions,\n infer _TLinkedFragments\n >\n ? TRoutes\n : never;\n\ntype InternalLinkedRoutes<TLinkedFragments> =\n TLinkedFragments extends Record<string, AnyFragnoInstantiatedFragment>\n ? TLinkedFragments extends { _fragno_internal: infer TInternal }\n ? ExtractRoutesFromFragment<TInternal> extends readonly AnyFragnoRouteConfig[]\n ? PrefixInternalRoutes<ExtractRoutesFromFragment<TInternal>>\n : readonly []\n : readonly []\n : readonly [];\n\nexport type RoutesWithInternal<\n TRoutes extends readonly AnyFragnoRouteConfig[],\n TLinkedFragments,\n> = readonly [...TRoutes, ...InternalLinkedRoutes<TLinkedFragments>];\n\n/**\n * Helper type to extract the instantiated fragment type from a fragment definition.\n * This is useful for typing functions that accept instantiated fragments based on their definition.\n *\n * @example\n * ```typescript\n * const myFragmentDef = defineFragment(\"my-fragment\").build();\n * type MyInstantiatedFragment = InstantiatedFragmentFromDefinition<typeof myFragmentDef>;\n * ```\n */\nexport type InstantiatedFragmentFromDefinition<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n TDef extends FragmentDefinition<any, any, any, any, any, any, any, any, any, any, any>,\n> =\n TDef extends FragmentDefinition<\n infer _TConfig,\n infer TOptions,\n infer TDeps,\n infer TBaseServices,\n infer TServices,\n infer _TServiceDependencies,\n infer _TPrivateServices,\n infer TServiceThisContext,\n infer THandlerThisContext,\n infer TRequestStorage,\n infer TLinkedFragments\n >\n ? FragnoInstantiatedFragment<\n RoutesWithInternal<readonly AnyFragnoRouteConfig[], TLinkedFragments>,\n TDeps,\n BoundServices<TBaseServices & TServices>,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TOptions,\n TLinkedFragments\n >\n : never;\n\ntype AstroHandlers = {\n ALL: (req: Request) => Promise<Response>;\n};\n\ntype ReactRouterHandlers = {\n loader: (args: { request: Request }) => Promise<Response>;\n action: (args: { request: Request }) => Promise<Response>;\n};\n\nconst serializeHeadersForTrace = (headers: Headers): [string, string][] =>\n Array.from(headers.entries()).sort(([a], [b]) => a.localeCompare(b));\n\nconst serializeQueryForTrace = (query: URLSearchParams): [string, string][] =>\n Array.from(query.entries()).sort(([a], [b]) => a.localeCompare(b));\n\nconst serializeBodyForTrace = (body: RequestBodyType): unknown => {\n if (body instanceof FormData) {\n const entries = Array.from(body.entries()).map(([key, value]) => {\n if (value instanceof Blob) {\n return [key, { type: \"blob\", size: value.size, mime: value.type }] as const;\n }\n return [key, value] as const;\n });\n return { type: \"form-data\", entries };\n }\n\n if (body instanceof Blob) {\n return { type: \"blob\", size: body.size, mime: body.type };\n }\n\n if (body instanceof ReadableStream) {\n return { type: \"stream\" };\n }\n\n return body;\n};\n\ntype SolidStartHandlers = {\n GET: (args: { request: Request }) => Promise<Response>;\n POST: (args: { request: Request }) => Promise<Response>;\n PUT: (args: { request: Request }) => Promise<Response>;\n DELETE: (args: { request: Request }) => Promise<Response>;\n PATCH: (args: { request: Request }) => Promise<Response>;\n HEAD: (args: { request: Request }) => Promise<Response>;\n OPTIONS: (args: { request: Request }) => Promise<Response>;\n};\n\ntype TanStackStartHandlers = SolidStartHandlers;\n\ntype StandardHandlers = {\n GET: (req: Request) => Promise<Response>;\n POST: (req: Request) => Promise<Response>;\n PUT: (req: Request) => Promise<Response>;\n DELETE: (req: Request) => Promise<Response>;\n PATCH: (req: Request) => Promise<Response>;\n HEAD: (req: Request) => Promise<Response>;\n OPTIONS: (req: Request) => Promise<Response>;\n};\n\ntype HandlersByFramework = {\n astro: AstroHandlers;\n \"react-router\": ReactRouterHandlers;\n \"next-js\": StandardHandlers;\n \"svelte-kit\": StandardHandlers;\n \"solid-start\": SolidStartHandlers;\n \"tanstack-start\": TanStackStartHandlers;\n};\n\ntype FullstackFrameworks = keyof HandlersByFramework;\n\nexport type AnyFragnoInstantiatedFragment = FragnoInstantiatedFragment<\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n any\n>;\n\nconst INTERNAL_LINKED_FRAGMENT_NAME = \"_fragno_internal\";\nconst INTERNAL_ROUTE_PREFIX = \"/_internal\";\n\ntype InternalLinkedRouteMeta = {\n fragment: AnyFragnoInstantiatedFragment;\n originalPath: string;\n routes: readonly AnyFragnoRouteConfig[];\n};\n\ntype InternalLinkedRouteConfig = AnyFragnoRouteConfig & {\n __internal?: InternalLinkedRouteMeta;\n};\n\nfunction normalizeRoutePrefix(prefix: string): string {\n if (!prefix.startsWith(\"/\")) {\n prefix = `/${prefix}`;\n }\n return prefix.endsWith(\"/\") && prefix.length > 1 ? prefix.slice(0, -1) : prefix;\n}\n\nfunction joinRoutePath(prefix: string, path: string): string {\n const normalizedPrefix = normalizeRoutePrefix(prefix);\n if (!path || path === \"/\") {\n return normalizedPrefix;\n }\n const normalizedPath = path.startsWith(\"/\") ? path : `/${path}`;\n return `${normalizedPrefix}${normalizedPath}`;\n}\n\nfunction collectLinkedFragmentRoutes(\n linkedFragments: Record<string, AnyFragnoInstantiatedFragment>,\n): InternalLinkedRouteConfig[] {\n const linkedRoutes: InternalLinkedRouteConfig[] = [];\n\n for (const [name, fragment] of Object.entries(linkedFragments)) {\n if (name !== INTERNAL_LINKED_FRAGMENT_NAME) {\n continue;\n }\n\n const internalRoutes = (fragment.routes ?? []) as readonly AnyFragnoRouteConfig[];\n if (internalRoutes.length === 0) {\n continue;\n }\n\n for (const route of internalRoutes) {\n linkedRoutes.push({\n ...route,\n path: joinRoutePath(INTERNAL_ROUTE_PREFIX, route.path),\n __internal: {\n fragment,\n originalPath: route.path,\n routes: internalRoutes,\n },\n });\n }\n }\n\n return linkedRoutes;\n}\n\nexport interface FragnoFragmentSharedConfig<\n TRoutes extends readonly FragnoRouteConfig<\n HTTPMethod,\n string,\n StandardSchemaV1 | undefined,\n StandardSchemaV1 | undefined,\n string,\n string\n >[],\n> {\n name: string;\n routes: TRoutes;\n}\n\n/**\n * Instantiated fragment class with encapsulated state.\n * Provides the same public API as the old FragnoInstantiatedFragment but with better encapsulation.\n */\nexport class FragnoInstantiatedFragment<\n TRoutes extends readonly AnyFragnoRouteConfig[],\n TDeps,\n TServices extends Record<string, unknown>,\n TServiceThisContext extends RequestThisContext,\n THandlerThisContext extends RequestThisContext,\n TRequestStorage = {},\n TOptions extends FragnoPublicConfig = FragnoPublicConfig,\n TLinkedFragments extends Record<string, AnyFragnoInstantiatedFragment> = {},\n> implements IFragnoInstantiatedFragment\n{\n readonly [instantiatedFragmentFakeSymbol] = instantiatedFragmentFakeSymbol;\n\n // Private fields\n #name: string;\n #routes: TRoutes;\n #deps: TDeps;\n #services: TServices;\n #mountRoute: string;\n #router: ReturnType<typeof createRouter>;\n #middlewareHandler?: FragnoMiddlewareCallback<TRoutes, TDeps, TServices>;\n #serviceThisContext?: TServiceThisContext; // Context for services (may have restricted capabilities)\n #handlerThisContext?: THandlerThisContext; // Context for handlers (full capabilities)\n #contextStorage: RequestContextStorage<TRequestStorage>;\n #createRequestStorage?: () => TRequestStorage;\n #options: TOptions;\n #linkedFragments: TLinkedFragments;\n #internalData: Record<string, unknown>;\n\n constructor(params: {\n name: string;\n routes: TRoutes;\n deps: TDeps;\n services: TServices;\n mountRoute: string;\n serviceThisContext?: TServiceThisContext;\n handlerThisContext?: THandlerThisContext;\n storage: RequestContextStorage<TRequestStorage>;\n createRequestStorage?: () => TRequestStorage;\n options: TOptions;\n linkedFragments?: TLinkedFragments;\n internalData?: Record<string, unknown>;\n }) {\n this.#name = params.name;\n this.#routes = params.routes;\n this.#deps = params.deps;\n this.#services = params.services;\n this.#mountRoute = params.mountRoute;\n this.#serviceThisContext = params.serviceThisContext;\n this.#handlerThisContext = params.handlerThisContext;\n this.#contextStorage = params.storage;\n this.#createRequestStorage = params.createRequestStorage;\n this.#options = params.options;\n this.#linkedFragments = params.linkedFragments ?? ({} as TLinkedFragments);\n this.#internalData = params.internalData ?? {};\n\n // Build router\n this.#router =\n createRouter<\n FragnoRouteConfig<\n HTTPMethod,\n string,\n StandardSchemaV1 | undefined,\n StandardSchemaV1 | undefined,\n string,\n string,\n RequestThisContext\n >\n >();\n\n for (const routeConfig of this.#routes) {\n addRoute(this.#router, routeConfig.method.toUpperCase(), routeConfig.path, routeConfig);\n }\n\n // Bind handler method to maintain 'this' context\n this.handler = this.handler.bind(this);\n }\n\n // Public getters\n get name(): string {\n return this.#name;\n }\n\n get routes(): TRoutes {\n return this.#routes;\n }\n\n get services(): TServices {\n return this.#services;\n }\n\n get mountRoute(): string {\n return this.#mountRoute;\n }\n\n /**\n * @internal\n */\n get $internal() {\n return {\n deps: this.#deps,\n options: this.#options,\n linkedFragments: this.#linkedFragments,\n ...this.#internalData,\n };\n }\n\n /**\n * Add middleware to this fragment.\n * Middleware can inspect and modify requests before they reach handlers.\n */\n withMiddleware(handler: FragnoMiddlewareCallback<TRoutes, TDeps, TServices>): this {\n if (this.#middlewareHandler) {\n throw new Error(\"Middleware already set\");\n }\n this.#middlewareHandler = handler;\n return this;\n }\n\n /**\n * Run a callback within the fragment's request context with initialized storage.\n * This is a shared helper used by inContext(), handler(), and callRouteRaw().\n * @private\n */\n #withRequestStorage<T>(callback: () => T): T;\n #withRequestStorage<T>(callback: () => Promise<T>): Promise<T>;\n #withRequestStorage<T>(callback: () => T | Promise<T>): T | Promise<T> {\n if (!this.#serviceThisContext && !this.#handlerThisContext) {\n // No request context configured - just run callback directly\n return callback();\n }\n\n // Initialize storage with fresh data for this request\n const storageData = this.#createRequestStorage\n ? this.#createRequestStorage()\n : ({} as TRequestStorage);\n return this.#contextStorage.run(storageData, callback);\n }\n\n /**\n * Execute a callback within a request context.\n * Establishes an async context for the duration of the callback, allowing services\n * to access the `this` context. The callback's `this` will be bound to the fragment's\n * handler context (with full capabilities including execute methods).\n * Useful for calling services outside of route handlers (e.g., in tests, background jobs).\n *\n * @param callback - The callback to run within the context\n *\n * @example\n * ```typescript\n * const result = await fragment.inContext(function () {\n * // `this` is bound to the handler context (can call execute methods)\n * await this.getUnitOfWork().executeRetrieve();\n * return this.someContextMethod();\n * });\n * ```\n */\n inContext<T>(callback: (this: THandlerThisContext) => T): T;\n inContext<T>(callback: (this: THandlerThisContext) => Promise<T>): Promise<T>;\n inContext<T>(callback: (this: THandlerThisContext) => T | Promise<T>): T | Promise<T> {\n // Always use handler context for inContext - it has full capabilities\n if (this.#handlerThisContext) {\n const boundCallback = callback.bind(this.#handlerThisContext);\n return this.#withRequestStorage(boundCallback);\n }\n return this.#withRequestStorage(callback);\n }\n\n /**\n * Get framework-specific handlers for this fragment.\n * Use this to integrate the fragment with different fullstack frameworks.\n */\n handlersFor<T extends FullstackFrameworks>(framework: T): HandlersByFramework[T] {\n const handler = this.handler.bind(this);\n\n // LLMs hallucinate these values sometimes, solution isn't obvious so we throw this error\n // @ts-expect-error TS2367\n if (framework === \"h3\" || framework === \"nuxt\") {\n throw new Error(`To get handlers for h3, use the 'fromWebHandler' utility function:\n import { fromWebHandler } from \"h3\";\n export default fromWebHandler(myFragment().handler);`);\n }\n\n const allHandlers = {\n astro: { ALL: handler },\n \"react-router\": {\n loader: ({ request }: { request: Request }) => handler(request),\n action: ({ request }: { request: Request }) => handler(request),\n },\n \"next-js\": {\n GET: handler,\n POST: handler,\n PUT: handler,\n DELETE: handler,\n PATCH: handler,\n HEAD: handler,\n OPTIONS: handler,\n },\n \"svelte-kit\": {\n GET: handler,\n POST: handler,\n PUT: handler,\n DELETE: handler,\n PATCH: handler,\n HEAD: handler,\n OPTIONS: handler,\n },\n \"solid-start\": {\n GET: ({ request }: { request: Request }) => handler(request),\n POST: ({ request }: { request: Request }) => handler(request),\n PUT: ({ request }: { request: Request }) => handler(request),\n DELETE: ({ request }: { request: Request }) => handler(request),\n PATCH: ({ request }: { request: Request }) => handler(request),\n HEAD: ({ request }: { request: Request }) => handler(request),\n OPTIONS: ({ request }: { request: Request }) => handler(request),\n },\n \"tanstack-start\": {\n GET: ({ request }: { request: Request }) => handler(request),\n POST: ({ request }: { request: Request }) => handler(request),\n PUT: ({ request }: { request: Request }) => handler(request),\n DELETE: ({ request }: { request: Request }) => handler(request),\n PATCH: ({ request }: { request: Request }) => handler(request),\n HEAD: ({ request }: { request: Request }) => handler(request),\n OPTIONS: ({ request }: { request: Request }) => handler(request),\n },\n } satisfies HandlersByFramework;\n\n return allHandlers[framework];\n }\n\n /**\n * Main request handler for this fragment.\n * Handles routing, middleware, and error handling.\n */\n async handler(req: Request): Promise<Response> {\n const url = new URL(req.url);\n const pathname = url.pathname;\n\n // Match route\n const matchRoute = pathname.startsWith(this.#mountRoute)\n ? pathname.slice(this.#mountRoute.length)\n : null;\n\n if (matchRoute === null) {\n return Response.json(\n {\n error:\n `Fragno: Route for '${this.#name}' not found. Is the fragment mounted on the right route? ` +\n `Expecting: '${this.#mountRoute}'.`,\n code: \"ROUTE_NOT_FOUND\",\n },\n { status: 404 },\n );\n }\n\n const route = findRoute(this.#router, req.method, matchRoute);\n\n if (!route) {\n return Response.json(\n { error: `Fragno: Route for '${this.#name}' not found`, code: \"ROUTE_NOT_FOUND\" },\n { status: 404 },\n );\n }\n\n // Get the expected content type from route config (default: application/json)\n const routeConfig = route.data as InternalLinkedRouteConfig;\n const expectedContentType = routeConfig.contentType ?? \"application/json\";\n\n // Parse request body based on route's expected content type\n let requestBody: RequestBodyType = undefined;\n let rawBody: string | undefined = undefined;\n\n if (req.body instanceof ReadableStream) {\n const requestContentType = (req.headers.get(\"content-type\") ?? \"\").toLowerCase();\n\n if (expectedContentType === \"multipart/form-data\") {\n // Route expects FormData (file uploads)\n if (!requestContentType.includes(\"multipart/form-data\")) {\n return Response.json(\n {\n error: `This endpoint expects multipart/form-data, but received: ${requestContentType || \"no content-type\"}`,\n code: \"UNSUPPORTED_MEDIA_TYPE\",\n },\n { status: 415 },\n );\n }\n\n try {\n requestBody = await req.formData();\n } catch {\n return Response.json(\n { error: \"Failed to parse multipart form data\", code: \"INVALID_REQUEST_BODY\" },\n { status: 400 },\n );\n }\n } else if (expectedContentType === \"application/octet-stream\") {\n if (!requestContentType.includes(\"application/octet-stream\")) {\n return Response.json(\n {\n error: `This endpoint expects application/octet-stream, but received: ${requestContentType || \"no content-type\"}`,\n code: \"UNSUPPORTED_MEDIA_TYPE\",\n },\n { status: 415 },\n );\n }\n\n requestBody = req.body ?? new ReadableStream<Uint8Array>();\n } else {\n // Route expects JSON (default)\n // Note: We're lenient here - we accept requests without Content-Type header\n // or with application/json. We reject multipart/form-data for JSON routes.\n if (requestContentType.includes(\"multipart/form-data\")) {\n return Response.json(\n {\n error: `This endpoint expects JSON, but received multipart/form-data. Use a route with contentType: \"multipart/form-data\" for file uploads.`,\n code: \"UNSUPPORTED_MEDIA_TYPE\",\n },\n { status: 415 },\n );\n }\n\n // Clone request to make sure we don't consume body stream\n const clonedReq = req.clone();\n\n // Get raw text\n rawBody = await clonedReq.text();\n\n // Parse JSON if body is not empty\n if (rawBody) {\n try {\n requestBody = JSON.parse(rawBody);\n } catch {\n // If JSON parsing fails, keep body as undefined\n // This handles cases where body is not JSON\n requestBody = undefined;\n }\n }\n }\n }\n\n // URL decode path params from rou3 (which returns encoded values)\n const decodedRouteParams: Record<string, string> = {};\n for (const [key, value] of Object.entries(route.params ?? {})) {\n decodedRouteParams[key] = decodeURIComponent(value);\n }\n\n const requestState = new MutableRequestState({\n pathParams: decodedRouteParams,\n searchParams: url.searchParams,\n body: requestBody,\n headers: new Headers(req.headers),\n });\n\n // Execute middleware and handler\n const executeRequest = async (): Promise<Response> => {\n // Parent middleware execution\n const middlewareResult = await this.#executeMiddleware(req, route, requestState);\n if (middlewareResult !== undefined) {\n return middlewareResult;\n }\n\n // Internal fragment middleware execution (if linked)\n const internalMeta = routeConfig.__internal;\n if (internalMeta) {\n const internalResult = await FragnoInstantiatedFragment.#runMiddlewareForFragment(\n internalMeta.fragment as AnyFragnoInstantiatedFragment,\n {\n req,\n method: routeConfig.method,\n path: internalMeta.originalPath,\n requestState,\n routes: internalMeta.routes,\n },\n );\n if (internalResult !== undefined) {\n return internalResult;\n }\n }\n\n // Handler execution\n return this.#executeHandler(req, route, requestState, rawBody);\n };\n\n // Wrap with request storage context if provided\n return this.#withRequestStorage(executeRequest);\n }\n\n /**\n * Call a route directly with typed inputs and outputs.\n * Useful for testing and server-side route calls.\n */\n async callRoute<TMethod extends HTTPMethod, TPath extends ExtractRoutePath<TRoutes, TMethod>>(\n method: TMethod,\n path: TPath,\n inputOptions?: RouteHandlerInputOptions<\n TPath,\n ExtractRouteByPath<TRoutes, TPath, TMethod>[\"inputSchema\"]\n >,\n ): Promise<\n FragnoResponse<\n InferOrUnknown<NonNullable<ExtractRouteByPath<TRoutes, TPath, TMethod>[\"outputSchema\"]>>\n >\n > {\n const response = await this.callRouteRaw(method, path, inputOptions);\n return parseFragnoResponse(response);\n }\n\n /**\n * Call a route directly and get the raw Response object.\n * Useful for testing and server-side route calls.\n */\n async callRouteRaw<TMethod extends HTTPMethod, TPath extends ExtractRoutePath<TRoutes, TMethod>>(\n method: TMethod,\n path: TPath,\n inputOptions?: RouteHandlerInputOptions<\n TPath,\n ExtractRouteByPath<TRoutes, TPath, TMethod>[\"inputSchema\"]\n >,\n ): Promise<Response> {\n // Find route in this.#routes\n const route = this.#routes.find((r) => r.method === method && r.path === path);\n\n if (!route) {\n return Response.json(\n {\n error: `Route ${method} ${path} not found`,\n code: \"ROUTE_NOT_FOUND\",\n },\n { status: 404 },\n );\n }\n\n const { pathParams = {}, body, query, headers } = inputOptions || {};\n\n // Convert query to URLSearchParams if needed\n const searchParams =\n query instanceof URLSearchParams\n ? query\n : query\n ? new URLSearchParams(query)\n : new URLSearchParams();\n\n const requestHeaders =\n headers instanceof Headers ? headers : headers ? new Headers(headers) : new Headers();\n\n // Construct RequestInputContext\n const inputContext = new RequestInputContext({\n path: route.path,\n method: route.method,\n pathParams: pathParams as ExtractPathParams<typeof route.path>,\n searchParams,\n headers: requestHeaders,\n parsedBody: body,\n inputSchema: route.inputSchema,\n shouldValidateInput: true, // Enable validation for production use\n });\n\n recordTraceEvent({\n type: \"route-input\",\n method: route.method,\n path: route.path,\n pathParams: (pathParams ?? {}) as Record<string, string>,\n queryParams: serializeQueryForTrace(searchParams),\n headers: serializeHeadersForTrace(requestHeaders),\n body: serializeBodyForTrace(body),\n });\n\n // Construct RequestOutputContext\n const outputContext = new RequestOutputContext(route.outputSchema);\n\n // Execute handler\n const executeHandler = async (): Promise<Response> => {\n try {\n // Use handler context (full capabilities)\n const thisContext = this.#handlerThisContext ?? ({} as RequestThisContext);\n return await route.handler.call(thisContext, inputContext, outputContext);\n } catch (error) {\n console.error(\"Error in callRoute handler\", error);\n\n if (error instanceof FragnoApiError) {\n return error.toResponse();\n }\n\n return Response.json(\n { error: \"Internal server error\", code: \"INTERNAL_SERVER_ERROR\" },\n { status: 500 },\n );\n }\n };\n\n // Wrap with request storage context if provided\n return this.#withRequestStorage(executeHandler);\n }\n\n /**\n * Execute middleware for a request.\n * Returns undefined if middleware allows the request to continue to the handler.\n */\n async #executeMiddleware(\n req: Request,\n route: ReturnType<typeof findRoute>,\n requestState: MutableRequestState,\n ): Promise<Response | undefined> {\n if (!route) {\n return undefined;\n }\n\n const { path } = route.data as AnyFragnoRouteConfig;\n return FragnoInstantiatedFragment.#runMiddlewareForFragment(this, {\n req,\n method: req.method as HTTPMethod,\n path,\n requestState,\n });\n }\n\n static async #runMiddlewareForFragment(\n fragment: AnyFragnoInstantiatedFragment,\n options: {\n req: Request;\n method: HTTPMethod;\n path: string;\n requestState: MutableRequestState;\n routes?: readonly AnyFragnoRouteConfig[];\n },\n ): Promise<Response | undefined> {\n if (!fragment.#middlewareHandler) {\n return undefined;\n }\n\n const middlewareInputContext = new RequestMiddlewareInputContext(\n (options.routes ?? fragment.#routes) as readonly AnyFragnoRouteConfig[],\n {\n method: options.method,\n path: options.path,\n request: options.req,\n state: options.requestState,\n },\n );\n\n const middlewareOutputContext = new RequestMiddlewareOutputContext(\n fragment.#deps,\n fragment.#services,\n );\n\n try {\n const middlewareResult = await fragment.#middlewareHandler(\n middlewareInputContext,\n middlewareOutputContext,\n );\n recordTraceEvent({\n type: \"middleware-decision\",\n method: options.method,\n path: options.path,\n outcome: middlewareResult ? \"deny\" : \"allow\",\n status: middlewareResult?.status,\n });\n if (middlewareResult !== undefined) {\n return middlewareResult;\n }\n } catch (error) {\n console.error(\"Error in middleware\", error);\n\n recordTraceEvent({\n type: \"middleware-decision\",\n method: options.method,\n path: options.path,\n outcome: \"deny\",\n status: error instanceof FragnoApiError ? error.status : 500,\n });\n if (error instanceof FragnoApiError) {\n return error.toResponse();\n }\n\n return Response.json(\n { error: \"Internal server error\", code: \"INTERNAL_SERVER_ERROR\" },\n { status: 500 },\n );\n }\n\n return undefined;\n }\n\n /**\n * Execute a route handler with proper error handling.\n */\n async #executeHandler(\n req: Request,\n route: ReturnType<typeof findRoute>,\n requestState: MutableRequestState,\n rawBody?: string,\n ): Promise<Response> {\n if (!route) {\n return Response.json({ error: \"Route not found\", code: \"ROUTE_NOT_FOUND\" }, { status: 404 });\n }\n\n const { handler, inputSchema, outputSchema, path } = route.data as AnyFragnoRouteConfig;\n\n const inputContext = await RequestInputContext.fromRequest({\n request: req,\n method: req.method,\n path,\n pathParams: (route.params ?? {}) as ExtractPathParams<typeof path>,\n inputSchema,\n state: requestState,\n rawBody,\n });\n\n recordTraceEvent({\n type: \"route-input\",\n method: req.method,\n path,\n pathParams: inputContext.pathParams as Record<string, string>,\n queryParams: serializeQueryForTrace(requestState.searchParams),\n headers: serializeHeadersForTrace(requestState.headers),\n body: serializeBodyForTrace(requestState.body),\n });\n\n const outputContext = new RequestOutputContext(outputSchema);\n\n try {\n // Note: We don't call .run() here because the storage should already be initialized\n // by the handler() method or inContext() method before this point\n // Use handler context (full capabilities)\n const contextForHandler = this.#handlerThisContext ?? ({} as RequestThisContext);\n const result = await handler.call(contextForHandler, inputContext, outputContext);\n return result;\n } catch (error) {\n console.error(\"Error in handler\", error);\n\n if (error instanceof FragnoApiError) {\n return error.toResponse();\n }\n\n return Response.json(\n { error: \"Internal server error\", code: \"INTERNAL_SERVER_ERROR\" },\n { status: 500 },\n );\n }\n }\n}\n\n/**\n * Options for fragment instantiation.\n */\nexport interface InstantiationOptions {\n /**\n * If true, catches errors during initialization and returns stub implementations.\n * This is useful for CLI tools that need to extract metadata (like database schemas)\n * without requiring all dependencies to be fully initialized.\n */\n dryRun?: boolean;\n}\n\n/**\n * Core instantiation function that creates a fragment instance from a definition.\n * This function validates dependencies, calls all callbacks, and wires everything together.\n */\nexport function instantiateFragment<\n const TConfig,\n const TOptions extends FragnoPublicConfig,\n const TDeps,\n const TBaseServices extends Record<string, unknown>,\n const TServices extends Record<string, unknown>,\n const TServiceDependencies,\n const TPrivateServices extends Record<string, unknown>,\n const TServiceThisContext extends RequestThisContext,\n const THandlerThisContext extends RequestThisContext,\n const TRequestStorage,\n const TRoutesOrFactories extends readonly AnyRouteOrFactory[],\n const TLinkedFragments extends Record<string, AnyFragnoInstantiatedFragment>,\n>(\n definition: FragmentDefinition<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TLinkedFragments\n >,\n config: TConfig,\n routesOrFactories: TRoutesOrFactories,\n options: TOptions,\n serviceImplementations?: TServiceDependencies,\n instantiationOptions?: InstantiationOptions,\n): FragnoInstantiatedFragment<\n RoutesWithInternal<FlattenRouteFactories<TRoutesOrFactories>, TLinkedFragments>,\n TDeps,\n BoundServices<TBaseServices & TServices>,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TOptions,\n TLinkedFragments\n> {\n const { dryRun = false } = instantiationOptions ?? {};\n\n // 1. Validate service dependencies\n const serviceDependencies = definition.serviceDependencies;\n if (serviceDependencies) {\n for (const [serviceName, meta] of Object.entries(serviceDependencies)) {\n const metadata = meta as { name: string; required: boolean };\n const implementation = serviceImplementations?.[serviceName as keyof TServiceDependencies];\n if (metadata.required && !implementation) {\n throw new Error(\n `Fragment '${definition.name}' requires service '${metadata.name}' but it was not provided`,\n );\n }\n }\n }\n\n // 2. Call dependencies callback\n let deps: TDeps;\n try {\n deps = definition.dependencies?.({ config, options }) ?? ({} as TDeps);\n } catch (error) {\n if (dryRun) {\n console.warn(\n \"Warning: Failed to initialize dependencies in dry run mode:\",\n error instanceof Error ? error.message : String(error),\n );\n // Return empty deps - database fragments will add implicit deps later\n deps = {} as TDeps;\n } else {\n throw error;\n }\n }\n\n // 3. Instantiate linked fragments FIRST (before any services)\n // Their services will be merged into private services\n const linkedFragmentInstances = {} as TLinkedFragments;\n const linkedFragmentServices: Record<string, unknown> = {};\n\n if (definition.linkedFragments) {\n for (const [name, callback] of Object.entries(definition.linkedFragments)) {\n const linkedFragment = callback({\n config,\n options,\n serviceDependencies: serviceImplementations,\n });\n (linkedFragmentInstances as Record<string, AnyFragnoInstantiatedFragment>)[name] =\n linkedFragment;\n\n // Merge all services from linked fragment into private services directly by their service name\n const services = linkedFragment.services as Record<string, unknown>;\n for (const [serviceName, service] of Object.entries(services)) {\n linkedFragmentServices[serviceName] = service;\n }\n }\n }\n\n // Identity function for service definition (used to set 'this' context)\n const defineService = <T>(services: T & ThisType<TServiceThisContext>): T => services;\n\n // 4. Call privateServices factories\n // Private services are instantiated in order, so earlier ones are available to later ones\n // Start with linked fragment services, then add explicitly defined private services\n const privateServices = { ...linkedFragmentServices } as TPrivateServices;\n if (definition.privateServices) {\n for (const [serviceName, factory] of Object.entries(definition.privateServices)) {\n const serviceFactory = factory as (context: {\n config: TConfig;\n options: TOptions;\n deps: TDeps;\n serviceDeps: TServiceDependencies;\n privateServices: TPrivateServices;\n defineService: <T>(svc: T & ThisType<TServiceThisContext>) => T;\n }) => unknown;\n\n try {\n (privateServices as Record<string, unknown>)[serviceName] = serviceFactory({\n config,\n options,\n deps,\n serviceDeps: (serviceImplementations ?? {}) as TServiceDependencies,\n privateServices, // Pass the current state of private services (earlier ones are available)\n defineService,\n });\n } catch (error) {\n if (dryRun) {\n console.warn(\n `Warning: Failed to initialize private service '${serviceName}' in dry run mode:`,\n error instanceof Error ? error.message : String(error),\n );\n (privateServices as Record<string, unknown>)[serviceName] = {};\n } else {\n throw error;\n }\n }\n }\n }\n\n // 5. Call baseServices callback (with access to private services including linked fragment services)\n let baseServices: TBaseServices;\n try {\n baseServices =\n definition.baseServices?.({\n config,\n options,\n deps,\n serviceDeps: (serviceImplementations ?? {}) as TServiceDependencies,\n privateServices,\n defineService,\n }) ?? ({} as TBaseServices);\n } catch (error) {\n if (dryRun) {\n console.warn(\n \"Warning: Failed to initialize base services in dry run mode:\",\n error instanceof Error ? error.message : String(error),\n );\n baseServices = {} as TBaseServices;\n } else {\n throw error;\n }\n }\n\n // 6. Call namedServices factories (with access to private services including linked fragment services)\n const namedServices = {} as TServices;\n if (definition.namedServices) {\n for (const [serviceName, factory] of Object.entries(definition.namedServices)) {\n const serviceFactory = factory as (context: {\n config: TConfig;\n options: TOptions;\n deps: TDeps;\n serviceDeps: TServiceDependencies;\n privateServices: TPrivateServices;\n defineService: <T>(svc: T & ThisType<TServiceThisContext>) => T;\n }) => unknown;\n\n try {\n (namedServices as Record<string, unknown>)[serviceName] = serviceFactory({\n config,\n options,\n deps,\n serviceDeps: (serviceImplementations ?? {}) as TServiceDependencies,\n privateServices,\n defineService,\n });\n } catch (error) {\n if (dryRun) {\n console.warn(\n `Warning: Failed to initialize service '${serviceName}' in dry run mode:`,\n error instanceof Error ? error.message : String(error),\n );\n (namedServices as Record<string, unknown>)[serviceName] = {};\n } else {\n throw error;\n }\n }\n }\n }\n\n // 7. Merge public services (NOT including private services)\n const services = {\n ...baseServices,\n ...namedServices,\n };\n\n // 8. Create request context storage and both service & handler contexts\n // Use external storage if provided, otherwise create new storage\n const storage = definition.getExternalStorage\n ? definition.getExternalStorage({ config, options, deps })\n : new RequestContextStorage<TRequestStorage>();\n\n // Create both contexts using createThisContext (returns { serviceContext, handlerContext })\n const contexts = definition.createThisContext?.({\n config,\n options,\n deps,\n storage,\n });\n\n const serviceContext = contexts?.serviceContext;\n const handlerContext = contexts?.handlerContext;\n const internalData =\n definition.internalDataFactory?.({\n config,\n options,\n deps,\n linkedFragments: linkedFragmentInstances,\n }) ?? {};\n\n // 9. Bind services to serviceContext (restricted)\n // Services get the restricted context (for database fragments, this excludes execute methods)\n const boundServices = serviceContext ? bindServicesToContext(services, serviceContext) : services;\n\n // 10. Resolve routes with bound services\n const context = {\n config,\n deps,\n services: boundServices,\n serviceDeps: serviceImplementations ?? ({} as TServiceDependencies),\n };\n const routes = resolveRouteFactories(context, routesOrFactories) as AnyFragnoRouteConfig[];\n const linkedRoutes = collectLinkedFragmentRoutes(\n linkedFragmentInstances as Record<string, AnyFragnoInstantiatedFragment>,\n );\n const finalRoutes =\n linkedRoutes.length > 0 ? [...routes, ...linkedRoutes] : (routes as AnyFragnoRouteConfig[]);\n\n // 11. Calculate mount route\n const mountRoute = getMountRoute({\n name: definition.name,\n mountRoute: options.mountRoute,\n });\n\n // 12. Wrap createRequestStorage to capture context\n const createRequestStorageWithContext = definition.createRequestStorage\n ? () => definition.createRequestStorage!({ config, options, deps })\n : undefined;\n\n // 13. Create and return fragment instance\n // Pass bound services so they have access to serviceContext via 'this'\n // Handlers get handlerContext which may have more capabilities than serviceContext\n return new FragnoInstantiatedFragment({\n name: definition.name,\n routes: finalRoutes as unknown as RoutesWithInternal<\n FlattenRouteFactories<TRoutesOrFactories>,\n TLinkedFragments\n >,\n deps,\n services: boundServices as BoundServices<TBaseServices & TServices>,\n mountRoute,\n serviceThisContext: serviceContext,\n handlerThisContext: handlerContext,\n storage,\n createRequestStorage: createRequestStorageWithContext,\n options,\n linkedFragments: linkedFragmentInstances,\n internalData: internalData as Record<string, unknown>,\n });\n}\n\n/**\n * Interface that defines the public API for a fragment instantiation builder.\n * Used to ensure consistency between real implementations and stubs.\n */\ninterface IFragmentInstantiationBuilder {\n /**\n * Get the fragment definition\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get definition(): any;\n\n /**\n * Get the configured routes\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get routes(): any;\n\n /**\n * Get the configuration\n */\n get config(): unknown;\n\n /**\n * Get the options\n */\n get options(): unknown;\n\n /**\n * Set the configuration for the fragment\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withConfig(config: any): unknown;\n\n /**\n * Set the routes for the fragment\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withRoutes(routes: any): unknown;\n\n /**\n * Set the options for the fragment (e.g., mountRoute, databaseAdapter)\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withOptions(options: any): unknown;\n\n /**\n * Provide implementations for services that this fragment uses\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withServices(services: any): unknown;\n\n /**\n * Build and return the instantiated fragment\n */\n build(): IFragnoInstantiatedFragment;\n}\n\n/**\n * Interface that defines the public API for an instantiated fragment.\n * Used to ensure consistency between real implementations and stubs.\n */\ninterface IFragnoInstantiatedFragment {\n readonly [instantiatedFragmentFakeSymbol]: typeof instantiatedFragmentFakeSymbol;\n\n get name(): string;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n get routes(): any;\n get services(): Record<string, unknown>;\n get mountRoute(): string;\n get $internal(): {\n deps: unknown;\n options: unknown;\n linkedFragments: unknown;\n } & Record<string, unknown>;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n withMiddleware(handler: any): this;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inContext<T>(callback: any): T;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n inContext<T>(callback: any): Promise<T>;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n handlersFor(framework: FullstackFrameworks): any;\n\n handler(req: Request): Promise<Response>;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callRoute(method: HTTPMethod, path: string, inputOptions?: any): Promise<any>;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n callRouteRaw(method: HTTPMethod, path: string, inputOptions?: any): Promise<Response>;\n}\n\n/**\n * Fluent builder for instantiating fragments.\n * Provides a type-safe API for configuring and building fragment instances.\n */\nexport class FragmentInstantiationBuilder<\n TConfig,\n TOptions extends FragnoPublicConfig,\n TDeps,\n TBaseServices extends Record<string, unknown>,\n TServices extends Record<string, unknown>,\n TServiceDependencies,\n TPrivateServices extends Record<string, unknown>,\n TServiceThisContext extends RequestThisContext,\n THandlerThisContext extends RequestThisContext,\n TRequestStorage,\n TRoutesOrFactories extends readonly AnyRouteOrFactory[],\n TLinkedFragments extends Record<string, AnyFragnoInstantiatedFragment>,\n> implements IFragmentInstantiationBuilder\n{\n #definition: FragmentDefinition<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TLinkedFragments\n >;\n #config?: TConfig;\n #routes?: TRoutesOrFactories;\n #options?: TOptions;\n #services?: TServiceDependencies;\n\n constructor(\n definition: FragmentDefinition<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TLinkedFragments\n >,\n routes?: TRoutesOrFactories,\n ) {\n this.#definition = definition;\n this.#routes = routes;\n }\n\n /**\n * Get the fragment definition\n */\n get definition(): FragmentDefinition<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TLinkedFragments\n > {\n return this.#definition;\n }\n\n /**\n * Get the configured routes\n */\n get routes(): TRoutesOrFactories {\n return this.#routes ?? ([] as const as unknown as TRoutesOrFactories);\n }\n\n /**\n * Get the configuration\n */\n get config(): TConfig | undefined {\n return this.#config;\n }\n\n /**\n * Get the options\n */\n get options(): TOptions | undefined {\n return this.#options;\n }\n\n /**\n * Set the configuration for the fragment\n */\n withConfig(config: TConfig): this {\n this.#config = config;\n return this;\n }\n\n /**\n * Set the routes for the fragment\n */\n withRoutes<const TNewRoutes extends readonly AnyRouteOrFactory[]>(\n routes: TNewRoutes,\n ): FragmentInstantiationBuilder<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TNewRoutes,\n TLinkedFragments\n > {\n const newBuilder = new FragmentInstantiationBuilder(this.#definition, routes);\n // Preserve config, options, and services from the current instance\n newBuilder.#config = this.#config;\n newBuilder.#options = this.#options;\n newBuilder.#services = this.#services;\n return newBuilder;\n }\n\n /**\n * Set the options for the fragment (e.g., mountRoute, databaseAdapter)\n */\n withOptions(options: TOptions): this {\n this.#options = options;\n return this;\n }\n\n /**\n * Provide implementations for services that this fragment uses\n */\n withServices(services: TServiceDependencies): this {\n this.#services = services;\n return this;\n }\n\n /**\n * Build and return the instantiated fragment\n */\n build(): FragnoInstantiatedFragment<\n RoutesWithInternal<FlattenRouteFactories<TRoutesOrFactories>, TLinkedFragments>,\n TDeps,\n BoundServices<TBaseServices & TServices>,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TOptions,\n TLinkedFragments\n > {\n // This variable is set by the frango-cli when extracting database schemas\n const dryRun = process.env[\"FRAGNO_INIT_DRY_RUN\"] === \"true\";\n\n return instantiateFragment(\n this.#definition,\n this.#config ?? ({} as TConfig),\n this.#routes ?? ([] as const as unknown as TRoutesOrFactories),\n this.#options ?? ({} as TOptions),\n this.#services,\n { dryRun },\n );\n }\n}\n\n/**\n * Create a fluent builder for instantiating a fragment.\n *\n * @example\n * ```ts\n * const fragment = instantiate(myFragmentDefinition)\n * .withConfig({ apiKey: \"key\" })\n * .withRoutes([route1, route2])\n * .withOptions({ mountRoute: \"/api\" })\n * .build();\n * ```\n */\nexport function instantiate<\n TConfig,\n TOptions extends FragnoPublicConfig,\n TDeps,\n TBaseServices extends Record<string, unknown>,\n TServices extends Record<string, unknown>,\n TServiceDependencies,\n TPrivateServices extends Record<string, unknown>,\n TServiceThisContext extends RequestThisContext,\n THandlerThisContext extends RequestThisContext,\n TRequestStorage,\n TLinkedFragments extends Record<string, AnyFragnoInstantiatedFragment>,\n>(\n definition: FragmentDefinition<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TLinkedFragments\n >,\n): FragmentInstantiationBuilder<\n TConfig,\n TOptions,\n TDeps,\n TBaseServices,\n TServices,\n TServiceDependencies,\n TPrivateServices,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n readonly [],\n TLinkedFragments\n> {\n return new FragmentInstantiationBuilder(definition);\n}\n\n// Export interfaces for stub implementations\nexport type { IFragmentInstant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AACA,QAAKC,aAAc;AACnB,QAAKxB,SAAU;;;;;CAMjB,IAAI,aAYF;AACA,SAAO,MAAKwB;;;;;CAMd,IAAI,SAA6B;AAC/B,SAAO,MAAKxB,UAAY,EAAE;;;;;CAM5B,IAAI,SAA8B;AAChC,SAAO,MAAKyB;;;;;CAMd,IAAI,UAAgC;AAClC,SAAO,MAAKjB;;;;;CAMd,WAAW,QAAuB;AAChC,QAAKiB,SAAU;AACf,SAAO;;;;;CAMT,WACE,QAcA;EACA,MAAM,aAAa,IAAI,6BAA6B,MAAKD,YAAa,OAAO;AAE7E,cAAWC,SAAU,MAAKA;AAC1B,cAAWjB,UAAW,MAAKA;AAC3B,cAAWN,WAAY,MAAKA;AAC5B,SAAO;;;;;CAMT,YAAY,SAAyB;AACnC,QAAKM,UAAW;AAChB,SAAO;;;;;CAMT,aAAa,UAAsC;AACjD,QAAKN,WAAY;AACjB,SAAO;;;;;CAMT,QASE;EAEA,MAAM,SAAS,QAAQ,IAAI,2BAA2B;AAEtD,SAAO,oBACL,MAAKsB,YACL,MAAKC,UAAY,EAAE,EACnB,MAAKzB,UAAY,EAAE,EACnB,MAAKQ,WAAa,EAAE,EACpB,MAAKN,UACL,EAAE,QAAQ,CACX;;;;;;;;;;;;;;;AAgBL,SAAgB,YAad,YA0BA;AACA,QAAO,IAAI,6BAA6B,WAAW"}
@@ -4,7 +4,7 @@ import { HTTPMethod } from "./api.js";
4
4
  import { StandardSchemaV1 } from "@standard-schema/spec";
5
5
 
6
6
  //#region src/api/request-input-context.d.ts
7
- type RequestBodyType = unknown | FormData | Blob | null | undefined;
7
+ type RequestBodyType = unknown | FormData | Blob | ReadableStream<Uint8Array> | null | undefined;
8
8
  declare class RequestInputContext<TPath extends string = string, TInputSchema extends StandardSchemaV1 | undefined = undefined> {
9
9
  #private;
10
10
  constructor(config: {
@@ -75,6 +75,62 @@ declare class RequestInputContext<TPath extends string = string, TInputSchema ex
75
75
  */
76
76
  get headers(): Headers;
77
77
  get rawBody(): string | undefined;
78
+ /**
79
+ * Access the request body as FormData.
80
+ *
81
+ * Use this method when handling file uploads or multipart form submissions.
82
+ * The request must have been sent with Content-Type: multipart/form-data.
83
+ *
84
+ * @throws Error if the request body is not FormData
85
+ *
86
+ * @example
87
+ * ```typescript
88
+ * defineRoute({
89
+ * method: "POST",
90
+ * path: "/upload",
91
+ * async handler(ctx, res) {
92
+ * const formData = ctx.formData();
93
+ * const file = formData.get("file") as File;
94
+ * const description = formData.get("description") as string;
95
+ * // ... process file
96
+ * }
97
+ * });
98
+ * ```
99
+ */
100
+ formData(): FormData;
101
+ /**
102
+ * Check if the request body is FormData.
103
+ *
104
+ * Useful for routes that accept both JSON and FormData payloads.
105
+ *
106
+ * @example
107
+ * ```typescript
108
+ * defineRoute({
109
+ * method: "POST",
110
+ * path: "/upload",
111
+ * async handler(ctx, res) {
112
+ * if (ctx.isFormData()) {
113
+ * const formData = ctx.formData();
114
+ * // handle file upload
115
+ * } else {
116
+ * const json = await ctx.input.valid();
117
+ * // handle JSON payload
118
+ * }
119
+ * }
120
+ * });
121
+ * ```
122
+ */
123
+ isFormData(): boolean;
124
+ /**
125
+ * Access the request body as a ReadableStream (application/octet-stream).
126
+ *
127
+ * @throws Error if the request body is not a ReadableStream
128
+ */
129
+ bodyStream(): ReadableStream<Uint8Array>;
130
+ /**
131
+ * Check if the request body is a ReadableStream.
132
+ */
133
+ isBodyStream(): boolean;
78
134
  /**
79
135
  * Input validation context (only if inputSchema is defined)
80
136
  * @remarks `InputContext`