@opencrvs/toolkit 1.9.12-rc.eca3bde → 1.9.12-rc.ee91738

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 +1 -1
  2. package/dist/cli.js +1246 -35
  3. package/dist/commons/api/router.d.ts +163 -161
  4. package/dist/commons/events/EventConfig.d.ts +3 -1
  5. package/dist/commons/events/FieldConfig.d.ts +2 -2
  6. package/dist/commons/events/scopes.d.ts +1 -1
  7. package/dist/events/index.js +17 -4
  8. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +3 -0
  9. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -0
  10. package/dist/migrations/v2.0/checkout-upstream-files.js +143 -0
  11. package/dist/migrations/v2.0/convert-config-files-to-ts.d.ts.map +1 -1
  12. package/dist/migrations/v2.0/convert-config-files-to-ts.js +97 -21
  13. package/dist/migrations/v2.0/create-events-index.d.ts +3 -0
  14. package/dist/migrations/v2.0/create-events-index.d.ts.map +1 -0
  15. package/dist/migrations/v2.0/create-events-index.js +326 -0
  16. package/dist/migrations/v2.0/index.d.ts.map +1 -1
  17. package/dist/migrations/v2.0/index.js +1244 -33
  18. package/dist/migrations/v2.0/migrate-scopes.d.ts.map +1 -1
  19. package/dist/migrations/v2.0/migrate-scopes.js +6 -5
  20. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts +3 -0
  21. package/dist/migrations/v2.0/migrate-workqueue-configs.d.ts.map +1 -0
  22. package/dist/migrations/v2.0/migrate-workqueue-configs.js +237 -0
  23. package/dist/migrations/v2.0/remove-demo-scope.d.ts +3 -0
  24. package/dist/migrations/v2.0/remove-demo-scope.d.ts.map +1 -0
  25. package/dist/migrations/v2.0/remove-demo-scope.js +75 -0
  26. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts +3 -0
  27. package/dist/migrations/v2.0/remove-hearth-migrations.d.ts.map +1 -0
  28. package/dist/migrations/v2.0/remove-hearth-migrations.js +78 -0
  29. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts +3 -0
  30. package/dist/migrations/v2.0/simplify-analytics-precalculations.d.ts.map +1 -0
  31. package/dist/migrations/v2.0/simplify-analytics-precalculations.js +196 -0
  32. package/dist/notification/index.js +5 -2
  33. package/opencrvs-toolkit-1.9.12-rc.ee91738.tgz +0 -0
  34. package/package.json +1 -1
  35. package/tsconfig.json +3 -0
  36. package/tsconfig.tsbuildinfo +1 -1
  37. package/opencrvs-toolkit-1.9.12-rc.eca3bde.tgz +0 -0
@@ -916,8 +916,8 @@ function isBirthConfig(configArg) {
916
916
  }
917
917
  return false;
918
918
  }
919
- function hasElementWithId(array, id) {
920
- for (const el of array.getElements()) {
919
+ function hasElementWithId(array3, id) {
920
+ for (const el of array3.getElements()) {
921
921
  if (!import_ts_morph6.Node.isObjectLiteralExpression(el)) continue;
922
922
  const idProp = el.getProperty("id");
923
923
  if (!idProp || !import_ts_morph6.Node.isPropertyAssignment(idProp)) continue;
@@ -1179,15 +1179,15 @@ function processFile7(filePath, project) {
1179
1179
  const arrayLiterals = sourceFile.getDescendantsOfKind(
1180
1180
  import_ts_morph7.SyntaxKind.ArrayLiteralExpression
1181
1181
  );
1182
- for (const array of arrayLiterals) {
1182
+ for (const array3 of arrayLiterals) {
1183
1183
  const indicesToRemove = [];
1184
- array.getElements().forEach((element, index) => {
1184
+ array3.getElements().forEach((element, index) => {
1185
1185
  if (isPendingCertificationFlag(element)) {
1186
1186
  indicesToRemove.push(index);
1187
1187
  }
1188
1188
  });
1189
1189
  for (const index of indicesToRemove.reverse()) {
1190
- array.removeElement(index);
1190
+ array3.removeElement(index);
1191
1191
  removedCount++;
1192
1192
  console.log(
1193
1193
  ` [${import_path7.default.relative(getCwd(), filePath)}] Removed InherentFlags.PENDING_CERTIFICATION from array`
@@ -1636,25 +1636,6 @@ ${elementParts.join(",\n")}
1636
1636
  ]`;
1637
1637
  }
1638
1638
  function generateTsContent(configObj, exportName, group, isProd) {
1639
- const headerLines = [];
1640
- if (isProd) {
1641
- headerLines.push(`import { env } from './environment'`);
1642
- }
1643
- headerLines.push(`import { ${group.defineFn} } from '${group.importFrom}'`);
1644
- if (group.applicationConfigImportPath) {
1645
- headerLines.push(
1646
- `import { applicationConfig } from '${group.applicationConfigImportPath}'`
1647
- );
1648
- }
1649
- headerLines.push("");
1650
- if (isProd) {
1651
- headerLines.push(`const scheme = 'https'`);
1652
- headerLines.push(`const hostname = env.DOMAIN`);
1653
- headerLines.push(`const sentry = env.SENTRY_DSN`);
1654
- } else {
1655
- headerLines.push(`const scheme = 'http'`);
1656
- headerLines.push(`const hostname = 'localhost'`);
1657
- }
1658
1639
  const propertyLines = [];
1659
1640
  const seenKeys = /* @__PURE__ */ new Set();
1660
1641
  const appConfigKeySet = new Set(group.applicationConfigKeys ?? []);
@@ -1690,6 +1671,27 @@ function generateTsContent(configObj, exportName, group, isProd) {
1690
1671
  propertyLines.push(` ${key}: applicationConfig.${key}`);
1691
1672
  }
1692
1673
  const body = propertyLines.join(",\n");
1674
+ const headerLines = [];
1675
+ headerLines.push(`import * as fs from 'fs'`);
1676
+ headerLines.push(`import { join } from 'path'`);
1677
+ if (isProd) {
1678
+ headerLines.push(`import { env } from './environment'`);
1679
+ }
1680
+ headerLines.push(`import { ${group.defineFn} } from '${group.importFrom}'`);
1681
+ if (group.applicationConfigImportPath) {
1682
+ headerLines.push(
1683
+ `import { applicationConfig } from '${group.applicationConfigImportPath}'`
1684
+ );
1685
+ }
1686
+ headerLines.push("");
1687
+ if (isProd) {
1688
+ headerLines.push(`const scheme = 'https'`);
1689
+ headerLines.push(`const hostname = env.DOMAIN`);
1690
+ headerLines.push(`const sentry = env.SENTRY_DSN`);
1691
+ } else {
1692
+ headerLines.push(`const scheme = 'http'`);
1693
+ headerLines.push(`const hostname = 'localhost'`);
1694
+ }
1693
1695
  return [
1694
1696
  ...headerLines,
1695
1697
  "",
@@ -1824,9 +1826,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1824
1826
  }
1825
1827
  return replacedCount;
1826
1828
  }
1827
- function resolveConfigChain(configObj, path12) {
1829
+ function resolveConfigChain(configObj, path17) {
1828
1830
  let current = configObj;
1829
- for (const key of path12) {
1831
+ for (const key of path17) {
1830
1832
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1831
1833
  const prop = current.getProperty(key);
1832
1834
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -1836,6 +1838,40 @@ function resolveConfigChain(configObj, path12) {
1836
1838
  }
1837
1839
  return current.getText();
1838
1840
  }
1841
+ function rewriteDirnameRefs(text, relDir) {
1842
+ if (!relDir || relDir === ".") return text;
1843
+ const relForward = relDir.replace(/\\/g, "/");
1844
+ return text.replace(
1845
+ /\b((?:path\.)?(?:join|resolve))\s*\(\s*__dirname\s*,/g,
1846
+ `$1(__dirname, '${relForward}',`
1847
+ );
1848
+ }
1849
+ function ensureFsImport(sf) {
1850
+ const hasFs = sf.getImportDeclarations().some(
1851
+ (d) => d.getModuleSpecifierValue() === "fs" && (d.getNamespaceImport() || d.getDefaultImport())
1852
+ );
1853
+ if (hasFs) return;
1854
+ sf.addImportDeclaration({
1855
+ moduleSpecifier: "fs",
1856
+ namespaceImport: "fs"
1857
+ });
1858
+ }
1859
+ function ensureJoinImport(sf) {
1860
+ const pathImports = sf.getImportDeclarations().filter((d) => d.getModuleSpecifierValue() === "path");
1861
+ if (pathImports.some(
1862
+ (d) => d.getNamedImports().some((ni) => ni.getName() === "join")
1863
+ )) {
1864
+ return;
1865
+ }
1866
+ if (pathImports.length > 0) {
1867
+ pathImports[0].addNamedImport("join");
1868
+ return;
1869
+ }
1870
+ sf.addImportDeclaration({
1871
+ moduleSpecifier: "path",
1872
+ namedImports: ["join"]
1873
+ });
1874
+ }
1839
1875
  async function main10() {
1840
1876
  const srcDir = import_path10.default.join(getCwd(), "src");
1841
1877
  const relCwd = (fp) => import_path10.default.relative(getCwd(), fp);
@@ -1881,12 +1917,15 @@ async function main10() {
1881
1917
  });
1882
1918
  if (propsToRemove.length > 0) {
1883
1919
  const filesToSaveAfterInlining = /* @__PURE__ */ new Set();
1920
+ const appConfigDir = import_path10.default.dirname(appConfigAbsPath);
1884
1921
  for (const removedProp of propsToRemove) {
1885
1922
  const key = removedProp.getName();
1886
1923
  for (const sf of appConfigProject.getSourceFiles()) {
1887
1924
  if (sf.getFilePath() === appConfigAbsPath) continue;
1888
1925
  if (!sf.getFilePath().includes("/src/")) continue;
1889
1926
  if (sf.getFilePath().includes("/node_modules/")) continue;
1927
+ const targetDir = import_path10.default.dirname(sf.getFilePath());
1928
+ const relDirFromTarget = import_path10.default.relative(targetDir, appConfigDir);
1890
1929
  let madeReplacement = true;
1891
1930
  while (madeReplacement) {
1892
1931
  madeReplacement = false;
@@ -1911,9 +1950,19 @@ async function main10() {
1911
1950
  );
1912
1951
  continue;
1913
1952
  }
1914
- node.replaceWithText(resolvedValue);
1953
+ const adjustedValue = rewriteDirnameRefs(
1954
+ resolvedValue,
1955
+ relDirFromTarget
1956
+ );
1957
+ node.replaceWithText(adjustedValue);
1958
+ if (/\bfs\s*\./.test(adjustedValue)) {
1959
+ ensureFsImport(sf);
1960
+ }
1961
+ if (/\bjoin\s*\(/.test(adjustedValue)) {
1962
+ ensureJoinImport(sf);
1963
+ }
1915
1964
  console.log(
1916
- ` Inlined applicationConfig.${accessPath.join(".")} \u2192 ${resolvedValue} in ${import_path10.default.relative(getCwd(), sf.getFilePath())}`
1965
+ ` Inlined applicationConfig.${accessPath.join(".")} \u2192 ${adjustedValue} in ${import_path10.default.relative(getCwd(), sf.getFilePath())}`
1917
1966
  );
1918
1967
  filesToSaveAfterInlining.add(sf);
1919
1968
  madeReplacement = true;
@@ -2013,7 +2062,486 @@ Done. Converted ${convertedCount} config file(s), replaced ${totalReplaced} rout
2013
2062
  // src/migrations/v2.0/migrate-scopes.ts
2014
2063
  var import_ts_morph11 = require("ts-morph");
2015
2064
  var import_path11 = __toESM(require("path"));
2016
- var import_commons = require("../commons");
2065
+
2066
+ // ../commons/src/scopes.ts
2067
+ var z3 = __toESM(require("zod/v4"));
2068
+ var qs = __toESM(require("qs"));
2069
+
2070
+ // ../commons/src/uuid.ts
2071
+ var import_uuid = require("uuid");
2072
+ var z = __toESM(require("zod/v4"));
2073
+ var UUID = z.uuid().brand("UUID");
2074
+
2075
+ // ../commons/src/authentication.ts
2076
+ var import_jwt_decode = __toESM(require("jwt-decode"));
2077
+ var z2 = __toESM(require("zod/v4"));
2078
+ var TokenUserType = z2.enum(["user", "system"]);
2079
+ var TokenWithBearer = z2.string().regex(/^Bearer\s/);
2080
+
2081
+ // ../commons/src/scopes.ts
2082
+ var JurisdictionFilter = z3.enum(["administrativeArea", "location", "all"]).describe(
2083
+ "Filters based on user jurisdiction relative to their office location in hierarchy."
2084
+ );
2085
+ var UserFilter = z3.enum(["user"]).describe("Filters based on the user. Limits to self.");
2086
+ var RecordScopeTypeV2 = z3.enum([
2087
+ "record.search",
2088
+ "record.create",
2089
+ "record.read",
2090
+ "record.declare",
2091
+ "record.notify",
2092
+ "record.edit",
2093
+ "record.reject",
2094
+ "record.archive",
2095
+ "record.review-duplicates",
2096
+ "record.register",
2097
+ "record.print-certified-copies",
2098
+ "record.request-correction",
2099
+ "record.correct",
2100
+ "record.unassign-others",
2101
+ "record.custom-action"
2102
+ ]);
2103
+ var PlainScopeType = z3.enum([
2104
+ // Misc. system scopes
2105
+ "bypassratelimit",
2106
+ "record.reindex",
2107
+ "user.data-seeding",
2108
+ "integration.create",
2109
+ "record.import",
2110
+ "config.update-all",
2111
+ "attachment.upload",
2112
+ "profile.electronic-signature",
2113
+ "user.read-only-my-audit",
2114
+ // Performance dashboard
2115
+ "performance.read",
2116
+ "performance.read-dashboards",
2117
+ "performance.vital-statistics-export",
2118
+ // Scopes used exclusively by countryconfig integration token
2119
+ "record.confirm-registration",
2120
+ "record.reject-registration"
2121
+ ]);
2122
+ var scopeByEvent = z3.preprocess(
2123
+ (val) => val === void 0 ? void 0 : [val].flat(),
2124
+ z3.array(z3.string()).optional()
2125
+ ).describe("Event type, e.g. birth, death");
2126
+ var scopeOptionsPlaceEvent = z3.object({
2127
+ event: scopeByEvent,
2128
+ placeOfEvent: JurisdictionFilter.optional()
2129
+ }).describe("Options applicable to all record scopes.");
2130
+ var scopeOptionsDeclared = scopeOptionsPlaceEvent.extend({
2131
+ declaredIn: JurisdictionFilter.optional(),
2132
+ declaredBy: UserFilter.optional()
2133
+ }).describe("Options applicable to actions that may take place after DECLARE");
2134
+ var AllRecordScopeOptions = scopeOptionsDeclared.extend({
2135
+ registeredIn: JurisdictionFilter.optional(),
2136
+ registeredBy: UserFilter.optional()
2137
+ }).describe(
2138
+ "Options applicable to actions that may take place after REGISTER, with full filtering capabilities."
2139
+ );
2140
+ var CustomActionScopeOptions = AllRecordScopeOptions.extend({
2141
+ customActionTypes: z3.preprocess(
2142
+ (val) => val === void 0 ? void 0 : [val].flat(),
2143
+ z3.array(z3.string()).optional()
2144
+ ).describe("Allowed custom action types")
2145
+ });
2146
+ var AccessLevelOptions = z3.object({
2147
+ accessLevel: JurisdictionFilter.optional()
2148
+ });
2149
+ var WorkqueueOrDashboardOptions = z3.object({
2150
+ ids: z3.preprocess(
2151
+ (val) => val === void 0 ? void 0 : [val].flat(),
2152
+ z3.array(z3.string())
2153
+ ).describe("Must contain a list of workqueue or dashboard ids.")
2154
+ });
2155
+ var AllScopeOptions = z3.object({
2156
+ ...AllRecordScopeOptions.shape,
2157
+ ...AccessLevelOptions.shape,
2158
+ ...WorkqueueOrDashboardOptions.shape
2159
+ });
2160
+ var ScopeOptionKey = AllScopeOptions.keyof();
2161
+ var ResolvedScopeOptionsPlaceEvent = z3.object({
2162
+ event: scopeByEvent,
2163
+ placeOfEvent: UUID.nullish()
2164
+ }).describe(
2165
+ "Resolved options applicable to all record scopes, with location ID instead of jurisdiction filter."
2166
+ );
2167
+ var ResolvedScopeOptionsDeclared = ResolvedScopeOptionsPlaceEvent.extend({
2168
+ declaredIn: UUID.nullish(),
2169
+ declaredBy: z3.string().optional()
2170
+ }).describe(
2171
+ "Resolved options applicable to actions that may take place after DECLARE, with location ID and user ID instead of filters."
2172
+ );
2173
+ var ResolvedScopeOptionsFull = ResolvedScopeOptionsDeclared.extend({
2174
+ registeredIn: UUID.nullish(),
2175
+ registeredBy: z3.string().optional()
2176
+ }).describe(
2177
+ "Resolved options applicable to actions that may take place after REGISTER, with full filtering capabilities and location/user IDs instead of filters."
2178
+ );
2179
+ var ScopesWithPlaceEventOptions = RecordScopeTypeV2.extract([
2180
+ "record.create",
2181
+ "record.declare",
2182
+ "record.notify"
2183
+ ]);
2184
+ var ScopesWithDeclaredOptions = RecordScopeTypeV2.extract([
2185
+ "record.edit",
2186
+ "record.reject",
2187
+ "record.archive",
2188
+ "record.review-duplicates",
2189
+ "record.register"
2190
+ ]);
2191
+ var ScopesWithFullOptions = RecordScopeTypeV2.extract([
2192
+ "record.search",
2193
+ "record.read",
2194
+ "record.request-correction",
2195
+ "record.correct",
2196
+ "record.unassign-others"
2197
+ ]);
2198
+ var ScopeOptionsPrintCertifiedCopies = AllRecordScopeOptions.extend({
2199
+ templates: z3.preprocess(
2200
+ (val) => val === void 0 ? void 0 : [val].flat(),
2201
+ z3.array(z3.string()).optional()
2202
+ ).describe(
2203
+ "Template IDs for certified copies. Controls which certificate templates are returned to the client via the config service. Certificate printing is a client-side operation \u2014 this option is not validated when the printCertificate action is submitted."
2204
+ )
2205
+ });
2206
+ var RecordScopeV2 = z3.discriminatedUnion("type", [
2207
+ z3.object({
2208
+ type: ScopesWithPlaceEventOptions,
2209
+ options: scopeOptionsPlaceEvent.optional()
2210
+ }),
2211
+ z3.object({
2212
+ type: ScopesWithDeclaredOptions,
2213
+ options: scopeOptionsDeclared.optional()
2214
+ }),
2215
+ z3.object({
2216
+ type: ScopesWithFullOptions,
2217
+ options: AllRecordScopeOptions.optional()
2218
+ }),
2219
+ z3.object({
2220
+ type: z3.literal("record.custom-action"),
2221
+ options: CustomActionScopeOptions.optional()
2222
+ }),
2223
+ z3.object({
2224
+ type: z3.literal("record.print-certified-copies"),
2225
+ options: ScopeOptionsPrintCertifiedCopies.optional()
2226
+ })
2227
+ ]).describe(
2228
+ "Scopes used to check user's permission to perform actions on a record."
2229
+ );
2230
+ var ResolvedRecordScopeV2 = z3.discriminatedUnion("type", [
2231
+ z3.object({
2232
+ type: ScopesWithPlaceEventOptions,
2233
+ options: ResolvedScopeOptionsPlaceEvent.optional()
2234
+ }),
2235
+ z3.object({
2236
+ type: ScopesWithDeclaredOptions,
2237
+ options: ResolvedScopeOptionsDeclared.optional()
2238
+ }),
2239
+ z3.object({
2240
+ type: ScopesWithFullOptions,
2241
+ options: ResolvedScopeOptionsFull.optional()
2242
+ }),
2243
+ z3.object({
2244
+ type: z3.literal("record.print-certified-copies"),
2245
+ options: ResolvedScopeOptionsFull.extend({
2246
+ templates: z3.array(z3.string()).optional()
2247
+ }).optional()
2248
+ })
2249
+ ]).describe("Resolved scope with location/user IDs instead of filters.");
2250
+ var SystemScopeType = z3.enum([
2251
+ "organisation.read-locations",
2252
+ "user.read",
2253
+ "user.create",
2254
+ "user.edit"
2255
+ ]);
2256
+ var Scope2 = z3.discriminatedUnion("type", [
2257
+ z3.object({ type: PlainScopeType }),
2258
+ ...RecordScopeV2.options,
2259
+ z3.object({ type: SystemScopeType, options: AccessLevelOptions.optional() }),
2260
+ z3.object({
2261
+ type: z3.literal("workqueue"),
2262
+ options: WorkqueueOrDashboardOptions
2263
+ }),
2264
+ z3.object({
2265
+ type: z3.literal("dashboard.view"),
2266
+ options: WorkqueueOrDashboardOptions
2267
+ })
2268
+ ]);
2269
+ var ScopeType2 = z3.enum([
2270
+ ...SystemScopeType.options,
2271
+ ...RecordScopeTypeV2.options,
2272
+ ...PlainScopeType.options,
2273
+ "workqueue",
2274
+ "dashboard.view"
2275
+ ]);
2276
+ var flattenScope = (scope) => ({
2277
+ type: scope.type,
2278
+ ..."options" in scope ? scope.options : {}
2279
+ });
2280
+ var unflattenScope = (input) => {
2281
+ const { type, ...options } = input;
2282
+ return { type, options };
2283
+ };
2284
+ var EncodedScope2 = z3.string().brand("EncodedScope");
2285
+ var encodeScope = (scope) => {
2286
+ const flattened = flattenScope(scope);
2287
+ return qs.stringify(flattened, {
2288
+ arrayFormat: "comma",
2289
+ allowDots: true,
2290
+ addQueryPrefix: false,
2291
+ encode: false
2292
+ });
2293
+ };
2294
+ var decodeScope = (query) => {
2295
+ const scope = qs.parse(query, {
2296
+ ignoreQueryPrefix: true,
2297
+ comma: true,
2298
+ allowDots: true
2299
+ });
2300
+ const unflattenedScope = unflattenScope(scope);
2301
+ return Scope2.safeParse(unflattenedScope)?.data;
2302
+ };
2303
+ var DEFAULT_SCOPE_OPTIONS = {
2304
+ placeOfEvent: JurisdictionFilter.enum.all,
2305
+ accessLevel: JurisdictionFilter.enum.all
2306
+ };
2307
+
2308
+ // ../commons/src/scopes.deprecated.do-not-use.ts
2309
+ var z4 = __toESM(require("zod/v4"));
2310
+ var rawConfigurableScopeRegex = /^([a-zA-Z][a-zA-Z0-9.-]*(?:\.[a-zA-Z0-9.-]+)*)\[((?:\w+=[\w.-]+(?:\|[\w.-]+)*)(?:,[\w]+=[\w.-]+(?:\|[\w.-]+)*)*)\]$/;
2311
+ var rawConfigurableScope = z4.string().regex(rawConfigurableScopeRegex);
2312
+ var SearchScope = z4.object({
2313
+ type: z4.literal("search"),
2314
+ options: z4.object({
2315
+ event: z4.array(z4.string()).length(1),
2316
+ access: z4.array(z4.enum(["my-jurisdiction", "all"])).length(1)
2317
+ })
2318
+ });
2319
+ var CreateUserScope = z4.object({
2320
+ type: z4.literal("user.create"),
2321
+ options: z4.object({
2322
+ role: z4.array(z4.string())
2323
+ })
2324
+ });
2325
+ var EditUserScope = z4.object({
2326
+ type: z4.literal("user.edit"),
2327
+ options: z4.object({
2328
+ role: z4.array(z4.string())
2329
+ })
2330
+ });
2331
+ var WorkqueueScope = z4.object({
2332
+ type: z4.literal("workqueue"),
2333
+ options: z4.object({
2334
+ id: z4.array(z4.string())
2335
+ })
2336
+ });
2337
+ var PrintCertifiedCopiesScope = z4.object({
2338
+ type: z4.literal("record.registered.print-certified-copies"),
2339
+ options: z4.object({
2340
+ event: z4.array(z4.string()).describe("Event type, e.g. birth, death"),
2341
+ templates: z4.array(z4.string()).optional().describe(
2342
+ "Template IDs for certified copies. If not provided, all templates will be used."
2343
+ )
2344
+ })
2345
+ });
2346
+ var LegacyRecordScope = z4.object({
2347
+ type: z4.enum([
2348
+ "record.create",
2349
+ "record.read",
2350
+ "record.declare",
2351
+ "record.notify",
2352
+ "record.declared.edit",
2353
+ "record.declared.validate",
2354
+ "record.declared.reject",
2355
+ "record.declared.archive",
2356
+ "record.declared.review-duplicates",
2357
+ "record.register",
2358
+ "record.registered.request-correction",
2359
+ "record.registered.correct",
2360
+ "record.unassign-others"
2361
+ ]),
2362
+ options: z4.object({
2363
+ event: z4.array(z4.string()).describe("Event type, e.g. birth, death")
2364
+ })
2365
+ }).describe(
2366
+ "Scopes used to check user's permission to perform actions on a record."
2367
+ );
2368
+ var ConfigurableRawScopes = z4.discriminatedUnion("type", [
2369
+ SearchScope,
2370
+ LegacyRecordScope,
2371
+ PrintCertifiedCopiesScope,
2372
+ CreateUserScope,
2373
+ EditUserScope,
2374
+ WorkqueueScope
2375
+ ]);
2376
+ function getScopeOptions(rawOptions) {
2377
+ return rawOptions.split(",").reduce((acc, option) => {
2378
+ const [key, value] = option.split("=");
2379
+ acc[key] = value.split("|");
2380
+ return acc;
2381
+ }, {});
2382
+ }
2383
+ function parseConfigurableScope(scope) {
2384
+ const maybeConfigurableScope = rawConfigurableScope.safeParse(scope);
2385
+ if (!maybeConfigurableScope.success) {
2386
+ return;
2387
+ }
2388
+ const rawScope = maybeConfigurableScope.data;
2389
+ const [, type, rawOptions] = rawScope.match(rawConfigurableScopeRegex) ?? [];
2390
+ const options = getScopeOptions(rawOptions);
2391
+ const parsedScope = {
2392
+ type,
2393
+ options
2394
+ };
2395
+ const result = ConfigurableRawScopes.safeParse(parsedScope);
2396
+ return result.success ? result.data : void 0;
2397
+ }
2398
+ var SCOPES = {
2399
+ BYPASSRATELIMIT: "bypassratelimit",
2400
+ RECORD_REINDEX: "record.reindex",
2401
+ RECORD_IMPORT: "record.import",
2402
+ ATTACHMENT_UPLOAD: "attachment.upload",
2403
+ USER_DATA_SEEDING: "user.data-seeding",
2404
+ INTEGRATION_CREATE: "integration.create",
2405
+ PERFORMANCE_EXPORT_VITAL_STATISTICS: "performance.vital-statistics-export",
2406
+ PROFILE_ELECTRONIC_SIGNATURE: "profile.electronic-signature",
2407
+ PERFORMANCE_READ: "performance.read",
2408
+ PERFORMANCE_READ_DASHBOARDS: "performance.read-dashboards",
2409
+ CONFIG_UPDATE_ALL: "config.update-all",
2410
+ ORGANISATION_READ_LOCATIONS: "organisation.read-locations",
2411
+ ORGANISATION_READ_LOCATIONS_MY_OFFICE: "organisation.read-locations:my-office",
2412
+ ORGANISATION_READ_LOCATIONS_MY_JURISDICTION: "organisation.read-locations:my-jurisdiction",
2413
+ USER_CREATE: "user.create:all",
2414
+ USER_READ: "user.read:all",
2415
+ USER_UPDATE: "user.update:all",
2416
+ USER_READ_MY_OFFICE: "user.read:my-office",
2417
+ USER_READ_MY_JURISDICTION: "user.read:my-jurisdiction",
2418
+ USER_READ_ONLY_MY_AUDIT: "user.read:only-my-audit",
2419
+ USER_CREATE_MY_JURISDICTION: "user.create:my-jurisdiction",
2420
+ USER_UPDATE_MY_JURISDICTION: "user.update:my-jurisdiction"
2421
+ };
2422
+ var literalScopeToV2ScopeMap = {
2423
+ [SCOPES.BYPASSRATELIMIT]: { type: "bypassratelimit" },
2424
+ [SCOPES.RECORD_REINDEX]: { type: "record.reindex" },
2425
+ [SCOPES.RECORD_IMPORT]: { type: "record.import" },
2426
+ [SCOPES.ATTACHMENT_UPLOAD]: { type: "attachment.upload" },
2427
+ [SCOPES.USER_DATA_SEEDING]: { type: "user.data-seeding" },
2428
+ [SCOPES.INTEGRATION_CREATE]: { type: "integration.create" },
2429
+ [SCOPES.PERFORMANCE_EXPORT_VITAL_STATISTICS]: {
2430
+ type: "performance.vital-statistics-export"
2431
+ },
2432
+ [SCOPES.PROFILE_ELECTRONIC_SIGNATURE]: {
2433
+ type: "profile.electronic-signature"
2434
+ },
2435
+ [SCOPES.PERFORMANCE_READ]: { type: "performance.read" },
2436
+ [SCOPES.PERFORMANCE_READ_DASHBOARDS]: { type: "performance.read-dashboards" },
2437
+ [SCOPES.CONFIG_UPDATE_ALL]: { type: "config.update-all" },
2438
+ [SCOPES.ORGANISATION_READ_LOCATIONS]: {
2439
+ type: "organisation.read-locations"
2440
+ },
2441
+ [SCOPES.ORGANISATION_READ_LOCATIONS_MY_OFFICE]: {
2442
+ type: "organisation.read-locations",
2443
+ options: { accessLevel: "location" }
2444
+ },
2445
+ [SCOPES.ORGANISATION_READ_LOCATIONS_MY_JURISDICTION]: {
2446
+ type: "organisation.read-locations",
2447
+ options: { accessLevel: "administrativeArea" }
2448
+ },
2449
+ [SCOPES.USER_CREATE]: { type: "user.create" },
2450
+ [SCOPES.USER_CREATE_MY_JURISDICTION]: {
2451
+ type: "user.create",
2452
+ options: { accessLevel: "administrativeArea" }
2453
+ },
2454
+ [SCOPES.USER_READ]: { type: "user.read" },
2455
+ [SCOPES.USER_READ_MY_OFFICE]: {
2456
+ type: "user.read",
2457
+ options: { accessLevel: "location" }
2458
+ },
2459
+ [SCOPES.USER_READ_MY_JURISDICTION]: {
2460
+ type: "user.read",
2461
+ options: { accessLevel: "administrativeArea" }
2462
+ },
2463
+ [SCOPES.USER_READ_ONLY_MY_AUDIT]: { type: "user.read-only-my-audit" },
2464
+ [SCOPES.USER_UPDATE]: { type: "user.edit" },
2465
+ [SCOPES.USER_UPDATE_MY_JURISDICTION]: {
2466
+ type: "user.edit",
2467
+ options: { accessLevel: "administrativeArea" }
2468
+ }
2469
+ };
2470
+ function parseLiteralScope(scope) {
2471
+ if (scope in literalScopeToV2ScopeMap) {
2472
+ return literalScopeToV2ScopeMap[scope];
2473
+ }
2474
+ return void 0;
2475
+ }
2476
+ var v1ToV2ConfigScopeTypeMap = {
2477
+ search: "record.search",
2478
+ workqueue: "workqueue",
2479
+ "user.create": "user.create",
2480
+ "user.edit": "user.edit",
2481
+ "record.create": "record.create",
2482
+ "record.read": "record.read",
2483
+ "record.declare": "record.declare",
2484
+ "record.notify": "record.notify",
2485
+ "record.register": "record.register",
2486
+ "record.unassign-others": "record.unassign-others",
2487
+ "record.declared.reject": "record.reject",
2488
+ "record.declared.archive": "record.archive",
2489
+ "record.declared.review-duplicates": "record.review-duplicates",
2490
+ "record.registered.print-certified-copies": "record.print-certified-copies",
2491
+ "record.registered.request-correction": "record.request-correction",
2492
+ "record.registered.correct": "record.correct",
2493
+ "record.declared.edit": "record.edit",
2494
+ "record.declared.validate": "record.custom-action"
2495
+ };
2496
+ var legacyScopeToV2Scope = (v1Scope) => {
2497
+ const configurableV1Scope = parseConfigurableScope(v1Scope);
2498
+ const literalV1Scope = parseLiteralScope(v1Scope);
2499
+ if (!configurableV1Scope && !literalV1Scope) {
2500
+ throw new Error(`Invalid V1 scope: ${v1Scope}`);
2501
+ }
2502
+ if (literalV1Scope) {
2503
+ return encodeScope(literalV1Scope);
2504
+ }
2505
+ if (configurableV1Scope) {
2506
+ const type = v1ToV2ConfigScopeTypeMap[configurableV1Scope.type];
2507
+ if (type === void 0) {
2508
+ throw new Error(`Unsupported V1 scope type: ${configurableV1Scope.type}`);
2509
+ }
2510
+ if (configurableV1Scope.type === "workqueue") {
2511
+ return encodeScope({
2512
+ type: "workqueue",
2513
+ options: {
2514
+ ids: configurableV1Scope.options.id || []
2515
+ }
2516
+ });
2517
+ }
2518
+ if (configurableV1Scope.type === "search") {
2519
+ return encodeScope({
2520
+ type,
2521
+ options: {
2522
+ event: configurableV1Scope.options.event || [],
2523
+ placeOfEvent: configurableV1Scope.options.access[0] === "my-jurisdiction" ? "administrativeArea" : "all"
2524
+ }
2525
+ });
2526
+ }
2527
+ if (configurableV1Scope.type === "record.declared.validate") {
2528
+ return encodeScope({
2529
+ type: "record.custom-action",
2530
+ options: {
2531
+ event: configurableV1Scope.options.event,
2532
+ customActionTypes: ["VALIDATE_DECLARATION"]
2533
+ }
2534
+ });
2535
+ }
2536
+ return encodeScope({
2537
+ type,
2538
+ options: configurableV1Scope.options
2539
+ });
2540
+ }
2541
+ throw new Error(`Unsupported V1 scope type: ${v1Scope}`);
2542
+ };
2543
+
2544
+ // src/migrations/v2.0/migrate-scopes.ts
2017
2545
  var ROLES_FILE_RELATIVE_PATH = "src/data-seeding/roles/roles.ts";
2018
2546
  var SCOPES_PROPERTY_NAME = "scopes";
2019
2547
  var TOOLKIT_SCOPES_MODULE = "@opencrvs/toolkit/scopes";
@@ -2037,7 +2565,7 @@ function resolveLegacyScopeFromElement(element) {
2037
2565
  }
2038
2566
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2039
2567
  if (scopeKey) {
2040
- const scopeValue = import_commons.SCOPES[scopeKey];
2568
+ const scopeValue = SCOPES[scopeKey];
2041
2569
  return typeof scopeValue === "string" ? scopeValue : null;
2042
2570
  }
2043
2571
  const expressionType = element.getType();
@@ -2061,7 +2589,7 @@ function migrateScopesArrays(rolesFilePath, project) {
2061
2589
  const element = elements[index];
2062
2590
  if (!import_ts_morph11.Node.isExpression(element)) continue;
2063
2591
  const scopeKey = resolveScopeKeyFromElementAccess(element);
2064
- if (scopeKey && !(scopeKey in import_commons.SCOPES)) {
2592
+ if (scopeKey && !(scopeKey in SCOPES)) {
2065
2593
  console.warn(
2066
2594
  ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Removing unknown scope reference: SCOPES.${scopeKey}`
2067
2595
  );
@@ -2077,8 +2605,8 @@ function migrateScopesArrays(rolesFilePath, project) {
2077
2605
  continue;
2078
2606
  }
2079
2607
  try {
2080
- const migratedScope = (0, import_commons.legacyScopeToV2Scope)(legacyScope);
2081
- const scope = (0, import_commons.decodeScope)(migratedScope);
2608
+ const migratedScope = legacyScopeToV2Scope(legacyScope);
2609
+ const scope = decodeScope(migratedScope);
2082
2610
  if (!scope) {
2083
2611
  console.warn(
2084
2612
  ` [${import_path11.default.relative(getCwd(), rolesFilePath)}] Could not decode migrated scope '${migratedScope}'.`
@@ -2327,6 +2855,683 @@ Saving ${modifiedFiles.length} modified file(s)...`);
2327
2855
  Done. Removed ${totalRemoved} deprecated import(s).`);
2328
2856
  }
2329
2857
 
2858
+ // src/migrations/v2.0/migrate-workqueue-configs.ts
2859
+ var import_ts_morph13 = require("ts-morph");
2860
+ var import_path13 = __toESM(require("path"));
2861
+ var DEFINE_WORKQUEUES_NAME3 = "defineWorkqueues";
2862
+ var ACTIONS_PROPERTY_NAME5 = "actions";
2863
+ var ACTION_PROPERTY_NAME2 = "action";
2864
+ var CONDITIONALS_PROPERTY_NAME = "conditionals";
2865
+ var TYPE_PROPERTY_NAME7 = "type";
2866
+ var SLUG_PROPERTY_NAME = "slug";
2867
+ var SUPPORTED_WORKQUEUE_ACTION_TYPES = /* @__PURE__ */ new Set([
2868
+ "READ",
2869
+ "DELETE",
2870
+ "DECLARE",
2871
+ "REGISTER",
2872
+ "EDIT",
2873
+ "REJECT",
2874
+ "MARK_AS_DUPLICATE",
2875
+ "ARCHIVE",
2876
+ "PRINT_CERTIFICATE",
2877
+ "REQUEST_CORRECTION"
2878
+ ]);
2879
+ function getWorkqueueLabel(workqueue) {
2880
+ const slugProperty = workqueue.getProperty(SLUG_PROPERTY_NAME);
2881
+ if (!slugProperty || !import_ts_morph13.Node.isPropertyAssignment(slugProperty)) {
2882
+ return "(unknown slug)";
2883
+ }
2884
+ const slugInitializer = slugProperty.getInitializer();
2885
+ if (!slugInitializer || !import_ts_morph13.Node.isStringLiteral(slugInitializer)) {
2886
+ return "(unknown slug)";
2887
+ }
2888
+ return slugInitializer.getLiteralValue();
2889
+ }
2890
+ function getActionTypeName(action) {
2891
+ const typeProperty = action.getProperty(TYPE_PROPERTY_NAME7);
2892
+ if (!typeProperty || !import_ts_morph13.Node.isPropertyAssignment(typeProperty)) {
2893
+ return null;
2894
+ }
2895
+ const typeInitializer = typeProperty.getInitializer();
2896
+ if (!typeInitializer) {
2897
+ return null;
2898
+ }
2899
+ if (import_ts_morph13.Node.isStringLiteral(typeInitializer)) {
2900
+ return typeInitializer.getLiteralValue();
2901
+ }
2902
+ if (import_ts_morph13.Node.isPropertyAccessExpression(typeInitializer)) {
2903
+ return typeInitializer.getName();
2904
+ }
2905
+ return null;
2906
+ }
2907
+ function isUnsupportedActionType(action) {
2908
+ const typeName = getActionTypeName(action);
2909
+ if (!typeName) {
2910
+ return false;
2911
+ }
2912
+ return !SUPPORTED_WORKQUEUE_ACTION_TYPES.has(typeName);
2913
+ }
2914
+ function migrateWorkqueueActions(workqueue, relPath) {
2915
+ const actionsProperty = workqueue.getProperty(ACTIONS_PROPERTY_NAME5);
2916
+ if (!actionsProperty || !import_ts_morph13.Node.isPropertyAssignment(actionsProperty)) {
2917
+ return 0;
2918
+ }
2919
+ const actionsInitializer = actionsProperty.getInitializer();
2920
+ if (!actionsInitializer || !import_ts_morph13.Node.isArrayLiteralExpression(actionsInitializer)) {
2921
+ return 0;
2922
+ }
2923
+ const workqueueLabel = getWorkqueueLabel(workqueue);
2924
+ const existingActionProperty = workqueue.getProperty(ACTION_PROPERTY_NAME2);
2925
+ if (existingActionProperty) {
2926
+ if (import_ts_morph13.Node.isPropertyAssignment(existingActionProperty)) {
2927
+ const existingActionInitializer = existingActionProperty.getInitializer();
2928
+ if (existingActionInitializer && import_ts_morph13.Node.isObjectLiteralExpression(existingActionInitializer)) {
2929
+ const conditionalsProperty2 = existingActionInitializer.getProperty(
2930
+ CONDITIONALS_PROPERTY_NAME
2931
+ );
2932
+ if (conditionalsProperty2) {
2933
+ conditionalsProperty2.remove();
2934
+ console.log(
2935
+ ` [${relPath}] Removed deprecated 'conditionals' from 'action' on workqueue '${workqueueLabel}'`
2936
+ );
2937
+ }
2938
+ if (isUnsupportedActionType(existingActionInitializer)) {
2939
+ existingActionProperty.remove();
2940
+ console.log(
2941
+ ` [${relPath}] Removed unsupported 'action' type on workqueue '${workqueueLabel}'`
2942
+ );
2943
+ }
2944
+ }
2945
+ }
2946
+ actionsProperty.remove();
2947
+ console.log(
2948
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' (existing 'action' kept)`
2949
+ );
2950
+ return 1;
2951
+ }
2952
+ const actionCandidates = actionsInitializer.getElements().filter(
2953
+ (element) => import_ts_morph13.Node.isObjectLiteralExpression(element)
2954
+ );
2955
+ if (actionCandidates.length === 0) {
2956
+ actionsProperty.remove();
2957
+ console.log(
2958
+ ` [${relPath}] Removed empty 'actions' from workqueue '${workqueueLabel}'`
2959
+ );
2960
+ return 1;
2961
+ }
2962
+ if (actionCandidates.length > 1) {
2963
+ const droppedCount = actionCandidates.length - 1;
2964
+ console.warn(
2965
+ ` [${relPath}] Workqueue '${workqueueLabel}' has ${actionCandidates.length} actions; keeping first as 'action' and dropping ${droppedCount} extra action(s)`
2966
+ );
2967
+ }
2968
+ const conditionalsProperty = actionCandidates[0].getProperty(
2969
+ CONDITIONALS_PROPERTY_NAME
2970
+ );
2971
+ if (conditionalsProperty) {
2972
+ conditionalsProperty.remove();
2973
+ console.log(
2974
+ ` [${relPath}] Removed deprecated 'conditionals' from migrated 'action' on workqueue '${workqueueLabel}'`
2975
+ );
2976
+ }
2977
+ if (isUnsupportedActionType(actionCandidates[0])) {
2978
+ actionsProperty.remove();
2979
+ console.log(
2980
+ ` [${relPath}] Removed deprecated 'actions' from workqueue '${workqueueLabel}' because action type is unsupported`
2981
+ );
2982
+ return 1;
2983
+ }
2984
+ const firstActionText = actionCandidates[0].getText();
2985
+ workqueue.addPropertyAssignment({
2986
+ name: ACTION_PROPERTY_NAME2,
2987
+ initializer: firstActionText
2988
+ });
2989
+ actionsProperty.remove();
2990
+ console.log(
2991
+ ` [${relPath}] Replaced 'actions' with 'action' on workqueue '${workqueueLabel}'`
2992
+ );
2993
+ return 1;
2994
+ }
2995
+ function processFile11(filePath, project) {
2996
+ const sourceFile = project.getSourceFile(filePath);
2997
+ if (!sourceFile) return 0;
2998
+ let migratedWorkqueues = 0;
2999
+ const relPath = import_path13.default.relative(getCwd(), filePath);
3000
+ const callExpressions = sourceFile.getDescendantsOfKind(
3001
+ import_ts_morph13.SyntaxKind.CallExpression
3002
+ );
3003
+ for (const call of callExpressions) {
3004
+ const expression = call.getExpression();
3005
+ if (!import_ts_morph13.Node.isIdentifier(expression) || expression.getText() !== DEFINE_WORKQUEUES_NAME3) {
3006
+ continue;
3007
+ }
3008
+ const args = call.getArguments();
3009
+ if (args.length === 0) continue;
3010
+ const workqueuesArg = args[0];
3011
+ if (!import_ts_morph13.Node.isArrayLiteralExpression(workqueuesArg)) continue;
3012
+ for (const element of workqueuesArg.getElements()) {
3013
+ if (!import_ts_morph13.Node.isObjectLiteralExpression(element)) continue;
3014
+ migratedWorkqueues += migrateWorkqueueActions(element, relPath);
3015
+ }
3016
+ }
3017
+ return migratedWorkqueues;
3018
+ }
3019
+ async function main13() {
3020
+ const srcDir = import_path13.default.join(getCwd(), "src");
3021
+ console.log(`Scanning for defineWorkqueues calls in: ${srcDir}
3022
+ `);
3023
+ const project = new import_ts_morph13.Project({
3024
+ tsConfigFilePath: import_path13.default.resolve(srcDir, "../tsconfig.json"),
3025
+ skipAddingFilesFromTsConfig: false
3026
+ });
3027
+ const sourceFiles = project.getSourceFiles().filter((sf) => {
3028
+ const fp = sf.getFilePath();
3029
+ return fp.includes("/src/") && !fp.includes("/node_modules/");
3030
+ });
3031
+ console.log(`Found ${sourceFiles.length} source file(s) to analyse.
3032
+ `);
3033
+ let totalMigrated = 0;
3034
+ const modifiedFiles = [];
3035
+ for (const sourceFile of sourceFiles) {
3036
+ const filePath = sourceFile.getFilePath();
3037
+ const migrated = processFile11(filePath, project);
3038
+ if (migrated > 0) {
3039
+ totalMigrated += migrated;
3040
+ modifiedFiles.push(filePath);
3041
+ }
3042
+ }
3043
+ if (modifiedFiles.length === 0) {
3044
+ console.log(
3045
+ "No deprecated workqueue 'actions' arrays found inside defineWorkqueues calls. Nothing to do."
3046
+ );
3047
+ return;
3048
+ }
3049
+ console.log(`
3050
+ Saving ${modifiedFiles.length} modified file(s)...`);
3051
+ for (const filePath of modifiedFiles) {
3052
+ const sourceFile = project.getSourceFileOrThrow(filePath);
3053
+ await sourceFile.save();
3054
+ console.log(` Saved: ${import_path13.default.relative(getCwd(), filePath)}`);
3055
+ }
3056
+ console.log(
3057
+ `
3058
+ Done. Migrated ${totalMigrated} deprecated workqueue 'actions' definition(s) to 'action'.`
3059
+ );
3060
+ }
3061
+
3062
+ // src/migrations/v2.0/remove-demo-scope.ts
3063
+ var import_path14 = __toESM(require("path"));
3064
+ var import_ts_morph14 = require("ts-morph");
3065
+ var ROLES_HANDLER_RELATIVE_PATH = "src/data-seeding/roles/handler.ts";
3066
+ async function main14() {
3067
+ const rolesHandlerPath = import_path14.default.join(getCwd(), ROLES_HANDLER_RELATIVE_PATH);
3068
+ const project = new import_ts_morph14.Project({
3069
+ tsConfigFilePath: import_path14.default.resolve(getCwd(), "tsconfig.json"),
3070
+ skipAddingFilesFromTsConfig: false
3071
+ });
3072
+ const sourceFile = project.getSourceFile(rolesHandlerPath);
3073
+ if (!sourceFile) {
3074
+ console.log(
3075
+ `No roles handler found at '${ROLES_HANDLER_RELATIVE_PATH}'. Nothing to do.`
3076
+ );
3077
+ return;
3078
+ }
3079
+ let changed = false;
3080
+ const constantsImport = sourceFile.getImportDeclaration(
3081
+ (decl) => decl.getModuleSpecifierValue() === "@countryconfig/constants"
3082
+ );
3083
+ if (constantsImport) {
3084
+ constantsImport.remove();
3085
+ changed = true;
3086
+ }
3087
+ const rolesHandler = sourceFile.getFunction("rolesHandler");
3088
+ if (!rolesHandler) {
3089
+ console.log(
3090
+ `No rolesHandler export found in '${ROLES_HANDLER_RELATIVE_PATH}'. Nothing to do.`
3091
+ );
3092
+ return;
3093
+ }
3094
+ const secondParam = rolesHandler.getParameters()[1];
3095
+ const secondParamName = secondParam?.getName();
3096
+ const responseToolkitIdentifier = secondParamName || "h";
3097
+ const currentBodyText = rolesHandler.getBodyText();
3098
+ const normalizedCurrent = currentBodyText?.replace(/\s+/g, " ").trim() ?? "";
3099
+ const normalizedDesired = `return ${responseToolkitIdentifier}.response(roles)`;
3100
+ if (normalizedCurrent !== normalizedDesired) {
3101
+ rolesHandler.setBodyText(`return ${responseToolkitIdentifier}.response(roles)`);
3102
+ changed = true;
3103
+ }
3104
+ if (!changed) {
3105
+ console.log(
3106
+ `No changes needed in '${ROLES_HANDLER_RELATIVE_PATH}'.`
3107
+ );
3108
+ return;
3109
+ }
3110
+ await sourceFile.save();
3111
+ console.log(
3112
+ `Updated '${ROLES_HANDLER_RELATIVE_PATH}' to remove demo scope behavior while preserving file structure.`
3113
+ );
3114
+ }
3115
+
3116
+ // src/migrations/v2.0/remove-hearth-migrations.ts
3117
+ var fs2 = __toESM(require("fs"));
3118
+ var import_path15 = __toESM(require("path"));
3119
+ var PATHS_TO_REMOVE = [
3120
+ {
3121
+ relativePath: "src/migrations/hearth",
3122
+ label: "Hearth migrations directory"
3123
+ },
3124
+ {
3125
+ relativePath: "src/migrations/user-mgnt",
3126
+ label: "user-mgnt migrations directory"
3127
+ },
3128
+ { relativePath: "src/utils/hearth-helpers.ts", label: "Hearth helpers file" }
3129
+ ];
3130
+ async function main15() {
3131
+ for (const { relativePath, label } of PATHS_TO_REMOVE) {
3132
+ const absolutePath = import_path15.default.join(getCwd(), relativePath);
3133
+ if (fs2.existsSync(absolutePath)) {
3134
+ fs2.rmSync(absolutePath, { recursive: true, force: true });
3135
+ console.log(`Removed ${label} '${relativePath}'.`);
3136
+ } else {
3137
+ console.log(`No ${label} found at '${relativePath}'.`);
3138
+ }
3139
+ }
3140
+ }
3141
+
3142
+ // src/migrations/v2.0/create-events-index.ts
3143
+ var import_ts_morph15 = require("ts-morph");
3144
+ var import_fs = __toESM(require("fs"));
3145
+ var import_path16 = __toESM(require("path"));
3146
+ var DEFINE_CONFIG_NAME5 = "defineConfig";
3147
+ var HANDLER_FUNCTION_NAMES = /* @__PURE__ */ new Set([
3148
+ "getCustomEventsHandler",
3149
+ "getEventsHandler"
3150
+ ]);
3151
+ var EVENT_CONFIGS_IDENTIFIER = "eventConfigs";
3152
+ var EVENTS_INDEX_IMPORT_PATH = "@countryconfig/events";
3153
+ var RESPONSE_METHOD_NAME = "response";
3154
+ var LICENSE_HEADER = `/*
3155
+ * This Source Code Form is subject to the terms of the Mozilla Public
3156
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
3157
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
3158
+ *
3159
+ * OpenCRVS is also distributed under the terms of the Civil Registration
3160
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
3161
+ *
3162
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
3163
+ */
3164
+ `;
3165
+ function findEventConfigExports(project, srcDir) {
3166
+ const found = [];
3167
+ const eventsIndexAbs = import_path16.default.join(srcDir, "events", "index.ts");
3168
+ for (const sourceFile of project.getSourceFiles()) {
3169
+ const filePath = sourceFile.getFilePath();
3170
+ if (!filePath.startsWith(srcDir) || filePath.includes("/node_modules/")) {
3171
+ continue;
3172
+ }
3173
+ if (filePath === eventsIndexAbs) continue;
3174
+ for (const statement of sourceFile.getVariableStatements()) {
3175
+ if (!statement.hasExportKeyword()) continue;
3176
+ for (const decl of statement.getDeclarations()) {
3177
+ const initializer = decl.getInitializer();
3178
+ if (!initializer) continue;
3179
+ const unwrapped = import_ts_morph15.Node.isAsExpression(initializer) ? initializer.getExpression() : initializer;
3180
+ if (!import_ts_morph15.Node.isCallExpression(unwrapped)) continue;
3181
+ const callee = unwrapped.getExpression();
3182
+ if (!import_ts_morph15.Node.isIdentifier(callee)) continue;
3183
+ if (callee.getText() !== DEFINE_CONFIG_NAME5) continue;
3184
+ found.push({ name: decl.getName(), filePath });
3185
+ }
3186
+ }
3187
+ }
3188
+ return found;
3189
+ }
3190
+ function buildIndexImportSpecifier(eventConfigFilePath, srcDir) {
3191
+ const eventsIndexDir = import_path16.default.join(srcDir, "events");
3192
+ let rel = import_path16.default.relative(eventsIndexDir, eventConfigFilePath).split(import_path16.default.sep).join("/");
3193
+ if (rel.endsWith(".ts")) rel = rel.slice(0, -".ts".length);
3194
+ if (rel.endsWith("/index")) rel = rel.slice(0, -"/index".length);
3195
+ if (!rel.startsWith(".")) rel = "./" + rel;
3196
+ return rel;
3197
+ }
3198
+ function buildEventsIndexSource(exports, srcDir) {
3199
+ const imports = exports.map(
3200
+ (e) => `import { ${e.name} } from '${buildIndexImportSpecifier(
3201
+ e.filePath,
3202
+ srcDir
3203
+ )}'`
3204
+ ).join("\n");
3205
+ const array3 = `export const ${EVENT_CONFIGS_IDENTIFIER} = [${exports.map((e) => e.name).join(", ")}]`;
3206
+ return `${LICENSE_HEADER}${imports}
3207
+
3208
+ ${array3}
3209
+ `;
3210
+ }
3211
+ function findHandlerSourceFile(project, srcDir) {
3212
+ for (const sf of project.getSourceFiles()) {
3213
+ const fp = sf.getFilePath();
3214
+ if (!fp.startsWith(srcDir) || fp.includes("/node_modules/")) continue;
3215
+ for (const fn of sf.getFunctions()) {
3216
+ const name = fn.getName();
3217
+ if (name && HANDLER_FUNCTION_NAMES.has(name)) return sf;
3218
+ }
3219
+ for (const statement of sf.getVariableStatements()) {
3220
+ for (const decl of statement.getDeclarations()) {
3221
+ if (HANDLER_FUNCTION_NAMES.has(decl.getName())) return sf;
3222
+ }
3223
+ }
3224
+ }
3225
+ return void 0;
3226
+ }
3227
+ function modifyHandler(sourceFile, exportNames) {
3228
+ const changes = [];
3229
+ for (const importDecl of [...sourceFile.getImportDeclarations()]) {
3230
+ const namedImports = importDecl.getNamedImports();
3231
+ if (namedImports.length === 0) continue;
3232
+ const matched = namedImports.filter((ni) => exportNames.has(ni.getName()));
3233
+ if (matched.length === 0) continue;
3234
+ const removedNames = matched.map((ni) => ni.getName());
3235
+ for (const ni of matched) ni.remove();
3236
+ changes.push(`removed direct imports: ${removedNames.join(", ")}`);
3237
+ const stillUsed = importDecl.getNamedImports().length > 0 || importDecl.getDefaultImport() || importDecl.getNamespaceImport();
3238
+ if (!stillUsed) importDecl.remove();
3239
+ }
3240
+ for (const statement of [...sourceFile.getVariableStatements()]) {
3241
+ if (!statement.hasExportKeyword()) continue;
3242
+ const hasEventConfigs = statement.getDeclarations().some((d) => d.getName() === EVENT_CONFIGS_IDENTIFIER);
3243
+ if (hasEventConfigs) {
3244
+ statement.remove();
3245
+ changes.push(`removed inline 'export const ${EVENT_CONFIGS_IDENTIFIER}'`);
3246
+ }
3247
+ }
3248
+ const existing = sourceFile.getImportDeclaration(
3249
+ (imp) => imp.getModuleSpecifierValue() === EVENTS_INDEX_IMPORT_PATH
3250
+ );
3251
+ if (existing) {
3252
+ const already = existing.getNamedImports().some((ni) => ni.getName() === EVENT_CONFIGS_IDENTIFIER);
3253
+ if (!already) {
3254
+ existing.addNamedImport(EVENT_CONFIGS_IDENTIFIER);
3255
+ changes.push(
3256
+ `added '${EVENT_CONFIGS_IDENTIFIER}' to existing import from '${EVENTS_INDEX_IMPORT_PATH}'`
3257
+ );
3258
+ }
3259
+ } else {
3260
+ sourceFile.addImportDeclaration({
3261
+ moduleSpecifier: EVENTS_INDEX_IMPORT_PATH,
3262
+ namedImports: [EVENT_CONFIGS_IDENTIFIER]
3263
+ });
3264
+ changes.push(
3265
+ `added import { ${EVENT_CONFIGS_IDENTIFIER} } from '${EVENTS_INDEX_IMPORT_PATH}'`
3266
+ );
3267
+ }
3268
+ for (const call of sourceFile.getDescendantsOfKind(
3269
+ import_ts_morph15.SyntaxKind.CallExpression
3270
+ )) {
3271
+ const callee = call.getExpression();
3272
+ if (!import_ts_morph15.Node.isPropertyAccessExpression(callee)) continue;
3273
+ if (callee.getName() !== RESPONSE_METHOD_NAME) continue;
3274
+ const args = call.getArguments();
3275
+ if (args.length !== 1) continue;
3276
+ const [arg] = args;
3277
+ if (!import_ts_morph15.Node.isArrayLiteralExpression(arg)) continue;
3278
+ if (arg.getElements().length === 0) continue;
3279
+ if (!arg.getElements().every((el) => import_ts_morph15.Node.isIdentifier(el))) continue;
3280
+ arg.replaceWithText(EVENT_CONFIGS_IDENTIFIER);
3281
+ changes.push(
3282
+ `rewrote h.response([...]) \u2192 h.response(${EVENT_CONFIGS_IDENTIFIER})`
3283
+ );
3284
+ }
3285
+ return changes;
3286
+ }
3287
+ async function main16() {
3288
+ const cwd2 = getCwd();
3289
+ const srcDir = import_path16.default.join(cwd2, "src");
3290
+ console.log(`Scanning for defineConfig event exports in: ${srcDir}
3291
+ `);
3292
+ const project = new import_ts_morph15.Project({
3293
+ tsConfigFilePath: import_path16.default.resolve(srcDir, "../tsconfig.json"),
3294
+ skipAddingFilesFromTsConfig: false
3295
+ });
3296
+ const eventConfigExports = findEventConfigExports(project, srcDir);
3297
+ if (eventConfigExports.length === 0) {
3298
+ console.log(
3299
+ "No top-level `export const X = defineConfig(...)` declarations found. Nothing to do."
3300
+ );
3301
+ return;
3302
+ }
3303
+ console.log(`Found ${eventConfigExports.length} event config export(s):`);
3304
+ for (const e of eventConfigExports) {
3305
+ console.log(` ${e.name} \u2190 ${import_path16.default.relative(cwd2, e.filePath)}`);
3306
+ }
3307
+ const eventsIndexAbs = import_path16.default.join(srcDir, "events", "index.ts");
3308
+ const eventsIndexRel = import_path16.default.relative(cwd2, eventsIndexAbs);
3309
+ if (import_fs.default.existsSync(eventsIndexAbs)) {
3310
+ console.log(`
3311
+ [${eventsIndexRel}] already exists \u2014 leaving untouched.`);
3312
+ } else {
3313
+ import_fs.default.mkdirSync(import_path16.default.dirname(eventsIndexAbs), { recursive: true });
3314
+ const source = buildEventsIndexSource(eventConfigExports, srcDir);
3315
+ const eventsIndexFile = project.createSourceFile(eventsIndexAbs, source, {
3316
+ overwrite: false
3317
+ });
3318
+ await eventsIndexFile.save();
3319
+ console.log(
3320
+ `
3321
+ [${eventsIndexRel}] created with ${EVENT_CONFIGS_IDENTIFIER} of ${eventConfigExports.length} event(s).`
3322
+ );
3323
+ }
3324
+ const handler = findHandlerSourceFile(project, srcDir);
3325
+ if (!handler) {
3326
+ console.log(
3327
+ `
3328
+ No event-config handler file found (looked for exported function(s): ${Array.from(
3329
+ HANDLER_FUNCTION_NAMES
3330
+ ).join(", ")}). Skipping handler rewrite.`
3331
+ );
3332
+ return;
3333
+ }
3334
+ const handlerRelPath = import_path16.default.relative(cwd2, handler.getFilePath());
3335
+ const exportNameSet = new Set(eventConfigExports.map((e) => e.name));
3336
+ const changes = modifyHandler(handler, exportNameSet);
3337
+ if (changes.length === 0) {
3338
+ console.log(`
3339
+ [${handlerRelPath}] already wired to ${EVENTS_INDEX_IMPORT_PATH} \u2014 no changes.`);
3340
+ return;
3341
+ }
3342
+ for (const c of changes) console.log(` [${handlerRelPath}] ${c}`);
3343
+ await handler.save();
3344
+ console.log(`
3345
+ Saved ${handlerRelPath}.`);
3346
+ }
3347
+
3348
+ // src/migrations/v2.0/checkout-upstream-files.ts
3349
+ var import_child_process = require("child_process");
3350
+ var UPSTREAM_URL = "https://github.com/opencrvs/opencrvs-countryconfig.git";
3351
+ var UPSTREAM_BRANCH = "develop";
3352
+ var TEMP_REMOTE = "opencrvs-upgrade-v19-v20-codemod";
3353
+ var FILES_TO_CHECKOUT = [
3354
+ "infrastructure/postgres/setup-analytics.sh",
3355
+ "src/analytics/analytics.ts"
3356
+ ];
3357
+ function runGit(args, { silent = false } = {}) {
3358
+ return (0, import_child_process.execFileSync)("git", args, {
3359
+ cwd: getCwd(),
3360
+ encoding: "utf8",
3361
+ stdio: silent ? ["ignore", "pipe", "pipe"] : ["ignore", "pipe", "inherit"]
3362
+ });
3363
+ }
3364
+ function tryGit(args) {
3365
+ try {
3366
+ runGit(args, { silent: true });
3367
+ return true;
3368
+ } catch {
3369
+ return false;
3370
+ }
3371
+ }
3372
+ function assertIsGitRepo() {
3373
+ if (!tryGit(["rev-parse", "--is-inside-work-tree"])) {
3374
+ throw new Error(
3375
+ `checkout-upstream-files: ${getCwd()} is not a git repository. Initialise git (or run the upgrade inside a git checkout) before re-running.`
3376
+ );
3377
+ }
3378
+ }
3379
+ async function main17() {
3380
+ console.log(
3381
+ `Checking out ${FILES_TO_CHECKOUT.length} file(s) from ${UPSTREAM_URL}@${UPSTREAM_BRANCH}...
3382
+ `
3383
+ );
3384
+ assertIsGitRepo();
3385
+ tryGit(["remote", "remove", TEMP_REMOTE]);
3386
+ try {
3387
+ console.log(` Adding temporary remote '${TEMP_REMOTE}' \u2192 ${UPSTREAM_URL}`);
3388
+ runGit(["remote", "add", TEMP_REMOTE, UPSTREAM_URL], { silent: true });
3389
+ console.log(` Fetching ${TEMP_REMOTE}/${UPSTREAM_BRANCH} (depth 1)...`);
3390
+ runGit(["fetch", "--depth=1", TEMP_REMOTE, UPSTREAM_BRANCH]);
3391
+ const ref = `${TEMP_REMOTE}/${UPSTREAM_BRANCH}`;
3392
+ const missing = [];
3393
+ let checkedOut = 0;
3394
+ for (const file of FILES_TO_CHECKOUT) {
3395
+ if (tryGit(["checkout", ref, "--", file])) {
3396
+ console.log(` Checked out ${file} from ${ref}`);
3397
+ checkedOut++;
3398
+ } else {
3399
+ console.warn(
3400
+ ` [warn] ${file} not found on ${ref} \u2014 skipping. Verify the path exists on that branch.`
3401
+ );
3402
+ missing.push(file);
3403
+ }
3404
+ }
3405
+ console.log(
3406
+ `
3407
+ Checked out ${checkedOut}/${FILES_TO_CHECKOUT.length} file(s) from ${ref}.`
3408
+ );
3409
+ if (missing.length > 0) {
3410
+ console.warn(` Missing on upstream branch: ${missing.join(", ")}`);
3411
+ }
3412
+ if (checkedOut > 0) {
3413
+ console.log(
3414
+ ` Review the staged changes with: git diff --cached -- ${FILES_TO_CHECKOUT.map(
3415
+ (f) => `'${f}'`
3416
+ ).join(" ")}
3417
+ `
3418
+ );
3419
+ }
3420
+ } finally {
3421
+ if (tryGit(["remote", "remove", TEMP_REMOTE])) {
3422
+ console.log(` Removed temporary remote '${TEMP_REMOTE}'.`);
3423
+ }
3424
+ }
3425
+ }
3426
+
3427
+ // src/migrations/v2.0/simplify-analytics-precalculations.ts
3428
+ var import_ts_morph16 = require("ts-morph");
3429
+ var import_fs2 = __toESM(require("fs"));
3430
+ var import_path17 = __toESM(require("path"));
3431
+ var ANALYTICS_FILE_REL = "src/analytics/analytics.ts";
3432
+ var FUNCTION_NAME = "precalculateAdditionalAnalytics";
3433
+ var IMPORT_NAMES_TO_REMOVE = /* @__PURE__ */ new Set(["Event", "precalculateBirthEvent"]);
3434
+ var RETURN_EXPRESSION_TEXT = "declaration";
3435
+ function removeTargetedNamedImports(sourceFile) {
3436
+ const log = [];
3437
+ for (const importDecl of [...sourceFile.getImportDeclarations()]) {
3438
+ const namedImports = importDecl.getNamedImports();
3439
+ if (namedImports.length === 0) continue;
3440
+ const matched = namedImports.filter(
3441
+ (ni) => IMPORT_NAMES_TO_REMOVE.has(ni.getName())
3442
+ );
3443
+ if (matched.length === 0) continue;
3444
+ const removedNames = matched.map((ni) => ni.getName());
3445
+ for (const ni of matched) ni.remove();
3446
+ log.push(
3447
+ `removed import(s) ${removedNames.join(", ")} from '${importDecl.getModuleSpecifierValue()}'`
3448
+ );
3449
+ const stillUsed = importDecl.getNamedImports().length > 0 || importDecl.getDefaultImport() || importDecl.getNamespaceImport();
3450
+ if (!stillUsed) importDecl.remove();
3451
+ }
3452
+ return log;
3453
+ }
3454
+ function findPrecalculateFunction(sourceFile) {
3455
+ for (const fn of sourceFile.getFunctions()) {
3456
+ if (fn.getName() === FUNCTION_NAME) return fn;
3457
+ }
3458
+ for (const statement of sourceFile.getVariableStatements()) {
3459
+ for (const decl of statement.getDeclarations()) {
3460
+ if (decl.getName() === FUNCTION_NAME) return decl;
3461
+ }
3462
+ }
3463
+ return void 0;
3464
+ }
3465
+ function getFunctionBodyBlock(fn) {
3466
+ if (import_ts_morph16.Node.isFunctionDeclaration(fn)) return fn.getBody();
3467
+ const initializer = fn.getInitializer();
3468
+ if (!initializer) return void 0;
3469
+ if (!import_ts_morph16.Node.isArrowFunction(initializer) && !import_ts_morph16.Node.isFunctionExpression(initializer)) {
3470
+ return void 0;
3471
+ }
3472
+ return initializer.getBody();
3473
+ }
3474
+ function simplifyPrecalculateFunction(sourceFile) {
3475
+ const log = [];
3476
+ const fn = findPrecalculateFunction(sourceFile);
3477
+ if (!fn) return log;
3478
+ const body = getFunctionBodyBlock(fn);
3479
+ if (!body || !import_ts_morph16.Node.isBlock(body)) return log;
3480
+ for (const statement of [...body.getStatements()]) {
3481
+ const references = statement.getDescendantsOfKind(import_ts_morph16.SyntaxKind.Identifier).some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
3482
+ if (references) {
3483
+ statement.remove();
3484
+ log.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
3485
+ }
3486
+ }
3487
+ const remaining = body.getStatements();
3488
+ const last = remaining[remaining.length - 1];
3489
+ const alreadyCorrect = last && import_ts_morph16.Node.isReturnStatement(last) && last.getExpression()?.getText() === RETURN_EXPRESSION_TEXT;
3490
+ if (!alreadyCorrect) {
3491
+ body.addStatements(`return ${RETURN_EXPRESSION_TEXT}`);
3492
+ log.push(
3493
+ `ensured '${FUNCTION_NAME}' ends with 'return ${RETURN_EXPRESSION_TEXT}'`
3494
+ );
3495
+ }
3496
+ return log;
3497
+ }
3498
+ async function main18() {
3499
+ const cwd2 = getCwd();
3500
+ const absPath = import_path17.default.join(cwd2, ANALYTICS_FILE_REL);
3501
+ if (!import_fs2.default.existsSync(absPath)) {
3502
+ console.log(
3503
+ `[${ANALYTICS_FILE_REL}] does not exist \u2014 nothing to clean up.`
3504
+ );
3505
+ return;
3506
+ }
3507
+ const project = new import_ts_morph16.Project({
3508
+ tsConfigFilePath: import_path17.default.resolve(cwd2, "tsconfig.json"),
3509
+ skipAddingFilesFromTsConfig: false
3510
+ });
3511
+ const sourceFile = project.getSourceFile(absPath);
3512
+ if (!sourceFile) {
3513
+ console.log(
3514
+ `[${ANALYTICS_FILE_REL}] is not part of the tsconfig project. Skipping.`
3515
+ );
3516
+ return;
3517
+ }
3518
+ console.log(`Cleaning up ${ANALYTICS_FILE_REL}...
3519
+ `);
3520
+ const importLogs = removeTargetedNamedImports(sourceFile);
3521
+ const fnLogs = simplifyPrecalculateFunction(sourceFile);
3522
+ const allLogs = [...importLogs, ...fnLogs];
3523
+ if (allLogs.length === 0) {
3524
+ console.log(`[${ANALYTICS_FILE_REL}] already clean \u2014 nothing to do.`);
3525
+ return;
3526
+ }
3527
+ for (const log of allLogs) {
3528
+ console.log(` [${ANALYTICS_FILE_REL}] ${log}`);
3529
+ }
3530
+ await sourceFile.save();
3531
+ console.log(`
3532
+ Saved ${ANALYTICS_FILE_REL}.`);
3533
+ }
3534
+
2330
3535
  // src/migrations/v2.0/index.ts
2331
3536
  var cwd;
2332
3537
  function getCwd() {
@@ -2346,6 +3551,7 @@ async function runUpgrade(ccwd) {
2346
3551
  );
2347
3552
  cwd = process.cwd();
2348
3553
  }
3554
+ await main13();
2349
3555
  await main();
2350
3556
  await main2();
2351
3557
  await main3();
@@ -2358,4 +3564,9 @@ async function runUpgrade(ccwd) {
2358
3564
  await main10();
2359
3565
  await main11();
2360
3566
  await main12();
3567
+ await main14();
3568
+ await main15();
3569
+ await main16();
3570
+ await main17();
3571
+ await main18();
2361
3572
  }