mulesoft-anypoint-cli-agent-fabric-plugin 1.0.9 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/dist/commands/agent-network/project/build.d.ts +0 -4
  2. package/dist/commands/agent-network/project/build.js +22 -139
  3. package/dist/commands/agent-network/project/build.js.map +1 -1
  4. package/dist/commands/agent-network/project/create.js +32 -25
  5. package/dist/commands/agent-network/project/create.js.map +1 -1
  6. package/dist/commands/agent-network/project/deploy.d.ts +2 -36
  7. package/dist/commands/agent-network/project/deploy.js +117 -506
  8. package/dist/commands/agent-network/project/deploy.js.map +1 -1
  9. package/dist/commands/agent-network/project/publish.d.ts +0 -1
  10. package/dist/commands/agent-network/project/publish.js +26 -94
  11. package/dist/commands/agent-network/project/publish.js.map +1 -1
  12. package/dist/commands/agent-network/setup/dependencies.js +2 -1
  13. package/dist/commands/agent-network/setup/dependencies.js.map +1 -1
  14. package/dist/commands/agent-network/setup/gateways.js +23 -19
  15. package/dist/commands/agent-network/setup/gateways.js.map +1 -1
  16. package/dist/errors/base-error.d.ts +10 -0
  17. package/dist/errors/base-error.js +42 -13
  18. package/dist/errors/base-error.js.map +1 -1
  19. package/dist/errors/error-factory.d.ts +20 -6
  20. package/dist/errors/error-factory.js +128 -32
  21. package/dist/errors/error-factory.js.map +1 -1
  22. package/dist/helpers/connection-id.d.ts +1 -0
  23. package/dist/helpers/connection-id.js +8 -0
  24. package/dist/helpers/connection-id.js.map +1 -0
  25. package/dist/helpers/dependency-manager.js +1 -6
  26. package/dist/helpers/dependency-manager.js.map +1 -1
  27. package/dist/helpers/policy-helper.d.ts +66 -3
  28. package/dist/helpers/policy-helper.js +152 -11
  29. package/dist/helpers/policy-helper.js.map +1 -1
  30. package/dist/helpers/project/api-project-dependency-fetcher.d.ts +3 -0
  31. package/dist/helpers/project/api-project-dependency-fetcher.js +17 -7
  32. package/dist/helpers/project/api-project-dependency-fetcher.js.map +1 -1
  33. package/dist/helpers/project/templates.js +2 -1
  34. package/dist/helpers/project/templates.js.map +1 -1
  35. package/dist/helpers/request-utils.d.ts +3 -0
  36. package/dist/helpers/request-utils.js +11 -0
  37. package/dist/helpers/request-utils.js.map +1 -0
  38. package/dist/helpers/types.d.ts +1 -1
  39. package/dist/helpers/utils.d.ts +17 -18
  40. package/dist/helpers/utils.js +73 -27
  41. package/dist/helpers/utils.js.map +1 -1
  42. package/dist/types/agent-network.d.ts +90 -61
  43. package/dist/types/agent-network.js +6 -1
  44. package/dist/types/agent-network.js.map +1 -1
  45. package/dist/types/types.d.ts +64 -4
  46. package/dist/utils/builders/agent-builder.d.ts +11 -0
  47. package/dist/utils/builders/agent-builder.js +79 -0
  48. package/dist/utils/builders/agent-builder.js.map +1 -0
  49. package/dist/utils/builders/broker-builder.d.ts +22 -0
  50. package/dist/utils/builders/broker-builder.js +292 -0
  51. package/dist/utils/builders/broker-builder.js.map +1 -0
  52. package/dist/utils/builders/builder.d.ts +9 -0
  53. package/dist/utils/builders/builder.js +110 -0
  54. package/dist/utils/builders/builder.js.map +1 -0
  55. package/dist/utils/builders/connections-builder.d.ts +25 -0
  56. package/dist/utils/builders/connections-builder.js +233 -0
  57. package/dist/utils/builders/connections-builder.js.map +1 -0
  58. package/dist/utils/builders/llm-builder.d.ts +12 -0
  59. package/dist/utils/builders/llm-builder.js +64 -0
  60. package/dist/utils/builders/llm-builder.js.map +1 -0
  61. package/dist/utils/builders/mcp-builder.d.ts +12 -0
  62. package/dist/utils/builders/mcp-builder.js +48 -0
  63. package/dist/utils/builders/mcp-builder.js.map +1 -0
  64. package/dist/utils/builders/network-builder.d.ts +13 -0
  65. package/dist/utils/builders/network-builder.js +77 -0
  66. package/dist/utils/builders/network-builder.js.map +1 -0
  67. package/dist/utils/builders/path.d.ts +12 -0
  68. package/dist/utils/builders/path.js +35 -0
  69. package/dist/utils/builders/path.js.map +1 -0
  70. package/dist/utils/builders/policies-factory.d.ts +8 -0
  71. package/dist/utils/builders/policies-factory.js +255 -0
  72. package/dist/utils/builders/policies-factory.js.map +1 -0
  73. package/dist/utils/builders/project-builder-impl.d.ts +233 -0
  74. package/dist/utils/builders/project-builder-impl.js +552 -0
  75. package/dist/utils/builders/project-builder-impl.js.map +1 -0
  76. package/dist/utils/builders/project-builder.d.ts +313 -0
  77. package/dist/utils/builders/project-builder.js +76 -0
  78. package/dist/utils/builders/project-builder.js.map +1 -0
  79. package/dist/utils/builders/space-serializer.d.ts +18 -0
  80. package/dist/utils/builders/space-serializer.js +239 -0
  81. package/dist/utils/builders/space-serializer.js.map +1 -0
  82. package/dist/utils/constants.d.ts +3 -1
  83. package/dist/utils/constants.js +6 -3
  84. package/dist/utils/constants.js.map +1 -1
  85. package/dist/utils/exchange.d.ts +7 -1
  86. package/dist/utils/exchange.js +90 -2
  87. package/dist/utils/exchange.js.map +1 -1
  88. package/dist/utils/facets/abstract-facet.d.ts +34 -0
  89. package/dist/utils/facets/abstract-facet.js +50 -0
  90. package/dist/utils/facets/abstract-facet.js.map +1 -0
  91. package/dist/utils/facets/api-instance-facet.d.ts +16 -0
  92. package/dist/utils/facets/api-instance-facet.js +274 -0
  93. package/dist/utils/facets/api-instance-facet.js.map +1 -0
  94. package/dist/utils/facets/asset-facet.d.ts +11 -0
  95. package/dist/utils/facets/asset-facet.js +151 -0
  96. package/dist/utils/facets/asset-facet.js.map +1 -0
  97. package/dist/utils/facets/connection-facet.d.ts +16 -0
  98. package/dist/utils/facets/connection-facet.js +277 -0
  99. package/dist/utils/facets/connection-facet.js.map +1 -0
  100. package/dist/utils/facets/deployment-helpers.d.ts +2 -0
  101. package/dist/utils/facets/deployment-helpers.js +44 -0
  102. package/dist/utils/facets/deployment-helpers.js.map +1 -0
  103. package/dist/utils/facets/facets.d.ts +7 -0
  104. package/dist/utils/facets/facets.js +55 -0
  105. package/dist/utils/facets/facets.js.map +1 -0
  106. package/dist/utils/facets/mule-application-facet.d.ts +20 -0
  107. package/dist/utils/facets/mule-application-facet.js +282 -0
  108. package/dist/utils/facets/mule-application-facet.js.map +1 -0
  109. package/dist/utils/files.d.ts +1 -1
  110. package/dist/utils/files.js +9 -16
  111. package/dist/utils/files.js.map +1 -1
  112. package/dist/utils/gateway.d.ts +4 -0
  113. package/dist/utils/gateway.js +32 -0
  114. package/dist/utils/gateway.js.map +1 -1
  115. package/dist/utils/logger.d.ts +15 -0
  116. package/dist/utils/logger.js +46 -0
  117. package/dist/utils/logger.js.map +1 -0
  118. package/dist/utils/promise/promiseCreator.d.ts +8 -0
  119. package/dist/utils/promise/promiseCreator.js +19 -0
  120. package/dist/utils/promise/promiseCreator.js.map +1 -0
  121. package/dist/utils/uris.d.ts +1 -0
  122. package/dist/utils/uris.js +12 -3
  123. package/dist/utils/uris.js.map +1 -1
  124. package/dist/utils/variables.d.ts +15 -4
  125. package/dist/utils/variables.js +102 -0
  126. package/dist/utils/variables.js.map +1 -1
  127. package/package.json +1 -1
  128. package/dist/utils/api-instance-builder.d.ts +0 -28
  129. package/dist/utils/api-instance-builder.js +0 -467
  130. package/dist/utils/api-instance-builder.js.map +0 -1
  131. package/dist/utils/asset-builder.d.ts +0 -28
  132. package/dist/utils/asset-builder.js +0 -248
  133. package/dist/utils/asset-builder.js.map +0 -1
@@ -1,21 +1,29 @@
1
1
  "use strict";
2
- var _a;
3
2
  Object.defineProperty(exports, "__esModule", { value: true });
4
3
  const tslib_1 = require("tslib");
5
4
  const gateway_1 = require("../../../utils/gateway");
6
5
  const core_1 = require("@oclif/core");
7
6
  const anypoint_cli_command_1 = require("anypoint-cli-command");
7
+ const logger_1 = require("../../../utils/logger");
8
8
  const node_path_1 = require("node:path");
9
9
  const constants_1 = require("../../../utils/constants");
10
- const semver_1 = tslib_1.__importDefault(require("semver"));
11
10
  const error_factory_1 = require("../../../errors/error-factory");
12
- const api_instance_builder_1 = require("../../../utils/api-instance-builder");
13
11
  const utils_1 = require("../../../helpers/utils");
14
- const entitlement_utils_1 = require("../../../helpers/entitlement-utils");
15
12
  const exchange_1 = require("../../../utils/exchange");
16
- const naming_1 = require("../../../utils/naming");
13
+ const node_http_1 = tslib_1.__importDefault(require("node:http"));
14
+ const node_https_1 = tslib_1.__importDefault(require("node:https"));
15
+ const node_crypto_1 = require("node:crypto");
16
+ const request_utils_1 = require("../../../helpers/request-utils");
17
+ const variables_1 = require("../../../utils/variables");
18
+ const constants_2 = require("../../../helpers/project/constants");
19
+ const space_serializer_1 = require("../../../utils/builders/space-serializer");
20
+ const project_builder_1 = require("../../../utils/builders/project-builder");
21
+ const facets_1 = require("../../../utils/facets/facets");
22
+ const project_builder_impl_1 = require("../../../utils/builders/project-builder-impl");
23
+ const policy_helper_1 = require("../../../helpers/policy-helper");
17
24
  class Deploy extends anypoint_cli_command_1.AuthenticationBaseCommand {
18
25
  async run() {
26
+ var _a, _b;
19
27
  const { flags } = await this.parse(Deploy);
20
28
  const ingressGwName = flags['ingress-gw'];
21
29
  const egressGwName = flags['egress-gw'];
@@ -23,543 +31,145 @@ class Deploy extends anypoint_cli_command_1.AuthenticationBaseCommand {
23
31
  const dontWaitForAgentNetwork = flags['dont-wait-for-agent-network'];
24
32
  const disableTracing = flags['disable-tracing'];
25
33
  const properties = flags.property;
26
- const basePath = flags.path || process.cwd();
27
- const mulesoftOrg = utils_1.MULESOFT_ORGS[flags.host];
28
- const json = flags.json || false;
29
34
  const userRequestTimeout = flags['request-timeout'];
30
35
  const userProcessTimeout = flags['process-timeout'];
36
+ if (this.req.defaults) {
37
+ this.req.defaults.httpAgent = new node_http_1.default.Agent({ keepAlive: true });
38
+ this.req.defaults.httpsAgent = new node_https_1.default.Agent({ keepAlive: true });
39
+ }
40
+ const requestId = (0, node_crypto_1.randomUUID)();
41
+ const requestInterceptorId = (_a = this.req.interceptors.request) === null || _a === void 0 ? void 0 : _a.use(config => {
42
+ var _a;
43
+ config.headers[utils_1.X_REQUEST_D] = config.headers[utils_1.X_REQUEST_ID] || requestId;
44
+ logger_1.Log.debug(`${(_a = config.method) === null || _a === void 0 ? void 0 : _a.toUpperCase()} ${config.url} - sending`);
45
+ return config;
46
+ });
47
+ const responseInterceptorId = (_b = this.req.interceptors.response) === null || _b === void 0 ? void 0 : _b.use(response => {
48
+ var _a;
49
+ logger_1.Log.debug(`${(_a = response.config.method) === null || _a === void 0 ? void 0 : _a.toUpperCase()} ${response.config.url} - ${response.status} - response`);
50
+ return response;
51
+ }, error => {
52
+ var _a, _b, _c, _d;
53
+ if (error.response) {
54
+ const config = error.config;
55
+ logger_1.Log.debug(`${(_a = config === null || config === void 0 ? void 0 : config.method) === null || _a === void 0 ? void 0 : _a.toUpperCase()} ${config === null || config === void 0 ? void 0 : config.url} - ${error.response.status} - response`);
56
+ }
57
+ else {
58
+ logger_1.Log.debug(`${(_c = (_b = error.config) === null || _b === void 0 ? void 0 : _b.method) === null || _c === void 0 ? void 0 : _c.toUpperCase()} ${(_d = error.config) === null || _d === void 0 ? void 0 : _d.url} - ${error.message} - response`);
59
+ }
60
+ return Promise.reject(error);
61
+ });
62
+ const steps = [
63
+ { name: 'Get Ingress GW', completed: false },
64
+ { name: 'Get Egress GW', completed: false },
65
+ { name: 'Get Private Space', completed: false },
66
+ { name: 'Deploy Project', completed: false },
67
+ ];
31
68
  const deployCommand = async () => {
32
- var _b;
33
- const exchangeJsonPath = (0, node_path_1.join)(basePath, constants_1.EXCHANGE_JSON_FILENAME);
69
+ const projectPath = flags.path || process.cwd();
70
+ const targetDir = (0, node_path_1.join)(projectPath, 'target');
71
+ const spaceSerializer = new space_serializer_1.SpaceSerializer(targetDir);
72
+ const space = spaceSerializer.load();
73
+ if (!space) {
74
+ throw error_factory_1.ErrorFactory.invalidOrNotBuiltAgentNetworkProject();
75
+ }
76
+ const exchangeJsonPath = (0, node_path_1.join)(projectPath, constants_2.DESCRIPTOR_FILE);
34
77
  const agentNetworkDescriptor = (0, utils_1.safeJsonFileParse)(exchangeJsonPath).jsonObject;
78
+ const variables = space.variables;
79
+ let collectedProperties = { properties: {}, securedProperties: {} };
80
+ if (variables) {
81
+ const userProvidedProperties = variables_1.VariablesHelper.propertiesArrayToObject(properties);
82
+ const needsPrompts = variables_1.VariablesHelper.checkIfPromptsNeeded(variables, userProvidedProperties);
83
+ if (needsPrompts) {
84
+ logger_1.Log.print('Please provide values for the following variables:');
85
+ }
86
+ collectedProperties = await variables_1.VariablesHelper.promptForVariables(variables, userProvidedProperties);
87
+ }
35
88
  const organizationId = this.session.selectedOrganization.id;
36
- const environmentId = this.session.selectedEnvironment.id;
37
89
  const maxRetries = flags['max-retries'];
38
- anypoint_cli_command_1.Logger.info('Deploying agent network project...');
90
+ logger_1.Log.debug('⏳ Fetching Ingress Gateway');
39
91
  const ingressGW = await gateway_1.GatewayUtils.getGatewayDescription(this.req, organizationId, this.session.selectedEnvironment, ingressGwName);
92
+ steps[0].completed = true;
93
+ logger_1.Log.debug('✅ Ingress Gateway fetched successfully');
94
+ logger_1.Log.debug('⏳ Fetching Egress Gateway');
40
95
  const egressGW = await gateway_1.GatewayUtils.getGatewayDescription(this.req, organizationId, this.session.selectedEnvironment, egressGwName);
96
+ steps[1].completed = true;
97
+ logger_1.Log.debug('✅ Egress Gateway fetched successfully');
98
+ logger_1.Log.debug('⏳ Fetching Private Space');
41
99
  const targetPrivateSpace = await gateway_1.GatewayUtils.getPrivateSpace(this.req, organizationId, this.session.selectedEnvironment, targetSpace);
100
+ steps[2].completed = true;
101
+ logger_1.Log.debug('✅ Private Space fetched successfully');
42
102
  // Add a check for gateway integrity. Gateways must have the same target as the selected one.
43
103
  if (!this.checkGatewayTargetSpace(ingressGW, egressGW, targetPrivateSpace)) {
44
104
  throw error_factory_1.ErrorFactory.gatewayTargetSpaceError(ingressGW, egressGW, targetPrivateSpace);
45
105
  }
46
- const mainFilePath = (0, node_path_1.join)(basePath, agentNetworkDescriptor.main || 'agent-network-descriptor.yaml');
47
- // Prompt user for variables defined in the ExchangeDescriptor
48
- let collectedVariables = { properties: {}, securedProperties: {} };
49
- if ((_b = agentNetworkDescriptor === null || agentNetworkDescriptor === void 0 ? void 0 : agentNetworkDescriptor.metadata) === null || _b === void 0 ? void 0 : _b.variables) {
50
- const propObject = this.propertiesArrayToObject(properties);
51
- const needsPrompts = this.checkIfPromptsNeeded(agentNetworkDescriptor.metadata.variables, propObject);
52
- if (needsPrompts) {
53
- anypoint_cli_command_1.Logger.print('Please provide values for the following variables:');
54
- }
55
- collectedVariables = await this.promptForVariables(agentNetworkDescriptor.metadata.variables, propObject);
56
- }
57
- collectedVariables = {
58
- properties: {
59
- ...collectedVariables.properties,
60
- [constants_1.INGRESS_GW_URL_PROPERTY]: this.getAgentRegistryUrl(ingressGW),
61
- [constants_1.EGRESS_GW_URL_PROPERTY]: this.getAgentRegistryUrl(egressGW)
62
- },
63
- securedProperties: { ...collectedVariables.securedProperties },
64
- };
65
- const instanceBuilder = new api_instance_builder_1.AgentNetworkApiInstanceBuilder(basePath, mainFilePath, agentNetworkDescriptor, collectedVariables, mulesoftOrg);
66
- const egressApis = instanceBuilder.egress();
67
106
  const nonPublishedAssets = [];
68
- await Promise.all(egressApis.map(async (api) => {
69
- const isAssetPublished = await (0, exchange_1.assetExists)(this.req, api.asset, true);
107
+ const assets = Object.values(space.components).flatMap(component => Object.values(component.assets).map(asset => ({ asset, version: component.version })));
108
+ await Promise.all(assets.map(async ({ asset, version }) => {
109
+ const gav = { groupId: space.gav.groupId, assetId: asset.assetId, version };
110
+ const isAssetPublished = await (0, exchange_1.assetExists)(this.req, gav, true);
70
111
  if (!isAssetPublished) {
71
- nonPublishedAssets.push(api.asset);
112
+ nonPublishedAssets.push(gav);
72
113
  }
73
- }))
74
- .catch(error => {
114
+ })).catch(error => {
75
115
  throw error_factory_1.ErrorFactory.findingAssetsError(error);
76
116
  });
77
117
  if (nonPublishedAssets.length > 0) {
78
118
  throw error_factory_1.ErrorFactory.nonPublishedAssetsFoundError(nonPublishedAssets);
79
119
  }
80
- // Deploy egress APIs
81
- for (const api of egressApis) {
82
- await this.deployAPIInstance(api, egressGW, mulesoftOrg);
83
- }
84
- if (instanceBuilder.hasBrokers()) {
85
- // If no brokers
86
- const deploymentResult = await this.deployApplication(agentNetworkDescriptor, instanceBuilder, targetPrivateSpace, collectedVariables, disableTracing, maxRetries, userRequestTimeout);
87
- const ingressApis = instanceBuilder.ingress(deploymentResult.url);
88
- // Deploy ingress APIs
89
- for (const api of ingressApis) {
90
- await this.deployAPIInstance(api, ingressGW, mulesoftOrg);
91
- }
92
- if (!dontWaitForAgentNetwork) {
93
- anypoint_cli_command_1.Logger.cliStart(`Waiting for application: '${agentNetworkDescriptor.name}' to be ready.`);
94
- let status;
95
- do {
96
- await (0, utils_1.sleep)(2 * 1000); // Wait 2 seconds
97
- const getDeploymentResult = await (0, utils_1.executeRequestWithRetry)(() => this.req.get(`/amc/adam/api/organizations/${organizationId}/environments/${environmentId}/deployments/${deploymentResult.deploymentId}`, { timeout: userRequestTimeout }), maxRetries, userRequestTimeout);
98
- status = getDeploymentResult.data.status;
99
- } while (status.toUpperCase() !== 'STARTED' && status.toUpperCase() !== 'FAILED' && status.toUpperCase() !== 'APPLIED');
100
- if (status === 'FAILED') {
101
- anypoint_cli_command_1.Logger.cliEndFailed();
102
- throw error_factory_1.ErrorFactory.brokerGroupDeploymentError();
103
- }
104
- else {
105
- anypoint_cli_command_1.Logger.cliEndOk();
106
- }
107
- }
108
- anypoint_cli_command_1.Logger.print('Brokers:');
109
- for (const agentDescriptor of ingressApis) {
110
- this.printAgentUrl(json, ingressGW, agentDescriptor);
111
- }
112
- }
113
- anypoint_cli_command_1.Logger.info(`Agent network project '${agentNetworkDescriptor.name}' was deployed.`);
114
- };
115
- return (0, utils_1.runCommandWithTimeout)(deployCommand(), userProcessTimeout, 'Deploy');
116
- }
117
- toErrorJson(err) {
118
- return { error: { ...err, message: err.message } };
119
- }
120
- printAgentUrl(json, ingressGW, agentDescriptor) {
121
- const url = `${this.getAgentRegistryUrl(ingressGW)}/${agentDescriptor.asset.assetId}/`;
122
- const urlData = { name: agentDescriptor.asset.assetId, version: agentDescriptor.asset.version, url };
123
- if (json) {
124
- anypoint_cli_command_1.Logger.print(JSON.stringify(urlData));
125
- }
126
- else {
127
- anypoint_cli_command_1.Logger.cliObject(urlData, ['name', 'version', 'url']);
128
- }
129
- }
130
- propertiesArrayToObject(properties) {
131
- const result = {};
132
- for (const entry of properties) {
133
- const [name, ...rest] = entry.split(':');
134
- result[name] = rest.join(':'); // Handles values with colons
135
- }
136
- return result;
137
- }
138
- async deployAPIInstance(api, gateway, mulesoftOrg) {
139
- anypoint_cli_command_1.Logger.cliStart(`Deploying API: '${api.label}'`);
140
- const organizationId = this.session.selectedOrganization.id;
141
- const environmentId = this.session.selectedEnvironment.id;
142
- const existingApiResponse = await this.req.get(`/apimanager/api/v1/organizations/${organizationId}/environments/${environmentId}/apis?assetId=${api.asset.assetId}&groupId=${api.asset.groupId}`);
143
- let existingApi = null;
144
- let apiId = null;
145
- for (const asset of existingApiResponse.data.assets) {
146
- const foundApi = asset.apis.find(apimApi => {
147
- var _b;
148
- return api.metadata.connectionId === ((_b = apimApi.metadata) === null || _b === void 0 ? void 0 : _b.connectionId);
149
- });
150
- if (foundApi) {
151
- existingApi = foundApi;
152
- apiId = foundApi.id.toString();
153
- break;
154
- }
155
- }
156
- const endpointPath = api.endpointPath.startsWith('/') ? api.endpointPath.slice(1) : api.endpointPath;
157
- const commonApiBody = {
158
- spec: {
159
- groupId: api.asset.groupId,
160
- assetId: api.asset.assetId,
161
- version: api.asset.version,
162
- },
163
- endpoint: {
164
- type: api.type,
165
- deploymentType: 'HY',
166
- uri: this.sanitizeUpstreamUrl(api.upstreamUrl),
167
- proxyUri: `http://0.0.0.0:8081/${endpointPath}/`,
168
- isCloudHub: null,
169
- },
170
- endpointUri: `${this.getAgentRegistryUrl(gateway)}/${endpointPath}/`,
171
- technology: 'flexGateway',
172
- instanceLabel: api.id,
173
- description: api.label + ' ' + (api.description || ''),
174
- };
175
- const deploymentBody = {
176
- gatewayVersion: 'N/A',
177
- targetId: gateway.id,
178
- targetName: gateway.name,
179
- type: 'HY',
180
- environmentId: `${environmentId}`,
181
- };
182
- if (apiId && existingApi) {
183
- let gateKeeper;
184
- let listPolicies;
185
- const updatedMetadata = (existingApi === null || existingApi === void 0 ? void 0 : existingApi.metadata) ? { metadata: { ...existingApi.metadata, source: api.metadata.source } } : undefined;
186
- try {
187
- await this.req.patch(`/apimanager/api/v1/organizations/${organizationId}/environments/${environmentId}/apis/${apiId}`, {
188
- groupId: api.asset.groupId,
189
- assetId: api.asset.assetId,
190
- assetVersion: api.asset.version,
191
- ...(commonApiBody),
192
- ...(updatedMetadata),
193
- deployment: deploymentBody,
194
- });
195
- listPolicies = await this.req.get(`/apimanager/api/v1/organizations/${organizationId}/environments/${environmentId}/apis/${apiId}/policies`);
196
- if (!listPolicies.data.policies.some(p => p.template.assetId === constants_1.GATEKEEPER_POLICY_NAME)) {
197
- // Gatekeeper
198
- gateKeeper = await this.req.post(`/apimanager/api/v1/organizations/${organizationId}/environments/${environmentId}/apis/${apiId}/policies`, {
199
- configurationData: {},
200
- pointcutData: null,
201
- groupId: mulesoftOrg,
202
- assetId: constants_1.GATEKEEPER_POLICY_NAME,
203
- assetVersion: '1.0.0',
204
- order: 0,
205
- });
206
- }
207
- }
208
- catch (error) {
209
- anypoint_cli_command_1.Logger.cliEndFailed();
210
- throw error_factory_1.ErrorFactory.createPatchApiError(api.label, error);
211
- }
212
- for (const appliedPolicy of listPolicies.data.policies) {
213
- try {
214
- const policyId = appliedPolicy.policyId;
215
- await this.req.delete(`/apimanager/api/v1/organizations/${organizationId}/environments/${environmentId}/apis/${apiId}/policies/${policyId}`);
216
- }
217
- catch (error) {
218
- anypoint_cli_command_1.Logger.cliEndFailed();
219
- throw error_factory_1.ErrorFactory.deletePolicyError(api.label, gateKeeper.data.id, error);
220
- }
221
- }
222
- await this.applyInboundPolicies(api, apiId, organizationId, environmentId);
223
- await this.applyOutboundPolicies(organizationId, environmentId, apiId, api);
224
- if (gateKeeper) {
225
- try {
226
- // Delete gatekeeper
227
- await this.req.delete(`/apimanager/api/v1/organizations/${organizationId}/environments/${environmentId}/apis/${apiId}/policies/${gateKeeper.data.id}`);
228
- }
229
- catch (error) {
230
- anypoint_cli_command_1.Logger.cliEndFailed();
231
- throw error_factory_1.ErrorFactory.deletePolicyError(api.label, gateKeeper.data.id, error);
232
- }
233
- }
234
- }
235
- else {
236
- try {
237
- const createAPIResponse = await this.req.post(`/apimanager/api/v1/organizations/${organizationId}/environments/${environmentId}/apis`, {
238
- ...(commonApiBody),
239
- metadata: api.metadata,
240
- });
241
- apiId = createAPIResponse.data.id.toString();
242
- for (const tag of api.tags || []) {
243
- await this.req.put(`/apimanager/api/v1/organizations/${organizationId}/environments/${environmentId}/apis/${apiId}/tags/${tag}`);
244
- }
245
- }
246
- catch (error) {
247
- anypoint_cli_command_1.Logger.cliEndFailed();
248
- throw error_factory_1.ErrorFactory.createApiError(api.label, error);
249
- }
250
- await this.applyInboundPolicies(api, apiId, organizationId, environmentId);
120
+ const stageContextBuilder = new project_builder_impl_1.DefaultStageContextBuilder(this.req)
121
+ .withFlags(flags)
122
+ .withProperties(collectedProperties)
123
+ .withSession(this.session)
124
+ .withGateways({ ingress: ingressGW, egress: egressGW })
125
+ .withRuntimeTarget(targetPrivateSpace)
126
+ .withMaxRetries(maxRetries)
127
+ .withRequestTimeout(userRequestTimeout)
128
+ .withTracingDisabled(disableTracing)
129
+ .withDontWait(dontWaitForAgentNetwork);
130
+ logger_1.Log.cliStart(`Deploying Agent Network project ${agentNetworkDescriptor.name}.`);
131
+ const stageContext = stageContextBuilder.build();
132
+ (0, policy_helper_1.resetPolicyCache)();
251
133
  try {
252
- await this.req.post(`/proxies/xapi/v1/organizations/${organizationId}/environments/${environmentId}/apis/${apiId}/deployments`, deploymentBody);
134
+ await facets_1.ProjectFacets.execute(project_builder_1.Stages.Deployment, space, stageContext);
253
135
  }
254
136
  catch (error) {
255
- anypoint_cli_command_1.Logger.cliEndFailed();
256
- throw error_factory_1.ErrorFactory.deployError(api.label, gateway.name, error);
137
+ logger_1.Log.cliEndFailed();
138
+ throw error;
257
139
  }
258
- await this.applyOutboundPolicies(organizationId, environmentId, apiId, api);
259
- }
260
- anypoint_cli_command_1.Logger.cliEndOk();
261
- }
262
- async applyOutboundPolicies(organizationId, environmentId, apiId, api) {
263
- const upstreams = await this.req.get(`/apimanager/api/v1/organizations/${organizationId}/environments/${environmentId}/apis/${apiId}/upstreams`);
264
- const outboundPolicies = await api.outboundPolicies(apiId);
265
- for (const policy of outboundPolicies) {
266
- try {
267
- await this.req.post(`/apimanager/xapi/v1/organizations/${organizationId}/environments/${environmentId}/apis/${apiId}/policies/outbound-policies`, {
268
- configurationData: policy.configuration,
269
- groupId: policy.policyRef.groupId,
270
- assetId: policy.policyRef.assetId,
271
- assetVersion: policy.policyRef.version,
272
- upstreamIds: upstreams.data.upstreams.map(u => u.id),
273
- apiVersionId: Number(apiId),
274
- });
275
- }
276
- catch (error) {
277
- anypoint_cli_command_1.Logger.cliEndFailed();
278
- throw error_factory_1.ErrorFactory.outboundPolicyError(policy.policyRef.groupId, policy.policyRef.assetId, policy.policyRef.version, error);
279
- }
280
- }
281
- }
282
- async applyInboundPolicies(api, apiId, organizationId, environmentId) {
283
- const inboundPolicies = await api.inboundPolicies(apiId);
284
- for (const policy of inboundPolicies) {
285
- try {
286
- await this.req.post(`/apimanager/api/v1/organizations/${organizationId}/environments/${environmentId}/apis/${apiId}/policies`, {
287
- configurationData: policy.configuration,
288
- pointcutData: null,
289
- groupId: policy.policyRef.groupId,
290
- assetId: policy.policyRef.assetId,
291
- assetVersion: policy.policyRef.version,
292
- });
293
- }
294
- catch (error) {
295
- anypoint_cli_command_1.Logger.cliEndFailed();
296
- throw error_factory_1.ErrorFactory.applyPolicyError(policy.policyRef.groupId, policy.policyRef.assetId, policy.policyRef.version, error);
297
- }
298
- }
299
- }
300
- sanitizeUpstreamUrl(upstreamUrl) {
301
- if (!upstreamUrl.endsWith('/')) {
302
- return `${upstreamUrl}/`;
303
- }
304
- return upstreamUrl;
305
- }
306
- async deployApplication(agentNetworkDescriptor, instanceBuilder, privateSpace, collectedVariables, disableTracing, maxRetries, timeout) {
307
- var _b;
308
- const targetId = privateSpace.id;
309
- const runtimeVersion = await this.getLatestRuntimeVersion(privateSpace);
310
- const organizationId = this.session.selectedOrganization.id;
311
- const environmentId = this.session.selectedEnvironment.id;
312
- let deploymentId = '';
313
- const connectionsNames = {};
314
- anypoint_cli_command_1.Logger.cliStart(`Deploying application: '${agentNetworkDescriptor.name}'`);
315
- try {
316
- const connections = instanceBuilder.requiredConnections();
317
- for (const connection of connections) {
318
- const existingAPI = await this.req.get(`/apimanager/api/v1/organizations/${organizationId}/environments/${environmentId}/apis?assetId=${connection.asset.assetId}&groupId=${connection.asset.groupId}`);
319
- if (existingAPI.data.total === 0) {
320
- throw error_factory_1.ErrorFactory.connectionNotFoundError(connection.asset.groupId, connection.asset.assetId, connection.asset.version);
321
- }
322
- else {
323
- const api = this.findEgressAPI(existingAPI);
324
- if (api) {
325
- const connectionName = (_b = api.endpointUri) === null || _b === void 0 ? void 0 : _b.split('/').filter(part => part).pop();
326
- connectionsNames[`connections.${connection.asset.assetId}.default`] = connectionName;
327
- }
328
- else {
329
- throw error_factory_1.ErrorFactory.connectionNotFoundError(connection.asset.groupId, connection.asset.assetId, connection.asset.version);
330
- }
331
- }
332
- }
333
- }
334
- catch (error) {
335
- anypoint_cli_command_1.Logger.cliEndFailed();
336
- throw error_factory_1.ErrorFactory.gettingEgressConnectionError(targetId, runtimeVersion, organizationId, environmentId, error);
337
- }
338
- const body = {
339
- application: {
340
- desiredState: 'STARTED',
341
- asset: [],
342
- ref: {
343
- artifactId: gateway_1.GatewayUtils.intoMuleAppName(agentNetworkDescriptor),
344
- groupId: agentNetworkDescriptor.groupId,
345
- packaging: 'jar',
346
- version: agentNetworkDescriptor.version,
347
- },
348
- configuration: {
349
- 'mule.agent.application.properties.service': {
350
- properties: {
351
- ...collectedVariables.properties,
352
- 'mule.oauth.token.nullcheck': 'true',
353
- 'mule.put.trace.id.and.span.id.in.mdc': 'true',
354
- 'mule.http.service.implementation': 'GRIZZLY',
355
- ...connectionsNames,
356
- },
357
- secureProperties: {
358
- ...collectedVariables.securedProperties,
359
- },
360
- applicationName: agentNetworkDescriptor.assetId,
361
- },
362
- },
363
- integrations: {
364
- services: {
365
- objectStoreV2: {
366
- enabled: true,
367
- },
368
- },
369
- },
370
- ...(this.isRuntimeFabric(privateSpace) ? {} : { vCores: '0.1' }),
371
- },
372
- target: {
373
- provider: 'MC',
374
- replicas: 1,
375
- targetId: targetId,
376
- deploymentSettings: {
377
- clustered: false,
378
- disableAmLogForwarding: false,
379
- jvm: {},
380
- runtime: {
381
- version: runtimeVersion,
382
- releaseChannel: 'EDGE',
383
- java: '17',
384
- },
385
- updateStrategy: 'rolling',
386
- http: {
387
- inbound: {
388
- internalUrl: this.getInternalUrl(privateSpace, agentNetworkDescriptor.assetId),
389
- publicUrl: null,
390
- pathRewrite: null,
391
- lastMileSecurity: false,
392
- forwardSslSession: false,
393
- },
394
- },
395
- ...(this.isRuntimeFabric(privateSpace) ? {
396
- resources: {
397
- cpu: {
398
- reserved: '20m',
399
- limit: '2000m',
400
- },
401
- memory: {
402
- reserved: '700Mi',
403
- limit: '700Mi',
404
- },
405
- },
406
- } : {}),
407
- tracingEnabled: false,
408
- environmentVariables: {},
409
- generateDefaultPublicUrl: false,
410
- },
411
- },
412
- name: (0, naming_1.normalizeDeploymentName)(agentNetworkDescriptor.assetId),
413
- labels: [constants_1.BROKER_TAG, agentNetworkDescriptor.assetId],
414
- };
415
- if (!disableTracing) {
416
- const hasTracingEnabled = await entitlement_utils_1.EntitlementUtils.hasTracingEntitlement(this.req, organizationId, false);
417
- if (hasTracingEnabled) {
418
- anypoint_cli_command_1.Logger.debug('Tracing is enabled for the organization, deploying with tracing enabled');
419
- body.target.deploymentSettings.tracingEnabled = true;
420
- body.target.deploymentSettings.environmentVariables = {
421
- TRACING_ENABLED: 'true',
422
- };
423
- }
424
- }
425
- let muleAppUrl = '';
426
- try {
427
- const allDeployments = await this.req.get(`/amc/application-manager/api/v2/organizations/${organizationId}/environments/${environmentId}/deployments`);
428
- const existingDeployment = allDeployments.data.items.find(deployment => deployment.name === body.name);
429
- if (existingDeployment) {
430
- deploymentId = existingDeployment.id;
431
- await this.req.patch(`/amc/application-manager/api/v2/organizations/${organizationId}/environments/${environmentId}/deployments/${deploymentId}`, body, { headers: { 'Content-Type': 'application/json' } });
140
+ steps[3].completed = true;
141
+ if (dontWaitForAgentNetwork) {
142
+ logger_1.Log.info(`Agent network project '${agentNetworkDescriptor.name}' deployment started. The Agent Network may take some time to become ready.`);
143
+ anypoint_cli_command_1.Logger.info(`Agent network project '${agentNetworkDescriptor.name}' deployment started.`);
432
144
  }
433
145
  else {
434
- const deploymentResult = await this.req.post(`/amc/application-manager/api/v2/organizations/${organizationId}/environments/${environmentId}/deployments`, body, { headers: { 'Content-Type': 'application/json' } });
435
- deploymentId = deploymentResult.data.id;
436
- }
437
- do {
438
- await (0, utils_1.sleep)(2 * 1000); // Wait 2 seconds
439
- const getDeploymentResult = await (0, utils_1.executeRequestWithRetry)(() => this.req.get(`/amc/adam/api/organizations/${organizationId}/environments/${environmentId}/deployments/${deploymentId}`, { timeout: timeout }), maxRetries, timeout);
440
- muleAppUrl = getDeploymentResult.data.target.deploymentSettings.http.inbound.internalUrl;
441
- } while (!muleAppUrl);
442
- }
443
- catch (error) {
444
- anypoint_cli_command_1.Logger.cliEndFailed();
445
- throw error_factory_1.ErrorFactory.deployAPIError(error);
446
- }
447
- anypoint_cli_command_1.Logger.cliEndOk();
448
- return { url: muleAppUrl, deploymentId };
449
- }
450
- getInternalUrl(privateSpace, assetId) {
451
- return this.isRuntimeFabric(privateSpace) ? this.getMuleAppUrlForRuntimeFabric(assetId) : null;
452
- }
453
- isRuntimeFabric(privateSpace) {
454
- return privateSpace.type === constants_1.RUNTIME_FABRIC_TARGET_TYPE;
455
- }
456
- findEgressAPI(existingAPI) {
457
- const assets = existingAPI.data.assets;
458
- let api;
459
- for (const asset of assets) {
460
- api = asset.apis.find(api => {
461
- var _b;
462
- return ((_b = api.metadata) === null || _b === void 0 ? void 0 : _b.protectionDirection) === 'egress';
463
- });
464
- if (api) {
465
- break;
466
- }
467
- }
468
- return api;
469
- }
470
- getAgentRegistryUrl(gateway) {
471
- let url = gateway.configuration.ingress.publicUrl || gateway.configuration.ingress.internalUrl;
472
- if (url.indexOf(',') > -1) {
473
- url = url.split(',')[0];
474
- }
475
- if (url.endsWith('/')) {
476
- url = url.slice(0, -1);
477
- }
478
- return url;
479
- }
480
- getMuleAppUrlForRuntimeFabric(applicationId) {
481
- return `http://${applicationId}:8081/`;
482
- }
483
- async getLatestRuntimeVersion(privateSpace) {
484
- var _b;
485
- try {
486
- const targetSpace = await gateway_1.GatewayUtils.getTargetSpaceMetadata(this.req, this.session.selectedOrganization.id, privateSpace.id);
487
- const runtimeVersions = (_b = targetSpace.runtimes
488
- .find(runtime => runtime.type.toLowerCase() === 'mule')) === null || _b === void 0 ? void 0 : _b.versions.filter(version => version.channel.toUpperCase() === 'EDGE').map(version => version.baseVersion).sort((a, b) => semver_1.default.compare(b, a));
489
- return Array.isArray(runtimeVersions) && runtimeVersions.length > 0 ? runtimeVersions[0] : Deploy.DEFAULT_MULE_VERSION;
490
- }
491
- catch {
492
- anypoint_cli_command_1.Logger.debug('Could not fetch runtime versions from API, using default');
493
- }
494
- // Fallback to default version if API call fails
495
- return Deploy.DEFAULT_MULE_VERSION;
496
- }
497
- checkIfPromptsNeeded(variables, defaultProp, prefix = '') {
498
- for (const [key, value] of Object.entries(variables)) {
499
- const fullKey = prefix ? `${prefix}.${key}` : key;
500
- if (typeof value === 'object' && value !== null && 'description' in value) {
501
- // This is a leaf variable with description
502
- if (!defaultProp[fullKey]) {
503
- return true;
504
- }
505
- }
506
- else if (typeof value === 'object' && value !== null && // This is a nested object, recurse
507
- this.checkIfPromptsNeeded(value, defaultProp, fullKey)) {
508
- return true;
146
+ logger_1.Log.info(`Agent network project '${agentNetworkDescriptor.name}' was deployed.`);
147
+ anypoint_cli_command_1.Logger.info(`Agent network project '${agentNetworkDescriptor.name}' was deployed.`);
509
148
  }
510
- }
511
- return false;
149
+ logger_1.Log.cliEndOk();
150
+ };
151
+ return (0, utils_1.runCommandWithTimeout)(deployCommand(), userProcessTimeout, 'Deploy', requestId, () => steps)
152
+ .finally(() => {
153
+ var _a, _b;
154
+ (_a = this.req.interceptors.request) === null || _a === void 0 ? void 0 : _a.eject(requestInterceptorId);
155
+ (_b = this.req.interceptors.response) === null || _b === void 0 ? void 0 : _b.eject(responseInterceptorId);
156
+ });
512
157
  }
513
- async promptForVariables(variables, defaultProp, prefix = '') {
514
- let collectedVariables = { properties: {}, securedProperties: {} };
515
- for (const [key, value] of Object.entries(variables)) {
516
- const fullKey = prefix ? `${prefix}.${key}` : key;
517
- if (typeof value === 'object' && value !== null && 'description' in value) {
518
- // This is a leaf variable with description
519
- const varValue = value;
520
- const isSecured = !(varValue.secret === false);
521
- const propertyGroup = isSecured ? collectedVariables.securedProperties : collectedVariables.properties;
522
- if (defaultProp[fullKey]) {
523
- propertyGroup[fullKey] = defaultProp[fullKey];
524
- }
525
- else {
526
- const promptText = `${varValue.description}`;
527
- const userInput = await anypoint_cli_command_1.Logger.cliPrompt(promptText, {
528
- default: varValue.default,
529
- type: isSecured ? 'mask' : 'normal',
530
- });
531
- propertyGroup[fullKey] = userInput || varValue.default || '';
532
- }
533
- }
534
- else if (typeof value === 'object' && value !== null) {
535
- const childVariables = await this.promptForVariables(value, defaultProp, fullKey);
536
- // This is a nested object, recurse
537
- collectedVariables = {
538
- properties: {
539
- ...collectedVariables.properties,
540
- ...childVariables.properties,
541
- },
542
- securedProperties: {
543
- ...collectedVariables.securedProperties,
544
- ...childVariables.securedProperties,
545
- },
546
- };
547
- }
548
- }
549
- return collectedVariables;
158
+ toErrorJson(err) {
159
+ return { error: { ...err, message: err.message } };
550
160
  }
551
161
  checkGatewayTargetSpace(ingressGW, egressGW, targetPrivateSpace) {
552
162
  return ingressGW.targetId === targetPrivateSpace.id && egressGW.targetId === targetPrivateSpace.id;
553
163
  }
554
164
  }
555
165
  exports.default = Deploy;
556
- _a = Deploy;
557
- Deploy.defaultRequestTimeout = 60 * 1000; // 60 seconds
558
- Deploy.defaultProcessTimeout = 10 * 60 * 1000; // 10 minutes
559
166
  Deploy.description = 'Deploys the Agent Network application';
560
167
  Deploy.DEFAULT_MULE_VERSION = '4.9.7';
561
168
  Deploy.examples = [
562
169
  '$ agent-network project deploy',
170
+ '$ agent-network project deploy --property apiKey:sk-xxx',
171
+ '$ agent-network project deploy --property apiKey:sk-xxx --property role:user',
172
+ '$ agent-network project deploy --path ./my-project --property myAgent.url:https://api.example.com',
563
173
  ];
564
174
  Deploy.flags = {
565
175
  ...anypoint_cli_command_1.AuthenticationBaseCommand.flags,
@@ -568,14 +178,15 @@ Deploy.flags = {
568
178
  'target-space': core_1.Flags.string({ char: 't', description: 'Name of the target private space to deploy', default: constants_1.AGENT_NETWORK_TARGET_SPACE }),
569
179
  'dont-wait-for-agent-network': core_1.Flags.boolean({ description: 'Do not wait for the Agent Network to be ready', default: false }),
570
180
  'disable-tracing': core_1.Flags.boolean({ description: 'Disable tracing functionalities', default: false }),
571
- property: core_1.Flags.string({ multiple: true, description: 'Name and value for the properties. Name:Value', default: [] }),
181
+ property: core_1.Flags.string({ multiple: true, description: 'Property to override in format name:value (e.g., --property apiKey:sk-xxx)', default: [] }),
572
182
  path: core_1.Flags.file({
573
183
  description: 'The path to the project.',
574
184
  default: '.',
575
185
  }),
576
186
  'max-retries': core_1.Flags.integer({ description: 'Max retries to check the status of the deploying application.', required: false, default: 3 }),
577
- 'request-timeout': core_1.Flags.integer({ description: 'Request timeout in millis.', required: false, default: _a.defaultRequestTimeout }),
578
- 'process-timeout': core_1.Flags.integer({ description: 'Request timeout in millis.', required: false, default: _a.defaultProcessTimeout }),
187
+ 'request-timeout': core_1.Flags.integer({ description: 'Request timeout in millis.', required: false, default: request_utils_1.DEFAULT_REQUEST_TIMEOUT }),
188
+ 'process-timeout': core_1.Flags.integer({ description: 'Request timeout in millis.', required: false, default: request_utils_1.DEFAULT_PROCESS_TIMEOUT }),
189
+ 'force-ownership': core_1.Flags.boolean({ description: 'Force ownership', default: false, hidden: true }),
579
190
  };
580
191
  Deploy.enableJsonFlag = true;
581
192
  //# sourceMappingURL=deploy.js.map