@opencrvs/toolkit 2.1.2 → 2.2.0-rc.1a111f2

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 (163) hide show
  1. package/build.sh +2 -12
  2. package/create-countryconfig/package.json +1 -1
  3. package/dist/application-config/index.js +41 -9
  4. package/dist/authentication/index.d.ts +1 -0
  5. package/dist/authentication/index.js +30 -6
  6. package/dist/cli.js +1489 -2020
  7. package/dist/commons/api/router.d.ts +1551 -248
  8. package/dist/commons/application-config/index.d.ts +2 -2
  9. package/dist/commons/conditionals/conditionals.d.ts +3 -3
  10. package/dist/commons/conditionals/index.d.ts +1 -0
  11. package/dist/commons/conditionals/validate.d.ts +5 -0
  12. package/dist/commons/events/ActionConfig.d.ts +146 -20
  13. package/dist/commons/events/ActionDocument.d.ts +89 -0
  14. package/dist/commons/events/ActionInput.d.ts +56 -4
  15. package/dist/commons/events/ActionType.d.ts +13 -1
  16. package/dist/commons/events/AdvancedSearchConfig.d.ts +15 -0
  17. package/dist/commons/events/AuditLog.d.ts +4 -0
  18. package/dist/commons/events/CompositeFieldValue.d.ts +5 -1
  19. package/dist/commons/events/CountryConfigQueryInput.d.ts +192 -18
  20. package/dist/commons/events/Draft.d.ts +36 -1
  21. package/dist/commons/events/EventConfig.d.ts +412 -6
  22. package/dist/commons/events/EventDocument.d.ts +88 -0
  23. package/dist/commons/events/EventIndex.d.ts +43 -6
  24. package/dist/commons/events/EventMetadata.d.ts +23 -1
  25. package/dist/commons/events/EventStatus.d.ts +1 -0
  26. package/dist/commons/events/FieldConfig.d.ts +11 -1
  27. package/dist/commons/events/FieldTypeMapping.d.ts +6 -6
  28. package/dist/commons/events/Flag.d.ts +1 -7
  29. package/dist/commons/events/PlainDate.d.ts +1 -0
  30. package/dist/commons/events/WorkqueueConfig.d.ts +224 -33
  31. package/dist/commons/events/defineConfig.d.ts +7 -2
  32. package/dist/commons/events/event.d.ts +4 -1
  33. package/dist/commons/events/eventConfigValidation.d.ts +26 -1
  34. package/dist/commons/events/field.d.ts +5 -0
  35. package/dist/commons/events/index.d.ts +3 -0
  36. package/dist/commons/events/scopes.d.ts +3 -0
  37. package/dist/commons/events/state/flags.d.ts +1 -1
  38. package/dist/commons/events/state/index.d.ts +10 -2
  39. package/dist/commons/events/state/utils.d.ts +11 -1
  40. package/dist/commons/events/test.utils.d.ts +87 -6
  41. package/dist/commons/events/toNotificationForm.d.ts +17 -0
  42. package/dist/commons/events/utils.d.ts +75 -8
  43. package/dist/conditionals/index.js +16 -4
  44. package/dist/environment/custom-types.d.ts +1 -0
  45. package/dist/environment/custom-types.d.ts.map +1 -1
  46. package/dist/environment/derived-variables.d.ts +24 -4
  47. package/dist/environment/derived-variables.d.ts.map +1 -1
  48. package/dist/environment/derived-variables.js +27 -4
  49. package/dist/environment/questions.d.ts +42 -9
  50. package/dist/environment/questions.d.ts.map +1 -1
  51. package/dist/environment/questions.js +71 -48
  52. package/dist/environment/registry.d.ts +15 -0
  53. package/dist/environment/registry.d.ts.map +1 -0
  54. package/dist/environment/registry.js +112 -0
  55. package/dist/environment/setup-environment.d.ts.map +1 -1
  56. package/dist/environment/setup-environment.js +159 -35
  57. package/dist/environment/templates.d.ts.map +1 -1
  58. package/dist/events/index.js +944 -214
  59. package/dist/migrations/add-notify-config.d.ts +40 -0
  60. package/dist/migrations/add-notify-config.d.ts.map +1 -0
  61. package/dist/migrations/add-notify-config.js +249 -0
  62. package/dist/migrations/index.d.ts +9 -0
  63. package/dist/migrations/index.d.ts.map +1 -0
  64. package/dist/migrations/index.js +1306 -0
  65. package/dist/migrations/move-declaration-to-declare-action.d.ts +38 -0
  66. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -0
  67. package/dist/migrations/move-declaration-to-declare-action.js +260 -0
  68. package/dist/migrations/{v2.1 → persistent}/add-translations.d.ts +7 -1
  69. package/dist/migrations/persistent/add-translations.d.ts.map +1 -0
  70. package/dist/migrations/{v2.1 → persistent}/add-translations.js +14 -12
  71. package/dist/migrations/persistent/check-upgrade-path.d.ts +36 -0
  72. package/dist/migrations/persistent/check-upgrade-path.d.ts.map +1 -0
  73. package/dist/migrations/persistent/check-upgrade-path.js +105 -0
  74. package/dist/migrations/persistent/update-toolkit-dependency.d.ts +7 -0
  75. package/dist/migrations/persistent/update-toolkit-dependency.d.ts.map +1 -0
  76. package/dist/migrations/persistent/update-toolkit-dependency.js +77 -0
  77. package/dist/migrations/read-declaration-through-helper.d.ts +39 -0
  78. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -0
  79. package/dist/migrations/read-declaration-through-helper.js +199 -0
  80. package/dist/migrations/replace-incomplete-flag.d.ts +26 -0
  81. package/dist/migrations/replace-incomplete-flag.d.ts.map +1 -0
  82. package/dist/migrations/replace-incomplete-flag.js +126 -0
  83. package/dist/migrations/resolve-versioned-event-config.d.ts +56 -0
  84. package/dist/migrations/resolve-versioned-event-config.d.ts.map +1 -0
  85. package/dist/migrations/resolve-versioned-event-config.js +353 -0
  86. package/dist/migrations/utils.d.ts +61 -0
  87. package/dist/migrations/utils.d.ts.map +1 -0
  88. package/dist/migrations/utils.js +218 -0
  89. package/dist/notification/index.js +887 -129
  90. package/dist/scopes/index.d.ts +83 -90
  91. package/dist/scopes/index.js +26 -6
  92. package/dist/templates/charts-values/dependencies/values.yaml +3 -2
  93. package/dist/templates/charts-values/opencrvs-services/values.yaml +5 -7
  94. package/dist/templates/charts-values/traefik/values.yaml +4 -3
  95. package/dist/verify/endpoints.d.ts +11 -0
  96. package/dist/verify/endpoints.d.ts.map +1 -1
  97. package/dist/verify/endpoints.js +21 -27
  98. package/opencrvs-toolkit-2.2.0-rc.1a111f2.tgz +0 -0
  99. package/package.json +3 -2
  100. package/tsconfig.build.tsbuildinfo +1 -1
  101. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts +0 -3
  102. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts.map +0 -1
  103. package/dist/migrations/v2.1/add-explicit-correction-flags.js +0 -234
  104. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +0 -3
  105. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +0 -1
  106. package/dist/migrations/v2.1/add-recovery-link-notifications.js +0 -511
  107. package/dist/migrations/v2.1/add-translations.d.ts.map +0 -1
  108. package/dist/migrations/v2.1/enable-telemetry.d.ts +0 -3
  109. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +0 -1
  110. package/dist/migrations/v2.1/enable-telemetry.js +0 -455
  111. package/dist/migrations/v2.1/index.d.ts +0 -6
  112. package/dist/migrations/v2.1/index.d.ts.map +0 -1
  113. package/dist/migrations/v2.1/index.js +0 -2170
  114. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +0 -14
  115. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +0 -1
  116. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +0 -348
  117. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +0 -2
  118. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +0 -1
  119. package/dist/migrations/v2.1/remove-metabase-package-installs.js +0 -161
  120. package/dist/migrations/v2.1/remove-sentry.d.ts +0 -3
  121. package/dist/migrations/v2.1/remove-sentry.d.ts.map +0 -1
  122. package/dist/migrations/v2.1/remove-sentry.js +0 -354
  123. package/dist/migrations/v2.1/rename-trigger-paths.d.ts +0 -3
  124. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +0 -1
  125. package/dist/migrations/v2.1/rename-trigger-paths.js +0 -216
  126. package/dist/migrations/v2.1/template-files.d.ts +0 -8
  127. package/dist/migrations/v2.1/template-files.d.ts.map +0 -1
  128. package/dist/migrations/v2.1/template-files.js +0 -49
  129. package/dist/migrations/v2.1/upgrade-tilt.d.ts +0 -8
  130. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +0 -1
  131. package/dist/migrations/v2.1/upgrade-tilt.js +0 -139
  132. package/dist/templates/countryconfig-template/.tiltignore +0 -1
  133. package/dist/templates/countryconfig-template/Dockerfile.assets +0 -7
  134. package/dist/templates/countryconfig-template/Tiltfile +0 -112
  135. package/dist/templates/countryconfig-template/assets/README.md +0 -1
  136. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +0 -61
  137. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +0 -455
  138. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +0 -168
  139. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +0 -67
  140. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +0 -168
  141. package/dist/templates/countryconfig-template/assets/metabase/README.md +0 -34
  142. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +0 -36
  143. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +0 -46
  144. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +0 -27737
  145. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +0 -21
  146. package/dist/templates/countryconfig-template/assets/metabase/package.json +0 -13
  147. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +0 -108
  148. package/dist/templates/countryconfig-template/assets/metabase/run.sh +0 -120
  149. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +0 -40
  150. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +0 -135
  151. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +0 -108
  152. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +0 -50
  153. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +0 -35
  154. package/dist/templates/countryconfig-template/tilt/common.tilt +0 -145
  155. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +0 -15
  156. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +0 -56
  157. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +0 -21
  158. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +0 -38
  159. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +0 -17
  160. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +0 -16
  161. package/dist/templates/countryconfig-template/tilt/lib.tilt +0 -95
  162. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +0 -136
  163. package/opencrvs-toolkit-2.1.2.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_path11.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_path11.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_path11.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_path11, 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_path11 = require("path");
58
+ import_path10 = require("path");
59
59
  glob = __toESM(require("glob"));
60
- OLD_INVENTORY_DIR = (0, import_path11.join)(
60
+ OLD_INVENTORY_DIR = (0, import_path10.join)(
61
61
  "infrastructure",
62
62
  "server-setup",
63
63
  "inventory"
@@ -403,15 +403,17 @@ var init_derived_variables = __esm({
403
403
  scope: "ENVIRONMENT"
404
404
  },
405
405
  {
406
- name: "MINIO_ROOT_USER",
407
- valueLabel: "MINIO_ROOT_USER",
406
+ name: "S3_ADMIN_ACCESS_KEY",
407
+ valueLabel: "S3_ADMIN_ACCESS_KEY",
408
+ legacyValueLabel: "MINIO_ROOT_USER",
408
409
  valueType: "SECRET",
409
410
  type: "disabled",
410
411
  scope: "ENVIRONMENT"
411
412
  },
412
413
  {
413
- name: "MINIO_ROOT_PASSWORD",
414
- valueLabel: "MINIO_ROOT_PASSWORD",
414
+ name: "S3_ADMIN_SECRET_KEY",
415
+ valueLabel: "S3_ADMIN_SECRET_KEY",
416
+ legacyValueLabel: "MINIO_ROOT_PASSWORD",
415
417
  valueType: "SECRET",
416
418
  type: "disabled",
417
419
  scope: "ENVIRONMENT"
@@ -499,6 +501,27 @@ var init_derived_variables = __esm({
499
501
  valueType: "VARIABLE",
500
502
  type: "disabled",
501
503
  scope: "ENVIRONMENT"
504
+ },
505
+ {
506
+ name: "TWO_FA_ENABLED",
507
+ valueLabel: "TWO_FA_ENABLED",
508
+ valueType: "VARIABLE",
509
+ type: "disabled",
510
+ scope: "ENVIRONMENT"
511
+ },
512
+ {
513
+ name: "MONITORING_ENABLED",
514
+ valueLabel: "MONITORING_ENABLED",
515
+ valueType: "VARIABLE",
516
+ type: "disabled",
517
+ scope: "ENVIRONMENT"
518
+ },
519
+ {
520
+ name: "RUSTFS_HOST_DATA_PATH",
521
+ valueLabel: "RUSTFS_HOST_DATA_PATH",
522
+ valueType: "VARIABLE",
523
+ type: "disabled",
524
+ scope: "ENVIRONMENT"
502
525
  }
503
526
  ];
504
527
  }
@@ -518,7 +541,7 @@ function findExistingValue(name, type, scope, existingValues) {
518
541
  );
519
542
  }
520
543
  function readYamlFile(filePath) {
521
- const fileContent = import_fs9.default.readFileSync(filePath, "utf8");
544
+ const fileContent = import_fs4.default.readFileSync(filePath, "utf8");
522
545
  return yaml.load(fileContent);
523
546
  }
524
547
  function writeYamlFile(filePath, data) {
@@ -531,16 +554,16 @@ function writeYamlFile(filePath, data) {
531
554
  noRefs: true,
532
555
  sortKeys: false
533
556
  });
534
- import_fs9.default.writeFileSync(filePath, yamlContent, "utf8");
535
- } catch (error3) {
536
- throw new Error(`Failed to write inventory file: ${error3}`);
557
+ import_fs4.default.writeFileSync(filePath, yamlContent, "utf8");
558
+ } catch (error2) {
559
+ throw new Error(`Failed to write inventory file: ${error2}`);
537
560
  }
538
561
  }
539
- var import_fs9, yaml;
562
+ var import_fs4, yaml;
540
563
  var init_utils = __esm({
541
564
  "src/environment/utils.ts"() {
542
565
  "use strict";
543
- import_fs9 = __toESM(require("fs"));
566
+ import_fs4 = __toESM(require("fs"));
544
567
  yaml = __toESM(require("js-yaml"));
545
568
  }
546
569
  });
@@ -589,29 +612,29 @@ function extractWorkerNodes(data) {
589
612
  return worker_hosts;
590
613
  }
591
614
  function copyChartsValues(env, values) {
592
- const srcDir = import_path12.default.resolve(__dirname, "templates", "charts-values");
593
- const destDir = import_path12.default.resolve(process.cwd(), "environments", env);
594
- import_fs10.default.mkdirSync(destDir, { recursive: true });
615
+ const srcDir = import_path11.default.resolve(__dirname, "templates", "charts-values");
616
+ const destDir = import_path11.default.resolve(process.cwd(), "environments", env);
617
+ import_fs5.default.mkdirSync(destDir, { recursive: true });
595
618
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
596
619
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
597
620
  values["opencrvs_environment"] = env;
598
621
  function copyRecursive(src, dest) {
599
- const stat = import_fs10.default.statSync(src);
622
+ const stat = import_fs5.default.statSync(src);
600
623
  if (stat.isDirectory()) {
601
- import_fs10.default.mkdirSync(dest, { recursive: true });
602
- for (const item of import_fs10.default.readdirSync(src)) {
603
- copyRecursive(import_path12.default.join(src, item), import_path12.default.join(dest, item));
624
+ import_fs5.default.mkdirSync(dest, { recursive: true });
625
+ for (const item of import_fs5.default.readdirSync(src)) {
626
+ copyRecursive(import_path11.default.join(src, item), import_path11.default.join(dest, item));
604
627
  }
605
628
  } else {
606
- const content = import_fs10.default.readFileSync(src, "utf8");
629
+ const content = import_fs5.default.readFileSync(src, "utf8");
607
630
  const template = import_handlebars.default.compile(content);
608
631
  const updated = template(values);
609
632
  const isOverridesFile = dest.endsWith("override.yaml");
610
- if (isOverridesFile && import_fs10.default.existsSync(dest)) {
633
+ if (isOverridesFile && import_fs5.default.existsSync(dest)) {
611
634
  log(` \u21B7 Skipped existing overrides file: ${dest}`);
612
635
  return;
613
636
  }
614
- import_fs10.default.writeFileSync(dest, updated, "utf8");
637
+ import_fs5.default.writeFileSync(dest, updated, "utf8");
615
638
  log(` \u2713 Created: ${dest}`);
616
639
  }
617
640
  }
@@ -622,29 +645,32 @@ function copyChartsValues(env, values) {
622
645
  `);
623
646
  }
624
647
  function generateInventory(env, values) {
625
- const templatePath = import_path12.default.join(
648
+ const templatePath = import_path11.default.join(
626
649
  __dirname,
627
650
  "templates",
628
651
  "inventory",
629
652
  "inventory.template.yml"
630
653
  );
631
- const outputPath = import_path12.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
632
- const templateFile = import_fs10.default.readFileSync(templatePath, "utf-8");
654
+ const outputPath = import_path11.default.resolve(
655
+ process.cwd(),
656
+ getEnvironmentInventoryPath(env)
657
+ );
658
+ const templateFile = import_fs5.default.readFileSync(templatePath, "utf-8");
633
659
  const template = import_handlebars.default.compile(templateFile);
634
660
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
635
661
  const updated = template(values);
636
- import_fs10.default.mkdirSync(import_path12.default.dirname(outputPath), { recursive: true });
637
- import_fs10.default.writeFileSync(outputPath, updated);
662
+ import_fs5.default.mkdirSync(import_path11.default.dirname(outputPath), { recursive: true });
663
+ import_fs5.default.writeFileSync(outputPath, updated);
638
664
  log(`
639
665
  \u2705 Generated inventory file at ${outputPath}
640
666
  `);
641
667
  }
642
- var import_fs10, import_path12, import_handlebars;
668
+ var import_fs5, import_path11, import_handlebars;
643
669
  var init_templates = __esm({
644
670
  "src/environment/templates.ts"() {
645
671
  "use strict";
646
- import_fs10 = __toESM(require("fs"));
647
- import_path12 = __toESM(require("path"));
672
+ import_fs5 = __toESM(require("fs"));
673
+ import_path11 = __toESM(require("path"));
648
674
  init_logger();
649
675
  init_paths();
650
676
  import_handlebars = __toESM(require("handlebars"));
@@ -675,16 +701,16 @@ var update_workflows_exports = {};
675
701
  __export(update_workflows_exports, {
676
702
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
677
703
  });
678
- function isDirectory(path14) {
704
+ function isDirectory(path15) {
679
705
  try {
680
- return (0, import_fs11.statSync)(path14).isDirectory();
706
+ return (0, import_fs6.statSync)(path15).isDirectory();
681
707
  } catch {
682
708
  return false;
683
709
  }
684
710
  }
685
711
  async function extractInfrastructureNames() {
686
- const files = glob2.sync((0, import_path13.join)("environments", "*", INVENTORY_FILE_NAME));
687
- const infraEnvironments = files.map((file) => (0, import_path13.basename)((0, import_path13.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)));
688
714
  if (infraEnvironments.length === 0) {
689
715
  console.log(
690
716
  `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
@@ -697,9 +723,9 @@ async function extractInfrastructureNames() {
697
723
  async function extractEnvironmentNames() {
698
724
  const entries = await (0, import_promises.readdir)("environments");
699
725
  const environments = entries.filter((entry) => {
700
- const environmentPath = (0, import_path13.join)("environments", entry);
701
- const opencrvsServicesPath = (0, import_path13.join)(environmentPath, "opencrvs-services");
702
- return isDirectory(environmentPath) && (0, import_fs11.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
726
+ const environmentPath = (0, import_path12.join)("environments", entry);
727
+ const opencrvsServicesPath = (0, import_path12.join)(environmentPath, "opencrvs-services");
728
+ return isDirectory(environmentPath) && (0, import_fs6.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
703
729
  });
704
730
  if (environments.length === 0) {
705
731
  console.log(
@@ -724,12 +750,12 @@ function updateOptionsInYaml(content, envList) {
724
750
  async function updateWorkflows(envList, config) {
725
751
  const { workflows } = config;
726
752
  for (const workflowPath of workflows) {
727
- if (!(0, import_fs11.existsSync)(workflowPath)) {
753
+ if (!(0, import_fs6.existsSync)(workflowPath)) {
728
754
  log(` \u21B7 Skipped ${workflowPath} (not found in this repository)`);
729
755
  continue;
730
756
  }
731
757
  try {
732
- const fileContents = (0, import_fs11.readFileSync)(workflowPath, "utf8");
758
+ const fileContents = (0, import_fs6.readFileSync)(workflowPath, "utf8");
733
759
  const workflowData = yaml2.load(fileContents);
734
760
  if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
735
761
  throw new Error(
@@ -737,15 +763,15 @@ async function updateWorkflows(envList, config) {
737
763
  );
738
764
  }
739
765
  const updatedContent = updateOptionsInYaml(fileContents, envList);
740
- (0, import_fs11.writeFileSync)(workflowPath, updatedContent, "utf8");
766
+ (0, import_fs6.writeFileSync)(workflowPath, updatedContent, "utf8");
741
767
  log(` \u2713 Successfully updated ${workflowPath}`);
742
- } catch (error3) {
768
+ } catch (error2) {
743
769
  console.error(
744
770
  `
745
771
  \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`
746
772
  );
747
- console.error(`\u2717 Failed to update ${workflowPath}:`, error3);
748
- throw error3;
773
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error2);
774
+ throw error2;
749
775
  }
750
776
  }
751
777
  }
@@ -786,18 +812,18 @@ async function updateWorkflowEnvironments() {
786
812
  } else {
787
813
  log("\u2139\uFE0F No workflows were updated.");
788
814
  }
789
- } catch (error3) {
790
- console.error("\n\u274C Error updating workflows:", error3);
815
+ } catch (error2) {
816
+ console.error("\n\u274C Error updating workflows:", error2);
791
817
  process.exit(1);
792
818
  }
793
819
  }
794
- var import_promises, import_fs11, import_path13, glob2, yaml2;
820
+ var import_promises, import_fs6, import_path12, glob2, yaml2;
795
821
  var init_update_workflows = __esm({
796
822
  "src/environment/update-workflows.ts"() {
797
823
  "use strict";
798
824
  import_promises = require("fs/promises");
799
- import_fs11 = require("fs");
800
- import_path13 = require("path");
825
+ import_fs6 = require("fs");
826
+ import_path12 = require("path");
801
827
  glob2 = __toESM(require("glob"));
802
828
  yaml2 = __toESM(require("js-yaml"));
803
829
  init_logger();
@@ -808,7 +834,7 @@ var init_update_workflows = __esm({
808
834
  // src/environment/git.ts
809
835
  function getRepoInfo() {
810
836
  try {
811
- const remoteUrl = (0, import_child_process2.execSync)("git config --get remote.origin.url", {
837
+ const remoteUrl = (0, import_child_process.execSync)("git config --get remote.origin.url", {
812
838
  stdio: ["ignore", "pipe", "ignore"]
813
839
  }).toString().trim();
814
840
  const match = remoteUrl.match(/github\.com[:/](.+?)\/(.+?)(\.git)?$/);
@@ -826,11 +852,11 @@ function getRepoInfo() {
826
852
  };
827
853
  }
828
854
  }
829
- var import_child_process2;
855
+ var import_child_process;
830
856
  var init_git = __esm({
831
857
  "src/environment/git.ts"() {
832
858
  "use strict";
833
- import_child_process2 = require("child_process");
859
+ import_child_process = require("child_process");
834
860
  }
835
861
  });
836
862
 
@@ -855,7 +881,10 @@ function validateCIDRs(input4) {
855
881
  }
856
882
  return true;
857
883
  }
858
- 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;
859
888
  var init_questions = __esm({
860
889
  "src/environment/questions.ts"() {
861
890
  "use strict";
@@ -863,45 +892,59 @@ var init_questions = __esm({
863
892
  init_utils();
864
893
  init_git();
865
894
  notEmpty = (value) => value.toString().trim().length > 0 ? true : "Please enter a value";
866
- 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
+ },
867
906
  {
868
- name: "dockerhubOrganisation",
907
+ name: "registryOrganisation",
869
908
  type: "text",
870
- 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?",
871
910
  valueType: "SECRET",
872
- valueLabel: "DOCKERHUB_ACCOUNT",
911
+ valueLabel: "REGISTRY_ORGANISATION",
912
+ legacyValueLabel: "DOCKERHUB_ACCOUNT",
873
913
  validate: notEmpty,
874
- initial: process.env.DOCKER_ORGANISATION,
914
+ initial: process.env.REGISTRY_ORGANISATION,
875
915
  scope: "REPOSITORY"
876
916
  },
877
917
  {
878
- name: "dockerhubRepository",
918
+ name: "registryRepository",
879
919
  type: "text",
880
- message: "What is the name of your private Docker Hub repository?",
920
+ message: "What is the name of your private container repository?",
881
921
  valueType: "SECRET",
882
- valueLabel: "DOCKERHUB_REPO",
922
+ valueLabel: "REGISTRY_REPOSITORY",
923
+ legacyValueLabel: "DOCKERHUB_REPO",
883
924
  validate: notEmpty,
884
- initial: process.env.DOCKER_REPO,
925
+ initial: process.env.REGISTRY_REPOSITORY,
885
926
  scope: "REPOSITORY"
886
927
  },
887
928
  {
888
- name: "dockerhubUsername",
929
+ name: "registryUsername",
889
930
  type: "text",
890
- 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?",
891
932
  valueType: "SECRET",
892
- valueLabel: "DOCKER_USERNAME",
933
+ valueLabel: "REGISTRY_USERNAME",
934
+ legacyValueLabel: "DOCKER_USERNAME",
893
935
  validate: notEmpty,
894
- initial: process.env.DOCKER_USERNAME,
936
+ initial: process.env.REGISTRY_USERNAME,
895
937
  scope: "REPOSITORY"
896
938
  },
897
939
  {
898
- name: "dockerhubToken",
940
+ name: "registryToken",
899
941
  type: "text",
900
- message: "What is the token of this Docker Hub account?",
942
+ message: "What is the token of this container registry account?",
901
943
  valueType: "SECRET",
902
- valueLabel: "DOCKER_TOKEN",
944
+ valueLabel: "REGISTRY_TOKEN",
945
+ legacyValueLabel: "DOCKER_TOKEN",
903
946
  validate: notEmpty,
904
- initial: process.env.DOCKER_TOKEN,
947
+ initial: process.env.REGISTRY_TOKEN,
905
948
  scope: "REPOSITORY"
906
949
  }
907
950
  ];
@@ -923,36 +966,38 @@ var init_questions = __esm({
923
966
  scope: "REPOSITORY"
924
967
  }
925
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
+ };
926
998
  githubOtherQuestions = [
927
- {
928
- name: "githubApprovers",
929
- type: "text",
930
- message: "Please provide/update list of production approvers?",
931
- initial: process.env.GH_APPROVERS,
932
- valueType: "VARIABLE",
933
- valueLabel: "GH_APPROVERS",
934
- scope: "REPOSITORY"
935
- },
936
- {
937
- name: "approvalRequired",
938
- type: "select",
939
- message: "Would you like to enable approvals process for GitHub action workflows?",
940
- choices: [
941
- {
942
- title: "True",
943
- value: "true"
944
- },
945
- {
946
- title: "False",
947
- value: "false"
948
- }
949
- ],
950
- valueType: "VARIABLE",
951
- validate: notEmpty,
952
- valueLabel: "APPROVAL_REQUIRED",
953
- initial: process.env.APPROVAL_REQUIRED,
954
- scope: "ENVIRONMENT"
955
- }
999
+ githubApprovalRequiredQuestion,
1000
+ githubApproversQuestion
956
1001
  ];
957
1002
  githubTokenQuestion = [
958
1003
  {
@@ -1360,6 +1405,87 @@ var init_questions_helper = __esm({
1360
1405
  }
1361
1406
  });
1362
1407
 
1408
+ // src/environment/registry.ts
1409
+ function registryApiHost(registry) {
1410
+ const host = registry.trim().toLowerCase();
1411
+ return host === "docker.io" || host === "index.docker.io" ? "registry-1.docker.io" : host;
1412
+ }
1413
+ function request(url, authorization) {
1414
+ return fetch(url, {
1415
+ headers: authorization ? { Authorization: authorization } : {},
1416
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1417
+ });
1418
+ }
1419
+ function failure(registry, step, response) {
1420
+ const reason = `${registry} ${step} responded with HTTP ${response.status}`;
1421
+ switch (response.status) {
1422
+ case 401:
1423
+ case 403:
1424
+ return {
1425
+ status: "invalid-credentials",
1426
+ reason: `${reason}. Check REGISTRY_USERNAME, REGISTRY_TOKEN, REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
1427
+ };
1428
+ case 404:
1429
+ return {
1430
+ status: "repository-not-found",
1431
+ reason: `${reason}. This is also the answer for an empty repository. Check REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
1432
+ };
1433
+ default:
1434
+ return { status: "unreachable", reason };
1435
+ }
1436
+ }
1437
+ async function validateRegistryCredentials(registry, organisation, repository, username, token) {
1438
+ if (!registry || !organisation || !repository || !username || !token) {
1439
+ return {
1440
+ status: "skipped",
1441
+ reason: "Some values are kept from existing GitHub secrets, which cannot be read back"
1442
+ };
1443
+ }
1444
+ const host = registryApiHost(registry);
1445
+ const name = `${organisation}/${repository}`;
1446
+ const basic = `Basic ${Buffer.from(`${username}:${token}`).toString("base64")}`;
1447
+ try {
1448
+ const challenge = (await request(`https://${host}/v2/`, void 0)).headers.get(
1449
+ "www-authenticate"
1450
+ ) ?? "";
1451
+ const realm = challenge.match(/realm="([^"]*)"/i)?.[1];
1452
+ const service = challenge.match(/service="([^"]*)"/i)?.[1];
1453
+ let authorization = basic;
1454
+ if (/^\s*bearer/i.test(challenge) && realm) {
1455
+ const tokenUrl = new URL(realm);
1456
+ if (service) {
1457
+ tokenUrl.searchParams.set("service", service);
1458
+ }
1459
+ tokenUrl.searchParams.set("scope", `repository:${name}:pull`);
1460
+ const login = await request(tokenUrl, basic);
1461
+ if (!login.ok) {
1462
+ return failure(registry, "login", login);
1463
+ }
1464
+ const body = await login.json();
1465
+ authorization = `Bearer ${body.token ?? body.access_token}`;
1466
+ }
1467
+ const path15 = name.split("/").map(encodeURIComponent).join("/");
1468
+ const response = await request(
1469
+ `https://${host}/v2/${path15}/tags/list?n=1`,
1470
+ authorization
1471
+ );
1472
+ return response.ok ? { status: "valid" } : failure(registry, `lookup of repository ${name}`, response);
1473
+ } catch (err) {
1474
+ if (!(err instanceof Error)) {
1475
+ return { status: "unreachable", reason: String(err) };
1476
+ }
1477
+ const cause = err.cause instanceof Error ? `: ${err.cause.message}` : "";
1478
+ return { status: "unreachable", reason: `${err.message}${cause}` };
1479
+ }
1480
+ }
1481
+ var REQUEST_TIMEOUT_MS;
1482
+ var init_registry = __esm({
1483
+ "src/environment/registry.ts"() {
1484
+ "use strict";
1485
+ REQUEST_TIMEOUT_MS = 1e4;
1486
+ }
1487
+ });
1488
+
1363
1489
  // src/environment/manage-users.ts
1364
1490
  async function inquirerPrompt(name, options) {
1365
1491
  const inquirer = await import("@inquirer/prompts");
@@ -1397,13 +1523,13 @@ function getCurrentUserSSHKeys() {
1397
1523
  for (const keyFile of keyFiles) {
1398
1524
  const keyPath = path11.join(sshDir, keyFile);
1399
1525
  try {
1400
- if (fs3.existsSync(keyPath)) {
1401
- const keyContent = fs3.readFileSync(keyPath, "utf8").trim();
1526
+ if (fs5.existsSync(keyPath)) {
1527
+ const keyContent = fs5.readFileSync(keyPath, "utf8").trim();
1402
1528
  if (keyContent) {
1403
1529
  keys.push(keyContent);
1404
1530
  }
1405
1531
  }
1406
- } catch (error3) {
1532
+ } catch (error2) {
1407
1533
  continue;
1408
1534
  }
1409
1535
  }
@@ -1617,7 +1743,7 @@ async function editUser(user) {
1617
1743
  return updatedUser;
1618
1744
  }
1619
1745
  async function manageUsers(inventoryPath) {
1620
- let users = fs3.existsSync(inventoryPath) ? parseInventoryFile(inventoryPath) : [];
1746
+ let users = fs5.existsSync(inventoryPath) ? parseInventoryFile(inventoryPath) : [];
1621
1747
  if (users.length > 0) {
1622
1748
  displayUserSummary(users);
1623
1749
  }
@@ -1709,7 +1835,7 @@ async function manageUsers(inventoryPath) {
1709
1835
  message: "Save changes end exit?",
1710
1836
  default: true
1711
1837
  });
1712
- if (confirmSave && fs3.existsSync(inventoryPath)) {
1838
+ if (confirmSave && fs5.existsSync(inventoryPath)) {
1713
1839
  updateInventoryFile(inventoryPath, users);
1714
1840
  console.log(`
1715
1841
  \u2705 Changes saved to ${inventoryPath}
@@ -1736,12 +1862,12 @@ async function manageUsers(inventoryPath) {
1736
1862
  }
1737
1863
  return users;
1738
1864
  }
1739
- var os, fs3, path11, input2, select2, confirm, editor, checkbox;
1865
+ var os, fs5, path11, input2, select2, confirm, editor, checkbox;
1740
1866
  var init_manage_users = __esm({
1741
1867
  "src/environment/manage-users.ts"() {
1742
1868
  "use strict";
1743
1869
  os = __toESM(require("os"));
1744
- fs3 = __toESM(require("fs"));
1870
+ fs5 = __toESM(require("fs"));
1745
1871
  path11 = __toESM(require("path"));
1746
1872
  init_logger();
1747
1873
  init_utils();
@@ -1774,6 +1900,7 @@ async function input3(options) {
1774
1900
  function questionToPrompt({
1775
1901
  valueType,
1776
1902
  valueLabel,
1903
+ legacyValueLabel,
1777
1904
  scope,
1778
1905
  ...promptOptions
1779
1906
  }) {
@@ -1837,6 +1964,12 @@ function getAnswers(existingValues) {
1837
1964
  });
1838
1965
  });
1839
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
+ }
1840
1973
  async function promptAndStoreAnswer(questions, existingValues) {
1841
1974
  log("");
1842
1975
  const processedQuestions = questions.flatMap((question) => {
@@ -1854,14 +1987,22 @@ async function promptAndStoreAnswer(questions, existingValues) {
1854
1987
  questionWithVariableLabel.scope,
1855
1988
  existingValues
1856
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
+ }
1857
2005
  if (existingVariable) {
1858
- let initial_value = existingVariable.value;
1859
- if (questionWithVariableLabel.type === "select" && Array.isArray(questionWithVariableLabel.choices)) {
1860
- initial_value = getIndexFromChoices(
1861
- questionWithVariableLabel.choices,
1862
- existingVariable.value
1863
- );
1864
- }
1865
2006
  return [
1866
2007
  {
1867
2008
  name: "overWrite" + questionWithVariableLabel.name,
@@ -1876,7 +2017,10 @@ async function promptAndStoreAnswer(questions, existingValues) {
1876
2017
  {
1877
2018
  ...questionWithVariableLabel,
1878
2019
  type: (prev) => prev ? questionWithVariableLabel.type : null,
1879
- initial: initial_value
2020
+ initial: getInitialValue(
2021
+ questionWithVariableLabel,
2022
+ existingVariable
2023
+ )
1880
2024
  }
1881
2025
  ];
1882
2026
  }
@@ -1888,6 +2032,32 @@ async function promptAndStoreAnswer(questions, existingValues) {
1888
2032
  questionWithVariableLabel.scope,
1889
2033
  existingValues
1890
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
+ }
1891
2061
  if (existingSecret) {
1892
2062
  return [
1893
2063
  {
@@ -1927,6 +2097,47 @@ async function promptAndStoreAnswer(questions, existingValues) {
1927
2097
  ]);
1928
2098
  return { ...Object.fromEntries(existingValuesForQuestions), ...result };
1929
2099
  }
2100
+ function defineIfMissing(existingValues, name, type, scope, newValue) {
2101
+ if (findExistingValue(name, type, scope, existingValues)) {
2102
+ return null;
2103
+ }
2104
+ const legacyName = ALL_QUESTIONS.find(
2105
+ (question) => question.valueLabel === name && question.valueType === type && question.scope === scope
2106
+ )?.legacyValueLabel;
2107
+ if (legacyName && findExistingValue(legacyName, type, scope, existingValues)) {
2108
+ log(
2109
+ import_kleur4.default.bold().green("\u2714"),
2110
+ import_kleur4.default.bold().yellow(
2111
+ `${legacyName} exists, the secrets migration workflow copies it to ${name}`
2112
+ )
2113
+ );
2114
+ return null;
2115
+ }
2116
+ return process.env[name] || newValue;
2117
+ }
2118
+ async function promptAndValidateRegistry(existingValues) {
2119
+ const answers = await promptAndStoreAnswer(registryQuestions, existingValues);
2120
+ const result = await validateRegistryCredentials(
2121
+ answers.registryHost,
2122
+ answers.registryOrganisation,
2123
+ answers.registryRepository,
2124
+ answers.registryUsername,
2125
+ answers.registryToken
2126
+ );
2127
+ if (result.status === "valid" || result.status === "skipped") {
2128
+ return;
2129
+ }
2130
+ error(`
2131
+ ${result.status}: ${result.reason || "Generic error"}
2132
+ `);
2133
+ const continueNotValidated = await confirm2({
2134
+ message: "Container registry credentials are not validated. Continue anyway?",
2135
+ default: false
2136
+ });
2137
+ if (!continueNotValidated) {
2138
+ process.exit(1);
2139
+ }
2140
+ }
1930
2141
  async function runSetupEnvironment() {
1931
2142
  log("\n", import_kleur4.default.bold().underline("Github"), "\n");
1932
2143
  const { githubOrganisation, githubRepository } = await (0, import_prompts2.default)(
@@ -1990,16 +2201,6 @@ async function runSetupEnvironment() {
1990
2201
  ]
1991
2202
  });
1992
2203
  }
1993
- log("\n", import_kleur4.default.bold().underline("Two-factor authentication (2FA)"));
1994
- const two_fa_enabled = await confirm2({
1995
- message: "Enable two-factor authentication (2FA)? This should be enabled for any environment that hosts PII data.",
1996
- default: process.env.TWO_FA_ENABLED ? process.env.TWO_FA_ENABLED === "true" : environment_type === "production"
1997
- });
1998
- if (!two_fa_enabled && ["production", "staging"].includes(environment_type)) {
1999
- warn(
2000
- "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."
2001
- );
2002
- }
2003
2204
  const environment_exists = existingEnvironments.map((e) => e.trim()).includes(environment);
2004
2205
  if (!environment) {
2005
2206
  process.exit(1);
@@ -2061,10 +2262,42 @@ async function runSetupEnvironment() {
2061
2262
  "WARNING! You are setting up a production environment.\n Make sure you have read the deployment guide carefully before proceeding.\n"
2062
2263
  )
2063
2264
  );
2064
- await promptAndStoreAnswer(githubOtherQuestions, existingValues);
2065
2265
  }
2066
- log("\n", import_kleur4.default.bold().underline("Docker Hub"));
2067
- await promptAndStoreAnswer(dockerhubQuestions, existingValues);
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);
2281
+ }
2282
+ log("\n", import_kleur4.default.bold().underline("Two-factor authentication (2FA)"));
2283
+ const existingTwoFaEnabled = findExistingValue(
2284
+ "TWO_FA_ENABLED",
2285
+ "VARIABLE",
2286
+ "ENVIRONMENT",
2287
+ existingValues
2288
+ );
2289
+ const twoFaDefault = process.env.TWO_FA_ENABLED || existingTwoFaEnabled?.value;
2290
+ const two_fa_enabled = await confirm2({
2291
+ message: "Enable two-factor authentication (2FA)? This should be enabled for any environment that hosts PII data.",
2292
+ default: twoFaDefault ? twoFaDefault === "true" : environment_type === "production"
2293
+ });
2294
+ if (!two_fa_enabled && ["production", "staging"].includes(environment_type)) {
2295
+ warn(
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."
2297
+ );
2298
+ }
2299
+ log("\n", import_kleur4.default.bold().underline("Container registry"));
2300
+ await promptAndValidateRegistry(existingValues);
2068
2301
  log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
2069
2302
  const infrastructure = await promptAndStoreAnswer(
2070
2303
  infrastructureQuestions,
@@ -2156,6 +2389,13 @@ async function runSetupEnvironment() {
2156
2389
  );
2157
2390
  }
2158
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");
2159
2399
  let backupHost = findExistingValue("BACKUP_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2160
2400
  let backupType = "";
2161
2401
  let restoreEnvironmentName = findExistingValue(
@@ -2248,7 +2488,22 @@ async function runSetupEnvironment() {
2248
2488
  log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2249
2489
  }
2250
2490
  log("\n", import_kleur4.default.bold().underline("Monitoring"));
2251
- await promptAndStoreAnswer(databaseAndMonitoringQuestions, existingValues);
2491
+ const existingMonitoringEnabled = findExistingValue(
2492
+ "MONITORING_ENABLED",
2493
+ "VARIABLE",
2494
+ "ENVIRONMENT",
2495
+ existingValues
2496
+ );
2497
+ const monitoringDefault = process.env.MONITORING_ENABLED || existingMonitoringEnabled?.value;
2498
+ const monitoring_enabled = await confirm2({
2499
+ message: "Enable monitoring (Kibana, APM, Filebeat, Metricbeat, Elastalert, OpenTelemetry Collector and tracing)? Disable it if this environment does not need its own monitoring stack.",
2500
+ default: monitoringDefault ? monitoringDefault === "true" : true
2501
+ });
2502
+ if (monitoring_enabled) {
2503
+ await promptAndStoreAnswer(databaseAndMonitoringQuestions, existingValues);
2504
+ } else {
2505
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Monitoring is disabled"));
2506
+ }
2252
2507
  const sentryDSNExists = findExistingValue(
2253
2508
  "SENTRY_DSN",
2254
2509
  "SECRET",
@@ -2279,9 +2534,7 @@ async function runSetupEnvironment() {
2279
2534
  return { ...acc, ...answer };
2280
2535
  });
2281
2536
  const answerOrExisting = (variable, existingValue, fn) => fn(variable || existingValue?.value) || "";
2282
- function findExistingOrDefine(name, type, scope, newValue) {
2283
- return findExistingValue(name, type, scope, existingValues) ? null : process.env[name] || newValue;
2284
- }
2537
+ const findExistingOrDefine = (name, type, scope, newValue) => defineIfMissing(existingValues, name, type, scope, newValue);
2285
2538
  const derivedUpdates = [
2286
2539
  {
2287
2540
  name: "GH_ENCRYPTION_PASSWORD",
@@ -2318,6 +2571,28 @@ async function runSetupEnvironment() {
2318
2571
  ),
2319
2572
  scope: "ENVIRONMENT"
2320
2573
  });
2574
+ derivedUpdates.push({
2575
+ name: "TWO_FA_ENABLED",
2576
+ type: "VARIABLE",
2577
+ didExist: existingTwoFaEnabled,
2578
+ // Always stored, so the next run defaults to the current answer
2579
+ value: two_fa_enabled ? "true" : "false",
2580
+ scope: "ENVIRONMENT"
2581
+ });
2582
+ derivedUpdates.push({
2583
+ name: "MONITORING_ENABLED",
2584
+ type: "VARIABLE",
2585
+ didExist: existingMonitoringEnabled,
2586
+ value: monitoring_enabled ? "true" : "false",
2587
+ scope: "ENVIRONMENT"
2588
+ });
2589
+ derivedUpdates.push({
2590
+ name: "RUSTFS_HOST_DATA_PATH",
2591
+ type: "VARIABLE",
2592
+ didExist: existingRustfsHostDataPath,
2593
+ value: rustfs_host_data_path,
2594
+ scope: "ENVIRONMENT"
2595
+ });
2321
2596
  derivedUpdates.push(...ssl_answers);
2322
2597
  if (configureBackup) {
2323
2598
  derivedUpdates.push({
@@ -2374,16 +2649,16 @@ async function runSetupEnvironment() {
2374
2649
  scope: "ENVIRONMENT"
2375
2650
  },
2376
2651
  {
2377
- name: "MINIO_ROOT_USER",
2652
+ name: "S3_ADMIN_ACCESS_KEY",
2378
2653
  type: "SECRET",
2379
2654
  didExist: findExistingValue(
2380
- "MINIO_ROOT_USER",
2655
+ "S3_ADMIN_ACCESS_KEY",
2381
2656
  "SECRET",
2382
2657
  "ENVIRONMENT",
2383
2658
  existingValues
2384
2659
  ),
2385
2660
  value: findExistingOrDefine(
2386
- "MINIO_ROOT_USER",
2661
+ "S3_ADMIN_ACCESS_KEY",
2387
2662
  "SECRET",
2388
2663
  "ENVIRONMENT",
2389
2664
  generateLongPassword()
@@ -2391,16 +2666,16 @@ async function runSetupEnvironment() {
2391
2666
  scope: "ENVIRONMENT"
2392
2667
  },
2393
2668
  {
2394
- name: "MINIO_ROOT_PASSWORD",
2669
+ name: "S3_ADMIN_SECRET_KEY",
2395
2670
  type: "SECRET",
2396
2671
  didExist: findExistingValue(
2397
- "MINIO_ROOT_PASSWORD",
2672
+ "S3_ADMIN_SECRET_KEY",
2398
2673
  "SECRET",
2399
2674
  "ENVIRONMENT",
2400
2675
  existingValues
2401
2676
  ),
2402
2677
  value: findExistingOrDefine(
2403
- "MINIO_ROOT_PASSWORD",
2678
+ "S3_ADMIN_SECRET_KEY",
2404
2679
  "SECRET",
2405
2680
  "ENVIRONMENT",
2406
2681
  generateLongPassword()
@@ -2664,7 +2939,7 @@ async function runSetupEnvironment() {
2664
2939
  );
2665
2940
  const unknownVariables = existingValues.filter((value) => {
2666
2941
  return !ALL_QUESTIONS.find(
2667
- (question) => question.valueLabel === value.name && question.valueType === value.type && question.scope === value.scope
2942
+ (question) => (question.valueLabel === value.name || question.legacyValueLabel === value.name) && question.valueType === value.type && question.scope === value.scope
2668
2943
  );
2669
2944
  });
2670
2945
  log("");
@@ -2868,6 +3143,8 @@ async function runSetupEnvironment() {
2868
3143
  env: environment,
2869
3144
  environment_type,
2870
3145
  two_fa_enabled,
3146
+ monitoring_enabled,
3147
+ rustfs_host_data_path,
2871
3148
  traefik_mode: traefikConfOption,
2872
3149
  restore_enabled: restoreEnvironmentName ? true : false,
2873
3150
  restore_environment_name: restoreEnvironmentName || "",
@@ -2933,6 +3210,7 @@ var init_setup_environment = __esm({
2933
3210
  init_questions();
2934
3211
  init_editor_questions();
2935
3212
  init_questions_helper();
3213
+ init_registry();
2936
3214
  init_manage_users();
2937
3215
  init_paths();
2938
3216
  ALL_QUESTIONS = [];
@@ -2940,7 +3218,7 @@ var init_setup_environment = __esm({
2940
3218
  ALL_QUESTIONS.push(
2941
3219
  ...githubTokenQuestion,
2942
3220
  ...githubOtherQuestions,
2943
- ...dockerhubQuestions,
3221
+ ...registryQuestions,
2944
3222
  ...diskQuestions,
2945
3223
  ...infrastructureQuestions,
2946
3224
  ...backupQuestions,
@@ -2960,17 +3238,17 @@ __export(upgrade_exports, {
2960
3238
  upgradeEnvironmentLayout: () => upgradeEnvironmentLayout
2961
3239
  });
2962
3240
  function moveFileIfDestinationMissing(sourcePath, destinationPath) {
2963
- if (!(0, import_fs12.existsSync)(sourcePath)) {
3241
+ if (!(0, import_fs7.existsSync)(sourcePath)) {
2964
3242
  return false;
2965
3243
  }
2966
- if ((0, import_fs12.existsSync)(destinationPath)) {
3244
+ if ((0, import_fs7.existsSync)(destinationPath)) {
2967
3245
  warn(
2968
3246
  `\u26A0\uFE0F Skipped ${sourcePath}; destination already exists at ${destinationPath}`
2969
3247
  );
2970
3248
  return false;
2971
3249
  }
2972
- (0, import_fs12.mkdirSync)((0, import_path14.dirname)(destinationPath), { recursive: true });
2973
- (0, import_fs12.renameSync)(sourcePath, destinationPath);
3250
+ (0, import_fs7.mkdirSync)((0, import_path13.dirname)(destinationPath), { recursive: true });
3251
+ (0, import_fs7.renameSync)(sourcePath, destinationPath);
2974
3252
  log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
2975
3253
  return true;
2976
3254
  }
@@ -2990,8 +3268,8 @@ function migrateInventoryFiles() {
2990
3268
  ) || didMoveInventory;
2991
3269
  }
2992
3270
  try {
2993
- if ((0, import_fs12.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs12.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
2994
- (0, import_fs12.rmdirSync)(OLD_INVENTORY_DIR);
3271
+ if ((0, import_fs7.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs7.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
3272
+ (0, import_fs7.rmdirSync)(OLD_INVENTORY_DIR);
2995
3273
  log(` \u2713 Removed empty ${OLD_INVENTORY_DIR}`);
2996
3274
  }
2997
3275
  } catch {
@@ -3009,12 +3287,12 @@ async function upgradeEnvironmentLayout() {
3009
3287
  }
3010
3288
  log("\nCommit changes into git after upgrade");
3011
3289
  }
3012
- var import_fs12, import_path14, import_kleur5;
3290
+ var import_fs7, import_path13, import_kleur5;
3013
3291
  var init_upgrade = __esm({
3014
3292
  "src/environment/upgrade.ts"() {
3015
3293
  "use strict";
3016
- import_fs12 = require("fs");
3017
- import_path14 = require("path");
3294
+ import_fs7 = require("fs");
3295
+ import_path13 = require("path");
3018
3296
  import_kleur5 = __toESM(require("kleur"));
3019
3297
  init_logger();
3020
3298
  init_paths();
@@ -3032,16 +3310,16 @@ async function select4(options) {
3032
3310
  return inquirer.select(options);
3033
3311
  }
3034
3312
  async function selectInventoryFile(dirPath = "./environments") {
3035
- if (!fs4.existsSync(dirPath)) {
3313
+ if (!fs6.existsSync(dirPath)) {
3036
3314
  warn(`\u26A0\uFE0F No environment configuration directory found at ${dirPath}`);
3037
3315
  warn(
3038
3316
  "Hint: If this is a new infrastructure repository, run `opencrvs environment init` first."
3039
3317
  );
3040
3318
  return null;
3041
3319
  }
3042
- const environments = fs4.readdirSync(dirPath).filter((entry) => {
3320
+ const environments = fs6.readdirSync(dirPath).filter((entry) => {
3043
3321
  const filePath = path12.join(dirPath, entry);
3044
- return fs4.statSync(filePath).isDirectory() && fs4.existsSync(getEnvironmentInventoryPath(entry));
3322
+ return fs6.statSync(filePath).isDirectory() && fs6.existsSync(getEnvironmentInventoryPath(entry));
3045
3323
  }).sort();
3046
3324
  if (environments.length === 0) {
3047
3325
  warn(`\u26A0\uFE0F No environment configuration files found at ${dirPath}`);
@@ -3068,11 +3346,11 @@ async function manageEnvironmentUsers() {
3068
3346
  }
3069
3347
  await manageUsers(inventory_file);
3070
3348
  }
3071
- var fs4, path12, import_kleur6;
3349
+ var fs6, path12, import_kleur6;
3072
3350
  var init_users = __esm({
3073
3351
  "src/environment/users.ts"() {
3074
3352
  "use strict";
3075
- fs4 = __toESM(require("fs"));
3353
+ fs6 = __toESM(require("fs"));
3076
3354
  path12 = __toESM(require("path"));
3077
3355
  import_kleur6 = __toESM(require("kleur"));
3078
3356
  init_manage_users();
@@ -3260,187 +3538,12 @@ var init_swarm_to_k8s = __esm({
3260
3538
  }
3261
3539
  });
3262
3540
 
3263
- // src/migrations/v2.1/add-explicit-correction-flags.ts
3264
- var import_ts_morph = require("ts-morph");
3265
- var import_path = __toESM(require("path"));
3266
- var DEFINE_CONFIG_NAME = "defineConfig";
3267
- var ACTIONS_PROPERTY_NAME = "actions";
3268
- var TYPE_PROPERTY_NAME = "type";
3269
- var FLAGS_PROPERTY_NAME = "flags";
3270
- var CONDITIONALS_PROPERTY_NAME = "conditionals";
3271
- var ACTION_TYPE_ENUM_NAME = "ActionType";
3272
- var REQUEST_CORRECTION_TYPE = "REQUEST_CORRECTION";
3273
- var CORRECTION_ACTIONS_TO_ADD = [
3274
- {
3275
- actionType: "APPROVE_CORRECTION",
3276
- labelId: "v2.events.correction.approve.label",
3277
- defaultMessage: "Approve correction",
3278
- description: "Label for the approve correction action"
3279
- },
3280
- {
3281
- actionType: "REJECT_CORRECTION",
3282
- labelId: "v2.events.correction.reject.label",
3283
- defaultMessage: "Reject correction",
3284
- description: "Label for the reject correction action"
3285
- }
3286
- ];
3287
- function isActionOfType(obj, typeName) {
3288
- const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME);
3289
- if (!typeProperty || !import_ts_morph.Node.isPropertyAssignment(typeProperty)) return false;
3290
- const typeInit = typeProperty.getInitializer();
3291
- if (!typeInit) return false;
3292
- if (import_ts_morph.Node.isPropertyAccessExpression(typeInit)) {
3293
- return typeInit.getExpression().getText() === ACTION_TYPE_ENUM_NAME && typeInit.getName() === typeName;
3294
- }
3295
- if (import_ts_morph.Node.isStringLiteral(typeInit)) {
3296
- return typeInit.getLiteralValue() === typeName;
3297
- }
3298
- return false;
3299
- }
3300
- function getTypeInitializerStyle(obj) {
3301
- const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME);
3302
- if (typeProperty && import_ts_morph.Node.isPropertyAssignment(typeProperty)) {
3303
- const typeInit = typeProperty.getInitializer();
3304
- if (typeInit && import_ts_morph.Node.isPropertyAccessExpression(typeInit)) return "enum";
3305
- }
3306
- return "string";
3307
- }
3308
- function getNonEmptyArrayPropertyText(obj, propName) {
3309
- const prop = obj.getProperty(propName);
3310
- if (!prop || !import_ts_morph.Node.isPropertyAssignment(prop)) return void 0;
3311
- const init = prop.getInitializer();
3312
- if (!init || !import_ts_morph.Node.isArrayLiteralExpression(init)) return void 0;
3313
- if (init.getElements().length === 0) return void 0;
3314
- return init.getText();
3315
- }
3316
- function buildCorrectionActionText(spec, typeStyle, flagsText, conditionalsText) {
3317
- const typeText = typeStyle === "enum" ? `${ACTION_TYPE_ENUM_NAME}.${spec.actionType}` : `'${spec.actionType}'`;
3318
- const lines = [
3319
- `type: ${typeText}`,
3320
- `label: {
3321
- id: '${spec.labelId}',
3322
- defaultMessage: '${spec.defaultMessage}',
3323
- description: '${spec.description}'
3324
- }`
3325
- ];
3326
- if (flagsText) {
3327
- lines.push(`${FLAGS_PROPERTY_NAME}: ${flagsText}`);
3328
- }
3329
- if (conditionalsText) {
3330
- lines.push(`${CONDITIONALS_PROPERTY_NAME}: ${conditionalsText}`);
3331
- }
3332
- return `{
3333
- ${lines.join(",\n ")}
3334
- }`;
3335
- }
3336
- function processFile(filePath, project) {
3337
- const sourceFile = project.getSourceFile(filePath);
3338
- if (!sourceFile) return 0;
3339
- let changes = 0;
3340
- const relPath = import_path.default.relative(process.cwd(), filePath);
3341
- const callExpressions = sourceFile.getDescendantsOfKind(
3342
- import_ts_morph.SyntaxKind.CallExpression
3343
- );
3344
- for (const call of callExpressions) {
3345
- const expression = call.getExpression();
3346
- if (!import_ts_morph.Node.isIdentifier(expression) || expression.getText() !== DEFINE_CONFIG_NAME) {
3347
- continue;
3348
- }
3349
- const args2 = call.getArguments();
3350
- if (args2.length === 0) continue;
3351
- const configArg = args2[0];
3352
- if (!import_ts_morph.Node.isObjectLiteralExpression(configArg)) continue;
3353
- const actionsProperty = configArg.getProperty(ACTIONS_PROPERTY_NAME);
3354
- if (!actionsProperty || !import_ts_morph.Node.isPropertyAssignment(actionsProperty))
3355
- continue;
3356
- const actionsInitializer = actionsProperty.getInitializer();
3357
- if (!actionsInitializer || !import_ts_morph.Node.isArrayLiteralExpression(actionsInitializer))
3358
- continue;
3359
- const elements = actionsInitializer.getElements();
3360
- const requestCorrectionIndex = elements.findIndex(
3361
- (el) => import_ts_morph.Node.isObjectLiteralExpression(el) && isActionOfType(el, REQUEST_CORRECTION_TYPE)
3362
- );
3363
- if (requestCorrectionIndex === -1) continue;
3364
- const requestCorrection = elements[requestCorrectionIndex];
3365
- const flagsText = getNonEmptyArrayPropertyText(
3366
- requestCorrection,
3367
- FLAGS_PROPERTY_NAME
3368
- );
3369
- const conditionalsText = getNonEmptyArrayPropertyText(
3370
- requestCorrection,
3371
- CONDITIONALS_PROPERTY_NAME
3372
- );
3373
- if (!flagsText && !conditionalsText) continue;
3374
- const typeStyle = getTypeInitializerStyle(requestCorrection);
3375
- let insertAt = requestCorrectionIndex + 1;
3376
- for (const spec of CORRECTION_ACTIONS_TO_ADD) {
3377
- const alreadyPresent = actionsInitializer.getElements().some(
3378
- (el) => import_ts_morph.Node.isObjectLiteralExpression(el) && isActionOfType(el, spec.actionType)
3379
- );
3380
- if (alreadyPresent) continue;
3381
- const text = buildCorrectionActionText(
3382
- spec,
3383
- typeStyle,
3384
- flagsText,
3385
- conditionalsText
3386
- );
3387
- actionsInitializer.insertElement(insertAt, text);
3388
- insertAt++;
3389
- changes++;
3390
- console.log(
3391
- ` [${relPath}] Added ${spec.actionType} action carrying over REQUEST_CORRECTION's flags/conditionals`
3392
- );
3393
- }
3394
- }
3395
- return changes;
3396
- }
3397
- async function main() {
3398
- const srcDir = import_path.default.join(process.cwd(), "src");
3399
- console.log(`Scanning for defineConfig calls in: ${srcDir}
3400
- `);
3401
- const project = new import_ts_morph.Project({
3402
- tsConfigFilePath: import_path.default.resolve(srcDir, "../tsconfig.json"),
3403
- skipAddingFilesFromTsConfig: false
3404
- });
3405
- const sourceFiles = project.getSourceFiles().filter((sf) => {
3406
- const fp = sf.getFilePath();
3407
- return fp.includes("/src/") && !fp.includes("/node_modules/");
3408
- });
3409
- console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3410
- `);
3411
- let totalChanges = 0;
3412
- const modifiedFiles = [];
3413
- for (const sourceFile of sourceFiles) {
3414
- const filePath = sourceFile.getFilePath();
3415
- const changes = processFile(filePath, project);
3416
- if (changes > 0) {
3417
- totalChanges += changes;
3418
- modifiedFiles.push(filePath);
3419
- }
3420
- }
3421
- if (modifiedFiles.length === 0) {
3422
- console.log(
3423
- "No REQUEST_CORRECTION actions with flags/conditionals found. Nothing to do."
3424
- );
3425
- return;
3426
- }
3427
- console.log(`
3428
- Saving ${modifiedFiles.length} modified file(s)...`);
3429
- for (const filePath of modifiedFiles) {
3430
- const sourceFile = project.getSourceFileOrThrow(filePath);
3431
- await sourceFile.save();
3432
- console.log(` Saved: ${import_path.default.relative(process.cwd(), filePath)}`);
3433
- }
3434
- console.log(
3435
- `
3436
- Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.length} file(s).`
3437
- );
3438
- }
3541
+ // src/cli.ts
3542
+ var import_fs9 = __toESM(require("fs"));
3543
+ var import_path15 = __toESM(require("path"));
3439
3544
 
3440
- // src/migrations/v2.1/add-recovery-link-notifications.ts
3441
- var import_ts_morph2 = require("ts-morph");
3442
- var import_fs2 = require("fs");
3443
- var import_path2 = __toESM(require("path"));
3545
+ // src/migrations/persistent/add-translations.ts
3546
+ var import_path = __toESM(require("path"));
3444
3547
 
3445
3548
  // src/csv.ts
3446
3549
  var import_fs = require("fs");
@@ -3482,20 +3585,20 @@ function idOf(line2) {
3482
3585
  const comma = line2.indexOf(",");
3483
3586
  return comma === -1 ? line2 : line2.slice(0, comma);
3484
3587
  }
3485
- function readCsvFile(path14) {
3486
- if (!(0, import_fs.existsSync)(path14)) {
3588
+ function readCsvFile(path15) {
3589
+ if (!(0, import_fs.existsSync)(path15)) {
3487
3590
  return void 0;
3488
3591
  }
3489
- const contents = (0, import_fs.readFileSync)(path14, "utf8");
3592
+ const contents = (0, import_fs.readFileSync)(path15, "utf8");
3490
3593
  const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3491
3594
  const trailingNewline = /\r?\n$/.test(contents);
3492
3595
  const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3493
3596
  const body = lines.slice(1).filter((line2) => line2 !== "");
3494
3597
  return { header: lines[0], body, newline, trailingNewline };
3495
3598
  }
3496
- function writeCsvFile(path14, file) {
3599
+ function writeCsvFile(path15, file) {
3497
3600
  (0, import_fs.writeFileSync)(
3498
- path14,
3601
+ path15,
3499
3602
  [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3500
3603
  );
3501
3604
  }
@@ -3509,464 +3612,17 @@ function addRows(file, rows) {
3509
3612
  if (file.body.some((line2) => idOf(line2) === id)) {
3510
3613
  continue;
3511
3614
  }
3512
- const insertAt = isSorted ? file.body.findIndex((line2) => idOf(line2) > id) : -1;
3513
- if (insertAt === -1) {
3615
+ const insertAt2 = isSorted ? file.body.findIndex((line2) => idOf(line2) > id) : -1;
3616
+ if (insertAt2 === -1) {
3514
3617
  file.body.push(row);
3515
3618
  } else {
3516
- file.body.splice(insertAt, 0, row);
3619
+ file.body.splice(insertAt2, 0, row);
3517
3620
  }
3518
3621
  added.push(id);
3519
3622
  }
3520
3623
  return added;
3521
3624
  }
3522
3625
 
3523
- // src/migrations/v2.1/add-recovery-link-notifications.ts
3524
- var EMAIL_TEMPLATES_FILE = "src/api/notification/email-templates/index.ts";
3525
- var SMS_SERVICE_FILE = "src/api/notification/sms-service.ts";
3526
- var HANDLER_FILE = "src/api/notification/handler.ts";
3527
- var ROUTES_FILE = "src/config/routes/userNotificationRoutes.ts";
3528
- var EMAIL_TEMPLATE_DIR = "src/api/notification/email-templates/other";
3529
- var NOTIFICATION_CSV = "src/translations/notification.csv";
3530
- var LOGIN_CSV = "src/translations/login.csv";
3531
- var TRIGGER_VARIABLE_OBJECT = "TriggerVariable";
3532
- var TEMPLATES_OBJECT = "templates";
3533
- var OTHER_TEMPLATES_OBJECT = "otherTemplates";
3534
- var TRIGGER_TO_SMS_TEMPLATE_OBJECT = "TriggerToSMSTemplate";
3535
- var CONVERT_PAYLOAD_FUNCTION = "convertPayloadToVariable";
3536
- var ROUTES_FUNCTION = "getUserNotificationRoutes";
3537
- var RECOVERY_EVENTS = [
3538
- {
3539
- id: "password-reset-link",
3540
- constant: "PASSWORD_RESET_LINK",
3541
- smsTemplate: "resetPasswordLinkNotification",
3542
- emailSubject: "Reset your password",
3543
- routeDescription: "Handles notification for password reset recovery link",
3544
- heading: "Reset your password",
3545
- reason: "Someone asked to reset the password for your {{applicationName}}\n account.",
3546
- linkLabel: "Reset your password"
3547
- },
3548
- {
3549
- id: "username-reminder-link",
3550
- constant: "USERNAME_REMINDER_LINK",
3551
- smsTemplate: "retrieveUsernameLinkNotification",
3552
- emailSubject: "Retrieve your username",
3553
- routeDescription: "Handles notification for username reminder recovery link",
3554
- heading: "Retrieve your username",
3555
- reason: "Someone asked for a reminder of the username for your\n {{applicationName}} account.",
3556
- linkLabel: "Retrieve your username"
3557
- }
3558
- ];
3559
- var NOTIFICATION_CSV_ROWS = [
3560
- `resetPasswordLinkNotification,The SMS message that is sent to a user containing a self-service password reset link,{{applicationName}}: reset your password using this link. It expires in 1 hour. {{{recoveryURL}}},{{applicationName}} : r\xE9initialisez votre mot de passe \xE0 l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`,
3561
- `retrieveUsernameLinkNotification,The SMS message that is sent to a user containing a self-service username retrieval link,{{applicationName}}: retrieve your username using this link. It expires in 1 hour. {{{recoveryURL}}},{{applicationName}} : r\xE9cup\xE9rez votre nom d'utilisateur \xE0 l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`
3562
- ];
3563
- var LOGIN_CSV_ROWS = [
3564
- `buttons.backToLogin,"Label used to leave a screen that is waiting on an emailed link, where logging in is not yet possible",Back to login,Retour \xE0 la connexion`,
3565
- `resetCredentials.recoveryInstructionsSent.body,"Body message for the recovery instructions sent page. Must not assert delivery, since the account may not exist.","If we found an account, you'll receive instructions for {forgottenItem, select, username {retrieving your username} other {resetting your password}}. The link expires in 1 hour.","Si nous trouvons un compte correspondant, vous recevrez les instructions pour {forgottenItem, select, username {r\xE9cup\xE9rer votre nom d'utilisateur} other {r\xE9initialiser votre mot de passe}}. Le lien expire dans 1 heure."`,
3566
- `resetCredentials.recoveryInstructionsSent.title.email,Title for the recovery instructions sent page when notifications are delivered by email,Check your email,V\xE9rifiez votre e-mail`,
3567
- `resetCredentials.recoveryInstructionsSent.title.phone,Title for the recovery instructions sent page when notifications are delivered by SMS,Check your phone,V\xE9rifiez votre t\xE9l\xE9phone`,
3568
- `resetCredentials.recoveryLinkLanding.expired.body,"Body shown when a recovery link is invalid, expired, or already used. Must not reveal whether the underlying account exists.",This link is no longer valid. Request a new one to continue.,Ce lien n'est plus valide. Veuillez en demander un nouveau pour continuer.`,
3569
- `resetCredentials.recoveryLinkLanding.expired.link,Link back to the forgotten item form shown on an expired/invalid recovery link,Start again,Recommencer`,
3570
- `resetCredentials.recoveryLinkLanding.expired.title,"Title shown when a recovery link is invalid, expired, or already used",This link has expired,Ce lien a expir\xE9`
3571
- ];
3572
- var skipped = [];
3573
- function warnSkipped(message) {
3574
- skipped.push(message);
3575
- console.warn(` \u26A0\uFE0F ${message}`);
3576
- }
3577
- function findObjectLiteral(declaration) {
3578
- let expression = declaration?.getInitializer();
3579
- while (expression && (import_ts_morph2.Node.isAsExpression(expression) || import_ts_morph2.Node.isSatisfiesExpression(expression))) {
3580
- expression = expression.getExpression();
3581
- }
3582
- return expression && import_ts_morph2.Node.isObjectLiteralExpression(expression) ? expression : void 0;
3583
- }
3584
- function hasKeyFor(obj, key, constant) {
3585
- const accepted = /* @__PURE__ */ new Set([
3586
- `[TriggerEvent.${constant}]`,
3587
- `['${key}']`,
3588
- `["${key}"]`,
3589
- `'${key}'`,
3590
- `"${key}"`,
3591
- key
3592
- ]);
3593
- return obj.getProperties().some(
3594
- (property) => import_ts_morph2.Node.isPropertyAssignment(property) && accepted.has(property.getName().trim())
3595
- );
3596
- }
3597
- function renderKey(obj, key, constant) {
3598
- const names = obj.getProperties().filter(import_ts_morph2.Node.isPropertyAssignment).map((property) => property.getName().trim());
3599
- if (names.some((name) => name.startsWith("[TriggerEvent."))) {
3600
- return `[TriggerEvent.${constant}]`;
3601
- }
3602
- if (names.some((name) => name.startsWith("["))) {
3603
- return `['${key}']`;
3604
- }
3605
- return `'${key}'`;
3606
- }
3607
- function appendEntry(sourceFile, objectName, key, valueLines) {
3608
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3609
- const properties = obj?.getProperties() ?? [];
3610
- const lastProperty = properties[properties.length - 1];
3611
- if (!lastProperty) return false;
3612
- const indent = lastProperty.getIndentationText();
3613
- const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${key}: ${line2}` : line2}`).join("\n");
3614
- sourceFile.insertText(lastProperty.getEnd(), `,
3615
- ${entry}`);
3616
- return true;
3617
- }
3618
- function objectHasKeyFor(sourceFile, objectName, key, constant) {
3619
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3620
- return obj ? hasKeyFor(obj, key, constant) : false;
3621
- }
3622
- function renderKeyFor(sourceFile, objectName, key, constant) {
3623
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3624
- return obj ? renderKey(obj, key, constant) : `'${key}'`;
3625
- }
3626
- function updateEmailTemplates(project, cwd) {
3627
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, EMAIL_TEMPLATES_FILE));
3628
- if (!sourceFile) {
3629
- warnSkipped(`${EMAIL_TEMPLATES_FILE} not found; email templates not wired`);
3630
- return;
3631
- }
3632
- const missingObject = [TRIGGER_VARIABLE_OBJECT, TEMPLATES_OBJECT].find(
3633
- (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3634
- );
3635
- if (missingObject) {
3636
- warnSkipped(
3637
- `Could not find '${missingObject}' in ${EMAIL_TEMPLATES_FILE}; email templates not wired`
3638
- );
3639
- return;
3640
- }
3641
- for (const event of RECOVERY_EVENTS) {
3642
- if (!objectHasKeyFor(
3643
- sourceFile,
3644
- TRIGGER_VARIABLE_OBJECT,
3645
- event.id,
3646
- event.constant
3647
- ) && appendEntry(
3648
- sourceFile,
3649
- TRIGGER_VARIABLE_OBJECT,
3650
- renderKeyFor(
3651
- sourceFile,
3652
- TRIGGER_VARIABLE_OBJECT,
3653
- event.id,
3654
- event.constant
3655
- ),
3656
- [
3657
- "z.object({",
3658
- " firstname: z.string(),",
3659
- " applicationName: z.string(),",
3660
- " countryLogo: z.string(),",
3661
- " recoveryURL: z.string()",
3662
- "})"
3663
- ]
3664
- )) {
3665
- console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} variables`);
3666
- }
3667
- if (!objectHasKeyFor(
3668
- sourceFile,
3669
- TEMPLATES_OBJECT,
3670
- event.id,
3671
- event.constant
3672
- ) && appendEntry(
3673
- sourceFile,
3674
- TEMPLATES_OBJECT,
3675
- renderKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant),
3676
- [
3677
- "{",
3678
- ` type: '${event.id}',`,
3679
- ` subject: '${event.emailSubject}',`,
3680
- ` template: readOtherTemplate<TriggerVariable['${event.id}']>(`,
3681
- ` '${event.id}'`,
3682
- " )",
3683
- "}"
3684
- ]
3685
- )) {
3686
- console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} template`);
3687
- }
3688
- }
3689
- }
3690
- function updateSmsService(project, cwd) {
3691
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, SMS_SERVICE_FILE));
3692
- if (!sourceFile) {
3693
- warnSkipped(`${SMS_SERVICE_FILE} not found; SMS templates not wired`);
3694
- return;
3695
- }
3696
- const missingObject = [
3697
- OTHER_TEMPLATES_OBJECT,
3698
- TRIGGER_TO_SMS_TEMPLATE_OBJECT
3699
- ].find(
3700
- (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3701
- );
3702
- if (missingObject) {
3703
- warnSkipped(
3704
- `Could not find '${missingObject}' in ${SMS_SERVICE_FILE}; SMS templates not wired`
3705
- );
3706
- return;
3707
- }
3708
- for (const event of RECOVERY_EVENTS) {
3709
- if (!objectHasKeyFor(
3710
- sourceFile,
3711
- OTHER_TEMPLATES_OBJECT,
3712
- event.smsTemplate,
3713
- event.smsTemplate
3714
- ) && appendEntry(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, [
3715
- `'${event.smsTemplate}'`
3716
- ])) {
3717
- console.log(` \u2713 ${SMS_SERVICE_FILE}: ${event.smsTemplate}`);
3718
- }
3719
- if (!objectHasKeyFor(
3720
- sourceFile,
3721
- TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3722
- event.id,
3723
- event.constant
3724
- ) && appendEntry(
3725
- sourceFile,
3726
- TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3727
- renderKeyFor(
3728
- sourceFile,
3729
- TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3730
- event.id,
3731
- event.constant
3732
- ),
3733
- [`'${event.smsTemplate}'`]
3734
- )) {
3735
- console.log(
3736
- ` \u2713 ${SMS_SERVICE_FILE}: ${event.id} -> ${event.smsTemplate}`
3737
- );
3738
- }
3739
- }
3740
- }
3741
- function updateHandler(project, cwd) {
3742
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, HANDLER_FILE));
3743
- if (!sourceFile) {
3744
- warnSkipped(`${HANDLER_FILE} not found; payload conversion not wired`);
3745
- return;
3746
- }
3747
- const convertPayload = sourceFile.getFunction(CONVERT_PAYLOAD_FUNCTION);
3748
- const caseBlock = convertPayload?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.SwitchStatement)?.getCaseBlock();
3749
- if (!caseBlock) {
3750
- warnSkipped(
3751
- `Could not find a switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE}; payload conversion not wired`
3752
- );
3753
- return;
3754
- }
3755
- const missing = RECOVERY_EVENTS.filter(
3756
- (event) => !caseBlock.getText().includes(`TriggerEvent.${event.constant}`) && !caseBlock.getText().includes(`'${event.id}'`)
3757
- );
3758
- if (missing.length === 0) return;
3759
- const existingClauses = caseBlock.getClauses();
3760
- if (existingClauses.length === 0) {
3761
- warnSkipped(
3762
- `The switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE} has no cases; payload conversion not wired`
3763
- );
3764
- return;
3765
- }
3766
- const defaultClause = existingClauses.find(import_ts_morph2.Node.isDefaultClause);
3767
- const anchor = defaultClause ?? existingClauses[existingClauses.length - 1];
3768
- const indent = anchor.getIndentationText();
3769
- const lines = [
3770
- ...missing.map((event) => `case TriggerEvent.${event.constant}:`),
3771
- ` return {`,
3772
- ` firstname,`,
3773
- ` applicationName: applicationConfig.APPLICATION_NAME,`,
3774
- ` countryLogo: COUNTRY_LOGO_URL,`,
3775
- ` recoveryURL: \`\${LOGIN_URL}recover?token=\${encodeURIComponent(payload.token)}\``,
3776
- ` }`
3777
- ];
3778
- if (defaultClause) {
3779
- caseBlock.insertText(
3780
- anchor.getStart(),
3781
- `${lines.map((line2, index) => index === 0 ? line2 : `${indent}${line2}`).join("\n")}
3782
- ${indent}`
3783
- );
3784
- } else {
3785
- caseBlock.insertText(
3786
- anchor.getEnd(),
3787
- `
3788
- ${lines.map((line2) => `${indent}${line2}`).join("\n")}`
3789
- );
3790
- }
3791
- for (const event of missing) {
3792
- console.log(` \u2713 ${HANDLER_FILE}: ${event.id} case`);
3793
- }
3794
- }
3795
- function updateRoutes(project, cwd) {
3796
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, ROUTES_FILE));
3797
- if (!sourceFile) {
3798
- warnSkipped(`${ROUTES_FILE} not found; trigger routes not registered`);
3799
- return;
3800
- }
3801
- const routesFunction = sourceFile.getFunction(ROUTES_FUNCTION) ?? sourceFile.getFunctions().find((fn) => fn.isDefaultExport());
3802
- const routesArray = routesFunction?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.ReturnStatement)?.getExpressionIfKind(import_ts_morph2.SyntaxKind.ArrayLiteralExpression);
3803
- if (!routesArray) {
3804
- warnSkipped(
3805
- `Could not find the route array returned by '${ROUTES_FUNCTION}' in ${ROUTES_FILE}; trigger routes not registered`
3806
- );
3807
- return;
3808
- }
3809
- for (const event of RECOVERY_EVENTS) {
3810
- if (routesArray.getText().includes(`/trigger/user/${event.id}`)) continue;
3811
- routesArray.addElement(`{
3812
- method: 'POST',
3813
- path: '/trigger/user/${event.id}',
3814
- handler: makeNotificationHandler('${event.id}'),
3815
- options: {
3816
- auth: false,
3817
- tags: ['api'],
3818
- description: '${event.routeDescription}'
3819
- }
3820
- }`);
3821
- console.log(` \u2713 ${ROUTES_FILE}: POST /trigger/user/${event.id}`);
3822
- }
3823
- }
3824
- function renderEmailTemplate(event) {
3825
- return `<!--
3826
- This Source Code Form is subject to the terms of the Mozilla Public
3827
- License, v. 2.0. If a copy of the MPL was not distributed with this
3828
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
3829
-
3830
- OpenCRVS is also distributed under the terms of the Civil Registration
3831
- & Healthcare Disclaimer located at http://opencrvs.org/license.
3832
-
3833
- Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
3834
- -->
3835
- <!doctype html>
3836
- <html>
3837
- <head>
3838
- <link
3839
- href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
3840
- rel="stylesheet"
3841
- />
3842
- <style type="text/css">
3843
- body {
3844
- font-family: 'Noto Sans', sans-serif;
3845
- color: #222;
3846
- padding: 16px 24px;
3847
- }
3848
-
3849
- h1 {
3850
- font-size: 21px;
3851
- margin-top: 32px;
3852
- margin-bottom: 36px;
3853
- font-weight: 700;
3854
- }
3855
-
3856
- p {
3857
- font-weight: 400;
3858
- font-size: 16px;
3859
- line-height: 1.8;
3860
- margin-bottom: 24px;
3861
- }
3862
-
3863
- i {
3864
- color: #666;
3865
- font-weight: 400;
3866
- font-size: 16px;
3867
- }
3868
- </style>
3869
- </head>
3870
-
3871
- <body>
3872
- <img
3873
- src="{{countryLogo}}"
3874
- alt="country_logo"
3875
- style="max-height: 88px; max-width: 100%"
3876
- />
3877
- <h1>${event.heading}</h1>
3878
- <p>Hello {{firstname}},</p>
3879
- <p>
3880
- ${event.reason}
3881
- </p>
3882
-
3883
- <div style="margin-top: 32px; margin-bottom: 32px">
3884
- <a href="{{{recoveryURL}}}">${event.linkLabel}</a>
3885
- </div>
3886
- <br />
3887
- <p>
3888
- This link expires in 1 hour and can only be used once. If you did not
3889
- request this, you can ignore this email.
3890
- </p>
3891
- <br />
3892
- <p>
3893
- Best regards, <br />
3894
- {{applicationName}} Team
3895
- </p>
3896
- </body>
3897
- </html>
3898
- `;
3899
- }
3900
- function writeEmailTemplates(cwd) {
3901
- const templateDir = import_path2.default.join(cwd, EMAIL_TEMPLATE_DIR);
3902
- if (!(0, import_fs2.existsSync)(templateDir)) {
3903
- warnSkipped(
3904
- `${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`
3905
- );
3906
- return;
3907
- }
3908
- for (const event of RECOVERY_EVENTS) {
3909
- const templatePath = import_path2.default.join(templateDir, `${event.id}.html`);
3910
- if ((0, import_fs2.existsSync)(templatePath)) continue;
3911
- (0, import_fs2.writeFileSync)(templatePath, renderEmailTemplate(event));
3912
- console.log(` \u2713 ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
3913
- }
3914
- }
3915
- function addCsvRows(cwd, relativePath, rows) {
3916
- const csvPath = import_path2.default.join(cwd, relativePath);
3917
- const file = readCsvFile(csvPath);
3918
- if (!file) {
3919
- warnSkipped(`${relativePath} not found; translations not added`);
3920
- return;
3921
- }
3922
- const added = addRows(file, rows);
3923
- if (added.length === 0) return;
3924
- for (const id of added) {
3925
- console.log(` \u2713 ${relativePath}: ${id}`);
3926
- }
3927
- writeCsvFile(csvPath, file);
3928
- }
3929
- async function main2() {
3930
- const cwd = process.cwd();
3931
- const tsConfigFilePath = import_path2.default.join(cwd, "tsconfig.json");
3932
- console.log(
3933
- "Registering the password-reset-link and username-reminder-link notifications...\n"
3934
- );
3935
- if (!(0, import_fs2.existsSync)(tsConfigFilePath)) {
3936
- warnSkipped(
3937
- `tsconfig.json not found in ${cwd}; notification wiring skipped entirely`
3938
- );
3939
- return;
3940
- }
3941
- const project = new import_ts_morph2.Project({
3942
- tsConfigFilePath,
3943
- skipAddingFilesFromTsConfig: false,
3944
- // ts-morph indents inserted code with four spaces by default, which every
3945
- // country config's prettier run would immediately undo.
3946
- manipulationSettings: { indentationText: import_ts_morph2.IndentationText.TwoSpaces }
3947
- });
3948
- updateEmailTemplates(project, cwd);
3949
- updateSmsService(project, cwd);
3950
- updateHandler(project, cwd);
3951
- updateRoutes(project, cwd);
3952
- await project.save();
3953
- writeEmailTemplates(cwd);
3954
- addCsvRows(cwd, NOTIFICATION_CSV, NOTIFICATION_CSV_ROWS);
3955
- addCsvRows(cwd, LOGIN_CSV, LOGIN_CSV_ROWS);
3956
- if (skipped.length > 0) {
3957
- console.warn(
3958
- `
3959
- \u26A0\uFE0F ${skipped.length} step(s) were skipped. Wire the following by hand before upgrading:`
3960
- );
3961
- for (const message of skipped) {
3962
- console.warn(` - ${message}`);
3963
- }
3964
- }
3965
- }
3966
-
3967
- // src/migrations/v2.1/add-translations.ts
3968
- var import_path3 = __toESM(require("path"));
3969
-
3970
3626
  // src/translations/template.ts
3971
3627
  var REPOSITORY = "opencrvs/opencrvs-core";
3972
3628
  var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
@@ -4007,12 +3663,11 @@ async function fetchTemplate(refs, application) {
4007
3663
  return void 0;
4008
3664
  }
4009
3665
 
4010
- // src/migrations/v2.1/add-translations.ts
3666
+ // src/migrations/persistent/add-translations.ts
4011
3667
  var APPLICATIONS = ["client", "login"];
4012
- var TARGET_VERSION = "2.1";
4013
- var skipped2 = [];
4014
- function warnSkipped2(message) {
4015
- skipped2.push(message);
3668
+ var skipped = [];
3669
+ function warnSkipped(message) {
3670
+ skipped.push(message);
4016
3671
  console.warn(` \u26A0\uFE0F ${message}`);
4017
3672
  }
4018
3673
  function rowsToAdd(local, template) {
@@ -4028,17 +3683,17 @@ function rowsToAdd(local, template) {
4028
3683
  );
4029
3684
  });
4030
3685
  }
4031
- async function updateApplication(cwd, refs, application) {
3686
+ async function updateApplication(cwd, targetVersion, refs, application) {
4032
3687
  const relativePath = `src/translations/${application}.csv`;
4033
- const local = readCsvFile(import_path3.default.join(cwd, relativePath));
3688
+ const local = readCsvFile(import_path.default.join(cwd, relativePath));
4034
3689
  if (!local) {
4035
- warnSkipped2(`${relativePath} not found; translations not added`);
3690
+ warnSkipped(`${relativePath} not found; translations not added`);
4036
3691
  return;
4037
3692
  }
4038
3693
  const fetched = await fetchTemplate(refs, application);
4039
3694
  if (!fetched) {
4040
- warnSkipped2(
4041
- `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
3695
+ warnSkipped(
3696
+ `No ${application}.csv found in the ${targetVersion} country config template on GitHub; ${application}.csv not updated`
4042
3697
  );
4043
3698
  return;
4044
3699
  }
@@ -4048,10 +3703,10 @@ async function updateApplication(cwd, refs, application) {
4048
3703
  return;
4049
3704
  }
4050
3705
  try {
4051
- writeCsvFile(import_path3.default.join(cwd, relativePath), local);
4052
- } catch (error3) {
4053
- warnSkipped2(
4054
- `Could not write ${relativePath} (${error3.message}); translations not added`
3706
+ writeCsvFile(import_path.default.join(cwd, relativePath), local);
3707
+ } catch (error2) {
3708
+ warnSkipped(
3709
+ `Could not write ${relativePath} (${error2.message}); translations not added`
4055
3710
  );
4056
3711
  return;
4057
3712
  }
@@ -4068,1331 +3723,1138 @@ function readTemplate(contents) {
4068
3723
  trailingNewline: true
4069
3724
  };
4070
3725
  }
4071
- async function listRefs() {
3726
+ async function listRefs(targetVersion) {
4072
3727
  try {
4073
- return await candidateRefs(TARGET_VERSION);
4074
- } catch (error3) {
4075
- warnSkipped2(
4076
- `Could not list the ${TARGET_VERSION} refs on GitHub (${error3.message}); translations not added`
3728
+ return await candidateRefs(targetVersion);
3729
+ } catch (error2) {
3730
+ warnSkipped(
3731
+ `Could not list the ${targetVersion} refs on GitHub (${error2.message}); translations not added`
4077
3732
  );
4078
3733
  return void 0;
4079
3734
  }
4080
3735
  }
4081
- async function main3() {
3736
+ async function main(targetVersion) {
4082
3737
  const cwd = process.cwd();
4083
3738
  console.log("Adding the translation keys core gained this version...\n");
4084
- const refs = await listRefs();
3739
+ const refs = await listRefs(targetVersion);
4085
3740
  if (refs) {
4086
3741
  for (const application of APPLICATIONS) {
4087
3742
  try {
4088
- await updateApplication(cwd, refs, application);
4089
- } catch (error3) {
4090
- warnSkipped2(
4091
- `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${application}.csv not updated`
3743
+ await updateApplication(cwd, targetVersion, refs, application);
3744
+ } catch (error2) {
3745
+ warnSkipped(
3746
+ `Could not read ${application}.csv from the country config template on GitHub (${error2.message}); ${application}.csv not updated`
4092
3747
  );
4093
3748
  }
4094
3749
  }
4095
3750
  }
4096
- if (skipped2.length > 0) {
3751
+ if (skipped.length > 0) {
4097
3752
  console.warn(
4098
3753
  `
4099
- \u26A0\uFE0F ${skipped2.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
3754
+ \u26A0\uFE0F ${skipped.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
4100
3755
  );
4101
- for (const message of skipped2) {
3756
+ for (const message of skipped) {
4102
3757
  console.warn(` - ${message}`);
4103
3758
  }
4104
3759
  }
4105
3760
  }
4106
3761
 
4107
- // src/migrations/v2.1/enable-telemetry.ts
4108
- var import_ts_morph3 = require("ts-morph");
4109
- var import_fs3 = require("fs");
4110
- var import_path4 = __toESM(require("path"));
4111
- var HANDLER_FILE2 = "src/api/telemetry/handler.ts";
4112
- var ENVIRONMENT_FILE = "src/environment.ts";
4113
- var INDEX_FILE = "src/index.ts";
4114
- var HANDLER_MODULE = "./api/telemetry/handler";
4115
- var skipped3 = [];
4116
- function warnSkipped3(message) {
4117
- skipped3.push(message);
4118
- console.warn(` \u26A0\uFE0F ${message}`);
4119
- }
4120
- var TELEMETRY_HANDLER_SOURCE = `/*
4121
- * This Source Code Form is subject to the terms of the Mozilla Public
4122
- * License, v. 2.0. If a copy of the MPL was not distributed with this
4123
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
4124
- *
4125
- * OpenCRVS is also distributed under the terms of the Civil Registration
4126
- * & Healthcare Disclaimer located at http://opencrvs.org/license.
4127
- *
4128
- * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
4129
- */
4130
-
4131
- import { Request, ResponseToolkit } from '@hapi/hapi'
4132
- import * as Joi from 'joi'
4133
- import { sendTelemetry, TelemetryReport } from '@opencrvs/toolkit/telemetry'
4134
- import { env } from '@countryconfig/environment'
4135
- import { logger } from '@countryconfig/logger'
4136
- import { applicationConfig } from '@countryconfig/api/application/application-config'
4137
-
4138
- /** Report the events service posts to \`/trigger/telemetry\`. */
4139
- export const telemetrySchema = Joi.object({
4140
- reported_at: Joi.string().isoDate().required(),
4141
- app_version: Joi.string().optional(),
4142
- metrics: Joi.object()
4143
- .pattern(
4144
- Joi.string(),
4145
- Joi.alternatives(Joi.number(), Joi.string(), Joi.boolean())
4146
- )
4147
- .required()
4148
- })
3762
+ // src/migrations/move-declaration-to-declare-action.ts
3763
+ var import_ts_morph2 = require("ts-morph");
3764
+ var import_path3 = __toESM(require("path"));
4149
3765
 
4150
- interface IncomingReport {
4151
- reported_at: string
4152
- app_version?: string
4153
- metrics: Record<string, number | string | boolean>
3766
+ // src/migrations/utils.ts
3767
+ var import_ts_morph = require("ts-morph");
3768
+ var import_path2 = __toESM(require("path"));
3769
+ var DEFINE_CONFIG_NAME = "defineConfig";
3770
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3771
+ function location(node) {
3772
+ const relPath = import_path2.default.relative(
3773
+ process.cwd(),
3774
+ node.getSourceFile().getFilePath()
3775
+ );
3776
+ return `${relPath}:${node.getStartLineNumber()}`;
4154
3777
  }
4155
-
4156
- /** Logged once at countryconfig startup while telemetry is disabled. */
4157
- export const TELEMETRY_DISABLED_NOTICE =
4158
- 'Telemetry is disabled. Help improve OpenCRVS by sharing anonymous, ' +
4159
- 'aggregate usage metrics (registration and certificate counts, active ' +
4160
- 'users, uptime) \u2014 no personal, health, or otherwise protected record data ' +
4161
- 'ever leaves your instance. Enable it by setting TELEMETRY_ENABLED=true on ' +
4162
- 'the countryconfig service.'
4163
-
4164
- /**
4165
- * Receives a usage report from the events service and, when telemetry is
4166
- * enabled for this instance, stamps the instance identity onto it and forwards
4167
- * it to the status service via the toolkit's \`sendTelemetry\` (which owns the
4168
- * endpoint and payload schema). The events service is unaware of whether
4169
- * telemetry is enabled or of the country code / domain / environment reported.
4170
- */
4171
- export async function telemetryHandler(request: Request, h: ResponseToolkit) {
4172
- // Only accept OpenCRVS *system* tokens (the events service's service
4173
- // token has userType 'system'). A logged-in user's token is a 'user' token,
4174
- // so a user cannot submit telemetry with their own credentials \u2014 and the
4175
- // service-token endpoint is not reachable through the public gateway.
4176
- const credentials = request.auth.credentials as
4177
- | { userType?: string }
4178
- | undefined
4179
- if (credentials?.userType !== 'system') {
4180
- logger.warn('Telemetry: rejected a request that is not from a system token')
4181
- return h.response({ error: 'forbidden' }).code(403)
4182
- }
4183
-
4184
- if (!env.TELEMETRY_ENABLED) {
4185
- // The encouraging notice is logged once at startup (see index.ts); keep the
4186
- // per-report path quiet.
4187
- return h.response({ status: 'skipped' }).code(200)
3778
+ function isToolkitDefineConfigCall(call) {
3779
+ const symbol = call.getExpression().getSymbol();
3780
+ const resolved = symbol?.getAliasedSymbol() ?? symbol;
3781
+ if (resolved?.getName() !== DEFINE_CONFIG_NAME) {
3782
+ return false;
4188
3783
  }
4189
-
4190
- const incoming = request.payload as IncomingReport
4191
-
4192
- // Only production instances report; staging, QA and local build the report
4193
- // but never reach the status service. (This gate used to live in the
4194
- // toolkit's sendTelemetry; each country config now owns it.)
4195
- if (!env.isProduction) {
4196
- logger.info(
4197
- \`Telemetry: report for \${incoming.reported_at} was not sent \u2014 only production instances report\`
4198
- )
4199
- return h.response({ status: 'skipped' }).code(200)
3784
+ return resolved.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
3785
+ }
3786
+ function findProperty(literal, name) {
3787
+ const property = literal.getProperty(name);
3788
+ return import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property) ? property : void 0;
3789
+ }
3790
+ function mayHaveActionType(actionType, node, expectedActionType) {
3791
+ const typeProperty = actionType.getProperty("type");
3792
+ if (!typeProperty) {
3793
+ return true;
4200
3794
  }
4201
-
4202
- const report: TelemetryReport = {
4203
- reported_at: incoming.reported_at,
4204
- country_code: env.COUNTRY_CODE,
4205
- organisation: env.ORGANISATION,
4206
- // env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
4207
- // "no domain" rather than reporting a literal "*".
4208
- domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
4209
- instance: {
4210
- application_name: applicationConfig.APPLICATION_NAME,
4211
- environment: env.ENVIRONMENT_NAME,
4212
- app_version: incoming.app_version
4213
- },
4214
- metrics: incoming.metrics
3795
+ const type = typeProperty.getTypeAtLocation(node);
3796
+ const values = type.isUnion() ? type.getUnionTypes() : [type];
3797
+ return !values.every(
3798
+ (value) => value.isStringLiteral() && value.getLiteralValue() !== expectedActionType
3799
+ );
3800
+ }
3801
+ function mayBeAction(node, actionType) {
3802
+ if (import_ts_morph.Node.isObjectLiteralExpression(node)) {
3803
+ return isAction(node, actionType);
4215
3804
  }
4216
-
4217
- let result
4218
- try {
4219
- result = await sendTelemetry(report)
4220
- } catch (error) {
4221
- const message = error instanceof Error ? error.message : String(error)
4222
- logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
4223
- return h.response({ status: 'error' }).code(502)
3805
+ if (import_ts_morph.Node.isSpreadElement(node)) {
3806
+ const arrayType = node.getExpression().getType();
3807
+ const elementTypes = arrayType.isTuple() ? arrayType.getTupleElements() : [arrayType.getArrayElementType()];
3808
+ return elementTypes.some(
3809
+ (elementType) => !elementType || mayHaveActionType(elementType, node, actionType)
3810
+ );
4224
3811
  }
4225
-
4226
- if (result.outcome === 'rejected') {
4227
- logger.error(
4228
- \`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
4229
- )
4230
- return h.response({ status: 'error' }).code(502)
3812
+ return mayHaveActionType(node.getType(), node, actionType);
3813
+ }
3814
+ function isAction(literal, actionType) {
3815
+ const type = findProperty(literal, "type");
3816
+ return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === actionType;
3817
+ }
3818
+ function indentationOf(node) {
3819
+ const text = node.getSourceFile().getFullText();
3820
+ const lineStart = text.lastIndexOf("\n", node.getStart() - 1) + 1;
3821
+ return /^[ \t]*/.exec(text.slice(lineStart))?.[0] ?? "";
3822
+ }
3823
+ function restOfLine(text, position) {
3824
+ const lineEnd = text.indexOf("\n", position);
3825
+ return text.slice(position, lineEnd === -1 ? text.length : lineEnd);
3826
+ }
3827
+ function isOnlyComments(text) {
3828
+ return /^\s*(?:\/\/.*|\/\*.*?\*\/\s*)*$/.test(text);
3829
+ }
3830
+ function layoutOf(property) {
3831
+ const text = property.getSourceFile().getFullText();
3832
+ const next = property.getNextSibling();
3833
+ const hasComma = next?.getKind() === import_ts_morph.SyntaxKind.CommaToken;
3834
+ const end = next && hasComma ? next.getEnd() : property.getEnd();
3835
+ const trailing = restOfLine(text, end);
3836
+ const lineBreak = text.slice(property.getFullStart(), property.getStart()).indexOf("\n");
3837
+ if (lineBreak === -1 || !isOnlyComments(trailing)) {
3838
+ return {
3839
+ ownsLines: false,
3840
+ start: property.getStart(true),
3841
+ end,
3842
+ hasComma,
3843
+ trailingComment: ""
3844
+ };
4231
3845
  }
4232
-
4233
- logger.info(
4234
- \`Telemetry: forwarded report for \${report.reported_at} to the status service\`
4235
- )
4236
- return h.response({ status: 'forwarded' }).code(202)
3846
+ const firstLine = property.getFullStart() + lineBreak + 1;
3847
+ return {
3848
+ ownsLines: true,
3849
+ start: firstLine + (/^\s*/.exec(text.slice(firstLine))?.[0].length ?? 0),
3850
+ end,
3851
+ hasComma,
3852
+ trailingComment: trailing.trimEnd()
3853
+ };
4237
3854
  }
4238
- `;
4239
- var TELEMETRY_DISABLED = {
4240
- enabled: false,
4241
- countryCode: "",
4242
- organisation: ""
4243
- };
4244
- async function promptTelemetryConfig() {
4245
- if (!process.stdin.isTTY) {
4246
- return TELEMETRY_DISABLED;
3855
+ function insertAt(position, text) {
3856
+ return { start: position, end: position, text };
3857
+ }
3858
+ function applyTextEdits(sourceFile, edits) {
3859
+ const text = [...edits].sort((a, b) => b.start - a.start).reduce(
3860
+ (result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end),
3861
+ sourceFile.getFullText()
3862
+ );
3863
+ sourceFile.replaceWithText(text);
3864
+ }
3865
+ function findToolkitImport(sourceFile) {
3866
+ return sourceFile.getImportDeclaration(
3867
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
3868
+ );
3869
+ }
3870
+ function findToolkitImportName(sourceFile, name) {
3871
+ const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === name);
3872
+ if (imported) {
3873
+ return imported.getAliasNode()?.getText() ?? name;
4247
3874
  }
4248
- const { confirm: confirm3, input: input4 } = await import("@inquirer/prompts");
4249
- const enabled = await confirm3({
4250
- message: "Enable anonymous usage telemetry to help improve OpenCRVS? Only aggregate metrics are shared \u2014 no personal or protected data.",
4251
- default: true
4252
- });
4253
- if (!enabled) {
4254
- return TELEMETRY_DISABLED;
4255
- }
4256
- const countryCode = (await input4({
4257
- message: "Country code (ISO alpha-3, e.g. FAR):",
4258
- validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) || "Enter a 3-letter ISO alpha-3 code."
4259
- })).trim().toUpperCase();
4260
- const organisation = (await input4({
4261
- message: "Organisation running this instance:",
4262
- validate: (value) => value.trim() !== "" || "Enter an organisation name."
4263
- })).trim();
4264
- return { enabled: true, countryCode, organisation };
4265
- }
4266
- function writeTelemetryHandler(cwd) {
4267
- const handlerPath = import_path4.default.join(cwd, HANDLER_FILE2);
4268
- if ((0, import_fs3.existsSync)(handlerPath)) {
4269
- console.log(` ${HANDLER_FILE2} already present; left unchanged`);
4270
- return;
3875
+ if (sourceFile.getLocal(name)) {
3876
+ return void 0;
4271
3877
  }
4272
- (0, import_fs3.mkdirSync)(import_path4.default.dirname(handlerPath), { recursive: true });
4273
- (0, import_fs3.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
4274
- console.log(` \u2713 ${HANDLER_FILE2}`);
4275
- }
4276
- function appendProperty(sourceFile, object2, name, valueLines) {
4277
- const properties = object2.getProperties();
4278
- const lastProperty = properties[properties.length - 1];
4279
- if (!lastProperty) return false;
4280
- const indent = lastProperty.getIndentationText();
4281
- const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${name}: ${line2}` : line2}`).join("\n");
4282
- sourceFile.insertText(lastProperty.getEnd(), `,
4283
- ${entry}`);
4284
- return true;
3878
+ return name;
4285
3879
  }
4286
- function ensureEnvalidNamedImports(sourceFile, names) {
4287
- const importDeclaration = sourceFile.getImportDeclarations().find((declaration) => declaration.getModuleSpecifierValue() === "envalid");
4288
- if (!importDeclaration) {
4289
- warnSkipped3(
4290
- `Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(", ")} } by hand`
3880
+ function addToolkitImport(sourceFile, name) {
3881
+ const toolkitImport = findToolkitImport(sourceFile);
3882
+ if (!toolkitImport) {
3883
+ const imports = sourceFile.getImportDeclarations();
3884
+ const lastImport = imports[imports.length - 1];
3885
+ sourceFile.insertStatements(
3886
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
3887
+ `import { ${name} } from '${TOOLKIT_EVENTS_MODULE}'`
4291
3888
  );
4292
3889
  return;
4293
3890
  }
4294
- const existing = new Set(
4295
- importDeclaration.getNamedImports().map((named) => named.getName())
3891
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === name);
3892
+ if (alreadyImported) {
3893
+ return;
3894
+ }
3895
+ const namedImports = toolkitImport.getNamedImports();
3896
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
3897
+ toolkitImport.addNamedImport(name);
3898
+ return;
3899
+ }
3900
+ const names = [
3901
+ ...namedImports.map((namedImport) => namedImport.getText()),
3902
+ name
3903
+ ];
3904
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
3905
+ ${names.join(",\n ")}
3906
+ }` : `{ ${names.join(", ")} }`;
3907
+ toolkitImport.replaceWithText(
3908
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
4296
3909
  );
4297
- for (const name of names) {
4298
- if (!existing.has(name)) {
4299
- importDeclaration.addNamedImport(name);
3910
+ }
3911
+
3912
+ // src/migrations/move-declaration-to-declare-action.ts
3913
+ var DEFINE_CONFIG_NAME2 = "defineConfig";
3914
+ var DECLARATION_PROPERTY_NAME = "declaration";
3915
+ var ACTIONS_PROPERTY_NAME = "actions";
3916
+ var DECLARE_ACTION_TYPE = "DECLARE";
3917
+ function findDeclareAction(config) {
3918
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
3919
+ const actionsValue = import_ts_morph2.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
3920
+ if (!import_ts_morph2.Node.isArrayLiteralExpression(actionsValue)) {
3921
+ console.warn(
3922
+ ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`
3923
+ );
3924
+ return void 0;
3925
+ }
3926
+ const candidates = actionsValue.getElements().filter((element) => mayBeAction(element, DECLARE_ACTION_TYPE));
3927
+ if (candidates.length !== 1 || !import_ts_morph2.Node.isObjectLiteralExpression(candidates[0])) {
3928
+ console.warn(
3929
+ ` [${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.`
3930
+ );
3931
+ return void 0;
3932
+ }
3933
+ const declareAction = candidates[0];
3934
+ if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
3935
+ console.warn(
3936
+ ` [${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.`
3937
+ );
3938
+ return void 0;
3939
+ }
3940
+ return declareAction;
3941
+ }
3942
+ function insertIntoDeclareAction(declareAction, property) {
3943
+ const anchor = declareAction.getProperty("label") ?? declareAction.getPropertyOrThrow("type");
3944
+ const text = property.getSourceFile().getFullText();
3945
+ const anchorLayout = layoutOf(anchor);
3946
+ const layout = layoutOf(property);
3947
+ const indent = indentationOf(anchor);
3948
+ const oldIndent = indentationOf(property);
3949
+ const reindent = (lines) => lines.split("\n").map(
3950
+ (line2, index) => index > 0 && line2.startsWith(oldIndent) ? indent + line2.slice(oldIndent.length) : line2
3951
+ ).join("\n");
3952
+ if (anchorLayout.ownsLines) {
3953
+ const moved = reindent(text.slice(layout.start, property.getEnd()));
3954
+ const position = anchorLayout.end + restOfLine(text, anchorLayout.end).length;
3955
+ const insertion = `
3956
+ ${indent}${moved}${anchorLayout.hasComma ? "," : ""}${layout.trailingComment}`;
3957
+ if (anchorLayout.hasComma) {
3958
+ return [insertAt(position, insertion)];
4300
3959
  }
3960
+ return position === anchor.getEnd() ? [insertAt(position, `,${insertion}`)] : [insertAt(anchor.getEnd(), ","), insertAt(position, insertion)];
4301
3961
  }
3962
+ const droppedComments = text.slice(layout.start, property.getStart(true)).trim() !== "" || layout.trailingComment !== "";
3963
+ if (droppedComments) {
3964
+ console.warn(
3965
+ ` [${location(property)}] The comments next to \`${DECLARATION_PROPERTY_NAME}\` were not moved with it. Move them onto the ${DECLARE_ACTION_TYPE} action by hand.`
3966
+ );
3967
+ }
3968
+ const isMultiLine = declareAction.getText().includes("\n");
3969
+ const separator = isMultiLine ? `,
3970
+ ${indent}` : ", ";
3971
+ return [
3972
+ insertAt(anchor.getEnd(), `${separator}${reindent(property.getText(true))}`)
3973
+ ];
4302
3974
  }
4303
- function getCleanEnvObject(sourceFile) {
4304
- const options = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
4305
- return options && import_ts_morph3.Node.isObjectLiteralExpression(options) ? options : void 0;
4306
- }
4307
- function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
4308
- const object2 = getCleanEnvObject(sourceFile);
4309
- if (!object2) return;
4310
- const existing = object2.getProperty(name);
4311
- if (existing && import_ts_morph3.Node.isPropertyAssignment(existing)) {
4312
- if (!update) return;
4313
- const options = existing.getInitializerIfKind(import_ts_morph3.SyntaxKind.CallExpression)?.getArguments()[0];
4314
- if (options && import_ts_morph3.Node.isObjectLiteralExpression(options)) {
4315
- const defaultProperty = options.getProperty("default");
4316
- if (defaultProperty && import_ts_morph3.Node.isPropertyAssignment(defaultProperty)) {
4317
- defaultProperty.setInitializer(defaultExpr);
4318
- } else {
4319
- options.insertPropertyAssignment(0, {
4320
- name: "default",
4321
- initializer: defaultExpr
4322
- });
3975
+ function removeFromConfig(property) {
3976
+ const text = property.getSourceFile().getFullText();
3977
+ const layout = layoutOf(property);
3978
+ const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph2.SyntaxKind.CommaToken);
3979
+ if (layout.ownsLines) {
3980
+ const lines = {
3981
+ start: text.lastIndexOf("\n", layout.start - 1),
3982
+ end: layout.end + restOfLine(text, layout.end).length,
3983
+ text: ""
3984
+ };
3985
+ return !layout.hasComma && previousComma ? [
3986
+ lines,
3987
+ {
3988
+ start: previousComma.getStart(),
3989
+ end: previousComma.getEnd(),
3990
+ text: ""
4323
3991
  }
4324
- console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name} default set`);
3992
+ ] : [lines];
3993
+ }
3994
+ if (layout.hasComma) {
3995
+ return [{ start: property.getFullStart(), end: layout.end, text: "" }];
3996
+ }
3997
+ return [
3998
+ {
3999
+ start: (previousComma ?? property).getStart(),
4000
+ end: property.getEnd(),
4001
+ text: ""
4325
4002
  }
4326
- return;
4003
+ ];
4004
+ }
4005
+ function findConfigLiteral(call) {
4006
+ const config = call.getArguments()[0];
4007
+ if (!config || import_ts_morph2.Node.isObjectLiteralExpression(config)) {
4008
+ return config;
4327
4009
  }
4328
- if (appendProperty(sourceFile, object2, name, [
4329
- `${kind}({`,
4330
- ` default: ${defaultExpr},`,
4331
- ` desc: ${JSON.stringify(desc)}`,
4332
- "})"
4333
- ])) {
4334
- console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name}`);
4010
+ if (config.getType().getProperty(DECLARATION_PROPERTY_NAME)) {
4011
+ console.warn(
4012
+ ` [${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.`
4013
+ );
4335
4014
  }
4015
+ return void 0;
4336
4016
  }
4337
- function addEnvironmentVariables(project, cwd, config) {
4338
- const sourceFile = project.addSourceFileAtPathIfExists(
4339
- import_path4.default.join(cwd, ENVIRONMENT_FILE)
4340
- );
4341
- if (!sourceFile) {
4342
- warnSkipped3(
4343
- `${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`
4017
+ function moveDeclarationToDeclareAction(sourceFile) {
4018
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph2.Node.isObjectLiteralExpression);
4019
+ const edits = [];
4020
+ let changes = 0;
4021
+ for (const config of configs) {
4022
+ const declaration = findProperty(config, DECLARATION_PROPERTY_NAME);
4023
+ if (!declaration) {
4024
+ continue;
4025
+ }
4026
+ const declareAction = findDeclareAction(config);
4027
+ if (!declareAction) {
4028
+ continue;
4029
+ }
4030
+ console.log(
4031
+ ` [${location(declaration)}] Moved \`${declaration.getText()}\` onto the ${DECLARE_ACTION_TYPE} action`
4032
+ );
4033
+ edits.push(
4034
+ ...insertIntoDeclareAction(declareAction, declaration),
4035
+ ...removeFromConfig(declaration)
4344
4036
  );
4037
+ changes++;
4038
+ }
4039
+ if (changes === 0) {
4040
+ return 0;
4041
+ }
4042
+ applyTextEdits(sourceFile, edits);
4043
+ return changes;
4044
+ }
4045
+ async function main2() {
4046
+ const srcDir = import_path3.default.join(process.cwd(), "src");
4047
+ console.log(`Scanning for top-level event declarations in: ${srcDir}
4048
+ `);
4049
+ const project = new import_ts_morph2.Project({
4050
+ tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
4051
+ skipAddingFilesFromTsConfig: false
4052
+ });
4053
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
4054
+ const fp = sf.getFilePath();
4055
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
4056
+ });
4057
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
4058
+ `);
4059
+ let totalChanges = 0;
4060
+ const modifiedFiles = [];
4061
+ for (const sourceFile of sourceFiles) {
4062
+ const changes = moveDeclarationToDeclareAction(sourceFile);
4063
+ if (changes > 0) {
4064
+ totalChanges += changes;
4065
+ modifiedFiles.push(sourceFile);
4066
+ }
4067
+ }
4068
+ if (modifiedFiles.length === 0) {
4069
+ console.log("No top-level event declarations found. Nothing to do.");
4345
4070
  return;
4346
4071
  }
4347
- if (!getCleanEnvObject(sourceFile)) {
4348
- warnSkipped3(
4349
- `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`
4072
+ console.log(`
4073
+ Saving ${modifiedFiles.length} modified file(s)...`);
4074
+ for (const sourceFile of modifiedFiles) {
4075
+ await sourceFile.save();
4076
+ console.log(
4077
+ ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
4350
4078
  );
4351
- return;
4352
4079
  }
4353
- ensureEnvalidNamedImports(sourceFile, ["bool", "str"]);
4354
- upsertEnvVar(
4355
- sourceFile,
4356
- "TELEMETRY_ENABLED",
4357
- "bool",
4358
- config.enabled ? "true" : "false",
4359
- "When true, usage telemetry received from the events service is forwarded to the OpenCRVS status service.",
4360
- true
4361
- );
4362
- upsertEnvVar(
4363
- sourceFile,
4364
- "COUNTRY_CODE",
4365
- "str",
4366
- config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`,
4367
- "ISO-style country code of this instance, reported with telemetry.",
4368
- config.enabled
4369
- );
4370
- upsertEnvVar(
4371
- sourceFile,
4372
- "ORGANISATION",
4373
- "str",
4374
- config.enabled ? JSON.stringify(config.organisation) : `''`,
4375
- "Organisation running this instance, reported with telemetry. Empty by default.",
4376
- config.enabled
4377
- );
4378
- upsertEnvVar(
4379
- sourceFile,
4380
- "ENVIRONMENT_NAME",
4381
- "str",
4382
- `'development'`,
4383
- 'Environment name (e.g. "production", "staging") reported as the telemetry environment.',
4384
- false
4080
+ console.log(
4081
+ `
4082
+ Done. Moved ${totalChanges} declaration(s) across ${modifiedFiles.length} file(s).`
4385
4083
  );
4386
4084
  }
4387
- function ensureHandlerNamedImports(sourceFile, names) {
4388
- const importDeclaration = sourceFile.getImportDeclarations().find(
4389
- (declaration) => declaration.getModuleSpecifierValue() === HANDLER_MODULE
4390
- );
4391
- if (!importDeclaration) {
4392
- sourceFile.addImportDeclaration({
4393
- moduleSpecifier: HANDLER_MODULE,
4394
- namedImports: names
4395
- });
4396
- console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
4397
- return;
4085
+
4086
+ // src/migrations/add-notify-config.ts
4087
+ var import_ts_morph3 = require("ts-morph");
4088
+ var import_path4 = __toESM(require("path"));
4089
+ var DEFINE_CONFIG_NAME3 = "defineConfig";
4090
+ var ACTIONS_PROPERTY_NAME2 = "actions";
4091
+ var DECLARATION_PROPERTY_NAME2 = "declaration";
4092
+ var NOTIFY_ACTION_TYPE = "NOTIFY";
4093
+ var DECLARE_ACTION_TYPE2 = "DECLARE";
4094
+ var NOTIFY_PROPERTIES = [
4095
+ {
4096
+ name: "notificationForm",
4097
+ helper: "toNotificationForm",
4098
+ declareProperty: DECLARATION_PROPERTY_NAME2
4099
+ },
4100
+ {
4101
+ name: "review",
4102
+ helper: "toNotificationReview",
4103
+ declareProperty: "review"
4398
4104
  }
4399
- const existing = new Set(
4400
- importDeclaration.getNamedImports().map((named) => named.getName())
4401
- );
4402
- const missing = names.filter((name) => !existing.has(name));
4403
- for (const name of missing) {
4404
- importDeclaration.addNamedImport(name);
4105
+ ];
4106
+ function referenceOf(property) {
4107
+ if (import_ts_morph3.Node.isShorthandPropertyAssignment(property)) {
4108
+ return property.getName();
4405
4109
  }
4406
- if (missing.length > 0) {
4407
- console.log(
4408
- ` \u2713 ${INDEX_FILE}: import ${missing.join(", ")} from ${HANDLER_MODULE}`
4409
- );
4110
+ const value = property?.getInitializer();
4111
+ return import_ts_morph3.Node.isIdentifier(value) || import_ts_morph3.Node.isPropertyAccessExpression(value) ? value.getText() : void 0;
4112
+ }
4113
+ function findConfigLiteral2(call) {
4114
+ const config = call.getArguments()[0];
4115
+ if (import_ts_morph3.Node.isObjectLiteralExpression(config)) {
4116
+ return config;
4410
4117
  }
4118
+ console.warn(
4119
+ ` [${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.`
4120
+ );
4121
+ return void 0;
4411
4122
  }
4412
- function wireIndex(project, cwd) {
4413
- const sourceFile = project.addSourceFileAtPathIfExists(
4414
- import_path4.default.join(cwd, INDEX_FILE)
4123
+ function findNotifyAction(config, actions) {
4124
+ const candidates = actions.filter(
4125
+ (action) => mayBeAction(action, NOTIFY_ACTION_TYPE)
4415
4126
  );
4416
- if (!sourceFile) {
4417
- warnSkipped3(
4418
- `${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`
4127
+ if (candidates.length === 0) {
4128
+ console.warn(
4129
+ ` [${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\`.`
4419
4130
  );
4420
- return;
4131
+ return void 0;
4421
4132
  }
4422
- ensureHandlerNamedImports(sourceFile, [
4423
- "telemetryHandler",
4424
- "telemetrySchema",
4425
- "TELEMETRY_DISABLED_NOTICE"
4426
- ]);
4427
- if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
4428
- const lastRouteStatement = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter((call) => call.getExpression().getText() === "server.route").map(
4429
- (call) => call.getFirstAncestorByKind(import_ts_morph3.SyntaxKind.ExpressionStatement)
4430
- ).filter(
4431
- (statement) => Boolean(statement)
4432
- ).pop();
4433
- if (!lastRouteStatement) {
4434
- warnSkipped3(
4435
- `Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`
4436
- );
4437
- } else {
4438
- const indent = lastRouteStatement.getIndentationText();
4439
- const route = [
4440
- `server.route({`,
4441
- ` method: 'POST',`,
4442
- ` path: '/trigger/telemetry',`,
4443
- ` handler: telemetryHandler,`,
4444
- ` options: {`,
4445
- ` tags: ['api', 'triggers'],`,
4446
- ` validate: {`,
4447
- ` payload: telemetrySchema`,
4448
- ` },`,
4449
- ` description:`,
4450
- ` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
4451
- ` }`,
4452
- `})`
4453
- ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4454
- sourceFile.insertText(lastRouteStatement.getEnd(), `
4455
-
4456
- ${route}`);
4457
- console.log(` \u2713 ${INDEX_FILE}: POST /trigger/telemetry`);
4133
+ if (candidates.length !== 1 || !import_ts_morph3.Node.isObjectLiteralExpression(candidates[0])) {
4134
+ console.warn(
4135
+ ` [${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.`
4136
+ );
4137
+ return void 0;
4138
+ }
4139
+ return candidates[0];
4140
+ }
4141
+ function insertIntoAction(action, properties) {
4142
+ const anchor = action.getProperty("label") ?? action.getPropertyOrThrow("type");
4143
+ const text = action.getSourceFile().getFullText();
4144
+ const anchorLayout = layoutOf(anchor);
4145
+ const indent = indentationOf(anchor);
4146
+ if (anchorLayout.ownsLines) {
4147
+ const position = anchorLayout.end + restOfLine(text, anchorLayout.end).length;
4148
+ const lines = properties.map((property) => `
4149
+ ${indent}${property}`);
4150
+ if (anchorLayout.hasComma) {
4151
+ return [insertAt(position, `${lines.join(",")},`)];
4458
4152
  }
4153
+ return position === anchor.getEnd() ? [insertAt(position, `,${lines.join(",")}`)] : [insertAt(anchor.getEnd(), ","), insertAt(position, lines.join(","))];
4459
4154
  }
4460
- if (!sourceFile.getText().includes("logger.info(TELEMETRY_DISABLED_NOTICE)")) {
4461
- const startedLog = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.ExpressionStatement).find(
4462
- (statement) => statement.getText().includes("Server successfully started")
4155
+ const separator = action.getText().includes("\n") ? `,
4156
+ ${indent}` : ", ";
4157
+ return [
4158
+ insertAt(
4159
+ anchor.getEnd(),
4160
+ properties.map((property) => `${separator}${property}`).join("")
4161
+ )
4162
+ ];
4163
+ }
4164
+ function addNotifyConfig(sourceFile) {
4165
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral2).filter(import_ts_morph3.Node.isObjectLiteralExpression);
4166
+ const helperNames = Object.fromEntries(
4167
+ NOTIFY_PROPERTIES.map(({ helper }) => [
4168
+ helper,
4169
+ findToolkitImportName(sourceFile, helper)
4170
+ ])
4171
+ );
4172
+ const edits = [];
4173
+ const usedHelpers = /* @__PURE__ */ new Set();
4174
+ let changes = 0;
4175
+ for (const config of configs) {
4176
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME2);
4177
+ const actionsValue = import_ts_morph3.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
4178
+ if (!import_ts_morph3.Node.isArrayLiteralExpression(actionsValue)) {
4179
+ console.warn(
4180
+ ` [${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.`
4181
+ );
4182
+ continue;
4183
+ }
4184
+ const notifyAction = findNotifyAction(config, actionsValue.getElements());
4185
+ if (!notifyAction) {
4186
+ continue;
4187
+ }
4188
+ const declareAction = actionsValue.getElements().find(
4189
+ (action) => import_ts_morph3.Node.isObjectLiteralExpression(action) && isAction(action, DECLARE_ACTION_TYPE2)
4463
4190
  );
4464
- if (!startedLog) {
4465
- warnSkipped3(
4466
- `Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`
4191
+ const properties = NOTIFY_PROPERTIES.filter(
4192
+ ({ name }) => !findProperty(notifyAction, name)
4193
+ ).flatMap(({ name, helper, declareProperty }) => {
4194
+ const helperName = helperNames[helper];
4195
+ const reference = referenceOf(
4196
+ (declareAction && findProperty(declareAction, declareProperty)) ?? (declareProperty === DECLARATION_PROPERTY_NAME2 ? findProperty(config, declareProperty) : void 0)
4467
4197
  );
4468
- } else {
4469
- const indent = startedLog.getIndentationText();
4470
- const notice = [
4471
- `if (!env.TELEMETRY_ENABLED) {`,
4472
- ` logger.info(TELEMETRY_DISABLED_NOTICE)`,
4473
- `}`
4474
- ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4475
- sourceFile.insertText(startedLog.getEnd(), `
4476
-
4477
- ${notice}`);
4478
- console.log(` \u2713 ${INDEX_FILE}: telemetry-disabled startup notice`);
4479
- if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "./environment")) {
4480
- warnSkipped3(
4481
- `The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`
4198
+ if (!helperName) {
4199
+ console.warn(
4200
+ ` [${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}\`.`
4482
4201
  );
4202
+ return [];
4483
4203
  }
4204
+ if (!reference) {
4205
+ console.warn(
4206
+ ` [${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.`
4207
+ );
4208
+ return [];
4209
+ }
4210
+ if (helperName === helper) {
4211
+ usedHelpers.add(helper);
4212
+ }
4213
+ return [`${name}: ${helperName}(${reference})`];
4214
+ });
4215
+ if (properties.length === 0) {
4216
+ continue;
4484
4217
  }
4218
+ console.log(
4219
+ ` [${location(notifyAction)}] Added \`${properties.join("`, `")}\` to the ${NOTIFY_ACTION_TYPE} action`
4220
+ );
4221
+ edits.push(...insertIntoAction(notifyAction, properties));
4222
+ changes++;
4485
4223
  }
4224
+ if (changes === 0) {
4225
+ return 0;
4226
+ }
4227
+ applyTextEdits(sourceFile, edits);
4228
+ for (const helper of usedHelpers) {
4229
+ addToolkitImport(sourceFile, helper);
4230
+ }
4231
+ return changes;
4486
4232
  }
4487
- async function main4() {
4488
- const cwd = process.cwd();
4489
- const config = await promptTelemetryConfig();
4490
- console.log(
4491
- `
4492
- Adding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : "disabled"} by default)...
4493
- `
4494
- );
4495
- writeTelemetryHandler(cwd);
4233
+ async function main3() {
4234
+ const srcDir = import_path4.default.join(process.cwd(), "src");
4235
+ console.log(`Scanning for NOTIFY actions in: ${srcDir}
4236
+ `);
4496
4237
  const project = new import_ts_morph3.Project({
4497
- // ts-morph indents inserted code with four spaces and double-quotes strings
4498
- // by default, both of which the country config's prettier run would undo.
4499
- manipulationSettings: {
4500
- indentationText: import_ts_morph3.IndentationText.TwoSpaces,
4501
- quoteKind: import_ts_morph3.QuoteKind.Single
4502
- }
4238
+ tsConfigFilePath: import_path4.default.resolve(srcDir, "../tsconfig.json"),
4239
+ skipAddingFilesFromTsConfig: false
4503
4240
  });
4504
- addEnvironmentVariables(project, cwd, config);
4505
- wireIndex(project, cwd);
4506
- await project.save();
4507
- if (skipped3.length > 0) {
4508
- console.warn(
4509
- `
4510
- \u26A0\uFE0F ${skipped3.length} telemetry step(s) were skipped. Wire the following by hand:`
4511
- );
4512
- for (const message of skipped3) {
4513
- console.warn(` - ${message}`);
4241
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
4242
+ const fp = sf.getFilePath();
4243
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
4244
+ });
4245
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
4246
+ `);
4247
+ let totalChanges = 0;
4248
+ const modifiedFiles = [];
4249
+ for (const sourceFile of sourceFiles) {
4250
+ const changes = addNotifyConfig(sourceFile);
4251
+ if (changes > 0) {
4252
+ totalChanges += changes;
4253
+ modifiedFiles.push(sourceFile);
4514
4254
  }
4515
4255
  }
4256
+ if (modifiedFiles.length === 0) {
4257
+ console.log("No NOTIFY actions to update. Nothing to do.");
4258
+ return;
4259
+ }
4260
+ console.log(`
4261
+ Saving ${modifiedFiles.length} modified file(s)...`);
4262
+ for (const sourceFile of modifiedFiles) {
4263
+ await sourceFile.save();
4264
+ console.log(
4265
+ ` Saved: ${import_path4.default.relative(process.cwd(), sourceFile.getFilePath())}`
4266
+ );
4267
+ }
4268
+ console.log(
4269
+ `
4270
+ Done. Updated ${totalChanges} NOTIFY action(s) across ${modifiedFiles.length} file(s).`
4271
+ );
4516
4272
  }
4517
4273
 
4518
- // src/migrations/v2.1/migrate-infrastructure-to-assets.ts
4519
- var import_child_process = require("child_process");
4520
- var import_fs5 = require("fs");
4521
- var import_os = require("os");
4522
- var import_path6 = __toESM(require("path"));
4523
-
4524
- // src/migrations/v2.1/template-files.ts
4525
- var import_fs4 = require("fs");
4274
+ // src/migrations/read-declaration-through-helper.ts
4275
+ var import_ts_morph4 = require("ts-morph");
4526
4276
  var import_path5 = __toESM(require("path"));
4527
- function findTemplateDir() {
4528
- const candidates = [
4529
- import_path5.default.resolve(__dirname, "templates", "countryconfig-template"),
4530
- import_path5.default.resolve(__dirname, "../../../../countryconfig-template")
4531
- ];
4532
- const templateDir = candidates.find(
4533
- (candidate) => (0, import_fs4.existsSync)(import_path5.default.join(candidate, "Tiltfile"))
4534
- );
4535
- if (!templateDir) {
4536
- throw new Error(
4537
- `Country config template files not found in any of: ${candidates.join(", ")}`
4538
- );
4277
+ var EVENT_CONFIG_TYPE_NAME = "EventConfig";
4278
+ var DECLARATION_PROPERTY_NAME3 = "declaration";
4279
+ var GET_DECLARATION_NAME = "getDeclaration";
4280
+ function isToolkitEventConfig(type) {
4281
+ const nonNullableType = type.getNonNullableType();
4282
+ const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
4283
+ if (symbol?.getName() !== EVENT_CONFIG_TYPE_NAME) {
4284
+ return false;
4539
4285
  }
4540
- return templateDir;
4286
+ return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
4541
4287
  }
4542
- function listFiles(root, dir) {
4543
- const absolute = import_path5.default.join(root, dir);
4544
- if (!(0, import_fs4.existsSync)(absolute)) {
4545
- return [];
4546
- }
4547
- return (0, import_fs4.readdirSync)(absolute, { withFileTypes: true }).flatMap((entry) => {
4548
- const relative = import_path5.default.posix.join(dir, entry.name);
4549
- return entry.isDirectory() ? listFiles(root, relative) : [relative];
4550
- });
4288
+ function isDeclarationReadOnEventConfig(node) {
4289
+ return node.getName() === DECLARATION_PROPERTY_NAME3 && isToolkitEventConfig(node.getExpression().getType());
4551
4290
  }
4552
-
4553
- // src/migrations/v2.1/migrate-infrastructure-to-assets.ts
4554
- var INFRASTRUCTURE_DIR = "infrastructure";
4555
- var ASSETS_DIR = "assets";
4556
- var BASE_URL = "https://raw.githubusercontent.com/opencrvs/opencrvs-farajaland/release/v2.0.0/infrastructure";
4557
- var SOURCE_OF = {
4558
- "elasticsearch/reindex.sh": "deployment/reindex.sh"
4559
- };
4560
- var MIGRATED_DIRS = ["metabase", "postgres", "deployment", "elasticsearch"];
4561
- var NOT_MOVED = ["postgres/on-deploy.sh"];
4562
- var isMigrated = (file) => MIGRATED_DIRS.some((dir) => file.startsWith(`${dir}/`));
4563
- function tryGit(args2) {
4564
- try {
4565
- (0, import_child_process.execFileSync)("git", args2, { stdio: "ignore" });
4291
+ function isAssignmentOperator(kind) {
4292
+ return kind >= import_ts_morph4.SyntaxKind.FirstAssignment && kind <= import_ts_morph4.SyntaxKind.LastAssignment;
4293
+ }
4294
+ function isWriteTarget(node) {
4295
+ const parent = node.getParent();
4296
+ if (import_ts_morph4.Node.isDeleteExpression(parent)) {
4566
4297
  return true;
4567
- } catch {
4568
- return false;
4569
4298
  }
4299
+ return import_ts_morph4.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
4570
4300
  }
4571
- function assertIsGitRepo() {
4572
- if (!tryGit(["rev-parse", "--is-inside-work-tree"])) {
4573
- throw new Error(
4574
- `${process.cwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
4301
+ function location2(node) {
4302
+ const relPath = import_path5.default.relative(
4303
+ process.cwd(),
4304
+ node.getSourceFile().getFilePath()
4305
+ );
4306
+ return `${relPath}:${node.getStartLineNumber()}`;
4307
+ }
4308
+ function warnDestructuredDeclarations(sourceFile) {
4309
+ for (const pattern of sourceFile.getDescendantsOfKind(
4310
+ import_ts_morph4.SyntaxKind.ObjectBindingPattern
4311
+ )) {
4312
+ const destructuresDeclaration = pattern.getElements().some(
4313
+ (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME3
4575
4314
  );
4315
+ if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
4316
+ console.warn(
4317
+ ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME3}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
4318
+ );
4319
+ }
4576
4320
  }
4577
4321
  }
4578
- var toBytes = (buffer) => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
4579
- var sameBytes = (a, b) => a.length === b.length && a.every((byte, index) => byte === b[index]);
4580
- var isBinary = (contents) => contents.includes(0);
4581
- function readIfExists(file) {
4582
- return (0, import_fs5.existsSync)(file) ? toBytes((0, import_fs5.readFileSync)(file)) : void 0;
4583
- }
4584
- function mergeFile(file, ours, base, theirs) {
4585
- const dir = (0, import_fs5.mkdtempSync)(import_path6.default.join((0, import_os.tmpdir)(), "opencrvs-merge-assets-"));
4586
- try {
4587
- const [oursPath, basePath, theirsPath] = ["ours", "base", "theirs"].map(
4588
- (name) => import_path6.default.join(dir, name)
4322
+ function warnSpreadDeclarations(sourceFile) {
4323
+ for (const literal of sourceFile.getDescendantsOfKind(
4324
+ import_ts_morph4.SyntaxKind.ObjectLiteralExpression
4325
+ )) {
4326
+ const properties = literal.getProperties();
4327
+ const spreadsEventConfig = properties.some(
4328
+ (property) => import_ts_morph4.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
4589
4329
  );
4590
- (0, import_fs5.writeFileSync)(oursPath, ours);
4591
- (0, import_fs5.writeFileSync)(basePath, base);
4592
- (0, import_fs5.writeFileSync)(theirsPath, theirs);
4593
- const args2 = [
4594
- "merge-file",
4595
- "-q",
4596
- "-L",
4597
- `infrastructure/${file}`,
4598
- "-L",
4599
- "v2.0",
4600
- "-L",
4601
- `v2.1 template`,
4602
- oursPath,
4603
- basePath,
4604
- theirsPath
4605
- ];
4606
- let conflicts = 0;
4607
- try {
4608
- (0, import_child_process.execFileSync)("git", args2, { stdio: "ignore" });
4609
- } catch (error3) {
4610
- const { status } = error3;
4611
- if (!status || status >= 255) throw error3;
4612
- conflicts = status;
4330
+ const setsDeclaration = properties.some(
4331
+ (property) => (import_ts_morph4.Node.isPropertyAssignment(property) || import_ts_morph4.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME3
4332
+ );
4333
+ if (spreadsEventConfig && setsDeclaration) {
4334
+ console.warn(
4335
+ ` [${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.`
4336
+ );
4613
4337
  }
4614
- return { contents: toBytes((0, import_fs5.readFileSync)(oursPath)), conflicts };
4615
- } finally {
4616
- (0, import_fs5.rmSync)(dir, { recursive: true, force: true });
4617
4338
  }
4618
4339
  }
4619
- async function fetchBases(files) {
4620
- const bases = /* @__PURE__ */ new Map();
4621
- for (const file of files) {
4622
- const url = `${BASE_URL}/${file}`;
4623
- const response = await fetch(url);
4624
- if (response.ok) {
4625
- bases.set(file, new Uint8Array(await response.arrayBuffer()));
4626
- } else if (response.status !== 404) {
4627
- throw new Error(
4628
- `GitHub answered ${response.status} ${response.statusText} for ${url}`
4340
+ function rewriteDeclarationReads(sourceFile) {
4341
+ warnDestructuredDeclarations(sourceFile);
4342
+ warnSpreadDeclarations(sourceFile);
4343
+ const reads = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
4344
+ if (node.hasQuestionDotToken()) {
4345
+ console.warn(
4346
+ ` [${location2(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
4629
4347
  );
4348
+ return false;
4630
4349
  }
4350
+ if (isWriteTarget(node)) {
4351
+ console.warn(
4352
+ ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME3}\` on the DECLARE action instead.`
4353
+ );
4354
+ return false;
4355
+ }
4356
+ return true;
4357
+ }).sort((a, b) => b.getStart() - a.getStart());
4358
+ if (reads.length === 0) {
4359
+ return 0;
4360
+ }
4361
+ const getDeclarationName = findToolkitImportName(
4362
+ sourceFile,
4363
+ GET_DECLARATION_NAME
4364
+ );
4365
+ if (!getDeclarationName) {
4366
+ console.warn(
4367
+ ` [${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.`
4368
+ );
4369
+ return 0;
4370
+ }
4371
+ for (const read of reads) {
4372
+ console.log(
4373
+ ` [${location2(read)}] ${read.getText()} -> ${getDeclarationName}(${read.getExpression().getText()})`
4374
+ );
4375
+ read.replaceWithText(
4376
+ `${getDeclarationName}(${read.getExpression().getText()})`
4377
+ );
4378
+ }
4379
+ addToolkitImport(sourceFile, GET_DECLARATION_NAME);
4380
+ return reads.length;
4381
+ }
4382
+ async function main4() {
4383
+ const srcDir = import_path5.default.join(process.cwd(), "src");
4384
+ console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
4385
+ `);
4386
+ const project = new import_ts_morph4.Project({
4387
+ tsConfigFilePath: import_path5.default.resolve(srcDir, "../tsconfig.json"),
4388
+ skipAddingFilesFromTsConfig: false
4389
+ });
4390
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
4391
+ const fp = sf.getFilePath();
4392
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
4393
+ });
4394
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
4395
+ `);
4396
+ let totalChanges = 0;
4397
+ const modifiedFiles = [];
4398
+ for (const sourceFile of sourceFiles) {
4399
+ const changes = rewriteDeclarationReads(sourceFile);
4400
+ if (changes > 0) {
4401
+ totalChanges += changes;
4402
+ modifiedFiles.push(sourceFile);
4403
+ }
4404
+ }
4405
+ if (modifiedFiles.length === 0) {
4406
+ console.log("No EventConfig declaration reads found. Nothing to do.");
4407
+ return;
4408
+ }
4409
+ console.log(`
4410
+ Saving ${modifiedFiles.length} modified file(s)...`);
4411
+ for (const sourceFile of modifiedFiles) {
4412
+ await sourceFile.save();
4413
+ console.log(
4414
+ ` Saved: ${import_path5.default.relative(process.cwd(), sourceFile.getFilePath())}`
4415
+ );
4416
+ }
4417
+ console.log(
4418
+ `
4419
+ Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length} file(s).`
4420
+ );
4421
+ }
4422
+
4423
+ // src/migrations/resolve-versioned-event-config.ts
4424
+ var import_ts_morph5 = require("ts-morph");
4425
+ var import_path6 = __toESM(require("path"));
4426
+ var EVENT_CONFIG_TYPE_NAME2 = "EventConfig";
4427
+ var VERSIONED_EVENT_CONFIG_TYPE_NAME = "VersionedEventConfig";
4428
+ var RESOLVE_EVENT_CONFIG_NAME = "resolveEventConfig";
4429
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
4430
+ function isToolkitType(type, name) {
4431
+ const nonNullableType = type.getNonNullableType();
4432
+ const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
4433
+ if (symbol?.getName() !== name) {
4434
+ return false;
4435
+ }
4436
+ return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
4437
+ }
4438
+ function isVersionedEventConfig(type) {
4439
+ return isToolkitType(type, VERSIONED_EVENT_CONFIG_TYPE_NAME);
4440
+ }
4441
+ function isEventConfig(type) {
4442
+ return isToolkitType(type, EVENT_CONFIG_TYPE_NAME2);
4443
+ }
4444
+ function isArrayOf(type, isElement) {
4445
+ const elementType = type.getNonNullableType().getArrayElementType();
4446
+ return elementType !== void 0 && isElement(elementType);
4447
+ }
4448
+ function isVersionedField(type, name) {
4449
+ return type.getNonNullableType().getProperty(name) !== void 0;
4450
+ }
4451
+ function isAssignmentOperator2(kind) {
4452
+ return kind >= import_ts_morph5.SyntaxKind.FirstAssignment && kind <= import_ts_morph5.SyntaxKind.LastAssignment;
4453
+ }
4454
+ function isWriteTarget2(node) {
4455
+ const parent = node.getParent();
4456
+ if (import_ts_morph5.Node.isDeleteExpression(parent)) {
4457
+ return true;
4631
4458
  }
4632
- return bases;
4459
+ return import_ts_morph5.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator2(parent.getOperatorToken().getKind());
4633
4460
  }
4634
- function migrateInfrastructureToAssets(cwd, templateDir, readBase) {
4635
- const infrastructure = import_path6.default.join(cwd, INFRASTRUCTURE_DIR);
4636
- const templateAssets = import_path6.default.join(templateDir, ASSETS_DIR);
4637
- const relativeTo = (dir) => (file) => file.slice(dir.length + 1);
4638
- const localFiles = listFiles(cwd, INFRASTRUCTURE_DIR).map(relativeTo(INFRASTRUCTURE_DIR)).filter(isMigrated);
4639
- const templateFiles = listFiles(templateDir, ASSETS_DIR).map(
4640
- relativeTo(ASSETS_DIR)
4461
+ function location3(node) {
4462
+ const relPath = import_path6.default.relative(
4463
+ process.cwd(),
4464
+ node.getSourceFile().getFilePath()
4641
4465
  );
4642
- const outcomes = {};
4643
- const migrated = /* @__PURE__ */ new Set();
4644
- for (const file of [.../* @__PURE__ */ new Set([...templateFiles, ...localFiles])].sort()) {
4645
- const sourceFile = !localFiles.includes(file) && localFiles.includes(SOURCE_OF[file]) ? SOURCE_OF[file] : file;
4646
- const ours = readIfExists(import_path6.default.join(infrastructure, sourceFile));
4647
- const theirsPath = import_path6.default.join(templateAssets, file);
4648
- const theirs = readIfExists(theirsPath);
4649
- const base = ours && readBase(sourceFile);
4650
- const target = import_path6.default.join(cwd, ASSETS_DIR, file);
4651
- if (NOT_MOVED.includes(file)) {
4652
- if (ours && base && sameBytes(ours, base)) {
4653
- migrated.add(file);
4654
- outcomes[file] = "dropped";
4655
- } else if (ours) {
4656
- outcomes[file] = "not-moved";
4657
- }
4658
- continue;
4659
- }
4660
- const ownsSource = ours !== void 0 && sourceFile === file;
4661
- if ((0, import_fs5.existsSync)(target)) {
4662
- if (ownsSource) {
4663
- const same = sameBytes(toBytes((0, import_fs5.readFileSync)(target)), ours);
4664
- if (same) {
4665
- migrated.add(file);
4666
- }
4667
- outcomes[file] = same ? "exists" : "exists-differs";
4668
- }
4669
- continue;
4670
- }
4671
- if (ownsSource) {
4672
- migrated.add(file);
4673
- }
4674
- let contents;
4675
- let outcome;
4676
- if (!ours) {
4677
- contents = theirs;
4678
- outcome = "copied";
4679
- } else if (!theirs) {
4680
- const unchanged = base && sameBytes(ours, base);
4681
- contents = unchanged ? void 0 : ours;
4682
- outcome = unchanged ? "dropped" : "kept";
4683
- } else if (sameBytes(ours, theirs) || base && sameBytes(ours, base)) {
4684
- contents = theirs;
4685
- outcome = "copied";
4686
- } else if (!base || sameBytes(base, theirs) || isBinary(ours)) {
4687
- contents = ours;
4688
- outcome = "kept";
4689
- } else {
4690
- const result = mergeFile(sourceFile, ours, base, theirs);
4691
- contents = result.contents;
4692
- outcome = result.conflicts > 0 ? "conflict" : "merged";
4693
- }
4694
- outcomes[file] = outcome;
4695
- if (contents === void 0) {
4466
+ return `${relPath}:${node.getStartLineNumber()}`;
4467
+ }
4468
+ function warnDestructuredVersionFields(sourceFile) {
4469
+ for (const pattern of sourceFile.getDescendantsOfKind(
4470
+ import_ts_morph5.SyntaxKind.ObjectBindingPattern
4471
+ )) {
4472
+ const type = pattern.getType();
4473
+ if (!isVersionedEventConfig(type)) {
4696
4474
  continue;
4697
4475
  }
4698
- (0, import_fs5.mkdirSync)(import_path6.default.dirname(target), { recursive: true });
4699
- (0, import_fs5.writeFileSync)(target, contents);
4700
- const modeSource = ours && outcome === "kept" ? import_path6.default.join(infrastructure, sourceFile) : theirsPath;
4701
- if ((0, import_fs5.existsSync)(modeSource)) {
4702
- (0, import_fs5.chmodSync)(target, (0, import_fs5.statSync)(modeSource).mode & 511);
4476
+ const destructuresVersionField = pattern.getElements().some(
4477
+ (element) => !element.getDotDotDotToken() && !isVersionedField(
4478
+ type,
4479
+ element.getPropertyNameNode()?.getText() ?? element.getName()
4480
+ )
4481
+ );
4482
+ if (destructuresVersionField) {
4483
+ console.warn(
4484
+ ` [${location3(pattern)}] Destructures a field of a version from a VersionedEventConfig. Destructure it from \`${RESOLVE_EVENT_CONFIG_NAME}(config)\` by hand.`
4485
+ );
4703
4486
  }
4704
4487
  }
4705
- return { outcomes, migrated: [...migrated].sort() };
4706
4488
  }
4707
- function removeMigrated(cwd, migrated) {
4708
- const infrastructure = import_path6.default.join(cwd, INFRASTRUCTURE_DIR);
4709
- for (const file of migrated) {
4710
- (0, import_fs5.rmSync)(import_path6.default.join(infrastructure, file), { force: true });
4711
- }
4712
- const pruneEmpty = (dir) => {
4713
- if (!(0, import_fs5.existsSync)(dir)) {
4714
- return true;
4715
- }
4716
- const empty = (0, import_fs5.readdirSync)(dir, { withFileTypes: true }).map(
4717
- (entry) => entry.isDirectory() ? pruneEmpty(import_path6.default.join(dir, entry.name)) : false
4718
- ).every(Boolean);
4719
- if (empty) {
4720
- (0, import_fs5.rmdirSync)(dir);
4721
- }
4722
- return empty;
4723
- };
4724
- pruneEmpty(infrastructure);
4725
- }
4726
- var DESCRIPTIONS = {
4727
- copied: "from the template",
4728
- kept: "country's version",
4729
- merged: "merged",
4730
- conflict: "CONFLICT, resolve the markers by hand",
4731
- dropped: "dropped, no longer used",
4732
- exists: "already migrated",
4733
- "exists-differs": "already exists with different contents; infrastructure/ copy kept for review",
4734
- "not-moved": "changed locally but not moved: the chart runs its own on-deploy script, port your changes there"
4735
- };
4736
- async function main5(dockerSwarm = false) {
4737
- const cwd = process.cwd();
4738
- console.log("Moving infrastructure/ into assets/...\n");
4739
- const templateDir = findTemplateDir();
4740
- if ((0, import_fs5.existsSync)(import_path6.default.join(cwd, INFRASTRUCTURE_DIR))) {
4741
- assertIsGitRepo();
4742
- const needed = listFiles(cwd, INFRASTRUCTURE_DIR).map((file) => file.slice(INFRASTRUCTURE_DIR.length + 1)).filter(isMigrated);
4743
- let bases;
4744
- try {
4745
- bases = await fetchBases(needed);
4746
- } catch (error3) {
4489
+ function findVersionFieldReads(sourceFile) {
4490
+ return sourceFile.getDescendantsOfKind(import_ts_morph5.SyntaxKind.PropertyAccessExpression).filter((node) => {
4491
+ const type = node.getExpression().getType();
4492
+ return isVersionedEventConfig(type) && !isVersionedField(type, node.getName());
4493
+ }).filter((node) => {
4494
+ if (node.hasQuestionDotToken()) {
4747
4495
  console.warn(
4748
- ` \u26A0\uFE0F Could not read the v2.0 files to merge against (${error3.message}); infrastructure/ was not migrated. Re-run 'opencrvs upgrade' with network access.`
4496
+ ` [${location3(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${RESOLVE_EVENT_CONFIG_NAME}()\` by hand.`
4749
4497
  );
4750
- return;
4498
+ return false;
4751
4499
  }
4752
- const { outcomes, migrated } = migrateInfrastructureToAssets(
4753
- cwd,
4754
- templateDir,
4755
- (file) => bases.get(file)
4756
- );
4757
- for (const [file, outcome] of Object.entries(outcomes)) {
4758
- const needsReview = ["conflict", "not-moved", "exists-differs"].includes(
4759
- outcome
4500
+ if (isWriteTarget2(node)) {
4501
+ console.warn(
4502
+ ` [${location3(node)}] Skipped write to \`${node.getText()}\`. Set it in the version passed to \`defineConfig\` instead.`
4760
4503
  );
4761
- const shown = outcome === "not-moved" ? INFRASTRUCTURE_DIR : ASSETS_DIR;
4762
- const line2 = ` ${needsReview ? "\u26A0\uFE0F " : "\u2713"} ${shown}/${file}: ${DESCRIPTIONS[outcome]}`;
4763
- if (needsReview) {
4764
- console.warn(line2);
4765
- } else {
4766
- console.log(line2);
4767
- }
4504
+ return false;
4768
4505
  }
4769
- if (dockerSwarm) {
4770
- console.log(
4771
- "\n infrastructure/ kept in place (--docker-swarm); assets/ now holds a copy."
4772
- );
4773
- } else {
4774
- removeMigrated(cwd, migrated);
4506
+ return true;
4507
+ });
4508
+ }
4509
+ function isHandedOver(node) {
4510
+ const parent = node.getParent();
4511
+ if (import_ts_morph5.Node.isCallExpression(parent) || import_ts_morph5.Node.isNewExpression(parent)) {
4512
+ return parent.getArguments().includes(node);
4513
+ }
4514
+ return (import_ts_morph5.Node.isVariableDeclaration(parent) || import_ts_morph5.Node.isPropertyAssignment(parent)) && parent.getInitializer() === node || import_ts_morph5.Node.isReturnStatement(parent);
4515
+ }
4516
+ function findValuesExpectingEventConfig(sourceFile) {
4517
+ return sourceFile.getDescendants().filter((node) => import_ts_morph5.Node.isExpression(node)).filter(isHandedOver).map((node) => {
4518
+ const type = node.getType();
4519
+ const expectedType = node.getContextualType();
4520
+ if (!expectedType) {
4521
+ return void 0;
4775
4522
  }
4776
- tryGit(["add", "-A", "--", ASSETS_DIR, INFRASTRUCTURE_DIR]);
4777
- const conflicts = Object.keys(outcomes).filter(
4778
- (file) => outcomes[file] === "conflict"
4779
- );
4780
- for (const file of conflicts) {
4781
- tryGit(["restore", "--staged", "--", `${ASSETS_DIR}/${file}`]);
4523
+ if (isVersionedEventConfig(type) && isEventConfig(expectedType)) {
4524
+ return { node, isArray: false };
4782
4525
  }
4783
- if (conflicts.length > 0) {
4784
- console.warn(
4785
- `
4786
- \u26A0\uFE0F ${conflicts.length} file(s) need their conflicts resolved: ${conflicts.map((file) => `assets/${file}`).join(", ")}`
4787
- );
4526
+ if (isArrayOf(type, isVersionedEventConfig) && isArrayOf(expectedType, isEventConfig)) {
4527
+ return { node, isArray: true };
4788
4528
  }
4789
- if ((0, import_fs5.existsSync)(import_path6.default.join(cwd, INFRASTRUCTURE_DIR)) && !dockerSwarm) {
4529
+ return void 0;
4530
+ }).filter((value) => value !== void 0).filter(({ node }) => {
4531
+ if (node.getType().isNullable()) {
4790
4532
  console.warn(
4791
- " \u26A0\uFE0F infrastructure/ still has files the Kubernetes deployment does not use. Review and delete them if they are no longer needed."
4533
+ ` [${location3(node)}] Skipped \`${node.getText()}\`, which may be undefined where an EventConfig is expected. Narrow it and pass \`${RESOLVE_EVENT_CONFIG_NAME}(...)\` by hand.`
4792
4534
  );
4535
+ return false;
4793
4536
  }
4794
- } else {
4795
- console.log(" infrastructure/ not found, nothing to move.");
4796
- }
4797
- const dockerfile = toBytes(
4798
- (0, import_fs5.readFileSync)(import_path6.default.join(templateDir, "Dockerfile.assets"))
4799
- );
4800
- const current = readIfExists(import_path6.default.join(cwd, "Dockerfile.assets"));
4801
- if (!current || !sameBytes(current, dockerfile)) {
4802
- (0, import_fs5.writeFileSync)(import_path6.default.join(cwd, "Dockerfile.assets"), dockerfile);
4803
- tryGit(["add", "--", "Dockerfile.assets"]);
4804
- console.log(" \u2713 Dockerfile.assets replaced with the template version");
4805
- }
4537
+ return true;
4538
+ });
4806
4539
  }
4807
-
4808
- // src/migrations/v2.1/remove-metabase-package-installs.ts
4809
- var import_fs6 = require("fs");
4810
- var import_path7 = require("path");
4811
- var METABASE_DIRS = ["infrastructure/metabase", "assets/metabase"];
4812
- var APK_BLOCK = [
4813
- "apk update",
4814
- "apk upgrade",
4815
- "apk add --no-cache gettext",
4816
- "apk add --no-cache util-linux",
4817
- "",
4818
- ""
4819
- ].join("\n");
4820
- var SALT_LINE = "export OPENCRVS_METABASE_ADMIN_PASSWORD_SALT=$(uuidgen)\n";
4821
- var FIXED_SALT_LINE = "export OPENCRVS_METABASE_ADMIN_PASSWORD_SALT=$(cat /proc/sys/kernel/random/uuid 2>/dev/null || uuidgen)\n\n";
4822
- var FIXED_SALT_MARKER = "/proc/sys/kernel/random/uuid";
4823
- var ENVSUBST_GUARD = [
4824
- "if ! which envsubst >/dev/null; then",
4825
- ' echo "envsubst could not be found. Please install envsubst before continuing."',
4826
- ' echo "MacOS: brew install gettext && brew link --force gettext"',
4827
- " exit 1",
4828
- "fi",
4829
- ""
4830
- ].join("\n");
4831
- var ENVSUBST_CALL = "envsubst < $environment_configuration_sql_file > $environment_configuration_sql_file.tmp\n";
4832
- var FIXED_EXPANSION = [
4833
- "",
4834
- "# Expand $VAR / ${VAR} using bash's own heredoc expansion instead of envsubst,",
4835
- "# because envsubst is not installed in the Metabase image",
4836
- 'eval "cat <<OPENCRVS_ENV_EOF',
4837
- '$(cat "$environment_configuration_sql_file")',
4838
- 'OPENCRVS_ENV_EOF" > "$environment_configuration_sql_file.tmp"',
4839
- ""
4840
- ].join("\n");
4841
- var FIXED_EXPANSION_MARKER = "OPENCRVS_ENV_EOF";
4842
- function patchRunScript(source) {
4843
- if (source.includes(FIXED_SALT_MARKER) && !source.includes(APK_BLOCK)) {
4844
- return source;
4845
- }
4846
- if (!source.includes(APK_BLOCK) || !source.includes(SALT_LINE)) {
4847
- return void 0;
4848
- }
4849
- return source.replace(APK_BLOCK, "").replace(SALT_LINE, FIXED_SALT_LINE);
4540
+ function findToolkitImport2(sourceFile) {
4541
+ return sourceFile.getImportDeclaration(
4542
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2 && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
4543
+ );
4850
4544
  }
4851
- function patchUpdateDatabaseScript(source) {
4852
- if (source.includes(FIXED_EXPANSION_MARKER) && !source.includes(ENVSUBST_CALL)) {
4853
- return source;
4545
+ function findResolveEventConfigName(sourceFile) {
4546
+ const imported = findToolkitImport2(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === RESOLVE_EVENT_CONFIG_NAME);
4547
+ if (imported) {
4548
+ return imported.getAliasNode()?.getText() ?? RESOLVE_EVENT_CONFIG_NAME;
4854
4549
  }
4855
- if (!source.includes(ENVSUBST_GUARD) || !source.includes(ENVSUBST_CALL)) {
4550
+ if (sourceFile.getLocal(RESOLVE_EVENT_CONFIG_NAME)) {
4856
4551
  return void 0;
4857
4552
  }
4858
- return source.replace(ENVSUBST_GUARD, "").replace(ENVSUBST_CALL, FIXED_EXPANSION);
4553
+ return RESOLVE_EVENT_CONFIG_NAME;
4859
4554
  }
4860
- function patchFile(relativePath, patch, removed) {
4861
- const filePath = (0, import_path7.join)(process.cwd(), relativePath);
4862
- if (!(0, import_fs6.existsSync)(filePath)) {
4863
- return;
4864
- }
4865
- const source = (0, import_fs6.readFileSync)(filePath, "utf8");
4866
- const patched = patch(source);
4867
- if (patched === void 0) {
4868
- console.warn(
4869
- ` \u26A0\uFE0F ${relativePath} does not match the upstream v2.0 version, so it was left alone. Apply https://github.com/opencrvs/opencrvs-core/pull/13778 by hand, or Metabase will fail to start behind the chart's private egress policy.`
4555
+ function addResolveEventConfigImport(sourceFile) {
4556
+ const toolkitImport = findToolkitImport2(sourceFile);
4557
+ if (!toolkitImport) {
4558
+ const imports = sourceFile.getImportDeclarations();
4559
+ const lastImport = imports[imports.length - 1];
4560
+ sourceFile.insertStatements(
4561
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
4562
+ `import { ${RESOLVE_EVENT_CONFIG_NAME} } from '${TOOLKIT_EVENTS_MODULE2}'`
4870
4563
  );
4871
4564
  return;
4872
4565
  }
4873
- if (patched === source) {
4566
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === RESOLVE_EVENT_CONFIG_NAME);
4567
+ if (alreadyImported) {
4874
4568
  return;
4875
4569
  }
4876
- (0, import_fs6.writeFileSync)(filePath, patched);
4877
- console.log(` \u2713 ${relativePath}: ${removed}`);
4878
- }
4879
- async function main6() {
4880
- console.log("\nRemoving the Metabase package installs...\n");
4881
- for (const dir of METABASE_DIRS) {
4882
- patchFile((0, import_path7.join)(dir, "run.sh"), patchRunScript, "apk add gettext util-linux");
4883
- patchFile(
4884
- (0, import_path7.join)(dir, "update-database.sh"),
4885
- patchUpdateDatabaseScript,
4886
- "envsubst"
4887
- );
4570
+ const namedImports = toolkitImport.getNamedImports();
4571
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
4572
+ toolkitImport.addNamedImport(RESOLVE_EVENT_CONFIG_NAME);
4573
+ return;
4888
4574
  }
4889
- }
4890
-
4891
- // src/migrations/v2.1/remove-sentry.ts
4892
- var import_fs7 = require("fs");
4893
- var import_path8 = __toESM(require("path"));
4894
- var import_ts_morph4 = require("ts-morph");
4895
- var CONFIG_FILES = [
4896
- "src/client-config.ts",
4897
- "src/client-config.prod.ts",
4898
- "src/login-config.ts",
4899
- "src/login-config.prod.ts"
4900
- ];
4901
- var ENVIRONMENT_FILE2 = "src/environment.ts";
4902
- var CONSTANTS_FILE = "src/constants.ts";
4903
- var INDEX_FILE2 = "src/index.ts";
4904
- var UTILS_FILE = "src/utils/index.ts";
4905
- var PACKAGE_JSON_FILE = "package.json";
4906
- var TYPINGS_FILE = "typings/hapi-sentry.d.ts";
4907
- var SENTRY_PLUGIN = "hapi-sentry";
4908
- var skipped4 = [];
4909
- function warnSkipped4(message) {
4910
- skipped4.push(message);
4911
- console.warn(` \u26A0\uFE0F ${message}`);
4912
- }
4913
- function isReferenced(sourceFile, name) {
4914
- return sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.Identifier).some(
4915
- (identifier) => identifier.getText() === name && !identifier.getFirstAncestorByKind(import_ts_morph4.SyntaxKind.ImportDeclaration)
4575
+ const names = [
4576
+ ...namedImports.map((namedImport) => namedImport.getText()),
4577
+ RESOLVE_EVENT_CONFIG_NAME
4578
+ ];
4579
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
4580
+ ${names.join(",\n ")}
4581
+ }` : `{ ${names.join(", ")} }`;
4582
+ toolkitImport.replaceWithText(
4583
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE2}'`
4916
4584
  );
4917
4585
  }
4918
- function removeIfUnused(sourceFile, importDeclaration) {
4919
- const names = [
4920
- importDeclaration.getDefaultImport()?.getText(),
4921
- importDeclaration.getNamespaceImport()?.getText(),
4922
- ...importDeclaration.getNamedImports().map((named) => named.getName())
4923
- ].filter((name) => Boolean(name));
4924
- if (names.length > 0 && names.every((name) => !isReferenced(sourceFile, name))) {
4925
- importDeclaration.remove();
4926
- return true;
4927
- }
4928
- return false;
4586
+ function withToolkitEventsAt(compilerOptions, toolkitEventsPath) {
4587
+ return {
4588
+ ...compilerOptions,
4589
+ paths: {
4590
+ ...compilerOptions.paths,
4591
+ [TOOLKIT_EVENTS_MODULE2]: [toolkitEventsPath]
4592
+ }
4593
+ };
4929
4594
  }
4930
- function removeNamedImport(sourceFile, moduleSpecifier, name) {
4931
- const importDeclaration = sourceFile.getImportDeclarations().find(
4932
- (declaration) => declaration.getModuleSpecifierValue() === moduleSpecifier
4595
+ function rewriteVersionedEventConfigUses(sourceFile) {
4596
+ warnDestructuredVersionFields(sourceFile);
4597
+ const uses = [
4598
+ ...findVersionFieldReads(sourceFile).map((node) => ({
4599
+ node,
4600
+ rewrite: (name) => `${name}(${node.getExpression().getText()}).${node.getName()}`
4601
+ })),
4602
+ ...findValuesExpectingEventConfig(sourceFile).map(({ node, isArray }) => ({
4603
+ node,
4604
+ rewrite: (name) => isArray ? `${node.getText()}.map(${name})` : `${name}(${node.getText()})`
4605
+ }))
4606
+ ].sort(
4607
+ (a, b) => b.node.getStart() - a.node.getStart() || a.node.getEnd() - b.node.getEnd()
4933
4608
  );
4934
- if (!importDeclaration) return false;
4935
- const named = importDeclaration.getNamedImports().find((namedImport) => namedImport.getName() === name);
4936
- if (!named) return false;
4937
- named.remove();
4938
- if (importDeclaration.getNamedImports().length === 0 && !importDeclaration.getDefaultImport() && !importDeclaration.getNamespaceImport()) {
4939
- importDeclaration.remove();
4609
+ if (uses.length === 0) {
4610
+ return 0;
4940
4611
  }
4941
- return true;
4942
- }
4943
- function removeSentryFromConfigs(project, cwd) {
4944
- for (const file of CONFIG_FILES) {
4945
- const sourceFile = project.addSourceFileAtPathIfExists(import_path8.default.join(cwd, file));
4946
- if (!sourceFile) continue;
4947
- const property = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAssignment).find((assignment) => assignment.getName() === "SENTRY");
4948
- if (!property) continue;
4949
- const usedNames = new Set(
4950
- property.getDescendantsOfKind(import_ts_morph4.SyntaxKind.Identifier).map((identifier) => identifier.getText())
4612
+ const resolveEventConfigName = findResolveEventConfigName(sourceFile);
4613
+ if (!resolveEventConfigName) {
4614
+ console.warn(
4615
+ ` [${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.`
4951
4616
  );
4952
- property.remove();
4953
- for (const importDeclaration of [...sourceFile.getImportDeclarations()]) {
4954
- const imported = [
4955
- importDeclaration.getDefaultImport()?.getText(),
4956
- importDeclaration.getNamespaceImport()?.getText(),
4957
- ...importDeclaration.getNamedImports().map((named) => named.getName())
4958
- ].filter((name) => Boolean(name));
4959
- if (imported.some((name) => usedNames.has(name))) {
4960
- removeIfUnused(sourceFile, importDeclaration);
4961
- }
4962
- }
4963
- console.log(` \u2713 ${file}: SENTRY`);
4617
+ return 0;
4964
4618
  }
4619
+ for (const { node, rewrite } of uses) {
4620
+ const before = node.getText();
4621
+ const after = rewrite(resolveEventConfigName);
4622
+ console.log(` [${location3(node)}] ${before} -> ${after}`);
4623
+ node.replaceWithText(after);
4624
+ }
4625
+ addResolveEventConfigImport(sourceFile);
4626
+ return uses.length;
4965
4627
  }
4966
- function removeEnvironmentVariable(project, cwd) {
4967
- const sourceFile = project.addSourceFileAtPathIfExists(
4968
- import_path8.default.join(cwd, ENVIRONMENT_FILE2)
4628
+ async function main5() {
4629
+ const srcDir = import_path6.default.join(process.cwd(), "src");
4630
+ console.log(
4631
+ `Scanning for VersionedEventConfig used as an EventConfig in: ${srcDir}
4632
+ `
4969
4633
  );
4970
- if (!sourceFile) return;
4971
- const options = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
4972
- if (!options || !import_ts_morph4.Node.isObjectLiteralExpression(options)) {
4973
- warnSkipped4(
4974
- `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE2}; remove SENTRY_DSN by hand`
4634
+ const tsConfigFilePath = import_path6.default.resolve(srcDir, "../tsconfig.json");
4635
+ const project = new import_ts_morph5.Project({
4636
+ tsConfigFilePath,
4637
+ skipAddingFilesFromTsConfig: false,
4638
+ // The events module of this toolkit, next to the migrations in `dist`
4639
+ compilerOptions: withToolkitEventsAt(
4640
+ (0, import_ts_morph5.getCompilerOptionsFromTsConfig)(tsConfigFilePath).options,
4641
+ import_path6.default.resolve(__dirname, "../events")
4642
+ )
4643
+ });
4644
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
4645
+ const fp = sf.getFilePath();
4646
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
4647
+ });
4648
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
4649
+ `);
4650
+ let totalChanges = 0;
4651
+ const modifiedFiles = [];
4652
+ for (const sourceFile of sourceFiles) {
4653
+ const changes = rewriteVersionedEventConfigUses(sourceFile);
4654
+ if (changes > 0) {
4655
+ totalChanges += changes;
4656
+ modifiedFiles.push(sourceFile);
4657
+ }
4658
+ }
4659
+ if (modifiedFiles.length === 0) {
4660
+ console.log(
4661
+ "No VersionedEventConfig used as an EventConfig found. Nothing to do."
4975
4662
  );
4976
4663
  return;
4977
4664
  }
4978
- const property = options.getProperty("SENTRY_DSN");
4979
- if (!property) return;
4980
- property.remove();
4981
- console.log(` \u2713 ${ENVIRONMENT_FILE2}: SENTRY_DSN`);
4982
- }
4983
- function removeConstant(project, cwd) {
4984
- const sourceFile = project.addSourceFileAtPathIfExists(
4985
- import_path8.default.join(cwd, CONSTANTS_FILE)
4986
- );
4987
- if (!sourceFile) return;
4988
- for (const statement of [...sourceFile.getVariableStatements()]) {
4989
- const declarations = statement.getDeclarations();
4990
- const matching = declarations.filter(
4991
- (declaration) => declaration.getName() === "SENTRY_DSN" || /\benv\.SENTRY_DSN\b/.test(
4992
- declaration.getInitializer()?.getText() ?? ""
4993
- )
4665
+ console.log(`
4666
+ Saving ${modifiedFiles.length} modified file(s)...`);
4667
+ for (const sourceFile of modifiedFiles) {
4668
+ await sourceFile.save();
4669
+ console.log(
4670
+ ` Saved: ${import_path6.default.relative(process.cwd(), sourceFile.getFilePath())}`
4994
4671
  );
4995
- if (matching.length === 0) continue;
4996
- const names = matching.map((declaration) => declaration.getName());
4997
- if (matching.length === declarations.length) {
4998
- statement.remove();
4999
- } else {
5000
- for (const declaration of matching) {
5001
- declaration.remove();
5002
- }
5003
- }
5004
- console.log(` \u2713 ${CONSTANTS_FILE}: ${names.join(", ")}`);
5005
4672
  }
5006
- }
5007
- function unwireIndex(project, cwd) {
5008
- const sourceFile = project.addSourceFileAtPathIfExists(
5009
- import_path8.default.join(cwd, INDEX_FILE2)
5010
- );
5011
- if (!sourceFile) return;
5012
- const pluginImport = sourceFile.getImportDeclarations().find(
5013
- (declaration) => declaration.getModuleSpecifierValue() === SENTRY_PLUGIN
5014
- );
5015
- const pluginName = pluginImport?.getNamespaceImport()?.getText() ?? pluginImport?.getDefaultImport()?.getText() ?? "Sentry";
5016
- const registration = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.IfStatement).find(
5017
- (statement) => /\bSENTRY_DSN\b/.test(statement.getExpression().getText()) && new RegExp(`\\bplugin:\\s*${pluginName}\\b`).test(statement.getText())
4673
+ console.log(
4674
+ `
4675
+ Done. Rewrote ${totalChanges} use(s) across ${modifiedFiles.length} file(s).`
5018
4676
  );
5019
- if (registration) {
5020
- registration.remove();
5021
- console.log(` \u2713 ${INDEX_FILE2}: hapi-sentry plugin registration`);
5022
- } else if (sourceFile.getText().includes(SENTRY_PLUGIN)) {
5023
- warnSkipped4(
5024
- `Could not find the hapi-sentry plugin registration in ${INDEX_FILE2}; remove it by hand`
4677
+ }
4678
+
4679
+ // src/migrations/persistent/update-toolkit-dependency.ts
4680
+ var import_fs3 = __toESM(require("fs"));
4681
+ var import_path8 = __toESM(require("path"));
4682
+
4683
+ // src/migrations/persistent/check-upgrade-path.ts
4684
+ var import_fs2 = __toESM(require("fs"));
4685
+ var import_path7 = __toESM(require("path"));
4686
+ var TOOLKIT_PACKAGE_NAME = "@opencrvs/toolkit";
4687
+ function findMajorMinor(version) {
4688
+ const match = /(\d+)\.(\d+)/.exec(version);
4689
+ return match ? { major: Number(match[1]), minor: Number(match[2]) } : void 0;
4690
+ }
4691
+ function format({ major, minor }) {
4692
+ return `${major}.${minor}`;
4693
+ }
4694
+ function findCountryConfigToolkitVersion(cwd) {
4695
+ try {
4696
+ const packageJson = JSON.parse(
4697
+ import_fs2.default.readFileSync(import_path7.default.join(cwd, "package.json"), "utf-8")
5025
4698
  );
4699
+ return packageJson.dependencies?.[TOOLKIT_PACKAGE_NAME] ?? packageJson.devDependencies?.[TOOLKIT_PACKAGE_NAME];
4700
+ } catch {
4701
+ return void 0;
5026
4702
  }
5027
- const scopeExtension = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.ExpressionStatement).find(
5028
- (statement) => statement.getText().includes("sentryScope") && statement.getText().startsWith("server.ext")
5029
- );
5030
- if (scopeExtension) {
5031
- scopeExtension.remove();
5032
- console.log(` \u2713 ${INDEX_FILE2}: onRequest Sentry scope extension`);
5033
- } else if (sourceFile.getText().includes("sentryScope")) {
5034
- warnSkipped4(
5035
- `Found 'sentryScope' in ${INDEX_FILE2} outside a server.ext(...) call; remove it by hand`
5036
- );
4703
+ }
4704
+ function checkUpgradePath(countryConfigToolkitVersion, toolkitVersion) {
4705
+ const target = findMajorMinor(toolkitVersion);
4706
+ const current = countryConfigToolkitVersion ? findMajorMinor(countryConfigToolkitVersion) : void 0;
4707
+ if (!target || !current) {
4708
+ return {
4709
+ status: "unknown",
4710
+ 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.`
4711
+ };
5037
4712
  }
5038
- if (pluginImport && removeIfUnused(sourceFile, pluginImport)) {
5039
- console.log(` \u2713 ${INDEX_FILE2}: import '${SENTRY_PLUGIN}'`);
4713
+ const isSameVersion = current.major === target.major && current.minor === target.minor;
4714
+ const isPreviousMinor = current.major === target.major && current.minor === target.minor - 1;
4715
+ const isPreviousMajor = target.minor === 0 && current.major === target.major - 1;
4716
+ if (isSameVersion || isPreviousMinor || isPreviousMajor) {
4717
+ return { status: "ok" };
5040
4718
  }
5041
- if (!isReferenced(sourceFile, "SENTRY_DSN")) {
5042
- for (const declaration of [...sourceFile.getImportDeclarations()]) {
5043
- const specifier = declaration.getModuleSpecifierValue();
5044
- if (removeNamedImport(sourceFile, specifier, "SENTRY_DSN")) {
5045
- console.log(` \u2713 ${INDEX_FILE2}: import SENTRY_DSN from '${specifier}'`);
5046
- break;
5047
- }
5048
- }
4719
+ const isNewer = current.major > target.major || current.major === target.major && current.minor > target.minor;
4720
+ if (isNewer) {
4721
+ return {
4722
+ status: "blocked",
4723
+ 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.`
4724
+ };
5049
4725
  }
4726
+ const upgradesFrom = target.minor > 0 ? format({ major: target.major, minor: target.minor - 1 }) : `the last ${target.major - 1}.x`;
4727
+ const nextStep = current.major === target.major ? `: run \`npx ${TOOLKIT_PACKAGE_NAME}@${format({ major: current.major, minor: current.minor + 1 })} upgrade\` first` : "";
4728
+ return {
4729
+ status: "blocked",
4730
+ message: `The country config is on ${format(current)}, but toolkit ${toolkitVersion} only upgrades from ${upgradesFrom}. Upgrade one minor version at a time${nextStep}.`
4731
+ };
5050
4732
  }
5051
- function removeApplicationConfigField(project, cwd) {
5052
- const sourceFile = project.addSourceFileAtPathIfExists(
5053
- import_path8.default.join(cwd, UTILS_FILE)
5054
- );
5055
- if (!sourceFile) return;
5056
- const property = sourceFile.getInterface("IApplicationConfig")?.getProperty("SENTRY");
5057
- if (!property) return;
5058
- property.remove();
5059
- console.log(` \u2713 ${UTILS_FILE}: IApplicationConfig.SENTRY`);
5060
- }
5061
- function isSentryPackage(name) {
5062
- return name === SENTRY_PLUGIN || name.startsWith("@sentry/");
5063
- }
5064
- function removeDependencies(cwd) {
5065
- const packageJsonPath = import_path8.default.join(cwd, PACKAGE_JSON_FILE);
5066
- if (!(0, import_fs7.existsSync)(packageJsonPath)) return;
5067
- const raw = (0, import_fs7.readFileSync)(packageJsonPath, "utf8");
5068
- let parsed;
5069
- try {
5070
- parsed = JSON.parse(raw);
5071
- } catch (error3) {
5072
- warnSkipped4(
5073
- `${PACKAGE_JSON_FILE} could not be parsed (${error3.message}); remove the Sentry dependencies by hand`
5074
- );
5075
- return;
5076
- }
5077
- const removed = [];
5078
- for (const bucket of ["dependencies", "devDependencies"]) {
5079
- const dependencies = parsed[bucket];
5080
- if (!dependencies) continue;
5081
- for (const name of Object.keys(dependencies)) {
5082
- if (isSentryPackage(name)) {
5083
- delete dependencies[name];
5084
- removed.push(name);
4733
+
4734
+ // src/migrations/persistent/update-toolkit-dependency.ts
4735
+ var DEPENDENCY_PATTERN = new RegExp(
4736
+ `("${TOOLKIT_PACKAGE_NAME}"\\s*:\\s*")([^"]*)(")`,
4737
+ "g"
4738
+ );
4739
+ function updateToolkitDependency(packageJson, toolkitVersion) {
4740
+ const updated = packageJson.replace(
4741
+ DEPENDENCY_PATTERN,
4742
+ (match, before, version, after) => {
4743
+ if (!findMajorMinor(version)) {
4744
+ return match;
5085
4745
  }
4746
+ const range = /^[\^~]?/.exec(version)?.[0] ?? "";
4747
+ return `${before}${range}${toolkitVersion}${after}`;
5086
4748
  }
5087
- }
5088
- if (removed.length === 0) return;
5089
- const trailingNewline = raw.endsWith("\n") ? "\n" : "";
5090
- (0, import_fs7.writeFileSync)(
5091
- packageJsonPath,
5092
- `${JSON.stringify(parsed, null, 2)}${trailingNewline}`
5093
4749
  );
5094
- console.log(` \u2713 ${PACKAGE_JSON_FILE}: ${removed.join(", ")}`);
5095
- }
5096
- function removeTypings(cwd) {
5097
- const typingsPath = import_path8.default.join(cwd, TYPINGS_FILE);
5098
- if (!(0, import_fs7.existsSync)(typingsPath)) return;
5099
- const declarations = (0, import_fs7.readFileSync)(typingsPath, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "").trim();
5100
- if (!/^declare module ['"]hapi-sentry['"];?$/.test(declarations)) {
5101
- warnSkipped4(
5102
- `${TYPINGS_FILE} declares more than the 'hapi-sentry' module; remove the declaration by hand`
5103
- );
4750
+ return updated === packageJson ? void 0 : updated;
4751
+ }
4752
+ async function main6(toolkitVersion) {
4753
+ const packageJsonPath = import_path8.default.join(process.cwd(), "package.json");
4754
+ if (!import_fs3.default.existsSync(packageJsonPath)) {
4755
+ console.log(`No package.json found. Skipping ${TOOLKIT_PACKAGE_NAME}.`);
5104
4756
  return;
5105
4757
  }
5106
- (0, import_fs7.rmSync)(typingsPath);
5107
- console.log(` \u2713 ${TYPINGS_FILE}: deleted`);
5108
- }
5109
- async function main7() {
5110
- const cwd = process.cwd();
5111
- console.log("\nRemoving Sentry...\n");
5112
- const project = new import_ts_morph4.Project({
5113
- // ts-morph indents with four spaces and double-quotes strings by default,
5114
- // both of which the country config's prettier run would undo.
5115
- manipulationSettings: {
5116
- indentationText: import_ts_morph4.IndentationText.TwoSpaces,
5117
- quoteKind: import_ts_morph4.QuoteKind.Single
5118
- }
5119
- });
5120
- removeSentryFromConfigs(project, cwd);
5121
- removeEnvironmentVariable(project, cwd);
5122
- removeConstant(project, cwd);
5123
- unwireIndex(project, cwd);
5124
- removeApplicationConfigField(project, cwd);
5125
- await project.save();
5126
- removeDependencies(cwd);
5127
- removeTypings(cwd);
5128
- if (skipped4.length > 0) {
5129
- console.warn(
5130
- `
5131
- \u26A0\uFE0F ${skipped4.length} Sentry removal step(s) were skipped. Handle the following by hand:`
4758
+ const updated = updateToolkitDependency(
4759
+ import_fs3.default.readFileSync(packageJsonPath, "utf-8"),
4760
+ toolkitVersion
4761
+ );
4762
+ if (!updated) {
4763
+ console.log(
4764
+ `${TOOLKIT_PACKAGE_NAME} in package.json needs no update. Nothing to do.`
5132
4765
  );
5133
- for (const message of skipped4) {
5134
- console.warn(` - ${message}`);
5135
- }
4766
+ return;
5136
4767
  }
4768
+ import_fs3.default.writeFileSync(packageJsonPath, updated);
4769
+ console.log(
4770
+ `Updated ${TOOLKIT_PACKAGE_NAME} to ${toolkitVersion} in package.json. Install the dependencies again to use it.`
4771
+ );
5137
4772
  }
5138
4773
 
5139
- // src/migrations/v2.1/rename-trigger-paths.ts
5140
- var import_ts_morph5 = require("ts-morph");
4774
+ // src/migrations/replace-incomplete-flag.ts
4775
+ var import_ts_morph6 = require("ts-morph");
5141
4776
  var import_path9 = __toESM(require("path"));
5142
- var PATH_PREFIX_RENAMES = {
5143
- "/triggers/user/": "/trigger/user/",
5144
- "/triggers/system/": "/trigger/system/"
5145
- };
5146
- var STALE_PREFIX = "/triggers/";
5147
- var METHOD_PROPERTY_NAME = "method";
5148
- var PATH_PROPERTY_NAME = "path";
5149
- var HTTP_VERBS = /* @__PURE__ */ new Set([
5150
- "GET",
5151
- "POST",
5152
- "PUT",
5153
- "PATCH",
5154
- "DELETE",
5155
- "OPTIONS",
5156
- "HEAD",
5157
- "*"
5158
- ]);
5159
- function isRouteConfig(obj) {
5160
- const methodProp = obj.getProperty(METHOD_PROPERTY_NAME);
5161
- if (!methodProp || !import_ts_morph5.Node.isPropertyAssignment(methodProp)) return false;
5162
- const methodInit = methodProp.getInitializer();
5163
- if (!methodInit) return false;
5164
- if (import_ts_morph5.Node.isStringLiteral(methodInit)) {
5165
- if (!HTTP_VERBS.has(methodInit.getLiteralValue().toUpperCase()))
5166
- return false;
5167
- } else if (import_ts_morph5.Node.isArrayLiteralExpression(methodInit)) {
5168
- const allVerbs = methodInit.getElements().every(
5169
- (el) => import_ts_morph5.Node.isStringLiteral(el) && HTTP_VERBS.has(el.getLiteralValue().toUpperCase())
5170
- );
5171
- if (!allVerbs) return false;
5172
- } else {
5173
- return false;
5174
- }
5175
- const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
5176
- if (!pathProp || !import_ts_morph5.Node.isPropertyAssignment(pathProp)) return false;
5177
- const pathInit = pathProp.getInitializer();
5178
- return !!pathInit && import_ts_morph5.Node.isStringLiteral(pathInit);
5179
- }
5180
- function renameRoutePath(obj) {
5181
- const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
5182
- if (!pathProp || !import_ts_morph5.Node.isPropertyAssignment(pathProp)) return null;
5183
- const pathInit = pathProp.getInitializer();
5184
- if (!pathInit || !import_ts_morph5.Node.isStringLiteral(pathInit)) return null;
5185
- const oldPath = pathInit.getLiteralValue();
5186
- const match = Object.entries(PATH_PREFIX_RENAMES).find(
5187
- ([from2]) => oldPath.startsWith(from2)
5188
- );
5189
- if (!match) return null;
5190
- const [from, to] = match;
5191
- const newPath = to + oldPath.slice(from.length);
5192
- pathInit.replaceWithText(`'${newPath}'`);
5193
- return newPath;
5194
- }
5195
- function processFile2(filePath, project) {
5196
- const sourceFile = project.getSourceFile(filePath);
5197
- if (!sourceFile) return 0;
5198
- let renamedCount = 0;
5199
- const relPath = import_path9.default.relative(process.cwd(), filePath);
5200
- const candidates = sourceFile.getDescendantsOfKind(
5201
- import_ts_morph5.SyntaxKind.ObjectLiteralExpression
4777
+ var INCOMPLETE = "InherentFlags.INCOMPLETE";
4778
+ var NOTIFIED_STATUS = `{ type: 'exact', term: EventStatus.enum.NOTIFIED }`;
4779
+ function ensureEventStatusImport(sourceFile) {
4780
+ const importDeclaration = sourceFile.getImportDeclarations().find(
4781
+ (declaration) => declaration.getNamedImports().some((named) => named.getName() === "InherentFlags")
5202
4782
  );
5203
- for (const obj of candidates) {
5204
- if (!isRouteConfig(obj)) continue;
5205
- const newPath = renameRoutePath(obj);
5206
- if (newPath) {
5207
- renamedCount++;
5208
- console.log(` [${relPath}] Renamed route path \u2192 '${newPath}'`);
5209
- }
4783
+ const hasEventStatus = importDeclaration?.getNamedImports().some((named) => named.getName() === "EventStatus");
4784
+ if (importDeclaration && !hasEventStatus) {
4785
+ importDeclaration.addNamedImport("EventStatus");
5210
4786
  }
5211
- return renamedCount;
5212
4787
  }
5213
- function warnAboutStalePaths(sourceFiles) {
5214
- const stale = [];
5215
- for (const sourceFile of sourceFiles) {
5216
- const relPath = import_path9.default.relative(process.cwd(), sourceFile.getFilePath());
5217
- const lines = sourceFile.getFullText().split("\n");
5218
- lines.forEach((line2, index) => {
5219
- if (line2.includes(STALE_PREFIX)) {
5220
- stale.push(` ${relPath}:${index + 1}: ${line2.trim()}`);
5221
- }
5222
- });
4788
+ function replaceIncompleteFlag(sourceFile) {
4789
+ let changed = false;
4790
+ 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) => {
4791
+ const anyOf = array2.getParent();
4792
+ const flags = anyOf?.getParent()?.getParent();
4793
+ return import_ts_morph6.Node.isPropertyAssignment(anyOf) && anyOf.getName() === "anyOf" && import_ts_morph6.Node.isPropertyAssignment(flags) && flags.getName() === "flags";
4794
+ });
4795
+ for (const array2 of anyOfIncomplete) {
4796
+ const anyOf = array2.getParentIfKindOrThrow(import_ts_morph6.SyntaxKind.PropertyAssignment);
4797
+ const flagsObject = anyOf.getParentIfKindOrThrow(
4798
+ import_ts_morph6.SyntaxKind.ObjectLiteralExpression
4799
+ );
4800
+ const flags = flagsObject.getParentIfKindOrThrow(
4801
+ import_ts_morph6.SyntaxKind.PropertyAssignment
4802
+ );
4803
+ const query = flags.getParentIfKindOrThrow(
4804
+ import_ts_morph6.SyntaxKind.ObjectLiteralExpression
4805
+ );
4806
+ array2.getElements().filter((element) => element.getText() === INCOMPLETE).forEach((element) => array2.removeElement(element));
4807
+ if (array2.getElements().length === 0) anyOf.remove();
4808
+ if (flagsObject.getProperties().length === 0) flags.remove();
4809
+ if (!query.getProperty("status")) {
4810
+ query.addPropertyAssignment({
4811
+ name: "status",
4812
+ initializer: NOTIFIED_STATUS
4813
+ });
4814
+ }
4815
+ changed = true;
5223
4816
  }
5224
- if (stale.length === 0) return;
5225
- console.log(
5226
- `
5227
- WARNING: ${stale.length} remaining '${STALE_PREFIX}' reference(s) need to be renamed by hand:`
5228
- );
5229
- console.log(stale.join("\n"));
4817
+ if (changed) ensureEventStatusImport(sourceFile);
4818
+ const remaining = sourceFile.getDescendantsOfKind(import_ts_morph6.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
4819
+ return { changed, remaining };
5230
4820
  }
5231
- async function main8() {
5232
- const srcDir = import_path9.default.join(process.cwd(), "src");
5233
- console.log(`Scanning for Hapi route configs in: ${srcDir}
5234
- `);
5235
- console.log("Active path renames:");
5236
- for (const [from, to] of Object.entries(PATH_PREFIX_RENAMES)) {
5237
- console.log(` '${from}*' \u2192 '${to}*'`);
5238
- }
5239
- console.log();
5240
- const project = new import_ts_morph5.Project({
5241
- tsConfigFilePath: import_path9.default.resolve(srcDir, "../tsconfig.json"),
5242
- skipAddingFilesFromTsConfig: false
5243
- });
5244
- const sourceFiles = project.getSourceFiles().filter((sf) => {
5245
- const fp = sf.getFilePath();
5246
- return fp.includes("/src/") && !fp.includes("/node_modules/");
4821
+ async function main7() {
4822
+ const project = new import_ts_morph6.Project({
4823
+ tsConfigFilePath: import_path9.default.join(process.cwd(), "tsconfig.json")
5247
4824
  });
5248
- console.log(`Found ${sourceFiles.length} source file(s) to analyse.
5249
- `);
5250
- let totalRenamed = 0;
5251
- const modifiedFiles = [];
4825
+ const sourceFiles = project.getSourceFiles().filter((sf) => !sf.getFilePath().includes("/node_modules/"));
5252
4826
  for (const sourceFile of sourceFiles) {
5253
- const filePath = sourceFile.getFilePath();
5254
- const renamed = processFile2(filePath, project);
5255
- if (renamed > 0) {
5256
- totalRenamed += renamed;
5257
- modifiedFiles.push(filePath);
5258
- }
5259
- }
5260
- if (modifiedFiles.length === 0) {
5261
- console.log("No trigger route paths to rename.");
5262
- } else {
5263
- console.log(`
5264
- Saving ${modifiedFiles.length} modified file(s)...`);
5265
- for (const filePath of modifiedFiles) {
5266
- const sourceFile = project.getSourceFileOrThrow(filePath);
4827
+ const relPath = import_path9.default.relative(process.cwd(), sourceFile.getFilePath());
4828
+ const { changed, remaining } = replaceIncompleteFlag(sourceFile);
4829
+ if (changed) {
5267
4830
  await sourceFile.save();
5268
- console.log(` Saved: ${import_path9.default.relative(process.cwd(), filePath)}`);
4831
+ console.log(
4832
+ ` [${relPath}] Replaced the incomplete flag with the NOTIFIED status`
4833
+ );
5269
4834
  }
5270
- console.log(`
5271
- Done. Renamed ${totalRenamed} route path(s).`);
5272
- }
5273
- warnAboutStalePaths(sourceFiles);
5274
- }
5275
-
5276
- // src/migrations/v2.1/upgrade-tilt.ts
5277
- var import_fs8 = require("fs");
5278
- var import_path10 = __toESM(require("path"));
5279
- var COUNTRY_OWNED_DIR = "tilt/helm/";
5280
- var CHARTS_CHECKOUT_DIR = ".opencrvs-core-charts";
5281
- var IMAGE_NAME_PATTERN = /^countryconfig_image_name\s*=\s*(["'])(.*?)\1/m;
5282
- function writeIfChanged(cwd, relativePath, contents, mode) {
5283
- const target = import_path10.default.join(cwd, relativePath);
5284
- const existed = (0, import_fs8.existsSync)(target);
5285
- if (existed && (0, import_fs8.readFileSync)(target, "utf8") === contents) {
5286
- return "unchanged";
5287
- }
5288
- (0, import_fs8.mkdirSync)(import_path10.default.dirname(target), { recursive: true });
5289
- (0, import_fs8.writeFileSync)(target, contents);
5290
- if (mode !== void 0) {
5291
- (0, import_fs8.chmodSync)(target, mode & 511);
5292
- }
5293
- return existed ? "updated" : "created";
5294
- }
5295
- function report(relativePath, change) {
5296
- if (change !== "unchanged") {
5297
- console.log(` \u2713 ${change} ${relativePath}`);
5298
- }
5299
- }
5300
- function renderTiltfile(template, existing) {
5301
- const imageName = existing?.match(IMAGE_NAME_PATTERN)?.[2];
5302
- if (!imageName) {
5303
- return template;
5304
- }
5305
- return template.replace(
5306
- IMAGE_NAME_PATTERN,
5307
- (_line, quote) => `countryconfig_image_name=${quote}${imageName}${quote}`
5308
- );
5309
- }
5310
- function withIgnoreEntry(contents, line2) {
5311
- const normalise = (entry) => entry.trim().replace(/^\//, "").replace(/\/$/, "");
5312
- const alreadyIgnored = contents.split(/\r?\n/).some((entry) => normalise(entry) === normalise(line2));
5313
- if (alreadyIgnored) {
5314
- return contents;
5315
- }
5316
- const separator = contents === "" || contents.endsWith("\n") ? "" : "\n";
5317
- return `${contents}${separator}${line2}
5318
- `;
5319
- }
5320
- function ensureIgnored(cwd, file, line2) {
5321
- const target = import_path10.default.join(cwd, file);
5322
- const contents = (0, import_fs8.existsSync)(target) ? (0, import_fs8.readFileSync)(target, "utf8") : "";
5323
- report(file, writeIfChanged(cwd, file, withIgnoreEntry(contents, line2)));
5324
- }
5325
- function upgradeTilt(cwd, templateDir) {
5326
- const tiltfilePath = import_path10.default.join(cwd, "Tiltfile");
5327
- const existingTiltfile = (0, import_fs8.existsSync)(tiltfilePath) ? (0, import_fs8.readFileSync)(tiltfilePath, "utf8") : void 0;
5328
- report(
5329
- "Tiltfile",
5330
- writeIfChanged(
5331
- cwd,
5332
- "Tiltfile",
5333
- renderTiltfile(
5334
- (0, import_fs8.readFileSync)(import_path10.default.join(templateDir, "Tiltfile"), "utf8"),
5335
- existingTiltfile
5336
- )
5337
- )
5338
- );
5339
- const templateFiles = listFiles(templateDir, "tilt");
5340
- for (const file of templateFiles) {
5341
- const source = import_path10.default.join(templateDir, file);
5342
- const countryOwned = file.startsWith(COUNTRY_OWNED_DIR);
5343
- if (countryOwned && (0, import_fs8.existsSync)(import_path10.default.join(cwd, file))) {
5344
- continue;
4835
+ for (const line2 of remaining) {
4836
+ console.warn(
4837
+ ` [${relPath}:${line2}] ${INCOMPLETE} was removed, update this reference to use the NOTIFIED status`
4838
+ );
5345
4839
  }
5346
- report(
5347
- file,
5348
- writeIfChanged(
5349
- cwd,
5350
- file,
5351
- (0, import_fs8.readFileSync)(source, "utf8"),
5352
- (0, import_fs8.statSync)(source).mode
5353
- )
5354
- );
5355
- }
5356
- const unknownFiles = listFiles(cwd, "tilt").filter(
5357
- (file) => !file.startsWith(COUNTRY_OWNED_DIR) && !templateFiles.includes(file)
5358
- );
5359
- for (const file of unknownFiles) {
5360
- console.warn(
5361
- ` \u26A0\uFE0F ${file} is not part of the template and was left in place.`
5362
- );
5363
- }
5364
- ensureIgnored(cwd, ".tiltignore", `${CHARTS_CHECKOUT_DIR}/`);
5365
- ensureIgnored(cwd, ".gitignore", CHARTS_CHECKOUT_DIR);
5366
- if (existingTiltfile?.includes("opencrvs-helm-charts")) {
5367
- console.log(
5368
- ` \u2139\uFE0F The Tiltfile no longer uses ../opencrvs-helm-charts; charts are cloned into ${CHARTS_CHECKOUT_DIR}/ instead. The old checkout can be deleted.`
5369
- );
5370
4840
  }
5371
4841
  }
5372
- async function main9() {
5373
- console.log("Upgrading the local Tilt setup...\n");
5374
- upgradeTilt(process.cwd(), findTemplateDir());
5375
- console.log(
5376
- "\n Review local customisations with: git diff -- Tiltfile tilt/ .tiltignore .gitignore\n"
5377
- );
5378
- }
5379
4842
 
5380
- // src/migrations/v2.1/index.ts
5381
- async function runUpgrade(dockerSwarm) {
5382
- await main();
5383
- await main8();
4843
+ // src/migrations/index.ts
4844
+ async function runUpgrade(toolkitVersion) {
4845
+ const [major, minor] = toolkitVersion.split(".");
5384
4846
  await main2();
5385
4847
  await main3();
5386
- await main7();
5387
- await main6();
5388
- await main5(dockerSwarm);
5389
- await main9();
4848
+ await main5();
5390
4849
  await main4();
4850
+ await main(`${major}.${minor}`);
4851
+ await main7();
4852
+ await main6(toolkitVersion);
5391
4853
  }
5392
4854
 
5393
4855
  // src/environment/index.ts
5394
- var import_fs13 = require("fs");
5395
- var import_path15 = require("path");
4856
+ var import_fs8 = require("fs");
4857
+ var import_path14 = require("path");
5396
4858
  init_paths();
5397
4859
  var REQUIRED_REPOSITORY_DIRECTORIES = [
5398
4860
  ".github/workflows",
@@ -5403,7 +4865,7 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
5403
4865
  const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
5404
4866
  (directory) => {
5405
4867
  try {
5406
- return !(0, import_fs13.statSync)((0, import_path15.resolve)(repositoryRoot, directory)).isDirectory();
4868
+ return !(0, import_fs8.statSync)((0, import_path14.resolve)(repositoryRoot, directory)).isDirectory();
5407
4869
  } catch {
5408
4870
  return true;
5409
4871
  }
@@ -5444,7 +4906,7 @@ async function runEnvironmentSwarmToK8s() {
5444
4906
  // src/verify/endpoints.ts
5445
4907
  var import_colors = require("kleur/colors");
5446
4908
  var z = __toESM(require("zod/v4"));
5447
- var REQUEST_TIMEOUT_MS = 15e3;
4909
+ var REQUEST_TIMEOUT_MS2 = 15e3;
5448
4910
  var DEFAULT_TARGET_URL = "http://localhost:3040";
5449
4911
  var REQUIRED_PUBLIC_ENDPOINTS = [
5450
4912
  { method: "GET", path: "/client-config.js" },
@@ -5515,7 +4977,7 @@ async function requestStatus(url, method) {
5515
4977
  try {
5516
4978
  const response = await fetch(url, {
5517
4979
  method,
5518
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
4980
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2),
5519
4981
  // Sent without an Authorization header on purpose. A secured route
5520
4982
  // rejects with 401/403 before ever reading the body.
5521
4983
  headers: method === "POST" ? { "Content-Type": "application/json" } : void 0,
@@ -5526,40 +4988,30 @@ async function requestStatus(url, method) {
5526
4988
  return "error";
5527
4989
  }
5528
4990
  }
5529
- function toEventTriggerConfig(value) {
5530
- if (typeof value !== "object" || value === null) {
5531
- return null;
5532
- }
5533
- const record2 = value;
5534
- if (typeof record2.id !== "string") {
5535
- return null;
5536
- }
5537
- const actions = Array.isArray(record2.actions) ? Array.from(
5538
- new Set(
5539
- record2.actions.map((action) => {
5540
- if (typeof action !== "object" || action === null) {
5541
- return null;
5542
- }
5543
- const type = action.type;
5544
- return typeof type === "string" ? type : null;
5545
- }).filter((type) => type !== null)
5546
- )
5547
- ) : [];
5548
- return { id: record2.id, actions };
4991
+ var ServedEventConfigVersion = z.object({
4992
+ actions: z.array(z.object({ type: z.string() }))
4993
+ });
4994
+ var ServedEventConfig = z.union([
4995
+ z.object({ id: z.string(), versions: z.array(ServedEventConfigVersion) }),
4996
+ ServedEventConfigVersion.extend({ id: z.string() })
4997
+ ]);
4998
+ function toEventTriggerConfig(config) {
4999
+ const versions = "versions" in config ? config.versions : [config];
5000
+ const actions = versions.flatMap(
5001
+ (version) => version.actions.map(({ type }) => type)
5002
+ );
5003
+ return { id: config.id, actions: Array.from(new Set(actions)) };
5549
5004
  }
5550
5005
  async function fetchEventConfigs(baseUrl) {
5551
5006
  try {
5552
5007
  const response = await fetch(`${baseUrl}/config/events`, {
5553
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
5008
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
5554
5009
  });
5555
5010
  if (!response.ok) {
5556
5011
  return null;
5557
5012
  }
5558
- const body = await response.json();
5559
- if (!Array.isArray(body)) {
5560
- return null;
5561
- }
5562
- return body.map(toEventTriggerConfig).filter((config) => config !== null);
5013
+ const parsed = z.array(ServedEventConfig).safeParse(await response.json());
5014
+ return parsed.success ? parsed.data.map(toEventTriggerConfig) : null;
5563
5015
  } catch {
5564
5016
  return null;
5565
5017
  }
@@ -5614,7 +5066,7 @@ var ServedTranslations = z.object({
5614
5066
  async function fetchServedTranslations(baseUrl, application) {
5615
5067
  try {
5616
5068
  const response = await fetch(`${baseUrl}/content/${application}`, {
5617
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
5069
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
5618
5070
  });
5619
5071
  if (!response.ok) {
5620
5072
  return null;
@@ -5630,10 +5082,10 @@ async function verifyTranslations(baseUrl) {
5630
5082
  let refs;
5631
5083
  try {
5632
5084
  refs = await candidateRefs(TEMPLATE_VERSION);
5633
- } catch (error3) {
5085
+ } catch (error2) {
5634
5086
  console.log(
5635
5087
  " " + (0, import_colors.yellow)(
5636
- `Could not list the ${TEMPLATE_VERSION} refs on GitHub (${error3.message}); translations not checked.`
5088
+ `Could not list the ${TEMPLATE_VERSION} refs on GitHub (${error2.message}); translations not checked.`
5637
5089
  )
5638
5090
  );
5639
5091
  return 0;
@@ -5644,10 +5096,10 @@ async function verifyTranslations(baseUrl) {
5644
5096
  let fetched;
5645
5097
  try {
5646
5098
  fetched = await fetchTemplate(refs, application);
5647
- } catch (error3) {
5099
+ } catch (error2) {
5648
5100
  console.log(
5649
5101
  " " + (0, import_colors.yellow)(
5650
- `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${endpoint} not checked.`
5102
+ `Could not read ${application}.csv from the country config template on GitHub (${error2.message}); ${endpoint} not checked.`
5651
5103
  )
5652
5104
  );
5653
5105
  continue;
@@ -5730,8 +5182,8 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
5730
5182
  console.log(line(ok, endpointLabel(check), detail));
5731
5183
  }
5732
5184
  {
5733
- const path14 = `/fonts/${PROBE_SEGMENT}.ttf`;
5734
- const status = await requestStatus(`${baseUrl}${path14}`, "GET");
5185
+ const path15 = `/fonts/${PROBE_SEGMENT}.ttf`;
5186
+ const status = await requestStatus(`${baseUrl}${path15}`, "GET");
5735
5187
  const ok = status === 200 || status === 404;
5736
5188
  if (!ok) {
5737
5189
  failures++;
@@ -5746,7 +5198,7 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
5746
5198
  } else {
5747
5199
  detail = `${describeStatus(status)} \u2014 unexpected`;
5748
5200
  }
5749
- console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path14}`)}`, detail));
5201
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path15}`)}`, detail));
5750
5202
  }
5751
5203
  console.log();
5752
5204
  console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
@@ -5799,13 +5251,13 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
5799
5251
  line(true, pattern, `${actions.length} action(s) \u2014 all require auth`)
5800
5252
  );
5801
5253
  } else {
5802
- for (const failure of failed) {
5254
+ for (const failure2 of failed) {
5803
5255
  failures++;
5804
5256
  console.log(
5805
5257
  line(
5806
5258
  false,
5807
- `POST /trigger/events/${event.id}/actions/${failure.action}`,
5808
- securedDetail(failure.status)
5259
+ `POST /trigger/events/${event.id}/actions/${failure2.action}`,
5260
+ securedDetail(failure2.status)
5809
5261
  )
5810
5262
  );
5811
5263
  }
@@ -5873,18 +5325,20 @@ Exits with a non-zero status if any check fails.
5873
5325
  var UPGRADE_USAGE = `
5874
5326
  Usage: opencrvs upgrade [options]
5875
5327
 
5876
- Upgrade the country config in the current working directory to the next
5877
- major version of OpenCRVS.
5328
+ Upgrade the country config in the current working directory to this toolkit's
5329
+ version of OpenCRVS. Upgrade one minor version at a time: toolkit 2.2 upgrades
5330
+ a country config on 2.1.
5331
+
5332
+ The upgrade tells which version the country config is on by its
5333
+ @opencrvs/toolkit dependency, and updates that dependency itself once done.
5334
+ Run it without changing the dependency first, e.g.
5335
+
5336
+ npx @opencrvs/toolkit@2.2 upgrade
5878
5337
 
5879
5338
  Options:
5880
- --docker-swarm Keep the 'infrastructure/' directory where it is and
5881
- only copy what the assets image needs into 'assets/'.
5882
- Use this if your country deploys OpenCRVS via Docker
5883
- Swarm. When omitted, 'infrastructure/' moves to
5884
- 'assets/' (default).
5885
5339
  -h, --help Show this message.
5886
5340
  `.trim();
5887
- function main10() {
5341
+ function main8() {
5888
5342
  const command = args[0];
5889
5343
  if (!command || command === "--help" || command === "-h") {
5890
5344
  console.log(USAGE);
@@ -5946,37 +5400,52 @@ Subcommands:
5946
5400
  async function runEnvironmentCommand(operation, command) {
5947
5401
  try {
5948
5402
  await command();
5949
- } catch (error3) {
5403
+ } catch (error2) {
5950
5404
  console.error(
5951
5405
  `Environment ${operation} failed:`,
5952
- error3 instanceof Error ? error3.message : error3
5406
+ error2 instanceof Error ? error2.message : error2
5953
5407
  );
5954
5408
  process.exit(1);
5955
5409
  }
5956
5410
  }
5411
+ function readToolkitVersion() {
5412
+ const packageJson = JSON.parse(
5413
+ import_fs9.default.readFileSync(import_path15.default.join(__dirname, "..", "package.json"), "utf-8")
5414
+ );
5415
+ return packageJson.version;
5416
+ }
5957
5417
  async function handleUpgrade() {
5958
5418
  const upgradeArgs = args.slice(1);
5959
5419
  if (upgradeArgs.includes("--help") || upgradeArgs.includes("-h")) {
5960
5420
  console.log(UPGRADE_USAGE);
5961
5421
  process.exit(0);
5962
5422
  }
5963
- const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--docker-swarm"]);
5964
- const unknownFlags = upgradeArgs.filter(
5965
- (arg) => arg.startsWith("-") && !KNOWN_FLAGS.has(arg)
5966
- );
5423
+ const unknownFlags = upgradeArgs.filter((arg) => arg.startsWith("-"));
5967
5424
  if (unknownFlags.length > 0) {
5968
5425
  console.error(`Unknown option(s): ${unknownFlags.join(", ")}
5969
5426
  `);
5970
5427
  console.log(UPGRADE_USAGE);
5971
5428
  process.exit(1);
5972
5429
  }
5973
- const dockerSwarm = upgradeArgs.includes("--docker-swarm");
5430
+ const toolkitVersion = readToolkitVersion();
5431
+ const upgradePath = checkUpgradePath(
5432
+ findCountryConfigToolkitVersion(process.cwd()),
5433
+ toolkitVersion
5434
+ );
5435
+ if (upgradePath.status === "unknown") {
5436
+ console.warn(`\u26A0\uFE0F ${upgradePath.message}
5437
+ `);
5438
+ }
5439
+ if (upgradePath.status === "blocked") {
5440
+ console.error(upgradePath.message);
5441
+ process.exit(1);
5442
+ }
5974
5443
  console.log("Initiating upgrade...");
5975
5444
  try {
5976
- await runUpgrade(dockerSwarm);
5445
+ await runUpgrade(toolkitVersion);
5977
5446
  console.log("Upgrade completed successfully!");
5978
- } catch (error3) {
5979
- console.error("Upgrade failed:", error3);
5447
+ } catch (error2) {
5448
+ console.error("Upgrade failed:", error2);
5980
5449
  process.exit(1);
5981
5450
  }
5982
5451
  }
@@ -5997,12 +5466,12 @@ async function handleVerifyEndpoints() {
5997
5466
  }
5998
5467
  try {
5999
5468
  await runVerifyEndpoints(positional[0]);
6000
- } catch (error3) {
5469
+ } catch (error2) {
6001
5470
  console.error(
6002
5471
  "Endpoint verification failed:",
6003
- error3 instanceof Error ? error3.message : error3
5472
+ error2 instanceof Error ? error2.message : error2
6004
5473
  );
6005
5474
  process.exit(1);
6006
5475
  }
6007
5476
  }
6008
- main10();
5477
+ main8();