@opencrvs/toolkit 2.1.0-rc.7985421 → 2.1.0-rc.7c723fe

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 (242) hide show
  1. package/README.md +3 -12
  2. package/build.sh +22 -4
  3. package/create-countryconfig/index.js +441 -59
  4. package/create-countryconfig/node_modules/.bin/degit +21 -0
  5. package/create-countryconfig/package.json +4 -1
  6. package/dist/application-config/index.js +361 -284
  7. package/dist/authentication/index.d.ts +66 -0
  8. package/dist/authentication/index.d.ts.map +1 -0
  9. package/dist/authentication/index.js +765 -0
  10. package/dist/cli.js +3751 -1232
  11. package/dist/commons/api/router.d.ts +745 -372
  12. package/dist/commons/application-config/index.d.ts +0 -2
  13. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  14. package/dist/commons/conditionals/validate.d.ts +34 -8
  15. package/dist/commons/events/ActionConfig.d.ts +5 -14
  16. package/dist/commons/events/ActionDocument.d.ts +35 -15
  17. package/dist/commons/events/ActionInput.d.ts +4 -4
  18. package/dist/commons/events/ActionStatus.d.ts +14 -0
  19. package/dist/commons/events/AdvancedSearchConfig.d.ts +42 -12
  20. package/dist/commons/events/AuditLog.d.ts +39 -0
  21. package/dist/commons/events/Draft.d.ts +1 -21
  22. package/dist/commons/events/EventConfig.d.ts +3 -0
  23. package/dist/commons/events/EventDocument.d.ts +472 -4
  24. package/dist/commons/events/EventIndex.d.ts +3 -26
  25. package/dist/commons/events/EventMetadata.d.ts +1 -11
  26. package/dist/commons/events/EventStatus.d.ts +19 -0
  27. package/dist/commons/events/FieldConfig.d.ts +104 -63
  28. package/dist/commons/events/FieldTypeMapping.d.ts +17 -17
  29. package/dist/commons/events/FieldValue.d.ts +3 -2
  30. package/dist/commons/events/Flag.d.ts +42 -0
  31. package/dist/commons/events/FormConfig.d.ts +6 -0
  32. package/dist/commons/events/PageConfig.d.ts +4 -0
  33. package/dist/commons/events/PlainDate.d.ts +8 -0
  34. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  35. package/dist/commons/events/WorkqueueConfig.d.ts +17 -14
  36. package/dist/commons/events/event.d.ts +12 -0
  37. package/dist/commons/events/locations.d.ts +162 -26
  38. package/dist/commons/events/mocks.test.utils.d.ts +30 -0
  39. package/dist/commons/events/scopes.d.ts +21 -1
  40. package/dist/commons/events/test.utils.d.ts +78 -25
  41. package/dist/commons/events/utils.d.ts +39 -4
  42. package/dist/commons/notification/UserNotifications.d.ts +28 -13
  43. package/dist/commons/notification/dispatch.d.ts +10 -0
  44. package/dist/commons/notification/index.d.ts +1 -0
  45. package/dist/conditionals/index.js +348 -65
  46. package/dist/csv.d.ts +25 -0
  47. package/dist/csv.d.ts.map +1 -0
  48. package/dist/csv.js +120 -0
  49. package/dist/environment/index.d.ts +1 -0
  50. package/dist/environment/index.d.ts.map +1 -1
  51. package/dist/environment/index.js +12 -1
  52. package/dist/environment/logger.d.ts +15 -3
  53. package/dist/environment/logger.d.ts.map +1 -1
  54. package/dist/environment/manage-users.js +1 -1
  55. package/dist/environment/paths.d.ts +7 -0
  56. package/dist/environment/paths.d.ts.map +1 -0
  57. package/dist/environment/paths.js +72 -0
  58. package/dist/environment/questions.d.ts.map +1 -1
  59. package/dist/environment/questions.js +20 -14
  60. package/dist/environment/setup-environment.d.ts +1 -1
  61. package/dist/environment/setup-environment.d.ts.map +1 -1
  62. package/dist/environment/setup-environment.js +594 -562
  63. package/dist/environment/swarm-to-k8s.js +3 -4
  64. package/dist/environment/templates.d.ts +0 -1
  65. package/dist/environment/templates.d.ts.map +1 -1
  66. package/dist/environment/templates.js +5 -9
  67. package/dist/environment/update-workflows.d.ts.map +1 -1
  68. package/dist/environment/update-workflows.js +21 -5
  69. package/dist/environment/upgrade.d.ts +2 -0
  70. package/dist/environment/upgrade.d.ts.map +1 -0
  71. package/dist/environment/upgrade.js +82 -0
  72. package/dist/environment/users.js +11 -13
  73. package/dist/environment/utils.d.ts +0 -12
  74. package/dist/environment/utils.d.ts.map +1 -1
  75. package/dist/environment/utils.js +1 -28
  76. package/dist/events/index.js +7286 -6783
  77. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  78. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  79. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  80. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  81. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  82. package/dist/migrations/v2.1/add-translations.js +149 -0
  83. package/dist/migrations/{v2.0/rename-api-paths.d.ts → v2.1/enable-telemetry.d.ts} +1 -1
  84. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  85. package/dist/migrations/v2.1/enable-telemetry.js +455 -0
  86. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  87. package/dist/migrations/v2.1/index.js +1952 -0
  88. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +14 -0
  89. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +1 -0
  90. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +348 -0
  91. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +2 -0
  92. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +1 -0
  93. package/dist/migrations/v2.1/remove-metabase-package-installs.js +161 -0
  94. package/dist/migrations/{v2.0/migrate-scopes.d.ts → v2.1/remove-sentry.d.ts} +1 -1
  95. package/dist/migrations/v2.1/remove-sentry.d.ts.map +1 -0
  96. package/dist/migrations/v2.1/remove-sentry.js +354 -0
  97. package/dist/migrations/{v2.0/create-events-index.d.ts → v2.1/rename-trigger-paths.d.ts} +1 -1
  98. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +1 -0
  99. package/dist/migrations/{v2.0/rename-api-paths.js → v2.1/rename-trigger-paths.js} +69 -40
  100. package/dist/migrations/v2.1/template-files.d.ts +8 -0
  101. package/dist/migrations/v2.1/template-files.d.ts.map +1 -0
  102. package/dist/migrations/v2.1/template-files.js +49 -0
  103. package/dist/migrations/v2.1/upgrade-tilt.d.ts +8 -0
  104. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +1 -0
  105. package/dist/migrations/v2.1/upgrade-tilt.js +139 -0
  106. package/dist/notification/index.js +1839 -1499
  107. package/dist/scopes/index.d.ts +612 -36
  108. package/dist/scopes/index.js +350 -65
  109. package/dist/telemetry/index.d.ts +45 -0
  110. package/dist/telemetry/index.d.ts.map +1 -0
  111. package/dist/telemetry/index.js +43 -0
  112. package/dist/templates/charts-values/dependencies/values.yaml +8 -0
  113. package/dist/templates/charts-values/opencrvs-services/values.yaml +10 -3
  114. package/dist/templates/charts-values/opentelemetry/values.yaml +102 -0
  115. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  116. package/dist/templates/countryconfig-template/.tiltignore +1 -0
  117. package/dist/templates/countryconfig-template/Dockerfile.assets +7 -0
  118. package/dist/templates/countryconfig-template/Tiltfile +112 -0
  119. package/dist/templates/countryconfig-template/assets/README.md +1 -0
  120. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +61 -0
  121. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +455 -0
  122. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +168 -0
  123. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +67 -0
  124. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +168 -0
  125. package/dist/templates/countryconfig-template/assets/metabase/README.md +34 -0
  126. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +36 -0
  127. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +46 -0
  128. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +27737 -0
  129. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +21 -0
  130. package/dist/templates/countryconfig-template/assets/metabase/package.json +13 -0
  131. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +108 -0
  132. package/dist/templates/countryconfig-template/assets/metabase/run.sh +120 -0
  133. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +40 -0
  134. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +135 -0
  135. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +108 -0
  136. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +50 -0
  137. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +35 -0
  138. package/dist/templates/countryconfig-template/tilt/common.tilt +145 -0
  139. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +15 -0
  140. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +56 -0
  141. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +21 -0
  142. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +38 -0
  143. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +17 -0
  144. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +16 -0
  145. package/dist/templates/countryconfig-template/tilt/lib.tilt +95 -0
  146. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +136 -0
  147. package/dist/templates/inventory/inventory.template.yml +1 -3
  148. package/dist/translations/template.d.ts +11 -0
  149. package/dist/translations/template.d.ts.map +1 -0
  150. package/dist/translations/template.js +100 -0
  151. package/dist/verify/endpoints.d.ts +2 -0
  152. package/dist/verify/endpoints.d.ts.map +1 -0
  153. package/dist/verify/endpoints.js +510 -0
  154. package/opencrvs-toolkit-2.1.0-rc.7c723fe.tgz +0 -0
  155. package/package.json +13 -7
  156. package/tsconfig.build.json +11 -0
  157. package/tsconfig.build.tsbuildinfo +1 -0
  158. package/tsconfig.json +3 -0
  159. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts +0 -3
  160. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +0 -1
  161. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +0 -429
  162. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts +0 -3
  163. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts.map +0 -1
  164. package/dist/migrations/v2.0/add-resend-invite-notification.js +0 -373
  165. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +0 -22
  166. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +0 -1
  167. package/dist/migrations/v2.0/checkout-upstream-files.js +0 -146
  168. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts +0 -2
  169. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +0 -1
  170. package/dist/migrations/v2.0/convert-config-files-to-ts.js +0 -838
  171. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts +0 -3
  172. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +0 -1
  173. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +0 -158
  174. package/dist/migrations/v2.0/create-events-index.d.ts.map +0 -1
  175. package/dist/migrations/v2.0/create-events-index.js +0 -325
  176. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +0 -11
  177. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +0 -1
  178. package/dist/migrations/v2.0/delete-infrastructure-directory.js +0 -123
  179. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +0 -3
  180. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +0 -1
  181. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +0 -110
  182. package/dist/migrations/v2.0/index.d.ts +0 -13
  183. package/dist/migrations/v2.0/index.d.ts.map +0 -1
  184. package/dist/migrations/v2.0/index.js +0 -103
  185. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts +0 -3
  186. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +0 -1
  187. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +0 -432
  188. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +0 -13
  189. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +0 -1
  190. package/dist/migrations/v2.0/merge-infrastructure-directory.js +0 -222
  191. package/dist/migrations/v2.0/migrate-application-config-url.d.ts +0 -3
  192. package/dist/migrations/v2.0/migrate-application-config-url.d.ts.map +0 -1
  193. package/dist/migrations/v2.0/migrate-application-config-url.js +0 -343
  194. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +0 -1
  195. package/dist/migrations/v2.0/migrate-scopes.js +0 -305
  196. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts +0 -3
  197. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +0 -1
  198. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +0 -267
  199. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts +0 -3
  200. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +0 -1
  201. package/dist/migrations/v2.0/migrate-workqueue-configs.js +0 -317
  202. package/dist/migrations/v2.0/remove-delete-actions.d.ts +0 -3
  203. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +0 -1
  204. package/dist/migrations/v2.0/remove-delete-actions.js +0 -156
  205. package/dist/migrations/v2.0/remove-demo-scope.d.ts +0 -3
  206. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +0 -1
  207. package/dist/migrations/v2.0/remove-demo-scope.js +0 -74
  208. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts +0 -3
  209. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +0 -1
  210. package/dist/migrations/v2.0/remove-deprecated-imports.js +0 -96
  211. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts +0 -3
  212. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts.map +0 -1
  213. package/dist/migrations/v2.0/remove-fhir-url-helpers.js +0 -163
  214. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts +0 -3
  215. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +0 -1
  216. package/dist/migrations/v2.0/remove-hearth-migrations.js +0 -87
  217. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts +0 -3
  218. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts.map +0 -1
  219. package/dist/migrations/v2.0/remove-old-statistics-service.js +0 -356
  220. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts +0 -3
  221. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +0 -1
  222. package/dist/migrations/v2.0/remove-pending-certification-flag.js +0 -109
  223. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts +0 -3
  224. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +0 -1
  225. package/dist/migrations/v2.0/remove-review-from-register-action.js +0 -163
  226. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts +0 -3
  227. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts.map +0 -1
  228. package/dist/migrations/v2.0/remove-unused-environment-variables.js +0 -186
  229. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +0 -1
  230. package/dist/migrations/v2.0/rename-location-parent-id.d.ts +0 -3
  231. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +0 -1
  232. package/dist/migrations/v2.0/rename-location-parent-id.js +0 -180
  233. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts +0 -3
  234. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +0 -1
  235. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +0 -195
  236. package/dist/migrations/v2.0/update-package-json.d.ts +0 -3
  237. package/dist/migrations/v2.0/update-package-json.d.ts.map +0 -1
  238. package/dist/migrations/v2.0/update-package-json.js +0 -105
  239. package/dist/templates/inventory/production.example.yml +0 -77
  240. package/dist/templates/inventory/qa.example.yml +0 -48
  241. package/opencrvs-toolkit-2.1.0-rc.7985421.tgz +0 -0
  242. package/tsconfig.tsbuildinfo +0 -1
@@ -212,7 +212,1959 @@ Done. Added ${totalChanges} correction action config(s) across ${modifiedFiles.l
212
212
  );
213
213
  }
214
214
 
215
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
216
+ var import_ts_morph2 = require("ts-morph");
217
+ var import_fs2 = require("fs");
218
+ var import_path2 = __toESM(require("path"));
219
+
220
+ // src/csv.ts
221
+ var import_fs = require("fs");
222
+ function parseCsvLine(line) {
223
+ const values = [];
224
+ let value = "";
225
+ let quoted = false;
226
+ for (let index = 0; index < line.length; index++) {
227
+ const character = line[index];
228
+ if (quoted) {
229
+ if (character !== '"') {
230
+ value += character;
231
+ } else if (line[index + 1] === '"') {
232
+ value += '"';
233
+ index++;
234
+ } else {
235
+ quoted = false;
236
+ }
237
+ continue;
238
+ }
239
+ if (character === '"') {
240
+ quoted = true;
241
+ } else if (character === ",") {
242
+ values.push(value);
243
+ value = "";
244
+ } else {
245
+ value += character;
246
+ }
247
+ }
248
+ values.push(value);
249
+ return values;
250
+ }
251
+ function toCsvLine(values) {
252
+ return values.map(
253
+ (value) => /["\n,]/.test(value) ? `"${value.replace(/"/g, '""')}"` : value
254
+ ).join(",");
255
+ }
256
+ function idOf(line) {
257
+ const comma = line.indexOf(",");
258
+ return comma === -1 ? line : line.slice(0, comma);
259
+ }
260
+ function readCsvFile(path10) {
261
+ if (!(0, import_fs.existsSync)(path10)) {
262
+ return void 0;
263
+ }
264
+ const contents = (0, import_fs.readFileSync)(path10, "utf8");
265
+ const newline = contents.includes("\r\n") ? "\r\n" : "\n";
266
+ const trailingNewline = /\r?\n$/.test(contents);
267
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
268
+ const body = lines.slice(1).filter((line) => line !== "");
269
+ return { header: lines[0], body, newline, trailingNewline };
270
+ }
271
+ function writeCsvFile(path10, file) {
272
+ (0, import_fs.writeFileSync)(
273
+ path10,
274
+ [file.header, ...file.body].join(file.newline) + (file.trailingNewline ? file.newline : "")
275
+ );
276
+ }
277
+ function addRows(file, rows) {
278
+ const isSorted = file.body.every(
279
+ (line, index) => index === 0 || idOf(file.body[index - 1]) <= idOf(line)
280
+ );
281
+ const added = [];
282
+ for (const row of rows) {
283
+ const id = idOf(row);
284
+ if (file.body.some((line) => idOf(line) === id)) {
285
+ continue;
286
+ }
287
+ const insertAt = isSorted ? file.body.findIndex((line) => idOf(line) > id) : -1;
288
+ if (insertAt === -1) {
289
+ file.body.push(row);
290
+ } else {
291
+ file.body.splice(insertAt, 0, row);
292
+ }
293
+ added.push(id);
294
+ }
295
+ return added;
296
+ }
297
+
298
+ // src/migrations/v2.1/add-recovery-link-notifications.ts
299
+ var EMAIL_TEMPLATES_FILE = "src/api/notification/email-templates/index.ts";
300
+ var SMS_SERVICE_FILE = "src/api/notification/sms-service.ts";
301
+ var HANDLER_FILE = "src/api/notification/handler.ts";
302
+ var ROUTES_FILE = "src/config/routes/userNotificationRoutes.ts";
303
+ var EMAIL_TEMPLATE_DIR = "src/api/notification/email-templates/other";
304
+ var NOTIFICATION_CSV = "src/translations/notification.csv";
305
+ var LOGIN_CSV = "src/translations/login.csv";
306
+ var TRIGGER_VARIABLE_OBJECT = "TriggerVariable";
307
+ var TEMPLATES_OBJECT = "templates";
308
+ var OTHER_TEMPLATES_OBJECT = "otherTemplates";
309
+ var TRIGGER_TO_SMS_TEMPLATE_OBJECT = "TriggerToSMSTemplate";
310
+ var CONVERT_PAYLOAD_FUNCTION = "convertPayloadToVariable";
311
+ var ROUTES_FUNCTION = "getUserNotificationRoutes";
312
+ var RECOVERY_EVENTS = [
313
+ {
314
+ id: "password-reset-link",
315
+ constant: "PASSWORD_RESET_LINK",
316
+ smsTemplate: "resetPasswordLinkNotification",
317
+ emailSubject: "Reset your password",
318
+ routeDescription: "Handles notification for password reset recovery link",
319
+ heading: "Reset your password",
320
+ reason: "Someone asked to reset the password for your {{applicationName}}\n account.",
321
+ linkLabel: "Reset your password"
322
+ },
323
+ {
324
+ id: "username-reminder-link",
325
+ constant: "USERNAME_REMINDER_LINK",
326
+ smsTemplate: "retrieveUsernameLinkNotification",
327
+ emailSubject: "Retrieve your username",
328
+ routeDescription: "Handles notification for username reminder recovery link",
329
+ heading: "Retrieve your username",
330
+ reason: "Someone asked for a reminder of the username for your\n {{applicationName}} account.",
331
+ linkLabel: "Retrieve your username"
332
+ }
333
+ ];
334
+ var NOTIFICATION_CSV_ROWS = [
335
+ `resetPasswordLinkNotification,The SMS message that is sent to a user containing a self-service password reset link,{{applicationName}}: reset your password using this link. It expires in 1 hour. {{{recoveryURL}}},{{applicationName}} : r\xE9initialisez votre mot de passe \xE0 l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`,
336
+ `retrieveUsernameLinkNotification,The SMS message that is sent to a user containing a self-service username retrieval link,{{applicationName}}: retrieve your username using this link. It expires in 1 hour. {{{recoveryURL}}},{{applicationName}} : r\xE9cup\xE9rez votre nom d'utilisateur \xE0 l'aide de ce lien. Il expire dans 1 heure. {{{recoveryURL}}}`
337
+ ];
338
+ var LOGIN_CSV_ROWS = [
339
+ `buttons.backToLogin,"Label used to leave a screen that is waiting on an emailed link, where logging in is not yet possible",Back to login,Retour \xE0 la connexion`,
340
+ `resetCredentials.recoveryInstructionsSent.body,"Body message for the recovery instructions sent page. Must not assert delivery, since the account may not exist.","If we found an account, you'll receive instructions for {forgottenItem, select, username {retrieving your username} other {resetting your password}}. The link expires in 1 hour.","Si nous trouvons un compte correspondant, vous recevrez les instructions pour {forgottenItem, select, username {r\xE9cup\xE9rer votre nom d'utilisateur} other {r\xE9initialiser votre mot de passe}}. Le lien expire dans 1 heure."`,
341
+ `resetCredentials.recoveryInstructionsSent.title.email,Title for the recovery instructions sent page when notifications are delivered by email,Check your email,V\xE9rifiez votre e-mail`,
342
+ `resetCredentials.recoveryInstructionsSent.title.phone,Title for the recovery instructions sent page when notifications are delivered by SMS,Check your phone,V\xE9rifiez votre t\xE9l\xE9phone`,
343
+ `resetCredentials.recoveryLinkLanding.expired.body,"Body shown when a recovery link is invalid, expired, or already used. Must not reveal whether the underlying account exists.",This link is no longer valid. Request a new one to continue.,Ce lien n'est plus valide. Veuillez en demander un nouveau pour continuer.`,
344
+ `resetCredentials.recoveryLinkLanding.expired.link,Link back to the forgotten item form shown on an expired/invalid recovery link,Start again,Recommencer`,
345
+ `resetCredentials.recoveryLinkLanding.expired.title,"Title shown when a recovery link is invalid, expired, or already used",This link has expired,Ce lien a expir\xE9`
346
+ ];
347
+ var skipped = [];
348
+ function warnSkipped(message) {
349
+ skipped.push(message);
350
+ console.warn(` \u26A0\uFE0F ${message}`);
351
+ }
352
+ function findObjectLiteral(declaration) {
353
+ let expression = declaration?.getInitializer();
354
+ while (expression && (import_ts_morph2.Node.isAsExpression(expression) || import_ts_morph2.Node.isSatisfiesExpression(expression))) {
355
+ expression = expression.getExpression();
356
+ }
357
+ return expression && import_ts_morph2.Node.isObjectLiteralExpression(expression) ? expression : void 0;
358
+ }
359
+ function hasKeyFor(obj, key, constant) {
360
+ const accepted = /* @__PURE__ */ new Set([
361
+ `[TriggerEvent.${constant}]`,
362
+ `['${key}']`,
363
+ `["${key}"]`,
364
+ `'${key}'`,
365
+ `"${key}"`,
366
+ key
367
+ ]);
368
+ return obj.getProperties().some(
369
+ (property) => import_ts_morph2.Node.isPropertyAssignment(property) && accepted.has(property.getName().trim())
370
+ );
371
+ }
372
+ function renderKey(obj, key, constant) {
373
+ const names = obj.getProperties().filter(import_ts_morph2.Node.isPropertyAssignment).map((property) => property.getName().trim());
374
+ if (names.some((name) => name.startsWith("[TriggerEvent."))) {
375
+ return `[TriggerEvent.${constant}]`;
376
+ }
377
+ if (names.some((name) => name.startsWith("["))) {
378
+ return `['${key}']`;
379
+ }
380
+ return `'${key}'`;
381
+ }
382
+ function appendEntry(sourceFile, objectName, key, valueLines) {
383
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
384
+ const properties = obj?.getProperties() ?? [];
385
+ const lastProperty = properties[properties.length - 1];
386
+ if (!lastProperty) return false;
387
+ const indent = lastProperty.getIndentationText();
388
+ const entry = valueLines.map((line, index) => `${indent}${index === 0 ? `${key}: ${line}` : line}`).join("\n");
389
+ sourceFile.insertText(lastProperty.getEnd(), `,
390
+ ${entry}`);
391
+ return true;
392
+ }
393
+ function objectHasKeyFor(sourceFile, objectName, key, constant) {
394
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
395
+ return obj ? hasKeyFor(obj, key, constant) : false;
396
+ }
397
+ function renderKeyFor(sourceFile, objectName, key, constant) {
398
+ const obj = findObjectLiteral(sourceFile.getVariableDeclaration(objectName));
399
+ return obj ? renderKey(obj, key, constant) : `'${key}'`;
400
+ }
401
+ function updateEmailTemplates(project, cwd) {
402
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, EMAIL_TEMPLATES_FILE));
403
+ if (!sourceFile) {
404
+ warnSkipped(`${EMAIL_TEMPLATES_FILE} not found; email templates not wired`);
405
+ return;
406
+ }
407
+ const missingObject = [TRIGGER_VARIABLE_OBJECT, TEMPLATES_OBJECT].find(
408
+ (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
409
+ );
410
+ if (missingObject) {
411
+ warnSkipped(
412
+ `Could not find '${missingObject}' in ${EMAIL_TEMPLATES_FILE}; email templates not wired`
413
+ );
414
+ return;
415
+ }
416
+ for (const event of RECOVERY_EVENTS) {
417
+ if (!objectHasKeyFor(
418
+ sourceFile,
419
+ TRIGGER_VARIABLE_OBJECT,
420
+ event.id,
421
+ event.constant
422
+ ) && appendEntry(
423
+ sourceFile,
424
+ TRIGGER_VARIABLE_OBJECT,
425
+ renderKeyFor(
426
+ sourceFile,
427
+ TRIGGER_VARIABLE_OBJECT,
428
+ event.id,
429
+ event.constant
430
+ ),
431
+ [
432
+ "z.object({",
433
+ " firstname: z.string(),",
434
+ " applicationName: z.string(),",
435
+ " countryLogo: z.string(),",
436
+ " recoveryURL: z.string()",
437
+ "})"
438
+ ]
439
+ )) {
440
+ console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} variables`);
441
+ }
442
+ if (!objectHasKeyFor(
443
+ sourceFile,
444
+ TEMPLATES_OBJECT,
445
+ event.id,
446
+ event.constant
447
+ ) && appendEntry(
448
+ sourceFile,
449
+ TEMPLATES_OBJECT,
450
+ renderKeyFor(sourceFile, TEMPLATES_OBJECT, event.id, event.constant),
451
+ [
452
+ "{",
453
+ ` type: '${event.id}',`,
454
+ ` subject: '${event.emailSubject}',`,
455
+ ` template: readOtherTemplate<TriggerVariable['${event.id}']>(`,
456
+ ` '${event.id}'`,
457
+ " )",
458
+ "}"
459
+ ]
460
+ )) {
461
+ console.log(` \u2713 ${EMAIL_TEMPLATES_FILE}: ${event.id} template`);
462
+ }
463
+ }
464
+ }
465
+ function updateSmsService(project, cwd) {
466
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, SMS_SERVICE_FILE));
467
+ if (!sourceFile) {
468
+ warnSkipped(`${SMS_SERVICE_FILE} not found; SMS templates not wired`);
469
+ return;
470
+ }
471
+ const missingObject = [
472
+ OTHER_TEMPLATES_OBJECT,
473
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT
474
+ ].find(
475
+ (objectName) => !findObjectLiteral(sourceFile.getVariableDeclaration(objectName))
476
+ );
477
+ if (missingObject) {
478
+ warnSkipped(
479
+ `Could not find '${missingObject}' in ${SMS_SERVICE_FILE}; SMS templates not wired`
480
+ );
481
+ return;
482
+ }
483
+ for (const event of RECOVERY_EVENTS) {
484
+ if (!objectHasKeyFor(
485
+ sourceFile,
486
+ OTHER_TEMPLATES_OBJECT,
487
+ event.smsTemplate,
488
+ event.smsTemplate
489
+ ) && appendEntry(sourceFile, OTHER_TEMPLATES_OBJECT, event.smsTemplate, [
490
+ `'${event.smsTemplate}'`
491
+ ])) {
492
+ console.log(` \u2713 ${SMS_SERVICE_FILE}: ${event.smsTemplate}`);
493
+ }
494
+ if (!objectHasKeyFor(
495
+ sourceFile,
496
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
497
+ event.id,
498
+ event.constant
499
+ ) && appendEntry(
500
+ sourceFile,
501
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
502
+ renderKeyFor(
503
+ sourceFile,
504
+ TRIGGER_TO_SMS_TEMPLATE_OBJECT,
505
+ event.id,
506
+ event.constant
507
+ ),
508
+ [`'${event.smsTemplate}'`]
509
+ )) {
510
+ console.log(
511
+ ` \u2713 ${SMS_SERVICE_FILE}: ${event.id} -> ${event.smsTemplate}`
512
+ );
513
+ }
514
+ }
515
+ }
516
+ function updateHandler(project, cwd) {
517
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, HANDLER_FILE));
518
+ if (!sourceFile) {
519
+ warnSkipped(`${HANDLER_FILE} not found; payload conversion not wired`);
520
+ return;
521
+ }
522
+ const convertPayload = sourceFile.getFunction(CONVERT_PAYLOAD_FUNCTION);
523
+ const caseBlock = convertPayload?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.SwitchStatement)?.getCaseBlock();
524
+ if (!caseBlock) {
525
+ warnSkipped(
526
+ `Could not find a switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE}; payload conversion not wired`
527
+ );
528
+ return;
529
+ }
530
+ const missing = RECOVERY_EVENTS.filter(
531
+ (event) => !caseBlock.getText().includes(`TriggerEvent.${event.constant}`) && !caseBlock.getText().includes(`'${event.id}'`)
532
+ );
533
+ if (missing.length === 0) return;
534
+ const existingClauses = caseBlock.getClauses();
535
+ if (existingClauses.length === 0) {
536
+ warnSkipped(
537
+ `The switch inside '${CONVERT_PAYLOAD_FUNCTION}' in ${HANDLER_FILE} has no cases; payload conversion not wired`
538
+ );
539
+ return;
540
+ }
541
+ const defaultClause = existingClauses.find(import_ts_morph2.Node.isDefaultClause);
542
+ const anchor = defaultClause ?? existingClauses[existingClauses.length - 1];
543
+ const indent = anchor.getIndentationText();
544
+ const lines = [
545
+ ...missing.map((event) => `case TriggerEvent.${event.constant}:`),
546
+ ` return {`,
547
+ ` firstname,`,
548
+ ` applicationName: applicationConfig.APPLICATION_NAME,`,
549
+ ` countryLogo: COUNTRY_LOGO_URL,`,
550
+ ` recoveryURL: \`\${LOGIN_URL}recover?token=\${encodeURIComponent(payload.token)}\``,
551
+ ` }`
552
+ ];
553
+ if (defaultClause) {
554
+ caseBlock.insertText(
555
+ anchor.getStart(),
556
+ `${lines.map((line, index) => index === 0 ? line : `${indent}${line}`).join("\n")}
557
+ ${indent}`
558
+ );
559
+ } else {
560
+ caseBlock.insertText(
561
+ anchor.getEnd(),
562
+ `
563
+ ${lines.map((line) => `${indent}${line}`).join("\n")}`
564
+ );
565
+ }
566
+ for (const event of missing) {
567
+ console.log(` \u2713 ${HANDLER_FILE}: ${event.id} case`);
568
+ }
569
+ }
570
+ function updateRoutes(project, cwd) {
571
+ const sourceFile = project.getSourceFile(import_path2.default.join(cwd, ROUTES_FILE));
572
+ if (!sourceFile) {
573
+ warnSkipped(`${ROUTES_FILE} not found; trigger routes not registered`);
574
+ return;
575
+ }
576
+ const routesFunction = sourceFile.getFunction(ROUTES_FUNCTION) ?? sourceFile.getFunctions().find((fn) => fn.isDefaultExport());
577
+ const routesArray = routesFunction?.getFirstDescendantByKind(import_ts_morph2.SyntaxKind.ReturnStatement)?.getExpressionIfKind(import_ts_morph2.SyntaxKind.ArrayLiteralExpression);
578
+ if (!routesArray) {
579
+ warnSkipped(
580
+ `Could not find the route array returned by '${ROUTES_FUNCTION}' in ${ROUTES_FILE}; trigger routes not registered`
581
+ );
582
+ return;
583
+ }
584
+ for (const event of RECOVERY_EVENTS) {
585
+ if (routesArray.getText().includes(`/trigger/user/${event.id}`)) continue;
586
+ routesArray.addElement(`{
587
+ method: 'POST',
588
+ path: '/trigger/user/${event.id}',
589
+ handler: makeNotificationHandler('${event.id}'),
590
+ options: {
591
+ auth: false,
592
+ tags: ['api'],
593
+ description: '${event.routeDescription}'
594
+ }
595
+ }`);
596
+ console.log(` \u2713 ${ROUTES_FILE}: POST /trigger/user/${event.id}`);
597
+ }
598
+ }
599
+ function renderEmailTemplate(event) {
600
+ return `<!--
601
+ This Source Code Form is subject to the terms of the Mozilla Public
602
+ License, v. 2.0. If a copy of the MPL was not distributed with this
603
+ file, You can obtain one at https://mozilla.org/MPL/2.0/.
604
+
605
+ OpenCRVS is also distributed under the terms of the Civil Registration
606
+ & Healthcare Disclaimer located at http://opencrvs.org/license.
607
+
608
+ Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
609
+ -->
610
+ <!doctype html>
611
+ <html>
612
+ <head>
613
+ <link
614
+ href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
615
+ rel="stylesheet"
616
+ />
617
+ <style type="text/css">
618
+ body {
619
+ font-family: 'Noto Sans', sans-serif;
620
+ color: #222;
621
+ padding: 16px 24px;
622
+ }
623
+
624
+ h1 {
625
+ font-size: 21px;
626
+ margin-top: 32px;
627
+ margin-bottom: 36px;
628
+ font-weight: 700;
629
+ }
630
+
631
+ p {
632
+ font-weight: 400;
633
+ font-size: 16px;
634
+ line-height: 1.8;
635
+ margin-bottom: 24px;
636
+ }
637
+
638
+ i {
639
+ color: #666;
640
+ font-weight: 400;
641
+ font-size: 16px;
642
+ }
643
+ </style>
644
+ </head>
645
+
646
+ <body>
647
+ <img
648
+ src="{{countryLogo}}"
649
+ alt="country_logo"
650
+ style="max-height: 88px; max-width: 100%"
651
+ />
652
+ <h1>${event.heading}</h1>
653
+ <p>Hello {{firstname}},</p>
654
+ <p>
655
+ ${event.reason}
656
+ </p>
657
+
658
+ <div style="margin-top: 32px; margin-bottom: 32px">
659
+ <a href="{{{recoveryURL}}}">${event.linkLabel}</a>
660
+ </div>
661
+ <br />
662
+ <p>
663
+ This link expires in 1 hour and can only be used once. If you did not
664
+ request this, you can ignore this email.
665
+ </p>
666
+ <br />
667
+ <p>
668
+ Best regards, <br />
669
+ {{applicationName}} Team
670
+ </p>
671
+ </body>
672
+ </html>
673
+ `;
674
+ }
675
+ function writeEmailTemplates(cwd) {
676
+ const templateDir = import_path2.default.join(cwd, EMAIL_TEMPLATE_DIR);
677
+ if (!(0, import_fs2.existsSync)(templateDir)) {
678
+ warnSkipped(
679
+ `${EMAIL_TEMPLATE_DIR} not found; recovery email bodies not written`
680
+ );
681
+ return;
682
+ }
683
+ for (const event of RECOVERY_EVENTS) {
684
+ const templatePath = import_path2.default.join(templateDir, `${event.id}.html`);
685
+ if ((0, import_fs2.existsSync)(templatePath)) continue;
686
+ (0, import_fs2.writeFileSync)(templatePath, renderEmailTemplate(event));
687
+ console.log(` \u2713 ${EMAIL_TEMPLATE_DIR}/${event.id}.html`);
688
+ }
689
+ }
690
+ function addCsvRows(cwd, relativePath, rows) {
691
+ const csvPath = import_path2.default.join(cwd, relativePath);
692
+ const file = readCsvFile(csvPath);
693
+ if (!file) {
694
+ warnSkipped(`${relativePath} not found; translations not added`);
695
+ return;
696
+ }
697
+ const added = addRows(file, rows);
698
+ if (added.length === 0) return;
699
+ for (const id of added) {
700
+ console.log(` \u2713 ${relativePath}: ${id}`);
701
+ }
702
+ writeCsvFile(csvPath, file);
703
+ }
704
+ async function main2() {
705
+ const cwd = process.cwd();
706
+ const tsConfigFilePath = import_path2.default.join(cwd, "tsconfig.json");
707
+ console.log(
708
+ "Registering the password-reset-link and username-reminder-link notifications...\n"
709
+ );
710
+ if (!(0, import_fs2.existsSync)(tsConfigFilePath)) {
711
+ warnSkipped(
712
+ `tsconfig.json not found in ${cwd}; notification wiring skipped entirely`
713
+ );
714
+ return;
715
+ }
716
+ const project = new import_ts_morph2.Project({
717
+ tsConfigFilePath,
718
+ skipAddingFilesFromTsConfig: false,
719
+ // ts-morph indents inserted code with four spaces by default, which every
720
+ // country config's prettier run would immediately undo.
721
+ manipulationSettings: { indentationText: import_ts_morph2.IndentationText.TwoSpaces }
722
+ });
723
+ updateEmailTemplates(project, cwd);
724
+ updateSmsService(project, cwd);
725
+ updateHandler(project, cwd);
726
+ updateRoutes(project, cwd);
727
+ await project.save();
728
+ writeEmailTemplates(cwd);
729
+ addCsvRows(cwd, NOTIFICATION_CSV, NOTIFICATION_CSV_ROWS);
730
+ addCsvRows(cwd, LOGIN_CSV, LOGIN_CSV_ROWS);
731
+ if (skipped.length > 0) {
732
+ console.warn(
733
+ `
734
+ \u26A0\uFE0F ${skipped.length} step(s) were skipped. Wire the following by hand before upgrading:`
735
+ );
736
+ for (const message of skipped) {
737
+ console.warn(` - ${message}`);
738
+ }
739
+ }
740
+ }
741
+
742
+ // src/migrations/v2.1/add-translations.ts
743
+ var import_path3 = __toESM(require("path"));
744
+
745
+ // src/translations/template.ts
746
+ var REPOSITORY = "opencrvs/opencrvs-core";
747
+ var TEMPLATE_TRANSLATIONS = "packages/countryconfig-template/src/translations";
748
+ async function matchingRefs(namespace, prefix) {
749
+ const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
750
+ const response = await fetch(url, {
751
+ headers: { accept: "application/vnd.github+json" }
752
+ });
753
+ if (!response.ok) {
754
+ throw new Error(
755
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
756
+ );
757
+ }
758
+ const refs = await response.json();
759
+ const patchOf = (ref) => Number(ref.split(".").pop()) || 0;
760
+ return refs.map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, "")).sort((a, b) => patchOf(b) - patchOf(a));
761
+ }
762
+ async function candidateRefs(version) {
763
+ return [
764
+ ...await matchingRefs("heads", `release/${version}.`),
765
+ ...await matchingRefs("tags", `v${version}.`),
766
+ "develop"
767
+ ];
768
+ }
769
+ async function fetchTemplate(refs, application) {
770
+ for (const ref of refs) {
771
+ const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
772
+ const response = await fetch(url);
773
+ if (response.ok) {
774
+ return { ref, contents: await response.text() };
775
+ }
776
+ if (response.status !== 404) {
777
+ throw new Error(
778
+ `GitHub answered ${response.status} ${response.statusText} for ${url}`
779
+ );
780
+ }
781
+ }
782
+ return void 0;
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
+ }
793
+ function rowsToAdd(local, template) {
794
+ const localColumns = parseCsvLine(local.header);
795
+ const templateColumns = parseCsvLine(template.header);
796
+ return template.body.filter((line) => line !== "").map((line) => {
797
+ const values = parseCsvLine(line);
798
+ return toCsvLine(
799
+ localColumns.map((column) => {
800
+ const index = templateColumns.indexOf(column);
801
+ return index === -1 ? "" : values[index] ?? "";
802
+ })
803
+ );
804
+ });
805
+ }
806
+ async function updateApplication(cwd, refs, application) {
807
+ const relativePath = `src/translations/${application}.csv`;
808
+ const local = readCsvFile(import_path3.default.join(cwd, relativePath));
809
+ if (!local) {
810
+ warnSkipped2(`${relativePath} not found; translations not added`);
811
+ return;
812
+ }
813
+ const fetched = await fetchTemplate(refs, application);
814
+ if (!fetched) {
815
+ warnSkipped2(
816
+ `No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`
817
+ );
818
+ return;
819
+ }
820
+ const template = readTemplate(fetched.contents);
821
+ const added = addRows(local, rowsToAdd(local, template));
822
+ if (added.length === 0) {
823
+ return;
824
+ }
825
+ try {
826
+ writeCsvFile(import_path3.default.join(cwd, relativePath), local);
827
+ } catch (error) {
828
+ warnSkipped2(
829
+ `Could not write ${relativePath} (${error.message}); translations not added`
830
+ );
831
+ return;
832
+ }
833
+ for (const id of added) {
834
+ console.log(` \u2713 ${relativePath}: ${id}`);
835
+ }
836
+ }
837
+ function readTemplate(contents) {
838
+ const lines = contents.replace(/\r?\n$/, "").split(/\r?\n/);
839
+ return {
840
+ header: lines[0],
841
+ body: lines.slice(1),
842
+ newline: "\n",
843
+ trailingNewline: true
844
+ };
845
+ }
846
+ async function listRefs() {
847
+ try {
848
+ return await candidateRefs(TARGET_VERSION);
849
+ } catch (error) {
850
+ warnSkipped2(
851
+ `Could not list the ${TARGET_VERSION} refs on GitHub (${error.message}); translations not added`
852
+ );
853
+ return void 0;
854
+ }
855
+ }
856
+ async function main3() {
857
+ const cwd = process.cwd();
858
+ console.log("Adding the translation keys core gained this version...\n");
859
+ const refs = await listRefs();
860
+ if (refs) {
861
+ for (const application of APPLICATIONS) {
862
+ try {
863
+ await updateApplication(cwd, refs, application);
864
+ } catch (error) {
865
+ warnSkipped2(
866
+ `Could not read ${application}.csv from the country config template on GitHub (${error.message}); ${application}.csv not updated`
867
+ );
868
+ }
869
+ }
870
+ }
871
+ if (skipped2.length > 0) {
872
+ console.warn(
873
+ `
874
+ \u26A0\uFE0F ${skipped2.length} step(s) were skipped. Add the missing translations by hand before upgrading:`
875
+ );
876
+ for (const message of skipped2) {
877
+ console.warn(` - ${message}`);
878
+ }
879
+ }
880
+ }
881
+
882
+ // src/migrations/v2.1/enable-telemetry.ts
883
+ var import_ts_morph3 = require("ts-morph");
884
+ var import_fs3 = require("fs");
885
+ var import_path4 = __toESM(require("path"));
886
+ var HANDLER_FILE2 = "src/api/telemetry/handler.ts";
887
+ var ENVIRONMENT_FILE = "src/environment.ts";
888
+ var INDEX_FILE = "src/index.ts";
889
+ var HANDLER_MODULE = "./api/telemetry/handler";
890
+ var skipped3 = [];
891
+ function warnSkipped3(message) {
892
+ skipped3.push(message);
893
+ console.warn(` \u26A0\uFE0F ${message}`);
894
+ }
895
+ var TELEMETRY_HANDLER_SOURCE = `/*
896
+ * This Source Code Form is subject to the terms of the Mozilla Public
897
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
898
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
899
+ *
900
+ * OpenCRVS is also distributed under the terms of the Civil Registration
901
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
902
+ *
903
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
904
+ */
905
+
906
+ import { Request, ResponseToolkit } from '@hapi/hapi'
907
+ import * as Joi from 'joi'
908
+ import { sendTelemetry, TelemetryReport } from '@opencrvs/toolkit/telemetry'
909
+ import { env } from '@countryconfig/environment'
910
+ import { logger } from '@countryconfig/logger'
911
+ import { applicationConfig } from '@countryconfig/api/application/application-config'
912
+
913
+ /** Report the events service posts to \`/trigger/telemetry\`. */
914
+ export const telemetrySchema = Joi.object({
915
+ reported_at: Joi.string().isoDate().required(),
916
+ app_version: Joi.string().optional(),
917
+ metrics: Joi.object()
918
+ .pattern(
919
+ Joi.string(),
920
+ Joi.alternatives(Joi.number(), Joi.string(), Joi.boolean())
921
+ )
922
+ .required()
923
+ })
924
+
925
+ interface IncomingReport {
926
+ reported_at: string
927
+ app_version?: string
928
+ metrics: Record<string, number | string | boolean>
929
+ }
930
+
931
+ /** Logged once at countryconfig startup while telemetry is disabled. */
932
+ export const TELEMETRY_DISABLED_NOTICE =
933
+ 'Telemetry is disabled. Help improve OpenCRVS by sharing anonymous, ' +
934
+ 'aggregate usage metrics (registration and certificate counts, active ' +
935
+ 'users, uptime) \u2014 no personal, health, or otherwise protected record data ' +
936
+ 'ever leaves your instance. Enable it by setting TELEMETRY_ENABLED=true on ' +
937
+ 'the countryconfig service.'
938
+
939
+ /**
940
+ * Receives a usage report from the events service and, when telemetry is
941
+ * enabled for this instance, stamps the instance identity onto it and forwards
942
+ * it to the status service via the toolkit's \`sendTelemetry\` (which owns the
943
+ * endpoint and payload schema). The events service is unaware of whether
944
+ * telemetry is enabled or of the country code / domain / environment reported.
945
+ */
946
+ export async function telemetryHandler(request: Request, h: ResponseToolkit) {
947
+ // Only accept OpenCRVS *system* tokens (the events service's service
948
+ // token has userType 'system'). A logged-in user's token is a 'user' token,
949
+ // so a user cannot submit telemetry with their own credentials \u2014 and the
950
+ // service-token endpoint is not reachable through the public gateway.
951
+ const credentials = request.auth.credentials as
952
+ | { userType?: string }
953
+ | undefined
954
+ if (credentials?.userType !== 'system') {
955
+ logger.warn('Telemetry: rejected a request that is not from a system token')
956
+ return h.response({ error: 'forbidden' }).code(403)
957
+ }
958
+
959
+ if (!env.TELEMETRY_ENABLED) {
960
+ // The encouraging notice is logged once at startup (see index.ts); keep the
961
+ // per-report path quiet.
962
+ return h.response({ status: 'skipped' }).code(200)
963
+ }
964
+
965
+ const incoming = request.payload as IncomingReport
966
+
967
+ // Only production instances report; staging, QA and local build the report
968
+ // but never reach the status service. (This gate used to live in the
969
+ // toolkit's sendTelemetry; each country config now owns it.)
970
+ if (!env.isProduction) {
971
+ logger.info(
972
+ \`Telemetry: report for \${incoming.reported_at} was not sent \u2014 only production instances report\`
973
+ )
974
+ return h.response({ status: 'skipped' }).code(200)
975
+ }
976
+
977
+ const report: TelemetryReport = {
978
+ reported_at: incoming.reported_at,
979
+ country_code: env.COUNTRY_CODE,
980
+ organisation: env.ORGANISATION,
981
+ // env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
982
+ // "no domain" rather than reporting a literal "*".
983
+ domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
984
+ instance: {
985
+ application_name: applicationConfig.APPLICATION_NAME,
986
+ environment: env.ENVIRONMENT_NAME,
987
+ app_version: incoming.app_version
988
+ },
989
+ metrics: incoming.metrics
990
+ }
991
+
992
+ let result
993
+ try {
994
+ result = await sendTelemetry(report)
995
+ } catch (error) {
996
+ const message = error instanceof Error ? error.message : String(error)
997
+ logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
998
+ return h.response({ status: 'error' }).code(502)
999
+ }
1000
+
1001
+ if (result.outcome === 'rejected') {
1002
+ logger.error(
1003
+ \`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
1004
+ )
1005
+ return h.response({ status: 'error' }).code(502)
1006
+ }
1007
+
1008
+ logger.info(
1009
+ \`Telemetry: forwarded report for \${report.reported_at} to the status service\`
1010
+ )
1011
+ return h.response({ status: 'forwarded' }).code(202)
1012
+ }
1013
+ `;
1014
+ var TELEMETRY_DISABLED = {
1015
+ enabled: false,
1016
+ countryCode: "",
1017
+ organisation: ""
1018
+ };
1019
+ async function promptTelemetryConfig() {
1020
+ if (!process.stdin.isTTY) {
1021
+ return TELEMETRY_DISABLED;
1022
+ }
1023
+ const { confirm, input } = await import("@inquirer/prompts");
1024
+ const enabled = await confirm({
1025
+ message: "Enable anonymous usage telemetry to help improve OpenCRVS? Only aggregate metrics are shared \u2014 no personal or protected data.",
1026
+ default: true
1027
+ });
1028
+ if (!enabled) {
1029
+ return TELEMETRY_DISABLED;
1030
+ }
1031
+ const countryCode = (await input({
1032
+ message: "Country code (ISO alpha-3, e.g. FAR):",
1033
+ validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) || "Enter a 3-letter ISO alpha-3 code."
1034
+ })).trim().toUpperCase();
1035
+ const organisation = (await input({
1036
+ message: "Organisation running this instance:",
1037
+ validate: (value) => value.trim() !== "" || "Enter an organisation name."
1038
+ })).trim();
1039
+ return { enabled: true, countryCode, organisation };
1040
+ }
1041
+ function writeTelemetryHandler(cwd) {
1042
+ const handlerPath = import_path4.default.join(cwd, HANDLER_FILE2);
1043
+ if ((0, import_fs3.existsSync)(handlerPath)) {
1044
+ console.log(` ${HANDLER_FILE2} already present; left unchanged`);
1045
+ return;
1046
+ }
1047
+ (0, import_fs3.mkdirSync)(import_path4.default.dirname(handlerPath), { recursive: true });
1048
+ (0, import_fs3.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
1049
+ console.log(` \u2713 ${HANDLER_FILE2}`);
1050
+ }
1051
+ function appendProperty(sourceFile, object, name, valueLines) {
1052
+ const properties = object.getProperties();
1053
+ const lastProperty = properties[properties.length - 1];
1054
+ if (!lastProperty) return false;
1055
+ const indent = lastProperty.getIndentationText();
1056
+ const entry = valueLines.map((line, index) => `${indent}${index === 0 ? `${name}: ${line}` : line}`).join("\n");
1057
+ sourceFile.insertText(lastProperty.getEnd(), `,
1058
+ ${entry}`);
1059
+ return true;
1060
+ }
1061
+ function ensureEnvalidNamedImports(sourceFile, names) {
1062
+ const importDeclaration = sourceFile.getImportDeclarations().find((declaration) => declaration.getModuleSpecifierValue() === "envalid");
1063
+ if (!importDeclaration) {
1064
+ warnSkipped3(
1065
+ `Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(", ")} } by hand`
1066
+ );
1067
+ return;
1068
+ }
1069
+ const existing = new Set(
1070
+ importDeclaration.getNamedImports().map((named) => named.getName())
1071
+ );
1072
+ for (const name of names) {
1073
+ if (!existing.has(name)) {
1074
+ importDeclaration.addNamedImport(name);
1075
+ }
1076
+ }
1077
+ }
1078
+ function getCleanEnvObject(sourceFile) {
1079
+ const options = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).find((call) => call.getExpression().getText() === "cleanEnv")?.getArguments()[1];
1080
+ return options && import_ts_morph3.Node.isObjectLiteralExpression(options) ? options : void 0;
1081
+ }
1082
+ function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
1083
+ const object = getCleanEnvObject(sourceFile);
1084
+ if (!object) return;
1085
+ const existing = object.getProperty(name);
1086
+ if (existing && import_ts_morph3.Node.isPropertyAssignment(existing)) {
1087
+ if (!update) return;
1088
+ const options = existing.getInitializerIfKind(import_ts_morph3.SyntaxKind.CallExpression)?.getArguments()[0];
1089
+ if (options && import_ts_morph3.Node.isObjectLiteralExpression(options)) {
1090
+ const defaultProperty = options.getProperty("default");
1091
+ if (defaultProperty && import_ts_morph3.Node.isPropertyAssignment(defaultProperty)) {
1092
+ defaultProperty.setInitializer(defaultExpr);
1093
+ } else {
1094
+ options.insertPropertyAssignment(0, {
1095
+ name: "default",
1096
+ initializer: defaultExpr
1097
+ });
1098
+ }
1099
+ console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name} default set`);
1100
+ }
1101
+ return;
1102
+ }
1103
+ if (appendProperty(sourceFile, object, name, [
1104
+ `${kind}({`,
1105
+ ` default: ${defaultExpr},`,
1106
+ ` desc: ${JSON.stringify(desc)}`,
1107
+ "})"
1108
+ ])) {
1109
+ console.log(` \u2713 ${ENVIRONMENT_FILE}: ${name}`);
1110
+ }
1111
+ }
1112
+ function addEnvironmentVariables(project, cwd, config) {
1113
+ const sourceFile = project.addSourceFileAtPathIfExists(
1114
+ import_path4.default.join(cwd, ENVIRONMENT_FILE)
1115
+ );
1116
+ if (!sourceFile) {
1117
+ warnSkipped3(
1118
+ `${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`
1119
+ );
1120
+ return;
1121
+ }
1122
+ if (!getCleanEnvObject(sourceFile)) {
1123
+ warnSkipped3(
1124
+ `Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`
1125
+ );
1126
+ return;
1127
+ }
1128
+ ensureEnvalidNamedImports(sourceFile, ["bool", "str"]);
1129
+ upsertEnvVar(
1130
+ sourceFile,
1131
+ "TELEMETRY_ENABLED",
1132
+ "bool",
1133
+ config.enabled ? "true" : "false",
1134
+ "When true, usage telemetry received from the events service is forwarded to the OpenCRVS status service.",
1135
+ true
1136
+ );
1137
+ upsertEnvVar(
1138
+ sourceFile,
1139
+ "COUNTRY_CODE",
1140
+ "str",
1141
+ config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`,
1142
+ "ISO-style country code of this instance, reported with telemetry.",
1143
+ config.enabled
1144
+ );
1145
+ upsertEnvVar(
1146
+ sourceFile,
1147
+ "ORGANISATION",
1148
+ "str",
1149
+ config.enabled ? JSON.stringify(config.organisation) : `''`,
1150
+ "Organisation running this instance, reported with telemetry. Empty by default.",
1151
+ config.enabled
1152
+ );
1153
+ upsertEnvVar(
1154
+ sourceFile,
1155
+ "ENVIRONMENT_NAME",
1156
+ "str",
1157
+ `'development'`,
1158
+ 'Environment name (e.g. "production", "staging") reported as the telemetry environment.',
1159
+ false
1160
+ );
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
+ }
1187
+ function wireIndex(project, cwd) {
1188
+ const sourceFile = project.addSourceFileAtPathIfExists(
1189
+ import_path4.default.join(cwd, INDEX_FILE)
1190
+ );
1191
+ if (!sourceFile) {
1192
+ warnSkipped3(
1193
+ `${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`
1194
+ );
1195
+ return;
1196
+ }
1197
+ ensureHandlerNamedImports(sourceFile, [
1198
+ "telemetryHandler",
1199
+ "telemetrySchema",
1200
+ "TELEMETRY_DISABLED_NOTICE"
1201
+ ]);
1202
+ if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
1203
+ const lastRouteStatement = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.CallExpression).filter((call) => call.getExpression().getText() === "server.route").map(
1204
+ (call) => call.getFirstAncestorByKind(import_ts_morph3.SyntaxKind.ExpressionStatement)
1205
+ ).filter(
1206
+ (statement) => Boolean(statement)
1207
+ ).pop();
1208
+ if (!lastRouteStatement) {
1209
+ warnSkipped3(
1210
+ `Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`
1211
+ );
1212
+ } else {
1213
+ const indent = lastRouteStatement.getIndentationText();
1214
+ const route = [
1215
+ `server.route({`,
1216
+ ` method: 'POST',`,
1217
+ ` path: '/trigger/telemetry',`,
1218
+ ` handler: telemetryHandler,`,
1219
+ ` options: {`,
1220
+ ` tags: ['api', 'triggers'],`,
1221
+ ` validate: {`,
1222
+ ` payload: telemetrySchema`,
1223
+ ` },`,
1224
+ ` description:`,
1225
+ ` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
1226
+ ` }`,
1227
+ `})`
1228
+ ].map((line) => line ? `${indent}${line}` : line).join("\n");
1229
+ sourceFile.insertText(lastRouteStatement.getEnd(), `
1230
+
1231
+ ${route}`);
1232
+ console.log(` \u2713 ${INDEX_FILE}: POST /trigger/telemetry`);
1233
+ }
1234
+ }
1235
+ if (!sourceFile.getText().includes("logger.info(TELEMETRY_DISABLED_NOTICE)")) {
1236
+ const startedLog = sourceFile.getDescendantsOfKind(import_ts_morph3.SyntaxKind.ExpressionStatement).find(
1237
+ (statement) => statement.getText().includes("Server successfully started")
1238
+ );
1239
+ if (!startedLog) {
1240
+ warnSkipped3(
1241
+ `Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`
1242
+ );
1243
+ } else {
1244
+ const indent = startedLog.getIndentationText();
1245
+ const notice = [
1246
+ `if (!env.TELEMETRY_ENABLED) {`,
1247
+ ` logger.info(TELEMETRY_DISABLED_NOTICE)`,
1248
+ `}`
1249
+ ].map((line) => line ? `${indent}${line}` : line).join("\n");
1250
+ sourceFile.insertText(startedLog.getEnd(), `
1251
+
1252
+ ${notice}`);
1253
+ console.log(` \u2713 ${INDEX_FILE}: telemetry-disabled startup notice`);
1254
+ if (!sourceFile.getImportDeclarations().some((d) => d.getModuleSpecifierValue() === "./environment")) {
1255
+ warnSkipped3(
1256
+ `The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`
1257
+ );
1258
+ }
1259
+ }
1260
+ }
1261
+ }
1262
+ async function main4() {
1263
+ const cwd = process.cwd();
1264
+ const config = await promptTelemetryConfig();
1265
+ console.log(
1266
+ `
1267
+ Adding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : "disabled"} by default)...
1268
+ `
1269
+ );
1270
+ writeTelemetryHandler(cwd);
1271
+ const project = new import_ts_morph3.Project({
1272
+ // ts-morph indents inserted code with four spaces and double-quotes strings
1273
+ // by default, both of which the country config's prettier run would undo.
1274
+ manipulationSettings: {
1275
+ indentationText: import_ts_morph3.IndentationText.TwoSpaces,
1276
+ quoteKind: import_ts_morph3.QuoteKind.Single
1277
+ }
1278
+ });
1279
+ addEnvironmentVariables(project, cwd, config);
1280
+ wireIndex(project, cwd);
1281
+ await project.save();
1282
+ if (skipped3.length > 0) {
1283
+ console.warn(
1284
+ `
1285
+ \u26A0\uFE0F ${skipped3.length} telemetry step(s) were skipped. Wire the following by hand:`
1286
+ );
1287
+ for (const message of skipped3) {
1288
+ console.warn(` - ${message}`);
1289
+ }
1290
+ }
1291
+ }
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.`
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
+
215
2155
  // src/migrations/v2.1/index.ts
216
2156
  async function runUpgrade(dockerSwarm) {
217
2157
  await main();
2158
+ await main8();
2159
+ await main2();
2160
+ await main3();
2161
+ await main7();
2162
+ await main6();
2163
+ await main5(dockerSwarm);
2164
+ await main9();
2165
+ await main4();
218
2166
  }
2167
+ // Annotate the CommonJS export names for ESM import in node:
2168
+ 0 && (module.exports = {
2169
+ runUpgrade
2170
+ });