@aifabrix/builder 2.46.0 → 2.47.0

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 (175) hide show
  1. package/.npmrc.token +1 -0
  2. package/.temp/jest-protection-convert/run-IFN2nv/.protection/hubspot-companies.json +1 -0
  3. package/.temp/jest-protection-convert/run-IvmKLO/.protection/hubspot-companies.yaml +17 -0
  4. package/.temp/jest-protection-convert/run-SdvblF/.protection/hubspot-companies.json +1 -0
  5. package/.temp/jest-protection-convert/run-b51TsW/.protection/hubspot-companies.json +1 -0
  6. package/.temp/jest-protection-convert/run-fiLmb1/.protection/hubspot-companies.json +1 -0
  7. package/.temp/jest-protection-convert/run-qYGHMU/.protection/hubspot-companies.yaml +17 -0
  8. package/.temp/jest-protection-fixtures/hubspot-Mq5re8/hubspot-companies.yaml +17 -0
  9. package/.temp/jest-protection-fixtures/hubspot-f3u4YL/hubspot-companies.yaml +17 -0
  10. package/.temp/jest-protection-fixtures/hubspot-iQtd1O/hubspot-companies.yaml +17 -0
  11. package/.temp/jest-protection-fixtures/hubspot-mdmz5M/hubspot-companies.yaml +17 -0
  12. package/.temp/jest-protection-fixtures/hubspot-qbKYxQ/hubspot-companies.yaml +17 -0
  13. package/.temp/jest-protection-fixtures/hubspot-yzlJy6/hubspot-companies.yaml +17 -0
  14. package/.temp/validation/summary.txt +5 -0
  15. package/jest.isolated-projects.js +18 -2
  16. package/jest.projects.js +24 -0
  17. package/lib/api/dataplane-health.api.js +19 -7
  18. package/lib/api/lifecycle.api.js +22 -1
  19. package/lib/api/resource-types.api.js +107 -0
  20. package/lib/api/runtime-configuration.api.js +72 -0
  21. package/lib/api/types/resource-types.types.js +45 -0
  22. package/lib/api/user-groups.api.js +9 -9
  23. package/lib/api/users.api.js +8 -8
  24. package/lib/api/wizard.api.js +10 -2
  25. package/lib/app/down.js +58 -26
  26. package/lib/app/index.js +2 -2
  27. package/lib/app/run-resolve-image.js +2 -1
  28. package/lib/app/run-stop-containers.js +113 -0
  29. package/lib/app/run.js +1 -31
  30. package/lib/app/show-display.js +35 -0
  31. package/lib/app/show.js +32 -1
  32. package/lib/build/index.js +17 -5
  33. package/lib/build/miso-controller-npm-sdk-guard.js +25 -0
  34. package/lib/channels/add-channel.js +348 -0
  35. package/lib/channels/channel-artifact-generator.js +141 -0
  36. package/lib/channels/channel-audit.js +101 -0
  37. package/lib/channels/channel-auth-context.js +37 -0
  38. package/lib/channels/channel-credential.js +200 -0
  39. package/lib/channels/channel-display-name.js +64 -0
  40. package/lib/channels/channel-external-system.js +106 -0
  41. package/lib/channels/channel-integration-generator.js +274 -0
  42. package/lib/channels/channel-probe.js +89 -0
  43. package/lib/channels/channel-runtime-resolver.js +152 -0
  44. package/lib/channels/channel-status-display.js +141 -0
  45. package/lib/channels/channel-targets.js +115 -0
  46. package/lib/cli/index.js +16 -4
  47. package/lib/cli/setup-app.js +54 -3
  48. package/lib/cli/setup-infra-up-dataplane-action.js +2 -2
  49. package/lib/cli/setup-infra-up-platform-action.js +2 -1
  50. package/lib/cli/setup-platform.js +1 -1
  51. package/lib/cli/setup-utility-help-after.js +4 -1
  52. package/lib/cli/setup-utility-resolve.js +8 -5
  53. package/lib/commands/app-logs.js +54 -26
  54. package/lib/commands/app.js +41 -0
  55. package/lib/commands/auth-status-dataplane-version.js +97 -61
  56. package/lib/commands/auth-status.js +2 -7
  57. package/lib/commands/channel.js +58 -0
  58. package/lib/commands/datasource.js +1 -1
  59. package/lib/commands/identity-apply-sync.js +49 -8
  60. package/lib/commands/identity-group-cli.js +66 -26
  61. package/lib/commands/identity-membership-role-cache.js +58 -37
  62. package/lib/commands/identity-shared.js +22 -1
  63. package/lib/commands/identity-user-cli.js +80 -34
  64. package/lib/commands/repair-auth-apply.js +30 -4
  65. package/lib/commands/repair-auth-config.js +8 -13
  66. package/lib/commands/repair-datasource-com-v2.js +15 -0
  67. package/lib/commands/repair-datasource-service-contract.js +206 -0
  68. package/lib/commands/repair-datasource.js +53 -18
  69. package/lib/commands/repair-env-template.js +12 -12
  70. package/lib/commands/repair-openapi-sync.js +26 -4
  71. package/lib/commands/repair-steps.js +28 -13
  72. package/lib/commands/repair-system-alignment.js +7 -4
  73. package/lib/commands/resource-type.js +371 -0
  74. package/lib/commands/setup-modes.js +1 -1
  75. package/lib/commands/setup-prompts-platform-mode.js +24 -21
  76. package/lib/commands/test-trust-external.js +39 -90
  77. package/lib/commands/up-common.js +33 -1
  78. package/lib/commands/up-dataplane.js +8 -4
  79. package/lib/commands/upload.js +24 -3
  80. package/lib/commands/verify-trust-command-action.js +4 -1
  81. package/lib/commands/verify-trust-external.js +12 -20
  82. package/lib/core/config-setup-platform-mode.js +3 -3
  83. package/lib/core/setup-platform-mode.js +41 -6
  84. package/lib/datasource/capability/capability-diff-slice.js +2 -2
  85. package/lib/datasource/capability/capability-manifest.js +254 -0
  86. package/lib/datasource/capability/capability-resolve.js +3 -4
  87. package/lib/datasource/capability/copy-operations.js +5 -3
  88. package/lib/datasource/capability/remove-operations.js +2 -1
  89. package/lib/datasource/capability/run-capability-copy.js +32 -4
  90. package/lib/datasource/capability/run-capability-diff.js +3 -3
  91. package/lib/datasource/capability/run-capability-dimension.js +2 -4
  92. package/lib/datasource/capability/run-capability-edit.js +4 -7
  93. package/lib/datasource/capability/run-capability-relate.js +2 -4
  94. package/lib/datasource/capability/run-capability-remove.js +2 -4
  95. package/lib/datasource/capability/validate-capability-slice.js +2 -1
  96. package/lib/datasource/datasource-identifier.js +2 -1
  97. package/lib/datasource/datasource-validate-display.js +1 -1
  98. package/lib/datasource/field-reference-validator.js +24 -3
  99. package/lib/datasource/orphan-profiles-validator.js +98 -0
  100. package/lib/datasource/validate.js +41 -23
  101. package/lib/external-system/download-helpers.js +87 -0
  102. package/lib/external-system/download.js +61 -122
  103. package/lib/external-system/generator.js +1 -59
  104. package/lib/external-system/test.js +10 -15
  105. package/lib/generator/builders.js +11 -1
  106. package/lib/generator/external-controller-manifest.js +5 -2
  107. package/lib/generator/split.js +3 -1
  108. package/lib/generator/wizard.js +1 -28
  109. package/lib/identity/fk-reference.js +65 -0
  110. package/lib/identity/identity-apply-core.js +13 -58
  111. package/lib/identity/identity-apply-phases.js +5 -1
  112. package/lib/identity/identity-display.js +243 -0
  113. package/lib/identity/identity-response-helpers.js +52 -0
  114. package/lib/identity/identity-sync-errors.js +62 -0
  115. package/lib/identity/resolve-user-id.js +129 -0
  116. package/lib/identity/username-default.js +31 -0
  117. package/lib/lifecycle/certification-progress.js +2 -2
  118. package/lib/lifecycle/report-display-trust.js +70 -0
  119. package/lib/lifecycle/report-display.js +14 -13
  120. package/lib/resolvers/datasource-resolver.js +2 -3
  121. package/lib/resolvers/resource-type-file.js +159 -0
  122. package/lib/schema/application-schema.json +16 -0
  123. package/lib/schema/deployment-rules.yaml +2 -1
  124. package/lib/schema/external-datasource.schema.json +372 -58
  125. package/lib/schema/external-system.schema.json +331 -2
  126. package/lib/schema/type/document-storage.json +9 -5
  127. package/lib/utils/app-run-containers.js +25 -2
  128. package/lib/utils/authentication-shape.js +224 -0
  129. package/lib/utils/build-copy.js +36 -5
  130. package/lib/utils/build-resolve-image.js +66 -12
  131. package/lib/utils/celery-companion-apps.js +53 -0
  132. package/lib/utils/cli-utils.js +4 -0
  133. package/lib/utils/compose-celery-worker.js +23 -0
  134. package/lib/utils/compose-generate-docker-compose.js +9 -1
  135. package/lib/utils/configuration-env-resolver.js +36 -0
  136. package/lib/utils/credential-secrets-env-kv.js +216 -0
  137. package/lib/utils/credential-secrets-env.js +52 -262
  138. package/lib/utils/dataplane-resolver.js +4 -115
  139. package/lib/utils/declarative-url-ports.js +24 -1
  140. package/lib/utils/docker-build.js +1 -4
  141. package/lib/utils/external-env-template.js +10 -3
  142. package/lib/utils/external-system-validators.js +8 -2
  143. package/lib/utils/help-builder.js +2 -0
  144. package/lib/utils/paths.js +25 -0
  145. package/lib/utils/platform-controller-url.js +2 -1
  146. package/lib/utils/platform-kv-ref.js +57 -0
  147. package/lib/utils/runtime-configuration-download.js +189 -0
  148. package/lib/utils/runtime-configuration-values.js +119 -0
  149. package/lib/utils/schema-loader.js +19 -4
  150. package/lib/utils/worker-sidecars.js +142 -0
  151. package/lib/validation/external-manifest-validator.js +2 -0
  152. package/lib/validation/runtime-configuration-rules.js +98 -0
  153. package/lib/validation/validate-display-dimensions.js +154 -0
  154. package/lib/validation/validate-display-sections.js +276 -0
  155. package/lib/validation/validate-display-steps.js +67 -0
  156. package/lib/validation/validate-display.js +24 -402
  157. package/package.json +1 -1
  158. package/templates/applications/dataplane/application.yaml +5 -0
  159. package/templates/applications/dataplane/env.template +26 -13
  160. package/templates/applications/dataplane/rbac.yaml +108 -1
  161. package/templates/applications/miso-controller/application.yaml +2 -2
  162. package/templates/applications/miso-controller/env.template +37 -122
  163. package/templates/applications/miso-controller/rbac.yaml +28 -13
  164. package/templates/channels/chatgpt/install.template.md.hbs +49 -0
  165. package/templates/channels/chatgpt/manifest.template.json.hbs +9 -0
  166. package/templates/channels/microsoft-copilot/install.template.md.hbs +49 -0
  167. package/templates/channels/microsoft-copilot/manifest.template.json.hbs +8 -0
  168. package/templates/channels/slack/install.template.md.hbs +49 -0
  169. package/templates/channels/slack/manifest.template.json.hbs +66 -0
  170. package/templates/channels/teams-bot/install.template.md.hbs +49 -0
  171. package/templates/channels/teams-bot/manifest.template.json.hbs +13 -0
  172. package/templates/channels/web-embed/install.template.md.hbs +49 -0
  173. package/templates/channels/web-embed/manifest.template.json.hbs +8 -0
  174. package/templates/python/docker-compose.hbs +56 -0
  175. package/templates/typescript/docker-compose.hbs +52 -0
@@ -1,8 +1,5 @@
1
1
  const {
2
2
  formatSuccessLine,
3
- formatSuccessParagraph,
4
- sectionTitle,
5
- headerKeyValue,
6
3
  metadata,
7
4
  formatProgress,
8
5
  formatWarningLine
@@ -36,83 +33,18 @@ const { getExternalSystemConfig } = require('../api/external-systems.api');
36
33
  const { getDeploymentAuth, requireBearerForDataplanePipeline } = require('../utils/token-manager');
37
34
  const { getConfig } = require('../core/config');
38
35
  const { getIntegrationPath } = require('../utils/paths');
39
- const { retemplateConfigurationForDownload } = require('../utils/configuration-env-resolver');
36
+ const { retemplateConfigurationForDownload, retemplateAllVariableDefinitions } = require('../utils/configuration-env-resolver');
37
+ const { syncRuntimeConfigurationFromDataplane } = require('../utils/runtime-configuration-download');
40
38
  const logger = require('../utils/logger');
41
39
  const { resolveControllerUrl } = require('../utils/controller-url');
42
40
  const generator = require('../generator');
43
-
44
- /**
45
- * Validates system type from downloaded application
46
- * @param {Object} application - External system configuration
47
- * @returns {string} System type (openapi, mcp, custom)
48
- * @throws {Error} If system type is invalid
49
- */
50
- function validateSystemType(application) {
51
- if (!application || typeof application !== 'object') {
52
- throw new Error('Application configuration is required');
53
- }
54
-
55
- const validTypes = ['openapi', 'mcp', 'custom'];
56
- const systemType = application.type;
57
-
58
- if (!systemType || !validTypes.includes(systemType)) {
59
- throw new Error(`Invalid system type: ${systemType}. Must be one of: ${validTypes.join(', ')}`);
60
- }
61
-
62
- return systemType;
63
- }
64
-
65
- /**
66
- * Validates downloaded data structure before writing files
67
- * @param {Object} application - External system configuration
68
- * @param {Array} dataSources - Array of datasource configurations
69
- * @throws {Error} If validation fails
70
- */
71
- /**
72
- * Validates application configuration
73
- * @function validateApplicationConfig
74
- * @param {Object} application - Application configuration
75
- * @throws {Error} If validation fails
76
- */
77
- function validateApplicationConfig(application) {
78
- if (!application || typeof application !== 'object') {
79
- throw new Error('Application configuration is required');
80
- }
81
- if (!application.key || typeof application.key !== 'string') {
82
- throw new Error('Application key is required');
83
- }
84
- }
85
-
86
- /**
87
- * Validates datasource configuration
88
- * @function validateDatasourceConfig
89
- * @param {Object} datasource - Datasource configuration
90
- * @param {string} applicationKey - Application key
91
- * @throws {Error} If validation fails
92
- */
93
- function validateDatasourceConfig(datasource, applicationKey) {
94
- if (!datasource.key || typeof datasource.key !== 'string') {
95
- throw new Error('Datasource key is required for all datasources');
96
- }
97
- if (!datasource.systemKey || typeof datasource.systemKey !== 'string') {
98
- throw new Error('Datasource systemKey is required for all datasources');
99
- }
100
- if (datasource.systemKey !== applicationKey) {
101
- throw new Error(`Datasource systemKey (${datasource.systemKey}) does not match application key (${applicationKey})`);
102
- }
103
- }
104
-
105
- function validateDownloadedData(application, dataSources) {
106
- validateApplicationConfig(application);
107
-
108
- if (!Array.isArray(dataSources)) {
109
- throw new Error('DataSources must be an array');
110
- }
111
-
112
- for (const datasource of dataSources) {
113
- validateDatasourceConfig(datasource, application.key);
114
- }
115
- }
41
+ const {
42
+ validateSystemType,
43
+ validateDownloadedData,
44
+ logDownloadCommandHeader,
45
+ displayDownloadSuccess,
46
+ runConvertToJsonIfRequested
47
+ } = require('./download-helpers');
116
48
 
117
49
  /**
118
50
  * Setup authentication and get dataplane URL
@@ -354,10 +286,9 @@ async function applyRetemplateToSystemFile(systemKey, systemFilePath) {
354
286
  const systemContent = await fs.readFile(systemFilePath, 'utf8');
355
287
  const systemObj = yaml.load(systemContent);
356
288
  if (!Array.isArray(systemObj?.configuration)) return;
357
- const applied = await retemplateConfigurationForDownload(systemKey, systemObj.configuration);
358
- if (applied) {
359
- await fs.writeFile(systemFilePath, yaml.dump(systemObj, { indent: 2, lineWidth: -1 }), 'utf8');
360
- }
289
+ retemplateAllVariableDefinitions(systemObj.configuration);
290
+ await retemplateConfigurationForDownload(systemKey, systemObj.configuration);
291
+ await fs.writeFile(systemFilePath, yaml.dump(systemObj, { indent: 2, lineWidth: -1 }), 'utf8');
361
292
  }
362
293
 
363
294
  /**
@@ -397,43 +328,54 @@ async function processDownloadedSystem(systemKey, manifest, splitOptions = {}) {
397
328
  }
398
329
 
399
330
  /**
400
- * Display download success message
401
- * @param {string} systemKey - System key
402
- * @param {string} finalPath - Final destination path
403
- * @param {number} datasourceCount - Number of datasources
404
- */
405
- function displayDownloadSuccess(systemKey, finalPath, datasourceCount) {
406
- logger.log(
407
- formatSuccessParagraph(
408
- `Downloaded ${systemKey} (${datasourceCount} datasource${datasourceCount === 1 ? '' : 's'})`
409
- )
410
- );
411
- logger.log(headerKeyValue('Location:', finalPath));
412
- }
413
-
414
- /**
415
- * After YAML split, convert integration files to JSON when --format json.
416
- * @async
417
- * @param {string} systemKey
331
+ * Post-split download steps: governance packs, optional JSON convert, runtime config sync.
332
+ * @param {Object} params
333
+ * @param {string} params.systemKey
334
+ * @param {Object} params.manifest
335
+ * @param {string} params.finalPath
336
+ * @param {string} params.dataplaneUrl
337
+ * @param {Object} params.authConfig
338
+ * @param {string} params.format
418
339
  * @returns {Promise<void>}
419
340
  */
420
- async function runConvertToJsonIfRequested(systemKey) {
421
- const { runConvert } = require('../commands/convert');
341
+ async function finalizeDownloadArtifacts({
342
+ systemKey,
343
+ manifest,
344
+ finalPath,
345
+ dataplaneUrl,
346
+ authConfig,
347
+ format
348
+ }) {
349
+ const { downloadGovernanceScenarioPacksFromManifest } = require('../lifecycle/scenario-upload');
350
+ await downloadGovernanceScenarioPacksFromManifest(
351
+ systemKey,
352
+ manifest,
353
+ dataplaneUrl,
354
+ authConfig
355
+ );
356
+ if (format === 'json') {
357
+ await runConvertToJsonIfRequested(systemKey);
358
+ }
422
359
  try {
423
- await runConvert(systemKey, { format: 'json', force: true });
424
- logger.log(formatSuccessLine('Converted component files to JSON'));
425
- } catch (convertErr) {
426
- throw new Error(`Download succeeded but convert to JSON failed: ${convertErr.message}`);
360
+ const configSync = await syncRuntimeConfigurationFromDataplane({
361
+ dataplaneUrl,
362
+ authConfig,
363
+ systemKey,
364
+ integrationPath: finalPath,
365
+ dataSources: manifest.dataSources
366
+ });
367
+ if (configSync.merged > 0) {
368
+ const nameList = configSync.names.length ? ` (${configSync.names.join(', ')})` : '';
369
+ logger.log(
370
+ formatSuccessLine(
371
+ `Merged ${configSync.merged} runtime configuration variable(s) into env.template${nameList}.`
372
+ )
373
+ );
374
+ }
375
+ } catch (syncErr) {
376
+ logger.log(formatWarningLine(`Runtime configuration sync skipped: ${syncErr.message}`));
427
377
  }
428
- }
429
-
430
- /**
431
- * @param {string} systemKey
432
- */
433
- function logDownloadCommandHeader(systemKey) {
434
- logger.log('');
435
- logger.log(sectionTitle('Download'));
436
- logger.log(headerKeyValue('System:', systemKey));
378
+ displayDownloadSuccess(systemKey, finalPath, manifest.dataSources.length);
437
379
  }
438
380
 
439
381
  /**
@@ -468,17 +410,14 @@ async function downloadExternalSystem(systemKey, options = {}) {
468
410
  manifest,
469
411
  await resolveDownloadSplitOptions(finalPath, options)
470
412
  );
471
- const { downloadGovernanceScenarioPacksFromManifest } = require('../lifecycle/scenario-upload');
472
- await downloadGovernanceScenarioPacksFromManifest(
413
+ await finalizeDownloadArtifacts({
473
414
  systemKey,
474
415
  manifest,
416
+ finalPath,
475
417
  dataplaneUrl,
476
- authConfig
477
- );
478
- if (format === 'json') {
479
- await runConvertToJsonIfRequested(systemKey);
480
- }
481
- displayDownloadSuccess(systemKey, finalPath, manifest.dataSources.length);
418
+ authConfig,
419
+ format
420
+ });
482
421
  } catch (error) {
483
422
  throw new Error(`Failed to download external system: ${error.message}`);
484
423
  }
@@ -16,70 +16,12 @@ const handlebars = require('handlebars');
16
16
  const logger = require('../utils/logger');
17
17
  const { resolveApplicationConfigPath } = require('../utils/app-config-resolver');
18
18
  const { loadConfigFile, writeConfigFile } = require('../utils/config-format');
19
- const { getKvPathSegmentForSecurityKey } = require('../utils/credential-secrets-env');
19
+ const { buildAuthenticationFromMethod } = require('../utils/authentication-shape');
20
20
 
21
21
  // Register Handlebars helper for equality check
22
22
  handlebars.registerHelper('eq', (a, b) => a === b);
23
23
  handlebars.registerHelper('json', (obj) => JSON.stringify(obj));
24
24
 
25
- /**
26
- * Build authentication object per schema authenticationVariablesByMethod.
27
- * Security values use canonical kv://<systemKey>/<segment> paths (segment from getKvPathSegmentForSecurityKey).
28
- * @param {string} systemKey - External system key
29
- * @param {string} authType - Auth method (oauth2, aad, apikey, bearerToken, basic, queryParam, oidc, hmac, none)
30
- * @returns {{ method: string, variables: Object, security: Object }} Authentication object
31
- */
32
- function buildAuthenticationFromMethod(systemKey, authType) {
33
- const kvPath = (securityKey) => {
34
- const segment = getKvPathSegmentForSecurityKey(securityKey);
35
- return segment ? `kv://${systemKey}/${segment}` : null;
36
- };
37
- const method = authType || 'apikey';
38
- const base = 'https://api.example.com';
39
-
40
- const authMap = {
41
- oauth2: {
42
- variables: { baseUrl: base, tokenUrl: `${base}/oauth/token`, authorizationUrl: `${base}/oauth/authorize` },
43
- security: { clientId: kvPath('clientId'), clientSecret: kvPath('clientSecret') }
44
- },
45
- aad: {
46
- variables: { baseUrl: base, tokenUrl: 'https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token', tenantId: '{tenant-id}' },
47
- security: { clientId: kvPath('clientId'), clientSecret: kvPath('clientSecret') }
48
- },
49
- apikey: {
50
- variables: { baseUrl: base, headerName: 'X-API-Key' },
51
- security: { apiKey: kvPath('apiKey') }
52
- },
53
- bearerToken: {
54
- variables: { baseUrl: base, headerName: 'Authorization', prefix: 'Bearer' },
55
- security: { token: kvPath('token') }
56
- },
57
- basic: {
58
- variables: { baseUrl: base },
59
- security: { username: kvPath('username'), password: kvPath('password') }
60
- },
61
- queryParam: {
62
- variables: { baseUrl: base, paramName: 'api_key' },
63
- security: { paramValue: kvPath('paramValue') }
64
- },
65
- oidc: {
66
- variables: { openIdConfigUrl: 'https://example.com/.well-known/openid-configuration', clientId: 'app-id' },
67
- security: {}
68
- },
69
- hmac: {
70
- variables: { baseUrl: base, algorithm: 'sha256', signatureHeader: 'X-Signature' },
71
- security: { signingSecret: kvPath('signingSecret') }
72
- },
73
- none: {
74
- variables: {},
75
- security: {}
76
- }
77
- };
78
-
79
- const auth = authMap[method] || authMap.apikey;
80
- return { method, variables: auth.variables, security: auth.security };
81
- }
82
-
83
25
  /** Target extension for format */
84
26
  const FORMAT_EXT = { yaml: '.yaml', json: '.json' };
85
27
 
@@ -7,7 +7,6 @@
7
7
  */
8
8
  /* eslint-disable max-lines,max-lines-per-function,max-statements,complexity,max-depth -- Integration test flow with system-level and per-datasource paths */
9
9
 
10
- const fs = require('fs').promises;
11
10
  const fsSync = require('fs');
12
11
  const path = require('path');
13
12
  const chalk = require('chalk');
@@ -69,15 +68,15 @@ async function loadVariablesYamlFile(variablesPath) {
69
68
  }
70
69
 
71
70
  /**
72
- * Loads a single JSON file
71
+ * Loads a single integration config file (JSON, YAML, or YML).
73
72
  * @async
74
- * @function loadJsonFile
75
- * @param {string} filePath - Path to JSON file
73
+ * @function loadIntegrationConfigFile
74
+ * @param {string} filePath - Path to config file
76
75
  * @param {string} fileName - File name for error messages
77
- * @returns {Promise<Object>} Parsed JSON data
78
- * @throws {Error} If file not found or invalid JSON
76
+ * @returns {Promise<Object>} Parsed config object
77
+ * @throws {Error} If file not found or invalid format
79
78
  */
80
- async function loadJsonFile(filePath, fileName) {
79
+ async function loadIntegrationConfigFile(filePath, fileName) {
81
80
  if (!fsSync.existsSync(filePath)) {
82
81
  // Use "System file not found" for system files to match test expectations
83
82
  if (fileName.includes('system') || fileName.includes('deploy')) {
@@ -86,12 +85,8 @@ async function loadJsonFile(filePath, fileName) {
86
85
  throw new Error(`${fileName} not found: ${filePath}`);
87
86
  }
88
87
 
89
- const content = await fs.readFile(filePath, 'utf8');
90
- try {
91
- return JSON.parse(content);
92
- } catch (error) {
93
- throw new Error(`Invalid JSON syntax in ${fileName}: ${error.message}`);
94
- }
88
+ const { loadConfigFile } = require('../utils/config-format');
89
+ return loadConfigFile(filePath);
95
90
  }
96
91
 
97
92
  /**
@@ -121,7 +116,7 @@ async function loadSystemFiles(systemFiles, schemaBasePath, appPath) {
121
116
  const systemJsonFiles = [];
122
117
  for (const systemFile of systemFiles) {
123
118
  const systemPath = resolveFilePath(schemaBasePath, appPath, systemFile);
124
- const systemJson = await loadJsonFile(systemPath, systemFile);
119
+ const systemJson = await loadIntegrationConfigFile(systemPath, systemFile);
125
120
  systemJsonFiles.push({ path: systemPath, data: systemJson });
126
121
  }
127
122
  return systemJsonFiles;
@@ -140,7 +135,7 @@ async function loadDatasourceFiles(datasourceFiles, schemaBasePath, appPath) {
140
135
  const datasourceJsonFiles = [];
141
136
  for (const datasourceFile of datasourceFiles) {
142
137
  const datasourcePath = resolveFilePath(schemaBasePath, appPath, datasourceFile);
143
- const datasourceJson = await loadJsonFile(datasourcePath, datasourceFile);
138
+ const datasourceJson = await loadIntegrationConfigFile(datasourcePath, datasourceFile);
144
139
  datasourceJsonFiles.push({ path: datasourcePath, data: datasourceJson });
145
140
  }
146
141
  return datasourceJsonFiles;
@@ -267,6 +267,15 @@ function validateBuildFields(build) {
267
267
  if (build.dockerfile && build.dockerfile.trim()) {
268
268
  buildConfig.dockerfile = build.dockerfile;
269
269
  }
270
+ if (build.worker === true) {
271
+ buildConfig.worker = true;
272
+ }
273
+ if (typeof build.imageRunWorker === 'string' && build.imageRunWorker.trim()) {
274
+ buildConfig.imageRunWorker = build.imageRunWorker.trim();
275
+ }
276
+ if (typeof build.imageRunBeat === 'string' && build.imageRunBeat.trim()) {
277
+ buildConfig.imageRunBeat = build.imageRunBeat.trim();
278
+ }
270
279
 
271
280
  return Object.keys(buildConfig).length > 0 ? buildConfig : null;
272
281
  }
@@ -390,6 +399,7 @@ module.exports = {
390
399
  buildOptionalFields,
391
400
  buildManifestStructure,
392
401
  filterConfigurationByRegistryMode,
393
- sanitizeAuthType
402
+ sanitizeAuthType,
403
+ validateBuildFields
394
404
  };
395
405
 
@@ -27,11 +27,14 @@ const { loadVariables, loadRbac } = require('./helpers');
27
27
  * @param {Object} systemJson - System JSON object (mutated in place)
28
28
  */
29
29
  function normalizeLegacyAuthMethod(systemJson) {
30
+ const { getAuthCredentialTemplate } = require('../utils/authentication-shape');
30
31
  const auth = systemJson && systemJson.authentication;
31
32
  if (!auth || typeof auth !== 'object') return;
32
- const method = String(auth.method || '').trim().toLowerCase();
33
+ const credential = getAuthCredentialTemplate(auth);
34
+ if (!credential) return;
35
+ const method = String(credential.method || '').trim().toLowerCase();
33
36
  if (method === 'bearerkey') {
34
- auth.method = 'bearerToken';
37
+ credential.method = 'bearerToken';
35
38
  }
36
39
  }
37
40
 
@@ -453,6 +453,8 @@ module.exports = {
453
453
  extractVariablesYaml,
454
454
  extractRbacYaml,
455
455
  parseImageReference,
456
- generateReadmeFromDeployJson
456
+ generateReadmeFromDeployJson,
457
+ mergeEnvTemplateWithExisting,
458
+ buildEnvTemplateExpectedByKey
457
459
  };
458
460
 
@@ -32,34 +32,7 @@ function toKeySegment(str) {
32
32
  return sanitized || 'default';
33
33
  }
34
34
 
35
- /**
36
- * Align authentication.security kv:// namespaces and credentialKey with the final system key.
37
- * Dataplane normalizes this before respond; when appName overrides a spec-derived key (e.g.
38
- * OpenAPI title "Companies"), the builder still must rewrite nested auth so it matches env.template.
39
- *
40
- * @param {Object|null|undefined} authentication - authentication block from dataplane
41
- * @param {string} systemKey - Final external system key (integration app name)
42
- * @param {string} [authDisplayName] - Credential display name (typically title-cased app name)
43
- */
44
- function normalizeAuthenticationToSystemKey(authentication, systemKey, authDisplayName) {
45
- if (!authentication || typeof authentication !== 'object') return;
46
- authentication.credentialKey = `${systemKey}-cred`;
47
- const security = authentication.security;
48
- if (security && typeof security === 'object') {
49
- for (const k of Object.keys(security)) {
50
- const v = security[k];
51
- if (typeof v === 'string' && v.startsWith('kv://')) {
52
- const rest = v.slice(5);
53
- const idx = rest.indexOf('/');
54
- const suffix = idx >= 0 ? rest.slice(idx + 1) : '';
55
- security[k] = suffix ? `kv://${systemKey}/${suffix}` : `kv://${systemKey}`;
56
- }
57
- }
58
- }
59
- if (authDisplayName) {
60
- authentication.displayName = authDisplayName;
61
- }
62
- }
35
+ const { normalizeAuthenticationToSystemKey } = require('../utils/authentication-shape');
63
36
 
64
37
  /**
65
38
  * Generate files from dataplane-generated wizard configurations
@@ -0,0 +1,65 @@
1
+ /**
2
+ * @fileoverview Parse ForeignKeyReference objects from controller identity APIs (plan 194)
3
+ * @author AI Fabrix Team
4
+ * @version 1.0.0
5
+ */
6
+
7
+ 'use strict';
8
+
9
+ /**
10
+ * @param {string|Object|null|undefined} ref
11
+ * @returns {string}
12
+ */
13
+ function readFkId(ref) {
14
+ if (typeof ref === 'string') {
15
+ return ref;
16
+ }
17
+ return String(ref?.id || '').trim();
18
+ }
19
+
20
+ /**
21
+ * @param {string|Object|null|undefined} ref
22
+ * @returns {string}
23
+ */
24
+ function readFkKey(ref) {
25
+ if (typeof ref === 'string') {
26
+ return ref;
27
+ }
28
+ return String(ref?.key || '').trim();
29
+ }
30
+
31
+ /**
32
+ * @param {string|Object|null|undefined} ref
33
+ * @returns {string}
34
+ */
35
+ function readFkName(ref) {
36
+ if (typeof ref === 'string') {
37
+ return '';
38
+ }
39
+ return String(ref?.name || '').trim();
40
+ }
41
+
42
+ /**
43
+ * @param {string|Object|null|undefined} ref
44
+ * @param {string} [fallback]
45
+ * @returns {string}
46
+ */
47
+ function formatFkLabel(ref, fallback = '—') {
48
+ const name = readFkName(ref);
49
+ if (name) {
50
+ return name;
51
+ }
52
+ const key = readFkKey(ref);
53
+ if (key) {
54
+ return key;
55
+ }
56
+ const id = readFkId(ref);
57
+ return id || fallback;
58
+ }
59
+
60
+ module.exports = {
61
+ readFkId,
62
+ readFkKey,
63
+ readFkName,
64
+ formatFkLabel
65
+ };
@@ -6,46 +6,13 @@
6
6
 
7
7
  'use strict';
8
8
 
9
- const { getUser, listUsers } = require('../api/users.api');
10
-
11
- /**
12
- * @param {Object} response
13
- * @returns {any}
14
- */
15
- function unwrapControllerData(response) {
16
- if (!response || response.success === false) {
17
- return null;
18
- }
19
- return response?.data?.data ?? response?.data ?? response;
20
- }
21
-
22
- /**
23
- * @param {Object} response
24
- * @returns {string}
25
- */
26
- function apiErrorMessage(response) {
27
- if (!response) {
28
- return 'Request failed';
29
- }
30
- const err = response.error;
31
- if (typeof err === 'string') {
32
- return err;
33
- }
34
- if (err && typeof err === 'object') {
35
- return err.formattedError || err.message || err.error || 'Request failed';
36
- }
37
- return response.formattedError || response.message || 'Request failed';
38
- }
39
-
40
- /**
41
- * @param {Object} response
42
- * @throws {Error}
43
- */
44
- function throwIfApiFailed(response) {
45
- if (!response || response.success === false) {
46
- throw new Error(apiErrorMessage(response));
47
- }
48
- }
9
+ const { lookupUserByIdOrEmail } = require('./resolve-user-id');
10
+ const { buildSyncStatsFailureMessage } = require('./identity-sync-errors');
11
+ const {
12
+ unwrapControllerData,
13
+ apiErrorMessage,
14
+ throwIfApiFailed
15
+ } = require('./identity-response-helpers');
49
16
 
50
17
  /**
51
18
  * @param {Object|null|undefined} stats
@@ -55,11 +22,7 @@ function throwIfApiFailed(response) {
55
22
  function assertSyncStatsOk(stats, opts = {}) {
56
23
  const syncErrors = Number(stats?.errors ?? 0);
57
24
  if (syncErrors > 0) {
58
- throw new Error(
59
- `Dataplane full sync reported ${syncErrors} error(s). ` +
60
- `usersProcessed=${stats?.usersProcessed ?? 0} groupsProcessed=${stats?.groupsProcessed ?? 0}. ` +
61
- 'Check miso-controller logs for the sync request.'
62
- );
25
+ throw new Error(buildSyncStatsFailureMessage(stats));
63
26
  }
64
27
  const processed = Number(stats?.usersProcessed ?? 0);
65
28
  if (processed === 0 && !opts.allowEmptySync) {
@@ -79,24 +42,16 @@ function assertSyncStatsOk(stats, opts = {}) {
79
42
  async function findExistingUser(controllerUrl, authConfig, userSpec) {
80
43
  const csvId = String(userSpec.csvId || '').trim();
81
44
  if (csvId) {
82
- const byId = await getUser(controllerUrl, authConfig, csvId);
83
- const row = unwrapControllerData(byId);
84
- if (row && row.id) {
85
- return row;
45
+ const byId = await lookupUserByIdOrEmail(controllerUrl, authConfig, csvId);
46
+ if (byId?.id) {
47
+ return byId;
86
48
  }
87
49
  }
88
50
  const email = String(userSpec.email || '').trim();
89
- const listed = await listUsers(controllerUrl, authConfig, {
90
- search: email,
91
- pageSize: 10,
92
- page: 1
93
- });
94
- const items = unwrapControllerData(listed);
95
- const list = Array.isArray(items) ? items : items?.data;
96
- if (!Array.isArray(list)) {
51
+ if (!email) {
97
52
  return null;
98
53
  }
99
- return list.find((u) => String(u.email || '').toLowerCase() === email.toLowerCase()) || null;
54
+ return lookupUserByIdOrEmail(controllerUrl, authConfig, email);
100
55
  }
101
56
 
102
57
  module.exports = {
@@ -18,6 +18,7 @@ const {
18
18
  apiErrorMessage,
19
19
  findExistingUser
20
20
  } = require('./identity-apply-core');
21
+ const { resolveIdentityUsername } = require('./username-default');
21
22
 
22
23
  /**
23
24
  * @param {string} msg
@@ -75,7 +76,10 @@ async function ensureUser(controllerUrl, authConfig, userSpec, dryRun) {
75
76
  firstName: userSpec.firstName,
76
77
  lastName: userSpec.lastName,
77
78
  displayName: userSpec.displayName,
78
- username: userSpec.username,
79
+ username: resolveIdentityUsername({
80
+ username: userSpec.username,
81
+ email: userSpec.email
82
+ }),
79
83
  status: 'active'
80
84
  };
81
85
  Object.keys(body).forEach((k) => {