@opencrvs/toolkit 1.9.12-rc.8a4bacb → 1.9.12-rc.8c751a0

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.
@@ -1826,9 +1826,9 @@ function updateRouteHandlers(sourceFiles, group, srcDir, relCwd) {
1826
1826
  }
1827
1827
  return replacedCount;
1828
1828
  }
1829
- function resolveConfigChain(configObj, path15) {
1829
+ function resolveConfigChain(configObj, path17) {
1830
1830
  let current = configObj;
1831
- for (const key of path15) {
1831
+ for (const key of path17) {
1832
1832
  if (!import_ts_morph10.Node.isObjectLiteralExpression(current)) return null;
1833
1833
  const prop = current.getProperty(key);
1834
1834
  if (!prop || !import_ts_morph10.Node.isPropertyAssignment(prop)) return null;
@@ -3139,6 +3139,399 @@ async function main15() {
3139
3139
  }
3140
3140
  }
3141
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
+
3142
3535
  // src/migrations/v2.0/index.ts
3143
3536
  var cwd;
3144
3537
  function getCwd() {
@@ -3173,4 +3566,7 @@ async function runUpgrade(ccwd) {
3173
3566
  await main12();
3174
3567
  await main14();
3175
3568
  await main15();
3569
+ await main16();
3570
+ await main17();
3571
+ await main18();
3176
3572
  }
@@ -0,0 +1,3 @@
1
+ declare function main(): Promise<void>;
2
+ export { main };
3
+ //# sourceMappingURL=simplify-analytics-precalculations.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"simplify-analytics-precalculations.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.0/simplify-analytics-precalculations.ts"],"names":[],"mappings":"AAuLA,iBAAe,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC,CAyCnC;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
@@ -0,0 +1,196 @@
1
+ "use strict";
2
+ /*
3
+ * This Source Code Form is subject to the terms of the Mozilla Public
4
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
5
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
6
+ *
7
+ * OpenCRVS is also distributed under the terms of the Civil Registration
8
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
9
+ *
10
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
11
+ */
12
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
13
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
14
+ return new (P || (P = Promise))(function (resolve, reject) {
15
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
16
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
17
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
18
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
19
+ });
20
+ };
21
+ var __importDefault = (this && this.__importDefault) || function (mod) {
22
+ return (mod && mod.__esModule) ? mod : { "default": mod };
23
+ };
24
+ Object.defineProperty(exports, "__esModule", { value: true });
25
+ exports.main = main;
26
+ /**
27
+ * Codemod: Clean up `src/analytics/analytics.ts` by removing the Farajaland
28
+ * sample precalculation wiring.
29
+ *
30
+ * Usage:
31
+ * ts-node -r tsconfig-paths/register src/migrations/v2.0/simplify-analytics-precalculations.ts
32
+ *
33
+ * Runs LAST, after `checkout-upstream-files` has replaced
34
+ * `src/analytics/analytics.ts` with the upstream v2.0 version. That upstream
35
+ * version hardcodes a Farajaland-specific birth-event precalculation (it
36
+ * imports `Event` and `precalculateBirthEvent`), which countries implementing
37
+ * their own flows don't want. This codemod strips that out so each country
38
+ * starts from a clean placeholder.
39
+ *
40
+ * What it does (only to `src/analytics/analytics.ts`, if present):
41
+ * 1. Removes the named imports `Event` and `precalculateBirthEvent`.
42
+ * If an import declaration becomes empty it is removed entirely.
43
+ * 2. Rewrites the body of `precalculateAdditionalAnalytics` so it contains
44
+ * nothing but `return declaration` — i.e. every statement that
45
+ * references `Event` or `precalculateBirthEvent` is dropped, and a
46
+ * `return declaration` is ensured at the end.
47
+ *
48
+ * The codemod is safe to re-run: if the imports are already gone and the
49
+ * function body is already `return declaration`, it is a no-op.
50
+ */
51
+ const ts_morph_1 = require("ts-morph");
52
+ const fs_1 = __importDefault(require("fs"));
53
+ const path_1 = __importDefault(require("path"));
54
+ const _1 = require(".");
55
+ const ANALYTICS_FILE_REL = 'src/analytics/analytics.ts';
56
+ const FUNCTION_NAME = 'precalculateAdditionalAnalytics';
57
+ const IMPORT_NAMES_TO_REMOVE = new Set(['Event', 'precalculateBirthEvent']);
58
+ const RETURN_EXPRESSION_TEXT = 'declaration';
59
+ // ─── Import cleanup ──────────────────────────────────────────────────────────
60
+ /**
61
+ * Removes every named import in `sourceFile` whose local binding name is in
62
+ * `IMPORT_NAMES_TO_REMOVE`. If a given import declaration is left with no
63
+ * named imports, default import or namespace import, the declaration itself
64
+ * is removed.
65
+ */
66
+ function removeTargetedNamedImports(sourceFile) {
67
+ const log = [];
68
+ for (const importDecl of [...sourceFile.getImportDeclarations()]) {
69
+ const namedImports = importDecl.getNamedImports();
70
+ if (namedImports.length === 0)
71
+ continue;
72
+ const matched = namedImports.filter((ni) => IMPORT_NAMES_TO_REMOVE.has(ni.getName()));
73
+ if (matched.length === 0)
74
+ continue;
75
+ const removedNames = matched.map((ni) => ni.getName());
76
+ for (const ni of matched)
77
+ ni.remove();
78
+ log.push(`removed import(s) ${removedNames.join(', ')} from '${importDecl.getModuleSpecifierValue()}'`);
79
+ const stillUsed = importDecl.getNamedImports().length > 0 ||
80
+ importDecl.getDefaultImport() ||
81
+ importDecl.getNamespaceImport();
82
+ if (!stillUsed)
83
+ importDecl.remove();
84
+ }
85
+ return log;
86
+ }
87
+ // ─── Function-body cleanup ───────────────────────────────────────────────────
88
+ /**
89
+ * Returns the `precalculateAdditionalAnalytics` declaration in `sourceFile`,
90
+ * whether it was written as `function precalculateAdditionalAnalytics(...)` or
91
+ * as `const precalculateAdditionalAnalytics = (...) => { ... }`.
92
+ */
93
+ function findPrecalculateFunction(sourceFile) {
94
+ for (const fn of sourceFile.getFunctions()) {
95
+ if (fn.getName() === FUNCTION_NAME)
96
+ return fn;
97
+ }
98
+ for (const statement of sourceFile.getVariableStatements()) {
99
+ for (const decl of statement.getDeclarations()) {
100
+ if (decl.getName() === FUNCTION_NAME)
101
+ return decl;
102
+ }
103
+ }
104
+ return undefined;
105
+ }
106
+ /**
107
+ * Returns the block body of a function declaration or variable-declared arrow
108
+ * / function expression, or undefined if the function has an expression body
109
+ * or doesn't exist.
110
+ */
111
+ function getFunctionBodyBlock(fn) {
112
+ if (ts_morph_1.Node.isFunctionDeclaration(fn))
113
+ return fn.getBody();
114
+ const initializer = fn.getInitializer();
115
+ if (!initializer)
116
+ return undefined;
117
+ if (!ts_morph_1.Node.isArrowFunction(initializer) &&
118
+ !ts_morph_1.Node.isFunctionExpression(initializer)) {
119
+ return undefined;
120
+ }
121
+ return initializer.getBody();
122
+ }
123
+ /**
124
+ * Rewrites the body of `precalculateAdditionalAnalytics` so that the only
125
+ * statement is `return declaration`. Any statement whose subtree references
126
+ * the removed imports (`Event`, `precalculateBirthEvent`) is dropped; a
127
+ * trailing `return declaration` is ensured.
128
+ */
129
+ function simplifyPrecalculateFunction(sourceFile) {
130
+ var _a;
131
+ const log = [];
132
+ const fn = findPrecalculateFunction(sourceFile);
133
+ if (!fn)
134
+ return log;
135
+ const body = getFunctionBodyBlock(fn);
136
+ if (!body || !ts_morph_1.Node.isBlock(body))
137
+ return log;
138
+ // Drop every statement (not just `if`s) whose AST references an identifier
139
+ // in IMPORT_NAMES_TO_REMOVE. This handles both the upstream shape
140
+ // if (eventConfig.id === Event.Birth) return precalculateBirthEvent(...)
141
+ // and any equivalent variant a country might have typed.
142
+ for (const statement of [...body.getStatements()]) {
143
+ const references = statement
144
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.Identifier)
145
+ .some((id) => IMPORT_NAMES_TO_REMOVE.has(id.getText()));
146
+ if (references) {
147
+ statement.remove();
148
+ log.push(`removed statement in ${FUNCTION_NAME} referencing removed imports`);
149
+ }
150
+ }
151
+ // Ensure the function ends with `return declaration`. If nothing changed
152
+ // and the body already ends correctly, this is a no-op.
153
+ const remaining = body.getStatements();
154
+ const last = remaining[remaining.length - 1];
155
+ const alreadyCorrect = last &&
156
+ ts_morph_1.Node.isReturnStatement(last) &&
157
+ ((_a = last.getExpression()) === null || _a === void 0 ? void 0 : _a.getText()) === RETURN_EXPRESSION_TEXT;
158
+ if (!alreadyCorrect) {
159
+ body.addStatements(`return ${RETURN_EXPRESSION_TEXT}`);
160
+ log.push(`ensured '${FUNCTION_NAME}' ends with 'return ${RETURN_EXPRESSION_TEXT}'`);
161
+ }
162
+ return log;
163
+ }
164
+ // ─── Entry point ─────────────────────────────────────────────────────────────
165
+ function main() {
166
+ return __awaiter(this, void 0, void 0, function* () {
167
+ const cwd = (0, _1.getCwd)();
168
+ const absPath = path_1.default.join(cwd, ANALYTICS_FILE_REL);
169
+ if (!fs_1.default.existsSync(absPath)) {
170
+ console.log(`[${ANALYTICS_FILE_REL}] does not exist — nothing to clean up.`);
171
+ return;
172
+ }
173
+ const project = new ts_morph_1.Project({
174
+ tsConfigFilePath: path_1.default.resolve(cwd, 'tsconfig.json'),
175
+ skipAddingFilesFromTsConfig: false
176
+ });
177
+ const sourceFile = project.getSourceFile(absPath);
178
+ if (!sourceFile) {
179
+ console.log(`[${ANALYTICS_FILE_REL}] is not part of the tsconfig project. Skipping.`);
180
+ return;
181
+ }
182
+ console.log(`Cleaning up ${ANALYTICS_FILE_REL}...\n`);
183
+ const importLogs = removeTargetedNamedImports(sourceFile);
184
+ const fnLogs = simplifyPrecalculateFunction(sourceFile);
185
+ const allLogs = [...importLogs, ...fnLogs];
186
+ if (allLogs.length === 0) {
187
+ console.log(`[${ANALYTICS_FILE_REL}] already clean — nothing to do.`);
188
+ return;
189
+ }
190
+ for (const log of allLogs) {
191
+ console.log(` [${ANALYTICS_FILE_REL}] ${log}`);
192
+ }
193
+ yield sourceFile.save();
194
+ console.log(`\nSaved ${ANALYTICS_FILE_REL}.`);
195
+ });
196
+ }
@@ -1992,7 +1992,7 @@ var LocationInput = BaseField.extend({
1992
1992
  configuration: import_v43.default.object({
1993
1993
  locationTypes: import_v43.default.array(import_v43.default.string()).optional().describe("Types of the locations that are available for selection."),
1994
1994
  allowedLocations: AllowedLocations
1995
- })
1995
+ }).optional()
1996
1996
  }).describe("Input field for a location");
1997
1997
  var FileUploadWithOptions = BaseField.extend({
1998
1998
  type: import_v43.default.literal(FieldType.FILE_WITH_OPTIONS),
@@ -3661,6 +3661,9 @@ var _EventConfigBase = z33.object({
3661
3661
  ),
3662
3662
  flags: z33.array(FlagConfig).optional().default([]).describe(
3663
3663
  "Configuration of flags associated with the actions of this event type."
3664
+ ),
3665
+ analytics: z33.boolean().optional().default(true).describe(
3666
+ "Indicates whether the records of this event type are included in analytics"
3664
3667
  )
3665
3668
  });
3666
3669
  var EventConfig = _EventConfigBase.superRefine((event2, ctx) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opencrvs/toolkit",
3
- "version": "1.9.12-rc.8a4bacb",
3
+ "version": "1.9.12-rc.8c751a0",
4
4
  "description": "OpenCRVS toolkit for building country configurations",
5
5
  "license": "MPL-2.0",
6
6
  "bin": {
@@ -1 +1 @@
1
- {"root":["./src/cli.ts","./src/api/index.ts","./src/application-config/index.ts","./src/conditionals/index.ts","./src/events/deduplication.ts","./src/events/index.ts","./src/migrations/v2.0/add-birth-certificate-issuance-flag.ts","./src/migrations/v2.0/convert-config-files-to-ts.ts","./src/migrations/v2.0/convert-paragraph-to-heading.ts","./src/migrations/v2.0/index.ts","./src/migrations/v2.0/make-built-in-validate-actions-custom.ts","./src/migrations/v2.0/migrate-scopes.ts","./src/migrations/v2.0/migrate-validated-workqueue-status-to-flag.ts","./src/migrations/v2.0/migrate-workqueue-configs.ts","./src/migrations/v2.0/remove-delete-actions.ts","./src/migrations/v2.0/remove-demo-scope.ts","./src/migrations/v2.0/remove-deprecated-imports.ts","./src/migrations/v2.0/remove-hearth-migrations.ts","./src/migrations/v2.0/remove-pending-certification-flag.ts","./src/migrations/v2.0/remove-review-from-register-action.ts","./src/migrations/v2.0/rename-api-paths.ts","./src/migrations/v2.0/rename-location-parent-id.ts","./src/notification/index.ts","./src/scopes/index.ts"],"version":"5.6.3"}
1
+ {"root":["./src/cli.ts","./src/api/index.ts","./src/application-config/index.ts","./src/conditionals/index.ts","./src/events/deduplication.ts","./src/events/index.ts","./src/migrations/v2.0/add-birth-certificate-issuance-flag.ts","./src/migrations/v2.0/checkout-upstream-files.ts","./src/migrations/v2.0/convert-config-files-to-ts.ts","./src/migrations/v2.0/convert-paragraph-to-heading.ts","./src/migrations/v2.0/create-events-index.ts","./src/migrations/v2.0/index.ts","./src/migrations/v2.0/make-built-in-validate-actions-custom.ts","./src/migrations/v2.0/migrate-scopes.ts","./src/migrations/v2.0/migrate-validated-workqueue-status-to-flag.ts","./src/migrations/v2.0/migrate-workqueue-configs.ts","./src/migrations/v2.0/remove-delete-actions.ts","./src/migrations/v2.0/remove-demo-scope.ts","./src/migrations/v2.0/remove-deprecated-imports.ts","./src/migrations/v2.0/remove-hearth-migrations.ts","./src/migrations/v2.0/remove-pending-certification-flag.ts","./src/migrations/v2.0/remove-review-from-register-action.ts","./src/migrations/v2.0/rename-api-paths.ts","./src/migrations/v2.0/rename-location-parent-id.ts","./src/migrations/v2.0/simplify-analytics-precalculations.ts","./src/notification/index.ts","./src/scopes/index.ts"],"version":"5.6.3"}