@opencrvs/toolkit 2.1.0-rc.05eb1de → 2.1.0-rc.06c6f7a

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 (127) 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 +343 -275
  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 +1890 -271
  11. package/dist/commons/api/router.d.ts +3925 -3327
  12. package/dist/commons/application-config/index.d.ts +6 -6
  13. package/dist/commons/conditionals/conditionals.d.ts +259 -2102
  14. package/dist/commons/conditionals/validate.d.ts +16 -5
  15. package/dist/commons/events/ActionConfig.d.ts +112 -105
  16. package/dist/commons/events/ActionDocument.d.ts +121 -127
  17. package/dist/commons/events/ActionInput.d.ts +4 -10
  18. package/dist/commons/events/ActionStatus.d.ts +14 -0
  19. package/dist/commons/events/ActionType.d.ts +62 -62
  20. package/dist/commons/events/AdvancedSearchConfig.d.ts +531 -507
  21. package/dist/commons/events/AuditLog.d.ts +189 -42
  22. package/dist/commons/events/CompositeFieldValue.d.ts +4 -4
  23. package/dist/commons/events/Conditional.d.ts +3 -3
  24. package/dist/commons/events/CountryConfigQueryInput.d.ts +590 -590
  25. package/dist/commons/events/Draft.d.ts +37 -37
  26. package/dist/commons/events/DynamicFieldValue.d.ts +9 -9
  27. package/dist/commons/events/EventConfig.d.ts +8 -5
  28. package/dist/commons/events/EventDocument.d.ts +518 -50
  29. package/dist/commons/events/EventIndex.d.ts +49 -72
  30. package/dist/commons/events/EventMetadata.d.ts +39 -49
  31. package/dist/commons/events/EventStatus.d.ts +19 -0
  32. package/dist/commons/events/FieldConfig.d.ts +424 -389
  33. package/dist/commons/events/FieldType.d.ts +51 -51
  34. package/dist/commons/events/FieldTypeMapping.d.ts +86 -86
  35. package/dist/commons/events/FieldValue.d.ts +14 -14
  36. package/dist/commons/events/Flag.d.ts +57 -15
  37. package/dist/commons/events/PlainDate.d.ts +8 -0
  38. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  39. package/dist/commons/events/TemplateConfig.d.ts +1 -1
  40. package/dist/commons/events/WorkqueueColumnConfig.d.ts +40 -40
  41. package/dist/commons/events/WorkqueueConfig.d.ts +817 -814
  42. package/dist/commons/events/deduplication.d.ts +1 -1
  43. package/dist/commons/events/event.d.ts +14 -2
  44. package/dist/commons/events/field.d.ts +78 -895
  45. package/dist/commons/events/index.d.ts +1 -0
  46. package/dist/commons/events/locationPayloads.d.ts +95 -0
  47. package/dist/commons/events/locations.d.ts +247 -14
  48. package/dist/commons/events/mocks.test.utils.d.ts +48 -4
  49. package/dist/commons/events/scopes.d.ts +4 -4
  50. package/dist/commons/events/state/index.d.ts +17 -17
  51. package/dist/commons/events/state/utils.d.ts +7 -7
  52. package/dist/commons/events/test.utils.d.ts +64 -46
  53. package/dist/commons/events/utils.d.ts +133 -114
  54. package/dist/commons/notification/UserNotifications.d.ts +38 -23
  55. package/dist/commons/notification/dispatch.d.ts +10 -0
  56. package/dist/commons/notification/index.d.ts +1 -0
  57. package/dist/conditionals/index.js +328 -58
  58. package/dist/csv.d.ts +25 -0
  59. package/dist/csv.d.ts.map +1 -0
  60. package/dist/csv.js +120 -0
  61. package/dist/environment/derived-variables.d.ts +119 -131
  62. package/dist/environment/derived-variables.d.ts.map +1 -1
  63. package/dist/environment/derived-variables.js +0 -14
  64. package/dist/environment/index.d.ts +1 -0
  65. package/dist/environment/index.d.ts.map +1 -1
  66. package/dist/environment/index.js +10 -0
  67. package/dist/environment/logger.d.ts +15 -3
  68. package/dist/environment/logger.d.ts.map +1 -1
  69. package/dist/environment/paths.d.ts +7 -0
  70. package/dist/environment/paths.d.ts.map +1 -0
  71. package/dist/environment/paths.js +72 -0
  72. package/dist/environment/questions.d.ts +75 -74
  73. package/dist/environment/questions.d.ts.map +1 -1
  74. package/dist/environment/questions.js +20 -14
  75. package/dist/environment/setup-environment.js +36 -35
  76. package/dist/environment/templates.d.ts.map +1 -1
  77. package/dist/environment/templates.js +2 -1
  78. package/dist/environment/update-workflows.d.ts.map +1 -1
  79. package/dist/environment/update-workflows.js +17 -5
  80. package/dist/environment/upgrade.d.ts +2 -0
  81. package/dist/environment/upgrade.d.ts.map +1 -0
  82. package/dist/environment/upgrade.js +82 -0
  83. package/dist/environment/users.js +11 -13
  84. package/dist/environment/utils.d.ts +1 -1
  85. package/dist/events/deduplication.d.ts +1 -1
  86. package/dist/events/index.js +7617 -7112
  87. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
  88. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  89. package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
  90. package/dist/migrations/v2.0/migrate-application-config-url.js +4 -3
  91. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  92. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  93. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  94. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  95. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  96. package/dist/migrations/v2.1/add-translations.js +213 -0
  97. package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
  98. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  99. package/dist/migrations/v2.1/enable-telemetry.js +438 -0
  100. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  101. package/dist/migrations/v2.1/index.js +1058 -0
  102. package/dist/notification/index.js +1867 -1465
  103. package/dist/scopes/index.d.ts +464 -169
  104. package/dist/scopes/index.js +329 -58
  105. package/dist/telemetry/index.d.ts +45 -0
  106. package/dist/telemetry/index.d.ts.map +1 -0
  107. package/dist/telemetry/index.js +39 -0
  108. package/dist/templates/charts-values/dependencies/values.yaml +2 -3
  109. package/dist/templates/charts-values/opencrvs-services/values.yaml +4 -7
  110. package/dist/templates/charts-values/opentelemetry/values.yaml +95 -0
  111. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  112. package/dist/templates/inventory/inventory.template.yml +1 -3
  113. package/dist/translations/check.d.ts +19 -0
  114. package/dist/translations/check.d.ts.map +1 -0
  115. package/dist/translations/check.js +127 -0
  116. package/dist/verify/endpoints.d.ts +2 -0
  117. package/dist/verify/endpoints.d.ts.map +1 -0
  118. package/dist/verify/endpoints.js +345 -0
  119. package/opencrvs-toolkit-2.1.0-rc.06c6f7a.tgz +0 -0
  120. package/package.json +12 -7
  121. package/tsconfig.build.json +11 -0
  122. package/tsconfig.build.tsbuildinfo +1 -0
  123. package/tsconfig.json +3 -0
  124. package/dist/templates/inventory/production.example.yml +0 -77
  125. package/dist/templates/inventory/qa.example.yml +0 -48
  126. package/opencrvs-toolkit-2.1.0-rc.05eb1de.tgz +0 -0
  127. 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({
@@ -380,20 +416,6 @@ var init_derived_variables = __esm({
380
416
  type: "disabled",
381
417
  scope: "ENVIRONMENT"
382
418
  },
383
- {
384
- name: "MONGODB_ADMIN_USER",
385
- valueLabel: "MONGODB_ADMIN_USER",
386
- valueType: "SECRET",
387
- type: "disabled",
388
- scope: "ENVIRONMENT"
389
- },
390
- {
391
- name: "MONGODB_ADMIN_PASSWORD",
392
- valueLabel: "MONGODB_ADMIN_PASSWORD",
393
- valueType: "SECRET",
394
- type: "disabled",
395
- scope: "ENVIRONMENT"
396
- },
397
419
  {
398
420
  name: "POSTGRES_USER",
399
421
  valueLabel: "POSTGRES_USER",
@@ -485,9 +507,9 @@ function storeSecrets(environment, answers) {
485
507
  let envConfig = {};
486
508
  try {
487
509
  envConfig = import_dotenv.default.parse(
488
- (0, import_fs.readFileSync)(`${process.cwd()}/.env.${environment}`)
510
+ (0, import_fs4.readFileSync)(`${process.cwd()}/.env.${environment}`)
489
511
  );
490
- } catch (error4) {
512
+ } catch (error3) {
491
513
  envConfig = {};
492
514
  }
493
515
  const linesFromAnswers = answers.map(
@@ -495,10 +517,10 @@ function storeSecrets(environment, answers) {
495
517
  );
496
518
  const linesFromEnvConfig = Object.entries(envConfig).filter(([name]) => !answers.find((update) => update.name === name)).map(([name, value]) => `${name}="${value}"`);
497
519
  const allLines = [...linesFromEnvConfig, ...linesFromAnswers].sort();
498
- (0, import_fs.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
520
+ (0, import_fs4.writeFileSync)(`.env.${environment}`, allLines.join("\n"));
499
521
  }
500
522
  function readYamlFile(filePath) {
501
- const fileContent = import_fs.default.readFileSync(filePath, "utf8");
523
+ const fileContent = import_fs4.default.readFileSync(filePath, "utf8");
502
524
  return yaml.load(fileContent);
503
525
  }
504
526
  function writeYamlFile(filePath, data) {
@@ -511,16 +533,16 @@ function writeYamlFile(filePath, data) {
511
533
  noRefs: true,
512
534
  sortKeys: false
513
535
  });
514
- import_fs.default.writeFileSync(filePath, yamlContent, "utf8");
515
- } catch (error4) {
516
- 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}`);
517
539
  }
518
540
  }
519
- var import_fs, yaml, import_dotenv;
541
+ var import_fs4, yaml, import_dotenv;
520
542
  var init_utils = __esm({
521
543
  "src/environment/utils.ts"() {
522
544
  "use strict";
523
- import_fs = __toESM(require("fs"));
545
+ import_fs4 = __toESM(require("fs"));
524
546
  yaml = __toESM(require("js-yaml"));
525
547
  import_dotenv = __toESM(require("dotenv"));
526
548
  }
@@ -573,29 +595,29 @@ function extractWorkerNodes(data) {
573
595
  return worker_hosts;
574
596
  }
575
597
  function copyChartsValues(env, values) {
576
- const srcDir = import_path2.default.resolve(__dirname, "templates", "charts-values");
577
- const destDir = import_path2.default.resolve(process.cwd(), "environments", env);
578
- 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 });
579
601
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
580
602
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
581
603
  values["opencrvs_environment"] = env;
582
604
  function copyRecursive(src, dest) {
583
- const stat = import_fs2.default.statSync(src);
605
+ const stat = import_fs5.default.statSync(src);
584
606
  if (stat.isDirectory()) {
585
- import_fs2.default.mkdirSync(dest, { recursive: true });
586
- for (const item of import_fs2.default.readdirSync(src)) {
587
- 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));
588
610
  }
589
611
  } else {
590
- const content = import_fs2.default.readFileSync(src, "utf8");
612
+ const content = import_fs5.default.readFileSync(src, "utf8");
591
613
  const template = import_handlebars.default.compile(content);
592
614
  const updated = template(values);
593
615
  const isOverridesFile = dest.endsWith("override.yaml");
594
- if (isOverridesFile && import_fs2.default.existsSync(dest)) {
616
+ if (isOverridesFile && import_fs5.default.existsSync(dest)) {
595
617
  log(` \u21B7 Skipped existing overrides file: ${dest}`);
596
618
  return;
597
619
  }
598
- import_fs2.default.writeFileSync(dest, updated, "utf8");
620
+ import_fs5.default.writeFileSync(dest, updated, "utf8");
599
621
  log(` \u2713 Created: ${dest}`);
600
622
  }
601
623
  }
@@ -606,36 +628,31 @@ function copyChartsValues(env, values) {
606
628
  `);
607
629
  }
608
630
  function generateInventory(env, values) {
609
- const templatePath = import_path2.default.join(
631
+ const templatePath = import_path7.default.join(
610
632
  __dirname,
611
633
  "templates",
612
634
  "inventory",
613
635
  "inventory.template.yml"
614
636
  );
615
- const outputPath = import_path2.default.join(
616
- process.cwd(),
617
- "infrastructure",
618
- "server-setup",
619
- "inventory",
620
- `${env}.yml`
621
- );
622
- 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");
623
639
  const template = import_handlebars.default.compile(templateFile);
624
640
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
625
641
  const updated = template(values);
626
- import_fs2.default.mkdirSync(import_path2.default.dirname(outputPath), { recursive: true });
627
- 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);
628
644
  log(`
629
645
  \u2705 Generated inventory file at ${outputPath}
630
646
  `);
631
647
  }
632
- var import_fs2, import_path2, import_handlebars;
648
+ var import_fs5, import_path7, import_handlebars;
633
649
  var init_templates = __esm({
634
650
  "src/environment/templates.ts"() {
635
651
  "use strict";
636
- import_fs2 = __toESM(require("fs"));
637
- import_path2 = __toESM(require("path"));
652
+ import_fs5 = __toESM(require("fs"));
653
+ import_path7 = __toESM(require("path"));
638
654
  init_logger();
655
+ init_paths();
639
656
  import_handlebars = __toESM(require("handlebars"));
640
657
  import_handlebars.default.registerHelper("data_label_idx", function(value) {
641
658
  return parseInt(value) + 2;
@@ -689,18 +706,18 @@ var init_git = __esm({
689
706
  });
690
707
 
691
708
  // src/environment/questions.ts
692
- function validateCIDR(input3) {
693
- if (!input3.trim()) {
709
+ function validateCIDR(input4) {
710
+ if (!input4.trim()) {
694
711
  return true;
695
712
  }
696
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])$/;
697
- 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)";
698
715
  }
699
- function validateCIDRs(input3) {
700
- if (!input3.trim()) {
716
+ function validateCIDRs(input4) {
717
+ if (!input4.trim()) {
701
718
  return true;
702
719
  }
703
- const cidrs = input3.split(",").map((v) => v.trim());
720
+ const cidrs = input4.split(",").map((v) => v.trim());
704
721
  for (const cidr of cidrs) {
705
722
  const result = validateCIDR(cidr);
706
723
  if (result !== true) {
@@ -843,11 +860,28 @@ var init_questions = __esm({
843
860
  scope: "ENVIRONMENT"
844
861
  },
845
862
  {
846
- name: "kubeAPIHost",
863
+ name: "kubeMasterNode",
864
+ type: "text",
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",
847
882
  type: "text",
848
- message: `Kubernetes API endpoint (default: auto-detect)`,
883
+ message: `Kubernetes API endpoint IP (default: KUBE_MASTER_NODE)`,
849
884
  valueType: "VARIABLE",
850
- // validate: notEmpty,
851
885
  valueLabel: "KUBE_API_HOST",
852
886
  initial: process.env.KUBE_API_HOST,
853
887
  scope: "ENVIRONMENT"
@@ -861,16 +895,6 @@ var init_questions = __esm({
861
895
  valueLabel: "KUBE_API_ALLOWED_CIDRS",
862
896
  initial: process.env.KUBE_API_ALLOWED_CIDRS || "",
863
897
  scope: "ENVIRONMENT"
864
- },
865
- {
866
- name: "kubeWorkerNodes",
867
- type: "text",
868
- message: `Kubernetes worker node hostnames or IPs (comma-separated, default: no worker nodes)`,
869
- valueType: "VARIABLE",
870
- // validate: notEmpty,
871
- valueLabel: "KUBE_WORKER_NODES",
872
- initial: process.env.KUBE_WORKER_NODES || "",
873
- scope: "ENVIRONMENT"
874
898
  }
875
899
  ];
876
900
  staticSSLCertQuestions = [
@@ -901,7 +925,6 @@ var init_questions = __esm({
901
925
  type: "text",
902
926
  message: `Please enter backup server host/IP address, (default: no backup):`,
903
927
  valueType: "VARIABLE",
904
- // validate: notEmpty,
905
928
  valueLabel: "BACKUP_HOST",
906
929
  initial: process.env.BACKUP_HOST || "",
907
930
  scope: "ENVIRONMENT"
@@ -1234,7 +1257,7 @@ function getCurrentUsername() {
1234
1257
  }
1235
1258
  function getCurrentUserSSHKeys() {
1236
1259
  const homeDir = os.homedir();
1237
- const sshDir = path3.join(homeDir, ".ssh");
1260
+ const sshDir = path7.join(homeDir, ".ssh");
1238
1261
  const keys = [];
1239
1262
  const keyFiles = [
1240
1263
  "id_rsa.pub",
@@ -1243,7 +1266,7 @@ function getCurrentUserSSHKeys() {
1243
1266
  "id_dsa.pub"
1244
1267
  ];
1245
1268
  for (const keyFile of keyFiles) {
1246
- const keyPath = path3.join(sshDir, keyFile);
1269
+ const keyPath = path7.join(sshDir, keyFile);
1247
1270
  try {
1248
1271
  if (fs3.existsSync(keyPath)) {
1249
1272
  const keyContent = fs3.readFileSync(keyPath, "utf8").trim();
@@ -1251,7 +1274,7 @@ function getCurrentUserSSHKeys() {
1251
1274
  keys.push(keyContent);
1252
1275
  }
1253
1276
  }
1254
- } catch (error4) {
1277
+ } catch (error3) {
1255
1278
  continue;
1256
1279
  }
1257
1280
  }
@@ -1584,13 +1607,13 @@ async function manageUsers(inventoryPath) {
1584
1607
  }
1585
1608
  return users;
1586
1609
  }
1587
- var os, fs3, path3, input2, select2, confirm, editor, checkbox;
1610
+ var os, fs3, path7, input2, select2, confirm, editor, checkbox;
1588
1611
  var init_manage_users = __esm({
1589
1612
  "src/environment/manage-users.ts"() {
1590
1613
  "use strict";
1591
1614
  os = __toESM(require("os"));
1592
1615
  fs3 = __toESM(require("fs"));
1593
- path3 = __toESM(require("path"));
1616
+ path7 = __toESM(require("path"));
1594
1617
  init_logger();
1595
1618
  init_utils();
1596
1619
  init_templates();
@@ -1612,6 +1635,10 @@ async function select3(options) {
1612
1635
  const inquirer = await import("@inquirer/prompts");
1613
1636
  return inquirer.select(options);
1614
1637
  }
1638
+ async function input3(options) {
1639
+ const inquirer = await import("@inquirer/prompts");
1640
+ return inquirer.input(options);
1641
+ }
1615
1642
  function questionToPrompt({
1616
1643
  valueType,
1617
1644
  valueLabel,
@@ -1787,6 +1814,7 @@ var init_setup_environment = __esm({
1787
1814
  init_editor_questions();
1788
1815
  init_questions_helper();
1789
1816
  init_manage_users();
1817
+ init_paths();
1790
1818
  ALL_QUESTIONS = [];
1791
1819
  ALL_ANSWERS = [];
1792
1820
  ALL_QUESTIONS.push(
@@ -1950,9 +1978,7 @@ var init_setup_environment = __esm({
1950
1978
  );
1951
1979
  const kubeWorkerNodes = infrastructure.kubeWorkerNodes ? infrastructure.kubeWorkerNodes.split(",").map((ip) => ip.trim()) : [];
1952
1980
  log("\n", import_kleur4.default.bold().underline("SSH Users"), "\n");
1953
- const users = await manageUsers(
1954
- `infrastructure/server-setup/inventory/${environment}.yml`
1955
- );
1981
+ const users = await manageUsers(getEnvironmentInventoryPath(environment));
1956
1982
  log("\n", import_kleur4.default.bold().underline("Traefik SSL Certificate"), "\n");
1957
1983
  const sslCertExists = findExistingValue(
1958
1984
  "SSL_CRT",
@@ -2044,6 +2070,7 @@ var init_setup_environment = __esm({
2044
2070
  "ENVIRONMENT",
2045
2071
  existingValues
2046
2072
  )?.value;
2073
+ let restoreHost = findExistingValue("RESTORE_HOST", "VARIABLE", "ENVIRONMENT", existingValues)?.value || "";
2047
2074
  let restoreType = findExistingValue(
2048
2075
  "RESTORE_ENVIRONMENT_MODE",
2049
2076
  "VARIABLE",
@@ -2119,6 +2146,10 @@ var init_setup_environment = __esm({
2119
2146
  }
2120
2147
  ]
2121
2148
  });
2149
+ restoreHost = await input3({
2150
+ message: "What is the host/IP address of the restore backup server?",
2151
+ default: restoreHost
2152
+ });
2122
2153
  } else {
2123
2154
  log(import_kleur4.default.bold().green("\u2714"), import_kleur4.default.bold().yellow("Restore is disabled"));
2124
2155
  }
@@ -2290,40 +2321,6 @@ var init_setup_environment = __esm({
2290
2321
  ),
2291
2322
  scope: "ENVIRONMENT"
2292
2323
  },
2293
- {
2294
- name: "MONGODB_ADMIN_USER",
2295
- type: "SECRET",
2296
- didExist: findExistingValue(
2297
- "MONGODB_ADMIN_USER",
2298
- "SECRET",
2299
- "ENVIRONMENT",
2300
- existingValues
2301
- ),
2302
- value: findExistingOrDefine(
2303
- "MONGODB_ADMIN_USER",
2304
- "SECRET",
2305
- "ENVIRONMENT",
2306
- generateLongPassword()
2307
- ),
2308
- scope: "ENVIRONMENT"
2309
- },
2310
- {
2311
- name: "MONGODB_ADMIN_PASSWORD",
2312
- type: "SECRET",
2313
- didExist: findExistingValue(
2314
- "MONGODB_ADMIN_PASSWORD",
2315
- "SECRET",
2316
- "ENVIRONMENT",
2317
- existingValues
2318
- ),
2319
- value: findExistingOrDefine(
2320
- "MONGODB_ADMIN_PASSWORD",
2321
- "SECRET",
2322
- "ENVIRONMENT",
2323
- generateLongPassword()
2324
- ),
2325
- scope: "ENVIRONMENT"
2326
- },
2327
2324
  {
2328
2325
  name: "POSTGRES_USER",
2329
2326
  type: "SECRET",
@@ -2487,6 +2484,22 @@ var init_setup_environment = __esm({
2487
2484
  existingValues
2488
2485
  ),
2489
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"
2490
2503
  }
2491
2504
  ];
2492
2505
  if (enableEncryption) {
@@ -2738,7 +2751,7 @@ var init_setup_environment = __esm({
2738
2751
  log("\n", import_kleur4.default.bold().underline("Running configuration files updates"));
2739
2752
  generateInventory(environment, {
2740
2753
  kube_worker_nodes: kubeWorkerNodes,
2741
- kube_api_host: infrastructure.kubeAPIHost || "",
2754
+ kube_api_host: infrastructure.kubeApiHost || "",
2742
2755
  backup_host: backupHost || "",
2743
2756
  users
2744
2757
  });
@@ -2749,12 +2762,14 @@ var init_setup_environment = __esm({
2749
2762
  // Hardcode like this blocks us from being generic:
2750
2763
  // https://github.com/opencrvs/opencrvs-core/issues/11171
2751
2764
  two_fa_enabled: environment !== "production" ? false : true,
2752
- backup_enabled: configureBackup ? true : false,
2765
+ traefik_mode: traefikConfOption,
2753
2766
  restore_enabled: restoreEnvironmentName ? true : false,
2754
2767
  restore_environment_name: restoreEnvironmentName || "",
2755
2768
  restore_type: restoreType,
2756
- traefik_mode: traefikConfOption,
2757
- backup_type: backupType
2769
+ restore_host: restoreHost || "",
2770
+ backup_enabled: configureBackup ? true : false,
2771
+ backup_type: backupType,
2772
+ backup_host: backupHost || ""
2758
2773
  });
2759
2774
  let addon_message = kubeWorkerNodes.length > 0 || configureBackup ? `--------------------------------------------------------------------------------------------
2760
2775
 
@@ -2799,12 +2814,19 @@ var update_workflows_exports = {};
2799
2814
  __export(update_workflows_exports, {
2800
2815
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
2801
2816
  });
2817
+ function isDirectory(path10) {
2818
+ try {
2819
+ return (0, import_fs6.statSync)(path10).isDirectory();
2820
+ } catch {
2821
+ return false;
2822
+ }
2823
+ }
2802
2824
  async function extractInfrastructureNames() {
2803
- const files = glob.sync("infrastructure/server-setup/inventory/*.yml");
2804
- 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)));
2805
2827
  if (infraEnvironments.length === 0) {
2806
2828
  console.log(
2807
- "\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}`
2808
2830
  );
2809
2831
  return [];
2810
2832
  }
@@ -2814,8 +2836,9 @@ async function extractInfrastructureNames() {
2814
2836
  async function extractEnvironmentNames() {
2815
2837
  const entries = await (0, import_promises.readdir)("environments");
2816
2838
  const environments = entries.filter((entry) => {
2817
- const fullPath = (0, import_path3.join)("environments", entry);
2818
- 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);
2819
2842
  });
2820
2843
  if (environments.length === 0) {
2821
2844
  console.log(
@@ -2841,7 +2864,7 @@ async function updateWorkflows(envList, config) {
2841
2864
  const { workflows } = config;
2842
2865
  for (const workflowPath of workflows) {
2843
2866
  try {
2844
- const fileContents = (0, import_fs3.readFileSync)(workflowPath, "utf8");
2867
+ const fileContents = (0, import_fs6.readFileSync)(workflowPath, "utf8");
2845
2868
  const workflowData = yaml2.load(fileContents);
2846
2869
  if (!workflowData?.on?.workflow_dispatch?.inputs?.environment?.options) {
2847
2870
  throw new Error(
@@ -2849,15 +2872,15 @@ async function updateWorkflows(envList, config) {
2849
2872
  );
2850
2873
  }
2851
2874
  const updatedContent = updateOptionsInYaml(fileContents, envList);
2852
- (0, import_fs3.writeFileSync)(workflowPath, updatedContent, "utf8");
2875
+ (0, import_fs6.writeFileSync)(workflowPath, updatedContent, "utf8");
2853
2876
  log(` \u2713 Successfully updated ${workflowPath}`);
2854
- } catch (error4) {
2877
+ } catch (error3) {
2855
2878
  console.error(
2856
2879
  `
2857
2880
  \u26A0\uFE0F Error updating ${workflowPath} with environments: [${envList.join(", ")}]`
2858
2881
  );
2859
- console.error(`\u2717 Failed to update ${workflowPath}:`, error4);
2860
- throw error4;
2882
+ console.error(`\u2717 Failed to update ${workflowPath}:`, error3);
2883
+ throw error3;
2861
2884
  }
2862
2885
  }
2863
2886
  }
@@ -2898,21 +2921,90 @@ async function updateWorkflowEnvironments() {
2898
2921
  } else {
2899
2922
  log("\u2139\uFE0F No workflows were updated.");
2900
2923
  }
2901
- } catch (error4) {
2902
- console.error("\n\u274C Error updating workflows:", error4);
2924
+ } catch (error3) {
2925
+ console.error("\n\u274C Error updating workflows:", error3);
2903
2926
  process.exit(1);
2904
2927
  }
2905
2928
  }
2906
- var import_promises, import_fs3, import_path3, glob, yaml2;
2929
+ var import_promises, import_fs6, import_path8, glob2, yaml2;
2907
2930
  var init_update_workflows = __esm({
2908
2931
  "src/environment/update-workflows.ts"() {
2909
2932
  "use strict";
2910
2933
  import_promises = require("fs/promises");
2911
- import_fs3 = require("fs");
2912
- import_path3 = require("path");
2913
- glob = __toESM(require("glob"));
2934
+ import_fs6 = require("fs");
2935
+ import_path8 = require("path");
2936
+ glob2 = __toESM(require("glob"));
2914
2937
  yaml2 = __toESM(require("js-yaml"));
2915
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();
2916
3008
  }
2917
3009
  });
2918
3010
 
@@ -2925,7 +3017,7 @@ async function select4(options) {
2925
3017
  const inquirer = await import("@inquirer/prompts");
2926
3018
  return inquirer.select(options);
2927
3019
  }
2928
- async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inventory/") {
3020
+ async function selectInventoryFile(dirPath = "./environments") {
2929
3021
  if (!fs4.existsSync(dirPath)) {
2930
3022
  warn(`\u26A0\uFE0F No environment configuration directory found at ${dirPath}`);
2931
3023
  warn(
@@ -2933,22 +3025,20 @@ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inve
2933
3025
  );
2934
3026
  return null;
2935
3027
  }
2936
- const files = fs4.readdirSync(dirPath).filter((file) => {
2937
- const filePath = path4.join(dirPath, file);
2938
- const isFile = fs4.statSync(filePath).isFile();
2939
- const ext = path4.extname(file).slice(1).toLowerCase();
2940
- 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));
2941
3031
  }).sort();
2942
- if (files.length === 0) {
3032
+ if (environments.length === 0) {
2943
3033
  warn(`\u26A0\uFE0F No environment configuration files found at ${dirPath}`);
2944
3034
  warn(
2945
3035
  "Hint: If this is a new infrastructure repository, run `opencrvs environment init` first."
2946
3036
  );
2947
3037
  return null;
2948
3038
  }
2949
- const choices = files.map((file) => ({
2950
- name: path4.basename(file, path4.extname(file)),
2951
- value: path4.join(dirPath, file)
3039
+ const choices = environments.map((environment) => ({
3040
+ name: environment,
3041
+ value: getEnvironmentInventoryPath(environment)
2952
3042
  }));
2953
3043
  const selectedFile = await select4({
2954
3044
  message: "Select environment (inventory file) to load users:",
@@ -2957,33 +3047,34 @@ async function selectInventoryFile(dirPath = "./infrastructure/server-setup/inve
2957
3047
  return selectedFile;
2958
3048
  }
2959
3049
  async function manageEnvironmentUsers() {
2960
- console.log("\n", import_kleur5.default.bold().underline("Manage users"), "\n");
3050
+ console.log("\n", import_kleur6.default.bold().underline("Manage users"), "\n");
2961
3051
  const inventory_file = await selectInventoryFile();
2962
3052
  if (!inventory_file) {
2963
3053
  return;
2964
3054
  }
2965
3055
  await manageUsers(inventory_file);
2966
3056
  }
2967
- var fs4, path4, import_kleur5;
3057
+ var fs4, path8, import_kleur6;
2968
3058
  var init_users = __esm({
2969
3059
  "src/environment/users.ts"() {
2970
3060
  "use strict";
2971
3061
  fs4 = __toESM(require("fs"));
2972
- path4 = __toESM(require("path"));
2973
- import_kleur5 = __toESM(require("kleur"));
3062
+ path8 = __toESM(require("path"));
3063
+ import_kleur6 = __toESM(require("kleur"));
2974
3064
  init_manage_users();
2975
3065
  init_logger();
3066
+ init_paths();
2976
3067
  }
2977
3068
  });
2978
3069
 
2979
3070
  // src/environment/swarm-to-k8s.ts
2980
3071
  var swarm_to_k8s_exports = {};
2981
- var path5, import_kleur6, import_core2;
3072
+ var path9, import_kleur7, import_core2;
2982
3073
  var init_swarm_to_k8s = __esm({
2983
3074
  "src/environment/swarm-to-k8s.ts"() {
2984
3075
  "use strict";
2985
- path5 = __toESM(require("path"));
2986
- import_kleur6 = __toESM(require("kleur"));
3076
+ path9 = __toESM(require("path"));
3077
+ import_kleur7 = __toESM(require("kleur"));
2987
3078
  init_logger();
2988
3079
  init_utils();
2989
3080
  init_templates();
@@ -2992,7 +3083,7 @@ var init_swarm_to_k8s = __esm({
2992
3083
  init_github();
2993
3084
  (async () => {
2994
3085
  log(
2995
- import_kleur6.default.bold(
3086
+ import_kleur7.default.bold(
2996
3087
  "------------------------------------------------\nOpenCRVS Infrastructure migration script: \nMigrating Swarm configurations to Kubernetes\n------------------------------------------------\n"
2997
3088
  )
2998
3089
  );
@@ -3023,7 +3114,7 @@ var init_swarm_to_k8s = __esm({
3023
3114
  );
3024
3115
  process.exit(0);
3025
3116
  }
3026
- log(import_kleur6.default.bold().underline("Migration properties:"));
3117
+ log(import_kleur7.default.bold().underline("Migration properties:"));
3027
3118
  log(` \u2713 Environment: ${environment}`);
3028
3119
  const old_inventory_path = process.env.OLD_INVENTORY_PATH || "";
3029
3120
  if (!old_inventory_path) {
@@ -3034,7 +3125,7 @@ var init_swarm_to_k8s = __esm({
3034
3125
  );
3035
3126
  process.exit(1);
3036
3127
  }
3037
- const ansible_inventory = path5.join(old_inventory_path, environment + ".yml");
3128
+ const ansible_inventory = path9.join(old_inventory_path, environment + ".yml");
3038
3129
  const data = readYamlFile(ansible_inventory);
3039
3130
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3040
3131
  const master = dockerManagerFirst(data) || "";
@@ -3335,142 +3426,1589 @@ Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.l
3335
3426
  );
3336
3427
  }
3337
3428
 
3338
- // src/migrations/v2.1/index.ts
3339
- async function runUpgrade(dockerSwarm) {
3340
- await main();
3341
- }
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"));
3342
3433
 
3343
- // src/environment/index.ts
3344
- var import_fs4 = require("fs");
3345
- var import_path4 = require("path");
3346
- var REQUIRED_REPOSITORY_DIRECTORIES = [
3347
- ".github/workflows",
3348
- "environments",
3349
- "infrastructure"
3350
- ];
3351
- function validateRepositoryStructure(repositoryRoot = process.cwd()) {
3352
- const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
3353
- (directory) => {
3354
- try {
3355
- return !(0, import_fs4.statSync)((0, import_path4.resolve)(repositoryRoot, directory)).isDirectory();
3356
- } catch {
3357
- return true;
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;
3358
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;
3359
3460
  }
3360
- );
3361
- if (missingDirectories.length > 0) {
3362
- throw new Error(
3363
- `The current directory is not a valid OpenCRVS country configuration repository. Missing required director${missingDirectories.length === 1 ? "y" : "ies"}: ${missingDirectories.join(", ")}`
3364
- );
3365
3461
  }
3462
+ values.push(value);
3463
+ return values;
3366
3464
  }
3367
- async function runEnvironmentInit() {
3368
- validateRepositoryStructure();
3369
- await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
3465
+ function toCsvLine(values) {
3466
+ return values.map(
3467
+ (value) => /["\n,]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
3468
+ ).join(",");
3370
3469
  }
3371
- async function runEnvironmentUpdateWorkflows() {
3372
- validateRepositoryStructure();
3373
- const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
3374
- await updateWorkflowEnvironments2();
3470
+ function idOf(line2) {
3471
+ const comma = line2.indexOf(",");
3472
+ return comma === -1 ? line2 : line2.slice(0, comma);
3375
3473
  }
3376
- async function runEnvironmentUsers() {
3377
- validateRepositoryStructure();
3378
- const { manageEnvironmentUsers: manageEnvironmentUsers2 } = await Promise.resolve().then(() => (init_users(), users_exports));
3379
- await manageEnvironmentUsers2();
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 };
3380
3484
  }
3381
- async function runEnvironmentSwarmToK8s() {
3382
- validateRepositoryStructure();
3383
- await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
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
+ );
3384
3490
  }
3385
-
3386
- // src/cli.ts
3387
- var args = process.argv.slice(2);
3388
- var USAGE = `
3389
- Usage: opencrvs <command>
3390
-
3391
- Commands:
3392
- environment Manage deployment environments
3393
- upgrade Upgrade an existing environment
3394
- check-translations Check translation files for completeness
3395
-
3396
- Run 'opencrvs <command> --help' for more information on a command.
3397
- `.trim();
3398
- var UPGRADE_USAGE = `
3399
- Usage: opencrvs upgrade [options]
3400
-
3401
- Upgrade the country config in the current working directory to the next
3402
- major version of OpenCRVS.
3403
-
3404
- Options:
3405
- --docker-swarm Keep and merge the 'infrastructure/' directory with
3406
- upstream changes. Use this if your country deploys
3407
- OpenCRVS via Docker Swarm. When omitted, the
3408
- 'infrastructure/' directory is deleted (default).
3409
- -h, --help Show this message.
3410
- `.trim();
3411
- function main2() {
3412
- const command = args[0];
3413
- if (!command || command === "--help" || command === "-h") {
3414
- console.log(USAGE);
3415
- process.exit(0);
3416
- }
3417
- switch (command) {
3418
- case "environment":
3419
- return handleEnvironment();
3420
- case "upgrade":
3421
- return handleUpgrade();
3422
- case "check-translations":
3423
- return handleCheckTranslations();
3424
- default:
3425
- console.error(`Unknown command: ${command}
3426
- `);
3427
- console.log(USAGE);
3428
- process.exit(1);
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);
3429
3508
  }
3509
+ return added;
3430
3510
  }
3431
- async function handleEnvironment() {
3432
- const subcommand = args[1];
3433
- if (!subcommand || subcommand === "--help" || subcommand === "-h") {
3434
- console.log(
3435
- `
3436
- Usage: opencrvs environment <subcommand>
3437
3511
 
3438
- Subcommands:
3439
- init Initialise a new environment
3440
- update-workflows Update workflow environment options
3441
- users Manage environment users
3442
- swarm-to-k8s Migrate Docker Swarm configuration to Kubernetes
3443
- `.trim()
3444
- );
3445
- process.exit(0);
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"
3446
3546
  }
3447
- switch (subcommand) {
3448
- case "init":
3449
- return runEnvironmentCommand("initialisation", runEnvironmentInit);
3450
- case "update-workflows":
3451
- return runEnvironmentCommand(
3452
- "workflow update",
3453
- runEnvironmentUpdateWorkflows
3454
- );
3455
- case "users":
3456
- return runEnvironmentCommand("user management", runEnvironmentUsers);
3457
- case "swarm-to-k8s":
3458
- return runEnvironmentCommand(
3459
- "Swarm to Kubernetes migration",
3460
- runEnvironmentSwarmToK8s
3461
- );
3462
- default:
3463
- console.error(`Unknown subcommand: environment ${subcommand}`);
3464
- process.exit(1);
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
+
4484
+ // src/migrations/v2.1/index.ts
4485
+ async function runUpgrade(dockerSwarm) {
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;
4573
+ }
4574
+
4575
+ // src/environment/index.ts
4576
+ var import_fs8 = require("fs");
4577
+ var import_path10 = require("path");
4578
+ init_paths();
4579
+ var REQUIRED_REPOSITORY_DIRECTORIES = [
4580
+ ".github/workflows",
4581
+ "environments",
4582
+ "infrastructure"
4583
+ ];
4584
+ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
4585
+ const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
4586
+ (directory) => {
4587
+ try {
4588
+ return !(0, import_fs8.statSync)((0, import_path10.resolve)(repositoryRoot, directory)).isDirectory();
4589
+ } catch {
4590
+ return true;
4591
+ }
4592
+ }
4593
+ );
4594
+ if (missingDirectories.length > 0) {
4595
+ throw new Error(
4596
+ `The current directory is not a valid OpenCRVS country configuration repository. Missing required director${missingDirectories.length === 1 ? "y" : "ies"}: ${missingDirectories.join(", ")}`
4597
+ );
4598
+ }
4599
+ }
4600
+ async function runEnvironmentInit() {
4601
+ validateRepositoryStructure();
4602
+ assertNoOldInventoryLayout();
4603
+ await Promise.resolve().then(() => (init_setup_environment(), setup_environment_exports));
4604
+ }
4605
+ async function runEnvironmentUpgrade() {
4606
+ validateRepositoryStructure();
4607
+ const { upgradeEnvironmentLayout: upgradeEnvironmentLayout2 } = await Promise.resolve().then(() => (init_upgrade(), upgrade_exports));
4608
+ await upgradeEnvironmentLayout2();
4609
+ }
4610
+ async function runEnvironmentUpdateWorkflows() {
4611
+ validateRepositoryStructure();
4612
+ const { updateWorkflowEnvironments: updateWorkflowEnvironments2 } = await Promise.resolve().then(() => (init_update_workflows(), update_workflows_exports));
4613
+ await updateWorkflowEnvironments2();
4614
+ }
4615
+ async function runEnvironmentUsers() {
4616
+ validateRepositoryStructure();
4617
+ const { manageEnvironmentUsers: manageEnvironmentUsers2 } = await Promise.resolve().then(() => (init_users(), users_exports));
4618
+ await manageEnvironmentUsers2();
4619
+ }
4620
+ async function runEnvironmentSwarmToK8s() {
4621
+ validateRepositoryStructure();
4622
+ await Promise.resolve().then(() => (init_swarm_to_k8s(), swarm_to_k8s_exports));
4623
+ }
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
+
4897
+ // src/cli.ts
4898
+ var args = process.argv.slice(2);
4899
+ var USAGE = `
4900
+ Usage: opencrvs <command>
4901
+
4902
+ Commands:
4903
+ environment Manage deployment environments
4904
+ upgrade Upgrade an existing environment
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
4908
+
4909
+ Run 'opencrvs <command> --help' for more information on a command.
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();
4931
+ var UPGRADE_USAGE = `
4932
+ Usage: opencrvs upgrade [options]
4933
+
4934
+ Upgrade the country config in the current working directory to the next
4935
+ major version of OpenCRVS.
4936
+
4937
+ Options:
4938
+ --docker-swarm Keep and merge the 'infrastructure/' directory with
4939
+ upstream changes. Use this if your country deploys
4940
+ OpenCRVS via Docker Swarm. When omitted, the
4941
+ 'infrastructure/' directory is deleted (default).
4942
+ -h, --help Show this message.
4943
+ `.trim();
4944
+ function main5() {
4945
+ const command = args[0];
4946
+ if (!command || command === "--help" || command === "-h") {
4947
+ console.log(USAGE);
4948
+ process.exit(0);
4949
+ }
4950
+ switch (command) {
4951
+ case "environment":
4952
+ return handleEnvironment();
4953
+ case "upgrade":
4954
+ return handleUpgrade();
4955
+ case "check-translations":
4956
+ return handleCheckTranslations();
4957
+ case "verify-endpoints":
4958
+ return handleVerifyEndpoints();
4959
+ default:
4960
+ console.error(`Unknown command: ${command}
4961
+ `);
4962
+ console.log(USAGE);
4963
+ process.exit(1);
4964
+ }
4965
+ }
4966
+ async function handleEnvironment() {
4967
+ const subcommand = args[1];
4968
+ if (!subcommand || subcommand === "--help" || subcommand === "-h") {
4969
+ console.log(
4970
+ `
4971
+ Usage: opencrvs environment <subcommand>
4972
+
4973
+ Subcommands:
4974
+ init Initialise a new environment
4975
+ upgrade Upgrade existing environment configuration
4976
+ update-workflows Update workflow environment options
4977
+ users Manage environment users
4978
+ swarm-to-k8s Migrate Docker Swarm configuration to Kubernetes
4979
+ `.trim()
4980
+ );
4981
+ process.exit(0);
4982
+ }
4983
+ switch (subcommand) {
4984
+ case "init":
4985
+ return runEnvironmentCommand("initialisation", runEnvironmentInit);
4986
+ case "upgrade":
4987
+ return runEnvironmentCommand("environment upgrade", runEnvironmentUpgrade);
4988
+ case "update-workflows":
4989
+ return runEnvironmentCommand(
4990
+ "workflow update",
4991
+ runEnvironmentUpdateWorkflows
4992
+ );
4993
+ case "users":
4994
+ return runEnvironmentCommand("user management", runEnvironmentUsers);
4995
+ case "swarm-to-k8s":
4996
+ return runEnvironmentCommand(
4997
+ "Swarm to Kubernetes migration",
4998
+ runEnvironmentSwarmToK8s
4999
+ );
5000
+ default:
5001
+ console.error(`Unknown subcommand: environment ${subcommand}`);
5002
+ process.exit(1);
3465
5003
  }
3466
5004
  }
3467
5005
  async function runEnvironmentCommand(operation, command) {
3468
5006
  try {
3469
5007
  await command();
3470
- } catch (error4) {
5008
+ } catch (error3) {
3471
5009
  console.error(
3472
5010
  `Environment ${operation} failed:`,
3473
- error4 instanceof Error ? error4.message : error4
5011
+ error3 instanceof Error ? error3.message : error3
3474
5012
  );
3475
5013
  process.exit(1);
3476
5014
  }
@@ -3496,14 +5034,95 @@ async function handleUpgrade() {
3496
5034
  try {
3497
5035
  await runUpgrade(dockerSwarm);
3498
5036
  console.log("Upgrade completed successfully!");
3499
- } catch (error4) {
3500
- console.error("Upgrade failed:", error4);
5037
+ } catch (error3) {
5038
+ console.error("Upgrade failed:", error3);
3501
5039
  process.exit(1);
3502
5040
  }
3503
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
+ `;
3504
5053
  function handleCheckTranslations() {
3505
- console.log("Checking translations...");
3506
- console.warn("This command is not implemented yet!");
3507
- 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
+ }
3508
5127
  }
3509
- main2();
5128
+ main5();