@opencrvs/toolkit 2.2.0-rc.ac299dc → 2.2.0-rc.e6591c5

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 (249) hide show
  1. package/build.sh +17 -14
  2. package/dist/application-config/index.js +21 -11
  3. package/dist/authentication/index.d.ts +2 -1
  4. package/dist/authentication/index.js +20 -13
  5. package/dist/cli.js +2631 -377
  6. package/dist/commons/api/router.d.ts +263 -250
  7. package/dist/commons/application-config/index.d.ts +3 -3
  8. package/dist/commons/conditionals/conditionals.d.ts +4 -4
  9. package/dist/commons/conditionals/index.d.ts +1 -0
  10. package/dist/commons/conditionals/validate.d.ts +6 -1
  11. package/dist/commons/events/ActionConfig.d.ts +16 -23
  12. package/dist/commons/events/ActionDocument.d.ts +1 -0
  13. package/dist/commons/events/ActionInput.d.ts +4 -4
  14. package/dist/commons/events/ActionStatus.d.ts +2 -2
  15. package/dist/commons/events/ActionType.d.ts +2 -0
  16. package/dist/commons/events/AdvancedSearchConfig.d.ts +3 -6
  17. package/dist/commons/events/CompositeFieldValue.d.ts +5 -1
  18. package/dist/commons/events/CountryConfigQueryInput.d.ts +0 -18
  19. package/dist/commons/events/Draft.d.ts +34 -1
  20. package/dist/commons/events/EventConfig.d.ts +448 -1
  21. package/dist/commons/events/EventDocument.d.ts +2 -0
  22. package/dist/commons/events/EventIndex.d.ts +3 -6
  23. package/dist/commons/events/EventInput.d.ts +1 -0
  24. package/dist/commons/events/EventMetadata.d.ts +1 -1
  25. package/dist/commons/events/FieldConfig.d.ts +1 -1
  26. package/dist/commons/events/FieldTypeMapping.d.ts +17 -17
  27. package/dist/commons/events/Flag.d.ts +1 -7
  28. package/dist/commons/events/PlainDate.d.ts +6 -0
  29. package/dist/commons/events/WorkqueueConfig.d.ts +12 -27
  30. package/dist/commons/events/defineConfig.d.ts +7 -2
  31. package/dist/commons/events/event.d.ts +4 -1
  32. package/dist/commons/events/eventConfigValidation.d.ts +9 -0
  33. package/dist/commons/events/field.d.ts +5 -5
  34. package/dist/commons/events/index.d.ts +3 -0
  35. package/dist/commons/events/locations.d.ts +1 -1
  36. package/dist/commons/events/scopes.d.ts +2 -1
  37. package/dist/commons/events/state/flags.d.ts +1 -1
  38. package/dist/commons/events/state/index.d.ts +1 -0
  39. package/dist/commons/events/test.utils.d.ts +62 -7
  40. package/dist/commons/events/toNotificationForm.d.ts +17 -0
  41. package/dist/commons/events/utils.d.ts +59 -7
  42. package/dist/commons/users/Role.d.ts +23 -0
  43. package/dist/commons/users/User.d.ts +263 -0
  44. package/dist/commons/users/authentication.d.ts +67 -0
  45. package/dist/commons/users/index.d.ts +5 -0
  46. package/dist/commons/users/roleValidations.d.ts +15 -0
  47. package/dist/commons/users/scopes.d.ts +1402 -0
  48. package/dist/commons/users/userReferences.d.ts +176 -0
  49. package/dist/conditionals/index.js +5 -6
  50. package/dist/configurator/index.d.ts +24 -0
  51. package/dist/configurator/index.d.ts.map +1 -0
  52. package/dist/configurator/index.js +161 -0
  53. package/dist/configurator/layout.d.ts +29 -0
  54. package/dist/configurator/layout.d.ts.map +1 -0
  55. package/dist/configurator/layout.js +78 -0
  56. package/dist/configurator/paths.d.ts +13 -0
  57. package/dist/configurator/paths.d.ts.map +1 -0
  58. package/dist/configurator/paths.js +48 -0
  59. package/dist/configurator/server/environments.d.ts +20 -0
  60. package/dist/configurator/server/environments.d.ts.map +1 -0
  61. package/dist/configurator/server/environments.js +143 -0
  62. package/dist/configurator/server/files.d.ts +11 -0
  63. package/dist/configurator/server/files.d.ts.map +1 -0
  64. package/dist/configurator/server/files.js +67 -0
  65. package/dist/configurator/server/github.d.ts +56 -0
  66. package/dist/configurator/server/github.d.ts.map +1 -0
  67. package/dist/configurator/server/github.js +239 -0
  68. package/dist/configurator/server/plugin.d.ts +39 -0
  69. package/dist/configurator/server/plugin.d.ts.map +1 -0
  70. package/dist/configurator/server/plugin.js +298 -0
  71. package/dist/configurator/server/seal.d.ts +2 -0
  72. package/dist/configurator/server/seal.d.ts.map +1 -0
  73. package/dist/configurator/server/seal.js +36 -0
  74. package/dist/configurator/server/sshKeys.d.ts +5 -0
  75. package/dist/configurator/server/sshKeys.d.ts.map +1 -0
  76. package/dist/configurator/server/sshKeys.js +28 -0
  77. package/dist/configurator/server/start.d.ts +12 -0
  78. package/dist/configurator/server/start.d.ts.map +1 -0
  79. package/dist/configurator/server/start.js +91 -0
  80. package/dist/configurator/testing.d.ts +11 -0
  81. package/dist/configurator/testing.d.ts.map +1 -0
  82. package/dist/configurator/testing.js +74 -0
  83. package/dist/configurator/ui/bindings/bindings.d.ts +35 -0
  84. package/dist/configurator/ui/bindings/bindings.d.ts.map +1 -0
  85. package/dist/configurator/ui/bindings/bindings.js +5 -0
  86. package/dist/configurator/ui/bindings/parsers.d.ts +7 -0
  87. package/dist/configurator/ui/bindings/parsers.d.ts.map +1 -0
  88. package/dist/configurator/ui/bindings/parsers.js +85 -0
  89. package/dist/configurator/ui/form/users.d.ts +11 -0
  90. package/dist/configurator/ui/form/users.d.ts.map +1 -0
  91. package/dist/configurator/ui/form/users.js +33 -0
  92. package/dist/configurator/ui/plan/dependencyHosts.d.ts +2 -0
  93. package/dist/configurator/ui/plan/dependencyHosts.d.ts.map +1 -0
  94. package/dist/configurator/ui/plan/dependencyHosts.js +36 -0
  95. package/dist/configurator/ui/plan/templateValues.d.ts +11 -0
  96. package/dist/configurator/ui/plan/templateValues.d.ts.map +1 -0
  97. package/dist/configurator/ui/plan/templateValues.js +70 -0
  98. package/dist/configurator/workflows.d.ts +54 -0
  99. package/dist/configurator/workflows.d.ts.map +1 -0
  100. package/dist/configurator/workflows.js +161 -0
  101. package/dist/configurator-assets/forms/bindings.yml +265 -0
  102. package/dist/configurator-assets/templates/README.md +18 -0
  103. package/dist/configurator-assets/templates/charts-values/dependencies/values.override.yaml +4 -0
  104. package/dist/configurator-assets/templates/charts-values/dependencies/values.yaml +96 -0
  105. package/dist/configurator-assets/templates/charts-values/opencrvs-services/values.override.yaml +4 -0
  106. package/dist/configurator-assets/templates/charts-values/opencrvs-services/values.yaml +83 -0
  107. package/dist/configurator-assets/templates/charts-values/opentelemetry/values.yaml +102 -0
  108. package/dist/configurator-assets/templates/charts-values/traefik/values.override.yaml +4 -0
  109. package/dist/configurator-assets/templates/charts-values/traefik/values.yaml +130 -0
  110. package/dist/configurator-assets/templates/inventory/inventory.template.yml +98 -0
  111. package/dist/configurator-assets/ui/apple-touch-icon.png +0 -0
  112. package/dist/configurator-assets/ui/assets/index-CaqYFJUk.css +6 -0
  113. package/dist/configurator-assets/ui/assets/index-DU1Y6E0b.js +169 -0
  114. package/dist/configurator-assets/ui/assets/opencrvs-logo-sIjz08HT.svg +1 -0
  115. package/dist/configurator-assets/ui/assets/poppins-400-BwTUGeWf.woff2 +0 -0
  116. package/dist/configurator-assets/ui/assets/poppins-500-CWICHMj6.woff2 +0 -0
  117. package/dist/configurator-assets/ui/assets/poppins-600-DJVo7c07.woff2 +0 -0
  118. package/dist/configurator-assets/ui/assets/poppins-700-g9MkRaG0.woff2 +0 -0
  119. package/dist/configurator-assets/ui/favicon-32x32.png +0 -0
  120. package/dist/configurator-assets/ui/index.html +25 -0
  121. package/dist/environment/custom-types.d.ts +1 -0
  122. package/dist/environment/custom-types.d.ts.map +1 -1
  123. package/dist/environment/derived-variables.d.ts +18 -4
  124. package/dist/environment/derived-variables.d.ts.map +1 -1
  125. package/dist/environment/derived-variables.js +20 -4
  126. package/dist/environment/questions.d.ts +42 -9
  127. package/dist/environment/questions.d.ts.map +1 -1
  128. package/dist/environment/questions.js +71 -48
  129. package/dist/environment/registry.d.ts +15 -0
  130. package/dist/environment/registry.d.ts.map +1 -0
  131. package/dist/environment/registry.js +112 -0
  132. package/dist/environment/setup-environment.d.ts.map +1 -1
  133. package/dist/environment/setup-environment.js +145 -25
  134. package/dist/environment/templates.d.ts.map +1 -1
  135. package/dist/events/index.js +826 -210
  136. package/dist/migrations/add-notify-config.d.ts +40 -0
  137. package/dist/migrations/add-notify-config.d.ts.map +1 -0
  138. package/dist/migrations/add-notify-config.js +249 -0
  139. package/dist/migrations/index.d.ts +9 -0
  140. package/dist/migrations/index.d.ts.map +1 -0
  141. package/dist/migrations/index.js +1306 -0
  142. package/dist/migrations/move-declaration-to-declare-action.d.ts +38 -0
  143. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -0
  144. package/dist/migrations/move-declaration-to-declare-action.js +260 -0
  145. package/dist/migrations/{add-translations.d.ts → persistent/add-translations.d.ts} +1 -1
  146. package/dist/migrations/persistent/add-translations.d.ts.map +1 -0
  147. package/dist/migrations/{add-translations.js → persistent/add-translations.js} +2 -2
  148. package/dist/migrations/persistent/check-upgrade-path.d.ts +36 -0
  149. package/dist/migrations/persistent/check-upgrade-path.d.ts.map +1 -0
  150. package/dist/migrations/persistent/check-upgrade-path.js +105 -0
  151. package/dist/migrations/persistent/update-toolkit-dependency.d.ts +7 -0
  152. package/dist/migrations/persistent/update-toolkit-dependency.d.ts.map +1 -0
  153. package/dist/migrations/persistent/update-toolkit-dependency.js +77 -0
  154. package/dist/migrations/{v2.2/read-declaration-through-helper.d.ts → read-declaration-through-helper.d.ts} +1 -1
  155. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -0
  156. package/dist/migrations/{v2.2/read-declaration-through-helper.js → read-declaration-through-helper.js} +4 -62
  157. package/dist/migrations/replace-incomplete-flag.d.ts +26 -0
  158. package/dist/migrations/replace-incomplete-flag.d.ts.map +1 -0
  159. package/dist/migrations/replace-incomplete-flag.js +126 -0
  160. package/dist/migrations/resolve-versioned-event-config.d.ts +56 -0
  161. package/dist/migrations/resolve-versioned-event-config.d.ts.map +1 -0
  162. package/dist/migrations/resolve-versioned-event-config.js +353 -0
  163. package/dist/migrations/utils.d.ts +61 -0
  164. package/dist/migrations/utils.d.ts.map +1 -0
  165. package/dist/migrations/utils.js +218 -0
  166. package/dist/notification/index.js +722 -82
  167. package/dist/roles/index.d.ts +2 -0
  168. package/dist/roles/index.d.ts.map +1 -0
  169. package/dist/roles/index.js +730 -0
  170. package/dist/scopes/index.d.ts +54 -94
  171. package/dist/scopes/index.js +15 -12
  172. package/dist/templates/charts-values/dependencies/values.yaml +5 -2
  173. package/dist/templates/charts-values/opencrvs-services/values.yaml +5 -7
  174. package/dist/templates/charts-values/traefik/values.yaml +2 -0
  175. package/dist/verify/endpoints.d.ts +11 -0
  176. package/dist/verify/endpoints.d.ts.map +1 -1
  177. package/dist/verify/endpoints.js +21 -27
  178. package/opencrvs-toolkit-2.2.0-rc.e6591c5.tgz +0 -0
  179. package/package.json +17 -4
  180. package/tsconfig.build.json +11 -1
  181. package/tsconfig.build.tsbuildinfo +1 -1
  182. package/tsconfig.json +15 -6
  183. package/dist/migrations/add-translations.d.ts.map +0 -1
  184. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts +0 -3
  185. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts.map +0 -1
  186. package/dist/migrations/v2.1/add-explicit-correction-flags.js +0 -234
  187. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +0 -3
  188. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +0 -1
  189. package/dist/migrations/v2.1/add-recovery-link-notifications.js +0 -511
  190. package/dist/migrations/v2.1/enable-telemetry.d.ts +0 -3
  191. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +0 -1
  192. package/dist/migrations/v2.1/enable-telemetry.js +0 -455
  193. package/dist/migrations/v2.1/index.d.ts +0 -6
  194. package/dist/migrations/v2.1/index.d.ts.map +0 -1
  195. package/dist/migrations/v2.1/index.js +0 -50
  196. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +0 -17
  197. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +0 -1
  198. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +0 -348
  199. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +0 -2
  200. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +0 -1
  201. package/dist/migrations/v2.1/remove-metabase-package-installs.js +0 -161
  202. package/dist/migrations/v2.1/remove-sentry.d.ts +0 -3
  203. package/dist/migrations/v2.1/remove-sentry.d.ts.map +0 -1
  204. package/dist/migrations/v2.1/remove-sentry.js +0 -354
  205. package/dist/migrations/v2.1/rename-trigger-paths.d.ts +0 -3
  206. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +0 -1
  207. package/dist/migrations/v2.1/rename-trigger-paths.js +0 -216
  208. package/dist/migrations/v2.1/template-files.d.ts +0 -8
  209. package/dist/migrations/v2.1/template-files.d.ts.map +0 -1
  210. package/dist/migrations/v2.1/template-files.js +0 -49
  211. package/dist/migrations/v2.1/upgrade-tilt.d.ts +0 -11
  212. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +0 -1
  213. package/dist/migrations/v2.1/upgrade-tilt.js +0 -139
  214. package/dist/migrations/v2.2/index.d.ts +0 -6
  215. package/dist/migrations/v2.2/index.d.ts.map +0 -1
  216. package/dist/migrations/v2.2/index.js +0 -456
  217. package/dist/migrations/v2.2/read-declaration-through-helper.d.ts.map +0 -1
  218. package/dist/templates/countryconfig-template/.tiltignore +0 -1
  219. package/dist/templates/countryconfig-template/Dockerfile.assets +0 -7
  220. package/dist/templates/countryconfig-template/Tiltfile +0 -112
  221. package/dist/templates/countryconfig-template/assets/README.md +0 -1
  222. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +0 -61
  223. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +0 -455
  224. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +0 -168
  225. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +0 -67
  226. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +0 -168
  227. package/dist/templates/countryconfig-template/assets/metabase/README.md +0 -34
  228. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +0 -36
  229. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +0 -46
  230. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +0 -27737
  231. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +0 -21
  232. package/dist/templates/countryconfig-template/assets/metabase/package.json +0 -13
  233. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +0 -108
  234. package/dist/templates/countryconfig-template/assets/metabase/run.sh +0 -120
  235. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +0 -40
  236. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +0 -135
  237. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +0 -108
  238. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +0 -50
  239. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +0 -35
  240. package/dist/templates/countryconfig-template/tilt/common.tilt +0 -145
  241. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +0 -15
  242. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +0 -56
  243. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +0 -21
  244. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +0 -38
  245. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +0 -17
  246. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +0 -16
  247. package/dist/templates/countryconfig-template/tilt/lib.tilt +0 -95
  248. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +0 -136
  249. package/opencrvs-toolkit-2.2.0-rc.ac299dc.tgz +0 -0
package/dist/cli.js CHANGED
@@ -32,13 +32,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
 
33
33
  // src/environment/paths.ts
34
34
  function getEnvironmentInventoryPath(environment) {
35
- return (0, import_path3.join)("environments", environment, INVENTORY_FILE_NAME);
35
+ return (0, import_path10.join)("environments", environment, INVENTORY_FILE_NAME);
36
36
  }
37
37
  function findOldInventoryFiles() {
38
- return glob.sync((0, import_path3.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
38
+ return glob.sync((0, import_path10.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
39
39
  }
40
40
  function getEnvironmentNameFromOldInventoryPath(filePath) {
41
- return (0, import_path3.basename)(filePath, ".yml");
41
+ return (0, import_path10.basename)(filePath, ".yml");
42
42
  }
43
43
  function assertNoOldInventoryLayout() {
44
44
  if (findOldInventoryFiles().length === 0) {
@@ -51,13 +51,13 @@ function assertNoOldInventoryLayout() {
51
51
  ].join(" ")
52
52
  );
53
53
  }
54
- var import_path3, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
54
+ var import_path10, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
55
55
  var init_paths = __esm({
56
56
  "src/environment/paths.ts"() {
57
57
  "use strict";
58
- import_path3 = require("path");
58
+ import_path10 = require("path");
59
59
  glob = __toESM(require("glob"));
60
- OLD_INVENTORY_DIR = (0, import_path3.join)(
60
+ OLD_INVENTORY_DIR = (0, import_path10.join)(
61
61
  "infrastructure",
62
62
  "server-setup",
63
63
  "inventory"
@@ -403,15 +403,17 @@ var init_derived_variables = __esm({
403
403
  scope: "ENVIRONMENT"
404
404
  },
405
405
  {
406
- name: "MINIO_ROOT_USER",
407
- valueLabel: "MINIO_ROOT_USER",
406
+ name: "S3_ADMIN_ACCESS_KEY",
407
+ valueLabel: "S3_ADMIN_ACCESS_KEY",
408
+ legacyValueLabel: "MINIO_ROOT_USER",
408
409
  valueType: "SECRET",
409
410
  type: "disabled",
410
411
  scope: "ENVIRONMENT"
411
412
  },
412
413
  {
413
- name: "MINIO_ROOT_PASSWORD",
414
- valueLabel: "MINIO_ROOT_PASSWORD",
414
+ name: "S3_ADMIN_SECRET_KEY",
415
+ valueLabel: "S3_ADMIN_SECRET_KEY",
416
+ legacyValueLabel: "MINIO_ROOT_PASSWORD",
415
417
  valueType: "SECRET",
416
418
  type: "disabled",
417
419
  scope: "ENVIRONMENT"
@@ -506,6 +508,20 @@ var init_derived_variables = __esm({
506
508
  valueType: "VARIABLE",
507
509
  type: "disabled",
508
510
  scope: "ENVIRONMENT"
511
+ },
512
+ {
513
+ name: "MONITORING_ENABLED",
514
+ valueLabel: "MONITORING_ENABLED",
515
+ valueType: "VARIABLE",
516
+ type: "disabled",
517
+ scope: "ENVIRONMENT"
518
+ },
519
+ {
520
+ name: "RUSTFS_HOST_DATA_PATH",
521
+ valueLabel: "RUSTFS_HOST_DATA_PATH",
522
+ valueType: "VARIABLE",
523
+ type: "disabled",
524
+ scope: "ENVIRONMENT"
509
525
  }
510
526
  ];
511
527
  }
@@ -525,7 +541,7 @@ function findExistingValue(name, type, scope, existingValues) {
525
541
  );
526
542
  }
527
543
  function readYamlFile(filePath) {
528
- const fileContent = import_fs2.default.readFileSync(filePath, "utf8");
544
+ const fileContent = import_fs4.default.readFileSync(filePath, "utf8");
529
545
  return yaml.load(fileContent);
530
546
  }
531
547
  function writeYamlFile(filePath, data) {
@@ -538,16 +554,16 @@ function writeYamlFile(filePath, data) {
538
554
  noRefs: true,
539
555
  sortKeys: false
540
556
  });
541
- import_fs2.default.writeFileSync(filePath, yamlContent, "utf8");
542
- } catch (error3) {
543
- throw new Error(`Failed to write inventory file: ${error3}`);
557
+ import_fs4.default.writeFileSync(filePath, yamlContent, "utf8");
558
+ } catch (error2) {
559
+ throw new Error(`Failed to write inventory file: ${error2}`);
544
560
  }
545
561
  }
546
- var import_fs2, yaml;
562
+ var import_fs4, yaml;
547
563
  var init_utils = __esm({
548
564
  "src/environment/utils.ts"() {
549
565
  "use strict";
550
- import_fs2 = __toESM(require("fs"));
566
+ import_fs4 = __toESM(require("fs"));
551
567
  yaml = __toESM(require("js-yaml"));
552
568
  }
553
569
  });
@@ -596,29 +612,29 @@ function extractWorkerNodes(data) {
596
612
  return worker_hosts;
597
613
  }
598
614
  function copyChartsValues(env, values) {
599
- const srcDir = import_path4.default.resolve(__dirname, "templates", "charts-values");
600
- const destDir = import_path4.default.resolve(process.cwd(), "environments", env);
601
- import_fs3.default.mkdirSync(destDir, { recursive: true });
615
+ const srcDir = import_path11.default.resolve(__dirname, "templates", "charts-values");
616
+ const destDir = import_path11.default.resolve(process.cwd(), "environments", env);
617
+ import_fs5.default.mkdirSync(destDir, { recursive: true });
602
618
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
603
619
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
604
620
  values["opencrvs_environment"] = env;
605
621
  function copyRecursive(src, dest) {
606
- const stat = import_fs3.default.statSync(src);
622
+ const stat = import_fs5.default.statSync(src);
607
623
  if (stat.isDirectory()) {
608
- import_fs3.default.mkdirSync(dest, { recursive: true });
609
- for (const item of import_fs3.default.readdirSync(src)) {
610
- copyRecursive(import_path4.default.join(src, item), import_path4.default.join(dest, item));
624
+ import_fs5.default.mkdirSync(dest, { recursive: true });
625
+ for (const item of import_fs5.default.readdirSync(src)) {
626
+ copyRecursive(import_path11.default.join(src, item), import_path11.default.join(dest, item));
611
627
  }
612
628
  } else {
613
- const content = import_fs3.default.readFileSync(src, "utf8");
629
+ const content = import_fs5.default.readFileSync(src, "utf8");
614
630
  const template = import_handlebars.default.compile(content);
615
631
  const updated = template(values);
616
632
  const isOverridesFile = dest.endsWith("override.yaml");
617
- if (isOverridesFile && import_fs3.default.existsSync(dest)) {
633
+ if (isOverridesFile && import_fs5.default.existsSync(dest)) {
618
634
  log(` \u21B7 Skipped existing overrides file: ${dest}`);
619
635
  return;
620
636
  }
621
- import_fs3.default.writeFileSync(dest, updated, "utf8");
637
+ import_fs5.default.writeFileSync(dest, updated, "utf8");
622
638
  log(` \u2713 Created: ${dest}`);
623
639
  }
624
640
  }
@@ -629,29 +645,32 @@ function copyChartsValues(env, values) {
629
645
  `);
630
646
  }
631
647
  function generateInventory(env, values) {
632
- const templatePath = import_path4.default.join(
648
+ const templatePath = import_path11.default.join(
633
649
  __dirname,
634
650
  "templates",
635
651
  "inventory",
636
652
  "inventory.template.yml"
637
653
  );
638
- const outputPath = import_path4.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
639
- const templateFile = import_fs3.default.readFileSync(templatePath, "utf-8");
654
+ const outputPath = import_path11.default.resolve(
655
+ process.cwd(),
656
+ getEnvironmentInventoryPath(env)
657
+ );
658
+ const templateFile = import_fs5.default.readFileSync(templatePath, "utf-8");
640
659
  const template = import_handlebars.default.compile(templateFile);
641
660
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
642
661
  const updated = template(values);
643
- import_fs3.default.mkdirSync(import_path4.default.dirname(outputPath), { recursive: true });
644
- import_fs3.default.writeFileSync(outputPath, updated);
662
+ import_fs5.default.mkdirSync(import_path11.default.dirname(outputPath), { recursive: true });
663
+ import_fs5.default.writeFileSync(outputPath, updated);
645
664
  log(`
646
665
  \u2705 Generated inventory file at ${outputPath}
647
666
  `);
648
667
  }
649
- var import_fs3, import_path4, import_handlebars;
668
+ var import_fs5, import_path11, import_handlebars;
650
669
  var init_templates = __esm({
651
670
  "src/environment/templates.ts"() {
652
671
  "use strict";
653
- import_fs3 = __toESM(require("fs"));
654
- import_path4 = __toESM(require("path"));
672
+ import_fs5 = __toESM(require("fs"));
673
+ import_path11 = __toESM(require("path"));
655
674
  init_logger();
656
675
  init_paths();
657
676
  import_handlebars = __toESM(require("handlebars"));
@@ -682,16 +701,16 @@ var update_workflows_exports = {};
682
701
  __export(update_workflows_exports, {
683
702
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
684
703
  });
685
- function isDirectory(path7) {
704
+ function isDirectory(path15) {
686
705
  try {
687
- return (0, import_fs4.statSync)(path7).isDirectory();
706
+ return (0, import_fs6.statSync)(path15).isDirectory();
688
707
  } catch {
689
708
  return false;
690
709
  }
691
710
  }
692
711
  async function extractInfrastructureNames() {
693
- const files = glob2.sync((0, import_path5.join)("environments", "*", INVENTORY_FILE_NAME));
694
- const infraEnvironments = files.map((file) => (0, import_path5.basename)((0, import_path5.dirname)(file)));
712
+ const files = glob2.sync((0, import_path12.join)("environments", "*", INVENTORY_FILE_NAME));
713
+ const infraEnvironments = files.map((file) => (0, import_path12.basename)((0, import_path12.dirname)(file)));
695
714
  if (infraEnvironments.length === 0) {
696
715
  console.log(
697
716
  `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
@@ -704,9 +723,9 @@ async function extractInfrastructureNames() {
704
723
  async function extractEnvironmentNames() {
705
724
  const entries = await (0, import_promises.readdir)("environments");
706
725
  const environments = entries.filter((entry) => {
707
- const environmentPath = (0, import_path5.join)("environments", entry);
708
- const opencrvsServicesPath = (0, import_path5.join)(environmentPath, "opencrvs-services");
709
- return isDirectory(environmentPath) && (0, import_fs4.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
726
+ const environmentPath = (0, import_path12.join)("environments", entry);
727
+ const opencrvsServicesPath = (0, import_path12.join)(environmentPath, "opencrvs-services");
728
+ return isDirectory(environmentPath) && (0, import_fs6.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
710
729
  });
711
730
  if (environments.length === 0) {
712
731
  console.log(
@@ -731,12 +750,12 @@ function updateOptionsInYaml(content, envList) {
731
750
  async function updateWorkflows(envList, config) {
732
751
  const { workflows } = config;
733
752
  for (const workflowPath of workflows) {
734
- if (!(0, import_fs4.existsSync)(workflowPath)) {
753
+ if (!(0, import_fs6.existsSync)(workflowPath)) {
735
754
  log(` \u21B7 Skipped ${workflowPath} (not found in this repository)`);
736
755
  continue;
737
756
  }
738
757
  try {
739
- const fileContents = (0, import_fs4.readFileSync)(workflowPath, "utf8");
758
+ const fileContents = (0, import_fs6.readFileSync)(workflowPath, "utf8");
740
759
  const workflowData = yaml2.load(fileContents);
741
760
  if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
742
761
  throw new Error(
@@ -744,15 +763,15 @@ async function updateWorkflows(envList, config) {
744
763
  );
745
764
  }
746
765
  const updatedContent = updateOptionsInYaml(fileContents, envList);
747
- (0, import_fs4.writeFileSync)(workflowPath, updatedContent, "utf8");
766
+ (0, import_fs6.writeFileSync)(workflowPath, updatedContent, "utf8");
748
767
  log(` \u2713 Successfully updated ${workflowPath}`);
749
- } catch (error3) {
768
+ } catch (error2) {
750
769
  console.error(
751
770
  `
752
771
  \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`
753
772
  );
754
- console.error(`\u2717 Failed to update ${workflowPath}:`, error3);
755
- throw error3;
773
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error2);
774
+ throw error2;
756
775
  }
757
776
  }
758
777
  }
@@ -793,18 +812,18 @@ async function updateWorkflowEnvironments() {
793
812
  } else {
794
813
  log("\u2139\uFE0F No workflows were updated.");
795
814
  }
796
- } catch (error3) {
797
- console.error("\n\u274C Error updating workflows:", error3);
815
+ } catch (error2) {
816
+ console.error("\n\u274C Error updating workflows:", error2);
798
817
  process.exit(1);
799
818
  }
800
819
  }
801
- var import_promises, import_fs4, import_path5, glob2, yaml2;
820
+ var import_promises, import_fs6, import_path12, glob2, yaml2;
802
821
  var init_update_workflows = __esm({
803
822
  "src/environment/update-workflows.ts"() {
804
823
  "use strict";
805
824
  import_promises = require("fs/promises");
806
- import_fs4 = require("fs");
807
- import_path5 = require("path");
825
+ import_fs6 = require("fs");
826
+ import_path12 = require("path");
808
827
  glob2 = __toESM(require("glob"));
809
828
  yaml2 = __toESM(require("js-yaml"));
810
829
  init_logger();
@@ -862,7 +881,10 @@ function validateCIDRs(input4) {
862
881
  }
863
882
  return true;
864
883
  }
865
- var import_kleur2, notEmpty, dockerhubQuestions, githubQuestions, githubOtherQuestions, githubTokenQuestion, countryQuestions, infrastructureQuestions, staticSSLCertQuestions, backupQuestions, diskQuestions, databaseAndMonitoringQuestions, emailQuestions, sentryQuestions, metabaseAdminQuestions;
884
+ function validateRegistryHost(input4) {
885
+ return /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:[0-9]+)?$/i.test(input4) ? true : "Please enter a registry host without protocol or path (e.g. docker.io, ghcr.io)";
886
+ }
887
+ var import_kleur2, notEmpty, registryQuestions, githubQuestions, githubApprovalRequiredQuestion, githubApproversQuestion, githubOtherQuestions, githubTokenQuestion, countryQuestions, infrastructureQuestions, staticSSLCertQuestions, backupQuestions, diskQuestions, databaseAndMonitoringQuestions, emailQuestions, sentryQuestions, metabaseAdminQuestions;
866
888
  var init_questions = __esm({
867
889
  "src/environment/questions.ts"() {
868
890
  "use strict";
@@ -870,45 +892,59 @@ var init_questions = __esm({
870
892
  init_utils();
871
893
  init_git();
872
894
  notEmpty = (value) => value.toString().trim().length > 0 ? true : "Please enter a value";
873
- dockerhubQuestions = [
895
+ registryQuestions = [
896
+ {
897
+ name: "registryHost",
898
+ type: "text",
899
+ message: "What is the host of your container registry? (e.g. docker.io, ghcr.io)",
900
+ valueType: "VARIABLE",
901
+ valueLabel: "REGISTRY_HOST",
902
+ validate: validateRegistryHost,
903
+ initial: process.env.REGISTRY_HOST || "docker.io",
904
+ scope: "REPOSITORY"
905
+ },
874
906
  {
875
- name: "dockerhubOrganisation",
907
+ name: "registryOrganisation",
876
908
  type: "text",
877
- message: "What is the name of your Docker Hub organisation?",
909
+ message: "What is the name of your organisation (or user) in the container registry?",
878
910
  valueType: "SECRET",
879
- valueLabel: "DOCKERHUB_ACCOUNT",
911
+ valueLabel: "REGISTRY_ORGANISATION",
912
+ legacyValueLabel: "DOCKERHUB_ACCOUNT",
880
913
  validate: notEmpty,
881
- initial: process.env.DOCKER_ORGANISATION,
914
+ initial: process.env.REGISTRY_ORGANISATION,
882
915
  scope: "REPOSITORY"
883
916
  },
884
917
  {
885
- name: "dockerhubRepository",
918
+ name: "registryRepository",
886
919
  type: "text",
887
- message: "What is the name of your private Docker Hub repository?",
920
+ message: "What is the name of your private container repository?",
888
921
  valueType: "SECRET",
889
- valueLabel: "DOCKERHUB_REPO",
922
+ valueLabel: "REGISTRY_REPOSITORY",
923
+ legacyValueLabel: "DOCKERHUB_REPO",
890
924
  validate: notEmpty,
891
- initial: process.env.DOCKER_REPO,
925
+ initial: process.env.REGISTRY_REPOSITORY,
892
926
  scope: "REPOSITORY"
893
927
  },
894
928
  {
895
- name: "dockerhubUsername",
929
+ name: "registryUsername",
896
930
  type: "text",
897
- message: "What is the Docker Hub username the the target server should be using?",
931
+ message: "What is the container registry username the target server should be using?",
898
932
  valueType: "SECRET",
899
- valueLabel: "DOCKER_USERNAME",
933
+ valueLabel: "REGISTRY_USERNAME",
934
+ legacyValueLabel: "DOCKER_USERNAME",
900
935
  validate: notEmpty,
901
- initial: process.env.DOCKER_USERNAME,
936
+ initial: process.env.REGISTRY_USERNAME,
902
937
  scope: "REPOSITORY"
903
938
  },
904
939
  {
905
- name: "dockerhubToken",
940
+ name: "registryToken",
906
941
  type: "text",
907
- message: "What is the token of this Docker Hub account?",
942
+ message: "What is the token of this container registry account?",
908
943
  valueType: "SECRET",
909
- valueLabel: "DOCKER_TOKEN",
944
+ valueLabel: "REGISTRY_TOKEN",
945
+ legacyValueLabel: "DOCKER_TOKEN",
910
946
  validate: notEmpty,
911
- initial: process.env.DOCKER_TOKEN,
947
+ initial: process.env.REGISTRY_TOKEN,
912
948
  scope: "REPOSITORY"
913
949
  }
914
950
  ];
@@ -930,36 +966,38 @@ var init_questions = __esm({
930
966
  scope: "REPOSITORY"
931
967
  }
932
968
  ];
969
+ githubApprovalRequiredQuestion = {
970
+ name: "approvalRequired",
971
+ type: "select",
972
+ message: "Would you like to enable approvals process for GitHub action workflows?",
973
+ choices: [
974
+ {
975
+ title: "True",
976
+ value: "true"
977
+ },
978
+ {
979
+ title: "False",
980
+ value: "false"
981
+ }
982
+ ],
983
+ valueType: "VARIABLE",
984
+ validate: notEmpty,
985
+ valueLabel: "APPROVAL_REQUIRED",
986
+ initial: process.env.APPROVAL_REQUIRED,
987
+ scope: "ENVIRONMENT"
988
+ };
989
+ githubApproversQuestion = {
990
+ name: "githubApprovers",
991
+ type: "text",
992
+ message: "Please provide/update list of approvers?",
993
+ initial: process.env.GH_APPROVERS,
994
+ valueType: "VARIABLE",
995
+ valueLabel: "GH_APPROVERS",
996
+ scope: "REPOSITORY"
997
+ };
933
998
  githubOtherQuestions = [
934
- {
935
- name: "githubApprovers",
936
- type: "text",
937
- message: "Please provide/update list of production approvers?",
938
- initial: process.env.GH_APPROVERS,
939
- valueType: "VARIABLE",
940
- valueLabel: "GH_APPROVERS",
941
- scope: "REPOSITORY"
942
- },
943
- {
944
- name: "approvalRequired",
945
- type: "select",
946
- message: "Would you like to enable approvals process for GitHub action workflows?",
947
- choices: [
948
- {
949
- title: "True",
950
- value: "true"
951
- },
952
- {
953
- title: "False",
954
- value: "false"
955
- }
956
- ],
957
- valueType: "VARIABLE",
958
- validate: notEmpty,
959
- valueLabel: "APPROVAL_REQUIRED",
960
- initial: process.env.APPROVAL_REQUIRED,
961
- scope: "ENVIRONMENT"
962
- }
999
+ githubApprovalRequiredQuestion,
1000
+ githubApproversQuestion
963
1001
  ];
964
1002
  githubTokenQuestion = [
965
1003
  {
@@ -1367,6 +1405,87 @@ var init_questions_helper = __esm({
1367
1405
  }
1368
1406
  });
1369
1407
 
1408
+ // src/environment/registry.ts
1409
+ function registryApiHost(registry) {
1410
+ const host = registry.trim().toLowerCase();
1411
+ return host === "docker.io" || host === "index.docker.io" ? "registry-1.docker.io" : host;
1412
+ }
1413
+ function request(url, authorization) {
1414
+ return fetch(url, {
1415
+ headers: authorization ? { Authorization: authorization } : {},
1416
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1417
+ });
1418
+ }
1419
+ function failure(registry, step, response) {
1420
+ const reason = `${registry} ${step} responded with HTTP ${response.status}`;
1421
+ switch (response.status) {
1422
+ case 401:
1423
+ case 403:
1424
+ return {
1425
+ status: "invalid-credentials",
1426
+ reason: `${reason}. Check REGISTRY_USERNAME, REGISTRY_TOKEN, REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
1427
+ };
1428
+ case 404:
1429
+ return {
1430
+ status: "repository-not-found",
1431
+ reason: `${reason}. This is also the answer for an empty repository. Check REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
1432
+ };
1433
+ default:
1434
+ return { status: "unreachable", reason };
1435
+ }
1436
+ }
1437
+ async function validateRegistryCredentials(registry, organisation, repository, username, token) {
1438
+ if (!registry || !organisation || !repository || !username || !token) {
1439
+ return {
1440
+ status: "skipped",
1441
+ reason: "Some values are kept from existing GitHub secrets, which cannot be read back"
1442
+ };
1443
+ }
1444
+ const host = registryApiHost(registry);
1445
+ const name = `${organisation}/${repository}`;
1446
+ const basic = `Basic ${Buffer.from(`${username}:${token}`).toString("base64")}`;
1447
+ try {
1448
+ const challenge = (await request(`https://${host}/v2/`, void 0)).headers.get(
1449
+ "www-authenticate"
1450
+ ) ?? "";
1451
+ const realm = challenge.match(/realm="([^"]*)"/i)?.[1];
1452
+ const service = challenge.match(/service="([^"]*)"/i)?.[1];
1453
+ let authorization = basic;
1454
+ if (/^\s*bearer/i.test(challenge) && realm) {
1455
+ const tokenUrl = new URL(realm);
1456
+ if (service) {
1457
+ tokenUrl.searchParams.set("service", service);
1458
+ }
1459
+ tokenUrl.searchParams.set("scope", `repository:${name}:pull`);
1460
+ const login = await request(tokenUrl, basic);
1461
+ if (!login.ok) {
1462
+ return failure(registry, "login", login);
1463
+ }
1464
+ const body = await login.json();
1465
+ authorization = `Bearer ${body.token ?? body.access_token}`;
1466
+ }
1467
+ const path15 = name.split("/").map(encodeURIComponent).join("/");
1468
+ const response = await request(
1469
+ `https://${host}/v2/${path15}/tags/list?n=1`,
1470
+ authorization
1471
+ );
1472
+ return response.ok ? { status: "valid" } : failure(registry, `lookup of repository ${name}`, response);
1473
+ } catch (err) {
1474
+ if (!(err instanceof Error)) {
1475
+ return { status: "unreachable", reason: String(err) };
1476
+ }
1477
+ const cause = err.cause instanceof Error ? `: ${err.cause.message}` : "";
1478
+ return { status: "unreachable", reason: `${err.message}${cause}` };
1479
+ }
1480
+ }
1481
+ var REQUEST_TIMEOUT_MS;
1482
+ var init_registry = __esm({
1483
+ "src/environment/registry.ts"() {
1484
+ "use strict";
1485
+ REQUEST_TIMEOUT_MS = 1e4;
1486
+ }
1487
+ });
1488
+
1370
1489
  // src/environment/manage-users.ts
1371
1490
  async function inquirerPrompt(name, options) {
1372
1491
  const inquirer = await import("@inquirer/prompts");
@@ -1393,7 +1512,7 @@ function getCurrentUsername() {
1393
1512
  }
1394
1513
  function getCurrentUserSSHKeys() {
1395
1514
  const homeDir = os.homedir();
1396
- const sshDir = path4.join(homeDir, ".ssh");
1515
+ const sshDir = path11.join(homeDir, ".ssh");
1397
1516
  const keys = [];
1398
1517
  const keyFiles = [
1399
1518
  "id_rsa.pub",
@@ -1402,15 +1521,15 @@ function getCurrentUserSSHKeys() {
1402
1521
  "id_dsa.pub"
1403
1522
  ];
1404
1523
  for (const keyFile of keyFiles) {
1405
- const keyPath = path4.join(sshDir, keyFile);
1524
+ const keyPath = path11.join(sshDir, keyFile);
1406
1525
  try {
1407
- if (fs3.existsSync(keyPath)) {
1408
- const keyContent = fs3.readFileSync(keyPath, "utf8").trim();
1526
+ if (fs5.existsSync(keyPath)) {
1527
+ const keyContent = fs5.readFileSync(keyPath, "utf8").trim();
1409
1528
  if (keyContent) {
1410
1529
  keys.push(keyContent);
1411
1530
  }
1412
1531
  }
1413
- } catch (error3) {
1532
+ } catch (error2) {
1414
1533
  continue;
1415
1534
  }
1416
1535
  }
@@ -1624,7 +1743,7 @@ async function editUser(user) {
1624
1743
  return updatedUser;
1625
1744
  }
1626
1745
  async function manageUsers(inventoryPath) {
1627
- let users = fs3.existsSync(inventoryPath) ? parseInventoryFile(inventoryPath) : [];
1746
+ let users = fs5.existsSync(inventoryPath) ? parseInventoryFile(inventoryPath) : [];
1628
1747
  if (users.length > 0) {
1629
1748
  displayUserSummary(users);
1630
1749
  }
@@ -1716,7 +1835,7 @@ async function manageUsers(inventoryPath) {
1716
1835
  message: "Save changes end exit?",
1717
1836
  default: true
1718
1837
  });
1719
- if (confirmSave && fs3.existsSync(inventoryPath)) {
1838
+ if (confirmSave && fs5.existsSync(inventoryPath)) {
1720
1839
  updateInventoryFile(inventoryPath, users);
1721
1840
  console.log(`
1722
1841
  \u2705 Changes saved to ${inventoryPath}
@@ -1743,13 +1862,13 @@ async function manageUsers(inventoryPath) {
1743
1862
  }
1744
1863
  return users;
1745
1864
  }
1746
- var os, fs3, path4, input2, select2, confirm, editor, checkbox;
1865
+ var os, fs5, path11, input2, select2, confirm, editor, checkbox;
1747
1866
  var init_manage_users = __esm({
1748
1867
  "src/environment/manage-users.ts"() {
1749
1868
  "use strict";
1750
1869
  os = __toESM(require("os"));
1751
- fs3 = __toESM(require("fs"));
1752
- path4 = __toESM(require("path"));
1870
+ fs5 = __toESM(require("fs"));
1871
+ path11 = __toESM(require("path"));
1753
1872
  init_logger();
1754
1873
  init_utils();
1755
1874
  init_templates();
@@ -1781,6 +1900,7 @@ async function input3(options) {
1781
1900
  function questionToPrompt({
1782
1901
  valueType,
1783
1902
  valueLabel,
1903
+ legacyValueLabel,
1784
1904
  scope,
1785
1905
  ...promptOptions
1786
1906
  }) {
@@ -1844,6 +1964,12 @@ function getAnswers(existingValues) {
1844
1964
  });
1845
1965
  });
1846
1966
  }
1967
+ function getInitialValue(question, variable) {
1968
+ if (question.type === "select" && Array.isArray(question.choices)) {
1969
+ return getIndexFromChoices(question.choices, variable.value);
1970
+ }
1971
+ return variable.value;
1972
+ }
1847
1973
  async function promptAndStoreAnswer(questions, existingValues) {
1848
1974
  log("");
1849
1975
  const processedQuestions = questions.flatMap((question) => {
@@ -1861,14 +1987,22 @@ async function promptAndStoreAnswer(questions, existingValues) {
1861
1987
  questionWithVariableLabel.scope,
1862
1988
  existingValues
1863
1989
  );
1990
+ const legacyVariable = !existingVariable && questionWithVariableLabel.legacyValueLabel ? findExistingValue(
1991
+ questionWithVariableLabel.legacyValueLabel,
1992
+ "VARIABLE",
1993
+ questionWithVariableLabel.scope,
1994
+ existingValues
1995
+ ) : void 0;
1996
+ if (legacyVariable) {
1997
+ return {
1998
+ ...questionWithVariableLabel,
1999
+ message: `${questionWithVariableLabel.message} ${import_kleur4.default.gray(
2000
+ `(default taken from ${legacyVariable.name}, the previous name of this variable)`
2001
+ )}`,
2002
+ initial: getInitialValue(questionWithVariableLabel, legacyVariable)
2003
+ };
2004
+ }
1864
2005
  if (existingVariable) {
1865
- let initial_value = existingVariable.value;
1866
- if (questionWithVariableLabel.type === "select" && Array.isArray(questionWithVariableLabel.choices)) {
1867
- initial_value = getIndexFromChoices(
1868
- questionWithVariableLabel.choices,
1869
- existingVariable.value
1870
- );
1871
- }
1872
2006
  return [
1873
2007
  {
1874
2008
  name: "overWrite" + questionWithVariableLabel.name,
@@ -1883,7 +2017,10 @@ async function promptAndStoreAnswer(questions, existingValues) {
1883
2017
  {
1884
2018
  ...questionWithVariableLabel,
1885
2019
  type: (prev) => prev ? questionWithVariableLabel.type : null,
1886
- initial: initial_value
2020
+ initial: getInitialValue(
2021
+ questionWithVariableLabel,
2022
+ existingVariable
2023
+ )
1887
2024
  }
1888
2025
  ];
1889
2026
  }
@@ -1895,6 +2032,32 @@ async function promptAndStoreAnswer(questions, existingValues) {
1895
2032
  questionWithVariableLabel.scope,
1896
2033
  existingValues
1897
2034
  );
2035
+ const legacySecret = !existingSecret && questionWithVariableLabel.legacyValueLabel ? findExistingValue(
2036
+ questionWithVariableLabel.legacyValueLabel,
2037
+ "SECRET",
2038
+ questionWithVariableLabel.scope,
2039
+ existingValues
2040
+ ) : void 0;
2041
+ if (legacySecret) {
2042
+ return [
2043
+ {
2044
+ name: "overWrite" + questionWithVariableLabel.name,
2045
+ type: "confirm",
2046
+ scope: questionWithVariableLabel.scope,
2047
+ message: `${import_kleur4.default.yellow(
2048
+ `${legacySecret.scope === "REPOSITORY" ? "Repository secret" : "Secret"} ${import_kleur4.default.cyan(
2049
+ legacySecret.name
2050
+ )} already exists in Github under the previous name of ${import_kleur4.default.cyan(
2051
+ questionWithVariableLabel.valueLabel
2052
+ )}. The secrets migration workflow copies it. Do you want to enter a new value instead?`
2053
+ )}`
2054
+ },
2055
+ {
2056
+ ...questionWithVariableLabel,
2057
+ type: (prev) => prev ? questionWithVariableLabel.type : null
2058
+ }
2059
+ ];
2060
+ }
1898
2061
  if (existingSecret) {
1899
2062
  return [
1900
2063
  {
@@ -1934,6 +2097,47 @@ async function promptAndStoreAnswer(questions, existingValues) {
1934
2097
  ]);
1935
2098
  return { ...Object.fromEntries(existingValuesForQuestions), ...result };
1936
2099
  }
2100
+ function defineIfMissing(existingValues, name, type, scope, newValue) {
2101
+ if (findExistingValue(name, type, scope, existingValues)) {
2102
+ return null;
2103
+ }
2104
+ const legacyName = ALL_QUESTIONS.find(
2105
+ (question) => question.valueLabel === name && question.valueType === type && question.scope === scope
2106
+ )?.legacyValueLabel;
2107
+ if (legacyName && findExistingValue(legacyName, type, scope, existingValues)) {
2108
+ log(
2109
+ import_kleur4.default.bold().green("\u2714"),
2110
+ import_kleur4.default.bold().yellow(
2111
+ `${legacyName} exists, the secrets migration workflow copies it to ${name}`
2112
+ )
2113
+ );
2114
+ return null;
2115
+ }
2116
+ return process.env[name] || newValue;
2117
+ }
2118
+ async function promptAndValidateRegistry(existingValues) {
2119
+ const answers = await promptAndStoreAnswer(registryQuestions, existingValues);
2120
+ const result = await validateRegistryCredentials(
2121
+ answers.registryHost,
2122
+ answers.registryOrganisation,
2123
+ answers.registryRepository,
2124
+ answers.registryUsername,
2125
+ answers.registryToken
2126
+ );
2127
+ if (result.status === "valid" || result.status === "skipped") {
2128
+ return;
2129
+ }
2130
+ error(`
2131
+ ${result.status}: ${result.reason || "Generic error"}
2132
+ `);
2133
+ const continueNotValidated = await confirm2({
2134
+ message: "Container registry credentials are not validated. Continue anyway?",
2135
+ default: false
2136
+ });
2137
+ if (!continueNotValidated) {
2138
+ process.exit(1);
2139
+ }
2140
+ }
1937
2141
  async function runSetupEnvironment() {
1938
2142
  log("\n", import_kleur4.default.bold().underline("Github"), "\n");
1939
2143
  const { githubOrganisation, githubRepository } = await (0, import_prompts2.default)(
@@ -2058,7 +2262,22 @@ async function runSetupEnvironment() {
2058
2262
  "WARNING! You are setting up a production environment.\n Make sure you have read the deployment guide carefully before proceeding.\n"
2059
2263
  )
2060
2264
  );
2061
- await promptAndStoreAnswer(githubOtherQuestions, existingValues);
2265
+ }
2266
+ log("\n", import_kleur4.default.bold().underline("Workflow approvals"));
2267
+ const { approvalRequired } = await promptAndStoreAnswer(
2268
+ [
2269
+ {
2270
+ ...githubApprovalRequiredQuestion,
2271
+ initial: getIndexFromChoices(
2272
+ githubApprovalRequiredQuestion.choices,
2273
+ process.env.APPROVAL_REQUIRED || (environment_type === "production" ? "true" : "false")
2274
+ )
2275
+ }
2276
+ ],
2277
+ existingValues
2278
+ );
2279
+ if (approvalRequired !== "false") {
2280
+ await promptAndStoreAnswer([githubApproversQuestion], existingValues);
2062
2281
  }
2063
2282
  log("\n", import_kleur4.default.bold().underline("Two-factor authentication (2FA)"));
2064
2283
  const existingTwoFaEnabled = findExistingValue(
@@ -2077,8 +2296,8 @@ async function runSetupEnvironment() {
2077
2296
  "2FA is disabled on a production-like environment. Logins will accept the fixed test code 000000, exposing real citizen data. Only do this if you know what you are doing."
2078
2297
  );
2079
2298
  }
2080
- log("\n", import_kleur4.default.bold().underline("Docker Hub"));
2081
- await promptAndStoreAnswer(dockerhubQuestions, existingValues);
2299
+ log("\n", import_kleur4.default.bold().underline("Container registry"));
2300
+ await promptAndValidateRegistry(existingValues);
2082
2301
  log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
2083
2302
  const infrastructure = await promptAndStoreAnswer(
2084
2303
  infrastructureQuestions,
@@ -2170,6 +2389,14 @@ async function runSetupEnvironment() {
2170
2389
  );
2171
2390
  }
2172
2391
  }
2392
+ const existingRustfsHostDataPath = findExistingValue(
2393
+ "RUSTFS_HOST_DATA_PATH",
2394
+ "VARIABLE",
2395
+ "ENVIRONMENT",
2396
+ existingValues
2397
+ );
2398
+ const rustfs_host_data_path = existingRustfsHostDataPath?.value || (environment_exists ? "/data/minio" : "/data/rustfs");
2399
+ const rustfs_pvc_name = rustfs_host_data_path.endsWith("/minio") ? "minio" : "rustfs";
2173
2400
  let backupHost = findExistingValue("BACKUP_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2174
2401
  let backupType = "";
2175
2402
  let restoreEnvironmentName = findExistingValue(
@@ -2262,7 +2489,22 @@ async function runSetupEnvironment() {
2262
2489
  log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2263
2490
  }
2264
2491
  log("\n", import_kleur4.default.bold().underline("Monitoring"));
2265
- await promptAndStoreAnswer(databaseAndMonitoringQuestions, existingValues);
2492
+ const existingMonitoringEnabled = findExistingValue(
2493
+ "MONITORING_ENABLED",
2494
+ "VARIABLE",
2495
+ "ENVIRONMENT",
2496
+ existingValues
2497
+ );
2498
+ const monitoringDefault = process.env.MONITORING_ENABLED || existingMonitoringEnabled?.value;
2499
+ const monitoring_enabled = await confirm2({
2500
+ message: "Enable monitoring (Kibana, APM, Filebeat, Metricbeat, Elastalert, OpenTelemetry Collector and tracing)? Disable it if this environment does not need its own monitoring stack.",
2501
+ default: monitoringDefault ? monitoringDefault === "true" : true
2502
+ });
2503
+ if (monitoring_enabled) {
2504
+ await promptAndStoreAnswer(databaseAndMonitoringQuestions, existingValues);
2505
+ } else {
2506
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Monitoring is disabled"));
2507
+ }
2266
2508
  const sentryDSNExists = findExistingValue(
2267
2509
  "SENTRY_DSN",
2268
2510
  "SECRET",
@@ -2293,9 +2535,7 @@ async function runSetupEnvironment() {
2293
2535
  return { ...acc, ...answer };
2294
2536
  });
2295
2537
  const answerOrExisting = (variable, existingValue, fn) => fn(variable || existingValue?.value) || "";
2296
- function findExistingOrDefine(name, type, scope, newValue) {
2297
- return findExistingValue(name, type, scope, existingValues) ? null : process.env[name] || newValue;
2298
- }
2538
+ const findExistingOrDefine = (name, type, scope, newValue) => defineIfMissing(existingValues, name, type, scope, newValue);
2299
2539
  const derivedUpdates = [
2300
2540
  {
2301
2541
  name: "GH_ENCRYPTION_PASSWORD",
@@ -2340,6 +2580,20 @@ async function runSetupEnvironment() {
2340
2580
  value: two_fa_enabled ? "true" : "false",
2341
2581
  scope: "ENVIRONMENT"
2342
2582
  });
2583
+ derivedUpdates.push({
2584
+ name: "MONITORING_ENABLED",
2585
+ type: "VARIABLE",
2586
+ didExist: existingMonitoringEnabled,
2587
+ value: monitoring_enabled ? "true" : "false",
2588
+ scope: "ENVIRONMENT"
2589
+ });
2590
+ derivedUpdates.push({
2591
+ name: "RUSTFS_HOST_DATA_PATH",
2592
+ type: "VARIABLE",
2593
+ didExist: existingRustfsHostDataPath,
2594
+ value: rustfs_host_data_path,
2595
+ scope: "ENVIRONMENT"
2596
+ });
2343
2597
  derivedUpdates.push(...ssl_answers);
2344
2598
  if (configureBackup) {
2345
2599
  derivedUpdates.push({
@@ -2396,16 +2650,16 @@ async function runSetupEnvironment() {
2396
2650
  scope: "ENVIRONMENT"
2397
2651
  },
2398
2652
  {
2399
- name: "MINIO_ROOT_USER",
2653
+ name: "S3_ADMIN_ACCESS_KEY",
2400
2654
  type: "SECRET",
2401
2655
  didExist: findExistingValue(
2402
- "MINIO_ROOT_USER",
2656
+ "S3_ADMIN_ACCESS_KEY",
2403
2657
  "SECRET",
2404
2658
  "ENVIRONMENT",
2405
2659
  existingValues
2406
2660
  ),
2407
2661
  value: findExistingOrDefine(
2408
- "MINIO_ROOT_USER",
2662
+ "S3_ADMIN_ACCESS_KEY",
2409
2663
  "SECRET",
2410
2664
  "ENVIRONMENT",
2411
2665
  generateLongPassword()
@@ -2413,16 +2667,16 @@ async function runSetupEnvironment() {
2413
2667
  scope: "ENVIRONMENT"
2414
2668
  },
2415
2669
  {
2416
- name: "MINIO_ROOT_PASSWORD",
2670
+ name: "S3_ADMIN_SECRET_KEY",
2417
2671
  type: "SECRET",
2418
2672
  didExist: findExistingValue(
2419
- "MINIO_ROOT_PASSWORD",
2673
+ "S3_ADMIN_SECRET_KEY",
2420
2674
  "SECRET",
2421
2675
  "ENVIRONMENT",
2422
2676
  existingValues
2423
2677
  ),
2424
2678
  value: findExistingOrDefine(
2425
- "MINIO_ROOT_PASSWORD",
2679
+ "S3_ADMIN_SECRET_KEY",
2426
2680
  "SECRET",
2427
2681
  "ENVIRONMENT",
2428
2682
  generateLongPassword()
@@ -2686,7 +2940,7 @@ async function runSetupEnvironment() {
2686
2940
  );
2687
2941
  const unknownVariables = existingValues.filter((value) => {
2688
2942
  return !ALL_QUESTIONS.find(
2689
- (question) => question.valueLabel === value.name && question.valueType === value.type && question.scope === value.scope
2943
+ (question) => (question.valueLabel === value.name || question.legacyValueLabel === value.name) && question.valueType === value.type && question.scope === value.scope
2690
2944
  );
2691
2945
  });
2692
2946
  log("");
@@ -2890,6 +3144,9 @@ async function runSetupEnvironment() {
2890
3144
  env: environment,
2891
3145
  environment_type,
2892
3146
  two_fa_enabled,
3147
+ monitoring_enabled,
3148
+ rustfs_host_data_path,
3149
+ rustfs_pvc_name,
2893
3150
  traefik_mode: traefikConfOption,
2894
3151
  restore_enabled: restoreEnvironmentName ? true : false,
2895
3152
  restore_environment_name: restoreEnvironmentName || "",
@@ -2955,6 +3212,7 @@ var init_setup_environment = __esm({
2955
3212
  init_questions();
2956
3213
  init_editor_questions();
2957
3214
  init_questions_helper();
3215
+ init_registry();
2958
3216
  init_manage_users();
2959
3217
  init_paths();
2960
3218
  ALL_QUESTIONS = [];
@@ -2962,7 +3220,7 @@ var init_setup_environment = __esm({
2962
3220
  ALL_QUESTIONS.push(
2963
3221
  ...githubTokenQuestion,
2964
3222
  ...githubOtherQuestions,
2965
- ...dockerhubQuestions,
3223
+ ...registryQuestions,
2966
3224
  ...diskQuestions,
2967
3225
  ...infrastructureQuestions,
2968
3226
  ...backupQuestions,
@@ -2982,17 +3240,17 @@ __export(upgrade_exports, {
2982
3240
  upgradeEnvironmentLayout: () => upgradeEnvironmentLayout
2983
3241
  });
2984
3242
  function moveFileIfDestinationMissing(sourcePath, destinationPath) {
2985
- if (!(0, import_fs5.existsSync)(sourcePath)) {
3243
+ if (!(0, import_fs7.existsSync)(sourcePath)) {
2986
3244
  return false;
2987
3245
  }
2988
- if ((0, import_fs5.existsSync)(destinationPath)) {
3246
+ if ((0, import_fs7.existsSync)(destinationPath)) {
2989
3247
  warn(
2990
3248
  `\u26A0\uFE0F Skipped ${sourcePath}; destination already exists at ${destinationPath}`
2991
3249
  );
2992
3250
  return false;
2993
3251
  }
2994
- (0, import_fs5.mkdirSync)((0, import_path6.dirname)(destinationPath), { recursive: true });
2995
- (0, import_fs5.renameSync)(sourcePath, destinationPath);
3252
+ (0, import_fs7.mkdirSync)((0, import_path13.dirname)(destinationPath), { recursive: true });
3253
+ (0, import_fs7.renameSync)(sourcePath, destinationPath);
2996
3254
  log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
2997
3255
  return true;
2998
3256
  }
@@ -3012,8 +3270,8 @@ function migrateInventoryFiles() {
3012
3270
  ) || didMoveInventory;
3013
3271
  }
3014
3272
  try {
3015
- if ((0, import_fs5.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs5.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
3016
- (0, import_fs5.rmdirSync)(OLD_INVENTORY_DIR);
3273
+ if ((0, import_fs7.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs7.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
3274
+ (0, import_fs7.rmdirSync)(OLD_INVENTORY_DIR);
3017
3275
  log(` \u2713 Removed empty ${OLD_INVENTORY_DIR}`);
3018
3276
  }
3019
3277
  } catch {
@@ -3031,12 +3289,12 @@ async function upgradeEnvironmentLayout() {
3031
3289
  }
3032
3290
  log("\nCommit changes into git after upgrade");
3033
3291
  }
3034
- var import_fs5, import_path6, import_kleur5;
3292
+ var import_fs7, import_path13, import_kleur5;
3035
3293
  var init_upgrade = __esm({
3036
3294
  "src/environment/upgrade.ts"() {
3037
3295
  "use strict";
3038
- import_fs5 = require("fs");
3039
- import_path6 = require("path");
3296
+ import_fs7 = require("fs");
3297
+ import_path13 = require("path");
3040
3298
  import_kleur5 = __toESM(require("kleur"));
3041
3299
  init_logger();
3042
3300
  init_paths();
@@ -3054,16 +3312,16 @@ async function select4(options) {
3054
3312
  return inquirer.select(options);
3055
3313
  }
3056
3314
  async function selectInventoryFile(dirPath = "./environments") {
3057
- if (!fs4.existsSync(dirPath)) {
3315
+ if (!fs6.existsSync(dirPath)) {
3058
3316
  warn(`\u26A0\uFE0F No environment configuration directory found at ${dirPath}`);
3059
3317
  warn(
3060
3318
  "Hint: If this is a new infrastructure repository, run `opencrvs environment init` first."
3061
3319
  );
3062
3320
  return null;
3063
3321
  }
3064
- const environments = fs4.readdirSync(dirPath).filter((entry) => {
3065
- const filePath = path5.join(dirPath, entry);
3066
- return fs4.statSync(filePath).isDirectory() && fs4.existsSync(getEnvironmentInventoryPath(entry));
3322
+ const environments = fs6.readdirSync(dirPath).filter((entry) => {
3323
+ const filePath = path12.join(dirPath, entry);
3324
+ return fs6.statSync(filePath).isDirectory() && fs6.existsSync(getEnvironmentInventoryPath(entry));
3067
3325
  }).sort();
3068
3326
  if (environments.length === 0) {
3069
3327
  warn(`\u26A0\uFE0F No environment configuration files found at ${dirPath}`);
@@ -3090,12 +3348,12 @@ async function manageEnvironmentUsers() {
3090
3348
  }
3091
3349
  await manageUsers(inventory_file);
3092
3350
  }
3093
- var fs4, path5, import_kleur6;
3351
+ var fs6, path12, import_kleur6;
3094
3352
  var init_users = __esm({
3095
3353
  "src/environment/users.ts"() {
3096
3354
  "use strict";
3097
- fs4 = __toESM(require("fs"));
3098
- path5 = __toESM(require("path"));
3355
+ fs6 = __toESM(require("fs"));
3356
+ path12 = __toESM(require("path"));
3099
3357
  import_kleur6 = __toESM(require("kleur"));
3100
3358
  init_manage_users();
3101
3359
  init_logger();
@@ -3105,11 +3363,11 @@ var init_users = __esm({
3105
3363
 
3106
3364
  // src/environment/swarm-to-k8s.ts
3107
3365
  var swarm_to_k8s_exports = {};
3108
- var path6, import_kleur7, import_core2;
3366
+ var path13, import_kleur7, import_core2;
3109
3367
  var init_swarm_to_k8s = __esm({
3110
3368
  "src/environment/swarm-to-k8s.ts"() {
3111
3369
  "use strict";
3112
- path6 = __toESM(require("path"));
3370
+ path13 = __toESM(require("path"));
3113
3371
  import_kleur7 = __toESM(require("kleur"));
3114
3372
  init_logger();
3115
3373
  init_utils();
@@ -3161,7 +3419,7 @@ var init_swarm_to_k8s = __esm({
3161
3419
  );
3162
3420
  process.exit(1);
3163
3421
  }
3164
- const ansible_inventory = path6.join(old_inventory_path, environment + ".yml");
3422
+ const ansible_inventory = path13.join(old_inventory_path, environment + ".yml");
3165
3423
  const data = readYamlFile(ansible_inventory);
3166
3424
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3167
3425
  const master = dockerManagerFirst(data) || "";
@@ -3282,7 +3540,11 @@ var init_swarm_to_k8s = __esm({
3282
3540
  }
3283
3541
  });
3284
3542
 
3285
- // src/migrations/add-translations.ts
3543
+ // src/cli.ts
3544
+ var import_fs9 = __toESM(require("fs"));
3545
+ var import_path15 = __toESM(require("path"));
3546
+
3547
+ // src/migrations/persistent/add-translations.ts
3286
3548
  var import_path = __toESM(require("path"));
3287
3549
 
3288
3550
  // src/csv.ts
@@ -3325,20 +3587,20 @@ function idOf(line2) {
3325
3587
  const comma = line2.indexOf(",");
3326
3588
  return comma === -1 ? line2 : line2.slice(0, comma);
3327
3589
  }
3328
- function readCsvFile(path7) {
3329
- if (!(0, import_fs.existsSync)(path7)) {
3590
+ function readCsvFile(path15) {
3591
+ if (!(0, import_fs.existsSync)(path15)) {
3330
3592
  return void 0;
3331
3593
  }
3332
- const contents = (0, import_fs.readFileSync)(path7, "utf8");
3594
+ const contents = (0, import_fs.readFileSync)(path15, "utf8");
3333
3595
  const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3334
3596
  const trailingNewline = /\r?\n$/.test(contents);
3335
3597
  const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3336
3598
  const body = lines.slice(1).filter((line2) => line2 !== "");
3337
3599
  return { header: lines[0], body, newline, trailingNewline };
3338
3600
  }
3339
- function writeCsvFile(path7, file) {
3601
+ function writeCsvFile(path15, file) {
3340
3602
  (0, import_fs.writeFileSync)(
3341
- path7,
3603
+ path15,
3342
3604
  [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3343
3605
  );
3344
3606
  }
@@ -3352,11 +3614,11 @@ function addRows(file, rows) {
3352
3614
  if (file.body.some((line2) => idOf(line2) === id)) {
3353
3615
  continue;
3354
3616
  }
3355
- const insertAt = isSorted ? file.body.findIndex((line2) => idOf(line2) > id) : -1;
3356
- if (insertAt === -1) {
3617
+ const insertAt2 = isSorted ? file.body.findIndex((line2) => idOf(line2) > id) : -1;
3618
+ if (insertAt2 === -1) {
3357
3619
  file.body.push(row);
3358
3620
  } else {
3359
- file.body.splice(insertAt, 0, row);
3621
+ file.body.splice(insertAt2, 0, row);
3360
3622
  }
3361
3623
  added.push(id);
3362
3624
  }
@@ -3403,7 +3665,7 @@ async function fetchTemplate(refs, application) {
3403
3665
  return void 0;
3404
3666
  }
3405
3667
 
3406
- // src/migrations/add-translations.ts
3668
+ // src/migrations/persistent/add-translations.ts
3407
3669
  var APPLICATIONS = ["client", "login"];
3408
3670
  var skipped = [];
3409
3671
  function warnSkipped(message) {
@@ -3444,9 +3706,9 @@ async function updateApplication(cwd, targetVersion, refs, application) {
3444
3706
  }
3445
3707
  try {
3446
3708
  writeCsvFile(import_path.default.join(cwd, relativePath), local);
3447
- } catch (error3) {
3709
+ } catch (error2) {
3448
3710
  warnSkipped(
3449
- `Could not write ${relativePath} (${error3.message}); translations not added`
3711
+ `Could not write ${relativePath} (${error2.message}); translations not added`
3450
3712
  );
3451
3713
  return;
3452
3714
  }
@@ -3466,9 +3728,9 @@ function readTemplate(contents) {
3466
3728
  async function listRefs(targetVersion) {
3467
3729
  try {
3468
3730
  return await candidateRefs(targetVersion);
3469
- } catch (error3) {
3731
+ } catch (error2) {
3470
3732
  warnSkipped(
3471
- `Could not list the ${targetVersion} refs on GitHub (${error3.message}); translations not added`
3733
+ `Could not list the ${targetVersion} refs on GitHub (${error2.message}); translations not added`
3472
3734
  );
3473
3735
  return void 0;
3474
3736
  }
@@ -3481,9 +3743,9 @@ async function main(targetVersion) {
3481
3743
  for (const application of APPLICATIONS) {
3482
3744
  try {
3483
3745
  await updateApplication(cwd, targetVersion, refs, application);
3484
- } catch (error3) {
3746
+ } catch (error2) {
3485
3747
  warnSkipped(
3486
- `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${application}.csv not updated`
3748
+ `Could not read ${application}.csv from the country config template on GitHub (${error2.message}); ${application}.csv not updated`
3487
3749
  );
3488
3750
  }
3489
3751
  }
@@ -3499,111 +3761,147 @@ async function main(targetVersion) {
3499
3761
  }
3500
3762
  }
3501
3763
 
3502
- // src/migrations/v2.2/read-declaration-through-helper.ts
3764
+ // src/migrations/move-declaration-to-declare-action.ts
3765
+ var import_ts_morph2 = require("ts-morph");
3766
+ var import_path3 = __toESM(require("path"));
3767
+
3768
+ // src/migrations/utils.ts
3503
3769
  var import_ts_morph = require("ts-morph");
3504
3770
  var import_path2 = __toESM(require("path"));
3505
- var EVENT_CONFIG_TYPE_NAME = "EventConfig";
3506
- var DECLARATION_PROPERTY_NAME = "declaration";
3507
- var GET_DECLARATION_NAME = "getDeclaration";
3771
+ var DEFINE_CONFIG_NAME = "defineConfig";
3508
3772
  var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3509
- function isToolkitEventConfig(type) {
3510
- const nonNullableType = type.getNonNullableType();
3511
- const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
3512
- if (symbol?.getName() !== EVENT_CONFIG_TYPE_NAME) {
3773
+ function location(node) {
3774
+ const relPath = import_path2.default.relative(
3775
+ process.cwd(),
3776
+ node.getSourceFile().getFilePath()
3777
+ );
3778
+ return `${relPath}:${node.getStartLineNumber()}`;
3779
+ }
3780
+ function isToolkitDefineConfigCall(call) {
3781
+ const symbol = call.getExpression().getSymbol();
3782
+ const resolved = symbol?.getAliasedSymbol() ?? symbol;
3783
+ if (resolved?.getName() !== DEFINE_CONFIG_NAME) {
3513
3784
  return false;
3514
3785
  }
3515
- return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
3516
- }
3517
- function isDeclarationReadOnEventConfig(node) {
3518
- return node.getName() === DECLARATION_PROPERTY_NAME && isToolkitEventConfig(node.getExpression().getType());
3786
+ return resolved.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
3519
3787
  }
3520
- function isAssignmentOperator(kind) {
3521
- return kind >= import_ts_morph.SyntaxKind.FirstAssignment && kind <= import_ts_morph.SyntaxKind.LastAssignment;
3788
+ function findProperty(literal, name) {
3789
+ const property = literal.getProperty(name);
3790
+ return import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property) ? property : void 0;
3522
3791
  }
3523
- function isWriteTarget(node) {
3524
- const parent = node.getParent();
3525
- if (import_ts_morph.Node.isDeleteExpression(parent)) {
3792
+ function mayHaveActionType(actionType, node, expectedActionType) {
3793
+ const typeProperty = actionType.getProperty("type");
3794
+ if (!typeProperty) {
3526
3795
  return true;
3527
3796
  }
3528
- return import_ts_morph.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
3529
- }
3530
- function location(node) {
3531
- const relPath = import_path2.default.relative(
3532
- process.cwd(),
3533
- node.getSourceFile().getFilePath()
3797
+ const type = typeProperty.getTypeAtLocation(node);
3798
+ const values = type.isUnion() ? type.getUnionTypes() : [type];
3799
+ return !values.every(
3800
+ (value) => value.isStringLiteral() && value.getLiteralValue() !== expectedActionType
3534
3801
  );
3535
- return `${relPath}:${node.getStartLineNumber()}`;
3536
3802
  }
3537
- function warnDestructuredDeclarations(sourceFile) {
3538
- for (const pattern of sourceFile.getDescendantsOfKind(
3539
- import_ts_morph.SyntaxKind.ObjectBindingPattern
3540
- )) {
3541
- const destructuresDeclaration = pattern.getElements().some(
3542
- (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME
3803
+ function mayBeAction(node, actionType) {
3804
+ if (import_ts_morph.Node.isObjectLiteralExpression(node)) {
3805
+ return isAction(node, actionType);
3806
+ }
3807
+ if (import_ts_morph.Node.isSpreadElement(node)) {
3808
+ const arrayType = node.getExpression().getType();
3809
+ const elementTypes = arrayType.isTuple() ? arrayType.getTupleElements() : [arrayType.getArrayElementType()];
3810
+ return elementTypes.some(
3811
+ (elementType) => !elementType || mayHaveActionType(elementType, node, actionType)
3543
3812
  );
3544
- if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
3545
- console.warn(
3546
- ` [${location(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
3547
- );
3548
- }
3549
3813
  }
3814
+ return mayHaveActionType(node.getType(), node, actionType);
3550
3815
  }
3551
- function warnSpreadDeclarations(sourceFile) {
3552
- for (const literal of sourceFile.getDescendantsOfKind(
3553
- import_ts_morph.SyntaxKind.ObjectLiteralExpression
3554
- )) {
3555
- const properties = literal.getProperties();
3556
- const spreadsEventConfig = properties.some(
3557
- (property) => import_ts_morph.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
3558
- );
3559
- const setsDeclaration = properties.some(
3560
- (property) => (import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME
3561
- );
3562
- if (spreadsEventConfig && setsDeclaration) {
3563
- console.warn(
3564
- ` [${location(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME}\` on its DECLARE action, so replace that one by hand.`
3565
- );
3566
- }
3816
+ function isAction(literal, actionType) {
3817
+ const type = findProperty(literal, "type");
3818
+ return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === actionType;
3819
+ }
3820
+ function indentationOf(node) {
3821
+ const text2 = node.getSourceFile().getFullText();
3822
+ const lineStart = text2.lastIndexOf("\n", node.getStart() - 1) + 1;
3823
+ return /^[ \t]*/.exec(text2.slice(lineStart))?.[0] ?? "";
3824
+ }
3825
+ function restOfLine(text2, position) {
3826
+ const lineEnd = text2.indexOf("\n", position);
3827
+ return text2.slice(position, lineEnd === -1 ? text2.length : lineEnd);
3828
+ }
3829
+ function isOnlyComments(text2) {
3830
+ return /^\s*(?:\/\/.*|\/\*.*?\*\/\s*)*$/.test(text2);
3831
+ }
3832
+ function layoutOf(property) {
3833
+ const text2 = property.getSourceFile().getFullText();
3834
+ const next = property.getNextSibling();
3835
+ const hasComma = next?.getKind() === import_ts_morph.SyntaxKind.CommaToken;
3836
+ const end = next && hasComma ? next.getEnd() : property.getEnd();
3837
+ const trailing = restOfLine(text2, end);
3838
+ const lineBreak = text2.slice(property.getFullStart(), property.getStart()).indexOf("\n");
3839
+ if (lineBreak === -1 || !isOnlyComments(trailing)) {
3840
+ return {
3841
+ ownsLines: false,
3842
+ start: property.getStart(true),
3843
+ end,
3844
+ hasComma,
3845
+ trailingComment: ""
3846
+ };
3567
3847
  }
3848
+ const firstLine = property.getFullStart() + lineBreak + 1;
3849
+ return {
3850
+ ownsLines: true,
3851
+ start: firstLine + (/^\s*/.exec(text2.slice(firstLine))?.[0].length ?? 0),
3852
+ end,
3853
+ hasComma,
3854
+ trailingComment: trailing.trimEnd()
3855
+ };
3856
+ }
3857
+ function insertAt(position, text2) {
3858
+ return { start: position, end: position, text: text2 };
3859
+ }
3860
+ function applyTextEdits(sourceFile, edits) {
3861
+ const text2 = [...edits].sort((a, b) => b.start - a.start).reduce(
3862
+ (result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end),
3863
+ sourceFile.getFullText()
3864
+ );
3865
+ sourceFile.replaceWithText(text2);
3568
3866
  }
3569
3867
  function findToolkitImport(sourceFile) {
3570
3868
  return sourceFile.getImportDeclaration(
3571
3869
  (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
3572
3870
  );
3573
3871
  }
3574
- function findGetDeclarationName(sourceFile) {
3575
- const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
3872
+ function findToolkitImportName(sourceFile, name) {
3873
+ const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === name);
3576
3874
  if (imported) {
3577
- return imported.getAliasNode()?.getText() ?? GET_DECLARATION_NAME;
3875
+ return imported.getAliasNode()?.getText() ?? name;
3578
3876
  }
3579
- if (sourceFile.getLocal(GET_DECLARATION_NAME)) {
3877
+ if (sourceFile.getLocal(name)) {
3580
3878
  return void 0;
3581
3879
  }
3582
- return GET_DECLARATION_NAME;
3880
+ return name;
3583
3881
  }
3584
- function addGetDeclarationImport(sourceFile) {
3882
+ function addToolkitImport(sourceFile, name) {
3585
3883
  const toolkitImport = findToolkitImport(sourceFile);
3586
3884
  if (!toolkitImport) {
3587
3885
  const imports = sourceFile.getImportDeclarations();
3588
3886
  const lastImport = imports[imports.length - 1];
3589
3887
  sourceFile.insertStatements(
3590
3888
  lastImport ? lastImport.getChildIndex() + 1 : 0,
3591
- `import { ${GET_DECLARATION_NAME} } from '${TOOLKIT_EVENTS_MODULE}'`
3889
+ `import { ${name} } from '${TOOLKIT_EVENTS_MODULE}'`
3592
3890
  );
3593
3891
  return;
3594
3892
  }
3595
- const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
3893
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === name);
3596
3894
  if (alreadyImported) {
3597
3895
  return;
3598
3896
  }
3599
3897
  const namedImports = toolkitImport.getNamedImports();
3600
3898
  if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
3601
- toolkitImport.addNamedImport(GET_DECLARATION_NAME);
3899
+ toolkitImport.addNamedImport(name);
3602
3900
  return;
3603
3901
  }
3604
3902
  const names = [
3605
3903
  ...namedImports.map((namedImport) => namedImport.getText()),
3606
- GET_DECLARATION_NAME
3904
+ name
3607
3905
  ];
3608
3906
  const specifiers = toolkitImport.getText().includes("\n") ? `{
3609
3907
  ${names.join(",\n ")}
@@ -3612,55 +3910,487 @@ function addGetDeclarationImport(sourceFile) {
3612
3910
  `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
3613
3911
  );
3614
3912
  }
3615
- function rewriteDeclarationReads(sourceFile) {
3616
- warnDestructuredDeclarations(sourceFile);
3617
- warnSpreadDeclarations(sourceFile);
3618
- const reads = sourceFile.getDescendantsOfKind(import_ts_morph.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
3619
- if (node.hasQuestionDotToken()) {
3620
- console.warn(
3621
- ` [${location(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
3622
- );
3623
- return false;
3624
- }
3625
- if (isWriteTarget(node)) {
3626
- console.warn(
3627
- ` [${location(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME}\` on the DECLARE action instead.`
3628
- );
3629
- return false;
3630
- }
3631
- return true;
3632
- }).sort((a, b) => b.getStart() - a.getStart());
3633
- if (reads.length === 0) {
3634
- return 0;
3913
+
3914
+ // src/migrations/move-declaration-to-declare-action.ts
3915
+ var DEFINE_CONFIG_NAME2 = "defineConfig";
3916
+ var DECLARATION_PROPERTY_NAME = "declaration";
3917
+ var ACTIONS_PROPERTY_NAME = "actions";
3918
+ var DECLARE_ACTION_TYPE = "DECLARE";
3919
+ function findDeclareAction(config) {
3920
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
3921
+ const actionsValue = import_ts_morph2.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
3922
+ if (!import_ts_morph2.Node.isArrayLiteralExpression(actionsValue)) {
3923
+ console.warn(
3924
+ ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`
3925
+ );
3926
+ return void 0;
3635
3927
  }
3636
- const getDeclarationName = findGetDeclarationName(sourceFile);
3637
- if (!getDeclarationName) {
3928
+ const candidates = actionsValue.getElements().filter((element) => mayBeAction(element, DECLARE_ACTION_TYPE));
3929
+ if (candidates.length !== 1 || !import_ts_morph2.Node.isObjectLiteralExpression(candidates[0])) {
3638
3930
  console.warn(
3639
- ` [${location(reads[reads.length - 1])}] Skipped ${reads.length} read(s): the file already declares its own \`${GET_DECLARATION_NAME}\`. Rewrite them to use the toolkit's \`${GET_DECLARATION_NAME}()\` by hand.`
3931
+ ` [${location(config)}] Skipped: could not find exactly one ${DECLARE_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME}\`. Move \`${DECLARATION_PROPERTY_NAME}\` onto it by hand.`
3640
3932
  );
3641
- return 0;
3933
+ return void 0;
3642
3934
  }
3643
- for (const read of reads) {
3644
- console.log(
3645
- ` [${location(read)}] ${read.getText()} -> ${getDeclarationName}(${read.getExpression().getText()})`
3935
+ const declareAction = candidates[0];
3936
+ if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
3937
+ console.warn(
3938
+ ` [${location(config)}] Skipped: \`${DECLARATION_PROPERTY_NAME}\` is set both at the top level and on the ${DECLARE_ACTION_TYPE} action. Keep only the one on the action.`
3646
3939
  );
3647
- read.replaceWithText(
3648
- `${getDeclarationName}(${read.getExpression().getText()})`
3940
+ return void 0;
3941
+ }
3942
+ return declareAction;
3943
+ }
3944
+ function insertIntoDeclareAction(declareAction, property) {
3945
+ const anchor = declareAction.getProperty("label") ?? declareAction.getPropertyOrThrow("type");
3946
+ const text2 = property.getSourceFile().getFullText();
3947
+ const anchorLayout = layoutOf(anchor);
3948
+ const layout = layoutOf(property);
3949
+ const indent = indentationOf(anchor);
3950
+ const oldIndent = indentationOf(property);
3951
+ const reindent = (lines) => lines.split("\n").map(
3952
+ (line2, index) => index > 0 && line2.startsWith(oldIndent) ? indent + line2.slice(oldIndent.length) : line2
3953
+ ).join("\n");
3954
+ if (anchorLayout.ownsLines) {
3955
+ const moved = reindent(text2.slice(layout.start, property.getEnd()));
3956
+ const position = anchorLayout.end + restOfLine(text2, anchorLayout.end).length;
3957
+ const insertion = `
3958
+ ${indent}${moved}${anchorLayout.hasComma ? "," : ""}${layout.trailingComment}`;
3959
+ if (anchorLayout.hasComma) {
3960
+ return [insertAt(position, insertion)];
3961
+ }
3962
+ return position === anchor.getEnd() ? [insertAt(position, `,${insertion}`)] : [insertAt(anchor.getEnd(), ","), insertAt(position, insertion)];
3963
+ }
3964
+ const droppedComments = text2.slice(layout.start, property.getStart(true)).trim() !== "" || layout.trailingComment !== "";
3965
+ if (droppedComments) {
3966
+ console.warn(
3967
+ ` [${location(property)}] The comments next to \`${DECLARATION_PROPERTY_NAME}\` were not moved with it. Move them onto the ${DECLARE_ACTION_TYPE} action by hand.`
3649
3968
  );
3650
3969
  }
3651
- addGetDeclarationImport(sourceFile);
3652
- return reads.length;
3970
+ const isMultiLine = declareAction.getText().includes("\n");
3971
+ const separator = isMultiLine ? `,
3972
+ ${indent}` : ", ";
3973
+ return [
3974
+ insertAt(anchor.getEnd(), `${separator}${reindent(property.getText(true))}`)
3975
+ ];
3653
3976
  }
3654
- async function main2() {
3655
- const srcDir = import_path2.default.join(process.cwd(), "src");
3656
- console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
3657
- `);
3658
- const project = new import_ts_morph.Project({
3659
- tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
3660
- skipAddingFilesFromTsConfig: false
3661
- });
3662
- const sourceFiles = project.getSourceFiles().filter((sf) => {
3663
- const fp = sf.getFilePath();
3977
+ function removeFromConfig(property) {
3978
+ const text2 = property.getSourceFile().getFullText();
3979
+ const layout = layoutOf(property);
3980
+ const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph2.SyntaxKind.CommaToken);
3981
+ if (layout.ownsLines) {
3982
+ const lines = {
3983
+ start: text2.lastIndexOf("\n", layout.start - 1),
3984
+ end: layout.end + restOfLine(text2, layout.end).length,
3985
+ text: ""
3986
+ };
3987
+ return !layout.hasComma && previousComma ? [
3988
+ lines,
3989
+ {
3990
+ start: previousComma.getStart(),
3991
+ end: previousComma.getEnd(),
3992
+ text: ""
3993
+ }
3994
+ ] : [lines];
3995
+ }
3996
+ if (layout.hasComma) {
3997
+ return [{ start: property.getFullStart(), end: layout.end, text: "" }];
3998
+ }
3999
+ return [
4000
+ {
4001
+ start: (previousComma ?? property).getStart(),
4002
+ end: property.getEnd(),
4003
+ text: ""
4004
+ }
4005
+ ];
4006
+ }
4007
+ function findConfigLiteral(call) {
4008
+ const config = call.getArguments()[0];
4009
+ if (!config || import_ts_morph2.Node.isObjectLiteralExpression(config)) {
4010
+ return config;
4011
+ }
4012
+ if (config.getType().getProperty(DECLARATION_PROPERTY_NAME)) {
4013
+ console.warn(
4014
+ ` [${location(config)}] Skipped: \`${DEFINE_CONFIG_NAME2}\` is not given an object literal. If its config has a top-level \`${DECLARATION_PROPERTY_NAME}\`, move it onto the ${DECLARE_ACTION_TYPE} action by hand.`
4015
+ );
4016
+ }
4017
+ return void 0;
4018
+ }
4019
+ function moveDeclarationToDeclareAction(sourceFile) {
4020
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph2.Node.isObjectLiteralExpression);
4021
+ const edits = [];
4022
+ let changes = 0;
4023
+ for (const config of configs) {
4024
+ const declaration = findProperty(config, DECLARATION_PROPERTY_NAME);
4025
+ if (!declaration) {
4026
+ continue;
4027
+ }
4028
+ const declareAction = findDeclareAction(config);
4029
+ if (!declareAction) {
4030
+ continue;
4031
+ }
4032
+ console.log(
4033
+ ` [${location(declaration)}] Moved \`${declaration.getText()}\` onto the ${DECLARE_ACTION_TYPE} action`
4034
+ );
4035
+ edits.push(
4036
+ ...insertIntoDeclareAction(declareAction, declaration),
4037
+ ...removeFromConfig(declaration)
4038
+ );
4039
+ changes++;
4040
+ }
4041
+ if (changes === 0) {
4042
+ return 0;
4043
+ }
4044
+ applyTextEdits(sourceFile, edits);
4045
+ return changes;
4046
+ }
4047
+ async function main2() {
4048
+ const srcDir = import_path3.default.join(process.cwd(), "src");
4049
+ console.log(`Scanning for top-level event declarations in: ${srcDir}
4050
+ `);
4051
+ const project = new import_ts_morph2.Project({
4052
+ tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
4053
+ skipAddingFilesFromTsConfig: false
4054
+ });
4055
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
4056
+ const fp = sf.getFilePath();
4057
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
4058
+ });
4059
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
4060
+ `);
4061
+ let totalChanges = 0;
4062
+ const modifiedFiles = [];
4063
+ for (const sourceFile of sourceFiles) {
4064
+ const changes = moveDeclarationToDeclareAction(sourceFile);
4065
+ if (changes > 0) {
4066
+ totalChanges += changes;
4067
+ modifiedFiles.push(sourceFile);
4068
+ }
4069
+ }
4070
+ if (modifiedFiles.length === 0) {
4071
+ console.log("No top-level event declarations found. Nothing to do.");
4072
+ return;
4073
+ }
4074
+ console.log(`
4075
+ Saving ${modifiedFiles.length} modified file(s)...`);
4076
+ for (const sourceFile of modifiedFiles) {
4077
+ await sourceFile.save();
4078
+ console.log(
4079
+ ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
4080
+ );
4081
+ }
4082
+ console.log(
4083
+ `
4084
+ Done. Moved ${totalChanges} declaration(s) across ${modifiedFiles.length} file(s).`
4085
+ );
4086
+ }
4087
+
4088
+ // src/migrations/add-notify-config.ts
4089
+ var import_ts_morph3 = require("ts-morph");
4090
+ var import_path4 = __toESM(require("path"));
4091
+ var DEFINE_CONFIG_NAME3 = "defineConfig";
4092
+ var ACTIONS_PROPERTY_NAME2 = "actions";
4093
+ var DECLARATION_PROPERTY_NAME2 = "declaration";
4094
+ var NOTIFY_ACTION_TYPE = "NOTIFY";
4095
+ var DECLARE_ACTION_TYPE2 = "DECLARE";
4096
+ var NOTIFY_PROPERTIES = [
4097
+ {
4098
+ name: "notificationForm",
4099
+ helper: "toNotificationForm",
4100
+ declareProperty: DECLARATION_PROPERTY_NAME2
4101
+ },
4102
+ {
4103
+ name: "review",
4104
+ helper: "toNotificationReview",
4105
+ declareProperty: "review"
4106
+ }
4107
+ ];
4108
+ function referenceOf(property) {
4109
+ if (import_ts_morph3.Node.isShorthandPropertyAssignment(property)) {
4110
+ return property.getName();
4111
+ }
4112
+ const value = property?.getInitializer();
4113
+ return import_ts_morph3.Node.isIdentifier(value) || import_ts_morph3.Node.isPropertyAccessExpression(value) ? value.getText() : void 0;
4114
+ }
4115
+ function findConfigLiteral2(call) {
4116
+ const config = call.getArguments()[0];
4117
+ if (import_ts_morph3.Node.isObjectLiteralExpression(config)) {
4118
+ return config;
4119
+ }
4120
+ console.warn(
4121
+ ` [${location(call)}] Skipped: \`${DEFINE_CONFIG_NAME3}\` is not given an object literal. If the event has a NOTIFY action, give it a \`notificationForm\` and \`review\` by hand.`
4122
+ );
4123
+ return void 0;
4124
+ }
4125
+ function findNotifyAction(config, actions) {
4126
+ const candidates = actions.filter(
4127
+ (action) => mayBeAction(action, NOTIFY_ACTION_TYPE)
4128
+ );
4129
+ if (candidates.length === 0) {
4130
+ console.warn(
4131
+ ` [${location(config)}] No ${NOTIFY_ACTION_TYPE} action: the event cannot be notified. If a role has \`record.notify\` for it, add a ${NOTIFY_ACTION_TYPE} action with a \`notificationForm\` and \`review\`.`
4132
+ );
4133
+ return void 0;
4134
+ }
4135
+ if (candidates.length !== 1 || !import_ts_morph3.Node.isObjectLiteralExpression(candidates[0])) {
4136
+ console.warn(
4137
+ ` [${location(config)}] Skipped: could not find exactly one ${NOTIFY_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME2}\`. Give it a \`notificationForm\` and \`review\` by hand.`
4138
+ );
4139
+ return void 0;
4140
+ }
4141
+ return candidates[0];
4142
+ }
4143
+ function insertIntoAction(action, properties) {
4144
+ const anchor = action.getProperty("label") ?? action.getPropertyOrThrow("type");
4145
+ const text2 = action.getSourceFile().getFullText();
4146
+ const anchorLayout = layoutOf(anchor);
4147
+ const indent = indentationOf(anchor);
4148
+ if (anchorLayout.ownsLines) {
4149
+ const position = anchorLayout.end + restOfLine(text2, anchorLayout.end).length;
4150
+ const lines = properties.map((property) => `
4151
+ ${indent}${property}`);
4152
+ if (anchorLayout.hasComma) {
4153
+ return [insertAt(position, `${lines.join(",")},`)];
4154
+ }
4155
+ return position === anchor.getEnd() ? [insertAt(position, `,${lines.join(",")}`)] : [insertAt(anchor.getEnd(), ","), insertAt(position, lines.join(","))];
4156
+ }
4157
+ const separator = action.getText().includes("\n") ? `,
4158
+ ${indent}` : ", ";
4159
+ return [
4160
+ insertAt(
4161
+ anchor.getEnd(),
4162
+ properties.map((property) => `${separator}${property}`).join("")
4163
+ )
4164
+ ];
4165
+ }
4166
+ function addNotifyConfig(sourceFile) {
4167
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral2).filter(import_ts_morph3.Node.isObjectLiteralExpression);
4168
+ const helperNames = Object.fromEntries(
4169
+ NOTIFY_PROPERTIES.map(({ helper }) => [
4170
+ helper,
4171
+ findToolkitImportName(sourceFile, helper)
4172
+ ])
4173
+ );
4174
+ const edits = [];
4175
+ const usedHelpers = /* @__PURE__ */ new Set();
4176
+ let changes = 0;
4177
+ for (const config of configs) {
4178
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME2);
4179
+ const actionsValue = import_ts_morph3.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
4180
+ if (!import_ts_morph3.Node.isArrayLiteralExpression(actionsValue)) {
4181
+ console.warn(
4182
+ ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME2}\` is not an array literal. If the event has a ${NOTIFY_ACTION_TYPE} action, give it a \`notificationForm\` and \`review\` by hand.`
4183
+ );
4184
+ continue;
4185
+ }
4186
+ const notifyAction = findNotifyAction(config, actionsValue.getElements());
4187
+ if (!notifyAction) {
4188
+ continue;
4189
+ }
4190
+ const declareAction = actionsValue.getElements().find(
4191
+ (action) => import_ts_morph3.Node.isObjectLiteralExpression(action) && isAction(action, DECLARE_ACTION_TYPE2)
4192
+ );
4193
+ const properties = NOTIFY_PROPERTIES.filter(
4194
+ ({ name }) => !findProperty(notifyAction, name)
4195
+ ).flatMap(({ name, helper, declareProperty }) => {
4196
+ const helperName = helperNames[helper];
4197
+ const reference = referenceOf(
4198
+ (declareAction && findProperty(declareAction, declareProperty)) ?? (declareProperty === DECLARATION_PROPERTY_NAME2 ? findProperty(config, declareProperty) : void 0)
4199
+ );
4200
+ if (!helperName) {
4201
+ console.warn(
4202
+ ` [${location(notifyAction)}] Skipped \`${name}\`: the file already declares its own \`${helper}\`. Add \`${name}\` to the ${NOTIFY_ACTION_TYPE} action by hand, using the toolkit's \`${helper}\`.`
4203
+ );
4204
+ return [];
4205
+ }
4206
+ if (!reference) {
4207
+ console.warn(
4208
+ ` [${location(notifyAction)}] Skipped \`${name}\`: the ${DECLARE_ACTION_TYPE2} action's \`${declareProperty}\` is not given as a name. Add \`${name}: ${helper}(<${DECLARE_ACTION_TYPE2} ${declareProperty}>)\` to the ${NOTIFY_ACTION_TYPE} action by hand.`
4209
+ );
4210
+ return [];
4211
+ }
4212
+ if (helperName === helper) {
4213
+ usedHelpers.add(helper);
4214
+ }
4215
+ return [`${name}: ${helperName}(${reference})`];
4216
+ });
4217
+ if (properties.length === 0) {
4218
+ continue;
4219
+ }
4220
+ console.log(
4221
+ ` [${location(notifyAction)}] Added \`${properties.join("`, `")}\` to the ${NOTIFY_ACTION_TYPE} action`
4222
+ );
4223
+ edits.push(...insertIntoAction(notifyAction, properties));
4224
+ changes++;
4225
+ }
4226
+ if (changes === 0) {
4227
+ return 0;
4228
+ }
4229
+ applyTextEdits(sourceFile, edits);
4230
+ for (const helper of usedHelpers) {
4231
+ addToolkitImport(sourceFile, helper);
4232
+ }
4233
+ return changes;
4234
+ }
4235
+ async function main3() {
4236
+ const srcDir = import_path4.default.join(process.cwd(), "src");
4237
+ console.log(`Scanning for NOTIFY actions in: ${srcDir}
4238
+ `);
4239
+ const project = new import_ts_morph3.Project({
4240
+ tsConfigFilePath: import_path4.default.resolve(srcDir, "../tsconfig.json"),
4241
+ skipAddingFilesFromTsConfig: false
4242
+ });
4243
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
4244
+ const fp = sf.getFilePath();
4245
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
4246
+ });
4247
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
4248
+ `);
4249
+ let totalChanges = 0;
4250
+ const modifiedFiles = [];
4251
+ for (const sourceFile of sourceFiles) {
4252
+ const changes = addNotifyConfig(sourceFile);
4253
+ if (changes > 0) {
4254
+ totalChanges += changes;
4255
+ modifiedFiles.push(sourceFile);
4256
+ }
4257
+ }
4258
+ if (modifiedFiles.length === 0) {
4259
+ console.log("No NOTIFY actions to update. Nothing to do.");
4260
+ return;
4261
+ }
4262
+ console.log(`
4263
+ Saving ${modifiedFiles.length} modified file(s)...`);
4264
+ for (const sourceFile of modifiedFiles) {
4265
+ await sourceFile.save();
4266
+ console.log(
4267
+ ` Saved: ${import_path4.default.relative(process.cwd(), sourceFile.getFilePath())}`
4268
+ );
4269
+ }
4270
+ console.log(
4271
+ `
4272
+ Done. Updated ${totalChanges} NOTIFY action(s) across ${modifiedFiles.length} file(s).`
4273
+ );
4274
+ }
4275
+
4276
+ // src/migrations/read-declaration-through-helper.ts
4277
+ var import_ts_morph4 = require("ts-morph");
4278
+ var import_path5 = __toESM(require("path"));
4279
+ var EVENT_CONFIG_TYPE_NAME = "EventConfig";
4280
+ var DECLARATION_PROPERTY_NAME3 = "declaration";
4281
+ var GET_DECLARATION_NAME = "getDeclaration";
4282
+ function isToolkitEventConfig(type) {
4283
+ const nonNullableType = type.getNonNullableType();
4284
+ const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
4285
+ if (symbol?.getName() !== EVENT_CONFIG_TYPE_NAME) {
4286
+ return false;
4287
+ }
4288
+ return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
4289
+ }
4290
+ function isDeclarationReadOnEventConfig(node) {
4291
+ return node.getName() === DECLARATION_PROPERTY_NAME3 && isToolkitEventConfig(node.getExpression().getType());
4292
+ }
4293
+ function isAssignmentOperator(kind) {
4294
+ return kind >= import_ts_morph4.SyntaxKind.FirstAssignment && kind <= import_ts_morph4.SyntaxKind.LastAssignment;
4295
+ }
4296
+ function isWriteTarget(node) {
4297
+ const parent = node.getParent();
4298
+ if (import_ts_morph4.Node.isDeleteExpression(parent)) {
4299
+ return true;
4300
+ }
4301
+ return import_ts_morph4.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
4302
+ }
4303
+ function location2(node) {
4304
+ const relPath = import_path5.default.relative(
4305
+ process.cwd(),
4306
+ node.getSourceFile().getFilePath()
4307
+ );
4308
+ return `${relPath}:${node.getStartLineNumber()}`;
4309
+ }
4310
+ function warnDestructuredDeclarations(sourceFile) {
4311
+ for (const pattern of sourceFile.getDescendantsOfKind(
4312
+ import_ts_morph4.SyntaxKind.ObjectBindingPattern
4313
+ )) {
4314
+ const destructuresDeclaration = pattern.getElements().some(
4315
+ (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME3
4316
+ );
4317
+ if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
4318
+ console.warn(
4319
+ ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME3}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
4320
+ );
4321
+ }
4322
+ }
4323
+ }
4324
+ function warnSpreadDeclarations(sourceFile) {
4325
+ for (const literal of sourceFile.getDescendantsOfKind(
4326
+ import_ts_morph4.SyntaxKind.ObjectLiteralExpression
4327
+ )) {
4328
+ const properties = literal.getProperties();
4329
+ const spreadsEventConfig = properties.some(
4330
+ (property) => import_ts_morph4.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
4331
+ );
4332
+ const setsDeclaration = properties.some(
4333
+ (property) => (import_ts_morph4.Node.isPropertyAssignment(property) || import_ts_morph4.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME3
4334
+ );
4335
+ if (spreadsEventConfig && setsDeclaration) {
4336
+ console.warn(
4337
+ ` [${location2(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME3}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME3}\` on its DECLARE action, so replace that one by hand.`
4338
+ );
4339
+ }
4340
+ }
4341
+ }
4342
+ function rewriteDeclarationReads(sourceFile) {
4343
+ warnDestructuredDeclarations(sourceFile);
4344
+ warnSpreadDeclarations(sourceFile);
4345
+ const reads = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
4346
+ if (node.hasQuestionDotToken()) {
4347
+ console.warn(
4348
+ ` [${location2(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
4349
+ );
4350
+ return false;
4351
+ }
4352
+ if (isWriteTarget(node)) {
4353
+ console.warn(
4354
+ ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME3}\` on the DECLARE action instead.`
4355
+ );
4356
+ return false;
4357
+ }
4358
+ return true;
4359
+ }).sort((a, b) => b.getStart() - a.getStart());
4360
+ if (reads.length === 0) {
4361
+ return 0;
4362
+ }
4363
+ const getDeclarationName = findToolkitImportName(
4364
+ sourceFile,
4365
+ GET_DECLARATION_NAME
4366
+ );
4367
+ if (!getDeclarationName) {
4368
+ console.warn(
4369
+ ` [${location2(reads[reads.length - 1])}] Skipped ${reads.length} read(s): the file already declares its own \`${GET_DECLARATION_NAME}\`. Rewrite them to use the toolkit's \`${GET_DECLARATION_NAME}()\` by hand.`
4370
+ );
4371
+ return 0;
4372
+ }
4373
+ for (const read of reads) {
4374
+ console.log(
4375
+ ` [${location2(read)}] ${read.getText()} -> ${getDeclarationName}(${read.getExpression().getText()})`
4376
+ );
4377
+ read.replaceWithText(
4378
+ `${getDeclarationName}(${read.getExpression().getText()})`
4379
+ );
4380
+ }
4381
+ addToolkitImport(sourceFile, GET_DECLARATION_NAME);
4382
+ return reads.length;
4383
+ }
4384
+ async function main4() {
4385
+ const srcDir = import_path5.default.join(process.cwd(), "src");
4386
+ console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
4387
+ `);
4388
+ const project = new import_ts_morph4.Project({
4389
+ tsConfigFilePath: import_path5.default.resolve(srcDir, "../tsconfig.json"),
4390
+ skipAddingFilesFromTsConfig: false
4391
+ });
4392
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
4393
+ const fp = sf.getFilePath();
3664
4394
  return fp.includes("/src/") && !fp.includes("/node_modules/");
3665
4395
  });
3666
4396
  console.log(`Found ${sourceFiles.length} source file(s) to analyse.
@@ -3674,85 +4404,1533 @@ async function main2() {
3674
4404
  modifiedFiles.push(sourceFile);
3675
4405
  }
3676
4406
  }
3677
- if (modifiedFiles.length === 0) {
3678
- console.log("No EventConfig declaration reads found. Nothing to do.");
3679
- return;
4407
+ if (modifiedFiles.length === 0) {
4408
+ console.log("No EventConfig declaration reads found. Nothing to do.");
4409
+ return;
4410
+ }
4411
+ console.log(`
4412
+ Saving ${modifiedFiles.length} modified file(s)...`);
4413
+ for (const sourceFile of modifiedFiles) {
4414
+ await sourceFile.save();
4415
+ console.log(
4416
+ ` Saved: ${import_path5.default.relative(process.cwd(), sourceFile.getFilePath())}`
4417
+ );
4418
+ }
4419
+ console.log(
4420
+ `
4421
+ Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length} file(s).`
4422
+ );
4423
+ }
4424
+
4425
+ // src/migrations/resolve-versioned-event-config.ts
4426
+ var import_ts_morph5 = require("ts-morph");
4427
+ var import_path6 = __toESM(require("path"));
4428
+ var EVENT_CONFIG_TYPE_NAME2 = "EventConfig";
4429
+ var VERSIONED_EVENT_CONFIG_TYPE_NAME = "VersionedEventConfig";
4430
+ var RESOLVE_EVENT_CONFIG_NAME = "resolveEventConfig";
4431
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
4432
+ function isToolkitType(type, name) {
4433
+ const nonNullableType = type.getNonNullableType();
4434
+ const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
4435
+ if (symbol?.getName() !== name) {
4436
+ return false;
4437
+ }
4438
+ return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
4439
+ }
4440
+ function isVersionedEventConfig(type) {
4441
+ return isToolkitType(type, VERSIONED_EVENT_CONFIG_TYPE_NAME);
4442
+ }
4443
+ function isEventConfig(type) {
4444
+ return isToolkitType(type, EVENT_CONFIG_TYPE_NAME2);
4445
+ }
4446
+ function isArrayOf(type, isElement) {
4447
+ const elementType = type.getNonNullableType().getArrayElementType();
4448
+ return elementType !== void 0 && isElement(elementType);
4449
+ }
4450
+ function isVersionedField(type, name) {
4451
+ return type.getNonNullableType().getProperty(name) !== void 0;
4452
+ }
4453
+ function isAssignmentOperator2(kind) {
4454
+ return kind >= import_ts_morph5.SyntaxKind.FirstAssignment && kind <= import_ts_morph5.SyntaxKind.LastAssignment;
4455
+ }
4456
+ function isWriteTarget2(node) {
4457
+ const parent = node.getParent();
4458
+ if (import_ts_morph5.Node.isDeleteExpression(parent)) {
4459
+ return true;
4460
+ }
4461
+ return import_ts_morph5.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator2(parent.getOperatorToken().getKind());
4462
+ }
4463
+ function location3(node) {
4464
+ const relPath = import_path6.default.relative(
4465
+ process.cwd(),
4466
+ node.getSourceFile().getFilePath()
4467
+ );
4468
+ return `${relPath}:${node.getStartLineNumber()}`;
4469
+ }
4470
+ function warnDestructuredVersionFields(sourceFile) {
4471
+ for (const pattern of sourceFile.getDescendantsOfKind(
4472
+ import_ts_morph5.SyntaxKind.ObjectBindingPattern
4473
+ )) {
4474
+ const type = pattern.getType();
4475
+ if (!isVersionedEventConfig(type)) {
4476
+ continue;
4477
+ }
4478
+ const destructuresVersionField = pattern.getElements().some(
4479
+ (element) => !element.getDotDotDotToken() && !isVersionedField(
4480
+ type,
4481
+ element.getPropertyNameNode()?.getText() ?? element.getName()
4482
+ )
4483
+ );
4484
+ if (destructuresVersionField) {
4485
+ console.warn(
4486
+ ` [${location3(pattern)}] Destructures a field of a version from a VersionedEventConfig. Destructure it from \`${RESOLVE_EVENT_CONFIG_NAME}(config)\` by hand.`
4487
+ );
4488
+ }
4489
+ }
4490
+ }
4491
+ function findVersionFieldReads(sourceFile) {
4492
+ return sourceFile.getDescendantsOfKind(import_ts_morph5.SyntaxKind.PropertyAccessExpression).filter((node) => {
4493
+ const type = node.getExpression().getType();
4494
+ return isVersionedEventConfig(type) && !isVersionedField(type, node.getName());
4495
+ }).filter((node) => {
4496
+ if (node.hasQuestionDotToken()) {
4497
+ console.warn(
4498
+ ` [${location3(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${RESOLVE_EVENT_CONFIG_NAME}()\` by hand.`
4499
+ );
4500
+ return false;
4501
+ }
4502
+ if (isWriteTarget2(node)) {
4503
+ console.warn(
4504
+ ` [${location3(node)}] Skipped write to \`${node.getText()}\`. Set it in the version passed to \`defineConfig\` instead.`
4505
+ );
4506
+ return false;
4507
+ }
4508
+ return true;
4509
+ });
4510
+ }
4511
+ function isHandedOver(node) {
4512
+ const parent = node.getParent();
4513
+ if (import_ts_morph5.Node.isCallExpression(parent) || import_ts_morph5.Node.isNewExpression(parent)) {
4514
+ return parent.getArguments().includes(node);
4515
+ }
4516
+ return (import_ts_morph5.Node.isVariableDeclaration(parent) || import_ts_morph5.Node.isPropertyAssignment(parent)) && parent.getInitializer() === node || import_ts_morph5.Node.isReturnStatement(parent);
4517
+ }
4518
+ function findValuesExpectingEventConfig(sourceFile) {
4519
+ return sourceFile.getDescendants().filter((node) => import_ts_morph5.Node.isExpression(node)).filter(isHandedOver).map((node) => {
4520
+ const type = node.getType();
4521
+ const expectedType = node.getContextualType();
4522
+ if (!expectedType) {
4523
+ return void 0;
4524
+ }
4525
+ if (isVersionedEventConfig(type) && isEventConfig(expectedType)) {
4526
+ return { node, isArray: false };
4527
+ }
4528
+ if (isArrayOf(type, isVersionedEventConfig) && isArrayOf(expectedType, isEventConfig)) {
4529
+ return { node, isArray: true };
4530
+ }
4531
+ return void 0;
4532
+ }).filter((value) => value !== void 0).filter(({ node }) => {
4533
+ if (node.getType().isNullable()) {
4534
+ console.warn(
4535
+ ` [${location3(node)}] Skipped \`${node.getText()}\`, which may be undefined where an EventConfig is expected. Narrow it and pass \`${RESOLVE_EVENT_CONFIG_NAME}(...)\` by hand.`
4536
+ );
4537
+ return false;
4538
+ }
4539
+ return true;
4540
+ });
4541
+ }
4542
+ function findToolkitImport2(sourceFile) {
4543
+ return sourceFile.getImportDeclaration(
4544
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2 && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
4545
+ );
4546
+ }
4547
+ function findResolveEventConfigName(sourceFile) {
4548
+ const imported = findToolkitImport2(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === RESOLVE_EVENT_CONFIG_NAME);
4549
+ if (imported) {
4550
+ return imported.getAliasNode()?.getText() ?? RESOLVE_EVENT_CONFIG_NAME;
4551
+ }
4552
+ if (sourceFile.getLocal(RESOLVE_EVENT_CONFIG_NAME)) {
4553
+ return void 0;
4554
+ }
4555
+ return RESOLVE_EVENT_CONFIG_NAME;
4556
+ }
4557
+ function addResolveEventConfigImport(sourceFile) {
4558
+ const toolkitImport = findToolkitImport2(sourceFile);
4559
+ if (!toolkitImport) {
4560
+ const imports = sourceFile.getImportDeclarations();
4561
+ const lastImport = imports[imports.length - 1];
4562
+ sourceFile.insertStatements(
4563
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
4564
+ `import { ${RESOLVE_EVENT_CONFIG_NAME} } from '${TOOLKIT_EVENTS_MODULE2}'`
4565
+ );
4566
+ return;
4567
+ }
4568
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === RESOLVE_EVENT_CONFIG_NAME);
4569
+ if (alreadyImported) {
4570
+ return;
4571
+ }
4572
+ const namedImports = toolkitImport.getNamedImports();
4573
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
4574
+ toolkitImport.addNamedImport(RESOLVE_EVENT_CONFIG_NAME);
4575
+ return;
4576
+ }
4577
+ const names = [
4578
+ ...namedImports.map((namedImport) => namedImport.getText()),
4579
+ RESOLVE_EVENT_CONFIG_NAME
4580
+ ];
4581
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
4582
+ ${names.join(",\n ")}
4583
+ }` : `{ ${names.join(", ")} }`;
4584
+ toolkitImport.replaceWithText(
4585
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE2}'`
4586
+ );
4587
+ }
4588
+ function withToolkitEventsAt(compilerOptions, toolkitEventsPath) {
4589
+ return {
4590
+ ...compilerOptions,
4591
+ paths: {
4592
+ ...compilerOptions.paths,
4593
+ [TOOLKIT_EVENTS_MODULE2]: [toolkitEventsPath]
4594
+ }
4595
+ };
4596
+ }
4597
+ function rewriteVersionedEventConfigUses(sourceFile) {
4598
+ warnDestructuredVersionFields(sourceFile);
4599
+ const uses = [
4600
+ ...findVersionFieldReads(sourceFile).map((node) => ({
4601
+ node,
4602
+ rewrite: (name) => `${name}(${node.getExpression().getText()}).${node.getName()}`
4603
+ })),
4604
+ ...findValuesExpectingEventConfig(sourceFile).map(({ node, isArray }) => ({
4605
+ node,
4606
+ rewrite: (name) => isArray ? `${node.getText()}.map(${name})` : `${name}(${node.getText()})`
4607
+ }))
4608
+ ].sort(
4609
+ (a, b) => b.node.getStart() - a.node.getStart() || a.node.getEnd() - b.node.getEnd()
4610
+ );
4611
+ if (uses.length === 0) {
4612
+ return 0;
4613
+ }
4614
+ const resolveEventConfigName = findResolveEventConfigName(sourceFile);
4615
+ if (!resolveEventConfigName) {
4616
+ console.warn(
4617
+ ` [${location3(uses[uses.length - 1].node)}] Skipped ${uses.length} use(s): the file already declares its own \`${RESOLVE_EVENT_CONFIG_NAME}\`. Rewrite them to use the toolkit's \`${RESOLVE_EVENT_CONFIG_NAME}()\` by hand.`
4618
+ );
4619
+ return 0;
4620
+ }
4621
+ for (const { node, rewrite } of uses) {
4622
+ const before = node.getText();
4623
+ const after = rewrite(resolveEventConfigName);
4624
+ console.log(` [${location3(node)}] ${before} -> ${after}`);
4625
+ node.replaceWithText(after);
4626
+ }
4627
+ addResolveEventConfigImport(sourceFile);
4628
+ return uses.length;
4629
+ }
4630
+ async function main5() {
4631
+ const srcDir = import_path6.default.join(process.cwd(), "src");
4632
+ console.log(
4633
+ `Scanning for VersionedEventConfig used as an EventConfig in: ${srcDir}
4634
+ `
4635
+ );
4636
+ const tsConfigFilePath = import_path6.default.resolve(srcDir, "../tsconfig.json");
4637
+ const project = new import_ts_morph5.Project({
4638
+ tsConfigFilePath,
4639
+ skipAddingFilesFromTsConfig: false,
4640
+ // The events module of this toolkit, next to the migrations in `dist`
4641
+ compilerOptions: withToolkitEventsAt(
4642
+ (0, import_ts_morph5.getCompilerOptionsFromTsConfig)(tsConfigFilePath).options,
4643
+ import_path6.default.resolve(__dirname, "../events")
4644
+ )
4645
+ });
4646
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
4647
+ const fp = sf.getFilePath();
4648
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
4649
+ });
4650
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
4651
+ `);
4652
+ let totalChanges = 0;
4653
+ const modifiedFiles = [];
4654
+ for (const sourceFile of sourceFiles) {
4655
+ const changes = rewriteVersionedEventConfigUses(sourceFile);
4656
+ if (changes > 0) {
4657
+ totalChanges += changes;
4658
+ modifiedFiles.push(sourceFile);
4659
+ }
4660
+ }
4661
+ if (modifiedFiles.length === 0) {
4662
+ console.log(
4663
+ "No VersionedEventConfig used as an EventConfig found. Nothing to do."
4664
+ );
4665
+ return;
4666
+ }
4667
+ console.log(`
4668
+ Saving ${modifiedFiles.length} modified file(s)...`);
4669
+ for (const sourceFile of modifiedFiles) {
4670
+ await sourceFile.save();
4671
+ console.log(
4672
+ ` Saved: ${import_path6.default.relative(process.cwd(), sourceFile.getFilePath())}`
4673
+ );
4674
+ }
4675
+ console.log(
4676
+ `
4677
+ Done. Rewrote ${totalChanges} use(s) across ${modifiedFiles.length} file(s).`
4678
+ );
4679
+ }
4680
+
4681
+ // src/migrations/persistent/update-toolkit-dependency.ts
4682
+ var import_fs3 = __toESM(require("fs"));
4683
+ var import_path8 = __toESM(require("path"));
4684
+
4685
+ // src/migrations/persistent/check-upgrade-path.ts
4686
+ var import_fs2 = __toESM(require("fs"));
4687
+ var import_path7 = __toESM(require("path"));
4688
+ var TOOLKIT_PACKAGE_NAME = "@opencrvs/toolkit";
4689
+ function findMajorMinor(version) {
4690
+ const match = /(\d+)\.(\d+)/.exec(version);
4691
+ return match ? { major: Number(match[1]), minor: Number(match[2]) } : void 0;
4692
+ }
4693
+ function format({ major, minor }) {
4694
+ return `${major}.${minor}`;
4695
+ }
4696
+ function findCountryConfigToolkitVersion(cwd) {
4697
+ try {
4698
+ const packageJson = JSON.parse(
4699
+ import_fs2.default.readFileSync(import_path7.default.join(cwd, "package.json"), "utf-8")
4700
+ );
4701
+ return packageJson.dependencies?.[TOOLKIT_PACKAGE_NAME] ?? packageJson.devDependencies?.[TOOLKIT_PACKAGE_NAME];
4702
+ } catch {
4703
+ return void 0;
4704
+ }
4705
+ }
4706
+ function checkUpgradePath(countryConfigToolkitVersion, toolkitVersion) {
4707
+ const target = findMajorMinor(toolkitVersion);
4708
+ const current = countryConfigToolkitVersion ? findMajorMinor(countryConfigToolkitVersion) : void 0;
4709
+ if (!target || !current) {
4710
+ return {
4711
+ status: "unknown",
4712
+ message: `Could not tell which version the country config is on from its ${TOOLKIT_PACKAGE_NAME} dependency (${countryConfigToolkitVersion ?? "not found"}). Make sure it is on the version before ${toolkitVersion}: upgrade one minor version at a time.`
4713
+ };
4714
+ }
4715
+ const isSameVersion = current.major === target.major && current.minor === target.minor;
4716
+ const isPreviousMinor = current.major === target.major && current.minor === target.minor - 1;
4717
+ const isPreviousMajor = target.minor === 0 && current.major === target.major - 1;
4718
+ if (isSameVersion || isPreviousMinor || isPreviousMajor) {
4719
+ return { status: "ok" };
4720
+ }
4721
+ const isNewer = current.major > target.major || current.major === target.major && current.minor > target.minor;
4722
+ if (isNewer) {
4723
+ return {
4724
+ status: "blocked",
4725
+ message: `The country config is already on ${format(current)}, newer than toolkit ${toolkitVersion}. Run the upgrade with the toolkit of the version you are upgrading to.`
4726
+ };
4727
+ }
4728
+ const upgradesFrom = target.minor > 0 ? format({ major: target.major, minor: target.minor - 1 }) : `the last ${target.major - 1}.x`;
4729
+ const nextStep = current.major === target.major ? `: run \`npx ${TOOLKIT_PACKAGE_NAME}@${format({ major: current.major, minor: current.minor + 1 })} upgrade\` first` : "";
4730
+ return {
4731
+ status: "blocked",
4732
+ message: `The country config is on ${format(current)}, but toolkit ${toolkitVersion} only upgrades from ${upgradesFrom}. Upgrade one minor version at a time${nextStep}.`
4733
+ };
4734
+ }
4735
+
4736
+ // src/migrations/persistent/update-toolkit-dependency.ts
4737
+ var DEPENDENCY_PATTERN = new RegExp(
4738
+ `("${TOOLKIT_PACKAGE_NAME}"\\s*:\\s*")([^"]*)(")`,
4739
+ "g"
4740
+ );
4741
+ function updateToolkitDependency(packageJson, toolkitVersion) {
4742
+ const updated = packageJson.replace(
4743
+ DEPENDENCY_PATTERN,
4744
+ (match, before, version, after) => {
4745
+ if (!findMajorMinor(version)) {
4746
+ return match;
4747
+ }
4748
+ const range = /^[\^~]?/.exec(version)?.[0] ?? "";
4749
+ return `${before}${range}${toolkitVersion}${after}`;
4750
+ }
4751
+ );
4752
+ return updated === packageJson ? void 0 : updated;
4753
+ }
4754
+ async function main6(toolkitVersion) {
4755
+ const packageJsonPath = import_path8.default.join(process.cwd(), "package.json");
4756
+ if (!import_fs3.default.existsSync(packageJsonPath)) {
4757
+ console.log(`No package.json found. Skipping ${TOOLKIT_PACKAGE_NAME}.`);
4758
+ return;
4759
+ }
4760
+ const updated = updateToolkitDependency(
4761
+ import_fs3.default.readFileSync(packageJsonPath, "utf-8"),
4762
+ toolkitVersion
4763
+ );
4764
+ if (!updated) {
4765
+ console.log(
4766
+ `${TOOLKIT_PACKAGE_NAME} in package.json needs no update. Nothing to do.`
4767
+ );
4768
+ return;
4769
+ }
4770
+ import_fs3.default.writeFileSync(packageJsonPath, updated);
4771
+ console.log(
4772
+ `Updated ${TOOLKIT_PACKAGE_NAME} to ${toolkitVersion} in package.json. Install the dependencies again to use it.`
4773
+ );
4774
+ }
4775
+
4776
+ // src/migrations/replace-incomplete-flag.ts
4777
+ var import_ts_morph6 = require("ts-morph");
4778
+ var import_path9 = __toESM(require("path"));
4779
+ var INCOMPLETE = "InherentFlags.INCOMPLETE";
4780
+ var NOTIFIED_STATUS = `{ type: 'exact', term: EventStatus.enum.NOTIFIED }`;
4781
+ function ensureEventStatusImport(sourceFile) {
4782
+ const importDeclaration = sourceFile.getImportDeclarations().find(
4783
+ (declaration) => declaration.getNamedImports().some((named) => named.getName() === "InherentFlags")
4784
+ );
4785
+ const hasEventStatus = importDeclaration?.getNamedImports().some((named) => named.getName() === "EventStatus");
4786
+ if (importDeclaration && !hasEventStatus) {
4787
+ importDeclaration.addNamedImport("EventStatus");
4788
+ }
4789
+ }
4790
+ function replaceIncompleteFlag(sourceFile) {
4791
+ let changed = false;
4792
+ const anyOfIncomplete = sourceFile.getDescendantsOfKind(import_ts_morph6.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getParent()).filter(import_ts_morph6.Node.isArrayLiteralExpression).filter((array2) => {
4793
+ const anyOf = array2.getParent();
4794
+ const flags = anyOf?.getParent()?.getParent();
4795
+ return import_ts_morph6.Node.isPropertyAssignment(anyOf) && anyOf.getName() === "anyOf" && import_ts_morph6.Node.isPropertyAssignment(flags) && flags.getName() === "flags";
4796
+ });
4797
+ for (const array2 of anyOfIncomplete) {
4798
+ const anyOf = array2.getParentIfKindOrThrow(import_ts_morph6.SyntaxKind.PropertyAssignment);
4799
+ const flagsObject = anyOf.getParentIfKindOrThrow(
4800
+ import_ts_morph6.SyntaxKind.ObjectLiteralExpression
4801
+ );
4802
+ const flags = flagsObject.getParentIfKindOrThrow(
4803
+ import_ts_morph6.SyntaxKind.PropertyAssignment
4804
+ );
4805
+ const query = flags.getParentIfKindOrThrow(
4806
+ import_ts_morph6.SyntaxKind.ObjectLiteralExpression
4807
+ );
4808
+ array2.getElements().filter((element) => element.getText() === INCOMPLETE).forEach((element) => array2.removeElement(element));
4809
+ if (array2.getElements().length === 0) anyOf.remove();
4810
+ if (flagsObject.getProperties().length === 0) flags.remove();
4811
+ if (!query.getProperty("status")) {
4812
+ query.addPropertyAssignment({
4813
+ name: "status",
4814
+ initializer: NOTIFIED_STATUS
4815
+ });
4816
+ }
4817
+ changed = true;
4818
+ }
4819
+ if (changed) ensureEventStatusImport(sourceFile);
4820
+ const remaining = sourceFile.getDescendantsOfKind(import_ts_morph6.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
4821
+ return { changed, remaining };
4822
+ }
4823
+ async function main7() {
4824
+ const project = new import_ts_morph6.Project({
4825
+ tsConfigFilePath: import_path9.default.join(process.cwd(), "tsconfig.json")
4826
+ });
4827
+ const sourceFiles = project.getSourceFiles().filter((sf) => !sf.getFilePath().includes("/node_modules/"));
4828
+ for (const sourceFile of sourceFiles) {
4829
+ const relPath = import_path9.default.relative(process.cwd(), sourceFile.getFilePath());
4830
+ const { changed, remaining } = replaceIncompleteFlag(sourceFile);
4831
+ if (changed) {
4832
+ await sourceFile.save();
4833
+ console.log(
4834
+ ` [${relPath}] Replaced the incomplete flag with the NOTIFIED status`
4835
+ );
4836
+ }
4837
+ for (const line2 of remaining) {
4838
+ console.warn(
4839
+ ` [${relPath}:${line2}] ${INCOMPLETE} was removed, update this reference to use the NOTIFIED status`
4840
+ );
4841
+ }
4842
+ }
4843
+ }
4844
+
4845
+ // src/migrations/index.ts
4846
+ async function runUpgrade(toolkitVersion) {
4847
+ const [major, minor] = toolkitVersion.split(".");
4848
+ await main2();
4849
+ await main3();
4850
+ await main5();
4851
+ await main4();
4852
+ await main(`${major}.${minor}`);
4853
+ await main7();
4854
+ await main6(toolkitVersion);
4855
+ }
4856
+
4857
+ // src/environment/index.ts
4858
+ var import_fs8 = require("fs");
4859
+ var import_path14 = require("path");
4860
+ init_paths();
4861
+ var REQUIRED_REPOSITORY_DIRECTORIES = [
4862
+ ".github/workflows",
4863
+ "environments",
4864
+ "infrastructure"
4865
+ ];
4866
+ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
4867
+ const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
4868
+ (directory) => {
4869
+ try {
4870
+ return !(0, import_fs8.statSync)((0, import_path14.resolve)(repositoryRoot, directory)).isDirectory();
4871
+ } catch {
4872
+ return true;
4873
+ }
4874
+ }
4875
+ );
4876
+ if (missingDirectories.length > 0) {
4877
+ throw new Error(
4878
+ `The current directory is not a valid OpenCRVS country configuration repository. Missing required director${missingDirectories.length === 1 ? "y" : "ies"}: ${missingDirectories.join(", ")}`
4879
+ );
4880
+ }
4881
+ }
4882
+ async function runEnvironmentInit() {
4883
+ validateRepositoryStructure();
4884
+ assertNoOldInventoryLayout();
4885
+ const { runSetupEnvironment: runSetupEnvironment2 } = await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
4886
+ await runSetupEnvironment2();
4887
+ }
4888
+ async function runEnvironmentUpgrade() {
4889
+ validateRepositoryStructure();
4890
+ const { upgradeEnvironmentLayout: upgradeEnvironmentLayout2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
4891
+ await upgradeEnvironmentLayout2();
4892
+ }
4893
+ async function runEnvironmentUpdateWorkflows() {
4894
+ validateRepositoryStructure();
4895
+ const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
4896
+ await updateWorkflowEnvironments2();
4897
+ }
4898
+ async function runEnvironmentUsers() {
4899
+ validateRepositoryStructure();
4900
+ const { manageEnvironmentUsers: manageEnvironmentUsers2 } = await Promise.resolve().then(() => (init_users(), users_exports));
4901
+ await manageEnvironmentUsers2();
4902
+ }
4903
+ async function runEnvironmentSwarmToK8s() {
4904
+ validateRepositoryStructure();
4905
+ await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
4906
+ }
4907
+
4908
+ // src/configurator/index.ts
4909
+ var import_node_fs6 = require("node:fs");
4910
+ var import_node_path8 = require("node:path");
4911
+ var import_node_util = require("node:util");
4912
+
4913
+ // src/configurator/layout.ts
4914
+ var import_node_fs2 = require("node:fs");
4915
+ var import_node_path2 = require("node:path");
4916
+
4917
+ // src/configurator/paths.ts
4918
+ var import_node_fs = require("node:fs");
4919
+ var import_node_path = require("node:path");
4920
+ var OLD_INVENTORY_DIR2 = (0, import_node_path.join)(
4921
+ "infrastructure",
4922
+ "server-setup",
4923
+ "inventory"
4924
+ );
4925
+ var ENVIRONMENTS_DIR = "environments";
4926
+ var WORKFLOWS_DIR = (0, import_node_path.join)(".github", "workflows");
4927
+ var INVENTORY_FILE_NAME2 = "inventory.yml";
4928
+ function environmentInventoryPath(environment) {
4929
+ return (0, import_node_path.join)(ENVIRONMENTS_DIR, environment, INVENTORY_FILE_NAME2);
4930
+ }
4931
+ function isDirectory2(path15) {
4932
+ try {
4933
+ return (0, import_node_fs.statSync)(path15).isDirectory();
4934
+ } catch {
4935
+ return false;
4936
+ }
4937
+ }
4938
+ function assertInfrastructureRepository(root, required = [
4939
+ WORKFLOWS_DIR,
4940
+ ENVIRONMENTS_DIR,
4941
+ "infrastructure"
4942
+ ]) {
4943
+ const missing = required.filter(
4944
+ (directory) => !isDirectory2((0, import_node_path.resolve)(root, directory))
4945
+ );
4946
+ if (missing.length > 0) {
4947
+ throw new Error(
4948
+ `The current directory is not a valid OpenCRVS infrastructure repository. Missing required director${missing.length === 1 ? "y" : "ies"}: ${missing.join(", ")}`
4949
+ );
4950
+ }
4951
+ }
4952
+
4953
+ // src/configurator/layout.ts
4954
+ function findOldInventoryFiles2(root) {
4955
+ const directory = (0, import_node_path2.join)(root, OLD_INVENTORY_DIR2);
4956
+ if (!isDirectory2(directory)) return [];
4957
+ return (0, import_node_fs2.readdirSync)(directory, { withFileTypes: true }).filter((entry) => entry.isFile() && entry.name.endsWith(".yml")).map((entry) => (0, import_node_path2.join)(OLD_INVENTORY_DIR2, entry.name)).sort();
4958
+ }
4959
+ function migrateLayout(root) {
4960
+ const oldFiles = findOldInventoryFiles2(root);
4961
+ const result = {
4962
+ moved: [],
4963
+ skipped: [],
4964
+ oldDirectoryRemoved: false
4965
+ };
4966
+ if (oldFiles.length === 0) return result;
4967
+ for (const from of oldFiles) {
4968
+ const environment = (0, import_node_path2.basename)(from, ".yml");
4969
+ const move = {
4970
+ environment,
4971
+ from,
4972
+ to: environmentInventoryPath(environment)
4973
+ };
4974
+ if ((0, import_node_fs2.existsSync)((0, import_node_path2.join)(root, move.to))) {
4975
+ result.skipped.push(move);
4976
+ continue;
4977
+ }
4978
+ (0, import_node_fs2.mkdirSync)((0, import_node_path2.dirname)((0, import_node_path2.join)(root, move.to)), { recursive: true });
4979
+ (0, import_node_fs2.renameSync)((0, import_node_path2.join)(root, move.from), (0, import_node_path2.join)(root, move.to));
4980
+ result.moved.push(move);
4981
+ }
4982
+ const oldDirectory = (0, import_node_path2.join)(root, OLD_INVENTORY_DIR2);
4983
+ try {
4984
+ if ((0, import_node_fs2.readdirSync)(oldDirectory).length === 0) {
4985
+ (0, import_node_fs2.rmdirSync)(oldDirectory);
4986
+ result.oldDirectoryRemoved = true;
4987
+ }
4988
+ } catch {
4989
+ }
4990
+ return result;
4991
+ }
4992
+ function assertNoOldInventoryLayout2(root) {
4993
+ if (findOldInventoryFiles2(root).length === 0) return;
4994
+ throw new Error(
4995
+ `Old inventory layout detected at ${OLD_INVENTORY_DIR2}. Please run \`opencrvs configurator upgrade\` before \`opencrvs configurator init\`.`
4996
+ );
4997
+ }
4998
+
4999
+ // src/configurator/server/start.ts
5000
+ var import_node_http = require("node:http");
5001
+ var import_node_fs4 = require("node:fs");
5002
+ var import_promises4 = require("node:fs/promises");
5003
+ var import_node_path6 = require("node:path");
5004
+ var import_yaml = require("yaml");
5005
+
5006
+ // src/configurator/server/plugin.ts
5007
+ var import_node_fs3 = require("node:fs");
5008
+ var import_node_path5 = require("node:path");
5009
+
5010
+ // src/configurator/server/environments.ts
5011
+ var import_promises2 = require("node:fs/promises");
5012
+ var import_node_path3 = require("node:path");
5013
+ var ENVIRONMENT_FILES = ["inventory.yml", "dependencies/values.yaml", "traefik/values.yaml", "opencrvs-services/values.yaml"];
5014
+ var INVENTORY = ENVIRONMENT_FILES[0];
5015
+ var YAML_FILE = /\.ya?ml$/;
5016
+ var SAFE_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
5017
+ async function listEnvironmentNames(dir) {
5018
+ let entries;
5019
+ try {
5020
+ entries = await (0, import_promises2.readdir)(dir, { withFileTypes: true });
5021
+ } catch {
5022
+ return { names: [], layout: "none" };
5023
+ }
5024
+ const folders = entries.filter((entry) => entry.isDirectory() && !entry.name.startsWith("."));
5025
+ if (folders.length > 0) {
5026
+ return { names: folders.map((entry) => entry.name).sort(), layout: "folders" };
5027
+ }
5028
+ const files = entries.filter((entry) => entry.isFile() && YAML_FILE.test(entry.name));
5029
+ if (files.length > 0) {
5030
+ return { names: files.map((entry) => entry.name.replace(YAML_FILE, "")).sort(), layout: "files" };
5031
+ }
5032
+ return { names: [], layout: "none" };
5033
+ }
5034
+ async function readIfPresent(path15) {
5035
+ try {
5036
+ return await (0, import_promises2.readFile)(path15, "utf8");
5037
+ } catch {
5038
+ return void 0;
5039
+ }
5040
+ }
5041
+ async function readEnvironmentFiles(dir, name, flatFile = INVENTORY) {
5042
+ if (!SAFE_NAME.test(name)) return void 0;
5043
+ const { names, layout } = await listEnvironmentNames(dir);
5044
+ if (!names.includes(name)) return void 0;
5045
+ const files = {};
5046
+ if (layout === "files") {
5047
+ for (const extension of [".yml", ".yaml"]) {
5048
+ const text2 = await readIfPresent((0, import_node_path3.join)(dir, `${name}${extension}`));
5049
+ if (text2 !== void 0) files[flatFile] = text2;
5050
+ }
5051
+ return files;
5052
+ }
5053
+ for (const file of ENVIRONMENT_FILES) {
5054
+ const text2 = await readIfPresent((0, import_node_path3.join)(dir, name, file));
5055
+ if (text2 !== void 0) files[file] = text2;
5056
+ }
5057
+ return files;
5058
+ }
5059
+ async function fileTargets(dir, name, flatFile = INVENTORY) {
5060
+ const { layout } = await listEnvironmentNames(dir);
5061
+ const targets = {};
5062
+ if (layout === "files") {
5063
+ const hasYaml = await readIfPresent((0, import_node_path3.join)(dir, `${name}.yaml`)) !== void 0;
5064
+ const hasYml = await readIfPresent((0, import_node_path3.join)(dir, `${name}.yml`)) !== void 0;
5065
+ const extension = hasYml && !hasYaml ? ".yml" : ".yaml";
5066
+ for (const path15 of ENVIRONMENT_FILES) targets[path15] = path15 === flatFile ? `${name}${extension}` : null;
5067
+ } else {
5068
+ for (const path15 of ENVIRONMENT_FILES) targets[path15] = `${name}/${path15}`;
5069
+ }
5070
+ return { layout, targets };
5071
+ }
5072
+ function parseGitRemote(url) {
5073
+ const match = url.trim().match(/github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/);
5074
+ return match ? { owner: match[1], repo: match[2] } : null;
5075
+ }
5076
+ async function readGitRemote(cwd) {
5077
+ const config = await readIfPresent((0, import_node_path3.join)(cwd, ".git", "config"));
5078
+ if (config === void 0) return void 0;
5079
+ let inOrigin = false;
5080
+ for (const line2 of config.split(/\r?\n/)) {
5081
+ const section = line2.match(/^\s*\[(.*)\]\s*$/);
5082
+ if (section) {
5083
+ inOrigin = /^remote\s+"origin"$/.test(section[1].trim());
5084
+ continue;
5085
+ }
5086
+ const url = inOrigin ? line2.match(/^\s*url\s*=\s*(.+?)\s*$/) : null;
5087
+ if (url) return url[1];
5088
+ }
5089
+ return void 0;
5090
+ }
5091
+
5092
+ // src/configurator/server/files.ts
5093
+ var import_handlebars2 = __toESM(require("handlebars"));
5094
+ var import_promises3 = require("node:fs/promises");
5095
+ var import_node_path4 = require("node:path");
5096
+
5097
+ // src/configurator/ui/form/users.ts
5098
+ function parseKeys(text2) {
5099
+ if (typeof text2 !== "string") return [];
5100
+ return text2.split("\n").map((line2) => line2.trim()).filter((line2) => line2 && !line2.startsWith("#"));
5101
+ }
5102
+ function rowsToUsers(rows) {
5103
+ if (!Array.isArray(rows)) return [];
5104
+ return rows.filter((row) => row?.name?.trim()).map((row) => ({
5105
+ name: row.name.trim(),
5106
+ ssh_keys: parseKeys(row.ssh_keys),
5107
+ state: row.state ?? "present",
5108
+ role: row.role ?? "operator"
5109
+ }));
5110
+ }
5111
+
5112
+ // src/configurator/ui/bindings/parsers.ts
5113
+ var text = (raw) => typeof raw === "string" || typeof raw === "number" || typeof raw === "boolean" ? String(raw).trim() : "";
5114
+ var FORMATTERS = {
5115
+ string: (value) => typeof value === "string" ? value.trim() : String(value),
5116
+ boolean: (value) => value === true || value === "true",
5117
+ // table rows -> "10.0.0.1,10.0.0.2" (a GitHub variable)
5118
+ "csv-to-ip-rows": (value) => ipsOf(value).join(","),
5119
+ // table rows -> ["10.0.0.1", "10.0.0.2"] (a template list)
5120
+ "ip-rows": (value) => ipsOf(value),
5121
+ // table rows -> the users the inventory template expects
5122
+ users: (value) => rowsToUsers(value)
5123
+ };
5124
+ function ipsOf(rows) {
5125
+ if (!Array.isArray(rows)) return [];
5126
+ return rows.map((row) => text(row?.ip)).filter(Boolean);
5127
+ }
5128
+ function formatWith(name, value) {
5129
+ const formatter = FORMATTERS[name ?? "string"];
5130
+ if (!formatter) throw new Error(`Unknown parser "${name}"`);
5131
+ return formatter(value);
5132
+ }
5133
+
5134
+ // src/configurator/ui/plan/dependencyHosts.ts
5135
+ var DEFAULT_HOSTS = {
5136
+ ELASTICSEARCH_HOST: (environment) => `elasticsearch.opencrvs-deps-${environment}.svc.cluster.local`,
5137
+ S3_HOST: (environment) => `rustfs-0.rustfs.opencrvs-deps-${environment}.svc.cluster.local`,
5138
+ POSTGRES_HOST: (environment) => `postgres-0.postgres.opencrvs-deps-${environment}.svc.cluster.local`,
5139
+ REDIS_HOST: (environment) => `redis-0.redis.opencrvs-deps-${environment}.svc.cluster.local`,
5140
+ OTEL_COLLECTOR_ENDPOINT: (environment) => `http://opentelemetry-collector.opencrvs-deps-${environment}.svc.cluster.local:4317`
5141
+ };
5142
+
5143
+ // src/configurator/ui/plan/templateValues.ts
5144
+ var DERIVED = {
5145
+ env: ({ environment }) => environment,
5146
+ // A cluster is a single node unless it has workers or a backup server (the CLI passes a string).
5147
+ single_node: ({ fromQuestions }) => fromQuestions.kube_worker_nodes?.length || fromQuestions.backup_host ? "false" : "true",
5148
+ backup_enabled: ({ answers }) => answers.BACKUP_OR_RESTORE === "backup",
5149
+ restore_enabled: ({ answers }) => answers.BACKUP_OR_RESTORE === "restore",
5150
+ opencrvs_environment: ({ environment }) => environment,
5151
+ // On unless the question says otherwise (the template reads it only to switch tracing on).
5152
+ monitoring_enabled: ({ answers }) => answers.MONITORING_ENABLED !== false,
5153
+ lets_encrypt: ({ answers }) => answers.TRAEFIK_MODE === "lets_encrypt",
5154
+ static_ssl: ({ answers }) => answers.TRAEFIK_MODE === "static_ssl"
5155
+ };
5156
+ var variableOf = (target) => target.collect === "container" ? target.var.split(".")[0] : target.var;
5157
+ function* fileTargets2(template, bindings) {
5158
+ for (const [question, binding] of Object.entries(bindings.bindings)) {
5159
+ for (const target of binding.targets) {
5160
+ if (target.source === "file" && target.template === template) yield { question, target, variable: variableOf(target) };
5161
+ }
5162
+ }
5163
+ }
5164
+ function builtInValues(template, environment, bindings) {
5165
+ const values = {};
5166
+ for (const { question, variable } of fileTargets2(template, bindings)) {
5167
+ const address = DEFAULT_HOSTS[question];
5168
+ if (address) values[variable] = address(environment);
5169
+ }
5170
+ return values;
5171
+ }
5172
+ function templateValues(template, environment, answers, bindings) {
5173
+ const fromQuestions = {};
5174
+ for (const { question, target, variable } of fileTargets2(template, bindings)) {
5175
+ if (answers[question] !== void 0) fromQuestions[variable] = formatWith(target.parse, answers[question]);
5176
+ }
5177
+ const config = bindings.templates?.[template];
5178
+ const values = { ...config?.defaults ?? {}, ...fromQuestions };
5179
+ for (const [variable, address] of Object.entries(builtInValues(template, environment, bindings))) {
5180
+ if (!values[variable]) values[variable] = address;
5181
+ }
5182
+ for (const name of config?.derived ?? []) {
5183
+ const derive = DERIVED[name];
5184
+ if (!derive) throw new Error(`${template}: no derived value named "${name}"`);
5185
+ values[name] = derive({ environment, answers, fromQuestions });
5186
+ }
5187
+ return values;
5188
+ }
5189
+
5190
+ // src/configurator/server/files.ts
5191
+ function renderEnvironmentFiles({ environment, values, bindings, readTemplate: readTemplate2 }) {
5192
+ const files = {};
5193
+ for (const [template, output] of Object.entries(bindings.files)) {
5194
+ const handlebars = import_handlebars2.default.create();
5195
+ handlebars.registerHelper("data_label_idx", (value) => Number.parseInt(String(value), 10) + 2);
5196
+ files[output] = handlebars.compile(readTemplate2(template))(templateValues(template, environment, values, bindings));
5197
+ }
5198
+ return files;
5199
+ }
5200
+ async function writeEnvironmentFiles(dir, environment, files, flatFile) {
5201
+ if (!SAFE_NAME.test(environment)) throw new Error("Invalid environment name.");
5202
+ for (const path15 of Object.keys(files)) {
5203
+ if (!ENVIRONMENT_FILES.includes(path15)) throw new Error(`Refusing to write ${path15}.`);
5204
+ }
5205
+ const { targets } = await fileTargets(dir, environment, flatFile);
5206
+ const written = [];
5207
+ for (const [path15, text2] of Object.entries(files)) {
5208
+ const target = targets[path15];
5209
+ if (target === null || target === void 0) continue;
5210
+ await (0, import_promises3.mkdir)((0, import_node_path4.dirname)((0, import_node_path4.join)(dir, target)), { recursive: true });
5211
+ await (0, import_promises3.writeFile)((0, import_node_path4.join)(dir, target), text2);
5212
+ written.push(target);
5213
+ }
5214
+ return written;
5215
+ }
5216
+
5217
+ // src/configurator/server/seal.ts
5218
+ var import_libsodium_wrappers2 = __toESM(require("libsodium-wrappers"));
5219
+ async function sealSecret(publicKeyBase64, value) {
5220
+ await import_libsodium_wrappers2.default.ready;
5221
+ const key = import_libsodium_wrappers2.default.from_base64(publicKeyBase64, import_libsodium_wrappers2.default.base64_variants.ORIGINAL);
5222
+ const sealed = import_libsodium_wrappers2.default.crypto_box_seal(import_libsodium_wrappers2.default.from_string(value), key);
5223
+ return import_libsodium_wrappers2.default.to_base64(sealed, import_libsodium_wrappers2.default.base64_variants.ORIGINAL);
5224
+ }
5225
+
5226
+ // src/configurator/server/github.ts
5227
+ var GitHubError = class extends Error {
5228
+ status;
5229
+ constructor(message, status) {
5230
+ super(message);
5231
+ this.status = status;
5232
+ }
5233
+ };
5234
+ var API_VERSION = "2022-11-28";
5235
+ var PER_PAGE = 100;
5236
+ var GitHubClient = class {
5237
+ owner;
5238
+ repo;
5239
+ token;
5240
+ baseUrl;
5241
+ fetchImpl;
5242
+ constructor(options) {
5243
+ this.owner = options.owner;
5244
+ this.repo = options.repo;
5245
+ this.token = options.token;
5246
+ this.baseUrl = new URL(options.baseUrl ?? "https://api.github.com");
5247
+ this.fetchImpl = options.fetch ?? fetch;
5248
+ }
5249
+ repoPath(suffix = "") {
5250
+ return `/repos/${encodeURIComponent(this.owner)}/${encodeURIComponent(this.repo)}${suffix}`;
5251
+ }
5252
+ // Messages never contain the token, a value that was sent, or anything GitHub sent back.
5253
+ async request(method, url, body) {
5254
+ let response;
5255
+ try {
5256
+ response = await this.fetchImpl(url, {
5257
+ method,
5258
+ headers: {
5259
+ Authorization: `Bearer ${this.token}`,
5260
+ Accept: "application/vnd.github+json",
5261
+ "X-GitHub-Api-Version": API_VERSION,
5262
+ "User-Agent": "env-init-ui",
5263
+ ...body === void 0 ? {} : { "Content-Type": "application/json" }
5264
+ },
5265
+ body: body === void 0 ? void 0 : JSON.stringify(body)
5266
+ });
5267
+ } catch {
5268
+ throw new GitHubError("Could not reach GitHub.");
5269
+ }
5270
+ if (response.ok) return response;
5271
+ if (response.status === 401) throw new GitHubError("GitHub rejected the token (bad credentials).", 401);
5272
+ if (response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0") {
5273
+ throw new GitHubError("GitHub rate limit reached. Try again later.", 403);
5274
+ }
5275
+ if (response.status === 403) {
5276
+ throw new GitHubError(
5277
+ method === "GET" ? "The token is not allowed to read this (HTTP 403)." : "The token is not allowed to change this (HTTP 403). Writing needs access to the repository, and creating environments needs admin access.",
5278
+ 403
5279
+ );
5280
+ }
5281
+ if (response.status === 404) {
5282
+ throw new GitHubError(`Not found: ${this.owner}/${this.repo}, or the token cannot see it.`, 404);
5283
+ }
5284
+ if (response.status === 409) throw new GitHubError("GitHub reports a conflict (HTTP 409).", 409);
5285
+ if (response.status === 422) throw new GitHubError("GitHub refused the request (HTTP 422).", 422);
5286
+ throw new GitHubError(`GitHub answered with HTTP ${response.status}.`, response.status);
5287
+ }
5288
+ get(url) {
5289
+ return this.request("GET", url);
5290
+ }
5291
+ url(path15) {
5292
+ return new URL(path15, this.baseUrl);
5293
+ }
5294
+ // Follows rel="next" links, but only ones on the same host: the token must never be sent elsewhere.
5295
+ async paginate(path15, pick) {
5296
+ const items = [];
5297
+ let next = this.url(path15);
5298
+ next.searchParams.set("per_page", String(PER_PAGE));
5299
+ for (let page = 0; next && page < 100; page++) {
5300
+ const response = await this.get(next);
5301
+ items.push(...pick(await response.json()));
5302
+ const link = response.headers.get("link") ?? "";
5303
+ const target = link.match(/<([^>]+)>;\s*rel="next"/)?.[1];
5304
+ const candidate = target ? new URL(target, this.baseUrl) : void 0;
5305
+ next = candidate && candidate.origin === this.baseUrl.origin ? candidate : void 0;
5306
+ }
5307
+ return items;
5308
+ }
5309
+ // Checks the token and what it can do. Classic tokens report their scopes in a header;
5310
+ // fine-grained tokens do not, so for those only the repository permissions can be checked.
5311
+ async connect() {
5312
+ try {
5313
+ const user = await this.get(this.url("/user"));
5314
+ const scopesHeader = user.headers.get("x-oauth-scopes");
5315
+ const login = String((await user.json()).login ?? this.owner);
5316
+ const repository = await this.get(this.url(this.repoPath()));
5317
+ const permissions = (await repository.json()).permissions ?? {};
5318
+ const missing = [];
5319
+ if (scopesHeader !== null) {
5320
+ const scopes = scopesHeader.split(",").map((scope) => scope.trim());
5321
+ if (!scopes.includes("repo")) missing.push('manage environments, secrets and variables or trigger workflows (classic token scope "repo")');
5322
+ if (!scopes.includes("workflow")) missing.push('update workflow files (classic token scope "workflow")');
5323
+ }
5324
+ if (!permissions.admin) missing.push("create environments (needs admin access to the repository)");
5325
+ return { ok: true, login, missingPermissions: missing };
5326
+ } catch (error2) {
5327
+ return { ok: false, error: error2 instanceof GitHubError ? error2.message : "Could not reach GitHub." };
5328
+ }
3680
5329
  }
3681
- console.log(`
3682
- Saving ${modifiedFiles.length} modified file(s)...`);
3683
- for (const sourceFile of modifiedFiles) {
3684
- await sourceFile.save();
3685
- console.log(
3686
- ` Saved: ${import_path2.default.relative(process.cwd(), sourceFile.getFilePath())}`
3687
- );
5330
+ async listEnvironments() {
5331
+ const environments = await this.paginate(this.repoPath("/environments"), (body) => body.environments ?? []);
5332
+ return environments.map((environment) => environment.name);
3688
5333
  }
3689
- console.log(
3690
- `
3691
- Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length} file(s).`
3692
- );
3693
- }
5334
+ async readScope(base) {
5335
+ const [variables, secrets] = await Promise.all([
5336
+ this.paginate(`${base}/variables`, (body) => body.variables ?? []),
5337
+ this.paginate(`${base}/secrets`, (body) => body.secrets ?? [])
5338
+ ]);
5339
+ return {
5340
+ variables: Object.fromEntries(variables.map((variable) => [variable.name, variable.value])),
5341
+ // GitHub returns names (and dates) for secrets, never values.
5342
+ secretNames: secrets.map((secret) => secret.name)
5343
+ };
5344
+ }
5345
+ readRepository() {
5346
+ return this.readScope(this.repoPath("/actions"));
5347
+ }
5348
+ async readEnvironment(name) {
5349
+ try {
5350
+ return await this.readScope(this.repoPath(`/environments/${encodeURIComponent(name)}`));
5351
+ } catch (error2) {
5352
+ if (error2 instanceof GitHubError && error2.status === 404) return { variables: {}, secretNames: [] };
5353
+ throw error2;
5354
+ }
5355
+ }
5356
+ // --- writing ---------------------------------------------------------------------------
5357
+ scopeBase(target) {
5358
+ return target.scope === "environment" ? this.repoPath(`/environments/${encodeURIComponent(target.environment ?? "")}`) : this.repoPath("/actions");
5359
+ }
5360
+ // Creates the environment, or leaves it as it is if it exists.
5361
+ async createEnvironment(name) {
5362
+ await this.request("PUT", this.url(this.repoPath(`/environments/${encodeURIComponent(name)}`)), {});
5363
+ }
5364
+ // A 404 on an environment's variables or secrets means the environment is missing,
5365
+ // not that the repository is: say so.
5366
+ async inEnvironment(target, action) {
5367
+ try {
5368
+ await action();
5369
+ } catch (error2) {
5370
+ if (error2 instanceof GitHubError && error2.status === 404 && target.scope === "environment") {
5371
+ throw new GitHubError(`The environment \u201C${target.environment}\u201D does not exist yet.`, 404);
5372
+ }
5373
+ throw error2;
5374
+ }
5375
+ }
5376
+ putVariable(target, exists) {
5377
+ return this.inEnvironment(target, () => this.putVariableUnchecked(target, exists));
5378
+ }
5379
+ putSecret(target) {
5380
+ return this.inEnvironment(target, () => this.putSecretUnchecked(target));
5381
+ }
5382
+ // `exists` is what the plan found out; if it was wrong, the other call is tried.
5383
+ async putVariableUnchecked(target, exists) {
5384
+ const base = `${this.scopeBase(target)}/variables`;
5385
+ const create = () => this.request("POST", this.url(base), { name: target.name, value: target.value });
5386
+ const update = () => this.request("PATCH", this.url(`${base}/${encodeURIComponent(target.name)}`), { name: target.name, value: target.value });
5387
+ try {
5388
+ await (exists ? update() : create());
5389
+ } catch (error2) {
5390
+ if (!(error2 instanceof GitHubError)) throw error2;
5391
+ if (!exists && error2.status === 409) await update();
5392
+ else if (exists && error2.status === 404) await create();
5393
+ else throw error2;
5394
+ }
5395
+ }
5396
+ async putSecretUnchecked(target) {
5397
+ const base = `${this.scopeBase(target)}/secrets`;
5398
+ const key = await (await this.get(this.url(`${base}/public-key`))).json();
5399
+ const encrypted = await sealSecret(key.key, target.value);
5400
+ await this.request("PUT", this.url(`${base}/${encodeURIComponent(target.name)}`), {
5401
+ encrypted_value: encrypted,
5402
+ key_id: key.key_id
5403
+ });
5404
+ }
5405
+ };
3694
5406
 
3695
- // src/migrations/v2.2/index.ts
3696
- async function runUpgrade() {
3697
- await main2();
3698
- await main("2.2");
5407
+ // src/configurator/server/sshKeys.ts
5408
+ var import_ssh22 = __toESM(require("ssh2"));
5409
+ var { utils: utils2 } = import_ssh22.default;
5410
+ function generateSSHKeyPair2() {
5411
+ const keys = utils2.generateKeyPairSync("ed25519");
5412
+ return {
5413
+ publicKey: keys.public.toString(),
5414
+ privateKey: keys.private.toString()
5415
+ };
3699
5416
  }
3700
5417
 
3701
- // src/environment/index.ts
3702
- var import_fs6 = require("fs");
3703
- var import_path7 = require("path");
3704
- init_paths();
3705
- var REQUIRED_REPOSITORY_DIRECTORIES = [
3706
- ".github/workflows",
3707
- "environments",
3708
- "infrastructure"
3709
- ];
3710
- function validateRepositoryStructure(repositoryRoot = process.cwd()) {
3711
- const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
3712
- (directory) => {
3713
- try {
3714
- return !(0, import_fs6.statSync)((0, import_path7.resolve)(repositoryRoot, directory)).isDirectory();
3715
- } catch {
3716
- return true;
5418
+ // src/configurator/server/plugin.ts
5419
+ var GitHubSession = class {
5420
+ client;
5421
+ baseUrl;
5422
+ fetchImpl;
5423
+ constructor(options = {}) {
5424
+ this.baseUrl = options.baseUrl;
5425
+ this.fetchImpl = options.fetch;
5426
+ }
5427
+ async connect(token, owner, repo) {
5428
+ const client = new GitHubClient({ token, owner, repo, baseUrl: this.baseUrl, fetch: this.fetchImpl });
5429
+ const result = await client.connect();
5430
+ this.client = result.ok ? client : void 0;
5431
+ return result;
5432
+ }
5433
+ disconnect() {
5434
+ this.client = void 0;
5435
+ }
5436
+ get current() {
5437
+ return this.client;
5438
+ }
5439
+ };
5440
+ var LOCAL_HOST = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/;
5441
+ var NAME = /^[A-Za-z0-9_.-]{1,100}$/;
5442
+ var VARIABLE_NAME = /^[A-Za-z_][A-Za-z0-9_]{0,99}$/;
5443
+ var MAX_VALUE = 49152;
5444
+ var fail = (status, error2) => ({ status, body: { error: error2 } });
5445
+ function crossSiteProblem(request2) {
5446
+ const host = request2.host ?? "localhost";
5447
+ if (!LOCAL_HOST.test(host)) return "Only local requests are accepted.";
5448
+ if (request2.origin !== void 0 && request2.origin !== `http://${host}`) return "Requests from other sites are not accepted.";
5449
+ return void 0;
5450
+ }
5451
+ var mapGitHubError = (error2) => error2 instanceof GitHubError ? fail(error2.status === 401 ? 401 : 502, error2.message) : fail(502, "Could not reach GitHub.");
5452
+ async function githubWrite(path15, body, session) {
5453
+ const client = session.current;
5454
+ if (!client) return fail(409, "Not connected to GitHub.");
5455
+ const input4 = body ?? {};
5456
+ try {
5457
+ if (path15 === "/api/github/environment") {
5458
+ if (typeof input4.name !== "string" || !NAME.test(input4.name)) return fail(400, "Invalid environment name.");
5459
+ await client.createEnvironment(input4.name);
5460
+ return { status: 200, body: { ok: true } };
5461
+ }
5462
+ const { scope, environment, name, value } = input4;
5463
+ if (scope !== "environment" && scope !== "repository") return fail(400, "Scope must be environment or repository.");
5464
+ if (scope === "environment" && (typeof environment !== "string" || !NAME.test(environment))) return fail(400, "Invalid environment name.");
5465
+ if (typeof name !== "string" || !VARIABLE_NAME.test(name)) return fail(400, "Invalid variable or secret name.");
5466
+ if (typeof value !== "string" || value === "" || value.length > MAX_VALUE) return fail(400, "The value must be 1 to 49152 characters.");
5467
+ const target = { scope, name, value, ...scope === "environment" ? { environment } : {} };
5468
+ if (path15 === "/api/github/variable") await client.putVariable(target, typeof input4.exists === "boolean" ? input4.exists : void 0);
5469
+ else await client.putSecret(target);
5470
+ return { status: 200, body: { ok: true } };
5471
+ } catch (error2) {
5472
+ return mapGitHubError(error2);
5473
+ }
5474
+ }
5475
+ async function githubRoute(path15, method, body, options) {
5476
+ const session = options.github;
5477
+ if (path15 === "/api/github/status" && method === "GET") {
5478
+ const client = session.current;
5479
+ return { status: 200, body: client ? { connected: true, owner: client.owner, repo: client.repo } : { connected: false } };
5480
+ }
5481
+ if (path15 === "/api/github/connect" && method === "POST") {
5482
+ const { token, owner, repo } = body ?? {};
5483
+ if (typeof token !== "string" || !token.trim() || token.length > 500) return fail(400, "Enter a token.");
5484
+ if (typeof owner !== "string" || !NAME.test(owner) || typeof repo !== "string" || !NAME.test(repo)) {
5485
+ return fail(400, "Enter the repository owner and name.");
5486
+ }
5487
+ return { status: 200, body: await session.connect(token.trim(), owner, repo) };
5488
+ }
5489
+ if (path15 === "/api/github/disconnect" && method === "POST") {
5490
+ session.disconnect();
5491
+ return { status: 200, body: { ok: true } };
5492
+ }
5493
+ const writeRoutes = ["/api/github/environment", "/api/github/variable", "/api/github/secret"];
5494
+ if (method === "POST" && writeRoutes.includes(path15)) return githubWrite(path15, body, session);
5495
+ const reads = ["/api/github/environments", "/api/github/repository"];
5496
+ const environment = path15.match(/^\/api\/github\/environments\/([^/]+)$/);
5497
+ if (method === "GET" && (reads.includes(path15) || environment)) {
5498
+ const client = session.current;
5499
+ if (!client) return fail(409, "Not connected to GitHub.");
5500
+ try {
5501
+ if (path15 === "/api/github/environments") return { status: 200, body: { names: await client.listEnvironments() } };
5502
+ if (path15 === "/api/github/repository") return { status: 200, body: await client.readRepository() };
5503
+ return { status: 200, body: await client.readEnvironment(decodeURIComponent(environment[1])) };
5504
+ } catch (error2) {
5505
+ return mapGitHubError(error2);
5506
+ }
5507
+ }
5508
+ return null;
5509
+ }
5510
+ async function filesRoute(name, action, method, body, options) {
5511
+ const wanted = action === "render" ? "POST" : "PUT";
5512
+ if (method !== wanted) return null;
5513
+ if (!options.files) return fail(501, "File rendering is not configured.");
5514
+ if (!SAFE_NAME.test(name)) return fail(400, "Invalid environment name.");
5515
+ const values = body?.values;
5516
+ if (!values || typeof values !== "object" || Array.isArray(values)) return fail(400, "Send the answers as { values }.");
5517
+ let rendered;
5518
+ try {
5519
+ const { bindings, templatesDir } = options.files;
5520
+ rendered = renderEnvironmentFiles({
5521
+ environment: name,
5522
+ values,
5523
+ bindings,
5524
+ readTemplate: (template) => (0, import_node_fs3.readFileSync)((0, import_node_path5.join)(templatesDir, template), "utf8")
5525
+ });
5526
+ } catch {
5527
+ return fail(500, "Could not render the files.");
5528
+ }
5529
+ const flat = options.files.bindings.flat;
5530
+ if (action === "render") {
5531
+ const existing = await readEnvironmentFiles(options.environmentsDir, name, flat) ?? {};
5532
+ const { layout, targets } = await fileTargets(options.environmentsDir, name, flat);
5533
+ return {
5534
+ status: 200,
5535
+ body: {
5536
+ layout,
5537
+ // `target` is where the file would be written, or null when the layout has no place for it.
5538
+ files: Object.entries(rendered).map(([path15, text2]) => ({
5539
+ path: path15,
5540
+ text: text2,
5541
+ existing: targets[path15] === null ? null : existing[path15] ?? null,
5542
+ target: targets[path15] ?? null
5543
+ }))
5544
+ }
5545
+ };
5546
+ }
5547
+ try {
5548
+ return { status: 200, body: { written: await writeEnvironmentFiles(options.environmentsDir, name, rendered, flat) } };
5549
+ } catch (error2) {
5550
+ return fail(409, error2 instanceof Error ? error2.message : "Could not write the files.");
5551
+ }
5552
+ }
5553
+ async function handleApiRequest(path15, options, request2 = {}) {
5554
+ const method = request2.method ?? "GET";
5555
+ const problem = crossSiteProblem(request2);
5556
+ if (problem) return fail(403, problem);
5557
+ if (path15.startsWith("/api/github/")) return githubRoute(path15, method, request2.body, options);
5558
+ if (path15 === "/api/ssh-keypair" && method === "POST") return { status: 200, body: generateSSHKeyPair2() };
5559
+ const fileRoute = path15.match(/^\/api\/environments\/([^/]+)\/(render|files)$/);
5560
+ if (fileRoute) return filesRoute(decodeURIComponent(fileRoute[1]), fileRoute[2], method, request2.body, options);
5561
+ if (method !== "GET") return null;
5562
+ if (path15 === "/api/context") {
5563
+ const remote = await (options.gitRemote ?? (() => readGitRemote(options.projectDir)))();
5564
+ return { status: 200, body: { repository: remote ? parseGitRemote(remote) : null } };
5565
+ }
5566
+ if (path15 === "/api/environments") {
5567
+ return { status: 200, body: await listEnvironmentNames(options.environmentsDir) };
5568
+ }
5569
+ const match = path15.match(/^\/api\/environments\/([^/]+)$/);
5570
+ if (match) {
5571
+ const files = await readEnvironmentFiles(options.environmentsDir, decodeURIComponent(match[1]));
5572
+ return files ? { status: 200, body: { files } } : fail(404, "Unknown environment");
5573
+ }
5574
+ return null;
5575
+ }
5576
+ async function readJson(request2) {
5577
+ const chunks = [];
5578
+ let size = 0;
5579
+ for await (const chunk of request2) {
5580
+ size += chunk.length;
5581
+ if (size > 3e5) throw new Error("too large");
5582
+ chunks.push(chunk);
5583
+ }
5584
+ return chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : void 0;
5585
+ }
5586
+ function middleware(options) {
5587
+ return async (request2, response, next) => {
5588
+ const path15 = new URL(request2.url ?? "/", "http://localhost").pathname;
5589
+ if (!path15.startsWith("/api/")) return next();
5590
+ let result;
5591
+ try {
5592
+ const method = request2.method ?? "GET";
5593
+ const json = (request2.headers["content-type"] ?? "").startsWith("application/json");
5594
+ const hasBody = method === "POST" || method === "PUT";
5595
+ if (hasBody && !json) {
5596
+ result = fail(415, "Send JSON.");
5597
+ } else {
5598
+ result = await handleApiRequest(path15, options, {
5599
+ method,
5600
+ body: hasBody ? await readJson(request2) : void 0,
5601
+ host: request2.headers.host,
5602
+ origin: request2.headers.origin
5603
+ }) ?? fail(404, "Unknown API path");
3717
5604
  }
5605
+ } catch {
5606
+ result = fail(400, "Bad request.");
5607
+ }
5608
+ response.statusCode = result.status;
5609
+ response.setHeader("Content-Type", "application/json");
5610
+ response.setHeader("Cache-Control", "no-store");
5611
+ response.end(JSON.stringify(result.body));
5612
+ };
5613
+ }
5614
+
5615
+ // src/configurator/server/start.ts
5616
+ var TYPES = {
5617
+ ".html": "text/html; charset=utf-8",
5618
+ ".js": "text/javascript; charset=utf-8",
5619
+ ".css": "text/css; charset=utf-8",
5620
+ ".svg": "image/svg+xml",
5621
+ ".png": "image/png",
5622
+ ".woff2": "font/woff2",
5623
+ ".json": "application/json"
5624
+ };
5625
+ async function serveStatic(staticDir, urlPath, response) {
5626
+ const relative = (0, import_node_path6.normalize)(decodeURIComponent(urlPath)).replace(/^([/\\])+/, "");
5627
+ let file = (0, import_node_path6.join)(staticDir, relative);
5628
+ if (!file.startsWith(staticDir)) file = (0, import_node_path6.join)(staticDir, "index.html");
5629
+ let body;
5630
+ try {
5631
+ body = await (0, import_promises4.readFile)(file);
5632
+ } catch {
5633
+ file = (0, import_node_path6.join)(staticDir, "index.html");
5634
+ body = await (0, import_promises4.readFile)(file);
5635
+ }
5636
+ response.setHeader("Content-Type", TYPES[(0, import_node_path6.extname)(file)] ?? "application/octet-stream");
5637
+ response.end(body);
5638
+ }
5639
+ function startServer(options) {
5640
+ const projectDir = (0, import_node_path6.resolve)(options.projectDir);
5641
+ const assetsDir = (0, import_node_path6.resolve)(options.assetsDir);
5642
+ const staticDir = (0, import_node_path6.join)(assetsDir, "ui");
5643
+ const api = middleware({
5644
+ environmentsDir: process.env.ENVIRONMENTS_DIR ?? (0, import_node_path6.join)(projectDir, "environments"),
5645
+ projectDir,
5646
+ github: new GitHubSession({ baseUrl: process.env.GITHUB_API_URL }),
5647
+ files: {
5648
+ bindings: (0, import_yaml.parse)((0, import_node_fs4.readFileSync)((0, import_node_path6.join)(assetsDir, "forms", "bindings.yml"), "utf8")),
5649
+ templatesDir: (0, import_node_path6.join)(assetsDir, "templates")
3718
5650
  }
5651
+ });
5652
+ const server = (0, import_node_http.createServer)((request2, response) => {
5653
+ api(request2, response, () => {
5654
+ const path15 = new URL(request2.url ?? "/", "http://localhost").pathname;
5655
+ serveStatic(staticDir, path15, response).catch(() => {
5656
+ response.statusCode = 500;
5657
+ response.end("The page is not built. Build the toolkit first.");
5658
+ });
5659
+ }).catch(() => {
5660
+ response.statusCode = 500;
5661
+ response.end();
5662
+ });
5663
+ });
5664
+ return new Promise((resolveListening, reject) => {
5665
+ server.once("error", reject);
5666
+ server.listen(options.port ?? 4173, options.host ?? "127.0.0.1", () => resolveListening(server));
5667
+ });
5668
+ }
5669
+
5670
+ // src/configurator/workflows.ts
5671
+ var import_node_fs5 = require("node:fs");
5672
+ var import_node_path7 = require("node:path");
5673
+ var import_yaml2 = require("yaml");
5674
+ var INFRASTRUCTURE_WORKFLOWS = [
5675
+ "provision.yml",
5676
+ "reset-2fa.yml"
5677
+ ];
5678
+ var APPLICATION_WORKFLOWS = [
5679
+ "deploy-dependencies.yml",
5680
+ "deploy-opencrvs.yml",
5681
+ "clear-all-data.yml",
5682
+ "seed-data.yml",
5683
+ "reindex.yml",
5684
+ "github-to-k8s-sync-env.yml"
5685
+ ];
5686
+ var ENVIRONMENT_INPUT = [
5687
+ "on",
5688
+ "workflow_dispatch",
5689
+ "inputs",
5690
+ "environment"
5691
+ ];
5692
+ var WorkflowFormatError = class extends Error {
5693
+ };
5694
+ function listEnvironments(root) {
5695
+ const directory = (0, import_node_path7.join)(root, ENVIRONMENTS_DIR);
5696
+ const names = isDirectory2(directory) ? (0, import_node_fs5.readdirSync)(directory).filter((name) => isDirectory2((0, import_node_path7.join)(directory, name))).sort() : [];
5697
+ return {
5698
+ infrastructure: names.filter(
5699
+ (name) => (0, import_node_fs5.existsSync)((0, import_node_path7.join)(directory, name, INVENTORY_FILE_NAME2))
5700
+ ),
5701
+ application: names.filter(
5702
+ (name) => isDirectory2((0, import_node_path7.join)(directory, name, "opencrvs-services"))
5703
+ )
5704
+ };
5705
+ }
5706
+ function updateEnvironmentOptions(content, environments) {
5707
+ const document = (0, import_yaml2.parseDocument)(content);
5708
+ if (document.errors.length > 0) {
5709
+ throw new WorkflowFormatError(
5710
+ `Invalid YAML: ${document.errors[0].message}`
5711
+ );
5712
+ }
5713
+ const options = document.getIn([...ENVIRONMENT_INPUT, "options"], true);
5714
+ if (!(0, import_yaml2.isSeq)(options)) {
5715
+ throw new WorkflowFormatError(
5716
+ "Expected a list at on.workflow_dispatch.inputs.environment.options"
5717
+ );
5718
+ }
5719
+ if (options.flow || !options.range) {
5720
+ throw new WorkflowFormatError(
5721
+ 'on.workflow_dispatch.inputs.environment.options has to be a block list, one "- name" per line'
5722
+ );
5723
+ }
5724
+ const warnings = [];
5725
+ const fallback = document.getIn([...ENVIRONMENT_INPUT, "default"]);
5726
+ if (typeof fallback === "string" && !environments.includes(fallback)) {
5727
+ warnings.push(
5728
+ `the default environment "${fallback}" is not one of the options`
5729
+ );
5730
+ }
5731
+ const current = options.items.map(
5732
+ (item) => String((0, import_yaml2.isScalar)(item) ? item.value : item)
3719
5733
  );
3720
- if (missingDirectories.length > 0) {
3721
- throw new Error(
3722
- `The current directory is not a valid OpenCRVS country configuration repository. Missing required director${missingDirectories.length === 1 ? "y" : "ies"}: ${missingDirectories.join(", ")}`
5734
+ const target = [
5735
+ ...current.filter(
5736
+ (name, i) => environments.includes(name) && current.indexOf(name) === i
5737
+ ),
5738
+ ...environments.filter((name) => !current.includes(name))
5739
+ ];
5740
+ if (target.length === current.length && target.every((name, i) => name === current[i])) {
5741
+ return { content, warnings };
5742
+ }
5743
+ const [start, end] = options.range;
5744
+ const indentation = content.slice(
5745
+ content.lastIndexOf("\n", start - 1) + 1,
5746
+ start
5747
+ );
5748
+ if (indentation.trim() !== "") {
5749
+ throw new WorkflowFormatError(
5750
+ "on.workflow_dispatch.inputs.environment.options is not on its own lines"
3723
5751
  );
3724
5752
  }
5753
+ const eol = content.includes("\r\n") ? "\r\n" : "\n";
5754
+ const endsWithLineBreak = content.slice(start, end).endsWith("\n");
5755
+ const items = target.map((name) => `- ${(0, import_yaml2.stringify)(name, { lineWidth: 0 }).trimEnd()}`).join(eol + indentation);
5756
+ return {
5757
+ content: content.slice(0, start) + items + (endsWithLineBreak ? eol : "") + content.slice(end),
5758
+ warnings
5759
+ };
3725
5760
  }
3726
- async function runEnvironmentInit() {
3727
- validateRepositoryStructure();
3728
- assertNoOldInventoryLayout();
3729
- const { runSetupEnvironment: runSetupEnvironment2 } = await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
3730
- await runSetupEnvironment2();
5761
+ function planWorkflow(root, workflow, environments) {
5762
+ const file = (0, import_node_path7.join)(WORKFLOWS_DIR, workflow);
5763
+ const path15 = (0, import_node_path7.join)(root, file);
5764
+ const change = {
5765
+ file,
5766
+ environments,
5767
+ before: "",
5768
+ after: "",
5769
+ warnings: []
5770
+ };
5771
+ if (!(0, import_node_fs5.existsSync)(path15)) return { ...change, status: "not-found" };
5772
+ const before = (0, import_node_fs5.readFileSync)(path15, "utf8");
5773
+ if (environments.length === 0)
5774
+ return { ...change, status: "no-environments", before, after: before };
5775
+ try {
5776
+ const { content, warnings } = updateEnvironmentOptions(before, environments);
5777
+ return {
5778
+ ...change,
5779
+ status: content === before ? "unchanged" : "updated",
5780
+ before,
5781
+ after: content,
5782
+ warnings
5783
+ };
5784
+ } catch (error2) {
5785
+ if (error2 instanceof WorkflowFormatError) {
5786
+ throw new WorkflowFormatError(`${file}: ${error2.message}`);
5787
+ }
5788
+ throw error2;
5789
+ }
3731
5790
  }
3732
- async function runEnvironmentUpgrade() {
3733
- validateRepositoryStructure();
3734
- const { upgradeEnvironmentLayout: upgradeEnvironmentLayout2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
3735
- await upgradeEnvironmentLayout2();
5791
+ function planWorkflowUpdates(root) {
5792
+ const { infrastructure, application } = listEnvironments(root);
5793
+ return [
5794
+ ...INFRASTRUCTURE_WORKFLOWS.map(
5795
+ (workflow) => planWorkflow(root, workflow, infrastructure)
5796
+ ),
5797
+ ...APPLICATION_WORKFLOWS.map(
5798
+ (workflow) => planWorkflow(root, workflow, application)
5799
+ )
5800
+ ];
3736
5801
  }
3737
- async function runEnvironmentUpdateWorkflows() {
3738
- validateRepositoryStructure();
3739
- const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
3740
- await updateWorkflowEnvironments2();
5802
+ function applyWorkflowUpdates(root, changes) {
5803
+ const updated = changes.filter((change) => change.status === "updated");
5804
+ for (const change of updated) {
5805
+ (0, import_node_fs5.writeFileSync)((0, import_node_path7.join)(root, change.file), change.after, "utf8");
5806
+ }
5807
+ return updated.map((change) => change.file);
3741
5808
  }
3742
- async function runEnvironmentUsers() {
3743
- validateRepositoryStructure();
3744
- const { manageEnvironmentUsers: manageEnvironmentUsers2 } = await Promise.resolve().then(() => (init_users(), users_exports));
3745
- await manageEnvironmentUsers2();
5809
+
5810
+ // src/configurator/index.ts
5811
+ var processContext = () => ({
5812
+ root: process.cwd(),
5813
+ log: console.log
5814
+ });
5815
+ var defaultAssetsDir = () => (0, import_node_path8.join)(__dirname, "configurator-assets");
5816
+ function startConfigurator(context, { port = 4173, host, assetsDir = defaultAssetsDir() } = {}) {
5817
+ return startServer({ projectDir: context.root, assetsDir, port, host });
3746
5818
  }
3747
- async function runEnvironmentSwarmToK8s() {
3748
- validateRepositoryStructure();
3749
- await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
5819
+ async function runConfiguratorInit(args2 = [], context = processContext()) {
5820
+ const { values } = (0, import_node_util.parseArgs)({
5821
+ args: args2,
5822
+ options: { port: { type: "string" }, host: { type: "string" } }
5823
+ });
5824
+ const port = values.port === void 0 ? 4173 : Number(values.port);
5825
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
5826
+ throw new Error(`Invalid port: ${values.port}`);
5827
+ }
5828
+ assertInfrastructureRepository(context.root);
5829
+ assertNoOldInventoryLayout2(context.root);
5830
+ const assetsDir = defaultAssetsDir();
5831
+ if (!(0, import_node_fs6.existsSync)((0, import_node_path8.join)(assetsDir, "ui", "index.html"))) {
5832
+ throw new Error(
5833
+ "The configurator page is not built. Build the toolkit first (pnpm build in packages/toolkit)."
5834
+ );
5835
+ }
5836
+ const server = await startConfigurator(context, {
5837
+ port,
5838
+ host: values.host,
5839
+ assetsDir
5840
+ });
5841
+ const { port: listening } = server.address();
5842
+ context.log(`OpenCRVS configurator: http://localhost:${listening}`);
5843
+ context.log(`Repository: ${context.root}`);
5844
+ context.log("Press Ctrl+C to stop.");
5845
+ await new Promise((resolve4) => {
5846
+ const stop = () => {
5847
+ server.close(() => resolve4());
5848
+ server.closeAllConnections();
5849
+ };
5850
+ process.once("SIGINT", stop);
5851
+ process.once("SIGTERM", stop);
5852
+ });
5853
+ }
5854
+ var describe = (change) => `${change.file} (${change.environments.join(", ")})`;
5855
+ function reportWorkflows(changes, context, dryRun) {
5856
+ for (const change of changes) {
5857
+ switch (change.status) {
5858
+ case "updated":
5859
+ context.log(
5860
+ ` ${dryRun ? "would update" : "\u2713 updated"} ${describe(change)}`
5861
+ );
5862
+ break;
5863
+ case "unchanged":
5864
+ context.log(` = ${change.file} is up to date`);
5865
+ break;
5866
+ case "not-found":
5867
+ context.log(
5868
+ ` \u21B7 skipped ${change.file} (not found in this repository)`
5869
+ );
5870
+ break;
5871
+ case "no-environments":
5872
+ context.log(` \u21B7 skipped ${change.file} (no environments to list)`);
5873
+ break;
5874
+ }
5875
+ for (const warning of change.warnings) {
5876
+ context.log(` \u26A0 ${change.file}: ${warning}`);
5877
+ }
5878
+ }
5879
+ }
5880
+ function updateWorkflows2(context, dryRun) {
5881
+ const { infrastructure, application } = listEnvironments(context.root);
5882
+ context.log(
5883
+ `Servers (inventory.yml): ${infrastructure.join(", ") || "none"}`
5884
+ );
5885
+ context.log(
5886
+ `Clusters (opencrvs-services): ${application.join(", ") || "none"}`
5887
+ );
5888
+ const changes = planWorkflowUpdates(context.root);
5889
+ context.log(`
5890
+ Workflows in ${WORKFLOWS_DIR}:`);
5891
+ if (!dryRun) applyWorkflowUpdates(context.root, changes);
5892
+ reportWorkflows(changes, context, dryRun);
5893
+ }
5894
+ async function runConfiguratorUpdateWorkflows(args2 = [], context = processContext()) {
5895
+ const { values } = (0, import_node_util.parseArgs)({
5896
+ args: args2,
5897
+ options: { "dry-run": { type: "boolean" } }
5898
+ });
5899
+ assertInfrastructureRepository(context.root);
5900
+ updateWorkflows2(context, values["dry-run"] ?? false);
5901
+ }
5902
+ async function runConfiguratorUpgrade(context = processContext()) {
5903
+ assertInfrastructureRepository(context.root);
5904
+ const migration = migrateLayout(context.root);
5905
+ if (migration.moved.length + migration.skipped.length === 0) {
5906
+ context.log(`No old inventory files found at ${OLD_INVENTORY_DIR2}`);
5907
+ } else {
5908
+ context.log("Migrating Ansible inventory files");
5909
+ for (const { from, to } of migration.moved) {
5910
+ context.log(` \u2713 moved ${from} -> ${to}`);
5911
+ }
5912
+ for (const { from, to } of migration.skipped) {
5913
+ context.log(` \u21B7 skipped ${from}: ${to} already exists`);
5914
+ }
5915
+ if (migration.oldDirectoryRemoved) {
5916
+ context.log(` \u2713 removed empty ${OLD_INVENTORY_DIR2}`);
5917
+ } else if ((0, import_node_fs6.existsSync)((0, import_node_path8.join)(context.root, OLD_INVENTORY_DIR2))) {
5918
+ context.log(
5919
+ ` \u26A0 ${OLD_INVENTORY_DIR2} still has files in it, review it manually`
5920
+ );
5921
+ }
5922
+ }
5923
+ context.log("");
5924
+ updateWorkflows2(context, false);
5925
+ context.log(
5926
+ migration.moved.length > 0 ? "\n\u2713 Environment layout upgraded. Commit the changes into git." : "\n\u2713 Environment layout already uses the current structure."
5927
+ );
3750
5928
  }
3751
5929
 
3752
5930
  // src/verify/endpoints.ts
3753
5931
  var import_colors = require("kleur/colors");
3754
5932
  var z = __toESM(require("zod/v4"));
3755
- var REQUEST_TIMEOUT_MS = 15e3;
5933
+ var REQUEST_TIMEOUT_MS2 = 15e3;
3756
5934
  var DEFAULT_TARGET_URL = "http://localhost:3040";
3757
5935
  var REQUIRED_PUBLIC_ENDPOINTS = [
3758
5936
  { method: "GET", path: "/client-config.js" },
@@ -3823,7 +6001,7 @@ async function requestStatus(url, method) {
3823
6001
  try {
3824
6002
  const response = await fetch(url, {
3825
6003
  method,
3826
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
6004
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2),
3827
6005
  // Sent without an Authorization header on purpose. A secured route
3828
6006
  // rejects with 401/403 before ever reading the body.
3829
6007
  headers: method === "POST" ? { "Content-Type": "application/json" } : void 0,
@@ -3834,40 +6012,30 @@ async function requestStatus(url, method) {
3834
6012
  return "error";
3835
6013
  }
3836
6014
  }
3837
- function toEventTriggerConfig(value) {
3838
- if (typeof value !== "object" || value === null) {
3839
- return null;
3840
- }
3841
- const record2 = value;
3842
- if (typeof record2.id !== "string") {
3843
- return null;
3844
- }
3845
- const actions = Array.isArray(record2.actions) ? Array.from(
3846
- new Set(
3847
- record2.actions.map((action) => {
3848
- if (typeof action !== "object" || action === null) {
3849
- return null;
3850
- }
3851
- const type = action.type;
3852
- return typeof type === "string" ? type : null;
3853
- }).filter((type) => type !== null)
3854
- )
3855
- ) : [];
3856
- return { id: record2.id, actions };
6015
+ var ServedEventConfigVersion = z.object({
6016
+ actions: z.array(z.object({ type: z.string() }))
6017
+ });
6018
+ var ServedEventConfig = z.union([
6019
+ z.object({ id: z.string(), versions: z.array(ServedEventConfigVersion) }),
6020
+ ServedEventConfigVersion.extend({ id: z.string() })
6021
+ ]);
6022
+ function toEventTriggerConfig(config) {
6023
+ const versions = "versions" in config ? config.versions : [config];
6024
+ const actions = versions.flatMap(
6025
+ (version) => version.actions.map(({ type }) => type)
6026
+ );
6027
+ return { id: config.id, actions: Array.from(new Set(actions)) };
3857
6028
  }
3858
6029
  async function fetchEventConfigs(baseUrl) {
3859
6030
  try {
3860
6031
  const response = await fetch(`${baseUrl}/config/events`, {
3861
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
6032
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
3862
6033
  });
3863
6034
  if (!response.ok) {
3864
6035
  return null;
3865
6036
  }
3866
- const body = await response.json();
3867
- if (!Array.isArray(body)) {
3868
- return null;
3869
- }
3870
- return body.map(toEventTriggerConfig).filter((config) => config !== null);
6037
+ const parsed = z.array(ServedEventConfig).safeParse(await response.json());
6038
+ return parsed.success ? parsed.data.map(toEventTriggerConfig) : null;
3871
6039
  } catch {
3872
6040
  return null;
3873
6041
  }
@@ -3922,7 +6090,7 @@ var ServedTranslations = z.object({
3922
6090
  async function fetchServedTranslations(baseUrl, application) {
3923
6091
  try {
3924
6092
  const response = await fetch(`${baseUrl}/content/${application}`, {
3925
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
6093
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
3926
6094
  });
3927
6095
  if (!response.ok) {
3928
6096
  return null;
@@ -3938,10 +6106,10 @@ async function verifyTranslations(baseUrl) {
3938
6106
  let refs;
3939
6107
  try {
3940
6108
  refs = await candidateRefs(TEMPLATE_VERSION);
3941
- } catch (error3) {
6109
+ } catch (error2) {
3942
6110
  console.log(
3943
6111
  " " + (0, import_colors.yellow)(
3944
- `Could not list the ${TEMPLATE_VERSION} refs on GitHub (${error3.message}); translations not checked.`
6112
+ `Could not list the ${TEMPLATE_VERSION} refs on GitHub (${error2.message}); translations not checked.`
3945
6113
  )
3946
6114
  );
3947
6115
  return 0;
@@ -3952,10 +6120,10 @@ async function verifyTranslations(baseUrl) {
3952
6120
  let fetched;
3953
6121
  try {
3954
6122
  fetched = await fetchTemplate(refs, application);
3955
- } catch (error3) {
6123
+ } catch (error2) {
3956
6124
  console.log(
3957
6125
  " " + (0, import_colors.yellow)(
3958
- `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${endpoint} not checked.`
6126
+ `Could not read ${application}.csv from the country config template on GitHub (${error2.message}); ${endpoint} not checked.`
3959
6127
  )
3960
6128
  );
3961
6129
  continue;
@@ -4038,8 +6206,8 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4038
6206
  console.log(line(ok, endpointLabel(check), detail));
4039
6207
  }
4040
6208
  {
4041
- const path7 = `/fonts/${PROBE_SEGMENT}.ttf`;
4042
- const status = await requestStatus(`${baseUrl}${path7}`, "GET");
6209
+ const path15 = `/fonts/${PROBE_SEGMENT}.ttf`;
6210
+ const status = await requestStatus(`${baseUrl}${path15}`, "GET");
4043
6211
  const ok = status === 200 || status === 404;
4044
6212
  if (!ok) {
4045
6213
  failures++;
@@ -4054,7 +6222,7 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4054
6222
  } else {
4055
6223
  detail = `${describeStatus(status)} \u2014 unexpected`;
4056
6224
  }
4057
- console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path7}`)}`, detail));
6225
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path15}`)}`, detail));
4058
6226
  }
4059
6227
  console.log();
4060
6228
  console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
@@ -4107,13 +6275,13 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4107
6275
  line(true, pattern, `${actions.length} action(s) \u2014 all require auth`)
4108
6276
  );
4109
6277
  } else {
4110
- for (const failure of failed) {
6278
+ for (const failure2 of failed) {
4111
6279
  failures++;
4112
6280
  console.log(
4113
6281
  line(
4114
6282
  false,
4115
- `POST /trigger/events/${event.id}/actions/${failure.action}`,
4116
- securedDetail(failure.status)
6283
+ `POST /trigger/events/${event.id}/actions/${failure2.action}`,
6284
+ securedDetail(failure2.status)
4117
6285
  )
4118
6286
  );
4119
6287
  }
@@ -4146,6 +6314,7 @@ Usage: opencrvs <command>
4146
6314
 
4147
6315
  Commands:
4148
6316
  environment Manage deployment environments
6317
+ configurator Manage deployment environments in the browser
4149
6318
  upgrade Upgrade an existing environment
4150
6319
  verify-endpoints Verify the locally-running country config exposes the
4151
6320
  expected endpoints, keeps secured ones locked down and
@@ -4181,13 +6350,20 @@ Exits with a non-zero status if any check fails.
4181
6350
  var UPGRADE_USAGE = `
4182
6351
  Usage: opencrvs upgrade [options]
4183
6352
 
4184
- Upgrade the country config in the current working directory to the next
4185
- major version of OpenCRVS.
6353
+ Upgrade the country config in the current working directory to this toolkit's
6354
+ version of OpenCRVS. Upgrade one minor version at a time: toolkit 2.2 upgrades
6355
+ a country config on 2.1.
6356
+
6357
+ The upgrade tells which version the country config is on by its
6358
+ @opencrvs/toolkit dependency, and updates that dependency itself once done.
6359
+ Run it without changing the dependency first, e.g.
6360
+
6361
+ npx @opencrvs/toolkit@2.2 upgrade
4186
6362
 
4187
6363
  Options:
4188
6364
  -h, --help Show this message.
4189
6365
  `.trim();
4190
- function main3() {
6366
+ function main8() {
4191
6367
  const command = args[0];
4192
6368
  if (!command || command === "--help" || command === "-h") {
4193
6369
  console.log(USAGE);
@@ -4196,6 +6372,8 @@ function main3() {
4196
6372
  switch (command) {
4197
6373
  case "environment":
4198
6374
  return handleEnvironment();
6375
+ case "configurator":
6376
+ return handleConfigurator();
4199
6377
  case "upgrade":
4200
6378
  return handleUpgrade();
4201
6379
  case "verify-endpoints":
@@ -4249,14 +6427,77 @@ Subcommands:
4249
6427
  async function runEnvironmentCommand(operation, command) {
4250
6428
  try {
4251
6429
  await command();
4252
- } catch (error3) {
6430
+ } catch (error2) {
4253
6431
  console.error(
4254
6432
  `Environment ${operation} failed:`,
4255
- error3 instanceof Error ? error3.message : error3
6433
+ error2 instanceof Error ? error2.message : error2
4256
6434
  );
4257
6435
  process.exit(1);
4258
6436
  }
4259
6437
  }
6438
+ async function handleConfigurator() {
6439
+ const subcommand = args[1];
6440
+ const subcommandArgs = args.slice(2);
6441
+ if (!subcommand || subcommand === "--help" || subcommand === "-h") {
6442
+ console.log(
6443
+ `
6444
+ Usage: opencrvs configurator <subcommand>
6445
+
6446
+ Run it from the root of an OpenCRVS infrastructure repository.
6447
+
6448
+ Subcommands:
6449
+ init [--port <port>] [--host <host>]
6450
+ Create or update environments in the browser. Serves the
6451
+ configurator on http://localhost:4173 until stopped.
6452
+ In a container pass --host 0.0.0.0 and publish the port on
6453
+ the host's loopback only.
6454
+ upgrade Move the inventories of an old repository layout to
6455
+ environments/<name>/inventory.yml, then update the workflows
6456
+ update-workflows [--dry-run]
6457
+ Set the environments the GitHub workflows offer to the ones
6458
+ found in environments/
6459
+ `.trim()
6460
+ );
6461
+ process.exit(0);
6462
+ }
6463
+ const runConfiguratorCommand = async (operation, command) => {
6464
+ try {
6465
+ await command();
6466
+ } catch (error2) {
6467
+ console.error(
6468
+ `Configurator ${operation} failed:`,
6469
+ error2 instanceof Error ? error2.message : error2
6470
+ );
6471
+ process.exit(1);
6472
+ }
6473
+ };
6474
+ switch (subcommand) {
6475
+ case "init":
6476
+ return runConfiguratorCommand(
6477
+ "initialisation",
6478
+ () => runConfiguratorInit(subcommandArgs)
6479
+ );
6480
+ case "upgrade":
6481
+ return runConfiguratorCommand(
6482
+ "environment upgrade",
6483
+ () => runConfiguratorUpgrade()
6484
+ );
6485
+ case "update-workflows":
6486
+ return runConfiguratorCommand(
6487
+ "workflow update",
6488
+ () => runConfiguratorUpdateWorkflows(subcommandArgs)
6489
+ );
6490
+ default:
6491
+ console.error(`Unknown subcommand: configurator ${subcommand}`);
6492
+ process.exit(1);
6493
+ }
6494
+ }
6495
+ function readToolkitVersion() {
6496
+ const packageJson = JSON.parse(
6497
+ import_fs9.default.readFileSync(import_path15.default.join(__dirname, "..", "package.json"), "utf-8")
6498
+ );
6499
+ return packageJson.version;
6500
+ }
4260
6501
  async function handleUpgrade() {
4261
6502
  const upgradeArgs = args.slice(1);
4262
6503
  if (upgradeArgs.includes("--help") || upgradeArgs.includes("-h")) {
@@ -4270,12 +6511,25 @@ async function handleUpgrade() {
4270
6511
  console.log(UPGRADE_USAGE);
4271
6512
  process.exit(1);
4272
6513
  }
6514
+ const toolkitVersion = readToolkitVersion();
6515
+ const upgradePath = checkUpgradePath(
6516
+ findCountryConfigToolkitVersion(process.cwd()),
6517
+ toolkitVersion
6518
+ );
6519
+ if (upgradePath.status === "unknown") {
6520
+ console.warn(`\u26A0\uFE0F ${upgradePath.message}
6521
+ `);
6522
+ }
6523
+ if (upgradePath.status === "blocked") {
6524
+ console.error(upgradePath.message);
6525
+ process.exit(1);
6526
+ }
4273
6527
  console.log("Initiating upgrade...");
4274
6528
  try {
4275
- await runUpgrade();
6529
+ await runUpgrade(toolkitVersion);
4276
6530
  console.log("Upgrade completed successfully!");
4277
- } catch (error3) {
4278
- console.error("Upgrade failed:", error3);
6531
+ } catch (error2) {
6532
+ console.error("Upgrade failed:", error2);
4279
6533
  process.exit(1);
4280
6534
  }
4281
6535
  }
@@ -4296,12 +6550,12 @@ async function handleVerifyEndpoints() {
4296
6550
  }
4297
6551
  try {
4298
6552
  await runVerifyEndpoints(positional[0]);
4299
- } catch (error3) {
6553
+ } catch (error2) {
4300
6554
  console.error(
4301
6555
  "Endpoint verification failed:",
4302
- error3 instanceof Error ? error3.message : error3
6556
+ error2 instanceof Error ? error2.message : error2
4303
6557
  );
4304
6558
  process.exit(1);
4305
6559
  }
4306
6560
  }
4307
- main3();
6561
+ main8();