@opencrvs/toolkit 2.0.0-rc.2e68bac → 2.0.0-rc.2e6b38d

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 +276 -122
  4. package/dist/cli.js +484 -151
  5. package/dist/commons/api/router.d.ts +3377 -237
  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 +383 -50
  17. package/dist/commons/events/FieldType.d.ts +1 -0
  18. package/dist/commons/events/FieldTypeMapping.d.ts +1 -1
  19. package/dist/commons/events/FieldValue.d.ts +6 -0
  20. package/dist/commons/events/WorkqueueConfig.d.ts +150 -150
  21. package/dist/commons/events/field.d.ts +53 -1
  22. package/dist/commons/events/index.d.ts +2 -0
  23. package/dist/commons/events/locations.d.ts +21 -0
  24. package/dist/commons/events/mocks.test.utils.d.ts +19 -0
  25. package/dist/commons/events/scopes.d.ts +24 -1
  26. package/dist/commons/events/state/flags.d.ts +16 -0
  27. package/dist/commons/events/state/index.d.ts +0 -4
  28. package/dist/commons/events/state/utils.d.ts +12 -289
  29. package/dist/commons/events/utils.d.ts +13 -2
  30. package/dist/conditionals/index.js +60 -5
  31. package/dist/events/index.js +1040 -268
  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 +482 -149
  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 +830 -157
  54. package/dist/scopes/index.d.ts +10 -7
  55. package/dist/scopes/index.js +17 -7
  56. package/opencrvs-toolkit-2.0.0-rc.2e6b38d.tgz +0 -0
  57. package/package.json +6 -2
  58. package/tsconfig.tsbuildinfo +1 -1
  59. package/opencrvs-toolkit-2.0.0-rc.2e68bac.tgz +0 -0
@@ -190,6 +190,8 @@ function ensureImports(sourceFile) {
190
190
  var DEFINE_CONFIG_NAME2 = "defineConfig";
191
191
  var ACTIONS_PROPERTY_NAME2 = "actions";
192
192
  var TYPE_PROPERTY_NAME2 = "type";
193
+ var ID_PROPERTY_NAME = "id";
194
+ var FLAGS_PROPERTY_NAME = "flags";
193
195
  var CUSTOM_ACTION_TYPE_PROPERTY_NAME = "customActionType";
194
196
  var AUDIT_HISTORY_LABEL_PROPERTY_NAME = "auditHistoryLabel";
195
197
  var DEDUPLICATION_PROPERTY_NAME = "deduplication";
@@ -199,9 +201,12 @@ var FORM_PROPERTY_NAME = "form";
199
201
  var ACTION_TYPE_ENUM_NAME = "ActionType";
200
202
  var VALIDATE_MEMBER_NAME = "VALIDATE";
201
203
  var CUSTOM_MEMBER_NAME = "CUSTOM";
204
+ var REGISTER_MEMBER_NAME2 = "REGISTER";
202
205
  var VALIDATE_STRING_LITERAL = "VALIDATE";
203
206
  var CUSTOM_STRING_LITERAL = "CUSTOM";
207
+ var REGISTER_STRING_LITERAL2 = "REGISTER";
204
208
  var VALIDATE_DECLARATION_VALUE = "VALIDATE_DECLARATION";
209
+ var VALIDATED_FLAG_VALUE = "validated";
205
210
  function isValidateType(typeInitializer) {
206
211
  if (typeInitializer.getKind() === import_ts_morph2.SyntaxKind.PropertyAccessExpression) {
207
212
  const propAccess = typeInitializer.asKindOrThrow(
@@ -325,6 +330,50 @@ function transformValidateActionToCustom(obj, eventType) {
325
330
  }
326
331
  return true;
327
332
  }
333
+ function isRegisterAction(action) {
334
+ const typeProperty = action.getProperty(TYPE_PROPERTY_NAME2);
335
+ if (!typeProperty || !import_ts_morph2.Node.isPropertyAssignment(typeProperty)) return false;
336
+ const typeInit = typeProperty.getInitializer();
337
+ if (!typeInit) return false;
338
+ if (import_ts_morph2.Node.isPropertyAccessExpression(typeInit)) {
339
+ const enumExpr = typeInit.getExpression();
340
+ return import_ts_morph2.Node.isIdentifier(enumExpr) && enumExpr.getText() === ACTION_TYPE_ENUM_NAME && typeInit.getName() === REGISTER_MEMBER_NAME2;
341
+ }
342
+ if (import_ts_morph2.Node.isStringLiteral(typeInit)) {
343
+ return typeInit.getLiteralValue() === REGISTER_STRING_LITERAL2;
344
+ }
345
+ return false;
346
+ }
347
+ function arrayHasElementWithId(array3, id) {
348
+ for (const el of array3.getElements()) {
349
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(el)) continue;
350
+ const idProp = el.getProperty(ID_PROPERTY_NAME);
351
+ if (!idProp || !import_ts_morph2.Node.isPropertyAssignment(idProp)) continue;
352
+ const idInit = idProp.getInitializer();
353
+ if (idInit && import_ts_morph2.Node.isStringLiteral(idInit) && idInit.getLiteralValue() === id) {
354
+ return true;
355
+ }
356
+ }
357
+ return false;
358
+ }
359
+ function ensureRegisterRemovesValidatedFlag(action) {
360
+ const entry = `{ id: '${VALIDATED_FLAG_VALUE}', operation: 'remove' }`;
361
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME);
362
+ if (flagsProp && import_ts_morph2.Node.isPropertyAssignment(flagsProp)) {
363
+ const flagsInit = flagsProp.getInitializer();
364
+ if (flagsInit && import_ts_morph2.Node.isArrayLiteralExpression(flagsInit)) {
365
+ if (arrayHasElementWithId(flagsInit, VALIDATED_FLAG_VALUE)) return false;
366
+ flagsInit.addElement(entry);
367
+ return true;
368
+ }
369
+ return false;
370
+ }
371
+ action.addPropertyAssignment({
372
+ name: FLAGS_PROPERTY_NAME,
373
+ initializer: `[${entry}]`
374
+ });
375
+ return true;
376
+ }
328
377
  function processFile2(filePath, project) {
329
378
  const sourceFile = project.getSourceFile(filePath);
330
379
  if (!sourceFile) return 0;
@@ -390,6 +439,18 @@ function processFile2(filePath, project) {
390
439
  ` [${import_path2.default.relative(process.cwd(), filePath)}] Added top-level 'flags' array to defineConfig`
391
440
  );
392
441
  }
442
+ if (configHadValidateAction) {
443
+ for (const element of actionsInitializer.getElements()) {
444
+ if (!import_ts_morph2.Node.isObjectLiteralExpression(element)) continue;
445
+ if (!isRegisterAction(element)) continue;
446
+ if (ensureRegisterRemovesValidatedFlag(element)) {
447
+ transformedCount++;
448
+ console.log(
449
+ ` [${import_path2.default.relative(process.cwd(), filePath)}] Added '${VALIDATED_FLAG_VALUE}' remove-flag to REGISTER action`
450
+ );
451
+ }
452
+ }
453
+ }
393
454
  if (fileNeedsImports) {
394
455
  ensureImports(sourceFile);
395
456
  }
@@ -436,7 +497,7 @@ Saving ${modifiedFiles.length} modified file(s)...`);
436
497
  }
437
498
  console.log(
438
499
  `
439
- Done. Transformed ${totalTransformed} VALIDATE action(s) to CUSTOM with customActionType: '${VALIDATE_DECLARATION_VALUE}'.`
500
+ Done. Applied ${totalTransformed} change(s): VALIDATE \u2192 CUSTOM (${VALIDATE_DECLARATION_VALUE}) and '${VALIDATED_FLAG_VALUE}' remove-flag on matching REGISTER actions.`
440
501
  );
441
502
  }
442
503
 
@@ -679,14 +740,14 @@ var QUERY_PROPERTY_NAME = "query";
679
740
  var TYPE_PROPERTY_NAME5 = "type";
680
741
  var CLAUSES_PROPERTY_NAME = "clauses";
681
742
  var STATUS_PROPERTY_NAME = "status";
682
- var FLAGS_PROPERTY_NAME = "flags";
743
+ var FLAGS_PROPERTY_NAME2 = "flags";
683
744
  var TERMS_PROPERTY_NAME = "terms";
684
745
  var TERM_PROPERTY_NAME = "term";
685
746
  var ANY_OF_PROPERTY_NAME = "anyOf";
686
747
  var VALIDATED_STATUS_VALUE = "VALIDATED";
687
- var VALIDATED_FLAG_VALUE = "validated";
748
+ var VALIDATED_FLAG_VALUE2 = "validated";
688
749
  function addValidatedFlag(clause) {
689
- const flagsProperty = clause.getProperty(FLAGS_PROPERTY_NAME);
750
+ const flagsProperty = clause.getProperty(FLAGS_PROPERTY_NAME2);
690
751
  if (flagsProperty && import_ts_morph5.Node.isPropertyAssignment(flagsProperty)) {
691
752
  const flagsInit = flagsProperty.getInitializer();
692
753
  if (flagsInit && import_ts_morph5.Node.isObjectLiteralExpression(flagsInit)) {
@@ -694,19 +755,19 @@ function addValidatedFlag(clause) {
694
755
  if (anyOfProperty && import_ts_morph5.Node.isPropertyAssignment(anyOfProperty)) {
695
756
  const anyOfInit = anyOfProperty.getInitializer();
696
757
  if (anyOfInit && import_ts_morph5.Node.isArrayLiteralExpression(anyOfInit)) {
697
- anyOfInit.addElement(`'${VALIDATED_FLAG_VALUE}'`);
758
+ anyOfInit.addElement(`'${VALIDATED_FLAG_VALUE2}'`);
698
759
  }
699
760
  } else {
700
761
  flagsInit.addPropertyAssignment({
701
762
  name: ANY_OF_PROPERTY_NAME,
702
- initializer: `['${VALIDATED_FLAG_VALUE}']`
763
+ initializer: `['${VALIDATED_FLAG_VALUE2}']`
703
764
  });
704
765
  }
705
766
  }
706
767
  } else {
707
768
  clause.addPropertyAssignment({
708
- name: FLAGS_PROPERTY_NAME,
709
- initializer: `{ ${ANY_OF_PROPERTY_NAME}: ['${VALIDATED_FLAG_VALUE}'] }`
769
+ name: FLAGS_PROPERTY_NAME2,
770
+ initializer: `{ ${ANY_OF_PROPERTY_NAME}: ['${VALIDATED_FLAG_VALUE2}'] }`
710
771
  });
711
772
  }
712
773
  }
@@ -872,10 +933,10 @@ var DEFINE_CONFIG_NAME4 = "defineConfig";
872
933
  var DEFINE_WORKQUEUES_NAME2 = "defineWorkqueues";
873
934
  var ACTIONS_PROPERTY_NAME4 = "actions";
874
935
  var ACTION_PROPERTY_NAME = "action";
875
- var FLAGS_PROPERTY_NAME2 = "flags";
936
+ var FLAGS_PROPERTY_NAME3 = "flags";
876
937
  var QUERY_PROPERTY_NAME2 = "query";
877
938
  var TYPE_PROPERTY_NAME6 = "type";
878
- var ID_PROPERTY_NAME = "id";
939
+ var ID_PROPERTY_NAME2 = "id";
879
940
  var CLAUSES_PROPERTY_NAME2 = "clauses";
880
941
  var ANY_OF_PROPERTY_NAME2 = "anyOf";
881
942
  var FLAG_ID = "pending-first-certificate-issuance";
@@ -906,7 +967,7 @@ function isActionOfType(obj, typeName) {
906
967
  return false;
907
968
  }
908
969
  function getEventType(configArg) {
909
- for (const propName of [TYPE_PROPERTY_NAME6, ID_PROPERTY_NAME]) {
970
+ for (const propName of [TYPE_PROPERTY_NAME6, ID_PROPERTY_NAME2]) {
910
971
  const prop = configArg.getProperty(propName);
911
972
  if (!prop || !import_ts_morph6.Node.isPropertyAssignment(prop)) continue;
912
973
  const initializer = prop.getInitializer();
@@ -934,7 +995,7 @@ function hasElementWithId(array3, id) {
934
995
  }
935
996
  function ensureTopLevelFlagDefinition(configArg, eventType) {
936
997
  const initializer = flagDefinitionInitializer(eventType);
937
- const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME2);
998
+ const flagsProp = configArg.getProperty(FLAGS_PROPERTY_NAME3);
938
999
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
939
1000
  const flagsInit = flagsProp.getInitializer();
940
1001
  if (flagsInit && import_ts_morph6.Node.isArrayLiteralExpression(flagsInit)) {
@@ -945,7 +1006,7 @@ function ensureTopLevelFlagDefinition(configArg, eventType) {
945
1006
  return false;
946
1007
  }
947
1008
  configArg.addPropertyAssignment({
948
- name: FLAGS_PROPERTY_NAME2,
1009
+ name: FLAGS_PROPERTY_NAME3,
949
1010
  initializer: `[
950
1011
  ${initializer}
951
1012
  ]`
@@ -953,7 +1014,7 @@ function ensureTopLevelFlagDefinition(configArg, eventType) {
953
1014
  return true;
954
1015
  }
955
1016
  function ensureActionOperationFlag(action, operation) {
956
- const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME2);
1017
+ const flagsProp = action.getProperty(FLAGS_PROPERTY_NAME3);
957
1018
  const entry = `{ id: '${FLAG_ID}', operation: '${operation}' }`;
958
1019
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
959
1020
  const flagsInit = flagsProp.getInitializer();
@@ -965,7 +1026,7 @@ function ensureActionOperationFlag(action, operation) {
965
1026
  return false;
966
1027
  }
967
1028
  action.addPropertyAssignment({
968
- name: FLAGS_PROPERTY_NAME2,
1029
+ name: FLAGS_PROPERTY_NAME3,
969
1030
  initializer: `[${entry}]`
970
1031
  });
971
1032
  return true;
@@ -1027,7 +1088,7 @@ function hasPrintCertificateAction(workqueue) {
1027
1088
  return false;
1028
1089
  }
1029
1090
  function addFlagToQueryClause(clause) {
1030
- const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME2);
1091
+ const flagsProp = clause.getProperty(FLAGS_PROPERTY_NAME3);
1031
1092
  if (flagsProp && import_ts_morph6.Node.isPropertyAssignment(flagsProp)) {
1032
1093
  const flagsInit = flagsProp.getInitializer();
1033
1094
  if (flagsInit && import_ts_morph6.Node.isObjectLiteralExpression(flagsInit)) {
@@ -1052,7 +1113,7 @@ function addFlagToQueryClause(clause) {
1052
1113
  }
1053
1114
  } else {
1054
1115
  clause.addPropertyAssignment({
1055
- name: FLAGS_PROPERTY_NAME2,
1116
+ name: FLAGS_PROPERTY_NAME3,
1056
1117
  initializer: `{ ${ANY_OF_PROPERTY_NAME2}: ['${FLAG_ID}'] }`
1057
1118
  });
1058
1119
  return true;
@@ -1834,9 +1895,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1834
1895
  }
1835
1896
  return replacedCount;
1836
1897
  }
1837
- function resolveConfigChain(configObj, path23) {
1898
+ function resolveConfigChain(configObj, path24) {
1838
1899
  let current = configObj;
1839
- for (const key of path23) {
1900
+ for (const key of path24) {
1840
1901
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1841
1902
  const prop = current.getProperty(key);
1842
1903
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -2071,6 +2132,10 @@ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} rout
2071
2132
  var import_ts_morph11 = require("ts-morph");
2072
2133
  var import_path11 = __toESM(require("path"));
2073
2134
 
2135
+ // ../commons/src/scopes.deprecated.do-not-use.ts
2136
+ var z4 = __toESM(require("zod/v4"));
2137
+ var import_lodash = require("lodash");
2138
+
2074
2139
  // ../commons/src/scopes.ts
2075
2140
  var z3 = __toESM(require("zod/v4"));
2076
2141
  var qs = __toESM(require("qs"));
@@ -2247,12 +2312,14 @@ var SystemScopeType = z3.enum([
2247
2312
  "organisation.read-locations",
2248
2313
  "user.read",
2249
2314
  "user.create",
2250
- "user.edit"
2315
+ "user.edit",
2316
+ "user.search"
2251
2317
  ]);
2252
2318
  var UserScopeType = SystemScopeType.extract([
2253
2319
  "user.read",
2254
2320
  "user.create",
2255
- "user.edit"
2321
+ "user.edit",
2322
+ "user.search"
2256
2323
  ]);
2257
2324
  var ScopesWithRoleOption = UserScopeType.extract(["user.edit", "user.create"]);
2258
2325
  var UserScopeV2 = z3.discriminatedUnion("type", [
@@ -2261,7 +2328,7 @@ var UserScopeV2 = z3.discriminatedUnion("type", [
2261
2328
  options: AllUserScopeOptions.optional()
2262
2329
  }),
2263
2330
  z3.object({
2264
- type: UserScopeType.extract(["user.read"]),
2331
+ type: UserScopeType.extract(["user.read", "user.search"]),
2265
2332
  options: AccessLevelOptions.optional()
2266
2333
  })
2267
2334
  ]);
@@ -2327,22 +2394,29 @@ var encodeScope = (scope) => {
2327
2394
  encode: false
2328
2395
  });
2329
2396
  };
2330
- var decodeScope = (query) => {
2331
- const scope = qs.parse(query, {
2397
+ var decodedScopeCache = /* @__PURE__ */ new Map();
2398
+ var decodeScope = (encodedScope) => {
2399
+ if (decodedScopeCache.has(encodedScope)) {
2400
+ return decodedScopeCache.get(encodedScope);
2401
+ }
2402
+ const scope = qs.parse(encodedScope, {
2332
2403
  ignoreQueryPrefix: true,
2333
2404
  comma: true,
2334
2405
  allowDots: true
2335
2406
  });
2336
2407
  const unflattenedScope = unflattenScope(scope);
2337
- return Scope2.safeParse(unflattenedScope)?.data;
2408
+ const result = Scope2.safeParse(unflattenedScope)?.data;
2409
+ decodedScopeCache.set(encodedScope, result);
2410
+ return result;
2338
2411
  };
2339
2412
  var DEFAULT_SCOPE_OPTIONS = {
2340
2413
  placeOfEvent: JurisdictionFilter.enum.all,
2341
- accessLevel: JurisdictionFilter.enum.all
2414
+ accessLevel: JurisdictionFilter.enum.all,
2415
+ registeredIn: JurisdictionFilter.enum.all,
2416
+ declaredIn: JurisdictionFilter.enum.all
2342
2417
  };
2343
2418
 
2344
2419
  // ../commons/src/scopes.deprecated.do-not-use.ts
2345
- var z4 = __toESM(require("zod/v4"));
2346
2420
  var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2347
2421
  var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2348
2422
  var SearchScope = z4.object({
@@ -2576,6 +2650,74 @@ var legacyScopeToV2Scope = (v1Scope) => {
2576
2650
  }
2577
2651
  throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2578
2652
  };
2653
+ var MERGEABLE_USER_SCOPE_TYPES = ["user.create", "user.edit"];
2654
+ function isMergeableUserScopeType(type) {
2655
+ return MERGEABLE_USER_SCOPE_TYPES.includes(type);
2656
+ }
2657
+ function decodeLegacyScope(legacy) {
2658
+ const encoded = legacyScopeToV2Scope(legacy);
2659
+ const scope = decodeScope(encoded);
2660
+ if (!scope) {
2661
+ throw new Error(
2662
+ `Could not decode migrated scope from legacy '${legacy}' (encoded: '${encoded}').`
2663
+ );
2664
+ }
2665
+ return { legacy, scope };
2666
+ }
2667
+ function groupByType(entries) {
2668
+ return entries.reduce(
2669
+ (groups, entry) => ({
2670
+ ...groups,
2671
+ [entry.scope.type]: [...groups[entry.scope.type] ?? [], entry]
2672
+ }),
2673
+ {}
2674
+ );
2675
+ }
2676
+ function deduplicateEntries(entries) {
2677
+ return entries.filter(
2678
+ (entry, index) => entries.findIndex((e) => (0, import_lodash.isEqual)(e.scope, entry.scope)) === index
2679
+ );
2680
+ }
2681
+ function mergeEntries(type, entries) {
2682
+ const optionsList = entries.map(
2683
+ (e) => "options" in e.scope && e.scope.options ? e.scope.options : {}
2684
+ );
2685
+ const allKeys = optionsList.flatMap(
2686
+ (opts) => Object.keys(opts).filter((k) => opts[k] !== void 0)
2687
+ );
2688
+ const conflictKey = allKeys.find((key, i) => allKeys.indexOf(key) !== i);
2689
+ if (conflictKey) {
2690
+ const conflicting = entries.filter(
2691
+ (e) => conflictKey in ("options" in e.scope && e.scope.options || {})
2692
+ ).map((e) => JSON.stringify(e.legacy));
2693
+ throw new Error(
2694
+ `Cannot auto-merge two '${type}' scopes that both define '${conflictKey}'. Conflicting legacy scopes: [${conflicting.join(", ")}]. Resolve manually in roles.ts and re-run.`
2695
+ );
2696
+ }
2697
+ const mergedOptions = Object.assign({}, ...optionsList);
2698
+ const merged = Object.keys(mergedOptions).length > 0 ? { type, options: mergedOptions } : { type };
2699
+ const parsed = Scope2.safeParse(merged);
2700
+ if (!parsed.success) {
2701
+ throw new Error(
2702
+ `Merged '${type}' scope failed schema validation: ${parsed.error.message}. Legacy scopes: [${entries.map((e) => JSON.stringify(e.legacy)).join(", ")}].`
2703
+ );
2704
+ }
2705
+ return parsed.data;
2706
+ }
2707
+ function migrateLegacyScopesArrayToV2Scopes(legacyScopes) {
2708
+ const groups = groupByType(legacyScopes.map(decodeLegacyScope));
2709
+ return Object.entries(groups).flatMap(([type, entries]) => {
2710
+ const deduped = deduplicateEntries(entries);
2711
+ if (deduped.length <= 1) return deduped.map((e) => e.scope);
2712
+ if (!isMergeableUserScopeType(type)) {
2713
+ console.warn(
2714
+ `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.`
2715
+ );
2716
+ return deduped.map((e) => e.scope);
2717
+ }
2718
+ return [mergeEntries(type, deduped)];
2719
+ });
2720
+ }
2579
2721
 
2580
2722
  // src/migrations/v2.0/migrate-scopes.ts
2581
2723
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
@@ -2613,57 +2755,65 @@ function resolveLegacyScopeFromElement(element) {
2613
2755
  }
2614
2756
  function migrateScopesArrays(rolesFilePath, project) {
2615
2757
  const sourceFile = project.getSourceFile(rolesFilePath);
2616
- if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
2758
+ if (!sourceFile) {
2759
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
2760
+ }
2617
2761
  let migratedCount = 0;
2618
2762
  let removedCount = 0;
2763
+ let mergedCount = 0;
2619
2764
  const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
2765
+ const relPath = import_path11.default.relative(process.cwd(), rolesFilePath);
2620
2766
  for (const scopesProp of scopesProperties) {
2621
2767
  const initializer = scopesProp.getInitializer();
2622
2768
  if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2623
- const elements = initializer.getElements();
2624
- for (let index = elements.length - 1; index >= 0; index--) {
2625
- const element = elements[index];
2626
- if (!import_ts_morph11.Node.isExpression(element)) continue;
2769
+ const rawTexts = [];
2770
+ const legacyStrings = [];
2771
+ let anyChange = false;
2772
+ for (const element of initializer.getElements()) {
2627
2773
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2628
2774
  if (scopeKey && !(scopeKey in SCOPES)) {
2629
2775
  console.warn(
2630
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2776
+ ` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`
2631
2777
  );
2632
- initializer.removeElement(index);
2633
2778
  removedCount++;
2779
+ anyChange = true;
2634
2780
  continue;
2635
2781
  }
2636
2782
  const legacyScope = resolveLegacyScopeFromElement(element);
2637
2783
  if (!legacyScope) {
2638
2784
  console.warn(
2639
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2785
+ ` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`
2640
2786
  );
2787
+ rawTexts.push(element.getText());
2641
2788
  continue;
2642
2789
  }
2643
- try {
2644
- const migratedScope = legacyScopeToV2Scope(legacyScope);
2645
- const scope = decodeScope(migratedScope);
2646
- if (!scope) {
2647
- console.warn(
2648
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2649
- );
2650
- continue;
2651
- }
2652
- element.replaceWithText(JSON.stringify(scope));
2653
- migratedCount++;
2654
- } catch (error) {
2655
- console.warn(
2656
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2657
- );
2658
- }
2790
+ legacyStrings.push(legacyScope);
2791
+ anyChange = true;
2792
+ }
2793
+ if (!anyChange) continue;
2794
+ let mergedScopes;
2795
+ try {
2796
+ mergedScopes = migrateLegacyScopesArrayToV2Scopes(legacyStrings);
2797
+ } catch (error) {
2798
+ throw new Error(
2799
+ `[${relPath}] Failed to migrate scopes for role: ${error instanceof Error ? error.message : String(error)}`,
2800
+ { cause: error }
2801
+ );
2659
2802
  }
2803
+ migratedCount += legacyStrings.length;
2804
+ mergedCount += legacyStrings.length - mergedScopes.length;
2805
+ const outputElements = [
2806
+ ...rawTexts,
2807
+ ...mergedScopes.map((s) => JSON.stringify(s))
2808
+ ];
2809
+ scopesProp.setInitializer(`[${outputElements.join(", ")}]`);
2660
2810
  }
2661
2811
  if (removedCount > 0) {
2662
2812
  console.log(
2663
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
2813
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`
2664
2814
  );
2665
2815
  }
2666
- return { migratedCount, removedCount };
2816
+ return { migratedCount, removedCount, mergedCount };
2667
2817
  }
2668
2818
  function ensureScopesHelpersImport(rolesFilePath, project) {
2669
2819
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -2798,7 +2948,7 @@ async function main11() {
2798
2948
  return;
2799
2949
  }
2800
2950
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2801
- const { migratedCount, removedCount } = migrateScopesArrays(
2951
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(
2802
2952
  rolesFilePath,
2803
2953
  project
2804
2954
  );
@@ -2817,7 +2967,7 @@ async function main11() {
2817
2967
  }
2818
2968
  await sourceFile.save();
2819
2969
  console.log(
2820
- `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." : "."}`
2970
+ `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." : "."}`
2821
2971
  );
2822
2972
  }
2823
2973
 
@@ -3623,6 +3773,10 @@ var ACTION_PROPERTY_NAME2 = "action";
3623
3773
  var CONDITIONALS_PROPERTY_NAME = "conditionals";
3624
3774
  var TYPE_PROPERTY_NAME7 = "type";
3625
3775
  var SLUG_PROPERTY_NAME = "slug";
3776
+ var READ_ACTION_TYPE = "READ";
3777
+ var ACTION_TYPE_IMPORT_NAME = "ActionType";
3778
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
3779
+ var READ_ACTION_FALLBACK_INITIALIZER = `{ type: ${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE} }`;
3626
3780
  var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
3627
3781
  "READ",
3628
3782
  "DELETE",
@@ -3670,91 +3824,137 @@ function isUnsupportedActionType(action) {
3670
3824
  }
3671
3825
  return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3672
3826
  }
3673
- function migrateWorkqueueActions(workqueue, relPath) {
3674
- const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3675
- if (!actionsProperty || !import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3676
- return 0;
3677
- }
3678
- const actionsInitializer = actionsProperty.getInitializer();
3679
- if (!actionsInitializer || !import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3680
- return 0;
3827
+ function ensureValidAction(workqueue, relPath) {
3828
+ const workqueueLabel = getWorkqueueLabel(workqueue);
3829
+ const actionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3830
+ if (actionProperty && import_ts_morph17.Node.isPropertyAssignment(actionProperty)) {
3831
+ const initializer = actionProperty.getInitializer();
3832
+ if (initializer && import_ts_morph17.Node.isObjectLiteralExpression(initializer)) {
3833
+ if (!isUnsupportedActionType(initializer)) {
3834
+ return { changed: false, usedReadFallback: false };
3835
+ }
3836
+ actionProperty.set({
3837
+ name: ACTION_PROPERTY_NAME2,
3838
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3839
+ });
3840
+ console.log(
3841
+ ` [${relPath}] Replaced unsupported 'action' type with '${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE}' on workqueue '${workqueueLabel}'`
3842
+ );
3843
+ return { changed: true, usedReadFallback: true };
3844
+ }
3681
3845
  }
3846
+ workqueue.addPropertyAssignment({
3847
+ name: ACTION_PROPERTY_NAME2,
3848
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3849
+ });
3850
+ console.log(
3851
+ ` [${relPath}] Added default 'action: ${READ_ACTION_FALLBACK_INITIALIZER}' to workqueue '${workqueueLabel}'`
3852
+ );
3853
+ return { changed: true, usedReadFallback: true };
3854
+ }
3855
+ function migrateWorkqueueActions(workqueue, relPath) {
3682
3856
  const workqueueLabel = getWorkqueueLabel(workqueue);
3683
- const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3684
- if (existingActionProperty) {
3685
- if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3686
- const existingActionInitializer = existingActionProperty.getInitializer();
3687
- if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3688
- const conditionalsProperty2 = existingActionInitializer.getProperty(
3689
- CONDITIONALS_PROPERTY_NAME
3857
+ const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3858
+ let actionsArrayMigrated = false;
3859
+ if (actionsProperty && import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3860
+ const actionsInitializer = actionsProperty.getInitializer();
3861
+ if (actionsInitializer && import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3862
+ const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3863
+ if (existingActionProperty) {
3864
+ if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3865
+ const existingActionInitializer = existingActionProperty.getInitializer();
3866
+ if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3867
+ const conditionalsProperty = existingActionInitializer.getProperty(
3868
+ CONDITIONALS_PROPERTY_NAME
3869
+ );
3870
+ if (conditionalsProperty) {
3871
+ conditionalsProperty.remove();
3872
+ console.log(
3873
+ ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3874
+ );
3875
+ }
3876
+ }
3877
+ }
3878
+ actionsProperty.remove();
3879
+ console.log(
3880
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3881
+ );
3882
+ actionsArrayMigrated = true;
3883
+ } else {
3884
+ const actionCandidates = actionsInitializer.getElements().filter(
3885
+ (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3690
3886
  );
3691
- if (conditionalsProperty2) {
3692
- conditionalsProperty2.remove();
3887
+ if (actionCandidates.length === 0) {
3888
+ actionsProperty.remove();
3693
3889
  console.log(
3694
- ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3890
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3695
3891
  );
3696
- }
3697
- if (isUnsupportedActionType(existingActionInitializer)) {
3698
- existingActionProperty.remove();
3699
- console.log(
3700
- ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
3892
+ actionsArrayMigrated = true;
3893
+ } else {
3894
+ if (actionCandidates.length > 1) {
3895
+ const droppedCount = actionCandidates.length - 1;
3896
+ console.warn(
3897
+ ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3898
+ );
3899
+ }
3900
+ const conditionalsProperty = actionCandidates[0].getProperty(
3901
+ CONDITIONALS_PROPERTY_NAME
3701
3902
  );
3903
+ if (conditionalsProperty) {
3904
+ conditionalsProperty.remove();
3905
+ console.log(
3906
+ ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3907
+ );
3908
+ }
3909
+ if (isUnsupportedActionType(actionCandidates[0])) {
3910
+ actionsProperty.remove();
3911
+ console.log(
3912
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3913
+ );
3914
+ actionsArrayMigrated = true;
3915
+ } else {
3916
+ const firstActionText = actionCandidates[0].getText();
3917
+ workqueue.addPropertyAssignment({
3918
+ name: ACTION_PROPERTY_NAME2,
3919
+ initializer: firstActionText
3920
+ });
3921
+ actionsProperty.remove();
3922
+ console.log(
3923
+ ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3924
+ );
3925
+ actionsArrayMigrated = true;
3926
+ }
3702
3927
  }
3703
3928
  }
3704
3929
  }
3705
- actionsProperty.remove();
3706
- console.log(
3707
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3708
- );
3709
- return 1;
3710
- }
3711
- const actionCandidates = actionsInitializer.getElements().filter(
3712
- (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3713
- );
3714
- if (actionCandidates.length === 0) {
3715
- actionsProperty.remove();
3716
- console.log(
3717
- ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3718
- );
3719
- return 1;
3720
- }
3721
- if (actionCandidates.length > 1) {
3722
- const droppedCount = actionCandidates.length - 1;
3723
- console.warn(
3724
- ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3725
- );
3726
3930
  }
3727
- const conditionalsProperty = actionCandidates[0].getProperty(
3728
- CONDITIONALS_PROPERTY_NAME
3931
+ const fallback = ensureValidAction(workqueue, relPath);
3932
+ return {
3933
+ changed: actionsArrayMigrated || fallback.changed,
3934
+ usedReadFallback: fallback.usedReadFallback
3935
+ };
3936
+ }
3937
+ function ensureActionTypeImport(sourceFile) {
3938
+ const existingImport = sourceFile.getImportDeclaration(
3939
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2
3729
3940
  );
3730
- if (conditionalsProperty) {
3731
- conditionalsProperty.remove();
3732
- console.log(
3733
- ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3734
- );
3735
- }
3736
- if (isUnsupportedActionType(actionCandidates[0])) {
3737
- actionsProperty.remove();
3738
- console.log(
3739
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3740
- );
3741
- return 1;
3941
+ if (existingImport) {
3942
+ const alreadyImported = existingImport.getNamedImports().some((ni) => ni.getName() === ACTION_TYPE_IMPORT_NAME);
3943
+ if (!alreadyImported) {
3944
+ existingImport.addNamedImport(ACTION_TYPE_IMPORT_NAME);
3945
+ }
3946
+ return;
3742
3947
  }
3743
- const firstActionText = actionCandidates[0].getText();
3744
- workqueue.addPropertyAssignment({
3745
- name: ACTION_PROPERTY_NAME2,
3746
- initializer: firstActionText
3948
+ sourceFile.addImportDeclaration({
3949
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE2,
3950
+ namedImports: [ACTION_TYPE_IMPORT_NAME]
3747
3951
  });
3748
- actionsProperty.remove();
3749
- console.log(
3750
- ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3751
- );
3752
- return 1;
3753
3952
  }
3754
3953
  function processFile13(filePath, project) {
3755
3954
  const sourceFile = project.getSourceFile(filePath);
3756
3955
  if (!sourceFile) return 0;
3757
3956
  let migratedWorkqueues = 0;
3957
+ let needsActionTypeImport = false;
3758
3958
  const relPath = import_path18.default.relative(process.cwd(), filePath);
3759
3959
  const callExpressions = sourceFile.getDescendantsOfKind(
3760
3960
  import_ts_morph17.SyntaxKind.CallExpression
@@ -3770,9 +3970,14 @@ function processFile13(filePath, project) {
3770
3970
  if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3771
3971
  for (const element of workqueuesArg.getElements()) {
3772
3972
  if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3773
- migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3973
+ const result = migrateWorkqueueActions(element, relPath);
3974
+ if (result.changed) migratedWorkqueues++;
3975
+ if (result.usedReadFallback) needsActionTypeImport = true;
3774
3976
  }
3775
3977
  }
3978
+ if (needsActionTypeImport) {
3979
+ ensureActionTypeImport(sourceFile);
3980
+ }
3776
3981
  return migratedWorkqueues;
3777
3982
  }
3778
3983
  async function main18() {
@@ -4107,7 +4312,7 @@ Saved ${handlerRelPath}.`);
4107
4312
  // src/migrations/v2.0/checkout-upstream-files.ts
4108
4313
  var import_child_process = require("child_process");
4109
4314
  var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
4110
- var UPSTREAM_BRANCH = "develop";
4315
+ var UPSTREAM_BRANCH = "release-v2.0.0";
4111
4316
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
4112
4317
  var FILES_TO_CHECKOUT = [
4113
4318
  "src/analytics/analytics.ts",
@@ -4646,9 +4851,9 @@ var import_path24 = require("path");
4646
4851
  var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4647
4852
  var INFRASTRUCTURE_DIR = "infrastructure";
4648
4853
  var BASE_BRANCH = "release-v1.9";
4649
- function gitShowBytes(ref, path23) {
4854
+ function gitShowBytes(ref, path24) {
4650
4855
  try {
4651
- const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path23}`], {
4856
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path24}`], {
4652
4857
  cwd: process.cwd(),
4653
4858
  stdio: ["ignore", "pipe", "pipe"]
4654
4859
  });
@@ -4657,9 +4862,13 @@ function gitShowBytes(ref, path23) {
4657
4862
  return null;
4658
4863
  }
4659
4864
  }
4660
- async function main25() {
4865
+ async function main25({
4866
+ subdirs = []
4867
+ } = {}) {
4868
+ const pathspecs = subdirs.length > 0 ? subdirs.map((s) => `${INFRASTRUCTURE_DIR}/${s}/`) : [`${INFRASTRUCTURE_DIR}/`];
4869
+ const scopeLabel = pathspecs.map((p) => `'${p}'`).join(", ");
4661
4870
  console.log(
4662
- `Merging '${INFRASTRUCTURE_DIR}/' from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4871
+ `Merging ${scopeLabel} from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4663
4872
  `
4664
4873
  );
4665
4874
  assertIsGitRepo();
@@ -4674,20 +4883,12 @@ async function main25() {
4674
4883
  const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4675
4884
  const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4676
4885
  const upstreamFiles = runGit(
4677
- [
4678
- "ls-tree",
4679
- "-r",
4680
- "--name-only",
4681
- "-z",
4682
- ref,
4683
- "--",
4684
- `${INFRASTRUCTURE_DIR}/`
4685
- ],
4886
+ ["ls-tree", "-r", "--name-only", "-z", ref, "--", ...pathspecs],
4686
4887
  { silent: true }
4687
4888
  ).split("\0").filter(Boolean);
4688
4889
  if (upstreamFiles.length === 0) {
4689
4890
  console.log(
4690
- ` No files found under '${INFRASTRUCTURE_DIR}/' on ${ref}. Nothing to merge.`
4891
+ ` No files found under ${scopeLabel} on ${ref}. Nothing to merge.`
4691
4892
  );
4692
4893
  return;
4693
4894
  }
@@ -4762,7 +4963,9 @@ async function main25() {
4762
4963
  var import_fs6 = require("fs");
4763
4964
  var import_path25 = require("path");
4764
4965
  var INFRASTRUCTURE_DIR2 = "infrastructure";
4765
- async function main26() {
4966
+ async function main26({
4967
+ keep = []
4968
+ } = {}) {
4766
4969
  const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4767
4970
  if (!(0, import_fs6.existsSync)(fullPath)) {
4768
4971
  console.log(
@@ -4770,24 +4973,152 @@ async function main26() {
4770
4973
  );
4771
4974
  return;
4772
4975
  }
4773
- console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4774
- `);
4775
4976
  assertIsGitRepo();
4776
- runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4777
- silent: true
4977
+ if (keep.length === 0) {
4978
+ console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4979
+ `);
4980
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4981
+ silent: true
4982
+ });
4983
+ console.log(
4984
+ ` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`
4985
+ );
4986
+ if ((0, import_fs6.existsSync)(fullPath)) {
4987
+ (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4988
+ console.log(
4989
+ ` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`
4990
+ );
4991
+ }
4992
+ console.log(
4993
+ `
4994
+ Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4995
+ );
4996
+ return;
4997
+ }
4998
+ const keepSet = new Set(keep);
4999
+ console.log(
5000
+ `Deleting contents of '${INFRASTRUCTURE_DIR2}/' except: ${[...keepSet].map((name) => `'${name}'`).join(", ")}
5001
+ `
5002
+ );
5003
+ const topLevelEntries = (0, import_fs6.readdirSync)(fullPath, { withFileTypes: true });
5004
+ let deleted = 0;
5005
+ for (const entry of topLevelEntries) {
5006
+ if (keepSet.has(entry.name)) {
5007
+ console.log(` Keeping '${INFRASTRUCTURE_DIR2}/${entry.name}'.`);
5008
+ continue;
5009
+ }
5010
+ const relPath = `${INFRASTRUCTURE_DIR2}/${entry.name}${entry.isDirectory() ? "/" : ""}`;
5011
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", relPath], { silent: true });
5012
+ const fullEntryPath = (0, import_path25.join)(fullPath, entry.name);
5013
+ if ((0, import_fs6.existsSync)(fullEntryPath)) {
5014
+ (0, import_fs6.rmSync)(fullEntryPath, { recursive: true, force: true });
5015
+ }
5016
+ console.log(` Deleted '${relPath}'.`);
5017
+ deleted++;
5018
+ }
5019
+ const presentNames = new Set(topLevelEntries.map((e) => e.name));
5020
+ const missingKeeps = [...keepSet].filter((name) => !presentNames.has(name));
5021
+ if (missingKeeps.length > 0) {
5022
+ console.warn(
5023
+ ` [warn] Requested to keep ${missingKeeps.map((n) => `'${n}'`).join(", ")} but they don't exist under '${INFRASTRUCTURE_DIR2}/'.`
5024
+ );
5025
+ }
5026
+ console.log(
5027
+ `
5028
+ Done. Deleted ${deleted} top-level entr${deleted === 1 ? "y" : "ies"}. Review the staged deletions with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
5029
+ );
5030
+ }
5031
+
5032
+ // src/migrations/v2.0/fix-accept-requested-registration-function-type.ts
5033
+ var import_ts_morph22 = require("ts-morph");
5034
+ var import_path26 = __toESM(require("path"));
5035
+ var TARGET_FUNCTION_NAME = "acceptRequestedRegistration";
5036
+ var ACTION_PARAMETER_NAME = "action";
5037
+ var OLD_TYPE = "ActionInput";
5038
+ var NEW_TYPE = "Extract<ActionInput, { type?: 'REGISTER' }>";
5039
+ function isAcceptRequestedRegistrationParameter(parameter) {
5040
+ const functionDeclaration = parameter.getFirstAncestorByKind(
5041
+ import_ts_morph22.SyntaxKind.FunctionDeclaration
5042
+ );
5043
+ if (functionDeclaration?.getName() === TARGET_FUNCTION_NAME) {
5044
+ return true;
5045
+ }
5046
+ const arrowFunction = parameter.getFirstAncestorByKind(
5047
+ import_ts_morph22.SyntaxKind.ArrowFunction
5048
+ );
5049
+ const variableDeclaration = arrowFunction?.getFirstAncestorByKind(
5050
+ import_ts_morph22.SyntaxKind.VariableDeclaration
5051
+ );
5052
+ return variableDeclaration?.getName() === TARGET_FUNCTION_NAME;
5053
+ }
5054
+ function processFile14(filePath, project) {
5055
+ const sourceFile = project.getSourceFile(filePath);
5056
+ if (!sourceFile) return 0;
5057
+ let updatedCount = 0;
5058
+ for (const parameter of sourceFile.getDescendantsOfKind(
5059
+ import_ts_morph22.SyntaxKind.Parameter
5060
+ )) {
5061
+ if (parameter.getName() !== ACTION_PARAMETER_NAME) {
5062
+ continue;
5063
+ }
5064
+ if (!isAcceptRequestedRegistrationParameter(parameter)) {
5065
+ continue;
5066
+ }
5067
+ const typeNode = parameter.getTypeNode();
5068
+ if (!typeNode || typeNode.getText() !== OLD_TYPE) {
5069
+ continue;
5070
+ }
5071
+ parameter.setType(NEW_TYPE);
5072
+ updatedCount++;
5073
+ console.log(
5074
+ ` [${import_path26.default.relative(process.cwd(), filePath)}] Updated '${ACTION_PARAMETER_NAME}' in ${TARGET_FUNCTION_NAME} to ${NEW_TYPE}`
5075
+ );
5076
+ }
5077
+ return updatedCount;
5078
+ }
5079
+ async function main27() {
5080
+ const srcDir = import_path26.default.join(process.cwd(), "src");
5081
+ console.log(`Scanning for ${TARGET_FUNCTION_NAME} in: ${srcDir}
5082
+ `);
5083
+ const project = new import_ts_morph22.Project({
5084
+ tsConfigFilePath: import_path26.default.resolve(srcDir, "../tsconfig.json"),
5085
+ skipAddingFilesFromTsConfig: false
4778
5086
  });
4779
- console.log(` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4780
- if ((0, import_fs6.existsSync)(fullPath)) {
4781
- (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4782
- console.log(` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`);
5087
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
5088
+ const filePath = sf.getFilePath();
5089
+ return filePath.includes("/src/") && !filePath.includes("/node_modules/");
5090
+ });
5091
+ let totalUpdated = 0;
5092
+ const modifiedFiles = [];
5093
+ for (const sourceFile of sourceFiles) {
5094
+ const filePath = sourceFile.getFilePath();
5095
+ const updated = processFile14(filePath, project);
5096
+ if (updated > 0) {
5097
+ totalUpdated += updated;
5098
+ modifiedFiles.push(filePath);
5099
+ }
5100
+ }
5101
+ if (modifiedFiles.length === 0) {
5102
+ console.log(
5103
+ `No '${ACTION_PARAMETER_NAME}: ${OLD_TYPE}' parameter in ${TARGET_FUNCTION_NAME} found. Nothing to do.`
5104
+ );
5105
+ return;
5106
+ }
5107
+ console.log(`
5108
+ Saving ${modifiedFiles.length} modified file(s)...`);
5109
+ for (const filePath of modifiedFiles) {
5110
+ const sourceFile = project.getSourceFileOrThrow(filePath);
5111
+ await sourceFile.save();
5112
+ console.log(` Saved: ${import_path26.default.relative(process.cwd(), filePath)}`);
4783
5113
  }
4784
5114
  console.log(
4785
5115
  `
4786
- Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
5116
+ Done. Updated ${totalUpdated} parameter type annotation(s) in ${TARGET_FUNCTION_NAME}.`
4787
5117
  );
4788
5118
  }
4789
5119
 
4790
5120
  // src/migrations/v2.0/index.ts
5121
+ var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
4791
5122
  async function runUpgrade(dockerSwarm) {
4792
5123
  await main18();
4793
5124
  await main();
@@ -4812,10 +5143,12 @@ async function runUpgrade(dockerSwarm) {
4812
5143
  await main22();
4813
5144
  await main23();
4814
5145
  await main24();
5146
+ await main27();
4815
5147
  await main17();
4816
5148
  if (dockerSwarm) {
4817
5149
  await main25();
4818
5150
  } else {
4819
- await main26();
5151
+ await main26({ keep: NON_SWARM_INFRA_SUBDIRS });
5152
+ await main25({ subdirs: NON_SWARM_INFRA_SUBDIRS });
4820
5153
  }
4821
5154
  }