@geekmidas/cli 0.6.2 → 0.7.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/dist/config.d.cts +1 -1
- package/dist/config.d.mts +1 -1
- package/dist/index.cjs +2561 -34
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +2556 -29
- package/dist/index.mjs.map +1 -1
- package/dist/openapi-Mwy2_R4W.mjs +957 -0
- package/dist/openapi-Mwy2_R4W.mjs.map +1 -0
- package/dist/{openapi-react-query-_-B3s8v_.mjs → openapi-react-query-CcciaVu5.mjs} +1 -1
- package/dist/{openapi-react-query-_-B3s8v_.mjs.map → openapi-react-query-CcciaVu5.mjs.map} +1 -1
- package/dist/{openapi-react-query-Cp-w8_05.cjs → openapi-react-query-o5iMi8tz.cjs} +1 -1
- package/dist/{openapi-react-query-Cp-w8_05.cjs.map → openapi-react-query-o5iMi8tz.cjs.map} +1 -1
- package/dist/openapi-react-query.cjs +1 -1
- package/dist/openapi-react-query.mjs +1 -1
- package/dist/openapi-tAIbJJU_.cjs +993 -0
- package/dist/openapi-tAIbJJU_.cjs.map +1 -0
- package/dist/openapi.cjs +1 -4
- package/dist/openapi.d.cts +1 -1
- package/dist/openapi.d.mts +1 -1
- package/dist/openapi.mjs +1 -4
- package/dist/{types-Bi7VzDUZ.d.mts → types-B3TXoj7v.d.mts} +21 -53
- package/dist/{types-KmjzMgu8.d.cts → types-C0hwnSjm.d.cts} +21 -53
- package/package.json +5 -5
- package/src/build/types.ts +13 -0
- package/src/dev/index.ts +71 -8
- package/src/generators/EndpointGenerator.ts +46 -5
- package/src/generators/__tests__/EndpointGenerator.spec.ts +1 -1
- package/src/init/generators/config.ts +6 -1
- package/src/init/generators/package.ts +5 -1
- package/src/init/index.ts +9 -1
- package/src/init/templates/api.ts +31 -0
- package/src/init/templates/index.ts +1 -0
- package/src/init/templates/minimal.ts +83 -0
- package/src/types.ts +19 -0
- package/tsdown.config.ts +6 -0
- package/dist/CronGenerator-CCRYptuT.mjs +0 -55
- package/dist/CronGenerator-CCRYptuT.mjs.map +0 -1
- package/dist/CronGenerator-D4TWXQbh.cjs +0 -61
- package/dist/CronGenerator-D4TWXQbh.cjs.map +0 -1
- package/dist/CronGenerator-DWS3CCZt.d.cts +0 -14
- package/dist/CronGenerator-DZjdkEjI.d.mts +0 -14
- package/dist/EndpointGenerator-DGivkPLT.mjs +0 -335
- package/dist/EndpointGenerator-DGivkPLT.mjs.map +0 -1
- package/dist/EndpointGenerator-Dh7kMtuL.d.mts +0 -19
- package/dist/EndpointGenerator-npWEDoK2.cjs +0 -341
- package/dist/EndpointGenerator-npWEDoK2.cjs.map +0 -1
- package/dist/EndpointGenerator-zBsie_7s.d.cts +0 -19
- package/dist/FunctionGenerator-BmDHo27U.d.mts +0 -14
- package/dist/FunctionGenerator-CVk0h8tO.mjs +0 -54
- package/dist/FunctionGenerator-CVk0h8tO.mjs.map +0 -1
- package/dist/FunctionGenerator-DXjXBxUd.d.cts +0 -14
- package/dist/FunctionGenerator-DYTnyr4c.cjs +0 -60
- package/dist/FunctionGenerator-DYTnyr4c.cjs.map +0 -1
- package/dist/Generator-BGY-2dgI.d.cts +0 -27
- package/dist/Generator-CDt4pB3W.mjs +0 -41
- package/dist/Generator-CDt4pB3W.mjs.map +0 -1
- package/dist/Generator-CLVplqm2.cjs +0 -47
- package/dist/Generator-CLVplqm2.cjs.map +0 -1
- package/dist/Generator-yi9DH5TN.d.mts +0 -27
- package/dist/OpenApiTsGenerator-BVS4pOH7.mjs +0 -495
- package/dist/OpenApiTsGenerator-BVS4pOH7.mjs.map +0 -1
- package/dist/OpenApiTsGenerator-gPIIyppX.cjs +0 -501
- package/dist/OpenApiTsGenerator-gPIIyppX.cjs.map +0 -1
- package/dist/SubscriberGenerator-Bb-z3Kvx.d.cts +0 -15
- package/dist/SubscriberGenerator-CwsXqCpS.d.mts +0 -15
- package/dist/SubscriberGenerator-DABaJXML.mjs +0 -200
- package/dist/SubscriberGenerator-DABaJXML.mjs.map +0 -1
- package/dist/SubscriberGenerator-D_zpNGFr.cjs +0 -206
- package/dist/SubscriberGenerator-D_zpNGFr.cjs.map +0 -1
- package/dist/api-Bp5TIl1R.mjs +0 -167
- package/dist/api-Bp5TIl1R.mjs.map +0 -1
- package/dist/api-D4W9-tdZ.cjs +0 -173
- package/dist/api-D4W9-tdZ.cjs.map +0 -1
- package/dist/build/index.cjs +0 -15
- package/dist/build/index.d.cts +0 -7
- package/dist/build/index.d.mts +0 -7
- package/dist/build/index.mjs +0 -15
- package/dist/build/manifests.cjs +0 -4
- package/dist/build/manifests.d.cts +0 -13
- package/dist/build/manifests.d.mts +0 -13
- package/dist/build/manifests.mjs +0 -3
- package/dist/build/providerResolver.cjs +0 -5
- package/dist/build/providerResolver.d.cts +0 -23
- package/dist/build/providerResolver.d.mts +0 -23
- package/dist/build/providerResolver.mjs +0 -3
- package/dist/build/types.cjs +0 -0
- package/dist/build/types.d.cts +0 -3
- package/dist/build/types.d.mts +0 -3
- package/dist/build/types.mjs +0 -0
- package/dist/build-Cu6Mi0Lf.mjs +0 -87
- package/dist/build-Cu6Mi0Lf.mjs.map +0 -1
- package/dist/build-wmt8ZcmA.cjs +0 -93
- package/dist/build-wmt8ZcmA.cjs.map +0 -1
- package/dist/config-BP1IZynR.cjs +0 -168
- package/dist/config-BP1IZynR.cjs.map +0 -1
- package/dist/config-CIzRhm_D.d.mts +0 -11
- package/dist/config-CvehIYsb.d.cts +0 -11
- package/dist/config-UCK12Lrr.mjs +0 -162
- package/dist/config-UCK12Lrr.mjs.map +0 -1
- package/dist/dev/index.cjs +0 -17
- package/dist/dev/index.d.cts +0 -36
- package/dist/dev/index.d.mts +0 -36
- package/dist/dev/index.mjs +0 -13
- package/dist/dev-BBPWSllq.mjs +0 -348
- package/dist/dev-BBPWSllq.mjs.map +0 -1
- package/dist/dev-C2lCgE53.cjs +0 -378
- package/dist/dev-C2lCgE53.cjs.map +0 -1
- package/dist/docker-2-ipZDOJ.cjs +0 -119
- package/dist/docker-2-ipZDOJ.cjs.map +0 -1
- package/dist/docker-31GNwU3F.mjs +0 -113
- package/dist/docker-31GNwU3F.mjs.map +0 -1
- package/dist/env-CQ3hXAAW.d.mts +0 -11
- package/dist/env-CS0jvg7k.cjs +0 -144
- package/dist/env-CS0jvg7k.cjs.map +0 -1
- package/dist/env-D4YFgMqo.d.cts +0 -11
- package/dist/env-DEeVOvVu.mjs +0 -138
- package/dist/env-DEeVOvVu.mjs.map +0 -1
- package/dist/generators/CronGenerator.cjs +0 -4
- package/dist/generators/CronGenerator.d.cts +0 -5
- package/dist/generators/CronGenerator.d.mts +0 -5
- package/dist/generators/CronGenerator.mjs +0 -4
- package/dist/generators/EndpointGenerator.cjs +0 -4
- package/dist/generators/EndpointGenerator.d.cts +0 -5
- package/dist/generators/EndpointGenerator.d.mts +0 -5
- package/dist/generators/EndpointGenerator.mjs +0 -4
- package/dist/generators/FunctionGenerator.cjs +0 -4
- package/dist/generators/FunctionGenerator.d.cts +0 -5
- package/dist/generators/FunctionGenerator.d.mts +0 -5
- package/dist/generators/FunctionGenerator.mjs +0 -4
- package/dist/generators/Generator.cjs +0 -3
- package/dist/generators/Generator.d.cts +0 -4
- package/dist/generators/Generator.d.mts +0 -4
- package/dist/generators/Generator.mjs +0 -3
- package/dist/generators/OpenApiTsGenerator.cjs +0 -3
- package/dist/generators/OpenApiTsGenerator.d.cts +0 -44
- package/dist/generators/OpenApiTsGenerator.d.mts +0 -44
- package/dist/generators/OpenApiTsGenerator.mjs +0 -3
- package/dist/generators/SubscriberGenerator.cjs +0 -4
- package/dist/generators/SubscriberGenerator.d.cts +0 -5
- package/dist/generators/SubscriberGenerator.d.mts +0 -5
- package/dist/generators/SubscriberGenerator.mjs +0 -4
- package/dist/generators/index.cjs +0 -12
- package/dist/generators/index.d.cts +0 -8
- package/dist/generators/index.d.mts +0 -8
- package/dist/generators/index.mjs +0 -8
- package/dist/generators-3IemvCLk.cjs +0 -0
- package/dist/generators-FNpdfN6J.mjs +0 -0
- package/dist/index-DG6xNQMH.d.cts +0 -81
- package/dist/index-DZgrOOOW.d.mts +0 -81
- package/dist/init/generators/config.cjs +0 -3
- package/dist/init/generators/config.d.cts +0 -3
- package/dist/init/generators/config.d.mts +0 -3
- package/dist/init/generators/config.mjs +0 -3
- package/dist/init/generators/docker.cjs +0 -3
- package/dist/init/generators/docker.d.cts +0 -11
- package/dist/init/generators/docker.d.mts +0 -11
- package/dist/init/generators/docker.mjs +0 -3
- package/dist/init/generators/env.cjs +0 -3
- package/dist/init/generators/env.d.cts +0 -3
- package/dist/init/generators/env.d.mts +0 -3
- package/dist/init/generators/env.mjs +0 -3
- package/dist/init/generators/index.cjs +0 -14
- package/dist/init/generators/index.d.cts +0 -6
- package/dist/init/generators/index.d.mts +0 -6
- package/dist/init/generators/index.mjs +0 -11
- package/dist/init/generators/models.cjs +0 -3
- package/dist/init/generators/models.d.cts +0 -11
- package/dist/init/generators/models.d.mts +0 -11
- package/dist/init/generators/models.mjs +0 -3
- package/dist/init/generators/monorepo.cjs +0 -3
- package/dist/init/generators/monorepo.d.cts +0 -11
- package/dist/init/generators/monorepo.d.mts +0 -11
- package/dist/init/generators/monorepo.mjs +0 -3
- package/dist/init/generators/package.cjs +0 -8
- package/dist/init/generators/package.d.cts +0 -3
- package/dist/init/generators/package.d.mts +0 -3
- package/dist/init/generators/package.mjs +0 -8
- package/dist/init/generators/source.cjs +0 -3
- package/dist/init/generators/source.d.cts +0 -3
- package/dist/init/generators/source.d.mts +0 -3
- package/dist/init/generators/source.mjs +0 -3
- package/dist/init/index.cjs +0 -16
- package/dist/init/index.d.cts +0 -17
- package/dist/init/index.d.mts +0 -17
- package/dist/init/index.mjs +0 -16
- package/dist/init/templates/api.cjs +0 -3
- package/dist/init/templates/api.d.cts +0 -7
- package/dist/init/templates/api.d.mts +0 -7
- package/dist/init/templates/api.mjs +0 -3
- package/dist/init/templates/index.cjs +0 -12
- package/dist/init/templates/index.d.cts +0 -2
- package/dist/init/templates/index.d.mts +0 -2
- package/dist/init/templates/index.mjs +0 -7
- package/dist/init/templates/minimal.cjs +0 -3
- package/dist/init/templates/minimal.d.cts +0 -7
- package/dist/init/templates/minimal.d.mts +0 -7
- package/dist/init/templates/minimal.mjs +0 -3
- package/dist/init/templates/serverless.cjs +0 -3
- package/dist/init/templates/serverless.d.cts +0 -7
- package/dist/init/templates/serverless.d.mts +0 -7
- package/dist/init/templates/serverless.mjs +0 -3
- package/dist/init/templates/worker.cjs +0 -3
- package/dist/init/templates/worker.d.cts +0 -7
- package/dist/init/templates/worker.d.mts +0 -7
- package/dist/init/templates/worker.mjs +0 -3
- package/dist/init/utils.cjs +0 -7
- package/dist/init/utils.d.cts +0 -25
- package/dist/init/utils.d.mts +0 -25
- package/dist/init/utils.mjs +0 -3
- package/dist/init-BMA7xi8r.mjs +0 -161
- package/dist/init-BMA7xi8r.mjs.map +0 -1
- package/dist/init-D-7WEk-b.cjs +0 -167
- package/dist/init-D-7WEk-b.cjs.map +0 -1
- package/dist/manifests-BNKG6AXf.mjs +0 -68
- package/dist/manifests-BNKG6AXf.mjs.map +0 -1
- package/dist/manifests-D13Ej8AE.cjs +0 -80
- package/dist/manifests-D13Ej8AE.cjs.map +0 -1
- package/dist/minimal-BkyASH_C.mjs +0 -93
- package/dist/minimal-BkyASH_C.mjs.map +0 -1
- package/dist/minimal-CSFggzdH.cjs +0 -99
- package/dist/minimal-CSFggzdH.cjs.map +0 -1
- package/dist/models-BWlDfviw.mjs +0 -115
- package/dist/models-BWlDfviw.mjs.map +0 -1
- package/dist/models-BapGSoHC.cjs +0 -121
- package/dist/models-BapGSoHC.cjs.map +0 -1
- package/dist/monorepo-BBOWhkcd.mjs +0 -184
- package/dist/monorepo-BBOWhkcd.mjs.map +0 -1
- package/dist/monorepo-CFtxHeDh.cjs +0 -190
- package/dist/monorepo-CFtxHeDh.cjs.map +0 -1
- package/dist/openapi-DA9RkPJl.mjs +0 -74
- package/dist/openapi-DA9RkPJl.mjs.map +0 -1
- package/dist/openapi-DZH6RQHk.cjs +0 -98
- package/dist/openapi-DZH6RQHk.cjs.map +0 -1
- package/dist/package-6h-7QfJZ.d.cts +0 -11
- package/dist/package-BCe_KvGv.d.mts +0 -11
- package/dist/package-C3If80n1.mjs +0 -57
- package/dist/package-C3If80n1.mjs.map +0 -1
- package/dist/package-Dk8IMBOB.cjs +0 -62
- package/dist/package-Dk8IMBOB.cjs.map +0 -1
- package/dist/providerResolver-DEVKngbC.mjs +0 -96
- package/dist/providerResolver-DEVKngbC.mjs.map +0 -1
- package/dist/providerResolver-DOTbN9jo.cjs +0 -114
- package/dist/providerResolver-DOTbN9jo.cjs.map +0 -1
- package/dist/serverless-AGOS-l3G.cjs +0 -119
- package/dist/serverless-AGOS-l3G.cjs.map +0 -1
- package/dist/serverless-D5HjJByU.mjs +0 -113
- package/dist/serverless-D5HjJByU.mjs.map +0 -1
- package/dist/source-C1cyfHcF.cjs +0 -17
- package/dist/source-C1cyfHcF.cjs.map +0 -1
- package/dist/source-C3LiNUV9.d.mts +0 -11
- package/dist/source-CkQHBpwu.mjs +0 -11
- package/dist/source-CkQHBpwu.mjs.map +0 -1
- package/dist/source-Dtcjbokc.d.cts +0 -11
- package/dist/templates-C0EMmhwb.mjs +0 -88
- package/dist/templates-C0EMmhwb.mjs.map +0 -1
- package/dist/templates-CbgQ9dw0.cjs +0 -123
- package/dist/templates-CbgQ9dw0.cjs.map +0 -1
- package/dist/types-D2xYkOal.d.mts +0 -51
- package/dist/types-DA-r8HWZ.d.cts +0 -51
- package/dist/types.cjs +0 -0
- package/dist/types.d.cts +0 -2
- package/dist/types.d.mts +0 -2
- package/dist/types.mjs +0 -0
- package/dist/utils-CKEzCxc1.mjs +0 -69
- package/dist/utils-CKEzCxc1.mjs.map +0 -1
- package/dist/utils-DSdN2MTt.cjs +0 -99
- package/dist/utils-DSdN2MTt.cjs.map +0 -1
- package/dist/worker-CGhlqNH-.cjs +0 -156
- package/dist/worker-CGhlqNH-.cjs.map +0 -1
- package/dist/worker-CiP420As.mjs +0 -150
- package/dist/worker-CiP420As.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,37 +1,25 @@
|
|
|
1
1
|
#!/usr/bin/env -S npx tsx
|
|
2
|
-
import "./config-Bq72aj8e.mjs";
|
|
3
|
-
import "./
|
|
4
|
-
import "./
|
|
5
|
-
import "
|
|
6
|
-
import "./EndpointGenerator-DGivkPLT.mjs";
|
|
7
|
-
import "./FunctionGenerator-CVk0h8tO.mjs";
|
|
8
|
-
import "./SubscriberGenerator-DABaJXML.mjs";
|
|
9
|
-
import "./generators-FNpdfN6J.mjs";
|
|
10
|
-
import "./OpenApiTsGenerator-BVS4pOH7.mjs";
|
|
11
|
-
import { openapiCommand } from "./openapi-DA9RkPJl.mjs";
|
|
12
|
-
import { devCommand } from "./dev-BBPWSllq.mjs";
|
|
13
|
-
import "./manifests-BNKG6AXf.mjs";
|
|
14
|
-
import { buildCommand } from "./build-Cu6Mi0Lf.mjs";
|
|
15
|
-
import "./config-UCK12Lrr.mjs";
|
|
16
|
-
import "./docker-31GNwU3F.mjs";
|
|
17
|
-
import "./env-DEeVOvVu.mjs";
|
|
18
|
-
import "./models-BWlDfviw.mjs";
|
|
19
|
-
import "./monorepo-BBOWhkcd.mjs";
|
|
20
|
-
import "./api-Bp5TIl1R.mjs";
|
|
21
|
-
import "./minimal-BkyASH_C.mjs";
|
|
22
|
-
import "./serverless-D5HjJByU.mjs";
|
|
23
|
-
import "./worker-CiP420As.mjs";
|
|
24
|
-
import "./templates-C0EMmhwb.mjs";
|
|
25
|
-
import "./package-C3If80n1.mjs";
|
|
26
|
-
import "./source-CkQHBpwu.mjs";
|
|
27
|
-
import "./utils-CKEzCxc1.mjs";
|
|
28
|
-
import { initCommand } from "./init-BMA7xi8r.mjs";
|
|
29
|
-
import { generateReactQueryCommand } from "./openapi-react-query-_-B3s8v_.mjs";
|
|
2
|
+
import { loadConfig, parseModuleConfig } from "./config-Bq72aj8e.mjs";
|
|
3
|
+
import { ConstructGenerator, EndpointGenerator, generateOpenApi, openapiCommand, resolveOpenApiConfig } from "./openapi-Mwy2_R4W.mjs";
|
|
4
|
+
import { generateReactQueryCommand } from "./openapi-react-query-CcciaVu5.mjs";
|
|
5
|
+
import { join, relative } from "path";
|
|
30
6
|
import { Command } from "commander";
|
|
7
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
8
|
+
import { dirname, join as join$1, relative as relative$1, resolve } from "node:path";
|
|
9
|
+
import { execSync, spawn } from "node:child_process";
|
|
10
|
+
import { existsSync } from "node:fs";
|
|
11
|
+
import { createServer } from "node:net";
|
|
12
|
+
import chokidar from "chokidar";
|
|
13
|
+
import { config } from "dotenv";
|
|
14
|
+
import fg from "fast-glob";
|
|
15
|
+
import { Cron } from "@geekmidas/constructs/crons";
|
|
16
|
+
import { Function } from "@geekmidas/constructs/functions";
|
|
17
|
+
import { Subscriber } from "@geekmidas/constructs/subscribers";
|
|
18
|
+
import prompts from "prompts";
|
|
31
19
|
|
|
32
20
|
//#region package.json
|
|
33
21
|
var name = "@geekmidas/cli";
|
|
34
|
-
var version = "0.
|
|
22
|
+
var version = "0.7.0";
|
|
35
23
|
var description = "CLI tools for building Lambda handlers, server applications, and generating OpenAPI specs";
|
|
36
24
|
var private$1 = false;
|
|
37
25
|
var type = "module";
|
|
@@ -111,6 +99,2545 @@ var package_default = {
|
|
|
111
99
|
peerDependenciesMeta
|
|
112
100
|
};
|
|
113
101
|
|
|
102
|
+
//#endregion
|
|
103
|
+
//#region src/build/providerResolver.ts
|
|
104
|
+
/**
|
|
105
|
+
* Resolves provider configuration from the new simplified system
|
|
106
|
+
* to the internal legacy format for backward compatibility
|
|
107
|
+
*/
|
|
108
|
+
function resolveProviders(config$1, options) {
|
|
109
|
+
const providers = [];
|
|
110
|
+
let enableOpenApi = options.enableOpenApi || false;
|
|
111
|
+
if (options.providers) return {
|
|
112
|
+
providers: options.providers,
|
|
113
|
+
enableOpenApi
|
|
114
|
+
};
|
|
115
|
+
if (options.provider) {
|
|
116
|
+
const resolvedProviders = resolveMainProvider(options.provider, config$1.providers);
|
|
117
|
+
providers.push(...resolvedProviders.providers);
|
|
118
|
+
enableOpenApi = resolvedProviders.enableOpenApi || enableOpenApi;
|
|
119
|
+
} else if (config$1.providers) {
|
|
120
|
+
const resolvedProviders = resolveAllConfiguredProviders(config$1.providers);
|
|
121
|
+
providers.push(...resolvedProviders.providers);
|
|
122
|
+
enableOpenApi = resolvedProviders.enableOpenApi || enableOpenApi;
|
|
123
|
+
} else providers.push("aws-apigatewayv2", "aws-lambda");
|
|
124
|
+
return {
|
|
125
|
+
providers: [...new Set(providers)],
|
|
126
|
+
enableOpenApi
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
function resolveMainProvider(mainProvider, providersConfig) {
|
|
130
|
+
const providers = [];
|
|
131
|
+
let enableOpenApi = false;
|
|
132
|
+
if (mainProvider === "aws") {
|
|
133
|
+
const awsConfig = providersConfig?.aws;
|
|
134
|
+
if (awsConfig?.apiGateway) {
|
|
135
|
+
if (isEnabled(awsConfig.apiGateway.v1)) providers.push("aws-apigatewayv1");
|
|
136
|
+
if (isEnabled(awsConfig.apiGateway.v2)) providers.push("aws-apigatewayv2");
|
|
137
|
+
} else providers.push("aws-apigatewayv2");
|
|
138
|
+
if (awsConfig?.lambda) {
|
|
139
|
+
if (isEnabled(awsConfig.lambda.functions) || isEnabled(awsConfig.lambda.crons)) providers.push("aws-lambda");
|
|
140
|
+
} else providers.push("aws-lambda");
|
|
141
|
+
} else if (mainProvider === "server") {
|
|
142
|
+
providers.push("server");
|
|
143
|
+
const serverConfig = providersConfig?.server;
|
|
144
|
+
if (typeof serverConfig === "object" && serverConfig?.enableOpenApi) enableOpenApi = true;
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
providers,
|
|
148
|
+
enableOpenApi
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function resolveAllConfiguredProviders(providersConfig) {
|
|
152
|
+
const providers = [];
|
|
153
|
+
let enableOpenApi = false;
|
|
154
|
+
if (providersConfig.aws) {
|
|
155
|
+
const awsProviders = resolveMainProvider("aws", providersConfig);
|
|
156
|
+
providers.push(...awsProviders.providers);
|
|
157
|
+
}
|
|
158
|
+
if (providersConfig.server && isEnabled(providersConfig.server)) {
|
|
159
|
+
providers.push("server");
|
|
160
|
+
if (typeof providersConfig.server === "object" && providersConfig.server.enableOpenApi) enableOpenApi = true;
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
providers,
|
|
164
|
+
enableOpenApi
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
function isEnabled(config$1) {
|
|
168
|
+
if (config$1 === void 0) return false;
|
|
169
|
+
if (typeof config$1 === "boolean") return config$1;
|
|
170
|
+
return config$1.enabled !== false;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
//#endregion
|
|
174
|
+
//#region src/generators/CronGenerator.ts
|
|
175
|
+
var CronGenerator = class extends ConstructGenerator {
|
|
176
|
+
async build(context, constructs, outputDir, options) {
|
|
177
|
+
const provider = options?.provider || "aws-lambda";
|
|
178
|
+
const logger$3 = console;
|
|
179
|
+
const cronInfos = [];
|
|
180
|
+
if (constructs.length === 0 || provider !== "aws-lambda") return cronInfos;
|
|
181
|
+
const cronsDir = join$1(outputDir, "crons");
|
|
182
|
+
await mkdir(cronsDir, { recursive: true });
|
|
183
|
+
for (const { key, construct, path } of constructs) {
|
|
184
|
+
const handlerFile = await this.generateCronHandler(cronsDir, path.relative, key, context);
|
|
185
|
+
cronInfos.push({
|
|
186
|
+
name: key,
|
|
187
|
+
handler: relative$1(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
188
|
+
schedule: construct.schedule || "rate(1 hour)",
|
|
189
|
+
timeout: construct.timeout,
|
|
190
|
+
memorySize: construct.memorySize,
|
|
191
|
+
environment: await construct.getEnvironment()
|
|
192
|
+
});
|
|
193
|
+
logger$3.log(`Generated cron handler: ${key}`);
|
|
194
|
+
}
|
|
195
|
+
return cronInfos;
|
|
196
|
+
}
|
|
197
|
+
isConstruct(value) {
|
|
198
|
+
return Cron.isCron(value);
|
|
199
|
+
}
|
|
200
|
+
async generateCronHandler(outputDir, sourceFile, exportName, context) {
|
|
201
|
+
const handlerFileName = `${exportName}.ts`;
|
|
202
|
+
const handlerPath = join$1(outputDir, handlerFileName);
|
|
203
|
+
const relativePath = relative$1(dirname(handlerPath), sourceFile);
|
|
204
|
+
const importPath = relativePath.replace(/\.ts$/, ".js");
|
|
205
|
+
const relativeEnvParserPath = relative$1(dirname(handlerPath), context.envParserPath);
|
|
206
|
+
const relativeLoggerPath = relative$1(dirname(handlerPath), context.loggerPath);
|
|
207
|
+
const content = `import { AWSScheduledFunction } from '@geekmidas/constructs/crons';
|
|
208
|
+
import { ${exportName} } from '${importPath}';
|
|
209
|
+
import ${context.envParserImportPattern} from '${relativeEnvParserPath}';
|
|
210
|
+
import ${context.loggerImportPattern} from '${relativeLoggerPath}';
|
|
211
|
+
|
|
212
|
+
const adapter = new AWSScheduledFunction(envParser, ${exportName});
|
|
213
|
+
|
|
214
|
+
export const handler = adapter.handler;
|
|
215
|
+
`;
|
|
216
|
+
await writeFile(handlerPath, content);
|
|
217
|
+
return handlerPath;
|
|
218
|
+
}
|
|
219
|
+
};
|
|
220
|
+
|
|
221
|
+
//#endregion
|
|
222
|
+
//#region src/generators/FunctionGenerator.ts
|
|
223
|
+
var FunctionGenerator = class extends ConstructGenerator {
|
|
224
|
+
isConstruct(value) {
|
|
225
|
+
return Function.isFunction(value);
|
|
226
|
+
}
|
|
227
|
+
async build(context, constructs, outputDir, options) {
|
|
228
|
+
const provider = options?.provider || "aws-lambda";
|
|
229
|
+
const logger$3 = console;
|
|
230
|
+
const functionInfos = [];
|
|
231
|
+
if (constructs.length === 0 || provider !== "aws-lambda") return functionInfos;
|
|
232
|
+
const functionsDir = join$1(outputDir, "functions");
|
|
233
|
+
await mkdir(functionsDir, { recursive: true });
|
|
234
|
+
for (const { key, construct, path } of constructs) {
|
|
235
|
+
const handlerFile = await this.generateFunctionHandler(functionsDir, path.relative, key, context);
|
|
236
|
+
functionInfos.push({
|
|
237
|
+
name: key,
|
|
238
|
+
handler: relative$1(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
239
|
+
timeout: construct.timeout,
|
|
240
|
+
memorySize: construct.memorySize,
|
|
241
|
+
environment: await construct.getEnvironment()
|
|
242
|
+
});
|
|
243
|
+
logger$3.log(`Generated function handler: ${key}`);
|
|
244
|
+
}
|
|
245
|
+
return functionInfos;
|
|
246
|
+
}
|
|
247
|
+
async generateFunctionHandler(outputDir, sourceFile, exportName, context) {
|
|
248
|
+
const handlerFileName = `${exportName}.ts`;
|
|
249
|
+
const handlerPath = join$1(outputDir, handlerFileName);
|
|
250
|
+
const relativePath = relative$1(dirname(handlerPath), sourceFile);
|
|
251
|
+
const importPath = relativePath.replace(/\.ts$/, ".js");
|
|
252
|
+
const relativeEnvParserPath = relative$1(dirname(handlerPath), context.envParserPath);
|
|
253
|
+
const relativeLoggerPath = relative$1(dirname(handlerPath), context.loggerPath);
|
|
254
|
+
const content = `import { AWSLambdaFunction } from '@geekmidas/constructs/functions';
|
|
255
|
+
import { ${exportName} } from '${importPath}';
|
|
256
|
+
import ${context.envParserImportPattern} from '${relativeEnvParserPath}';
|
|
257
|
+
import ${context.loggerImportPattern} from '${relativeLoggerPath}';
|
|
258
|
+
|
|
259
|
+
const adapter = new AWSLambdaFunction(envParser, ${exportName});
|
|
260
|
+
|
|
261
|
+
export const handler = adapter.handler;
|
|
262
|
+
`;
|
|
263
|
+
await writeFile(handlerPath, content);
|
|
264
|
+
return handlerPath;
|
|
265
|
+
}
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
//#endregion
|
|
269
|
+
//#region src/generators/SubscriberGenerator.ts
|
|
270
|
+
var SubscriberGenerator = class extends ConstructGenerator {
|
|
271
|
+
isConstruct(value) {
|
|
272
|
+
return Subscriber.isSubscriber(value);
|
|
273
|
+
}
|
|
274
|
+
async build(context, constructs, outputDir, options) {
|
|
275
|
+
const provider = options?.provider || "aws-lambda";
|
|
276
|
+
const logger$3 = console;
|
|
277
|
+
const subscriberInfos = [];
|
|
278
|
+
if (provider === "server") {
|
|
279
|
+
await this.generateServerSubscribersFile(outputDir, constructs);
|
|
280
|
+
logger$3.log(`Generated server subscribers file with ${constructs.length} subscribers (polling mode)`);
|
|
281
|
+
return subscriberInfos;
|
|
282
|
+
}
|
|
283
|
+
if (constructs.length === 0) return subscriberInfos;
|
|
284
|
+
if (provider !== "aws-lambda") return subscriberInfos;
|
|
285
|
+
const subscribersDir = join$1(outputDir, "subscribers");
|
|
286
|
+
await mkdir(subscribersDir, { recursive: true });
|
|
287
|
+
for (const { key, construct, path } of constructs) {
|
|
288
|
+
const handlerFile = await this.generateSubscriberHandler(subscribersDir, path.relative, key, construct, context);
|
|
289
|
+
subscriberInfos.push({
|
|
290
|
+
name: key,
|
|
291
|
+
handler: relative$1(process.cwd(), handlerFile).replace(/\.ts$/, ".handler"),
|
|
292
|
+
subscribedEvents: construct.subscribedEvents || [],
|
|
293
|
+
timeout: construct.timeout,
|
|
294
|
+
memorySize: construct.memorySize,
|
|
295
|
+
environment: await construct.getEnvironment()
|
|
296
|
+
});
|
|
297
|
+
logger$3.log(`Generated subscriber handler: ${key}`);
|
|
298
|
+
}
|
|
299
|
+
return subscriberInfos;
|
|
300
|
+
}
|
|
301
|
+
async generateSubscriberHandler(outputDir, sourceFile, exportName, _subscriber, context) {
|
|
302
|
+
const handlerFileName = `${exportName}.ts`;
|
|
303
|
+
const handlerPath = join$1(outputDir, handlerFileName);
|
|
304
|
+
const relativePath = relative$1(dirname(handlerPath), sourceFile);
|
|
305
|
+
const importPath = relativePath.replace(/\.ts$/, ".js");
|
|
306
|
+
const relativeEnvParserPath = relative$1(dirname(handlerPath), context.envParserPath);
|
|
307
|
+
const content = `import { AWSLambdaSubscriber } from '@geekmidas/constructs/aws';
|
|
308
|
+
import { ${exportName} } from '${importPath}';
|
|
309
|
+
import ${context.envParserImportPattern} from '${relativeEnvParserPath}';
|
|
310
|
+
|
|
311
|
+
const adapter = new AWSLambdaSubscriber(envParser, ${exportName});
|
|
312
|
+
|
|
313
|
+
export const handler = adapter.handler;
|
|
314
|
+
`;
|
|
315
|
+
await writeFile(handlerPath, content);
|
|
316
|
+
return handlerPath;
|
|
317
|
+
}
|
|
318
|
+
async generateServerSubscribersFile(outputDir, subscribers) {
|
|
319
|
+
await mkdir(outputDir, { recursive: true });
|
|
320
|
+
const subscribersFileName = "subscribers.ts";
|
|
321
|
+
const subscribersPath = join$1(outputDir, subscribersFileName);
|
|
322
|
+
const importsByFile = /* @__PURE__ */ new Map();
|
|
323
|
+
for (const { path, key } of subscribers) {
|
|
324
|
+
const relativePath = relative$1(dirname(subscribersPath), path.relative);
|
|
325
|
+
const importPath = relativePath.replace(/\.ts$/, ".js");
|
|
326
|
+
if (!importsByFile.has(importPath)) importsByFile.set(importPath, []);
|
|
327
|
+
importsByFile.get(importPath).push(key);
|
|
328
|
+
}
|
|
329
|
+
const imports = Array.from(importsByFile.entries()).map(([importPath, exports$1]) => `import { ${exports$1.join(", ")} } from '${importPath}';`).join("\n");
|
|
330
|
+
const allExportNames = subscribers.map(({ key }) => key);
|
|
331
|
+
const content = `/**
|
|
332
|
+
* Generated subscribers setup
|
|
333
|
+
*
|
|
334
|
+
* ⚠️ WARNING: This is for LOCAL DEVELOPMENT ONLY
|
|
335
|
+
* This uses event polling which is not suitable for production.
|
|
336
|
+
*
|
|
337
|
+
* For production, use AWS Lambda with SQS/SNS event source mappings.
|
|
338
|
+
* Lambda automatically:
|
|
339
|
+
* - Scales based on queue depth
|
|
340
|
+
* - Handles batch processing and retries
|
|
341
|
+
* - Manages dead letter queues
|
|
342
|
+
* - Provides better cost optimization
|
|
343
|
+
*
|
|
344
|
+
* This polling implementation is useful for:
|
|
345
|
+
* - Local development and testing
|
|
346
|
+
* - Understanding event flow without Lambda deployment
|
|
347
|
+
*
|
|
348
|
+
* Supported connection strings:
|
|
349
|
+
* - sqs://region/account-id/queue-name (SQS queue)
|
|
350
|
+
* - sns://region/account-id/topic-name (SNS topic)
|
|
351
|
+
* - rabbitmq://host:port/queue-name (RabbitMQ)
|
|
352
|
+
* - basic://in-memory (In-memory for testing)
|
|
353
|
+
*/
|
|
354
|
+
import type { EnvironmentParser } from '@geekmidas/envkit';
|
|
355
|
+
import type { Logger } from '@geekmidas/logger';
|
|
356
|
+
import { EventConnectionFactory, Subscriber } from '@geekmidas/events';
|
|
357
|
+
import type { EventConnection, EventSubscriber } from '@geekmidas/events';
|
|
358
|
+
import { ServiceDiscovery } from '@geekmidas/services';
|
|
359
|
+
${imports}
|
|
360
|
+
|
|
361
|
+
const subscribers = [
|
|
362
|
+
${allExportNames.join(",\n ")}
|
|
363
|
+
];
|
|
364
|
+
|
|
365
|
+
const activeSubscribers: EventSubscriber<any>[] = [];
|
|
366
|
+
|
|
367
|
+
export async function setupSubscribers(
|
|
368
|
+
envParser: EnvironmentParser<any>,
|
|
369
|
+
logger: Logger,
|
|
370
|
+
): Promise<void> {
|
|
371
|
+
logger.info('Setting up subscribers in polling mode (local development)');
|
|
372
|
+
|
|
373
|
+
const config = envParser.create((get) => ({
|
|
374
|
+
connectionString: get('EVENT_SUBSCRIBER_CONNECTION_STRING').string().optional(),
|
|
375
|
+
})).parse();
|
|
376
|
+
|
|
377
|
+
if (!config.connectionString) {
|
|
378
|
+
logger.warn('EVENT_SUBSCRIBER_CONNECTION_STRING not configured, skipping subscriber setup');
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const serviceDiscovery = ServiceDiscovery.getInstance(logger, envParser);
|
|
383
|
+
|
|
384
|
+
// Create connection once, outside the loop (more efficient)
|
|
385
|
+
// EventConnectionFactory automatically determines the right connection type
|
|
386
|
+
let connection: EventConnection;
|
|
387
|
+
try {
|
|
388
|
+
connection = await EventConnectionFactory.fromConnectionString(config.connectionString);
|
|
389
|
+
|
|
390
|
+
const connectionType = new URL(config.connectionString).protocol.replace(':', '');
|
|
391
|
+
logger.info({ connectionType }, 'Created shared event connection');
|
|
392
|
+
} catch (error) {
|
|
393
|
+
logger.error({ error }, 'Failed to create event connection');
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
for (const subscriber of subscribers) {
|
|
398
|
+
try {
|
|
399
|
+
// Create subscriber from shared connection
|
|
400
|
+
const eventSubscriber = await Subscriber.fromConnection(connection);
|
|
401
|
+
|
|
402
|
+
// Register services
|
|
403
|
+
const services = subscriber.services.length > 0
|
|
404
|
+
? await serviceDiscovery.register(subscriber.services)
|
|
405
|
+
: {};
|
|
406
|
+
|
|
407
|
+
// Subscribe to events
|
|
408
|
+
const subscribedEvents = subscriber.subscribedEvents || [];
|
|
409
|
+
|
|
410
|
+
if (subscribedEvents.length === 0) {
|
|
411
|
+
logger.warn({ subscriber: subscriber.constructor.name }, 'Subscriber has no subscribed events, skipping');
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
await eventSubscriber.subscribe(subscribedEvents, async (event) => {
|
|
416
|
+
try {
|
|
417
|
+
// Process single event (batch of 1)
|
|
418
|
+
await subscriber.handler({
|
|
419
|
+
events: [event],
|
|
420
|
+
services: services as any,
|
|
421
|
+
logger: subscriber.logger,
|
|
422
|
+
});
|
|
423
|
+
|
|
424
|
+
logger.debug({ eventType: event.type }, 'Successfully processed event');
|
|
425
|
+
} catch (error) {
|
|
426
|
+
logger.error({ error, event }, 'Failed to process event');
|
|
427
|
+
// Event will become visible again for retry
|
|
428
|
+
}
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
activeSubscribers.push(eventSubscriber);
|
|
432
|
+
|
|
433
|
+
logger.info(
|
|
434
|
+
{
|
|
435
|
+
events: subscribedEvents,
|
|
436
|
+
},
|
|
437
|
+
'Subscriber started polling'
|
|
438
|
+
);
|
|
439
|
+
} catch (error) {
|
|
440
|
+
logger.error({ error, subscriber: subscriber.constructor.name }, 'Failed to setup subscriber');
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Setup graceful shutdown
|
|
445
|
+
const shutdown = () => {
|
|
446
|
+
logger.info('Stopping all subscribers');
|
|
447
|
+
for (const eventSubscriber of activeSubscribers) {
|
|
448
|
+
connection.stop();
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
|
|
452
|
+
process.on('SIGTERM', shutdown);
|
|
453
|
+
process.on('SIGINT', shutdown);
|
|
454
|
+
}
|
|
455
|
+
`;
|
|
456
|
+
await writeFile(subscribersPath, content);
|
|
457
|
+
return subscribersPath;
|
|
458
|
+
}
|
|
459
|
+
};
|
|
460
|
+
|
|
461
|
+
//#endregion
|
|
462
|
+
//#region src/dev/index.ts
|
|
463
|
+
const logger$2 = console;
|
|
464
|
+
/**
|
|
465
|
+
* Load environment files
|
|
466
|
+
* @internal Exported for testing
|
|
467
|
+
*/
|
|
468
|
+
function loadEnvFiles(envConfig, cwd = process.cwd()) {
|
|
469
|
+
const loaded = [];
|
|
470
|
+
const missing = [];
|
|
471
|
+
const envFiles = envConfig ? Array.isArray(envConfig) ? envConfig : [envConfig] : [".env"];
|
|
472
|
+
for (const envFile of envFiles) {
|
|
473
|
+
const envPath = resolve(cwd, envFile);
|
|
474
|
+
if (existsSync(envPath)) {
|
|
475
|
+
config({
|
|
476
|
+
path: envPath,
|
|
477
|
+
override: true,
|
|
478
|
+
quiet: true
|
|
479
|
+
});
|
|
480
|
+
loaded.push(envFile);
|
|
481
|
+
} else if (envConfig) missing.push(envFile);
|
|
482
|
+
}
|
|
483
|
+
return {
|
|
484
|
+
loaded,
|
|
485
|
+
missing
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
/**
|
|
489
|
+
* Check if a port is available
|
|
490
|
+
* @internal Exported for testing
|
|
491
|
+
*/
|
|
492
|
+
async function isPortAvailable(port) {
|
|
493
|
+
return new Promise((resolve$1) => {
|
|
494
|
+
const server = createServer();
|
|
495
|
+
server.once("error", (err) => {
|
|
496
|
+
if (err.code === "EADDRINUSE") resolve$1(false);
|
|
497
|
+
else resolve$1(false);
|
|
498
|
+
});
|
|
499
|
+
server.once("listening", () => {
|
|
500
|
+
server.close();
|
|
501
|
+
resolve$1(true);
|
|
502
|
+
});
|
|
503
|
+
server.listen(port);
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
/**
|
|
507
|
+
* Find an available port starting from the preferred port
|
|
508
|
+
* @internal Exported for testing
|
|
509
|
+
*/
|
|
510
|
+
async function findAvailablePort(preferredPort, maxAttempts = 10) {
|
|
511
|
+
for (let i = 0; i < maxAttempts; i++) {
|
|
512
|
+
const port = preferredPort + i;
|
|
513
|
+
if (await isPortAvailable(port)) return port;
|
|
514
|
+
logger$2.log(`⚠️ Port ${port} is in use, trying ${port + 1}...`);
|
|
515
|
+
}
|
|
516
|
+
throw new Error(`Could not find an available port after trying ${maxAttempts} ports starting from ${preferredPort}`);
|
|
517
|
+
}
|
|
518
|
+
/**
|
|
519
|
+
* Normalize telescope configuration
|
|
520
|
+
* @internal Exported for testing
|
|
521
|
+
*/
|
|
522
|
+
function normalizeTelescopeConfig(config$1) {
|
|
523
|
+
if (config$1 === false) return void 0;
|
|
524
|
+
if (typeof config$1 === "string") {
|
|
525
|
+
const { path: telescopePath, importPattern: telescopeImportPattern } = parseModuleConfig(config$1, "telescope");
|
|
526
|
+
return {
|
|
527
|
+
enabled: true,
|
|
528
|
+
telescopePath,
|
|
529
|
+
telescopeImportPattern,
|
|
530
|
+
path: "/__telescope",
|
|
531
|
+
ignore: [],
|
|
532
|
+
recordBody: true,
|
|
533
|
+
maxEntries: 1e3,
|
|
534
|
+
websocket: true
|
|
535
|
+
};
|
|
536
|
+
}
|
|
537
|
+
const isEnabled$1 = config$1 === true || config$1 === void 0 || config$1.enabled !== false;
|
|
538
|
+
if (!isEnabled$1) return void 0;
|
|
539
|
+
const telescopeConfig = typeof config$1 === "object" ? config$1 : {};
|
|
540
|
+
return {
|
|
541
|
+
enabled: true,
|
|
542
|
+
path: telescopeConfig.path ?? "/__telescope",
|
|
543
|
+
ignore: telescopeConfig.ignore ?? [],
|
|
544
|
+
recordBody: telescopeConfig.recordBody ?? true,
|
|
545
|
+
maxEntries: telescopeConfig.maxEntries ?? 1e3,
|
|
546
|
+
websocket: telescopeConfig.websocket ?? true
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* Normalize studio configuration
|
|
551
|
+
* @internal Exported for testing
|
|
552
|
+
*/
|
|
553
|
+
function normalizeStudioConfig(config$1) {
|
|
554
|
+
if (config$1 === false) return void 0;
|
|
555
|
+
if (typeof config$1 === "string") {
|
|
556
|
+
const { path: studioPath, importPattern: studioImportPattern } = parseModuleConfig(config$1, "studio");
|
|
557
|
+
return {
|
|
558
|
+
enabled: true,
|
|
559
|
+
studioPath,
|
|
560
|
+
studioImportPattern,
|
|
561
|
+
path: "/__studio",
|
|
562
|
+
schema: "public"
|
|
563
|
+
};
|
|
564
|
+
}
|
|
565
|
+
const isEnabled$1 = config$1 === true || config$1 === void 0 || config$1.enabled !== false;
|
|
566
|
+
if (!isEnabled$1) return void 0;
|
|
567
|
+
const studioConfig = typeof config$1 === "object" ? config$1 : {};
|
|
568
|
+
return {
|
|
569
|
+
enabled: true,
|
|
570
|
+
path: studioConfig.path ?? "/__studio",
|
|
571
|
+
schema: studioConfig.schema ?? "public"
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
async function devCommand(options) {
|
|
575
|
+
const defaultEnv = loadEnvFiles(".env");
|
|
576
|
+
if (defaultEnv.loaded.length > 0) logger$2.log(`📦 Loaded env: ${defaultEnv.loaded.join(", ")}`);
|
|
577
|
+
const config$1 = await loadConfig();
|
|
578
|
+
if (config$1.env) {
|
|
579
|
+
const { loaded, missing } = loadEnvFiles(config$1.env);
|
|
580
|
+
if (loaded.length > 0) logger$2.log(`📦 Loaded env: ${loaded.join(", ")}`);
|
|
581
|
+
if (missing.length > 0) logger$2.warn(`⚠️ Missing env files: ${missing.join(", ")}`);
|
|
582
|
+
}
|
|
583
|
+
const resolved = resolveProviders(config$1, { provider: "server" });
|
|
584
|
+
logger$2.log("🚀 Starting development server...");
|
|
585
|
+
logger$2.log(`Loading routes from: ${config$1.routes}`);
|
|
586
|
+
if (config$1.functions) logger$2.log(`Loading functions from: ${config$1.functions}`);
|
|
587
|
+
if (config$1.crons) logger$2.log(`Loading crons from: ${config$1.crons}`);
|
|
588
|
+
if (config$1.subscribers) logger$2.log(`Loading subscribers from: ${config$1.subscribers}`);
|
|
589
|
+
logger$2.log(`Using envParser: ${config$1.envParser}`);
|
|
590
|
+
const { path: envParserPath, importPattern: envParserImportPattern } = parseModuleConfig(config$1.envParser, "envParser");
|
|
591
|
+
const { path: loggerPath, importPattern: loggerImportPattern } = parseModuleConfig(config$1.logger, "logger");
|
|
592
|
+
const telescope = normalizeTelescopeConfig(config$1.telescope);
|
|
593
|
+
if (telescope) logger$2.log(`🔭 Telescope enabled at ${telescope.path}`);
|
|
594
|
+
const studio = normalizeStudioConfig(config$1.studio);
|
|
595
|
+
if (studio) logger$2.log(`🗄️ Studio enabled at ${studio.path}`);
|
|
596
|
+
const openApiConfig = resolveOpenApiConfig(config$1);
|
|
597
|
+
const enableOpenApi = openApiConfig.enabled || resolved.enableOpenApi;
|
|
598
|
+
if (enableOpenApi) logger$2.log(`📄 OpenAPI output: ${openApiConfig.output}`);
|
|
599
|
+
const buildContext = {
|
|
600
|
+
envParserPath,
|
|
601
|
+
envParserImportPattern,
|
|
602
|
+
loggerPath,
|
|
603
|
+
loggerImportPattern,
|
|
604
|
+
telescope,
|
|
605
|
+
studio
|
|
606
|
+
};
|
|
607
|
+
await buildServer(config$1, buildContext, resolved.providers[0], enableOpenApi);
|
|
608
|
+
if (enableOpenApi) await generateOpenApi(config$1);
|
|
609
|
+
const runtime = config$1.runtime ?? "node";
|
|
610
|
+
const devServer = new DevServer(resolved.providers[0], options.port || 3e3, enableOpenApi, telescope, studio, runtime);
|
|
611
|
+
await devServer.start();
|
|
612
|
+
const envParserFile = config$1.envParser.split("#")[0];
|
|
613
|
+
const loggerFile = config$1.logger.split("#")[0];
|
|
614
|
+
const watchPatterns = [
|
|
615
|
+
config$1.routes,
|
|
616
|
+
...config$1.functions ? [config$1.functions] : [],
|
|
617
|
+
...config$1.crons ? [config$1.crons] : [],
|
|
618
|
+
...config$1.subscribers ? [config$1.subscribers] : [],
|
|
619
|
+
envParserFile.endsWith(".ts") ? envParserFile : `${envParserFile}.ts`,
|
|
620
|
+
loggerFile.endsWith(".ts") ? loggerFile : `${loggerFile}.ts`
|
|
621
|
+
].flat();
|
|
622
|
+
const normalizedPatterns = watchPatterns.map((p) => p.startsWith("./") ? p.slice(2) : p);
|
|
623
|
+
logger$2.log(`👀 Watching for changes in: ${normalizedPatterns.join(", ")}`);
|
|
624
|
+
const resolvedFiles = await fg(normalizedPatterns, {
|
|
625
|
+
cwd: process.cwd(),
|
|
626
|
+
absolute: false,
|
|
627
|
+
onlyFiles: true
|
|
628
|
+
});
|
|
629
|
+
const dirsToWatch = [...new Set(resolvedFiles.map((f) => f.split("/").slice(0, -1).join("/")))];
|
|
630
|
+
logger$2.log(`📁 Found ${resolvedFiles.length} files in ${dirsToWatch.length} directories`);
|
|
631
|
+
const watcher = chokidar.watch([...resolvedFiles, ...dirsToWatch], {
|
|
632
|
+
ignored: /(^|[\/\\])\../,
|
|
633
|
+
persistent: true,
|
|
634
|
+
ignoreInitial: true,
|
|
635
|
+
cwd: process.cwd()
|
|
636
|
+
});
|
|
637
|
+
watcher.on("ready", () => {
|
|
638
|
+
logger$2.log("🔍 File watcher ready");
|
|
639
|
+
});
|
|
640
|
+
watcher.on("error", (error) => {
|
|
641
|
+
logger$2.error("❌ Watcher error:", error);
|
|
642
|
+
});
|
|
643
|
+
let rebuildTimeout = null;
|
|
644
|
+
watcher.on("change", async (path) => {
|
|
645
|
+
logger$2.log(`📝 File changed: ${path}`);
|
|
646
|
+
if (rebuildTimeout) clearTimeout(rebuildTimeout);
|
|
647
|
+
rebuildTimeout = setTimeout(async () => {
|
|
648
|
+
try {
|
|
649
|
+
logger$2.log("🔄 Rebuilding...");
|
|
650
|
+
await buildServer(config$1, buildContext, resolved.providers[0], enableOpenApi);
|
|
651
|
+
if (enableOpenApi) await generateOpenApi(config$1, { silent: true });
|
|
652
|
+
logger$2.log("✅ Rebuild complete, restarting server...");
|
|
653
|
+
await devServer.restart();
|
|
654
|
+
} catch (error) {
|
|
655
|
+
logger$2.error("❌ Rebuild failed:", error.message);
|
|
656
|
+
}
|
|
657
|
+
}, 300);
|
|
658
|
+
});
|
|
659
|
+
const shutdown = async () => {
|
|
660
|
+
logger$2.log("\n🛑 Shutting down...");
|
|
661
|
+
await watcher.close();
|
|
662
|
+
await devServer.stop();
|
|
663
|
+
process.exit(0);
|
|
664
|
+
};
|
|
665
|
+
process.on("SIGINT", shutdown);
|
|
666
|
+
process.on("SIGTERM", shutdown);
|
|
667
|
+
}
|
|
668
|
+
async function buildServer(config$1, context, provider, enableOpenApi) {
|
|
669
|
+
const endpointGenerator = new EndpointGenerator();
|
|
670
|
+
const functionGenerator = new FunctionGenerator();
|
|
671
|
+
const cronGenerator = new CronGenerator();
|
|
672
|
+
const subscriberGenerator = new SubscriberGenerator();
|
|
673
|
+
const [allEndpoints, allFunctions, allCrons, allSubscribers] = await Promise.all([
|
|
674
|
+
endpointGenerator.load(config$1.routes),
|
|
675
|
+
config$1.functions ? functionGenerator.load(config$1.functions) : [],
|
|
676
|
+
config$1.crons ? cronGenerator.load(config$1.crons) : [],
|
|
677
|
+
config$1.subscribers ? subscriberGenerator.load(config$1.subscribers) : []
|
|
678
|
+
]);
|
|
679
|
+
const outputDir = join$1(process.cwd(), ".gkm", provider);
|
|
680
|
+
await mkdir(outputDir, { recursive: true });
|
|
681
|
+
await Promise.all([
|
|
682
|
+
endpointGenerator.build(context, allEndpoints, outputDir, {
|
|
683
|
+
provider,
|
|
684
|
+
enableOpenApi
|
|
685
|
+
}),
|
|
686
|
+
functionGenerator.build(context, allFunctions, outputDir, { provider }),
|
|
687
|
+
cronGenerator.build(context, allCrons, outputDir, { provider }),
|
|
688
|
+
subscriberGenerator.build(context, allSubscribers, outputDir, { provider })
|
|
689
|
+
]);
|
|
690
|
+
}
|
|
691
|
+
var DevServer = class {
|
|
692
|
+
serverProcess = null;
|
|
693
|
+
isRunning = false;
|
|
694
|
+
actualPort;
|
|
695
|
+
constructor(provider, requestedPort, enableOpenApi, telescope, studio, runtime = "node") {
|
|
696
|
+
this.provider = provider;
|
|
697
|
+
this.requestedPort = requestedPort;
|
|
698
|
+
this.enableOpenApi = enableOpenApi;
|
|
699
|
+
this.telescope = telescope;
|
|
700
|
+
this.studio = studio;
|
|
701
|
+
this.runtime = runtime;
|
|
702
|
+
this.actualPort = requestedPort;
|
|
703
|
+
}
|
|
704
|
+
async start() {
|
|
705
|
+
if (this.isRunning) await this.stop();
|
|
706
|
+
this.actualPort = await findAvailablePort(this.requestedPort);
|
|
707
|
+
if (this.actualPort !== this.requestedPort) logger$2.log(`ℹ️ Port ${this.requestedPort} was in use, using port ${this.actualPort} instead`);
|
|
708
|
+
const serverEntryPath = join$1(process.cwd(), ".gkm", this.provider, "server.ts");
|
|
709
|
+
await this.createServerEntry();
|
|
710
|
+
logger$2.log(`\n✨ Starting server on port ${this.actualPort}...`);
|
|
711
|
+
this.serverProcess = spawn("npx", [
|
|
712
|
+
"tsx",
|
|
713
|
+
serverEntryPath,
|
|
714
|
+
"--port",
|
|
715
|
+
this.actualPort.toString()
|
|
716
|
+
], {
|
|
717
|
+
stdio: "inherit",
|
|
718
|
+
env: {
|
|
719
|
+
...process.env,
|
|
720
|
+
NODE_ENV: "development"
|
|
721
|
+
},
|
|
722
|
+
detached: true
|
|
723
|
+
});
|
|
724
|
+
this.isRunning = true;
|
|
725
|
+
this.serverProcess.on("error", (error) => {
|
|
726
|
+
logger$2.error("❌ Server error:", error);
|
|
727
|
+
});
|
|
728
|
+
this.serverProcess.on("exit", (code, signal) => {
|
|
729
|
+
if (code !== null && code !== 0 && signal !== "SIGTERM") logger$2.error(`❌ Server exited with code ${code}`);
|
|
730
|
+
this.isRunning = false;
|
|
731
|
+
});
|
|
732
|
+
await new Promise((resolve$1) => setTimeout(resolve$1, 1e3));
|
|
733
|
+
if (this.isRunning) {
|
|
734
|
+
logger$2.log(`\n🎉 Server running at http://localhost:${this.actualPort}`);
|
|
735
|
+
if (this.enableOpenApi) logger$2.log(`📚 API Docs available at http://localhost:${this.actualPort}/__docs`);
|
|
736
|
+
if (this.telescope) logger$2.log(`🔭 Telescope available at http://localhost:${this.actualPort}${this.telescope.path}`);
|
|
737
|
+
if (this.studio) logger$2.log(`🗄️ Studio available at http://localhost:${this.actualPort}${this.studio.path}`);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
async stop() {
|
|
741
|
+
if (this.serverProcess && this.isRunning) {
|
|
742
|
+
const pid = this.serverProcess.pid;
|
|
743
|
+
if (pid) try {
|
|
744
|
+
process.kill(-pid, "SIGTERM");
|
|
745
|
+
} catch {}
|
|
746
|
+
await new Promise((resolve$1) => {
|
|
747
|
+
const timeout = setTimeout(() => {
|
|
748
|
+
if (pid) try {
|
|
749
|
+
process.kill(-pid, "SIGKILL");
|
|
750
|
+
} catch {}
|
|
751
|
+
resolve$1();
|
|
752
|
+
}, 3e3);
|
|
753
|
+
this.serverProcess?.on("exit", () => {
|
|
754
|
+
clearTimeout(timeout);
|
|
755
|
+
resolve$1();
|
|
756
|
+
});
|
|
757
|
+
});
|
|
758
|
+
this.serverProcess = null;
|
|
759
|
+
this.isRunning = false;
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
async restart() {
|
|
763
|
+
const portToReuse = this.actualPort;
|
|
764
|
+
await this.stop();
|
|
765
|
+
let attempts = 0;
|
|
766
|
+
while (attempts < 30) {
|
|
767
|
+
if (await isPortAvailable(portToReuse)) break;
|
|
768
|
+
await new Promise((resolve$1) => setTimeout(resolve$1, 100));
|
|
769
|
+
attempts++;
|
|
770
|
+
}
|
|
771
|
+
this.requestedPort = portToReuse;
|
|
772
|
+
await this.start();
|
|
773
|
+
}
|
|
774
|
+
async createServerEntry() {
|
|
775
|
+
const { writeFile: writeFile$1 } = await import("node:fs/promises");
|
|
776
|
+
const { relative: relative$2, dirname: dirname$1 } = await import("node:path");
|
|
777
|
+
const serverPath = join$1(process.cwd(), ".gkm", this.provider, "server.ts");
|
|
778
|
+
const relativeAppPath = relative$2(dirname$1(serverPath), join$1(dirname$1(serverPath), "app.js"));
|
|
779
|
+
const serveCode = this.runtime === "bun" ? `Bun.serve({
|
|
780
|
+
port,
|
|
781
|
+
fetch: app.fetch,
|
|
782
|
+
});` : `const { serve } = await import('@hono/node-server');
|
|
783
|
+
const server = serve({
|
|
784
|
+
fetch: app.fetch,
|
|
785
|
+
port,
|
|
786
|
+
});
|
|
787
|
+
// Inject WebSocket support if available
|
|
788
|
+
const injectWs = (app as any).__injectWebSocket;
|
|
789
|
+
if (injectWs) {
|
|
790
|
+
injectWs(server);
|
|
791
|
+
console.log('🔌 Telescope real-time updates enabled');
|
|
792
|
+
}`;
|
|
793
|
+
const content = `#!/usr/bin/env node
|
|
794
|
+
/**
|
|
795
|
+
* Development server entry point
|
|
796
|
+
* This file is auto-generated by 'gkm dev'
|
|
797
|
+
*/
|
|
798
|
+
import { createApp } from './${relativeAppPath.startsWith(".") ? relativeAppPath : "./" + relativeAppPath}';
|
|
799
|
+
|
|
800
|
+
const port = process.argv.includes('--port')
|
|
801
|
+
? Number.parseInt(process.argv[process.argv.indexOf('--port') + 1])
|
|
802
|
+
: 3000;
|
|
803
|
+
|
|
804
|
+
// createApp is async to support optional WebSocket setup
|
|
805
|
+
const { app, start } = await createApp(undefined, ${this.enableOpenApi});
|
|
806
|
+
|
|
807
|
+
// Start the server
|
|
808
|
+
start({
|
|
809
|
+
port,
|
|
810
|
+
serve: async (app, port) => {
|
|
811
|
+
${serveCode}
|
|
812
|
+
},
|
|
813
|
+
}).catch((error) => {
|
|
814
|
+
console.error('Failed to start server:', error);
|
|
815
|
+
process.exit(1);
|
|
816
|
+
});
|
|
817
|
+
`;
|
|
818
|
+
await writeFile$1(serverPath, content);
|
|
819
|
+
}
|
|
820
|
+
};
|
|
821
|
+
|
|
822
|
+
//#endregion
|
|
823
|
+
//#region src/build/manifests.ts
|
|
824
|
+
const logger$1 = console;
|
|
825
|
+
async function generateAwsManifest(outputDir, routes, functions, crons, subscribers) {
|
|
826
|
+
const manifestDir = join(outputDir, "manifest");
|
|
827
|
+
await mkdir(manifestDir, { recursive: true });
|
|
828
|
+
const awsRoutes = routes.filter((r) => r.method !== "ALL");
|
|
829
|
+
const content = `export const manifest = {
|
|
830
|
+
routes: ${JSON.stringify(awsRoutes, null, 2)},
|
|
831
|
+
functions: ${JSON.stringify(functions, null, 2)},
|
|
832
|
+
crons: ${JSON.stringify(crons, null, 2)},
|
|
833
|
+
subscribers: ${JSON.stringify(subscribers, null, 2)},
|
|
834
|
+
} as const;
|
|
835
|
+
|
|
836
|
+
// Derived types
|
|
837
|
+
export type Route = (typeof manifest.routes)[number];
|
|
838
|
+
export type Function = (typeof manifest.functions)[number];
|
|
839
|
+
export type Cron = (typeof manifest.crons)[number];
|
|
840
|
+
export type Subscriber = (typeof manifest.subscribers)[number];
|
|
841
|
+
|
|
842
|
+
// Useful union types
|
|
843
|
+
export type Authorizer = Route['authorizer'];
|
|
844
|
+
export type HttpMethod = Route['method'];
|
|
845
|
+
export type RoutePath = Route['path'];
|
|
846
|
+
`;
|
|
847
|
+
const manifestPath = join(manifestDir, "aws.ts");
|
|
848
|
+
await writeFile(manifestPath, content);
|
|
849
|
+
logger$1.log(`Generated AWS manifest with ${awsRoutes.length} routes, ${functions.length} functions, ${crons.length} crons, ${subscribers.length} subscribers`);
|
|
850
|
+
logger$1.log(`Manifest: ${relative(process.cwd(), manifestPath)}`);
|
|
851
|
+
}
|
|
852
|
+
async function generateServerManifest(outputDir, appInfo, routes, subscribers) {
|
|
853
|
+
const manifestDir = join(outputDir, "manifest");
|
|
854
|
+
await mkdir(manifestDir, { recursive: true });
|
|
855
|
+
const serverRoutes = routes.filter((r) => r.method !== "ALL").map((r) => ({
|
|
856
|
+
path: r.path,
|
|
857
|
+
method: r.method,
|
|
858
|
+
authorizer: r.authorizer
|
|
859
|
+
}));
|
|
860
|
+
const serverSubscribers = subscribers.map((s) => ({
|
|
861
|
+
name: s.name,
|
|
862
|
+
subscribedEvents: s.subscribedEvents
|
|
863
|
+
}));
|
|
864
|
+
const content = `export const manifest = {
|
|
865
|
+
app: ${JSON.stringify(appInfo, null, 2)},
|
|
866
|
+
routes: ${JSON.stringify(serverRoutes, null, 2)},
|
|
867
|
+
subscribers: ${JSON.stringify(serverSubscribers, null, 2)},
|
|
868
|
+
} as const;
|
|
869
|
+
|
|
870
|
+
// Derived types
|
|
871
|
+
export type Route = (typeof manifest.routes)[number];
|
|
872
|
+
export type Subscriber = (typeof manifest.subscribers)[number];
|
|
873
|
+
|
|
874
|
+
// Useful union types
|
|
875
|
+
export type Authorizer = Route['authorizer'];
|
|
876
|
+
export type HttpMethod = Route['method'];
|
|
877
|
+
export type RoutePath = Route['path'];
|
|
878
|
+
`;
|
|
879
|
+
const manifestPath = join(manifestDir, "server.ts");
|
|
880
|
+
await writeFile(manifestPath, content);
|
|
881
|
+
logger$1.log(`Generated server manifest with ${serverRoutes.length} routes, ${serverSubscribers.length} subscribers`);
|
|
882
|
+
logger$1.log(`Manifest: ${relative(process.cwd(), manifestPath)}`);
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
//#endregion
|
|
886
|
+
//#region src/build/index.ts
|
|
887
|
+
const logger = console;
|
|
888
|
+
async function buildCommand(options) {
|
|
889
|
+
const config$1 = await loadConfig();
|
|
890
|
+
const resolved = resolveProviders(config$1, options);
|
|
891
|
+
logger.log(`Building with providers: ${resolved.providers.join(", ")}`);
|
|
892
|
+
logger.log(`Loading routes from: ${config$1.routes}`);
|
|
893
|
+
if (config$1.functions) logger.log(`Loading functions from: ${config$1.functions}`);
|
|
894
|
+
if (config$1.crons) logger.log(`Loading crons from: ${config$1.crons}`);
|
|
895
|
+
if (config$1.subscribers) logger.log(`Loading subscribers from: ${config$1.subscribers}`);
|
|
896
|
+
logger.log(`Using envParser: ${config$1.envParser}`);
|
|
897
|
+
const { path: envParserPath, importPattern: envParserImportPattern } = parseModuleConfig(config$1.envParser, "envParser");
|
|
898
|
+
const { path: loggerPath, importPattern: loggerImportPattern } = parseModuleConfig(config$1.logger, "logger");
|
|
899
|
+
const telescope = normalizeTelescopeConfig(config$1.telescope);
|
|
900
|
+
if (telescope) logger.log(`🔭 Telescope enabled at ${telescope.path}`);
|
|
901
|
+
const buildContext = {
|
|
902
|
+
envParserPath,
|
|
903
|
+
envParserImportPattern,
|
|
904
|
+
loggerPath,
|
|
905
|
+
loggerImportPattern,
|
|
906
|
+
telescope
|
|
907
|
+
};
|
|
908
|
+
const endpointGenerator = new EndpointGenerator();
|
|
909
|
+
const functionGenerator = new FunctionGenerator();
|
|
910
|
+
const cronGenerator = new CronGenerator();
|
|
911
|
+
const subscriberGenerator = new SubscriberGenerator();
|
|
912
|
+
const [allEndpoints, allFunctions, allCrons, allSubscribers] = await Promise.all([
|
|
913
|
+
endpointGenerator.load(config$1.routes),
|
|
914
|
+
config$1.functions ? functionGenerator.load(config$1.functions) : [],
|
|
915
|
+
config$1.crons ? cronGenerator.load(config$1.crons) : [],
|
|
916
|
+
config$1.subscribers ? subscriberGenerator.load(config$1.subscribers) : []
|
|
917
|
+
]);
|
|
918
|
+
logger.log(`Found ${allEndpoints.length} endpoints`);
|
|
919
|
+
logger.log(`Found ${allFunctions.length} functions`);
|
|
920
|
+
logger.log(`Found ${allCrons.length} crons`);
|
|
921
|
+
logger.log(`Found ${allSubscribers.length} subscribers`);
|
|
922
|
+
if (allEndpoints.length === 0 && allFunctions.length === 0 && allCrons.length === 0 && allSubscribers.length === 0) {
|
|
923
|
+
logger.log("No endpoints, functions, crons, or subscribers found to process");
|
|
924
|
+
return;
|
|
925
|
+
}
|
|
926
|
+
const rootOutputDir = join$1(process.cwd(), ".gkm");
|
|
927
|
+
await mkdir(rootOutputDir, { recursive: true });
|
|
928
|
+
for (const provider of resolved.providers) await buildForProvider(provider, buildContext, rootOutputDir, endpointGenerator, functionGenerator, cronGenerator, subscriberGenerator, allEndpoints, allFunctions, allCrons, allSubscribers, resolved.enableOpenApi);
|
|
929
|
+
}
|
|
930
|
+
async function buildForProvider(provider, context, rootOutputDir, endpointGenerator, functionGenerator, cronGenerator, subscriberGenerator, endpoints, functions, crons, subscribers, enableOpenApi) {
|
|
931
|
+
const outputDir = join$1(process.cwd(), ".gkm", provider);
|
|
932
|
+
await mkdir(outputDir, { recursive: true });
|
|
933
|
+
logger.log(`\nGenerating handlers for provider: ${provider}`);
|
|
934
|
+
const [routes, functionInfos, cronInfos, subscriberInfos] = await Promise.all([
|
|
935
|
+
endpointGenerator.build(context, endpoints, outputDir, {
|
|
936
|
+
provider,
|
|
937
|
+
enableOpenApi
|
|
938
|
+
}),
|
|
939
|
+
functionGenerator.build(context, functions, outputDir, { provider }),
|
|
940
|
+
cronGenerator.build(context, crons, outputDir, { provider }),
|
|
941
|
+
subscriberGenerator.build(context, subscribers, outputDir, { provider })
|
|
942
|
+
]);
|
|
943
|
+
logger.log(`Generated ${routes.length} routes, ${functionInfos.length} functions, ${cronInfos.length} crons, ${subscriberInfos.length} subscribers for ${provider}`);
|
|
944
|
+
if (provider === "server") {
|
|
945
|
+
const routeMetadata = await Promise.all(endpoints.map(async ({ construct }) => ({
|
|
946
|
+
path: construct._path,
|
|
947
|
+
method: construct.method,
|
|
948
|
+
handler: "",
|
|
949
|
+
authorizer: construct.authorizer?.name ?? "none"
|
|
950
|
+
})));
|
|
951
|
+
const appInfo = {
|
|
952
|
+
handler: relative$1(process.cwd(), join$1(outputDir, "app.ts")),
|
|
953
|
+
endpoints: relative$1(process.cwd(), join$1(outputDir, "endpoints.ts"))
|
|
954
|
+
};
|
|
955
|
+
await generateServerManifest(rootOutputDir, appInfo, routeMetadata, subscriberInfos);
|
|
956
|
+
} else await generateAwsManifest(rootOutputDir, routes, functionInfos, cronInfos, subscriberInfos);
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
//#endregion
|
|
960
|
+
//#region src/init/generators/config.ts
|
|
961
|
+
/**
|
|
962
|
+
* Generate configuration files (gkm.config.ts, tsconfig.json, biome.json, turbo.json)
|
|
963
|
+
*/
|
|
964
|
+
function generateConfigFiles(options, template) {
|
|
965
|
+
const { telescope, studio, routesStructure } = options;
|
|
966
|
+
const isServerless = template.name === "serverless";
|
|
967
|
+
const hasWorker = template.name === "worker";
|
|
968
|
+
const getRoutesGlob = () => {
|
|
969
|
+
switch (routesStructure) {
|
|
970
|
+
case "centralized-endpoints": return "./src/endpoints/**/*.ts";
|
|
971
|
+
case "centralized-routes": return "./src/routes/**/*.ts";
|
|
972
|
+
case "domain-based": return "./src/**/routes/*.ts";
|
|
973
|
+
}
|
|
974
|
+
};
|
|
975
|
+
let gkmConfig = `import { defineConfig } from '@geekmidas/cli/config';
|
|
976
|
+
|
|
977
|
+
export default defineConfig({
|
|
978
|
+
routes: '${getRoutesGlob()}',
|
|
979
|
+
envParser: './src/config/env#envParser',
|
|
980
|
+
logger: './src/config/logger#logger',`;
|
|
981
|
+
if (isServerless || hasWorker) gkmConfig += `
|
|
982
|
+
functions: './src/functions/**/*.ts',`;
|
|
983
|
+
if (hasWorker) gkmConfig += `
|
|
984
|
+
crons: './src/crons/**/*.ts',
|
|
985
|
+
subscribers: './src/subscribers/**/*.ts',`;
|
|
986
|
+
if (telescope) gkmConfig += `
|
|
987
|
+
telescope: {
|
|
988
|
+
enabled: true,
|
|
989
|
+
path: '/__telescope',
|
|
990
|
+
},`;
|
|
991
|
+
if (studio) gkmConfig += `
|
|
992
|
+
studio: './src/config/studio#studio',`;
|
|
993
|
+
gkmConfig += `
|
|
994
|
+
openapi: {
|
|
995
|
+
enabled: true,
|
|
996
|
+
},`;
|
|
997
|
+
gkmConfig += `
|
|
998
|
+
});
|
|
999
|
+
`;
|
|
1000
|
+
const tsConfig = options.monorepo ? {
|
|
1001
|
+
extends: "../../tsconfig.json",
|
|
1002
|
+
compilerOptions: {
|
|
1003
|
+
outDir: "./dist",
|
|
1004
|
+
rootDir: "./src",
|
|
1005
|
+
baseUrl: ".",
|
|
1006
|
+
paths: { [`@${options.name}/*`]: ["../../packages/*/src"] }
|
|
1007
|
+
},
|
|
1008
|
+
include: ["src/**/*.ts"],
|
|
1009
|
+
exclude: ["node_modules", "dist"]
|
|
1010
|
+
} : {
|
|
1011
|
+
compilerOptions: {
|
|
1012
|
+
target: "ES2022",
|
|
1013
|
+
module: "NodeNext",
|
|
1014
|
+
moduleResolution: "NodeNext",
|
|
1015
|
+
lib: ["ES2022"],
|
|
1016
|
+
strict: true,
|
|
1017
|
+
esModuleInterop: true,
|
|
1018
|
+
skipLibCheck: true,
|
|
1019
|
+
forceConsistentCasingInFileNames: true,
|
|
1020
|
+
resolveJsonModule: true,
|
|
1021
|
+
declaration: true,
|
|
1022
|
+
declarationMap: true,
|
|
1023
|
+
outDir: "./dist",
|
|
1024
|
+
rootDir: "./src"
|
|
1025
|
+
},
|
|
1026
|
+
include: ["src/**/*.ts"],
|
|
1027
|
+
exclude: ["node_modules", "dist"]
|
|
1028
|
+
};
|
|
1029
|
+
if (options.monorepo) return [{
|
|
1030
|
+
path: "gkm.config.ts",
|
|
1031
|
+
content: gkmConfig
|
|
1032
|
+
}, {
|
|
1033
|
+
path: "tsconfig.json",
|
|
1034
|
+
content: JSON.stringify(tsConfig, null, 2) + "\n"
|
|
1035
|
+
}];
|
|
1036
|
+
const biomeConfig = {
|
|
1037
|
+
$schema: "https://biomejs.dev/schemas/1.9.4/schema.json",
|
|
1038
|
+
vcs: {
|
|
1039
|
+
enabled: true,
|
|
1040
|
+
clientKind: "git",
|
|
1041
|
+
useIgnoreFile: true
|
|
1042
|
+
},
|
|
1043
|
+
organizeImports: { enabled: true },
|
|
1044
|
+
formatter: {
|
|
1045
|
+
enabled: true,
|
|
1046
|
+
indentStyle: "space",
|
|
1047
|
+
indentWidth: 2,
|
|
1048
|
+
lineWidth: 80
|
|
1049
|
+
},
|
|
1050
|
+
javascript: { formatter: {
|
|
1051
|
+
quoteStyle: "single",
|
|
1052
|
+
trailingCommas: "all",
|
|
1053
|
+
semicolons: "always",
|
|
1054
|
+
arrowParentheses: "always"
|
|
1055
|
+
} },
|
|
1056
|
+
linter: {
|
|
1057
|
+
enabled: true,
|
|
1058
|
+
rules: {
|
|
1059
|
+
recommended: true,
|
|
1060
|
+
correctness: {
|
|
1061
|
+
noUnusedImports: "error",
|
|
1062
|
+
noUnusedVariables: "error"
|
|
1063
|
+
},
|
|
1064
|
+
style: { noNonNullAssertion: "off" }
|
|
1065
|
+
}
|
|
1066
|
+
},
|
|
1067
|
+
files: { ignore: [
|
|
1068
|
+
"node_modules",
|
|
1069
|
+
"dist",
|
|
1070
|
+
".gkm",
|
|
1071
|
+
"coverage"
|
|
1072
|
+
] }
|
|
1073
|
+
};
|
|
1074
|
+
const turboConfig = {
|
|
1075
|
+
$schema: "https://turbo.build/schema.json",
|
|
1076
|
+
tasks: {
|
|
1077
|
+
build: {
|
|
1078
|
+
dependsOn: ["^build"],
|
|
1079
|
+
outputs: ["dist/**"]
|
|
1080
|
+
},
|
|
1081
|
+
dev: {
|
|
1082
|
+
cache: false,
|
|
1083
|
+
persistent: true
|
|
1084
|
+
},
|
|
1085
|
+
test: {
|
|
1086
|
+
dependsOn: ["^build"],
|
|
1087
|
+
cache: false
|
|
1088
|
+
},
|
|
1089
|
+
"test:once": {
|
|
1090
|
+
dependsOn: ["^build"],
|
|
1091
|
+
outputs: ["coverage/**"]
|
|
1092
|
+
},
|
|
1093
|
+
typecheck: {
|
|
1094
|
+
dependsOn: ["^build"],
|
|
1095
|
+
outputs: []
|
|
1096
|
+
},
|
|
1097
|
+
lint: { outputs: [] },
|
|
1098
|
+
fmt: { outputs: [] }
|
|
1099
|
+
}
|
|
1100
|
+
};
|
|
1101
|
+
return [
|
|
1102
|
+
{
|
|
1103
|
+
path: "gkm.config.ts",
|
|
1104
|
+
content: gkmConfig
|
|
1105
|
+
},
|
|
1106
|
+
{
|
|
1107
|
+
path: "tsconfig.json",
|
|
1108
|
+
content: JSON.stringify(tsConfig, null, 2) + "\n"
|
|
1109
|
+
},
|
|
1110
|
+
{
|
|
1111
|
+
path: "biome.json",
|
|
1112
|
+
content: JSON.stringify(biomeConfig, null, 2) + "\n"
|
|
1113
|
+
},
|
|
1114
|
+
{
|
|
1115
|
+
path: "turbo.json",
|
|
1116
|
+
content: JSON.stringify(turboConfig, null, 2) + "\n"
|
|
1117
|
+
}
|
|
1118
|
+
];
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
//#endregion
|
|
1122
|
+
//#region src/init/generators/docker.ts
|
|
1123
|
+
/**
|
|
1124
|
+
* Generate docker-compose.yml based on template and options
|
|
1125
|
+
*/
|
|
1126
|
+
function generateDockerFiles(options, template) {
|
|
1127
|
+
const { database } = options;
|
|
1128
|
+
const isServerless = template.name === "serverless";
|
|
1129
|
+
const hasWorker = template.name === "worker";
|
|
1130
|
+
const services = [];
|
|
1131
|
+
const volumes = [];
|
|
1132
|
+
if (database) {
|
|
1133
|
+
services.push(` postgres:
|
|
1134
|
+
image: postgres:16-alpine
|
|
1135
|
+
container_name: ${options.name}-postgres
|
|
1136
|
+
restart: unless-stopped
|
|
1137
|
+
environment:
|
|
1138
|
+
POSTGRES_USER: postgres
|
|
1139
|
+
POSTGRES_PASSWORD: postgres
|
|
1140
|
+
POSTGRES_DB: ${options.name.replace(/-/g, "_")}_dev
|
|
1141
|
+
ports:
|
|
1142
|
+
- '5432:5432'
|
|
1143
|
+
volumes:
|
|
1144
|
+
- postgres_data:/var/lib/postgresql/data
|
|
1145
|
+
healthcheck:
|
|
1146
|
+
test: ['CMD-SHELL', 'pg_isready -U postgres']
|
|
1147
|
+
interval: 5s
|
|
1148
|
+
timeout: 5s
|
|
1149
|
+
retries: 5`);
|
|
1150
|
+
volumes.push(" postgres_data:");
|
|
1151
|
+
}
|
|
1152
|
+
if (isServerless) {
|
|
1153
|
+
services.push(` redis:
|
|
1154
|
+
image: redis:7-alpine
|
|
1155
|
+
container_name: ${options.name}-redis
|
|
1156
|
+
restart: unless-stopped
|
|
1157
|
+
ports:
|
|
1158
|
+
- '6379:6379'
|
|
1159
|
+
volumes:
|
|
1160
|
+
- redis_data:/data
|
|
1161
|
+
healthcheck:
|
|
1162
|
+
test: ['CMD', 'redis-cli', 'ping']
|
|
1163
|
+
interval: 5s
|
|
1164
|
+
timeout: 5s
|
|
1165
|
+
retries: 5
|
|
1166
|
+
|
|
1167
|
+
serverless-redis:
|
|
1168
|
+
image: hiett/serverless-redis-http:latest
|
|
1169
|
+
container_name: ${options.name}-serverless-redis
|
|
1170
|
+
restart: unless-stopped
|
|
1171
|
+
ports:
|
|
1172
|
+
- '8079:80'
|
|
1173
|
+
environment:
|
|
1174
|
+
SRH_MODE: env
|
|
1175
|
+
SRH_TOKEN: local_dev_token
|
|
1176
|
+
SRH_CONNECTION_STRING: redis://redis:6379
|
|
1177
|
+
depends_on:
|
|
1178
|
+
redis:
|
|
1179
|
+
condition: service_healthy`);
|
|
1180
|
+
volumes.push(" redis_data:");
|
|
1181
|
+
} else {
|
|
1182
|
+
services.push(` redis:
|
|
1183
|
+
image: redis:7-alpine
|
|
1184
|
+
container_name: ${options.name}-redis
|
|
1185
|
+
restart: unless-stopped
|
|
1186
|
+
ports:
|
|
1187
|
+
- '6379:6379'
|
|
1188
|
+
volumes:
|
|
1189
|
+
- redis_data:/data
|
|
1190
|
+
healthcheck:
|
|
1191
|
+
test: ['CMD', 'redis-cli', 'ping']
|
|
1192
|
+
interval: 5s
|
|
1193
|
+
timeout: 5s
|
|
1194
|
+
retries: 5`);
|
|
1195
|
+
volumes.push(" redis_data:");
|
|
1196
|
+
}
|
|
1197
|
+
if (hasWorker) {
|
|
1198
|
+
services.push(` rabbitmq:
|
|
1199
|
+
image: rabbitmq:3-management-alpine
|
|
1200
|
+
container_name: ${options.name}-rabbitmq
|
|
1201
|
+
restart: unless-stopped
|
|
1202
|
+
ports:
|
|
1203
|
+
- '5672:5672'
|
|
1204
|
+
- '15672:15672'
|
|
1205
|
+
environment:
|
|
1206
|
+
RABBITMQ_DEFAULT_USER: guest
|
|
1207
|
+
RABBITMQ_DEFAULT_PASS: guest
|
|
1208
|
+
volumes:
|
|
1209
|
+
- rabbitmq_data:/var/lib/rabbitmq
|
|
1210
|
+
healthcheck:
|
|
1211
|
+
test: ['CMD', 'rabbitmq-diagnostics', 'check_running']
|
|
1212
|
+
interval: 10s
|
|
1213
|
+
timeout: 5s
|
|
1214
|
+
retries: 5`);
|
|
1215
|
+
volumes.push(" rabbitmq_data:");
|
|
1216
|
+
}
|
|
1217
|
+
let dockerCompose = `version: '3.8'
|
|
1218
|
+
|
|
1219
|
+
services:
|
|
1220
|
+
${services.join("\n\n")}
|
|
1221
|
+
`;
|
|
1222
|
+
if (volumes.length > 0) dockerCompose += `
|
|
1223
|
+
volumes:
|
|
1224
|
+
${volumes.join("\n")}
|
|
1225
|
+
`;
|
|
1226
|
+
return [{
|
|
1227
|
+
path: "docker-compose.yml",
|
|
1228
|
+
content: dockerCompose
|
|
1229
|
+
}];
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
//#endregion
|
|
1233
|
+
//#region src/init/generators/env.ts
|
|
1234
|
+
/**
|
|
1235
|
+
* Generate environment files (.env, .env.example, .env.development, .env.test, .gitignore)
|
|
1236
|
+
*/
|
|
1237
|
+
function generateEnvFiles(options, template) {
|
|
1238
|
+
const { database } = options;
|
|
1239
|
+
const isServerless = template.name === "serverless";
|
|
1240
|
+
const hasWorker = template.name === "worker";
|
|
1241
|
+
let baseEnv = `# Application
|
|
1242
|
+
NODE_ENV=development
|
|
1243
|
+
PORT=3000
|
|
1244
|
+
LOG_LEVEL=info
|
|
1245
|
+
`;
|
|
1246
|
+
if (isServerless) baseEnv = `# AWS
|
|
1247
|
+
STAGE=dev
|
|
1248
|
+
AWS_REGION=us-east-1
|
|
1249
|
+
LOG_LEVEL=info
|
|
1250
|
+
`;
|
|
1251
|
+
if (database) baseEnv += `
|
|
1252
|
+
# Database
|
|
1253
|
+
DATABASE_URL=postgresql://user:password@localhost:5432/mydb
|
|
1254
|
+
`;
|
|
1255
|
+
if (hasWorker) baseEnv += `
|
|
1256
|
+
# Message Queue
|
|
1257
|
+
RABBITMQ_URL=amqp://localhost:5672
|
|
1258
|
+
`;
|
|
1259
|
+
baseEnv += `
|
|
1260
|
+
# Authentication
|
|
1261
|
+
JWT_SECRET=your-secret-key-change-in-production
|
|
1262
|
+
`;
|
|
1263
|
+
let devEnv = `# Development Environment
|
|
1264
|
+
NODE_ENV=development
|
|
1265
|
+
PORT=3000
|
|
1266
|
+
LOG_LEVEL=debug
|
|
1267
|
+
`;
|
|
1268
|
+
if (isServerless) devEnv = `# Development Environment
|
|
1269
|
+
STAGE=dev
|
|
1270
|
+
AWS_REGION=us-east-1
|
|
1271
|
+
LOG_LEVEL=debug
|
|
1272
|
+
`;
|
|
1273
|
+
if (database) devEnv += `
|
|
1274
|
+
# Database
|
|
1275
|
+
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/mydb_dev
|
|
1276
|
+
`;
|
|
1277
|
+
if (hasWorker) devEnv += `
|
|
1278
|
+
# Message Queue
|
|
1279
|
+
RABBITMQ_URL=amqp://localhost:5672
|
|
1280
|
+
`;
|
|
1281
|
+
devEnv += `
|
|
1282
|
+
# Authentication
|
|
1283
|
+
JWT_SECRET=dev-secret-not-for-production
|
|
1284
|
+
`;
|
|
1285
|
+
let testEnv = `# Test Environment
|
|
1286
|
+
NODE_ENV=test
|
|
1287
|
+
PORT=3001
|
|
1288
|
+
LOG_LEVEL=error
|
|
1289
|
+
`;
|
|
1290
|
+
if (isServerless) testEnv = `# Test Environment
|
|
1291
|
+
STAGE=test
|
|
1292
|
+
AWS_REGION=us-east-1
|
|
1293
|
+
LOG_LEVEL=error
|
|
1294
|
+
`;
|
|
1295
|
+
if (database) testEnv += `
|
|
1296
|
+
# Database
|
|
1297
|
+
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/mydb_test
|
|
1298
|
+
`;
|
|
1299
|
+
if (hasWorker) testEnv += `
|
|
1300
|
+
# Message Queue
|
|
1301
|
+
RABBITMQ_URL=amqp://localhost:5672
|
|
1302
|
+
`;
|
|
1303
|
+
testEnv += `
|
|
1304
|
+
# Authentication
|
|
1305
|
+
JWT_SECRET=test-secret-not-for-production
|
|
1306
|
+
`;
|
|
1307
|
+
const files = [
|
|
1308
|
+
{
|
|
1309
|
+
path: ".env.example",
|
|
1310
|
+
content: baseEnv
|
|
1311
|
+
},
|
|
1312
|
+
{
|
|
1313
|
+
path: ".env",
|
|
1314
|
+
content: baseEnv
|
|
1315
|
+
},
|
|
1316
|
+
{
|
|
1317
|
+
path: ".env.development",
|
|
1318
|
+
content: devEnv
|
|
1319
|
+
},
|
|
1320
|
+
{
|
|
1321
|
+
path: ".env.test",
|
|
1322
|
+
content: testEnv
|
|
1323
|
+
}
|
|
1324
|
+
];
|
|
1325
|
+
if (!options.monorepo) {
|
|
1326
|
+
const gitignore = `# Dependencies
|
|
1327
|
+
node_modules/
|
|
1328
|
+
|
|
1329
|
+
# Build output
|
|
1330
|
+
dist/
|
|
1331
|
+
.gkm/
|
|
1332
|
+
|
|
1333
|
+
# Environment
|
|
1334
|
+
.env
|
|
1335
|
+
.env.local
|
|
1336
|
+
.env.*.local
|
|
1337
|
+
|
|
1338
|
+
# IDE
|
|
1339
|
+
.idea/
|
|
1340
|
+
.vscode/
|
|
1341
|
+
*.swp
|
|
1342
|
+
*.swo
|
|
1343
|
+
|
|
1344
|
+
# OS
|
|
1345
|
+
.DS_Store
|
|
1346
|
+
Thumbs.db
|
|
1347
|
+
|
|
1348
|
+
# Logs
|
|
1349
|
+
*.log
|
|
1350
|
+
npm-debug.log*
|
|
1351
|
+
yarn-debug.log*
|
|
1352
|
+
pnpm-debug.log*
|
|
1353
|
+
|
|
1354
|
+
# Test coverage
|
|
1355
|
+
coverage/
|
|
1356
|
+
|
|
1357
|
+
# TypeScript cache
|
|
1358
|
+
*.tsbuildinfo
|
|
1359
|
+
`;
|
|
1360
|
+
files.push({
|
|
1361
|
+
path: ".gitignore",
|
|
1362
|
+
content: gitignore
|
|
1363
|
+
});
|
|
1364
|
+
}
|
|
1365
|
+
return files;
|
|
1366
|
+
}
|
|
1367
|
+
|
|
1368
|
+
//#endregion
|
|
1369
|
+
//#region src/init/generators/models.ts
|
|
1370
|
+
/**
|
|
1371
|
+
* Generate packages/models for shared Zod schemas (monorepo only)
|
|
1372
|
+
*/
|
|
1373
|
+
function generateModelsPackage(options) {
|
|
1374
|
+
if (!options.monorepo) return [];
|
|
1375
|
+
const packageName = `@${options.name}/models`;
|
|
1376
|
+
const packageJson = {
|
|
1377
|
+
name: packageName,
|
|
1378
|
+
version: "0.0.1",
|
|
1379
|
+
private: true,
|
|
1380
|
+
type: "module",
|
|
1381
|
+
exports: {
|
|
1382
|
+
".": {
|
|
1383
|
+
types: "./dist/index.d.ts",
|
|
1384
|
+
import: "./dist/index.js"
|
|
1385
|
+
},
|
|
1386
|
+
"./*": {
|
|
1387
|
+
types: "./dist/*.d.ts",
|
|
1388
|
+
import: "./dist/*.js"
|
|
1389
|
+
}
|
|
1390
|
+
},
|
|
1391
|
+
scripts: {
|
|
1392
|
+
build: "tsc",
|
|
1393
|
+
"build:watch": "tsc --watch",
|
|
1394
|
+
typecheck: "tsc --noEmit"
|
|
1395
|
+
},
|
|
1396
|
+
dependencies: { zod: "~4.1.0" },
|
|
1397
|
+
devDependencies: { typescript: "~5.8.2" }
|
|
1398
|
+
};
|
|
1399
|
+
const tsConfig = {
|
|
1400
|
+
extends: "../../tsconfig.json",
|
|
1401
|
+
compilerOptions: {
|
|
1402
|
+
outDir: "./dist",
|
|
1403
|
+
rootDir: "./src"
|
|
1404
|
+
},
|
|
1405
|
+
include: ["src/**/*.ts"],
|
|
1406
|
+
exclude: ["node_modules", "dist"]
|
|
1407
|
+
};
|
|
1408
|
+
const indexTs = `import { z } from 'zod';
|
|
1409
|
+
|
|
1410
|
+
// ============================================
|
|
1411
|
+
// Common Schemas
|
|
1412
|
+
// ============================================
|
|
1413
|
+
|
|
1414
|
+
export const idSchema = z.string().uuid();
|
|
1415
|
+
|
|
1416
|
+
export const timestampsSchema = z.object({
|
|
1417
|
+
createdAt: z.coerce.date(),
|
|
1418
|
+
updatedAt: z.coerce.date(),
|
|
1419
|
+
});
|
|
1420
|
+
|
|
1421
|
+
export const paginationSchema = z.object({
|
|
1422
|
+
page: z.coerce.number().int().positive().default(1),
|
|
1423
|
+
limit: z.coerce.number().int().positive().max(100).default(20),
|
|
1424
|
+
});
|
|
1425
|
+
|
|
1426
|
+
export const paginatedResponseSchema = <T extends z.ZodTypeAny>(itemSchema: T) =>
|
|
1427
|
+
z.object({
|
|
1428
|
+
items: z.array(itemSchema),
|
|
1429
|
+
total: z.number(),
|
|
1430
|
+
page: z.number(),
|
|
1431
|
+
limit: z.number(),
|
|
1432
|
+
totalPages: z.number(),
|
|
1433
|
+
});
|
|
1434
|
+
|
|
1435
|
+
// ============================================
|
|
1436
|
+
// User Schemas
|
|
1437
|
+
// ============================================
|
|
1438
|
+
|
|
1439
|
+
export const userSchema = z.object({
|
|
1440
|
+
id: idSchema,
|
|
1441
|
+
email: z.string().email(),
|
|
1442
|
+
name: z.string().min(1).max(100),
|
|
1443
|
+
...timestampsSchema.shape,
|
|
1444
|
+
});
|
|
1445
|
+
|
|
1446
|
+
export const createUserSchema = userSchema.omit({
|
|
1447
|
+
id: true,
|
|
1448
|
+
createdAt: true,
|
|
1449
|
+
updatedAt: true,
|
|
1450
|
+
});
|
|
1451
|
+
|
|
1452
|
+
export const updateUserSchema = createUserSchema.partial();
|
|
1453
|
+
|
|
1454
|
+
// ============================================
|
|
1455
|
+
// Type Exports
|
|
1456
|
+
// ============================================
|
|
1457
|
+
|
|
1458
|
+
export type Id = z.infer<typeof idSchema>;
|
|
1459
|
+
export type Timestamps = z.infer<typeof timestampsSchema>;
|
|
1460
|
+
export type Pagination = z.infer<typeof paginationSchema>;
|
|
1461
|
+
export type User = z.infer<typeof userSchema>;
|
|
1462
|
+
export type CreateUser = z.infer<typeof createUserSchema>;
|
|
1463
|
+
export type UpdateUser = z.infer<typeof updateUserSchema>;
|
|
1464
|
+
`;
|
|
1465
|
+
return [
|
|
1466
|
+
{
|
|
1467
|
+
path: "packages/models/package.json",
|
|
1468
|
+
content: JSON.stringify(packageJson, null, 2) + "\n"
|
|
1469
|
+
},
|
|
1470
|
+
{
|
|
1471
|
+
path: "packages/models/tsconfig.json",
|
|
1472
|
+
content: JSON.stringify(tsConfig, null, 2) + "\n"
|
|
1473
|
+
},
|
|
1474
|
+
{
|
|
1475
|
+
path: "packages/models/src/index.ts",
|
|
1476
|
+
content: indexTs
|
|
1477
|
+
}
|
|
1478
|
+
];
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1481
|
+
//#endregion
|
|
1482
|
+
//#region src/init/generators/monorepo.ts
|
|
1483
|
+
/**
|
|
1484
|
+
* Generate monorepo root files (pnpm-workspace.yaml, root package.json, etc.)
|
|
1485
|
+
*/
|
|
1486
|
+
function generateMonorepoFiles(options, _template) {
|
|
1487
|
+
if (!options.monorepo) return [];
|
|
1488
|
+
const rootPackageJson = {
|
|
1489
|
+
name: options.name,
|
|
1490
|
+
version: "0.0.1",
|
|
1491
|
+
private: true,
|
|
1492
|
+
type: "module",
|
|
1493
|
+
scripts: {
|
|
1494
|
+
dev: "turbo dev",
|
|
1495
|
+
build: "turbo build",
|
|
1496
|
+
test: "turbo test",
|
|
1497
|
+
"test:once": "turbo test:once",
|
|
1498
|
+
typecheck: "turbo typecheck",
|
|
1499
|
+
lint: "biome lint .",
|
|
1500
|
+
fmt: "biome format . --write",
|
|
1501
|
+
"fmt:check": "biome format ."
|
|
1502
|
+
},
|
|
1503
|
+
devDependencies: {
|
|
1504
|
+
"@biomejs/biome": "~1.9.4",
|
|
1505
|
+
turbo: "~2.3.0",
|
|
1506
|
+
typescript: "~5.8.2",
|
|
1507
|
+
vitest: "~4.0.0"
|
|
1508
|
+
}
|
|
1509
|
+
};
|
|
1510
|
+
const apiPathParts = options.apiPath.split("/");
|
|
1511
|
+
const appsFolder = apiPathParts[0] || "apps";
|
|
1512
|
+
const pnpmWorkspace = `packages:
|
|
1513
|
+
- '${appsFolder}/*'
|
|
1514
|
+
- 'packages/*'
|
|
1515
|
+
`;
|
|
1516
|
+
const biomeConfig = {
|
|
1517
|
+
$schema: "https://biomejs.dev/schemas/1.9.4/schema.json",
|
|
1518
|
+
vcs: {
|
|
1519
|
+
enabled: true,
|
|
1520
|
+
clientKind: "git",
|
|
1521
|
+
useIgnoreFile: true
|
|
1522
|
+
},
|
|
1523
|
+
organizeImports: { enabled: true },
|
|
1524
|
+
formatter: {
|
|
1525
|
+
enabled: true,
|
|
1526
|
+
indentStyle: "space",
|
|
1527
|
+
indentWidth: 2,
|
|
1528
|
+
lineWidth: 80
|
|
1529
|
+
},
|
|
1530
|
+
javascript: { formatter: {
|
|
1531
|
+
quoteStyle: "single",
|
|
1532
|
+
trailingCommas: "all",
|
|
1533
|
+
semicolons: "always",
|
|
1534
|
+
arrowParentheses: "always"
|
|
1535
|
+
} },
|
|
1536
|
+
linter: {
|
|
1537
|
+
enabled: true,
|
|
1538
|
+
rules: {
|
|
1539
|
+
recommended: true,
|
|
1540
|
+
correctness: {
|
|
1541
|
+
noUnusedImports: "error",
|
|
1542
|
+
noUnusedVariables: "error"
|
|
1543
|
+
},
|
|
1544
|
+
style: { noNonNullAssertion: "off" }
|
|
1545
|
+
}
|
|
1546
|
+
},
|
|
1547
|
+
files: { ignore: [
|
|
1548
|
+
"node_modules",
|
|
1549
|
+
"dist",
|
|
1550
|
+
".gkm",
|
|
1551
|
+
"coverage"
|
|
1552
|
+
] }
|
|
1553
|
+
};
|
|
1554
|
+
const turboConfig = {
|
|
1555
|
+
$schema: "https://turbo.build/schema.json",
|
|
1556
|
+
tasks: {
|
|
1557
|
+
build: {
|
|
1558
|
+
dependsOn: ["^build"],
|
|
1559
|
+
outputs: ["dist/**"]
|
|
1560
|
+
},
|
|
1561
|
+
dev: {
|
|
1562
|
+
cache: false,
|
|
1563
|
+
persistent: true
|
|
1564
|
+
},
|
|
1565
|
+
test: {
|
|
1566
|
+
dependsOn: ["^build"],
|
|
1567
|
+
cache: false
|
|
1568
|
+
},
|
|
1569
|
+
"test:once": {
|
|
1570
|
+
dependsOn: ["^build"],
|
|
1571
|
+
outputs: ["coverage/**"]
|
|
1572
|
+
},
|
|
1573
|
+
typecheck: {
|
|
1574
|
+
dependsOn: ["^build"],
|
|
1575
|
+
outputs: []
|
|
1576
|
+
},
|
|
1577
|
+
lint: { outputs: [] },
|
|
1578
|
+
fmt: { outputs: [] }
|
|
1579
|
+
}
|
|
1580
|
+
};
|
|
1581
|
+
const gitignore = `# Dependencies
|
|
1582
|
+
node_modules/
|
|
1583
|
+
|
|
1584
|
+
# Build output
|
|
1585
|
+
dist/
|
|
1586
|
+
.gkm/
|
|
1587
|
+
|
|
1588
|
+
# Environment
|
|
1589
|
+
.env
|
|
1590
|
+
.env.local
|
|
1591
|
+
.env.*.local
|
|
1592
|
+
|
|
1593
|
+
# IDE
|
|
1594
|
+
.idea/
|
|
1595
|
+
.vscode/
|
|
1596
|
+
*.swp
|
|
1597
|
+
*.swo
|
|
1598
|
+
|
|
1599
|
+
# OS
|
|
1600
|
+
.DS_Store
|
|
1601
|
+
Thumbs.db
|
|
1602
|
+
|
|
1603
|
+
# Logs
|
|
1604
|
+
*.log
|
|
1605
|
+
npm-debug.log*
|
|
1606
|
+
yarn-debug.log*
|
|
1607
|
+
pnpm-debug.log*
|
|
1608
|
+
|
|
1609
|
+
# Test coverage
|
|
1610
|
+
coverage/
|
|
1611
|
+
|
|
1612
|
+
# TypeScript cache
|
|
1613
|
+
*.tsbuildinfo
|
|
1614
|
+
|
|
1615
|
+
# Turbo
|
|
1616
|
+
.turbo/
|
|
1617
|
+
`;
|
|
1618
|
+
const tsConfig = {
|
|
1619
|
+
compilerOptions: {
|
|
1620
|
+
target: "ES2022",
|
|
1621
|
+
module: "NodeNext",
|
|
1622
|
+
moduleResolution: "NodeNext",
|
|
1623
|
+
lib: ["ES2022"],
|
|
1624
|
+
strict: true,
|
|
1625
|
+
esModuleInterop: true,
|
|
1626
|
+
skipLibCheck: true,
|
|
1627
|
+
forceConsistentCasingInFileNames: true,
|
|
1628
|
+
resolveJsonModule: true,
|
|
1629
|
+
declaration: true,
|
|
1630
|
+
declarationMap: true,
|
|
1631
|
+
composite: true
|
|
1632
|
+
},
|
|
1633
|
+
exclude: ["node_modules", "dist"]
|
|
1634
|
+
};
|
|
1635
|
+
return [
|
|
1636
|
+
{
|
|
1637
|
+
path: "package.json",
|
|
1638
|
+
content: JSON.stringify(rootPackageJson, null, 2) + "\n"
|
|
1639
|
+
},
|
|
1640
|
+
{
|
|
1641
|
+
path: "pnpm-workspace.yaml",
|
|
1642
|
+
content: pnpmWorkspace
|
|
1643
|
+
},
|
|
1644
|
+
{
|
|
1645
|
+
path: "tsconfig.json",
|
|
1646
|
+
content: JSON.stringify(tsConfig, null, 2) + "\n"
|
|
1647
|
+
},
|
|
1648
|
+
{
|
|
1649
|
+
path: "biome.json",
|
|
1650
|
+
content: JSON.stringify(biomeConfig, null, 2) + "\n"
|
|
1651
|
+
},
|
|
1652
|
+
{
|
|
1653
|
+
path: "turbo.json",
|
|
1654
|
+
content: JSON.stringify(turboConfig, null, 2) + "\n"
|
|
1655
|
+
},
|
|
1656
|
+
{
|
|
1657
|
+
path: ".gitignore",
|
|
1658
|
+
content: gitignore
|
|
1659
|
+
}
|
|
1660
|
+
];
|
|
1661
|
+
}
|
|
1662
|
+
|
|
1663
|
+
//#endregion
|
|
1664
|
+
//#region src/init/templates/api.ts
|
|
1665
|
+
const apiTemplate = {
|
|
1666
|
+
name: "api",
|
|
1667
|
+
description: "Full API with auth, database, services",
|
|
1668
|
+
dependencies: {
|
|
1669
|
+
"@geekmidas/constructs": "workspace:*",
|
|
1670
|
+
"@geekmidas/envkit": "workspace:*",
|
|
1671
|
+
"@geekmidas/logger": "workspace:*",
|
|
1672
|
+
"@geekmidas/services": "workspace:*",
|
|
1673
|
+
"@geekmidas/errors": "workspace:*",
|
|
1674
|
+
"@geekmidas/auth": "workspace:*",
|
|
1675
|
+
hono: "~4.8.2",
|
|
1676
|
+
pino: "~9.6.0"
|
|
1677
|
+
},
|
|
1678
|
+
devDependencies: {
|
|
1679
|
+
"@biomejs/biome": "~1.9.4",
|
|
1680
|
+
"@geekmidas/cli": "workspace:*",
|
|
1681
|
+
"@types/node": "~22.0.0",
|
|
1682
|
+
tsx: "~4.20.0",
|
|
1683
|
+
turbo: "~2.3.0",
|
|
1684
|
+
typescript: "~5.8.2",
|
|
1685
|
+
vitest: "~4.0.0"
|
|
1686
|
+
},
|
|
1687
|
+
scripts: {
|
|
1688
|
+
dev: "gkm dev",
|
|
1689
|
+
build: "gkm build",
|
|
1690
|
+
test: "vitest",
|
|
1691
|
+
"test:once": "vitest run",
|
|
1692
|
+
typecheck: "tsc --noEmit",
|
|
1693
|
+
lint: "biome lint .",
|
|
1694
|
+
fmt: "biome format . --write",
|
|
1695
|
+
"fmt:check": "biome format ."
|
|
1696
|
+
},
|
|
1697
|
+
files: (options) => {
|
|
1698
|
+
const { loggerType, routesStructure } = options;
|
|
1699
|
+
const loggerContent = `import { createLogger } from '@geekmidas/logger/${loggerType}';
|
|
1700
|
+
|
|
1701
|
+
export const logger = createLogger();
|
|
1702
|
+
`;
|
|
1703
|
+
const getRoutePath = (file) => {
|
|
1704
|
+
switch (routesStructure) {
|
|
1705
|
+
case "centralized-endpoints": return `src/endpoints/${file}`;
|
|
1706
|
+
case "centralized-routes": return `src/routes/${file}`;
|
|
1707
|
+
case "domain-based": {
|
|
1708
|
+
const parts = file.split("/");
|
|
1709
|
+
if (parts.length === 1) return `src/${file.replace(".ts", "")}/routes/index.ts`;
|
|
1710
|
+
return `src/${parts[0]}/routes/${parts.slice(1).join("/")}`;
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
};
|
|
1714
|
+
const files = [
|
|
1715
|
+
{
|
|
1716
|
+
path: "src/config/env.ts",
|
|
1717
|
+
content: `import { EnvironmentParser } from '@geekmidas/envkit';
|
|
1718
|
+
|
|
1719
|
+
export const envParser = new EnvironmentParser(process.env);
|
|
1720
|
+
|
|
1721
|
+
export const config = envParser
|
|
1722
|
+
.create((get) => ({
|
|
1723
|
+
port: get('PORT').string().transform(Number).default(3000),
|
|
1724
|
+
nodeEnv: get('NODE_ENV').string().default('development'),
|
|
1725
|
+
jwtSecret: get('JWT_SECRET').string().default('change-me-in-production'),${options.database ? `
|
|
1726
|
+
database: {
|
|
1727
|
+
url: get('DATABASE_URL').string().default('postgresql://localhost:5432/mydb'),
|
|
1728
|
+
},` : ""}
|
|
1729
|
+
}))
|
|
1730
|
+
.parse();
|
|
1731
|
+
`
|
|
1732
|
+
},
|
|
1733
|
+
{
|
|
1734
|
+
path: "src/config/logger.ts",
|
|
1735
|
+
content: loggerContent
|
|
1736
|
+
},
|
|
1737
|
+
{
|
|
1738
|
+
path: getRoutePath("health.ts"),
|
|
1739
|
+
content: `import { e } from '@geekmidas/constructs/endpoints';
|
|
1740
|
+
|
|
1741
|
+
export default e
|
|
1742
|
+
.get('/health')
|
|
1743
|
+
.handle(async () => ({
|
|
1744
|
+
status: 'ok',
|
|
1745
|
+
timestamp: new Date().toISOString(),
|
|
1746
|
+
}));
|
|
1747
|
+
`
|
|
1748
|
+
},
|
|
1749
|
+
{
|
|
1750
|
+
path: getRoutePath("users/list.ts"),
|
|
1751
|
+
content: `import { e } from '@geekmidas/constructs/endpoints';
|
|
1752
|
+
|
|
1753
|
+
export default e
|
|
1754
|
+
.get('/users')
|
|
1755
|
+
.handle(async () => ({
|
|
1756
|
+
users: [
|
|
1757
|
+
{ id: '1', name: 'Alice' },
|
|
1758
|
+
{ id: '2', name: 'Bob' },
|
|
1759
|
+
],
|
|
1760
|
+
}));
|
|
1761
|
+
`
|
|
1762
|
+
},
|
|
1763
|
+
{
|
|
1764
|
+
path: getRoutePath("users/get.ts"),
|
|
1765
|
+
content: `import { e } from '@geekmidas/constructs/endpoints';
|
|
1766
|
+
import { z } from 'zod';
|
|
1767
|
+
|
|
1768
|
+
export default e
|
|
1769
|
+
.get('/users/:id')
|
|
1770
|
+
.params(z.object({ id: z.string() }))
|
|
1771
|
+
.handle(async ({ params }) => ({
|
|
1772
|
+
id: params.id,
|
|
1773
|
+
name: 'Alice',
|
|
1774
|
+
email: 'alice@example.com',
|
|
1775
|
+
}));
|
|
1776
|
+
`
|
|
1777
|
+
}
|
|
1778
|
+
];
|
|
1779
|
+
if (options.database) files.push({
|
|
1780
|
+
path: "src/services/database.ts",
|
|
1781
|
+
content: `import type { Service } from '@geekmidas/services';
|
|
1782
|
+
import { Kysely, PostgresDialect } from 'kysely';
|
|
1783
|
+
import pg from 'pg';
|
|
1784
|
+
|
|
1785
|
+
// Define your database schema
|
|
1786
|
+
export interface Database {
|
|
1787
|
+
users: {
|
|
1788
|
+
id: string;
|
|
1789
|
+
name: string;
|
|
1790
|
+
email: string;
|
|
1791
|
+
created_at: Date;
|
|
1792
|
+
};
|
|
1793
|
+
}
|
|
1794
|
+
|
|
1795
|
+
export const databaseService = {
|
|
1796
|
+
serviceName: 'database' as const,
|
|
1797
|
+
async register(envParser) {
|
|
1798
|
+
const config = envParser
|
|
1799
|
+
.create((get) => ({
|
|
1800
|
+
url: get('DATABASE_URL').string(),
|
|
1801
|
+
}))
|
|
1802
|
+
.parse();
|
|
1803
|
+
|
|
1804
|
+
return new Kysely<Database>({
|
|
1805
|
+
dialect: new PostgresDialect({
|
|
1806
|
+
pool: new pg.Pool({ connectionString: config.url }),
|
|
1807
|
+
}),
|
|
1808
|
+
});
|
|
1809
|
+
},
|
|
1810
|
+
} satisfies Service<'database', Kysely<Database>>;
|
|
1811
|
+
`
|
|
1812
|
+
});
|
|
1813
|
+
if (options.telescope) files.push({
|
|
1814
|
+
path: "src/config/telescope.ts",
|
|
1815
|
+
content: `import { Telescope } from '@geekmidas/telescope';
|
|
1816
|
+
import { InMemoryStorage } from '@geekmidas/telescope/storage/memory';
|
|
1817
|
+
|
|
1818
|
+
export const telescope = new Telescope({
|
|
1819
|
+
storage: new InMemoryStorage({ maxEntries: 100 }),
|
|
1820
|
+
enabled: process.env.NODE_ENV === 'development',
|
|
1821
|
+
});
|
|
1822
|
+
`
|
|
1823
|
+
});
|
|
1824
|
+
if (options.studio && options.database) files.push({
|
|
1825
|
+
path: "src/config/studio.ts",
|
|
1826
|
+
content: `import { Direction, InMemoryMonitoringStorage, Studio } from '@geekmidas/studio';
|
|
1827
|
+
import { Kysely, PostgresDialect } from 'kysely';
|
|
1828
|
+
import pg from 'pg';
|
|
1829
|
+
import type { Database } from '../services/database';
|
|
1830
|
+
import { config } from './env';
|
|
1831
|
+
|
|
1832
|
+
// Create a Kysely instance for Studio
|
|
1833
|
+
const db = new Kysely<Database>({
|
|
1834
|
+
dialect: new PostgresDialect({
|
|
1835
|
+
pool: new pg.Pool({ connectionString: config.database.url }),
|
|
1836
|
+
}),
|
|
1837
|
+
});
|
|
1838
|
+
|
|
1839
|
+
export const studio = new Studio<Database>({
|
|
1840
|
+
monitoring: {
|
|
1841
|
+
storage: new InMemoryMonitoringStorage({ maxEntries: 100 }),
|
|
1842
|
+
},
|
|
1843
|
+
data: {
|
|
1844
|
+
db,
|
|
1845
|
+
cursor: { field: 'id', direction: Direction.Desc },
|
|
1846
|
+
},
|
|
1847
|
+
enabled: process.env.NODE_ENV === 'development',
|
|
1848
|
+
});
|
|
1849
|
+
`
|
|
1850
|
+
});
|
|
1851
|
+
return files;
|
|
1852
|
+
}
|
|
1853
|
+
};
|
|
1854
|
+
|
|
1855
|
+
//#endregion
|
|
1856
|
+
//#region src/init/templates/minimal.ts
|
|
1857
|
+
const minimalTemplate = {
|
|
1858
|
+
name: "minimal",
|
|
1859
|
+
description: "Basic health endpoint",
|
|
1860
|
+
dependencies: {
|
|
1861
|
+
"@geekmidas/constructs": "workspace:*",
|
|
1862
|
+
"@geekmidas/envkit": "workspace:*",
|
|
1863
|
+
"@geekmidas/logger": "workspace:*",
|
|
1864
|
+
hono: "~4.8.2",
|
|
1865
|
+
pino: "~9.6.0"
|
|
1866
|
+
},
|
|
1867
|
+
devDependencies: {
|
|
1868
|
+
"@biomejs/biome": "~1.9.4",
|
|
1869
|
+
"@geekmidas/cli": "workspace:*",
|
|
1870
|
+
"@types/node": "~22.0.0",
|
|
1871
|
+
tsx: "~4.20.0",
|
|
1872
|
+
turbo: "~2.3.0",
|
|
1873
|
+
typescript: "~5.8.2",
|
|
1874
|
+
vitest: "~4.0.0"
|
|
1875
|
+
},
|
|
1876
|
+
scripts: {
|
|
1877
|
+
dev: "gkm dev",
|
|
1878
|
+
build: "gkm build",
|
|
1879
|
+
test: "vitest",
|
|
1880
|
+
"test:once": "vitest run",
|
|
1881
|
+
typecheck: "tsc --noEmit",
|
|
1882
|
+
lint: "biome lint .",
|
|
1883
|
+
fmt: "biome format . --write",
|
|
1884
|
+
"fmt:check": "biome format ."
|
|
1885
|
+
},
|
|
1886
|
+
files: (options) => {
|
|
1887
|
+
const { loggerType, routesStructure } = options;
|
|
1888
|
+
const loggerContent = `import { createLogger } from '@geekmidas/logger/${loggerType}';
|
|
1889
|
+
|
|
1890
|
+
export const logger = createLogger();
|
|
1891
|
+
`;
|
|
1892
|
+
const getRoutePath = (file) => {
|
|
1893
|
+
switch (routesStructure) {
|
|
1894
|
+
case "centralized-endpoints": return `src/endpoints/${file}`;
|
|
1895
|
+
case "centralized-routes": return `src/routes/${file}`;
|
|
1896
|
+
case "domain-based": return `src/${file.replace(".ts", "")}/routes/index.ts`;
|
|
1897
|
+
}
|
|
1898
|
+
};
|
|
1899
|
+
const files = [
|
|
1900
|
+
{
|
|
1901
|
+
path: "src/config/env.ts",
|
|
1902
|
+
content: `import { EnvironmentParser } from '@geekmidas/envkit';
|
|
1903
|
+
|
|
1904
|
+
export const envParser = new EnvironmentParser(process.env);
|
|
1905
|
+
|
|
1906
|
+
export const config = envParser
|
|
1907
|
+
.create((get) => ({
|
|
1908
|
+
port: get('PORT').string().transform(Number).default(3000),
|
|
1909
|
+
nodeEnv: get('NODE_ENV').string().default('development'),
|
|
1910
|
+
}))
|
|
1911
|
+
.parse();
|
|
1912
|
+
`
|
|
1913
|
+
},
|
|
1914
|
+
{
|
|
1915
|
+
path: "src/config/logger.ts",
|
|
1916
|
+
content: loggerContent
|
|
1917
|
+
},
|
|
1918
|
+
{
|
|
1919
|
+
path: getRoutePath("health.ts"),
|
|
1920
|
+
content: `import { e } from '@geekmidas/constructs/endpoints';
|
|
1921
|
+
|
|
1922
|
+
export default e
|
|
1923
|
+
.get('/health')
|
|
1924
|
+
.handle(async () => ({
|
|
1925
|
+
status: 'ok',
|
|
1926
|
+
timestamp: new Date().toISOString(),
|
|
1927
|
+
}));
|
|
1928
|
+
`
|
|
1929
|
+
}
|
|
1930
|
+
];
|
|
1931
|
+
if (options.database) {
|
|
1932
|
+
files[0] = {
|
|
1933
|
+
path: "src/config/env.ts",
|
|
1934
|
+
content: `import { EnvironmentParser } from '@geekmidas/envkit';
|
|
1935
|
+
|
|
1936
|
+
export const envParser = new EnvironmentParser(process.env);
|
|
1937
|
+
|
|
1938
|
+
export const config = envParser
|
|
1939
|
+
.create((get) => ({
|
|
1940
|
+
port: get('PORT').string().transform(Number).default(3000),
|
|
1941
|
+
nodeEnv: get('NODE_ENV').string().default('development'),
|
|
1942
|
+
database: {
|
|
1943
|
+
url: get('DATABASE_URL').string().default('postgresql://localhost:5432/mydb'),
|
|
1944
|
+
},
|
|
1945
|
+
}))
|
|
1946
|
+
.parse();
|
|
1947
|
+
`
|
|
1948
|
+
};
|
|
1949
|
+
files.push({
|
|
1950
|
+
path: "src/services/database.ts",
|
|
1951
|
+
content: `import type { Service } from '@geekmidas/services';
|
|
1952
|
+
import { Kysely, PostgresDialect } from 'kysely';
|
|
1953
|
+
import pg from 'pg';
|
|
1954
|
+
|
|
1955
|
+
// Define your database schema
|
|
1956
|
+
export interface Database {
|
|
1957
|
+
// Add your tables here
|
|
1958
|
+
}
|
|
1959
|
+
|
|
1960
|
+
export const databaseService = {
|
|
1961
|
+
serviceName: 'database' as const,
|
|
1962
|
+
async register(envParser) {
|
|
1963
|
+
const config = envParser
|
|
1964
|
+
.create((get) => ({
|
|
1965
|
+
url: get('DATABASE_URL').string(),
|
|
1966
|
+
}))
|
|
1967
|
+
.parse();
|
|
1968
|
+
|
|
1969
|
+
return new Kysely<Database>({
|
|
1970
|
+
dialect: new PostgresDialect({
|
|
1971
|
+
pool: new pg.Pool({ connectionString: config.url }),
|
|
1972
|
+
}),
|
|
1973
|
+
});
|
|
1974
|
+
},
|
|
1975
|
+
} satisfies Service<'database', Kysely<Database>>;
|
|
1976
|
+
`
|
|
1977
|
+
});
|
|
1978
|
+
}
|
|
1979
|
+
if (options.telescope) files.push({
|
|
1980
|
+
path: "src/config/telescope.ts",
|
|
1981
|
+
content: `import { Telescope } from '@geekmidas/telescope';
|
|
1982
|
+
import { InMemoryStorage } from '@geekmidas/telescope/storage/memory';
|
|
1983
|
+
|
|
1984
|
+
export const telescope = new Telescope({
|
|
1985
|
+
storage: new InMemoryStorage({ maxEntries: 100 }),
|
|
1986
|
+
enabled: process.env.NODE_ENV === 'development',
|
|
1987
|
+
});
|
|
1988
|
+
`
|
|
1989
|
+
});
|
|
1990
|
+
if (options.studio && options.database) files.push({
|
|
1991
|
+
path: "src/config/studio.ts",
|
|
1992
|
+
content: `import { Direction, InMemoryMonitoringStorage, Studio } from '@geekmidas/studio';
|
|
1993
|
+
import { Kysely, PostgresDialect } from 'kysely';
|
|
1994
|
+
import pg from 'pg';
|
|
1995
|
+
import type { Database } from '../services/database';
|
|
1996
|
+
import { config } from './env';
|
|
1997
|
+
|
|
1998
|
+
// Create a Kysely instance for Studio
|
|
1999
|
+
const db = new Kysely<Database>({
|
|
2000
|
+
dialect: new PostgresDialect({
|
|
2001
|
+
pool: new pg.Pool({ connectionString: config.database.url }),
|
|
2002
|
+
}),
|
|
2003
|
+
});
|
|
2004
|
+
|
|
2005
|
+
export const studio = new Studio<Database>({
|
|
2006
|
+
monitoring: {
|
|
2007
|
+
storage: new InMemoryMonitoringStorage({ maxEntries: 100 }),
|
|
2008
|
+
},
|
|
2009
|
+
data: {
|
|
2010
|
+
db,
|
|
2011
|
+
cursor: { field: 'id', direction: Direction.Desc },
|
|
2012
|
+
},
|
|
2013
|
+
enabled: process.env.NODE_ENV === 'development',
|
|
2014
|
+
});
|
|
2015
|
+
`
|
|
2016
|
+
});
|
|
2017
|
+
return files;
|
|
2018
|
+
}
|
|
2019
|
+
};
|
|
2020
|
+
|
|
2021
|
+
//#endregion
|
|
2022
|
+
//#region src/init/templates/serverless.ts
|
|
2023
|
+
const serverlessTemplate = {
|
|
2024
|
+
name: "serverless",
|
|
2025
|
+
description: "AWS Lambda handlers",
|
|
2026
|
+
dependencies: {
|
|
2027
|
+
"@geekmidas/constructs": "workspace:*",
|
|
2028
|
+
"@geekmidas/envkit": "workspace:*",
|
|
2029
|
+
"@geekmidas/logger": "workspace:*",
|
|
2030
|
+
"@geekmidas/cloud": "workspace:*",
|
|
2031
|
+
hono: "~4.8.2",
|
|
2032
|
+
pino: "~9.6.0"
|
|
2033
|
+
},
|
|
2034
|
+
devDependencies: {
|
|
2035
|
+
"@biomejs/biome": "~1.9.4",
|
|
2036
|
+
"@geekmidas/cli": "workspace:*",
|
|
2037
|
+
"@types/aws-lambda": "~8.10.92",
|
|
2038
|
+
"@types/node": "~22.0.0",
|
|
2039
|
+
tsx: "~4.20.0",
|
|
2040
|
+
turbo: "~2.3.0",
|
|
2041
|
+
typescript: "~5.8.2",
|
|
2042
|
+
vitest: "~4.0.0"
|
|
2043
|
+
},
|
|
2044
|
+
scripts: {
|
|
2045
|
+
dev: "gkm dev",
|
|
2046
|
+
build: "gkm build --provider aws-apigatewayv2",
|
|
2047
|
+
test: "vitest",
|
|
2048
|
+
"test:once": "vitest run",
|
|
2049
|
+
typecheck: "tsc --noEmit",
|
|
2050
|
+
lint: "biome lint .",
|
|
2051
|
+
fmt: "biome format . --write",
|
|
2052
|
+
"fmt:check": "biome format ."
|
|
2053
|
+
},
|
|
2054
|
+
files: (options) => {
|
|
2055
|
+
const { loggerType, routesStructure } = options;
|
|
2056
|
+
const loggerContent = `import { createLogger } from '@geekmidas/logger/${loggerType}';
|
|
2057
|
+
|
|
2058
|
+
export const logger = createLogger();
|
|
2059
|
+
`;
|
|
2060
|
+
const getRoutePath = (file) => {
|
|
2061
|
+
switch (routesStructure) {
|
|
2062
|
+
case "centralized-endpoints": return `src/endpoints/${file}`;
|
|
2063
|
+
case "centralized-routes": return `src/routes/${file}`;
|
|
2064
|
+
case "domain-based": return `src/${file.replace(".ts", "")}/routes/index.ts`;
|
|
2065
|
+
}
|
|
2066
|
+
};
|
|
2067
|
+
const files = [
|
|
2068
|
+
{
|
|
2069
|
+
path: "src/config/env.ts",
|
|
2070
|
+
content: `import { EnvironmentParser } from '@geekmidas/envkit';
|
|
2071
|
+
|
|
2072
|
+
export const envParser = new EnvironmentParser(process.env);
|
|
2073
|
+
|
|
2074
|
+
export const config = envParser
|
|
2075
|
+
.create((get) => ({
|
|
2076
|
+
stage: get('STAGE').string().default('dev'),
|
|
2077
|
+
region: get('AWS_REGION').string().default('us-east-1'),${options.database ? `
|
|
2078
|
+
database: {
|
|
2079
|
+
url: get('DATABASE_URL').string(),
|
|
2080
|
+
},` : ""}
|
|
2081
|
+
}))
|
|
2082
|
+
.parse();
|
|
2083
|
+
`
|
|
2084
|
+
},
|
|
2085
|
+
{
|
|
2086
|
+
path: "src/config/logger.ts",
|
|
2087
|
+
content: loggerContent
|
|
2088
|
+
},
|
|
2089
|
+
{
|
|
2090
|
+
path: getRoutePath("health.ts"),
|
|
2091
|
+
content: `import { e } from '@geekmidas/constructs/endpoints';
|
|
2092
|
+
|
|
2093
|
+
export default e
|
|
2094
|
+
.get('/health')
|
|
2095
|
+
.handle(async () => ({
|
|
2096
|
+
status: 'ok',
|
|
2097
|
+
timestamp: new Date().toISOString(),
|
|
2098
|
+
region: process.env.AWS_REGION || 'local',
|
|
2099
|
+
}));
|
|
2100
|
+
`
|
|
2101
|
+
},
|
|
2102
|
+
{
|
|
2103
|
+
path: "src/functions/hello.ts",
|
|
2104
|
+
content: `import { f } from '@geekmidas/constructs/functions';
|
|
2105
|
+
import { z } from 'zod';
|
|
2106
|
+
|
|
2107
|
+
export default f
|
|
2108
|
+
.input(z.object({ name: z.string() }))
|
|
2109
|
+
.output(z.object({ message: z.string() }))
|
|
2110
|
+
.handle(async ({ input }) => ({
|
|
2111
|
+
message: \`Hello, \${input.name}!\`,
|
|
2112
|
+
}));
|
|
2113
|
+
`
|
|
2114
|
+
}
|
|
2115
|
+
];
|
|
2116
|
+
if (options.telescope) files.push({
|
|
2117
|
+
path: "src/config/telescope.ts",
|
|
2118
|
+
content: `import { Telescope } from '@geekmidas/telescope';
|
|
2119
|
+
import { InMemoryStorage } from '@geekmidas/telescope/storage/memory';
|
|
2120
|
+
|
|
2121
|
+
// Note: For production Lambda, consider using a persistent storage
|
|
2122
|
+
export const telescope = new Telescope({
|
|
2123
|
+
storage: new InMemoryStorage({ maxEntries: 50 }),
|
|
2124
|
+
enabled: process.env.STAGE === 'dev',
|
|
2125
|
+
});
|
|
2126
|
+
`
|
|
2127
|
+
});
|
|
2128
|
+
return files;
|
|
2129
|
+
}
|
|
2130
|
+
};
|
|
2131
|
+
|
|
2132
|
+
//#endregion
|
|
2133
|
+
//#region src/init/templates/worker.ts
|
|
2134
|
+
const workerTemplate = {
|
|
2135
|
+
name: "worker",
|
|
2136
|
+
description: "Background job processing",
|
|
2137
|
+
dependencies: {
|
|
2138
|
+
"@geekmidas/constructs": "workspace:*",
|
|
2139
|
+
"@geekmidas/envkit": "workspace:*",
|
|
2140
|
+
"@geekmidas/logger": "workspace:*",
|
|
2141
|
+
"@geekmidas/events": "workspace:*",
|
|
2142
|
+
hono: "~4.8.2",
|
|
2143
|
+
pino: "~9.6.0"
|
|
2144
|
+
},
|
|
2145
|
+
devDependencies: {
|
|
2146
|
+
"@biomejs/biome": "~1.9.4",
|
|
2147
|
+
"@geekmidas/cli": "workspace:*",
|
|
2148
|
+
"@types/node": "~22.0.0",
|
|
2149
|
+
tsx: "~4.20.0",
|
|
2150
|
+
turbo: "~2.3.0",
|
|
2151
|
+
typescript: "~5.8.2",
|
|
2152
|
+
vitest: "~4.0.0"
|
|
2153
|
+
},
|
|
2154
|
+
scripts: {
|
|
2155
|
+
dev: "gkm dev",
|
|
2156
|
+
build: "gkm build",
|
|
2157
|
+
test: "vitest",
|
|
2158
|
+
"test:once": "vitest run",
|
|
2159
|
+
typecheck: "tsc --noEmit",
|
|
2160
|
+
lint: "biome lint .",
|
|
2161
|
+
fmt: "biome format . --write",
|
|
2162
|
+
"fmt:check": "biome format ."
|
|
2163
|
+
},
|
|
2164
|
+
files: (options) => {
|
|
2165
|
+
const { loggerType, routesStructure } = options;
|
|
2166
|
+
const loggerContent = `import { createLogger } from '@geekmidas/logger/${loggerType}';
|
|
2167
|
+
|
|
2168
|
+
export const logger = createLogger();
|
|
2169
|
+
`;
|
|
2170
|
+
const getRoutePath = (file) => {
|
|
2171
|
+
switch (routesStructure) {
|
|
2172
|
+
case "centralized-endpoints": return `src/endpoints/${file}`;
|
|
2173
|
+
case "centralized-routes": return `src/routes/${file}`;
|
|
2174
|
+
case "domain-based": return `src/${file.replace(".ts", "")}/routes/index.ts`;
|
|
2175
|
+
}
|
|
2176
|
+
};
|
|
2177
|
+
const files = [
|
|
2178
|
+
{
|
|
2179
|
+
path: "src/config/env.ts",
|
|
2180
|
+
content: `import { EnvironmentParser } from '@geekmidas/envkit';
|
|
2181
|
+
|
|
2182
|
+
export const envParser = new EnvironmentParser(process.env);
|
|
2183
|
+
|
|
2184
|
+
export const config = envParser
|
|
2185
|
+
.create((get) => ({
|
|
2186
|
+
port: get('PORT').string().transform(Number).default(3000),
|
|
2187
|
+
nodeEnv: get('NODE_ENV').string().default('development'),
|
|
2188
|
+
rabbitmq: {
|
|
2189
|
+
url: get('RABBITMQ_URL').string().default('amqp://localhost:5672'),
|
|
2190
|
+
},${options.database ? `
|
|
2191
|
+
database: {
|
|
2192
|
+
url: get('DATABASE_URL').string().default('postgresql://localhost:5432/mydb'),
|
|
2193
|
+
},` : ""}
|
|
2194
|
+
}))
|
|
2195
|
+
.parse();
|
|
2196
|
+
`
|
|
2197
|
+
},
|
|
2198
|
+
{
|
|
2199
|
+
path: "src/config/logger.ts",
|
|
2200
|
+
content: loggerContent
|
|
2201
|
+
},
|
|
2202
|
+
{
|
|
2203
|
+
path: getRoutePath("health.ts"),
|
|
2204
|
+
content: `import { e } from '@geekmidas/constructs/endpoints';
|
|
2205
|
+
|
|
2206
|
+
export default e
|
|
2207
|
+
.get('/health')
|
|
2208
|
+
.handle(async () => ({
|
|
2209
|
+
status: 'ok',
|
|
2210
|
+
timestamp: new Date().toISOString(),
|
|
2211
|
+
}));
|
|
2212
|
+
`
|
|
2213
|
+
},
|
|
2214
|
+
{
|
|
2215
|
+
path: "src/events/types.ts",
|
|
2216
|
+
content: `import type { PublishableMessage } from '@geekmidas/events';
|
|
2217
|
+
|
|
2218
|
+
// Define your event types here
|
|
2219
|
+
export type AppEvents =
|
|
2220
|
+
| PublishableMessage<'user.created', { userId: string; email: string }>
|
|
2221
|
+
| PublishableMessage<'user.updated', { userId: string; changes: Record<string, unknown> }>
|
|
2222
|
+
| PublishableMessage<'order.placed', { orderId: string; userId: string; total: number }>;
|
|
2223
|
+
`
|
|
2224
|
+
},
|
|
2225
|
+
{
|
|
2226
|
+
path: "src/subscribers/user-events.ts",
|
|
2227
|
+
content: `import { s } from '@geekmidas/constructs/subscribers';
|
|
2228
|
+
import type { AppEvents } from '../events/types.js';
|
|
2229
|
+
|
|
2230
|
+
export default s<AppEvents>()
|
|
2231
|
+
.events(['user.created', 'user.updated'])
|
|
2232
|
+
.handle(async ({ event, logger }) => {
|
|
2233
|
+
logger.info({ type: event.type, payload: event.payload }, 'Processing user event');
|
|
2234
|
+
|
|
2235
|
+
switch (event.type) {
|
|
2236
|
+
case 'user.created':
|
|
2237
|
+
// Handle user creation
|
|
2238
|
+
logger.info({ userId: event.payload.userId }, 'New user created');
|
|
2239
|
+
break;
|
|
2240
|
+
case 'user.updated':
|
|
2241
|
+
// Handle user update
|
|
2242
|
+
logger.info({ userId: event.payload.userId }, 'User updated');
|
|
2243
|
+
break;
|
|
2244
|
+
}
|
|
2245
|
+
});
|
|
2246
|
+
`
|
|
2247
|
+
},
|
|
2248
|
+
{
|
|
2249
|
+
path: "src/crons/cleanup.ts",
|
|
2250
|
+
content: `import { cron } from '@geekmidas/constructs/crons';
|
|
2251
|
+
|
|
2252
|
+
// Run every day at midnight
|
|
2253
|
+
export default cron('0 0 * * *')
|
|
2254
|
+
.handle(async ({ logger }) => {
|
|
2255
|
+
logger.info('Running cleanup job');
|
|
2256
|
+
|
|
2257
|
+
// Add your cleanup logic here
|
|
2258
|
+
// e.g., delete old sessions, clean up temp files, etc.
|
|
2259
|
+
|
|
2260
|
+
logger.info('Cleanup job completed');
|
|
2261
|
+
});
|
|
2262
|
+
`
|
|
2263
|
+
}
|
|
2264
|
+
];
|
|
2265
|
+
if (options.telescope) files.push({
|
|
2266
|
+
path: "src/config/telescope.ts",
|
|
2267
|
+
content: `import { Telescope } from '@geekmidas/telescope';
|
|
2268
|
+
import { InMemoryStorage } from '@geekmidas/telescope/storage/memory';
|
|
2269
|
+
|
|
2270
|
+
export const telescope = new Telescope({
|
|
2271
|
+
storage: new InMemoryStorage({ maxEntries: 100 }),
|
|
2272
|
+
enabled: process.env.NODE_ENV === 'development',
|
|
2273
|
+
});
|
|
2274
|
+
`
|
|
2275
|
+
});
|
|
2276
|
+
return files;
|
|
2277
|
+
}
|
|
2278
|
+
};
|
|
2279
|
+
|
|
2280
|
+
//#endregion
|
|
2281
|
+
//#region src/init/templates/index.ts
|
|
2282
|
+
/**
|
|
2283
|
+
* OpenAPI output path (fixed, not configurable)
|
|
2284
|
+
*/
|
|
2285
|
+
const OPENAPI_OUTPUT_PATH = "./.gkm/openapi.ts";
|
|
2286
|
+
/**
|
|
2287
|
+
* All available templates
|
|
2288
|
+
*/
|
|
2289
|
+
const templates = {
|
|
2290
|
+
minimal: minimalTemplate,
|
|
2291
|
+
api: apiTemplate,
|
|
2292
|
+
serverless: serverlessTemplate,
|
|
2293
|
+
worker: workerTemplate
|
|
2294
|
+
};
|
|
2295
|
+
/**
|
|
2296
|
+
* Template choices for prompts
|
|
2297
|
+
*/
|
|
2298
|
+
const templateChoices = [
|
|
2299
|
+
{
|
|
2300
|
+
title: "Minimal",
|
|
2301
|
+
value: "minimal",
|
|
2302
|
+
description: "Basic health endpoint"
|
|
2303
|
+
},
|
|
2304
|
+
{
|
|
2305
|
+
title: "API",
|
|
2306
|
+
value: "api",
|
|
2307
|
+
description: "Full API with auth, database, services"
|
|
2308
|
+
},
|
|
2309
|
+
{
|
|
2310
|
+
title: "Serverless",
|
|
2311
|
+
value: "serverless",
|
|
2312
|
+
description: "AWS Lambda handlers"
|
|
2313
|
+
},
|
|
2314
|
+
{
|
|
2315
|
+
title: "Worker",
|
|
2316
|
+
value: "worker",
|
|
2317
|
+
description: "Background job processing"
|
|
2318
|
+
}
|
|
2319
|
+
];
|
|
2320
|
+
/**
|
|
2321
|
+
* Logger type choices for prompts
|
|
2322
|
+
*/
|
|
2323
|
+
const loggerTypeChoices = [{
|
|
2324
|
+
title: "Pino",
|
|
2325
|
+
value: "pino",
|
|
2326
|
+
description: "Fast JSON logger for production (recommended)"
|
|
2327
|
+
}, {
|
|
2328
|
+
title: "Console",
|
|
2329
|
+
value: "console",
|
|
2330
|
+
description: "Simple console logger for development"
|
|
2331
|
+
}];
|
|
2332
|
+
/**
|
|
2333
|
+
* Routes structure choices for prompts
|
|
2334
|
+
*/
|
|
2335
|
+
const routesStructureChoices = [
|
|
2336
|
+
{
|
|
2337
|
+
title: "Centralized (endpoints)",
|
|
2338
|
+
value: "centralized-endpoints",
|
|
2339
|
+
description: "src/endpoints/**/*.ts"
|
|
2340
|
+
},
|
|
2341
|
+
{
|
|
2342
|
+
title: "Centralized (routes)",
|
|
2343
|
+
value: "centralized-routes",
|
|
2344
|
+
description: "src/routes/**/*.ts"
|
|
2345
|
+
},
|
|
2346
|
+
{
|
|
2347
|
+
title: "Domain-based",
|
|
2348
|
+
value: "domain-based",
|
|
2349
|
+
description: "src/**/routes/*.ts (e.g., src/users/routes/list.ts)"
|
|
2350
|
+
}
|
|
2351
|
+
];
|
|
2352
|
+
/**
|
|
2353
|
+
* Get a template by name
|
|
2354
|
+
*/
|
|
2355
|
+
function getTemplate(name$1) {
|
|
2356
|
+
const template = templates[name$1];
|
|
2357
|
+
if (!template) throw new Error(`Unknown template: ${name$1}`);
|
|
2358
|
+
return template;
|
|
2359
|
+
}
|
|
2360
|
+
|
|
2361
|
+
//#endregion
|
|
2362
|
+
//#region src/init/generators/package.ts
|
|
2363
|
+
/**
|
|
2364
|
+
* Generate package.json with dependencies based on template and options
|
|
2365
|
+
*/
|
|
2366
|
+
function generatePackageJson(options, template) {
|
|
2367
|
+
const { name: name$1, telescope, database, studio, monorepo } = options;
|
|
2368
|
+
const dependencies$1 = { ...template.dependencies };
|
|
2369
|
+
const devDependencies$1 = { ...template.devDependencies };
|
|
2370
|
+
const scripts$1 = { ...template.scripts };
|
|
2371
|
+
if (telescope) dependencies$1["@geekmidas/telescope"] = "workspace:*";
|
|
2372
|
+
if (studio) dependencies$1["@geekmidas/studio"] = "workspace:*";
|
|
2373
|
+
if (database) {
|
|
2374
|
+
dependencies$1["@geekmidas/db"] = "workspace:*";
|
|
2375
|
+
dependencies$1["kysely"] = "~0.28.2";
|
|
2376
|
+
dependencies$1["pg"] = "~8.16.0";
|
|
2377
|
+
devDependencies$1["@types/pg"] = "~8.15.0";
|
|
2378
|
+
}
|
|
2379
|
+
dependencies$1["zod"] = "~4.1.0";
|
|
2380
|
+
if (monorepo) {
|
|
2381
|
+
delete devDependencies$1["@biomejs/biome"];
|
|
2382
|
+
delete devDependencies$1["turbo"];
|
|
2383
|
+
delete scripts$1["lint"];
|
|
2384
|
+
delete scripts$1["fmt"];
|
|
2385
|
+
delete scripts$1["fmt:check"];
|
|
2386
|
+
dependencies$1[`@${name$1}/models`] = "workspace:*";
|
|
2387
|
+
delete dependencies$1["zod"];
|
|
2388
|
+
}
|
|
2389
|
+
const sortObject = (obj) => Object.fromEntries(Object.entries(obj).sort(([a], [b]) => a.localeCompare(b)));
|
|
2390
|
+
let packageName = name$1;
|
|
2391
|
+
if (monorepo && options.apiPath) {
|
|
2392
|
+
const pathParts = options.apiPath.split("/");
|
|
2393
|
+
const appName = pathParts[pathParts.length - 1] || "api";
|
|
2394
|
+
packageName = `@${name$1}/${appName}`;
|
|
2395
|
+
}
|
|
2396
|
+
const packageJson = {
|
|
2397
|
+
name: packageName,
|
|
2398
|
+
version: "0.0.1",
|
|
2399
|
+
private: true,
|
|
2400
|
+
type: "module",
|
|
2401
|
+
exports: { "./client": {
|
|
2402
|
+
types: OPENAPI_OUTPUT_PATH,
|
|
2403
|
+
import: OPENAPI_OUTPUT_PATH
|
|
2404
|
+
} },
|
|
2405
|
+
scripts: scripts$1,
|
|
2406
|
+
dependencies: sortObject(dependencies$1),
|
|
2407
|
+
devDependencies: sortObject(devDependencies$1)
|
|
2408
|
+
};
|
|
2409
|
+
return [{
|
|
2410
|
+
path: "package.json",
|
|
2411
|
+
content: JSON.stringify(packageJson, null, 2) + "\n"
|
|
2412
|
+
}];
|
|
2413
|
+
}
|
|
2414
|
+
|
|
2415
|
+
//#endregion
|
|
2416
|
+
//#region src/init/generators/source.ts
|
|
2417
|
+
/**
|
|
2418
|
+
* Generate source files from template
|
|
2419
|
+
*/
|
|
2420
|
+
function generateSourceFiles(options, template) {
|
|
2421
|
+
return template.files(options);
|
|
2422
|
+
}
|
|
2423
|
+
|
|
2424
|
+
//#endregion
|
|
2425
|
+
//#region src/init/utils.ts
|
|
2426
|
+
/**
|
|
2427
|
+
* Detect the package manager being used based on lockfiles or npm_config_user_agent
|
|
2428
|
+
*/
|
|
2429
|
+
function detectPackageManager(cwd = process.cwd()) {
|
|
2430
|
+
if (existsSync(join$1(cwd, "pnpm-lock.yaml"))) return "pnpm";
|
|
2431
|
+
if (existsSync(join$1(cwd, "yarn.lock"))) return "yarn";
|
|
2432
|
+
if (existsSync(join$1(cwd, "bun.lockb"))) return "bun";
|
|
2433
|
+
if (existsSync(join$1(cwd, "package-lock.json"))) return "npm";
|
|
2434
|
+
const userAgent = process.env.npm_config_user_agent || "";
|
|
2435
|
+
if (userAgent.includes("pnpm")) return "pnpm";
|
|
2436
|
+
if (userAgent.includes("yarn")) return "yarn";
|
|
2437
|
+
if (userAgent.includes("bun")) return "bun";
|
|
2438
|
+
return "npm";
|
|
2439
|
+
}
|
|
2440
|
+
/**
|
|
2441
|
+
* Validate project name for npm package naming conventions
|
|
2442
|
+
*/
|
|
2443
|
+
function validateProjectName(name$1) {
|
|
2444
|
+
if (!name$1) return "Project name is required";
|
|
2445
|
+
if (!/^[a-z0-9-_@/.]+$/i.test(name$1)) return "Project name can only contain letters, numbers, hyphens, underscores, @, /, and .";
|
|
2446
|
+
const reserved = [
|
|
2447
|
+
"node_modules",
|
|
2448
|
+
".git",
|
|
2449
|
+
"package.json",
|
|
2450
|
+
"src"
|
|
2451
|
+
];
|
|
2452
|
+
if (reserved.includes(name$1.toLowerCase())) return `"${name$1}" is a reserved name`;
|
|
2453
|
+
return true;
|
|
2454
|
+
}
|
|
2455
|
+
/**
|
|
2456
|
+
* Check if a directory already exists at the target path
|
|
2457
|
+
*/
|
|
2458
|
+
function checkDirectoryExists(name$1, cwd = process.cwd()) {
|
|
2459
|
+
const targetPath = join$1(cwd, name$1);
|
|
2460
|
+
if (existsSync(targetPath)) return `Directory "${name$1}" already exists`;
|
|
2461
|
+
return true;
|
|
2462
|
+
}
|
|
2463
|
+
/**
|
|
2464
|
+
* Get the install command for a package manager
|
|
2465
|
+
*/
|
|
2466
|
+
function getInstallCommand(pkgManager) {
|
|
2467
|
+
switch (pkgManager) {
|
|
2468
|
+
case "pnpm": return "pnpm install";
|
|
2469
|
+
case "yarn": return "yarn";
|
|
2470
|
+
case "bun": return "bun install";
|
|
2471
|
+
case "npm":
|
|
2472
|
+
default: return "npm install";
|
|
2473
|
+
}
|
|
2474
|
+
}
|
|
2475
|
+
/**
|
|
2476
|
+
* Get the dev command for a package manager
|
|
2477
|
+
*/
|
|
2478
|
+
function getRunCommand(pkgManager, script) {
|
|
2479
|
+
switch (pkgManager) {
|
|
2480
|
+
case "pnpm": return `pnpm ${script}`;
|
|
2481
|
+
case "yarn": return `yarn ${script}`;
|
|
2482
|
+
case "bun": return `bun run ${script}`;
|
|
2483
|
+
case "npm":
|
|
2484
|
+
default: return `npm run ${script}`;
|
|
2485
|
+
}
|
|
2486
|
+
}
|
|
2487
|
+
|
|
2488
|
+
//#endregion
|
|
2489
|
+
//#region src/init/index.ts
|
|
2490
|
+
/**
|
|
2491
|
+
* Main init command - scaffolds a new project
|
|
2492
|
+
*/
|
|
2493
|
+
async function initCommand(projectName, options = {}) {
|
|
2494
|
+
const cwd = process.cwd();
|
|
2495
|
+
const pkgManager = detectPackageManager(cwd);
|
|
2496
|
+
prompts.override({});
|
|
2497
|
+
const onCancel = () => {
|
|
2498
|
+
process.exit(0);
|
|
2499
|
+
};
|
|
2500
|
+
const answers = await prompts([
|
|
2501
|
+
{
|
|
2502
|
+
type: projectName ? null : "text",
|
|
2503
|
+
name: "name",
|
|
2504
|
+
message: "Project name:",
|
|
2505
|
+
initial: "my-api",
|
|
2506
|
+
validate: (value) => {
|
|
2507
|
+
const nameValid = validateProjectName(value);
|
|
2508
|
+
if (nameValid !== true) return nameValid;
|
|
2509
|
+
const dirValid = checkDirectoryExists(value, cwd);
|
|
2510
|
+
if (dirValid !== true) return dirValid;
|
|
2511
|
+
return true;
|
|
2512
|
+
}
|
|
2513
|
+
},
|
|
2514
|
+
{
|
|
2515
|
+
type: options.template || options.yes ? null : "select",
|
|
2516
|
+
name: "template",
|
|
2517
|
+
message: "Template:",
|
|
2518
|
+
choices: templateChoices,
|
|
2519
|
+
initial: 0
|
|
2520
|
+
},
|
|
2521
|
+
{
|
|
2522
|
+
type: options.yes ? null : "confirm",
|
|
2523
|
+
name: "telescope",
|
|
2524
|
+
message: "Include Telescope (debugging dashboard)?",
|
|
2525
|
+
initial: true
|
|
2526
|
+
},
|
|
2527
|
+
{
|
|
2528
|
+
type: options.yes ? null : "confirm",
|
|
2529
|
+
name: "database",
|
|
2530
|
+
message: "Include database support (Kysely)?",
|
|
2531
|
+
initial: true
|
|
2532
|
+
},
|
|
2533
|
+
{
|
|
2534
|
+
type: (prev) => options.yes ? null : prev ? "confirm" : null,
|
|
2535
|
+
name: "studio",
|
|
2536
|
+
message: "Include Studio (database browser)?",
|
|
2537
|
+
initial: true
|
|
2538
|
+
},
|
|
2539
|
+
{
|
|
2540
|
+
type: options.yes ? null : "select",
|
|
2541
|
+
name: "loggerType",
|
|
2542
|
+
message: "Logger:",
|
|
2543
|
+
choices: loggerTypeChoices,
|
|
2544
|
+
initial: 0
|
|
2545
|
+
},
|
|
2546
|
+
{
|
|
2547
|
+
type: options.yes ? null : "select",
|
|
2548
|
+
name: "routesStructure",
|
|
2549
|
+
message: "Routes structure:",
|
|
2550
|
+
choices: routesStructureChoices,
|
|
2551
|
+
initial: 0
|
|
2552
|
+
},
|
|
2553
|
+
{
|
|
2554
|
+
type: options.yes || options.monorepo !== void 0 ? null : "confirm",
|
|
2555
|
+
name: "monorepo",
|
|
2556
|
+
message: "Setup as monorepo?",
|
|
2557
|
+
initial: false
|
|
2558
|
+
},
|
|
2559
|
+
{
|
|
2560
|
+
type: (prev) => (prev === true || options.monorepo) && !options.apiPath ? "text" : null,
|
|
2561
|
+
name: "apiPath",
|
|
2562
|
+
message: "API app path:",
|
|
2563
|
+
initial: "apps/api"
|
|
2564
|
+
}
|
|
2565
|
+
], { onCancel });
|
|
2566
|
+
const name$1 = projectName || answers.name;
|
|
2567
|
+
if (!name$1) {
|
|
2568
|
+
console.error(" Error: Project name is required\n");
|
|
2569
|
+
process.exit(1);
|
|
2570
|
+
}
|
|
2571
|
+
if (projectName) {
|
|
2572
|
+
const nameValid = validateProjectName(projectName);
|
|
2573
|
+
if (nameValid !== true) {
|
|
2574
|
+
console.error(` Error: ${nameValid}\n`);
|
|
2575
|
+
process.exit(1);
|
|
2576
|
+
}
|
|
2577
|
+
const dirValid = checkDirectoryExists(projectName, cwd);
|
|
2578
|
+
if (dirValid !== true) {
|
|
2579
|
+
console.error(` Error: ${dirValid}\n`);
|
|
2580
|
+
process.exit(1);
|
|
2581
|
+
}
|
|
2582
|
+
}
|
|
2583
|
+
const monorepo = options.monorepo ?? (options.yes ? false : answers.monorepo ?? false);
|
|
2584
|
+
const database = options.yes ? true : answers.database ?? true;
|
|
2585
|
+
const templateOptions = {
|
|
2586
|
+
name: name$1,
|
|
2587
|
+
template: options.template || answers.template || "minimal",
|
|
2588
|
+
telescope: options.yes ? true : answers.telescope ?? true,
|
|
2589
|
+
database,
|
|
2590
|
+
studio: database && (options.yes ? true : answers.studio ?? true),
|
|
2591
|
+
loggerType: options.yes ? "pino" : answers.loggerType ?? "pino",
|
|
2592
|
+
routesStructure: options.yes ? "centralized-endpoints" : answers.routesStructure ?? "centralized-endpoints",
|
|
2593
|
+
monorepo,
|
|
2594
|
+
apiPath: monorepo ? options.apiPath ?? answers.apiPath ?? "apps/api" : ""
|
|
2595
|
+
};
|
|
2596
|
+
const targetDir = join$1(cwd, name$1);
|
|
2597
|
+
const template = getTemplate(templateOptions.template);
|
|
2598
|
+
const isMonorepo = templateOptions.monorepo;
|
|
2599
|
+
const apiPath = templateOptions.apiPath;
|
|
2600
|
+
await mkdir(targetDir, { recursive: true });
|
|
2601
|
+
const appDir = isMonorepo ? join$1(targetDir, apiPath) : targetDir;
|
|
2602
|
+
if (isMonorepo) await mkdir(appDir, { recursive: true });
|
|
2603
|
+
const appFiles = [
|
|
2604
|
+
...generatePackageJson(templateOptions, template),
|
|
2605
|
+
...generateConfigFiles(templateOptions, template),
|
|
2606
|
+
...generateEnvFiles(templateOptions, template),
|
|
2607
|
+
...generateSourceFiles(templateOptions, template),
|
|
2608
|
+
...generateDockerFiles(templateOptions, template)
|
|
2609
|
+
];
|
|
2610
|
+
const rootFiles = [...generateMonorepoFiles(templateOptions, template), ...generateModelsPackage(templateOptions)];
|
|
2611
|
+
for (const { path, content } of rootFiles) {
|
|
2612
|
+
const fullPath = join$1(targetDir, path);
|
|
2613
|
+
await mkdir(dirname(fullPath), { recursive: true });
|
|
2614
|
+
await writeFile(fullPath, content);
|
|
2615
|
+
}
|
|
2616
|
+
for (const { path, content } of appFiles) {
|
|
2617
|
+
const fullPath = join$1(appDir, path);
|
|
2618
|
+
const displayPath = isMonorepo ? `${apiPath}/${path}` : path;
|
|
2619
|
+
await mkdir(dirname(fullPath), { recursive: true });
|
|
2620
|
+
await writeFile(fullPath, content);
|
|
2621
|
+
}
|
|
2622
|
+
if (!options.skipInstall) {
|
|
2623
|
+
try {
|
|
2624
|
+
execSync(getInstallCommand(pkgManager), {
|
|
2625
|
+
cwd: targetDir,
|
|
2626
|
+
stdio: "inherit"
|
|
2627
|
+
});
|
|
2628
|
+
} catch {
|
|
2629
|
+
console.error("\n Warning: Failed to install dependencies.");
|
|
2630
|
+
}
|
|
2631
|
+
try {
|
|
2632
|
+
execSync("npx @biomejs/biome format --write --unsafe .", {
|
|
2633
|
+
cwd: targetDir,
|
|
2634
|
+
stdio: "inherit"
|
|
2635
|
+
});
|
|
2636
|
+
} catch {}
|
|
2637
|
+
}
|
|
2638
|
+
const devCommand$1 = getRunCommand(pkgManager, "dev");
|
|
2639
|
+
}
|
|
2640
|
+
|
|
114
2641
|
//#endregion
|
|
115
2642
|
//#region src/index.ts
|
|
116
2643
|
const program = new Command();
|