@opencrvs/toolkit 2.1.0-rc.5d808c4 → 2.1.0-rc.65b5bdf

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 (104) hide show
  1. package/README.md +1 -0
  2. package/build.sh +9 -1
  3. package/create-countryconfig/index.js +412 -59
  4. package/create-countryconfig/node_modules/.bin/degit +21 -0
  5. package/create-countryconfig/package.json +4 -1
  6. package/dist/application-config/index.js +341 -274
  7. package/dist/authentication/index.d.ts +67 -0
  8. package/dist/authentication/index.d.ts.map +1 -0
  9. package/dist/authentication/index.js +750 -0
  10. package/dist/cli.js +1780 -113
  11. package/dist/commons/api/router.d.ts +691 -76
  12. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  13. package/dist/commons/conditionals/validate.d.ts +16 -5
  14. package/dist/commons/events/ActionDocument.d.ts +5 -11
  15. package/dist/commons/events/ActionInput.d.ts +4 -4
  16. package/dist/commons/events/ActionStatus.d.ts +14 -0
  17. package/dist/commons/events/AdvancedSearchConfig.d.ts +24 -0
  18. package/dist/commons/events/AuditLog.d.ts +147 -0
  19. package/dist/commons/events/EventConfig.d.ts +3 -0
  20. package/dist/commons/events/EventDocument.d.ts +470 -2
  21. package/dist/commons/events/EventIndex.d.ts +3 -26
  22. package/dist/commons/events/EventMetadata.d.ts +1 -11
  23. package/dist/commons/events/EventStatus.d.ts +19 -0
  24. package/dist/commons/events/FieldConfig.d.ts +88 -53
  25. package/dist/commons/events/FieldTypeMapping.d.ts +27 -27
  26. package/dist/commons/events/FieldValue.d.ts +2 -2
  27. package/dist/commons/events/Flag.d.ts +42 -0
  28. package/dist/commons/events/PlainDate.d.ts +8 -0
  29. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  30. package/dist/commons/events/WorkqueueConfig.d.ts +17 -14
  31. package/dist/commons/events/event.d.ts +12 -0
  32. package/dist/commons/events/index.d.ts +1 -0
  33. package/dist/commons/events/locationPayloads.d.ts +95 -0
  34. package/dist/commons/events/locations.d.ts +169 -26
  35. package/dist/commons/events/mocks.test.utils.d.ts +30 -0
  36. package/dist/commons/events/test.utils.d.ts +25 -4
  37. package/dist/commons/events/utils.d.ts +13 -2
  38. package/dist/commons/notification/UserNotifications.d.ts +28 -13
  39. package/dist/commons/notification/dispatch.d.ts +10 -0
  40. package/dist/commons/notification/index.d.ts +1 -0
  41. package/dist/conditionals/index.js +328 -58
  42. package/dist/csv.d.ts +25 -0
  43. package/dist/csv.d.ts.map +1 -0
  44. package/dist/csv.js +120 -0
  45. package/dist/environment/index.d.ts +1 -0
  46. package/dist/environment/index.d.ts.map +1 -1
  47. package/dist/environment/index.js +10 -0
  48. package/dist/environment/logger.d.ts +15 -3
  49. package/dist/environment/logger.d.ts.map +1 -1
  50. package/dist/environment/paths.d.ts +7 -0
  51. package/dist/environment/paths.d.ts.map +1 -0
  52. package/dist/environment/paths.js +72 -0
  53. package/dist/environment/questions.d.ts.map +1 -1
  54. package/dist/environment/questions.js +20 -14
  55. package/dist/environment/setup-environment.js +28 -7
  56. package/dist/environment/templates.d.ts.map +1 -1
  57. package/dist/environment/templates.js +2 -1
  58. package/dist/environment/update-workflows.d.ts.map +1 -1
  59. package/dist/environment/update-workflows.js +17 -5
  60. package/dist/environment/upgrade.d.ts +2 -0
  61. package/dist/environment/upgrade.d.ts.map +1 -0
  62. package/dist/environment/upgrade.js +82 -0
  63. package/dist/environment/users.js +11 -13
  64. package/dist/events/index.js +7540 -7056
  65. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
  66. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  67. package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
  68. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  69. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  70. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  71. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  72. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  73. package/dist/migrations/v2.1/add-translations.js +213 -0
  74. package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
  75. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  76. package/dist/migrations/v2.1/enable-telemetry.js +438 -0
  77. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  78. package/dist/migrations/v2.1/index.js +1058 -0
  79. package/dist/notification/index.js +1825 -1418
  80. package/dist/scopes/index.d.ts +327 -32
  81. package/dist/scopes/index.js +329 -58
  82. package/dist/telemetry/index.d.ts +45 -0
  83. package/dist/telemetry/index.d.ts.map +1 -0
  84. package/dist/telemetry/index.js +39 -0
  85. package/dist/templates/charts-values/dependencies/values.yaml +2 -0
  86. package/dist/templates/charts-values/opencrvs-services/values.yaml +4 -3
  87. package/dist/templates/charts-values/opentelemetry/values.yaml +95 -0
  88. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  89. package/dist/templates/inventory/inventory.template.yml +1 -3
  90. package/dist/translations/check.d.ts +19 -0
  91. package/dist/translations/check.d.ts.map +1 -0
  92. package/dist/translations/check.js +127 -0
  93. package/dist/verify/endpoints.d.ts +2 -0
  94. package/dist/verify/endpoints.d.ts.map +1 -0
  95. package/dist/verify/endpoints.js +345 -0
  96. package/opencrvs-toolkit-2.1.0-rc.65b5bdf.tgz +0 -0
  97. package/package.json +12 -7
  98. package/tsconfig.build.json +11 -0
  99. package/tsconfig.build.tsbuildinfo +1 -0
  100. package/tsconfig.json +3 -0
  101. package/dist/templates/inventory/production.example.yml +0 -77
  102. package/dist/templates/inventory/qa.example.yml +0 -48
  103. package/opencrvs-toolkit-2.1.0-rc.5d808c4.tgz +0 -0
  104. package/tsconfig.tsbuildinfo +0 -1
package/dist/cli.js CHANGED
@@ -30,6 +30,42 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
30
30
  mod
31
31
  ));
32
32
 
33
+ // src/environment/paths.ts
34
+ function getEnvironmentInventoryPath(environment) {
35
+ return (0, import_path6.join)("environments", environment, INVENTORY_FILE_NAME);
36
+ }
37
+ function findOldInventoryFiles() {
38
+ return glob.sync((0, import_path6.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
39
+ }
40
+ function getEnvironmentNameFromOldInventoryPath(filePath) {
41
+ return (0, import_path6.basename)(filePath, ".yml");
42
+ }
43
+ function assertNoOldInventoryLayout() {
44
+ if (findOldInventoryFiles().length === 0) {
45
+ return;
46
+ }
47
+ throw new Error(
48
+ [
49
+ `Old inventory layout detected at ${OLD_INVENTORY_DIR}.`,
50
+ "Please run `yarn environment:upgrade` before running `yarn environment:init`."
51
+ ].join(" ")
52
+ );
53
+ }
54
+ var import_path6, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
55
+ var init_paths = __esm({
56
+ "src/environment/paths.ts"() {
57
+ "use strict";
58
+ import_path6 = require("path");
59
+ glob = __toESM(require("glob"));
60
+ OLD_INVENTORY_DIR = (0, import_path6.join)(
61
+ "infrastructure",
62
+ "server-setup",
63
+ "inventory"
64
+ );
65
+ INVENTORY_FILE_NAME = "inventory.yml";
66
+ }
67
+ });
68
+
33
69
  // src/environment/logger.ts
34
70
  var import_kleur, log, warn, success, info, error;
35
71
  var init_logger = __esm({
@@ -471,9 +507,9 @@ function storeSecrets(environment, answers) {
471
507
  let envConfig = {};
472
508
  try {
473
509
  envConfig = import_dotenv.default.parse(
474
- (0, import_fs.readFileSync)(`${process.cwd()}/.env.${environment}`)
510
+ (0, import_fs4.readFileSync)(`${process.cwd()}/.env.${environment}`)
475
511
  );
476
- } catch (error4) {
512
+ } catch (error3) {
477
513
  envConfig = {};
478
514
  }
479
515
  const linesFromAnswers = answers.map(
@@ -481,10 +517,10 @@ function storeSecrets(environment, answers) {
481
517
  );
482
518
  const linesFromEnvConfig = Object.entries(envConfig).filter(([name]) => !answers.find((update) => update.name === name)).map(([name, value]) => `${name}="${value}"`);
483
519
  const allLines = [...linesFromEnvConfig, ...linesFromAnswers].sort();
484
- (0, import_fs.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
520
+ (0, import_fs4.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
485
521
  }
486
522
  function readYamlFile(filePath) {
487
- const fileContent = import_fs.default.readFileSync(filePath, "utf8");
523
+ const fileContent = import_fs4.default.readFileSync(filePath, "utf8");
488
524
  return yaml.load(fileContent);
489
525
  }
490
526
  function writeYamlFile(filePath, data) {
@@ -497,16 +533,16 @@ function writeYamlFile(filePath, data) {
497
533
  noRefs: true,
498
534
  sortKeys: false
499
535
  });
500
- import_fs.default.writeFileSync(filePath, yamlContent, "utf8");
501
- } catch (error4) {
502
- throw new Error(`Failed to write inventory file: ${error4}`);
536
+ import_fs4.default.writeFileSync(filePath, yamlContent, "utf8");
537
+ } catch (error3) {
538
+ throw new Error(`Failed to write inventory file: ${error3}`);
503
539
  }
504
540
  }
505
- var import_fs, yaml, import_dotenv;
541
+ var import_fs4, yaml, import_dotenv;
506
542
  var init_utils = __esm({
507
543
  "src/environment/utils.ts"() {
508
544
  "use strict";
509
- import_fs = __toESM(require("fs"));
545
+ import_fs4 = __toESM(require("fs"));
510
546
  yaml = __toESM(require("js-yaml"));
511
547
  import_dotenv = __toESM(require("dotenv"));
512
548
  }
@@ -559,29 +595,29 @@ function extractWorkerNodes(data) {
559
595
  return worker_hosts;
560
596
  }
561
597
  function copyChartsValues(env, values) {
562
- const srcDir = import_path2.default.resolve(__dirname, "templates", "charts-values");
563
- const destDir = import_path2.default.resolve(process.cwd(), "environments", env);
564
- import_fs2.default.mkdirSync(destDir, { recursive: true });
598
+ const srcDir = import_path7.default.resolve(__dirname, "templates", "charts-values");
599
+ const destDir = import_path7.default.resolve(process.cwd(), "environments", env);
600
+ import_fs5.default.mkdirSync(destDir, { recursive: true });
565
601
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
566
602
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
567
603
  values["opencrvs_environment"] = env;
568
604
  function copyRecursive(src, dest) {
569
- const stat = import_fs2.default.statSync(src);
605
+ const stat = import_fs5.default.statSync(src);
570
606
  if (stat.isDirectory()) {
571
- import_fs2.default.mkdirSync(dest, { recursive: true });
572
- for (const item of import_fs2.default.readdirSync(src)) {
573
- copyRecursive(import_path2.default.join(src, item), import_path2.default.join(dest, item));
607
+ import_fs5.default.mkdirSync(dest, { recursive: true });
608
+ for (const item of import_fs5.default.readdirSync(src)) {
609
+ copyRecursive(import_path7.default.join(src, item), import_path7.default.join(dest, item));
574
610
  }
575
611
  } else {
576
- const content = import_fs2.default.readFileSync(src, "utf8");
612
+ const content = import_fs5.default.readFileSync(src, "utf8");
577
613
  const template = import_handlebars.default.compile(content);
578
614
  const updated = template(values);
579
615
  const isOverridesFile = dest.endsWith("override.yaml");
580
- if (isOverridesFile && import_fs2.default.existsSync(dest)) {
616
+ if (isOverridesFile && import_fs5.default.existsSync(dest)) {
581
617
  log(` \u21B7 Skipped existing overrides file: ${dest}`);
582
618
  return;
583
619
  }
584
- import_fs2.default.writeFileSync(dest, updated, "utf8");
620
+ import_fs5.default.writeFileSync(dest, updated, "utf8");
585
621
  log(` \u2713 Created: ${dest}`);
586
622
  }
587
623
  }
@@ -592,36 +628,31 @@ function copyChartsValues(env, values) {
592
628
  `);
593
629
  }
594
630
  function generateInventory(env, values) {
595
- const templatePath = import_path2.default.join(
631
+ const templatePath = import_path7.default.join(
596
632
  __dirname,
597
633
  "templates",
598
634
  "inventory",
599
635
  "inventory.template.yml"
600
636
  );
601
- const outputPath = import_path2.default.join(
602
- process.cwd(),
603
- "infrastructure",
604
- "server-setup",
605
- "inventory",
606
- `${env}.yml`
607
- );
608
- const templateFile = import_fs2.default.readFileSync(templatePath, "utf-8");
637
+ const outputPath = import_path7.default.resolve(process.cwd(), getEnvironmentInventoryPath(env));
638
+ const templateFile = import_fs5.default.readFileSync(templatePath, "utf-8");
609
639
  const template = import_handlebars.default.compile(templateFile);
610
640
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
611
641
  const updated = template(values);
612
- import_fs2.default.mkdirSync(import_path2.default.dirname(outputPath), { recursive: true });
613
- import_fs2.default.writeFileSync(outputPath, updated);
642
+ import_fs5.default.mkdirSync(import_path7.default.dirname(outputPath), { recursive: true });
643
+ import_fs5.default.writeFileSync(outputPath, updated);
614
644
  log(`
615
645
  \u2705 Generated inventory file at ${outputPath}
616
646
  `);
617
647
  }
618
- var import_fs2, import_path2, import_handlebars;
648
+ var import_fs5, import_path7, import_handlebars;
619
649
  var init_templates = __esm({
620
650
  "src/environment/templates.ts"() {
621
651
  "use strict";
622
- import_fs2 = __toESM(require("fs"));
623
- import_path2 = __toESM(require("path"));
652
+ import_fs5 = __toESM(require("fs"));
653
+ import_path7 = __toESM(require("path"));
624
654
  init_logger();
655
+ init_paths();
625
656
  import_handlebars = __toESM(require("handlebars"));
626
657
  import_handlebars.default.registerHelper("data_label_idx", function(value) {
627
658
  return parseInt(value) + 2;
@@ -675,18 +706,18 @@ var init_git = __esm({
675
706
  });
676
707
 
677
708
  // src/environment/questions.ts
678
- function validateCIDR(input3) {
679
- if (!input3.trim()) {
709
+ function validateCIDR(input4) {
710
+ if (!input4.trim()) {
680
711
  return true;
681
712
  }
682
713
  const cidrRegex = /^((25[0-5]|(2[0-4]|1\d|[1-9]?\d)\d?)\.){3}(25[0-5]|(2[0-4]|1\d|[1-9]?\d)\d?)\/([0-9]|[12][0-9]|3[0-2])$/;
683
- return cidrRegex.test(input3.trim()) ? true : "Please enter a valid CIDR (e.g. 10.0.0.0/24)";
714
+ return cidrRegex.test(input4.trim()) ? true : "Please enter a valid CIDR (e.g. 10.0.0.0/24)";
684
715
  }
685
- function validateCIDRs(input3) {
686
- if (!input3.trim()) {
716
+ function validateCIDRs(input4) {
717
+ if (!input4.trim()) {
687
718
  return true;
688
719
  }
689
- const cidrs = input3.split(",").map((v) => v.trim());
720
+ const cidrs = input4.split(",").map((v) => v.trim());
690
721
  for (const cidr of cidrs) {
691
722
  const result = validateCIDR(cidr);
692
723
  if (result !== true) {
@@ -829,11 +860,28 @@ var init_questions = __esm({
829
860
  scope: "ENVIRONMENT"
830
861
  },
831
862
  {
832
- name: "kubeAPIHost",
863
+ name: "kubeMasterNode",
833
864
  type: "text",
834
- message: `Kubernetes API endpoint (default: auto-detect)`,
865
+ message: `Kubernetes master node hostnames or IP (default: auto-detect)`,
866
+ valueType: "VARIABLE",
867
+ valueLabel: "KUBE_MASTER_NODE",
868
+ initial: process.env.KUBE_MASTER_NODE,
869
+ scope: "ENVIRONMENT"
870
+ },
871
+ {
872
+ name: "kubeWorkerNodes",
873
+ type: "text",
874
+ message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
875
+ valueType: "VARIABLE",
876
+ valueLabel: "KUBE_WORKER_NODES",
877
+ initial: process.env.KUBE_WORKER_NODES || "",
878
+ scope: "ENVIRONMENT"
879
+ },
880
+ {
881
+ name: "kubeApiHost",
882
+ type: "text",
883
+ message: `Kubernetes API endpoint IP (default: KUBE_MASTER_NODE)`,
835
884
  valueType: "VARIABLE",
836
- // validate: notEmpty,
837
885
  valueLabel: "KUBE_API_HOST",
838
886
  initial: process.env.KUBE_API_HOST,
839
887
  scope: "ENVIRONMENT"
@@ -847,16 +895,6 @@ var init_questions = __esm({
847
895
  valueLabel: "KUBE_API_ALLOWED_CIDRS",
848
896
  initial: process.env.KUBE_API_ALLOWED_CIDRS || "",
849
897
  scope: "ENVIRONMENT"
850
- },
851
- {
852
- name: "kubeWorkerNodes",
853
- type: "text",
854
- message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
855
- valueType: "VARIABLE",
856
- // validate: notEmpty,
857
- valueLabel: "KUBE_WORKER_NODES",
858
- initial: process.env.KUBE_WORKER_NODES || "",
859
- scope: "ENVIRONMENT"
860
898
  }
861
899
  ];
862
900
  staticSSLCertQuestions = [
@@ -887,7 +925,6 @@ var init_questions = __esm({
887
925
  type: "text",
888
926
  message: `Please enter backup server host/IP address, (default: no backup):`,
889
927
  valueType: "VARIABLE",
890
- // validate: notEmpty,
891
928
  valueLabel: "BACKUP_HOST",
892
929
  initial: process.env.BACKUP_HOST || "",
893
930
  scope: "ENVIRONMENT"
@@ -1220,7 +1257,7 @@ function getCurrentUsername() {
1220
1257
  }
1221
1258
  function getCurrentUserSSHKeys() {
1222
1259
  const homeDir = os.homedir();
1223
- const sshDir = path3.join(homeDir, ".ssh");
1260
+ const sshDir = path7.join(homeDir, ".ssh");
1224
1261
  const keys = [];
1225
1262
  const keyFiles = [
1226
1263
  "id_rsa.pub",
@@ -1229,7 +1266,7 @@ function getCurrentUserSSHKeys() {
1229
1266
  "id_dsa.pub"
1230
1267
  ];
1231
1268
  for (const keyFile of keyFiles) {
1232
- const keyPath = path3.join(sshDir, keyFile);
1269
+ const keyPath = path7.join(sshDir, keyFile);
1233
1270
  try {
1234
1271
  if (fs3.existsSync(keyPath)) {
1235
1272
  const keyContent = fs3.readFileSync(keyPath, "utf8").trim();
@@ -1237,7 +1274,7 @@ function getCurrentUserSSHKeys() {
1237
1274
  keys.push(keyContent);
1238
1275
  }
1239
1276
  }
1240
- } catch (error4) {
1277
+ } catch (error3) {
1241
1278
  continue;
1242
1279
  }
1243
1280
  }
@@ -1570,13 +1607,13 @@ async function manageUsers(inventoryPath) {
1570
1607
  }
1571
1608
  return users;
1572
1609
  }
1573
- var os, fs3, path3, input2, select2, confirm, editor, checkbox;
1610
+ var os, fs3, path7, input2, select2, confirm, editor, checkbox;
1574
1611
  var init_manage_users = __esm({
1575
1612
  "src/environment/manage-users.ts"() {
1576
1613
  "use strict";
1577
1614
  os = __toESM(require("os"));
1578
1615
  fs3 = __toESM(require("fs"));
1579
- path3 = __toESM(require("path"));
1616
+ path7 = __toESM(require("path"));
1580
1617
  init_logger();
1581
1618
  init_utils();
1582
1619
  init_templates();
@@ -1598,6 +1635,10 @@ async function select3(options) {
1598
1635
  const inquirer = await import("@inquirer/prompts");
1599
1636
  return inquirer.select(options);
1600
1637
  }
1638
+ async function input3(options) {
1639
+ const inquirer = await import("@inquirer/prompts");
1640
+ return inquirer.input(options);
1641
+ }
1601
1642
  function questionToPrompt({
1602
1643
  valueType,
1603
1644
  valueLabel,
@@ -1773,6 +1814,7 @@ var init_setup_environment = __esm({
1773
1814
  init_editor_questions();
1774
1815
  init_questions_helper();
1775
1816
  init_manage_users();
1817
+ init_paths();
1776
1818
  ALL_QUESTIONS = [];
1777
1819
  ALL_ANSWERS = [];
1778
1820
  ALL_QUESTIONS.push(
@@ -1936,9 +1978,7 @@ var init_setup_environment = __esm({
1936
1978
  );
1937
1979
  const kubeWorkerNodes = infrastructure.kubeWorkerNodes ? infrastructure.kubeWorkerNodes.split(",").map((ip) => ip.trim()) : [];
1938
1980
  log("\n", import_kleur4.default.bold().underline("SSH Users"), "\n");
1939
- const users = await manageUsers(
1940
- `infrastructure/server-setup/inventory/${environment}.yml`
1941
- );
1981
+ const users = await manageUsers(getEnvironmentInventoryPath(environment));
1942
1982
  log("\n", import_kleur4.default.bold().underline("Traefik SSL Certificate"), "\n");
1943
1983
  const sslCertExists = findExistingValue(
1944
1984
  "SSL_CRT",
@@ -2030,6 +2070,7 @@ var init_setup_environment = __esm({
2030
2070
  "ENVIRONMENT",
2031
2071
  existingValues
2032
2072
  )?.value;
2073
+ let restoreHost = findExistingValue("RESTORE_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2033
2074
  let restoreType = findExistingValue(
2034
2075
  "RESTORE_ENVIRONMENT_MODE",
2035
2076
  "VARIABLE",
@@ -2105,6 +2146,10 @@ var init_setup_environment = __esm({
2105
2146
  }
2106
2147
  ]
2107
2148
  });
2149
+ restoreHost = await input3({
2150
+ message: "What is the host/IP address of the restore backup server?",
2151
+ default: restoreHost
2152
+ });
2108
2153
  } else {
2109
2154
  log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2110
2155
  }
@@ -2439,6 +2484,22 @@ var init_setup_environment = __esm({
2439
2484
  existingValues
2440
2485
  ),
2441
2486
  scope: "ENVIRONMENT"
2487
+ },
2488
+ {
2489
+ type: "VARIABLE",
2490
+ name: "RESTORE_HOST",
2491
+ value: answerOrExisting(
2492
+ restoreHost,
2493
+ findExistingValue("RESTORE_HOST", "VARIABLE", "ENVIRONMENT", existingValues),
2494
+ (val) => val || ""
2495
+ ),
2496
+ didExist: findExistingValue(
2497
+ "RESTORE_HOST",
2498
+ "VARIABLE",
2499
+ "ENVIRONMENT",
2500
+ existingValues
2501
+ ),
2502
+ scope: "ENVIRONMENT"
2442
2503
  }
2443
2504
  ];
2444
2505
  if (enableEncryption) {
@@ -2690,7 +2751,7 @@ var init_setup_environment = __esm({
2690
2751
  log("\n", import_kleur4.default.bold().underline("Running configuration files updates"));
2691
2752
  generateInventory(environment, {
2692
2753
  kube_worker_nodes: kubeWorkerNodes,
2693
- kube_api_host: infrastructure.kubeAPIHost || "",
2754
+ kube_api_host: infrastructure.kubeApiHost || "",
2694
2755
  backup_host: backupHost || "",
2695
2756
  users
2696
2757
  });
@@ -2701,12 +2762,14 @@ var init_setup_environment = __esm({
2701
2762
  // Hardcode like this blocks us from being generic:
2702
2763
  // https://github.com/opencrvs/opencrvs-core/issues/11171
2703
2764
  two_fa_enabled: environment !== "production" ? false : true,
2704
- backup_enabled: configureBackup ? true : false,
2765
+ traefik_mode: traefikConfOption,
2705
2766
  restore_enabled: restoreEnvironmentName ? true : false,
2706
2767
  restore_environment_name: restoreEnvironmentName || "",
2707
2768
  restore_type: restoreType,
2708
- traefik_mode: traefikConfOption,
2709
- backup_type: backupType
2769
+ restore_host: restoreHost || "",
2770
+ backup_enabled: configureBackup ? true : false,
2771
+ backup_type: backupType,
2772
+ backup_host: backupHost || ""
2710
2773
  });
2711
2774
  let addon_message = kubeWorkerNodes.length > 0 || configureBackup ? `--------------------------------------------------------------------------------------------
2712
2775
 
@@ -2751,12 +2814,19 @@ var update_workflows_exports = {};
2751
2814
  __export(update_workflows_exports, {
2752
2815
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
2753
2816
  });
2817
+ function isDirectory(path10) {
2818
+ try {
2819
+ return (0, import_fs6.statSync)(path10).isDirectory();
2820
+ } catch {
2821
+ return false;
2822
+ }
2823
+ }
2754
2824
  async function extractInfrastructureNames() {
2755
- const files = glob.sync("infrastructure/server-setup/inventory/*.yml");
2756
- const infraEnvironments = files.map((file) => (0, import_path3.basename)(file, ".yml"));
2825
+ const files = glob2.sync((0, import_path8.join)("environments", "*", INVENTORY_FILE_NAME));
2826
+ const infraEnvironments = files.map((file) => (0, import_path8.basename)((0, import_path8.dirname)(file)));
2757
2827
  if (infraEnvironments.length === 0) {
2758
2828
  console.log(
2759
- "\u26A0\uFE0F Warning: No environment directories found in infrastructure/server-setup/inventory/"
2829
+ `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
2760
2830
  );
2761
2831
  return [];
2762
2832
  }
@@ -2766,8 +2836,9 @@ async function extractInfrastructureNames() {
2766
2836
  async function extractEnvironmentNames() {
2767
2837
  const entries = await (0, import_promises.readdir)("environments");
2768
2838
  const environments = entries.filter((entry) => {
2769
- const fullPath = (0, import_path3.join)("environments", entry);
2770
- return (0, import_fs3.statSync)(fullPath).isDirectory();
2839
+ const environmentPath = (0, import_path8.join)("environments", entry);
2840
+ const opencrvsServicesPath = (0, import_path8.join)(environmentPath, "opencrvs-services");
2841
+ return isDirectory(environmentPath) && (0, import_fs6.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
2771
2842
  });
2772
2843
  if (environments.length === 0) {
2773
2844
  console.log(
@@ -2793,7 +2864,7 @@ async function updateWorkflows(envList, config) {
2793
2864
  const { workflows } = config;
2794
2865
  for (const workflowPath of workflows) {
2795
2866
  try {
2796
- const fileContents = (0, import_fs3.readFileSync)(workflowPath, "utf8");
2867
+ const fileContents = (0, import_fs6.readFileSync)(workflowPath, "utf8");
2797
2868
  const workflowData = yaml2.load(fileContents);
2798
2869
  if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
2799
2870
  throw new Error(
@@ -2801,15 +2872,15 @@ async function updateWorkflows(envList, config) {
2801
2872
  );
2802
2873
  }
2803
2874
  const updatedContent = updateOptionsInYaml(fileContents, envList);
2804
- (0, import_fs3.writeFileSync)(workflowPath, updatedContent, "utf8");
2875
+ (0, import_fs6.writeFileSync)(workflowPath, updatedContent, "utf8");
2805
2876
  log(` \u2713 Successfully updated ${workflowPath}`);
2806
- } catch (error4) {
2877
+ } catch (error3) {
2807
2878
  console.error(
2808
2879
  `
2809
2880
  \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`
2810
2881
  );
2811
- console.error(`\u2717 Failed to update ${workflowPath}:`, error4);
2812
- throw error4;
2882
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error3);
2883
+ throw error3;
2813
2884
  }
2814
2885
  }
2815
2886
  }
@@ -2850,21 +2921,90 @@ async function updateWorkflowEnvironments() {
2850
2921
  } else {
2851
2922
  log("\u2139\uFE0F No workflows were updated.");
2852
2923
  }
2853
- } catch (error4) {
2854
- console.error("\n\u274C Error updating workflows:", error4);
2924
+ } catch (error3) {
2925
+ console.error("\n\u274C Error updating workflows:", error3);
2855
2926
  process.exit(1);
2856
2927
  }
2857
2928
  }
2858
- var import_promises, import_fs3, import_path3, glob, yaml2;
2929
+ var import_promises, import_fs6, import_path8, glob2, yaml2;
2859
2930
  var init_update_workflows = __esm({
2860
2931
  "src/environment/update-workflows.ts"() {
2861
2932
  "use strict";
2862
2933
  import_promises = require("fs/promises");
2863
- import_fs3 = require("fs");
2864
- import_path3 = require("path");
2865
- glob = __toESM(require("glob"));
2934
+ import_fs6 = require("fs");
2935
+ import_path8 = require("path");
2936
+ glob2 = __toESM(require("glob"));
2866
2937
  yaml2 = __toESM(require("js-yaml"));
2867
2938
  init_logger();
2939
+ init_paths();
2940
+ }
2941
+ });
2942
+
2943
+ // src/environment/upgrade.ts
2944
+ var upgrade_exports = {};
2945
+ __export(upgrade_exports, {
2946
+ upgradeEnvironmentLayout: () => upgradeEnvironmentLayout
2947
+ });
2948
+ function moveFileIfDestinationMissing(sourcePath, destinationPath) {
2949
+ if (!(0, import_fs7.existsSync)(sourcePath)) {
2950
+ return false;
2951
+ }
2952
+ if ((0, import_fs7.existsSync)(destinationPath)) {
2953
+ warn(
2954
+ `\u26A0\uFE0F Skipped ${sourcePath}; destination already exists at ${destinationPath}`
2955
+ );
2956
+ return false;
2957
+ }
2958
+ (0, import_fs7.mkdirSync)((0, import_path9.dirname)(destinationPath), { recursive: true });
2959
+ (0, import_fs7.renameSync)(sourcePath, destinationPath);
2960
+ log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
2961
+ return true;
2962
+ }
2963
+ function migrateInventoryFiles() {
2964
+ const oldInventoryFiles = findOldInventoryFiles();
2965
+ if (oldInventoryFiles.length === 0) {
2966
+ log(`\u2139\uFE0F No old inventory files found at ${OLD_INVENTORY_DIR}`);
2967
+ return false;
2968
+ }
2969
+ log(import_kleur5.default.bold("\nMigrating Ansible inventory files"));
2970
+ let didMoveInventory = false;
2971
+ for (const oldInventoryFile of oldInventoryFiles) {
2972
+ const environment = getEnvironmentNameFromOldInventoryPath(oldInventoryFile);
2973
+ didMoveInventory = moveFileIfDestinationMissing(
2974
+ oldInventoryFile,
2975
+ getEnvironmentInventoryPath(environment)
2976
+ ) || didMoveInventory;
2977
+ }
2978
+ try {
2979
+ if ((0, import_fs7.existsSync)(OLD_INVENTORY_DIR) && (0, import_fs7.readdirSync)(OLD_INVENTORY_DIR).length === 0) {
2980
+ (0, import_fs7.rmdirSync)(OLD_INVENTORY_DIR);
2981
+ log(` \u2713 Removed empty ${OLD_INVENTORY_DIR}`);
2982
+ }
2983
+ } catch {
2984
+ warn(`\u26A0\uFE0F Could not remove ${OLD_INVENTORY_DIR}; please review it manually`);
2985
+ }
2986
+ return didMoveInventory;
2987
+ }
2988
+ async function upgradeEnvironmentLayout() {
2989
+ const didMoveInventory = migrateInventoryFiles();
2990
+ await updateWorkflowEnvironments();
2991
+ if (didMoveInventory) {
2992
+ success("\n\u2705 Environment layout upgrade completed successfully.");
2993
+ } else {
2994
+ success("\n\u2705 Environment layout already uses the current structure.");
2995
+ }
2996
+ log("\nCommit changes into git after upgrade");
2997
+ }
2998
+ var import_fs7, import_path9, import_kleur5;
2999
+ var init_upgrade = __esm({
3000
+ "src/environment/upgrade.ts"() {
3001
+ "use strict";
3002
+ import_fs7 = require("fs");
3003
+ import_path9 = require("path");
3004
+ import_kleur5 = __toESM(require("kleur"));
3005
+ init_logger();
3006
+ init_paths();
3007
+ init_update_workflows();
2868
3008
  }
2869
3009
  });
2870
3010
 
@@ -2877,7 +3017,7 @@ async function select4(options) {
2877
3017
  const inquirer = await import("@inquirer/prompts");
2878
3018
  return inquirer.select(options);
2879
3019
  }
2880
- async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inventory/") {
3020
+ async function selectInventoryFile(dirPath = "./environments") {
2881
3021
  if (!fs4.existsSync(dirPath)) {
2882
3022
  warn(`\u26A0\uFE0F No environment configuration directory found at ${dirPath}`);
2883
3023
  warn(
@@ -2885,22 +3025,20 @@ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inve
2885
3025
  );
2886
3026
  return null;
2887
3027
  }
2888
- const files = fs4.readdirSync(dirPath).filter((file) => {
2889
- const filePath = path4.join(dirPath, file);
2890
- const isFile = fs4.statSync(filePath).isFile();
2891
- const ext = path4.extname(file).slice(1).toLowerCase();
2892
- return isFile && (ext === "yml" || ext === "yaml");
3028
+ const environments = fs4.readdirSync(dirPath).filter((entry) => {
3029
+ const filePath = path8.join(dirPath, entry);
3030
+ return fs4.statSync(filePath).isDirectory() && fs4.existsSync(getEnvironmentInventoryPath(entry));
2893
3031
  }).sort();
2894
- if (files.length === 0) {
3032
+ if (environments.length === 0) {
2895
3033
  warn(`\u26A0\uFE0F No environment configuration files found at ${dirPath}`);
2896
3034
  warn(
2897
3035
  "Hint: If this is a new infrastructure repository, run `opencrvs environment init` first."
2898
3036
  );
2899
3037
  return null;
2900
3038
  }
2901
- const choices = files.map((file) => ({
2902
- name: path4.basename(file, path4.extname(file)),
2903
- value: path4.join(dirPath, file)
3039
+ const choices = environments.map((environment) => ({
3040
+ name: environment,
3041
+ value: getEnvironmentInventoryPath(environment)
2904
3042
  }));
2905
3043
  const selectedFile = await select4({
2906
3044
  message: "Select environment (inventory file) to load users:",
@@ -2909,33 +3047,34 @@ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inve
2909
3047
  return selectedFile;
2910
3048
  }
2911
3049
  async function manageEnvironmentUsers() {
2912
- console.log("\n", import_kleur5.default.bold().underline("Manage users"), "\n");
3050
+ console.log("\n", import_kleur6.default.bold().underline("Manage users"), "\n");
2913
3051
  const inventory_file = await selectInventoryFile();
2914
3052
  if (!inventory_file) {
2915
3053
  return;
2916
3054
  }
2917
3055
  await manageUsers(inventory_file);
2918
3056
  }
2919
- var fs4, path4, import_kleur5;
3057
+ var fs4, path8, import_kleur6;
2920
3058
  var init_users = __esm({
2921
3059
  "src/environment/users.ts"() {
2922
3060
  "use strict";
2923
3061
  fs4 = __toESM(require("fs"));
2924
- path4 = __toESM(require("path"));
2925
- import_kleur5 = __toESM(require("kleur"));
3062
+ path8 = __toESM(require("path"));
3063
+ import_kleur6 = __toESM(require("kleur"));
2926
3064
  init_manage_users();
2927
3065
  init_logger();
3066
+ init_paths();
2928
3067
  }
2929
3068
  });
2930
3069
 
2931
3070
  // src/environment/swarm-to-k8s.ts
2932
3071
  var swarm_to_k8s_exports = {};
2933
- var path5, import_kleur6, import_core2;
3072
+ var path9, import_kleur7, import_core2;
2934
3073
  var init_swarm_to_k8s = __esm({
2935
3074
  "src/environment/swarm-to-k8s.ts"() {
2936
3075
  "use strict";
2937
- path5 = __toESM(require("path"));
2938
- import_kleur6 = __toESM(require("kleur"));
3076
+ path9 = __toESM(require("path"));
3077
+ import_kleur7 = __toESM(require("kleur"));
2939
3078
  init_logger();
2940
3079
  init_utils();
2941
3080
  init_templates();
@@ -2944,7 +3083,7 @@ var init_swarm_to_k8s = __esm({
2944
3083
  init_github();
2945
3084
  (async () => {
2946
3085
  log(
2947
- import_kleur6.default.bold(
3086
+ import_kleur7.default.bold(
2948
3087
  "------------------------------------------------\nOpenCRVS Infrastructure migration script: \nMigrating Swarm configurations to Kubernetes\n------------------------------------------------\n"
2949
3088
  )
2950
3089
  );
@@ -2975,7 +3114,7 @@ var init_swarm_to_k8s = __esm({
2975
3114
  );
2976
3115
  process.exit(0);
2977
3116
  }
2978
- log(import_kleur6.default.bold().underline("Migration properties:"));
3117
+ log(import_kleur7.default.bold().underline("Migration properties:"));
2979
3118
  log(` \u2713 Environment: ${environment}`);
2980
3119
  const old_inventory_path = process.env.OLD_INVENTORY_PATH || "";
2981
3120
  if (!old_inventory_path) {
@@ -2986,7 +3125,7 @@ var init_swarm_to_k8s = __esm({
2986
3125
  );
2987
3126
  process.exit(1);
2988
3127
  }
2989
- const ansible_inventory = path5.join(old_inventory_path, environment + ".yml");
3128
+ const ansible_inventory = path9.join(old_inventory_path, environment + ".yml");
2990
3129
  const data = readYamlFile(ansible_inventory);
2991
3130
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
2992
3131
  const master = dockerManagerFirst(data) || "";
@@ -3287,14 +3426,1156 @@ Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.l
3287
3426
  );
3288
3427
  }
3289
3428
 
3429
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
3430
+ var import_ts_morph2 = require("ts-morph");
3431
+ var import_fs2 = require("fs");
3432
+ var import_path2 = __toESM(require("path"));
3433
+
3434
+ // src/csv.ts
3435
+ var import_fs = require("fs");
3436
+ function parseCsvLine(line2) {
3437
+ const values = [];
3438
+ let value = "";
3439
+ let quoted = false;
3440
+ for (let index = 0; index < line2.length; index++) {
3441
+ const character = line2[index];
3442
+ if (quoted) {
3443
+ if (character !== '"') {
3444
+ value += character;
3445
+ } else if (line2[index + 1] === '"') {
3446
+ value += '"';
3447
+ index++;
3448
+ } else {
3449
+ quoted = false;
3450
+ }
3451
+ continue;
3452
+ }
3453
+ if (character === '"') {
3454
+ quoted = true;
3455
+ } else if (character === ",") {
3456
+ values.push(value);
3457
+ value = "";
3458
+ } else {
3459
+ value += character;
3460
+ }
3461
+ }
3462
+ values.push(value);
3463
+ return values;
3464
+ }
3465
+ function toCsvLine(values) {
3466
+ return values.map(
3467
+ (value) => /["\n,]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
3468
+ ).join(",");
3469
+ }
3470
+ function idOf(line2) {
3471
+ const comma = line2.indexOf(",");
3472
+ return comma === -1 ? line2 : line2.slice(0, comma);
3473
+ }
3474
+ function readCsvFile(path10) {
3475
+ if (!(0, import_fs.existsSync)(path10)) {
3476
+ return void 0;
3477
+ }
3478
+ const contents = (0, import_fs.readFileSync)(path10, "utf8");
3479
+ const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3480
+ const trailingNewline = /\r?\n$/.test(contents);
3481
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3482
+ const body = lines.slice(1).filter((line2) => line2 !== "");
3483
+ return { header: lines[0], body, newline, trailingNewline };
3484
+ }
3485
+ function writeCsvFile(path10, file) {
3486
+ (0, import_fs.writeFileSync)(
3487
+ path10,
3488
+ [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3489
+ );
3490
+ }
3491
+ function addRows(file, rows) {
3492
+ const isSorted = file.body.every(
3493
+ (line2, index) => index === 0 || idOf(file.body[index - 1]) <= idOf(line2)
3494
+ );
3495
+ const added = [];
3496
+ for (const row of rows) {
3497
+ const id = idOf(row);
3498
+ if (file.body.some((line2) => idOf(line2) === id)) {
3499
+ continue;
3500
+ }
3501
+ const insertAt = isSorted ? file.body.findIndex((line2) => idOf(line2) > id) : -1;
3502
+ if (insertAt === -1) {
3503
+ file.body.push(row);
3504
+ } else {
3505
+ file.body.splice(insertAt, 0, row);
3506
+ }
3507
+ added.push(id);
3508
+ }
3509
+ return added;
3510
+ }
3511
+
3512
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
3513
+ var EMAIL_TEMPLATES_FILE = "src/api/notification/email-templates/index.ts";
3514
+ var SMS_SERVICE_FILE = "src/api/notification/sms-service.ts";
3515
+ var HANDLER_FILE = "src/api/notification/handler.ts";
3516
+ var ROUTES_FILE = "src/config/routes/userNotificationRoutes.ts";
3517
+ var EMAIL_TEMPLATE_DIR = "src/api/notification/email-templates/other";
3518
+ var NOTIFICATION_CSV = "src/translations/notification.csv";
3519
+ var LOGIN_CSV = "src/translations/login.csv";
3520
+ var TRIGGER_VARIABLE_OBJECT = "TriggerVariable";
3521
+ var TEMPLATES_OBJECT = "templates";
3522
+ var OTHER_TEMPLATES_OBJECT = "otherTemplates";
3523
+ var TRIGGER_TO_SMS_TEMPLATE_OBJECT = "TriggerToSMSTemplate";
3524
+ var CONVERT_PAYLOAD_FUNCTION = "convertPayloadToVariable";
3525
+ var ROUTES_FUNCTION = "getUserNotificationRoutes";
3526
+ var RECOVERY_EVENTS = [
3527
+ {
3528
+ id: "password-reset-link",
3529
+ constant: "PASSWORD_RESET_LINK",
3530
+ smsTemplate: "resetPasswordLinkNotification",
3531
+ emailSubject: "Reset your password",
3532
+ routeDescription: "Handles notification for password reset recovery link",
3533
+ heading: "Reset your password",
3534
+ reason: "Someone asked to reset the password for your {{applicationName}}\n account.",
3535
+ linkLabel: "Reset your password"
3536
+ },
3537
+ {
3538
+ id: "username-reminder-link",
3539
+ constant: "USERNAME_REMINDER_LINK",
3540
+ smsTemplate: "retrieveUsernameLinkNotification",
3541
+ emailSubject: "Retrieve your username",
3542
+ routeDescription: "Handles notification for username reminder recovery link",
3543
+ heading: "Retrieve your username",
3544
+ reason: "Someone asked for a reminder of the username for your\n {{applicationName}} account.",
3545
+ linkLabel: "Retrieve your username"
3546
+ }
3547
+ ];
3548
+ var NOTIFICATION_CSV_ROWS = [
3549
+ `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}}}`,
3550
+ `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}}}`
3551
+ ];
3552
+ var LOGIN_CSV_ROWS = [
3553
+ `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`,
3554
+ `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."`,
3555
+ `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`,
3556
+ `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`,
3557
+ `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.`,
3558
+ `resetCredentials.recoveryLinkLanding.expired.link,Link back to the forgotten item form shown on an expired/invalid recovery link,Start again,Recommencer`,
3559
+ `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`
3560
+ ];
3561
+ var skipped = [];
3562
+ function warnSkipped(message) {
3563
+ skipped.push(message);
3564
+ console.warn(` \u26A0\uFE0F ${message}`);
3565
+ }
3566
+ function findObjectLiteral(declaration) {
3567
+ let expression = declaration?.getInitializer();
3568
+ while (expression && (import_ts_morph2.Node.isAsExpression(expression) || import_ts_morph2.Node.isSatisfiesExpression(expression))) {
3569
+ expression = expression.getExpression();
3570
+ }
3571
+ return expression && import_ts_morph2.Node.isObjectLiteralExpression(expression) ? expression : void 0;
3572
+ }
3573
+ function hasKeyFor(obj, key, constant) {
3574
+ const accepted = /* @__PURE__ */ new Set([
3575
+ `[TriggerEvent.${constant}]`,
3576
+ `['${key}']`,
3577
+ `["${key}"]`,
3578
+ `'${key}'`,
3579
+ `"${key}"`,
3580
+ key
3581
+ ]);
3582
+ return obj.getProperties().some(
3583
+ (property) => import_ts_morph2.Node.isPropertyAssignment(property) && accepted.has(property.getName().trim())
3584
+ );
3585
+ }
3586
+ function renderKey(obj, key, constant) {
3587
+ const names = obj.getProperties().filter(import_ts_morph2.Node.isPropertyAssignment).map((property) => property.getName().trim());
3588
+ if (names.some((name) => name.startsWith("[TriggerEvent."))) {
3589
+ return `[TriggerEvent.${constant}]`;
3590
+ }
3591
+ if (names.some((name) => name.startsWith("["))) {
3592
+ return `['${key}']`;
3593
+ }
3594
+ return `'${key}'`;
3595
+ }
3596
+ function appendEntry(sourceFile, objectName, key, valueLines) {
3597
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3598
+ const properties = obj?.getProperties() ?? [];
3599
+ const lastProperty = properties[properties.length - 1];
3600
+ if (!lastProperty) return false;
3601
+ const indent = lastProperty.getIndentationText();
3602
+ const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${key}: ${line2}` : line2}`).join("\n");
3603
+ sourceFile.insertText(lastProperty.getEnd(), `,
3604
+ ${entry}`);
3605
+ return true;
3606
+ }
3607
+ function objectHasKeyFor(sourceFile, objectName, key, constant) {
3608
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3609
+ return obj ? hasKeyFor(obj, key, constant) : false;
3610
+ }
3611
+ function renderKeyFor(sourceFile, objectName, key, constant) {
3612
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
3613
+ return obj ? renderKey(obj, key, constant) : `'${key}'`;
3614
+ }
3615
+ function updateEmailTemplates(project, cwd) {
3616
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, EMAIL_TEMPLATES_FILE));
3617
+ if (!sourceFile) {
3618
+ warnSkipped(`${EMAIL_TEMPLATES_FILE} not found; email templates not wired`);
3619
+ return;
3620
+ }
3621
+ const missingObject = [TRIGGER_VARIABLE_OBJECT, TEMPLATES_OBJECT].find(
3622
+ (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3623
+ );
3624
+ if (missingObject) {
3625
+ warnSkipped(
3626
+ `Could not find '${missingObject}' in ${EMAIL_TEMPLATES_FILE}; email templates not wired`
3627
+ );
3628
+ return;
3629
+ }
3630
+ for (const event of RECOVERY_EVENTS) {
3631
+ if (!objectHasKeyFor(
3632
+ sourceFile,
3633
+ TRIGGER_VARIABLE_OBJECT,
3634
+ event.id,
3635
+ event.constant
3636
+ ) && appendEntry(
3637
+ sourceFile,
3638
+ TRIGGER_VARIABLE_OBJECT,
3639
+ renderKeyFor(
3640
+ sourceFile,
3641
+ TRIGGER_VARIABLE_OBJECT,
3642
+ event.id,
3643
+ event.constant
3644
+ ),
3645
+ [
3646
+ "z.object({",
3647
+ " firstname: z.string(),",
3648
+ " applicationName: z.string(),",
3649
+ " countryLogo: z.string(),",
3650
+ " recoveryURL: z.string()",
3651
+ "})"
3652
+ ]
3653
+ )) {
3654
+ console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} variables`);
3655
+ }
3656
+ if (!objectHasKeyFor(
3657
+ sourceFile,
3658
+ TEMPLATES_OBJECT,
3659
+ event.id,
3660
+ event.constant
3661
+ ) && appendEntry(
3662
+ sourceFile,
3663
+ TEMPLATES_OBJECT,
3664
+ renderKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant),
3665
+ [
3666
+ "{",
3667
+ ` type: '${event.id}',`,
3668
+ ` subject: '${event.emailSubject}',`,
3669
+ ` template: readOtherTemplate<TriggerVariable['${event.id}']>(`,
3670
+ ` '${event.id}'`,
3671
+ " )",
3672
+ "}"
3673
+ ]
3674
+ )) {
3675
+ console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} template`);
3676
+ }
3677
+ }
3678
+ }
3679
+ function updateSmsService(project, cwd) {
3680
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, SMS_SERVICE_FILE));
3681
+ if (!sourceFile) {
3682
+ warnSkipped(`${SMS_SERVICE_FILE} not found; SMS templates not wired`);
3683
+ return;
3684
+ }
3685
+ const missingObject = [
3686
+ OTHER_TEMPLATES_OBJECT,
3687
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT
3688
+ ].find(
3689
+ (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
3690
+ );
3691
+ if (missingObject) {
3692
+ warnSkipped(
3693
+ `Could not find '${missingObject}' in ${SMS_SERVICE_FILE}; SMS templates not wired`
3694
+ );
3695
+ return;
3696
+ }
3697
+ for (const event of RECOVERY_EVENTS) {
3698
+ if (!objectHasKeyFor(
3699
+ sourceFile,
3700
+ OTHER_TEMPLATES_OBJECT,
3701
+ event.smsTemplate,
3702
+ event.smsTemplate
3703
+ ) && appendEntry(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, [
3704
+ `'${event.smsTemplate}'`
3705
+ ])) {
3706
+ console.log(` \u2713 ${SMS_SERVICE_FILE}: ${event.smsTemplate}`);
3707
+ }
3708
+ if (!objectHasKeyFor(
3709
+ sourceFile,
3710
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3711
+ event.id,
3712
+ event.constant
3713
+ ) && appendEntry(
3714
+ sourceFile,
3715
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3716
+ renderKeyFor(
3717
+ sourceFile,
3718
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
3719
+ event.id,
3720
+ event.constant
3721
+ ),
3722
+ [`'${event.smsTemplate}'`]
3723
+ )) {
3724
+ console.log(
3725
+ ` \u2713 ${SMS_SERVICE_FILE}: ${event.id} -> ${event.smsTemplate}`
3726
+ );
3727
+ }
3728
+ }
3729
+ }
3730
+ function updateHandler(project, cwd) {
3731
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, HANDLER_FILE));
3732
+ if (!sourceFile) {
3733
+ warnSkipped(`${HANDLER_FILE} not found; payload conversion not wired`);
3734
+ return;
3735
+ }
3736
+ const convertPayload = sourceFile.getFunction(CONVERT_PAYLOAD_FUNCTION);
3737
+ const caseBlock = convertPayload?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.SwitchStatement)?.getCaseBlock();
3738
+ if (!caseBlock) {
3739
+ warnSkipped(
3740
+ `Could not find a switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE}; payload conversion not wired`
3741
+ );
3742
+ return;
3743
+ }
3744
+ const missing = RECOVERY_EVENTS.filter(
3745
+ (event) => !caseBlock.getText().includes(`TriggerEvent.${event.constant}`) && !caseBlock.getText().includes(`'${event.id}'`)
3746
+ );
3747
+ if (missing.length === 0) return;
3748
+ const existingClauses = caseBlock.getClauses();
3749
+ if (existingClauses.length === 0) {
3750
+ warnSkipped(
3751
+ `The switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE} has no cases; payload conversion not wired`
3752
+ );
3753
+ return;
3754
+ }
3755
+ const defaultClause = existingClauses.find(import_ts_morph2.Node.isDefaultClause);
3756
+ const anchor = defaultClause ?? existingClauses[existingClauses.length - 1];
3757
+ const indent = anchor.getIndentationText();
3758
+ const lines = [
3759
+ ...missing.map((event) => `case TriggerEvent.${event.constant}:`),
3760
+ ` return {`,
3761
+ ` firstname,`,
3762
+ ` applicationName: applicationConfig.APPLICATION_NAME,`,
3763
+ ` countryLogo: COUNTRY_LOGO_URL,`,
3764
+ ` recoveryURL: \`\${LOGIN_URL}recover?token=\${encodeURIComponent(payload.token)}\``,
3765
+ ` }`
3766
+ ];
3767
+ if (defaultClause) {
3768
+ caseBlock.insertText(
3769
+ anchor.getStart(),
3770
+ `${lines.map((line2, index) => index === 0 ? line2 : `${indent}${line2}`).join("\n")}
3771
+ ${indent}`
3772
+ );
3773
+ } else {
3774
+ caseBlock.insertText(
3775
+ anchor.getEnd(),
3776
+ `
3777
+ ${lines.map((line2) => `${indent}${line2}`).join("\n")}`
3778
+ );
3779
+ }
3780
+ for (const event of missing) {
3781
+ console.log(` \u2713 ${HANDLER_FILE}: ${event.id} case`);
3782
+ }
3783
+ }
3784
+ function updateRoutes(project, cwd) {
3785
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, ROUTES_FILE));
3786
+ if (!sourceFile) {
3787
+ warnSkipped(`${ROUTES_FILE} not found; trigger routes not registered`);
3788
+ return;
3789
+ }
3790
+ const routesFunction = sourceFile.getFunction(ROUTES_FUNCTION) ?? sourceFile.getFunctions().find((fn) => fn.isDefaultExport());
3791
+ const routesArray = routesFunction?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.ReturnStatement)?.getExpressionIfKind(import_ts_morph2.SyntaxKind.ArrayLiteralExpression);
3792
+ if (!routesArray) {
3793
+ warnSkipped(
3794
+ `Could not find the route array returned by '${ROUTES_FUNCTION}' in ${ROUTES_FILE}; trigger routes not registered`
3795
+ );
3796
+ return;
3797
+ }
3798
+ for (const event of RECOVERY_EVENTS) {
3799
+ if (routesArray.getText().includes(`/triggers/user/${event.id}`)) continue;
3800
+ routesArray.addElement(`{
3801
+ method: 'POST',
3802
+ path: '/triggers/user/${event.id}',
3803
+ handler: makeNotificationHandler('${event.id}'),
3804
+ options: {
3805
+ auth: false,
3806
+ tags: ['api'],
3807
+ description: '${event.routeDescription}'
3808
+ }
3809
+ }`);
3810
+ console.log(` \u2713 ${ROUTES_FILE}: POST /triggers/user/${event.id}`);
3811
+ }
3812
+ }
3813
+ function renderEmailTemplate(event) {
3814
+ return `<!--
3815
+ This Source Code Form is subject to the terms of the Mozilla Public
3816
+ License, v. 2.0. If a copy of the MPL was not distributed with this
3817
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
3818
+
3819
+ OpenCRVS is also distributed under the terms of the Civil Registration
3820
+ & Healthcare Disclaimer located at http://opencrvs.org/license.
3821
+
3822
+ Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
3823
+ -->
3824
+ <!doctype html>
3825
+ <html>
3826
+ <head>
3827
+ <link
3828
+ href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
3829
+ rel="stylesheet"
3830
+ />
3831
+ <style type="text/css">
3832
+ body {
3833
+ font-family: 'Noto Sans', sans-serif;
3834
+ color: #222;
3835
+ padding: 16px 24px;
3836
+ }
3837
+
3838
+ h1 {
3839
+ font-size: 21px;
3840
+ margin-top: 32px;
3841
+ margin-bottom: 36px;
3842
+ font-weight: 700;
3843
+ }
3844
+
3845
+ p {
3846
+ font-weight: 400;
3847
+ font-size: 16px;
3848
+ line-height: 1.8;
3849
+ margin-bottom: 24px;
3850
+ }
3851
+
3852
+ i {
3853
+ color: #666;
3854
+ font-weight: 400;
3855
+ font-size: 16px;
3856
+ }
3857
+ </style>
3858
+ </head>
3859
+
3860
+ <body>
3861
+ <img
3862
+ src="{{countryLogo}}"
3863
+ alt="country_logo"
3864
+ style="max-height: 88px; max-width: 100%"
3865
+ />
3866
+ <h1>${event.heading}</h1>
3867
+ <p>Hello {{firstname}},</p>
3868
+ <p>
3869
+ ${event.reason}
3870
+ </p>
3871
+
3872
+ <div style="margin-top: 32px; margin-bottom: 32px">
3873
+ <a href="{{{recoveryURL}}}">${event.linkLabel}</a>
3874
+ </div>
3875
+ <br />
3876
+ <p>
3877
+ This link expires in 1 hour and can only be used once. If you did not
3878
+ request this, you can ignore this email.
3879
+ </p>
3880
+ <br />
3881
+ <p>
3882
+ Best regards, <br />
3883
+ {{applicationName}} Team
3884
+ </p>
3885
+ </body>
3886
+ </html>
3887
+ `;
3888
+ }
3889
+ function writeEmailTemplates(cwd) {
3890
+ const templateDir = import_path2.default.join(cwd, EMAIL_TEMPLATE_DIR);
3891
+ if (!(0, import_fs2.existsSync)(templateDir)) {
3892
+ warnSkipped(
3893
+ `${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`
3894
+ );
3895
+ return;
3896
+ }
3897
+ for (const event of RECOVERY_EVENTS) {
3898
+ const templatePath = import_path2.default.join(templateDir, `${event.id}.html`);
3899
+ if ((0, import_fs2.existsSync)(templatePath)) continue;
3900
+ (0, import_fs2.writeFileSync)(templatePath, renderEmailTemplate(event));
3901
+ console.log(` \u2713 ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
3902
+ }
3903
+ }
3904
+ function addCsvRows(cwd, relativePath, rows) {
3905
+ const csvPath = import_path2.default.join(cwd, relativePath);
3906
+ const file = readCsvFile(csvPath);
3907
+ if (!file) {
3908
+ warnSkipped(`${relativePath} not found; translations not added`);
3909
+ return;
3910
+ }
3911
+ const added = addRows(file, rows);
3912
+ if (added.length === 0) return;
3913
+ for (const id of added) {
3914
+ console.log(` \u2713 ${relativePath}: ${id}`);
3915
+ }
3916
+ writeCsvFile(csvPath, file);
3917
+ }
3918
+ async function main2() {
3919
+ const cwd = process.cwd();
3920
+ const tsConfigFilePath = import_path2.default.join(cwd, "tsconfig.json");
3921
+ console.log(
3922
+ "Registering the password-reset-link and username-reminder-link notifications...\n"
3923
+ );
3924
+ if (!(0, import_fs2.existsSync)(tsConfigFilePath)) {
3925
+ warnSkipped(
3926
+ `tsconfig.json not found in ${cwd}; notification wiring skipped entirely`
3927
+ );
3928
+ return;
3929
+ }
3930
+ const project = new import_ts_morph2.Project({
3931
+ tsConfigFilePath,
3932
+ skipAddingFilesFromTsConfig: false,
3933
+ // ts-morph indents inserted code with four spaces by default, which every
3934
+ // country config's prettier run would immediately undo.
3935
+ manipulationSettings: { indentationText: import_ts_morph2.IndentationText.TwoSpaces }
3936
+ });
3937
+ updateEmailTemplates(project, cwd);
3938
+ updateSmsService(project, cwd);
3939
+ updateHandler(project, cwd);
3940
+ updateRoutes(project, cwd);
3941
+ await project.save();
3942
+ writeEmailTemplates(cwd);
3943
+ addCsvRows(cwd, NOTIFICATION_CSV, NOTIFICATION_CSV_ROWS);
3944
+ addCsvRows(cwd, LOGIN_CSV, LOGIN_CSV_ROWS);
3945
+ if (skipped.length > 0) {
3946
+ console.warn(
3947
+ `
3948
+ \u26A0\uFE0F ${skipped.length} step(s) were skipped. Wire the following by hand before upgrading:`
3949
+ );
3950
+ for (const message of skipped) {
3951
+ console.warn(` - ${message}`);
3952
+ }
3953
+ }
3954
+ }
3955
+
3956
+ // src/migrations/v2.1/add-translations.ts
3957
+ var import_path3 = __toESM(require("path"));
3958
+ var REPOSITORY = "opencrvs/opencrvs-core";
3959
+ var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
3960
+ var APPLICATIONS = ["client", "login"];
3961
+ var TARGET_VERSION = "2.1";
3962
+ var skipped2 = [];
3963
+ function warnSkipped2(message) {
3964
+ skipped2.push(message);
3965
+ console.warn(` \u26A0\uFE0F ${message}`);
3966
+ }
3967
+ async function matchingRefs(namespace, prefix) {
3968
+ const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
3969
+ const response = await fetch(url, {
3970
+ headers: { accept: "application/vnd.github+json" }
3971
+ });
3972
+ if (!response.ok) {
3973
+ throw new Error(
3974
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
3975
+ );
3976
+ }
3977
+ const refs = await response.json();
3978
+ const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
3979
+ return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
3980
+ }
3981
+ async function candidateRefs() {
3982
+ return [
3983
+ ...await matchingRefs("heads", `release/${TARGET_VERSION}.`),
3984
+ ...await matchingRefs("tags", `v${TARGET_VERSION}.`),
3985
+ "develop"
3986
+ ];
3987
+ }
3988
+ async function fetchTemplate(refs, application) {
3989
+ for (const ref of refs) {
3990
+ const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
3991
+ const response = await fetch(url);
3992
+ if (response.ok) {
3993
+ return { ref, contents: await response.text() };
3994
+ }
3995
+ if (response.status !== 404) {
3996
+ throw new Error(
3997
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
3998
+ );
3999
+ }
4000
+ }
4001
+ warnSkipped2(
4002
+ `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
4003
+ );
4004
+ return void 0;
4005
+ }
4006
+ function rowsToAdd(local, template) {
4007
+ const localColumns = parseCsvLine(local.header);
4008
+ const templateColumns = parseCsvLine(template.header);
4009
+ return template.body.filter((line2) => line2 !== "").map((line2) => {
4010
+ const values = parseCsvLine(line2);
4011
+ return toCsvLine(
4012
+ localColumns.map((column) => {
4013
+ const index = templateColumns.indexOf(column);
4014
+ return index === -1 ? "" : values[index] ?? "";
4015
+ })
4016
+ );
4017
+ });
4018
+ }
4019
+ async function updateApplication(cwd, refs, application) {
4020
+ const relativePath = `src/translations/${application}.csv`;
4021
+ const local = readCsvFile(import_path3.default.join(cwd, relativePath));
4022
+ if (!local) {
4023
+ warnSkipped2(`${relativePath} not found; translations not added`);
4024
+ return;
4025
+ }
4026
+ const fetched = await fetchTemplate(refs, application);
4027
+ if (!fetched) {
4028
+ return;
4029
+ }
4030
+ const template = readTemplate(fetched.contents);
4031
+ const added = addRows(local, rowsToAdd(local, template));
4032
+ if (added.length === 0) {
4033
+ return;
4034
+ }
4035
+ try {
4036
+ writeCsvFile(import_path3.default.join(cwd, relativePath), local);
4037
+ } catch (error3) {
4038
+ warnSkipped2(
4039
+ `Could not write ${relativePath} (${error3.message}); translations not added`
4040
+ );
4041
+ return;
4042
+ }
4043
+ for (const id of added) {
4044
+ console.log(` \u2713 ${relativePath}: ${id}`);
4045
+ }
4046
+ }
4047
+ function readTemplate(contents) {
4048
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
4049
+ return {
4050
+ header: lines[0],
4051
+ body: lines.slice(1),
4052
+ newline: "\n",
4053
+ trailingNewline: true
4054
+ };
4055
+ }
4056
+ async function listRefs() {
4057
+ try {
4058
+ return await candidateRefs();
4059
+ } catch (error3) {
4060
+ warnSkipped2(
4061
+ `Could not list the ${TARGET_VERSION} refs on GitHub (${error3.message}); translations not added`
4062
+ );
4063
+ return void 0;
4064
+ }
4065
+ }
4066
+ async function main3() {
4067
+ const cwd = process.cwd();
4068
+ console.log("Adding the translation keys core gained this version...\n");
4069
+ const refs = await listRefs();
4070
+ if (refs) {
4071
+ for (const application of APPLICATIONS) {
4072
+ try {
4073
+ await updateApplication(cwd, refs, application);
4074
+ } catch (error3) {
4075
+ warnSkipped2(
4076
+ `Could not read ${application}.csv from the country config template on GitHub (${error3.message}); ${application}.csv not updated`
4077
+ );
4078
+ }
4079
+ }
4080
+ }
4081
+ if (skipped2.length > 0) {
4082
+ console.warn(
4083
+ `
4084
+ \u26A0\uFE0F ${skipped2.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
4085
+ );
4086
+ for (const message of skipped2) {
4087
+ console.warn(` - ${message}`);
4088
+ }
4089
+ }
4090
+ }
4091
+
4092
+ // src/migrations/v2.1/enable-telemetry.ts
4093
+ var import_ts_morph3 = require("ts-morph");
4094
+ var import_fs3 = require("fs");
4095
+ var import_path4 = __toESM(require("path"));
4096
+ var HANDLER_FILE2 = "src/api/telemetry/handler.ts";
4097
+ var ENVIRONMENT_FILE = "src/environment.ts";
4098
+ var INDEX_FILE = "src/index.ts";
4099
+ var HANDLER_MODULE = "./api/telemetry/handler";
4100
+ var skipped3 = [];
4101
+ function warnSkipped3(message) {
4102
+ skipped3.push(message);
4103
+ console.warn(` \u26A0\uFE0F ${message}`);
4104
+ }
4105
+ var TELEMETRY_HANDLER_SOURCE = `/*
4106
+ * This Source Code Form is subject to the terms of the Mozilla Public
4107
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4108
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
4109
+ *
4110
+ * OpenCRVS is also distributed under the terms of the Civil Registration
4111
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
4112
+ *
4113
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
4114
+ */
4115
+
4116
+ import { Request, ResponseToolkit } from '@hapi/hapi'
4117
+ import * as Joi from 'joi'
4118
+ import { sendTelemetry, TelemetryReport } from '@opencrvs/toolkit/telemetry'
4119
+ import { env } from '@countryconfig/environment'
4120
+ import { logger } from '@countryconfig/logger'
4121
+ import { applicationConfig } from '@countryconfig/api/application/application-config'
4122
+
4123
+ /** Report the events service posts to \`/trigger/telemetry\`. */
4124
+ export const telemetrySchema = Joi.object({
4125
+ reported_at: Joi.string().isoDate().required(),
4126
+ app_version: Joi.string().optional(),
4127
+ metrics: Joi.object()
4128
+ .pattern(
4129
+ Joi.string(),
4130
+ Joi.alternatives(Joi.number(), Joi.string(), Joi.boolean())
4131
+ )
4132
+ .required()
4133
+ })
4134
+
4135
+ interface IncomingReport {
4136
+ reported_at: string
4137
+ app_version?: string
4138
+ metrics: Record<string, number | string | boolean>
4139
+ }
4140
+
4141
+ /** Logged once at countryconfig startup while telemetry is disabled. */
4142
+ export const TELEMETRY_DISABLED_NOTICE =
4143
+ 'Telemetry is disabled. Help improve OpenCRVS by sharing anonymous, ' +
4144
+ 'aggregate usage metrics (registration and certificate counts, active ' +
4145
+ 'users, uptime) \u2014 no personal, health, or otherwise protected record data ' +
4146
+ 'ever leaves your instance. Enable it by setting TELEMETRY_ENABLED=true on ' +
4147
+ 'the countryconfig service.'
4148
+
4149
+ /**
4150
+ * Receives a usage report from the events service and, when telemetry is
4151
+ * enabled for this instance, stamps the instance identity onto it and forwards
4152
+ * it to the status service via the toolkit's \`sendTelemetry\` (which owns the
4153
+ * endpoint and payload schema). The events service is unaware of whether
4154
+ * telemetry is enabled or of the country code / domain / environment reported.
4155
+ */
4156
+ export async function telemetryHandler(request: Request, h: ResponseToolkit) {
4157
+ // Only accept OpenCRVS *system* tokens (the events service's service
4158
+ // token has userType 'system'). A logged-in user's token is a 'user' token,
4159
+ // so a user cannot submit telemetry with their own credentials \u2014 and the
4160
+ // service-token endpoint is not reachable through the public gateway.
4161
+ const credentials = request.auth.credentials as
4162
+ | { userType?: string }
4163
+ | undefined
4164
+ if (credentials?.userType !== 'system') {
4165
+ logger.warn('Telemetry: rejected a request that is not from a system token')
4166
+ return h.response({ error: 'forbidden' }).code(403)
4167
+ }
4168
+
4169
+ if (!env.TELEMETRY_ENABLED) {
4170
+ // The encouraging notice is logged once at startup (see index.ts); keep the
4171
+ // per-report path quiet.
4172
+ return h.response({ status: 'skipped' }).code(200)
4173
+ }
4174
+
4175
+ const incoming = request.payload as IncomingReport
4176
+
4177
+ // Only production instances report; staging, QA and local build the report
4178
+ // but never reach the status service. (This gate used to live in the
4179
+ // toolkit's sendTelemetry; each country config now owns it.)
4180
+ if (!env.isProduction) {
4181
+ logger.info(
4182
+ \`Telemetry: report for \${incoming.reported_at} was not sent \u2014 only production instances report\`
4183
+ )
4184
+ return h.response({ status: 'skipped' }).code(200)
4185
+ }
4186
+
4187
+ const report: TelemetryReport = {
4188
+ reported_at: incoming.reported_at,
4189
+ country_code: env.COUNTRY_CODE,
4190
+ organisation: env.ORGANISATION,
4191
+ // env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
4192
+ // "no domain" rather than reporting a literal "*".
4193
+ domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
4194
+ instance: {
4195
+ application_name: applicationConfig.APPLICATION_NAME,
4196
+ environment: env.ENVIRONMENT_NAME,
4197
+ app_version: incoming.app_version
4198
+ },
4199
+ metrics: incoming.metrics
4200
+ }
4201
+
4202
+ let result
4203
+ try {
4204
+ result = await sendTelemetry(report)
4205
+ } catch (error) {
4206
+ const message = error instanceof Error ? error.message : String(error)
4207
+ logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
4208
+ return h.response({ status: 'error' }).code(502)
4209
+ }
4210
+
4211
+ if (result.outcome === 'rejected') {
4212
+ logger.error(
4213
+ \`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
4214
+ )
4215
+ return h.response({ status: 'error' }).code(502)
4216
+ }
4217
+
4218
+ logger.info(
4219
+ \`Telemetry: forwarded report for \${report.reported_at} to the status service\`
4220
+ )
4221
+ return h.response({ status: 'forwarded' }).code(202)
4222
+ }
4223
+ `;
4224
+ var TELEMETRY_DISABLED = {
4225
+ enabled: false,
4226
+ countryCode: "",
4227
+ organisation: ""
4228
+ };
4229
+ async function promptTelemetryConfig() {
4230
+ if (!process.stdin.isTTY) {
4231
+ return TELEMETRY_DISABLED;
4232
+ }
4233
+ const { confirm: confirm3, input: input4 } = await import("@inquirer/prompts");
4234
+ const enabled = await confirm3({
4235
+ message: "Enable anonymous usage telemetry to help improve OpenCRVS? Only aggregate metrics are shared \u2014 no personal or protected data.",
4236
+ default: true
4237
+ });
4238
+ if (!enabled) {
4239
+ return TELEMETRY_DISABLED;
4240
+ }
4241
+ const countryCode = (await input4({
4242
+ message: "Country code (ISO alpha-3, e.g. FAR):",
4243
+ validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) || "Enter a 3-letter ISO alpha-3 code."
4244
+ })).trim().toUpperCase();
4245
+ const organisation = (await input4({
4246
+ message: "Organisation running this instance:",
4247
+ validate: (value) => value.trim() !== "" || "Enter an organisation name."
4248
+ })).trim();
4249
+ return { enabled: true, countryCode, organisation };
4250
+ }
4251
+ function writeTelemetryHandler(cwd) {
4252
+ const handlerPath = import_path4.default.join(cwd, HANDLER_FILE2);
4253
+ if ((0, import_fs3.existsSync)(handlerPath)) {
4254
+ console.log(` ${HANDLER_FILE2} already present; left unchanged`);
4255
+ return;
4256
+ }
4257
+ (0, import_fs3.mkdirSync)(import_path4.default.dirname(handlerPath), { recursive: true });
4258
+ (0, import_fs3.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
4259
+ console.log(` \u2713 ${HANDLER_FILE2}`);
4260
+ }
4261
+ function appendProperty(sourceFile, object, name, valueLines) {
4262
+ const properties = object.getProperties();
4263
+ const lastProperty = properties[properties.length - 1];
4264
+ if (!lastProperty) return false;
4265
+ const indent = lastProperty.getIndentationText();
4266
+ const entry = valueLines.map((line2, index) => `${indent}${index === 0 ? `${name}: ${line2}` : line2}`).join("\n");
4267
+ sourceFile.insertText(lastProperty.getEnd(), `,
4268
+ ${entry}`);
4269
+ return true;
4270
+ }
4271
+ function ensureEnvalidNamedImports(sourceFile, names) {
4272
+ const importDeclaration = sourceFile.getImportDeclarations().find((declaration) => declaration.getModuleSpecifierValue() === "envalid");
4273
+ if (!importDeclaration) {
4274
+ warnSkipped3(
4275
+ `Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(", ")} } by hand`
4276
+ );
4277
+ return;
4278
+ }
4279
+ const existing = new Set(
4280
+ importDeclaration.getNamedImports().map((named) => named.getName())
4281
+ );
4282
+ for (const name of names) {
4283
+ if (!existing.has(name)) {
4284
+ importDeclaration.addNamedImport(name);
4285
+ }
4286
+ }
4287
+ }
4288
+ function getCleanEnvObject(sourceFile) {
4289
+ const options = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
4290
+ return options && import_ts_morph3.Node.isObjectLiteralExpression(options) ? options : void 0;
4291
+ }
4292
+ function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
4293
+ const object = getCleanEnvObject(sourceFile);
4294
+ if (!object) return;
4295
+ const existing = object.getProperty(name);
4296
+ if (existing && import_ts_morph3.Node.isPropertyAssignment(existing)) {
4297
+ if (!update) return;
4298
+ const options = existing.getInitializerIfKind(import_ts_morph3.SyntaxKind.CallExpression)?.getArguments()[0];
4299
+ if (options && import_ts_morph3.Node.isObjectLiteralExpression(options)) {
4300
+ const defaultProperty = options.getProperty("default");
4301
+ if (defaultProperty && import_ts_morph3.Node.isPropertyAssignment(defaultProperty)) {
4302
+ defaultProperty.setInitializer(defaultExpr);
4303
+ } else {
4304
+ options.insertPropertyAssignment(0, {
4305
+ name: "default",
4306
+ initializer: defaultExpr
4307
+ });
4308
+ }
4309
+ console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name} default set`);
4310
+ }
4311
+ return;
4312
+ }
4313
+ if (appendProperty(sourceFile, object, name, [
4314
+ `${kind}({`,
4315
+ ` default: ${defaultExpr},`,
4316
+ ` desc: ${JSON.stringify(desc)}`,
4317
+ "})"
4318
+ ])) {
4319
+ console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name}`);
4320
+ }
4321
+ }
4322
+ function addEnvironmentVariables(project, cwd, config) {
4323
+ const sourceFile = project.addSourceFileAtPathIfExists(
4324
+ import_path4.default.join(cwd, ENVIRONMENT_FILE)
4325
+ );
4326
+ if (!sourceFile) {
4327
+ warnSkipped3(
4328
+ `${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`
4329
+ );
4330
+ return;
4331
+ }
4332
+ if (!getCleanEnvObject(sourceFile)) {
4333
+ warnSkipped3(
4334
+ `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`
4335
+ );
4336
+ return;
4337
+ }
4338
+ ensureEnvalidNamedImports(sourceFile, ["bool", "str"]);
4339
+ upsertEnvVar(
4340
+ sourceFile,
4341
+ "TELEMETRY_ENABLED",
4342
+ "bool",
4343
+ config.enabled ? "true" : "false",
4344
+ "When true, usage telemetry received from the events service is forwarded to the OpenCRVS status service.",
4345
+ true
4346
+ );
4347
+ upsertEnvVar(
4348
+ sourceFile,
4349
+ "COUNTRY_CODE",
4350
+ "str",
4351
+ config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`,
4352
+ "ISO-style country code of this instance, reported with telemetry.",
4353
+ config.enabled
4354
+ );
4355
+ upsertEnvVar(
4356
+ sourceFile,
4357
+ "ORGANISATION",
4358
+ "str",
4359
+ config.enabled ? JSON.stringify(config.organisation) : `''`,
4360
+ "Organisation running this instance, reported with telemetry. Empty by default.",
4361
+ config.enabled
4362
+ );
4363
+ upsertEnvVar(
4364
+ sourceFile,
4365
+ "ENVIRONMENT_NAME",
4366
+ "str",
4367
+ `'development'`,
4368
+ 'Environment name (e.g. "production", "staging") reported as the telemetry environment.',
4369
+ false
4370
+ );
4371
+ }
4372
+ function wireIndex(project, cwd) {
4373
+ const sourceFile = project.addSourceFileAtPathIfExists(
4374
+ import_path4.default.join(cwd, INDEX_FILE)
4375
+ );
4376
+ if (!sourceFile) {
4377
+ warnSkipped3(
4378
+ `${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`
4379
+ );
4380
+ return;
4381
+ }
4382
+ if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === HANDLER_MODULE)) {
4383
+ sourceFile.addImportDeclaration({
4384
+ moduleSpecifier: HANDLER_MODULE,
4385
+ namedImports: [
4386
+ "telemetryHandler",
4387
+ "telemetrySchema",
4388
+ "TELEMETRY_DISABLED_NOTICE"
4389
+ ]
4390
+ });
4391
+ console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
4392
+ }
4393
+ if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
4394
+ const lastRouteStatement = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter((call) => call.getExpression().getText() === "server.route").map(
4395
+ (call) => call.getFirstAncestorByKind(import_ts_morph3.SyntaxKind.ExpressionStatement)
4396
+ ).filter(
4397
+ (statement) => Boolean(statement)
4398
+ ).pop();
4399
+ if (!lastRouteStatement) {
4400
+ warnSkipped3(
4401
+ `Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`
4402
+ );
4403
+ } else {
4404
+ const indent = lastRouteStatement.getIndentationText();
4405
+ const route = [
4406
+ `server.route({`,
4407
+ ` method: 'POST',`,
4408
+ ` path: '/trigger/telemetry',`,
4409
+ ` handler: telemetryHandler,`,
4410
+ ` options: {`,
4411
+ ` tags: ['api', 'triggers'],`,
4412
+ ` validate: {`,
4413
+ ` payload: telemetrySchema`,
4414
+ ` },`,
4415
+ ` description:`,
4416
+ ` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
4417
+ ` }`,
4418
+ `})`
4419
+ ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4420
+ sourceFile.insertText(lastRouteStatement.getEnd(), `
4421
+
4422
+ ${route}`);
4423
+ console.log(` \u2713 ${INDEX_FILE}: POST /trigger/telemetry`);
4424
+ }
4425
+ }
4426
+ if (!sourceFile.getText().includes("logger.info(TELEMETRY_DISABLED_NOTICE)")) {
4427
+ const startedLog = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.ExpressionStatement).find(
4428
+ (statement) => statement.getText().includes("Server successfully started")
4429
+ );
4430
+ if (!startedLog) {
4431
+ warnSkipped3(
4432
+ `Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`
4433
+ );
4434
+ } else {
4435
+ const indent = startedLog.getIndentationText();
4436
+ const notice = [
4437
+ `if (!env.TELEMETRY_ENABLED) {`,
4438
+ ` logger.info(TELEMETRY_DISABLED_NOTICE)`,
4439
+ `}`
4440
+ ].map((line2) => line2 ? `${indent}${line2}` : line2).join("\n");
4441
+ sourceFile.insertText(startedLog.getEnd(), `
4442
+
4443
+ ${notice}`);
4444
+ console.log(` \u2713 ${INDEX_FILE}: telemetry-disabled startup notice`);
4445
+ if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "./environment")) {
4446
+ warnSkipped3(
4447
+ `The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`
4448
+ );
4449
+ }
4450
+ }
4451
+ }
4452
+ }
4453
+ async function main4() {
4454
+ const cwd = process.cwd();
4455
+ const config = await promptTelemetryConfig();
4456
+ console.log(
4457
+ `
4458
+ Adding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : "disabled"} by default)...
4459
+ `
4460
+ );
4461
+ writeTelemetryHandler(cwd);
4462
+ const project = new import_ts_morph3.Project({
4463
+ // ts-morph indents inserted code with four spaces and double-quotes strings
4464
+ // by default, both of which the country config's prettier run would undo.
4465
+ manipulationSettings: {
4466
+ indentationText: import_ts_morph3.IndentationText.TwoSpaces,
4467
+ quoteKind: import_ts_morph3.QuoteKind.Single
4468
+ }
4469
+ });
4470
+ addEnvironmentVariables(project, cwd, config);
4471
+ wireIndex(project, cwd);
4472
+ await project.save();
4473
+ if (skipped3.length > 0) {
4474
+ console.warn(
4475
+ `
4476
+ \u26A0\uFE0F ${skipped3.length} telemetry step(s) were skipped. Wire the following by hand:`
4477
+ );
4478
+ for (const message of skipped3) {
4479
+ console.warn(` - ${message}`);
4480
+ }
4481
+ }
4482
+ }
4483
+
3290
4484
  // src/migrations/v2.1/index.ts
3291
4485
  async function runUpgrade(dockerSwarm) {
3292
4486
  await main();
4487
+ await main2();
4488
+ await main3();
4489
+ await main4();
4490
+ }
4491
+
4492
+ // src/translations/check.ts
4493
+ var import_ts_morph4 = require("ts-morph");
4494
+ var import_path5 = __toESM(require("path"));
4495
+ var TRANSLATIONS = "src/translations";
4496
+ var OWN_FILE = `${TRANSLATIONS}/countryconfig.csv`;
4497
+ var CORE_FILES = [`${TRANSLATIONS}/client.csv`, `${TRANSLATIONS}/login.csv`];
4498
+ function staticStringOf(node, name) {
4499
+ const property = node.getProperty(name);
4500
+ if (!property || !import_ts_morph4.Node.isPropertyAssignment(property)) {
4501
+ return void 0;
4502
+ }
4503
+ const initializer = property.getInitializer();
4504
+ return initializer && (import_ts_morph4.Node.isStringLiteral(initializer) || import_ts_morph4.Node.isNoSubstitutionTemplateLiteral(initializer)) ? initializer.getLiteralValue() : void 0;
4505
+ }
4506
+ function messagesDeclaredIn(cwd) {
4507
+ const project = new import_ts_morph4.Project({ skipAddingFilesFromTsConfig: true });
4508
+ project.addSourceFilesAtPaths([
4509
+ import_path5.default.join(cwd, "src/**/*.ts"),
4510
+ import_path5.default.join(cwd, "src/**/*.tsx"),
4511
+ `!${import_path5.default.join(cwd, "src/**/*.test.ts")}`,
4512
+ `!${import_path5.default.join(cwd, "src/**/*.test.tsx")}`,
4513
+ `!${import_path5.default.join(cwd, "src/**/*.stories.ts")}`,
4514
+ `!${import_path5.default.join(cwd, "src/**/*.stories.tsx")}`
4515
+ ]);
4516
+ const messages = [];
4517
+ const dynamicIds = [];
4518
+ for (const sourceFile of project.getSourceFiles()) {
4519
+ sourceFile.forEachDescendant((node) => {
4520
+ if (!import_ts_morph4.Node.isObjectLiteralExpression(node)) {
4521
+ return;
4522
+ }
4523
+ if (!(node.getProperty("id") && node.getProperty("defaultMessage"))) {
4524
+ return;
4525
+ }
4526
+ const id = staticStringOf(node, "id");
4527
+ if (id === void 0) {
4528
+ dynamicIds.push(import_path5.default.relative(cwd, sourceFile.getFilePath()));
4529
+ return;
4530
+ }
4531
+ messages.push({
4532
+ id,
4533
+ defaultMessage: staticStringOf(node, "defaultMessage") ?? "",
4534
+ description: staticStringOf(node, "description") ?? ""
4535
+ });
4536
+ });
4537
+ }
4538
+ return { messages, dynamicIds: [...new Set(dynamicIds)] };
4539
+ }
4540
+ function check(cwd) {
4541
+ const { messages, dynamicIds } = messagesDeclaredIn(cwd);
4542
+ const own = readCsvFile(import_path5.default.join(cwd, OWN_FILE));
4543
+ const covered = new Set(
4544
+ [own, ...CORE_FILES.map((file) => readCsvFile(import_path5.default.join(cwd, file)))].flatMap((csv) => csv?.body ?? []).map(idOf)
4545
+ );
4546
+ const missing = [
4547
+ ...new Map(
4548
+ messages.filter(({ id }) => !covered.has(id)).map((message) => [message.id, message])
4549
+ ).values()
4550
+ ].sort((a, b) => a.id < b.id ? -1 : 1);
4551
+ const declared = new Set(messages.map(({ id }) => id));
4552
+ const outdated = (own?.body ?? []).map(idOf).filter((id) => !declared.has(id));
4553
+ return { missing, outdated, dynamicIds };
4554
+ }
4555
+ function writeMissing(cwd, missing) {
4556
+ const file = readCsvFile(import_path5.default.join(cwd, OWN_FILE));
4557
+ if (!file) {
4558
+ throw new Error(`${OWN_FILE} not found in ${cwd}`);
4559
+ }
4560
+ const columns = file.header.split(",");
4561
+ const rows = missing.map(
4562
+ (message) => toCsvLine(
4563
+ columns.map((column) => {
4564
+ if (column === "id") return message.id;
4565
+ if (column === "description") return message.description;
4566
+ return column === "en" ? message.defaultMessage : "";
4567
+ })
4568
+ )
4569
+ );
4570
+ const added = addRows(file, rows);
4571
+ writeCsvFile(import_path5.default.join(cwd, OWN_FILE), file);
4572
+ return added;
3293
4573
  }
3294
4574
 
3295
4575
  // src/environment/index.ts
3296
- var import_fs4 = require("fs");
3297
- var import_path4 = require("path");
4576
+ var import_fs8 = require("fs");
4577
+ var import_path10 = require("path");
4578
+ init_paths();
3298
4579
  var REQUIRED_REPOSITORY_DIRECTORIES = [
3299
4580
  ".github/workflows",
3300
4581
  "environments",
@@ -3304,7 +4585,7 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
3304
4585
  const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
3305
4586
  (directory) => {
3306
4587
  try {
3307
- return !(0, import_fs4.statSync)((0, import_path4.resolve)(repositoryRoot, directory)).isDirectory();
4588
+ return !(0, import_fs8.statSync)((0, import_path10.resolve)(repositoryRoot, directory)).isDirectory();
3308
4589
  } catch {
3309
4590
  return true;
3310
4591
  }
@@ -3318,8 +4599,14 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
3318
4599
  }
3319
4600
  async function runEnvironmentInit() {
3320
4601
  validateRepositoryStructure();
4602
+ assertNoOldInventoryLayout();
3321
4603
  await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
3322
4604
  }
4605
+ async function runEnvironmentUpgrade() {
4606
+ validateRepositoryStructure();
4607
+ const { upgradeEnvironmentLayout: upgradeEnvironmentLayout2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
4608
+ await upgradeEnvironmentLayout2();
4609
+ }
3323
4610
  async function runEnvironmentUpdateWorkflows() {
3324
4611
  validateRepositoryStructure();
3325
4612
  const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
@@ -3335,6 +4622,278 @@ async function runEnvironmentSwarmToK8s() {
3335
4622
  await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
3336
4623
  }
3337
4624
 
4625
+ // src/verify/endpoints.ts
4626
+ var import_colors = require("kleur/colors");
4627
+ var REQUEST_TIMEOUT_MS = 15e3;
4628
+ var DEFAULT_TARGET_URL = "http://localhost:3040";
4629
+ var REQUIRED_PUBLIC_ENDPOINTS = [
4630
+ { method: "GET", path: "/client-config.js" },
4631
+ { method: "GET", path: "/login-config.js" },
4632
+ { method: "GET", path: "/handlebars.js" },
4633
+ { method: "GET", path: "/content/client" },
4634
+ { method: "GET", path: "/content/login" },
4635
+ { method: "GET", path: "/content/map.geojson" },
4636
+ { method: "GET", path: "/content/country-logo" },
4637
+ { method: "GET", path: "/config/application" },
4638
+ { method: "GET", path: "/config/workqueues" },
4639
+ { method: "GET", path: "/config/locations" },
4640
+ { method: "GET", path: "/config/roles" },
4641
+ { method: "GET", path: "/config/events" }
4642
+ ];
4643
+ var PROBE_SEGMENT = "verify-endpoints-probe";
4644
+ var SECURED_TRIGGER_USER_EVENTS = [
4645
+ "user-created",
4646
+ "user-updated",
4647
+ "username-reminder",
4648
+ "reset-password",
4649
+ "reset-password-by-admin",
4650
+ "password-reset-link",
4651
+ "username-reminder-link",
4652
+ "resend-invite",
4653
+ "2fa",
4654
+ "all-user-notification",
4655
+ "change-phone-number",
4656
+ "change-email-address"
4657
+ ];
4658
+ var SECURED_ENDPOINTS = [
4659
+ ...SECURED_TRIGGER_USER_EVENTS.map(
4660
+ (event) => ({
4661
+ method: "POST",
4662
+ path: `/triggers/user/${event}`
4663
+ })
4664
+ ),
4665
+ { method: "POST", path: "/trigger/telemetry" },
4666
+ { method: "GET", path: "/triggers/system/ready" },
4667
+ {
4668
+ method: "GET",
4669
+ path: `/certificates/${PROBE_SEGMENT}`,
4670
+ label: "/certificates/{id}"
4671
+ },
4672
+ { method: "GET", path: "/certificates" },
4673
+ { method: "GET", path: "/config/users" }
4674
+ ];
4675
+ var FALLBACK_EVENT_TRIGGERS = [
4676
+ {
4677
+ method: "POST",
4678
+ path: `/trigger/events/${PROBE_SEGMENT}/actions/${PROBE_SEGMENT}`,
4679
+ label: "/trigger/events/{event}/actions/{action}"
4680
+ },
4681
+ {
4682
+ method: "POST",
4683
+ path: `/trigger/events/birth/actions/${PROBE_SEGMENT}`,
4684
+ label: "/trigger/events/birth/actions/{action}"
4685
+ },
4686
+ {
4687
+ method: "POST",
4688
+ path: `/trigger/events/death/actions/${PROBE_SEGMENT}`,
4689
+ label: "/trigger/events/death/actions/{action}"
4690
+ }
4691
+ ];
4692
+ var isSuccess = (status) => status !== "error" && status >= 200 && status < 300;
4693
+ var requiresAuthOrAbsent = (status) => status === 401 || status === 403 || status === 404;
4694
+ async function requestStatus(url, method) {
4695
+ const controller = new AbortController();
4696
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
4697
+ try {
4698
+ const response = await fetch(url, {
4699
+ method,
4700
+ signal: controller.signal,
4701
+ // Sent without an Authorization header on purpose. A secured route
4702
+ // rejects with 401/403 before ever reading the body.
4703
+ headers: method === "POST" ? { "Content-Type": "application/json" } : void 0,
4704
+ body: method === "POST" ? "{}" : void 0
4705
+ });
4706
+ return response.status;
4707
+ } catch {
4708
+ return "error";
4709
+ } finally {
4710
+ clearTimeout(timer);
4711
+ }
4712
+ }
4713
+ function toEventTriggerConfig(value) {
4714
+ if (typeof value !== "object" || value === null) {
4715
+ return null;
4716
+ }
4717
+ const record = value;
4718
+ if (typeof record.id !== "string") {
4719
+ return null;
4720
+ }
4721
+ const actions = Array.isArray(record.actions) ? Array.from(
4722
+ new Set(
4723
+ record.actions.map((action) => {
4724
+ if (typeof action !== "object" || action === null) {
4725
+ return null;
4726
+ }
4727
+ const type = action.type;
4728
+ return typeof type === "string" ? type : null;
4729
+ }).filter((type) => type !== null)
4730
+ )
4731
+ ) : [];
4732
+ return { id: record.id, actions };
4733
+ }
4734
+ async function fetchEventConfigs(baseUrl) {
4735
+ const controller = new AbortController();
4736
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
4737
+ try {
4738
+ const response = await fetch(`${baseUrl}/config/events`, {
4739
+ signal: controller.signal
4740
+ });
4741
+ if (!response.ok) {
4742
+ return null;
4743
+ }
4744
+ const body = await response.json();
4745
+ if (!Array.isArray(body)) {
4746
+ return null;
4747
+ }
4748
+ return body.map(toEventTriggerConfig).filter((config) => config !== null);
4749
+ } catch {
4750
+ return null;
4751
+ } finally {
4752
+ clearTimeout(timer);
4753
+ }
4754
+ }
4755
+ function resolveBaseUrl(input4) {
4756
+ const withProtocol = /^https?:\/\//i.test(input4) ? input4 : `https://${input4}`;
4757
+ return withProtocol.replace(/\/+$/, "");
4758
+ }
4759
+ function describeStatus(status) {
4760
+ return status === "error" ? "no response" : `HTTP ${status}`;
4761
+ }
4762
+ function endpointLabel(check2) {
4763
+ const shown = check2.label ?? check2.path;
4764
+ const suffix = check2.label ? (0, import_colors.dim)(` \u2192 ${check2.path}`) : "";
4765
+ return `${check2.method} ${shown}${suffix}`;
4766
+ }
4767
+ function line(ok, label, detail) {
4768
+ const mark = ok ? (0, import_colors.green)("\u2713") : (0, import_colors.red)("\u2717");
4769
+ return ` ${mark} ${label} ${(0, import_colors.dim)(`(${detail})`)}`;
4770
+ }
4771
+ function securedDetail(status) {
4772
+ if (status === 401 || status === 403) {
4773
+ return `${describeStatus(status)} \u2014 auth required`;
4774
+ }
4775
+ if (status === 404) {
4776
+ return `${describeStatus(status)} \u2014 not implemented`;
4777
+ }
4778
+ if (status === "error") {
4779
+ return `${describeStatus(status)} \u2014 request failed`;
4780
+ }
4781
+ return `${describeStatus(status)} \u2014 INSECURE: processed without a token`;
4782
+ }
4783
+ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4784
+ const baseUrl = resolveBaseUrl(target);
4785
+ console.log((0, import_colors.bold)(`Verifying country config endpoints at ${baseUrl}
4786
+ `));
4787
+ let failures = 0;
4788
+ console.log((0, import_colors.bold)("Required public endpoints (must respond 2xx):"));
4789
+ for (const check2 of REQUIRED_PUBLIC_ENDPOINTS) {
4790
+ const status = await requestStatus(`${baseUrl}${check2.path}`, check2.method);
4791
+ const ok = isSuccess(status);
4792
+ if (!ok) {
4793
+ failures++;
4794
+ }
4795
+ const detail = status === 404 ? `${describeStatus(status)} \u2014 missing` : ok ? describeStatus(status) : `${describeStatus(status)} \u2014 unexpected`;
4796
+ console.log(line(ok, endpointLabel(check2), detail));
4797
+ }
4798
+ {
4799
+ const path10 = `/fonts/${PROBE_SEGMENT}.ttf`;
4800
+ const status = await requestStatus(`${baseUrl}${path10}`, "GET");
4801
+ const ok = status === 200 || status === 404;
4802
+ if (!ok) {
4803
+ failures++;
4804
+ }
4805
+ let detail;
4806
+ if (status === 404) {
4807
+ detail = `${describeStatus(status)} \u2014 reachable (made-up filename)`;
4808
+ } else if (status === 200) {
4809
+ detail = describeStatus(status);
4810
+ } else if (status === 401 || status === 403) {
4811
+ detail = `${describeStatus(status)} \u2014 must be public`;
4812
+ } else {
4813
+ detail = `${describeStatus(status)} \u2014 unexpected`;
4814
+ }
4815
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path10}`)}`, detail));
4816
+ }
4817
+ console.log();
4818
+ console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
4819
+ for (const check2 of SECURED_ENDPOINTS) {
4820
+ const status = await requestStatus(`${baseUrl}${check2.path}`, check2.method);
4821
+ const ok = requiresAuthOrAbsent(status);
4822
+ if (!ok) {
4823
+ failures++;
4824
+ }
4825
+ console.log(line(ok, endpointLabel(check2), securedDetail(status)));
4826
+ }
4827
+ console.log();
4828
+ console.log((0, import_colors.bold)("Event action triggers (must be absent or require auth):"));
4829
+ const events = await fetchEventConfigs(baseUrl);
4830
+ if (!events) {
4831
+ console.log(
4832
+ " " + (0, import_colors.yellow)(
4833
+ "Could not read /config/events; falling back to route-pattern checks."
4834
+ )
4835
+ );
4836
+ for (const check2 of FALLBACK_EVENT_TRIGGERS) {
4837
+ const status = await requestStatus(
4838
+ `${baseUrl}${check2.path}`,
4839
+ check2.method
4840
+ );
4841
+ const ok = requiresAuthOrAbsent(status);
4842
+ if (!ok) {
4843
+ failures++;
4844
+ }
4845
+ console.log(line(ok, endpointLabel(check2), securedDetail(status)));
4846
+ }
4847
+ } else if (events.length === 0) {
4848
+ console.log(" " + (0, import_colors.yellow)("No events configured."));
4849
+ } else {
4850
+ for (const event of events) {
4851
+ const actions = event.actions.length ? event.actions : [PROBE_SEGMENT];
4852
+ const failed = [];
4853
+ for (const action of actions) {
4854
+ const status = await requestStatus(
4855
+ `${baseUrl}/trigger/events/${event.id}/actions/${action}`,
4856
+ "POST"
4857
+ );
4858
+ if (!requiresAuthOrAbsent(status)) {
4859
+ failed.push({ action, status });
4860
+ }
4861
+ }
4862
+ const pattern = `POST /trigger/events/${event.id}/actions/{action}`;
4863
+ if (failed.length === 0) {
4864
+ console.log(
4865
+ line(true, pattern, `${actions.length} action(s) \u2014 all require auth`)
4866
+ );
4867
+ } else {
4868
+ for (const failure of failed) {
4869
+ failures++;
4870
+ console.log(
4871
+ line(
4872
+ false,
4873
+ `POST /trigger/events/${event.id}/actions/${failure.action}`,
4874
+ securedDetail(failure.status)
4875
+ )
4876
+ );
4877
+ }
4878
+ const okCount = actions.length - failed.length;
4879
+ if (okCount > 0) {
4880
+ console.log(
4881
+ line(true, pattern, `${okCount} other action(s) require auth`)
4882
+ );
4883
+ }
4884
+ }
4885
+ }
4886
+ }
4887
+ console.log();
4888
+ if (failures > 0) {
4889
+ console.log(
4890
+ (0, import_colors.red)((0, import_colors.bold)(`\u2717 ${failures} check(s) failed.`)) + (0, import_colors.yellow)(" See the lines marked \u2717 above.")
4891
+ );
4892
+ process.exit(1);
4893
+ }
4894
+ console.log((0, import_colors.green)((0, import_colors.bold)("\u2713 All endpoint checks passed.")));
4895
+ }
4896
+
3338
4897
  // src/cli.ts
3339
4898
  var args = process.argv.slice(2);
3340
4899
  var USAGE = `
@@ -3344,9 +4903,31 @@ Commands:
3344
4903
  environment Manage deployment environments
3345
4904
  upgrade Upgrade an existing environment
3346
4905
  check-translations Check translation files for completeness
4906
+ verify-endpoints Verify the locally-running country config exposes the
4907
+ expected endpoints and keeps secured ones locked down
3347
4908
 
3348
4909
  Run 'opencrvs <command> --help' for more information on a command.
3349
4910
  `.trim();
4911
+ var VERIFY_ENDPOINTS_USAGE = `
4912
+ Usage: opencrvs verify-endpoints [country-config-url]
4913
+
4914
+ Run this after 'opencrvs upgrade', with the upgraded country config running
4915
+ locally, to confirm it still behaves correctly. It checks over HTTP that:
4916
+ - required public endpoints exist (respond 2xx), and
4917
+ - user-notification trigger endpoints are either absent or reject
4918
+ unauthenticated requests (never processed without a token).
4919
+
4920
+ Arguments:
4921
+ [country-config-url] Optional. Domain or URL of the country config
4922
+ service. Defaults to 'http://localhost:3040', the
4923
+ port country config listens on locally. A bare
4924
+ domain is assumed to use https.
4925
+
4926
+ Options:
4927
+ -h, --help Show this message.
4928
+
4929
+ Exits with a non-zero status if any check fails.
4930
+ `.trim();
3350
4931
  var UPGRADE_USAGE = `
3351
4932
  Usage: opencrvs upgrade [options]
3352
4933
 
@@ -3360,7 +4941,7 @@ Options:
3360
4941
  'infrastructure/' directory is deleted (default).
3361
4942
  -h, --help Show this message.
3362
4943
  `.trim();
3363
- function main2() {
4944
+ function main5() {
3364
4945
  const command = args[0];
3365
4946
  if (!command || command === "--help" || command === "-h") {
3366
4947
  console.log(USAGE);
@@ -3373,6 +4954,8 @@ function main2() {
3373
4954
  return handleUpgrade();
3374
4955
  case "check-translations":
3375
4956
  return handleCheckTranslations();
4957
+ case "verify-endpoints":
4958
+ return handleVerifyEndpoints();
3376
4959
  default:
3377
4960
  console.error(`Unknown command: ${command}
3378
4961
  `);
@@ -3389,6 +4972,7 @@ Usage: opencrvs environment <subcommand>
3389
4972
 
3390
4973
  Subcommands:
3391
4974
  init Initialise a new environment
4975
+ upgrade Upgrade existing environment configuration
3392
4976
  update-workflows Update workflow environment options
3393
4977
  users Manage environment users
3394
4978
  swarm-to-k8s Migrate Docker Swarm configuration to Kubernetes
@@ -3399,6 +4983,8 @@ Subcommands:
3399
4983
  switch (subcommand) {
3400
4984
  case "init":
3401
4985
  return runEnvironmentCommand("initialisation", runEnvironmentInit);
4986
+ case "upgrade":
4987
+ return runEnvironmentCommand("environment upgrade", runEnvironmentUpgrade);
3402
4988
  case "update-workflows":
3403
4989
  return runEnvironmentCommand(
3404
4990
  "workflow update",
@@ -3419,10 +5005,10 @@ Subcommands:
3419
5005
  async function runEnvironmentCommand(operation, command) {
3420
5006
  try {
3421
5007
  await command();
3422
- } catch (error4) {
5008
+ } catch (error3) {
3423
5009
  console.error(
3424
5010
  `Environment ${operation} failed:`,
3425
- error4 instanceof Error ? error4.message : error4
5011
+ error3 instanceof Error ? error3.message : error3
3426
5012
  );
3427
5013
  process.exit(1);
3428
5014
  }
@@ -3448,14 +5034,95 @@ async function handleUpgrade() {
3448
5034
  try {
3449
5035
  await runUpgrade(dockerSwarm);
3450
5036
  console.log("Upgrade completed successfully!");
3451
- } catch (error4) {
3452
- console.error("Upgrade failed:", error4);
5037
+ } catch (error3) {
5038
+ console.error("Upgrade failed:", error3);
3453
5039
  process.exit(1);
3454
5040
  }
3455
5041
  }
5042
+ var CHECK_TRANSLATIONS_USAGE = `
5043
+ Usage: opencrvs check-translations [options]
5044
+
5045
+ Check that every message this country config declares has a row in
5046
+ src/translations/countryconfig.csv.
5047
+
5048
+ Options:
5049
+ --write Add the missing rows, filling in English only
5050
+ --outdated List rows nothing in the source declares any more
5051
+ -h, --help Show this help
5052
+ `;
3456
5053
  function handleCheckTranslations() {
3457
- console.log("Checking translations...");
3458
- console.warn("This command is not implemented yet!");
3459
- process.exit(1);
5054
+ const checkArgs = args.slice(1);
5055
+ if (checkArgs.includes("--help") || checkArgs.includes("-h")) {
5056
+ console.log(CHECK_TRANSLATIONS_USAGE);
5057
+ return;
5058
+ }
5059
+ const unknownFlags = checkArgs.filter(
5060
+ (arg) => arg.startsWith("-") && !["--write", "--outdated"].includes(arg)
5061
+ );
5062
+ if (unknownFlags.length > 0) {
5063
+ console.error(`Unknown option: ${unknownFlags.join(", ")}
5064
+ `);
5065
+ console.log(CHECK_TRANSLATIONS_USAGE);
5066
+ process.exit(1);
5067
+ }
5068
+ const cwd = process.cwd();
5069
+ const { missing, outdated, dynamicIds } = check(cwd);
5070
+ for (const file of dynamicIds) {
5071
+ console.warn(
5072
+ `Warning: ${file} declares a message whose id is built at runtime. Ids have to be hardcoded to be checked.`
5073
+ );
5074
+ }
5075
+ if (checkArgs.includes("--outdated")) {
5076
+ console.log(
5077
+ `${outdated.length} row(s) in countryconfig.csv are not declared in src:
5078
+ `
5079
+ );
5080
+ console.log(outdated.join("\n"));
5081
+ return;
5082
+ }
5083
+ if (missing.length === 0) {
5084
+ console.log("Every message declared in src has a translation row.");
5085
+ return;
5086
+ }
5087
+ console.error(
5088
+ `${missing.length} message(s) declared in src have no row in src/translations/countryconfig.csv:
5089
+ `
5090
+ );
5091
+ console.error(missing.map(({ id }) => ` ${id}`).join("\n"));
5092
+ if (!checkArgs.includes("--write")) {
5093
+ console.error(
5094
+ "\nRun `pnpm extract:translations --write` to add them with their English copy."
5095
+ );
5096
+ process.exit(1);
5097
+ }
5098
+ const added = writeMissing(cwd, missing);
5099
+ console.log(`
5100
+ Added ${added.length} row(s) to countryconfig.csv.`);
5101
+ console.log("The languages other than English are still yours to write.");
5102
+ }
5103
+ async function handleVerifyEndpoints() {
5104
+ const verifyArgs = args.slice(1);
5105
+ if (verifyArgs.includes("--help") || verifyArgs.includes("-h")) {
5106
+ console.log(VERIFY_ENDPOINTS_USAGE);
5107
+ process.exit(0);
5108
+ }
5109
+ const positional = verifyArgs.filter((arg) => !arg.startsWith("-"));
5110
+ if (positional.length > 1) {
5111
+ console.error(
5112
+ `Unexpected extra argument(s): ${positional.slice(1).join(", ")}
5113
+ `
5114
+ );
5115
+ console.log(VERIFY_ENDPOINTS_USAGE);
5116
+ process.exit(1);
5117
+ }
5118
+ try {
5119
+ await runVerifyEndpoints(positional[0]);
5120
+ } catch (error3) {
5121
+ console.error(
5122
+ "Endpoint verification failed:",
5123
+ error3 instanceof Error ? error3.message : error3
5124
+ );
5125
+ process.exit(1);
5126
+ }
3460
5127
  }
3461
- main2();
5128
+ main5();