@opencrvs/toolkit 2.2.0-rc.045257f → 2.2.0-rc.25c3c81

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 (156) hide show
  1. package/build.sh +15 -2
  2. package/dist/application-config/index.js +16 -5
  3. package/dist/authentication/index.d.ts +1 -1
  4. package/dist/authentication/index.js +4 -8
  5. package/dist/cli.js +2197 -544
  6. package/dist/commons/api/router.d.ts +17 -4
  7. package/dist/commons/application-config/index.d.ts +1 -1
  8. package/dist/commons/conditionals/conditionals.d.ts +4 -4
  9. package/dist/commons/conditionals/validate.d.ts +1 -1
  10. package/dist/commons/events/ActionStatus.d.ts +2 -2
  11. package/dist/commons/events/ActionType.d.ts +2 -0
  12. package/dist/commons/events/AdvancedSearchConfig.d.ts +3 -0
  13. package/dist/commons/events/Draft.d.ts +34 -1
  14. package/dist/commons/events/EventConfig.d.ts +446 -0
  15. package/dist/commons/events/EventDocument.d.ts +2 -0
  16. package/dist/commons/events/EventIndex.d.ts +1 -0
  17. package/dist/commons/events/EventInput.d.ts +1 -0
  18. package/dist/commons/events/EventMetadata.d.ts +1 -0
  19. package/dist/commons/events/FieldTypeMapping.d.ts +19 -19
  20. package/dist/commons/events/PlainDate.d.ts +5 -0
  21. package/dist/commons/events/defineConfig.d.ts +7 -2
  22. package/dist/commons/events/event.d.ts +4 -1
  23. package/dist/commons/events/field.d.ts +5 -0
  24. package/dist/commons/events/locations.d.ts +1 -1
  25. package/dist/commons/events/scopes.d.ts +2 -1
  26. package/dist/commons/events/state/index.d.ts +1 -0
  27. package/dist/commons/events/test.utils.d.ts +59 -6
  28. package/dist/commons/events/utils.d.ts +28 -2
  29. package/dist/commons/users/Role.d.ts +23 -0
  30. package/dist/commons/users/User.d.ts +263 -0
  31. package/dist/commons/users/authentication.d.ts +67 -0
  32. package/dist/commons/users/index.d.ts +5 -0
  33. package/dist/commons/users/roleValidations.d.ts +15 -0
  34. package/dist/commons/users/scopes.d.ts +1402 -0
  35. package/dist/commons/users/userReferences.d.ts +176 -0
  36. package/dist/conditionals/index.js +3 -3
  37. package/dist/configurator/index.d.ts +24 -0
  38. package/dist/configurator/index.d.ts.map +1 -0
  39. package/dist/configurator/index.js +161 -0
  40. package/dist/configurator/layout.d.ts +28 -0
  41. package/dist/configurator/layout.d.ts.map +1 -0
  42. package/dist/configurator/layout.js +78 -0
  43. package/dist/configurator/paths.d.ts +13 -0
  44. package/dist/configurator/paths.d.ts.map +1 -0
  45. package/dist/configurator/paths.js +48 -0
  46. package/dist/configurator/server/environments.d.ts +20 -0
  47. package/dist/configurator/server/environments.d.ts.map +1 -0
  48. package/dist/configurator/server/environments.js +143 -0
  49. package/dist/configurator/server/files.d.ts +11 -0
  50. package/dist/configurator/server/files.d.ts.map +1 -0
  51. package/dist/configurator/server/files.js +67 -0
  52. package/dist/configurator/server/github.d.ts +56 -0
  53. package/dist/configurator/server/github.d.ts.map +1 -0
  54. package/dist/configurator/server/github.js +239 -0
  55. package/dist/configurator/server/plugin.d.ts +39 -0
  56. package/dist/configurator/server/plugin.d.ts.map +1 -0
  57. package/dist/configurator/server/plugin.js +298 -0
  58. package/dist/configurator/server/seal.d.ts +2 -0
  59. package/dist/configurator/server/seal.d.ts.map +1 -0
  60. package/dist/configurator/server/seal.js +36 -0
  61. package/dist/configurator/server/sshKeys.d.ts +5 -0
  62. package/dist/configurator/server/sshKeys.d.ts.map +1 -0
  63. package/dist/configurator/server/sshKeys.js +28 -0
  64. package/dist/configurator/server/start.d.ts +12 -0
  65. package/dist/configurator/server/start.d.ts.map +1 -0
  66. package/dist/configurator/server/start.js +91 -0
  67. package/dist/configurator/testing.d.ts +11 -0
  68. package/dist/configurator/testing.d.ts.map +1 -0
  69. package/dist/configurator/testing.js +74 -0
  70. package/dist/configurator/ui/bindings/bindings.d.ts +35 -0
  71. package/dist/configurator/ui/bindings/bindings.d.ts.map +1 -0
  72. package/dist/configurator/ui/bindings/bindings.js +5 -0
  73. package/dist/configurator/ui/bindings/parsers.d.ts +7 -0
  74. package/dist/configurator/ui/bindings/parsers.d.ts.map +1 -0
  75. package/dist/configurator/ui/bindings/parsers.js +85 -0
  76. package/dist/configurator/ui/form/users.d.ts +11 -0
  77. package/dist/configurator/ui/form/users.d.ts.map +1 -0
  78. package/dist/configurator/ui/form/users.js +33 -0
  79. package/dist/configurator/ui/plan/dependencyHosts.d.ts +2 -0
  80. package/dist/configurator/ui/plan/dependencyHosts.d.ts.map +1 -0
  81. package/dist/configurator/ui/plan/dependencyHosts.js +36 -0
  82. package/dist/configurator/ui/plan/templateValues.d.ts +11 -0
  83. package/dist/configurator/ui/plan/templateValues.d.ts.map +1 -0
  84. package/dist/configurator/ui/plan/templateValues.js +70 -0
  85. package/dist/configurator/workflows.d.ts +53 -0
  86. package/dist/configurator/workflows.d.ts.map +1 -0
  87. package/dist/configurator/workflows.js +161 -0
  88. package/dist/configurator-assets/forms/bindings.yml +263 -0
  89. package/dist/configurator-assets/templates/README.md +18 -0
  90. package/dist/configurator-assets/templates/charts-values/dependencies/values.override.yaml +4 -0
  91. package/dist/configurator-assets/templates/charts-values/dependencies/values.yaml +99 -0
  92. package/dist/configurator-assets/templates/charts-values/opencrvs-services/values.override.yaml +4 -0
  93. package/dist/configurator-assets/templates/charts-values/opencrvs-services/values.yaml +83 -0
  94. package/dist/configurator-assets/templates/charts-values/opentelemetry/values.yaml +102 -0
  95. package/dist/configurator-assets/templates/charts-values/traefik/values.override.yaml +4 -0
  96. package/dist/configurator-assets/templates/charts-values/traefik/values.yaml +130 -0
  97. package/dist/configurator-assets/templates/inventory/inventory.template.yml +98 -0
  98. package/dist/configurator-assets/ui/apple-touch-icon.png +0 -0
  99. package/dist/configurator-assets/ui/assets/index-Bf3eC7uO.js +169 -0
  100. package/dist/configurator-assets/ui/assets/index-CaqYFJUk.css +6 -0
  101. package/dist/configurator-assets/ui/assets/opencrvs-logo-sIjz08HT.svg +1 -0
  102. package/dist/configurator-assets/ui/assets/poppins-400-BwTUGeWf.woff2 +0 -0
  103. package/dist/configurator-assets/ui/assets/poppins-500-CWICHMj6.woff2 +0 -0
  104. package/dist/configurator-assets/ui/assets/poppins-600-DJVo7c07.woff2 +0 -0
  105. package/dist/configurator-assets/ui/assets/poppins-700-g9MkRaG0.woff2 +0 -0
  106. package/dist/configurator-assets/ui/favicon-32x32.png +0 -0
  107. package/dist/configurator-assets/ui/index.html +25 -0
  108. package/dist/environment/custom-types.d.ts +1 -0
  109. package/dist/environment/custom-types.d.ts.map +1 -1
  110. package/dist/environment/derived-variables.d.ts +8 -0
  111. package/dist/environment/derived-variables.d.ts.map +1 -1
  112. package/dist/environment/derived-variables.js +9 -0
  113. package/dist/environment/questions.d.ts +42 -9
  114. package/dist/environment/questions.d.ts.map +1 -1
  115. package/dist/environment/questions.js +70 -47
  116. package/dist/environment/registry.d.ts +15 -0
  117. package/dist/environment/registry.d.ts.map +1 -0
  118. package/dist/environment/registry.js +112 -0
  119. package/dist/environment/setup-environment.d.ts.map +1 -1
  120. package/dist/environment/setup-environment.js +104 -23
  121. package/dist/events/index.js +635 -149
  122. package/dist/migrations/add-notify-config.d.ts +40 -0
  123. package/dist/migrations/add-notify-config.d.ts.map +1 -0
  124. package/dist/migrations/add-notify-config.js +249 -0
  125. package/dist/migrations/index.d.ts.map +1 -1
  126. package/dist/migrations/index.js +602 -143
  127. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -1
  128. package/dist/migrations/move-declaration-to-declare-action.js +27 -144
  129. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -1
  130. package/dist/migrations/read-declaration-through-helper.js +3 -61
  131. package/dist/migrations/resolve-versioned-event-config.d.ts +56 -0
  132. package/dist/migrations/resolve-versioned-event-config.d.ts.map +1 -0
  133. package/dist/migrations/resolve-versioned-event-config.js +353 -0
  134. package/dist/migrations/utils.d.ts +61 -0
  135. package/dist/migrations/utils.d.ts.map +1 -0
  136. package/dist/migrations/utils.js +218 -0
  137. package/dist/notification/index.js +616 -66
  138. package/dist/roles/index.d.ts +2 -0
  139. package/dist/roles/index.d.ts.map +1 -0
  140. package/dist/roles/index.js +730 -0
  141. package/dist/scopes/index.d.ts +0 -10
  142. package/dist/scopes/index.js +3 -7
  143. package/dist/templates/charts-values/dependencies/values.yaml +4 -1
  144. package/dist/templates/charts-values/opencrvs-services/values.yaml +2 -2
  145. package/dist/verify/endpoints.d.ts +11 -0
  146. package/dist/verify/endpoints.d.ts.map +1 -1
  147. package/dist/verify/endpoints.js +21 -27
  148. package/opencrvs-toolkit-2.2.0-rc.25c3c81.tgz +0 -0
  149. package/package.json +16 -3
  150. package/tsconfig.build.json +11 -1
  151. package/tsconfig.build.tsbuildinfo +1 -1
  152. package/tsconfig.json +15 -6
  153. package/dist/environment/dockerhub.d.ts +0 -15
  154. package/dist/environment/dockerhub.d.ts.map +0 -1
  155. package/dist/environment/dockerhub.js +0 -104
  156. package/opencrvs-toolkit-2.2.0-rc.045257f.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_path7.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_path7.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_path7.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_path7, 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_path7 = require("path");
58
+ import_path10 = require("path");
59
59
  glob = __toESM(require("glob"));
60
- OLD_INVENTORY_DIR = (0, import_path7.join)(
60
+ OLD_INVENTORY_DIR = (0, import_path10.join)(
61
61
  "infrastructure",
62
62
  "server-setup",
63
63
  "inventory"
@@ -405,6 +405,7 @@ var init_derived_variables = __esm({
405
405
  {
406
406
  name: "S3_ADMIN_ACCESS_KEY",
407
407
  valueLabel: "S3_ADMIN_ACCESS_KEY",
408
+ legacyValueLabel: "MINIO_ROOT_USER",
408
409
  valueType: "SECRET",
409
410
  type: "disabled",
410
411
  scope: "ENVIRONMENT"
@@ -412,6 +413,7 @@ var init_derived_variables = __esm({
412
413
  {
413
414
  name: "S3_ADMIN_SECRET_KEY",
414
415
  valueLabel: "S3_ADMIN_SECRET_KEY",
416
+ legacyValueLabel: "MINIO_ROOT_PASSWORD",
415
417
  valueType: "SECRET",
416
418
  type: "disabled",
417
419
  scope: "ENVIRONMENT"
@@ -513,6 +515,13 @@ var init_derived_variables = __esm({
513
515
  valueType: "VARIABLE",
514
516
  type: "disabled",
515
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"
516
525
  }
517
526
  ];
518
527
  }
@@ -603,8 +612,8 @@ function extractWorkerNodes(data) {
603
612
  return worker_hosts;
604
613
  }
605
614
  function copyChartsValues(env, values) {
606
- const srcDir = import_path8.default.resolve(__dirname, "templates", "charts-values");
607
- const destDir = import_path8.default.resolve(process.cwd(), "environments", env);
615
+ const srcDir = import_path11.default.resolve(__dirname, "templates", "charts-values");
616
+ const destDir = import_path11.default.resolve(process.cwd(), "environments", env);
608
617
  import_fs5.default.mkdirSync(destDir, { recursive: true });
609
618
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
610
619
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
@@ -614,7 +623,7 @@ function copyChartsValues(env, values) {
614
623
  if (stat.isDirectory()) {
615
624
  import_fs5.default.mkdirSync(dest, { recursive: true });
616
625
  for (const item of import_fs5.default.readdirSync(src)) {
617
- copyRecursive(import_path8.default.join(src, item), import_path8.default.join(dest, item));
626
+ copyRecursive(import_path11.default.join(src, item), import_path11.default.join(dest, item));
618
627
  }
619
628
  } else {
620
629
  const content = import_fs5.default.readFileSync(src, "utf8");
@@ -636,13 +645,13 @@ function copyChartsValues(env, values) {
636
645
  `);
637
646
  }
638
647
  function generateInventory(env, values) {
639
- const templatePath = import_path8.default.join(
648
+ const templatePath = import_path11.default.join(
640
649
  __dirname,
641
650
  "templates",
642
651
  "inventory",
643
652
  "inventory.template.yml"
644
653
  );
645
- const outputPath = import_path8.default.resolve(
654
+ const outputPath = import_path11.default.resolve(
646
655
  process.cwd(),
647
656
  getEnvironmentInventoryPath(env)
648
657
  );
@@ -650,18 +659,18 @@ function generateInventory(env, values) {
650
659
  const template = import_handlebars.default.compile(templateFile);
651
660
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
652
661
  const updated = template(values);
653
- import_fs5.default.mkdirSync(import_path8.default.dirname(outputPath), { recursive: true });
662
+ import_fs5.default.mkdirSync(import_path11.default.dirname(outputPath), { recursive: true });
654
663
  import_fs5.default.writeFileSync(outputPath, updated);
655
664
  log(`
656
665
  \u2705 Generated inventory file at ${outputPath}
657
666
  `);
658
667
  }
659
- var import_fs5, import_path8, import_handlebars;
668
+ var import_fs5, import_path11, import_handlebars;
660
669
  var init_templates = __esm({
661
670
  "src/environment/templates.ts"() {
662
671
  "use strict";
663
672
  import_fs5 = __toESM(require("fs"));
664
- import_path8 = __toESM(require("path"));
673
+ import_path11 = __toESM(require("path"));
665
674
  init_logger();
666
675
  init_paths();
667
676
  import_handlebars = __toESM(require("handlebars"));
@@ -692,16 +701,16 @@ var update_workflows_exports = {};
692
701
  __export(update_workflows_exports, {
693
702
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
694
703
  });
695
- function isDirectory(path12) {
704
+ function isDirectory(path15) {
696
705
  try {
697
- return (0, import_fs6.statSync)(path12).isDirectory();
706
+ return (0, import_fs6.statSync)(path15).isDirectory();
698
707
  } catch {
699
708
  return false;
700
709
  }
701
710
  }
702
711
  async function extractInfrastructureNames() {
703
- const files = glob2.sync((0, import_path9.join)("environments", "*", INVENTORY_FILE_NAME));
704
- const infraEnvironments = files.map((file) => (0, import_path9.basename)((0, import_path9.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)));
705
714
  if (infraEnvironments.length === 0) {
706
715
  console.log(
707
716
  `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
@@ -714,8 +723,8 @@ async function extractInfrastructureNames() {
714
723
  async function extractEnvironmentNames() {
715
724
  const entries = await (0, import_promises.readdir)("environments");
716
725
  const environments = entries.filter((entry) => {
717
- const environmentPath = (0, import_path9.join)("environments", entry);
718
- const opencrvsServicesPath = (0, import_path9.join)(environmentPath, "opencrvs-services");
726
+ const environmentPath = (0, import_path12.join)("environments", entry);
727
+ const opencrvsServicesPath = (0, import_path12.join)(environmentPath, "opencrvs-services");
719
728
  return isDirectory(environmentPath) && (0, import_fs6.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
720
729
  });
721
730
  if (environments.length === 0) {
@@ -808,13 +817,13 @@ async function updateWorkflowEnvironments() {
808
817
  process.exit(1);
809
818
  }
810
819
  }
811
- var import_promises, import_fs6, import_path9, glob2, yaml2;
820
+ var import_promises, import_fs6, import_path12, glob2, yaml2;
812
821
  var init_update_workflows = __esm({
813
822
  "src/environment/update-workflows.ts"() {
814
823
  "use strict";
815
824
  import_promises = require("fs/promises");
816
825
  import_fs6 = require("fs");
817
- import_path9 = require("path");
826
+ import_path12 = require("path");
818
827
  glob2 = __toESM(require("glob"));
819
828
  yaml2 = __toESM(require("js-yaml"));
820
829
  init_logger();
@@ -872,7 +881,10 @@ function validateCIDRs(input4) {
872
881
  }
873
882
  return true;
874
883
  }
875
- 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;
876
888
  var init_questions = __esm({
877
889
  "src/environment/questions.ts"() {
878
890
  "use strict";
@@ -880,45 +892,59 @@ var init_questions = __esm({
880
892
  init_utils();
881
893
  init_git();
882
894
  notEmpty = (value) => value.toString().trim().length > 0 ? true : "Please enter a value";
883
- 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
+ },
884
906
  {
885
- name: "dockerhubOrganisation",
907
+ name: "registryOrganisation",
886
908
  type: "text",
887
- 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?",
888
910
  valueType: "SECRET",
889
- valueLabel: "DOCKERHUB_ACCOUNT",
911
+ valueLabel: "REGISTRY_ORGANISATION",
912
+ legacyValueLabel: "DOCKERHUB_ACCOUNT",
890
913
  validate: notEmpty,
891
- initial: process.env.DOCKER_ORGANISATION,
914
+ initial: process.env.REGISTRY_ORGANISATION,
892
915
  scope: "REPOSITORY"
893
916
  },
894
917
  {
895
- name: "dockerhubRepository",
918
+ name: "registryRepository",
896
919
  type: "text",
897
- message: "What is the name of your private Docker Hub repository?",
920
+ message: "What is the name of your private container repository?",
898
921
  valueType: "SECRET",
899
- valueLabel: "DOCKERHUB_REPO",
922
+ valueLabel: "REGISTRY_REPOSITORY",
923
+ legacyValueLabel: "DOCKERHUB_REPO",
900
924
  validate: notEmpty,
901
- initial: process.env.DOCKER_REPO,
925
+ initial: process.env.REGISTRY_REPOSITORY,
902
926
  scope: "REPOSITORY"
903
927
  },
904
928
  {
905
- name: "dockerhubUsername",
929
+ name: "registryUsername",
906
930
  type: "text",
907
- 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?",
908
932
  valueType: "SECRET",
909
- valueLabel: "DOCKER_USERNAME",
933
+ valueLabel: "REGISTRY_USERNAME",
934
+ legacyValueLabel: "DOCKER_USERNAME",
910
935
  validate: notEmpty,
911
- initial: process.env.DOCKER_USERNAME,
936
+ initial: process.env.REGISTRY_USERNAME,
912
937
  scope: "REPOSITORY"
913
938
  },
914
939
  {
915
- name: "dockerhubToken",
940
+ name: "registryToken",
916
941
  type: "text",
917
- message: "What is the token of this Docker Hub account?",
942
+ message: "What is the token of this container registry account?",
918
943
  valueType: "SECRET",
919
- valueLabel: "DOCKER_TOKEN",
944
+ valueLabel: "REGISTRY_TOKEN",
945
+ legacyValueLabel: "DOCKER_TOKEN",
920
946
  validate: notEmpty,
921
- initial: process.env.DOCKER_TOKEN,
947
+ initial: process.env.REGISTRY_TOKEN,
922
948
  scope: "REPOSITORY"
923
949
  }
924
950
  ];
@@ -940,36 +966,38 @@ var init_questions = __esm({
940
966
  scope: "REPOSITORY"
941
967
  }
942
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
+ };
943
998
  githubOtherQuestions = [
944
- {
945
- name: "githubApprovers",
946
- type: "text",
947
- message: "Please provide/update list of production approvers?",
948
- initial: process.env.GH_APPROVERS,
949
- valueType: "VARIABLE",
950
- valueLabel: "GH_APPROVERS",
951
- scope: "REPOSITORY"
952
- },
953
- {
954
- name: "approvalRequired",
955
- type: "select",
956
- message: "Would you like to enable approvals process for GitHub action workflows?",
957
- choices: [
958
- {
959
- title: "True",
960
- value: "true"
961
- },
962
- {
963
- title: "False",
964
- value: "false"
965
- }
966
- ],
967
- valueType: "VARIABLE",
968
- validate: notEmpty,
969
- valueLabel: "APPROVAL_REQUIRED",
970
- initial: process.env.APPROVAL_REQUIRED,
971
- scope: "ENVIRONMENT"
972
- }
999
+ githubApprovalRequiredQuestion,
1000
+ githubApproversQuestion
973
1001
  ];
974
1002
  githubTokenQuestion = [
975
1003
  {
@@ -1377,69 +1405,71 @@ var init_questions_helper = __esm({
1377
1405
  }
1378
1406
  });
1379
1407
 
1380
- // src/environment/dockerhub.ts
1381
- async function validateDockerHubCredentials(organisation, repository, username, token) {
1382
- if (!organisation || !repository || !username || !token) {
1383
- return {
1384
- status: "skipped",
1385
- reason: "Some values are kept from existing GitHub secrets, which cannot be read back"
1386
- };
1387
- }
1388
- try {
1389
- const login = await fetch(`${DOCKER_HUB_API}/auth/token`, {
1390
- method: "POST",
1391
- headers: { "Content-Type": "application/json" },
1392
- body: JSON.stringify({ identifier: username, secret: token }),
1393
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1394
- });
1395
- if (login.status === 401 || login.status === 403) {
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:
1396
1424
  return {
1397
1425
  status: "invalid-credentials",
1398
- reason: "Docker Hub rejected the username or token. Check DOCKER_USERNAME and DOCKER_TOKEN"
1399
- };
1400
- }
1401
- if (!login.ok) {
1402
- return {
1403
- status: "unreachable",
1404
- reason: `Docker Hub login responded with HTTP ${login.status}`
1405
- };
1406
- }
1407
- const body = await login.json();
1408
- const accessToken = body.access_token ?? body.token;
1409
- if (!accessToken) {
1410
- return {
1411
- status: "unreachable",
1412
- reason: "Docker Hub login response did not contain an access token"
1426
+ reason: `${reason}. Check REGISTRY_USERNAME, REGISTRY_TOKEN, REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
1413
1427
  };
1414
- }
1415
- const repositoryResponse = await fetch(
1416
- `${DOCKER_HUB_API}/repositories/${encodeURIComponent(
1417
- organisation
1418
- )}/${encodeURIComponent(repository)}/`,
1419
- {
1420
- headers: { Authorization: `Bearer ${accessToken}` },
1421
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1422
- }
1423
- );
1424
- if (repositoryResponse.ok) {
1425
- return { status: "valid" };
1426
- }
1427
- if (repositoryResponse.status === 404) {
1428
+ case 404:
1428
1429
  return {
1429
1430
  status: "repository-not-found",
1430
- reason: `Login succeeded, but repository ${organisation}/${repository} was not found or is not accessible with this token. Check DOCKERHUB_ACCOUNT and DOCKERHUB_REPO`
1431
- };
1432
- }
1433
- if (repositoryResponse.status === 401 || repositoryResponse.status === 403) {
1434
- return {
1435
- status: "invalid-credentials",
1436
- reason: `Login succeeded, but the token is not allowed to read repository ${organisation}/${repository}`
1431
+ reason: `${reason}. This is also the answer for an empty repository. Check REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
1437
1432
  };
1438
- }
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
1439
  return {
1440
- status: "unreachable",
1441
- reason: `Docker Hub repository lookup responded with HTTP ${repositoryResponse.status}`
1440
+ status: "skipped",
1441
+ reason: "Some values are kept from existing GitHub secrets, which cannot be read back"
1442
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);
1443
1473
  } catch (err) {
1444
1474
  if (!(err instanceof Error)) {
1445
1475
  return { status: "unreachable", reason: String(err) };
@@ -1448,11 +1478,10 @@ async function validateDockerHubCredentials(organisation, repository, username,
1448
1478
  return { status: "unreachable", reason: `${err.message}${cause}` };
1449
1479
  }
1450
1480
  }
1451
- var DOCKER_HUB_API, REQUEST_TIMEOUT_MS;
1452
- var init_dockerhub = __esm({
1453
- "src/environment/dockerhub.ts"() {
1481
+ var REQUEST_TIMEOUT_MS;
1482
+ var init_registry = __esm({
1483
+ "src/environment/registry.ts"() {
1454
1484
  "use strict";
1455
- DOCKER_HUB_API = "https://hub.docker.com/v2";
1456
1485
  REQUEST_TIMEOUT_MS = 1e4;
1457
1486
  }
1458
1487
  });
@@ -1483,7 +1512,7 @@ function getCurrentUsername() {
1483
1512
  }
1484
1513
  function getCurrentUserSSHKeys() {
1485
1514
  const homeDir = os.homedir();
1486
- const sshDir = path8.join(homeDir, ".ssh");
1515
+ const sshDir = path11.join(homeDir, ".ssh");
1487
1516
  const keys = [];
1488
1517
  const keyFiles = [
1489
1518
  "id_rsa.pub",
@@ -1492,7 +1521,7 @@ function getCurrentUserSSHKeys() {
1492
1521
  "id_dsa.pub"
1493
1522
  ];
1494
1523
  for (const keyFile of keyFiles) {
1495
- const keyPath = path8.join(sshDir, keyFile);
1524
+ const keyPath = path11.join(sshDir, keyFile);
1496
1525
  try {
1497
1526
  if (fs5.existsSync(keyPath)) {
1498
1527
  const keyContent = fs5.readFileSync(keyPath, "utf8").trim();
@@ -1833,13 +1862,13 @@ async function manageUsers(inventoryPath) {
1833
1862
  }
1834
1863
  return users;
1835
1864
  }
1836
- var os, fs5, path8, input2, select2, confirm, editor, checkbox;
1865
+ var os, fs5, path11, input2, select2, confirm, editor, checkbox;
1837
1866
  var init_manage_users = __esm({
1838
1867
  "src/environment/manage-users.ts"() {
1839
1868
  "use strict";
1840
1869
  os = __toESM(require("os"));
1841
1870
  fs5 = __toESM(require("fs"));
1842
- path8 = __toESM(require("path"));
1871
+ path11 = __toESM(require("path"));
1843
1872
  init_logger();
1844
1873
  init_utils();
1845
1874
  init_templates();
@@ -1871,6 +1900,7 @@ async function input3(options) {
1871
1900
  function questionToPrompt({
1872
1901
  valueType,
1873
1902
  valueLabel,
1903
+ legacyValueLabel,
1874
1904
  scope,
1875
1905
  ...promptOptions
1876
1906
  }) {
@@ -1934,6 +1964,12 @@ function getAnswers(existingValues) {
1934
1964
  });
1935
1965
  });
1936
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
+ }
1937
1973
  async function promptAndStoreAnswer(questions, existingValues) {
1938
1974
  log("");
1939
1975
  const processedQuestions = questions.flatMap((question) => {
@@ -1951,14 +1987,22 @@ async function promptAndStoreAnswer(questions, existingValues) {
1951
1987
  questionWithVariableLabel.scope,
1952
1988
  existingValues
1953
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
+ }
1954
2005
  if (existingVariable) {
1955
- let initial_value = existingVariable.value;
1956
- if (questionWithVariableLabel.type === "select" && Array.isArray(questionWithVariableLabel.choices)) {
1957
- initial_value = getIndexFromChoices(
1958
- questionWithVariableLabel.choices,
1959
- existingVariable.value
1960
- );
1961
- }
1962
2006
  return [
1963
2007
  {
1964
2008
  name: "overWrite" + questionWithVariableLabel.name,
@@ -1973,7 +2017,10 @@ async function promptAndStoreAnswer(questions, existingValues) {
1973
2017
  {
1974
2018
  ...questionWithVariableLabel,
1975
2019
  type: (prev) => prev ? questionWithVariableLabel.type : null,
1976
- initial: initial_value
2020
+ initial: getInitialValue(
2021
+ questionWithVariableLabel,
2022
+ existingVariable
2023
+ )
1977
2024
  }
1978
2025
  ];
1979
2026
  }
@@ -1985,6 +2032,32 @@ async function promptAndStoreAnswer(questions, existingValues) {
1985
2032
  questionWithVariableLabel.scope,
1986
2033
  existingValues
1987
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
+ }
1988
2061
  if (existingSecret) {
1989
2062
  return [
1990
2063
  {
@@ -2024,13 +2097,32 @@ async function promptAndStoreAnswer(questions, existingValues) {
2024
2097
  ]);
2025
2098
  return { ...Object.fromEntries(existingValuesForQuestions), ...result };
2026
2099
  }
2027
- async function promptAndValidateDockerhub(existingValues) {
2028
- const answers = await promptAndStoreAnswer(dockerhubQuestions, existingValues);
2029
- const result = await validateDockerHubCredentials(
2030
- answers.dockerhubOrganisation,
2031
- answers.dockerhubRepository,
2032
- answers.dockerhubUsername,
2033
- answers.dockerhubToken
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
2034
2126
  );
2035
2127
  if (result.status === "valid" || result.status === "skipped") {
2036
2128
  return;
@@ -2039,7 +2131,7 @@ async function promptAndValidateDockerhub(existingValues) {
2039
2131
  ${result.status}: ${result.reason || "Generic error"}
2040
2132
  `);
2041
2133
  const continueNotValidated = await confirm2({
2042
- message: "Docker Hub credentials are not validated. Continue anyway?",
2134
+ message: "Container registry credentials are not validated. Continue anyway?",
2043
2135
  default: false
2044
2136
  });
2045
2137
  if (!continueNotValidated) {
@@ -2170,7 +2262,22 @@ async function runSetupEnvironment() {
2170
2262
  "WARNING! You are setting up a production environment.\n Make sure you have read the deployment guide carefully before proceeding.\n"
2171
2263
  )
2172
2264
  );
2173
- 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);
2174
2281
  }
2175
2282
  log("\n", import_kleur4.default.bold().underline("Two-factor authentication (2FA)"));
2176
2283
  const existingTwoFaEnabled = findExistingValue(
@@ -2189,8 +2296,8 @@ async function runSetupEnvironment() {
2189
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."
2190
2297
  );
2191
2298
  }
2192
- log("\n", import_kleur4.default.bold().underline("Docker Hub"));
2193
- await promptAndValidateDockerhub(existingValues);
2299
+ log("\n", import_kleur4.default.bold().underline("Container registry"));
2300
+ await promptAndValidateRegistry(existingValues);
2194
2301
  log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
2195
2302
  const infrastructure = await promptAndStoreAnswer(
2196
2303
  infrastructureQuestions,
@@ -2282,6 +2389,14 @@ async function runSetupEnvironment() {
2282
2389
  );
2283
2390
  }
2284
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";
2285
2400
  let backupHost = findExistingValue("BACKUP_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2286
2401
  let backupType = "";
2287
2402
  let restoreEnvironmentName = findExistingValue(
@@ -2420,9 +2535,7 @@ async function runSetupEnvironment() {
2420
2535
  return { ...acc, ...answer };
2421
2536
  });
2422
2537
  const answerOrExisting = (variable, existingValue, fn) => fn(variable || existingValue?.value) || "";
2423
- function findExistingOrDefine(name, type, scope, newValue) {
2424
- return findExistingValue(name, type, scope, existingValues) ? null : process.env[name] || newValue;
2425
- }
2538
+ const findExistingOrDefine = (name, type, scope, newValue) => defineIfMissing(existingValues, name, type, scope, newValue);
2426
2539
  const derivedUpdates = [
2427
2540
  {
2428
2541
  name: "GH_ENCRYPTION_PASSWORD",
@@ -2474,6 +2587,13 @@ async function runSetupEnvironment() {
2474
2587
  value: monitoring_enabled ? "true" : "false",
2475
2588
  scope: "ENVIRONMENT"
2476
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
+ });
2477
2597
  derivedUpdates.push(...ssl_answers);
2478
2598
  if (configureBackup) {
2479
2599
  derivedUpdates.push({
@@ -2820,7 +2940,7 @@ async function runSetupEnvironment() {
2820
2940
  );
2821
2941
  const unknownVariables = existingValues.filter((value) => {
2822
2942
  return !ALL_QUESTIONS.find(
2823
- (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
2824
2944
  );
2825
2945
  });
2826
2946
  log("");
@@ -3025,6 +3145,8 @@ async function runSetupEnvironment() {
3025
3145
  environment_type,
3026
3146
  two_fa_enabled,
3027
3147
  monitoring_enabled,
3148
+ rustfs_host_data_path,
3149
+ rustfs_pvc_name,
3028
3150
  traefik_mode: traefikConfOption,
3029
3151
  restore_enabled: restoreEnvironmentName ? true : false,
3030
3152
  restore_environment_name: restoreEnvironmentName || "",
@@ -3090,7 +3212,7 @@ var init_setup_environment = __esm({
3090
3212
  init_questions();
3091
3213
  init_editor_questions();
3092
3214
  init_questions_helper();
3093
- init_dockerhub();
3215
+ init_registry();
3094
3216
  init_manage_users();
3095
3217
  init_paths();
3096
3218
  ALL_QUESTIONS = [];
@@ -3098,7 +3220,7 @@ var init_setup_environment = __esm({
3098
3220
  ALL_QUESTIONS.push(
3099
3221
  ...githubTokenQuestion,
3100
3222
  ...githubOtherQuestions,
3101
- ...dockerhubQuestions,
3223
+ ...registryQuestions,
3102
3224
  ...diskQuestions,
3103
3225
  ...infrastructureQuestions,
3104
3226
  ...backupQuestions,
@@ -3127,7 +3249,7 @@ function moveFileIfDestinationMissing(sourcePath, destinationPath) {
3127
3249
  );
3128
3250
  return false;
3129
3251
  }
3130
- (0, import_fs7.mkdirSync)((0, import_path10.dirname)(destinationPath), { recursive: true });
3252
+ (0, import_fs7.mkdirSync)((0, import_path13.dirname)(destinationPath), { recursive: true });
3131
3253
  (0, import_fs7.renameSync)(sourcePath, destinationPath);
3132
3254
  log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
3133
3255
  return true;
@@ -3167,12 +3289,12 @@ async function upgradeEnvironmentLayout() {
3167
3289
  }
3168
3290
  log("\nCommit changes into git after upgrade");
3169
3291
  }
3170
- var import_fs7, import_path10, import_kleur5;
3292
+ var import_fs7, import_path13, import_kleur5;
3171
3293
  var init_upgrade = __esm({
3172
3294
  "src/environment/upgrade.ts"() {
3173
3295
  "use strict";
3174
3296
  import_fs7 = require("fs");
3175
- import_path10 = require("path");
3297
+ import_path13 = require("path");
3176
3298
  import_kleur5 = __toESM(require("kleur"));
3177
3299
  init_logger();
3178
3300
  init_paths();
@@ -3198,7 +3320,7 @@ async function selectInventoryFile(dirPath = "./environments") {
3198
3320
  return null;
3199
3321
  }
3200
3322
  const environments = fs6.readdirSync(dirPath).filter((entry) => {
3201
- const filePath = path9.join(dirPath, entry);
3323
+ const filePath = path12.join(dirPath, entry);
3202
3324
  return fs6.statSync(filePath).isDirectory() && fs6.existsSync(getEnvironmentInventoryPath(entry));
3203
3325
  }).sort();
3204
3326
  if (environments.length === 0) {
@@ -3226,12 +3348,12 @@ async function manageEnvironmentUsers() {
3226
3348
  }
3227
3349
  await manageUsers(inventory_file);
3228
3350
  }
3229
- var fs6, path9, import_kleur6;
3351
+ var fs6, path12, import_kleur6;
3230
3352
  var init_users = __esm({
3231
3353
  "src/environment/users.ts"() {
3232
3354
  "use strict";
3233
3355
  fs6 = __toESM(require("fs"));
3234
- path9 = __toESM(require("path"));
3356
+ path12 = __toESM(require("path"));
3235
3357
  import_kleur6 = __toESM(require("kleur"));
3236
3358
  init_manage_users();
3237
3359
  init_logger();
@@ -3241,11 +3363,11 @@ var init_users = __esm({
3241
3363
 
3242
3364
  // src/environment/swarm-to-k8s.ts
3243
3365
  var swarm_to_k8s_exports = {};
3244
- var path10, import_kleur7, import_core2;
3366
+ var path13, import_kleur7, import_core2;
3245
3367
  var init_swarm_to_k8s = __esm({
3246
3368
  "src/environment/swarm-to-k8s.ts"() {
3247
3369
  "use strict";
3248
- path10 = __toESM(require("path"));
3370
+ path13 = __toESM(require("path"));
3249
3371
  import_kleur7 = __toESM(require("kleur"));
3250
3372
  init_logger();
3251
3373
  init_utils();
@@ -3297,7 +3419,7 @@ var init_swarm_to_k8s = __esm({
3297
3419
  );
3298
3420
  process.exit(1);
3299
3421
  }
3300
- const ansible_inventory = path10.join(old_inventory_path, environment + ".yml");
3422
+ const ansible_inventory = path13.join(old_inventory_path, environment + ".yml");
3301
3423
  const data = readYamlFile(ansible_inventory);
3302
3424
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3303
3425
  const master = dockerManagerFirst(data) || "";
@@ -3420,7 +3542,7 @@ var init_swarm_to_k8s = __esm({
3420
3542
 
3421
3543
  // src/cli.ts
3422
3544
  var import_fs9 = __toESM(require("fs"));
3423
- var import_path12 = __toESM(require("path"));
3545
+ var import_path15 = __toESM(require("path"));
3424
3546
 
3425
3547
  // src/migrations/persistent/add-translations.ts
3426
3548
  var import_path = __toESM(require("path"));
@@ -3465,20 +3587,20 @@ function idOf(line2) {
3465
3587
  const comma = line2.indexOf(",");
3466
3588
  return comma === -1 ? line2 : line2.slice(0, comma);
3467
3589
  }
3468
- function readCsvFile(path12) {
3469
- if (!(0, import_fs.existsSync)(path12)) {
3590
+ function readCsvFile(path15) {
3591
+ if (!(0, import_fs.existsSync)(path15)) {
3470
3592
  return void 0;
3471
3593
  }
3472
- const contents = (0, import_fs.readFileSync)(path12, "utf8");
3594
+ const contents = (0, import_fs.readFileSync)(path15, "utf8");
3473
3595
  const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3474
3596
  const trailingNewline = /\r?\n$/.test(contents);
3475
3597
  const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3476
3598
  const body = lines.slice(1).filter((line2) => line2 !== "");
3477
3599
  return { header: lines[0], body, newline, trailingNewline };
3478
3600
  }
3479
- function writeCsvFile(path12, file) {
3601
+ function writeCsvFile(path15, file) {
3480
3602
  (0, import_fs.writeFileSync)(
3481
- path12,
3603
+ path15,
3482
3604
  [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3483
3605
  );
3484
3606
  }
@@ -3640,12 +3762,14 @@ async function main(targetVersion) {
3640
3762
  }
3641
3763
 
3642
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
3643
3769
  var import_ts_morph = require("ts-morph");
3644
3770
  var import_path2 = __toESM(require("path"));
3645
3771
  var DEFINE_CONFIG_NAME = "defineConfig";
3646
- var DECLARATION_PROPERTY_NAME = "declaration";
3647
- var ACTIONS_PROPERTY_NAME = "actions";
3648
- var DECLARE_ACTION_TYPE = "DECLARE";
3772
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3649
3773
  function location(node) {
3650
3774
  const relPath = import_path2.default.relative(
3651
3775
  process.cwd(),
@@ -3665,7 +3789,7 @@ function findProperty(literal, name) {
3665
3789
  const property = literal.getProperty(name);
3666
3790
  return import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property) ? property : void 0;
3667
3791
  }
3668
- function mayHaveDeclareType(actionType, node) {
3792
+ function mayHaveActionType(actionType, node, expectedActionType) {
3669
3793
  const typeProperty = actionType.getProperty("type");
3670
3794
  if (!typeProperty) {
3671
3795
  return true;
@@ -3673,70 +3797,45 @@ function mayHaveDeclareType(actionType, node) {
3673
3797
  const type = typeProperty.getTypeAtLocation(node);
3674
3798
  const values = type.isUnion() ? type.getUnionTypes() : [type];
3675
3799
  return !values.every(
3676
- (value) => value.isStringLiteral() && value.getLiteralValue() !== DECLARE_ACTION_TYPE
3800
+ (value) => value.isStringLiteral() && value.getLiteralValue() !== expectedActionType
3677
3801
  );
3678
3802
  }
3679
- function mayBeDeclareAction(node) {
3803
+ function mayBeAction(node, actionType) {
3680
3804
  if (import_ts_morph.Node.isObjectLiteralExpression(node)) {
3681
- return isDeclareAction(node);
3805
+ return isAction(node, actionType);
3682
3806
  }
3683
3807
  if (import_ts_morph.Node.isSpreadElement(node)) {
3684
3808
  const arrayType = node.getExpression().getType();
3685
3809
  const elementTypes = arrayType.isTuple() ? arrayType.getTupleElements() : [arrayType.getArrayElementType()];
3686
3810
  return elementTypes.some(
3687
- (elementType) => !elementType || mayHaveDeclareType(elementType, node)
3811
+ (elementType) => !elementType || mayHaveActionType(elementType, node, actionType)
3688
3812
  );
3689
3813
  }
3690
- return mayHaveDeclareType(node.getType(), node);
3814
+ return mayHaveActionType(node.getType(), node, actionType);
3691
3815
  }
3692
- function isDeclareAction(literal) {
3816
+ function isAction(literal, actionType) {
3693
3817
  const type = findProperty(literal, "type");
3694
- return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === DECLARE_ACTION_TYPE;
3695
- }
3696
- function findDeclareAction(config) {
3697
- const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
3698
- const actionsValue = import_ts_morph.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
3699
- if (!import_ts_morph.Node.isArrayLiteralExpression(actionsValue)) {
3700
- console.warn(
3701
- ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`
3702
- );
3703
- return void 0;
3704
- }
3705
- const candidates = actionsValue.getElements().filter(mayBeDeclareAction);
3706
- if (candidates.length !== 1 || !import_ts_morph.Node.isObjectLiteralExpression(candidates[0])) {
3707
- console.warn(
3708
- ` [${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.`
3709
- );
3710
- return void 0;
3711
- }
3712
- const declareAction = candidates[0];
3713
- if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
3714
- console.warn(
3715
- ` [${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.`
3716
- );
3717
- return void 0;
3718
- }
3719
- return declareAction;
3818
+ return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === actionType;
3720
3819
  }
3721
3820
  function indentationOf(node) {
3722
- const text = node.getSourceFile().getFullText();
3723
- const lineStart = text.lastIndexOf("\n", node.getStart() - 1) + 1;
3724
- return /^[ \t]*/.exec(text.slice(lineStart))?.[0] ?? "";
3821
+ const text2 = node.getSourceFile().getFullText();
3822
+ const lineStart = text2.lastIndexOf("\n", node.getStart() - 1) + 1;
3823
+ return /^[ \t]*/.exec(text2.slice(lineStart))?.[0] ?? "";
3725
3824
  }
3726
- function restOfLine(text, position) {
3727
- const lineEnd = text.indexOf("\n", position);
3728
- return text.slice(position, lineEnd === -1 ? text.length : lineEnd);
3825
+ function restOfLine(text2, position) {
3826
+ const lineEnd = text2.indexOf("\n", position);
3827
+ return text2.slice(position, lineEnd === -1 ? text2.length : lineEnd);
3729
3828
  }
3730
- function isOnlyComments(text) {
3731
- return /^\s*(?:\/\/.*|\/\*.*?\*\/\s*)*$/.test(text);
3829
+ function isOnlyComments(text2) {
3830
+ return /^\s*(?:\/\/.*|\/\*.*?\*\/\s*)*$/.test(text2);
3732
3831
  }
3733
3832
  function layoutOf(property) {
3734
- const text = property.getSourceFile().getFullText();
3833
+ const text2 = property.getSourceFile().getFullText();
3735
3834
  const next = property.getNextSibling();
3736
3835
  const hasComma = next?.getKind() === import_ts_morph.SyntaxKind.CommaToken;
3737
3836
  const end = next && hasComma ? next.getEnd() : property.getEnd();
3738
- const trailing = restOfLine(text, end);
3739
- const lineBreak = text.slice(property.getFullStart(), property.getStart()).indexOf("\n");
3837
+ const trailing = restOfLine(text2, end);
3838
+ const lineBreak = text2.slice(property.getFullStart(), property.getStart()).indexOf("\n");
3740
3839
  if (lineBreak === -1 || !isOnlyComments(trailing)) {
3741
3840
  return {
3742
3841
  ownsLines: false,
@@ -3749,18 +3848,102 @@ function layoutOf(property) {
3749
3848
  const firstLine = property.getFullStart() + lineBreak + 1;
3750
3849
  return {
3751
3850
  ownsLines: true,
3752
- start: firstLine + (/^\s*/.exec(text.slice(firstLine))?.[0].length ?? 0),
3851
+ start: firstLine + (/^\s*/.exec(text2.slice(firstLine))?.[0].length ?? 0),
3753
3852
  end,
3754
3853
  hasComma,
3755
3854
  trailingComment: trailing.trimEnd()
3756
3855
  };
3757
3856
  }
3758
- function insertAt(position, text) {
3759
- return { start: position, end: position, text };
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);
3866
+ }
3867
+ function findToolkitImport(sourceFile) {
3868
+ return sourceFile.getImportDeclaration(
3869
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
3870
+ );
3871
+ }
3872
+ function findToolkitImportName(sourceFile, name) {
3873
+ const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === name);
3874
+ if (imported) {
3875
+ return imported.getAliasNode()?.getText() ?? name;
3876
+ }
3877
+ if (sourceFile.getLocal(name)) {
3878
+ return void 0;
3879
+ }
3880
+ return name;
3881
+ }
3882
+ function addToolkitImport(sourceFile, name) {
3883
+ const toolkitImport = findToolkitImport(sourceFile);
3884
+ if (!toolkitImport) {
3885
+ const imports = sourceFile.getImportDeclarations();
3886
+ const lastImport = imports[imports.length - 1];
3887
+ sourceFile.insertStatements(
3888
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
3889
+ `import { ${name} } from '${TOOLKIT_EVENTS_MODULE}'`
3890
+ );
3891
+ return;
3892
+ }
3893
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === name);
3894
+ if (alreadyImported) {
3895
+ return;
3896
+ }
3897
+ const namedImports = toolkitImport.getNamedImports();
3898
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
3899
+ toolkitImport.addNamedImport(name);
3900
+ return;
3901
+ }
3902
+ const names = [
3903
+ ...namedImports.map((namedImport) => namedImport.getText()),
3904
+ name
3905
+ ];
3906
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
3907
+ ${names.join(",\n ")}
3908
+ }` : `{ ${names.join(", ")} }`;
3909
+ toolkitImport.replaceWithText(
3910
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
3911
+ );
3912
+ }
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;
3927
+ }
3928
+ const candidates = actionsValue.getElements().filter((element) => mayBeAction(element, DECLARE_ACTION_TYPE));
3929
+ if (candidates.length !== 1 || !import_ts_morph2.Node.isObjectLiteralExpression(candidates[0])) {
3930
+ console.warn(
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.`
3932
+ );
3933
+ return void 0;
3934
+ }
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.`
3939
+ );
3940
+ return void 0;
3941
+ }
3942
+ return declareAction;
3760
3943
  }
3761
3944
  function insertIntoDeclareAction(declareAction, property) {
3762
3945
  const anchor = declareAction.getProperty("label") ?? declareAction.getPropertyOrThrow("type");
3763
- const text = property.getSourceFile().getFullText();
3946
+ const text2 = property.getSourceFile().getFullText();
3764
3947
  const anchorLayout = layoutOf(anchor);
3765
3948
  const layout = layoutOf(property);
3766
3949
  const indent = indentationOf(anchor);
@@ -3769,8 +3952,8 @@ function insertIntoDeclareAction(declareAction, property) {
3769
3952
  (line2, index) => index > 0 && line2.startsWith(oldIndent) ? indent + line2.slice(oldIndent.length) : line2
3770
3953
  ).join("\n");
3771
3954
  if (anchorLayout.ownsLines) {
3772
- const moved = reindent(text.slice(layout.start, property.getEnd()));
3773
- const position = anchorLayout.end + restOfLine(text, anchorLayout.end).length;
3955
+ const moved = reindent(text2.slice(layout.start, property.getEnd()));
3956
+ const position = anchorLayout.end + restOfLine(text2, anchorLayout.end).length;
3774
3957
  const insertion = `
3775
3958
  ${indent}${moved}${anchorLayout.hasComma ? "," : ""}${layout.trailingComment}`;
3776
3959
  if (anchorLayout.hasComma) {
@@ -3778,7 +3961,7 @@ ${indent}${moved}${anchorLayout.hasComma ? "," : ""}${layout.trailingComment}`;
3778
3961
  }
3779
3962
  return position === anchor.getEnd() ? [insertAt(position, `,${insertion}`)] : [insertAt(anchor.getEnd(), ","), insertAt(position, insertion)];
3780
3963
  }
3781
- const droppedComments = text.slice(layout.start, property.getStart(true)).trim() !== "" || layout.trailingComment !== "";
3964
+ const droppedComments = text2.slice(layout.start, property.getStart(true)).trim() !== "" || layout.trailingComment !== "";
3782
3965
  if (droppedComments) {
3783
3966
  console.warn(
3784
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.`
@@ -3792,13 +3975,13 @@ ${indent}` : ", ";
3792
3975
  ];
3793
3976
  }
3794
3977
  function removeFromConfig(property) {
3795
- const text = property.getSourceFile().getFullText();
3978
+ const text2 = property.getSourceFile().getFullText();
3796
3979
  const layout = layoutOf(property);
3797
- const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph.SyntaxKind.CommaToken);
3980
+ const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph2.SyntaxKind.CommaToken);
3798
3981
  if (layout.ownsLines) {
3799
3982
  const lines = {
3800
- start: text.lastIndexOf("\n", layout.start - 1),
3801
- end: layout.end + restOfLine(text, layout.end).length,
3983
+ start: text2.lastIndexOf("\n", layout.start - 1),
3984
+ end: layout.end + restOfLine(text2, layout.end).length,
3802
3985
  text: ""
3803
3986
  };
3804
3987
  return !layout.hasComma && previousComma ? [
@@ -3823,18 +4006,18 @@ function removeFromConfig(property) {
3823
4006
  }
3824
4007
  function findConfigLiteral(call) {
3825
4008
  const config = call.getArguments()[0];
3826
- if (!config || import_ts_morph.Node.isObjectLiteralExpression(config)) {
4009
+ if (!config || import_ts_morph2.Node.isObjectLiteralExpression(config)) {
3827
4010
  return config;
3828
4011
  }
3829
4012
  if (config.getType().getProperty(DECLARATION_PROPERTY_NAME)) {
3830
4013
  console.warn(
3831
- ` [${location(config)}] Skipped: \`${DEFINE_CONFIG_NAME}\` 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.`
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.`
3832
4015
  );
3833
4016
  }
3834
4017
  return void 0;
3835
4018
  }
3836
4019
  function moveDeclarationToDeclareAction(sourceFile) {
3837
- const configs = sourceFile.getDescendantsOfKind(import_ts_morph.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph.Node.isObjectLiteralExpression);
4020
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph2.Node.isObjectLiteralExpression);
3838
4021
  const edits = [];
3839
4022
  let changes = 0;
3840
4023
  for (const config of configs) {
@@ -3858,19 +4041,15 @@ function moveDeclarationToDeclareAction(sourceFile) {
3858
4041
  if (changes === 0) {
3859
4042
  return 0;
3860
4043
  }
3861
- const text = 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(text);
4044
+ applyTextEdits(sourceFile, edits);
3866
4045
  return changes;
3867
4046
  }
3868
4047
  async function main2() {
3869
- const srcDir = import_path2.default.join(process.cwd(), "src");
4048
+ const srcDir = import_path3.default.join(process.cwd(), "src");
3870
4049
  console.log(`Scanning for top-level event declarations in: ${srcDir}
3871
4050
  `);
3872
- const project = new import_ts_morph.Project({
3873
- tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
4051
+ const project = new import_ts_morph2.Project({
4052
+ tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
3874
4053
  skipAddingFilesFromTsConfig: false
3875
4054
  });
3876
4055
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -3897,7 +4076,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
3897
4076
  for (const sourceFile of modifiedFiles) {
3898
4077
  await sourceFile.save();
3899
4078
  console.log(
3900
- ` Saved: ${import_path2.default.relative(process.cwd(), sourceFile.getFilePath())}`
4079
+ ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
3901
4080
  );
3902
4081
  }
3903
4082
  console.log(
@@ -3906,36 +4085,223 @@ Done. Moved ${totalChanges} declaration(s) across ${modifiedFiles.length} file(s
3906
4085
  );
3907
4086
  }
3908
4087
 
3909
- // src/migrations/read-declaration-through-helper.ts
3910
- var import_ts_morph2 = require("ts-morph");
3911
- var import_path3 = __toESM(require("path"));
3912
- var EVENT_CONFIG_TYPE_NAME = "EventConfig";
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";
3913
4093
  var DECLARATION_PROPERTY_NAME2 = "declaration";
3914
- var GET_DECLARATION_NAME = "getDeclaration";
3915
- var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3916
- function isToolkitEventConfig(type) {
3917
- const nonNullableType = type.getNonNullableType();
3918
- const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
3919
- if (symbol?.getName() !== EVENT_CONFIG_TYPE_NAME) {
3920
- return false;
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"
3921
4106
  }
3922
- return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
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());
3923
4289
  }
3924
4290
  function isDeclarationReadOnEventConfig(node) {
3925
- return node.getName() === DECLARATION_PROPERTY_NAME2 && isToolkitEventConfig(node.getExpression().getType());
4291
+ return node.getName() === DECLARATION_PROPERTY_NAME3 && isToolkitEventConfig(node.getExpression().getType());
3926
4292
  }
3927
4293
  function isAssignmentOperator(kind) {
3928
- return kind >= import_ts_morph2.SyntaxKind.FirstAssignment && kind <= import_ts_morph2.SyntaxKind.LastAssignment;
4294
+ return kind >= import_ts_morph4.SyntaxKind.FirstAssignment && kind <= import_ts_morph4.SyntaxKind.LastAssignment;
3929
4295
  }
3930
4296
  function isWriteTarget(node) {
3931
4297
  const parent = node.getParent();
3932
- if (import_ts_morph2.Node.isDeleteExpression(parent)) {
4298
+ if (import_ts_morph4.Node.isDeleteExpression(parent)) {
3933
4299
  return true;
3934
4300
  }
3935
- return import_ts_morph2.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
4301
+ return import_ts_morph4.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
3936
4302
  }
3937
4303
  function location2(node) {
3938
- const relPath = import_path3.default.relative(
4304
+ const relPath = import_path5.default.relative(
3939
4305
  process.cwd(),
3940
4306
  node.getSourceFile().getFilePath()
3941
4307
  );
@@ -3943,86 +4309,40 @@ function location2(node) {
3943
4309
  }
3944
4310
  function warnDestructuredDeclarations(sourceFile) {
3945
4311
  for (const pattern of sourceFile.getDescendantsOfKind(
3946
- import_ts_morph2.SyntaxKind.ObjectBindingPattern
4312
+ import_ts_morph4.SyntaxKind.ObjectBindingPattern
3947
4313
  )) {
3948
4314
  const destructuresDeclaration = pattern.getElements().some(
3949
- (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME2
4315
+ (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME3
3950
4316
  );
3951
4317
  if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
3952
4318
  console.warn(
3953
- ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME2}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
4319
+ ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME3}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
3954
4320
  );
3955
4321
  }
3956
4322
  }
3957
4323
  }
3958
4324
  function warnSpreadDeclarations(sourceFile) {
3959
4325
  for (const literal of sourceFile.getDescendantsOfKind(
3960
- import_ts_morph2.SyntaxKind.ObjectLiteralExpression
4326
+ import_ts_morph4.SyntaxKind.ObjectLiteralExpression
3961
4327
  )) {
3962
4328
  const properties = literal.getProperties();
3963
4329
  const spreadsEventConfig = properties.some(
3964
- (property) => import_ts_morph2.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
4330
+ (property) => import_ts_morph4.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
3965
4331
  );
3966
4332
  const setsDeclaration = properties.some(
3967
- (property) => (import_ts_morph2.Node.isPropertyAssignment(property) || import_ts_morph2.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME2
4333
+ (property) => (import_ts_morph4.Node.isPropertyAssignment(property) || import_ts_morph4.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME3
3968
4334
  );
3969
4335
  if (spreadsEventConfig && setsDeclaration) {
3970
4336
  console.warn(
3971
- ` [${location2(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME2}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME2}\` on its DECLARE action, so replace that one by hand.`
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.`
3972
4338
  );
3973
4339
  }
3974
4340
  }
3975
4341
  }
3976
- function findToolkitImport(sourceFile) {
3977
- return sourceFile.getImportDeclaration(
3978
- (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
3979
- );
3980
- }
3981
- function findGetDeclarationName(sourceFile) {
3982
- const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
3983
- if (imported) {
3984
- return imported.getAliasNode()?.getText() ?? GET_DECLARATION_NAME;
3985
- }
3986
- if (sourceFile.getLocal(GET_DECLARATION_NAME)) {
3987
- return void 0;
3988
- }
3989
- return GET_DECLARATION_NAME;
3990
- }
3991
- function addGetDeclarationImport(sourceFile) {
3992
- const toolkitImport = findToolkitImport(sourceFile);
3993
- if (!toolkitImport) {
3994
- const imports = sourceFile.getImportDeclarations();
3995
- const lastImport = imports[imports.length - 1];
3996
- sourceFile.insertStatements(
3997
- lastImport ? lastImport.getChildIndex() + 1 : 0,
3998
- `import { ${GET_DECLARATION_NAME} } from '${TOOLKIT_EVENTS_MODULE}'`
3999
- );
4000
- return;
4001
- }
4002
- const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
4003
- if (alreadyImported) {
4004
- return;
4005
- }
4006
- const namedImports = toolkitImport.getNamedImports();
4007
- if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
4008
- toolkitImport.addNamedImport(GET_DECLARATION_NAME);
4009
- return;
4010
- }
4011
- const names = [
4012
- ...namedImports.map((namedImport) => namedImport.getText()),
4013
- GET_DECLARATION_NAME
4014
- ];
4015
- const specifiers = toolkitImport.getText().includes("\n") ? `{
4016
- ${names.join(",\n ")}
4017
- }` : `{ ${names.join(", ")} }`;
4018
- toolkitImport.replaceWithText(
4019
- `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
4020
- );
4021
- }
4022
4342
  function rewriteDeclarationReads(sourceFile) {
4023
4343
  warnDestructuredDeclarations(sourceFile);
4024
4344
  warnSpreadDeclarations(sourceFile);
4025
- const reads = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
4345
+ const reads = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
4026
4346
  if (node.hasQuestionDotToken()) {
4027
4347
  console.warn(
4028
4348
  ` [${location2(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
@@ -4031,7 +4351,7 @@ function rewriteDeclarationReads(sourceFile) {
4031
4351
  }
4032
4352
  if (isWriteTarget(node)) {
4033
4353
  console.warn(
4034
- ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME2}\` on the DECLARE action instead.`
4354
+ ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME3}\` on the DECLARE action instead.`
4035
4355
  );
4036
4356
  return false;
4037
4357
  }
@@ -4040,7 +4360,10 @@ function rewriteDeclarationReads(sourceFile) {
4040
4360
  if (reads.length === 0) {
4041
4361
  return 0;
4042
4362
  }
4043
- const getDeclarationName = findGetDeclarationName(sourceFile);
4363
+ const getDeclarationName = findToolkitImportName(
4364
+ sourceFile,
4365
+ GET_DECLARATION_NAME
4366
+ );
4044
4367
  if (!getDeclarationName) {
4045
4368
  console.warn(
4046
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.`
@@ -4055,15 +4378,15 @@ function rewriteDeclarationReads(sourceFile) {
4055
4378
  `${getDeclarationName}(${read.getExpression().getText()})`
4056
4379
  );
4057
4380
  }
4058
- addGetDeclarationImport(sourceFile);
4381
+ addToolkitImport(sourceFile, GET_DECLARATION_NAME);
4059
4382
  return reads.length;
4060
4383
  }
4061
- async function main3() {
4062
- const srcDir = import_path3.default.join(process.cwd(), "src");
4384
+ async function main4() {
4385
+ const srcDir = import_path5.default.join(process.cwd(), "src");
4063
4386
  console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
4064
4387
  `);
4065
- const project = new import_ts_morph2.Project({
4066
- tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
4388
+ const project = new import_ts_morph4.Project({
4389
+ tsConfigFilePath: import_path5.default.resolve(srcDir, "../tsconfig.json"),
4067
4390
  skipAddingFilesFromTsConfig: false
4068
4391
  });
4069
4392
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -4090,7 +4413,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
4090
4413
  for (const sourceFile of modifiedFiles) {
4091
4414
  await sourceFile.save();
4092
4415
  console.log(
4093
- ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
4416
+ ` Saved: ${import_path5.default.relative(process.cwd(), sourceFile.getFilePath())}`
4094
4417
  );
4095
4418
  }
4096
4419
  console.log(
@@ -4099,229 +4422,1509 @@ Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length}
4099
4422
  );
4100
4423
  }
4101
4424
 
4102
- // src/migrations/persistent/update-toolkit-dependency.ts
4103
- var import_fs3 = __toESM(require("fs"));
4104
- var import_path5 = __toESM(require("path"));
4105
-
4106
- // src/migrations/persistent/check-upgrade-path.ts
4107
- var import_fs2 = __toESM(require("fs"));
4108
- var import_path4 = __toESM(require("path"));
4109
- var TOOLKIT_PACKAGE_NAME = "@opencrvs/toolkit";
4110
- function findMajorMinor(version) {
4111
- const match = /(\d+)\.(\d+)/.exec(version);
4112
- return match ? { major: Number(match[1]), minor: Number(match[2]) } : void 0;
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());
4113
4439
  }
4114
- function format({ major, minor }) {
4115
- return `${major}.${minor}`;
4440
+ function isVersionedEventConfig(type) {
4441
+ return isToolkitType(type, VERSIONED_EVENT_CONFIG_TYPE_NAME);
4116
4442
  }
4117
- function findCountryConfigToolkitVersion(cwd) {
4118
- try {
4119
- const packageJson = JSON.parse(
4120
- import_fs2.default.readFileSync(import_path4.default.join(cwd, "package.json"), "utf-8")
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
+ )
4121
4483
  );
4122
- return packageJson.dependencies?.[TOOLKIT_PACKAGE_NAME] ?? packageJson.devDependencies?.[TOOLKIT_PACKAGE_NAME];
4123
- } catch {
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)) {
4124
4553
  return void 0;
4125
4554
  }
4555
+ return RESOLVE_EVENT_CONFIG_NAME;
4126
4556
  }
4127
- function checkUpgradePath(countryConfigToolkitVersion, toolkitVersion) {
4128
- const target = findMajorMinor(toolkitVersion);
4129
- const current = countryConfigToolkitVersion ? findMajorMinor(countryConfigToolkitVersion) : void 0;
4130
- if (!target || !current) {
4131
- return {
4132
- status: "unknown",
4133
- 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.`
4134
- };
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;
4135
4567
  }
4136
- const isSameVersion = current.major === target.major && current.minor === target.minor;
4137
- const isPreviousMinor = current.major === target.major && current.minor === target.minor - 1;
4138
- const isPreviousMajor = target.minor === 0 && current.major === target.major - 1;
4139
- if (isSameVersion || isPreviousMinor || isPreviousMajor) {
4140
- return { status: "ok" };
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
+ }
5329
+ }
5330
+ async listEnvironments() {
5331
+ const environments = await this.paginate(this.repoPath("/environments"), (body) => body.environments ?? []);
5332
+ return environments.map((environment) => environment.name);
5333
+ }
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
+ };
5406
+
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
+ };
5416
+ }
5417
+
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.");
4141
5528
  }
4142
- const isNewer = current.major > target.major || current.major === target.major && current.minor > target.minor;
4143
- if (isNewer) {
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);
4144
5533
  return {
4145
- status: "blocked",
4146
- 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.`
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
+ }
4147
5545
  };
4148
5546
  }
4149
- const upgradesFrom = target.minor > 0 ? format({ major: target.major, minor: target.minor - 1 }) : `the last ${target.major - 1}.x`;
4150
- const nextStep = current.major === target.major ? `: run \`npx ${TOOLKIT_PACKAGE_NAME}@${format({ major: current.major, minor: current.minor + 1 })} upgrade\` first` : "";
4151
- return {
4152
- status: "blocked",
4153
- message: `The country config is on ${format(current)}, but toolkit ${toolkitVersion} only upgrades from ${upgradesFrom}. Upgrade one minor version at a time${nextStep}.`
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");
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));
4154
5612
  };
4155
5613
  }
4156
5614
 
4157
- // src/migrations/persistent/update-toolkit-dependency.ts
4158
- var DEPENDENCY_PATTERN = new RegExp(
4159
- `("${TOOLKIT_PACKAGE_NAME}"\\s*:\\s*")([^"]*)(")`,
4160
- "g"
4161
- );
4162
- function updateToolkitDependency(packageJson, toolkitVersion) {
4163
- const updated = packageJson.replace(
4164
- DEPENDENCY_PATTERN,
4165
- (match, before, version, after) => {
4166
- if (!findMajorMinor(version)) {
4167
- return match;
4168
- }
4169
- const range = /^[\^~]?/.exec(version)?.[0] ?? "";
4170
- return `${before}${range}${toolkitVersion}${after}`;
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")
4171
5650
  }
4172
- );
4173
- return updated === packageJson ? void 0 : updated;
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
+ });
4174
5668
  }
4175
- async function main4(toolkitVersion) {
4176
- const packageJsonPath = import_path5.default.join(process.cwd(), "package.json");
4177
- if (!import_fs3.default.existsSync(packageJsonPath)) {
4178
- console.log(`No package.json found. Skipping ${TOOLKIT_PACKAGE_NAME}.`);
4179
- return;
4180
- }
4181
- const updated = updateToolkitDependency(
4182
- import_fs3.default.readFileSync(packageJsonPath, "utf-8"),
4183
- toolkitVersion
4184
- );
4185
- if (!updated) {
4186
- console.log(
4187
- `${TOOLKIT_PACKAGE_NAME} in package.json needs no update. Nothing to do.`
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}`
4188
5711
  );
4189
- return;
4190
5712
  }
4191
- import_fs3.default.writeFileSync(packageJsonPath, updated);
4192
- console.log(
4193
- `Updated ${TOOLKIT_PACKAGE_NAME} to ${toolkitVersion} in package.json. Install the dependencies again to use it.`
4194
- );
4195
- }
4196
-
4197
- // src/migrations/replace-incomplete-flag.ts
4198
- var import_ts_morph3 = require("ts-morph");
4199
- var import_path6 = __toESM(require("path"));
4200
- var INCOMPLETE = "InherentFlags.INCOMPLETE";
4201
- var NOTIFIED_STATUS = `{ type: 'exact', term: EventStatus.enum.NOTIFIED }`;
4202
- function ensureEventStatusImport(sourceFile) {
4203
- const importDeclaration = sourceFile.getImportDeclarations().find(
4204
- (declaration) => declaration.getNamedImports().some((named) => named.getName() === "InherentFlags")
4205
- );
4206
- const hasEventStatus = importDeclaration?.getNamedImports().some((named) => named.getName() === "EventStatus");
4207
- if (importDeclaration && !hasEventStatus) {
4208
- importDeclaration.addNamedImport("EventStatus");
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
+ );
4209
5718
  }
4210
- }
4211
- function replaceIncompleteFlag(sourceFile) {
4212
- let changed = false;
4213
- const anyOfIncomplete = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getParent()).filter(import_ts_morph3.Node.isArrayLiteralExpression).filter((array2) => {
4214
- const anyOf = array2.getParent();
4215
- const flags = anyOf?.getParent()?.getParent();
4216
- return import_ts_morph3.Node.isPropertyAssignment(anyOf) && anyOf.getName() === "anyOf" && import_ts_morph3.Node.isPropertyAssignment(flags) && flags.getName() === "flags";
4217
- });
4218
- for (const array2 of anyOfIncomplete) {
4219
- const anyOf = array2.getParentIfKindOrThrow(import_ts_morph3.SyntaxKind.PropertyAssignment);
4220
- const flagsObject = anyOf.getParentIfKindOrThrow(
4221
- import_ts_morph3.SyntaxKind.ObjectLiteralExpression
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'
4222
5722
  );
4223
- const flags = flagsObject.getParentIfKindOrThrow(
4224
- import_ts_morph3.SyntaxKind.PropertyAssignment
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`
4225
5729
  );
4226
- const query = flags.getParentIfKindOrThrow(
4227
- import_ts_morph3.SyntaxKind.ObjectLiteralExpression
5730
+ }
5731
+ const current = options.items.map(
5732
+ (item) => String((0, import_yaml2.isScalar)(item) ? item.value : item)
5733
+ );
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"
4228
5751
  );
4229
- array2.getElements().filter((element) => element.getText() === INCOMPLETE).forEach((element) => array2.removeElement(element));
4230
- if (array2.getElements().length === 0) anyOf.remove();
4231
- if (flagsObject.getProperties().length === 0) flags.remove();
4232
- if (!query.getProperty("status")) {
4233
- query.addPropertyAssignment({
4234
- name: "status",
4235
- initializer: NOTIFIED_STATUS
4236
- });
4237
- }
4238
- changed = true;
4239
5752
  }
4240
- if (changed) ensureEventStatusImport(sourceFile);
4241
- const remaining = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
4242
- return { changed, remaining };
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
+ };
4243
5760
  }
4244
- async function main5() {
4245
- const project = new import_ts_morph3.Project({
4246
- tsConfigFilePath: import_path6.default.join(process.cwd(), "tsconfig.json")
4247
- });
4248
- const sourceFiles = project.getSourceFiles().filter((sf) => !sf.getFilePath().includes("/node_modules/"));
4249
- for (const sourceFile of sourceFiles) {
4250
- const relPath = import_path6.default.relative(process.cwd(), sourceFile.getFilePath());
4251
- const { changed, remaining } = replaceIncompleteFlag(sourceFile);
4252
- if (changed) {
4253
- await sourceFile.save();
4254
- console.log(
4255
- ` [${relPath}] Replaced the incomplete flag with the NOTIFIED status`
4256
- );
4257
- }
4258
- for (const line2 of remaining) {
4259
- console.warn(
4260
- ` [${relPath}:${line2}] ${INCOMPLETE} was removed, update this reference to use the NOTIFIED status`
4261
- );
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}`);
4262
5787
  }
5788
+ throw error2;
4263
5789
  }
4264
5790
  }
4265
-
4266
- // src/migrations/index.ts
4267
- async function runUpgrade(toolkitVersion) {
4268
- const [major, minor] = toolkitVersion.split(".");
4269
- await main2();
4270
- await main3();
4271
- await main(`${major}.${minor}`);
4272
- await main5();
4273
- await main4(toolkitVersion);
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
+ ];
5801
+ }
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);
4274
5808
  }
4275
5809
 
4276
- // src/environment/index.ts
4277
- var import_fs8 = require("fs");
4278
- var import_path11 = require("path");
4279
- init_paths();
4280
- var REQUIRED_REPOSITORY_DIRECTORIES = [
4281
- ".github/workflows",
4282
- "environments",
4283
- "infrastructure"
4284
- ];
4285
- function validateRepositoryStructure(repositoryRoot = process.cwd()) {
4286
- const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
4287
- (directory) => {
4288
- try {
4289
- return !(0, import_fs8.statSync)((0, import_path11.resolve)(repositoryRoot, directory)).isDirectory();
4290
- } catch {
4291
- return true;
4292
- }
4293
- }
4294
- );
4295
- if (missingDirectories.length > 0) {
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 });
5818
+ }
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"))) {
4296
5832
  throw new Error(
4297
- `The current directory is not a valid OpenCRVS country configuration repository. Missing required director${missingDirectories.length === 1 ? "y" : "ies"}: ${missingDirectories.join(", ")}`
5833
+ "The configurator page is not built. Build the toolkit first (pnpm build in packages/toolkit)."
4298
5834
  );
4299
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
+ });
4300
5853
  }
4301
- async function runEnvironmentInit() {
4302
- validateRepositoryStructure();
4303
- assertNoOldInventoryLayout();
4304
- const { runSetupEnvironment: runSetupEnvironment2 } = await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
4305
- await runSetupEnvironment2();
4306
- }
4307
- async function runEnvironmentUpgrade() {
4308
- validateRepositoryStructure();
4309
- const { upgradeEnvironmentLayout: upgradeEnvironmentLayout2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
4310
- await upgradeEnvironmentLayout2();
4311
- }
4312
- async function runEnvironmentUpdateWorkflows() {
4313
- validateRepositoryStructure();
4314
- const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
4315
- await updateWorkflowEnvironments2();
4316
- }
4317
- async function runEnvironmentUsers() {
4318
- validateRepositoryStructure();
4319
- const { manageEnvironmentUsers: manageEnvironmentUsers2 } = await Promise.resolve().then(() => (init_users(), users_exports));
4320
- await manageEnvironmentUsers2();
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
+ }
4321
5879
  }
4322
- async function runEnvironmentSwarmToK8s() {
4323
- validateRepositoryStructure();
4324
- await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
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
+ );
4325
5928
  }
4326
5929
 
4327
5930
  // src/verify/endpoints.ts
@@ -4409,26 +6012,19 @@ async function requestStatus(url, method) {
4409
6012
  return "error";
4410
6013
  }
4411
6014
  }
4412
- function toEventTriggerConfig(value) {
4413
- if (typeof value !== "object" || value === null) {
4414
- return null;
4415
- }
4416
- const record2 = value;
4417
- if (typeof record2.id !== "string") {
4418
- return null;
4419
- }
4420
- const actions = Array.isArray(record2.actions) ? Array.from(
4421
- new Set(
4422
- record2.actions.map((action) => {
4423
- if (typeof action !== "object" || action === null) {
4424
- return null;
4425
- }
4426
- const type = action.type;
4427
- return typeof type === "string" ? type : null;
4428
- }).filter((type) => type !== null)
4429
- )
4430
- ) : [];
4431
- 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)) };
4432
6028
  }
4433
6029
  async function fetchEventConfigs(baseUrl) {
4434
6030
  try {
@@ -4438,11 +6034,8 @@ async function fetchEventConfigs(baseUrl) {
4438
6034
  if (!response.ok) {
4439
6035
  return null;
4440
6036
  }
4441
- const body = await response.json();
4442
- if (!Array.isArray(body)) {
4443
- return null;
4444
- }
4445
- 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;
4446
6039
  } catch {
4447
6040
  return null;
4448
6041
  }
@@ -4613,8 +6206,8 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4613
6206
  console.log(line(ok, endpointLabel(check), detail));
4614
6207
  }
4615
6208
  {
4616
- const path12 = `/fonts/${PROBE_SEGMENT}.ttf`;
4617
- const status = await requestStatus(`${baseUrl}${path12}`, "GET");
6209
+ const path15 = `/fonts/${PROBE_SEGMENT}.ttf`;
6210
+ const status = await requestStatus(`${baseUrl}${path15}`, "GET");
4618
6211
  const ok = status === 200 || status === 404;
4619
6212
  if (!ok) {
4620
6213
  failures++;
@@ -4629,7 +6222,7 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4629
6222
  } else {
4630
6223
  detail = `${describeStatus(status)} \u2014 unexpected`;
4631
6224
  }
4632
- console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path12}`)}`, detail));
6225
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path15}`)}`, detail));
4633
6226
  }
4634
6227
  console.log();
4635
6228
  console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
@@ -4682,13 +6275,13 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4682
6275
  line(true, pattern, `${actions.length} action(s) \u2014 all require auth`)
4683
6276
  );
4684
6277
  } else {
4685
- for (const failure of failed) {
6278
+ for (const failure2 of failed) {
4686
6279
  failures++;
4687
6280
  console.log(
4688
6281
  line(
4689
6282
  false,
4690
- `POST /trigger/events/${event.id}/actions/${failure.action}`,
4691
- securedDetail(failure.status)
6283
+ `POST /trigger/events/${event.id}/actions/${failure2.action}`,
6284
+ securedDetail(failure2.status)
4692
6285
  )
4693
6286
  );
4694
6287
  }
@@ -4721,6 +6314,7 @@ Usage: opencrvs <command>
4721
6314
 
4722
6315
  Commands:
4723
6316
  environment Manage deployment environments
6317
+ configurator Manage deployment environments in the browser
4724
6318
  upgrade Upgrade an existing environment
4725
6319
  verify-endpoints Verify the locally-running country config exposes the
4726
6320
  expected endpoints, keeps secured ones locked down and
@@ -4769,7 +6363,7 @@ Run it without changing the dependency first, e.g.
4769
6363
  Options:
4770
6364
  -h, --help Show this message.
4771
6365
  `.trim();
4772
- function main6() {
6366
+ function main8() {
4773
6367
  const command = args[0];
4774
6368
  if (!command || command === "--help" || command === "-h") {
4775
6369
  console.log(USAGE);
@@ -4778,6 +6372,8 @@ function main6() {
4778
6372
  switch (command) {
4779
6373
  case "environment":
4780
6374
  return handleEnvironment();
6375
+ case "configurator":
6376
+ return handleConfigurator();
4781
6377
  case "upgrade":
4782
6378
  return handleUpgrade();
4783
6379
  case "verify-endpoints":
@@ -4839,9 +6435,66 @@ async function runEnvironmentCommand(operation, command) {
4839
6435
  process.exit(1);
4840
6436
  }
4841
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
+ }
4842
6495
  function readToolkitVersion() {
4843
6496
  const packageJson = JSON.parse(
4844
- import_fs9.default.readFileSync(import_path12.default.join(__dirname, "..", "package.json"), "utf-8")
6497
+ import_fs9.default.readFileSync(import_path15.default.join(__dirname, "..", "package.json"), "utf-8")
4845
6498
  );
4846
6499
  return packageJson.version;
4847
6500
  }
@@ -4905,4 +6558,4 @@ async function handleVerifyEndpoints() {
4905
6558
  process.exit(1);
4906
6559
  }
4907
6560
  }
4908
- main6();
6561
+ main8();