@opencrvs/toolkit 2.1.0-rc.976ee09 → 2.1.0-rc.982e0ae

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 (103) hide show
  1. package/README.md +1 -0
  2. package/build.sh +9 -1
  3. package/create-countryconfig/index.js +284 -62
  4. package/create-countryconfig/node_modules/.bin/degit +21 -0
  5. package/create-countryconfig/package.json +4 -1
  6. package/dist/application-config/index.js +341 -274
  7. package/dist/authentication/index.d.ts +67 -0
  8. package/dist/authentication/index.d.ts.map +1 -0
  9. package/dist/authentication/index.js +750 -0
  10. package/dist/cli.js +1744 -104
  11. package/dist/commons/api/router.d.ts +691 -76
  12. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  13. package/dist/commons/conditionals/validate.d.ts +16 -5
  14. package/dist/commons/events/ActionDocument.d.ts +5 -11
  15. package/dist/commons/events/ActionInput.d.ts +4 -4
  16. package/dist/commons/events/ActionStatus.d.ts +14 -0
  17. package/dist/commons/events/AdvancedSearchConfig.d.ts +24 -0
  18. package/dist/commons/events/AuditLog.d.ts +147 -0
  19. package/dist/commons/events/EventConfig.d.ts +3 -0
  20. package/dist/commons/events/EventDocument.d.ts +470 -2
  21. package/dist/commons/events/EventIndex.d.ts +3 -26
  22. package/dist/commons/events/EventMetadata.d.ts +1 -11
  23. package/dist/commons/events/EventStatus.d.ts +19 -0
  24. package/dist/commons/events/FieldConfig.d.ts +88 -53
  25. package/dist/commons/events/FieldTypeMapping.d.ts +27 -27
  26. package/dist/commons/events/FieldValue.d.ts +2 -2
  27. package/dist/commons/events/Flag.d.ts +42 -0
  28. package/dist/commons/events/PlainDate.d.ts +8 -0
  29. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  30. package/dist/commons/events/WorkqueueConfig.d.ts +17 -14
  31. package/dist/commons/events/event.d.ts +12 -0
  32. package/dist/commons/events/index.d.ts +1 -0
  33. package/dist/commons/events/locationPayloads.d.ts +95 -0
  34. package/dist/commons/events/locations.d.ts +165 -26
  35. package/dist/commons/events/mocks.test.utils.d.ts +30 -0
  36. package/dist/commons/events/test.utils.d.ts +8 -4
  37. package/dist/commons/events/utils.d.ts +2 -2
  38. package/dist/commons/notification/UserNotifications.d.ts +28 -13
  39. package/dist/commons/notification/dispatch.d.ts +10 -0
  40. package/dist/commons/notification/index.d.ts +1 -0
  41. package/dist/conditionals/index.js +328 -58
  42. package/dist/csv.d.ts +25 -0
  43. package/dist/csv.d.ts.map +1 -0
  44. package/dist/csv.js +120 -0
  45. package/dist/environment/index.d.ts +1 -0
  46. package/dist/environment/index.d.ts.map +1 -1
  47. package/dist/environment/index.js +10 -0
  48. package/dist/environment/logger.d.ts +15 -3
  49. package/dist/environment/logger.d.ts.map +1 -1
  50. package/dist/environment/paths.d.ts +7 -0
  51. package/dist/environment/paths.d.ts.map +1 -0
  52. package/dist/environment/paths.js +72 -0
  53. package/dist/environment/questions.d.ts.map +1 -1
  54. package/dist/environment/questions.js +20 -14
  55. package/dist/environment/setup-environment.js +3 -2
  56. package/dist/environment/templates.d.ts.map +1 -1
  57. package/dist/environment/templates.js +2 -1
  58. package/dist/environment/update-workflows.d.ts.map +1 -1
  59. package/dist/environment/update-workflows.js +17 -5
  60. package/dist/environment/upgrade.d.ts +2 -0
  61. package/dist/environment/upgrade.d.ts.map +1 -0
  62. package/dist/environment/upgrade.js +82 -0
  63. package/dist/environment/users.js +11 -13
  64. package/dist/events/index.js +3688 -3293
  65. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
  66. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  67. package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
  68. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  69. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  70. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  71. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  72. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  73. package/dist/migrations/v2.1/add-translations.js +213 -0
  74. package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
  75. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  76. package/dist/migrations/v2.1/enable-telemetry.js +438 -0
  77. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  78. package/dist/migrations/v2.1/index.js +1058 -0
  79. package/dist/notification/index.js +1833 -1426
  80. package/dist/scopes/index.d.ts +327 -32
  81. package/dist/scopes/index.js +329 -58
  82. package/dist/telemetry/index.d.ts +45 -0
  83. package/dist/telemetry/index.d.ts.map +1 -0
  84. package/dist/telemetry/index.js +39 -0
  85. package/dist/templates/charts-values/opencrvs-services/values.yaml +4 -3
  86. package/dist/templates/charts-values/opentelemetry/values.yaml +95 -0
  87. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  88. package/dist/templates/inventory/inventory.template.yml +1 -3
  89. package/dist/translations/check.d.ts +19 -0
  90. package/dist/translations/check.d.ts.map +1 -0
  91. package/dist/translations/check.js +127 -0
  92. package/dist/verify/endpoints.d.ts +2 -0
  93. package/dist/verify/endpoints.d.ts.map +1 -0
  94. package/dist/verify/endpoints.js +345 -0
  95. package/opencrvs-toolkit-2.1.0-rc.982e0ae.tgz +0 -0
  96. package/package.json +11 -5
  97. package/tsconfig.build.json +11 -0
  98. package/tsconfig.build.tsbuildinfo +1 -0
  99. package/tsconfig.json +3 -0
  100. package/dist/templates/inventory/production.example.yml +0 -77
  101. package/dist/templates/inventory/qa.example.yml +0 -48
  102. package/opencrvs-toolkit-2.1.0-rc.976ee09.tgz +0 -0
  103. package/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,213 @@
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.rowsToAdd = rowsToAdd;
26
+ exports.main = main;
27
+ /**
28
+ * Codemod: copy the translation keys core gained this version into this country
29
+ * config.
30
+ *
31
+ * Unlike every other codemod, this one carries no list of what it changes, and
32
+ * should not need editing again. Its input is `client.csv` and `login.csv` from
33
+ * the country config template of the version being upgraded to, fetched from
34
+ * GitHub; whatever rows those files have gained, this adds. A pull request that
35
+ * introduces a translation key therefore only has to add it to the template —
36
+ * `packages/countryconfig-template/src/translations/` — which the
37
+ * check-missing-translation workflow makes it do anyway.
38
+ *
39
+ * `countryconfig.csv` is deliberately left alone. It holds the copy the country
40
+ * config declares itself, which is nobody's business but the country's.
41
+ *
42
+ * Rows are rebuilt against the local file's own columns rather than copied
43
+ * across, so a country config with languages the template does not have keeps
44
+ * its shape: the template's value is used for a language they share, and an
45
+ * empty cell for one it has nothing for.
46
+ */
47
+ const path_1 = __importDefault(require("path"));
48
+ const csv_1 = require("../../csv");
49
+ const REPOSITORY = 'opencrvs/opencrvs-core';
50
+ const TEMPLATE_TRANSLATIONS = 'packages/countryconfig-template/src/translations';
51
+ const APPLICATIONS = ['client', 'login'];
52
+ /** The version this folder upgrades a country config to. */
53
+ const TARGET_VERSION = '2.1';
54
+ const skipped = [];
55
+ function warnSkipped(message) {
56
+ skipped.push(message);
57
+ console.warn(` ⚠️ ${message}`);
58
+ }
59
+ /**
60
+ * The refs matching a prefix, newest patch first.
61
+ *
62
+ * Every patch gets its own release branch — `release/2.1.0`, `release/2.1.1` —
63
+ * and a translation key added in a patch only exists on that patch's branch, so
64
+ * the newest one is the one worth reading.
65
+ */
66
+ function matchingRefs(namespace, prefix) {
67
+ return __awaiter(this, void 0, void 0, function* () {
68
+ const url = `https://api.github.com/repos/${REPOSITORY}/git/matching-refs/${namespace}/${prefix}`;
69
+ const response = yield fetch(url, {
70
+ headers: { accept: 'application/vnd.github+json' }
71
+ });
72
+ /*
73
+ * An empty list and a failed request are not the same thing: GitHub answers
74
+ * 200 with `[]` for a prefix nothing matches, so anything else is the request
75
+ * failing rather than the version having no release branch. Swallowing it
76
+ * would leave `develop` as the only candidate left, and an unauthenticated
77
+ * api.github.com allows 60 requests an hour per IP — a country upgrading from
78
+ * a shared network or a CI runner would quietly get unreleased copy.
79
+ */
80
+ if (!response.ok) {
81
+ throw new Error(`GitHub answered ${response.status} ${response.statusText} for ${url}`);
82
+ }
83
+ const refs = (yield response.json());
84
+ const patchOf = (ref) => Number(ref.split('.').pop()) || 0;
85
+ return refs
86
+ .map(({ ref }) => ref.replace(/^refs\/(heads|tags)\//, ''))
87
+ .sort((a, b) => patchOf(b) - patchOf(a));
88
+ });
89
+ }
90
+ /**
91
+ * Where to read the template from, most specific first: the newest release
92
+ * branch of the target version, then its newest tag, then `develop` for anyone
93
+ * running the codemod before the version has been cut.
94
+ */
95
+ function candidateRefs() {
96
+ return __awaiter(this, void 0, void 0, function* () {
97
+ return [
98
+ ...(yield matchingRefs('heads', `release/${TARGET_VERSION}.`)),
99
+ ...(yield matchingRefs('tags', `v${TARGET_VERSION}.`)),
100
+ 'develop'
101
+ ];
102
+ });
103
+ }
104
+ function fetchTemplate(refs, application) {
105
+ return __awaiter(this, void 0, void 0, function* () {
106
+ for (const ref of refs) {
107
+ const url = `https://raw.githubusercontent.com/${REPOSITORY}/${ref}/${TEMPLATE_TRANSLATIONS}/${application}.csv`;
108
+ const response = yield fetch(url);
109
+ if (response.ok) {
110
+ return { ref, contents: yield response.text() };
111
+ }
112
+ // 404 means this ref does not carry the file and the next one is worth a
113
+ // try. Anything else is the request failing, and moving on would read the
114
+ // template from a ref older than the one that was asked for.
115
+ if (response.status !== 404) {
116
+ throw new Error(`GitHub answered ${response.status} ${response.statusText} for ${url}`);
117
+ }
118
+ }
119
+ warnSkipped(`No ${application}.csv found in the ${TARGET_VERSION} country config template on GitHub; ${application}.csv not updated`);
120
+ return undefined;
121
+ });
122
+ }
123
+ /**
124
+ * The rows of the template that the local file has no id for, expressed in the
125
+ * local file's columns.
126
+ */
127
+ function rowsToAdd(local, template) {
128
+ const localColumns = (0, csv_1.parseCsvLine)(local.header);
129
+ const templateColumns = (0, csv_1.parseCsvLine)(template.header);
130
+ return template.body
131
+ .filter((line) => line !== '')
132
+ .map((line) => {
133
+ const values = (0, csv_1.parseCsvLine)(line);
134
+ return (0, csv_1.toCsvLine)(localColumns.map((column) => {
135
+ var _a;
136
+ const index = templateColumns.indexOf(column);
137
+ return index === -1 ? '' : ((_a = values[index]) !== null && _a !== void 0 ? _a : '');
138
+ }));
139
+ });
140
+ }
141
+ function updateApplication(cwd, refs, application) {
142
+ return __awaiter(this, void 0, void 0, function* () {
143
+ const relativePath = `src/translations/${application}.csv`;
144
+ const local = (0, csv_1.readCsvFile)(path_1.default.join(cwd, relativePath));
145
+ if (!local) {
146
+ warnSkipped(`${relativePath} not found; translations not added`);
147
+ return;
148
+ }
149
+ const fetched = yield fetchTemplate(refs, application);
150
+ if (!fetched) {
151
+ return;
152
+ }
153
+ const template = readTemplate(fetched.contents);
154
+ const added = (0, csv_1.addRows)(local, rowsToAdd(local, template));
155
+ if (added.length === 0) {
156
+ return;
157
+ }
158
+ try {
159
+ (0, csv_1.writeCsvFile)(path_1.default.join(cwd, relativePath), local);
160
+ }
161
+ catch (error) {
162
+ warnSkipped(`Could not write ${relativePath} (${error.message}); translations not added`);
163
+ return;
164
+ }
165
+ for (const id of added) {
166
+ console.log(` ✓ ${relativePath}: ${id}`);
167
+ }
168
+ });
169
+ }
170
+ function readTemplate(contents) {
171
+ const lines = contents.replace(/\r?\n$/, '').split(/\r?\n/);
172
+ return {
173
+ header: lines[0],
174
+ body: lines.slice(1),
175
+ newline: '\n',
176
+ trailingNewline: true
177
+ };
178
+ }
179
+ /** Refs to read the template from. Undefined when GitHub cannot be asked. */
180
+ function listRefs() {
181
+ return __awaiter(this, void 0, void 0, function* () {
182
+ try {
183
+ return yield candidateRefs();
184
+ }
185
+ catch (error) {
186
+ warnSkipped(`Could not list the ${TARGET_VERSION} refs on GitHub (${error.message}); translations not added`);
187
+ return undefined;
188
+ }
189
+ });
190
+ }
191
+ function main() {
192
+ return __awaiter(this, void 0, void 0, function* () {
193
+ const cwd = process.cwd();
194
+ console.log('Adding the translation keys core gained this version...\n');
195
+ const refs = yield listRefs();
196
+ if (refs) {
197
+ for (const application of APPLICATIONS) {
198
+ try {
199
+ yield updateApplication(cwd, refs, application);
200
+ }
201
+ catch (error) {
202
+ warnSkipped(`Could not read ${application}.csv from the country config template on GitHub (${error.message}); ${application}.csv not updated`);
203
+ }
204
+ }
205
+ }
206
+ if (skipped.length > 0) {
207
+ console.warn(`\n⚠️ ${skipped.length} step(s) were skipped. Add the missing translations by hand before upgrading:`);
208
+ for (const message of skipped) {
209
+ console.warn(` - ${message}`);
210
+ }
211
+ }
212
+ });
213
+ }
@@ -0,0 +1,3 @@
1
+ declare function main(): Promise<void>;
2
+ export { main };
3
+ //# sourceMappingURL=enable-telemetry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"enable-telemetry.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/enable-telemetry.ts"],"names":[],"mappings":"AAwhBA,iBAAe,IAAI,kBAiClB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}
@@ -0,0 +1,438 @@
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: bring v2.1 daily-usage telemetry to a country config.
28
+ *
29
+ * v2.1 adds a `POST /trigger/telemetry` endpoint the events service posts to,
30
+ * which forwards to the OpenCRVS status service via `@opencrvs/toolkit`. A v2.0
31
+ * country config has none of this, so this step:
32
+ * - writes `src/api/telemetry/handler.ts` (the forwarding handler),
33
+ * - adds the telemetry env vars to `src/environment.ts`
34
+ * (`TELEMETRY_ENABLED`, `COUNTRY_CODE`, `ENVIRONMENT_NAME`, `ORGANISATION`),
35
+ * - registers the route and the startup notice in `src/index.ts`.
36
+ *
37
+ * It first asks whether to enable telemetry (default yes); the answer only sets
38
+ * the `TELEMETRY_ENABLED` default — the endpoint is wired in either way so it
39
+ * can be turned on later. Anything already present is left untouched, and any
40
+ * step whose structure cannot be found is skipped with a warning listing what
41
+ * to wire by hand.
42
+ */
43
+ const ts_morph_1 = require("ts-morph");
44
+ const fs_1 = require("fs");
45
+ const path_1 = __importDefault(require("path"));
46
+ const HANDLER_FILE = 'src/api/telemetry/handler.ts';
47
+ const ENVIRONMENT_FILE = 'src/environment.ts';
48
+ const INDEX_FILE = 'src/index.ts';
49
+ const HANDLER_MODULE = './api/telemetry/handler';
50
+ const skipped = [];
51
+ function warnSkipped(message) {
52
+ skipped.push(message);
53
+ console.warn(` ⚠️ ${message}`);
54
+ }
55
+ // ─── The handler source written into the country config ──────────────────────
56
+ const TELEMETRY_HANDLER_SOURCE = `/*
57
+ * This Source Code Form is subject to the terms of the Mozilla Public
58
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
59
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
60
+ *
61
+ * OpenCRVS is also distributed under the terms of the Civil Registration
62
+ * & Healthcare Disclaimer located at http://opencrvs.org/license.
63
+ *
64
+ * Copyright (C) The OpenCRVS Authors located at https://github.com/opencrvs/opencrvs-core/blob/master/AUTHORS.
65
+ */
66
+
67
+ import { Request, ResponseToolkit } from '@hapi/hapi'
68
+ import * as Joi from 'joi'
69
+ import { sendTelemetry, TelemetryReport } from '@opencrvs/toolkit/telemetry'
70
+ import { env } from '@countryconfig/environment'
71
+ import { logger } from '@countryconfig/logger'
72
+ import { applicationConfig } from '@countryconfig/api/application/application-config'
73
+
74
+ /** Report the events service posts to \`/trigger/telemetry\`. */
75
+ export const telemetrySchema = Joi.object({
76
+ reported_at: Joi.string().isoDate().required(),
77
+ app_version: Joi.string().optional(),
78
+ metrics: Joi.object()
79
+ .pattern(
80
+ Joi.string(),
81
+ Joi.alternatives(Joi.number(), Joi.string(), Joi.boolean())
82
+ )
83
+ .required()
84
+ })
85
+
86
+ interface IncomingReport {
87
+ reported_at: string
88
+ app_version?: string
89
+ metrics: Record<string, number | string | boolean>
90
+ }
91
+
92
+ /** Logged once at countryconfig startup while telemetry is disabled. */
93
+ export const TELEMETRY_DISABLED_NOTICE =
94
+ 'Telemetry is disabled. Help improve OpenCRVS by sharing anonymous, ' +
95
+ 'aggregate usage metrics (registration and certificate counts, active ' +
96
+ 'users, uptime) — no personal, health, or otherwise protected record data ' +
97
+ 'ever leaves your instance. Enable it by setting TELEMETRY_ENABLED=true on ' +
98
+ 'the countryconfig service.'
99
+
100
+ /**
101
+ * Receives a usage report from the events service and, when telemetry is
102
+ * enabled for this instance, stamps the instance identity onto it and forwards
103
+ * it to the status service via the toolkit's \`sendTelemetry\` (which owns the
104
+ * endpoint and payload schema). The events service is unaware of whether
105
+ * telemetry is enabled or of the country code / domain / environment reported.
106
+ */
107
+ export async function telemetryHandler(request: Request, h: ResponseToolkit) {
108
+ // Only accept OpenCRVS *system* tokens (the events service's service
109
+ // token has userType 'system'). A logged-in user's token is a 'user' token,
110
+ // so a user cannot submit telemetry with their own credentials — and the
111
+ // service-token endpoint is not reachable through the public gateway.
112
+ const credentials = request.auth.credentials as
113
+ | { userType?: string }
114
+ | undefined
115
+ if (credentials?.userType !== 'system') {
116
+ logger.warn('Telemetry: rejected a request that is not from a system token')
117
+ return h.response({ error: 'forbidden' }).code(403)
118
+ }
119
+
120
+ if (!env.TELEMETRY_ENABLED) {
121
+ // The encouraging notice is logged once at startup (see index.ts); keep the
122
+ // per-report path quiet.
123
+ return h.response({ status: 'skipped' }).code(200)
124
+ }
125
+
126
+ const incoming = request.payload as IncomingReport
127
+
128
+ // Only production instances report; staging, QA and local build the report
129
+ // but never reach the status service. (This gate used to live in the
130
+ // toolkit's sendTelemetry; each country config now owns it.)
131
+ if (!env.isProduction) {
132
+ logger.info(
133
+ \`Telemetry: report for \${incoming.reported_at} was not sent — only production instances report\`
134
+ )
135
+ return h.response({ status: 'skipped' }).code(200)
136
+ }
137
+
138
+ const report: TelemetryReport = {
139
+ reported_at: incoming.reported_at,
140
+ country_code: env.COUNTRY_CODE,
141
+ organisation: env.ORGANISATION,
142
+ // env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
143
+ // "no domain" rather than reporting a literal "*".
144
+ domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
145
+ instance: {
146
+ application_name: applicationConfig.APPLICATION_NAME,
147
+ environment: env.ENVIRONMENT_NAME,
148
+ app_version: incoming.app_version
149
+ },
150
+ metrics: incoming.metrics
151
+ }
152
+
153
+ let result
154
+ try {
155
+ result = await sendTelemetry(report)
156
+ } catch (error) {
157
+ const message = error instanceof Error ? error.message : String(error)
158
+ logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
159
+ return h.response({ status: 'error' }).code(502)
160
+ }
161
+
162
+ if (result.outcome === 'rejected') {
163
+ logger.error(
164
+ \`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
165
+ )
166
+ return h.response({ status: 'error' }).code(502)
167
+ }
168
+
169
+ logger.info(
170
+ \`Telemetry: forwarded report for \${report.reported_at} to the status service\`
171
+ )
172
+ return h.response({ status: 'forwarded' }).code(202)
173
+ }
174
+ `;
175
+ const TELEMETRY_DISABLED = {
176
+ enabled: false,
177
+ countryCode: '',
178
+ organisation: ''
179
+ };
180
+ /**
181
+ * Asks whether to enable telemetry and, when enabled, for the country code and
182
+ * organisation reported with it — both mandatory, re-asking until supplied.
183
+ * Non-interactive upgrades cannot answer, so telemetry stays disabled there.
184
+ */
185
+ function promptTelemetryConfig() {
186
+ return __awaiter(this, void 0, void 0, function* () {
187
+ if (!process.stdin.isTTY) {
188
+ return TELEMETRY_DISABLED;
189
+ }
190
+ const { confirm, input } = yield import('@inquirer/prompts');
191
+ const enabled = yield confirm({
192
+ message: 'Enable anonymous usage telemetry to help improve OpenCRVS? Only ' +
193
+ 'aggregate metrics are shared — no personal or protected data.',
194
+ default: true
195
+ });
196
+ if (!enabled) {
197
+ return TELEMETRY_DISABLED;
198
+ }
199
+ const countryCode = (yield input({
200
+ message: 'Country code (ISO alpha-3, e.g. FAR):',
201
+ validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) ||
202
+ 'Enter a 3-letter ISO alpha-3 code.'
203
+ }))
204
+ .trim()
205
+ .toUpperCase();
206
+ const organisation = (yield input({
207
+ message: 'Organisation running this instance:',
208
+ validate: (value) => value.trim() !== '' || 'Enter an organisation name.'
209
+ })).trim();
210
+ return { enabled: true, countryCode, organisation };
211
+ });
212
+ }
213
+ // ─── Steps ───────────────────────────────────────────────────────────────────
214
+ function writeTelemetryHandler(cwd) {
215
+ const handlerPath = path_1.default.join(cwd, HANDLER_FILE);
216
+ if ((0, fs_1.existsSync)(handlerPath)) {
217
+ console.log(` ${HANDLER_FILE} already present; left unchanged`);
218
+ return;
219
+ }
220
+ (0, fs_1.mkdirSync)(path_1.default.dirname(handlerPath), { recursive: true });
221
+ (0, fs_1.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
222
+ console.log(` ✓ ${HANDLER_FILE}`);
223
+ }
224
+ /**
225
+ * Adds `name: <initializer>` after the last entry of `object`, indented to
226
+ * match its neighbours. Text insertion (rather than `addPropertyAssignment`)
227
+ * keeps ts-morph from re-indenting the whole object. Returns false when the
228
+ * object is empty.
229
+ */
230
+ function appendProperty(sourceFile, object, name, valueLines) {
231
+ const properties = object.getProperties();
232
+ const lastProperty = properties[properties.length - 1];
233
+ if (!lastProperty)
234
+ return false;
235
+ const indent = lastProperty.getIndentationText();
236
+ const entry = valueLines
237
+ .map((line, index) => `${indent}${index === 0 ? `${name}: ${line}` : line}`)
238
+ .join('\n');
239
+ sourceFile.insertText(lastProperty.getEnd(), `,\n${entry}`);
240
+ return true;
241
+ }
242
+ function ensureEnvalidNamedImports(sourceFile, names) {
243
+ const importDeclaration = sourceFile
244
+ .getImportDeclarations()
245
+ .find((declaration) => declaration.getModuleSpecifierValue() === 'envalid');
246
+ if (!importDeclaration) {
247
+ warnSkipped(`Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(', ')} } by hand`);
248
+ return;
249
+ }
250
+ const existing = new Set(importDeclaration.getNamedImports().map((named) => named.getName()));
251
+ for (const name of names) {
252
+ if (!existing.has(name)) {
253
+ importDeclaration.addNamedImport(name);
254
+ }
255
+ }
256
+ }
257
+ function getCleanEnvObject(sourceFile) {
258
+ var _a;
259
+ const options = (_a = sourceFile
260
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.CallExpression)
261
+ .find((call) => call.getExpression().getText() === 'cleanEnv')) === null || _a === void 0 ? void 0 : _a.getArguments()[1];
262
+ return options && ts_morph_1.Node.isObjectLiteralExpression(options)
263
+ ? options
264
+ : undefined;
265
+ }
266
+ /**
267
+ * Ensures an env var exists in the cleanEnv config with the given default.
268
+ *
269
+ * - `update: true` sets the default even when the var already exists (used for
270
+ * the values the operator just supplied).
271
+ * - `update: false` only adds the var when missing, never touching an existing
272
+ * one (so disabling never clobbers a country's own values).
273
+ *
274
+ * Every call re-resolves the config object: a prior `insertText` invalidates
275
+ * nodes previously read from the file.
276
+ */
277
+ function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
278
+ var _a;
279
+ const object = getCleanEnvObject(sourceFile);
280
+ if (!object)
281
+ return;
282
+ const existing = object.getProperty(name);
283
+ if (existing && ts_morph_1.Node.isPropertyAssignment(existing)) {
284
+ if (!update)
285
+ return;
286
+ const options = (_a = existing
287
+ .getInitializerIfKind(ts_morph_1.SyntaxKind.CallExpression)) === null || _a === void 0 ? void 0 : _a.getArguments()[0];
288
+ if (options && ts_morph_1.Node.isObjectLiteralExpression(options)) {
289
+ const defaultProperty = options.getProperty('default');
290
+ if (defaultProperty && ts_morph_1.Node.isPropertyAssignment(defaultProperty)) {
291
+ defaultProperty.setInitializer(defaultExpr);
292
+ }
293
+ else {
294
+ options.insertPropertyAssignment(0, {
295
+ name: 'default',
296
+ initializer: defaultExpr
297
+ });
298
+ }
299
+ console.log(` ✓ ${ENVIRONMENT_FILE}: ${name} default set`);
300
+ }
301
+ return;
302
+ }
303
+ if (appendProperty(sourceFile, object, name, [
304
+ `${kind}({`,
305
+ ` default: ${defaultExpr},`,
306
+ ` desc: ${JSON.stringify(desc)}`,
307
+ '})'
308
+ ])) {
309
+ console.log(` ✓ ${ENVIRONMENT_FILE}: ${name}`);
310
+ }
311
+ }
312
+ function addEnvironmentVariables(project, cwd, config) {
313
+ const sourceFile = project.addSourceFileAtPathIfExists(path_1.default.join(cwd, ENVIRONMENT_FILE));
314
+ if (!sourceFile) {
315
+ warnSkipped(`${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`);
316
+ return;
317
+ }
318
+ if (!getCleanEnvObject(sourceFile)) {
319
+ warnSkipped(`Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`);
320
+ return;
321
+ }
322
+ ensureEnvalidNamedImports(sourceFile, ['bool', 'str']);
323
+ // Reflect the operator's choice in the on/off default.
324
+ upsertEnvVar(sourceFile, 'TELEMETRY_ENABLED', 'bool', config.enabled ? 'true' : 'false', 'When true, usage telemetry received from the events service is forwarded to the OpenCRVS status service.', true);
325
+ // When enabled, bake the supplied identity into the defaults; when disabled,
326
+ // only seed placeholders if the vars are missing (never overwrite).
327
+ upsertEnvVar(sourceFile, 'COUNTRY_CODE', 'str', config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`, 'ISO-style country code of this instance, reported with telemetry.', config.enabled);
328
+ upsertEnvVar(sourceFile, 'ORGANISATION', 'str', config.enabled ? JSON.stringify(config.organisation) : `''`, 'Organisation running this instance, reported with telemetry. Empty by default.', config.enabled);
329
+ upsertEnvVar(sourceFile, 'ENVIRONMENT_NAME', 'str', `'development'`, 'Environment name (e.g. "production", "staging") reported as the telemetry environment.', false);
330
+ }
331
+ function wireIndex(project, cwd) {
332
+ const sourceFile = project.addSourceFileAtPathIfExists(path_1.default.join(cwd, INDEX_FILE));
333
+ if (!sourceFile) {
334
+ warnSkipped(`${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`);
335
+ return;
336
+ }
337
+ // 1. import
338
+ if (!sourceFile
339
+ .getImportDeclarations()
340
+ .some((d) => d.getModuleSpecifierValue() === HANDLER_MODULE)) {
341
+ sourceFile.addImportDeclaration({
342
+ moduleSpecifier: HANDLER_MODULE,
343
+ namedImports: [
344
+ 'telemetryHandler',
345
+ 'telemetrySchema',
346
+ 'TELEMETRY_DISABLED_NOTICE'
347
+ ]
348
+ });
349
+ console.log(` ✓ ${INDEX_FILE}: import ${HANDLER_MODULE}`);
350
+ }
351
+ // 2. route, inserted after the last server.route(...) call
352
+ if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
353
+ const lastRouteStatement = sourceFile
354
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.CallExpression)
355
+ .filter((call) => call.getExpression().getText() === 'server.route')
356
+ .map((call) => call.getFirstAncestorByKind(ts_morph_1.SyntaxKind.ExpressionStatement))
357
+ .filter((statement) => Boolean(statement))
358
+ .pop();
359
+ if (!lastRouteStatement) {
360
+ warnSkipped(`Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`);
361
+ }
362
+ else {
363
+ const indent = lastRouteStatement.getIndentationText();
364
+ const route = [
365
+ `server.route({`,
366
+ ` method: 'POST',`,
367
+ ` path: '/trigger/telemetry',`,
368
+ ` handler: telemetryHandler,`,
369
+ ` options: {`,
370
+ ` tags: ['api', 'triggers'],`,
371
+ ` validate: {`,
372
+ ` payload: telemetrySchema`,
373
+ ` },`,
374
+ ` description:`,
375
+ ` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
376
+ ` }`,
377
+ `})`
378
+ ]
379
+ .map((line) => (line ? `${indent}${line}` : line))
380
+ .join('\n');
381
+ sourceFile.insertText(lastRouteStatement.getEnd(), `\n\n${route}`);
382
+ console.log(` ✓ ${INDEX_FILE}: POST /trigger/telemetry`);
383
+ }
384
+ }
385
+ // 3. startup notice, inserted after the "Server successfully started" log.
386
+ // Guard on the usage, not the name — the import added above also mentions it.
387
+ if (!sourceFile.getText().includes('logger.info(TELEMETRY_DISABLED_NOTICE)')) {
388
+ const startedLog = sourceFile
389
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.ExpressionStatement)
390
+ .find((statement) => statement.getText().includes('Server successfully started'));
391
+ if (!startedLog) {
392
+ warnSkipped(`Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`);
393
+ }
394
+ else {
395
+ const indent = startedLog.getIndentationText();
396
+ const notice = [
397
+ `if (!env.TELEMETRY_ENABLED) {`,
398
+ ` logger.info(TELEMETRY_DISABLED_NOTICE)`,
399
+ `}`
400
+ ]
401
+ .map((line) => (line ? `${indent}${line}` : line))
402
+ .join('\n');
403
+ sourceFile.insertText(startedLog.getEnd(), `\n\n${notice}`);
404
+ console.log(` ✓ ${INDEX_FILE}: telemetry-disabled startup notice`);
405
+ if (!sourceFile
406
+ .getImportDeclarations()
407
+ .some((d) => d.getModuleSpecifierValue() === './environment')) {
408
+ warnSkipped(`The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`);
409
+ }
410
+ }
411
+ }
412
+ }
413
+ // ─── Entry point ─────────────────────────────────────────────────────────────
414
+ function main() {
415
+ return __awaiter(this, void 0, void 0, function* () {
416
+ const cwd = process.cwd();
417
+ const config = yield promptTelemetryConfig();
418
+ console.log(`\nAdding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : 'disabled'} by default)...\n`);
419
+ writeTelemetryHandler(cwd);
420
+ const project = new ts_morph_1.Project({
421
+ // ts-morph indents inserted code with four spaces and double-quotes strings
422
+ // by default, both of which the country config's prettier run would undo.
423
+ manipulationSettings: {
424
+ indentationText: ts_morph_1.IndentationText.TwoSpaces,
425
+ quoteKind: ts_morph_1.QuoteKind.Single
426
+ }
427
+ });
428
+ addEnvironmentVariables(project, cwd, config);
429
+ wireIndex(project, cwd);
430
+ yield project.save();
431
+ if (skipped.length > 0) {
432
+ console.warn(`\n⚠️ ${skipped.length} telemetry step(s) were skipped. Wire the following by hand:`);
433
+ for (const message of skipped) {
434
+ console.warn(` - ${message}`);
435
+ }
436
+ }
437
+ });
438
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/index.ts"],"names":[],"mappings":"AAYA;;;GAGG;AACH,wBAAsB,UAAU,CAAC,WAAW,EAAE,OAAO,iBAEpD"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/migrations/v2.1/index.ts"],"names":[],"mappings":"AAeA;;;GAGG;AACH,wBAAsB,UAAU,CAAC,WAAW,EAAE,OAAO,iBAKpD"}