@aws/nx-plugin 1.0.0-rc.60 → 1.0.0-rc.62

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 (75) hide show
  1. package/migrations.json +36 -26
  2. package/package.json +1 -1
  3. package/src/mcp-server/tools/general-guidance.js +1 -1
  4. package/src/mcp-server/tools/general-guidance.js.map +1 -1
  5. package/src/migrations/latest/py-agent-lifespan-construction/metadata.json +3 -0
  6. package/src/migrations/latest/py-agent-lifespan-construction/migration.js +412 -0
  7. package/src/migrations/latest/py-agent-lifespan-construction/migration.js.map +1 -0
  8. package/src/migrations/latest/rename-load-runtime-config-target/metadata.json +3 -0
  9. package/src/migrations/latest/rename-load-runtime-config-target/migration.js +33 -0
  10. package/src/migrations/latest/rename-load-runtime-config-target/migration.js.map +1 -0
  11. package/src/migrations/v1.0.0-rc.50/0001-modernize-function-props-cast/migration.js.map +1 -0
  12. package/src/migrations/v1.0.0-rc.50/0002-restrict-cors-to-custom-domains/migration.js.map +1 -0
  13. package/src/migrations/v1.0.0-rc.50/0003-terraform-bootstrap-adopt-existing-bucket/migration.d.ts +6 -0
  14. package/src/migrations/v1.0.0-rc.50/0003-terraform-bootstrap-adopt-existing-bucket/migration.js.map +1 -0
  15. package/src/migrations/v1.0.0-rc.52/0001-user-identity-waf-allow-localhost-callback/migration.js.map +1 -0
  16. package/src/migrations/v1.0.0-rc.54/0001-order-access-log-delivery-after-bucket-policy/migration.js.map +1 -0
  17. package/src/migrations/v1.0.0-rc.55/0001-backfill-generator-metadata/migration.js.map +1 -0
  18. package/src/migrations/v1.0.0-rc.56/0001-dynamodb-local-remove-optimize-flag/migration.js.map +1 -0
  19. package/src/migrations/v1.0.0-rc.57/0001-ts-agent-session-management-support/migration.d.ts +6 -0
  20. package/src/migrations/v1.0.0-rc.57/0001-ts-agent-session-management-support/migration.js.map +1 -0
  21. package/src/py/agent/__snapshots__/generator.constructs.spec.ts.snap +2 -10
  22. package/src/py/agent/__snapshots__/generator.frameworks.spec.ts.snap +12 -8
  23. package/src/py/agent/files/{ag-ui-langchain → langchain/ag-ui}/main.py.template +12 -8
  24. package/src/py/agent/files/{http → langchain/http}/init.py.template +10 -0
  25. package/src/py/agent/files/{http-langchain → langchain/http}/main.py.template +1 -4
  26. package/src/py/agent/files/strands/ag-ui/main.py.template +89 -0
  27. package/src/py/agent/files/strands/http/init.py.template +97 -0
  28. package/src/py/agent/files/{http → strands/http}/main.py.template +2 -10
  29. package/src/py/agent/generator.js +9 -19
  30. package/src/py/agent/generator.js.map +1 -1
  31. package/src/ts/react-website/app/__snapshots__/generator.spec.ts.snap +6 -6
  32. package/src/ts/react-website/app/files/app/common/README.md.template +1 -1
  33. package/src/ts/react-website/app/generator.js +4 -4
  34. package/src/ts/react-website/app/generator.js.map +1 -1
  35. package/src/utils/migration-versions.d.ts +31 -2
  36. package/src/utils/migration-versions.js +74 -10
  37. package/src/utils/migration-versions.js.map +1 -1
  38. package/src/migrations/v1.0.0-rc.50/modernize-function-props-cast/migration.js.map +0 -1
  39. package/src/migrations/v1.0.0-rc.50/restrict-cors-to-custom-domains/migration.js.map +0 -1
  40. package/src/migrations/v1.0.0-rc.50/terraform-bootstrap-adopt-existing-bucket/migration.js.map +0 -1
  41. package/src/migrations/v1.0.0-rc.52/user-identity-waf-allow-localhost-callback/migration.js.map +0 -1
  42. package/src/migrations/v1.0.0-rc.54/order-access-log-delivery-after-bucket-policy/migration.js.map +0 -1
  43. package/src/migrations/v1.0.0-rc.55/backfill-generator-metadata/migration.js.map +0 -1
  44. package/src/migrations/v1.0.0-rc.56/dynamodb-local-remove-optimize-flag/migration.js.map +0 -1
  45. package/src/migrations/v1.0.0-rc.57/ts-agent-session-management-support/migration.js.map +0 -1
  46. package/src/py/agent/files/ag-ui/main.py.template +0 -37
  47. /package/src/migrations/{v1.0.0-rc.50/modernize-function-props-cast → latest/py-agent-lifespan-construction}/migration.d.ts +0 -0
  48. /package/src/migrations/{v1.0.0-rc.50/restrict-cors-to-custom-domains → latest/rename-load-runtime-config-target}/migration.d.ts +0 -0
  49. /package/src/migrations/v1.0.0-rc.50/{modernize-function-props-cast → 0001-modernize-function-props-cast}/metadata.json +0 -0
  50. /package/src/migrations/v1.0.0-rc.50/{terraform-bootstrap-adopt-existing-bucket → 0001-modernize-function-props-cast}/migration.d.ts +0 -0
  51. /package/src/migrations/v1.0.0-rc.50/{modernize-function-props-cast → 0001-modernize-function-props-cast}/migration.js +0 -0
  52. /package/src/migrations/v1.0.0-rc.50/{restrict-cors-to-custom-domains → 0002-restrict-cors-to-custom-domains}/metadata.json +0 -0
  53. /package/src/migrations/{v1.0.0-rc.57/ts-agent-session-management-support → v1.0.0-rc.50/0002-restrict-cors-to-custom-domains}/migration.d.ts +0 -0
  54. /package/src/migrations/v1.0.0-rc.50/{restrict-cors-to-custom-domains → 0002-restrict-cors-to-custom-domains}/migration.js +0 -0
  55. /package/src/migrations/v1.0.0-rc.50/{terraform-bootstrap-adopt-existing-bucket → 0003-terraform-bootstrap-adopt-existing-bucket}/metadata.json +0 -0
  56. /package/src/migrations/v1.0.0-rc.50/{terraform-bootstrap-adopt-existing-bucket → 0003-terraform-bootstrap-adopt-existing-bucket}/migration.js +0 -0
  57. /package/src/migrations/v1.0.0-rc.52/{user-identity-waf-allow-localhost-callback → 0001-user-identity-waf-allow-localhost-callback}/metadata.json +0 -0
  58. /package/src/migrations/v1.0.0-rc.52/{user-identity-waf-allow-localhost-callback → 0001-user-identity-waf-allow-localhost-callback}/migration.d.ts +0 -0
  59. /package/src/migrations/v1.0.0-rc.52/{user-identity-waf-allow-localhost-callback → 0001-user-identity-waf-allow-localhost-callback}/migration.js +0 -0
  60. /package/src/migrations/v1.0.0-rc.54/{order-access-log-delivery-after-bucket-policy → 0001-order-access-log-delivery-after-bucket-policy}/metadata.json +0 -0
  61. /package/src/migrations/v1.0.0-rc.54/{order-access-log-delivery-after-bucket-policy → 0001-order-access-log-delivery-after-bucket-policy}/migration.d.ts +0 -0
  62. /package/src/migrations/v1.0.0-rc.54/{order-access-log-delivery-after-bucket-policy → 0001-order-access-log-delivery-after-bucket-policy}/migration.js +0 -0
  63. /package/src/migrations/v1.0.0-rc.55/{backfill-generator-metadata → 0001-backfill-generator-metadata}/metadata.json +0 -0
  64. /package/src/migrations/v1.0.0-rc.55/{backfill-generator-metadata → 0001-backfill-generator-metadata}/migration.d.ts +0 -0
  65. /package/src/migrations/v1.0.0-rc.55/{backfill-generator-metadata → 0001-backfill-generator-metadata}/migration.js +0 -0
  66. /package/src/migrations/v1.0.0-rc.56/{dynamodb-local-remove-optimize-flag → 0001-dynamodb-local-remove-optimize-flag}/metadata.json +0 -0
  67. /package/src/migrations/v1.0.0-rc.56/{dynamodb-local-remove-optimize-flag → 0001-dynamodb-local-remove-optimize-flag}/migration.d.ts +0 -0
  68. /package/src/migrations/v1.0.0-rc.56/{dynamodb-local-remove-optimize-flag → 0001-dynamodb-local-remove-optimize-flag}/migration.js +0 -0
  69. /package/src/migrations/v1.0.0-rc.57/{ts-agent-session-management-support → 0001-ts-agent-session-management-support}/metadata.json +0 -0
  70. /package/src/migrations/v1.0.0-rc.57/{ts-agent-session-management-support → 0001-ts-agent-session-management-support}/migration.js +0 -0
  71. /package/src/py/agent/files/{a2a-langchain → langchain/a2a}/main.py.template +0 -0
  72. /package/src/py/agent/files/{common-langchain → langchain/common}/agent.py.template +0 -0
  73. /package/src/py/agent/files/{a2a → strands/a2a}/main.py.template +0 -0
  74. /package/src/py/agent/files/{common → strands/common}/__init__.py.template +0 -0
  75. /package/src/py/agent/files/{common → strands/common}/agent.py.template +0 -0
@@ -33,7 +33,7 @@ You can also automatically fix some lint errors by running the following command
33
33
 
34
34
  In order to integrate with cognito or trpc backends, you need to have a `runtime-config.json` file in your `/public` website directory. You can fetch this is follows:
35
35
 
36
- `<%= pkgMgrCmd %> nx run <%= fullyQualifiedName %>:load:runtime-config`
36
+ `<%= pkgMgrCmd %> nx load-runtime-config <%= fullyQualifiedName %>`
37
37
 
38
38
  > [!IMPORTANT]
39
39
  > Ensure you have AWS CLI and curl installed
@@ -181,20 +181,20 @@ export async function tsReactWebsiteGenerator(tree, schema) {
181
181
  const projectConfiguration = readProjectConfiguration(tree, fullyQualifiedName);
182
182
  const targets = projectConfiguration.targets;
183
183
  const infra = schema.infra ?? 'cloudfront-s3';
184
- // Configure load:runtime-config target based on IaC provider (only when infra is not none)
184
+ // Configure load-runtime-config target based on IaC provider (only when infra is not none)
185
185
  const iac = infra !== 'none' ? await resolveIac(tree, schema.iac) : undefined;
186
186
  if (iac === 'cdk') {
187
- targets['load:runtime-config'] = {
187
+ targets['load-runtime-config'] = {
188
188
  executor: 'nx:run-commands',
189
189
  metadata: {
190
- description: `Load runtime config from your deployed stack for dev purposes. You must set your AWS CLI credentials whilst calling '${getPackageManagerDisplayCommands().exec} nx run ${fullyQualifiedName}:load:runtime-config'`
190
+ 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}'`
191
191
  },
192
192
  options: {
193
193
  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"`
194
194
  }
195
195
  };
196
196
  } else if (iac === 'terraform') {
197
- targets['load:runtime-config'] = {
197
+ targets['load-runtime-config'] = {
198
198
  executor: 'nx:run-commands',
199
199
  metadata: {
200
200
  description: "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."
@@ -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 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';\nimport {\n addDestructuredImport,\n addSingleImport,\n applyGritQL,\n} from '../../../utils/ast';\nimport {\n declareDependencies,\n ownedElsewhere,\n} from '../../../utils/declared-dependencies';\nimport { formatFilesInSubtree } from '../../../utils/format';\nimport { resolveIac } from '../../../utils/iac';\nimport { installDependencies } from '../../../utils/install';\nimport { addGeneratorMetricsIfApplicable } from '../../../utils/metrics';\nimport { kebabCase, toClassName, toKebabCase } from '../../../utils/names';\nimport { getNpmScopePrefix } from '../../../utils/npm-scope';\nimport {\n addGeneratorMetadata,\n getGeneratorInfo,\n type NxGeneratorInfo,\n} from '../../../utils/nx';\nimport { sortObjectKeys } from '../../../utils/object';\nimport { getRelativePathToRoot } from '../../../utils/paths';\nimport { getPackageManagerDisplayCommands } from '../../../utils/pkg-manager';\nimport {\n SHARED_CONSTRUCTS_DEPENDENCIES,\n sharedConstructsGenerator,\n} from '../../../utils/shared-constructs';\nimport {\n type IacMetadata,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n} from '../../../utils/shared-constructs-constants';\nimport {\n SHADCN_DEPENDENCIES,\n sharedShadcnGenerator,\n} from '../../../utils/shared-shadcn';\nimport {\n addWebsiteInfra,\n WEBSITE_CONSTRUCTS_PY_DEPENDENCIES,\n} from '../../../utils/website-constructs/website-constructs';\nimport { configureTsProject } from '../../lib/ts-project-utils';\nimport { VITEST_DEPENDENCIES } from '../../lib/vitest';\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 ...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 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 run ${fullyQualifiedName}:load:runtime-config'`,\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: 'dist/packages/common/terraform/runtime-config.json',\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 dependsOn: ['^build'],\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\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 }\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 // 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(__dirname, 'src/routes'), generatedRouteTree: resolve(__dirname, 'src/routeTree.gen.ts') }), $items]` where { $items <: within `defineConfig($_)`, $items <: not contains `tanstackRouter` }\",\n );\n }\n\n if (tailwind) {\n await applyGritQL(\n tree,\n viteConfigPath,\n '`plugins: [$items]` => `plugins: [$items, tailwindcss()]` where { $items <: within `defineConfig($_)`, $items <: not some `tailwindcss()` }',\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'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":["generateFiles","joinPathFragments","names","OverwriteStrategy","readProjectConfiguration","removeDependenciesFromPackageJson","updateJson","updateProjectConfiguration","applicationGenerator","relative","sep","addTsDependencies","addDestructuredImport","addSingleImport","applyGritQL","declareDependencies","ownedElsewhere","formatFilesInSubtree","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","kebabCase","toClassName","toKebabCase","getNpmScopePrefix","addGeneratorMetadata","getGeneratorInfo","sortObjectKeys","getRelativePathToRoot","getPackageManagerDisplayCommands","SHARED_CONSTRUCTS_DEPENDENCIES","sharedConstructsGenerator","PACKAGES_DIR","SHARED_SHADCN_DIR","SHADCN_DEPENDENCIES","sharedShadcnGenerator","addWebsiteInfra","WEBSITE_CONSTRUCTS_PY_DEPENDENCIES","configureTsProject","VITEST_DEPENDENCIES","DEPENDENCIES","ts","name","dev","root","when","m","ux","tanstackRouter","tailwind","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","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","tsconfig","compilerOptions","moduleResolution","module","outDirToRootRelativePath","distDir","tsBuildInfoFile","lib","references","filter","ref","path","projectRoot","ignore","preferInstallDependencies","languages","ensureResolvable"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,KAAK,EACLC,iBAAiB,EACjBC,wBAAwB,EACxBC,iCAAiC,EAEjCC,UAAU,EACVC,0BAA0B,QACr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,GAAGD,SAASC,eAAe;gBAC3BF,QAAQM;gBACRC,iBAAiBtI,kBAAkBqI,SAAS;gBAC5CE,KAAK;oBAAC;iBAAM;YACd;YACAC,YACE1F,OAAO,WACH;mBACK,AAACkF,CAAAA,SAASQ,UAAU,IAAI,EAAE,AAAD,EAAGC,MAAM,CACnC,CAACC,MAAQA,IAAIC,IAAI,KAAK1B;gBAExB;oBACE0B,MAAM1B;gBACR;aACD,GACDe,SAASQ,UAAU;QAC3B,CAAA;IAGF9H,kBAAkB4C,MAAMf,cAAc;QAAEsD;QAAU+C,aAAa/B;IAAY;IAE3E,uEAAuE;IACvE,0EAA0E;IAC1E,4EAA4E;IAC5E,4EAA4E;IAC5E,mDAAmD;IACnDzG,kCAAkCkD,MAAM;QAAC;QAAS;KAAY,EAAE,EAAE;IAElE,MAAMnC,gCAAgCmC,MAAM;QAC1CH;KACD;IAED,+EAA+E;IAC/E,gFAAgF;IAChF,wEAAwE;IACxE,+EAA+E;IAC/E,2DAA2D;IAC3D,MAAMnC,qBAAqBsC,MAAMqC,WAAW;QAC1CkD,QAAQ9F,iBACJ;YAAC/C,kBAAkB6G,aAAa,OAAO;SAAoB,GAC3D,EAAE;IACR;IACA,4EAA4E;IAC5E,8EAA8E;IAC9E,gEAAgE;IAChE,OAAO,IACL3F,oBAAoBoC,MAAMC,OAAOuF,yBAAyB,EAAE;YAC1DC,WAAW;gBAAC;aAAa;YACzBC,kBAAkB;mBACZhG,WAAY;oBAAC;iBAAoB,GAAa,EAAE;mBAChDD,iBAAkB;oBAAC;iBAA0B,GAAa,EAAE;aACjE;QACH;AACJ;AACA,eAAeM,wBAAwB"}
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 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';\nimport {\n addDestructuredImport,\n addSingleImport,\n applyGritQL,\n} from '../../../utils/ast';\nimport {\n declareDependencies,\n ownedElsewhere,\n} from '../../../utils/declared-dependencies';\nimport { formatFilesInSubtree } from '../../../utils/format';\nimport { resolveIac } from '../../../utils/iac';\nimport { installDependencies } from '../../../utils/install';\nimport { addGeneratorMetricsIfApplicable } from '../../../utils/metrics';\nimport { kebabCase, toClassName, toKebabCase } from '../../../utils/names';\nimport { getNpmScopePrefix } from '../../../utils/npm-scope';\nimport {\n addGeneratorMetadata,\n getGeneratorInfo,\n type NxGeneratorInfo,\n} from '../../../utils/nx';\nimport { sortObjectKeys } from '../../../utils/object';\nimport { getRelativePathToRoot } from '../../../utils/paths';\nimport { getPackageManagerDisplayCommands } from '../../../utils/pkg-manager';\nimport {\n SHARED_CONSTRUCTS_DEPENDENCIES,\n sharedConstructsGenerator,\n} from '../../../utils/shared-constructs';\nimport {\n type IacMetadata,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n} from '../../../utils/shared-constructs-constants';\nimport {\n SHADCN_DEPENDENCIES,\n sharedShadcnGenerator,\n} from '../../../utils/shared-shadcn';\nimport {\n addWebsiteInfra,\n WEBSITE_CONSTRUCTS_PY_DEPENDENCIES,\n} from '../../../utils/website-constructs/website-constructs';\nimport { configureTsProject } from '../../lib/ts-project-utils';\nimport { VITEST_DEPENDENCIES } from '../../lib/vitest';\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 ...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 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: 'dist/packages/common/terraform/runtime-config.json',\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 dependsOn: ['^build'],\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\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 }\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 // 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(__dirname, 'src/routes'), generatedRouteTree: resolve(__dirname, 'src/routeTree.gen.ts') }), $items]` where { $items <: within `defineConfig($_)`, $items <: not contains `tanstackRouter` }\",\n );\n }\n\n if (tailwind) {\n await applyGritQL(\n tree,\n viteConfigPath,\n '`plugins: [$items]` => `plugins: [$items, tailwindcss()]` where { $items <: within `defineConfig($_)`, $items <: not some `tailwindcss()` }',\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'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":["generateFiles","joinPathFragments","names","OverwriteStrategy","readProjectConfiguration","removeDependenciesFromPackageJson","updateJson","updateProjectConfiguration","applicationGenerator","relative","sep","addTsDependencies","addDestructuredImport","addSingleImport","applyGritQL","declareDependencies","ownedElsewhere","formatFilesInSubtree","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","kebabCase","toClassName","toKebabCase","getNpmScopePrefix","addGeneratorMetadata","getGeneratorInfo","sortObjectKeys","getRelativePathToRoot","getPackageManagerDisplayCommands","SHARED_CONSTRUCTS_DEPENDENCIES","sharedConstructsGenerator","PACKAGES_DIR","SHARED_SHADCN_DIR","SHADCN_DEPENDENCIES","sharedShadcnGenerator","addWebsiteInfra","WEBSITE_CONSTRUCTS_PY_DEPENDENCIES","configureTsProject","VITEST_DEPENDENCIES","DEPENDENCIES","ts","name","dev","root","when","m","ux","tanstackRouter","tailwind","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","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","tsconfig","compilerOptions","moduleResolution","module","outDirToRootRelativePath","distDir","tsBuildInfoFile","lib","references","filter","ref","path","projectRoot","ignore","preferInstallDependencies","languages","ensureResolvable"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,KAAK,EACLC,iBAAiB,EACjBC,wBAAwB,EACxBC,iCAAiC,EAEjCC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAASC,oBAAoB,QAAQ,YAAY;AAC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iBAAiBtI,kBAAkBqI,SAAS;gBAC5CE,KAAK;oBAAC;iBAAM;YACd;YACAC,YACE1F,OAAO,WACH;mBACK,AAACkF,CAAAA,SAASQ,UAAU,IAAI,EAAE,AAAD,EAAGC,MAAM,CACnC,CAACC,MAAQA,IAAIC,IAAI,KAAK1B;gBAExB;oBACE0B,MAAM1B;gBACR;aACD,GACDe,SAASQ,UAAU;QAC3B,CAAA;IAGF9H,kBAAkB4C,MAAMf,cAAc;QAAEsD;QAAU+C,aAAa/B;IAAY;IAE3E,uEAAuE;IACvE,0EAA0E;IAC1E,4EAA4E;IAC5E,4EAA4E;IAC5E,mDAAmD;IACnDzG,kCAAkCkD,MAAM;QAAC;QAAS;KAAY,EAAE,EAAE;IAElE,MAAMnC,gCAAgCmC,MAAM;QAC1CH;KACD;IAED,+EAA+E;IAC/E,gFAAgF;IAChF,wEAAwE;IACxE,+EAA+E;IAC/E,2DAA2D;IAC3D,MAAMnC,qBAAqBsC,MAAMqC,WAAW;QAC1CkD,QAAQ9F,iBACJ;YAAC/C,kBAAkB6G,aAAa,OAAO;SAAoB,GAC3D,EAAE;IACR;IACA,4EAA4E;IAC5E,8EAA8E;IAC9E,gEAAgE;IAChE,OAAO,IACL3F,oBAAoBoC,MAAMC,OAAOuF,yBAAyB,EAAE;YAC1DC,WAAW;gBAAC;aAAa;YACzBC,kBAAkB;mBACZhG,WAAY;oBAAC;iBAAoB,GAAa,EAAE;mBAChDD,iBAAkB;oBAAC;iBAA0B,GAAa,EAAE;aACjE;QACH;AACJ;AACA,eAAeM,wBAAwB"}
@@ -72,13 +72,26 @@ export declare const readShippedMigrationVersions: (migrations: MigrationsJson,
72
72
  * every generator entry, preserving any already present, and the pending version
73
73
  * recorded on any `packageJsonUpdates` entry still holding `latest`.
74
74
  *
75
+ * `nx migrate` sorts the run ascending by version and keeps the manifest's order
76
+ * among equal versions, so the order entries are emitted in is the run order
77
+ * within a release. Migrations sharing a version (a batch shipped together, or a
78
+ * whole `v<x.y.z>` folder replayed on a big version jump) are therefore ordered
79
+ * here by the commit that added them — an earlier-committed migration runs
80
+ * first — so a later migration can depend on an earlier one in the same batch.
81
+ * Every-migration entries are emitted last regardless, so they run after the
82
+ * release's own migrations (letting one add a dependency this then brings up to
83
+ * date). Entries with no rank fall back to the manifest's order, which
84
+ * `assembleMigrations` already sorts by key.
85
+ *
75
86
  * @param migrations parsed migrations.json to stamp
76
87
  * @param shippedVersions migration key -> version of the earliest release
77
88
  * tag that registers it (absent for migrations that haven't shipped)
78
89
  * @param pendingVersion version the release is about to publish, stamped onto
79
90
  * unshipped migrations so their version is one that really shipped
91
+ * @param commitRanks migration key -> rank of the commit that added it (lower is
92
+ * earlier); absent entries fall back to the manifest's order
80
93
  */
81
- export declare const stampMigrationVersions: (migrations: MigrationsJson, shippedVersions: Record<string, string>, pendingVersion: string) => MigrationsJson;
94
+ export declare const stampMigrationVersions: (migrations: MigrationsJson, shippedVersions: Record<string, string>, pendingVersion: string, commitRanks?: Record<string, number>) => MigrationsJson;
82
95
  /** Directory a newly scaffolded migration lands in, before a release claims it. */
83
96
  export declare const LATEST_MIGRATIONS_DIR = "latest";
84
97
  /** Directory holding the migrations shipped by a given release. */
@@ -89,6 +102,13 @@ export declare const versionMigrationsDir: (version: string) => string;
89
102
  * one that already shipped.
90
103
  */
91
104
  export declare const migrationKey: (dir: string, name: string) => string;
105
+ /**
106
+ * Format a 1-based order into the folder-name prefix that beds it in. Backfill
107
+ * prefixes a released migration's folder with its commit order within the
108
+ * release (`0001-foo`), so the folder name alone sorts a version's migrations
109
+ * into commit order — stamping doesn't have to re-read git for them.
110
+ */
111
+ export declare const orderPrefix: (order: number) => string;
92
112
  /** A migration directory move the caller needs to make on disk. */
93
113
  export interface MigrationDirMove {
94
114
  name: string;
@@ -102,14 +122,23 @@ export interface MigrationDirMove {
102
122
  * return the collection alongside the keys that changed and the directory moves
103
123
  * to make on disk.
104
124
  *
125
+ * A backfilled migration's new folder name is prefixed with its commit order
126
+ * within the release (`0001-foo`), so the folder layout beds in the order the
127
+ * release ran them: `assembleMigrations` sorts by key, so the prefix alone puts
128
+ * a version's migrations in commit order and stamping never has to re-read git
129
+ * for a released migration. Migrations sharing a commit (a squashed PR) fall
130
+ * back to alphabetical order, matching stamping.
131
+ *
105
132
  * Unlike `stampMigrationVersions` this only records already-released versions,
106
133
  * leaving the release to decide what a net-new migration gets.
107
134
  *
108
135
  * @param migrations parsed migrations.json to backfill
109
136
  * @param shippedVersions migration key -> version of the earliest release tag
110
137
  * that registers it (absent for migrations that haven't shipped)
138
+ * @param commitRanks migration key -> rank of the commit that added it (lower is
139
+ * earlier), used to order the migrations bedded into each release
111
140
  */
112
- export declare const backfillMigrationVersions: (migrations: MigrationsJson, shippedVersions: Record<string, string>) => {
141
+ export declare const backfillMigrationVersions: (migrations: MigrationsJson, shippedVersions: Record<string, string>, commitRanks?: Record<string, number>) => {
113
142
  migrations: MigrationsJson;
114
143
  backfilled: string[];
115
144
  moves: MigrationDirMove[];
@@ -48,22 +48,45 @@
48
48
  }
49
49
  return shippedVersions;
50
50
  };
51
+ /**
52
+ * Rank a migration ships under, lower running first. Unranked entries (no commit
53
+ * history for them, or an every-migration entry with no folder) sort after every
54
+ * ranked one, so a ranked migration always precedes an unranked peer.
55
+ */ const UNRANKED = Number.MAX_SAFE_INTEGER;
51
56
  /**
52
57
  * Return a copy of the migrations collection with a `version` stamped onto
53
58
  * every generator entry, preserving any already present, and the pending version
54
59
  * recorded on any `packageJsonUpdates` entry still holding `latest`.
55
60
  *
61
+ * `nx migrate` sorts the run ascending by version and keeps the manifest's order
62
+ * among equal versions, so the order entries are emitted in is the run order
63
+ * within a release. Migrations sharing a version (a batch shipped together, or a
64
+ * whole `v<x.y.z>` folder replayed on a big version jump) are therefore ordered
65
+ * here by the commit that added them — an earlier-committed migration runs
66
+ * first — so a later migration can depend on an earlier one in the same batch.
67
+ * Every-migration entries are emitted last regardless, so they run after the
68
+ * release's own migrations (letting one add a dependency this then brings up to
69
+ * date). Entries with no rank fall back to the manifest's order, which
70
+ * `assembleMigrations` already sorts by key.
71
+ *
56
72
  * @param migrations parsed migrations.json to stamp
57
73
  * @param shippedVersions migration key -> version of the earliest release
58
74
  * tag that registers it (absent for migrations that haven't shipped)
59
75
  * @param pendingVersion version the release is about to publish, stamped onto
60
76
  * unshipped migrations so their version is one that really shipped
61
- */ export const stampMigrationVersions = (migrations, shippedVersions, pendingVersion)=>({
77
+ * @param commitRanks migration key -> rank of the commit that added it (lower is
78
+ * earlier); absent entries fall back to the manifest's order
79
+ */ export const stampMigrationVersions = (migrations, shippedVersions, pendingVersion, commitRanks = {})=>({
62
80
  ...migrations,
63
- generators: Object.fromEntries(// `nx migrate` sorts the run ascending by version and preserves the
64
- // manifest's order among equal versions, so emitting the every-migration
65
- // entries last is what makes them run after the release's own migrations.
66
- Object.entries(migrations.generators ?? {}).sort(([, a], [, b])=>Number(a.everyMigration ?? false) - Number(b.everyMigration ?? false)).map(([name, entry])=>{
81
+ generators: Object.fromEntries(Object.entries(migrations.generators ?? {}).sort(([keyA, a], [keyB, b])=>{
82
+ const everyDiff = Number(a.everyMigration ?? false) - Number(b.everyMigration ?? false);
83
+ if (everyDiff !== 0) {
84
+ return everyDiff;
85
+ }
86
+ // Equal ranks (same commit, or both unranked) fall through to a stable
87
+ // sort, keeping the manifest's key order the assembly already imposed.
88
+ return (commitRanks[keyA] ?? UNRANKED) - (commitRanks[keyB] ?? UNRANKED);
89
+ }).map(([name, entry])=>{
67
90
  // Source-only marker, stripped from what nx reads.
68
91
  const { everyMigration, version: sourceVersion, ...published } = entry;
69
92
  // Overrides any source version so it stays ahead of what is installed.
@@ -92,36 +115,77 @@
92
115
  * one that already shipped.
93
116
  */ export const migrationKey = (dir, name)=>`${dir}-${name}`;
94
117
  const LATEST_KEY_PREFIX = `${LATEST_MIGRATIONS_DIR}-`;
118
+ /** Digits in the zero-padded order prefix a bedded-in migration folder carries. */ const ORDER_PREFIX_WIDTH = 4;
119
+ /**
120
+ * Format a 1-based order into the folder-name prefix that beds it in. Backfill
121
+ * prefixes a released migration's folder with its commit order within the
122
+ * release (`0001-foo`), so the folder name alone sorts a version's migrations
123
+ * into commit order — stamping doesn't have to re-read git for them.
124
+ */ export const orderPrefix = (order)=>String(order).padStart(ORDER_PREFIX_WIDTH, '0');
125
+ /** The base migration name a `latest` key carries, without its folder prefix. */ const latestKeyName = (key)=>key.startsWith(LATEST_KEY_PREFIX) ? key.slice(LATEST_KEY_PREFIX.length) : key;
95
126
  /**
96
127
  * Record the release that shipped each migration on entries without a version,
97
128
  * re-keying them and re-pointing their paths at that release's folder, and
98
129
  * return the collection alongside the keys that changed and the directory moves
99
130
  * to make on disk.
100
131
  *
132
+ * A backfilled migration's new folder name is prefixed with its commit order
133
+ * within the release (`0001-foo`), so the folder layout beds in the order the
134
+ * release ran them: `assembleMigrations` sorts by key, so the prefix alone puts
135
+ * a version's migrations in commit order and stamping never has to re-read git
136
+ * for a released migration. Migrations sharing a commit (a squashed PR) fall
137
+ * back to alphabetical order, matching stamping.
138
+ *
101
139
  * Unlike `stampMigrationVersions` this only records already-released versions,
102
140
  * leaving the release to decide what a net-new migration gets.
103
141
  *
104
142
  * @param migrations parsed migrations.json to backfill
105
143
  * @param shippedVersions migration key -> version of the earliest release tag
106
144
  * that registers it (absent for migrations that haven't shipped)
107
- */ export const backfillMigrationVersions = (migrations, shippedVersions)=>{
145
+ * @param commitRanks migration key -> rank of the commit that added it (lower is
146
+ * earlier), used to order the migrations bedded into each release
147
+ */ export const backfillMigrationVersions = (migrations, shippedVersions, commitRanks = {})=>{
108
148
  const generators = {};
109
149
  const backfilled = [];
110
150
  const moves = [];
111
151
  // Reported alongside the migrations so the update's PR says an nx bump was
112
152
  // dated, and so the caller knows there is something to commit.
113
153
  const backfilledUpdates = Object.entries(migrations.packageJsonUpdates ?? {}).filter(([key, entry])=>entry.version === LATEST_MIGRATIONS_DIR && shippedVersions[key]).map(([key])=>key);
154
+ const toBackfill = Object.entries(migrations.generators ?? {}).filter(// Pinning an every-migration entry would stop it running on later upgrades.
155
+ ([key, entry])=>!entry.version && !entry.everyMigration && shippedVersions[key]);
156
+ // The order prefix is a migration's position within its release, so number
157
+ // each version's migrations together, in commit order (alphabetical among a
158
+ // shared commit). All of a release's migrations are backfilled in one run —
159
+ // they sat in `latest` until it shipped — so a version is numbered from 1 here.
160
+ const orderByKey = new Map();
161
+ const byVersion = new Map();
162
+ for (const [key] of toBackfill){
163
+ const version = shippedVersions[key];
164
+ const keys = byVersion.get(version) ?? [];
165
+ keys.push(key);
166
+ byVersion.set(version, keys);
167
+ }
168
+ for (const keys of byVersion.values()){
169
+ const ordered = keys.sort((a, b)=>{
170
+ const rankDiff = (commitRanks[a] ?? Number.MAX_SAFE_INTEGER) - (commitRanks[b] ?? Number.MAX_SAFE_INTEGER);
171
+ return rankDiff !== 0 ? rankDiff : latestKeyName(a).localeCompare(latestKeyName(b));
172
+ });
173
+ ordered.forEach((key, index)=>{
174
+ orderByKey.set(key, index + 1);
175
+ });
176
+ }
114
177
  for (const [key, entry] of Object.entries(migrations.generators ?? {})){
115
178
  const version = shippedVersions[key];
116
- // Pinning an every-migration entry would stop it running on later upgrades.
117
179
  if (entry.version || !version || entry.everyMigration) {
118
180
  generators[key] = entry;
119
181
  continue;
120
182
  }
121
- const name = key.startsWith(LATEST_KEY_PREFIX) ? key.slice(LATEST_KEY_PREFIX.length) : key;
183
+ const name = latestKeyName(key);
184
+ // The commit-order prefix beds the run order into the folder name.
185
+ const prefixedName = `${orderPrefix(orderByKey.get(key) ?? 1)}-${name}`;
122
186
  const versionDir = versionMigrationsDir(version);
123
187
  const latestSegment = `/${LATEST_MIGRATIONS_DIR}/${name}/`;
124
- const versionSegment = `/${versionDir}/${name}/`;
188
+ const versionSegment = `/${versionDir}/${prefixedName}/`;
125
189
  // Re-point each path field at the version folder, recording the move the
126
190
  // caller needs to make on disk the first time one is found.
127
191
  const repointed = {};
@@ -143,7 +207,7 @@ const LATEST_KEY_PREFIX = `${LATEST_MIGRATIONS_DIR}-`;
143
207
  });
144
208
  }
145
209
  }
146
- generators[migrationKey(versionDir, name)] = {
210
+ generators[migrationKey(versionDir, prefixedName)] = {
147
211
  version,
148
212
  ...repointed
149
213
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/migration-versions.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { compare, valid } from 'semver';\n\n/**\n * Version stamping for migrations.\n *\n * A new migration is committed with no `version` — releases are calculated from\n * conventional commits and written only to `dist/` and a git tag, so versions\n * reach the published `migrations.json` two ways:\n *\n * - At release time (`scripts/stamp-migrations.ts`) entries still missing a\n * version are stamped into the compiled `migrations.json`: an already shipped\n * one gets the earliest release tag registering it, and a net-new one gets the\n * version the release is about to publish, which the release job passes in\n * after `nx release version` writes it to the dist manifests.\n * - The weekly `update-versions` PR backfills the version of the release that\n * shipped each migration, moving and re-keying it accordingly\n * (`scripts/backfill-migration-versions.ts`), so source converges on the\n * versions of everything already released. `packageJsonUpdates` entries are\n * dated in place there too, since their keys never change.\n *\n * A version already in source always wins, so backfilled entries are stable.\n *\n * An entry marked `everyMigration: true` is never backfilled or pinned, and is\n * re-stamped with each pending version, so it runs on every upgrade.\n */\n\nexport interface MigrationsJson {\n $schema?: string;\n name?: string;\n generators?: Record<\n string,\n { version?: string; everyMigration?: boolean } & Record<string, unknown>\n >;\n /**\n * Declarative dependency bumps `nx migrate` applies to the root manifest.\n * Keyed by what the bump targets rather than the release that ships it, so an\n * entry is unique from the moment it is written and one release's bump can sit\n * beside the next; nx itself gates on the entry's `version`.\n */\n packageJsonUpdates?: Record<\n string,\n { version: string } & Record<string, unknown>\n >;\n}\n\n/** Ascending semver comparator for `Array.prototype.sort`. */\nexport const compareVersions = compare;\n\n/** Whether a string is an exact semver version. */\nexport const isValidVersion = (version: string): boolean =>\n valid(version) !== null;\n\n/**\n * Map of entry key -> version of the earliest release that registers it, across\n * both `generators` and `packageJsonUpdates`. Resolved only for the entries still\n * missing a version (one already recorded in source wins, so its history doesn't\n * need reading). An entry that hasn't been released is absent.\n *\n * Walks releases newest first and stops as soon as every entry is resolved: an\n * entry that has disappeared from a release's `migrations.json` was first\n * registered by the release after it, which is the one that shipped it.\n *\n * Both sections resolve the same way and share the walk, so the release doesn't\n * read tag history twice. Keys can't collide: a migration is keyed by its own\n * name, an nx bump by the nx version it moves to.\n *\n * @param migrations parsed source migrations.json\n * @param versions released versions in descending semver order\n * @param readReleasedMigrations reads the `migrations.json` published by a given\n * version, or undefined if it predates the manifest\n */\nexport const readShippedMigrationVersions = (\n migrations: MigrationsJson,\n versions: string[],\n readReleasedMigrations: (version: string) => MigrationsJson | undefined,\n): Record<string, string> => {\n const shippedVersions: Record<string, string> = {};\n // A `packageJsonUpdates` entry records `latest` rather than omitting its\n // version, since nx requires the field.\n let unresolved = [\n ...Object.entries(migrations.generators ?? {})\n .filter(([, entry]) => !entry.version)\n .map(([key]) => key),\n ...Object.entries(migrations.packageJsonUpdates ?? {})\n .filter(([, entry]) => entry.version === LATEST_MIGRATIONS_DIR)\n .map(([key]) => key),\n ];\n\n for (const version of versions) {\n if (unresolved.length === 0) {\n break;\n }\n const released = readReleasedMigrations(version);\n const registered = new Set([\n ...Object.keys(released?.generators ?? {}),\n ...Object.keys(released?.packageJsonUpdates ?? {}),\n ]);\n // Entries gone at this release keep the version recorded from the release\n // after it (if any) and stop being looked up.\n unresolved = unresolved.filter((key) => registered.has(key));\n for (const key of unresolved) {\n shippedVersions[key] = version;\n }\n }\n\n return shippedVersions;\n};\n\n/**\n * Return a copy of the migrations collection with a `version` stamped onto\n * every generator entry, preserving any already present, and the pending version\n * recorded on any `packageJsonUpdates` entry still holding `latest`.\n *\n * @param migrations parsed migrations.json to stamp\n * @param shippedVersions migration key -> version of the earliest release\n * tag that registers it (absent for migrations that haven't shipped)\n * @param pendingVersion version the release is about to publish, stamped onto\n * unshipped migrations so their version is one that really shipped\n */\nexport const stampMigrationVersions = (\n migrations: MigrationsJson,\n shippedVersions: Record<string, string>,\n pendingVersion: string,\n): MigrationsJson => ({\n ...migrations,\n generators: Object.fromEntries(\n // `nx migrate` sorts the run ascending by version and preserves the\n // manifest's order among equal versions, so emitting the every-migration\n // entries last is what makes them run after the release's own migrations.\n Object.entries(migrations.generators ?? {})\n .sort(\n ([, a], [, b]) =>\n Number(a.everyMigration ?? false) - Number(b.everyMigration ?? false),\n )\n .map(([name, entry]) => {\n // Source-only marker, stripped from what nx reads.\n const { everyMigration, version: sourceVersion, ...published } = entry;\n // Overrides any source version so it stays ahead of what is installed.\n const version = everyMigration\n ? pendingVersion\n : (sourceVersion ?? shippedVersions[name] ?? pendingVersion);\n return [name, { version, ...published }];\n }),\n ),\n ...(migrations.packageJsonUpdates && {\n packageJsonUpdates: stampPackageJsonUpdates(\n migrations.packageJsonUpdates,\n pendingVersion,\n ),\n }),\n});\n\n/**\n * Version any `packageJsonUpdates` entry still holding `latest` with the release\n * about to publish it, so the nx bump ships under a version `nx migrate` gates on.\n */\nconst stampPackageJsonUpdates = (\n packageJsonUpdates: NonNullable<MigrationsJson['packageJsonUpdates']>,\n pendingVersion: string,\n): NonNullable<MigrationsJson['packageJsonUpdates']> =>\n resolvePackageJsonUpdateVersions(packageJsonUpdates, () => pendingVersion);\n\n/** Directory a newly scaffolded migration lands in, before a release claims it. */\nexport const LATEST_MIGRATIONS_DIR = 'latest';\n\n/** Directory holding the migrations shipped by a given release. */\nexport const versionMigrationsDir = (version: string) => `v${version}`;\n\n/**\n * Key a migration is registered under in `migrations.json`. Prefixed with its\n * directory so reusing a name in a later release can't silently overwrite the\n * one that already shipped.\n */\nexport const migrationKey = (dir: string, name: string) => `${dir}-${name}`;\n\nconst LATEST_KEY_PREFIX = `${LATEST_MIGRATIONS_DIR}-`;\n\n/** A migration directory move the caller needs to make on disk. */\nexport interface MigrationDirMove {\n name: string;\n version: string;\n from: string;\n to: string;\n}\n\n/**\n * Record the release that shipped each migration on entries without a version,\n * re-keying them and re-pointing their paths at that release's folder, and\n * return the collection alongside the keys that changed and the directory moves\n * to make on disk.\n *\n * Unlike `stampMigrationVersions` this only records already-released versions,\n * leaving the release to decide what a net-new migration gets.\n *\n * @param migrations parsed migrations.json to backfill\n * @param shippedVersions migration key -> version of the earliest release tag\n * that registers it (absent for migrations that haven't shipped)\n */\nexport const backfillMigrationVersions = (\n migrations: MigrationsJson,\n shippedVersions: Record<string, string>,\n): {\n migrations: MigrationsJson;\n backfilled: string[];\n moves: MigrationDirMove[];\n} => {\n const generators: NonNullable<MigrationsJson['generators']> = {};\n const backfilled: string[] = [];\n const moves: MigrationDirMove[] = [];\n // Reported alongside the migrations so the update's PR says an nx bump was\n // dated, and so the caller knows there is something to commit.\n const backfilledUpdates = Object.entries(migrations.packageJsonUpdates ?? {})\n .filter(\n ([key, entry]) =>\n entry.version === LATEST_MIGRATIONS_DIR && shippedVersions[key],\n )\n .map(([key]) => key);\n\n for (const [key, entry] of Object.entries(migrations.generators ?? {})) {\n const version = shippedVersions[key];\n // Pinning an every-migration entry would stop it running on later upgrades.\n if (entry.version || !version || entry.everyMigration) {\n generators[key] = entry;\n continue;\n }\n\n const name = key.startsWith(LATEST_KEY_PREFIX)\n ? key.slice(LATEST_KEY_PREFIX.length)\n : key;\n const versionDir = versionMigrationsDir(version);\n const latestSegment = `/${LATEST_MIGRATIONS_DIR}/${name}/`;\n const versionSegment = `/${versionDir}/${name}/`;\n\n // Re-point each path field at the version folder, recording the move the\n // caller needs to make on disk the first time one is found.\n const repointed: Record<string, unknown> = {};\n let moved = false;\n for (const [field, value] of Object.entries(entry)) {\n if (typeof value !== 'string' || !value.includes(latestSegment)) {\n repointed[field] = value;\n continue;\n }\n repointed[field] = value.replace(latestSegment, versionSegment);\n if (!moved) {\n moved = true;\n const dir = value.slice(0, value.indexOf(latestSegment));\n moves.push({\n name,\n version,\n from: `${dir}${latestSegment}`.replace(/^\\.\\/|\\/$/g, ''),\n to: `${dir}${versionSegment}`.replace(/^\\.\\/|\\/$/g, ''),\n });\n }\n }\n\n generators[migrationKey(versionDir, name)] = { version, ...repointed };\n backfilled.push(key);\n }\n\n return {\n migrations: {\n ...migrations,\n generators,\n ...(migrations.packageJsonUpdates && {\n packageJsonUpdates: resolvePackageJsonUpdateVersions(\n migrations.packageJsonUpdates,\n (key) => shippedVersions[key],\n ),\n }),\n },\n backfilled: [...backfilled, ...backfilledUpdates],\n moves,\n };\n};\n\n/**\n * Record the version each `packageJsonUpdates` entry ships under, for those still\n * holding `latest`.\n *\n * The key already identifies the entry — an nx bump is named for the nx version\n * it moves to — so only the `version` field changes. Nothing is re-keyed, which\n * is what lets one release's bump sit alongside the next without either being\n * overwritten before it ships.\n */\nconst resolvePackageJsonUpdateVersions = (\n packageJsonUpdates: NonNullable<MigrationsJson['packageJsonUpdates']>,\n resolve: (key: string) => string | undefined,\n): NonNullable<MigrationsJson['packageJsonUpdates']> =>\n Object.fromEntries(\n Object.entries(packageJsonUpdates).map(([key, entry]) => {\n const version =\n entry.version === LATEST_MIGRATIONS_DIR ? resolve(key) : undefined;\n return [key, version ? { ...entry, version } : entry];\n }),\n );\n"],"names":["compare","valid","compareVersions","isValidVersion","version","readShippedMigrationVersions","migrations","versions","readReleasedMigrations","shippedVersions","unresolved","Object","entries","generators","filter","entry","map","key","packageJsonUpdates","LATEST_MIGRATIONS_DIR","length","released","registered","Set","keys","has","stampMigrationVersions","pendingVersion","fromEntries","sort","a","b","Number","everyMigration","name","sourceVersion","published","stampPackageJsonUpdates","resolvePackageJsonUpdateVersions","versionMigrationsDir","migrationKey","dir","LATEST_KEY_PREFIX","backfillMigrationVersions","backfilled","moves","backfilledUpdates","startsWith","slice","versionDir","latestSegment","versionSegment","repointed","moved","field","value","includes","replace","indexOf","push","from","to","resolve","undefined"],"mappings":"AAAA;;;CAGC,GACD,SAASA,OAAO,EAAEC,KAAK,QAAQ,SAAS;AA6CxC,4DAA4D,GAC5D,OAAO,MAAMC,kBAA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,MAAMU,gBAAgB,CAACM,OAAO,CAAC,cAAc;gBACtD;YACF;QACF;QAEA5C,UAAU,CAAC2B,aAAaS,YAAYf,MAAM,GAAG;YAAE9B;YAAS,GAAGgD,SAAS;QAAC;QACrER,WAAWe,IAAI,CAAC1C;IAClB;IAEA,OAAO;QACLX,YAAY;YACV,GAAGA,UAAU;YACbO;YACA,GAAIP,WAAWY,kBAAkB,IAAI;gBACnCA,oBAAoBoB,iCAClBhC,WAAWY,kBAAkB,EAC7B,CAACD,MAAQR,eAAe,CAACQ,IAAI;YAEjC,CAAC;QACH;QACA2B,YAAY;eAAIA;eAAeE;SAAkB;QACjDD;IACF;AACF,EAAE;AAEF;;;;;;;;CAQC,GACD,MAAMP,mCAAmC,CACvCpB,oBACA4C,UAEAnD,OAAOiB,WAAW,CAChBjB,OAAOC,OAAO,CAACM,oBAAoBF,GAAG,CAAC,CAAC,CAACC,KAAKF,MAAM;QAClD,MAAMX,UACJW,MAAMX,OAAO,KAAKe,wBAAwB2C,QAAQ7C,OAAO8C;QAC3D,OAAO;YAAC9C;YAAKb,UAAU;gBAAE,GAAGW,KAAK;gBAAEX;YAAQ,IAAIW;SAAM;IACvD"}
1
+ {"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/migration-versions.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { compare, valid } from 'semver';\n\n/**\n * Version stamping for migrations.\n *\n * A new migration is committed with no `version` — releases are calculated from\n * conventional commits and written only to `dist/` and a git tag, so versions\n * reach the published `migrations.json` two ways:\n *\n * - At release time (`scripts/stamp-migrations.ts`) entries still missing a\n * version are stamped into the compiled `migrations.json`: an already shipped\n * one gets the earliest release tag registering it, and a net-new one gets the\n * version the release is about to publish, which the release job passes in\n * after `nx release version` writes it to the dist manifests.\n * - The weekly `update-versions` PR backfills the version of the release that\n * shipped each migration, moving and re-keying it accordingly\n * (`scripts/backfill-migration-versions.ts`), so source converges on the\n * versions of everything already released. `packageJsonUpdates` entries are\n * dated in place there too, since their keys never change.\n *\n * A version already in source always wins, so backfilled entries are stable.\n *\n * An entry marked `everyMigration: true` is never backfilled or pinned, and is\n * re-stamped with each pending version, so it runs on every upgrade.\n */\n\nexport interface MigrationsJson {\n $schema?: string;\n name?: string;\n generators?: Record<\n string,\n { version?: string; everyMigration?: boolean } & Record<string, unknown>\n >;\n /**\n * Declarative dependency bumps `nx migrate` applies to the root manifest.\n * Keyed by what the bump targets rather than the release that ships it, so an\n * entry is unique from the moment it is written and one release's bump can sit\n * beside the next; nx itself gates on the entry's `version`.\n */\n packageJsonUpdates?: Record<\n string,\n { version: string } & Record<string, unknown>\n >;\n}\n\n/** Ascending semver comparator for `Array.prototype.sort`. */\nexport const compareVersions = compare;\n\n/** Whether a string is an exact semver version. */\nexport const isValidVersion = (version: string): boolean =>\n valid(version) !== null;\n\n/**\n * Map of entry key -> version of the earliest release that registers it, across\n * both `generators` and `packageJsonUpdates`. Resolved only for the entries still\n * missing a version (one already recorded in source wins, so its history doesn't\n * need reading). An entry that hasn't been released is absent.\n *\n * Walks releases newest first and stops as soon as every entry is resolved: an\n * entry that has disappeared from a release's `migrations.json` was first\n * registered by the release after it, which is the one that shipped it.\n *\n * Both sections resolve the same way and share the walk, so the release doesn't\n * read tag history twice. Keys can't collide: a migration is keyed by its own\n * name, an nx bump by the nx version it moves to.\n *\n * @param migrations parsed source migrations.json\n * @param versions released versions in descending semver order\n * @param readReleasedMigrations reads the `migrations.json` published by a given\n * version, or undefined if it predates the manifest\n */\nexport const readShippedMigrationVersions = (\n migrations: MigrationsJson,\n versions: string[],\n readReleasedMigrations: (version: string) => MigrationsJson | undefined,\n): Record<string, string> => {\n const shippedVersions: Record<string, string> = {};\n // A `packageJsonUpdates` entry records `latest` rather than omitting its\n // version, since nx requires the field.\n let unresolved = [\n ...Object.entries(migrations.generators ?? {})\n .filter(([, entry]) => !entry.version)\n .map(([key]) => key),\n ...Object.entries(migrations.packageJsonUpdates ?? {})\n .filter(([, entry]) => entry.version === LATEST_MIGRATIONS_DIR)\n .map(([key]) => key),\n ];\n\n for (const version of versions) {\n if (unresolved.length === 0) {\n break;\n }\n const released = readReleasedMigrations(version);\n const registered = new Set([\n ...Object.keys(released?.generators ?? {}),\n ...Object.keys(released?.packageJsonUpdates ?? {}),\n ]);\n // Entries gone at this release keep the version recorded from the release\n // after it (if any) and stop being looked up.\n unresolved = unresolved.filter((key) => registered.has(key));\n for (const key of unresolved) {\n shippedVersions[key] = version;\n }\n }\n\n return shippedVersions;\n};\n\n/**\n * Rank a migration ships under, lower running first. Unranked entries (no commit\n * history for them, or an every-migration entry with no folder) sort after every\n * ranked one, so a ranked migration always precedes an unranked peer.\n */\nconst UNRANKED = Number.MAX_SAFE_INTEGER;\n\n/**\n * Return a copy of the migrations collection with a `version` stamped onto\n * every generator entry, preserving any already present, and the pending version\n * recorded on any `packageJsonUpdates` entry still holding `latest`.\n *\n * `nx migrate` sorts the run ascending by version and keeps the manifest's order\n * among equal versions, so the order entries are emitted in is the run order\n * within a release. Migrations sharing a version (a batch shipped together, or a\n * whole `v<x.y.z>` folder replayed on a big version jump) are therefore ordered\n * here by the commit that added them — an earlier-committed migration runs\n * first — so a later migration can depend on an earlier one in the same batch.\n * Every-migration entries are emitted last regardless, so they run after the\n * release's own migrations (letting one add a dependency this then brings up to\n * date). Entries with no rank fall back to the manifest's order, which\n * `assembleMigrations` already sorts by key.\n *\n * @param migrations parsed migrations.json to stamp\n * @param shippedVersions migration key -> version of the earliest release\n * tag that registers it (absent for migrations that haven't shipped)\n * @param pendingVersion version the release is about to publish, stamped onto\n * unshipped migrations so their version is one that really shipped\n * @param commitRanks migration key -> rank of the commit that added it (lower is\n * earlier); absent entries fall back to the manifest's order\n */\nexport const stampMigrationVersions = (\n migrations: MigrationsJson,\n shippedVersions: Record<string, string>,\n pendingVersion: string,\n commitRanks: Record<string, number> = {},\n): MigrationsJson => ({\n ...migrations,\n generators: Object.fromEntries(\n Object.entries(migrations.generators ?? {})\n .sort(([keyA, a], [keyB, b]) => {\n const everyDiff =\n Number(a.everyMigration ?? false) - Number(b.everyMigration ?? false);\n if (everyDiff !== 0) {\n return everyDiff;\n }\n // Equal ranks (same commit, or both unranked) fall through to a stable\n // sort, keeping the manifest's key order the assembly already imposed.\n return (\n (commitRanks[keyA] ?? UNRANKED) - (commitRanks[keyB] ?? UNRANKED)\n );\n })\n .map(([name, entry]) => {\n // Source-only marker, stripped from what nx reads.\n const { everyMigration, version: sourceVersion, ...published } = entry;\n // Overrides any source version so it stays ahead of what is installed.\n const version = everyMigration\n ? pendingVersion\n : (sourceVersion ?? shippedVersions[name] ?? pendingVersion);\n return [name, { version, ...published }];\n }),\n ),\n ...(migrations.packageJsonUpdates && {\n packageJsonUpdates: stampPackageJsonUpdates(\n migrations.packageJsonUpdates,\n pendingVersion,\n ),\n }),\n});\n\n/**\n * Version any `packageJsonUpdates` entry still holding `latest` with the release\n * about to publish it, so the nx bump ships under a version `nx migrate` gates on.\n */\nconst stampPackageJsonUpdates = (\n packageJsonUpdates: NonNullable<MigrationsJson['packageJsonUpdates']>,\n pendingVersion: string,\n): NonNullable<MigrationsJson['packageJsonUpdates']> =>\n resolvePackageJsonUpdateVersions(packageJsonUpdates, () => pendingVersion);\n\n/** Directory a newly scaffolded migration lands in, before a release claims it. */\nexport const LATEST_MIGRATIONS_DIR = 'latest';\n\n/** Directory holding the migrations shipped by a given release. */\nexport const versionMigrationsDir = (version: string) => `v${version}`;\n\n/**\n * Key a migration is registered under in `migrations.json`. Prefixed with its\n * directory so reusing a name in a later release can't silently overwrite the\n * one that already shipped.\n */\nexport const migrationKey = (dir: string, name: string) => `${dir}-${name}`;\n\nconst LATEST_KEY_PREFIX = `${LATEST_MIGRATIONS_DIR}-`;\n\n/** Digits in the zero-padded order prefix a bedded-in migration folder carries. */\nconst ORDER_PREFIX_WIDTH = 4;\n\n/**\n * Format a 1-based order into the folder-name prefix that beds it in. Backfill\n * prefixes a released migration's folder with its commit order within the\n * release (`0001-foo`), so the folder name alone sorts a version's migrations\n * into commit order — stamping doesn't have to re-read git for them.\n */\nexport const orderPrefix = (order: number): string =>\n String(order).padStart(ORDER_PREFIX_WIDTH, '0');\n\n/** A migration directory move the caller needs to make on disk. */\nexport interface MigrationDirMove {\n name: string;\n version: string;\n from: string;\n to: string;\n}\n\n/** The base migration name a `latest` key carries, without its folder prefix. */\nconst latestKeyName = (key: string): string =>\n key.startsWith(LATEST_KEY_PREFIX) ? key.slice(LATEST_KEY_PREFIX.length) : key;\n\n/**\n * Record the release that shipped each migration on entries without a version,\n * re-keying them and re-pointing their paths at that release's folder, and\n * return the collection alongside the keys that changed and the directory moves\n * to make on disk.\n *\n * A backfilled migration's new folder name is prefixed with its commit order\n * within the release (`0001-foo`), so the folder layout beds in the order the\n * release ran them: `assembleMigrations` sorts by key, so the prefix alone puts\n * a version's migrations in commit order and stamping never has to re-read git\n * for a released migration. Migrations sharing a commit (a squashed PR) fall\n * back to alphabetical order, matching stamping.\n *\n * Unlike `stampMigrationVersions` this only records already-released versions,\n * leaving the release to decide what a net-new migration gets.\n *\n * @param migrations parsed migrations.json to backfill\n * @param shippedVersions migration key -> version of the earliest release tag\n * that registers it (absent for migrations that haven't shipped)\n * @param commitRanks migration key -> rank of the commit that added it (lower is\n * earlier), used to order the migrations bedded into each release\n */\nexport const backfillMigrationVersions = (\n migrations: MigrationsJson,\n shippedVersions: Record<string, string>,\n commitRanks: Record<string, number> = {},\n): {\n migrations: MigrationsJson;\n backfilled: string[];\n moves: MigrationDirMove[];\n} => {\n const generators: NonNullable<MigrationsJson['generators']> = {};\n const backfilled: string[] = [];\n const moves: MigrationDirMove[] = [];\n // Reported alongside the migrations so the update's PR says an nx bump was\n // dated, and so the caller knows there is something to commit.\n const backfilledUpdates = Object.entries(migrations.packageJsonUpdates ?? {})\n .filter(\n ([key, entry]) =>\n entry.version === LATEST_MIGRATIONS_DIR && shippedVersions[key],\n )\n .map(([key]) => key);\n\n const toBackfill = Object.entries(migrations.generators ?? {}).filter(\n // Pinning an every-migration entry would stop it running on later upgrades.\n ([key, entry]) =>\n !entry.version && !entry.everyMigration && shippedVersions[key],\n );\n\n // The order prefix is a migration's position within its release, so number\n // each version's migrations together, in commit order (alphabetical among a\n // shared commit). All of a release's migrations are backfilled in one run —\n // they sat in `latest` until it shipped — so a version is numbered from 1 here.\n const orderByKey = new Map<string, number>();\n const byVersion = new Map<string, string[]>();\n for (const [key] of toBackfill) {\n const version = shippedVersions[key];\n const keys = byVersion.get(version) ?? [];\n keys.push(key);\n byVersion.set(version, keys);\n }\n for (const keys of byVersion.values()) {\n const ordered = keys.sort((a, b) => {\n const rankDiff =\n (commitRanks[a] ?? Number.MAX_SAFE_INTEGER) -\n (commitRanks[b] ?? Number.MAX_SAFE_INTEGER);\n return rankDiff !== 0\n ? rankDiff\n : latestKeyName(a).localeCompare(latestKeyName(b));\n });\n ordered.forEach((key, index) => {\n orderByKey.set(key, index + 1);\n });\n }\n\n for (const [key, entry] of Object.entries(migrations.generators ?? {})) {\n const version = shippedVersions[key];\n if (entry.version || !version || entry.everyMigration) {\n generators[key] = entry;\n continue;\n }\n\n const name = latestKeyName(key);\n // The commit-order prefix beds the run order into the folder name.\n const prefixedName = `${orderPrefix(orderByKey.get(key) ?? 1)}-${name}`;\n const versionDir = versionMigrationsDir(version);\n const latestSegment = `/${LATEST_MIGRATIONS_DIR}/${name}/`;\n const versionSegment = `/${versionDir}/${prefixedName}/`;\n\n // Re-point each path field at the version folder, recording the move the\n // caller needs to make on disk the first time one is found.\n const repointed: Record<string, unknown> = {};\n let moved = false;\n for (const [field, value] of Object.entries(entry)) {\n if (typeof value !== 'string' || !value.includes(latestSegment)) {\n repointed[field] = value;\n continue;\n }\n repointed[field] = value.replace(latestSegment, versionSegment);\n if (!moved) {\n moved = true;\n const dir = value.slice(0, value.indexOf(latestSegment));\n moves.push({\n name,\n version,\n from: `${dir}${latestSegment}`.replace(/^\\.\\/|\\/$/g, ''),\n to: `${dir}${versionSegment}`.replace(/^\\.\\/|\\/$/g, ''),\n });\n }\n }\n\n generators[migrationKey(versionDir, prefixedName)] = {\n version,\n ...repointed,\n };\n backfilled.push(key);\n }\n\n return {\n migrations: {\n ...migrations,\n generators,\n ...(migrations.packageJsonUpdates && {\n packageJsonUpdates: resolvePackageJsonUpdateVersions(\n migrations.packageJsonUpdates,\n (key) => shippedVersions[key],\n ),\n }),\n },\n backfilled: [...backfilled, ...backfilledUpdates],\n moves,\n };\n};\n\n/**\n * Record the version each `packageJsonUpdates` entry ships under, for those still\n * holding `latest`.\n *\n * The key already identifies the entry — an nx bump is named for the nx version\n * it moves to — so only the `version` field changes. Nothing is re-keyed, which\n * is what lets one release's bump sit alongside the next without either being\n * overwritten before it ships.\n */\nconst resolvePackageJsonUpdateVersions = (\n packageJsonUpdates: NonNullable<MigrationsJson['packageJsonUpdates']>,\n resolve: (key: string) => string | undefined,\n): NonNullable<MigrationsJson['packageJsonUpdates']> =>\n Object.fromEntries(\n Object.entries(packageJsonUpdates).map(([key, entry]) => {\n const version =\n entry.version === LATEST_MIGRATIONS_DIR ? resolve(key) : undefined;\n return [key, version ? { ...entry, version } : entry];\n }),\n );\n"],"names":["compare","valid","compareVersions","isValidVersion","version","readShippedMigrationVersions","migrations","versions","readReleasedMigrations","shippedVersions","unresolved","Object","entries","generators","filter","entry","map","key","packageJsonUpdates","LATEST_MIGRATIONS_DIR","length","released","registered","Set","keys","has","UNRANKED","Number","MAX_SAFE_INTEGER","stampMigrationVersions","pendingVersion","commitRanks","fromEntries","sort","keyA","a","keyB","b","everyDiff","everyMigration","name","sourceVersion","published","stampPackageJsonUpdates","resolvePackageJsonUpdateVersions","versionMigrationsDir","migrationKey","dir","LATEST_KEY_PREFIX","ORDER_PREFIX_WIDTH","orderPrefix","order","String","padStart","latestKeyName","startsWith","slice","backfillMigrationVersions","backfilled","moves","backfilledUpdates","toBackfill","orderByKey","Map","byVersion","get","push","set","values","ordered","rankDiff","localeCompare","forEach","index","prefixedName","versionDir","latestSegment","versionSegment","repointed","moved","field","value","includes","replace","indexOf","from","to","resolve","undefined"],"mappings":"AAAA;;;CAGC,GACD,SAASA,OAAO,EAAEC,KAAK,QAAQ,SAAS;AA6CxC,4DAA4D,GAC5D,OAAO,MAAMC,kBAAkBF,QAAQ;AAEvC,iDAAiD,GACjD,OAAO,MAAMG,iBAAiB,CAACC,UAC7BH,MAAMG,aAAa,KAAK;AAE1B;;;;;;;;;;;;;;;;;;CAkBC,GACD,OAAO,MAAMC,+BAA+B,CAC1CC,YACAC,UACAC;IAEA,MAAMC,kBAA0C,CAAC;IACjD,yEAAyE;IACzE,wCAAwC;IACxC,IAAIC,aAAa;WACZC,OAAOC,OAAO,CAACN,WAAWO,UAAU,IAAI,CAAC,GACzCC,MAAM,CAAC,CAAC,GAAGC,MAAM,GAAK,CAACA,MAAMX,OAAO,EACpCY,GAAG,CAAC,CAAC,CAACC,IAAI,GAAKA;WACfN,OAAOC,OAAO,CAACN,WAAWY,kBAAkB,IAAI,CAAC,GACjDJ,MAAM,CAAC,CAAC,GAAGC,MAAM,GAAKA,MAAMX,OAAO,KAAKe,uBACxCH,GAAG,CAAC,CAAC,CAACC,IAAI,GAAKA;KACnB;IAED,KAAK,MAAMb,WAAWG,SAAU;QAC9B,IAAIG,WAAWU,MAAM,KAAK,GAAG;YAC3B;QACF;QACA,MAAMC,WAAWb,uBAAuBJ;QACxC,MAAMkB,aAAa,IAAIC,IAAI;eACtBZ,OAAOa,IAAI,CAACH,UAAUR,cAAc,CAAC;eACrCF,OAAOa,IAAI,CAACH,UAAUH,sBAAsB,CAAC;SACjD;QACD,0EAA0E;QAC1E,8CAA8C;QAC9CR,aAAaA,WAAWI,MAAM,CAAC,CAACG,MAAQK,WAAWG,GAAG,CAACR;QACvD,KAAK,MAAMA,OAAOP,WAAY;YAC5BD,eAAe,CAACQ,IAAI,GAAGb;QACzB;IACF;IAEA,OAAOK;AACT,EAAE;AAEF;;;;CAIC,GACD,MAAMi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+0,0 @@
1
- {"version":3,"sources":["../../../../../../../packages/nx-plugin/src/migrations/v1.0.0-rc.50/modernize-function-props-cast/migration.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n type MigrationReturnObject,\n type Tree,\n visitNotIgnoredFiles,\n} from '@nx/devkit';\nimport { formatFilesInSubtree } from '../../../utils/format';\nimport {\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n} from '../../../utils/shared-constructs-constants';\n\n/**\n * Replace the legacy angle-bracket FunctionProps type assertion with the modern as syntax in generated API constructs\n *\n * The legacy `<FunctionProps>{ ... }` cast form is not supported by GritQL's\n * TypeScript parser, which silently breaks parsing (and therefore matching)\n * for the entire containing file. Since several other migrations rely on\n * GritQL to update these API construct files, this cast is replaced here with\n * the equivalent, GritQL-compatible `{ ... } as FunctionProps` form. This is\n * matched as an exact literal (rather than via GritQL) since GritQL cannot\n * parse the file while the legacy cast is still present.\n *\n * How to write a migration:\n * - https://nx.dev/docs/kb/migration-generators\n * - What `nextSteps` means: https://nx.dev/docs/reference/devkit/MigrationReturnObject\n *\n * Guardrails:\n * - Pattern-match before writing: skip files that have diverged from the shape\n * your generators produce and report them via `nextSteps`, or consider a\n * hybrid migration, rather than clobbering the user's changes.\n * - Idempotent: re-running must be a no-op.\n * - Format what you write: finish with `formatFilesInSubtree` so the files your\n * migration wrote are formatted correctly.\n */\n\nconst APIS_APP_DIR = `${PACKAGES_DIR}/${SHARED_CONSTRUCTS_DIR}/src/app/apis`;\n\nconst OLD_CAST_OPEN = 'defaultIntegrationOptions: <FunctionProps>{';\nconst NEW_CAST_OPEN = 'defaultIntegrationOptions: {';\nconst OLD_CAST_CLOSE = '\\n },\\n buildDefaultIntegration:';\nconst NEW_CAST_CLOSE =\n '\\n } as FunctionProps,\\n buildDefaultIntegration:';\n\nexport default async function migration(\n tree: Tree,\n): Promise<MigrationReturnObject> {\n const nextSteps: string[] = [];\n\n if (!tree.exists(APIS_APP_DIR)) {\n return { nextSteps };\n }\n\n const apiAppFiles: string[] = [];\n visitNotIgnoredFiles(tree, APIS_APP_DIR, (filePath) => {\n apiAppFiles.push(filePath);\n });\n\n for (const filePath of apiAppFiles) {\n if (!filePath.endsWith('.ts') || filePath.endsWith('/index.ts')) {\n continue;\n }\n const contents = tree.read(filePath, 'utf-8') ?? '';\n if (!contents.includes(OLD_CAST_OPEN)) {\n // Already migrated, or doesn't use this shape.\n continue;\n }\n if (!contents.includes(OLD_CAST_CLOSE)) {\n nextSteps.push(\n `${filePath}: the defaultIntegrationOptions cast has diverged from the generated shape - left untouched. Manually replace \\`<FunctionProps>{ ... }\\` with \\`{ ... } as FunctionProps\\`.`,\n );\n continue;\n }\n tree.write(\n filePath,\n contents\n .replace(OLD_CAST_OPEN, NEW_CAST_OPEN)\n .replace(OLD_CAST_CLOSE, NEW_CAST_CLOSE),\n );\n }\n\n await formatFilesInSubtree(tree);\n\n return { nextSteps };\n}\n"],"names":["visitNotIgnoredFiles","formatFilesInSubtree","PACKAGES_DIR","SHARED_CONSTRUCTS_DIR","APIS_APP_DIR","OLD_CAST_OPEN","NEW_CAST_OPEN","OLD_CAST_CLOSE","NEW_CAST_CLOSE","migration","tree","nextSteps","exists","apiAppFiles","filePath","push","endsWith","contents","read","includes","write","replace"],"mappings":"AAAA;;;CAGC,GACD,SAGEA,oBAAoB,QACf,aAAa;AACpB,SAASC,oBAAoB,QAAQ,2BAAwB;AAC7D,SACEC,YAAY,EACZC,qBAAqB,QAChB,gDAA6C;AAEpD;;;;;;;;;;;;;;;;;;;;;;CAsBC,GAED,MAAMC,eAAe,GAAGF,aAAa,CAAC,EAAEC,sBAAsB,aAAa,CAAC;AAE5E,MAAME,gBAAgB;AACtB,MAAMC,gBAAgB;AACtB,MAAMC,iBAAiB;AACvB,MAAMC,iBACJ;AAEF,eAAe,eAAeC,UAC5BC,IAAU;IAEV,MAAMC,YAAsB,EAAE;IAE9B,IAAI,CAACD,KAAKE,MAAM,CAACR,eAAe;QAC9B,OAAO;YAAEO;QAAU;IACrB;IAEA,MAAME,cAAwB,EAAE;IAChCb,qBAAqBU,MAAMN,cAAc,CAACU;QACxCD,YAAYE,IAAI,CAACD;IACnB;IAEA,KAAK,MAAMA,YAAYD,YAAa;QAClC,IAAI,CAACC,SAASE,QAAQ,CAAC,UAAUF,SAASE,QAAQ,CAAC,cAAc;YAC/D;QACF;QACA,MAAMC,WAAWP,KAAKQ,IAAI,CAACJ,UAAU,YAAY;QACjD,IAAI,CAACG,SAASE,QAAQ,CAACd,gBAAgB;YAErC;QACF;QACA,IAAI,CAACY,SAASE,QAAQ,CAACZ,iBAAiB;YACtCI,UAAUI,IAAI,CACZ,GAAGD,SAAS,2KAA2K,CAAC;YAE1L;QACF;QACAJ,KAAKU,KAAK,CACRN,UACAG,SACGI,OAAO,CAAChB,eAAeC,eACvBe,OAAO,CAACd,gBAAgBC;IAE/B;IAEA,MAAMP,qBAAqBS;IAE3B,OAAO;QAAEC;IAAU;AACrB"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../../../../packages/nx-plugin/src/migrations/v1.0.0-rc.50/restrict-cors-to-custom-domains/migration.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n type MigrationReturnObject,\n type Tree,\n visitNotIgnoredFiles,\n} from '@nx/devkit';\nimport {\n addDestructuredImport,\n addStarExport,\n applyGritQL,\n} from '../../../utils/ast';\nimport { formatFilesInSubtree } from '../../../utils/format';\nimport { isEsmWorkspace } from '../../../utils/module-format';\nimport {\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n} from '../../../utils/shared-constructs-constants';\n\n/**\n * Include CloudFront custom domain aliases in restrictCorsTo and UserIdentity callback URLs\n *\n * How to write a migration:\n * - https://nx.dev/docs/kb/migration-generators\n * - What `nextSteps` means: https://nx.dev/docs/reference/devkit/MigrationReturnObject\n *\n * Guardrails:\n * - Pattern-match before writing: skip files that have diverged from the shape\n * your generators produce and report them via `nextSteps`, rather than\n * clobbering the user's changes.\n * - Idempotent: re-running must be a no-op.\n * - Format what you write: finish with `formatFilesInSubtree` so the files your\n * migration wrote are formatted correctly.\n */\n\nconst CORE_DIR = `${PACKAGES_DIR}/${SHARED_CONSTRUCTS_DIR}/src/core`;\nconst APIS_APP_DIR = `${PACKAGES_DIR}/${SHARED_CONSTRUCTS_DIR}/src/app/apis`;\nconst CLOUDFRONT_CORE_FILE = `${CORE_DIR}/cloudfront.ts`;\nconst CORE_INDEX_FILE = `${CORE_DIR}/index.ts`;\nconst USER_IDENTITY_FILE = `${CORE_DIR}/user-identity.ts`;\n\nconst CLOUDFRONT_HELPER_CONTENT = `import { CfnDistribution, Distribution } from 'aws-cdk-lib/aws-cloudfront';\n\n/**\n * Finds the domain names associated with a CloudFront distribution.\n *\n * Includes the distribution's default \\`*.cloudfront.net\\` domain name plus any custom\n * domain names (aliases) configured on it.\n */\nexport const findCloudFrontDomainNames = (\n distribution: Distribution,\n): string[] => {\n const cfnDistribution = distribution.node.defaultChild as CfnDistribution;\n const distributionConfig =\n cfnDistribution.distributionConfig as CfnDistribution.DistributionConfigProperty;\n return [distribution.domainName, ...(distributionConfig.aliases ?? [])];\n};\n`;\n\n// Rewrites the `restrictCorsTo` body as produced by generators prior to this fix.\nconst RESTRICT_CORS_TO_GRITQL_PATTERN =\n \"`origins.map(($o) => typeof $o === 'string' ? $o : 'cloudFrontDistribution' in $o ? $branch1 : $branch2)` where { $branch1 <: contains `distributionDomainName`, $branch2 <: contains `distributionDomainName` } => raw`origins.flatMap(($o) => typeof $o === 'string' ? [$o] : findCloudFrontDomainNames('cloudFrontDistribution' in $o ? $o.cloudFrontDistribution : $o).map((domain) => \\\\`https://${domain}\\\\`))`\";\n\n// Rewrites UserIdentity's callback/logout URL logic as produced by generators\n// prior to this fix.\nconst USER_IDENTITY_CALLBACK_URLS_GRITQL_PATTERN =\n '`this.findCloudFrontDomainNames()` => `Stack.of(this).node.findAll().filter((child): child is Distribution => child instanceof Distribution).flatMap(findCloudFrontDomainNames)`';\n\nexport default async function migration(\n tree: Tree,\n): Promise<MigrationReturnObject> {\n const nextSteps: string[] = [];\n\n if (!tree.exists(CORE_INDEX_FILE)) {\n // No common/constructs shared library in this workspace - nothing to migrate.\n return { nextSteps };\n }\n\n const esm = isEsmWorkspace(tree);\n const apiCloudFrontImportSpecifier = esm\n ? '../../core/cloudfront.js'\n : '../../core/cloudfront';\n const coreCloudFrontImportSpecifier = esm\n ? './cloudfront.js'\n : './cloudfront';\n\n if (!tree.exists(CLOUDFRONT_CORE_FILE)) {\n tree.write(CLOUDFRONT_CORE_FILE, CLOUDFRONT_HELPER_CONTENT);\n }\n await addStarExport(tree, CORE_INDEX_FILE, './cloudfront.js');\n\n const apiAppFiles: string[] = [];\n visitNotIgnoredFiles(tree, APIS_APP_DIR, (filePath) => {\n apiAppFiles.push(filePath);\n });\n\n for (const filePath of apiAppFiles) {\n if (!filePath.endsWith('.ts') || filePath.endsWith('/index.ts')) {\n continue;\n }\n const rewrote = await applyGritQL(\n tree,\n filePath,\n RESTRICT_CORS_TO_GRITQL_PATTERN,\n );\n if (rewrote) {\n await addDestructuredImport(\n tree,\n filePath,\n ['findCloudFrontDomainNames'],\n apiCloudFrontImportSpecifier,\n );\n continue;\n }\n const contents = tree.read(filePath, 'utf-8') ?? '';\n if (!contents.includes('findCloudFrontDomainNames(')) {\n nextSteps.push(\n `${filePath}: restrictCorsTo has diverged from the generated shape - left untouched. Manually apply the CloudFront custom domain fix (see findCloudFrontDomainNames in common/constructs/src/core/cloudfront.ts).`,\n );\n }\n // Otherwise already migrated - silent skip.\n }\n\n if (tree.exists(USER_IDENTITY_FILE)) {\n const rewrote = await applyGritQL(\n tree,\n USER_IDENTITY_FILE,\n USER_IDENTITY_CALLBACK_URLS_GRITQL_PATTERN,\n );\n if (rewrote) {\n await applyGritQL(\n tree,\n USER_IDENTITY_FILE,\n \"`import { CfnDistribution, Distribution } from 'aws-cdk-lib/aws-cloudfront'` => `import { Distribution } from 'aws-cdk-lib/aws-cloudfront';`\",\n );\n await applyGritQL(\n tree,\n USER_IDENTITY_FILE,\n \"or { `// Includes each distribution's default domain name plus any custom domain names (aliases) configured on it.` => ., `private findCloudFrontDomainNames = (): string[] => $body` => . }\",\n );\n await addDestructuredImport(\n tree,\n USER_IDENTITY_FILE,\n ['findCloudFrontDomainNames'],\n coreCloudFrontImportSpecifier,\n );\n } else {\n const contents = tree.read(USER_IDENTITY_FILE, 'utf-8') ?? '';\n if (!contents.includes('.flatMap(findCloudFrontDomainNames)')) {\n nextSteps.push(\n `${USER_IDENTITY_FILE}: the callback URL logic has diverged from the generated shape - left untouched. Manually apply the shared findCloudFrontDomainNames helper (see common/constructs/src/core/cloudfront.ts).`,\n );\n }\n // Otherwise already migrated - silent skip.\n }\n }\n\n await formatFilesInSubtree(tree);\n\n return { nextSteps };\n}\n"],"names":["visitNotIgnoredFiles","addDestructuredImport","addStarExport","applyGritQL","formatFilesInSubtree","isEsmWorkspace","PACKAGES_DIR","SHARED_CONSTRUCTS_DIR","CORE_DIR","APIS_APP_DIR","CLOUDFRONT_CORE_FILE","CORE_INDEX_FILE","USER_IDENTITY_FILE","CLOUDFRONT_HELPER_CONTENT","RESTRICT_CORS_TO_GRITQL_PATTERN","USER_IDENTITY_CALLBACK_URLS_GRITQL_PATTERN","migration","tree","nextSteps","exists","esm","apiCloudFrontImportSpecifier","coreCloudFrontImportSpecifier","write","apiAppFiles","filePath","push","endsWith","rewrote","contents","read","includes"],"mappings":"AAAA;;;CAGC,GACD,SAGEA,oBAAoB,QACf,aAAa;AACpB,SACEC,qBAAqB,EACrBC,aAAa,EACbC,WAAW,QACN,wBAAqB;AAC5B,SAASC,oBAAoB,QAAQ,2BAAwB;AAC7D,SAASC,cAAc,QAAQ,kCAA+B;AAC9D,SACEC,YAAY,EACZC,qBAAqB,QAChB,gDAA6C;AAEpD;;;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I,SAASE,QAAQ,CAAC,+BAA+B;YACpDb,UAAUQ,IAAI,CACZ,GAAGD,SAAS,qMAAqM,CAAC;QAEtN;IACA,4CAA4C;IAC9C;IAEA,IAAIR,KAAKE,MAAM,CAACP,qBAAqB;QACnC,MAAMgB,UAAU,MAAMzB,YACpBc,MACAL,oBACAG;QAEF,IAAIa,SAAS;YACX,MAAMzB,YACJc,MACAL,oBACA;YAEF,MAAMT,YACJc,MACAL,oBACA;YAEF,MAAMX,sBACJgB,MACAL,oBACA;gBAAC;aAA4B,EAC7BU;QAEJ,OAAO;YACL,MAAMO,WAAWZ,KAAKa,IAAI,CAAClB,oBAAoB,YAAY;YAC3D,IAAI,CAACiB,SAASE,QAAQ,CAAC,wCAAwC;gBAC7Db,UAAUQ,IAAI,CACZ,GAAGd,mBAAmB,2LAA2L,CAAC;YAEtN;QACA,4CAA4C;QAC9C;IACF;IAEA,MAAMR,qBAAqBa;IAE3B,OAAO;QAAEC;IAAU;AACrB"}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../../../../../packages/nx-plugin/src/migrations/v1.0.0-rc.50/terraform-bootstrap-adopt-existing-bucket/migration.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n getProjects,\n joinPathFragments,\n type MigrationReturnObject,\n type Tree,\n} from '@nx/devkit';\nimport { TERRAFORM_PROJECT_GENERATOR_INFO } from '../../../terraform/project/generator';\nimport {\n applyGritQL,\n GRIT_INSERT_PLACEHOLDER,\n insertViaGritQL,\n matchGritQL,\n} from '../../../utils/ast';\nimport { formatFilesInSubtree } from '../../../utils/format';\n\n/**\n * Adopt an existing Terraform state bucket in the vended bootstrap script when its state object is missing\n *\n * The state bucket stores its own tfstate inside itself, so if that object is\n * deleted while the bucket survives, `bootstrap` reads the 404 as a first run\n * and asks terraform to create a bucket that already exists — failing with\n * `BucketAlreadyOwnedByYou` on every subsequent run, with no retry that clears\n * it. The vended script now imports the existing bucket instead.\n *\n * Every edit is expressed as a GritQL rewrite so the script is matched on its\n * AST rather than its formatting.\n *\n * How to write a migration:\n * - https://nx.dev/docs/kb/migration-generators\n * - What `nextSteps` means: https://nx.dev/docs/reference/devkit/MigrationReturnObject\n *\n * Guardrails:\n * - Pattern-match before writing: skip files that have diverged from the shape\n * your generators produce and report them via `nextSteps`, or consider a\n * hybrid migration, rather than clobbering the user's changes.\n * - Idempotent: re-running must be a no-op.\n * - Format what you write: finish with `formatFilesInSubtree` so the files your\n * migration wrote are formatted correctly.\n */\n\n// Guards the whole migration: present only once the import step exists.\nconst MIGRATED_PATTERN = '`bucketExists($_, $_)`';\n\n// Every edit site, matched structurally so formatting and argument layout\n// don't affect whether the script is recognised.\nconst STATE_FETCH_TRY_PATTERN =\n 'try_statement() as $try where { $try <: contains `GetObjectCommand` }';\nconst STATE_FLAG_SET_PATTERN = '`if (out.Body) { $body }`';\nconst HELPER_PATTERN = '`const main = async () => { $body }`';\nconst INIT_PATTERN = \"`execFileSync('terraform', ['init'], $opts)`\";\nconst S3_IMPORT_PATTERN =\n \"`import { $before, GetObjectCommand, $after } from '@aws-sdk/client-s3'`\";\nconst HEADER_COMMENT_PATTERN =\n 'comment() as $c where { $c <: includes \"state back to S3.\" }';\n\n// GritQL snippets are parsed as backtick-quoted patterns, so any backtick in\n// the inserted source has to survive that layer escaped.\nconst BUCKET_EXISTS_HELPER = `// S3 answers 404 only when the name is genuinely free; 403 means it exists\n// but is not readable with these credentials.\nconst bucketExists = async (s3: S3Client, bucket: string) => {\n try {\n await s3.send(new HeadBucketCommand({ Bucket: bucket }));\n return true;\n } catch (err: any) {\n const status = err?.$metadata?.httpStatusCode;\n if (status === 404) return false;\n if (status === 403) return true;\n throw err;\n }\n};`;\n\nconst IMPORT_STEP = `// The bucket holds its own state, so losing the state object while the\n // bucket survives would otherwise wedge bootstrap on a permanent\n // \\`BucketAlreadyOwnedByYou\\`. Adopt the existing bucket instead.\n if (!haveState && (await bucketExists(s3, bucket))) {\n console.log(\n \\`State bucket \\${bucket} already exists but its bootstrap state is missing — importing it.\\`,\n );\n execFileSync(\n 'terraform',\n [\n 'import',\n \\`-state=\\${tfStatePath}\\`,\n \\`-var=aws_region=\\${region}\\`,\n 'aws_s3_bucket.terraform_state',\n bucket,\n ],\n { cwd: bootstrapDir, stdio: 'inherit' },\n );\n }`;\n\n// Rewritten wholesale rather than appended to, since the summary sentence\n// changes rather than gaining a clause.\nconst NEW_HEADER_COMMENT = `/**\n * Bootstraps the remote Terraform state bucket.\n *\n * Equivalent to \\\\\\`cdk bootstrap\\\\\\` — resolves account + region from the AWS\n * SDK credential chain, pulls any existing bootstrap tfstate from S3,\n * runs \\\\\\`terraform apply\\\\\\` in the \\\\\\`bootstrap\\\\\\` dir, then pushes the new\n * state back to S3. Adopts an already-existing state bucket when its\n * state object is missing.\n */`;\n\nconst DIVERGED_NEXT_STEP = (filePath: string) =>\n `${filePath}: the bootstrap script has diverged from the generated shape - left untouched. Manually \\`terraform import aws_s3_bucket.terraform_state <bucket>\\` before \\`terraform apply\\` when the state bucket exists but its \\`bootstrap.tfstate\\` object does not, otherwise bootstrap fails with BucketAlreadyOwnedByYou.`;\n\nexport default async function migration(\n tree: Tree,\n): Promise<MigrationReturnObject> {\n const nextSteps: string[] = [];\n\n // Terraform application projects are the only ones that vend bootstrap.ts.\n const bootstrapScripts = [...getProjects(tree).values()]\n .filter(\n (project) =>\n (project.metadata as any)?.generator ===\n TERRAFORM_PROJECT_GENERATOR_INFO.id,\n )\n .map((project) => joinPathFragments(project.root, 'scripts/bootstrap.ts'))\n .filter((filePath) => tree.exists(filePath));\n\n for (const filePath of bootstrapScripts) {\n if (await matchGritQL(tree, filePath, MIGRATED_PATTERN)) {\n // Already migrated - silent skip keeps re-runs a no-op.\n continue;\n }\n\n // Confirm every edit site is present before writing any of them, so a\n // script that only partly matches is left whole rather than half-edited.\n const allSitesPresent = (\n await Promise.all(\n [\n STATE_FETCH_TRY_PATTERN,\n STATE_FLAG_SET_PATTERN,\n HELPER_PATTERN,\n INIT_PATTERN,\n S3_IMPORT_PATTERN,\n HEADER_COMMENT_PATTERN,\n ].map((pattern) => matchGritQL(tree, filePath, pattern)),\n )\n ).every(Boolean);\n\n if (!allSitesPresent) {\n nextSteps.push(DIVERGED_NEXT_STEP(filePath));\n continue;\n }\n\n // `haveState` distinguishes \"no remote state\" from \"no bucket\", so the\n // import only runs when terraform has no prior knowledge of the bucket.\n await insertViaGritQL(\n tree,\n filePath,\n `${STATE_FETCH_TRY_PATTERN} => \\`${GRIT_INSERT_PLACEHOLDER}\\n $try\\``,\n 'let haveState = false;',\n );\n await applyGritQL(\n tree,\n filePath,\n `${STATE_FLAG_SET_PATTERN} => \\`if (out.Body) {\\n $body\\n haveState = true;\\n }\\``,\n );\n await insertViaGritQL(\n tree,\n filePath,\n `${HELPER_PATTERN} => \\`${GRIT_INSERT_PLACEHOLDER}\\n\\nconst main = async () => { $body }\\``,\n BUCKET_EXISTS_HELPER,\n );\n await insertViaGritQL(\n tree,\n filePath,\n `${INIT_PATTERN} => \\`execFileSync('terraform', ['init'], $opts);\\n\\n ${GRIT_INSERT_PLACEHOLDER}\\n\\``,\n IMPORT_STEP,\n );\n\n // Placed in the generator's import position rather than appended, so a\n // migrated workspace matches a freshly generated one.\n await applyGritQL(\n tree,\n filePath,\n `${S3_IMPORT_PATTERN} => \\`import { $before, GetObjectCommand, HeadBucketCommand, $after } from '@aws-sdk/client-s3'\\``,\n );\n\n await applyGritQL(\n tree,\n filePath,\n `${HEADER_COMMENT_PATTERN} => \\`${NEW_HEADER_COMMENT}\\``,\n );\n }\n\n await formatFilesInSubtree(tree);\n\n return { nextSteps };\n}\n"],"names":["getProjects","joinPathFragments","TERRAFORM_PROJECT_GENERATOR_INFO","applyGritQL","GRIT_INSERT_PLACEHOLDER","insertViaGritQL","matchGritQL","formatFilesInSubtree","MIGRATED_PATTERN","STATE_FETCH_TRY_PATTERN","STATE_FLAG_SET_PATTERN","HELPER_PATTERN","INIT_PATTERN","S3_IMPORT_PATTERN","HEADER_COMMENT_PATTERN","BUCKET_EXISTS_HELPER","IMPORT_STEP","NEW_HEADER_COMMENT","DIVERGED_NEXT_STEP","filePath","migration","tree","nextSteps","bootstrapScripts","values","filter","project","metadata","generator","id","map","root","exists","allSitesPresent","Promise","all","pattern","every","Boolean","push"],"mappings":"AAAA;;;CAGC,GACD,SACEA,WAAW,EACXC,iBAAiB,QAGZ,aAAa;AACpB,SAASC,gCAAgC,QAAQ,0CAAuC;AACxF,SACEC,WAAW,EACXC,uBAAuB,EACvBC,eAAe,EACfC,WAAW,QACN,wBAAqB;AAC5B,SAASC,oBAAoB,QAAQ,2BAAwB;AAE7D;;;;;;;;;;;;;;;;;;;;;;;CAuBC,GAED,wEAAwE;AACxE,MAAMC,mBAAmB;AAEzB,0EAA0E;AAC1E,iDAAiD;AACjD,MAAMC,0BACJ;AACF,MAAMC,yBAAyB;AAC/B,MAAMC,iBAAiB;AACvB,MAAMC,eAAe;AACrB,MAAMC,oBACJ;AACF,MAAMC,yBACJ;AAEF,6EAA6E;AAC7E,yDAAyD;AACzD,MAAMC,uBAAuB,CAAC;;;;;;;;;;;;EAY5B,CAAC;AAEH,MAAMC,cAAc,CAAC;;;;;;;;;;;;;;;;;;GAkBlB,CAAC;AAEJ,0EAA0E;AAC1E,wCAAwC;AACxC,MAAMC,qBAAqB,CAAC;;;;;;;;GAQzB,CAAC;AAEJ,MAAMC,qBAAqB,CAACC,WAC1B,GAAGA,SAAS,kTAAkT,CAAC;AAEjU,eAAe,eAAeC,UAC5BC,IAAU;IAEV,MAAMC,YAAsB,EAAE;IAE9B,2EAA2E;IAC3E,MAAMC,mBAAmB;WAAIvB,YAAYqB,MAAMG,MAAM;KAAG,CACrDC,MAAM,CACL,CAACC,UACC,AAACA,QAAQC,QAAQ,EAAUC,cAC3B1B,iCAAiC2B,EAAE,EAEtCC,GAAG,CAAC,CAACJ,UAAYzB,kBAAkByB,QAAQK,IAAI,EA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