@opencrvs/toolkit 2.1.0-rc.05a1257 → 2.1.0-rc.05b7761

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 (66) hide show
  1. package/README.md +2 -12
  2. package/build.sh +10 -3
  3. package/create-countryconfig/index.js +338 -4
  4. package/dist/application-config/index.js +17 -18
  5. package/dist/authentication/index.d.ts +67 -0
  6. package/dist/authentication/index.d.ts.map +1 -0
  7. package/dist/authentication/index.js +751 -0
  8. package/dist/cli.js +1090 -187
  9. package/dist/commons/api/router.d.ts +6 -42
  10. package/dist/commons/conditionals/conditionals.d.ts +6 -6
  11. package/dist/commons/conditionals/validate.d.ts +1 -1
  12. package/dist/commons/events/ActionConfig.d.ts +4 -0
  13. package/dist/commons/events/AdvancedSearchConfig.d.ts +12 -12
  14. package/dist/commons/events/FieldConfig.d.ts +16 -15
  15. package/dist/commons/events/FormConfig.d.ts +6 -0
  16. package/dist/commons/events/PageConfig.d.ts +4 -0
  17. package/dist/commons/events/locations.d.ts +4 -0
  18. package/dist/commons/events/test.utils.d.ts +18 -1
  19. package/dist/commons/events/utils.d.ts +15 -0
  20. package/dist/commons/notification/dispatch.d.ts +1 -6
  21. package/dist/conditionals/index.js +7 -6
  22. package/dist/csv.d.ts.map +1 -1
  23. package/dist/csv.js +7 -2
  24. package/dist/environment/logger.d.ts +3 -0
  25. package/dist/environment/logger.d.ts.map +1 -1
  26. package/dist/environment/manage-users.js +1 -1
  27. package/dist/environment/setup-environment.js +44 -26
  28. package/dist/environment/templates.d.ts +0 -1
  29. package/dist/environment/templates.d.ts.map +1 -1
  30. package/dist/environment/templates.js +3 -8
  31. package/dist/environment/update-workflows.d.ts.map +1 -1
  32. package/dist/environment/update-workflows.js +4 -0
  33. package/dist/environment/utils.d.ts +0 -12
  34. package/dist/environment/utils.d.ts.map +1 -1
  35. package/dist/environment/utils.js +1 -28
  36. package/dist/events/index.js +1901 -1792
  37. package/dist/migrations/v2.0/merge-infrastructure-directory.js +3 -3
  38. package/dist/migrations/v2.1/add-recovery-link-notifications.js +4 -4
  39. package/dist/migrations/v2.1/add-translations.d.ts.map +1 -1
  40. package/dist/migrations/v2.1/add-translations.js +42 -11
  41. package/dist/migrations/v2.1/enable-telemetry.d.ts +3 -0
  42. package/dist/migrations/v2.1/enable-telemetry.d.ts.map +1 -0
  43. package/dist/migrations/v2.1/enable-telemetry.js +455 -0
  44. package/dist/migrations/v2.1/index.d.ts.map +1 -1
  45. package/dist/migrations/v2.1/index.js +601 -19
  46. package/dist/migrations/v2.1/rename-trigger-paths.d.ts +3 -0
  47. package/dist/migrations/v2.1/rename-trigger-paths.d.ts.map +1 -0
  48. package/dist/migrations/v2.1/rename-trigger-paths.js +216 -0
  49. package/dist/notification/index.js +167 -155
  50. package/dist/scopes/index.d.ts +109 -5
  51. package/dist/scopes/index.js +7 -6
  52. package/dist/telemetry/index.d.ts +45 -0
  53. package/dist/telemetry/index.d.ts.map +1 -0
  54. package/dist/telemetry/index.js +43 -0
  55. package/dist/templates/charts-values/dependencies/values.yaml +2 -0
  56. package/dist/translations/check.d.ts +2 -4
  57. package/dist/translations/check.d.ts.map +1 -1
  58. package/dist/translations/check.js +14 -8
  59. package/dist/verify/endpoints.d.ts +2 -0
  60. package/dist/verify/endpoints.d.ts.map +1 -0
  61. package/dist/verify/endpoints.js +345 -0
  62. package/opencrvs-toolkit-2.1.0-rc.05b7761.tgz +0 -0
  63. package/package.json +5 -2
  64. package/tsconfig.build.tsbuildinfo +1 -1
  65. package/tsconfig.json +3 -0
  66. package/opencrvs-toolkit-2.1.0-rc.05a1257.tgz +0 -0
package/README.md CHANGED
@@ -55,19 +55,9 @@ Toolkit "re-exports" TRPC router to allow for easy client interaction.
55
55
 
56
56
  Toolkit "re-exports" common definitions (e.g. events, conditionals) and make them available through npm.
57
57
 
58
- ### Releasing and buiding
58
+ ### Publishing
59
59
 
60
- #### While developing
61
-
62
- 1. Update version number in `package.json`
63
- 2. `yarn build:all`
64
- 3. `npm publish`
65
-
66
- #### Through version control
67
-
68
- 1. Update version number in `package.json`
69
- 2. Create a pull request
70
- 3. Once merged, github action will get triggered.
60
+ Publish via [Publish toolkit to NPM registry](https://github.com/opencrvs/opencrvs-core/actions/workflows/publish-toolkit-to-npm.yml).
71
61
 
72
62
  #### Gotchas, good to know
73
63
 
package/build.sh CHANGED
@@ -18,6 +18,9 @@ npx tsc --build tsconfig.build.json
18
18
 
19
19
  # Build common events
20
20
  npx esbuild src/events/index.ts --bundle --format=cjs --outdir=./dist/events --allow-overwrite --packages=external
21
+
22
+ # Build telemetry client (self-contained; .d.ts comes from tsc --build above)
23
+ npx esbuild src/telemetry/index.ts --bundle --platform=node --format=cjs --outdir=./dist/telemetry --allow-overwrite --packages=external
21
24
  mkdir -p ./dist/commons/events
22
25
  cp -r ../commons/build/dist/common/events/*.d.ts ./dist/commons/events
23
26
  mkdir -p ./dist/commons/events/state
@@ -32,6 +35,10 @@ cp -r ../commons/build/dist/common/conditionals/*.d.ts ./dist/commons/conditiona
32
35
  npx esbuild src/scopes/index.ts --bundle --format=cjs --outdir=./dist/scopes --allow-overwrite --packages=external
33
36
  cp -r ../commons/build/dist/common/scopes.d.ts ./dist/scopes/index.d.ts
34
37
 
38
+ # Build common authentication
39
+ npx esbuild src/authentication/index.ts --bundle --format=cjs --outdir=./dist/authentication --allow-overwrite --packages=external
40
+ cp -r ../commons/build/dist/common/authentication.d.ts ./dist/authentication/index.d.ts
41
+
35
42
  # Build api client
36
43
  npx esbuild src/api/index.ts --bundle --format=cjs --outdir=./dist/api --allow-overwrite --packages=external
37
44
  mkdir -p ./dist/commons/api
@@ -42,7 +49,7 @@ npx esbuild src/events/deduplication.ts --bundle --format=cjs --outdir=./dist/ev
42
49
  cp -r ../commons/build/dist/common/events/deduplication.d.ts ./dist/events/deduplication.d.ts
43
50
 
44
51
  # Build common notifications
45
- npx esbuild src/notification/index.ts --bundle --format=cjs --outdir=./dist/notification --allow-overwrite --packages=external
52
+ npx esbuild src/notification/index.ts --bundle --platform=node --format=cjs --outdir=./dist/notification --allow-overwrite --packages=external
46
53
  mkdir -p ./dist/commons/notification
47
54
  cp -r ../commons/build/dist/common/notification/*.d.ts ./dist/commons/notification
48
55
 
@@ -52,7 +59,7 @@ mkdir -p ./dist/commons/application-config
52
59
  cp -r ../commons/build/dist/common/application-config.d.ts ./dist/commons/application-config/index.d.ts
53
60
 
54
61
  # Build migration CLI
55
- npx esbuild src/migrations/v2.1/index.ts --bundle --format=cjs --outdir=./dist/migrations/v2.1 --allow-overwrite --packages=external --banner:js="#!/usr/bin/env node"
62
+ npx esbuild src/migrations/v2.1/index.ts --bundle --platform=node --format=cjs --outdir=./dist/migrations/v2.1 --allow-overwrite --packages=external --banner:js="#!/usr/bin/env node"
56
63
  chmod +x ./dist/migrations/v2.1/index.js
57
64
 
58
65
  if [[ "$OSTYPE" == "darwin"* ]]; then
@@ -64,7 +71,7 @@ else
64
71
  fi
65
72
 
66
73
  # Build CLI
67
- npx esbuild src/cli.ts --bundle --format=cjs --outdir=./dist --allow-overwrite --packages=external --banner:js="#!/usr/bin/env node"
74
+ npx esbuild src/cli.ts --bundle --platform=node --format=cjs --outdir=./dist --allow-overwrite --packages=external --banner:js="#!/usr/bin/env node"
68
75
  cp -R src/environment/templates dist/templates
69
76
  chmod +x ./dist/cli.js
70
77
 
@@ -13,6 +13,8 @@
13
13
 
14
14
  const path = require('path')
15
15
  const fs = require('fs')
16
+ const { execSync } = require('child_process')
17
+ const readline = require('readline/promises')
16
18
  const degit = require('degit').default
17
19
 
18
20
  const INFRASTRUCTURE_REPOSITORY = 'opencrvs/infrastructure'
@@ -20,6 +22,14 @@ const CORE_REPOSITORY = 'opencrvs/opencrvs-core'
20
22
  const COUNTRYCONFIG_TEMPLATE_REPOSITORY_SUBPATH =
21
23
  'packages/countryconfig-template'
22
24
 
25
+ const CORE_REPO_URL = 'https://github.com/' + CORE_REPOSITORY + '.git'
26
+ const INFRASTRUCTURE_REPO_URL =
27
+ 'https://github.com/' + INFRASTRUCTURE_REPOSITORY + '.git'
28
+
29
+ const { version } = JSON.parse(
30
+ fs.readFileSync(path.join(__dirname, 'package.json'), 'utf-8')
31
+ )
32
+
23
33
  function joinValues(values, separator) {
24
34
  return values
25
35
  .filter((value) => !!value)
@@ -27,19 +37,162 @@ function joinValues(values, separator) {
27
37
  .trim()
28
38
  }
29
39
 
40
+ function tagExists(repoUrl, tag) {
41
+ try {
42
+ execSync(
43
+ 'git ls-remote --exit-code --tags ' + repoUrl + ' refs/tags/' + tag,
44
+ { stdio: 'pipe' }
45
+ )
46
+ return true
47
+ } catch (err) {
48
+ return false
49
+ }
50
+ }
51
+
52
+ function branchExists(repoUrl, branch) {
53
+ try {
54
+ execSync(
55
+ 'git ls-remote --exit-code --heads ' + repoUrl + ' refs/heads/' + branch,
56
+ { stdio: 'pipe' }
57
+ )
58
+ return true
59
+ } catch (err) {
60
+ return false
61
+ }
62
+ }
63
+
64
+ /**
65
+ * Release tags (e.g. "v2.1.0"), highest first. Delegates the version-aware
66
+ * ordering to git itself rather than hand-parsing semver, then filters down
67
+ * to strict "vX.Y.Z" tags - `--sort=-version:refname` alone still leaves in
68
+ * non-release refs (e.g. "vtesting", "v2.0.0-beta") and peeled annotated-tag
69
+ * lines ("refs/tags/v2.0.0^{}").
70
+ */
71
+ function listReleaseTags(repoUrl) {
72
+ const output = execSync(
73
+ 'git ls-remote --tags --sort=-version:refname ' + repoUrl,
74
+ { encoding: 'utf-8' }
75
+ )
76
+
77
+ return output
78
+ .split('\n')
79
+ .map((line) => line.split('\t')[1])
80
+ .filter(Boolean)
81
+ .map((ref) => ref.replace('refs/tags/', ''))
82
+ .filter((tag) => /^v\d+\.\d+\.\d+$/.test(tag))
83
+ }
84
+
85
+ /**
86
+ * The highest release tag present in *both* repositories - used as the
87
+ * fallback when the version-specific tag can't be found in one or both, so
88
+ * scaffolding still lands on a real, matched release rather than develop.
89
+ */
90
+ function getLatestCommonReleaseTag() {
91
+ const infrastructureTags = new Set(listReleaseTags(INFRASTRUCTURE_REPO_URL))
92
+ return (
93
+ listReleaseTags(CORE_REPO_URL).find((tag) => infrastructureTags.has(tag)) ||
94
+ null
95
+ )
96
+ }
97
+
98
+ /**
99
+ * Resolves the ref that both repositories are cloned from. A single ref
100
+ * clones both, so every candidate must exist in *both* - a tag present in
101
+ * only one of them can't be used.
102
+ *
103
+ * The exact "v<version>" tag wins whenever it exists: it pins a commit, so
104
+ * a release, an explicit `@X.Y.Z` pin, or a blessed prerelease (npm `@beta`,
105
+ * published from that tag) reproduces however late it's scaffolded.
106
+ *
107
+ * Otherwise a prerelease falls back to a branch, since a rolling release
108
+ * candidate (npm `@next`) is never tagged: "release/X.Y.Z" of the base
109
+ * version when that release has been cut, otherwise develop. A release
110
+ * falls back to the highest tag common to both repositories - never a
111
+ * mismatched pairing of the two at different releases - or errors.
112
+ */
113
+ function resolveRef() {
114
+ const versionTag = 'v' + version
115
+ if (
116
+ tagExists(CORE_REPO_URL, versionTag) &&
117
+ tagExists(INFRASTRUCTURE_REPO_URL, versionTag)
118
+ ) {
119
+ return versionTag
120
+ }
121
+
122
+ if (version.includes('-')) {
123
+ const releaseBranch = 'release/' + version.split('-')[0]
124
+ if (
125
+ branchExists(CORE_REPO_URL, releaseBranch) &&
126
+ branchExists(INFRASTRUCTURE_REPO_URL, releaseBranch)
127
+ ) {
128
+ return releaseBranch
129
+ }
130
+ return 'develop'
131
+ }
132
+
133
+ const latestCommonTag = getLatestCommonReleaseTag()
134
+ if (latestCommonTag) {
135
+ console.warn(
136
+ '\nWarning: tag "' +
137
+ versionTag +
138
+ '" was not found in both repositories; falling back to the latest ' +
139
+ 'available release, ' +
140
+ latestCommonTag +
141
+ '.'
142
+ )
143
+ return latestCommonTag
144
+ }
145
+
146
+ console.error(
147
+ '\nError: no matching release tag was found in both the core and ' +
148
+ 'infrastructure repositories.'
149
+ )
150
+ process.exit(1)
151
+ }
152
+
30
153
  /**
31
154
  * Clones a repository from GitHub to a target directory.
32
155
  *
33
156
  * @param {*} param0 repository - The repository to clone (e.g., 'opencrvs/opencrvs-core').
34
157
  * @param {*} param0 repositorySubPath - The subpath within the repository to clone (optional). Otherwise the entire repository will be cloned.
35
158
  * @param {*} param0 branch - The branch to clone (optional). Defaults to the default branch if not specified.
159
+ * @param {*} param0 keepHistory - Keep the repository's git history instead of degit's usual history-free copy (optional, defaults to false). The cloned "origin" remote is replaced with "upstream", leaving the directory ready for the user to add their own fork/repo as "origin". Not supported together with repositorySubPath, since a plain git clone can't fetch a single subdirectory.
36
160
  *
37
161
  * @param {*} targetDir - The target directory where the repository will be cloned.
38
162
  */
39
163
  async function cloneRepository(
40
- { repository, repositorySubPath, branch },
164
+ { repository, repositorySubPath, branch, keepHistory = false },
41
165
  targetDir
42
166
  ) {
167
+ if (keepHistory && repositorySubPath) {
168
+ throw new Error(
169
+ 'cloneRepository: keepHistory is not supported together with repositorySubPath.'
170
+ )
171
+ }
172
+
173
+ if (keepHistory) {
174
+ const repoUrl = `https://github.com/${repository}.git`
175
+ console.log(
176
+ `Cloning repository from ${repoUrl}#${branch} to ${targetDir}...`
177
+ )
178
+
179
+ execSync('git clone --branch ' + branch + ' ' + repoUrl + ' ' + targetDir, {
180
+ stdio: 'inherit'
181
+ })
182
+
183
+ console.log(
184
+ `Copied files from ${repoUrl}#${branch} to ${targetDir} succesfully.`
185
+ )
186
+
187
+ console.log(`Replacing 'origin' remote with 'upstream' in ${targetDir}...`)
188
+ execSync('git remote remove origin', { cwd: targetDir, stdio: 'inherit' })
189
+ execSync('git remote add upstream ' + repoUrl, {
190
+ cwd: targetDir,
191
+ stdio: 'inherit'
192
+ })
193
+ return
194
+ }
195
+
43
196
  const repositoryPath = joinValues([repository, repositorySubPath], '/')
44
197
  const fullPath = joinValues([repositoryPath, branch], '#')
45
198
 
@@ -64,6 +217,166 @@ function ensureTargetDirectoryDoesNotExist(directoryName) {
64
217
  }
65
218
  }
66
219
 
220
+ /**
221
+ * Asks whether to enable telemetry. Defaults to yes, and answers yes without
222
+ * prompting when not attached to a terminal (e.g. non-interactive scaffolding).
223
+ */
224
+ async function promptEnableTelemetry() {
225
+ if (!process.stdin.isTTY) {
226
+ return true
227
+ }
228
+
229
+ const rl = readline.createInterface({
230
+ input: process.stdin,
231
+ output: process.stdout
232
+ })
233
+ try {
234
+ const answer = (
235
+ await rl.question(
236
+ '\nEnable anonymous usage telemetry to help improve OpenCRVS? Only ' +
237
+ 'aggregate metrics are shared — no personal or protected data. [Y/n] '
238
+ )
239
+ )
240
+ .trim()
241
+ .toLowerCase()
242
+ return answer === '' || answer === 'y' || answer === 'yes'
243
+ } finally {
244
+ rl.close()
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Prompts for a single line of input, re-asking until `validate` accepts the
250
+ * trimmed answer. `validate` returns an error message string when the answer is
251
+ * invalid, or a falsy value when it is accepted. Exits when not attached to a
252
+ * terminal, since a mandatory value cannot be gathered non-interactively.
253
+ */
254
+ async function promptRequired(question, validate) {
255
+ if (!process.stdin.isTTY) {
256
+ console.error(
257
+ '\nError: interactive input is required to set the organisation name and country code.'
258
+ )
259
+ process.exit(1)
260
+ }
261
+
262
+ const rl = readline.createInterface({
263
+ input: process.stdin,
264
+ output: process.stdout
265
+ })
266
+ try {
267
+ while (true) {
268
+ const answer = (await rl.question(question)).trim()
269
+ const error = validate(answer)
270
+ if (!error) {
271
+ return answer
272
+ }
273
+ console.error(error)
274
+ }
275
+ } finally {
276
+ rl.close()
277
+ }
278
+ }
279
+
280
+ /**
281
+ * Prompts for the organisation name reported with telemetry. Mandatory.
282
+ */
283
+ function promptOrganisation() {
284
+ return promptRequired('\nOrganisation running this instance: ', (answer) =>
285
+ answer === '' ? 'Please enter an organisation name.' : undefined
286
+ )
287
+ }
288
+
289
+ /**
290
+ * Prompts for the alpha-3 ISO country code reported with telemetry, re-asking
291
+ * until a valid three-letter code is given. Mandatory.
292
+ */
293
+ async function promptCountryCode() {
294
+ const answer = await promptRequired(
295
+ '\nAlpha-3 ISO country code of this instance (e.g. "GBR"): ',
296
+ (value) =>
297
+ /^[A-Za-z]{3}$/.test(value)
298
+ ? undefined
299
+ : 'Please enter a three-letter alpha-3 ISO country code (e.g. "GBR").'
300
+ )
301
+ return answer.toUpperCase()
302
+ }
303
+
304
+ /**
305
+ * Flips the `TELEMETRY_ENABLED` env var default in the cloned country config's
306
+ * environment to `true`. The template ships it defaulting to `false`.
307
+ */
308
+ function enableTelemetryInEnvironment(targetPath) {
309
+ const environmentPath = path.join(targetPath, 'src', 'environment.ts')
310
+ if (!fs.existsSync(environmentPath)) {
311
+ console.warn(
312
+ '\nWarning: could not find src/environment.ts; telemetry default not changed.'
313
+ )
314
+ return
315
+ }
316
+
317
+ const original = fs.readFileSync(environmentPath, 'utf-8')
318
+ const updated = original.replace(
319
+ /(TELEMETRY_ENABLED:\s*bool\(\{[\s\S]*?default:\s*)false/,
320
+ '$1true'
321
+ )
322
+
323
+ if (updated === original) {
324
+ console.warn(
325
+ '\nWarning: could not update the TELEMETRY_ENABLED default in src/environment.ts.'
326
+ )
327
+ return
328
+ }
329
+
330
+ fs.writeFileSync(environmentPath, updated)
331
+ console.log('\nTelemetry enabled (TELEMETRY_ENABLED now defaults to true).')
332
+ }
333
+
334
+ /**
335
+ * Replaces the string `default` of an envalid `str({ ... })` field in the
336
+ * cloned country config's environment. Returns the updated source, or the
337
+ * original source (with a warning) when the field could not be located.
338
+ */
339
+ function setEnvironmentStringDefault(source, key, value) {
340
+ const pattern = new RegExp(
341
+ `(${key}:\\s*str\\(\\{[\\s\\S]*?default:\\s*)'[^']*'`
342
+ )
343
+ // Escape for a single-quoted TS string literal, and use a function replacer
344
+ // so `$` in the value is not treated as a replacement pattern.
345
+ const literal = "'" + value.replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'"
346
+ const updated = source.replace(pattern, (_, prefix) => prefix + literal)
347
+
348
+ if (updated === source) {
349
+ console.warn(
350
+ `\nWarning: could not update the ${key} default in src/environment.ts.`
351
+ )
352
+ }
353
+
354
+ return updated
355
+ }
356
+
357
+ /**
358
+ * Writes the given organisation name and alpha-3 country code as the defaults
359
+ * for the `ORGANISATION` and `COUNTRY_CODE` env vars in the cloned country
360
+ * config's environment.
361
+ */
362
+ function setTelemetryIdentityInEnvironment(
363
+ targetPath,
364
+ { organisation, countryCode }
365
+ ) {
366
+ const environmentPath = path.join(targetPath, 'src', 'environment.ts')
367
+ if (!fs.existsSync(environmentPath)) {
368
+ console.warn(
369
+ '\nWarning: could not find src/environment.ts; organisation and country code defaults not changed.'
370
+ )
371
+ return
372
+ }
373
+
374
+ let source = fs.readFileSync(environmentPath, 'utf-8')
375
+ source = setEnvironmentStringDefault(source, 'ORGANISATION', organisation)
376
+ source = setEnvironmentStringDefault(source, 'COUNTRY_CODE', countryCode)
377
+ fs.writeFileSync(environmentPath, source)
378
+ }
379
+
67
380
  function updatePackageJsonName(targetPath, newName) {
68
381
  console.log('\nUpdating package.json with project name: ' + newName + '\n')
69
382
 
@@ -110,12 +423,19 @@ async function main() {
110
423
  ensureTargetDirectoryDoesNotExist(countryconfigDirName)
111
424
  ensureTargetDirectoryDoesNotExist(infrastructureDirName)
112
425
 
426
+ const ref = resolveRef()
427
+
428
+ // Gather all answers up front so the operator isn't interrupted mid-clone.
429
+ const organisation = await promptOrganisation()
430
+ const countryCode = await promptCountryCode()
431
+ const telemetryEnabled = await promptEnableTelemetry()
432
+
113
433
  try {
114
434
  await cloneRepository(
115
435
  {
116
436
  repository: CORE_REPOSITORY,
117
437
  repositorySubPath: COUNTRYCONFIG_TEMPLATE_REPOSITORY_SUBPATH,
118
- branch: 'ocrvs-13179' // @todo: remove this hardcoded branch once the countryconfig-template is merged into main
438
+ branch: ref
119
439
  },
120
440
  countryconfigTargetPath
121
441
  )
@@ -128,7 +448,7 @@ async function main() {
128
448
 
129
449
  try {
130
450
  await cloneRepository(
131
- { repository: INFRASTRUCTURE_REPOSITORY },
451
+ { repository: INFRASTRUCTURE_REPOSITORY, branch: ref, keepHistory: true },
132
452
  infrastructureTargetPath
133
453
  )
134
454
  } catch (err) {
@@ -136,6 +456,15 @@ async function main() {
136
456
  process.exit(1)
137
457
  }
138
458
 
459
+ setTelemetryIdentityInEnvironment(countryconfigTargetPath, {
460
+ organisation,
461
+ countryCode
462
+ })
463
+
464
+ if (telemetryEnabled) {
465
+ enableTelemetryInEnvironment(countryconfigTargetPath)
466
+ }
467
+
139
468
  console.log('\nDone! Your project has been set up in two directories:\n')
140
469
  console.log(' ./' + countryconfigDirName + ' -- country configuration')
141
470
  console.log(' ./' + infrastructureDirName + ' -- server infrastructure\n')
@@ -145,7 +474,12 @@ async function main() {
145
474
  console.log(' tilt up\n')
146
475
  console.log('To get started with the infrastructure:\n')
147
476
  console.log(' cd ' + infrastructureDirName)
148
- console.log(' git init\n')
477
+ console.log(' git remote add origin <your-infrastructure-repo-url>')
478
+ console.log(' git push -u origin ' + ref + '\n')
479
+ console.log(
480
+ 'The "upstream" remote points at the official infrastructure repository, ' +
481
+ 'so you can pull future releases with `git fetch upstream`.\n'
482
+ )
149
483
  }
150
484
 
151
485
  main()
@@ -741,10 +741,7 @@ var PlainScopeType = z13.enum([
741
741
  // Performance dashboard
742
742
  "performance.read",
743
743
  "performance.read-dashboards",
744
- "performance.vital-statistics-export",
745
- // Scopes used exclusively by countryconfig integration token
746
- "record.confirm-registration",
747
- "record.reject-registration"
744
+ "performance.vital-statistics-export"
748
745
  ]);
749
746
  var scopeByEvent = z13.preprocess(
750
747
  (val) => val === void 0 ? void 0 : [val].flat(),
@@ -762,7 +759,9 @@ var userRole = z13.preprocess(
762
759
  ).describe("User role, e.g. admin, field agent");
763
760
  var scopeOptionsPlaceEvent = z13.object({
764
761
  event: scopeByEvent,
765
- placeOfEvent: JurisdictionFilter.optional()
762
+ placeOfEvent: JurisdictionFilter.optional(),
763
+ createdBy: UserFilter.optional(),
764
+ createdIn: JurisdictionFilter.optional()
766
765
  }).describe("Options applicable to all record scopes.");
767
766
  var scopeOptionsDeclaredOrNotified = scopeOptionsPlaceEvent.extend({
768
767
  notifiedIn: JurisdictionFilter.optional(),
@@ -805,7 +804,9 @@ var AllScopeOptions = z13.object({
805
804
  var ScopeOptionKey = AllScopeOptions.keyof();
806
805
  var ResolvedScopeOptionsPlaceEvent = z13.object({
807
806
  event: scopeByEvent,
808
- placeOfEvent: UUID.nullish()
807
+ placeOfEvent: UUID.nullish(),
808
+ createdBy: z13.string().optional(),
809
+ createdIn: UUID.nullish()
809
810
  }).describe(
810
811
  "Resolved options applicable to all record scopes, with location ID instead of jurisdiction filter."
811
812
  );
@@ -1912,9 +1913,6 @@ var AdministrativeAreaField = BaseField.extend({
1912
1913
  partOf: FieldReference.optional().describe("Parent location"),
1913
1914
  type: AdministrativeAreas,
1914
1915
  allowedLocations: AllowedLocations,
1915
- listHistoricalNames: import_v43.default.boolean().optional().describe(
1916
- "List every historical name a location has had as a separate, selectable option."
1917
- ),
1918
1916
  activeOnly: import_v43.default.boolean().optional().describe(
1919
1917
  "Offer only locations that are active at the resolved anchor date (today, or the date of event when anchorToDateOfEvent is set); inactive or not-yet-effective versions are excluded."
1920
1918
  ),
@@ -1932,9 +1930,6 @@ var LocationInput = BaseField.extend({
1932
1930
  configuration: import_v43.default.object({
1933
1931
  locationTypes: import_v43.default.array(import_v43.default.string()).optional().describe("Types of the locations that are available for selection."),
1934
1932
  allowedLocations: AllowedLocations,
1935
- listHistoricalNames: import_v43.default.boolean().optional().describe(
1936
- "List every historical name a location has had as a separate, selectable option."
1937
- ),
1938
1933
  activeOnly: import_v43.default.boolean().optional().describe(
1939
1934
  "Offer only locations that are active at the resolved anchor date (today, or the date of event when anchorToDateOfEvent is set); inactive or not-yet-effective versions are excluded."
1940
1935
  ),
@@ -1968,7 +1963,6 @@ var Facility = BaseField.extend({
1968
1963
  defaultValue: NonEmptyTextValue.or(ComputedDefaultValue).optional(),
1969
1964
  configuration: import_v43.default.object({
1970
1965
  allowedLocations: AllowedLocations,
1971
- listHistoricalNames: import_v43.default.boolean().optional(),
1972
1966
  activeOnly: import_v43.default.boolean().optional(),
1973
1967
  anchorToDateOfEvent: import_v43.default.boolean().optional()
1974
1968
  }).optional()
@@ -1978,7 +1972,6 @@ var Office = BaseField.extend({
1978
1972
  defaultValue: NonEmptyTextValue.or(ComputedDefaultValue).optional(),
1979
1973
  configuration: import_v43.default.object({
1980
1974
  allowedLocations: AllowedLocations,
1981
- listHistoricalNames: import_v43.default.boolean().optional(),
1982
1975
  activeOnly: import_v43.default.boolean().optional(),
1983
1976
  anchorToDateOfEvent: import_v43.default.boolean().optional()
1984
1977
  }).optional()
@@ -2015,9 +2008,6 @@ var Address = BaseField.extend({
2015
2008
  })
2016
2009
  ).optional(),
2017
2010
  allowedLocations: AllowedLocations,
2018
- listHistoricalNames: import_v43.default.boolean().optional().describe(
2019
- "List every historical name a location has had as a separate, selectable option. Propagated to the embedded admin-area selectors."
2020
- ),
2021
2011
  activeOnly: import_v43.default.boolean().optional().describe(
2022
2012
  "Offer only admin areas that are active at the resolved anchor date (today, or the date of event when anchorToDateOfEvent is set); inactive or not-yet-effective versions are excluded. Propagated to the embedded admin-area selectors."
2023
2013
  ),
@@ -2078,10 +2068,19 @@ var ButtonField = BaseField.extend({
2078
2068
  description: "A generic button that can be used to trigger an action",
2079
2069
  id: "ButtonField"
2080
2070
  });
2071
+ var FieldGroupConfiguration = import_v43.default.object({
2072
+ separator: import_v43.default.string().optional().describe(
2073
+ 'Joins the subfield values when the group is rendered as output, e.g. ", ". Defaults to one subfield per line.'
2074
+ ),
2075
+ hideEmptyFields: import_v43.default.boolean().default(false).optional().describe(
2076
+ "Leaves subfields without a value out of the output. Pair it with a separator so the separator does not double up around the gaps."
2077
+ )
2078
+ });
2081
2079
  var FieldGroup = BaseField.extend({
2082
2080
  type: import_v43.default.literal(FieldType.FIELD_GROUP),
2083
2081
  // eslint-disable-next-line @typescript-eslint/no-use-before-define
2084
- fields: import_v43.default.lazy(() => import_v43.default.array(FieldConfig))
2082
+ fields: import_v43.default.lazy(() => import_v43.default.array(FieldConfig)),
2083
+ configuration: FieldGroupConfiguration.optional()
2085
2084
  }).meta({
2086
2085
  description: "A group of fields that are displayed together",
2087
2086
  id: "FieldGroup"
@@ -0,0 +1,67 @@
1
+ import { Nominal } from './nominal';
2
+ import * as z from 'zod/v4';
3
+ import { ScopeType, Scope, EncodedScope } from './scopes';
4
+ import { UUID } from './uuid';
5
+ export * from './scopes';
6
+ /**
7
+ * Returns an array of accepted scopes from a JWT token, filtered by the given accepted scope types.
8
+ *
9
+ * @param token - The JWT token containing scope definitions.
10
+ * @param acceptedScopes - An array of acceptable scope types to filter by.
11
+ * @returns An array of parsed RecordScopeV2 objects that are found in the token and match the accepted scope types.
12
+ */
13
+ export declare function getAcceptedScopesFromToken<T extends ScopeType>(token: string, acceptedScopes: T[]): Array<Extract<Scope, {
14
+ type: T;
15
+ }>>;
16
+ export declare const TokenUserType: z.ZodEnum<{
17
+ system: "system";
18
+ user: "user";
19
+ }>;
20
+ export type TokenUserType = z.infer<typeof TokenUserType>;
21
+ export interface ITokenPayload {
22
+ sub: string;
23
+ exp: string;
24
+ algorithm: string;
25
+ scope: EncodedScope[];
26
+ role?: string;
27
+ userType: TokenUserType;
28
+ eventId?: UUID;
29
+ actionId?: UUID;
30
+ }
31
+ /**
32
+ * Depending on how the API is called, there might or might not be Bearer keyword in the header.
33
+ * To allow for usage with both direct HTTP calls and TRPC, ensure it's present to be able to use shared scope auth functions.
34
+ */
35
+ export declare function setBearerForToken(token: string): string;
36
+ export declare function getScopes(token: string): EncodedScope[];
37
+ export declare const getTokenPayload: (token: string) => ITokenPayload;
38
+ export declare const getUserId: (token: TokenWithBearer) => string;
39
+ /**
40
+ * Extracts the subject (user ID) from a raw JWT string (without Bearer prefix).
41
+ * Returns null if the token cannot be decoded.
42
+ */
43
+ export declare const getUserIdFromToken: (token: string) => string | null;
44
+ /**
45
+ * Fixed subject (`sub`) of the service token that core's auth service mints
46
+ * at `GET /internal/service-token`. The token carries no scopes and has
47
+ * userType 'system'; core uses it for unattended service-to-service calls where
48
+ * no user is involved — startup event-config load, background broadcasts and
49
+ * telemetry. See packages/auth/src/features/serviceToken/handler.ts.
50
+ */
51
+ export declare const SERVICE_USER_ID = "__SERVICE_USER__";
52
+ /**
53
+ * True when a decoded token payload (e.g. Hapi's `request.auth.credentials`)
54
+ * belongs to core's service token, identified by its fixed subject. A country
55
+ * configuration uses this to accept core's own service-to-service calls (e.g.
56
+ * telemetry, all-user broadcasts) while rejecting any logged-in user's token.
57
+ *
58
+ * Accepts `unknown` so loosely-typed framework credentials can be passed
59
+ * directly without a cast; anything that is not an object with the matching
60
+ * `sub` yields `false`.
61
+ */
62
+ export declare function isServiceToken(credentials: unknown): boolean;
63
+ export declare const getUserTypeFromToken: (token: TokenWithBearer) => TokenUserType;
64
+ export declare const TokenWithBearer: z.ZodType<`Bearer ${string}`>;
65
+ export type TokenWithBearer = z.infer<typeof TokenWithBearer>;
66
+ export type Token = Nominal<string, 'TokenWithoutBearer'>;
67
+ //# sourceMappingURL=authentication.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/authentication/index.ts"],"names":[],"mappings":"AAaA,cAAc,kCAAkC,CAAA"}