@contrail/cli 3.5.4 → 3.5.5-alpha.177136f

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 (30) hide show
  1. package/README.md +50 -1
  2. package/dist/api/feature-flags.d.ts +3 -0
  3. package/dist/api/feature-flags.js +29 -0
  4. package/dist/api/users.d.ts +1 -0
  5. package/dist/api/users.js +10 -1
  6. package/dist/commands/feature-flags/export.d.ts +19 -0
  7. package/dist/commands/feature-flags/export.js +66 -0
  8. package/dist/commands/feature-flags/export.spec.d.ts +1 -0
  9. package/dist/commands/feature-flags/export.spec.js +109 -0
  10. package/dist/commands/feature-flags/import.d.ts +42 -0
  11. package/dist/commands/feature-flags/import.js +191 -0
  12. package/dist/commands/feature-flags/import.spec.d.ts +1 -0
  13. package/dist/commands/feature-flags/import.spec.js +194 -0
  14. package/dist/commands/instance/export.d.ts +9 -0
  15. package/dist/commands/instance/export.js +18 -3
  16. package/dist/commands/instance/export.spec.d.ts +1 -0
  17. package/dist/commands/instance/export.spec.js +32 -0
  18. package/dist/commands/instance/import.d.ts +3 -0
  19. package/dist/commands/instance/import.js +5 -0
  20. package/dist/commands/instance/import.spec.js +4 -0
  21. package/dist/helpers/app/app-config-validators.d.ts +5 -0
  22. package/dist/helpers/app/app-config-validators.js +102 -3
  23. package/dist/helpers/app/app-config-validators.spec.js +46 -0
  24. package/dist/helpers/app/extensions-deployer.d.ts +10 -2
  25. package/dist/helpers/app/extensions-deployer.js +31 -37
  26. package/dist/helpers/app/extensions-deployer.spec.d.ts +1 -0
  27. package/dist/helpers/app/extensions-deployer.spec.js +29 -0
  28. package/dist/interfaces.d.ts +36 -0
  29. package/oclif.manifest.json +111 -1
  30. package/package.json +4 -1
package/README.md CHANGED
@@ -17,7 +17,7 @@ $ npm install -g @contrail/cli
17
17
  $ contrail COMMAND
18
18
  running command...
19
19
  $ contrail (--version)
20
- @contrail/cli/3.5.4 linux-x64 node-v24.20.0
20
+ @contrail/cli/3.5.5-alpha.177136f linux-x64 node-v24.21.0
21
21
  $ contrail --help [COMMAND]
22
22
  USAGE
23
23
  $ contrail COMMAND
@@ -51,6 +51,8 @@ To get instructions on how to set up autocomplete for your shell, run `contrail
51
51
  * [`contrail config list`](#contrail-config-list)
52
52
  * [`contrail config set`](#contrail-config-set)
53
53
  * [`contrail config use [NAME]`](#contrail-config-use-name)
54
+ * [`contrail feature-flags export`](#contrail-feature-flags-export)
55
+ * [`contrail feature-flags import`](#contrail-feature-flags-import)
54
56
  * [`contrail file upload FILELOCATION CONTENTTYPE`](#contrail-file-upload-filelocation-contenttype)
55
57
  * [`contrail groups export`](#contrail-groups-export)
56
58
  * [`contrail groups import GROUPSFILE`](#contrail-groups-import-groupsfile)
@@ -537,6 +539,53 @@ EXAMPLES
537
539
  $ contrail config use demo-org
538
540
  ```
539
541
 
542
+ ## `contrail feature-flags export`
543
+
544
+ Export the enabled feature flags for your Org
545
+
546
+ ```
547
+ USAGE
548
+ $ contrail feature-flags export [-l error|warn|info|debug] [-e true|false] [-d <value>] [-f]
549
+
550
+ FLAGS
551
+ -d, --outDir=<value> [default: .] The directory to which to export the feature flags. Defaults to the
552
+ current directory
553
+ -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
554
+ <options: true|false>
555
+ -f, --overwrite Replaces any existing export files in outDir
556
+ -l, --logLevel=<option> The Log Level
557
+ <options: error|warn|info|debug>
558
+
559
+ DESCRIPTION
560
+ Export the enabled feature flags for your Org
561
+
562
+ EXAMPLES
563
+ $ contrail feature-flags export
564
+ ```
565
+
566
+ ## `contrail feature-flags import`
567
+
568
+ Upload an extracted set of feature flags
569
+
570
+ ```
571
+ USAGE
572
+ $ contrail feature-flags import [-l error|warn|info|debug] [-e true|false] [-d <value>]
573
+
574
+ FLAGS
575
+ -d, --dir=<value> [default: .] The directory from which to import the feature flags. Defaults to the
576
+ current directory. The feature flags will be loaded from $dir/feature-flags.yml
577
+ -e, --alwaysConfirmEnv=<option> [default: true] The Environment variables
578
+ <options: true|false>
579
+ -l, --logLevel=<option> The Log Level
580
+ <options: error|warn|info|debug>
581
+
582
+ DESCRIPTION
583
+ Upload an extracted set of feature flags
584
+
585
+ EXAMPLES
586
+ $ contrail feature-flags import
587
+ ```
588
+
540
589
  ## `contrail file upload FILELOCATION CONTENTTYPE`
541
590
 
542
591
  Uploads a file to the VibeIQ platform
@@ -0,0 +1,3 @@
1
+ export declare function getFeatureFlags(options?: any): Promise<any[]>;
2
+ export declare function createFeatureFlag(featureName: string): Promise<any>;
3
+ export declare function deleteFeatureFlag(id: string): Promise<any>;
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deleteFeatureFlag = exports.createFeatureFlag = exports.getFeatureFlags = void 0;
4
+ const sdk_1 = require("@contrail/sdk");
5
+ // a feature flag record exists only for features that are turned ON for the org,
6
+ // and carries no configuration beyond its featureName
7
+ async function getFeatureFlags(options) {
8
+ return new sdk_1.Entities().get({
9
+ entityName: 'feature-flag',
10
+ ...options,
11
+ });
12
+ }
13
+ exports.getFeatureFlags = getFeatureFlags;
14
+ // the API treats create as an upsert on featureName, so creating an already
15
+ // enabled flag returns the existing record instead of failing
16
+ async function createFeatureFlag(featureName) {
17
+ return new sdk_1.Entities().create({
18
+ entityName: 'feature-flag',
19
+ object: { featureName },
20
+ });
21
+ }
22
+ exports.createFeatureFlag = createFeatureFlag;
23
+ async function deleteFeatureFlag(id) {
24
+ return new sdk_1.Entities().delete({
25
+ entityName: 'feature-flag',
26
+ id,
27
+ });
28
+ }
29
+ exports.deleteFeatureFlag = deleteFeatureFlag;
@@ -1,2 +1,3 @@
1
1
  export declare function getUserOrgs(options?: any): Promise<any[]>;
2
2
  export declare function getGroups(options?: any): Promise<any[]>;
3
+ export declare function getCurrentUserWithPlatformRoles(): Promise<any>;
package/dist/api/users.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getGroups = exports.getUserOrgs = void 0;
3
+ exports.getCurrentUserWithPlatformRoles = exports.getGroups = exports.getUserOrgs = void 0;
4
4
  const sdk_1 = require("@contrail/sdk");
5
5
  async function getUserOrgs(options) {
6
6
  return new sdk_1.Entities().get({
@@ -16,3 +16,12 @@ async function getGroups(options) {
16
16
  });
17
17
  }
18
18
  exports.getGroups = getGroups;
19
+ // GET /users/current only populates platformRoles when it is asked for as a relation
20
+ async function getCurrentUserWithPlatformRoles() {
21
+ return new sdk_1.Entities().get({
22
+ entityName: 'user',
23
+ id: 'current',
24
+ relations: ['platformRoles'],
25
+ });
26
+ }
27
+ exports.getCurrentUserWithPlatformRoles = getCurrentUserWithPlatformRoles;
@@ -0,0 +1,19 @@
1
+ import { BaseCommand } from '../../basecommand';
2
+ export declare const FEATURE_FLAGS_FILE = "feature-flags.yml";
3
+ export default class ExportFeatureFlags extends BaseCommand {
4
+ static description: string;
5
+ static examples: string[];
6
+ static flags: {
7
+ outDir: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
8
+ overwrite: import("@oclif/core/lib/interfaces").BooleanFlag<boolean>;
9
+ alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
10
+ logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
11
+ };
12
+ run(): Promise<void>;
13
+ }
14
+ /**
15
+ * Writes the org's enabled feature flags to $outDir/feature-flags.yml as a list of
16
+ * `- featureName: X` entries. An org with no flags enabled still gets a file (an empty
17
+ * list), so the export stays a faithful snapshot of what is turned on.
18
+ */
19
+ export declare function exportFeatureFlags(outDir: string, overwrite: boolean): Promise<void>;
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.exportFeatureFlags = exports.FEATURE_FLAGS_FILE = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const path = tslib_1.__importStar(require("path"));
6
+ const chalk_1 = tslib_1.__importDefault(require("chalk"));
7
+ const fs_1 = tslib_1.__importDefault(require("fs"));
8
+ const login_1 = require("../../auth/login");
9
+ const core_1 = require("@oclif/core");
10
+ const file_helpers_1 = require("../../helpers/file-helpers");
11
+ const error_helpers_1 = require("../../helpers/error-helpers");
12
+ const feature_flags_1 = require("../../api/feature-flags");
13
+ const basecommand_1 = require("../../basecommand");
14
+ exports.FEATURE_FLAGS_FILE = 'feature-flags.yml';
15
+ class ExportFeatureFlags extends basecommand_1.BaseCommand {
16
+ static description = 'Export the enabled feature flags for your Org';
17
+ static examples = [
18
+ `$ contrail feature-flags export
19
+ `,
20
+ ];
21
+ static flags = {
22
+ ...basecommand_1.BaseCommand.baseFlags,
23
+ outDir: core_1.Flags.string({
24
+ char: 'd',
25
+ description: 'The directory to which to export the feature flags. Defaults to the current directory',
26
+ required: false,
27
+ default: '.',
28
+ }),
29
+ overwrite: core_1.Flags.boolean({
30
+ char: 'f',
31
+ description: 'Replaces any existing export files in outDir',
32
+ required: false,
33
+ default: false,
34
+ }),
35
+ };
36
+ async run() {
37
+ try {
38
+ await (0, login_1.authUser)();
39
+ this.log(`${chalk_1.default.blue.bold('START')} Getting Feature Flags.`);
40
+ this.log(`${chalk_1.default.yellow.bold('FEATURE FLAGS')} Exporting`);
41
+ await exportFeatureFlags(this.flags.outDir, this.flags.overwrite);
42
+ this.log(`${chalk_1.default.yellow.bold('FEATURE FLAGS')} Exported`);
43
+ }
44
+ catch (e) {
45
+ this.log(`${chalk_1.default.red.bold('FAIL')} Feature Flags Export Failed. ${(0, error_helpers_1.describeError)(e)}`);
46
+ process.exitCode = 1;
47
+ return;
48
+ }
49
+ this.log(`${chalk_1.default.green.bold('COMPLETE')} Feature Flags Export Complete.`);
50
+ }
51
+ }
52
+ exports.default = ExportFeatureFlags;
53
+ /**
54
+ * Writes the org's enabled feature flags to $outDir/feature-flags.yml as a list of
55
+ * `- featureName: X` entries. An org with no flags enabled still gets a file (an empty
56
+ * list), so the export stays a faithful snapshot of what is turned on.
57
+ */
58
+ async function exportFeatureFlags(outDir, overwrite) {
59
+ const featureFlags = await (0, feature_flags_1.getFeatureFlags)();
60
+ const featureNames = [
61
+ ...new Set((featureFlags ?? []).map((flag) => flag?.featureName).filter(Boolean)),
62
+ ].sort();
63
+ fs_1.default.mkdirSync(path.resolve(outDir), { recursive: true });
64
+ await (0, file_helpers_1.saveData)(featureNames.map((featureName) => ({ featureName })), path.join(outDir, exports.FEATURE_FLAGS_FILE), overwrite);
65
+ }
66
+ exports.exportFeatureFlags = exportFeatureFlags;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,109 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ const fs_1 = tslib_1.__importDefault(require("fs"));
5
+ const export_1 = tslib_1.__importStar(require("./export"));
6
+ const file_helpers_1 = require("../../helpers/file-helpers");
7
+ const feature_flags_1 = require("../../api/feature-flags");
8
+ const login_1 = require("../../auth/login");
9
+ jest.mock('../../helpers/file-helpers');
10
+ jest.mock('../../api/feature-flags');
11
+ jest.mock('../../auth/login');
12
+ const mocked = (fn) => fn;
13
+ describe('exportFeatureFlags', () => {
14
+ let mkdirSyncSpy;
15
+ beforeEach(() => {
16
+ jest.clearAllMocks();
17
+ mkdirSyncSpy = jest.spyOn(fs_1.default, 'mkdirSync').mockReturnValue(undefined);
18
+ mocked(file_helpers_1.saveData).mockResolvedValue(undefined);
19
+ });
20
+ afterEach(() => {
21
+ mkdirSyncSpy.mockRestore();
22
+ });
23
+ it('writes the enabled flags sorted, without org specific fields', async () => {
24
+ mocked(feature_flags_1.getFeatureFlags).mockResolvedValue([
25
+ { id: '1', orgId: 'org-a', featureName: 'SHOWROOM' },
26
+ { id: '2', orgId: 'org-a', featureName: 'DEV_TABS' },
27
+ ]);
28
+ await (0, export_1.exportFeatureFlags)('out-dir', true);
29
+ expect(mocked(file_helpers_1.saveData)).toHaveBeenCalledWith([{ featureName: 'DEV_TABS' }, { featureName: 'SHOWROOM' }], 'out-dir/feature-flags.yml', true);
30
+ });
31
+ it('still writes a file when no flags are enabled, so the export is a full snapshot', async () => {
32
+ mocked(feature_flags_1.getFeatureFlags).mockResolvedValue([]);
33
+ await (0, export_1.exportFeatureFlags)('out-dir', false);
34
+ expect(mocked(file_helpers_1.saveData)).toHaveBeenCalledWith([], 'out-dir/feature-flags.yml', false);
35
+ });
36
+ });
37
+ describe('ExportFeatureFlags command', () => {
38
+ let mkdirSyncSpy;
39
+ let logs;
40
+ // oclif's init() parses argv and reads the on-disk config, so drive run() with flags set directly
41
+ const runCommand = async () => {
42
+ const command = new export_1.default([], {});
43
+ command.flags = { outDir: 'out-dir', overwrite: true };
44
+ jest.spyOn(command, 'log').mockImplementation((message) => logs.push(String(message)));
45
+ await command.run();
46
+ };
47
+ beforeEach(() => {
48
+ jest.clearAllMocks();
49
+ logs = [];
50
+ process.exitCode = undefined;
51
+ mkdirSyncSpy = jest.spyOn(fs_1.default, 'mkdirSync').mockReturnValue(undefined);
52
+ mocked(login_1.authUser).mockResolvedValue({});
53
+ mocked(file_helpers_1.saveData).mockResolvedValue(undefined);
54
+ mocked(feature_flags_1.getFeatureFlags).mockResolvedValue([]);
55
+ });
56
+ afterEach(() => {
57
+ mkdirSyncSpy.mockRestore();
58
+ process.exitCode = undefined;
59
+ });
60
+ it('leaves the exit code alone on success', async () => {
61
+ await runCommand();
62
+ expect(process.exitCode).toBeUndefined();
63
+ expect(logs.join('\n')).toContain('Feature Flags Export Complete');
64
+ });
65
+ const failures = [
66
+ [
67
+ 'authentication fails',
68
+ () => {
69
+ mocked(login_1.authUser).mockRejectedValue(new Error('boom'));
70
+ },
71
+ ],
72
+ [
73
+ 'the API read fails',
74
+ () => {
75
+ mocked(feature_flags_1.getFeatureFlags).mockRejectedValue(new Error('boom'));
76
+ },
77
+ ],
78
+ [
79
+ 'the directory cannot be created',
80
+ () => {
81
+ mkdirSyncSpy.mockImplementation(() => {
82
+ throw new Error('boom');
83
+ });
84
+ },
85
+ ],
86
+ [
87
+ 'the file write fails',
88
+ () => {
89
+ mocked(file_helpers_1.saveData).mockRejectedValue(new Error('boom'));
90
+ },
91
+ ],
92
+ ];
93
+ it.each(failures)('exits non-zero when %s, so automation does not read it as a success', async (_, fail) => {
94
+ fail();
95
+ await runCommand();
96
+ expect(process.exitCode).toBe(1);
97
+ const output = logs.join('\n');
98
+ expect(output).toContain('Feature Flags Export Failed');
99
+ expect(output).not.toContain('Feature Flags Export Complete');
100
+ });
101
+ it('reports the API message rather than a bare "Error"', async () => {
102
+ // the SDK's ApiError has an undefined message and keeps the body in details
103
+ mocked(feature_flags_1.getFeatureFlags).mockRejectedValue({
104
+ details: '{"message":"Forbidden resource","statusCode":403}',
105
+ });
106
+ await runCommand();
107
+ expect(logs.join('\n')).toContain('Forbidden resource');
108
+ });
109
+ });
@@ -0,0 +1,42 @@
1
+ import { BaseCommand } from '../../basecommand';
2
+ export declare const REQUIRED_PLATFORM_ROLES: string[];
3
+ export default class ImportFeatureFlags extends BaseCommand {
4
+ static description: string;
5
+ static examples: string[];
6
+ static flags: {
7
+ dir: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
8
+ alwaysConfirmEnv: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
9
+ logLevel: import("@oclif/core/lib/interfaces").OptionFlag<string, import("@oclif/core/lib/interfaces/parser").CustomOptions>;
10
+ };
11
+ run(): Promise<void>;
12
+ }
13
+ /**
14
+ * The feature flags API only lets a platform admin/manager create or delete flags, and a
15
+ * missing role surfaces as a generic 403 partway through the run. Checking up front stops
16
+ * the command before it half-applies the file.
17
+ */
18
+ export declare function assertCanManageFeatureFlags(): Promise<void>;
19
+ /**
20
+ * The `instance import` variant: feature flags are one step of a much larger config copy that
21
+ * org admins without a platform role are expected to run, so a missing role (or roles we could
22
+ * not read) logs and skips instead of failing the whole import. Errors from the flag upload
23
+ * itself still propagate — only the permission check is soft here.
24
+ *
25
+ * `contrail feature-flags import` deliberately does the opposite and fails, because there the
26
+ * flags are the entire point of the command.
27
+ */
28
+ export declare function uploadFeatureFlagsIfPermitted(dir: string): Promise<void>;
29
+ /**
30
+ * Makes the target org's enabled feature flags match $dir/feature-flags.yml: enables every
31
+ * flag in the file and disables any flag the target has that the file does not, the same
32
+ * way groups import reconciles groups. Feature flags are not editable in place, so there is
33
+ * no update step.
34
+ *
35
+ * Failures are collected and rethrown so an import never reports success while the org is
36
+ * missing flags.
37
+ *
38
+ * A file that lists no flags at all is skipped rather than applied: reconciling against an
39
+ * empty list would disable every flag in the target org, which is almost never what a copy
40
+ * is meant to do. Flags that should be off in the target have to be disabled by hand.
41
+ */
42
+ export declare function uploadFeatureFlags(dir: string): Promise<void>;
@@ -0,0 +1,191 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.uploadFeatureFlags = exports.uploadFeatureFlagsIfPermitted = exports.assertCanManageFeatureFlags = exports.REQUIRED_PLATFORM_ROLES = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const path = tslib_1.__importStar(require("path"));
6
+ const chalk_1 = tslib_1.__importDefault(require("chalk"));
7
+ const fs_1 = tslib_1.__importDefault(require("fs"));
8
+ const login_1 = require("../../auth/login");
9
+ const core_1 = require("@oclif/core");
10
+ const file_helpers_1 = require("../../helpers/file-helpers");
11
+ const error_helpers_1 = require("../../helpers/error-helpers");
12
+ const feature_flags_1 = require("../../api/feature-flags");
13
+ const users_1 = require("../../api/users");
14
+ const export_1 = require("./export");
15
+ const basecommand_1 = require("../../basecommand");
16
+ const logger_1 = tslib_1.__importDefault(require("../../logger"));
17
+ exports.REQUIRED_PLATFORM_ROLES = ['PLATFORM_ADMIN', 'PLATFORM_MANAGER'];
18
+ class ImportFeatureFlags extends basecommand_1.BaseCommand {
19
+ static description = 'Upload an extracted set of feature flags';
20
+ static examples = [
21
+ `$ contrail feature-flags import
22
+ `,
23
+ ];
24
+ static flags = {
25
+ ...basecommand_1.BaseCommand.baseFlags,
26
+ dir: core_1.Flags.string({
27
+ char: 'd',
28
+ description: `The directory from which to import the feature flags. Defaults to the current directory. The feature flags will be loaded from $dir/${export_1.FEATURE_FLAGS_FILE}`,
29
+ required: false,
30
+ default: '.',
31
+ }),
32
+ };
33
+ async run() {
34
+ try {
35
+ await (0, login_1.authUser)();
36
+ await assertCanManageFeatureFlags();
37
+ this.log(`${chalk_1.default.blue.bold('START')} Uploading Feature Flags.`);
38
+ this.log(`${chalk_1.default.yellow.bold('FEATURE FLAGS')} Uploading`);
39
+ await uploadFeatureFlags(this.flags.dir);
40
+ this.log(`${chalk_1.default.yellow.bold('FEATURE FLAGS')} Uploaded`);
41
+ }
42
+ catch (e) {
43
+ this.log(`${chalk_1.default.red.bold('FAIL')} Feature Flags Upload Failed. ${(0, error_helpers_1.describeError)(e)}`);
44
+ process.exitCode = 1;
45
+ return;
46
+ }
47
+ this.log(`${chalk_1.default.green.bold('COMPLETE')} Feature Flags Upload Complete.`);
48
+ }
49
+ }
50
+ exports.default = ImportFeatureFlags;
51
+ async function getPlatformRoles() {
52
+ try {
53
+ const currentUser = await (0, users_1.getCurrentUserWithPlatformRoles)();
54
+ return normalizePlatformRoles(currentUser?.platformRoles);
55
+ }
56
+ catch (e) {
57
+ throw new Error(`Could not read your platform roles. ${(0, error_helpers_1.describeError)(e)}`);
58
+ }
59
+ }
60
+ /**
61
+ * The feature flags API only lets a platform admin/manager create or delete flags, and a
62
+ * missing role surfaces as a generic 403 partway through the run. Checking up front stops
63
+ * the command before it half-applies the file.
64
+ */
65
+ async function assertCanManageFeatureFlags() {
66
+ const platformRoles = await getPlatformRoles();
67
+ if (!platformRoles.some((role) => exports.REQUIRED_PLATFORM_ROLES.includes(role))) {
68
+ throw new Error(`Importing feature flags requires the ${exports.REQUIRED_PLATFORM_ROLES.join(' or ')} platform role. ` +
69
+ `Your roles: ${platformRoles.length ? platformRoles.join(', ') : 'none'}.`);
70
+ }
71
+ }
72
+ exports.assertCanManageFeatureFlags = assertCanManageFeatureFlags;
73
+ /**
74
+ * The `instance import` variant: feature flags are one step of a much larger config copy that
75
+ * org admins without a platform role are expected to run, so a missing role (or roles we could
76
+ * not read) logs and skips instead of failing the whole import. Errors from the flag upload
77
+ * itself still propagate — only the permission check is soft here.
78
+ *
79
+ * `contrail feature-flags import` deliberately does the opposite and fails, because there the
80
+ * flags are the entire point of the command.
81
+ */
82
+ async function uploadFeatureFlagsIfPermitted(dir) {
83
+ let platformRoles;
84
+ try {
85
+ platformRoles = await getPlatformRoles();
86
+ }
87
+ catch (e) {
88
+ logger_1.default.info(`${chalk_1.default.yellow.bold('FEATURE FLAGS')} Skipping feature flags: ${(0, error_helpers_1.describeError)(e)} ` +
89
+ `Ask a platform admin to run 'contrail feature-flags import -d ${dir}'.`);
90
+ return;
91
+ }
92
+ if (!platformRoles.some((role) => exports.REQUIRED_PLATFORM_ROLES.includes(role))) {
93
+ logger_1.default.info(`${chalk_1.default.yellow.bold('FEATURE FLAGS')} Skipping feature flags: this requires the ` +
94
+ `${exports.REQUIRED_PLATFORM_ROLES.join(' or ')} platform role and you have ` +
95
+ `${platformRoles.length ? platformRoles.join(', ') : 'none'}. ` +
96
+ `Ask a platform admin to run 'contrail feature-flags import -d ${dir}'.`);
97
+ return;
98
+ }
99
+ await uploadFeatureFlags(dir);
100
+ }
101
+ exports.uploadFeatureFlagsIfPermitted = uploadFeatureFlagsIfPermitted;
102
+ /**
103
+ * Makes the target org's enabled feature flags match $dir/feature-flags.yml: enables every
104
+ * flag in the file and disables any flag the target has that the file does not, the same
105
+ * way groups import reconciles groups. Feature flags are not editable in place, so there is
106
+ * no update step.
107
+ *
108
+ * Failures are collected and rethrown so an import never reports success while the org is
109
+ * missing flags.
110
+ *
111
+ * A file that lists no flags at all is skipped rather than applied: reconciling against an
112
+ * empty list would disable every flag in the target org, which is almost never what a copy
113
+ * is meant to do. Flags that should be off in the target have to be disabled by hand.
114
+ */
115
+ async function uploadFeatureFlags(dir) {
116
+ const filePath = path.join(dir, export_1.FEATURE_FLAGS_FILE);
117
+ if (!fs_1.default.existsSync(filePath)) {
118
+ logger_1.default.info(`${chalk_1.default.yellow.bold('FEATURE FLAGS')} No feature flags found in ${dir}. Skipping.`);
119
+ return;
120
+ }
121
+ const data = (0, file_helpers_1.loadData)(filePath) ?? [];
122
+ if (!Array.isArray(data)) {
123
+ throw new Error(`${filePath} must contain a YAML list of feature flags`);
124
+ }
125
+ const featureNamesToEnable = new Set(data.map(toFeatureName).filter(Boolean));
126
+ if (featureNamesToEnable.size === 0) {
127
+ logger_1.default.info(`${chalk_1.default.yellow.bold('FEATURE FLAGS')} ${filePath} lists no feature flags. Skipping, so ` +
128
+ 'the flags currently enabled in this org are left as they are.');
129
+ return;
130
+ }
131
+ const existingFlags = (await (0, feature_flags_1.getFeatureFlags)()) ?? [];
132
+ const enabledFeatureNames = new Set(existingFlags.map((flag) => flag?.featureName));
133
+ const toCreate = [...featureNamesToEnable].filter((name) => !enabledFeatureNames.has(name));
134
+ const toDelete = existingFlags.filter((flag) => !featureNamesToEnable.has(flag?.featureName));
135
+ const failures = [];
136
+ for (const featureName of toCreate) {
137
+ try {
138
+ await (0, feature_flags_1.createFeatureFlag)(featureName);
139
+ logger_1.default.info(`${chalk_1.default.yellow.bold('FEATURE FLAGS')} Enabled ${featureName}`);
140
+ }
141
+ catch (e) {
142
+ failures.push(`could not enable ${featureName}: ${(0, error_helpers_1.describeError)(e)}`);
143
+ }
144
+ }
145
+ const removed = [];
146
+ for (const flag of toDelete) {
147
+ try {
148
+ await (0, feature_flags_1.deleteFeatureFlag)(flag.id);
149
+ logger_1.default.info(`${chalk_1.default.yellow.bold('FEATURE FLAGS')} Disabled ${flag.featureName}`);
150
+ removed.push(flag.featureName);
151
+ }
152
+ catch (e) {
153
+ failures.push(`could not disable ${flag.featureName}: ${(0, error_helpers_1.describeError)(e)}`);
154
+ }
155
+ }
156
+ // call out the removals explicitly: they are the only destructive part of the import
157
+ if (removed.length) {
158
+ const removedList = removed.sort().join(', ');
159
+ logger_1.default.info(`${chalk_1.default.yellow.bold('FEATURE FLAGS')} The following ${removed.length} flag(s) were ` +
160
+ `enabled in this org but not in the source, so they were removed: ${removedList}`);
161
+ }
162
+ if (failures.length) {
163
+ throw new Error(`Failed to apply feature flags. ${failures.join('; ')}`);
164
+ }
165
+ }
166
+ exports.uploadFeatureFlags = uploadFeatureFlags;
167
+ // the API returns platformRoles as an array, but some contexts carry it as a JSON string
168
+ function normalizePlatformRoles(platformRoles) {
169
+ if (Array.isArray(platformRoles)) {
170
+ return platformRoles;
171
+ }
172
+ if (typeof platformRoles === 'string') {
173
+ try {
174
+ const parsed = JSON.parse(platformRoles);
175
+ return Array.isArray(parsed) ? parsed : [];
176
+ }
177
+ catch {
178
+ return [];
179
+ }
180
+ }
181
+ return [];
182
+ }
183
+ // entries are exported as `- featureName: X`, but a hand written `- X` is accepted too
184
+ function toFeatureName(entry) {
185
+ const featureName = typeof entry === 'string' ? entry : entry?.featureName;
186
+ if (typeof featureName !== 'string' || !featureName.trim()) {
187
+ logger_1.default.info(`${chalk_1.default.yellow.bold('FEATURE FLAGS')} Skipping entry with no featureName`);
188
+ return undefined;
189
+ }
190
+ return featureName.trim();
191
+ }
@@ -0,0 +1 @@
1
+ export {};