@opencrvs/toolkit 1.9.12-rc.b38f7ff → 1.9.12-rc.ba2ea5c

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 (118) 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 +135 -0
  6. package/dist/cli.d.ts +2 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +3161 -0
  9. package/dist/commons/api/router.d.ts +3386 -2262
  10. package/dist/commons/application-config/index.d.ts +82 -0
  11. package/dist/commons/conditionals/conditionals.d.ts +27 -3
  12. package/dist/commons/conditionals/validate.d.ts +13 -2
  13. package/dist/commons/events/ActionConfig.d.ts +415 -1555
  14. package/dist/commons/events/ActionDocument.d.ts +889 -1942
  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 +73 -108
  25. package/dist/commons/events/DynamicFieldValue.d.ts +12 -78
  26. package/dist/commons/events/EventConfig.d.ts +35 -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 -12519
  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 +35 -34
  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 +191 -173
  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 +374 -443
  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 +2850 -2107
  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/convert-config-files-to-ts.d.ts +2 -0
  68. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +1 -0
  69. package/dist/migrations/v2.0/convert-config-files-to-ts.js +753 -0
  70. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts +3 -0
  71. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +1 -0
  72. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +159 -0
  73. package/dist/migrations/v2.0/index.d.ts +7 -0
  74. package/dist/migrations/v2.0/index.d.ts.map +1 -0
  75. package/dist/migrations/v2.0/index.js +3100 -0
  76. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts +3 -0
  77. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +1 -0
  78. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +344 -0
  79. package/dist/migrations/v2.0/migrate-scopes.d.ts +3 -0
  80. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -0
  81. package/dist/migrations/v2.0/migrate-scopes.js +282 -0
  82. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts +3 -0
  83. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +1 -0
  84. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +268 -0
  85. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts +3 -0
  86. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -0
  87. package/dist/migrations/v2.0/migrate-workqueue-configs.js +237 -0
  88. package/dist/migrations/v2.0/remove-delete-actions.d.ts +3 -0
  89. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +1 -0
  90. package/dist/migrations/v2.0/remove-delete-actions.js +157 -0
  91. package/dist/migrations/v2.0/remove-demo-scope.d.ts +3 -0
  92. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +1 -0
  93. package/dist/migrations/v2.0/remove-demo-scope.js +75 -0
  94. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts +3 -0
  95. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +1 -0
  96. package/dist/migrations/v2.0/remove-deprecated-imports.js +97 -0
  97. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts +3 -0
  98. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +1 -0
  99. package/dist/migrations/v2.0/remove-pending-certification-flag.js +110 -0
  100. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts +3 -0
  101. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +1 -0
  102. package/dist/migrations/v2.0/remove-review-from-register-action.js +164 -0
  103. package/dist/migrations/v2.0/rename-api-paths.d.ts +3 -0
  104. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +1 -0
  105. package/dist/migrations/v2.0/rename-api-paths.js +188 -0
  106. package/dist/migrations/v2.0/rename-location-parent-id.d.ts +3 -0
  107. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +1 -0
  108. package/dist/migrations/v2.0/rename-location-parent-id.js +181 -0
  109. package/dist/notification/index.d.ts.map +1 -1
  110. package/dist/notification/index.js +2085 -1770
  111. package/dist/scopes/index.d.ts +640 -353
  112. package/dist/scopes/index.d.ts.map +1 -1
  113. package/dist/scopes/index.js +340 -300
  114. package/opencrvs-toolkit-1.9.12-rc.ba2ea5c.tgz +0 -0
  115. package/package.json +18 -8
  116. package/tsconfig.json +12 -2
  117. package/tsconfig.tsbuildinfo +1 -1
  118. package/dist/commons/events/CreatedAtLocation.d.ts +0 -2
@@ -0,0 +1,753 @@
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
+ // ── File header ─────────────────────────────────────────────────────────────
322
+ const headerLines = [];
323
+ if (isProd) {
324
+ headerLines.push(`import { env } from './environment'`);
325
+ }
326
+ headerLines.push(`import { ${group.defineFn} } from '${group.importFrom}'`);
327
+ if (group.applicationConfigImportPath) {
328
+ headerLines.push(`import { applicationConfig } from '${group.applicationConfigImportPath}'`);
329
+ }
330
+ headerLines.push('');
331
+ if (isProd) {
332
+ headerLines.push(`const scheme = 'https'`);
333
+ headerLines.push(`const hostname = env.DOMAIN`);
334
+ headerLines.push(`const sentry = env.SENTRY_DSN`);
335
+ }
336
+ else {
337
+ headerLines.push(`const scheme = 'http'`);
338
+ headerLines.push(`const hostname = 'localhost'`);
339
+ }
340
+ // ── Config properties ────────────────────────────────────────────────────────
341
+ const propertyLines = [];
342
+ const seenKeys = new Set();
343
+ const appConfigKeySet = new Set((_a = group.applicationConfigKeys) !== null && _a !== void 0 ? _a : []);
344
+ for (const prop of configObj.getProperties()) {
345
+ if (!ts_morph_1.Node.isPropertyAssignment(prop))
346
+ continue;
347
+ const name = prop.getName();
348
+ if (!group.validKeys.has(name))
349
+ continue;
350
+ // Keys sourced from applicationConfig are always emitted separately below
351
+ if (appConfigKeySet.has(name))
352
+ continue;
353
+ seenKeys.add(name);
354
+ const init = prop.getInitializer();
355
+ if (!init)
356
+ continue;
357
+ if (name === 'LANGUAGES') {
358
+ propertyLines.push(` LANGUAGES: ${convertLanguages(init)}`);
359
+ }
360
+ else if (name === 'SENTRY' && isProd) {
361
+ propertyLines.push(` SENTRY: sentry`);
362
+ }
363
+ else if (name === 'DASHBOARDS') {
364
+ propertyLines.push(` DASHBOARDS: ${transformDashboardsValue(init, isProd)}`);
365
+ }
366
+ else {
367
+ propertyLines.push(` ${name}: ${init.getText()}`);
368
+ }
369
+ }
370
+ // Add placeholder lines for required keys that were absent in the JS file
371
+ for (const [key, placeholder] of Object.entries(group.requiredPlaceholders)) {
372
+ if (!seenKeys.has(key)) {
373
+ propertyLines.push(` // TODO: configure ${key} — replace this placeholder`, ` ${key}: ${placeholder}`);
374
+ }
375
+ }
376
+ // Always emit applicationConfig-sourced keys last, regardless of whether
377
+ // they appeared in the original JS file
378
+ for (const key of appConfigKeySet) {
379
+ propertyLines.push(` ${key}: applicationConfig.${key}`);
380
+ }
381
+ const body = propertyLines.join(',\n');
382
+ return [
383
+ ...headerLines,
384
+ '',
385
+ `export const ${exportName} = ${group.defineFn}({`,
386
+ body,
387
+ '})',
388
+ ''
389
+ ].join('\n');
390
+ }
391
+ /**
392
+ * Converts a single JS config file to TypeScript.
393
+ * Returns true if a file was written.
394
+ */
395
+ function convertFile(name, group, srcDir) {
396
+ const jsFilePath = path_1.default.join(srcDir, `${name}.js`);
397
+ const tsFilePath = path_1.default.join(srcDir, `${name}.ts`);
398
+ if (!fs.existsSync(jsFilePath)) {
399
+ console.log(` Skipping ${name}.js — file not found`);
400
+ return false;
401
+ }
402
+ if (fs.existsSync(tsFilePath)) {
403
+ console.log(` Skipping ${name}.js — ${name}.ts already exists`);
404
+ return false;
405
+ }
406
+ const configObj = extractWindowConfig(jsFilePath);
407
+ if (!configObj) {
408
+ console.warn(` [${name}.js] Could not locate window.config assignment — skipping`);
409
+ return false;
410
+ }
411
+ const isProd = name.endsWith('.prod');
412
+ const exportName = group.exportNames[name];
413
+ const content = generateTsContent(configObj, exportName, group, isProd);
414
+ fs.writeFileSync(tsFilePath, content, 'utf8');
415
+ fs.unlinkSync(jsFilePath);
416
+ console.log(` Converted ${name}.js → ${name}.ts (export: ${exportName})`);
417
+ return true;
418
+ }
419
+ // ─── Phase 2 helpers ──────────────────────────────────────────────────────────
420
+ /**
421
+ * Returns true when an ObjectLiteralExpression is a Hapi route config, i.e. it
422
+ * has both a `method` property (a recognised HTTP verb or array of verbs) and a
423
+ * `path` property that is a string literal.
424
+ */
425
+ function isRouteConfig(obj) {
426
+ const methodProp = obj.getProperty('method');
427
+ if (!methodProp || !ts_morph_1.Node.isPropertyAssignment(methodProp))
428
+ return false;
429
+ const methodInit = methodProp.getInitializer();
430
+ if (!methodInit)
431
+ return false;
432
+ if (ts_morph_1.Node.isStringLiteral(methodInit)) {
433
+ if (!HTTP_VERBS.has(methodInit.getLiteralValue().toUpperCase()))
434
+ return false;
435
+ }
436
+ else if (ts_morph_1.Node.isArrayLiteralExpression(methodInit)) {
437
+ const allVerbs = methodInit
438
+ .getElements()
439
+ .every((el) => ts_morph_1.Node.isStringLiteral(el) &&
440
+ HTTP_VERBS.has(el.getLiteralValue().toUpperCase()));
441
+ if (!allVerbs)
442
+ return false;
443
+ }
444
+ else {
445
+ return false;
446
+ }
447
+ const pathProp = obj.getProperty('path');
448
+ if (!pathProp || !ts_morph_1.Node.isPropertyAssignment(pathProp))
449
+ return false;
450
+ const pathInit = pathProp.getInitializer();
451
+ return !!pathInit && ts_morph_1.Node.isStringLiteral(pathInit);
452
+ }
453
+ /**
454
+ * Returns the string value of a route config's `path` property, or null if not
455
+ * available.
456
+ */
457
+ function getRoutePath(obj) {
458
+ const pathProp = obj.getProperty('path');
459
+ if (!pathProp || !ts_morph_1.Node.isPropertyAssignment(pathProp))
460
+ return null;
461
+ const pathInit = pathProp.getInitializer();
462
+ if (!pathInit || !ts_morph_1.Node.isStringLiteral(pathInit))
463
+ return null;
464
+ return pathInit.getLiteralValue();
465
+ }
466
+ /**
467
+ * Finds the PropertyAssignment for the handler function inside a route config.
468
+ * Looks at both `handler` (top-level) and `options.handler` (nested).
469
+ */
470
+ function findHandlerProperty(routeObj) {
471
+ // Top-level handler
472
+ const directHandler = routeObj.getProperty('handler');
473
+ if (directHandler && ts_morph_1.Node.isPropertyAssignment(directHandler)) {
474
+ return directHandler;
475
+ }
476
+ // options.handler
477
+ const optionsProp = routeObj.getProperty('options');
478
+ if (optionsProp && ts_morph_1.Node.isPropertyAssignment(optionsProp)) {
479
+ const optionsInit = optionsProp.getInitializer();
480
+ if (optionsInit && ts_morph_1.Node.isObjectLiteralExpression(optionsInit)) {
481
+ const nestedHandler = optionsInit.getProperty('handler');
482
+ if (nestedHandler && ts_morph_1.Node.isPropertyAssignment(nestedHandler)) {
483
+ return nestedHandler;
484
+ }
485
+ }
486
+ }
487
+ return null;
488
+ }
489
+ /**
490
+ * Ensures the source file has named imports for both the base and prod config
491
+ * exports, adding the import declarations if they are not already present.
492
+ */
493
+ function ensureConfigImports(sourceFile, group, srcDir) {
494
+ const routeFileDir = path_1.default.dirname(sourceFile.getFilePath());
495
+ for (const name of [group.baseName, group.prodName]) {
496
+ const exportName = group.exportNames[name];
497
+ const absoluteConfigPath = path_1.default.join(srcDir, name);
498
+ const rel = path_1.default
499
+ .relative(routeFileDir, absoluteConfigPath)
500
+ .replace(/\\/g, '/');
501
+ const moduleSpecifier = rel.startsWith('.') ? rel : `./${rel}`;
502
+ const alreadyImported = sourceFile
503
+ .getImportDeclarations()
504
+ .some((d) => d.getModuleSpecifierValue() === moduleSpecifier ||
505
+ d.getNamedImports().some((ni) => ni.getName() === exportName));
506
+ if (!alreadyImported) {
507
+ sourceFile.addImportDeclaration({
508
+ moduleSpecifier,
509
+ namedImports: [exportName]
510
+ });
511
+ }
512
+ }
513
+ }
514
+ /**
515
+ * Processes all TypeScript source files for route handler replacements.
516
+ * Returns the total number of handlers replaced.
517
+ */
518
+ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
519
+ const baseExport = group.exportNames[group.baseName];
520
+ const prodExport = group.exportNames[group.prodName];
521
+ // The new handler body — note the escaped template literal so that the
522
+ // output file contains a real template literal, not an interpolation here.
523
+ const newHandlerText = `async (request, h) => {
524
+ const config =
525
+ process.env.NODE_ENV === 'production' ? ${prodExport} : ${baseExport}
526
+ return h
527
+ .response(\`window.config = \${JSON.stringify(config)}\`)
528
+ .type('application/javascript')
529
+ }`;
530
+ let replacedCount = 0;
531
+ for (const sourceFile of sourceFiles) {
532
+ const filePath = sourceFile.getFilePath();
533
+ const candidates = sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.ObjectLiteralExpression);
534
+ for (const obj of candidates) {
535
+ if (!isRouteConfig(obj))
536
+ continue;
537
+ if (getRoutePath(obj) !== group.routePath)
538
+ continue;
539
+ const handlerProp = findHandlerProperty(obj);
540
+ if (!handlerProp) {
541
+ console.warn(` [${relCwd(filePath)}] Found route '${group.routePath}' but could not locate handler property — skipping`);
542
+ continue;
543
+ }
544
+ handlerProp.setInitializer(newHandlerText);
545
+ ensureConfigImports(sourceFile, group, srcDir);
546
+ replacedCount++;
547
+ console.log(` [${relCwd(filePath)}] Replaced handler for route '${group.routePath}'`);
548
+ }
549
+ }
550
+ return replacedCount;
551
+ }
552
+ // ─── Phase 3 helper ──────────────────────────────────────────────────────────
553
+ /**
554
+ * Resolves a chain of property accesses on an ObjectLiteralExpression.
555
+ * E.g. given path ['BIRTH', 'LATE_REGISTRATION_TARGET'] and an object
556
+ * `{ BIRTH: { LATE_REGISTRATION_TARGET: 45 } }`, returns the text '45'.
557
+ * Returns null if any segment of the path cannot be resolved.
558
+ */
559
+ function resolveConfigChain(configObj, path) {
560
+ let current = configObj;
561
+ for (const key of path) {
562
+ if (!ts_morph_1.Node.isObjectLiteralExpression(current))
563
+ return null;
564
+ const prop = current.getProperty(key);
565
+ if (!prop || !ts_morph_1.Node.isPropertyAssignment(prop))
566
+ return null;
567
+ const initNode = prop.getInitializer();
568
+ if (!initNode)
569
+ return null;
570
+ current = initNode;
571
+ }
572
+ return current.getText();
573
+ }
574
+ // ─── Entry point ─────────────────────────────────────────────────────────────
575
+ function main() {
576
+ return __awaiter(this, void 0, void 0, function* () {
577
+ var _a;
578
+ const srcDir = path_1.default.join((0, _1.getCwd)(), 'src');
579
+ const relCwd = (fp) => path_1.default.relative((0, _1.getCwd)(), fp);
580
+ // ── Phase 1: Convert JS config files to TypeScript ────────────────────────
581
+ console.log('Phase 1: Converting JS config files to TypeScript...\n');
582
+ let convertedCount = 0;
583
+ for (const group of CONFIG_GROUPS) {
584
+ for (const name of [group.baseName, group.prodName]) {
585
+ if (convertFile(name, group, srcDir)) {
586
+ convertedCount++;
587
+ }
588
+ }
589
+ }
590
+ if (convertedCount === 0) {
591
+ console.log(' No JS config files needed conversion.\n');
592
+ }
593
+ else {
594
+ console.log(`\n Converted ${convertedCount} file(s).\n`);
595
+ }
596
+ // ── Phase 3: Wrap applicationConfig with defineApplicationConfig ──────────
597
+ console.log('Phase 3: Wrapping applicationConfig with defineApplicationConfig...\n');
598
+ const appConfigRelPath = 'api/application/application-config.ts';
599
+ const appConfigAbsPath = path_1.default.join(srcDir, appConfigRelPath);
600
+ if (!fs.existsSync(appConfigAbsPath)) {
601
+ console.log(` Skipping Phase 3 — ${appConfigRelPath} not found in src/\n`);
602
+ }
603
+ else {
604
+ const appConfigProject = new ts_morph_1.Project({
605
+ tsConfigFilePath: path_1.default.resolve(srcDir, '../tsconfig.json'),
606
+ skipAddingFilesFromTsConfig: false
607
+ });
608
+ const appConfigFile = (_a = appConfigProject.getSourceFile(appConfigAbsPath)) !== null && _a !== void 0 ? _a : appConfigProject.addSourceFileAtPath(appConfigAbsPath);
609
+ let wrapped = false;
610
+ for (const varDecl of appConfigFile.getVariableDeclarations()) {
611
+ if (varDecl.getName() !== 'applicationConfig')
612
+ continue;
613
+ const init = varDecl.getInitializer();
614
+ if (!init || !ts_morph_1.Node.isObjectLiteralExpression(init))
615
+ continue;
616
+ // Remove properties not defined in the ApplicationConfig schema
617
+ const propsToRemove = init.getProperties().filter((prop) => {
618
+ if (!ts_morph_1.Node.isPropertyAssignment(prop))
619
+ return false;
620
+ const name = prop
621
+ .getNameNode()
622
+ .getText()
623
+ .replace(/^['"]|['"]$/g, '');
624
+ return !APPLICATION_CONFIG_VALID_KEYS.has(name);
625
+ });
626
+ if (propsToRemove.length > 0) {
627
+ // Before removing, inline every cross-file reference to each unknown key.
628
+ // Example: applicationConfig.BIRTH.LATE_REGISTRATION_TARGET → 45
629
+ const filesToSaveAfterInlining = new Set();
630
+ for (const removedProp of propsToRemove) {
631
+ const key = removedProp.getName();
632
+ for (const sf of appConfigProject.getSourceFiles()) {
633
+ // Skip the config file itself, files outside src/, and node_modules
634
+ if (sf.getFilePath() === appConfigAbsPath)
635
+ continue;
636
+ if (!sf.getFilePath().includes('/src/'))
637
+ continue;
638
+ if (sf.getFilePath().includes('/node_modules/'))
639
+ continue;
640
+ // Break-and-restart after each replacement because replaceWithText()
641
+ // invalidates existing node references in the ts-morph tree
642
+ let madeReplacement = true;
643
+ while (madeReplacement) {
644
+ madeReplacement = false;
645
+ for (const identNode of sf.getDescendantsOfKind(ts_morph_1.SyntaxKind.Identifier)) {
646
+ if (identNode.getText() !== 'applicationConfig')
647
+ continue;
648
+ // Walk up the property-access chain from this identifier
649
+ let node = identNode;
650
+ const accessPath = [];
651
+ while (true) {
652
+ const parent = node.getParent();
653
+ if (!ts_morph_1.Node.isPropertyAccessExpression(parent))
654
+ break;
655
+ if (parent.getExpression() !== node)
656
+ break;
657
+ accessPath.push(parent.getName());
658
+ node = parent;
659
+ }
660
+ if (accessPath.length === 0 || accessPath[0] !== key)
661
+ continue;
662
+ const resolvedValue = resolveConfigChain(init, accessPath);
663
+ if (resolvedValue === null) {
664
+ console.log(` Cannot resolve applicationConfig.${accessPath.join('.')} — skipping inline replacement`);
665
+ continue;
666
+ }
667
+ node.replaceWithText(resolvedValue);
668
+ console.log(` Inlined applicationConfig.${accessPath.join('.')} → ${resolvedValue} in ${path_1.default.relative((0, _1.getCwd)(), sf.getFilePath())}`);
669
+ filesToSaveAfterInlining.add(sf);
670
+ madeReplacement = true;
671
+ break; // restart — tree has changed
672
+ }
673
+ }
674
+ }
675
+ }
676
+ // Persist files that received inline replacements
677
+ for (const sf of Array.from(filesToSaveAfterInlining)) {
678
+ yield sf.save();
679
+ console.log(` Saved (inlined): ${path_1.default.relative((0, _1.getCwd)(), sf.getFilePath())}`);
680
+ }
681
+ // Remove in reverse order to avoid index shifting
682
+ for (const prop of [...propsToRemove].reverse()) {
683
+ const propName = prop.getName();
684
+ console.log(` Removing unknown key '${propName}' from applicationConfig (not in ApplicationConfig schema)`);
685
+ prop.remove();
686
+ }
687
+ }
688
+ // Wrap the plain object literal with defineApplicationConfig(...)
689
+ varDecl.setInitializer(`defineApplicationConfig(${init.getText()})`);
690
+ // Upsert the defineApplicationConfig named import
691
+ const TOOLKIT_MODULE = '@opencrvs/toolkit/application-config';
692
+ const existing = appConfigFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === TOOLKIT_MODULE);
693
+ if (existing) {
694
+ const names = new Set(existing.getNamedImports().map((ni) => ni.getName()));
695
+ if (!names.has('defineApplicationConfig')) {
696
+ existing.addNamedImport('defineApplicationConfig');
697
+ }
698
+ }
699
+ else {
700
+ appConfigFile.addImportDeclaration({
701
+ moduleSpecifier: TOOLKIT_MODULE,
702
+ namedImports: ['defineApplicationConfig']
703
+ });
704
+ }
705
+ wrapped = true;
706
+ console.log(` Wrapped applicationConfig with defineApplicationConfig in ${appConfigRelPath}`);
707
+ break;
708
+ }
709
+ if (!wrapped) {
710
+ console.log(` Skipping Phase 3 — applicationConfig plain object not found (already wrapped?)\n`);
711
+ }
712
+ else {
713
+ yield appConfigFile.save();
714
+ console.log(` Saved: ${appConfigRelPath}\n`);
715
+ }
716
+ }
717
+ // ── Phase 2: Update Hapi route handlers ───────────────────────────────────
718
+ console.log('Phase 2: Updating Hapi route handlers...\n');
719
+ const project = new ts_morph_1.Project({
720
+ tsConfigFilePath: path_1.default.resolve(srcDir, '../tsconfig.json'),
721
+ skipAddingFilesFromTsConfig: false
722
+ });
723
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
724
+ const fp = sf.getFilePath();
725
+ return fp.includes('/src/') && !fp.includes('/node_modules/');
726
+ });
727
+ console.log(` Analysing ${sourceFiles.length} source file(s).\n`);
728
+ let totalReplaced = 0;
729
+ for (const group of CONFIG_GROUPS) {
730
+ totalReplaced += updateRouteHandlers(sourceFiles, group, srcDir, relCwd);
731
+ }
732
+ if (totalReplaced === 0) {
733
+ console.log(' No route handlers matched — nothing to update in Phase 2.\n');
734
+ }
735
+ // ── Save modified TS files ────────────────────────────────────────────────
736
+ const modified = sourceFiles.filter((sf) => sf.wasForgotten() === false);
737
+ const toSave = modified.filter((sf) => sf.getDescendantsOfKind(ts_morph_1.SyntaxKind.ObjectLiteralExpression).length > 0);
738
+ // Only save files that actually had route handler changes
739
+ let savedCount = 0;
740
+ for (const sf of project.getSourceFiles()) {
741
+ if (sf.isSaved())
742
+ continue;
743
+ yield sf.save();
744
+ console.log(` Saved: ${relCwd(sf.getFilePath())}`);
745
+ savedCount++;
746
+ }
747
+ if (savedCount === 0 && totalReplaced === 0) {
748
+ console.log('Nothing was changed.');
749
+ return;
750
+ }
751
+ console.log(`\nDone. Converted ${convertedCount} config file(s), replaced ${totalReplaced} route handler(s).`);
752
+ });
753
+ }