@opencrvs/toolkit 2.1.0 → 2.2.0-rc.3af310b

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 (136) hide show
  1. package/build.sh +2 -12
  2. package/create-countryconfig/package.json +1 -1
  3. package/dist/application-config/index.js +36 -4
  4. package/dist/authentication/index.js +14 -2
  5. package/dist/cli.js +961 -2033
  6. package/dist/commons/api/router.d.ts +1374 -71
  7. package/dist/commons/conditionals/conditionals.d.ts +3 -3
  8. package/dist/commons/events/ActionConfig.d.ts +146 -20
  9. package/dist/commons/events/ActionDocument.d.ts +88 -0
  10. package/dist/commons/events/ActionInput.d.ts +52 -0
  11. package/dist/commons/events/ActionType.d.ts +11 -1
  12. package/dist/commons/events/AdvancedSearchConfig.d.ts +12 -0
  13. package/dist/commons/events/AuditLog.d.ts +4 -0
  14. package/dist/commons/events/CountryConfigQueryInput.d.ts +192 -18
  15. package/dist/commons/events/Draft.d.ts +2 -0
  16. package/dist/commons/events/EventConfig.d.ts +36 -6
  17. package/dist/commons/events/EventDocument.d.ts +88 -0
  18. package/dist/commons/events/EventIndex.d.ts +41 -4
  19. package/dist/commons/events/EventMetadata.d.ts +23 -1
  20. package/dist/commons/events/EventStatus.d.ts +1 -0
  21. package/dist/commons/events/FieldConfig.d.ts +10 -0
  22. package/dist/commons/events/Flag.d.ts +0 -6
  23. package/dist/commons/events/WorkqueueConfig.d.ts +224 -33
  24. package/dist/commons/events/eventConfigValidation.d.ts +26 -1
  25. package/dist/commons/events/notificationFormFallback.d.ts +10 -0
  26. package/dist/commons/events/scopes.d.ts +2 -0
  27. package/dist/commons/events/state/flags.d.ts +1 -1
  28. package/dist/commons/events/state/index.d.ts +10 -2
  29. package/dist/commons/events/state/utils.d.ts +11 -1
  30. package/dist/commons/events/test.utils.d.ts +31 -1
  31. package/dist/commons/events/utils.d.ts +53 -20
  32. package/dist/conditionals/index.js +14 -2
  33. package/dist/environment/derived-variables.d.ts +24 -0
  34. package/dist/environment/derived-variables.d.ts.map +1 -1
  35. package/dist/environment/derived-variables.js +28 -0
  36. package/dist/environment/dockerhub.d.ts +15 -0
  37. package/dist/environment/dockerhub.d.ts.map +1 -0
  38. package/dist/environment/dockerhub.js +104 -0
  39. package/dist/environment/questions.js +1 -1
  40. package/dist/environment/setup-environment.d.ts.map +1 -1
  41. package/dist/environment/setup-environment.js +70 -12
  42. package/dist/environment/templates.d.ts.map +1 -1
  43. package/dist/events/index.js +461 -83
  44. package/dist/migrations/index.d.ts +9 -0
  45. package/dist/migrations/index.d.ts.map +1 -0
  46. package/dist/migrations/index.js +847 -0
  47. package/dist/migrations/move-declaration-to-declare-action.d.ts +38 -0
  48. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -0
  49. package/dist/migrations/move-declaration-to-declare-action.js +377 -0
  50. package/dist/migrations/{v2.1 → persistent}/add-translations.d.ts +7 -1
  51. package/dist/migrations/persistent/add-translations.d.ts.map +1 -0
  52. package/dist/migrations/{v2.1 → persistent}/add-translations.js +14 -12
  53. package/dist/migrations/persistent/check-upgrade-path.d.ts +36 -0
  54. package/dist/migrations/persistent/check-upgrade-path.d.ts.map +1 -0
  55. package/dist/migrations/persistent/check-upgrade-path.js +105 -0
  56. package/dist/migrations/persistent/update-toolkit-dependency.d.ts +7 -0
  57. package/dist/migrations/persistent/update-toolkit-dependency.d.ts.map +1 -0
  58. package/dist/migrations/persistent/update-toolkit-dependency.js +77 -0
  59. package/dist/migrations/read-declaration-through-helper.d.ts +39 -0
  60. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -0
  61. package/dist/migrations/read-declaration-through-helper.js +257 -0
  62. package/dist/migrations/replace-incomplete-flag.d.ts +26 -0
  63. package/dist/migrations/replace-incomplete-flag.d.ts.map +1 -0
  64. package/dist/migrations/replace-incomplete-flag.js +126 -0
  65. package/dist/notification/index.js +401 -100
  66. package/dist/scopes/index.d.ts +29 -39
  67. package/dist/scopes/index.js +14 -2
  68. package/dist/templates/charts-values/dependencies/values.yaml +1 -1
  69. package/dist/templates/charts-values/opencrvs-services/values.yaml +1 -2
  70. package/dist/templates/charts-values/traefik/values.yaml +4 -3
  71. package/opencrvs-toolkit-2.2.0-rc.3af310b.tgz +0 -0
  72. package/package.json +1 -1
  73. package/tsconfig.build.tsbuildinfo +1 -1
  74. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts +0 -3
  75. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts.map +0 -1
  76. package/dist/migrations/v2.1/add-explicit-correction-flags.js +0 -234
  77. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +0 -3
  78. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +0 -1
  79. package/dist/migrations/v2.1/add-recovery-link-notifications.js +0 -511
  80. package/dist/migrations/v2.1/add-translations.d.ts.map +0 -1
  81. package/dist/migrations/v2.1/enable-telemetry.d.ts +0 -3
  82. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +0 -1
  83. package/dist/migrations/v2.1/enable-telemetry.js +0 -455
  84. package/dist/migrations/v2.1/index.d.ts +0 -6
  85. package/dist/migrations/v2.1/index.d.ts.map +0 -1
  86. package/dist/migrations/v2.1/index.js +0 -2170
  87. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +0 -14
  88. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +0 -1
  89. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +0 -348
  90. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +0 -2
  91. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +0 -1
  92. package/dist/migrations/v2.1/remove-metabase-package-installs.js +0 -161
  93. package/dist/migrations/v2.1/remove-sentry.d.ts +0 -3
  94. package/dist/migrations/v2.1/remove-sentry.d.ts.map +0 -1
  95. package/dist/migrations/v2.1/remove-sentry.js +0 -354
  96. package/dist/migrations/v2.1/rename-trigger-paths.d.ts +0 -3
  97. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +0 -1
  98. package/dist/migrations/v2.1/rename-trigger-paths.js +0 -216
  99. package/dist/migrations/v2.1/template-files.d.ts +0 -8
  100. package/dist/migrations/v2.1/template-files.d.ts.map +0 -1
  101. package/dist/migrations/v2.1/template-files.js +0 -49
  102. package/dist/migrations/v2.1/upgrade-tilt.d.ts +0 -8
  103. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +0 -1
  104. package/dist/migrations/v2.1/upgrade-tilt.js +0 -139
  105. package/dist/templates/countryconfig-template/.tiltignore +0 -1
  106. package/dist/templates/countryconfig-template/Dockerfile.assets +0 -7
  107. package/dist/templates/countryconfig-template/Tiltfile +0 -112
  108. package/dist/templates/countryconfig-template/assets/README.md +0 -1
  109. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +0 -61
  110. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +0 -455
  111. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +0 -168
  112. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +0 -67
  113. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +0 -168
  114. package/dist/templates/countryconfig-template/assets/metabase/README.md +0 -34
  115. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +0 -36
  116. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +0 -46
  117. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +0 -27737
  118. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +0 -21
  119. package/dist/templates/countryconfig-template/assets/metabase/package.json +0 -13
  120. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +0 -108
  121. package/dist/templates/countryconfig-template/assets/metabase/run.sh +0 -120
  122. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +0 -40
  123. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +0 -135
  124. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +0 -108
  125. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +0 -50
  126. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +0 -35
  127. package/dist/templates/countryconfig-template/tilt/common.tilt +0 -145
  128. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +0 -15
  129. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +0 -56
  130. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +0 -21
  131. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +0 -38
  132. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +0 -17
  133. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +0 -16
  134. package/dist/templates/countryconfig-template/tilt/lib.tilt +0 -95
  135. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +0 -136
  136. package/opencrvs-toolkit-2.1.0.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_path7.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_path7.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_path7.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_path7, 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_path7 = require("path");
59
59
  glob = __toESM(require("glob"));
60
- OLD_INVENTORY_DIR = (0, import_path11.join)(
60
+ OLD_INVENTORY_DIR = (0, import_path7.join)(
61
61
  "infrastructure",
62
62
  "server-setup",
63
63
  "inventory"
@@ -479,12 +479,40 @@ var init_derived_variables = __esm({
479
479
  type: "disabled",
480
480
  scope: "ENVIRONMENT"
481
481
  },
482
+ {
483
+ name: "RESTORE_ENVIRONMENT_MODE",
484
+ valueLabel: "RESTORE_ENVIRONMENT_MODE",
485
+ valueType: "VARIABLE",
486
+ type: "disabled",
487
+ scope: "ENVIRONMENT"
488
+ },
489
+ {
490
+ name: "RESTORE_HOST",
491
+ valueLabel: "RESTORE_HOST",
492
+ valueType: "VARIABLE",
493
+ type: "disabled",
494
+ scope: "ENVIRONMENT"
495
+ },
482
496
  {
483
497
  name: "NOTIFICATION_TRANSPORT",
484
498
  valueLabel: "NOTIFICATION_TRANSPORT",
485
499
  valueType: "VARIABLE",
486
500
  type: "disabled",
487
501
  scope: "ENVIRONMENT"
502
+ },
503
+ {
504
+ name: "TWO_FA_ENABLED",
505
+ valueLabel: "TWO_FA_ENABLED",
506
+ valueType: "VARIABLE",
507
+ type: "disabled",
508
+ scope: "ENVIRONMENT"
509
+ },
510
+ {
511
+ name: "MONITORING_ENABLED",
512
+ valueLabel: "MONITORING_ENABLED",
513
+ valueType: "VARIABLE",
514
+ type: "disabled",
515
+ scope: "ENVIRONMENT"
488
516
  }
489
517
  ];
490
518
  }
@@ -504,7 +532,7 @@ function findExistingValue(name, type, scope, existingValues) {
504
532
  );
505
533
  }
506
534
  function readYamlFile(filePath) {
507
- const fileContent = import_fs9.default.readFileSync(filePath, "utf8");
535
+ const fileContent = import_fs4.default.readFileSync(filePath, "utf8");
508
536
  return yaml.load(fileContent);
509
537
  }
510
538
  function writeYamlFile(filePath, data) {
@@ -517,16 +545,16 @@ function writeYamlFile(filePath, data) {
517
545
  noRefs: true,
518
546
  sortKeys: false
519
547
  });
520
- import_fs9.default.writeFileSync(filePath, yamlContent, "utf8");
521
- } catch (error3) {
522
- throw new Error(`Failed to write inventory file: ${error3}`);
548
+ import_fs4.default.writeFileSync(filePath, yamlContent, "utf8");
549
+ } catch (error2) {
550
+ throw new Error(`Failed to write inventory file: ${error2}`);
523
551
  }
524
552
  }
525
- var import_fs9, yaml;
553
+ var import_fs4, yaml;
526
554
  var init_utils = __esm({
527
555
  "src/environment/utils.ts"() {
528
556
  "use strict";
529
- import_fs9 = __toESM(require("fs"));
557
+ import_fs4 = __toESM(require("fs"));
530
558
  yaml = __toESM(require("js-yaml"));
531
559
  }
532
560
  });
@@ -575,29 +603,29 @@ function extractWorkerNodes(data) {
575
603
  return worker_hosts;
576
604
  }
577
605
  function copyChartsValues(env, values) {
578
- const srcDir = import_path12.default.resolve(__dirname, "templates", "charts-values");
579
- const destDir = import_path12.default.resolve(process.cwd(), "environments", env);
580
- import_fs10.default.mkdirSync(destDir, { recursive: true });
606
+ const srcDir = import_path8.default.resolve(__dirname, "templates", "charts-values");
607
+ const destDir = import_path8.default.resolve(process.cwd(), "environments", env);
608
+ import_fs5.default.mkdirSync(destDir, { recursive: true });
581
609
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
582
610
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
583
611
  values["opencrvs_environment"] = env;
584
612
  function copyRecursive(src, dest) {
585
- const stat = import_fs10.default.statSync(src);
613
+ const stat = import_fs5.default.statSync(src);
586
614
  if (stat.isDirectory()) {
587
- import_fs10.default.mkdirSync(dest, { recursive: true });
588
- for (const item of import_fs10.default.readdirSync(src)) {
589
- copyRecursive(import_path12.default.join(src, item), import_path12.default.join(dest, item));
615
+ import_fs5.default.mkdirSync(dest, { recursive: true });
616
+ for (const item of import_fs5.default.readdirSync(src)) {
617
+ copyRecursive(import_path8.default.join(src, item), import_path8.default.join(dest, item));
590
618
  }
591
619
  } else {
592
- const content = import_fs10.default.readFileSync(src, "utf8");
620
+ const content = import_fs5.default.readFileSync(src, "utf8");
593
621
  const template = import_handlebars.default.compile(content);
594
622
  const updated = template(values);
595
623
  const isOverridesFile = dest.endsWith("override.yaml");
596
- if (isOverridesFile && import_fs10.default.existsSync(dest)) {
624
+ if (isOverridesFile && import_fs5.default.existsSync(dest)) {
597
625
  log(` \u21B7 Skipped existing overrides file: ${dest}`);
598
626
  return;
599
627
  }
600
- import_fs10.default.writeFileSync(dest, updated, "utf8");
628
+ import_fs5.default.writeFileSync(dest, updated, "utf8");
601
629
  log(` \u2713 Created: ${dest}`);
602
630
  }
603
631
  }
@@ -608,29 +636,32 @@ function copyChartsValues(env, values) {
608
636
  `);
609
637
  }
610
638
  function generateInventory(env, values) {
611
- const templatePath = import_path12.default.join(
639
+ const templatePath = import_path8.default.join(
612
640
  __dirname,
613
641
  "templates",
614
642
  "inventory",
615
643
  "inventory.template.yml"
616
644
  );
617
- const outputPath = import_path12.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
618
- const templateFile = import_fs10.default.readFileSync(templatePath, "utf-8");
645
+ const outputPath = import_path8.default.resolve(
646
+ process.cwd(),
647
+ getEnvironmentInventoryPath(env)
648
+ );
649
+ const templateFile = import_fs5.default.readFileSync(templatePath, "utf-8");
619
650
  const template = import_handlebars.default.compile(templateFile);
620
651
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
621
652
  const updated = template(values);
622
- import_fs10.default.mkdirSync(import_path12.default.dirname(outputPath), { recursive: true });
623
- import_fs10.default.writeFileSync(outputPath, updated);
653
+ import_fs5.default.mkdirSync(import_path8.default.dirname(outputPath), { recursive: true });
654
+ import_fs5.default.writeFileSync(outputPath, updated);
624
655
  log(`
625
656
  \u2705 Generated inventory file at ${outputPath}
626
657
  `);
627
658
  }
628
- var import_fs10, import_path12, import_handlebars;
659
+ var import_fs5, import_path8, import_handlebars;
629
660
  var init_templates = __esm({
630
661
  "src/environment/templates.ts"() {
631
662
  "use strict";
632
- import_fs10 = __toESM(require("fs"));
633
- import_path12 = __toESM(require("path"));
663
+ import_fs5 = __toESM(require("fs"));
664
+ import_path8 = __toESM(require("path"));
634
665
  init_logger();
635
666
  init_paths();
636
667
  import_handlebars = __toESM(require("handlebars"));
@@ -661,16 +692,16 @@ var update_workflows_exports = {};
661
692
  __export(update_workflows_exports, {
662
693
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
663
694
  });
664
- function isDirectory(path14) {
695
+ function isDirectory(path12) {
665
696
  try {
666
- return (0, import_fs11.statSync)(path14).isDirectory();
697
+ return (0, import_fs6.statSync)(path12).isDirectory();
667
698
  } catch {
668
699
  return false;
669
700
  }
670
701
  }
671
702
  async function extractInfrastructureNames() {
672
- const files = glob2.sync((0, import_path13.join)("environments", "*", INVENTORY_FILE_NAME));
673
- const infraEnvironments = files.map((file) => (0, import_path13.basename)((0, import_path13.dirname)(file)));
703
+ const files = glob2.sync((0, import_path9.join)("environments", "*", INVENTORY_FILE_NAME));
704
+ const infraEnvironments = files.map((file) => (0, import_path9.basename)((0, import_path9.dirname)(file)));
674
705
  if (infraEnvironments.length === 0) {
675
706
  console.log(
676
707
  `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
@@ -683,9 +714,9 @@ async function extractInfrastructureNames() {
683
714
  async function extractEnvironmentNames() {
684
715
  const entries = await (0, import_promises.readdir)("environments");
685
716
  const environments = entries.filter((entry) => {
686
- const environmentPath = (0, import_path13.join)("environments", entry);
687
- const opencrvsServicesPath = (0, import_path13.join)(environmentPath, "opencrvs-services");
688
- return isDirectory(environmentPath) && (0, import_fs11.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
717
+ const environmentPath = (0, import_path9.join)("environments", entry);
718
+ const opencrvsServicesPath = (0, import_path9.join)(environmentPath, "opencrvs-services");
719
+ return isDirectory(environmentPath) && (0, import_fs6.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
689
720
  });
690
721
  if (environments.length === 0) {
691
722
  console.log(
@@ -710,12 +741,12 @@ function updateOptionsInYaml(content, envList) {
710
741
  async function updateWorkflows(envList, config) {
711
742
  const { workflows } = config;
712
743
  for (const workflowPath of workflows) {
713
- if (!(0, import_fs11.existsSync)(workflowPath)) {
744
+ if (!(0, import_fs6.existsSync)(workflowPath)) {
714
745
  log(` \u21B7 Skipped ${workflowPath} (not found in this repository)`);
715
746
  continue;
716
747
  }
717
748
  try {
718
- const fileContents = (0, import_fs11.readFileSync)(workflowPath, "utf8");
749
+ const fileContents = (0, import_fs6.readFileSync)(workflowPath, "utf8");
719
750
  const workflowData = yaml2.load(fileContents);
720
751
  if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
721
752
  throw new Error(
@@ -723,15 +754,15 @@ async function updateWorkflows(envList, config) {
723
754
  );
724
755
  }
725
756
  const updatedContent = updateOptionsInYaml(fileContents, envList);
726
- (0, import_fs11.writeFileSync)(workflowPath, updatedContent, "utf8");
757
+ (0, import_fs6.writeFileSync)(workflowPath, updatedContent, "utf8");
727
758
  log(` \u2713 Successfully updated ${workflowPath}`);
728
- } catch (error3) {
759
+ } catch (error2) {
729
760
  console.error(
730
761
  `
731
762
  \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`
732
763
  );
733
- console.error(`\u2717 Failed to update ${workflowPath}:`, error3);
734
- throw error3;
764
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error2);
765
+ throw error2;
735
766
  }
736
767
  }
737
768
  }
@@ -772,18 +803,18 @@ async function updateWorkflowEnvironments() {
772
803
  } else {
773
804
  log("\u2139\uFE0F No workflows were updated.");
774
805
  }
775
- } catch (error3) {
776
- console.error("\n\u274C Error updating workflows:", error3);
806
+ } catch (error2) {
807
+ console.error("\n\u274C Error updating workflows:", error2);
777
808
  process.exit(1);
778
809
  }
779
810
  }
780
- var import_promises, import_fs11, import_path13, glob2, yaml2;
811
+ var import_promises, import_fs6, import_path9, glob2, yaml2;
781
812
  var init_update_workflows = __esm({
782
813
  "src/environment/update-workflows.ts"() {
783
814
  "use strict";
784
815
  import_promises = require("fs/promises");
785
- import_fs11 = require("fs");
786
- import_path13 = require("path");
816
+ import_fs6 = require("fs");
817
+ import_path9 = require("path");
787
818
  glob2 = __toESM(require("glob"));
788
819
  yaml2 = __toESM(require("js-yaml"));
789
820
  init_logger();
@@ -794,7 +825,7 @@ var init_update_workflows = __esm({
794
825
  // src/environment/git.ts
795
826
  function getRepoInfo() {
796
827
  try {
797
- const remoteUrl = (0, import_child_process2.execSync)("git config --get remote.origin.url", {
828
+ const remoteUrl = (0, import_child_process.execSync)("git config --get remote.origin.url", {
798
829
  stdio: ["ignore", "pipe", "ignore"]
799
830
  }).toString().trim();
800
831
  const match = remoteUrl.match(/github\.com[:/](.+?)\/(.+?)(\.git)?$/);
@@ -812,11 +843,11 @@ function getRepoInfo() {
812
843
  };
813
844
  }
814
845
  }
815
- var import_child_process2;
846
+ var import_child_process;
816
847
  var init_git = __esm({
817
848
  "src/environment/git.ts"() {
818
849
  "use strict";
819
- import_child_process2 = require("child_process");
850
+ import_child_process = require("child_process");
820
851
  }
821
852
  });
822
853
 
@@ -1346,6 +1377,86 @@ var init_questions_helper = __esm({
1346
1377
  }
1347
1378
  });
1348
1379
 
1380
+ // src/environment/dockerhub.ts
1381
+ async function validateDockerHubCredentials(organisation, repository, username, token) {
1382
+ if (!organisation || !repository || !username || !token) {
1383
+ return {
1384
+ status: "skipped",
1385
+ reason: "Some values are kept from existing GitHub secrets, which cannot be read back"
1386
+ };
1387
+ }
1388
+ try {
1389
+ const login = await fetch(`${DOCKER_HUB_API}/auth/token`, {
1390
+ method: "POST",
1391
+ headers: { "Content-Type": "application/json" },
1392
+ body: JSON.stringify({ identifier: username, secret: token }),
1393
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1394
+ });
1395
+ if (login.status === 401 || login.status === 403) {
1396
+ return {
1397
+ status: "invalid-credentials",
1398
+ reason: "Docker Hub rejected the username or token. Check DOCKER_USERNAME and DOCKER_TOKEN"
1399
+ };
1400
+ }
1401
+ if (!login.ok) {
1402
+ return {
1403
+ status: "unreachable",
1404
+ reason: `Docker Hub login responded with HTTP ${login.status}`
1405
+ };
1406
+ }
1407
+ const body = await login.json();
1408
+ const accessToken = body.access_token ?? body.token;
1409
+ if (!accessToken) {
1410
+ return {
1411
+ status: "unreachable",
1412
+ reason: "Docker Hub login response did not contain an access token"
1413
+ };
1414
+ }
1415
+ const repositoryResponse = await fetch(
1416
+ `${DOCKER_HUB_API}/repositories/${encodeURIComponent(
1417
+ organisation
1418
+ )}/${encodeURIComponent(repository)}/`,
1419
+ {
1420
+ headers: { Authorization: `Bearer ${accessToken}` },
1421
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1422
+ }
1423
+ );
1424
+ if (repositoryResponse.ok) {
1425
+ return { status: "valid" };
1426
+ }
1427
+ if (repositoryResponse.status === 404) {
1428
+ return {
1429
+ status: "repository-not-found",
1430
+ reason: `Login succeeded, but repository ${organisation}/${repository} was not found or is not accessible with this token. Check DOCKERHUB_ACCOUNT and DOCKERHUB_REPO`
1431
+ };
1432
+ }
1433
+ if (repositoryResponse.status === 401 || repositoryResponse.status === 403) {
1434
+ return {
1435
+ status: "invalid-credentials",
1436
+ reason: `Login succeeded, but the token is not allowed to read repository ${organisation}/${repository}`
1437
+ };
1438
+ }
1439
+ return {
1440
+ status: "unreachable",
1441
+ reason: `Docker Hub repository lookup responded with HTTP ${repositoryResponse.status}`
1442
+ };
1443
+ } catch (err) {
1444
+ if (!(err instanceof Error)) {
1445
+ return { status: "unreachable", reason: String(err) };
1446
+ }
1447
+ const cause = err.cause instanceof Error ? `: ${err.cause.message}` : "";
1448
+ return { status: "unreachable", reason: `${err.message}${cause}` };
1449
+ }
1450
+ }
1451
+ var DOCKER_HUB_API, REQUEST_TIMEOUT_MS;
1452
+ var init_dockerhub = __esm({
1453
+ "src/environment/dockerhub.ts"() {
1454
+ "use strict";
1455
+ DOCKER_HUB_API = "https://hub.docker.com/v2";
1456
+ REQUEST_TIMEOUT_MS = 1e4;
1457
+ }
1458
+ });
1459
+
1349
1460
  // src/environment/manage-users.ts
1350
1461
  async function inquirerPrompt(name, options) {
1351
1462
  const inquirer = await import("@inquirer/prompts");
@@ -1372,7 +1483,7 @@ function getCurrentUsername() {
1372
1483
  }
1373
1484
  function getCurrentUserSSHKeys() {
1374
1485
  const homeDir = os.homedir();
1375
- const sshDir = path11.join(homeDir, ".ssh");
1486
+ const sshDir = path8.join(homeDir, ".ssh");
1376
1487
  const keys = [];
1377
1488
  const keyFiles = [
1378
1489
  "id_rsa.pub",
@@ -1381,15 +1492,15 @@ function getCurrentUserSSHKeys() {
1381
1492
  "id_dsa.pub"
1382
1493
  ];
1383
1494
  for (const keyFile of keyFiles) {
1384
- const keyPath = path11.join(sshDir, keyFile);
1495
+ const keyPath = path8.join(sshDir, keyFile);
1385
1496
  try {
1386
- if (fs3.existsSync(keyPath)) {
1387
- const keyContent = fs3.readFileSync(keyPath, "utf8").trim();
1497
+ if (fs5.existsSync(keyPath)) {
1498
+ const keyContent = fs5.readFileSync(keyPath, "utf8").trim();
1388
1499
  if (keyContent) {
1389
1500
  keys.push(keyContent);
1390
1501
  }
1391
1502
  }
1392
- } catch (error3) {
1503
+ } catch (error2) {
1393
1504
  continue;
1394
1505
  }
1395
1506
  }
@@ -1603,7 +1714,7 @@ async function editUser(user) {
1603
1714
  return updatedUser;
1604
1715
  }
1605
1716
  async function manageUsers(inventoryPath) {
1606
- let users = fs3.existsSync(inventoryPath) ? parseInventoryFile(inventoryPath) : [];
1717
+ let users = fs5.existsSync(inventoryPath) ? parseInventoryFile(inventoryPath) : [];
1607
1718
  if (users.length > 0) {
1608
1719
  displayUserSummary(users);
1609
1720
  }
@@ -1695,7 +1806,7 @@ async function manageUsers(inventoryPath) {
1695
1806
  message: "Save changes end exit?",
1696
1807
  default: true
1697
1808
  });
1698
- if (confirmSave && fs3.existsSync(inventoryPath)) {
1809
+ if (confirmSave && fs5.existsSync(inventoryPath)) {
1699
1810
  updateInventoryFile(inventoryPath, users);
1700
1811
  console.log(`
1701
1812
  \u2705 Changes saved to ${inventoryPath}
@@ -1722,13 +1833,13 @@ async function manageUsers(inventoryPath) {
1722
1833
  }
1723
1834
  return users;
1724
1835
  }
1725
- var os, fs3, path11, input2, select2, confirm, editor, checkbox;
1836
+ var os, fs5, path8, input2, select2, confirm, editor, checkbox;
1726
1837
  var init_manage_users = __esm({
1727
1838
  "src/environment/manage-users.ts"() {
1728
1839
  "use strict";
1729
1840
  os = __toESM(require("os"));
1730
- fs3 = __toESM(require("fs"));
1731
- path11 = __toESM(require("path"));
1841
+ fs5 = __toESM(require("fs"));
1842
+ path8 = __toESM(require("path"));
1732
1843
  init_logger();
1733
1844
  init_utils();
1734
1845
  init_templates();
@@ -1913,6 +2024,28 @@ async function promptAndStoreAnswer(questions, existingValues) {
1913
2024
  ]);
1914
2025
  return { ...Object.fromEntries(existingValuesForQuestions), ...result };
1915
2026
  }
2027
+ async function promptAndValidateDockerhub(existingValues) {
2028
+ const answers = await promptAndStoreAnswer(dockerhubQuestions, existingValues);
2029
+ const result = await validateDockerHubCredentials(
2030
+ answers.dockerhubOrganisation,
2031
+ answers.dockerhubRepository,
2032
+ answers.dockerhubUsername,
2033
+ answers.dockerhubToken
2034
+ );
2035
+ if (result.status === "valid" || result.status === "skipped") {
2036
+ return;
2037
+ }
2038
+ error(`
2039
+ ${result.status}: ${result.reason || "Generic error"}
2040
+ `);
2041
+ const continueNotValidated = await confirm2({
2042
+ message: "Docker Hub credentials are not validated. Continue anyway?",
2043
+ default: false
2044
+ });
2045
+ if (!continueNotValidated) {
2046
+ process.exit(1);
2047
+ }
2048
+ }
1916
2049
  async function runSetupEnvironment() {
1917
2050
  log("\n", import_kleur4.default.bold().underline("Github"), "\n");
1918
2051
  const { githubOrganisation, githubRepository } = await (0, import_prompts2.default)(
@@ -1976,16 +2109,6 @@ async function runSetupEnvironment() {
1976
2109
  ]
1977
2110
  });
1978
2111
  }
1979
- log("\n", import_kleur4.default.bold().underline("Two-factor authentication (2FA)"));
1980
- const two_fa_enabled = await confirm2({
1981
- message: "Enable two-factor authentication (2FA)? This should be enabled for any environment that hosts PII data.",
1982
- default: process.env.TWO_FA_ENABLED ? process.env.TWO_FA_ENABLED === "true" : environment_type === "production"
1983
- });
1984
- if (!two_fa_enabled && ["production", "staging"].includes(environment_type)) {
1985
- warn(
1986
- "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."
1987
- );
1988
- }
1989
2112
  const environment_exists = existingEnvironments.map((e) => e.trim()).includes(environment);
1990
2113
  if (!environment) {
1991
2114
  process.exit(1);
@@ -2049,8 +2172,25 @@ async function runSetupEnvironment() {
2049
2172
  );
2050
2173
  await promptAndStoreAnswer(githubOtherQuestions, existingValues);
2051
2174
  }
2175
+ log("\n", import_kleur4.default.bold().underline("Two-factor authentication (2FA)"));
2176
+ const existingTwoFaEnabled = findExistingValue(
2177
+ "TWO_FA_ENABLED",
2178
+ "VARIABLE",
2179
+ "ENVIRONMENT",
2180
+ existingValues
2181
+ );
2182
+ const twoFaDefault = process.env.TWO_FA_ENABLED || existingTwoFaEnabled?.value;
2183
+ const two_fa_enabled = await confirm2({
2184
+ message: "Enable two-factor authentication (2FA)? This should be enabled for any environment that hosts PII data.",
2185
+ default: twoFaDefault ? twoFaDefault === "true" : environment_type === "production"
2186
+ });
2187
+ if (!two_fa_enabled && ["production", "staging"].includes(environment_type)) {
2188
+ warn(
2189
+ "2FA is disabled on a production-like environment. Logins will accept the fixed test code 000000, exposing real citizen data. Only do this if you know what you are doing."
2190
+ );
2191
+ }
2052
2192
  log("\n", import_kleur4.default.bold().underline("Docker Hub"));
2053
- await promptAndStoreAnswer(dockerhubQuestions, existingValues);
2193
+ await promptAndValidateDockerhub(existingValues);
2054
2194
  log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
2055
2195
  const infrastructure = await promptAndStoreAnswer(
2056
2196
  infrastructureQuestions,
@@ -2214,6 +2354,7 @@ async function runSetupEnvironment() {
2214
2354
  });
2215
2355
  restoreType = await select3({
2216
2356
  message: `Select ${import_kleur4.default.yellow().bold(restoreEnvironmentName)} environment backup mode`,
2357
+ default: restoreType,
2217
2358
  choices: [
2218
2359
  {
2219
2360
  name: "Full dump (daily full database backup)",
@@ -2233,7 +2374,22 @@ async function runSetupEnvironment() {
2233
2374
  log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2234
2375
  }
2235
2376
  log("\n", import_kleur4.default.bold().underline("Monitoring"));
2236
- await promptAndStoreAnswer(databaseAndMonitoringQuestions, existingValues);
2377
+ const existingMonitoringEnabled = findExistingValue(
2378
+ "MONITORING_ENABLED",
2379
+ "VARIABLE",
2380
+ "ENVIRONMENT",
2381
+ existingValues
2382
+ );
2383
+ const monitoringDefault = process.env.MONITORING_ENABLED || existingMonitoringEnabled?.value;
2384
+ const monitoring_enabled = await confirm2({
2385
+ message: "Enable monitoring (Kibana, APM, Filebeat, Metricbeat, Elastalert, OpenTelemetry Collector and tracing)? Disable it if this environment does not need its own monitoring stack.",
2386
+ default: monitoringDefault ? monitoringDefault === "true" : true
2387
+ });
2388
+ if (monitoring_enabled) {
2389
+ await promptAndStoreAnswer(databaseAndMonitoringQuestions, existingValues);
2390
+ } else {
2391
+ log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Monitoring is disabled"));
2392
+ }
2237
2393
  const sentryDSNExists = findExistingValue(
2238
2394
  "SENTRY_DSN",
2239
2395
  "SECRET",
@@ -2303,6 +2459,21 @@ async function runSetupEnvironment() {
2303
2459
  ),
2304
2460
  scope: "ENVIRONMENT"
2305
2461
  });
2462
+ derivedUpdates.push({
2463
+ name: "TWO_FA_ENABLED",
2464
+ type: "VARIABLE",
2465
+ didExist: existingTwoFaEnabled,
2466
+ // Always stored, so the next run defaults to the current answer
2467
+ value: two_fa_enabled ? "true" : "false",
2468
+ scope: "ENVIRONMENT"
2469
+ });
2470
+ derivedUpdates.push({
2471
+ name: "MONITORING_ENABLED",
2472
+ type: "VARIABLE",
2473
+ didExist: existingMonitoringEnabled,
2474
+ value: monitoring_enabled ? "true" : "false",
2475
+ scope: "ENVIRONMENT"
2476
+ });
2306
2477
  derivedUpdates.push(...ssl_answers);
2307
2478
  if (configureBackup) {
2308
2479
  derivedUpdates.push({
@@ -2576,6 +2747,19 @@ async function runSetupEnvironment() {
2576
2747
  existingValues
2577
2748
  ),
2578
2749
  scope: "ENVIRONMENT"
2750
+ },
2751
+ {
2752
+ type: "VARIABLE",
2753
+ name: "RESTORE_ENVIRONMENT_MODE",
2754
+ // Only persist the mode when restore is configured
2755
+ value: restoreEnvironmentName ? restoreType : "",
2756
+ didExist: findExistingValue(
2757
+ "RESTORE_ENVIRONMENT_MODE",
2758
+ "VARIABLE",
2759
+ "ENVIRONMENT",
2760
+ existingValues
2761
+ ),
2762
+ scope: "ENVIRONMENT"
2579
2763
  }
2580
2764
  ];
2581
2765
  if (enableEncryption) {
@@ -2840,6 +3024,7 @@ async function runSetupEnvironment() {
2840
3024
  env: environment,
2841
3025
  environment_type,
2842
3026
  two_fa_enabled,
3027
+ monitoring_enabled,
2843
3028
  traefik_mode: traefikConfOption,
2844
3029
  restore_enabled: restoreEnvironmentName ? true : false,
2845
3030
  restore_environment_name: restoreEnvironmentName || "",
@@ -2905,6 +3090,7 @@ var init_setup_environment = __esm({
2905
3090
  init_questions();
2906
3091
  init_editor_questions();
2907
3092
  init_questions_helper();
3093
+ init_dockerhub();
2908
3094
  init_manage_users();
2909
3095
  init_paths();
2910
3096
  ALL_QUESTIONS = [];
@@ -2932,17 +3118,17 @@ __export(upgrade_exports, {
2932
3118
  upgradeEnvironmentLayout: () => upgradeEnvironmentLayout
2933
3119
  });
2934
3120
  function moveFileIfDestinationMissing(sourcePath, destinationPath) {
2935
- if (!(0, import_fs12.existsSync)(sourcePath)) {
3121
+ if (!(0, import_fs7.existsSync)(sourcePath)) {
2936
3122
  return false;
2937
3123
  }
2938
- if ((0, import_fs12.existsSync)(destinationPath)) {
3124
+ if ((0, import_fs7.existsSync)(destinationPath)) {
2939
3125
  warn(
2940
3126
  `\u26A0\uFE0F Skipped ${sourcePath}; destination already exists at ${destinationPath}`
2941
3127
  );
2942
3128
  return false;
2943
3129
  }
2944
- (0, import_fs12.mkdirSync)((0, import_path14.dirname)(destinationPath), { recursive: true });
2945
- (0, import_fs12.renameSync)(sourcePath, destinationPath);
3130
+ (0, import_fs7.mkdirSync)((0, import_path10.dirname)(destinationPath), { recursive: true });
3131
+ (0, import_fs7.renameSync)(sourcePath, destinationPath);
2946
3132
  log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
2947
3133
  return true;
2948
3134
  }
@@ -2962,8 +3148,8 @@ function migrateInventoryFiles() {
2962
3148
  ) || didMoveInventory;
2963
3149
  }
2964
3150
  try {
2965
- if ((0, import_fs12.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs12.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
2966
- (0, import_fs12.rmdirSync)(OLD_INVENTORY_DIR);
3151
+ if ((0, import_fs7.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs7.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
3152
+ (0, import_fs7.rmdirSync)(OLD_INVENTORY_DIR);
2967
3153
  log(` \u2713 Removed empty ${OLD_INVENTORY_DIR}`);
2968
3154
  }
2969
3155
  } catch {
@@ -2981,12 +3167,12 @@ async function upgradeEnvironmentLayout() {
2981
3167
  }
2982
3168
  log("\nCommit changes into git after upgrade");
2983
3169
  }
2984
- var import_fs12, import_path14, import_kleur5;
3170
+ var import_fs7, import_path10, import_kleur5;
2985
3171
  var init_upgrade = __esm({
2986
3172
  "src/environment/upgrade.ts"() {
2987
3173
  "use strict";
2988
- import_fs12 = require("fs");
2989
- import_path14 = require("path");
3174
+ import_fs7 = require("fs");
3175
+ import_path10 = require("path");
2990
3176
  import_kleur5 = __toESM(require("kleur"));
2991
3177
  init_logger();
2992
3178
  init_paths();
@@ -3004,16 +3190,16 @@ async function select4(options) {
3004
3190
  return inquirer.select(options);
3005
3191
  }
3006
3192
  async function selectInventoryFile(dirPath = "./environments") {
3007
- if (!fs4.existsSync(dirPath)) {
3193
+ if (!fs6.existsSync(dirPath)) {
3008
3194
  warn(`\u26A0\uFE0F No environment configuration directory found at ${dirPath}`);
3009
3195
  warn(
3010
3196
  "Hint: If this is a new infrastructure repository, run `opencrvs environment init` first."
3011
3197
  );
3012
3198
  return null;
3013
3199
  }
3014
- const environments = fs4.readdirSync(dirPath).filter((entry) => {
3015
- const filePath = path12.join(dirPath, entry);
3016
- return fs4.statSync(filePath).isDirectory() && fs4.existsSync(getEnvironmentInventoryPath(entry));
3200
+ const environments = fs6.readdirSync(dirPath).filter((entry) => {
3201
+ const filePath = path9.join(dirPath, entry);
3202
+ return fs6.statSync(filePath).isDirectory() && fs6.existsSync(getEnvironmentInventoryPath(entry));
3017
3203
  }).sort();
3018
3204
  if (environments.length === 0) {
3019
3205
  warn(`\u26A0\uFE0F No environment configuration files found at ${dirPath}`);
@@ -3040,12 +3226,12 @@ async function manageEnvironmentUsers() {
3040
3226
  }
3041
3227
  await manageUsers(inventory_file);
3042
3228
  }
3043
- var fs4, path12, import_kleur6;
3229
+ var fs6, path9, import_kleur6;
3044
3230
  var init_users = __esm({
3045
3231
  "src/environment/users.ts"() {
3046
3232
  "use strict";
3047
- fs4 = __toESM(require("fs"));
3048
- path12 = __toESM(require("path"));
3233
+ fs6 = __toESM(require("fs"));
3234
+ path9 = __toESM(require("path"));
3049
3235
  import_kleur6 = __toESM(require("kleur"));
3050
3236
  init_manage_users();
3051
3237
  init_logger();
@@ -3055,11 +3241,11 @@ var init_users = __esm({
3055
3241
 
3056
3242
  // src/environment/swarm-to-k8s.ts
3057
3243
  var swarm_to_k8s_exports = {};
3058
- var path13, import_kleur7, import_core2;
3244
+ var path10, import_kleur7, import_core2;
3059
3245
  var init_swarm_to_k8s = __esm({
3060
3246
  "src/environment/swarm-to-k8s.ts"() {
3061
3247
  "use strict";
3062
- path13 = __toESM(require("path"));
3248
+ path10 = __toESM(require("path"));
3063
3249
  import_kleur7 = __toESM(require("kleur"));
3064
3250
  init_logger();
3065
3251
  init_utils();
@@ -3111,7 +3297,7 @@ var init_swarm_to_k8s = __esm({
3111
3297
  );
3112
3298
  process.exit(1);
3113
3299
  }
3114
- const ansible_inventory = path13.join(old_inventory_path, environment + ".yml");
3300
+ const ansible_inventory = path10.join(old_inventory_path, environment + ".yml");
3115
3301
  const data = readYamlFile(ansible_inventory);
3116
3302
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3117
3303
  const master = dockerManagerFirst(data) || "";
@@ -3232,187 +3418,12 @@ var init_swarm_to_k8s = __esm({
3232
3418
  }
3233
3419
  });
3234
3420
 
3235
- // src/migrations/v2.1/add-explicit-correction-flags.ts
3236
- var import_ts_morph = require("ts-morph");
3237
- var import_path = __toESM(require("path"));
3238
- var DEFINE_CONFIG_NAME = "defineConfig";
3239
- var ACTIONS_PROPERTY_NAME = "actions";
3240
- var TYPE_PROPERTY_NAME = "type";
3241
- var FLAGS_PROPERTY_NAME = "flags";
3242
- var CONDITIONALS_PROPERTY_NAME = "conditionals";
3243
- var ACTION_TYPE_ENUM_NAME = "ActionType";
3244
- var REQUEST_CORRECTION_TYPE = "REQUEST_CORRECTION";
3245
- var CORRECTION_ACTIONS_TO_ADD = [
3246
- {
3247
- actionType: "APPROVE_CORRECTION",
3248
- labelId: "v2.events.correction.approve.label",
3249
- defaultMessage: "Approve correction",
3250
- description: "Label for the approve correction action"
3251
- },
3252
- {
3253
- actionType: "REJECT_CORRECTION",
3254
- labelId: "v2.events.correction.reject.label",
3255
- defaultMessage: "Reject correction",
3256
- description: "Label for the reject correction action"
3257
- }
3258
- ];
3259
- function isActionOfType(obj, typeName) {
3260
- const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME);
3261
- if (!typeProperty || !import_ts_morph.Node.isPropertyAssignment(typeProperty)) return false;
3262
- const typeInit = typeProperty.getInitializer();
3263
- if (!typeInit) return false;
3264
- if (import_ts_morph.Node.isPropertyAccessExpression(typeInit)) {
3265
- return typeInit.getExpression().getText() === ACTION_TYPE_ENUM_NAME && typeInit.getName() === typeName;
3266
- }
3267
- if (import_ts_morph.Node.isStringLiteral(typeInit)) {
3268
- return typeInit.getLiteralValue() === typeName;
3269
- }
3270
- return false;
3271
- }
3272
- function getTypeInitializerStyle(obj) {
3273
- const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME);
3274
- if (typeProperty && import_ts_morph.Node.isPropertyAssignment(typeProperty)) {
3275
- const typeInit = typeProperty.getInitializer();
3276
- if (typeInit && import_ts_morph.Node.isPropertyAccessExpression(typeInit)) return "enum";
3277
- }
3278
- return "string";
3279
- }
3280
- function getNonEmptyArrayPropertyText(obj, propName) {
3281
- const prop = obj.getProperty(propName);
3282
- if (!prop || !import_ts_morph.Node.isPropertyAssignment(prop)) return void 0;
3283
- const init = prop.getInitializer();
3284
- if (!init || !import_ts_morph.Node.isArrayLiteralExpression(init)) return void 0;
3285
- if (init.getElements().length === 0) return void 0;
3286
- return init.getText();
3287
- }
3288
- function buildCorrectionActionText(spec, typeStyle, flagsText, conditionalsText) {
3289
- const typeText = typeStyle === "enum" ? `${ACTION_TYPE_ENUM_NAME}.${spec.actionType}` : `'${spec.actionType}'`;
3290
- const lines = [
3291
- `type: ${typeText}`,
3292
- `label: {
3293
- id: '${spec.labelId}',
3294
- defaultMessage: '${spec.defaultMessage}',
3295
- description: '${spec.description}'
3296
- }`
3297
- ];
3298
- if (flagsText) {
3299
- lines.push(`${FLAGS_PROPERTY_NAME}: ${flagsText}`);
3300
- }
3301
- if (conditionalsText) {
3302
- lines.push(`${CONDITIONALS_PROPERTY_NAME}: ${conditionalsText}`);
3303
- }
3304
- return `{
3305
- ${lines.join(",\n ")}
3306
- }`;
3307
- }
3308
- function processFile(filePath, project) {
3309
- const sourceFile = project.getSourceFile(filePath);
3310
- if (!sourceFile) return 0;
3311
- let changes = 0;
3312
- const relPath = import_path.default.relative(process.cwd(), filePath);
3313
- const callExpressions = sourceFile.getDescendantsOfKind(
3314
- import_ts_morph.SyntaxKind.CallExpression
3315
- );
3316
- for (const call of callExpressions) {
3317
- const expression = call.getExpression();
3318
- if (!import_ts_morph.Node.isIdentifier(expression) || expression.getText() !== DEFINE_CONFIG_NAME) {
3319
- continue;
3320
- }
3321
- const args2 = call.getArguments();
3322
- if (args2.length === 0) continue;
3323
- const configArg = args2[0];
3324
- if (!import_ts_morph.Node.isObjectLiteralExpression(configArg)) continue;
3325
- const actionsProperty = configArg.getProperty(ACTIONS_PROPERTY_NAME);
3326
- if (!actionsProperty || !import_ts_morph.Node.isPropertyAssignment(actionsProperty))
3327
- continue;
3328
- const actionsInitializer = actionsProperty.getInitializer();
3329
- if (!actionsInitializer || !import_ts_morph.Node.isArrayLiteralExpression(actionsInitializer))
3330
- continue;
3331
- const elements = actionsInitializer.getElements();
3332
- const requestCorrectionIndex = elements.findIndex(
3333
- (el) => import_ts_morph.Node.isObjectLiteralExpression(el) && isActionOfType(el, REQUEST_CORRECTION_TYPE)
3334
- );
3335
- if (requestCorrectionIndex === -1) continue;
3336
- const requestCorrection = elements[requestCorrectionIndex];
3337
- const flagsText = getNonEmptyArrayPropertyText(
3338
- requestCorrection,
3339
- FLAGS_PROPERTY_NAME
3340
- );
3341
- const conditionalsText = getNonEmptyArrayPropertyText(
3342
- requestCorrection,
3343
- CONDITIONALS_PROPERTY_NAME
3344
- );
3345
- if (!flagsText && !conditionalsText) continue;
3346
- const typeStyle = getTypeInitializerStyle(requestCorrection);
3347
- let insertAt = requestCorrectionIndex + 1;
3348
- for (const spec of CORRECTION_ACTIONS_TO_ADD) {
3349
- const alreadyPresent = actionsInitializer.getElements().some(
3350
- (el) => import_ts_morph.Node.isObjectLiteralExpression(el) && isActionOfType(el, spec.actionType)
3351
- );
3352
- if (alreadyPresent) continue;
3353
- const text = buildCorrectionActionText(
3354
- spec,
3355
- typeStyle,
3356
- flagsText,
3357
- conditionalsText
3358
- );
3359
- actionsInitializer.insertElement(insertAt, text);
3360
- insertAt++;
3361
- changes++;
3362
- console.log(
3363
- ` [${relPath}] Added ${spec.actionType} action carrying over REQUEST_CORRECTION's flags/conditionals`
3364
- );
3365
- }
3366
- }
3367
- return changes;
3368
- }
3369
- async function main() {
3370
- const srcDir = import_path.default.join(process.cwd(), "src");
3371
- console.log(`Scanning for defineConfig calls in: ${srcDir}
3372
- `);
3373
- const project = new import_ts_morph.Project({
3374
- tsConfigFilePath: import_path.default.resolve(srcDir, "../tsconfig.json"),
3375
- skipAddingFilesFromTsConfig: false
3376
- });
3377
- const sourceFiles = project.getSourceFiles().filter((sf) => {
3378
- const fp = sf.getFilePath();
3379
- return fp.includes("/src/") && !fp.includes("/node_modules/");
3380
- });
3381
- console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3382
- `);
3383
- let totalChanges = 0;
3384
- const modifiedFiles = [];
3385
- for (const sourceFile of sourceFiles) {
3386
- const filePath = sourceFile.getFilePath();
3387
- const changes = processFile(filePath, project);
3388
- if (changes > 0) {
3389
- totalChanges += changes;
3390
- modifiedFiles.push(filePath);
3391
- }
3392
- }
3393
- if (modifiedFiles.length === 0) {
3394
- console.log(
3395
- "No REQUEST_CORRECTION actions with flags/conditionals found. Nothing to do."
3396
- );
3397
- return;
3398
- }
3399
- console.log(`
3400
- Saving ${modifiedFiles.length} modified file(s)...`);
3401
- for (const filePath of modifiedFiles) {
3402
- const sourceFile = project.getSourceFileOrThrow(filePath);
3403
- await sourceFile.save();
3404
- console.log(` Saved: ${import_path.default.relative(process.cwd(), filePath)}`);
3405
- }
3406
- console.log(
3407
- `
3408
- Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.length} file(s).`
3409
- );
3410
- }
3421
+ // src/cli.ts
3422
+ var import_fs9 = __toESM(require("fs"));
3423
+ var import_path12 = __toESM(require("path"));
3411
3424
 
3412
- // src/migrations/v2.1/add-recovery-link-notifications.ts
3413
- var import_ts_morph2 = require("ts-morph");
3414
- var import_fs2 = require("fs");
3415
- var import_path2 = __toESM(require("path"));
3425
+ // src/migrations/persistent/add-translations.ts
3426
+ var import_path = __toESM(require("path"));
3416
3427
 
3417
3428
  // src/csv.ts
3418
3429
  var import_fs = require("fs");
@@ -3454,20 +3465,20 @@ function idOf(line2) {
3454
3465
  const comma = line2.indexOf(",");
3455
3466
  return comma === -1 ? line2 : line2.slice(0, comma);
3456
3467
  }
3457
- function readCsvFile(path14) {
3458
- if (!(0, import_fs.existsSync)(path14)) {
3468
+ function readCsvFile(path12) {
3469
+ if (!(0, import_fs.existsSync)(path12)) {
3459
3470
  return void 0;
3460
3471
  }
3461
- const contents = (0, import_fs.readFileSync)(path14, "utf8");
3472
+ const contents = (0, import_fs.readFileSync)(path12, "utf8");
3462
3473
  const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3463
3474
  const trailingNewline = /\r?\n$/.test(contents);
3464
3475
  const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3465
3476
  const body = lines.slice(1).filter((line2) => line2 !== "");
3466
3477
  return { header: lines[0], body, newline, trailingNewline };
3467
3478
  }
3468
- function writeCsvFile(path14, file) {
3479
+ function writeCsvFile(path12, file) {
3469
3480
  (0, import_fs.writeFileSync)(
3470
- path14,
3481
+ path12,
3471
3482
  [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3472
3483
  );
3473
3484
  }
@@ -3481,549 +3492,101 @@ function addRows(file, rows) {
3481
3492
  if (file.body.some((line2) => idOf(line2) === id)) {
3482
3493
  continue;
3483
3494
  }
3484
- const insertAt = isSorted ? file.body.findIndex((line2) => idOf(line2) > id) : -1;
3485
- if (insertAt === -1) {
3495
+ const insertAt2 = isSorted ? file.body.findIndex((line2) => idOf(line2) > id) : -1;
3496
+ if (insertAt2 === -1) {
3486
3497
  file.body.push(row);
3487
3498
  } else {
3488
- file.body.splice(insertAt, 0, row);
3499
+ file.body.splice(insertAt2, 0, row);
3489
3500
  }
3490
3501
  added.push(id);
3491
3502
  }
3492
3503
  return added;
3493
3504
  }
3494
3505
 
3495
- // src/migrations/v2.1/add-recovery-link-notifications.ts
3496
- var EMAIL_TEMPLATES_FILE = "src/api/notification/email-templates/index.ts";
3497
- var SMS_SERVICE_FILE = "src/api/notification/sms-service.ts";
3498
- var HANDLER_FILE = "src/api/notification/handler.ts";
3499
- var ROUTES_FILE = "src/config/routes/userNotificationRoutes.ts";
3500
- var EMAIL_TEMPLATE_DIR = "src/api/notification/email-templates/other";
3501
- var NOTIFICATION_CSV = "src/translations/notification.csv";
3502
- var LOGIN_CSV = "src/translations/login.csv";
3503
- var TRIGGER_VARIABLE_OBJECT = "TriggerVariable";
3504
- var TEMPLATES_OBJECT = "templates";
3505
- var OTHER_TEMPLATES_OBJECT = "otherTemplates";
3506
- var TRIGGER_TO_SMS_TEMPLATE_OBJECT = "TriggerToSMSTemplate";
3507
- var CONVERT_PAYLOAD_FUNCTION = "convertPayloadToVariable";
3508
- var ROUTES_FUNCTION = "getUserNotificationRoutes";
3509
- var RECOVERY_EVENTS = [
3510
- {
3511
- id: "password-reset-link",
3512
- constant: "PASSWORD_RESET_LINK",
3513
- smsTemplate: "resetPasswordLinkNotification",
3514
- emailSubject: "Reset your password",
3515
- routeDescription: "Handles notification for password reset recovery link",
3516
- heading: "Reset your password",
3517
- reason: "Someone asked to reset the password for your {{applicationName}}\n account.",
3518
- linkLabel: "Reset your password"
3519
- },
3520
- {
3521
- id: "username-reminder-link",
3522
- constant: "USERNAME_REMINDER_LINK",
3523
- smsTemplate: "retrieveUsernameLinkNotification",
3524
- emailSubject: "Retrieve your username",
3525
- routeDescription: "Handles notification for username reminder recovery link",
3526
- heading: "Retrieve your username",
3527
- reason: "Someone asked for a reminder of the username for your\n {{applicationName}} account.",
3528
- linkLabel: "Retrieve your username"
3506
+ // src/translations/template.ts
3507
+ var REPOSITORY = "opencrvs/opencrvs-core";
3508
+ var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
3509
+ async function matchingRefs(namespace, prefix) {
3510
+ const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
3511
+ const response = await fetch(url, {
3512
+ headers: { accept: "application/vnd.github+json" }
3513
+ });
3514
+ if (!response.ok) {
3515
+ throw new Error(
3516
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
3517
+ );
3529
3518
  }
3530
- ];
3531
- var NOTIFICATION_CSV_ROWS = [
3532
- `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}}}`,
3533
- `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}}}`
3534
- ];
3535
- var LOGIN_CSV_ROWS = [
3536
- `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`,
3537
- `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."`,
3538
- `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`,
3539
- `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`,
3540
- `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.`,
3541
- `resetCredentials.recoveryLinkLanding.expired.link,Link back to the forgotten item form shown on an expired/invalid recovery link,Start again,Recommencer`,
3542
- `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`
3543
- ];
3519
+ const refs = await response.json();
3520
+ const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
3521
+ return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
3522
+ }
3523
+ async function candidateRefs(version) {
3524
+ return [
3525
+ ...await matchingRefs("heads", `release/${version}.`),
3526
+ ...await matchingRefs("tags", `v${version}.`),
3527
+ "develop"
3528
+ ];
3529
+ }
3530
+ async function fetchTemplate(refs, application) {
3531
+ for (const ref of refs) {
3532
+ const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
3533
+ const response = await fetch(url);
3534
+ if (response.ok) {
3535
+ return { ref, contents: await response.text() };
3536
+ }
3537
+ if (response.status !== 404) {
3538
+ throw new Error(
3539
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
3540
+ );
3541
+ }
3542
+ }
3543
+ return void 0;
3544
+ }
3545
+
3546
+ // src/migrations/persistent/add-translations.ts
3547
+ var APPLICATIONS = ["client", "login"];
3544
3548
  var skipped = [];
3545
3549
  function warnSkipped(message) {
3546
3550
  skipped.push(message);
3547
3551
  console.warn(` \u26A0\uFE0F ${message}`);
3548
3552
  }
3549
- function findObjectLiteral(declaration) {
3550
- let expression = declaration?.getInitializer();
3551
- while (expression && (import_ts_morph2.Node.isAsExpression(expression) || import_ts_morph2.Node.isSatisfiesExpression(expression))) {
3552
- expression = expression.getExpression();
3553
- }
3554
- return expression && import_ts_morph2.Node.isObjectLiteralExpression(expression) ? expression : void 0;
3555
- }
3556
- function hasKeyFor(obj, key, constant) {
3557
- const accepted = /* @__PURE__ */ new Set([
3558
- `[TriggerEvent.${constant}]`,
3559
- `['${key}']`,
3560
- `["${key}"]`,
3561
- `'${key}'`,
3562
- `"${key}"`,
3563
- key
3564
- ]);
3565
- return obj.getProperties().some(
3566
- (property) => import_ts_morph2.Node.isPropertyAssignment(property) && accepted.has(property.getName().trim())
3567
- );
3568
- }
3569
- function renderKey(obj, key, constant) {
3570
- const names = obj.getProperties().filter(import_ts_morph2.Node.isPropertyAssignment).map((property) => property.getName().trim());
3571
- if (names.some((name) => name.startsWith("[TriggerEvent."))) {
3572
- return `[TriggerEvent.${constant}]`;
3573
- }
3574
- if (names.some((name) => name.startsWith("["))) {
3575
- return `['${key}']`;
3576
- }
3577
- return `'${key}'`;
3578
- }
3579
- function appendEntry(sourceFile, objectName, key, valueLines) {
3580
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3581
- const properties = obj?.getProperties() ?? [];
3582
- const lastProperty = properties[properties.length - 1];
3583
- if (!lastProperty) return false;
3584
- const indent = lastProperty.getIndentationText();
3585
- const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${key}: ${line2}` : line2}`).join("\n");
3586
- sourceFile.insertText(lastProperty.getEnd(), `,
3587
- ${entry}`);
3588
- return true;
3589
- }
3590
- function objectHasKeyFor(sourceFile, objectName, key, constant) {
3591
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3592
- return obj ? hasKeyFor(obj, key, constant) : false;
3593
- }
3594
- function renderKeyFor(sourceFile, objectName, key, constant) {
3595
- const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3596
- return obj ? renderKey(obj, key, constant) : `'${key}'`;
3553
+ function rowsToAdd(local, template) {
3554
+ const localColumns = parseCsvLine(local.header);
3555
+ const templateColumns = parseCsvLine(template.header);
3556
+ return template.body.filter((line2) => line2 !== "").map((line2) => {
3557
+ const values = parseCsvLine(line2);
3558
+ return toCsvLine(
3559
+ localColumns.map((column) => {
3560
+ const index = templateColumns.indexOf(column);
3561
+ return index === -1 ? "" : values[index] ?? "";
3562
+ })
3563
+ );
3564
+ });
3597
3565
  }
3598
- function updateEmailTemplates(project, cwd) {
3599
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, EMAIL_TEMPLATES_FILE));
3600
- if (!sourceFile) {
3601
- warnSkipped(`${EMAIL_TEMPLATES_FILE} not found; email templates not wired`);
3566
+ async function updateApplication(cwd, targetVersion, refs, application) {
3567
+ const relativePath = `src/translations/${application}.csv`;
3568
+ const local = readCsvFile(import_path.default.join(cwd, relativePath));
3569
+ if (!local) {
3570
+ warnSkipped(`${relativePath} not found; translations not added`);
3602
3571
  return;
3603
3572
  }
3604
- const missingObject = [TRIGGER_VARIABLE_OBJECT, TEMPLATES_OBJECT].find(
3605
- (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3606
- );
3607
- if (missingObject) {
3573
+ const fetched = await fetchTemplate(refs, application);
3574
+ if (!fetched) {
3608
3575
  warnSkipped(
3609
- `Could not find '${missingObject}' in ${EMAIL_TEMPLATES_FILE}; email templates not wired`
3576
+ `No ${application}.csv found in the ${targetVersion} country config template on GitHub; ${application}.csv not updated`
3610
3577
  );
3611
3578
  return;
3612
3579
  }
3613
- for (const event of RECOVERY_EVENTS) {
3614
- if (!objectHasKeyFor(
3615
- sourceFile,
3616
- TRIGGER_VARIABLE_OBJECT,
3617
- event.id,
3618
- event.constant
3619
- ) && appendEntry(
3620
- sourceFile,
3621
- TRIGGER_VARIABLE_OBJECT,
3622
- renderKeyFor(
3623
- sourceFile,
3624
- TRIGGER_VARIABLE_OBJECT,
3625
- event.id,
3626
- event.constant
3627
- ),
3628
- [
3629
- "z.object({",
3630
- " firstname: z.string(),",
3631
- " applicationName: z.string(),",
3632
- " countryLogo: z.string(),",
3633
- " recoveryURL: z.string()",
3634
- "})"
3635
- ]
3636
- )) {
3637
- console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} variables`);
3638
- }
3639
- if (!objectHasKeyFor(
3640
- sourceFile,
3641
- TEMPLATES_OBJECT,
3642
- event.id,
3643
- event.constant
3644
- ) && appendEntry(
3645
- sourceFile,
3646
- TEMPLATES_OBJECT,
3647
- renderKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant),
3648
- [
3649
- "{",
3650
- ` type: '${event.id}',`,
3651
- ` subject: '${event.emailSubject}',`,
3652
- ` template: readOtherTemplate<TriggerVariable['${event.id}']>(`,
3653
- ` '${event.id}'`,
3654
- " )",
3655
- "}"
3656
- ]
3657
- )) {
3658
- console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} template`);
3659
- }
3660
- }
3661
- }
3662
- function updateSmsService(project, cwd) {
3663
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, SMS_SERVICE_FILE));
3664
- if (!sourceFile) {
3665
- warnSkipped(`${SMS_SERVICE_FILE} not found; SMS templates not wired`);
3666
- return;
3667
- }
3668
- const missingObject = [
3669
- OTHER_TEMPLATES_OBJECT,
3670
- TRIGGER_TO_SMS_TEMPLATE_OBJECT
3671
- ].find(
3672
- (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3673
- );
3674
- if (missingObject) {
3675
- warnSkipped(
3676
- `Could not find '${missingObject}' in ${SMS_SERVICE_FILE}; SMS templates not wired`
3677
- );
3678
- return;
3679
- }
3680
- for (const event of RECOVERY_EVENTS) {
3681
- if (!objectHasKeyFor(
3682
- sourceFile,
3683
- OTHER_TEMPLATES_OBJECT,
3684
- event.smsTemplate,
3685
- event.smsTemplate
3686
- ) && appendEntry(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, [
3687
- `'${event.smsTemplate}'`
3688
- ])) {
3689
- console.log(` \u2713 ${SMS_SERVICE_FILE}: ${event.smsTemplate}`);
3690
- }
3691
- if (!objectHasKeyFor(
3692
- sourceFile,
3693
- TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3694
- event.id,
3695
- event.constant
3696
- ) && appendEntry(
3697
- sourceFile,
3698
- TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3699
- renderKeyFor(
3700
- sourceFile,
3701
- TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3702
- event.id,
3703
- event.constant
3704
- ),
3705
- [`'${event.smsTemplate}'`]
3706
- )) {
3707
- console.log(
3708
- ` \u2713 ${SMS_SERVICE_FILE}: ${event.id} -> ${event.smsTemplate}`
3709
- );
3710
- }
3711
- }
3712
- }
3713
- function updateHandler(project, cwd) {
3714
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, HANDLER_FILE));
3715
- if (!sourceFile) {
3716
- warnSkipped(`${HANDLER_FILE} not found; payload conversion not wired`);
3717
- return;
3718
- }
3719
- const convertPayload = sourceFile.getFunction(CONVERT_PAYLOAD_FUNCTION);
3720
- const caseBlock = convertPayload?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.SwitchStatement)?.getCaseBlock();
3721
- if (!caseBlock) {
3722
- warnSkipped(
3723
- `Could not find a switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE}; payload conversion not wired`
3724
- );
3725
- return;
3726
- }
3727
- const missing = RECOVERY_EVENTS.filter(
3728
- (event) => !caseBlock.getText().includes(`TriggerEvent.${event.constant}`) && !caseBlock.getText().includes(`'${event.id}'`)
3729
- );
3730
- if (missing.length === 0) return;
3731
- const existingClauses = caseBlock.getClauses();
3732
- if (existingClauses.length === 0) {
3733
- warnSkipped(
3734
- `The switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE} has no cases; payload conversion not wired`
3735
- );
3736
- return;
3737
- }
3738
- const defaultClause = existingClauses.find(import_ts_morph2.Node.isDefaultClause);
3739
- const anchor = defaultClause ?? existingClauses[existingClauses.length - 1];
3740
- const indent = anchor.getIndentationText();
3741
- const lines = [
3742
- ...missing.map((event) => `case TriggerEvent.${event.constant}:`),
3743
- ` return {`,
3744
- ` firstname,`,
3745
- ` applicationName: applicationConfig.APPLICATION_NAME,`,
3746
- ` countryLogo: COUNTRY_LOGO_URL,`,
3747
- ` recoveryURL: \`\${LOGIN_URL}recover?token=\${encodeURIComponent(payload.token)}\``,
3748
- ` }`
3749
- ];
3750
- if (defaultClause) {
3751
- caseBlock.insertText(
3752
- anchor.getStart(),
3753
- `${lines.map((line2, index) => index === 0 ? line2 : `${indent}${line2}`).join("\n")}
3754
- ${indent}`
3755
- );
3756
- } else {
3757
- caseBlock.insertText(
3758
- anchor.getEnd(),
3759
- `
3760
- ${lines.map((line2) => `${indent}${line2}`).join("\n")}`
3761
- );
3762
- }
3763
- for (const event of missing) {
3764
- console.log(` \u2713 ${HANDLER_FILE}: ${event.id} case`);
3765
- }
3766
- }
3767
- function updateRoutes(project, cwd) {
3768
- const sourceFile = project.getSourceFile(import_path2.default.join(cwd, ROUTES_FILE));
3769
- if (!sourceFile) {
3770
- warnSkipped(`${ROUTES_FILE} not found; trigger routes not registered`);
3771
- return;
3772
- }
3773
- const routesFunction = sourceFile.getFunction(ROUTES_FUNCTION) ?? sourceFile.getFunctions().find((fn) => fn.isDefaultExport());
3774
- const routesArray = routesFunction?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.ReturnStatement)?.getExpressionIfKind(import_ts_morph2.SyntaxKind.ArrayLiteralExpression);
3775
- if (!routesArray) {
3776
- warnSkipped(
3777
- `Could not find the route array returned by '${ROUTES_FUNCTION}' in ${ROUTES_FILE}; trigger routes not registered`
3778
- );
3779
- return;
3780
- }
3781
- for (const event of RECOVERY_EVENTS) {
3782
- if (routesArray.getText().includes(`/trigger/user/${event.id}`)) continue;
3783
- routesArray.addElement(`{
3784
- method: 'POST',
3785
- path: '/trigger/user/${event.id}',
3786
- handler: makeNotificationHandler('${event.id}'),
3787
- options: {
3788
- auth: false,
3789
- tags: ['api'],
3790
- description: '${event.routeDescription}'
3791
- }
3792
- }`);
3793
- console.log(` \u2713 ${ROUTES_FILE}: POST /trigger/user/${event.id}`);
3794
- }
3795
- }
3796
- function renderEmailTemplate(event) {
3797
- return `<!--
3798
- This Source Code Form is subject to the terms of the Mozilla Public
3799
- License, v. 2.0. If a copy of the MPL was not distributed with this
3800
- file, You can obtain one at https://mozilla.org/MPL/2.0/.
3801
-
3802
- OpenCRVS is also distributed under the terms of the Civil Registration
3803
- & Healthcare Disclaimer located at http://opencrvs.org/license.
3804
-
3805
- Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
3806
- -->
3807
- <!doctype html>
3808
- <html>
3809
- <head>
3810
- <link
3811
- href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
3812
- rel="stylesheet"
3813
- />
3814
- <style type="text/css">
3815
- body {
3816
- font-family: 'Noto Sans', sans-serif;
3817
- color: #222;
3818
- padding: 16px 24px;
3819
- }
3820
-
3821
- h1 {
3822
- font-size: 21px;
3823
- margin-top: 32px;
3824
- margin-bottom: 36px;
3825
- font-weight: 700;
3826
- }
3827
-
3828
- p {
3829
- font-weight: 400;
3830
- font-size: 16px;
3831
- line-height: 1.8;
3832
- margin-bottom: 24px;
3833
- }
3834
-
3835
- i {
3836
- color: #666;
3837
- font-weight: 400;
3838
- font-size: 16px;
3839
- }
3840
- </style>
3841
- </head>
3842
-
3843
- <body>
3844
- <img
3845
- src="{{countryLogo}}"
3846
- alt="country_logo"
3847
- style="max-height: 88px; max-width: 100%"
3848
- />
3849
- <h1>${event.heading}</h1>
3850
- <p>Hello {{firstname}},</p>
3851
- <p>
3852
- ${event.reason}
3853
- </p>
3854
-
3855
- <div style="margin-top: 32px; margin-bottom: 32px">
3856
- <a href="{{{recoveryURL}}}">${event.linkLabel}</a>
3857
- </div>
3858
- <br />
3859
- <p>
3860
- This link expires in 1 hour and can only be used once. If you did not
3861
- request this, you can ignore this email.
3862
- </p>
3863
- <br />
3864
- <p>
3865
- Best regards, <br />
3866
- {{applicationName}} Team
3867
- </p>
3868
- </body>
3869
- </html>
3870
- `;
3871
- }
3872
- function writeEmailTemplates(cwd) {
3873
- const templateDir = import_path2.default.join(cwd, EMAIL_TEMPLATE_DIR);
3874
- if (!(0, import_fs2.existsSync)(templateDir)) {
3875
- warnSkipped(
3876
- `${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`
3877
- );
3878
- return;
3879
- }
3880
- for (const event of RECOVERY_EVENTS) {
3881
- const templatePath = import_path2.default.join(templateDir, `${event.id}.html`);
3882
- if ((0, import_fs2.existsSync)(templatePath)) continue;
3883
- (0, import_fs2.writeFileSync)(templatePath, renderEmailTemplate(event));
3884
- console.log(` \u2713 ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
3885
- }
3886
- }
3887
- function addCsvRows(cwd, relativePath, rows) {
3888
- const csvPath = import_path2.default.join(cwd, relativePath);
3889
- const file = readCsvFile(csvPath);
3890
- if (!file) {
3891
- warnSkipped(`${relativePath} not found; translations not added`);
3892
- return;
3893
- }
3894
- const added = addRows(file, rows);
3895
- if (added.length === 0) return;
3896
- for (const id of added) {
3897
- console.log(` \u2713 ${relativePath}: ${id}`);
3898
- }
3899
- writeCsvFile(csvPath, file);
3900
- }
3901
- async function main2() {
3902
- const cwd = process.cwd();
3903
- const tsConfigFilePath = import_path2.default.join(cwd, "tsconfig.json");
3904
- console.log(
3905
- "Registering the password-reset-link and username-reminder-link notifications...\n"
3906
- );
3907
- if (!(0, import_fs2.existsSync)(tsConfigFilePath)) {
3908
- warnSkipped(
3909
- `tsconfig.json not found in ${cwd}; notification wiring skipped entirely`
3910
- );
3911
- return;
3912
- }
3913
- const project = new import_ts_morph2.Project({
3914
- tsConfigFilePath,
3915
- skipAddingFilesFromTsConfig: false,
3916
- // ts-morph indents inserted code with four spaces by default, which every
3917
- // country config's prettier run would immediately undo.
3918
- manipulationSettings: { indentationText: import_ts_morph2.IndentationText.TwoSpaces }
3919
- });
3920
- updateEmailTemplates(project, cwd);
3921
- updateSmsService(project, cwd);
3922
- updateHandler(project, cwd);
3923
- updateRoutes(project, cwd);
3924
- await project.save();
3925
- writeEmailTemplates(cwd);
3926
- addCsvRows(cwd, NOTIFICATION_CSV, NOTIFICATION_CSV_ROWS);
3927
- addCsvRows(cwd, LOGIN_CSV, LOGIN_CSV_ROWS);
3928
- if (skipped.length > 0) {
3929
- console.warn(
3930
- `
3931
- \u26A0\uFE0F ${skipped.length} step(s) were skipped. Wire the following by hand before upgrading:`
3932
- );
3933
- for (const message of skipped) {
3934
- console.warn(` - ${message}`);
3935
- }
3936
- }
3937
- }
3938
-
3939
- // src/migrations/v2.1/add-translations.ts
3940
- var import_path3 = __toESM(require("path"));
3941
-
3942
- // src/translations/template.ts
3943
- var REPOSITORY = "opencrvs/opencrvs-core";
3944
- var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
3945
- async function matchingRefs(namespace, prefix) {
3946
- const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
3947
- const response = await fetch(url, {
3948
- headers: { accept: "application/vnd.github+json" }
3949
- });
3950
- if (!response.ok) {
3951
- throw new Error(
3952
- `GitHub answered ${response.status} ${response.statusText} for ${url}`
3953
- );
3954
- }
3955
- const refs = await response.json();
3956
- const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
3957
- return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
3958
- }
3959
- async function candidateRefs(version) {
3960
- return [
3961
- ...await matchingRefs("heads", `release/${version}.`),
3962
- ...await matchingRefs("tags", `v${version}.`),
3963
- "develop"
3964
- ];
3965
- }
3966
- async function fetchTemplate(refs, application) {
3967
- for (const ref of refs) {
3968
- const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
3969
- const response = await fetch(url);
3970
- if (response.ok) {
3971
- return { ref, contents: await response.text() };
3972
- }
3973
- if (response.status !== 404) {
3974
- throw new Error(
3975
- `GitHub answered ${response.status} ${response.statusText} for ${url}`
3976
- );
3977
- }
3978
- }
3979
- return void 0;
3980
- }
3981
-
3982
- // src/migrations/v2.1/add-translations.ts
3983
- var APPLICATIONS = ["client", "login"];
3984
- var TARGET_VERSION = "2.1";
3985
- var skipped2 = [];
3986
- function warnSkipped2(message) {
3987
- skipped2.push(message);
3988
- console.warn(` \u26A0\uFE0F ${message}`);
3989
- }
3990
- function rowsToAdd(local, template) {
3991
- const localColumns = parseCsvLine(local.header);
3992
- const templateColumns = parseCsvLine(template.header);
3993
- return template.body.filter((line2) => line2 !== "").map((line2) => {
3994
- const values = parseCsvLine(line2);
3995
- return toCsvLine(
3996
- localColumns.map((column) => {
3997
- const index = templateColumns.indexOf(column);
3998
- return index === -1 ? "" : values[index] ?? "";
3999
- })
4000
- );
4001
- });
4002
- }
4003
- async function updateApplication(cwd, refs, application) {
4004
- const relativePath = `src/translations/${application}.csv`;
4005
- const local = readCsvFile(import_path3.default.join(cwd, relativePath));
4006
- if (!local) {
4007
- warnSkipped2(`${relativePath} not found; translations not added`);
4008
- return;
4009
- }
4010
- const fetched = await fetchTemplate(refs, application);
4011
- if (!fetched) {
4012
- warnSkipped2(
4013
- `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
4014
- );
4015
- return;
4016
- }
4017
- const template = readTemplate(fetched.contents);
4018
- const added = addRows(local, rowsToAdd(local, template));
4019
- if (added.length === 0) {
4020
- return;
3580
+ const template = readTemplate(fetched.contents);
3581
+ const added = addRows(local, rowsToAdd(local, template));
3582
+ if (added.length === 0) {
3583
+ return;
4021
3584
  }
4022
3585
  try {
4023
- writeCsvFile(import_path3.default.join(cwd, relativePath), local);
4024
- } catch (error3) {
4025
- warnSkipped2(
4026
- `Could not write ${relativePath} (${error3.message}); translations not added`
3586
+ writeCsvFile(import_path.default.join(cwd, relativePath), local);
3587
+ } catch (error2) {
3588
+ warnSkipped(
3589
+ `Could not write ${relativePath} (${error2.message}); translations not added`
4027
3590
  );
4028
3591
  return;
4029
3592
  }
@@ -4040,1177 +3603,467 @@ function readTemplate(contents) {
4040
3603
  trailingNewline: true
4041
3604
  };
4042
3605
  }
4043
- async function listRefs() {
3606
+ async function listRefs(targetVersion) {
4044
3607
  try {
4045
- return await candidateRefs(TARGET_VERSION);
4046
- } catch (error3) {
4047
- warnSkipped2(
4048
- `Could not list the ${TARGET_VERSION} refs on GitHub (${error3.message}); translations not added`
3608
+ return await candidateRefs(targetVersion);
3609
+ } catch (error2) {
3610
+ warnSkipped(
3611
+ `Could not list the ${targetVersion} refs on GitHub (${error2.message}); translations not added`
4049
3612
  );
4050
3613
  return void 0;
4051
3614
  }
4052
3615
  }
4053
- async function main3() {
3616
+ async function main(targetVersion) {
4054
3617
  const cwd = process.cwd();
4055
3618
  console.log("Adding the translation keys core gained this version...\n");
4056
- const refs = await listRefs();
3619
+ const refs = await listRefs(targetVersion);
4057
3620
  if (refs) {
4058
3621
  for (const application of APPLICATIONS) {
4059
3622
  try {
4060
- await updateApplication(cwd, refs, application);
4061
- } catch (error3) {
4062
- warnSkipped2(
4063
- `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${application}.csv not updated`
3623
+ await updateApplication(cwd, targetVersion, refs, application);
3624
+ } catch (error2) {
3625
+ warnSkipped(
3626
+ `Could not read ${application}.csv from the country config template on GitHub (${error2.message}); ${application}.csv not updated`
4064
3627
  );
4065
3628
  }
4066
3629
  }
4067
3630
  }
4068
- if (skipped2.length > 0) {
3631
+ if (skipped.length > 0) {
4069
3632
  console.warn(
4070
3633
  `
4071
- \u26A0\uFE0F ${skipped2.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
3634
+ \u26A0\uFE0F ${skipped.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
4072
3635
  );
4073
- for (const message of skipped2) {
3636
+ for (const message of skipped) {
4074
3637
  console.warn(` - ${message}`);
4075
3638
  }
4076
3639
  }
4077
3640
  }
4078
3641
 
4079
- // src/migrations/v2.1/enable-telemetry.ts
4080
- var import_ts_morph3 = require("ts-morph");
4081
- var import_fs3 = require("fs");
4082
- var import_path4 = __toESM(require("path"));
4083
- var HANDLER_FILE2 = "src/api/telemetry/handler.ts";
4084
- var ENVIRONMENT_FILE = "src/environment.ts";
4085
- var INDEX_FILE = "src/index.ts";
4086
- var HANDLER_MODULE = "./api/telemetry/handler";
4087
- var skipped3 = [];
4088
- function warnSkipped3(message) {
4089
- skipped3.push(message);
4090
- console.warn(` \u26A0\uFE0F ${message}`);
4091
- }
4092
- var TELEMETRY_HANDLER_SOURCE = `/*
4093
- * This Source Code Form is subject to the terms of the Mozilla Public
4094
- * License, v. 2.0. If a copy of the MPL was not distributed with this
4095
- * file, You can obtain one at https://mozilla.org/MPL/2.0/.
4096
- *
4097
- * OpenCRVS is also distributed under the terms of the Civil Registration
4098
- * & Healthcare Disclaimer located at http://opencrvs.org/license.
4099
- *
4100
- * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
4101
- */
4102
-
4103
- import { Request, ResponseToolkit } from '@hapi/hapi'
4104
- import * as Joi from 'joi'
4105
- import { sendTelemetry, TelemetryReport } from '@opencrvs/toolkit/telemetry'
4106
- import { env } from '@countryconfig/environment'
4107
- import { logger } from '@countryconfig/logger'
4108
- import { applicationConfig } from '@countryconfig/api/application/application-config'
4109
-
4110
- /** Report the events service posts to \`/trigger/telemetry\`. */
4111
- export const telemetrySchema = Joi.object({
4112
- reported_at: Joi.string().isoDate().required(),
4113
- app_version: Joi.string().optional(),
4114
- metrics: Joi.object()
4115
- .pattern(
4116
- Joi.string(),
4117
- Joi.alternatives(Joi.number(), Joi.string(), Joi.boolean())
4118
- )
4119
- .required()
4120
- })
4121
-
4122
- interface IncomingReport {
4123
- reported_at: string
4124
- app_version?: string
4125
- metrics: Record<string, number | string | boolean>
4126
- }
4127
-
4128
- /** Logged once at countryconfig startup while telemetry is disabled. */
4129
- export const TELEMETRY_DISABLED_NOTICE =
4130
- 'Telemetry is disabled. Help improve OpenCRVS by sharing anonymous, ' +
4131
- 'aggregate usage metrics (registration and certificate counts, active ' +
4132
- 'users, uptime) \u2014 no personal, health, or otherwise protected record data ' +
4133
- 'ever leaves your instance. Enable it by setting TELEMETRY_ENABLED=true on ' +
4134
- 'the countryconfig service.'
4135
-
4136
- /**
4137
- * Receives a usage report from the events service and, when telemetry is
4138
- * enabled for this instance, stamps the instance identity onto it and forwards
4139
- * it to the status service via the toolkit's \`sendTelemetry\` (which owns the
4140
- * endpoint and payload schema). The events service is unaware of whether
4141
- * telemetry is enabled or of the country code / domain / environment reported.
4142
- */
4143
- export async function telemetryHandler(request: Request, h: ResponseToolkit) {
4144
- // Only accept OpenCRVS *system* tokens (the events service's service
4145
- // token has userType 'system'). A logged-in user's token is a 'user' token,
4146
- // so a user cannot submit telemetry with their own credentials \u2014 and the
4147
- // service-token endpoint is not reachable through the public gateway.
4148
- const credentials = request.auth.credentials as
4149
- | { userType?: string }
4150
- | undefined
4151
- if (credentials?.userType !== 'system') {
4152
- logger.warn('Telemetry: rejected a request that is not from a system token')
4153
- return h.response({ error: 'forbidden' }).code(403)
4154
- }
4155
-
4156
- if (!env.TELEMETRY_ENABLED) {
4157
- // The encouraging notice is logged once at startup (see index.ts); keep the
4158
- // per-report path quiet.
4159
- return h.response({ status: 'skipped' }).code(200)
4160
- }
4161
-
4162
- const incoming = request.payload as IncomingReport
4163
-
4164
- // Only production instances report; staging, QA and local build the report
4165
- // but never reach the status service. (This gate used to live in the
4166
- // toolkit's sendTelemetry; each country config now owns it.)
4167
- if (!env.isProduction) {
4168
- logger.info(
4169
- \`Telemetry: report for \${incoming.reported_at} was not sent \u2014 only production instances report\`
4170
- )
4171
- return h.response({ status: 'skipped' }).code(200)
4172
- }
4173
-
4174
- const report: TelemetryReport = {
4175
- reported_at: incoming.reported_at,
4176
- country_code: env.COUNTRY_CODE,
4177
- organisation: env.ORGANISATION,
4178
- // env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
4179
- // "no domain" rather than reporting a literal "*".
4180
- domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
4181
- instance: {
4182
- application_name: applicationConfig.APPLICATION_NAME,
4183
- environment: env.ENVIRONMENT_NAME,
4184
- app_version: incoming.app_version
4185
- },
4186
- metrics: incoming.metrics
4187
- }
4188
-
4189
- let result
4190
- try {
4191
- result = await sendTelemetry(report)
4192
- } catch (error) {
4193
- const message = error instanceof Error ? error.message : String(error)
4194
- logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
4195
- return h.response({ status: 'error' }).code(502)
4196
- }
4197
-
4198
- if (result.outcome === 'rejected') {
4199
- logger.error(
4200
- \`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
4201
- )
4202
- return h.response({ status: 'error' }).code(502)
4203
- }
4204
-
4205
- logger.info(
4206
- \`Telemetry: forwarded report for \${report.reported_at} to the status service\`
4207
- )
4208
- return h.response({ status: 'forwarded' }).code(202)
4209
- }
4210
- `;
4211
- var TELEMETRY_DISABLED = {
4212
- enabled: false,
4213
- countryCode: "",
4214
- organisation: ""
4215
- };
4216
- async function promptTelemetryConfig() {
4217
- if (!process.stdin.isTTY) {
4218
- return TELEMETRY_DISABLED;
4219
- }
4220
- const { confirm: confirm3, input: input4 } = await import("@inquirer/prompts");
4221
- const enabled = await confirm3({
4222
- message: "Enable anonymous usage telemetry to help improve OpenCRVS? Only aggregate metrics are shared \u2014 no personal or protected data.",
4223
- default: true
4224
- });
4225
- if (!enabled) {
4226
- return TELEMETRY_DISABLED;
4227
- }
4228
- const countryCode = (await input4({
4229
- message: "Country code (ISO alpha-3, e.g. FAR):",
4230
- validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) || "Enter a 3-letter ISO alpha-3 code."
4231
- })).trim().toUpperCase();
4232
- const organisation = (await input4({
4233
- message: "Organisation running this instance:",
4234
- validate: (value) => value.trim() !== "" || "Enter an organisation name."
4235
- })).trim();
4236
- return { enabled: true, countryCode, organisation };
4237
- }
4238
- function writeTelemetryHandler(cwd) {
4239
- const handlerPath = import_path4.default.join(cwd, HANDLER_FILE2);
4240
- if ((0, import_fs3.existsSync)(handlerPath)) {
4241
- console.log(` ${HANDLER_FILE2} already present; left unchanged`);
4242
- return;
4243
- }
4244
- (0, import_fs3.mkdirSync)(import_path4.default.dirname(handlerPath), { recursive: true });
4245
- (0, import_fs3.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
4246
- console.log(` \u2713 ${HANDLER_FILE2}`);
4247
- }
4248
- function appendProperty(sourceFile, object2, name, valueLines) {
4249
- const properties = object2.getProperties();
4250
- const lastProperty = properties[properties.length - 1];
4251
- if (!lastProperty) return false;
4252
- const indent = lastProperty.getIndentationText();
4253
- const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${name}: ${line2}` : line2}`).join("\n");
4254
- sourceFile.insertText(lastProperty.getEnd(), `,
4255
- ${entry}`);
4256
- return true;
4257
- }
4258
- function ensureEnvalidNamedImports(sourceFile, names) {
4259
- const importDeclaration = sourceFile.getImportDeclarations().find((declaration) => declaration.getModuleSpecifierValue() === "envalid");
4260
- if (!importDeclaration) {
4261
- warnSkipped3(
4262
- `Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(", ")} } by hand`
4263
- );
4264
- return;
4265
- }
4266
- const existing = new Set(
4267
- importDeclaration.getNamedImports().map((named) => named.getName())
4268
- );
4269
- for (const name of names) {
4270
- if (!existing.has(name)) {
4271
- importDeclaration.addNamedImport(name);
4272
- }
4273
- }
4274
- }
4275
- function getCleanEnvObject(sourceFile) {
4276
- const options = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
4277
- return options && import_ts_morph3.Node.isObjectLiteralExpression(options) ? options : void 0;
4278
- }
4279
- function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
4280
- const object2 = getCleanEnvObject(sourceFile);
4281
- if (!object2) return;
4282
- const existing = object2.getProperty(name);
4283
- if (existing && import_ts_morph3.Node.isPropertyAssignment(existing)) {
4284
- if (!update) return;
4285
- const options = existing.getInitializerIfKind(import_ts_morph3.SyntaxKind.CallExpression)?.getArguments()[0];
4286
- if (options && import_ts_morph3.Node.isObjectLiteralExpression(options)) {
4287
- const defaultProperty = options.getProperty("default");
4288
- if (defaultProperty && import_ts_morph3.Node.isPropertyAssignment(defaultProperty)) {
4289
- defaultProperty.setInitializer(defaultExpr);
4290
- } else {
4291
- options.insertPropertyAssignment(0, {
4292
- name: "default",
4293
- initializer: defaultExpr
4294
- });
4295
- }
4296
- console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name} default set`);
4297
- }
4298
- return;
4299
- }
4300
- if (appendProperty(sourceFile, object2, name, [
4301
- `${kind}({`,
4302
- ` default: ${defaultExpr},`,
4303
- ` desc: ${JSON.stringify(desc)}`,
4304
- "})"
4305
- ])) {
4306
- console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name}`);
4307
- }
4308
- }
4309
- function addEnvironmentVariables(project, cwd, config) {
4310
- const sourceFile = project.addSourceFileAtPathIfExists(
4311
- import_path4.default.join(cwd, ENVIRONMENT_FILE)
4312
- );
4313
- if (!sourceFile) {
4314
- warnSkipped3(
4315
- `${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`
4316
- );
4317
- return;
4318
- }
4319
- if (!getCleanEnvObject(sourceFile)) {
4320
- warnSkipped3(
4321
- `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`
4322
- );
4323
- return;
4324
- }
4325
- ensureEnvalidNamedImports(sourceFile, ["bool", "str"]);
4326
- upsertEnvVar(
4327
- sourceFile,
4328
- "TELEMETRY_ENABLED",
4329
- "bool",
4330
- config.enabled ? "true" : "false",
4331
- "When true, usage telemetry received from the events service is forwarded to the OpenCRVS status service.",
4332
- true
4333
- );
4334
- upsertEnvVar(
4335
- sourceFile,
4336
- "COUNTRY_CODE",
4337
- "str",
4338
- config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`,
4339
- "ISO-style country code of this instance, reported with telemetry.",
4340
- config.enabled
4341
- );
4342
- upsertEnvVar(
4343
- sourceFile,
4344
- "ORGANISATION",
4345
- "str",
4346
- config.enabled ? JSON.stringify(config.organisation) : `''`,
4347
- "Organisation running this instance, reported with telemetry. Empty by default.",
4348
- config.enabled
4349
- );
4350
- upsertEnvVar(
4351
- sourceFile,
4352
- "ENVIRONMENT_NAME",
4353
- "str",
4354
- `'development'`,
4355
- 'Environment name (e.g. "production", "staging") reported as the telemetry environment.',
4356
- false
4357
- );
4358
- }
4359
- function ensureHandlerNamedImports(sourceFile, names) {
4360
- const importDeclaration = sourceFile.getImportDeclarations().find(
4361
- (declaration) => declaration.getModuleSpecifierValue() === HANDLER_MODULE
4362
- );
4363
- if (!importDeclaration) {
4364
- sourceFile.addImportDeclaration({
4365
- moduleSpecifier: HANDLER_MODULE,
4366
- namedImports: names
4367
- });
4368
- console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
4369
- return;
4370
- }
4371
- const existing = new Set(
4372
- importDeclaration.getNamedImports().map((named) => named.getName())
4373
- );
4374
- const missing = names.filter((name) => !existing.has(name));
4375
- for (const name of missing) {
4376
- importDeclaration.addNamedImport(name);
4377
- }
4378
- if (missing.length > 0) {
4379
- console.log(
4380
- ` \u2713 ${INDEX_FILE}: import ${missing.join(", ")} from ${HANDLER_MODULE}`
4381
- );
4382
- }
4383
- }
4384
- function wireIndex(project, cwd) {
4385
- const sourceFile = project.addSourceFileAtPathIfExists(
4386
- import_path4.default.join(cwd, INDEX_FILE)
4387
- );
4388
- if (!sourceFile) {
4389
- warnSkipped3(
4390
- `${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`
4391
- );
4392
- return;
4393
- }
4394
- ensureHandlerNamedImports(sourceFile, [
4395
- "telemetryHandler",
4396
- "telemetrySchema",
4397
- "TELEMETRY_DISABLED_NOTICE"
4398
- ]);
4399
- if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
4400
- const lastRouteStatement = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter((call) => call.getExpression().getText() === "server.route").map(
4401
- (call) => call.getFirstAncestorByKind(import_ts_morph3.SyntaxKind.ExpressionStatement)
4402
- ).filter(
4403
- (statement) => Boolean(statement)
4404
- ).pop();
4405
- if (!lastRouteStatement) {
4406
- warnSkipped3(
4407
- `Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`
4408
- );
4409
- } else {
4410
- const indent = lastRouteStatement.getIndentationText();
4411
- const route = [
4412
- `server.route({`,
4413
- ` method: 'POST',`,
4414
- ` path: '/trigger/telemetry',`,
4415
- ` handler: telemetryHandler,`,
4416
- ` options: {`,
4417
- ` tags: ['api', 'triggers'],`,
4418
- ` validate: {`,
4419
- ` payload: telemetrySchema`,
4420
- ` },`,
4421
- ` description:`,
4422
- ` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
4423
- ` }`,
4424
- `})`
4425
- ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4426
- sourceFile.insertText(lastRouteStatement.getEnd(), `
4427
-
4428
- ${route}`);
4429
- console.log(` \u2713 ${INDEX_FILE}: POST /trigger/telemetry`);
4430
- }
4431
- }
4432
- if (!sourceFile.getText().includes("logger.info(TELEMETRY_DISABLED_NOTICE)")) {
4433
- const startedLog = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.ExpressionStatement).find(
4434
- (statement) => statement.getText().includes("Server successfully started")
4435
- );
4436
- if (!startedLog) {
4437
- warnSkipped3(
4438
- `Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`
4439
- );
4440
- } else {
4441
- const indent = startedLog.getIndentationText();
4442
- const notice = [
4443
- `if (!env.TELEMETRY_ENABLED) {`,
4444
- ` logger.info(TELEMETRY_DISABLED_NOTICE)`,
4445
- `}`
4446
- ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4447
- sourceFile.insertText(startedLog.getEnd(), `
4448
-
4449
- ${notice}`);
4450
- console.log(` \u2713 ${INDEX_FILE}: telemetry-disabled startup notice`);
4451
- if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "./environment")) {
4452
- warnSkipped3(
4453
- `The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`
4454
- );
4455
- }
4456
- }
4457
- }
4458
- }
4459
- async function main4() {
4460
- const cwd = process.cwd();
4461
- const config = await promptTelemetryConfig();
4462
- console.log(
4463
- `
4464
- Adding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : "disabled"} by default)...
4465
- `
3642
+ // src/migrations/move-declaration-to-declare-action.ts
3643
+ var import_ts_morph = require("ts-morph");
3644
+ var import_path2 = __toESM(require("path"));
3645
+ var DEFINE_CONFIG_NAME = "defineConfig";
3646
+ var DECLARATION_PROPERTY_NAME = "declaration";
3647
+ var ACTIONS_PROPERTY_NAME = "actions";
3648
+ var DECLARE_ACTION_TYPE = "DECLARE";
3649
+ function location(node) {
3650
+ const relPath = import_path2.default.relative(
3651
+ process.cwd(),
3652
+ node.getSourceFile().getFilePath()
4466
3653
  );
4467
- writeTelemetryHandler(cwd);
4468
- const project = new import_ts_morph3.Project({
4469
- // ts-morph indents inserted code with four spaces and double-quotes strings
4470
- // by default, both of which the country config's prettier run would undo.
4471
- manipulationSettings: {
4472
- indentationText: import_ts_morph3.IndentationText.TwoSpaces,
4473
- quoteKind: import_ts_morph3.QuoteKind.Single
4474
- }
4475
- });
4476
- addEnvironmentVariables(project, cwd, config);
4477
- wireIndex(project, cwd);
4478
- await project.save();
4479
- if (skipped3.length > 0) {
4480
- console.warn(
4481
- `
4482
- \u26A0\uFE0F ${skipped3.length} telemetry step(s) were skipped. Wire the following by hand:`
4483
- );
4484
- for (const message of skipped3) {
4485
- console.warn(` - ${message}`);
4486
- }
4487
- }
3654
+ return `${relPath}:${node.getStartLineNumber()}`;
4488
3655
  }
4489
-
4490
- // src/migrations/v2.1/migrate-infrastructure-to-assets.ts
4491
- var import_child_process = require("child_process");
4492
- var import_fs5 = require("fs");
4493
- var import_os = require("os");
4494
- var import_path6 = __toESM(require("path"));
4495
-
4496
- // src/migrations/v2.1/template-files.ts
4497
- var import_fs4 = require("fs");
4498
- var import_path5 = __toESM(require("path"));
4499
- function findTemplateDir() {
4500
- const candidates = [
4501
- import_path5.default.resolve(__dirname, "templates", "countryconfig-template"),
4502
- import_path5.default.resolve(__dirname, "../../../../countryconfig-template")
4503
- ];
4504
- const templateDir = candidates.find(
4505
- (candidate) => (0, import_fs4.existsSync)(import_path5.default.join(candidate, "Tiltfile"))
4506
- );
4507
- if (!templateDir) {
4508
- throw new Error(
4509
- `Country config template files not found in any of: ${candidates.join(", ")}`
4510
- );
3656
+ function isToolkitDefineConfigCall(call) {
3657
+ const symbol = call.getExpression().getSymbol();
3658
+ const resolved = symbol?.getAliasedSymbol() ?? symbol;
3659
+ if (resolved?.getName() !== DEFINE_CONFIG_NAME) {
3660
+ return false;
4511
3661
  }
4512
- return templateDir;
3662
+ return resolved.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
4513
3663
  }
4514
- function listFiles(root, dir) {
4515
- const absolute = import_path5.default.join(root, dir);
4516
- if (!(0, import_fs4.existsSync)(absolute)) {
4517
- return [];
4518
- }
4519
- return (0, import_fs4.readdirSync)(absolute, { withFileTypes: true }).flatMap((entry) => {
4520
- const relative = import_path5.default.posix.join(dir, entry.name);
4521
- return entry.isDirectory() ? listFiles(root, relative) : [relative];
4522
- });
3664
+ function findProperty(literal, name) {
3665
+ const property = literal.getProperty(name);
3666
+ return import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property) ? property : void 0;
4523
3667
  }
4524
-
4525
- // src/migrations/v2.1/migrate-infrastructure-to-assets.ts
4526
- var INFRASTRUCTURE_DIR = "infrastructure";
4527
- var ASSETS_DIR = "assets";
4528
- var BASE_URL = "https://raw.githubusercontent.com/opencrvs/opencrvs-farajaland/release/v2.0.0/infrastructure";
4529
- var SOURCE_OF = {
4530
- "elasticsearch/reindex.sh": "deployment/reindex.sh"
4531
- };
4532
- var MIGRATED_DIRS = ["metabase", "postgres", "deployment", "elasticsearch"];
4533
- var NOT_MOVED = ["postgres/on-deploy.sh"];
4534
- var isMigrated = (file) => MIGRATED_DIRS.some((dir) => file.startsWith(`${dir}/`));
4535
- function tryGit(args2) {
4536
- try {
4537
- (0, import_child_process.execFileSync)("git", args2, { stdio: "ignore" });
3668
+ function mayHaveDeclareType(actionType, node) {
3669
+ const typeProperty = actionType.getProperty("type");
3670
+ if (!typeProperty) {
4538
3671
  return true;
4539
- } catch {
4540
- return false;
4541
3672
  }
3673
+ const type = typeProperty.getTypeAtLocation(node);
3674
+ const values = type.isUnion() ? type.getUnionTypes() : [type];
3675
+ return !values.every(
3676
+ (value) => value.isStringLiteral() && value.getLiteralValue() !== DECLARE_ACTION_TYPE
3677
+ );
4542
3678
  }
4543
- function assertIsGitRepo() {
4544
- if (!tryGit(["rev-parse", "--is-inside-work-tree"])) {
4545
- throw new Error(
4546
- `${process.cwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
4547
- );
3679
+ function mayBeDeclareAction(node) {
3680
+ if (import_ts_morph.Node.isObjectLiteralExpression(node)) {
3681
+ return isDeclareAction(node);
4548
3682
  }
4549
- }
4550
- var toBytes = (buffer) => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
4551
- var sameBytes = (a, b) => a.length === b.length && a.every((byte, index) => byte === b[index]);
4552
- var isBinary = (contents) => contents.includes(0);
4553
- function readIfExists(file) {
4554
- return (0, import_fs5.existsSync)(file) ? toBytes((0, import_fs5.readFileSync)(file)) : void 0;
4555
- }
4556
- function mergeFile(file, ours, base, theirs) {
4557
- const dir = (0, import_fs5.mkdtempSync)(import_path6.default.join((0, import_os.tmpdir)(), "opencrvs-merge-assets-"));
4558
- try {
4559
- const [oursPath, basePath, theirsPath] = ["ours", "base", "theirs"].map(
4560
- (name) => import_path6.default.join(dir, name)
3683
+ if (import_ts_morph.Node.isSpreadElement(node)) {
3684
+ const arrayType = node.getExpression().getType();
3685
+ const elementTypes = arrayType.isTuple() ? arrayType.getTupleElements() : [arrayType.getArrayElementType()];
3686
+ return elementTypes.some(
3687
+ (elementType) => !elementType || mayHaveDeclareType(elementType, node)
4561
3688
  );
4562
- (0, import_fs5.writeFileSync)(oursPath, ours);
4563
- (0, import_fs5.writeFileSync)(basePath, base);
4564
- (0, import_fs5.writeFileSync)(theirsPath, theirs);
4565
- const args2 = [
4566
- "merge-file",
4567
- "-q",
4568
- "-L",
4569
- `infrastructure/${file}`,
4570
- "-L",
4571
- "v2.0",
4572
- "-L",
4573
- `v2.1 template`,
4574
- oursPath,
4575
- basePath,
4576
- theirsPath
4577
- ];
4578
- let conflicts = 0;
4579
- try {
4580
- (0, import_child_process.execFileSync)("git", args2, { stdio: "ignore" });
4581
- } catch (error3) {
4582
- const { status } = error3;
4583
- if (!status || status >= 255) throw error3;
4584
- conflicts = status;
4585
- }
4586
- return { contents: toBytes((0, import_fs5.readFileSync)(oursPath)), conflicts };
4587
- } finally {
4588
- (0, import_fs5.rmSync)(dir, { recursive: true, force: true });
4589
3689
  }
3690
+ return mayHaveDeclareType(node.getType(), node);
4590
3691
  }
4591
- async function fetchBases(files) {
4592
- const bases = /* @__PURE__ */ new Map();
4593
- for (const file of files) {
4594
- const url = `${BASE_URL}/${file}`;
4595
- const response = await fetch(url);
4596
- if (response.ok) {
4597
- bases.set(file, new Uint8Array(await response.arrayBuffer()));
4598
- } else if (response.status !== 404) {
4599
- throw new Error(
4600
- `GitHub answered ${response.status} ${response.statusText} for ${url}`
4601
- );
4602
- }
4603
- }
4604
- return bases;
4605
- }
4606
- function migrateInfrastructureToAssets(cwd, templateDir, readBase) {
4607
- const infrastructure = import_path6.default.join(cwd, INFRASTRUCTURE_DIR);
4608
- const templateAssets = import_path6.default.join(templateDir, ASSETS_DIR);
4609
- const relativeTo = (dir) => (file) => file.slice(dir.length + 1);
4610
- const localFiles = listFiles(cwd, INFRASTRUCTURE_DIR).map(relativeTo(INFRASTRUCTURE_DIR)).filter(isMigrated);
4611
- const templateFiles = listFiles(templateDir, ASSETS_DIR).map(
4612
- relativeTo(ASSETS_DIR)
4613
- );
4614
- const outcomes = {};
4615
- const migrated = /* @__PURE__ */ new Set();
4616
- for (const file of [.../* @__PURE__ */ new Set([...templateFiles, ...localFiles])].sort()) {
4617
- const sourceFile = !localFiles.includes(file) && localFiles.includes(SOURCE_OF[file]) ? SOURCE_OF[file] : file;
4618
- const ours = readIfExists(import_path6.default.join(infrastructure, sourceFile));
4619
- const theirsPath = import_path6.default.join(templateAssets, file);
4620
- const theirs = readIfExists(theirsPath);
4621
- const base = ours && readBase(sourceFile);
4622
- const target = import_path6.default.join(cwd, ASSETS_DIR, file);
4623
- if (NOT_MOVED.includes(file)) {
4624
- if (ours && base && sameBytes(ours, base)) {
4625
- migrated.add(file);
4626
- outcomes[file] = "dropped";
4627
- } else if (ours) {
4628
- outcomes[file] = "not-moved";
4629
- }
4630
- continue;
4631
- }
4632
- const ownsSource = ours !== void 0 && sourceFile === file;
4633
- if ((0, import_fs5.existsSync)(target)) {
4634
- if (ownsSource) {
4635
- const same = sameBytes(toBytes((0, import_fs5.readFileSync)(target)), ours);
4636
- if (same) {
4637
- migrated.add(file);
4638
- }
4639
- outcomes[file] = same ? "exists" : "exists-differs";
4640
- }
4641
- continue;
4642
- }
4643
- if (ownsSource) {
4644
- migrated.add(file);
4645
- }
4646
- let contents;
4647
- let outcome;
4648
- if (!ours) {
4649
- contents = theirs;
4650
- outcome = "copied";
4651
- } else if (!theirs) {
4652
- const unchanged = base && sameBytes(ours, base);
4653
- contents = unchanged ? void 0 : ours;
4654
- outcome = unchanged ? "dropped" : "kept";
4655
- } else if (sameBytes(ours, theirs) || base && sameBytes(ours, base)) {
4656
- contents = theirs;
4657
- outcome = "copied";
4658
- } else if (!base || sameBytes(base, theirs) || isBinary(ours)) {
4659
- contents = ours;
4660
- outcome = "kept";
4661
- } else {
4662
- const result = mergeFile(sourceFile, ours, base, theirs);
4663
- contents = result.contents;
4664
- outcome = result.conflicts > 0 ? "conflict" : "merged";
4665
- }
4666
- outcomes[file] = outcome;
4667
- if (contents === void 0) {
4668
- continue;
4669
- }
4670
- (0, import_fs5.mkdirSync)(import_path6.default.dirname(target), { recursive: true });
4671
- (0, import_fs5.writeFileSync)(target, contents);
4672
- const modeSource = ours && outcome === "kept" ? import_path6.default.join(infrastructure, sourceFile) : theirsPath;
4673
- if ((0, import_fs5.existsSync)(modeSource)) {
4674
- (0, import_fs5.chmodSync)(target, (0, import_fs5.statSync)(modeSource).mode & 511);
4675
- }
4676
- }
4677
- return { outcomes, migrated: [...migrated].sort() };
3692
+ function isDeclareAction(literal) {
3693
+ const type = findProperty(literal, "type");
3694
+ return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === DECLARE_ACTION_TYPE;
4678
3695
  }
4679
- function removeMigrated(cwd, migrated) {
4680
- const infrastructure = import_path6.default.join(cwd, INFRASTRUCTURE_DIR);
4681
- for (const file of migrated) {
4682
- (0, import_fs5.rmSync)(import_path6.default.join(infrastructure, file), { force: true });
4683
- }
4684
- const pruneEmpty = (dir) => {
4685
- if (!(0, import_fs5.existsSync)(dir)) {
4686
- return true;
4687
- }
4688
- const empty = (0, import_fs5.readdirSync)(dir, { withFileTypes: true }).map(
4689
- (entry) => entry.isDirectory() ? pruneEmpty(import_path6.default.join(dir, entry.name)) : false
4690
- ).every(Boolean);
4691
- if (empty) {
4692
- (0, import_fs5.rmdirSync)(dir);
4693
- }
4694
- return empty;
4695
- };
4696
- pruneEmpty(infrastructure);
4697
- }
4698
- var DESCRIPTIONS = {
4699
- copied: "from the template",
4700
- kept: "country's version",
4701
- merged: "merged",
4702
- conflict: "CONFLICT, resolve the markers by hand",
4703
- dropped: "dropped, no longer used",
4704
- exists: "already migrated",
4705
- "exists-differs": "already exists with different contents; infrastructure/ copy kept for review",
4706
- "not-moved": "changed locally but not moved: the chart runs its own on-deploy script, port your changes there"
4707
- };
4708
- async function main5(dockerSwarm = false) {
4709
- const cwd = process.cwd();
4710
- console.log("Moving infrastructure/ into assets/...\n");
4711
- const templateDir = findTemplateDir();
4712
- if ((0, import_fs5.existsSync)(import_path6.default.join(cwd, INFRASTRUCTURE_DIR))) {
4713
- assertIsGitRepo();
4714
- const needed = listFiles(cwd, INFRASTRUCTURE_DIR).map((file) => file.slice(INFRASTRUCTURE_DIR.length + 1)).filter(isMigrated);
4715
- let bases;
4716
- try {
4717
- bases = await fetchBases(needed);
4718
- } catch (error3) {
4719
- console.warn(
4720
- ` \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.`
4721
- );
4722
- return;
4723
- }
4724
- const { outcomes, migrated } = migrateInfrastructureToAssets(
4725
- cwd,
4726
- templateDir,
4727
- (file) => bases.get(file)
4728
- );
4729
- for (const [file, outcome] of Object.entries(outcomes)) {
4730
- const needsReview = ["conflict", "not-moved", "exists-differs"].includes(
4731
- outcome
4732
- );
4733
- const shown = outcome === "not-moved" ? INFRASTRUCTURE_DIR : ASSETS_DIR;
4734
- const line2 = ` ${needsReview ? "\u26A0\uFE0F " : "\u2713"} ${shown}/${file}: ${DESCRIPTIONS[outcome]}`;
4735
- if (needsReview) {
4736
- console.warn(line2);
4737
- } else {
4738
- console.log(line2);
4739
- }
4740
- }
4741
- if (dockerSwarm) {
4742
- console.log(
4743
- "\n infrastructure/ kept in place (--docker-swarm); assets/ now holds a copy."
4744
- );
4745
- } else {
4746
- removeMigrated(cwd, migrated);
4747
- }
4748
- tryGit(["add", "-A", "--", ASSETS_DIR, INFRASTRUCTURE_DIR]);
4749
- const conflicts = Object.keys(outcomes).filter(
4750
- (file) => outcomes[file] === "conflict"
3696
+ function findDeclareAction(config) {
3697
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
3698
+ const actionsValue = import_ts_morph.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
3699
+ if (!import_ts_morph.Node.isArrayLiteralExpression(actionsValue)) {
3700
+ console.warn(
3701
+ ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`
4751
3702
  );
4752
- for (const file of conflicts) {
4753
- tryGit(["restore", "--staged", "--", `${ASSETS_DIR}/${file}`]);
4754
- }
4755
- if (conflicts.length > 0) {
4756
- console.warn(
4757
- `
4758
- \u26A0\uFE0F ${conflicts.length} file(s) need their conflicts resolved: ${conflicts.map((file) => `assets/${file}`).join(", ")}`
4759
- );
4760
- }
4761
- if ((0, import_fs5.existsSync)(import_path6.default.join(cwd, INFRASTRUCTURE_DIR)) && !dockerSwarm) {
4762
- console.warn(
4763
- " \u26A0\uFE0F infrastructure/ still has files the Kubernetes deployment does not use. Review and delete them if they are no longer needed."
4764
- );
4765
- }
4766
- } else {
4767
- console.log(" infrastructure/ not found, nothing to move.");
3703
+ return void 0;
4768
3704
  }
4769
- const dockerfile = toBytes(
4770
- (0, import_fs5.readFileSync)(import_path6.default.join(templateDir, "Dockerfile.assets"))
4771
- );
4772
- const current = readIfExists(import_path6.default.join(cwd, "Dockerfile.assets"));
4773
- if (!current || !sameBytes(current, dockerfile)) {
4774
- (0, import_fs5.writeFileSync)(import_path6.default.join(cwd, "Dockerfile.assets"), dockerfile);
4775
- tryGit(["add", "--", "Dockerfile.assets"]);
4776
- console.log(" \u2713 Dockerfile.assets replaced with the template version");
3705
+ const candidates = actionsValue.getElements().filter(mayBeDeclareAction);
3706
+ if (candidates.length !== 1 || !import_ts_morph.Node.isObjectLiteralExpression(candidates[0])) {
3707
+ console.warn(
3708
+ ` [${location(config)}] Skipped: could not find exactly one ${DECLARE_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME}\`. Move \`${DECLARATION_PROPERTY_NAME}\` onto it by hand.`
3709
+ );
3710
+ return void 0;
4777
3711
  }
4778
- }
4779
-
4780
- // src/migrations/v2.1/remove-metabase-package-installs.ts
4781
- var import_fs6 = require("fs");
4782
- var import_path7 = require("path");
4783
- var METABASE_DIRS = ["infrastructure/metabase", "assets/metabase"];
4784
- var APK_BLOCK = [
4785
- "apk update",
4786
- "apk upgrade",
4787
- "apk add --no-cache gettext",
4788
- "apk add --no-cache util-linux",
4789
- "",
4790
- ""
4791
- ].join("\n");
4792
- var SALT_LINE = "export OPENCRVS_METABASE_ADMIN_PASSWORD_SALT=$(uuidgen)\n";
4793
- var FIXED_SALT_LINE = "export OPENCRVS_METABASE_ADMIN_PASSWORD_SALT=$(cat /proc/sys/kernel/random/uuid 2>/dev/null || uuidgen)\n\n";
4794
- var FIXED_SALT_MARKER = "/proc/sys/kernel/random/uuid";
4795
- var ENVSUBST_GUARD = [
4796
- "if ! which envsubst >/dev/null; then",
4797
- ' echo "envsubst could not be found. Please install envsubst before continuing."',
4798
- ' echo "MacOS: brew install gettext && brew link --force gettext"',
4799
- " exit 1",
4800
- "fi",
4801
- ""
4802
- ].join("\n");
4803
- var ENVSUBST_CALL = "envsubst < $environment_configuration_sql_file > $environment_configuration_sql_file.tmp\n";
4804
- var FIXED_EXPANSION = [
4805
- "",
4806
- "# Expand $VAR / ${VAR} using bash's own heredoc expansion instead of envsubst,",
4807
- "# because envsubst is not installed in the Metabase image",
4808
- 'eval "cat <<OPENCRVS_ENV_EOF',
4809
- '$(cat "$environment_configuration_sql_file")',
4810
- 'OPENCRVS_ENV_EOF" > "$environment_configuration_sql_file.tmp"',
4811
- ""
4812
- ].join("\n");
4813
- var FIXED_EXPANSION_MARKER = "OPENCRVS_ENV_EOF";
4814
- function patchRunScript(source) {
4815
- if (source.includes(FIXED_SALT_MARKER) && !source.includes(APK_BLOCK)) {
4816
- return source;
4817
- }
4818
- if (!source.includes(APK_BLOCK) || !source.includes(SALT_LINE)) {
3712
+ const declareAction = candidates[0];
3713
+ if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
3714
+ console.warn(
3715
+ ` [${location(config)}] Skipped: \`${DECLARATION_PROPERTY_NAME}\` is set both at the top level and on the ${DECLARE_ACTION_TYPE} action. Keep only the one on the action.`
3716
+ );
4819
3717
  return void 0;
4820
3718
  }
4821
- return source.replace(APK_BLOCK, "").replace(SALT_LINE, FIXED_SALT_LINE);
3719
+ return declareAction;
4822
3720
  }
4823
- function patchUpdateDatabaseScript(source) {
4824
- if (source.includes(FIXED_EXPANSION_MARKER) && !source.includes(ENVSUBST_CALL)) {
4825
- return source;
3721
+ function indentationOf(node) {
3722
+ const text = node.getSourceFile().getFullText();
3723
+ const lineStart = text.lastIndexOf("\n", node.getStart() - 1) + 1;
3724
+ return /^[ \t]*/.exec(text.slice(lineStart))?.[0] ?? "";
3725
+ }
3726
+ function restOfLine(text, position) {
3727
+ const lineEnd = text.indexOf("\n", position);
3728
+ return text.slice(position, lineEnd === -1 ? text.length : lineEnd);
3729
+ }
3730
+ function isOnlyComments(text) {
3731
+ return /^\s*(?:\/\/.*|\/\*.*?\*\/\s*)*$/.test(text);
3732
+ }
3733
+ function layoutOf(property) {
3734
+ const text = property.getSourceFile().getFullText();
3735
+ const next = property.getNextSibling();
3736
+ const hasComma = next?.getKind() === import_ts_morph.SyntaxKind.CommaToken;
3737
+ const end = next && hasComma ? next.getEnd() : property.getEnd();
3738
+ const trailing = restOfLine(text, end);
3739
+ const lineBreak = text.slice(property.getFullStart(), property.getStart()).indexOf("\n");
3740
+ if (lineBreak === -1 || !isOnlyComments(trailing)) {
3741
+ return {
3742
+ ownsLines: false,
3743
+ start: property.getStart(true),
3744
+ end,
3745
+ hasComma,
3746
+ trailingComment: ""
3747
+ };
4826
3748
  }
4827
- if (!source.includes(ENVSUBST_GUARD) || !source.includes(ENVSUBST_CALL)) {
4828
- return void 0;
3749
+ const firstLine = property.getFullStart() + lineBreak + 1;
3750
+ return {
3751
+ ownsLines: true,
3752
+ start: firstLine + (/^\s*/.exec(text.slice(firstLine))?.[0].length ?? 0),
3753
+ end,
3754
+ hasComma,
3755
+ trailingComment: trailing.trimEnd()
3756
+ };
3757
+ }
3758
+ function insertAt(position, text) {
3759
+ return { start: position, end: position, text };
3760
+ }
3761
+ function insertIntoDeclareAction(declareAction, property) {
3762
+ const anchor = declareAction.getProperty("label") ?? declareAction.getPropertyOrThrow("type");
3763
+ const text = property.getSourceFile().getFullText();
3764
+ const anchorLayout = layoutOf(anchor);
3765
+ const layout = layoutOf(property);
3766
+ const indent = indentationOf(anchor);
3767
+ const oldIndent = indentationOf(property);
3768
+ const reindent = (lines) => lines.split("\n").map(
3769
+ (line2, index) => index > 0 && line2.startsWith(oldIndent) ? indent + line2.slice(oldIndent.length) : line2
3770
+ ).join("\n");
3771
+ if (anchorLayout.ownsLines) {
3772
+ const moved = reindent(text.slice(layout.start, property.getEnd()));
3773
+ const position = anchorLayout.end + restOfLine(text, anchorLayout.end).length;
3774
+ const insertion = `
3775
+ ${indent}${moved}${anchorLayout.hasComma ? "," : ""}${layout.trailingComment}`;
3776
+ if (anchorLayout.hasComma) {
3777
+ return [insertAt(position, insertion)];
3778
+ }
3779
+ return position === anchor.getEnd() ? [insertAt(position, `,${insertion}`)] : [insertAt(anchor.getEnd(), ","), insertAt(position, insertion)];
3780
+ }
3781
+ const droppedComments = text.slice(layout.start, property.getStart(true)).trim() !== "" || layout.trailingComment !== "";
3782
+ if (droppedComments) {
3783
+ console.warn(
3784
+ ` [${location(property)}] The comments next to \`${DECLARATION_PROPERTY_NAME}\` were not moved with it. Move them onto the ${DECLARE_ACTION_TYPE} action by hand.`
3785
+ );
4829
3786
  }
4830
- return source.replace(ENVSUBST_GUARD, "").replace(ENVSUBST_CALL, FIXED_EXPANSION);
3787
+ const isMultiLine = declareAction.getText().includes("\n");
3788
+ const separator = isMultiLine ? `,
3789
+ ${indent}` : ", ";
3790
+ return [
3791
+ insertAt(anchor.getEnd(), `${separator}${reindent(property.getText(true))}`)
3792
+ ];
4831
3793
  }
4832
- function patchFile(relativePath, patch, removed) {
4833
- const filePath = (0, import_path7.join)(process.cwd(), relativePath);
4834
- if (!(0, import_fs6.existsSync)(filePath)) {
4835
- return;
3794
+ function removeFromConfig(property) {
3795
+ const text = property.getSourceFile().getFullText();
3796
+ const layout = layoutOf(property);
3797
+ const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph.SyntaxKind.CommaToken);
3798
+ if (layout.ownsLines) {
3799
+ const lines = {
3800
+ start: text.lastIndexOf("\n", layout.start - 1),
3801
+ end: layout.end + restOfLine(text, layout.end).length,
3802
+ text: ""
3803
+ };
3804
+ return !layout.hasComma && previousComma ? [
3805
+ lines,
3806
+ {
3807
+ start: previousComma.getStart(),
3808
+ end: previousComma.getEnd(),
3809
+ text: ""
3810
+ }
3811
+ ] : [lines];
3812
+ }
3813
+ if (layout.hasComma) {
3814
+ return [{ start: property.getFullStart(), end: layout.end, text: "" }];
3815
+ }
3816
+ return [
3817
+ {
3818
+ start: (previousComma ?? property).getStart(),
3819
+ end: property.getEnd(),
3820
+ text: ""
3821
+ }
3822
+ ];
3823
+ }
3824
+ function findConfigLiteral(call) {
3825
+ const config = call.getArguments()[0];
3826
+ if (!config || import_ts_morph.Node.isObjectLiteralExpression(config)) {
3827
+ return config;
4836
3828
  }
4837
- const source = (0, import_fs6.readFileSync)(filePath, "utf8");
4838
- const patched = patch(source);
4839
- if (patched === void 0) {
3829
+ if (config.getType().getProperty(DECLARATION_PROPERTY_NAME)) {
4840
3830
  console.warn(
4841
- ` \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.`
3831
+ ` [${location(config)}] Skipped: \`${DEFINE_CONFIG_NAME}\` is not given an object literal. If its config has a top-level \`${DECLARATION_PROPERTY_NAME}\`, move it onto the ${DECLARE_ACTION_TYPE} action by hand.`
4842
3832
  );
4843
- return;
4844
3833
  }
4845
- if (patched === source) {
3834
+ return void 0;
3835
+ }
3836
+ function moveDeclarationToDeclareAction(sourceFile) {
3837
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph.Node.isObjectLiteralExpression);
3838
+ const edits = [];
3839
+ let changes = 0;
3840
+ for (const config of configs) {
3841
+ const declaration = findProperty(config, DECLARATION_PROPERTY_NAME);
3842
+ if (!declaration) {
3843
+ continue;
3844
+ }
3845
+ const declareAction = findDeclareAction(config);
3846
+ if (!declareAction) {
3847
+ continue;
3848
+ }
3849
+ console.log(
3850
+ ` [${location(declaration)}] Moved \`${declaration.getText()}\` onto the ${DECLARE_ACTION_TYPE} action`
3851
+ );
3852
+ edits.push(
3853
+ ...insertIntoDeclareAction(declareAction, declaration),
3854
+ ...removeFromConfig(declaration)
3855
+ );
3856
+ changes++;
3857
+ }
3858
+ if (changes === 0) {
3859
+ return 0;
3860
+ }
3861
+ const text = edits.sort((a, b) => b.start - a.start).reduce(
3862
+ (result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end),
3863
+ sourceFile.getFullText()
3864
+ );
3865
+ sourceFile.replaceWithText(text);
3866
+ return changes;
3867
+ }
3868
+ async function main2() {
3869
+ const srcDir = import_path2.default.join(process.cwd(), "src");
3870
+ console.log(`Scanning for top-level event declarations in: ${srcDir}
3871
+ `);
3872
+ const project = new import_ts_morph.Project({
3873
+ tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
3874
+ skipAddingFilesFromTsConfig: false
3875
+ });
3876
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3877
+ const fp = sf.getFilePath();
3878
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3879
+ });
3880
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3881
+ `);
3882
+ let totalChanges = 0;
3883
+ const modifiedFiles = [];
3884
+ for (const sourceFile of sourceFiles) {
3885
+ const changes = moveDeclarationToDeclareAction(sourceFile);
3886
+ if (changes > 0) {
3887
+ totalChanges += changes;
3888
+ modifiedFiles.push(sourceFile);
3889
+ }
3890
+ }
3891
+ if (modifiedFiles.length === 0) {
3892
+ console.log("No top-level event declarations found. Nothing to do.");
4846
3893
  return;
4847
3894
  }
4848
- (0, import_fs6.writeFileSync)(filePath, patched);
4849
- console.log(` \u2713 ${relativePath}: ${removed}`);
4850
- }
4851
- async function main6() {
4852
- console.log("\nRemoving the Metabase package installs...\n");
4853
- for (const dir of METABASE_DIRS) {
4854
- patchFile((0, import_path7.join)(dir, "run.sh"), patchRunScript, "apk add gettext util-linux");
4855
- patchFile(
4856
- (0, import_path7.join)(dir, "update-database.sh"),
4857
- patchUpdateDatabaseScript,
4858
- "envsubst"
3895
+ console.log(`
3896
+ Saving ${modifiedFiles.length} modified file(s)...`);
3897
+ for (const sourceFile of modifiedFiles) {
3898
+ await sourceFile.save();
3899
+ console.log(
3900
+ ` Saved: ${import_path2.default.relative(process.cwd(), sourceFile.getFilePath())}`
4859
3901
  );
4860
3902
  }
3903
+ console.log(
3904
+ `
3905
+ Done. Moved ${totalChanges} declaration(s) across ${modifiedFiles.length} file(s).`
3906
+ );
4861
3907
  }
4862
3908
 
4863
- // src/migrations/v2.1/remove-sentry.ts
4864
- var import_fs7 = require("fs");
4865
- var import_path8 = __toESM(require("path"));
4866
- var import_ts_morph4 = require("ts-morph");
4867
- var CONFIG_FILES = [
4868
- "src/client-config.ts",
4869
- "src/client-config.prod.ts",
4870
- "src/login-config.ts",
4871
- "src/login-config.prod.ts"
4872
- ];
4873
- var ENVIRONMENT_FILE2 = "src/environment.ts";
4874
- var CONSTANTS_FILE = "src/constants.ts";
4875
- var INDEX_FILE2 = "src/index.ts";
4876
- var UTILS_FILE = "src/utils/index.ts";
4877
- var PACKAGE_JSON_FILE = "package.json";
4878
- var TYPINGS_FILE = "typings/hapi-sentry.d.ts";
4879
- var SENTRY_PLUGIN = "hapi-sentry";
4880
- var skipped4 = [];
4881
- function warnSkipped4(message) {
4882
- skipped4.push(message);
4883
- console.warn(` \u26A0\uFE0F ${message}`);
3909
+ // src/migrations/read-declaration-through-helper.ts
3910
+ var import_ts_morph2 = require("ts-morph");
3911
+ var import_path3 = __toESM(require("path"));
3912
+ var EVENT_CONFIG_TYPE_NAME = "EventConfig";
3913
+ var DECLARATION_PROPERTY_NAME2 = "declaration";
3914
+ var GET_DECLARATION_NAME = "getDeclaration";
3915
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3916
+ function isToolkitEventConfig(type) {
3917
+ const nonNullableType = type.getNonNullableType();
3918
+ const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
3919
+ if (symbol?.getName() !== EVENT_CONFIG_TYPE_NAME) {
3920
+ return false;
3921
+ }
3922
+ return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
4884
3923
  }
4885
- function isReferenced(sourceFile, name) {
4886
- return sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.Identifier).some(
4887
- (identifier) => identifier.getText() === name && !identifier.getFirstAncestorByKind(import_ts_morph4.SyntaxKind.ImportDeclaration)
4888
- );
3924
+ function isDeclarationReadOnEventConfig(node) {
3925
+ return node.getName() === DECLARATION_PROPERTY_NAME2 && isToolkitEventConfig(node.getExpression().getType());
4889
3926
  }
4890
- function removeIfUnused(sourceFile, importDeclaration) {
4891
- const names = [
4892
- importDeclaration.getDefaultImport()?.getText(),
4893
- importDeclaration.getNamespaceImport()?.getText(),
4894
- ...importDeclaration.getNamedImports().map((named) => named.getName())
4895
- ].filter((name) => Boolean(name));
4896
- if (names.length > 0 && names.every((name) => !isReferenced(sourceFile, name))) {
4897
- importDeclaration.remove();
3927
+ function isAssignmentOperator(kind) {
3928
+ return kind >= import_ts_morph2.SyntaxKind.FirstAssignment && kind <= import_ts_morph2.SyntaxKind.LastAssignment;
3929
+ }
3930
+ function isWriteTarget(node) {
3931
+ const parent = node.getParent();
3932
+ if (import_ts_morph2.Node.isDeleteExpression(parent)) {
4898
3933
  return true;
4899
3934
  }
4900
- return false;
3935
+ return import_ts_morph2.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
4901
3936
  }
4902
- function removeNamedImport(sourceFile, moduleSpecifier, name) {
4903
- const importDeclaration = sourceFile.getImportDeclarations().find(
4904
- (declaration) => declaration.getModuleSpecifierValue() === moduleSpecifier
3937
+ function location2(node) {
3938
+ const relPath = import_path3.default.relative(
3939
+ process.cwd(),
3940
+ node.getSourceFile().getFilePath()
4905
3941
  );
4906
- if (!importDeclaration) return false;
4907
- const named = importDeclaration.getNamedImports().find((namedImport) => namedImport.getName() === name);
4908
- if (!named) return false;
4909
- named.remove();
4910
- if (importDeclaration.getNamedImports().length === 0 && !importDeclaration.getDefaultImport() && !importDeclaration.getNamespaceImport()) {
4911
- importDeclaration.remove();
4912
- }
4913
- return true;
4914
- }
4915
- function removeSentryFromConfigs(project, cwd) {
4916
- for (const file of CONFIG_FILES) {
4917
- const sourceFile = project.addSourceFileAtPathIfExists(import_path8.default.join(cwd, file));
4918
- if (!sourceFile) continue;
4919
- const property = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAssignment).find((assignment) => assignment.getName() === "SENTRY");
4920
- if (!property) continue;
4921
- const usedNames = new Set(
4922
- property.getDescendantsOfKind(import_ts_morph4.SyntaxKind.Identifier).map((identifier) => identifier.getText())
3942
+ return `${relPath}:${node.getStartLineNumber()}`;
3943
+ }
3944
+ function warnDestructuredDeclarations(sourceFile) {
3945
+ for (const pattern of sourceFile.getDescendantsOfKind(
3946
+ import_ts_morph2.SyntaxKind.ObjectBindingPattern
3947
+ )) {
3948
+ const destructuresDeclaration = pattern.getElements().some(
3949
+ (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME2
4923
3950
  );
4924
- property.remove();
4925
- for (const importDeclaration of [...sourceFile.getImportDeclarations()]) {
4926
- const imported = [
4927
- importDeclaration.getDefaultImport()?.getText(),
4928
- importDeclaration.getNamespaceImport()?.getText(),
4929
- ...importDeclaration.getNamedImports().map((named) => named.getName())
4930
- ].filter((name) => Boolean(name));
4931
- if (imported.some((name) => usedNames.has(name))) {
4932
- removeIfUnused(sourceFile, importDeclaration);
4933
- }
3951
+ if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
3952
+ console.warn(
3953
+ ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME2}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
3954
+ );
4934
3955
  }
4935
- console.log(` \u2713 ${file}: SENTRY`);
4936
3956
  }
4937
3957
  }
4938
- function removeEnvironmentVariable(project, cwd) {
4939
- const sourceFile = project.addSourceFileAtPathIfExists(
4940
- import_path8.default.join(cwd, ENVIRONMENT_FILE2)
4941
- );
4942
- if (!sourceFile) return;
4943
- const options = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
4944
- if (!options || !import_ts_morph4.Node.isObjectLiteralExpression(options)) {
4945
- warnSkipped4(
4946
- `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE2}; remove SENTRY_DSN by hand`
3958
+ function warnSpreadDeclarations(sourceFile) {
3959
+ for (const literal of sourceFile.getDescendantsOfKind(
3960
+ import_ts_morph2.SyntaxKind.ObjectLiteralExpression
3961
+ )) {
3962
+ const properties = literal.getProperties();
3963
+ const spreadsEventConfig = properties.some(
3964
+ (property) => import_ts_morph2.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
4947
3965
  );
4948
- return;
4949
- }
4950
- const property = options.getProperty("SENTRY_DSN");
4951
- if (!property) return;
4952
- property.remove();
4953
- console.log(` \u2713 ${ENVIRONMENT_FILE2}: SENTRY_DSN`);
4954
- }
4955
- function removeConstant(project, cwd) {
4956
- const sourceFile = project.addSourceFileAtPathIfExists(
4957
- import_path8.default.join(cwd, CONSTANTS_FILE)
4958
- );
4959
- if (!sourceFile) return;
4960
- for (const statement of [...sourceFile.getVariableStatements()]) {
4961
- const declarations = statement.getDeclarations();
4962
- const matching = declarations.filter(
4963
- (declaration) => declaration.getName() === "SENTRY_DSN" || /\benv\.SENTRY_DSN\b/.test(
4964
- declaration.getInitializer()?.getText() ?? ""
4965
- )
3966
+ const setsDeclaration = properties.some(
3967
+ (property) => (import_ts_morph2.Node.isPropertyAssignment(property) || import_ts_morph2.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME2
4966
3968
  );
4967
- if (matching.length === 0) continue;
4968
- const names = matching.map((declaration) => declaration.getName());
4969
- if (matching.length === declarations.length) {
4970
- statement.remove();
4971
- } else {
4972
- for (const declaration of matching) {
4973
- declaration.remove();
4974
- }
3969
+ if (spreadsEventConfig && setsDeclaration) {
3970
+ console.warn(
3971
+ ` [${location2(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME2}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME2}\` on its DECLARE action, so replace that one by hand.`
3972
+ );
4975
3973
  }
4976
- console.log(` \u2713 ${CONSTANTS_FILE}: ${names.join(", ")}`);
4977
3974
  }
4978
3975
  }
4979
- function unwireIndex(project, cwd) {
4980
- const sourceFile = project.addSourceFileAtPathIfExists(
4981
- import_path8.default.join(cwd, INDEX_FILE2)
4982
- );
4983
- if (!sourceFile) return;
4984
- const pluginImport = sourceFile.getImportDeclarations().find(
4985
- (declaration) => declaration.getModuleSpecifierValue() === SENTRY_PLUGIN
3976
+ function findToolkitImport(sourceFile) {
3977
+ return sourceFile.getImportDeclaration(
3978
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
4986
3979
  );
4987
- const pluginName = pluginImport?.getNamespaceImport()?.getText() ?? pluginImport?.getDefaultImport()?.getText() ?? "Sentry";
4988
- const registration = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.IfStatement).find(
4989
- (statement) => /\bSENTRY_DSN\b/.test(statement.getExpression().getText()) && new RegExp(`\\bplugin:\\s*${pluginName}\\b`).test(statement.getText())
4990
- );
4991
- if (registration) {
4992
- registration.remove();
4993
- console.log(` \u2713 ${INDEX_FILE2}: hapi-sentry plugin registration`);
4994
- } else if (sourceFile.getText().includes(SENTRY_PLUGIN)) {
4995
- warnSkipped4(
4996
- `Could not find the hapi-sentry plugin registration in ${INDEX_FILE2}; remove it by hand`
4997
- );
4998
- }
4999
- const scopeExtension = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.ExpressionStatement).find(
5000
- (statement) => statement.getText().includes("sentryScope") && statement.getText().startsWith("server.ext")
5001
- );
5002
- if (scopeExtension) {
5003
- scopeExtension.remove();
5004
- console.log(` \u2713 ${INDEX_FILE2}: onRequest Sentry scope extension`);
5005
- } else if (sourceFile.getText().includes("sentryScope")) {
5006
- warnSkipped4(
5007
- `Found 'sentryScope' in ${INDEX_FILE2} outside a server.ext(...) call; remove it by hand`
5008
- );
5009
- }
5010
- if (pluginImport && removeIfUnused(sourceFile, pluginImport)) {
5011
- console.log(` \u2713 ${INDEX_FILE2}: import '${SENTRY_PLUGIN}'`);
3980
+ }
3981
+ function findGetDeclarationName(sourceFile) {
3982
+ const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
3983
+ if (imported) {
3984
+ return imported.getAliasNode()?.getText() ?? GET_DECLARATION_NAME;
5012
3985
  }
5013
- if (!isReferenced(sourceFile, "SENTRY_DSN")) {
5014
- for (const declaration of [...sourceFile.getImportDeclarations()]) {
5015
- const specifier = declaration.getModuleSpecifierValue();
5016
- if (removeNamedImport(sourceFile, specifier, "SENTRY_DSN")) {
5017
- console.log(` \u2713 ${INDEX_FILE2}: import SENTRY_DSN from '${specifier}'`);
5018
- break;
5019
- }
5020
- }
3986
+ if (sourceFile.getLocal(GET_DECLARATION_NAME)) {
3987
+ return void 0;
5021
3988
  }
3989
+ return GET_DECLARATION_NAME;
5022
3990
  }
5023
- function removeApplicationConfigField(project, cwd) {
5024
- const sourceFile = project.addSourceFileAtPathIfExists(
5025
- import_path8.default.join(cwd, UTILS_FILE)
5026
- );
5027
- if (!sourceFile) return;
5028
- const property = sourceFile.getInterface("IApplicationConfig")?.getProperty("SENTRY");
5029
- if (!property) return;
5030
- property.remove();
5031
- console.log(` \u2713 ${UTILS_FILE}: IApplicationConfig.SENTRY`);
5032
- }
5033
- function isSentryPackage(name) {
5034
- return name === SENTRY_PLUGIN || name.startsWith("@sentry/");
5035
- }
5036
- function removeDependencies(cwd) {
5037
- const packageJsonPath = import_path8.default.join(cwd, PACKAGE_JSON_FILE);
5038
- if (!(0, import_fs7.existsSync)(packageJsonPath)) return;
5039
- const raw = (0, import_fs7.readFileSync)(packageJsonPath, "utf8");
5040
- let parsed;
5041
- try {
5042
- parsed = JSON.parse(raw);
5043
- } catch (error3) {
5044
- warnSkipped4(
5045
- `${PACKAGE_JSON_FILE} could not be parsed (${error3.message}); remove the Sentry dependencies by hand`
3991
+ function addGetDeclarationImport(sourceFile) {
3992
+ const toolkitImport = findToolkitImport(sourceFile);
3993
+ if (!toolkitImport) {
3994
+ const imports = sourceFile.getImportDeclarations();
3995
+ const lastImport = imports[imports.length - 1];
3996
+ sourceFile.insertStatements(
3997
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
3998
+ `import { ${GET_DECLARATION_NAME} } from '${TOOLKIT_EVENTS_MODULE}'`
5046
3999
  );
5047
4000
  return;
5048
4001
  }
5049
- const removed = [];
5050
- for (const bucket of ["dependencies", "devDependencies"]) {
5051
- const dependencies = parsed[bucket];
5052
- if (!dependencies) continue;
5053
- for (const name of Object.keys(dependencies)) {
5054
- if (isSentryPackage(name)) {
5055
- delete dependencies[name];
5056
- removed.push(name);
5057
- }
5058
- }
4002
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
4003
+ if (alreadyImported) {
4004
+ return;
5059
4005
  }
5060
- if (removed.length === 0) return;
5061
- const trailingNewline = raw.endsWith("\n") ? "\n" : "";
5062
- (0, import_fs7.writeFileSync)(
5063
- packageJsonPath,
5064
- `${JSON.stringify(parsed, null, 2)}${trailingNewline}`
5065
- );
5066
- console.log(` \u2713 ${PACKAGE_JSON_FILE}: ${removed.join(", ")}`);
5067
- }
5068
- function removeTypings(cwd) {
5069
- const typingsPath = import_path8.default.join(cwd, TYPINGS_FILE);
5070
- if (!(0, import_fs7.existsSync)(typingsPath)) return;
5071
- const declarations = (0, import_fs7.readFileSync)(typingsPath, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "").trim();
5072
- if (!/^declare module ['"]hapi-sentry['"];?$/.test(declarations)) {
5073
- warnSkipped4(
5074
- `${TYPINGS_FILE} declares more than the 'hapi-sentry' module; remove the declaration by hand`
5075
- );
4006
+ const namedImports = toolkitImport.getNamedImports();
4007
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
4008
+ toolkitImport.addNamedImport(GET_DECLARATION_NAME);
5076
4009
  return;
5077
4010
  }
5078
- (0, import_fs7.rmSync)(typingsPath);
5079
- console.log(` \u2713 ${TYPINGS_FILE}: deleted`);
4011
+ const names = [
4012
+ ...namedImports.map((namedImport) => namedImport.getText()),
4013
+ GET_DECLARATION_NAME
4014
+ ];
4015
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
4016
+ ${names.join(",\n ")}
4017
+ }` : `{ ${names.join(", ")} }`;
4018
+ toolkitImport.replaceWithText(
4019
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
4020
+ );
5080
4021
  }
5081
- async function main7() {
5082
- const cwd = process.cwd();
5083
- console.log("\nRemoving Sentry...\n");
5084
- const project = new import_ts_morph4.Project({
5085
- // ts-morph indents with four spaces and double-quotes strings by default,
5086
- // both of which the country config's prettier run would undo.
5087
- manipulationSettings: {
5088
- indentationText: import_ts_morph4.IndentationText.TwoSpaces,
5089
- quoteKind: import_ts_morph4.QuoteKind.Single
4022
+ function rewriteDeclarationReads(sourceFile) {
4023
+ warnDestructuredDeclarations(sourceFile);
4024
+ warnSpreadDeclarations(sourceFile);
4025
+ const reads = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
4026
+ if (node.hasQuestionDotToken()) {
4027
+ console.warn(
4028
+ ` [${location2(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
4029
+ );
4030
+ return false;
5090
4031
  }
5091
- });
5092
- removeSentryFromConfigs(project, cwd);
5093
- removeEnvironmentVariable(project, cwd);
5094
- removeConstant(project, cwd);
5095
- unwireIndex(project, cwd);
5096
- removeApplicationConfigField(project, cwd);
5097
- await project.save();
5098
- removeDependencies(cwd);
5099
- removeTypings(cwd);
5100
- if (skipped4.length > 0) {
5101
- console.warn(
5102
- `
5103
- \u26A0\uFE0F ${skipped4.length} Sentry removal step(s) were skipped. Handle the following by hand:`
5104
- );
5105
- for (const message of skipped4) {
5106
- console.warn(` - ${message}`);
4032
+ if (isWriteTarget(node)) {
4033
+ console.warn(
4034
+ ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME2}\` on the DECLARE action instead.`
4035
+ );
4036
+ return false;
5107
4037
  }
4038
+ return true;
4039
+ }).sort((a, b) => b.getStart() - a.getStart());
4040
+ if (reads.length === 0) {
4041
+ return 0;
5108
4042
  }
5109
- }
5110
-
5111
- // src/migrations/v2.1/rename-trigger-paths.ts
5112
- var import_ts_morph5 = require("ts-morph");
5113
- var import_path9 = __toESM(require("path"));
5114
- var PATH_PREFIX_RENAMES = {
5115
- "/triggers/user/": "/trigger/user/",
5116
- "/triggers/system/": "/trigger/system/"
5117
- };
5118
- var STALE_PREFIX = "/triggers/";
5119
- var METHOD_PROPERTY_NAME = "method";
5120
- var PATH_PROPERTY_NAME = "path";
5121
- var HTTP_VERBS = /* @__PURE__ */ new Set([
5122
- "GET",
5123
- "POST",
5124
- "PUT",
5125
- "PATCH",
5126
- "DELETE",
5127
- "OPTIONS",
5128
- "HEAD",
5129
- "*"
5130
- ]);
5131
- function isRouteConfig(obj) {
5132
- const methodProp = obj.getProperty(METHOD_PROPERTY_NAME);
5133
- if (!methodProp || !import_ts_morph5.Node.isPropertyAssignment(methodProp)) return false;
5134
- const methodInit = methodProp.getInitializer();
5135
- if (!methodInit) return false;
5136
- if (import_ts_morph5.Node.isStringLiteral(methodInit)) {
5137
- if (!HTTP_VERBS.has(methodInit.getLiteralValue().toUpperCase()))
5138
- return false;
5139
- } else if (import_ts_morph5.Node.isArrayLiteralExpression(methodInit)) {
5140
- const allVerbs = methodInit.getElements().every(
5141
- (el) => import_ts_morph5.Node.isStringLiteral(el) && HTTP_VERBS.has(el.getLiteralValue().toUpperCase())
4043
+ const getDeclarationName = findGetDeclarationName(sourceFile);
4044
+ if (!getDeclarationName) {
4045
+ console.warn(
4046
+ ` [${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.`
5142
4047
  );
5143
- if (!allVerbs) return false;
5144
- } else {
5145
- return false;
5146
- }
5147
- const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
5148
- if (!pathProp || !import_ts_morph5.Node.isPropertyAssignment(pathProp)) return false;
5149
- const pathInit = pathProp.getInitializer();
5150
- return !!pathInit && import_ts_morph5.Node.isStringLiteral(pathInit);
5151
- }
5152
- function renameRoutePath(obj) {
5153
- const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
5154
- if (!pathProp || !import_ts_morph5.Node.isPropertyAssignment(pathProp)) return null;
5155
- const pathInit = pathProp.getInitializer();
5156
- if (!pathInit || !import_ts_morph5.Node.isStringLiteral(pathInit)) return null;
5157
- const oldPath = pathInit.getLiteralValue();
5158
- const match = Object.entries(PATH_PREFIX_RENAMES).find(
5159
- ([from2]) => oldPath.startsWith(from2)
5160
- );
5161
- if (!match) return null;
5162
- const [from, to] = match;
5163
- const newPath = to + oldPath.slice(from.length);
5164
- pathInit.replaceWithText(`'${newPath}'`);
5165
- return newPath;
5166
- }
5167
- function processFile2(filePath, project) {
5168
- const sourceFile = project.getSourceFile(filePath);
5169
- if (!sourceFile) return 0;
5170
- let renamedCount = 0;
5171
- const relPath = import_path9.default.relative(process.cwd(), filePath);
5172
- const candidates = sourceFile.getDescendantsOfKind(
5173
- import_ts_morph5.SyntaxKind.ObjectLiteralExpression
5174
- );
5175
- for (const obj of candidates) {
5176
- if (!isRouteConfig(obj)) continue;
5177
- const newPath = renameRoutePath(obj);
5178
- if (newPath) {
5179
- renamedCount++;
5180
- console.log(` [${relPath}] Renamed route path \u2192 '${newPath}'`);
5181
- }
4048
+ return 0;
5182
4049
  }
5183
- return renamedCount;
5184
- }
5185
- function warnAboutStalePaths(sourceFiles) {
5186
- const stale = [];
5187
- for (const sourceFile of sourceFiles) {
5188
- const relPath = import_path9.default.relative(process.cwd(), sourceFile.getFilePath());
5189
- const lines = sourceFile.getFullText().split("\n");
5190
- lines.forEach((line2, index) => {
5191
- if (line2.includes(STALE_PREFIX)) {
5192
- stale.push(` ${relPath}:${index + 1}: ${line2.trim()}`);
5193
- }
5194
- });
4050
+ for (const read of reads) {
4051
+ console.log(
4052
+ ` [${location2(read)}] ${read.getText()} -> ${getDeclarationName}(${read.getExpression().getText()})`
4053
+ );
4054
+ read.replaceWithText(
4055
+ `${getDeclarationName}(${read.getExpression().getText()})`
4056
+ );
5195
4057
  }
5196
- if (stale.length === 0) return;
5197
- console.log(
5198
- `
5199
- WARNING: ${stale.length} remaining '${STALE_PREFIX}' reference(s) need to be renamed by hand:`
5200
- );
5201
- console.log(stale.join("\n"));
4058
+ addGetDeclarationImport(sourceFile);
4059
+ return reads.length;
5202
4060
  }
5203
- async function main8() {
5204
- const srcDir = import_path9.default.join(process.cwd(), "src");
5205
- console.log(`Scanning for Hapi route configs in: ${srcDir}
4061
+ async function main3() {
4062
+ const srcDir = import_path3.default.join(process.cwd(), "src");
4063
+ console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
5206
4064
  `);
5207
- console.log("Active path renames:");
5208
- for (const [from, to] of Object.entries(PATH_PREFIX_RENAMES)) {
5209
- console.log(` '${from}*' \u2192 '${to}*'`);
5210
- }
5211
- console.log();
5212
- const project = new import_ts_morph5.Project({
5213
- tsConfigFilePath: import_path9.default.resolve(srcDir, "../tsconfig.json"),
4065
+ const project = new import_ts_morph2.Project({
4066
+ tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
5214
4067
  skipAddingFilesFromTsConfig: false
5215
4068
  });
5216
4069
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -5219,152 +4072,210 @@ async function main8() {
5219
4072
  });
5220
4073
  console.log(`Found ${sourceFiles.length} source file(s) to analyse.
5221
4074
  `);
5222
- let totalRenamed = 0;
4075
+ let totalChanges = 0;
5223
4076
  const modifiedFiles = [];
5224
4077
  for (const sourceFile of sourceFiles) {
5225
- const filePath = sourceFile.getFilePath();
5226
- const renamed = processFile2(filePath, project);
5227
- if (renamed > 0) {
5228
- totalRenamed += renamed;
5229
- modifiedFiles.push(filePath);
4078
+ const changes = rewriteDeclarationReads(sourceFile);
4079
+ if (changes > 0) {
4080
+ totalChanges += changes;
4081
+ modifiedFiles.push(sourceFile);
5230
4082
  }
5231
4083
  }
5232
4084
  if (modifiedFiles.length === 0) {
5233
- console.log("No trigger route paths to rename.");
5234
- } else {
5235
- console.log(`
4085
+ console.log("No EventConfig declaration reads found. Nothing to do.");
4086
+ return;
4087
+ }
4088
+ console.log(`
5236
4089
  Saving ${modifiedFiles.length} modified file(s)...`);
5237
- for (const filePath of modifiedFiles) {
5238
- const sourceFile = project.getSourceFileOrThrow(filePath);
5239
- await sourceFile.save();
5240
- console.log(` Saved: ${import_path9.default.relative(process.cwd(), filePath)}`);
5241
- }
5242
- console.log(`
5243
- Done. Renamed ${totalRenamed} route path(s).`);
4090
+ for (const sourceFile of modifiedFiles) {
4091
+ await sourceFile.save();
4092
+ console.log(
4093
+ ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
4094
+ );
5244
4095
  }
5245
- warnAboutStalePaths(sourceFiles);
4096
+ console.log(
4097
+ `
4098
+ Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length} file(s).`
4099
+ );
5246
4100
  }
5247
4101
 
5248
- // src/migrations/v2.1/upgrade-tilt.ts
5249
- var import_fs8 = require("fs");
5250
- var import_path10 = __toESM(require("path"));
5251
- var COUNTRY_OWNED_DIR = "tilt/helm/";
5252
- var CHARTS_CHECKOUT_DIR = ".opencrvs-core-charts";
5253
- var IMAGE_NAME_PATTERN = /^countryconfig_image_name\s*=\s*(["'])(.*?)\1/m;
5254
- function writeIfChanged(cwd, relativePath, contents, mode) {
5255
- const target = import_path10.default.join(cwd, relativePath);
5256
- const existed = (0, import_fs8.existsSync)(target);
5257
- if (existed && (0, import_fs8.readFileSync)(target, "utf8") === contents) {
5258
- return "unchanged";
5259
- }
5260
- (0, import_fs8.mkdirSync)(import_path10.default.dirname(target), { recursive: true });
5261
- (0, import_fs8.writeFileSync)(target, contents);
5262
- if (mode !== void 0) {
5263
- (0, import_fs8.chmodSync)(target, mode & 511);
5264
- }
5265
- return existed ? "updated" : "created";
5266
- }
5267
- function report(relativePath, change) {
5268
- if (change !== "unchanged") {
5269
- console.log(` \u2713 ${change} ${relativePath}`);
5270
- }
5271
- }
5272
- function renderTiltfile(template, existing) {
5273
- const imageName = existing?.match(IMAGE_NAME_PATTERN)?.[2];
5274
- if (!imageName) {
5275
- return template;
5276
- }
5277
- return template.replace(
5278
- IMAGE_NAME_PATTERN,
5279
- (_line, quote) => `countryconfig_image_name=${quote}${imageName}${quote}`
5280
- );
4102
+ // src/migrations/persistent/update-toolkit-dependency.ts
4103
+ var import_fs3 = __toESM(require("fs"));
4104
+ var import_path5 = __toESM(require("path"));
4105
+
4106
+ // src/migrations/persistent/check-upgrade-path.ts
4107
+ var import_fs2 = __toESM(require("fs"));
4108
+ var import_path4 = __toESM(require("path"));
4109
+ var TOOLKIT_PACKAGE_NAME = "@opencrvs/toolkit";
4110
+ function findMajorMinor(version) {
4111
+ const match = /(\d+)\.(\d+)/.exec(version);
4112
+ return match ? { major: Number(match[1]), minor: Number(match[2]) } : void 0;
5281
4113
  }
5282
- function withIgnoreEntry(contents, line2) {
5283
- const normalise = (entry) => entry.trim().replace(/^\//, "").replace(/\/$/, "");
5284
- const alreadyIgnored = contents.split(/\r?\n/).some((entry) => normalise(entry) === normalise(line2));
5285
- if (alreadyIgnored) {
5286
- return contents;
5287
- }
5288
- const separator = contents === "" || contents.endsWith("\n") ? "" : "\n";
5289
- return `${contents}${separator}${line2}
5290
- `;
5291
- }
5292
- function ensureIgnored(cwd, file, line2) {
5293
- const target = import_path10.default.join(cwd, file);
5294
- const contents = (0, import_fs8.existsSync)(target) ? (0, import_fs8.readFileSync)(target, "utf8") : "";
5295
- report(file, writeIfChanged(cwd, file, withIgnoreEntry(contents, line2)));
5296
- }
5297
- function upgradeTilt(cwd, templateDir) {
5298
- const tiltfilePath = import_path10.default.join(cwd, "Tiltfile");
5299
- const existingTiltfile = (0, import_fs8.existsSync)(tiltfilePath) ? (0, import_fs8.readFileSync)(tiltfilePath, "utf8") : void 0;
5300
- report(
5301
- "Tiltfile",
5302
- writeIfChanged(
5303
- cwd,
5304
- "Tiltfile",
5305
- renderTiltfile(
5306
- (0, import_fs8.readFileSync)(import_path10.default.join(templateDir, "Tiltfile"), "utf8"),
5307
- existingTiltfile
5308
- )
5309
- )
5310
- );
5311
- const templateFiles = listFiles(templateDir, "tilt");
5312
- for (const file of templateFiles) {
5313
- const source = import_path10.default.join(templateDir, file);
5314
- const countryOwned = file.startsWith(COUNTRY_OWNED_DIR);
5315
- if (countryOwned && (0, import_fs8.existsSync)(import_path10.default.join(cwd, file))) {
5316
- continue;
5317
- }
5318
- report(
5319
- file,
5320
- writeIfChanged(
5321
- cwd,
5322
- file,
5323
- (0, import_fs8.readFileSync)(source, "utf8"),
5324
- (0, import_fs8.statSync)(source).mode
5325
- )
4114
+ function format({ major, minor }) {
4115
+ return `${major}.${minor}`;
4116
+ }
4117
+ function findCountryConfigToolkitVersion(cwd) {
4118
+ try {
4119
+ const packageJson = JSON.parse(
4120
+ import_fs2.default.readFileSync(import_path4.default.join(cwd, "package.json"), "utf-8")
5326
4121
  );
4122
+ return packageJson.dependencies?.[TOOLKIT_PACKAGE_NAME] ?? packageJson.devDependencies?.[TOOLKIT_PACKAGE_NAME];
4123
+ } catch {
4124
+ return void 0;
4125
+ }
4126
+ }
4127
+ function checkUpgradePath(countryConfigToolkitVersion, toolkitVersion) {
4128
+ const target = findMajorMinor(toolkitVersion);
4129
+ const current = countryConfigToolkitVersion ? findMajorMinor(countryConfigToolkitVersion) : void 0;
4130
+ if (!target || !current) {
4131
+ return {
4132
+ status: "unknown",
4133
+ message: `Could not tell which version the country config is on from its ${TOOLKIT_PACKAGE_NAME} dependency (${countryConfigToolkitVersion ?? "not found"}). Make sure it is on the version before ${toolkitVersion}: upgrade one minor version at a time.`
4134
+ };
4135
+ }
4136
+ const isSameVersion = current.major === target.major && current.minor === target.minor;
4137
+ const isPreviousMinor = current.major === target.major && current.minor === target.minor - 1;
4138
+ const isPreviousMajor = target.minor === 0 && current.major === target.major - 1;
4139
+ if (isSameVersion || isPreviousMinor || isPreviousMajor) {
4140
+ return { status: "ok" };
5327
4141
  }
5328
- const unknownFiles = listFiles(cwd, "tilt").filter(
5329
- (file) => !file.startsWith(COUNTRY_OWNED_DIR) && !templateFiles.includes(file)
4142
+ const isNewer = current.major > target.major || current.major === target.major && current.minor > target.minor;
4143
+ if (isNewer) {
4144
+ return {
4145
+ status: "blocked",
4146
+ message: `The country config is already on ${format(current)}, newer than toolkit ${toolkitVersion}. Run the upgrade with the toolkit of the version you are upgrading to.`
4147
+ };
4148
+ }
4149
+ const upgradesFrom = target.minor > 0 ? format({ major: target.major, minor: target.minor - 1 }) : `the last ${target.major - 1}.x`;
4150
+ const nextStep = current.major === target.major ? `: run \`npx ${TOOLKIT_PACKAGE_NAME}@${format({ major: current.major, minor: current.minor + 1 })} upgrade\` first` : "";
4151
+ return {
4152
+ status: "blocked",
4153
+ message: `The country config is on ${format(current)}, but toolkit ${toolkitVersion} only upgrades from ${upgradesFrom}. Upgrade one minor version at a time${nextStep}.`
4154
+ };
4155
+ }
4156
+
4157
+ // src/migrations/persistent/update-toolkit-dependency.ts
4158
+ var DEPENDENCY_PATTERN = new RegExp(
4159
+ `("${TOOLKIT_PACKAGE_NAME}"\\s*:\\s*")([^"]*)(")`,
4160
+ "g"
4161
+ );
4162
+ function updateToolkitDependency(packageJson, toolkitVersion) {
4163
+ const updated = packageJson.replace(
4164
+ DEPENDENCY_PATTERN,
4165
+ (match, before, version, after) => {
4166
+ if (!findMajorMinor(version)) {
4167
+ return match;
4168
+ }
4169
+ const range = /^[\^~]?/.exec(version)?.[0] ?? "";
4170
+ return `${before}${range}${toolkitVersion}${after}`;
4171
+ }
5330
4172
  );
5331
- for (const file of unknownFiles) {
5332
- console.warn(
5333
- ` \u26A0\uFE0F ${file} is not part of the template and was left in place.`
5334
- );
4173
+ return updated === packageJson ? void 0 : updated;
4174
+ }
4175
+ async function main4(toolkitVersion) {
4176
+ const packageJsonPath = import_path5.default.join(process.cwd(), "package.json");
4177
+ if (!import_fs3.default.existsSync(packageJsonPath)) {
4178
+ console.log(`No package.json found. Skipping ${TOOLKIT_PACKAGE_NAME}.`);
4179
+ return;
5335
4180
  }
5336
- ensureIgnored(cwd, ".tiltignore", `${CHARTS_CHECKOUT_DIR}/`);
5337
- ensureIgnored(cwd, ".gitignore", CHARTS_CHECKOUT_DIR);
5338
- if (existingTiltfile?.includes("opencrvs-helm-charts")) {
4181
+ const updated = updateToolkitDependency(
4182
+ import_fs3.default.readFileSync(packageJsonPath, "utf-8"),
4183
+ toolkitVersion
4184
+ );
4185
+ if (!updated) {
5339
4186
  console.log(
5340
- ` \u2139\uFE0F The Tiltfile no longer uses ../opencrvs-helm-charts; charts are cloned into ${CHARTS_CHECKOUT_DIR}/ instead. The old checkout can be deleted.`
4187
+ `${TOOLKIT_PACKAGE_NAME} in package.json needs no update. Nothing to do.`
5341
4188
  );
4189
+ return;
5342
4190
  }
5343
- }
5344
- async function main9() {
5345
- console.log("Upgrading the local Tilt setup...\n");
5346
- upgradeTilt(process.cwd(), findTemplateDir());
4191
+ import_fs3.default.writeFileSync(packageJsonPath, updated);
5347
4192
  console.log(
5348
- "\n Review local customisations with: git diff -- Tiltfile tilt/ .tiltignore .gitignore\n"
4193
+ `Updated ${TOOLKIT_PACKAGE_NAME} to ${toolkitVersion} in package.json. Install the dependencies again to use it.`
5349
4194
  );
5350
4195
  }
5351
4196
 
5352
- // src/migrations/v2.1/index.ts
5353
- async function runUpgrade(dockerSwarm) {
5354
- await main();
5355
- await main8();
4197
+ // src/migrations/replace-incomplete-flag.ts
4198
+ var import_ts_morph3 = require("ts-morph");
4199
+ var import_path6 = __toESM(require("path"));
4200
+ var INCOMPLETE = "InherentFlags.INCOMPLETE";
4201
+ var NOTIFIED_STATUS = `{ type: 'exact', term: EventStatus.enum.NOTIFIED }`;
4202
+ function ensureEventStatusImport(sourceFile) {
4203
+ const importDeclaration = sourceFile.getImportDeclarations().find(
4204
+ (declaration) => declaration.getNamedImports().some((named) => named.getName() === "InherentFlags")
4205
+ );
4206
+ const hasEventStatus = importDeclaration?.getNamedImports().some((named) => named.getName() === "EventStatus");
4207
+ if (importDeclaration && !hasEventStatus) {
4208
+ importDeclaration.addNamedImport("EventStatus");
4209
+ }
4210
+ }
4211
+ function replaceIncompleteFlag(sourceFile) {
4212
+ let changed = false;
4213
+ const anyOfIncomplete = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getParent()).filter(import_ts_morph3.Node.isArrayLiteralExpression).filter((array2) => {
4214
+ const anyOf = array2.getParent();
4215
+ const flags = anyOf?.getParent()?.getParent();
4216
+ return import_ts_morph3.Node.isPropertyAssignment(anyOf) && anyOf.getName() === "anyOf" && import_ts_morph3.Node.isPropertyAssignment(flags) && flags.getName() === "flags";
4217
+ });
4218
+ for (const array2 of anyOfIncomplete) {
4219
+ const anyOf = array2.getParentIfKindOrThrow(import_ts_morph3.SyntaxKind.PropertyAssignment);
4220
+ const flagsObject = anyOf.getParentIfKindOrThrow(
4221
+ import_ts_morph3.SyntaxKind.ObjectLiteralExpression
4222
+ );
4223
+ const flags = flagsObject.getParentIfKindOrThrow(
4224
+ import_ts_morph3.SyntaxKind.PropertyAssignment
4225
+ );
4226
+ const query = flags.getParentIfKindOrThrow(
4227
+ import_ts_morph3.SyntaxKind.ObjectLiteralExpression
4228
+ );
4229
+ array2.getElements().filter((element) => element.getText() === INCOMPLETE).forEach((element) => array2.removeElement(element));
4230
+ if (array2.getElements().length === 0) anyOf.remove();
4231
+ if (flagsObject.getProperties().length === 0) flags.remove();
4232
+ if (!query.getProperty("status")) {
4233
+ query.addPropertyAssignment({
4234
+ name: "status",
4235
+ initializer: NOTIFIED_STATUS
4236
+ });
4237
+ }
4238
+ changed = true;
4239
+ }
4240
+ if (changed) ensureEventStatusImport(sourceFile);
4241
+ const remaining = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
4242
+ return { changed, remaining };
4243
+ }
4244
+ async function main5() {
4245
+ const project = new import_ts_morph3.Project({
4246
+ tsConfigFilePath: import_path6.default.join(process.cwd(), "tsconfig.json")
4247
+ });
4248
+ const sourceFiles = project.getSourceFiles().filter((sf) => !sf.getFilePath().includes("/node_modules/"));
4249
+ for (const sourceFile of sourceFiles) {
4250
+ const relPath = import_path6.default.relative(process.cwd(), sourceFile.getFilePath());
4251
+ const { changed, remaining } = replaceIncompleteFlag(sourceFile);
4252
+ if (changed) {
4253
+ await sourceFile.save();
4254
+ console.log(
4255
+ ` [${relPath}] Replaced the incomplete flag with the NOTIFIED status`
4256
+ );
4257
+ }
4258
+ for (const line2 of remaining) {
4259
+ console.warn(
4260
+ ` [${relPath}:${line2}] ${INCOMPLETE} was removed, update this reference to use the NOTIFIED status`
4261
+ );
4262
+ }
4263
+ }
4264
+ }
4265
+
4266
+ // src/migrations/index.ts
4267
+ async function runUpgrade(toolkitVersion) {
4268
+ const [major, minor] = toolkitVersion.split(".");
5356
4269
  await main2();
5357
4270
  await main3();
5358
- await main7();
5359
- await main6();
5360
- await main5(dockerSwarm);
5361
- await main9();
5362
- await main4();
4271
+ await main(`${major}.${minor}`);
4272
+ await main5();
4273
+ await main4(toolkitVersion);
5363
4274
  }
5364
4275
 
5365
4276
  // src/environment/index.ts
5366
- var import_fs13 = require("fs");
5367
- var import_path15 = require("path");
4277
+ var import_fs8 = require("fs");
4278
+ var import_path11 = require("path");
5368
4279
  init_paths();
5369
4280
  var REQUIRED_REPOSITORY_DIRECTORIES = [
5370
4281
  ".github/workflows",
@@ -5375,7 +4286,7 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
5375
4286
  const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
5376
4287
  (directory) => {
5377
4288
  try {
5378
- return !(0, import_fs13.statSync)((0, import_path15.resolve)(repositoryRoot, directory)).isDirectory();
4289
+ return !(0, import_fs8.statSync)((0, import_path11.resolve)(repositoryRoot, directory)).isDirectory();
5379
4290
  } catch {
5380
4291
  return true;
5381
4292
  }
@@ -5416,7 +4327,7 @@ async function runEnvironmentSwarmToK8s() {
5416
4327
  // src/verify/endpoints.ts
5417
4328
  var import_colors = require("kleur/colors");
5418
4329
  var z = __toESM(require("zod/v4"));
5419
- var REQUEST_TIMEOUT_MS = 15e3;
4330
+ var REQUEST_TIMEOUT_MS2 = 15e3;
5420
4331
  var DEFAULT_TARGET_URL = "http://localhost:3040";
5421
4332
  var REQUIRED_PUBLIC_ENDPOINTS = [
5422
4333
  { method: "GET", path: "/client-config.js" },
@@ -5487,7 +4398,7 @@ async function requestStatus(url, method) {
5487
4398
  try {
5488
4399
  const response = await fetch(url, {
5489
4400
  method,
5490
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
4401
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2),
5491
4402
  // Sent without an Authorization header on purpose. A secured route
5492
4403
  // rejects with 401/403 before ever reading the body.
5493
4404
  headers: method === "POST" ? { "Content-Type": "application/json" } : void 0,
@@ -5522,7 +4433,7 @@ function toEventTriggerConfig(value) {
5522
4433
  async function fetchEventConfigs(baseUrl) {
5523
4434
  try {
5524
4435
  const response = await fetch(`${baseUrl}/config/events`, {
5525
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
4436
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
5526
4437
  });
5527
4438
  if (!response.ok) {
5528
4439
  return null;
@@ -5586,7 +4497,7 @@ var ServedTranslations = z.object({
5586
4497
  async function fetchServedTranslations(baseUrl, application) {
5587
4498
  try {
5588
4499
  const response = await fetch(`${baseUrl}/content/${application}`, {
5589
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
4500
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS2)
5590
4501
  });
5591
4502
  if (!response.ok) {
5592
4503
  return null;
@@ -5602,10 +4513,10 @@ async function verifyTranslations(baseUrl) {
5602
4513
  let refs;
5603
4514
  try {
5604
4515
  refs = await candidateRefs(TEMPLATE_VERSION);
5605
- } catch (error3) {
4516
+ } catch (error2) {
5606
4517
  console.log(
5607
4518
  " " + (0, import_colors.yellow)(
5608
- `Could not list the ${TEMPLATE_VERSION} refs on GitHub (${error3.message}); translations not checked.`
4519
+ `Could not list the ${TEMPLATE_VERSION} refs on GitHub (${error2.message}); translations not checked.`
5609
4520
  )
5610
4521
  );
5611
4522
  return 0;
@@ -5616,10 +4527,10 @@ async function verifyTranslations(baseUrl) {
5616
4527
  let fetched;
5617
4528
  try {
5618
4529
  fetched = await fetchTemplate(refs, application);
5619
- } catch (error3) {
4530
+ } catch (error2) {
5620
4531
  console.log(
5621
4532
  " " + (0, import_colors.yellow)(
5622
- `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${endpoint} not checked.`
4533
+ `Could not read ${application}.csv from the country config template on GitHub (${error2.message}); ${endpoint} not checked.`
5623
4534
  )
5624
4535
  );
5625
4536
  continue;
@@ -5702,8 +4613,8 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
5702
4613
  console.log(line(ok, endpointLabel(check), detail));
5703
4614
  }
5704
4615
  {
5705
- const path14 = `/fonts/${PROBE_SEGMENT}.ttf`;
5706
- const status = await requestStatus(`${baseUrl}${path14}`, "GET");
4616
+ const path12 = `/fonts/${PROBE_SEGMENT}.ttf`;
4617
+ const status = await requestStatus(`${baseUrl}${path12}`, "GET");
5707
4618
  const ok = status === 200 || status === 404;
5708
4619
  if (!ok) {
5709
4620
  failures++;
@@ -5718,7 +4629,7 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
5718
4629
  } else {
5719
4630
  detail = `${describeStatus(status)} \u2014 unexpected`;
5720
4631
  }
5721
- console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path14}`)}`, detail));
4632
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path12}`)}`, detail));
5722
4633
  }
5723
4634
  console.log();
5724
4635
  console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
@@ -5845,18 +4756,20 @@ Exits with a non-zero status if any check fails.
5845
4756
  var UPGRADE_USAGE = `
5846
4757
  Usage: opencrvs upgrade [options]
5847
4758
 
5848
- Upgrade the country config in the current working directory to the next
5849
- major version of OpenCRVS.
4759
+ Upgrade the country config in the current working directory to this toolkit's
4760
+ version of OpenCRVS. Upgrade one minor version at a time: toolkit 2.2 upgrades
4761
+ a country config on 2.1.
4762
+
4763
+ The upgrade tells which version the country config is on by its
4764
+ @opencrvs/toolkit dependency, and updates that dependency itself once done.
4765
+ Run it without changing the dependency first, e.g.
4766
+
4767
+ npx @opencrvs/toolkit@2.2 upgrade
5850
4768
 
5851
4769
  Options:
5852
- --docker-swarm Keep the 'infrastructure/' directory where it is and
5853
- only copy what the assets image needs into 'assets/'.
5854
- Use this if your country deploys OpenCRVS via Docker
5855
- Swarm. When omitted, 'infrastructure/' moves to
5856
- 'assets/' (default).
5857
4770
  -h, --help Show this message.
5858
4771
  `.trim();
5859
- function main10() {
4772
+ function main6() {
5860
4773
  const command = args[0];
5861
4774
  if (!command || command === "--help" || command === "-h") {
5862
4775
  console.log(USAGE);
@@ -5918,37 +4831,52 @@ Subcommands:
5918
4831
  async function runEnvironmentCommand(operation, command) {
5919
4832
  try {
5920
4833
  await command();
5921
- } catch (error3) {
4834
+ } catch (error2) {
5922
4835
  console.error(
5923
4836
  `Environment ${operation} failed:`,
5924
- error3 instanceof Error ? error3.message : error3
4837
+ error2 instanceof Error ? error2.message : error2
5925
4838
  );
5926
4839
  process.exit(1);
5927
4840
  }
5928
4841
  }
4842
+ function readToolkitVersion() {
4843
+ const packageJson = JSON.parse(
4844
+ import_fs9.default.readFileSync(import_path12.default.join(__dirname, "..", "package.json"), "utf-8")
4845
+ );
4846
+ return packageJson.version;
4847
+ }
5929
4848
  async function handleUpgrade() {
5930
4849
  const upgradeArgs = args.slice(1);
5931
4850
  if (upgradeArgs.includes("--help") || upgradeArgs.includes("-h")) {
5932
4851
  console.log(UPGRADE_USAGE);
5933
4852
  process.exit(0);
5934
4853
  }
5935
- const KNOWN_FLAGS = /* @__PURE__ */ new Set(["--docker-swarm"]);
5936
- const unknownFlags = upgradeArgs.filter(
5937
- (arg) => arg.startsWith("-") && !KNOWN_FLAGS.has(arg)
5938
- );
4854
+ const unknownFlags = upgradeArgs.filter((arg) => arg.startsWith("-"));
5939
4855
  if (unknownFlags.length > 0) {
5940
4856
  console.error(`Unknown option(s): ${unknownFlags.join(", ")}
5941
4857
  `);
5942
4858
  console.log(UPGRADE_USAGE);
5943
4859
  process.exit(1);
5944
4860
  }
5945
- const dockerSwarm = upgradeArgs.includes("--docker-swarm");
4861
+ const toolkitVersion = readToolkitVersion();
4862
+ const upgradePath = checkUpgradePath(
4863
+ findCountryConfigToolkitVersion(process.cwd()),
4864
+ toolkitVersion
4865
+ );
4866
+ if (upgradePath.status === "unknown") {
4867
+ console.warn(`\u26A0\uFE0F ${upgradePath.message}
4868
+ `);
4869
+ }
4870
+ if (upgradePath.status === "blocked") {
4871
+ console.error(upgradePath.message);
4872
+ process.exit(1);
4873
+ }
5946
4874
  console.log("Initiating upgrade...");
5947
4875
  try {
5948
- await runUpgrade(dockerSwarm);
4876
+ await runUpgrade(toolkitVersion);
5949
4877
  console.log("Upgrade completed successfully!");
5950
- } catch (error3) {
5951
- console.error("Upgrade failed:", error3);
4878
+ } catch (error2) {
4879
+ console.error("Upgrade failed:", error2);
5952
4880
  process.exit(1);
5953
4881
  }
5954
4882
  }
@@ -5969,12 +4897,12 @@ async function handleVerifyEndpoints() {
5969
4897
  }
5970
4898
  try {
5971
4899
  await runVerifyEndpoints(positional[0]);
5972
- } catch (error3) {
4900
+ } catch (error2) {
5973
4901
  console.error(
5974
4902
  "Endpoint verification failed:",
5975
- error3 instanceof Error ? error3.message : error3
4903
+ error2 instanceof Error ? error2.message : error2
5976
4904
  );
5977
4905
  process.exit(1);
5978
4906
  }
5979
4907
  }
5980
- main10();
4908
+ main6();