@geekmidas/cli 10.0.0-alpha.55 → 10.0.0-alpha.57

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 (76) hide show
  1. package/README.md +9 -8
  2. package/dist/{OpenApiTsGenerator-WlUHjimW.cjs → OpenApiTsGenerator-BLRQ7Iu9.cjs} +25 -49
  3. package/dist/OpenApiTsGenerator-BLRQ7Iu9.cjs.map +1 -0
  4. package/dist/{OpenApiTsGenerator-DKmAorGX.mjs → OpenApiTsGenerator-NThANByQ.mjs} +25 -49
  5. package/dist/OpenApiTsGenerator-NThANByQ.mjs.map +1 -0
  6. package/dist/{SSMStateStore-oda9xOGc.mjs → SSMStateStore-7hPWW7v7.mjs} +12 -7
  7. package/dist/{SSMStateStore-oda9xOGc.mjs.map → SSMStateStore-7hPWW7v7.mjs.map} +1 -1
  8. package/dist/{SSMStateStore-DD7jKrCO.cjs → SSMStateStore-C7KcDSTb.cjs} +12 -7
  9. package/dist/{SSMStateStore-DD7jKrCO.cjs.map → SSMStateStore-C7KcDSTb.cjs.map} +1 -1
  10. package/dist/{backends-BNrMPlJb.mjs → backends-BcHL7Gy_.mjs} +2 -2
  11. package/dist/{backends-BNrMPlJb.mjs.map → backends-BcHL7Gy_.mjs.map} +1 -1
  12. package/dist/{backends-nBauiBkt.cjs → backends-_gQdAzBK.cjs} +2 -2
  13. package/dist/{backends-nBauiBkt.cjs.map → backends-_gQdAzBK.cjs.map} +1 -1
  14. package/dist/{config-XEd-dKVX.mjs → config-20V08LZp.mjs} +2 -3
  15. package/dist/config-20V08LZp.mjs.map +1 -0
  16. package/dist/{config-C7NZG2tr.cjs → config-CP6wsLHA.cjs} +2 -3
  17. package/dist/config-CP6wsLHA.cjs.map +1 -0
  18. package/dist/config.cjs +2 -2
  19. package/dist/config.d.cts +2 -2
  20. package/dist/config.d.mts +2 -2
  21. package/dist/config.mjs +2 -2
  22. package/dist/{encryption-DSHYN5ap.cjs → encryption-10Srqiix.cjs} +4 -4
  23. package/dist/{encryption-DSHYN5ap.cjs.map → encryption-10Srqiix.cjs.map} +1 -1
  24. package/dist/{encryption-Bc1cMdeY.mjs → encryption-KQTYFEzU.mjs} +4 -4
  25. package/dist/{encryption-Bc1cMdeY.mjs.map → encryption-KQTYFEzU.mjs.map} +1 -1
  26. package/dist/{github-CWflxaV4.cjs → github-DtRUkHN8.cjs} +3 -3
  27. package/dist/{github-CWflxaV4.cjs.map → github-DtRUkHN8.cjs.map} +1 -1
  28. package/dist/{github-DWHXTcwL.mjs → github-y7OEj59M.mjs} +3 -3
  29. package/dist/{github-DWHXTcwL.mjs.map → github-y7OEj59M.mjs.map} +1 -1
  30. package/dist/{index-B8nraKvg.d.mts → index-DMcjpvd-.d.cts} +2 -2
  31. package/dist/{index-B8nraKvg.d.mts.map → index-DMcjpvd-.d.cts.map} +1 -1
  32. package/dist/{index-BvBQS89a.d.cts → index-RM92lx8A.d.mts} +2 -2
  33. package/dist/{index-BvBQS89a.d.cts.map → index-RM92lx8A.d.mts.map} +1 -1
  34. package/dist/index.cjs +201 -1084
  35. package/dist/index.cjs.map +1 -1
  36. package/dist/index.mjs +201 -1084
  37. package/dist/index.mjs.map +1 -1
  38. package/dist/{migrate-PcQg692O.mjs → migrate-CS3DkO6y.mjs} +4 -4
  39. package/dist/{migrate-PcQg692O.mjs.map → migrate-CS3DkO6y.mjs.map} +1 -1
  40. package/dist/{migrate-DHMRgnP6.cjs → migrate-DQ54y2WD.cjs} +4 -4
  41. package/dist/{migrate-DHMRgnP6.cjs.map → migrate-DQ54y2WD.cjs.map} +1 -1
  42. package/dist/openapi.cjs +2 -2
  43. package/dist/openapi.d.cts +1 -1
  44. package/dist/openapi.d.mts +1 -1
  45. package/dist/openapi.mjs +2 -2
  46. package/dist/{ready-bES_Jk5v.mjs → ready-BSpUZnNo.mjs} +2 -2
  47. package/dist/ready-BSpUZnNo.mjs.map +1 -0
  48. package/dist/{ready-BefA4mM0.cjs → ready-MUhVJDHe.cjs} +2 -2
  49. package/dist/ready-MUhVJDHe.cjs.map +1 -0
  50. package/dist/reconcile/public.d.cts +1 -1
  51. package/dist/reconcile/public.d.mts +1 -1
  52. package/dist/{types-Cgj-cq2m.d.mts → types-BIyIQUR-.d.cts} +3 -30
  53. package/dist/{types-CmxMhLGp.d.cts.map → types-BIyIQUR-.d.cts.map} +1 -1
  54. package/dist/{types-CmxMhLGp.d.cts → types-CmQl6zaP.d.mts} +2 -31
  55. package/dist/{types-Cgj-cq2m.d.mts.map → types-CmQl6zaP.d.mts.map} +1 -1
  56. package/dist/vitest.cjs +1 -1
  57. package/dist/vitest.mjs +1 -1
  58. package/dist/workspace/index.cjs +1 -1
  59. package/dist/workspace/index.d.cts +2 -2
  60. package/dist/workspace/index.d.mts +2 -2
  61. package/dist/workspace/index.mjs +1 -1
  62. package/dist/{workspace-CXvYabDJ.cjs → workspace-BbPJVCto.cjs} +5 -5
  63. package/dist/{workspace-CXvYabDJ.cjs.map → workspace-BbPJVCto.cjs.map} +1 -1
  64. package/dist/{workspace-DL_99LJC.cjs → workspace-BpdXIeWV.cjs} +1 -16
  65. package/dist/{workspace-DL_99LJC.cjs.map → workspace-BpdXIeWV.cjs.map} +1 -1
  66. package/dist/{workspace-DHK2N1mq.mjs → workspace-C2mFV53i.mjs} +1 -16
  67. package/dist/{workspace-DHK2N1mq.mjs.map → workspace-C2mFV53i.mjs.map} +1 -1
  68. package/dist/{workspace-BE0WHPw9.mjs → workspace-CgWcE_Yr.mjs} +5 -5
  69. package/dist/{workspace-BE0WHPw9.mjs.map → workspace-CgWcE_Yr.mjs.map} +1 -1
  70. package/package.json +13 -14
  71. package/dist/OpenApiTsGenerator-DKmAorGX.mjs.map +0 -1
  72. package/dist/OpenApiTsGenerator-WlUHjimW.cjs.map +0 -1
  73. package/dist/config-C7NZG2tr.cjs.map +0 -1
  74. package/dist/config-XEd-dKVX.mjs.map +0 -1
  75. package/dist/ready-BefA4mM0.cjs.map +0 -1
  76. package/dist/ready-bES_Jk5v.mjs.map +0 -1
package/README.md CHANGED
@@ -7,7 +7,7 @@ A powerful CLI tool for building and managing TypeScript-based backend APIs with
7
7
  - **Project Scaffolding**: Interactive `init` command to bootstrap new projects with templates
8
8
  - **Multi-Provider Support**: Generate handlers for AWS Lambda (API Gateway v1/v2) and server applications
9
9
  - **Development Server**: Hot-reload development server with file watching
10
- - **Telescope Integration**: Laravel-style debugging dashboard for inspecting requests, logs, and exceptions
10
+ - **Telescope Integration**: Laravel-style recording of requests, logs and exceptions, served as JSON
11
11
  - **OpenAPI Generation**: Auto-generate OpenAPI 3.0 specifications from your endpoints
12
12
  - **Docker Support**: Generate optimized Dockerfiles with multi-stage builds, turbo prune for monorepos
13
13
  - **Secrets Management**: Secure credential generation, encryption, and stage-based secrets storage
@@ -73,7 +73,7 @@ export default defineConfig({
73
73
  // Logger configuration
74
74
  logger: './src/logger.ts#logger',
75
75
 
76
- // Optional: Telescope debugging dashboard (enabled by default in dev)
76
+ // Optional: Telescope request recording (enabled by default in dev)
77
77
  telescope: {
78
78
  enabled: true,
79
79
  path: '/__telescope',
@@ -226,7 +226,7 @@ When run without `--yes`, the command will ask:
226
226
  - `api` - Full API with auth, database, services
227
227
  - `serverless` - AWS Lambda handlers
228
228
  - `worker` - Background job processing
229
- 3. **Telescope** - Include debugging dashboard (default: yes)
229
+ 3. **Telescope** - Include request, exception and log recording (default: yes)
230
230
  4. **Database** - Include Kysely database support (default: yes)
231
231
  5. **Logger** - Choose logger implementation:
232
232
  - `pino` - Fast JSON logger for production (recommended)
@@ -545,7 +545,7 @@ services:
545
545
 
546
546
  ### `gkm dev`
547
547
 
548
- Start a development server with hot-reload and optional Telescope debugging dashboard.
548
+ Start a development server with hot-reload and optional Telescope recording.
549
549
 
550
550
  ```bash
551
551
  gkm dev [options]
@@ -557,7 +557,8 @@ gkm dev [options]
557
557
  **Features:**
558
558
  - Hot-reload on file changes (endpoints, functions, crons, subscribers)
559
559
  - Automatic port switching if requested port is in use
560
- - Telescope debugging dashboard (enabled by default)
560
+ - Telescope JSON API at `/__telescope/api` (enabled by default)
561
+ - The declared database, read-only, as JSON at `/__gkm/db`
561
562
  - Real-time WebSocket updates in Telescope
562
563
 
563
564
  **Example:**
@@ -1054,7 +1055,7 @@ interface GkmConfig {
1054
1055
 
1055
1056
  interface TelescopeConfig {
1056
1057
  enabled?: boolean; // Enable/disable (default: true in dev)
1057
- path?: string; // Dashboard path (default: '/__telescope')
1058
+ path?: string; // Where the JSON API is mounted (default: '/__telescope')
1058
1059
  ignore?: string[]; // URL patterns to ignore
1059
1060
  recordBody?: boolean; // Record request/response bodies (default: true)
1060
1061
  maxEntries?: number; // Max entries to keep (default: 1000)
@@ -1112,7 +1113,7 @@ logger: './src/utils.ts#appLogger'
1112
1113
 
1113
1114
  #### `telescope`
1114
1115
 
1115
- Configuration for the Telescope debugging dashboard. Telescope is enabled by default when using `gkm dev`.
1116
+ Configuration for Telescope, which records requests, logs and exceptions and serves them as JSON. Telescope is enabled by default when using `gkm dev`.
1116
1117
 
1117
1118
  ```typescript
1118
1119
  // Disable telescope
@@ -1137,7 +1138,7 @@ telescope: {
1137
1138
  | Option | Type | Default | Description |
1138
1139
  |--------|------|---------|-------------|
1139
1140
  | `enabled` | `boolean` | `true` | Enable/disable Telescope |
1140
- | `path` | `string` | `/__telescope` | Dashboard URL path |
1141
+ | `path` | `string` | `/__telescope` | Where the JSON API is mounted |
1141
1142
  | `ignore` | `string[]` | `[]` | URL patterns to exclude from recording |
1142
1143
  | `recordBody` | `boolean` | `true` | Record request/response bodies |
1143
1144
  | `maxEntries` | `number` | `1000` | Maximum entries per type to keep |
@@ -809,35 +809,22 @@ export async function setupEndpoints(
809
809
  const telescopeEnabled = context.telescope?.enabled;
810
810
  const telescopeWebSocketEnabled = context.telescope?.websocket;
811
811
  const usesExternalTelescope = !!context.telescope?.telescopePath;
812
- const studioEnabled = context.studio?.enabled;
813
- const usesExternalStudio = !!context.studio?.studioPath;
814
- const studioFromDatabase = !usesExternalStudio && !!context.studio?.database;
815
812
  const telescopeFromSurface = !!context.surface?.module && !usesExternalTelescope;
816
813
  let telescopeImports = "";
817
814
  if (telescopeEnabled) {
818
815
  if (telescopeFromSurface) telescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';
819
- import { createMiddleware, createUI } from '@geekmidas/telescope/hono';`;
816
+ import { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;
820
817
  else if (usesExternalTelescope) {
821
818
  const relativeTelescopePath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.telescope?.telescopePath);
822
819
  telescopeImports = `import ${context.telescope?.telescopeImportPattern} from '${relativeTelescopePath}';
823
- import { createMiddleware, createUI } from '@geekmidas/telescope/hono';`;
820
+ import { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;
824
821
  } else telescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';
825
- import { createMiddleware, createUI } from '@geekmidas/telescope/hono';`;
826
- }
827
- let studioImports = "";
828
- if (studioEnabled) {
829
- if (usesExternalStudio) {
830
- const relativeStudioPath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.studio?.studioPath);
831
- studioImports = `import ${context.studio?.studioImportPattern} from '${relativeStudioPath}';
832
- import { createStudioApp } from '@geekmidas/studio/server/hono';`;
833
- } else if (studioFromDatabase) {
834
- const dbSpecifier = importSpecifier((0, node_path.dirname)(appPath), context.studio.database.specifier);
835
- studioImports = `import { snifferContext } from '@geekmidas/constructs';
836
- import { Direction, InMemoryMonitoringStorage, Studio } from '@geekmidas/studio';
837
- import { ${context.studio.database.exportName} as __studioDb } from '${dbSpecifier}';
838
- import { createStudioApp } from '@geekmidas/studio/server/hono';`;
839
- } else studioImports = "";
822
+ import { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;
840
823
  }
824
+ const databaseApi = context.databaseApi;
825
+ const databaseApiImports = databaseApi ? `import { snifferContext } from '@geekmidas/constructs';
826
+ import { createIntrospectionHandler } from '@geekmidas/db/introspect';
827
+ import { ${databaseApi.database.exportName} as __introspectedDb } from '${importSpecifier((0, node_path.dirname)(appPath), databaseApi.database.specifier)}';` : "";
841
828
  const cors = corsFor(context.surface);
842
829
  let hooksImports = "";
843
830
  let beforeSetupCall = "";
@@ -895,9 +882,9 @@ ${telescopeWebSocketSetupCode}
895
882
  // Add telescope middleware (before endpoints to capture all requests)
896
883
  honoApp.use('*', createMiddleware(telescope));
897
884
 
898
- // Mount telescope UI
899
- const telescopeUI = createUI(telescope);
900
- honoApp.route('${context.telescope?.path}', telescopeUI);
885
+ // Mount Telescope's JSON API
886
+ const telescopeApi = createApi(telescope);
887
+ honoApp.route('${context.telescope?.path}', telescopeApi);
901
888
  `;
902
889
  else telescopeSetup = `
903
890
  // Setup Telescope for debugging/monitoring
@@ -913,32 +900,21 @@ ${telescopeWebSocketSetupCode}
913
900
  // Add telescope middleware (before endpoints to capture all requests)
914
901
  honoApp.use('*', createMiddleware(telescope));
915
902
 
916
- // Mount telescope UI
917
- const telescopeUI = createUI(telescope);
918
- honoApp.route('${context.telescope?.path}', telescopeUI);
903
+ // Mount Telescope's JSON API
904
+ const telescopeApi = createApi(telescope);
905
+ honoApp.route('${context.telescope?.path}', telescopeApi);
919
906
  `;
920
907
  }
921
- let studioSetup = "";
922
- if (studioEnabled && studioFromDatabase) studioSetup = `
923
- // Studio, built from the declared database. The client comes from the
924
- // construct, so what you inspect is by definition what the handlers write to.
925
- const studio = new Studio({
926
- monitoring: { storage: new InMemoryMonitoringStorage({ maxEntries: 100 }) },
927
- data: {
928
- db: await __studioDb.service.register({ envParser, context: snifferContext }),
929
- cursor: { field: 'id', direction: Direction.Desc },
930
- },
931
- enabled: true,
908
+ const databaseApiSetup = databaseApi ? `
909
+ // The database's structure and rows as JSON, read-only, for whatever tool
910
+ // the developer points at it. Dev only: it answers anyone who can reach the
911
+ // port.
912
+ const databaseApi = createIntrospectionHandler({
913
+ db: await __introspectedDb.service.register({ envParser, context: snifferContext }),
914
+ basePath: '${databaseApi.path}',
932
915
  });
933
-
934
- const studioApp = createStudioApp(studio);
935
- honoApp.route('${context.studio?.path}', studioApp);
936
- `;
937
- else if (studioEnabled && usesExternalStudio) studioSetup = `
938
- // Mount Studio data browser UI
939
- const studioApp = createStudioApp(studio);
940
- honoApp.route('${context.studio?.path}', studioApp);
941
- `;
916
+ honoApp.all('${databaseApi.path}/*', (c) => databaseApi(c.req.raw));
917
+ ` : "";
942
918
  const content = `/**
943
919
  * Generated server application
944
920
  *
@@ -954,7 +930,7 @@ import { setupQueues } from './queues.js';
954
930
  import { setupCrons } from './crons.js';
955
931
  ${runtime.imports}
956
932
  ${telescopeImports}
957
- ${studioImports}
933
+ ${databaseApiImports}
958
934
  ${hooksImports}
959
935
  ${cors.imports}
960
936
  ${context.storageDrivers?.imports ?? ""}
@@ -1024,7 +1000,7 @@ process.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};
1024
1000
  */
1025
1001
  export async function createApp(app?: HonoType, enableOpenApi: boolean = true): Promise<ServerApp> {
1026
1002
  const honoApp = app || new Hono();
1027
- ${telescopeSetup}${cors.setup}${beforeSetupCall}${studioSetup}
1003
+ ${telescopeSetup}${cors.setup}${beforeSetupCall}${databaseApiSetup}
1028
1004
  // Setup HTTP endpoints
1029
1005
  await setupEndpoints(honoApp, envParser, logger, enableOpenApi);
1030
1006
  ${afterSetupCall}
@@ -1808,4 +1784,4 @@ Object.defineProperty(exports, "runtimeFor", {
1808
1784
  }
1809
1785
  });
1810
1786
 
1811
- //# sourceMappingURL=OpenApiTsGenerator-WlUHjimW.cjs.map
1787
+ //# sourceMappingURL=OpenApiTsGenerator-BLRQ7Iu9.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"OpenApiTsGenerator-BLRQ7Iu9.cjs","names":["relative","ConstructGenerator","Endpoint","join","mkdir","dirname","writeFile","getRegisteredZodJsonSchemas","getSchemaMetadata","StandardSchemaJsonSchema"],"sources":["../src/build/endpoint-analyzer.ts","../src/build/handler-templates.ts","../src/generators/EndpointGenerator.ts","../src/generators/OpenApiTsGenerator.ts"],"sourcesContent":["/**\n * Endpoint Analyzer for Build-Time Feature Detection\n *\n * Analyzes endpoints at build time to determine their features and assign\n * optimization tiers. This enables generating specialized handler code\n * for maximum performance.\n */\nimport type { Endpoint } from '@geekmidas/constructs/endpoints';\n\n/**\n * Features detected from an endpoint configuration\n */\nexport interface EndpointFeatures {\n\thasAuth: boolean;\n\thasServices: boolean;\n\thasDatabase: boolean;\n\thasBodyValidation: boolean;\n\thasQueryValidation: boolean;\n\thasParamValidation: boolean;\n\thasAudits: boolean;\n\thasEvents: boolean;\n\thasRateLimit: boolean;\n\thasRls: boolean;\n\thasOutputValidation: boolean;\n}\n\n/**\n * Optimization tiers based on endpoint complexity\n *\n * - minimal: No auth, no services, no audits, no events - near-raw-Hono performance\n * - standard: Some features enabled - uses middleware composition\n * - full: Complex endpoints with many features - full handler chain\n */\nexport type EndpointTier = 'minimal' | 'standard' | 'full';\n\n/**\n * Complete analysis of an endpoint for build-time optimization\n */\nexport interface EndpointAnalysis {\n\troute: string;\n\tmethod: string;\n\texportName: string;\n\tfeatures: EndpointFeatures;\n\ttier: EndpointTier;\n\tserviceNames: string[];\n\tdatabaseServiceName?: string;\n}\n\n/**\n * Analyze an endpoint to extract its features\n */\nexport function analyzeEndpointFeatures(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany\n\t>,\n): EndpointFeatures {\n\treturn {\n\t\thasAuth: !!endpoint.authorizer,\n\t\thasServices: endpoint.services.length > 0,\n\t\thasDatabase: !!endpoint.databaseService,\n\t\thasBodyValidation: !!endpoint.input?.body,\n\t\thasQueryValidation: !!endpoint.input?.query,\n\t\thasParamValidation: !!endpoint.input?.params,\n\t\t// Only declarative audits (.audit([...])) require full tier with transaction wrapping\n\t\t// Having auditorStorageService just makes auditor available to handler (like other services)\n\t\thasAudits: (endpoint.audits?.length ?? 0) > 0,\n\t\thasEvents: (endpoint.events?.length ?? 0) > 0,\n\t\thasRateLimit: !!endpoint.rateLimit,\n\t\thasRls: !!endpoint.rlsConfig && !endpoint.rlsBypass,\n\t\thasOutputValidation: !!endpoint.outputSchema,\n\t};\n}\n\n/**\n * Determine the optimization tier for an endpoint based on its features\n */\nexport function determineEndpointTier(\n\tfeatures: EndpointFeatures,\n): EndpointTier {\n\tconst {\n\t\thasAuth,\n\t\thasServices,\n\t\thasDatabase,\n\t\thasAudits,\n\t\thasEvents,\n\t\thasRateLimit,\n\t\thasRls,\n\t} = features;\n\n\t// Minimal tier: No complex features\n\t// These endpoints can use near-raw-Hono handlers\n\tif (\n\t\t!hasAuth &&\n\t\t!hasServices &&\n\t\t!hasDatabase &&\n\t\t!hasAudits &&\n\t\t!hasEvents &&\n\t\t!hasRateLimit &&\n\t\t!hasRls\n\t) {\n\t\treturn 'minimal';\n\t}\n\n\t// Full tier: Has audits, RLS, or rate limiting (complex state management)\n\tif (hasAudits || hasRls || hasRateLimit) {\n\t\treturn 'full';\n\t}\n\n\t// Standard tier: Auth and/or services, but no complex state\n\treturn 'standard';\n}\n\n/**\n * Perform complete analysis of an endpoint\n */\nexport function analyzeEndpoint(\n\tendpoint: Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany\n\t>,\n\texportName: string,\n): EndpointAnalysis {\n\tconst features = analyzeEndpointFeatures(endpoint);\n\tconst tier = determineEndpointTier(features);\n\n\treturn {\n\t\troute: endpoint.route,\n\t\tmethod: endpoint.method,\n\t\texportName,\n\t\tfeatures,\n\t\ttier,\n\t\tserviceNames: endpoint.services.map(\n\t\t\t(s: { serviceName: string }) => s.serviceName,\n\t\t),\n\t\tdatabaseServiceName: endpoint.databaseService?.serviceName,\n\t};\n}\n\n/**\n * Analyze multiple endpoints and return analysis results\n */\nexport function analyzeEndpoints(\n\tendpoints: Array<{\n\t\tendpoint: Endpoint<\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany,\n\t\t\tany\n\t\t>;\n\t\texportName: string;\n\t}>,\n): EndpointAnalysis[] {\n\treturn endpoints.map(({ endpoint, exportName }) =>\n\t\tanalyzeEndpoint(endpoint, exportName),\n\t);\n}\n\n/**\n * Generate a summary of endpoint analysis for logging\n */\nexport function summarizeAnalysis(analyses: EndpointAnalysis[]): {\n\ttotal: number;\n\tbyTier: Record<EndpointTier, number>;\n\tbyFeature: Record<keyof EndpointFeatures, number>;\n} {\n\tconst byTier: Record<EndpointTier, number> = {\n\t\tminimal: 0,\n\t\tstandard: 0,\n\t\tfull: 0,\n\t};\n\n\tconst byFeature: Record<keyof EndpointFeatures, number> = {\n\t\thasAuth: 0,\n\t\thasServices: 0,\n\t\thasDatabase: 0,\n\t\thasBodyValidation: 0,\n\t\thasQueryValidation: 0,\n\t\thasParamValidation: 0,\n\t\thasAudits: 0,\n\t\thasEvents: 0,\n\t\thasRateLimit: 0,\n\t\thasRls: 0,\n\t\thasOutputValidation: 0,\n\t};\n\n\tfor (const analysis of analyses) {\n\t\tbyTier[analysis.tier]++;\n\n\t\tfor (const [feature, enabled] of Object.entries(analysis.features)) {\n\t\t\tif (enabled) {\n\t\t\t\tbyFeature[feature as keyof EndpointFeatures]++;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn {\n\t\ttotal: analyses.length,\n\t\tbyTier,\n\t\tbyFeature,\n\t};\n}\n","/**\n * Handler Templates for Build-Time Code Generation\n *\n * Generates optimized handler code based on endpoint tier:\n * - minimal: Near-raw-Hono performance for simple endpoints\n * - standard: Middleware composition for auth/services\n * - full: Complete handler chain for complex endpoints\n *\n * Output structure (split by tier):\n * - endpoints/validators.ts - Shared validator factories\n * - endpoints/minimal.ts - Minimal tier handlers\n * - endpoints/standard.ts - Standard tier handlers\n * - endpoints/full.ts - Full tier handlers\n * - endpoints/index.ts - Main entry point\n */\nimport type { EndpointAnalysis, EndpointFeatures } from './endpoint-analyzer';\n\n/**\n * Multi-file output structure (flat by tier)\n */\nexport interface GeneratedEndpointFiles {\n\t'validators.ts': string;\n\t'minimal.ts': string;\n\t'standard.ts': string;\n\t'full.ts': string;\n\t'index.ts': string;\n}\n\n/**\n * Nested folder structure with per-endpoint files\n *\n * Structure:\n * - endpoints/validators.ts\n * - endpoints/minimal/index.ts\n * - endpoints/minimal/[endpointName].ts\n * - endpoints/standard/index.ts\n * - endpoints/standard/[endpointName].ts\n * - endpoints/full/index.ts\n * - endpoints/full/[endpointName].ts\n * - endpoints/index.ts\n */\nexport interface GeneratedEndpointFilesNested {\n\t'validators.ts': string;\n\t'minimal/index.ts': string;\n\t'standard/index.ts': string;\n\t'full/index.ts': string;\n\t'index.ts': string;\n\t[path: string]: string; // e.g., 'minimal/healthEndpoint.ts'\n}\n\n/**\n * Endpoint import info for generating import statements\n */\nexport interface EndpointImportInfo {\n\texportName: string;\n\timportPath: string;\n}\n\n/**\n * Generate imports needed for optimized endpoints file\n */\nexport function generateOptimizedImports(analyses: EndpointAnalysis[]): string {\n\tconst needsValidator = analyses.some(\n\t\t(a) =>\n\t\t\ta.features.hasBodyValidation ||\n\t\t\ta.features.hasQueryValidation ||\n\t\t\ta.features.hasParamValidation,\n\t);\n\n\tconst needsResponseBuilder = analyses.some(\n\t\t(a) => a.tier === 'standard' || a.tier === 'full',\n\t);\n\n\tconst needsServiceDiscovery = analyses.some(\n\t\t(a) => a.features.hasServices || a.features.hasDatabase,\n\t);\n\n\tconst needsEvents = analyses.some((a) => a.features.hasEvents);\n\n\tconst needsAudits = analyses.some((a) => a.features.hasAudits);\n\n\tconst needsRateLimit = analyses.some((a) => a.features.hasRateLimit);\n\n\tconst needsRls = analyses.some((a) => a.features.hasRls);\n\n\tconst imports: string[] = [\n\t\t`import type { EnvironmentParser } from '@geekmidas/envkit';`,\n\t\t`import type { Logger } from '@geekmidas/logger';`,\n\t\t`import type { Hono } from 'hono';`,\n\t];\n\n\tif (needsValidator) {\n\t\timports.push(`import { validator } from 'hono/validator';`);\n\t}\n\n\timports.push(`import { Endpoint } from '@geekmidas/constructs/endpoints';`);\n\n\tif (needsResponseBuilder) {\n\t\timports.push(\n\t\t\t`import { ResponseBuilder } from '@geekmidas/constructs/endpoints';`,\n\t\t);\n\t}\n\n\tif (needsServiceDiscovery) {\n\t\timports.push(`import { ServiceDiscovery } from '@geekmidas/services';`);\n\t}\n\n\tif (needsEvents) {\n\t\timports.push(\n\t\t\t`import { publishConstructEvents } from '@geekmidas/constructs/endpoints';`,\n\t\t);\n\t}\n\n\tif (needsAudits) {\n\t\timports.push(\n\t\t\t`import { createAuditContext, withAuditableEndpointTransaction } from '@geekmidas/constructs/endpoints';`,\n\t\t);\n\t}\n\n\tif (needsRateLimit) {\n\t\timports.push(`import { createError } from '@geekmidas/errors';`);\n\t}\n\n\tif (needsRls) {\n\t\timports.push(\n\t\t\t`import { withRlsContext, extractRlsContext } from '@geekmidas/constructs/endpoints';`,\n\t\t);\n\t}\n\n\treturn imports.join('\\n');\n}\n\n/**\n * Generate reusable validator middleware factories\n */\nexport function generateValidatorFactories(\n\tanalyses: EndpointAnalysis[],\n): string {\n\tconst needsBody = analyses.some((a) => a.features.hasBodyValidation);\n\tconst needsQuery = analyses.some((a) => a.features.hasQueryValidation);\n\tconst needsParams = analyses.some((a) => a.features.hasParamValidation);\n\n\tif (!needsBody && !needsQuery && !needsParams) {\n\t\treturn '';\n\t}\n\n\tconst factories: string[] = [];\n\n\tif (needsBody) {\n\t\tfactories.push(`\nconst validateBody = (endpoint: any) =>\n validator('json', async (value, c) => {\n if (!endpoint.input?.body) return undefined;\n const parsed = await Endpoint.validate(endpoint.input.body, value);\n if (parsed.issues) return c.json(parsed.issues, 422);\n return parsed.value;\n });`);\n\t}\n\n\tif (needsQuery) {\n\t\tfactories.push(`\nconst validateQuery = (endpoint: any) =>\n validator('query', async (_, c) => {\n if (!endpoint.input?.query) return undefined;\n const rawQuery = Object.fromEntries(new URL(c.req.url).searchParams);\n const parsed = await Endpoint.validate(endpoint.input.query, rawQuery);\n if (parsed.issues) return c.json(parsed.issues, 422);\n return parsed.value;\n });`);\n\t}\n\n\tif (needsParams) {\n\t\tfactories.push(`\nconst validateParams = (endpoint: any) =>\n validator('param', async (params, c) => {\n if (!endpoint.input?.params) return undefined;\n const parsed = await Endpoint.validate(endpoint.input.params, params);\n if (parsed.issues) return c.json(parsed.issues, 422);\n return parsed.value;\n });`);\n\t}\n\n\treturn factories.join('\\n');\n}\n\n/**\n * Generate validator references for an endpoint\n */\nfunction generateValidators(\n\texportName: string,\n\tfeatures: EndpointFeatures,\n): string {\n\tconst validators: string[] = [];\n\n\tif (features.hasBodyValidation) {\n\t\tvalidators.push(`validateBody(${exportName})`);\n\t}\n\n\tif (features.hasQueryValidation) {\n\t\tvalidators.push(`validateQuery(${exportName})`);\n\t}\n\n\tif (features.hasParamValidation) {\n\t\tvalidators.push(`validateParams(${exportName})`);\n\t}\n\n\t// Add trailing comma if there are validators (needed before the handler function)\n\treturn validators.length > 0 ? `\\n ${validators.join(',\\n ')},` : '';\n}\n\n/**\n * Generate a minimal handler (near-raw-Hono performance)\n *\n * Used for: Health checks, public endpoints with no services\n */\nexport function generateMinimalHandler(analysis: EndpointAnalysis): string {\n\tconst { exportName, features } = analysis;\n\tconst method = analysis.method.toLowerCase();\n\n\tconst validators = generateValidators(exportName, features);\n\tconst hasValidators = validators.length > 0;\n\n\t// For truly minimal endpoints (no validation), generate inline handler\n\tif (!hasValidators && !features.hasOutputValidation) {\n\t\treturn `\n // Minimal handler: ${analysis.route} (${analysis.method})\n app.${method}('${analysis.route}', async (c) => {\n const result = await ${exportName}.handler(\n {\n services: {},\n logger,\n body: undefined,\n query: undefined,\n params: undefined,\n session: undefined,\n header: Endpoint.createHeaders(c.req.header()),\n cookie: Endpoint.createCookies(c.req.header().cookie),\n auditor: undefined,\n db: undefined,\n } as any,\n { getMetadata: () => ({}) } as any,\n );\n return c.json(result, ${exportName}.status as any);\n });`;\n\t}\n\n\t// With validation but still minimal\n\treturn `\n // Minimal handler with validation: ${analysis.route} (${analysis.method})\n app.${method}('${analysis.route}',${validators}\n async (c) => {\n const result = await ${exportName}.handler(\n {\n services: {},\n logger,\n body: ${features.hasBodyValidation ? \"(c.req.valid as any)('json')\" : 'undefined'},\n query: ${features.hasQueryValidation ? \"(c.req.valid as any)('query')\" : 'undefined'},\n params: ${features.hasParamValidation ? \"(c.req.valid as any)('param')\" : 'undefined'},\n session: undefined,\n header: Endpoint.createHeaders(c.req.header()),\n cookie: Endpoint.createCookies(c.req.header().cookie),\n auditor: undefined,\n db: undefined,\n } as any,\n { getMetadata: () => ({}) } as any,\n );\n ${\n\t\t\t\tfeatures.hasOutputValidation\n\t\t\t\t\t? `const output = await ${exportName}.parseOutput(result);\n return c.json(output, ${exportName}.status as any);`\n\t\t\t\t\t: `return c.json(result, ${exportName}.status as any);`\n\t\t\t}\n }\n );`;\n}\n\n/**\n * Generate a standard handler (auth and/or services)\n *\n * Used for: Authenticated endpoints, endpoints with services\n */\nexport function generateStandardHandler(analysis: EndpointAnalysis): string {\n\tconst { exportName, features } = analysis;\n\tconst method = analysis.method.toLowerCase();\n\n\tconst validators = generateValidators(exportName, features);\n\n\t// Build service resolution code\n\tlet serviceResolution = '';\n\tif (features.hasServices || features.hasDatabase) {\n\t\tserviceResolution = `\n const services = await serviceDiscovery.register(${exportName}.services);\n ${\n\t\t\t\tfeatures.hasDatabase\n\t\t\t\t\t? `const db = ${exportName}.databaseService\n ? (await serviceDiscovery.register([${exportName}.databaseService]) as any)[${exportName}.databaseService.serviceName]\n : undefined;`\n\t\t\t\t\t: 'const db = undefined;'\n\t\t\t}`;\n\t} else {\n\t\tserviceResolution = `\n const services = {};\n const db = undefined;`;\n\t}\n\n\t// Build auth code\n\tlet authCode = '';\n\tif (features.hasAuth) {\n\t\tauthCode = `\n // Authentication\n const session = await ${exportName}.getSession({\n services,\n logger,\n header,\n cookie,\n ...(db !== undefined && { db }),\n } as any);\n\n const isAuthorized = await ${exportName}.authorize({\n header,\n cookie,\n services,\n logger,\n session,\n } as any);\n\n if (!isAuthorized) {\n return c.json({ error: 'Unauthorized' }, 401);\n }`;\n\t}\n\n\t// Build event publishing code\n\tlet eventCode = '';\n\tif (features.hasEvents) {\n\t\teventCode = `\n // Publish events on success\n if (Endpoint.isSuccessStatus(${exportName}.status)) {\n await (publishConstructEvents as any)(\n ${exportName},\n result,\n serviceDiscovery,\n logger,\n );\n }`;\n\t}\n\n\treturn `\n // Standard handler: ${analysis.route} (${analysis.method})\n app.${method}('${analysis.route}',${validators}\n async (c) => {\n const headerValues = c.req.header();\n const header = Endpoint.createHeaders(headerValues);\n const cookie = Endpoint.createCookies(headerValues.cookie);\n${serviceResolution}\n${authCode}\n\n const responseBuilder = new ResponseBuilder();\n const result = await ${exportName}.handler(\n {\n services,\n logger,\n body: ${features.hasBodyValidation ? \"(c.req.valid as any)('json')\" : 'undefined'},\n query: ${features.hasQueryValidation ? \"(c.req.valid as any)('query')\" : 'undefined'},\n params: ${features.hasParamValidation ? \"(c.req.valid as any)('param')\" : 'undefined'},\n session: ${features.hasAuth ? 'session' : 'undefined'},\n header,\n cookie,\n auditor: undefined,\n db,\n } as any,\n responseBuilder,\n );\n\n let data = result;\n let metadata = responseBuilder.getMetadata();\n\n if (Endpoint.hasMetadata(result)) {\n data = result.data;\n metadata = result.metadata;\n }\n\n ${\n\t\t\t\tfeatures.hasOutputValidation\n\t\t\t\t\t? `const output = ${exportName}.outputSchema\n ? await ${exportName}.parseOutput(data)\n : data;`\n\t\t\t\t\t: 'const output = data;'\n\t\t\t}\n${eventCode}\n\n const status = (metadata.status ?? ${exportName}.status) as any;\n return c.json(output, status);\n }\n );`;\n}\n\n/**\n * Generate setup function that uses HonoEndpoint.addRoutes for full-featured endpoints\n * but generates optimized inline handlers for minimal/standard endpoints\n */\nexport function generateOptimizedSetupFunction(\n\tanalyses: EndpointAnalysis[],\n\t_allExportNames: string[],\n): string {\n\tconst minimalEndpoints = analyses.filter((a) => a.tier === 'minimal');\n\tconst standardEndpoints = analyses.filter((a) => a.tier === 'standard');\n\tconst fullEndpoints = analyses.filter((a) => a.tier === 'full');\n\n\t// Generate inline handlers for minimal and standard endpoints\n\tconst minimalHandlers = minimalEndpoints\n\t\t.map((a) => generateMinimalHandler(a))\n\t\t.join('\\n');\n\n\tconst standardHandlers = standardEndpoints\n\t\t.map((a) => generateStandardHandler(a))\n\t\t.join('\\n');\n\n\t// Full endpoints use HonoEndpoint.addRoutes\n\tconst fullEndpointNames = fullEndpoints.map((a) => a.exportName);\n\n\tconst fullEndpointsSetup =\n\t\tfullEndpointNames.length > 0\n\t\t\t? `\n // Full-featured endpoints use HonoEndpoint.addRoutes\n const fullEndpoints = [${fullEndpointNames.join(', ')}];\n HonoEndpoint.addRoutes(fullEndpoints, serviceDiscovery, app, openApiOptions);`\n\t\t\t: '';\n\n\t// Add HonoEndpoint import only if needed\n\tconst honoEndpointImport =\n\t\tfullEndpointNames.length > 0\n\t\t\t? `import { HonoEndpoint } from '@geekmidas/constructs/hono';`\n\t\t\t: '';\n\n\t// Only generate openApiOptions if we have full endpoints that need it\n\tconst openApiOptionsDecl =\n\t\tfullEndpointNames.length > 0\n\t\t\t? `\n const openApiOptions: any = enableOpenApi ? {\n docsPath: '/__docs',\n openApiOptions: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'Generated API documentation'\n }\n } : { docsPath: false };`\n\t\t\t: '';\n\n\treturn `${honoEndpointImport}\n\nexport async function setupEndpoints(\n app: Hono,\n envParser: EnvironmentParser<any>,\n logger: Logger,\n enableOpenApi: boolean = false,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n${openApiOptionsDecl}\n\n // ============================================\n // Minimal handlers (${minimalEndpoints.length} endpoints)\n // Near-raw-Hono performance\n // ============================================\n${minimalHandlers}\n\n // ============================================\n // Standard handlers (${standardEndpoints.length} endpoints)\n // Auth and/or services\n // ============================================\n${standardHandlers}\n${fullEndpointsSetup}\n\n // Add Swagger UI if OpenAPI is enabled\n if (enableOpenApi) {\n try {\n const { swaggerUI } = await import('@hono/swagger-ui');\n app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));\n } catch {\n // @hono/swagger-ui not installed, skip Swagger UI\n }\n }\n}`;\n}\n\n/**\n * Generate complete optimized endpoints file\n */\nexport function generateOptimizedEndpointsFile(\n\tanalyses: EndpointAnalysis[],\n\tendpointImports: string,\n\tallExportNames: string[],\n): string {\n\tconst imports = generateOptimizedImports(analyses);\n\tconst validatorFactories = generateValidatorFactories(analyses);\n\tconst setupFunction = generateOptimizedSetupFunction(\n\t\tanalyses,\n\t\tallExportNames,\n\t);\n\n\treturn `/**\n * Generated optimized endpoints file\n *\n * Build-time optimization tiers:\n * - minimal: ${analyses.filter((a) => a.tier === 'minimal').length} endpoints (near-raw-Hono)\n * - standard: ${analyses.filter((a) => a.tier === 'standard').length} endpoints (auth/services)\n * - full: ${analyses.filter((a) => a.tier === 'full').length} endpoints (audits/rls/rate-limit)\n */\n${imports}\n${endpointImports}\n${validatorFactories}\n\n${setupFunction}\n`;\n}\n\n// ============================================================================\n// Multi-File Generation (Split by Tier)\n// ============================================================================\n\n/**\n * Generate validators.ts - Shared validator middleware factories\n */\nfunction generateValidatorsFile(analyses: EndpointAnalysis[]): string {\n\tconst needsBody = analyses.some((a) => a.features.hasBodyValidation);\n\tconst needsQuery = analyses.some((a) => a.features.hasQueryValidation);\n\tconst needsParams = analyses.some((a) => a.features.hasParamValidation);\n\n\tif (!needsBody && !needsQuery && !needsParams) {\n\t\treturn `// No validators needed for this build\\nexport {};\\n`;\n\t}\n\n\tconst exports: string[] = [];\n\tconst factories: string[] = [];\n\n\tif (needsBody) {\n\t\texports.push('validateBody');\n\t\tfactories.push(`\nexport const validateBody = (endpoint: any) =>\n validator('json', async (value, c) => {\n if (!endpoint.input?.body) return undefined;\n const parsed = await Endpoint.validate(endpoint.input.body, value);\n if (parsed.issues) return c.json(parsed.issues, 422);\n return parsed.value;\n });`);\n\t}\n\n\tif (needsQuery) {\n\t\texports.push('validateQuery');\n\t\tfactories.push(`\nexport const validateQuery = (endpoint: any) =>\n validator('query', async (_, c) => {\n if (!endpoint.input?.query) return undefined;\n const rawQuery = Object.fromEntries(new URL(c.req.url).searchParams);\n const parsed = await Endpoint.validate(endpoint.input.query, rawQuery);\n if (parsed.issues) return c.json(parsed.issues, 422);\n return parsed.value;\n });`);\n\t}\n\n\tif (needsParams) {\n\t\texports.push('validateParams');\n\t\tfactories.push(`\nexport const validateParams = (endpoint: any) =>\n validator('param', async (params, c) => {\n if (!endpoint.input?.params) return undefined;\n const parsed = await Endpoint.validate(endpoint.input.params, params);\n if (parsed.issues) return c.json(parsed.issues, 422);\n return parsed.value;\n });`);\n\t}\n\n\treturn `/**\n * Generated validator middleware factories\n * Shared across all endpoint tiers that need validation\n */\nimport { validator } from 'hono/validator';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\n${factories.join('\\n')}\n`;\n}\n\n/**\n * Generate minimal.ts - Minimal tier handlers\n */\nfunction generateMinimalFile(\n\tanalyses: EndpointAnalysis[],\n\tendpointImports: EndpointImportInfo[],\n): string {\n\tconst minimalEndpoints = analyses.filter((a) => a.tier === 'minimal');\n\n\tif (minimalEndpoints.length === 0) {\n\t\treturn `// No minimal-tier endpoints in this build\nimport type { Hono } from 'hono';\nimport type { Logger } from '@geekmidas/logger';\n\nexport function setupMinimalEndpoints(\n _app: Hono,\n _logger: Logger,\n): void {\n // No minimal endpoints\n}\n`;\n\t}\n\n\tconst minimalExportNames = minimalEndpoints.map((a) => a.exportName);\n\tconst relevantImports = endpointImports.filter((i) =>\n\t\tminimalExportNames.includes(i.exportName),\n\t);\n\n\tconst importStatements = relevantImports\n\t\t.map((i) => `import { ${i.exportName} } from '${i.importPath}';`)\n\t\t.join('\\n');\n\n\tconst needsValidators = minimalEndpoints.some(\n\t\t(a) =>\n\t\t\ta.features.hasBodyValidation ||\n\t\t\ta.features.hasQueryValidation ||\n\t\t\ta.features.hasParamValidation,\n\t);\n\n\tconst validatorImport = needsValidators\n\t\t? generateValidatorImports(minimalEndpoints)\n\t\t: '';\n\n\tconst handlers = minimalEndpoints\n\t\t.map((a) => generateMinimalHandler(a))\n\t\t.join('\\n');\n\n\treturn `/**\n * Minimal-tier endpoint handlers (${minimalEndpoints.length} endpoints)\n * Near-raw-Hono performance - no auth, no services, no complex features\n */\nimport type { Hono } from 'hono';\nimport type { Logger } from '@geekmidas/logger';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\n${validatorImport}\n${importStatements}\n\nexport function setupMinimalEndpoints(\n app: Hono,\n logger: Logger,\n): void {\n${handlers}\n}\n`;\n}\n\n/**\n * Generate standard.ts - Standard tier handlers\n */\nfunction generateStandardFile(\n\tanalyses: EndpointAnalysis[],\n\tendpointImports: EndpointImportInfo[],\n): string {\n\tconst standardEndpoints = analyses.filter((a) => a.tier === 'standard');\n\n\tif (standardEndpoints.length === 0) {\n\t\treturn `// No standard-tier endpoints in this build\nimport type { Hono } from 'hono';\nimport type { Logger } from '@geekmidas/logger';\nimport type { ServiceDiscovery } from '@geekmidas/services';\n\nexport function setupStandardEndpoints(\n _app: Hono,\n _serviceDiscovery: ServiceDiscovery<any, any>,\n _logger: Logger,\n): void {\n // No standard endpoints\n}\n`;\n\t}\n\n\tconst standardExportNames = standardEndpoints.map((a) => a.exportName);\n\tconst relevantImports = endpointImports.filter((i) =>\n\t\tstandardExportNames.includes(i.exportName),\n\t);\n\n\tconst importStatements = relevantImports\n\t\t.map((i) => `import { ${i.exportName} } from '${i.importPath}';`)\n\t\t.join('\\n');\n\n\tconst needsValidators = standardEndpoints.some(\n\t\t(a) =>\n\t\t\ta.features.hasBodyValidation ||\n\t\t\ta.features.hasQueryValidation ||\n\t\t\ta.features.hasParamValidation,\n\t);\n\n\tconst validatorImport = needsValidators\n\t\t? generateValidatorImports(standardEndpoints)\n\t\t: '';\n\n\tconst needsEvents = standardEndpoints.some((a) => a.features.hasEvents);\n\tconst eventsImport = needsEvents\n\t\t? `import { publishConstructEvents } from '@geekmidas/constructs/endpoints';`\n\t\t: '';\n\n\tconst handlers = standardEndpoints\n\t\t.map((a) => generateStandardHandler(a))\n\t\t.join('\\n');\n\n\treturn `/**\n * Standard-tier endpoint handlers (${standardEndpoints.length} endpoints)\n * Auth and/or services enabled, but no complex features like audits/RLS\n */\nimport type { Hono } from 'hono';\nimport type { Logger } from '@geekmidas/logger';\nimport type { ServiceDiscovery } from '@geekmidas/services';\nimport { Endpoint, ResponseBuilder } from '@geekmidas/constructs/endpoints';\n${eventsImport}\n${validatorImport}\n${importStatements}\n\nexport function setupStandardEndpoints(\n app: Hono,\n serviceDiscovery: ServiceDiscovery<any, any>,\n logger: Logger,\n): void {\n${handlers}\n}\n`;\n}\n\n/**\n * Generate full.ts - Full tier handlers (uses HonoEndpoint.addRoutes)\n */\nfunction generateFullFile(\n\tanalyses: EndpointAnalysis[],\n\tendpointImports: EndpointImportInfo[],\n): string {\n\tconst fullEndpoints = analyses.filter((a) => a.tier === 'full');\n\n\tif (fullEndpoints.length === 0) {\n\t\treturn `// No full-tier endpoints in this build\nimport type { Hono } from 'hono';\nimport type { ServiceDiscovery } from '@geekmidas/services';\n\nexport function setupFullEndpoints(\n _app: Hono,\n _serviceDiscovery: ServiceDiscovery<any, any>,\n _enableOpenApi: boolean,\n): void {\n // No full endpoints\n}\n`;\n\t}\n\n\tconst fullExportNames = fullEndpoints.map((a) => a.exportName);\n\tconst relevantImports = endpointImports.filter((i) =>\n\t\tfullExportNames.includes(i.exportName),\n\t);\n\n\tconst importStatements = relevantImports\n\t\t.map((i) => `import { ${i.exportName} } from '${i.importPath}';`)\n\t\t.join('\\n');\n\n\treturn `/**\n * Full-tier endpoint handlers (${fullEndpoints.length} endpoints)\n * Complex features: audits, RLS, rate limiting\n * Uses HonoEndpoint.addRoutes for full feature support\n */\nimport type { Hono } from 'hono';\nimport type { ServiceDiscovery } from '@geekmidas/services';\nimport { HonoEndpoint } from '@geekmidas/constructs/hono';\n${importStatements}\n\nconst fullEndpoints = [${fullExportNames.join(', ')}];\n\nexport function setupFullEndpoints(\n app: Hono,\n serviceDiscovery: ServiceDiscovery<any, any>,\n enableOpenApi: boolean,\n): void {\n const openApiOptions: any = enableOpenApi ? {\n docsPath: '/__docs',\n openApiOptions: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'Generated API documentation'\n }\n } : { docsPath: false };\n\n HonoEndpoint.addRoutes(fullEndpoints as any, serviceDiscovery, app, openApiOptions);\n}\n`;\n}\n\n/**\n * Generate index.ts - Main entry point\n */\nfunction generateIndexFile(analyses: EndpointAnalysis[]): string {\n\tconst minimalCount = analyses.filter((a) => a.tier === 'minimal').length;\n\tconst standardCount = analyses.filter((a) => a.tier === 'standard').length;\n\tconst fullCount = analyses.filter((a) => a.tier === 'full').length;\n\n\treturn `/**\n * Generated optimized endpoints\n *\n * Build-time optimization tiers:\n * - minimal: ${minimalCount} endpoints (near-raw-Hono)\n * - standard: ${standardCount} endpoints (auth/services)\n * - full: ${fullCount} endpoints (audits/rls/rate-limit)\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport type { Hono } from 'hono';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport { setupMinimalEndpoints } from './minimal.js';\nimport { setupStandardEndpoints } from './standard.js';\nimport { setupFullEndpoints } from './full.js';\n\nexport async function setupEndpoints(\n app: Hono,\n envParser: EnvironmentParser<any>,\n logger: Logger,\n enableOpenApi: boolean = false,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n // Minimal handlers (${minimalCount} endpoints) - near-raw-Hono performance\n setupMinimalEndpoints(app, logger);\n\n // Standard handlers (${standardCount} endpoints) - auth/services\n setupStandardEndpoints(app, serviceDiscovery, logger);\n\n // Full handlers (${fullCount} endpoints) - audits/rls/rate-limit\n setupFullEndpoints(app, serviceDiscovery, enableOpenApi);\n\n // Add Swagger UI if OpenAPI is enabled\n if (enableOpenApi) {\n try {\n const { swaggerUI } = await import('@hono/swagger-ui');\n app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));\n } catch {\n // @hono/swagger-ui not installed, skip Swagger UI\n }\n }\n}\n`;\n}\n\n/**\n * Generate validator imports based on what's needed\n */\nfunction generateValidatorImports(analyses: EndpointAnalysis[]): string {\n\tconst needsBody = analyses.some((a) => a.features.hasBodyValidation);\n\tconst needsQuery = analyses.some((a) => a.features.hasQueryValidation);\n\tconst needsParams = analyses.some((a) => a.features.hasParamValidation);\n\n\tconst imports: string[] = [];\n\tif (needsBody) imports.push('validateBody');\n\tif (needsQuery) imports.push('validateQuery');\n\tif (needsParams) imports.push('validateParams');\n\n\tif (imports.length === 0) return '';\n\treturn `import { ${imports.join(', ')} } from './validators.js';`;\n}\n\n/**\n * Generate all endpoint files split by tier (flat structure)\n */\nexport function generateEndpointFilesByTier(\n\tanalyses: EndpointAnalysis[],\n\tendpointImports: EndpointImportInfo[],\n): GeneratedEndpointFiles {\n\treturn {\n\t\t'validators.ts': generateValidatorsFile(analyses),\n\t\t'minimal.ts': generateMinimalFile(analyses, endpointImports),\n\t\t'standard.ts': generateStandardFile(analyses, endpointImports),\n\t\t'full.ts': generateFullFile(analyses, endpointImports),\n\t\t'index.ts': generateIndexFile(analyses),\n\t};\n}\n\n// ============================================================================\n// Per-Endpoint File Generation (Nested Folder Structure)\n// ============================================================================\n\n/**\n * Generate a standalone minimal endpoint file\n */\nfunction generateMinimalEndpointFile(\n\tanalysis: EndpointAnalysis,\n\tendpointImport: EndpointImportInfo,\n): string {\n\tconst { exportName, features } = analysis;\n\n\tconst needsValidators =\n\t\tfeatures.hasBodyValidation ||\n\t\tfeatures.hasQueryValidation ||\n\t\tfeatures.hasParamValidation;\n\n\tconst validatorImport = needsValidators\n\t\t? generateValidatorImportsForEndpoint(analysis)\n\t\t: '';\n\n\tconst handler = generateMinimalHandler(analysis);\n\n\treturn `/**\n * Minimal endpoint: ${analysis.route} (${analysis.method})\n * Near-raw-Hono performance\n */\nimport type { Hono } from 'hono';\nimport type { Logger } from '@geekmidas/logger';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\n${validatorImport}\nimport { ${exportName} } from '${endpointImport.importPath}';\n\nexport function setup${capitalize(exportName)}(\n app: Hono,\n logger: Logger,\n): void {\n${handler}\n}\n`;\n}\n\n/**\n * Generate a standalone standard endpoint file\n */\nfunction generateStandardEndpointFile(\n\tanalysis: EndpointAnalysis,\n\tendpointImport: EndpointImportInfo,\n): string {\n\tconst { exportName, features } = analysis;\n\n\tconst needsValidators =\n\t\tfeatures.hasBodyValidation ||\n\t\tfeatures.hasQueryValidation ||\n\t\tfeatures.hasParamValidation;\n\n\tconst validatorImport = needsValidators\n\t\t? generateValidatorImportsForEndpoint(analysis)\n\t\t: '';\n\n\tconst eventsImport = features.hasEvents\n\t\t? `import { publishConstructEvents } from '@geekmidas/constructs/endpoints';`\n\t\t: '';\n\n\tconst handler = generateStandardHandler(analysis);\n\n\treturn `/**\n * Standard endpoint: ${analysis.route} (${analysis.method})\n * Auth and/or services enabled\n */\nimport type { Hono } from 'hono';\nimport type { Logger } from '@geekmidas/logger';\nimport type { ServiceDiscovery } from '@geekmidas/services';\nimport { Endpoint, ResponseBuilder } from '@geekmidas/constructs/endpoints';\n${eventsImport}\n${validatorImport}\nimport { ${exportName} } from '${endpointImport.importPath}';\n\nexport function setup${capitalize(exportName)}(\n app: Hono,\n serviceDiscovery: ServiceDiscovery<any, any>,\n logger: Logger,\n): void {\n${handler}\n}\n`;\n}\n\n/**\n * Generate a standalone full endpoint file\n */\nfunction generateFullEndpointFile(\n\tanalysis: EndpointAnalysis,\n\tendpointImport: EndpointImportInfo,\n): string {\n\tconst { exportName } = analysis;\n\n\treturn `/**\n * Full endpoint: ${analysis.route} (${analysis.method})\n * Complex features: audits, RLS, rate limiting\n */\nimport type { Hono } from 'hono';\nimport type { ServiceDiscovery } from '@geekmidas/services';\nimport { HonoEndpoint } from '@geekmidas/constructs/hono';\nimport { ${exportName} } from '${endpointImport.importPath}';\n\nexport function setup${capitalize(exportName)}(\n app: Hono,\n serviceDiscovery: ServiceDiscovery<any, any>,\n openApiOptions: any,\n): void {\n HonoEndpoint.addRoutes([${exportName}] as any, serviceDiscovery, app, openApiOptions);\n}\n`;\n}\n\n/**\n * Generate tier index file that imports and calls all endpoint setup functions\n */\nfunction generateTierIndexFile(\n\ttier: 'minimal' | 'standard' | 'full',\n\tanalyses: EndpointAnalysis[],\n): string {\n\tconst tierEndpoints = analyses.filter((a) => a.tier === tier);\n\n\tif (tierEndpoints.length === 0) {\n\t\tif (tier === 'minimal') {\n\t\t\treturn `// No minimal-tier endpoints in this build\nimport type { Hono } from 'hono';\nimport type { Logger } from '@geekmidas/logger';\n\nexport function setupMinimalEndpoints(\n _app: Hono,\n _logger: Logger,\n): void {\n // No minimal endpoints\n}\n`;\n\t\t}\n\t\tif (tier === 'standard') {\n\t\t\treturn `// No standard-tier endpoints in this build\nimport type { Hono } from 'hono';\nimport type { Logger } from '@geekmidas/logger';\nimport type { ServiceDiscovery } from '@geekmidas/services';\n\nexport function setupStandardEndpoints(\n _app: Hono,\n _serviceDiscovery: ServiceDiscovery<any, any>,\n _logger: Logger,\n): void {\n // No standard endpoints\n}\n`;\n\t\t}\n\t\t// full\n\t\treturn `// No full-tier endpoints in this build\nimport type { Hono } from 'hono';\nimport type { ServiceDiscovery } from '@geekmidas/services';\n\nexport function setupFullEndpoints(\n _app: Hono,\n _serviceDiscovery: ServiceDiscovery<any, any>,\n _enableOpenApi: boolean,\n): void {\n // No full endpoints\n}\n`;\n\t}\n\n\tconst imports = tierEndpoints\n\t\t.map(\n\t\t\t(a) =>\n\t\t\t\t`import { setup${capitalize(a.exportName)} } from './${a.exportName}.js';`,\n\t\t)\n\t\t.join('\\n');\n\n\tif (tier === 'minimal') {\n\t\tconst calls = tierEndpoints\n\t\t\t.map((a) => ` setup${capitalize(a.exportName)}(app, logger);`)\n\t\t\t.join('\\n');\n\n\t\treturn `/**\n * Minimal-tier endpoint index (${tierEndpoints.length} endpoints)\n * Near-raw-Hono performance\n */\nimport type { Hono } from 'hono';\nimport type { Logger } from '@geekmidas/logger';\n${imports}\n\nexport function setupMinimalEndpoints(\n app: Hono,\n logger: Logger,\n): void {\n${calls}\n}\n`;\n\t}\n\n\tif (tier === 'standard') {\n\t\tconst calls = tierEndpoints\n\t\t\t.map(\n\t\t\t\t(a) =>\n\t\t\t\t\t` setup${capitalize(a.exportName)}(app, serviceDiscovery, logger);`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\treturn `/**\n * Standard-tier endpoint index (${tierEndpoints.length} endpoints)\n * Auth and/or services enabled\n */\nimport type { Hono } from 'hono';\nimport type { Logger } from '@geekmidas/logger';\nimport type { ServiceDiscovery } from '@geekmidas/services';\n${imports}\n\nexport function setupStandardEndpoints(\n app: Hono,\n serviceDiscovery: ServiceDiscovery<any, any>,\n logger: Logger,\n): void {\n${calls}\n}\n`;\n\t}\n\n\t// full\n\tconst calls = tierEndpoints\n\t\t.map(\n\t\t\t(a) =>\n\t\t\t\t` setup${capitalize(a.exportName)}(app, serviceDiscovery, openApiOptions);`,\n\t\t)\n\t\t.join('\\n');\n\n\treturn `/**\n * Full-tier endpoint index (${tierEndpoints.length} endpoints)\n * Complex features: audits, RLS, rate limiting\n */\nimport type { Hono } from 'hono';\nimport type { ServiceDiscovery } from '@geekmidas/services';\n${imports}\n\nexport function setupFullEndpoints(\n app: Hono,\n serviceDiscovery: ServiceDiscovery<any, any>,\n enableOpenApi: boolean,\n): void {\n const openApiOptions: any = enableOpenApi ? {\n docsPath: '/__docs',\n openApiOptions: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'Generated API documentation'\n }\n } : { docsPath: false };\n\n${calls}\n}\n`;\n}\n\n/**\n * Generate validator imports for a single endpoint\n */\nfunction generateValidatorImportsForEndpoint(\n\tanalysis: EndpointAnalysis,\n): string {\n\tconst imports: string[] = [];\n\tif (analysis.features.hasBodyValidation) imports.push('validateBody');\n\tif (analysis.features.hasQueryValidation) imports.push('validateQuery');\n\tif (analysis.features.hasParamValidation) imports.push('validateParams');\n\n\tif (imports.length === 0) return '';\n\treturn `import { ${imports.join(', ')} } from '../validators.js';`;\n}\n\n/**\n * Capitalize first letter\n */\nfunction capitalize(str: string): string {\n\treturn str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n/**\n * Generate all endpoint files with nested folder structure (per-endpoint files)\n */\nexport function generateEndpointFilesNested(\n\tanalyses: EndpointAnalysis[],\n\tendpointImports: EndpointImportInfo[],\n): GeneratedEndpointFilesNested {\n\tconst files: GeneratedEndpointFilesNested = {\n\t\t'validators.ts': generateValidatorsFile(analyses),\n\t\t'minimal/index.ts': generateTierIndexFile('minimal', analyses),\n\t\t'standard/index.ts': generateTierIndexFile('standard', analyses),\n\t\t'full/index.ts': generateTierIndexFile('full', analyses),\n\t\t'index.ts': generateNestedIndexFile(analyses),\n\t};\n\n\t// Generate individual endpoint files\n\tfor (const analysis of analyses) {\n\t\tconst endpointImport = endpointImports.find(\n\t\t\t(i) => i.exportName === analysis.exportName,\n\t\t);\n\t\tif (!endpointImport) continue;\n\n\t\tconst fileName = `${analysis.tier}/${analysis.exportName}.ts`;\n\n\t\tswitch (analysis.tier) {\n\t\t\tcase 'minimal':\n\t\t\t\tfiles[fileName] = generateMinimalEndpointFile(analysis, endpointImport);\n\t\t\t\tbreak;\n\t\t\tcase 'standard':\n\t\t\t\tfiles[fileName] = generateStandardEndpointFile(\n\t\t\t\t\tanalysis,\n\t\t\t\t\tendpointImport,\n\t\t\t\t);\n\t\t\t\tbreak;\n\t\t\tcase 'full':\n\t\t\t\tfiles[fileName] = generateFullEndpointFile(analysis, endpointImport);\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\treturn files;\n}\n\n/**\n * Generate index.ts for nested structure\n */\nfunction generateNestedIndexFile(analyses: EndpointAnalysis[]): string {\n\tconst minimalCount = analyses.filter((a) => a.tier === 'minimal').length;\n\tconst standardCount = analyses.filter((a) => a.tier === 'standard').length;\n\tconst fullCount = analyses.filter((a) => a.tier === 'full').length;\n\n\treturn `/**\n * Generated optimized endpoints\n *\n * Build-time optimization tiers:\n * - minimal: ${minimalCount} endpoints (near-raw-Hono)\n * - standard: ${standardCount} endpoints (auth/services)\n * - full: ${fullCount} endpoints (audits/rls/rate-limit)\n */\nimport type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport type { Hono } from 'hono';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport { setupMinimalEndpoints } from './minimal/index.js';\nimport { setupStandardEndpoints } from './standard/index.js';\nimport { setupFullEndpoints } from './full/index.js';\n\nexport async function setupEndpoints(\n app: Hono,\n envParser: EnvironmentParser<any>,\n logger: Logger,\n enableOpenApi: boolean = false,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n // Minimal handlers (${minimalCount} endpoints) - near-raw-Hono performance\n setupMinimalEndpoints(app, logger);\n\n // Standard handlers (${standardCount} endpoints) - auth/services\n setupStandardEndpoints(app, serviceDiscovery, logger);\n\n // Full handlers (${fullCount} endpoints) - audits/rls/rate-limit\n setupFullEndpoints(app, serviceDiscovery, enableOpenApi);\n\n // Add Swagger UI if OpenAPI is enabled\n if (enableOpenApi) {\n try {\n const { swaggerUI } = await import('@hono/swagger-ui');\n app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));\n } catch {\n // @hono/swagger-ui not installed, skip Swagger UI\n }\n }\n}\n`;\n}\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport {\n\tanalyzeEndpoint,\n\ttype EndpointAnalysis,\n\tsummarizeAnalysis,\n} from '../build/endpoint-analyzer';\nimport {\n\ttype EndpointImportInfo,\n\tgenerateEndpointFilesNested,\n} from '../build/handler-templates';\nimport type { BuildContext } from '../build/types';\nimport type { RouteInfo } from '../types';\nimport type { StorageDrivers } from './drivers';\nimport {\n\tConstructGenerator,\n\ttype GeneratedConstruct,\n\ttype GeneratorOptions,\n} from './Generator';\n\n/**\n * How a generated entry gets its logger and environment parser.\n *\n * From the surface it serves, when there is one: the surface holds both as\n * *objects*, and discovery already recorded which module declares it, so the\n * entry imports that module and reads them off it.\n *\n * The alternative — the shape this replaces — was naming both in config as\n * module paths, `envParser: './config/env#envParser'`, and printing an import\n * for each. Two strings per app, checked by nothing, describing files the\n * surface was already holding the contents of.\n *\n * Falls back to the configured paths for an app that declares no surface.\n */\nexport function runtimeFor(\n\tcontext: BuildContext,\n\tfromDir: string,\n\t/**\n\t * The construct that owns the thing being generated.\n\t *\n\t * An endpoint's surface, or the worker that handed out the cron factory.\n\t * Omitted for the app entry itself, which belongs to the primary surface.\n\t */\n\towner?: string,\n): { imports: string; bindings: string } {\n\tconst module = owner\n\t\t? (context.owners?.[owner] ?? context.surface?.module)\n\t\t: context.surface?.module;\n\n\tif (module) {\n\t\tconst specifier = importSpecifier(fromDir, module.specifier);\n\n\t\t// Bound to the same names the rest of the entry already uses, so what\n\t\t// changes is where they come from and nothing else.\n\t\treturn {\n\t\t\timports: `import { ${module.exportName} as __surface } from '${specifier}';`,\n\t\t\tbindings: [\n\t\t\t\t'// What this construct was declared with. Objects, not module paths:',\n\t\t\t\t'// the entry imports the owner, so there is nothing to print.',\n\t\t\t\t'const envParser = __surface.envParser;',\n\t\t\t\t'const logger = __surface.logger;',\n\t\t\t].join('\\n'),\n\t\t};\n\t}\n\n\t// No fallback. Every runnable comes from a factory a `RestApi` or a `Worker`\n\t// handed out, and that construct holds the objects — so there is no longer a\n\t// case where the only thing we know about a logger is a module path somebody\n\t// typed into config.\n\tthrow new Error(\n\t\t`No owner to take a logger and an environment parser from${\n\t\t\towner ? ` for \"${owner}\"` : ''\n\t\t}. Build it from a \\`RestApi\\` or a \\`Worker\\`.`,\n\t);\n}\n\n/** A relative specifier ESM will accept: always prefixed, never bare. */\nfunction importSpecifier(fromDir: string, target: string): string {\n\tconst rel = relative(fromDir, target).replace(/\\.ts$/, '.js');\n\n\treturn rel.startsWith('.') ? rel : `./${rel}`;\n}\n\n/**\n * CORS for a surface, derived rather than hand-written.\n *\n * Who may call a surface is already in the graph — every construct that\n * declared an edge to it — and reaches the process as one comma-separated\n * value. An application that maintained this by hand maintained a list that was\n * wrong in two directions at once: it trusted origins nothing was serving, and\n * it could not name hosts a deploy had not chosen yet.\n *\n * Only the parts a graph cannot answer are configurable, and every one has a\n * default: a surface that says nothing about CORS still gets it.\n */\nexport function corsFor(surface: BuildContext['surface']): {\n\timports: string;\n\tsetup: string;\n} {\n\tif (!surface) return { imports: '', setup: '' };\n\n\tconst cors = surface.cors ?? {};\n\tconst allowHeaders = [\n\t\t'content-type',\n\t\t'authorization',\n\t\t...(cors.allowHeaders ?? []),\n\t];\n\n\treturn {\n\t\timports: `import { cors } from 'hono/cors';`,\n\t\tsetup: `\n // Who may call ${surface.id}, read off the graph rather than listed here.\n {\n const { origins } = envParser\n .create((get) => ({\n origins: get('${surface.trustedOriginsKey}')\n .string()\n .default('')\n .transform((value: string) =>\n value.split(',').map((origin) => origin.trim()).filter(Boolean),\n ),\n }))\n .parse();\n\n honoApp.use('*', cors({\n origin: origins,\n allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],\n allowHeaders: ${JSON.stringify(allowHeaders)},${\n\t\t\t\tcors.exposeHeaders\n\t\t\t\t\t? `\\n exposeHeaders: ${JSON.stringify(cors.exposeHeaders)},`\n\t\t\t\t\t: ''\n\t\t\t}\n credentials: ${cors.credentials ?? true},\n maxAge: ${cors.maxAge ?? 86400},\n }));\n }\n`,\n\t};\n}\n\nexport class EndpointGenerator extends ConstructGenerator<\n\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>,\n\tRouteInfo[]\n> {\n\tisConstruct(\n\t\tvalue: any,\n\t): value is Endpoint<\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany,\n\t\tany\n\t> {\n\t\treturn Endpoint.isEndpoint(value);\n\t}\n\n\tasync build(\n\t\tcontext: BuildContext,\n\t\tconstructs: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t\toutputDir: string,\n\t\toptions?: GeneratorOptions,\n\t): Promise<RouteInfo[]> {\n\t\tconst target = options?.target ?? 'aws';\n\t\tconst root = options?.root ?? process.cwd();\n\t\tconst enableOpenApi = options?.enableOpenApi || false;\n\t\tconst logger = console;\n\t\tconst routes: RouteInfo[] = [];\n\n\t\tif (constructs.length === 0) {\n\t\t\treturn routes;\n\t\t}\n\n\t\tif (target === 'server') {\n\t\t\t// Generate endpoints.ts and app.ts\n\t\t\tawait this.generateEndpointsFile(outputDir, constructs, context);\n\t\t\tconst appFile = await this.generateAppFile(outputDir, context);\n\n\t\t\troutes.push({\n\t\t\t\tpath: '*',\n\t\t\t\tmethod: 'ALL',\n\t\t\t\thandler: relative(root, appFile),\n\t\t\t\tauthorizer: 'none',\n\t\t\t});\n\n\t\t\tlogger.log(\n\t\t\t\t`Generated server with ${constructs.length} endpoints${enableOpenApi ? ' (OpenAPI enabled)' : ''}`,\n\t\t\t);\n\n\t\t\treturn routes;\n\t\t}\n\n\t\t// One Lambda per endpoint, behind an HTTP API.\n\t\tconst routesDir = join(outputDir, 'routes');\n\t\tawait mkdir(routesDir, { recursive: true });\n\n\t\tfor (const { key, construct, path } of constructs) {\n\t\t\tconst handlerFile = await this.generateHandlerFile(\n\t\t\t\troutesDir,\n\t\t\t\tpath.relative,\n\t\t\t\tkey,\n\t\t\t\tcontext,\n\t\t\t);\n\n\t\t\tconst routeInfo: RouteInfo = {\n\t\t\t\tpath: construct._path,\n\t\t\t\tmethod: construct.method,\n\t\t\t\thandler: relative(root, handlerFile).replace(/\\.ts$/, '.handler'),\n\t\t\t\ttimeout: construct.timeout,\n\t\t\t\tmemorySize: construct.memorySize,\n\t\t\t\tenvironment: await construct.getEnvironment({\n\t\t\t\t\tmarkOptional: context.markOptional,\n\t\t\t\t}),\n\t\t\t\tdependencies: construct.constructs,\n\t\t\t\tauthorizer: construct.authorizer?.name ?? 'none',\n\t\t\t};\n\n\t\t\troutes.push(routeInfo);\n\t\t\tlogger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);\n\t\t}\n\n\t\treturn routes;\n\t}\n\n\tprivate async generateHandlerFile(\n\t\toutputDir: string,\n\t\tsourceFile: string,\n\t\texportName: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst handlerPath = join(outputDir, `${exportName}.ts`);\n\n\t\tconst relativePath = relative(dirname(handlerPath), sourceFile);\n\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\tawait writeFile(\n\t\t\thandlerPath,\n\t\t\tthis.generateAWSApiGatewayV2Handler(\n\t\t\t\timportPath,\n\t\t\t\texportName,\n\t\t\t\tcontext.storageDrivers,\n\t\t\t),\n\t\t);\n\t\treturn handlerPath;\n\t}\n\n\tprivate async generateEndpointsFile(\n\t\toutputDir: string,\n\t\tendpoints: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst endpointsFileName = 'endpoints.ts';\n\t\tconst endpointsPath = join(outputDir, endpointsFileName);\n\n\t\t// Group imports by file\n\t\tconst importsByFile = new Map<string, string[]>();\n\n\t\tfor (const { path, key } of endpoints) {\n\t\t\tconst relativePath = relative(dirname(endpointsPath), path.relative);\n\t\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\n\t\t\tif (!importsByFile.has(importPath)) {\n\t\t\t\timportsByFile.set(importPath, []);\n\t\t\t}\n\t\t\timportsByFile.get(importPath)?.push(key);\n\t\t}\n\n\t\t// Generate import statements for endpoints\n\t\tconst endpointImports = Array.from(importsByFile.entries())\n\t\t\t.map(\n\t\t\t\t([importPath, exports]) =>\n\t\t\t\t\t`import { ${exports.join(', ')} } from '${importPath}';`,\n\t\t\t)\n\t\t\t.join('\\n');\n\n\t\tconst allExportNames = endpoints.map(({ key }) => key);\n\n\t\t// Check if we should use optimized handler generation\n\t\tif (context.production?.enabled && context.production.optimizedHandlers) {\n\t\t\treturn this.generateOptimizedEndpointsFile(\n\t\t\t\tendpointsPath,\n\t\t\t\tendpoints,\n\t\t\t\tendpointImports,\n\t\t\t\tallExportNames,\n\t\t\t);\n\t\t}\n\n\t\t// Standard generation (development or optimizedHandlers: false)\n\t\tconst content = `import type { EnvironmentParser } from '@geekmidas/envkit';\nimport type { Logger } from '@geekmidas/logger';\nimport { HonoEndpoint } from '@geekmidas/constructs/hono';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport { ServiceDiscovery } from '@geekmidas/services';\nimport type { Hono } from 'hono';\n${endpointImports}\n\nexport const endpoints: Endpoint<any, any, any, any, any, any, any, any, any, any, any, any>[] = [\n ${allExportNames.join(',\\n ')}\n];\n\nexport async function setupEndpoints(\n app: Hono,\n envParser: EnvironmentParser<any>,\n logger: Logger,\n enableOpenApi: boolean = true,\n): Promise<void> {\n const serviceDiscovery = ServiceDiscovery.getInstance(envParser);\n\n // Configure OpenAPI options based on enableOpenApi flag\n const openApiOptions: any = enableOpenApi ? {\n docsPath: '/__docs',\n openApiOptions: {\n title: 'API Documentation',\n version: '1.0.0',\n description: 'Generated API documentation'\n }\n } : { docsPath: false };\n\n HonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, openApiOptions);\n\n // Add Swagger UI if OpenAPI is enabled\n if (enableOpenApi) {\n try {\n const { swaggerUI } = await import('@hono/swagger-ui');\n app.get('/__docs/ui', swaggerUI({ url: '/__docs' }));\n } catch {\n // @hono/swagger-ui not installed, skip Swagger UI\n }\n }\n}\n`;\n\n\t\tawait writeFile(endpointsPath, content);\n\n\t\treturn endpointsPath;\n\t}\n\n\t/**\n\t * Generate optimized endpoints files with nested folder structure (per-endpoint files)\n\t */\n\tprivate async generateOptimizedEndpointsFile(\n\t\tendpointsPath: string,\n\t\tendpoints: GeneratedConstruct<\n\t\t\tEndpoint<any, any, any, any, any, any, any, any, any, any, any, any>\n\t\t>[],\n\t\t_endpointImports: string,\n\t\t_allExportNames: string[],\n\t): Promise<string> {\n\t\tconst logger = console;\n\t\tconst outputDir = dirname(endpointsPath);\n\n\t\t// Create endpoints subdirectory with tier folders\n\t\tconst endpointsDir = join(outputDir, 'endpoints');\n\t\tawait mkdir(join(endpointsDir, 'minimal'), { recursive: true });\n\t\tawait mkdir(join(endpointsDir, 'standard'), { recursive: true });\n\t\tawait mkdir(join(endpointsDir, 'full'), { recursive: true });\n\n\t\t// Analyze each endpoint\n\t\tconst analyses: EndpointAnalysis[] = endpoints.map(({ key, construct }) =>\n\t\t\tanalyzeEndpoint(construct, key),\n\t\t);\n\n\t\t// Build endpoint import info with correct relative paths from each tier folder\n\t\t// Use paths relative to the tier folder (e.g., endpoints/standard/)\n\t\tconst endpointImports: EndpointImportInfo[] = endpoints.map(\n\t\t\t({ key, path }) => {\n\t\t\t\t// Calculate relative path from tier folder (one level deeper than endpointsDir)\n\t\t\t\tconst tierDir = join(endpointsDir, 'standard'); // Use any tier as reference - same depth\n\t\t\t\tconst relativePath = relative(tierDir, path.relative);\n\t\t\t\tconst importPath = relativePath.replace(/\\.ts$/, '.js');\n\t\t\t\treturn { exportName: key, importPath };\n\t\t\t},\n\t\t);\n\n\t\t// Log analysis summary\n\t\tconst summary = summarizeAnalysis(analyses);\n\t\tlogger.log(`\\n📊 Endpoint Analysis:`);\n\t\tlogger.log(` Total: ${summary.total} endpoints`);\n\t\tlogger.log(\n\t\t\t` - Minimal (near-raw-Hono): ${summary.byTier.minimal} endpoints`,\n\t\t);\n\t\tlogger.log(\n\t\t\t` - Standard (auth/services): ${summary.byTier.standard} endpoints`,\n\t\t);\n\t\tlogger.log(\n\t\t\t` - Full (audits/rls/rate-limit): ${summary.byTier.full} endpoints`,\n\t\t);\n\n\t\t// Generate files with nested structure (per-endpoint files)\n\t\tconst files = generateEndpointFilesNested(analyses, endpointImports);\n\n\t\t// Write each file, creating directories as needed\n\t\tfor (const [filename, content] of Object.entries(files)) {\n\t\t\tconst filePath = join(endpointsDir, filename);\n\t\t\tawait mkdir(dirname(filePath), { recursive: true });\n\t\t\tawait writeFile(filePath, content);\n\t\t}\n\n\t\t// Count files by type\n\t\tconst endpointFiles = Object.keys(files).filter(\n\t\t\t(f) => !f.endsWith('index.ts') && !f.endsWith('validators.ts'),\n\t\t).length;\n\t\tconst indexFiles = Object.keys(files).filter((f) =>\n\t\t\tf.endsWith('index.ts'),\n\t\t).length;\n\n\t\tlogger.log(\n\t\t\t` Generated ${endpointFiles} endpoint files + ${indexFiles} index files + validators.ts`,\n\t\t);\n\n\t\t// Return path to index file\n\t\treturn join(endpointsDir, 'index.ts');\n\t}\n\n\tprivate async generateAppFile(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\t// Use production generator if in production mode\n\t\tif (context.production?.enabled) {\n\t\t\treturn this.generateProductionAppFile(outputDir, context);\n\t\t}\n\n\t\tconst appFileName = 'app.ts';\n\t\tconst appPath = join(outputDir, appFileName);\n\n\t\t// The logger and the env parser, from the surface that already holds them.\n\t\tconst runtime = runtimeFor(context, dirname(appPath));\n\n\t\t// Generate telescope imports and setup if enabled\n\t\tconst telescopeEnabled = context.telescope?.enabled;\n\t\tconst telescopeWebSocketEnabled = context.telescope?.websocket;\n\t\tconst usesExternalTelescope = !!context.telescope?.telescopePath;\n\n\t\t// Generate imports based on whether telescope is external or inline\n\t\tconst telescopeFromSurface =\n\t\t\t!!context.surface?.module && !usesExternalTelescope;\n\n\t\tlet telescopeImports = '';\n\t\tif (telescopeEnabled) {\n\t\t\tif (telescopeFromSurface) {\n\t\t\t\t// The entry already imports the surface, which may or may not have\n\t\t\t\t// been given a Telescope — an object, so only the running entry can\n\t\t\t\t// tell. The inline one stands in when it was not.\n\t\t\t\ttelescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t} else if (usesExternalTelescope) {\n\t\t\t\tconst relativeTelescopePath = relative(\n\t\t\t\t\tdirname(appPath),\n\t\t\t\t\tcontext.telescope?.telescopePath!,\n\t\t\t\t);\n\t\t\t\ttelescopeImports = `import ${context.telescope?.telescopeImportPattern} from '${relativeTelescopePath}';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t} else {\n\t\t\t\ttelescopeImports = `import { Telescope, InMemoryStorage } from '@geekmidas/telescope';\nimport { createApi, createMiddleware } from '@geekmidas/telescope/hono';`;\n\t\t\t}\n\t\t}\n\n\t\t// The database's read-only JSON API, from the declared database. The\n\t\t// client comes from the construct, so what it reads is by definition what\n\t\t// the handlers write to.\n\t\tconst databaseApi = context.databaseApi;\n\t\tconst databaseApiImports = databaseApi\n\t\t\t? `import { snifferContext } from '@geekmidas/constructs';\nimport { createIntrospectionHandler } from '@geekmidas/db/introspect';\nimport { ${databaseApi.database.exportName} as __introspectedDb } from '${importSpecifier(dirname(appPath), databaseApi.database.specifier)}';`\n\t\t\t: '';\n\n\t\t// Generate imports for server hooks\n\t\tconst cors = corsFor(context.surface);\n\t\tlet hooksImports = '';\n\t\tlet beforeSetupCall = '';\n\t\tlet afterSetupCall = '';\n\t\tif (context.hooks?.serverHooksPath) {\n\t\t\tconst relativeHooksPath = relative(\n\t\t\t\tdirname(appPath),\n\t\t\t\tcontext.hooks.serverHooksPath,\n\t\t\t);\n\t\t\thooksImports = `import * as serverHooks from '${relativeHooksPath}';`;\n\t\t\tbeforeSetupCall = `\n // Call beforeSetup hook if defined\n if (typeof serverHooks.beforeSetup === 'function') {\n await serverHooks.beforeSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t\tafterSetupCall = `\n // Call afterSetup hook if defined\n if (typeof serverHooks.afterSetup === 'function') {\n await serverHooks.afterSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t}\n\n\t\tconst telescopeWebSocketSetupCode = telescopeWebSocketEnabled\n\t\t\t? `\n // Setup WebSocket for real-time telescope updates\n try {\n const { createNodeWebSocket } = await import('@hono/node-ws');\n const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app: honoApp });\n // Add WebSocket route directly to main app (sub-app routes don't support WS upgrade)\n honoApp.get('${context.telescope?.path}/ws', upgradeWebSocket(() => ({\n onOpen: (_event: Event, ws: any) => {\n telescope.addWsClient(ws);\n },\n onClose: (_event: Event, ws: any) => {\n telescope.removeWsClient(ws);\n },\n onMessage: (event: MessageEvent, ws: any) => {\n try {\n const data = JSON.parse(event.data);\n if (data.type === 'ping') {\n ws.send(JSON.stringify({ type: 'pong' }));\n }\n } catch {\n // Ignore invalid messages\n }\n },\n })));\n // Store injectWebSocket for server entry to call after serve()\n (honoApp as any).__injectWebSocket = injectWebSocket;\n logger.info('Telescope WebSocket enabled');\n } catch (e) {\n logger.warn({ error: e }, 'WebSocket support not available - install @hono/node-ws for real-time updates');\n }\n`\n\t\t\t: '';\n\n\t\t// Generate telescope setup - either use external instance or create inline\n\t\tlet telescopeSetup = '';\n\t\tif (telescopeEnabled) {\n\t\t\tif (telescopeFromSurface || usesExternalTelescope) {\n\t\t\t\t// Use external telescope instance - no need to create one\n\t\t\t\ttelescopeSetup = `\n${telescopeWebSocketSetupCode}\n // Add telescope middleware (before endpoints to capture all requests)\n honoApp.use('*', createMiddleware(telescope));\n\n // Mount Telescope's JSON API\n const telescopeApi = createApi(telescope);\n honoApp.route('${context.telescope?.path}', telescopeApi);\n`;\n\t\t\t} else {\n\t\t\t\t// Create inline telescope instance\n\t\t\t\ttelescopeSetup = `\n // Setup Telescope for debugging/monitoring\n const telescopeStorage = new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} });\n const telescope = new Telescope({\n enabled: true,\n path: '${context.telescope?.path}',\n ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},\n recordBody: ${context.telescope?.recordBody},\n storage: telescopeStorage,\n });\n${telescopeWebSocketSetupCode}\n // Add telescope middleware (before endpoints to capture all requests)\n honoApp.use('*', createMiddleware(telescope));\n\n // Mount Telescope's JSON API\n const telescopeApi = createApi(telescope);\n honoApp.route('${context.telescope?.path}', telescopeApi);\n`;\n\t\t\t}\n\t\t}\n\n\t\tconst databaseApiSetup = databaseApi\n\t\t\t? `\n // The database's structure and rows as JSON, read-only, for whatever tool\n // the developer points at it. Dev only: it answers anyone who can reach the\n // port.\n const databaseApi = createIntrospectionHandler({\n db: await __introspectedDb.service.register({ envParser, context: snifferContext }),\n basePath: '${databaseApi.path}',\n });\n honoApp.all('${databaseApi.path}/*', (c) => databaseApi(c.req.raw));\n`\n\t\t\t: '';\n\n\t\tconst content = `/**\n * Generated server application\n *\n * ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY\n * The subscriber polling mechanism is not production-ready.\n * For production, use AWS Lambda with SQS/SNS event sources.\n */\nimport { Hono } from 'hono';\nimport type { Hono as HonoType } from 'hono';\nimport { setupEndpoints } from './endpoints.js';\nimport { setupSubscribers } from './subscribers.js';\nimport { setupQueues } from './queues.js';\nimport { setupCrons } from './crons.js';\n${runtime.imports}\n${telescopeImports}\n${databaseApiImports}\n${hooksImports}\n${cors.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${runtime.bindings}\n${\n\ttelescopeEnabled && telescopeFromSurface\n\t\t? `// The surface's own Telescope, or the one \\`telescope\\` config describes.\nconst telescope =\n __surface.telescope ??\n new Telescope({\n enabled: true,\n path: '${context.telescope?.path}',\n ignorePatterns: ${JSON.stringify(context.telescope?.ignore)},\n recordBody: ${context.telescope?.recordBody},\n storage: new InMemoryStorage({ maxEntries: ${context.telescope?.maxEntries} }),\n });`\n\t\t: ''\n}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// Which storage drivers exist is the entry point's decision: the scheme in\n// each injected URL picks one, so no construct and no application module names\n// a provider.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n${\n\tcontext.surface\n\t\t? `// Who this server is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};\n\n`\n\t\t: ''\n}export interface ServerApp {\n app: HonoType;\n start: (options?: {\n port?: number;\n /** Returns the server, so a shutdown can stop it taking requests. */\n serve: (app: HonoType, port: number) => unknown;\n }) => Promise<void>;\n}\n\n/**\n * Create and configure the Hono application\n *\n * @param app - Optional Hono app instance to configure (creates new one if not provided)\n * @param enableOpenApi - Enable OpenAPI documentation (default: true)\n * @returns Server app with configured Hono app and start function\n *\n * @example\n * // With Bun\n * import { createApp } from './.gkm/server/app.js';\n *\n * const { app, start } = await createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * Bun.serve({ port, fetch: app.fetch });\n * }\n * });\n *\n * @example\n * // With Node.js (using @hono/node-server)\n * import { serve } from '@hono/node-server';\n * import { createApp } from './.gkm/server/app.js';\n *\n * const { app, start } = await createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * serve({ fetch: app.fetch, port });\n * }\n * });\n */\nexport async function createApp(app?: HonoType, enableOpenApi: boolean = true): Promise<ServerApp> {\n const honoApp = app || new Hono();\n${telescopeSetup}${cors.setup}${beforeSetupCall}${databaseApiSetup}\n // Setup HTTP endpoints\n await setupEndpoints(honoApp, envParser, logger, enableOpenApi);\n${afterSetupCall}\n\n return {\n app: honoApp,\n async start(options) {\n if (!options?.serve) {\n throw new Error(\n 'serve function is required. Pass a serve function for your runtime:\\\\n' +\n ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\\\n' +\n ' - Node: (app, port) => serve({ fetch: app.fetch, port })'\n );\n }\n\n const port = options.port ?? 3000;\n\n // Mount pushed subscribers' routes and start polled ones. What comes\n // back subscribes the routes, once the server can answer them.\n const subscribeForPush = await setupSubscribers(honoApp, envParser, logger).catch((error) => {\n logger.error({ error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n\n // Start queue workers in background (non-blocking, local development only)\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ error }, 'Failed to start queue workers');\n });\n\n // Schedule this app's crons. Caught like the others: a scheduler that\n // cannot start is not a reason for the HTTP server not to.\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ error }, 'Failed to schedule crons');\n });\n\n logger.info({ port }, 'Starting server');\n\n // Start HTTP server using provided serve function\n await options.serve(honoApp, port);\n\n logger.info({ port }, 'Server started');\n\n await subscribeForPush(port);\n }\n };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n\t\tawait writeFile(appPath, content);\n\n\t\treturn appPath;\n\t}\n\n\t/**\n\t * One Lambda, one endpoint — and no environment import.\n\t *\n\t * The endpoint was built from its surface, so it carries the parser the\n\t * adaptor needs. This used to read\n\t * `import { envParser } from '../../config/env'`, a line the build wrote\n\t * because a generator can print a module specifier and cannot print an\n\t * object. Nothing has to be printed now, which is also why nothing has to be\n\t * named in config.\n\t */\n\tprivate generateAWSApiGatewayV2Handler(\n\t\timportPath: string,\n\t\texportName: string,\n\t\tdrivers?: StorageDrivers,\n\t): string {\n\t\treturn `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\n${drivers?.imports ?? ''}\n${drivers?.setup ? `\\n// The handler registers the drivers its target needs.\\n${drivers.setup}\\n` : ''}\nconst adapter = new AmazonApiGatewayV2Endpoint(${exportName});\n\nexport const handler = adapter.handler;\n`;\n\t}\n\n\t/**\n\t * Generate a production-optimized app.ts file\n\t * No dev tools (Telescope, Studio, WebSocket), includes health checks and graceful shutdown\n\t */\n\tprivate async generateProductionAppFile(\n\t\toutputDir: string,\n\t\tcontext: BuildContext,\n\t): Promise<string> {\n\t\tconst appFileName = 'app.ts';\n\t\tconst appPath = join(outputDir, appFileName);\n\n\t\t// The app entry belongs to the primary surface, so no owner is named.\n\t\tconst runtime = runtimeFor(context, dirname(appPath));\n\n\t\tconst production = context.production!;\n\t\tconst healthCheckPath = production.healthCheck;\n\t\tconst enableGracefulShutdown = production.gracefulShutdown;\n\t\tconst enableOpenApi = production.openapi;\n\t\tconst includeSubscribers = production.subscribers === 'include';\n\n\t\t// Generate imports for server hooks\n\t\tconst cors = corsFor(context.surface);\n\t\tlet hooksImports = '';\n\t\tlet beforeSetupCall = '';\n\t\tlet afterSetupCall = '';\n\t\tif (context.hooks?.serverHooksPath) {\n\t\t\tconst relativeHooksPath = relative(\n\t\t\t\tdirname(appPath),\n\t\t\t\tcontext.hooks.serverHooksPath,\n\t\t\t);\n\t\t\thooksImports = `import * as serverHooks from '${relativeHooksPath}';`;\n\t\t\tbeforeSetupCall = `\n // Call beforeSetup hook if defined\n if (typeof serverHooks.beforeSetup === 'function') {\n await serverHooks.beforeSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t\tafterSetupCall = `\n // Call afterSetup hook if defined\n if (typeof serverHooks.afterSetup === 'function') {\n await serverHooks.afterSetup(honoApp, { envParser, logger });\n }\n`;\n\t\t}\n\n\t\t// Subscriber + queue setup code (background workers share the same flag)\n\t\tconst subscriberSetup = includeSubscribers\n\t\t\t? `\n // Mount pushed subscribers' routes and start polled ones. What comes\n // back subscribes the routes, once the server can answer them.\n const subscribeForPush = await setupSubscribers(honoApp, envParser, logger).catch((error) => {\n logger.error({ error }, 'Failed to start subscribers');\n return async (_port: number) => {};\n });\n\n // Start queue workers in background\n await setupQueues(envParser, logger).catch((error) => {\n logger.error({ error }, 'Failed to start queue workers');\n });\n\n // Schedule this app's crons. Caught like the others: a scheduler that\n // cannot start is not a reason for the HTTP server not to.\n await setupCrons(envParser, logger).catch((error) => {\n logger.error({ error }, 'Failed to schedule crons');\n });\n`\n\t\t\t: '';\n\n\t\tconst subscriberImport = includeSubscribers\n\t\t\t? `import { setupSubscribers } from './subscribers.js';\nimport { setupQueues } from './queues.js';\nimport { setupCrons } from './crons.js';`\n\t\t\t: '';\n\n\t\t// Graceful shutdown code\n\t\tconst gracefulShutdownCode = enableGracefulShutdown\n\t\t\t? `\n // Graceful shutdown: stop taking requests, let in-flight ones finish, then\n // close what constructs opened (database pools) — so a rolling deploy does\n // not leave the old task holding connections. Bounded by\n // GKM_SHUTDOWN_TIMEOUT_MS, 8s by default: under Docker's 10s stop timeout,\n // so the process exits on its own terms rather than being killed mid-drain.\n let isShuttingDown = false;\n\n const shutdown = async () => {\n if (isShuttingDown) return;\n isShuttingDown = true;\n const deadline = Number(process.env.GKM_SHUTDOWN_TIMEOUT_MS) || 8000;\n logger.info({ deadline }, 'Graceful shutdown initiated');\n setTimeout(() => {\n logger.warn({ deadline }, 'Shutdown deadline reached, exiting');\n process.exit(1);\n }, deadline).unref();\n await new Promise<void>((resolve) => {\n const close = (server as { close?: (done: () => void) => void } | undefined)?.close;\n if (typeof close === 'function') close.call(server, () => resolve());\n else resolve();\n });\n await runShutdownHooks((error) => logger.error({ error }, 'Shutdown hook failed'));\n process.exit(0);\n };\n\n process.on('SIGTERM', shutdown);\n process.on('SIGINT', shutdown);\n`\n\t\t\t: '';\n\n\t\t// Use endpoints/index.js for optimized builds, endpoints.js otherwise\n\t\tconst endpointsImportPath = production.optimizedHandlers\n\t\t\t? './endpoints/index.js'\n\t\t\t: './endpoints.js';\n\n\t\tconst content = `/**\n * Generated production server application\n *\n * This is a production-optimized build without dev tools.\n * - No Telescope debugging dashboard\n * - No Studio database browser\n * - No WebSocket updates\n * - Includes health checks and graceful shutdown\n */\nimport { Hono } from 'hono';\nimport type { Hono as HonoType } from 'hono';\n${enableGracefulShutdown ? \"import { runShutdownHooks } from '@geekmidas/constructs';\\n\" : ''}import { setupEndpoints } from '${endpointsImportPath}';\n${subscriberImport}\n${runtime.imports}\n${runtime.bindings}\n${hooksImports}\n${cors.imports}\n${context.storageDrivers?.imports ?? ''}\n\n${\n\tcontext.storageDrivers?.setup\n\t\t? `// The entry point registers the drivers its target needs.\n${context.storageDrivers.setup}\n`\n\t\t: ''\n}\n${\n\tcontext.surface\n\t\t? `// Who this server is to Postgres: application_name on every connection.\nprocess.env.GKM_APP_NAME ??= ${JSON.stringify(context.surface.id)};\n\n`\n\t\t: ''\n}export interface ServerApp {\n app: HonoType;\n start: (options?: {\n port?: number;\n serve: (app: HonoType, port: number) => void | Promise<void>;\n }) => Promise<void>;\n}\n\n/**\n * Create and configure the production Hono application\n */\nexport async function createApp(app?: HonoType): Promise<ServerApp> {\n const honoApp = app || new Hono();\n\n // Health check endpoint (always first)\n honoApp.get('${healthCheckPath}', (c) => c.json({ status: 'ok', timestamp: Date.now() }));\n honoApp.get('/ready', (c) => c.json({ ready: true }));\n${cors.setup}${beforeSetupCall}\n // Setup HTTP endpoints (OpenAPI: ${enableOpenApi})\n await setupEndpoints(honoApp, envParser, logger, ${enableOpenApi});\n${afterSetupCall}\n return {\n app: honoApp,\n async start(options) {\n if (!options?.serve) {\n throw new Error(\n 'serve function is required. Pass a serve function for your runtime:\\\\n' +\n ' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\\\n' +\n ' - Node: (app, port) => serve({ fetch: app.fetch, port })'\n );\n }\n\n const port = options.port ?? Number(process.env.PORT) ?? 3000;\n let server: unknown;\n${gracefulShutdownCode}${subscriberSetup}\n logger.info({ port }, 'Starting production server');\n\n // Start HTTP server using provided serve function\n server = await options.serve(honoApp, port);\n\n logger.info({ port }, 'Production server started');\n${includeSubscribers ? '\\n await subscribeForPush(port);' : ''}\n }\n };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n\t\tawait writeFile(appPath, content);\n\n\t\t// Also generate the production server entry point\n\t\tawait this.generateProductionServerEntry(outputDir);\n\n\t\treturn appPath;\n\t}\n\n\t/**\n\t * Generate production server.ts entry point\n\t */\n\tprivate async generateProductionServerEntry(\n\t\toutputDir: string,\n\t): Promise<void> {\n\t\tconst serverPath = join(outputDir, 'server.ts');\n\n\t\tconst content = `#!/usr/bin/env node\n/**\n * Production server entry point\n * Generated by 'gkm build --production'\n */\nimport { serve } from '@hono/node-server';\nimport { createApp } from './app.js';\n\nconst port = Number(process.env.PORT) || 3000;\n\nconst { start } = await createApp();\n\nawait start({\n port,\n serve: (app, port) => serve({ fetch: app.fetch, port }),\n});\n`;\n\n\t\tawait writeFile(serverPath, content);\n\t}\n}\n","import type { Endpoint } from '@geekmidas/constructs/endpoints';\nimport {\n\tgetRegisteredZodJsonSchemas,\n\tgetSchemaMetadata,\n\tStandardSchemaJsonSchema,\n} from '@geekmidas/schema/conversion';\nimport type { StandardSchemaV1 } from '@standard-schema/spec';\n\ninterface OpenApiTsOptions {\n\ttitle?: string;\n\tversion?: string;\n\tdescription?: string;\n}\n\n// JSON Schema type definition\ninterface JsonSchema {\n\t// An array since Zod 4.6, which writes a union of primitives — a nullable\n\t// string among them — as `type: ['string', 'null']` rather than `anyOf`.\n\ttype?: string | string[];\n\t/** A literal — `z.literal('open')` is `{ type: 'string', const: 'open' }`. */\n\tconst?: unknown;\n\tproperties?: Record<string, JsonSchema>;\n\titems?: JsonSchema;\n\trequired?: string[];\n\tenum?: string[];\n\t$ref?: string;\n\tanyOf?: JsonSchema[];\n\toneOf?: JsonSchema[];\n\tallOf?: JsonSchema[];\n\tadditionalProperties?: boolean | JsonSchema;\n\t[key: string]: unknown;\n}\n\n// Security scheme type (OpenAPI 3.1)\ninterface SecuritySchemeObject {\n\ttype: 'apiKey' | 'http' | 'mutualTLS' | 'oauth2' | 'openIdConnect';\n\tdescription?: string;\n\tname?: string;\n\tin?: 'query' | 'header' | 'cookie';\n\tscheme?: string;\n\tbearerFormat?: string;\n\tflows?: Record<string, unknown>;\n\topenIdConnectUrl?: string;\n\t[key: string]: unknown;\n}\n\ninterface EndpointInfo {\n\tendpoint: string;\n\troute: string;\n\tmethod: string;\n\tauthorizerName: string | null;\n\t/** @deprecated Use securityScheme instead */\n\tauthorizerType: string | null;\n\t/** The OpenAPI security scheme definition for this endpoint's authorizer */\n\tsecurityScheme: SecuritySchemeObject | null;\n\tinput?: {\n\t\tbody?: StandardSchemaV1;\n\t\tquery?: StandardSchemaV1;\n\t\tparams?: StandardSchemaV1;\n\t};\n\toutput?: StandardSchemaV1;\n\tdescription?: string;\n\ttags?: string[];\n\toperationId?: string;\n\tresponseType: string;\n}\n\ninterface SecuritySchemeInfo {\n\tname: string;\n\ttype: string;\n\tscheme: SecuritySchemeObject;\n}\n\n/**\n * Generates TypeScript OpenAPI module from endpoints.\n * Outputs:\n * - securitySchemes: typed security scheme definitions\n * - endpointAuth: runtime map of endpoints to auth requirements\n * - paths: TypeScript interface for type-safe fetcher\n * - schema interfaces: reusable TypeScript types from Zod/Valibot schemas\n */\nexport class OpenApiTsGenerator {\n\tasync generate(\n\t\tendpoints: Endpoint<any, any, any, any, any, any>[],\n\t\toptions: OpenApiTsOptions = {},\n\t): Promise<string> {\n\t\tconst { title = 'API', version = '1.0.0', description } = options;\n\n\t\t// Extract endpoint info\n\t\tconst endpointInfos = await this.extractEndpointInfos(endpoints);\n\n\t\t// Collect unique security schemes\n\t\tconst securitySchemes = this.collectSecuritySchemes(endpointInfos);\n\n\t\t// Build endpoint auth map\n\t\tconst endpointAuth = this.buildEndpointAuthMap(endpointInfos);\n\n\t\t// Generate schema interfaces\n\t\tconst schemaInterfaces = await this.generateSchemaInterfaces(endpointInfos);\n\n\t\t// Generate paths interface\n\t\tconst pathsInterface = await this.generatePathsInterface(endpointInfos);\n\n\t\t// Build the final TypeScript module\n\t\treturn this.buildModule({\n\t\t\ttitle,\n\t\t\tversion,\n\t\t\tdescription,\n\t\t\tsecuritySchemes,\n\t\t\tendpointAuth,\n\t\t\tschemaInterfaces,\n\t\t\tpathsInterface,\n\t\t});\n\t}\n\n\tprivate async extractEndpointInfos(\n\t\tendpoints: Endpoint<any, any, any, any, any, any>[],\n\t): Promise<EndpointInfo[]> {\n\t\treturn endpoints.map((ep) => {\n\t\t\tconst route = ep.route.replace(/:(\\w+)/g, '{$1}');\n\t\t\tconst method = ep.method.toUpperCase();\n\n\t\t\t// Get security scheme from authorizer (if available)\n\t\t\t// This is the preferred way - the scheme is stored directly on the authorizer\n\t\t\tconst securityScheme = ep.authorizer?.securityScheme as\n\t\t\t\t| SecuritySchemeObject\n\t\t\t\t| undefined;\n\n\t\t\treturn {\n\t\t\t\tendpoint: `${method} ${route}`,\n\t\t\t\troute,\n\t\t\t\tmethod,\n\t\t\t\tauthorizerName: ep.authorizer?.name ?? null,\n\t\t\t\tauthorizerType: ep.authorizer?.type ?? null,\n\t\t\t\tsecurityScheme: securityScheme ?? null,\n\t\t\t\tinput: ep.input,\n\t\t\t\toutput: ep.outputSchema,\n\t\t\t\tdescription: ep.description,\n\t\t\t\ttags: ep.tags,\n\t\t\t\toperationId: ep.operationId,\n\t\t\t\tresponseType: ep.responseType ?? 'application/json',\n\t\t\t};\n\t\t});\n\t}\n\n\tprivate collectSecuritySchemes(\n\t\tendpointInfos: EndpointInfo[],\n\t): SecuritySchemeInfo[] {\n\t\tconst schemes = new Map<string, SecuritySchemeInfo>();\n\n\t\tfor (const info of endpointInfos) {\n\t\t\tif (info.authorizerName && !schemes.has(info.authorizerName)) {\n\t\t\t\t// Prefer the stored security scheme (from .securitySchemes() or built-ins)\n\t\t\t\t// Fall back to inference from authorizerType for backward compatibility\n\t\t\t\tconst scheme =\n\t\t\t\t\tinfo.securityScheme ??\n\t\t\t\t\t(info.authorizerType\n\t\t\t\t\t\t? this.mapAuthorizerToSecurityScheme(\n\t\t\t\t\t\t\t\tinfo.authorizerType,\n\t\t\t\t\t\t\t\tinfo.authorizerName,\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t: null);\n\n\t\t\t\tif (scheme) {\n\t\t\t\t\tschemes.set(info.authorizerName, {\n\t\t\t\t\t\tname: info.authorizerName,\n\t\t\t\t\t\ttype: scheme.type,\n\t\t\t\t\t\tscheme,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn Array.from(schemes.values());\n\t}\n\n\tprivate mapAuthorizerToSecurityScheme(\n\t\ttype: string,\n\t\t_name: string,\n\t): SecuritySchemeObject {\n\t\tswitch (type.toLowerCase()) {\n\t\t\tcase 'jwt':\n\t\t\tcase 'bearer':\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'http',\n\t\t\t\t\tscheme: 'bearer',\n\t\t\t\t\tbearerFormat: 'JWT',\n\t\t\t\t};\n\t\t\tcase 'iam':\n\t\t\tcase 'aws-sigv4':\n\t\t\tcase 'sigv4':\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'apiKey',\n\t\t\t\t\tin: 'header',\n\t\t\t\t\tname: 'Authorization',\n\t\t\t\t\t'x-amazon-apigateway-authtype': 'awsSigv4',\n\t\t\t\t};\n\t\t\tcase 'apikey':\n\t\t\tcase 'api-key':\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'apiKey',\n\t\t\t\t\tin: 'header',\n\t\t\t\t\tname: 'X-API-Key',\n\t\t\t\t};\n\t\t\tcase 'oauth2':\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'oauth2',\n\t\t\t\t\tflows: {},\n\t\t\t\t};\n\t\t\tcase 'oidc':\n\t\t\tcase 'openidconnect':\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'openIdConnect',\n\t\t\t\t\topenIdConnectUrl: '',\n\t\t\t\t};\n\t\t\tdefault:\n\t\t\t\treturn {\n\t\t\t\t\ttype: 'http',\n\t\t\t\t\tscheme: 'bearer',\n\t\t\t\t};\n\t\t}\n\t}\n\n\tprivate buildEndpointAuthMap(\n\t\tendpointInfos: EndpointInfo[],\n\t): Record<string, string | null> {\n\t\tconst authMap: Record<string, string | null> = {};\n\n\t\tfor (const info of endpointInfos) {\n\t\t\tauthMap[info.endpoint] = info.authorizerName;\n\t\t}\n\n\t\treturn authMap;\n\t}\n\n\tprivate async generateSchemaInterfaces(\n\t\tendpointInfos: EndpointInfo[],\n\t): Promise<string> {\n\t\tconst interfaces: string[] = [];\n\t\tconst generatedNames = new Set<string>();\n\t\t// Collect nested schemas with $defs (from .meta({ id: 'X' }))\n\t\tconst collectedDefs = new Map<string, JsonSchema>();\n\n\t\tfor (const info of endpointInfos) {\n\t\t\tconst baseName = this.getSchemaBaseName(info);\n\n\t\t\t// Input body schema\n\t\t\tif (info.input?.body) {\n\t\t\t\tconst name = await this.getSchemaName(\n\t\t\t\t\tinfo.input.body,\n\t\t\t\t\t`${baseName}Input`,\n\t\t\t\t);\n\t\t\t\tif (!generatedNames.has(name)) {\n\t\t\t\t\tconst schema = await this.schemaToInterfaceWithDefs(\n\t\t\t\t\t\tinfo.input.body,\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tcollectedDefs,\n\t\t\t\t\t);\n\t\t\t\t\tif (schema) {\n\t\t\t\t\t\tinterfaces.push(schema);\n\t\t\t\t\t\tgeneratedNames.add(name);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Input params schema\n\t\t\tif (info.input?.params) {\n\t\t\t\tconst name = await this.getSchemaName(\n\t\t\t\t\tinfo.input.params,\n\t\t\t\t\t`${baseName}Params`,\n\t\t\t\t);\n\t\t\t\tif (!generatedNames.has(name)) {\n\t\t\t\t\tconst schema = await this.schemaToInterfaceWithDefs(\n\t\t\t\t\t\tinfo.input.params,\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tcollectedDefs,\n\t\t\t\t\t);\n\t\t\t\t\tif (schema) {\n\t\t\t\t\t\tinterfaces.push(schema);\n\t\t\t\t\t\tgeneratedNames.add(name);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Input query schema\n\t\t\tif (info.input?.query) {\n\t\t\t\tconst name = await this.getSchemaName(\n\t\t\t\t\tinfo.input.query,\n\t\t\t\t\t`${baseName}Query`,\n\t\t\t\t);\n\t\t\t\tif (!generatedNames.has(name)) {\n\t\t\t\t\tconst schema = await this.schemaToInterfaceWithDefs(\n\t\t\t\t\t\tinfo.input.query,\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tcollectedDefs,\n\t\t\t\t\t);\n\t\t\t\t\tif (schema) {\n\t\t\t\t\t\tinterfaces.push(schema);\n\t\t\t\t\t\tgeneratedNames.add(name);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Output schema\n\t\t\tif (info.output) {\n\t\t\t\tconst name = await this.getSchemaName(info.output, `${baseName}Output`);\n\t\t\t\tif (!generatedNames.has(name)) {\n\t\t\t\t\tconst schema = await this.schemaToInterfaceWithDefs(\n\t\t\t\t\t\tinfo.output,\n\t\t\t\t\t\tname,\n\t\t\t\t\t\tcollectedDefs,\n\t\t\t\t\t);\n\t\t\t\t\tif (schema) {\n\t\t\t\t\t\tinterfaces.push(schema);\n\t\t\t\t\t\tgeneratedNames.add(name);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Pull in every schema registered via `.meta({ id })` in zod's global\n\t\t// registry, even when no endpoint references it directly. This makes\n\t\t// derived schemas like `UserSchema.pick(...)` discoverable through the\n\t\t// named parent type without requiring the parent to be wired into an\n\t\t// endpoint.\n\t\tconst registrySchemas = await getRegisteredZodJsonSchemas();\n\t\tfor (const [rawName, rawSchema] of Object.entries(registrySchemas)) {\n\t\t\tconst defName = this.pascalCase(rawName);\n\t\t\tif (collectedDefs.has(defName) || generatedNames.has(defName)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst {\n\t\t\t\tid: _id,\n\t\t\t\t$defs: _defs,\n\t\t\t\t...rest\n\t\t\t} = rawSchema as JsonSchema & {\n\t\t\t\tid?: string;\n\t\t\t};\n\t\t\tcollectedDefs.set(defName, rest as JsonSchema);\n\t\t}\n\n\t\t// Generate interfaces for collected $defs (nested schemas with .meta({ id: 'X' }))\n\t\tfor (const [defName, defSchema] of collectedDefs) {\n\t\t\tif (!generatedNames.has(defName)) {\n\t\t\t\tconst interfaceStr = this.jsonSchemaToInterface(defSchema, defName);\n\t\t\t\tinterfaces.push(interfaceStr);\n\t\t\t\tgeneratedNames.add(defName);\n\t\t\t}\n\t\t}\n\n\t\treturn interfaces.join('\\n\\n');\n\t}\n\n\t/**\n\t * Get the name for a schema, using metadata `id` if available,\n\t * otherwise falling back to the provided default name.\n\t */\n\tprivate async getSchemaName(\n\t\tschema: StandardSchemaV1,\n\t\tdefaultName: string,\n\t): Promise<string> {\n\t\ttry {\n\t\t\tconst metadata = await getSchemaMetadata(schema);\n\t\t\tif (metadata?.id) {\n\t\t\t\treturn this.pascalCase(metadata.id);\n\t\t\t}\n\t\t} catch {\n\t\t\t// Ignore metadata extraction errors\n\t\t}\n\t\treturn defaultName;\n\t}\n\n\tprivate getSchemaBaseName(info: EndpointInfo): string {\n\t\tif (info.operationId) {\n\t\t\treturn this.pascalCase(info.operationId);\n\t\t}\n\n\t\t// Generate name from method + route\n\t\tconst routeParts = info.route\n\t\t\t.replace(/[{}]/g, '')\n\t\t\t.split('/')\n\t\t\t.filter(Boolean)\n\t\t\t.map((part) => this.pascalCase(part));\n\n\t\treturn `${this.pascalCase(info.method.toLowerCase())}${routeParts.join('')}`;\n\t}\n\n\tprivate pascalCase(str: string): string {\n\t\treturn str\n\t\t\t.replace(/[-_](.)/g, (_, c) => c.toUpperCase())\n\t\t\t.replace(/^./, (c) => c.toUpperCase());\n\t}\n\n\t/**\n\t * Convert schema to interface while collecting $defs for nested schemas\n\t * with .meta({ id: 'X' }).\n\t */\n\tprivate async schemaToInterfaceWithDefs(\n\t\tschema: StandardSchemaV1,\n\t\tname: string,\n\t\tcollectedDefs: Map<string, JsonSchema>,\n\t): Promise<string | null> {\n\t\ttry {\n\t\t\t// Get raw JSON schema with $defs intact (don't use convertStandardSchemaToJsonSchema\n\t\t\t// which strips $defs)\n\t\t\tconst vendor = schema['~standard']?.vendor;\n\t\t\tif (!vendor || !(vendor in StandardSchemaJsonSchema)) {\n\t\t\t\treturn unknownType(name);\n\t\t\t}\n\n\t\t\tconst toJsonSchema =\n\t\t\t\tStandardSchemaJsonSchema[\n\t\t\t\t\tvendor as keyof typeof StandardSchemaJsonSchema\n\t\t\t\t];\n\t\t\tconst jsonSchema = await toJsonSchema(schema);\n\t\t\tif (!jsonSchema) return unknownType(name);\n\n\t\t\t// Extract $defs from the JSON schema (these come from .meta({ id: 'X' }))\n\t\t\tif (jsonSchema.$defs && typeof jsonSchema.$defs === 'object') {\n\t\t\t\tfor (const [defName, defSchema] of Object.entries(jsonSchema.$defs)) {\n\t\t\t\t\tif (!collectedDefs.has(defName)) {\n\t\t\t\t\t\t// Remove the 'id' field from the schema as it's just metadata\n\t\t\t\t\t\tconst { id, ...schemaWithoutId } = defSchema as JsonSchema & {\n\t\t\t\t\t\t\tid?: string;\n\t\t\t\t\t\t};\n\t\t\t\t\t\tcollectedDefs.set(defName, schemaWithoutId as JsonSchema);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Remove $defs from the schema before converting to interface\n\t\t\tconst { $defs, ...schemaWithoutDefs } = jsonSchema;\n\n\t\t\t// A schema that *is* a registered schema converts to nothing but a\n\t\t\t// `$ref` at it, and the def it points at has already been collected\n\t\t\t// above — so emitting a declaration here as well produces\n\t\t\t// `export type User = User`, a circular alias that is not a type.\n\t\t\t//\n\t\t\t// Zod used to inline this case and only started emitting the `$ref` in\n\t\t\t// 4.6, which is how the bug arrived without the generator changing.\n\t\t\tconst ref = (schemaWithoutDefs as { $ref?: string }).$ref;\n\t\t\tif (\n\t\t\t\tref &&\n\t\t\t\tObject.keys(schemaWithoutDefs).every(\n\t\t\t\t\t(k) => k === '$ref' || k === '$schema',\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tconst target = ref.split('/').pop();\n\t\t\t\t// The def's own interface is the declaration. Only alias it when the\n\t\t\t\t// names actually differ, which is when the alias says something.\n\t\t\t\treturn target === name ? null : `export type ${name} = ${target};`;\n\t\t\t}\n\n\t\t\treturn this.jsonSchemaToInterface(schemaWithoutDefs, name);\n\t\t} catch {\n\t\t\treturn unknownType(name);\n\t\t}\n\t}\n\n\tprivate jsonSchemaToInterface(schema: JsonSchema, name: string): string {\n\t\tif (schema.type !== 'object' || !schema.properties) {\n\t\t\t// For non-object types, create a type alias\n\t\t\tconst typeStr = this.jsonSchemaTypeToTs(schema);\n\t\t\treturn `export type ${name} = ${typeStr};`;\n\t\t}\n\n\t\tconst props: string[] = [];\n\t\tconst required = new Set(schema.required || []);\n\n\t\tfor (const [propName, propSchema] of Object.entries(schema.properties)) {\n\t\t\tconst isRequired = required.has(propName);\n\t\t\tconst typeStr = this.jsonSchemaTypeToTs(propSchema as JsonSchema);\n\t\t\tconst optionalMark = isRequired ? '' : '?';\n\t\t\tprops.push(` ${propName}${optionalMark}: ${typeStr};`);\n\t\t}\n\n\t\treturn `export interface ${name} {\\n${props.join('\\n')}\\n}`;\n\t}\n\n\tprivate jsonSchemaTypeToTs(schema: JsonSchema): string {\n\t\tif (!schema) return 'unknown';\n\n\t\tif (schema.$ref) {\n\t\t\t// Extract name from $ref\n\t\t\tconst refName = schema.$ref.split('/').pop() || 'unknown';\n\t\t\treturn refName;\n\t\t}\n\n\t\t// Before the type: a literal is narrower than the type it belongs to, and\n\t\t// reading only the type turned `'open' | 'closed'` into `string | string`.\n\t\tif (schema.const !== undefined) {\n\t\t\treturn typeof schema.const === 'string'\n\t\t\t\t? `'${schema.const}'`\n\t\t\t\t: String(schema.const);\n\t\t}\n\n\t\tif (schema.anyOf) {\n\t\t\treturn schema.anyOf\n\t\t\t\t.map((s: JsonSchema) => this.jsonSchemaTypeToTs(s))\n\t\t\t\t.join(' | ');\n\t\t}\n\n\t\tif (schema.oneOf) {\n\t\t\treturn schema.oneOf\n\t\t\t\t.map((s: JsonSchema) => this.jsonSchemaTypeToTs(s))\n\t\t\t\t.join(' | ');\n\t\t}\n\n\t\tif (schema.allOf) {\n\t\t\treturn schema.allOf\n\t\t\t\t.map((s: JsonSchema) => this.jsonSchemaTypeToTs(s))\n\t\t\t\t.join(' & ');\n\t\t}\n\n\t\tif (Array.isArray(schema.type)) {\n\t\t\treturn schema.type\n\t\t\t\t.map((type) => this.jsonSchemaTypeToTs({ ...schema, type }))\n\t\t\t\t.join(' | ');\n\t\t}\n\n\t\tswitch (schema.type) {\n\t\t\tcase 'string':\n\t\t\t\tif (schema.enum) {\n\t\t\t\t\treturn schema.enum.map((e: string) => `'${e}'`).join(' | ');\n\t\t\t\t}\n\t\t\t\treturn 'string';\n\t\t\tcase 'number':\n\t\t\tcase 'integer':\n\t\t\t\treturn 'number';\n\t\t\tcase 'boolean':\n\t\t\t\treturn 'boolean';\n\t\t\tcase 'null':\n\t\t\t\treturn 'null';\n\t\t\tcase 'array':\n\t\t\t\tif (schema.items) {\n\t\t\t\t\treturn `Array<${this.jsonSchemaTypeToTs(schema.items as JsonSchema)}>`;\n\t\t\t\t}\n\t\t\t\treturn 'Array<unknown>';\n\t\t\tcase 'object':\n\t\t\t\tif (schema.properties) {\n\t\t\t\t\tconst props: string[] = [];\n\t\t\t\t\tconst required = new Set(schema.required || []);\n\t\t\t\t\tfor (const [propName, propSchema] of Object.entries(\n\t\t\t\t\t\tschema.properties,\n\t\t\t\t\t)) {\n\t\t\t\t\t\tconst isRequired = required.has(propName);\n\t\t\t\t\t\tconst typeStr = this.jsonSchemaTypeToTs(propSchema as JsonSchema);\n\t\t\t\t\t\tconst optionalMark = isRequired ? '' : '?';\n\t\t\t\t\t\tprops.push(`${propName}${optionalMark}: ${typeStr}`);\n\t\t\t\t\t}\n\t\t\t\t\treturn `{ ${props.join('; ')} }`;\n\t\t\t\t}\n\t\t\t\tif (schema.additionalProperties) {\n\t\t\t\t\tconst valueType = this.jsonSchemaTypeToTs(\n\t\t\t\t\t\tschema.additionalProperties as JsonSchema,\n\t\t\t\t\t);\n\t\t\t\t\treturn `Record<string, ${valueType}>`;\n\t\t\t\t}\n\t\t\t\treturn 'Record<string, unknown>';\n\t\t\tdefault:\n\t\t\t\treturn 'unknown';\n\t\t}\n\t}\n\n\tprivate async generatePathsInterface(\n\t\tendpointInfos: EndpointInfo[],\n\t): Promise<string> {\n\t\tconst pathGroups = new Map<string, EndpointInfo[]>();\n\n\t\t// Group endpoints by route\n\t\tfor (const info of endpointInfos) {\n\t\t\tconst existing = pathGroups.get(info.route) || [];\n\t\t\texisting.push(info);\n\t\t\tpathGroups.set(info.route, existing);\n\t\t}\n\n\t\tconst pathEntries: string[] = [];\n\n\t\tfor (const [route, infos] of pathGroups) {\n\t\t\tconst methodEntries: string[] = [];\n\n\t\t\tfor (const info of infos) {\n\t\t\t\tconst methodDef = await this.generateMethodDefinition(info);\n\t\t\t\tmethodEntries.push(` ${info.method.toLowerCase()}: ${methodDef};`);\n\t\t\t}\n\n\t\t\t// Add path parameters if present\n\t\t\tconst firstWithParams = infos.find((i) => i.input?.params);\n\t\t\tlet paramsEntry = '';\n\t\t\tif (firstWithParams?.input?.params) {\n\t\t\t\tconst paramsName = await this.getSchemaName(\n\t\t\t\t\tfirstWithParams.input.params,\n\t\t\t\t\t`${this.getSchemaBaseName(firstWithParams)}Params`,\n\t\t\t\t);\n\t\t\t\tparamsEntry = `\\n parameters: {\\n path: ${paramsName};\\n };`;\n\t\t\t}\n\n\t\t\tpathEntries.push(\n\t\t\t\t` '${route}': {${paramsEntry}\\n${methodEntries.join('\\n')}\\n };`,\n\t\t\t);\n\t\t}\n\n\t\treturn `export interface paths {\\n${pathEntries.join('\\n')}\\n}`;\n\t}\n\n\tprivate async generateMethodDefinition(info: EndpointInfo): Promise<string> {\n\t\tconst parts: string[] = [];\n\t\tconst baseName = this.getSchemaBaseName(info);\n\n\t\t// Request body\n\t\tif (info.input?.body) {\n\t\t\tconst bodyName = await this.getSchemaName(\n\t\t\t\tinfo.input.body,\n\t\t\t\t`${baseName}Input`,\n\t\t\t);\n\t\t\tparts.push(`requestBody: {\n content: {\n 'application/json': ${bodyName};\n };\n }`);\n\t\t}\n\n\t\t// Query parameters\n\t\tif (info.input?.query) {\n\t\t\tconst queryName = await this.getSchemaName(\n\t\t\t\tinfo.input.query,\n\t\t\t\t`${baseName}Query`,\n\t\t\t);\n\t\t\tparts.push(`parameters: {\n query: ${queryName};\n }`);\n\t\t}\n\n\t\t// Responses\n\t\tconst outputName = info.output\n\t\t\t? await this.getSchemaName(info.output, `${baseName}Output`)\n\t\t\t: 'unknown';\n\t\tparts.push(`responses: {\n 200: {\n content: {\n '${info.responseType}': ${outputName};\n };\n };\n }`);\n\n\t\treturn `{\\n ${parts.join(';\\n ')};\\n }`;\n\t}\n\n\tprivate buildModule(params: {\n\t\ttitle: string;\n\t\tversion: string;\n\t\tdescription?: string;\n\t\tsecuritySchemes: SecuritySchemeInfo[];\n\t\tendpointAuth: Record<string, string | null>;\n\t\tschemaInterfaces: string;\n\t\tpathsInterface: string;\n\t}): string {\n\t\tconst {\n\t\t\ttitle,\n\t\t\tversion,\n\t\t\tdescription,\n\t\t\tsecuritySchemes,\n\t\t\tendpointAuth,\n\t\t\tschemaInterfaces,\n\t\t\tpathsInterface,\n\t\t} = params;\n\n\t\tconst securitySchemesObj = securitySchemes.reduce(\n\t\t\t(acc, s) => {\n\t\t\t\tacc[s.name] = s.scheme;\n\t\t\t\treturn acc;\n\t\t\t},\n\t\t\t{} as Record<string, SecuritySchemeObject>,\n\t\t);\n\n\t\tconst schemeNames = securitySchemes.map((s) => `'${s.name}'`).join(' | ');\n\n\t\t// Generate createApi only if there are security schemes\n\t\tconst hasSecuritySchemes = schemeNames.length > 0;\n\n\t\tconst createApiSection = hasSecuritySchemes\n\t\t\t? `\n// ============================================================\n// API Client Factory\n// ============================================================\n\nimport {\n createAuthAwareFetcher,\n type AuthStrategy,\n} from '@geekmidas/client/auth-fetcher';\nimport { createEndpointHooks } from '@geekmidas/client/endpoint-hooks';\nimport type { QueryClient } from '@tanstack/react-query';\n\n/**\n * Options for creating the API client.\n */\nexport interface CreateApiOptions {\n /** Base URL for all API requests (required) */\n baseURL: string;\n /** Auth strategies for each security scheme used in this API */\n authStrategies: Record<SecuritySchemeId, AuthStrategy>;\n /** Optional React Query client instance */\n queryClient?: QueryClient;\n /** Optional request interceptor */\n onRequest?: (config: RequestInit) => RequestInit | Promise<RequestInit>;\n /** The \\`fetch\\` requests go out on — a test browser's, for one */\n fetch?: typeof fetch;\n}\n\n/**\n * Create a type-safe API client with authentication and React Query hooks.\n *\n * @example\n * \\`\\`\\`typescript\n * const api = createApi({\n * baseURL: 'https://api.example.com',\n * authStrategies: {\n * jwt: { type: 'bearer', tokenProvider },\n * },\n * });\n *\n * // Imperative fetch\n * const user = await api('GET /users/{id}', { params: { id: '123' } });\n *\n * // React Query hooks\n * const { data } = api.useQuery('GET /users/{id}', { params: { id: '123' } });\n * const mutation = api.useMutation('POST /users');\n * \\`\\`\\`\n */\nexport function createApi(options: CreateApiOptions) {\n const fetcher = createAuthAwareFetcher<paths, typeof endpointAuth, typeof securitySchemes>({\n baseURL: options.baseURL,\n endpointAuth,\n securitySchemes,\n authStrategies: options.authStrategies,\n onRequest: options.onRequest,\n ...(options.fetch ? { fetch: options.fetch } : {}),\n });\n\n const hooks = createEndpointHooks<paths>(fetcher, { queryClient: options.queryClient });\n\n return Object.assign(fetcher, hooks);\n}\n`\n\t\t\t: `\n// ============================================================\n// API Client Factory\n// ============================================================\n\nimport { createTypedFetcher, type FetcherOptions } from '@geekmidas/client/fetcher';\nimport { createEndpointHooks } from '@geekmidas/client/endpoint-hooks';\nimport type { QueryClient } from '@tanstack/react-query';\n\n/**\n * Options for creating the API client.\n */\nexport interface CreateApiOptions extends Omit<FetcherOptions, 'baseURL'> {\n /** Base URL for all API requests (required) */\n baseURL: string;\n /** Optional React Query client instance */\n queryClient?: QueryClient;\n}\n\n/**\n * Create a type-safe API client with React Query hooks.\n *\n * @example\n * \\`\\`\\`typescript\n * const api = createApi({\n * baseURL: 'https://api.example.com',\n * });\n *\n * // Imperative fetch\n * const data = await api('GET /health');\n *\n * // React Query hooks\n * const { data } = api.useQuery('GET /health');\n * \\`\\`\\`\n */\nexport function createApi(options: CreateApiOptions) {\n const { queryClient, ...fetcherOptions } = options;\n const request = createTypedFetcher<paths>(fetcherOptions);\n\n const hooks = createEndpointHooks<paths>(request, { queryClient });\n\n return Object.assign(request, hooks);\n}\n`;\n\n\t\treturn `// Auto-generated by @geekmidas/cli - DO NOT EDIT\n\n// ============================================================\n// Security Scheme Type\n// ============================================================\n\ninterface SecuritySchemeObject {\n type: 'apiKey' | 'http' | 'mutualTLS' | 'oauth2' | 'openIdConnect';\n description?: string;\n name?: string;\n in?: 'query' | 'header' | 'cookie';\n scheme?: string;\n bearerFormat?: string;\n flows?: Record<string, unknown>;\n openIdConnectUrl?: string;\n [key: string]: unknown;\n}\n\n// ============================================================\n// API Info\n// ============================================================\n\nexport const apiInfo = {\n title: '${title}',\n version: '${version}',${description ? `\\n description: '${description.replace(/'/g, \"\\\\'\")}',` : ''}\n} as const;\n\n// ============================================================\n// Security Schemes\n// ============================================================\n\n/**\n * Available security schemes for this API.\n * Maps authorizer names to OpenAPI security scheme definitions.\n */\nexport const securitySchemes = ${JSON.stringify(securitySchemesObj, null, 2).replace(/\"([a-zA-Z_$][a-zA-Z0-9_$]*)\":/g, '$1:')} as const satisfies Record<string, SecuritySchemeObject>;\n\nexport type SecuritySchemeId = ${schemeNames || 'never'};\n\n// ============================================================\n// Endpoint Authentication Map\n// ============================================================\n\n/**\n * Runtime map of endpoints to their required authentication scheme.\n * \\`null\\` indicates a public endpoint (no auth required).\n */\nexport const endpointAuth = ${JSON.stringify(endpointAuth, null, 2).replace(/\"([^\"]+)\":/g, \"'$1':\")} as const satisfies Record<string, SecuritySchemeId | null>;\n\nexport type EndpointString = keyof typeof endpointAuth;\n\nexport type AuthenticatedEndpoint = {\n [K in EndpointString]: typeof endpointAuth[K] extends null ? never : K;\n}[EndpointString];\n\nexport type PublicEndpoint = {\n [K in EndpointString]: typeof endpointAuth[K] extends null ? K : never;\n}[EndpointString];\n\n// ============================================================\n// Schema Definitions\n// ============================================================\n\n${schemaInterfaces}\n\n// ============================================================\n// OpenAPI Paths\n// ============================================================\n\n${pathsInterface}\n${createApiSection}\n`;\n\t}\n}\n\n/**\n * The declaration for a schema that cannot be converted — a vendor with no\n * converter, or one that fails. The paths interface names it either way, so\n * leaving it undeclared made the generated client fail to compile.\n */\nfunction unknownType(name: string): string {\n\treturn `export type ${name} = unknown;`;\n}\n"],"mappings":";;;;;;;;;AAmDA,SAAgB,wBACf,UAcmB;CACnB,OAAO;EACN,SAAS,CAAC,CAAC,SAAS;EACpB,aAAa,SAAS,SAAS,SAAS;EACxC,aAAa,CAAC,CAAC,SAAS;EACxB,mBAAmB,CAAC,CAAC,SAAS,OAAO;EACrC,oBAAoB,CAAC,CAAC,SAAS,OAAO;EACtC,oBAAoB,CAAC,CAAC,SAAS,OAAO;EAGtC,YAAY,SAAS,QAAQ,UAAU,KAAK;EAC5C,YAAY,SAAS,QAAQ,UAAU,KAAK;EAC5C,cAAc,CAAC,CAAC,SAAS;EACzB,QAAQ,CAAC,CAAC,SAAS,aAAa,CAAC,SAAS;EAC1C,qBAAqB,CAAC,CAAC,SAAS;CACjC;AACD;;;;AAKA,SAAgB,sBACf,UACe;CACf,MAAM,EACL,SACA,aACA,aACA,WACA,WACA,cACA,WACG;CAIJ,IACC,CAAC,WACD,CAAC,eACD,CAAC,eACD,CAAC,aACD,CAAC,aACD,CAAC,gBACD,CAAC,QAED,OAAO;CAIR,IAAI,aAAa,UAAU,cAC1B,OAAO;CAIR,OAAO;AACR;;;;AAKA,SAAgB,gBACf,UAcA,YACmB;CACnB,MAAM,WAAW,wBAAwB,QAAQ;CACjD,MAAM,OAAO,sBAAsB,QAAQ;CAE3C,OAAO;EACN,OAAO,SAAS;EAChB,QAAQ,SAAS;EACjB;EACA;EACA;EACA,cAAc,SAAS,SAAS,KAC9B,MAA+B,EAAE,WACnC;EACA,qBAAqB,SAAS,iBAAiB;CAChD;AACD;;;;AAgCA,SAAgB,kBAAkB,UAIhC;CACD,MAAM,SAAuC;EAC5C,SAAS;EACT,UAAU;EACV,MAAM;CACP;CAEA,MAAM,YAAoD;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