@opencrvs/toolkit 2.2.0-rc.ac299dc → 2.2.0-rc.e6591c5

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 (249) hide show
  1. package/build.sh +17 -14
  2. package/dist/application-config/index.js +21 -11
  3. package/dist/authentication/index.d.ts +2 -1
  4. package/dist/authentication/index.js +20 -13
  5. package/dist/cli.js +2631 -377
  6. package/dist/commons/api/router.d.ts +263 -250
  7. package/dist/commons/application-config/index.d.ts +3 -3
  8. package/dist/commons/conditionals/conditionals.d.ts +4 -4
  9. package/dist/commons/conditionals/index.d.ts +1 -0
  10. package/dist/commons/conditionals/validate.d.ts +6 -1
  11. package/dist/commons/events/ActionConfig.d.ts +16 -23
  12. package/dist/commons/events/ActionDocument.d.ts +1 -0
  13. package/dist/commons/events/ActionInput.d.ts +4 -4
  14. package/dist/commons/events/ActionStatus.d.ts +2 -2
  15. package/dist/commons/events/ActionType.d.ts +2 -0
  16. package/dist/commons/events/AdvancedSearchConfig.d.ts +3 -6
  17. package/dist/commons/events/CompositeFieldValue.d.ts +5 -1
  18. package/dist/commons/events/CountryConfigQueryInput.d.ts +0 -18
  19. package/dist/commons/events/Draft.d.ts +34 -1
  20. package/dist/commons/events/EventConfig.d.ts +448 -1
  21. package/dist/commons/events/EventDocument.d.ts +2 -0
  22. package/dist/commons/events/EventIndex.d.ts +3 -6
  23. package/dist/commons/events/EventInput.d.ts +1 -0
  24. package/dist/commons/events/EventMetadata.d.ts +1 -1
  25. package/dist/commons/events/FieldConfig.d.ts +1 -1
  26. package/dist/commons/events/FieldTypeMapping.d.ts +17 -17
  27. package/dist/commons/events/Flag.d.ts +1 -7
  28. package/dist/commons/events/PlainDate.d.ts +6 -0
  29. package/dist/commons/events/WorkqueueConfig.d.ts +12 -27
  30. package/dist/commons/events/defineConfig.d.ts +7 -2
  31. package/dist/commons/events/event.d.ts +4 -1
  32. package/dist/commons/events/eventConfigValidation.d.ts +9 -0
  33. package/dist/commons/events/field.d.ts +5 -5
  34. package/dist/commons/events/index.d.ts +3 -0
  35. package/dist/commons/events/locations.d.ts +1 -1
  36. package/dist/commons/events/scopes.d.ts +2 -1
  37. package/dist/commons/events/state/flags.d.ts +1 -1
  38. package/dist/commons/events/state/index.d.ts +1 -0
  39. package/dist/commons/events/test.utils.d.ts +62 -7
  40. package/dist/commons/events/toNotificationForm.d.ts +17 -0
  41. package/dist/commons/events/utils.d.ts +59 -7
  42. package/dist/commons/users/Role.d.ts +23 -0
  43. package/dist/commons/users/User.d.ts +263 -0
  44. package/dist/commons/users/authentication.d.ts +67 -0
  45. package/dist/commons/users/index.d.ts +5 -0
  46. package/dist/commons/users/roleValidations.d.ts +15 -0
  47. package/dist/commons/users/scopes.d.ts +1402 -0
  48. package/dist/commons/users/userReferences.d.ts +176 -0
  49. package/dist/conditionals/index.js +5 -6
  50. package/dist/configurator/index.d.ts +24 -0
  51. package/dist/configurator/index.d.ts.map +1 -0
  52. package/dist/configurator/index.js +161 -0
  53. package/dist/configurator/layout.d.ts +29 -0
  54. package/dist/configurator/layout.d.ts.map +1 -0
  55. package/dist/configurator/layout.js +78 -0
  56. package/dist/configurator/paths.d.ts +13 -0
  57. package/dist/configurator/paths.d.ts.map +1 -0
  58. package/dist/configurator/paths.js +48 -0
  59. package/dist/configurator/server/environments.d.ts +20 -0
  60. package/dist/configurator/server/environments.d.ts.map +1 -0
  61. package/dist/configurator/server/environments.js +143 -0
  62. package/dist/configurator/server/files.d.ts +11 -0
  63. package/dist/configurator/server/files.d.ts.map +1 -0
  64. package/dist/configurator/server/files.js +67 -0
  65. package/dist/configurator/server/github.d.ts +56 -0
  66. package/dist/configurator/server/github.d.ts.map +1 -0
  67. package/dist/configurator/server/github.js +239 -0
  68. package/dist/configurator/server/plugin.d.ts +39 -0
  69. package/dist/configurator/server/plugin.d.ts.map +1 -0
  70. package/dist/configurator/server/plugin.js +298 -0
  71. package/dist/configurator/server/seal.d.ts +2 -0
  72. package/dist/configurator/server/seal.d.ts.map +1 -0
  73. package/dist/configurator/server/seal.js +36 -0
  74. package/dist/configurator/server/sshKeys.d.ts +5 -0
  75. package/dist/configurator/server/sshKeys.d.ts.map +1 -0
  76. package/dist/configurator/server/sshKeys.js +28 -0
  77. package/dist/configurator/server/start.d.ts +12 -0
  78. package/dist/configurator/server/start.d.ts.map +1 -0
  79. package/dist/configurator/server/start.js +91 -0
  80. package/dist/configurator/testing.d.ts +11 -0
  81. package/dist/configurator/testing.d.ts.map +1 -0
  82. package/dist/configurator/testing.js +74 -0
  83. package/dist/configurator/ui/bindings/bindings.d.ts +35 -0
  84. package/dist/configurator/ui/bindings/bindings.d.ts.map +1 -0
  85. package/dist/configurator/ui/bindings/bindings.js +5 -0
  86. package/dist/configurator/ui/bindings/parsers.d.ts +7 -0
  87. package/dist/configurator/ui/bindings/parsers.d.ts.map +1 -0
  88. package/dist/configurator/ui/bindings/parsers.js +85 -0
  89. package/dist/configurator/ui/form/users.d.ts +11 -0
  90. package/dist/configurator/ui/form/users.d.ts.map +1 -0
  91. package/dist/configurator/ui/form/users.js +33 -0
  92. package/dist/configurator/ui/plan/dependencyHosts.d.ts +2 -0
  93. package/dist/configurator/ui/plan/dependencyHosts.d.ts.map +1 -0
  94. package/dist/configurator/ui/plan/dependencyHosts.js +36 -0
  95. package/dist/configurator/ui/plan/templateValues.d.ts +11 -0
  96. package/dist/configurator/ui/plan/templateValues.d.ts.map +1 -0
  97. package/dist/configurator/ui/plan/templateValues.js +70 -0
  98. package/dist/configurator/workflows.d.ts +54 -0
  99. package/dist/configurator/workflows.d.ts.map +1 -0
  100. package/dist/configurator/workflows.js +161 -0
  101. package/dist/configurator-assets/forms/bindings.yml +265 -0
  102. package/dist/configurator-assets/templates/README.md +18 -0
  103. package/dist/configurator-assets/templates/charts-values/dependencies/values.override.yaml +4 -0
  104. package/dist/configurator-assets/templates/charts-values/dependencies/values.yaml +96 -0
  105. package/dist/configurator-assets/templates/charts-values/opencrvs-services/values.override.yaml +4 -0
  106. package/dist/configurator-assets/templates/charts-values/opencrvs-services/values.yaml +83 -0
  107. package/dist/configurator-assets/templates/charts-values/opentelemetry/values.yaml +102 -0
  108. package/dist/configurator-assets/templates/charts-values/traefik/values.override.yaml +4 -0
  109. package/dist/configurator-assets/templates/charts-values/traefik/values.yaml +130 -0
  110. package/dist/configurator-assets/templates/inventory/inventory.template.yml +98 -0
  111. package/dist/configurator-assets/ui/apple-touch-icon.png +0 -0
  112. package/dist/configurator-assets/ui/assets/index-CaqYFJUk.css +6 -0
  113. package/dist/configurator-assets/ui/assets/index-DU1Y6E0b.js +169 -0
  114. package/dist/configurator-assets/ui/assets/opencrvs-logo-sIjz08HT.svg +1 -0
  115. package/dist/configurator-assets/ui/assets/poppins-400-BwTUGeWf.woff2 +0 -0
  116. package/dist/configurator-assets/ui/assets/poppins-500-CWICHMj6.woff2 +0 -0
  117. package/dist/configurator-assets/ui/assets/poppins-600-DJVo7c07.woff2 +0 -0
  118. package/dist/configurator-assets/ui/assets/poppins-700-g9MkRaG0.woff2 +0 -0
  119. package/dist/configurator-assets/ui/favicon-32x32.png +0 -0
  120. package/dist/configurator-assets/ui/index.html +25 -0
  121. package/dist/environment/custom-types.d.ts +1 -0
  122. package/dist/environment/custom-types.d.ts.map +1 -1
  123. package/dist/environment/derived-variables.d.ts +18 -4
  124. package/dist/environment/derived-variables.d.ts.map +1 -1
  125. package/dist/environment/derived-variables.js +20 -4
  126. package/dist/environment/questions.d.ts +42 -9
  127. package/dist/environment/questions.d.ts.map +1 -1
  128. package/dist/environment/questions.js +71 -48
  129. package/dist/environment/registry.d.ts +15 -0
  130. package/dist/environment/registry.d.ts.map +1 -0
  131. package/dist/environment/registry.js +112 -0
  132. package/dist/environment/setup-environment.d.ts.map +1 -1
  133. package/dist/environment/setup-environment.js +145 -25
  134. package/dist/environment/templates.d.ts.map +1 -1
  135. package/dist/events/index.js +826 -210
  136. package/dist/migrations/add-notify-config.d.ts +40 -0
  137. package/dist/migrations/add-notify-config.d.ts.map +1 -0
  138. package/dist/migrations/add-notify-config.js +249 -0
  139. package/dist/migrations/index.d.ts +9 -0
  140. package/dist/migrations/index.d.ts.map +1 -0
  141. package/dist/migrations/index.js +1306 -0
  142. package/dist/migrations/move-declaration-to-declare-action.d.ts +38 -0
  143. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -0
  144. package/dist/migrations/move-declaration-to-declare-action.js +260 -0
  145. package/dist/migrations/{add-translations.d.ts → persistent/add-translations.d.ts} +1 -1
  146. package/dist/migrations/persistent/add-translations.d.ts.map +1 -0
  147. package/dist/migrations/{add-translations.js → persistent/add-translations.js} +2 -2
  148. package/dist/migrations/persistent/check-upgrade-path.d.ts +36 -0
  149. package/dist/migrations/persistent/check-upgrade-path.d.ts.map +1 -0
  150. package/dist/migrations/persistent/check-upgrade-path.js +105 -0
  151. package/dist/migrations/persistent/update-toolkit-dependency.d.ts +7 -0
  152. package/dist/migrations/persistent/update-toolkit-dependency.d.ts.map +1 -0
  153. package/dist/migrations/persistent/update-toolkit-dependency.js +77 -0
  154. package/dist/migrations/{v2.2/read-declaration-through-helper.d.ts → read-declaration-through-helper.d.ts} +1 -1
  155. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -0
  156. package/dist/migrations/{v2.2/read-declaration-through-helper.js → read-declaration-through-helper.js} +4 -62
  157. package/dist/migrations/replace-incomplete-flag.d.ts +26 -0
  158. package/dist/migrations/replace-incomplete-flag.d.ts.map +1 -0
  159. package/dist/migrations/replace-incomplete-flag.js +126 -0
  160. package/dist/migrations/resolve-versioned-event-config.d.ts +56 -0
  161. package/dist/migrations/resolve-versioned-event-config.d.ts.map +1 -0
  162. package/dist/migrations/resolve-versioned-event-config.js +353 -0
  163. package/dist/migrations/utils.d.ts +61 -0
  164. package/dist/migrations/utils.d.ts.map +1 -0
  165. package/dist/migrations/utils.js +218 -0
  166. package/dist/notification/index.js +722 -82
  167. package/dist/roles/index.d.ts +2 -0
  168. package/dist/roles/index.d.ts.map +1 -0
  169. package/dist/roles/index.js +730 -0
  170. package/dist/scopes/index.d.ts +54 -94
  171. package/dist/scopes/index.js +15 -12
  172. package/dist/templates/charts-values/dependencies/values.yaml +5 -2
  173. package/dist/templates/charts-values/opencrvs-services/values.yaml +5 -7
  174. package/dist/templates/charts-values/traefik/values.yaml +2 -0
  175. package/dist/verify/endpoints.d.ts +11 -0
  176. package/dist/verify/endpoints.d.ts.map +1 -1
  177. package/dist/verify/endpoints.js +21 -27
  178. package/opencrvs-toolkit-2.2.0-rc.e6591c5.tgz +0 -0
  179. package/package.json +17 -4
  180. package/tsconfig.build.json +11 -1
  181. package/tsconfig.build.tsbuildinfo +1 -1
  182. package/tsconfig.json +15 -6
  183. package/dist/migrations/add-translations.d.ts.map +0 -1
  184. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts +0 -3
  185. package/dist/migrations/v2.1/add-explicit-correction-flags.d.ts.map +0 -1
  186. package/dist/migrations/v2.1/add-explicit-correction-flags.js +0 -234
  187. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +0 -3
  188. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +0 -1
  189. package/dist/migrations/v2.1/add-recovery-link-notifications.js +0 -511
  190. package/dist/migrations/v2.1/enable-telemetry.d.ts +0 -3
  191. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +0 -1
  192. package/dist/migrations/v2.1/enable-telemetry.js +0 -455
  193. package/dist/migrations/v2.1/index.d.ts +0 -6
  194. package/dist/migrations/v2.1/index.d.ts.map +0 -1
  195. package/dist/migrations/v2.1/index.js +0 -50
  196. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts +0 -17
  197. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.d.ts.map +0 -1
  198. package/dist/migrations/v2.1/migrate-infrastructure-to-assets.js +0 -348
  199. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts +0 -2
  200. package/dist/migrations/v2.1/remove-metabase-package-installs.d.ts.map +0 -1
  201. package/dist/migrations/v2.1/remove-metabase-package-installs.js +0 -161
  202. package/dist/migrations/v2.1/remove-sentry.d.ts +0 -3
  203. package/dist/migrations/v2.1/remove-sentry.d.ts.map +0 -1
  204. package/dist/migrations/v2.1/remove-sentry.js +0 -354
  205. package/dist/migrations/v2.1/rename-trigger-paths.d.ts +0 -3
  206. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +0 -1
  207. package/dist/migrations/v2.1/rename-trigger-paths.js +0 -216
  208. package/dist/migrations/v2.1/template-files.d.ts +0 -8
  209. package/dist/migrations/v2.1/template-files.d.ts.map +0 -1
  210. package/dist/migrations/v2.1/template-files.js +0 -49
  211. package/dist/migrations/v2.1/upgrade-tilt.d.ts +0 -11
  212. package/dist/migrations/v2.1/upgrade-tilt.d.ts.map +0 -1
  213. package/dist/migrations/v2.1/upgrade-tilt.js +0 -139
  214. package/dist/migrations/v2.2/index.d.ts +0 -6
  215. package/dist/migrations/v2.2/index.d.ts.map +0 -1
  216. package/dist/migrations/v2.2/index.js +0 -456
  217. package/dist/migrations/v2.2/read-declaration-through-helper.d.ts.map +0 -1
  218. package/dist/templates/countryconfig-template/.tiltignore +0 -1
  219. package/dist/templates/countryconfig-template/Dockerfile.assets +0 -7
  220. package/dist/templates/countryconfig-template/Tiltfile +0 -112
  221. package/dist/templates/countryconfig-template/assets/README.md +0 -1
  222. package/dist/templates/countryconfig-template/assets/clear-all-data-dev.sh +0 -61
  223. package/dist/templates/countryconfig-template/assets/deployment/deploy.sh +0 -455
  224. package/dist/templates/countryconfig-template/assets/deployment/reindex.sh +0 -168
  225. package/dist/templates/countryconfig-template/assets/deployment/validate-required-variables-in-compose-files.ts +0 -67
  226. package/dist/templates/countryconfig-template/assets/elasticsearch/reindex.sh +0 -168
  227. package/dist/templates/countryconfig-template/assets/metabase/README.md +0 -34
  228. package/dist/templates/countryconfig-template/assets/metabase/environment-configuration.sql +0 -36
  229. package/dist/templates/countryconfig-template/assets/metabase/initialize-database.sh +0 -46
  230. package/dist/templates/countryconfig-template/assets/metabase/metabase.init.db.sql +0 -27737
  231. package/dist/templates/countryconfig-template/assets/metabase/open-shell.sh +0 -21
  232. package/dist/templates/countryconfig-template/assets/metabase/package.json +0 -13
  233. package/dist/templates/countryconfig-template/assets/metabase/run-dev.sh +0 -108
  234. package/dist/templates/countryconfig-template/assets/metabase/run.sh +0 -120
  235. package/dist/templates/countryconfig-template/assets/metabase/update-database.sh +0 -40
  236. package/dist/templates/countryconfig-template/assets/postgres/setup-analytics.sh +0 -135
  237. package/dist/templates/countryconfig-template/assets/postgres/setup-reference-data.sh +0 -108
  238. package/dist/templates/countryconfig-template/tilt/clear-all-data.ps1 +0 -50
  239. package/dist/templates/countryconfig-template/tilt/clear-all-data.sh +0 -35
  240. package/dist/templates/countryconfig-template/tilt/common.tilt +0 -145
  241. package/dist/templates/countryconfig-template/tilt/examples/dependencies/values.yaml +0 -15
  242. package/dist/templates/countryconfig-template/tilt/examples/opencrvs-services/values.yaml +0 -56
  243. package/dist/templates/countryconfig-template/tilt/examples/traefik/values-minikube.yaml +0 -21
  244. package/dist/templates/countryconfig-template/tilt/examples/traefik/values.yaml +0 -38
  245. package/dist/templates/countryconfig-template/tilt/helm/dependencies/values.yaml +0 -17
  246. package/dist/templates/countryconfig-template/tilt/helm/opencrvs-services/values.yaml +0 -16
  247. package/dist/templates/countryconfig-template/tilt/lib.tilt +0 -95
  248. package/dist/templates/countryconfig-template/tilt/opencrvs.tilt +0 -136
  249. package/opencrvs-toolkit-2.2.0-rc.ac299dc.tgz +0 -0
@@ -29,7 +29,7 @@ exports.main = main;
29
29
  * `getDeclaration()` instead of the top-level `declaration` property.
30
30
  *
31
31
  * Usage:
32
- * ts-node -r tsconfig-paths/register src/migrations/v2.2/read-declaration-through-helper.ts
32
+ * ts-node -r tsconfig-paths/register src/migrations/read-declaration-through-helper.ts
33
33
  *
34
34
  * Why:
35
35
  * As of v2.2 the declaration form lives on the DECLARE action. `defineConfig`
@@ -54,10 +54,10 @@ exports.main = main;
54
54
  */
55
55
  const ts_morph_1 = require("ts-morph");
56
56
  const path_1 = __importDefault(require("path"));
57
+ const utils_1 = require("./utils");
57
58
  const EVENT_CONFIG_TYPE_NAME = 'EventConfig';
58
59
  const DECLARATION_PROPERTY_NAME = 'declaration';
59
60
  const GET_DECLARATION_NAME = 'getDeclaration';
60
- const TOOLKIT_EVENTS_MODULE = '@opencrvs/toolkit/events';
61
61
  /**
62
62
  * Returns true if the type is the `EventConfig` type published by the toolkit,
63
63
  * as opposed to a type of the same name declared in the country config itself.
@@ -122,64 +122,6 @@ function warnSpreadDeclarations(sourceFile) {
122
122
  }
123
123
  }
124
124
  }
125
- /** Finds the value import of the toolkit's events module, if the file has one. */
126
- function findToolkitImport(sourceFile) {
127
- // A type-only import cannot carry a function, and a namespace import cannot
128
- // be given named imports, so neither is extended
129
- return sourceFile.getImportDeclaration((declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE &&
130
- !declaration.isTypeOnly() &&
131
- !declaration.getNamespaceImport());
132
- }
133
- /**
134
- * Returns the name `getDeclaration` is called by in the file: its local alias
135
- * when the file already imports it from the toolkit, `getDeclaration` when the
136
- * name is free, or undefined when the file binds `getDeclaration` to
137
- * something else.
138
- */
139
- function findGetDeclarationName(sourceFile) {
140
- var _a, _b;
141
- var _c;
142
- const imported = (_a = findToolkitImport(sourceFile)) === null || _a === void 0 ? void 0 : _a.getNamedImports().find((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
143
- if (imported) {
144
- return (_c = (_b = imported.getAliasNode()) === null || _b === void 0 ? void 0 : _b.getText()) !== null && _c !== void 0 ? _c : GET_DECLARATION_NAME;
145
- }
146
- if (sourceFile.getLocal(GET_DECLARATION_NAME)) {
147
- return undefined;
148
- }
149
- return GET_DECLARATION_NAME;
150
- }
151
- function addGetDeclarationImport(sourceFile) {
152
- const toolkitImport = findToolkitImport(sourceFile);
153
- if (!toolkitImport) {
154
- const imports = sourceFile.getImportDeclarations();
155
- const lastImport = imports[imports.length - 1];
156
- // Inserted as text so the import keeps the country config's style
157
- // (single quotes, no semicolon) rather than ts-morph's defaults
158
- sourceFile.insertStatements(lastImport ? lastImport.getChildIndex() + 1 : 0, `import { ${GET_DECLARATION_NAME} } from '${TOOLKIT_EVENTS_MODULE}'`);
159
- return;
160
- }
161
- const alreadyImported = toolkitImport
162
- .getNamedImports()
163
- .some((namedImport) => namedImport.getName() === GET_DECLARATION_NAME);
164
- if (alreadyImported) {
165
- return;
166
- }
167
- const namedImports = toolkitImport.getNamedImports();
168
- // ts-morph's addNamedImport collapses a multi-line import onto one line, so
169
- // the import is rewritten keeping one name per line when it had them
170
- if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
171
- toolkitImport.addNamedImport(GET_DECLARATION_NAME);
172
- return;
173
- }
174
- const names = [
175
- ...namedImports.map((namedImport) => namedImport.getText()),
176
- GET_DECLARATION_NAME
177
- ];
178
- const specifiers = toolkitImport.getText().includes('\n')
179
- ? `{\n ${names.join(',\n ')}\n}`
180
- : `{ ${names.join(', ')} }`;
181
- toolkitImport.replaceWithText(`import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`);
182
- }
183
125
  /**
184
126
  * Rewrites every `x.declaration` read on an `EventConfig` in the file to
185
127
  * `getDeclaration(x)`.
@@ -209,7 +151,7 @@ function rewriteDeclarationReads(sourceFile) {
209
151
  if (reads.length === 0) {
210
152
  return 0;
211
153
  }
212
- const getDeclarationName = findGetDeclarationName(sourceFile);
154
+ const getDeclarationName = (0, utils_1.findToolkitImportName)(sourceFile, GET_DECLARATION_NAME);
213
155
  if (!getDeclarationName) {
214
156
  console.warn(` [${location(reads[reads.length - 1])}] Skipped ${reads.length} read(s): the file already declares its own \`${GET_DECLARATION_NAME}\`. Rewrite them to use the toolkit's \`${GET_DECLARATION_NAME}()\` by hand.`);
215
157
  return 0;
@@ -218,7 +160,7 @@ function rewriteDeclarationReads(sourceFile) {
218
160
  console.log(` [${location(read)}] ${read.getText()} -> ${getDeclarationName}(${read.getExpression().getText()})`);
219
161
  read.replaceWithText(`${getDeclarationName}(${read.getExpression().getText()})`);
220
162
  }
221
- addGetDeclarationImport(sourceFile);
163
+ (0, utils_1.addToolkitImport)(sourceFile, GET_DECLARATION_NAME);
222
164
  return reads.length;
223
165
  }
224
166
  function main() {
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Codemod: replace the removed `incomplete` flag with the NOTIFIED status.
3
+ *
4
+ * Why:
5
+ * `InherentFlags.INCOMPLETE` mirrored the NOTIFIED status and has been
6
+ * removed. See CHANGELOG.md ("The `incomplete` flag is removed").
7
+ *
8
+ * What it does:
9
+ * - In every query object of the form
10
+ * `{ flags: { anyOf: [InherentFlags.INCOMPLETE, ...] }, ... }`, removes
11
+ * the flag (and `anyOf` / `flags` if left empty) and adds
12
+ * `status: { type: 'exact', term: EventStatus.enum.NOTIFIED }`
13
+ * - Imports `EventStatus` next to `InherentFlags` when missing
14
+ * - Lists any other `InherentFlags.INCOMPLETE` reference for manual update
15
+ */
16
+ import { SourceFile } from 'ts-morph';
17
+ /**
18
+ * Rewrites `flags.anyOf` uses of the incomplete flag in place.
19
+ * Returns the line numbers of references it could not rewrite.
20
+ */
21
+ export declare function replaceIncompleteFlag(sourceFile: SourceFile): {
22
+ changed: boolean;
23
+ remaining: number[];
24
+ };
25
+ export declare function main(): Promise<void>;
26
+ //# sourceMappingURL=replace-incomplete-flag.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replace-incomplete-flag.d.ts","sourceRoot":"","sources":["../../src/migrations/replace-incomplete-flag.ts"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;;GAcG;AAEH,OAAO,EAAiB,UAAU,EAAc,MAAM,UAAU,CAAA;AAsBhE;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,UAAU,EAAE,UAAU;;;EAuD3D;AAED,wBAAsB,IAAI,kBAwBzB"}
@@ -0,0 +1,126 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
+ return new (P || (P = Promise))(function (resolve, reject) {
15
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
19
+ });
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.replaceIncompleteFlag = replaceIncompleteFlag;
26
+ exports.main = main;
27
+ /**
28
+ * Codemod: replace the removed `incomplete` flag with the NOTIFIED status.
29
+ *
30
+ * Why:
31
+ * `InherentFlags.INCOMPLETE` mirrored the NOTIFIED status and has been
32
+ * removed. See CHANGELOG.md ("The `incomplete` flag is removed").
33
+ *
34
+ * What it does:
35
+ * - In every query object of the form
36
+ * `{ flags: { anyOf: [InherentFlags.INCOMPLETE, ...] }, ... }`, removes
37
+ * the flag (and `anyOf` / `flags` if left empty) and adds
38
+ * `status: { type: 'exact', term: EventStatus.enum.NOTIFIED }`
39
+ * - Imports `EventStatus` next to `InherentFlags` when missing
40
+ * - Lists any other `InherentFlags.INCOMPLETE` reference for manual update
41
+ */
42
+ const ts_morph_1 = require("ts-morph");
43
+ const path_1 = __importDefault(require("path"));
44
+ const INCOMPLETE = 'InherentFlags.INCOMPLETE';
45
+ const NOTIFIED_STATUS = `{ type: 'exact', term: EventStatus.enum.NOTIFIED }`;
46
+ function ensureEventStatusImport(sourceFile) {
47
+ const importDeclaration = sourceFile
48
+ .getImportDeclarations()
49
+ .find((declaration) => declaration
50
+ .getNamedImports()
51
+ .some((named) => named.getName() === 'InherentFlags'));
52
+ const hasEventStatus = importDeclaration === null || importDeclaration === void 0 ? void 0 : importDeclaration.getNamedImports().some((named) => named.getName() === 'EventStatus');
53
+ if (importDeclaration && !hasEventStatus) {
54
+ importDeclaration.addNamedImport('EventStatus');
55
+ }
56
+ }
57
+ /**
58
+ * Rewrites `flags.anyOf` uses of the incomplete flag in place.
59
+ * Returns the line numbers of references it could not rewrite.
60
+ */
61
+ function replaceIncompleteFlag(sourceFile) {
62
+ let changed = false;
63
+ const anyOfIncomplete = sourceFile
64
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.PropertyAccessExpression)
65
+ .filter((node) => node.getText() === INCOMPLETE)
66
+ .map((node) => node.getParent())
67
+ .filter(ts_morph_1.Node.isArrayLiteralExpression)
68
+ .filter((array) => {
69
+ var _a;
70
+ const anyOf = array.getParent();
71
+ const flags = (_a = anyOf === null || anyOf === void 0 ? void 0 : anyOf.getParent()) === null || _a === void 0 ? void 0 : _a.getParent();
72
+ return (ts_morph_1.Node.isPropertyAssignment(anyOf) &&
73
+ anyOf.getName() === 'anyOf' &&
74
+ ts_morph_1.Node.isPropertyAssignment(flags) &&
75
+ flags.getName() === 'flags');
76
+ });
77
+ for (const array of anyOfIncomplete) {
78
+ const anyOf = array.getParentIfKindOrThrow(ts_morph_1.SyntaxKind.PropertyAssignment);
79
+ const flagsObject = anyOf.getParentIfKindOrThrow(ts_morph_1.SyntaxKind.ObjectLiteralExpression);
80
+ const flags = flagsObject.getParentIfKindOrThrow(ts_morph_1.SyntaxKind.PropertyAssignment);
81
+ const query = flags.getParentIfKindOrThrow(ts_morph_1.SyntaxKind.ObjectLiteralExpression);
82
+ array
83
+ .getElements()
84
+ .filter((element) => element.getText() === INCOMPLETE)
85
+ .forEach((element) => array.removeElement(element));
86
+ if (array.getElements().length === 0)
87
+ anyOf.remove();
88
+ if (flagsObject.getProperties().length === 0)
89
+ flags.remove();
90
+ if (!query.getProperty('status')) {
91
+ query.addPropertyAssignment({
92
+ name: 'status',
93
+ initializer: NOTIFIED_STATUS
94
+ });
95
+ }
96
+ changed = true;
97
+ }
98
+ if (changed)
99
+ ensureEventStatusImport(sourceFile);
100
+ const remaining = sourceFile
101
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.PropertyAccessExpression)
102
+ .filter((node) => node.getText() === INCOMPLETE)
103
+ .map((node) => node.getStartLineNumber());
104
+ return { changed, remaining };
105
+ }
106
+ function main() {
107
+ return __awaiter(this, void 0, void 0, function* () {
108
+ const project = new ts_morph_1.Project({
109
+ tsConfigFilePath: path_1.default.join(process.cwd(), 'tsconfig.json')
110
+ });
111
+ const sourceFiles = project
112
+ .getSourceFiles()
113
+ .filter((sf) => !sf.getFilePath().includes('/node_modules/'));
114
+ for (const sourceFile of sourceFiles) {
115
+ const relPath = path_1.default.relative(process.cwd(), sourceFile.getFilePath());
116
+ const { changed, remaining } = replaceIncompleteFlag(sourceFile);
117
+ if (changed) {
118
+ yield sourceFile.save();
119
+ console.log(` [${relPath}] Replaced the incomplete flag with the NOTIFIED status`);
120
+ }
121
+ for (const line of remaining) {
122
+ console.warn(` [${relPath}:${line}] ${INCOMPLETE} was removed, update this reference to use the NOTIFIED status`);
123
+ }
124
+ }
125
+ });
126
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * Codemod: Read a `VersionedEventConfig` through `resolveEventConfig()` wherever
3
+ * the country config uses it as a flat `EventConfig`.
4
+ *
5
+ * Usage:
6
+ * ts-node -r tsconfig-paths/register src/migrations/resolve-versioned-event-config.ts
7
+ *
8
+ * Why:
9
+ * As of v2.2 an event configuration can have several versions, each with an
10
+ * `effectiveFrom` date. `defineConfig` still accepts a flat configuration and
11
+ * wraps it in a single version, but it now returns a `VersionedEventConfig`:
12
+ * `{ id, label, advancedSearch, versions }`. Fields such as `actions` or
13
+ * `analytics` live on each version, so code that reads them straight off the
14
+ * result of `defineConfig`, or passes it to a function expecting an
15
+ * `EventConfig`, stops compiling.
16
+ *
17
+ * What it does:
18
+ * - Scans all TypeScript files under `src/`
19
+ * - Reads `@opencrvs/toolkit/events` from the toolkit running it, not the one the
20
+ * country config has installed, which predates `VersionedEventConfig`
21
+ * - Rewrites `x.field` to `resolveEventConfig(x).field` wherever `x` is the
22
+ * toolkit's `VersionedEventConfig` and `field` is not one of its own fields
23
+ * (`id`, `label`, `advancedSearch` and `versions` are left alone)
24
+ * - Rewrites `x` to `resolveEventConfig(x)` wherever a `VersionedEventConfig` is
25
+ * passed, assigned or returned where an `EventConfig` is expected, and `xs` to
26
+ * `xs.map(resolveEventConfig)` for arrays of them
27
+ * - Adds `resolveEventConfig` to the file's `@opencrvs/toolkit/events` import
28
+ * - Logs, without changing: optional chains (`x?.actions`), writes
29
+ * (`x.actions = ...`, `delete x.actions`...), destructuring `{ actions }` out
30
+ * of a `VersionedEventConfig`, and a possibly undefined `VersionedEventConfig`
31
+ * passed where an `EventConfig` is expected
32
+ * - Leaves a file alone, and logs it, when it already declares its own
33
+ * `resolveEventConfig`
34
+ * - Saves the modified files in-place
35
+ *
36
+ * Runs before `read-declaration-through-helper`, which then rewrites
37
+ * `resolveEventConfig(x).declaration` to `getDeclaration(resolveEventConfig(x))`.
38
+ */
39
+ import { CompilerOptions, SourceFile } from 'ts-morph';
40
+ /**
41
+ * Resolves `@opencrvs/toolkit/events` to `toolkitEventsPath`, keeping the country
42
+ * config's other `paths`. The country config still has the toolkit it upgrades from
43
+ * installed, whose types have no `VersionedEventConfig`, so the codemod reads the
44
+ * types of the toolkit running it instead.
45
+ */
46
+ export declare function withToolkitEventsAt(compilerOptions: CompilerOptions, toolkitEventsPath: string): CompilerOptions;
47
+ /**
48
+ * Rewrites every use of a `VersionedEventConfig` as a flat `EventConfig` in the
49
+ * file to go through `resolveEventConfig()`.
50
+ *
51
+ * @returns the number of uses rewritten.
52
+ */
53
+ export declare function rewriteVersionedEventConfigUses(sourceFile: SourceFile): number;
54
+ declare function main(): Promise<void>;
55
+ export { main };
56
+ //# sourceMappingURL=resolve-versioned-event-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resolve-versioned-event-config.d.ts","sourceRoot":"","sources":["../../src/migrations/resolve-versioned-event-config.ts"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAqCG;AAEH,OAAO,EACL,eAAe,EAMf,UAAU,EAGX,MAAM,UAAU,CAAA;AAsRjB;;;;;GAKG;AACH,wBAAgB,mBAAmB,CACjC,eAAe,EAAE,eAAe,EAChC,iBAAiB,EAAE,MAAM,GACxB,eAAe,CAQjB;AAED;;;;;GAKG;AACH,wBAAgB,+BAA+B,CAC7C,UAAU,EAAE,UAAU,GACrB,MAAM,CAiDR;AAED,iBAAe,IAAI,kBAuDlB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
@@ -0,0 +1,353 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
+ return new (P || (P = Promise))(function (resolve, reject) {
15
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
19
+ });
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.withToolkitEventsAt = withToolkitEventsAt;
26
+ exports.rewriteVersionedEventConfigUses = rewriteVersionedEventConfigUses;
27
+ exports.main = main;
28
+ /**
29
+ * Codemod: Read a `VersionedEventConfig` through `resolveEventConfig()` wherever
30
+ * the country config uses it as a flat `EventConfig`.
31
+ *
32
+ * Usage:
33
+ * ts-node -r tsconfig-paths/register src/migrations/resolve-versioned-event-config.ts
34
+ *
35
+ * Why:
36
+ * As of v2.2 an event configuration can have several versions, each with an
37
+ * `effectiveFrom` date. `defineConfig` still accepts a flat configuration and
38
+ * wraps it in a single version, but it now returns a `VersionedEventConfig`:
39
+ * `{ id, label, advancedSearch, versions }`. Fields such as `actions` or
40
+ * `analytics` live on each version, so code that reads them straight off the
41
+ * result of `defineConfig`, or passes it to a function expecting an
42
+ * `EventConfig`, stops compiling.
43
+ *
44
+ * What it does:
45
+ * - Scans all TypeScript files under `src/`
46
+ * - Reads `@opencrvs/toolkit/events` from the toolkit running it, not the one the
47
+ * country config has installed, which predates `VersionedEventConfig`
48
+ * - Rewrites `x.field` to `resolveEventConfig(x).field` wherever `x` is the
49
+ * toolkit's `VersionedEventConfig` and `field` is not one of its own fields
50
+ * (`id`, `label`, `advancedSearch` and `versions` are left alone)
51
+ * - Rewrites `x` to `resolveEventConfig(x)` wherever a `VersionedEventConfig` is
52
+ * passed, assigned or returned where an `EventConfig` is expected, and `xs` to
53
+ * `xs.map(resolveEventConfig)` for arrays of them
54
+ * - Adds `resolveEventConfig` to the file's `@opencrvs/toolkit/events` import
55
+ * - Logs, without changing: optional chains (`x?.actions`), writes
56
+ * (`x.actions = ...`, `delete x.actions`...), destructuring `{ actions }` out
57
+ * of a `VersionedEventConfig`, and a possibly undefined `VersionedEventConfig`
58
+ * passed where an `EventConfig` is expected
59
+ * - Leaves a file alone, and logs it, when it already declares its own
60
+ * `resolveEventConfig`
61
+ * - Saves the modified files in-place
62
+ *
63
+ * Runs before `read-declaration-through-helper`, which then rewrites
64
+ * `resolveEventConfig(x).declaration` to `getDeclaration(resolveEventConfig(x))`.
65
+ */
66
+ const ts_morph_1 = require("ts-morph");
67
+ const path_1 = __importDefault(require("path"));
68
+ const EVENT_CONFIG_TYPE_NAME = 'EventConfig';
69
+ const VERSIONED_EVENT_CONFIG_TYPE_NAME = 'VersionedEventConfig';
70
+ const RESOLVE_EVENT_CONFIG_NAME = 'resolveEventConfig';
71
+ const TOOLKIT_EVENTS_MODULE = '@opencrvs/toolkit/events';
72
+ /**
73
+ * Returns true if the type is the type of that name published by the toolkit,
74
+ * as opposed to a type of the same name declared in the country config itself.
75
+ */
76
+ function isToolkitType(type, name) {
77
+ var _a;
78
+ const nonNullableType = type.getNonNullableType();
79
+ const symbol = (_a = nonNullableType.getAliasSymbol()) !== null && _a !== void 0 ? _a : nonNullableType.getSymbol();
80
+ if ((symbol === null || symbol === void 0 ? void 0 : symbol.getName()) !== name) {
81
+ return false;
82
+ }
83
+ return symbol
84
+ .getDeclarations()
85
+ .some((declaration) => declaration.getSourceFile().isDeclarationFile());
86
+ }
87
+ function isVersionedEventConfig(type) {
88
+ return isToolkitType(type, VERSIONED_EVENT_CONFIG_TYPE_NAME);
89
+ }
90
+ function isEventConfig(type) {
91
+ return isToolkitType(type, EVENT_CONFIG_TYPE_NAME);
92
+ }
93
+ function isArrayOf(type, isElement) {
94
+ const elementType = type.getNonNullableType().getArrayElementType();
95
+ return elementType !== undefined && isElement(elementType);
96
+ }
97
+ /** Returns true if `name` is a field of `VersionedEventConfig` itself, e.g. `id` or `versions`. */
98
+ function isVersionedField(type, name) {
99
+ return type.getNonNullableType().getProperty(name) !== undefined;
100
+ }
101
+ function isAssignmentOperator(kind) {
102
+ return kind >= ts_morph_1.SyntaxKind.FirstAssignment && kind <= ts_morph_1.SyntaxKind.LastAssignment;
103
+ }
104
+ /**
105
+ * Returns true if the node is written to rather than read: the target of `=` or
106
+ * a compound assignment (`??=`, `||=`...), or the operand of `delete`.
107
+ * `resolveEventConfig(x)` gives a separate object, so writing to it is lost.
108
+ */
109
+ function isWriteTarget(node) {
110
+ const parent = node.getParent();
111
+ if (ts_morph_1.Node.isDeleteExpression(parent)) {
112
+ return true;
113
+ }
114
+ return (ts_morph_1.Node.isBinaryExpression(parent) &&
115
+ parent.getLeft() === node &&
116
+ isAssignmentOperator(parent.getOperatorToken().getKind()));
117
+ }
118
+ function location(node) {
119
+ const relPath = path_1.default.relative(process.cwd(), node.getSourceFile().getFilePath());
120
+ return `${relPath}:${node.getStartLineNumber()}`;
121
+ }
122
+ function warnDestructuredVersionFields(sourceFile) {
123
+ for (const pattern of sourceFile.getDescendantsOfKind(ts_morph_1.SyntaxKind.ObjectBindingPattern)) {
124
+ const type = pattern.getType();
125
+ if (!isVersionedEventConfig(type)) {
126
+ continue;
127
+ }
128
+ const destructuresVersionField = pattern
129
+ .getElements()
130
+ .some((element) => { var _a; var _b; return !element.getDotDotDotToken() &&
131
+ !isVersionedField(type, (_b = (_a = element.getPropertyNameNode()) === null || _a === void 0 ? void 0 : _a.getText()) !== null && _b !== void 0 ? _b : element.getName()); });
132
+ if (destructuresVersionField) {
133
+ console.warn(` [${location(pattern)}] Destructures a field of a version from a VersionedEventConfig. Destructure it from \`${RESOLVE_EVENT_CONFIG_NAME}(config)\` by hand.`);
134
+ }
135
+ }
136
+ }
137
+ /**
138
+ * Finds `x.field` reads where `x` is a `VersionedEventConfig` and `field` belongs
139
+ * to a version of it, e.g. `actions`.
140
+ */
141
+ function findVersionFieldReads(sourceFile) {
142
+ return sourceFile
143
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.PropertyAccessExpression)
144
+ .filter((node) => {
145
+ const type = node.getExpression().getType();
146
+ return (isVersionedEventConfig(type) && !isVersionedField(type, node.getName()));
147
+ })
148
+ .filter((node) => {
149
+ if (node.hasQuestionDotToken()) {
150
+ console.warn(` [${location(node)}] Skipped optional chain \`${node.getText()}\`. Rewrite it to use \`${RESOLVE_EVENT_CONFIG_NAME}()\` by hand.`);
151
+ return false;
152
+ }
153
+ if (isWriteTarget(node)) {
154
+ console.warn(` [${location(node)}] Skipped write to \`${node.getText()}\`. Set it in the version passed to \`defineConfig\` instead.`);
155
+ return false;
156
+ }
157
+ return true;
158
+ });
159
+ }
160
+ /**
161
+ * Returns true if the node is a value handed over to something else: a call
162
+ * argument, a variable initializer, a returned value or an object property
163
+ * value. Only these get a contextual type that `EventConfig` can come from.
164
+ */
165
+ function isHandedOver(node) {
166
+ const parent = node.getParent();
167
+ if (ts_morph_1.Node.isCallExpression(parent) || ts_morph_1.Node.isNewExpression(parent)) {
168
+ return parent.getArguments().includes(node);
169
+ }
170
+ return (((ts_morph_1.Node.isVariableDeclaration(parent) ||
171
+ ts_morph_1.Node.isPropertyAssignment(parent)) &&
172
+ parent.getInitializer() === node) ||
173
+ ts_morph_1.Node.isReturnStatement(parent));
174
+ }
175
+ /**
176
+ * Finds `VersionedEventConfig` values (or arrays of them) handed over where an
177
+ * `EventConfig` (or an array of them) is expected.
178
+ */
179
+ function findValuesExpectingEventConfig(sourceFile) {
180
+ return sourceFile
181
+ .getDescendants()
182
+ .filter((node) => ts_morph_1.Node.isExpression(node))
183
+ .filter(isHandedOver)
184
+ .map((node) => {
185
+ const type = node.getType();
186
+ const expectedType = node.getContextualType();
187
+ if (!expectedType) {
188
+ return undefined;
189
+ }
190
+ if (isVersionedEventConfig(type) && isEventConfig(expectedType)) {
191
+ return { node, isArray: false };
192
+ }
193
+ if (isArrayOf(type, isVersionedEventConfig) &&
194
+ isArrayOf(expectedType, isEventConfig)) {
195
+ return { node, isArray: true };
196
+ }
197
+ return undefined;
198
+ })
199
+ .filter((value) => value !== undefined)
200
+ .filter(({ node }) => {
201
+ if (node.getType().isNullable()) {
202
+ console.warn(` [${location(node)}] Skipped \`${node.getText()}\`, which may be undefined where an EventConfig is expected. Narrow it and pass \`${RESOLVE_EVENT_CONFIG_NAME}(...)\` by hand.`);
203
+ return false;
204
+ }
205
+ return true;
206
+ });
207
+ }
208
+ /** Finds the value import of the toolkit's events module, if the file has one. */
209
+ function findToolkitImport(sourceFile) {
210
+ // A type-only import cannot carry a function, and a namespace import cannot
211
+ // be given named imports, so neither is extended
212
+ return sourceFile.getImportDeclaration((declaration) => declaration.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE &&
213
+ !declaration.isTypeOnly() &&
214
+ !declaration.getNamespaceImport());
215
+ }
216
+ /**
217
+ * Returns the name `resolveEventConfig` is called by in the file: its local
218
+ * alias when the file already imports it from the toolkit, `resolveEventConfig`
219
+ * when the name is free, or undefined when the file binds `resolveEventConfig`
220
+ * to something else.
221
+ */
222
+ function findResolveEventConfigName(sourceFile) {
223
+ var _a, _b;
224
+ var _c;
225
+ const imported = (_a = findToolkitImport(sourceFile)) === null || _a === void 0 ? void 0 : _a.getNamedImports().find((namedImport) => namedImport.getName() === RESOLVE_EVENT_CONFIG_NAME);
226
+ if (imported) {
227
+ return (_c = (_b = imported.getAliasNode()) === null || _b === void 0 ? void 0 : _b.getText()) !== null && _c !== void 0 ? _c : RESOLVE_EVENT_CONFIG_NAME;
228
+ }
229
+ if (sourceFile.getLocal(RESOLVE_EVENT_CONFIG_NAME)) {
230
+ return undefined;
231
+ }
232
+ return RESOLVE_EVENT_CONFIG_NAME;
233
+ }
234
+ function addResolveEventConfigImport(sourceFile) {
235
+ const toolkitImport = findToolkitImport(sourceFile);
236
+ if (!toolkitImport) {
237
+ const imports = sourceFile.getImportDeclarations();
238
+ const lastImport = imports[imports.length - 1];
239
+ // Inserted as text so the import keeps the country config's style
240
+ // (single quotes, no semicolon) rather than ts-morph's defaults
241
+ sourceFile.insertStatements(lastImport ? lastImport.getChildIndex() + 1 : 0, `import { ${RESOLVE_EVENT_CONFIG_NAME} } from '${TOOLKIT_EVENTS_MODULE}'`);
242
+ return;
243
+ }
244
+ const alreadyImported = toolkitImport
245
+ .getNamedImports()
246
+ .some((namedImport) => namedImport.getName() === RESOLVE_EVENT_CONFIG_NAME);
247
+ if (alreadyImported) {
248
+ return;
249
+ }
250
+ const namedImports = toolkitImport.getNamedImports();
251
+ // ts-morph's addNamedImport collapses a multi-line import onto one line, so
252
+ // the import is rewritten keeping one name per line when it had them
253
+ if (toolkitImport.getDefaultImport() || namedImports.length === 0) {
254
+ toolkitImport.addNamedImport(RESOLVE_EVENT_CONFIG_NAME);
255
+ return;
256
+ }
257
+ const names = [
258
+ ...namedImports.map((namedImport) => namedImport.getText()),
259
+ RESOLVE_EVENT_CONFIG_NAME
260
+ ];
261
+ const specifiers = toolkitImport.getText().includes('\n')
262
+ ? `{\n ${names.join(',\n ')}\n}`
263
+ : `{ ${names.join(', ')} }`;
264
+ toolkitImport.replaceWithText(`import ${specifiers} from '${TOOLKIT_EVENTS_MODULE}'`);
265
+ }
266
+ /**
267
+ * Resolves `@opencrvs/toolkit/events` to `toolkitEventsPath`, keeping the country
268
+ * config's other `paths`. The country config still has the toolkit it upgrades from
269
+ * installed, whose types have no `VersionedEventConfig`, so the codemod reads the
270
+ * types of the toolkit running it instead.
271
+ */
272
+ function withToolkitEventsAt(compilerOptions, toolkitEventsPath) {
273
+ return Object.assign(Object.assign({}, compilerOptions), { paths: Object.assign(Object.assign({}, compilerOptions.paths), { [TOOLKIT_EVENTS_MODULE]: [toolkitEventsPath] }) });
274
+ }
275
+ /**
276
+ * Rewrites every use of a `VersionedEventConfig` as a flat `EventConfig` in the
277
+ * file to go through `resolveEventConfig()`.
278
+ *
279
+ * @returns the number of uses rewritten.
280
+ */
281
+ function rewriteVersionedEventConfigUses(sourceFile) {
282
+ warnDestructuredVersionFields(sourceFile);
283
+ // Types are read before any rewrite, as a rewrite invalidates them
284
+ const uses = [
285
+ ...findVersionFieldReads(sourceFile).map((node) => ({
286
+ node,
287
+ rewrite: (name) => `${name}(${node.getExpression().getText()}).${node.getName()}`
288
+ })),
289
+ ...findValuesExpectingEventConfig(sourceFile).map(({ node, isArray }) => ({
290
+ node,
291
+ rewrite: (name) => isArray
292
+ ? `${node.getText()}.map(${name})`
293
+ : `${name}(${node.getText()})`
294
+ }))
295
+ ]
296
+ // Replace the innermost uses first, so replacing an outer use does not
297
+ // invalidate nodes still waiting to be replaced.
298
+ .sort((a, b) => b.node.getStart() - a.node.getStart() ||
299
+ a.node.getEnd() - b.node.getEnd());
300
+ if (uses.length === 0) {
301
+ return 0;
302
+ }
303
+ const resolveEventConfigName = findResolveEventConfigName(sourceFile);
304
+ if (!resolveEventConfigName) {
305
+ console.warn(` [${location(uses[uses.length - 1].node)}] Skipped ${uses.length} use(s): the file already declares its own \`${RESOLVE_EVENT_CONFIG_NAME}\`. Rewrite them to use the toolkit's \`${RESOLVE_EVENT_CONFIG_NAME}()\` by hand.`);
306
+ return 0;
307
+ }
308
+ for (const { node, rewrite } of uses) {
309
+ const before = node.getText();
310
+ const after = rewrite(resolveEventConfigName);
311
+ console.log(` [${location(node)}] ${before} -> ${after}`);
312
+ node.replaceWithText(after);
313
+ }
314
+ addResolveEventConfigImport(sourceFile);
315
+ return uses.length;
316
+ }
317
+ function main() {
318
+ return __awaiter(this, void 0, void 0, function* () {
319
+ const srcDir = path_1.default.join(process.cwd(), 'src');
320
+ console.log(`Scanning for VersionedEventConfig used as an EventConfig in: ${srcDir}\n`);
321
+ const tsConfigFilePath = path_1.default.resolve(srcDir, '../tsconfig.json');
322
+ const project = new ts_morph_1.Project({
323
+ tsConfigFilePath,
324
+ skipAddingFilesFromTsConfig: false,
325
+ // The events module of this toolkit, next to the migrations in `dist`
326
+ compilerOptions: withToolkitEventsAt((0, ts_morph_1.getCompilerOptionsFromTsConfig)(tsConfigFilePath).options, path_1.default.resolve(__dirname, '../events'))
327
+ });
328
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
329
+ const fp = sf.getFilePath();
330
+ return fp.includes('/src/') && !fp.includes('/node_modules/');
331
+ });
332
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.\n`);
333
+ let totalChanges = 0;
334
+ const modifiedFiles = [];
335
+ for (const sourceFile of sourceFiles) {
336
+ const changes = rewriteVersionedEventConfigUses(sourceFile);
337
+ if (changes > 0) {
338
+ totalChanges += changes;
339
+ modifiedFiles.push(sourceFile);
340
+ }
341
+ }
342
+ if (modifiedFiles.length === 0) {
343
+ console.log('No VersionedEventConfig used as an EventConfig found. Nothing to do.');
344
+ return;
345
+ }
346
+ console.log(`\nSaving ${modifiedFiles.length} modified file(s)...`);
347
+ for (const sourceFile of modifiedFiles) {
348
+ yield sourceFile.save();
349
+ console.log(` Saved: ${path_1.default.relative(process.cwd(), sourceFile.getFilePath())}`);
350
+ }
351
+ console.log(`\nDone. Rewrote ${totalChanges} use(s) across ${modifiedFiles.length} file(s).`);
352
+ });
353
+ }