@aws/nx-plugin 1.0.0-rc.32 → 1.0.0-rc.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (277) hide show
  1. package/LICENSE-THIRD-PARTY +75 -86
  2. package/generators.json +27 -0
  3. package/package.json +10 -10
  4. package/src/connection/generator.js +12 -1
  5. package/src/connection/generator.js.map +1 -1
  6. package/src/connection/supported-connections.d.ts +10 -1
  7. package/src/connection/supported-connections.js +13 -0
  8. package/src/connection/supported-connections.js.map +1 -1
  9. package/src/infra/app/__snapshots__/generator.spec.ts.snap +21 -21
  10. package/src/infra/app/files/app/src/main.ts.template +1 -1
  11. package/src/infra/app/files/app/src/stages/application-stage.ts.template +1 -1
  12. package/src/infra/app/generator.js +3 -1
  13. package/src/infra/app/generator.js.map +1 -1
  14. package/src/open-api/ts-client/__snapshots__/generator.complex-types.spec.ts.snap +12 -12
  15. package/src/open-api/ts-client/__snapshots__/generator.composite-types.spec.ts.snap +74 -10
  16. package/src/open-api/ts-client/__snapshots__/generator.content-type.spec.ts.snap +22 -4
  17. package/src/open-api/ts-client/__snapshots__/generator.duplicate-types.spec.ts.snap +53 -8
  18. package/src/open-api/ts-client/__snapshots__/generator.edge-cases.spec.ts.snap +32 -4
  19. package/src/open-api/ts-client/__snapshots__/generator.fast-api-gaps.spec.ts.snap +736 -0
  20. package/src/open-api/ts-client/__snapshots__/generator.fast-api.spec.ts.snap +86 -11
  21. package/src/open-api/ts-client/__snapshots__/generator.multipart.spec.ts.snap +21 -3
  22. package/src/open-api/ts-client/__snapshots__/generator.primitive-types.spec.ts.snap +2 -2
  23. package/src/open-api/ts-client/__snapshots__/generator.request.spec.ts.snap +6 -6
  24. package/src/open-api/ts-client/__snapshots__/generator.reserved-keywords.spec.ts.snap +2 -2
  25. package/src/open-api/ts-client/__snapshots__/generator.spec-compliance.spec.ts.snap +1883 -0
  26. package/src/open-api/ts-client/__snapshots__/generator.tags.spec.ts.snap +4 -4
  27. package/src/open-api/ts-client/files/client.gen.ts.template +196 -13
  28. package/src/open-api/ts-client/files/types.gen.ts.template +2 -0
  29. package/src/open-api/ts-client/generator.js +27 -2
  30. package/src/open-api/ts-client/generator.js.map +1 -1
  31. package/src/open-api/ts-hooks/files/options-proxy.gen.ts.template +2 -2
  32. package/src/open-api/ts-hooks/generator.js +5 -1
  33. package/src/open-api/ts-hooks/generator.js.map +1 -1
  34. package/src/open-api/utils/codegen-data/languages.js +6 -0
  35. package/src/open-api/utils/codegen-data/languages.js.map +1 -1
  36. package/src/open-api/utils/codegen-data/types.d.ts +16 -1
  37. package/src/open-api/utils/codegen-data/types.js.map +1 -1
  38. package/src/open-api/utils/codegen-data.js +71 -0
  39. package/src/open-api/utils/codegen-data.js.map +1 -1
  40. package/src/open-api/utils/normalise.js +53 -8
  41. package/src/open-api/utils/normalise.js.map +1 -1
  42. package/src/open-api/utils/parser.js +48 -15
  43. package/src/open-api/utils/parser.js.map +1 -1
  44. package/src/preset/__snapshots__/generator.spec.ts.snap +5 -3
  45. package/src/preset/generator.d.ts +1 -1
  46. package/src/preset/generator.js +5 -2
  47. package/src/preset/generator.js.map +1 -1
  48. package/src/preset/schema.d.js.map +1 -1
  49. package/src/preset/schema.d.ts +2 -0
  50. package/src/preset/schema.json +6 -0
  51. package/src/py/agent/__snapshots__/generator.constructs.spec.ts.snap +7 -7
  52. package/src/py/agent/__snapshots__/generator.frameworks.spec.ts.snap +8 -8
  53. package/src/py/agent/__snapshots__/generator.protocols.spec.ts.snap +89 -3
  54. package/src/py/dynamodb/__snapshots__/generator.spec.ts.snap +2 -2
  55. package/src/py/fast-api/__snapshots__/generator.terraform.spec.ts.snap +12 -12
  56. package/src/py/lambda-function/__snapshots__/generator.spec.ts.snap +2 -2
  57. package/src/py/mcp-server/__snapshots__/generator.spec.ts.snap +91 -5
  58. package/src/py/rdb/__snapshots__/generator.spec.ts.snap +2038 -0
  59. package/src/py/rdb/agent-connection/__snapshots__/generator.spec.ts.snap +104 -0
  60. package/src/py/rdb/agent-connection/generator.d.ts +10 -0
  61. package/src/py/rdb/agent-connection/generator.js +46 -0
  62. package/src/py/rdb/agent-connection/generator.js.map +1 -0
  63. package/src/py/rdb/agent-connection/schema.d.js +8 -0
  64. package/src/py/rdb/agent-connection/schema.d.js.map +1 -0
  65. package/src/py/rdb/agent-connection/schema.d.ts +15 -0
  66. package/src/py/rdb/agent-connection/schema.json +27 -0
  67. package/src/py/rdb/fast-api-connection/__snapshots__/generator.spec.ts.snap +44 -0
  68. package/src/py/rdb/fast-api-connection/files/__apiModuleName__/dependencies/__rdbNameSnake__.py.template +14 -0
  69. package/src/py/rdb/fast-api-connection/generator.d.ts +10 -0
  70. package/src/py/rdb/fast-api-connection/generator.js +54 -0
  71. package/src/py/rdb/fast-api-connection/generator.js.map +1 -0
  72. package/src/py/rdb/fast-api-connection/schema.d.js +8 -0
  73. package/src/py/rdb/fast-api-connection/schema.d.js.map +1 -0
  74. package/src/py/rdb/fast-api-connection/schema.d.ts +13 -0
  75. package/src/py/rdb/fast-api-connection/schema.json +23 -0
  76. package/src/py/rdb/files/Dockerfile.create-db-user.template +10 -0
  77. package/src/py/rdb/files/Dockerfile.migration.template +10 -0
  78. package/src/py/rdb/files/__name__/__init__.py.template +3 -0
  79. package/src/py/rdb/files/__name__/connection.py.template +55 -0
  80. package/src/py/rdb/files/__name__/create_db_user_handler.py.template +97 -0
  81. package/src/py/rdb/files/__name__/migration_handler.py.template +36 -0
  82. package/src/py/rdb/files/__name__/models/__init__.py.template +3 -0
  83. package/src/py/rdb/files/__name__/models/example.py.template +8 -0
  84. package/src/py/rdb/files/__name__/utils.py.template +104 -0
  85. package/src/py/rdb/files/alembic.ini.template +38 -0
  86. package/src/py/rdb/files/config.json.template +14 -0
  87. package/src/py/rdb/files/migrations/env.py.template +80 -0
  88. package/src/py/rdb/files/migrations/script.py.mako.template +28 -0
  89. package/src/py/rdb/generator.d.ts +6 -0
  90. package/src/py/rdb/generator.js +263 -0
  91. package/src/py/rdb/generator.js.map +1 -0
  92. package/src/py/rdb/mcp-server-connection/__snapshots__/generator.spec.ts.snap +101 -0
  93. package/src/py/rdb/mcp-server-connection/generator.d.ts +10 -0
  94. package/src/py/rdb/mcp-server-connection/generator.js +46 -0
  95. package/src/py/rdb/mcp-server-connection/generator.js.map +1 -0
  96. package/src/py/rdb/mcp-server-connection/schema.d.js +8 -0
  97. package/src/py/rdb/mcp-server-connection/schema.d.js.map +1 -0
  98. package/src/py/rdb/mcp-server-connection/schema.d.ts +15 -0
  99. package/src/py/rdb/mcp-server-connection/schema.json +27 -0
  100. package/src/py/rdb/schema.d.js +6 -0
  101. package/src/py/rdb/schema.d.js.map +1 -0
  102. package/src/py/rdb/schema.d.ts +16 -0
  103. package/src/py/rdb/schema.json +77 -0
  104. package/src/py/rdb/utils.d.ts +6 -0
  105. package/src/py/rdb/utils.js +16 -0
  106. package/src/py/rdb/utils.js.map +1 -0
  107. package/src/sdk/py.d.ts +2 -0
  108. package/src/sdk/py.js +1 -0
  109. package/src/sdk/py.js.map +1 -1
  110. package/src/smithy/ts/api/__snapshots__/generator.spec.ts.snap +7 -7
  111. package/src/smithy/ts/api/files/handler.ts.template +2 -2
  112. package/src/smithy/ts/api/files/local-server.ts.template +2 -2
  113. package/src/smithy/ts/api/files/operations/echo.ts.template +2 -2
  114. package/src/smithy/ts/api/files/service.ts.template +3 -3
  115. package/src/smithy/ts/api/generator.js +3 -1
  116. package/src/smithy/ts/api/generator.js.map +1 -1
  117. package/src/trpc/backend/__snapshots__/generator.spec.ts.snap +12 -12
  118. package/src/trpc/backend/files/src/client/index.ts.template +1 -1
  119. package/src/trpc/backend/files/src/handler.ts.template +1 -1
  120. package/src/trpc/backend/files/src/index.ts.template +5 -5
  121. package/src/trpc/backend/files/src/init.ts.template +1 -1
  122. package/src/trpc/backend/files/src/local-server.ts.template +1 -1
  123. package/src/trpc/backend/files/src/middleware/index.ts.template +7 -7
  124. package/src/trpc/backend/files/src/procedures/echo.ts.template +2 -2
  125. package/src/trpc/backend/files/src/router.ts.template +2 -2
  126. package/src/trpc/backend/files/src/schema/index.ts.template +1 -1
  127. package/src/trpc/backend/generator.js +3 -1
  128. package/src/trpc/backend/generator.js.map +1 -1
  129. package/src/ts/agent/__snapshots__/generator.spec.ts.snap +89 -3
  130. package/src/ts/agent/a2a-connection/files/agent-connection/app/__targetAgentKebabCase__-client-strands.ts.template +2 -2
  131. package/src/ts/agent/a2a-connection/generator.js +3 -1
  132. package/src/ts/agent/a2a-connection/generator.js.map +1 -1
  133. package/src/ts/agent/files/a2a/index.ts.template +1 -1
  134. package/src/ts/agent/files/ag-ui/index.ts.template +1 -1
  135. package/src/ts/agent/files/http/client.ts.template +2 -2
  136. package/src/ts/agent/files/http/index.ts.template +2 -2
  137. package/src/ts/agent/files/http/router.ts.template +3 -3
  138. package/src/ts/agent/gateway-connection/files/agent-connection/app/__gatewayKebabCase__-client-strands.ts.template +2 -2
  139. package/src/ts/agent/gateway-connection/generator.js +3 -1
  140. package/src/ts/agent/gateway-connection/generator.js.map +1 -1
  141. package/src/ts/agent/generator.js +5 -2
  142. package/src/ts/agent/generator.js.map +1 -1
  143. package/src/ts/agent/mcp-connection/files/agent-connection/app/__mcpServerKebabCase__-client-strands.ts.template +2 -2
  144. package/src/ts/agent/mcp-connection/generator.js +3 -1
  145. package/src/ts/agent/mcp-connection/generator.js.map +1 -1
  146. package/src/ts/astro-docs/files/translation/scripts/translate.ts.template +3 -2
  147. package/src/ts/astro-docs/generator.js +2 -0
  148. package/src/ts/astro-docs/generator.js.map +1 -1
  149. package/src/ts/dynamodb/__snapshots__/generator.spec.ts.snap +2 -2
  150. package/src/ts/dynamodb/files/src/client.ts.template +5 -2
  151. package/src/ts/dynamodb/files/src/entities/example.ts.template +1 -1
  152. package/src/ts/dynamodb/files/src/entities/index.ts.template +1 -1
  153. package/src/ts/dynamodb/files/src/index.ts.template +2 -2
  154. package/src/ts/dynamodb/generator.js +3 -1
  155. package/src/ts/dynamodb/generator.js.map +1 -1
  156. package/src/ts/lambda-function/__snapshots__/generator.spec.ts.snap +2 -2
  157. package/src/ts/lib/generator.js +7 -1
  158. package/src/ts/lib/generator.js.map +1 -1
  159. package/src/ts/lib/ts-project-utils.js +19 -4
  160. package/src/ts/lib/ts-project-utils.js.map +1 -1
  161. package/src/ts/lib/types.d.ts +6 -0
  162. package/src/ts/lib/types.js.map +1 -1
  163. package/src/ts/mcp-server/__snapshots__/generator.spec.ts.snap +94 -8
  164. package/src/ts/mcp-server/generator.js +3 -2
  165. package/src/ts/mcp-server/generator.js.map +1 -1
  166. package/src/ts/nx-generator/files/local/generator.ts.template +2 -2
  167. package/src/ts/nx-generator/files/nx-plugin-for-aws/generator/generator.ts.template +2 -2
  168. package/src/ts/nx-generator/generator.js +5 -2
  169. package/src/ts/nx-generator/generator.js.map +1 -1
  170. package/src/ts/nx-plugin/files/mcp-server/server.ts.template +5 -5
  171. package/src/ts/nx-plugin/files/mcp-server/tools/create-workspace-command.ts.template +2 -2
  172. package/src/ts/nx-plugin/files/mcp-server/tools/general-guidance.ts.template +1 -1
  173. package/src/ts/nx-plugin/files/mcp-server/tools/generator-guide.ts.template +2 -2
  174. package/src/ts/nx-plugin/files/mcp-server/tools/list-generators.ts.template +2 -2
  175. package/src/ts/nx-plugin/files/mcp-server/utils.ts.template +3 -3
  176. package/src/ts/nx-plugin/generator.js +3 -1
  177. package/src/ts/nx-plugin/generator.js.map +1 -1
  178. package/src/ts/nx-plugin/utils.js +7 -4
  179. package/src/ts/nx-plugin/utils.js.map +1 -1
  180. package/src/ts/rdb/__snapshots__/generator.spec.ts.snap +149 -177
  181. package/src/ts/rdb/files/src/create-db-user-handler.ts.template +2 -2
  182. package/src/ts/rdb/files/src/index.ts.template +1 -1
  183. package/src/ts/rdb/files/src/migration-handler.ts.template +1 -1
  184. package/src/ts/rdb/files/src/prisma.ts.template +7 -4
  185. package/src/ts/rdb/generator.js +7 -4
  186. package/src/ts/rdb/generator.js.map +1 -1
  187. package/src/ts/rdb/schema.json +1 -1
  188. package/src/ts/react-website/app/__snapshots__/generator.spec.ts.snap +45 -45
  189. package/src/ts/react-website/cognito-auth/__snapshots__/generator.terraform.spec.ts.snap +2 -2
  190. package/src/utils/agent-chat/agent-chat.js +3 -1
  191. package/src/utils/agent-chat/agent-chat.js.map +1 -1
  192. package/src/utils/agent-chat/files/a2a/chat.ts.template +1 -1
  193. package/src/utils/agent-chat/files/ag-ui/chat.ts.template +1 -1
  194. package/src/utils/agent-chat/files/http-py/chat.ts.template +2 -2
  195. package/src/utils/agent-chat/files/http-ts/chat.ts.template +1 -1
  196. package/src/utils/agent-connection/agent-connection.js +4 -1
  197. package/src/utils/agent-connection/agent-connection.js.map +1 -1
  198. package/src/utils/agent-connection/files/core-a2a/agentcore-a2a-client-config.ts.template +2 -2
  199. package/src/utils/agent-connection/files/core-auth/agentcore-fetch.ts.template +1 -1
  200. package/src/utils/agent-connection/files/core-gateway/agentcore-gateway-mcp-transport.ts.template +2 -2
  201. package/src/utils/agent-connection/files/core-mcp/agentcore-mcp-transport.ts.template +2 -2
  202. package/src/utils/agent-connection/files/core-shared/agentcore-transport.ts.template +1 -1
  203. package/src/utils/agent-connection/files/core-strands/a2a/agentcore-a2a-client-strands.ts.template +1 -1
  204. package/src/utils/agent-connection/files/core-strands/base/with-session-id-strands.ts.template +1 -1
  205. package/src/utils/agent-connection/files/core-strands/gateway/agentcore-gateway-mcp-client-strands.ts.template +1 -1
  206. package/src/utils/agent-connection/files/core-strands/mcp/agentcore-mcp-client-strands.ts.template +1 -1
  207. package/src/utils/agent-core-constructs/agent-core-constructs.js +10 -3
  208. package/src/utils/agent-core-constructs/agent-core-constructs.js.map +1 -1
  209. package/src/utils/agent-core-constructs/files/cdk/app/agent-core/__nameKebabCase__/__nameKebabCase__.ts.template +3 -3
  210. package/src/utils/agent-core-constructs/files/cdk/app/agentcore-gateway/__nameKebabCase__/__nameKebabCase__.ts.template +4 -4
  211. package/src/utils/agent-core-constructs/files/cdk/core/agentcore-gateway/agentcore-gateway.ts.template +1 -1
  212. package/src/utils/agent-core-constructs/files/terraform/app/agent-core/__nameKebabCase__/__nameKebabCase__.tf.template +27 -0
  213. package/src/utils/agent-core-constructs/files/terraform/core/agent-core/runtime.tf.template +60 -1
  214. package/src/utils/api-constructs/api-constructs.js +8 -2
  215. package/src/utils/api-constructs/api-constructs.js.map +1 -1
  216. package/src/utils/api-constructs/files/cdk/app/apis/http/__apiNameKebabCase__.ts.template +8 -8
  217. package/src/utils/api-constructs/files/cdk/app/apis/rest/__apiNameKebabCase__.ts.template +8 -8
  218. package/src/utils/api-constructs/files/cdk/core/api/http/http-api.ts.template +3 -3
  219. package/src/utils/api-constructs/files/cdk/core/api/rest/api-gateway-account/index.js.template +32 -20
  220. package/src/utils/api-constructs/files/cdk/core/api/rest/api-gateway-account.ts.template +1 -1
  221. package/src/utils/api-constructs/files/cdk/core/api/rest/rest-api.ts.template +4 -4
  222. package/src/utils/api-constructs/files/cdk/core/api/trpc/trpc-utils.ts.template +1 -1
  223. package/src/utils/ast.js +16 -0
  224. package/src/utils/ast.js.map +1 -1
  225. package/src/utils/commands.d.ts +1 -1
  226. package/src/utils/commands.js +4 -1
  227. package/src/utils/commands.js.map +1 -1
  228. package/src/utils/dynamodb-constructs/dynamodb-constructs.js +9 -2
  229. package/src/utils/dynamodb-constructs/dynamodb-constructs.js.map +1 -1
  230. package/src/utils/dynamodb-constructs/files/cdk/app/dynamodb/__nameKebabCase__.ts.template +3 -3
  231. package/src/utils/dynamodb-constructs/files/cdk/core/dynamodb.ts.template +1 -1
  232. package/src/utils/files/common/constructs/src/core/index.ts.template +4 -4
  233. package/src/utils/files/common/constructs/src/index.ts.template +2 -2
  234. package/src/utils/files/common/infra-config/src/index.ts.template +3 -3
  235. package/src/utils/files/common/infra-config/src/resolve-stage.ts.template +2 -2
  236. package/src/utils/files/common/infra-config/src/stages.config.ts.template +1 -1
  237. package/src/utils/files/common/scripts/src/infra/infra-deploy.ts.template +1 -1
  238. package/src/utils/files/common/scripts/src/infra/infra-destroy.ts.template +1 -1
  239. package/src/utils/files/common/scripts/src/infra/stage-credentials/run.ts.template +3 -3
  240. package/src/utils/files/common/shadcn/src/index.ts.template +2 -2
  241. package/src/utils/function-constructs/files/cdk/app/lambda-functions/__nameKebabCase__.ts.template +1 -1
  242. package/src/utils/function-constructs/function-constructs.js +3 -1
  243. package/src/utils/function-constructs/function-constructs.js.map +1 -1
  244. package/src/utils/identity-constructs/files/cdk/core/user-identity.ts.template +2 -2
  245. package/src/utils/identity-constructs/identity-constructs.js +5 -1
  246. package/src/utils/identity-constructs/identity-constructs.js.map +1 -1
  247. package/src/utils/module-format.d.ts +28 -0
  248. package/src/utils/module-format.js +28 -0
  249. package/src/utils/module-format.js.map +1 -0
  250. package/src/utils/rdb-constructs/files/cdk/app/dbs/__nameKebabCase__.ts.template +61 -17
  251. package/src/utils/rdb-constructs/files/cdk/core/rdb/aurora.ts.template +68 -78
  252. package/src/utils/rdb-constructs/files/terraform/app/dbs/__nameKebabCase__/__nameKebabCase__.tf.template +88 -8
  253. package/src/utils/rdb-constructs/files/terraform/core/rdb/aurora/aurora.tf.template +5 -32
  254. package/src/utils/rdb-constructs/rdb-constructs.d.ts +11 -1
  255. package/src/utils/rdb-constructs/rdb-constructs.js +9 -2
  256. package/src/utils/rdb-constructs/rdb-constructs.js.map +1 -1
  257. package/src/utils/shared-constructs.js +12 -22
  258. package/src/utils/shared-constructs.js.map +1 -1
  259. package/src/utils/shared-infra-config.js +3 -1
  260. package/src/utils/shared-infra-config.js.map +1 -1
  261. package/src/utils/shared-infra-scripts.js +3 -1
  262. package/src/utils/shared-infra-scripts.js.map +1 -1
  263. package/src/utils/shared-rdb-scripts.js +5 -1
  264. package/src/utils/shared-rdb-scripts.js.map +1 -1
  265. package/src/utils/shared-shadcn.js +3 -1
  266. package/src/utils/shared-shadcn.js.map +1 -1
  267. package/src/utils/test.d.ts +2 -0
  268. package/src/utils/test.js +7 -1
  269. package/src/utils/test.js.map +1 -1
  270. package/src/utils/versions.d.ts +73 -69
  271. package/src/utils/versions.js +71 -67
  272. package/src/utils/versions.js.map +1 -1
  273. package/src/utils/website-constructs/files/cdk/app/static-websites/__websiteNameKebabCase__.ts.template +2 -2
  274. package/src/utils/website-constructs/files/cdk/core/static-website.ts.template +2 -2
  275. package/src/utils/website-constructs/website-constructs.js +9 -2
  276. package/src/utils/website-constructs/website-constructs.js.map +1 -1
  277. package/src/utils/files/terraform/scripts/reset-runtime-config.ts.template +0 -25
@@ -4,6 +4,7 @@
4
4
  */ import { joinPathFragments, updateJson } from "@nx/devkit";
5
5
  import { join, relative } from "path";
6
6
  import { addLicenseCheckToLintTarget } from "../../license/config.js";
7
+ import { isEsmWorkspace } from "../../utils/module-format.js";
7
8
  import { toScopeAlias } from "../../utils/npm-scope.js";
8
9
  import { configureBiomeLint } from "./biome.js";
9
10
  import { configureVitest } from "./vitest.js";
@@ -27,7 +28,11 @@ import { configureVitest } from "./vitest.js";
27
28
  /**
28
29
  * Updates typescript projects
29
30
  */ export const configureTsProject = async (tree, options)=>{
30
- // Remove conflicting commonjs module from tsconfig
31
+ // When the caller doesn't specify a module format, infer it from the
32
+ // workspace root package.json (defaulting to ESM for a fresh workspace).
33
+ const esm = options.esm ?? isEsmWorkspace(tree);
34
+ // Remove a conflicting `module: commonjs` from the project tsconfig.json
35
+ // (CommonJS is configured on tsconfig.lib.json below when needed).
31
36
  updateJson(tree, join(options.dir, 'tsconfig.json'), (tsConfig)=>({
32
37
  ...tsConfig,
33
38
  compilerOptions: {
@@ -46,7 +51,15 @@ import { configureVitest } from "./vitest.js";
46
51
  baseUrl: undefined,
47
52
  rootDir: '.',
48
53
  outDir: distDir,
49
- tsBuildInfoFile: join(distDir, 'tsconfig.lib.tsbuildinfo')
54
+ tsBuildInfoFile: join(distDir, 'tsconfig.lib.tsbuildinfo'),
55
+ // @nx/js configures the lib for ESM (module `nodenext`). CommonJS
56
+ // projects use `node16`, which honours the workspace's
57
+ // `type: commonjs`, emits CommonJS and resolves extensionless relative
58
+ // imports. (Plain `commonjs`/`node` is deprecated in TypeScript 6.)
59
+ ...esm ? {} : {
60
+ module: 'node16',
61
+ moduleResolution: 'node16'
62
+ }
50
63
  }
51
64
  }));
52
65
  }
@@ -79,10 +92,12 @@ import { configureVitest } from "./vitest.js";
79
92
  ])
80
93
  }));
81
94
  }
82
- // Update the root package.json
95
+ // Update the root package.json. ESM projects require `type: module`; for
96
+ // CommonJS we write an explicit `type: commonjs` marker (which Node treats
97
+ // identically to an absent `type`).
83
98
  updateJson(tree, 'package.json', (packageJson)=>({
84
99
  ...packageJson,
85
- type: 'module'
100
+ type: esm ? 'module' : 'commonjs'
86
101
  }));
87
102
  // Remove package.json if it exists
88
103
  if (tree.exists(join(options.dir, 'package.json'))) {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/lib/ts-project-utils.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { joinPathFragments, type Tree, updateJson } from '@nx/devkit';\nimport { join, relative } from 'path';\nimport { addLicenseCheckToLintTarget } from '../../license/config';\nimport { toScopeAlias } from '../../utils/npm-scope';\nimport { configureBiomeLint } from './biome';\nimport type { ConfigureProjectOptions } from './types';\nimport { configureVitest } from './vitest';\n\ninterface TsConfigReference {\n path: string;\n}\n\n/**\n * Merges new TypeScript project references into existing ones, deduplicating by\n * path and preserving the order of existing references so re-running a\n * generator neither duplicates nor reorders references.\n */\nexport const mergeTsReferences = (\n existing: TsConfigReference[] | undefined,\n toAdd: TsConfigReference[],\n): TsConfigReference[] => {\n const references = [...(existing ?? [])];\n const existingPaths = new Set(references.map((ref) => ref.path));\n for (const ref of toAdd) {\n if (!existingPaths.has(ref.path)) {\n references.push(ref);\n existingPaths.add(ref.path);\n }\n }\n return references;\n};\n\n/**\n * Updates typescript projects\n */\nexport const configureTsProject = async (\n tree: Tree,\n options: ConfigureProjectOptions,\n) => {\n // Remove conflicting commonjs module from tsconfig\n updateJson(tree, join(options.dir, 'tsconfig.json'), (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n module:\n tsConfig.compilerOptions?.module === 'commonjs'\n ? undefined\n : tsConfig.compilerOptions?.module,\n },\n }));\n const outDirToRootRelativePath = relative(\n join(tree.root, options.dir),\n tree.root,\n );\n const distDir = join(outDirToRootRelativePath, 'dist', options.dir, 'tsc');\n // Remove baseUrl and rootDir from the tsconfig.lib.json\n if (tree.exists(join(options.dir, 'tsconfig.lib.json'))) {\n updateJson(tree, join(options.dir, 'tsconfig.lib.json'), (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n baseUrl: undefined,\n rootDir: '.',\n outDir: distDir,\n tsBuildInfoFile: join(distDir, 'tsconfig.lib.tsbuildinfo'),\n },\n }));\n }\n // Update root project tsconfig\n updateJson(tree, 'tsconfig.base.json', (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n // baseUrl is deprecated in TypeScript 6 — use ./ prefix in paths instead\n baseUrl: undefined,\n rootDir: '.',\n paths: {\n // Remove any path aliases for this project with the npm scope prefix (eg remove @foo/bar)\n ...Object.fromEntries(\n Object.entries(tsConfig.compilerOptions?.paths ?? {}).filter(\n ([k]) => k !== options.fullyQualifiedName,\n ),\n ),\n // Add aliases which begin with colon (eg :foo/bar) to avoid sniping attacks\n [toScopeAlias(options.fullyQualifiedName)]: [\n `./${joinPathFragments(options.dir, 'src', 'index.ts')}`,\n ],\n },\n },\n }));\n if (tree.exists('tsconfig.json')) {\n updateJson(tree, 'tsconfig.json', (tsConfig) => ({\n ...tsConfig,\n // Add project references, deduplicating and preserving existing order\n references: mergeTsReferences(tsConfig.references, [\n { path: `./${options.dir}` },\n ]),\n }));\n }\n // Update the root package.json\n updateJson(tree, 'package.json', (packageJson) => ({\n ...packageJson,\n type: 'module',\n }));\n // Remove package.json if it exists\n if (tree.exists(join(options.dir, 'package.json'))) {\n tree.delete(join(options.dir, 'package.json'));\n }\n\n await configureBiomeLint(tree, options);\n await configureVitest(tree, options);\n\n // If license checking is configured, make this project's lint target depend\n // on the root license-check target. No-op if there's no license-check target\n // (i.e. the license generator hasn't run); the license generator wires up\n // existing projects itself, so this works regardless of generator order.\n addLicenseCheckToLintTarget(tree, options.fullyQualifiedName);\n};\n"],"names":["joinPathFragments","updateJson","join","relative","addLicenseCheckToLintTarget","toScopeAlias","configureBiomeLint","configureVitest","mergeTsReferences","existing","toAdd","references","existingPaths","Set","map","ref","path","has","push","add","configureTsProject","tree","options","dir","tsConfig","compilerOptions","module","undefined","outDirToRootRelativePath","root","distDir","exists","baseUrl","rootDir","outDir","tsBuildInfoFile","paths","Object","fromEntries","entries","filter","k","fullyQualifiedName","packageJson","type","delete"],"mappings":"AAAA;;;CAGC,GACD,SAASA,iBAAiB,EAAaC,UAAU,QAAQ,aAAa;AACtE,SAASC,IAAI,EAAEC,QAAQ,QAAQ,OAAO;AACtC,SAASC,2BAA2B,QAAQ,0BAAuB;AACnE,SAASC,YAAY,QAAQ,2BAAwB;AACrD,SAASC,kBAAkB,QAAQ,aAAU;AAE7C,SAASC,eAAe,QAAQ,cAAW;AAM3C;;;;CAIC,GACD,OAAO,MAAMC,oBAAoB,CAC/BC,UACAC;IAEA,MAAMC,aAAa;WAAKF,YAAY,EAAE;KAAE;IACxC,MAAMG,gBAAgB,IAAIC,IAAIF,WAAWG,GAAG,CAAC,CAACC,MAAQA,IAAIC,IAAI;IAC9D,KAAK,MAAMD,OAAOL,MAAO;QACvB,IAAI,CAACE,cAAcK,GAAG,CAACF,IAAIC,IAAI,GAAG;YAChCL,WAAWO,IAAI,CAACH;YAChBH,cAAcO,GAAG,CAACJ,IAAIC,IAAI;QAC5B;IACF;IACA,OAAOL;AACT,EAAE;AAEF;;CAEC,GACD,OAAO,MAAMS,qBAAqB,OAChCC,MACAC;IAEA,mDAAmD;IACnDrB,WAA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A;IACA,IAAIF,KAAKU,MAAM,CAAC,kBAAkB;QAChC9B,WAAWoB,MAAM,iBAAiB,CAACG,WAAc,CAAA;gBAC/C,GAAGA,QAAQ;gBACX,sEAAsE;gBACtEb,YAAYH,kBAAkBgB,SAASb,UAAU,EAAE;oBACjD;wBAAEK,MAAM,CAAC,EAAE,EAAEM,QAAQC,GAAG,EAAE;oBAAC;iBAC5B;YACH,CAAA;IACF;IACA,+BAA+B;IAC/BtB,WAAWoB,MAAM,gBAAgB,CAACsB,cAAiB,CAAA;YACjD,GAAGA,WAAW;YACdC,MAAM;QACR,CAAA;IACA,mCAAmC;IACnC,IAAIvB,KAAKU,MAAM,CAAC7B,KAAKoB,QAAQC,GAAG,EAAE,kBAAkB;QAClDF,KAAKwB,MAAM,CAAC3C,KAAKoB,QAAQC,GAAG,EAAE;IAChC;IAEA,MAAMjB,mBAAmBe,MAAMC;IAC/B,MAAMf,gBAAgBc,MAAMC;IAE5B,4EAA4E;IAC5E,6EAA6E;IAC7E,0EAA0E;IAC1E,yEAAyE;IACzElB,4BAA4BiB,MAAMC,QAAQoB,kBAAkB;AAC9D,EAAE"}
1
+ {"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/lib/ts-project-utils.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { joinPathFragments, type Tree, updateJson } from '@nx/devkit';\nimport { join, relative } from 'path';\nimport { addLicenseCheckToLintTarget } from '../../license/config';\nimport { isEsmWorkspace } from '../../utils/module-format';\nimport { toScopeAlias } from '../../utils/npm-scope';\nimport { configureBiomeLint } from './biome';\nimport type { ConfigureProjectOptions } from './types';\nimport { configureVitest } from './vitest';\n\ninterface TsConfigReference {\n path: string;\n}\n\n/**\n * Merges new TypeScript project references into existing ones, deduplicating by\n * path and preserving the order of existing references so re-running a\n * generator neither duplicates nor reorders references.\n */\nexport const mergeTsReferences = (\n existing: TsConfigReference[] | undefined,\n toAdd: TsConfigReference[],\n): TsConfigReference[] => {\n const references = [...(existing ?? [])];\n const existingPaths = new Set(references.map((ref) => ref.path));\n for (const ref of toAdd) {\n if (!existingPaths.has(ref.path)) {\n references.push(ref);\n existingPaths.add(ref.path);\n }\n }\n return references;\n};\n\n/**\n * Updates typescript projects\n */\nexport const configureTsProject = async (\n tree: Tree,\n options: ConfigureProjectOptions,\n) => {\n // When the caller doesn't specify a module format, infer it from the\n // workspace root package.json (defaulting to ESM for a fresh workspace).\n const esm = options.esm ?? isEsmWorkspace(tree);\n\n // Remove a conflicting `module: commonjs` from the project tsconfig.json\n // (CommonJS is configured on tsconfig.lib.json below when needed).\n updateJson(tree, join(options.dir, 'tsconfig.json'), (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n module:\n tsConfig.compilerOptions?.module === 'commonjs'\n ? undefined\n : tsConfig.compilerOptions?.module,\n },\n }));\n const outDirToRootRelativePath = relative(\n join(tree.root, options.dir),\n tree.root,\n );\n const distDir = join(outDirToRootRelativePath, 'dist', options.dir, 'tsc');\n // Remove baseUrl and rootDir from the tsconfig.lib.json\n if (tree.exists(join(options.dir, 'tsconfig.lib.json'))) {\n updateJson(tree, join(options.dir, 'tsconfig.lib.json'), (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n baseUrl: undefined,\n rootDir: '.',\n outDir: distDir,\n tsBuildInfoFile: join(distDir, 'tsconfig.lib.tsbuildinfo'),\n // @nx/js configures the lib for ESM (module `nodenext`). CommonJS\n // projects use `node16`, which honours the workspace's\n // `type: commonjs`, emits CommonJS and resolves extensionless relative\n // imports. (Plain `commonjs`/`node` is deprecated in TypeScript 6.)\n ...(esm ? {} : { module: 'node16', moduleResolution: 'node16' }),\n },\n }));\n }\n // Update root project tsconfig\n updateJson(tree, 'tsconfig.base.json', (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n // baseUrl is deprecated in TypeScript 6 — use ./ prefix in paths instead\n baseUrl: undefined,\n rootDir: '.',\n paths: {\n // Remove any path aliases for this project with the npm scope prefix (eg remove @foo/bar)\n ...Object.fromEntries(\n Object.entries(tsConfig.compilerOptions?.paths ?? {}).filter(\n ([k]) => k !== options.fullyQualifiedName,\n ),\n ),\n // Add aliases which begin with colon (eg :foo/bar) to avoid sniping attacks\n [toScopeAlias(options.fullyQualifiedName)]: [\n `./${joinPathFragments(options.dir, 'src', 'index.ts')}`,\n ],\n },\n },\n }));\n if (tree.exists('tsconfig.json')) {\n updateJson(tree, 'tsconfig.json', (tsConfig) => ({\n ...tsConfig,\n // Add project references, deduplicating and preserving existing order\n references: mergeTsReferences(tsConfig.references, [\n { path: `./${options.dir}` },\n ]),\n }));\n }\n // Update the root package.json. ESM projects require `type: module`; for\n // CommonJS we write an explicit `type: commonjs` marker (which Node treats\n // identically to an absent `type`).\n updateJson(tree, 'package.json', (packageJson) => ({\n ...packageJson,\n type: esm ? 'module' : 'commonjs',\n }));\n // Remove package.json if it exists\n if (tree.exists(join(options.dir, 'package.json'))) {\n tree.delete(join(options.dir, 'package.json'));\n }\n\n await configureBiomeLint(tree, options);\n await configureVitest(tree, options);\n\n // If license checking is configured, make this project's lint target depend\n // on the root license-check target. No-op if there's no license-check target\n // (i.e. the license generator hasn't run); the license generator wires up\n // existing projects itself, so this works regardless of generator order.\n addLicenseCheckToLintTarget(tree, options.fullyQualifiedName);\n};\n"],"names":["joinPathFragments","updateJson","join","relative","addLicenseCheckToLintTarget","isEsmWorkspace","toScopeAlias","configureBiomeLint","configureVitest","mergeTsReferences","existing","toAdd","references","existingPaths","Set","map","ref","path","has","push","add","configureTsProject","tree","options","esm","dir","tsConfig","compilerOptions","module","undefined","outDirToRootRelativePath","root","distDir","exists","baseUrl","rootDir","outDir","tsBuildInfoFile","moduleResolution","paths","Object","fromEntries","entries","filter","k","fullyQualifiedName","packageJson","type","delete"],"mappings":"AAAA;;;CAGC,GACD,SAASA,iBAAiB,EA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oC;IACpCxB,WAAWqB,MAAM,gBAAgB,CAACwB,cAAiB,CAAA;YACjD,GAAGA,WAAW;YACdC,MAAMvB,MAAM,WAAW;QACzB,CAAA;IACA,mCAAmC;IACnC,IAAIF,KAAKW,MAAM,CAAC/B,KAAKqB,QAAQE,GAAG,EAAE,kBAAkB;QAClDH,KAAK0B,MAAM,CAAC9C,KAAKqB,QAAQE,GAAG,EAAE;IAChC;IAEA,MAAMlB,mBAAmBe,MAAMC;IAC/B,MAAMf,gBAAgBc,MAAMC;IAE5B,4EAA4E;IAC5E,6EAA6E;IAC7E,0EAA0E;IAC1E,yEAAyE;IACzEnB,4BAA4BkB,MAAMC,QAAQsB,kBAAkB;AAC9D,EAAE"}
@@ -11,4 +11,10 @@ export interface ConfigureProjectOptions {
11
11
  * Directory of the project relative to the root
12
12
  */
13
13
  readonly dir: string;
14
+ /**
15
+ * Whether the project uses ES modules. When false, the project is configured
16
+ * for CommonJS (tsconfig `module`/`moduleResolution`, no root `type: module`).
17
+ * Defaults to true (ESM) when not specified.
18
+ */
19
+ readonly esm?: boolean;
14
20
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/lib/types.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nexport interface ConfigureProjectOptions {\n /**\n * Full package name including scope (eg @foo/bar)\n */\n readonly fullyQualifiedName: string;\n /**\n * Directory of the project relative to the root\n */\n readonly dir: string;\n}\n"],"names":[],"mappings":"AAAA;;;CAGC,GACD,WASC"}
1
+ {"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/lib/types.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nexport interface ConfigureProjectOptions {\n /**\n * Full package name including scope (eg @foo/bar)\n */\n readonly fullyQualifiedName: string;\n /**\n * Directory of the project relative to the root\n */\n readonly dir: string;\n /**\n * Whether the project uses ES modules. When false, the project is configured\n * for CommonJS (tsconfig `module`/`moduleResolution`, no root `type: module`).\n * Defaults to true (ESM) when not specified.\n */\n readonly esm?: boolean;\n}\n"],"names":[],"mappings":"AAAA;;;CAGC,GACD,WAeC"}
@@ -135,7 +135,7 @@ exports[`ts#mcp-server generator > should match snapshot for Terraform generated
135
135
  required_providers {
136
136
  aws = {
137
137
  source = "hashicorp/aws"
138
- version = "6.52.0"
138
+ version = "6.54.0"
139
139
  }
140
140
  null = {
141
141
  source = "hashicorp/null"
@@ -201,6 +201,30 @@ variable "additional_iam_policy_statements" {
201
201
  default = []
202
202
  }
203
203
 
204
+ # VPC Configuration (optional)
205
+ variable "enable_vpc" {
206
+ description = "Run the agent core runtime inside a VPC. Set alongside vpc_id/subnet_ids."
207
+ type = bool
208
+ default = false
209
+ }
210
+
211
+ variable "vpc_id" {
212
+ description = "VPC ID to run the agent core runtime in. Required when enable_vpc is true."
213
+ type = string
214
+ default = null
215
+
216
+ validation {
217
+ condition = !var.enable_vpc || (var.vpc_id != null && var.subnet_ids != null)
218
+ error_message = "vpc_id and subnet_ids must be set when enable_vpc is true."
219
+ }
220
+ }
221
+
222
+ variable "subnet_ids" {
223
+ description = "Subnet IDs to run the agent core runtime in. Required when enable_vpc is true."
224
+ type = list(string)
225
+ default = null
226
+ }
227
+
204
228
  variable "tags" {
205
229
  description = "Tags to apply to resources"
206
230
  type = map(string)
@@ -436,6 +460,28 @@ resource "null_resource" "docker_publish" {
436
460
  depends_on = [aws_ecr_repository_policy.agent_core_ecr_policy]
437
461
  }
438
462
 
463
+ # Security group for the agent core runtime, used when running inside a VPC
464
+ resource "aws_security_group" "agent_core_runtime" {
465
+ count = var.enable_vpc ? 1 : 0
466
+
467
+ #checkov:skip=CKV2_AWS_5:Attached to the runtime via network_configuration; Checkov cannot resolve this reference
468
+ name_prefix = "\${var.agent_runtime_name}-runtime-"
469
+ description = "Security group for the \${var.agent_runtime_name} agent core runtime"
470
+ vpc_id = var.vpc_id
471
+ tags = var.tags
472
+ }
473
+
474
+ resource "aws_vpc_security_group_egress_rule" "agent_core_runtime_https" {
475
+ count = var.enable_vpc ? 1 : 0
476
+
477
+ security_group_id = aws_security_group.agent_core_runtime[0].id
478
+ cidr_ipv4 = "0.0.0.0/0"
479
+ from_port = 443
480
+ to_port = 443
481
+ ip_protocol = "tcp"
482
+ description = "Allow outbound HTTPS to AWS service endpoints"
483
+ }
484
+
439
485
  # Bedrock AgentCore Agent Runtime
440
486
  resource "aws_bedrockagentcore_agent_runtime" "agent_runtime" {
441
487
  agent_runtime_name = "\${var.agent_runtime_name}_\${random_id.unique_suffix.hex}"
@@ -462,7 +508,15 @@ resource "aws_bedrockagentcore_agent_runtime" "agent_runtime" {
462
508
  }
463
509
 
464
510
  network_configuration {
465
- network_mode = "PUBLIC"
511
+ network_mode = var.enable_vpc ? "VPC" : "PUBLIC"
512
+
513
+ dynamic "network_mode_config" {
514
+ for_each = var.enable_vpc ? [1] : []
515
+ content {
516
+ security_groups = [aws_security_group.agent_core_runtime[0].id]
517
+ subnets = var.subnet_ids
518
+ }
519
+ }
466
520
  }
467
521
 
468
522
  protocol_configuration {
@@ -489,7 +543,7 @@ resource "null_resource" "runtime_ready" {
489
543
 
490
544
  provisioner "local-exec" {
491
545
  command = <<-EOT
492
- uv run --with boto3==1.43.37 python -c "
546
+ uv run --with boto3==1.43.46 python -c "
493
547
  import boto3
494
548
  import json
495
549
  import os
@@ -564,6 +618,11 @@ output "agent_runtime_version" {
564
618
  description = "Version of the Bedrock Agent Core runtime"
565
619
  value = aws_bedrockagentcore_agent_runtime.agent_runtime.agent_runtime_version
566
620
  }
621
+
622
+ output "security_group_id" {
623
+ description = "Security group ID of the agent core runtime, for use in ingress rules on resources it must reach (e.g. a database). Null unless enable_vpc is true."
624
+ value = var.enable_vpc ? aws_security_group.agent_core_runtime[0].id : null
625
+ }
567
626
  "
568
627
  `;
569
628
 
@@ -590,6 +649,25 @@ variable "tags" {
590
649
  default = {}
591
650
  }
592
651
 
652
+ # VPC Configuration (optional)
653
+ variable "enable_vpc" {
654
+ description = "Run the agent core runtime inside a VPC. Set alongside vpc_id/subnet_ids."
655
+ type = bool
656
+ default = false
657
+ }
658
+
659
+ variable "vpc_id" {
660
+ description = "VPC ID to run the agent core runtime in. Required when enable_vpc is true."
661
+ type = string
662
+ default = null
663
+ }
664
+
665
+ variable "subnet_ids" {
666
+ description = "Subnet IDs to run the agent core runtime in. Required when enable_vpc is true."
667
+ type = list(string)
668
+ default = null
669
+ }
670
+
593
671
  variable "appconfig_application_id" {
594
672
  description = "ID of the shared runtime-config AppConfig application (from \`core/runtime-config/appconfig.application_id\`). The agent reads its runtime configuration from this application."
595
673
  type = string
@@ -605,6 +683,9 @@ module "agent_core_runtime" {
605
683
  agent_runtime_name = "TerraformSnapshotServer"
606
684
  docker_image_tag = "proj-terraform-snapshot-server:latest"
607
685
  server_protocol = "MCP"
686
+ enable_vpc = var.enable_vpc
687
+ vpc_id = var.vpc_id
688
+ subnet_ids = var.subnet_ids
608
689
 
609
690
  env = merge({
610
691
  RUNTIME_CONFIG_APP_ID = var.appconfig_application_id
@@ -647,12 +728,17 @@ output "appconfig_application_id" {
647
728
  description = "AppConfig Application ID for runtime config (passthrough of the shared \`appconfig_application_id\` input)."
648
729
  value = var.appconfig_application_id
649
730
  }
731
+
732
+ output "security_group_id" {
733
+ description = "Security group ID of the agent core runtime, for use in ingress rules on resources it must reach (e.g. a database). Null unless enable_vpc is true."
734
+ value = module.agent_core_runtime.security_group_id
735
+ }
650
736
  "
651
737
  `;
652
738
 
653
739
  exports[`ts#mcp-server generator > should match snapshot for generated files > mcp-server-http.ts 1`] = `
654
740
  "#!/usr/bin/env node
655
- import { createServer } from './server';
741
+ import { createServer } from './server.js';
656
742
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
657
743
  import express, { Request, Response } from 'express';
658
744
 
@@ -740,14 +826,14 @@ void (async () => {
740
826
  `;
741
827
 
742
828
  exports[`ts#mcp-server generator > should match snapshot for generated files > mcp-server-index.ts 1`] = `
743
- "export * from './server';
829
+ "export * from './server.js';
744
830
  "
745
831
  `;
746
832
 
747
833
  exports[`ts#mcp-server generator > should match snapshot for generated files > mcp-server-server.ts 1`] = `
748
834
  "import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
749
- import { registerDivideTool } from './tools/divide';
750
- import { registerSampleGuidanceResource } from './resources/sample-guidance';
835
+ import { registerDivideTool } from './tools/divide.js';
836
+ import { registerSampleGuidanceResource } from './resources/sample-guidance.js';
751
837
 
752
838
  /**
753
839
  * Create the MCP Server
@@ -769,7 +855,7 @@ export const createServer = async () => {
769
855
  exports[`ts#mcp-server generator > should match snapshot for generated files > mcp-server-stdio.ts 1`] = `
770
856
  "#!/usr/bin/env node
771
857
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
772
- import { createServer } from './server';
858
+ import { createServer } from './server.js';
773
859
 
774
860
  export const startMcpServer = async () => {
775
861
  const transport = new StdioServerTransport();
@@ -12,6 +12,7 @@ import { FsCommands } from "../../utils/fs.js";
12
12
  import { resolveIac } from "../../utils/iac.js";
13
13
  import { installDependencies } from "../../utils/install.js";
14
14
  import { addGeneratorMetricsIfApplicable } from "../../utils/metrics.js";
15
+ import { isEsmWorkspace } from "../../utils/module-format.js";
15
16
  import { kebabCase, toClassName } from "../../utils/names.js";
16
17
  import { getNpmScope } from "../../utils/npm-scope.js";
17
18
  import { addComponentDevTarget, addComponentGeneratorMetadata, addDependencyToTargetIfNotPresent, getGeneratorInfo, readProjectConfigurationUnqualified } from "../../utils/nx.js";
@@ -41,8 +42,8 @@ export const tsMcpServerGenerator = async (tree, options)=>{
41
42
  const projectPackageJsonPath = joinPathFragments(project.root, 'package.json');
42
43
  // Generate esm if the module system is esm, otherwise commonjs. Projects
43
44
  // don't typically have their own package.json (dependencies are declared in
44
- // the workspace root), so fall back to the root which is esm by default.
45
- const esm = readJson(tree, tree.exists(projectPackageJsonPath) ? projectPackageJsonPath : 'package.json').type === 'module';
45
+ // the workspace root), so fall back to the workspace format when absent.
46
+ const esm = tree.exists(projectPackageJsonPath) ? readJson(tree, projectPackageJsonPath).type === 'module' : isEsmWorkspace(tree);
46
47
  // Generate example server
47
48
  generateFiles(tree, joinPathFragments(import.meta.dirname, 'files'), targetSourceDir, {
48
49
  name,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/mcp-server/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n addDependenciesToPackageJson,\n detectPackageManager,\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readJson,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { ensureLicenseExceptions } from '../../license/config';\nimport { MCP_INSPECTOR_EXCEPTIONS } from '../../license/known-exceptions';\nimport { addMcpServerInfra } from '../../utils/agent-core-constructs/agent-core-constructs';\nimport { addTypeScriptBundleTarget } from '../../utils/bundle/bundle';\nimport { resolveContainers } from '../../utils/containers';\nimport { formatFilesInSubtree } from '../../utils/format';\nimport { FsCommands } from '../../utils/fs';\nimport { resolveIac } from '../../utils/iac';\nimport { installDependencies } from '../../utils/install';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics';\nimport { kebabCase, toClassName } from '../../utils/names';\nimport { getNpmScope } from '../../utils/npm-scope';\nimport {\n addComponentDevTarget,\n addComponentGeneratorMetadata,\n addDependencyToTargetIfNotPresent,\n getGeneratorInfo,\n type NxGeneratorInfo,\n readProjectConfigurationUnqualified,\n} from '../../utils/nx';\nimport { sortObjectKeys } from '../../utils/object';\nimport { assignPort } from '../../utils/port';\nimport { sharedConstructsGenerator } from '../../utils/shared-constructs';\nimport { TS_VERSIONS, withVersions } from '../../utils/versions';\nimport type { TsMcpServerGeneratorSchema } from './schema';\n\nexport const TS_MCP_SERVER_GENERATOR_INFO: NxGeneratorInfo = getGeneratorInfo(\n import.meta.filename,\n);\n\nexport const tsMcpServerGenerator = async (\n tree: Tree,\n options: TsMcpServerGeneratorSchema,\n): Promise<GeneratorCallback> => {\n const project = readProjectConfigurationUnqualified(tree, options.project);\n\n if (!tree.exists(joinPathFragments(project.root, 'tsconfig.json'))) {\n throw new Error(\n `Unsupported project ${options.project}. Expected a TypeScript project (with a tsconfig.json)`,\n );\n }\n\n const defaultName = `${kebabCase(project.name.split('/').pop())}-mcp-server`;\n const name = kebabCase(options.name || defaultName);\n const mcpServerNameClassName = toClassName(name);\n const mcpTargetPrefix = options.name ? name : 'mcp-server';\n const targetSourceDirRelativeToProjectRoot = joinPathFragments(\n 'src',\n mcpTargetPrefix,\n );\n const targetSourceDir = joinPathFragments(\n project.root,\n targetSourceDirRelativeToProjectRoot,\n );\n const relativeSourceDir = targetSourceDir.replace(project.root + '/', './');\n const distDir = joinPathFragments('dist', project.root);\n\n const infra = options.infra ?? 'agentcore';\n\n if (infra === 'none' && options.auth && options.auth !== 'iam') {\n console.warn(\n 'Warning: auth is ignored when no infrastructure is configured (no infrastructure is generated)',\n );\n }\n\n const auth = options.auth ?? 'iam';\n\n const projectPackageJsonPath = joinPathFragments(\n project.root,\n 'package.json',\n );\n\n // Generate esm if the module system is esm, otherwise commonjs. Projects\n // don't typically have their own package.json (dependencies are declared in\n // the workspace root), so fall back to the root which is esm by default.\n const esm =\n readJson(\n tree,\n tree.exists(projectPackageJsonPath)\n ? projectPackageJsonPath\n : 'package.json',\n ).type === 'module';\n\n // Generate example server\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files'),\n targetSourceDir,\n {\n name,\n esm,\n distDir,\n adotVersion:\n TS_VERSIONS['@aws/aws-distro-opentelemetry-node-autoinstrumentation'],\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Add dependencies\n const deps = withVersions([\n '@modelcontextprotocol/sdk',\n 'zod',\n 'express',\n '@aws-lambda-powertools/parameters',\n '@aws-sdk/client-appconfigdata',\n ]);\n const devDeps = withVersions([\n 'tsx',\n '@types/express',\n '@modelcontextprotocol/inspector',\n ]);\n\n // Add hosting based on infra\n if (infra === 'agentcore') {\n const containers = await resolveContainers(tree, 'inherit');\n const dockerImageTag = `${getNpmScope(tree)}-${name}:latest`;\n\n // Add bundle target\n await addTypeScriptBundleTarget(tree, project, {\n targetFilePath: `${targetSourceDirRelativeToProjectRoot}/http.ts`,\n bundleOutputDir: joinPathFragments('mcp', name),\n });\n\n const dockerOutputDir = joinPathFragments(\n 'dist',\n project.root,\n 'bundle',\n 'mcp',\n name,\n );\n const dockerTargetName = `${mcpTargetPrefix}-docker`;\n\n const fs = new FsCommands(tree);\n project.targets[dockerTargetName] = {\n cache: true,\n outputs: [`{workspaceRoot}/${dockerOutputDir}/Dockerfile`],\n executor: 'nx:run-commands',\n options: {\n commands: [\n fs.cp(\n `${targetSourceDir}/Dockerfile`,\n `${dockerOutputDir}/Dockerfile`,\n ),\n `${containers} build --platform linux/arm64 -t ${dockerImageTag} ${dockerOutputDir}`,\n ],\n parallel: false,\n },\n dependsOn: ['bundle'],\n };\n\n addDependencyToTargetIfNotPresent(project, 'docker', dockerTargetName);\n addDependencyToTargetIfNotPresent(project, 'build', 'docker');\n\n // Add shared constructs\n const iac = await resolveIac(tree, options.iac);\n await sharedConstructsGenerator(tree, { iac });\n\n // Add the construct to deploy the mcp server\n await addMcpServerInfra(tree, {\n mcpServerNameKebabCase: name,\n mcpServerNameClassName,\n projectName: project.name,\n dockerImageTag,\n dockerOutputDir,\n iac,\n auth,\n containers,\n });\n } else {\n // No Dockerfile needed for non-hosted MCP\n tree.delete(joinPathFragments(targetSourceDir, 'Dockerfile'));\n }\n\n addDependenciesToPackageJson(tree, deps, devDeps);\n // Add to the project's package.json too if it has one (e.g. nx plugins),\n // otherwise dependencies live in the workspace root only.\n if (tree.exists(projectPackageJsonPath)) {\n addDependenciesToPackageJson(tree, deps, devDeps, projectPackageJsonPath);\n }\n\n // @modelcontextprotocol/sdk declares zod as a peer dependency with a wide range\n // (^3.25 || ^4.0). Yarn does not dedupe the peer to the workspace's pinned zod, so\n // without a resolution it installs a separate zod under the SDK's own node_modules.\n // The two zod copies have structurally incompatible types, which breaks type\n // inference for registerTool inputSchema. Scope the resolution to the SDK so\n // other consumers (e.g. @tanstack/router-generator pinning zod@3) are unaffected.\n if (detectPackageManager() === 'yarn') {\n updateJson(tree, 'package.json', (packageJson) => {\n packageJson.resolutions = {\n ...packageJson.resolutions,\n '**/@modelcontextprotocol/sdk/zod': TS_VERSIONS['zod'],\n };\n return packageJson;\n });\n }\n\n const localDevPort = assignPort(tree, project, 8000, {\n component: { info: TS_MCP_SERVER_GENERATOR_INFO, name: mcpTargetPrefix },\n });\n\n const mcpTargets = {\n ...project.targets,\n // Add targets for running the MCP server\n [`${mcpTargetPrefix}-serve-stdio`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/stdio.ts`],\n cwd: '{projectRoot}',\n },\n },\n [`${mcpTargetPrefix}-serve`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/http.ts`],\n cwd: '{projectRoot}',\n env: {\n PORT: `${localDevPort}`,\n },\n },\n },\n [`${mcpTargetPrefix}-dev`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/http.ts`],\n cwd: '{projectRoot}',\n env: {\n PORT: `${localDevPort}`,\n LOCAL_DEV: 'true',\n },\n },\n },\n [`${mcpTargetPrefix}-inspect`]: {\n executor: 'nx:run-commands',\n continuous: true,\n // Launch the inspector against the locally served HTTP server. The dev\n // target starts the server and any connected dependencies (e.g. a local\n // database).\n dependsOn: [`${mcpTargetPrefix}-dev`],\n options: {\n commands: [\n `mcp-inspector --transport http --server-url http://localhost:${localDevPort}/mcp`,\n ],\n cwd: '{projectRoot}',\n },\n },\n [`${mcpTargetPrefix}-inspect-stdio`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [\n `mcp-inspector -- tsx --watch ${relativeSourceDir}/stdio.ts`,\n ],\n cwd: '{projectRoot}',\n },\n },\n };\n\n // Aggregate `<mcp>-dev` under the project-level `dev` target.\n addComponentDevTarget(mcpTargets, `${mcpTargetPrefix}-dev`);\n\n updateProjectConfiguration(tree, project.name, {\n ...project,\n // Sort targets so their order is stable regardless of insertion order on\n // first run vs re-run.\n targets: sortObjectKeys(mcpTargets),\n });\n\n addComponentGeneratorMetadata(\n tree,\n project.name,\n TS_MCP_SERVER_GENERATOR_INFO,\n targetSourceDirRelativeToProjectRoot,\n mcpTargetPrefix,\n {\n port: localDevPort,\n rc: mcpServerNameClassName,\n auth,\n },\n );\n\n await addGeneratorMetricsIfApplicable(tree, [TS_MCP_SERVER_GENERATOR_INFO]);\n\n await ensureLicenseExceptions(tree, MCP_INSPECTOR_EXCEPTIONS);\n\n await formatFilesInSubtree(tree);\n return () =>\n installDependencies(tree, options.preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\n\nexport default tsMcpServerGenerator;\n"],"names":["addDependenciesToPackageJson","detectPackageManager","generateFiles","joinPathFragments","OverwriteStrategy","readJson","updateJson","updateProjectConfiguration","ensureLicenseExceptions","MCP_INSPECTOR_EXCEPTIONS","addMcpServerInfra","addTypeScriptBundleTarget","resolveContainers","formatFilesInSubtree","FsCommands","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","kebabCase","toClassName","getNpmScope","addComponentDevTarget","addComponentGeneratorMetadata","addDependencyToTargetIfNotPresent","getGeneratorInfo","readProjectConfigurationUnqualified","sortObjectKeys","assignPort","sharedConstructsGenerator","TS_VERSIONS","withVersions","TS_MCP_SERVER_GENERATOR_INFO","filename","tsMcpServerGenerator","tree","options","project","exists","root","Error","defaultName","name","split","pop","mcpServerNameClassName","mcpTargetPrefix","targetSourceDirRelativeToProjectRoot","targetSourceDir","relativeSourceDir","replace","distDir","infra","auth","console","warn","projectPackageJsonPath","esm","type","dirname","adotVersion","overwriteStrategy","KeepExisting","deps","devDeps","containers","dockerImageTag","targetFilePath","bundleOutputDir","dockerOutputDir","dockerTargetName","fs","targets","cache","outputs","executor","commands","cp","parallel","dependsOn","iac","mcpServerNameKebabCase","projectName","delete","packageJson","resolutions","localDevPort","component","info","mcpTargets","continuous","cwd","env","PORT","LOCAL_DEV","port","rc","preferInstallDependencies","languages"],"mappings":"AAAA;;;CAGC,GACD,SACEA,4BAA4B,EAC5BC,oBAAoB,EAEpBC,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EACjBC,QAAQ,EAERC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAASC,uBAAuB,QAAQ,0BAAuB;AAC/D,SAASC,wBAAwB,QAAQ,oCAAiC;AAC1E,SAASC,iBAAiB,QAAQ,6DAA0D;AAC5F,SAASC,yBAAyB,QAAQ,+BAA4B;AACtE,SAASC,iBAAiB,QAAQ,4BAAyB;AAC3D,SAASC,oBAAoB,QAAQ,wBAAqB;AAC1D,SAASC,UAAU,QAAQ,oBAAiB;AAC5C,SAASC,UAAU,QAAQ,qBAAkB;AAC7C,SAASC,mBAAmB,QAAQ,yBAAsB;AAC1D,SAASC,+BAA+B,QAAQ,yBAAsB;AACtE,SAASC,SAAS,EAAEC,WAAW,QAAQ,uBAAoB;AAC3D,SAASC,WAAW,QAAQ,2BAAwB;AACpD,SACEC,qBAAqB,EACrBC,6BAA6B,EAC7BC,iCAAiC,EACjCC,gBAAgB,EAEhBC,mCAAmC,QAC9B,oBAAiB;AACxB,SAASC,cAAc,QAAQ,wBAAqB;AACpD,SAASC,UAAU,QAAQ,sBAAmB;AAC9C,SAASC,yBAAyB,QAAQ,mCAAgC;AAC1E,SAASC,WAAW,EAAEC,YAAY,QAAQ,0BAAuB;AAGjE,OAAO,MAAMC,+BAAgDP,iBAC3D,YAAYQ,QAAQ,EACpB;AAEF,OAAO,MAAMC,uBAAuB,OAClCC,MACAC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/ts/mcp-server/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n addDependenciesToPackageJson,\n detectPackageManager,\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readJson,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { ensureLicenseExceptions } from '../../license/config';\nimport { MCP_INSPECTOR_EXCEPTIONS } from '../../license/known-exceptions';\nimport { addMcpServerInfra } from '../../utils/agent-core-constructs/agent-core-constructs';\nimport { addTypeScriptBundleTarget } from '../../utils/bundle/bundle';\nimport { resolveContainers } from '../../utils/containers';\nimport { formatFilesInSubtree } from '../../utils/format';\nimport { FsCommands } from '../../utils/fs';\nimport { resolveIac } from '../../utils/iac';\nimport { installDependencies } from '../../utils/install';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics';\nimport { isEsmWorkspace } from '../../utils/module-format';\nimport { kebabCase, toClassName } from '../../utils/names';\nimport { getNpmScope } from '../../utils/npm-scope';\nimport {\n addComponentDevTarget,\n addComponentGeneratorMetadata,\n addDependencyToTargetIfNotPresent,\n getGeneratorInfo,\n type NxGeneratorInfo,\n readProjectConfigurationUnqualified,\n} from '../../utils/nx';\nimport { sortObjectKeys } from '../../utils/object';\nimport { assignPort } from '../../utils/port';\nimport { sharedConstructsGenerator } from '../../utils/shared-constructs';\nimport { TS_VERSIONS, withVersions } from '../../utils/versions';\nimport type { TsMcpServerGeneratorSchema } from './schema';\n\nexport const TS_MCP_SERVER_GENERATOR_INFO: NxGeneratorInfo = getGeneratorInfo(\n import.meta.filename,\n);\n\nexport const tsMcpServerGenerator = async (\n tree: Tree,\n options: TsMcpServerGeneratorSchema,\n): Promise<GeneratorCallback> => {\n const project = readProjectConfigurationUnqualified(tree, options.project);\n\n if (!tree.exists(joinPathFragments(project.root, 'tsconfig.json'))) {\n throw new Error(\n `Unsupported project ${options.project}. Expected a TypeScript project (with a tsconfig.json)`,\n );\n }\n\n const defaultName = `${kebabCase(project.name.split('/').pop())}-mcp-server`;\n const name = kebabCase(options.name || defaultName);\n const mcpServerNameClassName = toClassName(name);\n const mcpTargetPrefix = options.name ? name : 'mcp-server';\n const targetSourceDirRelativeToProjectRoot = joinPathFragments(\n 'src',\n mcpTargetPrefix,\n );\n const targetSourceDir = joinPathFragments(\n project.root,\n targetSourceDirRelativeToProjectRoot,\n );\n const relativeSourceDir = targetSourceDir.replace(project.root + '/', './');\n const distDir = joinPathFragments('dist', project.root);\n\n const infra = options.infra ?? 'agentcore';\n\n if (infra === 'none' && options.auth && options.auth !== 'iam') {\n console.warn(\n 'Warning: auth is ignored when no infrastructure is configured (no infrastructure is generated)',\n );\n }\n\n const auth = options.auth ?? 'iam';\n\n const projectPackageJsonPath = joinPathFragments(\n project.root,\n 'package.json',\n );\n\n // Generate esm if the module system is esm, otherwise commonjs. Projects\n // don't typically have their own package.json (dependencies are declared in\n // the workspace root), so fall back to the workspace format when absent.\n const esm = tree.exists(projectPackageJsonPath)\n ? readJson(tree, projectPackageJsonPath).type === 'module'\n : isEsmWorkspace(tree);\n\n // Generate example server\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files'),\n targetSourceDir,\n {\n name,\n esm,\n distDir,\n adotVersion:\n TS_VERSIONS['@aws/aws-distro-opentelemetry-node-autoinstrumentation'],\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Add dependencies\n const deps = withVersions([\n '@modelcontextprotocol/sdk',\n 'zod',\n 'express',\n '@aws-lambda-powertools/parameters',\n '@aws-sdk/client-appconfigdata',\n ]);\n const devDeps = withVersions([\n 'tsx',\n '@types/express',\n '@modelcontextprotocol/inspector',\n ]);\n\n // Add hosting based on infra\n if (infra === 'agentcore') {\n const containers = await resolveContainers(tree, 'inherit');\n const dockerImageTag = `${getNpmScope(tree)}-${name}:latest`;\n\n // Add bundle target\n await addTypeScriptBundleTarget(tree, project, {\n targetFilePath: `${targetSourceDirRelativeToProjectRoot}/http.ts`,\n bundleOutputDir: joinPathFragments('mcp', name),\n });\n\n const dockerOutputDir = joinPathFragments(\n 'dist',\n project.root,\n 'bundle',\n 'mcp',\n name,\n );\n const dockerTargetName = `${mcpTargetPrefix}-docker`;\n\n const fs = new FsCommands(tree);\n project.targets[dockerTargetName] = {\n cache: true,\n outputs: [`{workspaceRoot}/${dockerOutputDir}/Dockerfile`],\n executor: 'nx:run-commands',\n options: {\n commands: [\n fs.cp(\n `${targetSourceDir}/Dockerfile`,\n `${dockerOutputDir}/Dockerfile`,\n ),\n `${containers} build --platform linux/arm64 -t ${dockerImageTag} ${dockerOutputDir}`,\n ],\n parallel: false,\n },\n dependsOn: ['bundle'],\n };\n\n addDependencyToTargetIfNotPresent(project, 'docker', dockerTargetName);\n addDependencyToTargetIfNotPresent(project, 'build', 'docker');\n\n // Add shared constructs\n const iac = await resolveIac(tree, options.iac);\n await sharedConstructsGenerator(tree, { iac });\n\n // Add the construct to deploy the mcp server\n await addMcpServerInfra(tree, {\n mcpServerNameKebabCase: name,\n mcpServerNameClassName,\n projectName: project.name,\n dockerImageTag,\n dockerOutputDir,\n iac,\n auth,\n containers,\n });\n } else {\n // No Dockerfile needed for non-hosted MCP\n tree.delete(joinPathFragments(targetSourceDir, 'Dockerfile'));\n }\n\n addDependenciesToPackageJson(tree, deps, devDeps);\n // Add to the project's package.json too if it has one (e.g. nx plugins),\n // otherwise dependencies live in the workspace root only.\n if (tree.exists(projectPackageJsonPath)) {\n addDependenciesToPackageJson(tree, deps, devDeps, projectPackageJsonPath);\n }\n\n // @modelcontextprotocol/sdk declares zod as a peer dependency with a wide range\n // (^3.25 || ^4.0). Yarn does not dedupe the peer to the workspace's pinned zod, so\n // without a resolution it installs a separate zod under the SDK's own node_modules.\n // The two zod copies have structurally incompatible types, which breaks type\n // inference for registerTool inputSchema. Scope the resolution to the SDK so\n // other consumers (e.g. @tanstack/router-generator pinning zod@3) are unaffected.\n if (detectPackageManager() === 'yarn') {\n updateJson(tree, 'package.json', (packageJson) => {\n packageJson.resolutions = {\n ...packageJson.resolutions,\n '**/@modelcontextprotocol/sdk/zod': TS_VERSIONS['zod'],\n };\n return packageJson;\n });\n }\n\n const localDevPort = assignPort(tree, project, 8000, {\n component: { info: TS_MCP_SERVER_GENERATOR_INFO, name: mcpTargetPrefix },\n });\n\n const mcpTargets = {\n ...project.targets,\n // Add targets for running the MCP server\n [`${mcpTargetPrefix}-serve-stdio`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/stdio.ts`],\n cwd: '{projectRoot}',\n },\n },\n [`${mcpTargetPrefix}-serve`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/http.ts`],\n cwd: '{projectRoot}',\n env: {\n PORT: `${localDevPort}`,\n },\n },\n },\n [`${mcpTargetPrefix}-dev`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/http.ts`],\n cwd: '{projectRoot}',\n env: {\n PORT: `${localDevPort}`,\n LOCAL_DEV: 'true',\n },\n },\n },\n [`${mcpTargetPrefix}-inspect`]: {\n executor: 'nx:run-commands',\n continuous: true,\n // Launch the inspector against the locally served HTTP server. The dev\n // target starts the server and any connected dependencies (e.g. a local\n // database).\n dependsOn: [`${mcpTargetPrefix}-dev`],\n options: {\n commands: [\n `mcp-inspector --transport http --server-url http://localhost:${localDevPort}/mcp`,\n ],\n cwd: '{projectRoot}',\n },\n },\n [`${mcpTargetPrefix}-inspect-stdio`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [\n `mcp-inspector -- tsx --watch ${relativeSourceDir}/stdio.ts`,\n ],\n cwd: '{projectRoot}',\n },\n },\n };\n\n // Aggregate `<mcp>-dev` under the project-level `dev` target.\n addComponentDevTarget(mcpTargets, `${mcpTargetPrefix}-dev`);\n\n updateProjectConfiguration(tree, project.name, {\n ...project,\n // Sort targets so their order is stable regardless of insertion order on\n // first run vs re-run.\n targets: sortObjectKeys(mcpTargets),\n });\n\n addComponentGeneratorMetadata(\n tree,\n project.name,\n TS_MCP_SERVER_GENERATOR_INFO,\n targetSourceDirRelativeToProjectRoot,\n mcpTargetPrefix,\n {\n port: localDevPort,\n rc: mcpServerNameClassName,\n auth,\n },\n );\n\n await addGeneratorMetricsIfApplicable(tree, [TS_MCP_SERVER_GENERATOR_INFO]);\n\n await ensureLicenseExceptions(tree, MCP_INSPECTOR_EXCEPTIONS);\n\n await formatFilesInSubtree(tree);\n return () =>\n installDependencies(tree, options.preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\n\nexport default tsMcpServerGenerator;\n"],"names":["addDependenciesToPackageJson","detectPackageManager","generateFiles","joinPathFragments","OverwriteStrategy","readJson","updateJson","updateProjectConfiguration","ensureLicenseExceptions","MCP_INSPECTOR_EXCEPTIONS","addMcpServerInfra","addTypeScriptBundleTarget","resolveContainers","formatFilesInSubtree","FsCommands","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","isEsmWorkspace","kebabCase","toClassName","getNpmScope","addComponentDevTarget","addComponentGeneratorMetadata","addDependencyToTargetIfNotPresent","getGeneratorInfo","readProjectConfigurationUnqualified","sortObjectKeys","assignPort","sharedConstructsGenerator","TS_VERSIONS","withVersions","TS_MCP_SERVER_GENERATOR_INFO","filename","tsMcpServerGenerator","tree","options","project","exists","root","Error","defaultName","name","split","pop","mcpServerNameClassName","mcpTargetPrefix","targetSourceDirRelativeToProjectRoot","targetSourceDir","relativeSourceDir","replace","distDir","infra","auth","console","warn","projectPackageJsonPath","esm","type","dirname","adotVersion","overwriteStrategy","KeepExisting","deps","devDeps","containers","dockerImageTag","targetFilePath","bundleOutputDir","dockerOutputDir","dockerTargetName","fs","targets","cache","outputs","executor","commands","cp","parallel","dependsOn","iac","mcpServerNameKebabCase","projectName","delete","packageJson","resolutions","localDevPort","component","info","mcpTargets","continuous","cwd","env","PORT","LOCAL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,CAAC,GAAGhD,gBAAgB,QAAQ,CAAC,CAAC,EAAE;YAC9B6B,UAAU;YACVe,YAAY;YACZ,uEAAuE;YACvE,wEAAwE;YACxE,aAAa;YACbX,WAAW;gBAAC,GAAGjC,gBAAgB,IAAI,CAAC;aAAC;YACrCV,SAAS;gBACPwC,UAAU;oBACR,CAAC,6DAA6D,EAAEU,aAAa,IAAI,CAAC;iBACnF;gBACDK,KAAK;YACP;QACF;QACA,CAAC,GAAG7C,gBAAgB,cAAc,CAAC,CAAC,EAAE;YACpC6B,UAAU;YACVe,YAAY;YACZtD,SAAS;gBACPwC,UAAU;oBACR,CAAC,6BAA6B,EAAE3B,kBAAkB,SAAS,CAAC;iBAC7D;gBACD0C,KAAK;YACP;QACF;IACF;IAEA,8DAA8D;IAC9DrE,sBAAsBmE,YAAY,GAAG3C,gBAAgB,IAAI,CAAC;IAE1DvC,2BAA2B4B,MAAME,QAAQK,IAAI,EAAE;QAC7C,GAAGL,OAAO;QACV,yEAAyE;QACzE,uBAAuB;QACvBmC,SAAS7C,eAAe8D;IAC1B;IAEAlE,8BACEY,MACAE,QAAQK,IAAI,EACZV,8BACAe,sCACAD,iBACA;QACEiD,MAAMT;QACNU,IAAInD;QACJQ;IACF;IAGF,MAAMpC,gCAAgCkB,MAAM;QAACH;KAA6B;IAE1E,MAAMxB,wBAAwB2B,MAAM1B;IAEpC,MAAMI,qBAAqBsB;IAC3B,OAAO,IACLnB,oBAAoBmB,MAAMC,QAAQ6D,yBAAyB,EAAE;YAC3DC,WAAW;gBAAC;aAAa;QAC3B;AACJ,EAAE;AAEF,eAAehE,qBAAqB"}
@@ -1,9 +1,9 @@
1
1
  import { type GeneratorCallback, type Tree, generateFiles, joinPathFragments } from "@nx/devkit";
2
- import type { <%- namePascalCase %>GeneratorSchema } from './schema.js';
2
+ import type { <%- namePascalCase %>GeneratorSchema } from './schema<% if (esm) { %>.js<% } %>';
3
3
 
4
4
  export const <%- nameCamelCase %>Generator = async (tree: Tree, options: <%- namePascalCase %>GeneratorSchema): Promise<GeneratorCallback | void> => {
5
5
  // TODO: implement your generator here, for example:
6
- generateFiles(tree, joinPathFragments(import.meta.dirname, 'files'), 'target/dir', options);
6
+ generateFiles(tree, joinPathFragments(<% if (esm) { %>import.meta.dirname<% } else { %>__dirname<% } %>, 'files'), 'target/dir', options);
7
7
  };
8
8
 
9
9
  export default <%- nameCamelCase %>Generator;
@@ -1,12 +1,12 @@
1
1
  import { type GeneratorCallback, type Tree } from "@nx/devkit";
2
- import type { <%- namePascalCase %>GeneratorSchema } from './schema.js';
2
+ import type { <%- namePascalCase %>GeneratorSchema } from './schema<% if (esm) { %>.js<% } %>';
3
3
  import { type NxGeneratorInfo, getGeneratorInfo } from '<%- pathToProjectSourceRoot %>utils/nx';
4
4
  import { addGeneratorMetricsIfApplicable } from '<%- pathToProjectSourceRoot %>utils/metrics';
5
5
  import { formatFilesInSubtree } from '<%- pathToProjectSourceRoot %>utils/format';
6
6
  import { installDependencies } from '<%- pathToProjectSourceRoot %>utils/install';
7
7
 
8
8
  export const <%- nameUpperSnakeCase %>_GENERATOR_INFO: NxGeneratorInfo =
9
- getGeneratorInfo(import.meta.filename);
9
+ getGeneratorInfo(<% if (esm) { %>import.meta.filename<% } else { %>__filename<% } %>);
10
10
 
11
11
  export const <%- nameCamelCase %>Generator = async (tree: Tree, options: <%- namePascalCase %>GeneratorSchema): Promise<GeneratorCallback> => {
12
12
 
@@ -10,6 +10,7 @@ import { addStarExport, applyGritQL } from "../../utils/ast.js";
10
10
  import { formatFilesInSubtree } from "../../utils/format.js";
11
11
  import { installDependencies } from "../../utils/install.js";
12
12
  import { addGeneratorMetricsIfApplicable } from "../../utils/metrics.js";
13
+ import { esmVars } from "../../utils/module-format.js";
13
14
  import { kebabCase, pascalCase, snakeCase } from "../../utils/names.js";
14
15
  import { addComponentGeneratorMetadata, getGeneratorInfo, readProjectConfigurationUnqualified } from "../../utils/nx.js";
15
16
  import { sortObjectKeys } from "../../utils/object.js";
@@ -38,7 +39,8 @@ export const tsNxGeneratorGenerator = async (tree, options)=>{
38
39
  isNxPluginForAws,
39
40
  pathToProjectSourceRoot: getRelativePathToRootByDirectory(generatorSubDir),
40
41
  generatorDir,
41
- generatorSubDir
42
+ generatorSubDir,
43
+ ...esmVars(tree)
42
44
  };
43
45
  // Add the common files, preserving any the user has already implemented
44
46
  generateFiles(tree, joinPathFragments(import.meta.dirname, 'files', 'common'), generatorDir, {
@@ -77,7 +79,8 @@ export const tsNxGeneratorGenerator = async (tree, options)=>{
77
79
  });
78
80
  const indexPath = joinPathFragments(sourceRoot, 'index.ts');
79
81
  if (tree.exists(indexPath)) {
80
- // NodeNext requires explicit extensions; the local plugin is ESM.
82
+ // ESM projects require the explicit `.js` extension; `addStarExport`
83
+ // strips it for CommonJS workspaces.
81
84
  await addStarExport(tree, indexPath, `./${generatorSubDir}/generator.js`);
82
85
  }
83
86
  addComponentGeneratorMetadata(tree, plugin.name, NX_GENERATOR_GENERATOR_INFO, joinPathFragments(srcDir, generatorSubDir), name);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/nx-generator/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readJson,\n type Tree,\n writeJson,\n} from '@nx/devkit';\nimport camelCase from 'lodash.camelcase';\nimport PackageJson from '../../../package.json' with { type: 'json' };\nimport { addStarExport, applyGritQL } from '../../utils/ast';\nimport { formatFilesInSubtree } from '../../utils/format';\nimport { installDependencies } from '../../utils/install';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics';\nimport { kebabCase, pascalCase, snakeCase } from '../../utils/names';\nimport {\n addComponentGeneratorMetadata,\n getGeneratorInfo,\n readProjectConfigurationUnqualified,\n} from '../../utils/nx';\nimport { sortObjectKeys } from '../../utils/object';\nimport { getRelativePathToRootByDirectory } from '../../utils/paths';\nimport { configureTsProjectAsNxPlugin } from '../nx-plugin/utils';\nimport type { TsNxGeneratorGeneratorSchema } from './schema';\n\nexport const NX_GENERATOR_GENERATOR_INFO = getGeneratorInfo(\n import.meta.filename,\n);\n\nexport const tsNxGeneratorGenerator = async (\n tree: Tree,\n options: TsNxGeneratorGeneratorSchema,\n): Promise<GeneratorCallback | void> => {\n const { name, directory, project: pluginProject, description } = options;\n\n const plugin = readProjectConfigurationUnqualified(tree, pluginProject);\n const sourceRoot = plugin.sourceRoot ?? joinPathFragments(plugin.root, 'src');\n const sourceRootParts = sourceRoot.split('/');\n const srcDir = sourceRootParts[sourceRootParts.length - 1];\n const generatorSubDir = directory ?? kebabCase(name);\n const generatorDir = joinPathFragments(sourceRoot, generatorSubDir);\n\n const rootPackageJson = tree.exists('package.json')\n ? readJson(tree, 'package.json')\n : undefined;\n const isNxPluginForAws = rootPackageJson?.name === '@aws/nx-plugin-source';\n\n // Configure the targeted project as an Nx Plugin\n configureTsProjectAsNxPlugin(tree, pluginProject);\n\n const enhancedOptions = {\n name,\n description,\n namePascalCase: pascalCase(name),\n nameCamelCase: camelCase(name),\n nameKebabCase: kebabCase(name),\n nameUpperSnakeCase: snakeCase(name).toUpperCase(),\n isNxPluginForAws,\n pathToProjectSourceRoot: getRelativePathToRootByDirectory(generatorSubDir),\n generatorDir,\n generatorSubDir,\n };\n\n // Add the common files, preserving any the user has already implemented\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'common'),\n generatorDir,\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Add the files specific to this repo vs a local generator in another project\n if (isNxPluginForAws) {\n // Generators should be in the @aws/nx-plugin project\n if (pluginProject !== PackageJson.name) {\n throw new Error(\n `Generators should be added to the ${PackageJson.name} project.`,\n );\n }\n\n // Add the generator\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'nx-plugin-for-aws',\n 'generator',\n ),\n generatorDir,\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Generate guide page in docs\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'nx-plugin-for-aws',\n 'docs',\n ),\n joinPathFragments('docs', 'src', 'content', 'docs', 'en', 'guides'),\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Update the docs config to add the page entry to the Generator guides sidebar section\n await applyGritQL(\n tree,\n joinPathFragments('docs', 'astro.config.mjs'),\n `\\`items: [$items]\\` where { $items <: within \\`sidebar: [$_]\\`, $items <: contains \\`'ts#project'\\`, $items <: not contains \\`'/guides/${enhancedOptions.nameKebabCase}'\\`, $items += \\`, { label: '${name}', link: '/guides/${enhancedOptions.nameKebabCase}' }\\` }`,\n );\n\n // Expose the generator from the SDK for known prefixes (ts# / py#)\n addSdkExport(tree, plugin.root, name, generatorSubDir, enhancedOptions);\n } else {\n // Local generator in a project other than nx-plugin-for-aws\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'local'),\n generatorDir,\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n const indexPath = joinPathFragments(sourceRoot, 'index.ts');\n if (tree.exists(indexPath)) {\n // NodeNext requires explicit extensions; the local plugin is ESM.\n await addStarExport(tree, indexPath, `./${generatorSubDir}/generator.js`);\n }\n\n addComponentGeneratorMetadata(\n tree,\n plugin.name,\n NX_GENERATOR_GENERATOR_INFO,\n joinPathFragments(srcDir, generatorSubDir),\n name,\n );\n }\n\n const factoryBasePath = `./${srcDir}/${generatorSubDir}`;\n\n // Update generators.json\n const generatorsJsonPath = joinPathFragments(plugin.root, 'generators.json');\n const generatorsJson = tree.exists(generatorsJsonPath)\n ? readJson(tree, generatorsJsonPath)\n : { generators: {} };\n // Metrics are only tracked within the @aws/nx-plugin repo. Reuse the existing\n // metric for a same-name re-run, otherwise allocate a new one.\n let metric: string | undefined;\n if (isNxPluginForAws) {\n const existingMetrics = Object.values(generatorsJson?.generators ?? {})\n .map((g: any) => g.metric)\n .filter((m): m is string => typeof m === 'string');\n metric =\n generatorsJson?.generators?.[name]?.metric ??\n (existingMetrics.length > 0 ? incrementMetric(existingMetrics) : 'g1');\n }\n writeJson(tree, generatorsJsonPath, {\n ...generatorsJson,\n generators: sortObjectKeys({\n ...generatorsJson?.generators,\n [name]: {\n factory: `${factoryBasePath}/generator`,\n schema: `${factoryBasePath}/schema.json`,\n description:\n description ?? 'TODO: Add short description of the generator',\n ...(isNxPluginForAws ? { metric } : {}),\n },\n }),\n });\n\n await addGeneratorMetricsIfApplicable(tree, [NX_GENERATOR_GENERATOR_INFO]);\n\n await formatFilesInSubtree(tree);\n\n return () =>\n installDependencies(tree, options.preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\n\nconst incrementMetric = (metrics: string[]): string => {\n const maxMetric = Math.max(...metrics.map((m) => Number(m.slice(1))));\n return `g${maxMetric + 1}`;\n};\n\n// Maps a generator name prefix to the SDK entry point that should re-export it\nconst SDK_EXPORT_PREFIXES: Record<string, string> = {\n 'ts#': 'ts',\n 'py#': 'py',\n};\n\n// Re-exports a generated generator from the matching SDK entry point so it is\n// available programmatically as part of @aws/nx-plugin's SDK\nconst addSdkExport = (\n tree: Tree,\n pluginRoot: string,\n name: string,\n generatorSubDir: string,\n options: { nameCamelCase: string; namePascalCase: string },\n): void => {\n const prefix = Object.keys(SDK_EXPORT_PREFIXES).find((p) =>\n name.startsWith(p),\n );\n if (!prefix) {\n return;\n }\n\n const sdkPath = joinPathFragments(\n pluginRoot,\n 'src',\n 'sdk',\n `${SDK_EXPORT_PREFIXES[prefix]}.ts`,\n );\n const generatorExport = `${options.nameCamelCase}Generator`;\n const schemaExport = `${options.namePascalCase}GeneratorSchema`;\n const moduleBase = `../${generatorSubDir}`;\n\n const contents = tree.exists(sdkPath) ? tree.read(sdkPath).toString() : '';\n // Idempotent: skip if this generator is already exported\n if (contents.includes(`${moduleBase}/generator`)) {\n return;\n }\n\n const block = `// ${options.namePascalCase} Generator\\nexport { ${generatorExport} } from '${moduleBase}/generator';\\nexport type { ${schemaExport} } from '${moduleBase}/schema';\\n`;\n\n const prefixContents = contents.trim()\n ? `${contents.replace(/\\s*$/, '')}\\n\\n`\n : '';\n tree.write(sdkPath, `${prefixContents}${block}`);\n};\n\nexport default tsNxGeneratorGenerator;\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","readJson","writeJson","camelCase","PackageJson","type","addStarExport","applyGritQL","formatFilesInSubtree","installDependencies","addGeneratorMetricsIfApplicable","kebabCase","pascalCase","snakeCase","addComponentGeneratorMetadata","getGeneratorInfo","readProjectConfigurationUnqualified","sortObjectKeys","getRelativePathToRootByDirectory","configureTsProjectAsNxPlugin","NX_GENERATOR_GENERATOR_INFO","filename","tsNxGeneratorGenerator","tree","options","name","directory","project","pluginProject","description","plugin","sourceRoot","root","sourceRootParts","split","srcDir","length","generatorSubDir","generatorDir","rootPackageJson","exists","undefined","isNxPluginForAws","enhancedOptions","namePascalCase","nameCamelCase","nameKebabCase","nameUpperSnakeCase","toUpperCase","pathToProjectSourceRoot","dirname","overwriteStrategy","KeepExisting","Error","addSdkExport","indexPath","factoryBasePath","generatorsJsonPath","generatorsJson","generators","metric","existingMetrics","Object","values","map","g","filter","m","incrementMetric","factory","schema","preferInstallDependencies","languages","metrics","maxMetric","Math","max","Number","slice","SDK_EXPORT_PREFIXES","pluginRoot","prefix","keys","find","p","startsWith","sdkPath","generatorExport","schemaExport","moduleBase","contents","read","toString","includes","block","prefixContents","trim","replace","write"],"mappings":"AAAA;;;CAGC,GACD,SAEEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EACjBC,QAAQ,EAERC,SAAS,QACJ,aAAa;AACpB,OAAOC,eAAe,mBAAmB;AACzC,OAAOC,iBAAiB,6BAA6B;IAAEC,MAAM;AAAO,EAAE;AACtE,SAASC,aAAa,EAAEC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AAexE,uBAAuB"}
1
+ {"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/nx-generator/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readJson,\n type Tree,\n writeJson,\n} from '@nx/devkit';\nimport camelCase from 'lodash.camelcase';\nimport PackageJson from '../../../package.json' with { type: 'json' };\nimport { addStarExport, applyGritQL } from '../../utils/ast';\nimport { formatFilesInSubtree } from '../../utils/format';\nimport { installDependencies } from '../../utils/install';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics';\nimport { esmVars } from '../../utils/module-format';\nimport { kebabCase, pascalCase, snakeCase } from '../../utils/names';\nimport {\n addComponentGeneratorMetadata,\n getGeneratorInfo,\n readProjectConfigurationUnqualified,\n} from '../../utils/nx';\nimport { sortObjectKeys } from '../../utils/object';\nimport { getRelativePathToRootByDirectory } from '../../utils/paths';\nimport { configureTsProjectAsNxPlugin } from '../nx-plugin/utils';\nimport type { TsNxGeneratorGeneratorSchema } from './schema';\n\nexport const NX_GENERATOR_GENERATOR_INFO = getGeneratorInfo(\n import.meta.filename,\n);\n\nexport const tsNxGeneratorGenerator = async (\n tree: Tree,\n options: TsNxGeneratorGeneratorSchema,\n): Promise<GeneratorCallback | void> => {\n const { name, directory, project: pluginProject, description } = options;\n\n const plugin = readProjectConfigurationUnqualified(tree, pluginProject);\n const sourceRoot = plugin.sourceRoot ?? joinPathFragments(plugin.root, 'src');\n const sourceRootParts = sourceRoot.split('/');\n const srcDir = sourceRootParts[sourceRootParts.length - 1];\n const generatorSubDir = directory ?? kebabCase(name);\n const generatorDir = joinPathFragments(sourceRoot, generatorSubDir);\n\n const rootPackageJson = tree.exists('package.json')\n ? readJson(tree, 'package.json')\n : undefined;\n const isNxPluginForAws = rootPackageJson?.name === '@aws/nx-plugin-source';\n\n // Configure the targeted project as an Nx Plugin\n configureTsProjectAsNxPlugin(tree, pluginProject);\n\n const enhancedOptions = {\n name,\n description,\n namePascalCase: pascalCase(name),\n nameCamelCase: camelCase(name),\n nameKebabCase: kebabCase(name),\n nameUpperSnakeCase: snakeCase(name).toUpperCase(),\n isNxPluginForAws,\n pathToProjectSourceRoot: getRelativePathToRootByDirectory(generatorSubDir),\n generatorDir,\n generatorSubDir,\n ...esmVars(tree),\n };\n\n // Add the common files, preserving any the user has already implemented\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'common'),\n generatorDir,\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Add the files specific to this repo vs a local generator in another project\n if (isNxPluginForAws) {\n // Generators should be in the @aws/nx-plugin project\n if (pluginProject !== PackageJson.name) {\n throw new Error(\n `Generators should be added to the ${PackageJson.name} project.`,\n );\n }\n\n // Add the generator\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'nx-plugin-for-aws',\n 'generator',\n ),\n generatorDir,\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Generate guide page in docs\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n 'nx-plugin-for-aws',\n 'docs',\n ),\n joinPathFragments('docs', 'src', 'content', 'docs', 'en', 'guides'),\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Update the docs config to add the page entry to the Generator guides sidebar section\n await applyGritQL(\n tree,\n joinPathFragments('docs', 'astro.config.mjs'),\n `\\`items: [$items]\\` where { $items <: within \\`sidebar: [$_]\\`, $items <: contains \\`'ts#project'\\`, $items <: not contains \\`'/guides/${enhancedOptions.nameKebabCase}'\\`, $items += \\`, { label: '${name}', link: '/guides/${enhancedOptions.nameKebabCase}' }\\` }`,\n );\n\n // Expose the generator from the SDK for known prefixes (ts# / py#)\n addSdkExport(tree, plugin.root, name, generatorSubDir, enhancedOptions);\n } else {\n // Local generator in a project other than nx-plugin-for-aws\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'local'),\n generatorDir,\n {\n ...enhancedOptions,\n },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n const indexPath = joinPathFragments(sourceRoot, 'index.ts');\n if (tree.exists(indexPath)) {\n // ESM projects require the explicit `.js` extension; `addStarExport`\n // strips it for CommonJS workspaces.\n await addStarExport(tree, indexPath, `./${generatorSubDir}/generator.js`);\n }\n\n addComponentGeneratorMetadata(\n tree,\n plugin.name,\n NX_GENERATOR_GENERATOR_INFO,\n joinPathFragments(srcDir, generatorSubDir),\n name,\n );\n }\n\n const factoryBasePath = `./${srcDir}/${generatorSubDir}`;\n\n // Update generators.json\n const generatorsJsonPath = joinPathFragments(plugin.root, 'generators.json');\n const generatorsJson = tree.exists(generatorsJsonPath)\n ? readJson(tree, generatorsJsonPath)\n : { generators: {} };\n // Metrics are only tracked within the @aws/nx-plugin repo. Reuse the existing\n // metric for a same-name re-run, otherwise allocate a new one.\n let metric: string | undefined;\n if (isNxPluginForAws) {\n const existingMetrics = Object.values(generatorsJson?.generators ?? {})\n .map((g: any) => g.metric)\n .filter((m): m is string => typeof m === 'string');\n metric =\n generatorsJson?.generators?.[name]?.metric ??\n (existingMetrics.length > 0 ? incrementMetric(existingMetrics) : 'g1');\n }\n writeJson(tree, generatorsJsonPath, {\n ...generatorsJson,\n generators: sortObjectKeys({\n ...generatorsJson?.generators,\n [name]: {\n factory: `${factoryBasePath}/generator`,\n schema: `${factoryBasePath}/schema.json`,\n description:\n description ?? 'TODO: Add short description of the generator',\n ...(isNxPluginForAws ? { metric } : {}),\n },\n }),\n });\n\n await addGeneratorMetricsIfApplicable(tree, [NX_GENERATOR_GENERATOR_INFO]);\n\n await formatFilesInSubtree(tree);\n\n return () =>\n installDependencies(tree, options.preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\n\nconst incrementMetric = (metrics: string[]): string => {\n const maxMetric = Math.max(...metrics.map((m) => Number(m.slice(1))));\n return `g${maxMetric + 1}`;\n};\n\n// Maps a generator name prefix to the SDK entry point that should re-export it\nconst SDK_EXPORT_PREFIXES: Record<string, string> = {\n 'ts#': 'ts',\n 'py#': 'py',\n};\n\n// Re-exports a generated generator from the matching SDK entry point so it is\n// available programmatically as part of @aws/nx-plugin's SDK\nconst addSdkExport = (\n tree: Tree,\n pluginRoot: string,\n name: string,\n generatorSubDir: string,\n options: { nameCamelCase: string; namePascalCase: string },\n): void => {\n const prefix = Object.keys(SDK_EXPORT_PREFIXES).find((p) =>\n name.startsWith(p),\n );\n if (!prefix) {\n return;\n }\n\n const sdkPath = joinPathFragments(\n pluginRoot,\n 'src',\n 'sdk',\n `${SDK_EXPORT_PREFIXES[prefix]}.ts`,\n );\n const generatorExport = `${options.nameCamelCase}Generator`;\n const schemaExport = `${options.namePascalCase}GeneratorSchema`;\n const moduleBase = `../${generatorSubDir}`;\n\n const contents = tree.exists(sdkPath) ? tree.read(sdkPath).toString() : '';\n // Idempotent: skip if this generator is already exported\n if (contents.includes(`${moduleBase}/generator`)) {\n return;\n }\n\n const block = `// ${options.namePascalCase} Generator\\nexport { ${generatorExport} } from '${moduleBase}/generator';\\nexport type { ${schemaExport} } from '${moduleBase}/schema';\\n`;\n\n const prefixContents = contents.trim()\n ? `${contents.replace(/\\s*$/, '')}\\n\\n`\n : '';\n tree.write(sdkPath, `${prefixContents}${block}`);\n};\n\nexport default tsNxGeneratorGenerator;\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","readJson","writeJson","camelCase","PackageJson","type","addStarExport","applyGritQL","formatFilesInSubtree","installDependencies","addGeneratorMetricsIfApplicable","esmVars","kebabCase","pascalCase","snakeCase","addComponentGeneratorMetadata","getGeneratorInfo","readProjectConfigurationUnqualified","sortObjectKeys","getRelativePathToRootByDirectory","configureTsProjectAsNxPlugin","NX_GENERATOR_GENERATOR_INFO","filename","tsNxGeneratorGenerator","tree","options","name","directory","project","pluginProject","description","plugin","sourceRoot","root","sourceRootParts","split","srcDir","length","generatorSubDir","generatorDir","rootPackageJson","exists","undefined","isNxPluginForAws","enhancedOptions","namePascalCase","nameCamelCase","nameKebabCase","nameUpperSnakeCase","toUpperCase","pathToProjectSourceRoot","dirname","overwriteStrategy","KeepExisting","Error","addSdkExport","indexPath","factoryBasePath","generatorsJsonPath","generatorsJson","generators","metric","existingMetrics","Object","values","map","g","filter","m","incrementMetric","factory","schema","preferInstallDependencies","languages","metrics","maxMetric","Math","max","Number","slice","SDK_EXPORT_PREFIXES","pluginRoot","prefix","keys","find","p","startsWith","sdkPath","generatorExport","schemaExport","moduleBase","contents","read","toString","includes","block","prefixContents","trim","replace","write"],"mappings":"AAAA;;;CAGC,GACD,SAEEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EACjBC,QAAQ,EAERC,SAAS,QACJ,aAAa;AACpB,OAAOC,eAAe,mBAAmB;AACzC,OAAOC,iBAAiB,6BAA6B;IAAEC,MAAM;AAAO,EAAE;AACtE,SAASC,aAAa,EAAEC,WAAW,QAAQ,qBAAkB;AAC7D,SAASC,oBAAoB,QAAQ,wBAAqB;AAC1D,SAASC,mBAAmB,QAAQ,yBAAsB;AAC1D,SAASC,+BAA+B,QAAQ,yBAAsB;AACtE,SAASC,OAAO,QAAQ,+BAA4B;AACpD,SAASC,SAAS,EAAEC,UAAU,EAAEC,SAAS,QAAQ,uBAAoB;AACrE,SACEC,6BAA6B,EAC7BC,gBAAgB,EAChBC,mCAAmC,QAC9B,oBAAiB;AACxB,SAASC,cAAc,QAAQ,wBAAqB;AACpD,SAASC,gCAAgC,QAAQ,uBAAoB;AACrE,SAASC,4BAA4B,QAAQ,wBAAqB;AAGlE,OAAO,MAAMC,8BAA8BL,iBACzC,YAAYM,QAAQ,EACpB;AAEF,OAAO,MAAMC,yBAAyB,OACpCC,MACAC;IAEA,MAAM,EAAEC,IAAI,EAAEC,SAAS,EAAEC,SAASC,aAAa,EAAEC,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A,OACA,GAAGD,mBAAmB,CAACE,OAAO,CAAC,GAAG,CAAC;IAErC,MAAMM,kBAAkB,GAAG/D,QAAQqB,aAAa,CAAC,SAAS,CAAC;IAC3D,MAAM2C,eAAe,GAAGhE,QAAQoB,cAAc,CAAC,eAAe,CAAC;IAC/D,MAAM6C,aAAa,CAAC,GAAG,EAAEpD,iBAAiB;IAE1C,MAAMqD,WAAWnE,KAAKiB,MAAM,CAAC8C,WAAW/D,KAAKoE,IAAI,CAACL,SAASM,QAAQ,KAAK;IACxE,yDAAyD;IACzD,IAAIF,SAASG,QAAQ,CAAC,GAAGJ,WAAW,UAAU,CAAC,GAAG;QAChD;IACF;IAEA,MAAMK,QAAQ,CAAC,GAAG,EAAEtE,QAAQoB,cAAc,CAAC,qBAAqB,EAAE2C,gBAAgB,SAAS,EAAEE,WAAW,4BAA4B,EAAED,aAAa,SAAS,EAAEC,WAAW,WAAW,CAAC;IAErL,MAAMM,iBAAiBL,SAASM,IAAI,KAChC,GAAGN,SAASO,OAAO,CAAC,QAAQ,IAAI,IAAI,CAAC,GACrC;IACJ1E,KAAK2E,KAAK,CAACZ,SAAS,GAAGS,iBAAiBD,OAAO;AACjD;AAEA,eAAexE,uBAAuB"}
@@ -1,9 +1,9 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- import { registerCreateWorkspaceCommandTool } from './tools/create-workspace-command.js';
3
- import { registerGeneralGuidanceTool } from './tools/general-guidance.js';
4
- import { registerListGeneratorsTool } from './tools/list-generators.js';
5
- import { registerGeneratorGuideTool } from './tools/generator-guide.js';
6
- import { getPackageName } from './utils.js';
2
+ import { registerCreateWorkspaceCommandTool } from './tools/create-workspace-command<% if (esm) { %>.js<% } %>';
3
+ import { registerGeneralGuidanceTool } from './tools/general-guidance<% if (esm) { %>.js<% } %>';
4
+ import { registerListGeneratorsTool } from './tools/list-generators<% if (esm) { %>.js<% } %>';
5
+ import { registerGeneratorGuideTool } from './tools/generator-guide<% if (esm) { %>.js<% } %>';
6
+ import { getPackageName } from './utils<% if (esm) { %>.js<% } %>';
7
7
 
8
8
  /**
9
9
  * Create the MCP Server
@@ -1,7 +1,7 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { z } from 'zod';
3
- import { PackageManagerSchema } from '../schema.js';
4
- import { buildCreateCommand, buildInstallCommand, getPackageName } from '../utils.js';
3
+ import { PackageManagerSchema } from '../schema<% if (esm) { %>.js<% } %>';
4
+ import { buildCreateCommand, buildInstallCommand, getPackageName } from '../utils<% if (esm) { %>.js<% } %>';
5
5
 
6
6
  /**
7
7
  * Registers a tool which tells a model how to create an Nx workspace
@@ -16,7 +16,7 @@ export const registerGeneralGuidanceTool = (server: McpServer) => {
16
16
  {
17
17
  type: 'text' as const,
18
18
  text: fs.readFileSync(
19
- path.resolve(import.meta.dirname, '../resources/GENERAL_GUIDANCE.md'),
19
+ path.resolve(<% if (esm) { %>import.meta.dirname<% } else { %>__dirname<% } %>, '../resources/GENERAL_GUIDANCE.md'),
20
20
  'utf-8',
21
21
  ),
22
22
  },
@@ -1,7 +1,7 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { z } from 'zod';
3
- import { renderGeneratorInfo, listGenerators } from '../utils.js';
4
- import { PackageManagerSchema } from '../schema.js';
3
+ import { renderGeneratorInfo, listGenerators } from '../utils<% if (esm) { %>.js<% } %>';
4
+ import { PackageManagerSchema } from '../schema<% if (esm) { %>.js<% } %>';
5
5
  import * as fs from 'fs';
6
6
  import * as path from 'path';
7
7
 
@@ -1,6 +1,6 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
- import { PackageManagerSchema } from '../schema.js';
3
- import { renderGeneratorInfo, listGenerators } from '../utils.js';
2
+ import { PackageManagerSchema } from '../schema<% if (esm) { %>.js<% } %>';
3
+ import { renderGeneratorInfo, listGenerators } from '../utils<% if (esm) { %>.js<% } %>';
4
4
 
5
5
  /**
6
6
  * Registers a tool which lists details about the available generators