@opencrvs/toolkit 2.0.0-rc.adf3f22 → 2.0.0-rc.afe621f

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 (28) hide show
  1. package/dist/application-config/index.js +12 -20
  2. package/dist/cli.js +295 -122
  3. package/dist/commons/api/router.d.ts +2881 -143
  4. package/dist/commons/conditionals/validate.d.ts +1 -0
  5. package/dist/commons/events/ActionInput.d.ts +108 -0
  6. package/dist/commons/events/Draft.d.ts +3 -0
  7. package/dist/commons/events/utils.d.ts +1 -1
  8. package/dist/events/index.js +28 -34
  9. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +1 -1
  10. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  11. package/dist/migrations/v2.0/checkout-upstream-files.js +1 -2
  12. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts +9 -1
  13. package/dist/migrations/v2.0/delete-infrastructure-directory.d.ts.map +1 -1
  14. package/dist/migrations/v2.0/delete-infrastructure-directory.js +66 -20
  15. package/dist/migrations/v2.0/index.d.ts +5 -3
  16. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  17. package/dist/migrations/v2.0/index.js +295 -122
  18. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts +11 -1
  19. package/dist/migrations/v2.0/merge-infrastructure-directory.d.ts.map +1 -1
  20. package/dist/migrations/v2.0/merge-infrastructure-directory.js +17 -16
  21. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -1
  22. package/dist/migrations/v2.0/migrate-scopes.js +54 -30
  23. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -1
  24. package/dist/migrations/v2.0/migrate-workqueue-configs.js +140 -59
  25. package/dist/notification/index.js +15 -20
  26. package/opencrvs-toolkit-2.0.0-rc.afe621f.tgz +0 -0
  27. package/package.json +1 -1
  28. package/opencrvs-toolkit-2.0.0-rc.adf3f22.tgz +0 -0
@@ -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"));
@@ -2405,7 +2409,6 @@ var DEFAULT_SCOPE_OPTIONS = {
2405
2409
  };
2406
2410
 
2407
2411
  // ../commons/src/scopes.deprecated.do-not-use.ts
2408
- var z4 = __toESM(require("zod/v4"));
2409
2412
  var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2410
2413
  var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2411
2414
  var SearchScope = z4.object({
@@ -2639,6 +2642,74 @@ var legacyScopeToV2Scope = (v1Scope) => {
2639
2642
  }
2640
2643
  throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2641
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
+ }
2642
2713
 
2643
2714
  // src/migrations/v2.0/migrate-scopes.ts
2644
2715
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
@@ -2676,57 +2747,65 @@ function resolveLegacyScopeFromElement(element) {
2676
2747
  }
2677
2748
  function migrateScopesArrays(rolesFilePath, project) {
2678
2749
  const sourceFile = project.getSourceFile(rolesFilePath);
2679
- if (!sourceFile) return { migratedCount: 0, removedCount: 0 };
2750
+ if (!sourceFile) {
2751
+ return { migratedCount: 0, removedCount: 0, mergedCount: 0 };
2752
+ }
2680
2753
  let migratedCount = 0;
2681
2754
  let removedCount = 0;
2755
+ let mergedCount = 0;
2682
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);
2683
2758
  for (const scopesProp of scopesProperties) {
2684
2759
  const initializer = scopesProp.getInitializer();
2685
2760
  if (!initializer || !import_ts_morph11.Node.isArrayLiteralExpression(initializer)) continue;
2686
- const elements = initializer.getElements();
2687
- for (let index = elements.length - 1; index >= 0; index--) {
2688
- const element = elements[index];
2689
- if (!import_ts_morph11.Node.isExpression(element)) continue;
2761
+ const rawTexts = [];
2762
+ const legacyStrings = [];
2763
+ let anyChange = false;
2764
+ for (const element of initializer.getElements()) {
2690
2765
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2691
2766
  if (scopeKey && !(scopeKey in SCOPES)) {
2692
2767
  console.warn(
2693
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2768
+ ` [${relPath}] Removing unknown scope reference: SCOPES.${scopeKey}`
2694
2769
  );
2695
- initializer.removeElement(index);
2696
2770
  removedCount++;
2771
+ anyChange = true;
2697
2772
  continue;
2698
2773
  }
2699
2774
  const legacyScope = resolveLegacyScopeFromElement(element);
2700
2775
  if (!legacyScope) {
2701
2776
  console.warn(
2702
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Skipping non-literal scope expression: ${element.getText()}`
2777
+ ` [${relPath}] Preserving non-literal scope expression verbatim: ${element.getText()}`
2703
2778
  );
2779
+ rawTexts.push(element.getText());
2704
2780
  continue;
2705
2781
  }
2706
- try {
2707
- const migratedScope = legacyScopeToV2Scope(legacyScope);
2708
- const scope = decodeScope(migratedScope);
2709
- if (!scope) {
2710
- console.warn(
2711
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
2712
- );
2713
- continue;
2714
- }
2715
- element.replaceWithText(JSON.stringify(scope));
2716
- migratedCount++;
2717
- } catch (error) {
2718
- console.warn(
2719
- ` [${import_path11.default.relative(process.cwd(), rolesFilePath)}] Could not migrate scope '${legacyScope}': ${error}`
2720
- );
2721
- }
2782
+ legacyStrings.push(legacyScope);
2783
+ anyChange = true;
2722
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
+ );
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(", ")}]`);
2723
2802
  }
2724
2803
  if (removedCount > 0) {
2725
2804
  console.log(
2726
- ` Removed ${removedCount} unknown SCOPES reference(s) from '${import_path11.default.relative(process.cwd(), rolesFilePath)}'.`
2805
+ ` Removed ${removedCount} unknown SCOPES reference(s) from '${relPath}'.`
2727
2806
  );
2728
2807
  }
2729
- return { migratedCount, removedCount };
2808
+ return { migratedCount, removedCount, mergedCount };
2730
2809
  }
2731
2810
  function ensureScopesHelpersImport(rolesFilePath, project) {
2732
2811
  const sourceFile = project.getSourceFile(rolesFilePath);
@@ -2861,7 +2940,7 @@ async function main11() {
2861
2940
  return;
2862
2941
  }
2863
2942
  const importChanged = ensureScopesHelpersImport(rolesFilePath, project);
2864
- const { migratedCount, removedCount } = migrateScopesArrays(
2943
+ const { migratedCount, removedCount, mergedCount } = migrateScopesArrays(
2865
2944
  rolesFilePath,
2866
2945
  project
2867
2946
  );
@@ -2880,7 +2959,7 @@ async function main11() {
2880
2959
  }
2881
2960
  await sourceFile.save();
2882
2961
  console.log(
2883
- `Done. Migrated ${migratedCount} legacy scope(s), removed ${removedCount} unknown SCOPES reference(s), wrapped ${wrappedScopesCount} scope array(s) with defineScopes()${wrappedRoles ? ", wrapped roles with defineRoles()" : ""}${removedRoleType ? ", and removed Role type definition" : ""}${importChanged ? ". Updated toolkit/scopes imports." : "."}`
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." : "."}`
2884
2963
  );
2885
2964
  }
2886
2965
 
@@ -3686,6 +3765,10 @@ var ACTION_PROPERTY_NAME2 = "action";
3686
3765
  var CONDITIONALS_PROPERTY_NAME = "conditionals";
3687
3766
  var TYPE_PROPERTY_NAME7 = "type";
3688
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} }`;
3689
3772
  var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
3690
3773
  "READ",
3691
3774
  "DELETE",
@@ -3733,91 +3816,137 @@ function isUnsupportedActionType(action) {
3733
3816
  }
3734
3817
  return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
3735
3818
  }
3736
- function migrateWorkqueueActions(workqueue, relPath) {
3737
- const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
3738
- if (!actionsProperty || !import_ts_morph17.Node.isPropertyAssignment(actionsProperty)) {
3739
- return 0;
3740
- }
3741
- const actionsInitializer = actionsProperty.getInitializer();
3742
- if (!actionsInitializer || !import_ts_morph17.Node.isArrayLiteralExpression(actionsInitializer)) {
3743
- return 0;
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
+ }
3744
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) {
3745
3848
  const workqueueLabel = getWorkqueueLabel(workqueue);
3746
- const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
3747
- if (existingActionProperty) {
3748
- if (import_ts_morph17.Node.isPropertyAssignment(existingActionProperty)) {
3749
- const existingActionInitializer = existingActionProperty.getInitializer();
3750
- if (existingActionInitializer && import_ts_morph17.Node.isObjectLiteralExpression(existingActionInitializer)) {
3751
- const conditionalsProperty2 = existingActionInitializer.getProperty(
3752
- CONDITIONALS_PROPERTY_NAME
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)
3753
3878
  );
3754
- if (conditionalsProperty2) {
3755
- conditionalsProperty2.remove();
3879
+ if (actionCandidates.length === 0) {
3880
+ actionsProperty.remove();
3756
3881
  console.log(
3757
- ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
3882
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3758
3883
  );
3759
- }
3760
- if (isUnsupportedActionType(existingActionInitializer)) {
3761
- existingActionProperty.remove();
3762
- console.log(
3763
- ` [${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
3764
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
+ }
3765
3919
  }
3766
3920
  }
3767
3921
  }
3768
- actionsProperty.remove();
3769
- console.log(
3770
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
3771
- );
3772
- return 1;
3773
- }
3774
- const actionCandidates = actionsInitializer.getElements().filter(
3775
- (element) => import_ts_morph17.Node.isObjectLiteralExpression(element)
3776
- );
3777
- if (actionCandidates.length === 0) {
3778
- actionsProperty.remove();
3779
- console.log(
3780
- ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
3781
- );
3782
- return 1;
3783
- }
3784
- if (actionCandidates.length > 1) {
3785
- const droppedCount = actionCandidates.length - 1;
3786
- console.warn(
3787
- ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
3788
- );
3789
3922
  }
3790
- const conditionalsProperty = actionCandidates[0].getProperty(
3791
- 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
3792
3932
  );
3793
- if (conditionalsProperty) {
3794
- conditionalsProperty.remove();
3795
- console.log(
3796
- ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
3797
- );
3798
- }
3799
- if (isUnsupportedActionType(actionCandidates[0])) {
3800
- actionsProperty.remove();
3801
- console.log(
3802
- ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
3803
- );
3804
- return 1;
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;
3805
3939
  }
3806
- const firstActionText = actionCandidates[0].getText();
3807
- workqueue.addPropertyAssignment({
3808
- name: ACTION_PROPERTY_NAME2,
3809
- initializer: firstActionText
3940
+ sourceFile.addImportDeclaration({
3941
+ moduleSpecifier: TOOLKIT_EVENTS_MODULE2,
3942
+ namedImports: [ACTION_TYPE_IMPORT_NAME]
3810
3943
  });
3811
- actionsProperty.remove();
3812
- console.log(
3813
- ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
3814
- );
3815
- return 1;
3816
3944
  }
3817
3945
  function processFile13(filePath, project) {
3818
3946
  const sourceFile = project.getSourceFile(filePath);
3819
3947
  if (!sourceFile) return 0;
3820
3948
  let migratedWorkqueues = 0;
3949
+ let needsActionTypeImport = false;
3821
3950
  const relPath = import_path18.default.relative(process.cwd(), filePath);
3822
3951
  const callExpressions = sourceFile.getDescendantsOfKind(
3823
3952
  import_ts_morph17.SyntaxKind.CallExpression
@@ -3833,9 +3962,14 @@ function processFile13(filePath, project) {
3833
3962
  if (!import_ts_morph17.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3834
3963
  for (const element of workqueuesArg.getElements()) {
3835
3964
  if (!import_ts_morph17.Node.isObjectLiteralExpression(element)) continue;
3836
- migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3965
+ const result = migrateWorkqueueActions(element, relPath);
3966
+ if (result.changed) migratedWorkqueues++;
3967
+ if (result.usedReadFallback) needsActionTypeImport = true;
3837
3968
  }
3838
3969
  }
3970
+ if (needsActionTypeImport) {
3971
+ ensureActionTypeImport(sourceFile);
3972
+ }
3839
3973
  return migratedWorkqueues;
3840
3974
  }
3841
3975
  async function main18() {
@@ -4170,7 +4304,7 @@ Saved ${handlerRelPath}.`);
4170
4304
  // src/migrations/v2.0/checkout-upstream-files.ts
4171
4305
  var import_child_process = require("child_process");
4172
4306
  var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
4173
- var UPSTREAM_BRANCH = "develop";
4307
+ var UPSTREAM_BRANCH = "release-v2.0.0";
4174
4308
  var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
4175
4309
  var FILES_TO_CHECKOUT = [
4176
4310
  "src/analytics/analytics.ts",
@@ -4720,9 +4854,13 @@ function gitShowBytes(ref, path23) {
4720
4854
  return null;
4721
4855
  }
4722
4856
  }
4723
- 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(", ");
4724
4862
  console.log(
4725
- `Merging '${INFRASTRUCTURE_DIR}/' from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4863
+ `Merging ${scopeLabel} from ${UPSTREAM_URL}@${UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...
4726
4864
  `
4727
4865
  );
4728
4866
  assertIsGitRepo();
@@ -4737,20 +4875,12 @@ async function main25() {
4737
4875
  const ref = `${TEMP_REMOTE2}/${UPSTREAM_BRANCH}`;
4738
4876
  const baseRef = `${TEMP_REMOTE2}/${BASE_BRANCH}`;
4739
4877
  const upstreamFiles = runGit(
4740
- [
4741
- "ls-tree",
4742
- "-r",
4743
- "--name-only",
4744
- "-z",
4745
- ref,
4746
- "--",
4747
- `${INFRASTRUCTURE_DIR}/`
4748
- ],
4878
+ ["ls-tree", "-r", "--name-only", "-z", ref, "--", ...pathspecs],
4749
4879
  { silent: true }
4750
4880
  ).split("\0").filter(Boolean);
4751
4881
  if (upstreamFiles.length === 0) {
4752
4882
  console.log(
4753
- ` No files found under '${INFRASTRUCTURE_DIR}/' on ${ref}. Nothing to merge.`
4883
+ ` No files found under ${scopeLabel} on ${ref}. Nothing to merge.`
4754
4884
  );
4755
4885
  return;
4756
4886
  }
@@ -4825,7 +4955,9 @@ async function main25() {
4825
4955
  var import_fs6 = require("fs");
4826
4956
  var import_path25 = require("path");
4827
4957
  var INFRASTRUCTURE_DIR2 = "infrastructure";
4828
- async function main26() {
4958
+ async function main26({
4959
+ keep = []
4960
+ } = {}) {
4829
4961
  const fullPath = (0, import_path25.join)(process.cwd(), INFRASTRUCTURE_DIR2);
4830
4962
  if (!(0, import_fs6.existsSync)(fullPath)) {
4831
4963
  console.log(
@@ -4833,24 +4965,64 @@ async function main26() {
4833
4965
  );
4834
4966
  return;
4835
4967
  }
4836
- console.log(`Deleting '${INFRASTRUCTURE_DIR2}/'...
4837
- `);
4838
4968
  assertIsGitRepo();
4839
- runGit(["rm", "-rf", "--ignore-unmatch", "--", `${INFRASTRUCTURE_DIR2}/`], {
4840
- silent: true
4841
- });
4842
- console.log(` Staged deletion of tracked files under '${INFRASTRUCTURE_DIR2}/'.`);
4843
- if ((0, import_fs6.existsSync)(fullPath)) {
4844
- (0, import_fs6.rmSync)(fullPath, { recursive: true, force: true });
4845
- console.log(` Removed remaining untracked files under '${INFRASTRUCTURE_DIR2}/'.`);
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
+ );
4846
5017
  }
4847
5018
  console.log(
4848
5019
  `
4849
- Done. Review the staged deletion with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
5020
+ Done. Deleted ${deleted} top-level entr${deleted === 1 ? "y" : "ies"}. Review the staged deletions with: git diff --cached -- '${INFRASTRUCTURE_DIR2}/'`
4850
5021
  );
4851
5022
  }
4852
5023
 
4853
5024
  // src/migrations/v2.0/index.ts
5025
+ var NON_SWARM_INFRA_SUBDIRS = ["postgres", "metabase"];
4854
5026
  async function runUpgrade(dockerSwarm) {
4855
5027
  await main18();
4856
5028
  await main();
@@ -4879,6 +5051,7 @@ async function runUpgrade(dockerSwarm) {
4879
5051
  if (dockerSwarm) {
4880
5052
  await main25();
4881
5053
  } else {
4882
- await main26();
5054
+ await main26({ keep: NON_SWARM_INFRA_SUBDIRS });
5055
+ await main25({ subdirs: NON_SWARM_INFRA_SUBDIRS });
4883
5056
  }
4884
5057
  }
@@ -1,3 +1,13 @@
1
- declare function main(): Promise<void>;
1
+ interface MergeInfrastructureOptions {
2
+ /**
3
+ * Top-level subdirectories of `infrastructure/` to scope the merge to.
4
+ * When omitted or empty, the entire `infrastructure/` tree is merged
5
+ * (legacy behavior). Each name is relative to `infrastructure/` —
6
+ * e.g. `['postgres', 'metabase']` merges only
7
+ * `infrastructure/postgres/` and `infrastructure/metabase/`.
8
+ */
9
+ subdirs?: string[];
10
+ }
11
+ declare function main({ subdirs }?: MergeInfrastructureOptions): Promise<void>;
2
12
  export { main };
3
13
  //# sourceMappingURL=merge-infrastructure-directory.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"merge-infrastructure-directory.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.0/merge-infrastructure-directory.ts"],"names":[],"mappings":"AAsHA,iBAAe,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAkInC;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
1
+ {"version":3,"file":"merge-infrastructure-directory.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.0/merge-infrastructure-directory.ts"],"names":[],"mappings":"AAsHA,UAAU,0BAA0B;IAClC;;;;;;OAMG;IACH,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;CACnB;AAID,iBAAe,IAAI,CAAC,EAClB,OAAY,EACb,GAAE,0BAA+B,GAAG,OAAO,CAAC,IAAI,CAAC,CAoIjD;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
@@ -22,7 +22,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
22
22
  exports.main = main;
23
23
  /**
24
24
  * Codemod: Merge upstream changes into the local `infrastructure/` directory
25
- * from opencrvs/opencrvs-countryconfig.
25
+ * (or selected subdirectories of it) from opencrvs/opencrvs-countryconfig.
26
26
  *
27
27
  * Usage:
28
28
  * ts-node -r tsconfig-paths/register src/migrations/v2.0/merge-infrastructure-directory.ts
@@ -33,8 +33,10 @@ exports.main = main;
33
33
  * - the upstream "theirs" branch (v2.0) → `UPSTREAM_BRANCH`
34
34
  * - the synthetic merge-base branch (latest 1.9 release line)
35
35
  * → `BASE_BRANCH`
36
- * 2. For every file under `infrastructure/` on upstream "theirs", performs
37
- * a file-scoped 3-way merge:
36
+ * 2. For every file under `infrastructure/` on upstream "theirs" (or, when
37
+ * `subdirs` is provided, only files under
38
+ * `infrastructure/<subdir>/` for each requested subdir), performs a
39
+ * file-scoped 3-way merge:
38
40
  * - new file on upstream → checked out and staged
39
41
  * - existing file → 3-way merged in place via `git merge-file`,
40
42
  * using the BASE_BRANCH version of the file
@@ -116,8 +118,14 @@ function gitShowBytes(ref, path) {
116
118
  }
117
119
  // ─── Entry point ─────────────────────────────────────────────────────────────
118
120
  function main() {
119
- return __awaiter(this, void 0, void 0, function* () {
120
- console.log(`Merging '${INFRASTRUCTURE_DIR}/' from ${checkout_upstream_files_1.UPSTREAM_URL}@${checkout_upstream_files_1.UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...\n`);
121
+ return __awaiter(this, arguments, void 0, function* ({ subdirs = [] } = {}) {
122
+ // Build the pathspec list passed to `git ls-tree`. Trailing slashes make
123
+ // git treat them as tree paths (recurse into them).
124
+ const pathspecs = subdirs.length > 0
125
+ ? subdirs.map((s) => `${INFRASTRUCTURE_DIR}/${s}/`)
126
+ : [`${INFRASTRUCTURE_DIR}/`];
127
+ const scopeLabel = pathspecs.map((p) => `'${p}'`).join(', ');
128
+ console.log(`Merging ${scopeLabel} from ${checkout_upstream_files_1.UPSTREAM_URL}@${checkout_upstream_files_1.UPSTREAM_BRANCH} (base: ${BASE_BRANCH})...\n`);
121
129
  (0, checkout_upstream_files_1.assertIsGitRepo)();
122
130
  // Best-effort cleanup of a stale temp remote from a previous aborted run.
123
131
  (0, checkout_upstream_files_1.tryGit)(['remote', 'remove', TEMP_REMOTE]);
@@ -131,20 +139,13 @@ function main() {
131
139
  const ref = `${TEMP_REMOTE}/${checkout_upstream_files_1.UPSTREAM_BRANCH}`;
132
140
  const baseRef = `${TEMP_REMOTE}/${BASE_BRANCH}`;
133
141
  // -z gives NUL-separated paths so filenames with spaces or newlines
134
- // survive the round-trip.
135
- const upstreamFiles = (0, checkout_upstream_files_1.runGit)([
136
- 'ls-tree',
137
- '-r',
138
- '--name-only',
139
- '-z',
140
- ref,
141
- '--',
142
- `${INFRASTRUCTURE_DIR}/`
143
- ], { silent: true })
142
+ // survive the round-trip. Multiple pathspecs after `--` are unioned
143
+ // by git, which scopes the listing to the requested subdirectories.
144
+ const upstreamFiles = (0, checkout_upstream_files_1.runGit)(['ls-tree', '-r', '--name-only', '-z', ref, '--', ...pathspecs], { silent: true })
144
145
  .split('\0')
145
146
  .filter(Boolean);
146
147
  if (upstreamFiles.length === 0) {
147
- console.log(` No files found under '${INFRASTRUCTURE_DIR}/' on ${ref}. Nothing to merge.`);
148
+ console.log(` No files found under ${scopeLabel} on ${ref}. Nothing to merge.`);
148
149
  return;
149
150
  }
150
151
  const tmpDir = (0, fs_1.mkdtempSync)((0, path_1.join)((0, os_1.tmpdir)(), 'opencrvs-merge-infra-'));
@@ -1 +1 @@
1
- {"version":3,"file":"migrate-scopes.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.0/migrate-scopes.ts"],"names":[],"mappings":"AAyVA,iBAAe,IAAI,kBAmDlB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
1
+ {"version":3,"file":"migrate-scopes.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.0/migrate-scopes.ts"],"names":[],"mappings":"AAoXA,iBAAe,IAAI,kBAmDlB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}