@aws/nx-plugin 1.0.0-rc.95 → 1.0.0-rc.96
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE-THIRD-PARTY +234 -38
- package/migrations.json +34 -1
- package/package.json +6 -6
- package/src/infra/app/__snapshots__/generator.spec.ts.snap +4 -10
- package/src/preset/__snapshots__/generator.spec.ts.snap +3 -5
- package/src/py/agent/a2a-connection/generator.d.ts +1 -1
- package/src/py/agent/gateway-connection/generator.d.ts +1 -1
- package/src/py/agent/mcp-connection/generator.d.ts +1 -1
- package/src/py/agent/react-connection/generator.d.ts +29 -0
- package/src/ts/agent/react-connection/generator.d.ts +37 -0
- package/src/ts/lib/generator.d.ts +13 -0
- package/src/ts/lib/generator.js +3 -2
- package/src/ts/lib/generator.js.map +1 -1
- package/src/ts/lib/ts-project-utils.d.ts +17 -1
- package/src/ts/lib/ts-project-utils.js +29 -0
- package/src/ts/lib/ts-project-utils.js.map +1 -1
- package/src/ts/lib/vitest.d.ts +6 -0
- package/src/ts/lib/vitest.js +16 -1
- package/src/ts/lib/vitest.js.map +1 -1
- package/src/ts/react-website/agui/generator.d.ts +21 -0
- package/src/ts/react-website/app/__snapshots__/generator.spec.ts.snap +26 -22
- package/src/ts/react-website/app/generator.d.ts +42 -0
- package/src/ts/react-website/app/generator.js +2 -1
- package/src/ts/react-website/app/generator.js.map +1 -1
- package/src/utils/dependencies.js +1 -10
- package/src/utils/dependencies.js.map +1 -1
- package/src/utils/shared-shadcn.d.ts +13 -0
- package/src/utils/shared-shadcn.js +3 -2
- package/src/utils/shared-shadcn.js.map +1 -1
- package/src/utils/test.js +15 -0
- package/src/utils/test.js.map +1 -1
- package/src/utils/version-upgrade-migration/sync-vended-versions.js +4 -4
- package/src/utils/version-upgrade-migration/sync-vended-versions.js.map +1 -1
- package/src/utils/versions.d.ts +10 -9
- package/src/utils/versions.js +10 -8
- package/src/utils/versions.js.map +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../../packages/nx-plugin/src/ts/react-website/app/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n detectPackageManager,\n generateFiles,\n joinPathFragments,\n names,\n OverwriteStrategy,\n readProjectConfiguration,\n removeDependenciesFromPackageJson,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { applicationGenerator } from '@nx/react';\nimport { relative, sep } from 'path';\nimport { addTsDependencies } from '../../../utils/add-dependencies.js';\nimport {\n addDestructuredImport,\n addSingleImport,\n appendToArrayViaGritQL,\n applyGritQL,\n} from '../../../utils/ast.js';\nimport {\n declareDependencies,\n ownedElsewhere,\n} from '../../../utils/declared-dependencies.js';\nimport { formatFilesInSubtree } from '../../../utils/format.js';\nimport { resolveIac } from '../../../utils/iac.js';\nimport { installDependencies } from '../../../utils/install.js';\nimport { addGeneratorMetricsIfApplicable } from '../../../utils/metrics.js';\nimport { kebabCase, toClassName, toKebabCase } from '../../../utils/names.js';\nimport { getNpmScopePrefix } from '../../../utils/npm-scope.js';\nimport {\n addGeneratorMetadata,\n getGeneratorInfo,\n type NxGeneratorInfo,\n} from '../../../utils/nx.js';\nimport { sortObjectKeys } from '../../../utils/object.js';\nimport { getRelativePathToRoot } from '../../../utils/paths.js';\nimport { getPackageManagerDisplayCommands } from '../../../utils/pkg-manager.js';\nimport { assignPort } from '../../../utils/port.js';\nimport {\n SHARED_CONSTRUCTS_DEPENDENCIES,\n sharedConstructsGenerator,\n} from '../../../utils/shared-constructs.js';\nimport {\n type IacMetadata,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n TERRAFORM_WEBSITE_RUNTIME_CONFIG_FILE,\n} from '../../../utils/shared-constructs-constants.js';\nimport {\n addSharedShadcnDependency,\n SHADCN_DEPENDENCIES,\n sharedShadcnGenerator,\n} from '../../../utils/shared-shadcn.js';\nimport { withVersions } from '../../../utils/versions.js';\nimport {\n addWebsiteInfra,\n WEBSITE_CONSTRUCTS_PY_DEPENDENCIES,\n} from '../../../utils/website-constructs/website-constructs.js';\nimport { configureTsProject } from '../../lib/ts-project-utils.js';\nimport { VITEST_DEPENDENCIES } from '../../lib/vitest.js';\n// typescript factory imports removed — now using GritQL for vite config transforms\nimport type {\n TsReactWebsiteGeneratorSchema,\n WebsiteInfraOption,\n} from './schema';\n\n/** The metadata this generator records, which its predicates read. */\nexport interface TsReactWebsiteMetadata extends IacMetadata {\n readonly ux: UxOption;\n readonly framework: string;\n readonly infra: WebsiteInfraOption;\n readonly tailwind: boolean;\n readonly tanstackRouter: boolean;\n}\n\n// Each entry names the branch it belongs to, so the same declaration drives both\n// adding and the version sync.\nexport const DEPENDENCIES = declareDependencies<TsReactWebsiteMetadata>()({\n ts: [\n { name: 'react' },\n { name: 'react-dom' },\n // Build/test tooling imported only from vite.config.mts stays at the root.\n { name: '@nx/react', dev: true, root: true },\n { name: '@vitest/ui', dev: true, root: true },\n {\n name: '@cloudscape-design/components',\n when: (m) => m.ux === 'cloudscape',\n },\n {\n name: '@cloudscape-design/board-components',\n when: (m) => m.ux === 'cloudscape',\n },\n {\n name: '@cloudscape-design/global-styles',\n when: (m) => m.ux === 'cloudscape',\n },\n // Shared shadcn components live in the common/shadcn package, but the\n // website's own generated components (e.g. the tanstack-router sidebar)\n // import lucide-react directly, so the website must declare it.\n {\n name: 'lucide-react',\n when: (m) => m.ux === 'shadcn' && m.tanstackRouter,\n },\n { name: 'tailwindcss', when: (m) => m.tailwind },\n {\n name: '@tailwindcss/vite',\n when: (m) => m.tailwind,\n dev: true,\n root: true,\n },\n { name: '@tanstack/react-router', when: (m) => m.tanstackRouter },\n {\n name: '@tanstack/router-plugin',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/router-generator',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/virtual-file-routes',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/router-utils',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n // Declared for its pinned version, which goes into npm's `overrides` below.\n { name: 'express', versionOnly: true },\n ...ownedElsewhere(SHADCN_DEPENDENCIES),\n ...ownedElsewhere(VITEST_DEPENDENCIES),\n ...ownedElsewhere(SHARED_CONSTRUCTS_DEPENDENCIES),\n ],\n py: ownedElsewhere(WEBSITE_CONSTRUCTS_PY_DEPENDENCIES),\n});\n\nexport const SUPPORTED_UX_PROVIDERS = ['none', 'cloudscape', 'shadcn'] as const;\n\nexport type UxOption = (typeof SUPPORTED_UX_PROVIDERS)[number];\n\nexport type Ux = UxOption;\n\nexport const REACT_WEBSITE_APP_GENERATOR_INFO: NxGeneratorInfo =\n getGeneratorInfo(import.meta.filename);\n\nexport async function tsReactWebsiteGenerator(\n tree: Tree,\n schema: TsReactWebsiteGeneratorSchema,\n) {\n const tailwind = schema.tailwind ?? true;\n const tanstackRouter = schema.tanstackRouter ?? true;\n const ux: Ux = schema.ux ?? 'shadcn';\n if (ux === 'shadcn' && !tailwind) {\n throw new Error('Shadcn requires TailwindCSS to be enabled.');\n }\n const npmScopePrefix = getNpmScopePrefix(tree);\n const scopeAlias = npmScopePrefix;\n const websiteNameClassName = toClassName(schema.name);\n const websiteNameKebabCase = toKebabCase(schema.name);\n const fullyQualifiedName = `${npmScopePrefix}${websiteNameKebabCase}`;\n // NB: interactive nx generator cli can pass empty string\n const websiteContentPath = joinPathFragments(\n schema.directory || '.',\n schema.subDirectory || websiteNameKebabCase,\n );\n\n const projectAlreadyExists = tree.exists(\n joinPathFragments(websiteContentPath, 'project.json'),\n );\n\n // TODO: consider exposing and supporting e2e tests\n const e2eTestRunner = 'none';\n\n if (!projectAlreadyExists) {\n await applicationGenerator(tree, {\n ...schema,\n name: fullyQualifiedName,\n directory: websiteContentPath,\n routing: false,\n e2eTestRunner,\n linter: 'none',\n bundler: 'vite',\n unitTestRunner: 'vitest',\n useProjectJson: true,\n style: 'css',\n // Register the @nx/vite and @nx/vitest plugins so build/serve/test\n // targets are inferred rather than emitting deprecated executor targets.\n addPlugin: true,\n });\n\n // Pin the inferred target names. The vite production build is exposed as\n // `bundle` (which produces the deployable artifact), leaving `build` as an\n // aggregator over lint/compile/test/bundle. vite's own typecheck is dropped\n // in favour of the tsc `compile`.\n updateJson(tree, 'nx.json', (nxJson) => {\n for (const plugin of nxJson.plugins ?? []) {\n if (typeof plugin === 'string') continue;\n if (plugin.plugin === '@nx/vite/plugin') {\n plugin.options = {\n ...plugin.options,\n buildTargetName: 'bundle',\n // Map both of vite's inferred dev-server targets onto `serve` so the\n // plugin doesn't emit a separate `dev`; we author our own `dev`\n // below running the local-dev vite mode.\n serveTargetName: 'serve',\n devTargetName: 'serve',\n previewTargetName: 'preview',\n serveStaticTargetName: 'serve-static',\n typecheckTargetName: 'vite:typecheck',\n };\n } else if (plugin.plugin === '@nx/vitest') {\n plugin.options = {\n ...plugin.options,\n testTargetName: 'test',\n };\n }\n }\n return nxJson;\n });\n\n // Replace with simpler sample source code\n tree.delete(joinPathFragments(websiteContentPath, 'src'));\n }\n\n const projectConfiguration = readProjectConfiguration(\n tree,\n fullyQualifiedName,\n );\n\n const targets = projectConfiguration.targets;\n\n // Each website gets its own explicit dev-server port. Vite itself already\n // auto-increments past a port already in use, so two websites don't actually\n // collide — but which port each one lands on then depends on start order and\n // can't be known ahead of time. An explicit, per-project port is what lets\n // the Cognito callback URL allow-list (added when auth is configured) be\n // computed deterministically instead.\n const port = assignPort(tree, projectConfiguration, 4200);\n // @nx/react's vite config defaults to 4200 for the dev server and 4300 for\n // preview; keep that +100 relationship so the pair stays predictable.\n const previewPort = port + 100;\n\n const infra = schema.infra ?? 'cloudfront-s3';\n\n // Configure load-runtime-config target based on IaC provider (only when infra is not none)\n const iac = infra !== 'none' ? await resolveIac(tree, schema.iac) : undefined;\n\n if (iac === 'cdk') {\n targets['load-runtime-config'] = {\n executor: 'nx:run-commands',\n metadata: {\n description: `Load runtime config from your deployed stack for dev purposes. You must set your AWS CLI credentials whilst calling '${getPackageManagerDisplayCommands().exec} nx load-runtime-config ${fullyQualifiedName}'`,\n },\n options: {\n command: `aws s3 cp s3://\\`aws cloudformation describe-stacks --query \"Stacks[?starts_with(StackName, '${kebabCase(npmScopePrefix)}-')][].Outputs[] | [?contains(OutputKey, '${websiteNameClassName}WebsiteBucketName')].OutputValue\" --output text\\`/runtime-config.json \"{projectRoot}/public/runtime-config.json\"`,\n },\n };\n } else if (iac === 'terraform') {\n targets['load-runtime-config'] = {\n executor: 'nx:run-commands',\n metadata: {\n description:\n \"Load runtime config from most recently applied terraform env for dev purposes. Copies the runtime config from the Terraform dist directory to the website's public directory.\",\n },\n options: {\n command:\n 'node -e \"const fs=require(\\'fs\\');fs.mkdirSync(process.env.DEST_DIR,{recursive:true});fs.copyFileSync(process.env.SRC_FILE,process.env.DEST_FILE);\"',\n env: {\n SRC_FILE: TERRAFORM_WEBSITE_RUNTIME_CONFIG_FILE,\n DEST_DIR: `{projectRoot}/public`,\n DEST_FILE: `{projectRoot}/public/runtime-config.json`,\n },\n },\n };\n }\n\n if (!projectAlreadyExists) {\n targets['compile'] = {\n // `tsc` needs its dependencies' declarations, which `compile` emits — not\n // their lint or test results.\n dependsOn: ['^compile'],\n executor: 'nx:run-commands',\n outputs: ['{workspaceRoot}/dist/{projectRoot}/tsc'],\n options: {\n command: 'tsc --build tsconfig.app.json',\n cwd: '{projectRoot}',\n },\n };\n // bundle is the @nx/vite/plugin inferred `vite build` (writing to the\n // bundle dir configured in vite.config) — it produces the deployable\n // artifact. build aggregates lint/compile/test/bundle.\n targets['build'] = {\n dependsOn: ['lint', 'compile', 'test', 'bundle'],\n };\n targets['assemble'] = {\n dependsOn: ['compile', 'bundle'],\n };\n\n // Run the website and its connected dependencies locally. Mirrors the\n // inferred `serve` target but with the local-dev vite mode.\n targets['dev'] = {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n command: 'vite --mode local-dev',\n cwd: '{projectRoot}',\n },\n };\n }\n\n projectConfiguration.targets = sortObjectKeys(targets);\n\n updateProjectConfiguration(tree, fullyQualifiedName, projectConfiguration);\n\n // Recorded here and read by the declaration's predicates, so the packages\n // added below are exactly the ones the version sync will own.\n const metadata: TsReactWebsiteMetadata = {\n ux,\n framework: 'react',\n infra,\n tailwind,\n tanstackRouter,\n // Undefined when no infrastructure was generated, so neither provider's\n // packages were added.\n ...(iac ? { iac } : {}),\n };\n addGeneratorMetadata(\n tree,\n projectConfiguration.name,\n REACT_WEBSITE_APP_GENERATOR_INFO,\n metadata,\n );\n\n await configureTsProject(\n tree,\n {\n dir: websiteContentPath,\n fullyQualifiedName,\n },\n DEPENDENCIES,\n );\n\n if (ux === 'shadcn') {\n await sharedShadcnGenerator(tree, DEPENDENCIES);\n addSharedShadcnDependency(tree, websiteContentPath);\n }\n\n if (iac) {\n await sharedConstructsGenerator(\n tree,\n {\n iac,\n },\n DEPENDENCIES,\n );\n\n await addWebsiteInfra(tree, {\n iac,\n websiteProjectName: fullyQualifiedName,\n scopeAlias,\n websiteContentPath: joinPathFragments('dist', websiteContentPath),\n websiteNameKebabCase,\n websiteNameClassName,\n });\n }\n\n const projectConfig = readProjectConfiguration(tree, fullyQualifiedName);\n const libraryRoot = projectConfig.root;\n const sharedShadcnStylesImport = relative(\n joinPathFragments(libraryRoot, 'src'),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n 'src',\n 'styles',\n 'globals.css',\n ),\n )\n .split(sep)\n .join('/');\n const sharedShadcnTsconfigRef = relative(\n joinPathFragments(tree.root, websiteContentPath),\n joinPathFragments(\n tree.root,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n 'tsconfig.json',\n ),\n )\n .split(sep)\n .join('/');\n const templateOptions = {\n ...schema,\n fullyQualifiedName,\n pkgMgrCmd: getPackageManagerDisplayCommands().exec,\n tailwind,\n tanstackRouter,\n scopeAlias,\n sharedShadcnStylesImport,\n };\n tree.delete(joinPathFragments(libraryRoot, 'src', 'app'));\n const appCommonTemplatePath = joinPathFragments(\n import.meta.dirname,\n './files/app/common',\n );\n const appTemplatePath = joinPathFragments(\n import.meta.dirname,\n `./files/app/${ux.toLowerCase()}`,\n );\n\n generateFiles(\n tree, // the virtual file system\n appCommonTemplatePath, // path to the file templates\n libraryRoot, // destination path of the files\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree, // the virtual file system\n appTemplatePath, // path to the file templates\n libraryRoot, // destination path of the files\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n if (tanstackRouter) {\n const routerCommonTemplatePath = joinPathFragments(\n import.meta.dirname,\n './files/tanstack-router/common',\n );\n const routerTemplatePath = joinPathFragments(\n import.meta.dirname,\n `./files/tanstack-router/${ux.toLowerCase()}`,\n );\n\n generateFiles(\n tree,\n routerCommonTemplatePath,\n libraryRoot,\n templateOptions,\n {\n // User-editable source (and the TanStack-managed route tree) - preserve on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree,\n routerTemplatePath,\n libraryRoot,\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n tree.delete(joinPathFragments(websiteContentPath, 'src', 'app.tsx'));\n }\n\n if (e2eTestRunner !== 'none') {\n const e2eFullyQualifiedName = `${fullyQualifiedName}-e2e`;\n const e2eRoot = readProjectConfiguration(tree, e2eFullyQualifiedName).root;\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, `./files/e2e/${e2eTestRunner}`), // path to the file templates\n e2eRoot, // destination path of the files\n { ...schema, ...names(fullyQualifiedName) },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n await configureTsProject(\n tree,\n {\n fullyQualifiedName: e2eFullyQualifiedName,\n dir: e2eRoot,\n },\n DEPENDENCIES,\n );\n }\n const viteConfigPath = joinPathFragments(libraryRoot, 'vite.config.mts');\n\n if (tree.exists(viteConfigPath)) {\n // Add Tanstack Router import if enabled\n if (tanstackRouter) {\n await addDestructuredImport(\n tree,\n viteConfigPath,\n ['tanstackRouter'],\n '@tanstack/router-plugin/vite',\n );\n\n await addDestructuredImport(tree, viteConfigPath, ['resolve'], 'path');\n }\n\n // Add TailwindCSS import if enabled\n if (tailwind) {\n await addSingleImport(\n tree,\n viteConfigPath,\n 'tailwindcss',\n '@tailwindcss/vite',\n );\n }\n\n // Update build.outDir. The inferred `vite build` target writes here, so\n // point it at the bundle dir the website infrastructure consumes.\n const outDir = joinPathFragments(\n getRelativePathToRoot(tree, fullyQualifiedName),\n 'dist',\n websiteContentPath,\n 'bundle',\n );\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`build: { $bprops }\\` where { $bprops <: contains \\`outDir: $_\\` => \\`outDir: '${outDir}'\\` }`,\n );\n\n // Replace @nx/react's default dev-server port (4200) with the one assigned above.\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`server: { $sprops }\\` where { $sprops <: contains \\`port: $_\\` => \\`port: ${port}\\` }`,\n );\n\n // Likewise for the preview port (@nx/react's default is 4300), so `vite preview`\n // doesn't collide across websites either.\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`preview: { $pprops }\\` where { $pprops <: contains \\`port: $_\\` => \\`port: ${previewPort}\\` }`,\n );\n\n // Add plugins to the plugins array\n if (tanstackRouter) {\n // Prepend tanstackRouter (must be first plugin) — rewrite works for both single/multi-element\n await applyGritQL(\n tree,\n viteConfigPath,\n \"`plugins: [$items]` => `plugins: [tanstackRouter({ routesDirectory: resolve(import.meta.dirname, 'src/routes'), generatedRouteTree: resolve(import.meta.dirname, 'src/routeTree.gen.ts') }), $items]` where { $items <: within `defineConfig($_)`, $items <: not contains `tanstackRouter` }\",\n );\n }\n\n if (tailwind) {\n await appendToArrayViaGritQL(\n tree,\n viteConfigPath,\n 'plugins:',\n 'tailwindcss()',\n { scope: 'defineConfig($_)' },\n );\n }\n\n // Use Vite's native tsconfig paths resolution (replaces vite-tsconfig-paths).\n // `dedupe` forces a single copy of react/react-dom into the bundle: each\n // project declares its own react dependency, so without this a workspace\n // library's hoisted copy can produce a second React instance and the\n // \"Invalid hook call\" runtime crash.\n await applyGritQL(\n tree,\n viteConfigPath,\n \"or { `defineConfig(() => ({ $props }))` where { $props <: not some `resolve: $_`, $props += `resolve: { tsconfigPaths: true, dedupe: ['react', 'react-dom'] }` }, `defineConfig({ $props })` where { $props <: not some `resolve: $_`, $props += `resolve: { tsconfigPaths: true, dedupe: ['react', 'react-dom'] }` } }\",\n );\n\n // Add define: { global: {} } to the config (handles both callback and direct forms)\n await applyGritQL(\n tree,\n viteConfigPath,\n 'or { `defineConfig(() => ({ $props }))` where { $props <: not contains `define`, $props += `define: { global: {} }` }, `defineConfig({ $props })` where { $props <: not contains `define`, $props += `define: { global: {} }` } }',\n );\n }\n\n updateJson(\n tree,\n joinPathFragments(websiteContentPath, 'tsconfig.json'),\n (tsconfig) => ({\n ...tsconfig,\n compilerOptions: {\n ...tsconfig.compilerOptions,\n moduleResolution: 'Bundler',\n module: 'Preserve',\n },\n }),\n );\n const outDirToRootRelativePath = relative(\n joinPathFragments(tree.root, websiteContentPath),\n tree.root,\n );\n const distDir = joinPathFragments(\n outDirToRootRelativePath,\n 'dist',\n websiteContentPath,\n 'tsc',\n );\n updateJson(\n tree,\n joinPathFragments(websiteContentPath, 'tsconfig.app.json'),\n (tsconfig) => ({\n ...tsconfig,\n compilerOptions: {\n ...tsconfig.compilerOptions,\n outDir: distDir,\n tsBuildInfoFile: joinPathFragments(distDir, 'tsconfig.lib.tsbuildinfo'),\n lib: ['DOM'],\n },\n references:\n ux === 'shadcn'\n ? [\n ...(tsconfig.references ?? []).filter(\n (ref) => ref.path !== sharedShadcnTsconfigRef,\n ),\n {\n path: sharedShadcnTsconfigRef,\n },\n ]\n : tsconfig.references,\n }),\n );\n\n addTsDependencies(tree, DEPENDENCIES, { metadata, projectRoot: libraryRoot });\n\n // @nx/react declares an optional `express` peer on the major behind the one\n // vended here, for a module-federation dev-server this never runs. npm alone\n // fails the whole install on an optional peer it cannot satisfy, so it gets a\n // scoped override; the other package managers only warn.\n if (detectPackageManager() === 'npm') {\n updateJson(tree, 'package.json', (packageJson) => {\n packageJson.overrides = {\n ...packageJson.overrides,\n '@nx/react': {\n ...packageJson.overrides?.['@nx/react'],\n ...withVersions(DEPENDENCIES, ['express']),\n },\n };\n return packageJson;\n });\n }\n\n // @nx/react's applicationGenerator seeds react/react-dom into the root\n // manifest. The website now declares its own pinned versions, so drop the\n // root copies: without catalogs (npm) the root's floating range resolves to\n // a different version than the website's pin, installing a second React and\n // producing the \"Invalid hook call\" runtime crash.\n removeDependenciesFromPackageJson(tree, ['react', 'react-dom'], []);\n\n await addGeneratorMetricsIfApplicable(tree, [\n REACT_WEBSITE_APP_GENERATOR_INFO,\n ]);\n\n // TanStack Router's vite plugin owns this website's route tree and rewrites it\n // in its own (unformatted) shape whenever the config is loaded — including when\n // Nx computes the project graph — so formatting it here would only make\n // generation non-idempotent. The vended biome config excludes `**/*.gen.*`, so\n // the workspace's own `format` target leaves it alone too.\n await formatFilesInSubtree(tree, undefined, {\n ignore: tanstackRouter\n ? [joinPathFragments(libraryRoot, 'src', 'routeTree.gen.ts')]\n : [],\n });\n // The generated vite.config.mts imports these, and Nx's inferred `@nx/vite`\n // plugin loads that config when computing the project graph — so they must be\n // installed even if the caller would otherwise prefer to defer.\n return () =>\n installDependencies(tree, schema.preferInstallDependencies, {\n languages: ['typescript'],\n ensureResolvable: [\n ...(tailwind ? (['@tailwindcss/vite'] as const) : []),\n ...(tanstackRouter ? (['@tanstack/router-plugin'] as const) : []),\n ],\n });\n}\nexport default tsReactWebsiteGenerator;\n"],"names":["detectPackageManager","generateFiles","joinPathFragments","names","OverwriteStrategy","readProjectConfiguration","removeDependenciesFromPackageJson","updateJson","updateProjectConfiguration","applicationGenerator","relative","sep","addTsDependencies","addDestructuredImport","addSingleImport","appendToArrayViaGritQL","applyGritQL","declareDependencies","ownedElsewhere","formatFilesInSubtree","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","kebabCase","toClassName","toKebabCase","getNpmScopePrefix","addGeneratorMetadata","getGeneratorInfo","sortObjectKeys","getRelativePathToRoot","getPackageManagerDisplayCommands","assignPort","SHARED_CONSTRUCTS_DEPENDENCIES","sharedConstructsGenerator","PACKAGES_DIR","SHARED_SHADCN_DIR","TERRAFORM_WEBSITE_RUNTIME_CONFIG_FILE","addSharedShadcnDependency","SHADCN_DEPENDENCIES","sharedShadcnGenerator","withVersions","addWebsiteInfra","WEBSITE_CONSTRUCTS_PY_DEPENDENCIES","configureTsProject","VITEST_DEPENDENCIES","DEPENDENCIES","ts","name","dev","root","when","m","ux","tanstackRouter","tailwind","versionOnly","py","SUPPORTED_UX_PROVIDERS","REACT_WEBSITE_APP_GENERATOR_INFO","filename","tsReactWebsiteGenerator","tree","schema","Error","npmScopePrefix","scopeAlias","websiteNameClassName","websiteNameKebabCase","fullyQualifiedName","websiteContentPath","directory","subDirectory","projectAlreadyExists","exists","e2eTestRunner","routing","linter","bundler","unitTestRunner","useProjectJson","style","addPlugin","nxJson","plugin","plugins","options","buildTargetName","serveTargetName","devTargetName","previewTargetName","serveStaticTargetName","typecheckTargetName","testTargetName","delete","projectConfiguration","targets","port","previewPort","infra","iac","undefined","executor","metadata","description","exec","command","env","SRC_FILE","DEST_DIR","DEST_FILE","dependsOn","outputs","cwd","continuous","framework","dir","websiteProjectName","projectConfig","libraryRoot","sharedShadcnStylesImport","split","join","sharedShadcnTsconfigRef","templateOptions","pkgMgrCmd","appCommonTemplatePath","dirname","appTemplatePath","toLowerCase","overwriteStrategy","KeepExisting","routerCommonTemplatePath","routerTemplatePath","e2eFullyQualifiedName","e2eRoot","viteConfigPath","outDir","scope","tsconfig","compilerOptions","moduleResolution","module","outDirToRootRelativePath","distDir","tsBuildInfoFile","lib","references","filter","ref","path","projectRoot","packageJson","overrides","ignore","preferInstallDependencies","languages","ensureResolvable"],"mappings":"AAAA;;;CAGC,GACD,SACEA,oBAAoB,EACpBC,aAAa,EACbC,iBAAiB,EACjBC,KAAK,EACLC,iBAAiB,EACjBC,wBAAwB,EACxBC,iCAAiC,EAEjCC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAASC,oBAAoB,QAAQ,YAAY;AACjD,SAASC,QAAQ,EAAEC,GAAG,QAAQ,OAAO;AACrC,SAASC,iBAAiB,QAAQ,qCAAqC;AACvE,SACEC,qBAAqB,EACrBC,eAAe,EACfC,sBAAsB,EACtBC,WAAW,QACN,wBAAwB;AAC/B,SACEC,mBAAmB,EACnBC,cAAc,QACT,0CAA0C;AACjD,SAASC,oBAAoB,QAAQ,2BAA2B;AAChE,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SAASC,mBAAmB,QAAQ,4BAA4B;AAChE,SAASC,+BAA+B,QAAQ,4BAA4B;AAC5E,SAASC,SAAS,EAAEC,WAAW,EAAEC,WAAW,QAAQ,0BAA0B;AAC9E,SAASC,iBAAiB,QAAQ,8BAA8B;AAChE,SACEC,oBAAoB,EACpBC,gBAAgB,QAEX,uBAAuB;AAC9B,SAASC,cAAc,QAAQ,2BAA2B;AAC1D,SAASC,qBAAqB,QAAQ,0BAA0B;AAChE,SAASC,gCAAgC,QAAQ,gCAAgC;AACjF,SAASC,UAAU,QAAQ,yBAAyB;AACpD,SACEC,8BAA8B,EAC9BC,yBAAyB,QACpB,sCAAsC;AAC7C,SAEEC,YAAY,EACZC,iBAAiB,EACjBC,qCAAqC,QAChC,gDAAgD;AACvD,SACEC,yBAAyB,EACzBC,mBAAmB,EACnBC,qBAAqB,QAChB,kCAAkC;AACzC,SAASC,YAAY,QAAQ,6BAA6B;AAC1D,SACEC,eAAe,EACfC,kC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ourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n detectPackageManager,\n generateFiles,\n joinPathFragments,\n names,\n OverwriteStrategy,\n readProjectConfiguration,\n removeDependenciesFromPackageJson,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { applicationGenerator } from '@nx/react';\nimport { relative, sep } from 'path';\nimport { addTsDependencies } from '../../../utils/add-dependencies.js';\nimport {\n addDestructuredImport,\n addSingleImport,\n appendToArrayViaGritQL,\n applyGritQL,\n} from '../../../utils/ast.js';\nimport {\n declareDependencies,\n ownedElsewhere,\n} from '../../../utils/declared-dependencies.js';\nimport { formatFilesInSubtree } from '../../../utils/format.js';\nimport { resolveIac } from '../../../utils/iac.js';\nimport { installDependencies } from '../../../utils/install.js';\nimport { addGeneratorMetricsIfApplicable } from '../../../utils/metrics.js';\nimport { kebabCase, toClassName, toKebabCase } from '../../../utils/names.js';\nimport { getNpmScopePrefix } from '../../../utils/npm-scope.js';\nimport {\n addGeneratorMetadata,\n getGeneratorInfo,\n type NxGeneratorInfo,\n} from '../../../utils/nx.js';\nimport { sortObjectKeys } from '../../../utils/object.js';\nimport { getRelativePathToRoot } from '../../../utils/paths.js';\nimport { getPackageManagerDisplayCommands } from '../../../utils/pkg-manager.js';\nimport { assignPort } from '../../../utils/port.js';\nimport {\n SHARED_CONSTRUCTS_DEPENDENCIES,\n sharedConstructsGenerator,\n} from '../../../utils/shared-constructs.js';\nimport {\n type IacMetadata,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n TERRAFORM_WEBSITE_RUNTIME_CONFIG_FILE,\n} from '../../../utils/shared-constructs-constants.js';\nimport {\n addSharedShadcnDependency,\n SHADCN_DEPENDENCIES,\n sharedShadcnGenerator,\n} from '../../../utils/shared-shadcn.js';\nimport { withVersions } from '../../../utils/versions.js';\nimport {\n addWebsiteInfra,\n WEBSITE_CONSTRUCTS_PY_DEPENDENCIES,\n} from '../../../utils/website-constructs/website-constructs.js';\nimport {\n configureTsProject,\n TS_PROJECT_DEPENDENCIES,\n} from '../../lib/ts-project-utils.js';\nimport { VITEST_DEPENDENCIES } from '../../lib/vitest.js';\n// typescript factory imports removed — now using GritQL for vite config transforms\nimport type {\n TsReactWebsiteGeneratorSchema,\n WebsiteInfraOption,\n} from './schema';\n\n/** The metadata this generator records, which its predicates read. */\nexport interface TsReactWebsiteMetadata extends IacMetadata {\n readonly ux: UxOption;\n readonly framework: string;\n readonly infra: WebsiteInfraOption;\n readonly tailwind: boolean;\n readonly tanstackRouter: boolean;\n}\n\n// Each entry names the branch it belongs to, so the same declaration drives both\n// adding and the version sync.\nexport const DEPENDENCIES = declareDependencies<TsReactWebsiteMetadata>()({\n ts: [\n { name: 'react' },\n { name: 'react-dom' },\n // Build/test tooling imported only from vite.config.mts stays at the root.\n { name: '@nx/react', dev: true, root: true },\n { name: '@vitest/ui', dev: true, root: true },\n {\n name: '@cloudscape-design/components',\n when: (m) => m.ux === 'cloudscape',\n },\n {\n name: '@cloudscape-design/board-components',\n when: (m) => m.ux === 'cloudscape',\n },\n {\n name: '@cloudscape-design/global-styles',\n when: (m) => m.ux === 'cloudscape',\n },\n // Shared shadcn components live in the common/shadcn package, but the\n // website's own generated components (e.g. the tanstack-router sidebar)\n // import lucide-react directly, so the website must declare it.\n {\n name: 'lucide-react',\n when: (m) => m.ux === 'shadcn' && m.tanstackRouter,\n },\n { name: 'tailwindcss', when: (m) => m.tailwind },\n {\n name: '@tailwindcss/vite',\n when: (m) => m.tailwind,\n dev: true,\n root: true,\n },\n { name: '@tanstack/react-router', when: (m) => m.tanstackRouter },\n {\n name: '@tanstack/router-plugin',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/router-generator',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/virtual-file-routes',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n {\n name: '@tanstack/router-utils',\n when: (m) => m.tanstackRouter,\n dev: true,\n root: true,\n },\n // Declared for its pinned version, which goes into npm's `overrides` below.\n { name: 'express', versionOnly: true },\n ...ownedElsewhere(TS_PROJECT_DEPENDENCIES),\n ...ownedElsewhere(SHADCN_DEPENDENCIES),\n ...ownedElsewhere(VITEST_DEPENDENCIES),\n ...ownedElsewhere(SHARED_CONSTRUCTS_DEPENDENCIES),\n ],\n py: ownedElsewhere(WEBSITE_CONSTRUCTS_PY_DEPENDENCIES),\n});\n\nexport const SUPPORTED_UX_PROVIDERS = ['none', 'cloudscape', 'shadcn'] as const;\n\nexport type UxOption = (typeof SUPPORTED_UX_PROVIDERS)[number];\n\nexport type Ux = UxOption;\n\nexport const REACT_WEBSITE_APP_GENERATOR_INFO: NxGeneratorInfo =\n getGeneratorInfo(import.meta.filename);\n\nexport async function tsReactWebsiteGenerator(\n tree: Tree,\n schema: TsReactWebsiteGeneratorSchema,\n) {\n const tailwind = schema.tailwind ?? true;\n const tanstackRouter = schema.tanstackRouter ?? true;\n const ux: Ux = schema.ux ?? 'shadcn';\n if (ux === 'shadcn' && !tailwind) {\n throw new Error('Shadcn requires TailwindCSS to be enabled.');\n }\n const npmScopePrefix = getNpmScopePrefix(tree);\n const scopeAlias = npmScopePrefix;\n const websiteNameClassName = toClassName(schema.name);\n const websiteNameKebabCase = toKebabCase(schema.name);\n const fullyQualifiedName = `${npmScopePrefix}${websiteNameKebabCase}`;\n // NB: interactive nx generator cli can pass empty string\n const websiteContentPath = joinPathFragments(\n schema.directory || '.',\n schema.subDirectory || websiteNameKebabCase,\n );\n\n const projectAlreadyExists = tree.exists(\n joinPathFragments(websiteContentPath, 'project.json'),\n );\n\n // TODO: consider exposing and supporting e2e tests\n const e2eTestRunner = 'none';\n\n if (!projectAlreadyExists) {\n await applicationGenerator(tree, {\n ...schema,\n name: fullyQualifiedName,\n directory: websiteContentPath,\n routing: false,\n e2eTestRunner,\n linter: 'none',\n bundler: 'vite',\n unitTestRunner: 'vitest',\n useProjectJson: true,\n style: 'css',\n // Register the @nx/vite and @nx/vitest plugins so build/serve/test\n // targets are inferred rather than emitting deprecated executor targets.\n addPlugin: true,\n });\n\n // Pin the inferred target names. The vite production build is exposed as\n // `bundle` (which produces the deployable artifact), leaving `build` as an\n // aggregator over lint/compile/test/bundle. vite's own typecheck is dropped\n // in favour of the tsc `compile`.\n updateJson(tree, 'nx.json', (nxJson) => {\n for (const plugin of nxJson.plugins ?? []) {\n if (typeof plugin === 'string') continue;\n if (plugin.plugin === '@nx/vite/plugin') {\n plugin.options = {\n ...plugin.options,\n buildTargetName: 'bundle',\n // Map both of vite's inferred dev-server targets onto `serve` so the\n // plugin doesn't emit a separate `dev`; we author our own `dev`\n // below running the local-dev vite mode.\n serveTargetName: 'serve',\n devTargetName: 'serve',\n previewTargetName: 'preview',\n serveStaticTargetName: 'serve-static',\n typecheckTargetName: 'vite:typecheck',\n };\n } else if (plugin.plugin === '@nx/vitest') {\n plugin.options = {\n ...plugin.options,\n testTargetName: 'test',\n };\n }\n }\n return nxJson;\n });\n\n // Replace with simpler sample source code\n tree.delete(joinPathFragments(websiteContentPath, 'src'));\n }\n\n const projectConfiguration = readProjectConfiguration(\n tree,\n fullyQualifiedName,\n );\n\n const targets = projectConfiguration.targets;\n\n // Each website gets its own explicit dev-server port. Vite itself already\n // auto-increments past a port already in use, so two websites don't actually\n // collide — but which port each one lands on then depends on start order and\n // can't be known ahead of time. An explicit, per-project port is what lets\n // the Cognito callback URL allow-list (added when auth is configured) be\n // computed deterministically instead.\n const port = assignPort(tree, projectConfiguration, 4200);\n // @nx/react's vite config defaults to 4200 for the dev server and 4300 for\n // preview; keep that +100 relationship so the pair stays predictable.\n const previewPort = port + 100;\n\n const infra = schema.infra ?? 'cloudfront-s3';\n\n // Configure load-runtime-config target based on IaC provider (only when infra is not none)\n const iac = infra !== 'none' ? await resolveIac(tree, schema.iac) : undefined;\n\n if (iac === 'cdk') {\n targets['load-runtime-config'] = {\n executor: 'nx:run-commands',\n metadata: {\n description: `Load runtime config from your deployed stack for dev purposes. You must set your AWS CLI credentials whilst calling '${getPackageManagerDisplayCommands().exec} nx load-runtime-config ${fullyQualifiedName}'`,\n },\n options: {\n command: `aws s3 cp s3://\\`aws cloudformation describe-stacks --query \"Stacks[?starts_with(StackName, '${kebabCase(npmScopePrefix)}-')][].Outputs[] | [?contains(OutputKey, '${websiteNameClassName}WebsiteBucketName')].OutputValue\" --output text\\`/runtime-config.json \"{projectRoot}/public/runtime-config.json\"`,\n },\n };\n } else if (iac === 'terraform') {\n targets['load-runtime-config'] = {\n executor: 'nx:run-commands',\n metadata: {\n description:\n \"Load runtime config from most recently applied terraform env for dev purposes. Copies the runtime config from the Terraform dist directory to the website's public directory.\",\n },\n options: {\n command:\n 'node -e \"const fs=require(\\'fs\\');fs.mkdirSync(process.env.DEST_DIR,{recursive:true});fs.copyFileSync(process.env.SRC_FILE,process.env.DEST_FILE);\"',\n env: {\n SRC_FILE: TERRAFORM_WEBSITE_RUNTIME_CONFIG_FILE,\n DEST_DIR: `{projectRoot}/public`,\n DEST_FILE: `{projectRoot}/public/runtime-config.json`,\n },\n },\n };\n }\n\n if (!projectAlreadyExists) {\n targets['compile'] = {\n // `tsc` needs its dependencies' declarations, which `compile` emits — not\n // their lint or test results.\n dependsOn: ['^compile'],\n executor: 'nx:run-commands',\n outputs: ['{workspaceRoot}/dist/{projectRoot}/tsc'],\n options: {\n command: 'tsc --build tsconfig.app.json',\n cwd: '{projectRoot}',\n },\n };\n // bundle is the @nx/vite/plugin inferred `vite build` (writing to the\n // bundle dir configured in vite.config) — it produces the deployable\n // artifact. build aggregates lint/compile/test/bundle.\n targets['build'] = {\n dependsOn: ['lint', 'compile', 'test', 'bundle'],\n };\n targets['assemble'] = {\n dependsOn: ['compile', 'bundle'],\n };\n\n // Run the website and its connected dependencies locally. Mirrors the\n // inferred `serve` target but with the local-dev vite mode.\n targets['dev'] = {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n command: 'vite --mode local-dev',\n cwd: '{projectRoot}',\n },\n };\n }\n\n projectConfiguration.targets = sortObjectKeys(targets);\n\n updateProjectConfiguration(tree, fullyQualifiedName, projectConfiguration);\n\n // Recorded here and read by the declaration's predicates, so the packages\n // added below are exactly the ones the version sync will own.\n const metadata: TsReactWebsiteMetadata = {\n ux,\n framework: 'react',\n infra,\n tailwind,\n tanstackRouter,\n // Undefined when no infrastructure was generated, so neither provider's\n // packages were added.\n ...(iac ? { iac } : {}),\n };\n addGeneratorMetadata(\n tree,\n projectConfiguration.name,\n REACT_WEBSITE_APP_GENERATOR_INFO,\n metadata,\n );\n\n await configureTsProject(\n tree,\n {\n dir: websiteContentPath,\n fullyQualifiedName,\n },\n DEPENDENCIES,\n );\n\n if (ux === 'shadcn') {\n await sharedShadcnGenerator(tree, DEPENDENCIES);\n addSharedShadcnDependency(tree, websiteContentPath);\n }\n\n if (iac) {\n await sharedConstructsGenerator(\n tree,\n {\n iac,\n },\n DEPENDENCIES,\n );\n\n await addWebsiteInfra(tree, {\n iac,\n websiteProjectName: fullyQualifiedName,\n scopeAlias,\n websiteContentPath: joinPathFragments('dist', websiteContentPath),\n websiteNameKebabCase,\n websiteNameClassName,\n });\n }\n\n const projectConfig = readProjectConfiguration(tree, fullyQualifiedName);\n const libraryRoot = projectConfig.root;\n const sharedShadcnStylesImport = relative(\n joinPathFragments(libraryRoot, 'src'),\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n 'src',\n 'styles',\n 'globals.css',\n ),\n )\n .split(sep)\n .join('/');\n const sharedShadcnTsconfigRef = relative(\n joinPathFragments(tree.root, websiteContentPath),\n joinPathFragments(\n tree.root,\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n 'tsconfig.json',\n ),\n )\n .split(sep)\n .join('/');\n const templateOptions = {\n ...schema,\n fullyQualifiedName,\n pkgMgrCmd: getPackageManagerDisplayCommands().exec,\n tailwind,\n tanstackRouter,\n scopeAlias,\n sharedShadcnStylesImport,\n };\n tree.delete(joinPathFragments(libraryRoot, 'src', 'app'));\n const appCommonTemplatePath = joinPathFragments(\n import.meta.dirname,\n './files/app/common',\n );\n const appTemplatePath = joinPathFragments(\n import.meta.dirname,\n `./files/app/${ux.toLowerCase()}`,\n );\n\n generateFiles(\n tree, // the virtual file system\n appCommonTemplatePath, // path to the file templates\n libraryRoot, // destination path of the files\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree, // the virtual file system\n appTemplatePath, // path to the file templates\n libraryRoot, // destination path of the files\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n if (tanstackRouter) {\n const routerCommonTemplatePath = joinPathFragments(\n import.meta.dirname,\n './files/tanstack-router/common',\n );\n const routerTemplatePath = joinPathFragments(\n import.meta.dirname,\n `./files/tanstack-router/${ux.toLowerCase()}`,\n );\n\n generateFiles(\n tree,\n routerCommonTemplatePath,\n libraryRoot,\n templateOptions,\n {\n // User-editable source (and the TanStack-managed route tree) - preserve on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree,\n routerTemplatePath,\n libraryRoot,\n templateOptions, // config object to replace variable in file templates\n {\n // User-editable source - preserve any edits on re-run\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n tree.delete(joinPathFragments(websiteContentPath, 'src', 'app.tsx'));\n }\n\n if (e2eTestRunner !== 'none') {\n const e2eFullyQualifiedName = `${fullyQualifiedName}-e2e`;\n const e2eRoot = readProjectConfiguration(tree, e2eFullyQualifiedName).root;\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, `./files/e2e/${e2eTestRunner}`), // path to the file templates\n e2eRoot, // destination path of the files\n { ...schema, ...names(fullyQualifiedName) },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n await configureTsProject(\n tree,\n {\n fullyQualifiedName: e2eFullyQualifiedName,\n dir: e2eRoot,\n },\n DEPENDENCIES,\n );\n }\n const viteConfigPath = joinPathFragments(libraryRoot, 'vite.config.mts');\n\n if (tree.exists(viteConfigPath)) {\n // Add Tanstack Router import if enabled\n if (tanstackRouter) {\n await addDestructuredImport(\n tree,\n viteConfigPath,\n ['tanstackRouter'],\n '@tanstack/router-plugin/vite',\n );\n\n await addDestructuredImport(tree, viteConfigPath, ['resolve'], 'path');\n }\n\n // Add TailwindCSS import if enabled\n if (tailwind) {\n await addSingleImport(\n tree,\n viteConfigPath,\n 'tailwindcss',\n '@tailwindcss/vite',\n );\n }\n\n // Update build.outDir. The inferred `vite build` target writes here, so\n // point it at the bundle dir the website infrastructure consumes.\n const outDir = joinPathFragments(\n getRelativePathToRoot(tree, fullyQualifiedName),\n 'dist',\n websiteContentPath,\n 'bundle',\n );\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`build: { $bprops }\\` where { $bprops <: contains \\`outDir: $_\\` => \\`outDir: '${outDir}'\\` }`,\n );\n\n // Replace @nx/react's default dev-server port (4200) with the one assigned above.\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`server: { $sprops }\\` where { $sprops <: contains \\`port: $_\\` => \\`port: ${port}\\` }`,\n );\n\n // Likewise for the preview port (@nx/react's default is 4300), so `vite preview`\n // doesn't collide across websites either.\n await applyGritQL(\n tree,\n viteConfigPath,\n `\\`preview: { $pprops }\\` where { $pprops <: contains \\`port: $_\\` => \\`port: ${previewPort}\\` }`,\n );\n\n // Add plugins to the plugins array\n if (tanstackRouter) {\n // Prepend tanstackRouter (must be first plugin) — rewrite works for both single/multi-element\n await applyGritQL(\n tree,\n viteConfigPath,\n \"`plugins: [$items]` => `plugins: [tanstackRouter({ routesDirectory: resolve(import.meta.dirname, 'src/routes'), generatedRouteTree: resolve(import.meta.dirname, 'src/routeTree.gen.ts') }), $items]` where { $items <: within `defineConfig($_)`, $items <: not contains `tanstackRouter` }\",\n );\n }\n\n if (tailwind) {\n await appendToArrayViaGritQL(\n tree,\n viteConfigPath,\n 'plugins:',\n 'tailwindcss()',\n { scope: 'defineConfig($_)' },\n );\n }\n\n // Use Vite's native tsconfig paths resolution (replaces vite-tsconfig-paths).\n // `dedupe` forces a single copy of react/react-dom into the bundle: each\n // project declares its own react dependency, so without this a workspace\n // library's hoisted copy can produce a second React instance and the\n // \"Invalid hook call\" runtime crash.\n await applyGritQL(\n tree,\n viteConfigPath,\n \"or { `defineConfig(() => ({ $props }))` where { $props <: not some `resolve: $_`, $props += `resolve: { tsconfigPaths: true, dedupe: ['react', 'react-dom'] }` }, `defineConfig({ $props })` where { $props <: not some `resolve: $_`, $props += `resolve: { tsconfigPaths: true, dedupe: ['react', 'react-dom'] }` } }\",\n );\n\n // Add define: { global: {} } to the config (handles both callback and direct forms)\n await applyGritQL(\n tree,\n viteConfigPath,\n 'or { `defineConfig(() => ({ $props }))` where { $props <: not contains `define`, $props += `define: { global: {} }` }, `defineConfig({ $props })` where { $props <: not contains `define`, $props += `define: { global: {} }` } }',\n );\n }\n\n updateJson(\n tree,\n joinPathFragments(websiteContentPath, 'tsconfig.json'),\n (tsconfig) => ({\n ...tsconfig,\n compilerOptions: {\n ...tsconfig.compilerOptions,\n moduleResolution: 'Bundler',\n module: 'Preserve',\n },\n }),\n );\n const outDirToRootRelativePath = relative(\n joinPathFragments(tree.root, websiteContentPath),\n tree.root,\n );\n const distDir = joinPathFragments(\n outDirToRootRelativePath,\n 'dist',\n websiteContentPath,\n 'tsc',\n );\n updateJson(\n tree,\n joinPathFragments(websiteContentPath, 'tsconfig.app.json'),\n (tsconfig) => ({\n ...tsconfig,\n compilerOptions: {\n ...tsconfig.compilerOptions,\n outDir: distDir,\n tsBuildInfoFile: joinPathFragments(distDir, 'tsconfig.lib.tsbuildinfo'),\n lib: ['DOM'],\n },\n references:\n ux === 'shadcn'\n ? [\n ...(tsconfig.references ?? []).filter(\n (ref) => ref.path !== sharedShadcnTsconfigRef,\n ),\n {\n path: sharedShadcnTsconfigRef,\n },\n ]\n : tsconfig.references,\n }),\n );\n\n addTsDependencies(tree, DEPENDENCIES, { metadata, projectRoot: libraryRoot });\n\n // @nx/react declares an optional `express` peer on the major behind the one\n // vended here, for a module-federation dev-server this never runs. npm alone\n // fails the whole install on an optional peer it cannot satisfy, so it gets a\n // scoped override; the other package managers only warn.\n if (detectPackageManager() === 'npm') {\n updateJson(tree, 'package.json', (packageJson) => {\n packageJson.overrides = {\n ...packageJson.overrides,\n '@nx/react': {\n ...packageJson.overrides?.['@nx/react'],\n ...withVersions(DEPENDENCIES, ['express']),\n },\n };\n return packageJson;\n });\n }\n\n // @nx/react's applicationGenerator seeds react/react-dom into the root\n // manifest. The website now declares its own pinned versions, so drop the\n // root copies: without catalogs (npm) the root's floating range resolves to\n // a different version than the website's pin, installing a second React and\n // producing the \"Invalid hook call\" runtime crash.\n removeDependenciesFromPackageJson(tree, ['react', 'react-dom'], []);\n\n await addGeneratorMetricsIfApplicable(tree, [\n REACT_WEBSITE_APP_GENERATOR_INFO,\n ]);\n\n // TanStack Router's vite plugin owns this website's route tree and rewrites it\n // in its own (unformatted) shape whenever the config is loaded — including when\n // Nx computes the project graph — so formatting it here would only make\n // generation non-idempotent. The vended biome config excludes `**/*.gen.*`, so\n // the workspace's own `format` target leaves it alone too.\n await formatFilesInSubtree(tree, undefined, {\n ignore: tanstackRouter\n ? [joinPathFragments(libraryRoot, 'src', 'routeTree.gen.ts')]\n : [],\n });\n // The generated vite.config.mts imports these, and Nx's inferred `@nx/vite`\n // plugin loads that config when computing the project graph — so they must be\n // installed even if the caller would otherwise prefer to defer.\n return () =>\n installDependencies(tree, schema.preferInstallDependencies, {\n languages: ['typescript'],\n ensureResolvable: [\n ...(tailwind ? (['@tailwindcss/vite'] as const) : []),\n ...(tanstackRouter ? (['@tanstack/router-plugin'] as const) : []),\n ],\n });\n}\nexport default tsReactWebsiteGenerator;\n"],"names":["detectPackageManager","generateFiles","joinPathFragments","names","OverwriteStrategy","readProjectConfiguration","removeDependenciesFromPackageJson","updateJson","updateProjectConfiguration","applicationGenerator","relative","sep","addTsDependencies","addDestructuredImport","addSingleImport","appendToArrayViaGritQL","applyGritQL","declareDependencies","ownedElsewhere","formatFilesInSubtree","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","kebabCase","toClassName","toKebabCase","getNpmScopePrefix","addGeneratorMetadata","getGeneratorInfo","sortObjectKeys","getRelativePathToRoot","getPackageManagerDisplayCommands","assignPort","SHARED_CONSTRUCTS_DEPENDENCIES","sharedConstructsGenerator","PACKAGES_DIR","SHARED_SHADCN_DIR","TERRAFORM_WEBSITE_RUNTIME_CONFIG_FILE","addSharedShadcnDependency","SHADCN_DEPENDENCIES","sharedShadcnGenerator","withVersions","addWebsiteInfra","WEBSITE_CONSTRUCTS_PY_DEPENDENCIES","configureTsProject","TS_PROJECT_DEPENDENCIES","VITEST_DEPENDENCIES","DEPENDENCIES","ts","name","dev","root","when","m","ux","tanstackRouter","tailwind","versionOnly","py","SUPPORTED_UX_PROVIDERS","REACT_WEBSITE_APP_GENERATOR_INFO","filename","tsReactWebsiteGenerator","tree","schema","Error","npmScopePrefix","scopeAlias","websiteNameClassName","websiteNameKebabCase","fullyQualifiedName","websiteContentPath","directory","subDirectory","projectAlreadyExists","exists","e2eTestRunner","routing","linter","bundler","unitTestRunner","useProjectJson","style","addPlugin","nxJson","plugin","plugins","options","buildTargetName","serveTargetName","devTargetName","previewTargetName","serveStaticTargetName","typecheckTargetName","testTargetName","delete","projectConfiguration","targets","port","previewPort","infra","iac","undefined","executor","metadata","description","exec","command","env","SRC_FILE","DEST_DIR","DEST_FILE","dependsOn","outputs","cwd","continuous","framework","dir","websiteProjectName","projectConfig","libraryRoot","sharedShadcnStylesImport","split","join","sharedShadcnTsconfigRef","templateOptions","pkgMgrCmd","appCommonTemplatePath","dirname","appTemplatePath","toLowerCase","overwriteStrategy","KeepExisting","routerCommonTemplatePath","routerTemplatePath","e2eFullyQualifiedName","e2eRoot","viteConfigPath","outDir","scope","tsconfig","compilerOptions","moduleResolution","module","outDirToRootRelativePath","distDir","tsBuildInfoFile","lib","references","filter","ref","path","projectRoot","packageJson","overrides","ignore","preferInstallDependencies","languages","ensureResolvable"],"mappings":"AAAA;;;CAGC,GACD,SACEA,oBAAoB,EACpBC,aAAa,EACbC,iBAAiB,EACjBC,KAAK,EACLC,iBAAiB,EACjBC,wBAAwB,EACxBC,iCAAiC,EAEjCC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAASC,oBAAoB,QAAQ,YAAY;AACjD,SAASC,QAAQ,EAAEC,GAAG,QAAQ,OAAO;AACrC,SAASC,iBAAiB,QAAQ,qCAAqC;AACvE,SACEC,qBAAqB,EACrBC,eAAe,EACfC,sBAAsB,EACtBC,WAAW,QACN,wBAAwB;AAC/B,SACEC,mBAAmB,EACnBC,cAAc,QACT,0CAA0C;AACjD,SAASC,oBAAoB,QAAQ,2BAA2B;AAChE,SAASC,UAAU,QAAQ,wBAAwB;AACnD,SAASC,mBAAmB,QAAQ,4BAA4B;AAChE,SAASC,+BAA+B,QAAQ,4BAA4B;AAC5E,SAASC,SAAS,EAAEC,WAAW,EAAEC,WAAW,QAAQ,0BAA0B;AAC9E,SAASC,iBAAiB,QAAQ,8BAA8B;AAChE,SACEC,oBAAoB,EACpBC,gBAAgB,QAEX,uBAAuB;AAC9B,SAASC,cAAc,QAAQ,2BAA2B;AAC1D,SAASC,qBAAqB,QAAQ,0BAA0B;AAChE,SAASC,gCAAgC,QAAQ,gCAAgC;AACjF,SAASC,UAAU,QAAQ,yBAAyB;AACpD,SACEC,8BAA8B,EAC9BC,yBAAyB,QACpB,sCAAsC;AAC7C,SAEEC,YAAY,EACZC,iBAAiB,EACjBC,qCAAqC,QAChC,gDAAgD;AACvD,SACEC,yBAAyB,EACzBC,mBAAmB,EACnBC,qBAAqB,QAChB,kCAAkC;AACzC,SAASC,YAAY,QAAQ,6BAA6B;AAC1D,SACE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6 @@ export const catalogsEnabled = (tree)=>{
|
|
|
113
113
|
}
|
|
114
114
|
return callback;
|
|
115
115
|
};
|
|
116
|
-
// Nx generators read these versions from the root manifest and coerce without
|
|
117
|
-
// a null guard; Nx ships no bun catalog manager, so an unresolved `catalog:`
|
|
118
|
-
// crashes them. Keep direct ranges on bun (react-dom pinned with react).
|
|
119
|
-
const BUN_INTROSPECTED_PACKAGES = new Set([
|
|
120
|
-
'vite',
|
|
121
|
-
'react',
|
|
122
|
-
'react-dom'
|
|
123
|
-
]);
|
|
124
|
-
const isCatalogExcluded = (tree, packageName)=>detectWorkspacePackageManager(tree) === 'bun' && BUN_INTROSPECTED_PACKAGES.has(packageName);
|
|
125
116
|
// Convert direct version ranges to `catalog:` references in a single manifest
|
|
126
117
|
// and record the range in the workspace catalog. Protocol specifiers
|
|
127
118
|
// (catalog:/workspace:/...) are left alone.
|
|
@@ -134,7 +125,7 @@ const convertDependenciesToCatalog = (tree, packageJsonPath, packageNames)=>{
|
|
|
134
125
|
]){
|
|
135
126
|
for (const packageName of packageNames){
|
|
136
127
|
const version = json[field]?.[packageName];
|
|
137
|
-
if (version && !version.includes(':')
|
|
128
|
+
if (version && !version.includes(':')) {
|
|
138
129
|
catalogUpdates[packageName] = version;
|
|
139
130
|
json[field][packageName] = 'catalog:';
|
|
140
131
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/dependencies.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n detectPackageManager,\n addDependenciesToPackageJson as devkitAddDependenciesToPackageJson,\n type GeneratorCallback,\n getPackageManagerVersion,\n type PackageManager,\n readJson,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport yaml from 'js-yaml';\nimport { coerce, gt, gte } from 'semver';\nimport { readAwsNxPluginConfig } from './config/utils.js';\n\n// Minimum version that introduced catalog support per package manager (npm has none).\nconst CATALOG_SUPPORT: Partial<Record<PackageManager, string>> = {\n pnpm: '9.5.0',\n yarn: '4.10.0',\n bun: '1.2.14',\n};\n\n// Prefer tree markers over devkit's `detectPackageManager`, which reads the\n// real filesystem and is nondeterministic for virtual trees in tests.\nexport const detectWorkspacePackageManager = (tree: Tree): PackageManager =>\n tree.exists('pnpm-workspace.yaml') ? 'pnpm' : detectPackageManager(tree.root);\n\n// Coerce a single simple range to a version. Rejects compound ranges\n// (whitespace / `||`), which coerce would silently reduce, plus tags/protocols.\nconst parseSimpleRange = (version: string) => {\n const trimmed = version.trim();\n if (/\\s|\\|\\|/.test(trimmed)) {\n return undefined;\n }\n return coerce(trimmed, { includePrerelease: true }) ?? undefined;\n};\n\nconst versionAtLeast = (version: string, minimum: string): boolean =>\n gte(\n parseSimpleRange(version) ?? '0.0.0',\n parseSimpleRange(minimum) ?? '0.0.0',\n );\n\n// Only a strict upgrade replaces an existing catalog entry, so generating a\n// project never downgrades a version the user raised. Uncomparable entries\n// (tags, complex ranges) are kept.\nconst isVersionUpgrade = (incoming: string, existing: string): boolean => {\n const existingParsed = parseSimpleRange(existing);\n const incomingParsed = parseSimpleRange(incoming);\n if (!existingParsed || !incomingParsed) {\n return false;\n }\n return gt(incomingParsed, existingParsed);\n};\n\n// Keyed by root + package manager; detecting support shells out for a version.\nconst catalogSupportCache = new Map<string, boolean>();\n\n/** Clears the catalog support cache. Only needed by tests. */\nexport const resetCatalogSupportCache = (): void => {\n catalogSupportCache.clear();\n};\n\n// Local-project specifier: the `workspace:` protocol where supported (pnpm,\n// bun, yarn berry), `*` on npm and yarn classic which reject it.\nexport const getLocalDependencySpecifier = (tree: Tree): string => {\n const packageManager = detectWorkspacePackageManager(tree);\n if (packageManager === 'npm') {\n return '*';\n }\n if (packageManager === 'yarn') {\n let major = 2;\n try {\n major = Number.parseInt(\n getPackageManagerVersion('yarn', tree.root).split('.')[0],\n 10,\n );\n } catch {\n // Not installed (e.g. tests) — assume berry.\n }\n if (major < 2) {\n return '*';\n }\n }\n return 'workspace:*';\n};\n\nexport const supportsCatalogs = (tree: Tree): boolean => {\n const packageManager = detectWorkspacePackageManager(tree);\n const cacheKey = `${tree.root}|${packageManager}`;\n const cached = catalogSupportCache.get(cacheKey);\n if (cached !== undefined) {\n return cached;\n }\n const minimumVersion = CATALOG_SUPPORT[packageManager];\n let supported = false;\n if (minimumVersion) {\n try {\n supported = versionAtLeast(\n getPackageManagerVersion(packageManager, tree.root),\n minimumVersion,\n );\n } catch {\n // Not installed (e.g. tests) — assume a modern version.\n supported = true;\n }\n }\n catalogSupportCache.set(cacheKey, supported);\n return supported;\n};\n\n// True when the package manager supports catalogs and the workspace hasn't\n// opted out via `packageManager.catalogs: false` in aws-nx-plugin.config.mts.\nexport const catalogsEnabled = (tree: Tree): boolean => {\n if (!supportsCatalogs(tree)) {\n return false;\n }\n const config = readAwsNxPluginConfig(tree);\n return config?.packageManager?.catalogs !== false;\n};\n\n/**\n * Drop-in replacement for devkit's `addDependenciesToPackageJson` that records\n * versions in the package manager's catalog when enabled. Callers pass a\n * project manifest path for runtime deps (so `noUndeclaredDependencies` passes)\n * and the root for shared tooling.\n */\nexport const addDependenciesToPackageJson = (\n tree: Tree,\n dependencies: Record<string, string>,\n devDependencies: Record<string, string>,\n packageJsonPath = 'package.json',\n): GeneratorCallback => {\n const callback = devkitAddDependenciesToPackageJson(\n tree,\n dependencies,\n devDependencies,\n packageJsonPath,\n );\n\n if (catalogsEnabled(tree)) {\n const packageNames = [\n ...Object.keys(dependencies),\n ...Object.keys(devDependencies),\n ];\n convertDependenciesToCatalog(tree, packageJsonPath, packageNames);\n // Convert any matching root ranges Nx wrote behind our back (e.g.\n // `@types/node`, `react`) so they don't resolve to a second copy alongside\n // the catalog version. Skipped when the caller already targeted the root.\n if (packageJsonPath !== 'package.json') {\n convertDependenciesToCatalog(tree, 'package.json', packageNames);\n }\n }\n\n return callback;\n};\n\n// Nx generators read these versions from the root manifest and coerce without\n// a null guard; Nx ships no bun catalog manager, so an unresolved `catalog:`\n// crashes them. Keep direct ranges on bun (react-dom pinned with react).\nconst BUN_INTROSPECTED_PACKAGES = new Set<string>([\n 'vite',\n 'react',\n 'react-dom',\n]);\n\nconst isCatalogExcluded = (tree: Tree, packageName: string): boolean =>\n detectWorkspacePackageManager(tree) === 'bun' &&\n BUN_INTROSPECTED_PACKAGES.has(packageName);\n\n// Convert direct version ranges to `catalog:` references in a single manifest\n// and record the range in the workspace catalog. Protocol specifiers\n// (catalog:/workspace:/...) are left alone.\nconst convertDependenciesToCatalog = (\n tree: Tree,\n packageJsonPath: string,\n packageNames: string[],\n): void => {\n const catalogUpdates: Record<string, string> = {};\n\n updateJson(tree, packageJsonPath, (json) => {\n for (const field of ['dependencies', 'devDependencies'] as const) {\n for (const packageName of packageNames) {\n const version = json[field]?.[packageName];\n if (\n version &&\n !version.includes(':') &&\n !isCatalogExcluded(tree, packageName)\n ) {\n catalogUpdates[packageName] = version;\n json[field][packageName] = 'catalog:';\n }\n }\n }\n return json;\n });\n\n if (Object.keys(catalogUpdates).length > 0) {\n writeCatalogVersions(tree, catalogUpdates);\n }\n};\n\n// Record ranges in the default catalog, creating it if absent. Only strict\n// upgrades replace existing entries (see `isVersionUpgrade`).\nconst writeCatalogVersions = (\n tree: Tree,\n updates: Record<string, string>,\n): void => {\n const applyUpdates = (\n catalog: Record<string, string> | undefined,\n ): Record<string, string> | undefined => {\n const existing = catalog ?? {};\n const applicable = Object.fromEntries(\n Object.entries(updates).filter(\n ([name, version]) =>\n existing[name] === undefined ||\n isVersionUpgrade(version, existing[name]),\n ),\n );\n if (Object.keys(applicable).length === 0) {\n return undefined;\n }\n return { ...existing, ...applicable };\n };\n\n switch (detectWorkspacePackageManager(tree)) {\n case 'pnpm': {\n const workspaceYaml =\n (yaml.load(tree.read('pnpm-workspace.yaml', 'utf-8') ?? '') as Record<\n string,\n unknown\n >) ?? {};\n const catalog = applyUpdates(\n workspaceYaml.catalog as Record<string, string> | undefined,\n );\n if (catalog) {\n tree.write(\n 'pnpm-workspace.yaml',\n yaml.dump({ ...workspaceYaml, catalog }, { quotingType: \"'\" }),\n );\n }\n break;\n }\n case 'yarn': {\n const yarnRc =\n (yaml.load(tree.read('.yarnrc.yml', 'utf-8') ?? '') as Record<\n string,\n unknown\n >) ?? {};\n const catalog = applyUpdates(\n yarnRc.catalog as Record<string, string> | undefined,\n );\n if (catalog) {\n tree.write(\n '.yarnrc.yml',\n yaml.dump({ ...yarnRc, catalog }, { quotingType: \"'\" }),\n );\n }\n break;\n }\n case 'bun': {\n const catalog = applyUpdates(\n readJson<{ catalog?: Record<string, string> }>(tree, 'package.json')\n .catalog,\n );\n if (catalog) {\n updateJson(tree, 'package.json', (json) => ({ ...json, catalog }));\n }\n break;\n }\n }\n};\n"],"names":["detectPackageManager","addDependenciesToPackageJson","devkitAddDependenciesToPackageJson","getPackageManagerVersion","readJson","updateJson","yaml","coerce","gt","gte","readAwsNxPluginConfig","CATALOG_SUPPORT","pnpm","yarn","bun","detectWorkspacePackageManager","tree","exists","root","parseSimpleRange","version","trimmed","trim","test","undefined","includePrerelease","versionAtLeast","minimum","isVersionUpgrade","incoming","existing","existingParsed","incomingParsed","catalogSupportCache","Map","resetCatalogSupportCache","clear","getLocalDependencySpecifier","packageManager","major","Number","parseInt","split","supportsCatalogs","cacheKey","cached","get","minimumVersion","supported","set","catalogsEnabled","config","catalogs","dependencies","devDependencies","packageJsonPath","callback","packageNames","Object","keys","convertDependenciesToCatalog","BUN_INTROSPECTED_PACKAGES","Set","isCatalogExcluded","packageName","has","catalogUpdates","json","field","includes","length","writeCatalogVersions","updates","applyUpdates","catalog","applicable","fromEntries","entries","filter","name","workspaceYaml","load","read","write","dump","quotingType","yarnRc"],"mappings":"AAAA;;;CAGC,GACD,SACEA,oBAAoB,EACpBC,gCAAgCC,kCAAkC,EAElEC,wBAAwB,EAExBC,QAAQ,EAERC,UAAU,QACL,aAAa;AACpB,OAAOC,UAAU,UAAU;AAC3B,SAASC,MAAM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KAAK,GAAG;YACxC,OAAO9C;QACT;QACA,OAAO;YAAE,GAAGM,QAAQ;YAAE,GAAG6C,UAAU;QAAC;IACtC;IAEA,OAAQ5D,8BAA8BC;QACpC,KAAK;YAAQ;gBACX,MAAMgE,gBACJ,AAAC1E,KAAK2E,IAAI,CAACjE,KAAKkE,IAAI,CAAC,uBAAuB,YAAY,OAGlD,CAAC;gBACT,MAAMR,UAAUD,aACdO,cAAcN,OAAO;gBAEvB,IAAIA,SAAS;oBACX1D,KAAKmE,KAAK,CACR,uBACA7E,KAAK8E,IAAI,CAAC;wBAAE,GAAGJ,aAAa;wBAAEN;oBAAQ,GAAG;wBAAEW,aAAa;oBAAI;gBAEhE;gBACA;YACF;QACA,KAAK;YAAQ;gBACX,MAAMC,SACJ,AAAChF,KAAK2E,IAAI,CAACjE,KAAKkE,IAAI,CAAC,eAAe,YAAY,OAG1C,CAAC;gBACT,MAAMR,UAAUD,aACda,OAAOZ,OAAO;gBAEhB,IAAIA,SAAS;oBACX1D,KAAKmE,KAAK,CACR,eACA7E,KAAK8E,IAAI,CAAC;wBAAE,GAAGE,MAAM;wBAAEZ;oBAAQ,GAAG;wBAAEW,aAAa;oBAAI;gBAEzD;gBACA;YACF;QACA,KAAK;YAAO;gBACV,MAAMX,UAAUD,aACdrE,SAA+CY,MAAM,gBAClD0D,OAAO;gBAEZ,IAAIA,SAAS;oBACXrE,WAAWW,MAAM,gBAAgB,CAACmD,OAAU,CAAA;4BAAE,GAAGA,IAAI;4BAAEO;wBAAQ,CAAA;gBACjE;gBACA;YACF;IACF;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/dependencies.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n detectPackageManager,\n addDependenciesToPackageJson as devkitAddDependenciesToPackageJson,\n type GeneratorCallback,\n getPackageManagerVersion,\n type PackageManager,\n readJson,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport yaml from 'js-yaml';\nimport { coerce, gt, gte } from 'semver';\nimport { readAwsNxPluginConfig } from './config/utils.js';\n\n// Minimum version that introduced catalog support per package manager (npm has none).\nconst CATALOG_SUPPORT: Partial<Record<PackageManager, string>> = {\n pnpm: '9.5.0',\n yarn: '4.10.0',\n bun: '1.2.14',\n};\n\n// Prefer tree markers over devkit's `detectPackageManager`, which reads the\n// real filesystem and is nondeterministic for virtual trees in tests.\nexport const detectWorkspacePackageManager = (tree: Tree): PackageManager =>\n tree.exists('pnpm-workspace.yaml') ? 'pnpm' : detectPackageManager(tree.root);\n\n// Coerce a single simple range to a version. Rejects compound ranges\n// (whitespace / `||`), which coerce would silently reduce, plus tags/protocols.\nconst parseSimpleRange = (version: string) => {\n const trimmed = version.trim();\n if (/\\s|\\|\\|/.test(trimmed)) {\n return undefined;\n }\n return coerce(trimmed, { includePrerelease: true }) ?? undefined;\n};\n\nconst versionAtLeast = (version: string, minimum: string): boolean =>\n gte(\n parseSimpleRange(version) ?? '0.0.0',\n parseSimpleRange(minimum) ?? '0.0.0',\n );\n\n// Only a strict upgrade replaces an existing catalog entry, so generating a\n// project never downgrades a version the user raised. Uncomparable entries\n// (tags, complex ranges) are kept.\nconst isVersionUpgrade = (incoming: string, existing: string): boolean => {\n const existingParsed = parseSimpleRange(existing);\n const incomingParsed = parseSimpleRange(incoming);\n if (!existingParsed || !incomingParsed) {\n return false;\n }\n return gt(incomingParsed, existingParsed);\n};\n\n// Keyed by root + package manager; detecting support shells out for a version.\nconst catalogSupportCache = new Map<string, boolean>();\n\n/** Clears the catalog support cache. Only needed by tests. */\nexport const resetCatalogSupportCache = (): void => {\n catalogSupportCache.clear();\n};\n\n// Local-project specifier: the `workspace:` protocol where supported (pnpm,\n// bun, yarn berry), `*` on npm and yarn classic which reject it.\nexport const getLocalDependencySpecifier = (tree: Tree): string => {\n const packageManager = detectWorkspacePackageManager(tree);\n if (packageManager === 'npm') {\n return '*';\n }\n if (packageManager === 'yarn') {\n let major = 2;\n try {\n major = Number.parseInt(\n getPackageManagerVersion('yarn', tree.root).split('.')[0],\n 10,\n );\n } catch {\n // Not installed (e.g. tests) — assume berry.\n }\n if (major < 2) {\n return '*';\n }\n }\n return 'workspace:*';\n};\n\nexport const supportsCatalogs = (tree: Tree): boolean => {\n const packageManager = detectWorkspacePackageManager(tree);\n const cacheKey = `${tree.root}|${packageManager}`;\n const cached = catalogSupportCache.get(cacheKey);\n if (cached !== undefined) {\n return cached;\n }\n const minimumVersion = CATALOG_SUPPORT[packageManager];\n let supported = false;\n if (minimumVersion) {\n try {\n supported = versionAtLeast(\n getPackageManagerVersion(packageManager, tree.root),\n minimumVersion,\n );\n } catch {\n // Not installed (e.g. tests) — assume a modern version.\n supported = true;\n }\n }\n catalogSupportCache.set(cacheKey, supported);\n return supported;\n};\n\n// True when the package manager supports catalogs and the workspace hasn't\n// opted out via `packageManager.catalogs: false` in aws-nx-plugin.config.mts.\nexport const catalogsEnabled = (tree: Tree): boolean => {\n if (!supportsCatalogs(tree)) {\n return false;\n }\n const config = readAwsNxPluginConfig(tree);\n return config?.packageManager?.catalogs !== false;\n};\n\n/**\n * Drop-in replacement for devkit's `addDependenciesToPackageJson` that records\n * versions in the package manager's catalog when enabled. Callers pass a\n * project manifest path for runtime deps (so `noUndeclaredDependencies` passes)\n * and the root for shared tooling.\n */\nexport const addDependenciesToPackageJson = (\n tree: Tree,\n dependencies: Record<string, string>,\n devDependencies: Record<string, string>,\n packageJsonPath = 'package.json',\n): GeneratorCallback => {\n const callback = devkitAddDependenciesToPackageJson(\n tree,\n dependencies,\n devDependencies,\n packageJsonPath,\n );\n\n if (catalogsEnabled(tree)) {\n const packageNames = [\n ...Object.keys(dependencies),\n ...Object.keys(devDependencies),\n ];\n convertDependenciesToCatalog(tree, packageJsonPath, packageNames);\n // Convert any matching root ranges Nx wrote behind our back (e.g.\n // `@types/node`, `react`) so they don't resolve to a second copy alongside\n // the catalog version. Skipped when the caller already targeted the root.\n if (packageJsonPath !== 'package.json') {\n convertDependenciesToCatalog(tree, 'package.json', packageNames);\n }\n }\n\n return callback;\n};\n\n// Convert direct version ranges to `catalog:` references in a single manifest\n// and record the range in the workspace catalog. Protocol specifiers\n// (catalog:/workspace:/...) are left alone.\nconst convertDependenciesToCatalog = (\n tree: Tree,\n packageJsonPath: string,\n packageNames: string[],\n): void => {\n const catalogUpdates: Record<string, string> = {};\n\n updateJson(tree, packageJsonPath, (json) => {\n for (const field of ['dependencies', 'devDependencies'] as const) {\n for (const packageName of packageNames) {\n const version = json[field]?.[packageName];\n if (version && !version.includes(':')) {\n catalogUpdates[packageName] = version;\n json[field][packageName] = 'catalog:';\n }\n }\n }\n return json;\n });\n\n if (Object.keys(catalogUpdates).length > 0) {\n writeCatalogVersions(tree, catalogUpdates);\n }\n};\n\n// Record ranges in the default catalog, creating it if absent. Only strict\n// upgrades replace existing entries (see `isVersionUpgrade`).\nconst writeCatalogVersions = (\n tree: Tree,\n updates: Record<string, string>,\n): void => {\n const applyUpdates = (\n catalog: Record<string, string> | undefined,\n ): Record<string, string> | undefined => {\n const existing = catalog ?? {};\n const applicable = Object.fromEntries(\n Object.entries(updates).filter(\n ([name, version]) =>\n existing[name] === undefined ||\n isVersionUpgrade(version, existing[name]),\n ),\n );\n if (Object.keys(applicable).length === 0) {\n return undefined;\n }\n return { ...existing, ...applicable };\n };\n\n switch (detectWorkspacePackageManager(tree)) {\n case 'pnpm': {\n const workspaceYaml =\n (yaml.load(tree.read('pnpm-workspace.yaml', 'utf-8') ?? '') as Record<\n string,\n unknown\n >) ?? {};\n const catalog = applyUpdates(\n workspaceYaml.catalog as Record<string, string> | undefined,\n );\n if (catalog) {\n tree.write(\n 'pnpm-workspace.yaml',\n yaml.dump({ ...workspaceYaml, catalog }, { quotingType: \"'\" }),\n );\n }\n break;\n }\n case 'yarn': {\n const yarnRc =\n (yaml.load(tree.read('.yarnrc.yml', 'utf-8') ?? '') as Record<\n string,\n unknown\n >) ?? {};\n const catalog = applyUpdates(\n yarnRc.catalog as Record<string, string> | undefined,\n );\n if (catalog) {\n tree.write(\n '.yarnrc.yml',\n yaml.dump({ ...yarnRc, catalog }, { quotingType: \"'\" }),\n );\n }\n break;\n }\n case 'bun': {\n const catalog = applyUpdates(\n readJson<{ catalog?: Record<string, string> }>(tree, 'package.json')\n .catalog,\n );\n if (catalog) {\n updateJson(tree, 'package.json', (json) => ({ ...json, catalog }));\n }\n break;\n }\n }\n};\n"],"names":["detectPackageManager","addDependenciesToPackageJson","devkitAddDependenciesToPackageJson","getPackageManagerVersion","readJson","updateJson","yaml","coerce","gt","gte","readAwsNxPluginConfig","CATALOG_SUPPORT","pnpm","yarn","bun","detectWorkspacePackageManager","tree","exists","root","parseSimpleRange","version","trimmed","trim","test","undefined","includePrerelease","versionAtLeast","minimum","isVersionUpgrade","incoming","existing","existingParsed","incomingParsed","catalogSupportCache","Map","resetCatalogSupportCache","clear","getLocalDependencySpecifier","packageManager","major","Number","parseInt","split","supportsCatalogs","cacheKey","cached","get","minimumVersion","supported","set","catalogsEnabled","config","catalogs","dependencies","devDependencies","packageJsonPath","callback","packageNames","Object","keys","convertDependenciesToCatalog","catalogUpdates","json","field","packageName","includes","length","writeCatalogVersions","updates","applyUpdates","catalog","applicable","fromEntries","entries","filter","name","workspaceYaml","load","read","write","dump","quotingType","yarnRc"],"mappings":"AAAA;;;CAGC,GACD,SACEA,oBAAoB,EACpBC,gCAAgCC,kCAAkC,EAElEC,wBAAwB,EAExBC,QAAQ,EAERC,UAAU,QACL,aAAa;AACpB,OAAOC,UAAU,UAAU;AAC3B,SAASC,MAAM,EAAEC,EAAE,EAAEC,GAAG,QAAQ,SAAS;AACzC,SAASC,qBAAqB,QAAQ,oBAAoB;AAE1D,sFAAsF;AACtF,MAAMC,kBAA2D;IAC/DC,MAAM;IACNC,MAAM;IACNC,KAAK;AACP;AAEA,4EAA4E;AAC5E,sEAAsE;AACtE,OAAO,MAAMC,gCAAgC,CAACC,OAC5CA,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AQ;gBACX,MAAMC,SACJ,AAAC5E,KAAKuE,IAAI,CAAC7D,KAAK8D,IAAI,CAAC,eAAe,YAAY,OAG1C,CAAC;gBACT,MAAMR,UAAUD,aACda,OAAOZ,OAAO;gBAEhB,IAAIA,SAAS;oBACXtD,KAAK+D,KAAK,CACR,eACAzE,KAAK0E,IAAI,CAAC;wBAAE,GAAGE,MAAM;wBAAEZ;oBAAQ,GAAG;wBAAEW,aAAa;oBAAI;gBAEzD;gBACA;YACF;QACA,KAAK;YAAO;gBACV,MAAMX,UAAUD,aACdjE,SAA+CY,MAAM,gBAClDsD,OAAO;gBAEZ,IAAIA,SAAS;oBACXjE,WAAWW,MAAM,gBAAgB,CAAC8C,OAAU,CAAA;4BAAE,GAAGA,IAAI;4BAAEQ;wBAAQ,CAAA;gBACjE;gBACA;YACF;IACF;AACF"}
|
|
@@ -27,6 +27,19 @@ export declare const SHADCN_DEPENDENCIES: readonly [{
|
|
|
27
27
|
readonly name: "vitest";
|
|
28
28
|
}, {
|
|
29
29
|
readonly name: "@vitest/coverage-v8";
|
|
30
|
+
}, {
|
|
31
|
+
readonly name: "jsdom";
|
|
32
|
+
}, {
|
|
33
|
+
readonly name: "@nx/vitest";
|
|
34
|
+
readonly dev: true;
|
|
35
|
+
readonly root: true;
|
|
36
|
+
}, {
|
|
37
|
+
readonly name: "@types/node";
|
|
38
|
+
readonly dev: true;
|
|
39
|
+
}, {
|
|
40
|
+
readonly name: "@types/node";
|
|
41
|
+
readonly dev: true;
|
|
42
|
+
readonly root: true;
|
|
30
43
|
}];
|
|
31
44
|
/** The shared shadcn package's fully-qualified npm name for this workspace. */
|
|
32
45
|
export declare const getSharedShadcnFullyQualifiedName: (tree: Tree) => string;
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* SPDX-License-Identifier: Apache-2.0
|
|
4
4
|
*/ import { generateFiles, joinPathFragments, OverwriteStrategy, updateJson } from "@nx/devkit";
|
|
5
5
|
import tsProjectGenerator from "../ts/lib/generator.js";
|
|
6
|
-
import { configureTsProject } from "../ts/lib/ts-project-utils.js";
|
|
6
|
+
import { configureTsProject, TS_PROJECT_DEPENDENCIES } from "../ts/lib/ts-project-utils.js";
|
|
7
7
|
import { VITEST_DEPENDENCIES } from "../ts/lib/vitest.js";
|
|
8
8
|
import { declaredNames, forDependencies } from "./declared-dependencies.js";
|
|
9
9
|
import { addDependenciesToPackageJson, getLocalDependencySpecifier } from "./dependencies.js";
|
|
@@ -37,7 +37,8 @@ import { withVersions } from "./versions.js";
|
|
|
37
37
|
{
|
|
38
38
|
name: 'radix-ui'
|
|
39
39
|
},
|
|
40
|
-
...VITEST_DEPENDENCIES
|
|
40
|
+
...VITEST_DEPENDENCIES,
|
|
41
|
+
...TS_PROJECT_DEPENDENCIES
|
|
41
42
|
];
|
|
42
43
|
/** The shared shadcn package's fully-qualified npm name for this workspace. */ export const getSharedShadcnFullyQualifiedName = (tree)=>`${getNpmScopePrefix(tree)}${SHARED_SHADCN_NAME}`;
|
|
43
44
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/shared-shadcn.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport tsProjectGenerator from '../ts/lib/generator.js';\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/shared-shadcn.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type Tree,\n updateJson,\n} from '@nx/devkit';\nimport tsProjectGenerator from '../ts/lib/generator.js';\nimport {\n configureTsProject,\n TS_PROJECT_DEPENDENCIES,\n} from '../ts/lib/ts-project-utils.js';\nimport { VITEST_DEPENDENCIES } from '../ts/lib/vitest.js';\nimport {\n type DependencyDeclaration,\n declaredNames,\n forDependencies,\n type MustDeclare,\n} from './declared-dependencies.js';\nimport {\n addDependenciesToPackageJson,\n getLocalDependencySpecifier,\n} from './dependencies.js';\nimport { formatFilesInSubtree } from './format.js';\nimport { esmVars } from './module-format.js';\nimport { getNpmScopePrefix } from './npm-scope.js';\nimport {\n PACKAGES_DIR,\n SHARED_SHADCN_DIR,\n SHARED_SHADCN_NAME,\n} from './shared-constructs-constants.js';\nimport { type ITsDepVersion, withVersions } from './versions.js';\n\n/** Dependencies a caller must declare to use the shared shadcn project. */\nexport const SHADCN_DEPENDENCIES = [\n { name: 'react' },\n { name: 'react-dom' },\n { name: 'class-variance-authority' },\n { name: 'clsx' },\n { name: 'tailwind-merge' },\n { name: 'lucide-react' },\n { name: 'tw-animate-css' },\n { name: 'radix-ui' },\n ...VITEST_DEPENDENCIES,\n ...TS_PROJECT_DEPENDENCIES,\n] as const satisfies readonly { name: ITsDepVersion; dev?: boolean }[];\n\n/** The shared shadcn package's fully-qualified npm name for this workspace. */\nexport const getSharedShadcnFullyQualifiedName = (tree: Tree): string =>\n `${getNpmScopePrefix(tree)}${SHARED_SHADCN_NAME}`;\n\n/**\n * Declares a `workspace:*` dependency on the shared shadcn package in a\n * consumer's own package.json, so it resolves through the shared package's\n * `exports` map (real package resolution) rather than a tsconfig `paths`\n * alias - see `sharedShadcnGenerator` for why.\n */\nexport const addSharedShadcnDependency = (\n tree: Tree,\n consumerDir: string,\n): void => {\n addDependenciesToPackageJson(\n tree,\n {\n [getSharedShadcnFullyQualifiedName(tree)]:\n getLocalDependencySpecifier(tree),\n },\n {},\n joinPathFragments(consumerDir, 'package.json'),\n );\n};\n\nexport async function sharedShadcnGenerator<\n const D extends DependencyDeclaration,\n>(tree: Tree, declaration: D & MustDeclare<typeof SHADCN_DEPENDENCIES, D>) {\n const fullyQualifiedName = getSharedShadcnFullyQualifiedName(tree);\n const libraryRoot = joinPathFragments(PACKAGES_DIR, SHARED_SHADCN_DIR);\n const shadcnSrcRoot = joinPathFragments(libraryRoot, 'src');\n\n if (!tree.exists(joinPathFragments(libraryRoot, 'project.json'))) {\n await tsProjectGenerator(tree, {\n name: SHARED_SHADCN_NAME,\n directory: PACKAGES_DIR,\n subDirectory: SHARED_SHADCN_DIR,\n });\n\n tree.delete(shadcnSrcRoot);\n\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', SHARED_SHADCN_DIR, 'src'),\n shadcnSrcRoot,\n esmVars(tree),\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n generateFiles(\n tree,\n joinPathFragments(\n import.meta.dirname,\n 'files',\n SHARED_SHADCN_DIR,\n 'readme',\n ),\n libraryRoot,\n {\n fullyQualifiedName,\n },\n {\n overwriteStrategy: OverwriteStrategy.Overwrite,\n },\n );\n\n await configureTsProject(\n tree,\n {\n dir: libraryRoot,\n fullyQualifiedName,\n },\n forDependencies<typeof SHADCN_DEPENDENCIES>(declaration),\n );\n\n updateJson(\n tree,\n joinPathFragments(libraryRoot, 'tsconfig.lib.json'),\n (json) => ({\n ...json,\n compilerOptions: {\n ...json.compilerOptions,\n jsx: 'react-jsx',\n module: 'preserve',\n moduleResolution: 'bundler',\n lib: Array.from(\n new Set([...(json.compilerOptions?.lib ?? []), 'DOM']),\n ),\n },\n include: Array.from(new Set([...(json.include ?? []), 'src/**/*.tsx'])),\n }),\n );\n\n addDependenciesToPackageJson(\n tree,\n withVersions(\n forDependencies<typeof SHADCN_DEPENDENCIES>(declaration),\n declaredNames(SHADCN_DEPENDENCIES),\n ),\n {},\n joinPathFragments(libraryRoot, 'package.json'),\n );\n\n // shadcn 4.x's CLI resolves the `components.json` alias via `imports`/\n // `exports` (Node's package resolution), not a tsconfig `paths` alias.\n // `imports` covers this package's own internal component-to-component\n // references (aliased in components.json below); `exports` covers every\n // other consumer.\n updateJson(\n tree,\n joinPathFragments(libraryRoot, 'package.json'),\n (packageJson) => ({\n ...packageJson,\n imports: {\n '#components/*': './src/components/*.tsx',\n '#lib/*': './src/lib/*.ts',\n '#hooks/*': './src/hooks/*.ts',\n },\n exports: {\n '.': './src/index.ts',\n './styles/*': './src/styles/*',\n './components/*': './src/components/*.tsx',\n './lib/*': './src/lib/*.ts',\n './hooks/*': './src/hooks/*.ts',\n },\n }),\n );\n }\n\n // components.json lives in the package so `shadcn add` runs there and\n // installs component dependencies into the package's own manifest.\n if (!tree.exists(joinPathFragments(libraryRoot, 'components.json'))) {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'shadcn'),\n libraryRoot,\n {},\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n }\n\n await formatFilesInSubtree(tree);\n}\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","updateJson","tsProjectGenerator","configureTsProject","TS_PROJECT_DEPENDENCIES","VITEST_DEPENDENCIES","declaredNames","forDependencies","addDependenciesToPackageJson","getLocalDependencySpecifier","formatFilesInSubtree","esmVars","getNpmScopePrefix","PACKAGES_DIR","SHARED_SHADCN_DIR","SHARED_SHADCN_NAME","withVersions","SHADCN_DEPENDENCIES","name","getSharedShadcnFullyQualifiedName","tree","addSharedShadcnDependency","consumerDir","sharedShadcnGenerator","declaration","fullyQualifiedName","libraryRoot","shadcnSrcRoot","exists","directory","subDirectory","delete","dirname","overwriteStrategy","KeepExisting","Overwrite","dir","json","compilerOptions","jsx","module","moduleResolution","lib","Array","from","Set","include","packageJson","imports","exports"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EAEjBC,UAAU,QACL,aAAa;AACpB,OAAOC,wBAAwB,yBAAyB;AACxD,SACEC,kBAAkB,EAClBC,uBAAuB,QAClB,gCAAgC;AACvC,SAASC,mBAAmB,QAAQ,sBAAsB;AAC1D,SAEEC,aAAa,EACbC,eAAe,QAEV,6BAA6B;AACpC,SACEC,4BAA4B,EAC5BC,2B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AEJ;IAEA,MAAMxB,qBAAqBU;AAC7B"}
|
package/src/utils/test.js
CHANGED
|
@@ -5,6 +5,13 @@
|
|
|
5
5
|
import { createTreeWithEmptyWorkspace } from "@nx/devkit/testing";
|
|
6
6
|
import { expect } from "vitest";
|
|
7
7
|
import { getDefaultBiomeConfig } from "./format.js";
|
|
8
|
+
/** Formatter configs Nx discovers and formats generated files with. */ const NX_FORMATTER_CONFIG_FILES = [
|
|
9
|
+
'.oxfmtrc.json',
|
|
10
|
+
'.oxfmtrc.jsonc',
|
|
11
|
+
'oxfmt.config.ts',
|
|
12
|
+
'oxfmt.config.mts',
|
|
13
|
+
'.prettierrc'
|
|
14
|
+
];
|
|
8
15
|
/**
|
|
9
16
|
* Create a workspace tree configured so that nx's `isUsingTsSolutionSetup`
|
|
10
17
|
* reports `true`, matching the workspaces our preset generates. Rather than
|
|
@@ -16,6 +23,14 @@ import { getDefaultBiomeConfig } from "./format.js";
|
|
|
16
23
|
* preset establishes
|
|
17
24
|
*/ export const createTreeUsingTsSolutionSetup = ()=>{
|
|
18
25
|
const tree = createTreeWithEmptyWorkspace();
|
|
26
|
+
// `createTreeWithEmptyWorkspace` seeds a formatter config Nx then formats
|
|
27
|
+
// generated files with. Our workspaces select `formatter: 'none'` and format
|
|
28
|
+
// with biome, so remove it to match what the preset produces.
|
|
29
|
+
for (const config of NX_FORMATTER_CONFIG_FILES){
|
|
30
|
+
if (tree.exists(config)) {
|
|
31
|
+
tree.delete(config);
|
|
32
|
+
}
|
|
33
|
+
}
|
|
19
34
|
tree.write('pnpm-workspace.yaml', `packages:\n - packages/*`);
|
|
20
35
|
// Write both workspace markers so package-manager detection finds workspaces
|
|
21
36
|
// enabled whether tests run via pnpm or npm/npx.
|
package/src/utils/test.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/test.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n joinPathFragments,\n readJson,\n type Tree,\n updateJson,\n writeJson,\n} from '@nx/devkit';\nimport { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';\nimport { expect } from 'vitest';\nimport { getDefaultBiomeConfig } from './format.js';\n\n/**\n * Create a workspace tree configured so that nx's `isUsingTsSolutionSetup`\n * reports `true`, matching the workspaces our preset generates. Rather than\n * mocking nx internals, we set up the real markers it checks for:\n * - package manager workspaces enabled (`pnpm-workspace.yaml` with `packages`)\n * - a root `tsconfig.json` extending `tsconfig.base.json` with empty `include`\n * - `composite: true` in `tsconfig.base.json`\n * - a root `package.json` with `type: module`, matching the ESM default the\n * preset establishes\n */\nexport const createTreeUsingTsSolutionSetup = (): Tree => {\n const tree = createTreeWithEmptyWorkspace();\n\n tree.write('pnpm-workspace.yaml', `packages:\\n - packages/*`);\n\n // Write both workspace markers so package-manager detection finds workspaces\n // enabled whether tests run via pnpm or npm/npx.\n updateJson(tree, 'package.json', (json) => ({\n ...json,\n type: 'module',\n workspaces: ['packages/*'],\n }));\n\n const baseTsConfig = readJson(tree, 'tsconfig.base.json');\n writeJson(tree, 'tsconfig.base.json', {\n ...baseTsConfig,\n compilerOptions: { ...baseTsConfig.compilerOptions, composite: true },\n });\n writeJson(tree, 'tsconfig.json', {\n extends: './tsconfig.base.json',\n files: [],\n include: [],\n references: [],\n });\n\n // The preset always writes biome.json at the workspace root, so mirror that\n // here for realistic lint-target configuration.\n tree.write(\n 'biome.json',\n JSON.stringify(getDefaultBiomeConfig(tree), null, 2),\n );\n return tree;\n};\n\n/**\n * Snapshot all files within a directory in the given tree\n */\nexport const snapshotTreeDir = (tree: Tree, dir: string) => {\n if (tree.isFile(dir)) {\n expect(tree.read(dir, 'utf-8')).toMatchSnapshot(dir);\n } else {\n tree\n .children(dir)\n .forEach((subDir) =>\n snapshotTreeDir(tree, joinPathFragments(dir, subDir)),\n );\n }\n};\n"],"names":["joinPathFragments","readJson","updateJson","writeJson","createTreeWithEmptyWorkspace","expect","getDefaultBiomeConfig","createTreeUsingTsSolutionSetup","tree","write","json","type","workspaces","baseTsConfig","compilerOptions","composite","extends","files","include","references","JSON","stringify","snapshotTreeDir","dir","isFile","read","toMatchSnapshot","children","forEach","subDir"],"mappings":"AAAA;;;CAGC,GAED,SACEA,iBAAiB,EACjBC,QAAQ,EAERC,UAAU,EACVC,SAAS,QACJ,aAAa;AACpB,SAASC,4BAA4B,QAAQ,qBAAqB;AAClE,SAASC,MAAM,QAAQ,SAAS;AAChC,SAASC,qBAAqB,QAAQ,cAAc;AAEpD;;;;;;;;;CASC,GACD,OAAO,MAAMC,iCAAiC;IAC5C,MAAMC,
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/test.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n joinPathFragments,\n readJson,\n type Tree,\n updateJson,\n writeJson,\n} from '@nx/devkit';\nimport { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';\nimport { expect } from 'vitest';\nimport { getDefaultBiomeConfig } from './format.js';\n\n/** Formatter configs Nx discovers and formats generated files with. */\nconst NX_FORMATTER_CONFIG_FILES = [\n '.oxfmtrc.json',\n '.oxfmtrc.jsonc',\n 'oxfmt.config.ts',\n 'oxfmt.config.mts',\n '.prettierrc',\n];\n\n/**\n * Create a workspace tree configured so that nx's `isUsingTsSolutionSetup`\n * reports `true`, matching the workspaces our preset generates. Rather than\n * mocking nx internals, we set up the real markers it checks for:\n * - package manager workspaces enabled (`pnpm-workspace.yaml` with `packages`)\n * - a root `tsconfig.json` extending `tsconfig.base.json` with empty `include`\n * - `composite: true` in `tsconfig.base.json`\n * - a root `package.json` with `type: module`, matching the ESM default the\n * preset establishes\n */\nexport const createTreeUsingTsSolutionSetup = (): Tree => {\n const tree = createTreeWithEmptyWorkspace();\n\n // `createTreeWithEmptyWorkspace` seeds a formatter config Nx then formats\n // generated files with. Our workspaces select `formatter: 'none'` and format\n // with biome, so remove it to match what the preset produces.\n for (const config of NX_FORMATTER_CONFIG_FILES) {\n if (tree.exists(config)) {\n tree.delete(config);\n }\n }\n\n tree.write('pnpm-workspace.yaml', `packages:\\n - packages/*`);\n\n // Write both workspace markers so package-manager detection finds workspaces\n // enabled whether tests run via pnpm or npm/npx.\n updateJson(tree, 'package.json', (json) => ({\n ...json,\n type: 'module',\n workspaces: ['packages/*'],\n }));\n\n const baseTsConfig = readJson(tree, 'tsconfig.base.json');\n writeJson(tree, 'tsconfig.base.json', {\n ...baseTsConfig,\n compilerOptions: { ...baseTsConfig.compilerOptions, composite: true },\n });\n writeJson(tree, 'tsconfig.json', {\n extends: './tsconfig.base.json',\n files: [],\n include: [],\n references: [],\n });\n\n // The preset always writes biome.json at the workspace root, so mirror that\n // here for realistic lint-target configuration.\n tree.write(\n 'biome.json',\n JSON.stringify(getDefaultBiomeConfig(tree), null, 2),\n );\n return tree;\n};\n\n/**\n * Snapshot all files within a directory in the given tree\n */\nexport const snapshotTreeDir = (tree: Tree, dir: string) => {\n if (tree.isFile(dir)) {\n expect(tree.read(dir, 'utf-8')).toMatchSnapshot(dir);\n } else {\n tree\n .children(dir)\n .forEach((subDir) =>\n snapshotTreeDir(tree, joinPathFragments(dir, subDir)),\n );\n }\n};\n"],"names":["joinPathFragments","readJson","updateJson","writeJson","createTreeWithEmptyWorkspace","expect","getDefaultBiomeConfig","NX_FORMATTER_CONFIG_FILES","createTreeUsingTsSolutionSetup","tree","config","exists","delete","write","json","type","workspaces","baseTsConfig","compilerOptions","composite","extends","files","include","references","JSON","stringify","snapshotTreeDir","dir","isFile","read","toMatchSnapshot","children","forEach","subDir"],"mappings":"AAAA;;;CAGC,GAED,SACEA,iBAAiB,EACjBC,QAAQ,EAERC,UAAU,EACVC,SAAS,QACJ,aAAa;AACpB,SAASC,4BAA4B,QAAQ,qBAAqB;AAClE,SAASC,MAAM,QAAQ,SAAS;AAChC,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from "./vended-upgrade.js";
|
|
|
39
39
|
/**
|
|
40
40
|
* Whether devkit may be handed this specifier.
|
|
41
41
|
*
|
|
42
|
-
* `catalog:` is only safe where devkit has a catalog manager (pnpm, yarn).
|
|
43
|
-
*
|
|
44
|
-
*
|
|
42
|
+
* `catalog:` is only safe where devkit has a catalog manager (pnpm, yarn, bun).
|
|
43
|
+
* Without one it rewrites the reference to a literal version, severing the
|
|
44
|
+
* catalog — so those references are synced directly instead.
|
|
45
45
|
*/ const isSyncableSpecifier = (tree, declared)=>{
|
|
46
46
|
// A manifest is the user's file and may hold anything. A version that isn't a
|
|
47
47
|
// string is not one this can reason about, and throwing here would abort the
|
|
@@ -132,7 +132,7 @@ import { isVendedUpgrade } from "./vended-upgrade.js";
|
|
|
132
132
|
].map((path)=>tree.exists(path) ? tree.read(path, 'utf-8') : '').join('\0');
|
|
133
133
|
/**
|
|
134
134
|
* Upgrade vended catalog entries devkit cannot reach: those no manifest
|
|
135
|
-
* references
|
|
135
|
+
* references.
|
|
136
136
|
*/ const syncOrphanCatalogEntries = (tree, owned)=>{
|
|
137
137
|
const referenced = referencedCatalogPackages(tree);
|
|
138
138
|
const updated = [];
|