@opencrvs/toolkit 2.0.0-rc.f3bc98a → 2.0.0-rc.f45dbb8

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 (126) hide show
  1. package/README.md +15 -0
  2. package/build.sh +3 -2
  3. package/create-countryconfig/index.js +103 -0
  4. package/create-countryconfig/package.json +21 -0
  5. package/dist/application-config/index.js +291 -126
  6. package/dist/cli.js +3759 -211
  7. package/dist/commons/api/router.d.ts +3387 -237
  8. package/dist/commons/application-config/index.d.ts +1 -0
  9. package/dist/commons/conditionals/conditionals.d.ts +360 -10
  10. package/dist/commons/conditionals/validate.d.ts +52 -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 +114 -0
  14. package/dist/commons/events/AdvancedSearchConfig.d.ts +354 -0
  15. package/dist/commons/events/CountryConfigQueryInput.d.ts +42 -0
  16. package/dist/commons/events/Draft.d.ts +4 -2
  17. package/dist/commons/events/EventConfig.d.ts +2 -0
  18. package/dist/commons/events/EventDocument.d.ts +3 -0
  19. package/dist/commons/events/EventIndex.d.ts +25 -3
  20. package/dist/commons/events/EventMetadata.d.ts +26 -7
  21. package/dist/commons/events/FieldConfig.d.ts +393 -50
  22. package/dist/commons/events/FieldType.d.ts +1 -0
  23. package/dist/commons/events/FieldTypeMapping.d.ts +1 -1
  24. package/dist/commons/events/FieldValue.d.ts +6 -0
  25. package/dist/commons/events/WorkqueueConfig.d.ts +189 -150
  26. package/dist/commons/events/field.d.ts +53 -1
  27. package/dist/commons/events/index.d.ts +2 -0
  28. package/dist/commons/events/locations.d.ts +22 -0
  29. package/dist/commons/events/mocks.test.utils.d.ts +19 -0
  30. package/dist/commons/events/scopes.d.ts +24 -1
  31. package/dist/commons/events/state/flags.d.ts +16 -0
  32. package/dist/commons/events/state/index.d.ts +8 -4
  33. package/dist/commons/events/state/utils.d.ts +21 -289
  34. package/dist/commons/events/utils.d.ts +13 -2
  35. package/dist/conditionals/index.js +68 -8
  36. package/dist/environment/custom-types.d.ts +33 -0
  37. package/dist/environment/custom-types.d.ts.map +1 -0
  38. package/dist/environment/custom-types.js +12 -0
  39. package/dist/environment/derived-variables.d.ts +134 -0
  40. package/dist/environment/derived-variables.d.ts.map +1 -0
  41. package/dist/environment/derived-variables.js +169 -0
  42. package/dist/environment/editor-questions.d.ts +4 -0
  43. package/dist/environment/editor-questions.d.ts.map +1 -0
  44. package/dist/environment/editor-questions.js +67 -0
  45. package/dist/environment/git.d.ts +5 -0
  46. package/dist/environment/git.d.ts.map +1 -0
  47. package/dist/environment/git.js +38 -0
  48. package/dist/environment/github.d.ts +26 -0
  49. package/dist/environment/github.d.ts.map +1 -0
  50. package/dist/environment/github.js +247 -0
  51. package/dist/environment/index.d.ts +5 -0
  52. package/dist/environment/index.d.ts.map +1 -0
  53. package/dist/environment/index.js +71 -0
  54. package/dist/environment/logger.d.ts +15 -0
  55. package/dist/environment/logger.d.ts.map +1 -0
  56. package/dist/environment/logger.js +25 -0
  57. package/dist/environment/manage-users.d.ts +11 -0
  58. package/dist/environment/manage-users.d.ts.map +1 -0
  59. package/dist/environment/manage-users.js +497 -0
  60. package/dist/environment/questions-helper.d.ts +15 -0
  61. package/dist/environment/questions-helper.d.ts.map +1 -0
  62. package/dist/environment/questions-helper.js +70 -0
  63. package/dist/environment/questions.d.ts +199 -0
  64. package/dist/environment/questions.d.ts.map +1 -0
  65. package/dist/environment/questions.js +412 -0
  66. package/dist/environment/setup-environment.d.ts +2 -0
  67. package/dist/environment/setup-environment.d.ts.map +1 -0
  68. package/dist/environment/setup-environment.js +794 -0
  69. package/dist/environment/ssh-keygen.d.ts +5 -0
  70. package/dist/environment/ssh-keygen.d.ts.map +1 -0
  71. package/dist/environment/ssh-keygen.js +21 -0
  72. package/dist/environment/swarm-to-k8s.d.ts +2 -0
  73. package/dist/environment/swarm-to-k8s.d.ts.map +1 -0
  74. package/dist/environment/swarm-to-k8s.js +173 -0
  75. package/dist/environment/templates.d.ts +27 -0
  76. package/dist/environment/templates.d.ts.map +1 -0
  77. package/dist/environment/templates.js +163 -0
  78. package/dist/environment/update-workflows.d.ts +2 -0
  79. package/dist/environment/update-workflows.d.ts.map +1 -0
  80. package/dist/environment/update-workflows.js +169 -0
  81. package/dist/environment/users.d.ts +2 -0
  82. package/dist/environment/users.d.ts.map +1 -0
  83. package/dist/environment/users.js +112 -0
  84. package/dist/environment/utils.d.ts +18 -0
  85. package/dist/environment/utils.d.ts.map +1 -0
  86. package/dist/environment/utils.js +100 -0
  87. package/dist/events/index.js +1173 -291
  88. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +1 -1
  89. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +60 -35
  90. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +1 -1
  91. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  92. package/dist/migrations/v2.0/checkout-upstream-files.js +1 -2
  93. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +9 -1
  94. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +1 -1
  95. package/dist/migrations/v2.0/delete-infrastructure-directory.js +66 -20
  96. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +3 -0
  97. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +1 -0
  98. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +110 -0
  99. package/dist/migrations/v2.0/index.d.ts +5 -3
  100. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  101. package/dist/migrations/v2.0/index.js +522 -175
  102. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +1 -1
  103. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +90 -1
  104. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +11 -1
  105. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +1 -1
  106. package/dist/migrations/v2.0/merge-infrastructure-directory.js +17 -16
  107. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -1
  108. package/dist/migrations/v2.0/migrate-scopes.js +54 -30
  109. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -1
  110. package/dist/migrations/v2.0/migrate-workqueue-configs.js +140 -59
  111. package/dist/notification/index.js +919 -162
  112. package/dist/scopes/index.d.ts +99 -8
  113. package/dist/scopes/index.js +25 -10
  114. package/dist/templates/charts-values/dependencies/values.override.yaml +4 -0
  115. package/dist/templates/charts-values/dependencies/values.yaml +83 -0
  116. package/dist/templates/charts-values/opencrvs-services/values.override.yaml +4 -0
  117. package/dist/templates/charts-values/opencrvs-services/values.yaml +81 -0
  118. package/dist/templates/charts-values/traefik/values.override.yaml +4 -0
  119. package/dist/templates/charts-values/traefik/values.yaml +115 -0
  120. package/dist/templates/inventory/inventory.template.yml +100 -0
  121. package/dist/templates/inventory/production.example.yml +77 -0
  122. package/dist/templates/inventory/qa.example.yml +48 -0
  123. package/opencrvs-toolkit-2.0.0-rc.f45dbb8.tgz +0 -0
  124. package/package.json +20 -2
  125. package/tsconfig.tsbuildinfo +1 -1
  126. package/opencrvs-toolkit-2.0.0-rc.f3bc98a.tgz +0 -0
package/dist/cli.js CHANGED
@@ -6,22 +6,3157 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
6
  var __getOwnPropNames = Object.getOwnPropertyNames;
7
7
  var __getProtoOf = Object.getPrototypeOf;
8
8
  var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __esm = (fn, res) => function __init() {
10
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
+ };
12
+ var __export = (target, all) => {
13
+ for (var name in all)
14
+ __defProp(target, name, { get: all[name], enumerable: true });
15
+ };
9
16
  var __copyProps = (to, from, except, desc) => {
10
17
  if (from && typeof from === "object" || typeof from === "function") {
11
18
  for (let key of __getOwnPropNames(from))
12
19
  if (!__hasOwnProp.call(to, key) && key !== except)
13
20
  __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
14
21
  }
15
- return to;
16
- };
17
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
18
- // If the importer is in node compatibility mode or this is not an ESM
19
- // file that has been converted to a CommonJS file using a Babel-
20
- // compatible transform (i.e. "__esModule" has not been set), then set
21
- // "default" to the CommonJS "module.exports" for node compatibility.
22
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
23
- mod
24
- ));
22
+ return to;
23
+ };
24
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
+ // If the importer is in node compatibility mode or this is not an ESM
26
+ // file that has been converted to a CommonJS file using a Babel-
27
+ // compatible transform (i.e. "__esModule" has not been set), then set
28
+ // "default" to the CommonJS "module.exports" for node compatibility.
29
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
+ mod
31
+ ));
32
+
33
+ // src/environment/logger.ts
34
+ var import_kleur, log, warn, success, info, error;
35
+ var init_logger = __esm({
36
+ "src/environment/logger.ts"() {
37
+ "use strict";
38
+ import_kleur = __toESM(require("kleur"));
39
+ log = console.log;
40
+ warn = console.warn;
41
+ success = (...args2) => console.log(import_kleur.default.green(args2.join(" ")));
42
+ info = console.info;
43
+ error = (...args2) => console.log(import_kleur.default.red(args2.join(" ")));
44
+ }
45
+ });
46
+
47
+ // src/environment/github.ts
48
+ async function createEnvironmentVariable(octokit, repositoryId, environment, name, value) {
49
+ await octokit.request(
50
+ `POST /repositories/${repositoryId}/environments/${environment}/variables`,
51
+ {
52
+ repository_id: repositoryId,
53
+ environment_name: environment,
54
+ name,
55
+ value,
56
+ headers: {
57
+ "X-GitHub-Api-Version": "2022-11-28"
58
+ }
59
+ }
60
+ );
61
+ }
62
+ async function updateEnvironmentVariable(octokit, repositoryId, environment, name, value) {
63
+ await octokit.request(
64
+ `PATCH /repositories/${repositoryId}/environments/${environment}/variables/${name}`,
65
+ {
66
+ repository_id: repositoryId,
67
+ environment_name: environment,
68
+ name,
69
+ value,
70
+ headers: {
71
+ "X-GitHub-Api-Version": "2022-11-28"
72
+ }
73
+ }
74
+ );
75
+ }
76
+ async function createRepositoryVariable(octokit, repositoryId, name, value) {
77
+ await octokit.request(
78
+ `POST /repositories/${repositoryId}/actions/variables`,
79
+ {
80
+ repository_id: repositoryId,
81
+ name,
82
+ value,
83
+ headers: {
84
+ "X-GitHub-Api-Version": "2022-11-28"
85
+ }
86
+ }
87
+ );
88
+ }
89
+ async function updateRepositoryVariable(octokit, repositoryId, name, value) {
90
+ await octokit.request(
91
+ `PATCH /repositories/${repositoryId}/actions/variables/${name}`,
92
+ {
93
+ repository_id: repositoryId,
94
+ name,
95
+ value,
96
+ headers: {
97
+ "X-GitHub-Api-Version": "2022-11-28"
98
+ }
99
+ }
100
+ );
101
+ }
102
+ async function getRepositoryId(octokit, owner, repo) {
103
+ const response = await octokit.request("GET /repos/{owner}/{repo}", {
104
+ owner,
105
+ repo
106
+ });
107
+ return response.data.id;
108
+ }
109
+ async function getRepositoryPublicKey(octokit, owner, repo) {
110
+ const res = await octokit.request(
111
+ "GET /repos/{owner}/{repo}/actions/secrets/public-key",
112
+ {
113
+ owner,
114
+ repo
115
+ }
116
+ );
117
+ return res.data;
118
+ }
119
+ async function getPublicKey(octokit, environment, ORGANISATION, REPOSITORY_NAME) {
120
+ const repositoryId = await getRepositoryId(
121
+ octokit,
122
+ ORGANISATION,
123
+ REPOSITORY_NAME
124
+ );
125
+ await octokit.request(
126
+ `PUT /repos/${ORGANISATION}/${REPOSITORY_NAME}/environments/${environment}`,
127
+ {
128
+ headers: {
129
+ "X-GitHub-Api-Version": "2022-11-28"
130
+ }
131
+ }
132
+ );
133
+ const res = await octokit.request(
134
+ `GET /repositories/${repositoryId}/environments/${environment}/secrets/public-key`,
135
+ {
136
+ owner: ORGANISATION,
137
+ repo: REPOSITORY_NAME,
138
+ headers: {
139
+ "X-GitHub-Api-Version": "2022-11-28"
140
+ }
141
+ }
142
+ );
143
+ return res.data;
144
+ }
145
+ async function createEnvironmentSecret(octokit, repositoryId, environment, name, secret, organisationName, repositoryName) {
146
+ await import_libsodium_wrappers.default.ready;
147
+ const { key, key_id } = await getPublicKey(
148
+ octokit,
149
+ environment,
150
+ organisationName,
151
+ repositoryName
152
+ );
153
+ const binkey = import_libsodium_wrappers.default.from_base64(key, import_libsodium_wrappers.default.base64_variants.ORIGINAL);
154
+ const binsec = import_libsodium_wrappers.default.from_string(secret);
155
+ const encBytes = import_libsodium_wrappers.default.crypto_box_seal(binsec, binkey);
156
+ const encryptedValue = import_libsodium_wrappers.default.to_base64(
157
+ encBytes,
158
+ import_libsodium_wrappers.default.base64_variants.ORIGINAL
159
+ );
160
+ await octokit.request(
161
+ `PUT /repositories/${repositoryId}/environments/${environment}/secrets/${name}`,
162
+ {
163
+ repository_id: repositoryId,
164
+ environment_name: environment,
165
+ secret_name: name,
166
+ encrypted_value: encryptedValue,
167
+ key_id,
168
+ headers: {
169
+ "X-GitHub-Api-Version": "2022-11-28"
170
+ }
171
+ }
172
+ );
173
+ }
174
+ async function createRepositorySecret(octokit, repositoryId, name, secret, organisationName, repositoryName) {
175
+ await import_libsodium_wrappers.default.ready;
176
+ const { key, key_id } = await getRepositoryPublicKey(
177
+ octokit,
178
+ organisationName,
179
+ repositoryName
180
+ );
181
+ const binkey = import_libsodium_wrappers.default.from_base64(key, import_libsodium_wrappers.default.base64_variants.ORIGINAL);
182
+ const binsec = import_libsodium_wrappers.default.from_string(secret);
183
+ const encBytes = import_libsodium_wrappers.default.crypto_box_seal(binsec, binkey);
184
+ const encryptedValue = import_libsodium_wrappers.default.to_base64(
185
+ encBytes,
186
+ import_libsodium_wrappers.default.base64_variants.ORIGINAL
187
+ );
188
+ await octokit.request(
189
+ `PUT /repositories/${repositoryId}/actions/secrets/${name}`,
190
+ {
191
+ encrypted_value: encryptedValue,
192
+ key_id,
193
+ headers: {
194
+ "X-GitHub-Api-Version": "2022-11-28"
195
+ }
196
+ }
197
+ );
198
+ }
199
+ async function getRepositoryEnvironments(octokit, githubOrganisation, repository) {
200
+ const response = await octokit.request(
201
+ "GET /repos/{githubOrganisation}/{repository}/environments",
202
+ {
203
+ githubOrganisation,
204
+ repository
205
+ }
206
+ );
207
+ const environments = (response.data.environments ?? []).map(
208
+ (env) => env.name
209
+ );
210
+ return environments;
211
+ }
212
+ async function createEnvironment(octokit, environment, ORGANISATION, REPOSITORY_NAME) {
213
+ try {
214
+ await octokit.request(
215
+ `PUT /repos/${ORGANISATION}/${REPOSITORY_NAME}/environments/${environment}`,
216
+ {
217
+ headers: {
218
+ "X-GitHub-Api-Version": "2022-11-28"
219
+ }
220
+ }
221
+ );
222
+ return true;
223
+ } catch (err) {
224
+ error(
225
+ `Cannot create environment: [${err.status}] ${err.response?.data?.message}`
226
+ );
227
+ throw new Error(
228
+ `Cannot create environment: [${err.status}] ${err.response?.data?.message}`
229
+ );
230
+ }
231
+ }
232
+ async function listEnvironmentSecrets(octokit, owner, repositoryId, environmentName) {
233
+ const response = await octokit.request(
234
+ "GET /repositories/{repository_id}/environments/{environment_name}/secrets",
235
+ {
236
+ owner,
237
+ repository_id: repositoryId,
238
+ environment_name: environmentName,
239
+ per_page: 100
240
+ }
241
+ );
242
+ return response.data.secrets.map((secret) => ({
243
+ ...secret,
244
+ type: "SECRET",
245
+ scope: "ENVIRONMENT"
246
+ }));
247
+ }
248
+ async function listRepositorySecrets(octokit, owner, repositoryName) {
249
+ const response = await octokit.request(
250
+ "GET /repos/{owner}/{repo}/actions/secrets",
251
+ {
252
+ owner,
253
+ repo: repositoryName,
254
+ per_page: 100
255
+ }
256
+ );
257
+ return response.data.secrets.map((secret) => ({
258
+ ...secret,
259
+ type: "SECRET",
260
+ scope: "REPOSITORY"
261
+ }));
262
+ }
263
+ async function listEnvironmentVariables(octokit, repositoryId, environmentName) {
264
+ const response = await octokit.request(
265
+ "GET /repositories/{repository_id}/environments/{environment_name}/variables",
266
+ {
267
+ repository_id: repositoryId,
268
+ environment_name: environmentName,
269
+ per_page: 100,
270
+ headers: {
271
+ "X-GitHub-Api-Version": "2022-11-28"
272
+ }
273
+ }
274
+ );
275
+ return response.data.variables.map((variable) => ({
276
+ ...variable,
277
+ type: "VARIABLE",
278
+ scope: "ENVIRONMENT"
279
+ })).filter(
280
+ (variable) => variable.name !== "ACTIONS_RUNNER_DEBUG"
281
+ );
282
+ }
283
+ async function listRepositoryVariables(octokit, owner, repositoryName) {
284
+ const response = await octokit.request(
285
+ "GET /repos/{owner}/{repo}/actions/variables",
286
+ {
287
+ owner,
288
+ repo: repositoryName,
289
+ per_page: 100
290
+ }
291
+ );
292
+ return response.data.variables.map((variable) => ({
293
+ ...variable,
294
+ type: "VARIABLE",
295
+ scope: "REPOSITORY"
296
+ }));
297
+ }
298
+ var import_libsodium_wrappers;
299
+ var init_github = __esm({
300
+ "src/environment/github.ts"() {
301
+ "use strict";
302
+ import_libsodium_wrappers = __toESM(require("libsodium-wrappers"));
303
+ init_logger();
304
+ }
305
+ });
306
+
307
+ // src/environment/derived-variables.ts
308
+ var derivedVariables;
309
+ var init_derived_variables = __esm({
310
+ "src/environment/derived-variables.ts"() {
311
+ "use strict";
312
+ derivedVariables = [
313
+ {
314
+ name: "ACTIVATE_USERS",
315
+ valueLabel: "ACTIVATE_USERS",
316
+ valueType: "VARIABLE",
317
+ type: "disabled",
318
+ scope: "ENVIRONMENT"
319
+ },
320
+ {
321
+ name: "COUNTRY_CONFIG_HOST",
322
+ valueLabel: "COUNTRY_CONFIG_HOST",
323
+ valueType: "VARIABLE",
324
+ type: "disabled",
325
+ scope: "ENVIRONMENT"
326
+ },
327
+ {
328
+ name: "GATEWAY_HOST",
329
+ valueLabel: "GATEWAY_HOST",
330
+ valueType: "VARIABLE",
331
+ type: "disabled",
332
+ scope: "ENVIRONMENT"
333
+ },
334
+ {
335
+ name: "CONTENT_SECURITY_POLICY_WILDCARD",
336
+ valueLabel: "CONTENT_SECURITY_POLICY_WILDCARD",
337
+ valueType: "VARIABLE",
338
+ type: "disabled",
339
+ scope: "ENVIRONMENT"
340
+ },
341
+ {
342
+ name: "CLIENT_APP_URL",
343
+ valueLabel: "CLIENT_APP_URL",
344
+ valueType: "VARIABLE",
345
+ type: "disabled",
346
+ scope: "ENVIRONMENT"
347
+ },
348
+ {
349
+ name: "LOGIN_URL",
350
+ valueLabel: "LOGIN_URL",
351
+ valueType: "VARIABLE",
352
+ type: "disabled",
353
+ scope: "ENVIRONMENT"
354
+ },
355
+ {
356
+ name: "ELASTICSEARCH_SUPERUSER_PASSWORD",
357
+ valueLabel: "ELASTICSEARCH_SUPERUSER_PASSWORD",
358
+ valueType: "SECRET",
359
+ type: "disabled",
360
+ scope: "ENVIRONMENT"
361
+ },
362
+ {
363
+ name: "KIBANA_SYSTEM_PASSWORD",
364
+ valueLabel: "KIBANA_SYSTEM_PASSWORD",
365
+ valueType: "SECRET",
366
+ type: "disabled",
367
+ scope: "ENVIRONMENT"
368
+ },
369
+ {
370
+ name: "MINIO_ROOT_USER",
371
+ valueLabel: "MINIO_ROOT_USER",
372
+ valueType: "SECRET",
373
+ type: "disabled",
374
+ scope: "ENVIRONMENT"
375
+ },
376
+ {
377
+ name: "MINIO_ROOT_PASSWORD",
378
+ valueLabel: "MINIO_ROOT_PASSWORD",
379
+ valueType: "SECRET",
380
+ type: "disabled",
381
+ scope: "ENVIRONMENT"
382
+ },
383
+ {
384
+ name: "MONGODB_ADMIN_USER",
385
+ valueLabel: "MONGODB_ADMIN_USER",
386
+ valueType: "SECRET",
387
+ type: "disabled",
388
+ scope: "ENVIRONMENT"
389
+ },
390
+ {
391
+ name: "MONGODB_ADMIN_PASSWORD",
392
+ valueLabel: "MONGODB_ADMIN_PASSWORD",
393
+ valueType: "SECRET",
394
+ type: "disabled",
395
+ scope: "ENVIRONMENT"
396
+ },
397
+ {
398
+ name: "POSTGRES_USER",
399
+ valueLabel: "POSTGRES_USER",
400
+ valueType: "SECRET",
401
+ type: "disabled",
402
+ scope: "ENVIRONMENT"
403
+ },
404
+ {
405
+ name: "POSTGRES_PASSWORD",
406
+ valueLabel: "POSTGRES_PASSWORD",
407
+ valueType: "SECRET",
408
+ type: "disabled",
409
+ scope: "ENVIRONMENT"
410
+ },
411
+ {
412
+ name: "SUPER_USER_PASSWORD",
413
+ valueLabel: "SUPER_USER_PASSWORD",
414
+ valueType: "SECRET",
415
+ type: "disabled",
416
+ scope: "ENVIRONMENT"
417
+ },
418
+ {
419
+ name: "ENCRYPTION_KEY",
420
+ valueLabel: "ENCRYPTION_KEY",
421
+ valueType: "SECRET",
422
+ type: "disabled",
423
+ scope: "ENVIRONMENT"
424
+ },
425
+ {
426
+ name: "GH_ENCRYPTION_PASSWORD",
427
+ valueLabel: "GH_ENCRYPTION_PASSWORD",
428
+ valueType: "SECRET",
429
+ type: "disabled",
430
+ scope: "REPOSITORY"
431
+ },
432
+ {
433
+ name: "BACKUP_ENCRYPTION_PASSPHRASE",
434
+ valueLabel: "BACKUP_ENCRYPTION_PASSPHRASE",
435
+ valueType: "SECRET",
436
+ type: "disabled",
437
+ scope: "ENVIRONMENT"
438
+ },
439
+ {
440
+ name: "BACKUP_HOST_PRIVATE_KEY",
441
+ valueLabel: "BACKUP_HOST_PRIVATE_KEY",
442
+ valueType: "SECRET",
443
+ type: "disabled",
444
+ scope: "ENVIRONMENT"
445
+ },
446
+ {
447
+ name: "BACKUP_HOST_PUBLIC_KEY",
448
+ valueLabel: "BACKUP_HOST_PUBLIC_KEY",
449
+ valueType: "SECRET",
450
+ type: "disabled",
451
+ scope: "ENVIRONMENT"
452
+ },
453
+ {
454
+ name: "RESTORE_ENVIRONMENT_NAME",
455
+ valueLabel: "RESTORE_ENVIRONMENT_NAME",
456
+ valueType: "VARIABLE",
457
+ type: "disabled",
458
+ scope: "ENVIRONMENT"
459
+ },
460
+ {
461
+ name: "NOTIFICATION_TRANSPORT",
462
+ valueLabel: "NOTIFICATION_TRANSPORT",
463
+ valueType: "VARIABLE",
464
+ type: "disabled",
465
+ scope: "ENVIRONMENT"
466
+ }
467
+ ];
468
+ }
469
+ });
470
+
471
+ // src/environment/utils.ts
472
+ function generateLongPassword() {
473
+ const chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
474
+ let result = "";
475
+ for (let i = 16; i > 0; --i)
476
+ result += chars[Math.floor(Math.random() * chars.length)];
477
+ return result;
478
+ }
479
+ function findExistingValue(name, type, scope, existingValues) {
480
+ return existingValues.find(
481
+ (value) => value.name === name && value.type === type && value.scope === scope
482
+ );
483
+ }
484
+ function storeSecrets(environment, answers) {
485
+ let envConfig = {};
486
+ try {
487
+ envConfig = import_dotenv.default.parse(
488
+ (0, import_fs7.readFileSync)(`${process.cwd()}/.env.${environment}`)
489
+ );
490
+ } catch (error4) {
491
+ envConfig = {};
492
+ }
493
+ const linesFromAnswers = answers.map(
494
+ (update) => `${update.name}="${update.value}"`
495
+ );
496
+ const linesFromEnvConfig = Object.entries(envConfig).filter(([name]) => !answers.find((update) => update.name === name)).map(([name, value]) => `${name}="${value}"`);
497
+ const allLines = [...linesFromEnvConfig, ...linesFromAnswers].sort();
498
+ (0, import_fs7.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
499
+ }
500
+ function readYamlFile(filePath) {
501
+ const fileContent = import_fs7.default.readFileSync(filePath, "utf8");
502
+ return yaml.load(fileContent);
503
+ }
504
+ function writeYamlFile(filePath, data) {
505
+ try {
506
+ const yamlContent = yaml.dump(data, {
507
+ indent: 2,
508
+ lineWidth: -1,
509
+ flowLevel: -1,
510
+ // Prevent flow style for arrays/objects
511
+ noRefs: true,
512
+ sortKeys: false
513
+ });
514
+ import_fs7.default.writeFileSync(filePath, yamlContent, "utf8");
515
+ } catch (error4) {
516
+ throw new Error(`Failed to write inventory file: ${error4}`);
517
+ }
518
+ }
519
+ var import_fs7, yaml, import_dotenv;
520
+ var init_utils = __esm({
521
+ "src/environment/utils.ts"() {
522
+ "use strict";
523
+ import_fs7 = __toESM(require("fs"));
524
+ yaml = __toESM(require("js-yaml"));
525
+ import_dotenv = __toESM(require("dotenv"));
526
+ }
527
+ });
528
+
529
+ // src/environment/templates.ts
530
+ function getUsers(data) {
531
+ if (!data?.all?.vars?.users) {
532
+ return { users: [] };
533
+ }
534
+ return data.all.vars.users;
535
+ }
536
+ function extractAndModifyUsers(data) {
537
+ if (!data?.all?.vars?.users) {
538
+ return { users: [] };
539
+ }
540
+ const users = data.all.vars.users.map((user) => {
541
+ const { sudoer, ...rest } = user;
542
+ return {
543
+ ...rest,
544
+ role: sudoer ? "admin" : "operator"
545
+ };
546
+ });
547
+ return users;
548
+ }
549
+ function dockerManagerFirst(data) {
550
+ if (!data?.["docker-manager-first"]?.hosts) {
551
+ throw new Error(
552
+ "Invalid YAML structure: missing docker-manager-first.hosts"
553
+ );
554
+ }
555
+ const hosts = data["docker-manager-first"].hosts;
556
+ const dockerManagerFirst2 = Object.values(hosts).filter((host) => host.ansible_host).map((host) => host.ansible_host);
557
+ return dockerManagerFirst2.length === 1 ? dockerManagerFirst2[0] : "";
558
+ }
559
+ function extractBackupNode(data) {
560
+ if (!data?.["backups"]?.hosts) {
561
+ return "";
562
+ }
563
+ const hosts = data["backups"].hosts;
564
+ const backupHostEntry = Object.values(hosts).filter((host) => host.ansible_host).map((host) => host.ansible_host);
565
+ return backupHostEntry.length === 1 ? backupHostEntry[0] : "";
566
+ }
567
+ function extractWorkerNodes(data) {
568
+ if (!data?.["docker-workers"]?.hosts) {
569
+ return [];
570
+ }
571
+ const hosts = data["docker-workers"].hosts;
572
+ const worker_hosts = Object.values(hosts).filter((host) => host.ansible_host).map((host) => host.ansible_host);
573
+ return worker_hosts;
574
+ }
575
+ function copyChartsValues(env, values) {
576
+ const srcDir = import_path27.default.resolve(__dirname, "templates", "charts-values");
577
+ const destDir = import_path27.default.resolve(process.cwd(), "environments", env);
578
+ import_fs8.default.mkdirSync(destDir, { recursive: true });
579
+ values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
580
+ values["static_ssl"] = values["traefik_mode"] === "static_ssl";
581
+ values["opencrvs_environment"] = env;
582
+ function copyRecursive(src, dest) {
583
+ const stat = import_fs8.default.statSync(src);
584
+ if (stat.isDirectory()) {
585
+ import_fs8.default.mkdirSync(dest, { recursive: true });
586
+ for (const item of import_fs8.default.readdirSync(src)) {
587
+ copyRecursive(import_path27.default.join(src, item), import_path27.default.join(dest, item));
588
+ }
589
+ } else {
590
+ const content = import_fs8.default.readFileSync(src, "utf8");
591
+ const template = import_handlebars.default.compile(content);
592
+ const updated = template(values);
593
+ const isOverridesFile = dest.endsWith("override.yaml");
594
+ if (isOverridesFile && import_fs8.default.existsSync(dest)) {
595
+ log(` \u21B7 Skipped existing overrides file: ${dest}`);
596
+ return;
597
+ }
598
+ import_fs8.default.writeFileSync(dest, updated, "utf8");
599
+ log(` \u2713 Created: ${dest}`);
600
+ }
601
+ }
602
+ log(`
603
+ \u{1F4CB} Copying charts-values templates to ${destDir}:`);
604
+ copyRecursive(srcDir, destDir);
605
+ success(`\u2705 Completed copying charts-values.
606
+ `);
607
+ }
608
+ function generateInventory(env, values) {
609
+ const templatePath = import_path27.default.join(
610
+ __dirname,
611
+ "templates",
612
+ "inventory",
613
+ "inventory.template.yml"
614
+ );
615
+ const outputPath = import_path27.default.join(
616
+ process.cwd(),
617
+ "infrastructure",
618
+ "server-setup",
619
+ "inventory",
620
+ `${env}.yml`
621
+ );
622
+ const templateFile = import_fs8.default.readFileSync(templatePath, "utf-8");
623
+ const template = import_handlebars.default.compile(templateFile);
624
+ values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
625
+ const updated = template(values);
626
+ import_fs8.default.mkdirSync(import_path27.default.dirname(outputPath), { recursive: true });
627
+ import_fs8.default.writeFileSync(outputPath, updated);
628
+ log(`
629
+ \u2705 Generated inventory file at ${outputPath}
630
+ `);
631
+ }
632
+ var import_fs8, import_path27, import_handlebars;
633
+ var init_templates = __esm({
634
+ "src/environment/templates.ts"() {
635
+ "use strict";
636
+ import_fs8 = __toESM(require("fs"));
637
+ import_path27 = __toESM(require("path"));
638
+ init_logger();
639
+ import_handlebars = __toESM(require("handlebars"));
640
+ import_handlebars.default.registerHelper("data_label_idx", function(value) {
641
+ return parseInt(value) + 2;
642
+ });
643
+ }
644
+ });
645
+
646
+ // src/environment/ssh-keygen.ts
647
+ function generateSSHKeyPair() {
648
+ const keys = import_ssh2.utils.generateKeyPairSync("ed25519");
649
+ return {
650
+ publicKey: keys.public.toString(),
651
+ privateKey: keys.private.toString()
652
+ };
653
+ }
654
+ var import_ssh2;
655
+ var init_ssh_keygen = __esm({
656
+ "src/environment/ssh-keygen.ts"() {
657
+ "use strict";
658
+ import_ssh2 = require("ssh2");
659
+ }
660
+ });
661
+
662
+ // src/environment/git.ts
663
+ function getRepoInfo() {
664
+ try {
665
+ const remoteUrl = (0, import_child_process3.execSync)("git config --get remote.origin.url", {
666
+ stdio: ["ignore", "pipe", "ignore"]
667
+ }).toString().trim();
668
+ const match = remoteUrl.match(/github\.com[:/](.+?)\/(.+?)(\.git)?$/);
669
+ if (!match) {
670
+ return { organization: "", repository: "" };
671
+ }
672
+ return {
673
+ organization: match[1],
674
+ repository: match[2]
675
+ };
676
+ } catch {
677
+ return {
678
+ organization: "",
679
+ repository: ""
680
+ };
681
+ }
682
+ }
683
+ var import_child_process3;
684
+ var init_git = __esm({
685
+ "src/environment/git.ts"() {
686
+ "use strict";
687
+ import_child_process3 = require("child_process");
688
+ }
689
+ });
690
+
691
+ // src/environment/questions.ts
692
+ function validateCIDR(input3) {
693
+ if (!input3.trim()) {
694
+ return true;
695
+ }
696
+ const cidrRegex = /^((25[0-5]|(2[0-4]|1\d|[1-9]?\d)\d?)\.){3}(25[0-5]|(2[0-4]|1\d|[1-9]?\d)\d?)\/([0-9]|[12][0-9]|3[0-2])$/;
697
+ return cidrRegex.test(input3.trim()) ? true : "Please enter a valid CIDR (e.g. 10.0.0.0/24)";
698
+ }
699
+ function validateCIDRs(input3) {
700
+ if (!input3.trim()) {
701
+ return true;
702
+ }
703
+ const cidrs = input3.split(",").map((v) => v.trim());
704
+ for (const cidr of cidrs) {
705
+ const result = validateCIDR(cidr);
706
+ if (result !== true) {
707
+ return `Invalid CIDR: ${cidr}`;
708
+ }
709
+ }
710
+ return true;
711
+ }
712
+ var import_kleur2, notEmpty, dockerhubQuestions, githubQuestions, githubOtherQuestions, githubTokenQuestion, countryQuestions, infrastructureQuestions, staticSSLCertQuestions, backupQuestions, diskQuestions, databaseAndMonitoringQuestions, emailQuestions, sentryQuestions, metabaseAdminQuestions;
713
+ var init_questions = __esm({
714
+ "src/environment/questions.ts"() {
715
+ "use strict";
716
+ import_kleur2 = __toESM(require("kleur"));
717
+ init_utils();
718
+ init_git();
719
+ notEmpty = (value) => value.toString().trim().length > 0 ? true : "Please enter a value";
720
+ dockerhubQuestions = [
721
+ {
722
+ name: "dockerhubOrganisation",
723
+ type: "text",
724
+ message: "What is the name of your Docker Hub organisation?",
725
+ valueType: "SECRET",
726
+ valueLabel: "DOCKERHUB_ACCOUNT",
727
+ validate: notEmpty,
728
+ initial: process.env.DOCKER_ORGANISATION,
729
+ scope: "REPOSITORY"
730
+ },
731
+ {
732
+ name: "dockerhubRepository",
733
+ type: "text",
734
+ message: "What is the name of your private Docker Hub repository?",
735
+ valueType: "SECRET",
736
+ valueLabel: "DOCKERHUB_REPO",
737
+ validate: notEmpty,
738
+ initial: process.env.DOCKER_REPO,
739
+ scope: "REPOSITORY"
740
+ },
741
+ {
742
+ name: "dockerhubUsername",
743
+ type: "text",
744
+ message: "What is the Docker Hub username the the target server should be using?",
745
+ valueType: "SECRET",
746
+ valueLabel: "DOCKER_USERNAME",
747
+ validate: notEmpty,
748
+ initial: process.env.DOCKER_USERNAME,
749
+ scope: "REPOSITORY"
750
+ },
751
+ {
752
+ name: "dockerhubToken",
753
+ type: "text",
754
+ message: "What is the token of this Docker Hub account?",
755
+ valueType: "SECRET",
756
+ valueLabel: "DOCKER_TOKEN",
757
+ validate: notEmpty,
758
+ initial: process.env.DOCKER_TOKEN,
759
+ scope: "REPOSITORY"
760
+ }
761
+ ];
762
+ githubQuestions = [
763
+ {
764
+ name: "githubOrganisation",
765
+ type: "text",
766
+ message: "What is the name of your Github organisation?",
767
+ validate: notEmpty,
768
+ initial: process.env.GITHUB_ORGANISATION || getRepoInfo().organization,
769
+ scope: "REPOSITORY"
770
+ },
771
+ {
772
+ name: "githubRepository",
773
+ type: "text",
774
+ message: "What is your Github infrastructure repository?",
775
+ validate: notEmpty,
776
+ initial: process.env.GITHUB_REPOSITORY || getRepoInfo().repository,
777
+ scope: "REPOSITORY"
778
+ }
779
+ ];
780
+ githubOtherQuestions = [
781
+ {
782
+ name: "githubApprovers",
783
+ type: "text",
784
+ message: "Please provide/update list of production approvers?",
785
+ initial: process.env.GH_APPROVERS,
786
+ valueType: "VARIABLE",
787
+ valueLabel: "GH_APPROVERS",
788
+ scope: "REPOSITORY"
789
+ },
790
+ {
791
+ name: "approvalRequired",
792
+ type: "select",
793
+ message: "Would you like to enable approvals process for GitHub action workflows?",
794
+ choices: [
795
+ {
796
+ title: "True",
797
+ value: "true"
798
+ },
799
+ {
800
+ title: "False",
801
+ value: "false"
802
+ }
803
+ ],
804
+ valueType: "VARIABLE",
805
+ validate: notEmpty,
806
+ valueLabel: "APPROVAL_REQUIRED",
807
+ initial: process.env.APPROVAL_REQUIRED,
808
+ scope: "ENVIRONMENT"
809
+ }
810
+ ];
811
+ githubTokenQuestion = [
812
+ {
813
+ name: "githubToken",
814
+ type: "text",
815
+ message: "What is your Github token?",
816
+ validate: notEmpty,
817
+ initial: process.env.GITHUB_TOKEN,
818
+ valueType: "SECRET",
819
+ scope: "REPOSITORY",
820
+ valueLabel: "GH_TOKEN"
821
+ }
822
+ ];
823
+ countryQuestions = [
824
+ {
825
+ name: "country",
826
+ type: "text",
827
+ message: 'What is the ISO 3166-1 alpha-3 country-code? (e.g. "NZL" for New Zealand) Reference: https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3',
828
+ valueType: "VARIABLE",
829
+ valueLabel: "COUNTRY",
830
+ initial: process.env.COUNTRY,
831
+ scope: "REPOSITORY"
832
+ }
833
+ ];
834
+ infrastructureQuestions = [
835
+ {
836
+ name: "domain",
837
+ type: "text",
838
+ message: "What is the web domain applied after all subdomains in URLs?",
839
+ valueType: "VARIABLE",
840
+ validate: notEmpty,
841
+ valueLabel: "DOMAIN",
842
+ initial: process.env.DOMAIN,
843
+ scope: "ENVIRONMENT"
844
+ },
845
+ {
846
+ name: "kubeAPIHost",
847
+ type: "text",
848
+ message: `Kubernetes API endpoint (default: auto-detect)`,
849
+ valueType: "VARIABLE",
850
+ // validate: notEmpty,
851
+ valueLabel: "KUBE_API_HOST",
852
+ initial: process.env.KUBE_API_HOST,
853
+ scope: "ENVIRONMENT"
854
+ },
855
+ {
856
+ name: "kubeApiAllowedCidrs",
857
+ type: "text",
858
+ message: `Allowed CIDRs for Kubernetes API access (default: KUBE_API_HOST)`,
859
+ valueType: "VARIABLE",
860
+ validate: validateCIDRs,
861
+ valueLabel: "KUBE_API_ALLOWED_CIDRS",
862
+ initial: process.env.KUBE_API_ALLOWED_CIDRS || "",
863
+ scope: "ENVIRONMENT"
864
+ },
865
+ {
866
+ name: "kubeWorkerNodes",
867
+ type: "text",
868
+ message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
869
+ valueType: "VARIABLE",
870
+ // validate: notEmpty,
871
+ valueLabel: "KUBE_WORKER_NODES",
872
+ initial: process.env.KUBE_WORKER_NODES || "",
873
+ scope: "ENVIRONMENT"
874
+ }
875
+ ];
876
+ staticSSLCertQuestions = [
877
+ {
878
+ name: "sslCrt",
879
+ type: "text",
880
+ message: "Provide SSL Certificate or Certificate chain:",
881
+ valueType: "SECRET",
882
+ validate: notEmpty,
883
+ valueLabel: "SSL_CRT",
884
+ initial: process.env.SSL_CRT,
885
+ scope: "ENVIRONMENT"
886
+ },
887
+ {
888
+ name: "sslKey",
889
+ type: "text",
890
+ message: "Provide SSL Certificate key",
891
+ valueType: "SECRET",
892
+ validate: notEmpty,
893
+ valueLabel: "SSL_KEY",
894
+ initial: process.env.SSL_KEY,
895
+ scope: "ENVIRONMENT"
896
+ }
897
+ ];
898
+ backupQuestions = [
899
+ {
900
+ name: "backupHost",
901
+ type: "text",
902
+ message: `Please enter backup server host/IP address, (default: no backup):`,
903
+ valueType: "VARIABLE",
904
+ // validate: notEmpty,
905
+ valueLabel: "BACKUP_HOST",
906
+ initial: process.env.BACKUP_HOST || "",
907
+ scope: "ENVIRONMENT"
908
+ },
909
+ {
910
+ name: "backupUser",
911
+ type: "text",
912
+ message: `Please enter backup server user name:`,
913
+ valueType: "SECRET",
914
+ validate: notEmpty,
915
+ valueLabel: "BACKUP_SERVER_USER",
916
+ initial: process.env.BACKUP_SERVER_USER || "backup",
917
+ scope: "ENVIRONMENT"
918
+ },
919
+ {
920
+ name: "backupType",
921
+ type: "select",
922
+ message: "Select environment backup mode",
923
+ choices: [
924
+ {
925
+ title: "Full dump (daily full database backup)",
926
+ value: "dump"
927
+ },
928
+ {
929
+ title: "Differential (weekly full, daily diff backup)",
930
+ value: "differential"
931
+ }
932
+ ],
933
+ valueType: "VARIABLE",
934
+ validate: notEmpty,
935
+ valueLabel: "BACKUP_ENVIRONMENT_MODE",
936
+ initial: process.env.BACKUP_ENVIRONMENT_MODE,
937
+ scope: "ENVIRONMENT"
938
+ }
939
+ ];
940
+ diskQuestions = [
941
+ {
942
+ name: "diskSpace",
943
+ type: "text",
944
+ message: `What is the amount of diskspace that should be dedicated to OpenCRVS data and will become the size of an encrypted cryptfs data directory.
945
+
946
+ ${import_kleur2.default.red("DO NOT USE ALL DISKSPACE FOR OPENCRVS!")}
947
+
948
+ Leave at least 50g available for OS use.`,
949
+ valueType: "VARIABLE",
950
+ validate: notEmpty,
951
+ valueLabel: "DISK_SPACE",
952
+ initial: process.env.DISK_SPACE || "200g",
953
+ scope: "ENVIRONMENT"
954
+ }
955
+ ];
956
+ databaseAndMonitoringQuestions = [
957
+ {
958
+ name: "kibanaUsername",
959
+ type: "text",
960
+ message: "Input the username for logging in to Kibana",
961
+ valueType: "SECRET",
962
+ validate: notEmpty,
963
+ valueLabel: "KIBANA_USERNAME",
964
+ initial: process.env.KIBANA_USERNAME || "opencrvs-admin",
965
+ scope: "ENVIRONMENT"
966
+ },
967
+ {
968
+ name: "kibanaPassword",
969
+ type: "text",
970
+ message: "Input the password for logging in to Kibana",
971
+ valueType: "SECRET",
972
+ validate: notEmpty,
973
+ valueLabel: "KIBANA_PASSWORD",
974
+ initial: process.env.KIBANA_PASSWORD || generateLongPassword(),
975
+ scope: "ENVIRONMENT"
976
+ }
977
+ ];
978
+ emailQuestions = [
979
+ {
980
+ name: "smtpHost",
981
+ type: "text",
982
+ message: "What is your SMTP host?",
983
+ valueType: "SECRET",
984
+ validate: notEmpty,
985
+ valueLabel: "SMTP_HOST",
986
+ initial: process.env.SMTP_HOST,
987
+ scope: "ENVIRONMENT"
988
+ },
989
+ {
990
+ name: "smtpUsername",
991
+ type: "text",
992
+ message: "What is your SMTP username?",
993
+ valueType: "SECRET",
994
+ validate: notEmpty,
995
+ valueLabel: "SMTP_USERNAME",
996
+ initial: process.env.SMTP_USERNAME,
997
+ scope: "ENVIRONMENT"
998
+ },
999
+ {
1000
+ name: "smtpPassword",
1001
+ type: "text",
1002
+ message: "What is your SMTP password?",
1003
+ valueType: "SECRET",
1004
+ validate: notEmpty,
1005
+ valueLabel: "SMTP_PASSWORD",
1006
+ initial: process.env.SMTP_PASSWORD,
1007
+ scope: "ENVIRONMENT"
1008
+ },
1009
+ {
1010
+ name: "smtpPort",
1011
+ type: "text",
1012
+ message: "What is your SMTP port?",
1013
+ valueType: "SECRET",
1014
+ validate: notEmpty,
1015
+ valueLabel: "SMTP_PORT",
1016
+ initial: process.env.SMTP_PORT,
1017
+ scope: "ENVIRONMENT"
1018
+ },
1019
+ {
1020
+ name: "smtpSecure",
1021
+ type: "select",
1022
+ message: "Is the SMTP connection made securely using TLS?",
1023
+ choices: [
1024
+ {
1025
+ title: "True",
1026
+ value: "true"
1027
+ },
1028
+ {
1029
+ title: "False",
1030
+ value: "false"
1031
+ }
1032
+ ],
1033
+ valueType: "SECRET",
1034
+ validate: notEmpty,
1035
+ valueLabel: "SMTP_SECURE",
1036
+ initial: process.env.SMTP_SECURE,
1037
+ scope: "ENVIRONMENT"
1038
+ },
1039
+ {
1040
+ name: "senderEmailAddress",
1041
+ type: "text",
1042
+ message: "What is your sender email address?",
1043
+ valueType: "SECRET",
1044
+ validate: notEmpty,
1045
+ valueLabel: "SENDER_EMAIL_ADDRESS",
1046
+ initial: process.env.SENDER_EMAIL_ADDRESS,
1047
+ scope: "ENVIRONMENT"
1048
+ },
1049
+ {
1050
+ name: "alertEmail",
1051
+ type: "text",
1052
+ message: "What is the email address to receive alert emails or a Slack channel email link?",
1053
+ valueType: "SECRET",
1054
+ validate: notEmpty,
1055
+ valueLabel: "ALERT_EMAIL",
1056
+ initial: process.env.ALERT_EMAIL,
1057
+ scope: "ENVIRONMENT"
1058
+ }
1059
+ ];
1060
+ sentryQuestions = [
1061
+ {
1062
+ name: "sentryDsn",
1063
+ type: "text",
1064
+ message: "What is your Sentry DSN?",
1065
+ valueType: "SECRET",
1066
+ validate: notEmpty,
1067
+ valueLabel: "SENTRY_DSN",
1068
+ initial: process.env.SENTRY_DSN,
1069
+ scope: "ENVIRONMENT"
1070
+ }
1071
+ ];
1072
+ metabaseAdminQuestions = [
1073
+ {
1074
+ valueType: "SECRET",
1075
+ name: "OPENCRVS_METABASE_ADMIN_EMAIL",
1076
+ type: "text",
1077
+ message: "Email for Metabase super admin. Used as a username when logging in to the dashboard",
1078
+ valueLabel: "OPENCRVS_METABASE_ADMIN_EMAIL",
1079
+ scope: "ENVIRONMENT",
1080
+ initial: "user@opencrvs.org"
1081
+ },
1082
+ {
1083
+ valueType: "SECRET",
1084
+ name: "OPENCRVS_METABASE_ADMIN_PASSWORD",
1085
+ type: "text",
1086
+ message: "Password for Metabase super admin.",
1087
+ valueLabel: "OPENCRVS_METABASE_ADMIN_PASSWORD",
1088
+ scope: "ENVIRONMENT",
1089
+ initial: generateLongPassword()
1090
+ }
1091
+ ];
1092
+ }
1093
+ });
1094
+
1095
+ // src/environment/editor-questions.ts
1096
+ function editorQuestion(question) {
1097
+ return import("@inquirer/prompts").then(
1098
+ ({ editor: editor2 }) => editor2({ message: question })
1099
+ );
1100
+ }
1101
+ async function askQuestionWithEditor(questions, existingValues) {
1102
+ const answers = [];
1103
+ for (const question of questions) {
1104
+ const questionWithVariableLabel = {
1105
+ ...question,
1106
+ message: `${import_kleur3.default.cyan(question.valueLabel || "")}: ${question.message}`
1107
+ };
1108
+ if (!questionWithVariableLabel.valueLabel) {
1109
+ throw Error("Undefined Label");
1110
+ }
1111
+ const existingSecret = findExistingValue(
1112
+ questionWithVariableLabel.valueLabel,
1113
+ "SECRET",
1114
+ questionWithVariableLabel.scope,
1115
+ existingValues
1116
+ );
1117
+ let updateSecret = true;
1118
+ if (existingSecret) {
1119
+ updateSecret = (await (0, import_prompts.default)([
1120
+ {
1121
+ name: "overWrite",
1122
+ type: "confirm",
1123
+ message: `${import_kleur3.default.yellow(
1124
+ `${existingSecret.scope === "REPOSITORY" ? "Repository secret" : "Secret"} ${import_kleur3.default.cyan(
1125
+ existingSecret.name
1126
+ )} already exists in Github. Do you want to update it?`
1127
+ )}`
1128
+ }
1129
+ ])).overWrite;
1130
+ }
1131
+ if (!existingSecret || updateSecret === true) {
1132
+ const question_answer = await editorQuestion(
1133
+ questionWithVariableLabel.message
1134
+ );
1135
+ const answer = {
1136
+ type: "SECRET",
1137
+ scope: "ENVIRONMENT",
1138
+ name: questionWithVariableLabel.valueLabel,
1139
+ value: question_answer,
1140
+ didExist: existingSecret
1141
+ };
1142
+ answers.push(answer);
1143
+ }
1144
+ }
1145
+ return answers;
1146
+ }
1147
+ var import_kleur3, import_prompts;
1148
+ var init_editor_questions = __esm({
1149
+ "src/environment/editor-questions.ts"() {
1150
+ "use strict";
1151
+ init_utils();
1152
+ import_kleur3 = __toESM(require("kleur"));
1153
+ import_prompts = __toESM(require("prompts"));
1154
+ }
1155
+ });
1156
+
1157
+ // src/environment/questions-helper.ts
1158
+ async function input(options) {
1159
+ const inquirer = await import("@inquirer/prompts");
1160
+ return inquirer.input(options);
1161
+ }
1162
+ async function select(options) {
1163
+ const inquirer = await import("@inquirer/prompts");
1164
+ return inquirer.select(options);
1165
+ }
1166
+ function getIndexFromChoices(choices, value) {
1167
+ let idx = 0;
1168
+ for (const choice of choices) {
1169
+ if (choice.value === value) {
1170
+ return idx;
1171
+ }
1172
+ idx++;
1173
+ }
1174
+ return 0;
1175
+ }
1176
+ async function selectWithCustom(config) {
1177
+ const {
1178
+ message,
1179
+ choices,
1180
+ initial = void 0,
1181
+ customLabel = "Other...",
1182
+ customInputMessage = "Enter custom value:"
1183
+ } = config;
1184
+ const CUSTOM = "__custom__";
1185
+ const selected = await select({
1186
+ message,
1187
+ choices: [
1188
+ ...choices,
1189
+ {
1190
+ value: CUSTOM,
1191
+ name: customLabel
1192
+ }
1193
+ ],
1194
+ default: initial
1195
+ });
1196
+ if (selected === CUSTOM) {
1197
+ const customValue = await input({
1198
+ message: customInputMessage,
1199
+ validate: (value) => value.trim().length > 0 ? true : "Value cannot be empty"
1200
+ });
1201
+ return customValue;
1202
+ }
1203
+ return selected;
1204
+ }
1205
+ var init_questions_helper = __esm({
1206
+ "src/environment/questions-helper.ts"() {
1207
+ "use strict";
1208
+ }
1209
+ });
1210
+
1211
+ // src/environment/manage-users.ts
1212
+ async function inquirerPrompt(name, options) {
1213
+ const inquirer = await import("@inquirer/prompts");
1214
+ return inquirer[name](options);
1215
+ }
1216
+ function updateInventoryFile(filePath, users) {
1217
+ const data = readYamlFile(filePath);
1218
+ if (!data?.all?.vars?.users) {
1219
+ throw Error(`'users' section not found within inventory file: ${filePath}`);
1220
+ }
1221
+ data.all.vars.users = users;
1222
+ writeYamlFile(filePath, data);
1223
+ }
1224
+ function parseInventoryFile(filePath) {
1225
+ try {
1226
+ const data = readYamlFile(filePath);
1227
+ return getUsers(data);
1228
+ } catch {
1229
+ return [];
1230
+ }
1231
+ }
1232
+ function getCurrentUsername() {
1233
+ return os.userInfo().username;
1234
+ }
1235
+ function getCurrentUserSSHKeys() {
1236
+ const homeDir = os.homedir();
1237
+ const sshDir = path25.join(homeDir, ".ssh");
1238
+ const keys = [];
1239
+ const keyFiles = [
1240
+ "id_rsa.pub",
1241
+ "id_ecdsa.pub",
1242
+ "id_ed25519.pub",
1243
+ "id_dsa.pub"
1244
+ ];
1245
+ for (const keyFile of keyFiles) {
1246
+ const keyPath = path25.join(sshDir, keyFile);
1247
+ try {
1248
+ if (fs7.existsSync(keyPath)) {
1249
+ const keyContent = fs7.readFileSync(keyPath, "utf8").trim();
1250
+ if (keyContent) {
1251
+ keys.push(keyContent);
1252
+ }
1253
+ }
1254
+ } catch (error4) {
1255
+ continue;
1256
+ }
1257
+ }
1258
+ return keys;
1259
+ }
1260
+ async function selectRole() {
1261
+ return await select2({
1262
+ message: "Select user role:",
1263
+ choices: [
1264
+ { name: "Admin (full access to OS and Kubernetes)", value: "admin" },
1265
+ { name: "Operator (read-only OS, full Kubernetes)", value: "operator" }
1266
+ ]
1267
+ });
1268
+ }
1269
+ async function selectState() {
1270
+ return await select2({
1271
+ message: "Select user state:",
1272
+ choices: [
1273
+ { name: "Present (user is allowed to login)", value: "present" },
1274
+ { name: "Absent (user account is disabled)", value: "absent" }
1275
+ ]
1276
+ });
1277
+ }
1278
+ async function askToAddCurrentUser(existingUsers) {
1279
+ const currentUsername = getCurrentUsername();
1280
+ const currentKeys = getCurrentUserSSHKeys();
1281
+ if (existingUsers.find((u) => u.name === currentUsername)) {
1282
+ info(`\u2139\uFE0F User "${currentUsername}" already exists in inventory.`);
1283
+ return null;
1284
+ }
1285
+ if (currentKeys.length === 0) {
1286
+ return null;
1287
+ }
1288
+ const addCurrentUser = await confirm({
1289
+ message: `Add current user "${currentUsername}" with ${currentKeys.length} SSH key(s)?`,
1290
+ default: true
1291
+ });
1292
+ if (!addCurrentUser) {
1293
+ return null;
1294
+ }
1295
+ const role = await selectRole();
1296
+ return {
1297
+ name: currentUsername,
1298
+ ssh_keys: currentKeys,
1299
+ state: "present",
1300
+ role
1301
+ };
1302
+ }
1303
+ async function addNewUser(existingUsers) {
1304
+ const name = await input2({
1305
+ message: "Enter username:",
1306
+ validate: (value) => {
1307
+ if (!value.trim()) {
1308
+ return "Username required";
1309
+ }
1310
+ if (existingUsers.find((u) => u.name === value.trim())) {
1311
+ return `User "${value}" already exists`;
1312
+ }
1313
+ if (!/^[a-z_][a-z0-9_-]*[$]?$/.test(value.trim())) {
1314
+ return "Invalid username format (use lowercase, numbers, underscore, hyphen)";
1315
+ }
1316
+ return true;
1317
+ }
1318
+ });
1319
+ const keysInput = await editor({
1320
+ message: "Paste SSH public key(s) (one per line):",
1321
+ default: ""
1322
+ });
1323
+ const ssh_keys = keysInput.split("\n").map((key) => key.trim()).filter((key) => key && !key.startsWith("#"));
1324
+ if (ssh_keys.length === 0) {
1325
+ warn(
1326
+ "\u26A0\uFE0F Warning: No SSH keys provided. User will not be able to login remotely."
1327
+ );
1328
+ }
1329
+ const role = await selectRole();
1330
+ const state = "present";
1331
+ return {
1332
+ name: name.trim(),
1333
+ ssh_keys,
1334
+ state,
1335
+ role
1336
+ };
1337
+ }
1338
+ function displayUserSummary(users) {
1339
+ if (users.length === 0) {
1340
+ console.log("\n\u{1F4CB} No users configured.\n");
1341
+ return;
1342
+ }
1343
+ console.log("\n" + "=".repeat(70));
1344
+ console.log(`\u{1F4CB} User Configuration Summary - Total users: ${users.length}`);
1345
+ console.log("=".repeat(70));
1346
+ users.forEach((user, index) => {
1347
+ const stateIcon = user.state === "present" ? "\u2705" : "\u274C";
1348
+ const roleIcon = user.role === "admin" ? "\u{1F451}" : "\u{1F464}";
1349
+ console.log(
1350
+ `${index + 1}. ${stateIcon} ${roleIcon} ${user.name.padEnd(20)} Role: ${user.role.padEnd(10)} State: ${user.state.padEnd(10)} SSH Keys: ${user.ssh_keys.length}`
1351
+ );
1352
+ });
1353
+ console.log("=".repeat(70) + "\n");
1354
+ }
1355
+ async function editUser(user) {
1356
+ const updatedUser = { ...user };
1357
+ let continueEditing = true;
1358
+ const clearScreen = () => {
1359
+ process.stdout.write("\x1Bc");
1360
+ };
1361
+ const displayUserState = () => {
1362
+ clearScreen();
1363
+ console.log("\u2500".repeat(70));
1364
+ console.log(`\u{1F4DD} Editing user: ${updatedUser.name}`);
1365
+ console.log("\u2500".repeat(70));
1366
+ console.log(
1367
+ `Current Role: ${updatedUser.role === "admin" ? "\u{1F451} admin" : "\u{1F464} operator"}`
1368
+ );
1369
+ console.log(
1370
+ `Current State: ${updatedUser.state === "present" ? "\u2705 present" : "\u274C absent"}`
1371
+ );
1372
+ console.log(`Current SSH Keys: ${updatedUser.ssh_keys.length} key(s)`);
1373
+ if (updatedUser.ssh_keys.length > 0) {
1374
+ updatedUser.ssh_keys.forEach((key, idx) => {
1375
+ const keyPreview = key.length > 50 ? key.substring(0, 47) + "..." : key;
1376
+ console.log(` ${idx + 1}. ${keyPreview}`);
1377
+ });
1378
+ }
1379
+ console.log("\u2500".repeat(70));
1380
+ console.log("");
1381
+ };
1382
+ while (continueEditing) {
1383
+ displayUserState();
1384
+ const action = await select2({
1385
+ message: "What would you like to modify?",
1386
+ choices: [
1387
+ {
1388
+ name: `Change role (current: ${updatedUser.role})`,
1389
+ value: "role"
1390
+ },
1391
+ {
1392
+ name: `Change state (current: ${updatedUser.state})`,
1393
+ value: "state"
1394
+ },
1395
+ {
1396
+ name: `Update SSH keys (current: ${updatedUser.ssh_keys.length} key(s))`,
1397
+ value: "keys"
1398
+ },
1399
+ {
1400
+ name: "\u{1F4BE} Save changes and return",
1401
+ value: "save"
1402
+ },
1403
+ {
1404
+ name: "\u{1F6AB} Cancel and discard changes",
1405
+ value: "cancel"
1406
+ }
1407
+ ]
1408
+ });
1409
+ switch (action) {
1410
+ case "role":
1411
+ const newRole = await selectRole();
1412
+ if (newRole !== updatedUser.role) {
1413
+ updatedUser.role = newRole;
1414
+ }
1415
+ break;
1416
+ case "state":
1417
+ const newState = await selectState();
1418
+ if (newState !== updatedUser.state) {
1419
+ updatedUser.state = newState;
1420
+ }
1421
+ break;
1422
+ case "keys":
1423
+ const keysInput = await editor({
1424
+ message: "Update SSH public key(s) (one per line):",
1425
+ default: updatedUser.ssh_keys.join("\n")
1426
+ });
1427
+ const newKeys = keysInput.split("\n").map((key) => key.trim()).filter((key) => key && !key.startsWith("#"));
1428
+ if (newKeys.length === 0) {
1429
+ clearScreen();
1430
+ displayUserState();
1431
+ const confirmRemoveKeys = await confirm({
1432
+ message: "\u26A0\uFE0F Warning: All SSH keys will be removed. Continue with no SSH keys?",
1433
+ default: false
1434
+ });
1435
+ if (confirmRemoveKeys) {
1436
+ updatedUser.ssh_keys = [];
1437
+ }
1438
+ } else {
1439
+ updatedUser.ssh_keys = newKeys;
1440
+ }
1441
+ break;
1442
+ case "save":
1443
+ const hasChanges = updatedUser.role !== user.role || updatedUser.state !== user.state || JSON.stringify(updatedUser.ssh_keys) !== JSON.stringify(user.ssh_keys);
1444
+ clearScreen();
1445
+ if (hasChanges) {
1446
+ console.log("\n\u2705 Changes saved for user:", updatedUser.name, "\n");
1447
+ } else {
1448
+ console.log("\n\u2139\uFE0F No changes made\n");
1449
+ }
1450
+ continueEditing = false;
1451
+ break;
1452
+ case "cancel":
1453
+ clearScreen();
1454
+ const confirmCancel = await confirm({
1455
+ message: "Discard all changes?",
1456
+ default: false
1457
+ });
1458
+ if (confirmCancel) {
1459
+ console.log("\n\u{1F6AB} Changes discarded\n");
1460
+ return user;
1461
+ }
1462
+ break;
1463
+ }
1464
+ }
1465
+ return updatedUser;
1466
+ }
1467
+ async function manageUsers(inventoryPath) {
1468
+ let users = fs7.existsSync(inventoryPath) ? parseInventoryFile(inventoryPath) : [];
1469
+ if (users.length > 0) {
1470
+ displayUserSummary(users);
1471
+ }
1472
+ let continueManaging = true;
1473
+ while (continueManaging) {
1474
+ const action = await select2({
1475
+ message: "What would you like to do?",
1476
+ choices: [
1477
+ { name: "\u2795 Add new user", value: "add" },
1478
+ { name: "\u270F\uFE0F Edit existing user", value: "edit" },
1479
+ { name: "\u{1F5D1}\uFE0F Remove user", value: "remove" },
1480
+ { name: "\u{1F464} Add current system user", value: "add-current" },
1481
+ { name: "\u{1F4CB} View all users", value: "view" },
1482
+ { name: "\u{1F4BE} Save and exit", value: "save" },
1483
+ { name: "\u{1F6AA} Exit without saving", value: "exit" }
1484
+ ]
1485
+ });
1486
+ switch (action) {
1487
+ case "add":
1488
+ const newUser = await addNewUser(users);
1489
+ if (newUser) {
1490
+ users.push(newUser);
1491
+ console.log(`\u2705 User "${newUser.name}" added.
1492
+ `);
1493
+ }
1494
+ break;
1495
+ case "add-current":
1496
+ const currentUser = await askToAddCurrentUser(users);
1497
+ if (currentUser) {
1498
+ users.push(currentUser);
1499
+ console.log(`\u2705 Current user "${currentUser.name}" added.
1500
+ `);
1501
+ }
1502
+ break;
1503
+ case "edit":
1504
+ if (users.length === 0) {
1505
+ console.log("\u26A0\uFE0F No users to edit.\n");
1506
+ break;
1507
+ }
1508
+ const userToEdit = await select2({
1509
+ message: "Select user to edit:",
1510
+ choices: users.map((u) => ({
1511
+ name: `${u.name} (${u.role}, ${u.state})`,
1512
+ value: u.name
1513
+ }))
1514
+ });
1515
+ const userIndex = users.findIndex((u) => u.name === userToEdit);
1516
+ if (userIndex !== -1) {
1517
+ users[userIndex] = await editUser(users[userIndex]);
1518
+ console.log(`\u2705 User "${userToEdit}" updated.
1519
+ `);
1520
+ }
1521
+ break;
1522
+ case "remove":
1523
+ if (users.length === 0) {
1524
+ console.log("\u26A0\uFE0F No users to remove.\n");
1525
+ break;
1526
+ }
1527
+ const usersToRemove = await checkbox({
1528
+ message: "Select user(s) to remove:",
1529
+ choices: users.map((u) => ({
1530
+ name: `${u.name} (${u.role}, ${u.state})`,
1531
+ value: u.name
1532
+ }))
1533
+ });
1534
+ if (usersToRemove.length > 0) {
1535
+ const confirmRemove = await confirm({
1536
+ message: `Remove ${usersToRemove.length} user(s)?`,
1537
+ default: false
1538
+ });
1539
+ if (confirmRemove) {
1540
+ users = users.filter((u) => !usersToRemove.includes(u.name));
1541
+ console.log(`\u2705 Removed ${usersToRemove.length} user(s).
1542
+ `);
1543
+ }
1544
+ }
1545
+ break;
1546
+ case "view":
1547
+ displayUserSummary(users);
1548
+ break;
1549
+ case "save":
1550
+ if (users.length === 0) {
1551
+ info("\n\u{1F4CB} No users configured.\n");
1552
+ continueManaging = false;
1553
+ break;
1554
+ }
1555
+ displayUserSummary(users);
1556
+ const confirmSave = await confirm({
1557
+ message: "Save changes end exit?",
1558
+ default: true
1559
+ });
1560
+ if (confirmSave && fs7.existsSync(inventoryPath)) {
1561
+ updateInventoryFile(inventoryPath, users);
1562
+ console.log(`
1563
+ \u2705 Changes saved to ${inventoryPath}
1564
+ `);
1565
+ }
1566
+ continueManaging = false;
1567
+ break;
1568
+ case "exit":
1569
+ if (users.length === 0) {
1570
+ info("\n\u{1F4CB} No users configured.\n");
1571
+ continueManaging = false;
1572
+ break;
1573
+ }
1574
+ const confirmExit = await confirm({
1575
+ message: "Exit without saving changes?",
1576
+ default: false
1577
+ });
1578
+ if (confirmExit) {
1579
+ console.log("\u{1F44B} Exited without saving.\n");
1580
+ continueManaging = false;
1581
+ }
1582
+ break;
1583
+ }
1584
+ }
1585
+ return users;
1586
+ }
1587
+ var os, fs7, path25, input2, select2, confirm, editor, checkbox;
1588
+ var init_manage_users = __esm({
1589
+ "src/environment/manage-users.ts"() {
1590
+ "use strict";
1591
+ os = __toESM(require("os"));
1592
+ fs7 = __toESM(require("fs"));
1593
+ path25 = __toESM(require("path"));
1594
+ init_logger();
1595
+ init_utils();
1596
+ init_templates();
1597
+ input2 = (options) => inquirerPrompt("input", options);
1598
+ select2 = (options) => inquirerPrompt("select", options);
1599
+ confirm = (options) => inquirerPrompt("confirm", options);
1600
+ editor = (options) => inquirerPrompt("editor", options);
1601
+ checkbox = (options) => inquirerPrompt("checkbox", options);
1602
+ }
1603
+ });
1604
+
1605
+ // src/environment/setup-environment.ts
1606
+ var setup_environment_exports = {};
1607
+ async function confirm2(options) {
1608
+ const inquirer = await import("@inquirer/prompts");
1609
+ return inquirer.confirm(options);
1610
+ }
1611
+ async function select3(options) {
1612
+ const inquirer = await import("@inquirer/prompts");
1613
+ return inquirer.select(options);
1614
+ }
1615
+ function questionToPrompt({
1616
+ valueType,
1617
+ valueLabel,
1618
+ scope,
1619
+ ...promptOptions
1620
+ }) {
1621
+ return promptOptions;
1622
+ }
1623
+ function getAnswers(existingValues) {
1624
+ return ALL_ANSWERS.flatMap((answerObject) => {
1625
+ const questionsThatAreSecretsOrVariables = Object.entries(
1626
+ answerObject
1627
+ ).filter(([key, value]) => {
1628
+ if (value === "") {
1629
+ return false;
1630
+ }
1631
+ const existingQuestion = ALL_QUESTIONS.find(
1632
+ (question) => question.name === key
1633
+ );
1634
+ const valueType = existingQuestion?.valueType;
1635
+ return valueType === "VARIABLE" || valueType === "SECRET";
1636
+ });
1637
+ return questionsThatAreSecretsOrVariables.map(([key, value]) => {
1638
+ const existingQuestion = ALL_QUESTIONS.find(
1639
+ (question) => question.name === key
1640
+ );
1641
+ if (!existingQuestion?.valueLabel || existingQuestion.valueType !== "SECRET" && existingQuestion.valueType !== "VARIABLE") {
1642
+ throw new Error(`No secret or variable question found for ${key}`);
1643
+ }
1644
+ const { valueLabel, valueType, scope } = existingQuestion;
1645
+ if (valueType === "SECRET") {
1646
+ const existingSecret = findExistingValue(
1647
+ valueLabel,
1648
+ "SECRET",
1649
+ scope,
1650
+ existingValues
1651
+ );
1652
+ return {
1653
+ type: valueType,
1654
+ name: valueLabel,
1655
+ value: value.toString(),
1656
+ didExist: existingSecret,
1657
+ scope
1658
+ };
1659
+ }
1660
+ const existingVariable = findExistingValue(
1661
+ valueLabel,
1662
+ valueType,
1663
+ scope,
1664
+ existingValues
1665
+ );
1666
+ return {
1667
+ type: valueType,
1668
+ name: valueLabel,
1669
+ didExist: findExistingValue(
1670
+ valueLabel,
1671
+ valueType,
1672
+ scope,
1673
+ existingValues
1674
+ ),
1675
+ value: value.toString() || existingVariable?.value || "",
1676
+ scope
1677
+ };
1678
+ });
1679
+ });
1680
+ }
1681
+ async function promptAndStoreAnswer(environment, questions, existingValues) {
1682
+ log("");
1683
+ const processedQuestions = questions.flatMap((question) => {
1684
+ const questionWithVariableLabel = {
1685
+ ...question,
1686
+ message: `${import_kleur4.default.cyan(question.valueLabel || "")}: ${question.message}`
1687
+ };
1688
+ if (!questionWithVariableLabel.valueLabel) {
1689
+ return questionWithVariableLabel;
1690
+ }
1691
+ if (questionWithVariableLabel.valueType === "VARIABLE") {
1692
+ const existingVariable = findExistingValue(
1693
+ questionWithVariableLabel.valueLabel,
1694
+ "VARIABLE",
1695
+ questionWithVariableLabel.scope,
1696
+ existingValues
1697
+ );
1698
+ if (existingVariable) {
1699
+ let initial_value = existingVariable.value;
1700
+ if (questionWithVariableLabel.type === "select" && Array.isArray(questionWithVariableLabel.choices)) {
1701
+ initial_value = getIndexFromChoices(
1702
+ questionWithVariableLabel.choices,
1703
+ existingVariable.value
1704
+ );
1705
+ }
1706
+ return [
1707
+ {
1708
+ name: "overWrite" + questionWithVariableLabel.name,
1709
+ type: "confirm",
1710
+ scope: questionWithVariableLabel.scope,
1711
+ message: `${import_kleur4.default.yellow(
1712
+ `Variable ${import_kleur4.default.cyan(
1713
+ existingVariable.name
1714
+ )} already exists in Github. Do you want to update it?`
1715
+ )}`
1716
+ },
1717
+ {
1718
+ ...questionWithVariableLabel,
1719
+ type: (prev) => prev ? questionWithVariableLabel.type : null,
1720
+ initial: initial_value
1721
+ }
1722
+ ];
1723
+ }
1724
+ }
1725
+ if (questionWithVariableLabel.valueType === "SECRET") {
1726
+ const existingSecret = findExistingValue(
1727
+ questionWithVariableLabel.valueLabel,
1728
+ "SECRET",
1729
+ questionWithVariableLabel.scope,
1730
+ existingValues
1731
+ );
1732
+ if (existingSecret) {
1733
+ return [
1734
+ {
1735
+ name: "overWrite" + questionWithVariableLabel.name,
1736
+ type: "confirm",
1737
+ scope: questionWithVariableLabel.scope,
1738
+ message: `${import_kleur4.default.yellow(
1739
+ `${existingSecret.scope === "REPOSITORY" ? "Repository secret" : "Secret"} ${import_kleur4.default.cyan(
1740
+ existingSecret.name
1741
+ )} already exists in Github. Do you want to update it?`
1742
+ )}`
1743
+ },
1744
+ {
1745
+ ...questionWithVariableLabel,
1746
+ type: (prev) => prev ? questionWithVariableLabel.type : null
1747
+ }
1748
+ ];
1749
+ }
1750
+ }
1751
+ return questionWithVariableLabel;
1752
+ });
1753
+ const promptQuestions = processedQuestions.map(questionToPrompt);
1754
+ const result = await (0, import_prompts2.default)(promptQuestions, {
1755
+ onCancel: () => {
1756
+ process.exit(1);
1757
+ }
1758
+ });
1759
+ ALL_ANSWERS.push(result);
1760
+ storeSecrets(environment, getAnswers(existingValues));
1761
+ const existingValuesForQuestions = questions.filter((question) => question.valueType === "VARIABLE").map((question) => [
1762
+ question.name,
1763
+ findExistingValue(
1764
+ question.valueLabel,
1765
+ "VARIABLE",
1766
+ question.scope,
1767
+ existingValues
1768
+ )?.value
1769
+ ]);
1770
+ return { ...Object.fromEntries(existingValuesForQuestions), ...result };
1771
+ }
1772
+ var import_core, import_dotenv2, import_kleur4, import_prompts2, ALL_QUESTIONS, ALL_ANSWERS;
1773
+ var init_setup_environment = __esm({
1774
+ "src/environment/setup-environment.ts"() {
1775
+ "use strict";
1776
+ import_core = require("@octokit/core");
1777
+ import_dotenv2 = __toESM(require("dotenv"));
1778
+ import_kleur4 = __toESM(require("kleur"));
1779
+ import_prompts2 = __toESM(require("prompts"));
1780
+ init_github();
1781
+ init_derived_variables();
1782
+ init_utils();
1783
+ init_logger();
1784
+ init_templates();
1785
+ init_ssh_keygen();
1786
+ init_questions();
1787
+ init_editor_questions();
1788
+ init_questions_helper();
1789
+ init_manage_users();
1790
+ ALL_QUESTIONS = [];
1791
+ ALL_ANSWERS = [];
1792
+ ALL_QUESTIONS.push(
1793
+ ...githubTokenQuestion,
1794
+ ...githubOtherQuestions,
1795
+ ...dockerhubQuestions,
1796
+ ...diskQuestions,
1797
+ ...infrastructureQuestions,
1798
+ ...backupQuestions,
1799
+ ...countryQuestions,
1800
+ ...databaseAndMonitoringQuestions,
1801
+ ...emailQuestions,
1802
+ ...sentryQuestions,
1803
+ ...derivedVariables,
1804
+ ...metabaseAdminQuestions
1805
+ );
1806
+ (async () => {
1807
+ log("\n", import_kleur4.default.bold().underline("Github"), "\n");
1808
+ const { githubOrganisation, githubRepository } = await (0, import_prompts2.default)(
1809
+ githubQuestions.map(questionToPrompt),
1810
+ {
1811
+ onCancel: () => {
1812
+ process.exit(1);
1813
+ }
1814
+ }
1815
+ );
1816
+ const { githubToken } = await promptAndStoreAnswer(
1817
+ "",
1818
+ githubTokenQuestion,
1819
+ []
1820
+ );
1821
+ const octokit = new import_core.Octokit({
1822
+ auth: githubToken
1823
+ });
1824
+ log(import_kleur4.default.green("\nSuccessfully logged in to Github\n"));
1825
+ const existingEnvironments = await getRepositoryEnvironments(
1826
+ octokit,
1827
+ githubOrganisation,
1828
+ githubRepository
1829
+ );
1830
+ const defaultChoices = [
1831
+ { name: "Development", value: "development" },
1832
+ { name: "Quality assurance (no PII data)", value: "qa" },
1833
+ {
1834
+ name: "Staging (hosts PII data, no backups)",
1835
+ value: "staging"
1836
+ },
1837
+ {
1838
+ name: "Production (hosts PII data, requires frequent backups)",
1839
+ value: "production"
1840
+ }
1841
+ ];
1842
+ const choices = [
1843
+ ...defaultChoices,
1844
+ ...existingEnvironments.filter((env) => !defaultChoices.some((choice) => choice.value === env)).map((env) => ({
1845
+ name: env,
1846
+ value: env
1847
+ }))
1848
+ ];
1849
+ const environment = await selectWithCustom({
1850
+ message: "Choose a name and purpose for the environment?",
1851
+ choices
1852
+ });
1853
+ let environment_type = "non-production";
1854
+ if (["development", "qa"].includes(environment)) {
1855
+ environment_type = "non-production";
1856
+ } else if (["staging", "production"].includes(environment)) {
1857
+ environment_type = "production";
1858
+ } else {
1859
+ environment_type = await select3({
1860
+ message: "Purpose for the environment?",
1861
+ choices: [
1862
+ {
1863
+ name: "Development/Quality assurance/Testing (no PII data)",
1864
+ value: "non-production"
1865
+ },
1866
+ {
1867
+ name: "Staging/Production (hosts PII data, requires frequent backups)",
1868
+ value: "production"
1869
+ }
1870
+ ]
1871
+ });
1872
+ }
1873
+ const environment_exists = existingEnvironments.map((e) => e.trim()).includes(environment);
1874
+ if (!environment) {
1875
+ process.exit(1);
1876
+ }
1877
+ import_dotenv2.default.config({
1878
+ path: `${process.cwd()}/.env.${environment}`
1879
+ });
1880
+ await createEnvironment(
1881
+ octokit,
1882
+ environment,
1883
+ githubOrganisation,
1884
+ githubRepository
1885
+ );
1886
+ const repositoryId = await getRepositoryId(
1887
+ octokit,
1888
+ githubOrganisation,
1889
+ githubRepository
1890
+ );
1891
+ const existingRepositorySecrets = await listRepositorySecrets(
1892
+ octokit,
1893
+ githubOrganisation,
1894
+ githubRepository
1895
+ );
1896
+ const existingRepositoryVariables = await listRepositoryVariables(
1897
+ octokit,
1898
+ githubOrganisation,
1899
+ githubRepository
1900
+ );
1901
+ const existingEnvironmentVariables = await listEnvironmentVariables(
1902
+ octokit,
1903
+ repositoryId,
1904
+ environment
1905
+ );
1906
+ const existingEnvironmentSecrets = await listEnvironmentSecrets(
1907
+ octokit,
1908
+ githubOrganisation,
1909
+ repositoryId,
1910
+ environment
1911
+ );
1912
+ const existingValues = [
1913
+ ...existingEnvironmentVariables,
1914
+ ...existingRepositoryVariables,
1915
+ ...existingRepositorySecrets,
1916
+ ...existingEnvironmentSecrets
1917
+ ];
1918
+ if (existingEnvironmentVariables.length > 0 || existingEnvironmentSecrets.length > 0) {
1919
+ log(
1920
+ "\nEnvironment with the name",
1921
+ environment,
1922
+ "already exists in Github.",
1923
+ "\nFound",
1924
+ existingEnvironmentVariables.length,
1925
+ "existing variables and",
1926
+ existingEnvironmentSecrets.length,
1927
+ "secrets"
1928
+ );
1929
+ }
1930
+ if (environment_type === "production") {
1931
+ log(
1932
+ "\n",
1933
+ import_kleur4.default.yellow().bold(
1934
+ "WARNING! You are setting up a production environment.\n Make sure you have read the deployment guide carefully before proceeding.\n"
1935
+ )
1936
+ );
1937
+ await promptAndStoreAnswer(
1938
+ environment,
1939
+ githubOtherQuestions,
1940
+ existingValues
1941
+ );
1942
+ }
1943
+ log("\n", import_kleur4.default.bold().underline("Docker Hub"));
1944
+ await promptAndStoreAnswer(environment, dockerhubQuestions, existingValues);
1945
+ log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
1946
+ const infrastructure = await promptAndStoreAnswer(
1947
+ environment,
1948
+ infrastructureQuestions,
1949
+ existingValues
1950
+ );
1951
+ const kubeWorkerNodes = infrastructure.kubeWorkerNodes ? infrastructure.kubeWorkerNodes.split(",").map((ip) => ip.trim()) : [];
1952
+ log("\n", import_kleur4.default.bold().underline("SSH Users"), "\n");
1953
+ const users = await manageUsers(
1954
+ `infrastructure/server-setup/inventory/${environment}.yml`
1955
+ );
1956
+ log("\n", import_kleur4.default.bold().underline("Traefik SSL Certificate"), "\n");
1957
+ const sslCertExists = findExistingValue(
1958
+ "SSL_CRT",
1959
+ "SECRET",
1960
+ "ENVIRONMENT",
1961
+ existingValues
1962
+ );
1963
+ let ssl_answers = [];
1964
+ const traefikConfOption = (await (0, import_prompts2.default)([
1965
+ {
1966
+ name: "traefikConfOption",
1967
+ type: "select",
1968
+ message: "Choose option to configure Traefik SSL Certificate",
1969
+ choices: [
1970
+ { title: "Let's Encrypt certificate", value: "lets_encrypt" },
1971
+ { title: "Static SSL certificate", value: "static_ssl" },
1972
+ { title: "Custom configuration", value: "custom" }
1973
+ ],
1974
+ initial: sslCertExists ? 1 : 0
1975
+ }
1976
+ ])).traefikConfOption;
1977
+ if (traefikConfOption === "static_ssl") {
1978
+ ssl_answers = await askQuestionWithEditor(
1979
+ staticSSLCertQuestions,
1980
+ existingEnvironmentSecrets
1981
+ );
1982
+ }
1983
+ log("\n", import_kleur4.default.bold().underline("Storage"), "\n");
1984
+ let enableEncryption = false;
1985
+ const encryption_key_defined = findExistingValue(
1986
+ "ENCRYPTION_KEY",
1987
+ "SECRET",
1988
+ "ENVIRONMENT",
1989
+ existingValues
1990
+ );
1991
+ if (!encryption_key_defined && !environment_exists) {
1992
+ const answers_enable_encryption = await (0, import_prompts2.default)(
1993
+ [
1994
+ {
1995
+ name: "enableEncryption",
1996
+ type: "confirm",
1997
+ message: "Do you want to enable disk encryption?",
1998
+ scope: "ENVIRONMENT",
1999
+ initial: Boolean(process.env.ENABLE_ENCRYPTION)
2000
+ }
2001
+ ].map(questionToPrompt)
2002
+ );
2003
+ enableEncryption = answers_enable_encryption.enableEncryption;
2004
+ }
2005
+ if (enableEncryption && !encryption_key_defined && !environment_exists) {
2006
+ log(
2007
+ import_kleur4.default.bold().green("\u2714"),
2008
+ import_kleur4.default.bold().yellow(" Disk encryption is enabled")
2009
+ );
2010
+ await promptAndStoreAnswer(environment, diskQuestions, existingValues);
2011
+ } else {
2012
+ if (!enableEncryption && !encryption_key_defined && environment_exists) {
2013
+ log(
2014
+ import_kleur4.default.bold().green("\u2714"),
2015
+ import_kleur4.default.bold().grey(
2016
+ `Environment ${environment} is already configured, skipping disk encryption question`
2017
+ )
2018
+ );
2019
+ }
2020
+ const DISK_SPACE = findExistingValue(
2021
+ "DISK_SPACE",
2022
+ "VARIABLE",
2023
+ "ENVIRONMENT",
2024
+ existingValues
2025
+ );
2026
+ if (!DISK_SPACE) {
2027
+ log(
2028
+ import_kleur4.default.bold().green("\u2714"),
2029
+ import_kleur4.default.bold().grey("All available disk space at /data will be used")
2030
+ );
2031
+ } else {
2032
+ log(
2033
+ import_kleur4.default.bold().green("\u2714"),
2034
+ import_kleur4.default.bold().yellow("Variable DISK_SPACE is read-only, allocated space:"),
2035
+ DISK_SPACE?.value
2036
+ );
2037
+ }
2038
+ }
2039
+ let backupHost = findExistingValue("BACKUP_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2040
+ let backupType = "";
2041
+ let restoreEnvironmentName = findExistingValue(
2042
+ "RESTORE_ENVIRONMENT_NAME",
2043
+ "VARIABLE",
2044
+ "ENVIRONMENT",
2045
+ existingValues
2046
+ )?.value;
2047
+ let restoreType = findExistingValue(
2048
+ "RESTORE_ENVIRONMENT_MODE",
2049
+ "VARIABLE",
2050
+ "ENVIRONMENT",
2051
+ existingValues
2052
+ )?.value || process.env.RESTORE_ENVIRONMENT_MODE || "dump";
2053
+ log("\n", import_kleur4.default.bold().underline("Backup"));
2054
+ let configureBackup = backupHost ? true : false;
2055
+ if (!configureBackup && !restoreEnvironmentName) {
2056
+ configureBackup = await confirm2({
2057
+ message: "Do you want to configure backup?",
2058
+ default: Boolean(process.env.CONFIGURE_BACKUP)
2059
+ });
2060
+ }
2061
+ let backupHostPrivateKey = "";
2062
+ let backupHostPublicKey = "";
2063
+ if (configureBackup) {
2064
+ const backupAnswers = await promptAndStoreAnswer(
2065
+ environment,
2066
+ backupQuestions,
2067
+ existingValues
2068
+ );
2069
+ const backupHostPrivateKeyExists = findExistingValue(
2070
+ "BACKUP_HOST_PRIVATE_KEY",
2071
+ "SECRET",
2072
+ "ENVIRONMENT",
2073
+ existingValues
2074
+ );
2075
+ backupType = backupAnswers.backupType;
2076
+ backupHost = backupAnswers.backupHost || backupHost;
2077
+ if (!backupHostPrivateKeyExists) {
2078
+ const { publicKey, privateKey } = generateSSHKeyPair();
2079
+ backupHostPublicKey = publicKey;
2080
+ backupHostPrivateKey = privateKey;
2081
+ log(
2082
+ import_kleur4.default.bold().green("\u2714"),
2083
+ import_kleur4.default.bold().yellow(`Generated new SSH key pair for backup host: ${backupHost}`)
2084
+ );
2085
+ }
2086
+ } else {
2087
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Backup is disabled"));
2088
+ }
2089
+ log("\n", import_kleur4.default.bold().underline("Restore"));
2090
+ let configureRestore = restoreEnvironmentName ? true : false;
2091
+ if (!restoreEnvironmentName && !configureBackup) {
2092
+ configureRestore = await confirm2({
2093
+ message: "Do you want to configure restore?",
2094
+ default: Boolean(process.env.CONFIGURE_RESTORE)
2095
+ });
2096
+ }
2097
+ if (configureRestore) {
2098
+ const env_list_filtered = existingEnvironments.filter(
2099
+ (env) => env !== environment
2100
+ );
2101
+ restoreEnvironmentName = await selectWithCustom({
2102
+ message: "What is the name of your environment to restore?",
2103
+ choices: env_list_filtered.map((env) => ({
2104
+ name: env,
2105
+ value: env
2106
+ })),
2107
+ initial: restoreEnvironmentName
2108
+ });
2109
+ restoreType = await select3({
2110
+ message: `Select ${import_kleur4.default.yellow().bold(restoreEnvironmentName)} environment backup mode`,
2111
+ choices: [
2112
+ {
2113
+ name: "Full dump (daily full database backup)",
2114
+ value: "dump"
2115
+ },
2116
+ {
2117
+ name: "Differential (weekly full, daily diff backup)",
2118
+ value: "differential"
2119
+ }
2120
+ ]
2121
+ });
2122
+ } else {
2123
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2124
+ }
2125
+ log("\n", import_kleur4.default.bold().underline("Monitoring"));
2126
+ await promptAndStoreAnswer(
2127
+ environment,
2128
+ databaseAndMonitoringQuestions,
2129
+ existingValues
2130
+ );
2131
+ const sentryDSNExists = findExistingValue(
2132
+ "SENTRY_DSN",
2133
+ "SECRET",
2134
+ "ENVIRONMENT",
2135
+ existingValues
2136
+ );
2137
+ log("\n", import_kleur4.default.bold().underline("Sentry"));
2138
+ if (sentryDSNExists) {
2139
+ await promptAndStoreAnswer(environment, sentryQuestions, existingValues);
2140
+ } else {
2141
+ const { useSentry } = await (0, import_prompts2.default)([
2142
+ {
2143
+ name: "useSentry",
2144
+ type: "confirm",
2145
+ message: "Do you want to use Sentry?",
2146
+ initial: Boolean(process.env.SENTRY_DNS)
2147
+ }
2148
+ ]);
2149
+ if (useSentry) {
2150
+ await promptAndStoreAnswer(environment, sentryQuestions, existingValues);
2151
+ }
2152
+ }
2153
+ log("\n", import_kleur4.default.bold().underline("METABASE ADMIN"));
2154
+ await promptAndStoreAnswer(
2155
+ environment,
2156
+ metabaseAdminQuestions,
2157
+ existingValues
2158
+ );
2159
+ log("\n", import_kleur4.default.bold().underline("SMTP"));
2160
+ await promptAndStoreAnswer(environment, emailQuestions, existingValues);
2161
+ const allAnswers = ALL_ANSWERS.reduce((acc, answer) => {
2162
+ return { ...acc, ...answer };
2163
+ });
2164
+ const answerOrExisting = (variable, existingValue, fn) => fn(variable || existingValue?.value) || "";
2165
+ function findExistingOrDefine(name, type, scope, newValue) {
2166
+ return findExistingValue(name, type, scope, existingValues) ? null : process.env[name] || newValue;
2167
+ }
2168
+ const derivedUpdates = [
2169
+ {
2170
+ name: "GH_ENCRYPTION_PASSWORD",
2171
+ type: "SECRET",
2172
+ didExist: findExistingValue(
2173
+ "GH_ENCRYPTION_PASSWORD",
2174
+ "SECRET",
2175
+ "REPOSITORY",
2176
+ existingValues
2177
+ ),
2178
+ value: findExistingOrDefine(
2179
+ "GH_ENCRYPTION_PASSWORD",
2180
+ "SECRET",
2181
+ "REPOSITORY",
2182
+ generateLongPassword()
2183
+ ),
2184
+ scope: "REPOSITORY"
2185
+ }
2186
+ ];
2187
+ derivedUpdates.push({
2188
+ name: "NOTIFICATION_TRANSPORT",
2189
+ type: "VARIABLE",
2190
+ didExist: findExistingValue(
2191
+ "NOTIFICATION_TRANSPORT",
2192
+ "VARIABLE",
2193
+ "ENVIRONMENT",
2194
+ existingValues
2195
+ ),
2196
+ value: findExistingOrDefine(
2197
+ "NOTIFICATION_TRANSPORT",
2198
+ "VARIABLE",
2199
+ "ENVIRONMENT",
2200
+ "email"
2201
+ ),
2202
+ scope: "ENVIRONMENT"
2203
+ });
2204
+ derivedUpdates.push(...ssl_answers);
2205
+ if (configureBackup) {
2206
+ derivedUpdates.push({
2207
+ name: "BACKUP_ENCRYPTION_PASSPHRASE",
2208
+ type: "SECRET",
2209
+ didExist: findExistingValue(
2210
+ "BACKUP_ENCRYPTION_PASSPHRASE",
2211
+ "SECRET",
2212
+ "ENVIRONMENT",
2213
+ existingValues
2214
+ ),
2215
+ value: findExistingOrDefine(
2216
+ "BACKUP_ENCRYPTION_PASSPHRASE",
2217
+ "SECRET",
2218
+ "ENVIRONMENT",
2219
+ generateLongPassword()
2220
+ ),
2221
+ scope: "ENVIRONMENT"
2222
+ });
2223
+ }
2224
+ const applicationServerUpdates = [
2225
+ {
2226
+ name: "ELASTICSEARCH_SUPERUSER_PASSWORD",
2227
+ type: "SECRET",
2228
+ didExist: findExistingValue(
2229
+ "ELASTICSEARCH_SUPERUSER_PASSWORD",
2230
+ "SECRET",
2231
+ "ENVIRONMENT",
2232
+ existingValues
2233
+ ),
2234
+ value: findExistingOrDefine(
2235
+ "ELASTICSEARCH_SUPERUSER_PASSWORD",
2236
+ "SECRET",
2237
+ "ENVIRONMENT",
2238
+ generateLongPassword()
2239
+ ),
2240
+ scope: "ENVIRONMENT"
2241
+ },
2242
+ {
2243
+ name: "KIBANA_SYSTEM_PASSWORD",
2244
+ type: "SECRET",
2245
+ didExist: findExistingValue(
2246
+ "KIBANA_SYSTEM_PASSWORD",
2247
+ "SECRET",
2248
+ "ENVIRONMENT",
2249
+ existingValues
2250
+ ),
2251
+ value: findExistingOrDefine(
2252
+ "KIBANA_SYSTEM_PASSWORD",
2253
+ "SECRET",
2254
+ "ENVIRONMENT",
2255
+ generateLongPassword()
2256
+ ),
2257
+ scope: "ENVIRONMENT"
2258
+ },
2259
+ {
2260
+ name: "MINIO_ROOT_USER",
2261
+ type: "SECRET",
2262
+ didExist: findExistingValue(
2263
+ "MINIO_ROOT_USER",
2264
+ "SECRET",
2265
+ "ENVIRONMENT",
2266
+ existingValues
2267
+ ),
2268
+ value: findExistingOrDefine(
2269
+ "MINIO_ROOT_USER",
2270
+ "SECRET",
2271
+ "ENVIRONMENT",
2272
+ generateLongPassword()
2273
+ ),
2274
+ scope: "ENVIRONMENT"
2275
+ },
2276
+ {
2277
+ name: "MINIO_ROOT_PASSWORD",
2278
+ type: "SECRET",
2279
+ didExist: findExistingValue(
2280
+ "MINIO_ROOT_PASSWORD",
2281
+ "SECRET",
2282
+ "ENVIRONMENT",
2283
+ existingValues
2284
+ ),
2285
+ value: findExistingOrDefine(
2286
+ "MINIO_ROOT_PASSWORD",
2287
+ "SECRET",
2288
+ "ENVIRONMENT",
2289
+ generateLongPassword()
2290
+ ),
2291
+ scope: "ENVIRONMENT"
2292
+ },
2293
+ {
2294
+ name: "MONGODB_ADMIN_USER",
2295
+ type: "SECRET",
2296
+ didExist: findExistingValue(
2297
+ "MONGODB_ADMIN_USER",
2298
+ "SECRET",
2299
+ "ENVIRONMENT",
2300
+ existingValues
2301
+ ),
2302
+ value: findExistingOrDefine(
2303
+ "MONGODB_ADMIN_USER",
2304
+ "SECRET",
2305
+ "ENVIRONMENT",
2306
+ generateLongPassword()
2307
+ ),
2308
+ scope: "ENVIRONMENT"
2309
+ },
2310
+ {
2311
+ name: "MONGODB_ADMIN_PASSWORD",
2312
+ type: "SECRET",
2313
+ didExist: findExistingValue(
2314
+ "MONGODB_ADMIN_PASSWORD",
2315
+ "SECRET",
2316
+ "ENVIRONMENT",
2317
+ existingValues
2318
+ ),
2319
+ value: findExistingOrDefine(
2320
+ "MONGODB_ADMIN_PASSWORD",
2321
+ "SECRET",
2322
+ "ENVIRONMENT",
2323
+ generateLongPassword()
2324
+ ),
2325
+ scope: "ENVIRONMENT"
2326
+ },
2327
+ {
2328
+ name: "POSTGRES_USER",
2329
+ type: "SECRET",
2330
+ didExist: findExistingValue(
2331
+ "POSTGRES_USER",
2332
+ "SECRET",
2333
+ "ENVIRONMENT",
2334
+ existingValues
2335
+ ),
2336
+ value: findExistingOrDefine(
2337
+ "POSTGRES_USER",
2338
+ "SECRET",
2339
+ "ENVIRONMENT",
2340
+ generateLongPassword()
2341
+ ),
2342
+ scope: "ENVIRONMENT"
2343
+ },
2344
+ {
2345
+ name: "POSTGRES_PASSWORD",
2346
+ type: "SECRET",
2347
+ didExist: findExistingValue(
2348
+ "POSTGRES_PASSWORD",
2349
+ "SECRET",
2350
+ "ENVIRONMENT",
2351
+ existingValues
2352
+ ),
2353
+ value: findExistingOrDefine(
2354
+ "POSTGRES_PASSWORD",
2355
+ "SECRET",
2356
+ "ENVIRONMENT",
2357
+ generateLongPassword()
2358
+ ),
2359
+ scope: "ENVIRONMENT"
2360
+ },
2361
+ {
2362
+ name: "SUPER_USER_PASSWORD",
2363
+ type: "SECRET",
2364
+ didExist: findExistingValue(
2365
+ "SUPER_USER_PASSWORD",
2366
+ "SECRET",
2367
+ "ENVIRONMENT",
2368
+ existingValues
2369
+ ),
2370
+ value: findExistingOrDefine(
2371
+ "SUPER_USER_PASSWORD",
2372
+ "SECRET",
2373
+ "ENVIRONMENT",
2374
+ generateLongPassword()
2375
+ ),
2376
+ scope: "ENVIRONMENT"
2377
+ },
2378
+ {
2379
+ type: "VARIABLE",
2380
+ name: "ACTIVATE_USERS",
2381
+ value: "production" === environment_type ? "false" : "true",
2382
+ didExist: findExistingValue(
2383
+ "ACTIVATE_USERS",
2384
+ "VARIABLE",
2385
+ "ENVIRONMENT",
2386
+ existingValues
2387
+ ),
2388
+ scope: "ENVIRONMENT"
2389
+ },
2390
+ {
2391
+ type: "VARIABLE",
2392
+ name: "COUNTRY_CONFIG_HOST",
2393
+ value: answerOrExisting(
2394
+ allAnswers.domain,
2395
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2396
+ (val) => `https://countryconfig.${val}`
2397
+ ),
2398
+ didExist: findExistingValue(
2399
+ "COUNTRY_CONFIG_HOST",
2400
+ "VARIABLE",
2401
+ "ENVIRONMENT",
2402
+ existingValues
2403
+ ),
2404
+ scope: "ENVIRONMENT"
2405
+ },
2406
+ {
2407
+ type: "VARIABLE",
2408
+ name: "GATEWAY_HOST",
2409
+ value: answerOrExisting(
2410
+ allAnswers.domain,
2411
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2412
+ (val) => `https://gateway.${val}`
2413
+ ),
2414
+ didExist: findExistingValue(
2415
+ "GATEWAY_HOST",
2416
+ "VARIABLE",
2417
+ "ENVIRONMENT",
2418
+ existingValues
2419
+ ),
2420
+ scope: "ENVIRONMENT"
2421
+ },
2422
+ {
2423
+ type: "VARIABLE",
2424
+ name: "CONTENT_SECURITY_POLICY_WILDCARD",
2425
+ value: answerOrExisting(
2426
+ allAnswers.domain,
2427
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2428
+ (val) => `*.${val}`
2429
+ ),
2430
+ didExist: findExistingValue(
2431
+ "CONTENT_SECURITY_POLICY_WILDCARD",
2432
+ "VARIABLE",
2433
+ "ENVIRONMENT",
2434
+ existingValues
2435
+ ),
2436
+ scope: "ENVIRONMENT"
2437
+ },
2438
+ {
2439
+ type: "VARIABLE",
2440
+ name: "CLIENT_APP_URL",
2441
+ value: answerOrExisting(
2442
+ allAnswers.domain,
2443
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2444
+ (val) => `https://register.${val}`
2445
+ ),
2446
+ didExist: findExistingValue(
2447
+ "CLIENT_APP_URL",
2448
+ "VARIABLE",
2449
+ "ENVIRONMENT",
2450
+ existingValues
2451
+ ),
2452
+ scope: "ENVIRONMENT"
2453
+ },
2454
+ {
2455
+ type: "VARIABLE",
2456
+ name: "LOGIN_URL",
2457
+ value: answerOrExisting(
2458
+ allAnswers.domain,
2459
+ findExistingValue("DOMAIN", "VARIABLE", "ENVIRONMENT", existingValues),
2460
+ (val) => `https://login.${val}`
2461
+ ),
2462
+ didExist: findExistingValue(
2463
+ "LOGIN_URL",
2464
+ "VARIABLE",
2465
+ "ENVIRONMENT",
2466
+ existingValues
2467
+ ),
2468
+ scope: "ENVIRONMENT"
2469
+ },
2470
+ {
2471
+ type: "VARIABLE",
2472
+ name: "RESTORE_ENVIRONMENT_NAME",
2473
+ value: answerOrExisting(
2474
+ restoreEnvironmentName,
2475
+ findExistingValue(
2476
+ "RESTORE_ENVIRONMENT_NAME",
2477
+ "VARIABLE",
2478
+ "ENVIRONMENT",
2479
+ existingValues
2480
+ ),
2481
+ (val) => val || ""
2482
+ ),
2483
+ didExist: findExistingValue(
2484
+ "RESTORE_ENVIRONMENT_NAME",
2485
+ "VARIABLE",
2486
+ "ENVIRONMENT",
2487
+ existingValues
2488
+ ),
2489
+ scope: "ENVIRONMENT"
2490
+ }
2491
+ ];
2492
+ if (enableEncryption) {
2493
+ applicationServerUpdates.push({
2494
+ name: "ENCRYPTION_KEY",
2495
+ type: "SECRET",
2496
+ didExist: findExistingValue(
2497
+ "ENCRYPTION_KEY",
2498
+ "SECRET",
2499
+ "ENVIRONMENT",
2500
+ existingValues
2501
+ ),
2502
+ value: findExistingOrDefine(
2503
+ "ENCRYPTION_KEY",
2504
+ "SECRET",
2505
+ "ENVIRONMENT",
2506
+ generateLongPassword()
2507
+ ),
2508
+ scope: "ENVIRONMENT"
2509
+ });
2510
+ }
2511
+ if (configureBackup && backupHostPrivateKey && backupHostPublicKey) {
2512
+ applicationServerUpdates.push({
2513
+ name: "BACKUP_HOST_PRIVATE_KEY",
2514
+ type: "SECRET",
2515
+ didExist: void 0,
2516
+ value: backupHostPrivateKey,
2517
+ scope: "ENVIRONMENT"
2518
+ });
2519
+ applicationServerUpdates.push({
2520
+ name: "BACKUP_HOST_PUBLIC_KEY",
2521
+ type: "SECRET",
2522
+ didExist: void 0,
2523
+ value: backupHostPublicKey,
2524
+ scope: "ENVIRONMENT"
2525
+ });
2526
+ }
2527
+ derivedUpdates.push(...applicationServerUpdates);
2528
+ const updates = getAnswers(existingValues).concat(
2529
+ ...derivedUpdates.filter(
2530
+ (update) => update.value !== null
2531
+ )
2532
+ ).filter(
2533
+ (variable) => Boolean(variable.value) && // Only update values that changed
2534
+ (variable.type !== "VARIABLE" || variable.value !== variable.didExist?.value)
2535
+ );
2536
+ storeSecrets(environment, updates);
2537
+ const newSecrets = updates.filter(
2538
+ (update) => update.type === "SECRET" && !update.didExist
2539
+ );
2540
+ const updatedSecrets = updates.filter(
2541
+ (update) => update.type === "SECRET" && Boolean(update.didExist)
2542
+ );
2543
+ const newVariables = updates.filter(
2544
+ (update) => update.type === "VARIABLE" && !update.didExist
2545
+ );
2546
+ const updatedVariables = updates.filter(
2547
+ (update) => update.type === "VARIABLE" && Boolean(update.didExist)
2548
+ );
2549
+ const unknownVariables = existingValues.filter((value) => {
2550
+ return !ALL_QUESTIONS.find(
2551
+ (question) => question.valueLabel === value.name && question.valueType === value.type && question.scope === value.scope
2552
+ );
2553
+ });
2554
+ log("");
2555
+ if (newSecrets.length > 0) {
2556
+ log(
2557
+ import_kleur4.default.yellow(
2558
+ `The following secrets will be added to Github for environment ${environment}:`
2559
+ )
2560
+ );
2561
+ newSecrets.filter(({ scope }) => scope === "ENVIRONMENT").forEach((secret) => {
2562
+ log(secret.name, "=", secret.value);
2563
+ });
2564
+ log("");
2565
+ log(
2566
+ import_kleur4.default.yellow(`The following secrets will be added to Github repository:`)
2567
+ );
2568
+ newSecrets.filter(({ scope }) => scope === "REPOSITORY").forEach((secret) => {
2569
+ log(secret.name, "=", secret.value);
2570
+ });
2571
+ log("");
2572
+ }
2573
+ if (updatedSecrets.length > 0) {
2574
+ log(
2575
+ import_kleur4.default.yellow(
2576
+ `The following secrets will be updated in Github for environment ${environment}:`
2577
+ )
2578
+ );
2579
+ updatedSecrets.forEach((secret) => {
2580
+ log(secret.name, "=", secret.value);
2581
+ });
2582
+ log("");
2583
+ }
2584
+ if (newVariables.length > 0) {
2585
+ log(
2586
+ import_kleur4.default.yellow(
2587
+ `The following variables will be added to Github for environment ${environment}:`
2588
+ )
2589
+ );
2590
+ newVariables.forEach((variable) => {
2591
+ log(variable.name, "=", variable.value);
2592
+ });
2593
+ log("");
2594
+ }
2595
+ if (updatedVariables.length > 0) {
2596
+ log(
2597
+ import_kleur4.default.yellow(
2598
+ `The following variables will be updated in Github for environment ${environment}:`
2599
+ )
2600
+ );
2601
+ updatedVariables.forEach((variable) => {
2602
+ log(
2603
+ variable.name,
2604
+ "=",
2605
+ variable.value,
2606
+ `(was ${variable.didExist?.value})`
2607
+ );
2608
+ });
2609
+ log("");
2610
+ }
2611
+ if (unknownVariables.length > 0) {
2612
+ log(
2613
+ import_kleur4.default.yellow(
2614
+ `The following unknown variables/secrets were stored in Github are not managed by this script:`
2615
+ )
2616
+ );
2617
+ log("");
2618
+ log(import_kleur4.default.blue(`Repository:`));
2619
+ unknownVariables.filter(({ scope }) => scope === "REPOSITORY").forEach((variable) => {
2620
+ log(import_kleur4.default.cyan(variable.type) + ":", variable.name);
2621
+ });
2622
+ log("");
2623
+ log(import_kleur4.default.blue(`Environment:`));
2624
+ unknownVariables.filter(({ scope }) => scope === "ENVIRONMENT").forEach((variable) => {
2625
+ log(import_kleur4.default.cyan(variable.type) + ":", variable.name);
2626
+ });
2627
+ log("");
2628
+ log(
2629
+ import_kleur4.default.yellow(
2630
+ `These variables will not be updated by this script. If you want to update them, you will need to do so manually.`
2631
+ )
2632
+ );
2633
+ log("");
2634
+ }
2635
+ if ([].concat(newSecrets).concat(updatedSecrets).concat(newVariables).concat(updatedVariables).length === 0) {
2636
+ process.exit(0);
2637
+ }
2638
+ const saveChanges = await confirm2({
2639
+ message: "Do you want to continue?",
2640
+ default: true
2641
+ });
2642
+ if (!saveChanges) {
2643
+ process.exit(0);
2644
+ }
2645
+ for (const newSecret of newSecrets) {
2646
+ log(`Creating secret ${newSecret.name} with value ${newSecret.value}`);
2647
+ if (newSecret.scope === "ENVIRONMENT") {
2648
+ await createEnvironmentSecret(
2649
+ octokit,
2650
+ repositoryId,
2651
+ environment,
2652
+ newSecret.name,
2653
+ newSecret.value,
2654
+ githubOrganisation,
2655
+ githubRepository
2656
+ );
2657
+ } else {
2658
+ await createRepositorySecret(
2659
+ octokit,
2660
+ repositoryId,
2661
+ newSecret.name,
2662
+ newSecret.value,
2663
+ githubOrganisation,
2664
+ githubRepository
2665
+ );
2666
+ }
2667
+ }
2668
+ for (const updatedSecret of updatedSecrets) {
2669
+ log(
2670
+ `Updating secret ${updatedSecret.name} with value ${updatedSecret.value}`
2671
+ );
2672
+ if (updatedSecret.scope === "ENVIRONMENT") {
2673
+ await createEnvironmentSecret(
2674
+ octokit,
2675
+ repositoryId,
2676
+ environment,
2677
+ updatedSecret.name,
2678
+ updatedSecret.value,
2679
+ githubOrganisation,
2680
+ githubRepository
2681
+ );
2682
+ } else {
2683
+ await createRepositorySecret(
2684
+ octokit,
2685
+ repositoryId,
2686
+ updatedSecret.name,
2687
+ updatedSecret.value,
2688
+ githubOrganisation,
2689
+ githubRepository
2690
+ );
2691
+ }
2692
+ }
2693
+ for (const newVariable of newVariables) {
2694
+ log(`Creating variable ${newVariable.name} with value ${newVariable.value}`);
2695
+ if (newVariable.scope === "ENVIRONMENT") {
2696
+ await createEnvironmentVariable(
2697
+ octokit,
2698
+ repositoryId,
2699
+ environment,
2700
+ newVariable.name,
2701
+ newVariable.value
2702
+ );
2703
+ } else {
2704
+ await createRepositoryVariable(
2705
+ octokit,
2706
+ repositoryId,
2707
+ newVariable.name,
2708
+ newVariable.value
2709
+ );
2710
+ }
2711
+ }
2712
+ for (const updatedVariable of updatedVariables) {
2713
+ log(
2714
+ `Updating variable ${updatedVariable.name} with value ${updatedVariable.value}`
2715
+ );
2716
+ if (updatedVariable.scope === "ENVIRONMENT") {
2717
+ await updateEnvironmentVariable(
2718
+ octokit,
2719
+ repositoryId,
2720
+ environment,
2721
+ updatedVariable.name,
2722
+ updatedVariable.value
2723
+ );
2724
+ } else {
2725
+ await updateRepositoryVariable(
2726
+ octokit,
2727
+ repositoryId,
2728
+ updatedVariable.name,
2729
+ updatedVariable.value
2730
+ );
2731
+ }
2732
+ }
2733
+ log(
2734
+ import_kleur4.default.green(
2735
+ `Successfully updated Github secrets and variables for environment ${environment}`
2736
+ )
2737
+ );
2738
+ log("\n", import_kleur4.default.bold().underline("Running configuration files updates"));
2739
+ generateInventory(environment, {
2740
+ kube_worker_nodes: kubeWorkerNodes,
2741
+ kube_api_host: infrastructure.kubeAPIHost || "",
2742
+ backup_host: backupHost || "",
2743
+ users
2744
+ });
2745
+ copyChartsValues(environment, {
2746
+ env: environment,
2747
+ environment_type,
2748
+ // FIXME: In general that should be environment_type,
2749
+ // Hardcode like this blocks us from being generic:
2750
+ // https://github.com/opencrvs/opencrvs-core/issues/11171
2751
+ two_fa_enabled: environment !== "production" ? false : true,
2752
+ backup_enabled: configureBackup ? true : false,
2753
+ restore_enabled: restoreEnvironmentName ? true : false,
2754
+ restore_environment_name: restoreEnvironmentName || "",
2755
+ restore_type: restoreType,
2756
+ traefik_mode: traefikConfOption,
2757
+ backup_type: backupType
2758
+ });
2759
+ let addon_message = kubeWorkerNodes.length > 0 || configureBackup ? `--------------------------------------------------------------------------------------------
2760
+
2761
+ \u27A1\uFE0F ${import_kleur4.default.bold().yellow("COPY the SSH public key from the master VM to your clipboard")}
2762
+ --------------------------------------------------------------------------------------------
2763
+ ` : "";
2764
+ addon_message += kubeWorkerNodes.length > 0 ? `\u27A1\uFE0F ${import_kleur4.default.bold().yellow("Run following command on Kubernetes worker VM to create provision user and setup SSH key:")}
2765
+
2766
+ curl -sfL https://raw.githubusercontent.com/opencrvs/infrastructure/refs/heads/develop/scripts/bootstrap/opencrvs-bootstrap.sh -o opencrvs-bootstrap.sh && \\
2767
+ bash opencrvs-bootstrap.sh --ssh-public-key "${import_kleur4.default.bold("[PUT PROVISION USER PUBLIC KEY FROM MASTER NODE]")}"
2768
+ ` : "";
2769
+ addon_message += configureBackup ? `
2770
+ \u27A1\uFE0F ${import_kleur4.default.bold().yellow("Run following command on backup server to create provision user and setup SSH key:")}
2771
+ curl -sfL https://raw.githubusercontent.com/opencrvs/infrastructure/refs/heads/develop/scripts/bootstrap/opencrvs-bootstrap.sh -o opencrvs-bootstrap.sh && \\
2772
+ bash opencrvs-bootstrap.sh --ssh-public-key "${import_kleur4.default.bold("[PUT PROVISION USER PUBLIC KEY FROM MASTER NODE]")}"` : "";
2773
+ log(`
2774
+ ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
2775
+ Follow the steps below to complete the setup of your environment:
2776
+ ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
2777
+ \u27A1\uFE0F ${import_kleur4.default.bold().yellow("Run following command on Kubernetes master VM to bootstrap self-hosted runner:")}
2778
+
2779
+ curl -sfL https://raw.githubusercontent.com/opencrvs/infrastructure/refs/heads/develop/scripts/bootstrap/opencrvs-bootstrap.sh -o opencrvs-bootstrap.sh && \\
2780
+ bash opencrvs-bootstrap.sh --owner ${githubOrganisation} \\
2781
+ --repo ${githubRepository} \\
2782
+ --env ${environment} \\
2783
+ --token ${githubToken} \\
2784
+ --enable-runner
2785
+
2786
+ ${addon_message}
2787
+
2788
+ ${import_kleur4.default.yellow("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}
2789
+ ${import_kleur4.default.yellow("Please KINDLY read hints above")}
2790
+ `);
2791
+ log("\nAll variables stored in", import_kleur4.default.cyan(`.env.${environment}`));
2792
+ log(import_kleur4.default.bold().yellow("DO NOT COMMIT THIS FILE TO GIT!"));
2793
+ })();
2794
+ }
2795
+ });
2796
+
2797
+ // src/environment/update-workflows.ts
2798
+ var update_workflows_exports = {};
2799
+ __export(update_workflows_exports, {
2800
+ updateWorkflowEnvironments: () => updateWorkflowEnvironments
2801
+ });
2802
+ async function extractInfrastructureNames() {
2803
+ const files = glob.sync("infrastructure/server-setup/inventory/*.yml");
2804
+ const infraEnvironments = files.map((file) => (0, import_path28.basename)(file, ".yml"));
2805
+ if (infraEnvironments.length === 0) {
2806
+ console.log(
2807
+ "\u26A0\uFE0F Warning: No environment directories found in infrastructure/server-setup/inventory/"
2808
+ );
2809
+ return [];
2810
+ }
2811
+ log("\u{1F50D} Found infrastructure configurations:", infraEnvironments.join(", "));
2812
+ return infraEnvironments;
2813
+ }
2814
+ async function extractEnvironmentNames() {
2815
+ const entries = await (0, import_promises.readdir)("environments");
2816
+ const environments = entries.filter((entry) => {
2817
+ const fullPath = (0, import_path28.join)("environments", entry);
2818
+ return (0, import_fs9.statSync)(fullPath).isDirectory();
2819
+ });
2820
+ if (environments.length === 0) {
2821
+ console.log(
2822
+ "\u26A0\uFE0F Warning: No environment directories found in environments/"
2823
+ );
2824
+ return [];
2825
+ }
2826
+ log("\u{1F50D} Found OpenCRVS configurations:", environments.join(", "));
2827
+ return environments;
2828
+ }
2829
+ function updateOptionsInYaml(content, envList) {
2830
+ const optionsRegex = /([ ]*options:[ ]*\n)((?:[ ]*-[^\n]*\n)+)/;
2831
+ const match = content.match(optionsRegex);
2832
+ if (!match) {
2833
+ throw new Error("Could not find options array in workflow file");
2834
+ }
2835
+ const firstItemMatch = match[2].match(/^([ ]*)-/);
2836
+ const itemIndent = firstItemMatch ? firstItemMatch[1] : " ";
2837
+ const newOptions = match[1] + envList.map((env) => `${itemIndent}- ${env}`).join("\n") + "\n";
2838
+ return content.replace(optionsRegex, newOptions);
2839
+ }
2840
+ async function updateWorkflows(envList, config) {
2841
+ const { workflows } = config;
2842
+ for (const workflowPath of workflows) {
2843
+ try {
2844
+ const fileContents = (0, import_fs9.readFileSync)(workflowPath, "utf8");
2845
+ const workflowData = yaml2.load(fileContents);
2846
+ if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
2847
+ throw new Error(
2848
+ "Workflow does not have the expected structure: on.workflow_dispatch.inputs.environment.options"
2849
+ );
2850
+ }
2851
+ const updatedContent = updateOptionsInYaml(fileContents, envList);
2852
+ (0, import_fs9.writeFileSync)(workflowPath, updatedContent, "utf8");
2853
+ log(` \u2713 Successfully updated ${workflowPath}`);
2854
+ } catch (error4) {
2855
+ console.error(
2856
+ `
2857
+ \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`
2858
+ );
2859
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error4);
2860
+ throw error4;
2861
+ }
2862
+ }
2863
+ }
2864
+ async function updateWorkflowEnvironments() {
2865
+ try {
2866
+ let didUpdateWorkflows = false;
2867
+ const infraEnvironments = await extractInfrastructureNames();
2868
+ if (infraEnvironments.length > 0) {
2869
+ console.log("\u{1F504} Updating infrastructure workflows:");
2870
+ await updateWorkflows(infraEnvironments, {
2871
+ workflows: [
2872
+ ".github/workflows/provision.yml",
2873
+ ".github/workflows/reset-2fa.yml"
2874
+ ],
2875
+ path: "on.workflow_dispatch.inputs.environment.options"
2876
+ });
2877
+ didUpdateWorkflows = true;
2878
+ }
2879
+ const environments = await extractEnvironmentNames();
2880
+ if (environments.length > 0) {
2881
+ const workflows = [
2882
+ ".github/workflows/deploy-dependencies.yml",
2883
+ ".github/workflows/deploy-opencrvs.yml",
2884
+ ".github/workflows/clear-all-data.yml",
2885
+ ".github/workflows/seed-data.yml",
2886
+ ".github/workflows/reindex.yml",
2887
+ ".github/workflows/github-to-k8s-sync-env.yml"
2888
+ ];
2889
+ log("\u{1F4CB} Updating OpenCRVS application workflows:");
2890
+ await updateWorkflows(environments, {
2891
+ workflows,
2892
+ path: "on.workflow_dispatch.inputs.environment.options"
2893
+ });
2894
+ didUpdateWorkflows = true;
2895
+ }
2896
+ if (didUpdateWorkflows) {
2897
+ success("\u2705 Workflow updates completed successfully!");
2898
+ } else {
2899
+ log("\u2139\uFE0F No workflows were updated.");
2900
+ }
2901
+ } catch (error4) {
2902
+ console.error("\n\u274C Error updating workflows:", error4);
2903
+ process.exit(1);
2904
+ }
2905
+ }
2906
+ var import_promises, import_fs9, import_path28, glob, yaml2;
2907
+ var init_update_workflows = __esm({
2908
+ "src/environment/update-workflows.ts"() {
2909
+ "use strict";
2910
+ import_promises = require("fs/promises");
2911
+ import_fs9 = require("fs");
2912
+ import_path28 = require("path");
2913
+ glob = __toESM(require("glob"));
2914
+ yaml2 = __toESM(require("js-yaml"));
2915
+ init_logger();
2916
+ }
2917
+ });
2918
+
2919
+ // src/environment/users.ts
2920
+ var users_exports = {};
2921
+ __export(users_exports, {
2922
+ manageEnvironmentUsers: () => manageEnvironmentUsers
2923
+ });
2924
+ async function select4(options) {
2925
+ const inquirer = await import("@inquirer/prompts");
2926
+ return inquirer.select(options);
2927
+ }
2928
+ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inventory/") {
2929
+ if (!fs8.existsSync(dirPath)) {
2930
+ warn(`\u26A0\uFE0F No environment configuration directory found at ${dirPath}`);
2931
+ warn(
2932
+ "Hint: If this is a new infrastructure repository, run `opencrvs environment init` first."
2933
+ );
2934
+ return null;
2935
+ }
2936
+ const files = fs8.readdirSync(dirPath).filter((file) => {
2937
+ const filePath = path26.join(dirPath, file);
2938
+ const isFile = fs8.statSync(filePath).isFile();
2939
+ const ext = path26.extname(file).slice(1).toLowerCase();
2940
+ return isFile && (ext === "yml" || ext === "yaml");
2941
+ }).sort();
2942
+ if (files.length === 0) {
2943
+ warn(`\u26A0\uFE0F No environment configuration files found at ${dirPath}`);
2944
+ warn(
2945
+ "Hint: If this is a new infrastructure repository, run `opencrvs environment init` first."
2946
+ );
2947
+ return null;
2948
+ }
2949
+ const choices = files.map((file) => ({
2950
+ name: path26.basename(file, path26.extname(file)),
2951
+ value: path26.join(dirPath, file)
2952
+ }));
2953
+ const selectedFile = await select4({
2954
+ message: "Select environment (inventory file) to load users:",
2955
+ choices
2956
+ });
2957
+ return selectedFile;
2958
+ }
2959
+ async function manageEnvironmentUsers() {
2960
+ console.log("\n", import_kleur5.default.bold().underline("Manage users"), "\n");
2961
+ const inventory_file = await selectInventoryFile();
2962
+ if (!inventory_file) {
2963
+ return;
2964
+ }
2965
+ await manageUsers(inventory_file);
2966
+ }
2967
+ var fs8, path26, import_kleur5;
2968
+ var init_users = __esm({
2969
+ "src/environment/users.ts"() {
2970
+ "use strict";
2971
+ fs8 = __toESM(require("fs"));
2972
+ path26 = __toESM(require("path"));
2973
+ import_kleur5 = __toESM(require("kleur"));
2974
+ init_manage_users();
2975
+ init_logger();
2976
+ }
2977
+ });
2978
+
2979
+ // src/environment/swarm-to-k8s.ts
2980
+ var swarm_to_k8s_exports = {};
2981
+ var path27, import_kleur6, import_core2;
2982
+ var init_swarm_to_k8s = __esm({
2983
+ "src/environment/swarm-to-k8s.ts"() {
2984
+ "use strict";
2985
+ path27 = __toESM(require("path"));
2986
+ import_kleur6 = __toESM(require("kleur"));
2987
+ init_logger();
2988
+ init_utils();
2989
+ init_templates();
2990
+ import_core2 = require("@octokit/core");
2991
+ init_ssh_keygen();
2992
+ init_github();
2993
+ (async () => {
2994
+ log(
2995
+ import_kleur6.default.bold(
2996
+ "------------------------------------------------\nOpenCRVS Infrastructure migration script: \nMigrating Swarm configurations to Kubernetes\n------------------------------------------------\n"
2997
+ )
2998
+ );
2999
+ const environment_type = process.env.ENVIRONMENT_TYPE || "production";
3000
+ const environment = process.env.ENVIRONMENT || "";
3001
+ const githubToken = process.env.INFRA_TOKEN || "";
3002
+ const githubOrganisation = process.env.INFRA_ORGANISATION || "";
3003
+ const githubRepository = process.env.INFRA_REPOSITORY || "";
3004
+ if (!environment) {
3005
+ error("\n", "Environment variable ENVIRONMENT is not set. Exiting.");
3006
+ process.exit(1);
3007
+ }
3008
+ if (!githubToken) {
3009
+ error("\n", "Environment variable GITHUB_TOKEN is not set. Exiting.");
3010
+ process.exit(1);
3011
+ }
3012
+ if (!githubOrganisation) {
3013
+ error("\n", "Environment variable INFRA_ORGANISATION is not set. Exiting.");
3014
+ process.exit(1);
3015
+ }
3016
+ if (!githubRepository) {
3017
+ error("\n", "Environment variable INFRA_REPOSITORY is not set. Exiting.");
3018
+ process.exit(1);
3019
+ }
3020
+ if (["backup", "jumpbox"].includes(environment)) {
3021
+ info(
3022
+ ` > ${environment} environment will not be migrated, see migration notes`
3023
+ );
3024
+ process.exit(0);
3025
+ }
3026
+ log(import_kleur6.default.bold().underline("Migration properties:"));
3027
+ log(` \u2713 Environment: ${environment}`);
3028
+ const old_inventory_path = process.env.OLD_INVENTORY_PATH || "";
3029
+ if (!old_inventory_path) {
3030
+ error("\n", "Environment variable OLD_INVENTORY_PATH is not set. Exiting.");
3031
+ log(
3032
+ "\n",
3033
+ "Old inventory path is required to read existing Swarm configurations."
3034
+ );
3035
+ process.exit(1);
3036
+ }
3037
+ const ansible_inventory = path27.join(old_inventory_path, environment + ".yml");
3038
+ const data = readYamlFile(ansible_inventory);
3039
+ log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3040
+ const master = dockerManagerFirst(data) || "";
3041
+ log(` \u2713 Kubernetes API Host (Docker Manager): ${master}`);
3042
+ const users = extractAndModifyUsers(data);
3043
+ const kube_worker_nodes = extractWorkerNodes(data);
3044
+ log(` \u2713 Worker nodes: ${kube_worker_nodes.join(", ")}`);
3045
+ const backup_host = extractBackupNode(data);
3046
+ log(` \u2713 Backup host: ${backup_host}`);
3047
+ generateInventory(environment, {
3048
+ kube_worker_nodes,
3049
+ users,
3050
+ backup_host: environment === "production" ? backup_host : "",
3051
+ kube_api_host: master
3052
+ });
3053
+ copyChartsValues(environment, {
3054
+ env: environment,
3055
+ environment_type,
3056
+ // FIXME: In general that should be environment_type,
3057
+ // Hardcode like this blocks us from being generic:
3058
+ // https://github.com/opencrvs/opencrvs-core/issues/11171
3059
+ two_fa_enabled: environment !== "production" ? false : true,
3060
+ backup_enabled: environment === "production" ? "true" : "false",
3061
+ restore_enabled: environment === "staging" ? "true" : "false",
3062
+ restore_environment_name: environment === "staging" ? "production" : "",
3063
+ restore_type: "dump",
3064
+ traefik_mode: "static_ssl",
3065
+ backup_type: "dump"
3066
+ });
3067
+ if (environment === "staging") {
3068
+ const octokit = new import_core2.Octokit({
3069
+ auth: githubToken
3070
+ });
3071
+ const repositoryId = await getRepositoryId(
3072
+ octokit,
3073
+ githubOrganisation,
3074
+ githubRepository
3075
+ );
3076
+ try {
3077
+ await createEnvironmentVariable(
3078
+ octokit,
3079
+ repositoryId,
3080
+ environment,
3081
+ "RESTORE_ENVIRONMENT_NAME",
3082
+ "production"
3083
+ );
3084
+ } catch (err) {
3085
+ error(
3086
+ `Failed to create variable RESTORE_ENVIRONMENT_NAME for environment ${environment}:`,
3087
+ err
3088
+ );
3089
+ }
3090
+ }
3091
+ if (environment === "production") {
3092
+ const octokit = new import_core2.Octokit({
3093
+ auth: githubToken
3094
+ });
3095
+ console.log(
3096
+ "Fetching repository ID for:",
3097
+ githubOrganisation,
3098
+ githubRepository
3099
+ );
3100
+ const repositoryId = await getRepositoryId(
3101
+ octokit,
3102
+ githubOrganisation,
3103
+ githubRepository
3104
+ );
3105
+ console.log("Repository ID:", repositoryId);
3106
+ const { publicKey, privateKey } = generateSSHKeyPair();
3107
+ const secretsToCreate = {
3108
+ BACKUP_HOST_PRIVATE_KEY: privateKey,
3109
+ BACKUP_HOST_PUBLIC_KEY: publicKey,
3110
+ BACKUP_SERVER_USER: "backup"
3111
+ };
3112
+ const variablesToCreate = {
3113
+ BACKUP_HOST: backup_host,
3114
+ KUBE_WORKER_NODES: kube_worker_nodes.join(",")
3115
+ };
3116
+ for (const [secretName, secretValue] of Object.entries(secretsToCreate)) {
3117
+ try {
3118
+ await createEnvironmentSecret(
3119
+ octokit,
3120
+ repositoryId,
3121
+ environment,
3122
+ secretName,
3123
+ secretValue,
3124
+ githubOrganisation,
3125
+ githubRepository
3126
+ );
3127
+ log(` \u2713 Created secret ${secretName} for environment ${environment}`);
3128
+ } catch (err) {
3129
+ error(
3130
+ `Failed to create secret ${secretName} for environment ${environment}:`,
3131
+ err
3132
+ );
3133
+ }
3134
+ }
3135
+ for (const [variableName, variableValue] of Object.entries(
3136
+ variablesToCreate
3137
+ )) {
3138
+ try {
3139
+ await createEnvironmentVariable(
3140
+ octokit,
3141
+ repositoryId,
3142
+ environment,
3143
+ variableName,
3144
+ variableValue
3145
+ );
3146
+ log(
3147
+ ` \u2713 Created variable ${variableName} for environment ${environment}`
3148
+ );
3149
+ } catch (err) {
3150
+ error(
3151
+ `Failed to create variable ${variableName} for environment ${environment}:`,
3152
+ err
3153
+ );
3154
+ }
3155
+ }
3156
+ }
3157
+ })();
3158
+ }
3159
+ });
25
3160
 
26
3161
  // src/migrations/v2.0/remove-review-from-register-action.ts
27
3162
  var import_ts_morph = require("ts-morph");
@@ -178,6 +3313,8 @@ function ensureImports(sourceFile) {
178
3313
  var DEFINE_CONFIG_NAME2 = "defineConfig";
179
3314
  var ACTIONS_PROPERTY_NAME2 = "actions";
180
3315
  var TYPE_PROPERTY_NAME2 = "type";
3316
+ var ID_PROPERTY_NAME = "id";
3317
+ var FLAGS_PROPERTY_NAME = "flags";
181
3318
  var CUSTOM_ACTION_TYPE_PROPERTY_NAME = "customActionType";
182
3319
  var AUDIT_HISTORY_LABEL_PROPERTY_NAME = "auditHistoryLabel";
183
3320
  var DEDUPLICATION_PROPERTY_NAME = "deduplication";
@@ -187,9 +3324,12 @@ var FORM_PROPERTY_NAME = "form";
187
3324
  var ACTION_TYPE_ENUM_NAME = "ActionType";
188
3325
  var VALIDATE_MEMBER_NAME = "VALIDATE";
189
3326
  var CUSTOM_MEMBER_NAME = "CUSTOM";
3327
+ var REGISTER_MEMBER_NAME2 = "REGISTER";
190
3328
  var VALIDATE_STRING_LITERAL = "VALIDATE";
191
3329
  var CUSTOM_STRING_LITERAL = "CUSTOM";
3330
+ var REGISTER_STRING_LITERAL2 = "REGISTER";
192
3331
  var VALIDATE_DECLARATION_VALUE = "VALIDATE_DECLARATION";
3332
+ var VALIDATED_FLAG_VALUE = "validated";
193
3333
  function isValidateType(typeInitializer) {
194
3334
  if (typeInitializer.getKind() === import_ts_morph2.SyntaxKind.PropertyAccessExpression) {
195
3335
  const propAccess = typeInitializer.asKindOrThrow(
@@ -313,6 +3453,50 @@ function transformValidateActionToCustom(obj, eventType) {
313
3453
  }
314
3454
  return true;
315
3455
  }
3456
+ function isRegisterAction(action) {
3457
+ const typeProperty = action.getProperty(TYPE_PROPERTY_NAME2);
3458
+ if (!typeProperty || !import_ts_morph2.Node.isPropertyAssignment(typeProperty)) return false;
3459
+ const typeInit = typeProperty.getInitializer();
3460
+ if (!typeInit) return false;
3461
+ if (import_ts_morph2.Node.isPropertyAccessExpression(typeInit)) {
3462
+ const enumExpr = typeInit.getExpression();
3463
+ return import_ts_morph2.Node.isIdentifier(enumExpr) && enumExpr.getText() === ACTION_TYPE_ENUM_NAME && typeInit.getName() === REGISTER_MEMBER_NAME2;
3464
+ }
3465
+ if (import_ts_morph2.Node.isStringLiteral(typeInit)) {
3466
+ return typeInit.getLiteralValue() === REGISTER_STRING_LITERAL2;
3467
+ }
3468
+ return false;
3469
+ }
3470
+ function arrayHasElementWithId(array3, id) {
3471
+ for (const el of array3.getElements()) {
3472
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(el)) continue;
3473
+ const idProp = el.getProperty(ID_PROPERTY_NAME);
3474
+ if (!idProp || !import_ts_morph2.Node.isPropertyAssignment(idProp)) continue;
3475
+ const idInit = idProp.getInitializer();
3476
+ if (idInit && import_ts_morph2.Node.isStringLiteral(idInit) && idInit.getLiteralValue() === id) {
3477
+ return true;
3478
+ }
3479
+ }
3480
+ return false;
3481
+ }
3482
+ function ensureRegisterRemovesValidatedFlag(action) {
3483
+ const entry = `{ id: '${VALIDATED_FLAG_VALUE}', operation: 'remove' }`;
3484
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME);
3485
+ if (flagsProp && import_ts_morph2.Node.isPropertyAssignment(flagsProp)) {
3486
+ const flagsInit = flagsProp.getInitializer();
3487
+ if (flagsInit && import_ts_morph2.Node.isArrayLiteralExpression(flagsInit)) {
3488
+ if (arrayHasElementWithId(flagsInit, VALIDATED_FLAG_VALUE)) return false;
3489
+ flagsInit.addElement(entry);
3490
+ return true;
3491
+ }
3492
+ return false;
3493
+ }
3494
+ action.addPropertyAssignment({
3495
+ name: FLAGS_PROPERTY_NAME,
3496
+ initializer: `[${entry}]`
3497
+ });
3498
+ return true;
3499
+ }
316
3500
  function processFile2(filePath, project) {
317
3501
  const sourceFile = project.getSourceFile(filePath);
318
3502
  if (!sourceFile) return 0;
@@ -378,6 +3562,18 @@ function processFile2(filePath, project) {
378
3562
  ` [${import_path2.default.relative(process.cwd(), filePath)}] Added top-level 'flags' array to defineConfig`
379
3563
  );
380
3564
  }
3565
+ if (configHadValidateAction) {
3566
+ for (const element of actionsInitializer.getElements()) {
3567
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(element)) continue;
3568
+ if (!isRegisterAction(element)) continue;
3569
+ if (ensureRegisterRemovesValidatedFlag(element)) {
3570
+ transformedCount++;
3571
+ console.log(
3572
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Added '${VALIDATED_FLAG_VALUE}' remove-flag to REGISTER action`
3573
+ );
3574
+ }
3575
+ }
3576
+ }
381
3577
  if (fileNeedsImports) {
382
3578
  ensureImports(sourceFile);
383
3579
  }
@@ -424,7 +3620,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
424
3620
  }
425
3621
  console.log(
426
3622
  `
427
- Done. Transformed ${totalTransformed} VALIDATE action(s) to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'.`
3623
+ Done. Applied ${totalTransformed} change(s): VALIDATE \u2192 CUSTOM (${VALIDATE_DECLARATION_VALUE}) and '${VALIDATED_FLAG_VALUE}' remove-flag on matching REGISTER actions.`
428
3624
  );
429
3625
  }
430
3626
 
@@ -667,14 +3863,14 @@ var QUERY_PROPERTY_NAME = "query";
667
3863
  var TYPE_PROPERTY_NAME5 = "type";
668
3864
  var CLAUSES_PROPERTY_NAME = "clauses";
669
3865
  var STATUS_PROPERTY_NAME = "status";
670
- var FLAGS_PROPERTY_NAME = "flags";
3866
+ var FLAGS_PROPERTY_NAME2 = "flags";
671
3867
  var TERMS_PROPERTY_NAME = "terms";
672
3868
  var TERM_PROPERTY_NAME = "term";
673
3869
  var ANY_OF_PROPERTY_NAME = "anyOf";
674
3870
  var VALIDATED_STATUS_VALUE = "VALIDATED";
675
- var VALIDATED_FLAG_VALUE = "validated";
3871
+ var VALIDATED_FLAG_VALUE2 = "validated";
676
3872
  function addValidatedFlag(clause) {
677
- const flagsProperty = clause.getProperty(FLAGS_PROPERTY_NAME);
3873
+ const flagsProperty = clause.getProperty(FLAGS_PROPERTY_NAME2);
678
3874
  if (flagsProperty && import_ts_morph5.Node.isPropertyAssignment(flagsProperty)) {
679
3875
  const flagsInit = flagsProperty.getInitializer();
680
3876
  if (flagsInit && import_ts_morph5.Node.isObjectLiteralExpression(flagsInit)) {
@@ -682,19 +3878,19 @@ function addValidatedFlag(clause) {
682
3878
  if (anyOfProperty && import_ts_morph5.Node.isPropertyAssignment(anyOfProperty)) {
683
3879
  const anyOfInit = anyOfProperty.getInitializer();
684
3880
  if (anyOfInit && import_ts_morph5.Node.isArrayLiteralExpression(anyOfInit)) {
685
- anyOfInit.addElement(`'${VALIDATED_FLAG_VALUE}'`);
3881
+ anyOfInit.addElement(`'${VALIDATED_FLAG_VALUE2}'`);
686
3882
  }
687
3883
  } else {
688
3884
  flagsInit.addPropertyAssignment({
689
3885
  name: ANY_OF_PROPERTY_NAME,
690
- initializer: `['${VALIDATED_FLAG_VALUE}']`
3886
+ initializer: `['${VALIDATED_FLAG_VALUE2}']`
691
3887
  });
692
3888
  }
693
3889
  }
694
3890
  } else {
695
3891
  clause.addPropertyAssignment({
696
- name: FLAGS_PROPERTY_NAME,
697
- initializer: `{ ${ANY_OF_PROPERTY_NAME}: ['${VALIDATED_FLAG_VALUE}'] }`
3892
+ name: FLAGS_PROPERTY_NAME2,
3893
+ initializer: `{ ${ANY_OF_PROPERTY_NAME}: ['${VALIDATED_FLAG_VALUE2}'] }`
698
3894
  });
699
3895
  }
700
3896
  }
@@ -860,23 +4056,26 @@ var DEFINE_CONFIG_NAME4 = "defineConfig";
860
4056
  var DEFINE_WORKQUEUES_NAME2 = "defineWorkqueues";
861
4057
  var ACTIONS_PROPERTY_NAME4 = "actions";
862
4058
  var ACTION_PROPERTY_NAME = "action";
863
- var FLAGS_PROPERTY_NAME2 = "flags";
4059
+ var FLAGS_PROPERTY_NAME3 = "flags";
864
4060
  var QUERY_PROPERTY_NAME2 = "query";
865
4061
  var TYPE_PROPERTY_NAME6 = "type";
4062
+ var ID_PROPERTY_NAME2 = "id";
866
4063
  var CLAUSES_PROPERTY_NAME2 = "clauses";
867
4064
  var ANY_OF_PROPERTY_NAME2 = "anyOf";
868
4065
  var FLAG_ID = "pending-first-certificate-issuance";
869
4066
  var REGISTER_TYPE = "REGISTER";
870
4067
  var PRINT_CERTIFICATE_TYPE = "PRINT_CERTIFICATE";
871
- var FLAG_DEFINITION_INITIALIZER = `{
4068
+ function flagDefinitionInitializer(eventType) {
4069
+ return `{
872
4070
  id: '${FLAG_ID}',
873
4071
  label: {
874
- id: 'event.birth.flag.${FLAG_ID}',
4072
+ id: 'event.${eventType}.flag.${FLAG_ID}',
875
4073
  defaultMessage: 'Pending first certificate issuance',
876
4074
  description: 'Flag label for first certificate issuance'
877
4075
  },
878
4076
  requiresAction: true
879
4077
  }`;
4078
+ }
880
4079
  function isActionOfType(obj, typeName) {
881
4080
  const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME6);
882
4081
  if (!typeProperty || !import_ts_morph6.Node.isPropertyAssignment(typeProperty)) return false;
@@ -890,18 +4089,20 @@ function isActionOfType(obj, typeName) {
890
4089
  }
891
4090
  return false;
892
4091
  }
893
- function isBirthConfig(configArg) {
894
- const typeProperty = configArg.getProperty(TYPE_PROPERTY_NAME6);
895
- if (!typeProperty || !import_ts_morph6.Node.isPropertyAssignment(typeProperty)) return false;
896
- const initializer = typeProperty.getInitializer();
897
- if (!initializer) return false;
898
- if (import_ts_morph6.Node.isStringLiteral(initializer)) {
899
- return initializer.getLiteralValue().toLowerCase() === "birth";
900
- }
901
- if (import_ts_morph6.Node.isPropertyAccessExpression(initializer)) {
902
- return initializer.getName().toLowerCase() === "birth";
4092
+ function getEventType(configArg) {
4093
+ for (const propName of [TYPE_PROPERTY_NAME6, ID_PROPERTY_NAME2]) {
4094
+ const prop = configArg.getProperty(propName);
4095
+ if (!prop || !import_ts_morph6.Node.isPropertyAssignment(prop)) continue;
4096
+ const initializer = prop.getInitializer();
4097
+ if (!initializer) continue;
4098
+ if (import_ts_morph6.Node.isStringLiteral(initializer)) {
4099
+ return initializer.getLiteralValue().toLowerCase();
4100
+ }
4101
+ if (import_ts_morph6.Node.isPropertyAccessExpression(initializer)) {
4102
+ return initializer.getName().toLowerCase();
4103
+ }
903
4104
  }
904
- return false;
4105
+ return null;
905
4106
  }
906
4107
  function hasElementWithId(array3, id) {
907
4108
  for (const el of array3.getElements()) {
@@ -915,27 +4116,28 @@ function hasElementWithId(array3, id) {
915
4116
  }
916
4117
  return false;
917
4118
  }
918
- function ensureTopLevelFlagDefinition(configArg) {
919
- const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME2);
4119
+ function ensureTopLevelFlagDefinition(configArg, eventType) {
4120
+ const initializer = flagDefinitionInitializer(eventType);
4121
+ const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME3);
920
4122
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
921
4123
  const flagsInit = flagsProp.getInitializer();
922
4124
  if (flagsInit && import_ts_morph6.Node.isArrayLiteralExpression(flagsInit)) {
923
4125
  if (hasElementWithId(flagsInit, FLAG_ID)) return false;
924
- flagsInit.addElement(FLAG_DEFINITION_INITIALIZER);
4126
+ flagsInit.addElement(initializer);
925
4127
  return true;
926
4128
  }
927
4129
  return false;
928
4130
  }
929
4131
  configArg.addPropertyAssignment({
930
- name: FLAGS_PROPERTY_NAME2,
4132
+ name: FLAGS_PROPERTY_NAME3,
931
4133
  initializer: `[
932
- ${FLAG_DEFINITION_INITIALIZER}
4134
+ ${initializer}
933
4135
  ]`
934
4136
  });
935
4137
  return true;
936
4138
  }
937
4139
  function ensureActionOperationFlag(action, operation) {
938
- const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME2);
4140
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME3);
939
4141
  const entry = `{ id: '${FLAG_ID}', operation: '${operation}' }`;
940
4142
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
941
4143
  const flagsInit = flagsProp.getInitializer();
@@ -947,16 +4149,18 @@ function ensureActionOperationFlag(action, operation) {
947
4149
  return false;
948
4150
  }
949
4151
  action.addPropertyAssignment({
950
- name: FLAGS_PROPERTY_NAME2,
4152
+ name: FLAGS_PROPERTY_NAME3,
951
4153
  initializer: `[${entry}]`
952
4154
  });
953
4155
  return true;
954
4156
  }
955
- function processBirthConfig(configArg, relPath) {
4157
+ function processConfig(configArg, eventType, relPath) {
956
4158
  let changes = 0;
957
- if (ensureTopLevelFlagDefinition(configArg)) {
4159
+ if (ensureTopLevelFlagDefinition(configArg, eventType)) {
958
4160
  changes++;
959
- console.log(` [${relPath}] Added '${FLAG_ID}' to top-level flags`);
4161
+ console.log(
4162
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' to top-level flags`
4163
+ );
960
4164
  }
961
4165
  const actionsProp = configArg.getProperty(ACTIONS_PROPERTY_NAME4);
962
4166
  if (!actionsProp || !import_ts_morph6.Node.isPropertyAssignment(actionsProp)) return changes;
@@ -970,7 +4174,7 @@ function processBirthConfig(configArg, relPath) {
970
4174
  if (ensureActionOperationFlag(element, "add")) {
971
4175
  changes++;
972
4176
  console.log(
973
- ` [${relPath}] Added '${FLAG_ID}' add-flag to REGISTER action`
4177
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' add-flag to REGISTER action`
974
4178
  );
975
4179
  }
976
4180
  }
@@ -978,7 +4182,7 @@ function processBirthConfig(configArg, relPath) {
978
4182
  if (ensureActionOperationFlag(element, "remove")) {
979
4183
  changes++;
980
4184
  console.log(
981
- ` [${relPath}] Added '${FLAG_ID}' remove-flag to PRINT_CERTIFICATE action`
4185
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' remove-flag to PRINT_CERTIFICATE action`
982
4186
  );
983
4187
  }
984
4188
  }
@@ -1007,7 +4211,7 @@ function hasPrintCertificateAction(workqueue) {
1007
4211
  return false;
1008
4212
  }
1009
4213
  function addFlagToQueryClause(clause) {
1010
- const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME2);
4214
+ const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME3);
1011
4215
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
1012
4216
  const flagsInit = flagsProp.getInitializer();
1013
4217
  if (flagsInit && import_ts_morph6.Node.isObjectLiteralExpression(flagsInit)) {
@@ -1032,7 +4236,7 @@ function addFlagToQueryClause(clause) {
1032
4236
  }
1033
4237
  } else {
1034
4238
  clause.addPropertyAssignment({
1035
- name: FLAGS_PROPERTY_NAME2,
4239
+ name: FLAGS_PROPERTY_NAME3,
1036
4240
  initializer: `{ ${ANY_OF_PROPERTY_NAME2}: ['${FLAG_ID}'] }`
1037
4241
  });
1038
4242
  return true;
@@ -1076,8 +4280,9 @@ function processFile6(filePath, project) {
1076
4280
  if (args2.length === 0) continue;
1077
4281
  const configArg = args2[0];
1078
4282
  if (!import_ts_morph6.Node.isObjectLiteralExpression(configArg)) continue;
1079
- if (!isBirthConfig(configArg)) continue;
1080
- totalChanges += processBirthConfig(configArg, relPath);
4283
+ const eventType = getEventType(configArg);
4284
+ if (!eventType) continue;
4285
+ totalChanges += processConfig(configArg, eventType, relPath);
1081
4286
  }
1082
4287
  if (calleeName === DEFINE_WORKQUEUES_NAME2) {
1083
4288
  const args2 = call.getArguments();
@@ -1106,7 +4311,7 @@ function processFile6(filePath, project) {
1106
4311
  async function main6() {
1107
4312
  const srcDir = import_path6.default.join(process.cwd(), "src");
1108
4313
  console.log(
1109
- `Scanning for birth defineConfig and PRINT_CERTIFICATE workqueues in: ${srcDir}
4314
+ `Scanning for defineConfig and PRINT_CERTIFICATE workqueues in: ${srcDir}
1110
4315
  `
1111
4316
  );
1112
4317
  const project = new import_ts_morph6.Project({
@@ -1131,7 +4336,7 @@ async function main6() {
1131
4336
  }
1132
4337
  if (modifiedFiles.length === 0) {
1133
4338
  console.log(
1134
- "No birth configs or PRINT_CERTIFICATE workqueues found. Nothing to do."
4339
+ "No event configs or PRINT_CERTIFICATE workqueues found. Nothing to do."
1135
4340
  );
1136
4341
  return;
1137
4342
  }
@@ -1813,9 +5018,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1813
5018
  }
1814
5019
  return replacedCount;
1815
5020
  }
1816
- function resolveConfigChain(configObj, path23) {
5021
+ function resolveConfigChain(configObj, path28) {
1817
5022
  let current = configObj;
1818
- for (const key of path23) {
5023
+ for (const key of path28) {
1819
5024
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1820
5025
  const prop = current.getProperty(key);
1821
5026
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -2050,6 +5255,10 @@ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} rout
2050
5255
  var import_ts_morph11 = require("ts-morph");
2051
5256
  var import_path11 = __toESM(require("path"));
2052
5257
 
5258
+ // ../commons/src/scopes.deprecated.do-not-use.ts
5259
+ var z4 = __toESM(require("zod/v4"));
5260
+ var import_lodash = require("lodash");
5261
+
2053
5262
  // ../commons/src/scopes.ts
2054
5263
  var z3 = __toESM(require("zod/v4"));
2055
5264
  var qs = __toESM(require("qs"));
@@ -2118,11 +5327,13 @@ var scopeOptionsPlaceEvent = z3.object({
2118
5327
  event: scopeByEvent,
2119
5328
  placeOfEvent: JurisdictionFilter.optional()
2120
5329
  }).describe("Options applicable to all record scopes.");
2121
- var scopeOptionsDeclared = scopeOptionsPlaceEvent.extend({
5330
+ var scopeOptionsDeclaredOrNotified = scopeOptionsPlaceEvent.extend({
5331
+ notifiedIn: JurisdictionFilter.optional(),
5332
+ notifiedBy: UserFilter.optional(),
2122
5333
  declaredIn: JurisdictionFilter.optional(),
2123
5334
  declaredBy: UserFilter.optional()
2124
5335
  }).describe("Options applicable to actions that may take place after DECLARE");
2125
- var AllRecordScopeOptions = scopeOptionsDeclared.extend({
5336
+ var AllRecordScopeOptions = scopeOptionsDeclaredOrNotified.extend({
2126
5337
  registeredIn: JurisdictionFilter.optional(),
2127
5338
  registeredBy: UserFilter.optional()
2128
5339
  }).describe(
@@ -2160,6 +5371,8 @@ var ResolvedScopeOptionsPlaceEvent = z3.object({
2160
5371
  "Resolved options applicable to all record scopes, with location ID instead of jurisdiction filter."
2161
5372
  );
2162
5373
  var ResolvedScopeOptionsDeclared = ResolvedScopeOptionsPlaceEvent.extend({
5374
+ notifiedIn: UUID.nullish(),
5375
+ notifiedBy: z3.string().optional(),
2163
5376
  declaredIn: UUID.nullish(),
2164
5377
  declaredBy: z3.string().optional()
2165
5378
  }).describe(
@@ -2205,7 +5418,7 @@ var RecordScopeV2 = z3.discriminatedUnion("type", [
2205
5418
  }),
2206
5419
  z3.object({
2207
5420
  type: ScopesWithDeclaredOptions,
2208
- options: scopeOptionsDeclared.optional()
5421
+ options: scopeOptionsDeclaredOrNotified.optional()
2209
5422
  }),
2210
5423
  z3.object({
2211
5424
  type: ScopesWithFullOptions,
@@ -2226,12 +5439,14 @@ var SystemScopeType = z3.enum([
2226
5439
  "organisation.read-locations",
2227
5440
  "user.read",
2228
5441
  "user.create",
2229
- "user.edit"
5442
+ "user.edit",
5443
+ "user.search"
2230
5444
  ]);
2231
5445
  var UserScopeType = SystemScopeType.extract([
2232
5446
  "user.read",
2233
5447
  "user.create",
2234
- "user.edit"
5448
+ "user.edit",
5449
+ "user.search"
2235
5450
  ]);
2236
5451
  var ScopesWithRoleOption = UserScopeType.extract(["user.edit", "user.create"]);
2237
5452
  var UserScopeV2 = z3.discriminatedUnion("type", [
@@ -2240,7 +5455,7 @@ var UserScopeV2 = z3.discriminatedUnion("type", [
2240
5455
  options: AllUserScopeOptions.optional()
2241
5456
  }),
2242
5457
  z3.object({
2243
- type: UserScopeType.extract(["user.read"]),
5458
+ type: UserScopeType.extract(["user.read", "user.search"]),
2244
5459
  options: AccessLevelOptions.optional()
2245
5460
  })
2246
5461
  ]);
@@ -2292,8 +5507,8 @@ var flattenScope = (scope) => ({
2292
5507
  type: scope.type,
2293
5508
  ..."options" in scope ? scope.options : {}
2294
5509
  });
2295
- var unflattenScope = (input) => {
2296
- const { type, ...options } = input;
5510
+ var unflattenScope = (input3) => {
5511
+ const { type, ...options } = input3;
2297
5512
  return { type, options };
2298
5513
  };
2299
5514
  var EncodedScope2 = z3.string().brand("EncodedScope");
@@ -2306,22 +5521,30 @@ var encodeScope = (scope) => {
2306
5521
  encode: false
2307
5522
  });
2308
5523
  };
2309
- var decodeScope = (query) => {
2310
- const scope = qs.parse(query, {
5524
+ var decodedScopeCache = /* @__PURE__ */ new Map();
5525
+ var decodeScope = (encodedScope) => {
5526
+ if (decodedScopeCache.has(encodedScope)) {
5527
+ return decodedScopeCache.get(encodedScope);
5528
+ }
5529
+ const scope = qs.parse(encodedScope, {
2311
5530
  ignoreQueryPrefix: true,
2312
5531
  comma: true,
2313
5532
  allowDots: true
2314
5533
  });
2315
5534
  const unflattenedScope = unflattenScope(scope);
2316
- return Scope2.safeParse(unflattenedScope)?.data;
5535
+ const result = Scope2.safeParse(unflattenedScope)?.data;
5536
+ decodedScopeCache.set(encodedScope, result);
5537
+ return result;
2317
5538
  };
2318
5539
  var DEFAULT_SCOPE_OPTIONS = {
2319
5540
  placeOfEvent: JurisdictionFilter.enum.all,
2320
- accessLevel: JurisdictionFilter.enum.all
5541
+ accessLevel: JurisdictionFilter.enum.all,
5542
+ notifiedIn: JurisdictionFilter.enum.all,
5543
+ declaredIn: JurisdictionFilter.enum.all,
5544
+ registeredIn: JurisdictionFilter.enum.all
2321
5545
  };
2322
5546
 
2323
5547
  // ../commons/src/scopes.deprecated.do-not-use.ts
2324
- var z4 = __toESM(require("zod/v4"));
2325
5548
  var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2326
5549
  var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2327
5550
  var SearchScope = z4.object({
@@ -2555,6 +5778,74 @@ var legacyScopeToV2Scope = (v1Scope) => {
2555
5778
  }
2556
5779
  throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2557
5780
  };
5781
+ var MERGEABLE_USER_SCOPE_TYPES = ["user.create", "user.edit"];
5782
+ function isMergeableUserScopeType(type) {
5783
+ return MERGEABLE_USER_SCOPE_TYPES.includes(type);
5784
+ }
5785
+ function decodeLegacyScope(legacy) {
5786
+ const encoded = legacyScopeToV2Scope(legacy);
5787
+ const scope = decodeScope(encoded);
5788
+ if (!scope) {
5789
+ throw new Error(
5790
+ `Could not decode migrated scope from legacy '${legacy}' (encoded: '${encoded}').`
5791
+ );
5792
+ }
5793
+ return { legacy, scope };
5794
+ }
5795
+ function groupByType(entries) {
5796
+ return entries.reduce(
5797
+ (groups, entry) => ({
5798
+ ...groups,
5799
+ [entry.scope.type]: [...groups[entry.scope.type] ?? [], entry]
5800
+ }),
5801
+ {}
5802
+ );
5803
+ }
5804
+ function deduplicateEntries(entries) {
5805
+ return entries.filter(
5806
+ (entry, index) => entries.findIndex((e) => (0, import_lodash.isEqual)(e.scope, entry.scope)) === index
5807
+ );
5808
+ }
5809
+ function mergeEntries(type, entries) {
5810
+ const optionsList = entries.map(
5811
+ (e) => "options" in e.scope && e.scope.options ? e.scope.options : {}
5812
+ );
5813
+ const allKeys = optionsList.flatMap(
5814
+ (opts) => Object.keys(opts).filter((k) => opts[k] !== void 0)
5815
+ );
5816
+ const conflictKey = allKeys.find((key, i) => allKeys.indexOf(key) !== i);
5817
+ if (conflictKey) {
5818
+ const conflicting = entries.filter(
5819
+ (e) => conflictKey in ("options" in e.scope && e.scope.options || {})
5820
+ ).map((e) => JSON.stringify(e.legacy));
5821
+ throw new Error(
5822
+ `Cannot auto-merge two '${type}' scopes that both define '${conflictKey}'. Conflicting legacy scopes: [${conflicting.join(", ")}]. Resolve manually in roles.ts and re-run.`
5823
+ );
5824
+ }
5825
+ const mergedOptions = Object.assign({}, ...optionsList);
5826
+ const merged = Object.keys(mergedOptions).length > 0 ? { type, options: mergedOptions } : { type };
5827
+ const parsed = Scope2.safeParse(merged);
5828
+ if (!parsed.success) {
5829
+ throw new Error(
5830
+ `Merged '${type}' scope failed schema validation: ${parsed.error.message}. Legacy scopes: [${entries.map((e) => JSON.stringify(e.legacy)).join(", ")}].`
5831
+ );
5832
+ }
5833
+ return parsed.data;
5834
+ }
5835
+ function migrateLegacyScopesArrayToV2Scopes(legacyScopes) {
5836
+ const groups = groupByType(legacyScopes.map(decodeLegacyScope));
5837
+ return Object.entries(groups).flatMap(([type, entries]) => {
5838
+ const deduped = deduplicateEntries(entries);
5839
+ if (deduped.length <= 1) return deduped.map((e) => e.scope);
5840
+ if (!isMergeableUserScopeType(type)) {
5841
+ console.warn(
5842
+ `Multiple non-mergeable '${type}' scopes detected after dedup \u2014 kept all as-is. Legacy scopes: [${deduped.map((e) => JSON.stringify(e.legacy)).join(", ")}]. Review whether the duplication is intentional.`
5843
+ );
5844
+ return deduped.map((e) => e.scope);
5845
+ }
5846
+ return [mergeEntries(type, deduped)];
5847
+ });
5848
+ }
2558
5849
 
2559
5850
  // src/migrations/v2.0/migrate-scopes.ts
2560
5851
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
@@ -2592,57 +5883,65 @@ function resolveLegacyScopeFromElement(element) {
2592
5883
  }
2593
5884
  function migrateScopesArrays(rolesFilePath, project) {
2594
5885
  const sourceFile = project.getSourceFile(rolesFilePath);
2595
- if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
5886
+ if (!sourceFile) {
5887
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
5888
+ }
2596
5889
  let migratedCount = 0;
2597
5890
  let removedCount = 0;
5891
+ let mergedCount = 0;
2598
5892
  const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
5893
+ const relPath = import_path11.default.relative(process.cwd(), rolesFilePath);
2599
5894
  for (const scopesProp of scopesProperties) {
2600
5895
  const initializer = scopesProp.getInitializer();
2601
5896
  if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2602
- const elements = initializer.getElements();
2603
- for (let index = elements.length - 1; index >= 0; index--) {
2604
- const element = elements[index];
2605
- if (!import_ts_morph11.Node.isExpression(element)) continue;
5897
+ const rawTexts = [];
5898
+ const legacyStrings = [];
5899
+ let anyChange = false;
5900
+ for (const element of initializer.getElements()) {
2606
5901
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2607
5902
  if (scopeKey && !(scopeKey in SCOPES)) {
2608
5903
  console.warn(
2609
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
5904
+ ` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`
2610
5905
  );
2611
- initializer.removeElement(index);
2612
5906
  removedCount++;
5907
+ anyChange = true;
2613
5908
  continue;
2614
5909
  }
2615
5910
  const legacyScope = resolveLegacyScopeFromElement(element);
2616
5911
  if (!legacyScope) {
2617
5912
  console.warn(
2618
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
5913
+ ` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`
2619
5914
  );
5915
+ rawTexts.push(element.getText());
2620
5916
  continue;
2621
5917
  }
2622
- try {
2623
- const migratedScope = legacyScopeToV2Scope(legacyScope);
2624
- const scope = decodeScope(migratedScope);
2625
- if (!scope) {
2626
- console.warn(
2627
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2628
- );
2629
- continue;
2630
- }
2631
- element.replaceWithText(JSON.stringify(scope));
2632
- migratedCount++;
2633
- } catch (error) {
2634
- console.warn(
2635
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2636
- );
2637
- }
5918
+ legacyStrings.push(legacyScope);
5919
+ anyChange = true;
5920
+ }
5921
+ if (!anyChange) continue;
5922
+ let mergedScopes;
5923
+ try {
5924
+ mergedScopes = migrateLegacyScopesArrayToV2Scopes(legacyStrings);
5925
+ } catch (error4) {
5926
+ throw new Error(
5927
+ `[${relPath}] Failed to migrate scopes for role: ${error4 instanceof Error ? error4.message : String(error4)}`,
5928
+ { cause: error4 }
5929
+ );
2638
5930
  }
5931
+ migratedCount += legacyStrings.length;
5932
+ mergedCount += legacyStrings.length - mergedScopes.length;
5933
+ const outputElements = [
5934
+ ...rawTexts,
5935
+ ...mergedScopes.map((s) => JSON.stringify(s))
5936
+ ];
5937
+ scopesProp.setInitializer(`[${outputElements.join(", ")}]`);
2639
5938
  }
2640
5939
  if (removedCount > 0) {
2641
5940
  console.log(
2642
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
5941
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`
2643
5942
  );
2644
5943
  }
2645
- return { migratedCount, removedCount };
5944
+ return { migratedCount, removedCount, mergedCount };
2646
5945
  }
2647
5946
  function ensureScopesHelpersImport(rolesFilePath, project) {
2648
5947
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -2777,7 +6076,7 @@ async function main11() {
2777
6076
  return;
2778
6077
  }
2779
6078
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2780
- const { migratedCount, removedCount } = migrateScopesArrays(
6079
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(
2781
6080
  rolesFilePath,
2782
6081
  project
2783
6082
  );
@@ -2796,7 +6095,7 @@ async function main11() {
2796
6095
  }
2797
6096
  await sourceFile.save();
2798
6097
  console.log(
2799
- `Done. Migrated ${migratedCount} legacy scope(s), removed ${removedCount} unknown SCOPES reference(s), wrapped ${wrappedScopesCount} scope array(s) with defineScopes()${wrappedRoles ? ", wrapped roles with defineRoles()" : ""}${removedRoleType ? ", and removed Role type definition" : ""}${importChanged ? ". Updated toolkit/scopes imports." : "."}`
6098
+ `Done. Migrated ${migratedCount} legacy scope(s), merged ${mergedCount} AND-paired scope(s) into single v2 objects (privilege-escalation fix, see issue #12489), removed ${removedCount} unknown SCOPES reference(s), wrapped ${wrappedScopesCount} scope array(s) with defineScopes()${wrappedRoles ? ", wrapped roles with defineRoles()" : ""}${removedRoleType ? ", and removed Role type definition" : ""}${importChanged ? ". Updated toolkit/scopes imports." : "."}`
2800
6099
  );
2801
6100
  }
2802
6101
 
@@ -3544,9 +6843,9 @@ async function main17() {
3544
6843
  let parsed;
3545
6844
  try {
3546
6845
  parsed = JSON.parse(raw);
3547
- } catch (error) {
6846
+ } catch (error4) {
3548
6847
  console.warn(
3549
- ` [${PACKAGE_JSON_RELATIVE}] Failed to parse JSON \u2014 skipping update. ${error.message}`
6848
+ ` [${PACKAGE_JSON_RELATIVE}] Failed to parse JSON \u2014 skipping update. ${error4.message}`
3550
6849
  );
3551
6850
  return;
3552
6851
  }
@@ -3602,6 +6901,10 @@ var ACTION_PROPERTY_NAME2 = "action";
3602
6901
  var CONDITIONALS_PROPERTY_NAME = "conditionals";
3603
6902
  var TYPE_PROPERTY_NAME7 = "type";
3604
6903
  var SLUG_PROPERTY_NAME = "slug";
6904
+ var READ_ACTION_TYPE = "READ";
6905
+ var ACTION_TYPE_IMPORT_NAME = "ActionType";
6906
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
6907
+ var READ_ACTION_FALLBACK_INITIALIZER = `{ type: ${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE} }`;
3605
6908
  var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
3606
6909
  "READ",
3607
6910
  "DELETE",
@@ -3649,91 +6952,137 @@ function isUnsupportedActionType(action) {
3649
6952
  }
3650
6953
  return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3651
6954
  }
3652
- function migrateWorkqueueActions(workqueue, relPath) {
3653
- const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3654
- if (!actionsProperty || !import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3655
- return 0;
3656
- }
3657
- const actionsInitializer = actionsProperty.getInitializer();
3658
- if (!actionsInitializer || !import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3659
- return 0;
6955
+ function ensureValidAction(workqueue, relPath) {
6956
+ const workqueueLabel = getWorkqueueLabel(workqueue);
6957
+ const actionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
6958
+ if (actionProperty && import_ts_morph17.Node.isPropertyAssignment(actionProperty)) {
6959
+ const initializer = actionProperty.getInitializer();
6960
+ if (initializer && import_ts_morph17.Node.isObjectLiteralExpression(initializer)) {
6961
+ if (!isUnsupportedActionType(initializer)) {
6962
+ return { changed: false, usedReadFallback: false };
6963
+ }
6964
+ actionProperty.set({
6965
+ name: ACTION_PROPERTY_NAME2,
6966
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
6967
+ });
6968
+ console.log(
6969
+ ` [${relPath}] Replaced unsupported 'action' type with '${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE}' on workqueue '${workqueueLabel}'`
6970
+ );
6971
+ return { changed: true, usedReadFallback: true };
6972
+ }
3660
6973
  }
6974
+ workqueue.addPropertyAssignment({
6975
+ name: ACTION_PROPERTY_NAME2,
6976
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
6977
+ });
6978
+ console.log(
6979
+ ` [${relPath}] Added default 'action: ${READ_ACTION_FALLBACK_INITIALIZER}' to workqueue '${workqueueLabel}'`
6980
+ );
6981
+ return { changed: true, usedReadFallback: true };
6982
+ }
6983
+ function migrateWorkqueueActions(workqueue, relPath) {
3661
6984
  const workqueueLabel = getWorkqueueLabel(workqueue);
3662
- const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3663
- if (existingActionProperty) {
3664
- if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3665
- const existingActionInitializer = existingActionProperty.getInitializer();
3666
- if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3667
- const conditionalsProperty2 = existingActionInitializer.getProperty(
3668
- CONDITIONALS_PROPERTY_NAME
6985
+ const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
6986
+ let actionsArrayMigrated = false;
6987
+ if (actionsProperty && import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
6988
+ const actionsInitializer = actionsProperty.getInitializer();
6989
+ if (actionsInitializer && import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
6990
+ const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
6991
+ if (existingActionProperty) {
6992
+ if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
6993
+ const existingActionInitializer = existingActionProperty.getInitializer();
6994
+ if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
6995
+ const conditionalsProperty = existingActionInitializer.getProperty(
6996
+ CONDITIONALS_PROPERTY_NAME
6997
+ );
6998
+ if (conditionalsProperty) {
6999
+ conditionalsProperty.remove();
7000
+ console.log(
7001
+ ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
7002
+ );
7003
+ }
7004
+ }
7005
+ }
7006
+ actionsProperty.remove();
7007
+ console.log(
7008
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
7009
+ );
7010
+ actionsArrayMigrated = true;
7011
+ } else {
7012
+ const actionCandidates = actionsInitializer.getElements().filter(
7013
+ (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3669
7014
  );
3670
- if (conditionalsProperty2) {
3671
- conditionalsProperty2.remove();
7015
+ if (actionCandidates.length === 0) {
7016
+ actionsProperty.remove();
3672
7017
  console.log(
3673
- ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
7018
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3674
7019
  );
3675
- }
3676
- if (isUnsupportedActionType(existingActionInitializer)) {
3677
- existingActionProperty.remove();
3678
- console.log(
3679
- ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
7020
+ actionsArrayMigrated = true;
7021
+ } else {
7022
+ if (actionCandidates.length > 1) {
7023
+ const droppedCount = actionCandidates.length - 1;
7024
+ console.warn(
7025
+ ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
7026
+ );
7027
+ }
7028
+ const conditionalsProperty = actionCandidates[0].getProperty(
7029
+ CONDITIONALS_PROPERTY_NAME
3680
7030
  );
7031
+ if (conditionalsProperty) {
7032
+ conditionalsProperty.remove();
7033
+ console.log(
7034
+ ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
7035
+ );
7036
+ }
7037
+ if (isUnsupportedActionType(actionCandidates[0])) {
7038
+ actionsProperty.remove();
7039
+ console.log(
7040
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
7041
+ );
7042
+ actionsArrayMigrated = true;
7043
+ } else {
7044
+ const firstActionText = actionCandidates[0].getText();
7045
+ workqueue.addPropertyAssignment({
7046
+ name: ACTION_PROPERTY_NAME2,
7047
+ initializer: firstActionText
7048
+ });
7049
+ actionsProperty.remove();
7050
+ console.log(
7051
+ ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
7052
+ );
7053
+ actionsArrayMigrated = true;
7054
+ }
3681
7055
  }
3682
7056
  }
3683
7057
  }
3684
- actionsProperty.remove();
3685
- console.log(
3686
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3687
- );
3688
- return 1;
3689
7058
  }
3690
- const actionCandidates = actionsInitializer.getElements().filter(
3691
- (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3692
- );
3693
- if (actionCandidates.length === 0) {
3694
- actionsProperty.remove();
3695
- console.log(
3696
- ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3697
- );
3698
- return 1;
3699
- }
3700
- if (actionCandidates.length > 1) {
3701
- const droppedCount = actionCandidates.length - 1;
3702
- console.warn(
3703
- ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3704
- );
3705
- }
3706
- const conditionalsProperty = actionCandidates[0].getProperty(
3707
- CONDITIONALS_PROPERTY_NAME
7059
+ const fallback = ensureValidAction(workqueue, relPath);
7060
+ return {
7061
+ changed: actionsArrayMigrated || fallback.changed,
7062
+ usedReadFallback: fallback.usedReadFallback
7063
+ };
7064
+ }
7065
+ function ensureActionTypeImport(sourceFile) {
7066
+ const existingImport = sourceFile.getImportDeclaration(
7067
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2
3708
7068
  );
3709
- if (conditionalsProperty) {
3710
- conditionalsProperty.remove();
3711
- console.log(
3712
- ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3713
- );
3714
- }
3715
- if (isUnsupportedActionType(actionCandidates[0])) {
3716
- actionsProperty.remove();
3717
- console.log(
3718
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3719
- );
3720
- return 1;
7069
+ if (existingImport) {
7070
+ const alreadyImported = existingImport.getNamedImports().some((ni) => ni.getName() === ACTION_TYPE_IMPORT_NAME);
7071
+ if (!alreadyImported) {
7072
+ existingImport.addNamedImport(ACTION_TYPE_IMPORT_NAME);
7073
+ }
7074
+ return;
3721
7075
  }
3722
- const firstActionText = actionCandidates[0].getText();
3723
- workqueue.addPropertyAssignment({
3724
- name: ACTION_PROPERTY_NAME2,
3725
- initializer: firstActionText
7076
+ sourceFile.addImportDeclaration({
7077
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE2,
7078
+ namedImports: [ACTION_TYPE_IMPORT_NAME]
3726
7079
  });
3727
- actionsProperty.remove();
3728
- console.log(
3729
- ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3730
- );
3731
- return 1;
3732
7080
  }
3733
7081
  function processFile13(filePath, project) {
3734
7082
  const sourceFile = project.getSourceFile(filePath);
3735
7083
  if (!sourceFile) return 0;
3736
7084
  let migratedWorkqueues = 0;
7085
+ let needsActionTypeImport = false;
3737
7086
  const relPath = import_path18.default.relative(process.cwd(), filePath);
3738
7087
  const callExpressions = sourceFile.getDescendantsOfKind(
3739
7088
  import_ts_morph17.SyntaxKind.CallExpression
@@ -3749,9 +7098,14 @@ function processFile13(filePath, project) {
3749
7098
  if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3750
7099
  for (const element of workqueuesArg.getElements()) {
3751
7100
  if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3752
- migratedWorkqueues += migrateWorkqueueActions(element, relPath);
7101
+ const result = migrateWorkqueueActions(element, relPath);
7102
+ if (result.changed) migratedWorkqueues++;
7103
+ if (result.usedReadFallback) needsActionTypeImport = true;
3753
7104
  }
3754
7105
  }
7106
+ if (needsActionTypeImport) {
7107
+ ensureActionTypeImport(sourceFile);
7108
+ }
3755
7109
  return migratedWorkqueues;
3756
7110
  }
3757
7111
  async function main18() {
@@ -4086,7 +7440,7 @@ Saved ${handlerRelPath}.`);
4086
7440
  // src/migrations/v2.0/checkout-upstream-files.ts
4087
7441
  var import_child_process = require("child_process");
4088
7442
  var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
4089
- var UPSTREAM_BRANCH = "develop";
7443
+ var UPSTREAM_BRANCH = "release/2.0.0";
4090
7444
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
4091
7445
  var FILES_TO_CHECKOUT = [
4092
7446
  "src/analytics/analytics.ts",
@@ -4518,7 +7872,7 @@ var FUNCTION_NAME = "precalculateAdditionalAnalytics";
4518
7872
  var IMPORT_NAMES_TO_REMOVE = /* @__PURE__ */ new Set(["Event", "precalculateBirthEvent"]);
4519
7873
  var RETURN_EXPRESSION_TEXT = "declaration";
4520
7874
  function removeTargetedNamedImports(sourceFile) {
4521
- const log = [];
7875
+ const log2 = [];
4522
7876
  for (const importDecl of [...sourceFile.getImportDeclarations()]) {
4523
7877
  const namedImports = importDecl.getNamedImports();
4524
7878
  if (namedImports.length === 0) continue;
@@ -4528,13 +7882,13 @@ function removeTargetedNamedImports(sourceFile) {
4528
7882
  if (matched.length === 0) continue;
4529
7883
  const removedNames = matched.map((ni) => ni.getName());
4530
7884
  for (const ni of matched) ni.remove();
4531
- log.push(
7885
+ log2.push(
4532
7886
  `removed import(s) ${removedNames.join(", ")} from '${importDecl.getModuleSpecifierValue()}'`
4533
7887
  );
4534
7888
  const stillUsed = importDecl.getNamedImports().length > 0 || importDecl.getDefaultImport() || importDecl.getNamespaceImport();
4535
7889
  if (!stillUsed) importDecl.remove();
4536
7890
  }
4537
- return log;
7891
+ return log2;
4538
7892
  }
4539
7893
  function findPrecalculateFunction(sourceFile) {
4540
7894
  for (const fn of sourceFile.getFunctions()) {
@@ -4557,16 +7911,16 @@ function getFunctionBodyBlock(fn) {
4557
7911
  return initializer.getBody();
4558
7912
  }
4559
7913
  function simplifyPrecalculateFunction(sourceFile) {
4560
- const log = [];
7914
+ const log2 = [];
4561
7915
  const fn = findPrecalculateFunction(sourceFile);
4562
- if (!fn) return log;
7916
+ if (!fn) return log2;
4563
7917
  const body = getFunctionBodyBlock(fn);
4564
- if (!body || !import_ts_morph21.Node.isBlock(body)) return log;
7918
+ if (!body || !import_ts_morph21.Node.isBlock(body)) return log2;
4565
7919
  for (const statement of [...body.getStatements()]) {
4566
7920
  const references = statement.getDescendantsOfKind(import_ts_morph21.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
4567
7921
  if (references) {
4568
7922
  statement.remove();
4569
- log.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
7923
+ log2.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
4570
7924
  }
4571
7925
  }
4572
7926
  const remaining = body.getStatements();
@@ -4574,11 +7928,11 @@ function simplifyPrecalculateFunction(sourceFile) {
4574
7928
  const alreadyCorrect = last && import_ts_morph21.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
4575
7929
  if (!alreadyCorrect) {
4576
7930
  body.addStatements(`return ${RETURN_EXPRESSION_TEXT}`);
4577
- log.push(
7931
+ log2.push(
4578
7932
  `ensured '${FUNCTION_NAME}' ends with 'return ${RETURN_EXPRESSION_TEXT}'`
4579
7933
  );
4580
7934
  }
4581
- return log;
7935
+ return log2;
4582
7936
  }
4583
7937
  async function main24() {
4584
7938
  const cwd = process.cwd();
@@ -4609,8 +7963,8 @@ async function main24() {
4609
7963
  console.log(`[${ANALYTICS_FILE_REL}] already clean \u2014 nothing to do.`);
4610
7964
  return;
4611
7965
  }
4612
- for (const log of allLogs) {
4613
- console.log(` [${ANALYTICS_FILE_REL}] ${log}`);
7966
+ for (const log2 of allLogs) {
7967
+ console.log(` [${ANALYTICS_FILE_REL}] ${log2}`);
4614
7968
  }
4615
7969
  await sourceFile.save();
4616
7970
  console.log(`
@@ -4625,9 +7979,9 @@ var import_path24 = require("path");
4625
7979
  var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4626
7980
  var INFRASTRUCTURE_DIR = "infrastructure";
4627
7981
  var BASE_BRANCH = "release-v1.9";
4628
- function gitShowBytes(ref, path23) {
7982
+ function gitShowBytes(ref, path28) {
4629
7983
  try {
4630
- const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path23}`], {
7984
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path28}`], {
4631
7985
  cwd: process.cwd(),
4632
7986
  stdio: ["ignore", "pipe", "pipe"]
4633
7987
  });
@@ -4636,9 +7990,13 @@ function gitShowBytes(ref, path23) {
4636
7990
  return null;
4637
7991
  }
4638
7992
  }
4639
- async function main25() {
7993
+ async function main25({
7994
+ subdirs = []
7995
+ } = {}) {
7996
+ const pathspecs = subdirs.length > 0 ? subdirs.map((s) => `${INFRASTRUCTURE_DIR}/${s}/`) : [`${INFRASTRUCTURE_DIR}/`];
7997
+ const scopeLabel = pathspecs.map((p) => `'${p}'`).join(", ");
4640
7998
  console.log(
4641
- `Merging '${INFRASTRUCTURE_DIR}/' from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
7999
+ `Merging ${scopeLabel} from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4642
8000
  `
4643
8001
  );
4644
8002
  assertIsGitRepo();
@@ -4653,20 +8011,12 @@ async function main25() {
4653
8011
  const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4654
8012
  const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4655
8013
  const upstreamFiles = runGit(
4656
- [
4657
- "ls-tree",
4658
- "-r",
4659
- "--name-only",
4660
- "-z",
4661
- ref,
4662
- "--",
4663
- `${INFRASTRUCTURE_DIR}/`
4664
- ],
8014
+ ["ls-tree", "-r", "--name-only", "-z", ref, "--", ...pathspecs],
4665
8015
  { silent: true }
4666
8016
  ).split("\0").filter(Boolean);
4667
8017
  if (upstreamFiles.length === 0) {
4668
8018
  console.log(
4669
- ` No files found under '${INFRASTRUCTURE_DIR}/' on ${ref}. Nothing to merge.`
8019
+ ` No files found under ${scopeLabel} on ${ref}. Nothing to merge.`
4670
8020
  );
4671
8021
  return;
4672
8022
  }
@@ -4741,7 +8091,9 @@ async function main25() {
4741
8091
  var import_fs6 = require("fs");
4742
8092
  var import_path25 = require("path");
4743
8093
  var INFRASTRUCTURE_DIR2 = "infrastructure";
4744
- async function main26() {
8094
+ async function main26({
8095
+ keep = []
8096
+ } = {}) {
4745
8097
  const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4746
8098
  if (!(0, import_fs6.existsSync)(fullPath)) {
4747
8099
  console.log(
@@ -4749,24 +8101,152 @@ async function main26() {
4749
8101
  );
4750
8102
  return;
4751
8103
  }
4752
- console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4753
- `);
4754
8104
  assertIsGitRepo();
4755
- runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4756
- silent: true
8105
+ if (keep.length === 0) {
8106
+ console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
8107
+ `);
8108
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
8109
+ silent: true
8110
+ });
8111
+ console.log(
8112
+ ` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`
8113
+ );
8114
+ if ((0, import_fs6.existsSync)(fullPath)) {
8115
+ (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
8116
+ console.log(
8117
+ ` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`
8118
+ );
8119
+ }
8120
+ console.log(
8121
+ `
8122
+ Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
8123
+ );
8124
+ return;
8125
+ }
8126
+ const keepSet = new Set(keep);
8127
+ console.log(
8128
+ `Deleting contents of '${INFRASTRUCTURE_DIR2}/' except: ${[...keepSet].map((name) => `'${name}'`).join(", ")}
8129
+ `
8130
+ );
8131
+ const topLevelEntries = (0, import_fs6.readdirSync)(fullPath, { withFileTypes: true });
8132
+ let deleted = 0;
8133
+ for (const entry of topLevelEntries) {
8134
+ if (keepSet.has(entry.name)) {
8135
+ console.log(` Keeping '${INFRASTRUCTURE_DIR2}/${entry.name}'.`);
8136
+ continue;
8137
+ }
8138
+ const relPath = `${INFRASTRUCTURE_DIR2}/${entry.name}${entry.isDirectory() ? "/" : ""}`;
8139
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", relPath], { silent: true });
8140
+ const fullEntryPath = (0, import_path25.join)(fullPath, entry.name);
8141
+ if ((0, import_fs6.existsSync)(fullEntryPath)) {
8142
+ (0, import_fs6.rmSync)(fullEntryPath, { recursive: true, force: true });
8143
+ }
8144
+ console.log(` Deleted '${relPath}'.`);
8145
+ deleted++;
8146
+ }
8147
+ const presentNames = new Set(topLevelEntries.map((e) => e.name));
8148
+ const missingKeeps = [...keepSet].filter((name) => !presentNames.has(name));
8149
+ if (missingKeeps.length > 0) {
8150
+ console.warn(
8151
+ ` [warn] Requested to keep ${missingKeeps.map((n) => `'${n}'`).join(", ")} but they don't exist under '${INFRASTRUCTURE_DIR2}/'.`
8152
+ );
8153
+ }
8154
+ console.log(
8155
+ `
8156
+ Done. Deleted ${deleted} top-level entr${deleted === 1 ? "y" : "ies"}. Review the staged deletions with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
8157
+ );
8158
+ }
8159
+
8160
+ // src/migrations/v2.0/fix-accept-requested-registration-function-type.ts
8161
+ var import_ts_morph22 = require("ts-morph");
8162
+ var import_path26 = __toESM(require("path"));
8163
+ var TARGET_FUNCTION_NAME = "acceptRequestedRegistration";
8164
+ var ACTION_PARAMETER_NAME = "action";
8165
+ var OLD_TYPE = "ActionInput";
8166
+ var NEW_TYPE = "Extract<ActionInput, { type?: 'REGISTER' }>";
8167
+ function isAcceptRequestedRegistrationParameter(parameter) {
8168
+ const functionDeclaration = parameter.getFirstAncestorByKind(
8169
+ import_ts_morph22.SyntaxKind.FunctionDeclaration
8170
+ );
8171
+ if (functionDeclaration?.getName() === TARGET_FUNCTION_NAME) {
8172
+ return true;
8173
+ }
8174
+ const arrowFunction = parameter.getFirstAncestorByKind(
8175
+ import_ts_morph22.SyntaxKind.ArrowFunction
8176
+ );
8177
+ const variableDeclaration = arrowFunction?.getFirstAncestorByKind(
8178
+ import_ts_morph22.SyntaxKind.VariableDeclaration
8179
+ );
8180
+ return variableDeclaration?.getName() === TARGET_FUNCTION_NAME;
8181
+ }
8182
+ function processFile14(filePath, project) {
8183
+ const sourceFile = project.getSourceFile(filePath);
8184
+ if (!sourceFile) return 0;
8185
+ let updatedCount = 0;
8186
+ for (const parameter of sourceFile.getDescendantsOfKind(
8187
+ import_ts_morph22.SyntaxKind.Parameter
8188
+ )) {
8189
+ if (parameter.getName() !== ACTION_PARAMETER_NAME) {
8190
+ continue;
8191
+ }
8192
+ if (!isAcceptRequestedRegistrationParameter(parameter)) {
8193
+ continue;
8194
+ }
8195
+ const typeNode = parameter.getTypeNode();
8196
+ if (!typeNode || typeNode.getText() !== OLD_TYPE) {
8197
+ continue;
8198
+ }
8199
+ parameter.setType(NEW_TYPE);
8200
+ updatedCount++;
8201
+ console.log(
8202
+ ` [${import_path26.default.relative(process.cwd(), filePath)}] Updated '${ACTION_PARAMETER_NAME}' in ${TARGET_FUNCTION_NAME} to ${NEW_TYPE}`
8203
+ );
8204
+ }
8205
+ return updatedCount;
8206
+ }
8207
+ async function main27() {
8208
+ const srcDir = import_path26.default.join(process.cwd(), "src");
8209
+ console.log(`Scanning for ${TARGET_FUNCTION_NAME} in: ${srcDir}
8210
+ `);
8211
+ const project = new import_ts_morph22.Project({
8212
+ tsConfigFilePath: import_path26.default.resolve(srcDir, "../tsconfig.json"),
8213
+ skipAddingFilesFromTsConfig: false
4757
8214
  });
4758
- console.log(` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4759
- if ((0, import_fs6.existsSync)(fullPath)) {
4760
- (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4761
- console.log(` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`);
8215
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
8216
+ const filePath = sf.getFilePath();
8217
+ return filePath.includes("/src/") && !filePath.includes("/node_modules/");
8218
+ });
8219
+ let totalUpdated = 0;
8220
+ const modifiedFiles = [];
8221
+ for (const sourceFile of sourceFiles) {
8222
+ const filePath = sourceFile.getFilePath();
8223
+ const updated = processFile14(filePath, project);
8224
+ if (updated > 0) {
8225
+ totalUpdated += updated;
8226
+ modifiedFiles.push(filePath);
8227
+ }
8228
+ }
8229
+ if (modifiedFiles.length === 0) {
8230
+ console.log(
8231
+ `No '${ACTION_PARAMETER_NAME}: ${OLD_TYPE}' parameter in ${TARGET_FUNCTION_NAME} found. Nothing to do.`
8232
+ );
8233
+ return;
8234
+ }
8235
+ console.log(`
8236
+ Saving ${modifiedFiles.length} modified file(s)...`);
8237
+ for (const filePath of modifiedFiles) {
8238
+ const sourceFile = project.getSourceFileOrThrow(filePath);
8239
+ await sourceFile.save();
8240
+ console.log(` Saved: ${import_path26.default.relative(process.cwd(), filePath)}`);
4762
8241
  }
4763
8242
  console.log(
4764
8243
  `
4765
- Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
8244
+ Done. Updated ${totalUpdated} parameter type annotation(s) in ${TARGET_FUNCTION_NAME}.`
4766
8245
  );
4767
8246
  }
4768
8247
 
4769
8248
  // src/migrations/v2.0/index.ts
8249
+ var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
4770
8250
  async function runUpgrade(dockerSwarm) {
4771
8251
  await main18();
4772
8252
  await main();
@@ -4791,13 +8271,58 @@ async function runUpgrade(dockerSwarm) {
4791
8271
  await main22();
4792
8272
  await main23();
4793
8273
  await main24();
8274
+ await main27();
4794
8275
  await main17();
4795
8276
  if (dockerSwarm) {
4796
8277
  await main25();
4797
8278
  } else {
4798
- await main26();
8279
+ await main26({ keep: NON_SWARM_INFRA_SUBDIRS });
8280
+ await main25({ subdirs: NON_SWARM_INFRA_SUBDIRS });
8281
+ }
8282
+ }
8283
+
8284
+ // src/environment/index.ts
8285
+ var import_fs10 = require("fs");
8286
+ var import_path29 = require("path");
8287
+ var REQUIRED_REPOSITORY_DIRECTORIES = [
8288
+ ".github/workflows",
8289
+ "environments",
8290
+ "infrastructure"
8291
+ ];
8292
+ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
8293
+ const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
8294
+ (directory) => {
8295
+ try {
8296
+ return !(0, import_fs10.statSync)((0, import_path29.resolve)(repositoryRoot, directory)).isDirectory();
8297
+ } catch {
8298
+ return true;
8299
+ }
8300
+ }
8301
+ );
8302
+ if (missingDirectories.length > 0) {
8303
+ throw new Error(
8304
+ `The current directory is not a valid OpenCRVS country configuration repository. Missing required director${missingDirectories.length === 1 ? "y" : "ies"}: ${missingDirectories.join(", ")}`
8305
+ );
4799
8306
  }
4800
8307
  }
8308
+ async function runEnvironmentInit() {
8309
+ validateRepositoryStructure();
8310
+ await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
8311
+ }
8312
+ async function runEnvironmentUpdateWorkflows() {
8313
+ validateRepositoryStructure();
8314
+ const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
8315
+ await updateWorkflowEnvironments2();
8316
+ }
8317
+ async function runEnvironmentUsers() {
8318
+ validateRepositoryStructure();
8319
+ const { manageEnvironmentUsers: manageEnvironmentUsers2 } = await Promise.resolve().then(() => (init_users(), users_exports));
8320
+ await manageEnvironmentUsers2();
8321
+ }
8322
+ async function runEnvironmentSwarmToK8s() {
8323
+ validateRepositoryStructure();
8324
+ await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
8325
+ }
4801
8326
 
4802
8327
  // src/cli.ts
4803
8328
  var args = process.argv.slice(2);
@@ -4805,7 +8330,7 @@ var USAGE = `
4805
8330
  Usage: opencrvs <command>
4806
8331
 
4807
8332
  Commands:
4808
- environment init Initialise a new environment
8333
+ environment Manage deployment environments
4809
8334
  upgrade Upgrade an existing environment
4810
8335
  check-translations Check translation files for completeness
4811
8336
 
@@ -4824,7 +8349,7 @@ Options:
4824
8349
  'infrastructure/' directory is deleted (default).
4825
8350
  -h, --help Show this message.
4826
8351
  `.trim();
4827
- function main27() {
8352
+ function main28() {
4828
8353
  const command = args[0];
4829
8354
  if (!command || command === "--help" || command === "-h") {
4830
8355
  console.log(USAGE);
@@ -4844,7 +8369,7 @@ function main27() {
4844
8369
  process.exit(1);
4845
8370
  }
4846
8371
  }
4847
- function handleEnvironment() {
8372
+ async function handleEnvironment() {
4848
8373
  const subcommand = args[1];
4849
8374
  if (!subcommand || subcommand === "--help" || subcommand === "-h") {
4850
8375
  console.log(
@@ -4852,22 +8377,45 @@ function handleEnvironment() {
4852
8377
  Usage: opencrvs environment <subcommand>
4853
8378
 
4854
8379
  Subcommands:
4855
- init Initialise a new environment
8380
+ init Initialise a new environment
8381
+ update-workflows Update workflow environment options
8382
+ users Manage environment users
8383
+ swarm-to-k8s Migrate Docker Swarm configuration to Kubernetes
4856
8384
  `.trim()
4857
8385
  );
4858
8386
  process.exit(0);
4859
8387
  }
4860
8388
  switch (subcommand) {
4861
8389
  case "init":
4862
- console.log("Initialising environment...");
4863
- console.warn("This command is not implemented yet!");
4864
- process.exit(1);
4865
- break;
8390
+ return runEnvironmentCommand("initialisation", runEnvironmentInit);
8391
+ case "update-workflows":
8392
+ return runEnvironmentCommand(
8393
+ "workflow update",
8394
+ runEnvironmentUpdateWorkflows
8395
+ );
8396
+ case "users":
8397
+ return runEnvironmentCommand("user management", runEnvironmentUsers);
8398
+ case "swarm-to-k8s":
8399
+ return runEnvironmentCommand(
8400
+ "Swarm to Kubernetes migration",
8401
+ runEnvironmentSwarmToK8s
8402
+ );
4866
8403
  default:
4867
8404
  console.error(`Unknown subcommand: environment ${subcommand}`);
4868
8405
  process.exit(1);
4869
8406
  }
4870
8407
  }
8408
+ async function runEnvironmentCommand(operation, command) {
8409
+ try {
8410
+ await command();
8411
+ } catch (error4) {
8412
+ console.error(
8413
+ `Environment ${operation} failed:`,
8414
+ error4 instanceof Error ? error4.message : error4
8415
+ );
8416
+ process.exit(1);
8417
+ }
8418
+ }
4871
8419
  async function handleUpgrade() {
4872
8420
  const upgradeArgs = args.slice(1);
4873
8421
  if (upgradeArgs.includes("--help") || upgradeArgs.includes("-h")) {
@@ -4889,8 +8437,8 @@ async function handleUpgrade() {
4889
8437
  try {
4890
8438
  await runUpgrade(dockerSwarm);
4891
8439
  console.log("Upgrade completed successfully!");
4892
- } catch (error) {
4893
- console.error("Upgrade failed:", error);
8440
+ } catch (error4) {
8441
+ console.error("Upgrade failed:", error4);
4894
8442
  process.exit(1);
4895
8443
  }
4896
8444
  }
@@ -4899,4 +8447,4 @@ function handleCheckTranslations() {
4899
8447
  console.warn("This command is not implemented yet!");
4900
8448
  process.exit(1);
4901
8449
  }
4902
- main27();
8450
+ main28();