@htilabs/platform-common-models 0.2.0-beta.4 → 0.3.0-beta.5

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 (75) hide show
  1. package/README.md +38 -0
  2. package/dist/constants/index.cjs +0 -843
  3. package/dist/constants/index.cjs.map +1 -1
  4. package/dist/constants/index.d.cts +146 -5
  5. package/dist/constants/index.d.ts +146 -5
  6. package/dist/constants/index.js +0 -786
  7. package/dist/constants/index.js.map +1 -1
  8. package/dist/{platform-role-AHv1l5Og.d.cts → cvcEntry-wqktWfzE.d.cts} +231 -37
  9. package/dist/{platform-role-AHv1l5Og.d.ts → cvcEntry-wqktWfzE.d.ts} +231 -37
  10. package/dist/cvcs/index.cjs +2184 -0
  11. package/dist/cvcs/index.cjs.map +1 -0
  12. package/dist/cvcs/index.d.cts +2384 -0
  13. package/dist/cvcs/index.d.ts +2384 -0
  14. package/dist/cvcs/index.js +2154 -0
  15. package/dist/cvcs/index.js.map +1 -0
  16. package/dist/index--NCIPluF.d.cts +378 -0
  17. package/dist/index-CFOrHA8l.d.ts +378 -0
  18. package/dist/index.cjs +2962 -843
  19. package/dist/index.cjs.map +1 -1
  20. package/dist/index.d.cts +217 -3
  21. package/dist/index.d.ts +217 -3
  22. package/dist/index.js +2934 -786
  23. package/dist/index.js.map +1 -1
  24. package/dist/models/index.cjs +211 -0
  25. package/dist/models/index.cjs.map +1 -1
  26. package/dist/models/index.d.cts +3 -292
  27. package/dist/models/index.d.ts +3 -292
  28. package/dist/models/index.js +209 -0
  29. package/dist/models/index.js.map +1 -1
  30. package/dist/{platform-auth-BTbQIY3b.d.cts → platform-auth-C-G2qeGM.d.cts} +1 -297
  31. package/dist/{platform-auth-BTbQIY3b.d.ts → platform-auth-C-G2qeGM.d.ts} +1 -297
  32. package/dist/schemas/index.cjs +195 -729
  33. package/dist/schemas/index.cjs.map +1 -1
  34. package/dist/schemas/index.d.cts +11 -11
  35. package/dist/schemas/index.d.ts +11 -11
  36. package/dist/schemas/index.js +189 -729
  37. package/dist/schemas/index.js.map +1 -1
  38. package/dist/services/index.cjs +1442 -0
  39. package/dist/services/index.cjs.map +1 -0
  40. package/dist/services/index.d.cts +305 -0
  41. package/dist/services/index.d.ts +305 -0
  42. package/dist/services/index.js +1417 -0
  43. package/dist/services/index.js.map +1 -0
  44. package/dist/types/index.d.cts +2 -2
  45. package/dist/types/index.d.ts +2 -2
  46. package/dist/validation/index.cjs +261 -0
  47. package/dist/validation/index.cjs.map +1 -0
  48. package/dist/validation/index.d.cts +251 -0
  49. package/dist/validation/index.d.ts +251 -0
  50. package/dist/validation/index.js +228 -0
  51. package/dist/validation/index.js.map +1 -0
  52. package/package.json +36 -12
  53. package/src/__tests__/__snapshots__/cvc-sot.snap +22 -0
  54. package/src/__tests__/cvc-sot-snapshot.test.ts +184 -0
  55. package/src/__tests__/cvc-structural.test.ts +130 -0
  56. package/src/constants/ic.ts +0 -925
  57. package/src/constants/service-catalog.ts +146 -4
  58. package/src/cvcs/index.ts +31 -0
  59. package/src/cvcs/missingness.v1.0.0.json +50 -0
  60. package/src/cvcs/serviceCategories.v1.0.0.json +1947 -0
  61. package/src/cvcs/serviceMechanisms.v1.0.0.json +47 -0
  62. package/src/cvcs/serviceStates.v1.0.0.json +106 -0
  63. package/src/generated/cvc-enums.ts +215 -0
  64. package/src/index.ts +61 -1
  65. package/src/models/cvcEntryModel.ts +32 -0
  66. package/src/models/cvcRegistryModel.ts +35 -0
  67. package/src/models/index.ts +8 -0
  68. package/src/schemas/cvcEntry.ts +158 -0
  69. package/src/schemas/cvcRegistry.ts +149 -0
  70. package/src/schemas/index.ts +16 -0
  71. package/src/services/__tests__/cvcRegistryService.test.ts +614 -0
  72. package/src/services/cvcRegistryService.ts +729 -0
  73. package/src/services/index.ts +21 -0
  74. package/src/validation/cvc.ts +414 -0
  75. package/src/validation/index.ts +15 -0
@@ -0,0 +1,1417 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __export = (target, all) => {
3
+ for (var name in all)
4
+ __defProp(target, name, { get: all[name], enumerable: true });
5
+ };
6
+
7
+ // src/services/cvcRegistryService.ts
8
+ import "mongoose";
9
+
10
+ // src/schemas/form.ts
11
+ import { Schema } from "mongoose";
12
+ var formSectionRefSchema = new Schema(
13
+ {
14
+ sectionId: { type: String, required: true },
15
+ sectionVersion: { type: String, required: true },
16
+ index: { type: Number, required: true },
17
+ isStep: { type: Boolean, default: false },
18
+ wizardStep: { type: Number },
19
+ label: { type: String },
20
+ presetsType: { type: String }
21
+ },
22
+ { _id: false }
23
+ );
24
+ var formSchemaDefinition = {
25
+ _schemaVersion: {
26
+ type: Number,
27
+ required: true,
28
+ default: 1
29
+ },
30
+ // Audit fields
31
+ createdUser: {
32
+ type: Schema.Types.ObjectId,
33
+ required: true,
34
+ index: true
35
+ },
36
+ updatedUser: {
37
+ type: Schema.Types.ObjectId,
38
+ index: true
39
+ },
40
+ // Versioning
41
+ key: {
42
+ type: String,
43
+ required: true
44
+ },
45
+ version: {
46
+ type: String,
47
+ required: true
48
+ },
49
+ // Form info
50
+ name: {
51
+ type: String,
52
+ required: true
53
+ },
54
+ description: {
55
+ type: String
56
+ },
57
+ formType: {
58
+ type: String,
59
+ index: true
60
+ },
61
+ appScope: {
62
+ type: [String],
63
+ enum: ["thread", "pave", "both"],
64
+ default: []
65
+ },
66
+ // Ordered sections
67
+ sections: {
68
+ type: [formSectionRefSchema],
69
+ default: []
70
+ },
71
+ // Lifecycle
72
+ status: {
73
+ type: String,
74
+ required: true,
75
+ enum: ["draft", "active", "deprecated"],
76
+ default: "draft",
77
+ index: true
78
+ },
79
+ supersedes: {
80
+ type: String
81
+ }
82
+ };
83
+ var formSchemaOptions = {
84
+ timestamps: {
85
+ createdAt: "createdTime",
86
+ updatedAt: "updatedTime"
87
+ },
88
+ collection: "forms"
89
+ };
90
+ function buildFormSchema() {
91
+ const schema = new Schema(formSchemaDefinition, formSchemaOptions);
92
+ schema.index({ key: 1, version: 1 }, { unique: true });
93
+ schema.index(
94
+ { key: 1 },
95
+ { unique: true, partialFilterExpression: { status: "active" } }
96
+ );
97
+ return schema;
98
+ }
99
+ var _formSchema = buildFormSchema();
100
+
101
+ // src/schemas/section.ts
102
+ import { Schema as Schema2 } from "mongoose";
103
+ var sectionQuestionRefSchema = new Schema2(
104
+ {
105
+ questionId: { type: String, required: true },
106
+ questionVersion: { type: String, required: true },
107
+ index: { type: Number, required: true }
108
+ },
109
+ { _id: false }
110
+ );
111
+ var guidanceSchema = new Schema2(
112
+ {
113
+ type: {
114
+ type: String,
115
+ required: true,
116
+ enum: ["tip", "warning", "prompt"]
117
+ },
118
+ text: { type: String, required: true }
119
+ },
120
+ { _id: false }
121
+ );
122
+ var sectionSchemaDefinition = {
123
+ _schemaVersion: {
124
+ type: Number,
125
+ required: true,
126
+ default: 1
127
+ },
128
+ // Audit fields
129
+ createdUser: {
130
+ type: Schema2.Types.ObjectId,
131
+ required: true,
132
+ index: true
133
+ },
134
+ updatedUser: {
135
+ type: Schema2.Types.ObjectId,
136
+ index: true
137
+ },
138
+ // Versioning
139
+ key: {
140
+ type: String,
141
+ required: true
142
+ },
143
+ version: {
144
+ type: String,
145
+ required: true
146
+ },
147
+ // Section info
148
+ name: {
149
+ type: String,
150
+ required: true
151
+ },
152
+ directions: {
153
+ type: String
154
+ },
155
+ // Typed guidance items
156
+ guidance: {
157
+ type: [guidanceSchema],
158
+ default: []
159
+ },
160
+ // Ordered question refs
161
+ questions: {
162
+ type: [sectionQuestionRefSchema],
163
+ default: []
164
+ },
165
+ // Template visibility
166
+ templateScope: {
167
+ type: [String],
168
+ default: void 0
169
+ },
170
+ collapsible: {
171
+ type: Boolean,
172
+ default: false
173
+ },
174
+ defaultCollapsed: {
175
+ type: Boolean,
176
+ default: false
177
+ },
178
+ // Lifecycle
179
+ status: {
180
+ type: String,
181
+ required: true,
182
+ enum: ["draft", "active", "deprecated"],
183
+ default: "draft",
184
+ index: true
185
+ },
186
+ supersedes: {
187
+ type: String
188
+ },
189
+ // PAVE-aligned optional fields
190
+ rephrasing: {
191
+ type: String
192
+ },
193
+ script: {
194
+ type: String
195
+ }
196
+ };
197
+ var sectionSchemaOptions = {
198
+ timestamps: {
199
+ createdAt: "createdTime",
200
+ updatedAt: "updatedTime"
201
+ },
202
+ collection: "sections"
203
+ };
204
+ function buildSectionSchema() {
205
+ const schema = new Schema2(sectionSchemaDefinition, sectionSchemaOptions);
206
+ schema.index({ key: 1, version: 1 }, { unique: true });
207
+ schema.index(
208
+ { key: 1 },
209
+ { unique: true, partialFilterExpression: { status: "active" } }
210
+ );
211
+ return schema;
212
+ }
213
+ var _sectionSchema = buildSectionSchema();
214
+
215
+ // src/schemas/question.ts
216
+ import { Schema as Schema3 } from "mongoose";
217
+ var choiceSchema = new Schema3(
218
+ {
219
+ val: { type: Schema3.Types.Mixed, required: true },
220
+ text: { type: String, required: true },
221
+ tip: { type: String },
222
+ trigger: { type: [String] }
223
+ },
224
+ { _id: false }
225
+ );
226
+ var visibilityRuleSchema = new Schema3(
227
+ {
228
+ dependsOn: { type: String, required: true },
229
+ condition: {
230
+ type: String,
231
+ required: true,
232
+ enum: ["equals", "not_equals", "any_of", "in_range"]
233
+ },
234
+ values: { type: [Schema3.Types.Mixed], required: true },
235
+ source: {
236
+ type: String,
237
+ enum: ["form", "session"],
238
+ default: "form"
239
+ }
240
+ },
241
+ { _id: false }
242
+ );
243
+ var layoutSchema = new Schema3(
244
+ {
245
+ columns: { type: Number, default: 1, min: 1, max: 4 },
246
+ collapsible: { type: Boolean, default: false },
247
+ groupKey: { type: String }
248
+ },
249
+ { _id: false }
250
+ );
251
+ var questionSchemaDefinition = {
252
+ _schemaVersion: {
253
+ type: Number,
254
+ required: true,
255
+ default: 1
256
+ },
257
+ // Audit fields
258
+ createdUser: {
259
+ type: Schema3.Types.ObjectId,
260
+ required: true,
261
+ index: true
262
+ },
263
+ updatedUser: {
264
+ type: Schema3.Types.ObjectId,
265
+ index: true
266
+ },
267
+ // Versioning
268
+ key: {
269
+ type: String,
270
+ required: true
271
+ },
272
+ version: {
273
+ type: String,
274
+ required: true
275
+ },
276
+ // Question definition
277
+ index: {
278
+ type: Number,
279
+ required: true
280
+ },
281
+ text: {
282
+ type: String,
283
+ required: true
284
+ },
285
+ format: {
286
+ type: String,
287
+ required: true
288
+ },
289
+ sectionId: {
290
+ type: String,
291
+ required: true
292
+ },
293
+ required: {
294
+ type: Boolean,
295
+ default: false
296
+ },
297
+ allowMultiple: {
298
+ type: Boolean,
299
+ default: false
300
+ },
301
+ // Nesting
302
+ isNested: {
303
+ type: Boolean,
304
+ default: false
305
+ },
306
+ nested: {
307
+ type: [String],
308
+ default: []
309
+ },
310
+ // Trigger logic
311
+ isTriggered: {
312
+ type: Boolean,
313
+ default: false
314
+ },
315
+ triggersWhenAnswered: {
316
+ type: [String],
317
+ default: []
318
+ },
319
+ // Display
320
+ header: { type: String },
321
+ directions: { type: String },
322
+ tip: { type: String },
323
+ // Dynamic choices
324
+ hasDynamicChoices: {
325
+ type: Boolean,
326
+ default: false
327
+ },
328
+ dynamicChoiceSet: { type: String },
329
+ group: { type: String },
330
+ // Static choices
331
+ choices: {
332
+ type: [choiceSchema],
333
+ default: []
334
+ },
335
+ // UI rendering hints
336
+ componentProps: {
337
+ type: Schema3.Types.Mixed
338
+ },
339
+ // Autofill
340
+ autofillRules: {
341
+ type: Schema3.Types.Mixed,
342
+ default: []
343
+ },
344
+ // Classification
345
+ formType: {
346
+ type: [String],
347
+ enum: ["screening", "intake", "assessment", "demographics"],
348
+ default: []
349
+ },
350
+ icCode: {
351
+ type: String
352
+ },
353
+ // Lifecycle
354
+ status: {
355
+ type: String,
356
+ required: true,
357
+ enum: ["draft", "active", "deprecated"],
358
+ default: "draft",
359
+ index: true
360
+ },
361
+ supersedes: {
362
+ type: String
363
+ },
364
+ // Entity mapping (dual-write bridge)
365
+ targetEntity: {
366
+ type: String,
367
+ enum: [
368
+ "caseSession",
369
+ "protectedPerson",
370
+ "perpetratorPerson",
371
+ "personnelPerson",
372
+ "caseRecord",
373
+ "serviceInstance"
374
+ ]
375
+ },
376
+ targetField: {
377
+ type: String
378
+ },
379
+ // Conditional visibility
380
+ visibilityRule: {
381
+ type: visibilityRuleSchema
382
+ },
383
+ // Layout hints
384
+ layout: {
385
+ type: layoutSchema
386
+ },
387
+ microcopy: {
388
+ type: String
389
+ },
390
+ sensitivity: {
391
+ type: String,
392
+ enum: ["standard", "sensitive", "highly_sensitive"]
393
+ },
394
+ // Scoring group
395
+ scoringGroup: {
396
+ type: String
397
+ },
398
+ // PAVE-aligned optional fields
399
+ groups: {
400
+ type: [String],
401
+ default: void 0
402
+ },
403
+ rephrasingSelector: {
404
+ type: Schema3.Types.Mixed
405
+ },
406
+ textSelector: {
407
+ type: Schema3.Types.Mixed
408
+ },
409
+ tipSelector: {
410
+ type: Schema3.Types.Mixed
411
+ },
412
+ sortChoices: {
413
+ type: Boolean
414
+ },
415
+ isAllRequired: {
416
+ type: Boolean
417
+ },
418
+ itemLabel: {
419
+ type: String
420
+ },
421
+ prompts: {
422
+ type: [String],
423
+ default: void 0
424
+ },
425
+ rephrasing: {
426
+ type: String
427
+ },
428
+ dynamicChoiceTrigger: {
429
+ type: String
430
+ }
431
+ };
432
+ var questionSchemaOptions = {
433
+ timestamps: {
434
+ createdAt: "createdTime",
435
+ updatedAt: "updatedTime"
436
+ },
437
+ collection: "questions"
438
+ };
439
+ function buildQuestionSchema() {
440
+ const schema = new Schema3(questionSchemaDefinition, questionSchemaOptions);
441
+ schema.index({ key: 1, version: 1 }, { unique: true });
442
+ schema.index(
443
+ { key: 1 },
444
+ { unique: true, partialFilterExpression: { status: "active" } }
445
+ );
446
+ schema.index({ sectionId: 1, index: 1 });
447
+ schema.index({ icCode: 1 }, { sparse: true });
448
+ return schema;
449
+ }
450
+ var _questionSchema = buildQuestionSchema();
451
+
452
+ // src/schemas/scoring-rule.ts
453
+ import { Schema as Schema4 } from "mongoose";
454
+ var scoringConditionSchema = new Schema4(
455
+ {
456
+ questionKey: { type: String, required: true },
457
+ operator: {
458
+ type: String,
459
+ required: true,
460
+ enum: ["eq", "ne", "in", "not_in", "gt", "gte", "lt", "lte"]
461
+ },
462
+ value: { type: Schema4.Types.Mixed, required: true },
463
+ weight: { type: Number, required: true }
464
+ },
465
+ { _id: false }
466
+ );
467
+ var scoringThresholdSchema = new Schema4(
468
+ {
469
+ minScore: { type: Number, required: true },
470
+ maxScore: { type: Number, required: true },
471
+ riskLevel: { type: String, required: true },
472
+ label: { type: String, required: true }
473
+ },
474
+ { _id: false }
475
+ );
476
+ var scoringRecommendationSchema = new Schema4(
477
+ {
478
+ riskLevel: { type: String, required: true },
479
+ action: { type: String, required: true },
480
+ description: { type: String, required: true }
481
+ },
482
+ { _id: false }
483
+ );
484
+ var scoringRuleSchemaDefinition = {
485
+ _schemaVersion: {
486
+ type: Number,
487
+ required: true,
488
+ default: 1
489
+ },
490
+ // Audit fields
491
+ createdUser: {
492
+ type: Schema4.Types.ObjectId,
493
+ required: true,
494
+ index: true
495
+ },
496
+ updatedUser: {
497
+ type: Schema4.Types.ObjectId,
498
+ index: true
499
+ },
500
+ // Reference to Form (cross-db string, not ObjectId)
501
+ formId: {
502
+ type: String,
503
+ required: true
504
+ },
505
+ formVersion: {
506
+ type: String,
507
+ required: true
508
+ },
509
+ // Rule info
510
+ name: {
511
+ type: String,
512
+ required: true
513
+ },
514
+ version: {
515
+ type: String,
516
+ required: true
517
+ },
518
+ appScope: {
519
+ type: [String],
520
+ enum: ["thread", "pave", "both"],
521
+ default: []
522
+ },
523
+ // Lifecycle
524
+ status: {
525
+ type: String,
526
+ required: true,
527
+ enum: ["draft", "active", "deprecated"],
528
+ default: "draft",
529
+ index: true
530
+ },
531
+ effectiveDate: {
532
+ type: Date
533
+ },
534
+ deprecatedDate: {
535
+ type: Date
536
+ },
537
+ replacedBy: {
538
+ type: String
539
+ },
540
+ // Scoring logic
541
+ conditions: {
542
+ type: [scoringConditionSchema],
543
+ default: []
544
+ },
545
+ thresholds: {
546
+ type: [scoringThresholdSchema],
547
+ default: []
548
+ },
549
+ recommendations: {
550
+ type: [scoringRecommendationSchema],
551
+ default: []
552
+ }
553
+ };
554
+ var scoringRuleSchemaOptions = {
555
+ timestamps: {
556
+ createdAt: "createdTime",
557
+ updatedAt: "updatedTime"
558
+ },
559
+ collection: "scoringrules"
560
+ };
561
+ function buildScoringRuleSchema() {
562
+ const schema = new Schema4(
563
+ scoringRuleSchemaDefinition,
564
+ scoringRuleSchemaOptions
565
+ );
566
+ schema.index(
567
+ { formId: 1, formVersion: 1, version: 1, name: 1 },
568
+ { unique: true }
569
+ );
570
+ schema.index({ formId: 1, formVersion: 1, status: 1 });
571
+ return schema;
572
+ }
573
+ var _scoringRuleSchema = buildScoringRuleSchema();
574
+
575
+ // src/schemas/platform-function.ts
576
+ import { Schema as Schema5 } from "mongoose";
577
+
578
+ // src/constants/platform-auth.ts
579
+ var PERMISSION_STATE = {
580
+ /** Role can always perform this function (mandatory, cannot disable). */
581
+ ALWAYS: "ALWAYS",
582
+ /** Default On — user can opt off. */
583
+ PREF_YES: "PREF_YES",
584
+ /** Default Off — user can opt in. */
585
+ PREF_NO: "PREF_NO",
586
+ /** Role is explicitly barred from this function. */
587
+ NEVER: "NEVER"
588
+ };
589
+ var PERMISSION_STATE_VALUES = [
590
+ PERMISSION_STATE.ALWAYS,
591
+ PERMISSION_STATE.PREF_YES,
592
+ PERMISSION_STATE.PREF_NO,
593
+ PERMISSION_STATE.NEVER
594
+ ];
595
+ var PERMISSION_STATE_LABELS = {
596
+ [PERMISSION_STATE.ALWAYS]: "Always",
597
+ [PERMISSION_STATE.PREF_YES]: "Default On",
598
+ [PERMISSION_STATE.PREF_NO]: "Default Off",
599
+ [PERMISSION_STATE.NEVER]: "Never"
600
+ };
601
+ var PERMISSION_STATE_DISPLAY = {
602
+ [PERMISSION_STATE.ALWAYS]: {
603
+ label: "Always",
604
+ color: "#2e7d32",
605
+ bgColor: "#e8f5e9",
606
+ icon: "\u{1F512}"
607
+ },
608
+ [PERMISSION_STATE.PREF_YES]: {
609
+ label: "Default On",
610
+ color: "#1565c0",
611
+ bgColor: "#e3f2fd",
612
+ icon: "\u{1F513}"
613
+ },
614
+ [PERMISSION_STATE.PREF_NO]: {
615
+ label: "Default Off",
616
+ color: "#e65100",
617
+ bgColor: "#fff3e0",
618
+ icon: "\u{1F513}"
619
+ },
620
+ [PERMISSION_STATE.NEVER]: {
621
+ label: "Never",
622
+ color: "#c62828",
623
+ bgColor: "#ffebee",
624
+ icon: "\u{1F512}"
625
+ }
626
+ };
627
+ var SHARE_VIEW = {
628
+ /** System metadata only (partial access). */
629
+ SYS_INFO: "sys_info",
630
+ /** Full case/record content. */
631
+ ALL: "all",
632
+ /** No data access. */
633
+ NONE: "none"
634
+ };
635
+ var SHARE_VIEW_VALUES = [
636
+ SHARE_VIEW.SYS_INFO,
637
+ SHARE_VIEW.ALL,
638
+ SHARE_VIEW.NONE
639
+ ];
640
+ var SHARE_VIEW_LABELS = {
641
+ [SHARE_VIEW.SYS_INFO]: "System Info Only",
642
+ [SHARE_VIEW.ALL]: "Full Content",
643
+ [SHARE_VIEW.NONE]: "No Data Access"
644
+ };
645
+ var PLATFORM_TOOL = {
646
+ PAVE: "PAVE",
647
+ ECHO: "ECHO",
648
+ LEADS: "LEADS",
649
+ THREAD: "THREAD",
650
+ TRAIL: "TRAIL",
651
+ PLATFORM: "PLATFORM"
652
+ };
653
+ var PLATFORM_TOOL_VALUES = [
654
+ PLATFORM_TOOL.PAVE,
655
+ PLATFORM_TOOL.ECHO,
656
+ PLATFORM_TOOL.LEADS,
657
+ PLATFORM_TOOL.THREAD,
658
+ PLATFORM_TOOL.TRAIL,
659
+ PLATFORM_TOOL.PLATFORM
660
+ ];
661
+ var PLATFORM_TOOL_LABELS = {
662
+ [PLATFORM_TOOL.PAVE]: "PAVE",
663
+ [PLATFORM_TOOL.ECHO]: "Echo",
664
+ [PLATFORM_TOOL.LEADS]: "LEADS",
665
+ [PLATFORM_TOOL.THREAD]: "Thread",
666
+ [PLATFORM_TOOL.TRAIL]: "Trail",
667
+ [PLATFORM_TOOL.PLATFORM]: "Platform"
668
+ };
669
+ var ROLE_LEVEL = {
670
+ /** User-facing roles (staff, volunteers, practitioners). */
671
+ OPERATIONAL: "operational",
672
+ /** Agency-level admin roles. */
673
+ AGENCY: "agency",
674
+ /** Team-level admin roles. */
675
+ TEAM: "team",
676
+ /** HTI-wide platform admin. */
677
+ PLATFORM: "platform",
678
+ /** External governance/oversight roles. */
679
+ OVERSIGHT: "oversight"
680
+ };
681
+ var ROLE_LEVEL_VALUES = [
682
+ ROLE_LEVEL.OPERATIONAL,
683
+ ROLE_LEVEL.AGENCY,
684
+ ROLE_LEVEL.TEAM,
685
+ ROLE_LEVEL.PLATFORM,
686
+ ROLE_LEVEL.OVERSIGHT
687
+ ];
688
+ var ROLE_LEVEL_LABELS = {
689
+ [ROLE_LEVEL.OPERATIONAL]: "Operational",
690
+ [ROLE_LEVEL.AGENCY]: "Agency",
691
+ [ROLE_LEVEL.TEAM]: "Team",
692
+ [ROLE_LEVEL.PLATFORM]: "Platform",
693
+ [ROLE_LEVEL.OVERSIGHT]: "Oversight"
694
+ };
695
+ var FUNCTION_STATUS = {
696
+ NOT_STARTED: "Not started",
697
+ DEFINED_NEW: "Defined; new function",
698
+ DEFINED_EXISTING: "Defined; existing PAVE function",
699
+ FUNCTIONAL: "Functional on all apps",
700
+ FUTURE: "Future function (not v1)"
701
+ };
702
+ var FUNCTION_STATUS_VALUES = [
703
+ FUNCTION_STATUS.NOT_STARTED,
704
+ FUNCTION_STATUS.DEFINED_NEW,
705
+ FUNCTION_STATUS.DEFINED_EXISTING,
706
+ FUNCTION_STATUS.FUNCTIONAL,
707
+ FUNCTION_STATUS.FUTURE
708
+ ];
709
+ var FUNCTION_STATUS_LABELS = {
710
+ [FUNCTION_STATUS.NOT_STARTED]: "Not Started",
711
+ [FUNCTION_STATUS.DEFINED_NEW]: "Defined (New)",
712
+ [FUNCTION_STATUS.DEFINED_EXISTING]: "Defined (Existing PAVE)",
713
+ [FUNCTION_STATUS.FUNCTIONAL]: "Functional",
714
+ [FUNCTION_STATUS.FUTURE]: "Future (Not v1)"
715
+ };
716
+
717
+ // src/schemas/platform-function.ts
718
+ var platformFunctionSchemaDefinition = {
719
+ code: {
720
+ type: String,
721
+ required: true
722
+ },
723
+ label: {
724
+ type: String,
725
+ required: true
726
+ },
727
+ description: {
728
+ type: String,
729
+ default: ""
730
+ },
731
+ category: {
732
+ type: String,
733
+ default: ""
734
+ },
735
+ tools: {
736
+ type: [String],
737
+ enum: [...PLATFORM_TOOL_VALUES],
738
+ default: []
739
+ },
740
+ isAdminRelevant: {
741
+ type: Boolean,
742
+ default: false
743
+ },
744
+ isUserRelevant: {
745
+ type: Boolean,
746
+ default: false
747
+ },
748
+ isHtiOnly: {
749
+ type: Boolean,
750
+ default: false
751
+ },
752
+ status: {
753
+ type: String,
754
+ enum: [...FUNCTION_STATUS_VALUES],
755
+ default: "Not started"
756
+ },
757
+ sortOrder: {
758
+ type: Number,
759
+ default: 0
760
+ }
761
+ };
762
+ var platformFunctionSchemaOptions = {
763
+ timestamps: {
764
+ createdAt: "createdTime",
765
+ updatedAt: "updatedTime"
766
+ },
767
+ collection: "platformFunctions"
768
+ };
769
+ function buildPlatformFunctionSchema() {
770
+ const schema = new Schema5(
771
+ platformFunctionSchemaDefinition,
772
+ platformFunctionSchemaOptions
773
+ );
774
+ schema.index({ code: 1 }, { unique: true });
775
+ schema.index({ tools: 1 });
776
+ schema.index({ category: 1 });
777
+ schema.index({ sortOrder: 1 });
778
+ return schema;
779
+ }
780
+ var _platformFunctionSchema = buildPlatformFunctionSchema();
781
+
782
+ // src/schemas/platform-role.ts
783
+ import { Schema as Schema6 } from "mongoose";
784
+ var platformRoleSchemaDefinition = {
785
+ code: {
786
+ type: String,
787
+ required: true
788
+ },
789
+ label: {
790
+ type: String,
791
+ required: true
792
+ },
793
+ description: {
794
+ type: String,
795
+ default: ""
796
+ },
797
+ level: {
798
+ type: String,
799
+ enum: [...ROLE_LEVEL_VALUES],
800
+ required: true
801
+ },
802
+ tools: {
803
+ type: [String],
804
+ enum: [...PLATFORM_TOOL_VALUES],
805
+ default: []
806
+ },
807
+ shareView: {
808
+ type: String,
809
+ enum: [...SHARE_VIEW_VALUES, null],
810
+ default: null
811
+ },
812
+ trainingRequirements: {
813
+ type: String,
814
+ default: null
815
+ },
816
+ isHtiOnly: {
817
+ type: Boolean,
818
+ default: false
819
+ },
820
+ /** Dynamic map of functionCode → PermissionStateValue. */
821
+ functions: {
822
+ type: Schema6.Types.Mixed,
823
+ default: {}
824
+ },
825
+ sortOrder: {
826
+ type: Number,
827
+ default: 0
828
+ }
829
+ };
830
+ var platformRoleSchemaOptions = {
831
+ timestamps: {
832
+ createdAt: "createdTime",
833
+ updatedAt: "updatedTime"
834
+ },
835
+ collection: "platformRoles"
836
+ };
837
+ function buildPlatformRoleSchema() {
838
+ const schema = new Schema6(
839
+ platformRoleSchemaDefinition,
840
+ platformRoleSchemaOptions
841
+ );
842
+ schema.index({ code: 1 }, { unique: true });
843
+ schema.index({ level: 1 });
844
+ schema.index({ tools: 1 });
845
+ schema.index({ isHtiOnly: 1 });
846
+ return schema;
847
+ }
848
+ var _platformRoleSchema = buildPlatformRoleSchema();
849
+
850
+ // src/models/cvcRegistryModel.ts
851
+ var cvcRegistryModel_exports = {};
852
+ __export(cvcRegistryModel_exports, {
853
+ buildSchema: () => buildCvcRegistrySchema,
854
+ compileModel: () => compileModel
855
+ });
856
+
857
+ // src/schemas/cvcRegistry.ts
858
+ import { Schema as Schema7 } from "mongoose";
859
+ var cvcRegistrySchemaDefinition = {
860
+ // Versioning — semantic version of this registry bundle
861
+ version: {
862
+ type: String,
863
+ required: true,
864
+ match: /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/
865
+ },
866
+ // Human-readable name (e.g. "PAVE production registry")
867
+ name: {
868
+ type: String,
869
+ required: true
870
+ },
871
+ // Scope keys. `null` widens scope: a null `application` means platform-wide;
872
+ // a null `agencyId` means all agencies within `application`.
873
+ application: {
874
+ type: String,
875
+ default: null
876
+ },
877
+ agencyId: {
878
+ type: Schema7.Types.ObjectId,
879
+ default: null
880
+ },
881
+ // Lifecycle
882
+ status: {
883
+ type: String,
884
+ required: true,
885
+ enum: ["draft", "active", "deprecated"],
886
+ default: "draft",
887
+ index: true
888
+ },
889
+ dateActivated: {
890
+ type: Date
891
+ },
892
+ dateDeactivated: {
893
+ type: Date
894
+ },
895
+ // Pinned domain versions: { service_categories: "1.0.0", ... }
896
+ // Stored as a Map<string, string> so individual domains can be added or
897
+ // bumped without re-validating the whole document shape.
898
+ cvcVersions: {
899
+ type: Map,
900
+ of: String,
901
+ required: true,
902
+ default: () => /* @__PURE__ */ new Map()
903
+ },
904
+ // Selective inclusion/exclusion lists. Both contain CVC entry codes
905
+ // (positional 7-segment, e.g. "01-02-00-00-00-00-00"). The runtime
906
+ // applies excludes after includes when resolving the effective set.
907
+ excludedEntries: {
908
+ type: [String],
909
+ default: []
910
+ },
911
+ includedEntries: {
912
+ type: [String],
913
+ default: []
914
+ },
915
+ // Inheritance pointer — when set, this registry inherits cvcVersions /
916
+ // include / exclude lists from its base before applying its own overrides.
917
+ // Indexed below so a base-version bump can find every dependent registry.
918
+ basedOn: {
919
+ type: Schema7.Types.ObjectId,
920
+ default: null
921
+ }
922
+ };
923
+ var cvcRegistrySchemaOptions = {
924
+ timestamps: true,
925
+ collection: "cvc_registries"
926
+ };
927
+ function buildCvcRegistrySchema() {
928
+ const schema = new Schema7(
929
+ cvcRegistrySchemaDefinition,
930
+ cvcRegistrySchemaOptions
931
+ );
932
+ schema.index(
933
+ { application: 1, agencyId: 1, version: 1 },
934
+ { unique: true }
935
+ );
936
+ schema.index(
937
+ { application: 1, agencyId: 1, status: 1 },
938
+ {
939
+ unique: true,
940
+ partialFilterExpression: { status: "active" }
941
+ }
942
+ );
943
+ schema.index({ basedOn: 1 });
944
+ return schema;
945
+ }
946
+ var _cvcRegistrySchema = buildCvcRegistrySchema();
947
+
948
+ // src/models/cvcRegistryModel.ts
949
+ function compileModel(connection, schema = buildCvcRegistrySchema()) {
950
+ return connection.models?.CvcRegistry ?? connection.model("CvcRegistry", schema);
951
+ }
952
+
953
+ // src/models/cvcEntryModel.ts
954
+ var cvcEntryModel_exports = {};
955
+ __export(cvcEntryModel_exports, {
956
+ buildSchema: () => buildCvcEntrySchema,
957
+ compileModel: () => compileModel2
958
+ });
959
+
960
+ // src/schemas/cvcEntry.ts
961
+ import { Schema as Schema8 } from "mongoose";
962
+ var CVC_CODE_PATTERN = /^\d{2}(-\d{2}){6}$/;
963
+ var CVC_KEY_PATTERN = /^[a-z][a-z0-9_]*$/;
964
+ var cvcEntrySchemaDefinition = {
965
+ // Compound identity: (domain, version, code) uniquely identifies an entry.
966
+ // `domain` is the SOT family (e.g. "service_categories"); `version` is the
967
+ // semantic version of the SOT JSON file the entry was loaded from.
968
+ domain: {
969
+ type: String,
970
+ required: true
971
+ },
972
+ version: {
973
+ type: String,
974
+ required: true
975
+ },
976
+ code: {
977
+ type: String,
978
+ required: true,
979
+ match: CVC_CODE_PATTERN
980
+ },
981
+ // Stable machine key for cross-CVC references (e.g. `relevantMechanisms`
982
+ // in service_categories points at service_mechanisms entries by `key`).
983
+ key: {
984
+ type: String,
985
+ required: true,
986
+ match: CVC_KEY_PATTERN
987
+ },
988
+ // Display fields
989
+ title: {
990
+ type: String,
991
+ required: true
992
+ },
993
+ // `selectable` distinguishes leaf entries (selectable) from structural
994
+ // grouping rows (not selectable). Required because the seed CLI must
995
+ // populate it explicitly — there is no sane default.
996
+ selectable: {
997
+ type: Boolean,
998
+ required: true
999
+ },
1000
+ // Tree structure. `parentCode` is `null` for root rows; `childCodes` is
1001
+ // empty for leaves. We give `parentCode` a `default: null` (rather than
1002
+ // marking it required) because Mongoose's `required` validator rejects
1003
+ // `null` outright — the default ensures the field is always present on
1004
+ // disk while still allowing the documented `string | null` shape. The
1005
+ // `match` validator is skipped by Mongoose when the value is null.
1006
+ parentCode: {
1007
+ type: String,
1008
+ default: null,
1009
+ match: CVC_CODE_PATTERN
1010
+ },
1011
+ childCodes: {
1012
+ type: [String],
1013
+ required: true,
1014
+ default: []
1015
+ },
1016
+ // Long-form definition. Same `default: null` treatment as `parentCode`
1017
+ // above — every row reaches disk with `definition` set to either a
1018
+ // string or an explicit null.
1019
+ definition: {
1020
+ type: String,
1021
+ default: null
1022
+ },
1023
+ // Domain-specific extension bag. Used for fields that only apply to a
1024
+ // particular CVC family — e.g. `relevantMechanisms` on service_categories
1025
+ // entries (a cross-CVC reference into service_mechanisms by key).
1026
+ meta: {
1027
+ type: Schema8.Types.Mixed
1028
+ }
1029
+ };
1030
+ var cvcEntrySchemaOptions = {
1031
+ timestamps: true,
1032
+ collection: "cvc_entities",
1033
+ // `parentCode` defaults to null but Mongoose strips required-with-default
1034
+ // null assignments unless we keep minimize off.
1035
+ minimize: false
1036
+ };
1037
+ function buildCvcEntrySchema() {
1038
+ const schema = new Schema8(cvcEntrySchemaDefinition, cvcEntrySchemaOptions);
1039
+ schema.index(
1040
+ { domain: 1, version: 1, code: 1 },
1041
+ { unique: true }
1042
+ );
1043
+ schema.index(
1044
+ { domain: 1, version: 1, key: 1 },
1045
+ { unique: true }
1046
+ );
1047
+ schema.index({ domain: 1, version: 1, parentCode: 1 });
1048
+ return schema;
1049
+ }
1050
+ var _cvcEntrySchema = buildCvcEntrySchema();
1051
+
1052
+ // src/models/cvcEntryModel.ts
1053
+ function compileModel2(connection, schema = buildCvcEntrySchema()) {
1054
+ return connection.models?.CvcEntry ?? connection.model("CvcEntry", schema);
1055
+ }
1056
+
1057
+ // src/services/cvcRegistryService.ts
1058
+ function cvcVersionsToRecord(versions) {
1059
+ if (!versions) return {};
1060
+ if (versions instanceof Map) {
1061
+ return Object.fromEntries(versions.entries());
1062
+ }
1063
+ return { ...versions };
1064
+ }
1065
+ function cascadeExclusions(excludedCodes, entries) {
1066
+ const result = new Set(excludedCodes);
1067
+ const childMap = /* @__PURE__ */ new Map();
1068
+ for (const entry of entries) {
1069
+ if (entry.parentCode) {
1070
+ const siblings = childMap.get(entry.parentCode);
1071
+ if (siblings) {
1072
+ siblings.push(entry.code);
1073
+ } else {
1074
+ childMap.set(entry.parentCode, [entry.code]);
1075
+ }
1076
+ }
1077
+ }
1078
+ const queue = [...excludedCodes];
1079
+ while (queue.length > 0) {
1080
+ const code = queue.shift();
1081
+ const children = childMap.get(code);
1082
+ if (!children) continue;
1083
+ for (const childCode of children) {
1084
+ if (!result.has(childCode)) {
1085
+ result.add(childCode);
1086
+ queue.push(childCode);
1087
+ }
1088
+ }
1089
+ }
1090
+ return result;
1091
+ }
1092
+ function applyEntryOverrides(excludedEntries, includedEntries, entries) {
1093
+ const excluded = new Set(excludedEntries ?? []);
1094
+ const included = new Set(includedEntries ?? []);
1095
+ const hasExclusions = excluded.size > 0;
1096
+ const hasInclusions = included.size > 0;
1097
+ if (!hasExclusions && !hasInclusions) {
1098
+ return [...entries];
1099
+ }
1100
+ if (!hasExclusions && hasInclusions) {
1101
+ return entries.filter((entry) => included.has(entry.code));
1102
+ }
1103
+ const cascadedExclusions = cascadeExclusions(excluded, entries);
1104
+ return entries.filter((entry) => {
1105
+ if (included.has(entry.code)) return true;
1106
+ if (cascadedExclusions.has(entry.code)) return false;
1107
+ return true;
1108
+ });
1109
+ }
1110
+ async function resolveRegistryWithInheritance(registry, loadRegistry, loadEntries) {
1111
+ const childVersions = cvcVersionsToRecord(registry.cvcVersions);
1112
+ let mergedVersions = { ...childVersions };
1113
+ if (registry.basedOn) {
1114
+ const base = await loadRegistry(registry.basedOn);
1115
+ if (!base) {
1116
+ throw new Error(
1117
+ `CvcRegistryService: basedOn registry not found: ${registry.basedOn.toString()}`
1118
+ );
1119
+ }
1120
+ mergedVersions = {
1121
+ ...cvcVersionsToRecord(base.cvcVersions),
1122
+ ...childVersions
1123
+ };
1124
+ }
1125
+ const pool = [];
1126
+ for (const [domain, version] of Object.entries(mergedVersions)) {
1127
+ const domainEntries = await loadEntries(domain, version);
1128
+ pool.push(...domainEntries);
1129
+ }
1130
+ const entries = applyEntryOverrides(
1131
+ registry.excludedEntries,
1132
+ registry.includedEntries,
1133
+ pool
1134
+ );
1135
+ return { mergedVersions, entries };
1136
+ }
1137
+ function scopeFilter(scope) {
1138
+ return {
1139
+ application: scope.application ?? null,
1140
+ agencyId: scope.agencyId ?? null
1141
+ };
1142
+ }
1143
+ function cacheKeyFor(registryId) {
1144
+ return registryId.toString();
1145
+ }
1146
+ var CvcRegistryService = class {
1147
+ registryModel;
1148
+ entryModel;
1149
+ scopeFallback;
1150
+ /**
1151
+ * Cached resolved entry set per registry id. The value is the full
1152
+ * post-override entry list — domain filtering is done on read so the
1153
+ * cache stays domain-agnostic. Cleared on activate/deprecate of any
1154
+ * registry that overlaps the cached scope.
1155
+ */
1156
+ resolvedCache = /* @__PURE__ */ new Map();
1157
+ /**
1158
+ * @param connection - Mongoose connection that owns `cvc_registries` and `cvc_entries`
1159
+ * @param options - Optional behavior toggles (see {@link CvcRegistryServiceOptions})
1160
+ */
1161
+ constructor(connection, options = {}) {
1162
+ this.registryModel = cvcRegistryModel_exports.compileModel(
1163
+ connection
1164
+ );
1165
+ this.entryModel = cvcEntryModel_exports.compileModel(
1166
+ connection
1167
+ );
1168
+ this.scopeFallback = options.scopeFallback ?? true;
1169
+ }
1170
+ // ──────────────────────────────────────────────────────────────────────────
1171
+ // Registry lifecycle
1172
+ // ──────────────────────────────────────────────────────────────────────────
1173
+ /**
1174
+ * Find the active registry for a scope, walking the fallback chain
1175
+ * (agency-specific → app-specific → platform-default) when enabled. Returns
1176
+ * `null` if no active registry exists at any level of the chain.
1177
+ */
1178
+ async getActiveRegistry(scope) {
1179
+ const candidates = [scope];
1180
+ if (this.scopeFallback) {
1181
+ if (scope.agencyId != null && scope.application != null) {
1182
+ candidates.push({ application: scope.application, agencyId: null });
1183
+ }
1184
+ if (scope.application != null) {
1185
+ candidates.push({ application: null, agencyId: null });
1186
+ }
1187
+ }
1188
+ for (const candidate of candidates) {
1189
+ const found = await this.registryModel.findOne({ ...scopeFilter(candidate), status: "active" }).lean().exec();
1190
+ if (found) return found;
1191
+ }
1192
+ return null;
1193
+ }
1194
+ /**
1195
+ * Look up a registry by its `(scope, version)` tuple. The scope must be
1196
+ * exact — there is no fallback chain here, since version pins are scope-
1197
+ * specific by definition.
1198
+ */
1199
+ async getRegistry(scope, version) {
1200
+ return this.registryModel.findOne({ ...scopeFilter(scope), version }).lean().exec();
1201
+ }
1202
+ /**
1203
+ * List every registry version for an exact scope, regardless of status.
1204
+ * Sorted by version so callers get a deterministic ordering for change
1205
+ * logs / version pickers. The version field is a semver string, so the
1206
+ * sort is lexicographic — good enough for the typical 1.0.0 / 1.1.0 case.
1207
+ */
1208
+ async listVersions(scope) {
1209
+ return this.registryModel.find(scopeFilter(scope)).sort({ version: 1 }).lean().exec();
1210
+ }
1211
+ /**
1212
+ * Promote a draft registry to `active`. Atomically demotes the previous
1213
+ * active registry in the same scope to `deprecated` so the
1214
+ * one-active-per-scope invariant holds even under concurrent activations
1215
+ * (the partial unique index on `cvc_registries` enforces this at the DB
1216
+ * layer; we mirror it here for clarity).
1217
+ *
1218
+ * @throws Error if the target registry doesn't exist or isn't in `draft`
1219
+ */
1220
+ async activate(registryId) {
1221
+ const target = await this.registryModel.findById(registryId).lean().exec();
1222
+ if (!target) {
1223
+ throw new Error(
1224
+ `CvcRegistryService.activate: registry not found: ${registryId.toString()}`
1225
+ );
1226
+ }
1227
+ if (target.status !== "draft") {
1228
+ throw new Error(
1229
+ `CvcRegistryService.activate: registry ${registryId.toString()} is '${target.status}', expected 'draft'`
1230
+ );
1231
+ }
1232
+ const now = /* @__PURE__ */ new Date();
1233
+ await this.registryModel.updateOne(
1234
+ {
1235
+ application: target.application ?? null,
1236
+ agencyId: target.agencyId ?? null,
1237
+ status: "active"
1238
+ },
1239
+ { $set: { status: "deprecated", dateDeactivated: now } }
1240
+ ).exec();
1241
+ const activated = await this.registryModel.findByIdAndUpdate(
1242
+ registryId,
1243
+ { $set: { status: "active", dateActivated: now } },
1244
+ { new: true }
1245
+ ).lean().exec();
1246
+ if (!activated) {
1247
+ throw new Error(
1248
+ `CvcRegistryService.activate: registry vanished mid-update: ${registryId.toString()}`
1249
+ );
1250
+ }
1251
+ this.resolvedCache.clear();
1252
+ return activated;
1253
+ }
1254
+ /**
1255
+ * Demote an active registry to `deprecated`. Idempotent only in the sense
1256
+ * that calling it twice on the same registry will fail the second time —
1257
+ * we don't allow re-deprecating something that's already deprecated, so
1258
+ * the lifecycle stays a strict state machine.
1259
+ *
1260
+ * @throws Error if the target registry doesn't exist or isn't `active`
1261
+ */
1262
+ async deprecate(registryId) {
1263
+ const target = await this.registryModel.findById(registryId).lean().exec();
1264
+ if (!target) {
1265
+ throw new Error(
1266
+ `CvcRegistryService.deprecate: registry not found: ${registryId.toString()}`
1267
+ );
1268
+ }
1269
+ if (target.status !== "active") {
1270
+ throw new Error(
1271
+ `CvcRegistryService.deprecate: registry ${registryId.toString()} is '${target.status}', expected 'active'`
1272
+ );
1273
+ }
1274
+ const updated = await this.registryModel.findByIdAndUpdate(
1275
+ registryId,
1276
+ { $set: { status: "deprecated", dateDeactivated: /* @__PURE__ */ new Date() } },
1277
+ { new: true }
1278
+ ).lean().exec();
1279
+ if (!updated) {
1280
+ throw new Error(
1281
+ `CvcRegistryService.deprecate: registry vanished mid-update: ${registryId.toString()}`
1282
+ );
1283
+ }
1284
+ this.resolvedCache.clear();
1285
+ return updated;
1286
+ }
1287
+ // ──────────────────────────────────────────────────────────────────────────
1288
+ // Entry resolution (core — all convenience methods funnel through here)
1289
+ // ──────────────────────────────────────────────────────────────────────────
1290
+ /**
1291
+ * Resolve a registry into its effective entry list, applying inheritance
1292
+ * and overrides. Results are memoised by registry id; the cache is
1293
+ * invalidated on `activate()` / `deprecate()`.
1294
+ */
1295
+ async resolveEntries(registryId) {
1296
+ const cacheKey = cacheKeyFor(registryId);
1297
+ const cached = this.resolvedCache.get(cacheKey);
1298
+ if (cached) return cached;
1299
+ const registry = await this.registryModel.findById(registryId).lean().exec();
1300
+ if (!registry) {
1301
+ throw new Error(
1302
+ `CvcRegistryService.resolveEntries: registry not found: ${registryId.toString()}`
1303
+ );
1304
+ }
1305
+ const { entries } = await resolveRegistryWithInheritance(
1306
+ registry,
1307
+ (id) => this.registryModel.findById(id).lean().exec(),
1308
+ (domain, version) => this.entryModel.find({ domain, version }).lean().exec()
1309
+ );
1310
+ this.resolvedCache.set(cacheKey, entries);
1311
+ return entries;
1312
+ }
1313
+ /**
1314
+ * Same as {@link resolveEntries} but filtered to a single CVC domain.
1315
+ * Filtering is done on the cached set so repeated calls for different
1316
+ * domains share the same underlying load.
1317
+ */
1318
+ async resolveEntriesForDomain(registryId, domain) {
1319
+ const all = await this.resolveEntries(registryId);
1320
+ return all.filter((entry) => entry.domain === domain);
1321
+ }
1322
+ // ──────────────────────────────────────────────────────────────────────────
1323
+ // Entry lookups (convenience — resolve through the active registry)
1324
+ // ──────────────────────────────────────────────────────────────────────────
1325
+ /**
1326
+ * Find an entry by its 7-segment positional code within the active
1327
+ * registry for `scope`. Returns `null` if no active registry exists or
1328
+ * the code isn't present in the resolved entry set.
1329
+ */
1330
+ async getEntryByCode(scope, code) {
1331
+ const registry = await this.getActiveRegistry(scope);
1332
+ if (!registry) return null;
1333
+ const entries = await this.resolveEntries(registry._id);
1334
+ return entries.find((entry) => entry.code === code) ?? null;
1335
+ }
1336
+ /**
1337
+ * Find an entry by its stable machine key within a specific domain in the
1338
+ * active registry. Keys are unique per `(domain, version)` so the lookup
1339
+ * always returns at most one entry.
1340
+ */
1341
+ async getEntryByKey(scope, domain, key) {
1342
+ const registry = await this.getActiveRegistry(scope);
1343
+ if (!registry) return null;
1344
+ const entries = await this.resolveEntriesForDomain(registry._id, domain);
1345
+ return entries.find((entry) => entry.key === key) ?? null;
1346
+ }
1347
+ /**
1348
+ * Get every resolved entry for a given domain in the active registry.
1349
+ */
1350
+ async getEntries(scope, domain) {
1351
+ const registry = await this.getActiveRegistry(scope);
1352
+ if (!registry) return [];
1353
+ return this.resolveEntriesForDomain(registry._id, domain);
1354
+ }
1355
+ /**
1356
+ * Get only the selectable (leaf) entries for a domain — useful for form
1357
+ * dropdowns where structural grouping rows must be hidden.
1358
+ */
1359
+ async getSelectableEntries(scope, domain) {
1360
+ const entries = await this.getEntries(scope, domain);
1361
+ return entries.filter((entry) => entry.selectable);
1362
+ }
1363
+ /**
1364
+ * Get the direct children of a parent code within the active registry.
1365
+ * Returns `[]` for leaves and for codes not present in the resolved set.
1366
+ */
1367
+ async getChildren(scope, code) {
1368
+ const registry = await this.getActiveRegistry(scope);
1369
+ if (!registry) return [];
1370
+ const entries = await this.resolveEntries(registry._id);
1371
+ return entries.filter((entry) => entry.parentCode === code);
1372
+ }
1373
+ /**
1374
+ * Walk the parent chain from `code` up to the tree root, returning the
1375
+ * ancestors in **root → entry** order (the entry itself is not included).
1376
+ * Stops early if a parent code references an entry that isn't present in
1377
+ * the resolved set — that's a corrupt-tree signal but we'd rather return
1378
+ * a partial chain than throw inside a UI breadcrumb call.
1379
+ */
1380
+ async getAncestors(scope, code) {
1381
+ const registry = await this.getActiveRegistry(scope);
1382
+ if (!registry) return [];
1383
+ const entries = await this.resolveEntries(registry._id);
1384
+ const byCode = new Map(entries.map((entry) => [entry.code, entry]));
1385
+ const chain = [];
1386
+ let current = byCode.get(code);
1387
+ const seen = /* @__PURE__ */ new Set();
1388
+ while (current?.parentCode && !seen.has(current.parentCode)) {
1389
+ seen.add(current.parentCode);
1390
+ const parent = byCode.get(current.parentCode);
1391
+ if (!parent) break;
1392
+ chain.push(parent);
1393
+ current = parent;
1394
+ }
1395
+ return chain.reverse();
1396
+ }
1397
+ // ──────────────────────────────────────────────────────────────────────────
1398
+ // Test seam: cache introspection
1399
+ // ──────────────────────────────────────────────────────────────────────────
1400
+ /**
1401
+ * Test-only accessor for the resolved-entry cache. Exposed so service
1402
+ * tests can assert that `activate()` / `deprecate()` actually flush the
1403
+ * cache, and so consumers diagnosing stale-data bugs can dump the live
1404
+ * keyset. Not part of the locked spec API surface — treat as internal.
1405
+ */
1406
+ get __cacheKeysForTests() {
1407
+ return [...this.resolvedCache.keys()];
1408
+ }
1409
+ };
1410
+ export {
1411
+ CvcRegistryService,
1412
+ applyEntryOverrides,
1413
+ cascadeExclusions,
1414
+ cvcVersionsToRecord,
1415
+ resolveRegistryWithInheritance
1416
+ };
1417
+ //# sourceMappingURL=index.js.map