@aws/nx-plugin 1.0.0-rc.45 → 1.0.0-rc.47
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 +3 -60
- package/generators.json +9 -9
- package/package.json +7 -3
- package/src/agentcore-gateway/generator.js +12 -2
- package/src/agentcore-gateway/generator.js.map +1 -1
- package/src/infra/app/__snapshots__/generator.spec.ts.snap +25 -31
- package/src/infra/app/generator.js +9 -6
- package/src/infra/app/generator.js.map +1 -1
- package/src/license/config.js +1 -1
- package/src/license/config.js.map +1 -1
- package/src/mcp-server/schema.d.ts +1 -1
- package/src/mcp-server/tools/general-guidance.js +5 -6
- package/src/mcp-server/tools/general-guidance.js.map +1 -1
- package/src/preset/__snapshots__/generator.spec.ts.snap +38 -7
- package/src/preset/generator.d.ts +1 -1
- package/src/preset/generator.js +4 -2
- package/src/preset/generator.js.map +1 -1
- package/src/preset/schema.d.js.map +1 -1
- package/src/preset/schema.d.ts +1 -0
- package/src/preset/schema.json +5 -0
- package/src/py/agent/generator.js +2 -1
- package/src/py/agent/generator.js.map +1 -1
- package/src/py/mcp-server/generator.js +2 -1
- package/src/py/mcp-server/generator.js.map +1 -1
- package/src/py/project/generator.js +2 -1
- package/src/py/project/generator.js.map +1 -1
- package/src/py/rdb/__snapshots__/generator.spec.ts.snap +1 -0
- package/src/py/rdb/generator.js +7 -1
- package/src/py/rdb/generator.js.map +1 -1
- package/src/smithy/ts/api/generator.js +5 -2
- package/src/smithy/ts/api/generator.js.map +1 -1
- package/src/terraform/project/generator.js +4 -1
- package/src/terraform/project/generator.js.map +1 -1
- package/src/trpc/backend/__snapshots__/generator.spec.ts.snap +6 -6
- package/src/trpc/backend/generator.js +7 -5
- package/src/trpc/backend/generator.js.map +1 -1
- package/src/trpc/react/generator.js +4 -4
- package/src/trpc/react/generator.js.map +1 -1
- package/src/ts/agent/__snapshots__/generator.spec.ts.snap +2 -2
- package/src/ts/agent/a2a-connection/generator.js +3 -2
- package/src/ts/agent/a2a-connection/generator.js.map +1 -1
- package/src/ts/agent/gateway-connection/generator.js +4 -3
- package/src/ts/agent/gateway-connection/generator.js.map +1 -1
- package/src/ts/agent/generator.js +8 -5
- package/src/ts/agent/generator.js.map +1 -1
- package/src/ts/agent/mcp-connection/__snapshots__/generator.spec.ts.snap +1 -1
- package/src/ts/agent/mcp-connection/generator.js +4 -3
- package/src/ts/agent/mcp-connection/generator.js.map +1 -1
- package/src/ts/agent/react-connection/generator.js +10 -19
- package/src/ts/agent/react-connection/generator.js.map +1 -1
- package/src/ts/astro-docs/generator.js +12 -3
- package/src/ts/astro-docs/generator.js.map +1 -1
- package/src/ts/dcr-proxy/generator.js +5 -5
- package/src/ts/dcr-proxy/generator.js.map +1 -1
- package/src/ts/dynamodb/generator.js +5 -2
- package/src/ts/dynamodb/generator.js.map +1 -1
- package/src/ts/lambda-function/__snapshots__/generator.spec.ts.snap +4 -2
- package/src/ts/lambda-function/files/handler/__lambdaFunctionKebabCase__.ts.template +2 -1
- package/src/ts/lambda-function/generator.js +3 -2
- package/src/ts/lambda-function/generator.js.map +1 -1
- package/src/ts/lib/ts-project-utils.js +17 -10
- package/src/ts/lib/ts-project-utils.js.map +1 -1
- package/src/ts/lib/vitest.js +2 -1
- package/src/ts/lib/vitest.js.map +1 -1
- package/src/ts/mcp-server/generator.js +11 -11
- package/src/ts/mcp-server/generator.js.map +1 -1
- package/src/ts/nx-generator/generator.js +5 -0
- package/src/ts/nx-generator/generator.js.map +1 -1
- package/src/ts/nx-plugin/__snapshots__/generator.spec.ts.snap +5 -6
- package/src/ts/nx-plugin/files/mcp-server/resources/GENERAL_GUIDANCE.md.template +5 -6
- package/src/ts/nx-plugin/utils.js +2 -1
- package/src/ts/nx-plugin/utils.js.map +1 -1
- package/src/ts/rdb/agent-connection/generator.js +1 -2
- package/src/ts/rdb/agent-connection/generator.js.map +1 -1
- package/src/ts/rdb/generator.js +10 -6
- package/src/ts/rdb/generator.js.map +1 -1
- package/src/ts/rdb/mcp-server-connection/generator.js +1 -2
- package/src/ts/rdb/mcp-server-connection/generator.js.map +1 -1
- package/src/ts/rdb/smithy-connection/generator.js +1 -2
- package/src/ts/rdb/smithy-connection/generator.js.map +1 -1
- package/src/ts/rdb/trpc-connection/generator.js +1 -2
- package/src/ts/rdb/trpc-connection/generator.js.map +1 -1
- package/src/ts/react-website/agui/generator.js +5 -4
- package/src/ts/react-website/agui/generator.js.map +1 -1
- package/src/ts/react-website/app/__snapshots__/generator.spec.ts.snap +219 -79
- package/src/ts/react-website/app/generator.js +34 -14
- package/src/ts/react-website/app/generator.js.map +1 -1
- package/src/ts/react-website/cognito-auth/__snapshots__/generator.spec.ts.snap +11 -6
- package/src/ts/react-website/cognito-auth/__snapshots__/generator.terraform.spec.ts.snap +12 -2
- package/src/ts/react-website/cognito-auth/generator.js +3 -2
- package/src/ts/react-website/cognito-auth/generator.js.map +1 -1
- package/src/ts/react-website/runtime-config/generator.js +2 -2
- package/src/ts/react-website/runtime-config/generator.js.map +1 -1
- package/src/ts/sync/generator.js +81 -3
- package/src/ts/sync/generator.js.map +1 -1
- package/src/utils/agent-connection/agent-connection.d.ts +1 -1
- package/src/utils/agent-connection/agent-connection.js +50 -1
- package/src/utils/agent-connection/agent-connection.js.map +1 -1
- package/src/utils/agent-core-constructs/agent-core-constructs.js +10 -1
- package/src/utils/agent-core-constructs/agent-core-constructs.js.map +1 -1
- package/src/utils/api-constructs/api-constructs.js +15 -1
- package/src/utils/api-constructs/api-constructs.js.map +1 -1
- package/src/utils/bundle/bundle.js +2 -1
- package/src/utils/bundle/bundle.js.map +1 -1
- package/src/utils/commands.d.ts +5 -3
- package/src/utils/commands.js +24 -3
- package/src/utils/commands.js.map +1 -1
- package/src/utils/config/index.d.ts +16 -0
- package/src/utils/config/index.js.map +1 -1
- package/src/utils/config/utils.d.ts +3 -2
- package/src/utils/config/utils.js +4 -3
- package/src/utils/config/utils.js.map +1 -1
- package/src/utils/connection/open-api/react.js +3 -2
- package/src/utils/connection/open-api/react.js.map +1 -1
- package/src/utils/containers.js +1 -1
- package/src/utils/containers.js.map +1 -1
- package/src/utils/dependencies.d.ts +18 -0
- package/src/utils/dependencies.js +206 -0
- package/src/utils/dependencies.js.map +1 -0
- package/src/utils/files/common/shadcn/readme/README.md.template +3 -3
- package/src/utils/files/shadcn/components.json.template +1 -1
- package/src/utils/format.d.ts +20 -1
- package/src/utils/format.js +83 -49
- package/src/utils/format.js.map +1 -1
- package/src/utils/fs.d.ts +1 -1
- package/src/utils/fs.js +1 -1
- package/src/utils/fs.js.map +1 -1
- package/src/utils/iac.js +1 -1
- package/src/utils/iac.js.map +1 -1
- package/src/utils/identity-constructs/files/cdk/core/user-identity.ts.template +11 -6
- package/src/utils/identity-constructs/identity-constructs.js +14 -3
- package/src/utils/identity-constructs/identity-constructs.js.map +1 -1
- package/src/utils/init.d.ts +7 -1
- package/src/utils/init.js +38 -17
- package/src/utils/init.js.map +1 -1
- package/src/utils/install.js +3 -1
- package/src/utils/install.js.map +1 -1
- package/src/utils/module-format.d.ts +5 -8
- package/src/utils/module-format.js +29 -12
- package/src/utils/module-format.js.map +1 -1
- package/src/utils/npm-scope.d.ts +0 -4
- package/src/utils/npm-scope.js +0 -5
- package/src/utils/npm-scope.js.map +1 -1
- package/src/utils/pnpm-workspace.d.ts +1 -12
- package/src/utils/pnpm-workspace.js +3 -30
- package/src/utils/pnpm-workspace.js.map +1 -1
- package/src/utils/project-package-json.d.ts +39 -0
- package/src/utils/project-package-json.js +119 -0
- package/src/utils/project-package-json.js.map +1 -0
- package/src/utils/shared-constructs.js +6 -5
- package/src/utils/shared-constructs.js.map +1 -1
- package/src/utils/shared-dynamodb-scripts.js +4 -2
- package/src/utils/shared-dynamodb-scripts.js.map +1 -1
- package/src/utils/shared-infra-scripts.js +5 -4
- package/src/utils/shared-infra-scripts.js.map +1 -1
- package/src/utils/shared-rdb-scripts.js +14 -1
- package/src/utils/shared-rdb-scripts.js.map +1 -1
- package/src/utils/shared-shadcn.js +11 -8
- package/src/utils/shared-shadcn.js.map +1 -1
- package/src/utils/test.js +8 -3
- package/src/utils/test.js.map +1 -1
- package/src/utils/versions.d.ts +4 -0
- package/src/utils/versions.js +8 -1
- package/src/utils/versions.js.map +1 -1
- package/src/utils/website-constructs/files/cdk/core/static-website.ts.template +3 -0
package/src/utils/iac.js
CHANGED
|
@@ -8,7 +8,7 @@ import { IAC_PROVIDERS } from "./iac-providers.js";
|
|
|
8
8
|
* Given an iac provider option, resolve the actual iac provider to use
|
|
9
9
|
*/ export const resolveIac = async (tree, iacOption)=>{
|
|
10
10
|
if (iacOption === 'inherit') {
|
|
11
|
-
const pluginConfig =
|
|
11
|
+
const pluginConfig = readAwsNxPluginConfig(tree);
|
|
12
12
|
if (!pluginConfig?.iac?.provider) {
|
|
13
13
|
throw new Error(`IaC provider "inherit" requires iac.provider to be set in ${AWS_NX_PLUGIN_CONFIG_FILE_NAME}`);
|
|
14
14
|
}
|
package/src/utils/iac.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/iac.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Tree } from '@nx/devkit';\nimport {\n AWS_NX_PLUGIN_CONFIG_FILE_NAME,\n readAwsNxPluginConfig,\n} from './config/utils';\n\nexport { IAC_PROVIDERS, type Iac, type IacOption } from './iac-providers';\n\nimport { IAC_PROVIDERS } from './iac-providers';\n\n/**\n * Configuration for infrastructure as code\n */\nexport interface IacConfig {\n /**\n * Default provider for infrastructure as code\n */\n provider: (typeof IAC_PROVIDERS)[number];\n}\n\n/**\n * Given an iac provider option, resolve the actual iac provider to use\n */\nexport const resolveIac = async (\n tree: Tree,\n iacOption: 'cdk' | 'terraform' | 'inherit',\n): Promise<(typeof IAC_PROVIDERS)[number]> => {\n if (iacOption === 'inherit') {\n const pluginConfig =
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/iac.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport type { Tree } from '@nx/devkit';\nimport {\n AWS_NX_PLUGIN_CONFIG_FILE_NAME,\n readAwsNxPluginConfig,\n} from './config/utils';\n\nexport { IAC_PROVIDERS, type Iac, type IacOption } from './iac-providers';\n\nimport { IAC_PROVIDERS } from './iac-providers';\n\n/**\n * Configuration for infrastructure as code\n */\nexport interface IacConfig {\n /**\n * Default provider for infrastructure as code\n */\n provider: (typeof IAC_PROVIDERS)[number];\n}\n\n/**\n * Given an iac provider option, resolve the actual iac provider to use\n */\nexport const resolveIac = async (\n tree: Tree,\n iacOption: 'cdk' | 'terraform' | 'inherit',\n): Promise<(typeof IAC_PROVIDERS)[number]> => {\n if (iacOption === 'inherit') {\n const pluginConfig = readAwsNxPluginConfig(tree);\n\n if (!pluginConfig?.iac?.provider) {\n throw new Error(\n `IaC provider \"inherit\" requires iac.provider to be set in ${AWS_NX_PLUGIN_CONFIG_FILE_NAME}`,\n );\n }\n if (!IAC_PROVIDERS.includes(pluginConfig.iac.provider)) {\n throw new Error(\n `iac.provider in ${AWS_NX_PLUGIN_CONFIG_FILE_NAME} must be one of ${IAC_PROVIDERS.join(', ')}`,\n );\n }\n\n return pluginConfig.iac.provider;\n }\n return iacOption;\n};\n"],"names":["AWS_NX_PLUGIN_CONFIG_FILE_NAME","readAwsNxPluginConfig","IAC_PROVIDERS","resolveIac","tree","iacOption","pluginConfig","iac","provider","Error","includes","join"],"mappings":"AAAA;;;CAGC,GAED,SACEA,8BAA8B,EAC9BC,qBAAqB,QAChB,oBAAiB;AAExB,SAASC,aAAa,QAAkC,qBAAkB;AAE1E,SAASA,aAAa,QAAQ,qBAAkB;AAYhD;;CAEC,GACD,OAAO,MAAMC,aAAa,OACxBC,MACAC;IAEA,IAAIA,cAAc,WAAW;QAC3B,MAAMC,eAAeL,sBAAsBG;QAE3C,IAAI,CAACE,cAAcC,KAAKC,UAAU;YAChC,MAAM,IAAIC,MACR,CAAC,0DAA0D,EAAET,gCAAgC;QAEjG;QACA,IAAI,CAACE,cAAcQ,QAAQ,CAACJ,aAAaC,GAAG,CAACC,QAAQ,GAAG;YACtD,MAAM,IAAIC,MACR,CAAC,gBAAgB,EAAET,+BAA+B,gBAAgB,EAAEE,cAAcS,IAAI,CAAC,OAAO;QAElG;QAEA,OAAOL,aAAaC,GAAG,CAACC,QAAQ;IAClC;IACA,OAAOH;AACT,EAAE"}
|
|
@@ -30,7 +30,7 @@ import {
|
|
|
30
30
|
import { LogGroup, RetentionDays } from 'aws-cdk-lib/aws-logs';
|
|
31
31
|
import { Construct } from 'constructs';
|
|
32
32
|
import { RuntimeConfig } from './runtime-config<% if (esm) { %>.js<% } %>';
|
|
33
|
-
import { Distribution } from 'aws-cdk-lib/aws-cloudfront';
|
|
33
|
+
import { CfnDistribution, Distribution } from 'aws-cdk-lib/aws-cloudfront';
|
|
34
34
|
import { suppressRules } from './checkov<% if (esm) { %>.js<% } %>';
|
|
35
35
|
|
|
36
36
|
const WEB_CLIENT_ID = 'WebClient';
|
|
@@ -242,9 +242,7 @@ export class UserIdentity extends Construct {
|
|
|
242
242
|
const lazilyComputedCallbackUrls = Lazy.list({
|
|
243
243
|
produce: () =>
|
|
244
244
|
['http://localhost:4200', 'http://localhost:4300'].concat(
|
|
245
|
-
this.
|
|
246
|
-
(d) => `https://${d.domainName}`
|
|
247
|
-
)
|
|
245
|
+
this.findCloudFrontDomainNames().map((domain) => `https://${domain}`)
|
|
248
246
|
),
|
|
249
247
|
});
|
|
250
248
|
|
|
@@ -294,8 +292,15 @@ export class UserIdentity extends Construct {
|
|
|
294
292
|
}).node.addDependency(userPoolClient, userPool, userPoolDomain);
|
|
295
293
|
};
|
|
296
294
|
|
|
297
|
-
|
|
295
|
+
// Includes each distribution's default domain name plus any custom domain names (aliases) configured on it.
|
|
296
|
+
private findCloudFrontDomainNames = (): string[] =>
|
|
298
297
|
Stack.of(this)
|
|
299
298
|
.node.findAll()
|
|
300
|
-
.filter((child) => child instanceof Distribution)
|
|
299
|
+
.filter((child): child is Distribution => child instanceof Distribution)
|
|
300
|
+
.flatMap((d) => {
|
|
301
|
+
const cfnDistribution = d.node.defaultChild as CfnDistribution;
|
|
302
|
+
const distributionConfig =
|
|
303
|
+
cfnDistribution.distributionConfig as CfnDistribution.DistributionConfigProperty;
|
|
304
|
+
return [d.domainName, ...(distributionConfig.aliases ?? [])];
|
|
305
|
+
});
|
|
301
306
|
}
|
|
@@ -37,14 +37,25 @@ const addIdentityTerraformModules = (tree, options)=>{
|
|
|
37
37
|
// Update the static website module to add the callback url
|
|
38
38
|
const staticWebsiteModule = tree.read(joinPathFragments(PACKAGES_DIR, SHARED_TERRAFORM_DIR, 'src', 'core', 'static-website', 'static-website.tf'), 'utf-8');
|
|
39
39
|
if (staticWebsiteModule && !staticWebsiteModule.includes('source = "../user-identity/add-callback-url"')) {
|
|
40
|
-
// Find the aws_cloudfront_distribution.website resource and add the callback URL module after it
|
|
40
|
+
// Find the aws_cloudfront_distribution.website resource and add the callback URL module after it.
|
|
41
|
+
// Includes the CloudFront domain plus any custom domain names (aliases) configured via var.custom_domain_names.
|
|
41
42
|
const callbackUrlModule = `
|
|
42
43
|
|
|
43
|
-
# Add CloudFront domain to user pool client callback URLs
|
|
44
|
+
# Add CloudFront domain and any custom domain names to user pool client callback URLs.
|
|
45
|
+
# Keyed by statically-known values so for_each keys are resolvable at plan time; the
|
|
46
|
+
# CloudFront domain is only known at apply time, so it appears in the value, not the key.
|
|
47
|
+
locals {
|
|
48
|
+
callback_urls = merge(
|
|
49
|
+
{ cloudfront = "https://\${aws_cloudfront_distribution.website.domain_name}" },
|
|
50
|
+
{ for domain in var.custom_domain_names : domain => "https://\${domain}" },
|
|
51
|
+
)
|
|
52
|
+
}
|
|
53
|
+
|
|
44
54
|
module "add_callback_url" {
|
|
45
55
|
source = "../user-identity/add-callback-url"
|
|
56
|
+
for_each = local.callback_urls
|
|
46
57
|
|
|
47
|
-
callback_url =
|
|
58
|
+
callback_url = each.value
|
|
48
59
|
|
|
49
60
|
depends_on = [aws_cloudfront_distribution.website]
|
|
50
61
|
}`;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/identity-constructs/identity-constructs.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type Tree,\n} from '@nx/devkit';\nimport { addStarExport } from '../ast';\nimport type { Iac } from '../iac';\nimport { esmVars } from '../module-format';\nimport {\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n SHARED_TERRAFORM_DIR,\n} from '../shared-constructs-constants';\nimport { PY_VERSIONS, terraformProviderVersions } from '../versions';\n\nexport interface AddIdentityInfraOptions {\n cognitoDomain: string;\n allowSignup: boolean;\n}\n\n/**\n * Add infrastructure for a static website\n */\nexport const addIdentityInfra = async (\n tree: Tree,\n options: AddIdentityInfraOptions & { iac: Iac },\n) => {\n if (options.iac === 'cdk') {\n await addIdentityCdkConstructs(tree, options);\n } else if (options.iac === 'terraform') {\n addIdentityTerraformModules(tree, options);\n } else {\n throw new Error(`Unsupported iac ${options.iac}`);\n }\n};\n\nconst addIdentityCdkConstructs = async (\n tree: Tree,\n options: AddIdentityInfraOptions,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'cdk', 'core'),\n joinPathFragments(PACKAGES_DIR, SHARED_CONSTRUCTS_DIR, 'src', 'core'),\n { ...options, ...esmVars(tree) },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n await addStarExport(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'core',\n 'index.ts',\n ),\n './user-identity.js',\n );\n};\n\nconst addIdentityTerraformModules = (\n tree: Tree,\n options: AddIdentityInfraOptions,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'terraform', 'core'),\n joinPathFragments(PACKAGES_DIR, SHARED_TERRAFORM_DIR, 'src', 'core'),\n {\n ...options,\n boto3Version: PY_VERSIONS.boto3,\n ...terraformProviderVersions(),\n },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n // Update the static website module to add the callback url\n const staticWebsiteModule = tree.read(\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_TERRAFORM_DIR,\n 'src',\n 'core',\n 'static-website',\n 'static-website.tf',\n ),\n 'utf-8',\n );\n if (\n staticWebsiteModule &&\n !staticWebsiteModule.includes(\n 'source = \"../user-identity/add-callback-url\"',\n )\n ) {\n // Find the aws_cloudfront_distribution.website resource and add the callback URL module after it
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/utils/identity-constructs/identity-constructs.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n type Tree,\n} from '@nx/devkit';\nimport { addStarExport } from '../ast';\nimport type { Iac } from '../iac';\nimport { esmVars } from '../module-format';\nimport {\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n SHARED_TERRAFORM_DIR,\n} from '../shared-constructs-constants';\nimport { PY_VERSIONS, terraformProviderVersions } from '../versions';\n\nexport interface AddIdentityInfraOptions {\n cognitoDomain: string;\n allowSignup: boolean;\n}\n\n/**\n * Add infrastructure for a static website\n */\nexport const addIdentityInfra = async (\n tree: Tree,\n options: AddIdentityInfraOptions & { iac: Iac },\n) => {\n if (options.iac === 'cdk') {\n await addIdentityCdkConstructs(tree, options);\n } else if (options.iac === 'terraform') {\n addIdentityTerraformModules(tree, options);\n } else {\n throw new Error(`Unsupported iac ${options.iac}`);\n }\n};\n\nconst addIdentityCdkConstructs = async (\n tree: Tree,\n options: AddIdentityInfraOptions,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'cdk', 'core'),\n joinPathFragments(PACKAGES_DIR, SHARED_CONSTRUCTS_DIR, 'src', 'core'),\n { ...options, ...esmVars(tree) },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n await addStarExport(\n tree,\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_CONSTRUCTS_DIR,\n 'src',\n 'core',\n 'index.ts',\n ),\n './user-identity.js',\n );\n};\n\nconst addIdentityTerraformModules = (\n tree: Tree,\n options: AddIdentityInfraOptions,\n) => {\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'terraform', 'core'),\n joinPathFragments(PACKAGES_DIR, SHARED_TERRAFORM_DIR, 'src', 'core'),\n {\n ...options,\n boto3Version: PY_VERSIONS.boto3,\n ...terraformProviderVersions(),\n },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n\n // Update the static website module to add the callback url\n const staticWebsiteModule = tree.read(\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_TERRAFORM_DIR,\n 'src',\n 'core',\n 'static-website',\n 'static-website.tf',\n ),\n 'utf-8',\n );\n if (\n staticWebsiteModule &&\n !staticWebsiteModule.includes(\n 'source = \"../user-identity/add-callback-url\"',\n )\n ) {\n // Find the aws_cloudfront_distribution.website resource and add the callback URL module after it.\n // Includes the CloudFront domain plus any custom domain names (aliases) configured via var.custom_domain_names.\n const callbackUrlModule = `\n\n# Add CloudFront domain and any custom domain names to user pool client callback URLs.\n# Keyed by statically-known values so for_each keys are resolvable at plan time; the\n# CloudFront domain is only known at apply time, so it appears in the value, not the key.\nlocals {\n callback_urls = merge(\n { cloudfront = \"https://\\${aws_cloudfront_distribution.website.domain_name}\" },\n { for domain in var.custom_domain_names : domain => \"https://\\${domain}\" },\n )\n}\n\nmodule \"add_callback_url\" {\n source = \"../user-identity/add-callback-url\"\n for_each = local.callback_urls\n\n callback_url = each.value\n\n depends_on = [aws_cloudfront_distribution.website]\n}`;\n\n // Find the CloudFront distribution resource using proper brace counting\n // This handles deeply nested structures correctly\n const resourceStartPattern =\n /resource\\s+\"aws_cloudfront_distribution\"\\s+\"website\"\\s*\\{/;\n const resourceStartMatch = staticWebsiteModule.match(resourceStartPattern);\n\n if (resourceStartMatch) {\n const startIndex =\n resourceStartMatch.index! + resourceStartMatch[0].length - 1; // Position at opening brace\n let braceCount = 0;\n let insertionPoint = -1;\n\n // Count braces to find the end of the resource block\n for (let i = startIndex; i < staticWebsiteModule.length; i++) {\n const char = staticWebsiteModule[i];\n if (char === '{') {\n braceCount++;\n } else if (char === '}') {\n braceCount--;\n if (braceCount === 0) {\n // Found the closing brace of the CloudFront resource\n insertionPoint = i + 1;\n break;\n }\n }\n }\n\n if (insertionPoint !== -1) {\n // Insert the callback URL module right after the CloudFront distribution\n const beforeInsertion = staticWebsiteModule.substring(\n 0,\n insertionPoint,\n );\n const afterInsertion = staticWebsiteModule.substring(insertionPoint);\n const updatedContent =\n beforeInsertion + callbackUrlModule + afterInsertion;\n\n tree.write(\n joinPathFragments(\n PACKAGES_DIR,\n SHARED_TERRAFORM_DIR,\n 'src',\n 'core',\n 'static-website',\n 'static-website.tf',\n ),\n updatedContent,\n );\n }\n }\n }\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","addStarExport","esmVars","PACKAGES_DIR","SHARED_CONSTRUCTS_DIR","SHARED_TERRAFORM_DIR","PY_VERSIONS","terraformProviderVersions","addIdentityInfra","tree","options","iac","addIdentityCdkConstructs","addIdentityTerraformModules","Error","dirname","overwriteStrategy","KeepExisting","boto3Version","boto3","staticWebsiteModule","read","includes","callbackUrlModule","resourceStartPattern","resourceStartMatch","match","startIndex","index","length","braceCount","insertionPoint","i","char","beforeInsertion","substring","afterInsertion","updatedContent","write"],"mappings":"AAAA;;;CAGC,GACD,SACE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AAQ,CAC3B,iDAEF;QACA,kGAAkG;QAClG,gHAAgH;QAChH,MAAMC,oBAAoB,CAAC;;;;;;;;;;;;;;;;;;;CAmB9B,CAAC;QAEE,wEAAwE;QACxE,kDAAkD;QAClD,MAAMC,uBACJ;QACF,MAAMC,qBAAqBL,oBAAoBM,KAAK,CAACF;QAErD,IAAIC,oBAAoB;YACtB,MAAME,aACJF,mBAAmBG,KAAK,GAAIH,kBAAkB,CAAC,EAAE,CAACI,MAAM,GAAG,GAAG,4BAA4B;YAC5F,IAAIC,aAAa;YACjB,IAAIC,iBAAiB,CAAC;YAEtB,qDAAqD;YACrD,IAAK,IAAIC,IAAIL,YAAYK,IAAIZ,oBAAoBS,MAAM,EAAEG,IAAK;gBAC5D,MAAMC,OAAOb,mBAAmB,CAACY,EAAE;gBACnC,IAAIC,SAAS,KAAK;oBAChBH;gBACF,OAAO,IAAIG,SAAS,KAAK;oBACvBH;oBACA,IAAIA,eAAe,GAAG;wBACpB,qDAAqD;wBACrDC,iBAAiBC,IAAI;wBACrB;oBACF;gBACF;YACF;YAEA,IAAID,mBAAmB,CAAC,GAAG;gBACzB,yEAAyE;gBACzE,MAAMG,kBAAkBd,oBAAoBe,SAAS,CACnD,GACAJ;gBAEF,MAAMK,iBAAiBhB,oBAAoBe,SAAS,CAACJ;gBACrD,MAAMM,iBACJH,kBAAkBX,oBAAoBa;gBAExC3B,KAAK6B,KAAK,CACRvC,kBACEI,cACAE,sBACA,OACA,QACA,kBACA,sBAEFgC;YAEJ;QACF;IACF;AACF"}
|
package/src/utils/init.d.ts
CHANGED
|
@@ -34,6 +34,12 @@ export interface ApplyWorkspaceInitOptions {
|
|
|
34
34
|
* the default) — it only adds the convenience scripts that are absent.
|
|
35
35
|
*/
|
|
36
36
|
readonly overwriteScripts?: boolean;
|
|
37
|
+
/**
|
|
38
|
+
* Whether generators use the package manager's dependency catalog. On pnpm
|
|
39
|
+
* this also sets `catalogMode: strict` so `pnpm add` records new deps in the
|
|
40
|
+
* catalog. Defaults to true.
|
|
41
|
+
*/
|
|
42
|
+
readonly catalogs?: boolean;
|
|
37
43
|
}
|
|
38
44
|
/**
|
|
39
45
|
* Transform an Nx workspace into one ready to run `@aws/nx-plugin` generators.
|
|
@@ -50,4 +56,4 @@ export interface ApplyWorkspaceInitOptions {
|
|
|
50
56
|
* existing projects — those are decisions for the user (see the "add to an
|
|
51
57
|
* existing workspace" guide).
|
|
52
58
|
*/
|
|
53
|
-
export declare const applyWorkspaceInit: (tree: Tree, { iac, containers, mcp, readmeOverwriteStrategy, overwriteScripts, }: ApplyWorkspaceInitOptions) => Promise<void>;
|
|
59
|
+
export declare const applyWorkspaceInit: (tree: Tree, { iac, containers, mcp, readmeOverwriteStrategy, overwriteScripts, catalogs, }: ApplyWorkspaceInitOptions) => Promise<void>;
|
package/src/utils/init.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
3
|
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
-
*/ import {
|
|
4
|
+
*/ import { generateFiles, joinPathFragments, OverwriteStrategy, readNxJson, updateJson, updateNxJson } from "@nx/devkit";
|
|
5
5
|
import { initGenerator } from "@nx/js";
|
|
6
6
|
import yaml from "js-yaml";
|
|
7
7
|
import { readModulePackageJson } from "nx/src/utils/package-json";
|
|
@@ -12,11 +12,13 @@ import { SYNC_GENERATOR_NAME as TS_SYNC_GENERATOR_NAME } from "../ts/sync/genera
|
|
|
12
12
|
import { BASE_TSCONFIG_COMPILER_OPTIONS } from "./base-tsconfig.js";
|
|
13
13
|
import { ensureAwsNxPluginConfig, updateAwsNxPluginConfig } from "./config/utils.js";
|
|
14
14
|
import { inferContainers } from "./containers.js";
|
|
15
|
-
import {
|
|
15
|
+
import { addDependenciesToPackageJson, detectWorkspacePackageManager } from "./dependencies.js";
|
|
16
|
+
import { getDefaultBiomeConfig } from "./format.js";
|
|
16
17
|
import { configureMcpServers } from "./mcp.js";
|
|
17
18
|
import { getNpmScope } from "./npm-scope.js";
|
|
18
19
|
import { mergeTargetDefault } from "./nx.js";
|
|
19
20
|
import { getPackageManagerDisplayCommands } from "./pkg-manager.js";
|
|
21
|
+
import { workspaceGlobs } from "./project-package-json.js";
|
|
20
22
|
import { withVersions } from "./versions.js";
|
|
21
23
|
const WORKSPACES = [
|
|
22
24
|
'packages/*'
|
|
@@ -43,7 +45,7 @@ export const PNPM_BUILT_DEPENDENCIES = [
|
|
|
43
45
|
* broken `set this to true or false` placeholder pnpm writes when it skips a
|
|
44
46
|
* build script. This makes the file self-consistent so the first generator's
|
|
45
47
|
* install doesn't fail with `ERR_PNPM_IGNORED_BUILDS`.
|
|
46
|
-
*/ const setUpPnpmWorkspace = (tree)=>{
|
|
48
|
+
*/ const setUpPnpmWorkspace = (tree, catalogs)=>{
|
|
47
49
|
const existing = tree.exists('pnpm-workspace.yaml') ? yaml.load(tree.read('pnpm-workspace.yaml', 'utf-8') ?? '') ?? {} : {};
|
|
48
50
|
// Preserve any packages globs the user already has, ensuring ours are present.
|
|
49
51
|
const packages = Array.from(new Set([
|
|
@@ -59,11 +61,18 @@ export const PNPM_BUILT_DEPENDENCIES = [
|
|
|
59
61
|
true
|
|
60
62
|
]))
|
|
61
63
|
};
|
|
64
|
+
// `strict` makes `pnpm add` record new deps in the catalog; it only gates
|
|
65
|
+
// that flow, so pre-declared direct ranges (e.g. tslib) still install.
|
|
66
|
+
// Preserve an explicit user choice.
|
|
67
|
+
const catalogMode = catalogs ? existing.catalogMode ?? 'strict' : existing.catalogMode;
|
|
62
68
|
tree.write('pnpm-workspace.yaml', yaml.dump({
|
|
63
69
|
...existing,
|
|
64
70
|
packages,
|
|
65
71
|
allowBuilds,
|
|
66
|
-
onlyBuiltDependencies: PNPM_BUILT_DEPENDENCIES
|
|
72
|
+
onlyBuiltDependencies: PNPM_BUILT_DEPENDENCIES,
|
|
73
|
+
...catalogMode ? {
|
|
74
|
+
catalogMode
|
|
75
|
+
} : {}
|
|
67
76
|
}, {
|
|
68
77
|
quotingType: "'"
|
|
69
78
|
}));
|
|
@@ -73,17 +82,25 @@ export const PNPM_BUILT_DEPENDENCIES = [
|
|
|
73
82
|
*
|
|
74
83
|
* pnpm workspaces are declared in `pnpm-workspace.yaml`; every other package
|
|
75
84
|
* manager reads the `workspaces` field of the root `package.json`.
|
|
76
|
-
*/ const setUpWorkspaces = (tree)=>{
|
|
77
|
-
if (
|
|
78
|
-
setUpPnpmWorkspace(tree);
|
|
85
|
+
*/ const setUpWorkspaces = (tree, catalogs)=>{
|
|
86
|
+
if (detectWorkspacePackageManager(tree) === 'pnpm') {
|
|
87
|
+
setUpPnpmWorkspace(tree, catalogs);
|
|
79
88
|
} else {
|
|
80
|
-
updateJson(tree, 'package.json', (json)=>
|
|
89
|
+
updateJson(tree, 'package.json', (json)=>{
|
|
90
|
+
// The `workspaces` field may be the object form ({ "packages": [...] })
|
|
91
|
+
// accepted by yarn and bun — extend the globs while preserving the form.
|
|
92
|
+
const globs = Array.from(new Set([
|
|
93
|
+
...workspaceGlobs(json.workspaces),
|
|
94
|
+
...WORKSPACES
|
|
95
|
+
]));
|
|
96
|
+
return {
|
|
81
97
|
...json,
|
|
82
|
-
workspaces: Array.
|
|
83
|
-
...json.workspaces
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
}
|
|
98
|
+
workspaces: json.workspaces !== undefined && !Array.isArray(json.workspaces) ? {
|
|
99
|
+
...json.workspaces,
|
|
100
|
+
packages: globs
|
|
101
|
+
} : globs
|
|
102
|
+
};
|
|
103
|
+
});
|
|
87
104
|
}
|
|
88
105
|
};
|
|
89
106
|
/**
|
|
@@ -140,9 +157,10 @@ export const PNPM_BUILT_DEPENDENCIES = [
|
|
|
140
157
|
* compiler options, migrate a workspace's package manager, or restructure
|
|
141
158
|
* existing projects — those are decisions for the user (see the "add to an
|
|
142
159
|
* existing workspace" guide).
|
|
143
|
-
*/ export const applyWorkspaceInit = async (tree, { iac, containers, mcp, readmeOverwriteStrategy = OverwriteStrategy.KeepExisting, overwriteScripts = false })=>{
|
|
160
|
+
*/ export const applyWorkspaceInit = async (tree, { iac, containers, mcp, readmeOverwriteStrategy = OverwriteStrategy.KeepExisting, overwriteScripts = false, catalogs = true })=>{
|
|
144
161
|
const resolvedContainers = !containers || containers === 'infer' ? inferContainers() : containers;
|
|
145
|
-
//
|
|
162
|
+
// The catalogs flag is written explicitly (even when true) so the workspace
|
|
163
|
+
// records its dependency-management choice.
|
|
146
164
|
await ensureAwsNxPluginConfig(tree);
|
|
147
165
|
await updateAwsNxPluginConfig(tree, {
|
|
148
166
|
iac: {
|
|
@@ -150,6 +168,9 @@ export const PNPM_BUILT_DEPENDENCIES = [
|
|
|
150
168
|
},
|
|
151
169
|
containers: {
|
|
152
170
|
engine: resolvedContainers
|
|
171
|
+
},
|
|
172
|
+
packageManager: {
|
|
173
|
+
catalogs
|
|
153
174
|
}
|
|
154
175
|
});
|
|
155
176
|
// Set up the TypeScript plugin, base tsconfig, formatter etc. `@nx/js`
|
|
@@ -161,7 +182,7 @@ export const PNPM_BUILT_DEPENDENCIES = [
|
|
|
161
182
|
});
|
|
162
183
|
ensureBaseTsConfig(tree);
|
|
163
184
|
ensureRootTsConfig(tree);
|
|
164
|
-
setUpWorkspaces(tree);
|
|
185
|
+
setUpWorkspaces(tree, catalogs);
|
|
165
186
|
const nxJson = readNxJson(tree);
|
|
166
187
|
updateNxJson(tree, {
|
|
167
188
|
...nxJson,
|
|
@@ -229,7 +250,7 @@ export const PNPM_BUILT_DEPENDENCIES = [
|
|
|
229
250
|
});
|
|
230
251
|
// Write biome.json for formatting and linting
|
|
231
252
|
if (!tree.exists('biome.json')) {
|
|
232
|
-
tree.write('biome.json', JSON.stringify(
|
|
253
|
+
tree.write('biome.json', JSON.stringify(getDefaultBiomeConfig(tree), null, 2));
|
|
233
254
|
}
|
|
234
255
|
generateFiles(tree, joinPathFragments(import.meta.dirname, '..', 'preset', 'files'), '.', {
|
|
235
256
|
projectName: getNpmScope(tree),
|
package/src/utils/init.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/init.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n addDependenciesToPackageJson,\n detectPackageManager,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readNxJson,\n type Tree,\n updateJson,\n updateNxJson,\n} from '@nx/devkit';\nimport { initGenerator } from '@nx/js';\nimport { readFileSync } from 'fs';\nimport yaml from 'js-yaml';\nimport { readModulePackageJson } from 'nx/src/utils/package-json';\nimport GeneratorsJson from '../../generators.json' with { type: 'json' };\nimport { SYNC_GENERATOR_NAME as TS_SYNC_GENERATOR_NAME } from '../ts/sync/generator';\nimport { BASE_TSCONFIG_COMPILER_OPTIONS } from './base-tsconfig';\nimport {\n ensureAwsNxPluginConfig,\n updateAwsNxPluginConfig,\n} from './config/utils';\nimport { type Containers, inferContainers } from './containers';\nimport { DEFAULT_BIOME_CONFIG } from './format';\nimport type { Iac } from './iac';\nimport { configureMcpServers } from './mcp';\nimport { getNpmScope } from './npm-scope';\nimport { mergeTargetDefault } from './nx';\nimport { getPackageManagerDisplayCommands } from './pkg-manager';\nimport { withVersions } from './versions';\n\nconst WORKSPACES = ['packages/*'];\nconst NX_TYPESCRIPT_SYNC_GENERATOR = '@nx/js:typescript-sync';\n\n// Built dependencies whose install scripts the generated workspace trusts.\n// `onlyBuiltDependencies` is the pnpm 10 key (silently ignored by pnpm 11);\n// pnpm 11 reads `allowBuilds` instead. Any dep NOT in this allowlist will\n// have its install scripts skipped with a warning — matching pnpm 10's\n// default behaviour. The user can opt-in later via `pnpm approve-builds`.\nexport const PNPM_BUILT_DEPENDENCIES = ['@swc/core', 'esbuild', 'nx', 'sharp'];\n\n/**\n * Options controlling how the workspace is initialised. These mirror the\n * preset schema so a workspace created via the preset and one initialised via\n * the `init` generator end up in the same shape.\n */\nexport interface ApplyWorkspaceInitOptions {\n /** The IaC provider to record in the plugin config. */\n readonly iac: Iac;\n /**\n * The container engine to record. `undefined`/`'infer'` picks docker when\n * installed, else finch.\n */\n readonly containers?: Containers | 'infer';\n /** Whether to configure MCP servers for coding agents. Defaults to true. */\n readonly mcp?: boolean;\n /**\n * How to treat the generated workspace README. The preset owns the README of\n * a greenfield workspace (`Overwrite`); the `init` generator must not clobber\n * an existing workspace's README (`KeepExisting`, the default).\n */\n readonly readmeOverwriteStrategy?: OverwriteStrategy;\n /**\n * Whether to overwrite root package.json scripts that already exist. The\n * preset owns a greenfield workspace's scripts (`true`); the `init`\n * generator must not clobber an existing workspace's scripts (`false`,\n * the default) — it only adds the convenience scripts that are absent.\n */\n readonly overwriteScripts?: boolean;\n}\n\n/**\n * Add or repair the pnpm `allowBuilds` / `onlyBuiltDependencies` allowlist for\n * the workspace's `packages` globs, without clobbering any packages the user\n * has already declared.\n *\n * A workspace not created by the preset commonly has either no\n * `pnpm-workspace.yaml`, one missing the `packages` globs, or one carrying the\n * broken `set this to true or false` placeholder pnpm writes when it skips a\n * build script. This makes the file self-consistent so the first generator's\n * install doesn't fail with `ERR_PNPM_IGNORED_BUILDS`.\n */\nconst setUpPnpmWorkspace = (tree: Tree) => {\n const existing = tree.exists('pnpm-workspace.yaml')\n ? ((yaml.load(tree.read('pnpm-workspace.yaml', 'utf-8') ?? '') as Record<\n string,\n unknown\n >) ?? {})\n : {};\n\n // Preserve any packages globs the user already has, ensuring ours are present.\n const packages = Array.from(\n new Set([...((existing.packages as string[]) ?? []), ...WORKSPACES]),\n );\n\n const allowBuilds = {\n ...(typeof existing.allowBuilds === 'object' && existing.allowBuilds\n ? (existing.allowBuilds as Record<string, unknown>)\n : {}),\n // Overwrite any non-boolean (e.g. the \"set this to true or false\"\n // placeholder) with an explicit true for the deps we trust.\n ...Object.fromEntries(PNPM_BUILT_DEPENDENCIES.map((dep) => [dep, true])),\n };\n\n tree.write(\n 'pnpm-workspace.yaml',\n yaml.dump(\n {\n ...existing,\n packages,\n allowBuilds,\n onlyBuiltDependencies: PNPM_BUILT_DEPENDENCIES,\n },\n { quotingType: \"'\" },\n ),\n );\n};\n\n/**\n * Configure the workspace's package manager for a monorepo layout.\n *\n * pnpm workspaces are declared in `pnpm-workspace.yaml`; every other package\n * manager reads the `workspaces` field of the root `package.json`.\n */\nconst setUpWorkspaces = (tree: Tree) => {\n if (detectPackageManager() === 'pnpm') {\n setUpPnpmWorkspace(tree);\n } else {\n updateJson(tree, 'package.json', (json) => ({\n ...json,\n workspaces: Array.from(\n new Set([...(json.workspaces ?? []), ...WORKSPACES]),\n ),\n }));\n }\n};\n\n/**\n * Ensure the workspace has a `tsconfig.base.json`.\n *\n * `@nx/js` `initGenerator` (with `addTsPlugin`) normally creates this, but it\n * short-circuits when the workspace already has a root `tsconfig.json` — in\n * which case no base file is written and the next project generator fails with\n * `Cannot find tsconfig.base.json`. So we create a compatible one when it's\n * absent. An existing base is left untouched: the user may have tuned it, and\n * rewriting shared compiler options can break other projects (see the\n * \"add to an existing workspace\" guide).\n */\nconst ensureBaseTsConfig = (tree: Tree) => {\n if (tree.exists('tsconfig.base.json')) {\n return;\n }\n tree.write(\n 'tsconfig.base.json',\n JSON.stringify(\n {\n compilerOptions: {\n ...BASE_TSCONFIG_COMPILER_OPTIONS,\n customConditions: [getNpmScope(tree)],\n },\n },\n null,\n 2,\n ),\n );\n};\n\n/**\n * Ensure the workspace has a root `tsconfig.json`.\n *\n * Nx's `@nx/js:typescript-sync` generator hard-fails with\n * `Missing root \"tsconfig.json\"` when it's absent. The plugin's TypeScript\n * projects reference each other via this file, so we guarantee a minimal one\n * exists (sync populates its `references`).\n */\nconst ensureRootTsConfig = (tree: Tree) => {\n if (tree.exists('tsconfig.json')) {\n return;\n }\n tree.write(\n 'tsconfig.json',\n JSON.stringify(\n {\n extends: './tsconfig.base.json',\n files: [],\n references: [],\n },\n null,\n 2,\n ),\n );\n};\n\n/**\n * Transform an Nx workspace into one ready to run `@aws/nx-plugin` generators.\n *\n * This is the deterministic core shared by the workspace preset and the `init`\n * generator. It is safe to re-run: every step is idempotent (config merges,\n * keyed nx.json / package.json entries, create-if-missing files), so running\n * it against an already-initialised workspace is a no-op.\n *\n * It preserves the workspace's module format: the root package.json `type`\n * field is owned by the preset (written from its `--module` option) and left\n * untouched here. It does NOT rewrite an existing `tsconfig.base.json`'s\n * compiler options, migrate a workspace's package manager, or restructure\n * existing projects — those are decisions for the user (see the \"add to an\n * existing workspace\" guide).\n */\nexport const applyWorkspaceInit = async (\n tree: Tree,\n {\n iac,\n containers,\n mcp,\n readmeOverwriteStrategy = OverwriteStrategy.KeepExisting,\n overwriteScripts = false,\n }: ApplyWorkspaceInitOptions,\n) => {\n const resolvedContainers =\n !containers || containers === 'infer' ? inferContainers() : containers;\n\n // Write IaC provider and container engine to plugin config\n await ensureAwsNxPluginConfig(tree);\n await updateAwsNxPluginConfig(tree, {\n iac: { provider: iac },\n containers: { engine: resolvedContainers },\n });\n\n // Set up the TypeScript plugin, base tsconfig, formatter etc. `@nx/js`\n // creates `tsconfig.base.json` when absent, but skips it when a root\n // `tsconfig.json` already exists — so we ensure both explicitly below.\n await initGenerator(tree, {\n formatter: 'none',\n addTsPlugin: true,\n });\n\n ensureBaseTsConfig(tree);\n ensureRootTsConfig(tree);\n\n setUpWorkspaces(tree);\n\n const nxJson = readNxJson(tree);\n updateNxJson(tree, {\n ...nxJson,\n // Preserve an explicit analytics choice in an existing workspace.\n analytics: (nxJson as { analytics?: boolean }).analytics ?? false,\n targetDefaults: {\n ...nxJson.targetDefaults,\n compile: mergeTargetDefault(nxJson.targetDefaults?.compile, (base) => ({\n ...base,\n syncGenerators: [\n ...(base.syncGenerators ?? []).filter(\n (g) =>\n ![TS_SYNC_GENERATOR_NAME, NX_TYPESCRIPT_SYNC_GENERATOR].includes(\n g,\n ),\n ),\n NX_TYPESCRIPT_SYNC_GENERATOR,\n TS_SYNC_GENERATOR_NAME,\n ],\n })),\n },\n });\n\n const CONVENIENCE_SCRIPTS = {\n dev: 'nx run-many --target dev',\n build: 'nx run-many --target build',\n lint: 'nx run-many --target lint --configuration=fix',\n test: 'nx run-many --target test --all',\n // Trivy container image scanning is not part of `build` (its result\n // depends on the ever-changing vulnerability database); run it explicitly,\n // e.g. in CI.\n trivy: 'nx run-many --target trivy --all',\n 'build:skip-lint': 'nx run-many --target build --configuration=skip-lint',\n 'build:all': 'nx run-many --target build --all',\n 'affected:all': 'nx affected --target build',\n };\n updateJson(tree, 'package.json', (packageJson) => ({\n ...packageJson,\n // The root `type` field is owned by the preset (written explicitly from\n // its `--module` option). `init` preserves an existing workspace's field\n // as-is: an ESM workspace already carries `type: \"module\"` (that is how\n // the format is inferred), and introducing a `type` into a CommonJS\n // workspace that lacks one changes behaviour for frameworks that parse it\n // (e.g. Next.js starts treating the app's ESM source as CJS).\n scripts: overwriteScripts\n ? { ...packageJson.scripts, ...CONVENIENCE_SCRIPTS }\n : { ...CONVENIENCE_SCRIPTS, ...packageJson.scripts },\n }));\n\n // Pin the workspace's `nx` to the version the plugin's @nx/* packages are\n // built against. A mismatched workspace nx (even a patch apart) hoists a\n // second nested nx under @nx/js, and the two instances deadlock `nx sync`.\n // `@nx/js` must be a root dependency for the `@nx/js:typescript-sync`\n // generator registered in nx.json to resolve (npm doesn't hoist the\n // plugin's own copy reliably).\n const nxVersion = readModulePackageJson('@nx/js').packageJson.version;\n addDependenciesToPackageJson(\n tree,\n {},\n {\n nx: nxVersion,\n '@nx/js': nxVersion,\n '@nx/workspace': nxVersion,\n ...withVersions(['typescript', '@biomejs/biome']),\n },\n );\n\n // Write biome.json for formatting and linting\n if (!tree.exists('biome.json')) {\n tree.write('biome.json', JSON.stringify(DEFAULT_BIOME_CONFIG, null, 2));\n }\n\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, '..', 'preset', 'files'),\n '.',\n {\n projectName: getNpmScope(tree),\n generators: Object.entries(GeneratorsJson.generators)\n .filter(([_, v]) => !v['hidden'])\n .map(([k, v]) => ({ name: k, description: v.description })),\n ...(() => {\n const cmds = getPackageManagerDisplayCommands();\n return {\n pkgMgrCmd: cmds.exec,\n buildCmd: `${cmds.run} build`,\n lintCmd: `${cmds.run} lint`,\n };\n })(),\n },\n {\n overwriteStrategy: readmeOverwriteStrategy,\n },\n );\n\n if (mcp !== false) {\n configureMcpServers(tree);\n }\n};\n"],"names":["addDependenciesToPackageJson","detectPackageManager","generateFiles","joinPathFragments","OverwriteStrategy","readNxJson","updateJson","updateNxJson","initGenerator","yaml","readModulePackageJson","GeneratorsJson","type","SYNC_GENERATOR_NAME","TS_SYNC_GENERATOR_NAME","BASE_TSCONFIG_COMPILER_OPTIONS","ensureAwsNxPluginConfig","updateAwsNxPluginConfig","inferContainers","DEFAULT_BIOME_CONFIG","configureMcpServers","getNpmScope","mergeTargetDefault","getPackageManagerDisplayCommands","withVersions","WORKSPACES","NX_TYPESCRIPT_SYNC_GENERATOR","PNPM_BUILT_DEPENDENCIES","setUpPnpmWorkspace","tree","existing","exists","load","read","packages","Array","from","Set","allowBuilds","Object","fromEntries","map","dep","write","dump","onlyBuiltDependencies","quotingType","setUpWorkspaces","json","workspaces","ensureBaseTsConfig","JSON","stringify","compilerOptions","customConditions","ensureRootTsConfig","extends","files","references","applyWorkspaceInit","iac","containers","mcp","readmeOverwriteStrategy","KeepExisting","overwriteScripts","resolvedContainers","provider","engine","formatter","addTsPlugin","nxJson","analytics","targetDefaults","compile","base","syncGenerators","filter","g","includes","CONVENIENCE_SCRIPTS","dev","build","lint","test","trivy","packageJson","scripts","nxVersion","version","nx","dirname","projectName","generators","entries","_","v","k","name","description","cmds","pkgMgrCmd","exec","buildCmd","run","lintCmd","overwriteStrategy"],"mappings":"AAAA;;;CAGC,GACD,SACEA,4BAA4B,EAC5BC,oBAAoB,EACpBC,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EACjBC,UAAU,EAEVC,UAAU,EACVC,YAAY,QACP,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yEAAyE;IACzE,2EAA2E;IAC3E,sEAAsE;IACtE,oEAAoE;IACpE,+BAA+B;IAC/B,MAAMC,YAAY9E,sBAAsB,UAAU4E,WAAW,CAACG,OAAO;IACrEzF,6BACE6B,MACA,CAAC,GACD;QACE6D,IAAIF;QACJ,UAAUA;QACV,iBAAiBA;QACjB,GAAGhE,aAAa;YAAC;YAAc;SAAiB,CAAC;IACnD;IAGF,8CAA8C;IAC9C,IAAI,CAACK,KAAKE,MAAM,CAAC,eAAe;QAC9BF,KAAKc,KAAK,CAAC,cAAcQ,KAAKC,SAAS,CAACjC,sBAAsB,MAAM;IACtE;IAEAjB,cACE2B,MACA1B,kBAAkB,YAAYwF,OAAO,EAAE,MAAM,UAAU,UACvD,KACA;QACEC,aAAavE,YAAYQ;QACzBgE,YAAYtD,OAAOuD,OAAO,CAACnF,eAAekF,UAAU,EACjDhB,MAAM,CAAC,CAAC,CAACkB,GAAGC,EAAE,GAAK,CAACA,CAAC,CAAC,SAAS,EAC/BvD,GAAG,CAAC,CAAC,CAACwD,GAAGD,EAAE,GAAM,CAAA;gBAAEE,MAAMD;gBAAGE,aAAaH,EAAEG,WAAW;YAAC,CAAA;QAC1D,GAAG,AAAC,CAAA;YACF,MAAMC,OAAO7E;YACb,OAAO;gBACL8E,WAAWD,KAAKE,IAAI;gBACpBC,UAAU,GAAGH,KAAKI,GAAG,CAAC,MAAM,CAAC;gBAC7BC,SAAS,GAAGL,KAAKI,GAAG,CAAC,KAAK,CAAC;YAC7B;QACF,CAAA,GAAI;IACN,GACA;QACEE,mBAAmB3C;IACrB;IAGF,IAAID,QAAQ,OAAO;QACjB1C,oBAAoBS;IACtB;AACF,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/init.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 readNxJson,\n type Tree,\n updateJson,\n updateNxJson,\n} from '@nx/devkit';\nimport { initGenerator } from '@nx/js';\nimport { readFileSync } from 'fs';\nimport yaml from 'js-yaml';\nimport { readModulePackageJson } from 'nx/src/utils/package-json';\nimport GeneratorsJson from '../../generators.json' with { type: 'json' };\nimport { SYNC_GENERATOR_NAME as TS_SYNC_GENERATOR_NAME } from '../ts/sync/generator';\nimport { BASE_TSCONFIG_COMPILER_OPTIONS } from './base-tsconfig';\nimport {\n ensureAwsNxPluginConfig,\n updateAwsNxPluginConfig,\n} from './config/utils';\nimport { type Containers, inferContainers } from './containers';\nimport {\n addDependenciesToPackageJson,\n detectWorkspacePackageManager,\n} from './dependencies';\nimport { getDefaultBiomeConfig } from './format';\nimport type { Iac } from './iac';\nimport { configureMcpServers } from './mcp';\nimport { getNpmScope } from './npm-scope';\nimport { mergeTargetDefault } from './nx';\nimport { getPackageManagerDisplayCommands } from './pkg-manager';\nimport { workspaceGlobs } from './project-package-json';\nimport { withVersions } from './versions';\n\nconst WORKSPACES = ['packages/*'];\nconst NX_TYPESCRIPT_SYNC_GENERATOR = '@nx/js:typescript-sync';\n\n// Built dependencies whose install scripts the generated workspace trusts.\n// `onlyBuiltDependencies` is the pnpm 10 key (silently ignored by pnpm 11);\n// pnpm 11 reads `allowBuilds` instead. Any dep NOT in this allowlist will\n// have its install scripts skipped with a warning — matching pnpm 10's\n// default behaviour. The user can opt-in later via `pnpm approve-builds`.\nexport const PNPM_BUILT_DEPENDENCIES = ['@swc/core', 'esbuild', 'nx', 'sharp'];\n\n/**\n * Options controlling how the workspace is initialised. These mirror the\n * preset schema so a workspace created via the preset and one initialised via\n * the `init` generator end up in the same shape.\n */\nexport interface ApplyWorkspaceInitOptions {\n /** The IaC provider to record in the plugin config. */\n readonly iac: Iac;\n /**\n * The container engine to record. `undefined`/`'infer'` picks docker when\n * installed, else finch.\n */\n readonly containers?: Containers | 'infer';\n /** Whether to configure MCP servers for coding agents. Defaults to true. */\n readonly mcp?: boolean;\n /**\n * How to treat the generated workspace README. The preset owns the README of\n * a greenfield workspace (`Overwrite`); the `init` generator must not clobber\n * an existing workspace's README (`KeepExisting`, the default).\n */\n readonly readmeOverwriteStrategy?: OverwriteStrategy;\n /**\n * Whether to overwrite root package.json scripts that already exist. The\n * preset owns a greenfield workspace's scripts (`true`); the `init`\n * generator must not clobber an existing workspace's scripts (`false`,\n * the default) — it only adds the convenience scripts that are absent.\n */\n readonly overwriteScripts?: boolean;\n /**\n * Whether generators use the package manager's dependency catalog. On pnpm\n * this also sets `catalogMode: strict` so `pnpm add` records new deps in the\n * catalog. Defaults to true.\n */\n readonly catalogs?: boolean;\n}\n\n/**\n * Add or repair the pnpm `allowBuilds` / `onlyBuiltDependencies` allowlist for\n * the workspace's `packages` globs, without clobbering any packages the user\n * has already declared.\n *\n * A workspace not created by the preset commonly has either no\n * `pnpm-workspace.yaml`, one missing the `packages` globs, or one carrying the\n * broken `set this to true or false` placeholder pnpm writes when it skips a\n * build script. This makes the file self-consistent so the first generator's\n * install doesn't fail with `ERR_PNPM_IGNORED_BUILDS`.\n */\nconst setUpPnpmWorkspace = (tree: Tree, catalogs: boolean) => {\n const existing = tree.exists('pnpm-workspace.yaml')\n ? ((yaml.load(tree.read('pnpm-workspace.yaml', 'utf-8') ?? '') as Record<\n string,\n unknown\n >) ?? {})\n : {};\n\n // Preserve any packages globs the user already has, ensuring ours are present.\n const packages = Array.from(\n new Set([...((existing.packages as string[]) ?? []), ...WORKSPACES]),\n );\n\n const allowBuilds = {\n ...(typeof existing.allowBuilds === 'object' && existing.allowBuilds\n ? (existing.allowBuilds as Record<string, unknown>)\n : {}),\n // Overwrite any non-boolean (e.g. the \"set this to true or false\"\n // placeholder) with an explicit true for the deps we trust.\n ...Object.fromEntries(PNPM_BUILT_DEPENDENCIES.map((dep) => [dep, true])),\n };\n\n // `strict` makes `pnpm add` record new deps in the catalog; it only gates\n // that flow, so pre-declared direct ranges (e.g. tslib) still install.\n // Preserve an explicit user choice.\n const catalogMode = catalogs\n ? (existing.catalogMode ?? 'strict')\n : existing.catalogMode;\n\n tree.write(\n 'pnpm-workspace.yaml',\n yaml.dump(\n {\n ...existing,\n packages,\n allowBuilds,\n onlyBuiltDependencies: PNPM_BUILT_DEPENDENCIES,\n ...(catalogMode ? { catalogMode } : {}),\n },\n { quotingType: \"'\" },\n ),\n );\n};\n\n/**\n * Configure the workspace's package manager for a monorepo layout.\n *\n * pnpm workspaces are declared in `pnpm-workspace.yaml`; every other package\n * manager reads the `workspaces` field of the root `package.json`.\n */\nconst setUpWorkspaces = (tree: Tree, catalogs: boolean) => {\n if (detectWorkspacePackageManager(tree) === 'pnpm') {\n setUpPnpmWorkspace(tree, catalogs);\n } else {\n updateJson(tree, 'package.json', (json) => {\n // The `workspaces` field may be the object form ({ \"packages\": [...] })\n // accepted by yarn and bun — extend the globs while preserving the form.\n const globs = Array.from(\n new Set([...workspaceGlobs(json.workspaces), ...WORKSPACES]),\n );\n return {\n ...json,\n workspaces:\n json.workspaces !== undefined && !Array.isArray(json.workspaces)\n ? { ...json.workspaces, packages: globs }\n : globs,\n };\n });\n }\n};\n\n/**\n * Ensure the workspace has a `tsconfig.base.json`.\n *\n * `@nx/js` `initGenerator` (with `addTsPlugin`) normally creates this, but it\n * short-circuits when the workspace already has a root `tsconfig.json` — in\n * which case no base file is written and the next project generator fails with\n * `Cannot find tsconfig.base.json`. So we create a compatible one when it's\n * absent. An existing base is left untouched: the user may have tuned it, and\n * rewriting shared compiler options can break other projects (see the\n * \"add to an existing workspace\" guide).\n */\nconst ensureBaseTsConfig = (tree: Tree) => {\n if (tree.exists('tsconfig.base.json')) {\n return;\n }\n tree.write(\n 'tsconfig.base.json',\n JSON.stringify(\n {\n compilerOptions: {\n ...BASE_TSCONFIG_COMPILER_OPTIONS,\n customConditions: [getNpmScope(tree)],\n },\n },\n null,\n 2,\n ),\n );\n};\n\n/**\n * Ensure the workspace has a root `tsconfig.json`.\n *\n * Nx's `@nx/js:typescript-sync` generator hard-fails with\n * `Missing root \"tsconfig.json\"` when it's absent. The plugin's TypeScript\n * projects reference each other via this file, so we guarantee a minimal one\n * exists (sync populates its `references`).\n */\nconst ensureRootTsConfig = (tree: Tree) => {\n if (tree.exists('tsconfig.json')) {\n return;\n }\n tree.write(\n 'tsconfig.json',\n JSON.stringify(\n {\n extends: './tsconfig.base.json',\n files: [],\n references: [],\n },\n null,\n 2,\n ),\n );\n};\n\n/**\n * Transform an Nx workspace into one ready to run `@aws/nx-plugin` generators.\n *\n * This is the deterministic core shared by the workspace preset and the `init`\n * generator. It is safe to re-run: every step is idempotent (config merges,\n * keyed nx.json / package.json entries, create-if-missing files), so running\n * it against an already-initialised workspace is a no-op.\n *\n * It preserves the workspace's module format: the root package.json `type`\n * field is owned by the preset (written from its `--module` option) and left\n * untouched here. It does NOT rewrite an existing `tsconfig.base.json`'s\n * compiler options, migrate a workspace's package manager, or restructure\n * existing projects — those are decisions for the user (see the \"add to an\n * existing workspace\" guide).\n */\nexport const applyWorkspaceInit = async (\n tree: Tree,\n {\n iac,\n containers,\n mcp,\n readmeOverwriteStrategy = OverwriteStrategy.KeepExisting,\n overwriteScripts = false,\n catalogs = true,\n }: ApplyWorkspaceInitOptions,\n) => {\n const resolvedContainers =\n !containers || containers === 'infer' ? inferContainers() : containers;\n\n // The catalogs flag is written explicitly (even when true) so the workspace\n // records its dependency-management choice.\n await ensureAwsNxPluginConfig(tree);\n await updateAwsNxPluginConfig(tree, {\n iac: { provider: iac },\n containers: { engine: resolvedContainers },\n packageManager: { catalogs },\n });\n\n // Set up the TypeScript plugin, base tsconfig, formatter etc. `@nx/js`\n // creates `tsconfig.base.json` when absent, but skips it when a root\n // `tsconfig.json` already exists — so we ensure both explicitly below.\n await initGenerator(tree, {\n formatter: 'none',\n addTsPlugin: true,\n });\n\n ensureBaseTsConfig(tree);\n ensureRootTsConfig(tree);\n\n setUpWorkspaces(tree, catalogs);\n\n const nxJson = readNxJson(tree);\n updateNxJson(tree, {\n ...nxJson,\n // Preserve an explicit analytics choice in an existing workspace.\n analytics: (nxJson as { analytics?: boolean }).analytics ?? false,\n targetDefaults: {\n ...nxJson.targetDefaults,\n compile: mergeTargetDefault(nxJson.targetDefaults?.compile, (base) => ({\n ...base,\n syncGenerators: [\n ...(base.syncGenerators ?? []).filter(\n (g) =>\n ![TS_SYNC_GENERATOR_NAME, NX_TYPESCRIPT_SYNC_GENERATOR].includes(\n g,\n ),\n ),\n NX_TYPESCRIPT_SYNC_GENERATOR,\n TS_SYNC_GENERATOR_NAME,\n ],\n })),\n },\n });\n\n const CONVENIENCE_SCRIPTS = {\n dev: 'nx run-many --target dev',\n build: 'nx run-many --target build',\n lint: 'nx run-many --target lint --configuration=fix',\n test: 'nx run-many --target test --all',\n // Trivy container image scanning is not part of `build` (its result\n // depends on the ever-changing vulnerability database); run it explicitly,\n // e.g. in CI.\n trivy: 'nx run-many --target trivy --all',\n 'build:skip-lint': 'nx run-many --target build --configuration=skip-lint',\n 'build:all': 'nx run-many --target build --all',\n 'affected:all': 'nx affected --target build',\n };\n updateJson(tree, 'package.json', (packageJson) => ({\n ...packageJson,\n // The root `type` field is owned by the preset (written explicitly from\n // its `--module` option). `init` preserves an existing workspace's field\n // as-is: an ESM workspace already carries `type: \"module\"` (that is how\n // the format is inferred), and introducing a `type` into a CommonJS\n // workspace that lacks one changes behaviour for frameworks that parse it\n // (e.g. Next.js starts treating the app's ESM source as CJS).\n scripts: overwriteScripts\n ? { ...packageJson.scripts, ...CONVENIENCE_SCRIPTS }\n : { ...CONVENIENCE_SCRIPTS, ...packageJson.scripts },\n }));\n\n // Pin the workspace's `nx` to the version the plugin's @nx/* packages are\n // built against. A mismatched workspace nx (even a patch apart) hoists a\n // second nested nx under @nx/js, and the two instances deadlock `nx sync`.\n // `@nx/js` must be a root dependency for the `@nx/js:typescript-sync`\n // generator registered in nx.json to resolve (npm doesn't hoist the\n // plugin's own copy reliably).\n const nxVersion = readModulePackageJson('@nx/js').packageJson.version;\n addDependenciesToPackageJson(\n tree,\n {},\n {\n nx: nxVersion,\n '@nx/js': nxVersion,\n '@nx/workspace': nxVersion,\n ...withVersions(['typescript', '@biomejs/biome']),\n },\n );\n\n // Write biome.json for formatting and linting\n if (!tree.exists('biome.json')) {\n tree.write(\n 'biome.json',\n JSON.stringify(getDefaultBiomeConfig(tree), null, 2),\n );\n }\n\n generateFiles(\n tree, // the virtual file system\n joinPathFragments(import.meta.dirname, '..', 'preset', 'files'),\n '.',\n {\n projectName: getNpmScope(tree),\n generators: Object.entries(GeneratorsJson.generators)\n .filter(([_, v]) => !v['hidden'])\n .map(([k, v]) => ({ name: k, description: v.description })),\n ...(() => {\n const cmds = getPackageManagerDisplayCommands();\n return {\n pkgMgrCmd: cmds.exec,\n buildCmd: `${cmds.run} build`,\n lintCmd: `${cmds.run} lint`,\n };\n })(),\n },\n {\n overwriteStrategy: readmeOverwriteStrategy,\n },\n );\n\n if (mcp !== false) {\n configureMcpServers(tree);\n }\n};\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","readNxJson","updateJson","updateNxJson","initGenerator","yaml","readModulePackageJson","GeneratorsJson","type","SYNC_GENERATOR_NAME","TS_SYNC_GENERATOR_NAME","BASE_TSCONFIG_COMPILER_OPTIONS","ensureAwsNxPluginConfig","updateAwsNxPluginConfig","inferContainers","addDependenciesToPackageJson","detectWorkspacePackageManager","getDefaultBiomeConfig","configureMcpServers","getNpmScope","mergeTargetDefault","getPackageManagerDisplayCommands","workspaceGlobs","withVersions","WORKSPACES","NX_TYPESCRIPT_SYNC_GENERATOR","PNPM_BUILT_DEPENDENCIES","setUpPnpmWorkspace","tree","catalogs","existing","exists","load","read","packages","Array","from","Set","allowBuilds","Object","fromEntries","map","dep","catalogMode","write","dump","onlyBuiltDependencies","quotingType","setUpWorkspaces","json","globs","workspaces","undefined","isArray","ensureBaseTsConfig","JSON","stringify","compilerOptions","customConditions","ensureRootTsConfig","extends","files","references","applyWorkspaceInit","iac","containers","mcp","readmeOverwriteStrategy","KeepExisting","overwriteScripts","resolvedContainers","provider","engine","packageManager","formatter","addTsPlugin","nxJson","analytics","targetDefaults","compile","base","syncGenerators","filter","g","includes","CONVENIENCE_SCRIPTS","dev","build","lint","test","trivy","packageJson","scripts","nxVersion","version","nx","dirname","projectName","generators","entries","_","v","k","name","description","cmds","pkgMgrCmd","exec","buildCmd","run","lintCmd","overwriteStrategy"],"mappings":"AAAA;;;CAGC,GACD,SACEA,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EACjBC,UAAU,EAEVC,UAAU,EACVC,YAAY,QACP,aAAa;AACpB,SAASC,aAAa,QAAQ,SAAS;AAEvC,OAAOC,UAAU,UAAU;AAC3B,SAASC,qBAAqB,QAAQ,4BAA4B;AAClE,OAAOC,oBAAoB,6BAA6B;IAAEC,MAAM;AAAO,EAAE;AACzE,SAASC,uBAAuBC,sBAAsB,QAAQ,0BAAuB;AACrF,SAASC,8BAA8B,QAAQ,qBAAkB;AACjE,SACEC,uBAAuB,EACvBC,uBAAuB,QAClB,oBAAiB;AACxB,SAA0BC,eAAe,QAAQ,kBAAe;AAChE,SACEC,4BAA4B,EAC5BC,6BAA6B,QACxB,oBAAiB;AACxB,SAASC,qBAAqB,QAAQ,cAAW;AAEjD,SAASC,mBAAmB,QAAQ,WAAQ;AAC5C,SAASC,WAAW,QAAQ,iBAAc;AAC1C,SAASC,kBAAkB,QAAQ,UAAO;AAC1C,SAASC,gCAAgC,QAAQ,mBAAgB;AACjE,SAASC,cAAc,QAAQ,4BAAyB;AACxD,SAASC,YAAY,QAAQ,gBAAa;AAE1C,MAAMC,aAAa;IAAC;CAAa;AACjC,MAAMC,+BAA+B;AAErC,2EAA2E;AAC3E,4EAA4E;AAC5E,0EAA0E;AAC1E,uEAAuE;AACvE,0EAA0E;AAC1E,OAAO,MAAMC,0BAA0B;IAAC;IAAa;IAAW;IAAM;CAAQ,CAAC;AAsC/E;;;;;;;;;;CAUC,GACD,MAAMC,qBAAqB,CAACC,MAAYC;IACtC,MAAMC,WAAWF,KA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AsBW,OAAO,MAAM;IAEtD;IAEA9B,cACE8B,MACA7B,kBAAkB,YAAYiG,OAAO,EAAE,MAAM,UAAU,UACvD,KACA;QACEC,aAAa9E,YAAYS;QACzBsE,YAAY3D,OAAO4D,OAAO,CAAC5F,eAAe2F,UAAU,EACjDhB,MAAM,CAAC,CAAC,CAACkB,GAAGC,EAAE,GAAK,CAACA,CAAC,CAAC,SAAS,EAC/B5D,GAAG,CAAC,CAAC,CAAC6D,GAAGD,EAAE,GAAM,CAAA;gBAAEE,MAAMD;gBAAGE,aAAaH,EAAEG,WAAW;YAAC,CAAA;QAC1D,GAAG,AAAC,CAAA;YACF,MAAMC,OAAOpF;YACb,OAAO;gBACLqF,WAAWD,KAAKE,IAAI;gBACpBC,UAAU,GAAGH,KAAKI,GAAG,CAAC,MAAM,CAAC;gBAC7BC,SAAS,GAAGL,KAAKI,GAAG,CAAC,KAAK,CAAC;YAC7B;QACF,CAAA,GAAI;IACN,GACA;QACEE,mBAAmB5C;IACrB;IAGF,IAAID,QAAQ,OAAO;QACjBhD,oBAAoBU;IACtB;AACF,EAAE"}
|
package/src/utils/install.js
CHANGED
|
@@ -46,7 +46,9 @@ import { Logger, UVProvider } from "./nxlv-python.js";
|
|
|
46
46
|
return;
|
|
47
47
|
}
|
|
48
48
|
if (languages.includes('typescript')) {
|
|
49
|
-
|
|
49
|
+
// Force the install: devkit's default only installs when the root
|
|
50
|
+
// package.json changed, but deps land in per-project manifests.
|
|
51
|
+
installPackagesTask(tree, true);
|
|
50
52
|
}
|
|
51
53
|
if (languages.includes('python')) {
|
|
52
54
|
await new UVProvider(tree.root, new Logger(), tree).install();
|
package/src/utils/install.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/install.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { installPackagesTask, type Tree } from '@nx/devkit';\nimport { Logger, UVProvider } from './nxlv-python';\nimport type { ITsDepVersion } from './versions';\n\n/**\n * Languages whose dependencies a generator may install.\n */\nexport type InstallLanguage = 'typescript' | 'python';\n\nexport interface InstallDependenciesOptions {\n /** Languages to install dependencies for. */\n languages: InstallLanguage[];\n /**\n * Packages that must resolve from the workspace after this generator, because\n * a config file it writes (e.g. `vite.config.mts`) imports them and Nx loads\n * that config when computing the project graph. When the caller prefers to\n * defer installing, we honour that only if these already resolve.\n *\n * The per-language graph deps in `LANGUAGE_GRAPH_DEPS` are always included, so\n * callers only list packages beyond those.\n */\n ensureResolvable?: ITsDepVersion[];\n}\n\n/**\n * Packages each language always needs resolvable for Nx to compute the project\n * graph, so a deferred install still runs whenever it would otherwise break.\n */\nconst LANGUAGE_GRAPH_DEPS: Record<InstallLanguage, string[]> = {\n typescript: ['vitest'], // every TypeScript project has a `vitest.config.mts`\n python: ['@nxlv/python'], // every Python project registers this inference plugin\n};\n\n/**\n * Returns true if every package is linked at `<root>/node_modules/<pkg>`.\n *\n * This is the condition Nx's inferred plugins need when they load a generated\n * config (e.g. `vite.config.mts`) during graph computation: the config's\n * imports resolve from inside the workspace's own `node_modules`. We avoid\n * `require.resolve`, which can succeed via an ancestor `node_modules` even when\n * the package isn't linked here. `existsSync` follows symlinks, so pnpm's store\n * links resolve, and Nx always uses a `node_modules` linker (never PnP).\n */\nconst allResolvable = (root: string, packages: string[]): boolean =>\n packages.every((pkg) => existsSync(join(root, 'node_modules', pkg)));\n\n/**\n * Installs dependencies for the given languages.\n *\n * Call from a generator's returned callback:\n * `return () => installDependencies(tree, options.preferInstallDependencies, { ... })`.\n *\n * `preferInstallDependencies` is a preference: when `false` the install is\n * deferred so a batch installs once at the end — unless an `ensureResolvable`\n * package is missing, in which case it runs anyway so the next `nx` command can\n * still compute the project graph.\n */\nexport const installDependencies = async (\n tree: Tree,\n preferInstallDependencies: boolean | undefined,\n options: InstallDependenciesOptions,\n): Promise<void> => {\n const { languages, ensureResolvable = [] } = options;\n const mustResolve = [\n ...ensureResolvable,\n ...languages.flatMap((language) => LANGUAGE_GRAPH_DEPS[language]),\n ];\n if (\n preferInstallDependencies === false &&\n allResolvable(tree.root, mustResolve)\n ) {\n return;\n }\n if (languages.includes('typescript')) {\n installPackagesTask(tree);\n }\n if (languages.includes('python')) {\n await new UVProvider(tree.root, new Logger(), tree).install();\n }\n};\n"],"names":["existsSync","join","installPackagesTask","Logger","UVProvider","LANGUAGE_GRAPH_DEPS","typescript","python","allResolvable","root","packages","every","pkg","installDependencies","tree","preferInstallDependencies","options","languages","ensureResolvable","mustResolve","flatMap","language","includes","install"],"mappings":"AAAA;;;CAGC,GACD,SAASA,UAAU,QAAQ,UAAU;AACrC,SAASC,IAAI,QAAQ,YAAY;AACjC,SAASC,mBAAmB,QAAmB,aAAa;AAC5D,SAASC,MAAM,EAAEC,UAAU,QAAQ,mBAAgB;AAuBnD;;;CAGC,GACD,MAAMC,sBAAyD;IAC7DC,YAAY;QAAC;KAAS;IACtBC,QAAQ;QAAC;KAAe;AAC1B;AAEA;;;;;;;;;CASC,GACD,MAAMC,gBAAgB,CAACC,MAAcC,WACnCA,SAASC,KAAK,CAAC,CAACC,MAAQZ,WAAWC,KAAKQ,MAAM,gBAAgBG;AAEhE;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,sBAAsB,OACjCC,MACAC,2BACAC;IAEA,MAAM,EAAEC,SAAS,EAAEC,mBAAmB,EAAE,EAAE,GAAGF;IAC7C,MAAMG,cAAc;WACfD;WACAD,UAAUG,OAAO,CAAC,CAACC,WAAahB,mBAAmB,CAACgB,SAAS;KACjE;IACD,IACEN,8BAA8B,SAC9BP,cAAcM,KAAKL,IAAI,EAAEU,cACzB;QACA;IACF;IACA,IAAIF,UAAUK,QAAQ,CAAC,eAAe;
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/install.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { existsSync } from 'node:fs';\nimport { join } from 'node:path';\nimport { installPackagesTask, type Tree } from '@nx/devkit';\nimport { Logger, UVProvider } from './nxlv-python';\nimport type { ITsDepVersion } from './versions';\n\n/**\n * Languages whose dependencies a generator may install.\n */\nexport type InstallLanguage = 'typescript' | 'python';\n\nexport interface InstallDependenciesOptions {\n /** Languages to install dependencies for. */\n languages: InstallLanguage[];\n /**\n * Packages that must resolve from the workspace after this generator, because\n * a config file it writes (e.g. `vite.config.mts`) imports them and Nx loads\n * that config when computing the project graph. When the caller prefers to\n * defer installing, we honour that only if these already resolve.\n *\n * The per-language graph deps in `LANGUAGE_GRAPH_DEPS` are always included, so\n * callers only list packages beyond those.\n */\n ensureResolvable?: ITsDepVersion[];\n}\n\n/**\n * Packages each language always needs resolvable for Nx to compute the project\n * graph, so a deferred install still runs whenever it would otherwise break.\n */\nconst LANGUAGE_GRAPH_DEPS: Record<InstallLanguage, string[]> = {\n typescript: ['vitest'], // every TypeScript project has a `vitest.config.mts`\n python: ['@nxlv/python'], // every Python project registers this inference plugin\n};\n\n/**\n * Returns true if every package is linked at `<root>/node_modules/<pkg>`.\n *\n * This is the condition Nx's inferred plugins need when they load a generated\n * config (e.g. `vite.config.mts`) during graph computation: the config's\n * imports resolve from inside the workspace's own `node_modules`. We avoid\n * `require.resolve`, which can succeed via an ancestor `node_modules` even when\n * the package isn't linked here. `existsSync` follows symlinks, so pnpm's store\n * links resolve, and Nx always uses a `node_modules` linker (never PnP).\n */\nconst allResolvable = (root: string, packages: string[]): boolean =>\n packages.every((pkg) => existsSync(join(root, 'node_modules', pkg)));\n\n/**\n * Installs dependencies for the given languages.\n *\n * Call from a generator's returned callback:\n * `return () => installDependencies(tree, options.preferInstallDependencies, { ... })`.\n *\n * `preferInstallDependencies` is a preference: when `false` the install is\n * deferred so a batch installs once at the end — unless an `ensureResolvable`\n * package is missing, in which case it runs anyway so the next `nx` command can\n * still compute the project graph.\n */\nexport const installDependencies = async (\n tree: Tree,\n preferInstallDependencies: boolean | undefined,\n options: InstallDependenciesOptions,\n): Promise<void> => {\n const { languages, ensureResolvable = [] } = options;\n const mustResolve = [\n ...ensureResolvable,\n ...languages.flatMap((language) => LANGUAGE_GRAPH_DEPS[language]),\n ];\n if (\n preferInstallDependencies === false &&\n allResolvable(tree.root, mustResolve)\n ) {\n return;\n }\n if (languages.includes('typescript')) {\n // Force the install: devkit's default only installs when the root\n // package.json changed, but deps land in per-project manifests.\n installPackagesTask(tree, true);\n }\n if (languages.includes('python')) {\n await new UVProvider(tree.root, new Logger(), tree).install();\n }\n};\n"],"names":["existsSync","join","installPackagesTask","Logger","UVProvider","LANGUAGE_GRAPH_DEPS","typescript","python","allResolvable","root","packages","every","pkg","installDependencies","tree","preferInstallDependencies","options","languages","ensureResolvable","mustResolve","flatMap","language","includes","install"],"mappings":"AAAA;;;CAGC,GACD,SAASA,UAAU,QAAQ,UAAU;AACrC,SAASC,IAAI,QAAQ,YAAY;AACjC,SAASC,mBAAmB,QAAmB,aAAa;AAC5D,SAASC,MAAM,EAAEC,UAAU,QAAQ,mBAAgB;AAuBnD;;;CAGC,GACD,MAAMC,sBAAyD;IAC7DC,YAAY;QAAC;KAAS;IACtBC,QAAQ;QAAC;KAAe;AAC1B;AAEA;;;;;;;;;CASC,GACD,MAAMC,gBAAgB,CAACC,MAAcC,WACnCA,SAASC,KAAK,CAAC,CAACC,MAAQZ,WAAWC,KAAKQ,MAAM,gBAAgBG;AAEhE;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,sBAAsB,OACjCC,MACAC,2BACAC;IAEA,MAAM,EAAEC,SAAS,EAAEC,mBAAmB,EAAE,EAAE,GAAGF;IAC7C,MAAMG,cAAc;WACfD;WACAD,UAAUG,OAAO,CAAC,CAACC,WAAahB,mBAAmB,CAACgB,SAAS;KACjE;IACD,IACEN,8BAA8B,SAC9BP,cAAcM,KAAKL,IAAI,EAAEU,cACzB;QACA;IACF;IACA,IAAIF,UAAUK,QAAQ,CAAC,eAAe;QACpC,kEAAkE;QAClE,gEAAgE;QAChEpB,oBAAoBY,MAAM;IAC5B;IACA,IAAIG,UAAUK,QAAQ,CAAC,WAAW;QAChC,MAAM,IAAIlB,WAAWU,KAAKL,IAAI,EAAE,IAAIN,UAAUW,MAAMS,OAAO;IAC7D;AACF,EAAE"}
|
|
@@ -8,14 +8,11 @@ import { type Tree } from '@nx/devkit';
|
|
|
8
8
|
*/
|
|
9
9
|
export type ModuleFormat = 'esm' | 'cjs';
|
|
10
10
|
/**
|
|
11
|
-
* Whether the workspace
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
* ESM requires an explicit `type: "module"`, matching Node: an absent `type` (or
|
|
17
|
-
* `type: "commonjs"`) means CommonJS. A workspace with no root package.json
|
|
18
|
-
* defaults to ESM.
|
|
11
|
+
* Whether the workspace targets ES modules, read from the tree so shared
|
|
12
|
+
* helpers needn't thread it through call sites. An explicit root `type` wins
|
|
13
|
+
* (`module`/`commonjs`); when absent (e.g. an adopted Nx workspace) infer ESM
|
|
14
|
+
* from any sibling project declaring `type: "module"`, else CJS. No root
|
|
15
|
+
* package.json defaults to ESM.
|
|
19
16
|
*/
|
|
20
17
|
export declare const isEsmWorkspace: (tree: Tree) => boolean;
|
|
21
18
|
/**
|
|
@@ -1,21 +1,38 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
3
|
* SPDX-License-Identifier: Apache-2.0
|
|
4
|
-
*/ import { readJson } from "@nx/devkit";
|
|
4
|
+
*/ import { getProjects, joinPathFragments, readJson } from "@nx/devkit";
|
|
5
5
|
/**
|
|
6
|
-
* Whether the workspace
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
11
|
-
* ESM requires an explicit `type: "module"`, matching Node: an absent `type` (or
|
|
12
|
-
* `type: "commonjs"`) means CommonJS. A workspace with no root package.json
|
|
13
|
-
* defaults to ESM.
|
|
6
|
+
* Whether the workspace targets ES modules, read from the tree so shared
|
|
7
|
+
* helpers needn't thread it through call sites. An explicit root `type` wins
|
|
8
|
+
* (`module`/`commonjs`); when absent (e.g. an adopted Nx workspace) infer ESM
|
|
9
|
+
* from any sibling project declaring `type: "module"`, else CJS. No root
|
|
10
|
+
* package.json defaults to ESM.
|
|
14
11
|
*/ export const isEsmWorkspace = (tree)=>{
|
|
15
|
-
if (tree.exists('package.json')) {
|
|
16
|
-
return
|
|
12
|
+
if (!tree.exists('package.json')) {
|
|
13
|
+
return true;
|
|
17
14
|
}
|
|
18
|
-
|
|
15
|
+
const rootType = readJson(tree, 'package.json').type;
|
|
16
|
+
if (rootType === 'module') {
|
|
17
|
+
return true;
|
|
18
|
+
}
|
|
19
|
+
if (rootType === 'commonjs') {
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
// Root `type` is absent: infer from sibling projects' own manifests.
|
|
23
|
+
return hasEsmProject(tree);
|
|
24
|
+
};
|
|
25
|
+
/** Whether any non-root project declares `type: "module"` in its own manifest. */ const hasEsmProject = (tree)=>{
|
|
26
|
+
for (const project of getProjects(tree).values()){
|
|
27
|
+
if (project.root === '.' || project.root === '') {
|
|
28
|
+
continue;
|
|
29
|
+
}
|
|
30
|
+
const packageJsonPath = joinPathFragments(project.root, 'package.json');
|
|
31
|
+
if (tree.exists(packageJsonPath) && readJson(tree, packageJsonPath).type === 'module') {
|
|
32
|
+
return true;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return false;
|
|
19
36
|
};
|
|
20
37
|
/**
|
|
21
38
|
* Returns the `esm` template variable for `generateFiles` substitutions,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/module-format.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/module-format.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n getProjects,\n joinPathFragments,\n readJson,\n type Tree,\n} from '@nx/devkit';\n\n/**\n * The module format for generated TypeScript code and configuration.\n */\nexport type ModuleFormat = 'esm' | 'cjs';\n\n/**\n * Whether the workspace targets ES modules, read from the tree so shared\n * helpers needn't thread it through call sites. An explicit root `type` wins\n * (`module`/`commonjs`); when absent (e.g. an adopted Nx workspace) infer ESM\n * from any sibling project declaring `type: \"module\"`, else CJS. No root\n * package.json defaults to ESM.\n */\nexport const isEsmWorkspace = (tree: Tree): boolean => {\n if (!tree.exists('package.json')) {\n return true;\n }\n const rootType = readJson(tree, 'package.json').type;\n if (rootType === 'module') {\n return true;\n }\n if (rootType === 'commonjs') {\n return false;\n }\n // Root `type` is absent: infer from sibling projects' own manifests.\n return hasEsmProject(tree);\n};\n\n/** Whether any non-root project declares `type: \"module\"` in its own manifest. */\nconst hasEsmProject = (tree: Tree): boolean => {\n for (const project of getProjects(tree).values()) {\n if (project.root === '.' || project.root === '') {\n continue;\n }\n const packageJsonPath = joinPathFragments(project.root, 'package.json');\n if (\n tree.exists(packageJsonPath) &&\n readJson(tree, packageJsonPath).type === 'module'\n ) {\n return true;\n }\n }\n return false;\n};\n\n/**\n * Returns the `esm` template variable for `generateFiles` substitutions,\n * inferred from the workspace root package.json. Spread into the substitution\n * object wherever a template contains `<% if (esm) { %>` conditionals.\n */\nexport const esmVars = (tree: Tree): { esm: boolean } => ({\n esm: isEsmWorkspace(tree),\n});\n"],"names":["getProjects","joinPathFragments","readJson","isEsmWorkspace","tree","exists","rootType","type","hasEsmProject","project","values","root","packageJsonPath","esmVars","esm"],"mappings":"AAAA;;;CAGC,GACD,SACEA,WAAW,EACXC,iBAAiB,EACjBC,QAAQ,QAEH,aAAa;AAOpB;;;;;;CAMC,GACD,OAAO,MAAMC,iBAAiB,CAACC;IAC7B,IAAI,CAACA,KAAKC,MAAM,CAAC,iBAAiB;QAChC,OAAO;IACT;IACA,MAAMC,WAAWJ,SAASE,MAAM,gBAAgBG,IAAI;IACpD,IAAID,aAAa,UAAU;QACzB,OAAO;IACT;IACA,IAAIA,aAAa,YAAY;QAC3B,OAAO;IACT;IACA,qEAAqE;IACrE,OAAOE,cAAcJ;AACvB,EAAE;AAEF,gFAAgF,GAChF,MAAMI,gBAAgB,CAACJ;IACrB,KAAK,MAAMK,WAAWT,YAAYI,MAAMM,MAAM,GAAI;QAChD,IAAID,QAAQE,IAAI,KAAK,OAAOF,QAAQE,IAAI,KAAK,IAAI;YAC/C;QACF;QACA,MAAMC,kBAAkBX,kBAAkBQ,QAAQE,IAAI,EAAE;QACxD,IACEP,KAAKC,MAAM,CAACO,oBACZV,SAASE,MAAMQ,iBAAiBL,IAAI,KAAK,UACzC;YACA,OAAO;QACT;IACF;IACA,OAAO;AACT;AAEA;;;;CAIC,GACD,OAAO,MAAMM,UAAU,CAACT,OAAkC,CAAA;QACxDU,KAAKX,eAAeC;IACtB,CAAA,EAAG"}
|
package/src/utils/npm-scope.d.ts
CHANGED
|
@@ -5,7 +5,3 @@
|
|
|
5
5
|
import { type Tree } from '@nx/devkit';
|
|
6
6
|
export declare function getNpmScope(tree: Tree): string | undefined;
|
|
7
7
|
export declare function getNpmScopePrefix(tree: Tree): string | undefined;
|
|
8
|
-
/**
|
|
9
|
-
* Returns a safe import alias for local packages to avoid the potential for sniping attacks
|
|
10
|
-
*/
|
|
11
|
-
export declare function toScopeAlias(npmScopeOrPackageName: string): string;
|
package/src/utils/npm-scope.js
CHANGED
|
@@ -12,10 +12,5 @@ export function getNpmScopePrefix(tree) {
|
|
|
12
12
|
const npmScope = getNpmScope(tree);
|
|
13
13
|
return `@${npmScope}/`;
|
|
14
14
|
}
|
|
15
|
-
/**
|
|
16
|
-
* Returns a safe import alias for local packages to avoid the potential for sniping attacks
|
|
17
|
-
*/ export function toScopeAlias(npmScopeOrPackageName) {
|
|
18
|
-
return npmScopeOrPackageName.startsWith('@') ? `:${npmScopeOrPackageName.slice(1)}` : npmScopeOrPackageName;
|
|
19
|
-
}
|
|
20
15
|
|
|
21
16
|
//# sourceMappingURL=npm-scope.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/npm-scope.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { readJson, type Tree } from '@nx/devkit';\nexport function getNpmScope(tree: Tree): string | undefined {\n const { name } = tree.exists('package.json')\n ? readJson<{\n name?: string;\n }>(tree, 'package.json')\n : { name: null };\n return name?.startsWith('@') ? name.split('/')[0].substring(1) : 'monorepo';\n}\nexport function getNpmScopePrefix(tree: Tree): string | undefined {\n const npmScope = getNpmScope(tree);\n return `@${npmScope}/`;\n}\n
|
|
1
|
+
{"version":3,"sources":["../../../../../packages/nx-plugin/src/utils/npm-scope.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { readJson, type Tree } from '@nx/devkit';\nexport function getNpmScope(tree: Tree): string | undefined {\n const { name } = tree.exists('package.json')\n ? readJson<{\n name?: string;\n }>(tree, 'package.json')\n : { name: null };\n return name?.startsWith('@') ? name.split('/')[0].substring(1) : 'monorepo';\n}\nexport function getNpmScopePrefix(tree: Tree): string | undefined {\n const npmScope = getNpmScope(tree);\n return `@${npmScope}/`;\n}\n"],"names":["readJson","getNpmScope","tree","name","exists","startsWith","split","substring","getNpmScopePrefix","npmScope"],"mappings":"AAAA;;;CAGC,GACD,SAASA,QAAQ,QAAmB,aAAa;AACjD,OAAO,SAASC,YAAYC,IAAU;IACpC,MAAM,EAAEC,IAAI,EAAE,GAAGD,KAAKE,MAAM,CAAC,kBACzBJ,SAEGE,MAAM,kBACT;QAAEC,MAAM;IAAK;IACjB,OAAOA,MAAME,WAAW,OAAOF,KAAKG,KAAK,CAAC,IAAI,CAAC,EAAE,CAACC,SAAS,CAAC,KAAK;AACnE;AACA,OAAO,SAASC,kBAAkBN,IAAU;IAC1C,MAAMO,WAAWR,YAAYC;IAC7B,OAAO,CAAC,CAAC,EAAEO,SAAS,CAAC,CAAC;AACxB"}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
|
|
3
3
|
* SPDX-License-Identifier: Apache-2.0
|
|
4
4
|
*/
|
|
5
|
-
import {
|
|
5
|
+
import type { Tree } from '@nx/devkit';
|
|
6
6
|
/**
|
|
7
7
|
* Merge `allowBuilds` (pnpm 11) / `onlyBuiltDependencies` (pnpm 10) entries
|
|
8
8
|
* into the generated workspace's `pnpm-workspace.yaml`. No-op for non-pnpm
|
|
@@ -20,14 +20,3 @@ import { type Tree } from '@nx/devkit';
|
|
|
20
20
|
* allowlist has no equivalent of the `false` decision).
|
|
21
21
|
*/
|
|
22
22
|
export declare const registerPnpmBuiltDependencies: (tree: Tree, entries: Record<string, boolean>) => void;
|
|
23
|
-
/**
|
|
24
|
-
* Set `ignoreWorkspaceRootCheck: true` in `pnpm-workspace.yaml` so `pnpm add`
|
|
25
|
-
* from the workspace root does not error with `ERR_PNPM_ADDING_TO_ROOT`.
|
|
26
|
-
*
|
|
27
|
-
* pnpm 11 no longer honours `ignore-workspace-root-check=true` in `.npmrc`;
|
|
28
|
-
* it must live in `pnpm-workspace.yaml` as the camelCased key. pnpm 10 also
|
|
29
|
-
* accepts the yaml form, so writing it here works for both majors.
|
|
30
|
-
*
|
|
31
|
-
* No-op for non-pnpm workspaces or when `pnpm-workspace.yaml` is absent.
|
|
32
|
-
*/
|
|
33
|
-
export declare const ensurePnpmIgnoresWorkspaceRootCheck: (tree: Tree) => boolean;
|