@opencrvs/toolkit 2.1.0-rc.99061f0 → 2.1.0-rc.9b7a167

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 (88) hide show
  1. package/build.sh +9 -1
  2. package/create-countryconfig/index.js +412 -59
  3. package/create-countryconfig/node_modules/.bin/degit +21 -0
  4. package/create-countryconfig/package.json +4 -1
  5. package/dist/application-config/index.js +341 -274
  6. package/dist/authentication/index.d.ts +67 -0
  7. package/dist/authentication/index.d.ts.map +1 -0
  8. package/dist/authentication/index.js +750 -0
  9. package/dist/cli.js +1608 -84
  10. package/dist/commons/api/router.d.ts +691 -76
  11. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  12. package/dist/commons/conditionals/validate.d.ts +16 -5
  13. package/dist/commons/events/ActionDocument.d.ts +5 -11
  14. package/dist/commons/events/ActionInput.d.ts +4 -4
  15. package/dist/commons/events/ActionStatus.d.ts +14 -0
  16. package/dist/commons/events/AdvancedSearchConfig.d.ts +24 -0
  17. package/dist/commons/events/AuditLog.d.ts +147 -0
  18. package/dist/commons/events/EventConfig.d.ts +3 -0
  19. package/dist/commons/events/EventDocument.d.ts +470 -2
  20. package/dist/commons/events/EventIndex.d.ts +3 -26
  21. package/dist/commons/events/EventMetadata.d.ts +1 -11
  22. package/dist/commons/events/EventStatus.d.ts +19 -0
  23. package/dist/commons/events/FieldConfig.d.ts +88 -53
  24. package/dist/commons/events/FieldTypeMapping.d.ts +27 -27
  25. package/dist/commons/events/FieldValue.d.ts +2 -2
  26. package/dist/commons/events/Flag.d.ts +42 -0
  27. package/dist/commons/events/PlainDate.d.ts +8 -0
  28. package/dist/commons/events/SummaryConfig.d.ts +249 -0
  29. package/dist/commons/events/WorkqueueConfig.d.ts +17 -14
  30. package/dist/commons/events/event.d.ts +12 -0
  31. package/dist/commons/events/index.d.ts +1 -0
  32. package/dist/commons/events/locationPayloads.d.ts +95 -0
  33. package/dist/commons/events/locations.d.ts +165 -26
  34. package/dist/commons/events/mocks.test.utils.d.ts +30 -0
  35. package/dist/commons/events/test.utils.d.ts +8 -4
  36. package/dist/commons/events/utils.d.ts +2 -2
  37. package/dist/commons/notification/UserNotifications.d.ts +28 -13
  38. package/dist/commons/notification/dispatch.d.ts +10 -0
  39. package/dist/commons/notification/index.d.ts +1 -0
  40. package/dist/conditionals/index.js +328 -58
  41. package/dist/csv.d.ts +25 -0
  42. package/dist/csv.d.ts.map +1 -0
  43. package/dist/csv.js +120 -0
  44. package/dist/environment/logger.d.ts +12 -3
  45. package/dist/environment/logger.d.ts.map +1 -1
  46. package/dist/environment/questions.d.ts.map +1 -1
  47. package/dist/environment/questions.js +20 -14
  48. package/dist/environment/setup-environment.js +1 -1
  49. package/dist/events/index.js +3688 -3293
  50. package/dist/migrations/v2.0/checkout-upstream-files.d.ts +2 -2
  51. package/dist/migrations/v2.0/checkout-upstream-files.d.ts.map +1 -1
  52. package/dist/migrations/v2.0/checkout-upstream-files.js +2 -2
  53. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts +3 -0
  54. package/dist/migrations/v2.1/add-recovery-link-notifications.d.ts.map +1 -0
  55. package/dist/migrations/v2.1/add-recovery-link-notifications.js +511 -0
  56. package/dist/migrations/v2.1/add-translations.d.ts +9 -0
  57. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -0
  58. package/dist/migrations/v2.1/add-translations.js +213 -0
  59. package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
  60. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  61. package/dist/migrations/v2.1/enable-telemetry.js +438 -0
  62. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  63. package/dist/migrations/v2.1/index.js +1058 -0
  64. package/dist/notification/index.js +1833 -1426
  65. package/dist/scopes/index.d.ts +327 -32
  66. package/dist/scopes/index.js +329 -58
  67. package/dist/telemetry/index.d.ts +45 -0
  68. package/dist/telemetry/index.d.ts.map +1 -0
  69. package/dist/telemetry/index.js +39 -0
  70. package/dist/templates/charts-values/opencrvs-services/values.yaml +4 -3
  71. package/dist/templates/charts-values/opentelemetry/values.yaml +95 -0
  72. package/dist/templates/charts-values/traefik/values.yaml +23 -9
  73. package/dist/templates/inventory/inventory.template.yml +1 -3
  74. package/dist/translations/check.d.ts +19 -0
  75. package/dist/translations/check.d.ts.map +1 -0
  76. package/dist/translations/check.js +127 -0
  77. package/dist/verify/endpoints.d.ts +2 -0
  78. package/dist/verify/endpoints.d.ts.map +1 -0
  79. package/dist/verify/endpoints.js +345 -0
  80. package/opencrvs-toolkit-2.1.0-rc.9b7a167.tgz +0 -0
  81. package/package.json +11 -5
  82. package/tsconfig.build.json +11 -0
  83. package/tsconfig.build.tsbuildinfo +1 -0
  84. package/tsconfig.json +3 -0
  85. package/dist/templates/inventory/production.example.yml +0 -77
  86. package/dist/templates/inventory/qa.example.yml +0 -48
  87. package/opencrvs-toolkit-2.1.0-rc.99061f0.tgz +0 -0
  88. package/tsconfig.tsbuildinfo +0 -1
@@ -0,0 +1,750 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/authentication/index.ts
31
+ var authentication_exports = {};
32
+ __export(authentication_exports, {
33
+ EncodedScope: () => EncodedScope,
34
+ JurisdictionFilter: () => JurisdictionFilter,
35
+ RecordScopeTypeV2: () => RecordScopeTypeV2,
36
+ RecordScopeV2: () => RecordScopeV2,
37
+ ResolvedRecordScopeV2: () => ResolvedRecordScopeV2,
38
+ SERVICE_USER_ID: () => SERVICE_USER_ID,
39
+ Scope: () => Scope,
40
+ ScopeOptionKey: () => ScopeOptionKey,
41
+ ScopeType: () => ScopeType,
42
+ ScopesWithDeclaredOptions: () => ScopesWithDeclaredOptions,
43
+ ScopesWithFullOptions: () => ScopesWithFullOptions,
44
+ ScopesWithPlaceEventOptions: () => ScopesWithPlaceEventOptions,
45
+ TokenUserType: () => TokenUserType,
46
+ TokenWithBearer: () => TokenWithBearer,
47
+ UserFilter: () => UserFilter,
48
+ UserScopeV2: () => UserScopeV2,
49
+ canUserCreateEvent: () => canUserCreateEvent,
50
+ decodeScope: () => decodeScope,
51
+ defineRoles: () => defineRoles,
52
+ defineScopes: () => defineScopes,
53
+ encodeScope: () => encodeScope,
54
+ getAcceptedScopesByType: () => getAcceptedScopesByType,
55
+ getAcceptedScopesFromToken: () => getAcceptedScopesFromToken,
56
+ getScopeOptionValue: () => getScopeOptionValue,
57
+ getScopes: () => getScopes,
58
+ getTokenPayload: () => getTokenPayload,
59
+ getUserId: () => getUserId,
60
+ getUserIdFromToken: () => getUserIdFromToken,
61
+ getUserTypeFromToken: () => getUserTypeFromToken,
62
+ hasAnyScope: () => hasAnyScope,
63
+ hasScope: () => hasScope,
64
+ isCustomActionScope: () => isCustomActionScope,
65
+ isServiceToken: () => isServiceToken,
66
+ scopeUsesDeclaredOptions: () => scopeUsesDeclaredOptions,
67
+ scopeUsesFullOptions: () => scopeUsesFullOptions,
68
+ scopeUsesPrintCertifiedCopiesOptions: () => scopeUsesPrintCertifiedCopiesOptions,
69
+ scopeUsesRoleOptions: () => scopeUsesRoleOptions,
70
+ setBearerForToken: () => setBearerForToken
71
+ });
72
+ module.exports = __toCommonJS(authentication_exports);
73
+ var z9 = __toESM(require("zod/v4"));
74
+
75
+ // ../commons/src/authentication.ts
76
+ var import_jwt_decode = __toESM(require("jwt-decode"));
77
+ var z8 = __toESM(require("zod/v4"));
78
+
79
+ // ../commons/src/scopes.ts
80
+ var z7 = __toESM(require("zod/v4"));
81
+ var qs = __toESM(require("qs"));
82
+
83
+ // ../commons/src/uuid.ts
84
+ var import_uuid = require("uuid");
85
+ var z = __toESM(require("zod/v4"));
86
+ var UUID = z.uuid().brand("UUID");
87
+
88
+ // ../commons/src/events/ActionType.ts
89
+ var z2 = __toESM(require("zod/v4"));
90
+ var ActionType = {
91
+ // Pre-declaration actions
92
+ DELETE: "DELETE",
93
+ CREATE: "CREATE",
94
+ NOTIFY: "NOTIFY",
95
+ // Declaration actions
96
+ DECLARE: "DECLARE",
97
+ REGISTER: "REGISTER",
98
+ EDIT: "EDIT",
99
+ // Declaration system actions. Non-configurable.
100
+ DUPLICATE_DETECTED: "DUPLICATE_DETECTED",
101
+ REJECT: "REJECT",
102
+ // REJECT_DECLARATION
103
+ MARK_AS_DUPLICATE: "MARK_AS_DUPLICATE",
104
+ MARK_AS_NOT_DUPLICATE: "MARK_AS_NOT_DUPLICATE",
105
+ ARCHIVE: "ARCHIVE",
106
+ UNARCHIVE: "UNARCHIVE",
107
+ // Record actions
108
+ PRINT_CERTIFICATE: "PRINT_CERTIFICATE",
109
+ REQUEST_CORRECTION: "REQUEST_CORRECTION",
110
+ REJECT_CORRECTION: "REJECT_CORRECTION",
111
+ APPROVE_CORRECTION: "APPROVE_CORRECTION",
112
+ // General actions
113
+ READ: "READ",
114
+ ASSIGN: "ASSIGN",
115
+ UNASSIGN: "UNASSIGN",
116
+ // Custom action
117
+ CUSTOM: "CUSTOM"
118
+ };
119
+ var ConfirmableActions = [
120
+ ActionType.NOTIFY,
121
+ ActionType.DECLARE,
122
+ ActionType.EDIT,
123
+ ActionType.REGISTER,
124
+ ActionType.REJECT,
125
+ ActionType.ARCHIVE,
126
+ ActionType.UNARCHIVE,
127
+ ActionType.PRINT_CERTIFICATE,
128
+ ActionType.REQUEST_CORRECTION,
129
+ ActionType.APPROVE_CORRECTION,
130
+ ActionType.REJECT_CORRECTION,
131
+ ActionType.CUSTOM
132
+ ];
133
+ var ActionTypes = z2.enum([
134
+ "DELETE",
135
+ "CREATE",
136
+ "NOTIFY",
137
+ "DECLARE",
138
+ "EDIT",
139
+ "REGISTER",
140
+ "DUPLICATE_DETECTED",
141
+ "REJECT",
142
+ "MARK_AS_DUPLICATE",
143
+ "MARK_AS_NOT_DUPLICATE",
144
+ "ARCHIVE",
145
+ "UNARCHIVE",
146
+ "PRINT_CERTIFICATE",
147
+ "REQUEST_CORRECTION",
148
+ "REJECT_CORRECTION",
149
+ "APPROVE_CORRECTION",
150
+ "READ",
151
+ "ASSIGN",
152
+ "UNASSIGN",
153
+ "CUSTOM"
154
+ ]);
155
+ var declarationActionValues = [
156
+ ActionTypes.enum.DECLARE,
157
+ ActionTypes.enum.EDIT,
158
+ ActionTypes.enum.REGISTER,
159
+ ActionTypes.enum.NOTIFY,
160
+ ActionTypes.enum.DUPLICATE_DETECTED
161
+ ];
162
+ var DeclarationActions = ActionTypes.extract(declarationActionValues);
163
+ var declarationUpdateActionValues = [
164
+ ...declarationActionValues,
165
+ ActionTypes.enum.REQUEST_CORRECTION
166
+ ];
167
+ var DeclarationUpdateActions = ActionTypes.extract(
168
+ declarationUpdateActionValues
169
+ );
170
+ var annotationActions = ActionTypes.exclude(declarationActionValues);
171
+ var writeActions = ActionTypes.exclude([
172
+ ActionType.CREATE,
173
+ ActionType.READ,
174
+ ActionType.ASSIGN,
175
+ ActionType.UNASSIGN
176
+ ]);
177
+ var WorkqueueActionType = ActionTypes.extract([
178
+ ActionType.READ,
179
+ ActionType.DELETE,
180
+ ActionType.DECLARE,
181
+ ActionType.REGISTER,
182
+ ActionType.EDIT,
183
+ ActionType.REJECT,
184
+ ActionType.MARK_AS_DUPLICATE,
185
+ ActionType.ARCHIVE,
186
+ ActionType.UNARCHIVE,
187
+ ActionType.PRINT_CERTIFICATE,
188
+ ActionType.REQUEST_CORRECTION
189
+ ]);
190
+ var META_ACTIONS = [
191
+ ActionType.ASSIGN,
192
+ ActionType.UNASSIGN,
193
+ ActionType.READ
194
+ ];
195
+
196
+ // ../commons/src/events/ActionStatus.ts
197
+ var ActionStatus = {
198
+ Requested: "Requested",
199
+ Accepted: "Accepted",
200
+ Rejected: "Rejected"
201
+ };
202
+
203
+ // ../commons/src/events/Flag.ts
204
+ var z5 = __toESM(require("zod/v4"));
205
+
206
+ // ../commons/src/events/TranslationConfig.ts
207
+ var z3 = __toESM(require("zod/v4"));
208
+ var TranslationConfig = z3.object({
209
+ id: z3.string().describe(
210
+ "The identifier of the translation referred in translation CSV files"
211
+ ),
212
+ defaultMessage: z3.string().describe("Default translation message"),
213
+ description: z3.string().describe(
214
+ "Describe the translation for a translator to be able to identify it."
215
+ )
216
+ }).meta({
217
+ description: "Translation configuration",
218
+ id: "TranslationConfig"
219
+ });
220
+
221
+ // ../commons/src/events/Conditional.ts
222
+ var z4 = __toESM(require("zod/v4"));
223
+ var Conditional = z4.any().describe("JSONSchema").meta({
224
+ description: "JSON schema conditional configuration",
225
+ id: "Conditional"
226
+ });
227
+ var ConditionalType = {
228
+ SHOW: "SHOW",
229
+ ENABLE: "ENABLE",
230
+ DISPLAY_ON_REVIEW: "DISPLAY_ON_REVIEW"
231
+ };
232
+ var ShowConditional = z4.object({
233
+ type: z4.literal(ConditionalType.SHOW),
234
+ conditional: Conditional
235
+ }).describe(
236
+ "If 'SHOW' conditional is defined, the component is shown to the user only if the condition is met"
237
+ );
238
+ var EnableConditional = z4.object({
239
+ type: z4.literal(ConditionalType.ENABLE),
240
+ conditional: Conditional
241
+ }).describe(
242
+ "If 'ENABLE' conditional is defined, the component is enabled only if the condition is met"
243
+ );
244
+ var ActionConditional = z4.discriminatedUnion("type", [
245
+ // Action can be shown / hidden
246
+ ShowConditional,
247
+ // Action can be shown to the user in the list but as disabled
248
+ EnableConditional
249
+ ]).meta({
250
+ id: "ActionConditional",
251
+ description: "Conditional gating whether an action is shown (SHOW) or enabled (ENABLE). When omitted from an action, the action is shown and enabled for everyone."
252
+ });
253
+ var DisplayOnReviewConditional = z4.object({
254
+ type: z4.literal(ConditionalType.DISPLAY_ON_REVIEW),
255
+ conditional: Conditional
256
+ }).describe(
257
+ "If 'DISPLAY_ON_REVIEW' conditional is defined, the component is shown on the review page only if both the 'DISPLAY_ON_REVIEW' and 'SHOW' conditions are met. This should only be used for fields within declaration forms, as they are the only ones with review pages."
258
+ );
259
+ var FieldConditional = z4.discriminatedUnion("type", [
260
+ // Field input can be shown / hidden
261
+ ShowConditional,
262
+ // Field input can be shown to the user but as disabled
263
+ EnableConditional,
264
+ // Field output can be shown / hidden on the review page
265
+ DisplayOnReviewConditional
266
+ ]).meta({
267
+ id: "FieldConditional",
268
+ description: "Conditional gating whether a form field is shown (SHOW), enabled (ENABLE), or displayed on the review page (DISPLAY_ON_REVIEW). When omitted, the field is shown and enabled for everyone, and is displayed on review whenever it has a value."
269
+ });
270
+
271
+ // ../commons/src/events/Flag.ts
272
+ var InherentFlags = {
273
+ INCOMPLETE: "incomplete",
274
+ REJECTED: "rejected",
275
+ CORRECTION_REQUESTED: "correction-requested",
276
+ POTENTIAL_DUPLICATE: "potential-duplicate",
277
+ /**
278
+ * This flag is set by the Edit-action and removed after the declaration or registration.
279
+ * A record should never stay with the EDIT_IN_PROGRESS flag, since it should always be declared or registered right after.
280
+ *
281
+ * We only use this flag to determine that a NOTIFY, DECLARE or REGISTER action is allowed next.
282
+ */
283
+ EDIT_IN_PROGRESS: "edit-in-progress"
284
+ };
285
+ var actionFlagPattern;
286
+ function getActionFlagPattern() {
287
+ actionFlagPattern ??= new RegExp(
288
+ `^(${Object.values(ActionType).join("|").toLowerCase()}):(${Object.values(
289
+ ActionStatus
290
+ ).join("|").toLowerCase()})$`
291
+ );
292
+ return actionFlagPattern;
293
+ }
294
+ var ActionFlag = z5.string().refine((value) => getActionFlagPattern().test(value), {
295
+ message: "Flag must be in the format ActionType:ActionStatus (lowerCase)"
296
+ });
297
+ var CustomFlag = z5.string().refine((val) => !Object.values(InherentFlags).includes(val), {
298
+ message: `Custom flag cannot be one of the inherent flags: ${Object.values(
299
+ InherentFlags
300
+ ).join(", ")}`
301
+ }).refine((val) => !ActionFlag.safeParse(val).success, {
302
+ message: "Custom flag cannot match the ActionFlag pattern (ActionType:ActionStatus)."
303
+ }).describe("Custom flag identifier defined by the country config.");
304
+ var Flag = ActionFlag.or(z5.enum(InherentFlags)).or(CustomFlag);
305
+ var ContainsFlags = z5.object({
306
+ anyOf: z5.array(Flag).optional(),
307
+ noneOf: z5.array(Flag).optional(),
308
+ allOf: z5.array(Flag).optional()
309
+ }).meta({
310
+ id: "ContainsFlags"
311
+ });
312
+ var FlagConfig = z5.object({
313
+ id: CustomFlag,
314
+ requiresAction: z5.boolean().describe(
315
+ "Indicates if this flag expects an action to be performed to be cleared."
316
+ ),
317
+ label: TranslationConfig.describe("Human readable label of the flag.")
318
+ }).meta({
319
+ id: "FlagConfig",
320
+ description: "Configuration for a custom flag that can be added to or removed from records by event actions."
321
+ });
322
+ var ActionFlagConfig = z5.object({
323
+ id: Flag,
324
+ operation: z5.enum(["add", "remove"]).describe("Operation to perform on the flag."),
325
+ conditional: Conditional.optional().describe(
326
+ "When conditional is met, the operation is performed on the flag. If not provided, the operation is performed unconditionally."
327
+ )
328
+ }).meta({
329
+ id: "ActionFlagConfig",
330
+ description: "Add or remove operation applied to a flag when the parent action is accepted. Optionally gated by a conditional."
331
+ });
332
+
333
+ // ../commons/src/events/EventStatus.ts
334
+ var z6 = __toESM(require("zod/v4"));
335
+ var EventStatus = z6.enum([
336
+ "CREATED",
337
+ "NOTIFIED",
338
+ "DECLARED",
339
+ "REGISTERED",
340
+ "ARCHIVED"
341
+ ]);
342
+
343
+ // ../commons/src/scopes.ts
344
+ var JurisdictionFilter = z7.enum(["administrativeArea", "location", "all"]).describe(
345
+ "Filters based on user jurisdiction relative to their office location in hierarchy."
346
+ );
347
+ var UserFilter = z7.enum(["user"]).describe("Filters based on the user. Limits to self.");
348
+ var RecordScopeTypeV2 = z7.enum([
349
+ "record.search",
350
+ "record.create",
351
+ "record.read",
352
+ "record.declare",
353
+ "record.notify",
354
+ "record.edit",
355
+ "record.reject",
356
+ "record.archive",
357
+ "record.unarchive",
358
+ "record.review-duplicates",
359
+ "record.register",
360
+ "record.print-certified-copies",
361
+ "record.request-correction",
362
+ "record.correct",
363
+ "record.unassign-others",
364
+ "record.custom-action"
365
+ ]);
366
+ var PlainScopeType = z7.enum([
367
+ // Misc. system scopes
368
+ "bypassratelimit",
369
+ "record.reindex",
370
+ "user.data-seeding",
371
+ "integration.create",
372
+ // Reading an integration's audit log. Deliberately separate from
373
+ // 'integration.create' so read-only oversight can be granted on its own, and
374
+ // deliberately option-less: system clients have no office and no
375
+ // administrative area, so jurisdiction options would have nothing to bind to.
376
+ "integration.audit.read",
377
+ "record.import",
378
+ "config.update-all",
379
+ "location.edit",
380
+ "attachment.upload",
381
+ "profile.electronic-signature",
382
+ "user.read-only-my-audit",
383
+ // Performance dashboard
384
+ "performance.read",
385
+ "performance.read-dashboards",
386
+ "performance.vital-statistics-export",
387
+ // Scopes used exclusively by countryconfig integration token
388
+ "record.confirm-registration",
389
+ "record.reject-registration"
390
+ ]);
391
+ var scopeByEvent = z7.preprocess(
392
+ (val) => val === void 0 ? void 0 : [val].flat(),
393
+ z7.array(z7.string()).optional()
394
+ ).describe("Event type, e.g. birth, death");
395
+ var scopeByStatus = z7.preprocess(
396
+ (val) => val === void 0 ? void 0 : [val].flat(),
397
+ z7.array(EventStatus).optional()
398
+ ).describe(
399
+ "Restricts the scope to records currently in one of these statuses."
400
+ );
401
+ var userRole = z7.preprocess(
402
+ (val) => val === void 0 ? void 0 : [val].flat(),
403
+ z7.array(z7.string()).optional()
404
+ ).describe("User role, e.g. admin, field agent");
405
+ var scopeOptionsPlaceEvent = z7.object({
406
+ event: scopeByEvent,
407
+ placeOfEvent: JurisdictionFilter.optional()
408
+ }).describe("Options applicable to all record scopes.");
409
+ var scopeOptionsDeclaredOrNotified = scopeOptionsPlaceEvent.extend({
410
+ notifiedIn: JurisdictionFilter.optional(),
411
+ notifiedBy: UserFilter.optional(),
412
+ declaredIn: JurisdictionFilter.optional(),
413
+ declaredBy: UserFilter.optional(),
414
+ status: scopeByStatus
415
+ }).describe("Options applicable to actions that may take place after DECLARE");
416
+ var AllRecordScopeOptions = scopeOptionsDeclaredOrNotified.extend({
417
+ registeredIn: JurisdictionFilter.optional(),
418
+ registeredBy: UserFilter.optional(),
419
+ flags: ContainsFlags.optional()
420
+ }).describe(
421
+ "Options applicable to actions that may take place after REGISTER, with full filtering capabilities."
422
+ );
423
+ var CustomActionScopeOptions = AllRecordScopeOptions.extend({
424
+ customActionTypes: z7.preprocess(
425
+ (val) => val === void 0 ? void 0 : [val].flat(),
426
+ z7.array(z7.string()).optional()
427
+ ).describe("Allowed custom action types")
428
+ });
429
+ var AccessLevelOptions = z7.object({
430
+ accessLevel: JurisdictionFilter.optional()
431
+ });
432
+ var AllUserScopeOptions = AccessLevelOptions.extend({
433
+ role: userRole.optional()
434
+ });
435
+ var WorkqueueOrDashboardOptions = z7.object({
436
+ ids: z7.preprocess(
437
+ (val) => val === void 0 ? void 0 : [val].flat(),
438
+ z7.array(z7.string())
439
+ ).describe("Must contain a list of workqueue or dashboard ids.")
440
+ });
441
+ var AllScopeOptions = z7.object({
442
+ ...AllRecordScopeOptions.shape,
443
+ ...AccessLevelOptions.shape,
444
+ ...AllUserScopeOptions.shape,
445
+ ...WorkqueueOrDashboardOptions.shape
446
+ });
447
+ var ScopeOptionKey = AllScopeOptions.keyof();
448
+ var ResolvedScopeOptionsPlaceEvent = z7.object({
449
+ event: scopeByEvent,
450
+ placeOfEvent: UUID.nullish()
451
+ }).describe(
452
+ "Resolved options applicable to all record scopes, with location ID instead of jurisdiction filter."
453
+ );
454
+ var ResolvedScopeOptionsDeclared = ResolvedScopeOptionsPlaceEvent.extend({
455
+ notifiedIn: UUID.nullish(),
456
+ notifiedBy: z7.string().optional(),
457
+ declaredIn: UUID.nullish(),
458
+ declaredBy: z7.string().optional()
459
+ }).describe(
460
+ "Resolved options applicable to actions that may take place after DECLARE, with location ID and user ID instead of filters."
461
+ );
462
+ var ResolvedScopeOptionsFull = ResolvedScopeOptionsDeclared.extend({
463
+ registeredIn: UUID.nullish(),
464
+ registeredBy: z7.string().optional(),
465
+ flags: ContainsFlags.optional()
466
+ }).describe(
467
+ "Resolved options applicable to actions that may take place after REGISTER, with full filtering capabilities and location/user IDs instead of filters."
468
+ );
469
+ var ScopesWithPlaceEventOptions = RecordScopeTypeV2.extract([
470
+ "record.create",
471
+ "record.declare",
472
+ "record.notify"
473
+ ]);
474
+ var ScopesWithDeclaredOptions = RecordScopeTypeV2.extract([
475
+ "record.edit",
476
+ "record.reject",
477
+ "record.archive",
478
+ "record.unarchive",
479
+ "record.register"
480
+ ]);
481
+ var ScopesWithFullOptions = RecordScopeTypeV2.extract([
482
+ "record.search",
483
+ "record.read",
484
+ "record.request-correction",
485
+ "record.correct",
486
+ "record.unassign-others",
487
+ "record.review-duplicates"
488
+ ]);
489
+ var ScopeOptionsPrintCertifiedCopies = AllRecordScopeOptions.extend({
490
+ templates: z7.preprocess(
491
+ (val) => val === void 0 ? void 0 : [val].flat(),
492
+ z7.array(z7.string()).optional()
493
+ ).describe(
494
+ "Template IDs for certified copies. Controls which certificate templates are returned to the client via the config service. Certificate printing is a client-side operation \u2014 this option is not validated when the printCertificate action is submitted."
495
+ )
496
+ });
497
+ var RecordScopeV2 = z7.discriminatedUnion("type", [
498
+ z7.object({
499
+ type: ScopesWithPlaceEventOptions,
500
+ options: scopeOptionsPlaceEvent.optional()
501
+ }),
502
+ z7.object({
503
+ type: ScopesWithDeclaredOptions,
504
+ options: scopeOptionsDeclaredOrNotified.optional()
505
+ }),
506
+ z7.object({
507
+ type: ScopesWithFullOptions,
508
+ options: AllRecordScopeOptions.optional()
509
+ }),
510
+ z7.object({
511
+ type: z7.literal("record.custom-action"),
512
+ options: CustomActionScopeOptions.optional()
513
+ }),
514
+ z7.object({
515
+ type: z7.literal("record.print-certified-copies"),
516
+ options: ScopeOptionsPrintCertifiedCopies.optional()
517
+ })
518
+ ]).describe(
519
+ "Scopes used to check user's permission to perform actions on a record."
520
+ );
521
+ var SystemScopeType = z7.enum([
522
+ "organisation.read-locations",
523
+ "user.read",
524
+ "user.create",
525
+ "user.edit",
526
+ "user.search"
527
+ ]);
528
+ var UserScopeType = SystemScopeType.extract([
529
+ "user.read",
530
+ "user.create",
531
+ "user.edit",
532
+ "user.search"
533
+ ]);
534
+ var ScopesWithRoleOption = UserScopeType.extract(["user.edit", "user.create"]);
535
+ var UserScopeV2 = z7.discriminatedUnion("type", [
536
+ z7.object({
537
+ type: ScopesWithRoleOption,
538
+ options: AllUserScopeOptions.optional()
539
+ }),
540
+ z7.object({
541
+ type: UserScopeType.extract(["user.read", "user.search"]),
542
+ options: AccessLevelOptions.optional()
543
+ })
544
+ ]);
545
+ function scopeUsesRoleOptions(scope) {
546
+ return ScopesWithRoleOption?.options.some((opt) => opt === scope.type);
547
+ }
548
+ function scopeUsesDeclaredOptions(scope) {
549
+ return !ScopesWithPlaceEventOptions.options.some((opt) => opt === scope.type);
550
+ }
551
+ function scopeUsesFullOptions(scope) {
552
+ return ScopesWithFullOptions.options.some((opt) => opt === scope.type);
553
+ }
554
+ function scopeUsesPrintCertifiedCopiesOptions(scope) {
555
+ return scope.type === "record.print-certified-copies";
556
+ }
557
+ function isCustomActionScope(scope) {
558
+ return scope.type === "record.custom-action";
559
+ }
560
+ var ResolvedRecordScopeV2 = z7.discriminatedUnion("type", [
561
+ z7.object({
562
+ type: ScopesWithPlaceEventOptions,
563
+ options: ResolvedScopeOptionsPlaceEvent.optional()
564
+ }),
565
+ z7.object({
566
+ type: ScopesWithDeclaredOptions,
567
+ options: ResolvedScopeOptionsDeclared.optional()
568
+ }),
569
+ z7.object({
570
+ type: ScopesWithFullOptions,
571
+ options: ResolvedScopeOptionsFull.optional()
572
+ }),
573
+ z7.object({
574
+ type: z7.literal("record.print-certified-copies"),
575
+ options: ResolvedScopeOptionsFull.extend({
576
+ templates: z7.array(z7.string()).optional()
577
+ }).optional()
578
+ })
579
+ ]).describe("Resolved scope with location/user IDs instead of filters.");
580
+ var Scope = z7.discriminatedUnion("type", [
581
+ z7.object({ type: PlainScopeType }),
582
+ ...RecordScopeV2.options,
583
+ ...UserScopeV2.options,
584
+ z7.object({
585
+ type: z7.literal("organisation.read-locations"),
586
+ options: AccessLevelOptions.optional()
587
+ }),
588
+ z7.object({
589
+ type: z7.literal("workqueue"),
590
+ options: WorkqueueOrDashboardOptions
591
+ }),
592
+ z7.object({
593
+ type: z7.literal("dashboard.view"),
594
+ options: WorkqueueOrDashboardOptions
595
+ })
596
+ ]);
597
+ var ScopeType = z7.enum([
598
+ ...SystemScopeType.options,
599
+ ...RecordScopeTypeV2.options,
600
+ ...PlainScopeType.options,
601
+ "workqueue",
602
+ "dashboard.view"
603
+ ]);
604
+ var flattenScope = (scope) => ({
605
+ type: scope.type,
606
+ ..."options" in scope ? scope.options : {}
607
+ });
608
+ var unflattenScope = (input) => {
609
+ const { type, ...options } = input;
610
+ return { type, options };
611
+ };
612
+ var EncodedScope = z7.string().brand("EncodedScope");
613
+ var encodeScope = (scope) => {
614
+ const flattened = flattenScope(scope);
615
+ return qs.stringify(flattened, {
616
+ arrayFormat: "comma",
617
+ commaRoundTrip: true,
618
+ allowDots: true,
619
+ addQueryPrefix: false,
620
+ encode: false
621
+ });
622
+ };
623
+ var decodedScopeCache = /* @__PURE__ */ new Map();
624
+ var decodeScope = (encodedScope) => {
625
+ if (decodedScopeCache.has(encodedScope)) {
626
+ return decodedScopeCache.get(encodedScope);
627
+ }
628
+ const scope = qs.parse(encodedScope, {
629
+ ignoreQueryPrefix: true,
630
+ comma: true,
631
+ allowDots: true
632
+ });
633
+ const unflattenedScope = unflattenScope(scope);
634
+ const result = Scope.safeParse(unflattenedScope)?.data;
635
+ decodedScopeCache.set(encodedScope, result);
636
+ return result;
637
+ };
638
+ var DEFAULT_SCOPE_OPTIONS = {
639
+ placeOfEvent: JurisdictionFilter.enum.all,
640
+ accessLevel: JurisdictionFilter.enum.all,
641
+ notifiedIn: JurisdictionFilter.enum.all,
642
+ declaredIn: JurisdictionFilter.enum.all,
643
+ registeredIn: JurisdictionFilter.enum.all
644
+ };
645
+ function getScopeOptionValue(scope, option) {
646
+ const options = "options" in scope ? scope.options : void 0;
647
+ const value = options?.[option];
648
+ const defaultValue = option in DEFAULT_SCOPE_OPTIONS ? DEFAULT_SCOPE_OPTIONS[option] : void 0;
649
+ return value ?? defaultValue;
650
+ }
651
+ function getAcceptedScopesByType({
652
+ acceptedScopes,
653
+ scopes
654
+ }) {
655
+ return scopes.map((scope) => {
656
+ const parsedScope = decodeScope(scope);
657
+ return parsedScope && acceptedScopes.some(
658
+ (acceptedScope) => acceptedScope === parsedScope.type
659
+ ) ? parsedScope : null;
660
+ }).filter((scope) => scope !== null);
661
+ }
662
+ function hasAnyScope(tokenOrScopes, scopes) {
663
+ const userScopes = Array.isArray(tokenOrScopes) ? tokenOrScopes : getScopes(tokenOrScopes);
664
+ const foundScopes = getAcceptedScopesByType({
665
+ acceptedScopes: scopes,
666
+ scopes: userScopes
667
+ });
668
+ return foundScopes.length > 0;
669
+ }
670
+ function hasScope(tokenOrScopes, scope) {
671
+ if (Array.isArray(tokenOrScopes)) {
672
+ return getAcceptedScopesByType({
673
+ acceptedScopes: [scope],
674
+ scopes: tokenOrScopes
675
+ }).length > 0;
676
+ }
677
+ return hasAnyScope(tokenOrScopes, [scope]);
678
+ }
679
+ function canUserCreateEvent(userScopes, eventType) {
680
+ const scopes = getAcceptedScopesByType({
681
+ acceptedScopes: ["record.create"],
682
+ scopes: userScopes
683
+ });
684
+ return scopes.some((scope) => {
685
+ if (!("options" in scope) || !scope.options || !("event" in scope.options)) {
686
+ return true;
687
+ }
688
+ return scope.options?.event?.includes(eventType);
689
+ });
690
+ }
691
+ function defineScopes(scopes) {
692
+ return scopes.map((scope) => Scope.parse(scope)).map(encodeScope);
693
+ }
694
+ function defineRoles(roles) {
695
+ return roles;
696
+ }
697
+
698
+ // ../commons/src/authentication.ts
699
+ function getAcceptedScopesFromToken(token, acceptedScopes) {
700
+ const tokenScopes = getScopes(token);
701
+ return tokenScopes.map((scope) => {
702
+ const parsedScope = decodeScope(scope);
703
+ return parsedScope && acceptedScopes.some((s) => s === parsedScope.type) ? parsedScope : null;
704
+ }).filter((scope) => scope !== null);
705
+ }
706
+ var TokenUserType = z8.enum(["user", "system"]);
707
+ function setBearerForToken(token) {
708
+ const bearer = "Bearer";
709
+ return token.startsWith(bearer) ? token : `${bearer} ${token}`;
710
+ }
711
+ function getScopes(token) {
712
+ const authHeader = { Authorization: setBearerForToken(token) };
713
+ const tokenPayload = getTokenPayload(authHeader.Authorization.split(" ")[1]);
714
+ return tokenPayload.scope || [];
715
+ }
716
+ var getTokenPayload = (token) => {
717
+ let decoded;
718
+ try {
719
+ decoded = (0, import_jwt_decode.default)(token);
720
+ } catch (err) {
721
+ throw new Error(
722
+ `getTokenPayload: Error occurred during token decode : ${err}`
723
+ );
724
+ }
725
+ return decoded;
726
+ };
727
+ var getUserId = (token) => {
728
+ const tokenPayload = getTokenPayload(token.split(" ")[1]);
729
+ return z8.string().parse(tokenPayload.sub);
730
+ };
731
+ var getUserIdFromToken = (token) => {
732
+ try {
733
+ const payload = (0, import_jwt_decode.default)(token);
734
+ return payload.sub ?? null;
735
+ } catch {
736
+ return null;
737
+ }
738
+ };
739
+ var SERVICE_USER_ID = "__SERVICE_USER__";
740
+ function isServiceToken(credentials) {
741
+ return typeof credentials === "object" && credentials !== null && credentials.sub === SERVICE_USER_ID;
742
+ }
743
+ var getUserTypeFromToken = (token) => {
744
+ const tokenPayload = getTokenPayload(token.split(" ")[1]);
745
+ return TokenUserType.parse(tokenPayload.userType);
746
+ };
747
+ var TokenWithBearer = z8.string().regex(/^Bearer\s/);
748
+
749
+ // src/authentication/index.ts
750
+ z9.globalRegistry.clear();