@opencrvs/toolkit 1.9.13-rc.f1fdcea → 2.0.0-beta

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 (157) hide show
  1. package/build.sh +13 -0
  2. package/create-countryconfig/index.js +73 -0
  3. package/create-countryconfig/package.json +11 -0
  4. package/dist/api/index.d.ts.map +1 -1
  5. package/dist/application-config/index.d.ts +2 -0
  6. package/dist/application-config/index.d.ts.map +1 -0
  7. package/dist/application-config/index.js +2158 -0
  8. package/dist/cli.d.ts +2 -0
  9. package/dist/cli.d.ts.map +1 -0
  10. package/dist/cli.js +4974 -0
  11. package/dist/commons/api/router.d.ts +3497 -2348
  12. package/dist/commons/application-config/index.d.ts +96 -0
  13. package/dist/commons/conditionals/conditionals.d.ts +27 -3
  14. package/dist/commons/conditionals/validate.d.ts +13 -2
  15. package/dist/commons/events/ActionConfig.d.ts +415 -1555
  16. package/dist/commons/events/ActionDocument.d.ts +888 -1941
  17. package/dist/commons/events/ActionInput.d.ts +277 -1073
  18. package/dist/commons/events/ActionType.d.ts +91 -11
  19. package/dist/commons/events/AdvancedSearchConfig.d.ts +294 -1496
  20. package/dist/commons/events/AuditLog.d.ts +407 -0
  21. package/dist/commons/events/CompositeFieldValue.d.ts +30 -190
  22. package/dist/commons/events/Conditional.d.ts +26 -38
  23. package/dist/commons/events/Constants.d.ts +1 -1
  24. package/dist/commons/events/CountryConfigQueryInput.d.ts +1592 -4471
  25. package/dist/commons/events/DeduplicationConfig.d.ts +15 -171
  26. package/dist/commons/events/Draft.d.ts +72 -107
  27. package/dist/commons/events/DynamicFieldValue.d.ts +12 -78
  28. package/dist/commons/events/EventConfig.d.ts +37 -2420
  29. package/dist/commons/events/EventConfigInput.d.ts +0 -3
  30. package/dist/commons/events/EventDocument.d.ts +354 -1366
  31. package/dist/commons/events/EventIndex.d.ts +212 -1010
  32. package/dist/commons/events/EventInput.d.ts +3 -8
  33. package/dist/commons/events/EventMetadata.d.ts +130 -357
  34. package/dist/commons/events/FieldConfig.d.ts +2902 -12901
  35. package/dist/commons/events/FieldType.d.ts +26 -4
  36. package/dist/commons/events/FieldTypeMapping.d.ts +314 -906
  37. package/dist/commons/events/FieldValue.d.ts +149 -527
  38. package/dist/commons/events/FileUtils.d.ts +2 -2
  39. package/dist/commons/events/Flag.d.ts +67 -0
  40. package/dist/commons/events/FormConfig.d.ts +54 -721
  41. package/dist/commons/events/PageConfig.d.ts +58 -320
  42. package/dist/commons/events/PlainDate.d.ts +1 -1
  43. package/dist/commons/events/SummaryConfig.d.ts +14 -161
  44. package/dist/commons/events/TemplateConfig.d.ts +2 -3
  45. package/dist/commons/events/TranslationConfig.d.ts +2 -2
  46. package/dist/commons/events/WorkqueueColumnConfig.d.ts +74 -37
  47. package/dist/commons/events/WorkqueueConfig.d.ts +2208 -7553
  48. package/dist/commons/events/deduplication.d.ts +3 -3
  49. package/dist/commons/events/defineConfig.d.ts +2 -247
  50. package/dist/commons/events/eventConfigValidation.d.ts +8 -0
  51. package/dist/commons/events/index.d.ts +3 -0
  52. package/dist/commons/events/locations.d.ts +93 -19
  53. package/dist/commons/events/mocks.test.utils.d.ts +19 -0
  54. package/dist/commons/events/scopes.d.ts +56 -32
  55. package/dist/commons/events/state/availableActions.d.ts +7 -2
  56. package/dist/commons/events/state/flags.d.ts +21 -3
  57. package/dist/commons/events/state/index.d.ts +30 -27
  58. package/dist/commons/events/state/utils.d.ts +190 -172
  59. package/dist/commons/events/test.utils.d.ts +52 -11
  60. package/dist/commons/events/transactions.d.ts +1 -1
  61. package/dist/commons/events/utils.d.ts +374 -443
  62. package/dist/commons/notification/UserNotifications.d.ts +76 -637
  63. package/dist/conditionals/index.d.ts.map +1 -1
  64. package/dist/conditionals/index.js +332 -14
  65. package/dist/events/deduplication.d.ts +3 -3
  66. package/dist/events/index.js +2989 -2121
  67. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts +3 -0
  68. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +1 -0
  69. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +429 -0
  70. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts +3 -0
  71. package/dist/migrations/v2.0/add-resend-invite-notification.d.ts.map +1 -0
  72. package/dist/migrations/v2.0/add-resend-invite-notification.js +373 -0
  73. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +22 -0
  74. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -0
  75. package/dist/migrations/v2.0/checkout-upstream-files.js +147 -0
  76. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts +2 -0
  77. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +1 -0
  78. package/dist/migrations/v2.0/convert-config-files-to-ts.js +828 -0
  79. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts +3 -0
  80. package/dist/migrations/v2.0/convert-paragraph-to-heading.d.ts.map +1 -0
  81. package/dist/migrations/v2.0/convert-paragraph-to-heading.js +158 -0
  82. package/dist/migrations/v2.0/create-events-index.d.ts +3 -0
  83. package/dist/migrations/v2.0/create-events-index.d.ts.map +1 -0
  84. package/dist/migrations/v2.0/create-events-index.js +325 -0
  85. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +3 -0
  86. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +1 -0
  87. package/dist/migrations/v2.0/delete-infrastructure-directory.js +77 -0
  88. package/dist/migrations/v2.0/index.d.ts +11 -0
  89. package/dist/migrations/v2.0/index.d.ts.map +1 -0
  90. package/dist/migrations/v2.0/index.js +4884 -0
  91. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts +3 -0
  92. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +1 -0
  93. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +432 -0
  94. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +3 -0
  95. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +1 -0
  96. package/dist/migrations/v2.0/merge-infrastructure-directory.js +221 -0
  97. package/dist/migrations/v2.0/migrate-application-config-url.d.ts +3 -0
  98. package/dist/migrations/v2.0/migrate-application-config-url.d.ts.map +1 -0
  99. package/dist/migrations/v2.0/migrate-application-config-url.js +342 -0
  100. package/dist/migrations/v2.0/migrate-scopes.d.ts +3 -0
  101. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -0
  102. package/dist/migrations/v2.0/migrate-scopes.js +281 -0
  103. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts +3 -0
  104. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.d.ts.map +1 -0
  105. package/dist/migrations/v2.0/migrate-validated-workqueue-status-to-flag.js +267 -0
  106. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts +3 -0
  107. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -0
  108. package/dist/migrations/v2.0/migrate-workqueue-configs.js +236 -0
  109. package/dist/migrations/v2.0/remove-delete-actions.d.ts +3 -0
  110. package/dist/migrations/v2.0/remove-delete-actions.d.ts.map +1 -0
  111. package/dist/migrations/v2.0/remove-delete-actions.js +156 -0
  112. package/dist/migrations/v2.0/remove-demo-scope.d.ts +3 -0
  113. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +1 -0
  114. package/dist/migrations/v2.0/remove-demo-scope.js +74 -0
  115. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts +3 -0
  116. package/dist/migrations/v2.0/remove-deprecated-imports.d.ts.map +1 -0
  117. package/dist/migrations/v2.0/remove-deprecated-imports.js +96 -0
  118. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts +3 -0
  119. package/dist/migrations/v2.0/remove-fhir-url-helpers.d.ts.map +1 -0
  120. package/dist/migrations/v2.0/remove-fhir-url-helpers.js +163 -0
  121. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts +3 -0
  122. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +1 -0
  123. package/dist/migrations/v2.0/remove-hearth-migrations.js +77 -0
  124. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts +3 -0
  125. package/dist/migrations/v2.0/remove-old-statistics-service.d.ts.map +1 -0
  126. package/dist/migrations/v2.0/remove-old-statistics-service.js +356 -0
  127. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts +3 -0
  128. package/dist/migrations/v2.0/remove-pending-certification-flag.d.ts.map +1 -0
  129. package/dist/migrations/v2.0/remove-pending-certification-flag.js +109 -0
  130. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts +3 -0
  131. package/dist/migrations/v2.0/remove-review-from-register-action.d.ts.map +1 -0
  132. package/dist/migrations/v2.0/remove-review-from-register-action.js +163 -0
  133. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts +3 -0
  134. package/dist/migrations/v2.0/remove-unused-environment-variables.d.ts.map +1 -0
  135. package/dist/migrations/v2.0/remove-unused-environment-variables.js +186 -0
  136. package/dist/migrations/v2.0/rename-api-paths.d.ts +3 -0
  137. package/dist/migrations/v2.0/rename-api-paths.d.ts.map +1 -0
  138. package/dist/migrations/v2.0/rename-api-paths.js +187 -0
  139. package/dist/migrations/v2.0/rename-location-parent-id.d.ts +3 -0
  140. package/dist/migrations/v2.0/rename-location-parent-id.d.ts.map +1 -0
  141. package/dist/migrations/v2.0/rename-location-parent-id.js +180 -0
  142. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts +3 -0
  143. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +1 -0
  144. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +195 -0
  145. package/dist/migrations/v2.0/update-package-json.d.ts +3 -0
  146. package/dist/migrations/v2.0/update-package-json.d.ts.map +1 -0
  147. package/dist/migrations/v2.0/update-package-json.js +105 -0
  148. package/dist/notification/index.d.ts.map +1 -1
  149. package/dist/notification/index.js +2112 -1770
  150. package/dist/scopes/index.d.ts +716 -352
  151. package/dist/scopes/index.d.ts.map +1 -1
  152. package/dist/scopes/index.js +374 -299
  153. package/opencrvs-toolkit-2.0.0-beta.tgz +0 -0
  154. package/package.json +18 -8
  155. package/tsconfig.json +12 -2
  156. package/tsconfig.tsbuildinfo +1 -1
  157. package/dist/commons/events/CreatedAtLocation.d.ts +0 -2
@@ -0,0 +1,4884 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/migrations/v2.0/index.ts
32
+ var v2_exports = {};
33
+ __export(v2_exports, {
34
+ runUpgrade: () => runUpgrade
35
+ });
36
+ module.exports = __toCommonJS(v2_exports);
37
+
38
+ // src/migrations/v2.0/remove-review-from-register-action.ts
39
+ var import_ts_morph = require("ts-morph");
40
+ var import_path = __toESM(require("path"));
41
+ var DEFINE_CONFIG_NAME = "defineConfig";
42
+ var ACTIONS_PROPERTY_NAME = "actions";
43
+ var TYPE_PROPERTY_NAME = "type";
44
+ var REVIEW_PROPERTY_NAME = "review";
45
+ var REGISTER_ENUM_NAME = "ActionType";
46
+ var REGISTER_MEMBER_NAME = "REGISTER";
47
+ var REGISTER_STRING_LITERAL = "REGISTER";
48
+ function isRegisterType(typeInitializer) {
49
+ if (typeInitializer.getKind() === import_ts_morph.SyntaxKind.PropertyAccessExpression) {
50
+ const propAccess = typeInitializer.asKindOrThrow(
51
+ import_ts_morph.SyntaxKind.PropertyAccessExpression
52
+ );
53
+ const obj = propAccess.getExpression();
54
+ const member = propAccess.getName();
55
+ return import_ts_morph.Node.isIdentifier(obj) && obj.getText() === REGISTER_ENUM_NAME && member === REGISTER_MEMBER_NAME;
56
+ }
57
+ if (typeInitializer.getKind() === import_ts_morph.SyntaxKind.StringLiteral) {
58
+ return typeInitializer.asKindOrThrow(import_ts_morph.SyntaxKind.StringLiteral).getLiteralValue() === REGISTER_STRING_LITERAL;
59
+ }
60
+ return false;
61
+ }
62
+ function removeReviewFromRegisterActions(obj) {
63
+ const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME);
64
+ if (!typeProperty || !import_ts_morph.Node.isPropertyAssignment(typeProperty)) {
65
+ return false;
66
+ }
67
+ const typeInitializer = typeProperty.getInitializer();
68
+ if (!typeInitializer || !isRegisterType(typeInitializer)) {
69
+ return false;
70
+ }
71
+ const reviewProperty = obj.getProperty(REVIEW_PROPERTY_NAME);
72
+ if (!reviewProperty) {
73
+ return false;
74
+ }
75
+ reviewProperty.remove();
76
+ return true;
77
+ }
78
+ function processFile(filePath, project) {
79
+ const sourceFile = project.getSourceFile(filePath);
80
+ if (!sourceFile) return 0;
81
+ let removedCount = 0;
82
+ const callExpressions = sourceFile.getDescendantsOfKind(
83
+ import_ts_morph.SyntaxKind.CallExpression
84
+ );
85
+ for (const call of callExpressions) {
86
+ const expression = call.getExpression();
87
+ if (!import_ts_morph.Node.isIdentifier(expression) || expression.getText() !== DEFINE_CONFIG_NAME) {
88
+ continue;
89
+ }
90
+ const args = call.getArguments();
91
+ if (args.length === 0) continue;
92
+ const configArg = args[0];
93
+ if (!import_ts_morph.Node.isObjectLiteralExpression(configArg)) continue;
94
+ const actionsProperty = configArg.getProperty(ACTIONS_PROPERTY_NAME);
95
+ if (!actionsProperty || !import_ts_morph.Node.isPropertyAssignment(actionsProperty))
96
+ continue;
97
+ const actionsInitializer = actionsProperty.getInitializer();
98
+ if (!actionsInitializer || !import_ts_morph.Node.isArrayLiteralExpression(actionsInitializer))
99
+ continue;
100
+ for (const element of actionsInitializer.getElements()) {
101
+ if (!import_ts_morph.Node.isObjectLiteralExpression(element)) continue;
102
+ const wasRemoved = removeReviewFromRegisterActions(element);
103
+ if (wasRemoved) {
104
+ removedCount++;
105
+ console.log(
106
+ ` [${import_path.default.relative(process.cwd(), filePath)}] Removed 'review' from REGISTER action`
107
+ );
108
+ }
109
+ }
110
+ }
111
+ return removedCount;
112
+ }
113
+ async function main() {
114
+ const srcDir = import_path.default.join(process.cwd(), "src");
115
+ console.log(`Scanning for defineConfig calls in: ${srcDir}
116
+ `);
117
+ const project = new import_ts_morph.Project({
118
+ tsConfigFilePath: import_path.default.resolve(srcDir, "../tsconfig.json"),
119
+ // Do not emit — we only manipulate source files
120
+ skipAddingFilesFromTsConfig: false
121
+ // addFilesFromTsConfig: true
122
+ });
123
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
124
+ const fp = sf.getFilePath();
125
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
126
+ });
127
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
128
+ `);
129
+ let totalRemoved = 0;
130
+ const modifiedFiles = [];
131
+ for (const sourceFile of sourceFiles) {
132
+ const filePath = sourceFile.getFilePath();
133
+ const removed = processFile(filePath, project);
134
+ if (removed > 0) {
135
+ totalRemoved += removed;
136
+ modifiedFiles.push(filePath);
137
+ }
138
+ }
139
+ if (modifiedFiles.length === 0) {
140
+ console.log(
141
+ "No 'review' properties found on REGISTER actions. Nothing to do."
142
+ );
143
+ return;
144
+ }
145
+ console.log(`
146
+ Saving ${modifiedFiles.length} modified file(s)...`);
147
+ for (const filePath of modifiedFiles) {
148
+ const sourceFile = project.getSourceFileOrThrow(filePath);
149
+ await sourceFile.save();
150
+ console.log(` Saved: ${import_path.default.relative(process.cwd(), filePath)}`);
151
+ }
152
+ console.log(
153
+ `
154
+ Done. Removed ${totalRemoved} 'review' property assignment(s) from REGISTER action(s).`
155
+ );
156
+ }
157
+
158
+ // src/migrations/v2.0/make-built-in-validate-actions-custom.ts
159
+ var import_ts_morph2 = require("ts-morph");
160
+ var import_path2 = __toESM(require("path"));
161
+ var TOOLKIT_EVENTS_MODULE = "@opencrvs/toolkit/events";
162
+ var REQUIRED_SYMBOLS = [
163
+ "ConditionalType",
164
+ "and",
165
+ "status",
166
+ "not",
167
+ "flag",
168
+ "InherentFlags"
169
+ ];
170
+ function ensureImports(sourceFile) {
171
+ const existingImport = sourceFile.getImportDeclaration(
172
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE
173
+ );
174
+ if (existingImport) {
175
+ const existingNames = new Set(
176
+ existingImport.getNamedImports().map((ni) => ni.getName())
177
+ );
178
+ for (const name of REQUIRED_SYMBOLS) {
179
+ if (!existingNames.has(name)) {
180
+ existingImport.addNamedImport(name);
181
+ }
182
+ }
183
+ } else {
184
+ sourceFile.addImportDeclaration({
185
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE,
186
+ namedImports: REQUIRED_SYMBOLS
187
+ });
188
+ }
189
+ }
190
+ var DEFINE_CONFIG_NAME2 = "defineConfig";
191
+ var ACTIONS_PROPERTY_NAME2 = "actions";
192
+ var TYPE_PROPERTY_NAME2 = "type";
193
+ var ID_PROPERTY_NAME = "id";
194
+ var FLAGS_PROPERTY_NAME = "flags";
195
+ var CUSTOM_ACTION_TYPE_PROPERTY_NAME = "customActionType";
196
+ var AUDIT_HISTORY_LABEL_PROPERTY_NAME = "auditHistoryLabel";
197
+ var DEDUPLICATION_PROPERTY_NAME = "deduplication";
198
+ var REVIEW_PROPERTY_NAME2 = "review";
199
+ var FIELDS_PROPERTY_NAME = "fields";
200
+ var FORM_PROPERTY_NAME = "form";
201
+ var ACTION_TYPE_ENUM_NAME = "ActionType";
202
+ var VALIDATE_MEMBER_NAME = "VALIDATE";
203
+ var CUSTOM_MEMBER_NAME = "CUSTOM";
204
+ var REGISTER_MEMBER_NAME2 = "REGISTER";
205
+ var VALIDATE_STRING_LITERAL = "VALIDATE";
206
+ var CUSTOM_STRING_LITERAL = "CUSTOM";
207
+ var REGISTER_STRING_LITERAL2 = "REGISTER";
208
+ var VALIDATE_DECLARATION_VALUE = "VALIDATE_DECLARATION";
209
+ var VALIDATED_FLAG_VALUE = "validated";
210
+ function isValidateType(typeInitializer) {
211
+ if (typeInitializer.getKind() === import_ts_morph2.SyntaxKind.PropertyAccessExpression) {
212
+ const propAccess = typeInitializer.asKindOrThrow(
213
+ import_ts_morph2.SyntaxKind.PropertyAccessExpression
214
+ );
215
+ const obj = propAccess.getExpression();
216
+ const member = propAccess.getName();
217
+ return import_ts_morph2.Node.isIdentifier(obj) && obj.getText() === ACTION_TYPE_ENUM_NAME && member === VALIDATE_MEMBER_NAME;
218
+ }
219
+ if (typeInitializer.getKind() === import_ts_morph2.SyntaxKind.StringLiteral) {
220
+ return typeInitializer.asKindOrThrow(import_ts_morph2.SyntaxKind.StringLiteral).getLiteralValue() === VALIDATE_STRING_LITERAL;
221
+ }
222
+ return false;
223
+ }
224
+ function resolveEventType(configArg) {
225
+ const typeProperty = configArg.getProperty(TYPE_PROPERTY_NAME2);
226
+ if (!typeProperty || !import_ts_morph2.Node.isPropertyAssignment(typeProperty)) return null;
227
+ const initializer = typeProperty.getInitializer();
228
+ if (!initializer) return null;
229
+ if (import_ts_morph2.Node.isStringLiteral(initializer)) {
230
+ return initializer.getLiteralValue().toLowerCase();
231
+ }
232
+ if (initializer.getKind() === import_ts_morph2.SyntaxKind.PropertyAccessExpression && import_ts_morph2.Node.isPropertyAccessExpression(initializer)) {
233
+ return initializer.getName().toLowerCase();
234
+ }
235
+ return null;
236
+ }
237
+ function transformValidateActionToCustom(obj, eventType) {
238
+ const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME2);
239
+ if (!typeProperty || !import_ts_morph2.Node.isPropertyAssignment(typeProperty)) {
240
+ return false;
241
+ }
242
+ const typeInitializer = typeProperty.getInitializer();
243
+ if (!typeInitializer || !isValidateType(typeInitializer)) {
244
+ return false;
245
+ }
246
+ if (typeInitializer.getKind() === import_ts_morph2.SyntaxKind.PropertyAccessExpression) {
247
+ typeInitializer.replaceWithText(
248
+ `${ACTION_TYPE_ENUM_NAME}.${CUSTOM_MEMBER_NAME}`
249
+ );
250
+ } else {
251
+ typeInitializer.replaceWithText(`'${CUSTOM_STRING_LITERAL}'`);
252
+ }
253
+ if (!obj.getProperty(CUSTOM_ACTION_TYPE_PROPERTY_NAME)) {
254
+ obj.addPropertyAssignment({
255
+ name: CUSTOM_ACTION_TYPE_PROPERTY_NAME,
256
+ initializer: `'${VALIDATE_DECLARATION_VALUE}'`
257
+ });
258
+ }
259
+ if (!obj.getProperty(AUDIT_HISTORY_LABEL_PROPERTY_NAME)) {
260
+ const messageId = `event.${eventType}.custom.action.validate-declaration.audit-history-label`;
261
+ obj.addPropertyAssignment({
262
+ name: AUDIT_HISTORY_LABEL_PROPERTY_NAME,
263
+ initializer: `{
264
+ defaultMessage: 'Validated',
265
+ description: 'The label to show in audit history for the validate action',
266
+ id: '${messageId}'
267
+ }`
268
+ });
269
+ }
270
+ if (!obj.getProperty("supportingCopy")) {
271
+ const supportingCopyId = `event.${eventType}.custom.action.validate-declaration.supportingCopy`;
272
+ obj.addPropertyAssignment({
273
+ name: "supportingCopy",
274
+ initializer: `{
275
+ defaultMessage:
276
+ 'Approving this declaration confirms it as legally accepted and eligible for registration.',
277
+ description:
278
+ 'This is the supporting copy for the Validate declaration -action',
279
+ id: '${supportingCopyId}'
280
+ }`
281
+ });
282
+ }
283
+ if (!obj.getProperty("conditionals")) {
284
+ obj.addPropertyAssignment({
285
+ name: "conditionals",
286
+ initializer: `[
287
+ {
288
+ type: ConditionalType.SHOW,
289
+ conditional: and(status('DECLARED'), not(flag('validated')))
290
+ },
291
+ {
292
+ type: ConditionalType.ENABLE,
293
+ conditional: not(flag(InherentFlags.POTENTIAL_DUPLICATE))
294
+ }
295
+ ]`
296
+ });
297
+ }
298
+ if (!obj.getProperty("flags")) {
299
+ obj.addPropertyAssignment({
300
+ name: "flags",
301
+ initializer: `[{ id: 'validated', operation: 'add' }]`
302
+ });
303
+ }
304
+ const deduplicationProperty = obj.getProperty(DEDUPLICATION_PROPERTY_NAME);
305
+ if (deduplicationProperty) {
306
+ deduplicationProperty.remove();
307
+ }
308
+ const reviewProperty = obj.getProperty(REVIEW_PROPERTY_NAME2);
309
+ if (reviewProperty && import_ts_morph2.Node.isPropertyAssignment(reviewProperty)) {
310
+ const reviewInitializer = reviewProperty.getInitializer();
311
+ if (reviewInitializer) {
312
+ if (import_ts_morph2.Node.isObjectLiteralExpression(reviewInitializer)) {
313
+ const fieldsProperty = reviewInitializer.getProperty(FIELDS_PROPERTY_NAME);
314
+ if (fieldsProperty && import_ts_morph2.Node.isPropertyAssignment(fieldsProperty)) {
315
+ const fieldsInitializer = fieldsProperty.getInitializer();
316
+ if (fieldsInitializer) {
317
+ reviewProperty.set({
318
+ name: FORM_PROPERTY_NAME,
319
+ initializer: fieldsInitializer.getText()
320
+ });
321
+ }
322
+ }
323
+ } else {
324
+ reviewProperty.set({
325
+ name: FORM_PROPERTY_NAME,
326
+ initializer: `${reviewInitializer.getText()}.fields`
327
+ });
328
+ }
329
+ }
330
+ }
331
+ return true;
332
+ }
333
+ function isRegisterAction(action) {
334
+ const typeProperty = action.getProperty(TYPE_PROPERTY_NAME2);
335
+ if (!typeProperty || !import_ts_morph2.Node.isPropertyAssignment(typeProperty)) return false;
336
+ const typeInit = typeProperty.getInitializer();
337
+ if (!typeInit) return false;
338
+ if (import_ts_morph2.Node.isPropertyAccessExpression(typeInit)) {
339
+ const enumExpr = typeInit.getExpression();
340
+ return import_ts_morph2.Node.isIdentifier(enumExpr) && enumExpr.getText() === ACTION_TYPE_ENUM_NAME && typeInit.getName() === REGISTER_MEMBER_NAME2;
341
+ }
342
+ if (import_ts_morph2.Node.isStringLiteral(typeInit)) {
343
+ return typeInit.getLiteralValue() === REGISTER_STRING_LITERAL2;
344
+ }
345
+ return false;
346
+ }
347
+ function arrayHasElementWithId(array3, id) {
348
+ for (const el of array3.getElements()) {
349
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(el)) continue;
350
+ const idProp = el.getProperty(ID_PROPERTY_NAME);
351
+ if (!idProp || !import_ts_morph2.Node.isPropertyAssignment(idProp)) continue;
352
+ const idInit = idProp.getInitializer();
353
+ if (idInit && import_ts_morph2.Node.isStringLiteral(idInit) && idInit.getLiteralValue() === id) {
354
+ return true;
355
+ }
356
+ }
357
+ return false;
358
+ }
359
+ function ensureRegisterRemovesValidatedFlag(action) {
360
+ const entry = `{ id: '${VALIDATED_FLAG_VALUE}', operation: 'remove' }`;
361
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME);
362
+ if (flagsProp && import_ts_morph2.Node.isPropertyAssignment(flagsProp)) {
363
+ const flagsInit = flagsProp.getInitializer();
364
+ if (flagsInit && import_ts_morph2.Node.isArrayLiteralExpression(flagsInit)) {
365
+ if (arrayHasElementWithId(flagsInit, VALIDATED_FLAG_VALUE)) return false;
366
+ flagsInit.addElement(entry);
367
+ return true;
368
+ }
369
+ return false;
370
+ }
371
+ action.addPropertyAssignment({
372
+ name: FLAGS_PROPERTY_NAME,
373
+ initializer: `[${entry}]`
374
+ });
375
+ return true;
376
+ }
377
+ function processFile2(filePath, project) {
378
+ const sourceFile = project.getSourceFile(filePath);
379
+ if (!sourceFile) return 0;
380
+ let transformedCount = 0;
381
+ const callExpressions = sourceFile.getDescendantsOfKind(
382
+ import_ts_morph2.SyntaxKind.CallExpression
383
+ );
384
+ for (const call of callExpressions) {
385
+ const expression = call.getExpression();
386
+ if (!import_ts_morph2.Node.isIdentifier(expression) || expression.getText() !== DEFINE_CONFIG_NAME2) {
387
+ continue;
388
+ }
389
+ const args = call.getArguments();
390
+ if (args.length === 0) continue;
391
+ const configArg = args[0];
392
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(configArg)) continue;
393
+ const actionsProperty = configArg.getProperty(ACTIONS_PROPERTY_NAME2);
394
+ if (!actionsProperty || !import_ts_morph2.Node.isPropertyAssignment(actionsProperty))
395
+ continue;
396
+ const actionsInitializer = actionsProperty.getInitializer();
397
+ if (!actionsInitializer || !import_ts_morph2.Node.isArrayLiteralExpression(actionsInitializer))
398
+ continue;
399
+ const eventType = resolveEventType(configArg);
400
+ if (!eventType) {
401
+ console.warn(
402
+ ` [${import_path2.default.relative(process.cwd(), configArg.getSourceFile().getFilePath())}] Could not resolve root 'type' from defineConfig \u2014 skipping auditHistoryLabel id generation`
403
+ );
404
+ }
405
+ let fileNeedsImports = false;
406
+ let configHadValidateAction = false;
407
+ for (const element of actionsInitializer.getElements()) {
408
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(element)) continue;
409
+ const wasTransformed = transformValidateActionToCustom(
410
+ element,
411
+ eventType ?? "unknown"
412
+ );
413
+ if (wasTransformed) {
414
+ transformedCount++;
415
+ fileNeedsImports = true;
416
+ configHadValidateAction = true;
417
+ console.log(
418
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Transformed VALIDATE action to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'`
419
+ );
420
+ }
421
+ }
422
+ if (configHadValidateAction && !configArg.getProperty("flags")) {
423
+ const resolvedEventType = eventType ?? "unknown";
424
+ configArg.addPropertyAssignment({
425
+ name: "flags",
426
+ initializer: `[
427
+ {
428
+ id: 'validated',
429
+ label: {
430
+ id: 'event.${resolvedEventType}.flag.validated',
431
+ defaultMessage: 'Validated',
432
+ description: 'Flag label for validated'
433
+ },
434
+ requiresAction: true
435
+ }
436
+ ]`
437
+ });
438
+ console.log(
439
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Added top-level 'flags' array to defineConfig`
440
+ );
441
+ }
442
+ if (configHadValidateAction) {
443
+ for (const element of actionsInitializer.getElements()) {
444
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(element)) continue;
445
+ if (!isRegisterAction(element)) continue;
446
+ if (ensureRegisterRemovesValidatedFlag(element)) {
447
+ transformedCount++;
448
+ console.log(
449
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Added '${VALIDATED_FLAG_VALUE}' remove-flag to REGISTER action`
450
+ );
451
+ }
452
+ }
453
+ }
454
+ if (fileNeedsImports) {
455
+ ensureImports(sourceFile);
456
+ }
457
+ }
458
+ return transformedCount;
459
+ }
460
+ async function main2() {
461
+ const srcDir = import_path2.default.join(process.cwd(), "src");
462
+ console.log(`Scanning for defineConfig calls in: ${srcDir}
463
+ `);
464
+ const project = new import_ts_morph2.Project({
465
+ tsConfigFilePath: import_path2.default.resolve(srcDir, "../tsconfig.json"),
466
+ // Do not emit — we only manipulate source files
467
+ skipAddingFilesFromTsConfig: false
468
+ });
469
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
470
+ const fp = sf.getFilePath();
471
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
472
+ });
473
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
474
+ `);
475
+ let totalTransformed = 0;
476
+ const modifiedFiles = [];
477
+ for (const sourceFile of sourceFiles) {
478
+ const filePath = sourceFile.getFilePath();
479
+ const transformed = processFile2(filePath, project);
480
+ if (transformed > 0) {
481
+ totalTransformed += transformed;
482
+ modifiedFiles.push(filePath);
483
+ }
484
+ }
485
+ if (modifiedFiles.length === 0) {
486
+ console.log(
487
+ "No VALIDATE actions found inside defineConfig calls. Nothing to do."
488
+ );
489
+ return;
490
+ }
491
+ console.log(`
492
+ Saving ${modifiedFiles.length} modified file(s)...`);
493
+ for (const filePath of modifiedFiles) {
494
+ const sourceFile = project.getSourceFileOrThrow(filePath);
495
+ await sourceFile.save();
496
+ console.log(` Saved: ${import_path2.default.relative(process.cwd(), filePath)}`);
497
+ }
498
+ console.log(
499
+ `
500
+ Done. Applied ${totalTransformed} change(s): VALIDATE \u2192 CUSTOM (${VALIDATE_DECLARATION_VALUE}) and '${VALIDATED_FLAG_VALUE}' remove-flag on matching REGISTER actions.`
501
+ );
502
+ }
503
+
504
+ // src/migrations/v2.0/remove-delete-actions.ts
505
+ var import_ts_morph3 = require("ts-morph");
506
+ var import_path3 = __toESM(require("path"));
507
+ var DEFINE_CONFIG_NAME3 = "defineConfig";
508
+ var ACTIONS_PROPERTY_NAME3 = "actions";
509
+ var TYPE_PROPERTY_NAME3 = "type";
510
+ var ACTION_TYPE_ENUM_NAME2 = "ActionType";
511
+ var DELETE_MEMBER_NAME = "DELETE";
512
+ var DELETE_STRING_LITERAL = "DELETE";
513
+ function isDeleteType(typeInitializer) {
514
+ if (typeInitializer.getKind() === import_ts_morph3.SyntaxKind.PropertyAccessExpression) {
515
+ const propAccess = typeInitializer.asKindOrThrow(
516
+ import_ts_morph3.SyntaxKind.PropertyAccessExpression
517
+ );
518
+ const obj = propAccess.getExpression();
519
+ const member = propAccess.getName();
520
+ return import_ts_morph3.Node.isIdentifier(obj) && obj.getText() === ACTION_TYPE_ENUM_NAME2 && member === DELETE_MEMBER_NAME;
521
+ }
522
+ if (typeInitializer.getKind() === import_ts_morph3.SyntaxKind.StringLiteral) {
523
+ return typeInitializer.asKindOrThrow(import_ts_morph3.SyntaxKind.StringLiteral).getLiteralValue() === DELETE_STRING_LITERAL;
524
+ }
525
+ return false;
526
+ }
527
+ function isDeleteAction(obj) {
528
+ const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME3);
529
+ if (!typeProperty || !import_ts_morph3.Node.isPropertyAssignment(typeProperty)) {
530
+ return false;
531
+ }
532
+ const typeInitializer = typeProperty.getInitializer();
533
+ return !!typeInitializer && isDeleteType(typeInitializer);
534
+ }
535
+ function processFile3(filePath, project) {
536
+ const sourceFile = project.getSourceFile(filePath);
537
+ if (!sourceFile) return 0;
538
+ let removedCount = 0;
539
+ const callExpressions = sourceFile.getDescendantsOfKind(
540
+ import_ts_morph3.SyntaxKind.CallExpression
541
+ );
542
+ for (const call of callExpressions) {
543
+ const expression = call.getExpression();
544
+ if (!import_ts_morph3.Node.isIdentifier(expression) || expression.getText() !== DEFINE_CONFIG_NAME3) {
545
+ continue;
546
+ }
547
+ const args = call.getArguments();
548
+ if (args.length === 0) continue;
549
+ const configArg = args[0];
550
+ if (!import_ts_morph3.Node.isObjectLiteralExpression(configArg)) continue;
551
+ const actionsProperty = configArg.getProperty(ACTIONS_PROPERTY_NAME3);
552
+ if (!actionsProperty || !import_ts_morph3.Node.isPropertyAssignment(actionsProperty))
553
+ continue;
554
+ const actionsInitializer = actionsProperty.getInitializer();
555
+ if (!actionsInitializer || !import_ts_morph3.Node.isArrayLiteralExpression(actionsInitializer))
556
+ continue;
557
+ const indicesToRemove = [];
558
+ actionsInitializer.getElements().forEach((element, index) => {
559
+ if (import_ts_morph3.Node.isObjectLiteralExpression(element) && isDeleteAction(element)) {
560
+ indicesToRemove.push(index);
561
+ }
562
+ });
563
+ for (const index of indicesToRemove.reverse()) {
564
+ actionsInitializer.removeElement(index);
565
+ removedCount++;
566
+ console.log(
567
+ ` [${import_path3.default.relative(process.cwd(), filePath)}] Removed DELETE action at index ${index}`
568
+ );
569
+ }
570
+ }
571
+ return removedCount;
572
+ }
573
+ async function main3() {
574
+ const srcDir = import_path3.default.join(process.cwd(), "src");
575
+ console.log(`Scanning for defineConfig calls in: ${srcDir}
576
+ `);
577
+ const project = new import_ts_morph3.Project({
578
+ tsConfigFilePath: import_path3.default.resolve(srcDir, "../tsconfig.json"),
579
+ // Do not emit — we only manipulate source files
580
+ skipAddingFilesFromTsConfig: false
581
+ });
582
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
583
+ const fp = sf.getFilePath();
584
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
585
+ });
586
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
587
+ `);
588
+ let totalRemoved = 0;
589
+ const modifiedFiles = [];
590
+ for (const sourceFile of sourceFiles) {
591
+ const filePath = sourceFile.getFilePath();
592
+ const removed = processFile3(filePath, project);
593
+ if (removed > 0) {
594
+ totalRemoved += removed;
595
+ modifiedFiles.push(filePath);
596
+ }
597
+ }
598
+ if (modifiedFiles.length === 0) {
599
+ console.log(
600
+ "No DELETE actions found inside defineConfig calls. Nothing to do."
601
+ );
602
+ return;
603
+ }
604
+ console.log(`
605
+ Saving ${modifiedFiles.length} modified file(s)...`);
606
+ for (const filePath of modifiedFiles) {
607
+ const sourceFile = project.getSourceFileOrThrow(filePath);
608
+ await sourceFile.save();
609
+ console.log(` Saved: ${import_path3.default.relative(process.cwd(), filePath)}`);
610
+ }
611
+ console.log(
612
+ `
613
+ Done. Removed ${totalRemoved} DELETE action(s) from defineConfig call(s).`
614
+ );
615
+ }
616
+
617
+ // src/migrations/v2.0/convert-paragraph-to-heading.ts
618
+ var import_ts_morph4 = require("ts-morph");
619
+ var import_path4 = __toESM(require("path"));
620
+ var FIELD_TYPE_ENUM_NAME = "FieldType";
621
+ var PARAGRAPH_MEMBER_NAME = "PARAGRAPH";
622
+ var HEADING_MEMBER_NAME = "HEADING";
623
+ var TYPE_PROPERTY_NAME4 = "type";
624
+ var CONFIGURATION_PROPERTY_NAME = "configuration";
625
+ var STYLES_PROPERTY_NAME = "styles";
626
+ var FONT_VARIANT_PROPERTY_NAME = "fontVariant";
627
+ var HEADING_FONT_VARIANTS = /* @__PURE__ */ new Set(["h1", "h2", "h3", "h4"]);
628
+ function isParagraphType(typeInitializer) {
629
+ if (!import_ts_morph4.Node.isPropertyAccessExpression(typeInitializer)) return false;
630
+ const obj = typeInitializer.getExpression();
631
+ const member = typeInitializer.getName();
632
+ return import_ts_morph4.Node.isIdentifier(obj) && obj.getText() === FIELD_TYPE_ENUM_NAME && member === PARAGRAPH_MEMBER_NAME;
633
+ }
634
+ function getFontVariantProperty(obj) {
635
+ const configProperty = obj.getProperty(CONFIGURATION_PROPERTY_NAME);
636
+ if (!configProperty || !import_ts_morph4.Node.isPropertyAssignment(configProperty)) return null;
637
+ const configInitializer = configProperty.getInitializer();
638
+ if (!configInitializer || !import_ts_morph4.Node.isObjectLiteralExpression(configInitializer))
639
+ return null;
640
+ const stylesProperty = configInitializer.getProperty(STYLES_PROPERTY_NAME);
641
+ if (!stylesProperty || !import_ts_morph4.Node.isPropertyAssignment(stylesProperty)) return null;
642
+ const stylesInitializer = stylesProperty.getInitializer();
643
+ if (!stylesInitializer || !import_ts_morph4.Node.isObjectLiteralExpression(stylesInitializer))
644
+ return null;
645
+ const fontVariantProperty = stylesInitializer.getProperty(
646
+ FONT_VARIANT_PROPERTY_NAME
647
+ );
648
+ if (!fontVariantProperty || !import_ts_morph4.Node.isPropertyAssignment(fontVariantProperty))
649
+ return null;
650
+ return fontVariantProperty;
651
+ }
652
+ function transformParagraphField(obj) {
653
+ const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME4);
654
+ if (!typeProperty || !import_ts_morph4.Node.isPropertyAssignment(typeProperty)) return null;
655
+ const typeInitializer = typeProperty.getInitializer();
656
+ if (!typeInitializer || !isParagraphType(typeInitializer)) return null;
657
+ const fontVariantProperty = getFontVariantProperty(obj);
658
+ if (fontVariantProperty) {
659
+ const fontVariantInitializer = fontVariantProperty.getInitializer();
660
+ if (fontVariantInitializer && import_ts_morph4.Node.isStringLiteral(fontVariantInitializer) && HEADING_FONT_VARIANTS.has(fontVariantInitializer.getLiteralValue())) {
661
+ typeInitializer.replaceWithText(
662
+ `${FIELD_TYPE_ENUM_NAME}.${HEADING_MEMBER_NAME}`
663
+ );
664
+ return "converted-to-heading";
665
+ }
666
+ fontVariantProperty.remove();
667
+ return "removed-font-variant";
668
+ }
669
+ return null;
670
+ }
671
+ function processFile4(filePath, project) {
672
+ const sourceFile = project.getSourceFile(filePath);
673
+ if (!sourceFile) return 0;
674
+ let changedCount = 0;
675
+ const objectLiterals = sourceFile.getDescendantsOfKind(
676
+ import_ts_morph4.SyntaxKind.ObjectLiteralExpression
677
+ );
678
+ for (const obj of objectLiterals) {
679
+ const result = transformParagraphField(obj);
680
+ if (result === "converted-to-heading") {
681
+ changedCount++;
682
+ console.log(
683
+ ` [${import_path4.default.relative(process.cwd(), filePath)}] Converted PARAGRAPH with heading fontVariant to HEADING`
684
+ );
685
+ } else if (result === "removed-font-variant") {
686
+ changedCount++;
687
+ console.log(
688
+ ` [${import_path4.default.relative(process.cwd(), filePath)}] Removed non-heading fontVariant from PARAGRAPH`
689
+ );
690
+ }
691
+ }
692
+ return changedCount;
693
+ }
694
+ async function main4() {
695
+ const srcDir = import_path4.default.join(process.cwd(), "src");
696
+ console.log(`Scanning for FieldType.PARAGRAPH fields in: ${srcDir}
697
+ `);
698
+ const project = new import_ts_morph4.Project({
699
+ tsConfigFilePath: import_path4.default.resolve(srcDir, "../tsconfig.json"),
700
+ skipAddingFilesFromTsConfig: false
701
+ });
702
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
703
+ const fp = sf.getFilePath();
704
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
705
+ });
706
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
707
+ `);
708
+ let totalChanged = 0;
709
+ const modifiedFiles = [];
710
+ for (const sourceFile of sourceFiles) {
711
+ const filePath = sourceFile.getFilePath();
712
+ const changed = processFile4(filePath, project);
713
+ if (changed > 0) {
714
+ totalChanged += changed;
715
+ modifiedFiles.push(filePath);
716
+ }
717
+ }
718
+ if (modifiedFiles.length === 0) {
719
+ console.log(
720
+ "No FieldType.PARAGRAPH fields with fontVariant found. Nothing to do."
721
+ );
722
+ return;
723
+ }
724
+ console.log(`
725
+ Saving ${modifiedFiles.length} modified file(s)...`);
726
+ for (const filePath of modifiedFiles) {
727
+ const sourceFile = project.getSourceFileOrThrow(filePath);
728
+ await sourceFile.save();
729
+ console.log(` Saved: ${import_path4.default.relative(process.cwd(), filePath)}`);
730
+ }
731
+ console.log(`
732
+ Done. Processed ${totalChanged} FieldType.PARAGRAPH field(s).`);
733
+ }
734
+
735
+ // src/migrations/v2.0/migrate-validated-workqueue-status-to-flag.ts
736
+ var import_ts_morph5 = require("ts-morph");
737
+ var import_path5 = __toESM(require("path"));
738
+ var DEFINE_WORKQUEUES_NAME = "defineWorkqueues";
739
+ var QUERY_PROPERTY_NAME = "query";
740
+ var TYPE_PROPERTY_NAME5 = "type";
741
+ var CLAUSES_PROPERTY_NAME = "clauses";
742
+ var STATUS_PROPERTY_NAME = "status";
743
+ var FLAGS_PROPERTY_NAME2 = "flags";
744
+ var TERMS_PROPERTY_NAME = "terms";
745
+ var TERM_PROPERTY_NAME = "term";
746
+ var ANY_OF_PROPERTY_NAME = "anyOf";
747
+ var VALIDATED_STATUS_VALUE = "VALIDATED";
748
+ var VALIDATED_FLAG_VALUE2 = "validated";
749
+ function addValidatedFlag(clause) {
750
+ const flagsProperty = clause.getProperty(FLAGS_PROPERTY_NAME2);
751
+ if (flagsProperty && import_ts_morph5.Node.isPropertyAssignment(flagsProperty)) {
752
+ const flagsInit = flagsProperty.getInitializer();
753
+ if (flagsInit && import_ts_morph5.Node.isObjectLiteralExpression(flagsInit)) {
754
+ const anyOfProperty = flagsInit.getProperty(ANY_OF_PROPERTY_NAME);
755
+ if (anyOfProperty && import_ts_morph5.Node.isPropertyAssignment(anyOfProperty)) {
756
+ const anyOfInit = anyOfProperty.getInitializer();
757
+ if (anyOfInit && import_ts_morph5.Node.isArrayLiteralExpression(anyOfInit)) {
758
+ anyOfInit.addElement(`'${VALIDATED_FLAG_VALUE2}'`);
759
+ }
760
+ } else {
761
+ flagsInit.addPropertyAssignment({
762
+ name: ANY_OF_PROPERTY_NAME,
763
+ initializer: `['${VALIDATED_FLAG_VALUE2}']`
764
+ });
765
+ }
766
+ }
767
+ } else {
768
+ clause.addPropertyAssignment({
769
+ name: FLAGS_PROPERTY_NAME2,
770
+ initializer: `{ ${ANY_OF_PROPERTY_NAME}: ['${VALIDATED_FLAG_VALUE2}'] }`
771
+ });
772
+ }
773
+ }
774
+ function migrateClause(clause) {
775
+ const statusProperty = clause.getProperty(STATUS_PROPERTY_NAME);
776
+ if (!statusProperty || !import_ts_morph5.Node.isPropertyAssignment(statusProperty)) {
777
+ return false;
778
+ }
779
+ const statusInit = statusProperty.getInitializer();
780
+ if (!statusInit || !import_ts_morph5.Node.isObjectLiteralExpression(statusInit)) {
781
+ return false;
782
+ }
783
+ const statusTypeProperty = statusInit.getProperty(TYPE_PROPERTY_NAME5);
784
+ if (!statusTypeProperty || !import_ts_morph5.Node.isPropertyAssignment(statusTypeProperty)) {
785
+ return false;
786
+ }
787
+ const statusTypeInit = statusTypeProperty.getInitializer();
788
+ if (!statusTypeInit || !import_ts_morph5.Node.isStringLiteral(statusTypeInit)) {
789
+ return false;
790
+ }
791
+ const statusType = statusTypeInit.getLiteralValue();
792
+ if (statusType === "anyOf") {
793
+ const termsProperty = statusInit.getProperty(TERMS_PROPERTY_NAME);
794
+ if (!termsProperty || !import_ts_morph5.Node.isPropertyAssignment(termsProperty)) {
795
+ return false;
796
+ }
797
+ const termsInit = termsProperty.getInitializer();
798
+ if (!termsInit || !import_ts_morph5.Node.isArrayLiteralExpression(termsInit)) {
799
+ return false;
800
+ }
801
+ const elements = termsInit.getElements();
802
+ const validatedIndex = elements.findIndex(
803
+ (el) => import_ts_morph5.Node.isStringLiteral(el) && el.getLiteralValue() === VALIDATED_STATUS_VALUE
804
+ );
805
+ if (validatedIndex === -1) return false;
806
+ termsInit.removeElement(validatedIndex);
807
+ if (termsInit.getElements().length === 0) {
808
+ statusProperty.remove();
809
+ }
810
+ addValidatedFlag(clause);
811
+ return true;
812
+ }
813
+ if (statusType === "exact") {
814
+ const termProperty = statusInit.getProperty(TERM_PROPERTY_NAME);
815
+ if (!termProperty || !import_ts_morph5.Node.isPropertyAssignment(termProperty)) {
816
+ return false;
817
+ }
818
+ const termInit = termProperty.getInitializer();
819
+ if (!termInit || !import_ts_morph5.Node.isStringLiteral(termInit)) {
820
+ return false;
821
+ }
822
+ if (termInit.getLiteralValue() !== VALIDATED_STATUS_VALUE) return false;
823
+ statusProperty.remove();
824
+ addValidatedFlag(clause);
825
+ return true;
826
+ }
827
+ return false;
828
+ }
829
+ function walkQuery(queryObj) {
830
+ const typeProperty = queryObj.getProperty(TYPE_PROPERTY_NAME5);
831
+ if (typeProperty && import_ts_morph5.Node.isPropertyAssignment(typeProperty)) {
832
+ const typeInit = typeProperty.getInitializer();
833
+ if (typeInit && import_ts_morph5.Node.isStringLiteral(typeInit) && (typeInit.getLiteralValue() === "or" || typeInit.getLiteralValue() === "and")) {
834
+ const clausesProperty = queryObj.getProperty(CLAUSES_PROPERTY_NAME);
835
+ if (!clausesProperty || !import_ts_morph5.Node.isPropertyAssignment(clausesProperty)) {
836
+ return 0;
837
+ }
838
+ const clausesInit = clausesProperty.getInitializer();
839
+ if (!clausesInit || !import_ts_morph5.Node.isArrayLiteralExpression(clausesInit)) {
840
+ return 0;
841
+ }
842
+ let changed = 0;
843
+ for (const clause of clausesInit.getElements()) {
844
+ if (import_ts_morph5.Node.isObjectLiteralExpression(clause)) {
845
+ changed += walkQuery(clause);
846
+ }
847
+ }
848
+ return changed;
849
+ }
850
+ }
851
+ return migrateClause(queryObj) ? 1 : 0;
852
+ }
853
+ function processFile5(filePath, project) {
854
+ const sourceFile = project.getSourceFile(filePath);
855
+ if (!sourceFile) return 0;
856
+ let migratedCount = 0;
857
+ const callExpressions = sourceFile.getDescendantsOfKind(
858
+ import_ts_morph5.SyntaxKind.CallExpression
859
+ );
860
+ for (const call of callExpressions) {
861
+ const expression = call.getExpression();
862
+ if (!import_ts_morph5.Node.isIdentifier(expression) || expression.getText() !== DEFINE_WORKQUEUES_NAME) {
863
+ continue;
864
+ }
865
+ const args = call.getArguments();
866
+ if (args.length === 0) continue;
867
+ const workqueuesArg = args[0];
868
+ if (!import_ts_morph5.Node.isArrayLiteralExpression(workqueuesArg)) continue;
869
+ for (const workqueueElement of workqueuesArg.getElements()) {
870
+ if (!import_ts_morph5.Node.isObjectLiteralExpression(workqueueElement)) continue;
871
+ const queryProperty = workqueueElement.getProperty(QUERY_PROPERTY_NAME);
872
+ if (!queryProperty || !import_ts_morph5.Node.isPropertyAssignment(queryProperty)) continue;
873
+ const queryInit = queryProperty.getInitializer();
874
+ if (!queryInit || !import_ts_morph5.Node.isObjectLiteralExpression(queryInit)) continue;
875
+ const changed = walkQuery(queryInit);
876
+ if (changed > 0) {
877
+ migratedCount += changed;
878
+ console.log(
879
+ ` [${import_path5.default.relative(process.cwd(), filePath)}] Migrated ${changed} clause(s): VALIDATED status \u2192 flags.anyOf`
880
+ );
881
+ }
882
+ }
883
+ }
884
+ return migratedCount;
885
+ }
886
+ async function main5() {
887
+ const srcDir = import_path5.default.join(process.cwd(), "src");
888
+ console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
889
+ `);
890
+ const project = new import_ts_morph5.Project({
891
+ tsConfigFilePath: import_path5.default.resolve(srcDir, "../tsconfig.json"),
892
+ skipAddingFilesFromTsConfig: false
893
+ });
894
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
895
+ const fp = sf.getFilePath();
896
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
897
+ });
898
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
899
+ `);
900
+ let totalMigrated = 0;
901
+ const modifiedFiles = [];
902
+ for (const sourceFile of sourceFiles) {
903
+ const filePath = sourceFile.getFilePath();
904
+ const migrated = processFile5(filePath, project);
905
+ if (migrated > 0) {
906
+ totalMigrated += migrated;
907
+ modifiedFiles.push(filePath);
908
+ }
909
+ }
910
+ if (modifiedFiles.length === 0) {
911
+ console.log(
912
+ "No VALIDATED status references found in defineWorkqueues calls. Nothing to do."
913
+ );
914
+ return;
915
+ }
916
+ console.log(`
917
+ Saving ${modifiedFiles.length} modified file(s)...`);
918
+ for (const filePath of modifiedFiles) {
919
+ const sourceFile = project.getSourceFileOrThrow(filePath);
920
+ await sourceFile.save();
921
+ console.log(` Saved: ${import_path5.default.relative(process.cwd(), filePath)}`);
922
+ }
923
+ console.log(
924
+ `
925
+ Done. Migrated ${totalMigrated} clause(s) from VALIDATED status to flags.anyOf['validated'].`
926
+ );
927
+ }
928
+
929
+ // src/migrations/v2.0/add-birth-certificate-issuance-flag.ts
930
+ var import_ts_morph6 = require("ts-morph");
931
+ var import_path6 = __toESM(require("path"));
932
+ var DEFINE_CONFIG_NAME4 = "defineConfig";
933
+ var DEFINE_WORKQUEUES_NAME2 = "defineWorkqueues";
934
+ var ACTIONS_PROPERTY_NAME4 = "actions";
935
+ var ACTION_PROPERTY_NAME = "action";
936
+ var FLAGS_PROPERTY_NAME3 = "flags";
937
+ var QUERY_PROPERTY_NAME2 = "query";
938
+ var TYPE_PROPERTY_NAME6 = "type";
939
+ var ID_PROPERTY_NAME2 = "id";
940
+ var CLAUSES_PROPERTY_NAME2 = "clauses";
941
+ var ANY_OF_PROPERTY_NAME2 = "anyOf";
942
+ var FLAG_ID = "pending-first-certificate-issuance";
943
+ var REGISTER_TYPE = "REGISTER";
944
+ var PRINT_CERTIFICATE_TYPE = "PRINT_CERTIFICATE";
945
+ function flagDefinitionInitializer(eventType) {
946
+ return `{
947
+ id: '${FLAG_ID}',
948
+ label: {
949
+ id: 'event.${eventType}.flag.${FLAG_ID}',
950
+ defaultMessage: 'Pending first certificate issuance',
951
+ description: 'Flag label for first certificate issuance'
952
+ },
953
+ requiresAction: true
954
+ }`;
955
+ }
956
+ function isActionOfType(obj, typeName) {
957
+ const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME6);
958
+ if (!typeProperty || !import_ts_morph6.Node.isPropertyAssignment(typeProperty)) return false;
959
+ const typeInit = typeProperty.getInitializer();
960
+ if (!typeInit) return false;
961
+ if (import_ts_morph6.Node.isPropertyAccessExpression(typeInit)) {
962
+ return typeInit.getName() === typeName;
963
+ }
964
+ if (import_ts_morph6.Node.isStringLiteral(typeInit)) {
965
+ return typeInit.getLiteralValue() === typeName;
966
+ }
967
+ return false;
968
+ }
969
+ function getEventType(configArg) {
970
+ for (const propName of [TYPE_PROPERTY_NAME6, ID_PROPERTY_NAME2]) {
971
+ const prop = configArg.getProperty(propName);
972
+ if (!prop || !import_ts_morph6.Node.isPropertyAssignment(prop)) continue;
973
+ const initializer = prop.getInitializer();
974
+ if (!initializer) continue;
975
+ if (import_ts_morph6.Node.isStringLiteral(initializer)) {
976
+ return initializer.getLiteralValue().toLowerCase();
977
+ }
978
+ if (import_ts_morph6.Node.isPropertyAccessExpression(initializer)) {
979
+ return initializer.getName().toLowerCase();
980
+ }
981
+ }
982
+ return null;
983
+ }
984
+ function hasElementWithId(array3, id) {
985
+ for (const el of array3.getElements()) {
986
+ if (!import_ts_morph6.Node.isObjectLiteralExpression(el)) continue;
987
+ const idProp = el.getProperty("id");
988
+ if (!idProp || !import_ts_morph6.Node.isPropertyAssignment(idProp)) continue;
989
+ const idInit = idProp.getInitializer();
990
+ if (idInit && import_ts_morph6.Node.isStringLiteral(idInit) && idInit.getLiteralValue() === id) {
991
+ return true;
992
+ }
993
+ }
994
+ return false;
995
+ }
996
+ function ensureTopLevelFlagDefinition(configArg, eventType) {
997
+ const initializer = flagDefinitionInitializer(eventType);
998
+ const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME3);
999
+ if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
1000
+ const flagsInit = flagsProp.getInitializer();
1001
+ if (flagsInit && import_ts_morph6.Node.isArrayLiteralExpression(flagsInit)) {
1002
+ if (hasElementWithId(flagsInit, FLAG_ID)) return false;
1003
+ flagsInit.addElement(initializer);
1004
+ return true;
1005
+ }
1006
+ return false;
1007
+ }
1008
+ configArg.addPropertyAssignment({
1009
+ name: FLAGS_PROPERTY_NAME3,
1010
+ initializer: `[
1011
+ ${initializer}
1012
+ ]`
1013
+ });
1014
+ return true;
1015
+ }
1016
+ function ensureActionOperationFlag(action, operation) {
1017
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME3);
1018
+ const entry = `{ id: '${FLAG_ID}', operation: '${operation}' }`;
1019
+ if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
1020
+ const flagsInit = flagsProp.getInitializer();
1021
+ if (flagsInit && import_ts_morph6.Node.isArrayLiteralExpression(flagsInit)) {
1022
+ if (hasElementWithId(flagsInit, FLAG_ID)) return false;
1023
+ flagsInit.addElement(entry);
1024
+ return true;
1025
+ }
1026
+ return false;
1027
+ }
1028
+ action.addPropertyAssignment({
1029
+ name: FLAGS_PROPERTY_NAME3,
1030
+ initializer: `[${entry}]`
1031
+ });
1032
+ return true;
1033
+ }
1034
+ function processConfig(configArg, eventType, relPath) {
1035
+ let changes = 0;
1036
+ if (ensureTopLevelFlagDefinition(configArg, eventType)) {
1037
+ changes++;
1038
+ console.log(
1039
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' to top-level flags`
1040
+ );
1041
+ }
1042
+ const actionsProp = configArg.getProperty(ACTIONS_PROPERTY_NAME4);
1043
+ if (!actionsProp || !import_ts_morph6.Node.isPropertyAssignment(actionsProp)) return changes;
1044
+ const actionsInit = actionsProp.getInitializer();
1045
+ if (!actionsInit || !import_ts_morph6.Node.isArrayLiteralExpression(actionsInit)) {
1046
+ return changes;
1047
+ }
1048
+ for (const element of actionsInit.getElements()) {
1049
+ if (!import_ts_morph6.Node.isObjectLiteralExpression(element)) continue;
1050
+ if (isActionOfType(element, REGISTER_TYPE)) {
1051
+ if (ensureActionOperationFlag(element, "add")) {
1052
+ changes++;
1053
+ console.log(
1054
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' add-flag to REGISTER action`
1055
+ );
1056
+ }
1057
+ }
1058
+ if (isActionOfType(element, PRINT_CERTIFICATE_TYPE)) {
1059
+ if (ensureActionOperationFlag(element, "remove")) {
1060
+ changes++;
1061
+ console.log(
1062
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' remove-flag to PRINT_CERTIFICATE action`
1063
+ );
1064
+ }
1065
+ }
1066
+ }
1067
+ return changes;
1068
+ }
1069
+ function hasPrintCertificateAction(workqueue) {
1070
+ const actionsProp = workqueue.getProperty(ACTIONS_PROPERTY_NAME4);
1071
+ if (actionsProp && import_ts_morph6.Node.isPropertyAssignment(actionsProp)) {
1072
+ const actionsInit = actionsProp.getInitializer();
1073
+ if (actionsInit && import_ts_morph6.Node.isArrayLiteralExpression(actionsInit)) {
1074
+ for (const el of actionsInit.getElements()) {
1075
+ if (import_ts_morph6.Node.isObjectLiteralExpression(el) && isActionOfType(el, PRINT_CERTIFICATE_TYPE)) {
1076
+ return true;
1077
+ }
1078
+ }
1079
+ }
1080
+ }
1081
+ const actionProp = workqueue.getProperty(ACTION_PROPERTY_NAME);
1082
+ if (actionProp && import_ts_morph6.Node.isPropertyAssignment(actionProp)) {
1083
+ const actionInit = actionProp.getInitializer();
1084
+ if (actionInit && import_ts_morph6.Node.isObjectLiteralExpression(actionInit) && isActionOfType(actionInit, PRINT_CERTIFICATE_TYPE)) {
1085
+ return true;
1086
+ }
1087
+ }
1088
+ return false;
1089
+ }
1090
+ function addFlagToQueryClause(clause) {
1091
+ const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME3);
1092
+ if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
1093
+ const flagsInit = flagsProp.getInitializer();
1094
+ if (flagsInit && import_ts_morph6.Node.isObjectLiteralExpression(flagsInit)) {
1095
+ const anyOfProp = flagsInit.getProperty(ANY_OF_PROPERTY_NAME2);
1096
+ if (anyOfProp && import_ts_morph6.Node.isPropertyAssignment(anyOfProp)) {
1097
+ const anyOfInit = anyOfProp.getInitializer();
1098
+ if (anyOfInit && import_ts_morph6.Node.isArrayLiteralExpression(anyOfInit)) {
1099
+ const alreadyPresent = anyOfInit.getElements().some(
1100
+ (el) => import_ts_morph6.Node.isStringLiteral(el) && el.getLiteralValue() === FLAG_ID
1101
+ );
1102
+ if (alreadyPresent) return false;
1103
+ anyOfInit.addElement(`'${FLAG_ID}'`);
1104
+ return true;
1105
+ }
1106
+ } else {
1107
+ flagsInit.addPropertyAssignment({
1108
+ name: ANY_OF_PROPERTY_NAME2,
1109
+ initializer: `['${FLAG_ID}']`
1110
+ });
1111
+ return true;
1112
+ }
1113
+ }
1114
+ } else {
1115
+ clause.addPropertyAssignment({
1116
+ name: FLAGS_PROPERTY_NAME3,
1117
+ initializer: `{ ${ANY_OF_PROPERTY_NAME2}: ['${FLAG_ID}'] }`
1118
+ });
1119
+ return true;
1120
+ }
1121
+ return false;
1122
+ }
1123
+ function walkQueryForFlagAddition(queryObj) {
1124
+ const typeProp = queryObj.getProperty(TYPE_PROPERTY_NAME6);
1125
+ if (typeProp && import_ts_morph6.Node.isPropertyAssignment(typeProp)) {
1126
+ const typeInit = typeProp.getInitializer();
1127
+ if (typeInit && import_ts_morph6.Node.isStringLiteral(typeInit) && (typeInit.getLiteralValue() === "or" || typeInit.getLiteralValue() === "and")) {
1128
+ const clausesProp = queryObj.getProperty(CLAUSES_PROPERTY_NAME2);
1129
+ if (!clausesProp || !import_ts_morph6.Node.isPropertyAssignment(clausesProp)) return 0;
1130
+ const clausesInit = clausesProp.getInitializer();
1131
+ if (!clausesInit || !import_ts_morph6.Node.isArrayLiteralExpression(clausesInit)) return 0;
1132
+ let changed = 0;
1133
+ for (const clause of clausesInit.getElements()) {
1134
+ if (import_ts_morph6.Node.isObjectLiteralExpression(clause)) {
1135
+ changed += walkQueryForFlagAddition(clause);
1136
+ }
1137
+ }
1138
+ return changed;
1139
+ }
1140
+ }
1141
+ return addFlagToQueryClause(queryObj) ? 1 : 0;
1142
+ }
1143
+ function processFile6(filePath, project) {
1144
+ const sourceFile = project.getSourceFile(filePath);
1145
+ if (!sourceFile) return 0;
1146
+ let totalChanges = 0;
1147
+ const relPath = import_path6.default.relative(process.cwd(), filePath);
1148
+ const callExpressions = sourceFile.getDescendantsOfKind(
1149
+ import_ts_morph6.SyntaxKind.CallExpression
1150
+ );
1151
+ for (const call of callExpressions) {
1152
+ const expression = call.getExpression();
1153
+ if (!import_ts_morph6.Node.isIdentifier(expression)) continue;
1154
+ const calleeName = expression.getText();
1155
+ if (calleeName === DEFINE_CONFIG_NAME4) {
1156
+ const args = call.getArguments();
1157
+ if (args.length === 0) continue;
1158
+ const configArg = args[0];
1159
+ if (!import_ts_morph6.Node.isObjectLiteralExpression(configArg)) continue;
1160
+ const eventType = getEventType(configArg);
1161
+ if (!eventType) continue;
1162
+ totalChanges += processConfig(configArg, eventType, relPath);
1163
+ }
1164
+ if (calleeName === DEFINE_WORKQUEUES_NAME2) {
1165
+ const args = call.getArguments();
1166
+ if (args.length === 0) continue;
1167
+ const workqueuesArg = args[0];
1168
+ if (!import_ts_morph6.Node.isArrayLiteralExpression(workqueuesArg)) continue;
1169
+ for (const workqueueEl of workqueuesArg.getElements()) {
1170
+ if (!import_ts_morph6.Node.isObjectLiteralExpression(workqueueEl)) continue;
1171
+ if (!hasPrintCertificateAction(workqueueEl)) continue;
1172
+ const queryProp = workqueueEl.getProperty(QUERY_PROPERTY_NAME2);
1173
+ if (!queryProp || !import_ts_morph6.Node.isPropertyAssignment(queryProp)) continue;
1174
+ const queryInit = queryProp.getInitializer();
1175
+ if (!queryInit || !import_ts_morph6.Node.isObjectLiteralExpression(queryInit)) continue;
1176
+ const changed = walkQueryForFlagAddition(queryInit);
1177
+ if (changed > 0) {
1178
+ totalChanges += changed;
1179
+ console.log(
1180
+ ` [${relPath}] Added '${FLAG_ID}' to flags.anyOf in ${changed} PRINT_CERTIFICATE workqueue clause(s)`
1181
+ );
1182
+ }
1183
+ }
1184
+ }
1185
+ }
1186
+ return totalChanges;
1187
+ }
1188
+ async function main6() {
1189
+ const srcDir = import_path6.default.join(process.cwd(), "src");
1190
+ console.log(
1191
+ `Scanning for defineConfig and PRINT_CERTIFICATE workqueues in: ${srcDir}
1192
+ `
1193
+ );
1194
+ const project = new import_ts_morph6.Project({
1195
+ tsConfigFilePath: import_path6.default.resolve(srcDir, "../tsconfig.json"),
1196
+ skipAddingFilesFromTsConfig: false
1197
+ });
1198
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
1199
+ const fp = sf.getFilePath();
1200
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
1201
+ });
1202
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
1203
+ `);
1204
+ let totalChanges = 0;
1205
+ const modifiedFiles = [];
1206
+ for (const sourceFile of sourceFiles) {
1207
+ const filePath = sourceFile.getFilePath();
1208
+ const changes = processFile6(filePath, project);
1209
+ if (changes > 0) {
1210
+ totalChanges += changes;
1211
+ modifiedFiles.push(filePath);
1212
+ }
1213
+ }
1214
+ if (modifiedFiles.length === 0) {
1215
+ console.log(
1216
+ "No event configs or PRINT_CERTIFICATE workqueues found. Nothing to do."
1217
+ );
1218
+ return;
1219
+ }
1220
+ console.log(`
1221
+ Saving ${modifiedFiles.length} modified file(s)...`);
1222
+ for (const filePath of modifiedFiles) {
1223
+ const sourceFile = project.getSourceFileOrThrow(filePath);
1224
+ await sourceFile.save();
1225
+ console.log(` Saved: ${import_path6.default.relative(process.cwd(), filePath)}`);
1226
+ }
1227
+ console.log(
1228
+ `
1229
+ Done. Applied ${totalChanges} change(s) across ${modifiedFiles.length} file(s).`
1230
+ );
1231
+ }
1232
+
1233
+ // src/migrations/v2.0/remove-pending-certification-flag.ts
1234
+ var import_ts_morph7 = require("ts-morph");
1235
+ var import_path7 = __toESM(require("path"));
1236
+ var INHERENT_FLAGS_ENUM_NAME = "InherentFlags";
1237
+ var PENDING_CERTIFICATION_MEMBER = "PENDING_CERTIFICATION";
1238
+ function isPendingCertificationFlag(node) {
1239
+ if (!import_ts_morph7.Node.isPropertyAccessExpression(node)) return false;
1240
+ const obj = node.getExpression();
1241
+ const member = node.getName();
1242
+ return import_ts_morph7.Node.isIdentifier(obj) && obj.getText() === INHERENT_FLAGS_ENUM_NAME && member === PENDING_CERTIFICATION_MEMBER;
1243
+ }
1244
+ function processFile7(filePath, project) {
1245
+ const sourceFile = project.getSourceFile(filePath);
1246
+ if (!sourceFile) return 0;
1247
+ let removedCount = 0;
1248
+ const arrayLiterals = sourceFile.getDescendantsOfKind(
1249
+ import_ts_morph7.SyntaxKind.ArrayLiteralExpression
1250
+ );
1251
+ for (const array3 of arrayLiterals) {
1252
+ const indicesToRemove = [];
1253
+ array3.getElements().forEach((element, index) => {
1254
+ if (isPendingCertificationFlag(element)) {
1255
+ indicesToRemove.push(index);
1256
+ }
1257
+ });
1258
+ for (const index of indicesToRemove.reverse()) {
1259
+ array3.removeElement(index);
1260
+ removedCount++;
1261
+ console.log(
1262
+ ` [${import_path7.default.relative(process.cwd(), filePath)}] Removed InherentFlags.PENDING_CERTIFICATION from array`
1263
+ );
1264
+ }
1265
+ }
1266
+ return removedCount;
1267
+ }
1268
+ async function main7() {
1269
+ const srcDir = import_path7.default.join(process.cwd(), "src");
1270
+ console.log(
1271
+ `Scanning for InherentFlags.PENDING_CERTIFICATION array elements in: ${srcDir}
1272
+ `
1273
+ );
1274
+ const project = new import_ts_morph7.Project({
1275
+ tsConfigFilePath: import_path7.default.resolve(srcDir, "../tsconfig.json"),
1276
+ skipAddingFilesFromTsConfig: false
1277
+ });
1278
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
1279
+ const fp = sf.getFilePath();
1280
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
1281
+ });
1282
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
1283
+ `);
1284
+ let totalRemoved = 0;
1285
+ const modifiedFiles = [];
1286
+ for (const sourceFile of sourceFiles) {
1287
+ const filePath = sourceFile.getFilePath();
1288
+ const removed = processFile7(filePath, project);
1289
+ if (removed > 0) {
1290
+ totalRemoved += removed;
1291
+ modifiedFiles.push(filePath);
1292
+ }
1293
+ }
1294
+ if (modifiedFiles.length === 0) {
1295
+ console.log(
1296
+ "No InherentFlags.PENDING_CERTIFICATION elements found in any array. Nothing to do."
1297
+ );
1298
+ return;
1299
+ }
1300
+ console.log(`
1301
+ Saving ${modifiedFiles.length} modified file(s)...`);
1302
+ for (const filePath of modifiedFiles) {
1303
+ const sourceFile = project.getSourceFileOrThrow(filePath);
1304
+ await sourceFile.save();
1305
+ console.log(` Saved: ${import_path7.default.relative(process.cwd(), filePath)}`);
1306
+ }
1307
+ console.log(
1308
+ `
1309
+ Done. Removed ${totalRemoved} InherentFlags.PENDING_CERTIFICATION element(s) from array(s).`
1310
+ );
1311
+ }
1312
+
1313
+ // src/migrations/v2.0/rename-location-parent-id.ts
1314
+ var import_ts_morph8 = require("ts-morph");
1315
+ var import_path8 = __toESM(require("path"));
1316
+ var OLD_PROPERTY_NAME = "parentId";
1317
+ var NEW_PROPERTY_NAME = "administrativeAreaId";
1318
+ var LOCATION_TYPE_NAME = "Location";
1319
+ var LOCATION_STRUCTURAL_PROPS = [
1320
+ "id",
1321
+ "name",
1322
+ "externalId",
1323
+ "locationType"
1324
+ ];
1325
+ var LOCATION_AREA_ID_PROPS = ["administrativeAreaId", "parentId"];
1326
+ function isSingleLocationType(t) {
1327
+ if (t.getAliasSymbol()?.getName() === LOCATION_TYPE_NAME) return true;
1328
+ if (t.getSymbol()?.getName() === LOCATION_TYPE_NAME) return true;
1329
+ if (t.isObject()) {
1330
+ const propNames = new Set(t.getProperties().map((p) => p.getName()));
1331
+ const hasCorePropNames = LOCATION_STRUCTURAL_PROPS.every(
1332
+ (p) => propNames.has(p)
1333
+ );
1334
+ const hasAreaIdProp = LOCATION_AREA_ID_PROPS.some((p) => propNames.has(p));
1335
+ if (hasCorePropNames && hasAreaIdProp) return true;
1336
+ }
1337
+ return false;
1338
+ }
1339
+ function isLocationType(node) {
1340
+ let type;
1341
+ try {
1342
+ type = node.getType();
1343
+ } catch {
1344
+ return false;
1345
+ }
1346
+ if (isSingleLocationType(type)) return true;
1347
+ for (const constituent of type.getUnionTypes()) {
1348
+ if (isSingleLocationType(constituent)) return true;
1349
+ }
1350
+ return false;
1351
+ }
1352
+ function processFile8(filePath, project) {
1353
+ const sourceFile = project.getSourceFile(filePath);
1354
+ if (!sourceFile) return 0;
1355
+ let renamedCount = 0;
1356
+ const candidates = sourceFile.getDescendantsOfKind(import_ts_morph8.SyntaxKind.PropertyAccessExpression).filter((propAccess) => propAccess.getName() === OLD_PROPERTY_NAME);
1357
+ for (const propAccess of candidates) {
1358
+ const obj = propAccess.getExpression();
1359
+ if (!isLocationType(obj)) continue;
1360
+ propAccess.getNameNode().replaceWithText(NEW_PROPERTY_NAME);
1361
+ renamedCount++;
1362
+ console.log(
1363
+ ` [${import_path8.default.relative(process.cwd(), filePath)}] Renamed Location.${OLD_PROPERTY_NAME} \u2192 Location.${NEW_PROPERTY_NAME}`
1364
+ );
1365
+ }
1366
+ return renamedCount;
1367
+ }
1368
+ async function main8() {
1369
+ const srcDir = import_path8.default.join(process.cwd(), "src");
1370
+ console.log(
1371
+ `Scanning for Location.${OLD_PROPERTY_NAME} references in: ${srcDir}
1372
+ `
1373
+ );
1374
+ const project = new import_ts_morph8.Project({
1375
+ tsConfigFilePath: import_path8.default.resolve(srcDir, "../tsconfig.json"),
1376
+ skipAddingFilesFromTsConfig: false
1377
+ });
1378
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
1379
+ const fp = sf.getFilePath();
1380
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
1381
+ });
1382
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
1383
+ `);
1384
+ let totalRenamed = 0;
1385
+ const modifiedFiles = [];
1386
+ for (const sourceFile of sourceFiles) {
1387
+ const filePath = sourceFile.getFilePath();
1388
+ const renamed = processFile8(filePath, project);
1389
+ if (renamed > 0) {
1390
+ totalRenamed += renamed;
1391
+ modifiedFiles.push(filePath);
1392
+ }
1393
+ }
1394
+ if (modifiedFiles.length === 0) {
1395
+ console.log(
1396
+ `No Location.${OLD_PROPERTY_NAME} references found. Nothing to do.`
1397
+ );
1398
+ return;
1399
+ }
1400
+ console.log(`
1401
+ Saving ${modifiedFiles.length} modified file(s)...`);
1402
+ for (const filePath of modifiedFiles) {
1403
+ const sourceFile = project.getSourceFileOrThrow(filePath);
1404
+ await sourceFile.save();
1405
+ console.log(` Saved: ${import_path8.default.relative(process.cwd(), filePath)}`);
1406
+ }
1407
+ console.log(
1408
+ `
1409
+ Done. Renamed ${totalRenamed} Location.${OLD_PROPERTY_NAME} reference(s) to Location.${NEW_PROPERTY_NAME}.`
1410
+ );
1411
+ }
1412
+
1413
+ // src/migrations/v2.0/rename-api-paths.ts
1414
+ var import_ts_morph9 = require("ts-morph");
1415
+ var import_path9 = __toESM(require("path"));
1416
+ var PATH_RENAMES = {
1417
+ "/events": "/config/events",
1418
+ "/application-config": "/config/application",
1419
+ "/workqueue": "/config/workqueues",
1420
+ "/locations": "/config/locations",
1421
+ "/users": "/config/users",
1422
+ "/roles": "/config/roles"
1423
+ };
1424
+ var METHOD_PROPERTY_NAME = "method";
1425
+ var PATH_PROPERTY_NAME = "path";
1426
+ var HTTP_VERBS = /* @__PURE__ */ new Set([
1427
+ "GET",
1428
+ "POST",
1429
+ "PUT",
1430
+ "PATCH",
1431
+ "DELETE",
1432
+ "OPTIONS",
1433
+ "HEAD",
1434
+ "*"
1435
+ ]);
1436
+ function isRouteConfig(obj) {
1437
+ const methodProp = obj.getProperty(METHOD_PROPERTY_NAME);
1438
+ if (!methodProp || !import_ts_morph9.Node.isPropertyAssignment(methodProp)) return false;
1439
+ const methodInit = methodProp.getInitializer();
1440
+ if (!methodInit) return false;
1441
+ if (import_ts_morph9.Node.isStringLiteral(methodInit)) {
1442
+ if (!HTTP_VERBS.has(methodInit.getLiteralValue().toUpperCase()))
1443
+ return false;
1444
+ } else if (import_ts_morph9.Node.isArrayLiteralExpression(methodInit)) {
1445
+ const allVerbs = methodInit.getElements().every(
1446
+ (el) => import_ts_morph9.Node.isStringLiteral(el) && HTTP_VERBS.has(el.getLiteralValue().toUpperCase())
1447
+ );
1448
+ if (!allVerbs) return false;
1449
+ } else {
1450
+ return false;
1451
+ }
1452
+ const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
1453
+ if (!pathProp || !import_ts_morph9.Node.isPropertyAssignment(pathProp)) return false;
1454
+ const pathInit = pathProp.getInitializer();
1455
+ return !!pathInit && import_ts_morph9.Node.isStringLiteral(pathInit);
1456
+ }
1457
+ function renameRoutePath(obj) {
1458
+ const pathProp = obj.getProperty(PATH_PROPERTY_NAME);
1459
+ if (!pathProp || !import_ts_morph9.Node.isPropertyAssignment(pathProp)) return null;
1460
+ const pathInit = pathProp.getInitializer();
1461
+ if (!pathInit || !import_ts_morph9.Node.isStringLiteral(pathInit)) return null;
1462
+ const oldPath = pathInit.getLiteralValue();
1463
+ const newPath = PATH_RENAMES[oldPath];
1464
+ if (!newPath) return null;
1465
+ pathInit.replaceWithText(`'${newPath}'`);
1466
+ return newPath;
1467
+ }
1468
+ function processFile9(filePath, project) {
1469
+ const sourceFile = project.getSourceFile(filePath);
1470
+ if (!sourceFile) return 0;
1471
+ let renamedCount = 0;
1472
+ const relPath = import_path9.default.relative(process.cwd(), filePath);
1473
+ const candidates = sourceFile.getDescendantsOfKind(
1474
+ import_ts_morph9.SyntaxKind.ObjectLiteralExpression
1475
+ );
1476
+ for (const obj of candidates) {
1477
+ if (!isRouteConfig(obj)) continue;
1478
+ const newPath = renameRoutePath(obj);
1479
+ if (newPath) {
1480
+ renamedCount++;
1481
+ console.log(` [${relPath}] Renamed route path \u2192 '${newPath}'`);
1482
+ }
1483
+ }
1484
+ return renamedCount;
1485
+ }
1486
+ async function main9() {
1487
+ const srcDir = import_path9.default.join(process.cwd(), "src");
1488
+ console.log(`Scanning for Hapi route configs in: ${srcDir}
1489
+ `);
1490
+ console.log("Active path renames:");
1491
+ for (const [from, to] of Object.entries(PATH_RENAMES)) {
1492
+ console.log(` '${from}' \u2192 '${to}'`);
1493
+ }
1494
+ console.log();
1495
+ const project = new import_ts_morph9.Project({
1496
+ tsConfigFilePath: import_path9.default.resolve(srcDir, "../tsconfig.json"),
1497
+ skipAddingFilesFromTsConfig: false
1498
+ });
1499
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
1500
+ const fp = sf.getFilePath();
1501
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
1502
+ });
1503
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
1504
+ `);
1505
+ let totalRenamed = 0;
1506
+ const modifiedFiles = [];
1507
+ for (const sourceFile of sourceFiles) {
1508
+ const filePath = sourceFile.getFilePath();
1509
+ const renamed = processFile9(filePath, project);
1510
+ if (renamed > 0) {
1511
+ totalRenamed += renamed;
1512
+ modifiedFiles.push(filePath);
1513
+ }
1514
+ }
1515
+ if (modifiedFiles.length === 0) {
1516
+ console.log("No matching route paths found. Nothing to do.");
1517
+ return;
1518
+ }
1519
+ console.log(`
1520
+ Saving ${modifiedFiles.length} modified file(s)...`);
1521
+ for (const filePath of modifiedFiles) {
1522
+ const sourceFile = project.getSourceFileOrThrow(filePath);
1523
+ await sourceFile.save();
1524
+ console.log(` Saved: ${import_path9.default.relative(process.cwd(), filePath)}`);
1525
+ }
1526
+ console.log(`
1527
+ Done. Renamed ${totalRenamed} route path(s).`);
1528
+ }
1529
+
1530
+ // src/migrations/v2.0/convert-config-files-to-ts.ts
1531
+ var fs = __toESM(require("fs"));
1532
+ var import_ts_morph10 = require("ts-morph");
1533
+ var import_path10 = __toESM(require("path"));
1534
+ var CLIENT_VALID_KEYS = /* @__PURE__ */ new Set([
1535
+ "COUNTRY",
1536
+ "LANGUAGES",
1537
+ "SENTRY",
1538
+ "REGISTER_BACKGROUND",
1539
+ "DASHBOARDS",
1540
+ "FEATURES"
1541
+ ]);
1542
+ var LOGIN_VALID_KEYS = /* @__PURE__ */ new Set([
1543
+ "COUNTRY",
1544
+ "LANGUAGES",
1545
+ "USER_NOTIFICATION_DELIVERY_METHOD",
1546
+ "INFORMANT_NOTIFICATION_DELIVERY_METHOD",
1547
+ "PHONE_NUMBER_PATTERN",
1548
+ "LOGIN_BACKGROUND",
1549
+ "SENTRY"
1550
+ ]);
1551
+ var APPLICATION_CONFIG_VALID_KEYS = /* @__PURE__ */ new Set([
1552
+ "APPLICATION_NAME",
1553
+ "COUNTRY_LOGO",
1554
+ "SYSTEM_IANA_TIMEZONE",
1555
+ "CURRENCY",
1556
+ "ADMIN_STRUCTURE",
1557
+ "PHONE_NUMBER_PATTERN",
1558
+ "USER_NOTIFICATION_DELIVERY_METHOD",
1559
+ "INFORMANT_NOTIFICATION_DELIVERY_METHOD",
1560
+ "SEARCH_DEFAULT_CRITERIA"
1561
+ ]);
1562
+ var CONFIG_GROUPS = [
1563
+ {
1564
+ baseName: "client-config",
1565
+ prodName: "client-config.prod",
1566
+ defineFn: "defineClientConfig",
1567
+ importFrom: "@opencrvs/toolkit/application-config",
1568
+ validKeys: CLIENT_VALID_KEYS,
1569
+ requiredPlaceholders: {
1570
+ // BackgroundConfig requires backgroundColor or backgroundImage
1571
+ REGISTER_BACKGROUND: "{ backgroundColor: '#F4F4F7' }"
1572
+ },
1573
+ exportNames: {
1574
+ "client-config": "clientConfig",
1575
+ "client-config.prod": "clientConfigProd"
1576
+ },
1577
+ routePath: "/client-config.js"
1578
+ },
1579
+ {
1580
+ baseName: "login-config",
1581
+ prodName: "login-config.prod",
1582
+ defineFn: "defineLoginConfig",
1583
+ importFrom: "@opencrvs/toolkit/application-config",
1584
+ validKeys: LOGIN_VALID_KEYS,
1585
+ requiredPlaceholders: {},
1586
+ // These keys are always sourced from applicationConfig rather than
1587
+ // copied from the old JS file or filled with a placeholder value.
1588
+ // LOGIN_BACKGROUND lives in applicationConfig and is not part of the
1589
+ // ApplicationConfig schema, so Phase 3 will inline its value and remove
1590
+ // it from applicationConfig automatically.
1591
+ applicationConfigKeys: [
1592
+ "LOGIN_BACKGROUND",
1593
+ "USER_NOTIFICATION_DELIVERY_METHOD",
1594
+ "INFORMANT_NOTIFICATION_DELIVERY_METHOD",
1595
+ "PHONE_NUMBER_PATTERN"
1596
+ ],
1597
+ applicationConfigImportPath: "./api/application/application-config",
1598
+ exportNames: {
1599
+ "login-config": "loginConfig",
1600
+ "login-config.prod": "loginConfigProd"
1601
+ },
1602
+ routePath: "/login-config.js"
1603
+ }
1604
+ ];
1605
+ var HTTP_VERBS2 = /* @__PURE__ */ new Set([
1606
+ "GET",
1607
+ "POST",
1608
+ "PUT",
1609
+ "PATCH",
1610
+ "DELETE",
1611
+ "OPTIONS",
1612
+ "HEAD",
1613
+ "*"
1614
+ ]);
1615
+ function extractWindowConfig(jsFilePath) {
1616
+ const jsProject = new import_ts_morph10.Project({
1617
+ compilerOptions: { allowJs: true, checkJs: false }
1618
+ // addFilesFromTsConfig: false
1619
+ });
1620
+ let sourceFile;
1621
+ try {
1622
+ sourceFile = jsProject.addSourceFileAtPath(jsFilePath);
1623
+ } catch {
1624
+ console.warn(` Could not parse ${jsFilePath}`);
1625
+ return null;
1626
+ }
1627
+ for (const binary of sourceFile.getDescendantsOfKind(
1628
+ import_ts_morph10.SyntaxKind.BinaryExpression
1629
+ )) {
1630
+ if (binary.getOperatorToken().getKind() !== import_ts_morph10.SyntaxKind.EqualsToken) continue;
1631
+ const left = binary.getLeft();
1632
+ if (!import_ts_morph10.Node.isPropertyAccessExpression(left)) continue;
1633
+ if (left.getExpression().getText() !== "window") continue;
1634
+ if (left.getName() !== "config") continue;
1635
+ const right = binary.getRight();
1636
+ if (import_ts_morph10.Node.isObjectLiteralExpression(right)) return right;
1637
+ }
1638
+ return null;
1639
+ }
1640
+ function convertLanguages(init) {
1641
+ if (import_ts_morph10.Node.isStringLiteral(init)) {
1642
+ const langs = init.getLiteralValue().split(",").map((l) => `'${l.trim()}'`).join(", ");
1643
+ return `[${langs}]`;
1644
+ }
1645
+ return init.getText();
1646
+ }
1647
+ function extractStaticUrlString(init) {
1648
+ if (import_ts_morph10.Node.isStringLiteral(init)) {
1649
+ return init.getLiteralValue();
1650
+ }
1651
+ if (init.getKind() === import_ts_morph10.SyntaxKind.NoSubstitutionTemplateLiteral) {
1652
+ const raw = init.getText();
1653
+ return raw.slice(1, -1);
1654
+ }
1655
+ return null;
1656
+ }
1657
+ function transformDashboardUrl(init, isProd) {
1658
+ if (!isProd) return init.getText();
1659
+ const urlString = extractStaticUrlString(init);
1660
+ if (!urlString) return init.getText();
1661
+ try {
1662
+ const parsed = new URL(urlString);
1663
+ const rest = parsed.pathname + parsed.search + parsed.hash;
1664
+ return `\`\${scheme}//metabase.\${hostname}${rest}\``;
1665
+ } catch {
1666
+ return init.getText();
1667
+ }
1668
+ }
1669
+ function transformDashboardsValue(init, isProd) {
1670
+ if (!isProd || !import_ts_morph10.Node.isArrayLiteralExpression(init)) {
1671
+ return init.getText();
1672
+ }
1673
+ const elementParts = [];
1674
+ for (const el of init.getElements()) {
1675
+ if (!import_ts_morph10.Node.isObjectLiteralExpression(el)) {
1676
+ elementParts.push(el.getText());
1677
+ continue;
1678
+ }
1679
+ const propParts = [];
1680
+ for (const prop of el.getProperties()) {
1681
+ if (!import_ts_morph10.Node.isPropertyAssignment(prop)) {
1682
+ propParts.push(prop.getText());
1683
+ continue;
1684
+ }
1685
+ const propName = prop.getName();
1686
+ const propInit = prop.getInitializer();
1687
+ if (!propInit) {
1688
+ propParts.push(prop.getText());
1689
+ continue;
1690
+ }
1691
+ if (propName === "url") {
1692
+ propParts.push(`url: ${transformDashboardUrl(propInit, isProd)}`);
1693
+ } else {
1694
+ propParts.push(`${propName}: ${propInit.getText()}`);
1695
+ }
1696
+ }
1697
+ elementParts.push(
1698
+ ` {
1699
+ ${propParts.map((p) => ` ${p}`).join(",\n")}
1700
+ }`
1701
+ );
1702
+ }
1703
+ return `[
1704
+ ${elementParts.join(",\n")}
1705
+ ]`;
1706
+ }
1707
+ function generateTsContent(configObj, exportName, group, isProd) {
1708
+ const propertyLines = [];
1709
+ const seenKeys = /* @__PURE__ */ new Set();
1710
+ const appConfigKeySet = new Set(group.applicationConfigKeys ?? []);
1711
+ for (const prop of configObj.getProperties()) {
1712
+ if (!import_ts_morph10.Node.isPropertyAssignment(prop)) continue;
1713
+ const name = prop.getName();
1714
+ if (!group.validKeys.has(name)) continue;
1715
+ if (appConfigKeySet.has(name)) continue;
1716
+ seenKeys.add(name);
1717
+ const init = prop.getInitializer();
1718
+ if (!init) continue;
1719
+ if (name === "LANGUAGES") {
1720
+ propertyLines.push(` LANGUAGES: ${convertLanguages(init)}`);
1721
+ } else if (name === "SENTRY" && isProd) {
1722
+ propertyLines.push(` SENTRY: sentry`);
1723
+ } else if (name === "DASHBOARDS") {
1724
+ propertyLines.push(
1725
+ ` DASHBOARDS: ${transformDashboardsValue(init, isProd)}`
1726
+ );
1727
+ } else {
1728
+ propertyLines.push(` ${name}: ${init.getText()}`);
1729
+ }
1730
+ }
1731
+ for (const [key, placeholder] of Object.entries(group.requiredPlaceholders)) {
1732
+ if (!seenKeys.has(key)) {
1733
+ propertyLines.push(
1734
+ ` // TODO: configure ${key} \u2014 replace this placeholder`,
1735
+ ` ${key}: ${placeholder}`
1736
+ );
1737
+ }
1738
+ }
1739
+ for (const key of appConfigKeySet) {
1740
+ propertyLines.push(` ${key}: applicationConfig.${key}`);
1741
+ }
1742
+ const body = propertyLines.join(",\n");
1743
+ const headerLines = [];
1744
+ headerLines.push(`import * as fs from 'fs'`);
1745
+ headerLines.push(`import { join } from 'path'`);
1746
+ if (isProd) {
1747
+ headerLines.push(`import { env } from './environment'`);
1748
+ }
1749
+ headerLines.push(`import { ${group.defineFn} } from '${group.importFrom}'`);
1750
+ if (group.applicationConfigImportPath) {
1751
+ headerLines.push(
1752
+ `import { applicationConfig } from '${group.applicationConfigImportPath}'`
1753
+ );
1754
+ }
1755
+ headerLines.push("");
1756
+ if (isProd) {
1757
+ headerLines.push(`const scheme = 'https'`);
1758
+ headerLines.push(`const hostname = env.DOMAIN`);
1759
+ headerLines.push(`const sentry = env.SENTRY_DSN`);
1760
+ } else {
1761
+ headerLines.push(`const scheme = 'http'`);
1762
+ headerLines.push(`const hostname = 'localhost'`);
1763
+ }
1764
+ return [
1765
+ ...headerLines,
1766
+ "",
1767
+ `export const ${exportName} = ${group.defineFn}({`,
1768
+ body,
1769
+ "})",
1770
+ ""
1771
+ ].join("\n");
1772
+ }
1773
+ function convertFile(name, group, srcDir) {
1774
+ const jsFilePath = import_path10.default.join(srcDir, `${name}.js`);
1775
+ const tsFilePath = import_path10.default.join(srcDir, `${name}.ts`);
1776
+ if (!fs.existsSync(jsFilePath)) {
1777
+ console.log(` Skipping ${name}.js \u2014 file not found`);
1778
+ return false;
1779
+ }
1780
+ if (fs.existsSync(tsFilePath)) {
1781
+ console.log(` Skipping ${name}.js \u2014 ${name}.ts already exists`);
1782
+ return false;
1783
+ }
1784
+ const configObj = extractWindowConfig(jsFilePath);
1785
+ if (!configObj) {
1786
+ console.warn(
1787
+ ` [${name}.js] Could not locate window.config assignment \u2014 skipping`
1788
+ );
1789
+ return false;
1790
+ }
1791
+ const isProd = name.endsWith(".prod");
1792
+ const exportName = group.exportNames[name];
1793
+ const content = generateTsContent(configObj, exportName, group, isProd);
1794
+ fs.writeFileSync(tsFilePath, content, "utf8");
1795
+ fs.unlinkSync(jsFilePath);
1796
+ console.log(` Converted ${name}.js \u2192 ${name}.ts (export: ${exportName})`);
1797
+ return true;
1798
+ }
1799
+ function isRouteConfig2(obj) {
1800
+ const methodProp = obj.getProperty("method");
1801
+ if (!methodProp || !import_ts_morph10.Node.isPropertyAssignment(methodProp)) return false;
1802
+ const methodInit = methodProp.getInitializer();
1803
+ if (!methodInit) return false;
1804
+ if (import_ts_morph10.Node.isStringLiteral(methodInit)) {
1805
+ if (!HTTP_VERBS2.has(methodInit.getLiteralValue().toUpperCase()))
1806
+ return false;
1807
+ } else if (import_ts_morph10.Node.isArrayLiteralExpression(methodInit)) {
1808
+ const allVerbs = methodInit.getElements().every(
1809
+ (el) => import_ts_morph10.Node.isStringLiteral(el) && HTTP_VERBS2.has(el.getLiteralValue().toUpperCase())
1810
+ );
1811
+ if (!allVerbs) return false;
1812
+ } else {
1813
+ return false;
1814
+ }
1815
+ const pathProp = obj.getProperty("path");
1816
+ if (!pathProp || !import_ts_morph10.Node.isPropertyAssignment(pathProp)) return false;
1817
+ const pathInit = pathProp.getInitializer();
1818
+ return !!pathInit && import_ts_morph10.Node.isStringLiteral(pathInit);
1819
+ }
1820
+ function getRoutePath(obj) {
1821
+ const pathProp = obj.getProperty("path");
1822
+ if (!pathProp || !import_ts_morph10.Node.isPropertyAssignment(pathProp)) return null;
1823
+ const pathInit = pathProp.getInitializer();
1824
+ if (!pathInit || !import_ts_morph10.Node.isStringLiteral(pathInit)) return null;
1825
+ return pathInit.getLiteralValue();
1826
+ }
1827
+ function findHandlerProperty(routeObj) {
1828
+ const directHandler = routeObj.getProperty("handler");
1829
+ if (directHandler && import_ts_morph10.Node.isPropertyAssignment(directHandler)) {
1830
+ return directHandler;
1831
+ }
1832
+ const optionsProp = routeObj.getProperty("options");
1833
+ if (optionsProp && import_ts_morph10.Node.isPropertyAssignment(optionsProp)) {
1834
+ const optionsInit = optionsProp.getInitializer();
1835
+ if (optionsInit && import_ts_morph10.Node.isObjectLiteralExpression(optionsInit)) {
1836
+ const nestedHandler = optionsInit.getProperty("handler");
1837
+ if (nestedHandler && import_ts_morph10.Node.isPropertyAssignment(nestedHandler)) {
1838
+ return nestedHandler;
1839
+ }
1840
+ }
1841
+ }
1842
+ return null;
1843
+ }
1844
+ function ensureConfigImports(sourceFile, group, srcDir) {
1845
+ const routeFileDir = import_path10.default.dirname(sourceFile.getFilePath());
1846
+ for (const name of [group.baseName, group.prodName]) {
1847
+ const exportName = group.exportNames[name];
1848
+ const absoluteConfigPath = import_path10.default.join(srcDir, name);
1849
+ const rel = import_path10.default.relative(routeFileDir, absoluteConfigPath).replace(/\\/g, "/");
1850
+ const moduleSpecifier = rel.startsWith(".") ? rel : `./${rel}`;
1851
+ const alreadyImported = sourceFile.getImportDeclarations().some(
1852
+ (d) => d.getModuleSpecifierValue() === moduleSpecifier || d.getNamedImports().some((ni) => ni.getName() === exportName)
1853
+ );
1854
+ if (!alreadyImported) {
1855
+ sourceFile.addImportDeclaration({
1856
+ moduleSpecifier,
1857
+ namedImports: [exportName]
1858
+ });
1859
+ }
1860
+ }
1861
+ }
1862
+ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1863
+ const baseExport = group.exportNames[group.baseName];
1864
+ const prodExport = group.exportNames[group.prodName];
1865
+ const newHandlerText = `async (request, h) => {
1866
+ const config =
1867
+ process.env.NODE_ENV === 'production' ? ${prodExport} : ${baseExport}
1868
+ return h
1869
+ .response(\`window.config = \${JSON.stringify(config)}\`)
1870
+ .type('application/javascript')
1871
+ }`;
1872
+ let replacedCount = 0;
1873
+ for (const sourceFile of sourceFiles) {
1874
+ const filePath = sourceFile.getFilePath();
1875
+ const candidates = sourceFile.getDescendantsOfKind(
1876
+ import_ts_morph10.SyntaxKind.ObjectLiteralExpression
1877
+ );
1878
+ for (const obj of candidates) {
1879
+ if (!isRouteConfig2(obj)) continue;
1880
+ if (getRoutePath(obj) !== group.routePath) continue;
1881
+ const handlerProp = findHandlerProperty(obj);
1882
+ if (!handlerProp) {
1883
+ console.warn(
1884
+ ` [${relCwd(filePath)}] Found route '${group.routePath}' but could not locate handler property \u2014 skipping`
1885
+ );
1886
+ continue;
1887
+ }
1888
+ handlerProp.setInitializer(newHandlerText);
1889
+ ensureConfigImports(sourceFile, group, srcDir);
1890
+ replacedCount++;
1891
+ console.log(
1892
+ ` [${relCwd(filePath)}] Replaced handler for route '${group.routePath}'`
1893
+ );
1894
+ }
1895
+ }
1896
+ return replacedCount;
1897
+ }
1898
+ function resolveConfigChain(configObj, path23) {
1899
+ let current = configObj;
1900
+ for (const key of path23) {
1901
+ if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1902
+ const prop = current.getProperty(key);
1903
+ if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
1904
+ const initNode = prop.getInitializer();
1905
+ if (!initNode) return null;
1906
+ current = initNode;
1907
+ }
1908
+ return current.getText();
1909
+ }
1910
+ function rewriteDirnameRefs(text, relDir) {
1911
+ if (!relDir || relDir === ".") return text;
1912
+ const relForward = relDir.replace(/\\/g, "/");
1913
+ return text.replace(
1914
+ /\b((?:path\.)?(?:join|resolve))\s*\(\s*__dirname\s*,/g,
1915
+ `$1(__dirname, '${relForward}',`
1916
+ );
1917
+ }
1918
+ function ensureFsImport(sf) {
1919
+ const hasFs = sf.getImportDeclarations().some(
1920
+ (d) => d.getModuleSpecifierValue() === "fs" && (d.getNamespaceImport() || d.getDefaultImport())
1921
+ );
1922
+ if (hasFs) return;
1923
+ sf.addImportDeclaration({
1924
+ moduleSpecifier: "fs",
1925
+ namespaceImport: "fs"
1926
+ });
1927
+ }
1928
+ function ensureJoinImport(sf) {
1929
+ const pathImports = sf.getImportDeclarations().filter((d) => d.getModuleSpecifierValue() === "path");
1930
+ if (pathImports.some(
1931
+ (d) => d.getNamedImports().some((ni) => ni.getName() === "join")
1932
+ )) {
1933
+ return;
1934
+ }
1935
+ if (pathImports.length > 0) {
1936
+ pathImports[0].addNamedImport("join");
1937
+ return;
1938
+ }
1939
+ sf.addImportDeclaration({
1940
+ moduleSpecifier: "path",
1941
+ namedImports: ["join"]
1942
+ });
1943
+ }
1944
+ async function main10() {
1945
+ const srcDir = import_path10.default.join(process.cwd(), "src");
1946
+ const relCwd = (fp) => import_path10.default.relative(process.cwd(), fp);
1947
+ console.log("Phase 1: Converting JS config files to TypeScript...\n");
1948
+ let convertedCount = 0;
1949
+ for (const group of CONFIG_GROUPS) {
1950
+ for (const name of [group.baseName, group.prodName]) {
1951
+ if (convertFile(name, group, srcDir)) {
1952
+ convertedCount++;
1953
+ }
1954
+ }
1955
+ }
1956
+ if (convertedCount === 0) {
1957
+ console.log(" No JS config files needed conversion.\n");
1958
+ } else {
1959
+ console.log(`
1960
+ Converted ${convertedCount} file(s).
1961
+ `);
1962
+ }
1963
+ console.log(
1964
+ "Phase 3: Wrapping applicationConfig with defineApplicationConfig...\n"
1965
+ );
1966
+ const appConfigRelPath = "api/application/application-config.ts";
1967
+ const appConfigAbsPath = import_path10.default.join(srcDir, appConfigRelPath);
1968
+ if (!fs.existsSync(appConfigAbsPath)) {
1969
+ console.log(` Skipping Phase 3 \u2014 ${appConfigRelPath} not found in src/
1970
+ `);
1971
+ } else {
1972
+ const appConfigProject = new import_ts_morph10.Project({
1973
+ tsConfigFilePath: import_path10.default.resolve(srcDir, "../tsconfig.json"),
1974
+ skipAddingFilesFromTsConfig: false
1975
+ });
1976
+ const appConfigFile = appConfigProject.getSourceFile(appConfigAbsPath) ?? appConfigProject.addSourceFileAtPath(appConfigAbsPath);
1977
+ let wrapped = false;
1978
+ for (const varDecl of appConfigFile.getVariableDeclarations()) {
1979
+ if (varDecl.getName() !== "applicationConfig") continue;
1980
+ const init = varDecl.getInitializer();
1981
+ if (!init || !import_ts_morph10.Node.isObjectLiteralExpression(init)) continue;
1982
+ const propsToRemove = init.getProperties().filter((prop) => {
1983
+ if (!import_ts_morph10.Node.isPropertyAssignment(prop)) return false;
1984
+ const name = prop.getNameNode().getText().replace(/^['"]|['"]$/g, "");
1985
+ return !APPLICATION_CONFIG_VALID_KEYS.has(name);
1986
+ });
1987
+ if (propsToRemove.length > 0) {
1988
+ const filesToSaveAfterInlining = /* @__PURE__ */ new Set();
1989
+ const appConfigDir = import_path10.default.dirname(appConfigAbsPath);
1990
+ for (const removedProp of propsToRemove) {
1991
+ const key = removedProp.getName();
1992
+ for (const sf of appConfigProject.getSourceFiles()) {
1993
+ if (sf.getFilePath() === appConfigAbsPath) continue;
1994
+ if (!sf.getFilePath().includes("/src/")) continue;
1995
+ if (sf.getFilePath().includes("/node_modules/")) continue;
1996
+ const targetDir = import_path10.default.dirname(sf.getFilePath());
1997
+ const relDirFromTarget = import_path10.default.relative(targetDir, appConfigDir);
1998
+ let madeReplacement = true;
1999
+ while (madeReplacement) {
2000
+ madeReplacement = false;
2001
+ for (const identNode of sf.getDescendantsOfKind(
2002
+ import_ts_morph10.SyntaxKind.Identifier
2003
+ )) {
2004
+ if (identNode.getText() !== "applicationConfig") continue;
2005
+ let node = identNode;
2006
+ const accessPath = [];
2007
+ while (true) {
2008
+ const parent = node.getParent();
2009
+ if (!import_ts_morph10.Node.isPropertyAccessExpression(parent)) break;
2010
+ if (parent.getExpression() !== node) break;
2011
+ accessPath.push(parent.getName());
2012
+ node = parent;
2013
+ }
2014
+ if (accessPath.length === 0 || accessPath[0] !== key) continue;
2015
+ const resolvedValue = resolveConfigChain(init, accessPath);
2016
+ if (resolvedValue === null) {
2017
+ console.log(
2018
+ ` Cannot resolve applicationConfig.${accessPath.join(".")} \u2014 skipping inline replacement`
2019
+ );
2020
+ continue;
2021
+ }
2022
+ const adjustedValue = rewriteDirnameRefs(
2023
+ resolvedValue,
2024
+ relDirFromTarget
2025
+ );
2026
+ node.replaceWithText(adjustedValue);
2027
+ if (/\bfs\s*\./.test(adjustedValue)) {
2028
+ ensureFsImport(sf);
2029
+ }
2030
+ if (/\bjoin\s*\(/.test(adjustedValue)) {
2031
+ ensureJoinImport(sf);
2032
+ }
2033
+ console.log(
2034
+ ` Inlined applicationConfig.${accessPath.join(".")} \u2192 ${adjustedValue} in ${import_path10.default.relative(process.cwd(), sf.getFilePath())}`
2035
+ );
2036
+ filesToSaveAfterInlining.add(sf);
2037
+ madeReplacement = true;
2038
+ break;
2039
+ }
2040
+ }
2041
+ }
2042
+ }
2043
+ for (const sf of Array.from(filesToSaveAfterInlining)) {
2044
+ await sf.save();
2045
+ console.log(
2046
+ ` Saved (inlined): ${import_path10.default.relative(process.cwd(), sf.getFilePath())}`
2047
+ );
2048
+ }
2049
+ for (const prop of [...propsToRemove].reverse()) {
2050
+ const propName = prop.getName();
2051
+ console.log(
2052
+ ` Removing unknown key '${propName}' from applicationConfig (not in ApplicationConfig schema)`
2053
+ );
2054
+ prop.remove();
2055
+ }
2056
+ }
2057
+ varDecl.setInitializer(`defineApplicationConfig(${init.getText()})`);
2058
+ const TOOLKIT_MODULE = "@opencrvs/toolkit/application-config";
2059
+ const existing = appConfigFile.getImportDeclaration(
2060
+ (d) => d.getModuleSpecifierValue() === TOOLKIT_MODULE
2061
+ );
2062
+ if (existing) {
2063
+ const names = new Set(
2064
+ existing.getNamedImports().map((ni) => ni.getName())
2065
+ );
2066
+ if (!names.has("defineApplicationConfig")) {
2067
+ existing.addNamedImport("defineApplicationConfig");
2068
+ }
2069
+ } else {
2070
+ appConfigFile.addImportDeclaration({
2071
+ moduleSpecifier: TOOLKIT_MODULE,
2072
+ namedImports: ["defineApplicationConfig"]
2073
+ });
2074
+ }
2075
+ wrapped = true;
2076
+ console.log(
2077
+ ` Wrapped applicationConfig with defineApplicationConfig in ${appConfigRelPath}`
2078
+ );
2079
+ break;
2080
+ }
2081
+ if (!wrapped) {
2082
+ console.log(
2083
+ ` Skipping Phase 3 \u2014 applicationConfig plain object not found (already wrapped?)
2084
+ `
2085
+ );
2086
+ } else {
2087
+ await appConfigFile.save();
2088
+ console.log(` Saved: ${appConfigRelPath}
2089
+ `);
2090
+ }
2091
+ }
2092
+ console.log("Phase 2: Updating Hapi route handlers...\n");
2093
+ const project = new import_ts_morph10.Project({
2094
+ tsConfigFilePath: import_path10.default.resolve(srcDir, "../tsconfig.json"),
2095
+ skipAddingFilesFromTsConfig: false
2096
+ });
2097
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
2098
+ const fp = sf.getFilePath();
2099
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
2100
+ });
2101
+ console.log(` Analysing ${sourceFiles.length} source file(s).
2102
+ `);
2103
+ let totalReplaced = 0;
2104
+ for (const group of CONFIG_GROUPS) {
2105
+ totalReplaced += updateRouteHandlers(sourceFiles, group, srcDir, relCwd);
2106
+ }
2107
+ if (totalReplaced === 0) {
2108
+ console.log(" No route handlers matched \u2014 nothing to update in Phase 2.\n");
2109
+ }
2110
+ const modified = sourceFiles.filter((sf) => sf.wasForgotten() === false);
2111
+ const toSave = modified.filter(
2112
+ (sf) => sf.getDescendantsOfKind(import_ts_morph10.SyntaxKind.ObjectLiteralExpression).length > 0
2113
+ );
2114
+ let savedCount = 0;
2115
+ for (const sf of project.getSourceFiles()) {
2116
+ if (sf.isSaved()) continue;
2117
+ await sf.save();
2118
+ console.log(` Saved: ${relCwd(sf.getFilePath())}`);
2119
+ savedCount++;
2120
+ }
2121
+ if (savedCount === 0 && totalReplaced === 0) {
2122
+ console.log("Nothing was changed.");
2123
+ return;
2124
+ }
2125
+ console.log(
2126
+ `
2127
+ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} route handler(s).`
2128
+ );
2129
+ }
2130
+
2131
+ // src/migrations/v2.0/migrate-scopes.ts
2132
+ var import_ts_morph11 = require("ts-morph");
2133
+ var import_path11 = __toESM(require("path"));
2134
+
2135
+ // ../commons/src/scopes.ts
2136
+ var z3 = __toESM(require("zod/v4"));
2137
+ var qs = __toESM(require("qs"));
2138
+
2139
+ // ../commons/src/uuid.ts
2140
+ var import_uuid = require("uuid");
2141
+ var z = __toESM(require("zod/v4"));
2142
+ var UUID = z.uuid().brand("UUID");
2143
+
2144
+ // ../commons/src/authentication.ts
2145
+ var import_jwt_decode = __toESM(require("jwt-decode"));
2146
+ var z2 = __toESM(require("zod/v4"));
2147
+ var TokenUserType = z2.enum(["user", "system"]);
2148
+ var TokenWithBearer = z2.string().regex(/^Bearer\s/);
2149
+
2150
+ // ../commons/src/scopes.ts
2151
+ var JurisdictionFilter = z3.enum(["administrativeArea", "location", "all"]).describe(
2152
+ "Filters based on user jurisdiction relative to their office location in hierarchy."
2153
+ );
2154
+ var UserFilter = z3.enum(["user"]).describe("Filters based on the user. Limits to self.");
2155
+ var RecordScopeTypeV2 = z3.enum([
2156
+ "record.search",
2157
+ "record.create",
2158
+ "record.read",
2159
+ "record.declare",
2160
+ "record.notify",
2161
+ "record.edit",
2162
+ "record.reject",
2163
+ "record.archive",
2164
+ "record.review-duplicates",
2165
+ "record.register",
2166
+ "record.print-certified-copies",
2167
+ "record.request-correction",
2168
+ "record.correct",
2169
+ "record.unassign-others",
2170
+ "record.custom-action"
2171
+ ]);
2172
+ var PlainScopeType = z3.enum([
2173
+ // Misc. system scopes
2174
+ "bypassratelimit",
2175
+ "record.reindex",
2176
+ "user.data-seeding",
2177
+ "integration.create",
2178
+ "record.import",
2179
+ "config.update-all",
2180
+ "attachment.upload",
2181
+ "profile.electronic-signature",
2182
+ "user.read-only-my-audit",
2183
+ // Performance dashboard
2184
+ "performance.read",
2185
+ "performance.read-dashboards",
2186
+ "performance.vital-statistics-export",
2187
+ // Scopes used exclusively by countryconfig integration token
2188
+ "record.confirm-registration",
2189
+ "record.reject-registration"
2190
+ ]);
2191
+ var scopeByEvent = z3.preprocess(
2192
+ (val) => val === void 0 ? void 0 : [val].flat(),
2193
+ z3.array(z3.string()).optional()
2194
+ ).describe("Event type, e.g. birth, death");
2195
+ var userRole = z3.preprocess(
2196
+ (val) => val === void 0 ? void 0 : [val].flat(),
2197
+ z3.array(z3.string()).optional()
2198
+ ).describe("User role, e.g. admin, field agent");
2199
+ var scopeOptionsPlaceEvent = z3.object({
2200
+ event: scopeByEvent,
2201
+ placeOfEvent: JurisdictionFilter.optional()
2202
+ }).describe("Options applicable to all record scopes.");
2203
+ var scopeOptionsDeclared = scopeOptionsPlaceEvent.extend({
2204
+ declaredIn: JurisdictionFilter.optional(),
2205
+ declaredBy: UserFilter.optional()
2206
+ }).describe("Options applicable to actions that may take place after DECLARE");
2207
+ var AllRecordScopeOptions = scopeOptionsDeclared.extend({
2208
+ registeredIn: JurisdictionFilter.optional(),
2209
+ registeredBy: UserFilter.optional()
2210
+ }).describe(
2211
+ "Options applicable to actions that may take place after REGISTER, with full filtering capabilities."
2212
+ );
2213
+ var CustomActionScopeOptions = AllRecordScopeOptions.extend({
2214
+ customActionTypes: z3.preprocess(
2215
+ (val) => val === void 0 ? void 0 : [val].flat(),
2216
+ z3.array(z3.string()).optional()
2217
+ ).describe("Allowed custom action types")
2218
+ });
2219
+ var AccessLevelOptions = z3.object({
2220
+ accessLevel: JurisdictionFilter.optional()
2221
+ });
2222
+ var AllUserScopeOptions = AccessLevelOptions.extend({
2223
+ role: userRole.optional()
2224
+ });
2225
+ var WorkqueueOrDashboardOptions = z3.object({
2226
+ ids: z3.preprocess(
2227
+ (val) => val === void 0 ? void 0 : [val].flat(),
2228
+ z3.array(z3.string())
2229
+ ).describe("Must contain a list of workqueue or dashboard ids.")
2230
+ });
2231
+ var AllScopeOptions = z3.object({
2232
+ ...AllRecordScopeOptions.shape,
2233
+ ...AccessLevelOptions.shape,
2234
+ ...AllUserScopeOptions.shape,
2235
+ ...WorkqueueOrDashboardOptions.shape
2236
+ });
2237
+ var ScopeOptionKey = AllScopeOptions.keyof();
2238
+ var ResolvedScopeOptionsPlaceEvent = z3.object({
2239
+ event: scopeByEvent,
2240
+ placeOfEvent: UUID.nullish()
2241
+ }).describe(
2242
+ "Resolved options applicable to all record scopes, with location ID instead of jurisdiction filter."
2243
+ );
2244
+ var ResolvedScopeOptionsDeclared = ResolvedScopeOptionsPlaceEvent.extend({
2245
+ declaredIn: UUID.nullish(),
2246
+ declaredBy: z3.string().optional()
2247
+ }).describe(
2248
+ "Resolved options applicable to actions that may take place after DECLARE, with location ID and user ID instead of filters."
2249
+ );
2250
+ var ResolvedScopeOptionsFull = ResolvedScopeOptionsDeclared.extend({
2251
+ registeredIn: UUID.nullish(),
2252
+ registeredBy: z3.string().optional()
2253
+ }).describe(
2254
+ "Resolved options applicable to actions that may take place after REGISTER, with full filtering capabilities and location/user IDs instead of filters."
2255
+ );
2256
+ var ScopesWithPlaceEventOptions = RecordScopeTypeV2.extract([
2257
+ "record.create",
2258
+ "record.declare",
2259
+ "record.notify"
2260
+ ]);
2261
+ var ScopesWithDeclaredOptions = RecordScopeTypeV2.extract([
2262
+ "record.edit",
2263
+ "record.reject",
2264
+ "record.archive",
2265
+ "record.review-duplicates",
2266
+ "record.register"
2267
+ ]);
2268
+ var ScopesWithFullOptions = RecordScopeTypeV2.extract([
2269
+ "record.search",
2270
+ "record.read",
2271
+ "record.request-correction",
2272
+ "record.correct",
2273
+ "record.unassign-others"
2274
+ ]);
2275
+ var ScopeOptionsPrintCertifiedCopies = AllRecordScopeOptions.extend({
2276
+ templates: z3.preprocess(
2277
+ (val) => val === void 0 ? void 0 : [val].flat(),
2278
+ z3.array(z3.string()).optional()
2279
+ ).describe(
2280
+ "Template IDs for certified copies. Controls which certificate templates are returned to the client via the config service. Certificate printing is a client-side operation \u2014 this option is not validated when the printCertificate action is submitted."
2281
+ )
2282
+ });
2283
+ var RecordScopeV2 = z3.discriminatedUnion("type", [
2284
+ z3.object({
2285
+ type: ScopesWithPlaceEventOptions,
2286
+ options: scopeOptionsPlaceEvent.optional()
2287
+ }),
2288
+ z3.object({
2289
+ type: ScopesWithDeclaredOptions,
2290
+ options: scopeOptionsDeclared.optional()
2291
+ }),
2292
+ z3.object({
2293
+ type: ScopesWithFullOptions,
2294
+ options: AllRecordScopeOptions.optional()
2295
+ }),
2296
+ z3.object({
2297
+ type: z3.literal("record.custom-action"),
2298
+ options: CustomActionScopeOptions.optional()
2299
+ }),
2300
+ z3.object({
2301
+ type: z3.literal("record.print-certified-copies"),
2302
+ options: ScopeOptionsPrintCertifiedCopies.optional()
2303
+ })
2304
+ ]).describe(
2305
+ "Scopes used to check user's permission to perform actions on a record."
2306
+ );
2307
+ var SystemScopeType = z3.enum([
2308
+ "organisation.read-locations",
2309
+ "user.read",
2310
+ "user.create",
2311
+ "user.edit",
2312
+ "user.search"
2313
+ ]);
2314
+ var UserScopeType = SystemScopeType.extract([
2315
+ "user.read",
2316
+ "user.create",
2317
+ "user.edit",
2318
+ "user.search"
2319
+ ]);
2320
+ var ScopesWithRoleOption = UserScopeType.extract(["user.edit", "user.create"]);
2321
+ var UserScopeV2 = z3.discriminatedUnion("type", [
2322
+ z3.object({
2323
+ type: ScopesWithRoleOption,
2324
+ options: AllUserScopeOptions.optional()
2325
+ }),
2326
+ z3.object({
2327
+ type: UserScopeType.extract(["user.read", "user.search"]),
2328
+ options: AccessLevelOptions.optional()
2329
+ })
2330
+ ]);
2331
+ var ResolvedRecordScopeV2 = z3.discriminatedUnion("type", [
2332
+ z3.object({
2333
+ type: ScopesWithPlaceEventOptions,
2334
+ options: ResolvedScopeOptionsPlaceEvent.optional()
2335
+ }),
2336
+ z3.object({
2337
+ type: ScopesWithDeclaredOptions,
2338
+ options: ResolvedScopeOptionsDeclared.optional()
2339
+ }),
2340
+ z3.object({
2341
+ type: ScopesWithFullOptions,
2342
+ options: ResolvedScopeOptionsFull.optional()
2343
+ }),
2344
+ z3.object({
2345
+ type: z3.literal("record.print-certified-copies"),
2346
+ options: ResolvedScopeOptionsFull.extend({
2347
+ templates: z3.array(z3.string()).optional()
2348
+ }).optional()
2349
+ })
2350
+ ]).describe("Resolved scope with location/user IDs instead of filters.");
2351
+ var Scope2 = z3.discriminatedUnion("type", [
2352
+ z3.object({ type: PlainScopeType }),
2353
+ ...RecordScopeV2.options,
2354
+ ...UserScopeV2.options,
2355
+ z3.object({
2356
+ type: z3.literal("organisation.read-locations"),
2357
+ options: AccessLevelOptions.optional()
2358
+ }),
2359
+ z3.object({
2360
+ type: z3.literal("workqueue"),
2361
+ options: WorkqueueOrDashboardOptions
2362
+ }),
2363
+ z3.object({
2364
+ type: z3.literal("dashboard.view"),
2365
+ options: WorkqueueOrDashboardOptions
2366
+ })
2367
+ ]);
2368
+ var ScopeType2 = z3.enum([
2369
+ ...SystemScopeType.options,
2370
+ ...RecordScopeTypeV2.options,
2371
+ ...PlainScopeType.options,
2372
+ "workqueue",
2373
+ "dashboard.view"
2374
+ ]);
2375
+ var flattenScope = (scope) => ({
2376
+ type: scope.type,
2377
+ ..."options" in scope ? scope.options : {}
2378
+ });
2379
+ var unflattenScope = (input) => {
2380
+ const { type, ...options } = input;
2381
+ return { type, options };
2382
+ };
2383
+ var EncodedScope2 = z3.string().brand("EncodedScope");
2384
+ var encodeScope = (scope) => {
2385
+ const flattened = flattenScope(scope);
2386
+ return qs.stringify(flattened, {
2387
+ arrayFormat: "comma",
2388
+ allowDots: true,
2389
+ addQueryPrefix: false,
2390
+ encode: false
2391
+ });
2392
+ };
2393
+ var decodeScope = (query) => {
2394
+ const scope = qs.parse(query, {
2395
+ ignoreQueryPrefix: true,
2396
+ comma: true,
2397
+ allowDots: true
2398
+ });
2399
+ const unflattenedScope = unflattenScope(scope);
2400
+ return Scope2.safeParse(unflattenedScope)?.data;
2401
+ };
2402
+ var DEFAULT_SCOPE_OPTIONS = {
2403
+ placeOfEvent: JurisdictionFilter.enum.all,
2404
+ accessLevel: JurisdictionFilter.enum.all
2405
+ };
2406
+
2407
+ // ../commons/src/scopes.deprecated.do-not-use.ts
2408
+ var z4 = __toESM(require("zod/v4"));
2409
+ var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2410
+ var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2411
+ var SearchScope = z4.object({
2412
+ type: z4.literal("search"),
2413
+ options: z4.object({
2414
+ event: z4.array(z4.string()).length(1),
2415
+ access: z4.array(z4.enum(["my-jurisdiction", "all"])).length(1)
2416
+ })
2417
+ });
2418
+ var CreateUserScope = z4.object({
2419
+ type: z4.literal("user.create"),
2420
+ options: z4.object({
2421
+ role: z4.array(z4.string())
2422
+ })
2423
+ });
2424
+ var EditUserScope = z4.object({
2425
+ type: z4.literal("user.edit"),
2426
+ options: z4.object({
2427
+ role: z4.array(z4.string())
2428
+ })
2429
+ });
2430
+ var WorkqueueScope = z4.object({
2431
+ type: z4.literal("workqueue"),
2432
+ options: z4.object({
2433
+ id: z4.array(z4.string())
2434
+ })
2435
+ });
2436
+ var PrintCertifiedCopiesScope = z4.object({
2437
+ type: z4.literal("record.registered.print-certified-copies"),
2438
+ options: z4.object({
2439
+ event: z4.array(z4.string()).describe("Event type, e.g. birth, death"),
2440
+ templates: z4.array(z4.string()).optional().describe(
2441
+ "Template IDs for certified copies. If not provided, all templates will be used."
2442
+ )
2443
+ })
2444
+ });
2445
+ var LegacyRecordScope = z4.object({
2446
+ type: z4.enum([
2447
+ "record.create",
2448
+ "record.read",
2449
+ "record.declare",
2450
+ "record.notify",
2451
+ "record.declared.edit",
2452
+ "record.declared.validate",
2453
+ "record.declared.reject",
2454
+ "record.declared.archive",
2455
+ "record.declared.review-duplicates",
2456
+ "record.register",
2457
+ "record.registered.request-correction",
2458
+ "record.registered.correct",
2459
+ "record.unassign-others"
2460
+ ]),
2461
+ options: z4.object({
2462
+ event: z4.array(z4.string()).describe("Event type, e.g. birth, death")
2463
+ })
2464
+ }).describe(
2465
+ "Scopes used to check user's permission to perform actions on a record."
2466
+ );
2467
+ var ConfigurableRawScopes = z4.discriminatedUnion("type", [
2468
+ SearchScope,
2469
+ LegacyRecordScope,
2470
+ PrintCertifiedCopiesScope,
2471
+ CreateUserScope,
2472
+ EditUserScope,
2473
+ WorkqueueScope
2474
+ ]);
2475
+ function getScopeOptions(rawOptions) {
2476
+ return rawOptions.split(",").reduce((acc, option) => {
2477
+ const [key, value] = option.split("=");
2478
+ acc[key] = value.split("|");
2479
+ return acc;
2480
+ }, {});
2481
+ }
2482
+ function parseConfigurableScope(scope) {
2483
+ const maybeConfigurableScope = rawConfigurableScope.safeParse(scope);
2484
+ if (!maybeConfigurableScope.success) {
2485
+ return;
2486
+ }
2487
+ const rawScope = maybeConfigurableScope.data;
2488
+ const [, type, rawOptions] = rawScope.match(rawConfigurableScopeRegex) ?? [];
2489
+ const options = getScopeOptions(rawOptions);
2490
+ const parsedScope = {
2491
+ type,
2492
+ options
2493
+ };
2494
+ const result = ConfigurableRawScopes.safeParse(parsedScope);
2495
+ return result.success ? result.data : void 0;
2496
+ }
2497
+ var SCOPES = {
2498
+ BYPASSRATELIMIT: "bypassratelimit",
2499
+ RECORD_REINDEX: "record.reindex",
2500
+ RECORD_IMPORT: "record.import",
2501
+ ATTACHMENT_UPLOAD: "attachment.upload",
2502
+ USER_DATA_SEEDING: "user.data-seeding",
2503
+ INTEGRATION_CREATE: "integration.create",
2504
+ PERFORMANCE_EXPORT_VITAL_STATISTICS: "performance.vital-statistics-export",
2505
+ PROFILE_ELECTRONIC_SIGNATURE: "profile.electronic-signature",
2506
+ PERFORMANCE_READ: "performance.read",
2507
+ PERFORMANCE_READ_DASHBOARDS: "performance.read-dashboards",
2508
+ CONFIG_UPDATE_ALL: "config.update-all",
2509
+ ORGANISATION_READ_LOCATIONS: "organisation.read-locations",
2510
+ ORGANISATION_READ_LOCATIONS_MY_OFFICE: "organisation.read-locations:my-office",
2511
+ ORGANISATION_READ_LOCATIONS_MY_JURISDICTION: "organisation.read-locations:my-jurisdiction",
2512
+ USER_CREATE: "user.create:all",
2513
+ USER_READ: "user.read:all",
2514
+ USER_UPDATE: "user.update:all",
2515
+ USER_READ_MY_OFFICE: "user.read:my-office",
2516
+ USER_READ_MY_JURISDICTION: "user.read:my-jurisdiction",
2517
+ USER_READ_ONLY_MY_AUDIT: "user.read:only-my-audit",
2518
+ USER_CREATE_MY_JURISDICTION: "user.create:my-jurisdiction",
2519
+ USER_UPDATE_MY_JURISDICTION: "user.update:my-jurisdiction"
2520
+ };
2521
+ var literalScopeToV2ScopeMap = {
2522
+ [SCOPES.BYPASSRATELIMIT]: { type: "bypassratelimit" },
2523
+ [SCOPES.RECORD_REINDEX]: { type: "record.reindex" },
2524
+ [SCOPES.RECORD_IMPORT]: { type: "record.import" },
2525
+ [SCOPES.ATTACHMENT_UPLOAD]: { type: "attachment.upload" },
2526
+ [SCOPES.USER_DATA_SEEDING]: { type: "user.data-seeding" },
2527
+ [SCOPES.INTEGRATION_CREATE]: { type: "integration.create" },
2528
+ [SCOPES.PERFORMANCE_EXPORT_VITAL_STATISTICS]: {
2529
+ type: "performance.vital-statistics-export"
2530
+ },
2531
+ [SCOPES.PROFILE_ELECTRONIC_SIGNATURE]: {
2532
+ type: "profile.electronic-signature"
2533
+ },
2534
+ [SCOPES.PERFORMANCE_READ]: { type: "performance.read" },
2535
+ [SCOPES.PERFORMANCE_READ_DASHBOARDS]: { type: "performance.read-dashboards" },
2536
+ [SCOPES.CONFIG_UPDATE_ALL]: { type: "config.update-all" },
2537
+ [SCOPES.ORGANISATION_READ_LOCATIONS]: {
2538
+ type: "organisation.read-locations"
2539
+ },
2540
+ [SCOPES.ORGANISATION_READ_LOCATIONS_MY_OFFICE]: {
2541
+ type: "organisation.read-locations",
2542
+ options: { accessLevel: "location" }
2543
+ },
2544
+ [SCOPES.ORGANISATION_READ_LOCATIONS_MY_JURISDICTION]: {
2545
+ type: "organisation.read-locations",
2546
+ options: { accessLevel: "administrativeArea" }
2547
+ },
2548
+ [SCOPES.USER_CREATE]: { type: "user.create" },
2549
+ [SCOPES.USER_CREATE_MY_JURISDICTION]: {
2550
+ type: "user.create",
2551
+ options: { accessLevel: "administrativeArea" }
2552
+ },
2553
+ [SCOPES.USER_READ]: { type: "user.read" },
2554
+ [SCOPES.USER_READ_MY_OFFICE]: {
2555
+ type: "user.read",
2556
+ options: { accessLevel: "location" }
2557
+ },
2558
+ [SCOPES.USER_READ_MY_JURISDICTION]: {
2559
+ type: "user.read",
2560
+ options: { accessLevel: "administrativeArea" }
2561
+ },
2562
+ [SCOPES.USER_READ_ONLY_MY_AUDIT]: { type: "user.read-only-my-audit" },
2563
+ [SCOPES.USER_UPDATE]: { type: "user.edit" },
2564
+ [SCOPES.USER_UPDATE_MY_JURISDICTION]: {
2565
+ type: "user.edit",
2566
+ options: { accessLevel: "administrativeArea" }
2567
+ }
2568
+ };
2569
+ function parseLiteralScope(scope) {
2570
+ if (scope in literalScopeToV2ScopeMap) {
2571
+ return literalScopeToV2ScopeMap[scope];
2572
+ }
2573
+ return void 0;
2574
+ }
2575
+ var v1ToV2ConfigScopeTypeMap = {
2576
+ search: "record.search",
2577
+ workqueue: "workqueue",
2578
+ "user.create": "user.create",
2579
+ "user.edit": "user.edit",
2580
+ "record.create": "record.create",
2581
+ "record.read": "record.read",
2582
+ "record.declare": "record.declare",
2583
+ "record.notify": "record.notify",
2584
+ "record.register": "record.register",
2585
+ "record.unassign-others": "record.unassign-others",
2586
+ "record.declared.reject": "record.reject",
2587
+ "record.declared.archive": "record.archive",
2588
+ "record.declared.review-duplicates": "record.review-duplicates",
2589
+ "record.registered.print-certified-copies": "record.print-certified-copies",
2590
+ "record.registered.request-correction": "record.request-correction",
2591
+ "record.registered.correct": "record.correct",
2592
+ "record.declared.edit": "record.edit",
2593
+ "record.declared.validate": "record.custom-action"
2594
+ };
2595
+ var legacyScopeToV2Scope = (v1Scope) => {
2596
+ const configurableV1Scope = parseConfigurableScope(v1Scope);
2597
+ const literalV1Scope = parseLiteralScope(v1Scope);
2598
+ if (!configurableV1Scope && !literalV1Scope) {
2599
+ throw new Error(`Invalid V1 scope: ${v1Scope}`);
2600
+ }
2601
+ if (literalV1Scope) {
2602
+ return encodeScope(literalV1Scope);
2603
+ }
2604
+ if (configurableV1Scope) {
2605
+ const type = v1ToV2ConfigScopeTypeMap[configurableV1Scope.type];
2606
+ if (type === void 0) {
2607
+ throw new Error(`Unsupported V1 scope type: ${configurableV1Scope.type}`);
2608
+ }
2609
+ if (configurableV1Scope.type === "workqueue") {
2610
+ return encodeScope({
2611
+ type: "workqueue",
2612
+ options: {
2613
+ ids: configurableV1Scope.options.id || []
2614
+ }
2615
+ });
2616
+ }
2617
+ if (configurableV1Scope.type === "search") {
2618
+ return encodeScope({
2619
+ type,
2620
+ options: {
2621
+ event: configurableV1Scope.options.event || [],
2622
+ placeOfEvent: configurableV1Scope.options.access[0] === "my-jurisdiction" ? "administrativeArea" : "all"
2623
+ }
2624
+ });
2625
+ }
2626
+ if (configurableV1Scope.type === "record.declared.validate") {
2627
+ return encodeScope({
2628
+ type: "record.custom-action",
2629
+ options: {
2630
+ event: configurableV1Scope.options.event,
2631
+ customActionTypes: ["VALIDATE_DECLARATION"]
2632
+ }
2633
+ });
2634
+ }
2635
+ return encodeScope({
2636
+ type,
2637
+ options: configurableV1Scope.options
2638
+ });
2639
+ }
2640
+ throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2641
+ };
2642
+
2643
+ // src/migrations/v2.0/migrate-scopes.ts
2644
+ var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
2645
+ var SCOPES_PROPERTY_NAME = "scopes";
2646
+ var TOOLKIT_SCOPES_MODULE = "@opencrvs/toolkit/scopes";
2647
+ var DEFINE_SCOPES_IMPORT_NAME = "defineScopes";
2648
+ var DEFINE_ROLES_IMPORT_NAME = "defineRoles";
2649
+ function resolveScopeKeyFromElementAccess(element) {
2650
+ if (import_ts_morph11.Node.isPropertyAccessExpression(element) && element.getExpression().getText() === "SCOPES") {
2651
+ return element.getName();
2652
+ }
2653
+ if (import_ts_morph11.Node.isElementAccessExpression(element) && element.getExpression().getText() === "SCOPES") {
2654
+ const argumentExpression = element.getArgumentExpression();
2655
+ if (argumentExpression && (import_ts_morph11.Node.isStringLiteral(argumentExpression) || import_ts_morph11.Node.isNoSubstitutionTemplateLiteral(argumentExpression))) {
2656
+ return argumentExpression.getLiteralValue();
2657
+ }
2658
+ }
2659
+ return null;
2660
+ }
2661
+ function resolveLegacyScopeFromElement(element) {
2662
+ if (import_ts_morph11.Node.isStringLiteral(element) || import_ts_morph11.Node.isNoSubstitutionTemplateLiteral(element)) {
2663
+ return element.getLiteralValue();
2664
+ }
2665
+ const scopeKey = resolveScopeKeyFromElementAccess(element);
2666
+ if (scopeKey) {
2667
+ const scopeValue = SCOPES[scopeKey];
2668
+ return typeof scopeValue === "string" ? scopeValue : null;
2669
+ }
2670
+ const expressionType = element.getType();
2671
+ if (expressionType.isStringLiteral()) {
2672
+ const literalValue = expressionType.getLiteralValue();
2673
+ return typeof literalValue === "string" ? literalValue : null;
2674
+ }
2675
+ return null;
2676
+ }
2677
+ function migrateScopesArrays(rolesFilePath, project) {
2678
+ const sourceFile = project.getSourceFile(rolesFilePath);
2679
+ if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
2680
+ let migratedCount = 0;
2681
+ let removedCount = 0;
2682
+ const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
2683
+ for (const scopesProp of scopesProperties) {
2684
+ const initializer = scopesProp.getInitializer();
2685
+ if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2686
+ const elements = initializer.getElements();
2687
+ for (let index = elements.length - 1; index >= 0; index--) {
2688
+ const element = elements[index];
2689
+ if (!import_ts_morph11.Node.isExpression(element)) continue;
2690
+ const scopeKey = resolveScopeKeyFromElementAccess(element);
2691
+ if (scopeKey && !(scopeKey in SCOPES)) {
2692
+ console.warn(
2693
+ ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2694
+ );
2695
+ initializer.removeElement(index);
2696
+ removedCount++;
2697
+ continue;
2698
+ }
2699
+ const legacyScope = resolveLegacyScopeFromElement(element);
2700
+ if (!legacyScope) {
2701
+ console.warn(
2702
+ ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2703
+ );
2704
+ continue;
2705
+ }
2706
+ try {
2707
+ const migratedScope = legacyScopeToV2Scope(legacyScope);
2708
+ const scope = decodeScope(migratedScope);
2709
+ if (!scope) {
2710
+ console.warn(
2711
+ ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2712
+ );
2713
+ continue;
2714
+ }
2715
+ element.replaceWithText(JSON.stringify(scope));
2716
+ migratedCount++;
2717
+ } catch (error) {
2718
+ console.warn(
2719
+ ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2720
+ );
2721
+ }
2722
+ }
2723
+ }
2724
+ if (removedCount > 0) {
2725
+ console.log(
2726
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
2727
+ );
2728
+ }
2729
+ return { migratedCount, removedCount };
2730
+ }
2731
+ function ensureScopesHelpersImport(rolesFilePath, project) {
2732
+ const sourceFile = project.getSourceFile(rolesFilePath);
2733
+ if (!sourceFile) return false;
2734
+ const existingImport = sourceFile.getImportDeclaration(
2735
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_SCOPES_MODULE
2736
+ );
2737
+ let changed = false;
2738
+ if (existingImport) {
2739
+ const hasDefineScopesImport = existingImport.getNamedImports().some((ni) => ni.getName() === DEFINE_SCOPES_IMPORT_NAME);
2740
+ const hasDefineRolesImport = existingImport.getNamedImports().some((ni) => ni.getName() === DEFINE_ROLES_IMPORT_NAME);
2741
+ if (!hasDefineScopesImport) {
2742
+ existingImport.addNamedImport(DEFINE_SCOPES_IMPORT_NAME);
2743
+ changed = true;
2744
+ }
2745
+ if (!hasDefineRolesImport) {
2746
+ existingImport.addNamedImport(DEFINE_ROLES_IMPORT_NAME);
2747
+ changed = true;
2748
+ }
2749
+ const encodeScopeImport = existingImport.getNamedImports().find((ni) => ni.getName() === "encodeScope");
2750
+ if (encodeScopeImport) {
2751
+ encodeScopeImport.remove();
2752
+ changed = true;
2753
+ }
2754
+ return changed;
2755
+ }
2756
+ sourceFile.addImportDeclaration({
2757
+ moduleSpecifier: TOOLKIT_SCOPES_MODULE,
2758
+ namedImports: [DEFINE_SCOPES_IMPORT_NAME, DEFINE_ROLES_IMPORT_NAME]
2759
+ });
2760
+ return true;
2761
+ }
2762
+ function wrapScopesArraysWithDefineScopes(rolesFilePath, project) {
2763
+ const sourceFile = project.getSourceFile(rolesFilePath);
2764
+ if (!sourceFile) return 0;
2765
+ let wrappedCount = 0;
2766
+ const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
2767
+ for (const scopesProp of scopesProperties) {
2768
+ const initializer = scopesProp.getInitializer();
2769
+ if (!initializer) continue;
2770
+ if (import_ts_morph11.Node.isCallExpression(initializer) && initializer.getExpression().getText() === DEFINE_SCOPES_IMPORT_NAME) {
2771
+ continue;
2772
+ }
2773
+ if (!import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2774
+ scopesProp.setInitializer(
2775
+ `${DEFINE_SCOPES_IMPORT_NAME}(${initializer.getText()})`
2776
+ );
2777
+ wrappedCount++;
2778
+ }
2779
+ return wrappedCount;
2780
+ }
2781
+ function wrapRolesWithDefineRoles(rolesFilePath, project) {
2782
+ const sourceFile = project.getSourceFile(rolesFilePath);
2783
+ if (!sourceFile) return false;
2784
+ const rolesDeclaration = sourceFile.getVariableDeclaration("roles");
2785
+ if (!rolesDeclaration) return false;
2786
+ const initializer = rolesDeclaration.getInitializer();
2787
+ if (!initializer) return false;
2788
+ if (import_ts_morph11.Node.isCallExpression(initializer) && initializer.getExpression().getText() === DEFINE_ROLES_IMPORT_NAME) {
2789
+ return false;
2790
+ }
2791
+ if (!import_ts_morph11.Node.isArrayLiteralExpression(initializer)) return false;
2792
+ const typeNode = rolesDeclaration.getTypeNode();
2793
+ if (typeNode?.getText().includes("Role")) {
2794
+ rolesDeclaration.removeType();
2795
+ }
2796
+ rolesDeclaration.setInitializer(
2797
+ `${DEFINE_ROLES_IMPORT_NAME}(${initializer.getText()})`
2798
+ );
2799
+ return true;
2800
+ }
2801
+ function pruneNamedImportIfUnused(sourceFile, moduleSpecifier, importName) {
2802
+ const importDeclaration = sourceFile.getImportDeclaration(
2803
+ (decl) => decl.getModuleSpecifierValue() === moduleSpecifier
2804
+ );
2805
+ if (!importDeclaration) return false;
2806
+ const namedImport = importDeclaration.getNamedImports().find((ni) => ni.getName() === importName);
2807
+ if (!namedImport) return false;
2808
+ const references = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.Identifier).filter(
2809
+ (identifier) => identifier.getText() === importName && !import_ts_morph11.Node.isImportSpecifier(identifier.getParent())
2810
+ );
2811
+ if (references.length > 0) {
2812
+ return false;
2813
+ }
2814
+ namedImport.remove();
2815
+ if (importDeclaration.getNamedImports().length === 0 && !importDeclaration.getDefaultImport() && !importDeclaration.getNamespaceImport()) {
2816
+ importDeclaration.remove();
2817
+ }
2818
+ return true;
2819
+ }
2820
+ function removeRoleTypeDefinitionAndUnusedImports(rolesFilePath, project) {
2821
+ const sourceFile = project.getSourceFile(rolesFilePath);
2822
+ if (!sourceFile) return false;
2823
+ let removed = false;
2824
+ const roleTypeAlias = sourceFile.getTypeAlias("Role");
2825
+ if (roleTypeAlias) {
2826
+ roleTypeAlias.remove();
2827
+ removed = true;
2828
+ }
2829
+ const roleInterface = sourceFile.getInterface("Role");
2830
+ if (roleInterface) {
2831
+ roleInterface.remove();
2832
+ removed = true;
2833
+ }
2834
+ const removedScopeImport = pruneNamedImportIfUnused(
2835
+ sourceFile,
2836
+ TOOLKIT_SCOPES_MODULE,
2837
+ "Scope"
2838
+ );
2839
+ const removedMessageDescriptorImport = pruneNamedImportIfUnused(
2840
+ sourceFile,
2841
+ "react-intl",
2842
+ "MessageDescriptor"
2843
+ );
2844
+ removed = removed || removedScopeImport || removedMessageDescriptorImport;
2845
+ return removed;
2846
+ }
2847
+ async function main11() {
2848
+ const cwd = process.cwd();
2849
+ const srcDir = import_path11.default.join(cwd, "src");
2850
+ const rolesFilePath = import_path11.default.join(cwd, ROLES_FILE_RELATIVE_PATH);
2851
+ console.log(`Scanning roles scopes in: ${rolesFilePath}`);
2852
+ const project = new import_ts_morph11.Project({
2853
+ tsConfigFilePath: import_path11.default.resolve(srcDir, "../tsconfig.json"),
2854
+ skipAddingFilesFromTsConfig: false
2855
+ });
2856
+ const sourceFile = project.getSourceFile(rolesFilePath);
2857
+ if (!sourceFile) {
2858
+ console.log(
2859
+ `No roles file found at '${ROLES_FILE_RELATIVE_PATH}'. Nothing to do.`
2860
+ );
2861
+ return;
2862
+ }
2863
+ const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2864
+ const { migratedCount, removedCount } = migrateScopesArrays(
2865
+ rolesFilePath,
2866
+ project
2867
+ );
2868
+ const wrappedScopesCount = wrapScopesArraysWithDefineScopes(
2869
+ rolesFilePath,
2870
+ project
2871
+ );
2872
+ const wrappedRoles = wrapRolesWithDefineRoles(rolesFilePath, project);
2873
+ const removedRoleType = removeRoleTypeDefinitionAndUnusedImports(
2874
+ rolesFilePath,
2875
+ project
2876
+ );
2877
+ if (migratedCount === 0 && removedCount === 0 && wrappedScopesCount === 0 && !wrappedRoles && !removedRoleType && !importChanged) {
2878
+ console.log("No migratable literal scopes found. Nothing to do.");
2879
+ return;
2880
+ }
2881
+ await sourceFile.save();
2882
+ console.log(
2883
+ `Done. Migrated ${migratedCount} legacy scope(s), removed ${removedCount} unknown SCOPES reference(s), wrapped ${wrappedScopesCount} scope array(s) with defineScopes()${wrappedRoles ? ", wrapped roles with defineRoles()" : ""}${removedRoleType ? ", and removed Role type definition" : ""}${importChanged ? ". Updated toolkit/scopes imports." : "."}`
2884
+ );
2885
+ }
2886
+
2887
+ // src/migrations/v2.0/remove-deprecated-imports.ts
2888
+ var import_ts_morph12 = require("ts-morph");
2889
+ var import_path12 = __toESM(require("path"));
2890
+ var DEPRECATED_IMPORT = "SCOPES";
2891
+ var TARGET_MODULES = /* @__PURE__ */ new Set([
2892
+ "@opencrvs/toolkit/scopes",
2893
+ "@opencrvs/toolkit"
2894
+ ]);
2895
+ function processFile10(filePath, project) {
2896
+ const sourceFile = project.getSourceFile(filePath);
2897
+ if (!sourceFile) return 0;
2898
+ let removedCount = 0;
2899
+ const importDecls = sourceFile.getImportDeclarations().filter((decl) => TARGET_MODULES.has(decl.getModuleSpecifierValue()));
2900
+ for (const decl of importDecls) {
2901
+ const matchingNamedImports = decl.getNamedImports().filter((ni) => ni.getName() === DEPRECATED_IMPORT);
2902
+ if (matchingNamedImports.length === 0) continue;
2903
+ for (const namedImport of matchingNamedImports) {
2904
+ namedImport.remove();
2905
+ removedCount++;
2906
+ }
2907
+ const hasAnyNamedImportsLeft = decl.getNamedImports().length > 0;
2908
+ const hasDefaultImport = !!decl.getDefaultImport();
2909
+ const hasNamespaceImport = !!decl.getNamespaceImport();
2910
+ if (!hasAnyNamedImportsLeft && !hasDefaultImport && !hasNamespaceImport) {
2911
+ decl.remove();
2912
+ }
2913
+ console.log(
2914
+ ` [${import_path12.default.relative(process.cwd(), filePath)}] Removed ${matchingNamedImports.length} deprecated '${DEPRECATED_IMPORT}' import(s) from '${decl.getModuleSpecifierValue()}'`
2915
+ );
2916
+ }
2917
+ return removedCount;
2918
+ }
2919
+ async function main12() {
2920
+ const srcDir = import_path12.default.join(process.cwd(), "src");
2921
+ console.log(`Scanning for deprecated imports in: ${srcDir}
2922
+ `);
2923
+ const project = new import_ts_morph12.Project({
2924
+ tsConfigFilePath: import_path12.default.resolve(srcDir, "../tsconfig.json"),
2925
+ skipAddingFilesFromTsConfig: false
2926
+ });
2927
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
2928
+ const fp = sf.getFilePath();
2929
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
2930
+ });
2931
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
2932
+ `);
2933
+ let totalRemoved = 0;
2934
+ const modifiedFiles = [];
2935
+ for (const sourceFile of sourceFiles) {
2936
+ const filePath = sourceFile.getFilePath();
2937
+ const removed = processFile10(filePath, project);
2938
+ if (removed > 0) {
2939
+ totalRemoved += removed;
2940
+ modifiedFiles.push(filePath);
2941
+ }
2942
+ }
2943
+ if (modifiedFiles.length === 0) {
2944
+ console.log("No deprecated imports found. Nothing to do.");
2945
+ return;
2946
+ }
2947
+ console.log(`
2948
+ Saving ${modifiedFiles.length} modified file(s)...`);
2949
+ for (const filePath of modifiedFiles) {
2950
+ await project.getSourceFileOrThrow(filePath).save();
2951
+ console.log(` Saved: ${import_path12.default.relative(process.cwd(), filePath)}`);
2952
+ }
2953
+ console.log(`
2954
+ Done. Removed ${totalRemoved} deprecated import(s).`);
2955
+ }
2956
+
2957
+ // src/migrations/v2.0/remove-unused-environment-variables.ts
2958
+ var import_path13 = __toESM(require("path"));
2959
+ var import_ts_morph13 = require("ts-morph");
2960
+ var UNUSED_ENV_VARS = /* @__PURE__ */ new Set([
2961
+ "APPLICATION_CONFIG_URL",
2962
+ "FHIR_URL",
2963
+ "CONFIRM_REGISTRATION_URL"
2964
+ ]);
2965
+ var ENVIRONMENT_FILE_RELATIVE = "src/environment.ts";
2966
+ var CONSTANTS_FILE_RELATIVE = "src/constants.ts";
2967
+ function cleanEnvironmentFile(project, filePath) {
2968
+ const sourceFile = project.getSourceFile(filePath);
2969
+ if (!sourceFile) return [];
2970
+ const removed = [];
2971
+ const cleanEnvCall = sourceFile.getDescendantsOfKind(import_ts_morph13.SyntaxKind.CallExpression).find((call) => {
2972
+ const expr = call.getExpression();
2973
+ return import_ts_morph13.Node.isIdentifier(expr) && expr.getText() === "cleanEnv";
2974
+ });
2975
+ if (!cleanEnvCall) return removed;
2976
+ const schemaArg = cleanEnvCall.getArguments()[1]?.asKind(import_ts_morph13.SyntaxKind.ObjectLiteralExpression);
2977
+ if (!schemaArg) return removed;
2978
+ for (const name of UNUSED_ENV_VARS) {
2979
+ const prop = schemaArg.getProperty(name);
2980
+ if (!prop) continue;
2981
+ if (prop.isKind(import_ts_morph13.SyntaxKind.PropertyAssignment) || prop.isKind(import_ts_morph13.SyntaxKind.ShorthandPropertyAssignment)) {
2982
+ prop.remove();
2983
+ removed.push(name);
2984
+ }
2985
+ }
2986
+ return removed;
2987
+ }
2988
+ function extractEnvAccess(initText) {
2989
+ if (!initText) return null;
2990
+ const match = /\benv\.([A-Z][A-Z0-9_]*)\b/.exec(initText);
2991
+ return match ? match[1] : null;
2992
+ }
2993
+ function cleanConstantsFile(project, filePath) {
2994
+ const sourceFile = project.getSourceFile(filePath);
2995
+ if (!sourceFile) return [];
2996
+ const removed = [];
2997
+ for (const stmt of [...sourceFile.getVariableStatements()]) {
2998
+ const declarations = [...stmt.getDeclarations()];
2999
+ const declarationsToRemove = declarations.filter((decl) => {
3000
+ const name = decl.getName();
3001
+ const accessedEnvVar = extractEnvAccess(decl.getInitializer()?.getText());
3002
+ return UNUSED_ENV_VARS.has(name) || accessedEnvVar !== null && UNUSED_ENV_VARS.has(accessedEnvVar);
3003
+ });
3004
+ if (declarationsToRemove.length === 0) continue;
3005
+ const namesToRemove = declarationsToRemove.map((decl) => decl.getName());
3006
+ removed.push(...namesToRemove);
3007
+ if (declarationsToRemove.length === declarations.length) {
3008
+ stmt.remove();
3009
+ } else {
3010
+ for (const decl of declarationsToRemove) {
3011
+ decl.remove();
3012
+ }
3013
+ }
3014
+ }
3015
+ return removed;
3016
+ }
3017
+ async function main13() {
3018
+ const project = new import_ts_morph13.Project({
3019
+ tsConfigFilePath: import_path13.default.resolve(process.cwd(), "tsconfig.json"),
3020
+ skipAddingFilesFromTsConfig: false
3021
+ });
3022
+ console.log(
3023
+ `Removing unused environment variable(s) (${[...UNUSED_ENV_VARS].join(", ")})...
3024
+ `
3025
+ );
3026
+ const envFilePath = import_path13.default.join(process.cwd(), ENVIRONMENT_FILE_RELATIVE);
3027
+ const constsFilePath = import_path13.default.join(process.cwd(), CONSTANTS_FILE_RELATIVE);
3028
+ const envRemoved = cleanEnvironmentFile(project, envFilePath);
3029
+ if (envRemoved.length > 0) {
3030
+ await project.getSourceFileOrThrow(envFilePath).save();
3031
+ console.log(
3032
+ ` [${ENVIRONMENT_FILE_RELATIVE}] Removed schema entr${envRemoved.length === 1 ? "y" : "ies"}: ${envRemoved.join(", ")}`
3033
+ );
3034
+ } else if (project.getSourceFile(envFilePath)) {
3035
+ console.log(
3036
+ ` [${ENVIRONMENT_FILE_RELATIVE}] No matching schema entries \u2014 nothing to remove.`
3037
+ );
3038
+ } else {
3039
+ console.log(
3040
+ ` [${ENVIRONMENT_FILE_RELATIVE}] File not found \u2014 skipping.`
3041
+ );
3042
+ }
3043
+ const constsRemoved = cleanConstantsFile(project, constsFilePath);
3044
+ if (constsRemoved.length > 0) {
3045
+ await project.getSourceFileOrThrow(constsFilePath).save();
3046
+ console.log(
3047
+ ` [${CONSTANTS_FILE_RELATIVE}] Removed declaration(s): ${constsRemoved.join(", ")}`
3048
+ );
3049
+ } else if (project.getSourceFile(constsFilePath)) {
3050
+ console.log(
3051
+ ` [${CONSTANTS_FILE_RELATIVE}] No matching declarations \u2014 nothing to remove.`
3052
+ );
3053
+ } else {
3054
+ console.log(` [${CONSTANTS_FILE_RELATIVE}] File not found \u2014 skipping.`);
3055
+ }
3056
+ if (envRemoved.length === 0 && constsRemoved.length === 0) {
3057
+ console.log("\nNothing to do.");
3058
+ return;
3059
+ }
3060
+ console.log(
3061
+ `
3062
+ Done. NOTE: usages of these constants elsewhere in 'src/' may now produce TypeScript errors and need manual review.`
3063
+ );
3064
+ }
3065
+
3066
+ // src/migrations/v2.0/remove-fhir-url-helpers.ts
3067
+ var import_path14 = __toESM(require("path"));
3068
+ var import_ts_morph14 = require("ts-morph");
3069
+ var FHIR_IMPORT = "FHIR_URL";
3070
+ var HELPER_NAMES = /* @__PURE__ */ new Set([
3071
+ "getFromFhir",
3072
+ "updateResourceFromHearth",
3073
+ "updateResourceInHearth"
3074
+ ]);
3075
+ function removeHelpers(sourceFilePath, project) {
3076
+ const sourceFile = project.getSourceFile(sourceFilePath);
3077
+ if (!sourceFile) {
3078
+ return {
3079
+ removedHelpers: [],
3080
+ removedImportCount: 0,
3081
+ remainingFhirReferences: 0
3082
+ };
3083
+ }
3084
+ const removedHelpers = [];
3085
+ let removedImportCount = 0;
3086
+ for (const fn of sourceFile.getFunctions()) {
3087
+ const name = fn.getName();
3088
+ if (!name || !HELPER_NAMES.has(name)) continue;
3089
+ removedHelpers.push(name);
3090
+ fn.remove();
3091
+ }
3092
+ for (const stmt of [...sourceFile.getVariableStatements()]) {
3093
+ const declarations = [...stmt.getDeclarations()];
3094
+ const toRemove = declarations.filter((decl) => HELPER_NAMES.has(decl.getName()));
3095
+ if (toRemove.length === 0) continue;
3096
+ removedHelpers.push(...toRemove.map((decl) => decl.getName()));
3097
+ if (toRemove.length === declarations.length) {
3098
+ stmt.remove();
3099
+ } else {
3100
+ for (const decl of toRemove) decl.remove();
3101
+ }
3102
+ }
3103
+ for (const decl of sourceFile.getImportDeclarations()) {
3104
+ const matches = decl.getNamedImports().filter((ni) => ni.getName() === FHIR_IMPORT);
3105
+ if (matches.length === 0) continue;
3106
+ for (const named of matches) {
3107
+ named.remove();
3108
+ removedImportCount++;
3109
+ }
3110
+ const hasAnyNamedImportsLeft = decl.getNamedImports().length > 0;
3111
+ const hasDefaultImport = !!decl.getDefaultImport();
3112
+ const hasNamespaceImport = !!decl.getNamespaceImport();
3113
+ if (!hasAnyNamedImportsLeft && !hasDefaultImport && !hasNamespaceImport) {
3114
+ decl.remove();
3115
+ }
3116
+ }
3117
+ const remainingFhirReferences = sourceFile.getDescendantsOfKind(import_ts_morph14.SyntaxKind.Identifier).filter((id) => id.getText() === FHIR_IMPORT).filter((id) => !id.getFirstAncestorByKind(import_ts_morph14.SyntaxKind.ImportDeclaration)).length;
3118
+ return { removedHelpers, removedImportCount, remainingFhirReferences };
3119
+ }
3120
+ async function main14() {
3121
+ const project = new import_ts_morph14.Project({
3122
+ tsConfigFilePath: import_path14.default.resolve(process.cwd(), "tsconfig.json"),
3123
+ skipAddingFilesFromTsConfig: false
3124
+ });
3125
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3126
+ const fp = sf.getFilePath();
3127
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3128
+ });
3129
+ console.log(`Removing legacy FHIR_URL helpers in ${sourceFiles.length} source file(s)...
3130
+ `);
3131
+ let totalRemovedImports = 0;
3132
+ let totalRemovedHelpers = 0;
3133
+ const modifiedFiles = [];
3134
+ const warnings = [];
3135
+ for (const sourceFile of sourceFiles) {
3136
+ const filePath = sourceFile.getFilePath();
3137
+ const rel = import_path14.default.relative(process.cwd(), filePath);
3138
+ const result = removeHelpers(filePath, project);
3139
+ const changed = result.removedImportCount > 0 || result.removedHelpers.length > 0;
3140
+ if (changed) {
3141
+ modifiedFiles.push(filePath);
3142
+ totalRemovedImports += result.removedImportCount;
3143
+ totalRemovedHelpers += result.removedHelpers.length;
3144
+ if (result.removedHelpers.length > 0) {
3145
+ console.log(
3146
+ ` [${rel}] Removed helper(s): ${result.removedHelpers.join(", ")}`
3147
+ );
3148
+ }
3149
+ if (result.removedImportCount > 0) {
3150
+ console.log(
3151
+ ` [${rel}] Removed ${result.removedImportCount} '${FHIR_IMPORT}' import(s)`
3152
+ );
3153
+ }
3154
+ }
3155
+ if (result.remainingFhirReferences > 0) {
3156
+ warnings.push(
3157
+ `${rel}: ${result.remainingFhirReferences} remaining '${FHIR_IMPORT}' reference(s)`
3158
+ );
3159
+ }
3160
+ }
3161
+ if (modifiedFiles.length === 0 && warnings.length === 0) {
3162
+ console.log("No FHIR_URL imports/helpers found. Nothing to do.");
3163
+ return;
3164
+ }
3165
+ if (modifiedFiles.length > 0) {
3166
+ console.log(`
3167
+ Saving ${modifiedFiles.length} modified file(s)...`);
3168
+ for (const filePath of modifiedFiles) {
3169
+ await project.getSourceFileOrThrow(filePath).save();
3170
+ console.log(` Saved: ${import_path14.default.relative(process.cwd(), filePath)}`);
3171
+ }
3172
+ }
3173
+ if (warnings.length > 0) {
3174
+ console.warn(
3175
+ `
3176
+ WARNING: Some '${FHIR_IMPORT}' usages remain and need manual cleanup:
3177
+ ` + warnings.map((line) => ` - ${line}`).join("\n")
3178
+ );
3179
+ }
3180
+ console.log(
3181
+ `
3182
+ Done. Removed ${totalRemovedHelpers} helper declaration(s) and ${totalRemovedImports} '${FHIR_IMPORT}' import(s).`
3183
+ );
3184
+ }
3185
+
3186
+ // src/migrations/v2.0/migrate-application-config-url.ts
3187
+ var import_path15 = __toESM(require("path"));
3188
+ var import_ts_morph15 = require("ts-morph");
3189
+ var TARGET_IDENTIFIER = "APPLICATION_CONFIG_URL";
3190
+ var REPLACEMENT_IDENTIFIER = "applicationConfig";
3191
+ var REPLACEMENT_MODULE = "@countryconfig/api/application/application-config";
3192
+ var FUNCTION_LIKE_KINDS = [
3193
+ import_ts_morph15.SyntaxKind.FunctionDeclaration,
3194
+ import_ts_morph15.SyntaxKind.FunctionExpression,
3195
+ import_ts_morph15.SyntaxKind.ArrowFunction,
3196
+ import_ts_morph15.SyntaxKind.MethodDeclaration
3197
+ ];
3198
+ function describeFunction(node) {
3199
+ if (import_ts_morph15.Node.isFunctionDeclaration(node) || import_ts_morph15.Node.isMethodDeclaration(node)) {
3200
+ return node.getName() ?? "<anonymous>";
3201
+ }
3202
+ const parent = node.getParent();
3203
+ if (parent && import_ts_morph15.Node.isVariableDeclaration(parent)) {
3204
+ return parent.getName();
3205
+ }
3206
+ if (parent && import_ts_morph15.Node.isPropertyAssignment(parent)) {
3207
+ return parent.getName();
3208
+ }
3209
+ if (import_ts_morph15.Node.isFunctionExpression(node) && node.getNameNode() !== void 0) {
3210
+ return node.getNameNode()?.getText() ?? "<anonymous>";
3211
+ }
3212
+ return "<anonymous>";
3213
+ }
3214
+ function hasBlockBody(node) {
3215
+ if (import_ts_morph15.Node.isFunctionDeclaration(node) || import_ts_morph15.Node.isFunctionExpression(node) || import_ts_morph15.Node.isMethodDeclaration(node)) {
3216
+ return node.getBody() !== void 0;
3217
+ }
3218
+ if (import_ts_morph15.Node.isArrowFunction(node)) {
3219
+ return node.getBody().getKind() === import_ts_morph15.SyntaxKind.Block;
3220
+ }
3221
+ return false;
3222
+ }
3223
+ function isConfigFetcher(node) {
3224
+ let referencesTarget = false;
3225
+ let callsFetch = false;
3226
+ for (const id of node.getDescendantsOfKind(import_ts_morph15.SyntaxKind.Identifier)) {
3227
+ const text = id.getText();
3228
+ if (!referencesTarget && text === TARGET_IDENTIFIER) referencesTarget = true;
3229
+ if (!callsFetch && text === "fetch") {
3230
+ const parent = id.getParent();
3231
+ if (import_ts_morph15.Node.isCallExpression(parent) && parent.getExpression() === id) {
3232
+ callsFetch = true;
3233
+ }
3234
+ }
3235
+ if (referencesTarget && callsFetch) return true;
3236
+ }
3237
+ return false;
3238
+ }
3239
+ function processFile11(sourceFile) {
3240
+ const importsWithTarget = sourceFile.getImportDeclarations().filter(
3241
+ (decl) => decl.getNamedImports().some((ni) => ni.getName() === TARGET_IDENTIFIER)
3242
+ );
3243
+ if (importsWithTarget.length === 0) {
3244
+ return { changed: false, rewrittenFunctions: [], renamedReferences: 0 };
3245
+ }
3246
+ const collidingLocals = sourceFile.getDescendantsOfKind(import_ts_morph15.SyntaxKind.Identifier).filter((id) => id.getText() === REPLACEMENT_IDENTIFIER).filter((id) => {
3247
+ const parent = id.getParent();
3248
+ const kind = parent.getKind();
3249
+ return kind === import_ts_morph15.SyntaxKind.VariableDeclaration || kind === import_ts_morph15.SyntaxKind.FunctionDeclaration || kind === import_ts_morph15.SyntaxKind.ClassDeclaration || kind === import_ts_morph15.SyntaxKind.Parameter;
3250
+ });
3251
+ if (collidingLocals.length > 0) {
3252
+ return {
3253
+ changed: false,
3254
+ rewrittenFunctions: [],
3255
+ renamedReferences: 0,
3256
+ skippedReason: `local declaration named '${REPLACEMENT_IDENTIFIER}' would collide`
3257
+ };
3258
+ }
3259
+ const candidateFunctions = FUNCTION_LIKE_KINDS.flatMap(
3260
+ (kind) => sourceFile.getDescendantsOfKind(kind)
3261
+ );
3262
+ candidateFunctions.sort((a, b) => a.getStart() - b.getStart());
3263
+ const rewrittenFunctions = [];
3264
+ const rewrittenSet = /* @__PURE__ */ new Set();
3265
+ for (const fn of candidateFunctions) {
3266
+ if (!hasBlockBody(fn)) continue;
3267
+ if (!isConfigFetcher(fn)) continue;
3268
+ let inRewrittenAncestor = false;
3269
+ let cursor = fn.getParent();
3270
+ while (cursor) {
3271
+ if (rewrittenSet.has(cursor)) {
3272
+ inRewrittenAncestor = true;
3273
+ break;
3274
+ }
3275
+ cursor = cursor.getParent();
3276
+ }
3277
+ if (inRewrittenAncestor) continue;
3278
+ const start = fn.getStart();
3279
+ const line = sourceFile.getLineAndColumnAtPos(start).line;
3280
+ const name = describeFunction(fn);
3281
+ if (import_ts_morph15.Node.isFunctionDeclaration(fn) || import_ts_morph15.Node.isFunctionExpression(fn) || import_ts_morph15.Node.isMethodDeclaration(fn) || import_ts_morph15.Node.isArrowFunction(fn)) {
3282
+ fn.setBodyText(`return ${REPLACEMENT_IDENTIFIER}`);
3283
+ }
3284
+ rewrittenFunctions.push({ name, line });
3285
+ rewrittenSet.add(fn);
3286
+ }
3287
+ for (const decl of importsWithTarget) {
3288
+ const targetNamed = decl.getNamedImports().find((ni) => ni.getName() === TARGET_IDENTIFIER);
3289
+ targetNamed?.remove();
3290
+ const isNowEmpty = decl.getNamedImports().length === 0 && !decl.getDefaultImport() && !decl.getNamespaceImport();
3291
+ if (isNowEmpty) decl.remove();
3292
+ }
3293
+ const existing = sourceFile.getImportDeclaration(
3294
+ (decl) => decl.getModuleSpecifierValue() === REPLACEMENT_MODULE
3295
+ );
3296
+ if (existing) {
3297
+ const alreadyImported = existing.getNamedImports().some((ni) => ni.getName() === REPLACEMENT_IDENTIFIER);
3298
+ if (!alreadyImported) existing.addNamedImport(REPLACEMENT_IDENTIFIER);
3299
+ } else {
3300
+ sourceFile.addImportDeclaration({
3301
+ moduleSpecifier: REPLACEMENT_MODULE,
3302
+ namedImports: [REPLACEMENT_IDENTIFIER]
3303
+ });
3304
+ }
3305
+ const renameTargets = sourceFile.getDescendantsOfKind(import_ts_morph15.SyntaxKind.Identifier).filter((id) => id.getText() === TARGET_IDENTIFIER).filter((id) => !id.getFirstAncestorByKind(import_ts_morph15.SyntaxKind.ImportDeclaration)).filter((id) => {
3306
+ const parent = id.getParent();
3307
+ const parentKind = parent.getKind();
3308
+ if (parentKind === import_ts_morph15.SyntaxKind.PropertyAccessExpression) {
3309
+ const pae = parent.asKind(import_ts_morph15.SyntaxKind.PropertyAccessExpression);
3310
+ if (pae.getNameNode() === id) return false;
3311
+ }
3312
+ if (parentKind === import_ts_morph15.SyntaxKind.PropertyAssignment) {
3313
+ const pa = parent.asKind(import_ts_morph15.SyntaxKind.PropertyAssignment);
3314
+ if (pa.getNameNode() === id) return false;
3315
+ }
3316
+ if (parentKind === import_ts_morph15.SyntaxKind.ShorthandPropertyAssignment) {
3317
+ return false;
3318
+ }
3319
+ return true;
3320
+ }).sort((a, b) => b.getPos() - a.getPos());
3321
+ for (const id of renameTargets) {
3322
+ id.replaceWithText(REPLACEMENT_IDENTIFIER);
3323
+ }
3324
+ return {
3325
+ changed: true,
3326
+ rewrittenFunctions,
3327
+ renamedReferences: renameTargets.length
3328
+ };
3329
+ }
3330
+ async function main15() {
3331
+ const project = new import_ts_morph15.Project({
3332
+ tsConfigFilePath: import_path15.default.resolve(process.cwd(), "tsconfig.json"),
3333
+ skipAddingFilesFromTsConfig: false
3334
+ });
3335
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3336
+ const fp = sf.getFilePath();
3337
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3338
+ });
3339
+ console.log(
3340
+ `Migrating '${TARGET_IDENTIFIER}' \u2192 '${REPLACEMENT_IDENTIFIER}' across ${sourceFiles.length} source file(s)...
3341
+ `
3342
+ );
3343
+ let changedFiles = 0;
3344
+ let totalRewrittenFunctions = 0;
3345
+ let totalRenamedReferences = 0;
3346
+ const skipped = [];
3347
+ for (const sourceFile of sourceFiles) {
3348
+ const filePath = sourceFile.getFilePath();
3349
+ const rel = import_path15.default.relative(process.cwd(), filePath);
3350
+ const result = processFile11(sourceFile);
3351
+ if (result.skippedReason) {
3352
+ skipped.push(`${rel} (${result.skippedReason})`);
3353
+ continue;
3354
+ }
3355
+ if (!result.changed) continue;
3356
+ await sourceFile.save();
3357
+ changedFiles++;
3358
+ totalRewrittenFunctions += result.rewrittenFunctions.length;
3359
+ totalRenamedReferences += result.renamedReferences;
3360
+ for (const fn of result.rewrittenFunctions) {
3361
+ console.log(
3362
+ ` [${rel}:${fn.line}] Rewrote '${fn.name}' body \u2192 'return ${REPLACEMENT_IDENTIFIER}' (config fetch eliminated)`
3363
+ );
3364
+ }
3365
+ if (result.renamedReferences > 0) {
3366
+ console.log(
3367
+ ` [${rel}] Renamed ${result.renamedReferences} stray reference(s) ${TARGET_IDENTIFIER} \u2192 ${REPLACEMENT_IDENTIFIER}`
3368
+ );
3369
+ }
3370
+ }
3371
+ if (skipped.length > 0) {
3372
+ console.warn(
3373
+ `
3374
+ ${skipped.length} file(s) skipped:
3375
+ ` + skipped.map((s) => ` - ${s}`).join("\n")
3376
+ );
3377
+ }
3378
+ if (changedFiles === 0) {
3379
+ console.log(`
3380
+ No files reference '${TARGET_IDENTIFIER}'. Nothing to do.`);
3381
+ return;
3382
+ }
3383
+ console.log(
3384
+ `
3385
+ Done. Updated ${changedFiles} file(s): ${totalRewrittenFunctions} fetch function(s) rewritten, ${totalRenamedReferences} bare reference(s) renamed.`
3386
+ );
3387
+ if (totalRewrittenFunctions > 0) {
3388
+ console.log(
3389
+ `NOTE: rewriting fetch functions discards any custom logic that lived inside them. Review the diff and re-apply any country-specific adjustments on top of '${REPLACEMENT_IDENTIFIER}'.`
3390
+ );
3391
+ }
3392
+ }
3393
+
3394
+ // src/migrations/v2.0/remove-old-statistics-service.ts
3395
+ var import_path16 = __toESM(require("path"));
3396
+ var import_ts_morph16 = require("ts-morph");
3397
+ var ROUTE_PATH = "/statistics";
3398
+ var HANDLER_NAME = "statisticsHandler";
3399
+ function isStatisticsRouteObject(obj) {
3400
+ const pathProp = obj.getProperty("path");
3401
+ if (!pathProp || !import_ts_morph16.Node.isPropertyAssignment(pathProp)) return false;
3402
+ const init = pathProp.getInitializer();
3403
+ if (!init) return false;
3404
+ if (import_ts_morph16.Node.isStringLiteral(init) || import_ts_morph16.Node.isNoSubstitutionTemplateLiteral(init)) {
3405
+ return init.getLiteralValue() === ROUTE_PATH;
3406
+ }
3407
+ return false;
3408
+ }
3409
+ function removeStatisticsRoutes(sourceFile) {
3410
+ let removed = 0;
3411
+ const callExpressions = [
3412
+ ...sourceFile.getDescendantsOfKind(import_ts_morph16.SyntaxKind.CallExpression)
3413
+ ];
3414
+ for (const call of callExpressions) {
3415
+ if (call.wasForgotten()) continue;
3416
+ const expr = call.getExpression();
3417
+ if (!import_ts_morph16.Node.isPropertyAccessExpression(expr)) continue;
3418
+ if (expr.getName() !== "route") continue;
3419
+ const args = call.getArguments();
3420
+ if (args.length === 0) continue;
3421
+ const firstArg = args[0];
3422
+ if (import_ts_morph16.Node.isObjectLiteralExpression(firstArg)) {
3423
+ if (!isStatisticsRouteObject(firstArg)) continue;
3424
+ const stmt = call.getFirstAncestorByKind(import_ts_morph16.SyntaxKind.ExpressionStatement);
3425
+ if (stmt) {
3426
+ stmt.remove();
3427
+ removed++;
3428
+ } else {
3429
+ call.replaceWithText("");
3430
+ removed++;
3431
+ }
3432
+ continue;
3433
+ }
3434
+ if (import_ts_morph16.Node.isArrayLiteralExpression(firstArg)) {
3435
+ const matchingIndexes = firstArg.getElements().map((el, idx) => ({ el, idx })).filter(
3436
+ ({ el }) => import_ts_morph16.Node.isObjectLiteralExpression(el) && isStatisticsRouteObject(el)
3437
+ ).map(({ idx }) => idx);
3438
+ matchingIndexes.sort((a, b) => b - a).forEach((idx) => {
3439
+ firstArg.removeElement(idx);
3440
+ removed++;
3441
+ });
3442
+ }
3443
+ }
3444
+ return removed;
3445
+ }
3446
+ function removeStatisticsHandlerImports(sourceFile) {
3447
+ let changed = false;
3448
+ for (const decl of sourceFile.getImportDeclarations()) {
3449
+ const targetNamed = decl.getNamedImports().find((ni) => ni.getName() === HANDLER_NAME);
3450
+ if (!targetNamed) continue;
3451
+ targetNamed.remove();
3452
+ changed = true;
3453
+ const isNowEmpty = decl.getNamedImports().length === 0 && !decl.getDefaultImport() && !decl.getNamespaceImport();
3454
+ if (isNowEmpty) decl.remove();
3455
+ }
3456
+ return changed;
3457
+ }
3458
+ function processFile12(sourceFile) {
3459
+ const routesRemoved = removeStatisticsRoutes(sourceFile);
3460
+ const importsCleaned = removeStatisticsHandlerImports(sourceFile);
3461
+ return { routesRemoved, importsCleaned };
3462
+ }
3463
+ function collectLocalImportsInSubtree(sourceFile, subtreeRoot) {
3464
+ const result = [];
3465
+ for (const decl of sourceFile.getImportDeclarations()) {
3466
+ const moduleSf = decl.getModuleSpecifierSourceFile();
3467
+ if (!moduleSf) continue;
3468
+ const fp = moduleSf.getFilePath();
3469
+ if (!fp.startsWith(subtreeRoot)) continue;
3470
+ result.push(fp);
3471
+ }
3472
+ return result;
3473
+ }
3474
+ function deleteOrphanedDescendants(project, startingFile, subtreeRoot) {
3475
+ const initialCandidates = collectLocalImportsInSubtree(
3476
+ startingFile,
3477
+ subtreeRoot
3478
+ );
3479
+ const startingPath = startingFile.getFilePath();
3480
+ const deleted = /* @__PURE__ */ new Set([startingPath]);
3481
+ const seen = /* @__PURE__ */ new Set();
3482
+ const worklist = [...initialCandidates];
3483
+ const orphans = [];
3484
+ while (worklist.length > 0) {
3485
+ const candidate = worklist.shift();
3486
+ if (seen.has(candidate)) continue;
3487
+ seen.add(candidate);
3488
+ if (deleted.has(candidate)) continue;
3489
+ if (!candidate.startsWith(subtreeRoot)) continue;
3490
+ const candidateSf = project.getSourceFile(candidate);
3491
+ if (!candidateSf) continue;
3492
+ const stillImported = project.getSourceFiles().some((sf) => {
3493
+ const sfPath = sf.getFilePath();
3494
+ if (deleted.has(sfPath)) return false;
3495
+ if (sfPath === candidate) return false;
3496
+ return sf.getImportDeclarations().some(
3497
+ (decl) => decl.getModuleSpecifierSourceFile()?.getFilePath() === candidate
3498
+ );
3499
+ });
3500
+ if (stillImported) continue;
3501
+ const next = collectLocalImportsInSubtree(candidateSf, subtreeRoot);
3502
+ worklist.push(...next);
3503
+ candidateSf.delete();
3504
+ deleted.add(candidate);
3505
+ orphans.push(candidate);
3506
+ }
3507
+ return orphans;
3508
+ }
3509
+ function processHandlerFile(project) {
3510
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3511
+ const fp = sf.getFilePath();
3512
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3513
+ });
3514
+ for (const sf of sourceFiles) {
3515
+ const fn = sf.getFunction(HANDLER_NAME);
3516
+ if (!fn) continue;
3517
+ const filePath = sf.getFilePath();
3518
+ const exportsByName = [...sf.getExportedDeclarations().keys()];
3519
+ const otherExports = exportsByName.filter((name) => name !== HANDLER_NAME);
3520
+ if (otherExports.length === 0) {
3521
+ const subtreeRoot = import_path16.default.dirname(filePath) + import_path16.default.sep;
3522
+ const orphansDeleted = deleteOrphanedDescendants(
3523
+ project,
3524
+ sf,
3525
+ subtreeRoot
3526
+ );
3527
+ sf.delete();
3528
+ return { filePath, action: "deleted", orphansDeleted };
3529
+ }
3530
+ fn.remove();
3531
+ return {
3532
+ filePath,
3533
+ action: "function-removed",
3534
+ remainingExports: otherExports,
3535
+ orphansDeleted: []
3536
+ };
3537
+ }
3538
+ return { filePath: "", action: "not-found", orphansDeleted: [] };
3539
+ }
3540
+ async function main16() {
3541
+ const project = new import_ts_morph16.Project({
3542
+ tsConfigFilePath: import_path16.default.resolve(process.cwd(), "tsconfig.json"),
3543
+ skipAddingFilesFromTsConfig: false
3544
+ });
3545
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3546
+ const fp = sf.getFilePath();
3547
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3548
+ });
3549
+ console.log(
3550
+ `Removing legacy 'GET ${ROUTE_PATH}' route and '${HANDLER_NAME}' across ${sourceFiles.length} source file(s)...
3551
+ `
3552
+ );
3553
+ let totalRoutesRemoved = 0;
3554
+ let totalFilesWithImportsCleaned = 0;
3555
+ let totalFilesWithRoutesRemoved = 0;
3556
+ for (const sourceFile of sourceFiles) {
3557
+ const filePath = sourceFile.getFilePath();
3558
+ const rel = import_path16.default.relative(process.cwd(), filePath);
3559
+ const result = processFile12(sourceFile);
3560
+ if (result.routesRemoved > 0) {
3561
+ console.log(
3562
+ ` [${rel}] Removed ${result.routesRemoved} '${ROUTE_PATH}' route(s)`
3563
+ );
3564
+ totalRoutesRemoved += result.routesRemoved;
3565
+ totalFilesWithRoutesRemoved++;
3566
+ }
3567
+ if (result.importsCleaned) {
3568
+ console.log(` [${rel}] Cleaned up '${HANDLER_NAME}' import`);
3569
+ totalFilesWithImportsCleaned++;
3570
+ }
3571
+ if (result.routesRemoved > 0 || result.importsCleaned) {
3572
+ await sourceFile.save();
3573
+ }
3574
+ }
3575
+ const handlerResult = processHandlerFile(project);
3576
+ switch (handlerResult.action) {
3577
+ case "deleted": {
3578
+ const rel = import_path16.default.relative(process.cwd(), handlerResult.filePath);
3579
+ console.log(
3580
+ ` [${rel}] Deleted handler file ('${HANDLER_NAME}' was the sole export).`
3581
+ );
3582
+ for (const orphanPath of handlerResult.orphansDeleted) {
3583
+ const orphanRel = import_path16.default.relative(process.cwd(), orphanPath);
3584
+ console.log(
3585
+ ` [${orphanRel}] Deleted (no remaining importers in the project after handler removal).`
3586
+ );
3587
+ }
3588
+ await project.save();
3589
+ break;
3590
+ }
3591
+ case "function-removed": {
3592
+ const rel = import_path16.default.relative(process.cwd(), handlerResult.filePath);
3593
+ console.warn(
3594
+ ` [${rel}] Removed '${HANDLER_NAME}' function but kept the file (other exports remain: ${handlerResult.remainingExports?.join(", ")}). Review whether the file is still needed.`
3595
+ );
3596
+ const sf = project.getSourceFile(handlerResult.filePath);
3597
+ if (sf) await sf.save();
3598
+ break;
3599
+ }
3600
+ case "not-found":
3601
+ break;
3602
+ }
3603
+ if (totalRoutesRemoved === 0 && totalFilesWithImportsCleaned === 0 && handlerResult.action === "not-found") {
3604
+ console.log(`
3605
+ No legacy '${ROUTE_PATH}' route or handler found. Nothing to do.`);
3606
+ return;
3607
+ }
3608
+ const orphansSummary = handlerResult.orphansDeleted.length > 0 ? ` and ${handlerResult.orphansDeleted.length} orphaned helper file(s)` : "";
3609
+ console.log(
3610
+ `
3611
+ Done. Removed ${totalRoutesRemoved} route(s) across ${totalFilesWithRoutesRemoved} file(s); cleaned ${HANDLER_NAME} import in ${totalFilesWithImportsCleaned} file(s)${orphansSummary}.`
3612
+ );
3613
+ }
3614
+
3615
+ // src/migrations/v2.0/update-package-json.ts
3616
+ var import_fs = require("fs");
3617
+ var import_path17 = __toESM(require("path"));
3618
+ var PACKAGE_JSON_RELATIVE = "package.json";
3619
+ var TARGET_VERSION = "2.0.0";
3620
+ var TARGET_ZOD_RANGE = "^4.2.1";
3621
+ async function main17() {
3622
+ const packageJsonPath = import_path17.default.join(process.cwd(), PACKAGE_JSON_RELATIVE);
3623
+ if (!(0, import_fs.existsSync)(packageJsonPath)) {
3624
+ console.log(`'${PACKAGE_JSON_RELATIVE}' not found in ${process.cwd()} \u2014 skipping.`);
3625
+ return;
3626
+ }
3627
+ const raw = (0, import_fs.readFileSync)(packageJsonPath, "utf8");
3628
+ let parsed;
3629
+ try {
3630
+ parsed = JSON.parse(raw);
3631
+ } catch (error) {
3632
+ console.warn(
3633
+ ` [${PACKAGE_JSON_RELATIVE}] Failed to parse JSON \u2014 skipping update. ${error.message}`
3634
+ );
3635
+ return;
3636
+ }
3637
+ console.log(`Updating '${PACKAGE_JSON_RELATIVE}'...`);
3638
+ const previousVersion = parsed.version;
3639
+ const versionChanged = previousVersion !== TARGET_VERSION;
3640
+ parsed.version = TARGET_VERSION;
3641
+ if (versionChanged) {
3642
+ console.log(
3643
+ ` Set version: ${previousVersion ?? "<unset>"} \u2192 ${TARGET_VERSION}`
3644
+ );
3645
+ } else {
3646
+ console.log(` Version already ${TARGET_VERSION} \u2014 no change.`);
3647
+ }
3648
+ let zodBucket = "dependencies";
3649
+ if (parsed.devDependencies && "zod" in parsed.devDependencies) {
3650
+ zodBucket = "devDependencies";
3651
+ }
3652
+ if (!parsed[zodBucket]) {
3653
+ parsed[zodBucket] = {};
3654
+ }
3655
+ const bucket = parsed[zodBucket];
3656
+ const previousZod = bucket.zod;
3657
+ const zodChanged = previousZod !== TARGET_ZOD_RANGE;
3658
+ bucket.zod = TARGET_ZOD_RANGE;
3659
+ if (zodChanged) {
3660
+ console.log(
3661
+ ` Set ${zodBucket}.zod: ${previousZod ?? "<absent>"} \u2192 ${TARGET_ZOD_RANGE}`
3662
+ );
3663
+ } else {
3664
+ console.log(` ${zodBucket}.zod already ${TARGET_ZOD_RANGE} \u2014 no change.`);
3665
+ }
3666
+ const trailingNewline = raw.endsWith("\n") ? "\n" : "";
3667
+ const next = JSON.stringify(parsed, null, 2) + trailingNewline;
3668
+ if (next === raw) {
3669
+ console.log("\n No changes to write.");
3670
+ return;
3671
+ }
3672
+ (0, import_fs.writeFileSync)(packageJsonPath, next, "utf8");
3673
+ console.log(`
3674
+ Saved '${PACKAGE_JSON_RELATIVE}'.`);
3675
+ console.log(
3676
+ ` NOTE: run \`yarn install\` (or your package manager equivalent) to install the updated dependency versions.`
3677
+ );
3678
+ }
3679
+
3680
+ // src/migrations/v2.0/migrate-workqueue-configs.ts
3681
+ var import_ts_morph17 = require("ts-morph");
3682
+ var import_path18 = __toESM(require("path"));
3683
+ var DEFINE_WORKQUEUES_NAME3 = "defineWorkqueues";
3684
+ var ACTIONS_PROPERTY_NAME5 = "actions";
3685
+ var ACTION_PROPERTY_NAME2 = "action";
3686
+ var CONDITIONALS_PROPERTY_NAME = "conditionals";
3687
+ var TYPE_PROPERTY_NAME7 = "type";
3688
+ var SLUG_PROPERTY_NAME = "slug";
3689
+ var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
3690
+ "READ",
3691
+ "DELETE",
3692
+ "DECLARE",
3693
+ "REGISTER",
3694
+ "EDIT",
3695
+ "REJECT",
3696
+ "MARK_AS_DUPLICATE",
3697
+ "ARCHIVE",
3698
+ "PRINT_CERTIFICATE",
3699
+ "REQUEST_CORRECTION"
3700
+ ]);
3701
+ function getWorkqueueLabel(workqueue) {
3702
+ const slugProperty = workqueue.getProperty(SLUG_PROPERTY_NAME);
3703
+ if (!slugProperty || !import_ts_morph17.Node.isPropertyAssignment(slugProperty)) {
3704
+ return "(unknown slug)";
3705
+ }
3706
+ const slugInitializer = slugProperty.getInitializer();
3707
+ if (!slugInitializer || !import_ts_morph17.Node.isStringLiteral(slugInitializer)) {
3708
+ return "(unknown slug)";
3709
+ }
3710
+ return slugInitializer.getLiteralValue();
3711
+ }
3712
+ function getActionTypeName(action) {
3713
+ const typeProperty = action.getProperty(TYPE_PROPERTY_NAME7);
3714
+ if (!typeProperty || !import_ts_morph17.Node.isPropertyAssignment(typeProperty)) {
3715
+ return null;
3716
+ }
3717
+ const typeInitializer = typeProperty.getInitializer();
3718
+ if (!typeInitializer) {
3719
+ return null;
3720
+ }
3721
+ if (import_ts_morph17.Node.isStringLiteral(typeInitializer)) {
3722
+ return typeInitializer.getLiteralValue();
3723
+ }
3724
+ if (import_ts_morph17.Node.isPropertyAccessExpression(typeInitializer)) {
3725
+ return typeInitializer.getName();
3726
+ }
3727
+ return null;
3728
+ }
3729
+ function isUnsupportedActionType(action) {
3730
+ const typeName = getActionTypeName(action);
3731
+ if (!typeName) {
3732
+ return false;
3733
+ }
3734
+ return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3735
+ }
3736
+ function migrateWorkqueueActions(workqueue, relPath) {
3737
+ const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3738
+ if (!actionsProperty || !import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3739
+ return 0;
3740
+ }
3741
+ const actionsInitializer = actionsProperty.getInitializer();
3742
+ if (!actionsInitializer || !import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3743
+ return 0;
3744
+ }
3745
+ const workqueueLabel = getWorkqueueLabel(workqueue);
3746
+ const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3747
+ if (existingActionProperty) {
3748
+ if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3749
+ const existingActionInitializer = existingActionProperty.getInitializer();
3750
+ if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3751
+ const conditionalsProperty2 = existingActionInitializer.getProperty(
3752
+ CONDITIONALS_PROPERTY_NAME
3753
+ );
3754
+ if (conditionalsProperty2) {
3755
+ conditionalsProperty2.remove();
3756
+ console.log(
3757
+ ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3758
+ );
3759
+ }
3760
+ if (isUnsupportedActionType(existingActionInitializer)) {
3761
+ existingActionProperty.remove();
3762
+ console.log(
3763
+ ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
3764
+ );
3765
+ }
3766
+ }
3767
+ }
3768
+ actionsProperty.remove();
3769
+ console.log(
3770
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3771
+ );
3772
+ return 1;
3773
+ }
3774
+ const actionCandidates = actionsInitializer.getElements().filter(
3775
+ (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3776
+ );
3777
+ if (actionCandidates.length === 0) {
3778
+ actionsProperty.remove();
3779
+ console.log(
3780
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3781
+ );
3782
+ return 1;
3783
+ }
3784
+ if (actionCandidates.length > 1) {
3785
+ const droppedCount = actionCandidates.length - 1;
3786
+ console.warn(
3787
+ ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3788
+ );
3789
+ }
3790
+ const conditionalsProperty = actionCandidates[0].getProperty(
3791
+ CONDITIONALS_PROPERTY_NAME
3792
+ );
3793
+ if (conditionalsProperty) {
3794
+ conditionalsProperty.remove();
3795
+ console.log(
3796
+ ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3797
+ );
3798
+ }
3799
+ if (isUnsupportedActionType(actionCandidates[0])) {
3800
+ actionsProperty.remove();
3801
+ console.log(
3802
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3803
+ );
3804
+ return 1;
3805
+ }
3806
+ const firstActionText = actionCandidates[0].getText();
3807
+ workqueue.addPropertyAssignment({
3808
+ name: ACTION_PROPERTY_NAME2,
3809
+ initializer: firstActionText
3810
+ });
3811
+ actionsProperty.remove();
3812
+ console.log(
3813
+ ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3814
+ );
3815
+ return 1;
3816
+ }
3817
+ function processFile13(filePath, project) {
3818
+ const sourceFile = project.getSourceFile(filePath);
3819
+ if (!sourceFile) return 0;
3820
+ let migratedWorkqueues = 0;
3821
+ const relPath = import_path18.default.relative(process.cwd(), filePath);
3822
+ const callExpressions = sourceFile.getDescendantsOfKind(
3823
+ import_ts_morph17.SyntaxKind.CallExpression
3824
+ );
3825
+ for (const call of callExpressions) {
3826
+ const expression = call.getExpression();
3827
+ if (!import_ts_morph17.Node.isIdentifier(expression) || expression.getText() !== DEFINE_WORKQUEUES_NAME3) {
3828
+ continue;
3829
+ }
3830
+ const args = call.getArguments();
3831
+ if (args.length === 0) continue;
3832
+ const workqueuesArg = args[0];
3833
+ if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3834
+ for (const element of workqueuesArg.getElements()) {
3835
+ if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3836
+ migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3837
+ }
3838
+ }
3839
+ return migratedWorkqueues;
3840
+ }
3841
+ async function main18() {
3842
+ const srcDir = import_path18.default.join(process.cwd(), "src");
3843
+ console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
3844
+ `);
3845
+ const project = new import_ts_morph17.Project({
3846
+ tsConfigFilePath: import_path18.default.resolve(srcDir, "../tsconfig.json"),
3847
+ skipAddingFilesFromTsConfig: false
3848
+ });
3849
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3850
+ const fp = sf.getFilePath();
3851
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3852
+ });
3853
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3854
+ `);
3855
+ let totalMigrated = 0;
3856
+ const modifiedFiles = [];
3857
+ for (const sourceFile of sourceFiles) {
3858
+ const filePath = sourceFile.getFilePath();
3859
+ const migrated = processFile13(filePath, project);
3860
+ if (migrated > 0) {
3861
+ totalMigrated += migrated;
3862
+ modifiedFiles.push(filePath);
3863
+ }
3864
+ }
3865
+ if (modifiedFiles.length === 0) {
3866
+ console.log(
3867
+ "No deprecated workqueue 'actions' arrays found inside defineWorkqueues calls. Nothing to do."
3868
+ );
3869
+ return;
3870
+ }
3871
+ console.log(`
3872
+ Saving ${modifiedFiles.length} modified file(s)...`);
3873
+ for (const filePath of modifiedFiles) {
3874
+ const sourceFile = project.getSourceFileOrThrow(filePath);
3875
+ await sourceFile.save();
3876
+ console.log(` Saved: ${import_path18.default.relative(process.cwd(), filePath)}`);
3877
+ }
3878
+ console.log(
3879
+ `
3880
+ Done. Migrated ${totalMigrated} deprecated workqueue 'actions' definition(s) to 'action'.`
3881
+ );
3882
+ }
3883
+
3884
+ // src/migrations/v2.0/remove-demo-scope.ts
3885
+ var import_path19 = __toESM(require("path"));
3886
+ var import_ts_morph18 = require("ts-morph");
3887
+ var ROLES_HANDLER_RELATIVE_PATH = "src/data-seeding/roles/handler.ts";
3888
+ async function main19() {
3889
+ const rolesHandlerPath = import_path19.default.join(process.cwd(), ROLES_HANDLER_RELATIVE_PATH);
3890
+ const project = new import_ts_morph18.Project({
3891
+ tsConfigFilePath: import_path19.default.resolve(process.cwd(), "tsconfig.json"),
3892
+ skipAddingFilesFromTsConfig: false
3893
+ });
3894
+ const sourceFile = project.getSourceFile(rolesHandlerPath);
3895
+ if (!sourceFile) {
3896
+ console.log(
3897
+ `No roles handler found at '${ROLES_HANDLER_RELATIVE_PATH}'. Nothing to do.`
3898
+ );
3899
+ return;
3900
+ }
3901
+ let changed = false;
3902
+ const constantsImport = sourceFile.getImportDeclaration(
3903
+ (decl) => decl.getModuleSpecifierValue() === "@countryconfig/constants"
3904
+ );
3905
+ if (constantsImport) {
3906
+ constantsImport.remove();
3907
+ changed = true;
3908
+ }
3909
+ const rolesHandler = sourceFile.getFunction("rolesHandler");
3910
+ if (!rolesHandler) {
3911
+ console.log(
3912
+ `No rolesHandler export found in '${ROLES_HANDLER_RELATIVE_PATH}'. Nothing to do.`
3913
+ );
3914
+ return;
3915
+ }
3916
+ const secondParam = rolesHandler.getParameters()[1];
3917
+ const secondParamName = secondParam?.getName();
3918
+ const responseToolkitIdentifier = secondParamName || "h";
3919
+ const currentBodyText = rolesHandler.getBodyText();
3920
+ const normalizedCurrent = currentBodyText?.replace(/\s+/g, " ").trim() ?? "";
3921
+ const normalizedDesired = `return ${responseToolkitIdentifier}.response(roles)`;
3922
+ if (normalizedCurrent !== normalizedDesired) {
3923
+ rolesHandler.setBodyText(`return ${responseToolkitIdentifier}.response(roles)`);
3924
+ changed = true;
3925
+ }
3926
+ if (!changed) {
3927
+ console.log(
3928
+ `No changes needed in '${ROLES_HANDLER_RELATIVE_PATH}'.`
3929
+ );
3930
+ return;
3931
+ }
3932
+ await sourceFile.save();
3933
+ console.log(
3934
+ `Updated '${ROLES_HANDLER_RELATIVE_PATH}' to remove demo scope behavior while preserving file structure.`
3935
+ );
3936
+ }
3937
+
3938
+ // src/migrations/v2.0/remove-hearth-migrations.ts
3939
+ var fs2 = __toESM(require("fs"));
3940
+ var import_path20 = __toESM(require("path"));
3941
+ var PATHS_TO_REMOVE = [
3942
+ {
3943
+ relativePath: "src/migrations/hearth",
3944
+ label: "Hearth migrations directory"
3945
+ },
3946
+ {
3947
+ relativePath: "src/migrations/user-mgnt",
3948
+ label: "user-mgnt migrations directory"
3949
+ },
3950
+ { relativePath: "src/utils/hearth-helpers.ts", label: "Hearth helpers file" }
3951
+ ];
3952
+ async function main20() {
3953
+ for (const { relativePath, label } of PATHS_TO_REMOVE) {
3954
+ const absolutePath = import_path20.default.join(process.cwd(), relativePath);
3955
+ if (fs2.existsSync(absolutePath)) {
3956
+ fs2.rmSync(absolutePath, { recursive: true, force: true });
3957
+ console.log(`Removed ${label} '${relativePath}'.`);
3958
+ } else {
3959
+ console.log(`No ${label} found at '${relativePath}'.`);
3960
+ }
3961
+ }
3962
+ }
3963
+
3964
+ // src/migrations/v2.0/create-events-index.ts
3965
+ var import_ts_morph19 = require("ts-morph");
3966
+ var import_fs2 = __toESM(require("fs"));
3967
+ var import_path21 = __toESM(require("path"));
3968
+ var DEFINE_CONFIG_NAME5 = "defineConfig";
3969
+ var HANDLER_FUNCTION_NAMES = /* @__PURE__ */ new Set([
3970
+ "getCustomEventsHandler",
3971
+ "getEventsHandler"
3972
+ ]);
3973
+ var EVENT_CONFIGS_IDENTIFIER = "eventConfigs";
3974
+ var EVENTS_INDEX_IMPORT_PATH = "@countryconfig/events";
3975
+ var RESPONSE_METHOD_NAME = "response";
3976
+ var LICENSE_HEADER = `/*
3977
+ * This Source Code Form is subject to the terms of the Mozilla Public
3978
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
3979
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
3980
+ *
3981
+ * OpenCRVS is also distributed under the terms of the Civil Registration
3982
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
3983
+ *
3984
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
3985
+ */
3986
+ `;
3987
+ function findEventConfigExports(project, srcDir) {
3988
+ const found = [];
3989
+ const eventsIndexAbs = import_path21.default.join(srcDir, "events", "index.ts");
3990
+ for (const sourceFile of project.getSourceFiles()) {
3991
+ const filePath = sourceFile.getFilePath();
3992
+ if (!filePath.startsWith(srcDir) || filePath.includes("/node_modules/")) {
3993
+ continue;
3994
+ }
3995
+ if (filePath === eventsIndexAbs) continue;
3996
+ for (const statement of sourceFile.getVariableStatements()) {
3997
+ if (!statement.hasExportKeyword()) continue;
3998
+ for (const decl of statement.getDeclarations()) {
3999
+ const initializer = decl.getInitializer();
4000
+ if (!initializer) continue;
4001
+ const unwrapped = import_ts_morph19.Node.isAsExpression(initializer) ? initializer.getExpression() : initializer;
4002
+ if (!import_ts_morph19.Node.isCallExpression(unwrapped)) continue;
4003
+ const callee = unwrapped.getExpression();
4004
+ if (!import_ts_morph19.Node.isIdentifier(callee)) continue;
4005
+ if (callee.getText() !== DEFINE_CONFIG_NAME5) continue;
4006
+ found.push({ name: decl.getName(), filePath });
4007
+ }
4008
+ }
4009
+ }
4010
+ return found;
4011
+ }
4012
+ function buildIndexImportSpecifier(eventConfigFilePath, srcDir) {
4013
+ const eventsIndexDir = import_path21.default.join(srcDir, "events");
4014
+ let rel = import_path21.default.relative(eventsIndexDir, eventConfigFilePath).split(import_path21.default.sep).join("/");
4015
+ if (rel.endsWith(".ts")) rel = rel.slice(0, -".ts".length);
4016
+ if (rel.endsWith("/index")) rel = rel.slice(0, -"/index".length);
4017
+ if (!rel.startsWith(".")) rel = "./" + rel;
4018
+ return rel;
4019
+ }
4020
+ function buildEventsIndexSource(exports, srcDir) {
4021
+ const imports = exports.map(
4022
+ (e) => `import { ${e.name} } from '${buildIndexImportSpecifier(
4023
+ e.filePath,
4024
+ srcDir
4025
+ )}'`
4026
+ ).join("\n");
4027
+ const array3 = `export const ${EVENT_CONFIGS_IDENTIFIER} = [${exports.map((e) => e.name).join(", ")}]`;
4028
+ return `${LICENSE_HEADER}${imports}
4029
+
4030
+ ${array3}
4031
+ `;
4032
+ }
4033
+ function findHandlerSourceFile(project, srcDir) {
4034
+ for (const sf of project.getSourceFiles()) {
4035
+ const fp = sf.getFilePath();
4036
+ if (!fp.startsWith(srcDir) || fp.includes("/node_modules/")) continue;
4037
+ for (const fn of sf.getFunctions()) {
4038
+ const name = fn.getName();
4039
+ if (name && HANDLER_FUNCTION_NAMES.has(name)) return sf;
4040
+ }
4041
+ for (const statement of sf.getVariableStatements()) {
4042
+ for (const decl of statement.getDeclarations()) {
4043
+ if (HANDLER_FUNCTION_NAMES.has(decl.getName())) return sf;
4044
+ }
4045
+ }
4046
+ }
4047
+ return void 0;
4048
+ }
4049
+ function modifyHandler(sourceFile, exportNames) {
4050
+ const changes = [];
4051
+ for (const importDecl of [...sourceFile.getImportDeclarations()]) {
4052
+ const namedImports = importDecl.getNamedImports();
4053
+ if (namedImports.length === 0) continue;
4054
+ const matched = namedImports.filter((ni) => exportNames.has(ni.getName()));
4055
+ if (matched.length === 0) continue;
4056
+ const removedNames = matched.map((ni) => ni.getName());
4057
+ for (const ni of matched) ni.remove();
4058
+ changes.push(`removed direct imports: ${removedNames.join(", ")}`);
4059
+ const stillUsed = importDecl.getNamedImports().length > 0 || importDecl.getDefaultImport() || importDecl.getNamespaceImport();
4060
+ if (!stillUsed) importDecl.remove();
4061
+ }
4062
+ for (const statement of [...sourceFile.getVariableStatements()]) {
4063
+ if (!statement.hasExportKeyword()) continue;
4064
+ const hasEventConfigs = statement.getDeclarations().some((d) => d.getName() === EVENT_CONFIGS_IDENTIFIER);
4065
+ if (hasEventConfigs) {
4066
+ statement.remove();
4067
+ changes.push(`removed inline 'export const ${EVENT_CONFIGS_IDENTIFIER}'`);
4068
+ }
4069
+ }
4070
+ const existing = sourceFile.getImportDeclaration(
4071
+ (imp) => imp.getModuleSpecifierValue() === EVENTS_INDEX_IMPORT_PATH
4072
+ );
4073
+ if (existing) {
4074
+ const already = existing.getNamedImports().some((ni) => ni.getName() === EVENT_CONFIGS_IDENTIFIER);
4075
+ if (!already) {
4076
+ existing.addNamedImport(EVENT_CONFIGS_IDENTIFIER);
4077
+ changes.push(
4078
+ `added '${EVENT_CONFIGS_IDENTIFIER}' to existing import from '${EVENTS_INDEX_IMPORT_PATH}'`
4079
+ );
4080
+ }
4081
+ } else {
4082
+ sourceFile.addImportDeclaration({
4083
+ moduleSpecifier: EVENTS_INDEX_IMPORT_PATH,
4084
+ namedImports: [EVENT_CONFIGS_IDENTIFIER]
4085
+ });
4086
+ changes.push(
4087
+ `added import { ${EVENT_CONFIGS_IDENTIFIER} } from '${EVENTS_INDEX_IMPORT_PATH}'`
4088
+ );
4089
+ }
4090
+ for (const call of sourceFile.getDescendantsOfKind(
4091
+ import_ts_morph19.SyntaxKind.CallExpression
4092
+ )) {
4093
+ const callee = call.getExpression();
4094
+ if (!import_ts_morph19.Node.isPropertyAccessExpression(callee)) continue;
4095
+ if (callee.getName() !== RESPONSE_METHOD_NAME) continue;
4096
+ const args = call.getArguments();
4097
+ if (args.length !== 1) continue;
4098
+ const [arg] = args;
4099
+ if (!import_ts_morph19.Node.isArrayLiteralExpression(arg)) continue;
4100
+ if (arg.getElements().length === 0) continue;
4101
+ if (!arg.getElements().every((el) => import_ts_morph19.Node.isIdentifier(el))) continue;
4102
+ arg.replaceWithText(EVENT_CONFIGS_IDENTIFIER);
4103
+ changes.push(
4104
+ `rewrote h.response([...]) \u2192 h.response(${EVENT_CONFIGS_IDENTIFIER})`
4105
+ );
4106
+ }
4107
+ return changes;
4108
+ }
4109
+ async function main21() {
4110
+ const cwd = process.cwd();
4111
+ const srcDir = import_path21.default.join(cwd, "src");
4112
+ console.log(`Scanning for defineConfig event exports in: ${srcDir}
4113
+ `);
4114
+ const project = new import_ts_morph19.Project({
4115
+ tsConfigFilePath: import_path21.default.resolve(srcDir, "../tsconfig.json"),
4116
+ skipAddingFilesFromTsConfig: false
4117
+ });
4118
+ const eventConfigExports = findEventConfigExports(project, srcDir);
4119
+ if (eventConfigExports.length === 0) {
4120
+ console.log(
4121
+ "No top-level `export const X = defineConfig(...)` declarations found. Nothing to do."
4122
+ );
4123
+ return;
4124
+ }
4125
+ console.log(`Found ${eventConfigExports.length} event config export(s):`);
4126
+ for (const e of eventConfigExports) {
4127
+ console.log(` ${e.name} \u2190 ${import_path21.default.relative(cwd, e.filePath)}`);
4128
+ }
4129
+ const eventsIndexAbs = import_path21.default.join(srcDir, "events", "index.ts");
4130
+ const eventsIndexRel = import_path21.default.relative(cwd, eventsIndexAbs);
4131
+ if (import_fs2.default.existsSync(eventsIndexAbs)) {
4132
+ console.log(`
4133
+ [${eventsIndexRel}] already exists \u2014 leaving untouched.`);
4134
+ } else {
4135
+ import_fs2.default.mkdirSync(import_path21.default.dirname(eventsIndexAbs), { recursive: true });
4136
+ const source = buildEventsIndexSource(eventConfigExports, srcDir);
4137
+ const eventsIndexFile = project.createSourceFile(eventsIndexAbs, source, {
4138
+ overwrite: false
4139
+ });
4140
+ await eventsIndexFile.save();
4141
+ console.log(
4142
+ `
4143
+ [${eventsIndexRel}] created with ${EVENT_CONFIGS_IDENTIFIER} of ${eventConfigExports.length} event(s).`
4144
+ );
4145
+ }
4146
+ const handler = findHandlerSourceFile(project, srcDir);
4147
+ if (!handler) {
4148
+ console.log(
4149
+ `
4150
+ No event-config handler file found (looked for exported function(s): ${Array.from(
4151
+ HANDLER_FUNCTION_NAMES
4152
+ ).join(", ")}). Skipping handler rewrite.`
4153
+ );
4154
+ return;
4155
+ }
4156
+ const handlerRelPath = import_path21.default.relative(cwd, handler.getFilePath());
4157
+ const exportNameSet = new Set(eventConfigExports.map((e) => e.name));
4158
+ const changes = modifyHandler(handler, exportNameSet);
4159
+ if (changes.length === 0) {
4160
+ console.log(`
4161
+ [${handlerRelPath}] already wired to ${EVENTS_INDEX_IMPORT_PATH} \u2014 no changes.`);
4162
+ return;
4163
+ }
4164
+ for (const c of changes) console.log(` [${handlerRelPath}] ${c}`);
4165
+ await handler.save();
4166
+ console.log(`
4167
+ Saved ${handlerRelPath}.`);
4168
+ }
4169
+
4170
+ // src/migrations/v2.0/checkout-upstream-files.ts
4171
+ var import_child_process = require("child_process");
4172
+ var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
4173
+ var UPSTREAM_BRANCH = "develop";
4174
+ var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
4175
+ var FILES_TO_CHECKOUT = [
4176
+ "src/analytics/analytics.ts",
4177
+ "Dockerfile",
4178
+ "Dockerfile.assets"
4179
+ ];
4180
+ function runGit(args, { silent = false } = {}) {
4181
+ return (0, import_child_process.execFileSync)("git", args, {
4182
+ cwd: process.cwd(),
4183
+ encoding: "utf8",
4184
+ stdio: silent ? ["ignore", "pipe", "pipe"] : ["ignore", "pipe", "inherit"]
4185
+ });
4186
+ }
4187
+ function tryGit(args) {
4188
+ try {
4189
+ runGit(args, { silent: true });
4190
+ return true;
4191
+ } catch {
4192
+ return false;
4193
+ }
4194
+ }
4195
+ function assertIsGitRepo() {
4196
+ if (!tryGit(["rev-parse", "--is-inside-work-tree"])) {
4197
+ throw new Error(
4198
+ `${process.cwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
4199
+ );
4200
+ }
4201
+ }
4202
+ async function main22() {
4203
+ console.log(
4204
+ `Checking out ${FILES_TO_CHECKOUT.length} file(s) from ${UPSTREAM_URL}@${UPSTREAM_BRANCH}...
4205
+ `
4206
+ );
4207
+ assertIsGitRepo();
4208
+ tryGit(["remote", "remove", TEMP_REMOTE]);
4209
+ try {
4210
+ console.log(` Adding temporary remote '${TEMP_REMOTE}' \u2192 ${UPSTREAM_URL}`);
4211
+ runGit(["remote", "add", TEMP_REMOTE, UPSTREAM_URL], { silent: true });
4212
+ console.log(` Fetching ${TEMP_REMOTE}/${UPSTREAM_BRANCH} (depth 1)...`);
4213
+ runGit(["fetch", "--depth=1", TEMP_REMOTE, UPSTREAM_BRANCH]);
4214
+ const ref = `${TEMP_REMOTE}/${UPSTREAM_BRANCH}`;
4215
+ const missing = [];
4216
+ let checkedOut = 0;
4217
+ for (const file of FILES_TO_CHECKOUT) {
4218
+ if (tryGit(["checkout", ref, "--", file])) {
4219
+ console.log(` Checked out ${file} from ${ref}`);
4220
+ checkedOut++;
4221
+ } else {
4222
+ console.warn(
4223
+ ` [warn] ${file} not found on ${ref} \u2014 skipping. Verify the path exists on that branch.`
4224
+ );
4225
+ missing.push(file);
4226
+ }
4227
+ }
4228
+ console.log(
4229
+ `
4230
+ Checked out ${checkedOut}/${FILES_TO_CHECKOUT.length} file(s) from ${ref}.`
4231
+ );
4232
+ if (missing.length > 0) {
4233
+ console.warn(` Missing on upstream branch: ${missing.join(", ")}`);
4234
+ }
4235
+ if (checkedOut > 0) {
4236
+ console.log(
4237
+ ` Review the staged changes with: git diff --cached -- ${FILES_TO_CHECKOUT.map(
4238
+ (f) => `'${f}'`
4239
+ ).join(" ")}
4240
+ `
4241
+ );
4242
+ }
4243
+ } finally {
4244
+ if (tryGit(["remote", "remove", TEMP_REMOTE])) {
4245
+ console.log(` Removed temporary remote '${TEMP_REMOTE}'.`);
4246
+ }
4247
+ }
4248
+ }
4249
+
4250
+ // src/migrations/v2.0/add-resend-invite-notification.ts
4251
+ var import_fs3 = require("fs");
4252
+ var import_path22 = __toESM(require("path"));
4253
+ var import_ts_morph20 = require("ts-morph");
4254
+ var TS_MORPH_PROJECT_OPTIONS = {
4255
+ skipAddingFilesFromTsConfig: true,
4256
+ manipulationSettings: {
4257
+ indentationText: import_ts_morph20.IndentationText.TwoSpaces
4258
+ }
4259
+ };
4260
+ var EMAIL_TEMPLATES_INDEX = "src/api/notification/email-templates/index.ts";
4261
+ var NOTIFICATION_HANDLER = "src/api/notification/handler.ts";
4262
+ var USER_NOTIFICATION_ROUTES = "src/config/routes/userNotificationRoutes.ts";
4263
+ var SMS_SERVICE = "src/api/notification/sms-service.ts";
4264
+ var NOTIFICATION_CSV = "src/translations/notification.csv";
4265
+ var RESEND_INVITE_HTML = "src/api/notification/email-templates/other/resend-invite.html";
4266
+ var RESEND_INVITE_HTML_CONTENT = `<!doctype html>
4267
+ <html>
4268
+ <head>
4269
+ <link
4270
+ href="https://fonts.googleapis.com/css2?family=Noto+Sans:wght@400;700&display=swap"
4271
+ rel="stylesheet"
4272
+ />
4273
+ <style type="text/css">
4274
+ body {
4275
+ font-family: 'Noto Sans', sans-serif;
4276
+ color: #222;
4277
+ padding: 16px 24px;
4278
+ }
4279
+
4280
+ h1 {
4281
+ font-size: 21px;
4282
+ margin-top: 32px;
4283
+ margin-bottom: 36px;
4284
+ font-weight: 700;
4285
+ }
4286
+
4287
+ p {
4288
+ font-weight: 400;
4289
+ font-size: 16px;
4290
+ line-height: 1.8;
4291
+ margin-bottom: 24px;
4292
+ }
4293
+
4294
+ i {
4295
+ color: #666;
4296
+ font-weight: 400;
4297
+ font-size: 16px;
4298
+ }
4299
+ </style>
4300
+ </head>
4301
+
4302
+ <body>
4303
+ <img
4304
+ src="{{countryLogo}}"
4305
+ alt="country_logo"
4306
+ style="max-height: 88px; max-width: 100%"
4307
+ />
4308
+ <h1>Your {{applicationName}} account invitation</h1>
4309
+ <p>Hello {{firstname}},</p>
4310
+ <p>Your account invitation has been resent. Please use the following credentials to access your account:</p>
4311
+ <p>
4312
+ Username: <strong>{{username}}</strong><br />
4313
+ Password: <strong>{{temporaryPassword}}</strong>
4314
+ </p>
4315
+ <p>
4316
+ Please click the link below to complete your account setup and start using
4317
+ {{applicationName}}.
4318
+ </p>
4319
+
4320
+ <div style="margin-top: 32px; margin-bottom: 32px">
4321
+ <a href="{{loginURL}}">Complete setup</a>
4322
+ </div>
4323
+ <br />
4324
+ <p>
4325
+ Best regards, <br />
4326
+ {{applicationName}} Team
4327
+ </p>
4328
+ </body>
4329
+ </html>
4330
+ `;
4331
+ var CSV_ROW = "resendInviteNotification,The SMS message that is sent when a user invitation is resent,Your OpenCRVS account invitation was resent. Please login with your username: {{username}} and temporary password: {{temporaryPassword}},Votre invitation de compte OpenCRVS a \xE9t\xE9 renvoy\xE9e. Veuillez vous connecter avec votre nom d'utilisateur : {{username}} et votre mot de passe temporaire : {{temporaryPassword}}.\n";
4332
+ function getObjectLiteralFromConst(declaration) {
4333
+ if (!declaration) {
4334
+ return;
4335
+ }
4336
+ const initializer = declaration.getInitializer();
4337
+ if (!initializer) {
4338
+ return;
4339
+ }
4340
+ if (import_ts_morph20.Node.isObjectLiteralExpression(initializer)) {
4341
+ return initializer;
4342
+ }
4343
+ if (import_ts_morph20.Node.isAsExpression(initializer)) {
4344
+ const expression = initializer.getExpression();
4345
+ if (import_ts_morph20.Node.isObjectLiteralExpression(expression)) {
4346
+ return expression;
4347
+ }
4348
+ }
4349
+ if (import_ts_morph20.Node.isSatisfiesExpression(initializer)) {
4350
+ const expression = initializer.getExpression();
4351
+ if (import_ts_morph20.Node.isObjectLiteralExpression(expression)) {
4352
+ return expression;
4353
+ }
4354
+ }
4355
+ }
4356
+ function patchEmailTemplatesIndex() {
4357
+ const full = import_path22.default.join(process.cwd(), EMAIL_TEMPLATES_INDEX);
4358
+ if (!(0, import_fs3.existsSync)(full)) {
4359
+ console.log(` '${EMAIL_TEMPLATES_INDEX}' missing \u2014 skipping.`);
4360
+ return false;
4361
+ }
4362
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4363
+ const sourceFile = project.addSourceFileAtPath(full);
4364
+ let changed = false;
4365
+ const triggerVariableObject = getObjectLiteralFromConst(
4366
+ sourceFile.getVariableDeclaration("TriggerVariable")
4367
+ );
4368
+ if (triggerVariableObject) {
4369
+ const hasResendInviteVariable = triggerVariableObject.getProperties().some((prop) => prop.getText().includes("[TriggerEvent.RESEND_INVITE]"));
4370
+ if (!hasResendInviteVariable) {
4371
+ const properties = triggerVariableObject.getProperties();
4372
+ const lastProperty = properties[properties.length - 1];
4373
+ if (lastProperty) {
4374
+ sourceFile.insertText(
4375
+ lastProperty.getEnd(),
4376
+ `,
4377
+ [TriggerEvent.RESEND_INVITE]: z.object({
4378
+ firstname: z.string(),
4379
+ username: z.string(),
4380
+ temporaryPassword: z.string(),
4381
+ completeSetupUrl: z.string(),
4382
+ loginURL: z.string()
4383
+ })`
4384
+ );
4385
+ changed = true;
4386
+ }
4387
+ }
4388
+ }
4389
+ const templatesObject = getObjectLiteralFromConst(
4390
+ sourceFile.getVariableDeclaration("templates")
4391
+ );
4392
+ if (templatesObject) {
4393
+ const hasResendInviteTemplate = templatesObject.getProperties().some(
4394
+ (prop) => prop.getText().includes("readOtherTemplate<TriggerVariable['resend-invite']>")
4395
+ );
4396
+ if (!hasResendInviteTemplate) {
4397
+ const userCreatedProp = templatesObject.getProperties().find((prop) => prop.getText().includes("[TriggerEvent.USER_CREATED]"));
4398
+ const anchor = userCreatedProp ?? templatesObject.getProperties()[templatesObject.getProperties().length - 1];
4399
+ if (anchor) {
4400
+ sourceFile.insertText(
4401
+ anchor.getEnd(),
4402
+ `,
4403
+ [TriggerEvent.RESEND_INVITE]: {
4404
+ type: 'resend-invite',
4405
+ subject: 'Your OpenCRVS account invitation',
4406
+ template:
4407
+ readOtherTemplate<TriggerVariable['resend-invite']>('resend-invite')
4408
+ }`
4409
+ );
4410
+ changed = true;
4411
+ }
4412
+ }
4413
+ }
4414
+ if (changed) {
4415
+ sourceFile.saveSync();
4416
+ }
4417
+ return changed;
4418
+ }
4419
+ function patchNotificationHandler() {
4420
+ const full = import_path22.default.join(process.cwd(), NOTIFICATION_HANDLER);
4421
+ if (!(0, import_fs3.existsSync)(full)) {
4422
+ return false;
4423
+ }
4424
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4425
+ const sourceFile = project.addSourceFileAtPath(full);
4426
+ const convertFn = sourceFile.getFunction("convertPayloadToVariable");
4427
+ if (!convertFn) {
4428
+ return false;
4429
+ }
4430
+ const switchStmt = convertFn.getFirstDescendantByKind(
4431
+ import_ts_morph20.SyntaxKind.SwitchStatement
4432
+ );
4433
+ if (!switchStmt) {
4434
+ return false;
4435
+ }
4436
+ const clauses = switchStmt.getCaseBlock().getClauses();
4437
+ const hasResendInvite = clauses.some(
4438
+ (clause) => import_ts_morph20.Node.isCaseClause(clause) && clause.getExpression().getText() === "TriggerEvent.RESEND_INVITE"
4439
+ );
4440
+ if (hasResendInvite) {
4441
+ return false;
4442
+ }
4443
+ const userCreatedClauseIndex = clauses.findIndex(
4444
+ (clause) => import_ts_morph20.Node.isCaseClause(clause) && clause.getExpression().getText() === "TriggerEvent.USER_CREATED"
4445
+ );
4446
+ if (userCreatedClauseIndex < 0) {
4447
+ return false;
4448
+ }
4449
+ const userCreatedClause = clauses[userCreatedClauseIndex];
4450
+ sourceFile.insertText(
4451
+ userCreatedClause.getEnd(),
4452
+ `
4453
+
4454
+ case TriggerEvent.RESEND_INVITE:
4455
+ return {
4456
+ firstname,
4457
+ username: payload.username,
4458
+ temporaryPassword: payload.temporaryPassword,
4459
+ completeSetupUrl: LOGIN_URL,
4460
+ loginURL: LOGIN_URL
4461
+ }`
4462
+ );
4463
+ sourceFile.saveSync();
4464
+ return true;
4465
+ }
4466
+ function getReturnedArrayLiteral(functionFilePath, fnName) {
4467
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4468
+ const sourceFile = project.addSourceFileAtPath(functionFilePath);
4469
+ const fn = sourceFile.getFunction(fnName);
4470
+ const returnStmt = fn?.getFirstDescendantByKind(import_ts_morph20.SyntaxKind.ReturnStatement);
4471
+ const expr = returnStmt?.getExpression();
4472
+ if (!expr || !import_ts_morph20.Node.isArrayLiteralExpression(expr)) {
4473
+ return { sourceFile, arrayLiteral: void 0 };
4474
+ }
4475
+ return { sourceFile, arrayLiteral: expr };
4476
+ }
4477
+ function patchUserNotificationRoutes() {
4478
+ const full = import_path22.default.join(process.cwd(), USER_NOTIFICATION_ROUTES);
4479
+ if (!(0, import_fs3.existsSync)(full)) {
4480
+ return false;
4481
+ }
4482
+ const { sourceFile, arrayLiteral } = getReturnedArrayLiteral(
4483
+ full,
4484
+ "getUserNotificationRoutes"
4485
+ );
4486
+ if (!arrayLiteral) {
4487
+ return false;
4488
+ }
4489
+ const elements = arrayLiteral.getElements();
4490
+ const routeExists = elements.some(
4491
+ (element) => element.getText().includes(`path: '/triggers/user/resend-invite'`)
4492
+ );
4493
+ if (routeExists) {
4494
+ return false;
4495
+ }
4496
+ const anchor = elements.find(
4497
+ (element) => element.getText().includes(`path: '/triggers/user/user-created'`)
4498
+ ) ?? elements[elements.length - 1];
4499
+ if (!anchor) {
4500
+ return false;
4501
+ }
4502
+ sourceFile.insertText(
4503
+ anchor.getEnd(),
4504
+ `,
4505
+ {
4506
+ method: 'POST',
4507
+ path: '/triggers/user/resend-invite',
4508
+ handler: makeNotificationHandler('resend-invite'),
4509
+ options: {
4510
+ auth: false,
4511
+ tags: ['api'],
4512
+ description: 'Handles notification for resent user invite'
4513
+ }
4514
+ }`
4515
+ );
4516
+ sourceFile.saveSync();
4517
+ return true;
4518
+ }
4519
+ function patchSmsService() {
4520
+ const full = import_path22.default.join(process.cwd(), SMS_SERVICE);
4521
+ if (!(0, import_fs3.existsSync)(full)) {
4522
+ return false;
4523
+ }
4524
+ const project = new import_ts_morph20.Project(TS_MORPH_PROJECT_OPTIONS);
4525
+ const sourceFile = project.addSourceFileAtPath(full);
4526
+ let changed = false;
4527
+ const otherTemplatesObject = getObjectLiteralFromConst(
4528
+ sourceFile.getVariableDeclaration("otherTemplates")
4529
+ );
4530
+ if (otherTemplatesObject) {
4531
+ const hasResendTemplate = otherTemplatesObject.getProperties().some((prop) => prop.getText().includes("resendInviteNotification"));
4532
+ if (!hasResendTemplate) {
4533
+ const userCredentialsIndex = otherTemplatesObject.getProperties().findIndex((prop) => prop.getText().includes("userCredentialsNotification"));
4534
+ otherTemplatesObject.insertPropertyAssignment(
4535
+ userCredentialsIndex >= 0 ? userCredentialsIndex + 1 : otherTemplatesObject.getProperties().length,
4536
+ {
4537
+ name: "resendInviteNotification",
4538
+ initializer: `'resendInviteNotification'`
4539
+ }
4540
+ );
4541
+ changed = true;
4542
+ }
4543
+ }
4544
+ const triggerToSmsTemplateObject = getObjectLiteralFromConst(
4545
+ sourceFile.getVariableDeclaration("TriggerToSMSTemplate")
4546
+ );
4547
+ if (triggerToSmsTemplateObject) {
4548
+ const hasResendInviteMap = triggerToSmsTemplateObject.getProperties().some((prop) => prop.getText().includes(`['resend-invite']`));
4549
+ if (!hasResendInviteMap) {
4550
+ const userCreatedIndex = triggerToSmsTemplateObject.getProperties().findIndex((prop) => prop.getText().includes(`['user-created']`));
4551
+ triggerToSmsTemplateObject.insertPropertyAssignment(
4552
+ userCreatedIndex >= 0 ? userCreatedIndex + 1 : triggerToSmsTemplateObject.getProperties().length,
4553
+ {
4554
+ name: `['resend-invite']`,
4555
+ initializer: `'resendInviteNotification'`
4556
+ }
4557
+ );
4558
+ changed = true;
4559
+ }
4560
+ }
4561
+ if (changed) {
4562
+ sourceFile.saveSync();
4563
+ }
4564
+ return changed;
4565
+ }
4566
+ async function main23() {
4567
+ console.log("Adding RESEND_INVITE notification wiring\u2026");
4568
+ const touched = [];
4569
+ if (patchEmailTemplatesIndex()) touched.push(EMAIL_TEMPLATES_INDEX);
4570
+ if (patchNotificationHandler()) touched.push(NOTIFICATION_HANDLER);
4571
+ if (patchUserNotificationRoutes()) touched.push(USER_NOTIFICATION_ROUTES);
4572
+ if (patchSmsService()) touched.push(SMS_SERVICE);
4573
+ const csvPath = import_path22.default.join(process.cwd(), NOTIFICATION_CSV);
4574
+ if ((0, import_fs3.existsSync)(csvPath)) {
4575
+ let t = (0, import_fs3.readFileSync)(csvPath, "utf8");
4576
+ if (!/^resendInviteNotification,/m.test(t)) {
4577
+ if (!t.endsWith("\n")) t += "\n";
4578
+ (0, import_fs3.writeFileSync)(csvPath, t + CSV_ROW);
4579
+ touched.push(NOTIFICATION_CSV);
4580
+ }
4581
+ }
4582
+ const htmlPath = import_path22.default.join(process.cwd(), RESEND_INVITE_HTML);
4583
+ (0, import_fs3.mkdirSync)(import_path22.default.dirname(htmlPath), { recursive: true });
4584
+ if (!(0, import_fs3.existsSync)(htmlPath)) {
4585
+ (0, import_fs3.writeFileSync)(htmlPath, RESEND_INVITE_HTML_CONTENT);
4586
+ touched.push(RESEND_INVITE_HTML);
4587
+ }
4588
+ if (touched.length === 0) {
4589
+ console.log(" Nothing to update (already present or anchors not found).");
4590
+ return;
4591
+ }
4592
+ console.log(` Updated:
4593
+ ${touched.map((f) => ` - ${f}`).join("\n")}`);
4594
+ }
4595
+
4596
+ // src/migrations/v2.0/simplify-analytics-precalculations.ts
4597
+ var import_ts_morph21 = require("ts-morph");
4598
+ var import_fs4 = __toESM(require("fs"));
4599
+ var import_path23 = __toESM(require("path"));
4600
+ var ANALYTICS_FILE_REL = "src/analytics/analytics.ts";
4601
+ var FUNCTION_NAME = "precalculateAdditionalAnalytics";
4602
+ var IMPORT_NAMES_TO_REMOVE = /* @__PURE__ */ new Set(["Event", "precalculateBirthEvent"]);
4603
+ var RETURN_EXPRESSION_TEXT = "declaration";
4604
+ function removeTargetedNamedImports(sourceFile) {
4605
+ const log = [];
4606
+ for (const importDecl of [...sourceFile.getImportDeclarations()]) {
4607
+ const namedImports = importDecl.getNamedImports();
4608
+ if (namedImports.length === 0) continue;
4609
+ const matched = namedImports.filter(
4610
+ (ni) => IMPORT_NAMES_TO_REMOVE.has(ni.getName())
4611
+ );
4612
+ if (matched.length === 0) continue;
4613
+ const removedNames = matched.map((ni) => ni.getName());
4614
+ for (const ni of matched) ni.remove();
4615
+ log.push(
4616
+ `removed import(s) ${removedNames.join(", ")} from '${importDecl.getModuleSpecifierValue()}'`
4617
+ );
4618
+ const stillUsed = importDecl.getNamedImports().length > 0 || importDecl.getDefaultImport() || importDecl.getNamespaceImport();
4619
+ if (!stillUsed) importDecl.remove();
4620
+ }
4621
+ return log;
4622
+ }
4623
+ function findPrecalculateFunction(sourceFile) {
4624
+ for (const fn of sourceFile.getFunctions()) {
4625
+ if (fn.getName() === FUNCTION_NAME) return fn;
4626
+ }
4627
+ for (const statement of sourceFile.getVariableStatements()) {
4628
+ for (const decl of statement.getDeclarations()) {
4629
+ if (decl.getName() === FUNCTION_NAME) return decl;
4630
+ }
4631
+ }
4632
+ return void 0;
4633
+ }
4634
+ function getFunctionBodyBlock(fn) {
4635
+ if (import_ts_morph21.Node.isFunctionDeclaration(fn)) return fn.getBody();
4636
+ const initializer = fn.getInitializer();
4637
+ if (!initializer) return void 0;
4638
+ if (!import_ts_morph21.Node.isArrowFunction(initializer) && !import_ts_morph21.Node.isFunctionExpression(initializer)) {
4639
+ return void 0;
4640
+ }
4641
+ return initializer.getBody();
4642
+ }
4643
+ function simplifyPrecalculateFunction(sourceFile) {
4644
+ const log = [];
4645
+ const fn = findPrecalculateFunction(sourceFile);
4646
+ if (!fn) return log;
4647
+ const body = getFunctionBodyBlock(fn);
4648
+ if (!body || !import_ts_morph21.Node.isBlock(body)) return log;
4649
+ for (const statement of [...body.getStatements()]) {
4650
+ const references = statement.getDescendantsOfKind(import_ts_morph21.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
4651
+ if (references) {
4652
+ statement.remove();
4653
+ log.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
4654
+ }
4655
+ }
4656
+ const remaining = body.getStatements();
4657
+ const last = remaining[remaining.length - 1];
4658
+ const alreadyCorrect = last && import_ts_morph21.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
4659
+ if (!alreadyCorrect) {
4660
+ body.addStatements(`return ${RETURN_EXPRESSION_TEXT}`);
4661
+ log.push(
4662
+ `ensured '${FUNCTION_NAME}' ends with 'return ${RETURN_EXPRESSION_TEXT}'`
4663
+ );
4664
+ }
4665
+ return log;
4666
+ }
4667
+ async function main24() {
4668
+ const cwd = process.cwd();
4669
+ const absPath = import_path23.default.join(cwd, ANALYTICS_FILE_REL);
4670
+ if (!import_fs4.default.existsSync(absPath)) {
4671
+ console.log(
4672
+ `[${ANALYTICS_FILE_REL}] does not exist \u2014 nothing to clean up.`
4673
+ );
4674
+ return;
4675
+ }
4676
+ const project = new import_ts_morph21.Project({
4677
+ tsConfigFilePath: import_path23.default.resolve(cwd, "tsconfig.json"),
4678
+ skipAddingFilesFromTsConfig: false
4679
+ });
4680
+ const sourceFile = project.getSourceFile(absPath);
4681
+ if (!sourceFile) {
4682
+ console.log(
4683
+ `[${ANALYTICS_FILE_REL}] is not part of the tsconfig project. Skipping.`
4684
+ );
4685
+ return;
4686
+ }
4687
+ console.log(`Cleaning up ${ANALYTICS_FILE_REL}...
4688
+ `);
4689
+ const importLogs = removeTargetedNamedImports(sourceFile);
4690
+ const fnLogs = simplifyPrecalculateFunction(sourceFile);
4691
+ const allLogs = [...importLogs, ...fnLogs];
4692
+ if (allLogs.length === 0) {
4693
+ console.log(`[${ANALYTICS_FILE_REL}] already clean \u2014 nothing to do.`);
4694
+ return;
4695
+ }
4696
+ for (const log of allLogs) {
4697
+ console.log(` [${ANALYTICS_FILE_REL}] ${log}`);
4698
+ }
4699
+ await sourceFile.save();
4700
+ console.log(`
4701
+ Saved ${ANALYTICS_FILE_REL}.`);
4702
+ }
4703
+
4704
+ // src/migrations/v2.0/merge-infrastructure-directory.ts
4705
+ var import_child_process2 = require("child_process");
4706
+ var import_fs5 = require("fs");
4707
+ var import_os = require("os");
4708
+ var import_path24 = require("path");
4709
+ var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4710
+ var INFRASTRUCTURE_DIR = "infrastructure";
4711
+ var BASE_BRANCH = "release-v1.9";
4712
+ function gitShowBytes(ref, path23) {
4713
+ try {
4714
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path23}`], {
4715
+ cwd: process.cwd(),
4716
+ stdio: ["ignore", "pipe", "pipe"]
4717
+ });
4718
+ return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
4719
+ } catch {
4720
+ return null;
4721
+ }
4722
+ }
4723
+ async function main25() {
4724
+ console.log(
4725
+ `Merging '${INFRASTRUCTURE_DIR}/' from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4726
+ `
4727
+ );
4728
+ assertIsGitRepo();
4729
+ tryGit(["remote", "remove", TEMP_REMOTE2]);
4730
+ try {
4731
+ console.log(` Adding temporary remote '${TEMP_REMOTE2}' \u2192 ${UPSTREAM_URL}`);
4732
+ runGit(["remote", "add", TEMP_REMOTE2, UPSTREAM_URL], { silent: true });
4733
+ console.log(
4734
+ ` Fetching ${TEMP_REMOTE2}/{${UPSTREAM_BRANCH},${BASE_BRANCH}} (depth 1)...`
4735
+ );
4736
+ runGit(["fetch", "--depth=1", TEMP_REMOTE2, UPSTREAM_BRANCH, BASE_BRANCH]);
4737
+ const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4738
+ const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4739
+ const upstreamFiles = runGit(
4740
+ [
4741
+ "ls-tree",
4742
+ "-r",
4743
+ "--name-only",
4744
+ "-z",
4745
+ ref,
4746
+ "--",
4747
+ `${INFRASTRUCTURE_DIR}/`
4748
+ ],
4749
+ { silent: true }
4750
+ ).split("\0").filter(Boolean);
4751
+ if (upstreamFiles.length === 0) {
4752
+ console.log(
4753
+ ` No files found under '${INFRASTRUCTURE_DIR}/' on ${ref}. Nothing to merge.`
4754
+ );
4755
+ return;
4756
+ }
4757
+ const tmpDir = (0, import_fs5.mkdtempSync)((0, import_path24.join)((0, import_os.tmpdir)(), "opencrvs-merge-infra-"));
4758
+ const baseTmp = (0, import_path24.join)(tmpDir, "base");
4759
+ const theirsTmp = (0, import_path24.join)(tmpDir, "theirs");
4760
+ let added = 0;
4761
+ let merged = 0;
4762
+ const conflictedFiles = [];
4763
+ for (const file of upstreamFiles) {
4764
+ const fullPath = (0, import_path24.join)(process.cwd(), file);
4765
+ if (!(0, import_fs5.existsSync)(fullPath)) {
4766
+ if (tryGit(["checkout", ref, "--", file])) {
4767
+ console.log(` + ${file} (new from upstream)`);
4768
+ added++;
4769
+ } else {
4770
+ console.warn(` [warn] failed to add new file ${file}`);
4771
+ }
4772
+ continue;
4773
+ }
4774
+ const theirContents = gitShowBytes(ref, file);
4775
+ if (theirContents === null) {
4776
+ console.warn(` [warn] could not read ${file} from ${ref} \u2014 skipping.`);
4777
+ continue;
4778
+ }
4779
+ (0, import_fs5.writeFileSync)(theirsTmp, theirContents);
4780
+ const baseContents = gitShowBytes(baseRef, file);
4781
+ (0, import_fs5.writeFileSync)(baseTmp, baseContents ?? new Uint8Array(0));
4782
+ try {
4783
+ (0, import_child_process2.execFileSync)("git", ["merge-file", fullPath, baseTmp, theirsTmp], {
4784
+ cwd: process.cwd(),
4785
+ stdio: ["ignore", "pipe", "pipe"]
4786
+ });
4787
+ runGit(["add", "--", file], { silent: true });
4788
+ merged++;
4789
+ } catch (err) {
4790
+ const status = err.status;
4791
+ if (typeof status === "number" && status > 0) {
4792
+ conflictedFiles.push(file);
4793
+ console.warn(
4794
+ ` ! ${file} (${status} conflict${status > 1 ? "s" : ""})`
4795
+ );
4796
+ } else {
4797
+ conflictedFiles.push(file);
4798
+ console.warn(
4799
+ ` [warn] merge failed for ${file} (likely binary or unreadable) \u2014 left untouched.`
4800
+ );
4801
+ }
4802
+ }
4803
+ }
4804
+ console.log(
4805
+ `
4806
+ Done. ${added} added, ${merged} merged cleanly, ${conflictedFiles.length} with conflicts.`
4807
+ );
4808
+ if (conflictedFiles.length > 0) {
4809
+ console.warn(
4810
+ `
4811
+ NOTE: ${conflictedFiles.length} file(s) under '${INFRASTRUCTURE_DIR}/' have merge conflicts that you must resolve manually.
4812
+ Look for the standard conflict markers (<<<<<<<, =======, >>>>>>>) in:
4813
+ ` + conflictedFiles.map((f) => ` - ${f}`).join("\n") + `
4814
+ After resolving, stage the fixes with: git add ${INFRASTRUCTURE_DIR}/`
4815
+ );
4816
+ }
4817
+ } finally {
4818
+ if (tryGit(["remote", "remove", TEMP_REMOTE2])) {
4819
+ console.log(` Removed temporary remote '${TEMP_REMOTE2}'.`);
4820
+ }
4821
+ }
4822
+ }
4823
+
4824
+ // src/migrations/v2.0/delete-infrastructure-directory.ts
4825
+ var import_fs6 = require("fs");
4826
+ var import_path25 = require("path");
4827
+ var INFRASTRUCTURE_DIR2 = "infrastructure";
4828
+ async function main26() {
4829
+ const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4830
+ if (!(0, import_fs6.existsSync)(fullPath)) {
4831
+ console.log(
4832
+ `'${INFRASTRUCTURE_DIR2}/' not found in ${process.cwd()} \u2014 nothing to delete.`
4833
+ );
4834
+ return;
4835
+ }
4836
+ console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4837
+ `);
4838
+ assertIsGitRepo();
4839
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4840
+ silent: true
4841
+ });
4842
+ console.log(` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4843
+ if ((0, import_fs6.existsSync)(fullPath)) {
4844
+ (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4845
+ console.log(` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4846
+ }
4847
+ console.log(
4848
+ `
4849
+ Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4850
+ );
4851
+ }
4852
+
4853
+ // src/migrations/v2.0/index.ts
4854
+ async function runUpgrade(dockerSwarm) {
4855
+ await main18();
4856
+ await main();
4857
+ await main2();
4858
+ await main3();
4859
+ await main4();
4860
+ await main5();
4861
+ await main6();
4862
+ await main7();
4863
+ await main8();
4864
+ await main9();
4865
+ await main10();
4866
+ await main11();
4867
+ await main12();
4868
+ await main13();
4869
+ await main14();
4870
+ await main15();
4871
+ await main16();
4872
+ await main19();
4873
+ await main20();
4874
+ await main21();
4875
+ await main22();
4876
+ await main23();
4877
+ await main24();
4878
+ await main17();
4879
+ if (dockerSwarm) {
4880
+ await main25();
4881
+ } else {
4882
+ await main26();
4883
+ }
4884
+ }