@aifabrix/builder 2.37.0 → 2.37.5

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.
@@ -16,6 +16,23 @@ const { validateControllerUrl, validateEnvironmentKey } = require('../utils/depl
16
16
  const { handleDeploymentError, handleDeploymentErrors } = require('../utils/deployment-errors');
17
17
  const { validatePipeline, deployPipeline, getPipelineDeployment } = require('../api/pipeline.api');
18
18
  const { handleValidationResponse } = require('../utils/deployment-validation-helpers');
19
+ const {
20
+ convertToPipelineAuthConfig,
21
+ processDeploymentStatusResponse
22
+ } = require('./deployer-status');
23
+
24
+ /**
25
+ * For external systems, send full manifest (application + inline system + full dataSources).
26
+ * No transform - controller receives complete application, external system, and data sources.
27
+ * @param {Object} manifest - Full manifest (type 'external', system, dataSources as full objects)
28
+ * @returns {Object} Manifest to send to pipeline (external sent as-is)
29
+ */
30
+ function transformExternalManifestForPipeline(manifest) {
31
+ if (!manifest) {
32
+ return manifest;
33
+ }
34
+ return manifest;
35
+ }
19
36
 
20
37
  /**
21
38
  * Build validation data for deployment
@@ -28,27 +45,42 @@ const { handleValidationResponse } = require('../utils/deployment-validation-hel
28
45
  */
29
46
  async function buildValidationData(manifest, validatedEnvKey, authConfig, options) {
30
47
  const tokenManager = require('../utils/token-manager');
31
- const { clientId, clientSecret } = await tokenManager.extractClientCredentials(
32
- authConfig,
33
- manifest.key,
34
- validatedEnvKey,
35
- options
36
- );
48
+ let clientId;
49
+ let clientSecret;
50
+ let pipelineAuthConfig;
51
+
52
+ try {
53
+ const credentials = await tokenManager.extractClientCredentials(
54
+ authConfig,
55
+ manifest.key,
56
+ validatedEnvKey,
57
+ options
58
+ );
59
+ clientId = credentials.clientId;
60
+ clientSecret = credentials.clientSecret;
61
+ pipelineAuthConfig = {
62
+ type: 'client-credentials',
63
+ clientId,
64
+ clientSecret
65
+ };
66
+ } catch (credError) {
67
+ if (authConfig.type === 'bearer' && authConfig.token) {
68
+ pipelineAuthConfig = { type: 'bearer', token: authConfig.token };
69
+ clientId = manifest.key;
70
+ clientSecret = '';
71
+ } else {
72
+ throw credError;
73
+ }
74
+ }
37
75
 
38
76
  const repositoryUrl = options.repositoryUrl || `https://github.com/aifabrix/${manifest.key}`;
39
77
  const validationData = {
40
- clientId: clientId,
41
- clientSecret: clientSecret,
78
+ clientId: clientId || '',
79
+ clientSecret: clientSecret || '',
42
80
  repositoryUrl: repositoryUrl,
43
81
  applicationConfig: manifest
44
82
  };
45
83
 
46
- const pipelineAuthConfig = {
47
- type: 'client-credentials',
48
- clientId: clientId,
49
- clientSecret: clientSecret
50
- };
51
-
52
84
  return { validationData, pipelineAuthConfig };
53
85
  }
54
86
 
@@ -130,7 +162,7 @@ function validateDeploymentCredentials(authConfig) {
130
162
  }
131
163
 
132
164
  /**
133
- * Build deployment data and auth config
165
+ * Build deployment data and auth config (supports bearer-only when no client credentials)
134
166
  * @param {string} validateToken - Validation token
135
167
  * @param {Object} authConfig - Authentication configuration
136
168
  * @param {Object} options - Deployment options
@@ -143,11 +175,13 @@ function buildDeploymentData(validateToken, authConfig, options) {
143
175
  imageTag: imageTag
144
176
  };
145
177
 
146
- const pipelineAuthConfig = {
147
- type: 'client-credentials',
148
- clientId: authConfig.clientId,
149
- clientSecret: authConfig.clientSecret
150
- };
178
+ const pipelineAuthConfig = authConfig.type === 'bearer' && authConfig.token && !authConfig.clientId
179
+ ? { type: 'bearer', token: authConfig.token }
180
+ : {
181
+ type: 'client-credentials',
182
+ clientId: authConfig.clientId,
183
+ clientSecret: authConfig.clientSecret
184
+ };
151
185
 
152
186
  return { deployData, pipelineAuthConfig };
153
187
  }
@@ -212,10 +246,12 @@ async function sendDeploymentRequest(url, envKey, validateToken, authConfig, opt
212
246
  const validatedEnvKey = validateEnvironmentKey(envKey);
213
247
  const maxRetries = options.maxRetries || 3;
214
248
 
215
- // Validate credentials
216
- validateDeploymentCredentials(authConfig);
249
+ const useBearerOnly = authConfig.type === 'bearer' && authConfig.token && !authConfig.clientId;
250
+ if (!useBearerOnly) {
251
+ validateDeploymentCredentials(authConfig);
252
+ }
217
253
 
218
- // Build deployment data
254
+ // Build deployment data (supports bearer-only when no client credentials)
219
255
  const { deployData, pipelineAuthConfig } = buildDeploymentData(validateToken, authConfig, options);
220
256
 
221
257
  // Wrap API call with retry logic
@@ -237,92 +273,6 @@ async function sendDeploymentRequest(url, envKey, validateToken, authConfig, opt
237
273
  throwDeploymentError(lastError, maxRetries);
238
274
  }
239
275
 
240
- /**
241
- * Checks if deployment status is terminal
242
- * @function isTerminalStatus
243
- * @param {string} status - Deployment status
244
- * @returns {boolean} True if status is terminal
245
- */
246
- function isTerminalStatus(status) {
247
- return status === 'completed' || status === 'failed' || status === 'cancelled';
248
- }
249
-
250
- /**
251
- * Convert authConfig to pipeline auth config format
252
- * @param {Object} authConfig - Authentication configuration
253
- * @returns {Object} Pipeline auth config
254
- */
255
- function convertToPipelineAuthConfig(authConfig) {
256
- return authConfig.type === 'bearer'
257
- ? { type: 'bearer', token: authConfig.token }
258
- : { type: 'client-credentials', clientId: authConfig.clientId, clientSecret: authConfig.clientSecret };
259
- }
260
-
261
- /**
262
- * Process deployment status response
263
- * @param {Object} response - API response
264
- * @param {number} attempt - Current attempt number
265
- * @param {number} maxAttempts - Maximum attempts
266
- * @param {number} interval - Polling interval
267
- * @param {string} deploymentId - Deployment ID for error messages
268
- * @returns {Object|null} Deployment data if terminal, null if needs to continue polling
269
- */
270
- /**
271
- * Handles error response from deployment status check
272
- * @function handleDeploymentStatusError
273
- * @param {Object} response - API response
274
- * @param {string} deploymentId - Deployment ID
275
- * @throws {Error} Appropriate error message
276
- */
277
- function handleDeploymentStatusError(response, deploymentId) {
278
- if (response.status === 404) {
279
- throw new Error(`Deployment ${deploymentId || response.deploymentId || 'unknown'} not found`);
280
- }
281
- throw new Error(`Status check failed: ${response.formattedError || response.error || 'Unknown error'}`);
282
- }
283
-
284
- /**
285
- * Extracts deployment data from response
286
- * @function extractDeploymentData
287
- * @param {Object} response - API response
288
- * @returns {Object} Deployment data
289
- */
290
- function extractDeploymentData(response) {
291
- const responseData = response.data;
292
- return responseData.data || responseData;
293
- }
294
-
295
- /**
296
- * Logs deployment progress
297
- * @function logDeploymentProgress
298
- * @param {Object} deploymentData - Deployment data
299
- * @param {number} attempt - Current attempt
300
- * @param {number} maxAttempts - Maximum attempts
301
- */
302
- function logDeploymentProgress(deploymentData, attempt, maxAttempts) {
303
- const status = deploymentData.status;
304
- const progress = deploymentData.progress || 0;
305
- logger.log(chalk.blue(` Status: ${status} (${progress}%) (attempt ${attempt + 1}/${maxAttempts})`));
306
- }
307
-
308
- async function processDeploymentStatusResponse(response, attempt, maxAttempts, interval, deploymentId) {
309
- if (!response.success || !response.data) {
310
- handleDeploymentStatusError(response, deploymentId);
311
- }
312
-
313
- const deploymentData = extractDeploymentData(response);
314
- if (isTerminalStatus(deploymentData.status)) {
315
- return deploymentData;
316
- }
317
-
318
- logDeploymentProgress(deploymentData, attempt, maxAttempts);
319
- if (attempt < maxAttempts - 1) {
320
- await new Promise(resolve => setTimeout(resolve, interval));
321
- }
322
-
323
- return null;
324
- }
325
-
326
276
  /**
327
277
  * Polls deployment status from controller
328
278
  * Uses pipeline endpoint for CI/CD monitoring with minimal deployment info
@@ -470,9 +420,11 @@ async function deployToController(manifest, controllerUrl, envKey, authConfig, o
470
420
  // Log deployment attempt for audit
471
421
  await auditLogger.logDeploymentAttempt(manifest.key, url, options);
472
422
 
423
+ const pipelineManifest = transformExternalManifestForPipeline(manifest);
424
+
473
425
  try {
474
426
  // Send deployment request
475
- const result = await sendDeployment(url, validatedEnvKey, manifest, authConfig, options);
427
+ const result = await sendDeployment(url, validatedEnvKey, pipelineManifest, authConfig, options);
476
428
 
477
429
  // Poll for deployment status if enabled
478
430
  return await pollDeployment(result, url, validatedEnvKey, authConfig, options);
@@ -9,16 +9,21 @@
9
9
  * @version 2.0.0
10
10
  */
11
11
 
12
+ const fs = require('fs');
13
+ const path = require('path');
12
14
  const chalk = require('chalk');
15
+ const Ajv = require('ajv');
13
16
  const logger = require('../utils/logger');
14
17
  const config = require('../core/config');
15
18
  const { resolveControllerUrl } = require('../utils/controller-url');
16
19
  const { validateControllerUrl, validateEnvironmentKey } = require('../utils/deployment-validation');
17
20
  const { getOrRefreshDeviceToken } = require('../utils/token-manager');
18
- const { getEnvironmentStatus } = require('../api/environments.api');
19
- const { deployEnvironment: deployEnvironmentInfra } = require('../api/deployments.api');
21
+ const { getPipelineDeployment } = require('../api/pipeline.api');
22
+ const { deployEnvironment: deployEnvironmentInfra, getDeployment } = require('../api/deployments.api');
20
23
  const { handleDeploymentErrors } = require('../utils/deployment-errors');
24
+ const { formatValidationErrors } = require('../utils/error-formatter');
21
25
  const auditLogger = require('../core/audit-logger');
26
+ const environmentDeployRequestSchema = require('../schema/environment-deploy-request.schema.json');
22
27
 
23
28
  /**
24
29
  * Validates environment deployment prerequisites
@@ -78,25 +83,88 @@ async function getEnvironmentAuth(controllerUrl) {
78
83
  * @throws {Error} If deployment fails
79
84
  */
80
85
  /**
81
- * Builds environment deployment request
86
+ * Loads and validates environment deploy config from a JSON file
87
+ * @param {string} configPath - Absolute or relative path to config JSON
88
+ * @returns {Object} Valid deploy request { environmentConfig, dryRun? }
89
+ * @throws {Error} If file missing, invalid JSON, or validation fails
90
+ */
91
+ function loadAndValidateEnvironmentDeployConfig(configPath) {
92
+ const resolvedPath = path.isAbsolute(configPath) ? configPath : path.resolve(process.cwd(), configPath);
93
+ if (!fs.existsSync(resolvedPath)) {
94
+ throw new Error(
95
+ `Environment config file not found: ${resolvedPath}\n` +
96
+ 'Use --config <file> with a JSON file containing "environmentConfig" (e.g. templates/infra/environment-dev.json).'
97
+ );
98
+ }
99
+ let raw;
100
+ try {
101
+ raw = fs.readFileSync(resolvedPath, 'utf8');
102
+ } catch (e) {
103
+ throw new Error(`Cannot read config file: ${resolvedPath}. ${e.message}`);
104
+ }
105
+ let parsed;
106
+ try {
107
+ parsed = JSON.parse(raw);
108
+ } catch (e) {
109
+ throw new Error(
110
+ `Invalid JSON in config file: ${resolvedPath}\n${e.message}\n` +
111
+ 'Expected format: { "environmentConfig": { "key", "environment", "preset", "serviceName", "location" }, "dryRun": false }'
112
+ );
113
+ }
114
+ if (parsed === null || typeof parsed !== 'object') {
115
+ throw new Error(
116
+ `Config file must be a JSON object with "environmentConfig". File: ${resolvedPath}\n` +
117
+ 'Example: { "environmentConfig": { "key": "dev", "environment": "dev", "preset": "s", "serviceName": "aifabrix", "location": "swedencentral" }, "dryRun": false }'
118
+ );
119
+ }
120
+ if (parsed.environmentConfig === undefined) {
121
+ throw new Error(
122
+ `Config file must contain "environmentConfig" (object). File: ${resolvedPath}\n` +
123
+ 'Example: { "environmentConfig": { "key": "dev", "environment": "dev", "preset": "s", "serviceName": "aifabrix", "location": "swedencentral" } }'
124
+ );
125
+ }
126
+ if (typeof parsed.environmentConfig !== 'object' || parsed.environmentConfig === null) {
127
+ throw new Error(
128
+ `"environmentConfig" must be an object. File: ${resolvedPath}`
129
+ );
130
+ }
131
+ const ajv = new Ajv({ allErrors: true, strict: false });
132
+ const validate = ajv.compile(environmentDeployRequestSchema);
133
+ const valid = validate(parsed);
134
+ if (!valid) {
135
+ const messages = formatValidationErrors(validate.errors);
136
+ throw new Error(
137
+ `Environment config validation failed (${resolvedPath}):\n • ${messages.join('\n • ')}\n` +
138
+ 'Fix the config file and run the command again. See templates/infra/environment-dev.json for a valid example.'
139
+ );
140
+ }
141
+ return {
142
+ environmentConfig: parsed.environmentConfig,
143
+ dryRun: Boolean(parsed.dryRun)
144
+ };
145
+ }
146
+
147
+ /**
148
+ * Builds environment deployment request from options (config file required)
82
149
  * @function buildEnvironmentDeploymentRequest
83
150
  * @param {string} validatedEnvKey - Validated environment key
84
- * @param {Object} options - Deployment options
85
- * @returns {Object} Deployment request object
151
+ * @param {Object} options - Deployment options (must include options.config)
152
+ * @returns {Object} Deployment request object for API
86
153
  */
87
154
  function buildEnvironmentDeploymentRequest(validatedEnvKey, options) {
88
- const capitalized = validatedEnvKey.charAt(0).toUpperCase() + validatedEnvKey.slice(1);
89
- const request = {
90
- key: validatedEnvKey,
91
- displayName: `${capitalized} Environment`,
92
- description: `${capitalized} environment for application deployments`
93
- };
94
-
95
- if (options.config) {
96
- request.description += ` (config: ${options.config})`;
155
+ if (!options.config || typeof options.config !== 'string') {
156
+ throw new Error(
157
+ 'Environment deploy requires a config file with "environmentConfig". Use --config <file>.\n' +
158
+ 'Example: aifabrix environment deploy dev --config templates/infra/environment-dev.json'
159
+ );
97
160
  }
98
-
99
- return request;
161
+ const deployRequest = loadAndValidateEnvironmentDeployConfig(options.config);
162
+ if (deployRequest.environmentConfig.key && deployRequest.environmentConfig.key !== validatedEnvKey) {
163
+ logger.log(chalk.yellow(
164
+ `⚠ Config key "${deployRequest.environmentConfig.key}" does not match deploy target "${validatedEnvKey}"; using target "${validatedEnvKey}".`
165
+ ));
166
+ }
167
+ return deployRequest;
100
168
  }
101
169
 
102
170
  /**
@@ -155,22 +223,47 @@ async function sendEnvironmentDeployment(controllerUrl, envKey, authConfig, opti
155
223
  }
156
224
 
157
225
  /**
158
- * Process environment status response
159
- * @param {Object} response - API response
226
+ * Fetches deployment status by ID (pipeline endpoint first, then environments)
227
+ * Mirrors miso-controller manual test: GET pipeline/deployments/:id then GET environments/deployments/:id
228
+ * @async
229
+ * @param {string} controllerUrl - Controller URL
230
+ * @param {string} envKey - Environment key
231
+ * @param {string} deploymentId - Deployment ID
232
+ * @param {Object} apiAuthConfig - Auth config { type: 'bearer', token }
233
+ * @returns {Promise<Object|null>} Deployment record (status, progress, etc.) or null
234
+ */
235
+ async function getDeploymentStatusById(controllerUrl, envKey, deploymentId, apiAuthConfig) {
236
+ try {
237
+ const pipelineRes = await getPipelineDeployment(controllerUrl, envKey, deploymentId, apiAuthConfig);
238
+ if (pipelineRes?.data?.data) return pipelineRes.data.data;
239
+ if (pipelineRes?.data && typeof pipelineRes.data === 'object' && pipelineRes.data.status) return pipelineRes.data;
240
+ } catch {
241
+ // Fallback to environments endpoint
242
+ }
243
+ try {
244
+ const envRes = await getDeployment(controllerUrl, envKey, deploymentId, apiAuthConfig);
245
+ if (envRes?.data?.data) return envRes.data.data;
246
+ if (envRes?.data && typeof envRes.data === 'object' && envRes.data.status) return envRes.data;
247
+ } catch {
248
+ // Ignore
249
+ }
250
+ return null;
251
+ }
252
+
253
+ /**
254
+ * Process deployment record from GET .../deployments/:deploymentId
255
+ * @param {Object|null} deployment - Deployment record (status, progress, message, error)
160
256
  * @param {string} validatedEnvKey - Validated environment key
161
- * @returns {Object|null} Status result if ready, null if needs to continue polling
257
+ * @returns {Object|null} Status result if completed, null if still in progress
162
258
  * @throws {Error} If deployment failed
163
259
  */
164
- function processEnvironmentStatusResponse(response, validatedEnvKey) {
165
- if (!response.success || !response.data) {
260
+ function processDeploymentStatusResponse(deployment, validatedEnvKey) {
261
+ if (!deployment || typeof deployment !== 'object') {
166
262
  return null;
167
263
  }
168
264
 
169
- const responseData = response.data.data || response.data;
170
- const status = responseData.status || responseData.ready;
171
- const isReady = status === 'ready' || status === 'completed' || responseData.ready === true;
172
-
173
- if (isReady) {
265
+ const status = deployment.status;
266
+ if (status === 'completed') {
174
267
  return {
175
268
  success: true,
176
269
  environment: validatedEnvKey,
@@ -179,9 +272,9 @@ function processEnvironmentStatusResponse(response, validatedEnvKey) {
179
272
  };
180
273
  }
181
274
 
182
- // Check for terminal failure states
183
275
  if (status === 'failed' || status === 'error') {
184
- throw new Error(`Environment deployment failed: ${responseData.message || 'Unknown error'}`);
276
+ const msg = deployment.message || deployment.error || 'Unknown error';
277
+ throw new Error(`Environment deployment failed: ${msg}`);
185
278
  }
186
279
 
187
280
  return null;
@@ -213,8 +306,18 @@ async function pollEnvironmentStatus(deploymentId, controllerUrl, envKey, authCo
213
306
  try {
214
307
  await new Promise(resolve => setTimeout(resolve, pollInterval));
215
308
 
216
- const response = await getEnvironmentStatus(validatedUrl, validatedEnvKey, apiAuthConfig);
217
- const statusResult = processEnvironmentStatusResponse(response, validatedEnvKey);
309
+ const deployment = await getDeploymentStatusById(
310
+ validatedUrl,
311
+ validatedEnvKey,
312
+ deploymentId,
313
+ apiAuthConfig
314
+ );
315
+ const progress = deployment?.progress ?? 0;
316
+ const statusLabel = deployment?.status ?? 'pending';
317
+ if (attempt <= maxAttempts) {
318
+ logger.log(chalk.gray(` Attempt ${attempt}/${maxAttempts}... Status: ${statusLabel} (${progress}%)`));
319
+ }
320
+ const statusResult = processDeploymentStatusResponse(deployment, validatedEnvKey);
218
321
  if (statusResult) {
219
322
  return statusResult;
220
323
  }
@@ -225,10 +328,6 @@ async function pollEnvironmentStatus(deploymentId, controllerUrl, envKey, authCo
225
328
  }
226
329
  // Otherwise, continue polling
227
330
  }
228
-
229
- if (attempt < maxAttempts) {
230
- logger.log(chalk.gray(` Attempt ${attempt}/${maxAttempts}...`));
231
- }
232
331
  }
233
332
 
234
333
  // Timeout
@@ -97,7 +97,11 @@ async function deployExternalSystem(appName, options = {}) {
97
97
 
98
98
  return result;
99
99
  } catch (error) {
100
- throw new Error(`Failed to deploy external system: ${error.message}`);
100
+ let message = `Failed to deploy external system: ${error.message}`;
101
+ if (error.message && error.message.includes('Application not found')) {
102
+ message += `\n\n💡 Register the app in the controller first: aifabrix app register ${appName}`;
103
+ }
104
+ throw new Error(message);
101
105
  }
102
106
  }
103
107
 
@@ -1,7 +1,9 @@
1
1
  /**
2
2
  * External System Test Authentication Helpers
3
3
  *
4
- * Authentication setup for integration tests
4
+ * Authentication setup for integration tests. Uses the dataplane service URL
5
+ * (discovered from the controller), not the external system app's config—external
6
+ * apps do not store a dataplane URL.
5
7
  *
6
8
  * @fileoverview Authentication helpers for external system testing
7
9
  * @author AI Fabrix Team
@@ -9,19 +11,19 @@
9
11
  */
10
12
 
11
13
  const { getDeploymentAuth } = require('../utils/token-manager');
12
- const { getDataplaneUrl } = require('../datasource/deploy');
14
+ const { resolveDataplaneUrl } = require('../utils/dataplane-resolver');
13
15
  const { resolveControllerUrl } = require('../utils/controller-url');
14
16
 
15
17
  /**
16
18
  * Setup authentication and get dataplane URL for integration tests
17
19
  * @async
18
- * @param {string} appName - Application name
19
- * @param {Object} options - Test options
20
- * @param {Object} config - Configuration object
20
+ * @param {string} appName - Application name (used for auth scope; dataplane URL is discovered from controller)
21
+ * @param {Object} options - Test options; options.dataplane overrides discovered URL
22
+ * @param {Object} _config - Configuration object
21
23
  * @returns {Promise<Object>} Object with authConfig and dataplaneUrl
22
24
  * @throws {Error} If authentication fails
23
25
  */
24
- async function setupIntegrationTestAuth(appName, _options, _config) {
26
+ async function setupIntegrationTestAuth(appName, options, _config) {
25
27
  const { resolveEnvironment } = require('../core/config');
26
28
  const environment = await resolveEnvironment();
27
29
  const controllerUrl = await resolveControllerUrl();
@@ -31,7 +33,12 @@ async function setupIntegrationTestAuth(appName, _options, _config) {
31
33
  throw new Error('Authentication required. Run "aifabrix login" or "aifabrix app register" first.');
32
34
  }
33
35
 
34
- const dataplaneUrl = await getDataplaneUrl(controllerUrl, appName, environment, authConfig);
36
+ let dataplaneUrl;
37
+ if (options && options.dataplane && typeof options.dataplane === 'string' && options.dataplane.trim()) {
38
+ dataplaneUrl = options.dataplane.trim();
39
+ } else {
40
+ dataplaneUrl = await resolveDataplaneUrl(controllerUrl, environment, authConfig);
41
+ }
35
42
 
36
43
  return { authConfig, dataplaneUrl };
37
44
  }
@@ -12,6 +12,19 @@ const chalk = require('chalk');
12
12
  const logger = require('../utils/logger');
13
13
  const { generateExternalReadmeContent } = require('../utils/external-readme');
14
14
 
15
+ /**
16
+ * Converts a string to a schema-valid key segment (lowercase letters, numbers, hyphens only).
17
+ * e.g. "recordStorage" -> "record-storage", "documentStorage" -> "document-storage"
18
+ * @param {string} str - Raw entity type or key segment (may be camelCase)
19
+ * @returns {string} Segment matching ^[a-z0-9-]+$
20
+ */
21
+ function toKeySegment(str) {
22
+ if (!str || typeof str !== 'string') return 'default';
23
+ const withHyphens = str.replace(/([A-Z])/g, '-$1').toLowerCase();
24
+ const sanitized = withHyphens.replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
25
+ return sanitized || 'default';
26
+ }
27
+
15
28
  /**
16
29
  * Generate files from dataplane-generated wizard configurations
17
30
  * @async
@@ -53,11 +66,12 @@ async function writeDatasourceJsonFiles(appPath, finalSystemKey, datasourceConfi
53
66
  const datasourceFileNames = [];
54
67
  for (const datasourceConfig of datasourceConfigs) {
55
68
  const entityType = datasourceConfig.entityType || datasourceConfig.entityKey || datasourceConfig.key?.split('-').pop() || 'default';
56
- const datasourceKey = datasourceConfig.key || `${finalSystemKey}-${entityType}`;
57
- // Extract datasource key (remove system key prefix if present)
69
+ const keySegment = toKeySegment(entityType);
70
+ const datasourceKey = datasourceConfig.key || `${finalSystemKey}-${keySegment}`;
71
+ // Extract datasource key (remove system key prefix if present); use normalized segment for filename
58
72
  const datasourceKeyOnly = datasourceKey.includes('-') && datasourceKey.startsWith(`${finalSystemKey}-`)
59
73
  ? datasourceKey.substring(finalSystemKey.length + 1)
60
- : entityType;
74
+ : keySegment;
61
75
  const datasourceFileName = `${finalSystemKey}-datasource-${datasourceKeyOnly}.json`;
62
76
  const datasourceFilePath = path.join(appPath, datasourceFileName);
63
77
  await fs.writeFile(datasourceFilePath, JSON.stringify(datasourceConfig, null, 2), 'utf8');
@@ -143,13 +157,14 @@ async function generateWizardFiles(appName, systemConfig, datasourceConfigs, sys
143
157
  displayName: appDisplayName
144
158
  };
145
159
 
146
- // Update datasource configs to use appName-based keys and systemKey
160
+ // Update datasource configs to use appName-based keys and systemKey (key must match ^[a-z0-9-]+$)
147
161
  const updatedDatasourceConfigs = datasourceConfigs.map(ds => {
148
162
  const entityType = ds.entityType || ds.entityKey || ds.key?.split('-').pop() || 'default';
163
+ const keySegment = toKeySegment(entityType);
149
164
  const entityDisplayName = entityType.charAt(0).toUpperCase() + entityType.slice(1).replace(/-/g, ' ');
150
165
  return {
151
166
  ...ds,
152
- key: `${finalSystemKey}-${entityType}`,
167
+ key: `${finalSystemKey}-${keySegment}`,
153
168
  systemKey: finalSystemKey,
154
169
  displayName: `${appDisplayName} ${entityDisplayName}`
155
170
  };
@@ -360,23 +375,22 @@ async function generateEnvTemplate(appPath, systemConfig) {
360
375
  }
361
376
 
362
377
  /**
363
- * Generate deployment scripts (deploy.sh, deploy.ps1, deploy.js) from templates
378
+ * Generate deployment script (deploy.js) from template
364
379
  * @async
365
380
  * @function generateDeployScripts
366
381
  * @param {string} appPath - Application directory path
367
382
  * @param {string} systemKey - System key
368
383
  * @param {string} systemFileName - System file name
369
384
  * @param {string[]} datasourceFileNames - Array of datasource file names
370
- * @returns {Promise<Object>} Object with deployShPath, deployPs1Path, deployJsPath
385
+ * @returns {Promise<Object>} Object with deployJsPath
371
386
  * @throws {Error} If generation fails
372
387
  */
373
388
  const templatesExternalDir = path.join(__dirname, '..', '..', 'templates', 'external-system');
374
389
 
375
- async function writeDeployScriptFromTemplate(templateName, outputPath, context, executable) {
390
+ async function writeDeployScriptFromTemplate(templateName, outputPath, context) {
376
391
  const templatePath = path.join(templatesExternalDir, templateName);
377
392
  const content = Handlebars.compile(await fs.readFile(templatePath, 'utf8'))(context);
378
393
  await fs.writeFile(outputPath, content, 'utf8');
379
- if (executable) await fs.chmod(outputPath, 0o755);
380
394
  logger.log(chalk.green(`✓ Generated ${path.basename(outputPath)}`));
381
395
  }
382
396
 
@@ -385,13 +399,9 @@ async function generateDeployScripts(appPath, systemKey, systemFileName, datasou
385
399
  const allJsonFiles = [systemFileName, ...datasourceFileNames];
386
400
  const context = { systemKey, allJsonFiles, datasourceFileNames };
387
401
 
388
- await writeDeployScriptFromTemplate('deploy.sh.hbs', path.join(appPath, 'deploy.sh'), context, true);
389
- await writeDeployScriptFromTemplate('deploy.ps1.hbs', path.join(appPath, 'deploy.ps1'), context, false);
390
- await writeDeployScriptFromTemplate('deploy.js.hbs', path.join(appPath, 'deploy.js'), context, false);
402
+ await writeDeployScriptFromTemplate('deploy.js.hbs', path.join(appPath, 'deploy.js'), context);
391
403
 
392
404
  return {
393
- deployShPath: path.join(appPath, 'deploy.sh'),
394
- deployPs1Path: path.join(appPath, 'deploy.ps1'),
395
405
  deployJsPath: path.join(appPath, 'deploy.js')
396
406
  };
397
407
  } catch (error) {
@@ -424,10 +434,11 @@ async function generateReadme(appPath, appName, systemKey, systemConfig, datasou
424
434
 
425
435
  const datasources = (Array.isArray(datasourceConfigs) ? datasourceConfigs : []).map((ds, index) => {
426
436
  const entityType = ds.entityType || ds.entityKey || ds.key?.split('-').pop() || `datasource${index + 1}`;
427
- const datasourceKey = ds.key || `${systemKey}-${entityType}`;
437
+ const keySegment = toKeySegment(entityType);
438
+ const datasourceKey = ds.key || `${systemKey}-${keySegment}`;
428
439
  const datasourceKeyOnly = datasourceKey.includes('-') && datasourceKey.startsWith(`${systemKey}-`)
429
440
  ? datasourceKey.substring(systemKey.length + 1)
430
- : entityType;
441
+ : keySegment;
431
442
  return {
432
443
  entityType,
433
444
  displayName: ds.displayName || ds.name || ds.key || `Datasource ${index + 1}`,