@opencrvs/toolkit 2.0.0-rc.bd420ee → 2.0.0-rc.bd55713

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 (103) hide show
  1. package/README.md +14 -0
  2. package/build.sh +1 -0
  3. package/create-countryconfig/index.js +50 -20
  4. package/create-countryconfig/package.json +12 -2
  5. package/dist/application-config/index.js +258 -94
  6. package/dist/cli.js +3294 -48
  7. package/dist/commons/api/router.d.ts +445 -20
  8. package/dist/commons/application-config/index.d.ts +1 -0
  9. package/dist/commons/conditionals/conditionals.d.ts +354 -4
  10. package/dist/commons/conditionals/validate.d.ts +51 -2
  11. package/dist/commons/events/ActionConfig.d.ts +28 -2
  12. package/dist/commons/events/ActionDocument.d.ts +6 -0
  13. package/dist/commons/events/ActionInput.d.ts +42 -36
  14. package/dist/commons/events/AdvancedSearchConfig.d.ts +342 -0
  15. package/dist/commons/events/Draft.d.ts +2 -3
  16. package/dist/commons/events/EventDocument.d.ts +3 -0
  17. package/dist/commons/events/FieldConfig.d.ts +378 -50
  18. package/dist/commons/events/FieldType.d.ts +1 -0
  19. package/dist/commons/events/FieldTypeMapping.d.ts +1 -1
  20. package/dist/commons/events/FieldValue.d.ts +6 -0
  21. package/dist/commons/events/WorkqueueConfig.d.ts +150 -150
  22. package/dist/commons/events/field.d.ts +53 -1
  23. package/dist/commons/events/index.d.ts +2 -0
  24. package/dist/commons/events/state/flags.d.ts +16 -0
  25. package/dist/commons/events/state/utils.d.ts +12 -287
  26. package/dist/commons/events/utils.d.ts +12 -1
  27. package/dist/conditionals/index.js +55 -2
  28. package/dist/environment/custom-types.d.ts +33 -0
  29. package/dist/environment/custom-types.d.ts.map +1 -0
  30. package/dist/environment/custom-types.js +2 -0
  31. package/dist/environment/derived-variables.d.ts +134 -0
  32. package/dist/environment/derived-variables.d.ts.map +1 -0
  33. package/dist/environment/derived-variables.js +159 -0
  34. package/dist/environment/editor-questions.d.ts +5 -0
  35. package/dist/environment/editor-questions.d.ts.map +1 -0
  36. package/dist/environment/editor-questions.js +56 -0
  37. package/dist/environment/git.d.ts +5 -0
  38. package/dist/environment/git.d.ts.map +1 -0
  39. package/dist/environment/git.js +28 -0
  40. package/dist/environment/github.d.ts +26 -0
  41. package/dist/environment/github.d.ts.map +1 -0
  42. package/dist/environment/github.js +234 -0
  43. package/dist/environment/index.d.ts +6 -0
  44. package/dist/environment/index.d.ts.map +1 -0
  45. package/dist/environment/index.js +61 -0
  46. package/dist/environment/logger.d.ts +15 -0
  47. package/dist/environment/logger.d.ts.map +1 -0
  48. package/dist/environment/logger.js +15 -0
  49. package/dist/environment/manage-users.d.ts +11 -0
  50. package/dist/environment/manage-users.d.ts.map +1 -0
  51. package/dist/environment/manage-users.js +484 -0
  52. package/dist/environment/questions-helper.d.ts +15 -0
  53. package/dist/environment/questions-helper.d.ts.map +1 -0
  54. package/dist/environment/questions-helper.js +60 -0
  55. package/dist/environment/questions.d.ts +222 -0
  56. package/dist/environment/questions.d.ts.map +1 -0
  57. package/dist/environment/questions.js +455 -0
  58. package/dist/environment/setup-environment.d.ts +2 -0
  59. package/dist/environment/setup-environment.d.ts.map +1 -0
  60. package/dist/environment/setup-environment.js +763 -0
  61. package/dist/environment/ssh-keygen.d.ts +5 -0
  62. package/dist/environment/ssh-keygen.d.ts.map +1 -0
  63. package/dist/environment/ssh-keygen.js +8 -0
  64. package/dist/environment/swarm-to-k8s.d.ts +2 -0
  65. package/dist/environment/swarm-to-k8s.d.ts.map +1 -0
  66. package/dist/environment/swarm-to-k8s.js +162 -0
  67. package/dist/environment/templates/charts-values/dependencies/values.override.yaml +4 -0
  68. package/dist/environment/templates/charts-values/dependencies/values.yaml +82 -0
  69. package/dist/environment/templates/charts-values/opencrvs-services/values.override.yaml +4 -0
  70. package/dist/environment/templates/charts-values/opencrvs-services/values.yaml +79 -0
  71. package/dist/environment/templates/charts-values/traefik/values.override.yaml +4 -0
  72. package/dist/environment/templates/charts-values/traefik/values.yaml +116 -0
  73. package/dist/environment/templates/inventory/inventory.template.yml +100 -0
  74. package/dist/environment/templates/inventory/production.example.yml +77 -0
  75. package/dist/environment/templates/inventory/qa.example.yml +48 -0
  76. package/dist/environment/templates.d.ts +27 -0
  77. package/dist/environment/templates.d.ts.map +1 -0
  78. package/dist/environment/templates.js +149 -0
  79. package/dist/environment/update-workflows.d.ts +2 -0
  80. package/dist/environment/update-workflows.d.ts.map +1 -0
  81. package/dist/environment/update-workflows.js +151 -0
  82. package/dist/environment/users.d.ts +2 -0
  83. package/dist/environment/users.d.ts.map +1 -0
  84. package/dist/environment/users.js +92 -0
  85. package/dist/environment/utils.d.ts +18 -0
  86. package/dist/environment/utils.d.ts.map +1 -0
  87. package/dist/environment/utils.js +90 -0
  88. package/dist/events/index.js +1050 -233
  89. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +1 -1
  90. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  91. package/dist/migrations/v2.0/checkout-upstream-files.js +1 -1
  92. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +3 -0
  93. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +1 -0
  94. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +110 -0
  95. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  96. package/dist/migrations/v2.0/index.js +106 -9
  97. package/dist/notification/index.js +884 -131
  98. package/dist/scopes/index.d.ts +4 -6
  99. package/dist/scopes/index.js +12 -4
  100. package/opencrvs-toolkit-2.0.0-rc.bd55713.tgz +0 -0
  101. package/package.json +20 -2
  102. package/tsconfig.tsbuildinfo +1 -1
  103. package/opencrvs-toolkit-2.0.0-rc.bd420ee.tgz +0 -0
@@ -0,0 +1,48 @@
1
+ all:
2
+ vars:
3
+ # Domain/IP address for remote access to your cluster API
4
+ # Domain/IP address will be added as main endpoint to your ~/.kube/config
5
+ # - If you are behind VPN, use private IP address
6
+ # - If your server is exposed (not recommeded), use public IP address
7
+ # - If you would like to run kubectl commands from the remote server, leave this field empty
8
+
9
+ # IMPORTANT: If master VM has multiple ethernet interfaces, put private IP address at kube_api_address
10
+ # kube_api_host: 10.10.10.10
11
+ kube_api_host: []
12
+
13
+ # Default ansible provision user, keep as is
14
+ ansible_user: provision
15
+
16
+ # single_node:
17
+ # For development/qa/testing/staging keep true
18
+ # For production keep false
19
+ # Defaults production configuration:
20
+ # - master node
21
+ # - 2 worker nodes
22
+ single_node: true
23
+
24
+ # users: Add as many users as you wish
25
+ # Configuration example
26
+ # - name: <login>
27
+ # ssh_keys:
28
+ # - <public ssh key 1>
29
+ # - <public ssh key 2>
30
+ # state: present
31
+ # role: admin
32
+ # Allowed roles:
33
+ # - operator: grant read only access to OS and full access to kubernetes cluster
34
+ # - admin: grant full access to OS and kubernetes cluster
35
+ # Allowed states:
36
+ # - present: user is allowed to login
37
+ # - absent: user account is disabled
38
+ users: []
39
+
40
+ children:
41
+ master:
42
+ hosts:
43
+ # Replace master with value returned by command: hostname
44
+ master:
45
+ # Keep values (ansible_host, ansible_connection) as is
46
+ # Ansible is executed on master node
47
+ ansible_host: localhost
48
+ ansible_connection: local
@@ -0,0 +1,27 @@
1
+ export declare function getUsers(data: any): any;
2
+ export declare function extractAndModifyUsers(data: any): any;
3
+ export declare function dockerManagerFirst(data: any): string;
4
+ export declare function extractBackupNode(data: any): string;
5
+ export declare function extractWorkerNodes(data: any): string[];
6
+ /**
7
+ * Copy charts-values directory into environments/<env>
8
+ * @param env Environment name
9
+ * Usage: copyChartsValues('dev')
10
+ */
11
+ /**
12
+ * Recursively copy a directory and replace placeholders in text files.
13
+ */
14
+ export declare function copyChartsValues(env: string, values: Record<string, string | boolean>): void;
15
+ /**
16
+ * Generate Ansible inventory file from template
17
+ * @param env Environment name
18
+ * @param number_of_servers Number of servers (1 for single-node, >1 for multi-node)
19
+ * @param values Key-value pairs to replace in the template
20
+ * Usage: generateInventory('dev', 1, {
21
+ * HOST: process.env.APP_HOST || "localhost",
22
+ * USER: process.env.SSH_USER || "ubuntu",
23
+ * PORT: process.env.SSH_PORT || "22"
24
+ * });
25
+ */
26
+ export declare function generateInventory(env: string, values: Record<string, any>): void;
27
+ //# sourceMappingURL=templates.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/environment/templates.ts"],"names":[],"mappings":"AAWA,wBAAgB,QAAQ,CAAC,IAAI,EAAE,GAAG,GAAG,GAAG,CAKvC;AAID,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,GAAG,GAAG,GAAG,CAYpD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM,CASpD;AAED,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM,CASnD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM,EAAE,CAStD;AAGD;;;;GAIG;AACH;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,QAwCrF;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,QAczE"}
@@ -0,0 +1,149 @@
1
+ "use strict";
2
+ var __rest = (this && this.__rest) || function (s, e) {
3
+ var t = {};
4
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
5
+ t[p] = s[p];
6
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
7
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
8
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
9
+ t[p[i]] = s[p[i]];
10
+ }
11
+ return t;
12
+ };
13
+ var __importDefault = (this && this.__importDefault) || function (mod) {
14
+ return (mod && mod.__esModule) ? mod : { "default": mod };
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.getUsers = getUsers;
18
+ exports.extractAndModifyUsers = extractAndModifyUsers;
19
+ exports.dockerManagerFirst = dockerManagerFirst;
20
+ exports.extractBackupNode = extractBackupNode;
21
+ exports.extractWorkerNodes = extractWorkerNodes;
22
+ exports.copyChartsValues = copyChartsValues;
23
+ exports.generateInventory = generateInventory;
24
+ const fs_1 = __importDefault(require("fs"));
25
+ const path_1 = __importDefault(require("path"));
26
+ const logger_1 = require("./logger");
27
+ const handlebars_1 = __importDefault(require("handlebars"));
28
+ // Register a helper to increment numbers
29
+ handlebars_1.default.registerHelper('data_label_idx', function (value) {
30
+ return parseInt(value) + 2;
31
+ });
32
+ function getUsers(data) {
33
+ var _a, _b;
34
+ if (!((_b = (_a = data === null || data === void 0 ? void 0 : data.all) === null || _a === void 0 ? void 0 : _a.vars) === null || _b === void 0 ? void 0 : _b.users)) {
35
+ return { users: [] };
36
+ }
37
+ return data.all.vars.users;
38
+ }
39
+ // START: TEMPORAL SECTION FOR TRANSITION FROM DOCKER SWARM TO K8s
40
+ // Extract users from the old inventory
41
+ // Docker swarm format to new
42
+ function extractAndModifyUsers(data) {
43
+ var _a, _b;
44
+ if (!((_b = (_a = data === null || data === void 0 ? void 0 : data.all) === null || _a === void 0 ? void 0 : _a.vars) === null || _b === void 0 ? void 0 : _b.users)) {
45
+ return { users: [] };
46
+ }
47
+ const users = data.all.vars.users.map((user) => {
48
+ const { sudoer } = user, rest = __rest(user, ["sudoer"]);
49
+ return Object.assign(Object.assign({}, rest), { role: sudoer ? "admin" : "operator" });
50
+ });
51
+ return users;
52
+ }
53
+ function dockerManagerFirst(data) {
54
+ var _a;
55
+ if (!((_a = data === null || data === void 0 ? void 0 : data['docker-manager-first']) === null || _a === void 0 ? void 0 : _a.hosts)) {
56
+ throw new Error('Invalid YAML structure: missing docker-manager-first.hosts');
57
+ }
58
+ const hosts = data['docker-manager-first'].hosts;
59
+ const dockerManagerFirst = Object.values(hosts)
60
+ .filter((host) => host.ansible_host)
61
+ .map((host) => host.ansible_host);
62
+ return dockerManagerFirst.length === 1 ? dockerManagerFirst[0] : '';
63
+ }
64
+ function extractBackupNode(data) {
65
+ var _a;
66
+ if (!((_a = data === null || data === void 0 ? void 0 : data['backups']) === null || _a === void 0 ? void 0 : _a.hosts)) {
67
+ return '';
68
+ }
69
+ const hosts = data['backups'].hosts;
70
+ const backupHostEntry = Object.values(hosts)
71
+ .filter((host) => host.ansible_host)
72
+ .map((host) => host.ansible_host);
73
+ return backupHostEntry.length === 1 ? backupHostEntry[0] : '';
74
+ }
75
+ function extractWorkerNodes(data) {
76
+ var _a;
77
+ if (!((_a = data === null || data === void 0 ? void 0 : data['docker-workers']) === null || _a === void 0 ? void 0 : _a.hosts)) {
78
+ return [];
79
+ }
80
+ const hosts = data['docker-workers'].hosts;
81
+ const worker_hosts = Object.values(hosts)
82
+ .filter((host) => host.ansible_host)
83
+ .map((host) => host.ansible_host);
84
+ return worker_hosts;
85
+ }
86
+ // END: TEMPORAL SECTION FOR TRANSITION FROM DOCKER SWARM TO K8s
87
+ /**
88
+ * Copy charts-values directory into environments/<env>
89
+ * @param env Environment name
90
+ * Usage: copyChartsValues('dev')
91
+ */
92
+ /**
93
+ * Recursively copy a directory and replace placeholders in text files.
94
+ */
95
+ function copyChartsValues(env, values) {
96
+ const srcDir = path_1.default.resolve(__dirname, "templates", "charts-values");
97
+ const destDir = path_1.default.resolve(process.cwd(), "environments", env);
98
+ fs_1.default.mkdirSync(destDir, { recursive: true });
99
+ values['lets_encrypt'] = values['traefik_mode'] === "lets_encrypt";
100
+ values['static_ssl'] = values['traefik_mode'] === "static_ssl";
101
+ function copyRecursive(src, dest) {
102
+ const stat = fs_1.default.statSync(src);
103
+ if (stat.isDirectory()) {
104
+ fs_1.default.mkdirSync(dest, { recursive: true });
105
+ for (const item of fs_1.default.readdirSync(src)) {
106
+ copyRecursive(path_1.default.join(src, item), path_1.default.join(dest, item));
107
+ }
108
+ }
109
+ else {
110
+ const content = fs_1.default.readFileSync(src, "utf8");
111
+ const template = handlebars_1.default.compile(content);
112
+ const updated = template(values);
113
+ const isOverridesFile = dest.endsWith("override.yaml");
114
+ // Skip overwrite for existing overrides.yaml
115
+ if (isOverridesFile && fs_1.default.existsSync(dest)) {
116
+ (0, logger_1.log)(` ↷ Skipped existing overrides file: ${dest}`);
117
+ return;
118
+ }
119
+ fs_1.default.writeFileSync(dest, updated, "utf8");
120
+ (0, logger_1.log)(` ✓ Created: ${dest}`);
121
+ }
122
+ }
123
+ (0, logger_1.log)(`\n📋 Copying charts-values templates to ${destDir}:`);
124
+ copyRecursive(srcDir, destDir);
125
+ (0, logger_1.success)(`✅ Completed copying charts-values.\n`);
126
+ }
127
+ /**
128
+ * Generate Ansible inventory file from template
129
+ * @param env Environment name
130
+ * @param number_of_servers Number of servers (1 for single-node, >1 for multi-node)
131
+ * @param values Key-value pairs to replace in the template
132
+ * Usage: generateInventory('dev', 1, {
133
+ * HOST: process.env.APP_HOST || "localhost",
134
+ * USER: process.env.SSH_USER || "ubuntu",
135
+ * PORT: process.env.SSH_PORT || "22"
136
+ * });
137
+ */
138
+ function generateInventory(env, values) {
139
+ // Template and output paths
140
+ const templatePath = path_1.default.join(__dirname, "templates", "inventory", "inventory.template.yml");
141
+ const outputPath = path_1.default.join(process.cwd(), "infrastructure", "server-setup", "inventory", `${env}.yml`);
142
+ const templateFile = fs_1.default.readFileSync(templatePath, "utf-8");
143
+ const template = handlebars_1.default.compile(templateFile);
144
+ values['single_node'] = (values['kube_worker_nodes'].length > 0 || values['backup_host']) ? "false" : "true";
145
+ const updated = template(values);
146
+ fs_1.default.mkdirSync(path_1.default.dirname(outputPath), { recursive: true });
147
+ fs_1.default.writeFileSync(outputPath, updated);
148
+ (0, logger_1.log)(`\n✅ Generated inventory file at ${outputPath}\n`);
149
+ }
@@ -0,0 +1,2 @@
1
+ export declare function updateWorkflowEnvironments(): Promise<void>;
2
+ //# sourceMappingURL=update-workflows.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"update-workflows.d.ts","sourceRoot":"","sources":["../../src/environment/update-workflows.ts"],"names":[],"mappings":"AA4FA,wBAAsB,0BAA0B,IAAI,OAAO,CAAC,IAAI,CAAC,CAsChE"}
@@ -0,0 +1,151 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ exports.updateWorkflowEnvironments = updateWorkflowEnvironments;
36
+ const promises_1 = require("fs/promises");
37
+ const fs_1 = require("fs");
38
+ const path_1 = require("path");
39
+ const glob = __importStar(require("glob"));
40
+ const yaml = __importStar(require("js-yaml"));
41
+ const logger_1 = require("./logger");
42
+ function extractInfrastructureNames() {
43
+ return __awaiter(this, void 0, void 0, function* () {
44
+ const files = glob.sync('infrastructure/server-setup/inventory/*.yml');
45
+ const infraEnvironments = files.map(file => (0, path_1.basename)(file, '.yml'));
46
+ if (infraEnvironments.length === 0) {
47
+ console.log('⚠️ Warning: No environment directories found in infrastructure/server-setup/inventory/');
48
+ return [];
49
+ }
50
+ (0, logger_1.log)('🔍 Found infrastructure configurations:', infraEnvironments.join(', '));
51
+ return infraEnvironments;
52
+ });
53
+ }
54
+ function extractEnvironmentNames() {
55
+ return __awaiter(this, void 0, void 0, function* () {
56
+ const entries = yield (0, promises_1.readdir)('environments');
57
+ // Filter only directories
58
+ const environments = entries.filter(entry => {
59
+ const fullPath = (0, path_1.join)('environments', entry);
60
+ return (0, fs_1.statSync)(fullPath).isDirectory();
61
+ });
62
+ if (environments.length === 0) {
63
+ console.log('⚠️ Warning: No environment directories found in environments/');
64
+ return [];
65
+ }
66
+ (0, logger_1.log)('🔍 Found OpenCRVS configurations:', environments.join(', '));
67
+ return environments;
68
+ });
69
+ }
70
+ function updateOptionsInYaml(content, envList) {
71
+ // Find the options array pattern
72
+ // Matches: options: followed by array items (- item)
73
+ const optionsRegex = /([ ]*options:[ ]*\n)((?:[ ]*-[^\n]*\n)+)/;
74
+ const match = content.match(optionsRegex);
75
+ if (!match) {
76
+ throw new Error('Could not find options array in workflow file');
77
+ }
78
+ // Get the indentation from the first array item
79
+ const firstItemMatch = match[2].match(/^([ ]*)-/);
80
+ const itemIndent = firstItemMatch ? firstItemMatch[1] : ' ';
81
+ // Create new options array
82
+ const newOptions = match[1] + envList.map(env => `${itemIndent}- ${env}`).join('\n') + '\n';
83
+ // Replace the old options array with the new one
84
+ return content.replace(optionsRegex, newOptions);
85
+ }
86
+ function updateWorkflows(envList, config) {
87
+ return __awaiter(this, void 0, void 0, function* () {
88
+ var _a, _b, _c, _d;
89
+ const { workflows } = config;
90
+ for (const workflowPath of workflows) {
91
+ try {
92
+ const fileContents = (0, fs_1.readFileSync)(workflowPath, 'utf8');
93
+ // Verify the file is valid YAML and has the expected structure
94
+ const workflowData = yaml.load(fileContents);
95
+ if (!((_d = (_c = (_b = (_a = workflowData === null || workflowData === void 0 ? void 0 : workflowData.on) === null || _a === void 0 ? void 0 : _a.workflow_dispatch) === null || _b === void 0 ? void 0 : _b.inputs) === null || _c === void 0 ? void 0 : _c.environment) === null || _d === void 0 ? void 0 : _d.options)) {
96
+ throw new Error('Workflow does not have the expected structure: on.workflow_dispatch.inputs.environment.options');
97
+ }
98
+ // Update only the options array while preserving everything else
99
+ const updatedContent = updateOptionsInYaml(fileContents, envList);
100
+ (0, fs_1.writeFileSync)(workflowPath, updatedContent, 'utf8');
101
+ (0, logger_1.log)(` ✓ Successfully updated ${workflowPath}`);
102
+ }
103
+ catch (error) {
104
+ console.error(`\n⚠️ Error updating ${workflowPath} with environments: [${envList.join(', ')}]`);
105
+ console.error(`✗ Failed to update ${workflowPath}:`, error);
106
+ throw error;
107
+ }
108
+ }
109
+ });
110
+ }
111
+ function updateWorkflowEnvironments() {
112
+ return __awaiter(this, void 0, void 0, function* () {
113
+ try {
114
+ // Extract infrastructure names
115
+ const infraEnvironments = yield extractInfrastructureNames();
116
+ // Update workflows with infrastructure configurations
117
+ console.log('🔄 Updating infrastructure workflows:');
118
+ yield updateWorkflows(infraEnvironments, {
119
+ workflows: [
120
+ '.github/workflows/provision.yml',
121
+ '.github/workflows/reset-2fa.yml',
122
+ ],
123
+ path: 'on.workflow_dispatch.inputs.environment.options'
124
+ });
125
+ // Extract environment names (only directories)
126
+ const environments = yield extractEnvironmentNames();
127
+ const workflows = [
128
+ '.github/workflows/deploy-dependencies.yml',
129
+ '.github/workflows/deploy-opencrvs.yml',
130
+ '.github/workflows/clear-all-data.yml',
131
+ '.github/workflows/seed-data.yml',
132
+ '.github/workflows/reindex.yml',
133
+ '.github/workflows/github-to-k8s-sync-env.yml'
134
+ ];
135
+ (0, logger_1.log)("📋 Updating OpenCRVS application workflows:");
136
+ yield updateWorkflows(environments, {
137
+ workflows,
138
+ path: 'on.workflow_dispatch.inputs.environment.options'
139
+ });
140
+ (0, logger_1.success)('✅ All workflows updated successfully!');
141
+ }
142
+ catch (error) {
143
+ console.error('\n❌ Error updating workflows:', error);
144
+ process.exit(1);
145
+ }
146
+ });
147
+ }
148
+ // Only run if this file is executed directly
149
+ if (require.main === module) {
150
+ updateWorkflowEnvironments();
151
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=users.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"users.d.ts","sourceRoot":"","sources":["../../src/environment/users.ts"],"names":[],"mappings":""}
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ const fs = __importStar(require("fs"));
39
+ const path = __importStar(require("path"));
40
+ const kleur_1 = __importDefault(require("kleur"));
41
+ const manage_users_1 = require("./manage-users");
42
+ function select(options) {
43
+ return __awaiter(this, void 0, void 0, function* () {
44
+ const inquirer = yield import('@inquirer/prompts');
45
+ return inquirer.select(options);
46
+ });
47
+ }
48
+ /**
49
+ * Allow user to select inventory file (environment from a list)
50
+ *
51
+ * @param {string} dirPath - Path to the inventory file
52
+ *
53
+ * * @returns {string} Inventory file
54
+ */
55
+ function selectInventoryFile() {
56
+ return __awaiter(this, arguments, void 0, function* (dirPath = './infrastructure/server-setup/inventory/') {
57
+ // Check if directory exists
58
+ if (!fs.existsSync(dirPath)) {
59
+ throw Error(`Directory ${dirPath} doesn't exist`);
60
+ }
61
+ // Read and filter files
62
+ const files = fs.readdirSync(dirPath)
63
+ .filter(file => {
64
+ const filePath = path.join(dirPath, file);
65
+ const isFile = fs.statSync(filePath).isFile();
66
+ const ext = path.extname(file).slice(1).toLowerCase();
67
+ return isFile && (ext === 'yml' || ext === 'yaml');
68
+ })
69
+ .sort();
70
+ if (files.length === 0) {
71
+ throw Error(`No environment configuration files found at ${dirPath}`);
72
+ }
73
+ // Create choices - remove extension from display
74
+ const choices = files.map(file => ({
75
+ name: path.basename(file, path.extname(file)),
76
+ value: path.join(dirPath, file)
77
+ }));
78
+ const selectedFile = yield select({
79
+ message: 'Select environment (inventory file) to load users:',
80
+ choices: choices
81
+ });
82
+ return selectedFile;
83
+ });
84
+ }
85
+ function manageUsersStandalone() {
86
+ return __awaiter(this, void 0, void 0, function* () {
87
+ console.log('\n', kleur_1.default.bold().underline("Manage users"), '\n');
88
+ const inventory_file = yield selectInventoryFile();
89
+ (0, manage_users_1.manageUsers)(inventory_file);
90
+ });
91
+ }
92
+ manageUsersStandalone();
@@ -0,0 +1,18 @@
1
+ import { Secret, Variable } from './github';
2
+ import { Answers } from './custom-types';
3
+ export declare function generateLongPassword(): string;
4
+ export declare function findExistingValue<T extends string>(name: string, type: T, scope: 'ENVIRONMENT' | 'REPOSITORY', existingValues: Array<Secret | Variable>): (T extends "SECRET" ? Secret : T extends "VARIABLE" ? Variable : never) | undefined;
5
+ /**
6
+ * Merges and stores secrets in `.env.{environment}` file.
7
+ * Updates existing variables, preserves unchanged ones, adds new ones.
8
+ *
9
+ * @param environment - Environment name (e.g., 'production')
10
+ * @param answers - Variables to update: `[{ name: 'KEY', value: 'val' }]`
11
+ *
12
+ * @example
13
+ * storeSecrets('prod', [{ name: 'API_KEY', value: 'abc123' }]);
14
+ */
15
+ export declare function storeSecrets(environment: string, answers: Answers): void;
16
+ export declare function readYamlFile(filePath: any): any;
17
+ export declare function writeYamlFile(filePath: string, data: any): void;
18
+ //# sourceMappingURL=utils.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../src/environment/utils.ts"],"names":[],"mappings":"AAIA,OAAO,EACL,MAAM,EACN,QAAQ,EACT,MAAM,UAAU,CAAA;AACjB,OAAO,EACL,OAAO,EACR,MAAM,gBAAgB,CAAA;AAGvB,wBAAgB,oBAAoB,WAMnC;AAED,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,MAAM,EAChD,IAAI,EAAE,MAAM,EACZ,IAAI,EAAE,CAAC,EACP,KAAK,EAAE,aAAa,GAAG,YAAY,EACnC,cAAc,EAAE,KAAK,CAAC,MAAM,GAAG,QAAQ,CAAC,GAMpC,CAAC,CAAC,SAAS,QAAQ,GAAG,MAAM,GAAG,CAAC,SAAS,UAAU,GAAG,QAAQ,GAAG,KAAK,CAAC,GACvE,SAAS,CACd;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,QAoBjE;AAED,wBAAgB,YAAY,CAAC,QAAQ,EAAE,GAAG,GAAG,GAAG,CAG/C;AAED,wBAAgB,aAAa,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,QAcxD"}
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ Object.defineProperty(exports, "__esModule", { value: true });
29
+ exports.generateLongPassword = generateLongPassword;
30
+ exports.findExistingValue = findExistingValue;
31
+ exports.storeSecrets = storeSecrets;
32
+ exports.readYamlFile = readYamlFile;
33
+ exports.writeYamlFile = writeYamlFile;
34
+ const fs_1 = __importStar(require("fs"));
35
+ const yaml = __importStar(require("js-yaml"));
36
+ const dotenv_1 = __importDefault(require("dotenv"));
37
+ function generateLongPassword() {
38
+ const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
39
+ let result = '';
40
+ for (let i = 16; i > 0; --i)
41
+ result += chars[Math.floor(Math.random() * chars.length)];
42
+ return result;
43
+ }
44
+ function findExistingValue(name, type, scope, existingValues) {
45
+ return existingValues.find((value) => value.name === name && value.type === type && value.scope === scope);
46
+ }
47
+ /**
48
+ * Merges and stores secrets in `.env.{environment}` file.
49
+ * Updates existing variables, preserves unchanged ones, adds new ones.
50
+ *
51
+ * @param environment - Environment name (e.g., 'production')
52
+ * @param answers - Variables to update: `[{ name: 'KEY', value: 'val' }]`
53
+ *
54
+ * @example
55
+ * storeSecrets('prod', [{ name: 'API_KEY', value: 'abc123' }]);
56
+ */
57
+ function storeSecrets(environment, answers) {
58
+ let envConfig = {};
59
+ try {
60
+ envConfig = dotenv_1.default.parse((0, fs_1.readFileSync)(`${process.cwd()}/.env.${environment}`));
61
+ }
62
+ catch (error) {
63
+ envConfig = {};
64
+ }
65
+ const linesFromAnswers = answers.map((update) => `${update.name}="${update.value}"`);
66
+ const linesFromEnvConfig = Object.entries(envConfig)
67
+ .filter(([name]) => !answers.find((update) => update.name === name))
68
+ .map(([name, value]) => `${name}="${value}"`);
69
+ const allLines = [...linesFromEnvConfig, ...linesFromAnswers].sort();
70
+ (0, fs_1.writeFileSync)(`.env.${environment}`, allLines.join('\n'));
71
+ }
72
+ function readYamlFile(filePath) {
73
+ const fileContent = fs_1.default.readFileSync(filePath, "utf8");
74
+ return yaml.load(fileContent);
75
+ }
76
+ function writeYamlFile(filePath, data) {
77
+ try {
78
+ const yamlContent = yaml.dump(data, {
79
+ indent: 2,
80
+ lineWidth: -1,
81
+ flowLevel: -1, // Prevent flow style for arrays/objects
82
+ noRefs: true,
83
+ sortKeys: false
84
+ });
85
+ fs_1.default.writeFileSync(filePath, yamlContent, 'utf8');
86
+ }
87
+ catch (error) {
88
+ throw new Error(`Failed to write inventory file: ${error}`);
89
+ }
90
+ }