@opencrvs/toolkit 2.2.0-rc.30529dd → 2.2.0-rc.3de6f63

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 (48) hide show
  1. package/dist/application-config/index.js +1 -1
  2. package/dist/authentication/index.js +10 -2
  3. package/dist/cli.js +586 -303
  4. package/dist/commons/events/ActionConfig.d.ts +2 -2
  5. package/dist/commons/events/EventConfig.d.ts +1 -10
  6. package/dist/commons/events/eventConfigValidation.d.ts +1 -1
  7. package/dist/commons/events/index.d.ts +1 -0
  8. package/dist/commons/events/test.utils.d.ts +2 -3
  9. package/dist/commons/events/toNotificationForm.d.ts +17 -0
  10. package/dist/commons/events/utils.d.ts +77 -56
  11. package/dist/environment/custom-types.d.ts +1 -0
  12. package/dist/environment/custom-types.d.ts.map +1 -1
  13. package/dist/environment/derived-variables.d.ts +6 -4
  14. package/dist/environment/derived-variables.d.ts.map +1 -1
  15. package/dist/environment/derived-variables.js +6 -4
  16. package/dist/environment/questions.d.ts +14 -2
  17. package/dist/environment/questions.d.ts.map +1 -1
  18. package/dist/environment/questions.js +39 -18
  19. package/dist/environment/registry.d.ts +15 -0
  20. package/dist/environment/registry.d.ts.map +1 -0
  21. package/dist/environment/registry.js +112 -0
  22. package/dist/environment/setup-environment.d.ts.map +1 -1
  23. package/dist/environment/setup-environment.js +76 -28
  24. package/dist/events/index.js +60 -97
  25. package/dist/migrations/add-notify-config.d.ts +40 -0
  26. package/dist/migrations/add-notify-config.d.ts.map +1 -0
  27. package/dist/migrations/add-notify-config.js +249 -0
  28. package/dist/migrations/index.d.ts.map +1 -1
  29. package/dist/migrations/index.js +345 -143
  30. package/dist/migrations/move-declaration-to-declare-action.d.ts.map +1 -1
  31. package/dist/migrations/move-declaration-to-declare-action.js +27 -144
  32. package/dist/migrations/read-declaration-through-helper.d.ts.map +1 -1
  33. package/dist/migrations/read-declaration-through-helper.js +3 -61
  34. package/dist/migrations/utils.d.ts +61 -0
  35. package/dist/migrations/utils.d.ts.map +1 -0
  36. package/dist/migrations/utils.js +218 -0
  37. package/dist/notification/index.js +47 -75
  38. package/dist/scopes/index.d.ts +5 -2
  39. package/dist/scopes/index.js +10 -2
  40. package/dist/templates/charts-values/opencrvs-services/values.yaml +3 -4
  41. package/opencrvs-toolkit-2.2.0-rc.3de6f63.tgz +0 -0
  42. package/package.json +2 -1
  43. package/tsconfig.build.tsbuildinfo +1 -1
  44. package/dist/commons/events/notificationFormFallback.d.ts +0 -10
  45. package/dist/environment/dockerhub.d.ts +0 -15
  46. package/dist/environment/dockerhub.d.ts.map +0 -1
  47. package/dist/environment/dockerhub.js +0 -104
  48. package/opencrvs-toolkit-2.2.0-rc.30529dd.tgz +0 -0
@@ -0,0 +1,112 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
22
+ exports.validateRegistryCredentials = validateRegistryCredentials;
23
+ const REQUEST_TIMEOUT_MS = 10000;
24
+ // Docker Hub serves its registry API from registry-1.docker.io, docker.io is the website
25
+ function registryApiHost(registry) {
26
+ const host = registry.trim().toLowerCase();
27
+ return host === 'docker.io' || host === 'index.docker.io'
28
+ ? 'registry-1.docker.io'
29
+ : host;
30
+ }
31
+ function request(url, authorization) {
32
+ return fetch(url, {
33
+ headers: authorization ? { Authorization: authorization } : {},
34
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
35
+ });
36
+ }
37
+ function failure(registry, step, response) {
38
+ const reason = `${registry} ${step} responded with HTTP ${response.status}`;
39
+ switch (response.status) {
40
+ case 401:
41
+ case 403:
42
+ return {
43
+ status: 'invalid-credentials',
44
+ reason: `${reason}. Check REGISTRY_USERNAME, REGISTRY_TOKEN, REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
45
+ };
46
+ case 404:
47
+ // The API cannot tell an empty repository from one that does not exist
48
+ return {
49
+ status: 'repository-not-found',
50
+ reason: `${reason}. This is also the answer for an empty repository. Check REGISTRY_ORGANISATION and REGISTRY_REPOSITORY`
51
+ };
52
+ default:
53
+ return { status: 'unreachable', reason };
54
+ }
55
+ }
56
+ /**
57
+ * Checks, using the OCI Distribution (Docker Registry HTTP API v2) that every
58
+ * registry implements, that the username/token pair is accepted by the registry
59
+ * and that the organisation/repository is visible to that account.
60
+ *
61
+ * Existing GitHub secrets cannot be read back, so when any value is missing
62
+ * (kept from an existing secret) the check is skipped.
63
+ */
64
+ function validateRegistryCredentials(registry, organisation, repository, username, token) {
65
+ return __awaiter(this, void 0, void 0, function* () {
66
+ var _a, _b;
67
+ var _c, _d;
68
+ if (!registry || !organisation || !repository || !username || !token) {
69
+ return {
70
+ status: 'skipped',
71
+ reason: 'Some values are kept from existing GitHub secrets, which cannot be read back'
72
+ };
73
+ }
74
+ const host = registryApiHost(registry);
75
+ const name = `${organisation}/${repository}`;
76
+ const basic = `Basic ${Buffer.from(`${username}:${token}`).toString('base64')}`;
77
+ try {
78
+ // A registry that wants a token names its token service in the challenge.
79
+ // For any other answer the credentials are sent as they are.
80
+ const challenge = (_c = (yield request(`https://${host}/v2/`, undefined)).headers.get('www-authenticate')) !== null && _c !== void 0 ? _c : '';
81
+ const realm = (_a = challenge.match(/realm="([^"]*)"/i)) === null || _a === void 0 ? void 0 : _a[1];
82
+ const service = (_b = challenge.match(/service="([^"]*)"/i)) === null || _b === void 0 ? void 0 : _b[1];
83
+ let authorization = basic;
84
+ if (/^\s*bearer/i.test(challenge) && realm) {
85
+ const tokenUrl = new URL(realm);
86
+ if (service) {
87
+ tokenUrl.searchParams.set('service', service);
88
+ }
89
+ tokenUrl.searchParams.set('scope', `repository:${name}:pull`);
90
+ const login = yield request(tokenUrl, basic);
91
+ if (!login.ok) {
92
+ return failure(registry, 'login', login);
93
+ }
94
+ const body = (yield login.json());
95
+ authorization = `Bearer ${(_d = body.token) !== null && _d !== void 0 ? _d : body.access_token}`;
96
+ }
97
+ const path = name.split('/').map(encodeURIComponent).join('/');
98
+ const response = yield request(`https://${host}/v2/${path}/tags/list?n=1`, authorization);
99
+ return response.ok
100
+ ? { status: 'valid' }
101
+ : failure(registry, `lookup of repository ${name}`, response);
102
+ }
103
+ catch (err) {
104
+ if (!(err instanceof Error)) {
105
+ return { status: 'unreachable', reason: String(err) };
106
+ }
107
+ // fetch only reports "fetch failed", the real error (e.g. ENOTFOUND) is its cause
108
+ const cause = err.cause instanceof Error ? `: ${err.cause.message}` : '';
109
+ return { status: 'unreachable', reason: `${err.message}${cause}` };
110
+ }
111
+ });
112
+ }
@@ -1 +1 @@
1
- {"version":3,"file":"setup-environment.d.ts","sourceRoot":"","sources":["../../src/environment/setup-environment.ts"],"names":[],"mappings":"AAiUA,wBAAsB,mBAAmB,kBA2pCxC"}
1
+ {"version":3,"file":"setup-environment.d.ts","sourceRoot":"","sources":["../../src/environment/setup-environment.ts"],"names":[],"mappings":"AA4aA,wBAAsB,mBAAmB,kBAwpCxC"}
@@ -65,11 +65,11 @@ const update_workflows_1 = require("./update-workflows");
65
65
  const questions_1 = require("./questions");
66
66
  const editor_questions_1 = require("./editor-questions");
67
67
  const questions_helper_1 = require("./questions-helper");
68
- const dockerhub_1 = require("./dockerhub");
68
+ const registry_1 = require("./registry");
69
69
  const manage_users_1 = require("./manage-users");
70
70
  const paths_1 = require("./paths");
71
71
  function questionToPrompt(_a) {
72
- var { valueType, valueLabel, scope } = _a, promptOptions = __rest(_a, ["valueType", "valueLabel", "scope"]);
72
+ var { valueType, valueLabel, legacyValueLabel, scope } = _a, promptOptions = __rest(_a, ["valueType", "valueLabel", "legacyValueLabel", "scope"]);
73
73
  return promptOptions;
74
74
  }
75
75
  const ALL_QUESTIONS = [];
@@ -113,6 +113,14 @@ function getAnswers(existingValues) {
113
113
  });
114
114
  });
115
115
  }
116
+ // The value of a variable that exists, as the initial value of its question.
117
+ // A select question takes the index of the choice.
118
+ function getInitialValue(question, variable) {
119
+ if (question.type === 'select' && Array.isArray(question.choices)) {
120
+ return (0, questions_helper_1.getIndexFromChoices)(question.choices, variable.value);
121
+ }
122
+ return variable.value;
123
+ }
116
124
  function promptAndStoreAnswer(questions, existingValues) {
117
125
  return __awaiter(this, void 0, void 0, function* () {
118
126
  (0, logger_1.log)('');
@@ -123,13 +131,15 @@ function promptAndStoreAnswer(questions, existingValues) {
123
131
  }
124
132
  if (questionWithVariableLabel.valueType === 'VARIABLE') {
125
133
  const existingVariable = (0, utils_1.findExistingValue)(questionWithVariableLabel.valueLabel, 'VARIABLE', questionWithVariableLabel.scope, existingValues);
134
+ // Unlike a secret, the value of a variable can be read, so one that only exists
135
+ // under its previous name is the default of the question
136
+ const legacyVariable = !existingVariable && questionWithVariableLabel.legacyValueLabel
137
+ ? (0, utils_1.findExistingValue)(questionWithVariableLabel.legacyValueLabel, 'VARIABLE', questionWithVariableLabel.scope, existingValues)
138
+ : undefined;
139
+ if (legacyVariable) {
140
+ return Object.assign(Object.assign({}, questionWithVariableLabel), { message: `${questionWithVariableLabel.message} ${kleur_1.default.gray(`(default taken from ${legacyVariable.name}, the previous name of this variable)`)}`, initial: getInitialValue(questionWithVariableLabel, legacyVariable) });
141
+ }
126
142
  if (existingVariable) {
127
- let initial_value = existingVariable.value;
128
- // Get correct initial value for select questions
129
- if (questionWithVariableLabel.type === 'select' &&
130
- Array.isArray(questionWithVariableLabel.choices)) {
131
- initial_value = (0, questions_helper_1.getIndexFromChoices)(questionWithVariableLabel.choices, existingVariable.value);
132
- }
133
143
  return [
134
144
  {
135
145
  name: 'overWrite' + questionWithVariableLabel.name,
@@ -137,12 +147,30 @@ function promptAndStoreAnswer(questions, existingValues) {
137
147
  scope: questionWithVariableLabel.scope,
138
148
  message: `${kleur_1.default.yellow(`Variable ${kleur_1.default.cyan(existingVariable.name)} already exists in Github. Do you want to update it?`)}`
139
149
  },
140
- Object.assign(Object.assign({}, questionWithVariableLabel), { type: ((prev) => prev ? questionWithVariableLabel.type : null), initial: initial_value })
150
+ Object.assign(Object.assign({}, questionWithVariableLabel), { type: ((prev) => prev ? questionWithVariableLabel.type : null), initial: getInitialValue(questionWithVariableLabel, existingVariable) })
141
151
  ];
142
152
  }
143
153
  }
144
154
  if (questionWithVariableLabel.valueType === 'SECRET') {
145
155
  const existingSecret = (0, utils_1.findExistingValue)(questionWithVariableLabel.valueLabel, 'SECRET', questionWithVariableLabel.scope, existingValues);
156
+ // The value of a secret that only exists under its previous name can't be read, so
157
+ // it is left to the secrets migration workflow, unless a new value is entered here
158
+ const legacySecret = !existingSecret && questionWithVariableLabel.legacyValueLabel
159
+ ? (0, utils_1.findExistingValue)(questionWithVariableLabel.legacyValueLabel, 'SECRET', questionWithVariableLabel.scope, existingValues)
160
+ : undefined;
161
+ if (legacySecret) {
162
+ return [
163
+ {
164
+ name: 'overWrite' + questionWithVariableLabel.name,
165
+ type: 'confirm',
166
+ scope: questionWithVariableLabel.scope,
167
+ message: `${kleur_1.default.yellow(`${legacySecret.scope === 'REPOSITORY'
168
+ ? 'Repository secret'
169
+ : 'Secret'} ${kleur_1.default.cyan(legacySecret.name)} already exists in Github under the previous name of ${kleur_1.default.cyan(questionWithVariableLabel.valueLabel)}. The secrets migration workflow copies it. Do you want to enter a new value instead?`)}`
170
+ },
171
+ Object.assign(Object.assign({}, questionWithVariableLabel), { type: ((prev) => prev ? questionWithVariableLabel.type : null) })
172
+ ];
173
+ }
146
174
  if (existingSecret) {
147
175
  return [
148
176
  {
@@ -176,16 +204,39 @@ function promptAndStoreAnswer(questions, existingValues) {
176
204
  return Object.assign(Object.assign({}, Object.fromEntries(existingValuesForQuestions)), result);
177
205
  });
178
206
  }
179
- function promptAndValidateDockerhub(existingValues) {
207
+ /**
208
+ * The value of a secret or variable that is generated rather than asked for, or
209
+ * null when it exists. One that only exists under its previous name counts as
210
+ * existing: the secrets migration workflow copies it, and a generated value
211
+ * would replace the credential that is in use.
212
+ */
213
+ function defineIfMissing(existingValues, name, type, scope, newValue) {
214
+ var _a;
215
+ if ((0, utils_1.findExistingValue)(name, type, scope, existingValues)) {
216
+ return null;
217
+ }
218
+ const legacyName = (_a = ALL_QUESTIONS.find((question) => question.valueLabel === name &&
219
+ question.valueType === type &&
220
+ question.scope === scope)) === null || _a === void 0 ? void 0 : _a.legacyValueLabel;
221
+ if (legacyName &&
222
+ (0, utils_1.findExistingValue)(legacyName, type, scope, existingValues)) {
223
+ (0, logger_1.log)(kleur_1.default.bold().green('✔'), kleur_1.default
224
+ .bold()
225
+ .yellow(`${legacyName} exists, the secrets migration workflow copies it to ${name}`));
226
+ return null;
227
+ }
228
+ return process.env[name] || newValue;
229
+ }
230
+ function promptAndValidateRegistry(existingValues) {
180
231
  return __awaiter(this, void 0, void 0, function* () {
181
- const answers = yield promptAndStoreAnswer(questions_1.dockerhubQuestions, existingValues);
182
- const result = yield (0, dockerhub_1.validateDockerHubCredentials)(answers.dockerhubOrganisation, answers.dockerhubRepository, answers.dockerhubUsername, answers.dockerhubToken);
232
+ const answers = yield promptAndStoreAnswer(questions_1.registryQuestions, existingValues);
233
+ const result = yield (0, registry_1.validateRegistryCredentials)(answers.registryHost, answers.registryOrganisation, answers.registryRepository, answers.registryUsername, answers.registryToken);
183
234
  if (result.status === 'valid' || result.status === 'skipped') {
184
235
  return;
185
236
  }
186
237
  (0, logger_1.error)(`\n${result.status}: ${result.reason || 'Generic error'}\n`);
187
238
  const continueNotValidated = yield confirm({
188
- message: 'Docker Hub credentials are not validated. Continue anyway?',
239
+ message: 'Container registry credentials are not validated. Continue anyway?',
189
240
  default: false
190
241
  });
191
242
  if (!continueNotValidated) {
@@ -193,7 +244,7 @@ function promptAndValidateDockerhub(existingValues) {
193
244
  }
194
245
  });
195
246
  }
196
- ALL_QUESTIONS.push(...questions_1.githubTokenQuestion, ...questions_1.githubOtherQuestions, ...questions_1.dockerhubQuestions, ...questions_1.diskQuestions, ...questions_1.infrastructureQuestions, ...questions_1.backupQuestions, ...questions_1.countryQuestions, ...questions_1.databaseAndMonitoringQuestions, ...questions_1.emailQuestions, ...questions_1.sentryQuestions, ...derived_variables_1.derivedVariables, ...questions_1.metabaseAdminQuestions);
247
+ ALL_QUESTIONS.push(...questions_1.githubTokenQuestion, ...questions_1.githubOtherQuestions, ...questions_1.registryQuestions, ...questions_1.diskQuestions, ...questions_1.infrastructureQuestions, ...questions_1.backupQuestions, ...questions_1.countryQuestions, ...questions_1.databaseAndMonitoringQuestions, ...questions_1.emailQuestions, ...questions_1.sentryQuestions, ...derived_variables_1.derivedVariables, ...questions_1.metabaseAdminQuestions);
197
248
  function runSetupEnvironment() {
198
249
  return __awaiter(this, void 0, void 0, function* () {
199
250
  var _a, _b, _c, _d;
@@ -297,8 +348,8 @@ function runSetupEnvironment() {
297
348
  if (!two_fa_enabled && ['production', 'staging'].includes(environment_type)) {
298
349
  (0, logger_1.warn)('2FA is disabled on a production-like environment. Logins will accept the fixed test code 000000, exposing real citizen data. Only do this if you know what you are doing.');
299
350
  }
300
- (0, logger_1.log)('\n', kleur_1.default.bold().underline('Docker Hub'));
301
- yield promptAndValidateDockerhub(existingValues);
351
+ (0, logger_1.log)('\n', kleur_1.default.bold().underline('Container registry'));
352
+ yield promptAndValidateRegistry(existingValues);
302
353
  (0, logger_1.log)('\n', kleur_1.default.bold().underline('Kubernetes & Runtime'));
303
354
  const infrastructure = yield promptAndStoreAnswer(questions_1.infrastructureQuestions, existingValues);
304
355
  const kubeWorkerNodes = infrastructure.kubeWorkerNodes
@@ -478,11 +529,7 @@ function runSetupEnvironment() {
478
529
  * Variables the user doesn't need to set manually
479
530
  */
480
531
  const answerOrExisting = (variable, existingValue, fn) => fn(variable || (existingValue === null || existingValue === void 0 ? void 0 : existingValue.value)) || '';
481
- function findExistingOrDefine(name, type, scope, newValue) {
482
- return (0, utils_1.findExistingValue)(name, type, scope, existingValues)
483
- ? null
484
- : process.env[name] || newValue;
485
- }
532
+ const findExistingOrDefine = (name, type, scope, newValue) => defineIfMissing(existingValues, name, type, scope, newValue);
486
533
  const derivedUpdates = [
487
534
  {
488
535
  name: 'GH_ENCRYPTION_PASSWORD',
@@ -542,17 +589,17 @@ function runSetupEnvironment() {
542
589
  scope: 'ENVIRONMENT'
543
590
  },
544
591
  {
545
- name: 'MINIO_ROOT_USER',
592
+ name: 'S3_ADMIN_ACCESS_KEY',
546
593
  type: 'SECRET',
547
- didExist: (0, utils_1.findExistingValue)('MINIO_ROOT_USER', 'SECRET', 'ENVIRONMENT', existingValues),
548
- value: findExistingOrDefine('MINIO_ROOT_USER', 'SECRET', 'ENVIRONMENT', (0, utils_1.generateLongPassword)()),
594
+ didExist: (0, utils_1.findExistingValue)('S3_ADMIN_ACCESS_KEY', 'SECRET', 'ENVIRONMENT', existingValues),
595
+ value: findExistingOrDefine('S3_ADMIN_ACCESS_KEY', 'SECRET', 'ENVIRONMENT', (0, utils_1.generateLongPassword)()),
549
596
  scope: 'ENVIRONMENT'
550
597
  },
551
598
  {
552
- name: 'MINIO_ROOT_PASSWORD',
599
+ name: 'S3_ADMIN_SECRET_KEY',
553
600
  type: 'SECRET',
554
- didExist: (0, utils_1.findExistingValue)('MINIO_ROOT_PASSWORD', 'SECRET', 'ENVIRONMENT', existingValues),
555
- value: findExistingOrDefine('MINIO_ROOT_PASSWORD', 'SECRET', 'ENVIRONMENT', (0, utils_1.generateLongPassword)()),
601
+ didExist: (0, utils_1.findExistingValue)('S3_ADMIN_SECRET_KEY', 'SECRET', 'ENVIRONMENT', existingValues),
602
+ value: findExistingOrDefine('S3_ADMIN_SECRET_KEY', 'SECRET', 'ENVIRONMENT', (0, utils_1.generateLongPassword)()),
556
603
  scope: 'ENVIRONMENT'
557
604
  },
558
605
  {
@@ -681,7 +728,8 @@ function runSetupEnvironment() {
681
728
  const newVariables = updates.filter((update) => update.type === 'VARIABLE' && !update.didExist);
682
729
  const updatedVariables = updates.filter((update) => update.type === 'VARIABLE' && Boolean(update.didExist));
683
730
  const unknownVariables = existingValues.filter((value) => {
684
- return !ALL_QUESTIONS.find((question) => question.valueLabel === value.name &&
731
+ return !ALL_QUESTIONS.find((question) => (question.valueLabel === value.name ||
732
+ question.legacyValueLabel === value.name) &&
685
733
  question.valueType === value.type &&
686
734
  question.scope === value.scope);
687
735
  });
@@ -339,6 +339,7 @@ __export(events_exports, {
339
339
  getActionAnnotation: () => getActionAnnotation,
340
340
  getActionAnnotationFields: () => getActionAnnotationFields,
341
341
  getActionConfig: () => getActionConfig,
342
+ getActionForm: () => getActionForm,
342
343
  getActionFormFields: () => getActionFormFields,
343
344
  getActionReview: () => getActionReview,
344
345
  getActionReviewFields: () => getActionReviewFields,
@@ -485,6 +486,8 @@ __export(events_exports, {
485
486
  timePeriodToDateRange: () => timePeriodToDateRange,
486
487
  toClientAdministrativeArea: () => toClientAdministrativeArea,
487
488
  toClientLocation: () => toClientLocation,
489
+ toNotificationForm: () => toNotificationForm,
490
+ toNotificationReview: () => toNotificationReview,
488
491
  toPlainDate: () => toPlainDate,
489
492
  todayISO: () => todayISO,
490
493
  user: () => user,
@@ -1525,7 +1528,7 @@ var z14 = __toESM(require("zod/v4"));
1525
1528
  // ../commons/src/documents.ts
1526
1529
  var z11 = __toESM(require("zod/v4"));
1527
1530
  var FullDocumentUrl = z11.string().brand("FullDocumentUrl").describe(
1528
- "A full url with protocol, host, bucket name, starting from the root of the S3 server, https://minio.opencrvs.com/bucket-name/document-id.jpg"
1531
+ "A full url with protocol, host, bucket name, starting from the root of the S3 server, https://s3.opencrvs.com/bucket-name/document-id.jpg"
1529
1532
  );
1530
1533
  var FullDocumentPath = z11.string().overwrite((val) => val.startsWith("/") ? val : `/${val}`).meta({ effectType: "input", type: "string" }).describe(
1531
1534
  "A full absolute path with bucket name, starting from the root of the S3 server, /bucket-name/document-id.jpg"
@@ -3546,11 +3549,11 @@ var ReadActionConfig = ActionConfigBase.extend(
3546
3549
  var NotifyConfig = ActionConfigBase.extend(
3547
3550
  z25.object({
3548
3551
  type: z25.literal(ActionType.NOTIFY),
3549
- notificationForm: DeclarationFormConfig.optional().describe(
3550
- "Notification form configuration. Its fields must be a subset of the declaration form fields, with matching types. The values submitted on the notification form pre-fill the declaration. If not defined, the declare action's declaration is used (with all fields optional)."
3552
+ notificationForm: DeclarationFormConfig.describe(
3553
+ "Notification form configuration. Its fields must be a subset of the declaration form fields, with matching types. The values submitted on the notification form pre-fill the declaration."
3551
3554
  ),
3552
3555
  review: DeclarationReviewConfig.describe(
3553
- "Review page configuration for the notify action. Values of its fields are stored as the NOTIFY action annotation. If not defined, defineConfig generates it from the declare action's review (with all fields optional)."
3556
+ "Review page configuration for the notify action. Values of its fields are stored as the NOTIFY action annotation."
3554
3557
  ),
3555
3558
  form: actionConfirmationForm
3556
3559
  }).shape
@@ -6298,34 +6301,6 @@ function areCertificateConditionsMet(conditions, values) {
6298
6301
  });
6299
6302
  }
6300
6303
 
6301
- // ../commons/src/events/notificationFormFallback.ts
6302
- function toOptionalField(field3) {
6303
- const { validation: _validation, ...rest } = field3;
6304
- if (rest.type === FieldType.FIELD_GROUP && "fields" in rest) {
6305
- return {
6306
- ...rest,
6307
- required: false,
6308
- fields: rest.fields.map(toOptionalField)
6309
- };
6310
- }
6311
- return { ...rest, required: false };
6312
- }
6313
- function deriveNotificationForm(declaration) {
6314
- return {
6315
- ...declaration,
6316
- pages: declaration.pages.map((page) => ({
6317
- ...page,
6318
- fields: page.fields.map(toOptionalField)
6319
- }))
6320
- };
6321
- }
6322
- function generateNotifyReview(declareReview) {
6323
- return {
6324
- ...declareReview,
6325
- fields: declareReview.fields.map(toOptionalField)
6326
- };
6327
- }
6328
-
6329
6304
  // ../commons/src/events/utils.ts
6330
6305
  var import_date_fns3 = require("date-fns");
6331
6306
  function ageToDate(age, asOfDate) {
@@ -6349,31 +6324,29 @@ function getDeclarationPages(configuration) {
6349
6324
  function getDeclarationFields(configuration) {
6350
6325
  return getDeclarationPages(configuration).flatMap(({ fields }) => fields);
6351
6326
  }
6352
- function getConfiguredNotificationForm(configuration) {
6327
+ function findNotificationForm(configuration) {
6353
6328
  const notifyAction = configuration.actions.find(
6354
6329
  (action) => action.type === ActionType.NOTIFY
6355
6330
  );
6356
6331
  return notifyAction?.type === ActionType.NOTIFY ? notifyAction.notificationForm : void 0;
6357
6332
  }
6358
- var derivedNotificationForms = /* @__PURE__ */ new WeakMap();
6359
6333
  function getNotificationForm(configuration) {
6360
- const configured = getConfiguredNotificationForm(configuration);
6361
- if (configured) {
6362
- return configured;
6363
- }
6364
- const cached = derivedNotificationForms.get(configuration);
6365
- if (cached) {
6366
- return cached;
6334
+ const notificationForm = findNotificationForm(configuration);
6335
+ if (!notificationForm) {
6336
+ throw new Error(
6337
+ `Event '${configuration.id}' has no ${ActionType.NOTIFY} action.`
6338
+ );
6367
6339
  }
6368
- const derived = deriveNotificationForm(getDeclaration(configuration));
6369
- derivedNotificationForms.set(configuration, derived);
6370
- return derived;
6340
+ return notificationForm;
6371
6341
  }
6372
6342
  function getNotificationFields(configuration) {
6373
6343
  return getNotificationForm(configuration).pages.flatMap(
6374
6344
  ({ fields }) => fields
6375
6345
  );
6376
6346
  }
6347
+ function getActionForm(configuration, actionType) {
6348
+ return actionType === ActionType.NOTIFY ? getNotificationForm(configuration) : getDeclaration(configuration);
6349
+ }
6377
6350
  function isActionConfigType(type) {
6378
6351
  return actionConfigTypes.has(type);
6379
6352
  }
@@ -6634,10 +6607,7 @@ function isWriteAction(actionType) {
6634
6607
  var findAllFields = (config) => {
6635
6608
  return (0, import_lodash4.flattenDeep)([
6636
6609
  ...getDeclarationFields(config),
6637
- // Only a configured notification form: a derived one repeats the declaration fields.
6638
- ...getConfiguredNotificationForm(config)?.pages.flatMap(
6639
- ({ fields }) => fields
6640
- ) ?? [],
6610
+ ...findNotificationForm(config)?.pages.flatMap(({ fields }) => fields) ?? [],
6641
6611
  ...getAllAnnotationFields(config)
6642
6612
  ]);
6643
6613
  };
@@ -7096,9 +7066,11 @@ function validateDeclarationGivenExactlyOnce(config, ctx) {
7096
7066
  }
7097
7067
  }
7098
7068
  function validateNotificationForm(event2, ctx) {
7099
- const declarationFields = getDeclarationFields(event2);
7069
+ const declarationFields = getDeclarationPages(event2).flatMap(
7070
+ (page) => page.fields.map((field3) => ({ field: field3, pageId: page.id }))
7071
+ );
7100
7072
  event2.actions.forEach((action, actionIndex) => {
7101
- if (action.type !== ActionType.NOTIFY || !action.notificationForm) {
7073
+ if (action.type !== ActionType.NOTIFY) {
7102
7074
  return;
7103
7075
  }
7104
7076
  action.notificationForm.pages.forEach((page, pageIndex) => {
@@ -7113,7 +7085,7 @@ function validateNotificationForm(event2, ctx) {
7113
7085
  fieldIndex
7114
7086
  ];
7115
7087
  const matchingFields = declarationFields.filter(
7116
- ({ id }) => id === field3.id
7088
+ (declarationField) => declarationField.field.id === field3.id
7117
7089
  );
7118
7090
  if (matchingFields.length === 0) {
7119
7091
  ctx.addIssue({
@@ -7123,10 +7095,13 @@ function validateNotificationForm(event2, ctx) {
7123
7095
  });
7124
7096
  return;
7125
7097
  }
7126
- if (!matchingFields.some(({ type }) => type === field3.type)) {
7098
+ if (!matchingFields.some(
7099
+ (declarationField) => declarationField.field.type === field3.type
7100
+ )) {
7101
+ const [declarationField] = matchingFields;
7127
7102
  ctx.addIssue({
7128
7103
  code: "custom",
7129
- message: `Notification form field '${field3.id}' is of type ${field3.type}, but the declaration form field with the same id in event '${event2.id}' is of type ${matchingFields[0].type}.`,
7104
+ message: `Notification form field '${field3.id}' on page '${page.id}' is of type ${field3.type}, but the declaration form field with the same id in event '${event2.id}' (${ActionType.DECLARE} declaration, page '${declarationField.pageId}') is of type ${declarationField.field.type}.`,
7130
7105
  path
7131
7106
  });
7132
7107
  }
@@ -7866,57 +7841,44 @@ function moveDeclarationToDeclareAction({
7866
7841
  )
7867
7842
  };
7868
7843
  }
7869
- function generateNotificationFormFallback(config) {
7870
- const declareAction = config.actions.find(
7871
- (action) => action.type === ActionType.DECLARE
7872
- );
7873
- const notifyAction = config.actions.find(
7874
- (action) => action.type === ActionType.NOTIFY
7875
- );
7876
- if (!notifyAction?.notificationForm) {
7877
- console.warn(
7878
- `Event '${config.id}' has no ${ActionType.NOTIFY} form. Using the ${ActionType.DECLARE} form with all fields optional. Configure \`actions[${ActionType.NOTIFY}].notificationForm\`. This fallback will be removed in a future release.`
7879
- );
7880
- }
7881
- if (notifyAction?.review) {
7882
- return config;
7883
- }
7884
- if (!declareAction?.declaration) {
7885
- throw new Error(
7886
- `Event '${config.id}' has no ${ActionType.DECLARE} form. Configure \`actions[${ActionType.DECLARE}].declaration\`.`
7887
- );
7844
+ var EventConfigDefinition = z43.custom().superRefine((config, ctx) => {
7845
+ if (validateExactlyOneDeclareAction(config, ctx)) {
7846
+ validateDeclarationGivenExactlyOnce(config, ctx);
7888
7847
  }
7889
- const review = generateNotifyReview(declareAction.review);
7890
- if (notifyAction) {
7848
+ }).transform(moveDeclarationToDeclareAction).pipe(EventConfig);
7849
+ var defineConfig = (config) => EventConfigDefinition.parse(config);
7850
+
7851
+ // ../commons/src/events/toNotificationForm.ts
7852
+ function toOptionalField(field3) {
7853
+ const { validation: _validation, ...rest } = field3;
7854
+ if (rest.type === FieldType.FIELD_GROUP && "fields" in rest) {
7891
7855
  return {
7892
- ...config,
7893
- actions: config.actions.map(
7894
- (action) => action === notifyAction ? { ...notifyAction, review } : action
7895
- )
7856
+ ...rest,
7857
+ required: false,
7858
+ fields: rest.fields.map(toOptionalField)
7896
7859
  };
7897
7860
  }
7898
- const notifyFromDeclare = {
7899
- type: ActionType.NOTIFY,
7900
- label: declareAction.label,
7901
- icon: declareAction.icon,
7902
- conditionals: declareAction.conditionals,
7903
- flags: declareAction.flags,
7904
- supportingCopy: declareAction.dialogCopy?.notify,
7905
- review
7861
+ return { ...rest, required: false };
7862
+ }
7863
+ function toNotificationForm(declaration) {
7864
+ return {
7865
+ ...declaration,
7866
+ pages: declaration.pages.map((page) => ({
7867
+ ...page,
7868
+ fields: page.fields.map(
7869
+ toOptionalField
7870
+ )
7871
+ }))
7906
7872
  };
7873
+ }
7874
+ function toNotificationReview(review) {
7907
7875
  return {
7908
- ...config,
7909
- actions: config.actions.flatMap(
7910
- (action) => action === declareAction ? [notifyFromDeclare, action] : [action]
7876
+ ...review,
7877
+ fields: review.fields.map(
7878
+ toOptionalField
7911
7879
  )
7912
7880
  };
7913
7881
  }
7914
- var EventConfigDefinition = z43.custom().superRefine((config, ctx) => {
7915
- if (validateExactlyOneDeclareAction(config, ctx)) {
7916
- validateDeclarationGivenExactlyOnce(config, ctx);
7917
- }
7918
- }).transform(moveDeclarationToDeclareAction).transform(generateNotificationFormFallback).pipe(EventConfig);
7919
- var defineConfig = (config) => EventConfigDefinition.parse(config);
7920
7882
 
7921
7883
  // ../commons/src/events/transactions.ts
7922
7884
  function generateTransactionId() {
@@ -9233,6 +9195,8 @@ var tennisClubMembershipEvent = defineConfig({
9233
9195
  description: "This is shown as the action name anywhere the user can trigger the action from",
9234
9196
  id: "event.tennis-club-membership.action.notify.label"
9235
9197
  },
9198
+ notificationForm: toNotificationForm(TENNIS_CLUB_DECLARATION_FORM),
9199
+ review: toNotificationReview(TENNIS_CLUB_DECLARATION_REVIEW),
9236
9200
  flags: [
9237
9201
  {
9238
9202
  id: "health-worker-notified",
@@ -11943,8 +11907,7 @@ function withDeclaration(configuration, declaration) {
11943
11907
  return { ...action, declaration };
11944
11908
  }
11945
11909
  if (action.type === ActionType.NOTIFY) {
11946
- const { notificationForm: _notificationForm, ...notifyAction } = action;
11947
- return notifyAction;
11910
+ return { ...action, notificationForm: toNotificationForm(declaration) };
11948
11911
  }
11949
11912
  return action;
11950
11913
  })
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Codemod: Give every NOTIFY action the `notificationForm` and `review` it
3
+ * requires.
4
+ *
5
+ * Usage:
6
+ * ts-node -r tsconfig-paths/register src/migrations/add-notify-config.ts
7
+ *
8
+ * Why:
9
+ * As of v2.2 a NOTIFY action must configure its `notificationForm` and
10
+ * `review`. A notification form is validated like any form, so a plain copy
11
+ * of the declaration would make NOTIFY reject incomplete records.
12
+ * `toNotificationForm` and `toNotificationReview` copy the DECLARE form and
13
+ * review with every field optional, which keeps NOTIFY accepting them.
14
+ *
15
+ * What it does:
16
+ * - Scans all TypeScript files under `src/`
17
+ * - Finds the NOTIFY action in the `actions` of every call to the toolkit's
18
+ * `defineConfig`
19
+ * - Adds `notificationForm: toNotificationForm(<DECLARE declaration>)` and
20
+ * `review: toNotificationReview(<DECLARE review>)` when missing, after its
21
+ * `label` (or its `type` when it has no `label`)
22
+ * - Adds the helpers to the file's `@opencrvs/toolkit/events` import
23
+ * - Logs events without a NOTIFY action, which cannot be notified
24
+ * - Logs, without changing, configs it cannot rewrite safely: a config not
25
+ * given as an object literal, `actions` that is not an array literal, a
26
+ * NOTIFY action not written inline, and a DECLARE `declaration` or
27
+ * `review` not given as a name (e.g. written inline)
28
+ * - Saves the modified files in-place
29
+ */
30
+ import { SourceFile } from 'ts-morph';
31
+ /**
32
+ * Adds the missing `notificationForm` and `review` to the NOTIFY action of
33
+ * every toolkit `defineConfig` call in the file.
34
+ *
35
+ * @returns the number of NOTIFY actions rewritten.
36
+ */
37
+ export declare function addNotifyConfig(sourceFile: SourceFile): number;
38
+ declare function main(): Promise<void>;
39
+ export { main };
40
+ //# sourceMappingURL=add-notify-config.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"add-notify-config.d.ts","sourceRoot":"","sources":["../../src/migrations/add-notify-config.ts"],"names":[],"mappings":"AAWA;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AAEH,OAAO,EAOL,UAAU,EAEX,MAAM,UAAU,CAAA;AA8IjB;;;;;GAKG;AACH,wBAAgB,eAAe,CAAC,UAAU,EAAE,UAAU,GAAG,MAAM,CAqG9D;AAED,iBAAe,IAAI,kBA6ClB;AAED,OAAO,EAAE,IAAI,EAAE,CAAA"}