@opencrvs/toolkit 2.0.0-rc.c0c9888 → 2.0.0-rc.c174741

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 (37) hide show
  1. package/dist/application-config/index.js +17 -23
  2. package/dist/cli.js +394 -130
  3. package/dist/commons/api/router.d.ts +2901 -163
  4. package/dist/commons/conditionals/conditionals.d.ts +3 -3
  5. package/dist/commons/conditionals/validate.d.ts +1 -0
  6. package/dist/commons/events/ActionInput.d.ts +108 -0
  7. package/dist/commons/events/Draft.d.ts +3 -0
  8. package/dist/commons/events/FieldConfig.d.ts +5 -0
  9. package/dist/commons/events/utils.d.ts +1 -1
  10. package/dist/conditionals/index.js +5 -3
  11. package/dist/events/index.js +33 -37
  12. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +1 -1
  13. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  14. package/dist/migrations/v2.0/checkout-upstream-files.js +1 -2
  15. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +9 -1
  16. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +1 -1
  17. package/dist/migrations/v2.0/delete-infrastructure-directory.js +66 -20
  18. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts +3 -0
  19. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.d.ts.map +1 -0
  20. package/dist/migrations/v2.0/fix-accept-requested-registration-function-type.js +110 -0
  21. package/dist/migrations/v2.0/index.d.ts +5 -3
  22. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  23. package/dist/migrations/v2.0/index.js +392 -128
  24. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +11 -1
  25. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +1 -1
  26. package/dist/migrations/v2.0/merge-infrastructure-directory.js +17 -16
  27. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -1
  28. package/dist/migrations/v2.0/migrate-scopes.js +54 -30
  29. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -1
  30. package/dist/migrations/v2.0/migrate-workqueue-configs.js +140 -59
  31. package/dist/notification/index.js +20 -23
  32. package/dist/scopes/index.d.ts +6 -1
  33. package/dist/scopes/index.js +5 -3
  34. package/opencrvs-toolkit-2.0.0-rc.c174741.tgz +0 -0
  35. package/package.json +1 -1
  36. package/tsconfig.tsbuildinfo +1 -1
  37. package/opencrvs-toolkit-2.0.0-rc.c0c9888.tgz +0 -0
@@ -1895,9 +1895,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1895
1895
  }
1896
1896
  return replacedCount;
1897
1897
  }
1898
- function resolveConfigChain(configObj, path23) {
1898
+ function resolveConfigChain(configObj, path24) {
1899
1899
  let current = configObj;
1900
- for (const key of path23) {
1900
+ for (const key of path24) {
1901
1901
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1902
1902
  const prop = current.getProperty(key);
1903
1903
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -2132,6 +2132,10 @@ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} rout
2132
2132
  var import_ts_morph11 = require("ts-morph");
2133
2133
  var import_path11 = __toESM(require("path"));
2134
2134
 
2135
+ // ../commons/src/scopes.deprecated.do-not-use.ts
2136
+ var z4 = __toESM(require("zod/v4"));
2137
+ var import_lodash = require("lodash");
2138
+
2135
2139
  // ../commons/src/scopes.ts
2136
2140
  var z3 = __toESM(require("zod/v4"));
2137
2141
  var qs = __toESM(require("qs"));
@@ -2308,12 +2312,14 @@ var SystemScopeType = z3.enum([
2308
2312
  "organisation.read-locations",
2309
2313
  "user.read",
2310
2314
  "user.create",
2311
- "user.edit"
2315
+ "user.edit",
2316
+ "user.search"
2312
2317
  ]);
2313
2318
  var UserScopeType = SystemScopeType.extract([
2314
2319
  "user.read",
2315
2320
  "user.create",
2316
- "user.edit"
2321
+ "user.edit",
2322
+ "user.search"
2317
2323
  ]);
2318
2324
  var ScopesWithRoleOption = UserScopeType.extract(["user.edit", "user.create"]);
2319
2325
  var UserScopeV2 = z3.discriminatedUnion("type", [
@@ -2322,7 +2328,7 @@ var UserScopeV2 = z3.discriminatedUnion("type", [
2322
2328
  options: AllUserScopeOptions.optional()
2323
2329
  }),
2324
2330
  z3.object({
2325
- type: UserScopeType.extract(["user.read"]),
2331
+ type: UserScopeType.extract(["user.read", "user.search"]),
2326
2332
  options: AccessLevelOptions.optional()
2327
2333
  })
2328
2334
  ]);
@@ -2403,7 +2409,6 @@ var DEFAULT_SCOPE_OPTIONS = {
2403
2409
  };
2404
2410
 
2405
2411
  // ../commons/src/scopes.deprecated.do-not-use.ts
2406
- var z4 = __toESM(require("zod/v4"));
2407
2412
  var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2408
2413
  var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2409
2414
  var SearchScope = z4.object({
@@ -2637,6 +2642,74 @@ var legacyScopeToV2Scope = (v1Scope) => {
2637
2642
  }
2638
2643
  throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2639
2644
  };
2645
+ var MERGEABLE_USER_SCOPE_TYPES = ["user.create", "user.edit"];
2646
+ function isMergeableUserScopeType(type) {
2647
+ return MERGEABLE_USER_SCOPE_TYPES.includes(type);
2648
+ }
2649
+ function decodeLegacyScope(legacy) {
2650
+ const encoded = legacyScopeToV2Scope(legacy);
2651
+ const scope = decodeScope(encoded);
2652
+ if (!scope) {
2653
+ throw new Error(
2654
+ `Could not decode migrated scope from legacy '${legacy}' (encoded: '${encoded}').`
2655
+ );
2656
+ }
2657
+ return { legacy, scope };
2658
+ }
2659
+ function groupByType(entries) {
2660
+ return entries.reduce(
2661
+ (groups, entry) => ({
2662
+ ...groups,
2663
+ [entry.scope.type]: [...groups[entry.scope.type] ?? [], entry]
2664
+ }),
2665
+ {}
2666
+ );
2667
+ }
2668
+ function deduplicateEntries(entries) {
2669
+ return entries.filter(
2670
+ (entry, index) => entries.findIndex((e) => (0, import_lodash.isEqual)(e.scope, entry.scope)) === index
2671
+ );
2672
+ }
2673
+ function mergeEntries(type, entries) {
2674
+ const optionsList = entries.map(
2675
+ (e) => "options" in e.scope && e.scope.options ? e.scope.options : {}
2676
+ );
2677
+ const allKeys = optionsList.flatMap(
2678
+ (opts) => Object.keys(opts).filter((k) => opts[k] !== void 0)
2679
+ );
2680
+ const conflictKey = allKeys.find((key, i) => allKeys.indexOf(key) !== i);
2681
+ if (conflictKey) {
2682
+ const conflicting = entries.filter(
2683
+ (e) => conflictKey in ("options" in e.scope && e.scope.options || {})
2684
+ ).map((e) => JSON.stringify(e.legacy));
2685
+ throw new Error(
2686
+ `Cannot auto-merge two '${type}' scopes that both define '${conflictKey}'. Conflicting legacy scopes: [${conflicting.join(", ")}]. Resolve manually in roles.ts and re-run.`
2687
+ );
2688
+ }
2689
+ const mergedOptions = Object.assign({}, ...optionsList);
2690
+ const merged = Object.keys(mergedOptions).length > 0 ? { type, options: mergedOptions } : { type };
2691
+ const parsed = Scope2.safeParse(merged);
2692
+ if (!parsed.success) {
2693
+ throw new Error(
2694
+ `Merged '${type}' scope failed schema validation: ${parsed.error.message}. Legacy scopes: [${entries.map((e) => JSON.stringify(e.legacy)).join(", ")}].`
2695
+ );
2696
+ }
2697
+ return parsed.data;
2698
+ }
2699
+ function migrateLegacyScopesArrayToV2Scopes(legacyScopes) {
2700
+ const groups = groupByType(legacyScopes.map(decodeLegacyScope));
2701
+ return Object.entries(groups).flatMap(([type, entries]) => {
2702
+ const deduped = deduplicateEntries(entries);
2703
+ if (deduped.length <= 1) return deduped.map((e) => e.scope);
2704
+ if (!isMergeableUserScopeType(type)) {
2705
+ console.warn(
2706
+ `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.`
2707
+ );
2708
+ return deduped.map((e) => e.scope);
2709
+ }
2710
+ return [mergeEntries(type, deduped)];
2711
+ });
2712
+ }
2640
2713
 
2641
2714
  // src/migrations/v2.0/migrate-scopes.ts
2642
2715
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
@@ -2674,57 +2747,65 @@ function resolveLegacyScopeFromElement(element) {
2674
2747
  }
2675
2748
  function migrateScopesArrays(rolesFilePath, project) {
2676
2749
  const sourceFile = project.getSourceFile(rolesFilePath);
2677
- if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
2750
+ if (!sourceFile) {
2751
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
2752
+ }
2678
2753
  let migratedCount = 0;
2679
2754
  let removedCount = 0;
2755
+ let mergedCount = 0;
2680
2756
  const scopesProperties = sourceFile.getDescendantsOfKind(import_ts_morph11.SyntaxKind.PropertyAssignment).filter((prop) => prop.getName() === SCOPES_PROPERTY_NAME);
2757
+ const relPath = import_path11.default.relative(process.cwd(), rolesFilePath);
2681
2758
  for (const scopesProp of scopesProperties) {
2682
2759
  const initializer = scopesProp.getInitializer();
2683
2760
  if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2684
- const elements = initializer.getElements();
2685
- for (let index = elements.length - 1; index >= 0; index--) {
2686
- const element = elements[index];
2687
- if (!import_ts_morph11.Node.isExpression(element)) continue;
2761
+ const rawTexts = [];
2762
+ const legacyStrings = [];
2763
+ let anyChange = false;
2764
+ for (const element of initializer.getElements()) {
2688
2765
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2689
2766
  if (scopeKey && !(scopeKey in SCOPES)) {
2690
2767
  console.warn(
2691
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2768
+ ` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`
2692
2769
  );
2693
- initializer.removeElement(index);
2694
2770
  removedCount++;
2771
+ anyChange = true;
2695
2772
  continue;
2696
2773
  }
2697
2774
  const legacyScope = resolveLegacyScopeFromElement(element);
2698
2775
  if (!legacyScope) {
2699
2776
  console.warn(
2700
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2777
+ ` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`
2701
2778
  );
2779
+ rawTexts.push(element.getText());
2702
2780
  continue;
2703
2781
  }
2704
- try {
2705
- const migratedScope = legacyScopeToV2Scope(legacyScope);
2706
- const scope = decodeScope(migratedScope);
2707
- if (!scope) {
2708
- console.warn(
2709
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2710
- );
2711
- continue;
2712
- }
2713
- element.replaceWithText(JSON.stringify(scope));
2714
- migratedCount++;
2715
- } catch (error) {
2716
- console.warn(
2717
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2718
- );
2719
- }
2782
+ legacyStrings.push(legacyScope);
2783
+ anyChange = true;
2784
+ }
2785
+ if (!anyChange) continue;
2786
+ let mergedScopes;
2787
+ try {
2788
+ mergedScopes = migrateLegacyScopesArrayToV2Scopes(legacyStrings);
2789
+ } catch (error) {
2790
+ throw new Error(
2791
+ `[${relPath}] Failed to migrate scopes for role: ${error instanceof Error ? error.message : String(error)}`,
2792
+ { cause: error }
2793
+ );
2720
2794
  }
2795
+ migratedCount += legacyStrings.length;
2796
+ mergedCount += legacyStrings.length - mergedScopes.length;
2797
+ const outputElements = [
2798
+ ...rawTexts,
2799
+ ...mergedScopes.map((s) => JSON.stringify(s))
2800
+ ];
2801
+ scopesProp.setInitializer(`[${outputElements.join(", ")}]`);
2721
2802
  }
2722
2803
  if (removedCount > 0) {
2723
2804
  console.log(
2724
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
2805
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`
2725
2806
  );
2726
2807
  }
2727
- return { migratedCount, removedCount };
2808
+ return { migratedCount, removedCount, mergedCount };
2728
2809
  }
2729
2810
  function ensureScopesHelpersImport(rolesFilePath, project) {
2730
2811
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -2859,7 +2940,7 @@ async function main11() {
2859
2940
  return;
2860
2941
  }
2861
2942
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2862
- const { migratedCount, removedCount } = migrateScopesArrays(
2943
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(
2863
2944
  rolesFilePath,
2864
2945
  project
2865
2946
  );
@@ -2878,7 +2959,7 @@ async function main11() {
2878
2959
  }
2879
2960
  await sourceFile.save();
2880
2961
  console.log(
2881
- `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." : "."}`
2962
+ `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." : "."}`
2882
2963
  );
2883
2964
  }
2884
2965
 
@@ -3684,6 +3765,10 @@ var ACTION_PROPERTY_NAME2 = "action";
3684
3765
  var CONDITIONALS_PROPERTY_NAME = "conditionals";
3685
3766
  var TYPE_PROPERTY_NAME7 = "type";
3686
3767
  var SLUG_PROPERTY_NAME = "slug";
3768
+ var READ_ACTION_TYPE = "READ";
3769
+ var ACTION_TYPE_IMPORT_NAME = "ActionType";
3770
+ var TOOLKIT_EVENTS_MODULE2 = "@opencrvs/toolkit/events";
3771
+ var READ_ACTION_FALLBACK_INITIALIZER = `{ type: ${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE} }`;
3687
3772
  var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
3688
3773
  "READ",
3689
3774
  "DELETE",
@@ -3731,91 +3816,137 @@ function isUnsupportedActionType(action) {
3731
3816
  }
3732
3817
  return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3733
3818
  }
3734
- function migrateWorkqueueActions(workqueue, relPath) {
3735
- const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3736
- if (!actionsProperty || !import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3737
- return 0;
3738
- }
3739
- const actionsInitializer = actionsProperty.getInitializer();
3740
- if (!actionsInitializer || !import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3741
- return 0;
3819
+ function ensureValidAction(workqueue, relPath) {
3820
+ const workqueueLabel = getWorkqueueLabel(workqueue);
3821
+ const actionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3822
+ if (actionProperty && import_ts_morph17.Node.isPropertyAssignment(actionProperty)) {
3823
+ const initializer = actionProperty.getInitializer();
3824
+ if (initializer && import_ts_morph17.Node.isObjectLiteralExpression(initializer)) {
3825
+ if (!isUnsupportedActionType(initializer)) {
3826
+ return { changed: false, usedReadFallback: false };
3827
+ }
3828
+ actionProperty.set({
3829
+ name: ACTION_PROPERTY_NAME2,
3830
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3831
+ });
3832
+ console.log(
3833
+ ` [${relPath}] Replaced unsupported 'action' type with '${ACTION_TYPE_IMPORT_NAME}.${READ_ACTION_TYPE}' on workqueue '${workqueueLabel}'`
3834
+ );
3835
+ return { changed: true, usedReadFallback: true };
3836
+ }
3742
3837
  }
3838
+ workqueue.addPropertyAssignment({
3839
+ name: ACTION_PROPERTY_NAME2,
3840
+ initializer: READ_ACTION_FALLBACK_INITIALIZER
3841
+ });
3842
+ console.log(
3843
+ ` [${relPath}] Added default 'action: ${READ_ACTION_FALLBACK_INITIALIZER}' to workqueue '${workqueueLabel}'`
3844
+ );
3845
+ return { changed: true, usedReadFallback: true };
3846
+ }
3847
+ function migrateWorkqueueActions(workqueue, relPath) {
3743
3848
  const workqueueLabel = getWorkqueueLabel(workqueue);
3744
- const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3745
- if (existingActionProperty) {
3746
- if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3747
- const existingActionInitializer = existingActionProperty.getInitializer();
3748
- if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3749
- const conditionalsProperty2 = existingActionInitializer.getProperty(
3750
- CONDITIONALS_PROPERTY_NAME
3849
+ const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3850
+ let actionsArrayMigrated = false;
3851
+ if (actionsProperty && import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3852
+ const actionsInitializer = actionsProperty.getInitializer();
3853
+ if (actionsInitializer && import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3854
+ const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3855
+ if (existingActionProperty) {
3856
+ if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3857
+ const existingActionInitializer = existingActionProperty.getInitializer();
3858
+ if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3859
+ const conditionalsProperty = existingActionInitializer.getProperty(
3860
+ CONDITIONALS_PROPERTY_NAME
3861
+ );
3862
+ if (conditionalsProperty) {
3863
+ conditionalsProperty.remove();
3864
+ console.log(
3865
+ ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3866
+ );
3867
+ }
3868
+ }
3869
+ }
3870
+ actionsProperty.remove();
3871
+ console.log(
3872
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3873
+ );
3874
+ actionsArrayMigrated = true;
3875
+ } else {
3876
+ const actionCandidates = actionsInitializer.getElements().filter(
3877
+ (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3751
3878
  );
3752
- if (conditionalsProperty2) {
3753
- conditionalsProperty2.remove();
3879
+ if (actionCandidates.length === 0) {
3880
+ actionsProperty.remove();
3754
3881
  console.log(
3755
- ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3882
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3756
3883
  );
3757
- }
3758
- if (isUnsupportedActionType(existingActionInitializer)) {
3759
- existingActionProperty.remove();
3760
- console.log(
3761
- ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
3884
+ actionsArrayMigrated = true;
3885
+ } else {
3886
+ if (actionCandidates.length > 1) {
3887
+ const droppedCount = actionCandidates.length - 1;
3888
+ console.warn(
3889
+ ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3890
+ );
3891
+ }
3892
+ const conditionalsProperty = actionCandidates[0].getProperty(
3893
+ CONDITIONALS_PROPERTY_NAME
3762
3894
  );
3895
+ if (conditionalsProperty) {
3896
+ conditionalsProperty.remove();
3897
+ console.log(
3898
+ ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3899
+ );
3900
+ }
3901
+ if (isUnsupportedActionType(actionCandidates[0])) {
3902
+ actionsProperty.remove();
3903
+ console.log(
3904
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3905
+ );
3906
+ actionsArrayMigrated = true;
3907
+ } else {
3908
+ const firstActionText = actionCandidates[0].getText();
3909
+ workqueue.addPropertyAssignment({
3910
+ name: ACTION_PROPERTY_NAME2,
3911
+ initializer: firstActionText
3912
+ });
3913
+ actionsProperty.remove();
3914
+ console.log(
3915
+ ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3916
+ );
3917
+ actionsArrayMigrated = true;
3918
+ }
3763
3919
  }
3764
3920
  }
3765
3921
  }
3766
- actionsProperty.remove();
3767
- console.log(
3768
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3769
- );
3770
- return 1;
3771
- }
3772
- const actionCandidates = actionsInitializer.getElements().filter(
3773
- (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3774
- );
3775
- if (actionCandidates.length === 0) {
3776
- actionsProperty.remove();
3777
- console.log(
3778
- ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3779
- );
3780
- return 1;
3781
3922
  }
3782
- if (actionCandidates.length > 1) {
3783
- const droppedCount = actionCandidates.length - 1;
3784
- console.warn(
3785
- ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3786
- );
3787
- }
3788
- const conditionalsProperty = actionCandidates[0].getProperty(
3789
- CONDITIONALS_PROPERTY_NAME
3923
+ const fallback = ensureValidAction(workqueue, relPath);
3924
+ return {
3925
+ changed: actionsArrayMigrated || fallback.changed,
3926
+ usedReadFallback: fallback.usedReadFallback
3927
+ };
3928
+ }
3929
+ function ensureActionTypeImport(sourceFile) {
3930
+ const existingImport = sourceFile.getImportDeclaration(
3931
+ (decl) => decl.getModuleSpecifierValue() === TOOLKIT_EVENTS_MODULE2
3790
3932
  );
3791
- if (conditionalsProperty) {
3792
- conditionalsProperty.remove();
3793
- console.log(
3794
- ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3795
- );
3796
- }
3797
- if (isUnsupportedActionType(actionCandidates[0])) {
3798
- actionsProperty.remove();
3799
- console.log(
3800
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3801
- );
3802
- return 1;
3933
+ if (existingImport) {
3934
+ const alreadyImported = existingImport.getNamedImports().some((ni) => ni.getName() === ACTION_TYPE_IMPORT_NAME);
3935
+ if (!alreadyImported) {
3936
+ existingImport.addNamedImport(ACTION_TYPE_IMPORT_NAME);
3937
+ }
3938
+ return;
3803
3939
  }
3804
- const firstActionText = actionCandidates[0].getText();
3805
- workqueue.addPropertyAssignment({
3806
- name: ACTION_PROPERTY_NAME2,
3807
- initializer: firstActionText
3940
+ sourceFile.addImportDeclaration({
3941
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE2,
3942
+ namedImports: [ACTION_TYPE_IMPORT_NAME]
3808
3943
  });
3809
- actionsProperty.remove();
3810
- console.log(
3811
- ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3812
- );
3813
- return 1;
3814
3944
  }
3815
3945
  function processFile13(filePath, project) {
3816
3946
  const sourceFile = project.getSourceFile(filePath);
3817
3947
  if (!sourceFile) return 0;
3818
3948
  let migratedWorkqueues = 0;
3949
+ let needsActionTypeImport = false;
3819
3950
  const relPath = import_path18.default.relative(process.cwd(), filePath);
3820
3951
  const callExpressions = sourceFile.getDescendantsOfKind(
3821
3952
  import_ts_morph17.SyntaxKind.CallExpression
@@ -3831,9 +3962,14 @@ function processFile13(filePath, project) {
3831
3962
  if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3832
3963
  for (const element of workqueuesArg.getElements()) {
3833
3964
  if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3834
- migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3965
+ const result = migrateWorkqueueActions(element, relPath);
3966
+ if (result.changed) migratedWorkqueues++;
3967
+ if (result.usedReadFallback) needsActionTypeImport = true;
3835
3968
  }
3836
3969
  }
3970
+ if (needsActionTypeImport) {
3971
+ ensureActionTypeImport(sourceFile);
3972
+ }
3837
3973
  return migratedWorkqueues;
3838
3974
  }
3839
3975
  async function main18() {
@@ -4168,7 +4304,7 @@ Saved ${handlerRelPath}.`);
4168
4304
  // src/migrations/v2.0/checkout-upstream-files.ts
4169
4305
  var import_child_process = require("child_process");
4170
4306
  var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
4171
- var UPSTREAM_BRANCH = "develop";
4307
+ var UPSTREAM_BRANCH = "release-v2.0.0";
4172
4308
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
4173
4309
  var FILES_TO_CHECKOUT = [
4174
4310
  "src/analytics/analytics.ts",
@@ -4707,9 +4843,9 @@ var import_path24 = require("path");
4707
4843
  var TEMP_REMOTE2 = "opencrvs-upgrade-v19-v20-codemod-merge-infra";
4708
4844
  var INFRASTRUCTURE_DIR = "infrastructure";
4709
4845
  var BASE_BRANCH = "release-v1.9";
4710
- function gitShowBytes(ref, path23) {
4846
+ function gitShowBytes(ref, path24) {
4711
4847
  try {
4712
- const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path23}`], {
4848
+ const buf = (0, import_child_process2.execFileSync)("git", ["show", `${ref}:${path24}`], {
4713
4849
  cwd: process.cwd(),
4714
4850
  stdio: ["ignore", "pipe", "pipe"]
4715
4851
  });
@@ -4718,9 +4854,13 @@ function gitShowBytes(ref, path23) {
4718
4854
  return null;
4719
4855
  }
4720
4856
  }
4721
- async function main25() {
4857
+ async function main25({
4858
+ subdirs = []
4859
+ } = {}) {
4860
+ const pathspecs = subdirs.length > 0 ? subdirs.map((s) => `${INFRASTRUCTURE_DIR}/${s}/`) : [`${INFRASTRUCTURE_DIR}/`];
4861
+ const scopeLabel = pathspecs.map((p) => `'${p}'`).join(", ");
4722
4862
  console.log(
4723
- `Merging '${INFRASTRUCTURE_DIR}/' from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4863
+ `Merging ${scopeLabel} from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4724
4864
  `
4725
4865
  );
4726
4866
  assertIsGitRepo();
@@ -4735,20 +4875,12 @@ async function main25() {
4735
4875
  const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4736
4876
  const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4737
4877
  const upstreamFiles = runGit(
4738
- [
4739
- "ls-tree",
4740
- "-r",
4741
- "--name-only",
4742
- "-z",
4743
- ref,
4744
- "--",
4745
- `${INFRASTRUCTURE_DIR}/`
4746
- ],
4878
+ ["ls-tree", "-r", "--name-only", "-z", ref, "--", ...pathspecs],
4747
4879
  { silent: true }
4748
4880
  ).split("\0").filter(Boolean);
4749
4881
  if (upstreamFiles.length === 0) {
4750
4882
  console.log(
4751
- ` No files found under '${INFRASTRUCTURE_DIR}/' on ${ref}. Nothing to merge.`
4883
+ ` No files found under ${scopeLabel} on ${ref}. Nothing to merge.`
4752
4884
  );
4753
4885
  return;
4754
4886
  }
@@ -4823,7 +4955,9 @@ async function main25() {
4823
4955
  var import_fs6 = require("fs");
4824
4956
  var import_path25 = require("path");
4825
4957
  var INFRASTRUCTURE_DIR2 = "infrastructure";
4826
- async function main26() {
4958
+ async function main26({
4959
+ keep = []
4960
+ } = {}) {
4827
4961
  const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4828
4962
  if (!(0, import_fs6.existsSync)(fullPath)) {
4829
4963
  console.log(
@@ -4831,24 +4965,152 @@ async function main26() {
4831
4965
  );
4832
4966
  return;
4833
4967
  }
4834
- console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4835
- `);
4836
4968
  assertIsGitRepo();
4837
- runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4838
- silent: true
4969
+ if (keep.length === 0) {
4970
+ console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4971
+ `);
4972
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4973
+ silent: true
4974
+ });
4975
+ console.log(
4976
+ ` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`
4977
+ );
4978
+ if ((0, import_fs6.existsSync)(fullPath)) {
4979
+ (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4980
+ console.log(
4981
+ ` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`
4982
+ );
4983
+ }
4984
+ console.log(
4985
+ `
4986
+ Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4987
+ );
4988
+ return;
4989
+ }
4990
+ const keepSet = new Set(keep);
4991
+ console.log(
4992
+ `Deleting contents of '${INFRASTRUCTURE_DIR2}/' except: ${[...keepSet].map((name) => `'${name}'`).join(", ")}
4993
+ `
4994
+ );
4995
+ const topLevelEntries = (0, import_fs6.readdirSync)(fullPath, { withFileTypes: true });
4996
+ let deleted = 0;
4997
+ for (const entry of topLevelEntries) {
4998
+ if (keepSet.has(entry.name)) {
4999
+ console.log(` Keeping '${INFRASTRUCTURE_DIR2}/${entry.name}'.`);
5000
+ continue;
5001
+ }
5002
+ const relPath = `${INFRASTRUCTURE_DIR2}/${entry.name}${entry.isDirectory() ? "/" : ""}`;
5003
+ runGit(["rm", "-rf", "--ignore-unmatch", "--", relPath], { silent: true });
5004
+ const fullEntryPath = (0, import_path25.join)(fullPath, entry.name);
5005
+ if ((0, import_fs6.existsSync)(fullEntryPath)) {
5006
+ (0, import_fs6.rmSync)(fullEntryPath, { recursive: true, force: true });
5007
+ }
5008
+ console.log(` Deleted '${relPath}'.`);
5009
+ deleted++;
5010
+ }
5011
+ const presentNames = new Set(topLevelEntries.map((e) => e.name));
5012
+ const missingKeeps = [...keepSet].filter((name) => !presentNames.has(name));
5013
+ if (missingKeeps.length > 0) {
5014
+ console.warn(
5015
+ ` [warn] Requested to keep ${missingKeeps.map((n) => `'${n}'`).join(", ")} but they don't exist under '${INFRASTRUCTURE_DIR2}/'.`
5016
+ );
5017
+ }
5018
+ console.log(
5019
+ `
5020
+ Done. Deleted ${deleted} top-level entr${deleted === 1 ? "y" : "ies"}. Review the staged deletions with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
5021
+ );
5022
+ }
5023
+
5024
+ // src/migrations/v2.0/fix-accept-requested-registration-function-type.ts
5025
+ var import_ts_morph22 = require("ts-morph");
5026
+ var import_path26 = __toESM(require("path"));
5027
+ var TARGET_FUNCTION_NAME = "acceptRequestedRegistration";
5028
+ var ACTION_PARAMETER_NAME = "action";
5029
+ var OLD_TYPE = "ActionInput";
5030
+ var NEW_TYPE = "Extract<ActionInput, { type?: 'REGISTER' }>";
5031
+ function isAcceptRequestedRegistrationParameter(parameter) {
5032
+ const functionDeclaration = parameter.getFirstAncestorByKind(
5033
+ import_ts_morph22.SyntaxKind.FunctionDeclaration
5034
+ );
5035
+ if (functionDeclaration?.getName() === TARGET_FUNCTION_NAME) {
5036
+ return true;
5037
+ }
5038
+ const arrowFunction = parameter.getFirstAncestorByKind(
5039
+ import_ts_morph22.SyntaxKind.ArrowFunction
5040
+ );
5041
+ const variableDeclaration = arrowFunction?.getFirstAncestorByKind(
5042
+ import_ts_morph22.SyntaxKind.VariableDeclaration
5043
+ );
5044
+ return variableDeclaration?.getName() === TARGET_FUNCTION_NAME;
5045
+ }
5046
+ function processFile14(filePath, project) {
5047
+ const sourceFile = project.getSourceFile(filePath);
5048
+ if (!sourceFile) return 0;
5049
+ let updatedCount = 0;
5050
+ for (const parameter of sourceFile.getDescendantsOfKind(
5051
+ import_ts_morph22.SyntaxKind.Parameter
5052
+ )) {
5053
+ if (parameter.getName() !== ACTION_PARAMETER_NAME) {
5054
+ continue;
5055
+ }
5056
+ if (!isAcceptRequestedRegistrationParameter(parameter)) {
5057
+ continue;
5058
+ }
5059
+ const typeNode = parameter.getTypeNode();
5060
+ if (!typeNode || typeNode.getText() !== OLD_TYPE) {
5061
+ continue;
5062
+ }
5063
+ parameter.setType(NEW_TYPE);
5064
+ updatedCount++;
5065
+ console.log(
5066
+ ` [${import_path26.default.relative(process.cwd(), filePath)}] Updated '${ACTION_PARAMETER_NAME}' in ${TARGET_FUNCTION_NAME} to ${NEW_TYPE}`
5067
+ );
5068
+ }
5069
+ return updatedCount;
5070
+ }
5071
+ async function main27() {
5072
+ const srcDir = import_path26.default.join(process.cwd(), "src");
5073
+ console.log(`Scanning for ${TARGET_FUNCTION_NAME} in: ${srcDir}
5074
+ `);
5075
+ const project = new import_ts_morph22.Project({
5076
+ tsConfigFilePath: import_path26.default.resolve(srcDir, "../tsconfig.json"),
5077
+ skipAddingFilesFromTsConfig: false
4839
5078
  });
4840
- console.log(` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4841
- if ((0, import_fs6.existsSync)(fullPath)) {
4842
- (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4843
- console.log(` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`);
5079
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
5080
+ const filePath = sf.getFilePath();
5081
+ return filePath.includes("/src/") && !filePath.includes("/node_modules/");
5082
+ });
5083
+ let totalUpdated = 0;
5084
+ const modifiedFiles = [];
5085
+ for (const sourceFile of sourceFiles) {
5086
+ const filePath = sourceFile.getFilePath();
5087
+ const updated = processFile14(filePath, project);
5088
+ if (updated > 0) {
5089
+ totalUpdated += updated;
5090
+ modifiedFiles.push(filePath);
5091
+ }
5092
+ }
5093
+ if (modifiedFiles.length === 0) {
5094
+ console.log(
5095
+ `No '${ACTION_PARAMETER_NAME}: ${OLD_TYPE}' parameter in ${TARGET_FUNCTION_NAME} found. Nothing to do.`
5096
+ );
5097
+ return;
5098
+ }
5099
+ console.log(`
5100
+ Saving ${modifiedFiles.length} modified file(s)...`);
5101
+ for (const filePath of modifiedFiles) {
5102
+ const sourceFile = project.getSourceFileOrThrow(filePath);
5103
+ await sourceFile.save();
5104
+ console.log(` Saved: ${import_path26.default.relative(process.cwd(), filePath)}`);
4844
5105
  }
4845
5106
  console.log(
4846
5107
  `
4847
- Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
5108
+ Done. Updated ${totalUpdated} parameter type annotation(s) in ${TARGET_FUNCTION_NAME}.`
4848
5109
  );
4849
5110
  }
4850
5111
 
4851
5112
  // src/migrations/v2.0/index.ts
5113
+ var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
4852
5114
  async function runUpgrade(dockerSwarm) {
4853
5115
  await main18();
4854
5116
  await main();
@@ -4873,10 +5135,12 @@ async function runUpgrade(dockerSwarm) {
4873
5135
  await main22();
4874
5136
  await main23();
4875
5137
  await main24();
5138
+ await main27();
4876
5139
  await main17();
4877
5140
  if (dockerSwarm) {
4878
5141
  await main25();
4879
5142
  } else {
4880
- await main26();
5143
+ await main26({ keep: NON_SWARM_INFRA_SUBDIRS });
5144
+ await main25({ subdirs: NON_SWARM_INFRA_SUBDIRS });
4881
5145
  }
4882
5146
  }