@opencrvs/toolkit 2.0.1 → 2.1.0-beta.2

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 (167) hide show
  1. package/README.md +18 -12
  2. package/build.sh +14 -5
  3. package/create-countryconfig/index.js +313 -129
  4. package/create-countryconfig/node_modules/.bin/degit +21 -0
  5. package/create-countryconfig/package.json +5 -2
  6. package/dist/application-config/index.js +367 -278
  7. package/dist/authentication/index.d.ts +67 -0
  8. package/dist/authentication/index.d.ts.map +1 -0
  9. package/dist/authentication/index.js +754 -0
  10. package/dist/cli.js +4320 -4790
  11. package/dist/commons/api/router.d.ts +4120 -2982
  12. package/dist/commons/application-config/index.d.ts +6 -6
  13. package/dist/commons/conditionals/conditionals.d.ts +32 -323
  14. package/dist/commons/conditionals/validate.d.ts +16 -5
  15. package/dist/commons/events/ActionConfig.d.ts +302 -67
  16. package/dist/commons/events/ActionDocument.d.ts +159 -121
  17. package/dist/commons/events/ActionInput.d.ts +30 -10
  18. package/dist/commons/events/ActionStatus.d.ts +14 -0
  19. package/dist/commons/events/ActionType.d.ts +63 -58
  20. package/dist/commons/events/AdvancedSearchConfig.d.ts +537 -495
  21. package/dist/commons/events/AuditLog.d.ts +189 -40
  22. package/dist/commons/events/CompositeFieldValue.d.ts +4 -4
  23. package/dist/commons/events/Conditional.d.ts +3 -3
  24. package/dist/commons/events/CountryConfigQueryInput.d.ts +603 -561
  25. package/dist/commons/events/Draft.d.ts +38 -36
  26. package/dist/commons/events/DynamicFieldValue.d.ts +9 -9
  27. package/dist/commons/events/EventConfig.d.ts +8 -3
  28. package/dist/commons/events/EventDocument.d.ts +537 -47
  29. package/dist/commons/events/EventIndex.d.ts +61 -59
  30. package/dist/commons/events/EventMetadata.d.ts +59 -43
  31. package/dist/commons/events/EventStatus.d.ts +19 -0
  32. package/dist/commons/events/FieldConfig.d.ts +431 -380
  33. package/dist/commons/events/FieldType.d.ts +51 -51
  34. package/dist/commons/events/FieldTypeMapping.d.ts +86 -86
  35. package/dist/commons/events/FieldValue.d.ts +14 -14
  36. package/dist/commons/events/Flag.d.ts +57 -15
  37. package/dist/commons/events/PlainDate.d.ts +8 -0
  38. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  39. package/dist/commons/events/TemplateConfig.d.ts +1 -1
  40. package/dist/commons/events/WorkqueueColumnConfig.d.ts +40 -40
  41. package/dist/commons/events/WorkqueueConfig.d.ts +835 -790
  42. package/dist/commons/events/deduplication.d.ts +1 -1
  43. package/dist/commons/events/event.d.ts +14 -2
  44. package/dist/commons/events/field.d.ts +69 -198
  45. package/dist/commons/events/index.d.ts +1 -0
  46. package/dist/commons/events/locationPayloads.d.ts +95 -0
  47. package/dist/commons/events/locations.d.ts +248 -14
  48. package/dist/commons/events/mocks.test.utils.d.ts +48 -4
  49. package/dist/commons/events/scopes.d.ts +5 -4
  50. package/dist/commons/events/state/index.d.ts +23 -15
  51. package/dist/commons/events/state/utils.d.ts +15 -6
  52. package/dist/commons/events/test.utils.d.ts +68 -42
  53. package/dist/commons/events/utils.d.ts +143 -110
  54. package/dist/commons/notification/UserNotifications.d.ts +38 -18
  55. package/dist/commons/notification/dispatch.d.ts +10 -0
  56. package/dist/commons/notification/index.d.ts +1 -0
  57. package/dist/conditionals/index.js +340 -63
  58. package/dist/csv.d.ts +25 -0
  59. package/dist/csv.d.ts.map +1 -0
  60. package/dist/csv.js +120 -0
  61. package/dist/environment/custom-types.d.ts +33 -0
  62. package/dist/environment/custom-types.d.ts.map +1 -0
  63. package/dist/environment/custom-types.js +12 -0
  64. package/dist/environment/derived-variables.d.ts +122 -0
  65. package/dist/environment/derived-variables.d.ts.map +1 -0
  66. package/dist/environment/derived-variables.js +155 -0
  67. package/dist/environment/editor-questions.d.ts +4 -0
  68. package/dist/environment/editor-questions.d.ts.map +1 -0
  69. package/dist/environment/editor-questions.js +67 -0
  70. package/dist/environment/git.d.ts +5 -0
  71. package/dist/environment/git.d.ts.map +1 -0
  72. package/dist/environment/git.js +38 -0
  73. package/dist/environment/github.d.ts +26 -0
  74. package/dist/environment/github.d.ts.map +1 -0
  75. package/dist/environment/github.js +247 -0
  76. package/dist/environment/index.d.ts +6 -0
  77. package/dist/environment/index.d.ts.map +1 -0
  78. package/dist/environment/index.js +81 -0
  79. package/dist/environment/logger.d.ts +18 -0
  80. package/dist/environment/logger.d.ts.map +1 -0
  81. package/dist/environment/logger.js +25 -0
  82. package/dist/environment/manage-users.d.ts +11 -0
  83. package/dist/environment/manage-users.d.ts.map +1 -0
  84. package/dist/environment/manage-users.js +507 -0
  85. package/dist/environment/paths.d.ts +7 -0
  86. package/dist/environment/paths.d.ts.map +1 -0
  87. package/dist/environment/paths.js +72 -0
  88. package/dist/environment/questions-helper.d.ts +15 -0
  89. package/dist/environment/questions-helper.d.ts.map +1 -0
  90. package/dist/environment/questions-helper.js +70 -0
  91. package/dist/environment/questions.d.ts +200 -0
  92. package/dist/environment/questions.d.ts.map +1 -0
  93. package/dist/environment/questions.js +418 -0
  94. package/dist/environment/setup-environment.d.ts +2 -0
  95. package/dist/environment/setup-environment.d.ts.map +1 -0
  96. package/dist/environment/setup-environment.js +793 -0
  97. package/dist/environment/ssh-keygen.d.ts +5 -0
  98. package/dist/environment/ssh-keygen.d.ts.map +1 -0
  99. package/dist/environment/ssh-keygen.js +21 -0
  100. package/dist/environment/swarm-to-k8s.d.ts +2 -0
  101. package/dist/environment/swarm-to-k8s.d.ts.map +1 -0
  102. package/dist/environment/swarm-to-k8s.js +183 -0
  103. package/dist/environment/templates.d.ts +26 -0
  104. package/dist/environment/templates.d.ts.map +1 -0
  105. package/dist/environment/templates.js +159 -0
  106. package/dist/environment/update-workflows.d.ts +2 -0
  107. package/dist/environment/update-workflows.d.ts.map +1 -0
  108. package/dist/environment/update-workflows.js +195 -0
  109. package/dist/environment/upgrade.d.ts +2 -0
  110. package/dist/environment/upgrade.d.ts.map +1 -0
  111. package/dist/environment/upgrade.js +82 -0
  112. package/dist/environment/users.d.ts +2 -0
  113. package/dist/environment/users.d.ts.map +1 -0
  114. package/dist/environment/users.js +120 -0
  115. package/dist/environment/utils.d.ts +6 -0
  116. package/dist/environment/utils.d.ts.map +1 -0
  117. package/dist/environment/utils.js +83 -0
  118. package/dist/events/deduplication.d.ts +1 -1
  119. package/dist/events/index.js +8107 -7388
  120. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
  121. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  122. package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
  123. package/dist/migrations/v2.0/convert-config-files-to-ts.js +17 -7
  124. package/dist/migrations/v2.0/index.js +88 -5143
  125. package/dist/migrations/v2.0/migrate-application-config-url.js +4 -3
  126. package/dist/migrations/v2.0/remove-hearth-migrations.js +17 -7
  127. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts +3 -0
  128. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts.map +1 -0
  129. package/dist/migrations/v2.1/add-explicit-correction-flags.js +234 -0
  130. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  131. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  132. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  133. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  134. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  135. package/dist/migrations/v2.1/add-translations.js +213 -0
  136. package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
  137. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  138. package/dist/migrations/v2.1/enable-telemetry.js +438 -0
  139. package/dist/migrations/v2.1/index.d.ts +6 -0
  140. package/dist/migrations/v2.1/index.d.ts.map +1 -0
  141. package/dist/migrations/v2.1/index.js +1276 -0
  142. package/dist/notification/index.js +2011 -1446
  143. package/dist/scopes/index.d.ts +550 -161
  144. package/dist/scopes/index.js +341 -63
  145. package/dist/telemetry/index.d.ts +45 -0
  146. package/dist/telemetry/index.d.ts.map +1 -0
  147. package/dist/telemetry/index.js +39 -0
  148. package/dist/templates/charts-values/dependencies/values.override.yaml +4 -0
  149. package/dist/templates/charts-values/dependencies/values.yaml +82 -0
  150. package/dist/templates/charts-values/opencrvs-services/values.override.yaml +4 -0
  151. package/dist/templates/charts-values/opencrvs-services/values.yaml +78 -0
  152. package/dist/templates/charts-values/opentelemetry/values.yaml +95 -0
  153. package/dist/templates/charts-values/traefik/values.override.yaml +4 -0
  154. package/dist/templates/charts-values/traefik/values.yaml +129 -0
  155. package/dist/templates/inventory/inventory.template.yml +98 -0
  156. package/dist/translations/check.d.ts +21 -0
  157. package/dist/translations/check.d.ts.map +1 -0
  158. package/dist/translations/check.js +132 -0
  159. package/dist/verify/endpoints.d.ts.map +1 -1
  160. package/dist/verify/endpoints.js +26 -26
  161. package/opencrvs-toolkit-2.1.0-beta.2.tgz +0 -0
  162. package/package.json +25 -6
  163. package/tsconfig.build.json +11 -0
  164. package/tsconfig.build.tsbuildinfo +1 -0
  165. package/tsconfig.json +3 -0
  166. package/opencrvs-toolkit-2.0.1.tgz +0 -0
  167. package/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,5 @@
1
+ export declare function generateSSHKeyPair(): {
2
+ publicKey: string;
3
+ privateKey: string;
4
+ };
5
+ //# sourceMappingURL=ssh-keygen.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssh-keygen.d.ts","sourceRoot":"","sources":["../../src/environment/ssh-keygen.ts"],"names":[],"mappings":"AAaA,wBAAgB,kBAAkB,IAAI;IACpC,SAAS,EAAE,MAAM,CAAA;IACjB,UAAU,EAAE,MAAM,CAAA;CACnB,CAMA"}
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ exports.generateSSHKeyPair = generateSSHKeyPair;
14
+ const ssh2_1 = require("ssh2");
15
+ function generateSSHKeyPair() {
16
+ const keys = ssh2_1.utils.generateKeyPairSync('ed25519');
17
+ return {
18
+ publicKey: keys.public.toString(),
19
+ privateKey: keys.private.toString()
20
+ };
21
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=swarm-to-k8s.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"swarm-to-k8s.d.ts","sourceRoot":"","sources":["../../src/environment/swarm-to-k8s.ts"],"names":[],"mappings":""}
@@ -0,0 +1,183 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || (function () {
29
+ var ownKeys = function(o) {
30
+ ownKeys = Object.getOwnPropertyNames || function (o) {
31
+ var ar = [];
32
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
+ return ar;
34
+ };
35
+ return ownKeys(o);
36
+ };
37
+ return function (mod) {
38
+ if (mod && mod.__esModule) return mod;
39
+ var result = {};
40
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
+ __setModuleDefault(result, mod);
42
+ return result;
43
+ };
44
+ })();
45
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
46
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
47
+ return new (P || (P = Promise))(function (resolve, reject) {
48
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
49
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
50
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
51
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
52
+ });
53
+ };
54
+ var __importDefault = (this && this.__importDefault) || function (mod) {
55
+ return (mod && mod.__esModule) ? mod : { "default": mod };
56
+ };
57
+ Object.defineProperty(exports, "__esModule", { value: true });
58
+ const path = __importStar(require("path"));
59
+ /* eslint-disable no-console */
60
+ const kleur_1 = __importDefault(require("kleur"));
61
+ const logger_1 = require("./logger");
62
+ const utils_1 = require("./utils");
63
+ const templates_1 = require("./templates");
64
+ const core_1 = require("@octokit/core");
65
+ const ssh_keygen_1 = require("./ssh-keygen");
66
+ const github_1 = require("./github");
67
+ (() => __awaiter(void 0, void 0, void 0, function* () {
68
+ (0, logger_1.log)(kleur_1.default.bold('------------------------------------------------\n' +
69
+ 'OpenCRVS Infrastructure migration script: \n' +
70
+ 'Migrating Swarm configurations to Kubernetes\n' +
71
+ '------------------------------------------------\n'));
72
+ const environment_type = process.env.ENVIRONMENT_TYPE || 'production';
73
+ const environment = process.env.ENVIRONMENT || '';
74
+ const githubToken = process.env.INFRA_TOKEN || '';
75
+ const githubOrganisation = process.env.INFRA_ORGANISATION || '';
76
+ const githubRepository = process.env.INFRA_REPOSITORY || '';
77
+ if (!environment) {
78
+ (0, logger_1.error)('\n', 'Environment variable ENVIRONMENT is not set. Exiting.');
79
+ process.exit(1);
80
+ }
81
+ if (!githubToken) {
82
+ (0, logger_1.error)('\n', 'Environment variable GITHUB_TOKEN is not set. Exiting.');
83
+ process.exit(1);
84
+ }
85
+ if (!githubOrganisation) {
86
+ (0, logger_1.error)('\n', 'Environment variable INFRA_ORGANISATION is not set. Exiting.');
87
+ process.exit(1);
88
+ }
89
+ if (!githubRepository) {
90
+ (0, logger_1.error)('\n', 'Environment variable INFRA_REPOSITORY is not set. Exiting.');
91
+ process.exit(1);
92
+ }
93
+ if (['backup', 'jumpbox'].includes(environment)) {
94
+ (0, logger_1.info)(` > ${environment} environment will not be migrated, see migration notes`);
95
+ process.exit(0);
96
+ }
97
+ (0, logger_1.log)(kleur_1.default.bold().underline('Migration properties:'));
98
+ (0, logger_1.log)(` ✓ Environment: ${environment}`);
99
+ const old_inventory_path = process.env.OLD_INVENTORY_PATH || '';
100
+ if (!old_inventory_path) {
101
+ (0, logger_1.error)('\n', 'Environment variable OLD_INVENTORY_PATH is not set. Exiting.');
102
+ (0, logger_1.log)('\n', 'Old inventory path is required to read existing Swarm configurations.');
103
+ process.exit(1);
104
+ }
105
+ const ansible_inventory = path.join(old_inventory_path, environment + '.yml');
106
+ const data = (0, utils_1.readYamlFile)(ansible_inventory);
107
+ (0, logger_1.log)(` ✓ Loaded old inventory file: ${ansible_inventory}`);
108
+ const master = (0, templates_1.dockerManagerFirst)(data) || '';
109
+ (0, logger_1.log)(` ✓ Kubernetes API Host (Docker Manager): ${master}`);
110
+ const users = (0, templates_1.extractAndModifyUsers)(data);
111
+ const kube_worker_nodes = (0, templates_1.extractWorkerNodes)(data);
112
+ (0, logger_1.log)(` ✓ Worker nodes: ${kube_worker_nodes.join(', ')}`);
113
+ const backup_host = (0, templates_1.extractBackupNode)(data);
114
+ (0, logger_1.log)(` ✓ Backup host: ${backup_host}`);
115
+ (0, templates_1.generateInventory)(environment, {
116
+ kube_worker_nodes: kube_worker_nodes,
117
+ users: users,
118
+ backup_host: environment === 'production' ? backup_host : '',
119
+ kube_api_host: master
120
+ });
121
+ (0, templates_1.copyChartsValues)(environment, {
122
+ env: environment,
123
+ environment_type: environment_type,
124
+ // FIXME: In general that should be environment_type,
125
+ // Hardcode like this blocks us from being generic:
126
+ // https://github.com/opencrvs/opencrvs-core/issues/11171
127
+ two_fa_enabled: environment !== 'production' ? false : true,
128
+ backup_enabled: environment === 'production' ? 'true' : 'false',
129
+ restore_enabled: environment === 'staging' ? 'true' : 'false',
130
+ restore_environment_name: environment === 'staging' ? 'production' : '',
131
+ restore_type: 'dump',
132
+ traefik_mode: 'static_ssl',
133
+ backup_type: 'dump'
134
+ });
135
+ if (environment === 'staging') {
136
+ const octokit = new core_1.Octokit({
137
+ auth: githubToken
138
+ });
139
+ const repositoryId = yield (0, github_1.getRepositoryId)(octokit, githubOrganisation, githubRepository);
140
+ try {
141
+ yield (0, github_1.createEnvironmentVariable)(octokit, repositoryId, environment, 'RESTORE_ENVIRONMENT_NAME', 'production');
142
+ }
143
+ catch (err) {
144
+ (0, logger_1.error)(`Failed to create variable RESTORE_ENVIRONMENT_NAME for environment ${environment}:`, err);
145
+ }
146
+ }
147
+ if (environment === 'production') {
148
+ const octokit = new core_1.Octokit({
149
+ auth: githubToken
150
+ });
151
+ console.log('Fetching repository ID for:', githubOrganisation, githubRepository);
152
+ const repositoryId = yield (0, github_1.getRepositoryId)(octokit, githubOrganisation, githubRepository);
153
+ console.log('Repository ID:', repositoryId);
154
+ const { publicKey, privateKey } = (0, ssh_keygen_1.generateSSHKeyPair)();
155
+ const secretsToCreate = {
156
+ BACKUP_HOST_PRIVATE_KEY: privateKey,
157
+ BACKUP_HOST_PUBLIC_KEY: publicKey,
158
+ BACKUP_SERVER_USER: 'backup'
159
+ };
160
+ const variablesToCreate = {
161
+ BACKUP_HOST: backup_host,
162
+ KUBE_WORKER_NODES: kube_worker_nodes.join(',')
163
+ };
164
+ for (const [secretName, secretValue] of Object.entries(secretsToCreate)) {
165
+ try {
166
+ yield (0, github_1.createEnvironmentSecret)(octokit, repositoryId, environment, secretName, secretValue, githubOrganisation, githubRepository);
167
+ (0, logger_1.log)(` ✓ Created secret ${secretName} for environment ${environment}`);
168
+ }
169
+ catch (err) {
170
+ (0, logger_1.error)(`Failed to create secret ${secretName} for environment ${environment}:`, err);
171
+ }
172
+ }
173
+ for (const [variableName, variableValue] of Object.entries(variablesToCreate)) {
174
+ try {
175
+ yield (0, github_1.createEnvironmentVariable)(octokit, repositoryId, environment, variableName, variableValue);
176
+ (0, logger_1.log)(` ✓ Created variable ${variableName} for environment ${environment}`);
177
+ }
178
+ catch (err) {
179
+ (0, logger_1.error)(`Failed to create variable ${variableName} for environment ${environment}:`, err);
180
+ }
181
+ }
182
+ }
183
+ }))();
@@ -0,0 +1,26 @@
1
+ export declare function extractAndModifyUsers(data: any): any;
2
+ export declare function dockerManagerFirst(data: any): string;
3
+ export declare function extractBackupNode(data: any): string;
4
+ export declare function extractWorkerNodes(data: any): string[];
5
+ /**
6
+ * Copy charts-values directory into environments/<env>
7
+ * @param env Environment name
8
+ * Usage: copyChartsValues('dev')
9
+ */
10
+ /**
11
+ * Recursively copy a directory and replace placeholders in text files.
12
+ */
13
+ export declare function copyChartsValues(env: string, values: Record<string, string | boolean>): void;
14
+ /**
15
+ * Generate Ansible inventory file from template
16
+ * @param env Environment name
17
+ * @param number_of_servers Number of servers (1 for single-node, >1 for multi-node)
18
+ * @param values Key-value pairs to replace in the template
19
+ * Usage: generateInventory('dev', 1, {
20
+ * HOST: process.env.APP_HOST || "localhost",
21
+ * USER: process.env.SSH_USER || "ubuntu",
22
+ * PORT: process.env.SSH_PORT || "22"
23
+ * });
24
+ */
25
+ export declare function generateInventory(env: string, values: Record<string, any>): void;
26
+ //# sourceMappingURL=templates.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../../src/environment/templates.ts"],"names":[],"mappings":"AA0BA,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,GAAG,GAAG,GAAG,CAepD;AAED,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM,CAWpD;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,CAC9B,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,QA0CzC;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,QAsBzE"}
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __rest = (this && this.__rest) || function (s, e) {
13
+ var t = {};
14
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
15
+ t[p] = s[p];
16
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
17
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
18
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
19
+ t[p[i]] = s[p[i]];
20
+ }
21
+ return t;
22
+ };
23
+ var __importDefault = (this && this.__importDefault) || function (mod) {
24
+ return (mod && mod.__esModule) ? mod : { "default": mod };
25
+ };
26
+ Object.defineProperty(exports, "__esModule", { value: true });
27
+ exports.extractAndModifyUsers = extractAndModifyUsers;
28
+ exports.dockerManagerFirst = dockerManagerFirst;
29
+ exports.extractBackupNode = extractBackupNode;
30
+ exports.extractWorkerNodes = extractWorkerNodes;
31
+ exports.copyChartsValues = copyChartsValues;
32
+ exports.generateInventory = generateInventory;
33
+ const fs_1 = __importDefault(require("fs"));
34
+ const path_1 = __importDefault(require("path"));
35
+ const logger_1 = require("./logger");
36
+ const paths_1 = require("./paths");
37
+ const handlebars_1 = __importDefault(require("handlebars"));
38
+ // Register a helper to increment numbers
39
+ handlebars_1.default.registerHelper('data_label_idx', function (value) {
40
+ return parseInt(value) + 2;
41
+ });
42
+ // START: TEMPORAL SECTION FOR TRANSITION FROM DOCKER SWARM TO K8s
43
+ // Extract users from the old inventory
44
+ // Docker swarm format to new
45
+ function extractAndModifyUsers(data) {
46
+ var _a, _b;
47
+ 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)) {
48
+ return { users: [] };
49
+ }
50
+ const users = data.all.vars.users.map((user) => {
51
+ if (user.role) {
52
+ return user;
53
+ }
54
+ const { sudoer } = user, rest = __rest(user, ["sudoer"]);
55
+ return Object.assign(Object.assign({}, rest), { role: sudoer ? 'admin' : 'operator' });
56
+ });
57
+ return users;
58
+ }
59
+ function dockerManagerFirst(data) {
60
+ var _a;
61
+ if (!((_a = data === null || data === void 0 ? void 0 : data['docker-manager-first']) === null || _a === void 0 ? void 0 : _a.hosts)) {
62
+ throw new Error('Invalid YAML structure: missing docker-manager-first.hosts');
63
+ }
64
+ const hosts = data['docker-manager-first'].hosts;
65
+ const dockerManagerFirst = Object.values(hosts)
66
+ .filter((host) => host.ansible_host)
67
+ .map((host) => host.ansible_host);
68
+ return dockerManagerFirst.length === 1 ? dockerManagerFirst[0] : '';
69
+ }
70
+ function extractBackupNode(data) {
71
+ var _a;
72
+ if (!((_a = data === null || data === void 0 ? void 0 : data['backups']) === null || _a === void 0 ? void 0 : _a.hosts)) {
73
+ return '';
74
+ }
75
+ const hosts = data['backups'].hosts;
76
+ const backupHostEntry = Object.values(hosts)
77
+ .filter((host) => host.ansible_host)
78
+ .map((host) => host.ansible_host);
79
+ return backupHostEntry.length === 1 ? backupHostEntry[0] : '';
80
+ }
81
+ function extractWorkerNodes(data) {
82
+ var _a;
83
+ if (!((_a = data === null || data === void 0 ? void 0 : data['docker-workers']) === null || _a === void 0 ? void 0 : _a.hosts)) {
84
+ return [];
85
+ }
86
+ const hosts = data['docker-workers'].hosts;
87
+ const worker_hosts = Object.values(hosts)
88
+ .filter((host) => host.ansible_host)
89
+ .map((host) => host.ansible_host);
90
+ return worker_hosts;
91
+ }
92
+ // END: TEMPORAL SECTION FOR TRANSITION FROM DOCKER SWARM TO K8s
93
+ /**
94
+ * Copy charts-values directory into environments/<env>
95
+ * @param env Environment name
96
+ * Usage: copyChartsValues('dev')
97
+ */
98
+ /**
99
+ * Recursively copy a directory and replace placeholders in text files.
100
+ */
101
+ function copyChartsValues(env, values) {
102
+ const srcDir = path_1.default.resolve(__dirname, 'templates', 'charts-values');
103
+ const destDir = path_1.default.resolve(process.cwd(), 'environments', env);
104
+ fs_1.default.mkdirSync(destDir, { recursive: true });
105
+ values['lets_encrypt'] = values['traefik_mode'] === 'lets_encrypt';
106
+ values['static_ssl'] = values['traefik_mode'] === 'static_ssl';
107
+ values['opencrvs_environment'] = env;
108
+ function copyRecursive(src, dest) {
109
+ const stat = fs_1.default.statSync(src);
110
+ if (stat.isDirectory()) {
111
+ fs_1.default.mkdirSync(dest, { recursive: true });
112
+ for (const item of fs_1.default.readdirSync(src)) {
113
+ copyRecursive(path_1.default.join(src, item), path_1.default.join(dest, item));
114
+ }
115
+ }
116
+ else {
117
+ const content = fs_1.default.readFileSync(src, 'utf8');
118
+ const template = handlebars_1.default.compile(content);
119
+ const updated = template(values);
120
+ const isOverridesFile = dest.endsWith('override.yaml');
121
+ // Skip overwrite for existing overrides.yaml
122
+ if (isOverridesFile && fs_1.default.existsSync(dest)) {
123
+ (0, logger_1.log)(` ↷ Skipped existing overrides file: ${dest}`);
124
+ return;
125
+ }
126
+ fs_1.default.writeFileSync(dest, updated, 'utf8');
127
+ (0, logger_1.log)(` ✓ Created: ${dest}`);
128
+ }
129
+ }
130
+ (0, logger_1.log)(`\n📋 Copying charts-values templates to ${destDir}:`);
131
+ copyRecursive(srcDir, destDir);
132
+ (0, logger_1.success)(`✅ Completed copying charts-values.\n`);
133
+ }
134
+ /**
135
+ * Generate Ansible inventory file from template
136
+ * @param env Environment name
137
+ * @param number_of_servers Number of servers (1 for single-node, >1 for multi-node)
138
+ * @param values Key-value pairs to replace in the template
139
+ * Usage: generateInventory('dev', 1, {
140
+ * HOST: process.env.APP_HOST || "localhost",
141
+ * USER: process.env.SSH_USER || "ubuntu",
142
+ * PORT: process.env.SSH_PORT || "22"
143
+ * });
144
+ */
145
+ function generateInventory(env, values) {
146
+ // Template and output paths
147
+ const templatePath = path_1.default.join(__dirname, 'templates', 'inventory', 'inventory.template.yml');
148
+ const outputPath = path_1.default.resolve(process.cwd(), (0, paths_1.getEnvironmentInventoryPath)(env));
149
+ const templateFile = fs_1.default.readFileSync(templatePath, 'utf-8');
150
+ const template = handlebars_1.default.compile(templateFile);
151
+ values['single_node'] =
152
+ values['kube_worker_nodes'].length > 0 || values['backup_host']
153
+ ? 'false'
154
+ : 'true';
155
+ const updated = template(values);
156
+ fs_1.default.mkdirSync(path_1.default.dirname(outputPath), { recursive: true });
157
+ fs_1.default.writeFileSync(outputPath, updated);
158
+ (0, logger_1.log)(`\n✅ Generated inventory file at ${outputPath}\n`);
159
+ }
@@ -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":"AAmIA,wBAAsB,0BAA0B,IAAI,OAAO,CAAC,IAAI,CAAC,CAgDhE"}
@@ -0,0 +1,195 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || (function () {
29
+ var ownKeys = function(o) {
30
+ ownKeys = Object.getOwnPropertyNames || function (o) {
31
+ var ar = [];
32
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
33
+ return ar;
34
+ };
35
+ return ownKeys(o);
36
+ };
37
+ return function (mod) {
38
+ if (mod && mod.__esModule) return mod;
39
+ var result = {};
40
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
41
+ __setModuleDefault(result, mod);
42
+ return result;
43
+ };
44
+ })();
45
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
46
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
47
+ return new (P || (P = Promise))(function (resolve, reject) {
48
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
49
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
50
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
51
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
52
+ });
53
+ };
54
+ Object.defineProperty(exports, "__esModule", { value: true });
55
+ exports.updateWorkflowEnvironments = updateWorkflowEnvironments;
56
+ const promises_1 = require("fs/promises");
57
+ /* eslint-disable no-console */
58
+ const fs_1 = require("fs");
59
+ const path_1 = require("path");
60
+ const glob = __importStar(require("glob"));
61
+ const yaml = __importStar(require("js-yaml"));
62
+ const logger_1 = require("./logger");
63
+ const paths_1 = require("./paths");
64
+ function isDirectory(path) {
65
+ try {
66
+ return (0, fs_1.statSync)(path).isDirectory();
67
+ }
68
+ catch (_a) {
69
+ return false;
70
+ }
71
+ }
72
+ function extractInfrastructureNames() {
73
+ return __awaiter(this, void 0, void 0, function* () {
74
+ const files = glob.sync((0, path_1.join)('environments', '*', paths_1.INVENTORY_FILE_NAME));
75
+ const infraEnvironments = files.map((file) => (0, path_1.basename)((0, path_1.dirname)(file)));
76
+ if (infraEnvironments.length === 0) {
77
+ console.log(`⚠️ Warning: No environment inventory files found at environments/*/${paths_1.INVENTORY_FILE_NAME}`);
78
+ return [];
79
+ }
80
+ (0, logger_1.log)('🔍 Found infrastructure configurations:', infraEnvironments.join(', '));
81
+ return infraEnvironments;
82
+ });
83
+ }
84
+ function extractEnvironmentNames() {
85
+ return __awaiter(this, void 0, void 0, function* () {
86
+ const entries = yield (0, promises_1.readdir)('environments');
87
+ // Filter only directories
88
+ const environments = entries.filter((entry) => {
89
+ const environmentPath = (0, path_1.join)('environments', entry);
90
+ const opencrvsServicesPath = (0, path_1.join)(environmentPath, 'opencrvs-services');
91
+ return (isDirectory(environmentPath) &&
92
+ (0, fs_1.existsSync)(opencrvsServicesPath) &&
93
+ isDirectory(opencrvsServicesPath));
94
+ });
95
+ if (environments.length === 0) {
96
+ console.log('⚠️ Warning: No environment directories found in environments/');
97
+ return [];
98
+ }
99
+ (0, logger_1.log)('🔍 Found OpenCRVS configurations:', environments.join(', '));
100
+ return environments;
101
+ });
102
+ }
103
+ function updateOptionsInYaml(content, envList) {
104
+ // Find the options array pattern
105
+ // Matches: options: followed by array items (- item)
106
+ const optionsRegex = /([ ]*options:[ ]*\n)((?:[ ]*-[^\n]*\n)+)/;
107
+ const match = content.match(optionsRegex);
108
+ if (!match) {
109
+ throw new Error('Could not find options array in workflow file');
110
+ }
111
+ // Get the indentation from the first array item
112
+ const firstItemMatch = match[2].match(/^([ ]*)-/);
113
+ const itemIndent = firstItemMatch ? firstItemMatch[1] : ' ';
114
+ // Create new options array
115
+ const newOptions = match[1] + envList.map((env) => `${itemIndent}- ${env}`).join('\n') + '\n';
116
+ // Replace the old options array with the new one
117
+ return content.replace(optionsRegex, newOptions);
118
+ }
119
+ function updateWorkflows(envList, config) {
120
+ return __awaiter(this, void 0, void 0, function* () {
121
+ var _a, _b, _c, _d;
122
+ const { workflows } = config;
123
+ for (const workflowPath of workflows) {
124
+ if (!(0, fs_1.existsSync)(workflowPath)) {
125
+ (0, logger_1.log)(` ↷ Skipped ${workflowPath} (not found in this repository)`);
126
+ continue;
127
+ }
128
+ try {
129
+ const fileContents = (0, fs_1.readFileSync)(workflowPath, 'utf8');
130
+ // Verify the file is valid YAML and has the expected structure
131
+ const workflowData = yaml.load(fileContents);
132
+ 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)) {
133
+ throw new Error('Workflow does not have the expected structure: on.workflow_dispatch.inputs.environment.options');
134
+ }
135
+ // Update only the options array while preserving everything else
136
+ const updatedContent = updateOptionsInYaml(fileContents, envList);
137
+ (0, fs_1.writeFileSync)(workflowPath, updatedContent, 'utf8');
138
+ (0, logger_1.log)(` ✓ Successfully updated ${workflowPath}`);
139
+ }
140
+ catch (error) {
141
+ console.error(`\n⚠️ Error updating ${workflowPath} with environments: [${envList.join(', ')}]`);
142
+ console.error(`✗ Failed to update ${workflowPath}:`, error);
143
+ throw error;
144
+ }
145
+ }
146
+ });
147
+ }
148
+ function updateWorkflowEnvironments() {
149
+ return __awaiter(this, void 0, void 0, function* () {
150
+ try {
151
+ let didUpdateWorkflows = false;
152
+ // Extract infrastructure names
153
+ const infraEnvironments = yield extractInfrastructureNames();
154
+ if (infraEnvironments.length > 0) {
155
+ console.log('🔄 Updating infrastructure workflows:');
156
+ yield updateWorkflows(infraEnvironments, {
157
+ workflows: [
158
+ '.github/workflows/provision.yml',
159
+ '.github/workflows/reset-2fa.yml'
160
+ ],
161
+ path: 'on.workflow_dispatch.inputs.environment.options'
162
+ });
163
+ didUpdateWorkflows = true;
164
+ }
165
+ // Extract environment names (only directories)
166
+ const environments = yield extractEnvironmentNames();
167
+ if (environments.length > 0) {
168
+ const workflows = [
169
+ '.github/workflows/deploy-dependencies.yml',
170
+ '.github/workflows/deploy-opencrvs.yml',
171
+ '.github/workflows/clear-all-data.yml',
172
+ '.github/workflows/seed-data.yml',
173
+ '.github/workflows/reindex.yml',
174
+ '.github/workflows/github-to-k8s-sync-env.yml'
175
+ ];
176
+ (0, logger_1.log)('📋 Updating OpenCRVS application workflows:');
177
+ yield updateWorkflows(environments, {
178
+ workflows,
179
+ path: 'on.workflow_dispatch.inputs.environment.options'
180
+ });
181
+ didUpdateWorkflows = true;
182
+ }
183
+ if (didUpdateWorkflows) {
184
+ (0, logger_1.success)('✅ Workflow updates completed successfully!');
185
+ }
186
+ else {
187
+ (0, logger_1.log)('ℹ️ No workflows were updated.');
188
+ }
189
+ }
190
+ catch (error) {
191
+ console.error('\n❌ Error updating workflows:', error);
192
+ process.exit(1);
193
+ }
194
+ });
195
+ }
@@ -0,0 +1,2 @@
1
+ export declare function upgradeEnvironmentLayout(): Promise<void>;
2
+ //# sourceMappingURL=upgrade.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"upgrade.d.ts","sourceRoot":"","sources":["../../src/environment/upgrade.ts"],"names":[],"mappings":"AAkFA,wBAAsB,wBAAwB,kBAY7C"}