@opencrvs/toolkit 2.1.0-rc.12673aa → 2.1.0-rc.14fb6a5

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 (188) hide show
  1. package/build.sh +14 -4
  2. package/create-countryconfig/index.js +59 -30
  3. package/dist/application-config/index.js +26 -13
  4. package/dist/authentication/index.d.ts +8 -9
  5. package/dist/authentication/index.js +23 -8
  6. package/dist/cli.js +2268 -1385
  7. package/dist/commons/api/router.d.ts +252 -290
  8. package/dist/commons/application-config/index.d.ts +0 -2
  9. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  10. package/dist/commons/conditionals/validate.d.ts +18 -3
  11. package/dist/commons/events/ActionConfig.d.ts +5 -14
  12. package/dist/commons/events/ActionDocument.d.ts +30 -4
  13. package/dist/commons/events/AdvancedSearchConfig.d.ts +24 -12
  14. package/dist/commons/events/AuditLog.d.ts +1 -0
  15. package/dist/commons/events/Draft.d.ts +1 -21
  16. package/dist/commons/events/EventDocument.d.ts +4 -4
  17. package/dist/commons/events/FieldConfig.d.ts +20 -10
  18. package/dist/commons/events/FieldTypeMapping.d.ts +10 -10
  19. package/dist/commons/events/FieldValue.d.ts +1 -0
  20. package/dist/commons/events/FormConfig.d.ts +6 -0
  21. package/dist/commons/events/PageConfig.d.ts +4 -0
  22. package/dist/commons/events/scopes.d.ts +21 -1
  23. package/dist/commons/events/test.utils.d.ts +53 -21
  24. package/dist/commons/events/utils.d.ts +26 -2
  25. package/dist/conditionals/index.js +21 -7
  26. package/dist/environment/index.d.ts.map +1 -1
  27. package/dist/environment/index.js +2 -1
  28. package/dist/environment/setup-environment.d.ts +1 -1
  29. package/dist/environment/setup-environment.d.ts.map +1 -1
  30. package/dist/environment/setup-environment.js +586 -569
  31. package/dist/environment/swarm-to-k8s.js +3 -4
  32. package/dist/events/index.js +282 -138
  33. package/dist/migrations/v2.1/add-recovery-link-notifications.js +4 -4
  34. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -1
  35. package/dist/migrations/v2.1/add-translations.js +4 -68
  36. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -1
  37. package/dist/migrations/v2.1/enable-telemetry.js +30 -13
  38. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  39. package/dist/migrations/v2.1/index.js +927 -33
  40. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +14 -0
  41. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +1 -0
  42. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +348 -0
  43. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +2 -0
  44. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +1 -0
  45. package/dist/migrations/v2.1/remove-metabase-package-installs.js +161 -0
  46. package/dist/migrations/{v2.0/migrate-scopes.d.ts → v2.1/remove-sentry.d.ts} +1 -1
  47. package/dist/migrations/v2.1/remove-sentry.d.ts.map +1 -0
  48. package/dist/migrations/v2.1/remove-sentry.js +354 -0
  49. package/dist/migrations/{v2.0/rename-api-paths.d.ts → v2.1/rename-trigger-paths.d.ts} +1 -1
  50. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +1 -0
  51. package/dist/migrations/{v2.0/rename-api-paths.js → v2.1/rename-trigger-paths.js} +69 -40
  52. package/dist/migrations/v2.1/template-files.d.ts +8 -0
  53. package/dist/migrations/v2.1/template-files.d.ts.map +1 -0
  54. package/dist/migrations/v2.1/template-files.js +49 -0
  55. package/dist/migrations/v2.1/upgrade-tilt.d.ts +8 -0
  56. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +1 -0
  57. package/dist/migrations/v2.1/upgrade-tilt.js +139 -0
  58. package/dist/notification/index.js +105 -61
  59. package/dist/scopes/index.d.ts +288 -5
  60. package/dist/scopes/index.js +22 -7
  61. package/dist/telemetry/index.js +4 -0
  62. package/dist/templates/charts-values/dependencies/values.yaml +6 -0
  63. package/dist/templates/charts-values/opencrvs-services/values.yaml +6 -0
  64. package/dist/templates/charts-values/opentelemetry/values.yaml +7 -0
  65. package/dist/templates/countryconfig-template/.tiltignore +1 -0
  66. package/dist/templates/countryconfig-template/Dockerfile.assets +7 -0
  67. package/dist/templates/countryconfig-template/Tiltfile +112 -0
  68. package/dist/templates/countryconfig-template/assets/README.md +1 -0
  69. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +61 -0
  70. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +455 -0
  71. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +168 -0
  72. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +67 -0
  73. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +168 -0
  74. package/dist/templates/countryconfig-template/assets/metabase/README.md +34 -0
  75. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +36 -0
  76. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +46 -0
  77. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +27737 -0
  78. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +21 -0
  79. package/dist/templates/countryconfig-template/assets/metabase/package.json +13 -0
  80. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +108 -0
  81. package/dist/templates/countryconfig-template/assets/metabase/run.sh +120 -0
  82. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +40 -0
  83. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +135 -0
  84. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +108 -0
  85. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +50 -0
  86. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +35 -0
  87. package/dist/templates/countryconfig-template/tilt/common.tilt +145 -0
  88. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +15 -0
  89. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +56 -0
  90. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +21 -0
  91. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +38 -0
  92. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +17 -0
  93. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +16 -0
  94. package/dist/templates/countryconfig-template/tilt/lib.tilt +95 -0
  95. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +136 -0
  96. package/dist/translations/template.d.ts +11 -0
  97. package/dist/translations/template.d.ts.map +1 -0
  98. package/dist/translations/template.js +100 -0
  99. package/dist/verify/endpoints.d.ts.map +1 -1
  100. package/dist/verify/endpoints.js +179 -14
  101. package/opencrvs-toolkit-2.1.0-rc.14fb6a5.tgz +0 -0
  102. package/package.json +2 -1
  103. package/tsconfig.build.tsbuildinfo +1 -1
  104. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts +0 -3
  105. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +0 -1
  106. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +0 -429
  107. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts +0 -3
  108. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts.map +0 -1
  109. package/dist/migrations/v2.0/add-resend-invite-notification.js +0 -373
  110. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +0 -22
  111. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +0 -1
  112. package/dist/migrations/v2.0/checkout-upstream-files.js +0 -146
  113. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts +0 -2
  114. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +0 -1
  115. package/dist/migrations/v2.0/convert-config-files-to-ts.js +0 -838
  116. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts +0 -3
  117. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +0 -1
  118. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +0 -158
  119. package/dist/migrations/v2.0/create-events-index.d.ts +0 -3
  120. package/dist/migrations/v2.0/create-events-index.d.ts.map +0 -1
  121. package/dist/migrations/v2.0/create-events-index.js +0 -325
  122. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +0 -11
  123. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +0 -1
  124. package/dist/migrations/v2.0/delete-infrastructure-directory.js +0 -123
  125. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +0 -3
  126. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +0 -1
  127. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +0 -110
  128. package/dist/migrations/v2.0/index.d.ts +0 -13
  129. package/dist/migrations/v2.0/index.d.ts.map +0 -1
  130. package/dist/migrations/v2.0/index.js +0 -103
  131. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts +0 -3
  132. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +0 -1
  133. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +0 -432
  134. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +0 -13
  135. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +0 -1
  136. package/dist/migrations/v2.0/merge-infrastructure-directory.js +0 -222
  137. package/dist/migrations/v2.0/migrate-application-config-url.d.ts +0 -3
  138. package/dist/migrations/v2.0/migrate-application-config-url.d.ts.map +0 -1
  139. package/dist/migrations/v2.0/migrate-application-config-url.js +0 -343
  140. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +0 -1
  141. package/dist/migrations/v2.0/migrate-scopes.js +0 -305
  142. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts +0 -3
  143. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +0 -1
  144. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +0 -267
  145. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts +0 -3
  146. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +0 -1
  147. package/dist/migrations/v2.0/migrate-workqueue-configs.js +0 -317
  148. package/dist/migrations/v2.0/remove-delete-actions.d.ts +0 -3
  149. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +0 -1
  150. package/dist/migrations/v2.0/remove-delete-actions.js +0 -156
  151. package/dist/migrations/v2.0/remove-demo-scope.d.ts +0 -3
  152. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +0 -1
  153. package/dist/migrations/v2.0/remove-demo-scope.js +0 -74
  154. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts +0 -3
  155. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +0 -1
  156. package/dist/migrations/v2.0/remove-deprecated-imports.js +0 -96
  157. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts +0 -3
  158. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts.map +0 -1
  159. package/dist/migrations/v2.0/remove-fhir-url-helpers.js +0 -163
  160. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts +0 -3
  161. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +0 -1
  162. package/dist/migrations/v2.0/remove-hearth-migrations.js +0 -87
  163. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts +0 -3
  164. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts.map +0 -1
  165. package/dist/migrations/v2.0/remove-old-statistics-service.js +0 -356
  166. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts +0 -3
  167. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +0 -1
  168. package/dist/migrations/v2.0/remove-pending-certification-flag.js +0 -109
  169. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts +0 -3
  170. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +0 -1
  171. package/dist/migrations/v2.0/remove-review-from-register-action.js +0 -163
  172. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts +0 -3
  173. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts.map +0 -1
  174. package/dist/migrations/v2.0/remove-unused-environment-variables.js +0 -186
  175. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +0 -1
  176. package/dist/migrations/v2.0/rename-location-parent-id.d.ts +0 -3
  177. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +0 -1
  178. package/dist/migrations/v2.0/rename-location-parent-id.js +0 -180
  179. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts +0 -3
  180. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +0 -1
  181. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +0 -195
  182. package/dist/migrations/v2.0/update-package-json.d.ts +0 -3
  183. package/dist/migrations/v2.0/update-package-json.d.ts.map +0 -1
  184. package/dist/migrations/v2.0/update-package-json.js +0 -105
  185. package/dist/translations/check.d.ts +0 -21
  186. package/dist/translations/check.d.ts.map +0 -1
  187. package/dist/translations/check.js +0 -132
  188. package/opencrvs-toolkit-2.1.0-rc.12673aa.tgz +0 -0
@@ -257,20 +257,20 @@ function idOf(line) {
257
257
  const comma = line.indexOf(",");
258
258
  return comma === -1 ? line : line.slice(0, comma);
259
259
  }
260
- function readCsvFile(path5) {
261
- if (!(0, import_fs.existsSync)(path5)) {
260
+ function readCsvFile(path10) {
261
+ if (!(0, import_fs.existsSync)(path10)) {
262
262
  return void 0;
263
263
  }
264
- const contents = (0, import_fs.readFileSync)(path5, "utf8");
264
+ const contents = (0, import_fs.readFileSync)(path10, "utf8");
265
265
  const newline = contents.includes("\r\n") ? "\r\n" : "\n";
266
266
  const trailingNewline = /\r?\n$/.test(contents);
267
267
  const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
268
268
  const body = lines.slice(1).filter((line) => line !== "");
269
269
  return { header: lines[0], body, newline, trailingNewline };
270
270
  }
271
- function writeCsvFile(path5, file) {
271
+ function writeCsvFile(path10, file) {
272
272
  (0, import_fs.writeFileSync)(
273
- path5,
273
+ path10,
274
274
  [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
275
275
  );
276
276
  }
@@ -582,10 +582,10 @@ function updateRoutes(project, cwd) {
582
582
  return;
583
583
  }
584
584
  for (const event of RECOVERY_EVENTS) {
585
- if (routesArray.getText().includes(`/triggers/user/${event.id}`)) continue;
585
+ if (routesArray.getText().includes(`/trigger/user/${event.id}`)) continue;
586
586
  routesArray.addElement(`{
587
587
  method: 'POST',
588
- path: '/triggers/user/${event.id}',
588
+ path: '/trigger/user/${event.id}',
589
589
  handler: makeNotificationHandler('${event.id}'),
590
590
  options: {
591
591
  auth: false,
@@ -593,7 +593,7 @@ function updateRoutes(project, cwd) {
593
593
  description: '${event.routeDescription}'
594
594
  }
595
595
  }`);
596
- console.log(` \u2713 ${ROUTES_FILE}: POST /triggers/user/${event.id}`);
596
+ console.log(` \u2713 ${ROUTES_FILE}: POST /trigger/user/${event.id}`);
597
597
  }
598
598
  }
599
599
  function renderEmailTemplate(event) {
@@ -741,15 +741,10 @@ async function main2() {
741
741
 
742
742
  // src/migrations/v2.1/add-translations.ts
743
743
  var import_path3 = __toESM(require("path"));
744
+
745
+ // src/translations/template.ts
744
746
  var REPOSITORY = "opencrvs/opencrvs-core";
745
747
  var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
746
- var APPLICATIONS = ["client", "login"];
747
- var TARGET_VERSION = "2.1";
748
- var skipped2 = [];
749
- function warnSkipped2(message) {
750
- skipped2.push(message);
751
- console.warn(` \u26A0\uFE0F ${message}`);
752
- }
753
748
  async function matchingRefs(namespace, prefix) {
754
749
  const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
755
750
  const response = await fetch(url, {
@@ -764,10 +759,10 @@ async function matchingRefs(namespace, prefix) {
764
759
  const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
765
760
  return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
766
761
  }
767
- async function candidateRefs() {
762
+ async function candidateRefs(version) {
768
763
  return [
769
- ...await matchingRefs("heads", `release/${TARGET_VERSION}.`),
770
- ...await matchingRefs("tags", `v${TARGET_VERSION}.`),
764
+ ...await matchingRefs("heads", `release/${version}.`),
765
+ ...await matchingRefs("tags", `v${version}.`),
771
766
  "develop"
772
767
  ];
773
768
  }
@@ -784,11 +779,17 @@ async function fetchTemplate(refs, application) {
784
779
  );
785
780
  }
786
781
  }
787
- warnSkipped2(
788
- `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
789
- );
790
782
  return void 0;
791
783
  }
784
+
785
+ // src/migrations/v2.1/add-translations.ts
786
+ var APPLICATIONS = ["client", "login"];
787
+ var TARGET_VERSION = "2.1";
788
+ var skipped2 = [];
789
+ function warnSkipped2(message) {
790
+ skipped2.push(message);
791
+ console.warn(` \u26A0\uFE0F ${message}`);
792
+ }
792
793
  function rowsToAdd(local, template) {
793
794
  const localColumns = parseCsvLine(local.header);
794
795
  const templateColumns = parseCsvLine(template.header);
@@ -811,6 +812,9 @@ async function updateApplication(cwd, refs, application) {
811
812
  }
812
813
  const fetched = await fetchTemplate(refs, application);
813
814
  if (!fetched) {
815
+ warnSkipped2(
816
+ `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
817
+ );
814
818
  return;
815
819
  }
816
820
  const template = readTemplate(fetched.contents);
@@ -841,7 +845,7 @@ function readTemplate(contents) {
841
845
  }
842
846
  async function listRefs() {
843
847
  try {
844
- return await candidateRefs();
848
+ return await candidateRefs(TARGET_VERSION);
845
849
  } catch (error) {
846
850
  warnSkipped2(
847
851
  `Could not list the ${TARGET_VERSION} refs on GitHub (${error.message}); translations not added`
@@ -1155,6 +1159,31 @@ function addEnvironmentVariables(project, cwd, config) {
1155
1159
  false
1156
1160
  );
1157
1161
  }
1162
+ function ensureHandlerNamedImports(sourceFile, names) {
1163
+ const importDeclaration = sourceFile.getImportDeclarations().find(
1164
+ (declaration) => declaration.getModuleSpecifierValue() === HANDLER_MODULE
1165
+ );
1166
+ if (!importDeclaration) {
1167
+ sourceFile.addImportDeclaration({
1168
+ moduleSpecifier: HANDLER_MODULE,
1169
+ namedImports: names
1170
+ });
1171
+ console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
1172
+ return;
1173
+ }
1174
+ const existing = new Set(
1175
+ importDeclaration.getNamedImports().map((named) => named.getName())
1176
+ );
1177
+ const missing = names.filter((name) => !existing.has(name));
1178
+ for (const name of missing) {
1179
+ importDeclaration.addNamedImport(name);
1180
+ }
1181
+ if (missing.length > 0) {
1182
+ console.log(
1183
+ ` \u2713 ${INDEX_FILE}: import ${missing.join(", ")} from ${HANDLER_MODULE}`
1184
+ );
1185
+ }
1186
+ }
1158
1187
  function wireIndex(project, cwd) {
1159
1188
  const sourceFile = project.addSourceFileAtPathIfExists(
1160
1189
  import_path4.default.join(cwd, INDEX_FILE)
@@ -1165,17 +1194,11 @@ function wireIndex(project, cwd) {
1165
1194
  );
1166
1195
  return;
1167
1196
  }
1168
- if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === HANDLER_MODULE)) {
1169
- sourceFile.addImportDeclaration({
1170
- moduleSpecifier: HANDLER_MODULE,
1171
- namedImports: [
1172
- "telemetryHandler",
1173
- "telemetrySchema",
1174
- "TELEMETRY_DISABLED_NOTICE"
1175
- ]
1176
- });
1177
- console.log(` \u2713 ${INDEX_FILE}: import ${HANDLER_MODULE}`);
1178
- }
1197
+ ensureHandlerNamedImports(sourceFile, [
1198
+ "telemetryHandler",
1199
+ "telemetrySchema",
1200
+ "TELEMETRY_DISABLED_NOTICE"
1201
+ ]);
1179
1202
  if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
1180
1203
  const lastRouteStatement = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter((call) => call.getExpression().getText() === "server.route").map(
1181
1204
  (call) => call.getFirstAncestorByKind(import_ts_morph3.SyntaxKind.ExpressionStatement)
@@ -1267,10 +1290,881 @@ Adding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCo
1267
1290
  }
1268
1291
  }
1269
1292
 
1293
+ // src/migrations/v2.1/migrate-infrastructure-to-assets.ts
1294
+ var import_child_process = require("child_process");
1295
+ var import_fs5 = require("fs");
1296
+ var import_os = require("os");
1297
+ var import_path6 = __toESM(require("path"));
1298
+
1299
+ // src/migrations/v2.1/template-files.ts
1300
+ var import_fs4 = require("fs");
1301
+ var import_path5 = __toESM(require("path"));
1302
+ function findTemplateDir() {
1303
+ const candidates = [
1304
+ import_path5.default.resolve(__dirname, "templates", "countryconfig-template"),
1305
+ import_path5.default.resolve(__dirname, "../../../../countryconfig-template")
1306
+ ];
1307
+ const templateDir = candidates.find(
1308
+ (candidate) => (0, import_fs4.existsSync)(import_path5.default.join(candidate, "Tiltfile"))
1309
+ );
1310
+ if (!templateDir) {
1311
+ throw new Error(
1312
+ `Country config template files not found in any of: ${candidates.join(", ")}`
1313
+ );
1314
+ }
1315
+ return templateDir;
1316
+ }
1317
+ function listFiles(root, dir) {
1318
+ const absolute = import_path5.default.join(root, dir);
1319
+ if (!(0, import_fs4.existsSync)(absolute)) {
1320
+ return [];
1321
+ }
1322
+ return (0, import_fs4.readdirSync)(absolute, { withFileTypes: true }).flatMap((entry) => {
1323
+ const relative = import_path5.default.posix.join(dir, entry.name);
1324
+ return entry.isDirectory() ? listFiles(root, relative) : [relative];
1325
+ });
1326
+ }
1327
+
1328
+ // src/migrations/v2.1/migrate-infrastructure-to-assets.ts
1329
+ var INFRASTRUCTURE_DIR = "infrastructure";
1330
+ var ASSETS_DIR = "assets";
1331
+ var BASE_URL = "https://raw.githubusercontent.com/opencrvs/opencrvs-farajaland/release/v2.0.0/infrastructure";
1332
+ var SOURCE_OF = {
1333
+ "elasticsearch/reindex.sh": "deployment/reindex.sh"
1334
+ };
1335
+ var MIGRATED_DIRS = ["metabase", "postgres", "deployment", "elasticsearch"];
1336
+ var NOT_MOVED = ["postgres/on-deploy.sh"];
1337
+ var isMigrated = (file) => MIGRATED_DIRS.some((dir) => file.startsWith(`${dir}/`));
1338
+ function tryGit(args) {
1339
+ try {
1340
+ (0, import_child_process.execFileSync)("git", args, { stdio: "ignore" });
1341
+ return true;
1342
+ } catch {
1343
+ return false;
1344
+ }
1345
+ }
1346
+ function assertIsGitRepo() {
1347
+ if (!tryGit(["rev-parse", "--is-inside-work-tree"])) {
1348
+ throw new Error(
1349
+ `${process.cwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
1350
+ );
1351
+ }
1352
+ }
1353
+ var toBytes = (buffer) => new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
1354
+ var sameBytes = (a, b) => a.length === b.length && a.every((byte, index) => byte === b[index]);
1355
+ var isBinary = (contents) => contents.includes(0);
1356
+ function readIfExists(file) {
1357
+ return (0, import_fs5.existsSync)(file) ? toBytes((0, import_fs5.readFileSync)(file)) : void 0;
1358
+ }
1359
+ function mergeFile(file, ours, base, theirs) {
1360
+ const dir = (0, import_fs5.mkdtempSync)(import_path6.default.join((0, import_os.tmpdir)(), "opencrvs-merge-assets-"));
1361
+ try {
1362
+ const [oursPath, basePath, theirsPath] = ["ours", "base", "theirs"].map(
1363
+ (name) => import_path6.default.join(dir, name)
1364
+ );
1365
+ (0, import_fs5.writeFileSync)(oursPath, ours);
1366
+ (0, import_fs5.writeFileSync)(basePath, base);
1367
+ (0, import_fs5.writeFileSync)(theirsPath, theirs);
1368
+ const args = [
1369
+ "merge-file",
1370
+ "-q",
1371
+ "-L",
1372
+ `infrastructure/${file}`,
1373
+ "-L",
1374
+ "v2.0",
1375
+ "-L",
1376
+ `v2.1 template`,
1377
+ oursPath,
1378
+ basePath,
1379
+ theirsPath
1380
+ ];
1381
+ let conflicts = 0;
1382
+ try {
1383
+ (0, import_child_process.execFileSync)("git", args, { stdio: "ignore" });
1384
+ } catch (error) {
1385
+ const { status } = error;
1386
+ if (!status || status >= 255) throw error;
1387
+ conflicts = status;
1388
+ }
1389
+ return { contents: toBytes((0, import_fs5.readFileSync)(oursPath)), conflicts };
1390
+ } finally {
1391
+ (0, import_fs5.rmSync)(dir, { recursive: true, force: true });
1392
+ }
1393
+ }
1394
+ async function fetchBases(files) {
1395
+ const bases = /* @__PURE__ */ new Map();
1396
+ for (const file of files) {
1397
+ const url = `${BASE_URL}/${file}`;
1398
+ const response = await fetch(url);
1399
+ if (response.ok) {
1400
+ bases.set(file, new Uint8Array(await response.arrayBuffer()));
1401
+ } else if (response.status !== 404) {
1402
+ throw new Error(
1403
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
1404
+ );
1405
+ }
1406
+ }
1407
+ return bases;
1408
+ }
1409
+ function migrateInfrastructureToAssets(cwd, templateDir, readBase) {
1410
+ const infrastructure = import_path6.default.join(cwd, INFRASTRUCTURE_DIR);
1411
+ const templateAssets = import_path6.default.join(templateDir, ASSETS_DIR);
1412
+ const relativeTo = (dir) => (file) => file.slice(dir.length + 1);
1413
+ const localFiles = listFiles(cwd, INFRASTRUCTURE_DIR).map(relativeTo(INFRASTRUCTURE_DIR)).filter(isMigrated);
1414
+ const templateFiles = listFiles(templateDir, ASSETS_DIR).map(
1415
+ relativeTo(ASSETS_DIR)
1416
+ );
1417
+ const outcomes = {};
1418
+ const migrated = /* @__PURE__ */ new Set();
1419
+ for (const file of [.../* @__PURE__ */ new Set([...templateFiles, ...localFiles])].sort()) {
1420
+ const sourceFile = !localFiles.includes(file) && localFiles.includes(SOURCE_OF[file]) ? SOURCE_OF[file] : file;
1421
+ const ours = readIfExists(import_path6.default.join(infrastructure, sourceFile));
1422
+ const theirsPath = import_path6.default.join(templateAssets, file);
1423
+ const theirs = readIfExists(theirsPath);
1424
+ const base = ours && readBase(sourceFile);
1425
+ const target = import_path6.default.join(cwd, ASSETS_DIR, file);
1426
+ if (NOT_MOVED.includes(file)) {
1427
+ if (ours && base && sameBytes(ours, base)) {
1428
+ migrated.add(file);
1429
+ outcomes[file] = "dropped";
1430
+ } else if (ours) {
1431
+ outcomes[file] = "not-moved";
1432
+ }
1433
+ continue;
1434
+ }
1435
+ const ownsSource = ours !== void 0 && sourceFile === file;
1436
+ if ((0, import_fs5.existsSync)(target)) {
1437
+ if (ownsSource) {
1438
+ const same = sameBytes(toBytes((0, import_fs5.readFileSync)(target)), ours);
1439
+ if (same) {
1440
+ migrated.add(file);
1441
+ }
1442
+ outcomes[file] = same ? "exists" : "exists-differs";
1443
+ }
1444
+ continue;
1445
+ }
1446
+ if (ownsSource) {
1447
+ migrated.add(file);
1448
+ }
1449
+ let contents;
1450
+ let outcome;
1451
+ if (!ours) {
1452
+ contents = theirs;
1453
+ outcome = "copied";
1454
+ } else if (!theirs) {
1455
+ const unchanged = base && sameBytes(ours, base);
1456
+ contents = unchanged ? void 0 : ours;
1457
+ outcome = unchanged ? "dropped" : "kept";
1458
+ } else if (sameBytes(ours, theirs) || base && sameBytes(ours, base)) {
1459
+ contents = theirs;
1460
+ outcome = "copied";
1461
+ } else if (!base || sameBytes(base, theirs) || isBinary(ours)) {
1462
+ contents = ours;
1463
+ outcome = "kept";
1464
+ } else {
1465
+ const result = mergeFile(sourceFile, ours, base, theirs);
1466
+ contents = result.contents;
1467
+ outcome = result.conflicts > 0 ? "conflict" : "merged";
1468
+ }
1469
+ outcomes[file] = outcome;
1470
+ if (contents === void 0) {
1471
+ continue;
1472
+ }
1473
+ (0, import_fs5.mkdirSync)(import_path6.default.dirname(target), { recursive: true });
1474
+ (0, import_fs5.writeFileSync)(target, contents);
1475
+ const modeSource = ours && outcome === "kept" ? import_path6.default.join(infrastructure, sourceFile) : theirsPath;
1476
+ if ((0, import_fs5.existsSync)(modeSource)) {
1477
+ (0, import_fs5.chmodSync)(target, (0, import_fs5.statSync)(modeSource).mode & 511);
1478
+ }
1479
+ }
1480
+ return { outcomes, migrated: [...migrated].sort() };
1481
+ }
1482
+ function removeMigrated(cwd, migrated) {
1483
+ const infrastructure = import_path6.default.join(cwd, INFRASTRUCTURE_DIR);
1484
+ for (const file of migrated) {
1485
+ (0, import_fs5.rmSync)(import_path6.default.join(infrastructure, file), { force: true });
1486
+ }
1487
+ const pruneEmpty = (dir) => {
1488
+ if (!(0, import_fs5.existsSync)(dir)) {
1489
+ return true;
1490
+ }
1491
+ const empty = (0, import_fs5.readdirSync)(dir, { withFileTypes: true }).map(
1492
+ (entry) => entry.isDirectory() ? pruneEmpty(import_path6.default.join(dir, entry.name)) : false
1493
+ ).every(Boolean);
1494
+ if (empty) {
1495
+ (0, import_fs5.rmdirSync)(dir);
1496
+ }
1497
+ return empty;
1498
+ };
1499
+ pruneEmpty(infrastructure);
1500
+ }
1501
+ var DESCRIPTIONS = {
1502
+ copied: "from the template",
1503
+ kept: "country's version",
1504
+ merged: "merged",
1505
+ conflict: "CONFLICT, resolve the markers by hand",
1506
+ dropped: "dropped, no longer used",
1507
+ exists: "already migrated",
1508
+ "exists-differs": "already exists with different contents; infrastructure/ copy kept for review",
1509
+ "not-moved": "changed locally but not moved: the chart runs its own on-deploy script, port your changes there"
1510
+ };
1511
+ async function main5(dockerSwarm = false) {
1512
+ const cwd = process.cwd();
1513
+ console.log("Moving infrastructure/ into assets/...\n");
1514
+ const templateDir = findTemplateDir();
1515
+ if ((0, import_fs5.existsSync)(import_path6.default.join(cwd, INFRASTRUCTURE_DIR))) {
1516
+ assertIsGitRepo();
1517
+ const needed = listFiles(cwd, INFRASTRUCTURE_DIR).map((file) => file.slice(INFRASTRUCTURE_DIR.length + 1)).filter(isMigrated);
1518
+ let bases;
1519
+ try {
1520
+ bases = await fetchBases(needed);
1521
+ } catch (error) {
1522
+ console.warn(
1523
+ ` \u26A0\uFE0F Could not read the v2.0 files to merge against (${error.message}); infrastructure/ was not migrated. Re-run 'opencrvs upgrade' with network access.`
1524
+ );
1525
+ return;
1526
+ }
1527
+ const { outcomes, migrated } = migrateInfrastructureToAssets(
1528
+ cwd,
1529
+ templateDir,
1530
+ (file) => bases.get(file)
1531
+ );
1532
+ for (const [file, outcome] of Object.entries(outcomes)) {
1533
+ const needsReview = ["conflict", "not-moved", "exists-differs"].includes(
1534
+ outcome
1535
+ );
1536
+ const shown = outcome === "not-moved" ? INFRASTRUCTURE_DIR : ASSETS_DIR;
1537
+ const line = ` ${needsReview ? "\u26A0\uFE0F " : "\u2713"} ${shown}/${file}: ${DESCRIPTIONS[outcome]}`;
1538
+ if (needsReview) {
1539
+ console.warn(line);
1540
+ } else {
1541
+ console.log(line);
1542
+ }
1543
+ }
1544
+ if (dockerSwarm) {
1545
+ console.log(
1546
+ "\n infrastructure/ kept in place (--docker-swarm); assets/ now holds a copy."
1547
+ );
1548
+ } else {
1549
+ removeMigrated(cwd, migrated);
1550
+ }
1551
+ tryGit(["add", "-A", "--", ASSETS_DIR, INFRASTRUCTURE_DIR]);
1552
+ const conflicts = Object.keys(outcomes).filter(
1553
+ (file) => outcomes[file] === "conflict"
1554
+ );
1555
+ for (const file of conflicts) {
1556
+ tryGit(["restore", "--staged", "--", `${ASSETS_DIR}/${file}`]);
1557
+ }
1558
+ if (conflicts.length > 0) {
1559
+ console.warn(
1560
+ `
1561
+ \u26A0\uFE0F ${conflicts.length} file(s) need their conflicts resolved: ${conflicts.map((file) => `assets/${file}`).join(", ")}`
1562
+ );
1563
+ }
1564
+ if ((0, import_fs5.existsSync)(import_path6.default.join(cwd, INFRASTRUCTURE_DIR)) && !dockerSwarm) {
1565
+ console.warn(
1566
+ " \u26A0\uFE0F infrastructure/ still has files the Kubernetes deployment does not use. Review and delete them if they are no longer needed."
1567
+ );
1568
+ }
1569
+ } else {
1570
+ console.log(" infrastructure/ not found, nothing to move.");
1571
+ }
1572
+ const dockerfile = toBytes(
1573
+ (0, import_fs5.readFileSync)(import_path6.default.join(templateDir, "Dockerfile.assets"))
1574
+ );
1575
+ const current = readIfExists(import_path6.default.join(cwd, "Dockerfile.assets"));
1576
+ if (!current || !sameBytes(current, dockerfile)) {
1577
+ (0, import_fs5.writeFileSync)(import_path6.default.join(cwd, "Dockerfile.assets"), dockerfile);
1578
+ tryGit(["add", "--", "Dockerfile.assets"]);
1579
+ console.log(" \u2713 Dockerfile.assets replaced with the template version");
1580
+ }
1581
+ }
1582
+
1583
+ // src/migrations/v2.1/remove-metabase-package-installs.ts
1584
+ var import_fs6 = require("fs");
1585
+ var import_path7 = require("path");
1586
+ var METABASE_DIRS = ["infrastructure/metabase", "assets/metabase"];
1587
+ var APK_BLOCK = [
1588
+ "apk update",
1589
+ "apk upgrade",
1590
+ "apk add --no-cache gettext",
1591
+ "apk add --no-cache util-linux",
1592
+ "",
1593
+ ""
1594
+ ].join("\n");
1595
+ var SALT_LINE = "export OPENCRVS_METABASE_ADMIN_PASSWORD_SALT=$(uuidgen)\n";
1596
+ var FIXED_SALT_LINE = "export OPENCRVS_METABASE_ADMIN_PASSWORD_SALT=$(cat /proc/sys/kernel/random/uuid 2>/dev/null || uuidgen)\n\n";
1597
+ var FIXED_SALT_MARKER = "/proc/sys/kernel/random/uuid";
1598
+ var ENVSUBST_GUARD = [
1599
+ "if ! which envsubst >/dev/null; then",
1600
+ ' echo "envsubst could not be found. Please install envsubst before continuing."',
1601
+ ' echo "MacOS: brew install gettext && brew link --force gettext"',
1602
+ " exit 1",
1603
+ "fi",
1604
+ ""
1605
+ ].join("\n");
1606
+ var ENVSUBST_CALL = "envsubst < $environment_configuration_sql_file > $environment_configuration_sql_file.tmp\n";
1607
+ var FIXED_EXPANSION = [
1608
+ "",
1609
+ "# Expand $VAR / ${VAR} using bash's own heredoc expansion instead of envsubst,",
1610
+ "# because envsubst is not installed in the Metabase image",
1611
+ 'eval "cat <<OPENCRVS_ENV_EOF',
1612
+ '$(cat "$environment_configuration_sql_file")',
1613
+ 'OPENCRVS_ENV_EOF" > "$environment_configuration_sql_file.tmp"',
1614
+ ""
1615
+ ].join("\n");
1616
+ var FIXED_EXPANSION_MARKER = "OPENCRVS_ENV_EOF";
1617
+ function patchRunScript(source) {
1618
+ if (source.includes(FIXED_SALT_MARKER) && !source.includes(APK_BLOCK)) {
1619
+ return source;
1620
+ }
1621
+ if (!source.includes(APK_BLOCK) || !source.includes(SALT_LINE)) {
1622
+ return void 0;
1623
+ }
1624
+ return source.replace(APK_BLOCK, "").replace(SALT_LINE, FIXED_SALT_LINE);
1625
+ }
1626
+ function patchUpdateDatabaseScript(source) {
1627
+ if (source.includes(FIXED_EXPANSION_MARKER) && !source.includes(ENVSUBST_CALL)) {
1628
+ return source;
1629
+ }
1630
+ if (!source.includes(ENVSUBST_GUARD) || !source.includes(ENVSUBST_CALL)) {
1631
+ return void 0;
1632
+ }
1633
+ return source.replace(ENVSUBST_GUARD, "").replace(ENVSUBST_CALL, FIXED_EXPANSION);
1634
+ }
1635
+ function patchFile(relativePath, patch, removed) {
1636
+ const filePath = (0, import_path7.join)(process.cwd(), relativePath);
1637
+ if (!(0, import_fs6.existsSync)(filePath)) {
1638
+ return;
1639
+ }
1640
+ const source = (0, import_fs6.readFileSync)(filePath, "utf8");
1641
+ const patched = patch(source);
1642
+ if (patched === void 0) {
1643
+ console.warn(
1644
+ ` \u26A0\uFE0F ${relativePath} does not match the upstream v2.0 version, so it was left alone. Apply https://github.com/opencrvs/opencrvs-core/pull/13778 by hand, or Metabase will fail to start behind the chart's private egress policy.`
1645
+ );
1646
+ return;
1647
+ }
1648
+ if (patched === source) {
1649
+ return;
1650
+ }
1651
+ (0, import_fs6.writeFileSync)(filePath, patched);
1652
+ console.log(` \u2713 ${relativePath}: ${removed}`);
1653
+ }
1654
+ async function main6() {
1655
+ console.log("\nRemoving the Metabase package installs...\n");
1656
+ for (const dir of METABASE_DIRS) {
1657
+ patchFile((0, import_path7.join)(dir, "run.sh"), patchRunScript, "apk add gettext util-linux");
1658
+ patchFile(
1659
+ (0, import_path7.join)(dir, "update-database.sh"),
1660
+ patchUpdateDatabaseScript,
1661
+ "envsubst"
1662
+ );
1663
+ }
1664
+ }
1665
+
1666
+ // src/migrations/v2.1/remove-sentry.ts
1667
+ var import_fs7 = require("fs");
1668
+ var import_path8 = __toESM(require("path"));
1669
+ var import_ts_morph4 = require("ts-morph");
1670
+ var CONFIG_FILES = [
1671
+ "src/client-config.ts",
1672
+ "src/client-config.prod.ts",
1673
+ "src/login-config.ts",
1674
+ "src/login-config.prod.ts"
1675
+ ];
1676
+ var ENVIRONMENT_FILE2 = "src/environment.ts";
1677
+ var CONSTANTS_FILE = "src/constants.ts";
1678
+ var INDEX_FILE2 = "src/index.ts";
1679
+ var UTILS_FILE = "src/utils/index.ts";
1680
+ var PACKAGE_JSON_FILE = "package.json";
1681
+ var TYPINGS_FILE = "typings/hapi-sentry.d.ts";
1682
+ var SENTRY_PLUGIN = "hapi-sentry";
1683
+ var skipped4 = [];
1684
+ function warnSkipped4(message) {
1685
+ skipped4.push(message);
1686
+ console.warn(` \u26A0\uFE0F ${message}`);
1687
+ }
1688
+ function isReferenced(sourceFile, name) {
1689
+ return sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.Identifier).some(
1690
+ (identifier) => identifier.getText() === name && !identifier.getFirstAncestorByKind(import_ts_morph4.SyntaxKind.ImportDeclaration)
1691
+ );
1692
+ }
1693
+ function removeIfUnused(sourceFile, importDeclaration) {
1694
+ const names = [
1695
+ importDeclaration.getDefaultImport()?.getText(),
1696
+ importDeclaration.getNamespaceImport()?.getText(),
1697
+ ...importDeclaration.getNamedImports().map((named) => named.getName())
1698
+ ].filter((name) => Boolean(name));
1699
+ if (names.length > 0 && names.every((name) => !isReferenced(sourceFile, name))) {
1700
+ importDeclaration.remove();
1701
+ return true;
1702
+ }
1703
+ return false;
1704
+ }
1705
+ function removeNamedImport(sourceFile, moduleSpecifier, name) {
1706
+ const importDeclaration = sourceFile.getImportDeclarations().find(
1707
+ (declaration) => declaration.getModuleSpecifierValue() === moduleSpecifier
1708
+ );
1709
+ if (!importDeclaration) return false;
1710
+ const named = importDeclaration.getNamedImports().find((namedImport) => namedImport.getName() === name);
1711
+ if (!named) return false;
1712
+ named.remove();
1713
+ if (importDeclaration.getNamedImports().length === 0 && !importDeclaration.getDefaultImport() && !importDeclaration.getNamespaceImport()) {
1714
+ importDeclaration.remove();
1715
+ }
1716
+ return true;
1717
+ }
1718
+ function removeSentryFromConfigs(project, cwd) {
1719
+ for (const file of CONFIG_FILES) {
1720
+ const sourceFile = project.addSourceFileAtPathIfExists(import_path8.default.join(cwd, file));
1721
+ if (!sourceFile) continue;
1722
+ const property = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.PropertyAssignment).find((assignment) => assignment.getName() === "SENTRY");
1723
+ if (!property) continue;
1724
+ const usedNames = new Set(
1725
+ property.getDescendantsOfKind(import_ts_morph4.SyntaxKind.Identifier).map((identifier) => identifier.getText())
1726
+ );
1727
+ property.remove();
1728
+ for (const importDeclaration of [...sourceFile.getImportDeclarations()]) {
1729
+ const imported = [
1730
+ importDeclaration.getDefaultImport()?.getText(),
1731
+ importDeclaration.getNamespaceImport()?.getText(),
1732
+ ...importDeclaration.getNamedImports().map((named) => named.getName())
1733
+ ].filter((name) => Boolean(name));
1734
+ if (imported.some((name) => usedNames.has(name))) {
1735
+ removeIfUnused(sourceFile, importDeclaration);
1736
+ }
1737
+ }
1738
+ console.log(` \u2713 ${file}: SENTRY`);
1739
+ }
1740
+ }
1741
+ function removeEnvironmentVariable(project, cwd) {
1742
+ const sourceFile = project.addSourceFileAtPathIfExists(
1743
+ import_path8.default.join(cwd, ENVIRONMENT_FILE2)
1744
+ );
1745
+ if (!sourceFile) return;
1746
+ const options = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
1747
+ if (!options || !import_ts_morph4.Node.isObjectLiteralExpression(options)) {
1748
+ warnSkipped4(
1749
+ `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE2}; remove SENTRY_DSN by hand`
1750
+ );
1751
+ return;
1752
+ }
1753
+ const property = options.getProperty("SENTRY_DSN");
1754
+ if (!property) return;
1755
+ property.remove();
1756
+ console.log(` \u2713 ${ENVIRONMENT_FILE2}: SENTRY_DSN`);
1757
+ }
1758
+ function removeConstant(project, cwd) {
1759
+ const sourceFile = project.addSourceFileAtPathIfExists(
1760
+ import_path8.default.join(cwd, CONSTANTS_FILE)
1761
+ );
1762
+ if (!sourceFile) return;
1763
+ for (const statement of [...sourceFile.getVariableStatements()]) {
1764
+ const declarations = statement.getDeclarations();
1765
+ const matching = declarations.filter(
1766
+ (declaration) => declaration.getName() === "SENTRY_DSN" || /\benv\.SENTRY_DSN\b/.test(
1767
+ declaration.getInitializer()?.getText() ?? ""
1768
+ )
1769
+ );
1770
+ if (matching.length === 0) continue;
1771
+ const names = matching.map((declaration) => declaration.getName());
1772
+ if (matching.length === declarations.length) {
1773
+ statement.remove();
1774
+ } else {
1775
+ for (const declaration of matching) {
1776
+ declaration.remove();
1777
+ }
1778
+ }
1779
+ console.log(` \u2713 ${CONSTANTS_FILE}: ${names.join(", ")}`);
1780
+ }
1781
+ }
1782
+ function unwireIndex(project, cwd) {
1783
+ const sourceFile = project.addSourceFileAtPathIfExists(
1784
+ import_path8.default.join(cwd, INDEX_FILE2)
1785
+ );
1786
+ if (!sourceFile) return;
1787
+ const pluginImport = sourceFile.getImportDeclarations().find(
1788
+ (declaration) => declaration.getModuleSpecifierValue() === SENTRY_PLUGIN
1789
+ );
1790
+ const pluginName = pluginImport?.getNamespaceImport()?.getText() ?? pluginImport?.getDefaultImport()?.getText() ?? "Sentry";
1791
+ const registration = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.IfStatement).find(
1792
+ (statement) => /\bSENTRY_DSN\b/.test(statement.getExpression().getText()) && new RegExp(`\\bplugin:\\s*${pluginName}\\b`).test(statement.getText())
1793
+ );
1794
+ if (registration) {
1795
+ registration.remove();
1796
+ console.log(` \u2713 ${INDEX_FILE2}: hapi-sentry plugin registration`);
1797
+ } else if (sourceFile.getText().includes(SENTRY_PLUGIN)) {
1798
+ warnSkipped4(
1799
+ `Could not find the hapi-sentry plugin registration in ${INDEX_FILE2}; remove it by hand`
1800
+ );
1801
+ }
1802
+ const scopeExtension = sourceFile.getDescendantsOfKind(import_ts_morph4.SyntaxKind.ExpressionStatement).find(
1803
+ (statement) => statement.getText().includes("sentryScope") && statement.getText().startsWith("server.ext")
1804
+ );
1805
+ if (scopeExtension) {
1806
+ scopeExtension.remove();
1807
+ console.log(` \u2713 ${INDEX_FILE2}: onRequest Sentry scope extension`);
1808
+ } else if (sourceFile.getText().includes("sentryScope")) {
1809
+ warnSkipped4(
1810
+ `Found 'sentryScope' in ${INDEX_FILE2} outside a server.ext(...) call; remove it by hand`
1811
+ );
1812
+ }
1813
+ if (pluginImport && removeIfUnused(sourceFile, pluginImport)) {
1814
+ console.log(` \u2713 ${INDEX_FILE2}: import '${SENTRY_PLUGIN}'`);
1815
+ }
1816
+ if (!isReferenced(sourceFile, "SENTRY_DSN")) {
1817
+ for (const declaration of [...sourceFile.getImportDeclarations()]) {
1818
+ const specifier = declaration.getModuleSpecifierValue();
1819
+ if (removeNamedImport(sourceFile, specifier, "SENTRY_DSN")) {
1820
+ console.log(` \u2713 ${INDEX_FILE2}: import SENTRY_DSN from '${specifier}'`);
1821
+ break;
1822
+ }
1823
+ }
1824
+ }
1825
+ }
1826
+ function removeApplicationConfigField(project, cwd) {
1827
+ const sourceFile = project.addSourceFileAtPathIfExists(
1828
+ import_path8.default.join(cwd, UTILS_FILE)
1829
+ );
1830
+ if (!sourceFile) return;
1831
+ const property = sourceFile.getInterface("IApplicationConfig")?.getProperty("SENTRY");
1832
+ if (!property) return;
1833
+ property.remove();
1834
+ console.log(` \u2713 ${UTILS_FILE}: IApplicationConfig.SENTRY`);
1835
+ }
1836
+ function isSentryPackage(name) {
1837
+ return name === SENTRY_PLUGIN || name.startsWith("@sentry/");
1838
+ }
1839
+ function removeDependencies(cwd) {
1840
+ const packageJsonPath = import_path8.default.join(cwd, PACKAGE_JSON_FILE);
1841
+ if (!(0, import_fs7.existsSync)(packageJsonPath)) return;
1842
+ const raw = (0, import_fs7.readFileSync)(packageJsonPath, "utf8");
1843
+ let parsed;
1844
+ try {
1845
+ parsed = JSON.parse(raw);
1846
+ } catch (error) {
1847
+ warnSkipped4(
1848
+ `${PACKAGE_JSON_FILE} could not be parsed (${error.message}); remove the Sentry dependencies by hand`
1849
+ );
1850
+ return;
1851
+ }
1852
+ const removed = [];
1853
+ for (const bucket of ["dependencies", "devDependencies"]) {
1854
+ const dependencies = parsed[bucket];
1855
+ if (!dependencies) continue;
1856
+ for (const name of Object.keys(dependencies)) {
1857
+ if (isSentryPackage(name)) {
1858
+ delete dependencies[name];
1859
+ removed.push(name);
1860
+ }
1861
+ }
1862
+ }
1863
+ if (removed.length === 0) return;
1864
+ const trailingNewline = raw.endsWith("\n") ? "\n" : "";
1865
+ (0, import_fs7.writeFileSync)(
1866
+ packageJsonPath,
1867
+ `${JSON.stringify(parsed, null, 2)}${trailingNewline}`
1868
+ );
1869
+ console.log(` \u2713 ${PACKAGE_JSON_FILE}: ${removed.join(", ")}`);
1870
+ }
1871
+ function removeTypings(cwd) {
1872
+ const typingsPath = import_path8.default.join(cwd, TYPINGS_FILE);
1873
+ if (!(0, import_fs7.existsSync)(typingsPath)) return;
1874
+ const declarations = (0, import_fs7.readFileSync)(typingsPath, "utf8").replace(/\/\*[\s\S]*?\*\//g, "").replace(/^\s*\/\/.*$/gm, "").trim();
1875
+ if (!/^declare module ['"]hapi-sentry['"];?$/.test(declarations)) {
1876
+ warnSkipped4(
1877
+ `${TYPINGS_FILE} declares more than the 'hapi-sentry' module; remove the declaration by hand`
1878
+ );
1879
+ return;
1880
+ }
1881
+ (0, import_fs7.rmSync)(typingsPath);
1882
+ console.log(` \u2713 ${TYPINGS_FILE}: deleted`);
1883
+ }
1884
+ async function main7() {
1885
+ const cwd = process.cwd();
1886
+ console.log("\nRemoving Sentry...\n");
1887
+ const project = new import_ts_morph4.Project({
1888
+ // ts-morph indents with four spaces and double-quotes strings by default,
1889
+ // both of which the country config's prettier run would undo.
1890
+ manipulationSettings: {
1891
+ indentationText: import_ts_morph4.IndentationText.TwoSpaces,
1892
+ quoteKind: import_ts_morph4.QuoteKind.Single
1893
+ }
1894
+ });
1895
+ removeSentryFromConfigs(project, cwd);
1896
+ removeEnvironmentVariable(project, cwd);
1897
+ removeConstant(project, cwd);
1898
+ unwireIndex(project, cwd);
1899
+ removeApplicationConfigField(project, cwd);
1900
+ await project.save();
1901
+ removeDependencies(cwd);
1902
+ removeTypings(cwd);
1903
+ if (skipped4.length > 0) {
1904
+ console.warn(
1905
+ `
1906
+ \u26A0\uFE0F ${skipped4.length} Sentry removal step(s) were skipped. Handle the following by hand:`
1907
+ );
1908
+ for (const message of skipped4) {
1909
+ console.warn(` - ${message}`);
1910
+ }
1911
+ }
1912
+ }
1913
+
1914
+ // src/migrations/v2.1/rename-trigger-paths.ts
1915
+ var import_ts_morph5 = require("ts-morph");
1916
+ var import_path9 = __toESM(require("path"));
1917
+ var PATH_PREFIX_RENAMES = {
1918
+ "/triggers/user/": "/trigger/user/",
1919
+ "/triggers/system/": "/trigger/system/"
1920
+ };
1921
+ var STALE_PREFIX = "/triggers/";
1922
+ var METHOD_PROPERTY_NAME = "method";
1923
+ var PATH_PROPERTY_NAME = "path";
1924
+ var HTTP_VERBS = /* @__PURE__ */ new Set([
1925
+ "GET",
1926
+ "POST",
1927
+ "PUT",
1928
+ "PATCH",
1929
+ "DELETE",
1930
+ "OPTIONS",
1931
+ "HEAD",
1932
+ "*"
1933
+ ]);
1934
+ function isRouteConfig(obj) {
1935
+ const methodProp = obj.getProperty(METHOD_PROPERTY_NAME);
1936
+ if (!methodProp || !import_ts_morph5.Node.isPropertyAssignment(methodProp)) return false;
1937
+ const methodInit = methodProp.getInitializer();
1938
+ if (!methodInit) return false;
1939
+ if (import_ts_morph5.Node.isStringLiteral(methodInit)) {
1940
+ if (!HTTP_VERBS.has(methodInit.getLiteralValue().toUpperCase()))
1941
+ return false;
1942
+ } else if (import_ts_morph5.Node.isArrayLiteralExpression(methodInit)) {
1943
+ const allVerbs = methodInit.getElements().every(
1944
+ (el) => import_ts_morph5.Node.isStringLiteral(el) && HTTP_VERBS.has(el.getLiteralValue().toUpperCase())
1945
+ );
1946
+ if (!allVerbs) return false;
1947
+ } else {
1948
+ return false;
1949
+ }
1950
+ const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
1951
+ if (!pathProp || !import_ts_morph5.Node.isPropertyAssignment(pathProp)) return false;
1952
+ const pathInit = pathProp.getInitializer();
1953
+ return !!pathInit && import_ts_morph5.Node.isStringLiteral(pathInit);
1954
+ }
1955
+ function renameRoutePath(obj) {
1956
+ const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
1957
+ if (!pathProp || !import_ts_morph5.Node.isPropertyAssignment(pathProp)) return null;
1958
+ const pathInit = pathProp.getInitializer();
1959
+ if (!pathInit || !import_ts_morph5.Node.isStringLiteral(pathInit)) return null;
1960
+ const oldPath = pathInit.getLiteralValue();
1961
+ const match = Object.entries(PATH_PREFIX_RENAMES).find(
1962
+ ([from2]) => oldPath.startsWith(from2)
1963
+ );
1964
+ if (!match) return null;
1965
+ const [from, to] = match;
1966
+ const newPath = to + oldPath.slice(from.length);
1967
+ pathInit.replaceWithText(`'${newPath}'`);
1968
+ return newPath;
1969
+ }
1970
+ function processFile2(filePath, project) {
1971
+ const sourceFile = project.getSourceFile(filePath);
1972
+ if (!sourceFile) return 0;
1973
+ let renamedCount = 0;
1974
+ const relPath = import_path9.default.relative(process.cwd(), filePath);
1975
+ const candidates = sourceFile.getDescendantsOfKind(
1976
+ import_ts_morph5.SyntaxKind.ObjectLiteralExpression
1977
+ );
1978
+ for (const obj of candidates) {
1979
+ if (!isRouteConfig(obj)) continue;
1980
+ const newPath = renameRoutePath(obj);
1981
+ if (newPath) {
1982
+ renamedCount++;
1983
+ console.log(` [${relPath}] Renamed route path \u2192 '${newPath}'`);
1984
+ }
1985
+ }
1986
+ return renamedCount;
1987
+ }
1988
+ function warnAboutStalePaths(sourceFiles) {
1989
+ const stale = [];
1990
+ for (const sourceFile of sourceFiles) {
1991
+ const relPath = import_path9.default.relative(process.cwd(), sourceFile.getFilePath());
1992
+ const lines = sourceFile.getFullText().split("\n");
1993
+ lines.forEach((line, index) => {
1994
+ if (line.includes(STALE_PREFIX)) {
1995
+ stale.push(` ${relPath}:${index + 1}: ${line.trim()}`);
1996
+ }
1997
+ });
1998
+ }
1999
+ if (stale.length === 0) return;
2000
+ console.log(
2001
+ `
2002
+ WARNING: ${stale.length} remaining '${STALE_PREFIX}' reference(s) need to be renamed by hand:`
2003
+ );
2004
+ console.log(stale.join("\n"));
2005
+ }
2006
+ async function main8() {
2007
+ const srcDir = import_path9.default.join(process.cwd(), "src");
2008
+ console.log(`Scanning for Hapi route configs in: ${srcDir}
2009
+ `);
2010
+ console.log("Active path renames:");
2011
+ for (const [from, to] of Object.entries(PATH_PREFIX_RENAMES)) {
2012
+ console.log(` '${from}*' \u2192 '${to}*'`);
2013
+ }
2014
+ console.log();
2015
+ const project = new import_ts_morph5.Project({
2016
+ tsConfigFilePath: import_path9.default.resolve(srcDir, "../tsconfig.json"),
2017
+ skipAddingFilesFromTsConfig: false
2018
+ });
2019
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
2020
+ const fp = sf.getFilePath();
2021
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
2022
+ });
2023
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
2024
+ `);
2025
+ let totalRenamed = 0;
2026
+ const modifiedFiles = [];
2027
+ for (const sourceFile of sourceFiles) {
2028
+ const filePath = sourceFile.getFilePath();
2029
+ const renamed = processFile2(filePath, project);
2030
+ if (renamed > 0) {
2031
+ totalRenamed += renamed;
2032
+ modifiedFiles.push(filePath);
2033
+ }
2034
+ }
2035
+ if (modifiedFiles.length === 0) {
2036
+ console.log("No trigger route paths to rename.");
2037
+ } else {
2038
+ console.log(`
2039
+ Saving ${modifiedFiles.length} modified file(s)...`);
2040
+ for (const filePath of modifiedFiles) {
2041
+ const sourceFile = project.getSourceFileOrThrow(filePath);
2042
+ await sourceFile.save();
2043
+ console.log(` Saved: ${import_path9.default.relative(process.cwd(), filePath)}`);
2044
+ }
2045
+ console.log(`
2046
+ Done. Renamed ${totalRenamed} route path(s).`);
2047
+ }
2048
+ warnAboutStalePaths(sourceFiles);
2049
+ }
2050
+
2051
+ // src/migrations/v2.1/upgrade-tilt.ts
2052
+ var import_fs8 = require("fs");
2053
+ var import_path10 = __toESM(require("path"));
2054
+ var COUNTRY_OWNED_DIR = "tilt/helm/";
2055
+ var CHARTS_CHECKOUT_DIR = ".opencrvs-core-charts";
2056
+ var IMAGE_NAME_PATTERN = /^countryconfig_image_name\s*=\s*(["'])(.*?)\1/m;
2057
+ function writeIfChanged(cwd, relativePath, contents, mode) {
2058
+ const target = import_path10.default.join(cwd, relativePath);
2059
+ const existed = (0, import_fs8.existsSync)(target);
2060
+ if (existed && (0, import_fs8.readFileSync)(target, "utf8") === contents) {
2061
+ return "unchanged";
2062
+ }
2063
+ (0, import_fs8.mkdirSync)(import_path10.default.dirname(target), { recursive: true });
2064
+ (0, import_fs8.writeFileSync)(target, contents);
2065
+ if (mode !== void 0) {
2066
+ (0, import_fs8.chmodSync)(target, mode & 511);
2067
+ }
2068
+ return existed ? "updated" : "created";
2069
+ }
2070
+ function report(relativePath, change) {
2071
+ if (change !== "unchanged") {
2072
+ console.log(` \u2713 ${change} ${relativePath}`);
2073
+ }
2074
+ }
2075
+ function renderTiltfile(template, existing) {
2076
+ const imageName = existing?.match(IMAGE_NAME_PATTERN)?.[2];
2077
+ if (!imageName) {
2078
+ return template;
2079
+ }
2080
+ return template.replace(
2081
+ IMAGE_NAME_PATTERN,
2082
+ (_line, quote) => `countryconfig_image_name=${quote}${imageName}${quote}`
2083
+ );
2084
+ }
2085
+ function withIgnoreEntry(contents, line) {
2086
+ const normalise = (entry) => entry.trim().replace(/^\//, "").replace(/\/$/, "");
2087
+ const alreadyIgnored = contents.split(/\r?\n/).some((entry) => normalise(entry) === normalise(line));
2088
+ if (alreadyIgnored) {
2089
+ return contents;
2090
+ }
2091
+ const separator = contents === "" || contents.endsWith("\n") ? "" : "\n";
2092
+ return `${contents}${separator}${line}
2093
+ `;
2094
+ }
2095
+ function ensureIgnored(cwd, file, line) {
2096
+ const target = import_path10.default.join(cwd, file);
2097
+ const contents = (0, import_fs8.existsSync)(target) ? (0, import_fs8.readFileSync)(target, "utf8") : "";
2098
+ report(file, writeIfChanged(cwd, file, withIgnoreEntry(contents, line)));
2099
+ }
2100
+ function upgradeTilt(cwd, templateDir) {
2101
+ const tiltfilePath = import_path10.default.join(cwd, "Tiltfile");
2102
+ const existingTiltfile = (0, import_fs8.existsSync)(tiltfilePath) ? (0, import_fs8.readFileSync)(tiltfilePath, "utf8") : void 0;
2103
+ report(
2104
+ "Tiltfile",
2105
+ writeIfChanged(
2106
+ cwd,
2107
+ "Tiltfile",
2108
+ renderTiltfile(
2109
+ (0, import_fs8.readFileSync)(import_path10.default.join(templateDir, "Tiltfile"), "utf8"),
2110
+ existingTiltfile
2111
+ )
2112
+ )
2113
+ );
2114
+ const templateFiles = listFiles(templateDir, "tilt");
2115
+ for (const file of templateFiles) {
2116
+ const source = import_path10.default.join(templateDir, file);
2117
+ const countryOwned = file.startsWith(COUNTRY_OWNED_DIR);
2118
+ if (countryOwned && (0, import_fs8.existsSync)(import_path10.default.join(cwd, file))) {
2119
+ continue;
2120
+ }
2121
+ report(
2122
+ file,
2123
+ writeIfChanged(
2124
+ cwd,
2125
+ file,
2126
+ (0, import_fs8.readFileSync)(source, "utf8"),
2127
+ (0, import_fs8.statSync)(source).mode
2128
+ )
2129
+ );
2130
+ }
2131
+ const unknownFiles = listFiles(cwd, "tilt").filter(
2132
+ (file) => !file.startsWith(COUNTRY_OWNED_DIR) && !templateFiles.includes(file)
2133
+ );
2134
+ for (const file of unknownFiles) {
2135
+ console.warn(
2136
+ ` \u26A0\uFE0F ${file} is not part of the template and was left in place. Move chart overrides into ${COUNTRY_OWNED_DIR}`
2137
+ );
2138
+ }
2139
+ ensureIgnored(cwd, ".tiltignore", `${CHARTS_CHECKOUT_DIR}/`);
2140
+ ensureIgnored(cwd, ".gitignore", CHARTS_CHECKOUT_DIR);
2141
+ if (existingTiltfile?.includes("opencrvs-helm-charts")) {
2142
+ console.log(
2143
+ ` \u2139\uFE0F The Tiltfile no longer uses ../opencrvs-helm-charts; charts are cloned into ${CHARTS_CHECKOUT_DIR}/ instead. The old checkout can be deleted.`
2144
+ );
2145
+ }
2146
+ }
2147
+ async function main9() {
2148
+ console.log("Upgrading the local Tilt setup...\n");
2149
+ upgradeTilt(process.cwd(), findTemplateDir());
2150
+ console.log(
2151
+ "\n Review local customisations with: git diff -- Tiltfile tilt/ .tiltignore .gitignore\n"
2152
+ );
2153
+ }
2154
+
1270
2155
  // src/migrations/v2.1/index.ts
1271
2156
  async function runUpgrade(dockerSwarm) {
1272
2157
  await main();
2158
+ await main8();
1273
2159
  await main2();
1274
2160
  await main3();
2161
+ await main7();
2162
+ await main6();
2163
+ await main5(dockerSwarm);
2164
+ await main9();
1275
2165
  await main4();
1276
2166
  }
2167
+ // Annotate the CommonJS export names for ESM import in node:
2168
+ 0 && (module.exports = {
2169
+ runUpgrade
2170
+ });