@opencrvs/toolkit 2.0.0-rc.b2d066a → 2.0.0-rc.b388b6b

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 (59) hide show
  1. package/create-countryconfig/index.js +103 -0
  2. package/create-countryconfig/package.json +21 -0
  3. package/dist/application-config/index.js +269 -121
  4. package/dist/cli.js +507 -171
  5. package/dist/commons/api/router.d.ts +3403 -272
  6. package/dist/commons/application-config/index.d.ts +1 -0
  7. package/dist/commons/conditionals/conditionals.d.ts +357 -7
  8. package/dist/commons/conditionals/validate.d.ts +52 -2
  9. package/dist/commons/events/ActionDocument.d.ts +6 -0
  10. package/dist/commons/events/ActionInput.d.ts +114 -0
  11. package/dist/commons/events/AdvancedSearchConfig.d.ts +342 -0
  12. package/dist/commons/events/Draft.d.ts +4 -2
  13. package/dist/commons/events/EventDocument.d.ts +3 -0
  14. package/dist/commons/events/EventIndex.d.ts +0 -3
  15. package/dist/commons/events/EventMetadata.d.ts +0 -7
  16. package/dist/commons/events/FieldConfig.d.ts +382 -50
  17. package/dist/commons/events/FieldValue.d.ts +6 -0
  18. package/dist/commons/events/WorkqueueConfig.d.ts +150 -150
  19. package/dist/commons/events/field.d.ts +53 -1
  20. package/dist/commons/events/index.d.ts +2 -0
  21. package/dist/commons/events/locations.d.ts +21 -0
  22. package/dist/commons/events/mocks.test.utils.d.ts +19 -0
  23. package/dist/commons/events/scopes.d.ts +24 -1
  24. package/dist/commons/events/state/flags.d.ts +16 -0
  25. package/dist/commons/events/state/index.d.ts +0 -4
  26. package/dist/commons/events/state/utils.d.ts +3 -2
  27. package/dist/commons/events/utils.d.ts +13 -2
  28. package/dist/conditionals/index.js +60 -5
  29. package/dist/events/index.js +1004 -253
  30. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.d.ts.map +1 -1
  31. package/dist/migrations/v2.0/add-birth-certificate-issuance-flag.js +60 -35
  32. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +1 -1
  33. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  34. package/dist/migrations/v2.0/checkout-upstream-files.js +1 -2
  35. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +9 -1
  36. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +1 -1
  37. package/dist/migrations/v2.0/delete-infrastructure-directory.js +66 -20
  38. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +3 -0
  39. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +1 -0
  40. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +110 -0
  41. package/dist/migrations/v2.0/index.d.ts +5 -3
  42. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  43. package/dist/migrations/v2.0/index.js +505 -169
  44. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.d.ts.map +1 -1
  45. package/dist/migrations/v2.0/make-built-in-validate-actions-custom.js +90 -1
  46. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +11 -1
  47. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +1 -1
  48. package/dist/migrations/v2.0/merge-infrastructure-directory.js +17 -16
  49. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -1
  50. package/dist/migrations/v2.0/migrate-scopes.js +54 -30
  51. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -1
  52. package/dist/migrations/v2.0/migrate-workqueue-configs.js +140 -59
  53. package/dist/notification/index.js +809 -156
  54. package/dist/scopes/index.d.ts +6 -1
  55. package/dist/scopes/index.js +8 -4
  56. package/opencrvs-toolkit-2.0.0-rc.b388b6b.tgz +0 -0
  57. package/package.json +6 -2
  58. package/tsconfig.tsbuildinfo +1 -1
  59. package/opencrvs-toolkit-2.0.0-rc.b2d066a.tgz +0 -0
package/dist/cli.js CHANGED
@@ -178,6 +178,8 @@ function ensureImports(sourceFile) {
178
178
  var DEFINE_CONFIG_NAME2 = "defineConfig";
179
179
  var ACTIONS_PROPERTY_NAME2 = "actions";
180
180
  var TYPE_PROPERTY_NAME2 = "type";
181
+ var ID_PROPERTY_NAME = "id";
182
+ var FLAGS_PROPERTY_NAME = "flags";
181
183
  var CUSTOM_ACTION_TYPE_PROPERTY_NAME = "customActionType";
182
184
  var AUDIT_HISTORY_LABEL_PROPERTY_NAME = "auditHistoryLabel";
183
185
  var DEDUPLICATION_PROPERTY_NAME = "deduplication";
@@ -187,9 +189,12 @@ var FORM_PROPERTY_NAME = "form";
187
189
  var ACTION_TYPE_ENUM_NAME = "ActionType";
188
190
  var VALIDATE_MEMBER_NAME = "VALIDATE";
189
191
  var CUSTOM_MEMBER_NAME = "CUSTOM";
192
+ var REGISTER_MEMBER_NAME2 = "REGISTER";
190
193
  var VALIDATE_STRING_LITERAL = "VALIDATE";
191
194
  var CUSTOM_STRING_LITERAL = "CUSTOM";
195
+ var REGISTER_STRING_LITERAL2 = "REGISTER";
192
196
  var VALIDATE_DECLARATION_VALUE = "VALIDATE_DECLARATION";
197
+ var VALIDATED_FLAG_VALUE = "validated";
193
198
  function isValidateType(typeInitializer) {
194
199
  if (typeInitializer.getKind() === import_ts_morph2.SyntaxKind.PropertyAccessExpression) {
195
200
  const propAccess = typeInitializer.asKindOrThrow(
@@ -313,6 +318,50 @@ function transformValidateActionToCustom(obj, eventType) {
313
318
  }
314
319
  return true;
315
320
  }
321
+ function isRegisterAction(action) {
322
+ const typeProperty = action.getProperty(TYPE_PROPERTY_NAME2);
323
+ if (!typeProperty || !import_ts_morph2.Node.isPropertyAssignment(typeProperty)) return false;
324
+ const typeInit = typeProperty.getInitializer();
325
+ if (!typeInit) return false;
326
+ if (import_ts_morph2.Node.isPropertyAccessExpression(typeInit)) {
327
+ const enumExpr = typeInit.getExpression();
328
+ return import_ts_morph2.Node.isIdentifier(enumExpr) && enumExpr.getText() === ACTION_TYPE_ENUM_NAME && typeInit.getName() === REGISTER_MEMBER_NAME2;
329
+ }
330
+ if (import_ts_morph2.Node.isStringLiteral(typeInit)) {
331
+ return typeInit.getLiteralValue() === REGISTER_STRING_LITERAL2;
332
+ }
333
+ return false;
334
+ }
335
+ function arrayHasElementWithId(array3, id) {
336
+ for (const el of array3.getElements()) {
337
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(el)) continue;
338
+ const idProp = el.getProperty(ID_PROPERTY_NAME);
339
+ if (!idProp || !import_ts_morph2.Node.isPropertyAssignment(idProp)) continue;
340
+ const idInit = idProp.getInitializer();
341
+ if (idInit && import_ts_morph2.Node.isStringLiteral(idInit) && idInit.getLiteralValue() === id) {
342
+ return true;
343
+ }
344
+ }
345
+ return false;
346
+ }
347
+ function ensureRegisterRemovesValidatedFlag(action) {
348
+ const entry = `{ id: '${VALIDATED_FLAG_VALUE}', operation: 'remove' }`;
349
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME);
350
+ if (flagsProp && import_ts_morph2.Node.isPropertyAssignment(flagsProp)) {
351
+ const flagsInit = flagsProp.getInitializer();
352
+ if (flagsInit && import_ts_morph2.Node.isArrayLiteralExpression(flagsInit)) {
353
+ if (arrayHasElementWithId(flagsInit, VALIDATED_FLAG_VALUE)) return false;
354
+ flagsInit.addElement(entry);
355
+ return true;
356
+ }
357
+ return false;
358
+ }
359
+ action.addPropertyAssignment({
360
+ name: FLAGS_PROPERTY_NAME,
361
+ initializer: `[${entry}]`
362
+ });
363
+ return true;
364
+ }
316
365
  function processFile2(filePath, project) {
317
366
  const sourceFile = project.getSourceFile(filePath);
318
367
  if (!sourceFile) return 0;
@@ -378,6 +427,18 @@ function processFile2(filePath, project) {
378
427
  ` [${import_path2.default.relative(process.cwd(), filePath)}] Added top-level 'flags' array to defineConfig`
379
428
  );
380
429
  }
430
+ if (configHadValidateAction) {
431
+ for (const element of actionsInitializer.getElements()) {
432
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(element)) continue;
433
+ if (!isRegisterAction(element)) continue;
434
+ if (ensureRegisterRemovesValidatedFlag(element)) {
435
+ transformedCount++;
436
+ console.log(
437
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Added '${VALIDATED_FLAG_VALUE}' remove-flag to REGISTER action`
438
+ );
439
+ }
440
+ }
441
+ }
381
442
  if (fileNeedsImports) {
382
443
  ensureImports(sourceFile);
383
444
  }
@@ -424,7 +485,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
424
485
  }
425
486
  console.log(
426
487
  `
427
- Done. Transformed ${totalTransformed} VALIDATE action(s) to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'.`
488
+ Done. Applied ${totalTransformed} change(s): VALIDATE \u2192 CUSTOM (${VALIDATE_DECLARATION_VALUE}) and '${VALIDATED_FLAG_VALUE}' remove-flag on matching REGISTER actions.`
428
489
  );
429
490
  }
430
491
 
@@ -667,14 +728,14 @@ var QUERY_PROPERTY_NAME = "query";
667
728
  var TYPE_PROPERTY_NAME5 = "type";
668
729
  var CLAUSES_PROPERTY_NAME = "clauses";
669
730
  var STATUS_PROPERTY_NAME = "status";
670
- var FLAGS_PROPERTY_NAME = "flags";
731
+ var FLAGS_PROPERTY_NAME2 = "flags";
671
732
  var TERMS_PROPERTY_NAME = "terms";
672
733
  var TERM_PROPERTY_NAME = "term";
673
734
  var ANY_OF_PROPERTY_NAME = "anyOf";
674
735
  var VALIDATED_STATUS_VALUE = "VALIDATED";
675
- var VALIDATED_FLAG_VALUE = "validated";
736
+ var VALIDATED_FLAG_VALUE2 = "validated";
676
737
  function addValidatedFlag(clause) {
677
- const flagsProperty = clause.getProperty(FLAGS_PROPERTY_NAME);
738
+ const flagsProperty = clause.getProperty(FLAGS_PROPERTY_NAME2);
678
739
  if (flagsProperty && import_ts_morph5.Node.isPropertyAssignment(flagsProperty)) {
679
740
  const flagsInit = flagsProperty.getInitializer();
680
741
  if (flagsInit && import_ts_morph5.Node.isObjectLiteralExpression(flagsInit)) {
@@ -682,19 +743,19 @@ function addValidatedFlag(clause) {
682
743
  if (anyOfProperty && import_ts_morph5.Node.isPropertyAssignment(anyOfProperty)) {
683
744
  const anyOfInit = anyOfProperty.getInitializer();
684
745
  if (anyOfInit && import_ts_morph5.Node.isArrayLiteralExpression(anyOfInit)) {
685
- anyOfInit.addElement(`'${VALIDATED_FLAG_VALUE}'`);
746
+ anyOfInit.addElement(`'${VALIDATED_FLAG_VALUE2}'`);
686
747
  }
687
748
  } else {
688
749
  flagsInit.addPropertyAssignment({
689
750
  name: ANY_OF_PROPERTY_NAME,
690
- initializer: `['${VALIDATED_FLAG_VALUE}']`
751
+ initializer: `['${VALIDATED_FLAG_VALUE2}']`
691
752
  });
692
753
  }
693
754
  }
694
755
  } else {
695
756
  clause.addPropertyAssignment({
696
- name: FLAGS_PROPERTY_NAME,
697
- initializer: `{ ${ANY_OF_PROPERTY_NAME}: ['${VALIDATED_FLAG_VALUE}'] }`
757
+ name: FLAGS_PROPERTY_NAME2,
758
+ initializer: `{ ${ANY_OF_PROPERTY_NAME}: ['${VALIDATED_FLAG_VALUE2}'] }`
698
759
  });
699
760
  }
700
761
  }
@@ -860,23 +921,26 @@ var DEFINE_CONFIG_NAME4 = "defineConfig";
860
921
  var DEFINE_WORKQUEUES_NAME2 = "defineWorkqueues";
861
922
  var ACTIONS_PROPERTY_NAME4 = "actions";
862
923
  var ACTION_PROPERTY_NAME = "action";
863
- var FLAGS_PROPERTY_NAME2 = "flags";
924
+ var FLAGS_PROPERTY_NAME3 = "flags";
864
925
  var QUERY_PROPERTY_NAME2 = "query";
865
926
  var TYPE_PROPERTY_NAME6 = "type";
927
+ var ID_PROPERTY_NAME2 = "id";
866
928
  var CLAUSES_PROPERTY_NAME2 = "clauses";
867
929
  var ANY_OF_PROPERTY_NAME2 = "anyOf";
868
930
  var FLAG_ID = "pending-first-certificate-issuance";
869
931
  var REGISTER_TYPE = "REGISTER";
870
932
  var PRINT_CERTIFICATE_TYPE = "PRINT_CERTIFICATE";
871
- var FLAG_DEFINITION_INITIALIZER = `{
933
+ function flagDefinitionInitializer(eventType) {
934
+ return `{
872
935
  id: '${FLAG_ID}',
873
936
  label: {
874
- id: 'event.birth.flag.${FLAG_ID}',
937
+ id: 'event.${eventType}.flag.${FLAG_ID}',
875
938
  defaultMessage: 'Pending first certificate issuance',
876
939
  description: 'Flag label for first certificate issuance'
877
940
  },
878
941
  requiresAction: true
879
942
  }`;
943
+ }
880
944
  function isActionOfType(obj, typeName) {
881
945
  const typeProperty = obj.getProperty(TYPE_PROPERTY_NAME6);
882
946
  if (!typeProperty || !import_ts_morph6.Node.isPropertyAssignment(typeProperty)) return false;
@@ -890,18 +954,20 @@ function isActionOfType(obj, typeName) {
890
954
  }
891
955
  return false;
892
956
  }
893
- function isBirthConfig(configArg) {
894
- const typeProperty = configArg.getProperty(TYPE_PROPERTY_NAME6);
895
- if (!typeProperty || !import_ts_morph6.Node.isPropertyAssignment(typeProperty)) return false;
896
- const initializer = typeProperty.getInitializer();
897
- if (!initializer) return false;
898
- if (import_ts_morph6.Node.isStringLiteral(initializer)) {
899
- return initializer.getLiteralValue().toLowerCase() === "birth";
900
- }
901
- if (import_ts_morph6.Node.isPropertyAccessExpression(initializer)) {
902
- return initializer.getName().toLowerCase() === "birth";
957
+ function getEventType(configArg) {
958
+ for (const propName of [TYPE_PROPERTY_NAME6, ID_PROPERTY_NAME2]) {
959
+ const prop = configArg.getProperty(propName);
960
+ if (!prop || !import_ts_morph6.Node.isPropertyAssignment(prop)) continue;
961
+ const initializer = prop.getInitializer();
962
+ if (!initializer) continue;
963
+ if (import_ts_morph6.Node.isStringLiteral(initializer)) {
964
+ return initializer.getLiteralValue().toLowerCase();
965
+ }
966
+ if (import_ts_morph6.Node.isPropertyAccessExpression(initializer)) {
967
+ return initializer.getName().toLowerCase();
968
+ }
903
969
  }
904
- return false;
970
+ return null;
905
971
  }
906
972
  function hasElementWithId(array3, id) {
907
973
  for (const el of array3.getElements()) {
@@ -915,27 +981,28 @@ function hasElementWithId(array3, id) {
915
981
  }
916
982
  return false;
917
983
  }
918
- function ensureTopLevelFlagDefinition(configArg) {
919
- const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME2);
984
+ function ensureTopLevelFlagDefinition(configArg, eventType) {
985
+ const initializer = flagDefinitionInitializer(eventType);
986
+ const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME3);
920
987
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
921
988
  const flagsInit = flagsProp.getInitializer();
922
989
  if (flagsInit && import_ts_morph6.Node.isArrayLiteralExpression(flagsInit)) {
923
990
  if (hasElementWithId(flagsInit, FLAG_ID)) return false;
924
- flagsInit.addElement(FLAG_DEFINITION_INITIALIZER);
991
+ flagsInit.addElement(initializer);
925
992
  return true;
926
993
  }
927
994
  return false;
928
995
  }
929
996
  configArg.addPropertyAssignment({
930
- name: FLAGS_PROPERTY_NAME2,
997
+ name: FLAGS_PROPERTY_NAME3,
931
998
  initializer: `[
932
- ${FLAG_DEFINITION_INITIALIZER}
999
+ ${initializer}
933
1000
  ]`
934
1001
  });
935
1002
  return true;
936
1003
  }
937
1004
  function ensureActionOperationFlag(action, operation) {
938
- const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME2);
1005
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME3);
939
1006
  const entry = `{ id: '${FLAG_ID}', operation: '${operation}' }`;
940
1007
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
941
1008
  const flagsInit = flagsProp.getInitializer();
@@ -947,16 +1014,18 @@ function ensureActionOperationFlag(action, operation) {
947
1014
  return false;
948
1015
  }
949
1016
  action.addPropertyAssignment({
950
- name: FLAGS_PROPERTY_NAME2,
1017
+ name: FLAGS_PROPERTY_NAME3,
951
1018
  initializer: `[${entry}]`
952
1019
  });
953
1020
  return true;
954
1021
  }
955
- function processBirthConfig(configArg, relPath) {
1022
+ function processConfig(configArg, eventType, relPath) {
956
1023
  let changes = 0;
957
- if (ensureTopLevelFlagDefinition(configArg)) {
1024
+ if (ensureTopLevelFlagDefinition(configArg, eventType)) {
958
1025
  changes++;
959
- console.log(` [${relPath}] Added '${FLAG_ID}' to top-level flags`);
1026
+ console.log(
1027
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' to top-level flags`
1028
+ );
960
1029
  }
961
1030
  const actionsProp = configArg.getProperty(ACTIONS_PROPERTY_NAME4);
962
1031
  if (!actionsProp || !import_ts_morph6.Node.isPropertyAssignment(actionsProp)) return changes;
@@ -970,7 +1039,7 @@ function processBirthConfig(configArg, relPath) {
970
1039
  if (ensureActionOperationFlag(element, "add")) {
971
1040
  changes++;
972
1041
  console.log(
973
- ` [${relPath}] Added '${FLAG_ID}' add-flag to REGISTER action`
1042
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' add-flag to REGISTER action`
974
1043
  );
975
1044
  }
976
1045
  }
@@ -978,7 +1047,7 @@ function processBirthConfig(configArg, relPath) {
978
1047
  if (ensureActionOperationFlag(element, "remove")) {
979
1048
  changes++;
980
1049
  console.log(
981
- ` [${relPath}] Added '${FLAG_ID}' remove-flag to PRINT_CERTIFICATE action`
1050
+ ` [${relPath}] (${eventType}) Added '${FLAG_ID}' remove-flag to PRINT_CERTIFICATE action`
982
1051
  );
983
1052
  }
984
1053
  }
@@ -1007,7 +1076,7 @@ function hasPrintCertificateAction(workqueue) {
1007
1076
  return false;
1008
1077
  }
1009
1078
  function addFlagToQueryClause(clause) {
1010
- const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME2);
1079
+ const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME3);
1011
1080
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
1012
1081
  const flagsInit = flagsProp.getInitializer();
1013
1082
  if (flagsInit && import_ts_morph6.Node.isObjectLiteralExpression(flagsInit)) {
@@ -1032,7 +1101,7 @@ function addFlagToQueryClause(clause) {
1032
1101
  }
1033
1102
  } else {
1034
1103
  clause.addPropertyAssignment({
1035
- name: FLAGS_PROPERTY_NAME2,
1104
+ name: FLAGS_PROPERTY_NAME3,
1036
1105
  initializer: `{ ${ANY_OF_PROPERTY_NAME2}: ['${FLAG_ID}'] }`
1037
1106
  });
1038
1107
  return true;
@@ -1076,8 +1145,9 @@ function processFile6(filePath, project) {
1076
1145
  if (args2.length === 0) continue;
1077
1146
  const configArg = args2[0];
1078
1147
  if (!import_ts_morph6.Node.isObjectLiteralExpression(configArg)) continue;
1079
- if (!isBirthConfig(configArg)) continue;
1080
- totalChanges += processBirthConfig(configArg, relPath);
1148
+ const eventType = getEventType(configArg);
1149
+ if (!eventType) continue;
1150
+ totalChanges += processConfig(configArg, eventType, relPath);
1081
1151
  }
1082
1152
  if (calleeName === DEFINE_WORKQUEUES_NAME2) {
1083
1153
  const args2 = call.getArguments();
@@ -1106,7 +1176,7 @@ function processFile6(filePath, project) {
1106
1176
  async function main6() {
1107
1177
  const srcDir = import_path6.default.join(process.cwd(), "src");
1108
1178
  console.log(
1109
- `Scanning for birth defineConfig and PRINT_CERTIFICATE workqueues in: ${srcDir}
1179
+ `Scanning for defineConfig and PRINT_CERTIFICATE workqueues in: ${srcDir}
1110
1180
  `
1111
1181
  );
1112
1182
  const project = new import_ts_morph6.Project({
@@ -1131,7 +1201,7 @@ async function main6() {
1131
1201
  }
1132
1202
  if (modifiedFiles.length === 0) {
1133
1203
  console.log(
1134
- "No birth configs or PRINT_CERTIFICATE workqueues found. Nothing to do."
1204
+ "No event configs or PRINT_CERTIFICATE workqueues found. Nothing to do."
1135
1205
  );
1136
1206
  return;
1137
1207
  }
@@ -1813,9 +1883,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1813
1883
  }
1814
1884
  return replacedCount;
1815
1885
  }
1816
- function resolveConfigChain(configObj, path23) {
1886
+ function resolveConfigChain(configObj, path24) {
1817
1887
  let current = configObj;
1818
- for (const key of path23) {
1888
+ for (const key of path24) {
1819
1889
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1820
1890
  const prop = current.getProperty(key);
1821
1891
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -2050,6 +2120,10 @@ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} rout
2050
2120
  var import_ts_morph11 = require("ts-morph");
2051
2121
  var import_path11 = __toESM(require("path"));
2052
2122
 
2123
+ // ../commons/src/scopes.deprecated.do-not-use.ts
2124
+ var z4 = __toESM(require("zod/v4"));
2125
+ var import_lodash = require("lodash");
2126
+
2053
2127
  // ../commons/src/scopes.ts
2054
2128
  var z3 = __toESM(require("zod/v4"));
2055
2129
  var qs = __toESM(require("qs"));
@@ -2226,12 +2300,14 @@ var SystemScopeType = z3.enum([
2226
2300
  "organisation.read-locations",
2227
2301
  "user.read",
2228
2302
  "user.create",
2229
- "user.edit"
2303
+ "user.edit",
2304
+ "user.search"
2230
2305
  ]);
2231
2306
  var UserScopeType = SystemScopeType.extract([
2232
2307
  "user.read",
2233
2308
  "user.create",
2234
- "user.edit"
2309
+ "user.edit",
2310
+ "user.search"
2235
2311
  ]);
2236
2312
  var ScopesWithRoleOption = UserScopeType.extract(["user.edit", "user.create"]);
2237
2313
  var UserScopeV2 = z3.discriminatedUnion("type", [
@@ -2240,7 +2316,7 @@ var UserScopeV2 = z3.discriminatedUnion("type", [
2240
2316
  options: AllUserScopeOptions.optional()
2241
2317
  }),
2242
2318
  z3.object({
2243
- type: UserScopeType.extract(["user.read"]),
2319
+ type: UserScopeType.extract(["user.read", "user.search"]),
2244
2320
  options: AccessLevelOptions.optional()
2245
2321
  })
2246
2322
  ]);
@@ -2317,11 +2393,12 @@ var decodeScope = (query) => {
2317
2393
  };
2318
2394
  var DEFAULT_SCOPE_OPTIONS = {
2319
2395
  placeOfEvent: JurisdictionFilter.enum.all,
2320
- accessLevel: JurisdictionFilter.enum.all
2396
+ accessLevel: JurisdictionFilter.enum.all,
2397
+ registeredIn: JurisdictionFilter.enum.all,
2398
+ declaredIn: JurisdictionFilter.enum.all
2321
2399
  };
2322
2400
 
2323
2401
  // ../commons/src/scopes.deprecated.do-not-use.ts
2324
- var z4 = __toESM(require("zod/v4"));
2325
2402
  var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2326
2403
  var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2327
2404
  var SearchScope = z4.object({
@@ -2555,6 +2632,74 @@ var legacyScopeToV2Scope = (v1Scope) => {
2555
2632
  }
2556
2633
  throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2557
2634
  };
2635
+ var MERGEABLE_USER_SCOPE_TYPES = ["user.create", "user.edit"];
2636
+ function isMergeableUserScopeType(type) {
2637
+ return MERGEABLE_USER_SCOPE_TYPES.includes(type);
2638
+ }
2639
+ function decodeLegacyScope(legacy) {
2640
+ const encoded = legacyScopeToV2Scope(legacy);
2641
+ const scope = decodeScope(encoded);
2642
+ if (!scope) {
2643
+ throw new Error(
2644
+ `Could not decode migrated scope from legacy '${legacy}' (encoded: '${encoded}').`
2645
+ );
2646
+ }
2647
+ return { legacy, scope };
2648
+ }
2649
+ function groupByType(entries) {
2650
+ return entries.reduce(
2651
+ (groups, entry) => ({
2652
+ ...groups,
2653
+ [entry.scope.type]: [...groups[entry.scope.type] ?? [], entry]
2654
+ }),
2655
+ {}
2656
+ );
2657
+ }
2658
+ function deduplicateEntries(entries) {
2659
+ return entries.filter(
2660
+ (entry, index) => entries.findIndex((e) => (0, import_lodash.isEqual)(e.scope, entry.scope)) === index
2661
+ );
2662
+ }
2663
+ function mergeEntries(type, entries) {
2664
+ const optionsList = entries.map(
2665
+ (e) => "options" in e.scope && e.scope.options ? e.scope.options : {}
2666
+ );
2667
+ const allKeys = optionsList.flatMap(
2668
+ (opts) => Object.keys(opts).filter((k) => opts[k] !== void 0)
2669
+ );
2670
+ const conflictKey = allKeys.find((key, i) => allKeys.indexOf(key) !== i);
2671
+ if (conflictKey) {
2672
+ const conflicting = entries.filter(
2673
+ (e) => conflictKey in ("options" in e.scope && e.scope.options || {})
2674
+ ).map((e) => JSON.stringify(e.legacy));
2675
+ throw new Error(
2676
+ `Cannot auto-merge two '${type}' scopes that both define '${conflictKey}'. Conflicting legacy scopes: [${conflicting.join(", ")}]. Resolve manually in roles.ts and re-run.`
2677
+ );
2678
+ }
2679
+ const mergedOptions = Object.assign({}, ...optionsList);
2680
+ const merged = Object.keys(mergedOptions).length > 0 ? { type, options: mergedOptions } : { type };
2681
+ const parsed = Scope2.safeParse(merged);
2682
+ if (!parsed.success) {
2683
+ throw new Error(
2684
+ `Merged '${type}' scope failed schema validation: ${parsed.error.message}. Legacy scopes: [${entries.map((e) => JSON.stringify(e.legacy)).join(", ")}].`
2685
+ );
2686
+ }
2687
+ return parsed.data;
2688
+ }
2689
+ function migrateLegacyScopesArrayToV2Scopes(legacyScopes) {
2690
+ const groups = groupByType(legacyScopes.map(decodeLegacyScope));
2691
+ return Object.entries(groups).flatMap(([type, entries]) => {
2692
+ const deduped = deduplicateEntries(entries);
2693
+ if (deduped.length <= 1) return deduped.map((e) => e.scope);
2694
+ if (!isMergeableUserScopeType(type)) {
2695
+ console.warn(
2696
+ `Multiple non-mergeable '${type}' scopes detected after dedup \u2014 kept all as-is. Legacy scopes: [${deduped.map((e) => JSON.stringify(e.legacy)).join(", ")}]. Review whether the duplication is intentional.`
2697
+ );
2698
+ return deduped.map((e) => e.scope);
2699
+ }
2700
+ return [mergeEntries(type, deduped)];
2701
+ });
2702
+ }
2558
2703
 
2559
2704
  // src/migrations/v2.0/migrate-scopes.ts
2560
2705
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
@@ -2592,57 +2737,65 @@ function resolveLegacyScopeFromElement(element) {
2592
2737
  }
2593
2738
  function migrateScopesArrays(rolesFilePath, project) {
2594
2739
  const sourceFile = project.getSourceFile(rolesFilePath);
2595
- if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
2740
+ if (!sourceFile) {
2741
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
2742
+ }
2596
2743
  let migratedCount = 0;
2597
2744
  let removedCount = 0;
2745
+ let mergedCount = 0;
2598
2746
  const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
2747
+ const relPath = import_path11.default.relative(process.cwd(), rolesFilePath);
2599
2748
  for (const scopesProp of scopesProperties) {
2600
2749
  const initializer = scopesProp.getInitializer();
2601
2750
  if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2602
- const elements = initializer.getElements();
2603
- for (let index = elements.length - 1; index >= 0; index--) {
2604
- const element = elements[index];
2605
- if (!import_ts_morph11.Node.isExpression(element)) continue;
2751
+ const rawTexts = [];
2752
+ const legacyStrings = [];
2753
+ let anyChange = false;
2754
+ for (const element of initializer.getElements()) {
2606
2755
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2607
2756
  if (scopeKey && !(scopeKey in SCOPES)) {
2608
2757
  console.warn(
2609
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2758
+ ` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`
2610
2759
  );
2611
- initializer.removeElement(index);
2612
2760
  removedCount++;
2761
+ anyChange = true;
2613
2762
  continue;
2614
2763
  }
2615
2764
  const legacyScope = resolveLegacyScopeFromElement(element);
2616
2765
  if (!legacyScope) {
2617
2766
  console.warn(
2618
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2767
+ ` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`
2619
2768
  );
2769
+ rawTexts.push(element.getText());
2620
2770
  continue;
2621
2771
  }
2622
- try {
2623
- const migratedScope = legacyScopeToV2Scope(legacyScope);
2624
- const scope = decodeScope(migratedScope);
2625
- if (!scope) {
2626
- console.warn(
2627
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2628
- );
2629
- continue;
2630
- }
2631
- element.replaceWithText(JSON.stringify(scope));
2632
- migratedCount++;
2633
- } catch (error) {
2634
- console.warn(
2635
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2636
- );
2637
- }
2772
+ legacyStrings.push(legacyScope);
2773
+ anyChange = true;
2638
2774
  }
2775
+ if (!anyChange) continue;
2776
+ let mergedScopes;
2777
+ try {
2778
+ mergedScopes = migrateLegacyScopesArrayToV2Scopes(legacyStrings);
2779
+ } catch (error) {
2780
+ throw new Error(
2781
+ `[${relPath}] Failed to migrate scopes for role: ${error instanceof Error ? error.message : String(error)}`,
2782
+ { cause: error }
2783
+ );
2784
+ }
2785
+ migratedCount += legacyStrings.length;
2786
+ mergedCount += legacyStrings.length - mergedScopes.length;
2787
+ const outputElements = [
2788
+ ...rawTexts,
2789
+ ...mergedScopes.map((s) => JSON.stringify(s))
2790
+ ];
2791
+ scopesProp.setInitializer(`[${outputElements.join(", ")}]`);
2639
2792
  }
2640
2793
  if (removedCount > 0) {
2641
2794
  console.log(
2642
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
2795
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`
2643
2796
  );
2644
2797
  }
2645
- return { migratedCount, removedCount };
2798
+ return { migratedCount, removedCount, mergedCount };
2646
2799
  }
2647
2800
  function ensureScopesHelpersImport(rolesFilePath, project) {
2648
2801
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -2777,7 +2930,7 @@ async function main11() {
2777
2930
  return;
2778
2931
  }
2779
2932
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2780
- const { migratedCount, removedCount } = migrateScopesArrays(
2933
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(
2781
2934
  rolesFilePath,
2782
2935
  project
2783
2936
  );
@@ -2796,7 +2949,7 @@ async function main11() {
2796
2949
  }
2797
2950
  await sourceFile.save();
2798
2951
  console.log(
2799
- `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." : "."}`
2952
+ `Done. Migrated ${migratedCount} legacy scope(s), merged ${mergedCount} AND-paired scope(s) into single v2 objects (privilege-escalation fix, see issue #12489), 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." : "."}`
2800
2953
  );
2801
2954
  }
2802
2955
 
@@ -3602,6 +3755,10 @@ var ACTION_PROPERTY_NAME2 = "action";
3602
3755
  var CONDITIONALS_PROPERTY_NAME = "conditionals";
3603
3756
  var TYPE_PROPERTY_NAME7 = "type";
3604
3757
  var SLUG_PROPERTY_NAME = "slug";
3758
+ var READ_ACTION_TYPE = "READ";
3759
+ var ACTION_TYPE_IMPORT_NAME = "ActionType";
3760
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
3761
+ var READ_ACTION_FALLBACK_INITIALIZER = `{ type: ${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE} }`;
3605
3762
  var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
3606
3763
  "READ",
3607
3764
  "DELETE",
@@ -3649,91 +3806,137 @@ function isUnsupportedActionType(action) {
3649
3806
  }
3650
3807
  return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3651
3808
  }
3652
- function migrateWorkqueueActions(workqueue, relPath) {
3653
- const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3654
- if (!actionsProperty || !import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3655
- return 0;
3656
- }
3657
- const actionsInitializer = actionsProperty.getInitializer();
3658
- if (!actionsInitializer || !import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3659
- return 0;
3809
+ function ensureValidAction(workqueue, relPath) {
3810
+ const workqueueLabel = getWorkqueueLabel(workqueue);
3811
+ const actionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3812
+ if (actionProperty && import_ts_morph17.Node.isPropertyAssignment(actionProperty)) {
3813
+ const initializer = actionProperty.getInitializer();
3814
+ if (initializer && import_ts_morph17.Node.isObjectLiteralExpression(initializer)) {
3815
+ if (!isUnsupportedActionType(initializer)) {
3816
+ return { changed: false, usedReadFallback: false };
3817
+ }
3818
+ actionProperty.set({
3819
+ name: ACTION_PROPERTY_NAME2,
3820
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3821
+ });
3822
+ console.log(
3823
+ ` [${relPath}] Replaced unsupported 'action' type with '${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE}' on workqueue '${workqueueLabel}'`
3824
+ );
3825
+ return { changed: true, usedReadFallback: true };
3826
+ }
3660
3827
  }
3828
+ workqueue.addPropertyAssignment({
3829
+ name: ACTION_PROPERTY_NAME2,
3830
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3831
+ });
3832
+ console.log(
3833
+ ` [${relPath}] Added default 'action: ${READ_ACTION_FALLBACK_INITIALIZER}' to workqueue '${workqueueLabel}'`
3834
+ );
3835
+ return { changed: true, usedReadFallback: true };
3836
+ }
3837
+ function migrateWorkqueueActions(workqueue, relPath) {
3661
3838
  const workqueueLabel = getWorkqueueLabel(workqueue);
3662
- const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3663
- if (existingActionProperty) {
3664
- if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3665
- const existingActionInitializer = existingActionProperty.getInitializer();
3666
- if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3667
- const conditionalsProperty2 = existingActionInitializer.getProperty(
3668
- CONDITIONALS_PROPERTY_NAME
3839
+ const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3840
+ let actionsArrayMigrated = false;
3841
+ if (actionsProperty && import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3842
+ const actionsInitializer = actionsProperty.getInitializer();
3843
+ if (actionsInitializer && import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3844
+ const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3845
+ if (existingActionProperty) {
3846
+ if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3847
+ const existingActionInitializer = existingActionProperty.getInitializer();
3848
+ if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3849
+ const conditionalsProperty = existingActionInitializer.getProperty(
3850
+ CONDITIONALS_PROPERTY_NAME
3851
+ );
3852
+ if (conditionalsProperty) {
3853
+ conditionalsProperty.remove();
3854
+ console.log(
3855
+ ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3856
+ );
3857
+ }
3858
+ }
3859
+ }
3860
+ actionsProperty.remove();
3861
+ console.log(
3862
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3669
3863
  );
3670
- if (conditionalsProperty2) {
3671
- conditionalsProperty2.remove();
3864
+ actionsArrayMigrated = true;
3865
+ } else {
3866
+ const actionCandidates = actionsInitializer.getElements().filter(
3867
+ (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3868
+ );
3869
+ if (actionCandidates.length === 0) {
3870
+ actionsProperty.remove();
3672
3871
  console.log(
3673
- ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3872
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3674
3873
  );
3675
- }
3676
- if (isUnsupportedActionType(existingActionInitializer)) {
3677
- existingActionProperty.remove();
3678
- console.log(
3679
- ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
3874
+ actionsArrayMigrated = true;
3875
+ } else {
3876
+ if (actionCandidates.length > 1) {
3877
+ const droppedCount = actionCandidates.length - 1;
3878
+ console.warn(
3879
+ ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3880
+ );
3881
+ }
3882
+ const conditionalsProperty = actionCandidates[0].getProperty(
3883
+ CONDITIONALS_PROPERTY_NAME
3680
3884
  );
3885
+ if (conditionalsProperty) {
3886
+ conditionalsProperty.remove();
3887
+ console.log(
3888
+ ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3889
+ );
3890
+ }
3891
+ if (isUnsupportedActionType(actionCandidates[0])) {
3892
+ actionsProperty.remove();
3893
+ console.log(
3894
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3895
+ );
3896
+ actionsArrayMigrated = true;
3897
+ } else {
3898
+ const firstActionText = actionCandidates[0].getText();
3899
+ workqueue.addPropertyAssignment({
3900
+ name: ACTION_PROPERTY_NAME2,
3901
+ initializer: firstActionText
3902
+ });
3903
+ actionsProperty.remove();
3904
+ console.log(
3905
+ ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3906
+ );
3907
+ actionsArrayMigrated = true;
3908
+ }
3681
3909
  }
3682
3910
  }
3683
3911
  }
3684
- actionsProperty.remove();
3685
- console.log(
3686
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3687
- );
3688
- return 1;
3689
3912
  }
3690
- const actionCandidates = actionsInitializer.getElements().filter(
3691
- (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3692
- );
3693
- if (actionCandidates.length === 0) {
3694
- actionsProperty.remove();
3695
- console.log(
3696
- ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3697
- );
3698
- return 1;
3699
- }
3700
- if (actionCandidates.length > 1) {
3701
- const droppedCount = actionCandidates.length - 1;
3702
- console.warn(
3703
- ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3704
- );
3705
- }
3706
- const conditionalsProperty = actionCandidates[0].getProperty(
3707
- CONDITIONALS_PROPERTY_NAME
3913
+ const fallback = ensureValidAction(workqueue, relPath);
3914
+ return {
3915
+ changed: actionsArrayMigrated || fallback.changed,
3916
+ usedReadFallback: fallback.usedReadFallback
3917
+ };
3918
+ }
3919
+ function ensureActionTypeImport(sourceFile) {
3920
+ const existingImport = sourceFile.getImportDeclaration(
3921
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2
3708
3922
  );
3709
- if (conditionalsProperty) {
3710
- conditionalsProperty.remove();
3711
- console.log(
3712
- ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3713
- );
3714
- }
3715
- if (isUnsupportedActionType(actionCandidates[0])) {
3716
- actionsProperty.remove();
3717
- console.log(
3718
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3719
- );
3720
- return 1;
3923
+ if (existingImport) {
3924
+ const alreadyImported = existingImport.getNamedImports().some((ni) => ni.getName() === ACTION_TYPE_IMPORT_NAME);
3925
+ if (!alreadyImported) {
3926
+ existingImport.addNamedImport(ACTION_TYPE_IMPORT_NAME);
3927
+ }
3928
+ return;
3721
3929
  }
3722
- const firstActionText = actionCandidates[0].getText();
3723
- workqueue.addPropertyAssignment({
3724
- name: ACTION_PROPERTY_NAME2,
3725
- initializer: firstActionText
3930
+ sourceFile.addImportDeclaration({
3931
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE2,
3932
+ namedImports: [ACTION_TYPE_IMPORT_NAME]
3726
3933
  });
3727
- actionsProperty.remove();
3728
- console.log(
3729
- ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3730
- );
3731
- return 1;
3732
3934
  }
3733
3935
  function processFile13(filePath, project) {
3734
3936
  const sourceFile = project.getSourceFile(filePath);
3735
3937
  if (!sourceFile) return 0;
3736
3938
  let migratedWorkqueues = 0;
3939
+ let needsActionTypeImport = false;
3737
3940
  const relPath = import_path18.default.relative(process.cwd(), filePath);
3738
3941
  const callExpressions = sourceFile.getDescendantsOfKind(
3739
3942
  import_ts_morph17.SyntaxKind.CallExpression
@@ -3749,9 +3952,14 @@ function processFile13(filePath, project) {
3749
3952
  if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3750
3953
  for (const element of workqueuesArg.getElements()) {
3751
3954
  if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3752
- migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3955
+ const result = migrateWorkqueueActions(element, relPath);
3956
+ if (result.changed) migratedWorkqueues++;
3957
+ if (result.usedReadFallback) needsActionTypeImport = true;
3753
3958
  }
3754
3959
  }
3960
+ if (needsActionTypeImport) {
3961
+ ensureActionTypeImport(sourceFile);
3962
+ }
3755
3963
  return migratedWorkqueues;
3756
3964
  }
3757
3965
  async function main18() {
@@ -4086,7 +4294,7 @@ Saved ${handlerRelPath}.`);
4086
4294
  // src/migrations/v2.0/checkout-upstream-files.ts
4087
4295
  var import_child_process = require("child_process");
4088
4296
  var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
4089
- var UPSTREAM_BRANCH = "develop";
4297
+ var UPSTREAM_BRANCH = "release-v2.0.0";
4090
4298
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
4091
4299
  var FILES_TO_CHECKOUT = [
4092
4300
  "src/analytics/analytics.ts",
@@ -4625,9 +4833,9 @@ var import_path24 = require("path");
4625
4833
  var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4626
4834
  var INFRASTRUCTURE_DIR = "infrastructure";
4627
4835
  var BASE_BRANCH = "release-v1.9";
4628
- function gitShowBytes(ref, path23) {
4836
+ function gitShowBytes(ref, path24) {
4629
4837
  try {
4630
- const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path23}`], {
4838
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path24}`], {
4631
4839
  cwd: process.cwd(),
4632
4840
  stdio: ["ignore", "pipe", "pipe"]
4633
4841
  });
@@ -4636,9 +4844,13 @@ function gitShowBytes(ref, path23) {
4636
4844
  return null;
4637
4845
  }
4638
4846
  }
4639
- async function main25() {
4847
+ async function main25({
4848
+ subdirs = []
4849
+ } = {}) {
4850
+ const pathspecs = subdirs.length > 0 ? subdirs.map((s) => `${INFRASTRUCTURE_DIR}/${s}/`) : [`${INFRASTRUCTURE_DIR}/`];
4851
+ const scopeLabel = pathspecs.map((p) => `'${p}'`).join(", ");
4640
4852
  console.log(
4641
- `Merging '${INFRASTRUCTURE_DIR}/' from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4853
+ `Merging ${scopeLabel} from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4642
4854
  `
4643
4855
  );
4644
4856
  assertIsGitRepo();
@@ -4653,20 +4865,12 @@ async function main25() {
4653
4865
  const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4654
4866
  const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4655
4867
  const upstreamFiles = runGit(
4656
- [
4657
- "ls-tree",
4658
- "-r",
4659
- "--name-only",
4660
- "-z",
4661
- ref,
4662
- "--",
4663
- `${INFRASTRUCTURE_DIR}/`
4664
- ],
4868
+ ["ls-tree", "-r", "--name-only", "-z", ref, "--", ...pathspecs],
4665
4869
  { silent: true }
4666
4870
  ).split("\0").filter(Boolean);
4667
4871
  if (upstreamFiles.length === 0) {
4668
4872
  console.log(
4669
- ` No files found under '${INFRASTRUCTURE_DIR}/' on ${ref}. Nothing to merge.`
4873
+ ` No files found under ${scopeLabel} on ${ref}. Nothing to merge.`
4670
4874
  );
4671
4875
  return;
4672
4876
  }
@@ -4741,7 +4945,9 @@ async function main25() {
4741
4945
  var import_fs6 = require("fs");
4742
4946
  var import_path25 = require("path");
4743
4947
  var INFRASTRUCTURE_DIR2 = "infrastructure";
4744
- async function main26() {
4948
+ async function main26({
4949
+ keep = []
4950
+ } = {}) {
4745
4951
  const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4746
4952
  if (!(0, import_fs6.existsSync)(fullPath)) {
4747
4953
  console.log(
@@ -4749,24 +4955,152 @@ async function main26() {
4749
4955
  );
4750
4956
  return;
4751
4957
  }
4752
- console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4753
- `);
4754
4958
  assertIsGitRepo();
4755
- runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4756
- silent: true
4959
+ if (keep.length === 0) {
4960
+ console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4961
+ `);
4962
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4963
+ silent: true
4964
+ });
4965
+ console.log(
4966
+ ` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`
4967
+ );
4968
+ if ((0, import_fs6.existsSync)(fullPath)) {
4969
+ (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4970
+ console.log(
4971
+ ` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`
4972
+ );
4973
+ }
4974
+ console.log(
4975
+ `
4976
+ Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4977
+ );
4978
+ return;
4979
+ }
4980
+ const keepSet = new Set(keep);
4981
+ console.log(
4982
+ `Deleting contents of '${INFRASTRUCTURE_DIR2}/' except: ${[...keepSet].map((name) => `'${name}'`).join(", ")}
4983
+ `
4984
+ );
4985
+ const topLevelEntries = (0, import_fs6.readdirSync)(fullPath, { withFileTypes: true });
4986
+ let deleted = 0;
4987
+ for (const entry of topLevelEntries) {
4988
+ if (keepSet.has(entry.name)) {
4989
+ console.log(` Keeping '${INFRASTRUCTURE_DIR2}/${entry.name}'.`);
4990
+ continue;
4991
+ }
4992
+ const relPath = `${INFRASTRUCTURE_DIR2}/${entry.name}${entry.isDirectory() ? "/" : ""}`;
4993
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", relPath], { silent: true });
4994
+ const fullEntryPath = (0, import_path25.join)(fullPath, entry.name);
4995
+ if ((0, import_fs6.existsSync)(fullEntryPath)) {
4996
+ (0, import_fs6.rmSync)(fullEntryPath, { recursive: true, force: true });
4997
+ }
4998
+ console.log(` Deleted '${relPath}'.`);
4999
+ deleted++;
5000
+ }
5001
+ const presentNames = new Set(topLevelEntries.map((e) => e.name));
5002
+ const missingKeeps = [...keepSet].filter((name) => !presentNames.has(name));
5003
+ if (missingKeeps.length > 0) {
5004
+ console.warn(
5005
+ ` [warn] Requested to keep ${missingKeeps.map((n) => `'${n}'`).join(", ")} but they don't exist under '${INFRASTRUCTURE_DIR2}/'.`
5006
+ );
5007
+ }
5008
+ console.log(
5009
+ `
5010
+ Done. Deleted ${deleted} top-level entr${deleted === 1 ? "y" : "ies"}. Review the staged deletions with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
5011
+ );
5012
+ }
5013
+
5014
+ // src/migrations/v2.0/fix-accept-requested-registration-function-type.ts
5015
+ var import_ts_morph22 = require("ts-morph");
5016
+ var import_path26 = __toESM(require("path"));
5017
+ var TARGET_FUNCTION_NAME = "acceptRequestedRegistration";
5018
+ var ACTION_PARAMETER_NAME = "action";
5019
+ var OLD_TYPE = "ActionInput";
5020
+ var NEW_TYPE = "Extract<ActionInput, { type?: 'REGISTER' }>";
5021
+ function isAcceptRequestedRegistrationParameter(parameter) {
5022
+ const functionDeclaration = parameter.getFirstAncestorByKind(
5023
+ import_ts_morph22.SyntaxKind.FunctionDeclaration
5024
+ );
5025
+ if (functionDeclaration?.getName() === TARGET_FUNCTION_NAME) {
5026
+ return true;
5027
+ }
5028
+ const arrowFunction = parameter.getFirstAncestorByKind(
5029
+ import_ts_morph22.SyntaxKind.ArrowFunction
5030
+ );
5031
+ const variableDeclaration = arrowFunction?.getFirstAncestorByKind(
5032
+ import_ts_morph22.SyntaxKind.VariableDeclaration
5033
+ );
5034
+ return variableDeclaration?.getName() === TARGET_FUNCTION_NAME;
5035
+ }
5036
+ function processFile14(filePath, project) {
5037
+ const sourceFile = project.getSourceFile(filePath);
5038
+ if (!sourceFile) return 0;
5039
+ let updatedCount = 0;
5040
+ for (const parameter of sourceFile.getDescendantsOfKind(
5041
+ import_ts_morph22.SyntaxKind.Parameter
5042
+ )) {
5043
+ if (parameter.getName() !== ACTION_PARAMETER_NAME) {
5044
+ continue;
5045
+ }
5046
+ if (!isAcceptRequestedRegistrationParameter(parameter)) {
5047
+ continue;
5048
+ }
5049
+ const typeNode = parameter.getTypeNode();
5050
+ if (!typeNode || typeNode.getText() !== OLD_TYPE) {
5051
+ continue;
5052
+ }
5053
+ parameter.setType(NEW_TYPE);
5054
+ updatedCount++;
5055
+ console.log(
5056
+ ` [${import_path26.default.relative(process.cwd(), filePath)}] Updated '${ACTION_PARAMETER_NAME}' in ${TARGET_FUNCTION_NAME} to ${NEW_TYPE}`
5057
+ );
5058
+ }
5059
+ return updatedCount;
5060
+ }
5061
+ async function main27() {
5062
+ const srcDir = import_path26.default.join(process.cwd(), "src");
5063
+ console.log(`Scanning for ${TARGET_FUNCTION_NAME} in: ${srcDir}
5064
+ `);
5065
+ const project = new import_ts_morph22.Project({
5066
+ tsConfigFilePath: import_path26.default.resolve(srcDir, "../tsconfig.json"),
5067
+ skipAddingFilesFromTsConfig: false
4757
5068
  });
4758
- console.log(` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4759
- if ((0, import_fs6.existsSync)(fullPath)) {
4760
- (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4761
- console.log(` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`);
5069
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
5070
+ const filePath = sf.getFilePath();
5071
+ return filePath.includes("/src/") && !filePath.includes("/node_modules/");
5072
+ });
5073
+ let totalUpdated = 0;
5074
+ const modifiedFiles = [];
5075
+ for (const sourceFile of sourceFiles) {
5076
+ const filePath = sourceFile.getFilePath();
5077
+ const updated = processFile14(filePath, project);
5078
+ if (updated > 0) {
5079
+ totalUpdated += updated;
5080
+ modifiedFiles.push(filePath);
5081
+ }
5082
+ }
5083
+ if (modifiedFiles.length === 0) {
5084
+ console.log(
5085
+ `No '${ACTION_PARAMETER_NAME}: ${OLD_TYPE}' parameter in ${TARGET_FUNCTION_NAME} found. Nothing to do.`
5086
+ );
5087
+ return;
5088
+ }
5089
+ console.log(`
5090
+ Saving ${modifiedFiles.length} modified file(s)...`);
5091
+ for (const filePath of modifiedFiles) {
5092
+ const sourceFile = project.getSourceFileOrThrow(filePath);
5093
+ await sourceFile.save();
5094
+ console.log(` Saved: ${import_path26.default.relative(process.cwd(), filePath)}`);
4762
5095
  }
4763
5096
  console.log(
4764
5097
  `
4765
- Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
5098
+ Done. Updated ${totalUpdated} parameter type annotation(s) in ${TARGET_FUNCTION_NAME}.`
4766
5099
  );
4767
5100
  }
4768
5101
 
4769
5102
  // src/migrations/v2.0/index.ts
5103
+ var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
4770
5104
  async function runUpgrade(dockerSwarm) {
4771
5105
  await main18();
4772
5106
  await main();
@@ -4791,11 +5125,13 @@ async function runUpgrade(dockerSwarm) {
4791
5125
  await main22();
4792
5126
  await main23();
4793
5127
  await main24();
5128
+ await main27();
4794
5129
  await main17();
4795
5130
  if (dockerSwarm) {
4796
5131
  await main25();
4797
5132
  } else {
4798
- await main26();
5133
+ await main26({ keep: NON_SWARM_INFRA_SUBDIRS });
5134
+ await main25({ subdirs: NON_SWARM_INFRA_SUBDIRS });
4799
5135
  }
4800
5136
  }
4801
5137
 
@@ -4824,7 +5160,7 @@ Options:
4824
5160
  'infrastructure/' directory is deleted (default).
4825
5161
  -h, --help Show this message.
4826
5162
  `.trim();
4827
- function main27() {
5163
+ function main28() {
4828
5164
  const command = args[0];
4829
5165
  if (!command || command === "--help" || command === "-h") {
4830
5166
  console.log(USAGE);
@@ -4899,4 +5235,4 @@ function handleCheckTranslations() {
4899
5235
  console.warn("This command is not implemented yet!");
4900
5236
  process.exit(1);
4901
5237
  }
4902
- main27();
5238
+ main28();