@aws/nx-plugin 1.0.0-rc.96 → 1.0.0-rc.97

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 (159) hide show
  1. package/migrations.json +33 -3
  2. package/package.json +1 -1
  3. package/src/agentcore-gateway/__snapshots__/generator.spec.ts.snap +1 -1
  4. package/src/agentcore-gateway/generator.js +6 -0
  5. package/src/agentcore-gateway/generator.js.map +1 -1
  6. package/src/agentcore-gateway/react-connection/__snapshots__/generator.spec.ts.snap +4 -1
  7. package/src/agentcore-harness/__snapshots__/generator.spec.ts.snap +68 -4
  8. package/src/agentcore-harness/generator.js +6 -0
  9. package/src/agentcore-harness/generator.js.map +1 -1
  10. package/src/connection/gateway-runtime-config.js +1 -1
  11. package/src/connection/gateway-runtime-config.js.map +1 -1
  12. package/src/infra/app/__snapshots__/generator.spec.ts.snap +6 -6
  13. package/src/infra/app/generator.js +34 -7
  14. package/src/infra/app/generator.js.map +1 -1
  15. package/src/init/generator.d.ts +1 -1
  16. package/src/init/generator.js +8 -6
  17. package/src/init/generator.js.map +1 -1
  18. package/src/init/schema.d.js.map +1 -1
  19. package/src/init/schema.d.ts +1 -0
  20. package/src/init/schema.json +5 -0
  21. package/src/mcp-server/server.js +2 -0
  22. package/src/mcp-server/server.js.map +1 -1
  23. package/src/mcp-server/tools/best-practices.d.ts +28 -0
  24. package/src/mcp-server/tools/best-practices.js +43 -0
  25. package/src/mcp-server/tools/best-practices.js.map +1 -0
  26. package/src/mcp-server/tools/general-guidance.d.ts +1 -1
  27. package/src/mcp-server/tools/general-guidance.js +13 -4
  28. package/src/mcp-server/tools/general-guidance.js.map +1 -1
  29. package/src/migrations/latest/checkov-scan-cache-inputs/metadata.json +3 -0
  30. package/src/migrations/latest/checkov-scan-cache-inputs/migration.d.ts +6 -0
  31. package/src/migrations/latest/checkov-scan-cache-inputs/migration.js +58 -0
  32. package/src/migrations/latest/checkov-scan-cache-inputs/migration.js.map +1 -0
  33. package/src/migrations/latest/gateway-url-accessor/__snapshots__/migration.spec.ts.snap +84 -0
  34. package/src/migrations/latest/gateway-url-accessor/metadata.json +3 -0
  35. package/src/migrations/latest/gateway-url-accessor/migration.d.ts +6 -0
  36. package/src/migrations/latest/gateway-url-accessor/migration.js +94 -0
  37. package/src/migrations/latest/gateway-url-accessor/migration.js.map +1 -0
  38. package/src/migrations/latest/infra-deploy-express-mode/metadata.json +1 -1
  39. package/src/migrations/latest/infra-deploy-express-mode/migration.js +26 -28
  40. package/src/migrations/latest/infra-deploy-express-mode/migration.js.map +1 -1
  41. package/src/migrations/latest/py-lambda-powertools-context/metadata.json +3 -0
  42. package/src/migrations/latest/py-lambda-powertools-context/migration.d.ts +6 -0
  43. package/src/migrations/latest/py-lambda-powertools-context/migration.js +58 -0
  44. package/src/migrations/latest/py-lambda-powertools-context/migration.js.map +1 -0
  45. package/src/migrations/latest/script-project-quality-gates/metadata.json +3 -0
  46. package/src/migrations/latest/script-project-quality-gates/migration.d.ts +6 -0
  47. package/src/migrations/latest/script-project-quality-gates/migration.js +53 -0
  48. package/src/migrations/latest/script-project-quality-gates/migration.js.map +1 -0
  49. package/src/migrations/latest/smithy-extension-trait-aliases/__snapshots__/migration.spec.ts.snap +25 -0
  50. package/src/migrations/latest/smithy-extension-trait-aliases/metadata.json +3 -0
  51. package/src/migrations/latest/smithy-extension-trait-aliases/migration.d.ts +28 -0
  52. package/src/migrations/latest/smithy-extension-trait-aliases/migration.js +75 -0
  53. package/src/migrations/latest/smithy-extension-trait-aliases/migration.js.map +1 -0
  54. package/src/migrations/latest/terraform-validate-without-backend/metadata.json +3 -0
  55. package/src/migrations/latest/terraform-validate-without-backend/migration.d.ts +6 -0
  56. package/src/migrations/latest/terraform-validate-without-backend/migration.js +84 -0
  57. package/src/migrations/latest/terraform-validate-without-backend/migration.js.map +1 -0
  58. package/src/preset/generator.js +4 -25
  59. package/src/preset/generator.js.map +1 -1
  60. package/src/py/agent/a2a-connection/generator.d.ts +1 -1
  61. package/src/py/agent/gateway-connection/generator.d.ts +1 -1
  62. package/src/py/agent/mcp-connection/generator.d.ts +1 -1
  63. package/src/py/agent/react-connection/__snapshots__/generator.spec.ts.snap +4 -1
  64. package/src/py/dynamodb/__snapshots__/generator.spec.ts.snap +8 -10
  65. package/src/py/dynamodb/generator.js +34 -7
  66. package/src/py/dynamodb/generator.js.map +1 -1
  67. package/src/py/lambda-function/__snapshots__/generator.spec.ts.snap +2 -1
  68. package/src/py/lambda-function/files/handler/__lambdaFunctionSnakeCase__.py.template +2 -1
  69. package/src/py/project/schema.json +3 -1
  70. package/src/py/rdb/__snapshots__/generator.spec.ts.snap +28 -12
  71. package/src/py/rdb/files/Dockerfile.create-db-user.template +7 -3
  72. package/src/py/rdb/files/Dockerfile.migration.template +7 -3
  73. package/src/py/rdb/generator.js +29 -28
  74. package/src/py/rdb/generator.js.map +1 -1
  75. package/src/smithy/react-connection/files/model/extensions.smithy.template +3 -3
  76. package/src/smithy/ts/api/generator.js +7 -2
  77. package/src/smithy/ts/api/generator.js.map +1 -1
  78. package/src/terraform/project/generator.js +34 -10
  79. package/src/terraform/project/generator.js.map +1 -1
  80. package/src/trpc/backend/generator.js +7 -1
  81. package/src/trpc/backend/generator.js.map +1 -1
  82. package/src/trpc/react/generator.js +6 -0
  83. package/src/trpc/react/generator.js.map +1 -1
  84. package/src/ts/agent/generator.js +3 -3
  85. package/src/ts/agent/generator.js.map +1 -1
  86. package/src/ts/dynamodb/__snapshots__/generator.spec.ts.snap +2 -0
  87. package/src/ts/dynamodb/generator.js +30 -6
  88. package/src/ts/dynamodb/generator.js.map +1 -1
  89. package/src/ts/lib/biome.d.ts +15 -1
  90. package/src/ts/lib/biome.js +79 -63
  91. package/src/ts/lib/biome.js.map +1 -1
  92. package/src/ts/lib/generator.js +11 -7
  93. package/src/ts/lib/generator.js.map +1 -1
  94. package/src/ts/lib/ts-project-utils.d.ts +14 -0
  95. package/src/ts/lib/ts-project-utils.js +24 -0
  96. package/src/ts/lib/ts-project-utils.js.map +1 -1
  97. package/src/ts/mcp-server/generator.js +3 -3
  98. package/src/ts/mcp-server/generator.js.map +1 -1
  99. package/src/ts/rdb/__snapshots__/generator.spec.ts.snap +5 -0
  100. package/src/ts/rdb/files/Dockerfile.template +5 -0
  101. package/src/ts/rdb/generator.d.ts +8 -0
  102. package/src/ts/rdb/generator.js +28 -24
  103. package/src/ts/rdb/generator.js.map +1 -1
  104. package/src/ts/rdb/trpc-connection/__snapshots__/generator.spec.ts.snap +39 -0
  105. package/src/ts/rdb/trpc-connection/generator.js +13 -0
  106. package/src/ts/rdb/trpc-connection/generator.js.map +1 -1
  107. package/src/ts/react-website/agui/files/common/src/components/__agentNameKebabCase__-chat.tsx.template +9 -0
  108. package/src/ts/react-website/agui/files/common/src/hooks/useAgui__agentNameClassName__.tsx.template +4 -1
  109. package/src/ts/react-website/agui/generator.js +6 -2
  110. package/src/ts/react-website/agui/generator.js.map +1 -1
  111. package/src/ts/react-website/app/generator.js +3 -8
  112. package/src/ts/react-website/app/generator.js.map +1 -1
  113. package/src/utils/agent-connection/agent-connection.d.ts +2 -1
  114. package/src/utils/agent-connection/agent-connection.js +6 -1
  115. package/src/utils/agent-connection/agent-connection.js.map +1 -1
  116. package/src/utils/agent-core-constructs/files/cdk/app/agentcore-gateway/__nameKebabCase__/__nameKebabCase__.ts.template +11 -7
  117. package/src/utils/agent-core-constructs/files/cdk/core/agentcore-gateway/agentcore-gateway.ts.template +14 -6
  118. package/src/utils/agent-core-packaging.js +5 -5
  119. package/src/utils/agent-core-packaging.js.map +1 -1
  120. package/src/utils/api-constructs/api-constructs.d.ts +5 -0
  121. package/src/utils/api-constructs/api-constructs.js +8 -0
  122. package/src/utils/api-constructs/api-constructs.js.map +1 -1
  123. package/src/utils/api-constructs/files/cdk/app/apis/http/__apiNameKebabCase__.ts.template +4 -2
  124. package/src/utils/api-constructs/files/cdk/app/apis/rest/__apiNameKebabCase__.ts.template +4 -2
  125. package/src/utils/ast.d.ts +10 -0
  126. package/src/utils/ast.js +33 -0
  127. package/src/utils/ast.js.map +1 -1
  128. package/src/utils/docker.d.ts +11 -0
  129. package/src/utils/docker.js +16 -3
  130. package/src/utils/docker.js.map +1 -1
  131. package/src/utils/dynamodb-config.d.ts +48 -0
  132. package/src/utils/dynamodb-config.js +44 -0
  133. package/src/utils/dynamodb-config.js.map +1 -0
  134. package/src/utils/dynamodb-constructs/files/cdk/app/dynamodb/__nameKebabCase__.ts.template +8 -4
  135. package/src/utils/git-secrets.d.ts +28 -0
  136. package/src/utils/git-secrets.js +66 -0
  137. package/src/utils/git-secrets.js.map +1 -0
  138. package/src/utils/init.js +7 -6
  139. package/src/utils/init.js.map +1 -1
  140. package/src/utils/local-project-dependency.d.ts +28 -0
  141. package/src/utils/local-project-dependency.js +40 -0
  142. package/src/utils/local-project-dependency.js.map +1 -0
  143. package/src/utils/nx.d.ts +14 -0
  144. package/src/utils/nx.js +30 -0
  145. package/src/utils/nx.js.map +1 -1
  146. package/src/utils/rdb-constructs/files/cdk/app/dbs/__nameKebabCase__.ts.template +11 -6
  147. package/src/utils/script-project-targets.d.ts +26 -0
  148. package/src/utils/script-project-targets.js +75 -0
  149. package/src/utils/script-project-targets.js.map +1 -0
  150. package/src/utils/versions.d.ts +3 -0
  151. package/src/utils/versions.js +7 -0
  152. package/src/utils/versions.js.map +1 -1
  153. package/src/utils/website-constructs/files/cdk/app/static-websites/__websiteNameKebabCase__.ts.template +8 -4
  154. package/src/py/dynamodb/files/__name__/__init__.py.template +0 -6
  155. package/src/py/dynamodb/files/__name__/entities/__init__.py.template +0 -4
  156. package/src/py/dynamodb/files/config.json.template +0 -24
  157. package/src/ts/dynamodb/files/config.json.template +0 -24
  158. package/src/ts/dynamodb/files/src/entities/index.ts.template +0 -1
  159. package/src/ts/dynamodb/files/src/index.ts.template +0 -2
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../packages/nx-plugin/src/ts/react-website/app/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n detectPackageManager,\n generateFiles,\n joinPathFragments,\n names,\n OverwriteStrategy,\n readProjectConfiguration,\n removeDependenciesFromPackageJson,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { applicationGenerator } from '@nx/react';\nimport { relative, sep } from 'path';\nimport { addTsDependencies } from '../../../utils/add-dependencies.js';\nimport {\n addDestructuredImport,\n addSingleImport,\n appendToArrayViaGritQL,\n applyGritQL,\n} from '../../../utils/ast.js';\nimport {\n declareDependencies,\n ownedElsewhere,\n} from '../../../utils/declared-dependencies.js';\nimport { formatFilesInSubtree } from '../../../utils/format.js';\nimport { resolveIac } from '../../../utils/iac.js';\nimport { installDependencies } from '../../../utils/install.js';\nimport { addGeneratorMetricsIfApplicable } from '../../../utils/metrics.js';\nimport { kebabCase, toClassName, toKebabCase } from '../../../utils/names.js';\nimport { getNpmScopePrefix } from '../../../utils/npm-scope.js';\nimport {\n addGeneratorMetadata,\n getGeneratorInfo,\n type NxGeneratorInfo,\n} from '../../../utils/nx.js';\nimport { sortObjectKeys } from '../../../utils/object.js';\nimport { getRelativePathToRoot } from '../../../utils/paths.js';\nimport { getPackageManagerDisplayCommands } from '../../../utils/pkg-manager.js';\nimport { assignPort } from '../../../utils/port.js';\nimport {\n SHARED_CONSTRUCTS_DEPENDENCIES,\n sharedConstructsGenerator,\n} from '../../../utils/shared-constructs.js';\nimport {\n type IacMetadata,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n TERRAFORM_WEBSITE_RUNTIME_CONFIG_FILE,\n} from '../../../utils/shared-constructs-constants.js';\nimport {\n addSharedShadcnDependency,\n SHADCN_DEPENDENCIES,\n sharedShadcnGenerator,\n} from '../../../utils/shared-shadcn.js';\nimport { withVersions } from '../../../utils/versions.js';\nimport {\n addWebsiteInfra,\n WEBSITE_CONSTRUCTS_PY_DEPENDENCIES,\n} from '../../../utils/website-constructs/website-constructs.js';\nimport {\n configureTsProject,\n TS_PROJECT_DEPENDENCIES,\n} from '../../lib/ts-project-utils.js';\nimport { VITEST_DEPENDENCIES } from '../../lib/vitest.js';\n// typescript factory imports removed — now using GritQL for vite config transforms\nimport type {\n TsReactWebsiteGeneratorSchema,\n WebsiteInfraOption,\n} from './schema';\n\n/** The metadata this generator records, which its predicates read. */\nexport interface TsReactWebsiteMetadata extends IacMetadata {\n readonly ux: UxOption;\n readonly framework: string;\n readonly infra: WebsiteInfraOption;\n readonly tailwind: boolean;\n readonly tanstackRouter: boolean;\n}\n\n// Each entry names the branch it belongs to, so the same declaration drives both\n// adding and the version sync.\nexport const DEPENDENCIES = declareDependencies<TsReactWebsiteMetadata>()({\n ts: [\n { name: 'react' },\n { name: 'react-dom' },\n // Build/test tooling imported only from vite.config.mts stays at the root.\n { name: '@nx/react', dev: true, root: true },\n { name: '@vitest/ui', dev: true, root: true },\n {\n name: '@cloudscape-design/components',\n when: (m) => m.ux === 'cloudscape',\n },\n {\n name: '@cloudscape-design/board-components',\n when: (m) => m.ux === 'cloudscape',\n },\n {\n name: '@cloudscape-design/global-styles',\n when: (m) => m.ux === 'cloudscape',\n },\n // Shared shadcn components live in the common/shadcn package, but the\n // website's own generated components (e.g. the tanstack-router sidebar)\n // import lucide-react directly, so the website must declare it.\n {\n name: 'lucide-react',\n when: (m) => m.ux === 'shadcn' && m.tanstackRouter,\n },\n { name: 'tailwindcss', when: (m) => m.tailwind },\n {\n name: '@tailwindcss/vite',\n when: (m) => m.tailwind,\n dev: true,\n root: true,\n },\n { name: '@tanstack/react-router', when: (m) => m.tanstackRouter },\n {\n name: '@tanstack/router-plugin',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/router-generator',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/virtual-file-routes',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/router-utils',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n // Declared for its pinned version, which goes into npm's `overrides` below.\n { name: 'express', versionOnly: true },\n ...ownedElsewhere(TS_PROJECT_DEPENDENCIES),\n ...ownedElsewhere(SHADCN_DEPENDENCIES),\n ...ownedElsewhere(VITEST_DEPENDENCIES),\n ...ownedElsewhere(SHARED_CONSTRUCTS_DEPENDENCIES),\n ],\n py: ownedElsewhere(WEBSITE_CONSTRUCTS_PY_DEPENDENCIES),\n});\n\nexport const SUPPORTED_UX_PROVIDERS = ['none', 'cloudscape', 'shadcn'] as const;\n\nexport type UxOption = (typeof SUPPORTED_UX_PROVIDERS)[number];\n\nexport type Ux = UxOption;\n\nexport const REACT_WEBSITE_APP_GENERATOR_INFO: NxGeneratorInfo =\n getGeneratorInfo(import.meta.filename);\n\nexport async function tsReactWebsiteGenerator(\n tree: Tree,\n schema: TsReactWebsiteGeneratorSchema,\n) {\n const tailwind = schema.tailwind ?? true;\n const tanstackRouter = schema.tanstackRouter ?? true;\n const ux: Ux = schema.ux ?? 'shadcn';\n if (ux === 'shadcn' && !tailwind) {\n throw new Error('Shadcn requires TailwindCSS to be enabled.');\n }\n const npmScopePrefix = getNpmScopePrefix(tree);\n const scopeAlias = npmScopePrefix;\n const websiteNameClassName = toClassName(schema.name);\n const websiteNameKebabCase = toKebabCase(schema.name);\n const fullyQualifiedName = `${npmScopePrefix}${websiteNameKebabCase}`;\n // NB: interactive nx generator cli can pass empty string\n const websiteContentPath = joinPathFragments(\n schema.directory || '.',\n schema.subDirectory || websiteNameKebabCase,\n );\n\n const projectAlreadyExists = tree.exists(\n joinPathFragments(websiteContentPath, 'project.json'),\n );\n\n // TODO: consider exposing and supporting e2e tests\n const e2eTestRunner = 'none';\n\n if (!projectAlreadyExists) {\n await applicationGenerator(tree, {\n ...schema,\n name: fullyQualifiedName,\n directory: websiteContentPath,\n routing: false,\n e2eTestRunner,\n linter: 'none',\n bundler: 'vite',\n unitTestRunner: 'vitest',\n useProjectJson: true,\n style: 'css',\n // Register the @nx/vite and @nx/vitest plugins so build/serve/test\n // targets are inferred rather than emitting deprecated executor targets.\n addPlugin: true,\n });\n\n // Pin the inferred target names. The vite production build is exposed as\n // `bundle` (which produces the deployable artifact), leaving `build` as an\n // aggregator over lint/compile/test/bundle. vite's own typecheck is dropped\n // in favour of the tsc `compile`.\n updateJson(tree, 'nx.json', (nxJson) => {\n for (const plugin of nxJson.plugins ?? []) {\n if (typeof plugin === 'string') continue;\n if (plugin.plugin === '@nx/vite/plugin') {\n plugin.options = {\n ...plugin.options,\n buildTargetName: 'bundle',\n // Map both of vite's inferred dev-server targets onto `serve` so the\n // plugin doesn't emit a separate `dev`; we author our own `dev`\n // below running the local-dev vite mode.\n serveTargetName: 'serve',\n devTargetName: 'serve',\n previewTargetName: 'preview',\n serveStaticTargetName: 'serve-static',\n typecheckTargetName: 'vite:typecheck',\n };\n } else if (plugin.plugin === '@nx/vitest') {\n plugin.options = {\n ...plugin.options,\n testTargetName: 'test',\n };\n }\n }\n return nxJson;\n });\n\n // Replace with simpler sample source code\n tree.delete(joinPathFragments(websiteContentPath, 'src'));\n }\n\n const projectConfiguration = readProjectConfiguration(\n tree,\n fullyQualifiedName,\n );\n\n const targets = projectConfiguration.targets;\n\n // Each website gets its own explicit dev-server port. Vite itself already\n // auto-increments past a port already in use, so two websites don't actually\n // collide — but which port each one lands on then depends on start order and\n // can't be known ahead of time. An explicit, per-project port is what lets\n // the Cognito callback URL allow-list (added when auth is configured) be\n // computed deterministically instead.\n const port = assignPort(tree, projectConfiguration, 4200);\n // @nx/react's vite config defaults to 4200 for the dev server and 4300 for\n // preview; keep that +100 relationship so the pair stays predictable.\n const previewPort = port + 100;\n\n const infra = schema.infra ?? 'cloudfront-s3';\n\n // Configure load-runtime-config target based on IaC provider (only when infra is not none)\n const iac = infra !== 'none' ? await resolveIac(tree, schema.iac) : undefined;\n\n if (iac === 'cdk') {\n targets['load-runtime-config'] = {\n executor: 'nx:run-commands',\n metadata: {\n description: `Load runtime config from your deployed stack for dev purposes. You must set your AWS CLI credentials whilst calling '${getPackageManagerDisplayCommands().exec} nx load-runtime-config ${fullyQualifiedName}'`,\n },\n options: {\n command: `aws s3 cp s3://\\`aws cloudformation describe-stacks --query \"Stacks[?starts_with(StackName, '${kebabCase(npmScopePrefix)}-')][].Outputs[] | [?contains(OutputKey, '${websiteNameClassName}WebsiteBucketName')].OutputValue\" --output text\\`/runtime-config.json \"{projectRoot}/public/runtime-config.json\"`,\n },\n };\n } else if (iac === 'terraform') {\n targets['load-runtime-config'] = {\n executor: 'nx:run-commands',\n metadata: {\n description:\n \"Load runtime config from most recently applied terraform env for dev purposes. Copies the runtime config from the Terraform dist directory to the website's public directory.\",\n },\n options: {\n command:\n 'node -e \"const fs=require(\\'fs\\');fs.mkdirSync(process.env.DEST_DIR,{recursive:true});fs.copyFileSync(process.env.SRC_FILE,process.env.DEST_FILE);\"',\n env: {\n SRC_FILE: TERRAFORM_WEBSITE_RUNTIME_CONFIG_FILE,\n DEST_DIR: `{projectRoot}/public`,\n DEST_FILE: `{projectRoot}/public/runtime-config.json`,\n },\n },\n };\n }\n\n if (!projectAlreadyExists) {\n targets['compile'] = {\n // `tsc` needs its dependencies' declarations, which `compile` emits — not\n // their lint or test results.\n dependsOn: ['^compile'],\n executor: 'nx:run-commands',\n outputs: ['{workspaceRoot}/dist/{projectRoot}/tsc'],\n options: {\n command: 'tsc --build tsconfig.app.json',\n cwd: '{projectRoot}',\n },\n };\n // bundle is the @nx/vite/plugin inferred `vite build` (writing to the\n // bundle dir configured in vite.config) — it produces the deployable\n // artifact. build aggregates lint/compile/test/bundle.\n targets['build'] = {\n dependsOn: ['lint', 'compile', 'test', 'bundle'],\n };\n targets['assemble'] = {\n dependsOn: ['compile', 'bundle'],\n };\n\n // Run the website and its connected dependencies locally. Mirrors the\n // inferred `serve` target but with the local-dev vite mode.\n targets['dev'] = {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n command: 'vite --mode local-dev',\n cwd: '{projectRoot}',\n },\n };\n }\n\n projectConfiguration.targets = sortObjectKeys(targets);\n\n updateProjectConfiguration(tree, fullyQualifiedName, projectConfiguration);\n\n // Recorded here and read by the declaration's predicates, so the packages\n // added below are exactly the ones the version sync will own.\n const metadata: TsReactWebsiteMetadata = {\n ux,\n framework: 'react',\n infra,\n tailwind,\n tanstackRouter,\n // Undefined when no infrastructure was generated, so neither provider's\n // packages were added.\n ...(iac ? { iac } : {}),\n };\n addGeneratorMetadata(\n tree,\n projectConfiguration.name,\n REACT_WEBSITE_APP_GENERATOR_INFO,\n metadata,\n );\n\n await configureTsProject(\n tree,\n {\n dir: websiteContentPath,\n fullyQualifiedName,\n },\n DEPENDENCIES,\n );\n\n if (ux === 'shadcn') {\n await sharedShadcnGenerator(tree, DEPENDENCIES);\n addSharedShadcnDependency(tree, websiteContentPath);\n }\n\n if (iac) {\n await sharedConstructsGenerator(\n tree,\n {\n iac,\n },\n DEPENDENCIES,\n );\n\n await addWebsiteInfra(tree, {\n iac,\n websiteProjectName: fullyQualifiedName,\n scopeAlias,\n websiteContentPath: joinPathFragments('dist', websiteContentPath),\n websiteNameKebabCase,\n websiteNameClassName,\n });\n }\n\n const projectConfig = readProjectConfiguration(tree, fullyQualifiedName);\n const libraryRoot = projectConfig.root;\n const sharedShadcnStylesImport = relative(\n joinPathFragments(libraryRoot, 'src'),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n 'src',\n 'styles',\n 'globals.css',\n ),\n )\n .split(sep)\n .join('/');\n const sharedShadcnTsconfigRef = relative(\n joinPathFragments(tree.root, websiteContentPath),\n joinPathFragments(\n tree.root,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n 'tsconfig.json',\n ),\n )\n .split(sep)\n .join('/');\n const templateOptions = {\n ...schema,\n fullyQualifiedName,\n pkgMgrCmd: getPackageManagerDisplayCommands().exec,\n tailwind,\n tanstackRouter,\n scopeAlias,\n sharedShadcnStylesImport,\n };\n tree.delete(joinPathFragments(libraryRoot, 'src', 'app'));\n const appCommonTemplatePath = joinPathFragments(\n import.meta.dirname,\n './files/app/common',\n );\n const appTemplatePath = joinPathFragments(\n import.meta.dirname,\n `./files/app/${ux.toLowerCase()}`,\n );\n\n generateFiles(\n tree, // the virtual file system\n appCommonTemplatePath, // path to the file templates\n libraryRoot, // destination path of the files\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree, // the virtual file system\n appTemplatePath, // path to the file templates\n libraryRoot, // destination path of the files\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n if (tanstackRouter) {\n const routerCommonTemplatePath = joinPathFragments(\n import.meta.dirname,\n './files/tanstack-router/common',\n );\n const routerTemplatePath = joinPathFragments(\n import.meta.dirname,\n `./files/tanstack-router/${ux.toLowerCase()}`,\n );\n\n generateFiles(\n tree,\n routerCommonTemplatePath,\n libraryRoot,\n templateOptions,\n {\n // User-editable source (and the TanStack-managed route tree) - preserve on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree,\n routerTemplatePath,\n libraryRoot,\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n tree.delete(joinPathFragments(websiteContentPath, 'src', 'app.tsx'));\n }\n\n if (e2eTestRunner !== 'none') {\n const e2eFullyQualifiedName = `${fullyQualifiedName}-e2e`;\n const e2eRoot = readProjectConfiguration(tree, e2eFullyQualifiedName).root;\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, `./files/e2e/${e2eTestRunner}`), // path to the file templates\n e2eRoot, // destination path of the files\n { ...schema, ...names(fullyQualifiedName) },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n await configureTsProject(\n tree,\n {\n fullyQualifiedName: e2eFullyQualifiedName,\n dir: e2eRoot,\n },\n DEPENDENCIES,\n );\n }\n const viteConfigPath = joinPathFragments(libraryRoot, 'vite.config.mts');\n\n if (tree.exists(viteConfigPath)) {\n // Add Tanstack Router import if enabled\n if (tanstackRouter) {\n await addDestructuredImport(\n tree,\n viteConfigPath,\n ['tanstackRouter'],\n '@tanstack/router-plugin/vite',\n );\n\n await addDestructuredImport(tree, viteConfigPath, ['resolve'], 'path');\n }\n\n // Add TailwindCSS import if enabled\n if (tailwind) {\n await addSingleImport(\n tree,\n viteConfigPath,\n 'tailwindcss',\n '@tailwindcss/vite',\n );\n }\n\n // Update build.outDir. The inferred `vite build` target writes here, so\n // point it at the bundle dir the website infrastructure consumes.\n const outDir = joinPathFragments(\n getRelativePathToRoot(tree, fullyQualifiedName),\n 'dist',\n websiteContentPath,\n 'bundle',\n );\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`build: { $bprops }\\` where { $bprops <: contains \\`outDir: $_\\` => \\`outDir: '${outDir}'\\` }`,\n );\n\n // Replace @nx/react's default dev-server port (4200) with the one assigned above.\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`server: { $sprops }\\` where { $sprops <: contains \\`port: $_\\` => \\`port: ${port}\\` }`,\n );\n\n // Likewise for the preview port (@nx/react's default is 4300), so `vite preview`\n // doesn't collide across websites either.\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`preview: { $pprops }\\` where { $pprops <: contains \\`port: $_\\` => \\`port: ${previewPort}\\` }`,\n );\n\n // Add plugins to the plugins array\n if (tanstackRouter) {\n // Prepend tanstackRouter (must be first plugin) — rewrite works for both single/multi-element\n await applyGritQL(\n tree,\n viteConfigPath,\n \"`plugins: [$items]` => `plugins: [tanstackRouter({ routesDirectory: resolve(import.meta.dirname, 'src/routes'), generatedRouteTree: resolve(import.meta.dirname, 'src/routeTree.gen.ts') }), $items]` where { $items <: within `defineConfig($_)`, $items <: not contains `tanstackRouter` }\",\n );\n }\n\n if (tailwind) {\n await appendToArrayViaGritQL(\n tree,\n viteConfigPath,\n 'plugins:',\n 'tailwindcss()',\n { scope: 'defineConfig($_)' },\n );\n }\n\n // Use Vite's native tsconfig paths resolution (replaces vite-tsconfig-paths).\n // `dedupe` forces a single copy of react/react-dom into the bundle: each\n // project declares its own react dependency, so without this a workspace\n // library's hoisted copy can produce a second React instance and the\n // \"Invalid hook call\" runtime crash.\n await applyGritQL(\n tree,\n viteConfigPath,\n \"or { `defineConfig(() => ({ $props }))` where { $props <: not some `resolve: $_`, $props += `resolve: { tsconfigPaths: true, dedupe: ['react', 'react-dom'] }` }, `defineConfig({ $props })` where { $props <: not some `resolve: $_`, $props += `resolve: { tsconfigPaths: true, dedupe: ['react', 'react-dom'] }` } }\",\n );\n\n // Add define: { global: {} } to the config (handles both callback and direct forms)\n await applyGritQL(\n tree,\n viteConfigPath,\n 'or { `defineConfig(() => ({ $props }))` where { $props <: not contains `define`, $props += `define: { global: {} }` }, `defineConfig({ $props })` where { $props <: not contains `define`, $props += `define: { global: {} }` } }',\n );\n }\n\n updateJson(\n tree,\n joinPathFragments(websiteContentPath, 'tsconfig.json'),\n (tsconfig) => ({\n ...tsconfig,\n compilerOptions: {\n ...tsconfig.compilerOptions,\n moduleResolution: 'Bundler',\n module: 'Preserve',\n },\n }),\n );\n const outDirToRootRelativePath = relative(\n joinPathFragments(tree.root, websiteContentPath),\n tree.root,\n );\n const distDir = joinPathFragments(\n outDirToRootRelativePath,\n 'dist',\n websiteContentPath,\n 'tsc',\n );\n updateJson(\n tree,\n joinPathFragments(websiteContentPath, 'tsconfig.app.json'),\n (tsconfig) => ({\n ...tsconfig,\n compilerOptions: {\n ...tsconfig.compilerOptions,\n outDir: distDir,\n tsBuildInfoFile: joinPathFragments(distDir, 'tsconfig.lib.tsbuildinfo'),\n lib: ['DOM'],\n },\n references:\n ux === 'shadcn'\n ? [\n ...(tsconfig.references ?? []).filter(\n (ref) => ref.path !== sharedShadcnTsconfigRef,\n ),\n {\n path: sharedShadcnTsconfigRef,\n },\n ]\n : tsconfig.references,\n }),\n );\n\n addTsDependencies(tree, DEPENDENCIES, { metadata, projectRoot: libraryRoot });\n\n // @nx/react declares an optional `express` peer on the major behind the one\n // vended here, for a module-federation dev-server this never runs. npm alone\n // fails the whole install on an optional peer it cannot satisfy, so it gets a\n // scoped override; the other package managers only warn.\n if (detectPackageManager() === 'npm') {\n updateJson(tree, 'package.json', (packageJson) => {\n packageJson.overrides = {\n ...packageJson.overrides,\n '@nx/react': {\n ...packageJson.overrides?.['@nx/react'],\n ...withVersions(DEPENDENCIES, ['express']),\n },\n };\n return packageJson;\n });\n }\n\n // @nx/react's applicationGenerator seeds react/react-dom into the root\n // manifest. The website now declares its own pinned versions, so drop the\n // root copies: without catalogs (npm) the root's floating range resolves to\n // a different version than the website's pin, installing a second React and\n // producing the \"Invalid hook call\" runtime crash.\n removeDependenciesFromPackageJson(tree, ['react', 'react-dom'], []);\n\n await addGeneratorMetricsIfApplicable(tree, [\n REACT_WEBSITE_APP_GENERATOR_INFO,\n ]);\n\n // TanStack Router's vite plugin owns this website's route tree and rewrites it\n // in its own (unformatted) shape whenever the config is loaded — including when\n // Nx computes the project graph — so formatting it here would only make\n // generation non-idempotent. The vended biome config excludes `**/*.gen.*`, so\n // the workspace's own `format` target leaves it alone too.\n await formatFilesInSubtree(tree, undefined, {\n ignore: tanstackRouter\n ? [joinPathFragments(libraryRoot, 'src', 'routeTree.gen.ts')]\n : [],\n });\n // The generated vite.config.mts imports these, and Nx's inferred `@nx/vite`\n // plugin loads that config when computing the project graph — so they must be\n // installed even if the caller would otherwise prefer to defer.\n return () =>\n installDependencies(tree, schema.preferInstallDependencies, {\n languages: ['typescript'],\n ensureResolvable: [\n ...(tailwind ? (['@tailwindcss/vite'] as const) : []),\n ...(tanstackRouter ? (['@tanstack/router-plugin'] as const) : []),\n ],\n });\n}\nexport default tsReactWebsiteGenerator;\n"],"names":["detectPackageManager","generateFiles","joinPathFragments","names","OverwriteStrategy","readProjectConfiguration","removeDependenciesFromPackageJson","updateJson","updateProjectConfiguration","applicationGenerator","relative","sep","addTsDependencies","addDestructuredImport","addSingleImport","appendToArrayViaGritQL","applyGritQL","declareDependencies","ownedElsewhere","formatFilesInSubtree","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","kebabCase","toClassName","toKebabCase","getNpmScopePrefix","addGeneratorMetadata","getGeneratorInfo","sortObjectKeys","getRelativePathToRoot","getPackageManagerDisplayCommands","assignPort","SHARED_CONSTRUCTS_DEPENDENCIES","sharedConstructsGenerator","PACKAGES_DIR","SHARED_SHADCN_DIR","TERRAFORM_WEBSITE_RUNTIME_CONFIG_FILE","addSharedShadcnDependency","SHADCN_DEPENDENCIES","sharedShadcnGenerator","withVersions","addWebsiteInfra","WEBSITE_CONSTRUCTS_PY_DEPENDENCIES","configureTsProject","TS_PROJECT_DEPENDENCIES","VITEST_DEPENDENCIES","DEPENDENCIES","ts","name","dev","root","when","m","ux","tanstackRouter","tailwind","versionOnly","py","SUPPORTED_UX_PROVIDERS","REACT_WEBSITE_APP_GENERATOR_INFO","filename","tsReactWebsiteGenerator","tree","schema","Error","npmScopePrefix","scopeAlias","websiteNameClassName","websiteNameKebabCase","fullyQualifiedName","websiteContentPath","directory","subDirectory","projectAlreadyExists","exists","e2eTestRunner","routing","linter","bundler","unitTestRunner","useProjectJson","style","addPlugin","nxJson","plugin","plugins","options","buildTargetName","serveTargetName","devTargetName","previewTargetName","serveStaticTargetName","typecheckTargetName","testTargetName","delete","projectConfiguration","targets","port","previewPort","infra","iac","undefined","executor","metadata","description","exec","command","env","SRC_FILE","DEST_DIR","DEST_FILE","dependsOn","outputs","cwd","continuous","framework","dir","websiteProjectName","projectConfig","libraryRoot","sharedShadcnStylesImport","split","join","sharedShadcnTsconfigRef","templateOptions","pkgMgrCmd","appCommonTemplatePath","dirname","appTemplatePath","toLowerCase","overwriteStrategy","KeepExisting","routerCommonTemplatePath","routerTemplatePath","e2eFullyQualifiedName","e2eRoot","viteConfigPath","outDir","scope","tsconfig","compilerOptions","moduleResolution","module","outDirToRootRelativePath","distDir","tsBuildInfoFile","lib","references","filter","ref","path","projectRoot","packageJson","overrides","ignore","preferInstallDependencies","languages","ensureResolvable"],"mappings":"AAAA;;;CAGC,GACD,SACEA,oBAAoB,EACpBC,aAAa,EACbC,iBAAiB,EACjBC,KAAK,EACLC,iBAAiB,EACjBC,wBAAwB,EACxBC,iCAAiC,EAEjCC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAASC,oBAAoB,QAAQ,YAAY;AACjD,SAASC,QAAQ,EAAEC,GAAG,QAAQ,OAAO;AACrC,SAASC,iBAAiB,QAAQ,qCAAqC;AACvE,SACEC,qBAAqB,EACrBC,eAAe,EACfC,sBAAsB,EACtBC,WAAW,QACN,wBAAwB;AAC/B,SACEC,mBAAmB,EACnBC,cAAc,QACT,0CAA0C;AACjD,SAASC,oBAAoB,QAAQ,2BAA2B;AAChE,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SAASC,mBAAmB,QAAQ,4BAA4B;AAChE,SAASC,+BAA+B,QAAQ,4BAA4B;AAC5E,SAASC,SAAS,EAAEC,WAAW,EAAEC,WAAW,QAAQ,0BAA0B;AAC9E,SAASC,iBAAiB,QAAQ,8BAA8B;AAChE,SACEC,oBAAoB,EACpBC,gBAAgB,QAEX,uBAAuB;AAC9B,SAASC,cAAc,QAAQ,2BAA2B;AAC1D,SAASC,qBAAqB,QAAQ,0BAA0B;AAChE,SAASC,gCAAgC,QAAQ,gCAAgC;AACjF,SAASC,UAAU,QAAQ,yBAAyB;AACpD,SACEC,8BAA8B,EAC9BC,yBAAyB,QACpB,sCAAsC;AAC7C,SAEEC,YAAY,EACZC,iBAAiB,EACjBC,qCAAqC,QAChC,gDAAgD;AACvD,SACEC,yBAAyB,EACzBC,mBAAmB,EACnBC,qBAAqB,QAChB,kCAAkC;AACzC,SAASC,YAAY,QAAQ,6BAA6B;AAC1D,SACEC,eAAe,EACfC,kCAAkC,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ts/react-website/app/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n detectPackageManager,\n generateFiles,\n joinPathFragments,\n names,\n OverwriteStrategy,\n readProjectConfiguration,\n removeDependenciesFromPackageJson,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { applicationGenerator } from '@nx/react';\nimport { relative, sep } from 'path';\nimport { addTsDependencies } from '../../../utils/add-dependencies.js';\nimport {\n addDestructuredImport,\n addSingleImport,\n appendToArrayViaGritQL,\n applyGritQL,\n} from '../../../utils/ast.js';\nimport {\n declareDependencies,\n ownedElsewhere,\n} from '../../../utils/declared-dependencies.js';\nimport { formatFilesInSubtree } from '../../../utils/format.js';\nimport { resolveIac } from '../../../utils/iac.js';\nimport { installDependencies } from '../../../utils/install.js';\nimport { addGeneratorMetricsIfApplicable } from '../../../utils/metrics.js';\nimport { kebabCase, toClassName, toKebabCase } from '../../../utils/names.js';\nimport { getNpmScopePrefix } from '../../../utils/npm-scope.js';\nimport {\n addGeneratorMetadata,\n getGeneratorInfo,\n type NxGeneratorInfo,\n} from '../../../utils/nx.js';\nimport { sortObjectKeys } from '../../../utils/object.js';\nimport { getRelativePathToRoot } from '../../../utils/paths.js';\nimport { getPackageManagerDisplayCommands } from '../../../utils/pkg-manager.js';\nimport { assignPort } from '../../../utils/port.js';\nimport {\n SHARED_CONSTRUCTS_DEPENDENCIES,\n sharedConstructsGenerator,\n} from '../../../utils/shared-constructs.js';\nimport {\n type IacMetadata,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n TERRAFORM_WEBSITE_RUNTIME_CONFIG_FILE,\n} from '../../../utils/shared-constructs-constants.js';\nimport {\n addSharedShadcnDependency,\n SHADCN_DEPENDENCIES,\n sharedShadcnGenerator,\n} from '../../../utils/shared-shadcn.js';\nimport { withVersions } from '../../../utils/versions.js';\nimport {\n addWebsiteInfra,\n WEBSITE_CONSTRUCTS_PY_DEPENDENCIES,\n} from '../../../utils/website-constructs/website-constructs.js';\nimport {\n configureTsProject,\n mergeTsProjectDirReference,\n TS_PROJECT_DEPENDENCIES,\n} from '../../lib/ts-project-utils.js';\nimport { VITEST_DEPENDENCIES } from '../../lib/vitest.js';\n// typescript factory imports removed — now using GritQL for vite config transforms\nimport type {\n TsReactWebsiteGeneratorSchema,\n WebsiteInfraOption,\n} from './schema';\n\n/** The metadata this generator records, which its predicates read. */\nexport interface TsReactWebsiteMetadata extends IacMetadata {\n readonly ux: UxOption;\n readonly framework: string;\n readonly infra: WebsiteInfraOption;\n readonly tailwind: boolean;\n readonly tanstackRouter: boolean;\n}\n\n// Each entry names the branch it belongs to, so the same declaration drives both\n// adding and the version sync.\nexport const DEPENDENCIES = declareDependencies<TsReactWebsiteMetadata>()({\n ts: [\n { name: 'react' },\n { name: 'react-dom' },\n // Build/test tooling imported only from vite.config.mts stays at the root.\n { name: '@nx/react', dev: true, root: true },\n { name: '@vitest/ui', dev: true, root: true },\n {\n name: '@cloudscape-design/components',\n when: (m) => m.ux === 'cloudscape',\n },\n {\n name: '@cloudscape-design/board-components',\n when: (m) => m.ux === 'cloudscape',\n },\n {\n name: '@cloudscape-design/global-styles',\n when: (m) => m.ux === 'cloudscape',\n },\n // Shared shadcn components live in the common/shadcn package, but the\n // website's own generated components (e.g. the tanstack-router sidebar)\n // import lucide-react directly, so the website must declare it.\n {\n name: 'lucide-react',\n when: (m) => m.ux === 'shadcn' && m.tanstackRouter,\n },\n { name: 'tailwindcss', when: (m) => m.tailwind },\n {\n name: '@tailwindcss/vite',\n when: (m) => m.tailwind,\n dev: true,\n root: true,\n },\n { name: '@tanstack/react-router', when: (m) => m.tanstackRouter },\n {\n name: '@tanstack/router-plugin',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/router-generator',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/virtual-file-routes',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/router-utils',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n // Declared for its pinned version, which goes into npm's `overrides` below.\n { name: 'express', versionOnly: true },\n ...ownedElsewhere(TS_PROJECT_DEPENDENCIES),\n ...ownedElsewhere(SHADCN_DEPENDENCIES),\n ...ownedElsewhere(VITEST_DEPENDENCIES),\n ...ownedElsewhere(SHARED_CONSTRUCTS_DEPENDENCIES),\n ],\n py: ownedElsewhere(WEBSITE_CONSTRUCTS_PY_DEPENDENCIES),\n});\n\nexport const SUPPORTED_UX_PROVIDERS = ['none', 'cloudscape', 'shadcn'] as const;\n\nexport type UxOption = (typeof SUPPORTED_UX_PROVIDERS)[number];\n\nexport type Ux = UxOption;\n\nexport const REACT_WEBSITE_APP_GENERATOR_INFO: NxGeneratorInfo =\n getGeneratorInfo(import.meta.filename);\n\nexport async function tsReactWebsiteGenerator(\n tree: Tree,\n schema: TsReactWebsiteGeneratorSchema,\n) {\n const tailwind = schema.tailwind ?? true;\n const tanstackRouter = schema.tanstackRouter ?? true;\n const ux: Ux = schema.ux ?? 'shadcn';\n if (ux === 'shadcn' && !tailwind) {\n throw new Error('Shadcn requires TailwindCSS to be enabled.');\n }\n const npmScopePrefix = getNpmScopePrefix(tree);\n const scopeAlias = npmScopePrefix;\n const websiteNameClassName = toClassName(schema.name);\n const websiteNameKebabCase = toKebabCase(schema.name);\n const fullyQualifiedName = `${npmScopePrefix}${websiteNameKebabCase}`;\n // NB: interactive nx generator cli can pass empty string\n const websiteContentPath = joinPathFragments(\n schema.directory || '.',\n schema.subDirectory || websiteNameKebabCase,\n );\n\n const projectAlreadyExists = tree.exists(\n joinPathFragments(websiteContentPath, 'project.json'),\n );\n\n // TODO: consider exposing and supporting e2e tests\n const e2eTestRunner = 'none';\n\n if (!projectAlreadyExists) {\n await applicationGenerator(tree, {\n ...schema,\n name: fullyQualifiedName,\n directory: websiteContentPath,\n routing: false,\n e2eTestRunner,\n linter: 'none',\n bundler: 'vite',\n unitTestRunner: 'vitest',\n useProjectJson: true,\n style: 'css',\n // Register the @nx/vite and @nx/vitest plugins so build/serve/test\n // targets are inferred rather than emitting deprecated executor targets.\n addPlugin: true,\n });\n\n // Pin the inferred target names. The vite production build is exposed as\n // `bundle` (which produces the deployable artifact), leaving `build` as an\n // aggregator over lint/compile/test/bundle. vite's own typecheck is dropped\n // in favour of the tsc `compile`.\n updateJson(tree, 'nx.json', (nxJson) => {\n for (const plugin of nxJson.plugins ?? []) {\n if (typeof plugin === 'string') continue;\n if (plugin.plugin === '@nx/vite/plugin') {\n plugin.options = {\n ...plugin.options,\n buildTargetName: 'bundle',\n // Map both of vite's inferred dev-server targets onto `serve` so the\n // plugin doesn't emit a separate `dev`; we author our own `dev`\n // below running the local-dev vite mode.\n serveTargetName: 'serve',\n devTargetName: 'serve',\n previewTargetName: 'preview',\n serveStaticTargetName: 'serve-static',\n typecheckTargetName: 'vite:typecheck',\n };\n } else if (plugin.plugin === '@nx/vitest') {\n plugin.options = {\n ...plugin.options,\n testTargetName: 'test',\n };\n }\n }\n return nxJson;\n });\n\n // Replace with simpler sample source code\n tree.delete(joinPathFragments(websiteContentPath, 'src'));\n }\n\n const projectConfiguration = readProjectConfiguration(\n tree,\n fullyQualifiedName,\n );\n\n const targets = projectConfiguration.targets;\n\n // Each website gets its own explicit dev-server port. Vite itself already\n // auto-increments past a port already in use, so two websites don't actually\n // collide — but which port each one lands on then depends on start order and\n // can't be known ahead of time. An explicit, per-project port is what lets\n // the Cognito callback URL allow-list (added when auth is configured) be\n // computed deterministically instead.\n const port = assignPort(tree, projectConfiguration, 4200);\n // @nx/react's vite config defaults to 4200 for the dev server and 4300 for\n // preview; keep that +100 relationship so the pair stays predictable.\n const previewPort = port + 100;\n\n const infra = schema.infra ?? 'cloudfront-s3';\n\n // Configure load-runtime-config target based on IaC provider (only when infra is not none)\n const iac = infra !== 'none' ? await resolveIac(tree, schema.iac) : undefined;\n\n if (iac === 'cdk') {\n targets['load-runtime-config'] = {\n executor: 'nx:run-commands',\n metadata: {\n description: `Load runtime config from your deployed stack for dev purposes. You must set your AWS CLI credentials whilst calling '${getPackageManagerDisplayCommands().exec} nx load-runtime-config ${fullyQualifiedName}'`,\n },\n options: {\n command: `aws s3 cp s3://\\`aws cloudformation describe-stacks --query \"Stacks[?starts_with(StackName, '${kebabCase(npmScopePrefix)}-')][].Outputs[] | [?contains(OutputKey, '${websiteNameClassName}WebsiteBucketName')].OutputValue\" --output text\\`/runtime-config.json \"{projectRoot}/public/runtime-config.json\"`,\n },\n };\n } else if (iac === 'terraform') {\n targets['load-runtime-config'] = {\n executor: 'nx:run-commands',\n metadata: {\n description:\n \"Load runtime config from most recently applied terraform env for dev purposes. Copies the runtime config from the Terraform dist directory to the website's public directory.\",\n },\n options: {\n command:\n 'node -e \"const fs=require(\\'fs\\');fs.mkdirSync(process.env.DEST_DIR,{recursive:true});fs.copyFileSync(process.env.SRC_FILE,process.env.DEST_FILE);\"',\n env: {\n SRC_FILE: TERRAFORM_WEBSITE_RUNTIME_CONFIG_FILE,\n DEST_DIR: `{projectRoot}/public`,\n DEST_FILE: `{projectRoot}/public/runtime-config.json`,\n },\n },\n };\n }\n\n if (!projectAlreadyExists) {\n targets['compile'] = {\n // `tsc` needs its dependencies' declarations, which `compile` emits — not\n // their lint or test results.\n dependsOn: ['^compile'],\n executor: 'nx:run-commands',\n outputs: ['{workspaceRoot}/dist/{projectRoot}/tsc'],\n options: {\n command: 'tsc --build tsconfig.app.json',\n cwd: '{projectRoot}',\n },\n };\n // bundle is the @nx/vite/plugin inferred `vite build` (writing to the\n // bundle dir configured in vite.config) — it produces the deployable\n // artifact. build aggregates lint/compile/test/bundle.\n targets['build'] = {\n dependsOn: ['lint', 'compile', 'test', 'bundle'],\n };\n targets['assemble'] = {\n dependsOn: ['compile', 'bundle'],\n };\n\n // Run the website and its connected dependencies locally. Mirrors the\n // inferred `serve` target but with the local-dev vite mode.\n targets['dev'] = {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n command: 'vite --mode local-dev',\n cwd: '{projectRoot}',\n },\n };\n }\n\n projectConfiguration.targets = sortObjectKeys(targets);\n\n updateProjectConfiguration(tree, fullyQualifiedName, projectConfiguration);\n\n // Recorded here and read by the declaration's predicates, so the packages\n // added below are exactly the ones the version sync will own.\n const metadata: TsReactWebsiteMetadata = {\n ux,\n framework: 'react',\n infra,\n tailwind,\n tanstackRouter,\n // Undefined when no infrastructure was generated, so neither provider's\n // packages were added.\n ...(iac ? { iac } : {}),\n };\n addGeneratorMetadata(\n tree,\n projectConfiguration.name,\n REACT_WEBSITE_APP_GENERATOR_INFO,\n metadata,\n );\n\n await configureTsProject(\n tree,\n {\n dir: websiteContentPath,\n fullyQualifiedName,\n },\n DEPENDENCIES,\n );\n\n if (ux === 'shadcn') {\n await sharedShadcnGenerator(tree, DEPENDENCIES);\n addSharedShadcnDependency(tree, websiteContentPath);\n }\n\n if (iac) {\n await sharedConstructsGenerator(\n tree,\n {\n iac,\n },\n DEPENDENCIES,\n );\n\n await addWebsiteInfra(tree, {\n iac,\n websiteProjectName: fullyQualifiedName,\n scopeAlias,\n websiteContentPath: joinPathFragments('dist', websiteContentPath),\n websiteNameKebabCase,\n websiteNameClassName,\n });\n }\n\n const projectConfig = readProjectConfiguration(tree, fullyQualifiedName);\n const libraryRoot = projectConfig.root;\n const sharedShadcnStylesImport = relative(\n joinPathFragments(libraryRoot, 'src'),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n 'src',\n 'styles',\n 'globals.css',\n ),\n )\n .split(sep)\n .join('/');\n const sharedShadcnProjectRef = relative(\n joinPathFragments(tree.root, websiteContentPath),\n joinPathFragments(tree.root, PACKAGES_DIR, SHARED_SHADCN_DIR),\n )\n .split(sep)\n .join('/');\n const templateOptions = {\n ...schema,\n fullyQualifiedName,\n pkgMgrCmd: getPackageManagerDisplayCommands().exec,\n tailwind,\n tanstackRouter,\n scopeAlias,\n sharedShadcnStylesImport,\n };\n tree.delete(joinPathFragments(libraryRoot, 'src', 'app'));\n const appCommonTemplatePath = joinPathFragments(\n import.meta.dirname,\n './files/app/common',\n );\n const appTemplatePath = joinPathFragments(\n import.meta.dirname,\n `./files/app/${ux.toLowerCase()}`,\n );\n\n generateFiles(\n tree, // the virtual file system\n appCommonTemplatePath, // path to the file templates\n libraryRoot, // destination path of the files\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree, // the virtual file system\n appTemplatePath, // path to the file templates\n libraryRoot, // destination path of the files\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n if (tanstackRouter) {\n const routerCommonTemplatePath = joinPathFragments(\n import.meta.dirname,\n './files/tanstack-router/common',\n );\n const routerTemplatePath = joinPathFragments(\n import.meta.dirname,\n `./files/tanstack-router/${ux.toLowerCase()}`,\n );\n\n generateFiles(\n tree,\n routerCommonTemplatePath,\n libraryRoot,\n templateOptions,\n {\n // User-editable source (and the TanStack-managed route tree) - preserve on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree,\n routerTemplatePath,\n libraryRoot,\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n tree.delete(joinPathFragments(websiteContentPath, 'src', 'app.tsx'));\n }\n\n if (e2eTestRunner !== 'none') {\n const e2eFullyQualifiedName = `${fullyQualifiedName}-e2e`;\n const e2eRoot = readProjectConfiguration(tree, e2eFullyQualifiedName).root;\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, `./files/e2e/${e2eTestRunner}`), // path to the file templates\n e2eRoot, // destination path of the files\n { ...schema, ...names(fullyQualifiedName) },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n await configureTsProject(\n tree,\n {\n fullyQualifiedName: e2eFullyQualifiedName,\n dir: e2eRoot,\n },\n DEPENDENCIES,\n );\n }\n const viteConfigPath = joinPathFragments(libraryRoot, 'vite.config.mts');\n\n if (tree.exists(viteConfigPath)) {\n // Add Tanstack Router import if enabled\n if (tanstackRouter) {\n await addDestructuredImport(\n tree,\n viteConfigPath,\n ['tanstackRouter'],\n '@tanstack/router-plugin/vite',\n );\n\n await addDestructuredImport(tree, viteConfigPath, ['resolve'], 'path');\n }\n\n // Add TailwindCSS import if enabled\n if (tailwind) {\n await addSingleImport(\n tree,\n viteConfigPath,\n 'tailwindcss',\n '@tailwindcss/vite',\n );\n }\n\n // Update build.outDir. The inferred `vite build` target writes here, so\n // point it at the bundle dir the website infrastructure consumes.\n const outDir = joinPathFragments(\n getRelativePathToRoot(tree, fullyQualifiedName),\n 'dist',\n websiteContentPath,\n 'bundle',\n );\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`build: { $bprops }\\` where { $bprops <: contains \\`outDir: $_\\` => \\`outDir: '${outDir}'\\` }`,\n );\n\n // Replace @nx/react's default dev-server port (4200) with the one assigned above.\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`server: { $sprops }\\` where { $sprops <: contains \\`port: $_\\` => \\`port: ${port}\\` }`,\n );\n\n // Likewise for the preview port (@nx/react's default is 4300), so `vite preview`\n // doesn't collide across websites either.\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`preview: { $pprops }\\` where { $pprops <: contains \\`port: $_\\` => \\`port: ${previewPort}\\` }`,\n );\n\n // Add plugins to the plugins array\n if (tanstackRouter) {\n // Prepend tanstackRouter (must be first plugin) — rewrite works for both single/multi-element\n await applyGritQL(\n tree,\n viteConfigPath,\n \"`plugins: [$items]` => `plugins: [tanstackRouter({ routesDirectory: resolve(import.meta.dirname, 'src/routes'), generatedRouteTree: resolve(import.meta.dirname, 'src/routeTree.gen.ts') }), $items]` where { $items <: within `defineConfig($_)`, $items <: not contains `tanstackRouter` }\",\n );\n }\n\n if (tailwind) {\n await appendToArrayViaGritQL(\n tree,\n viteConfigPath,\n 'plugins:',\n 'tailwindcss()',\n { scope: 'defineConfig($_)' },\n );\n }\n\n // Use Vite's native tsconfig paths resolution (replaces vite-tsconfig-paths).\n // `dedupe` forces a single copy of react/react-dom into the bundle: each\n // project declares its own react dependency, so without this a workspace\n // library's hoisted copy can produce a second React instance and the\n // \"Invalid hook call\" runtime crash.\n await applyGritQL(\n tree,\n viteConfigPath,\n \"or { `defineConfig(() => ({ $props }))` where { $props <: not some `resolve: $_`, $props += `resolve: { tsconfigPaths: true, dedupe: ['react', 'react-dom'] }` }, `defineConfig({ $props })` where { $props <: not some `resolve: $_`, $props += `resolve: { tsconfigPaths: true, dedupe: ['react', 'react-dom'] }` } }\",\n );\n\n // Add define: { global: {} } to the config (handles both callback and direct forms)\n await applyGritQL(\n tree,\n viteConfigPath,\n 'or { `defineConfig(() => ({ $props }))` where { $props <: not contains `define`, $props += `define: { global: {} }` }, `defineConfig({ $props })` where { $props <: not contains `define`, $props += `define: { global: {} }` } }',\n );\n }\n\n updateJson(\n tree,\n joinPathFragments(websiteContentPath, 'tsconfig.json'),\n (tsconfig) => ({\n ...tsconfig,\n compilerOptions: {\n ...tsconfig.compilerOptions,\n moduleResolution: 'Bundler',\n module: 'Preserve',\n },\n }),\n );\n const outDirToRootRelativePath = relative(\n joinPathFragments(tree.root, websiteContentPath),\n tree.root,\n );\n const distDir = joinPathFragments(\n outDirToRootRelativePath,\n 'dist',\n websiteContentPath,\n 'tsc',\n );\n updateJson(\n tree,\n joinPathFragments(websiteContentPath, 'tsconfig.app.json'),\n (tsconfig) => ({\n ...tsconfig,\n compilerOptions: {\n ...tsconfig.compilerOptions,\n outDir: distDir,\n tsBuildInfoFile: joinPathFragments(distDir, 'tsconfig.lib.tsbuildinfo'),\n lib: ['DOM'],\n },\n references:\n ux === 'shadcn'\n ? mergeTsProjectDirReference(\n tsconfig.references,\n sharedShadcnProjectRef,\n )\n : tsconfig.references,\n }),\n );\n\n addTsDependencies(tree, DEPENDENCIES, { metadata, projectRoot: libraryRoot });\n\n // @nx/react declares an optional `express` peer on the major behind the one\n // vended here, for a module-federation dev-server this never runs. npm alone\n // fails the whole install on an optional peer it cannot satisfy, so it gets a\n // scoped override; the other package managers only warn.\n if (detectPackageManager() === 'npm') {\n updateJson(tree, 'package.json', (packageJson) => {\n packageJson.overrides = {\n ...packageJson.overrides,\n '@nx/react': {\n ...packageJson.overrides?.['@nx/react'],\n ...withVersions(DEPENDENCIES, ['express']),\n },\n };\n return packageJson;\n });\n }\n\n // @nx/react's applicationGenerator seeds react/react-dom into the root\n // manifest. The website now declares its own pinned versions, so drop the\n // root copies: without catalogs (npm) the root's floating range resolves to\n // a different version than the website's pin, installing a second React and\n // producing the \"Invalid hook call\" runtime crash.\n removeDependenciesFromPackageJson(tree, ['react', 'react-dom'], []);\n\n await addGeneratorMetricsIfApplicable(tree, [\n REACT_WEBSITE_APP_GENERATOR_INFO,\n ]);\n\n // TanStack Router's vite plugin owns this website's route tree and rewrites it\n // in its own (unformatted) shape whenever the config is loaded — including when\n // Nx computes the project graph — so formatting it here would only make\n // generation non-idempotent. The vended biome config excludes `**/*.gen.*`, so\n // the workspace's own `format` target leaves it alone too.\n await formatFilesInSubtree(tree, undefined, {\n ignore: tanstackRouter\n ? [joinPathFragments(libraryRoot, 'src', 'routeTree.gen.ts')]\n : [],\n });\n\n // The generated vite.config.mts imports these, and Nx's inferred `@nx/vite`\n // plugin loads that config when computing the project graph — so they must be\n // installed even if the caller would otherwise prefer to defer.\n return () =>\n installDependencies(tree, schema.preferInstallDependencies, {\n languages: ['typescript'],\n ensureResolvable: [\n ...(tailwind ? (['@tailwindcss/vite'] as const) : []),\n ...(tanstackRouter ? (['@tanstack/router-plugin'] as const) : []),\n ],\n });\n}\nexport default tsReactWebsiteGenerator;\n"],"names":["detectPackageManager","generateFiles","joinPathFragments","names","OverwriteStrategy","readProjectConfiguration","removeDependenciesFromPackageJson","updateJson","updateProjectConfiguration","applicationGenerator","relative","sep","addTsDependencies","addDestructuredImport","addSingleImport","appendToArrayViaGritQL","applyGritQL","declareDependencies","ownedElsewhere","formatFilesInSubtree","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","kebabCase","toClassName","toKebabCase","getNpmScopePrefix","addGeneratorMetadata","getGeneratorInfo","sortObjectKeys","getRelativePathToRoot","getPackageManagerDisplayCommands","assignPort","SHARED_CONSTRUCTS_DEPENDENCIES","sharedConstructsGenerator","PACKAGES_DIR","SHARED_SHADCN_DIR","TERRAFORM_WEBSITE_RUNTIME_CONFIG_FILE","addSharedShadcnDependency","SHADCN_DEPENDENCIES","sharedShadcnGenerator","withVersions","addWebsiteInfra","WEBSITE_CONSTRUCTS_PY_DEPENDENCIES","configureTsProject","mergeTsProjectDirReference","TS_PROJECT_DEPENDENCIES","VITEST_DEPENDENCIES","DEPENDENCIES","ts","name","dev","root","when","m","ux","tanstackRouter","tailwind","versionOnly","py","SUPPORTED_UX_PROVIDERS","REACT_WEBSITE_APP_GENERATOR_INFO","filename","tsReactWebsiteGenerator","tree","schema","Error","npmScopePrefix","scopeAlias","websiteNameClassName","websiteNameKebabCase","fullyQualifiedName","websiteContentPath","directory","subDirectory","projectAlreadyExists","exists","e2eTestRunner","routing","linter","bundler","unitTestRunner","useProjectJson","style","addPlugin","nxJson","plugin","plugins","options","buildTargetName","serveTargetName","devTargetName","previewTargetName","serveStaticTargetName","typecheckTargetName","testTargetName","delete","projectConfiguration","targets","port","previewPort","infra","iac","undefined","executor","metadata","description","exec","command","env","SRC_FILE","DEST_DIR","DEST_FILE","dependsOn","outputs","cwd","continuous","framework","dir","websiteProjectName","projectConfig","libraryRoot","sharedShadcnStylesImport","split","join","sharedShadcnProjectRef","templateOptions","pkgMgrCmd","appCommonTemplatePath","dirname","appTemplatePath","toLowerCase","overwriteStrategy","KeepExisting","routerCommonTemplatePath","routerTemplatePath","e2eFullyQualifiedName","e2eRoot","viteConfigPath","outDir","scope","tsconfig","compilerOptions","moduleResolution","module","outDirToRootRelativePath","distDir","tsBuildInfoFile","lib","references","projectRoot","packageJson","overrides","ignore","preferInstallDependencies","languages","ensureResolvable"],"mappings":"AAAA;;;CAGC,GACD,SACEA,oBAAoB,EACpBC,aAAa,EACbC,iBAAiB,EACjBC,KAAK,EACLC,iBAAiB,EACjBC,wBAAwB,EACxBC,iCAAiC,EAEjCC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAASC,oBAAoB,QAAQ,YAAY;AACjD,SAASC,QAAQ,EAAEC,GAAG,QAAQ,OAAO;AACrC,SAASC,iBAAiB,QAAQ,qCAAqC;AACvE,SACEC,qBAAqB,EACrBC,eAAe,EACfC,sBAAsB,EACtBC,WAAW,QACN,wBAAwB;AAC/B,SACEC,mBAAmB,EACnBC,cAAc,QACT,0CAA0C;AACjD,SAASC,oBAAoB,QAAQ,2BAA2B;AAChE,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SAASC,mBAAmB,QAAQ,4BAA4B;AAChE,SAASC,+BAA+B,QAAQ,4BAA4B;AAC5E,SAASC,SAAS,EAAEC,WAAW,EAAEC,WAAW,QAAQ,0BAA0B;AAC9E,SAASC,iBAAiB,QAAQ,8BAA8B;AAChE,SACEC,oBAAoB,EACpBC,gBAAgB,QAEX,uBAAuB;AAC9B,SAASC,cAAc,QAAQ,2BAA2B;AAC1D,SAASC,qBAAqB,QAAQ,0BAA0B;AAChE,SAASC,gCAAgC,QAAQ,gCAAgC;AACjF,SAASC,UAAU,QAAQ,yBAAyB;AACpD,SACEC,8BAA8B,EAC9BC,yBAAyB,QACpB,sCAAsC;AAC7C,SAEEC,YAAY,EACZC,iBAAiB,EACjBC,qCAAqC,QAChC,gDAAgD;AACvD,SACEC,yBAAyB,EACzBC,mBAAmB,EACnBC,qBAAqB,QAChB,kCAAkC;AACzC,SAASC,YAAY,QAAQ,6BAA6B;AAC1D,SACEC,eAAe,EACfC,kCAAkC,QAC7B,0D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U,EACnBxB,0BAEFgB,SAASQ,UAAU;QAC3B,CAAA;IAGFzI,kBAAkBoD,MAAMhB,cAAc;QAAEyD;QAAU6C,aAAa7B;IAAY;IAE3E,4EAA4E;IAC5E,6EAA6E;IAC7E,8EAA8E;IAC9E,yDAAyD;IACzD,IAAIzH,2BAA2B,OAAO;QACpCO,WAAWyD,MAAM,gBAAgB,CAACuF;YAChCA,YAAYC,SAAS,GAAG;gBACtB,GAAGD,YAAYC,SAAS;gBACxB,aAAa;oBACX,GAAGD,YAAYC,SAAS,EAAE,CAAC,YAAY;oBACvC,GAAG/G,aAAaO,cAAc;wBAAC;qBAAU,CAAC;gBAC5C;YACF;YACA,OAAOuG;QACT;IACF;IAEA,uEAAuE;IACvE,0EAA0E;IAC1E,4EAA4E;IAC5E,4EAA4E;IAC5E,mDAAmD;IACnDjJ,kCAAkC0D,MAAM;QAAC;QAAS;KAAY,EAAE,EAAE;IAElE,MAAM1C,gCAAgC0C,MAAM;QAC1CH;KACD;IAED,+EAA+E;IAC/E,gFAAgF;IAChF,wEAAwE;IACxE,+EAA+E;IAC/E,2DAA2D;IAC3D,MAAM1C,qBAAqB6C,MAAMuC,WAAW;QAC1CkD,QAAQjG,iBACJ;YAACtD,kBAAkBuH,aAAa,OAAO;SAAoB,GAC3D,EAAE;IACR;IAEA,4EAA4E;IAC5E,8EAA8E;IAC9E,gEAAgE;IAChE,OAAO,IACLpG,oBAAoB2C,MAAMC,OAAOyF,yBAAyB,EAAE;YAC1DC,WAAW;gBAAC;aAAa;YACzBC,kBAAkB;mBACZnG,WAAY;oBAAC;iBAAoB,GAAa,EAAE;mBAChDD,iBAAkB;oBAAC;iBAA0B,GAAa,EAAE;aACjE;QACH;AACJ;AACA,eAAeO,wBAAwB"}
@@ -181,7 +181,8 @@ export interface PyMcpFamilyConnection extends PyClientNaming {
181
181
  export declare const PY_MCP_FAMILY_CONNECTIONS: Record<AgentFramework, PyMcpFamilyConnection>;
182
182
  /**
183
183
  * Add a re-export to the Python agent-connection module's __init__.py.
184
- * Equivalent to addStarExport for TS.
184
+ * Equivalent to addStarExport for TS, including creating the file when it does
185
+ * not yet exist in the tree.
185
186
  * Uses `__all__` to mark re-exports as public (satisfies ruff F401).
186
187
  * Uses GritQL for AST-aware transforms where possible.
187
188
  */
@@ -569,7 +569,8 @@ export const PY_MCP_FAMILY_CONNECTIONS = {
569
569
  };
570
570
  /**
571
571
  * Add a re-export to the Python agent-connection module's __init__.py.
572
- * Equivalent to addStarExport for TS.
572
+ * Equivalent to addStarExport for TS, including creating the file when it does
573
+ * not yet exist in the tree.
573
574
  * Uses `__all__` to mark re-exports as public (satisfies ruff F401).
574
575
  * Uses GritQL for AST-aware transforms where possible.
575
576
  */ export async function addPythonReExport(tree, initFilePath, fromModule, importName) {
@@ -579,6 +580,10 @@ export const PY_MCP_FAMILY_CONNECTIONS = {
579
580
  }
580
581
  const importLine = `from ${fromModule} import ${importName}`;
581
582
  const allEntry = `"${importName}"`;
583
+ if (!tree.exists(initFilePath)) {
584
+ tree.write(initFilePath, `${importLine}\n\n__all__ = [${allEntry}]\n`);
585
+ return;
586
+ }
582
587
  // If there's already an import from the same module, merge into its name list
583
588
  // (ruff I001 rejects two `from X import ...` lines for the same module).
584
589
  const mergedImport = await applyGritQL(tree, initFilePath, py(`\`from ${fromModule} import $names\` where {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/agent-connection/agent-connection.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type Tree,\n} from '@nx/devkit';\nimport pyProjectGenerator, {\n getPyProjectDetails,\n} from '../../py/project/generator.js';\nimport tsProjectGenerator from '../../ts/lib/generator.js';\nimport {\n addStarExport,\n appendToArrayViaGritQL,\n applyGritQL,\n matchGritQL,\n} from '../ast.js';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n type MustDeclarePy,\n} from '../declared-dependencies.js';\nimport { addDependenciesToPackageJson } from '../dependencies.js';\nimport { esmVars } from '../module-format.js';\nimport { addDependenciesToPyProjectToml } from '../py.js';\nimport {\n type IPyDepVersion,\n type ITsDepVersion,\n withVersions,\n} from '../versions.js';\n\n/** TypeScript dependencies a caller must declare to emit agent-connection clients. */\nexport const AGENT_CONNECTION_DEPENDENCIES = [\n { name: '@aws-lambda-powertools/parameters' },\n { name: '@aws-sdk/credential-providers' },\n { name: 'aws4fetch' },\n { name: '@modelcontextprotocol/sdk' },\n { name: '@a2a-js/sdk' },\n { name: '@strands-agents/sdk' },\n { name: '@aws-sdk/client-s3' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\n/** Python dependencies a caller must declare to emit agent-connection clients. */\nexport const AGENT_CONNECTION_PY_DEPENDENCIES = [\n { name: 'aws-lambda-powertools' },\n { name: 'strands-agents' },\n] as const satisfies readonly { name: IPyDepVersion }[];\n\ntype AgentConnectionPyDependency =\n (typeof AGENT_CONNECTION_PY_DEPENDENCIES)[number]['name'];\n\n/** Prefix a GritQL pattern with `language python` */\nconst py = (pattern: string) => `language python\\n${pattern}`;\n\nconst AGENT_CONNECTION_DIR = 'agent-connection';\nconst PACKAGES_DIR = 'packages';\nconst COMMON_DIR = 'common';\n\nexport const AGENT_CONNECTION_PROJECT_DIR = joinPathFragments(\n PACKAGES_DIR,\n COMMON_DIR,\n AGENT_CONNECTION_DIR,\n);\n\nconst PY_AGENT_CONNECTION_NAME = 'agent_connection';\n\n/**\n * Get the directory of the shared Python agent-connection project.\n */\nexport function getPythonAgentConnectionProjectDir(tree: Tree): string {\n const { dir } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return dir;\n}\n\n/**\n * Get the Python module name of the shared agent-connection project.\n */\nexport function getPythonAgentConnectionModuleName(tree: Tree): string {\n const { normalizedModuleName } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return normalizedModuleName;\n}\n\n/**\n * Get the shared agent-connection project as `{ name, root }`, suitable for\n * passing to {@link addWorkspaceDependencyToPyProject} (which derives the\n * dependency's PEP 503 distribution name from the project itself, so callers\n * never construct the name).\n */\nexport function getPythonAgentConnectionProject(tree: Tree): {\n name: string;\n root: string;\n} {\n const { fullyQualifiedName, dir } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return { name: fullyQualifiedName, root: dir };\n}\n\n/**\n * The connection protocols an agent framework can connect over. Each maps to a\n * framework-agnostic Layer-0/1 template directory plus a per-framework Layer-2\n * client directory (see `FRAMEWORKS`).\n */\nexport type ConnectionProtocol = 'mcp' | 'gateway' | 'a2a';\n\n/**\n * The agent frameworks we can generate connection clients for. Adding a new\n * framework is an additive change: append an entry to `FRAMEWORKS` with its\n * Layer-2 template directories and dependencies — the framework-agnostic\n * Layer-0/1 (`core-auth`, `core-shared`, the per-protocol transports/configs)\n * is reused unchanged.\n */\nexport type AgentFramework = 'strands' | 'langchain';\n\n/**\n * Resolve an agent component's framework, defaulting to `strands`. Connection\n * generators dispatch on the returned framework to pick the matching templates\n * and agent.py/agent.ts transforms.\n */\nexport function resolveAgentFramework(\n framework: string | undefined,\n): AgentFramework {\n return framework === 'langchain' ? 'langchain' : 'strands';\n}\n\n/**\n * Framework-agnostic Layer-1 templates, keyed by protocol. These resolve the\n * endpoint and build the signed transport/client-config; they contain no\n * framework dependency.\n */\nconst TS_PROTOCOL_TEMPLATES: Record<ConnectionProtocol, string> = {\n mcp: 'core-mcp',\n gateway: 'core-gateway',\n a2a: 'core-a2a',\n};\nconst PY_PROTOCOL_TEMPLATES: Record<ConnectionProtocol, string> = {\n mcp: 'py-core-mcp',\n gateway: 'py-core-gateway',\n a2a: 'py-core-a2a',\n};\n\n/**\n * A re-export the framework base emits into the agent-connection module's\n * `__init__.py` (the agent server entry point imports these by name).\n */\ninterface BaseReExport {\n fromModule: string;\n importName: string;\n}\n\n/**\n * A framework's Layer-2 templates for one language. `base` (optional) holds the\n * helpers every connection of that framework needs (error logging, per-session\n * agent cache); `baseReExports` lists what those helpers expose at the module\n * root. `protocols` maps each *supported* protocol to the thin client that wraps\n * the matching Layer-1 transport/config in the framework's client type.\n *\n * A framework whose Layer-2 needs no base helpers (e.g. LangChain, whose AG-UI\n * foundation reuses only the framework-agnostic session context) omits `base`\n * and leaves `baseReExports` empty.\n *\n * A protocol absent from `protocols` is not supported by that framework in that\n * language — callers must check before emitting. `deps` are the extra package\n * dependencies the base helpers require (per-connection client deps are added\n * by the connection generators, not here).\n */\ninterface FrameworkLanguageTemplates<Dep extends string> {\n base?: string;\n baseReExports: BaseReExport[];\n protocols: Partial<Record<ConnectionProtocol, string>>;\n deps: Dep[];\n}\n\n/**\n * Per-framework Layer-2 templates. Support is asymmetric by design: a framework\n * may target only one language (`ts`/`py` is optional) and only a subset of\n * protocols. Adding a framework — or extending an existing one to a new\n * language/protocol — is an additive change to this registry.\n */\ninterface FrameworkTemplates {\n ts?: FrameworkLanguageTemplates<string>;\n py?: FrameworkLanguageTemplates<AgentConnectionPyDependency>;\n}\n\nconst FRAMEWORKS: Record<AgentFramework, FrameworkTemplates> = {\n strands: {\n ts: {\n base: 'core-strands/base',\n baseReExports: [\n {\n fromModule: './core/with-session-id-strands.js',\n importName: '*',\n },\n {\n fromModule: './core/model-errors-strands.js',\n importName: '*',\n },\n {\n fromModule: './core/tool-errors-strands.js',\n importName: '*',\n },\n ],\n protocols: {\n mcp: 'core-strands/mcp',\n gateway: 'core-strands/gateway',\n a2a: 'core-strands/a2a',\n },\n deps: [],\n },\n py: {\n base: 'py-core-strands/base',\n baseReExports: [\n {\n fromModule: '.core.with_session_id_strands',\n importName: 'with_session_id',\n },\n {\n fromModule: '.core.model_errors_strands',\n importName: 'log_model_errors',\n },\n {\n fromModule: '.core.tool_errors_strands',\n importName: 'log_tool_errors',\n },\n ],\n protocols: {\n mcp: 'py-core-strands/mcp',\n gateway: 'py-core-strands/gateway',\n a2a: 'py-core-strands/a2a',\n },\n deps: ['strands-agents'],\n },\n },\n langchain: {\n // LangChain is supported for Python agents only (the TypeScript LangChain\n // agent foundation has no in-process AG-UI <-> LangGraph adapter, so it is\n // not scaffolded — see ts#agent). Its Layer-2 clients stay usable after\n // agent construction, so there is no base helper layer (no model-error\n // logger / per-session agent cache) and no strands-agents dependency — its\n // AG-UI foundation reuses only the framework-agnostic session context, and\n // its A2A client drives the a2a SDK directly rather than wrapping Strands'\n // A2AAgent. The per-connection adapter dependency (langchain-mcp-adapters /\n // a2a-sdk) is added by the connection generators.\n py: {\n baseReExports: [],\n protocols: {\n mcp: 'py-core-langchain/mcp',\n gateway: 'py-core-langchain/gateway',\n a2a: 'py-core-langchain/a2a',\n },\n deps: [],\n },\n },\n};\n\n/** Resolve a framework's templates for a language + protocol, or throw. */\nfunction frameworkLanguage<L extends 'ts' | 'py'>(\n framework: AgentFramework,\n language: L,\n protocol: ConnectionProtocol,\n): NonNullable<FrameworkTemplates[L]> & { protocol: string } {\n const lang = FRAMEWORKS[framework][language];\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support ${language === 'ts' ? 'TypeScript' : 'Python'} agents.`,\n );\n }\n const protocolDir = lang.protocols[protocol];\n if (!protocolDir) {\n throw new Error(\n `The '${framework}' framework does not support ${protocol} connections for ${language === 'ts' ? 'TypeScript' : 'Python'} agents.`,\n );\n }\n return { ...lang, protocol: protocolDir } as NonNullable<\n FrameworkTemplates[L]\n > & { protocol: string };\n}\n\n/** Protocols whose Layer-1 needs the shared MCP transport (`core-shared`). */\nconst MCP_TRANSPORT_PROTOCOLS: ConnectionProtocol[] = ['mcp', 'gateway'];\n\nconst tsCoreDir = () =>\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'core');\n\n/**\n * Runtime dependencies each TypeScript core template directory imports. Emitting\n * a template also declares its dependencies in the agent-connection project's\n * package.json so the `noUndeclaredDependencies` lint rule passes.\n */\nconst TS_TEMPLATE_DEPS: Record<\n string,\n (typeof AGENT_CONNECTION_DEPENDENCIES)[number]['name'][]\n> = {\n 'core-runtime-config': ['@aws-lambda-powertools/parameters'],\n 'core-auth': ['@aws-sdk/credential-providers', 'aws4fetch'],\n 'core-shared': ['@aws-sdk/credential-providers', '@modelcontextprotocol/sdk'],\n 'core-mcp': ['@aws-sdk/credential-providers', '@modelcontextprotocol/sdk'],\n 'core-gateway': [\n '@aws-sdk/credential-providers',\n '@modelcontextprotocol/sdk',\n ],\n 'core-a2a': ['@aws-sdk/credential-providers', '@a2a-js/sdk'],\n 'core-strands/base': ['@strands-agents/sdk', '@aws-sdk/client-s3'],\n 'core-strands/mcp': ['@strands-agents/sdk', '@aws-sdk/client-s3'],\n 'core-strands/gateway': ['@strands-agents/sdk', '@aws-sdk/client-s3'],\n 'core-strands/a2a': ['@strands-agents/sdk', '@aws-sdk/client-s3'],\n};\n\nconst emitTs = (\n tree: Tree,\n templateDir: string,\n declaration: DependencyDeclaration,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', templateDir),\n tsCoreDir(),\n { ...esmVars(tree) },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n const deps = TS_TEMPLATE_DEPS[templateDir];\n if (deps?.length) {\n addDependenciesToPackageJson(\n tree,\n withVersions(\n forDependencies<typeof AGENT_CONNECTION_DEPENDENCIES>(declaration),\n deps,\n ),\n {},\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'package.json'),\n );\n }\n};\n\n/**\n * Ensure the shared TypeScript agent-connection project exists and has the\n * framework-agnostic core helpers (runtime-config loader, session context).\n * Per-connection generators emit their own protocol + framework client\n * templates via `addTypeScriptCoreClient`.\n */\nexport async function ensureTypeScriptAgentConnectionProject<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n): Promise<void> {\n const projectJsonPath = joinPathFragments(\n AGENT_CONNECTION_PROJECT_DIR,\n 'project.json',\n );\n if (!tree.exists(projectJsonPath)) {\n await tsProjectGenerator(tree, {\n name: AGENT_CONNECTION_DIR,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n }\n\n // Framework-agnostic runtime-config + session-context helpers.\n emitTs(tree, 'core-runtime-config', declaration);\n\n // Re-export session-context helpers so agent server entry points can set the\n // current session on each inbound request without pulling in internals.\n await addStarExport(\n tree,\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'index.ts'),\n './core/session-context.js',\n );\n\n // Re-export the runtime-config loader so agent server entry points can read\n // their own connected resources (e.g. session storage) without pulling in\n // internals.\n await addStarExport(\n tree,\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'index.ts'),\n './core/runtime-config.js',\n );\n}\n\n/**\n * Emit a framework's base Layer-2 helpers (model-error logging + per-session\n * agent cache) into the agent-connection project and re-export them. The agent\n * server entry point imports these regardless of whether any connection client\n * is wired in, so the agent generator calls this directly; connection\n * generators call it transitively via `addTypeScriptCoreClient`.\n */\nexport async function addTypeScriptFrameworkBase<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const lang = FRAMEWORKS[framework].ts;\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support TypeScript agents.`,\n );\n }\n if (lang.base) {\n emitTs(tree, lang.base, declaration);\n }\n\n const indexPath = joinPathFragments(\n AGENT_CONNECTION_PROJECT_DIR,\n 'src',\n 'index.ts',\n );\n for (const reExport of lang.baseReExports) {\n await addStarExport(tree, indexPath, reExport.fromModule);\n }\n}\n\n/**\n * Emit the TypeScript client templates for a connection protocol and agent\n * framework into the agent-connection project's `src/core/` directory. Safe to\n * call multiple times — `KeepExisting` preserves customised files.\n *\n * Layers emitted:\n * - Layer 0 `core-auth` (signed fetch + endpoint resolution) — always\n * - Layer 1 `core-shared` MCP transport — for mcp/gateway protocols\n * - Layer 1 the protocol's transport/client-config — always\n * - Layer 2 the framework's base helpers + protocol client — per framework\n */\nexport async function addTypeScriptCoreClient<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n protocol: ConnectionProtocol,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const fw = frameworkLanguage(framework, 'ts', protocol);\n\n emitTs(tree, 'core-auth', declaration);\n if (MCP_TRANSPORT_PROTOCOLS.includes(protocol)) {\n emitTs(tree, 'core-shared', declaration);\n }\n emitTs(tree, TS_PROTOCOL_TEMPLATES[protocol], declaration);\n\n // Framework Layer 2: base helpers (re-exported for the agent server) + the\n // thin protocol client.\n await addTypeScriptFrameworkBase(\n tree,\n forDependencies<typeof AGENT_CONNECTION_DEPENDENCIES>(declaration),\n framework,\n );\n emitTs(tree, fw.protocol, declaration);\n}\n\n/**\n * Ensure the shared Python agent-connection project exists.\n * Only creates the project shell — per-connection generators are responsible\n * for emitting their own core client templates.\n */\nexport async function ensurePythonAgentConnectionProject<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n): Promise<void> {\n const projectDir = getPythonAgentConnectionProjectDir(tree);\n const moduleName = getPythonAgentConnectionModuleName(tree);\n const projectJsonPath = joinPathFragments(projectDir, 'project.json');\n\n if (!tree.exists(projectJsonPath)) {\n // Create the Python project using the standard py#project generator\n await pyProjectGenerator(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n type: 'library',\n });\n }\n\n const moduleDir = joinPathFragments(projectDir, moduleName);\n\n // Ensure core/__init__.py exists\n const coreDir = joinPathFragments(moduleDir, 'core');\n if (!tree.exists(joinPathFragments(coreDir, '__init__.py'))) {\n tree.write(joinPathFragments(coreDir, '__init__.py'), '');\n }\n\n // Ensure app/__init__.py exists\n const appInitPath = joinPathFragments(moduleDir, 'app', '__init__.py');\n if (!tree.exists(appInitPath)) {\n tree.write(appInitPath, '');\n }\n\n // Framework-agnostic runtime-config + session-context helpers.\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'py-core-runtime-config'),\n coreDir,\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Re-export the session id context so agent server entry points can set the\n // current session on each inbound request without importing internals.\n const moduleInitPath = joinPathFragments(moduleDir, '__init__.py');\n await addPythonReExport(\n tree,\n moduleInitPath,\n '.core.session_context',\n 'get_current_session_id',\n );\n await addPythonReExport(\n tree,\n moduleInitPath,\n '.core.session_context',\n 'session_id_context',\n );\n\n // The runtime-config loader reads AppConfig via aws-lambda-powertools.\n addDependenciesToPyProjectToml(\n tree,\n projectDir,\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n ['aws-lambda-powertools'],\n );\n}\n\nconst pyCoreDir = (tree: Tree) =>\n joinPathFragments(\n getPythonAgentConnectionProjectDir(tree),\n getPythonAgentConnectionModuleName(tree),\n 'core',\n );\n\nconst emitPy = (tree: Tree, templateDir: string) =>\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', templateDir),\n pyCoreDir(tree),\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n/**\n * Ensure the shared Python agent-connection project has\n * `s3_checkpoint_saver_langchain.py` — a vendored `S3CheckpointSaver`\n * (from `langgraph-checkpoint-s3`, MIT licensed) that LangChain agents with\n * `session: 's3'` import from directly (`.core.s3_checkpoint_saver_langchain`),\n * mirroring how they import `.core.runtime_config`. Vendored rather than\n * installed as a dependency, and shared rather than per-agent, since it has\n * no agent-specific templating.\n */\nexport function ensureLangchainS3CheckpointSaver(tree: Tree): void {\n emitPy(tree, 'py-core-langchain/s3');\n}\n\n/**\n * Emit a framework's base Layer-2 helpers (model-error logging + per-session\n * agent cache) into the Python agent-connection project and re-export them.\n * The agent server entry point imports these regardless of whether a connection\n * client is wired in, so the agent generator calls this directly; connection\n * generators call it transitively via `addPythonCoreClient`.\n */\nexport async function addPythonFrameworkBase<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const lang = FRAMEWORKS[framework].py;\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support Python agents.`,\n );\n }\n if (lang.base) {\n emitPy(tree, lang.base);\n }\n\n const moduleInitPath = joinPathFragments(\n getPythonAgentConnectionProjectDir(tree),\n getPythonAgentConnectionModuleName(tree),\n '__init__.py',\n );\n for (const reExport of lang.baseReExports) {\n await addPythonReExport(\n tree,\n moduleInitPath,\n reExport.fromModule,\n reExport.importName,\n );\n }\n\n if (lang.deps.length > 0) {\n addDependenciesToPyProjectToml(\n tree,\n getPythonAgentConnectionProjectDir(tree),\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n lang.deps,\n );\n }\n}\n\n/**\n * Emit the Python client templates for a connection protocol and agent\n * framework into the agent-connection project's core directory.\n *\n * Layers emitted:\n * - Layer 0 `py-core-auth` (SigV4 httpx.Auth, session auth, endpoints) — always\n * - Layer 1 `py-core-shared` MCP transport — for mcp/gateway protocols\n * - Layer 1 the protocol's transport/client-config — always\n * - Layer 2 the framework's base helpers + protocol client — per framework\n */\nexport async function addPythonCoreClient<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n protocol: ConnectionProtocol,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const fw = frameworkLanguage(framework, 'py', protocol);\n\n emitPy(tree, 'py-core-auth');\n if (MCP_TRANSPORT_PROTOCOLS.includes(protocol)) {\n emitPy(tree, 'py-core-shared');\n }\n emitPy(tree, PY_PROTOCOL_TEMPLATES[protocol]);\n\n // Framework Layer 2: base helpers + the thin protocol client.\n await addPythonFrameworkBase(\n tree,\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n framework,\n );\n emitPy(tree, fw.protocol);\n}\n\n/**\n * Patch a TypeScript agent.ts to create a connection client and register it\n * in the Agent's tools. Used by the MCP and gateway connection generators —\n * the client class must expose a static async `create()` returning a value\n * accepted by `Agent.tools` (e.g. an `McpClient`).\n */\nexport async function addTypeScriptClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n const clientCreationStmt = `const ${clientVarName} = await ${clientClassName}.create();`;\n\n // Transform the arrow function that contains `new Agent`:\n // - Expression body: wrap in block with client creation and return\n // - Block body: prepend client creation statement\n await applyGritQL(\n tree,\n agentFilePath,\n `or { \\`async ($p) => new Agent($args)\\` => raw\\`async ($p) => {\n ${clientCreationStmt}\n return new Agent($args);\n}\\` where { $program <: not contains \\`${clientClassName}.create\\` }, \\`async ($p) => { $body }\\` => raw\\`async ($p) => {\n ${clientCreationStmt}\n $body\n}\\` where { $body <: contains \\`new Agent($_)\\`, $program <: not contains \\`${clientClassName}.create\\` } }`,\n );\n\n // Prepend the client to the tools array\n await applyGritQL(\n tree,\n agentFilePath,\n `\\`tools: [$items]\\` => \\`tools: [${clientVarName}, $items]\\` where { $items <: within \\`new Agent($_)\\`, $items <: not contains \\`${clientVarName}\\` }`,\n );\n}\n\n/**\n * Patch a Python agent.py to create a context-managed connection client,\n * enter it in the `with` block around `yield Agent(...)`, and spread its\n * `list_tools_sync()` into the Agent's tools. Used by the MCP and gateway\n * connection generators — the client class must expose a static `create()`\n * returning a context manager with `list_tools_sync()` (e.g. an `MCPClient`).\n */\nasync function addPythonClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n await addPythonClientTools(tree, agentFilePath, clientVarName);\n await addPythonClientToGetAgent(\n tree,\n agentFilePath,\n clientClassName,\n clientVarName,\n );\n}\n\n/**\n * Append `*<clientVarName>.list_tools_sync()` to the Agent's tools list.\n */\nconst addPythonClientTools = async (\n tree: Tree,\n filePath: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(\n tree,\n filePath,\n py(`\\`${clientVarName}.list_tools_sync()\\``),\n )\n ) {\n return;\n }\n\n await appendToArrayViaGritQL(\n tree,\n filePath,\n 'tools=',\n `*${clientVarName}.list_tools_sync()`,\n { skipIfContains: clientVarName, language: 'py' },\n );\n};\n\n/**\n * Create the client in get_agent and enter it in the `with` block.\n *\n * First connection: rewrites `def get_agent` to wrap the body in a with\n * block. Subsequent connections: adds to the existing with items and\n * prepends the creation line.\n */\nconst addPythonClientToGetAgent = async (\n tree: Tree,\n filePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(tree, filePath, py(`\\`${clientClassName}.create()\\``))\n ) {\n return;\n }\n\n // Try the \"add to existing with block\" pattern first.\n // If it succeeds, there was already a with block from a previous connection.\n const addedToWith = await applyGritQL(\n tree,\n filePath,\n py(`\\`with ($items,): $body\\` where {\n $items <: not contains \\`${clientVarName}\\`,\n $items += \\`, ${clientVarName}\\`\n}`),\n );\n\n if (addedToWith) {\n // Subsequent connection — prepend the creation line to the function body\n // (a single anchor, so the line is inserted exactly once).\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`yield Agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n $body\\``),\n );\n return;\n }\n\n // First connection — wrap the existing `def get_agent` body in a single\n // `with (<var>,):` block.\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`yield Agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n with (\n ${clientVarName},\n ):\n $body\\``),\n );\n};\n\n/**\n * Patch a LangChain agent.py to load connection tools and spread them into the\n * `create_agent(...)` tools list. Used by the MCP and gateway connection\n * generators when the source agent uses the `langchain` framework — the client\n * class must expose a static `create()` returning a `list[BaseTool]`. The tools\n * come from langchain-mcp-adapters' `MultiServerMCPClient`, which keeps the\n * connection config on each tool and opens a fresh MCP session per call, so the\n * tools stay usable after `get_agent` returns — no `with` block is needed.\n * Mirrors {@link addPythonClientToAgent} for the Strands shape.\n */\nasync function addPythonLangchainClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n await addPythonLangchainClientTools(tree, agentFilePath, clientVarName);\n await addPythonLangchainClientToGetAgent(\n tree,\n agentFilePath,\n clientClassName,\n clientVarName,\n );\n}\n\n/**\n * Spread `*<clientVarName>` into the `create_agent(...)` tools list.\n *\n * Scoped via `$old <: within \\`create_agent($_)\\`` so only the agent's own\n * tools= keyword argument is touched (not an unrelated function with a\n * `tools=` parameter).\n */\nconst addPythonLangchainClientTools = async (\n tree: Tree,\n filePath: string,\n clientVarName: string,\n): Promise<void> => {\n await applyGritQL(\n tree,\n filePath,\n py(`\\`tools=$old\\` where {\n $old <: within \\`create_agent($_)\\`,\n $old <: not contains \\`*${clientVarName}\\`,\n if ($old <: \\`[]\\`) {\n $old => \\`[*${clientVarName}]\\`\n } else {\n $old <: \\`[$items]\\` where { $items += \\`, *${clientVarName}\\` }\n }\n}`),\n );\n};\n\n/**\n * Prepend `<clientVarName> = <clientClassName>.create()` to the get_agent body\n * (which loads the connection's tools). No `with` block — the LangChain client\n * hands langchain-mcp-adapters a connection config, so each tool opens its own\n * MCP session per call and the tools are safe to use after get_agent returns.\n * Idempotent via the `not contains <clientClassName>.create` guard.\n */\nconst addPythonLangchainClientToGetAgent = async (\n tree: Tree,\n filePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(tree, filePath, py(`\\`${clientClassName}.create()\\``))\n ) {\n return;\n }\n\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`create_agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n $body\\``),\n );\n};\n\n/**\n * Per-framework naming + template layout for a Python per-connection client.\n * Every py#agent connection generator (mcp, gateway, a2a) names its client\n * class `<Name>Client<suffix>`, its module `<name>_client_<suffix>`, and reads\n * the per-connection app-client template from a per-framework sub-path of its\n * own `files/` dir — all of which vary only by framework, so they live here as\n * one source of truth.\n *\n * Keyed by {@link AgentFramework} rather than a boolean so a third framework is\n * an additive entry here — never another `if (isLangchain)` branch in each\n * generator.\n */\nexport interface PyClientNaming {\n /** Class-name suffix on the per-connection app client (`<Name>Client<suffix>`). */\n clientClassSuffix: string;\n /** Module/file-name suffix on the per-connection app client (`<name>_client_<suffix>`). */\n clientModuleSuffix: string;\n /**\n * Sub-path, under a connection generator's `files/` dir, of the per-connection\n * app client template for this framework. Every connection generator lays its\n * templates out the same way, so this resolves against any of them.\n */\n appTemplateSubdir: string;\n}\n\nexport const PY_CLIENT_NAMING: Record<AgentFramework, PyClientNaming> = {\n strands: {\n clientClassSuffix: 'Strands',\n clientModuleSuffix: 'strands',\n appTemplateSubdir: joinPathFragments('agent-connection', 'app'),\n },\n langchain: {\n clientClassSuffix: 'LangChain',\n clientModuleSuffix: 'langchain',\n appTemplateSubdir: joinPathFragments(\n 'langchain',\n 'agent-connection',\n 'app',\n ),\n },\n};\n\n/**\n * How an MCP-family connection (an MCP server or an AgentCore Gateway, both of\n * which expose tools over MCP) is wired into a Python agent of a given\n * framework. The mcp-connection and gateway-connection generators share this:\n * they differ only in the metadata of the thing being connected, not in how\n * the framework's client is shaped or spliced into agent.py. A2A connections\n * wire tools differently, so they reuse only {@link PY_CLIENT_NAMING}.\n */\nexport interface PyMcpFamilyConnection extends PyClientNaming {\n /** Extra Python deps this framework's MCP-family client needs (beyond the shared transport). */\n deps: IPyDepVersion[];\n /**\n * Splice the per-connection client into the agent's `get_agent` in agent.py.\n * Strands enters a context-managed `MCPClient` and spreads `list_tools_sync()`;\n * LangChain loads `BaseTool`s and spreads them into `create_agent(...)`.\n */\n wireClientIntoAgent: (\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n ) => Promise<void>;\n}\n\nexport const PY_MCP_FAMILY_CONNECTIONS: Record<\n AgentFramework,\n PyMcpFamilyConnection\n> = {\n strands: {\n ...PY_CLIENT_NAMING.strands,\n deps: [],\n wireClientIntoAgent: addPythonClientToAgent,\n },\n langchain: {\n ...PY_CLIENT_NAMING.langchain,\n // langchain-mcp-adapters backs the LangChain client; it must not pull Strands in.\n deps: ['langchain-mcp-adapters'],\n wireClientIntoAgent: addPythonLangchainClientToAgent,\n },\n};\n\n/**\n * Add a re-export to the Python agent-connection module's __init__.py.\n * Equivalent to addStarExport for TS.\n * Uses `__all__` to mark re-exports as public (satisfies ruff F401).\n * Uses GritQL for AST-aware transforms where possible.\n */\nexport async function addPythonReExport(\n tree: Tree,\n initFilePath: string,\n fromModule: string,\n importName: string,\n): Promise<void> {\n // Check if already exported\n if (await matchGritQL(tree, initFilePath, `\\`${importName}\\``)) {\n return;\n }\n\n const importLine = `from ${fromModule} import ${importName}`;\n const allEntry = `\"${importName}\"`;\n\n // If there's already an import from the same module, merge into its name list\n // (ruff I001 rejects two `from X import ...` lines for the same module).\n const mergedImport = await applyGritQL(\n tree,\n initFilePath,\n py(`\\`from ${fromModule} import $names\\` where {\n $names <: not contains \\`${importName}\\`,\n $names += \\`, ${importName}\\`\n}`),\n );\n\n if (mergedImport) {\n await applyGritQL(\n tree,\n initFilePath,\n py(`\\`__all__ = [$items]\\` where { $items += \\`, ${allEntry}\\` }`),\n );\n return;\n }\n\n // Try to append import after existing import using +=\n const appendedImport = await applyGritQL(\n tree,\n initFilePath,\n py(\n `\\`from $mod import $name\\` as $stmt where {\n $program <: not contains \\`${importName}\\`,\n $stmt += \\`\\n${importLine}\\`\n}`,\n ),\n );\n\n if (appendedImport) {\n // Also append to existing __all__\n await applyGritQL(\n tree,\n initFilePath,\n py(`\\`__all__ = [$items]\\` where { $items += \\`, ${allEntry}\\` }`),\n );\n return;\n }\n\n // No existing imports — first re-export. Try to anchor after docstring.\n const anchoredImport = await applyGritQL(\n tree,\n initFilePath,\n py(\n `\\`\"\"\"Automatically generated by Nx.\"\"\"\\` as $doc => \\`$doc\\n${importLine}\\n\\n__all__ = [${allEntry}]\\``,\n ),\n );\n\n if (!anchoredImport) {\n // Completely empty file or no docstring — write directly\n tree.write(initFilePath, `${importLine}\\n\\n__all__ = [${allEntry}]\\n`);\n }\n}\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","pyProjectGenerator","getPyProjectDetails","tsProjectGenerator","addStarExport","appendToArrayViaGritQL","applyGritQL","matchGritQL","forDependencies","addDependenciesToPackageJson","esmVars","addDependenciesToPyProjectToml","withVersions","AGENT_CONNECTION_DEPENDENCIES","name","AGENT_CONNECTION_PY_DEPENDENCIES","py","pattern","AGENT_CONNECTION_DIR","PACKAGES_DIR","COMMON_DIR","AGENT_CONNECTION_PROJECT_DIR","PY_AGENT_CONNECTION_NAME","getPythonAgentConnectionProjectDir","tree","dir","directory","getPythonAgentConnectionModuleName","normalizedModuleName","getPythonAgentConnectionProject","fullyQualifiedName","root","resolveAgentFramework","framework","TS_PROTOCOL_TEMPLATES","mcp","gateway","a2a","PY_PROTOCOL_TEMPLATES","FRAMEWORKS","strands","ts","base","baseReExports","fromModule","importName","protocols","deps","langchain","frameworkLanguage","language","protocol","lang","Error","protocolDir","MCP_TRANSPORT_PROTOCOLS","tsCoreDir","TS_TEMPLATE_DEPS","emitTs","templateDir","declaration","dirname","overwriteStrategy","KeepExisting","length","ensureTypeScriptAgentConnectionProject","projectJsonPath","exists","addTypeScriptFrameworkBase","indexPath","reExport","addTypeScriptCoreClient","fw","includes","ensurePythonAgentConnectionProject","projectDir","moduleName","type","moduleDir","coreDir","write","appInitPath","moduleInitPath","addPythonReExport","pyCoreDir","emitPy","ensureLangchainS3CheckpointSaver","addPythonFrameworkBase","addPythonCoreClient","addTypeScriptClientToAgent","agentFilePath","clientClassName","clientVarName","clientCreationStmt","addPythonClientToAgent","addPythonClientTools","addPythonClientToGetAgent","filePath","skipIfContains","addedToWith","addPythonLangchainClientToAgent","addPythonLangchainClientTools","addPythonLangchainClientToGetAgent","PY_CLIENT_NAMING","clientClassSuffix","clientModuleSuffix","appTemplateSubdir","PY_MCP_FAMILY_CONNECTIONS","wireClientIntoAgent","initFilePath","importLine","allEntry","mergedImport","appendedImport","anchoredImport"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,QAEZ,aAAa;AACpB,OAAOC,sBACLC,mBAAmB,QACd,gCAAgC;AACvC,OAAOC,wBAAwB,4BAA4B;AAC3D,SACEC,aAAa,EACbC,sBAAsB,EACtBC,WAAW,EACXC,WAAW,QACN,YAAY;AACnB,SAEEC,eAAe,QAGV,8BAA8B;AACrC,SAASC,4BAA4B,QAAQ,qBAAqB;AAClE,SAASC,OAAO,QAAQ,sBAAsB;AAC9C,SAASC,8BAA8B,QAAQ,WAAW;AAC1D,SAGEC,YAAY,QACP,iBAAiB;AAExB,oFAAoF,GACpF,OAAO,MAAMC,gCAAgC;IAC3C;QAAEC,MAAM;IAAoC;IAC5C;QAAEA,MAAM;IAAgC;IACxC;QAAEA,MAAM;IAAY;IACpB;QAAEA,MAAM;IAA4B;IACpC;QAAEA,MAAM;IAAc;IACtB;QAAEA,MAAM;IAAsB;IAC9B;QAAEA,MAAM;IAAqB;CAC9B,CAAuD;AAExD,gFAAgF,GAChF,OAAO,MAAMC,mCAAmC;IAC9C;QAAED,MAAM;IAAwB;IAChC;QAAEA,MAAM;IAAiB;CAC1B,CAAuD;AAKxD,mD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connection/agent-connection.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type Tree,\n} from '@nx/devkit';\nimport pyProjectGenerator, {\n getPyProjectDetails,\n} from '../../py/project/generator.js';\nimport tsProjectGenerator from '../../ts/lib/generator.js';\nimport {\n addStarExport,\n appendToArrayViaGritQL,\n applyGritQL,\n matchGritQL,\n} from '../ast.js';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n type MustDeclarePy,\n} from '../declared-dependencies.js';\nimport { addDependenciesToPackageJson } from '../dependencies.js';\nimport { esmVars } from '../module-format.js';\nimport { addDependenciesToPyProjectToml } from '../py.js';\nimport {\n type IPyDepVersion,\n type ITsDepVersion,\n withVersions,\n} from '../versions.js';\n\n/** TypeScript dependencies a caller must declare to emit agent-connection clients. */\nexport const AGENT_CONNECTION_DEPENDENCIES = [\n { name: '@aws-lambda-powertools/parameters' },\n { name: '@aws-sdk/credential-providers' },\n { name: 'aws4fetch' },\n { name: '@modelcontextprotocol/sdk' },\n { name: '@a2a-js/sdk' },\n { name: '@strands-agents/sdk' },\n { name: '@aws-sdk/client-s3' },\n] as const satisfies readonly { name: ITsDepVersion }[];\n\n/** Python dependencies a caller must declare to emit agent-connection clients. */\nexport const AGENT_CONNECTION_PY_DEPENDENCIES = [\n { name: 'aws-lambda-powertools' },\n { name: 'strands-agents' },\n] as const satisfies readonly { name: IPyDepVersion }[];\n\ntype AgentConnectionPyDependency =\n (typeof AGENT_CONNECTION_PY_DEPENDENCIES)[number]['name'];\n\n/** Prefix a GritQL pattern with `language python` */\nconst py = (pattern: string) => `language python\\n${pattern}`;\n\nconst AGENT_CONNECTION_DIR = 'agent-connection';\nconst PACKAGES_DIR = 'packages';\nconst COMMON_DIR = 'common';\n\nexport const AGENT_CONNECTION_PROJECT_DIR = joinPathFragments(\n PACKAGES_DIR,\n COMMON_DIR,\n AGENT_CONNECTION_DIR,\n);\n\nconst PY_AGENT_CONNECTION_NAME = 'agent_connection';\n\n/**\n * Get the directory of the shared Python agent-connection project.\n */\nexport function getPythonAgentConnectionProjectDir(tree: Tree): string {\n const { dir } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return dir;\n}\n\n/**\n * Get the Python module name of the shared agent-connection project.\n */\nexport function getPythonAgentConnectionModuleName(tree: Tree): string {\n const { normalizedModuleName } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return normalizedModuleName;\n}\n\n/**\n * Get the shared agent-connection project as `{ name, root }`, suitable for\n * passing to {@link addWorkspaceDependencyToPyProject} (which derives the\n * dependency's PEP 503 distribution name from the project itself, so callers\n * never construct the name).\n */\nexport function getPythonAgentConnectionProject(tree: Tree): {\n name: string;\n root: string;\n} {\n const { fullyQualifiedName, dir } = getPyProjectDetails(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n return { name: fullyQualifiedName, root: dir };\n}\n\n/**\n * The connection protocols an agent framework can connect over. Each maps to a\n * framework-agnostic Layer-0/1 template directory plus a per-framework Layer-2\n * client directory (see `FRAMEWORKS`).\n */\nexport type ConnectionProtocol = 'mcp' | 'gateway' | 'a2a';\n\n/**\n * The agent frameworks we can generate connection clients for. Adding a new\n * framework is an additive change: append an entry to `FRAMEWORKS` with its\n * Layer-2 template directories and dependencies — the framework-agnostic\n * Layer-0/1 (`core-auth`, `core-shared`, the per-protocol transports/configs)\n * is reused unchanged.\n */\nexport type AgentFramework = 'strands' | 'langchain';\n\n/**\n * Resolve an agent component's framework, defaulting to `strands`. Connection\n * generators dispatch on the returned framework to pick the matching templates\n * and agent.py/agent.ts transforms.\n */\nexport function resolveAgentFramework(\n framework: string | undefined,\n): AgentFramework {\n return framework === 'langchain' ? 'langchain' : 'strands';\n}\n\n/**\n * Framework-agnostic Layer-1 templates, keyed by protocol. These resolve the\n * endpoint and build the signed transport/client-config; they contain no\n * framework dependency.\n */\nconst TS_PROTOCOL_TEMPLATES: Record<ConnectionProtocol, string> = {\n mcp: 'core-mcp',\n gateway: 'core-gateway',\n a2a: 'core-a2a',\n};\nconst PY_PROTOCOL_TEMPLATES: Record<ConnectionProtocol, string> = {\n mcp: 'py-core-mcp',\n gateway: 'py-core-gateway',\n a2a: 'py-core-a2a',\n};\n\n/**\n * A re-export the framework base emits into the agent-connection module's\n * `__init__.py` (the agent server entry point imports these by name).\n */\ninterface BaseReExport {\n fromModule: string;\n importName: string;\n}\n\n/**\n * A framework's Layer-2 templates for one language. `base` (optional) holds the\n * helpers every connection of that framework needs (error logging, per-session\n * agent cache); `baseReExports` lists what those helpers expose at the module\n * root. `protocols` maps each *supported* protocol to the thin client that wraps\n * the matching Layer-1 transport/config in the framework's client type.\n *\n * A framework whose Layer-2 needs no base helpers (e.g. LangChain, whose AG-UI\n * foundation reuses only the framework-agnostic session context) omits `base`\n * and leaves `baseReExports` empty.\n *\n * A protocol absent from `protocols` is not supported by that framework in that\n * language — callers must check before emitting. `deps` are the extra package\n * dependencies the base helpers require (per-connection client deps are added\n * by the connection generators, not here).\n */\ninterface FrameworkLanguageTemplates<Dep extends string> {\n base?: string;\n baseReExports: BaseReExport[];\n protocols: Partial<Record<ConnectionProtocol, string>>;\n deps: Dep[];\n}\n\n/**\n * Per-framework Layer-2 templates. Support is asymmetric by design: a framework\n * may target only one language (`ts`/`py` is optional) and only a subset of\n * protocols. Adding a framework — or extending an existing one to a new\n * language/protocol — is an additive change to this registry.\n */\ninterface FrameworkTemplates {\n ts?: FrameworkLanguageTemplates<string>;\n py?: FrameworkLanguageTemplates<AgentConnectionPyDependency>;\n}\n\nconst FRAMEWORKS: Record<AgentFramework, FrameworkTemplates> = {\n strands: {\n ts: {\n base: 'core-strands/base',\n baseReExports: [\n {\n fromModule: './core/with-session-id-strands.js',\n importName: '*',\n },\n {\n fromModule: './core/model-errors-strands.js',\n importName: '*',\n },\n {\n fromModule: './core/tool-errors-strands.js',\n importName: '*',\n },\n ],\n protocols: {\n mcp: 'core-strands/mcp',\n gateway: 'core-strands/gateway',\n a2a: 'core-strands/a2a',\n },\n deps: [],\n },\n py: {\n base: 'py-core-strands/base',\n baseReExports: [\n {\n fromModule: '.core.with_session_id_strands',\n importName: 'with_session_id',\n },\n {\n fromModule: '.core.model_errors_strands',\n importName: 'log_model_errors',\n },\n {\n fromModule: '.core.tool_errors_strands',\n importName: 'log_tool_errors',\n },\n ],\n protocols: {\n mcp: 'py-core-strands/mcp',\n gateway: 'py-core-strands/gateway',\n a2a: 'py-core-strands/a2a',\n },\n deps: ['strands-agents'],\n },\n },\n langchain: {\n // LangChain is supported for Python agents only (the TypeScript LangChain\n // agent foundation has no in-process AG-UI <-> LangGraph adapter, so it is\n // not scaffolded — see ts#agent). Its Layer-2 clients stay usable after\n // agent construction, so there is no base helper layer (no model-error\n // logger / per-session agent cache) and no strands-agents dependency — its\n // AG-UI foundation reuses only the framework-agnostic session context, and\n // its A2A client drives the a2a SDK directly rather than wrapping Strands'\n // A2AAgent. The per-connection adapter dependency (langchain-mcp-adapters /\n // a2a-sdk) is added by the connection generators.\n py: {\n baseReExports: [],\n protocols: {\n mcp: 'py-core-langchain/mcp',\n gateway: 'py-core-langchain/gateway',\n a2a: 'py-core-langchain/a2a',\n },\n deps: [],\n },\n },\n};\n\n/** Resolve a framework's templates for a language + protocol, or throw. */\nfunction frameworkLanguage<L extends 'ts' | 'py'>(\n framework: AgentFramework,\n language: L,\n protocol: ConnectionProtocol,\n): NonNullable<FrameworkTemplates[L]> & { protocol: string } {\n const lang = FRAMEWORKS[framework][language];\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support ${language === 'ts' ? 'TypeScript' : 'Python'} agents.`,\n );\n }\n const protocolDir = lang.protocols[protocol];\n if (!protocolDir) {\n throw new Error(\n `The '${framework}' framework does not support ${protocol} connections for ${language === 'ts' ? 'TypeScript' : 'Python'} agents.`,\n );\n }\n return { ...lang, protocol: protocolDir } as NonNullable<\n FrameworkTemplates[L]\n > & { protocol: string };\n}\n\n/** Protocols whose Layer-1 needs the shared MCP transport (`core-shared`). */\nconst MCP_TRANSPORT_PROTOCOLS: ConnectionProtocol[] = ['mcp', 'gateway'];\n\nconst tsCoreDir = () =>\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'core');\n\n/**\n * Runtime dependencies each TypeScript core template directory imports. Emitting\n * a template also declares its dependencies in the agent-connection project's\n * package.json so the `noUndeclaredDependencies` lint rule passes.\n */\nconst TS_TEMPLATE_DEPS: Record<\n string,\n (typeof AGENT_CONNECTION_DEPENDENCIES)[number]['name'][]\n> = {\n 'core-runtime-config': ['@aws-lambda-powertools/parameters'],\n 'core-auth': ['@aws-sdk/credential-providers', 'aws4fetch'],\n 'core-shared': ['@aws-sdk/credential-providers', '@modelcontextprotocol/sdk'],\n 'core-mcp': ['@aws-sdk/credential-providers', '@modelcontextprotocol/sdk'],\n 'core-gateway': [\n '@aws-sdk/credential-providers',\n '@modelcontextprotocol/sdk',\n ],\n 'core-a2a': ['@aws-sdk/credential-providers', '@a2a-js/sdk'],\n 'core-strands/base': ['@strands-agents/sdk', '@aws-sdk/client-s3'],\n 'core-strands/mcp': ['@strands-agents/sdk', '@aws-sdk/client-s3'],\n 'core-strands/gateway': ['@strands-agents/sdk', '@aws-sdk/client-s3'],\n 'core-strands/a2a': ['@strands-agents/sdk', '@aws-sdk/client-s3'],\n};\n\nconst emitTs = (\n tree: Tree,\n templateDir: string,\n declaration: DependencyDeclaration,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', templateDir),\n tsCoreDir(),\n { ...esmVars(tree) },\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n const deps = TS_TEMPLATE_DEPS[templateDir];\n if (deps?.length) {\n addDependenciesToPackageJson(\n tree,\n withVersions(\n forDependencies<typeof AGENT_CONNECTION_DEPENDENCIES>(declaration),\n deps,\n ),\n {},\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'package.json'),\n );\n }\n};\n\n/**\n * Ensure the shared TypeScript agent-connection project exists and has the\n * framework-agnostic core helpers (runtime-config loader, session context).\n * Per-connection generators emit their own protocol + framework client\n * templates via `addTypeScriptCoreClient`.\n */\nexport async function ensureTypeScriptAgentConnectionProject<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n): Promise<void> {\n const projectJsonPath = joinPathFragments(\n AGENT_CONNECTION_PROJECT_DIR,\n 'project.json',\n );\n if (!tree.exists(projectJsonPath)) {\n await tsProjectGenerator(tree, {\n name: AGENT_CONNECTION_DIR,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n });\n }\n\n // Framework-agnostic runtime-config + session-context helpers.\n emitTs(tree, 'core-runtime-config', declaration);\n\n // Re-export session-context helpers so agent server entry points can set the\n // current session on each inbound request without pulling in internals.\n await addStarExport(\n tree,\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'index.ts'),\n './core/session-context.js',\n );\n\n // Re-export the runtime-config loader so agent server entry points can read\n // their own connected resources (e.g. session storage) without pulling in\n // internals.\n await addStarExport(\n tree,\n joinPathFragments(AGENT_CONNECTION_PROJECT_DIR, 'src', 'index.ts'),\n './core/runtime-config.js',\n );\n}\n\n/**\n * Emit a framework's base Layer-2 helpers (model-error logging + per-session\n * agent cache) into the agent-connection project and re-export them. The agent\n * server entry point imports these regardless of whether any connection client\n * is wired in, so the agent generator calls this directly; connection\n * generators call it transitively via `addTypeScriptCoreClient`.\n */\nexport async function addTypeScriptFrameworkBase<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const lang = FRAMEWORKS[framework].ts;\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support TypeScript agents.`,\n );\n }\n if (lang.base) {\n emitTs(tree, lang.base, declaration);\n }\n\n const indexPath = joinPathFragments(\n AGENT_CONNECTION_PROJECT_DIR,\n 'src',\n 'index.ts',\n );\n for (const reExport of lang.baseReExports) {\n await addStarExport(tree, indexPath, reExport.fromModule);\n }\n}\n\n/**\n * Emit the TypeScript client templates for a connection protocol and agent\n * framework into the agent-connection project's `src/core/` directory. Safe to\n * call multiple times — `KeepExisting` preserves customised files.\n *\n * Layers emitted:\n * - Layer 0 `core-auth` (signed fetch + endpoint resolution) — always\n * - Layer 1 `core-shared` MCP transport — for mcp/gateway protocols\n * - Layer 1 the protocol's transport/client-config — always\n * - Layer 2 the framework's base helpers + protocol client — per framework\n */\nexport async function addTypeScriptCoreClient<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n protocol: ConnectionProtocol,\n declaration: D & MustDeclare<typeof AGENT_CONNECTION_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const fw = frameworkLanguage(framework, 'ts', protocol);\n\n emitTs(tree, 'core-auth', declaration);\n if (MCP_TRANSPORT_PROTOCOLS.includes(protocol)) {\n emitTs(tree, 'core-shared', declaration);\n }\n emitTs(tree, TS_PROTOCOL_TEMPLATES[protocol], declaration);\n\n // Framework Layer 2: base helpers (re-exported for the agent server) + the\n // thin protocol client.\n await addTypeScriptFrameworkBase(\n tree,\n forDependencies<typeof AGENT_CONNECTION_DEPENDENCIES>(declaration),\n framework,\n );\n emitTs(tree, fw.protocol, declaration);\n}\n\n/**\n * Ensure the shared Python agent-connection project exists.\n * Only creates the project shell — per-connection generators are responsible\n * for emitting their own core client templates.\n */\nexport async function ensurePythonAgentConnectionProject<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n): Promise<void> {\n const projectDir = getPythonAgentConnectionProjectDir(tree);\n const moduleName = getPythonAgentConnectionModuleName(tree);\n const projectJsonPath = joinPathFragments(projectDir, 'project.json');\n\n if (!tree.exists(projectJsonPath)) {\n // Create the Python project using the standard py#project generator\n await pyProjectGenerator(tree, {\n name: PY_AGENT_CONNECTION_NAME,\n directory: joinPathFragments(PACKAGES_DIR, COMMON_DIR),\n type: 'library',\n });\n }\n\n const moduleDir = joinPathFragments(projectDir, moduleName);\n\n // Ensure core/__init__.py exists\n const coreDir = joinPathFragments(moduleDir, 'core');\n if (!tree.exists(joinPathFragments(coreDir, '__init__.py'))) {\n tree.write(joinPathFragments(coreDir, '__init__.py'), '');\n }\n\n // Ensure app/__init__.py exists\n const appInitPath = joinPathFragments(moduleDir, 'app', '__init__.py');\n if (!tree.exists(appInitPath)) {\n tree.write(appInitPath, '');\n }\n\n // Framework-agnostic runtime-config + session-context helpers.\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'py-core-runtime-config'),\n coreDir,\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Re-export the session id context so agent server entry points can set the\n // current session on each inbound request without importing internals.\n const moduleInitPath = joinPathFragments(moduleDir, '__init__.py');\n await addPythonReExport(\n tree,\n moduleInitPath,\n '.core.session_context',\n 'get_current_session_id',\n );\n await addPythonReExport(\n tree,\n moduleInitPath,\n '.core.session_context',\n 'session_id_context',\n );\n\n // The runtime-config loader reads AppConfig via aws-lambda-powertools.\n addDependenciesToPyProjectToml(\n tree,\n projectDir,\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n ['aws-lambda-powertools'],\n );\n}\n\nconst pyCoreDir = (tree: Tree) =>\n joinPathFragments(\n getPythonAgentConnectionProjectDir(tree),\n getPythonAgentConnectionModuleName(tree),\n 'core',\n );\n\nconst emitPy = (tree: Tree, templateDir: string) =>\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', templateDir),\n pyCoreDir(tree),\n {},\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n/**\n * Ensure the shared Python agent-connection project has\n * `s3_checkpoint_saver_langchain.py` — a vendored `S3CheckpointSaver`\n * (from `langgraph-checkpoint-s3`, MIT licensed) that LangChain agents with\n * `session: 's3'` import from directly (`.core.s3_checkpoint_saver_langchain`),\n * mirroring how they import `.core.runtime_config`. Vendored rather than\n * installed as a dependency, and shared rather than per-agent, since it has\n * no agent-specific templating.\n */\nexport function ensureLangchainS3CheckpointSaver(tree: Tree): void {\n emitPy(tree, 'py-core-langchain/s3');\n}\n\n/**\n * Emit a framework's base Layer-2 helpers (model-error logging + per-session\n * agent cache) into the Python agent-connection project and re-export them.\n * The agent server entry point imports these regardless of whether a connection\n * client is wired in, so the agent generator calls this directly; connection\n * generators call it transitively via `addPythonCoreClient`.\n */\nexport async function addPythonFrameworkBase<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const lang = FRAMEWORKS[framework].py;\n if (!lang) {\n throw new Error(\n `The '${framework}' framework does not support Python agents.`,\n );\n }\n if (lang.base) {\n emitPy(tree, lang.base);\n }\n\n const moduleInitPath = joinPathFragments(\n getPythonAgentConnectionProjectDir(tree),\n getPythonAgentConnectionModuleName(tree),\n '__init__.py',\n );\n for (const reExport of lang.baseReExports) {\n await addPythonReExport(\n tree,\n moduleInitPath,\n reExport.fromModule,\n reExport.importName,\n );\n }\n\n if (lang.deps.length > 0) {\n addDependenciesToPyProjectToml(\n tree,\n getPythonAgentConnectionProjectDir(tree),\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n lang.deps,\n );\n }\n}\n\n/**\n * Emit the Python client templates for a connection protocol and agent\n * framework into the agent-connection project's core directory.\n *\n * Layers emitted:\n * - Layer 0 `py-core-auth` (SigV4 httpx.Auth, session auth, endpoints) — always\n * - Layer 1 `py-core-shared` MCP transport — for mcp/gateway protocols\n * - Layer 1 the protocol's transport/client-config — always\n * - Layer 2 the framework's base helpers + protocol client — per framework\n */\nexport async function addPythonCoreClient<\n const D extends DependencyDeclaration,\n>(\n tree: Tree,\n protocol: ConnectionProtocol,\n declaration: D & MustDeclarePy<typeof AGENT_CONNECTION_PY_DEPENDENCIES, D>,\n framework: AgentFramework = 'strands',\n): Promise<void> {\n const fw = frameworkLanguage(framework, 'py', protocol);\n\n emitPy(tree, 'py-core-auth');\n if (MCP_TRANSPORT_PROTOCOLS.includes(protocol)) {\n emitPy(tree, 'py-core-shared');\n }\n emitPy(tree, PY_PROTOCOL_TEMPLATES[protocol]);\n\n // Framework Layer 2: base helpers + the thin protocol client.\n await addPythonFrameworkBase(\n tree,\n forDependencies<[], typeof AGENT_CONNECTION_PY_DEPENDENCIES>(declaration),\n framework,\n );\n emitPy(tree, fw.protocol);\n}\n\n/**\n * Patch a TypeScript agent.ts to create a connection client and register it\n * in the Agent's tools. Used by the MCP and gateway connection generators —\n * the client class must expose a static async `create()` returning a value\n * accepted by `Agent.tools` (e.g. an `McpClient`).\n */\nexport async function addTypeScriptClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n const clientCreationStmt = `const ${clientVarName} = await ${clientClassName}.create();`;\n\n // Transform the arrow function that contains `new Agent`:\n // - Expression body: wrap in block with client creation and return\n // - Block body: prepend client creation statement\n await applyGritQL(\n tree,\n agentFilePath,\n `or { \\`async ($p) => new Agent($args)\\` => raw\\`async ($p) => {\n ${clientCreationStmt}\n return new Agent($args);\n}\\` where { $program <: not contains \\`${clientClassName}.create\\` }, \\`async ($p) => { $body }\\` => raw\\`async ($p) => {\n ${clientCreationStmt}\n $body\n}\\` where { $body <: contains \\`new Agent($_)\\`, $program <: not contains \\`${clientClassName}.create\\` } }`,\n );\n\n // Prepend the client to the tools array\n await applyGritQL(\n tree,\n agentFilePath,\n `\\`tools: [$items]\\` => \\`tools: [${clientVarName}, $items]\\` where { $items <: within \\`new Agent($_)\\`, $items <: not contains \\`${clientVarName}\\` }`,\n );\n}\n\n/**\n * Patch a Python agent.py to create a context-managed connection client,\n * enter it in the `with` block around `yield Agent(...)`, and spread its\n * `list_tools_sync()` into the Agent's tools. Used by the MCP and gateway\n * connection generators — the client class must expose a static `create()`\n * returning a context manager with `list_tools_sync()` (e.g. an `MCPClient`).\n */\nasync function addPythonClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n await addPythonClientTools(tree, agentFilePath, clientVarName);\n await addPythonClientToGetAgent(\n tree,\n agentFilePath,\n clientClassName,\n clientVarName,\n );\n}\n\n/**\n * Append `*<clientVarName>.list_tools_sync()` to the Agent's tools list.\n */\nconst addPythonClientTools = async (\n tree: Tree,\n filePath: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(\n tree,\n filePath,\n py(`\\`${clientVarName}.list_tools_sync()\\``),\n )\n ) {\n return;\n }\n\n await appendToArrayViaGritQL(\n tree,\n filePath,\n 'tools=',\n `*${clientVarName}.list_tools_sync()`,\n { skipIfContains: clientVarName, language: 'py' },\n );\n};\n\n/**\n * Create the client in get_agent and enter it in the `with` block.\n *\n * First connection: rewrites `def get_agent` to wrap the body in a with\n * block. Subsequent connections: adds to the existing with items and\n * prepends the creation line.\n */\nconst addPythonClientToGetAgent = async (\n tree: Tree,\n filePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(tree, filePath, py(`\\`${clientClassName}.create()\\``))\n ) {\n return;\n }\n\n // Try the \"add to existing with block\" pattern first.\n // If it succeeds, there was already a with block from a previous connection.\n const addedToWith = await applyGritQL(\n tree,\n filePath,\n py(`\\`with ($items,): $body\\` where {\n $items <: not contains \\`${clientVarName}\\`,\n $items += \\`, ${clientVarName}\\`\n}`),\n );\n\n if (addedToWith) {\n // Subsequent connection — prepend the creation line to the function body\n // (a single anchor, so the line is inserted exactly once).\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`yield Agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n $body\\``),\n );\n return;\n }\n\n // First connection — wrap the existing `def get_agent` body in a single\n // `with (<var>,):` block.\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`yield Agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n with (\n ${clientVarName},\n ):\n $body\\``),\n );\n};\n\n/**\n * Patch a LangChain agent.py to load connection tools and spread them into the\n * `create_agent(...)` tools list. Used by the MCP and gateway connection\n * generators when the source agent uses the `langchain` framework — the client\n * class must expose a static `create()` returning a `list[BaseTool]`. The tools\n * come from langchain-mcp-adapters' `MultiServerMCPClient`, which keeps the\n * connection config on each tool and opens a fresh MCP session per call, so the\n * tools stay usable after `get_agent` returns — no `with` block is needed.\n * Mirrors {@link addPythonClientToAgent} for the Strands shape.\n */\nasync function addPythonLangchainClientToAgent(\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> {\n await addPythonLangchainClientTools(tree, agentFilePath, clientVarName);\n await addPythonLangchainClientToGetAgent(\n tree,\n agentFilePath,\n clientClassName,\n clientVarName,\n );\n}\n\n/**\n * Spread `*<clientVarName>` into the `create_agent(...)` tools list.\n *\n * Scoped via `$old <: within \\`create_agent($_)\\`` so only the agent's own\n * tools= keyword argument is touched (not an unrelated function with a\n * `tools=` parameter).\n */\nconst addPythonLangchainClientTools = async (\n tree: Tree,\n filePath: string,\n clientVarName: string,\n): Promise<void> => {\n await applyGritQL(\n tree,\n filePath,\n py(`\\`tools=$old\\` where {\n $old <: within \\`create_agent($_)\\`,\n $old <: not contains \\`*${clientVarName}\\`,\n if ($old <: \\`[]\\`) {\n $old => \\`[*${clientVarName}]\\`\n } else {\n $old <: \\`[$items]\\` where { $items += \\`, *${clientVarName}\\` }\n }\n}`),\n );\n};\n\n/**\n * Prepend `<clientVarName> = <clientClassName>.create()` to the get_agent body\n * (which loads the connection's tools). No `with` block — the LangChain client\n * hands langchain-mcp-adapters a connection config, so each tool opens its own\n * MCP session per call and the tools are safe to use after get_agent returns.\n * Idempotent via the `not contains <clientClassName>.create` guard.\n */\nconst addPythonLangchainClientToGetAgent = async (\n tree: Tree,\n filePath: string,\n clientClassName: string,\n clientVarName: string,\n): Promise<void> => {\n if (\n await matchGritQL(tree, filePath, py(`\\`${clientClassName}.create()\\``))\n ) {\n return;\n }\n\n await applyGritQL(\n tree,\n filePath,\n py(`\\`def get_agent($params):\n $body\\` where {\n $body <: contains \\`create_agent($_)\\`,\n $body <: not contains \\`${clientClassName}.create\\`\n} => \\`def get_agent($params):\n ${clientVarName} = ${clientClassName}.create()\n $body\\``),\n );\n};\n\n/**\n * Per-framework naming + template layout for a Python per-connection client.\n * Every py#agent connection generator (mcp, gateway, a2a) names its client\n * class `<Name>Client<suffix>`, its module `<name>_client_<suffix>`, and reads\n * the per-connection app-client template from a per-framework sub-path of its\n * own `files/` dir — all of which vary only by framework, so they live here as\n * one source of truth.\n *\n * Keyed by {@link AgentFramework} rather than a boolean so a third framework is\n * an additive entry here — never another `if (isLangchain)` branch in each\n * generator.\n */\nexport interface PyClientNaming {\n /** Class-name suffix on the per-connection app client (`<Name>Client<suffix>`). */\n clientClassSuffix: string;\n /** Module/file-name suffix on the per-connection app client (`<name>_client_<suffix>`). */\n clientModuleSuffix: string;\n /**\n * Sub-path, under a connection generator's `files/` dir, of the per-connection\n * app client template for this framework. Every connection generator lays its\n * templates out the same way, so this resolves against any of them.\n */\n appTemplateSubdir: string;\n}\n\nexport const PY_CLIENT_NAMING: Record<AgentFramework, PyClientNaming> = {\n strands: {\n clientClassSuffix: 'Strands',\n clientModuleSuffix: 'strands',\n appTemplateSubdir: joinPathFragments('agent-connection', 'app'),\n },\n langchain: {\n clientClassSuffix: 'LangChain',\n clientModuleSuffix: 'langchain',\n appTemplateSubdir: joinPathFragments(\n 'langchain',\n 'agent-connection',\n 'app',\n ),\n },\n};\n\n/**\n * How an MCP-family connection (an MCP server or an AgentCore Gateway, both of\n * which expose tools over MCP) is wired into a Python agent of a given\n * framework. The mcp-connection and gateway-connection generators share this:\n * they differ only in the metadata of the thing being connected, not in how\n * the framework's client is shaped or spliced into agent.py. A2A connections\n * wire tools differently, so they reuse only {@link PY_CLIENT_NAMING}.\n */\nexport interface PyMcpFamilyConnection extends PyClientNaming {\n /** Extra Python deps this framework's MCP-family client needs (beyond the shared transport). */\n deps: IPyDepVersion[];\n /**\n * Splice the per-connection client into the agent's `get_agent` in agent.py.\n * Strands enters a context-managed `MCPClient` and spreads `list_tools_sync()`;\n * LangChain loads `BaseTool`s and spreads them into `create_agent(...)`.\n */\n wireClientIntoAgent: (\n tree: Tree,\n agentFilePath: string,\n clientClassName: string,\n clientVarName: string,\n ) => Promise<void>;\n}\n\nexport const PY_MCP_FAMILY_CONNECTIONS: Record<\n AgentFramework,\n PyMcpFamilyConnection\n> = {\n strands: {\n ...PY_CLIENT_NAMING.strands,\n deps: [],\n wireClientIntoAgent: addPythonClientToAgent,\n },\n langchain: {\n ...PY_CLIENT_NAMING.langchain,\n // langchain-mcp-adapters backs the LangChain client; it must not pull Strands in.\n deps: ['langchain-mcp-adapters'],\n wireClientIntoAgent: addPythonLangchainClientToAgent,\n },\n};\n\n/**\n * Add a re-export to the Python agent-connection module's __init__.py.\n * Equivalent to addStarExport for TS, including creating the file when it does\n * not yet exist in the tree.\n * Uses `__all__` to mark re-exports as public (satisfies ruff F401).\n * Uses GritQL for AST-aware transforms where possible.\n */\nexport async function addPythonReExport(\n tree: Tree,\n initFilePath: string,\n fromModule: string,\n importName: string,\n): Promise<void> {\n // Check if already exported\n if (await matchGritQL(tree, initFilePath, `\\`${importName}\\``)) {\n return;\n }\n\n const importLine = `from ${fromModule} import ${importName}`;\n const allEntry = `\"${importName}\"`;\n\n if (!tree.exists(initFilePath)) {\n tree.write(initFilePath, `${importLine}\\n\\n__all__ = [${allEntry}]\\n`);\n return;\n }\n\n // If there's already an import from the same module, merge into its name list\n // (ruff I001 rejects two `from X import ...` lines for the same module).\n const mergedImport = await applyGritQL(\n tree,\n initFilePath,\n py(`\\`from ${fromModule} import $names\\` where {\n $names <: not contains \\`${importName}\\`,\n $names += \\`, ${importName}\\`\n}`),\n );\n\n if (mergedImport) {\n await applyGritQL(\n tree,\n initFilePath,\n py(`\\`__all__ = [$items]\\` where { $items += \\`, ${allEntry}\\` }`),\n );\n return;\n }\n\n // Try to append import after existing import using +=\n const appendedImport = await applyGritQL(\n tree,\n initFilePath,\n py(\n `\\`from $mod import $name\\` as $stmt where {\n $program <: not contains \\`${importName}\\`,\n $stmt += \\`\\n${importLine}\\`\n}`,\n ),\n );\n\n if (appendedImport) {\n // Also append to existing __all__\n await applyGritQL(\n tree,\n initFilePath,\n py(`\\`__all__ = [$items]\\` where { $items += \\`, ${allEntry}\\` }`),\n );\n return;\n }\n\n // No existing imports — first re-export. Try to anchor after docstring.\n const anchoredImport = await applyGritQL(\n tree,\n initFilePath,\n py(\n `\\`\"\"\"Automatically generated by Nx.\"\"\"\\` as $doc => \\`$doc\\n${importLine}\\n\\n__all__ = [${allEntry}]\\``,\n ),\n );\n\n if (!anchoredImport) {\n // Completely empty file or no docstring — write directly\n tree.write(initFilePath, `${importLine}\\n\\n__all__ = [${allEntry}]\\n`);\n }\n}\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","pyProjectGenerator","getPyProjectDetails","tsProjectGenerator","addStarExport","appendToArrayViaGritQL","applyGritQL","matchGritQL","forDependencies","addDependenciesToPackageJson","esmVars","addDependenciesToPyProjectToml","withVersions","AGENT_CONNECTION_DEPENDENCIES","name","AGENT_CONNECTION_PY_DEPENDENCIES","py","pattern","AGENT_CONNECTION_DIR","PACKAGES_DIR","COMMON_DIR","AGENT_CONNECTION_PROJECT_DIR","PY_AGENT_CONNECTION_NAME","getPythonAgentConnectionProjectDir","tree","dir","directory","getPythonAgentConnectionModuleName","normalizedModuleName","getPythonAgentConnectionProject","fullyQualifiedName","root","resolveAgentFramework","framework","TS_PROTOCOL_TEMPLATES","mcp","gateway","a2a","PY_PROTOCOL_TEMPLATES","FRAMEWORKS","strands","ts","base","baseReExports","fromModule","importName","protocols","deps","langchain","frameworkLanguage","language","protocol","lang","Error","protocolDir","MCP_TRANSPORT_PROTOCOLS","tsCoreDir","TS_TEMPLATE_DEPS","emitTs","templateDir","declaration","dirname","overwriteStrategy","KeepExisting","length","ensureTypeScriptAgentConnectionProject","projectJsonPath","exists","addTypeScriptFrameworkBase","indexPath","reExport","addTypeScriptCoreClient","fw","includes","ensurePythonAgentConnectionProject","projectDir","moduleName","type","moduleDir","coreDir","write","appInitPath","moduleInitPath","addPythonReExport","pyCoreDir","emitPy","ensureLangchainS3CheckpointSaver","addPythonFrameworkBase","addPythonCoreClient","addTypeScriptClientToAgent","agentFilePath","clientClassName","clientVarName","clientCreationStmt","addPythonClientToAgent","addPythonClientTools","addPythonClientToGetAgent","filePath","skipIfContains","addedToWith","addPythonLangchainClientToAgent","addPythonLangchainClientTools","addPythonLangchainClientToGetAgent","PY_CLIENT_NAMING","clientClassSuffix","clientModuleSuffix","appTemplateSubdir","PY_MCP_FAMILY_CONNECTIONS","wireClientIntoAgent","initFilePath","importLine","allEntry","mergedImport","appendedImport","anchoredImport"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,QAEZ,aAAa;AACpB,OAAOC,sBACLC,mBAAmB,QACd,gCAAgC;AACvC,OAAOC,wBAAwB,4BAA4B;AAC3D,SACEC,aAAa,EACbC,sBAAsB,EACtBC,WAAW,EACXC,WAAW,QACN,YAAY;AACnB,SAEEC,eAAe,QAGV,8BAA8B;AACrC,SAASC,4BAA4B,QAAQ,qBAAqB;A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AI,CAAC;QAEnE;IACF;IAEA,sDAAsD;IACtD,MAAME,iBAAiB,MAAM3G,YAC3BkB,MACAqF,cACA7F,GACE,CAAC;6BACsB,EAAE6B,WAAW;eAC3B,EAAEiE,WAAW;CAC3B,CAAC;IAIA,IAAIG,gBAAgB;QAClB,kCAAkC;QAClC,MAAM3G,YACJkB,MACAqF,cACA7F,GAAG,CAAC,6CAA6C,EAAE+F,SAAS,IAAI,CAAC;QAEnE;IACF;IAEA,wEAAwE;IACxE,MAAMG,iBAAiB,MAAM5G,YAC3BkB,MACAqF,cACA7F,GACE,CAAC,4DAA4D,EAAE8F,WAAW,eAAe,EAAEC,SAAS,GAAG,CAAC;IAI5G,IAAI,CAACG,gBAAgB;QACnB,yDAAyD;QACzD1F,KAAKwD,KAAK,CAAC6B,cAAc,GAAGC,WAAW,eAAe,EAAEC,SAAS,GAAG,CAAC;IACvE;AACF"}
@@ -7,9 +7,13 @@ import * as url from 'node:url';
7
7
  import { GatewayAuthorizer } from 'aws-cdk-lib/aws-bedrockagentcore';
8
8
  import { IUserPool, IUserPoolClient } from 'aws-cdk-lib/aws-cognito';
9
9
  <%_ } _%>
10
+ <%_ /* Alias the core imports only when this gateway's name would shadow them. */ _%>
11
+ <%_ const collides = ['AgentCoreGateway', 'AgentCoreGatewayProps'].includes(nameClassName); _%>
12
+ <%_ const coreGateway = collides ? 'CoreAgentCoreGateway' : 'AgentCoreGateway'; _%>
13
+ <%_ const coreGatewayProps = collides ? 'CoreAgentCoreGatewayProps' : 'AgentCoreGatewayProps'; _%>
10
14
  import {
11
- AgentCoreGateway,
12
- AgentCoreGatewayProps,
15
+ AgentCoreGateway<% if (collides) { %> as <%= coreGateway %><% } %>,
16
+ AgentCoreGatewayProps<% if (collides) { %> as <%= coreGatewayProps %><% } %>,
13
17
  } from '../../../core/agentcore-gateway/agentcore-gateway<% if (esm) { %>.js<% } %>';
14
18
  import { RuntimeConfig } from '../../../core/runtime-config<% if (esm) { %>.js<% } %>';
15
19
  <%_ if (cedarPolicy) { _%>
@@ -18,7 +22,7 @@ import { findWorkspaceRoot } from '../../../core/workspace<% if (esm) { %>.js<%
18
22
 
19
23
  <%_ if (auth === 'cognito') { _%>
20
24
  export type <%- nameClassName %>Props = Omit<
21
- AgentCoreGatewayProps,
25
+ <%= coreGatewayProps %>,
22
26
  <%_ if (cedarPolicy) { _%>'cedarPolicyPath' | <%_ } _%>'authorizer' | 'protocol'
23
27
  > & {
24
28
  /**
@@ -31,9 +35,9 @@ export type <%- nameClassName %>Props = Omit<
31
35
  };
32
36
  };
33
37
  <%_ } else if (cedarPolicy) { _%>
34
- export type <%- nameClassName %>Props = Omit<AgentCoreGatewayProps, 'cedarPolicyPath' | 'protocol'>;
38
+ export type <%- nameClassName %>Props = Omit<<%= coreGatewayProps %>, 'cedarPolicyPath' | 'protocol'>;
35
39
  <%_ } else { _%>
36
- export type <%- nameClassName %>Props = Omit<AgentCoreGatewayProps, 'protocol'>;
40
+ export type <%- nameClassName %>Props = Omit<<%= coreGatewayProps %>, 'protocol'>;
37
41
  <%_ } _%>
38
42
 
39
43
  /**
@@ -44,7 +48,7 @@ export type <%- nameClassName %>Props = Omit<AgentCoreGatewayProps, 'protocol'>;
44
48
  * at synth time and attached to a PolicyEngine running in ENFORCE mode.
45
49
  <%_ } _%>
46
50
  */
47
- export class <%- nameClassName %> extends AgentCoreGateway {
51
+ export class <%- nameClassName %> extends <%= coreGateway %> {
48
52
  /** Default Gateway target name when added to another Gateway. */
49
53
  public readonly gatewayName = '<%- nameKebabCase %>';
50
54
 
@@ -81,7 +85,7 @@ export class <%- nameClassName %> extends AgentCoreGateway {
81
85
  const rc = RuntimeConfig.ensure(this);
82
86
  rc.set('agentcore', 'gateways', {
83
87
  ...rc.get('agentcore').gateways,
84
- <%- nameClassName %>: this.gateway.gatewayUrl,
88
+ <%- nameClassName %>: this.gatewayUrl,
85
89
  });
86
90
  }
87
91
  }
@@ -279,6 +279,18 @@ export class AgentCoreGateway extends Construct implements iam.IGrantable {
279
279
  return webAcl;
280
280
  }
281
281
 
282
+ /**
283
+ * The gateway's URL endpoint. The Gateway L2 types its own `gatewayUrl` as
284
+ * optional and only populates it when created from its own props, so fall
285
+ * back to the CloudFormation attribute.
286
+ */
287
+ public get gatewayUrl(): string {
288
+ return (
289
+ this.gateway.gatewayUrl ??
290
+ (this.gateway.node.defaultChild as agentcore.CfnGateway).attrGatewayUrl
291
+ );
292
+ }
293
+
282
294
  /**
283
295
  * The principal to grant permissions to.
284
296
  */
@@ -395,6 +407,7 @@ export class AgentCoreGateway extends Construct implements iam.IGrantable {
395
407
  gateway: Construct & {
396
408
  readonly gateway: agentcore.Gateway;
397
409
  readonly gatewayName: string;
410
+ readonly gatewayUrl: string;
398
411
  },
399
412
  props?: {
400
413
  gatewayTargetName?: string;
@@ -402,12 +415,7 @@ export class AgentCoreGateway extends Construct implements iam.IGrantable {
402
415
  ): agentcore.CfnGatewayTarget {
403
416
  const target = this.addGatewayTarget({
404
417
  gatewayTargetName: props?.gatewayTargetName ?? gateway.gatewayName,
405
- // The Gateway L2 only populates gatewayUrl when created from its own
406
- // props; fall back to the CloudFormation attribute otherwise.
407
- gatewayUrl:
408
- gateway.gateway.gatewayUrl ??
409
- (gateway.gateway.node.defaultChild as agentcore.CfnGateway)
410
- .attrGatewayUrl,
418
+ gatewayUrl: gateway.gatewayUrl,
411
419
  gatewayArn: gateway.gateway.gatewayArn,
412
420
  });
413
421
  // AgentCore fetches the target gateway's tools during target creation,
@@ -4,7 +4,7 @@
4
4
  */ import { joinPathFragments } from "@nx/devkit";
5
5
  import { forDependencies } from "./declared-dependencies.js";
6
6
  import { FS_DEPENDENCIES, FsCommands } from "./fs.js";
7
- import { addArtifactDependencyToTargets } from "./nx.js";
7
+ import { addArtifactDependencyToTargets, normalizeTargetKeyOrder } from "./nx.js";
8
8
  import { agentCoreRuntime, TS_VERSIONS } from "./versions.js";
9
9
  /**
10
10
  * How an AgentCore Runtime's artifact is packaged and hosted.
@@ -93,7 +93,7 @@ import { agentCoreRuntime, TS_VERSIONS } from "./versions.js";
93
93
  parallel: false
94
94
  }
95
95
  };
96
- project.targets[targetName] = {
96
+ project.targets[targetName] = normalizeTargetKeyOrder({
97
97
  cache: true,
98
98
  inputs: [
99
99
  'default'
@@ -115,7 +115,7 @@ import { agentCoreRuntime, TS_VERSIONS } from "./versions.js";
115
115
  bundleTargetName,
116
116
  ADOT_VENDOR_TARGET_NAME
117
117
  ]
118
- };
118
+ });
119
119
  addArtifactDependencyToTargets(project, targetName);
120
120
  };
121
121
  /**
@@ -137,7 +137,7 @@ import { agentCoreRuntime, TS_VERSIONS } from "./versions.js";
137
137
  const { project, targetName, bundleTargetName, bundleOutputDir, packageOutputDir, sourceRoot, moduleName, entryPointPath, entryPointFileName } = options;
138
138
  const fs = new FsCommands(tree, forDependencies(declaration));
139
139
  project.targets ??= {};
140
- project.targets[targetName] = {
140
+ project.targets[targetName] = normalizeTargetKeyOrder({
141
141
  cache: true,
142
142
  inputs: [
143
143
  'production',
@@ -160,7 +160,7 @@ import { agentCoreRuntime, TS_VERSIONS } from "./versions.js";
160
160
  dependsOn: [
161
161
  bundleTargetName
162
162
  ]
163
- };
163
+ });
164
164
  addArtifactDependencyToTargets(project, targetName);
165
165
  };
166
166