@geekmidas/cli 0.0.26 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/FUNCTION_CRON_SUPPORT.md +266 -0
- package/README.md +84 -17
- package/dist/CronGenerator-1PflEYe2.cjs +60 -0
- package/dist/CronGenerator-1PflEYe2.cjs.map +1 -0
- package/dist/CronGenerator-DXRfHQcV.mjs +54 -0
- package/dist/CronGenerator-DXRfHQcV.mjs.map +1 -0
- package/dist/EndpointGenerator-BbGrDiCP.cjs +264 -0
- package/dist/EndpointGenerator-BbGrDiCP.cjs.map +1 -0
- package/dist/EndpointGenerator-BmZ9BxbO.mjs +258 -0
- package/dist/EndpointGenerator-BmZ9BxbO.mjs.map +1 -0
- package/dist/FunctionGenerator-Clw64SwQ.cjs +59 -0
- package/dist/FunctionGenerator-Clw64SwQ.cjs.map +1 -0
- package/dist/FunctionGenerator-DOEB_yPh.mjs +53 -0
- package/dist/FunctionGenerator-DOEB_yPh.mjs.map +1 -0
- package/dist/Generator-CDoEXCDg.cjs +47 -0
- package/dist/Generator-CDoEXCDg.cjs.map +1 -0
- package/dist/Generator-UanJW0_V.mjs +41 -0
- package/dist/Generator-UanJW0_V.mjs.map +1 -0
- package/dist/SubscriberGenerator-BfMZCVNy.cjs +204 -0
- package/dist/SubscriberGenerator-BfMZCVNy.cjs.map +1 -0
- package/dist/SubscriberGenerator-D2u00NI3.mjs +198 -0
- package/dist/SubscriberGenerator-D2u00NI3.mjs.map +1 -0
- package/dist/build/index.cjs +12 -0
- package/dist/build/index.mjs +12 -0
- package/dist/build/manifests.cjs +3 -0
- package/dist/build/manifests.mjs +3 -0
- package/dist/build/providerResolver.cjs +5 -0
- package/dist/build/providerResolver.mjs +3 -0
- package/dist/build/types.cjs +0 -0
- package/dist/build/types.mjs +0 -0
- package/dist/build-BBhlEjf5.cjs +89 -0
- package/dist/build-BBhlEjf5.cjs.map +1 -0
- package/dist/build-kY-lG30Q.mjs +83 -0
- package/dist/build-kY-lG30Q.mjs.map +1 -0
- package/dist/config-D1EpSGk6.cjs +36 -0
- package/dist/config-D1EpSGk6.cjs.map +1 -0
- package/dist/config-U-mdW-7Y.mjs +30 -0
- package/dist/config-U-mdW-7Y.mjs.map +1 -0
- package/dist/config.cjs +1 -1
- package/dist/config.mjs +1 -1
- package/dist/generators/CronGenerator.cjs +4 -0
- package/dist/generators/CronGenerator.mjs +4 -0
- package/dist/generators/EndpointGenerator.cjs +4 -0
- package/dist/generators/EndpointGenerator.mjs +4 -0
- package/dist/generators/FunctionGenerator.cjs +4 -0
- package/dist/generators/FunctionGenerator.mjs +4 -0
- package/dist/generators/Generator.cjs +3 -0
- package/dist/generators/Generator.mjs +3 -0
- package/dist/generators/SubscriberGenerator.cjs +4 -0
- package/dist/generators/SubscriberGenerator.mjs +4 -0
- package/dist/generators/index.cjs +12 -0
- package/dist/generators/index.mjs +8 -0
- package/dist/generators-CEKtVh81.cjs +0 -0
- package/dist/generators-CsLujGXs.mjs +0 -0
- package/dist/index.cjs +71 -25
- package/dist/index.cjs.map +1 -0
- package/dist/index.mjs +71 -25
- package/dist/index.mjs.map +1 -0
- package/dist/manifests-BrJXpHrf.mjs +21 -0
- package/dist/manifests-BrJXpHrf.mjs.map +1 -0
- package/dist/manifests-D0saShvH.cjs +27 -0
- package/dist/manifests-D0saShvH.cjs.map +1 -0
- package/dist/{openapi-CksVdkh2.mjs → openapi-BQx3_JbM.mjs} +8 -6
- package/dist/openapi-BQx3_JbM.mjs.map +1 -0
- package/dist/{openapi-D4QQJUPY.cjs → openapi-CMLr04cz.cjs} +9 -7
- package/dist/openapi-CMLr04cz.cjs.map +1 -0
- package/dist/{openapi-react-query-DpT3XHFC.mjs → openapi-react-query-DbrWwQzb.mjs} +5 -3
- package/dist/openapi-react-query-DbrWwQzb.mjs.map +1 -0
- package/dist/{openapi-react-query-C1JLYUOs.cjs → openapi-react-query-Dvjqx_Eo.cjs} +5 -3
- package/dist/openapi-react-query-Dvjqx_Eo.cjs.map +1 -0
- package/dist/openapi-react-query.cjs +1 -1
- package/dist/openapi-react-query.mjs +1 -1
- package/dist/openapi.cjs +4 -3
- package/dist/openapi.mjs +4 -3
- package/dist/providerResolver-B_TjNF0_.mjs +96 -0
- package/dist/providerResolver-B_TjNF0_.mjs.map +1 -0
- package/dist/providerResolver-DgvzNfP4.cjs +114 -0
- package/dist/providerResolver-DgvzNfP4.cjs.map +1 -0
- package/examples/cron-example.ts +45 -0
- package/examples/function-example.ts +40 -0
- package/examples/gkm.config.json +22 -0
- package/examples/gkm.minimal.config.json +7 -0
- package/examples/gkm.production.config.json +27 -0
- package/examples/logger.ts +1 -1
- package/package.json +38 -14
- package/src/__tests__/config.spec.ts +110 -0
- package/src/__tests__/openapi-react-query.spec.ts +506 -0
- package/src/__tests__/openapi.spec.ts +362 -0
- package/src/__tests__/test-helpers.ts +180 -0
- package/src/build/__tests__/index-new.spec.ts +577 -0
- package/src/build/index.ts +197 -0
- package/src/build/manifests.ts +35 -0
- package/src/build/providerResolver.ts +184 -0
- package/src/build/types.ts +37 -0
- package/src/config.ts +14 -6
- package/src/generators/CronGenerator.ts +98 -0
- package/src/generators/EndpointGenerator.ts +389 -0
- package/src/generators/FunctionGenerator.ts +97 -0
- package/src/generators/Generator.ts +95 -0
- package/src/generators/SubscriberGenerator.ts +271 -0
- package/src/generators/__tests__/CronGenerator.spec.ts +445 -0
- package/src/generators/__tests__/EndpointGenerator.spec.ts +394 -0
- package/src/generators/__tests__/FunctionGenerator.spec.ts +256 -0
- package/src/generators/__tests__/SubscriberGenerator.spec.ts +341 -0
- package/src/generators/index.ts +9 -0
- package/src/index.ts +57 -22
- package/src/openapi-react-query.ts +2 -1
- package/src/openapi.ts +5 -4
- package/src/types.ts +91 -2
- package/dist/build-BTggTCYL.cjs +0 -176
- package/dist/build-Ca4P6_lY.mjs +0 -170
- package/dist/build.cjs +0 -5
- package/dist/build.mjs +0 -5
- package/dist/config-BNqUMsvc.cjs +0 -24
- package/dist/config-BciAdY6_.mjs +0 -18
- package/dist/loadEndpoints-BBIavB9h.cjs +0 -37
- package/dist/loadEndpoints-DAZ53Og2.mjs +0 -31
- package/dist/loadEndpoints.cjs +0 -3
- package/dist/loadEndpoints.mjs +0 -3
- package/src/build.ts +0 -305
- package/src/loadEndpoints.ts +0 -48
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
const require_chunk = require('./chunk-CUT6urMc.cjs');
|
|
2
|
+
const require_Generator = require('./Generator-CDoEXCDg.cjs');
|
|
3
|
+
const node_fs_promises = require_chunk.__toESM(require("node:fs/promises"));
|
|
4
|
+
const node_path = require_chunk.__toESM(require("node:path"));
|
|
5
|
+
const __geekmidas_constructs_endpoints = require_chunk.__toESM(require("@geekmidas/constructs/endpoints"));
|
|
6
|
+
|
|
7
|
+
//#region src/generators/EndpointGenerator.ts
|
|
8
|
+
var EndpointGenerator = class extends require_Generator.ConstructGenerator {
|
|
9
|
+
isConstruct(value) {
|
|
10
|
+
return __geekmidas_constructs_endpoints.Endpoint.isEndpoint(value);
|
|
11
|
+
}
|
|
12
|
+
async build(context, constructs, outputDir, options) {
|
|
13
|
+
const provider = options?.provider || "aws-apigatewayv2";
|
|
14
|
+
const enableOpenApi = options?.enableOpenApi || false;
|
|
15
|
+
const logger = console;
|
|
16
|
+
const routes = [];
|
|
17
|
+
if (constructs.length === 0) return routes;
|
|
18
|
+
if (provider === "server") {
|
|
19
|
+
await this.generateEndpointsFile(outputDir, constructs, context);
|
|
20
|
+
const appFile = await this.generateAppFile(outputDir, context);
|
|
21
|
+
routes.push({
|
|
22
|
+
path: "*",
|
|
23
|
+
method: "ALL",
|
|
24
|
+
handler: (0, node_path.relative)(process.cwd(), appFile)
|
|
25
|
+
});
|
|
26
|
+
logger.log(`Generated server with ${constructs.length} endpoints${enableOpenApi ? " (OpenAPI enabled)" : ""}`);
|
|
27
|
+
} else if (provider === "aws-lambda") {
|
|
28
|
+
const routesDir = (0, node_path.join)(outputDir, "routes");
|
|
29
|
+
await (0, node_fs_promises.mkdir)(routesDir, { recursive: true });
|
|
30
|
+
for (const { key, construct, path } of constructs) {
|
|
31
|
+
const handlerFile = await this.generateHandlerFile(routesDir, path.relative, key, "aws-apigatewayv2", construct, context);
|
|
32
|
+
const routeInfo = {
|
|
33
|
+
path: construct._path,
|
|
34
|
+
method: construct.method,
|
|
35
|
+
handler: (0, node_path.relative)(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
36
|
+
environment: await construct.getEnvironment()
|
|
37
|
+
};
|
|
38
|
+
routes.push(routeInfo);
|
|
39
|
+
logger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);
|
|
40
|
+
}
|
|
41
|
+
} else for (const { key, construct, path } of constructs) {
|
|
42
|
+
const handlerFile = await this.generateHandlerFile(outputDir, path.relative, key, provider, construct, context);
|
|
43
|
+
const routeInfo = {
|
|
44
|
+
path: construct._path,
|
|
45
|
+
method: construct.method,
|
|
46
|
+
handler: (0, node_path.relative)(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
47
|
+
environment: await construct.getEnvironment()
|
|
48
|
+
};
|
|
49
|
+
routes.push(routeInfo);
|
|
50
|
+
logger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);
|
|
51
|
+
}
|
|
52
|
+
return routes;
|
|
53
|
+
}
|
|
54
|
+
async generateHandlerFile(outputDir, sourceFile, exportName, provider, _endpoint, context) {
|
|
55
|
+
const handlerFileName = `${exportName}.ts`;
|
|
56
|
+
const handlerPath = (0, node_path.join)(outputDir, handlerFileName);
|
|
57
|
+
const relativePath = (0, node_path.relative)((0, node_path.dirname)(handlerPath), sourceFile);
|
|
58
|
+
const importPath = relativePath.replace(/\.ts$/, ".js");
|
|
59
|
+
const relativeEnvParserPath = (0, node_path.relative)((0, node_path.dirname)(handlerPath), context.envParserPath);
|
|
60
|
+
let content;
|
|
61
|
+
switch (provider) {
|
|
62
|
+
case "aws-apigatewayv1":
|
|
63
|
+
content = this.generateAWSApiGatewayV1Handler(importPath, exportName, relativeEnvParserPath, context.envParserImportPattern);
|
|
64
|
+
break;
|
|
65
|
+
case "aws-apigatewayv2":
|
|
66
|
+
content = this.generateAWSApiGatewayV2Handler(importPath, exportName, relativeEnvParserPath, context.envParserImportPattern);
|
|
67
|
+
break;
|
|
68
|
+
case "server":
|
|
69
|
+
content = this.generateServerHandler(importPath, exportName);
|
|
70
|
+
break;
|
|
71
|
+
default: throw new Error(`Unsupported provider: ${provider}`);
|
|
72
|
+
}
|
|
73
|
+
await (0, node_fs_promises.writeFile)(handlerPath, content);
|
|
74
|
+
return handlerPath;
|
|
75
|
+
}
|
|
76
|
+
async generateEndpointsFile(outputDir, endpoints, context) {
|
|
77
|
+
const endpointsFileName = "endpoints.ts";
|
|
78
|
+
const endpointsPath = (0, node_path.join)(outputDir, endpointsFileName);
|
|
79
|
+
const importsByFile = /* @__PURE__ */ new Map();
|
|
80
|
+
for (const { path, key } of endpoints) {
|
|
81
|
+
const relativePath = (0, node_path.relative)((0, node_path.dirname)(endpointsPath), path.relative);
|
|
82
|
+
const importPath = relativePath.replace(/\.ts$/, ".js");
|
|
83
|
+
if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
|
|
84
|
+
importsByFile.get(importPath).push(key);
|
|
85
|
+
}
|
|
86
|
+
const imports = Array.from(importsByFile.entries()).map(([importPath, exports$1]) => `import { ${exports$1.join(", ")} } from '${importPath}';`).join("\n");
|
|
87
|
+
const allExportNames = endpoints.map(({ key }) => key);
|
|
88
|
+
const content = `import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
89
|
+
import type { Logger } from '@geekmidas/logger';
|
|
90
|
+
import { HonoEndpoint } from '@geekmidas/constructs/hono';
|
|
91
|
+
import { Endpoint } from '@geekmidas/constructs/endpoints';
|
|
92
|
+
import { ServiceDiscovery } from '@geekmidas/services';
|
|
93
|
+
import type { Hono } from 'hono';
|
|
94
|
+
${imports}
|
|
95
|
+
|
|
96
|
+
const endpoints: Endpoint<any, any, any, any, any, any, any, any>[] = [
|
|
97
|
+
${allExportNames.join(",\n ")}
|
|
98
|
+
];
|
|
99
|
+
|
|
100
|
+
export function setupEndpoints(
|
|
101
|
+
app: Hono,
|
|
102
|
+
envParser: EnvironmentParser<any>,
|
|
103
|
+
logger: Logger,
|
|
104
|
+
enableOpenApi: boolean = true,
|
|
105
|
+
): void {
|
|
106
|
+
const serviceDiscovery = ServiceDiscovery.getInstance(
|
|
107
|
+
logger,
|
|
108
|
+
envParser
|
|
109
|
+
);
|
|
110
|
+
|
|
111
|
+
// Configure OpenAPI options based on enableOpenApi flag
|
|
112
|
+
const openApiOptions: any = enableOpenApi ? {
|
|
113
|
+
docsPath: '/docs',
|
|
114
|
+
openApiOptions: {
|
|
115
|
+
title: 'API Documentation',
|
|
116
|
+
version: '1.0.0',
|
|
117
|
+
description: 'Generated API documentation'
|
|
118
|
+
}
|
|
119
|
+
} : { docsPath: false };
|
|
120
|
+
|
|
121
|
+
HonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, openApiOptions);
|
|
122
|
+
}
|
|
123
|
+
`;
|
|
124
|
+
await (0, node_fs_promises.writeFile)(endpointsPath, content);
|
|
125
|
+
return endpointsPath;
|
|
126
|
+
}
|
|
127
|
+
async generateAppFile(outputDir, context) {
|
|
128
|
+
const appFileName = "app.ts";
|
|
129
|
+
const appPath = (0, node_path.join)(outputDir, appFileName);
|
|
130
|
+
const relativeLoggerPath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.loggerPath);
|
|
131
|
+
const relativeEnvParserPath = (0, node_path.relative)((0, node_path.dirname)(appPath), context.envParserPath);
|
|
132
|
+
const content = `/**
|
|
133
|
+
* Generated server application
|
|
134
|
+
*
|
|
135
|
+
* ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY
|
|
136
|
+
* The subscriber polling mechanism is not production-ready.
|
|
137
|
+
* For production, use AWS Lambda with SQS/SNS event sources.
|
|
138
|
+
*/
|
|
139
|
+
import { Hono } from 'hono';
|
|
140
|
+
import type { Hono as HonoType } from 'hono';
|
|
141
|
+
import { setupEndpoints } from './endpoints.js';
|
|
142
|
+
import { setupSubscribers } from './subscribers.js';
|
|
143
|
+
import ${context.envParserImportPattern} from '${relativeEnvParserPath}';
|
|
144
|
+
import ${context.loggerImportPattern} from '${relativeLoggerPath}';
|
|
145
|
+
|
|
146
|
+
export interface ServerApp {
|
|
147
|
+
app: HonoType;
|
|
148
|
+
start: (options?: {
|
|
149
|
+
port?: number;
|
|
150
|
+
serve: (app: HonoType, port: number) => void | Promise<void>;
|
|
151
|
+
}) => Promise<void>;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Create and configure the Hono application
|
|
156
|
+
*
|
|
157
|
+
* @param app - Optional Hono app instance to configure (creates new one if not provided)
|
|
158
|
+
* @param enableOpenApi - Enable OpenAPI documentation (default: true)
|
|
159
|
+
* @returns Server app with configured Hono app and start function
|
|
160
|
+
*
|
|
161
|
+
* @example
|
|
162
|
+
* // With Bun
|
|
163
|
+
* import { createApp } from './.gkm/server/app.js';
|
|
164
|
+
*
|
|
165
|
+
* const { app, start } = createApp();
|
|
166
|
+
*
|
|
167
|
+
* await start({
|
|
168
|
+
* port: 3000,
|
|
169
|
+
* serve: (app, port) => {
|
|
170
|
+
* Bun.serve({ port, fetch: app.fetch });
|
|
171
|
+
* }
|
|
172
|
+
* });
|
|
173
|
+
*
|
|
174
|
+
* @example
|
|
175
|
+
* // With Node.js (using @hono/node-server)
|
|
176
|
+
* import { serve } from '@hono/node-server';
|
|
177
|
+
* import { createApp } from './.gkm/server/app.js';
|
|
178
|
+
*
|
|
179
|
+
* const { app, start } = createApp();
|
|
180
|
+
*
|
|
181
|
+
* await start({
|
|
182
|
+
* port: 3000,
|
|
183
|
+
* serve: (app, port) => {
|
|
184
|
+
* serve({ fetch: app.fetch, port });
|
|
185
|
+
* }
|
|
186
|
+
* });
|
|
187
|
+
*/
|
|
188
|
+
export function createApp(app?: HonoType, enableOpenApi: boolean = true): ServerApp {
|
|
189
|
+
const honoApp = app || new Hono();
|
|
190
|
+
|
|
191
|
+
// Setup HTTP endpoints
|
|
192
|
+
setupEndpoints(honoApp, envParser, logger, enableOpenApi);
|
|
193
|
+
|
|
194
|
+
return {
|
|
195
|
+
app: honoApp,
|
|
196
|
+
async start(options) {
|
|
197
|
+
if (!options?.serve) {
|
|
198
|
+
throw new Error(
|
|
199
|
+
'serve function is required. Pass a serve function for your runtime:\\n' +
|
|
200
|
+
' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\n' +
|
|
201
|
+
' - Node: (app, port) => serve({ fetch: app.fetch, port })'
|
|
202
|
+
);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const port = options.port ?? 3000;
|
|
206
|
+
|
|
207
|
+
// Start subscribers in background (non-blocking, local development only)
|
|
208
|
+
await setupSubscribers(envParser, logger).catch((error) => {
|
|
209
|
+
logger.error({ error }, 'Failed to start subscribers');
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
logger.info({ port }, 'Starting server');
|
|
213
|
+
|
|
214
|
+
// Start HTTP server using provided serve function
|
|
215
|
+
await options.serve(honoApp, port);
|
|
216
|
+
|
|
217
|
+
logger.info({ port }, 'Server started');
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Default export for convenience
|
|
223
|
+
export default createApp;
|
|
224
|
+
`;
|
|
225
|
+
await (0, node_fs_promises.writeFile)(appPath, content);
|
|
226
|
+
return appPath;
|
|
227
|
+
}
|
|
228
|
+
generateAWSApiGatewayV1Handler(importPath, exportName, envParserPath, envParserImportPattern) {
|
|
229
|
+
return `import { AmazonApiGatewayV1Endpoint } from '@geekmidas/constructs/aws';
|
|
230
|
+
import { ${exportName} } from '${importPath}';
|
|
231
|
+
import ${envParserImportPattern} from '${envParserPath}';
|
|
232
|
+
|
|
233
|
+
const adapter = new AmazonApiGatewayV1Endpoint(envParser, ${exportName});
|
|
234
|
+
|
|
235
|
+
export const handler = adapter.handler;
|
|
236
|
+
`;
|
|
237
|
+
}
|
|
238
|
+
generateAWSApiGatewayV2Handler(importPath, exportName, envParserPath, envParserImportPattern) {
|
|
239
|
+
return `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';
|
|
240
|
+
import { ${exportName} } from '${importPath}';
|
|
241
|
+
import ${envParserImportPattern} from '${envParserPath}';
|
|
242
|
+
|
|
243
|
+
const adapter = new AmazonApiGatewayV2Endpoint(envParser, ${exportName});
|
|
244
|
+
|
|
245
|
+
export const handler = adapter.handler;
|
|
246
|
+
`;
|
|
247
|
+
}
|
|
248
|
+
generateServerHandler(importPath, exportName) {
|
|
249
|
+
return `import { ${exportName} } from '${importPath}';
|
|
250
|
+
|
|
251
|
+
// Server handler - implement based on your server framework
|
|
252
|
+
export const handler = ${exportName};
|
|
253
|
+
`;
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
//#endregion
|
|
258
|
+
Object.defineProperty(exports, 'EndpointGenerator', {
|
|
259
|
+
enumerable: true,
|
|
260
|
+
get: function () {
|
|
261
|
+
return EndpointGenerator;
|
|
262
|
+
}
|
|
263
|
+
});
|
|
264
|
+
//# sourceMappingURL=EndpointGenerator-BbGrDiCP.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"EndpointGenerator-BbGrDiCP.cjs","names":["ConstructGenerator","value: any","context: BuildContext","constructs: GeneratedConstruct<Endpoint<any, any, any, any, any, any>>[]","outputDir: string","options?: GeneratorOptions","routes: RouteInfo[]","routeInfo: RouteInfo","sourceFile: string","exportName: string","provider: LegacyProvider","_endpoint: Endpoint<any, any, any, any, any, any>","content: string","endpoints: GeneratedConstruct<Endpoint<any, any, any, any, any, any>>[]","exports","importPath: string","envParserPath: string","envParserImportPattern: string"],"sources":["../src/generators/EndpointGenerator.ts"],"sourcesContent":["import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport type { BuildContext } from '../build/types';\nimport type { LegacyProvider, RouteInfo } from '../types';\nimport {\n ConstructGenerator,\n type GeneratedConstruct,\n type GeneratorOptions,\n} from './Generator';\n\nexport class EndpointGenerator extends ConstructGenerator<\n Endpoint<any, any, any, any, any, any>,\n RouteInfo[]\n> {\n isConstruct(value: any): value is Endpoint<any, any, any, any, any, any> {\n return Endpoint.isEndpoint(value);\n }\n\n async build(\n context: BuildContext,\n constructs: GeneratedConstruct<Endpoint<any, any, any, any, any, any>>[],\n outputDir: string,\n options?: GeneratorOptions,\n ): Promise<RouteInfo[]> {\n const provider = options?.provider || 'aws-apigatewayv2';\n const enableOpenApi = options?.enableOpenApi || false;\n const logger = console;\n const routes: RouteInfo[] = [];\n\n if (constructs.length === 0) {\n return routes;\n }\n\n if (provider === 'server') {\n // Generate endpoints.ts and app.ts\n await this.generateEndpointsFile(outputDir, constructs, context);\n const appFile = await this.generateAppFile(outputDir, context);\n\n routes.push({\n path: '*',\n method: 'ALL',\n handler: relative(process.cwd(), appFile),\n });\n\n logger.log(\n `Generated server with ${constructs.length} endpoints${enableOpenApi ? ' (OpenAPI enabled)' : ''}`,\n );\n } else if (provider === 'aws-lambda') {\n // For aws-lambda, create routes subdirectory\n const routesDir = join(outputDir, 'routes');\n await mkdir(routesDir, { recursive: true });\n\n // Generate individual handlers for API Gateway routes\n for (const { key, construct, path } of constructs) {\n const handlerFile = await this.generateHandlerFile(\n routesDir,\n path.relative,\n key,\n 'aws-apigatewayv2',\n construct,\n context,\n );\n\n const routeInfo: RouteInfo = {\n path: construct._path,\n method: construct.method,\n handler: relative(process.cwd(), handlerFile).replace(\n /\\.ts$/,\n '.handler',\n ),\n environment: await construct.getEnvironment(),\n };\n\n routes.push(routeInfo);\n logger.log(\n `Generated handler for ${routeInfo.method} ${routeInfo.path}`,\n );\n }\n } else {\n // Generate individual handler files for AWS API Gateway providers\n for (const { key, construct, path } of constructs) {\n const handlerFile = await this.generateHandlerFile(\n outputDir,\n path.relative,\n key,\n provider,\n construct,\n context,\n );\n\n const routeInfo: RouteInfo = {\n path: construct._path,\n method: construct.method,\n handler: relative(process.cwd(), handlerFile).replace(\n /\\.ts$/,\n '.handler',\n ),\n environment: await construct.getEnvironment(),\n };\n\n routes.push(routeInfo);\n logger.log(\n `Generated handler for ${routeInfo.method} ${routeInfo.path}`,\n );\n }\n }\n\n return routes;\n }\n\n private async generateHandlerFile(\n outputDir: string,\n sourceFile: string,\n exportName: string,\n provider: LegacyProvider,\n _endpoint: Endpoint<any, any, any, any, any, any>,\n context: BuildContext,\n ): Promise<string> {\n const handlerFileName = `${exportName}.ts`;\n const handlerPath = join(outputDir, handlerFileName);\n\n const relativePath = relative(dirname(handlerPath), sourceFile);\n const importPath = relativePath.replace(/\\.ts$/, '.js');\n\n const relativeEnvParserPath = relative(\n dirname(handlerPath),\n context.envParserPath,\n );\n\n let content: string;\n\n switch (provider) {\n case 'aws-apigatewayv1':\n content = this.generateAWSApiGatewayV1Handler(\n importPath,\n exportName,\n relativeEnvParserPath,\n context.envParserImportPattern,\n );\n break;\n case 'aws-apigatewayv2':\n content = this.generateAWSApiGatewayV2Handler(\n importPath,\n exportName,\n relativeEnvParserPath,\n context.envParserImportPattern,\n );\n break;\n case 'server':\n content = this.generateServerHandler(importPath, exportName);\n break;\n default:\n throw new Error(`Unsupported provider: ${provider}`);\n }\n\n await writeFile(handlerPath, content);\n return handlerPath;\n }\n\n private async generateEndpointsFile(\n outputDir: string,\n endpoints: GeneratedConstruct<Endpoint<any, any, any, any, any, any>>[],\n context: BuildContext,\n ): Promise<string> {\n const endpointsFileName = 'endpoints.ts';\n const endpointsPath = join(outputDir, endpointsFileName);\n\n // Group imports by file\n const importsByFile = new Map<string, string[]>();\n\n for (const { path, key } of endpoints) {\n const relativePath = relative(dirname(endpointsPath), path.relative);\n const importPath = relativePath.replace(/\\.ts$/, '.js');\n\n if (!importsByFile.has(importPath)) {\n importsByFile.set(importPath, []);\n }\n importsByFile.get(importPath)!.push(key);\n }\n\n // Generate import statements\n const imports = Array.from(importsByFile.entries())\n .map(\n ([importPath, exports]) =>\n `import { ${exports.join(', ')} } from '${importPath}';`,\n )\n .join('\\n');\n\n const allExportNames = endpoints.map(({ key }) => key);\n\n const 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${imports}\n\nconst endpoints: Endpoint<any, any, any, any, any, any, any, any>[] = [\n ${allExportNames.join(',\\n ')}\n];\n\nexport function setupEndpoints(\n app: Hono,\n envParser: EnvironmentParser<any>,\n logger: Logger,\n enableOpenApi: boolean = true,\n): void {\n const serviceDiscovery = ServiceDiscovery.getInstance(\n logger,\n envParser\n );\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`;\n\n await writeFile(endpointsPath, content);\n\n return endpointsPath;\n }\n\n private async generateAppFile(\n outputDir: string,\n context: BuildContext,\n ): Promise<string> {\n const appFileName = 'app.ts';\n const appPath = join(outputDir, appFileName);\n\n const relativeLoggerPath = relative(dirname(appPath), context.loggerPath);\n\n const relativeEnvParserPath = relative(\n dirname(appPath),\n context.envParserPath,\n );\n\n const 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 ${context.envParserImportPattern} from '${relativeEnvParserPath}';\nimport ${context.loggerImportPattern} from '${relativeLoggerPath}';\n\nexport 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 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 } = 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 } = createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * serve({ fetch: app.fetch, port });\n * }\n * });\n */\nexport function createApp(app?: HonoType, enableOpenApi: boolean = true): ServerApp {\n const honoApp = app || new Hono();\n\n // Setup HTTP endpoints\n setupEndpoints(honoApp, envParser, logger, enableOpenApi);\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 // Start subscribers in background (non-blocking, local development only)\n await setupSubscribers(envParser, logger).catch((error) => {\n logger.error({ error }, 'Failed to start subscribers');\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 };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n await writeFile(appPath, content);\n\n return appPath;\n }\n\n private generateAWSApiGatewayV1Handler(\n importPath: string,\n exportName: string,\n envParserPath: string,\n envParserImportPattern: string,\n ): string {\n return `import { AmazonApiGatewayV1Endpoint } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\nimport ${envParserImportPattern} from '${envParserPath}';\n\nconst adapter = new AmazonApiGatewayV1Endpoint(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n }\n\n private generateAWSApiGatewayV2Handler(\n importPath: string,\n exportName: string,\n envParserPath: string,\n envParserImportPattern: string,\n ): string {\n return `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\nimport ${envParserImportPattern} from '${envParserPath}';\n\nconst adapter = new AmazonApiGatewayV2Endpoint(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n }\n\n private generateServerHandler(\n importPath: string,\n exportName: string,\n ): string {\n return `import { ${exportName} } from '${importPath}';\n\n// Server handler - implement based on your server framework\nexport const handler = ${exportName};\n`;\n }\n}\n"],"mappings":";;;;;;;AAWA,IAAa,oBAAb,cAAuCA,qCAGrC;CACA,YAAYC,OAA6D;AACvE,SAAO,0CAAS,WAAW,MAAM;CAClC;CAED,MAAM,MACJC,SACAC,YACAC,WACAC,SACsB;EACtB,MAAM,WAAW,SAAS,YAAY;EACtC,MAAM,gBAAgB,SAAS,iBAAiB;EAChD,MAAM,SAAS;EACf,MAAMC,SAAsB,CAAE;AAE9B,MAAI,WAAW,WAAW,EACxB,QAAO;AAGT,MAAI,aAAa,UAAU;AAEzB,SAAM,KAAK,sBAAsB,WAAW,YAAY,QAAQ;GAChE,MAAM,UAAU,MAAM,KAAK,gBAAgB,WAAW,QAAQ;AAE9D,UAAO,KAAK;IACV,MAAM;IACN,QAAQ;IACR,SAAS,wBAAS,QAAQ,KAAK,EAAE,QAAQ;GAC1C,EAAC;AAEF,UAAO,KACJ,wBAAwB,WAAW,OAAO,YAAY,gBAAgB,uBAAuB,GAAG,EAClG;EACF,WAAU,aAAa,cAAc;GAEpC,MAAM,YAAY,oBAAK,WAAW,SAAS;AAC3C,SAA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uBAAuB,SAAS,sBAAsB;SAC9D,QAAQ,oBAAoB,SAAS,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkF7D,QAAM,gCAAU,SAAS,QAAQ;AAEjC,SAAO;CACR;CAED,AAAQ,+BACNa,YACAN,YACAO,eACAC,wBACQ;AACR,UAAQ;WACD,WAAW,WAAW,WAAW;SACnC,uBAAuB,SAAS,cAAc;;4DAEK,WAAW;;;;CAIpE;CAED,AAAQ,+BACNF,YACAN,YACAO,eACAC,wBACQ;AACR,UAAQ;WACD,WAAW,WAAW,WAAW;SACnC,uBAAuB,SAAS,cAAc;;4DAEK,WAAW;;;;CAIpE;CAED,AAAQ,sBACNF,YACAN,YACQ;AACR,UAAQ,WAAW,WAAW,WAAW,WAAW;;;yBAG/B,WAAW;;CAEjC;AACF"}
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { ConstructGenerator } from "./Generator-UanJW0_V.mjs";
|
|
2
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
3
|
+
import { dirname, join, relative } from "node:path";
|
|
4
|
+
import { Endpoint } from "@geekmidas/constructs/endpoints";
|
|
5
|
+
|
|
6
|
+
//#region src/generators/EndpointGenerator.ts
|
|
7
|
+
var EndpointGenerator = class extends ConstructGenerator {
|
|
8
|
+
isConstruct(value) {
|
|
9
|
+
return Endpoint.isEndpoint(value);
|
|
10
|
+
}
|
|
11
|
+
async build(context, constructs, outputDir, options) {
|
|
12
|
+
const provider = options?.provider || "aws-apigatewayv2";
|
|
13
|
+
const enableOpenApi = options?.enableOpenApi || false;
|
|
14
|
+
const logger = console;
|
|
15
|
+
const routes = [];
|
|
16
|
+
if (constructs.length === 0) return routes;
|
|
17
|
+
if (provider === "server") {
|
|
18
|
+
await this.generateEndpointsFile(outputDir, constructs, context);
|
|
19
|
+
const appFile = await this.generateAppFile(outputDir, context);
|
|
20
|
+
routes.push({
|
|
21
|
+
path: "*",
|
|
22
|
+
method: "ALL",
|
|
23
|
+
handler: relative(process.cwd(), appFile)
|
|
24
|
+
});
|
|
25
|
+
logger.log(`Generated server with ${constructs.length} endpoints${enableOpenApi ? " (OpenAPI enabled)" : ""}`);
|
|
26
|
+
} else if (provider === "aws-lambda") {
|
|
27
|
+
const routesDir = join(outputDir, "routes");
|
|
28
|
+
await mkdir(routesDir, { recursive: true });
|
|
29
|
+
for (const { key, construct, path } of constructs) {
|
|
30
|
+
const handlerFile = await this.generateHandlerFile(routesDir, path.relative, key, "aws-apigatewayv2", construct, context);
|
|
31
|
+
const routeInfo = {
|
|
32
|
+
path: construct._path,
|
|
33
|
+
method: construct.method,
|
|
34
|
+
handler: relative(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
35
|
+
environment: await construct.getEnvironment()
|
|
36
|
+
};
|
|
37
|
+
routes.push(routeInfo);
|
|
38
|
+
logger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);
|
|
39
|
+
}
|
|
40
|
+
} else for (const { key, construct, path } of constructs) {
|
|
41
|
+
const handlerFile = await this.generateHandlerFile(outputDir, path.relative, key, provider, construct, context);
|
|
42
|
+
const routeInfo = {
|
|
43
|
+
path: construct._path,
|
|
44
|
+
method: construct.method,
|
|
45
|
+
handler: relative(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
46
|
+
environment: await construct.getEnvironment()
|
|
47
|
+
};
|
|
48
|
+
routes.push(routeInfo);
|
|
49
|
+
logger.log(`Generated handler for ${routeInfo.method} ${routeInfo.path}`);
|
|
50
|
+
}
|
|
51
|
+
return routes;
|
|
52
|
+
}
|
|
53
|
+
async generateHandlerFile(outputDir, sourceFile, exportName, provider, _endpoint, context) {
|
|
54
|
+
const handlerFileName = `${exportName}.ts`;
|
|
55
|
+
const handlerPath = join(outputDir, handlerFileName);
|
|
56
|
+
const relativePath = relative(dirname(handlerPath), sourceFile);
|
|
57
|
+
const importPath = relativePath.replace(/\.ts$/, ".js");
|
|
58
|
+
const relativeEnvParserPath = relative(dirname(handlerPath), context.envParserPath);
|
|
59
|
+
let content;
|
|
60
|
+
switch (provider) {
|
|
61
|
+
case "aws-apigatewayv1":
|
|
62
|
+
content = this.generateAWSApiGatewayV1Handler(importPath, exportName, relativeEnvParserPath, context.envParserImportPattern);
|
|
63
|
+
break;
|
|
64
|
+
case "aws-apigatewayv2":
|
|
65
|
+
content = this.generateAWSApiGatewayV2Handler(importPath, exportName, relativeEnvParserPath, context.envParserImportPattern);
|
|
66
|
+
break;
|
|
67
|
+
case "server":
|
|
68
|
+
content = this.generateServerHandler(importPath, exportName);
|
|
69
|
+
break;
|
|
70
|
+
default: throw new Error(`Unsupported provider: ${provider}`);
|
|
71
|
+
}
|
|
72
|
+
await writeFile(handlerPath, content);
|
|
73
|
+
return handlerPath;
|
|
74
|
+
}
|
|
75
|
+
async generateEndpointsFile(outputDir, endpoints, context) {
|
|
76
|
+
const endpointsFileName = "endpoints.ts";
|
|
77
|
+
const endpointsPath = join(outputDir, endpointsFileName);
|
|
78
|
+
const importsByFile = /* @__PURE__ */ new Map();
|
|
79
|
+
for (const { path, key } of endpoints) {
|
|
80
|
+
const relativePath = relative(dirname(endpointsPath), path.relative);
|
|
81
|
+
const importPath = relativePath.replace(/\.ts$/, ".js");
|
|
82
|
+
if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
|
|
83
|
+
importsByFile.get(importPath).push(key);
|
|
84
|
+
}
|
|
85
|
+
const imports = Array.from(importsByFile.entries()).map(([importPath, exports]) => `import { ${exports.join(", ")} } from '${importPath}';`).join("\n");
|
|
86
|
+
const allExportNames = endpoints.map(({ key }) => key);
|
|
87
|
+
const content = `import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
88
|
+
import type { Logger } from '@geekmidas/logger';
|
|
89
|
+
import { HonoEndpoint } from '@geekmidas/constructs/hono';
|
|
90
|
+
import { Endpoint } from '@geekmidas/constructs/endpoints';
|
|
91
|
+
import { ServiceDiscovery } from '@geekmidas/services';
|
|
92
|
+
import type { Hono } from 'hono';
|
|
93
|
+
${imports}
|
|
94
|
+
|
|
95
|
+
const endpoints: Endpoint<any, any, any, any, any, any, any, any>[] = [
|
|
96
|
+
${allExportNames.join(",\n ")}
|
|
97
|
+
];
|
|
98
|
+
|
|
99
|
+
export function setupEndpoints(
|
|
100
|
+
app: Hono,
|
|
101
|
+
envParser: EnvironmentParser<any>,
|
|
102
|
+
logger: Logger,
|
|
103
|
+
enableOpenApi: boolean = true,
|
|
104
|
+
): void {
|
|
105
|
+
const serviceDiscovery = ServiceDiscovery.getInstance(
|
|
106
|
+
logger,
|
|
107
|
+
envParser
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
// Configure OpenAPI options based on enableOpenApi flag
|
|
111
|
+
const openApiOptions: any = enableOpenApi ? {
|
|
112
|
+
docsPath: '/docs',
|
|
113
|
+
openApiOptions: {
|
|
114
|
+
title: 'API Documentation',
|
|
115
|
+
version: '1.0.0',
|
|
116
|
+
description: 'Generated API documentation'
|
|
117
|
+
}
|
|
118
|
+
} : { docsPath: false };
|
|
119
|
+
|
|
120
|
+
HonoEndpoint.addRoutes(endpoints, serviceDiscovery, app, openApiOptions);
|
|
121
|
+
}
|
|
122
|
+
`;
|
|
123
|
+
await writeFile(endpointsPath, content);
|
|
124
|
+
return endpointsPath;
|
|
125
|
+
}
|
|
126
|
+
async generateAppFile(outputDir, context) {
|
|
127
|
+
const appFileName = "app.ts";
|
|
128
|
+
const appPath = join(outputDir, appFileName);
|
|
129
|
+
const relativeLoggerPath = relative(dirname(appPath), context.loggerPath);
|
|
130
|
+
const relativeEnvParserPath = relative(dirname(appPath), context.envParserPath);
|
|
131
|
+
const content = `/**
|
|
132
|
+
* Generated server application
|
|
133
|
+
*
|
|
134
|
+
* ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY
|
|
135
|
+
* The subscriber polling mechanism is not production-ready.
|
|
136
|
+
* For production, use AWS Lambda with SQS/SNS event sources.
|
|
137
|
+
*/
|
|
138
|
+
import { Hono } from 'hono';
|
|
139
|
+
import type { Hono as HonoType } from 'hono';
|
|
140
|
+
import { setupEndpoints } from './endpoints.js';
|
|
141
|
+
import { setupSubscribers } from './subscribers.js';
|
|
142
|
+
import ${context.envParserImportPattern} from '${relativeEnvParserPath}';
|
|
143
|
+
import ${context.loggerImportPattern} from '${relativeLoggerPath}';
|
|
144
|
+
|
|
145
|
+
export interface ServerApp {
|
|
146
|
+
app: HonoType;
|
|
147
|
+
start: (options?: {
|
|
148
|
+
port?: number;
|
|
149
|
+
serve: (app: HonoType, port: number) => void | Promise<void>;
|
|
150
|
+
}) => Promise<void>;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Create and configure the Hono application
|
|
155
|
+
*
|
|
156
|
+
* @param app - Optional Hono app instance to configure (creates new one if not provided)
|
|
157
|
+
* @param enableOpenApi - Enable OpenAPI documentation (default: true)
|
|
158
|
+
* @returns Server app with configured Hono app and start function
|
|
159
|
+
*
|
|
160
|
+
* @example
|
|
161
|
+
* // With Bun
|
|
162
|
+
* import { createApp } from './.gkm/server/app.js';
|
|
163
|
+
*
|
|
164
|
+
* const { app, start } = createApp();
|
|
165
|
+
*
|
|
166
|
+
* await start({
|
|
167
|
+
* port: 3000,
|
|
168
|
+
* serve: (app, port) => {
|
|
169
|
+
* Bun.serve({ port, fetch: app.fetch });
|
|
170
|
+
* }
|
|
171
|
+
* });
|
|
172
|
+
*
|
|
173
|
+
* @example
|
|
174
|
+
* // With Node.js (using @hono/node-server)
|
|
175
|
+
* import { serve } from '@hono/node-server';
|
|
176
|
+
* import { createApp } from './.gkm/server/app.js';
|
|
177
|
+
*
|
|
178
|
+
* const { app, start } = createApp();
|
|
179
|
+
*
|
|
180
|
+
* await start({
|
|
181
|
+
* port: 3000,
|
|
182
|
+
* serve: (app, port) => {
|
|
183
|
+
* serve({ fetch: app.fetch, port });
|
|
184
|
+
* }
|
|
185
|
+
* });
|
|
186
|
+
*/
|
|
187
|
+
export function createApp(app?: HonoType, enableOpenApi: boolean = true): ServerApp {
|
|
188
|
+
const honoApp = app || new Hono();
|
|
189
|
+
|
|
190
|
+
// Setup HTTP endpoints
|
|
191
|
+
setupEndpoints(honoApp, envParser, logger, enableOpenApi);
|
|
192
|
+
|
|
193
|
+
return {
|
|
194
|
+
app: honoApp,
|
|
195
|
+
async start(options) {
|
|
196
|
+
if (!options?.serve) {
|
|
197
|
+
throw new Error(
|
|
198
|
+
'serve function is required. Pass a serve function for your runtime:\\n' +
|
|
199
|
+
' - Bun: (app, port) => Bun.serve({ port, fetch: app.fetch })\\n' +
|
|
200
|
+
' - Node: (app, port) => serve({ fetch: app.fetch, port })'
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const port = options.port ?? 3000;
|
|
205
|
+
|
|
206
|
+
// Start subscribers in background (non-blocking, local development only)
|
|
207
|
+
await setupSubscribers(envParser, logger).catch((error) => {
|
|
208
|
+
logger.error({ error }, 'Failed to start subscribers');
|
|
209
|
+
});
|
|
210
|
+
|
|
211
|
+
logger.info({ port }, 'Starting server');
|
|
212
|
+
|
|
213
|
+
// Start HTTP server using provided serve function
|
|
214
|
+
await options.serve(honoApp, port);
|
|
215
|
+
|
|
216
|
+
logger.info({ port }, 'Server started');
|
|
217
|
+
}
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Default export for convenience
|
|
222
|
+
export default createApp;
|
|
223
|
+
`;
|
|
224
|
+
await writeFile(appPath, content);
|
|
225
|
+
return appPath;
|
|
226
|
+
}
|
|
227
|
+
generateAWSApiGatewayV1Handler(importPath, exportName, envParserPath, envParserImportPattern) {
|
|
228
|
+
return `import { AmazonApiGatewayV1Endpoint } from '@geekmidas/constructs/aws';
|
|
229
|
+
import { ${exportName} } from '${importPath}';
|
|
230
|
+
import ${envParserImportPattern} from '${envParserPath}';
|
|
231
|
+
|
|
232
|
+
const adapter = new AmazonApiGatewayV1Endpoint(envParser, ${exportName});
|
|
233
|
+
|
|
234
|
+
export const handler = adapter.handler;
|
|
235
|
+
`;
|
|
236
|
+
}
|
|
237
|
+
generateAWSApiGatewayV2Handler(importPath, exportName, envParserPath, envParserImportPattern) {
|
|
238
|
+
return `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';
|
|
239
|
+
import { ${exportName} } from '${importPath}';
|
|
240
|
+
import ${envParserImportPattern} from '${envParserPath}';
|
|
241
|
+
|
|
242
|
+
const adapter = new AmazonApiGatewayV2Endpoint(envParser, ${exportName});
|
|
243
|
+
|
|
244
|
+
export const handler = adapter.handler;
|
|
245
|
+
`;
|
|
246
|
+
}
|
|
247
|
+
generateServerHandler(importPath, exportName) {
|
|
248
|
+
return `import { ${exportName} } from '${importPath}';
|
|
249
|
+
|
|
250
|
+
// Server handler - implement based on your server framework
|
|
251
|
+
export const handler = ${exportName};
|
|
252
|
+
`;
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
|
|
256
|
+
//#endregion
|
|
257
|
+
export { EndpointGenerator };
|
|
258
|
+
//# sourceMappingURL=EndpointGenerator-BmZ9BxbO.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"EndpointGenerator-BmZ9BxbO.mjs","names":["value: any","context: BuildContext","constructs: GeneratedConstruct<Endpoint<any, any, any, any, any, any>>[]","outputDir: string","options?: GeneratorOptions","routes: RouteInfo[]","routeInfo: RouteInfo","sourceFile: string","exportName: string","provider: LegacyProvider","_endpoint: Endpoint<any, any, any, any, any, any>","content: string","endpoints: GeneratedConstruct<Endpoint<any, any, any, any, any, any>>[]","importPath: string","envParserPath: string","envParserImportPattern: string"],"sources":["../src/generators/EndpointGenerator.ts"],"sourcesContent":["import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Endpoint } from '@geekmidas/constructs/endpoints';\nimport type { BuildContext } from '../build/types';\nimport type { LegacyProvider, RouteInfo } from '../types';\nimport {\n ConstructGenerator,\n type GeneratedConstruct,\n type GeneratorOptions,\n} from './Generator';\n\nexport class EndpointGenerator extends ConstructGenerator<\n Endpoint<any, any, any, any, any, any>,\n RouteInfo[]\n> {\n isConstruct(value: any): value is Endpoint<any, any, any, any, any, any> {\n return Endpoint.isEndpoint(value);\n }\n\n async build(\n context: BuildContext,\n constructs: GeneratedConstruct<Endpoint<any, any, any, any, any, any>>[],\n outputDir: string,\n options?: GeneratorOptions,\n ): Promise<RouteInfo[]> {\n const provider = options?.provider || 'aws-apigatewayv2';\n const enableOpenApi = options?.enableOpenApi || false;\n const logger = console;\n const routes: RouteInfo[] = [];\n\n if (constructs.length === 0) {\n return routes;\n }\n\n if (provider === 'server') {\n // Generate endpoints.ts and app.ts\n await this.generateEndpointsFile(outputDir, constructs, context);\n const appFile = await this.generateAppFile(outputDir, context);\n\n routes.push({\n path: '*',\n method: 'ALL',\n handler: relative(process.cwd(), appFile),\n });\n\n logger.log(\n `Generated server with ${constructs.length} endpoints${enableOpenApi ? ' (OpenAPI enabled)' : ''}`,\n );\n } else if (provider === 'aws-lambda') {\n // For aws-lambda, create routes subdirectory\n const routesDir = join(outputDir, 'routes');\n await mkdir(routesDir, { recursive: true });\n\n // Generate individual handlers for API Gateway routes\n for (const { key, construct, path } of constructs) {\n const handlerFile = await this.generateHandlerFile(\n routesDir,\n path.relative,\n key,\n 'aws-apigatewayv2',\n construct,\n context,\n );\n\n const routeInfo: RouteInfo = {\n path: construct._path,\n method: construct.method,\n handler: relative(process.cwd(), handlerFile).replace(\n /\\.ts$/,\n '.handler',\n ),\n environment: await construct.getEnvironment(),\n };\n\n routes.push(routeInfo);\n logger.log(\n `Generated handler for ${routeInfo.method} ${routeInfo.path}`,\n );\n }\n } else {\n // Generate individual handler files for AWS API Gateway providers\n for (const { key, construct, path } of constructs) {\n const handlerFile = await this.generateHandlerFile(\n outputDir,\n path.relative,\n key,\n provider,\n construct,\n context,\n );\n\n const routeInfo: RouteInfo = {\n path: construct._path,\n method: construct.method,\n handler: relative(process.cwd(), handlerFile).replace(\n /\\.ts$/,\n '.handler',\n ),\n environment: await construct.getEnvironment(),\n };\n\n routes.push(routeInfo);\n logger.log(\n `Generated handler for ${routeInfo.method} ${routeInfo.path}`,\n );\n }\n }\n\n return routes;\n }\n\n private async generateHandlerFile(\n outputDir: string,\n sourceFile: string,\n exportName: string,\n provider: LegacyProvider,\n _endpoint: Endpoint<any, any, any, any, any, any>,\n context: BuildContext,\n ): Promise<string> {\n const handlerFileName = `${exportName}.ts`;\n const handlerPath = join(outputDir, handlerFileName);\n\n const relativePath = relative(dirname(handlerPath), sourceFile);\n const importPath = relativePath.replace(/\\.ts$/, '.js');\n\n const relativeEnvParserPath = relative(\n dirname(handlerPath),\n context.envParserPath,\n );\n\n let content: string;\n\n switch (provider) {\n case 'aws-apigatewayv1':\n content = this.generateAWSApiGatewayV1Handler(\n importPath,\n exportName,\n relativeEnvParserPath,\n context.envParserImportPattern,\n );\n break;\n case 'aws-apigatewayv2':\n content = this.generateAWSApiGatewayV2Handler(\n importPath,\n exportName,\n relativeEnvParserPath,\n context.envParserImportPattern,\n );\n break;\n case 'server':\n content = this.generateServerHandler(importPath, exportName);\n break;\n default:\n throw new Error(`Unsupported provider: ${provider}`);\n }\n\n await writeFile(handlerPath, content);\n return handlerPath;\n }\n\n private async generateEndpointsFile(\n outputDir: string,\n endpoints: GeneratedConstruct<Endpoint<any, any, any, any, any, any>>[],\n context: BuildContext,\n ): Promise<string> {\n const endpointsFileName = 'endpoints.ts';\n const endpointsPath = join(outputDir, endpointsFileName);\n\n // Group imports by file\n const importsByFile = new Map<string, string[]>();\n\n for (const { path, key } of endpoints) {\n const relativePath = relative(dirname(endpointsPath), path.relative);\n const importPath = relativePath.replace(/\\.ts$/, '.js');\n\n if (!importsByFile.has(importPath)) {\n importsByFile.set(importPath, []);\n }\n importsByFile.get(importPath)!.push(key);\n }\n\n // Generate import statements\n const imports = Array.from(importsByFile.entries())\n .map(\n ([importPath, exports]) =>\n `import { ${exports.join(', ')} } from '${importPath}';`,\n )\n .join('\\n');\n\n const allExportNames = endpoints.map(({ key }) => key);\n\n const 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${imports}\n\nconst endpoints: Endpoint<any, any, any, any, any, any, any, any>[] = [\n ${allExportNames.join(',\\n ')}\n];\n\nexport function setupEndpoints(\n app: Hono,\n envParser: EnvironmentParser<any>,\n logger: Logger,\n enableOpenApi: boolean = true,\n): void {\n const serviceDiscovery = ServiceDiscovery.getInstance(\n logger,\n envParser\n );\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`;\n\n await writeFile(endpointsPath, content);\n\n return endpointsPath;\n }\n\n private async generateAppFile(\n outputDir: string,\n context: BuildContext,\n ): Promise<string> {\n const appFileName = 'app.ts';\n const appPath = join(outputDir, appFileName);\n\n const relativeLoggerPath = relative(dirname(appPath), context.loggerPath);\n\n const relativeEnvParserPath = relative(\n dirname(appPath),\n context.envParserPath,\n );\n\n const 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 ${context.envParserImportPattern} from '${relativeEnvParserPath}';\nimport ${context.loggerImportPattern} from '${relativeLoggerPath}';\n\nexport 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 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 } = 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 } = createApp();\n *\n * await start({\n * port: 3000,\n * serve: (app, port) => {\n * serve({ fetch: app.fetch, port });\n * }\n * });\n */\nexport function createApp(app?: HonoType, enableOpenApi: boolean = true): ServerApp {\n const honoApp = app || new Hono();\n\n // Setup HTTP endpoints\n setupEndpoints(honoApp, envParser, logger, enableOpenApi);\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 // Start subscribers in background (non-blocking, local development only)\n await setupSubscribers(envParser, logger).catch((error) => {\n logger.error({ error }, 'Failed to start subscribers');\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 };\n}\n\n// Default export for convenience\nexport default createApp;\n`;\n\n await writeFile(appPath, content);\n\n return appPath;\n }\n\n private generateAWSApiGatewayV1Handler(\n importPath: string,\n exportName: string,\n envParserPath: string,\n envParserImportPattern: string,\n ): string {\n return `import { AmazonApiGatewayV1Endpoint } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\nimport ${envParserImportPattern} from '${envParserPath}';\n\nconst adapter = new AmazonApiGatewayV1Endpoint(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n }\n\n private generateAWSApiGatewayV2Handler(\n importPath: string,\n exportName: string,\n envParserPath: string,\n envParserImportPattern: string,\n ): string {\n return `import { AmazonApiGatewayV2Endpoint } from '@geekmidas/constructs/aws';\nimport { ${exportName} } from '${importPath}';\nimport ${envParserImportPattern} from '${envParserPath}';\n\nconst adapter = new AmazonApiGatewayV2Endpoint(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n }\n\n private generateServerHandler(\n importPath: string,\n exportName: string,\n ): string {\n return `import { ${exportName} } from '${importPath}';\n\n// Server handler - implement based on your server framework\nexport const handler = ${exportName};\n`;\n }\n}\n"],"mappings":";;;;;;AAWA,IAAa,oBAAb,cAAuC,mBAGrC;CACA,YAAYA,OAA6D;AACvE,SAAO,SAAS,WAAW,MAAM;CAClC;CAED,MAAM,MACJC,SACAC,YACAC,WACAC,SACsB;EACtB,MAAM,WAAW,SAAS,YAAY;EACtC,MAAM,gBAAgB,SAAS,iBAAiB;EAChD,MAAM,SAAS;EACf,MAAMC,SAAsB,CAAE;AAE9B,MAAI,WAAW,WAAW,EACxB,QAAO;AAGT,MAAI,aAAa,UAAU;AAEzB,SAAM,KAAK,sBAAsB,WAAW,YAAY,QAAQ;GAChE,MAAM,UAAU,MAAM,KAAK,gBAAgB,WAAW,QAAQ;AAE9D,UAAO,KAAK;IACV,MAAM;IACN,QAAQ;IACR,SAAS,SAAS,QAAQ,KAAK,EAAE,QAAQ;GAC1C,EAAC;AAEF,UAAO,KACJ,wBAAwB,WAAW,OAAO,YAAY,gBAAgB,uBAAuB,GAAG,EAClG;EACF,WAAU,aAAa,cAAc;GAEpC,MAAM,YAAY,KAAK,WAAW,SAAS;AAC3C,SAAM,MAAM,WAAW,EAAE,WAAW,KAAM,EAAC;AAG3C,QAAK,MAAM,EAAE,KAAK,WAAW,MAAM,IAAI,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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkF7D,QAAM,UAAU,SAAS,QAAQ;AAEjC,SAAO;CACR;CAED,AAAQ,+BACNY,YACAL,YACAM,eACAC,wBACQ;AACR,UAAQ;WACD,WAAW,WAAW,WAAW;SACnC,uBAAuB,SAAS,cAAc;;4DAEK,WAAW;;;;CAIpE;CAED,AAAQ,+BACNF,YACAL,YACAM,eACAC,wBACQ;AACR,UAAQ;WACD,WAAW,WAAW,WAAW;SACnC,uBAAuB,SAAS,cAAc;;4DAEK,WAAW;;;;CAIpE;CAED,AAAQ,sBACNF,YACAL,YACQ;AACR,UAAQ,WAAW,WAAW,WAAW,WAAW;;;yBAG/B,WAAW;;CAEjC;AACF"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const require_chunk = require('./chunk-CUT6urMc.cjs');
|
|
2
|
+
const require_Generator = require('./Generator-CDoEXCDg.cjs');
|
|
3
|
+
const node_fs_promises = require_chunk.__toESM(require("node:fs/promises"));
|
|
4
|
+
const node_path = require_chunk.__toESM(require("node:path"));
|
|
5
|
+
const __geekmidas_constructs_functions = require_chunk.__toESM(require("@geekmidas/constructs/functions"));
|
|
6
|
+
|
|
7
|
+
//#region src/generators/FunctionGenerator.ts
|
|
8
|
+
var FunctionGenerator = class extends require_Generator.ConstructGenerator {
|
|
9
|
+
isConstruct(value) {
|
|
10
|
+
return __geekmidas_constructs_functions.Function.isFunction(value);
|
|
11
|
+
}
|
|
12
|
+
async build(context, constructs, outputDir, options) {
|
|
13
|
+
const provider = options?.provider || "aws-lambda";
|
|
14
|
+
const logger = console;
|
|
15
|
+
const functionInfos = [];
|
|
16
|
+
if (constructs.length === 0 || provider !== "aws-lambda") return functionInfos;
|
|
17
|
+
const functionsDir = (0, node_path.join)(outputDir, "functions");
|
|
18
|
+
await (0, node_fs_promises.mkdir)(functionsDir, { recursive: true });
|
|
19
|
+
for (const { key, construct, path } of constructs) {
|
|
20
|
+
const handlerFile = await this.generateFunctionHandler(functionsDir, path.relative, key, context);
|
|
21
|
+
functionInfos.push({
|
|
22
|
+
name: key,
|
|
23
|
+
handler: (0, node_path.relative)(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
24
|
+
timeout: construct.timeout,
|
|
25
|
+
environment: await construct.getEnvironment()
|
|
26
|
+
});
|
|
27
|
+
logger.log(`Generated function handler: ${key}`);
|
|
28
|
+
}
|
|
29
|
+
return functionInfos;
|
|
30
|
+
}
|
|
31
|
+
async generateFunctionHandler(outputDir, sourceFile, exportName, context) {
|
|
32
|
+
const handlerFileName = `${exportName}.ts`;
|
|
33
|
+
const handlerPath = (0, node_path.join)(outputDir, handlerFileName);
|
|
34
|
+
const relativePath = (0, node_path.relative)((0, node_path.dirname)(handlerPath), sourceFile);
|
|
35
|
+
const importPath = relativePath.replace(/\.ts$/, ".js");
|
|
36
|
+
const relativeEnvParserPath = (0, node_path.relative)((0, node_path.dirname)(handlerPath), context.envParserPath);
|
|
37
|
+
const relativeLoggerPath = (0, node_path.relative)((0, node_path.dirname)(handlerPath), context.loggerPath);
|
|
38
|
+
const content = `import { AWSLambdaFunction } from '@geekmidas/constructs/functions';
|
|
39
|
+
import { ${exportName} } from '${importPath}';
|
|
40
|
+
import ${context.envParserImportPattern} from '${relativeEnvParserPath}';
|
|
41
|
+
import ${context.loggerImportPattern} from '${relativeLoggerPath}';
|
|
42
|
+
|
|
43
|
+
const adapter = new AWSLambdaFunction(envParser, ${exportName});
|
|
44
|
+
|
|
45
|
+
export const handler = adapter.handler;
|
|
46
|
+
`;
|
|
47
|
+
await (0, node_fs_promises.writeFile)(handlerPath, content);
|
|
48
|
+
return handlerPath;
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
//#endregion
|
|
53
|
+
Object.defineProperty(exports, 'FunctionGenerator', {
|
|
54
|
+
enumerable: true,
|
|
55
|
+
get: function () {
|
|
56
|
+
return FunctionGenerator;
|
|
57
|
+
}
|
|
58
|
+
});
|
|
59
|
+
//# sourceMappingURL=FunctionGenerator-Clw64SwQ.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"FunctionGenerator-Clw64SwQ.cjs","names":["ConstructGenerator","value: any","context: BuildContext","constructs: GeneratedConstruct<Function<any, any, any, any>>[]","outputDir: string","options?: GeneratorOptions","functionInfos: FunctionInfo[]","sourceFile: string","exportName: string"],"sources":["../src/generators/FunctionGenerator.ts"],"sourcesContent":["import { mkdir, writeFile } from 'node:fs/promises';\nimport { dirname, join, relative } from 'node:path';\nimport { Function } from '@geekmidas/constructs/functions';\nimport type { BuildContext } from '../build/types';\nimport type { FunctionInfo } from '../types';\nimport {\n ConstructGenerator,\n type GeneratedConstruct,\n type GeneratorOptions,\n} from './Generator';\n\nexport class FunctionGenerator extends ConstructGenerator<\n Function<any, any, any, any>,\n FunctionInfo[]\n> {\n isConstruct(value: any): value is Function<any, any, any, any> {\n return Function.isFunction(value);\n }\n\n async build(\n context: BuildContext,\n constructs: GeneratedConstruct<Function<any, any, any, any>>[],\n outputDir: string,\n options?: GeneratorOptions,\n ): Promise<FunctionInfo[]> {\n const provider = options?.provider || 'aws-lambda';\n const logger = console;\n const functionInfos: FunctionInfo[] = [];\n\n if (constructs.length === 0 || provider !== 'aws-lambda') {\n return functionInfos;\n }\n\n // Create functions subdirectory\n const functionsDir = join(outputDir, 'functions');\n await mkdir(functionsDir, { recursive: true });\n\n // Generate function handlers\n for (const { key, construct, path } of constructs) {\n const handlerFile = await this.generateFunctionHandler(\n functionsDir,\n path.relative,\n key,\n context,\n );\n\n functionInfos.push({\n name: key,\n handler: relative(process.cwd(), handlerFile).replace(\n /\\.ts$/,\n '.handler',\n ),\n timeout: construct.timeout,\n environment: await construct.getEnvironment(),\n });\n\n logger.log(`Generated function handler: ${key}`);\n }\n\n return functionInfos;\n }\n\n private async generateFunctionHandler(\n outputDir: string,\n sourceFile: string,\n exportName: string,\n context: BuildContext,\n ): Promise<string> {\n const handlerFileName = `${exportName}.ts`;\n const handlerPath = join(outputDir, handlerFileName);\n\n const relativePath = relative(dirname(handlerPath), sourceFile);\n const importPath = relativePath.replace(/\\.ts$/, '.js');\n\n const relativeEnvParserPath = relative(\n dirname(handlerPath),\n context.envParserPath,\n );\n const relativeLoggerPath = relative(\n dirname(handlerPath),\n context.loggerPath,\n );\n\n const content = `import { AWSLambdaFunction } from '@geekmidas/constructs/functions';\nimport { ${exportName} } from '${importPath}';\nimport ${context.envParserImportPattern} from '${relativeEnvParserPath}';\nimport ${context.loggerImportPattern} from '${relativeLoggerPath}';\n\nconst adapter = new AWSLambdaFunction(envParser, ${exportName});\n\nexport const handler = adapter.handler;\n`;\n\n await writeFile(handlerPath, content);\n return handlerPath;\n }\n}\n"],"mappings":";;;;;;;AAWA,IAAa,oBAAb,cAAuCA,qCAGrC;CACA,YAAYC,OAAmD;AAC7D,SAAO,0CAAS,WAAW,MAAM;CAClC;CAED,MAAM,MACJC,SACAC,YACAC,WACAC,SACyB;EACzB,MAAM,WAAW,SAAS,YAAY;EACtC,MAAM,SAAS;EACf,MAAMC,gBAAgC,CAAE;AAExC,MAAI,WAAW,WAAW,KAAK,aAAa,aAC1C,QAAO;EAIT,MAAM,eAAe,oBAAK,WAAW,YAAY;AACjD,QAAM,4BAAM,cAAc,EAAE,WAAW,KAAM,EAAC;AAG9C,OAAK,MAAM,EAAE,KAAK,WAAW,MAAM,IAAI,YAAY;GACjD,MAAM,cAAc,MAAM,KAAK,wBAC7B,cACA,KAAK,UACL,KACA,QACD;AAED,iBAAc,KAAK;IACjB,MAAM;IACN,SAAS,wBAAS,QAAQ,KAAK,EAAE,YAAY,CAAC,QAC5C,SACA,WACD;IACD,SAAS,UAAU;IACnB,aAAa,MAAM,UAAU,gBAAgB;GAC9C,EAAC;AAEF,UAAO,KAAK,8BAA8B,IAAI,EAAE;EACjD;AAED,SAAO;CACR;CAED,MAAc,wBACZF,WACAG,YACAC,YACAN,SACiB;EACjB,MAAM,mBAAmB,EAAE,WAAW;EAC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