@opencrvs/toolkit 1.9.13-rc.fc5374d → 2.0.0-rc.e0918cb

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 (130) hide show
  1. package/build.sh +13 -0
  2. package/dist/api/index.d.ts.map +1 -1
  3. package/dist/application-config/index.d.ts +2 -0
  4. package/dist/application-config/index.d.ts.map +1 -0
  5. package/dist/application-config/index.js +2128 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +3633 -0
  9. package/dist/commons/api/router.d.ts +3438 -2300
  10. package/dist/commons/application-config/index.d.ts +84 -0
  11. package/dist/commons/conditionals/conditionals.d.ts +27 -3
  12. package/dist/commons/conditionals/validate.d.ts +13 -3
  13. package/dist/commons/events/ActionConfig.d.ts +415 -1555
  14. package/dist/commons/events/ActionDocument.d.ts +888 -1941
  15. package/dist/commons/events/ActionInput.d.ts +277 -1073
  16. package/dist/commons/events/ActionType.d.ts +91 -11
  17. package/dist/commons/events/AdvancedSearchConfig.d.ts +294 -1496
  18. package/dist/commons/events/AuditLog.d.ts +405 -0
  19. package/dist/commons/events/CompositeFieldValue.d.ts +30 -190
  20. package/dist/commons/events/Conditional.d.ts +26 -38
  21. package/dist/commons/events/Constants.d.ts +1 -1
  22. package/dist/commons/events/CountryConfigQueryInput.d.ts +1592 -4471
  23. package/dist/commons/events/DeduplicationConfig.d.ts +15 -171
  24. package/dist/commons/events/Draft.d.ts +72 -107
  25. package/dist/commons/events/DynamicFieldValue.d.ts +12 -78
  26. package/dist/commons/events/EventConfig.d.ts +37 -2420
  27. package/dist/commons/events/EventConfigInput.d.ts +0 -3
  28. package/dist/commons/events/EventDocument.d.ts +354 -1366
  29. package/dist/commons/events/EventIndex.d.ts +212 -1010
  30. package/dist/commons/events/EventInput.d.ts +3 -8
  31. package/dist/commons/events/EventMetadata.d.ts +130 -357
  32. package/dist/commons/events/FieldConfig.d.ts +2892 -12892
  33. package/dist/commons/events/FieldType.d.ts +26 -4
  34. package/dist/commons/events/FieldTypeMapping.d.ts +314 -906
  35. package/dist/commons/events/FieldValue.d.ts +149 -527
  36. package/dist/commons/events/FileUtils.d.ts +2 -2
  37. package/dist/commons/events/Flag.d.ts +67 -0
  38. package/dist/commons/events/FormConfig.d.ts +54 -721
  39. package/dist/commons/events/PageConfig.d.ts +58 -320
  40. package/dist/commons/events/PlainDate.d.ts +1 -1
  41. package/dist/commons/events/SummaryConfig.d.ts +14 -161
  42. package/dist/commons/events/TemplateConfig.d.ts +2 -3
  43. package/dist/commons/events/TranslationConfig.d.ts +2 -2
  44. package/dist/commons/events/WorkqueueColumnConfig.d.ts +74 -37
  45. package/dist/commons/events/WorkqueueConfig.d.ts +2208 -7553
  46. package/dist/commons/events/deduplication.d.ts +3 -3
  47. package/dist/commons/events/defineConfig.d.ts +2 -247
  48. package/dist/commons/events/eventConfigValidation.d.ts +8 -0
  49. package/dist/commons/events/index.d.ts +3 -0
  50. package/dist/commons/events/locations.d.ts +57 -20
  51. package/dist/commons/events/scopes.d.ts +36 -35
  52. package/dist/commons/events/state/availableActions.d.ts +7 -2
  53. package/dist/commons/events/state/flags.d.ts +21 -3
  54. package/dist/commons/events/state/index.d.ts +30 -27
  55. package/dist/commons/events/state/utils.d.ts +190 -172
  56. package/dist/commons/events/test.utils.d.ts +52 -11
  57. package/dist/commons/events/transactions.d.ts +1 -1
  58. package/dist/commons/events/utils.d.ts +373 -273
  59. package/dist/commons/notification/UserNotifications.d.ts +61 -637
  60. package/dist/conditionals/index.d.ts.map +1 -1
  61. package/dist/conditionals/index.js +302 -14
  62. package/dist/events/deduplication.d.ts +3 -3
  63. package/dist/events/index.js +2860 -2115
  64. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts +3 -0
  65. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +1 -0
  66. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +405 -0
  67. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +3 -0
  68. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -0
  69. package/dist/migrations/v2.0/checkout-upstream-files.js +143 -0
  70. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts +2 -0
  71. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +1 -0
  72. package/dist/migrations/v2.0/convert-config-files-to-ts.js +829 -0
  73. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts +3 -0
  74. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +1 -0
  75. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +159 -0
  76. package/dist/migrations/v2.0/create-events-index.d.ts +3 -0
  77. package/dist/migrations/v2.0/create-events-index.d.ts.map +1 -0
  78. package/dist/migrations/v2.0/create-events-index.js +326 -0
  79. package/dist/migrations/v2.0/index.d.ts +7 -0
  80. package/dist/migrations/v2.0/index.d.ts.map +1 -0
  81. package/dist/migrations/v2.0/index.js +3572 -0
  82. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts +3 -0
  83. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +1 -0
  84. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +344 -0
  85. package/dist/migrations/v2.0/migrate-scopes.d.ts +3 -0
  86. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -0
  87. package/dist/migrations/v2.0/migrate-scopes.js +282 -0
  88. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts +3 -0
  89. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +1 -0
  90. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +268 -0
  91. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts +3 -0
  92. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -0
  93. package/dist/migrations/v2.0/migrate-workqueue-configs.js +237 -0
  94. package/dist/migrations/v2.0/remove-delete-actions.d.ts +3 -0
  95. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +1 -0
  96. package/dist/migrations/v2.0/remove-delete-actions.js +157 -0
  97. package/dist/migrations/v2.0/remove-demo-scope.d.ts +3 -0
  98. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +1 -0
  99. package/dist/migrations/v2.0/remove-demo-scope.js +75 -0
  100. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts +3 -0
  101. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +1 -0
  102. package/dist/migrations/v2.0/remove-deprecated-imports.js +97 -0
  103. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts +3 -0
  104. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +1 -0
  105. package/dist/migrations/v2.0/remove-hearth-migrations.js +78 -0
  106. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts +3 -0
  107. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +1 -0
  108. package/dist/migrations/v2.0/remove-pending-certification-flag.js +110 -0
  109. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts +3 -0
  110. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +1 -0
  111. package/dist/migrations/v2.0/remove-review-from-register-action.js +164 -0
  112. package/dist/migrations/v2.0/rename-api-paths.d.ts +3 -0
  113. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +1 -0
  114. package/dist/migrations/v2.0/rename-api-paths.js +188 -0
  115. package/dist/migrations/v2.0/rename-location-parent-id.d.ts +3 -0
  116. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +1 -0
  117. package/dist/migrations/v2.0/rename-location-parent-id.js +181 -0
  118. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts +3 -0
  119. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +1 -0
  120. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +196 -0
  121. package/dist/notification/index.d.ts.map +1 -1
  122. package/dist/notification/index.js +2076 -1767
  123. package/dist/scopes/index.d.ts +640 -353
  124. package/dist/scopes/index.d.ts.map +1 -1
  125. package/dist/scopes/index.js +340 -300
  126. package/opencrvs-toolkit-2.0.0-rc.e0918cb.tgz +0 -0
  127. package/package.json +18 -8
  128. package/tsconfig.json +12 -2
  129. package/tsconfig.tsbuildinfo +1 -1
  130. package/dist/commons/events/CreatedAtLocation.d.ts +0 -2
@@ -0,0 +1,829 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ var desc = Object.getOwnPropertyDescriptor(m, k);
15
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
16
+ desc = { enumerable: true, get: function() { return m[k]; } };
17
+ }
18
+ Object.defineProperty(o, k2, desc);
19
+ }) : (function(o, m, k, k2) {
20
+ if (k2 === undefined) k2 = k;
21
+ o[k2] = m[k];
22
+ }));
23
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
24
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
25
+ }) : function(o, v) {
26
+ o["default"] = v;
27
+ });
28
+ var __importStar = (this && this.__importStar) || function (mod) {
29
+ if (mod && mod.__esModule) return mod;
30
+ var result = {};
31
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
32
+ __setModuleDefault(result, mod);
33
+ return result;
34
+ };
35
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
36
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
37
+ return new (P || (P = Promise))(function (resolve, reject) {
38
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
39
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
40
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
41
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
42
+ });
43
+ };
44
+ var __importDefault = (this && this.__importDefault) || function (mod) {
45
+ return (mod && mod.__esModule) ? mod : { "default": mod };
46
+ };
47
+ Object.defineProperty(exports, "__esModule", { value: true });
48
+ exports.main = main;
49
+ /**
50
+ * Codemod: Convert JS client/login config files to TypeScript and update Hapi route handlers.
51
+ *
52
+ * Usage:
53
+ * ts-node -r tsconfig-paths/register src/migrations/v2.0/convert-config-files-to-ts.ts
54
+ *
55
+ * Phase 1 — JS → TS conversion (for each of the four config files in src/):
56
+ * - client-config.js → client-config.ts (exports clientConfig)
57
+ * - client-config.prod.js → client-config.prod.ts (exports clientConfigProd)
58
+ * - login-config.js → login-config.ts (exports loginConfig)
59
+ * - login-config.prod.js → login-config.prod.ts (exports loginConfigProd)
60
+ *
61
+ * For each file:
62
+ * - Extracts the `window.config = { ... }` object (handles both direct and IIFE patterns)
63
+ * - Removes keys not present in the ClientConfig / LoginConfig schema
64
+ * - Converts LANGUAGES from a comma-separated string to an array of strings
65
+ * - Adds placeholder for REGISTER_BACKGROUND / LOGIN_BACKGROUND if absent
66
+ * - Wraps the config in defineClientConfig() / defineLoginConfig()
67
+ * - Deletes the original .js file
68
+ *
69
+ * For login config files specifically:
70
+ * - Imports applicationConfig from src/api/application/application-config
71
+ * - Sources USER_NOTIFICATION_DELIVERY_METHOD, INFORMANT_NOTIFICATION_DELIVERY_METHOD,
72
+ * and PHONE_NUMBER_PATTERN from applicationConfig rather than hardcoding them
73
+ *
74
+ * Phase 2 — Route handler replacement:
75
+ * - Finds every Hapi route object whose `path` is '/client-config.js' or '/login-config.js'
76
+ * - Replaces the handler (or options.handler) with:
77
+ * const config = process.env.NODE_ENV === 'production' ? <prod> : <base>
78
+ * return h.response(`window.config = ${JSON.stringify(config)}`).type('application/javascript')
79
+ * - Adds the required config imports to the route file
80
+ *
81
+ * Phase 3 — Wrap applicationConfig with defineApplicationConfig:
82
+ * - Finds src/api/application/application-config.ts
83
+ * - If the exported applicationConfig is a plain object literal, wraps it with
84
+ * defineApplicationConfig() from '@opencrvs/toolkit/application-config'
85
+ * - Adds the defineApplicationConfig import if not already present
86
+ */
87
+ const fs = __importStar(require("fs"));
88
+ const ts_morph_1 = require("ts-morph");
89
+ const path_1 = __importDefault(require("path"));
90
+ const _1 = require(".");
91
+ // ─── Schema-valid keys per config type ───────────────────────────────────────
92
+ const CLIENT_VALID_KEYS = new Set([
93
+ 'COUNTRY',
94
+ 'LANGUAGES',
95
+ 'SENTRY',
96
+ 'REGISTER_BACKGROUND',
97
+ 'DASHBOARDS',
98
+ 'FEATURES'
99
+ ]);
100
+ const LOGIN_VALID_KEYS = new Set([
101
+ 'COUNTRY',
102
+ 'LANGUAGES',
103
+ 'USER_NOTIFICATION_DELIVERY_METHOD',
104
+ 'INFORMANT_NOTIFICATION_DELIVERY_METHOD',
105
+ 'PHONE_NUMBER_PATTERN',
106
+ 'LOGIN_BACKGROUND',
107
+ 'SENTRY'
108
+ ]);
109
+ // Keys defined in ApplicationConfig from packages/commons/src/application-config.ts
110
+ const APPLICATION_CONFIG_VALID_KEYS = new Set([
111
+ 'APPLICATION_NAME',
112
+ 'COUNTRY_LOGO',
113
+ 'SYSTEM_IANA_TIMEZONE',
114
+ 'CURRENCY',
115
+ 'ADMIN_STRUCTURE',
116
+ 'PHONE_NUMBER_PATTERN',
117
+ 'USER_NOTIFICATION_DELIVERY_METHOD',
118
+ 'INFORMANT_NOTIFICATION_DELIVERY_METHOD',
119
+ 'SEARCH_DEFAULT_CRITERIA'
120
+ ]);
121
+ const CONFIG_GROUPS = [
122
+ {
123
+ baseName: 'client-config',
124
+ prodName: 'client-config.prod',
125
+ defineFn: 'defineClientConfig',
126
+ importFrom: '@opencrvs/toolkit/application-config',
127
+ validKeys: CLIENT_VALID_KEYS,
128
+ requiredPlaceholders: {
129
+ // BackgroundConfig requires backgroundColor or backgroundImage
130
+ REGISTER_BACKGROUND: "{ backgroundColor: '#F4F4F7' }"
131
+ },
132
+ exportNames: {
133
+ 'client-config': 'clientConfig',
134
+ 'client-config.prod': 'clientConfigProd'
135
+ },
136
+ routePath: '/client-config.js'
137
+ },
138
+ {
139
+ baseName: 'login-config',
140
+ prodName: 'login-config.prod',
141
+ defineFn: 'defineLoginConfig',
142
+ importFrom: '@opencrvs/toolkit/application-config',
143
+ validKeys: LOGIN_VALID_KEYS,
144
+ requiredPlaceholders: {},
145
+ // These keys are always sourced from applicationConfig rather than
146
+ // copied from the old JS file or filled with a placeholder value.
147
+ // LOGIN_BACKGROUND lives in applicationConfig and is not part of the
148
+ // ApplicationConfig schema, so Phase 3 will inline its value and remove
149
+ // it from applicationConfig automatically.
150
+ applicationConfigKeys: [
151
+ 'LOGIN_BACKGROUND',
152
+ 'USER_NOTIFICATION_DELIVERY_METHOD',
153
+ 'INFORMANT_NOTIFICATION_DELIVERY_METHOD',
154
+ 'PHONE_NUMBER_PATTERN'
155
+ ],
156
+ applicationConfigImportPath: './api/application/application-config',
157
+ exportNames: {
158
+ 'login-config': 'loginConfig',
159
+ 'login-config.prod': 'loginConfigProd'
160
+ },
161
+ routePath: '/login-config.js'
162
+ }
163
+ ];
164
+ // ─── HTTP verb set (for route detection) ─────────────────────────────────────
165
+ const HTTP_VERBS = new Set([
166
+ 'GET',
167
+ 'POST',
168
+ 'PUT',
169
+ 'PATCH',
170
+ 'DELETE',
171
+ 'OPTIONS',
172
+ 'HEAD',
173
+ '*'
174
+ ]);
175
+ // ─── Phase 1 helpers ──────────────────────────────────────────────────────────
176
+ /**
177
+ * Parses a JS config file and returns the ObjectLiteralExpression that is the
178
+ * right-hand side of the `window.config = { ... }` assignment.
179
+ * Handles both direct assignment and IIFE-wrapped assignment.
180
+ */
181
+ function extractWindowConfig(jsFilePath) {
182
+ const jsProject = new ts_morph_1.Project({
183
+ compilerOptions: { allowJs: true, checkJs: false }
184
+ // addFilesFromTsConfig: false
185
+ });
186
+ let sourceFile;
187
+ try {
188
+ sourceFile = jsProject.addSourceFileAtPath(jsFilePath);
189
+ }
190
+ catch (_a) {
191
+ console.warn(` Could not parse ${jsFilePath}`);
192
+ return null;
193
+ }
194
+ for (const binary of sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.BinaryExpression)) {
195
+ if (binary.getOperatorToken().getKind() !== ts_morph_1.SyntaxKind.EqualsToken)
196
+ continue;
197
+ const left = binary.getLeft();
198
+ if (!ts_morph_1.Node.isPropertyAccessExpression(left))
199
+ continue;
200
+ if (left.getExpression().getText() !== 'window')
201
+ continue;
202
+ if (left.getName() !== 'config')
203
+ continue;
204
+ const right = binary.getRight();
205
+ if (ts_morph_1.Node.isObjectLiteralExpression(right))
206
+ return right;
207
+ }
208
+ return null;
209
+ }
210
+ /**
211
+ * Converts a LANGUAGES string initializer like `'en,fr'` into an array literal
212
+ * like `['en', 'fr']`. If the initializer is already an array, returns its
213
+ * text unchanged.
214
+ */
215
+ function convertLanguages(init) {
216
+ if (ts_morph_1.Node.isStringLiteral(init)) {
217
+ const langs = init
218
+ .getLiteralValue()
219
+ .split(',')
220
+ .map((l) => `'${l.trim()}'`)
221
+ .join(', ');
222
+ return `[${langs}]`;
223
+ }
224
+ // Already an array or something else — keep as-is
225
+ return init.getText();
226
+ }
227
+ /**
228
+ * Extracts the plain URL string from a string literal or a no-substitution
229
+ * template literal (i.e. a backtick string with no ${…} expressions).
230
+ * Returns null for anything more complex.
231
+ */
232
+ function extractStaticUrlString(init) {
233
+ if (ts_morph_1.Node.isStringLiteral(init)) {
234
+ return init.getLiteralValue();
235
+ }
236
+ if (init.getKind() === ts_morph_1.SyntaxKind.NoSubstitutionTemplateLiteral) {
237
+ // getText() returns the text including surrounding backticks — strip them
238
+ const raw = init.getText();
239
+ return raw.slice(1, -1);
240
+ }
241
+ return null;
242
+ }
243
+ /**
244
+ * For prod files, rewrites a DASHBOARDS[].url initializer so that the origin
245
+ * (protocol + host + optional port) is replaced with `${scheme}//metabase.${hostname}`
246
+ * and the path/query/hash is preserved verbatim.
247
+ *
248
+ * Returns the original text unchanged for dev files or when the URL cannot be
249
+ * parsed.
250
+ */
251
+ function transformDashboardUrl(init, isProd) {
252
+ if (!isProd)
253
+ return init.getText();
254
+ const urlString = extractStaticUrlString(init);
255
+ if (!urlString)
256
+ return init.getText();
257
+ try {
258
+ const parsed = new URL(urlString);
259
+ const rest = parsed.pathname + parsed.search + parsed.hash;
260
+ // Escape the template literal so the OUTPUT file contains real ${} expressions
261
+ return `\`\${scheme}//metabase.\${hostname}${rest}\``;
262
+ }
263
+ catch (_a) {
264
+ return init.getText();
265
+ }
266
+ }
267
+ /**
268
+ * For prod files, recursively rewrites every `url` property inside the
269
+ * DASHBOARDS array using transformDashboardUrl.
270
+ * For dev files, returns the initializer text unchanged.
271
+ */
272
+ function transformDashboardsValue(init, isProd) {
273
+ if (!isProd || !ts_morph_1.Node.isArrayLiteralExpression(init)) {
274
+ return init.getText();
275
+ }
276
+ const elementParts = [];
277
+ for (const el of init.getElements()) {
278
+ if (!ts_morph_1.Node.isObjectLiteralExpression(el)) {
279
+ elementParts.push(el.getText());
280
+ continue;
281
+ }
282
+ const propParts = [];
283
+ for (const prop of el.getProperties()) {
284
+ if (!ts_morph_1.Node.isPropertyAssignment(prop)) {
285
+ propParts.push(prop.getText());
286
+ continue;
287
+ }
288
+ const propName = prop.getName();
289
+ const propInit = prop.getInitializer();
290
+ if (!propInit) {
291
+ propParts.push(prop.getText());
292
+ continue;
293
+ }
294
+ if (propName === 'url') {
295
+ propParts.push(`url: ${transformDashboardUrl(propInit, isProd)}`);
296
+ }
297
+ else {
298
+ propParts.push(`${propName}: ${propInit.getText()}`);
299
+ }
300
+ }
301
+ elementParts.push(` {\n${propParts.map((p) => ` ${p}`).join(',\n')}\n }`);
302
+ }
303
+ return `[\n${elementParts.join(',\n')}\n]`;
304
+ }
305
+ /**
306
+ * Generates the full TypeScript source for a converted config file.
307
+ *
308
+ * Prod files (isProd = true):
309
+ * - Import `env` from './environment'
310
+ * - Define `scheme = 'https'`, `hostname = env.DOMAIN`, `sentry = env.SENTRY_DSN`
311
+ * - Use `sentry` for the SENTRY property
312
+ * - Rewrite DASHBOARDS[].url origins to use scheme/hostname template expressions
313
+ *
314
+ * Dev files (isProd = false):
315
+ * - No env import
316
+ * - Define `scheme = 'http'`, `hostname = 'localhost'`
317
+ * - Keep SENTRY and DASHBOARDS URLs as-is from the original JS file
318
+ */
319
+ function generateTsContent(configObj, exportName, group, isProd) {
320
+ var _a;
321
+ // ── Config properties ────────────────────────────────────────────────────────
322
+ const propertyLines = [];
323
+ const seenKeys = new Set();
324
+ const appConfigKeySet = new Set((_a = group.applicationConfigKeys) !== null && _a !== void 0 ? _a : []);
325
+ for (const prop of configObj.getProperties()) {
326
+ if (!ts_morph_1.Node.isPropertyAssignment(prop))
327
+ continue;
328
+ const name = prop.getName();
329
+ if (!group.validKeys.has(name))
330
+ continue;
331
+ // Keys sourced from applicationConfig are always emitted separately below
332
+ if (appConfigKeySet.has(name))
333
+ continue;
334
+ seenKeys.add(name);
335
+ const init = prop.getInitializer();
336
+ if (!init)
337
+ continue;
338
+ if (name === 'LANGUAGES') {
339
+ propertyLines.push(` LANGUAGES: ${convertLanguages(init)}`);
340
+ }
341
+ else if (name === 'SENTRY' && isProd) {
342
+ propertyLines.push(` SENTRY: sentry`);
343
+ }
344
+ else if (name === 'DASHBOARDS') {
345
+ propertyLines.push(` DASHBOARDS: ${transformDashboardsValue(init, isProd)}`);
346
+ }
347
+ else {
348
+ propertyLines.push(` ${name}: ${init.getText()}`);
349
+ }
350
+ }
351
+ // Add placeholder lines for required keys that were absent in the JS file
352
+ for (const [key, placeholder] of Object.entries(group.requiredPlaceholders)) {
353
+ if (!seenKeys.has(key)) {
354
+ propertyLines.push(` // TODO: configure ${key} — replace this placeholder`, ` ${key}: ${placeholder}`);
355
+ }
356
+ }
357
+ // Always emit applicationConfig-sourced keys last, regardless of whether
358
+ // they appeared in the original JS file
359
+ for (const key of appConfigKeySet) {
360
+ propertyLines.push(` ${key}: applicationConfig.${key}`);
361
+ }
362
+ const body = propertyLines.join(',\n');
363
+ const headerLines = [];
364
+ headerLines.push(`import * as fs from 'fs'`);
365
+ headerLines.push(`import { join } from 'path'`);
366
+ if (isProd) {
367
+ headerLines.push(`import { env } from './environment'`);
368
+ }
369
+ headerLines.push(`import { ${group.defineFn} } from '${group.importFrom}'`);
370
+ if (group.applicationConfigImportPath) {
371
+ headerLines.push(`import { applicationConfig } from '${group.applicationConfigImportPath}'`);
372
+ }
373
+ headerLines.push('');
374
+ if (isProd) {
375
+ headerLines.push(`const scheme = 'https'`);
376
+ headerLines.push(`const hostname = env.DOMAIN`);
377
+ headerLines.push(`const sentry = env.SENTRY_DSN`);
378
+ }
379
+ else {
380
+ headerLines.push(`const scheme = 'http'`);
381
+ headerLines.push(`const hostname = 'localhost'`);
382
+ }
383
+ return [
384
+ ...headerLines,
385
+ '',
386
+ `export const ${exportName} = ${group.defineFn}({`,
387
+ body,
388
+ '})',
389
+ ''
390
+ ].join('\n');
391
+ }
392
+ /**
393
+ * Converts a single JS config file to TypeScript.
394
+ * Returns true if a file was written.
395
+ */
396
+ function convertFile(name, group, srcDir) {
397
+ const jsFilePath = path_1.default.join(srcDir, `${name}.js`);
398
+ const tsFilePath = path_1.default.join(srcDir, `${name}.ts`);
399
+ if (!fs.existsSync(jsFilePath)) {
400
+ console.log(` Skipping ${name}.js — file not found`);
401
+ return false;
402
+ }
403
+ if (fs.existsSync(tsFilePath)) {
404
+ console.log(` Skipping ${name}.js — ${name}.ts already exists`);
405
+ return false;
406
+ }
407
+ const configObj = extractWindowConfig(jsFilePath);
408
+ if (!configObj) {
409
+ console.warn(` [${name}.js] Could not locate window.config assignment — skipping`);
410
+ return false;
411
+ }
412
+ const isProd = name.endsWith('.prod');
413
+ const exportName = group.exportNames[name];
414
+ const content = generateTsContent(configObj, exportName, group, isProd);
415
+ fs.writeFileSync(tsFilePath, content, 'utf8');
416
+ fs.unlinkSync(jsFilePath);
417
+ console.log(` Converted ${name}.js → ${name}.ts (export: ${exportName})`);
418
+ return true;
419
+ }
420
+ // ─── Phase 2 helpers ──────────────────────────────────────────────────────────
421
+ /**
422
+ * Returns true when an ObjectLiteralExpression is a Hapi route config, i.e. it
423
+ * has both a `method` property (a recognised HTTP verb or array of verbs) and a
424
+ * `path` property that is a string literal.
425
+ */
426
+ function isRouteConfig(obj) {
427
+ const methodProp = obj.getProperty('method');
428
+ if (!methodProp || !ts_morph_1.Node.isPropertyAssignment(methodProp))
429
+ return false;
430
+ const methodInit = methodProp.getInitializer();
431
+ if (!methodInit)
432
+ return false;
433
+ if (ts_morph_1.Node.isStringLiteral(methodInit)) {
434
+ if (!HTTP_VERBS.has(methodInit.getLiteralValue().toUpperCase()))
435
+ return false;
436
+ }
437
+ else if (ts_morph_1.Node.isArrayLiteralExpression(methodInit)) {
438
+ const allVerbs = methodInit
439
+ .getElements()
440
+ .every((el) => ts_morph_1.Node.isStringLiteral(el) &&
441
+ HTTP_VERBS.has(el.getLiteralValue().toUpperCase()));
442
+ if (!allVerbs)
443
+ return false;
444
+ }
445
+ else {
446
+ return false;
447
+ }
448
+ const pathProp = obj.getProperty('path');
449
+ if (!pathProp || !ts_morph_1.Node.isPropertyAssignment(pathProp))
450
+ return false;
451
+ const pathInit = pathProp.getInitializer();
452
+ return !!pathInit && ts_morph_1.Node.isStringLiteral(pathInit);
453
+ }
454
+ /**
455
+ * Returns the string value of a route config's `path` property, or null if not
456
+ * available.
457
+ */
458
+ function getRoutePath(obj) {
459
+ const pathProp = obj.getProperty('path');
460
+ if (!pathProp || !ts_morph_1.Node.isPropertyAssignment(pathProp))
461
+ return null;
462
+ const pathInit = pathProp.getInitializer();
463
+ if (!pathInit || !ts_morph_1.Node.isStringLiteral(pathInit))
464
+ return null;
465
+ return pathInit.getLiteralValue();
466
+ }
467
+ /**
468
+ * Finds the PropertyAssignment for the handler function inside a route config.
469
+ * Looks at both `handler` (top-level) and `options.handler` (nested).
470
+ */
471
+ function findHandlerProperty(routeObj) {
472
+ // Top-level handler
473
+ const directHandler = routeObj.getProperty('handler');
474
+ if (directHandler && ts_morph_1.Node.isPropertyAssignment(directHandler)) {
475
+ return directHandler;
476
+ }
477
+ // options.handler
478
+ const optionsProp = routeObj.getProperty('options');
479
+ if (optionsProp && ts_morph_1.Node.isPropertyAssignment(optionsProp)) {
480
+ const optionsInit = optionsProp.getInitializer();
481
+ if (optionsInit && ts_morph_1.Node.isObjectLiteralExpression(optionsInit)) {
482
+ const nestedHandler = optionsInit.getProperty('handler');
483
+ if (nestedHandler && ts_morph_1.Node.isPropertyAssignment(nestedHandler)) {
484
+ return nestedHandler;
485
+ }
486
+ }
487
+ }
488
+ return null;
489
+ }
490
+ /**
491
+ * Ensures the source file has named imports for both the base and prod config
492
+ * exports, adding the import declarations if they are not already present.
493
+ */
494
+ function ensureConfigImports(sourceFile, group, srcDir) {
495
+ const routeFileDir = path_1.default.dirname(sourceFile.getFilePath());
496
+ for (const name of [group.baseName, group.prodName]) {
497
+ const exportName = group.exportNames[name];
498
+ const absoluteConfigPath = path_1.default.join(srcDir, name);
499
+ const rel = path_1.default
500
+ .relative(routeFileDir, absoluteConfigPath)
501
+ .replace(/\\/g, '/');
502
+ const moduleSpecifier = rel.startsWith('.') ? rel : `./${rel}`;
503
+ const alreadyImported = sourceFile
504
+ .getImportDeclarations()
505
+ .some((d) => d.getModuleSpecifierValue() === moduleSpecifier ||
506
+ d.getNamedImports().some((ni) => ni.getName() === exportName));
507
+ if (!alreadyImported) {
508
+ sourceFile.addImportDeclaration({
509
+ moduleSpecifier,
510
+ namedImports: [exportName]
511
+ });
512
+ }
513
+ }
514
+ }
515
+ /**
516
+ * Processes all TypeScript source files for route handler replacements.
517
+ * Returns the total number of handlers replaced.
518
+ */
519
+ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
520
+ const baseExport = group.exportNames[group.baseName];
521
+ const prodExport = group.exportNames[group.prodName];
522
+ // The new handler body — note the escaped template literal so that the
523
+ // output file contains a real template literal, not an interpolation here.
524
+ const newHandlerText = `async (request, h) => {
525
+ const config =
526
+ process.env.NODE_ENV === 'production' ? ${prodExport} : ${baseExport}
527
+ return h
528
+ .response(\`window.config = \${JSON.stringify(config)}\`)
529
+ .type('application/javascript')
530
+ }`;
531
+ let replacedCount = 0;
532
+ for (const sourceFile of sourceFiles) {
533
+ const filePath = sourceFile.getFilePath();
534
+ const candidates = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.ObjectLiteralExpression);
535
+ for (const obj of candidates) {
536
+ if (!isRouteConfig(obj))
537
+ continue;
538
+ if (getRoutePath(obj) !== group.routePath)
539
+ continue;
540
+ const handlerProp = findHandlerProperty(obj);
541
+ if (!handlerProp) {
542
+ console.warn(` [${relCwd(filePath)}] Found route '${group.routePath}' but could not locate handler property — skipping`);
543
+ continue;
544
+ }
545
+ handlerProp.setInitializer(newHandlerText);
546
+ ensureConfigImports(sourceFile, group, srcDir);
547
+ replacedCount++;
548
+ console.log(` [${relCwd(filePath)}] Replaced handler for route '${group.routePath}'`);
549
+ }
550
+ }
551
+ return replacedCount;
552
+ }
553
+ // ─── Phase 3 helper ──────────────────────────────────────────────────────────
554
+ /**
555
+ * Resolves a chain of property accesses on an ObjectLiteralExpression.
556
+ * E.g. given path ['BIRTH', 'LATE_REGISTRATION_TARGET'] and an object
557
+ * `{ BIRTH: { LATE_REGISTRATION_TARGET: 45 } }`, returns the text '45'.
558
+ * Returns null if any segment of the path cannot be resolved.
559
+ */
560
+ function resolveConfigChain(configObj, path) {
561
+ let current = configObj;
562
+ for (const key of path) {
563
+ if (!ts_morph_1.Node.isObjectLiteralExpression(current))
564
+ return null;
565
+ const prop = current.getProperty(key);
566
+ if (!prop || !ts_morph_1.Node.isPropertyAssignment(prop))
567
+ return null;
568
+ const initNode = prop.getInitializer();
569
+ if (!initNode)
570
+ return null;
571
+ current = initNode;
572
+ }
573
+ return current.getText();
574
+ }
575
+ /**
576
+ * When inlining a value from `application-config.ts` into a file in a
577
+ * different directory, `__dirname`-based paths (e.g. for reading image
578
+ * assets) must be adjusted so they continue to resolve to the original
579
+ * location — the referenced files themselves are NOT moved.
580
+ *
581
+ * Rewrites `join(__dirname, ...)` / `path.join(__dirname, ...)` /
582
+ * `resolve(__dirname, ...)` / `path.resolve(__dirname, ...)` by inserting
583
+ * the relative path from the target directory back to the source directory
584
+ * as an extra leading argument.
585
+ *
586
+ * Example: inlining from `src/api/application/` into `src/login-config.ts`
587
+ * join(__dirname, 'login-bg.jpg')
588
+ * → join(__dirname, 'api/application', 'login-bg.jpg')
589
+ */
590
+ function rewriteDirnameRefs(text, relDir) {
591
+ if (!relDir || relDir === '.')
592
+ return text;
593
+ const relForward = relDir.replace(/\\/g, '/');
594
+ return text.replace(/\b((?:path\.)?(?:join|resolve))\s*\(\s*__dirname\s*,/g, `$1(__dirname, '${relForward}',`);
595
+ }
596
+ /**
597
+ * Ensures the source file has a namespace `fs` import (`import * as fs from 'fs'`).
598
+ * No-op if a namespace or default `fs` import is already present.
599
+ */
600
+ function ensureFsImport(sf) {
601
+ const hasFs = sf
602
+ .getImportDeclarations()
603
+ .some((d) => d.getModuleSpecifierValue() === 'fs' &&
604
+ (d.getNamespaceImport() || d.getDefaultImport()));
605
+ if (hasFs)
606
+ return;
607
+ sf.addImportDeclaration({
608
+ moduleSpecifier: 'fs',
609
+ namespaceImport: 'fs'
610
+ });
611
+ }
612
+ /**
613
+ * Ensures the source file has a named `join` import from 'path'.
614
+ * Merges into an existing 'path' import if present, otherwise adds a new
615
+ * `import { join } from 'path'` declaration.
616
+ */
617
+ function ensureJoinImport(sf) {
618
+ const pathImports = sf
619
+ .getImportDeclarations()
620
+ .filter((d) => d.getModuleSpecifierValue() === 'path');
621
+ if (pathImports.some((d) => d.getNamedImports().some((ni) => ni.getName() === 'join'))) {
622
+ return;
623
+ }
624
+ if (pathImports.length > 0) {
625
+ pathImports[0].addNamedImport('join');
626
+ return;
627
+ }
628
+ sf.addImportDeclaration({
629
+ moduleSpecifier: 'path',
630
+ namedImports: ['join']
631
+ });
632
+ }
633
+ // ─── Entry point ─────────────────────────────────────────────────────────────
634
+ function main() {
635
+ return __awaiter(this, void 0, void 0, function* () {
636
+ var _a;
637
+ const srcDir = path_1.default.join((0, _1.getCwd)(), 'src');
638
+ const relCwd = (fp) => path_1.default.relative((0, _1.getCwd)(), fp);
639
+ // ── Phase 1: Convert JS config files to TypeScript ────────────────────────
640
+ console.log('Phase 1: Converting JS config files to TypeScript...\n');
641
+ let convertedCount = 0;
642
+ for (const group of CONFIG_GROUPS) {
643
+ for (const name of [group.baseName, group.prodName]) {
644
+ if (convertFile(name, group, srcDir)) {
645
+ convertedCount++;
646
+ }
647
+ }
648
+ }
649
+ if (convertedCount === 0) {
650
+ console.log(' No JS config files needed conversion.\n');
651
+ }
652
+ else {
653
+ console.log(`\n Converted ${convertedCount} file(s).\n`);
654
+ }
655
+ // ── Phase 3: Wrap applicationConfig with defineApplicationConfig ──────────
656
+ console.log('Phase 3: Wrapping applicationConfig with defineApplicationConfig...\n');
657
+ const appConfigRelPath = 'api/application/application-config.ts';
658
+ const appConfigAbsPath = path_1.default.join(srcDir, appConfigRelPath);
659
+ if (!fs.existsSync(appConfigAbsPath)) {
660
+ console.log(` Skipping Phase 3 — ${appConfigRelPath} not found in src/\n`);
661
+ }
662
+ else {
663
+ const appConfigProject = new ts_morph_1.Project({
664
+ tsConfigFilePath: path_1.default.resolve(srcDir, '../tsconfig.json'),
665
+ skipAddingFilesFromTsConfig: false
666
+ });
667
+ const appConfigFile = (_a = appConfigProject.getSourceFile(appConfigAbsPath)) !== null && _a !== void 0 ? _a : appConfigProject.addSourceFileAtPath(appConfigAbsPath);
668
+ let wrapped = false;
669
+ for (const varDecl of appConfigFile.getVariableDeclarations()) {
670
+ if (varDecl.getName() !== 'applicationConfig')
671
+ continue;
672
+ const init = varDecl.getInitializer();
673
+ if (!init || !ts_morph_1.Node.isObjectLiteralExpression(init))
674
+ continue;
675
+ // Remove properties not defined in the ApplicationConfig schema
676
+ const propsToRemove = init.getProperties().filter((prop) => {
677
+ if (!ts_morph_1.Node.isPropertyAssignment(prop))
678
+ return false;
679
+ const name = prop
680
+ .getNameNode()
681
+ .getText()
682
+ .replace(/^['"]|['"]$/g, '');
683
+ return !APPLICATION_CONFIG_VALID_KEYS.has(name);
684
+ });
685
+ if (propsToRemove.length > 0) {
686
+ // Before removing, inline every cross-file reference to each unknown key.
687
+ // Example: applicationConfig.BIRTH.LATE_REGISTRATION_TARGET → 45
688
+ const filesToSaveAfterInlining = new Set();
689
+ const appConfigDir = path_1.default.dirname(appConfigAbsPath);
690
+ for (const removedProp of propsToRemove) {
691
+ const key = removedProp.getName();
692
+ for (const sf of appConfigProject.getSourceFiles()) {
693
+ // Skip the config file itself, files outside src/, and node_modules
694
+ if (sf.getFilePath() === appConfigAbsPath)
695
+ continue;
696
+ if (!sf.getFilePath().includes('/src/'))
697
+ continue;
698
+ if (sf.getFilePath().includes('/node_modules/'))
699
+ continue;
700
+ // Relative path from the target file's directory back to the
701
+ // applicationConfig's directory. Used to adjust `__dirname`-based
702
+ // paths in the inlined value (e.g. image asset references) since
703
+ // those assets are not moved.
704
+ const targetDir = path_1.default.dirname(sf.getFilePath());
705
+ const relDirFromTarget = path_1.default.relative(targetDir, appConfigDir);
706
+ // Break-and-restart after each replacement because replaceWithText()
707
+ // invalidates existing node references in the ts-morph tree
708
+ let madeReplacement = true;
709
+ while (madeReplacement) {
710
+ madeReplacement = false;
711
+ for (const identNode of sf.getDescendantsOfKind(ts_morph_1.SyntaxKind.Identifier)) {
712
+ if (identNode.getText() !== 'applicationConfig')
713
+ continue;
714
+ // Walk up the property-access chain from this identifier
715
+ let node = identNode;
716
+ const accessPath = [];
717
+ while (true) {
718
+ const parent = node.getParent();
719
+ if (!ts_morph_1.Node.isPropertyAccessExpression(parent))
720
+ break;
721
+ if (parent.getExpression() !== node)
722
+ break;
723
+ accessPath.push(parent.getName());
724
+ node = parent;
725
+ }
726
+ if (accessPath.length === 0 || accessPath[0] !== key)
727
+ continue;
728
+ const resolvedValue = resolveConfigChain(init, accessPath);
729
+ if (resolvedValue === null) {
730
+ console.log(` Cannot resolve applicationConfig.${accessPath.join('.')} — skipping inline replacement`);
731
+ continue;
732
+ }
733
+ const adjustedValue = rewriteDirnameRefs(resolvedValue, relDirFromTarget);
734
+ node.replaceWithText(adjustedValue);
735
+ // If the inlined value references `fs` or `join`, ensure the
736
+ // target file has the corresponding imports — these are
737
+ // commonly used to read image assets from disk.
738
+ if (/\bfs\s*\./.test(adjustedValue)) {
739
+ ensureFsImport(sf);
740
+ }
741
+ if (/\bjoin\s*\(/.test(adjustedValue)) {
742
+ ensureJoinImport(sf);
743
+ }
744
+ console.log(` Inlined applicationConfig.${accessPath.join('.')} → ${adjustedValue} in ${path_1.default.relative((0, _1.getCwd)(), sf.getFilePath())}`);
745
+ filesToSaveAfterInlining.add(sf);
746
+ madeReplacement = true;
747
+ break; // restart — tree has changed
748
+ }
749
+ }
750
+ }
751
+ }
752
+ // Persist files that received inline replacements
753
+ for (const sf of Array.from(filesToSaveAfterInlining)) {
754
+ yield sf.save();
755
+ console.log(` Saved (inlined): ${path_1.default.relative((0, _1.getCwd)(), sf.getFilePath())}`);
756
+ }
757
+ // Remove in reverse order to avoid index shifting
758
+ for (const prop of [...propsToRemove].reverse()) {
759
+ const propName = prop.getName();
760
+ console.log(` Removing unknown key '${propName}' from applicationConfig (not in ApplicationConfig schema)`);
761
+ prop.remove();
762
+ }
763
+ }
764
+ // Wrap the plain object literal with defineApplicationConfig(...)
765
+ varDecl.setInitializer(`defineApplicationConfig(${init.getText()})`);
766
+ // Upsert the defineApplicationConfig named import
767
+ const TOOLKIT_MODULE = '@opencrvs/toolkit/application-config';
768
+ const existing = appConfigFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === TOOLKIT_MODULE);
769
+ if (existing) {
770
+ const names = new Set(existing.getNamedImports().map((ni) => ni.getName()));
771
+ if (!names.has('defineApplicationConfig')) {
772
+ existing.addNamedImport('defineApplicationConfig');
773
+ }
774
+ }
775
+ else {
776
+ appConfigFile.addImportDeclaration({
777
+ moduleSpecifier: TOOLKIT_MODULE,
778
+ namedImports: ['defineApplicationConfig']
779
+ });
780
+ }
781
+ wrapped = true;
782
+ console.log(` Wrapped applicationConfig with defineApplicationConfig in ${appConfigRelPath}`);
783
+ break;
784
+ }
785
+ if (!wrapped) {
786
+ console.log(` Skipping Phase 3 — applicationConfig plain object not found (already wrapped?)\n`);
787
+ }
788
+ else {
789
+ yield appConfigFile.save();
790
+ console.log(` Saved: ${appConfigRelPath}\n`);
791
+ }
792
+ }
793
+ // ── Phase 2: Update Hapi route handlers ───────────────────────────────────
794
+ console.log('Phase 2: Updating Hapi route handlers...\n');
795
+ const project = new ts_morph_1.Project({
796
+ tsConfigFilePath: path_1.default.resolve(srcDir, '../tsconfig.json'),
797
+ skipAddingFilesFromTsConfig: false
798
+ });
799
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
800
+ const fp = sf.getFilePath();
801
+ return fp.includes('/src/') && !fp.includes('/node_modules/');
802
+ });
803
+ console.log(` Analysing ${sourceFiles.length} source file(s).\n`);
804
+ let totalReplaced = 0;
805
+ for (const group of CONFIG_GROUPS) {
806
+ totalReplaced += updateRouteHandlers(sourceFiles, group, srcDir, relCwd);
807
+ }
808
+ if (totalReplaced === 0) {
809
+ console.log(' No route handlers matched — nothing to update in Phase 2.\n');
810
+ }
811
+ // ── Save modified TS files ────────────────────────────────────────────────
812
+ const modified = sourceFiles.filter((sf) => sf.wasForgotten() === false);
813
+ const toSave = modified.filter((sf) => sf.getDescendantsOfKind(ts_morph_1.SyntaxKind.ObjectLiteralExpression).length > 0);
814
+ // Only save files that actually had route handler changes
815
+ let savedCount = 0;
816
+ for (const sf of project.getSourceFiles()) {
817
+ if (sf.isSaved())
818
+ continue;
819
+ yield sf.save();
820
+ console.log(` Saved: ${relCwd(sf.getFilePath())}`);
821
+ savedCount++;
822
+ }
823
+ if (savedCount === 0 && totalReplaced === 0) {
824
+ console.log('Nothing was changed.');
825
+ return;
826
+ }
827
+ console.log(`\nDone. Converted ${convertedCount} config file(s), replaced ${totalReplaced} route handler(s).`);
828
+ });
829
+ }