@aws/nx-plugin 1.0.0-rc.96 → 1.0.0-rc.97
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/migrations.json +33 -3
- package/package.json +1 -1
- package/src/agentcore-gateway/__snapshots__/generator.spec.ts.snap +1 -1
- package/src/agentcore-gateway/generator.js +6 -0
- package/src/agentcore-gateway/generator.js.map +1 -1
- package/src/agentcore-gateway/react-connection/__snapshots__/generator.spec.ts.snap +4 -1
- package/src/agentcore-harness/__snapshots__/generator.spec.ts.snap +68 -4
- package/src/agentcore-harness/generator.js +6 -0
- package/src/agentcore-harness/generator.js.map +1 -1
- package/src/connection/gateway-runtime-config.js +1 -1
- package/src/connection/gateway-runtime-config.js.map +1 -1
- package/src/infra/app/__snapshots__/generator.spec.ts.snap +6 -6
- package/src/infra/app/generator.js +34 -7
- package/src/infra/app/generator.js.map +1 -1
- package/src/init/generator.d.ts +1 -1
- package/src/init/generator.js +8 -6
- package/src/init/generator.js.map +1 -1
- package/src/init/schema.d.js.map +1 -1
- package/src/init/schema.d.ts +1 -0
- package/src/init/schema.json +5 -0
- package/src/mcp-server/server.js +2 -0
- package/src/mcp-server/server.js.map +1 -1
- package/src/mcp-server/tools/best-practices.d.ts +28 -0
- package/src/mcp-server/tools/best-practices.js +43 -0
- package/src/mcp-server/tools/best-practices.js.map +1 -0
- package/src/mcp-server/tools/general-guidance.d.ts +1 -1
- package/src/mcp-server/tools/general-guidance.js +13 -4
- package/src/mcp-server/tools/general-guidance.js.map +1 -1
- package/src/migrations/latest/checkov-scan-cache-inputs/metadata.json +3 -0
- package/src/migrations/latest/checkov-scan-cache-inputs/migration.d.ts +6 -0
- package/src/migrations/latest/checkov-scan-cache-inputs/migration.js +58 -0
- package/src/migrations/latest/checkov-scan-cache-inputs/migration.js.map +1 -0
- package/src/migrations/latest/gateway-url-accessor/__snapshots__/migration.spec.ts.snap +84 -0
- package/src/migrations/latest/gateway-url-accessor/metadata.json +3 -0
- package/src/migrations/latest/gateway-url-accessor/migration.d.ts +6 -0
- package/src/migrations/latest/gateway-url-accessor/migration.js +94 -0
- package/src/migrations/latest/gateway-url-accessor/migration.js.map +1 -0
- package/src/migrations/latest/infra-deploy-express-mode/metadata.json +1 -1
- package/src/migrations/latest/infra-deploy-express-mode/migration.js +26 -28
- package/src/migrations/latest/infra-deploy-express-mode/migration.js.map +1 -1
- package/src/migrations/latest/py-lambda-powertools-context/metadata.json +3 -0
- package/src/migrations/latest/py-lambda-powertools-context/migration.d.ts +6 -0
- package/src/migrations/latest/py-lambda-powertools-context/migration.js +58 -0
- package/src/migrations/latest/py-lambda-powertools-context/migration.js.map +1 -0
- package/src/migrations/latest/script-project-quality-gates/metadata.json +3 -0
- package/src/migrations/latest/script-project-quality-gates/migration.d.ts +6 -0
- package/src/migrations/latest/script-project-quality-gates/migration.js +53 -0
- package/src/migrations/latest/script-project-quality-gates/migration.js.map +1 -0
- package/src/migrations/latest/smithy-extension-trait-aliases/__snapshots__/migration.spec.ts.snap +25 -0
- package/src/migrations/latest/smithy-extension-trait-aliases/metadata.json +3 -0
- package/src/migrations/latest/smithy-extension-trait-aliases/migration.d.ts +28 -0
- package/src/migrations/latest/smithy-extension-trait-aliases/migration.js +75 -0
- package/src/migrations/latest/smithy-extension-trait-aliases/migration.js.map +1 -0
- package/src/migrations/latest/terraform-validate-without-backend/metadata.json +3 -0
- package/src/migrations/latest/terraform-validate-without-backend/migration.d.ts +6 -0
- package/src/migrations/latest/terraform-validate-without-backend/migration.js +84 -0
- package/src/migrations/latest/terraform-validate-without-backend/migration.js.map +1 -0
- package/src/preset/generator.js +4 -25
- package/src/preset/generator.js.map +1 -1
- 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/__snapshots__/generator.spec.ts.snap +4 -1
- package/src/py/dynamodb/__snapshots__/generator.spec.ts.snap +8 -10
- package/src/py/dynamodb/generator.js +34 -7
- package/src/py/dynamodb/generator.js.map +1 -1
- package/src/py/lambda-function/__snapshots__/generator.spec.ts.snap +2 -1
- package/src/py/lambda-function/files/handler/__lambdaFunctionSnakeCase__.py.template +2 -1
- package/src/py/project/schema.json +3 -1
- package/src/py/rdb/__snapshots__/generator.spec.ts.snap +28 -12
- package/src/py/rdb/files/Dockerfile.create-db-user.template +7 -3
- package/src/py/rdb/files/Dockerfile.migration.template +7 -3
- package/src/py/rdb/generator.js +29 -28
- package/src/py/rdb/generator.js.map +1 -1
- package/src/smithy/react-connection/files/model/extensions.smithy.template +3 -3
- package/src/smithy/ts/api/generator.js +7 -2
- package/src/smithy/ts/api/generator.js.map +1 -1
- package/src/terraform/project/generator.js +34 -10
- package/src/terraform/project/generator.js.map +1 -1
- package/src/trpc/backend/generator.js +7 -1
- package/src/trpc/backend/generator.js.map +1 -1
- package/src/trpc/react/generator.js +6 -0
- package/src/trpc/react/generator.js.map +1 -1
- package/src/ts/agent/generator.js +3 -3
- package/src/ts/agent/generator.js.map +1 -1
- package/src/ts/dynamodb/__snapshots__/generator.spec.ts.snap +2 -0
- package/src/ts/dynamodb/generator.js +30 -6
- package/src/ts/dynamodb/generator.js.map +1 -1
- package/src/ts/lib/biome.d.ts +15 -1
- package/src/ts/lib/biome.js +79 -63
- package/src/ts/lib/biome.js.map +1 -1
- package/src/ts/lib/generator.js +11 -7
- package/src/ts/lib/generator.js.map +1 -1
- package/src/ts/lib/ts-project-utils.d.ts +14 -0
- package/src/ts/lib/ts-project-utils.js +24 -0
- package/src/ts/lib/ts-project-utils.js.map +1 -1
- package/src/ts/mcp-server/generator.js +3 -3
- package/src/ts/mcp-server/generator.js.map +1 -1
- package/src/ts/rdb/__snapshots__/generator.spec.ts.snap +5 -0
- package/src/ts/rdb/files/Dockerfile.template +5 -0
- package/src/ts/rdb/generator.d.ts +8 -0
- package/src/ts/rdb/generator.js +28 -24
- package/src/ts/rdb/generator.js.map +1 -1
- package/src/ts/rdb/trpc-connection/__snapshots__/generator.spec.ts.snap +39 -0
- package/src/ts/rdb/trpc-connection/generator.js +13 -0
- package/src/ts/rdb/trpc-connection/generator.js.map +1 -1
- package/src/ts/react-website/agui/files/common/src/components/__agentNameKebabCase__-chat.tsx.template +9 -0
- package/src/ts/react-website/agui/files/common/src/hooks/useAgui__agentNameClassName__.tsx.template +4 -1
- package/src/ts/react-website/agui/generator.js +6 -2
- package/src/ts/react-website/agui/generator.js.map +1 -1
- package/src/ts/react-website/app/generator.js +3 -8
- package/src/ts/react-website/app/generator.js.map +1 -1
- package/src/utils/agent-connection/agent-connection.d.ts +2 -1
- package/src/utils/agent-connection/agent-connection.js +6 -1
- package/src/utils/agent-connection/agent-connection.js.map +1 -1
- package/src/utils/agent-core-constructs/files/cdk/app/agentcore-gateway/__nameKebabCase__/__nameKebabCase__.ts.template +11 -7
- package/src/utils/agent-core-constructs/files/cdk/core/agentcore-gateway/agentcore-gateway.ts.template +14 -6
- package/src/utils/agent-core-packaging.js +5 -5
- package/src/utils/agent-core-packaging.js.map +1 -1
- package/src/utils/api-constructs/api-constructs.d.ts +5 -0
- package/src/utils/api-constructs/api-constructs.js +8 -0
- package/src/utils/api-constructs/api-constructs.js.map +1 -1
- package/src/utils/api-constructs/files/cdk/app/apis/http/__apiNameKebabCase__.ts.template +4 -2
- package/src/utils/api-constructs/files/cdk/app/apis/rest/__apiNameKebabCase__.ts.template +4 -2
- package/src/utils/ast.d.ts +10 -0
- package/src/utils/ast.js +33 -0
- package/src/utils/ast.js.map +1 -1
- package/src/utils/docker.d.ts +11 -0
- package/src/utils/docker.js +16 -3
- package/src/utils/docker.js.map +1 -1
- package/src/utils/dynamodb-config.d.ts +48 -0
- package/src/utils/dynamodb-config.js +44 -0
- package/src/utils/dynamodb-config.js.map +1 -0
- package/src/utils/dynamodb-constructs/files/cdk/app/dynamodb/__nameKebabCase__.ts.template +8 -4
- package/src/utils/git-secrets.d.ts +28 -0
- package/src/utils/git-secrets.js +66 -0
- package/src/utils/git-secrets.js.map +1 -0
- package/src/utils/init.js +7 -6
- package/src/utils/init.js.map +1 -1
- package/src/utils/local-project-dependency.d.ts +28 -0
- package/src/utils/local-project-dependency.js +40 -0
- package/src/utils/local-project-dependency.js.map +1 -0
- package/src/utils/nx.d.ts +14 -0
- package/src/utils/nx.js +30 -0
- package/src/utils/nx.js.map +1 -1
- package/src/utils/rdb-constructs/files/cdk/app/dbs/__nameKebabCase__.ts.template +11 -6
- package/src/utils/script-project-targets.d.ts +26 -0
- package/src/utils/script-project-targets.js +75 -0
- package/src/utils/script-project-targets.js.map +1 -0
- package/src/utils/versions.d.ts +3 -0
- package/src/utils/versions.js +7 -0
- package/src/utils/versions.js.map +1 -1
- package/src/utils/website-constructs/files/cdk/app/static-websites/__websiteNameKebabCase__.ts.template +8 -4
- package/src/py/dynamodb/files/__name__/__init__.py.template +0 -6
- package/src/py/dynamodb/files/__name__/entities/__init__.py.template +0 -4
- package/src/py/dynamodb/files/config.json.template +0 -24
- package/src/ts/dynamodb/files/config.json.template +0 -24
- package/src/ts/dynamodb/files/src/entities/index.ts.template +0 -1
- package/src/ts/dynamodb/files/src/index.ts.template +0 -2
package/src/ts/lib/biome.js
CHANGED
|
@@ -4,75 +4,77 @@
|
|
|
4
4
|
*/ import { readNxJson, updateNxJson, updateProjectConfiguration } from "@nx/devkit";
|
|
5
5
|
import { readProjectConfigurationUnqualified } from "../../utils/nx.js";
|
|
6
6
|
import { sortObjectKeys } from "../../utils/object.js";
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
command: 'biome lint {projectRoot}'
|
|
20
|
-
},
|
|
21
|
-
configurations: {
|
|
22
|
-
fix: {
|
|
23
|
-
command: 'biome check --write {projectRoot}'
|
|
7
|
+
/**
|
|
8
|
+
* The `format` and `lint` targets every Biome-linted project gets, so a project
|
|
9
|
+
* that isn't scaffolded by `ts#project` (e.g. an AgentCore Gateway hosting only
|
|
10
|
+
* `local-dev.ts`) is linted identically rather than by its own copy.
|
|
11
|
+
*
|
|
12
|
+
* When there's no root Biome configuration (eg the user removed it), the targets
|
|
13
|
+
* are no-ops rather than failing on a missing config.
|
|
14
|
+
*/ export const biomeTargets = (tree)=>{
|
|
15
|
+
if (!tree.exists('biome.json')) {
|
|
16
|
+
return {
|
|
17
|
+
format: {
|
|
18
|
+
executor: 'nx:noop'
|
|
24
19
|
},
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
command: 'node -e ""'
|
|
20
|
+
lint: {
|
|
21
|
+
executor: 'nx:noop'
|
|
28
22
|
}
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
cache: true,
|
|
45
|
-
inputs: [
|
|
46
|
-
'biome'
|
|
47
|
-
],
|
|
48
|
-
options: {
|
|
49
|
-
command: 'biome format {projectRoot}'
|
|
50
|
-
},
|
|
51
|
-
configurations: {
|
|
52
|
-
fix: {
|
|
53
|
-
command: 'biome format --write {projectRoot}'
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
return {
|
|
26
|
+
// The base format target checks formatting (failing when files aren't
|
|
27
|
+
// formatted); the `fix` configuration writes the changes. `skip-lint` is a
|
|
28
|
+
// no-op so `nx lint --configuration=skip-lint` propagates cleanly through
|
|
29
|
+
// the lint -> format dependency edge.
|
|
30
|
+
format: {
|
|
31
|
+
executor: 'nx:run-commands',
|
|
32
|
+
cache: true,
|
|
33
|
+
inputs: [
|
|
34
|
+
'biome'
|
|
35
|
+
],
|
|
36
|
+
options: {
|
|
37
|
+
command: 'biome format {projectRoot}'
|
|
54
38
|
},
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
39
|
+
configurations: {
|
|
40
|
+
fix: {
|
|
41
|
+
command: 'biome format --write {projectRoot}'
|
|
42
|
+
},
|
|
43
|
+
'skip-lint': {
|
|
44
|
+
// Cross-platform no-op (`true` is not available on Windows cmd).
|
|
45
|
+
command: 'node -e ""'
|
|
46
|
+
}
|
|
58
47
|
}
|
|
48
|
+
},
|
|
49
|
+
lint: {
|
|
50
|
+
executor: 'nx:run-commands',
|
|
51
|
+
cache: true,
|
|
52
|
+
inputs: [
|
|
53
|
+
'biome'
|
|
54
|
+
],
|
|
55
|
+
options: {
|
|
56
|
+
command: 'biome lint {projectRoot}'
|
|
57
|
+
},
|
|
58
|
+
configurations: {
|
|
59
|
+
fix: {
|
|
60
|
+
command: 'biome check --write {projectRoot}'
|
|
61
|
+
},
|
|
62
|
+
'skip-lint': {
|
|
63
|
+
command: 'node -e ""'
|
|
64
|
+
}
|
|
65
|
+
},
|
|
66
|
+
// Format before linting so any fixable formatting issues (eg line too
|
|
67
|
+
// long) are resolved first, mirroring the Python project generator.
|
|
68
|
+
dependsOn: [
|
|
69
|
+
'format'
|
|
70
|
+
]
|
|
59
71
|
}
|
|
60
|
-
} : {
|
|
61
|
-
executor: 'nx:noop'
|
|
62
72
|
};
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
targets: sortObjectKeys({
|
|
69
|
-
...projectJson?.targets,
|
|
70
|
-
format: formatTarget,
|
|
71
|
-
lint: lintTarget
|
|
72
|
-
})
|
|
73
|
-
});
|
|
74
|
-
// Register the `biome` named input so lint targets are cache-invalidated when
|
|
75
|
-
// the root biome.json changes.
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Register the `biome` named input so lint targets are cache-invalidated when
|
|
76
|
+
* the root biome.json changes.
|
|
77
|
+
*/ export const registerBiomeNamedInput = (tree)=>{
|
|
76
78
|
const nxJson = readNxJson(tree);
|
|
77
79
|
if (!nxJson.namedInputs?.biome || !nxJson.namedInputs.biome.includes('{workspaceRoot}/biome.json')) {
|
|
78
80
|
updateNxJson(tree, {
|
|
@@ -87,5 +89,19 @@ export const configureBiomeLint = async (tree, options)=>{
|
|
|
87
89
|
});
|
|
88
90
|
}
|
|
89
91
|
};
|
|
92
|
+
export const configureBiomeLint = async (tree, options)=>{
|
|
93
|
+
const projectJson = readProjectConfigurationUnqualified(tree, options.fullyQualifiedName);
|
|
94
|
+
updateProjectConfiguration(tree, options.fullyQualifiedName, {
|
|
95
|
+
...projectJson,
|
|
96
|
+
// Sort targets so the lint and format targets land in deterministic
|
|
97
|
+
// positions regardless of whether they already existed (keeps re-runs
|
|
98
|
+
// stable)
|
|
99
|
+
targets: sortObjectKeys({
|
|
100
|
+
...projectJson?.targets,
|
|
101
|
+
...biomeTargets(tree)
|
|
102
|
+
})
|
|
103
|
+
});
|
|
104
|
+
registerBiomeNamedInput(tree);
|
|
105
|
+
};
|
|
90
106
|
|
|
91
107
|
//# sourceMappingURL=biome.js.map
|
package/src/ts/lib/biome.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/lib/biome.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n readNxJson,\n type Tree,\n updateNxJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { readProjectConfigurationUnqualified } from '../../utils/nx.js';\nimport { sortObjectKeys } from '../../utils/object.js';\nimport type { ConfigureProjectOptions } from './types.js';\n\
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/lib/biome.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n readNxJson,\n type TargetConfiguration,\n type Tree,\n updateNxJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { readProjectConfigurationUnqualified } from '../../utils/nx.js';\nimport { sortObjectKeys } from '../../utils/object.js';\nimport type { ConfigureProjectOptions } from './types.js';\n\n/**\n * The `format` and `lint` targets every Biome-linted project gets, so a project\n * that isn't scaffolded by `ts#project` (e.g. an AgentCore Gateway hosting only\n * `local-dev.ts`) is linted identically rather than by its own copy.\n *\n * When there's no root Biome configuration (eg the user removed it), the targets\n * are no-ops rather than failing on a missing config.\n */\nexport const biomeTargets = (\n tree: Tree,\n): Record<'format' | 'lint', TargetConfiguration> => {\n if (!tree.exists('biome.json')) {\n return { format: { executor: 'nx:noop' }, lint: { executor: 'nx:noop' } };\n }\n return {\n // The base format target checks formatting (failing when files aren't\n // formatted); the `fix` configuration writes the changes. `skip-lint` is a\n // no-op so `nx lint --configuration=skip-lint` propagates cleanly through\n // the lint -> format dependency edge.\n format: {\n executor: 'nx:run-commands',\n cache: true,\n inputs: ['biome'],\n options: {\n command: 'biome format {projectRoot}',\n },\n configurations: {\n fix: {\n command: 'biome format --write {projectRoot}',\n },\n 'skip-lint': {\n // Cross-platform no-op (`true` is not available on Windows cmd).\n command: 'node -e \"\"',\n },\n },\n },\n lint: {\n executor: 'nx:run-commands',\n cache: true,\n inputs: ['biome'],\n options: {\n command: 'biome lint {projectRoot}',\n },\n configurations: {\n fix: {\n command: 'biome check --write {projectRoot}',\n },\n 'skip-lint': {\n command: 'node -e \"\"',\n },\n },\n // Format before linting so any fixable formatting issues (eg line too\n // long) are resolved first, mirroring the Python project generator.\n dependsOn: ['format'],\n },\n };\n};\n\n/**\n * Register the `biome` named input so lint targets are cache-invalidated when\n * the root biome.json changes.\n */\nexport const registerBiomeNamedInput = (tree: Tree): void => {\n const nxJson = readNxJson(tree);\n if (\n !nxJson.namedInputs?.biome ||\n !nxJson.namedInputs.biome.includes('{workspaceRoot}/biome.json')\n ) {\n updateNxJson(tree, {\n ...nxJson,\n namedInputs: {\n ...nxJson.namedInputs,\n biome: ['default', '{workspaceRoot}/biome.json'],\n },\n });\n }\n};\n\nexport const configureBiomeLint = async (\n tree: Tree,\n options: ConfigureProjectOptions,\n) => {\n const projectJson = readProjectConfigurationUnqualified(\n tree,\n options.fullyQualifiedName,\n );\n\n updateProjectConfiguration(tree, options.fullyQualifiedName, {\n ...projectJson,\n // Sort targets so the lint and format targets land in deterministic\n // positions regardless of whether they already existed (keeps re-runs\n // stable)\n targets: sortObjectKeys({\n ...projectJson?.targets,\n ...biomeTargets(tree),\n }),\n });\n\n registerBiomeNamedInput(tree);\n};\n"],"names":["readNxJson","updateNxJson","updateProjectConfiguration","readProjectConfigurationUnqualified","sortObjectKeys","biomeTargets","tree","exists","format","executor","lint","cache","inputs","options","command","configurations","fix","dependsOn","registerBiomeNamedInput","nxJson","namedInputs","biome","includes","configureBiomeLint","projectJson","fullyQualifiedName","targets"],"mappings":"AAAA;;;CAGC,GACD,SACEA,UAAU,EAGVC,YAAY,EACZC,0BAA0B,QACrB,aAAa;AACpB,SAASC,mCAAmC,QAAQ,oBAAoB;AACxE,SAASC,cAAc,QAAQ,wBAAwB;AAGvD;;;;;;;CAOC,GACD,OAAO,MAAMC,eAAe,CAC1BC;IAEA,IAAI,CAACA,KAAKC,MAAM,CAAC,eAAe;QAC9B,OAAO;YAAEC,QAAQ;gBAAEC,UAAU;YAAU;YAAGC,MAAM;gBAAED,UAAU;YAAU;QAAE;IAC1E;IACA,OAAO;QACL,sEAAsE;QACtE,2EAA2E;QAC3E,0EAA0E;QAC1E,sCAAsC;QACtCD,QAAQ;YACNC,UAAU;YACVE,OAAO;YACPC,QAAQ;gBAAC;aAAQ;YACjBC,SAAS;gBACPC,SAAS;YACX;YACAC,gBAAgB;gBACdC,KAAK;oBACHF,SAAS;gBACX;gBACA,aAAa;oBACX,iEAAiE;oBACjEA,SAAS;gBACX;YACF;QACF;QACAJ,MAAM;YACJD,UAAU;YACVE,OAAO;YACPC,QAAQ;gBAAC;aAAQ;YACjBC,SAAS;gBACPC,SAAS;YACX;YACAC,gBAAgB;gBACdC,KAAK;oBACHF,SAAS;gBACX;gBACA,aAAa;oBACXA,SAAS;gBACX;YACF;YACA,sEAAsE;YACtE,oEAAoE;YACpEG,WAAW;gBAAC;aAAS;QACvB;IACF;AACF,EAAE;AAEF;;;CAGC,GACD,OAAO,MAAMC,0BAA0B,CAACZ;IACtC,MAAMa,SAASnB,WAAWM;IAC1B,IACE,CAACa,OAAOC,WAAW,EAAEC,SACrB,CAACF,OAAOC,WAAW,CAACC,KAAK,CAACC,QAAQ,CAAC,+BACnC;QACArB,aAAaK,MAAM;YACjB,GAAGa,MAAM;YACTC,aAAa;gBACX,GAAGD,OAAOC,WAAW;gBACrBC,OAAO;oBAAC;oBAAW;iBAA6B;YAClD;QACF;IACF;AACF,EAAE;AAEF,OAAO,MAAME,qBAAqB,OAChCjB,MACAO;IAEA,MAAMW,cAAcrB,oCAClBG,MACAO,QAAQY,kBAAkB;IAG5BvB,2BAA2BI,MAAMO,QAAQY,kBAAkB,EAAE;QAC3D,GAAGD,WAAW;QACd,oEAAoE;QACpE,sEAAsE;QACtE,UAAU;QACVE,SAAStB,eAAe;YACtB,GAAGoB,aAAaE,OAAO;YACvB,GAAGrB,aAAaC,KAAK;QACvB;IACF;IAEAY,wBAAwBZ;AAC1B,EAAE"}
|
package/src/ts/lib/generator.js
CHANGED
|
@@ -10,7 +10,7 @@ import { addGeneratorMetricsIfApplicable } from "../../utils/metrics.js";
|
|
|
10
10
|
import { isEsmWorkspace } from "../../utils/module-format.js";
|
|
11
11
|
import { toKebabCase } from "../../utils/names.js";
|
|
12
12
|
import { getNpmScopePrefix } from "../../utils/npm-scope.js";
|
|
13
|
-
import { addGeneratorMetadata, getGeneratorInfo, mergeTargetDefault, projectExists } from "../../utils/nx.js";
|
|
13
|
+
import { addGeneratorMetadata, getGeneratorInfo, mergeTarget, mergeTargetDefault, projectExists } from "../../utils/nx.js";
|
|
14
14
|
import { sortObjectKeys } from "../../utils/object.js";
|
|
15
15
|
import { getPackageManagerDisplayCommands } from "../../utils/pkg-manager.js";
|
|
16
16
|
import { configureTsProject, TS_PROJECT_DEPENDENCIES } from "./ts-project-utils.js";
|
|
@@ -97,7 +97,11 @@ const VENDED_DEPENDENT_TASKS_OUTPUT_GLOBS = [
|
|
|
97
97
|
}, DEPENDENCIES);
|
|
98
98
|
const projectConfiguration = readProjectConfiguration(tree, fullyQualifiedName);
|
|
99
99
|
const targets = projectConfiguration.targets;
|
|
100
|
-
|
|
100
|
+
// Merged rather than assigned so a re-run converges this generator's own
|
|
101
|
+
// configuration without discarding what other generators contributed to the
|
|
102
|
+
// same targets — the `bundle` that ts#lambda-function adds to build and
|
|
103
|
+
// assemble, say, which those targets must keep depending on.
|
|
104
|
+
targets['compile'] = mergeTarget(targets['compile'], {
|
|
101
105
|
executor: 'nx:run-commands',
|
|
102
106
|
outputs: [
|
|
103
107
|
'{workspaceRoot}/dist/{projectRoot}/tsc'
|
|
@@ -106,20 +110,20 @@ const VENDED_DEPENDENT_TASKS_OUTPUT_GLOBS = [
|
|
|
106
110
|
command: 'tsc --build tsconfig.lib.json',
|
|
107
111
|
cwd: '{projectRoot}'
|
|
108
112
|
}
|
|
109
|
-
};
|
|
110
|
-
targets['build'] = {
|
|
113
|
+
});
|
|
114
|
+
targets['build'] = mergeTarget(targets['build'], {
|
|
111
115
|
dependsOn: [
|
|
112
116
|
'lint',
|
|
113
117
|
'compile',
|
|
114
118
|
'test'
|
|
115
119
|
]
|
|
116
|
-
};
|
|
120
|
+
});
|
|
117
121
|
// The artifact-only sibling of build, which the deploy targets depend on.
|
|
118
|
-
targets['assemble'] = {
|
|
122
|
+
targets['assemble'] = mergeTarget(targets['assemble'], {
|
|
119
123
|
dependsOn: [
|
|
120
124
|
'compile'
|
|
121
125
|
]
|
|
122
|
-
};
|
|
126
|
+
});
|
|
123
127
|
projectConfiguration.targets = sortObjectKeys(targets);
|
|
124
128
|
updateProjectConfiguration(tree, fullyQualifiedName, projectConfiguration);
|
|
125
129
|
addGeneratorMetadata(tree, fullyQualifiedName, TS_LIB_GENERATOR_INFO);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/lib/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n type NxJsonConfiguration,\n OverwriteStrategy,\n readProjectConfiguration,\n type TargetConfiguration,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { libraryGenerator } from '@nx/js';\nimport { declareDependencies } from '../../utils/declared-dependencies.js';\nimport { formatFilesInSubtree } from '../../utils/format.js';\nimport { installDependencies } from '../../utils/install.js';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics.js';\nimport { isEsmWorkspace } from '../../utils/module-format.js';\nimport { toKebabCase } from '../../utils/names.js';\nimport { getNpmScopePrefix } from '../../utils/npm-scope.js';\nimport {\n addGeneratorMetadata,\n getGeneratorInfo,\n mergeTargetDefault,\n type NxGeneratorInfo,\n projectExists,\n} from '../../utils/nx.js';\nimport { sortObjectKeys } from '../../utils/object.js';\nimport { getPackageManagerDisplayCommands } from '../../utils/pkg-manager.js';\nimport type { TsProjectGeneratorSchema } from './schema';\nimport {\n configureTsProject,\n TS_PROJECT_DEPENDENCIES,\n} from './ts-project-utils.js';\nimport { VITEST_DEPENDENCIES } from './vitest.js';\n\nexport const DEPENDENCIES = declareDependencies()({\n ts: [...VITEST_DEPENDENCIES, ...TS_PROJECT_DEPENDENCIES],\n});\n\nexport const TS_LIB_GENERATOR_INFO: NxGeneratorInfo = getGeneratorInfo(\n import.meta.filename,\n);\n\n/**\n * Consumes build artifacts produced by a project's dependencies, so a task\n * re-runs when the output it actually reads changes.\n *\n * Test reports are excluded rather than build artifacts included: several\n * generators emit generated sources outside `dist` (an OpenAPI client under a\n * website's `src/generated`, a Smithy SSDK, the Prisma client) and add them to\n * `.gitignore`, which keeps them out of the project's own fileset — so this\n * input is the only thing that hashes them. `reports/` and `coverage/` hold\n * pytest's JUnit and coverage XML, which carry a wall-clock timestamp and so\n * mint a fresh hash on every test run that would cascade through the graph.\n */\nexport const DEPENDENT_TASKS_OUTPUT_FILES_INPUT = {\n dependentTasksOutputFiles: '!{reports,coverage}/**',\n transitive: true,\n};\n\n// Globs this generator has vended for the dependent-task-output input. Any of\n// them is replaced in place, so the entry is neither duplicated nor left at a\n// different scope when a generator re-runs.\nconst VENDED_DEPENDENT_TASKS_OUTPUT_GLOBS = [\n '**/*',\n 'dist/**',\n DEPENDENT_TASKS_OUTPUT_FILES_INPUT.dependentTasksOutputFiles,\n];\n\nexport interface TsLibDetails {\n /**\n * Full package name including scope (eg @foo/bar)\n */\n readonly fullyQualifiedName: string;\n /**\n * Directory of the library relative to the root\n */\n readonly dir: string;\n}\n\n/**\n * Returns details about the TS library to be created\n */\nexport const getTsLibDetails = (\n tree: Tree,\n schema: TsProjectGeneratorSchema,\n): TsLibDetails => {\n const scope = getNpmScopePrefix(tree);\n const normalizedName = toKebabCase(schema.name);\n const fullyQualifiedName = `${scope}${normalizedName}`;\n // NB: interactive nx generator cli can pass empty string\n const dir = joinPathFragments(\n schema.directory || '.',\n schema.subDirectory || normalizedName,\n );\n return { dir, fullyQualifiedName };\n};\n\n/**\n * Generates a typescript project\n */\nexport const tsProjectGenerator = async (\n tree: Tree,\n schema: TsProjectGeneratorSchema,\n): Promise<GeneratorCallback> => {\n const { fullyQualifiedName, dir } = getTsLibDetails(tree, schema);\n // The module format is workspace-wide, established by the preset when the\n // workspace is created, so vending generators always infer it from the tree.\n const esm = isEsmWorkspace(tree);\n\n // Only scaffold the project on first run; on re-run skip creation so user\n // edits are preserved, but continue to (re)apply the configuration below.\n if (!projectExists(tree, fullyQualifiedName)) {\n await libraryGenerator(tree, {\n ...schema,\n name: fullyQualifiedName,\n directory: dir,\n skipPackageJson: true,\n bundler: 'tsc', // TODO: consider supporting others\n linter: 'none',\n unitTestRunner: 'vitest',\n // Register the @nx/vitest plugin so the test target is inferred rather\n // than emitting the deprecated @nx/vitest:test executor target.\n addPlugin: true,\n });\n\n // Replace with simpler sample source code\n tree.delete(joinPathFragments(dir, 'src'));\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files'),\n joinPathFragments(dir),\n {\n fullyQualifiedName,\n esm,\n pkgMgrCmd: getPackageManagerDisplayCommands().exec,\n },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n }\n await configureTsProject(\n tree,\n {\n dir,\n fullyQualifiedName,\n esm,\n },\n DEPENDENCIES,\n );\n\n const projectConfiguration = readProjectConfiguration(\n tree,\n fullyQualifiedName,\n );\n const targets = projectConfiguration.targets;\n\n targets['compile'] = {\n executor: 'nx:run-commands',\n outputs: ['{workspaceRoot}/dist/{projectRoot}/tsc'],\n options: {\n command: 'tsc --build tsconfig.lib.json',\n cwd: '{projectRoot}',\n },\n };\n targets['build'] = {\n dependsOn: ['lint', 'compile', 'test'],\n };\n // The artifact-only sibling of build, which the deploy targets depend on.\n targets['assemble'] = {\n dependsOn: ['compile'],\n };\n projectConfiguration.targets = sortObjectKeys(targets);\n\n updateProjectConfiguration(tree, fullyQualifiedName, projectConfiguration);\n\n addGeneratorMetadata(tree, fullyQualifiedName, TS_LIB_GENERATOR_INFO);\n\n updateJson(tree, 'nx.json', (nxJson: NxJsonConfiguration) => {\n nxJson.namedInputs = {\n ...nxJson.namedInputs,\n default: [\n ...(nxJson.namedInputs?.default ?? []).filter(\n (input) =>\n typeof input !== 'object' ||\n !('dependentTasksOutputFiles' in input) ||\n !(\n VENDED_DEPENDENT_TASKS_OUTPUT_GLOBS.includes(\n input.dependentTasksOutputFiles as string,\n ) && input.transitive\n ),\n ),\n DEPENDENT_TASKS_OUTPUT_FILES_INPUT,\n ],\n };\n\n const withDefaultInput = (base: Partial<TargetConfiguration>) => ({\n ...base,\n inputs: [\n ...(base.inputs ?? []).filter((i) => i !== 'default'),\n 'default',\n ],\n });\n\n nxJson.targetDefaults = {\n ...nxJson.targetDefaults,\n compile: mergeTargetDefault(nxJson.targetDefaults?.compile, (base) => ({\n cache: true,\n ...withDefaultInput(base),\n })),\n build: mergeTargetDefault(nxJson.targetDefaults?.build, (base) => ({\n cache: true,\n ...withDefaultInput(base),\n })),\n test: mergeTargetDefault(nxJson.targetDefaults?.test, withDefaultInput),\n };\n\n // Ensure we only declare a single typescript plugin with the correct settings\n nxJson.plugins = [\n {\n plugin: '@nx/js/typescript',\n options: {\n typecheck: {\n targetName: 'typecheck',\n },\n build: {\n targetName: 'compile',\n configName: 'tsconfig.lib.json',\n buildDepsName: 'build-deps',\n watchDepsName: 'watch-deps',\n },\n },\n },\n ...(nxJson.plugins ?? []).filter(\n (p) => typeof p === 'string' || p.plugin !== '@nx/js/typescript',\n ),\n ];\n\n return nxJson;\n });\n\n await addGeneratorMetricsIfApplicable(tree, [TS_LIB_GENERATOR_INFO]);\n\n await formatFilesInSubtree(tree);\n\n // `installDependencies` ensures vitest resolves for the `typescript` language (the\n // generated vitest.config.mts imports it and Nx loads that config when\n // computing the project graph), so a deferred install still runs when needed.\n return () =>\n installDependencies(tree, schema.preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\nexport default tsProjectGenerator;\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","readProjectConfiguration","updateJson","updateProjectConfiguration","libraryGenerator","declareDependencies","formatFilesInSubtree","installDependencies","addGeneratorMetricsIfApplicable","isEsmWorkspace","toKebabCase","getNpmScopePrefix","addGeneratorMetadata","getGeneratorInfo","mergeTargetDefault","projectExists","sortObjectKeys","getPackageManagerDisplayCommands","configureTsProject","TS_PROJECT_DEPENDENCIES","VITEST_DEPENDENCIES","DEPENDENCIES","ts","TS_LIB_GENERATOR_INFO","filename","DEPENDENT_TASKS_OUTPUT_FILES_INPUT","dependentTasksOutputFiles","transitive","VENDED_DEPENDENT_TASKS_OUTPUT_GLOBS","getTsLibDetails","tree","schema","scope","normalizedName","name","fullyQualifiedName","dir","directory","subDirectory","tsProjectGenerator","esm","skipPackageJson","bundler","linter","unitTestRunner","addPlugin","delete","dirname","pkgMgrCmd","exec","overwriteStrategy","KeepExisting","projectConfiguration","targets","executor","outputs","options","command","cwd","dependsOn","nxJson","namedInputs","default","filter","input","includes","withDefaultInput","base","inputs","i","targetDefaults","compile","cache","build","test","plugins","plugin","typecheck","targetName","configName","buildDepsName","watchDepsName","p","preferInstallDependencies","languages"],"mappings":"AAAA;;;CAGC,GACD,SAEEA,aAAa,EACbC,iBAAiB,EAEjBC,iBAAiB,EACjBC,wBAAwB,EAGxBC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAASC,gBAAgB,QAAQ,SAAS;AAC1C,SAASC,mBAAmB,QAAQ,uCAAuC;AAC3E,SAASC,oBAAoB,QAAQ,wBAAwB;AAC7D,SAASC,mBAAmB,QAAQ,yBAAyB;AAC7D,SAASC,+BAA+B,QAAQ,yBAAyB;AACzE,SAASC,cAAc,QAAQ,+BAA+B;AAC9D,SAASC,WAAW,QAAQ,uBAAuB;AACnD,SAASC,iBAAiB,QAAQ,2BAA2B;AAC7D,SACEC,oBAAoB,EACpBC,gBAAgB,EAChBC,kBAAkB,EAElBC,aAAa,QACR,oBAAoB;AAC3B,SAASC,cAAc,QAAQ,wBAAwB;AACvD,SAASC,gCAAgC,QAAQ,6BAA6B;AAE9E,SACEC,kBAAkB,EAClBC,uBAAuB,QAClB,wBAAwB;AAC/B,SAASC,mBAAmB,QAAQ,cAAc;AAElD,OAAO,MAAMC,eAAehB,sBAAsB;IAChDiB,IAAI;WAAIF;WAAwBD;KAAwB;AAC1D,GAAG;AAEH,OAAO,MAAMI,wBAAyCV,iBACpD,YAAYW,QAAQ,EACpB;AAEF;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,qCAAqC;IAChDC,2BAA2B;IAC3BC,YAAY;AACd,EAAE;AAEF,8EAA8E;AAC9E,8EAA8E;AAC9E,4CAA4C;AAC5C,MA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AAc,EAAEI,MAAMR;QACxD;QAEA,8EAA8E;QAC9EN,OAAOe,OAAO,GAAG;YACf;gBACEC,QAAQ;gBACRpB,SAAS;oBACPqB,WAAW;wBACTC,YAAY;oBACd;oBACAL,OAAO;wBACLK,YAAY;wBACZC,YAAY;wBACZC,eAAe;wBACfC,eAAe;oBACjB;gBACF;YACF;eACG,AAACrB,CAAAA,OAAOe,OAAO,IAAI,EAAE,AAAD,EAAGZ,MAAM,CAC9B,CAACmB,IAAM,OAAOA,MAAM,YAAYA,EAAEN,MAAM,KAAK;SAEhD;QAED,OAAOhB;IACT;IAEA,MAAMpD,gCAAgCsB,MAAM;QAACP;KAAsB;IAEnE,MAAMjB,qBAAqBwB;IAE3B,mFAAmF;IACnF,uEAAuE;IACvE,8EAA8E;IAC9E,OAAO,IACLvB,oBAAoBuB,MAAMC,OAAOoD,yBAAyB,EAAE;YAC1DC,WAAW;gBAAC;aAAa;QAC3B;AACJ,EAAE;AACF,eAAe7C,mBAAmB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/lib/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n type NxJsonConfiguration,\n OverwriteStrategy,\n readProjectConfiguration,\n type TargetConfiguration,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { libraryGenerator } from '@nx/js';\nimport { declareDependencies } from '../../utils/declared-dependencies.js';\nimport { formatFilesInSubtree } from '../../utils/format.js';\nimport { installDependencies } from '../../utils/install.js';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics.js';\nimport { isEsmWorkspace } from '../../utils/module-format.js';\nimport { toKebabCase } from '../../utils/names.js';\nimport { getNpmScopePrefix } from '../../utils/npm-scope.js';\nimport {\n addGeneratorMetadata,\n getGeneratorInfo,\n mergeTarget,\n mergeTargetDefault,\n type NxGeneratorInfo,\n projectExists,\n} from '../../utils/nx.js';\nimport { sortObjectKeys } from '../../utils/object.js';\nimport { getPackageManagerDisplayCommands } from '../../utils/pkg-manager.js';\nimport type { TsProjectGeneratorSchema } from './schema';\nimport {\n configureTsProject,\n TS_PROJECT_DEPENDENCIES,\n} from './ts-project-utils.js';\nimport { VITEST_DEPENDENCIES } from './vitest.js';\n\nexport const DEPENDENCIES = declareDependencies()({\n ts: [...VITEST_DEPENDENCIES, ...TS_PROJECT_DEPENDENCIES],\n});\n\nexport const TS_LIB_GENERATOR_INFO: NxGeneratorInfo = getGeneratorInfo(\n import.meta.filename,\n);\n\n/**\n * Consumes build artifacts produced by a project's dependencies, so a task\n * re-runs when the output it actually reads changes.\n *\n * Test reports are excluded rather than build artifacts included: several\n * generators emit generated sources outside `dist` (an OpenAPI client under a\n * website's `src/generated`, a Smithy SSDK, the Prisma client) and add them to\n * `.gitignore`, which keeps them out of the project's own fileset — so this\n * input is the only thing that hashes them. `reports/` and `coverage/` hold\n * pytest's JUnit and coverage XML, which carry a wall-clock timestamp and so\n * mint a fresh hash on every test run that would cascade through the graph.\n */\nexport const DEPENDENT_TASKS_OUTPUT_FILES_INPUT = {\n dependentTasksOutputFiles: '!{reports,coverage}/**',\n transitive: true,\n};\n\n// Globs this generator has vended for the dependent-task-output input. Any of\n// them is replaced in place, so the entry is neither duplicated nor left at a\n// different scope when a generator re-runs.\nconst VENDED_DEPENDENT_TASKS_OUTPUT_GLOBS = [\n '**/*',\n 'dist/**',\n DEPENDENT_TASKS_OUTPUT_FILES_INPUT.dependentTasksOutputFiles,\n];\n\nexport interface TsLibDetails {\n /**\n * Full package name including scope (eg @foo/bar)\n */\n readonly fullyQualifiedName: string;\n /**\n * Directory of the library relative to the root\n */\n readonly dir: string;\n}\n\n/**\n * Returns details about the TS library to be created\n */\nexport const getTsLibDetails = (\n tree: Tree,\n schema: TsProjectGeneratorSchema,\n): TsLibDetails => {\n const scope = getNpmScopePrefix(tree);\n const normalizedName = toKebabCase(schema.name);\n const fullyQualifiedName = `${scope}${normalizedName}`;\n // NB: interactive nx generator cli can pass empty string\n const dir = joinPathFragments(\n schema.directory || '.',\n schema.subDirectory || normalizedName,\n );\n return { dir, fullyQualifiedName };\n};\n\n/**\n * Generates a typescript project\n */\nexport const tsProjectGenerator = async (\n tree: Tree,\n schema: TsProjectGeneratorSchema,\n): Promise<GeneratorCallback> => {\n const { fullyQualifiedName, dir } = getTsLibDetails(tree, schema);\n // The module format is workspace-wide, established by the preset when the\n // workspace is created, so vending generators always infer it from the tree.\n const esm = isEsmWorkspace(tree);\n\n // Only scaffold the project on first run; on re-run skip creation so user\n // edits are preserved, but continue to (re)apply the configuration below.\n if (!projectExists(tree, fullyQualifiedName)) {\n await libraryGenerator(tree, {\n ...schema,\n name: fullyQualifiedName,\n directory: dir,\n skipPackageJson: true,\n bundler: 'tsc', // TODO: consider supporting others\n linter: 'none',\n unitTestRunner: 'vitest',\n // Register the @nx/vitest plugin so the test target is inferred rather\n // than emitting the deprecated @nx/vitest:test executor target.\n addPlugin: true,\n });\n\n // Replace with simpler sample source code\n tree.delete(joinPathFragments(dir, 'src'));\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files'),\n joinPathFragments(dir),\n {\n fullyQualifiedName,\n esm,\n pkgMgrCmd: getPackageManagerDisplayCommands().exec,\n },\n {\n overwriteStrategy: OverwriteStrategy.KeepExisting,\n },\n );\n }\n await configureTsProject(\n tree,\n {\n dir,\n fullyQualifiedName,\n esm,\n },\n DEPENDENCIES,\n );\n\n const projectConfiguration = readProjectConfiguration(\n tree,\n fullyQualifiedName,\n );\n const targets = projectConfiguration.targets;\n\n // Merged rather than assigned so a re-run converges this generator's own\n // configuration without discarding what other generators contributed to the\n // same targets — the `bundle` that ts#lambda-function adds to build and\n // assemble, say, which those targets must keep depending on.\n targets['compile'] = mergeTarget(targets['compile'], {\n executor: 'nx:run-commands',\n outputs: ['{workspaceRoot}/dist/{projectRoot}/tsc'],\n options: {\n command: 'tsc --build tsconfig.lib.json',\n cwd: '{projectRoot}',\n },\n });\n targets['build'] = mergeTarget(targets['build'], {\n dependsOn: ['lint', 'compile', 'test'],\n });\n // The artifact-only sibling of build, which the deploy targets depend on.\n targets['assemble'] = mergeTarget(targets['assemble'], {\n dependsOn: ['compile'],\n });\n projectConfiguration.targets = sortObjectKeys(targets);\n\n updateProjectConfiguration(tree, fullyQualifiedName, projectConfiguration);\n\n addGeneratorMetadata(tree, fullyQualifiedName, TS_LIB_GENERATOR_INFO);\n\n updateJson(tree, 'nx.json', (nxJson: NxJsonConfiguration) => {\n nxJson.namedInputs = {\n ...nxJson.namedInputs,\n default: [\n ...(nxJson.namedInputs?.default ?? []).filter(\n (input) =>\n typeof input !== 'object' ||\n !('dependentTasksOutputFiles' in input) ||\n !(\n VENDED_DEPENDENT_TASKS_OUTPUT_GLOBS.includes(\n input.dependentTasksOutputFiles as string,\n ) && input.transitive\n ),\n ),\n DEPENDENT_TASKS_OUTPUT_FILES_INPUT,\n ],\n };\n\n const withDefaultInput = (base: Partial<TargetConfiguration>) => ({\n ...base,\n inputs: [\n ...(base.inputs ?? []).filter((i) => i !== 'default'),\n 'default',\n ],\n });\n\n nxJson.targetDefaults = {\n ...nxJson.targetDefaults,\n compile: mergeTargetDefault(nxJson.targetDefaults?.compile, (base) => ({\n cache: true,\n ...withDefaultInput(base),\n })),\n build: mergeTargetDefault(nxJson.targetDefaults?.build, (base) => ({\n cache: true,\n ...withDefaultInput(base),\n })),\n test: mergeTargetDefault(nxJson.targetDefaults?.test, withDefaultInput),\n };\n\n // Ensure we only declare a single typescript plugin with the correct settings\n nxJson.plugins = [\n {\n plugin: '@nx/js/typescript',\n options: {\n typecheck: {\n targetName: 'typecheck',\n },\n build: {\n targetName: 'compile',\n configName: 'tsconfig.lib.json',\n buildDepsName: 'build-deps',\n watchDepsName: 'watch-deps',\n },\n },\n },\n ...(nxJson.plugins ?? []).filter(\n (p) => typeof p === 'string' || p.plugin !== '@nx/js/typescript',\n ),\n ];\n\n return nxJson;\n });\n\n await addGeneratorMetricsIfApplicable(tree, [TS_LIB_GENERATOR_INFO]);\n\n await formatFilesInSubtree(tree);\n\n // `installDependencies` ensures vitest resolves for the `typescript` language (the\n // generated vitest.config.mts imports it and Nx loads that config when\n // computing the project graph), so a deferred install still runs when needed.\n return () =>\n installDependencies(tree, schema.preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\nexport default tsProjectGenerator;\n"],"names":["generateFiles","joinPathFragments","OverwriteStrategy","readProjectConfiguration","updateJson","updateProjectConfiguration","libraryGenerator","declareDependencies","formatFilesInSubtree","installDependencies","addGeneratorMetricsIfApplicable","isEsmWorkspace","toKebabCase","getNpmScopePrefix","addGeneratorMetadata","getGeneratorInfo","mergeTarget","mergeTargetDefault","projectExists","sortObjectKeys","getPackageManagerDisplayCommands","configureTsProject","TS_PROJECT_DEPENDENCIES","VITEST_DEPENDENCIES","DEPENDENCIES","ts","TS_LIB_GENERATOR_INFO","filename","DEPENDENT_TASKS_OUTPUT_FILES_INPUT","dependentTasksOutputFiles","transitive","VENDED_DEPENDENT_TASKS_OUTPUT_GLOBS","getTsLibDetails","tree","schema","scope","normalizedName","name","fullyQualifiedName","dir","directory","subDirectory","tsProjectGenerator","esm","skipPackageJson","bundler","linter","unitTestRunner","addPlugin","delete","dirname","pkgMgrCmd","exec","overwriteStrategy","KeepExisting","projectConfiguration","targets","executor","outputs","options","command","cwd","dependsOn","nxJson","namedInputs","default","filter","input","includes","withDefaultInput","base","inputs","i","targetDefaults","compile","cache","build","test","plugins","plugin","typecheck","targetName","configName","buildDepsName","watchDepsName","p","preferInstallDependencies","languages"],"mappings":"AAAA;;;CAGC,GACD,SAEEA,aAAa,EACbC,iBAAiB,EAEjBC,iBAAiB,EACjBC,wBAAwB,EAGxBC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAASC,gBAAgB,QAAQ,SAAS;AAC1C,SAASC,mBAAmB,QAAQ,uCAAuC;AAC3E,S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YA,EAAEN,MAAM,KAAK;SAEhD;QAED,OAAOhB;IACT;IAEA,MAAMrD,gCAAgCuB,MAAM;QAACP;KAAsB;IAEnE,MAAMlB,qBAAqByB;IAE3B,mFAAmF;IACnF,uEAAuE;IACvE,8EAA8E;IAC9E,OAAO,IACLxB,oBAAoBwB,MAAMC,OAAOoD,yBAAyB,EAAE;YAC1DC,WAAW;gBAAC;aAAa;QAC3B;AACJ,EAAE;AACF,eAAe7C,mBAAmB"}
|
|
@@ -31,6 +31,20 @@ export declare const TS_PROJECT_DEPENDENCIES: readonly [{
|
|
|
31
31
|
* generator neither duplicates nor reorders references.
|
|
32
32
|
*/
|
|
33
33
|
export declare const mergeTsReferences: (existing: TsConfigReference[] | undefined, toAdd: TsConfigReference[]) => TsConfigReference[];
|
|
34
|
+
/**
|
|
35
|
+
* Merges a reference to another project's directory into existing TypeScript
|
|
36
|
+
* project references, treating any reference that resolves inside that
|
|
37
|
+
* directory as the same reference.
|
|
38
|
+
*
|
|
39
|
+
* `nx sync` rewrites a reference to a project's `tsconfig.json` into the
|
|
40
|
+
* specific `tsconfig.lib.json` it resolves to, so matching on the exact path
|
|
41
|
+
* alone would append a second reference to the same project on every re-run —
|
|
42
|
+
* which leaves the workspace out of sync and fails the next `build`.
|
|
43
|
+
*
|
|
44
|
+
* `projectDirRef` is the referenced project's directory, relative to the
|
|
45
|
+
* tsconfig being updated (eg `../common/shadcn`).
|
|
46
|
+
*/
|
|
47
|
+
export declare const mergeTsProjectDirReference: (existing: TsConfigReference[] | undefined, projectDirRef: string) => TsConfigReference[];
|
|
34
48
|
/**
|
|
35
49
|
* Updates typescript projects
|
|
36
50
|
*/
|
|
@@ -46,6 +46,30 @@ import { configureVitest } from "./vitest.js";
|
|
|
46
46
|
}
|
|
47
47
|
return references;
|
|
48
48
|
};
|
|
49
|
+
/**
|
|
50
|
+
* Merges a reference to another project's directory into existing TypeScript
|
|
51
|
+
* project references, treating any reference that resolves inside that
|
|
52
|
+
* directory as the same reference.
|
|
53
|
+
*
|
|
54
|
+
* `nx sync` rewrites a reference to a project's `tsconfig.json` into the
|
|
55
|
+
* specific `tsconfig.lib.json` it resolves to, so matching on the exact path
|
|
56
|
+
* alone would append a second reference to the same project on every re-run —
|
|
57
|
+
* which leaves the workspace out of sync and fails the next `build`.
|
|
58
|
+
*
|
|
59
|
+
* `projectDirRef` is the referenced project's directory, relative to the
|
|
60
|
+
* tsconfig being updated (eg `../common/shadcn`).
|
|
61
|
+
*/ export const mergeTsProjectDirReference = (existing, projectDirRef)=>{
|
|
62
|
+
const references = [
|
|
63
|
+
...existing ?? []
|
|
64
|
+
];
|
|
65
|
+
const alreadyReferenced = references.some((ref)=>ref.path === projectDirRef || ref.path.startsWith(`${projectDirRef}/tsconfig`));
|
|
66
|
+
return alreadyReferenced ? references : [
|
|
67
|
+
...references,
|
|
68
|
+
{
|
|
69
|
+
path: `${projectDirRef}/tsconfig.json`
|
|
70
|
+
}
|
|
71
|
+
];
|
|
72
|
+
};
|
|
49
73
|
/**
|
|
50
74
|
* Updates typescript projects
|
|
51
75
|
*/ export const configureTsProject = async (tree, options, declaration)=>{
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/lib/ts-project-utils.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { joinPathFragments, logger, type Tree, updateJson } from '@nx/devkit';\nimport { join, relative } from 'path';\nimport { addLicenseCheckToLintTarget } from '../../license/config.js';\nimport { addTsDependencies } from '../../utils/add-dependencies.js';\nimport { AWS_NX_PLUGIN_CONFIG_FILE_NAME } from '../../utils/config/utils.js';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n} from '../../utils/declared-dependencies.js';\nimport { isEsmWorkspace } from '../../utils/module-format.js';\nimport { ensureProjectPackageJson } from '../../utils/project-package-json.js';\nimport type { ITsDepVersion } from '../../utils/versions.js';\nimport { configureBiomeLint } from './biome.js';\nimport type { ConfigureProjectOptions } from './types.js';\nimport { configureVitest, type VITEST_DEPENDENCIES } from './vitest.js';\n\ninterface TsConfigReference {\n path: string;\n}\n\n/**\n * Dependencies a caller must declare to configure a TypeScript project.\n *\n * `@nx/js` writes `types: ['node']` into every project's `tsconfig.lib.json`, so\n * the types must be declared for `tsc` to resolve them. Declared twice: on the\n * project whose tsconfig names them, and at the root, which `@nx/js` seeded until\n * Nx 23.2 stopped.\n */\nexport const TS_PROJECT_DEPENDENCIES = [\n { name: '@types/node', dev: true },\n { name: '@types/node', dev: true, root: true },\n] as const satisfies readonly {\n name: ITsDepVersion;\n dev?: boolean;\n root?: boolean;\n}[];\n\n/**\n * Merges new TypeScript project references into existing ones, deduplicating by\n * path and preserving the order of existing references so re-running a\n * generator neither duplicates nor reorders references.\n */\nexport const mergeTsReferences = (\n existing: TsConfigReference[] | undefined,\n toAdd: TsConfigReference[],\n): TsConfigReference[] => {\n const references = [...(existing ?? [])];\n const existingPaths = new Set(references.map((ref) => ref.path));\n for (const ref of toAdd) {\n if (!existingPaths.has(ref.path)) {\n references.push(ref);\n existingPaths.add(ref.path);\n }\n }\n return references;\n};\n\n/**\n * Updates typescript projects\n */\nexport const configureTsProject = async <const D extends DependencyDeclaration>(\n tree: Tree,\n options: ConfigureProjectOptions,\n declaration: D &\n MustDeclare<typeof VITEST_DEPENDENCIES, D> &\n MustDeclare<typeof TS_PROJECT_DEPENDENCIES, D>,\n) => {\n // Point users at init when the workspace hasn't been configured, since\n // lint/format targets and workspace dependency sync depend on it.\n if (!tree.exists(AWS_NX_PLUGIN_CONFIG_FILE_NAME)) {\n logger.warn(\n `This workspace has no ${AWS_NX_PLUGIN_CONFIG_FILE_NAME} — run 'nx g @aws/nx-plugin:init' (or 'nx add @aws/nx-plugin') to configure linting, formatting and workspace dependency sync.`,\n );\n }\n\n // When the caller doesn't specify a module format, infer it from the\n // workspace root package.json (defaulting to ESM for a fresh workspace).\n const esm = options.esm ?? isEsmWorkspace(tree);\n\n // Remove a conflicting `module: commonjs` from the project tsconfig.json\n // (CommonJS is configured on tsconfig.lib.json below when needed).\n updateJson(tree, join(options.dir, 'tsconfig.json'), (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n module:\n tsConfig.compilerOptions?.module === 'commonjs'\n ? undefined\n : tsConfig.compilerOptions?.module,\n },\n }));\n const outDirToRootRelativePath = relative(\n join(tree.root, options.dir),\n tree.root,\n );\n const distDir = join(outDirToRootRelativePath, 'dist', options.dir, 'tsc');\n // Remove baseUrl and rootDir from the tsconfig.lib.json\n if (tree.exists(join(options.dir, 'tsconfig.lib.json'))) {\n updateJson(tree, join(options.dir, 'tsconfig.lib.json'), (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n baseUrl: undefined,\n rootDir: '.',\n outDir: distDir,\n tsBuildInfoFile: join(distDir, 'tsconfig.lib.tsbuildinfo'),\n // @nx/js configures the lib for ESM (module `nodenext`). CommonJS\n // projects use `node16`, which honours the workspace's\n // `type: commonjs`, emits CommonJS and resolves extensionless relative\n // imports. (Plain `commonjs`/`node` is deprecated in TypeScript 6.)\n ...(esm ? {} : { module: 'node16', moduleResolution: 'node16' }),\n },\n }));\n }\n // Update root project tsconfig\n updateJson(tree, 'tsconfig.base.json', (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n // baseUrl is deprecated in TypeScript 6 — use ./ prefix in paths instead\n baseUrl: undefined,\n rootDir: '.',\n paths: {\n ...tsConfig.compilerOptions?.paths,\n [options.fullyQualifiedName]: [\n `./${joinPathFragments(options.dir, 'src', 'index.ts')}`,\n ],\n },\n },\n }));\n if (tree.exists('tsconfig.json')) {\n updateJson(tree, 'tsconfig.json', (tsConfig) => ({\n ...tsConfig,\n // Add project references, deduplicating and preserving existing order\n references: mergeTsReferences(tsConfig.references, [\n { path: `./${options.dir}` },\n ]),\n }));\n }\n // Every project carries a minimal private package.json so the workspace\n // follows the standard npm package layout (see ensureProjectPackageJson).\n ensureProjectPackageJson(tree, {\n dir: options.dir,\n fullyQualifiedName: options.fullyQualifiedName,\n esm,\n });\n\n // From this helper's constant, not the caller's declaration, which marks these\n // `ownedElsewhere` because the install happens here.\n addTsDependencies(\n tree,\n { ts: [...TS_PROJECT_DEPENDENCIES], py: [] },\n { projectRoot: options.dir },\n );\n\n await configureBiomeLint(tree, options);\n await configureVitest(\n tree,\n options,\n forDependencies<typeof VITEST_DEPENDENCIES>(declaration),\n );\n\n // If license checking is configured, make this project's lint target depend\n // on the root license-check target. No-op if there's no license-check target\n // (i.e. the license generator hasn't run); the license generator wires up\n // existing projects itself, so this works regardless of generator order.\n addLicenseCheckToLintTarget(tree, options.fullyQualifiedName);\n};\n"],"names":["joinPathFragments","logger","updateJson","join","relative","addLicenseCheckToLintTarget","addTsDependencies","AWS_NX_PLUGIN_CONFIG_FILE_NAME","forDependencies","isEsmWorkspace","ensureProjectPackageJson","configureBiomeLint","configureVitest","TS_PROJECT_DEPENDENCIES","name","dev","root","mergeTsReferences","existing","toAdd","references","existingPaths","Set","map","ref","path","has","push","add","configureTsProject","tree","options","declaration","exists","warn","esm","dir","tsConfig","compilerOptions","module","undefined","outDirToRootRelativePath","distDir","baseUrl","rootDir","outDir","tsBuildInfoFile","moduleResolution","paths","fullyQualifiedName","ts","py","projectRoot"],"mappings":"AAAA;;;CAGC,GACD,SAASA,iBAAiB,EAAEC,MAAM,EAAaC,UAAU,QAAQ,aAAa;AAC9E,SAASC,IAAI,EAAEC,QAAQ,QAAQ,OAAO;AACtC,SAASC,2BAA2B,QAAQ,0BAA0B;AACtE,SAASC,iBAAiB,QAAQ,kCAAkC;AACpE,SAASC,8BAA8B,QAAQ,8BAA8B;AAC7E,SAEEC,eAAe,QAEV,uCAAuC;AAC9C,SAASC,cAAc,QAAQ,+BAA+B;AAC9D,SAASC,wBAAwB,QAAQ,sCAAsC;AAE/E,SAASC,kBAAkB,QA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G;QAChBa,oBAAoBlB,QAAQkB,kBAAkB;QAC9Cd;IACF;IAEA,+EAA+E;IAC/E,qDAAqD;IACrD7B,kBACEwB,MACA;QAAEoB,IAAI;eAAIrC;SAAwB;QAAEsC,IAAI,EAAE;IAAC,GAC3C;QAAEC,aAAarB,QAAQK,GAAG;IAAC;IAG7B,MAAMzB,mBAAmBmB,MAAMC;IAC/B,MAAMnB,gBACJkB,MACAC,SACAvB,gBAA4CwB;IAG9C,4EAA4E;IAC5E,6EAA6E;IAC7E,0EAA0E;IAC1E,yEAAyE;IACzE3B,4BAA4ByB,MAAMC,QAAQkB,kBAAkB;AAC9D,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/lib/ts-project-utils.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport { joinPathFragments, logger, type Tree, updateJson } from '@nx/devkit';\nimport { join, relative } from 'path';\nimport { addLicenseCheckToLintTarget } from '../../license/config.js';\nimport { addTsDependencies } from '../../utils/add-dependencies.js';\nimport { AWS_NX_PLUGIN_CONFIG_FILE_NAME } from '../../utils/config/utils.js';\nimport {\n type DependencyDeclaration,\n forDependencies,\n type MustDeclare,\n} from '../../utils/declared-dependencies.js';\nimport { isEsmWorkspace } from '../../utils/module-format.js';\nimport { ensureProjectPackageJson } from '../../utils/project-package-json.js';\nimport type { ITsDepVersion } from '../../utils/versions.js';\nimport { configureBiomeLint } from './biome.js';\nimport type { ConfigureProjectOptions } from './types.js';\nimport { configureVitest, type VITEST_DEPENDENCIES } from './vitest.js';\n\ninterface TsConfigReference {\n path: string;\n}\n\n/**\n * Dependencies a caller must declare to configure a TypeScript project.\n *\n * `@nx/js` writes `types: ['node']` into every project's `tsconfig.lib.json`, so\n * the types must be declared for `tsc` to resolve them. Declared twice: on the\n * project whose tsconfig names them, and at the root, which `@nx/js` seeded until\n * Nx 23.2 stopped.\n */\nexport const TS_PROJECT_DEPENDENCIES = [\n { name: '@types/node', dev: true },\n { name: '@types/node', dev: true, root: true },\n] as const satisfies readonly {\n name: ITsDepVersion;\n dev?: boolean;\n root?: boolean;\n}[];\n\n/**\n * Merges new TypeScript project references into existing ones, deduplicating by\n * path and preserving the order of existing references so re-running a\n * generator neither duplicates nor reorders references.\n */\nexport const mergeTsReferences = (\n existing: TsConfigReference[] | undefined,\n toAdd: TsConfigReference[],\n): TsConfigReference[] => {\n const references = [...(existing ?? [])];\n const existingPaths = new Set(references.map((ref) => ref.path));\n for (const ref of toAdd) {\n if (!existingPaths.has(ref.path)) {\n references.push(ref);\n existingPaths.add(ref.path);\n }\n }\n return references;\n};\n\n/**\n * Merges a reference to another project's directory into existing TypeScript\n * project references, treating any reference that resolves inside that\n * directory as the same reference.\n *\n * `nx sync` rewrites a reference to a project's `tsconfig.json` into the\n * specific `tsconfig.lib.json` it resolves to, so matching on the exact path\n * alone would append a second reference to the same project on every re-run —\n * which leaves the workspace out of sync and fails the next `build`.\n *\n * `projectDirRef` is the referenced project's directory, relative to the\n * tsconfig being updated (eg `../common/shadcn`).\n */\nexport const mergeTsProjectDirReference = (\n existing: TsConfigReference[] | undefined,\n projectDirRef: string,\n): TsConfigReference[] => {\n const references = [...(existing ?? [])];\n const alreadyReferenced = references.some(\n (ref) =>\n ref.path === projectDirRef ||\n ref.path.startsWith(`${projectDirRef}/tsconfig`),\n );\n return alreadyReferenced\n ? references\n : [...references, { path: `${projectDirRef}/tsconfig.json` }];\n};\n\n/**\n * Updates typescript projects\n */\nexport const configureTsProject = async <const D extends DependencyDeclaration>(\n tree: Tree,\n options: ConfigureProjectOptions,\n declaration: D &\n MustDeclare<typeof VITEST_DEPENDENCIES, D> &\n MustDeclare<typeof TS_PROJECT_DEPENDENCIES, D>,\n) => {\n // Point users at init when the workspace hasn't been configured, since\n // lint/format targets and workspace dependency sync depend on it.\n if (!tree.exists(AWS_NX_PLUGIN_CONFIG_FILE_NAME)) {\n logger.warn(\n `This workspace has no ${AWS_NX_PLUGIN_CONFIG_FILE_NAME} — run 'nx g @aws/nx-plugin:init' (or 'nx add @aws/nx-plugin') to configure linting, formatting and workspace dependency sync.`,\n );\n }\n\n // When the caller doesn't specify a module format, infer it from the\n // workspace root package.json (defaulting to ESM for a fresh workspace).\n const esm = options.esm ?? isEsmWorkspace(tree);\n\n // Remove a conflicting `module: commonjs` from the project tsconfig.json\n // (CommonJS is configured on tsconfig.lib.json below when needed).\n updateJson(tree, join(options.dir, 'tsconfig.json'), (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n module:\n tsConfig.compilerOptions?.module === 'commonjs'\n ? undefined\n : tsConfig.compilerOptions?.module,\n },\n }));\n const outDirToRootRelativePath = relative(\n join(tree.root, options.dir),\n tree.root,\n );\n const distDir = join(outDirToRootRelativePath, 'dist', options.dir, 'tsc');\n // Remove baseUrl and rootDir from the tsconfig.lib.json\n if (tree.exists(join(options.dir, 'tsconfig.lib.json'))) {\n updateJson(tree, join(options.dir, 'tsconfig.lib.json'), (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n baseUrl: undefined,\n rootDir: '.',\n outDir: distDir,\n tsBuildInfoFile: join(distDir, 'tsconfig.lib.tsbuildinfo'),\n // @nx/js configures the lib for ESM (module `nodenext`). CommonJS\n // projects use `node16`, which honours the workspace's\n // `type: commonjs`, emits CommonJS and resolves extensionless relative\n // imports. (Plain `commonjs`/`node` is deprecated in TypeScript 6.)\n ...(esm ? {} : { module: 'node16', moduleResolution: 'node16' }),\n },\n }));\n }\n // Update root project tsconfig\n updateJson(tree, 'tsconfig.base.json', (tsConfig) => ({\n ...tsConfig,\n compilerOptions: {\n ...tsConfig.compilerOptions,\n // baseUrl is deprecated in TypeScript 6 — use ./ prefix in paths instead\n baseUrl: undefined,\n rootDir: '.',\n paths: {\n ...tsConfig.compilerOptions?.paths,\n [options.fullyQualifiedName]: [\n `./${joinPathFragments(options.dir, 'src', 'index.ts')}`,\n ],\n },\n },\n }));\n if (tree.exists('tsconfig.json')) {\n updateJson(tree, 'tsconfig.json', (tsConfig) => ({\n ...tsConfig,\n // Add project references, deduplicating and preserving existing order\n references: mergeTsReferences(tsConfig.references, [\n { path: `./${options.dir}` },\n ]),\n }));\n }\n // Every project carries a minimal private package.json so the workspace\n // follows the standard npm package layout (see ensureProjectPackageJson).\n ensureProjectPackageJson(tree, {\n dir: options.dir,\n fullyQualifiedName: options.fullyQualifiedName,\n esm,\n });\n\n // From this helper's constant, not the caller's declaration, which marks these\n // `ownedElsewhere` because the install happens here.\n addTsDependencies(\n tree,\n { ts: [...TS_PROJECT_DEPENDENCIES], py: [] },\n { projectRoot: options.dir },\n );\n\n await configureBiomeLint(tree, options);\n await configureVitest(\n tree,\n options,\n forDependencies<typeof VITEST_DEPENDENCIES>(declaration),\n );\n\n // If license checking is configured, make this project's lint target depend\n // on the root license-check target. No-op if there's no license-check target\n // (i.e. the license generator hasn't run); the license generator wires up\n // existing projects itself, so this works regardless of generator order.\n addLicenseCheckToLintTarget(tree, options.fullyQualifiedName);\n};\n"],"names":["joinPathFragments","logger","updateJson","join","relative","addLicenseCheckToLintTarget","addTsDependencies","AWS_NX_PLUGIN_CONFIG_FILE_NAME","forDependencies","isEsmWorkspace","ensureProjectPackageJson","configureBiomeLint","configureVitest","TS_PROJECT_DEPENDENCIES","name","dev","root","mergeTsReferences","existing","toAdd","references","existingPaths","Set","map","ref","path","has","push","add","mergeTsProjectDirReference","projectDirRef","alreadyReferenced","some","startsWith","configureTsProject","tree","options","declaration","exists","warn","esm","dir","tsConfig","compilerOptions","module","undefined","outDirToRootRelativePath","distDir","baseUrl","rootDir","outDir","tsBuildInfoFile","moduleResolution","paths","fullyQualifiedName","ts","py","projectRoot"],"mappings":"AAAA;;;CAGC,GACD,SAASA,iBAAiB,EAAEC,MAAM,EAAaC,UAAU,QAAQ,aAAa;AAC9E,SAASC,IAAI,EAAEC,QAAQ,QAAQ,OAAO;A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,eAAe;gBAC3B,yEAAyE;gBACzEK,SAASH;gBACTI,SAAS;gBACTI,OAAO;oBACL,GAAGX,SAASC,eAAe,EAAEU,KAAK;oBAClC,CAACjB,QAAQkB,kBAAkB,CAAC,EAAE;wBAC5B,CAAC,EAAE,EAAEtD,kBAAkBoC,QAAQK,GAAG,EAAE,OAAO,aAAa;qBACzD;gBACH;YACF;QACF,CAAA;IACA,IAAIN,KAAKG,MAAM,CAAC,kBAAkB;QAChCpC,WAAWiC,MAAM,iBAAiB,CAACO,WAAc,CAAA;gBAC/C,GAAGA,QAAQ;gBACX,sEAAsE;gBACtEtB,YAAYH,kBAAkByB,SAAStB,UAAU,EAAE;oBACjD;wBAAEK,MAAM,CAAC,EAAE,EAAEW,QAAQK,GAAG,EAAE;oBAAC;iBAC5B;YACH,CAAA;IACF;IACA,wEAAwE;IACxE,0EAA0E;IAC1E/B,yBAAyByB,MAAM;QAC7BM,KAAKL,QAAQK,GAAG;QAChBa,oBAAoBlB,QAAQkB,kBAAkB;QAC9Cd;IACF;IAEA,+EAA+E;IAC/E,qDAAqD;IACrDlC,kBACE6B,MACA;QAAEoB,IAAI;eAAI1C;SAAwB;QAAE2C,IAAI,EAAE;IAAC,GAC3C;QAAEC,aAAarB,QAAQK,GAAG;IAAC;IAG7B,MAAM9B,mBAAmBwB,MAAMC;IAC/B,MAAMxB,gBACJuB,MACAC,SACA5B,gBAA4C6B;IAG9C,4EAA4E;IAC5E,6EAA6E;IAC7E,0EAA0E;IAC1E,yEAAyE;IACzEhC,4BAA4B8B,MAAMC,QAAQkB,kBAAkB;AAC9D,EAAE"}
|
|
@@ -17,7 +17,7 @@ import { addGeneratorMetricsIfApplicable } from "../../utils/metrics.js";
|
|
|
17
17
|
import { isEsmWorkspace } from "../../utils/module-format.js";
|
|
18
18
|
import { kebabCase, toClassName } from "../../utils/names.js";
|
|
19
19
|
import { getNpmScope } from "../../utils/npm-scope.js";
|
|
20
|
-
import { addArtifactDependencyToTargets, addComponentDevTarget, addComponentGeneratorMetadata, addDependencyToTargetIfNotPresent, getGeneratorInfo, readProjectConfigurationUnqualified } from "../../utils/nx.js";
|
|
20
|
+
import { addArtifactDependencyToTargets, addComponentDevTarget, addComponentGeneratorMetadata, addDependencyToTargetIfNotPresent, getGeneratorInfo, normalizeTargetKeyOrder, readProjectConfigurationUnqualified } from "../../utils/nx.js";
|
|
21
21
|
import { sortObjectKeys } from "../../utils/object.js";
|
|
22
22
|
import { registerPnpmBuiltDependencies } from "../../utils/pnpm-workspace.js";
|
|
23
23
|
import { assignPort } from "../../utils/port.js";
|
|
@@ -124,7 +124,7 @@ export const tsMcpServerGenerator = async (tree, options)=>{
|
|
|
124
124
|
});
|
|
125
125
|
const dockerTargetName = `${mcpTargetPrefix}-docker`;
|
|
126
126
|
const fs = new FsCommands(tree, DEPENDENCIES);
|
|
127
|
-
project.targets[dockerTargetName] = {
|
|
127
|
+
project.targets[dockerTargetName] = normalizeTargetKeyOrder({
|
|
128
128
|
cache: IMAGE_BUILD_CACHE,
|
|
129
129
|
executor: 'nx:run-commands',
|
|
130
130
|
options: {
|
|
@@ -137,7 +137,7 @@ export const tsMcpServerGenerator = async (tree, options)=>{
|
|
|
137
137
|
dependsOn: [
|
|
138
138
|
'bundle'
|
|
139
139
|
]
|
|
140
|
-
};
|
|
140
|
+
});
|
|
141
141
|
addDependencyToTargetIfNotPresent(project, 'docker', dockerTargetName);
|
|
142
142
|
addArtifactDependencyToTargets(project, 'docker');
|
|
143
143
|
addDockerScanTarget(tree, {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/mcp-server/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n detectPackageManager,\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readJson,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { addTsDependencies } from '../../utils/add-dependencies.js';\nimport {\n AGENT_CORE_CONSTRUCTS_PY_DEPENDENCIES,\n type AgentCoreArtifact,\n addMcpServerInfra,\n} from '../../utils/agent-core-constructs/agent-core-constructs.js';\nimport {\n addTypeScriptCodePackageTarget,\n agentCoreNodeRuntime,\n CODE_PACKAGE_DEPENDENCIES,\n isAgentCoreHosted,\n isContainerHosted,\n} from '../../utils/agent-core-packaging.js';\nimport {\n addTypeScriptBundleTarget,\n BUNDLE_DEPENDENCIES,\n} from '../../utils/bundle/bundle.js';\nimport { resolveContainers } from '../../utils/containers.js';\nimport {\n declareDependencies,\n ownedElsewhere,\n} from '../../utils/declared-dependencies.js';\nimport {\n ADOT_IMAGE_DEPENDENCIES,\n addDockerScanTarget,\n DOCKER_DEPENDENCIES,\n IMAGE_BUILD_CACHE,\n NODE_IMAGE_DEPENDENCIES,\n nodeImageVersions,\n} from '../../utils/docker.js';\nimport { formatFilesInSubtree } from '../../utils/format.js';\nimport { FS_DEPENDENCIES, FsCommands } from '../../utils/fs.js';\nimport { resolveIac } from '../../utils/iac.js';\nimport { installDependencies } from '../../utils/install.js';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics.js';\nimport { isEsmWorkspace } from '../../utils/module-format.js';\nimport { kebabCase, toClassName } from '../../utils/names.js';\nimport { getNpmScope } from '../../utils/npm-scope.js';\nimport {\n addArtifactDependencyToTargets,\n addComponentDevTarget,\n addComponentGeneratorMetadata,\n addDependencyToTargetIfNotPresent,\n getGeneratorInfo,\n type NxGeneratorInfo,\n readProjectConfigurationUnqualified,\n} from '../../utils/nx.js';\nimport { sortObjectKeys } from '../../utils/object.js';\nimport { registerPnpmBuiltDependencies } from '../../utils/pnpm-workspace.js';\nimport { assignPort } from '../../utils/port.js';\nimport {\n SHARED_CONSTRUCTS_DEPENDENCIES,\n sharedConstructsGenerator,\n} from '../../utils/shared-constructs.js';\nimport type { IacMetadata } from '../../utils/shared-constructs-constants.js';\nimport { BASE_IMAGES, TS_VERSIONS } from '../../utils/versions.js';\nimport type { TsMcpServerGeneratorSchema, TsMcpServerInfra } from './schema';\n\n/** The metadata this generator records, which its predicates read. */\nexport interface TsMcpServerMetadata extends IacMetadata {\n readonly port: number;\n readonly rc: string;\n readonly auth: string;\n /**\n * How this component is packaged and hosted, so a consumer can tell a\n * code-packaged runtime from a container-packaged one without re-deriving it.\n */\n readonly infra: TsMcpServerInfra;\n}\n\nexport const DEPENDENCIES = declareDependencies<TsMcpServerMetadata>()({\n ts: [\n { name: '@modelcontextprotocol/sdk' },\n { name: 'zod' },\n { name: 'express' },\n { name: '@aws-lambda-powertools/parameters' },\n { name: '@aws-sdk/client-appconfigdata' },\n { name: '@types/express', dev: true },\n // tsx (local dev) and the MCP inspector are shared tooling.\n { name: 'tsx', dev: true, root: true },\n { name: '@modelcontextprotocol/inspector', dev: true, root: true },\n ...ownedElsewhere(FS_DEPENDENCIES),\n ...ownedElsewhere(BUNDLE_DEPENDENCIES),\n ...ownedElsewhere(DOCKER_DEPENDENCIES),\n ...ownedElsewhere(SHARED_CONSTRUCTS_DEPENDENCIES),\n ...ownedElsewhere(NODE_IMAGE_DEPENDENCIES),\n ...ownedElsewhere(ADOT_IMAGE_DEPENDENCIES),\n ...ownedElsewhere(CODE_PACKAGE_DEPENDENCIES),\n ],\n py: ownedElsewhere(AGENT_CORE_CONSTRUCTS_PY_DEPENDENCIES),\n});\n\nexport const TS_MCP_SERVER_GENERATOR_INFO: NxGeneratorInfo = getGeneratorInfo(\n import.meta.filename,\n);\n\nexport const tsMcpServerGenerator = async (\n tree: Tree,\n options: TsMcpServerGeneratorSchema,\n): Promise<GeneratorCallback> => {\n const project = readProjectConfigurationUnqualified(tree, options.project);\n\n if (!tree.exists(joinPathFragments(project.root, 'tsconfig.json'))) {\n throw new Error(\n `Unsupported project ${options.project}. Expected a TypeScript project (with a tsconfig.json)`,\n );\n }\n\n const defaultName = `${kebabCase(project.name.split('/').pop())}-mcp-server`;\n const name = kebabCase(options.name || defaultName);\n const mcpServerNameClassName = toClassName(name);\n const mcpTargetPrefix = options.name ? name : 'mcp-server';\n const targetSourceDirRelativeToProjectRoot = joinPathFragments(\n 'src',\n mcpTargetPrefix,\n );\n const targetSourceDir = joinPathFragments(\n project.root,\n targetSourceDirRelativeToProjectRoot,\n );\n const relativeSourceDir = targetSourceDir.replace(project.root + '/', './');\n const distDir = joinPathFragments('dist', project.root);\n\n const infra = options.infra ?? 'agentcore';\n\n // Recorded in the metadata below so the version sync can tell a CDK\n // project from a Terraform one; undefined when no infrastructure was\n // generated, in which case neither provider's packages were added.\n const iac =\n infra !== 'none' ? await resolveIac(tree, options.iac) : undefined;\n\n if (infra === 'none' && options.auth && options.auth !== 'iam') {\n console.warn(\n 'Warning: auth is ignored when no infrastructure is configured (no infrastructure is generated)',\n );\n }\n\n const auth = options.auth ?? 'iam';\n\n const projectPackageJsonPath = joinPathFragments(\n project.root,\n 'package.json',\n );\n\n // Generate esm if the project's package.json is `type: module`, falling\n // back to the workspace format when the project has no manifest.\n const esm = tree.exists(projectPackageJsonPath)\n ? readJson(tree, projectPackageJsonPath).type === 'module'\n : isEsmWorkspace(tree);\n\n const templateContext = {\n name,\n esm,\n distDir,\n adotVersion:\n TS_VERSIONS['@aws/aws-distro-opentelemetry-node-autoinstrumentation'],\n jaegerVersion: TS_VERSIONS['@opentelemetry/propagator-jaeger'],\n nodeBaseImage: BASE_IMAGES.node,\n ...nodeImageVersions(),\n };\n\n // Generate example server\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'app'),\n targetSourceDir,\n templateContext,\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Add hosting based on infra\n if (isAgentCoreHosted(infra)) {\n const container = isContainerHosted(infra);\n const containers = await resolveContainers(tree, 'inherit');\n const dockerImageTag = `${getNpmScope(tree)}-${name}:latest`;\n\n // Add bundle target\n await addTypeScriptBundleTarget(\n tree,\n project,\n {\n targetFilePath: `${targetSourceDirRelativeToProjectRoot}/http.ts`,\n bundleOutputDir: joinPathFragments('mcp', name),\n },\n DEPENDENCIES,\n );\n\n const bundleOutputDir = joinPathFragments(\n 'dist',\n project.root,\n 'bundle',\n 'mcp',\n name,\n );\n\n let artifact: AgentCoreArtifact;\n\n if (container) {\n // Add the Dockerfile\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'deploy'),\n targetSourceDir,\n templateContext,\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n const dockerTargetName = `${mcpTargetPrefix}-docker`;\n\n const fs = new FsCommands(tree, DEPENDENCIES);\n project.targets[dockerTargetName] = {\n cache: IMAGE_BUILD_CACHE,\n executor: 'nx:run-commands',\n options: {\n commands: [\n fs.cpFile(\n `${targetSourceDir}/Dockerfile`,\n `${bundleOutputDir}/Dockerfile`,\n ),\n `${containers} build --platform linux/arm64 -t ${dockerImageTag} ${bundleOutputDir}`,\n ],\n parallel: false,\n },\n dependsOn: ['bundle'],\n };\n\n addDependencyToTargetIfNotPresent(project, 'docker', dockerTargetName);\n addArtifactDependencyToTargets(project, 'docker');\n\n addDockerScanTarget(\n tree,\n {\n project,\n containerEngine: containers,\n trivyTargetName: `${mcpTargetPrefix}-trivy`,\n dockerTargetName,\n imageTags: [dockerImageTag],\n },\n DEPENDENCIES,\n );\n\n artifact = {\n type: 'container',\n dockerImageTag,\n outputDir: bundleOutputDir,\n };\n } else {\n const packageOutputDir = joinPathFragments(\n 'dist',\n project.root,\n 'package',\n 'mcp',\n name,\n );\n addTypeScriptCodePackageTarget(\n tree,\n {\n project,\n targetName: `${mcpTargetPrefix}-package`,\n bundleTargetName: 'bundle',\n bundleOutputDir,\n packageOutputDir,\n },\n DEPENDENCIES,\n );\n\n artifact = {\n type: 'code',\n outputDir: packageOutputDir,\n runtime: agentCoreNodeRuntime(),\n entryPoint: 'index.js',\n };\n }\n\n // Add shared constructs\n await sharedConstructsGenerator(tree, { iac }, DEPENDENCIES);\n\n // Add the construct to deploy the mcp server\n await addMcpServerInfra(tree, {\n mcpServerNameKebabCase: name,\n mcpServerNameClassName,\n projectName: project.name,\n artifact,\n iac,\n auth,\n containers,\n });\n }\n\n // @modelcontextprotocol/sdk declares zod as a peer dependency with a wide range\n // (^3.25 || ^4.0). Yarn does not dedupe the peer to the workspace's pinned zod, so\n // without a resolution it installs a separate zod under the SDK's own node_modules.\n // The two zod copies have structurally incompatible types, which breaks type\n // inference for registerTool inputSchema. Scope the resolution to the SDK so\n // other consumers (e.g. @tanstack/router-generator pinning zod@3) are unaffected.\n // Classic yarn only honours the `**/`-prefixed descriptor in a workspace, and\n // berry only the bare one — it deletes a glob descriptor on install — so\n // declare both.\n if (detectPackageManager() === 'yarn') {\n updateJson(tree, 'package.json', (packageJson) => {\n packageJson.resolutions = {\n ...packageJson.resolutions,\n '**/@modelcontextprotocol/sdk/zod': TS_VERSIONS['zod'],\n '@modelcontextprotocol/sdk/zod': TS_VERSIONS['zod'],\n };\n return packageJson;\n });\n }\n\n const localDevPort = assignPort(tree, project, 8000, {\n component: { info: TS_MCP_SERVER_GENERATOR_INFO, name: mcpTargetPrefix },\n });\n\n // Recorded below and read by the declaration's predicates, so the packages\n // added here are exactly the ones the version sync will own.\n const metadata: TsMcpServerMetadata = {\n infra,\n port: localDevPort,\n rc: mcpServerNameClassName,\n auth,\n ...(iac ? { iac } : {}),\n };\n\n // The MCP inspector has a postinstall script that cascades installs into its\n // client packages, which no-ops when the package is installed as a dependency.\n // Register it as an explicitly-rejected build so pnpm 11's default\n // `strictDepBuilds=true` skips it instead of failing the install.\n registerPnpmBuiltDependencies(tree, {\n '@modelcontextprotocol/inspector': false,\n });\n\n addTsDependencies(tree, DEPENDENCIES, {\n metadata,\n projectRoot: project.root,\n });\n\n const mcpTargets = {\n ...project.targets,\n // Add targets for running the MCP server\n [`${mcpTargetPrefix}-serve-stdio`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/stdio.ts`],\n cwd: '{projectRoot}',\n },\n },\n [`${mcpTargetPrefix}-serve`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/http.ts`],\n cwd: '{projectRoot}',\n env: {\n PORT: `${localDevPort}`,\n },\n },\n },\n [`${mcpTargetPrefix}-dev`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/http.ts`],\n cwd: '{projectRoot}',\n env: {\n PORT: `${localDevPort}`,\n LOCAL_DEV: 'true',\n },\n },\n },\n [`${mcpTargetPrefix}-inspect`]: {\n executor: 'nx:run-commands',\n continuous: true,\n // Launch the inspector against the locally served HTTP server. The dev\n // target starts the server and any connected dependencies (e.g. a local\n // database).\n dependsOn: [`${mcpTargetPrefix}-dev`],\n options: {\n commands: [\n `mcp-inspector --transport http --server-url http://localhost:${localDevPort}/mcp`,\n ],\n cwd: '{projectRoot}',\n },\n },\n [`${mcpTargetPrefix}-inspect-stdio`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [\n `mcp-inspector -- tsx --watch ${relativeSourceDir}/stdio.ts`,\n ],\n cwd: '{projectRoot}',\n },\n },\n };\n\n // Aggregate `<mcp>-dev` under the project-level `dev` target.\n addComponentDevTarget(mcpTargets, `${mcpTargetPrefix}-dev`);\n\n updateProjectConfiguration(tree, project.name, {\n ...project,\n // Sort targets so their order is stable regardless of insertion order on\n // first run vs re-run.\n targets: sortObjectKeys(mcpTargets),\n });\n\n addComponentGeneratorMetadata(\n tree,\n project.name,\n TS_MCP_SERVER_GENERATOR_INFO,\n targetSourceDirRelativeToProjectRoot,\n mcpTargetPrefix,\n metadata,\n );\n\n await addGeneratorMetricsIfApplicable(tree, [TS_MCP_SERVER_GENERATOR_INFO]);\n\n await formatFilesInSubtree(tree);\n return () =>\n installDependencies(tree, options.preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\n\nexport default tsMcpServerGenerator;\n"],"names":["detectPackageManager","generateFiles","joinPathFragments","OverwriteStrategy","readJson","updateJson","updateProjectConfiguration","addTsDependencies","AGENT_CORE_CONSTRUCTS_PY_DEPENDENCIES","addMcpServerInfra","addTypeScriptCodePackageTarget","agentCoreNodeRuntime","CODE_PACKAGE_DEPENDENCIES","isAgentCoreHosted","isContainerHosted","addTypeScriptBundleTarget","BUNDLE_DEPENDENCIES","resolveContainers","declareDependencies","ownedElsewhere","ADOT_IMAGE_DEPENDENCIES","addDockerScanTarget","DOCKER_DEPENDENCIES","IMAGE_BUILD_CACHE","NODE_IMAGE_DEPENDENCIES","nodeImageVersions","formatFilesInSubtree","FS_DEPENDENCIES","FsCommands","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","isEsmWorkspace","kebabCase","toClassName","getNpmScope","addArtifactDependencyToTargets","addComponentDevTarget","addComponentGeneratorMetadata","addDependencyToTargetIfNotPresent","getGeneratorInfo","readProjectConfigurationUnqualified","sortObjectKeys","registerPnpmBuiltDependencies","assignPort","SHARED_CONSTRUCTS_DEPENDENCIES","sharedConstructsGenerator","BASE_IMAGES","TS_VERSIONS","DEPENDENCIES","ts","name","dev","root","py","TS_MCP_SERVER_GENERATOR_INFO","filename","tsMcpServerGenerator","tree","options","project","exists","Error","defaultName","split","pop","mcpServerNameClassName","mcpTargetPrefix","targetSourceDirRelativeToProjectRoot","targetSourceDir","relativeSourceDir","replace","distDir","infra","iac","undefined","auth","console","warn","projectPackageJsonPath","esm","type","templateContext","adotVersion","jaegerVersion","nodeBaseImage","node","dirname","overwriteStrategy","KeepExisting","container","containers","dockerImageTag","targetFilePath","bundleOutputDir","artifact","dockerTargetName","fs","targets","cache","executor","commands","cpFile","parallel","dependsOn","containerEngine","trivyTargetName","imageTags","outputDir","packageOutputDir","targetName","bundleTargetName","runtime","entryPoint","mcpServerNameKebabCase","projectName","packageJson","resolutions","localDevPort","component","info","metadata","port","rc","projectRoot","mcpTargets","continuous","cwd","env","PORT","LOCAL_DEV","preferInstallDependencies","languages"],"mappings":"AAAA;;;CAGC,GACD,SACEA,oB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E;YAC3DC,WAAW;gBAAC;aAAa;QAC3B;AACJ,EAAE;AAEF,eAAe3E,qBAAqB"}
|
|
1
|
+
{"version":3,"sources":["../../../../../../packages/nx-plugin/src/ts/mcp-server/generator.ts"],"sourcesContent":["/**\n * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {\n detectPackageManager,\n type GeneratorCallback,\n generateFiles,\n joinPathFragments,\n OverwriteStrategy,\n readJson,\n type Tree,\n updateJson,\n updateProjectConfiguration,\n} from '@nx/devkit';\nimport { addTsDependencies } from '../../utils/add-dependencies.js';\nimport {\n AGENT_CORE_CONSTRUCTS_PY_DEPENDENCIES,\n type AgentCoreArtifact,\n addMcpServerInfra,\n} from '../../utils/agent-core-constructs/agent-core-constructs.js';\nimport {\n addTypeScriptCodePackageTarget,\n agentCoreNodeRuntime,\n CODE_PACKAGE_DEPENDENCIES,\n isAgentCoreHosted,\n isContainerHosted,\n} from '../../utils/agent-core-packaging.js';\nimport {\n addTypeScriptBundleTarget,\n BUNDLE_DEPENDENCIES,\n} from '../../utils/bundle/bundle.js';\nimport { resolveContainers } from '../../utils/containers.js';\nimport {\n declareDependencies,\n ownedElsewhere,\n} from '../../utils/declared-dependencies.js';\nimport {\n ADOT_IMAGE_DEPENDENCIES,\n addDockerScanTarget,\n DOCKER_DEPENDENCIES,\n IMAGE_BUILD_CACHE,\n NODE_IMAGE_DEPENDENCIES,\n nodeImageVersions,\n} from '../../utils/docker.js';\nimport { formatFilesInSubtree } from '../../utils/format.js';\nimport { FS_DEPENDENCIES, FsCommands } from '../../utils/fs.js';\nimport { resolveIac } from '../../utils/iac.js';\nimport { installDependencies } from '../../utils/install.js';\nimport { addGeneratorMetricsIfApplicable } from '../../utils/metrics.js';\nimport { isEsmWorkspace } from '../../utils/module-format.js';\nimport { kebabCase, toClassName } from '../../utils/names.js';\nimport { getNpmScope } from '../../utils/npm-scope.js';\nimport {\n addArtifactDependencyToTargets,\n addComponentDevTarget,\n addComponentGeneratorMetadata,\n addDependencyToTargetIfNotPresent,\n getGeneratorInfo,\n type NxGeneratorInfo,\n normalizeTargetKeyOrder,\n readProjectConfigurationUnqualified,\n} from '../../utils/nx.js';\nimport { sortObjectKeys } from '../../utils/object.js';\nimport { registerPnpmBuiltDependencies } from '../../utils/pnpm-workspace.js';\nimport { assignPort } from '../../utils/port.js';\nimport {\n SHARED_CONSTRUCTS_DEPENDENCIES,\n sharedConstructsGenerator,\n} from '../../utils/shared-constructs.js';\nimport type { IacMetadata } from '../../utils/shared-constructs-constants.js';\nimport { BASE_IMAGES, TS_VERSIONS } from '../../utils/versions.js';\nimport type { TsMcpServerGeneratorSchema, TsMcpServerInfra } from './schema';\n\n/** The metadata this generator records, which its predicates read. */\nexport interface TsMcpServerMetadata extends IacMetadata {\n readonly port: number;\n readonly rc: string;\n readonly auth: string;\n /**\n * How this component is packaged and hosted, so a consumer can tell a\n * code-packaged runtime from a container-packaged one without re-deriving it.\n */\n readonly infra: TsMcpServerInfra;\n}\n\nexport const DEPENDENCIES = declareDependencies<TsMcpServerMetadata>()({\n ts: [\n { name: '@modelcontextprotocol/sdk' },\n { name: 'zod' },\n { name: 'express' },\n { name: '@aws-lambda-powertools/parameters' },\n { name: '@aws-sdk/client-appconfigdata' },\n { name: '@types/express', dev: true },\n // tsx (local dev) and the MCP inspector are shared tooling.\n { name: 'tsx', dev: true, root: true },\n { name: '@modelcontextprotocol/inspector', dev: true, root: true },\n ...ownedElsewhere(FS_DEPENDENCIES),\n ...ownedElsewhere(BUNDLE_DEPENDENCIES),\n ...ownedElsewhere(DOCKER_DEPENDENCIES),\n ...ownedElsewhere(SHARED_CONSTRUCTS_DEPENDENCIES),\n ...ownedElsewhere(NODE_IMAGE_DEPENDENCIES),\n ...ownedElsewhere(ADOT_IMAGE_DEPENDENCIES),\n ...ownedElsewhere(CODE_PACKAGE_DEPENDENCIES),\n ],\n py: ownedElsewhere(AGENT_CORE_CONSTRUCTS_PY_DEPENDENCIES),\n});\n\nexport const TS_MCP_SERVER_GENERATOR_INFO: NxGeneratorInfo = getGeneratorInfo(\n import.meta.filename,\n);\n\nexport const tsMcpServerGenerator = async (\n tree: Tree,\n options: TsMcpServerGeneratorSchema,\n): Promise<GeneratorCallback> => {\n const project = readProjectConfigurationUnqualified(tree, options.project);\n\n if (!tree.exists(joinPathFragments(project.root, 'tsconfig.json'))) {\n throw new Error(\n `Unsupported project ${options.project}. Expected a TypeScript project (with a tsconfig.json)`,\n );\n }\n\n const defaultName = `${kebabCase(project.name.split('/').pop())}-mcp-server`;\n const name = kebabCase(options.name || defaultName);\n const mcpServerNameClassName = toClassName(name);\n const mcpTargetPrefix = options.name ? name : 'mcp-server';\n const targetSourceDirRelativeToProjectRoot = joinPathFragments(\n 'src',\n mcpTargetPrefix,\n );\n const targetSourceDir = joinPathFragments(\n project.root,\n targetSourceDirRelativeToProjectRoot,\n );\n const relativeSourceDir = targetSourceDir.replace(project.root + '/', './');\n const distDir = joinPathFragments('dist', project.root);\n\n const infra = options.infra ?? 'agentcore';\n\n // Recorded in the metadata below so the version sync can tell a CDK\n // project from a Terraform one; undefined when no infrastructure was\n // generated, in which case neither provider's packages were added.\n const iac =\n infra !== 'none' ? await resolveIac(tree, options.iac) : undefined;\n\n if (infra === 'none' && options.auth && options.auth !== 'iam') {\n console.warn(\n 'Warning: auth is ignored when no infrastructure is configured (no infrastructure is generated)',\n );\n }\n\n const auth = options.auth ?? 'iam';\n\n const projectPackageJsonPath = joinPathFragments(\n project.root,\n 'package.json',\n );\n\n // Generate esm if the project's package.json is `type: module`, falling\n // back to the workspace format when the project has no manifest.\n const esm = tree.exists(projectPackageJsonPath)\n ? readJson(tree, projectPackageJsonPath).type === 'module'\n : isEsmWorkspace(tree);\n\n const templateContext = {\n name,\n esm,\n distDir,\n adotVersion:\n TS_VERSIONS['@aws/aws-distro-opentelemetry-node-autoinstrumentation'],\n jaegerVersion: TS_VERSIONS['@opentelemetry/propagator-jaeger'],\n nodeBaseImage: BASE_IMAGES.node,\n ...nodeImageVersions(),\n };\n\n // Generate example server\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'app'),\n targetSourceDir,\n templateContext,\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n // Add hosting based on infra\n if (isAgentCoreHosted(infra)) {\n const container = isContainerHosted(infra);\n const containers = await resolveContainers(tree, 'inherit');\n const dockerImageTag = `${getNpmScope(tree)}-${name}:latest`;\n\n // Add bundle target\n await addTypeScriptBundleTarget(\n tree,\n project,\n {\n targetFilePath: `${targetSourceDirRelativeToProjectRoot}/http.ts`,\n bundleOutputDir: joinPathFragments('mcp', name),\n },\n DEPENDENCIES,\n );\n\n const bundleOutputDir = joinPathFragments(\n 'dist',\n project.root,\n 'bundle',\n 'mcp',\n name,\n );\n\n let artifact: AgentCoreArtifact;\n\n if (container) {\n // Add the Dockerfile\n generateFiles(\n tree,\n joinPathFragments(import.meta.dirname, 'files', 'deploy'),\n targetSourceDir,\n templateContext,\n { overwriteStrategy: OverwriteStrategy.KeepExisting },\n );\n\n const dockerTargetName = `${mcpTargetPrefix}-docker`;\n\n const fs = new FsCommands(tree, DEPENDENCIES);\n project.targets[dockerTargetName] = normalizeTargetKeyOrder({\n cache: IMAGE_BUILD_CACHE,\n executor: 'nx:run-commands',\n options: {\n commands: [\n fs.cpFile(\n `${targetSourceDir}/Dockerfile`,\n `${bundleOutputDir}/Dockerfile`,\n ),\n `${containers} build --platform linux/arm64 -t ${dockerImageTag} ${bundleOutputDir}`,\n ],\n parallel: false,\n },\n dependsOn: ['bundle'],\n });\n\n addDependencyToTargetIfNotPresent(project, 'docker', dockerTargetName);\n addArtifactDependencyToTargets(project, 'docker');\n\n addDockerScanTarget(\n tree,\n {\n project,\n containerEngine: containers,\n trivyTargetName: `${mcpTargetPrefix}-trivy`,\n dockerTargetName,\n imageTags: [dockerImageTag],\n },\n DEPENDENCIES,\n );\n\n artifact = {\n type: 'container',\n dockerImageTag,\n outputDir: bundleOutputDir,\n };\n } else {\n const packageOutputDir = joinPathFragments(\n 'dist',\n project.root,\n 'package',\n 'mcp',\n name,\n );\n addTypeScriptCodePackageTarget(\n tree,\n {\n project,\n targetName: `${mcpTargetPrefix}-package`,\n bundleTargetName: 'bundle',\n bundleOutputDir,\n packageOutputDir,\n },\n DEPENDENCIES,\n );\n\n artifact = {\n type: 'code',\n outputDir: packageOutputDir,\n runtime: agentCoreNodeRuntime(),\n entryPoint: 'index.js',\n };\n }\n\n // Add shared constructs\n await sharedConstructsGenerator(tree, { iac }, DEPENDENCIES);\n\n // Add the construct to deploy the mcp server\n await addMcpServerInfra(tree, {\n mcpServerNameKebabCase: name,\n mcpServerNameClassName,\n projectName: project.name,\n artifact,\n iac,\n auth,\n containers,\n });\n }\n\n // @modelcontextprotocol/sdk declares zod as a peer dependency with a wide range\n // (^3.25 || ^4.0). Yarn does not dedupe the peer to the workspace's pinned zod, so\n // without a resolution it installs a separate zod under the SDK's own node_modules.\n // The two zod copies have structurally incompatible types, which breaks type\n // inference for registerTool inputSchema. Scope the resolution to the SDK so\n // other consumers (e.g. @tanstack/router-generator pinning zod@3) are unaffected.\n // Classic yarn only honours the `**/`-prefixed descriptor in a workspace, and\n // berry only the bare one — it deletes a glob descriptor on install — so\n // declare both.\n if (detectPackageManager() === 'yarn') {\n updateJson(tree, 'package.json', (packageJson) => {\n packageJson.resolutions = {\n ...packageJson.resolutions,\n '**/@modelcontextprotocol/sdk/zod': TS_VERSIONS['zod'],\n '@modelcontextprotocol/sdk/zod': TS_VERSIONS['zod'],\n };\n return packageJson;\n });\n }\n\n const localDevPort = assignPort(tree, project, 8000, {\n component: { info: TS_MCP_SERVER_GENERATOR_INFO, name: mcpTargetPrefix },\n });\n\n // Recorded below and read by the declaration's predicates, so the packages\n // added here are exactly the ones the version sync will own.\n const metadata: TsMcpServerMetadata = {\n infra,\n port: localDevPort,\n rc: mcpServerNameClassName,\n auth,\n ...(iac ? { iac } : {}),\n };\n\n // The MCP inspector has a postinstall script that cascades installs into its\n // client packages, which no-ops when the package is installed as a dependency.\n // Register it as an explicitly-rejected build so pnpm 11's default\n // `strictDepBuilds=true` skips it instead of failing the install.\n registerPnpmBuiltDependencies(tree, {\n '@modelcontextprotocol/inspector': false,\n });\n\n addTsDependencies(tree, DEPENDENCIES, {\n metadata,\n projectRoot: project.root,\n });\n\n const mcpTargets = {\n ...project.targets,\n // Add targets for running the MCP server\n [`${mcpTargetPrefix}-serve-stdio`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/stdio.ts`],\n cwd: '{projectRoot}',\n },\n },\n [`${mcpTargetPrefix}-serve`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/http.ts`],\n cwd: '{projectRoot}',\n env: {\n PORT: `${localDevPort}`,\n },\n },\n },\n [`${mcpTargetPrefix}-dev`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [`tsx --watch ${relativeSourceDir}/http.ts`],\n cwd: '{projectRoot}',\n env: {\n PORT: `${localDevPort}`,\n LOCAL_DEV: 'true',\n },\n },\n },\n [`${mcpTargetPrefix}-inspect`]: {\n executor: 'nx:run-commands',\n continuous: true,\n // Launch the inspector against the locally served HTTP server. The dev\n // target starts the server and any connected dependencies (e.g. a local\n // database).\n dependsOn: [`${mcpTargetPrefix}-dev`],\n options: {\n commands: [\n `mcp-inspector --transport http --server-url http://localhost:${localDevPort}/mcp`,\n ],\n cwd: '{projectRoot}',\n },\n },\n [`${mcpTargetPrefix}-inspect-stdio`]: {\n executor: 'nx:run-commands',\n continuous: true,\n options: {\n commands: [\n `mcp-inspector -- tsx --watch ${relativeSourceDir}/stdio.ts`,\n ],\n cwd: '{projectRoot}',\n },\n },\n };\n\n // Aggregate `<mcp>-dev` under the project-level `dev` target.\n addComponentDevTarget(mcpTargets, `${mcpTargetPrefix}-dev`);\n\n updateProjectConfiguration(tree, project.name, {\n ...project,\n // Sort targets so their order is stable regardless of insertion order on\n // first run vs re-run.\n targets: sortObjectKeys(mcpTargets),\n });\n\n addComponentGeneratorMetadata(\n tree,\n project.name,\n TS_MCP_SERVER_GENERATOR_INFO,\n targetSourceDirRelativeToProjectRoot,\n mcpTargetPrefix,\n metadata,\n );\n\n await addGeneratorMetricsIfApplicable(tree, [TS_MCP_SERVER_GENERATOR_INFO]);\n\n await formatFilesInSubtree(tree);\n return () =>\n installDependencies(tree, options.preferInstallDependencies, {\n languages: ['typescript'],\n });\n};\n\nexport default tsMcpServerGenerator;\n"],"names":["detectPackageManager","generateFiles","joinPathFragments","OverwriteStrategy","readJson","updateJson","updateProjectConfiguration","addTsDependencies","AGENT_CORE_CONSTRUCTS_PY_DEPENDENCIES","addMcpServerInfra","addTypeScriptCodePackageTarget","agentCoreNodeRuntime","CODE_PACKAGE_DEPENDENCIES","isAgentCoreHosted","isContainerHosted","addTypeScriptBundleTarget","BUNDLE_DEPENDENCIES","resolveContainers","declareDependencies","ownedElsewhere","ADOT_IMAGE_DEPENDENCIES","addDockerScanTarget","DOCKER_DEPENDENCIES","IMAGE_BUILD_CACHE","NODE_IMAGE_DEPENDENCIES","nodeImageVersions","formatFilesInSubtree","FS_DEPENDENCIES","FsCommands","resolveIac","installDependencies","addGeneratorMetricsIfApplicable","isEsmWorkspace","kebabCase","toClassName","getNpmScope","addArtifactDependencyToTargets","addComponentDevTarget","addComponentGeneratorMetadata","addDependencyToTargetIfNotPresent","getGeneratorInfo","normalizeTargetKeyOrder","readProjectConfigurationUnqualified","sortObjectKeys","registerPnpmBuiltDependencies","assignPort","SHARED_CONSTRUCTS_DEPENDENCIES","sharedConstructsGenerator","BASE_IMAGES","TS_VERSIONS","DEPENDENCIES","ts","name","dev","root","py","TS_MCP_SERVER_GENERATOR_INFO","filename","tsMcpServerGenerator","tree","options","project","exists","Error","defaultName","split","pop","mcpServerNameClassName","mcpTargetPrefix","targetSourceDirRelativeToProjectRoot","targetSourceDir","relativeSourceDir","replace","distDir","infra","iac","undefined","auth","console","warn","projectPackageJsonPath","esm","type","templateContext","adotVersion","jaegerVersion","nodeBaseImage","node","dirname","overwriteStrategy","KeepExisting","container","containers","dockerImageTag","targetFilePath","bundleOutputDir","artifact","dockerTargetName","fs","targets","cache","executor","commands","cpFile","parallel","dependsOn","containerEngine","trivyTargetName","imageTags","outputDir","packageOutputDir","targetName","bundleTargetName","runtime","entryPoint","mcpServerNameKebabCase","projectName","packageJson","resolutions","localDevPort","component","info","metadata","port","rc","projectRoot","mcpTargets","continuous","cwd","env","PORT","LOCAL_DEV","preferInstallDependencies","languages"],"mappings":"AAAA;;;CAGC,GACD,SACEA,oBAAoB,EAEpBC,aAAa,EACbC,iBAAiB,EACjBC,iBAAiB,EACjBC,QAAQ,EAERC,UAAU,EACVC,0BAA0B,QACrB,aAAa;AACpB,SAASC,iBAAiB,QAAQ,kCAAkC;AACpE,SACEC,qCAAqC,EAErCC,iBAAiB,QACZ,6DAA6D;AACpE,SACEC,8BAA8B,EAC9BC,oBAAoB,EACpBC,yBAAyB,EACzBC,iBAAiB,EACjBC,iBAAiB,QACZ,sCAAsC;AAC7C,SACEC,yBAAyB,EACzBC,mBAAmB,QACd,+BAA+B;AACtC,SAASC,iBAAiB,QAAQ,4BAA4B;AAC9D,SACEC,mBAAmB,EACnBC,cAAc,QACT,uCAAuC;AAC9C,SACEC,uBAAuB,EACvBC,mBAAmB,EACnBC,mBAAmB,EACnBC,iBAAiB,EACjBC,uBAAuB,EACvBC,iBAAiB,QACZ,wBAAwB;AAC/B,SAASC,oBAAoB,QAAQ,wBAAwB;AAC7D,SAASC,eAAe,EAAEC,UAAU,QAAQ,oBAAoB;AAChE,SAASC,UAAU,QAAQ,qBAAqB;AAChD,SAASC,mBAAmB,QAAQ,yBAAyB;AAC7D,SAASC,+BAA+B,QAAQ,yBAAyB;AACzE,SAASC,cAAc,QAAQ,+BAA+B;AAC9D,SAASC,SAAS,EAAEC,WAAW,QAAQ,uBAAuB;AAC9D,SAASC,WAAW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CAAC;iBAC7D;gBACDyD,KAAK;YACP;QACF;IACF;IAEA,8DAA8D;IAC9D3F,sBAAsByF,YAAY,GAAG1D,gBAAgB,IAAI,CAAC;IAE1D9D,2BAA2BqD,MAAME,QAAQT,IAAI,EAAE;QAC7C,GAAGS,OAAO;QACV,yEAAyE;QACzE,uBAAuB;QACvBsC,SAASxD,eAAemF;IAC1B;IAEAxF,8BACEqB,MACAE,QAAQT,IAAI,EACZI,8BACAa,sCACAD,iBACAsD;IAGF,MAAM3F,gCAAgC4B,MAAM;QAACH;KAA6B;IAE1E,MAAM9B,qBAAqBiC;IAC3B,OAAO,IACL7B,oBAAoB6B,MAAMC,QAAQwE,yBAAyB,EAAE;YAC3DC,WAAW;gBAAC;aAAa;QAC3B;AACJ,EAAE;AAEF,eAAe3E,qBAAqB"}
|
|
@@ -4533,10 +4533,15 @@ WORKDIR \${LAMBDA_TASK_ROOT}
|
|
|
4533
4533
|
|
|
4534
4534
|
# npm blocks dependency install scripts by default; allow prisma's so its
|
|
4535
4535
|
# postinstall downloads the schema-engine binary needed to run migrations.
|
|
4536
|
+
# The overrides pin transitive dependencies of the CLI with known HIGH/CRITICAL
|
|
4537
|
+
# vulnerabilities to fixed versions, which its own ranges resolve below.
|
|
4536
4538
|
# npm is removed once prisma is installed — the handler runs prisma's own
|
|
4537
4539
|
# binary directly, and npm's bundled dependencies would otherwise carry known
|
|
4538
4540
|
# HIGH/CRITICAL vulnerabilities into the image.
|
|
4539
4541
|
RUN printf 'allow-scripts[]=prisma\\nallow-scripts[]=@prisma/engines\\n' > .npmrc \\
|
|
4542
|
+
&& npm init -y \\
|
|
4543
|
+
&& npm pkg set "overrides.deepmerge-ts=8.0.0" \\
|
|
4544
|
+
&& npm pkg set "overrides.mysql2=3.22.0" \\
|
|
4540
4545
|
&& npm install prisma@7.10.0 \\
|
|
4541
4546
|
&& rm .npmrc \\
|
|
4542
4547
|
&& npm uninstall -g npm
|