@opencrvs/toolkit 2.2.0-rc.30529dd → 2.2.0-rc.3de6f63

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 (48) hide show
  1. package/dist/application-config/index.js +1 -1
  2. package/dist/authentication/index.js +10 -2
  3. package/dist/cli.js +586 -303
  4. package/dist/commons/events/ActionConfig.d.ts +2 -2
  5. package/dist/commons/events/EventConfig.d.ts +1 -10
  6. package/dist/commons/events/eventConfigValidation.d.ts +1 -1
  7. package/dist/commons/events/index.d.ts +1 -0
  8. package/dist/commons/events/test.utils.d.ts +2 -3
  9. package/dist/commons/events/toNotificationForm.d.ts +17 -0
  10. package/dist/commons/events/utils.d.ts +77 -56
  11. package/dist/environment/custom-types.d.ts +1 -0
  12. package/dist/environment/custom-types.d.ts.map +1 -1
  13. package/dist/environment/derived-variables.d.ts +6 -4
  14. package/dist/environment/derived-variables.d.ts.map +1 -1
  15. package/dist/environment/derived-variables.js +6 -4
  16. package/dist/environment/questions.d.ts +14 -2
  17. package/dist/environment/questions.d.ts.map +1 -1
  18. package/dist/environment/questions.js +39 -18
  19. package/dist/environment/registry.d.ts +15 -0
  20. package/dist/environment/registry.d.ts.map +1 -0
  21. package/dist/environment/registry.js +112 -0
  22. package/dist/environment/setup-environment.d.ts.map +1 -1
  23. package/dist/environment/setup-environment.js +76 -28
  24. package/dist/events/index.js +60 -97
  25. package/dist/migrations/add-notify-config.d.ts +40 -0
  26. package/dist/migrations/add-notify-config.d.ts.map +1 -0
  27. package/dist/migrations/add-notify-config.js +249 -0
  28. package/dist/migrations/index.d.ts.map +1 -1
  29. package/dist/migrations/index.js +345 -143
  30. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -1
  31. package/dist/migrations/move-declaration-to-declare-action.js +27 -144
  32. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -1
  33. package/dist/migrations/read-declaration-through-helper.js +3 -61
  34. package/dist/migrations/utils.d.ts +61 -0
  35. package/dist/migrations/utils.d.ts.map +1 -0
  36. package/dist/migrations/utils.js +218 -0
  37. package/dist/notification/index.js +47 -75
  38. package/dist/scopes/index.d.ts +5 -2
  39. package/dist/scopes/index.js +10 -2
  40. package/dist/templates/charts-values/opencrvs-services/values.yaml +3 -4
  41. package/opencrvs-toolkit-2.2.0-rc.3de6f63.tgz +0 -0
  42. package/package.json +2 -1
  43. package/tsconfig.build.tsbuildinfo +1 -1
  44. package/dist/commons/events/notificationFormFallback.d.ts +0 -10
  45. package/dist/environment/dockerhub.d.ts +0 -15
  46. package/dist/environment/dockerhub.d.ts.map +0 -1
  47. package/dist/environment/dockerhub.js +0 -104
  48. package/opencrvs-toolkit-2.2.0-rc.30529dd.tgz +0 -0
package/dist/cli.js CHANGED
@@ -32,13 +32,13 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
32
32
 
33
33
  // src/environment/paths.ts
34
34
  function getEnvironmentInventoryPath(environment) {
35
- return (0, import_path7.join)("environments", environment, INVENTORY_FILE_NAME);
35
+ return (0, import_path9.join)("environments", environment, INVENTORY_FILE_NAME);
36
36
  }
37
37
  function findOldInventoryFiles() {
38
- return glob.sync((0, import_path7.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
38
+ return glob.sync((0, import_path9.join)(OLD_INVENTORY_DIR, "*.yml")).sort();
39
39
  }
40
40
  function getEnvironmentNameFromOldInventoryPath(filePath) {
41
- return (0, import_path7.basename)(filePath, ".yml");
41
+ return (0, import_path9.basename)(filePath, ".yml");
42
42
  }
43
43
  function assertNoOldInventoryLayout() {
44
44
  if (findOldInventoryFiles().length === 0) {
@@ -51,13 +51,13 @@ function assertNoOldInventoryLayout() {
51
51
  ].join(" ")
52
52
  );
53
53
  }
54
- var import_path7, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
54
+ var import_path9, glob, OLD_INVENTORY_DIR, INVENTORY_FILE_NAME;
55
55
  var init_paths = __esm({
56
56
  "src/environment/paths.ts"() {
57
57
  "use strict";
58
- import_path7 = require("path");
58
+ import_path9 = require("path");
59
59
  glob = __toESM(require("glob"));
60
- OLD_INVENTORY_DIR = (0, import_path7.join)(
60
+ OLD_INVENTORY_DIR = (0, import_path9.join)(
61
61
  "infrastructure",
62
62
  "server-setup",
63
63
  "inventory"
@@ -403,15 +403,17 @@ var init_derived_variables = __esm({
403
403
  scope: "ENVIRONMENT"
404
404
  },
405
405
  {
406
- name: "MINIO_ROOT_USER",
407
- valueLabel: "MINIO_ROOT_USER",
406
+ name: "S3_ADMIN_ACCESS_KEY",
407
+ valueLabel: "S3_ADMIN_ACCESS_KEY",
408
+ legacyValueLabel: "MINIO_ROOT_USER",
408
409
  valueType: "SECRET",
409
410
  type: "disabled",
410
411
  scope: "ENVIRONMENT"
411
412
  },
412
413
  {
413
- name: "MINIO_ROOT_PASSWORD",
414
- valueLabel: "MINIO_ROOT_PASSWORD",
414
+ name: "S3_ADMIN_SECRET_KEY",
415
+ valueLabel: "S3_ADMIN_SECRET_KEY",
416
+ legacyValueLabel: "MINIO_ROOT_PASSWORD",
415
417
  valueType: "SECRET",
416
418
  type: "disabled",
417
419
  scope: "ENVIRONMENT"
@@ -603,8 +605,8 @@ function extractWorkerNodes(data) {
603
605
  return worker_hosts;
604
606
  }
605
607
  function copyChartsValues(env, values) {
606
- const srcDir = import_path8.default.resolve(__dirname, "templates", "charts-values");
607
- const destDir = import_path8.default.resolve(process.cwd(), "environments", env);
608
+ const srcDir = import_path10.default.resolve(__dirname, "templates", "charts-values");
609
+ const destDir = import_path10.default.resolve(process.cwd(), "environments", env);
608
610
  import_fs5.default.mkdirSync(destDir, { recursive: true });
609
611
  values["lets_encrypt"] = values["traefik_mode"] === "lets_encrypt";
610
612
  values["static_ssl"] = values["traefik_mode"] === "static_ssl";
@@ -614,7 +616,7 @@ function copyChartsValues(env, values) {
614
616
  if (stat.isDirectory()) {
615
617
  import_fs5.default.mkdirSync(dest, { recursive: true });
616
618
  for (const item of import_fs5.default.readdirSync(src)) {
617
- copyRecursive(import_path8.default.join(src, item), import_path8.default.join(dest, item));
619
+ copyRecursive(import_path10.default.join(src, item), import_path10.default.join(dest, item));
618
620
  }
619
621
  } else {
620
622
  const content = import_fs5.default.readFileSync(src, "utf8");
@@ -636,13 +638,13 @@ function copyChartsValues(env, values) {
636
638
  `);
637
639
  }
638
640
  function generateInventory(env, values) {
639
- const templatePath = import_path8.default.join(
641
+ const templatePath = import_path10.default.join(
640
642
  __dirname,
641
643
  "templates",
642
644
  "inventory",
643
645
  "inventory.template.yml"
644
646
  );
645
- const outputPath = import_path8.default.resolve(
647
+ const outputPath = import_path10.default.resolve(
646
648
  process.cwd(),
647
649
  getEnvironmentInventoryPath(env)
648
650
  );
@@ -650,18 +652,18 @@ function generateInventory(env, values) {
650
652
  const template = import_handlebars.default.compile(templateFile);
651
653
  values["single_node"] = values["kube_worker_nodes"].length > 0 || values["backup_host"] ? "false" : "true";
652
654
  const updated = template(values);
653
- import_fs5.default.mkdirSync(import_path8.default.dirname(outputPath), { recursive: true });
655
+ import_fs5.default.mkdirSync(import_path10.default.dirname(outputPath), { recursive: true });
654
656
  import_fs5.default.writeFileSync(outputPath, updated);
655
657
  log(`
656
658
  \u2705 Generated inventory file at ${outputPath}
657
659
  `);
658
660
  }
659
- var import_fs5, import_path8, import_handlebars;
661
+ var import_fs5, import_path10, import_handlebars;
660
662
  var init_templates = __esm({
661
663
  "src/environment/templates.ts"() {
662
664
  "use strict";
663
665
  import_fs5 = __toESM(require("fs"));
664
- import_path8 = __toESM(require("path"));
666
+ import_path10 = __toESM(require("path"));
665
667
  init_logger();
666
668
  init_paths();
667
669
  import_handlebars = __toESM(require("handlebars"));
@@ -692,16 +694,16 @@ var update_workflows_exports = {};
692
694
  __export(update_workflows_exports, {
693
695
  updateWorkflowEnvironments: () => updateWorkflowEnvironments
694
696
  });
695
- function isDirectory(path12) {
697
+ function isDirectory(path14) {
696
698
  try {
697
- return (0, import_fs6.statSync)(path12).isDirectory();
699
+ return (0, import_fs6.statSync)(path14).isDirectory();
698
700
  } catch {
699
701
  return false;
700
702
  }
701
703
  }
702
704
  async function extractInfrastructureNames() {
703
- const files = glob2.sync((0, import_path9.join)("environments", "*", INVENTORY_FILE_NAME));
704
- const infraEnvironments = files.map((file) => (0, import_path9.basename)((0, import_path9.dirname)(file)));
705
+ const files = glob2.sync((0, import_path11.join)("environments", "*", INVENTORY_FILE_NAME));
706
+ const infraEnvironments = files.map((file) => (0, import_path11.basename)((0, import_path11.dirname)(file)));
705
707
  if (infraEnvironments.length === 0) {
706
708
  console.log(
707
709
  `\u26A0\uFE0F Warning: No environment inventory files found at environments/*/${INVENTORY_FILE_NAME}`
@@ -714,8 +716,8 @@ async function extractInfrastructureNames() {
714
716
  async function extractEnvironmentNames() {
715
717
  const entries = await (0, import_promises.readdir)("environments");
716
718
  const environments = entries.filter((entry) => {
717
- const environmentPath = (0, import_path9.join)("environments", entry);
718
- const opencrvsServicesPath = (0, import_path9.join)(environmentPath, "opencrvs-services");
719
+ const environmentPath = (0, import_path11.join)("environments", entry);
720
+ const opencrvsServicesPath = (0, import_path11.join)(environmentPath, "opencrvs-services");
719
721
  return isDirectory(environmentPath) && (0, import_fs6.existsSync)(opencrvsServicesPath) && isDirectory(opencrvsServicesPath);
720
722
  });
721
723
  if (environments.length === 0) {
@@ -808,13 +810,13 @@ async function updateWorkflowEnvironments() {
808
810
  process.exit(1);
809
811
  }
810
812
  }
811
- var import_promises, import_fs6, import_path9, glob2, yaml2;
813
+ var import_promises, import_fs6, import_path11, glob2, yaml2;
812
814
  var init_update_workflows = __esm({
813
815
  "src/environment/update-workflows.ts"() {
814
816
  "use strict";
815
817
  import_promises = require("fs/promises");
816
818
  import_fs6 = require("fs");
817
- import_path9 = require("path");
819
+ import_path11 = require("path");
818
820
  glob2 = __toESM(require("glob"));
819
821
  yaml2 = __toESM(require("js-yaml"));
820
822
  init_logger();
@@ -872,7 +874,10 @@ function validateCIDRs(input4) {
872
874
  }
873
875
  return true;
874
876
  }
875
- var import_kleur2, notEmpty, dockerhubQuestions, githubQuestions, githubOtherQuestions, githubTokenQuestion, countryQuestions, infrastructureQuestions, staticSSLCertQuestions, backupQuestions, diskQuestions, databaseAndMonitoringQuestions, emailQuestions, sentryQuestions, metabaseAdminQuestions;
877
+ function validateRegistryHost(input4) {
878
+ return /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:[0-9]+)?$/i.test(input4) ? true : "Please enter a registry host without protocol or path (e.g. docker.io, ghcr.io)";
879
+ }
880
+ var import_kleur2, notEmpty, registryQuestions, githubQuestions, githubOtherQuestions, githubTokenQuestion, countryQuestions, infrastructureQuestions, staticSSLCertQuestions, backupQuestions, diskQuestions, databaseAndMonitoringQuestions, emailQuestions, sentryQuestions, metabaseAdminQuestions;
876
881
  var init_questions = __esm({
877
882
  "src/environment/questions.ts"() {
878
883
  "use strict";
@@ -880,45 +885,59 @@ var init_questions = __esm({
880
885
  init_utils();
881
886
  init_git();
882
887
  notEmpty = (value) => value.toString().trim().length > 0 ? true : "Please enter a value";
883
- dockerhubQuestions = [
888
+ registryQuestions = [
884
889
  {
885
- name: "dockerhubOrganisation",
890
+ name: "registryHost",
886
891
  type: "text",
887
- message: "What is the name of your Docker Hub organisation?",
892
+ message: "What is the host of your container registry? (e.g. docker.io, ghcr.io)",
893
+ valueType: "VARIABLE",
894
+ valueLabel: "REGISTRY_HOST",
895
+ validate: validateRegistryHost,
896
+ initial: process.env.REGISTRY_HOST || "docker.io",
897
+ scope: "REPOSITORY"
898
+ },
899
+ {
900
+ name: "registryOrganisation",
901
+ type: "text",
902
+ message: "What is the name of your organisation (or user) in the container registry?",
888
903
  valueType: "SECRET",
889
- valueLabel: "DOCKERHUB_ACCOUNT",
904
+ valueLabel: "REGISTRY_ORGANISATION",
905
+ legacyValueLabel: "DOCKERHUB_ACCOUNT",
890
906
  validate: notEmpty,
891
- initial: process.env.DOCKER_ORGANISATION,
907
+ initial: process.env.REGISTRY_ORGANISATION,
892
908
  scope: "REPOSITORY"
893
909
  },
894
910
  {
895
- name: "dockerhubRepository",
911
+ name: "registryRepository",
896
912
  type: "text",
897
- message: "What is the name of your private Docker Hub repository?",
913
+ message: "What is the name of your private container repository?",
898
914
  valueType: "SECRET",
899
- valueLabel: "DOCKERHUB_REPO",
915
+ valueLabel: "REGISTRY_REPOSITORY",
916
+ legacyValueLabel: "DOCKERHUB_REPO",
900
917
  validate: notEmpty,
901
- initial: process.env.DOCKER_REPO,
918
+ initial: process.env.REGISTRY_REPOSITORY,
902
919
  scope: "REPOSITORY"
903
920
  },
904
921
  {
905
- name: "dockerhubUsername",
922
+ name: "registryUsername",
906
923
  type: "text",
907
- message: "What is the Docker Hub username the the target server should be using?",
924
+ message: "What is the container registry username the target server should be using?",
908
925
  valueType: "SECRET",
909
- valueLabel: "DOCKER_USERNAME",
926
+ valueLabel: "REGISTRY_USERNAME",
927
+ legacyValueLabel: "DOCKER_USERNAME",
910
928
  validate: notEmpty,
911
- initial: process.env.DOCKER_USERNAME,
929
+ initial: process.env.REGISTRY_USERNAME,
912
930
  scope: "REPOSITORY"
913
931
  },
914
932
  {
915
- name: "dockerhubToken",
933
+ name: "registryToken",
916
934
  type: "text",
917
- message: "What is the token of this Docker Hub account?",
935
+ message: "What is the token of this container registry account?",
918
936
  valueType: "SECRET",
919
- valueLabel: "DOCKER_TOKEN",
937
+ valueLabel: "REGISTRY_TOKEN",
938
+ legacyValueLabel: "DOCKER_TOKEN",
920
939
  validate: notEmpty,
921
- initial: process.env.DOCKER_TOKEN,
940
+ initial: process.env.REGISTRY_TOKEN,
922
941
  scope: "REPOSITORY"
923
942
  }
924
943
  ];
@@ -1377,69 +1396,71 @@ var init_questions_helper = __esm({
1377
1396
  }
1378
1397
  });
1379
1398
 
1380
- // src/environment/dockerhub.ts
1381
- async function validateDockerHubCredentials(organisation, repository, username, token) {
1382
- if (!organisation || !repository || !username || !token) {
1383
- return {
1384
- status: "skipped",
1385
- reason: "Some values are kept from existing GitHub secrets, which cannot be read back"
1386
- };
1387
- }
1388
- try {
1389
- const login = await fetch(`${DOCKER_HUB_API}/auth/token`, {
1390
- method: "POST",
1391
- headers: { "Content-Type": "application/json" },
1392
- body: JSON.stringify({ identifier: username, secret: token }),
1393
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1394
- });
1395
- if (login.status === 401 || login.status === 403) {
1399
+ // src/environment/registry.ts
1400
+ function registryApiHost(registry) {
1401
+ const host = registry.trim().toLowerCase();
1402
+ return host === "docker.io" || host === "index.docker.io" ? "registry-1.docker.io" : host;
1403
+ }
1404
+ function request(url, authorization) {
1405
+ return fetch(url, {
1406
+ headers: authorization ? { Authorization: authorization } : {},
1407
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1408
+ });
1409
+ }
1410
+ function failure(registry, step, response) {
1411
+ const reason = `${registry} ${step} responded with HTTP ${response.status}`;
1412
+ switch (response.status) {
1413
+ case 401:
1414
+ case 403:
1396
1415
  return {
1397
1416
  status: "invalid-credentials",
1398
- reason: "Docker Hub rejected the username or token. Check DOCKER_USERNAME and DOCKER_TOKEN"
1399
- };
1400
- }
1401
- if (!login.ok) {
1402
- return {
1403
- status: "unreachable",
1404
- reason: `Docker Hub login responded with HTTP ${login.status}`
1405
- };
1406
- }
1407
- const body = await login.json();
1408
- const accessToken = body.access_token ?? body.token;
1409
- if (!accessToken) {
1410
- return {
1411
- status: "unreachable",
1412
- reason: "Docker Hub login response did not contain an access token"
1417
+ reason: `${reason}. Check REGISTRY_USERNAME, REGISTRY_TOKEN, REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
1413
1418
  };
1414
- }
1415
- const repositoryResponse = await fetch(
1416
- `${DOCKER_HUB_API}/repositories/${encodeURIComponent(
1417
- organisation
1418
- )}/${encodeURIComponent(repository)}/`,
1419
- {
1420
- headers: { Authorization: `Bearer ${accessToken}` },
1421
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1422
- }
1423
- );
1424
- if (repositoryResponse.ok) {
1425
- return { status: "valid" };
1426
- }
1427
- if (repositoryResponse.status === 404) {
1419
+ case 404:
1428
1420
  return {
1429
1421
  status: "repository-not-found",
1430
- reason: `Login succeeded, but repository ${organisation}/${repository} was not found or is not accessible with this token. Check DOCKERHUB_ACCOUNT and DOCKERHUB_REPO`
1431
- };
1432
- }
1433
- if (repositoryResponse.status === 401 || repositoryResponse.status === 403) {
1434
- return {
1435
- status: "invalid-credentials",
1436
- reason: `Login succeeded, but the token is not allowed to read repository ${organisation}/${repository}`
1422
+ reason: `${reason}. This is also the answer for an empty repository. Check REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
1437
1423
  };
1438
- }
1424
+ default:
1425
+ return { status: "unreachable", reason };
1426
+ }
1427
+ }
1428
+ async function validateRegistryCredentials(registry, organisation, repository, username, token) {
1429
+ if (!registry || !organisation || !repository || !username || !token) {
1439
1430
  return {
1440
- status: "unreachable",
1441
- reason: `Docker Hub repository lookup responded with HTTP ${repositoryResponse.status}`
1431
+ status: "skipped",
1432
+ reason: "Some values are kept from existing GitHub secrets, which cannot be read back"
1442
1433
  };
1434
+ }
1435
+ const host = registryApiHost(registry);
1436
+ const name = `${organisation}/${repository}`;
1437
+ const basic = `Basic ${Buffer.from(`${username}:${token}`).toString("base64")}`;
1438
+ try {
1439
+ const challenge = (await request(`https://${host}/v2/`, void 0)).headers.get(
1440
+ "www-authenticate"
1441
+ ) ?? "";
1442
+ const realm = challenge.match(/realm="([^"]*)"/i)?.[1];
1443
+ const service = challenge.match(/service="([^"]*)"/i)?.[1];
1444
+ let authorization = basic;
1445
+ if (/^\s*bearer/i.test(challenge) && realm) {
1446
+ const tokenUrl = new URL(realm);
1447
+ if (service) {
1448
+ tokenUrl.searchParams.set("service", service);
1449
+ }
1450
+ tokenUrl.searchParams.set("scope", `repository:${name}:pull`);
1451
+ const login = await request(tokenUrl, basic);
1452
+ if (!login.ok) {
1453
+ return failure(registry, "login", login);
1454
+ }
1455
+ const body = await login.json();
1456
+ authorization = `Bearer ${body.token ?? body.access_token}`;
1457
+ }
1458
+ const path14 = name.split("/").map(encodeURIComponent).join("/");
1459
+ const response = await request(
1460
+ `https://${host}/v2/${path14}/tags/list?n=1`,
1461
+ authorization
1462
+ );
1463
+ return response.ok ? { status: "valid" } : failure(registry, `lookup of repository ${name}`, response);
1443
1464
  } catch (err) {
1444
1465
  if (!(err instanceof Error)) {
1445
1466
  return { status: "unreachable", reason: String(err) };
@@ -1448,11 +1469,10 @@ async function validateDockerHubCredentials(organisation, repository, username,
1448
1469
  return { status: "unreachable", reason: `${err.message}${cause}` };
1449
1470
  }
1450
1471
  }
1451
- var DOCKER_HUB_API, REQUEST_TIMEOUT_MS;
1452
- var init_dockerhub = __esm({
1453
- "src/environment/dockerhub.ts"() {
1472
+ var REQUEST_TIMEOUT_MS;
1473
+ var init_registry = __esm({
1474
+ "src/environment/registry.ts"() {
1454
1475
  "use strict";
1455
- DOCKER_HUB_API = "https://hub.docker.com/v2";
1456
1476
  REQUEST_TIMEOUT_MS = 1e4;
1457
1477
  }
1458
1478
  });
@@ -1483,7 +1503,7 @@ function getCurrentUsername() {
1483
1503
  }
1484
1504
  function getCurrentUserSSHKeys() {
1485
1505
  const homeDir = os.homedir();
1486
- const sshDir = path8.join(homeDir, ".ssh");
1506
+ const sshDir = path10.join(homeDir, ".ssh");
1487
1507
  const keys = [];
1488
1508
  const keyFiles = [
1489
1509
  "id_rsa.pub",
@@ -1492,7 +1512,7 @@ function getCurrentUserSSHKeys() {
1492
1512
  "id_dsa.pub"
1493
1513
  ];
1494
1514
  for (const keyFile of keyFiles) {
1495
- const keyPath = path8.join(sshDir, keyFile);
1515
+ const keyPath = path10.join(sshDir, keyFile);
1496
1516
  try {
1497
1517
  if (fs5.existsSync(keyPath)) {
1498
1518
  const keyContent = fs5.readFileSync(keyPath, "utf8").trim();
@@ -1833,13 +1853,13 @@ async function manageUsers(inventoryPath) {
1833
1853
  }
1834
1854
  return users;
1835
1855
  }
1836
- var os, fs5, path8, input2, select2, confirm, editor, checkbox;
1856
+ var os, fs5, path10, input2, select2, confirm, editor, checkbox;
1837
1857
  var init_manage_users = __esm({
1838
1858
  "src/environment/manage-users.ts"() {
1839
1859
  "use strict";
1840
1860
  os = __toESM(require("os"));
1841
1861
  fs5 = __toESM(require("fs"));
1842
- path8 = __toESM(require("path"));
1862
+ path10 = __toESM(require("path"));
1843
1863
  init_logger();
1844
1864
  init_utils();
1845
1865
  init_templates();
@@ -1871,6 +1891,7 @@ async function input3(options) {
1871
1891
  function questionToPrompt({
1872
1892
  valueType,
1873
1893
  valueLabel,
1894
+ legacyValueLabel,
1874
1895
  scope,
1875
1896
  ...promptOptions
1876
1897
  }) {
@@ -1934,6 +1955,12 @@ function getAnswers(existingValues) {
1934
1955
  });
1935
1956
  });
1936
1957
  }
1958
+ function getInitialValue(question, variable) {
1959
+ if (question.type === "select" && Array.isArray(question.choices)) {
1960
+ return getIndexFromChoices(question.choices, variable.value);
1961
+ }
1962
+ return variable.value;
1963
+ }
1937
1964
  async function promptAndStoreAnswer(questions, existingValues) {
1938
1965
  log("");
1939
1966
  const processedQuestions = questions.flatMap((question) => {
@@ -1951,14 +1978,22 @@ async function promptAndStoreAnswer(questions, existingValues) {
1951
1978
  questionWithVariableLabel.scope,
1952
1979
  existingValues
1953
1980
  );
1981
+ const legacyVariable = !existingVariable && questionWithVariableLabel.legacyValueLabel ? findExistingValue(
1982
+ questionWithVariableLabel.legacyValueLabel,
1983
+ "VARIABLE",
1984
+ questionWithVariableLabel.scope,
1985
+ existingValues
1986
+ ) : void 0;
1987
+ if (legacyVariable) {
1988
+ return {
1989
+ ...questionWithVariableLabel,
1990
+ message: `${questionWithVariableLabel.message} ${import_kleur4.default.gray(
1991
+ `(default taken from ${legacyVariable.name}, the previous name of this variable)`
1992
+ )}`,
1993
+ initial: getInitialValue(questionWithVariableLabel, legacyVariable)
1994
+ };
1995
+ }
1954
1996
  if (existingVariable) {
1955
- let initial_value = existingVariable.value;
1956
- if (questionWithVariableLabel.type === "select" && Array.isArray(questionWithVariableLabel.choices)) {
1957
- initial_value = getIndexFromChoices(
1958
- questionWithVariableLabel.choices,
1959
- existingVariable.value
1960
- );
1961
- }
1962
1997
  return [
1963
1998
  {
1964
1999
  name: "overWrite" + questionWithVariableLabel.name,
@@ -1973,7 +2008,10 @@ async function promptAndStoreAnswer(questions, existingValues) {
1973
2008
  {
1974
2009
  ...questionWithVariableLabel,
1975
2010
  type: (prev) => prev ? questionWithVariableLabel.type : null,
1976
- initial: initial_value
2011
+ initial: getInitialValue(
2012
+ questionWithVariableLabel,
2013
+ existingVariable
2014
+ )
1977
2015
  }
1978
2016
  ];
1979
2017
  }
@@ -1985,6 +2023,32 @@ async function promptAndStoreAnswer(questions, existingValues) {
1985
2023
  questionWithVariableLabel.scope,
1986
2024
  existingValues
1987
2025
  );
2026
+ const legacySecret = !existingSecret && questionWithVariableLabel.legacyValueLabel ? findExistingValue(
2027
+ questionWithVariableLabel.legacyValueLabel,
2028
+ "SECRET",
2029
+ questionWithVariableLabel.scope,
2030
+ existingValues
2031
+ ) : void 0;
2032
+ if (legacySecret) {
2033
+ return [
2034
+ {
2035
+ name: "overWrite" + questionWithVariableLabel.name,
2036
+ type: "confirm",
2037
+ scope: questionWithVariableLabel.scope,
2038
+ message: `${import_kleur4.default.yellow(
2039
+ `${legacySecret.scope === "REPOSITORY" ? "Repository secret" : "Secret"} ${import_kleur4.default.cyan(
2040
+ legacySecret.name
2041
+ )} already exists in Github under the previous name of ${import_kleur4.default.cyan(
2042
+ questionWithVariableLabel.valueLabel
2043
+ )}. The secrets migration workflow copies it. Do you want to enter a new value instead?`
2044
+ )}`
2045
+ },
2046
+ {
2047
+ ...questionWithVariableLabel,
2048
+ type: (prev) => prev ? questionWithVariableLabel.type : null
2049
+ }
2050
+ ];
2051
+ }
1988
2052
  if (existingSecret) {
1989
2053
  return [
1990
2054
  {
@@ -2024,13 +2088,32 @@ async function promptAndStoreAnswer(questions, existingValues) {
2024
2088
  ]);
2025
2089
  return { ...Object.fromEntries(existingValuesForQuestions), ...result };
2026
2090
  }
2027
- async function promptAndValidateDockerhub(existingValues) {
2028
- const answers = await promptAndStoreAnswer(dockerhubQuestions, existingValues);
2029
- const result = await validateDockerHubCredentials(
2030
- answers.dockerhubOrganisation,
2031
- answers.dockerhubRepository,
2032
- answers.dockerhubUsername,
2033
- answers.dockerhubToken
2091
+ function defineIfMissing(existingValues, name, type, scope, newValue) {
2092
+ if (findExistingValue(name, type, scope, existingValues)) {
2093
+ return null;
2094
+ }
2095
+ const legacyName = ALL_QUESTIONS.find(
2096
+ (question) => question.valueLabel === name && question.valueType === type && question.scope === scope
2097
+ )?.legacyValueLabel;
2098
+ if (legacyName && findExistingValue(legacyName, type, scope, existingValues)) {
2099
+ log(
2100
+ import_kleur4.default.bold().green("\u2714"),
2101
+ import_kleur4.default.bold().yellow(
2102
+ `${legacyName} exists, the secrets migration workflow copies it to ${name}`
2103
+ )
2104
+ );
2105
+ return null;
2106
+ }
2107
+ return process.env[name] || newValue;
2108
+ }
2109
+ async function promptAndValidateRegistry(existingValues) {
2110
+ const answers = await promptAndStoreAnswer(registryQuestions, existingValues);
2111
+ const result = await validateRegistryCredentials(
2112
+ answers.registryHost,
2113
+ answers.registryOrganisation,
2114
+ answers.registryRepository,
2115
+ answers.registryUsername,
2116
+ answers.registryToken
2034
2117
  );
2035
2118
  if (result.status === "valid" || result.status === "skipped") {
2036
2119
  return;
@@ -2039,7 +2122,7 @@ async function promptAndValidateDockerhub(existingValues) {
2039
2122
  ${result.status}: ${result.reason || "Generic error"}
2040
2123
  `);
2041
2124
  const continueNotValidated = await confirm2({
2042
- message: "Docker Hub credentials are not validated. Continue anyway?",
2125
+ message: "Container registry credentials are not validated. Continue anyway?",
2043
2126
  default: false
2044
2127
  });
2045
2128
  if (!continueNotValidated) {
@@ -2189,8 +2272,8 @@ async function runSetupEnvironment() {
2189
2272
  "2FA is disabled on a production-like environment. Logins will accept the fixed test code 000000, exposing real citizen data. Only do this if you know what you are doing."
2190
2273
  );
2191
2274
  }
2192
- log("\n", import_kleur4.default.bold().underline("Docker Hub"));
2193
- await promptAndValidateDockerhub(existingValues);
2275
+ log("\n", import_kleur4.default.bold().underline("Container registry"));
2276
+ await promptAndValidateRegistry(existingValues);
2194
2277
  log("\n", import_kleur4.default.bold().underline("Kubernetes & Runtime"));
2195
2278
  const infrastructure = await promptAndStoreAnswer(
2196
2279
  infrastructureQuestions,
@@ -2420,9 +2503,7 @@ async function runSetupEnvironment() {
2420
2503
  return { ...acc, ...answer };
2421
2504
  });
2422
2505
  const answerOrExisting = (variable, existingValue, fn) => fn(variable || existingValue?.value) || "";
2423
- function findExistingOrDefine(name, type, scope, newValue) {
2424
- return findExistingValue(name, type, scope, existingValues) ? null : process.env[name] || newValue;
2425
- }
2506
+ const findExistingOrDefine = (name, type, scope, newValue) => defineIfMissing(existingValues, name, type, scope, newValue);
2426
2507
  const derivedUpdates = [
2427
2508
  {
2428
2509
  name: "GH_ENCRYPTION_PASSWORD",
@@ -2530,16 +2611,16 @@ async function runSetupEnvironment() {
2530
2611
  scope: "ENVIRONMENT"
2531
2612
  },
2532
2613
  {
2533
- name: "MINIO_ROOT_USER",
2614
+ name: "S3_ADMIN_ACCESS_KEY",
2534
2615
  type: "SECRET",
2535
2616
  didExist: findExistingValue(
2536
- "MINIO_ROOT_USER",
2617
+ "S3_ADMIN_ACCESS_KEY",
2537
2618
  "SECRET",
2538
2619
  "ENVIRONMENT",
2539
2620
  existingValues
2540
2621
  ),
2541
2622
  value: findExistingOrDefine(
2542
- "MINIO_ROOT_USER",
2623
+ "S3_ADMIN_ACCESS_KEY",
2543
2624
  "SECRET",
2544
2625
  "ENVIRONMENT",
2545
2626
  generateLongPassword()
@@ -2547,16 +2628,16 @@ async function runSetupEnvironment() {
2547
2628
  scope: "ENVIRONMENT"
2548
2629
  },
2549
2630
  {
2550
- name: "MINIO_ROOT_PASSWORD",
2631
+ name: "S3_ADMIN_SECRET_KEY",
2551
2632
  type: "SECRET",
2552
2633
  didExist: findExistingValue(
2553
- "MINIO_ROOT_PASSWORD",
2634
+ "S3_ADMIN_SECRET_KEY",
2554
2635
  "SECRET",
2555
2636
  "ENVIRONMENT",
2556
2637
  existingValues
2557
2638
  ),
2558
2639
  value: findExistingOrDefine(
2559
- "MINIO_ROOT_PASSWORD",
2640
+ "S3_ADMIN_SECRET_KEY",
2560
2641
  "SECRET",
2561
2642
  "ENVIRONMENT",
2562
2643
  generateLongPassword()
@@ -2820,7 +2901,7 @@ async function runSetupEnvironment() {
2820
2901
  );
2821
2902
  const unknownVariables = existingValues.filter((value) => {
2822
2903
  return !ALL_QUESTIONS.find(
2823
- (question) => question.valueLabel === value.name && question.valueType === value.type && question.scope === value.scope
2904
+ (question) => (question.valueLabel === value.name || question.legacyValueLabel === value.name) && question.valueType === value.type && question.scope === value.scope
2824
2905
  );
2825
2906
  });
2826
2907
  log("");
@@ -3090,7 +3171,7 @@ var init_setup_environment = __esm({
3090
3171
  init_questions();
3091
3172
  init_editor_questions();
3092
3173
  init_questions_helper();
3093
- init_dockerhub();
3174
+ init_registry();
3094
3175
  init_manage_users();
3095
3176
  init_paths();
3096
3177
  ALL_QUESTIONS = [];
@@ -3098,7 +3179,7 @@ var init_setup_environment = __esm({
3098
3179
  ALL_QUESTIONS.push(
3099
3180
  ...githubTokenQuestion,
3100
3181
  ...githubOtherQuestions,
3101
- ...dockerhubQuestions,
3182
+ ...registryQuestions,
3102
3183
  ...diskQuestions,
3103
3184
  ...infrastructureQuestions,
3104
3185
  ...backupQuestions,
@@ -3127,7 +3208,7 @@ function moveFileIfDestinationMissing(sourcePath, destinationPath) {
3127
3208
  );
3128
3209
  return false;
3129
3210
  }
3130
- (0, import_fs7.mkdirSync)((0, import_path10.dirname)(destinationPath), { recursive: true });
3211
+ (0, import_fs7.mkdirSync)((0, import_path12.dirname)(destinationPath), { recursive: true });
3131
3212
  (0, import_fs7.renameSync)(sourcePath, destinationPath);
3132
3213
  log(` \u2713 Moved ${sourcePath} -> ${destinationPath}`);
3133
3214
  return true;
@@ -3167,12 +3248,12 @@ async function upgradeEnvironmentLayout() {
3167
3248
  }
3168
3249
  log("\nCommit changes into git after upgrade");
3169
3250
  }
3170
- var import_fs7, import_path10, import_kleur5;
3251
+ var import_fs7, import_path12, import_kleur5;
3171
3252
  var init_upgrade = __esm({
3172
3253
  "src/environment/upgrade.ts"() {
3173
3254
  "use strict";
3174
3255
  import_fs7 = require("fs");
3175
- import_path10 = require("path");
3256
+ import_path12 = require("path");
3176
3257
  import_kleur5 = __toESM(require("kleur"));
3177
3258
  init_logger();
3178
3259
  init_paths();
@@ -3198,7 +3279,7 @@ async function selectInventoryFile(dirPath = "./environments") {
3198
3279
  return null;
3199
3280
  }
3200
3281
  const environments = fs6.readdirSync(dirPath).filter((entry) => {
3201
- const filePath = path9.join(dirPath, entry);
3282
+ const filePath = path11.join(dirPath, entry);
3202
3283
  return fs6.statSync(filePath).isDirectory() && fs6.existsSync(getEnvironmentInventoryPath(entry));
3203
3284
  }).sort();
3204
3285
  if (environments.length === 0) {
@@ -3226,12 +3307,12 @@ async function manageEnvironmentUsers() {
3226
3307
  }
3227
3308
  await manageUsers(inventory_file);
3228
3309
  }
3229
- var fs6, path9, import_kleur6;
3310
+ var fs6, path11, import_kleur6;
3230
3311
  var init_users = __esm({
3231
3312
  "src/environment/users.ts"() {
3232
3313
  "use strict";
3233
3314
  fs6 = __toESM(require("fs"));
3234
- path9 = __toESM(require("path"));
3315
+ path11 = __toESM(require("path"));
3235
3316
  import_kleur6 = __toESM(require("kleur"));
3236
3317
  init_manage_users();
3237
3318
  init_logger();
@@ -3241,11 +3322,11 @@ var init_users = __esm({
3241
3322
 
3242
3323
  // src/environment/swarm-to-k8s.ts
3243
3324
  var swarm_to_k8s_exports = {};
3244
- var path10, import_kleur7, import_core2;
3325
+ var path12, import_kleur7, import_core2;
3245
3326
  var init_swarm_to_k8s = __esm({
3246
3327
  "src/environment/swarm-to-k8s.ts"() {
3247
3328
  "use strict";
3248
- path10 = __toESM(require("path"));
3329
+ path12 = __toESM(require("path"));
3249
3330
  import_kleur7 = __toESM(require("kleur"));
3250
3331
  init_logger();
3251
3332
  init_utils();
@@ -3297,7 +3378,7 @@ var init_swarm_to_k8s = __esm({
3297
3378
  );
3298
3379
  process.exit(1);
3299
3380
  }
3300
- const ansible_inventory = path10.join(old_inventory_path, environment + ".yml");
3381
+ const ansible_inventory = path12.join(old_inventory_path, environment + ".yml");
3301
3382
  const data = readYamlFile(ansible_inventory);
3302
3383
  log(` \u2713 Loaded old inventory file: ${ansible_inventory}`);
3303
3384
  const master = dockerManagerFirst(data) || "";
@@ -3420,7 +3501,7 @@ var init_swarm_to_k8s = __esm({
3420
3501
 
3421
3502
  // src/cli.ts
3422
3503
  var import_fs9 = __toESM(require("fs"));
3423
- var import_path12 = __toESM(require("path"));
3504
+ var import_path14 = __toESM(require("path"));
3424
3505
 
3425
3506
  // src/migrations/persistent/add-translations.ts
3426
3507
  var import_path = __toESM(require("path"));
@@ -3465,20 +3546,20 @@ function idOf(line2) {
3465
3546
  const comma = line2.indexOf(",");
3466
3547
  return comma === -1 ? line2 : line2.slice(0, comma);
3467
3548
  }
3468
- function readCsvFile(path12) {
3469
- if (!(0, import_fs.existsSync)(path12)) {
3549
+ function readCsvFile(path14) {
3550
+ if (!(0, import_fs.existsSync)(path14)) {
3470
3551
  return void 0;
3471
3552
  }
3472
- const contents = (0, import_fs.readFileSync)(path12, "utf8");
3553
+ const contents = (0, import_fs.readFileSync)(path14, "utf8");
3473
3554
  const newline = contents.includes("\r\n") ? "\r\n" : "\n";
3474
3555
  const trailingNewline = /\r?\n$/.test(contents);
3475
3556
  const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
3476
3557
  const body = lines.slice(1).filter((line2) => line2 !== "");
3477
3558
  return { header: lines[0], body, newline, trailingNewline };
3478
3559
  }
3479
- function writeCsvFile(path12, file) {
3560
+ function writeCsvFile(path14, file) {
3480
3561
  (0, import_fs.writeFileSync)(
3481
- path12,
3562
+ path14,
3482
3563
  [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
3483
3564
  );
3484
3565
  }
@@ -3640,12 +3721,14 @@ async function main(targetVersion) {
3640
3721
  }
3641
3722
 
3642
3723
  // src/migrations/move-declaration-to-declare-action.ts
3724
+ var import_ts_morph2 = require("ts-morph");
3725
+ var import_path3 = __toESM(require("path"));
3726
+
3727
+ // src/migrations/utils.ts
3643
3728
  var import_ts_morph = require("ts-morph");
3644
3729
  var import_path2 = __toESM(require("path"));
3645
3730
  var DEFINE_CONFIG_NAME = "defineConfig";
3646
- var DECLARATION_PROPERTY_NAME = "declaration";
3647
- var ACTIONS_PROPERTY_NAME = "actions";
3648
- var DECLARE_ACTION_TYPE = "DECLARE";
3731
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3649
3732
  function location(node) {
3650
3733
  const relPath = import_path2.default.relative(
3651
3734
  process.cwd(),
@@ -3665,7 +3748,7 @@ function findProperty(literal, name) {
3665
3748
  const property = literal.getProperty(name);
3666
3749
  return import_ts_morph.Node.isPropertyAssignment(property) || import_ts_morph.Node.isShorthandPropertyAssignment(property) ? property : void 0;
3667
3750
  }
3668
- function mayHaveDeclareType(actionType, node) {
3751
+ function mayHaveActionType(actionType, node, expectedActionType) {
3669
3752
  const typeProperty = actionType.getProperty("type");
3670
3753
  if (!typeProperty) {
3671
3754
  return true;
@@ -3673,50 +3756,25 @@ function mayHaveDeclareType(actionType, node) {
3673
3756
  const type = typeProperty.getTypeAtLocation(node);
3674
3757
  const values = type.isUnion() ? type.getUnionTypes() : [type];
3675
3758
  return !values.every(
3676
- (value) => value.isStringLiteral() && value.getLiteralValue() !== DECLARE_ACTION_TYPE
3759
+ (value) => value.isStringLiteral() && value.getLiteralValue() !== expectedActionType
3677
3760
  );
3678
3761
  }
3679
- function mayBeDeclareAction(node) {
3762
+ function mayBeAction(node, actionType) {
3680
3763
  if (import_ts_morph.Node.isObjectLiteralExpression(node)) {
3681
- return isDeclareAction(node);
3764
+ return isAction(node, actionType);
3682
3765
  }
3683
3766
  if (import_ts_morph.Node.isSpreadElement(node)) {
3684
3767
  const arrayType = node.getExpression().getType();
3685
3768
  const elementTypes = arrayType.isTuple() ? arrayType.getTupleElements() : [arrayType.getArrayElementType()];
3686
3769
  return elementTypes.some(
3687
- (elementType) => !elementType || mayHaveDeclareType(elementType, node)
3770
+ (elementType) => !elementType || mayHaveActionType(elementType, node, actionType)
3688
3771
  );
3689
3772
  }
3690
- return mayHaveDeclareType(node.getType(), node);
3773
+ return mayHaveActionType(node.getType(), node, actionType);
3691
3774
  }
3692
- function isDeclareAction(literal) {
3775
+ function isAction(literal, actionType) {
3693
3776
  const type = findProperty(literal, "type");
3694
- return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === DECLARE_ACTION_TYPE;
3695
- }
3696
- function findDeclareAction(config) {
3697
- const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
3698
- const actionsValue = import_ts_morph.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
3699
- if (!import_ts_morph.Node.isArrayLiteralExpression(actionsValue)) {
3700
- console.warn(
3701
- ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`
3702
- );
3703
- return void 0;
3704
- }
3705
- const candidates = actionsValue.getElements().filter(mayBeDeclareAction);
3706
- if (candidates.length !== 1 || !import_ts_morph.Node.isObjectLiteralExpression(candidates[0])) {
3707
- console.warn(
3708
- ` [${location(config)}] Skipped: could not find exactly one ${DECLARE_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME}\`. Move \`${DECLARATION_PROPERTY_NAME}\` onto it by hand.`
3709
- );
3710
- return void 0;
3711
- }
3712
- const declareAction = candidates[0];
3713
- if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
3714
- console.warn(
3715
- ` [${location(config)}] Skipped: \`${DECLARATION_PROPERTY_NAME}\` is set both at the top level and on the ${DECLARE_ACTION_TYPE} action. Keep only the one on the action.`
3716
- );
3717
- return void 0;
3718
- }
3719
- return declareAction;
3777
+ return import_ts_morph.Node.isPropertyAssignment(type) && type.getInitializerOrThrow().getType().getLiteralValue() === actionType;
3720
3778
  }
3721
3779
  function indentationOf(node) {
3722
3780
  const text = node.getSourceFile().getFullText();
@@ -3758,6 +3816,90 @@ function layoutOf(property) {
3758
3816
  function insertAt(position, text) {
3759
3817
  return { start: position, end: position, text };
3760
3818
  }
3819
+ function applyTextEdits(sourceFile, edits) {
3820
+ const text = [...edits].sort((a, b) => b.start - a.start).reduce(
3821
+ (result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end),
3822
+ sourceFile.getFullText()
3823
+ );
3824
+ sourceFile.replaceWithText(text);
3825
+ }
3826
+ function findToolkitImport(sourceFile) {
3827
+ return sourceFile.getImportDeclaration(
3828
+ (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
3829
+ );
3830
+ }
3831
+ function findToolkitImportName(sourceFile, name) {
3832
+ const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === name);
3833
+ if (imported) {
3834
+ return imported.getAliasNode()?.getText() ?? name;
3835
+ }
3836
+ if (sourceFile.getLocal(name)) {
3837
+ return void 0;
3838
+ }
3839
+ return name;
3840
+ }
3841
+ function addToolkitImport(sourceFile, name) {
3842
+ const toolkitImport = findToolkitImport(sourceFile);
3843
+ if (!toolkitImport) {
3844
+ const imports = sourceFile.getImportDeclarations();
3845
+ const lastImport = imports[imports.length - 1];
3846
+ sourceFile.insertStatements(
3847
+ lastImport ? lastImport.getChildIndex() + 1 : 0,
3848
+ `import { ${name} } from '${TOOLKIT_EVENTS_MODULE}'`
3849
+ );
3850
+ return;
3851
+ }
3852
+ const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === name);
3853
+ if (alreadyImported) {
3854
+ return;
3855
+ }
3856
+ const namedImports = toolkitImport.getNamedImports();
3857
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
3858
+ toolkitImport.addNamedImport(name);
3859
+ return;
3860
+ }
3861
+ const names = [
3862
+ ...namedImports.map((namedImport) => namedImport.getText()),
3863
+ name
3864
+ ];
3865
+ const specifiers = toolkitImport.getText().includes("\n") ? `{
3866
+ ${names.join(",\n ")}
3867
+ }` : `{ ${names.join(", ")} }`;
3868
+ toolkitImport.replaceWithText(
3869
+ `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
3870
+ );
3871
+ }
3872
+
3873
+ // src/migrations/move-declaration-to-declare-action.ts
3874
+ var DEFINE_CONFIG_NAME2 = "defineConfig";
3875
+ var DECLARATION_PROPERTY_NAME = "declaration";
3876
+ var ACTIONS_PROPERTY_NAME = "actions";
3877
+ var DECLARE_ACTION_TYPE = "DECLARE";
3878
+ function findDeclareAction(config) {
3879
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME);
3880
+ const actionsValue = import_ts_morph2.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
3881
+ if (!import_ts_morph2.Node.isArrayLiteralExpression(actionsValue)) {
3882
+ console.warn(
3883
+ ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME}\` is not an array literal. Move \`${DECLARATION_PROPERTY_NAME}\` onto the ${DECLARE_ACTION_TYPE} action by hand.`
3884
+ );
3885
+ return void 0;
3886
+ }
3887
+ const candidates = actionsValue.getElements().filter((element) => mayBeAction(element, DECLARE_ACTION_TYPE));
3888
+ if (candidates.length !== 1 || !import_ts_morph2.Node.isObjectLiteralExpression(candidates[0])) {
3889
+ console.warn(
3890
+ ` [${location(config)}] Skipped: could not find exactly one ${DECLARE_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME}\`. Move \`${DECLARATION_PROPERTY_NAME}\` onto it by hand.`
3891
+ );
3892
+ return void 0;
3893
+ }
3894
+ const declareAction = candidates[0];
3895
+ if (findProperty(declareAction, DECLARATION_PROPERTY_NAME)) {
3896
+ console.warn(
3897
+ ` [${location(config)}] Skipped: \`${DECLARATION_PROPERTY_NAME}\` is set both at the top level and on the ${DECLARE_ACTION_TYPE} action. Keep only the one on the action.`
3898
+ );
3899
+ return void 0;
3900
+ }
3901
+ return declareAction;
3902
+ }
3761
3903
  function insertIntoDeclareAction(declareAction, property) {
3762
3904
  const anchor = declareAction.getProperty("label") ?? declareAction.getPropertyOrThrow("type");
3763
3905
  const text = property.getSourceFile().getFullText();
@@ -3794,7 +3936,7 @@ ${indent}` : ", ";
3794
3936
  function removeFromConfig(property) {
3795
3937
  const text = property.getSourceFile().getFullText();
3796
3938
  const layout = layoutOf(property);
3797
- const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph.SyntaxKind.CommaToken);
3939
+ const previousComma = property.getPreviousSiblings().find((sibling) => !isOnlyComments(sibling.getText()))?.asKind(import_ts_morph2.SyntaxKind.CommaToken);
3798
3940
  if (layout.ownsLines) {
3799
3941
  const lines = {
3800
3942
  start: text.lastIndexOf("\n", layout.start - 1),
@@ -3823,18 +3965,18 @@ function removeFromConfig(property) {
3823
3965
  }
3824
3966
  function findConfigLiteral(call) {
3825
3967
  const config = call.getArguments()[0];
3826
- if (!config || import_ts_morph.Node.isObjectLiteralExpression(config)) {
3968
+ if (!config || import_ts_morph2.Node.isObjectLiteralExpression(config)) {
3827
3969
  return config;
3828
3970
  }
3829
3971
  if (config.getType().getProperty(DECLARATION_PROPERTY_NAME)) {
3830
3972
  console.warn(
3831
- ` [${location(config)}] Skipped: \`${DEFINE_CONFIG_NAME}\` is not given an object literal. If its config has a top-level \`${DECLARATION_PROPERTY_NAME}\`, move it onto the ${DECLARE_ACTION_TYPE} action by hand.`
3973
+ ` [${location(config)}] Skipped: \`${DEFINE_CONFIG_NAME2}\` is not given an object literal. If its config has a top-level \`${DECLARATION_PROPERTY_NAME}\`, move it onto the ${DECLARE_ACTION_TYPE} action by hand.`
3832
3974
  );
3833
3975
  }
3834
3976
  return void 0;
3835
3977
  }
3836
3978
  function moveDeclarationToDeclareAction(sourceFile) {
3837
- const configs = sourceFile.getDescendantsOfKind(import_ts_morph.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph.Node.isObjectLiteralExpression);
3979
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral).filter(import_ts_morph2.Node.isObjectLiteralExpression);
3838
3980
  const edits = [];
3839
3981
  let changes = 0;
3840
3982
  for (const config of configs) {
@@ -3858,19 +4000,15 @@ function moveDeclarationToDeclareAction(sourceFile) {
3858
4000
  if (changes === 0) {
3859
4001
  return 0;
3860
4002
  }
3861
- const text = edits.sort((a, b) => b.start - a.start).reduce(
3862
- (result, edit) => result.slice(0, edit.start) + edit.text + result.slice(edit.end),
3863
- sourceFile.getFullText()
3864
- );
3865
- sourceFile.replaceWithText(text);
4003
+ applyTextEdits(sourceFile, edits);
3866
4004
  return changes;
3867
4005
  }
3868
4006
  async function main2() {
3869
- const srcDir = import_path2.default.join(process.cwd(), "src");
4007
+ const srcDir = import_path3.default.join(process.cwd(), "src");
3870
4008
  console.log(`Scanning for top-level event declarations in: ${srcDir}
3871
4009
  `);
3872
- const project = new import_ts_morph.Project({
3873
- tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
4010
+ const project = new import_ts_morph2.Project({
4011
+ tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
3874
4012
  skipAddingFilesFromTsConfig: false
3875
4013
  });
3876
4014
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -3897,7 +4035,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
3897
4035
  for (const sourceFile of modifiedFiles) {
3898
4036
  await sourceFile.save();
3899
4037
  console.log(
3900
- ` Saved: ${import_path2.default.relative(process.cwd(), sourceFile.getFilePath())}`
4038
+ ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
3901
4039
  );
3902
4040
  }
3903
4041
  console.log(
@@ -3906,13 +4044,200 @@ Done. Moved ${totalChanges} declaration(s) across ${modifiedFiles.length} file(s
3906
4044
  );
3907
4045
  }
3908
4046
 
4047
+ // src/migrations/add-notify-config.ts
4048
+ var import_ts_morph3 = require("ts-morph");
4049
+ var import_path4 = __toESM(require("path"));
4050
+ var DEFINE_CONFIG_NAME3 = "defineConfig";
4051
+ var ACTIONS_PROPERTY_NAME2 = "actions";
4052
+ var DECLARATION_PROPERTY_NAME2 = "declaration";
4053
+ var NOTIFY_ACTION_TYPE = "NOTIFY";
4054
+ var DECLARE_ACTION_TYPE2 = "DECLARE";
4055
+ var NOTIFY_PROPERTIES = [
4056
+ {
4057
+ name: "notificationForm",
4058
+ helper: "toNotificationForm",
4059
+ declareProperty: DECLARATION_PROPERTY_NAME2
4060
+ },
4061
+ {
4062
+ name: "review",
4063
+ helper: "toNotificationReview",
4064
+ declareProperty: "review"
4065
+ }
4066
+ ];
4067
+ function referenceOf(property) {
4068
+ if (import_ts_morph3.Node.isShorthandPropertyAssignment(property)) {
4069
+ return property.getName();
4070
+ }
4071
+ const value = property?.getInitializer();
4072
+ return import_ts_morph3.Node.isIdentifier(value) || import_ts_morph3.Node.isPropertyAccessExpression(value) ? value.getText() : void 0;
4073
+ }
4074
+ function findConfigLiteral2(call) {
4075
+ const config = call.getArguments()[0];
4076
+ if (import_ts_morph3.Node.isObjectLiteralExpression(config)) {
4077
+ return config;
4078
+ }
4079
+ console.warn(
4080
+ ` [${location(call)}] Skipped: \`${DEFINE_CONFIG_NAME3}\` is not given an object literal. If the event has a NOTIFY action, give it a \`notificationForm\` and \`review\` by hand.`
4081
+ );
4082
+ return void 0;
4083
+ }
4084
+ function findNotifyAction(config, actions) {
4085
+ const candidates = actions.filter(
4086
+ (action) => mayBeAction(action, NOTIFY_ACTION_TYPE)
4087
+ );
4088
+ if (candidates.length === 0) {
4089
+ console.warn(
4090
+ ` [${location(config)}] No ${NOTIFY_ACTION_TYPE} action: the event cannot be notified. If a role has \`record.notify\` for it, add a ${NOTIFY_ACTION_TYPE} action with a \`notificationForm\` and \`review\`.`
4091
+ );
4092
+ return void 0;
4093
+ }
4094
+ if (candidates.length !== 1 || !import_ts_morph3.Node.isObjectLiteralExpression(candidates[0])) {
4095
+ console.warn(
4096
+ ` [${location(config)}] Skipped: could not find exactly one ${NOTIFY_ACTION_TYPE} action written as an object literal in \`${ACTIONS_PROPERTY_NAME2}\`. Give it a \`notificationForm\` and \`review\` by hand.`
4097
+ );
4098
+ return void 0;
4099
+ }
4100
+ return candidates[0];
4101
+ }
4102
+ function insertIntoAction(action, properties) {
4103
+ const anchor = action.getProperty("label") ?? action.getPropertyOrThrow("type");
4104
+ const text = action.getSourceFile().getFullText();
4105
+ const anchorLayout = layoutOf(anchor);
4106
+ const indent = indentationOf(anchor);
4107
+ if (anchorLayout.ownsLines) {
4108
+ const position = anchorLayout.end + restOfLine(text, anchorLayout.end).length;
4109
+ const lines = properties.map((property) => `
4110
+ ${indent}${property}`);
4111
+ if (anchorLayout.hasComma) {
4112
+ return [insertAt(position, `${lines.join(",")},`)];
4113
+ }
4114
+ return position === anchor.getEnd() ? [insertAt(position, `,${lines.join(",")}`)] : [insertAt(anchor.getEnd(), ","), insertAt(position, lines.join(","))];
4115
+ }
4116
+ const separator = action.getText().includes("\n") ? `,
4117
+ ${indent}` : ", ";
4118
+ return [
4119
+ insertAt(
4120
+ anchor.getEnd(),
4121
+ properties.map((property) => `${separator}${property}`).join("")
4122
+ )
4123
+ ];
4124
+ }
4125
+ function addNotifyConfig(sourceFile) {
4126
+ const configs = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter(isToolkitDefineConfigCall).map(findConfigLiteral2).filter(import_ts_morph3.Node.isObjectLiteralExpression);
4127
+ const helperNames = Object.fromEntries(
4128
+ NOTIFY_PROPERTIES.map(({ helper }) => [
4129
+ helper,
4130
+ findToolkitImportName(sourceFile, helper)
4131
+ ])
4132
+ );
4133
+ const edits = [];
4134
+ const usedHelpers = /* @__PURE__ */ new Set();
4135
+ let changes = 0;
4136
+ for (const config of configs) {
4137
+ const actions = findProperty(config, ACTIONS_PROPERTY_NAME2);
4138
+ const actionsValue = import_ts_morph3.Node.isPropertyAssignment(actions) ? actions.getInitializer() : void 0;
4139
+ if (!import_ts_morph3.Node.isArrayLiteralExpression(actionsValue)) {
4140
+ console.warn(
4141
+ ` [${location(config)}] Skipped: \`${ACTIONS_PROPERTY_NAME2}\` is not an array literal. If the event has a ${NOTIFY_ACTION_TYPE} action, give it a \`notificationForm\` and \`review\` by hand.`
4142
+ );
4143
+ continue;
4144
+ }
4145
+ const notifyAction = findNotifyAction(config, actionsValue.getElements());
4146
+ if (!notifyAction) {
4147
+ continue;
4148
+ }
4149
+ const declareAction = actionsValue.getElements().find(
4150
+ (action) => import_ts_morph3.Node.isObjectLiteralExpression(action) && isAction(action, DECLARE_ACTION_TYPE2)
4151
+ );
4152
+ const properties = NOTIFY_PROPERTIES.filter(
4153
+ ({ name }) => !findProperty(notifyAction, name)
4154
+ ).flatMap(({ name, helper, declareProperty }) => {
4155
+ const helperName = helperNames[helper];
4156
+ const reference = referenceOf(
4157
+ (declareAction && findProperty(declareAction, declareProperty)) ?? (declareProperty === DECLARATION_PROPERTY_NAME2 ? findProperty(config, declareProperty) : void 0)
4158
+ );
4159
+ if (!helperName) {
4160
+ console.warn(
4161
+ ` [${location(notifyAction)}] Skipped \`${name}\`: the file already declares its own \`${helper}\`. Add \`${name}\` to the ${NOTIFY_ACTION_TYPE} action by hand, using the toolkit's \`${helper}\`.`
4162
+ );
4163
+ return [];
4164
+ }
4165
+ if (!reference) {
4166
+ console.warn(
4167
+ ` [${location(notifyAction)}] Skipped \`${name}\`: the ${DECLARE_ACTION_TYPE2} action's \`${declareProperty}\` is not given as a name. Add \`${name}: ${helper}(<${DECLARE_ACTION_TYPE2} ${declareProperty}>)\` to the ${NOTIFY_ACTION_TYPE} action by hand.`
4168
+ );
4169
+ return [];
4170
+ }
4171
+ if (helperName === helper) {
4172
+ usedHelpers.add(helper);
4173
+ }
4174
+ return [`${name}: ${helperName}(${reference})`];
4175
+ });
4176
+ if (properties.length === 0) {
4177
+ continue;
4178
+ }
4179
+ console.log(
4180
+ ` [${location(notifyAction)}] Added \`${properties.join("`, `")}\` to the ${NOTIFY_ACTION_TYPE} action`
4181
+ );
4182
+ edits.push(...insertIntoAction(notifyAction, properties));
4183
+ changes++;
4184
+ }
4185
+ if (changes === 0) {
4186
+ return 0;
4187
+ }
4188
+ applyTextEdits(sourceFile, edits);
4189
+ for (const helper of usedHelpers) {
4190
+ addToolkitImport(sourceFile, helper);
4191
+ }
4192
+ return changes;
4193
+ }
4194
+ async function main3() {
4195
+ const srcDir = import_path4.default.join(process.cwd(), "src");
4196
+ console.log(`Scanning for NOTIFY actions in: ${srcDir}
4197
+ `);
4198
+ const project = new import_ts_morph3.Project({
4199
+ tsConfigFilePath: import_path4.default.resolve(srcDir, "../tsconfig.json"),
4200
+ skipAddingFilesFromTsConfig: false
4201
+ });
4202
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
4203
+ const fp = sf.getFilePath();
4204
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
4205
+ });
4206
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
4207
+ `);
4208
+ let totalChanges = 0;
4209
+ const modifiedFiles = [];
4210
+ for (const sourceFile of sourceFiles) {
4211
+ const changes = addNotifyConfig(sourceFile);
4212
+ if (changes > 0) {
4213
+ totalChanges += changes;
4214
+ modifiedFiles.push(sourceFile);
4215
+ }
4216
+ }
4217
+ if (modifiedFiles.length === 0) {
4218
+ console.log("No NOTIFY actions to update. Nothing to do.");
4219
+ return;
4220
+ }
4221
+ console.log(`
4222
+ Saving ${modifiedFiles.length} modified file(s)...`);
4223
+ for (const sourceFile of modifiedFiles) {
4224
+ await sourceFile.save();
4225
+ console.log(
4226
+ ` Saved: ${import_path4.default.relative(process.cwd(), sourceFile.getFilePath())}`
4227
+ );
4228
+ }
4229
+ console.log(
4230
+ `
4231
+ Done. Updated ${totalChanges} NOTIFY action(s) across ${modifiedFiles.length} file(s).`
4232
+ );
4233
+ }
4234
+
3909
4235
  // src/migrations/read-declaration-through-helper.ts
3910
- var import_ts_morph2 = require("ts-morph");
3911
- var import_path3 = __toESM(require("path"));
4236
+ var import_ts_morph4 = require("ts-morph");
4237
+ var import_path5 = __toESM(require("path"));
3912
4238
  var EVENT_CONFIG_TYPE_NAME = "EventConfig";
3913
- var DECLARATION_PROPERTY_NAME2 = "declaration";
4239
+ var DECLARATION_PROPERTY_NAME3 = "declaration";
3914
4240
  var GET_DECLARATION_NAME = "getDeclaration";
3915
- var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
3916
4241
  function isToolkitEventConfig(type) {
3917
4242
  const nonNullableType = type.getNonNullableType();
3918
4243
  const symbol = nonNullableType.getAliasSymbol() ?? nonNullableType.getSymbol();
@@ -3922,20 +4247,20 @@ function isToolkitEventConfig(type) {
3922
4247
  return symbol.getDeclarations().some((declaration) => declaration.getSourceFile().isDeclarationFile());
3923
4248
  }
3924
4249
  function isDeclarationReadOnEventConfig(node) {
3925
- return node.getName() === DECLARATION_PROPERTY_NAME2 && isToolkitEventConfig(node.getExpression().getType());
4250
+ return node.getName() === DECLARATION_PROPERTY_NAME3 && isToolkitEventConfig(node.getExpression().getType());
3926
4251
  }
3927
4252
  function isAssignmentOperator(kind) {
3928
- return kind >= import_ts_morph2.SyntaxKind.FirstAssignment && kind <= import_ts_morph2.SyntaxKind.LastAssignment;
4253
+ return kind >= import_ts_morph4.SyntaxKind.FirstAssignment && kind <= import_ts_morph4.SyntaxKind.LastAssignment;
3929
4254
  }
3930
4255
  function isWriteTarget(node) {
3931
4256
  const parent = node.getParent();
3932
- if (import_ts_morph2.Node.isDeleteExpression(parent)) {
4257
+ if (import_ts_morph4.Node.isDeleteExpression(parent)) {
3933
4258
  return true;
3934
4259
  }
3935
- return import_ts_morph2.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
4260
+ return import_ts_morph4.Node.isBinaryExpression(parent) && parent.getLeft() === node && isAssignmentOperator(parent.getOperatorToken().getKind());
3936
4261
  }
3937
4262
  function location2(node) {
3938
- const relPath = import_path3.default.relative(
4263
+ const relPath = import_path5.default.relative(
3939
4264
  process.cwd(),
3940
4265
  node.getSourceFile().getFilePath()
3941
4266
  );
@@ -3943,86 +4268,40 @@ function location2(node) {
3943
4268
  }
3944
4269
  function warnDestructuredDeclarations(sourceFile) {
3945
4270
  for (const pattern of sourceFile.getDescendantsOfKind(
3946
- import_ts_morph2.SyntaxKind.ObjectBindingPattern
4271
+ import_ts_morph4.SyntaxKind.ObjectBindingPattern
3947
4272
  )) {
3948
4273
  const destructuresDeclaration = pattern.getElements().some(
3949
- (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME2
4274
+ (element) => (element.getPropertyNameNode()?.getText() ?? element.getName()) === DECLARATION_PROPERTY_NAME3
3950
4275
  );
3951
4276
  if (destructuresDeclaration && isToolkitEventConfig(pattern.getType())) {
3952
4277
  console.warn(
3953
- ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME2}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
4278
+ ` [${location2(pattern)}] Destructures \`${DECLARATION_PROPERTY_NAME3}\` from an EventConfig. Rewrite it to use \`${GET_DECLARATION_NAME}(config)\` by hand.`
3954
4279
  );
3955
4280
  }
3956
4281
  }
3957
4282
  }
3958
4283
  function warnSpreadDeclarations(sourceFile) {
3959
4284
  for (const literal of sourceFile.getDescendantsOfKind(
3960
- import_ts_morph2.SyntaxKind.ObjectLiteralExpression
4285
+ import_ts_morph4.SyntaxKind.ObjectLiteralExpression
3961
4286
  )) {
3962
4287
  const properties = literal.getProperties();
3963
4288
  const spreadsEventConfig = properties.some(
3964
- (property) => import_ts_morph2.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
4289
+ (property) => import_ts_morph4.Node.isSpreadAssignment(property) && isToolkitEventConfig(property.getExpression().getType())
3965
4290
  );
3966
4291
  const setsDeclaration = properties.some(
3967
- (property) => (import_ts_morph2.Node.isPropertyAssignment(property) || import_ts_morph2.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME2
4292
+ (property) => (import_ts_morph4.Node.isPropertyAssignment(property) || import_ts_morph4.Node.isShorthandPropertyAssignment(property)) && property.getName() === DECLARATION_PROPERTY_NAME3
3968
4293
  );
3969
4294
  if (spreadsEventConfig && setsDeclaration) {
3970
4295
  console.warn(
3971
- ` [${location2(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME2}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME2}\` on its DECLARE action, so replace that one by hand.`
4296
+ ` [${location2(literal)}] Spreads an EventConfig and sets \`${DECLARATION_PROPERTY_NAME3}\` next to it. The spread config already has a \`${DECLARATION_PROPERTY_NAME3}\` on its DECLARE action, so replace that one by hand.`
3972
4297
  );
3973
4298
  }
3974
4299
  }
3975
4300
  }
3976
- function findToolkitImport(sourceFile) {
3977
- return sourceFile.getImportDeclaration(
3978
- (declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE && !declaration.isTypeOnly() && !declaration.getNamespaceImport()
3979
- );
3980
- }
3981
- function findGetDeclarationName(sourceFile) {
3982
- const imported = findToolkitImport(sourceFile)?.getNamedImports().find((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
3983
- if (imported) {
3984
- return imported.getAliasNode()?.getText() ?? GET_DECLARATION_NAME;
3985
- }
3986
- if (sourceFile.getLocal(GET_DECLARATION_NAME)) {
3987
- return void 0;
3988
- }
3989
- return GET_DECLARATION_NAME;
3990
- }
3991
- function addGetDeclarationImport(sourceFile) {
3992
- const toolkitImport = findToolkitImport(sourceFile);
3993
- if (!toolkitImport) {
3994
- const imports = sourceFile.getImportDeclarations();
3995
- const lastImport = imports[imports.length - 1];
3996
- sourceFile.insertStatements(
3997
- lastImport ? lastImport.getChildIndex() + 1 : 0,
3998
- `import { ${GET_DECLARATION_NAME} } from '${TOOLKIT_EVENTS_MODULE}'`
3999
- );
4000
- return;
4001
- }
4002
- const alreadyImported = toolkitImport.getNamedImports().some((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
4003
- if (alreadyImported) {
4004
- return;
4005
- }
4006
- const namedImports = toolkitImport.getNamedImports();
4007
- if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
4008
- toolkitImport.addNamedImport(GET_DECLARATION_NAME);
4009
- return;
4010
- }
4011
- const names = [
4012
- ...namedImports.map((namedImport) => namedImport.getText()),
4013
- GET_DECLARATION_NAME
4014
- ];
4015
- const specifiers = toolkitImport.getText().includes("\n") ? `{
4016
- ${names.join(",\n ")}
4017
- }` : `{ ${names.join(", ")} }`;
4018
- toolkitImport.replaceWithText(
4019
- `import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`
4020
- );
4021
- }
4022
4301
  function rewriteDeclarationReads(sourceFile) {
4023
4302
  warnDestructuredDeclarations(sourceFile);
4024
4303
  warnSpreadDeclarations(sourceFile);
4025
- const reads = sourceFile.getDescendantsOfKind(import_ts_morph2.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
4304
+ const reads = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAccessExpression).filter(isDeclarationReadOnEventConfig).filter((node) => {
4026
4305
  if (node.hasQuestionDotToken()) {
4027
4306
  console.warn(
4028
4307
  ` [${location2(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${GET_DECLARATION_NAME}()\` by hand.`
@@ -4031,7 +4310,7 @@ function rewriteDeclarationReads(sourceFile) {
4031
4310
  }
4032
4311
  if (isWriteTarget(node)) {
4033
4312
  console.warn(
4034
- ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME2}\` on the DECLARE action instead.`
4313
+ ` [${location2(node)}] Skipped write to \`${node.getText()}\`. Set \`${DECLARATION_PROPERTY_NAME3}\` on the DECLARE action instead.`
4035
4314
  );
4036
4315
  return false;
4037
4316
  }
@@ -4040,7 +4319,10 @@ function rewriteDeclarationReads(sourceFile) {
4040
4319
  if (reads.length === 0) {
4041
4320
  return 0;
4042
4321
  }
4043
- const getDeclarationName = findGetDeclarationName(sourceFile);
4322
+ const getDeclarationName = findToolkitImportName(
4323
+ sourceFile,
4324
+ GET_DECLARATION_NAME
4325
+ );
4044
4326
  if (!getDeclarationName) {
4045
4327
  console.warn(
4046
4328
  ` [${location2(reads[reads.length - 1])}] Skipped ${reads.length} read(s): the file already declares its own \`${GET_DECLARATION_NAME}\`. Rewrite them to use the toolkit's \`${GET_DECLARATION_NAME}()\` by hand.`
@@ -4055,15 +4337,15 @@ function rewriteDeclarationReads(sourceFile) {
4055
4337
  `${getDeclarationName}(${read.getExpression().getText()})`
4056
4338
  );
4057
4339
  }
4058
- addGetDeclarationImport(sourceFile);
4340
+ addToolkitImport(sourceFile, GET_DECLARATION_NAME);
4059
4341
  return reads.length;
4060
4342
  }
4061
- async function main3() {
4062
- const srcDir = import_path3.default.join(process.cwd(), "src");
4343
+ async function main4() {
4344
+ const srcDir = import_path5.default.join(process.cwd(), "src");
4063
4345
  console.log(`Scanning for EventConfig declaration reads in: ${srcDir}
4064
4346
  `);
4065
- const project = new import_ts_morph2.Project({
4066
- tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
4347
+ const project = new import_ts_morph4.Project({
4348
+ tsConfigFilePath: import_path5.default.resolve(srcDir, "../tsconfig.json"),
4067
4349
  skipAddingFilesFromTsConfig: false
4068
4350
  });
4069
4351
  const sourceFiles = project.getSourceFiles().filter((sf) => {
@@ -4090,7 +4372,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
4090
4372
  for (const sourceFile of modifiedFiles) {
4091
4373
  await sourceFile.save();
4092
4374
  console.log(
4093
- ` Saved: ${import_path3.default.relative(process.cwd(), sourceFile.getFilePath())}`
4375
+ ` Saved: ${import_path5.default.relative(process.cwd(), sourceFile.getFilePath())}`
4094
4376
  );
4095
4377
  }
4096
4378
  console.log(
@@ -4101,11 +4383,11 @@ Done. Rewrote ${totalChanges} declaration read(s) across ${modifiedFiles.length}
4101
4383
 
4102
4384
  // src/migrations/persistent/update-toolkit-dependency.ts
4103
4385
  var import_fs3 = __toESM(require("fs"));
4104
- var import_path5 = __toESM(require("path"));
4386
+ var import_path7 = __toESM(require("path"));
4105
4387
 
4106
4388
  // src/migrations/persistent/check-upgrade-path.ts
4107
4389
  var import_fs2 = __toESM(require("fs"));
4108
- var import_path4 = __toESM(require("path"));
4390
+ var import_path6 = __toESM(require("path"));
4109
4391
  var TOOLKIT_PACKAGE_NAME = "@opencrvs/toolkit";
4110
4392
  function findMajorMinor(version) {
4111
4393
  const match = /(\d+)\.(\d+)/.exec(version);
@@ -4117,7 +4399,7 @@ function format({ major, minor }) {
4117
4399
  function findCountryConfigToolkitVersion(cwd) {
4118
4400
  try {
4119
4401
  const packageJson = JSON.parse(
4120
- import_fs2.default.readFileSync(import_path4.default.join(cwd, "package.json"), "utf-8")
4402
+ import_fs2.default.readFileSync(import_path6.default.join(cwd, "package.json"), "utf-8")
4121
4403
  );
4122
4404
  return packageJson.dependencies?.[TOOLKIT_PACKAGE_NAME] ?? packageJson.devDependencies?.[TOOLKIT_PACKAGE_NAME];
4123
4405
  } catch {
@@ -4172,8 +4454,8 @@ function updateToolkitDependency(packageJson, toolkitVersion) {
4172
4454
  );
4173
4455
  return updated === packageJson ? void 0 : updated;
4174
4456
  }
4175
- async function main4(toolkitVersion) {
4176
- const packageJsonPath = import_path5.default.join(process.cwd(), "package.json");
4457
+ async function main5(toolkitVersion) {
4458
+ const packageJsonPath = import_path7.default.join(process.cwd(), "package.json");
4177
4459
  if (!import_fs3.default.existsSync(packageJsonPath)) {
4178
4460
  console.log(`No package.json found. Skipping ${TOOLKIT_PACKAGE_NAME}.`);
4179
4461
  return;
@@ -4195,8 +4477,8 @@ async function main4(toolkitVersion) {
4195
4477
  }
4196
4478
 
4197
4479
  // src/migrations/replace-incomplete-flag.ts
4198
- var import_ts_morph3 = require("ts-morph");
4199
- var import_path6 = __toESM(require("path"));
4480
+ var import_ts_morph5 = require("ts-morph");
4481
+ var import_path8 = __toESM(require("path"));
4200
4482
  var INCOMPLETE = "InherentFlags.INCOMPLETE";
4201
4483
  var NOTIFIED_STATUS = `{ type: 'exact', term: EventStatus.enum.NOTIFIED }`;
4202
4484
  function ensureEventStatusImport(sourceFile) {
@@ -4210,21 +4492,21 @@ function ensureEventStatusImport(sourceFile) {
4210
4492
  }
4211
4493
  function replaceIncompleteFlag(sourceFile) {
4212
4494
  let changed = false;
4213
- const anyOfIncomplete = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getParent()).filter(import_ts_morph3.Node.isArrayLiteralExpression).filter((array2) => {
4495
+ const anyOfIncomplete = sourceFile.getDescendantsOfKind(import_ts_morph5.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getParent()).filter(import_ts_morph5.Node.isArrayLiteralExpression).filter((array2) => {
4214
4496
  const anyOf = array2.getParent();
4215
4497
  const flags = anyOf?.getParent()?.getParent();
4216
- return import_ts_morph3.Node.isPropertyAssignment(anyOf) && anyOf.getName() === "anyOf" && import_ts_morph3.Node.isPropertyAssignment(flags) && flags.getName() === "flags";
4498
+ return import_ts_morph5.Node.isPropertyAssignment(anyOf) && anyOf.getName() === "anyOf" && import_ts_morph5.Node.isPropertyAssignment(flags) && flags.getName() === "flags";
4217
4499
  });
4218
4500
  for (const array2 of anyOfIncomplete) {
4219
- const anyOf = array2.getParentIfKindOrThrow(import_ts_morph3.SyntaxKind.PropertyAssignment);
4501
+ const anyOf = array2.getParentIfKindOrThrow(import_ts_morph5.SyntaxKind.PropertyAssignment);
4220
4502
  const flagsObject = anyOf.getParentIfKindOrThrow(
4221
- import_ts_morph3.SyntaxKind.ObjectLiteralExpression
4503
+ import_ts_morph5.SyntaxKind.ObjectLiteralExpression
4222
4504
  );
4223
4505
  const flags = flagsObject.getParentIfKindOrThrow(
4224
- import_ts_morph3.SyntaxKind.PropertyAssignment
4506
+ import_ts_morph5.SyntaxKind.PropertyAssignment
4225
4507
  );
4226
4508
  const query = flags.getParentIfKindOrThrow(
4227
- import_ts_morph3.SyntaxKind.ObjectLiteralExpression
4509
+ import_ts_morph5.SyntaxKind.ObjectLiteralExpression
4228
4510
  );
4229
4511
  array2.getElements().filter((element) => element.getText() === INCOMPLETE).forEach((element) => array2.removeElement(element));
4230
4512
  if (array2.getElements().length === 0) anyOf.remove();
@@ -4238,16 +4520,16 @@ function replaceIncompleteFlag(sourceFile) {
4238
4520
  changed = true;
4239
4521
  }
4240
4522
  if (changed) ensureEventStatusImport(sourceFile);
4241
- const remaining = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
4523
+ const remaining = sourceFile.getDescendantsOfKind(import_ts_morph5.SyntaxKind.PropertyAccessExpression).filter((node) => node.getText() === INCOMPLETE).map((node) => node.getStartLineNumber());
4242
4524
  return { changed, remaining };
4243
4525
  }
4244
- async function main5() {
4245
- const project = new import_ts_morph3.Project({
4246
- tsConfigFilePath: import_path6.default.join(process.cwd(), "tsconfig.json")
4526
+ async function main6() {
4527
+ const project = new import_ts_morph5.Project({
4528
+ tsConfigFilePath: import_path8.default.join(process.cwd(), "tsconfig.json")
4247
4529
  });
4248
4530
  const sourceFiles = project.getSourceFiles().filter((sf) => !sf.getFilePath().includes("/node_modules/"));
4249
4531
  for (const sourceFile of sourceFiles) {
4250
- const relPath = import_path6.default.relative(process.cwd(), sourceFile.getFilePath());
4532
+ const relPath = import_path8.default.relative(process.cwd(), sourceFile.getFilePath());
4251
4533
  const { changed, remaining } = replaceIncompleteFlag(sourceFile);
4252
4534
  if (changed) {
4253
4535
  await sourceFile.save();
@@ -4268,14 +4550,15 @@ async function runUpgrade(toolkitVersion) {
4268
4550
  const [major, minor] = toolkitVersion.split(".");
4269
4551
  await main2();
4270
4552
  await main3();
4553
+ await main4();
4271
4554
  await main(`${major}.${minor}`);
4272
- await main5();
4273
- await main4(toolkitVersion);
4555
+ await main6();
4556
+ await main5(toolkitVersion);
4274
4557
  }
4275
4558
 
4276
4559
  // src/environment/index.ts
4277
4560
  var import_fs8 = require("fs");
4278
- var import_path11 = require("path");
4561
+ var import_path13 = require("path");
4279
4562
  init_paths();
4280
4563
  var REQUIRED_REPOSITORY_DIRECTORIES = [
4281
4564
  ".github/workflows",
@@ -4286,7 +4569,7 @@ function validateRepositoryStructure(repositoryRoot = process.cwd()) {
4286
4569
  const missingDirectories = REQUIRED_REPOSITORY_DIRECTORIES.filter(
4287
4570
  (directory) => {
4288
4571
  try {
4289
- return !(0, import_fs8.statSync)((0, import_path11.resolve)(repositoryRoot, directory)).isDirectory();
4572
+ return !(0, import_fs8.statSync)((0, import_path13.resolve)(repositoryRoot, directory)).isDirectory();
4290
4573
  } catch {
4291
4574
  return true;
4292
4575
  }
@@ -4613,8 +4896,8 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4613
4896
  console.log(line(ok, endpointLabel(check), detail));
4614
4897
  }
4615
4898
  {
4616
- const path12 = `/fonts/${PROBE_SEGMENT}.ttf`;
4617
- const status = await requestStatus(`${baseUrl}${path12}`, "GET");
4899
+ const path14 = `/fonts/${PROBE_SEGMENT}.ttf`;
4900
+ const status = await requestStatus(`${baseUrl}${path14}`, "GET");
4618
4901
  const ok = status === 200 || status === 404;
4619
4902
  if (!ok) {
4620
4903
  failures++;
@@ -4629,7 +4912,7 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4629
4912
  } else {
4630
4913
  detail = `${describeStatus(status)} \u2014 unexpected`;
4631
4914
  }
4632
- console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path12}`)}`, detail));
4915
+ console.log(line(ok, `GET /fonts/{filename}${(0, import_colors.dim)(` \u2192 ${path14}`)}`, detail));
4633
4916
  }
4634
4917
  console.log();
4635
4918
  console.log((0, import_colors.bold)("Secured endpoints (must be absent or require auth):"));
@@ -4682,13 +4965,13 @@ async function runVerifyEndpoints(target = DEFAULT_TARGET_URL) {
4682
4965
  line(true, pattern, `${actions.length} action(s) \u2014 all require auth`)
4683
4966
  );
4684
4967
  } else {
4685
- for (const failure of failed) {
4968
+ for (const failure2 of failed) {
4686
4969
  failures++;
4687
4970
  console.log(
4688
4971
  line(
4689
4972
  false,
4690
- `POST /trigger/events/${event.id}/actions/${failure.action}`,
4691
- securedDetail(failure.status)
4973
+ `POST /trigger/events/${event.id}/actions/${failure2.action}`,
4974
+ securedDetail(failure2.status)
4692
4975
  )
4693
4976
  );
4694
4977
  }
@@ -4769,7 +5052,7 @@ Run it without changing the dependency first, e.g.
4769
5052
  Options:
4770
5053
  -h, --help Show this message.
4771
5054
  `.trim();
4772
- function main6() {
5055
+ function main7() {
4773
5056
  const command = args[0];
4774
5057
  if (!command || command === "--help" || command === "-h") {
4775
5058
  console.log(USAGE);
@@ -4841,7 +5124,7 @@ async function runEnvironmentCommand(operation, command) {
4841
5124
  }
4842
5125
  function readToolkitVersion() {
4843
5126
  const packageJson = JSON.parse(
4844
- import_fs9.default.readFileSync(import_path12.default.join(__dirname, "..", "package.json"), "utf-8")
5127
+ import_fs9.default.readFileSync(import_path14.default.join(__dirname, "..", "package.json"), "utf-8")
4845
5128
  );
4846
5129
  return packageJson.version;
4847
5130
  }
@@ -4905,4 +5188,4 @@ async function handleVerifyEndpoints() {
4905
5188
  process.exit(1);
4906
5189
  }
4907
5190
  }
4908
- main6();
5191
+ main7();