@opencrvs/toolkit 2.1.0-rc.36dcafa → 2.1.0-rc.3a75e55

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 (85) hide show
  1. package/README.md +1 -0
  2. package/build.sh +3 -0
  3. package/create-countryconfig/index.js +281 -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/cli.js +1082 -101
  8. package/dist/commons/api/router.d.ts +702 -68
  9. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  10. package/dist/commons/conditionals/validate.d.ts +16 -5
  11. package/dist/commons/events/ActionDocument.d.ts +5 -11
  12. package/dist/commons/events/ActionInput.d.ts +4 -4
  13. package/dist/commons/events/ActionStatus.d.ts +14 -0
  14. package/dist/commons/events/AdvancedSearchConfig.d.ts +24 -0
  15. package/dist/commons/events/AuditLog.d.ts +147 -0
  16. package/dist/commons/events/EventConfig.d.ts +3 -0
  17. package/dist/commons/events/EventDocument.d.ts +470 -2
  18. package/dist/commons/events/EventIndex.d.ts +3 -26
  19. package/dist/commons/events/EventMetadata.d.ts +1 -11
  20. package/dist/commons/events/EventStatus.d.ts +19 -0
  21. package/dist/commons/events/FieldConfig.d.ts +88 -53
  22. package/dist/commons/events/FieldTypeMapping.d.ts +27 -27
  23. package/dist/commons/events/FieldValue.d.ts +2 -2
  24. package/dist/commons/events/Flag.d.ts +42 -0
  25. package/dist/commons/events/PlainDate.d.ts +8 -0
  26. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  27. package/dist/commons/events/WorkqueueConfig.d.ts +17 -14
  28. package/dist/commons/events/event.d.ts +12 -0
  29. package/dist/commons/events/index.d.ts +1 -0
  30. package/dist/commons/events/locationPayloads.d.ts +95 -0
  31. package/dist/commons/events/locations.d.ts +242 -13
  32. package/dist/commons/events/mocks.test.utils.d.ts +46 -2
  33. package/dist/commons/events/test.utils.d.ts +12 -8
  34. package/dist/commons/events/utils.d.ts +2 -2
  35. package/dist/commons/notification/UserNotifications.d.ts +28 -13
  36. package/dist/commons/notification/dispatch.d.ts +15 -0
  37. package/dist/commons/notification/index.d.ts +1 -0
  38. package/dist/conditionals/index.js +328 -58
  39. package/dist/environment/index.d.ts +1 -0
  40. package/dist/environment/index.d.ts.map +1 -1
  41. package/dist/environment/index.js +10 -0
  42. package/dist/environment/logger.d.ts +12 -3
  43. package/dist/environment/logger.d.ts.map +1 -1
  44. package/dist/environment/paths.d.ts +7 -0
  45. package/dist/environment/paths.d.ts.map +1 -0
  46. package/dist/environment/paths.js +72 -0
  47. package/dist/environment/questions.d.ts.map +1 -1
  48. package/dist/environment/questions.js +20 -14
  49. package/dist/environment/setup-environment.js +3 -2
  50. package/dist/environment/templates.d.ts.map +1 -1
  51. package/dist/environment/templates.js +2 -1
  52. package/dist/environment/update-workflows.d.ts.map +1 -1
  53. package/dist/environment/update-workflows.js +17 -5
  54. package/dist/environment/upgrade.d.ts +2 -0
  55. package/dist/environment/upgrade.d.ts.map +1 -0
  56. package/dist/environment/upgrade.js +82 -0
  57. package/dist/environment/users.js +11 -13
  58. package/dist/events/index.js +3759 -3357
  59. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
  60. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  61. package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
  62. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  63. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  64. package/dist/migrations/v2.1/add-recovery-link-notifications.js +530 -0
  65. package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
  66. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  67. package/dist/migrations/v2.1/enable-telemetry.js +435 -0
  68. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  69. package/dist/migrations/v2.1/index.js +859 -0
  70. package/dist/notification/index.js +1863 -1463
  71. package/dist/scopes/index.d.ts +327 -32
  72. package/dist/scopes/index.js +329 -58
  73. package/dist/telemetry/index.d.ts +48 -0
  74. package/dist/telemetry/index.d.ts.map +1 -0
  75. package/dist/telemetry/index.js +42 -0
  76. package/dist/templates/charts-values/opencrvs-services/values.yaml +4 -3
  77. package/dist/templates/charts-values/opentelemetry/values.yaml +95 -0
  78. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  79. package/dist/templates/inventory/inventory.template.yml +1 -3
  80. package/opencrvs-toolkit-2.1.0-rc.3a75e55.tgz +0 -0
  81. package/package.json +7 -5
  82. package/tsconfig.tsbuildinfo +1 -1
  83. package/dist/templates/inventory/production.example.yml +0 -77
  84. package/dist/templates/inventory/qa.example.yml +0 -48
  85. package/opencrvs-toolkit-2.1.0-rc.36dcafa.tgz +0 -0
@@ -0,0 +1,435 @@
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 anonymous
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
+ // anonymous-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
+ const report: TelemetryReport = {
129
+ reported_at: incoming.reported_at,
130
+ country_code: env.COUNTRY_CODE,
131
+ organisation: env.ORGANISATION,
132
+ // env.DOMAIN defaults to a wildcard for CORS in some setups; treat that as
133
+ // "no domain" rather than reporting a literal "*".
134
+ domain: env.DOMAIN && env.DOMAIN !== '*' ? env.DOMAIN : null,
135
+ instance: {
136
+ application_name: applicationConfig.APPLICATION_NAME,
137
+ environment: env.ENVIRONMENT_NAME,
138
+ app_version: incoming.app_version
139
+ },
140
+ metrics: incoming.metrics
141
+ }
142
+
143
+ let result
144
+ try {
145
+ result = await sendTelemetry(report)
146
+ } catch (error) {
147
+ const message = error instanceof Error ? error.message : String(error)
148
+ logger.error(\`Telemetry: forwarding to status service failed: \${message}\`)
149
+ return h.response({ status: 'error' }).code(502)
150
+ }
151
+
152
+ if (result.outcome === 'rejected') {
153
+ logger.error(
154
+ \`Telemetry: status service rejected report (HTTP \${result.status}): \${result.detail ?? ''}\`
155
+ )
156
+ return h.response({ status: 'error' }).code(502)
157
+ }
158
+
159
+ if (result.outcome === 'skipped') {
160
+ logger.info(
161
+ \`Telemetry: report for \${report.reported_at} was not sent — only production instances report\`
162
+ )
163
+ return h.response({ status: 'skipped' }).code(200)
164
+ }
165
+
166
+ logger.info(
167
+ \`Telemetry: forwarded report for \${report.reported_at} to the status service\`
168
+ )
169
+ return h.response({ status: 'forwarded' }).code(202)
170
+ }
171
+ `;
172
+ const TELEMETRY_DISABLED = {
173
+ enabled: false,
174
+ countryCode: '',
175
+ organisation: ''
176
+ };
177
+ /**
178
+ * Asks whether to enable telemetry and, when enabled, for the country code and
179
+ * organisation reported with it — both mandatory, re-asking until supplied.
180
+ * Non-interactive upgrades cannot answer, so telemetry stays disabled there.
181
+ */
182
+ function promptTelemetryConfig() {
183
+ return __awaiter(this, void 0, void 0, function* () {
184
+ if (!process.stdin.isTTY) {
185
+ return TELEMETRY_DISABLED;
186
+ }
187
+ const { confirm, input } = yield import('@inquirer/prompts');
188
+ const enabled = yield confirm({
189
+ message: 'Enable anonymous usage telemetry to help improve OpenCRVS? Only ' +
190
+ 'aggregate metrics are shared — no personal or protected data.',
191
+ default: true
192
+ });
193
+ if (!enabled) {
194
+ return TELEMETRY_DISABLED;
195
+ }
196
+ const countryCode = (yield input({
197
+ message: 'Country code (ISO alpha-3, e.g. FAR):',
198
+ validate: (value) => /^[A-Za-z]{3}$/.test(value.trim()) ||
199
+ 'Enter a 3-letter ISO alpha-3 code.'
200
+ }))
201
+ .trim()
202
+ .toUpperCase();
203
+ const organisation = (yield input({
204
+ message: 'Organisation running this instance:',
205
+ validate: (value) => value.trim() !== '' || 'Enter an organisation name.'
206
+ })).trim();
207
+ return { enabled: true, countryCode, organisation };
208
+ });
209
+ }
210
+ // ─── Steps ───────────────────────────────────────────────────────────────────
211
+ function writeTelemetryHandler(cwd) {
212
+ const handlerPath = path_1.default.join(cwd, HANDLER_FILE);
213
+ if ((0, fs_1.existsSync)(handlerPath)) {
214
+ console.log(` ${HANDLER_FILE} already present; left unchanged`);
215
+ return;
216
+ }
217
+ (0, fs_1.mkdirSync)(path_1.default.dirname(handlerPath), { recursive: true });
218
+ (0, fs_1.writeFileSync)(handlerPath, TELEMETRY_HANDLER_SOURCE);
219
+ console.log(` ✓ ${HANDLER_FILE}`);
220
+ }
221
+ /**
222
+ * Adds `name: <initializer>` after the last entry of `object`, indented to
223
+ * match its neighbours. Text insertion (rather than `addPropertyAssignment`)
224
+ * keeps ts-morph from re-indenting the whole object. Returns false when the
225
+ * object is empty.
226
+ */
227
+ function appendProperty(sourceFile, object, name, valueLines) {
228
+ const properties = object.getProperties();
229
+ const lastProperty = properties[properties.length - 1];
230
+ if (!lastProperty)
231
+ return false;
232
+ const indent = lastProperty.getIndentationText();
233
+ const entry = valueLines
234
+ .map((line, index) => `${indent}${index === 0 ? `${name}: ${line}` : line}`)
235
+ .join('\n');
236
+ sourceFile.insertText(lastProperty.getEnd(), `,\n${entry}`);
237
+ return true;
238
+ }
239
+ function ensureEnvalidNamedImports(sourceFile, names) {
240
+ const importDeclaration = sourceFile
241
+ .getImportDeclarations()
242
+ .find((declaration) => declaration.getModuleSpecifierValue() === 'envalid');
243
+ if (!importDeclaration) {
244
+ warnSkipped(`Could not find the 'envalid' import in ${ENVIRONMENT_FILE}; import { ${names.join(', ')} } by hand`);
245
+ return;
246
+ }
247
+ const existing = new Set(importDeclaration.getNamedImports().map((named) => named.getName()));
248
+ for (const name of names) {
249
+ if (!existing.has(name)) {
250
+ importDeclaration.addNamedImport(name);
251
+ }
252
+ }
253
+ }
254
+ function getCleanEnvObject(sourceFile) {
255
+ var _a;
256
+ const options = (_a = sourceFile
257
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.CallExpression)
258
+ .find((call) => call.getExpression().getText() === 'cleanEnv')) === null || _a === void 0 ? void 0 : _a.getArguments()[1];
259
+ return options && ts_morph_1.Node.isObjectLiteralExpression(options)
260
+ ? options
261
+ : undefined;
262
+ }
263
+ /**
264
+ * Ensures an env var exists in the cleanEnv config with the given default.
265
+ *
266
+ * - `update: true` sets the default even when the var already exists (used for
267
+ * the values the operator just supplied).
268
+ * - `update: false` only adds the var when missing, never touching an existing
269
+ * one (so disabling never clobbers a country's own values).
270
+ *
271
+ * Every call re-resolves the config object: a prior `insertText` invalidates
272
+ * nodes previously read from the file.
273
+ */
274
+ function upsertEnvVar(sourceFile, name, kind, defaultExpr, desc, update) {
275
+ var _a;
276
+ const object = getCleanEnvObject(sourceFile);
277
+ if (!object)
278
+ return;
279
+ const existing = object.getProperty(name);
280
+ if (existing && ts_morph_1.Node.isPropertyAssignment(existing)) {
281
+ if (!update)
282
+ return;
283
+ const options = (_a = existing
284
+ .getInitializerIfKind(ts_morph_1.SyntaxKind.CallExpression)) === null || _a === void 0 ? void 0 : _a.getArguments()[0];
285
+ if (options && ts_morph_1.Node.isObjectLiteralExpression(options)) {
286
+ const defaultProperty = options.getProperty('default');
287
+ if (defaultProperty && ts_morph_1.Node.isPropertyAssignment(defaultProperty)) {
288
+ defaultProperty.setInitializer(defaultExpr);
289
+ }
290
+ else {
291
+ options.insertPropertyAssignment(0, {
292
+ name: 'default',
293
+ initializer: defaultExpr
294
+ });
295
+ }
296
+ console.log(` ✓ ${ENVIRONMENT_FILE}: ${name} default set`);
297
+ }
298
+ return;
299
+ }
300
+ if (appendProperty(sourceFile, object, name, [
301
+ `${kind}({`,
302
+ ` default: ${defaultExpr},`,
303
+ ` desc: ${JSON.stringify(desc)}`,
304
+ '})'
305
+ ])) {
306
+ console.log(` ✓ ${ENVIRONMENT_FILE}: ${name}`);
307
+ }
308
+ }
309
+ function addEnvironmentVariables(project, cwd, config) {
310
+ const sourceFile = project.addSourceFileAtPathIfExists(path_1.default.join(cwd, ENVIRONMENT_FILE));
311
+ if (!sourceFile) {
312
+ warnSkipped(`${ENVIRONMENT_FILE} not found; add the telemetry env vars by hand`);
313
+ return;
314
+ }
315
+ if (!getCleanEnvObject(sourceFile)) {
316
+ warnSkipped(`Could not find the cleanEnv(...) config object in ${ENVIRONMENT_FILE}; add the telemetry env vars by hand`);
317
+ return;
318
+ }
319
+ ensureEnvalidNamedImports(sourceFile, ['bool', 'str']);
320
+ // Reflect the operator's choice in the on/off default.
321
+ 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);
322
+ // When enabled, bake the supplied identity into the defaults; when disabled,
323
+ // only seed placeholders if the vars are missing (never overwrite).
324
+ upsertEnvVar(sourceFile, 'COUNTRY_CODE', 'str', config.enabled ? JSON.stringify(config.countryCode) : `'FAR'`, 'ISO-style country code of this instance, reported with telemetry.', config.enabled);
325
+ upsertEnvVar(sourceFile, 'ORGANISATION', 'str', config.enabled ? JSON.stringify(config.organisation) : `''`, 'Organisation running this instance, reported with telemetry. Empty by default.', config.enabled);
326
+ upsertEnvVar(sourceFile, 'ENVIRONMENT_NAME', 'str', `'development'`, 'Environment name (e.g. "production", "staging") reported as the telemetry environment.', false);
327
+ }
328
+ function wireIndex(project, cwd) {
329
+ const sourceFile = project.addSourceFileAtPathIfExists(path_1.default.join(cwd, INDEX_FILE));
330
+ if (!sourceFile) {
331
+ warnSkipped(`${INDEX_FILE} not found; register POST /trigger/telemetry and the startup notice by hand`);
332
+ return;
333
+ }
334
+ // 1. import
335
+ if (!sourceFile
336
+ .getImportDeclarations()
337
+ .some((d) => d.getModuleSpecifierValue() === HANDLER_MODULE)) {
338
+ sourceFile.addImportDeclaration({
339
+ moduleSpecifier: HANDLER_MODULE,
340
+ namedImports: [
341
+ 'telemetryHandler',
342
+ 'telemetrySchema',
343
+ 'TELEMETRY_DISABLED_NOTICE'
344
+ ]
345
+ });
346
+ console.log(` ✓ ${INDEX_FILE}: import ${HANDLER_MODULE}`);
347
+ }
348
+ // 2. route, inserted after the last server.route(...) call
349
+ if (!sourceFile.getText().includes("path: '/trigger/telemetry'")) {
350
+ const lastRouteStatement = sourceFile
351
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.CallExpression)
352
+ .filter((call) => call.getExpression().getText() === 'server.route')
353
+ .map((call) => call.getFirstAncestorByKind(ts_morph_1.SyntaxKind.ExpressionStatement))
354
+ .filter((statement) => Boolean(statement))
355
+ .pop();
356
+ if (!lastRouteStatement) {
357
+ warnSkipped(`Could not find a server.route(...) call in ${INDEX_FILE}; register POST /trigger/telemetry by hand`);
358
+ }
359
+ else {
360
+ const indent = lastRouteStatement.getIndentationText();
361
+ const route = [
362
+ `server.route({`,
363
+ ` method: 'POST',`,
364
+ ` path: '/trigger/telemetry',`,
365
+ ` handler: telemetryHandler,`,
366
+ ` options: {`,
367
+ ` tags: ['api', 'triggers'],`,
368
+ ` validate: {`,
369
+ ` payload: telemetrySchema`,
370
+ ` },`,
371
+ ` description:`,
372
+ ` 'Receives a usage report from the events service and forwards it to the status service when telemetry is enabled'`,
373
+ ` }`,
374
+ `})`
375
+ ]
376
+ .map((line) => (line ? `${indent}${line}` : line))
377
+ .join('\n');
378
+ sourceFile.insertText(lastRouteStatement.getEnd(), `\n\n${route}`);
379
+ console.log(` ✓ ${INDEX_FILE}: POST /trigger/telemetry`);
380
+ }
381
+ }
382
+ // 3. startup notice, inserted after the "Server successfully started" log.
383
+ // Guard on the usage, not the name — the import added above also mentions it.
384
+ if (!sourceFile.getText().includes('logger.info(TELEMETRY_DISABLED_NOTICE)')) {
385
+ const startedLog = sourceFile
386
+ .getDescendantsOfKind(ts_morph_1.SyntaxKind.ExpressionStatement)
387
+ .find((statement) => statement.getText().includes('Server successfully started'));
388
+ if (!startedLog) {
389
+ warnSkipped(`Could not find the startup log in ${INDEX_FILE}; log TELEMETRY_DISABLED_NOTICE when TELEMETRY_ENABLED is false by hand`);
390
+ }
391
+ else {
392
+ const indent = startedLog.getIndentationText();
393
+ const notice = [
394
+ `if (!env.TELEMETRY_ENABLED) {`,
395
+ ` logger.info(TELEMETRY_DISABLED_NOTICE)`,
396
+ `}`
397
+ ]
398
+ .map((line) => (line ? `${indent}${line}` : line))
399
+ .join('\n');
400
+ sourceFile.insertText(startedLog.getEnd(), `\n\n${notice}`);
401
+ console.log(` ✓ ${INDEX_FILE}: telemetry-disabled startup notice`);
402
+ if (!sourceFile
403
+ .getImportDeclarations()
404
+ .some((d) => d.getModuleSpecifierValue() === './environment')) {
405
+ warnSkipped(`The startup notice reads env.TELEMETRY_ENABLED but ${INDEX_FILE} does not import env from './environment'; import it by hand`);
406
+ }
407
+ }
408
+ }
409
+ }
410
+ // ─── Entry point ─────────────────────────────────────────────────────────────
411
+ function main() {
412
+ return __awaiter(this, void 0, void 0, function* () {
413
+ const cwd = process.cwd();
414
+ const config = yield promptTelemetryConfig();
415
+ console.log(`\nAdding daily usage telemetry (${config.enabled ? `enabled for ${config.countryCode}` : 'disabled'} by default)...\n`);
416
+ writeTelemetryHandler(cwd);
417
+ const project = new ts_morph_1.Project({
418
+ // ts-morph indents inserted code with four spaces and double-quotes strings
419
+ // by default, both of which the country config's prettier run would undo.
420
+ manipulationSettings: {
421
+ indentationText: ts_morph_1.IndentationText.TwoSpaces,
422
+ quoteKind: ts_morph_1.QuoteKind.Single
423
+ }
424
+ });
425
+ addEnvironmentVariables(project, cwd, config);
426
+ wireIndex(project, cwd);
427
+ yield project.save();
428
+ if (skipped.length > 0) {
429
+ console.warn(`\n⚠️ ${skipped.length} telemetry step(s) were skipped. Wire the following by hand:`);
430
+ for (const message of skipped) {
431
+ console.warn(` - ${message}`);
432
+ }
433
+ }
434
+ });
435
+ }
@@ -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":"AAcA;;;GAGG;AACH,wBAAsB,UAAU,CAAC,WAAW,EAAE,OAAO,iBAIpD"}