@cosmneo/onion-lasagna 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/chunk-36IO4BM7.js +113 -0
  2. package/dist/chunk-36IO4BM7.js.map +1 -0
  3. package/dist/chunk-4BVOLXDJ.js +54 -0
  4. package/dist/chunk-4BVOLXDJ.js.map +1 -0
  5. package/dist/{chunk-GGSAAZPM.js → chunk-AUMHMWDD.js} +19 -20
  6. package/dist/chunk-AUMHMWDD.js.map +1 -0
  7. package/dist/chunk-CBTICRSM.js +34 -0
  8. package/dist/chunk-CBTICRSM.js.map +1 -0
  9. package/dist/chunk-H5TNDC5U.js +138 -0
  10. package/dist/chunk-H5TNDC5U.js.map +1 -0
  11. package/dist/chunk-KJ4JGZOE.js +96 -0
  12. package/dist/chunk-KJ4JGZOE.js.map +1 -0
  13. package/dist/chunk-MF2JDREK.js +168 -0
  14. package/dist/chunk-MF2JDREK.js.map +1 -0
  15. package/dist/chunk-RVSBIYY4.js +1 -0
  16. package/dist/chunk-RVSBIYY4.js.map +1 -0
  17. package/dist/{chunk-PUVAB3JX.js → chunk-XIRJ73IO.js} +38 -36
  18. package/dist/chunk-XIRJ73IO.js.map +1 -0
  19. package/dist/{chunk-DS7TE6KZ.js → chunk-XP6PLTV2.js} +11 -3
  20. package/dist/chunk-XP6PLTV2.js.map +1 -0
  21. package/dist/chunk-XWKHOLIP.js +191 -0
  22. package/dist/chunk-XWKHOLIP.js.map +1 -0
  23. package/dist/event-router-definition.type-CP9uTlux.d.cts +150 -0
  24. package/dist/event-router-definition.type-D8CG-kjZ.d.ts +150 -0
  25. package/dist/events/asyncapi/index.cjs +143 -0
  26. package/dist/events/asyncapi/index.cjs.map +1 -0
  27. package/dist/events/asyncapi/index.d.cts +184 -0
  28. package/dist/events/asyncapi/index.d.ts +184 -0
  29. package/dist/events/asyncapi/index.js +8 -0
  30. package/dist/events/asyncapi/index.js.map +1 -0
  31. package/dist/events/handler/index.cjs +171 -0
  32. package/dist/events/handler/index.cjs.map +1 -0
  33. package/dist/events/handler/index.d.cts +153 -0
  34. package/dist/events/handler/index.d.ts +153 -0
  35. package/dist/events/handler/index.js +21 -0
  36. package/dist/events/handler/index.js.map +1 -0
  37. package/dist/events/index.cjs +497 -0
  38. package/dist/events/index.cjs.map +1 -0
  39. package/dist/events/index.d.cts +9 -0
  40. package/dist/events/index.d.ts +9 -0
  41. package/dist/events/index.js +41 -0
  42. package/dist/events/index.js.map +1 -0
  43. package/dist/events/server/index.cjs +291 -0
  44. package/dist/events/server/index.cjs.map +1 -0
  45. package/dist/events/server/index.d.cts +281 -0
  46. package/dist/events/server/index.d.ts +281 -0
  47. package/dist/events/server/index.js +16 -0
  48. package/dist/events/server/index.js.map +1 -0
  49. package/dist/events/shared/index.cjs +85 -0
  50. package/dist/events/shared/index.cjs.map +1 -0
  51. package/dist/events/shared/index.d.cts +35 -0
  52. package/dist/events/shared/index.d.ts +35 -0
  53. package/dist/events/shared/index.js +13 -0
  54. package/dist/events/shared/index.js.map +1 -0
  55. package/dist/global.js +3 -3
  56. package/dist/http/index.cjs +563 -93
  57. package/dist/http/index.cjs.map +1 -1
  58. package/dist/http/index.d.cts +5 -3
  59. package/dist/http/index.d.ts +5 -3
  60. package/dist/http/index.js +30 -12
  61. package/dist/http/openapi/index.cjs +43 -35
  62. package/dist/http/openapi/index.cjs.map +1 -1
  63. package/dist/http/openapi/index.d.cts +8 -34
  64. package/dist/http/openapi/index.d.ts +8 -34
  65. package/dist/http/openapi/index.js +2 -2
  66. package/dist/http/route/index.cjs +106 -9
  67. package/dist/http/route/index.cjs.map +1 -1
  68. package/dist/http/route/index.d.cts +133 -227
  69. package/dist/http/route/index.d.ts +133 -227
  70. package/dist/http/route/index.js +5 -2
  71. package/dist/http/server/index.cjs +24 -19
  72. package/dist/http/server/index.cjs.map +1 -1
  73. package/dist/http/server/index.d.cts +4 -261
  74. package/dist/http/server/index.d.ts +4 -261
  75. package/dist/http/server/index.js +2 -2
  76. package/dist/http/shared/index.cjs.map +1 -1
  77. package/dist/http/shared/index.d.cts +10 -14
  78. package/dist/http/shared/index.d.ts +10 -14
  79. package/dist/http/shared/index.js +11 -127
  80. package/dist/http/shared/index.js.map +1 -1
  81. package/dist/index.js +6 -6
  82. package/dist/{router-definition.type-ynBhT16T.d.cts → router-definition.type-BElX-Pl4.d.cts} +169 -256
  83. package/dist/{router-definition.type-DORVlLNk.d.ts → router-definition.type-DxG8ncJZ.d.ts} +169 -256
  84. package/dist/types-B6Q1iCgf.d.ts +262 -0
  85. package/dist/types-afYpL7Ap.d.cts +262 -0
  86. package/dist/types-cke61juH.d.cts +42 -0
  87. package/dist/types-cke61juH.d.ts +42 -0
  88. package/package.json +35 -2
  89. package/dist/chunk-BZULBF4N.js +0 -82
  90. package/dist/chunk-BZULBF4N.js.map +0 -1
  91. package/dist/chunk-DS7TE6KZ.js.map +0 -1
  92. package/dist/chunk-GGSAAZPM.js.map +0 -1
  93. package/dist/chunk-PUVAB3JX.js.map +0 -1
@@ -1,82 +0,0 @@
1
- import {
2
- isRouteDefinition,
3
- isRouterDefinition
4
- } from "./chunk-DS7TE6KZ.js";
5
-
6
- // src/presentation/http/route/define-route.ts
7
- function defineRoute(input) {
8
- const definition = {
9
- method: input.method,
10
- path: input.path,
11
- request: {
12
- body: input.request?.body ?? void 0,
13
- query: input.request?.query ?? void 0,
14
- params: input.request?.params ?? void 0,
15
- headers: input.request?.headers ?? void 0,
16
- context: input.request?.context ?? void 0
17
- },
18
- responses: input.responses,
19
- docs: {
20
- summary: input.docs?.summary,
21
- description: input.docs?.description,
22
- tags: input.docs?.tags,
23
- operationId: input.docs?.operationId,
24
- deprecated: input.docs?.deprecated ?? false,
25
- security: input.docs?.security,
26
- externalDocs: input.docs?.externalDocs
27
- },
28
- _types: void 0
29
- };
30
- return Object.freeze(definition);
31
- }
32
-
33
- // src/presentation/http/route/define-router.ts
34
- function defineRouter(routes, options) {
35
- const definition = {
36
- routes,
37
- basePath: options?.basePath,
38
- tags: options?.tags,
39
- _isRouter: true
40
- };
41
- return deepFreeze(definition);
42
- }
43
- function deepFreeze(obj) {
44
- const propNames = Object.getOwnPropertyNames(obj);
45
- for (const name of propNames) {
46
- const value = obj[name];
47
- if (value && typeof value === "object" && !Object.isFrozen(value)) {
48
- deepFreeze(value);
49
- }
50
- }
51
- return Object.freeze(obj);
52
- }
53
- function extractRoutes(input) {
54
- return isRouterDefinition(input) ? input.routes : input;
55
- }
56
- function isSubRouter(value) {
57
- return typeof value === "object" && value !== null && !isRouteDefinition(value) && !isRouterDefinition(value);
58
- }
59
- function deepMergeConfigs(a, b) {
60
- const result = { ...a };
61
- for (const key of Object.keys(b)) {
62
- const aVal = result[key];
63
- const bVal = b[key];
64
- if (isSubRouter(aVal) && isSubRouter(bVal)) {
65
- result[key] = deepMergeConfigs(aVal, bVal);
66
- } else {
67
- result[key] = bVal;
68
- }
69
- }
70
- return result;
71
- }
72
- function mergeRouters(...routers) {
73
- const merged = routers.map(extractRoutes).reduce(deepMergeConfigs);
74
- return defineRouter(merged);
75
- }
76
-
77
- export {
78
- defineRoute,
79
- defineRouter,
80
- mergeRouters
81
- };
82
- //# sourceMappingURL=chunk-BZULBF4N.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/presentation/http/route/define-route.ts","../src/presentation/http/route/define-router.ts"],"sourcesContent":["/**\n * @fileoverview Factory function for creating route definitions.\n *\n * The `defineRoute` function is the main entry point for defining routes\n * in the unified system. It provides type inference and validation\n * for route configurations.\n *\n * @module unified/route/define-route\n */\n\nimport type { SchemaAdapter, InferOutput } from '../schema/types';\nimport type { HttpMethod, ResponsesConfig, RouteDefinition, PathParams } from './types';\n\n// ============================================================================\n// Input Types\n// ============================================================================\n\n/**\n * Request body configuration input.\n */\ninterface BodyInput<TSchema extends SchemaAdapter> {\n readonly schema: TSchema;\n readonly contentType?: string;\n readonly required?: boolean;\n readonly description?: string;\n}\n\n/**\n * Query parameters configuration input.\n */\ninterface QueryInput<TSchema extends SchemaAdapter> {\n readonly schema: TSchema;\n readonly description?: string;\n}\n\n/**\n * Path parameters configuration input.\n */\ninterface ParamsInput<TSchema extends SchemaAdapter> {\n readonly schema: TSchema;\n readonly description?: string;\n}\n\n/**\n * Headers configuration input.\n */\ninterface HeadersInput<TSchema extends SchemaAdapter> {\n readonly schema: TSchema;\n readonly description?: string;\n}\n\n/**\n * Context configuration input.\n * Used to validate and type context data from middleware (e.g., JWT payload).\n */\ninterface ContextInput<TSchema extends SchemaAdapter> {\n readonly schema: TSchema;\n readonly description?: string;\n}\n\n/**\n * Response configuration input.\n */\ninterface ResponseInput<TSchema extends SchemaAdapter | undefined = undefined> {\n readonly description: string;\n readonly schema?: TSchema;\n readonly contentType?: string;\n}\n\n/**\n * Complete input for defineRoute.\n */\ninterface DefineRouteInput<\n TMethod extends HttpMethod,\n TPath extends string,\n TBody extends SchemaAdapter | undefined = undefined,\n TQuery extends SchemaAdapter | undefined = undefined,\n TParams extends SchemaAdapter | undefined = undefined,\n THeaders extends SchemaAdapter | undefined = undefined,\n TContext extends SchemaAdapter | undefined = undefined,\n TResponses extends Record<number, ResponseInput<SchemaAdapter | undefined>> = Record<\n number,\n never\n >,\n> {\n readonly method: TMethod;\n readonly path: TPath;\n readonly request?: {\n readonly body?: TBody extends SchemaAdapter ? BodyInput<TBody> : undefined;\n readonly query?: TQuery extends SchemaAdapter ? QueryInput<TQuery> : undefined;\n readonly params?: TParams extends SchemaAdapter ? ParamsInput<TParams> : undefined;\n readonly headers?: THeaders extends SchemaAdapter ? HeadersInput<THeaders> : undefined;\n readonly context?: TContext extends SchemaAdapter ? ContextInput<TContext> : undefined;\n };\n readonly responses: TResponses;\n readonly docs?: {\n readonly summary?: string;\n readonly description?: string;\n readonly tags?: readonly string[];\n readonly operationId?: string;\n readonly deprecated?: boolean;\n readonly security?: readonly Record<string, readonly string[]>[];\n readonly externalDocs?: {\n readonly url: string;\n readonly description?: string;\n };\n };\n}\n\n// ============================================================================\n// Output Types\n// ============================================================================\n\n/**\n * Converts response inputs to response config type.\n */\ntype ToResponsesConfig<T extends Record<number, ResponseInput<SchemaAdapter | undefined>>> = {\n [K in keyof T]: T[K] extends ResponseInput<infer TSchema>\n ? {\n description: string;\n schema: TSchema extends SchemaAdapter ? TSchema : undefined;\n contentType?: string;\n }\n : never;\n};\n\n// ============================================================================\n// Factory Function\n// ============================================================================\n\n/**\n * Creates a route definition from the provided configuration.\n *\n * This is the main entry point for defining routes in the unified system.\n * The resulting definition can be used for:\n * - Type-safe client generation\n * - Server-side route registration\n * - OpenAPI specification generation\n *\n * @param input - Route configuration\n * @returns A frozen RouteDefinition object with full type information\n *\n * @example Basic GET route\n * ```typescript\n * import { defineRoute } from '@cosmneo/onion-lasagna/http';\n * import { zodSchema, z } from '@cosmneo/onion-lasagna/http/schema/zod';\n *\n * const listUsers = defineRoute({\n * method: 'GET',\n * path: '/api/users',\n * request: {\n * query: {\n * schema: zodSchema(z.object({\n * page: z.coerce.number().optional().default(1),\n * limit: z.coerce.number().optional().default(20),\n * })),\n * },\n * },\n * responses: {\n * 200: {\n * description: 'List of users',\n * schema: zodSchema(z.object({\n * users: z.array(z.object({\n * id: z.string(),\n * name: z.string(),\n * })),\n * total: z.number(),\n * })),\n * },\n * },\n * docs: {\n * summary: 'List all users',\n * tags: ['Users'],\n * },\n * });\n * ```\n *\n * @example POST route with path parameters\n * ```typescript\n * const createTask = defineRoute({\n * method: 'POST',\n * path: '/api/projects/:projectId/tasks',\n * request: {\n * body: {\n * schema: zodSchema(z.object({\n * title: z.string().min(1).max(200),\n * description: z.string().optional(),\n * })),\n * },\n * },\n * responses: {\n * 201: {\n * description: 'Task created',\n * schema: zodSchema(z.object({\n * id: z.string().uuid(),\n * title: z.string(),\n * projectId: z.string(),\n * createdAt: z.string().datetime(),\n * })),\n * },\n * 400: {\n * description: 'Invalid request',\n * },\n * 404: {\n * description: 'Project not found',\n * },\n * },\n * docs: {\n * summary: 'Create a new task',\n * tags: ['Tasks'],\n * operationId: 'createTask',\n * },\n * });\n * ```\n */\nexport function defineRoute<\n TMethod extends HttpMethod,\n TPath extends string,\n TBody extends SchemaAdapter | undefined = undefined,\n TQuery extends SchemaAdapter | undefined = undefined,\n TParams extends SchemaAdapter | undefined = undefined,\n THeaders extends SchemaAdapter | undefined = undefined,\n TContext extends SchemaAdapter | undefined = undefined,\n TResponses extends Record<number, ResponseInput<SchemaAdapter | undefined>> = Record<\n number,\n never\n >,\n>(\n input: DefineRouteInput<TMethod, TPath, TBody, TQuery, TParams, THeaders, TContext, TResponses>,\n): RouteDefinition<\n TMethod,\n TPath,\n TBody extends SchemaAdapter ? InferOutput<TBody> : undefined,\n TQuery extends SchemaAdapter ? InferOutput<TQuery> : undefined,\n TParams extends SchemaAdapter ? InferOutput<TParams> : PathParams<TPath>,\n THeaders extends SchemaAdapter ? InferOutput<THeaders> : undefined,\n TContext extends SchemaAdapter ? InferOutput<TContext> : undefined,\n ToResponsesConfig<TResponses> & ResponsesConfig\n> {\n const definition = {\n method: input.method,\n path: input.path,\n request: {\n body: input.request?.body ?? undefined,\n query: input.request?.query ?? undefined,\n params: input.request?.params ?? undefined,\n headers: input.request?.headers ?? undefined,\n context: input.request?.context ?? undefined,\n },\n responses: input.responses as ToResponsesConfig<TResponses> & ResponsesConfig,\n docs: {\n summary: input.docs?.summary,\n description: input.docs?.description,\n tags: input.docs?.tags,\n operationId: input.docs?.operationId,\n deprecated: input.docs?.deprecated ?? false,\n security: input.docs?.security,\n externalDocs: input.docs?.externalDocs,\n },\n _types: undefined as unknown,\n } as RouteDefinition<\n TMethod,\n TPath,\n TBody extends SchemaAdapter ? InferOutput<TBody> : undefined,\n TQuery extends SchemaAdapter ? InferOutput<TQuery> : undefined,\n TParams extends SchemaAdapter ? InferOutput<TParams> : PathParams<TPath>,\n THeaders extends SchemaAdapter ? InferOutput<THeaders> : undefined,\n TContext extends SchemaAdapter ? InferOutput<TContext> : undefined,\n ToResponsesConfig<TResponses> & ResponsesConfig\n >;\n\n // Freeze the definition to prevent accidental mutation\n return Object.freeze(definition);\n}\n","/**\n * @fileoverview Factory function for creating router definitions.\n *\n * The `defineRouter` function groups routes into a hierarchical structure\n * that enables organized API clients, OpenAPI tag grouping, and structured\n * server route registration.\n *\n * @module unified/route/define-router\n */\n\nimport type { RouterConfig, RouterDefinition, DeepMergeTwo, DeepMergeAll } from './types';\nimport { isRouteDefinition, isRouterDefinition } from './types';\n\n/**\n * Options for router definition.\n */\nexport interface DefineRouterOptions {\n /**\n * Base path prefix for all routes in this router.\n * Will be prepended to all route paths.\n *\n * @example\n * ```typescript\n * defineRouter({ ... }, { basePath: '/api/v1' })\n * ```\n */\n readonly basePath?: string;\n\n /**\n * Default tags for all routes in this router.\n * Will be merged with route-specific tags.\n */\n readonly tags?: readonly string[];\n}\n\n/**\n * Creates a router definition from a configuration object.\n *\n * A router is a hierarchical grouping of routes that provides:\n * - Organized API structure with nested namespaces\n * - Typed client method generation\n * - OpenAPI tag grouping\n * - Server route registration\n *\n * @param routes - Object containing routes and nested routers\n * @param options - Optional router configuration\n * @returns A frozen RouterDefinition object\n *\n * @example Basic router\n * ```typescript\n * import { defineRouter } from '@cosmneo/onion-lasagna/http';\n *\n * const api = defineRouter({\n * users: {\n * list: listUsersRoute,\n * get: getUserRoute,\n * create: createUserRoute,\n * update: updateUserRoute,\n * delete: deleteUserRoute,\n * },\n * posts: {\n * list: listPostsRoute,\n * get: getPostRoute,\n * create: createPostRoute,\n * },\n * });\n *\n * // Client usage:\n * // client.users.list({ query: { page: 1 } })\n * // client.users.get({ params: { id: '123' } })\n * // client.posts.create({ body: { title: 'Hello' } })\n * ```\n *\n * @example Nested routers\n * ```typescript\n * const projectRouter = defineRouter({\n * list: listProjectsRoute,\n * get: getProjectRoute,\n * tasks: {\n * list: listTasksRoute,\n * create: createTaskRoute,\n * update: updateTaskRoute,\n * },\n * members: {\n * list: listMembersRoute,\n * add: addMemberRoute,\n * remove: removeMemberRoute,\n * },\n * });\n *\n * const api = defineRouter({\n * projects: projectRouter.routes,\n * users: userRouter.routes,\n * });\n *\n * // Client usage:\n * // client.projects.tasks.create({ params: { projectId: '123' }, body: { ... } })\n * ```\n *\n * @example With base path and tags\n * ```typescript\n * const adminApi = defineRouter({\n * users: {\n * list: listUsersRoute,\n * ban: banUserRoute,\n * },\n * analytics: {\n * dashboard: getDashboardRoute,\n * reports: getReportsRoute,\n * },\n * }, {\n * basePath: '/admin',\n * tags: ['Admin'],\n * });\n * ```\n */\nexport function defineRouter<T extends RouterConfig>(\n routes: T,\n options?: DefineRouterOptions,\n): RouterDefinition<T> {\n const definition: RouterDefinition<T> = {\n routes,\n basePath: options?.basePath,\n tags: options?.tags,\n _isRouter: true,\n };\n\n // Deep freeze the router definition\n return deepFreeze(definition);\n}\n\n/**\n * Deep freezes an object and all its nested objects.\n */\nfunction deepFreeze<T extends object>(obj: T): T {\n // Get all property names\n const propNames = Object.getOwnPropertyNames(obj) as (keyof T)[];\n\n // Freeze properties before freezing self\n for (const name of propNames) {\n const value = obj[name];\n if (value && typeof value === 'object' && !Object.isFrozen(value)) {\n deepFreeze(value);\n }\n }\n\n return Object.freeze(obj);\n}\n\n// ============================================================================\n// mergeRouters — variadic deep merge\n// ============================================================================\n\ntype RouterInput<T extends RouterConfig> = T | RouterDefinition<T>;\n\n/** Extracts the raw RouterConfig from either a plain config or a RouterDefinition. */\nfunction extractRoutes<T extends RouterConfig>(input: RouterInput<T>): T {\n return isRouterDefinition(input) ? input.routes : input;\n}\n\n/** Returns true if `value` is a plain sub-router object (not a RouteDefinition, not a RouterDefinition). */\nfunction isSubRouter(value: unknown): value is RouterConfig {\n return (\n typeof value === 'object' &&\n value !== null &&\n !isRouteDefinition(value) &&\n !isRouterDefinition(value)\n );\n}\n\n/** Recursively deep-merges two router configs. Sub-routers are merged; leaves are overwritten. */\nfunction deepMergeConfigs(a: RouterConfig, b: RouterConfig): RouterConfig {\n const result: Record<string, unknown> = { ...a };\n\n for (const key of Object.keys(b)) {\n const aVal = result[key];\n const bVal = b[key];\n\n if (isSubRouter(aVal) && isSubRouter(bVal)) {\n result[key] = deepMergeConfigs(aVal, bVal);\n } else {\n result[key] = bVal;\n }\n }\n\n return result as RouterConfig;\n}\n\n// Overloads for 2–8 routers (clean IDE experience)\n\n/**\n * Merges multiple routers into a single router with deep merge.\n *\n * Overlapping sub-router keys are recursively merged instead of overwritten.\n * Leaf routes (RouteDefinition) use last-one-wins semantics.\n *\n * @example\n * ```typescript\n * const api = mergeRouters(\n * userRouter,\n * organizationRouter,\n * feedbackRouter,\n * );\n * // If all three define `users`, their sub-routes are deep-merged.\n * ```\n */\nexport function mergeRouters<T1 extends RouterConfig, T2 extends RouterConfig>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n): RouterDefinition<DeepMergeTwo<T1, T2>>;\nexport function mergeRouters<\n T1 extends RouterConfig,\n T2 extends RouterConfig,\n T3 extends RouterConfig,\n>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n r3: RouterInput<T3>,\n): RouterDefinition<DeepMergeAll<[T1, T2, T3]>>;\nexport function mergeRouters<\n T1 extends RouterConfig,\n T2 extends RouterConfig,\n T3 extends RouterConfig,\n T4 extends RouterConfig,\n>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n r3: RouterInput<T3>,\n r4: RouterInput<T4>,\n): RouterDefinition<DeepMergeAll<[T1, T2, T3, T4]>>;\nexport function mergeRouters<\n T1 extends RouterConfig,\n T2 extends RouterConfig,\n T3 extends RouterConfig,\n T4 extends RouterConfig,\n T5 extends RouterConfig,\n>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n r3: RouterInput<T3>,\n r4: RouterInput<T4>,\n r5: RouterInput<T5>,\n): RouterDefinition<DeepMergeAll<[T1, T2, T3, T4, T5]>>;\nexport function mergeRouters<\n T1 extends RouterConfig,\n T2 extends RouterConfig,\n T3 extends RouterConfig,\n T4 extends RouterConfig,\n T5 extends RouterConfig,\n T6 extends RouterConfig,\n>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n r3: RouterInput<T3>,\n r4: RouterInput<T4>,\n r5: RouterInput<T5>,\n r6: RouterInput<T6>,\n): RouterDefinition<DeepMergeAll<[T1, T2, T3, T4, T5, T6]>>;\nexport function mergeRouters<\n T1 extends RouterConfig,\n T2 extends RouterConfig,\n T3 extends RouterConfig,\n T4 extends RouterConfig,\n T5 extends RouterConfig,\n T6 extends RouterConfig,\n T7 extends RouterConfig,\n>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n r3: RouterInput<T3>,\n r4: RouterInput<T4>,\n r5: RouterInput<T5>,\n r6: RouterInput<T6>,\n r7: RouterInput<T7>,\n): RouterDefinition<DeepMergeAll<[T1, T2, T3, T4, T5, T6, T7]>>;\nexport function mergeRouters<\n T1 extends RouterConfig,\n T2 extends RouterConfig,\n T3 extends RouterConfig,\n T4 extends RouterConfig,\n T5 extends RouterConfig,\n T6 extends RouterConfig,\n T7 extends RouterConfig,\n T8 extends RouterConfig,\n>(\n r1: RouterInput<T1>,\n r2: RouterInput<T2>,\n r3: RouterInput<T3>,\n r4: RouterInput<T4>,\n r5: RouterInput<T5>,\n r6: RouterInput<T6>,\n r7: RouterInput<T7>,\n r8: RouterInput<T8>,\n): RouterDefinition<DeepMergeAll<[T1, T2, T3, T4, T5, T6, T7, T8]>>;\n\n// Variadic fallback for 9+\nexport function mergeRouters(\n ...routers: RouterInput<RouterConfig>[]\n): RouterDefinition<RouterConfig>;\n\n// Implementation\nexport function mergeRouters(\n ...routers: RouterInput<RouterConfig>[]\n): RouterDefinition<RouterConfig> {\n const merged = routers.map(extractRoutes).reduce(deepMergeConfigs);\n return defineRouter(merged);\n}\n"],"mappings":";;;;;;AAuNO,SAAS,YAad,OAUA;AACA,QAAM,aAAa;AAAA,IACjB,QAAQ,MAAM;AAAA,IACd,MAAM,MAAM;AAAA,IACZ,SAAS;AAAA,MACP,MAAM,MAAM,SAAS,QAAQ;AAAA,MA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AAG;AAChC,UAAM,OAAO,OAAO,GAAG;AACvB,UAAM,OAAO,EAAE,GAAG;AAElB,QAAI,YAAY,IAAI,KAAK,YAAY,IAAI,GAAG;AAC1C,aAAO,GAAG,IAAI,iBAAiB,MAAM,IAAI;AAAA,IAC3C,OAAO;AACL,aAAO,GAAG,IAAI;AAAA,IAChB;AAAA,EACF;AAEA,SAAO;AACT;AAmHO,SAAS,gBACX,SAC6B;AAChC,QAAM,SAAS,QAAQ,IAAI,aAAa,EAAE,OAAO,gBAAgB;AACjE,SAAO,aAAa,MAAM;AAC5B;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/presentation/http/route/types/path-params.type.ts","../src/presentation/http/route/types/router-definition.type.ts"],"sourcesContent":["/**\n * @fileoverview Path parameter extraction types.\n *\n * These types enable TypeScript to extract path parameter names from\n * URL path templates at compile time, providing full type safety for\n * path parameters in routes.\n *\n * @module unified/route/types/path-params\n */\n\n/**\n * Extracts parameter names from a path template string.\n *\n * Supports both `:param` and `{param}` syntaxes for maximum compatibility\n * with different routing conventions.\n *\n * @example Colon syntax (Express-style)\n * ```typescript\n * type Params = ExtractPathParamNames<'/users/:userId/posts/:postId'>;\n * // 'userId' | 'postId'\n * ```\n *\n * @example Brace syntax (OpenAPI-style)\n * ```typescript\n * type Params = ExtractPathParamNames<'/users/{userId}/posts/{postId}'>;\n * // 'userId' | 'postId'\n * ```\n *\n * @example No parameters\n * ```typescript\n * type Params = ExtractPathParamNames<'/users'>;\n * // never\n * ```\n */\nexport type ExtractPathParamNames<T extends string> =\n // Match :param followed by more path\n T extends `${string}:${infer Param}/${infer Rest}`\n ? Param | ExtractPathParamNames<`/${Rest}`>\n : // Match :param at end\n T extends `${string}:${infer Param}`\n ? Param\n : // Match {param} followed by more path\n T extends `${string}{${infer Param}}/${infer Rest}`\n ? Param | ExtractPathParamNames<`/${Rest}`>\n : // Match {param} at end\n T extends `${string}{${infer Param}}`\n ? Param\n : never;\n\n/**\n * Creates an object type with all path parameters as string properties.\n *\n * @example\n * ```typescript\n * type Params = PathParams<'/projects/:projectId/tasks/:taskId'>;\n * // { projectId: string; taskId: string }\n *\n * type NoParams = PathParams<'/projects'>;\n * // Record<string, never> (empty object type)\n * ```\n */\nexport type PathParams<T extends string> =\n ExtractPathParamNames<T> extends never\n ? Record<string, never>\n : Record<ExtractPathParamNames<T>, string>;\n\n/**\n * Checks if a path has any parameters.\n *\n * @example\n * ```typescript\n * type HasParams = HasPathParams<'/users/:id'>; // true\n * type NoParams = HasPathParams<'/users'>; // false\n * ```\n */\nexport type HasPathParams<T extends string> = ExtractPathParamNames<T> extends never ? false : true;\n\n/**\n * Converts a path template with parameters to a regex pattern.\n * This is used internally for route matching.\n *\n * @example\n * ```typescript\n * pathToRegex('/users/:id/posts/:postId')\n * // /^\\/users\\/([^\\/]+)\\/posts\\/([^\\/]+)\\/?$/\n * ```\n */\nexport function pathToRegex(path: string): RegExp {\n const pattern = path\n // Escape special regex characters except : and {}\n .replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n // Replace :param with capture group\n .replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, '([^/]+)')\n // Replace {param} with capture group\n .replace(/\\\\\\{([a-zA-Z_][a-zA-Z0-9_]*)\\\\\\}/g, '([^/]+)');\n\n return new RegExp(`^${pattern}/?$`);\n}\n\n/**\n * Extracts parameter names from a path string at runtime.\n *\n * @example\n * ```typescript\n * getPathParamNames('/users/:userId/posts/:postId')\n * // ['userId', 'postId']\n * ```\n */\nexport function getPathParamNames(path: string): string[] {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- regex capture group always exists\n const colonParams = [...path.matchAll(/:([a-zA-Z_][a-zA-Z0-9_]*)/g)].map((m) => m[1]!);\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- regex capture group always exists\n const braceParams = [...path.matchAll(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g)].map((m) => m[1]!);\n return [...colonParams, ...braceParams];\n}\n\n/**\n * Checks if a path has any parameters at runtime.\n */\nexport function hasPathParams(path: string): boolean {\n return /:([a-zA-Z_][a-zA-Z0-9_]*)/.test(path) || /\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/.test(path);\n}\n\n/**\n * Replaces path parameters with actual values.\n *\n * @example\n * ```typescript\n * buildPath('/users/:userId/posts/:postId', { userId: '123', postId: '456' })\n * // '/users/123/posts/456'\n *\n * buildPath('/users/{userId}', { userId: '123' })\n * // '/users/123'\n * ```\n */\nexport function buildPath(template: string, params: Record<string, string>): string {\n let result = template;\n\n // Replace :param syntax\n for (const [key, value] of Object.entries(params)) {\n result = result.replace(`:${key}`, encodeURIComponent(value));\n result = result.replace(`{${key}}`, encodeURIComponent(value));\n }\n\n return result;\n}\n\n/**\n * Normalizes a path template to use consistent :param syntax.\n *\n * @example\n * ```typescript\n * normalizePath('/users/{userId}')\n * // '/users/:userId'\n * ```\n */\nexport function normalizePath(path: string): string {\n return path.replace(/\\{([a-zA-Z_][a-zA-Z0-9_]*)\\}/g, ':$1');\n}\n","/**\n * @fileoverview Router definition types for grouping routes.\n *\n * A router is a hierarchical grouping of routes that enables:\n * - Organized API structure\n * - Nested client method generation\n * - Grouped OpenAPI tags\n *\n * @module unified/route/types/router-definition\n */\n\nimport type { RouteDefinition, ResponsesConfig } from './route-definition.type';\nimport type { HttpMethod } from './http.type';\n\n// ============================================================================\n// Router Types\n// ============================================================================\n\n/**\n * A router entry can be either a route definition or a nested router.\n * Uses permissive types to allow any valid route definition.\n */\nexport type RouterEntry =\n | RouteDefinition<\n HttpMethod,\n string,\n unknown,\n unknown,\n unknown,\n unknown,\n unknown,\n ResponsesConfig\n >\n | RouterConfig;\n\n/**\n * Configuration for a router (group of routes).\n */\nexport interface RouterConfig {\n readonly [key: string]: RouterEntry;\n}\n\n/**\n * A fully defined router.\n */\nexport interface RouterDefinition<T extends RouterConfig = RouterConfig> {\n /**\n * The routes and nested routers in this router.\n */\n readonly routes: T;\n\n /**\n * Base path prefix for all routes in this router.\n */\n readonly basePath?: string;\n\n /**\n * Default tags for all routes in this router.\n */\n readonly tags?: readonly string[];\n\n /**\n * Marker to identify this as a router.\n * @internal\n */\n readonly _isRouter: true;\n}\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Checks if a value is a RouteDefinition.\n */\nexport function isRouteDefinition(value: unknown): value is RouteDefinition {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'method' in value &&\n 'path' in value &&\n 'responses' in value &&\n '_types' in value\n );\n}\n\n/**\n * Checks if a value is a RouterDefinition.\n */\nexport function isRouterDefinition(value: unknown): value is RouterDefinition {\n return (\n typeof value === 'object' &&\n value !== null &&\n '_isRouter' in value &&\n (value as RouterDefinition)._isRouter === true\n );\n}\n\n// ============================================================================\n// Utility Types\n// ============================================================================\n\n/**\n * Flattens a router into a map of path keys to route definitions.\n *\n * @example\n * ```typescript\n * const router = defineRouter({\n * users: {\n * list: listUsersRoute,\n * get: getUserRoute,\n * },\n * posts: {\n * create: createPostRoute,\n * },\n * });\n *\n * type Flat = FlattenRouter<typeof router>;\n * // {\n * // 'users.list': typeof listUsersRoute,\n * // 'users.get': typeof getUserRoute,\n * // 'posts.create': typeof createPostRoute,\n * // }\n * ```\n */\nexport type FlattenRouter<\n T extends RouterConfig,\n Prefix extends string = '',\n> = T extends RouterConfig\n ? {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof T]: T[K] extends RouteDefinition<any, any, any, any, any, any, any, any>\n ? { [P in `${Prefix}${K & string}`]: T[K] }\n : T[K] extends RouterConfig\n ? FlattenRouter<T[K], `${Prefix}${K & string}.`>\n : never;\n }[keyof T] extends infer U\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n U extends Record<string, RouteDefinition<any, any, any, any, any, any, any, any>>\n ? U\n : never\n : never\n : never;\n\n/**\n * Gets all route keys from a router.\n *\n * @example\n * ```typescript\n * type Keys = RouterKeys<typeof router>;\n * // 'users.list' | 'users.get' | 'posts.create'\n * ```\n */\nexport type RouterKeys<T extends RouterConfig, Prefix extends string = ''> = T extends RouterConfig\n ? {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof T]: T[K] extends RouteDefinition<any, any, any, any, any, any, any, any>\n ? `${Prefix}${K & string}`\n : T[K] extends RouterConfig\n ? RouterKeys<T[K], `${Prefix}${K & string}.`>\n : never;\n }[keyof T]\n : never;\n\n/**\n * Gets a route by its dotted key path.\n *\n * @example\n * ```typescript\n * type UserGet = GetRoute<typeof router, 'users.get'>;\n * // typeof getUserRoute\n * ```\n */\nexport type GetRoute<\n T extends RouterConfig,\n K extends string,\n> = K extends `${infer Head}.${infer Tail}`\n ? Head extends keyof T\n ? T[Head] extends RouterConfig\n ? GetRoute<T[Head], Tail>\n : never\n : never\n : K extends keyof T\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n T[K] extends RouteDefinition<any, any, any, any, any, any, any, any>\n ? T[K]\n : never\n : never;\n\n// ============================================================================\n// Deep Merge Types\n// ============================================================================\n\n/**\n * Deep-merges two router configs at the type level.\n *\n * - If both sides are sub-routers (extend RouterConfig), recurse.\n * - Otherwise last-one-wins (B overrides A).\n * - RouteDefinition does NOT extend RouterConfig (it has `method`, `path`, etc.)\n * so the conditional correctly distinguishes leaves from sub-routers.\n */\nexport type DeepMergeTwo<A extends RouterConfig, B extends RouterConfig> = {\n readonly [K in keyof A | keyof B]: K extends keyof A\n ? K extends keyof B\n ? A[K] extends RouterConfig\n ? B[K] extends RouterConfig\n ? DeepMergeTwo<A[K], B[K]>\n : B[K]\n : B[K]\n : A[K]\n : K extends keyof B\n ? B[K]\n : never;\n};\n\n/**\n * Recursively deep-merges N router configs left-to-right.\n */\nexport type DeepMergeAll<T extends readonly RouterConfig[]> = T extends readonly [\n infer Only extends RouterConfig,\n]\n ? Only\n : T extends readonly [\n infer First extends RouterConfig,\n infer Second extends RouterConfig,\n ...infer Rest extends readonly RouterConfig[],\n ]\n ? DeepMergeAll<[DeepMergeTwo<First, Second>, ...Rest]>\n : RouterConfig;\n\n/**\n * Recursively flattens complex types for clean IDE hover display.\n * Applied at return sites (not inside recursion) so DTS emit stays fast —\n * TypeScript only resolves when concrete types are provided.\n *\n * Works with any recursive object type: router configs, client types,\n * React Query hooks, etc. Functions and primitives pass through unchanged.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type PrettifyDeep<T> = T extends (...args: any[]) => any\n ? T\n : T extends object\n ? { readonly [K in keyof T]: PrettifyDeep<T[K]> }\n : T;\n\n/**\n * Collects all routes from a router into an array.\n */\nexport function collectRoutes(\n config: RouterConfig,\n basePath = '',\n): { key: string; route: RouteDefinition }[] {\n const routes: { key: string; route: RouteDefinition }[] = [];\n\n for (const [key, value] of Object.entries(config)) {\n const fullKey = basePath ? `${basePath}.${key}` : key;\n\n if (isRouteDefinition(value)) {\n routes.push({ key: fullKey, route: value });\n } else if (isRouterDefinition(value)) {\n routes.push(...collectRoutes(value.routes, fullKey));\n } else if (typeof value === 'object' && value !== null) {\n routes.push(...collectRoutes(value as RouterConfig, fullKey));\n }\n }\n\n return routes;\n}\n"],"mappings":";AAuFO,SAAS,YAAY,MAAsB;AAChD,QAAM,UAAU,KAEb,QAAQ,uBAAuB,MAAM,EAErC,QAAQ,8BAA8B,SAAS,EAE/C,QAAQ,qCAAqC,SAAS;AAEzD,SAAO,IAAI,OAAO,IAAI,OAAO,KAAK;AACpC;AAWO,SAAS,kBAAkB,MAAwB;AAExD,QAAM,cAAc,CAAC,GAAG,KAAK,SAAS,4BAA4B,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAE;AAErF,QAAM,cAAc,CAAC,GAAG,KAAK,SAAS,+BAA+B,CAAC,EAAE,IAAI,CAAC,MAAM,EAAE,CAAC,CAAE;AACxF,SAAO,CAAC,GAAG,aAAa,GAAG,WAAW;AACxC;AAKO,SAAS,cAAc,MAAuB;AACnD,SAAO,4BAA4B,KAAK,IAAI,KAAK,+BAA+B,KAAK,IAAI;AAC3F;AAcO,SAAS,UAAU,UAAkB,QAAwC;AAClF,MAAI,SAAS;AAGb,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,aAAS,OAAO,QAAQ,IAAI,GAAG,IAAI,mBAAmB,KAAK,CAAC;AAC5D,aAAS,OAAO,QAAQ,IAAI,GAAG,KAAK,mBAAmB,KAAK,CAAC;AAAA,EAC/D;AAEA,SAAO;AACT;AAWO,SAAS,cAAc,MAAsB;AAClD,SAAO,KAAK,QAAQ,iCAAiC,KAAK;AAC5D;;;ACnFO,SAAS,kBAAkB,OAA0C;AAC1E,SACE,OAAO,UAAU,YACjB,UAAU,QACV,YAAY,SACZ,UAAU,SACV,eAAe,SACf,YAAY;AAEhB;AAKO,SAAS,mBAAmB,OAA2C;AAC5E,SACE,OAAO,UAAU,YACjB,UAAU,QACV,eAAe,SACd,MAA2B,cAAc;AAE9C;AAwJO,SAAS,cACd,QACA,WAAW,IACgC;AAC3C,QAAM,SAAoD,CAAC;AAE3D,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,GAAG;AACjD,UAAM,UAAU,WAAW,GAAG,QAAQ,IAAI,GAAG,KAAK;AAElD,QAAI,kBAAkB,KAAK,GAAG;AAC5B,aAAO,KAAK,EAAE,KAAK,SAAS,OAAO,MAAM,CAAC;AAAA,IAC5C,WAAW,mBAAmB,KAAK,GAAG;AACpC,aAAO,KAAK,GAAG,cAAc,MAAM,QAAQ,OAAO,CAAC;AAAA,IACrD,WAAW,OAAO,UAAU,YAAY,UAAU,MAAM;AACtD,aAAO,KAAK,GAAG,cAAc,OAAuB,OAAO,CAAC;AAAA,IAC9D;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/presentation/http/server/types.ts","../src/presentation/http/server/create-server-routes.ts","../src/presentation/http/server/server-routes-builder.ts"],"sourcesContent":["/**\n * @fileoverview Server types for the unified route system.\n *\n * @module unified/server/types\n */\n\nimport type {\n HttpMethod,\n RouteDefinition,\n RouterConfig,\n RouterKeys,\n GetRoute,\n} from '../route/types';\n\n// ============================================================================\n// Validated Request\n// ============================================================================\n\n/**\n * A validated request with typed data.\n * This is what handlers receive after validation passes.\n */\nexport interface ValidatedRequest<TRoute extends RouteDefinition> {\n /**\n * Validated request body.\n */\n readonly body: TRoute['_types']['body'];\n\n /**\n * Validated query parameters.\n */\n readonly query: TRoute['_types']['query'];\n\n /**\n * Validated path parameters.\n */\n readonly pathParams: TRoute['_types']['pathParams'];\n\n /**\n * Validated headers.\n */\n readonly headers: TRoute['_types']['headers'];\n\n /**\n * Raw request object for advanced use cases.\n */\n readonly raw: {\n readonly method: string;\n readonly url: string;\n readonly headers: Record<string, string>;\n };\n}\n\n/**\n * Typed context based on route definition.\n * If the route defines a context schema, this will be the validated type.\n * Otherwise, it falls back to the generic HandlerContext.\n */\nexport type TypedContext<TRoute extends RouteDefinition> =\n TRoute['_types']['context'] extends undefined ? HandlerContext : TRoute['_types']['context'];\n\n// ============================================================================\n// Handler Types\n// ============================================================================\n\n/**\n * Context passed to handlers.\n * Can be extended with custom context via serverRoutes options.\n */\nexport interface HandlerContext {\n /**\n * Request ID for tracing.\n */\n readonly requestId?: string;\n\n /**\n * Additional context data.\n */\n readonly [key: string]: unknown;\n}\n\n/**\n * Response from a handler.\n */\nexport interface HandlerResponse<TData = unknown> {\n /**\n * HTTP status code.\n */\n readonly status: number;\n\n /**\n * Response body.\n */\n readonly body?: TData;\n\n /**\n * Response headers.\n */\n readonly headers?: Record<string, string>;\n}\n\n// ============================================================================\n// Use Case Port\n// ============================================================================\n\n/**\n * Use case port interface for unified routes.\n *\n * This is a simplified version that accepts any input/output types (plain objects).\n * It's structurally compatible with `BaseInboundPort`, so existing use case\n * implementations work without changes.\n *\n * @typeParam TInput - Input type (plain object or void for no input)\n * @typeParam TOutput - Output type (plain object or void for no output)\n *\n * @example\n * ```typescript\n * // Define plain types for use case contracts\n * type CreateProjectInput = {\n * name: string;\n * description?: string;\n * };\n *\n * type CreateProjectOutput = {\n * projectId: string;\n * };\n *\n * // Use case implements this interface\n * class CreateProjectUseCase implements UseCasePort<CreateProjectInput, CreateProjectOutput> {\n * async execute(input: CreateProjectInput): Promise<CreateProjectOutput> {\n * // ... implementation\n * return { projectId: '...' };\n * }\n * }\n * ```\n */\n\nexport interface UseCasePort<TInput = void, TOutput = void> {\n execute(input?: TInput): Promise<TOutput>;\n}\n\n// ============================================================================\n// Server Configuration\n// ============================================================================\n\n/**\n * Handler configuration for a single route.\n *\n * Mirrors the BaseController pattern with three components:\n * - `requestMapper`: Maps validated HTTP request to use case input\n * - `useCase`: The use case to execute\n * - `responseMapper`: Maps use case output to HTTP response\n *\n * @typeParam TRoute - The route definition type\n * @typeParam TInput - Use case input type (plain object)\n * @typeParam TOutput - Use case output type (plain object)\n *\n * @example\n * ```typescript\n * const config: RouteHandlerConfig<typeof createProjectRoute, CreateProjectInput, CreateProjectOutput> = {\n * requestMapper: (req) => ({\n * name: req.body.name,\n * description: req.body.description,\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (out) => ({\n * status: 201,\n * body: { projectId: out.projectId },\n * }),\n * };\n * ```\n */\n\nexport interface RouteHandlerConfig<TRoute extends RouteDefinition, TInput = void, TOutput = void> {\n /**\n * Maps the validated HTTP request to use case input.\n * The request has already been validated by the route's schemas.\n * Context is typed based on the route's context schema (if defined).\n */\n readonly requestMapper: (req: ValidatedRequest<TRoute>, ctx: TypedContext<TRoute>) => TInput;\n\n /**\n * The use case to execute.\n * Can be any object with an `execute` method matching `UseCasePort`.\n */\n readonly useCase: UseCasePort<TInput, TOutput>;\n\n /**\n * Maps the use case output to an HTTP response.\n * Determines the status code and response body.\n */\n readonly responseMapper: (output: TOutput) => HandlerResponse;\n\n /**\n * Middleware to run before the handler.\n */\n readonly middleware?: readonly MiddlewareFunction[];\n}\n\n/**\n * Middleware function type.\n */\nexport type MiddlewareFunction = (\n request: unknown,\n context: HandlerContext,\n next: () => Promise<HandlerResponse>,\n) => Promise<HandlerResponse>;\n\n// ============================================================================\n// Simple Handler Types\n// ============================================================================\n\n/**\n * Simple handler function that directly returns a response.\n * Use this for simple routes that don't need the use case pattern.\n */\nexport type SimpleHandlerFn<TRoute extends RouteDefinition> = (\n req: ValidatedRequest<TRoute>,\n ctx: TypedContext<TRoute>,\n) => Promise<HandlerResponse> | HandlerResponse;\n\n/**\n * Configuration for a simple handler (no use case).\n */\nexport interface SimpleHandlerConfig<TRoute extends RouteDefinition> {\n readonly handler: SimpleHandlerFn<TRoute>;\n readonly middleware?: readonly MiddlewareFunction[];\n}\n\n/**\n * Union of all handler config types.\n * Used internally to store handlers in the builder.\n */\nexport type AnyHandlerConfig<TRoute extends RouteDefinition, TInput = unknown, TOutput = unknown> =\n | RouteHandlerConfig<TRoute, TInput, TOutput>\n | SimpleHandlerConfig<TRoute>;\n\n/**\n * Type guard to check if config is a simple handler.\n */\nexport function isSimpleHandlerConfig(\n config: AnyHandlerConfig<RouteDefinition, unknown, unknown>,\n): config is SimpleHandlerConfig<RouteDefinition> {\n return 'handler' in config && typeof config.handler === 'function';\n}\n\n/**\n * Configuration mapping route keys to handlers.\n *\n * Each route key maps to a `RouteHandlerConfig` with:\n * - The route definition for that key (provides request/response types)\n * - User-defined input/output types for the use case\n *\n * The `TInput` and `TOutput` types are inferred from the `useCase` property,\n * so you don't need to specify them explicitly.\n */\n// TInput/TOutput are user-defined per route - any is required for heterogeneous route configs\nexport type ServerRoutesConfig<T extends RouterConfig> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in RouterKeys<T>]: RouteHandlerConfig<GetRoute<T, K>, any, any>;\n};\n\n/**\n * Options for creating server routes.\n */\nexport interface CreateServerRoutesOptions {\n /**\n * Global middleware to run before all handlers.\n */\n readonly middleware?: readonly MiddlewareFunction[];\n\n /**\n * Whether to validate incoming requests against route schemas.\n * When enabled, invalid requests throw InvalidRequestError.\n * @default true\n */\n readonly validateRequest?: boolean;\n\n /**\n * Whether to validate outgoing responses against route schemas.\n * When enabled, invalid responses throw ControllerError.\n * Useful for catching bugs and ensuring API contract compliance.\n * @default true\n */\n readonly validateResponse?: boolean;\n\n /**\n * Context factory to create handler context.\n */\n readonly createContext?: (rawRequest: unknown) => HandlerContext;\n\n /**\n * Allow partial handler configuration (not all routes need handlers).\n * When true, missing handlers are silently skipped.\n * When false (default), missing handlers throw an error.\n * @default false\n * @internal Used by builder pattern's buildPartial()\n */\n readonly allowPartial?: boolean;\n}\n\n// ============================================================================\n// Route Input (for framework adapters)\n// ============================================================================\n\n/**\n * Route input compatible with framework adapters.\n * This is the output of serverRoutes().build().\n */\nexport interface UnifiedRouteInput {\n /**\n * HTTP method.\n */\n readonly method: HttpMethod;\n\n /**\n * URL path pattern.\n */\n readonly path: string;\n\n /**\n * Handler function.\n */\n readonly handler: (\n rawRequest: RawHttpRequest,\n context?: HandlerContext,\n ) => Promise<HandlerResponse>;\n\n /**\n * Route metadata for documentation.\n */\n readonly metadata: {\n readonly operationId?: string;\n readonly summary?: string;\n readonly description?: string;\n readonly tags?: readonly string[];\n readonly deprecated?: boolean;\n };\n}\n\n/**\n * Raw HTTP request from the framework.\n */\nexport interface RawHttpRequest {\n readonly method: string;\n readonly url: string;\n readonly headers: Record<string, string | string[] | undefined>;\n readonly body?: unknown;\n readonly query?: Record<string, string | string[] | undefined>;\n readonly params?: Record<string, string>;\n}\n","/**\n * @fileoverview Internal implementation for creating server routes with auto-validation.\n *\n * Generates server-side route handlers from a router definition.\n * Each handler automatically validates incoming requests and outgoing\n * responses against the route's schemas.\n *\n * @module unified/server/create-server-routes\n * @internal\n */\n\nimport type { SchemaAdapter, ValidationIssue } from '../schema/types';\nimport type { RouterConfig, RouterDefinition, RouteDefinition } from '../route/types';\nimport { isRouterDefinition, collectRoutes, normalizePath } from '../route/types';\nimport type {\n AnyHandlerConfig,\n CreateServerRoutesOptions,\n HandlerContext,\n HandlerResponse,\n RawHttpRequest,\n UnifiedRouteInput,\n ValidatedRequest,\n} from './types';\nimport { isSimpleHandlerConfig } from './types';\nimport { InvalidRequestError } from '../../exceptions/invalid-request.error';\nimport { ControllerError } from '../../exceptions/controller.error';\nimport { UnauthorizedError } from '../../../app/exceptions/unauthorized.error';\nimport { wrapError } from '../../../global/utils/wrap-error.util';\n\n/**\n * Internal implementation for creating server routes.\n * Used by the builder pattern (serverRoutes).\n *\n * @internal\n */\nexport function createServerRoutesInternal<T extends RouterConfig>(\n router: T | RouterDefinition<T>,\n handlers: Record<string, AnyHandlerConfig<RouteDefinition, unknown, unknown>>,\n options?: CreateServerRoutesOptions,\n): UnifiedRouteInput[] {\n const routes = isRouterDefinition(router) ? router.routes : router;\n const collectedRoutes = collectRoutes(routes);\n\n // Sort routes by specificity: static segments before parameterized\n // This ensures /api/users/me is registered before /api/users/:userId\n const sortedRoutes = sortRoutesBySpecificity(collectedRoutes);\n\n const result: UnifiedRouteInput[] = [];\n\n // Default validation options to true, allowPartial to false\n const resolvedOptions: CreateServerRoutesOptions = {\n ...options,\n validateRequest: options?.validateRequest ?? true,\n validateResponse: options?.validateResponse ?? true,\n allowPartial: options?.allowPartial ?? false,\n };\n\n for (const { key, route } of sortedRoutes) {\n const handlerConfig = handlers[key] as AnyHandlerConfig<RouteDefinition, any, any> | undefined;\n\n if (!handlerConfig) {\n if (resolvedOptions.allowPartial) {\n // Skip routes without handlers when allowPartial is true\n continue;\n }\n throw new Error(\n `Missing handler for route \"${key}\". All routes must have a handler configuration.`,\n );\n }\n\n result.push(createRouteHandler(route, handlerConfig, resolvedOptions));\n }\n\n return result;\n}\n\n/**\n * Sorts routes by path specificity to ensure correct route matching.\n *\n * Static path segments are sorted before parameterized segments at each position.\n * This ensures that `/api/users/me` is registered before `/api/users/:userId`,\n * preventing the parameterized route from incorrectly matching the static path.\n *\n * @example\n * Given routes:\n * - /api/users/:userId (parameterized)\n * - /api/users/me (static)\n *\n * After sorting:\n * - /api/users/me (registered first - matches exactly)\n * - /api/users/:userId (registered second - catches remaining)\n */\nfunction sortRoutesBySpecificity<T extends { route: { path: string } }>(routes: T[]): T[] {\n return [...routes].sort((a, b) => {\n const aSegments = a.route.path.split('/').filter(Boolean);\n const bSegments = b.route.path.split('/').filter(Boolean);\n\n const maxLen = Math.max(aSegments.length, bSegments.length);\n\n for (let i = 0; i < maxLen; i++) {\n const aSeg = aSegments[i];\n const bSeg = bSegments[i];\n\n // Missing segment (shorter path) - shorter paths first for same prefix\n if (aSeg === undefined && bSeg !== undefined) return -1;\n if (aSeg !== undefined && bSeg === undefined) return 1;\n if (aSeg === undefined || bSeg === undefined) return 0;\n\n // Check if segment is parameterized (supports both :param and {param} formats)\n const aIsParam = aSeg.startsWith(':') || (aSeg.startsWith('{') && aSeg.endsWith('}'));\n const bIsParam = bSeg.startsWith(':') || (bSeg.startsWith('{') && bSeg.endsWith('}'));\n\n // Static segments come before parameterized segments\n if (!aIsParam && bIsParam) return -1;\n if (aIsParam && !bIsParam) return 1;\n\n // Both static or both parameterized - compare alphabetically for stable sorting\n const cmp = aSeg.localeCompare(bSeg);\n if (cmp !== 0) return cmp;\n }\n\n return 0;\n });\n}\n\n/**\n * Creates a single route handler with validation.\n *\n * Supports two handler patterns:\n * - Simple handler: handler(req, ctx) → response\n * - Use case pattern: requestMapper → useCase.execute → responseMapper\n */\nfunction createRouteHandler(\n route: RouteDefinition,\n // TInput/TOutput are user-defined and erased at this level - any is required for type compatibility\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n config: AnyHandlerConfig<RouteDefinition, any, any>,\n options: CreateServerRoutesOptions,\n): UnifiedRouteInput {\n const middleware = config.middleware ?? [];\n const globalMiddleware = options?.middleware ?? [];\n const allMiddleware = [...globalMiddleware, ...middleware];\n\n const shouldValidateRequest = options.validateRequest ?? true;\n const shouldValidateResponse = options.validateResponse ?? true;\n\n return {\n method: route.method,\n path: normalizePath(route.path),\n metadata: {\n operationId: route.docs.operationId,\n summary: route.docs.summary,\n description: route.docs.description,\n tags: route.docs.tags as string[],\n deprecated: route.docs.deprecated,\n },\n handler: async (rawRequest: RawHttpRequest, ctx?: HandlerContext): Promise<HandlerResponse> => {\n // Create context\n const rawContext: HandlerContext = options?.createContext\n ? options.createContext(rawRequest)\n : (ctx ?? { requestId: generateRequestId() });\n\n // Validate context (if schema defined)\n // Context validation failures are treated as authentication errors (401)\n // because context typically carries auth data (user, session, token).\n // A missing or invalid context means the caller is not properly authenticated.\n const validatedContext: unknown = route.request.context?.schema\n ? wrapError(\n () => {\n const result = validateContextData(route, rawContext);\n if (!result.success) {\n const errors = result.errors ?? [];\n throw new InvalidRequestError({\n message: 'Context validation failed',\n validationErrors: errors.map((e) => ({\n field: e.path.join('.'),\n message: e.message,\n })),\n });\n }\n return result.data;\n },\n () => new UnauthorizedError({ message: 'Authentication required' }),\n )\n : rawContext;\n\n // Validate request (if enabled)\n // Use internal type since specific route types are erased in this function\n let validatedRequest: ValidatedRequestInternal;\n\n if (shouldValidateRequest) {\n const validationResult = validateRequestData(route, rawRequest);\n\n if (!validationResult.success) {\n const errors = validationResult.errors ?? [];\n throw new InvalidRequestError({\n message: 'Request validation failed',\n validationErrors: errors.map((e) => ({\n field: e.path.join('.'),\n message: e.message,\n })),\n });\n }\n\n const data = validationResult.data ?? {};\n\n validatedRequest = {\n body: data.body,\n query: data.query,\n pathParams: data.pathParams,\n headers: data.headers,\n raw: {\n method: rawRequest.method,\n url: rawRequest.url,\n headers: normalizeHeaders(rawRequest.headers),\n },\n };\n } else {\n // Skip validation - pass through normalized data\n\n validatedRequest = {\n body: rawRequest.body,\n query: normalizeQuery(rawRequest.query),\n pathParams: normalizePathParams(rawRequest.params),\n headers: normalizeHeaders(rawRequest.headers),\n raw: {\n method: rawRequest.method,\n url: rawRequest.url,\n headers: normalizeHeaders(rawRequest.headers),\n },\n };\n }\n\n // Execute the pipeline based on handler type\n // Errors from the use case/handler propagate to the framework's error handler\n const executePipeline = async (): Promise<HandlerResponse> => {\n if (isSimpleHandlerConfig(config)) {\n // Simple handler: direct call\n return config.handler(\n validatedRequest as unknown as ValidatedRequest<RouteDefinition>,\n validatedContext as HandlerContext,\n );\n } else {\n // Use case handler: requestMapper → useCase → responseMapper\n const { requestMapper, useCase, responseMapper } = config;\n\n // Map request to use case input\n // Cast is safe: ValidatedRequestInternal has same shape as ValidatedRequest<TRoute>\n // Type erasure in this function requires the cast for TypeScript\n // validatedContext is typed correctly based on route's context schema\n const input = requestMapper(\n validatedRequest as unknown as ValidatedRequest<RouteDefinition>,\n validatedContext as HandlerContext,\n );\n\n // Execute use case\n const output = await useCase.execute(input);\n\n // Map output to HTTP response\n return responseMapper(output);\n }\n };\n\n let response: HandlerResponse;\n\n if (allMiddleware.length === 0) {\n response = await executePipeline();\n } else {\n // Build middleware chain\n // Note: Middleware receives the raw context before validation\n let index = 0;\n const next = async (): Promise<HandlerResponse> => {\n if (index >= allMiddleware.length) {\n return executePipeline();\n }\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- index bounds checked above\n const mw = allMiddleware[index++]!;\n return mw(rawRequest, rawContext, next);\n };\n\n response = await next();\n }\n\n // Always validate status code (must be 100-599)\n validateStatusCode(response.status);\n\n // Validate response schema (if enabled)\n if (shouldValidateResponse) {\n const responseValidationResult = validateResponseData(route, response);\n\n if (!responseValidationResult.success) {\n const errors = responseValidationResult.errors ?? [];\n throw new ControllerError({\n message: 'Response validation failed',\n code: 'RESPONSE_VALIDATION_ERROR',\n cause: new Error(errors.map((e) => `${e.path.join('.')}: ${e.message}`).join('; ')),\n });\n }\n }\n\n return response;\n },\n };\n}\n\n/**\n * Validates request data against route schemas.\n */\nfunction validateRequestData(\n route: RouteDefinition,\n rawRequest: RawHttpRequest,\n): ValidationResultInternal {\n const errors: ValidationIssue[] = [];\n const data: {\n body?: unknown;\n query?: unknown;\n pathParams?: unknown;\n headers?: unknown;\n } = {};\n\n // Validate body\n if (route.request.body?.schema) {\n const result = (route.request.body.schema as SchemaAdapter).validate(rawRequest.body);\n if (result.success) {\n data.body = result.data;\n } else {\n errors.push(\n ...result.issues.map((issue) => ({\n ...issue,\n path: ['body', ...issue.path],\n })),\n );\n }\n }\n\n // Validate query\n if (route.request.query?.schema) {\n const queryObj = normalizeQuery(rawRequest.query);\n const result = (route.request.query.schema as SchemaAdapter).validate(queryObj);\n if (result.success) {\n data.query = result.data;\n } else {\n errors.push(\n ...result.issues.map((issue) => ({\n ...issue,\n path: ['query', ...issue.path],\n })),\n );\n }\n }\n\n // Validate path params\n if (route.request.params?.schema) {\n const result = (route.request.params.schema as SchemaAdapter).validate(rawRequest.params ?? {});\n if (result.success) {\n data.pathParams = result.data;\n } else {\n errors.push(\n ...result.issues.map((issue) => ({\n ...issue,\n path: ['pathParams', ...issue.path],\n })),\n );\n }\n } else {\n // Normalize raw params if no schema (ensure all values are strings)\n data.pathParams = normalizePathParams(rawRequest.params);\n }\n\n // Validate headers\n if (route.request.headers?.schema) {\n const headersObj = normalizeHeaders(rawRequest.headers);\n const result = (route.request.headers.schema as SchemaAdapter).validate(headersObj);\n if (result.success) {\n data.headers = result.data;\n } else {\n errors.push(\n ...result.issues.map((issue) => ({\n ...issue,\n path: ['headers', ...issue.path],\n })),\n );\n }\n }\n\n if (errors.length > 0) {\n return { success: false, errors };\n }\n\n return { success: true, data };\n}\n\n/**\n * Validates response data against route response schemas.\n */\nfunction validateResponseData(\n route: RouteDefinition,\n response: HandlerResponse,\n): ValidationResultInternal {\n const statusCode = String(response.status);\n const responses = route.responses as Record<string, { schema?: SchemaAdapter } | undefined>;\n const responseConfig = responses[statusCode];\n\n // No schema defined for this status code - skip validation\n if (!responseConfig) {\n return { success: true };\n }\n\n const schema = responseConfig.schema;\n\n // No schema in the response config - skip validation\n if (!schema) {\n return { success: true };\n }\n\n // Validate response body against schema\n const result = schema.validate(response.body);\n\n if (result.success) {\n return { success: true };\n }\n\n // Prefix errors with 'response.' for clarity\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['response', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\n/**\n * Validates context data against route context schema.\n */\nfunction validateContextData(\n route: RouteDefinition,\n context: HandlerContext,\n): ContextValidationResultInternal {\n const contextSchema = route.request.context?.schema as SchemaAdapter | undefined;\n\n // No context schema defined - skip validation\n if (!contextSchema) {\n return { success: true, data: context };\n }\n\n // Validate context against schema\n const result = contextSchema.validate(context);\n\n if (result.success) {\n return { success: true, data: result.data };\n }\n\n // Prefix errors with 'context.' for clarity\n const errors = result.issues.map((issue) => ({\n ...issue,\n path: ['context', ...issue.path],\n }));\n\n return { success: false, errors };\n}\n\ninterface ValidationResultInternal {\n success: boolean;\n errors?: ValidationIssue[];\n data?: {\n body?: unknown;\n query?: unknown;\n pathParams?: unknown;\n headers?: unknown;\n };\n}\n\ninterface ContextValidationResultInternal {\n success: boolean;\n errors?: ValidationIssue[];\n data?: unknown;\n}\n\n/**\n * Internal validated request type with unknown fields.\n * Used inside createRouteHandler where specific types are erased.\n * The requestMapper receives the properly typed ValidatedRequest<TRoute>.\n */\ninterface ValidatedRequestInternal {\n readonly body: unknown;\n readonly query: unknown;\n readonly pathParams: unknown;\n readonly headers: unknown;\n readonly raw: {\n readonly method: string;\n readonly url: string;\n readonly headers: Record<string, string>;\n };\n}\n\n/**\n * Validates that an HTTP status code is in the valid range (100-599).\n *\n * @throws {ControllerError} If the status code is invalid\n */\nfunction validateStatusCode(status: number): void {\n if (!Number.isInteger(status) || status < 100 || status > 599) {\n throw new ControllerError({\n message: `Invalid HTTP status code: ${status}. Status must be an integer between 100 and 599.`,\n code: 'INVALID_STATUS_CODE',\n });\n }\n}\n\n/**\n * Normalizes query parameters, preserving arrays for duplicate keys.\n *\n * When a query parameter appears multiple times (e.g., `?tag=a&tag=b`),\n * the framework provides an array. This function preserves that array\n * so schema validation can properly validate array vs single-value params.\n *\n * Empty strings are allowed (e.g., `?flag=` results in `{ flag: '' }`).\n * Undefined values are filtered out from arrays.\n */\nfunction normalizeQuery(\n query?: Record<string, string | string[] | undefined>,\n): Record<string, string | string[]> {\n if (!query) return {};\n\n const result: Record<string, string | string[]> = {};\n for (const [key, value] of Object.entries(query)) {\n if (value === undefined) continue;\n\n if (Array.isArray(value)) {\n // Filter out undefined values but preserve the array structure\n const definedValues = value.filter((v): v is string => v !== undefined);\n if (definedValues.length === 1 && definedValues[0] !== undefined) {\n // Single value in array - unwrap for convenience\n result[key] = definedValues[0];\n } else if (definedValues.length > 1) {\n // Multiple values - preserve as array for schema validation\n result[key] = definedValues;\n }\n // Empty array (all undefined) - skip this key\n } else {\n result[key] = value;\n }\n }\n return result;\n}\n\n/**\n * Normalizes path parameters to ensure all values are non-empty strings.\n *\n * @throws {InvalidRequestError} If any path parameter is empty\n */\nfunction normalizePathParams(params?: Record<string, string>): Record<string, string> {\n if (!params) return {};\n\n const result: Record<string, string> = {};\n const emptyParams: string[] = [];\n\n for (const [key, value] of Object.entries(params)) {\n if (value !== undefined) {\n const stringValue = String(value);\n if (stringValue === '') {\n emptyParams.push(key);\n } else {\n result[key] = stringValue;\n }\n }\n }\n\n // Throw error for empty path params instead of silently filtering\n if (emptyParams.length > 0) {\n throw new InvalidRequestError({\n message: 'Path parameters cannot be empty',\n validationErrors: emptyParams.map((param) => ({\n field: `pathParams.${param}`,\n message: 'Path parameter cannot be empty',\n })),\n });\n }\n\n return result;\n}\n\n/**\n * Normalizes headers to a flat object.\n *\n * Per RFC 7230, multiple header values are joined with \", \" (comma + space).\n * Headers are lowercased for consistency.\n */\nfunction normalizeHeaders(\n headers: Record<string, string | string[] | undefined>,\n): Record<string, string> {\n const result: Record<string, string> = {};\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined) continue;\n\n if (Array.isArray(value)) {\n // Filter undefined values and join per RFC 7230\n const definedValues = value.filter((v): v is string => v !== undefined);\n if (definedValues.length > 0) {\n result[key.toLowerCase()] = definedValues.join(', ');\n }\n } else {\n result[key.toLowerCase()] = value;\n }\n }\n return result;\n}\n\n/**\n * Generates a unique request ID using crypto-secure UUID.\n */\nfunction generateRequestId(): string {\n return `req_${crypto.randomUUID()}`;\n}\n","/**\n * @fileoverview Builder pattern for creating type-safe server routes.\n *\n * The `serverRoutes` function returns a builder that provides 100% type inference\n * for all handler parameters - no manual type annotations required.\n *\n * @module unified/server/server-routes-builder\n */\n\nimport type { RouterConfig, RouterDefinition, GetRoute, RouterKeys } from '../route/types';\nimport type {\n AnyHandlerConfig,\n CreateServerRoutesOptions,\n HandlerResponse,\n MiddlewareFunction,\n RouteHandlerConfig,\n SimpleHandlerConfig,\n SimpleHandlerFn,\n TypedContext,\n UnifiedRouteInput,\n UseCasePort,\n ValidatedRequest,\n} from './types';\nimport { createServerRoutesInternal } from './create-server-routes';\nimport type { RouteDefinition } from '../route/types';\n\n// ============================================================================\n// Builder Types\n// ============================================================================\n\n/**\n * Error type displayed when attempting to build() with missing handlers.\n * The `___missingRoutes` property shows which routes are missing.\n */\nexport interface MissingHandlersError<TMissing extends string> {\n /**\n * This error indicates that not all routes have handlers.\n * Use buildPartial() to build with only the defined handlers,\n * or add handlers for the missing routes.\n */\n (options?: never): never;\n /** Routes that are missing handlers */\n readonly ___missingRoutes: TMissing;\n}\n\n/**\n * Handler configuration for the builder pattern.\n * Identical to RouteHandlerConfig but with proper TypedContext.\n */\nexport interface BuilderHandlerConfig<TRoute extends RouteDefinition, TInput, TOutput> {\n /**\n * Maps the validated HTTP request to use case input.\n * Both `req` and `ctx` are fully typed based on route schemas.\n */\n readonly requestMapper: (req: ValidatedRequest<TRoute>, ctx: TypedContext<TRoute>) => TInput;\n\n /**\n * The use case to execute.\n */\n readonly useCase: UseCasePort<TInput, TOutput>;\n\n /**\n * Maps the use case output to an HTTP response.\n */\n readonly responseMapper: (output: TOutput) => HandlerResponse;\n\n /**\n * Middleware to run before the handler.\n */\n readonly middleware?: readonly MiddlewareFunction[];\n}\n\n/**\n * Builder interface for creating type-safe server routes.\n *\n * Each `.handle()` call captures the specific route type and provides\n * full type inference for requestMapper, useCase, and responseMapper.\n *\n * @typeParam T - The router configuration type\n * @typeParam THandled - Union of route keys that have handlers (accumulates)\n *\n * @example\n * ```typescript\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', {\n * requestMapper: (req, ctx) => ({\n * name: req.body.name, // Fully typed!\n * createdBy: ctx.userId, // Fully typed!\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (output) => ({\n * status: 201 as const,\n * body: { projectId: output.projectId },\n * }),\n * })\n * .handle('projects.list', { ... })\n * .build();\n * ```\n */\nexport interface ServerRoutesBuilder<T extends RouterConfig, THandled extends string = never> {\n /**\n * Register a simple handler for a route.\n * The handler receives validated request and context, returns response directly.\n *\n * @param key - The route key (e.g., 'projects.get')\n * @param handlerOrConfig - Simple handler function or configuration with handler and optional middleware\n * @returns A new builder with the route key added to handled routes\n */\n handle<K extends Exclude<RouterKeys<T>, THandled>>(\n key: K,\n handlerOrConfig: SimpleHandlerFn<GetRoute<T, K>> | SimpleHandlerConfig<GetRoute<T, K>>,\n ): ServerRoutesBuilder<T, THandled | K>;\n\n /**\n * Register a handler using the use case pattern.\n * Follows: requestMapper → useCase.execute() → responseMapper\n *\n * @param key - The route key (e.g., 'projects.create')\n * @param config - Handler configuration with requestMapper, useCase, responseMapper\n * @returns A new builder with the route key added to handled routes\n */\n handleWithUseCase<K extends Exclude<RouterKeys<T>, THandled>, TInput, TOutput>(\n key: K,\n config: BuilderHandlerConfig<GetRoute<T, K>, TInput, TOutput>,\n ): ServerRoutesBuilder<T, THandled | K>;\n\n /**\n * Build the routes array for framework registration.\n *\n * This method is only available when ALL routes have handlers.\n * If some routes are missing handlers, use `buildPartial()` instead.\n *\n * @param options - Optional configuration (validation, middleware)\n * @returns Array of route inputs for framework registration\n *\n * @throws {Error} At compile time if routes are missing (type error)\n */\n build: [Exclude<RouterKeys<T>, THandled>] extends [never]\n ? (options?: CreateServerRoutesOptions) => UnifiedRouteInput[]\n : MissingHandlersError<Exclude<RouterKeys<T>, THandled>>;\n\n /**\n * Build routes for only the defined handlers.\n *\n * Use this when you only want to register handlers for some routes,\n * not all routes in the router. No compile-time enforcement.\n *\n * @param options - Optional configuration (validation, middleware)\n * @returns Array of route inputs for framework registration\n */\n buildPartial(options?: CreateServerRoutesOptions): UnifiedRouteInput[];\n}\n\n// ============================================================================\n// Builder Implementation\n// ============================================================================\n\n/**\n * Internal builder implementation.\n *\n * Uses an immutable pattern where each handle() call returns a new\n * builder instance with the updated handlers map.\n */\nclass ServerRoutesBuilderImpl<T extends RouterConfig, THandled extends string = never> {\n private readonly router: T | RouterDefinition<T>;\n private readonly handlers: Map<string, AnyHandlerConfig<RouteDefinition, unknown, unknown>>;\n\n constructor(\n router: T | RouterDefinition<T>,\n handlers?: Map<string, AnyHandlerConfig<RouteDefinition, unknown, unknown>>,\n ) {\n this.router = router;\n this.handlers = handlers ?? new Map();\n }\n\n handle<K extends Exclude<RouterKeys<T>, THandled>>(\n key: K,\n handlerOrConfig: SimpleHandlerFn<GetRoute<T, K>> | SimpleHandlerConfig<GetRoute<T, K>>,\n ): ServerRoutesBuilder<T, THandled | K> {\n // Normalize function to config object\n const config: SimpleHandlerConfig<RouteDefinition> =\n typeof handlerOrConfig === 'function'\n ? { handler: handlerOrConfig as SimpleHandlerFn<RouteDefinition> }\n : (handlerOrConfig as SimpleHandlerConfig<RouteDefinition>);\n\n const newHandlers = new Map(this.handlers);\n newHandlers.set(key as string, config);\n\n return new ServerRoutesBuilderImpl<T, THandled | K>(\n this.router,\n newHandlers,\n ) as unknown as ServerRoutesBuilder<T, THandled | K>;\n }\n\n handleWithUseCase<K extends Exclude<RouterKeys<T>, THandled>, TInput, TOutput>(\n key: K,\n config: BuilderHandlerConfig<GetRoute<T, K>, TInput, TOutput>,\n ): ServerRoutesBuilder<T, THandled | K> {\n // Create new handlers map (immutable pattern)\n const newHandlers = new Map(this.handlers);\n newHandlers.set(key as string, config as RouteHandlerConfig<RouteDefinition, unknown, unknown>);\n\n // Return new builder with updated type\n // Cast through unknown is safe: the type system tracks THandled | K through the interface\n // The conditional type on `build` cannot be proven at compile time, hence the cast\n return new ServerRoutesBuilderImpl<T, THandled | K>(\n this.router,\n newHandlers,\n ) as unknown as ServerRoutesBuilder<T, THandled | K>;\n }\n\n // The build method's type is determined by the interface conditional type\n // At runtime, it always works the same way - the conditional type only affects compile-time\n build(options?: CreateServerRoutesOptions): UnifiedRouteInput[] {\n return createServerRoutesInternal(this.router, Object.fromEntries(this.handlers), options);\n }\n\n buildPartial(options?: CreateServerRoutesOptions): UnifiedRouteInput[] {\n return createServerRoutesInternal(this.router, Object.fromEntries(this.handlers), {\n ...options,\n allowPartial: true,\n });\n }\n}\n\n// ============================================================================\n// Public API\n// ============================================================================\n\n/**\n * Creates a type-safe server routes builder for a router.\n *\n * The builder pattern provides 100% type inference for all handler parameters:\n * - `req.body`, `req.query`, `req.pathParams`, `req.headers` are typed from route schemas\n * - `ctx` is typed from the route's context schema\n * - `output` in responseMapper is typed from the use case\n *\n * @param router - Router definition or router config\n * @returns Builder for registering handlers\n *\n * @example Basic usage\n * ```typescript\n * import { serverRoutes } from '@cosmneo/onion-lasagna/http/server';\n * import { projectRouter } from './router';\n *\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', {\n * requestMapper: (req, ctx) => ({\n * name: req.body.name,\n * createdBy: ctx.userId,\n * }),\n * useCase: createProjectUseCase,\n * responseMapper: (output) => ({\n * status: 201 as const,\n * body: { projectId: output.projectId },\n * }),\n * })\n * .handle('projects.list', {\n * requestMapper: (req) => ({\n * page: req.query.page ?? 1,\n * limit: req.query.limit ?? 20,\n * }),\n * useCase: listProjectsUseCase,\n * responseMapper: (output) => ({\n * status: 200 as const,\n * body: output.projects,\n * }),\n * })\n * .build();\n *\n * // Register with framework\n * registerHonoRoutes(app, routes);\n * ```\n *\n * @example Partial build (only some routes)\n * ```typescript\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', { ... })\n * // Skip other routes\n * .buildPartial(); // No type error even with missing routes\n * ```\n *\n * @example With options\n * ```typescript\n * const routes = serverRoutes(projectRouter)\n * .handle('projects.create', { ... })\n * .handle('projects.list', { ... })\n * .build({\n * validateRequest: true,\n * validateResponse: process.env.NODE_ENV !== 'production',\n * middleware: [loggingMiddleware],\n * });\n * ```\n */\nexport function serverRoutes<T extends RouterConfig>(\n router: T | RouterDefinition<T>,\n): ServerRoutesBuilder<T, never> {\n // Cast through unknown is safe: initial builder has no handlers (THandled = never)\n return new ServerRoutesBuilderImpl(router) as unknown as ServerRoutesBuilder<T, never>;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgPO,SAAS,sBACd,QACgD;AAChD,SAAO,aAAa,UAAU,OAAO,OAAO,YAAY;AAC1D;;;ACjNO,SAAS,2BACd,QACA,UACA,SACqB;AACrB,QAAM,SAAS,mBAAmB,MAAM,IAAI,OAAO,SAAS;AAC5D,QAAM,kBAAkB,cAAc,MAAM;AAI5C,QAAM,eAAe,wBAAwB,eAAe;AAE5D,QAAM,SAA8B,CAAC;AAGrC,QAAM,kBAA6C;AAAA,IACjD,GAAG;AAAA,IACH,iBAAiB,SAAS,mBAAmB;AAAA,IAC7C,kBAAkB,SAAS,oBAAoB;AAAA,IAC/C,cAAc,SAAS,gBAAgB;AAAA,EACzC;AAEA,aAAW,EAAE,KAAK,MAAM,KAAK,cAAc;AACzC,UAAM,gBAAgB,SAAS,GAAG;AAElC,QAAI,CAAC,eAAe;AAClB,UAAI,gBAAgB,cAAc;AAEhC;AAAA,MACF;AACA,YAAM,IAAI;AAAA,QACR,8BAA8B,GAAG;AAAA,MACnC;AAAA,IACF;AAEA,WAAO,KAAK,mBAAmB,OAAO,eAAe,eAAe,CAAC;AAAA,EACvE;AAEA,SAAO;AACT;AAkBA,SAAS,wBAA+D,QAAkB;AACxF,SAAO,CAAC,GAAG,MAAM,EAAE,KAAK,CAAC,GAAG,MAAM;AAChC,UAAM,YAAY,EAAE,MAAM,KAAK,MAAM,GAAG,EAAE,OAAO,OAAO;AACxD,UAAM,YAAY,EAAE,MAAM,KAAK,MAAM,GAAG,EAAE,OAAO,OAAO;AAExD,UAAM,SAAS,KAAK,IAAI,UAA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AAA,MACL;AAAA,IACF;AAAA,EACF;AAAA,EAEA,kBACE,KACA,QACsC;AAEtC,UAAM,cAAc,IAAI,IAAI,KAAK,QAAQ;AACzC,gBAAY,IAAI,KAAe,MAA+D;AAK9F,WAAO,IAAI;AAAA,MACT,KAAK;AAAA,MACL;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA,EAIA,MAAM,SAA0D;AAC9D,WAAO,2BAA2B,KAAK,QAAQ,OAAO,YAAY,KAAK,QAAQ,GAAG,OAAO;AAAA,EAC3F;AAAA,EAEA,aAAa,SAA0D;AACrE,WAAO,2BAA2B,KAAK,QAAQ,OAAO,YAAY,KAAK,QAAQ,GAAG;AAAA,MAChF,GAAG;AAAA,MACH,cAAc;AAAA,IAChB,CAAC;AAAA,EACH;AACF;AAuEO,SAAS,aACd,QAC+B;AAE/B,SAAO,IAAI,wBAAwB,MAAM;AAC3C;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/presentation/http/openapi/generate.ts"],"sourcesContent":["/**\n * @fileoverview OpenAPI specification generation from router definitions.\n *\n * The `generateOpenAPI` function creates a complete OpenAPI 3.1 specification\n * from a router definition. All route schemas are converted to JSON Schema\n * and included in the specification.\n *\n * @module unified/openapi/generate\n */\n\nimport type { JsonSchema, SchemaAdapter } from '../schema/types';\nimport type { RouterConfig, RouterDefinition, RouteDefinition } from '../route/types';\nimport { isRouterDefinition, collectRoutes, getPathParamNames } from '../route/types';\nimport type {\n OpenAPIConfig,\n OpenAPISpec,\n OpenAPIPaths,\n OpenAPIPathItem,\n OpenAPIOperation,\n OpenAPIParameter,\n OpenAPIRequestBody,\n OpenAPIResponses,\n OpenAPIResponse,\n OpenAPITag,\n} from './types';\n\n/**\n * Checks if a value is a valid JSON schema structure.\n *\n * A valid JSON schema must be an object and have at least one of:\n * - `type` property (primitive or object types)\n * - `$ref` property (reference to another schema)\n * - `oneOf`, `anyOf`, `allOf` (composition)\n * - `properties` (object schema without explicit type)\n * - `items` (array schema without explicit type)\n * - `enum` (enumeration)\n * - `const` (constant value)\n *\n * @param value - The value to check\n * @returns True if value appears to be a valid JSON schema\n */\nfunction isValidJsonSchema(value: unknown): value is JsonSchema {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return false;\n }\n\n const schema = value as Record<string, unknown>;\n\n // Check for valid JSON schema indicators\n return (\n 'type' in schema ||\n '$ref' in schema ||\n 'oneOf' in schema ||\n 'anyOf' in schema ||\n 'allOf' in schema ||\n 'properties' in schema ||\n 'items' in schema ||\n 'enum' in schema ||\n 'const' in schema\n );\n}\n\n/**\n * Generates an OpenAPI specification from a router definition.\n *\n * This function walks the router structure, extracts JSON schemas from\n * all route definitions, and builds a complete OpenAPI 3.1 specification.\n *\n * @param router - Router definition or router config\n * @param config - OpenAPI configuration (info, servers, security, etc.)\n * @returns Complete OpenAPI specification\n *\n * @example Basic usage\n * ```typescript\n * import { generateOpenAPI } from '@cosmneo/onion-lasagna/http/openapi';\n * import { api } from './routes';\n *\n * const spec = generateOpenAPI(api, {\n * info: {\n * title: 'My API',\n * version: '1.0.0',\n * description: 'A comprehensive API for managing resources',\n * },\n * servers: [\n * { url: 'http://localhost:3000', description: 'Development' },\n * { url: 'https://api.example.com', description: 'Production' },\n * ],\n * });\n *\n * // Serve the spec\n * app.get('/openapi.json', (c) => c.json(spec));\n * ```\n *\n * @example With security\n * ```typescript\n * const spec = generateOpenAPI(api, {\n * info: { title: 'Secure API', version: '1.0.0' },\n * securitySchemes: {\n * bearerAuth: {\n * type: 'http',\n * scheme: 'bearer',\n * bearerFormat: 'JWT',\n * },\n * apiKey: {\n * type: 'apiKey',\n * in: 'header',\n * name: 'X-API-Key',\n * },\n * },\n * security: [{ bearerAuth: [] }],\n * });\n * ```\n *\n * @example With custom tags\n * ```typescript\n * const spec = generateOpenAPI(api, {\n * info: { title: 'Tagged API', version: '1.0.0' },\n * tags: [\n * { name: 'Users', description: 'User management operations' },\n * { name: 'Posts', description: 'Blog post operations' },\n * { name: 'Admin', description: 'Administrative operations' },\n * ],\n * });\n * ```\n */\nexport function generateOpenAPI<T extends RouterConfig>(\n router: T | RouterDefinition<T>,\n config: OpenAPIConfig,\n): OpenAPISpec {\n const routes = isRouterDefinition(router) ? router.routes : router;\n const collectedRoutes = collectRoutes(routes);\n\n // Build paths\n const paths: OpenAPIPaths = {};\n const allTags = new Set<string>();\n\n for (const { route } of collectedRoutes) {\n const openAPIPath = convertToOpenAPIPath(route.path);\n\n if (!paths[openAPIPath]) {\n paths[openAPIPath] = {};\n }\n\n const operation = buildOperation(route);\n const method = route.method.toLowerCase() as keyof OpenAPIPathItem;\n\n (paths[openAPIPath] as Record<string, OpenAPIOperation>)[method] = operation;\n\n // Collect tags\n if (operation.tags) {\n for (const tag of operation.tags) {\n allTags.add(tag);\n }\n }\n }\n\n // Build the specification\n const spec: OpenAPISpec = {\n openapi: config.openapi ?? '3.1.0',\n info: config.info,\n paths,\n };\n\n // Add optional sections\n if (config.servers && config.servers.length > 0) {\n (spec as { servers: typeof config.servers }).servers = config.servers;\n }\n\n if (config.securitySchemes && Object.keys(config.securitySchemes).length > 0) {\n (spec as { components: { securitySchemes: typeof config.securitySchemes } }).components = {\n securitySchemes: config.securitySchemes,\n };\n }\n\n if (config.security && config.security.length > 0) {\n (spec as { security: typeof config.security }).security = config.security;\n }\n\n // Merge custom tags with collected tags\n const tags: OpenAPITag[] = config.tags ? [...config.tags] : [];\n for (const tagName of allTags) {\n if (!tags.some((t) => t.name === tagName)) {\n tags.push({ name: tagName });\n }\n }\n if (tags.length > 0) {\n (spec as unknown as { tags: OpenAPITag[] }).tags = tags;\n }\n\n if (config.externalDocs) {\n (spec as { externalDocs: typeof config.externalDocs }).externalDocs = config.externalDocs;\n }\n\n return spec;\n}\n\n/**\n * Converts a path with :param to OpenAPI {param} format.\n */\nfunction convertToOpenAPIPath(path: string): string {\n return path.replace(/:([a-zA-Z_][a-zA-Z0-9_]*)/g, '{$1}');\n}\n\n/**\n * Builds an OpenAPI operation from a route definition.\n */\nfunction buildOperation(route: RouteDefinition): OpenAPIOperation {\n const operation: OpenAPIOperation = {\n responses: buildResponses(route),\n };\n\n // Add documentation\n if (route.docs.operationId) {\n (operation as { operationId: string }).operationId = route.docs.operationId;\n }\n\n if (route.docs.summary) {\n (operation as { summary: string }).summary = route.docs.summary;\n }\n\n if (route.docs.description) {\n (operation as { description: string }).description = route.docs.description;\n }\n\n if (route.docs.tags && route.docs.tags.length > 0) {\n (operation as { tags: readonly string[] }).tags = route.docs.tags;\n }\n\n if (route.docs.deprecated) {\n (operation as { deprecated: boolean }).deprecated = true;\n }\n\n if (route.docs.security && route.docs.security.length > 0) {\n (operation as { security: typeof route.docs.security }).security = route.docs.security;\n }\n\n if (route.docs.externalDocs) {\n (operation as { externalDocs: typeof route.docs.externalDocs }).externalDocs =\n route.docs.externalDocs;\n }\n\n // Add parameters\n const parameters = buildParameters(route);\n if (parameters.length > 0) {\n (operation as unknown as { parameters: OpenAPIParameter[] }).parameters = parameters;\n }\n\n // Add request body\n if (route.request.body) {\n (operation as { requestBody: OpenAPIRequestBody }).requestBody = buildRequestBody(route);\n }\n\n return operation;\n}\n\n/**\n * Builds OpenAPI parameters from route.\n */\nfunction buildParameters(route: RouteDefinition): OpenAPIParameter[] {\n const parameters: OpenAPIParameter[] = [];\n\n // Path parameters\n const pathParamNames = getPathParamNames(route.path);\n for (const name of pathParamNames) {\n const param: OpenAPIParameter = {\n name,\n in: 'path',\n required: true,\n schema: { type: 'string' },\n };\n\n // If we have a params schema, try to get more info\n if (route.request.params?.schema) {\n const jsonSchema = (route.request.params.schema as SchemaAdapter).toJsonSchema();\n if (jsonSchema.properties && typeof jsonSchema.properties === 'object') {\n const propSchema = (jsonSchema.properties as Record<string, unknown>)[name];\n if (isValidJsonSchema(propSchema)) {\n (param as { schema: JsonSchema }).schema = propSchema;\n }\n }\n }\n\n parameters.push(param);\n }\n\n // Query parameters\n if (route.request.query?.schema) {\n const querySchema = (route.request.query.schema as SchemaAdapter).toJsonSchema();\n\n if (querySchema.properties && typeof querySchema.properties === 'object') {\n const requiredFields = new Set(\n Array.isArray(querySchema.required) ? querySchema.required : [],\n );\n\n for (const [name, propSchema] of Object.entries(\n querySchema.properties as Record<string, unknown>,\n )) {\n // Skip invalid schema structures\n if (!isValidJsonSchema(propSchema)) {\n continue;\n }\n\n const param: OpenAPIParameter = {\n name,\n in: 'query',\n required: requiredFields.has(name),\n schema: propSchema,\n };\n\n // Add description if present\n if ('description' in propSchema && typeof propSchema.description === 'string') {\n (param as { description: string }).description = propSchema.description;\n }\n\n parameters.push(param);\n }\n }\n }\n\n // Header parameters\n if (route.request.headers?.schema) {\n const headersSchema = (route.request.headers.schema as SchemaAdapter).toJsonSchema();\n\n if (headersSchema.properties && typeof headersSchema.properties === 'object') {\n const requiredFields = new Set(\n Array.isArray(headersSchema.required) ? headersSchema.required : [],\n );\n\n for (const [name, propSchema] of Object.entries(\n headersSchema.properties as Record<string, unknown>,\n )) {\n // Skip invalid schema structures\n if (!isValidJsonSchema(propSchema)) {\n continue;\n }\n\n const param: OpenAPIParameter = {\n name,\n in: 'header',\n required: requiredFields.has(name),\n schema: propSchema,\n };\n\n parameters.push(param);\n }\n }\n }\n\n return parameters;\n}\n\n/**\n * Builds OpenAPI request body from route.\n */\nfunction buildRequestBody(route: RouteDefinition): OpenAPIRequestBody {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- caller checks body exists\n const bodyConfig = route.request.body!;\n const contentType = bodyConfig.contentType ?? 'application/json';\n\n const requestBody: OpenAPIRequestBody = {\n required: bodyConfig.required !== false,\n content: {\n [contentType]: {\n schema: (bodyConfig.schema as SchemaAdapter).toJsonSchema(),\n },\n },\n };\n\n if (bodyConfig.description) {\n (requestBody as { description: string }).description = bodyConfig.description;\n }\n\n return requestBody;\n}\n\n/**\n * Builds OpenAPI responses from route.\n */\nfunction buildResponses(route: RouteDefinition): OpenAPIResponses {\n const responses: OpenAPIResponses = {};\n\n for (const [statusCode, responseConfig] of Object.entries(route.responses)) {\n if (!responseConfig || typeof responseConfig !== 'object') continue;\n\n const response: OpenAPIResponse = {\n description:\n (responseConfig as { description?: string }).description ?? `Response ${statusCode}`,\n };\n\n const schema = (responseConfig as { schema?: SchemaAdapter }).schema;\n if (schema) {\n const contentType =\n (responseConfig as { contentType?: string }).contentType ?? 'application/json';\n (response as { content: Record<string, { schema: object }> }).content = {\n [contentType]: {\n schema: schema.toJsonSchema(),\n },\n };\n }\n\n responses[statusCode] = response;\n }\n\n // Ensure at least a default response exists\n if (Object.keys(responses).length === 0) {\n responses['200'] = { description: 'Successful response' };\n }\n\n return responses;\n}\n"],"mappings":";;;;;;;AAyCA,SAAS,kBAAkB,OAAqC;AAC9D,MAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GAAG;AAC/D,WAAO;AAAA,EACT;AAEA,QAAM,SAAS;AAGf,SACE,UAAU,UACV,UAAU,UACV,WAAW,UACX,WAAW,UACX,WAAW,UACX,gBAAgB,UAChB,WAAW,UACX,UAAU,UACV,WAAW;AAEf;AAiEO,SAAS,gBACd,QACA,QACa;AACb,QAAM,SAAS,mBAAmB,MAAM,IAAI,OAAO,SAAS;AAC5D,QAAM,kBAAkB,cAAc,MAAM;AAG5C,QAAM,QAAsB,CAAC;AAC7B,QAAM,UAAU,oBAAI,IAAY;AAEhC,aAAW,EAAE,MAAM,KAAK,iBAAiB;AACvC,UAAM,cAAc,qBAAqB,MAAM,IAAI;AAEnD,QAAI,CAAC,MAAM,WAAW,GAAG;AACvB,YAAM,WAAW,IAAI,CAAC;AAAA,IACxB;AAEA,UAAM,YAAY,eAAe,KAAK;AACtC,UAAM,SAAS,MAAM,OAAO,YAAY;AAExC,IAAC,MAAM,WAAW,EAAuC,MAAM,IAAI;AAGnE,QAAI,UAAU,MAAM;AAClB,iBAAW,OAAO,UAAU,MAAM;AAChC,gBAAQ,IAAI,GAAG;AAAA,MACjB;AAAA,IACF;AAAA,EACF;AAGA,QAAM,OAAoB;AAAA,IACxB,S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