sos-sdk-core-ts 0.2.2 → 0.3.0

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.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,25 @@
2
2
 
3
3
  ## Unreleased
4
4
 
5
+ ## 0.3.0 - 2026-09-26
6
+
7
+ - Pin `sos-data-utils-ts@0.4.1`, which owns the Organization fallback target
8
+ and governed public-risk campaign criteria used by this release.
9
+ - Add idempotent fulfilled-Appointment to Encounter orchestration with
10
+ Appointment, subject, service provider and current Location continuity.
11
+ - Add fail-closed authorization for encounter-related voice, video and secure
12
+ messages. Calls never carry clinical Bundles, and preliminary Bundles may be
13
+ delivered only without updating the subject index.
14
+ - Create independent compact-coded emergency ServiceRequest and triage Task
15
+ entries targeting a HealthcareService or its owning Organization.
16
+ - Add frozen-cohort CommunicationRequest orchestration and per-recipient
17
+ delivery checks for blood-donation and governed FHIR SearchParameter
18
+ public-risk campaigns.
19
+ - Replace copied emergency Group members and split coding claims with the
20
+ canonical Group-reference and compact-code contract.
21
+ - Document the immutable main-tarball local Vet proof required before npm
22
+ publication and staging.
23
+
5
24
  ## 0.2.2 - 2026-09-25
6
25
 
7
26
  - Add runtime-neutral ML-KEM-768 multi-recipient encryption for written and
package/README.md CHANGED
@@ -1,12 +1,15 @@
1
1
  # Shared SOS SDK Core
2
2
  ## Blocking local-first SDK release
3
3
 
4
- The canonical contract is [`SDK_LAYERING.md`](https://github.com/Fundacion-UNID/sos-data-utils-ts/blob/main/docs/SDK_LAYERING.md). Its
5
- indivisible order is **local packages -> full local test matrix -> merge every
6
- validated branch to `main` -> publish bottom-up -> install exact registry
7
- versions and commit lockfiles on `main` -> staging**. Never publish to discover
8
- deterministic failures and never commit a local package reference. Staging
9
- begins only after exact registry packages are installed and verified.
4
+ The canonical contract is [`SDK_LAYERING.md`](https://github.com/Fundacion-UNID/sos-data-utils-ts/blob/main/docs/SDK_LAYERING.md).
5
+ Merge and push validated shared dependency sources to `main`, create immutable
6
+ unpublished tarballs from those main commits with `npm pack`, and install them
7
+ temporarily with `--no-save`. Prove the real local Vet channel (portal, phone
8
+ service, chatbot or other supported channel) -> BFF or channel service ->
9
+ high-level SDK -> GW VET journey without skips. Then merge the consumer source
10
+ to `main`, publish the exact commits bottom-up, pin exact registry versions and
11
+ lockfiles, repeat affected local gates, and only then promote to staging.
12
+ Never commit a tarball or `file:`, Git or workspace dependency.
10
13
 
11
14
 
12
15
  Runtime-neutral shared SDK for SOSChain, VetChain and UHC. Deterministic
@@ -35,13 +38,11 @@ jobs; those adapters do not belong here.
35
38
  Git, workspace, vendored and `file:` dependencies are forbidden in committed
36
39
  or deployed dependency state.
37
40
 
38
- The emergency-group contract treats `emergencyGroupId`, `subjectId` and
39
- `callerId` as opaque business identifiers. A group assistance request is one
40
- flat `ServiceRequest.*` claims under `resource.meta.claims`. A FHIR R5, R6 or
41
- other resource is projected only at an integration boundary.
42
-
43
- Groups are named collections. A scanned card is attached to one selected group
44
- before that group's identifiers are projected into a single service request.
41
+ The emergency-group contract stores subject references only on an enumerated
42
+ FHIR Group. A group assistance request references that Group from one standard,
43
+ compact-coded ServiceRequest; it never copies members or persists split coding
44
+ claims. Flat claims remain the canonical storage representation and native
45
+ FHIR is projected only at an explicit boundary.
45
46
 
46
47
  `authorizeEmergencyAction` separately checks trusted evidence for every
47
48
  member and for `sos:call` or `sos:request`. Identity verification alone never
@@ -57,6 +58,18 @@ to the same types and implementation; they are not a second contract.
57
58
  `buildSoschainPlaceCardAssociationClaims` records a UHC/VetChain card link to
58
59
  a canonical SOSChain Place or vehicle without merging either identity.
59
60
 
61
+ ## Care, emergency and alert orchestration
62
+
63
+ `sos-sdk-core-ts/care-emergency-alert-orchestration` supplies the shared,
64
+ runtime-neutral plans for Appointment-to-Encounter continuity, protected
65
+ pre-publication calls/messages, resilient emergency ServiceRequest plus triage
66
+ Task creation, and governed donation/public-risk campaigns. Transport,
67
+ persistence, authorization evidence acquisition and product policy remain in
68
+ the channel service, Node adapter and Vet/UHC/SOSChain layers.
69
+
70
+ See [docs/CARE_EMERGENCY_AND_ALERT_ORCHESTRATION.md](docs/CARE_EMERGENCY_AND_ALERT_ORCHESTRATION.md)
71
+ for lifecycle, authorization and persistence invariants.
72
+
60
73
  ## Multi-recipient secure messages
61
74
 
62
75
  `sos-sdk-core-ts/secure-message-crypto` protects written and binary-audio
@@ -0,0 +1,84 @@
1
+ import { type CareJourneyTransition, type EmergencyIntake, type GovernedAlertCampaign, type GovernedAlertCohortSnapshot, type GovernedAlertDeliveryAudit } from 'sos-data-utils-ts/care-emergency-alert-records';
2
+ import { type ClinicalCoding } from 'fhir-data-utils-ts/care-emergency-alert';
3
+ import type { FlatClaimResourceEntry } from 'fhir-data-utils-ts/flat-claim-resource-graph';
4
+ export type FulfilledAppointmentEncounterPlan = Readonly<{
5
+ created: false;
6
+ encounterReference: string;
7
+ }> | Readonly<{
8
+ created: true;
9
+ encounterReference: string;
10
+ encounterEntry: FlatClaimResourceEntry;
11
+ }>;
12
+ /**
13
+ * Plans one idempotent Appointment-to-Encounter transition. Persistence must
14
+ * enforce `idempotencyKey`; an existing reference suppresses duplicate writes.
15
+ */
16
+ export declare function orchestrateFulfilledAppointment(input: Readonly<{
17
+ transition: CareJourneyTransition;
18
+ encounterIdentifier: string;
19
+ existingEncounterReference?: string;
20
+ }>): FulfilledAppointmentEncounterPlan;
21
+ export type EncounterCommunicationAuthorization = Readonly<{
22
+ encounterReference: string;
23
+ actorReference: string;
24
+ recipientReferences: readonly string[];
25
+ channel: 'voice' | 'video' | 'encrypted-message';
26
+ includesClinicalBundle: boolean;
27
+ clinicalStatus?: 'preliminary' | 'final';
28
+ updateIndex: boolean;
29
+ }>;
30
+ /**
31
+ * Authorizes only the channel boundary. It never attests clinical data.
32
+ * Preliminary encrypted Bundles may be delivered directly but cannot update
33
+ * the subject index; voice/video signaling cannot carry a clinical Bundle.
34
+ */
35
+ export declare function authorizeEncounterCommunication(input: Readonly<{
36
+ encounterReference: string;
37
+ actorReference: string;
38
+ recipientReferences: readonly string[];
39
+ actorCanCommunicate: boolean;
40
+ encounterActive: boolean;
41
+ channel: EncounterCommunicationAuthorization['channel'];
42
+ includesClinicalBundle: boolean;
43
+ clinicalStatus?: 'preliminary' | 'final';
44
+ updateIndex: boolean;
45
+ }>): EncounterCommunicationAuthorization;
46
+ /** Creates independent standard ServiceRequest and durable triage Task entries. */
47
+ export declare function orchestrateEmergencyRequest(input: Readonly<{
48
+ intake: EmergencyIntake;
49
+ serviceRequestIdentifier: string;
50
+ triageTaskIdentifier: string;
51
+ assistanceCode: ClinicalCoding;
52
+ }>): Readonly<{
53
+ intake: EmergencyIntake;
54
+ serviceRequestEntry: FlatClaimResourceEntry;
55
+ triageTaskEntry: FlatClaimResourceEntry;
56
+ }>;
57
+ export type GovernedAlertCampaignPlan = Readonly<{
58
+ campaign: GovernedAlertCampaign;
59
+ cohortSnapshot: GovernedAlertCohortSnapshot;
60
+ communicationRequestEntry: FlatClaimResourceEntry;
61
+ }>;
62
+ /** Builds one campaign request bound to the frozen evaluated Group snapshot. */
63
+ export declare function prepareGovernedAlertCampaign(input: Readonly<{
64
+ campaign: GovernedAlertCampaign;
65
+ snapshotGroupReference: string;
66
+ evaluatedAt: string;
67
+ evaluationFingerprint: string;
68
+ eligibleSubjectReferences: readonly string[];
69
+ communicationRequestEntryId: string;
70
+ communicationRequestIdentifier: string;
71
+ category: ClinicalCoding;
72
+ }>): GovernedAlertCampaignPlan;
73
+ /** Rechecks frozen membership before recording the data-layer delivery audit. */
74
+ export declare function prepareGovernedAlertDelivery(input: Readonly<{
75
+ campaignPlan: GovernedAlertCampaignPlan;
76
+ recipientReference: string;
77
+ communicationReference: string;
78
+ evaluatedAt: string;
79
+ eligibilityCurrent: boolean;
80
+ exclusionCurrent: boolean;
81
+ consentReference?: string;
82
+ channelAuthorizationReference?: string;
83
+ outcome: 'sent' | 'suppressed';
84
+ }>): GovernedAlertDeliveryAudit;
@@ -0,0 +1,139 @@
1
+ import { freezeGovernedAlertCohort, normalizeCareJourneyTransition, normalizeEmergencyIntake, normalizeGovernedAlertCampaign, recordGovernedAlertDelivery, } from 'sos-data-utils-ts/care-emergency-alert-records';
2
+ import { buildCohortCommunicationRequestFlatEntry, buildEncounterCareJourneyFlatGraph, buildServiceRequestFlatEntry, buildServiceRequestTriageTaskFlatEntry, } from 'fhir-data-utils-ts/care-emergency-alert';
3
+ /**
4
+ * Plans one idempotent Appointment-to-Encounter transition. Persistence must
5
+ * enforce `idempotencyKey`; an existing reference suppresses duplicate writes.
6
+ */
7
+ export function orchestrateFulfilledAppointment(input) {
8
+ const transition = normalizeCareJourneyTransition(input.transition);
9
+ if (input.existingEncounterReference) {
10
+ return Object.freeze({
11
+ created: false,
12
+ encounterReference: reference(input.existingEncounterReference, 'Encounter', 'existing_encounter_reference_invalid'),
13
+ });
14
+ }
15
+ const encounterEntry = buildEncounterCareJourneyFlatGraph({
16
+ parent: {
17
+ entryId: transition.encounterEntryId,
18
+ identifier: input.encounterIdentifier,
19
+ status: 'in-progress',
20
+ subjectReference: transition.subjectReference,
21
+ appointmentReference: transition.appointmentReference,
22
+ serviceProviderReference: transition.serviceProviderReference,
23
+ periodStart: transition.occurredAt,
24
+ locationReference: transition.locationReference,
25
+ },
26
+ })[0];
27
+ return Object.freeze({ created: true, encounterReference: encounterEntry.reference, encounterEntry });
28
+ }
29
+ /**
30
+ * Authorizes only the channel boundary. It never attests clinical data.
31
+ * Preliminary encrypted Bundles may be delivered directly but cannot update
32
+ * the subject index; voice/video signaling cannot carry a clinical Bundle.
33
+ */
34
+ export function authorizeEncounterCommunication(input) {
35
+ if (!input.actorCanCommunicate)
36
+ throw new Error('encounter_communication_actor_forbidden');
37
+ if (!input.encounterActive)
38
+ throw new Error('encounter_communication_inactive_encounter');
39
+ if ((input.channel === 'voice' || input.channel === 'video') && input.includesClinicalBundle) {
40
+ throw new Error('encounter_call_clinical_bundle_forbidden');
41
+ }
42
+ if (input.includesClinicalBundle && !input.clinicalStatus)
43
+ throw new Error('encounter_communication_clinical_status_required');
44
+ if (input.clinicalStatus === 'preliminary' && input.updateIndex)
45
+ throw new Error('preliminary_clinical_index_update_forbidden');
46
+ const recipientReferences = uniqueReferences(input.recipientReferences, 'encounter_communication_recipient_required');
47
+ return Object.freeze({
48
+ encounterReference: reference(input.encounterReference, 'Encounter', 'encounter_communication_encounter_reference_invalid'),
49
+ actorReference: reference(input.actorReference, undefined, 'encounter_communication_actor_reference_invalid'),
50
+ recipientReferences,
51
+ channel: input.channel,
52
+ includesClinicalBundle: input.includesClinicalBundle,
53
+ ...(input.clinicalStatus ? { clinicalStatus: input.clinicalStatus } : {}),
54
+ updateIndex: input.updateIndex,
55
+ });
56
+ }
57
+ /** Creates independent standard ServiceRequest and durable triage Task entries. */
58
+ export function orchestrateEmergencyRequest(input) {
59
+ const intake = normalizeEmergencyIntake(input.intake);
60
+ const serviceRequestEntry = buildServiceRequestFlatEntry({
61
+ entryId: intake.serviceRequestEntryId,
62
+ identifier: input.serviceRequestIdentifier,
63
+ status: 'active',
64
+ intent: 'order',
65
+ priority: 'stat',
66
+ code: input.assistanceCode,
67
+ subjectReference: intake.subjectReference,
68
+ requesterReference: intake.requesterReference,
69
+ performerReferences: [intake.targetServiceReference],
70
+ authoredAt: intake.receivedAt,
71
+ });
72
+ const triageTaskEntry = buildServiceRequestTriageTaskFlatEntry({
73
+ entryId: intake.triageTaskEntryId,
74
+ identifier: input.triageTaskIdentifier,
75
+ serviceRequestReference: serviceRequestEntry.reference,
76
+ subjectReference: intake.subjectReference,
77
+ requesterReference: intake.requesterReference,
78
+ ownerReference: intake.triageOwnerReference,
79
+ authoredAt: intake.receivedAt,
80
+ });
81
+ return Object.freeze({ intake, serviceRequestEntry, triageTaskEntry });
82
+ }
83
+ /** Builds one campaign request bound to the frozen evaluated Group snapshot. */
84
+ export function prepareGovernedAlertCampaign(input) {
85
+ const campaign = normalizeGovernedAlertCampaign(input.campaign);
86
+ const cohortSnapshot = freezeGovernedAlertCohort({
87
+ campaign,
88
+ snapshotGroupReference: input.snapshotGroupReference,
89
+ evaluatedAt: input.evaluatedAt,
90
+ evaluationFingerprint: input.evaluationFingerprint,
91
+ eligibleSubjectReferences: input.eligibleSubjectReferences,
92
+ });
93
+ const communicationRequestEntry = buildCohortCommunicationRequestFlatEntry({
94
+ entryId: input.communicationRequestEntryId,
95
+ identifier: input.communicationRequestIdentifier,
96
+ status: 'active',
97
+ priority: 'routine',
98
+ category: input.category,
99
+ subjectReference: cohortSnapshot.snapshotGroupReference,
100
+ requesterReference: campaign.requesterReference,
101
+ authoredAt: cohortSnapshot.evaluatedAt,
102
+ reasonReferences: [campaign.groupDefinitionReference],
103
+ });
104
+ return Object.freeze({ campaign, cohortSnapshot, communicationRequestEntry });
105
+ }
106
+ /** Rechecks frozen membership before recording the data-layer delivery audit. */
107
+ export function prepareGovernedAlertDelivery(input) {
108
+ const recipientReference = reference(input.recipientReference, undefined, 'alert_delivery_recipient_reference_invalid');
109
+ if (!input.campaignPlan.cohortSnapshot.eligibleSubjectReferences.includes(recipientReference)) {
110
+ throw new Error('alert_delivery_recipient_not_in_snapshot');
111
+ }
112
+ return recordGovernedAlertDelivery({
113
+ campaignId: input.campaignPlan.campaign.campaignId,
114
+ snapshotGroupReference: input.campaignPlan.cohortSnapshot.snapshotGroupReference,
115
+ recipientReference,
116
+ communicationReference: input.communicationReference,
117
+ evaluatedAt: input.evaluatedAt,
118
+ eligibilityCurrent: input.eligibilityCurrent,
119
+ exclusionCurrent: input.exclusionCurrent,
120
+ consentReference: input.consentReference,
121
+ channelAuthorizationReference: input.channelAuthorizationReference,
122
+ outcome: input.outcome,
123
+ });
124
+ }
125
+ function uniqueReferences(values, error) {
126
+ const references = [...new Set(values.map(value => reference(value, undefined, error)))];
127
+ if (!references.length)
128
+ throw new TypeError(error);
129
+ return Object.freeze(references);
130
+ }
131
+ function reference(value, expectedType, error) {
132
+ if (typeof value !== 'string')
133
+ throw new TypeError(error);
134
+ const normalized = value.trim();
135
+ const match = /^([A-Z][A-Za-z0-9]+)\/([A-Za-z0-9.-]{1,128})$/.exec(normalized);
136
+ if (!match || (expectedType && match[1] !== expectedType))
137
+ throw new TypeError(error);
138
+ return normalized;
139
+ }
package/dist/index.d.ts CHANGED
@@ -3,5 +3,6 @@ export { EmergencyCapabilities, EvidenceDomains, EvidenceRelationships, Soschain
3
3
  export type { EvidenceRelationship, SoschainEvidenceRelationship, } from 'sos-data-utils-ts/emergency-evidence';
4
4
  export * from './emergency-group.js';
5
5
  export * from './emergency-authorization.js';
6
+ export * from './care-emergency-alert-orchestration.js';
6
7
  export * from './place-card-association.js';
7
8
  export * from './secure-message-crypto.js';
package/dist/index.js CHANGED
@@ -2,5 +2,6 @@
2
2
  export { EmergencyCapabilities, EvidenceDomains, EvidenceRelationships, SoschainEmergencyCapabilities, SoschainEvidenceDomains, SoschainEvidenceRelationships, } from 'sos-data-utils-ts/emergency-evidence';
3
3
  export * from './emergency-group.js';
4
4
  export * from './emergency-authorization.js';
5
+ export * from './care-emergency-alert-orchestration.js';
5
6
  export * from './place-card-association.js';
6
7
  export * from './secure-message-crypto.js';
@@ -0,0 +1,74 @@
1
+ # Care, Emergency and Alert Orchestration
2
+
3
+ This package owns runtime-neutral authorization and orchestration shared by
4
+ VetChain, UHC and SOSChain. FHIR flat-claim builders belong to
5
+ `fhir-data-utils-ts`; deterministic records belong to `sos-data-utils-ts`;
6
+ transport and persistence belong to BFF/channel and Node services; animal and
7
+ human policy stays in Vet and UHC.
8
+
9
+ ## 1. Care continuity and protected contact
10
+
11
+ 1. Appointment `fulfilled` -> Encounter is an idempotent transition.
12
+ 2. The Encounter preserves the selected subject, Appointment, service-provider
13
+ Organization, start time and current Location.
14
+ 3. Admission, diagnostics, intensive care, ward and discharge are represented
15
+ by Encounter/location continuity. Controllers see only what current Consent
16
+ and actor/subject authorization permit.
17
+ 4. An authorized practitioner may start voice/video contact or send an
18
+ encrypted message to the controller or permitted related recipients before
19
+ publishing stressful results.
20
+ 5. Voice/video signaling carries no clinical Bundle. A preliminary clinical
21
+ Bundle may be delivered by encrypted message only with `updateIndex=false`.
22
+ A call or preliminary message must not publish, attest or update the subject
23
+ index. Final clinical publication is a separate workflow.
24
+ 6. A missed call may create an encrypted text/audio message in the same thread;
25
+ its recipients and thread authorization are revalidated by the service.
26
+
27
+ The orchestrator returns a plan. The persistence owner must enforce the
28
+ idempotency key and must not treat a returned plan as authorization evidence.
29
+
30
+ ## 2. Resilient emergency assistance
31
+
32
+ When normal telephone service is unavailable, an authenticated controller or
33
+ authorized requester submits an emergency request to a HealthcareService or
34
+ its owning Organization. The BFF resolves the official target and creates two
35
+ independent resources:
36
+
37
+ - a compact-coded ServiceRequest containing the care request, requester,
38
+ subject and performer target;
39
+ - a Task containing durable intake/triage ownership and linking back through
40
+ `Task.focus`.
41
+
42
+ The emergency console can claim and update the Task, then open an authorized
43
+ voice/video callback or encrypted thread. Raw phone/email destinations,
44
+ WebRTC SDP/ICE/TURN state and encryption keys never enter either FHIR resource.
45
+ The request grants no read access by itself; subject access still requires the
46
+ current emergency or ordinary authorization contract.
47
+
48
+ ## 3. Governed alerts
49
+
50
+ The common flow supports both `blood-donation` and `public-risk` campaigns.
51
+ The server evaluates a governed definitional Group, freezes an enumerated Group
52
+ snapshot and binds a CommunicationRequest to that snapshot. Subscription wakes
53
+ evaluation; it is not Consent, cohort-query authority or send authority.
54
+
55
+ Blood-donation campaigns require compact `system|code` blood-group filters and
56
+ the minimum elapsed days since the last donation. Public-risk campaigns require
57
+ server-authorized FHIR `resourceType`, `searchParameter` and `value` criteria;
58
+ clients cannot submit executable queries.
59
+
60
+ Immediately before each delivery, the service must verify snapshot membership,
61
+ current eligibility, current exclusions, Consent and channel authorization.
62
+ Only then may it create/send the Communication and record the audit. Group and
63
+ CommunicationRequest resources never replace those per-recipient checks.
64
+
65
+ ## Release proof
66
+
67
+ Merge validated shared dependency sources to `main`, create immutable
68
+ unpublished tarballs from those commits, and install them temporarily with
69
+ `--no-save`. Prove the affected real local Vet channel (portal, phone service,
70
+ chatbot or another supported channel) -> BFF/channel service -> high-level SDK
71
+ -> GW VET journey without skips. Merge the validated consumer source to
72
+ `main`, publish exact packages bottom-up, pin registry versions, repeat affected
73
+ local gates, and only then promote to staging. Never commit local tarballs or
74
+ local dependency references.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sos-sdk-core-ts",
3
- "version": "0.2.2",
3
+ "version": "0.3.0",
4
4
  "description": "Runtime-neutral shared orchestration for SOS, Vet and UHC products",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Connecting Solution & Applications Ltd",
@@ -20,6 +20,10 @@
20
20
  "types": "./dist/emergency-group.d.ts",
21
21
  "default": "./dist/emergency-group.js"
22
22
  },
23
+ "./care-emergency-alert-orchestration": {
24
+ "types": "./dist/care-emergency-alert-orchestration.d.ts",
25
+ "default": "./dist/care-emergency-alert-orchestration.js"
26
+ },
23
27
  "./emergency-authorization": {
24
28
  "types": "./dist/emergency-authorization.d.ts",
25
29
  "default": "./dist/emergency-authorization.js"
@@ -51,7 +55,8 @@
51
55
  "@noble/ciphers": "2.4.0",
52
56
  "@noble/hashes": "2.4.0",
53
57
  "@noble/post-quantum": "0.7.1",
54
- "sos-data-utils-ts": "0.3.9"
58
+ "fhir-data-utils-ts": "0.3.7",
59
+ "sos-data-utils-ts": "0.4.1"
55
60
  },
56
61
  "devDependencies": {
57
62
  "@types/node": "^22.5.0",