@fragno-dev/core 0.1.10 → 0.1.11

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.
@@ -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","linkedFragmentServices: Record<string, unknown>","services","#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\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\n// Safe: This is a catch-all type for any instantiated fragment\ntype 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 type { AnyFragnoInstantiatedFragment };\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> {\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 // Convert headers to Headers if needed\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 * 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): FragnoInstantiatedFragment<\n FlattenRouteFactories<TRoutesOrFactories>,\n TDeps,\n BoundServices<TBaseServices & TServices>,\n TServiceThisContext,\n THandlerThisContext,\n TRequestStorage,\n TOptions,\n TLinkedFragments\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 const deps = definition.dependencies?.({ config, options }) ?? ({} as TDeps);\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 (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 }\n }\n\n // 5. Call baseServices callback (with access to private services including linked fragment services)\n const baseServices =\n definition.baseServices?.({\n config,\n options,\n deps,\n serviceDeps: (serviceImplementations ?? {}) as TServiceDependencies,\n privateServices,\n defineService,\n }) ?? ({} as TBaseServices);\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 (namedServices as Record<string, unknown>)[serviceName] = serviceFactory({\n config,\n options,\n deps,\n serviceDeps: (serviceImplementations ?? {}) as TServiceDependencies,\n privateServices,\n defineService,\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 * 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> {\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 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 );\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"],"mappings":";;;;;;;;;;;;;;;;;;AAmHA,IAAa,6BAAb,MASE;CACA,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,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U;;;;;CAMjB,IAAI,aAYF;AACA,SAAO,MAAKmB;;;;;CAMd,IAAI,SAA6B;AAC/B,SAAO,MAAKnB,UAAY,EAAE;;;;;CAM5B,IAAI,SAA8B;AAChC,SAAO,MAAKoB;;;;;CAMd,IAAI,UAAgC;AAClC,SAAO,MAAKZ;;;;;CAMd,WAAW,QAAuB;AAChC,QAAKY,SAAU;AACf,SAAO;;;;;CAMT,WACE,QAcA;EACA,MAAM,aAAa,IAAI,6BAA6B,MAAKD,YAAa,OAAO;AAE7E,cAAWC,SAAU,MAAKA;AAC1B,cAAWZ,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;AACA,SAAO,oBACL,MAAKiB,YACL,MAAKC,UAAY,EAAE,EACnB,MAAKpB,UAAY,EAAE,EACnB,MAAKQ,WAAa,EAAE,EACpB,MAAKN,SACN;;;;;;;;;;;;;;;AAgBL,SAAgB,YAad,YA0BA;AACA,QAAO,IAAI,6BAA6B,WAAW"}
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;;CA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AAO;;;;;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"}
@@ -3,7 +3,7 @@ import { FragnoRouteConfig, RequestThisContext } from "./api/api.js";
3
3
  import { BoundServices } from "./api/bind-services.js";
4
4
  import { RouteFactory, RouteFactoryContext, defineRoute, defineRoutes } from "./api/route.js";
5
5
  import { instantiatedFragmentFakeSymbol } from "./internal/symbols.js";
6
- import { FragmentInstantiationBuilder, FragnoInstantiatedFragment } from "./api/fragment-instantiator.js";
6
+ import { FragmentInstantiationBuilder, FragnoInstantiatedFragment, IFragmentInstantiationBuilder, InstantiatedFragmentFromDefinition } from "./api/fragment-instantiator.js";
7
7
  import { FragmentDefinition, FragmentDefinitionBuilder, ServiceConstructorFn, ServiceContext } from "./api/fragment-definition-builder.js";
8
8
 
9
9
  //#region src/mod-client.d.ts
@@ -19,19 +19,11 @@ declare function defineFragment(_name: string): {
19
19
  withThisContext: () => /*elided*/any;
20
20
  withLinkedFragment: () => /*elided*/any;
21
21
  extend: () => /*elided*/any;
22
- build: () => {};
23
- };
24
- declare function instantiate(_definition: unknown): {
25
- withConfig: () => /*elided*/any;
26
- withRoutes: () => /*elided*/any;
27
- withOptions: () => /*elided*/any;
28
- withServices: () => /*elided*/any;
29
- build: () => {};
30
- definition: {};
31
- routes: never[];
32
- config: undefined;
33
- options: undefined;
22
+ build: () => {
23
+ name: string;
24
+ };
34
25
  };
26
+ declare function instantiate(_definition: unknown): IFragmentInstantiationBuilder;
35
27
  //#endregion
36
- export { type BoundServices, type FragmentDefinition, FragmentDefinitionBuilder, type FragmentInstantiationBuilder, type FragnoInstantiatedFragment, type FragnoPublicConfig, type FragnoRouteConfig, type RequestThisContext, type RouteFactory, type RouteFactoryContext, type ServiceConstructorFn, type ServiceContext, defineFragment, defineRoute, defineRoutes, instantiate, instantiatedFragmentFakeSymbol };
28
+ export { type BoundServices, type FragmentDefinition, FragmentDefinitionBuilder, type FragmentInstantiationBuilder, type FragnoInstantiatedFragment, type FragnoPublicConfig, type FragnoRouteConfig, type InstantiatedFragmentFromDefinition, type RequestThisContext, type RouteFactory, type RouteFactoryContext, type ServiceConstructorFn, type ServiceContext, defineFragment, defineRoute, defineRoutes, instantiate, instantiatedFragmentFakeSymbol };
37
29
  //# sourceMappingURL=mod-client.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"mod-client.d.ts","names":[],"sources":["../src/mod-client.ts"],"sourcesContent":[],"mappings":";;;;;;;;;iBAyBgB,cAAA;;;;;;;EAAA,kBAAc,EAAA,GAAA,GAAA,UAAA,GAAA;EAuBd,0BAAW,EAAA,GAAA,GAAA,UAAA,GAAA;;;;;;iBAAX,WAAA"}
1
+ {"version":3,"file":"mod-client.d.ts","names":[],"sources":["../src/mod-client.ts"],"sourcesContent":[],"mappings":";;;;;;;;;iBAgCgB,cAAA;;;;;;EAAA,mBAAc,EAAA,GAAA,GAAA,UAAA,GAAA;EA2Bd,kBAAW,EAAA,GAAA,GAAqB,UAAA,GAAA;;;;;;;;;iBAAhC,WAAA,wBAAgC"}
@@ -1,9 +1,10 @@
1
+ import { instantiatedFragmentFakeSymbol } from "./internal/symbols.js";
1
2
  import { FragmentDefinitionBuilder } from "./api/fragment-definition-builder.js";
2
3
  import { defineRoute, defineRoutes } from "./api/route.js";
3
- import { instantiatedFragmentFakeSymbol } from "./internal/symbols.js";
4
4
 
5
5
  //#region src/mod-client.ts
6
6
  function defineFragment(_name) {
7
+ const definitionStub = { name: _name };
7
8
  const stub = {
8
9
  withDependencies: () => stub,
9
10
  providesBaseService: () => stub,
@@ -16,23 +17,49 @@ function defineFragment(_name) {
16
17
  withThisContext: () => stub,
17
18
  withLinkedFragment: () => stub,
18
19
  extend: () => stub,
19
- build: () => ({})
20
+ build: () => definitionStub
20
21
  };
21
22
  return stub;
22
23
  }
23
24
  function instantiate(_definition) {
24
- const stub = {
25
- withConfig: () => stub,
26
- withRoutes: () => stub,
27
- withOptions: () => stub,
28
- withServices: () => stub,
29
- build: () => ({}),
25
+ const fragmentStub = {
26
+ [instantiatedFragmentFakeSymbol]: instantiatedFragmentFakeSymbol,
27
+ name: "",
28
+ routes: [],
29
+ services: {},
30
+ mountRoute: "",
31
+ get $internal() {
32
+ return {
33
+ deps: {},
34
+ options: {},
35
+ linkedFragments: {}
36
+ };
37
+ },
38
+ withMiddleware: () => {
39
+ return fragmentStub;
40
+ },
41
+ inContext: (callback) => callback(),
42
+ handlersFor: () => ({}),
43
+ handler: async () => new Response(),
44
+ callRoute: async () => ({
45
+ ok: true,
46
+ data: void 0,
47
+ error: void 0
48
+ }),
49
+ callRouteRaw: async () => new Response()
50
+ };
51
+ const builderStub = {
52
+ withConfig: () => builderStub,
53
+ withRoutes: () => builderStub,
54
+ withOptions: () => builderStub,
55
+ withServices: () => builderStub,
56
+ build: () => fragmentStub,
30
57
  definition: {},
31
58
  routes: [],
32
59
  config: void 0,
33
60
  options: void 0
34
61
  };
35
- return stub;
62
+ return builderStub;
36
63
  }
37
64
 
38
65
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"mod-client.js","names":[],"sources":["../src/mod-client.ts"],"sourcesContent":["// ============================================================================\n// Client-side entry point for @fragno-dev/core\n// This file mirrors mod.ts but provides stub implementations for server-side\n// APIs that are stripped by unplugin-fragno during browser builds.\n// ============================================================================\n\n// ============================================================================\n// Fragment Definition and Instantiation\n// ============================================================================\n\n// Re-export types only\nexport type {\n FragmentDefinition,\n ServiceContext,\n ServiceConstructorFn,\n} from \"./api/fragment-definition-builder\";\n\nexport type {\n FragmentInstantiationBuilder,\n FragnoInstantiatedFragment,\n BoundServices,\n} from \"./api/fragment-instantiator\";\n\n// Stub implementation for defineFragment\n// This is stripped by unplugin-fragno in browser builds\nexport function defineFragment(_name: string) {\n const stub = {\n withDependencies: () => stub,\n providesBaseService: () => stub,\n providesService: () => stub,\n providesPrivateService: () => stub,\n usesService: () => stub,\n usesOptionalService: () => stub,\n withRequestStorage: () => stub,\n withExternalRequestStorage: () => stub,\n withThisContext: () => stub,\n withLinkedFragment: () => stub,\n extend: () => stub,\n build: () => ({}),\n };\n return stub;\n}\n\n// Re-export the builder class (for type compatibility)\nexport { FragmentDefinitionBuilder } from \"./api/fragment-definition-builder\";\n\n// Stub implementation for instantiate\n// This is stripped by unplugin-fragno in browser builds\nexport function instantiate(_definition: unknown) {\n const stub = {\n withConfig: () => stub,\n withRoutes: () => stub,\n withOptions: () => stub,\n withServices: () => stub,\n build: () => ({}),\n definition: {},\n routes: [],\n config: undefined,\n options: undefined,\n };\n return stub;\n}\n\n// ============================================================================\n// Core Configuration\n// ============================================================================\nexport type { FragnoPublicConfig } from \"./api/shared-types\";\n\n// ============================================================================\n// Route Definition\n// ============================================================================\nexport {\n defineRoute,\n defineRoutes,\n type RouteFactory,\n type RouteFactoryContext,\n} from \"./api/route\";\n\nexport type { FragnoRouteConfig, RequestThisContext } from \"./api/api\";\n\nexport { instantiatedFragmentFakeSymbol } from \"./internal/symbols\";\n"],"mappings":";;;;;AAyBA,SAAgB,eAAe,OAAe;CAC5C,MAAM,OAAO;EACX,wBAAwB;EACxB,2BAA2B;EAC3B,uBAAuB;EACvB,8BAA8B;EAC9B,mBAAmB;EACnB,2BAA2B;EAC3B,0BAA0B;EAC1B,kCAAkC;EAClC,uBAAuB;EACvB,0BAA0B;EAC1B,cAAc;EACd,cAAc,EAAE;EACjB;AACD,QAAO;;AAQT,SAAgB,YAAY,aAAsB;CAChD,MAAM,OAAO;EACX,kBAAkB;EAClB,kBAAkB;EAClB,mBAAmB;EACnB,oBAAoB;EACpB,cAAc,EAAE;EAChB,YAAY,EAAE;EACd,QAAQ,EAAE;EACV,QAAQ;EACR,SAAS;EACV;AACD,QAAO"}
1
+ {"version":3,"file":"mod-client.js","names":["fragmentStub: IFragnoInstantiatedFragment","builderStub: IFragmentInstantiationBuilder"],"sources":["../src/mod-client.ts"],"sourcesContent":["// ============================================================================\n// Client-side entry point for @fragno-dev/core\n// This file mirrors mod.ts but provides stub implementations for server-side\n// APIs that are stripped by unplugin-fragno during browser builds.\n// ============================================================================\n\n// ============================================================================\n// Fragment Definition and Instantiation\n// ============================================================================\n\n// Re-export types only\nexport type {\n FragmentDefinition,\n ServiceContext,\n ServiceConstructorFn,\n} from \"./api/fragment-definition-builder\";\n\nexport type {\n FragmentInstantiationBuilder,\n FragnoInstantiatedFragment,\n BoundServices,\n InstantiatedFragmentFromDefinition,\n} from \"./api/fragment-instantiator\";\n\nimport type {\n IFragmentInstantiationBuilder,\n IFragnoInstantiatedFragment,\n} from \"./api/fragment-instantiator\";\nimport { instantiatedFragmentFakeSymbol } from \"./internal/symbols\";\n\n// Stub implementation for defineFragment\n// This is stripped by unplugin-fragno in browser builds\nexport function defineFragment(_name: string) {\n const definitionStub = {\n name: _name,\n };\n\n const stub = {\n withDependencies: () => stub,\n providesBaseService: () => stub,\n providesService: () => stub,\n providesPrivateService: () => stub,\n usesService: () => stub,\n usesOptionalService: () => stub,\n withRequestStorage: () => stub,\n withExternalRequestStorage: () => stub,\n withThisContext: () => stub,\n withLinkedFragment: () => stub,\n extend: () => stub,\n build: () => definitionStub,\n };\n return stub;\n}\n\n// Re-export the builder class (for type compatibility)\nexport { FragmentDefinitionBuilder } from \"./api/fragment-definition-builder\";\n\n// Stub implementation for instantiate\n// This is stripped by unplugin-fragno in browser builds\nexport function instantiate(_definition: unknown) {\n const fragmentStub: IFragnoInstantiatedFragment = {\n [instantiatedFragmentFakeSymbol]: instantiatedFragmentFakeSymbol,\n name: \"\",\n routes: [],\n services: {},\n mountRoute: \"\",\n get $internal() {\n return {\n deps: {},\n options: {},\n linkedFragments: {},\n };\n },\n withMiddleware: () => {\n // throw new Error(\"withMiddleware is not supported in browser builds\");\n return fragmentStub;\n },\n inContext: <T>(callback: () => T) => callback(),\n handlersFor: () => ({}),\n handler: async () => new Response(),\n callRoute: async () => ({ ok: true, data: undefined, error: undefined }),\n callRouteRaw: async () => new Response(),\n };\n\n const builderStub: IFragmentInstantiationBuilder = {\n withConfig: () => builderStub,\n withRoutes: () => builderStub,\n withOptions: () => builderStub,\n withServices: () => builderStub,\n build: () => fragmentStub,\n definition: {},\n routes: [],\n config: undefined,\n options: undefined,\n };\n\n return builderStub;\n}\n\n// ============================================================================\n// Core Configuration\n// ============================================================================\nexport type { FragnoPublicConfig } from \"./api/shared-types\";\n\n// ============================================================================\n// Route Definition\n// ============================================================================\nexport {\n defineRoute,\n defineRoutes,\n type RouteFactory,\n type RouteFactoryContext,\n} from \"./api/route\";\n\nexport type { FragnoRouteConfig, RequestThisContext } from \"./api/api\";\n\nexport { instantiatedFragmentFakeSymbol } from \"./internal/symbols\";\n"],"mappings":";;;;;AAgCA,SAAgB,eAAe,OAAe;CAC5C,MAAM,iBAAiB,EACrB,MAAM,OACP;CAED,MAAM,OAAO;EACX,wBAAwB;EACxB,2BAA2B;EAC3B,uBAAuB;EACvB,8BAA8B;EAC9B,mBAAmB;EACnB,2BAA2B;EAC3B,0BAA0B;EAC1B,kCAAkC;EAClC,uBAAuB;EACvB,0BAA0B;EAC1B,cAAc;EACd,aAAa;EACd;AACD,QAAO;;AAQT,SAAgB,YAAY,aAAsB;CAChD,MAAMA,eAA4C;GAC/C,iCAAiC;EAClC,MAAM;EACN,QAAQ,EAAE;EACV,UAAU,EAAE;EACZ,YAAY;EACZ,IAAI,YAAY;AACd,UAAO;IACL,MAAM,EAAE;IACR,SAAS,EAAE;IACX,iBAAiB,EAAE;IACpB;;EAEH,sBAAsB;AAEpB,UAAO;;EAET,YAAe,aAAsB,UAAU;EAC/C,oBAAoB,EAAE;EACtB,SAAS,YAAY,IAAI,UAAU;EACnC,WAAW,aAAa;GAAE,IAAI;GAAM,MAAM;GAAW,OAAO;GAAW;EACvE,cAAc,YAAY,IAAI,UAAU;EACzC;CAED,MAAMC,cAA6C;EACjD,kBAAkB;EAClB,kBAAkB;EAClB,mBAAmB;EACnB,oBAAoB;EACpB,aAAa;EACb,YAAY,EAAE;EACd,QAAQ,EAAE;EACV,QAAQ;EACR,SAAS;EACV;AAED,QAAO"}
package/dist/mod.d.ts CHANGED
@@ -2,6 +2,6 @@ import { FragnoPublicConfig } from "./api/shared-types.js";
2
2
  import { FragnoRouteConfig, RequestThisContext } from "./api/api.js";
3
3
  import { BoundServices } from "./api/bind-services.js";
4
4
  import { RouteFactory, RouteFactoryContext, defineRoute, defineRoutes } from "./api/route.js";
5
- import { AnyFragnoInstantiatedFragment, FragmentInstantiationBuilder, FragnoInstantiatedFragment, instantiate } from "./api/fragment-instantiator.js";
5
+ import { AnyFragnoInstantiatedFragment, FragmentInstantiationBuilder, FragnoInstantiatedFragment, InstantiatedFragmentFromDefinition, instantiate } from "./api/fragment-instantiator.js";
6
6
  import { ExtractLinkedServices, FragmentDefinition, FragmentDefinitionBuilder, LinkedFragmentCallback, ServiceConstructorFn, ServiceContext, defineFragment } from "./api/fragment-definition-builder.js";
7
- export { type AnyFragnoInstantiatedFragment, type BoundServices, type ExtractLinkedServices, type FragmentDefinition, FragmentDefinitionBuilder, type FragmentInstantiationBuilder, type FragnoInstantiatedFragment, type FragnoPublicConfig, type FragnoRouteConfig, type LinkedFragmentCallback, type RequestThisContext, type RouteFactory, type RouteFactoryContext, type ServiceConstructorFn, type ServiceContext, defineFragment, defineRoute, defineRoutes, instantiate };
7
+ export { type AnyFragnoInstantiatedFragment, type BoundServices, type ExtractLinkedServices, type FragmentDefinition, FragmentDefinitionBuilder, type FragmentInstantiationBuilder, type FragnoInstantiatedFragment, type FragnoPublicConfig, type FragnoRouteConfig, type InstantiatedFragmentFromDefinition, type LinkedFragmentCallback, type RequestThisContext, type RouteFactory, type RouteFactoryContext, type ServiceConstructorFn, type ServiceContext, defineFragment, defineRoute, defineRoutes, instantiate };
package/package.json CHANGED
@@ -1,9 +1,16 @@
1
1
  {
2
2
  "name": "@fragno-dev/core",
3
- "version": "0.1.10",
3
+ "version": "0.1.11",
4
4
  "exports": {
5
5
  ".": {
6
- "development": "./src/mod.ts",
6
+ "workerd": {
7
+ "development": "./src/mod.ts",
8
+ "default": "./dist/mod.js"
9
+ },
10
+ "development": {
11
+ "browser": "./src/mod-client.ts",
12
+ "default": "./src/mod.ts"
13
+ },
7
14
  "browser": "./dist/mod-client.js",
8
15
  "types": "./dist/mod.d.ts",
9
16
  "default": "./dist/mod.js"
package/src/api/api.ts CHANGED
@@ -2,6 +2,8 @@ import type { StandardSchemaV1 } from "@standard-schema/spec";
2
2
  import type { RequestInputContext } from "./request-input-context";
3
3
  import type { RequestOutputContext } from "./request-output-context";
4
4
 
5
+ export type { StandardSchemaV1 } from "@standard-schema/spec";
6
+
5
7
  export type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS";
6
8
  export type NonGetHTTPMethod = Exclude<HTTPMethod, "GET">;
7
9
 
@@ -1,6 +1,10 @@
1
1
  import { describe, it, expect, vi, expectTypeOf } from "vitest";
2
2
  import { defineFragment } from "./fragment-definition-builder";
3
- import { instantiate, FragnoInstantiatedFragment } from "./fragment-instantiator";
3
+ import {
4
+ instantiate,
5
+ instantiateFragment,
6
+ FragnoInstantiatedFragment,
7
+ } from "./fragment-instantiator";
4
8
  import { defineRoute, defineRoutes, type AnyFragmentDefinition } from "./route";
5
9
  import type { FragnoPublicConfig } from "./shared-types";
6
10
  import type { RequestThisContext } from "./api";
@@ -1485,4 +1489,142 @@ describe("fragment-instantiator", () => {
1485
1489
  expect(data.code).toBe("INTERNAL_SERVER_ERROR");
1486
1490
  });
1487
1491
  });
1492
+
1493
+ describe("dry run mode", () => {
1494
+ it("should handle dependency errors in dry run mode", () => {
1495
+ interface Config {
1496
+ requiredKey: string;
1497
+ }
1498
+
1499
+ const definition = defineFragment<Config>("test-fragment")
1500
+ .withDependencies(({ config }) => {
1501
+ if (!config.requiredKey) {
1502
+ throw new Error("Missing required key");
1503
+ }
1504
+ return { key: config.requiredKey };
1505
+ })
1506
+ .build();
1507
+
1508
+ // Without dry run - should throw
1509
+ expect(() => {
1510
+ instantiateFragment(definition, {} as Config, [], {});
1511
+ }).toThrow("Missing required key");
1512
+
1513
+ // With dry run - should succeed with stub deps
1514
+ const fragment = instantiateFragment(definition, {} as Config, [], {}, undefined, {
1515
+ dryRun: true,
1516
+ });
1517
+
1518
+ expect(fragment).toBeInstanceOf(FragnoInstantiatedFragment);
1519
+ expect(fragment.$internal.deps).toEqual({});
1520
+ });
1521
+
1522
+ it("should handle service errors in dry run mode", () => {
1523
+ interface Config {
1524
+ value: string;
1525
+ }
1526
+
1527
+ const definition = defineFragment<Config>("test-fragment")
1528
+ .withDependencies(({ config }) => {
1529
+ if (!config.value) {
1530
+ throw new Error("Missing value");
1531
+ }
1532
+ return { val: config.value };
1533
+ })
1534
+ .providesBaseService(({ deps }) => {
1535
+ if (!deps.val) {
1536
+ throw new Error("Missing deps.val");
1537
+ }
1538
+ return {
1539
+ getValue: () => deps.val,
1540
+ };
1541
+ })
1542
+ .build();
1543
+
1544
+ // Without dry run - should throw during deps initialization
1545
+ expect(() => {
1546
+ instantiateFragment(definition, {} as Config, [], {});
1547
+ }).toThrow("Missing value");
1548
+
1549
+ // With dry run - should succeed with stub services
1550
+ const fragment = instantiateFragment(definition, {} as Config, [], {}, undefined, {
1551
+ dryRun: true,
1552
+ });
1553
+
1554
+ expect(fragment).toBeInstanceOf(FragnoInstantiatedFragment);
1555
+ // Services should be empty objects in dry run
1556
+ expect(fragment.services).toBeDefined();
1557
+ });
1558
+
1559
+ it("should handle named service errors in dry run mode", () => {
1560
+ interface Config {
1561
+ apiKey: string;
1562
+ }
1563
+
1564
+ const definition = defineFragment<Config>("test-fragment")
1565
+ .withDependencies(({ config }) => {
1566
+ if (!config.apiKey) {
1567
+ throw new Error("Missing API key");
1568
+ }
1569
+ return { key: config.apiKey };
1570
+ })
1571
+ .providesService("apiService", ({ deps }) => {
1572
+ if (!deps.key) {
1573
+ throw new Error("Cannot create service without key");
1574
+ }
1575
+ return {
1576
+ call: () => `Calling with ${deps.key}`,
1577
+ };
1578
+ })
1579
+ .build();
1580
+
1581
+ const fragment = instantiateFragment(definition, {} as Config, [], {}, undefined, {
1582
+ dryRun: true,
1583
+ });
1584
+
1585
+ expect(fragment).toBeInstanceOf(FragnoInstantiatedFragment);
1586
+ expect(fragment.services.apiService).toBeDefined();
1587
+ expect(fragment.services.apiService).toEqual({});
1588
+ });
1589
+
1590
+ it("should handle private service errors in dry run mode", () => {
1591
+ interface Config {
1592
+ secret: string;
1593
+ }
1594
+
1595
+ const definition = defineFragment<Config>("test-fragment")
1596
+ .withDependencies(({ config }) => {
1597
+ if (!config.secret) {
1598
+ throw new Error("Missing secret");
1599
+ }
1600
+ return { secret: config.secret };
1601
+ })
1602
+ .build();
1603
+
1604
+ const fragment = instantiateFragment(definition, {} as Config, [], {}, undefined, {
1605
+ dryRun: true,
1606
+ });
1607
+
1608
+ expect(fragment).toBeInstanceOf(FragnoInstantiatedFragment);
1609
+ });
1610
+
1611
+ it("should not catch errors when dry run is disabled", () => {
1612
+ interface Config {
1613
+ key: string;
1614
+ }
1615
+
1616
+ const definition = defineFragment<Config>("test-fragment")
1617
+ .withDependencies(({ config }) => {
1618
+ if (!config.key) {
1619
+ throw new Error("Missing key");
1620
+ }
1621
+ return { key: config.key };
1622
+ })
1623
+ .build();
1624
+
1625
+ expect(() => {
1626
+ instantiateFragment(definition, {} as Config, [], {}, undefined, { dryRun: false });
1627
+ }).toThrow("Missing key");
1628
+ });
1629
+ });
1488
1630
  });