@opencrvs/toolkit 2.0.0-rc.cfdbeba → 2.0.0-rc.d00640f

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