From 6cc29edf9407944480a1317fc38844485b375994 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:36:00 -0500 Subject: [PATCH 1/6] Vendor the core-05 Appendix C schema and Appendix B examples Replaces the 0.4.0 schema fixture used by the conformance test with the core-05 Appendix C JSON Schema, and adds the nine Appendix B examples. Co-Authored-By: Claude Opus 5.5 --- .../fixtures/appendix-c-json-schema.json | 1577 +++++++++++++++++ .../B1-two-party-call-inline-recording.json | 71 + .../examples/B2-email-thread-multipart.json | 58 + .../examples/B3-email-thread-text.json | 71 + .../B4-two-party-call-external-recording.json | 45 + .../B5-two-party-call-with-analysis.json | 1075 +++++++++++ .../fixtures/examples/B6-signed.json | 17 + .../fixtures/examples/B7-encrypted.json | 15 + .../fixtures/examples/B8-redacted.json | 165 ++ .../fixtures/examples/B9-amended-signed.json | 59 + src/__tests__/fixtures/vcon_json_schema.json | 529 ------ 11 files changed, 3153 insertions(+), 529 deletions(-) create mode 100644 src/__tests__/fixtures/appendix-c-json-schema.json create mode 100644 src/__tests__/fixtures/examples/B1-two-party-call-inline-recording.json create mode 100644 src/__tests__/fixtures/examples/B2-email-thread-multipart.json create mode 100644 src/__tests__/fixtures/examples/B3-email-thread-text.json create mode 100644 src/__tests__/fixtures/examples/B4-two-party-call-external-recording.json create mode 100644 src/__tests__/fixtures/examples/B5-two-party-call-with-analysis.json create mode 100644 src/__tests__/fixtures/examples/B6-signed.json create mode 100644 src/__tests__/fixtures/examples/B7-encrypted.json create mode 100644 src/__tests__/fixtures/examples/B8-redacted.json create mode 100644 src/__tests__/fixtures/examples/B9-amended-signed.json delete mode 100644 src/__tests__/fixtures/vcon_json_schema.json diff --git a/src/__tests__/fixtures/appendix-c-json-schema.json b/src/__tests__/fixtures/appendix-c-json-schema.json new file mode 100644 index 0000000..e3b5c90 --- /dev/null +++ b/src/__tests__/fixtures/appendix-c-json-schema.json @@ -0,0 +1,1577 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://ietf.org/vcon/schemas/unsigned-vcon.json", + "title": "vCon - Unsigned Form", + "description": "JSON schema for the unsigned form of vCon (Conversational Data Container) as defined in RFCXXXX", + "type": "object", + "required": [ + "uuid", + "created_at" + ], + "properties": { + "vcon": { + "type": "string", + "description": "DEPRECATED: Syntactic version of the JSON format. This was used to indicate schema changes in the Internet-Draft versions", + "const": "0.5.0" + }, + "uuid": { + "type": "string", + "description": "Globally unique identifier for the vCon. SHOULD be a version 8 UUID", + "format": "uuid" + }, + "extensions": { + "type": "array", + "description": "List of names of all vCon extensions used by this vCon", + "items": { + "type": "string" + } + }, + "critical": { + "type": "array", + "description": "List of extension names that a consumer MUST support to safely process this vCon", + "items": { + "type": "string" + } + }, + "created_at": { + "type": "string", + "description": "Creation time of this vCon in RFC3339 format", + "format": "date-time" + }, + "updated_at": { + "type": "string", + "description": "Last modified time of this vCon in RFC3339 format", + "format": "date-time" + }, + "subject": { + "type": "string", + "description": "Subject or topic of the conversation" + }, + "redacted_from": { + "type": "object", + "description": "Reference to the unredacted or less redacted vCon prior instance (Redacted_from Object); mutually exclusive with amended_from", + "required": [ + "type" + ], + "properties": { + "uuid": { + "type": "string", + "description": "UUID of the unredacted or less redacted vCon prior instance", + "format": "uuid" + }, + "type": { + "type": "string", + "description": "Type of redaction performed; same set of values as the type parameter of the Redacted_string Object" + }, + "url": { + "type": "string", + "description": "HTTPS URL where the referenced vCon is stored", + "format": "uri" + }, + "content_hash": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ], + "description": "Hash(es) of the external content using format: algorithm-base64url_encoded_hash" + } + }, + "dependencies": { + "url": [ + "content_hash" + ] + } + }, + "amended_from": { + "type": "object", + "description": "Reference to the prior vCon instance version that this vCon amends (Amended_from Object); mutually exclusive with redacted_from", + "properties": { + "uuid": { + "type": "string", + "description": "UUID of the prior vCon instance version", + "format": "uuid" + }, + "url": { + "type": "string", + "description": "HTTPS URL where the referenced vCon is stored", + "format": "uri" + }, + "content_hash": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ], + "description": "Hash(es) of the external content (required if url is provided)" + } + }, + "dependencies": { + "url": [ + "content_hash" + ] + }, + "if": { + "not": { + "required": [ + "url" + ] + } + }, + "then": { + "required": [ + "uuid" + ], + "$comment": "uuid is optional only if an external reference is provided" + } + }, + "redacted_strings": { + "type": "array", + "description": "Array of Redacted_string Objects, one for each unique substring replaced by __REDACTED_REF_# in the vCon", + "items": { + "$ref": "#/definitions/RedactedString" + } + }, + "sessions": { + "type": "array", + "description": "Array of Session Objects, each grouping the Dialog and Event Objects of one session of the conversation", + "items": { + "$ref": "#/definitions/Session" + } + }, + "parties": { + "type": "array", + "description": "Array of Party Objects representing all parties involved in the conversation", + "items": { + "$ref": "#/definitions/Party" + } + }, + "events": { + "type": "array", + "description": "Array of Event Objects; order is not significant, Event Objects are sequenced by their time parameter", + "items": { + "$ref": "#/definitions/Event" + } + }, + "dialog": { + "type": "array", + "description": "Array of Dialog Objects containing the captured conversation content", + "items": { + "$ref": "#/definitions/Dialog" + } + }, + "analysis": { + "type": "array", + "description": "Array of Analysis Objects containing analysis performed on the conversational data", + "items": { + "$ref": "#/definitions/Analysis" + } + }, + "attachments": { + "type": "array", + "description": "Array of Attachment Objects for ancillary documents related to the conversation", + "items": { + "$ref": "#/definitions/Attachment" + } + } + }, + "definitions": { + "Session": { + "type": "object", + "description": "Represents one session of the conversation and references the Dialog Objects which are part of it; a Session Object with no parameters is permitted", + "properties": { + "start": { + "type": "string", + "format": "date-time", + "description": "Start time of the session in RFC3339 format; SHOULD be present" + }, + "duration": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "number", + "minimum": 0 + } + ], + "description": "Duration of the session in seconds" + }, + "parties": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "description": "Indices of the parties that are the receivers of the dialog in the session; SHOULD be present; the first party is the implied originator" + }, + "originator": { + "type": "integer", + "minimum": 0, + "description": "Index of the originating party; only provided if the first party in parties is not the originator" + }, + "session_id": { + "$ref": "#/definitions/SessionId" + }, + "sessions": { + "type": "array", + "items": { + "$ref": "#/definitions/SessionReference" + }, + "description": "Relationships to other Session Objects" + }, + "dialog": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "description": "Indices of the Dialog Objects which are part of the session" + } + } + }, + "SessionReference": { + "type": "object", + "description": "Session_Reference Object: the relationship of another Session Object to the Session Object which contains this reference", + "required": [ + "session", + "type" + ], + "properties": { + "session": { + "type": "integer", + "minimum": 0, + "description": "Index of the referenced Session Object in the sessions array" + }, + "type": { + "type": "string", + "description": "Type of relationship: child, peer, precursor, breakout, or a value defined in a vCon extension" + }, + "description": { + "type": "string", + "description": "Free form text description of the relationship" + } + } + }, + "Party": { + "type": "object", + "description": "Represents a party involved in the conversation", + "properties": { + "tel": { + "type": "string", + "description": "TEL URL (RFC3966) for the party" + }, + "sip": { + "type": "string", + "description": "SIP URL for the party" + }, + "stir": { + "type": "string", + "description": "STIR PASSporT in JWS Compact Serialization form" + }, + "mailto": { + "type": "string", + "description": "Email address for the party in any common form, including a bare address or a MAILTO URL" + }, + "name": { + "type": "string", + "description": "Name of the party" + }, + "did": { + "type": "string", + "description": "Decentralized Identifier (DID) URI for the party" + }, + "validation": { + "type": "string", + "description": "Label or token identifying the method of identity validation used" + }, + "gmlpos": { + "type": "string", + "description": "Geographic location in GML pos format (latitude longitude)" + }, + "civicaddress": { + "$ref": "#/definitions/Civicaddress" + }, + "uuid": { + "type": "string", + "description": "Free form unique identifier for the participant; not constrained to UUID syntax" + }, + "type": { + "type": "string", + "description": "Participant type" + }, + "org": { + "type": "string", + "description": "Organization to which the party belongs" + }, + "dept": { + "type": "string", + "description": "Department to which the party belongs" + } + } + }, + "Civicaddress": { + "type": "object", + "description": "Civic address information for a party's location", + "properties": { + "country": { + "type": "string" + }, + "a1": { + "type": "string", + "description": "National subdivision (state/province)" + }, + "a2": { + "type": "string", + "description": "County/parish/district" + }, + "a3": { + "type": "string", + "description": "City/township" + }, + "a4": { + "type": "string", + "description": "City division/borough" + }, + "a5": { + "type": "string", + "description": "Neighborhood/block" + }, + "a6": { + "type": "string", + "description": "Street" + }, + "prd": { + "type": "string", + "description": "Leading street direction" + }, + "pod": { + "type": "string", + "description": "Trailing street suffix" + }, + "sts": { + "type": "string", + "description": "Street suffix" + }, + "hno": { + "type": "string", + "description": "House number" + }, + "hns": { + "type": "string", + "description": "House number suffix" + }, + "lmk": { + "type": "string", + "description": "Landmark" + }, + "loc": { + "type": "string", + "description": "Additional location info" + }, + "flr": { + "type": "string", + "description": "Floor" + }, + "nam": { + "type": "string", + "description": "Name/occupant" + }, + "pc": { + "type": "string", + "description": "Postal code" + } + } + }, + "Event": { + "type": "object", + "description": "Represents an event which occurred in a session, such as a party joining, a key press or a transfer", + "required": [ + "type", + "time" + ], + "properties": { + "type": { + "type": "string", + "description": "Type of event: join, drop, hold, unhold, mute, unmute, keydown, keyup, consultation-start, blind-transfer, consultative-transfer, transfer-abandoned, channel-contributors, or a value defined in a vCon extension" + }, + "time": { + "type": "string", + "format": "date-time", + "description": "Time of the event in RFC3339 format" + }, + "sessions": { + "oneOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + ], + "description": "Index or indices of the Session Objects in which the event occurred; the event applies only to the listed Session Objects; for transfer event types, a single index to the Session Object for the original call; MUST NOT be present for channel-contributors" + }, + "party": { + "type": "integer", + "minimum": 0, + "description": "Index of the party to which the event applies; for transfer event types, the Transferor; MUST NOT be present for channel-contributors" + }, + "dialog": { + "type": "integer", + "minimum": 0, + "description": "Index of the Dialog Object to which the event relates; required for channel-contributors, where it references a recording Dialog Object; SHOULD NOT be present for the other event types defined in RFCXXXX; an event type defined in a vCon extension may allow an array of indices" + }, + "channel": { + "type": "integer", + "minimum": 0, + "description": "Index of the channel of the recording, where 0 is the first channel (channel-contributors only)" + }, + "contributors": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + }, + { + "type": "null" + } + ], + "description": "Index or indices of the parties contributing to the channel starting at the time of the event; null or absent means no party contributes (channel-contributors only)" + }, + "button": { + "type": "string", + "description": "DTMF digit, character or string (required for keydown and keyup events)" + }, + "transferee": { + "type": "integer", + "minimum": 0, + "description": "Party index of the Transferee (transfer event types)" + }, + "transfer_target": { + "type": "integer", + "minimum": 0, + "description": "Party index of the Transfer Target (transfer event types; optional for transfer-abandoned)" + }, + "consultation": { + "type": "integer", + "minimum": 0, + "description": "Session index of the consultative call (consultation-start and consultative-transfer; optional for transfer-abandoned)" + }, + "target_session": { + "type": "integer", + "minimum": 0, + "description": "Session index of the target call (blind-transfer and consultative-transfer)" + } + }, + "allOf": [ + { + "if": { + "properties": { + "type": { + "enum": [ + "join", + "drop", + "hold", + "unhold", + "mute", + "unmute", + "keydown", + "keyup", + "consultation-start", + "blind-transfer", + "consultative-transfer", + "transfer-abandoned" + ] + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "sessions", + "party" + ], + "not": { + "anyOf": [ + { + "required": [ + "channel" + ] + }, + { + "required": [ + "contributors" + ] + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "enum": [ + "consultation-start", + "blind-transfer", + "consultative-transfer", + "transfer-abandoned" + ] + } + }, + "required": [ + "type" + ] + }, + "then": { + "properties": { + "sessions": { + "type": "integer", + "minimum": 0 + } + } + } + }, + { + "if": { + "properties": { + "type": { + "enum": [ + "join", + "drop", + "hold", + "unhold", + "mute", + "unmute" + ] + } + }, + "required": [ + "type" + ] + }, + "then": { + "not": { + "anyOf": [ + { + "required": [ + "button" + ] + }, + { + "required": [ + "transferee" + ] + }, + { + "required": [ + "transfer_target" + ] + }, + { + "required": [ + "consultation" + ] + }, + { + "required": [ + "target_session" + ] + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "enum": [ + "keydown", + "keyup" + ] + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "button" + ], + "not": { + "anyOf": [ + { + "required": [ + "transferee" + ] + }, + { + "required": [ + "transfer_target" + ] + }, + { + "required": [ + "consultation" + ] + }, + { + "required": [ + "target_session" + ] + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "consultation-start" + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "transferee", + "transfer_target", + "consultation" + ], + "not": { + "anyOf": [ + { + "required": [ + "button" + ] + }, + { + "required": [ + "target_session" + ] + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "blind-transfer" + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "transferee", + "transfer_target", + "target_session" + ], + "not": { + "anyOf": [ + { + "required": [ + "button" + ] + }, + { + "required": [ + "consultation" + ] + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "consultative-transfer" + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "transferee", + "transfer_target", + "consultation", + "target_session" + ], + "not": { + "anyOf": [ + { + "required": [ + "button" + ] + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "transfer-abandoned" + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "transferee" + ], + "not": { + "anyOf": [ + { + "required": [ + "button" + ] + }, + { + "required": [ + "target_session" + ] + } + ] + } + } + }, + { + "if": { + "properties": { + "type": { + "const": "channel-contributors" + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "dialog", + "channel" + ], + "not": { + "anyOf": [ + { + "required": [ + "sessions" + ] + }, + { + "required": [ + "party" + ] + }, + { + "required": [ + "button" + ] + }, + { + "required": [ + "transferee" + ] + }, + { + "required": [ + "transfer_target" + ] + }, + { + "required": [ + "consultation" + ] + }, + { + "required": [ + "target_session" + ] + } + ] + } + } + } + ], + "$comment": "The rules for each known type follow the Event Object Parameter Applicability by Type tables. SHOULD NOT statements, such as dialog in the event types other than channel-contributors, are not enforced. An Event Object with a type which is not listed is only checked for the parameters common to all types." + }, + "Dialog": { + "type": "object", + "description": "Represents a segment of captured conversation; an empty Dialog Object holds a position in the dialog array", + "anyOf": [ + { + "required": [ + "type" + ] + }, + { + "maxProperties": 0, + "$comment": "An empty Dialog Object has no type and no meaning" + } + ], + "properties": { + "type": { + "type": "string", + "description": "Type of dialog: recording, text, incomplete, or a value defined in a vCon extension" + }, + "start": { + "type": "string", + "format": "date-time", + "description": "Start time of the dialog in RFC3339 format; SHOULD be present unless not known" + }, + "duration": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "number", + "minimum": 0 + } + ], + "description": "Duration in seconds" + }, + "parties": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + }, + { + "type": "array", + "items": { + "anyOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + }, + { + "type": "null" + } + ] + } + } + ], + "description": "Index/indices of the parties that contributed to the dialog content; SHOULD be present for recording and text types" + }, + "mediatype": { + "type": "string", + "description": "Media type of the dialog content; MUST be present for inline content; not required when Dialog Content is absent" + }, + "filename": { + "type": "string", + "description": "Original filename of the dialog content" + }, + "body": { + "description": "Inline content of the dialog (for inline files). Any type for encoding json; a string for encoding base64url or none." + }, + "encoding": { + "type": "string", + "description": "Encoding type for inline content: base64url, json, none, or a value defined in a vCon extension" + }, + "url": { + "type": "string", + "format": "uri", + "description": "HTTPS URL for externally referenced content" + }, + "content_hash": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ], + "description": "Hash(es) of external content" + }, + "disposition": { + "type": "string", + "description": "Reason the call or conversation failed (required for incomplete type, SHOULD NOT be present for other types): no-answer, congestion, failed, busy, hung-up, voicemail-no-message, or a value defined in a vCon extension; \"failed\" SHOULD be used when the reason is not known" + }, + "session_id": { + "anyOf": [ + { + "$ref": "#/definitions/SessionId" + }, + { + "type": "array", + "items": { + "$ref": "#/definitions/SessionId" + } + }, + { + "type": "array", + "items": { + "oneOf": [ + { + "$ref": "#/definitions/SessionId" + }, + { + "type": "array", + "items": { + "$ref": "#/definitions/SessionId" + } + } + ] + } + } + ], + "description": "Session ID(s) for the dialog, correlated with the parties parameter" + }, + "application": { + "type": "string", + "description": "Application, communication channel or context of the conversation" + }, + "message_id": { + "type": "string", + "description": "Unique message identifier from the messaging system" + }, + "redacted_segments": { + "type": "array", + "description": "Redacted_segments Objects for the audiovisual segments which were redacted; SHOULD NOT be present for text; MUST NOT be present for incomplete", + "items": { + "$ref": "#/definitions/RedactedSegments" + } + } + }, + "dependencies": { + "url": [ + "content_hash" + ] + }, + "allOf": [ + { + "if": { + "properties": { + "type": { + "const": "incomplete" + } + }, + "required": [ + "type" + ] + }, + "then": { + "required": [ + "disposition" + ], + "not": { + "anyOf": [ + { + "required": [ + "mediatype" + ] + }, + { + "required": [ + "filename" + ] + }, + { + "required": [ + "body" + ] + }, + { + "required": [ + "encoding" + ] + }, + { + "required": [ + "url" + ] + }, + { + "required": [ + "content_hash" + ] + }, + { + "required": [ + "message_id" + ] + }, + { + "required": [ + "redacted_segments" + ] + } + ] + } + } + }, + { + "if": { + "required": [ + "body" + ], + "properties": { + "body": { + "not": { + "const": "" + } + } + } + }, + "then": { + "required": [ + "encoding" + ] + } + }, + { + "if": { + "required": [ + "body" + ], + "properties": { + "body": { + "not": { + "const": "" + } + } + } + }, + "then": { + "required": [ + "mediatype" + ] + } + }, + { + "if": { + "properties": { + "encoding": { + "enum": [ + "base64url", + "none" + ] + } + }, + "required": [ + "encoding" + ] + }, + "then": { + "properties": { + "body": { + "type": "string" + } + } + } + } + ], + "$comment": "The rules for each known type follow the Dialog Object Parameter Applicability by Type table. A Dialog Object with a type which is not listed is only checked for the rules common to all types." + }, + "SessionId": { + "type": "object", + "description": "Session identifier with local and remote UUIDs", + "properties": { + "local": { + "type": "string", + "description": "Local UUID for the session" + }, + "remote": { + "type": "string", + "description": "Remote UUID for the session" + } + } + }, + "Attachment": { + "type": "object", + "description": "Represents an ancillary document related to the conversation", + "required": [ + "start", + "party" + ], + "properties": { + "purpose": { + "type": "string", + "description": "text description of what the attachment is for" + }, + "start": { + "type": "string", + "format": "date-time", + "description": "Time the attachment was sent/exchanged in RFC3339 format" + }, + "party": { + "type": "integer", + "minimum": 0, + "description": "Index of the party that contributed the attachment" + }, + "dialog": { + "type": "integer", + "minimum": 0, + "description": "Index of the dialog this attachment is part of (optional; at least one of dialog or session MUST be present)" + }, + "session": { + "oneOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + ], + "description": "Index/indices of the Session Object(s) this attachment is related to" + }, + "mediatype": { + "type": "string", + "description": "Media type of the attachment content; MUST be present for inline content; not required when Attachment Content is absent" + }, + "filename": { + "type": "string", + "description": "Original filename of the attachment" + }, + "body": { + "description": "Inline content of the attachment (for inline files). Any type for encoding json; a string for encoding base64url or none." + }, + "encoding": { + "type": "string", + "description": "Encoding type for inline content: base64url, json, none, or a value defined in a vCon extension" + }, + "url": { + "type": "string", + "format": "uri", + "description": "HTTPS URL for externally referenced attachment" + }, + "content_hash": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ], + "description": "Hash(es) of external content" + } + }, + "dependencies": { + "url": [ + "content_hash" + ] + }, + "anyOf": [ + { + "required": [ + "dialog" + ] + }, + { + "required": [ + "session" + ] + } + ], + "allOf": [ + { + "if": { + "required": [ + "body" + ], + "properties": { + "body": { + "not": { + "const": "" + } + } + } + }, + "then": { + "required": [ + "encoding" + ] + } + }, + { + "if": { + "required": [ + "body" + ], + "properties": { + "body": { + "not": { + "const": "" + } + } + } + }, + "then": { + "required": [ + "mediatype" + ] + } + }, + { + "if": { + "properties": { + "encoding": { + "enum": [ + "base64url", + "none" + ] + } + }, + "required": [ + "encoding" + ] + }, + "then": { + "properties": { + "body": { + "type": "string" + } + } + } + } + ] + }, + "Analysis": { + "type": "object", + "description": "Represents analysis performed on the conversational data", + "required": [ + "type", + "vendor" + ], + "properties": { + "type": { + "type": "string", + "description": "Semantic type of analysis (e.g., report, sentiment, summary, transcript, translation, tts)" + }, + "dialog": { + "oneOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + ], + "description": "Index/indices of dialog objects this analysis is based on (optional)" + }, + "sessions": { + "oneOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + ], + "description": "Index/indices of Session Objects this analysis is based on (optional)" + }, + "attachment": { + "oneOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + ], + "description": "Index/indices of attachment objects this analysis is based on (optional)" + }, + "analysis": { + "oneOf": [ + { + "type": "integer", + "minimum": 0 + }, + { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + } + } + ], + "description": "Index/indices of other Analysis Objects this analysis is based on (optional); MUST NOT reference itself" + }, + "mediatype": { + "type": "string", + "description": "Media type of the analysis content; SHOULD be provided for inline content and for external content without an HTTPS Content-Type header; when no media type is defined for the data format, the vendor, product and schema parameters SHOULD identify the format instead" + }, + "filename": { + "type": "string", + "description": "Original filename of the analysis data" + }, + "vendor": { + "type": "string", + "description": "Vendor or product name that generated the analysis" + }, + "product": { + "type": "string", + "description": "Product name to differentiate from other vendor products" + }, + "schema": { + "type": "string", + "description": "Token or label for the data format/schema of the analysis" + }, + "body": { + "description": "Inline content of the analysis (for inline files). Any type for encoding json; a string for encoding base64url or none." + }, + "encoding": { + "type": "string", + "description": "Encoding type for inline content: base64url, json, none, or a value defined in a vCon extension" + }, + "url": { + "type": "string", + "format": "uri", + "description": "HTTPS URL for externally referenced analysis" + }, + "content_hash": { + "oneOf": [ + { + "type": "string" + }, + { + "type": "array", + "items": { + "type": "string" + } + } + ], + "description": "Hash(es) of external content" + } + }, + "dependencies": { + "url": [ + "content_hash" + ] + }, + "allOf": [ + { + "if": { + "required": [ + "body" + ], + "properties": { + "body": { + "not": { + "const": "" + } + } + } + }, + "then": { + "required": [ + "encoding" + ] + } + }, + { + "if": { + "properties": { + "encoding": { + "enum": [ + "base64url", + "none" + ] + } + }, + "required": [ + "encoding" + ] + }, + "then": { + "properties": { + "body": { + "type": "string" + } + } + } + } + ], + "$comment": "At least one of the dialog, sessions, attachment or analysis parameters SHOULD be present. An Analysis Object MUST NOT reference itself in the analysis parameter; this is not enforced by this schema." + }, + "RedactedString": { + "type": "object", + "description": "Information about a substring of the vCon which was replaced by __REDACTED_REF_#", + "required": [ + "ref" + ], + "properties": { + "ref": { + "type": "integer", + "minimum": 1, + "maximum": 99999, + "description": "Reference number of the redacted substring" + }, + "type": { + "type": "string", + "description": "Type of information redacted: GOVT_ID_NUM, FIN_ID_NUM, MED_ID_NUM, BIOMETRIC, AUTH_DATA, CONTACT_INFO, LOC_INFO, EMPL_INFO, BELIEF_INFO, UNSPECIFIED or another value; absent means UNSPECIFIED" + }, + "orig": { + "type": "string", + "description": "Original, unredacted value of the substring" + } + }, + "$comment": "That each __REDACTED_REF_# substring has a Redacted_string Object with a matching ref is not enforced by this schema." + }, + "RedactedSegments": { + "type": "object", + "description": "An audiovisual segment of a recording which was redacted", + "required": [ + "start", + "end" + ], + "properties": { + "start": { + "type": "string", + "format": "date-time", + "description": "Start time of the redaction in RFC3339 format" + }, + "end": { + "type": "string", + "format": "date-time", + "description": "End time of the redaction in RFC3339 format" + }, + "parties": { + "type": "array", + "items": { + "type": "integer", + "minimum": 0 + }, + "description": "Indices of the parties whose content was redacted" + } + }, + "$comment": "TODO: should use duration instead of end?" + } + }, + "not": { + "required": [ + "redacted_from", + "amended_from" + ], + "$comment": "The redacted_from and amended_from parameters are mutually exclusive" + }, + "allOf": [ + { + "if": { + "anyOf": [ + { + "required": [ + "dialog" + ], + "properties": { + "dialog": { + "minItems": 1 + } + } + }, + { + "required": [ + "events" + ], + "properties": { + "events": { + "minItems": 1 + } + } + } + ] + }, + "then": { + "required": [ + "sessions" + ], + "properties": { + "sessions": { + "minItems": 1 + } + }, + "$comment": "At least one Session Object MUST exist if the events array or the dialog array contain Objects" + } + } + ], + "$comment": "This schema is permissive: parameters and type values which are not defined in RFCXXXX do not cause validation to fail. At least one of the parties, dialog, analysis or attachments parameters SHOULD be present. SHOULD-level statements are not enforced by this schema. Index values are not checked against the size of the array which they reference." +} + diff --git a/src/__tests__/fixtures/examples/B1-two-party-call-inline-recording.json b/src/__tests__/fixtures/examples/B1-two-party-call-inline-recording.json new file mode 100644 index 0000000..834871c --- /dev/null +++ b/src/__tests__/fixtures/examples/B1-two-party-call-inline-recording.json @@ -0,0 +1,71 @@ +{ + "vcon": "0.5.0", + "created_at": "2022-06-21T13:53:00-04:00", + "parties": [ + { + "tel": "+12345678901", + "name": "Alice" + }, + { + "tel": "+19876543210", + "name": "Bob" + } + ], + "dialog": [ + { + "type": "recording", + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 4.72, + "parties": [ + 0, + 1 + ], + "mediatype": "audio/x-wav", + "filename": "ab_call.wav", + "encoding": "base64url", + "body": "UklGRioeAABXQVZFZm10IBQAAAAxAAEAQB8AAFkGAABBAAAAAgBAAWZhY3QEAAAAgJMAAGRhdGH2HQAAoxjXHYXCRekuye4gK4Tsiv4wZeNhtuvu3RMkgyPXme4NeahQLG0yeLayx5HCIiRWK7psbQrQTFm57NwQJvIbq1aNxk6VpMYAXSm5Bb1rgStIStvEzmCaOIabxs2gjReJ02Rk0BQtOxHkhUTIZd4VGKoq1KuoCGhrZTx1vRZICuZEcgkGjdH2jiCU1a0NMW6BE8lVHN-OYFPHcZspr0CSl1aeo2hOWUx3CbovpGqKsApWteunk8gMPMOdynRVFWR5o0l2BvaQDcWugGRHrQa9NcEbG1LWQq_AWLpsXKdMQefGrZu4ZE2ZSDIRGJLTKpIzDybqSyZishQmjuVGztMKNlcyt2vW546JsutgllyppQWroAtHbkyrrGAx3bIiX81g1sR-oVaBbtkobA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ciPHaL0Eyo0bWcX0DiZu29hwFntXxIIy4KuVckrtDCD4tGYSHctAFDmNzVbPQCvDauJGqTgafrcINDGcNGnZR7Zt3PoALxSCUqY0wbyrSHmTIZc" + } + ], + "analysis": [], + "attachments": [], + "sessions": [ + { + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 4.72, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0 + ] + } + ], + "uuid": "01a16b86-9a63-8346-b9a2-279e0d16bc46", + "events": [ + { + "type": "join", + "time": "2022-06-21T17:53:26.000+00:00", + "sessions": 0, + "party": 0 + }, + { + "type": "join", + "time": "2022-06-21T17:53:26.000+00:00", + "sessions": 0, + "party": 1 + }, + { + "type": "drop", + "time": "2022-06-21T17:53:30.720+00:00", + "sessions": 0, + "party": 0 + }, + { + "type": "drop", + "time": "2022-06-21T17:53:30.720+00:00", + "sessions": 0, + "party": 1 + } + ] +} diff --git a/src/__tests__/fixtures/examples/B2-email-thread-multipart.json b/src/__tests__/fixtures/examples/B2-email-thread-multipart.json new file mode 100644 index 0000000..fc6710d --- /dev/null +++ b/src/__tests__/fixtures/examples/B2-email-thread-multipart.json @@ -0,0 +1,58 @@ +{ + "vcon": "0.5.0", + "parties": [ + { + "mailto": "b@example.com", + "name": "Bob" + }, + { + "mailto": "a@example.com", + "name": "Alice" + } + ], + "dialog": [ + { + "type": "text", + "start": "2022-09-23T21:44:25.000+00:00", + "duration": 0, + "parties": [ + 0 + ], + "mediatype": "multipart/mixed; boundary=\"----=_Part_388314_1108189513.1663969465698\"", + "encoding": "none", + "body": "------=_Part_388314_1108189513.1663969465698\r\nContent-Type: multipart/alternative;\r\n\tboundary=\"----=_Part_388313_805631480.1663969465697\"\r\n\r\n------=_Part_388313_805631480.1663969465697\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\nAlice:Please find the image attached.\r\n\r\nRegards,Bob\r\n\r\n------=_Part_388313_805631480.1663969465697\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\n
Alice:
Please find the image attached.

Regards,
Bob

\r\n------=_Part_388313_805631480.1663969465697--\r\n\r\n------=_Part_388314_1108189513.1663969465698\r\nContent-Type: image/png\r\nContent-Transfer-Encoding: base64\r\nContent-Disposition: attachment; filename=\"=?UTF-8?b?c2NyZWVuc2hvdC5wbmc=?=\"\r\nContent-ID: \r\n\r\niVBORw0KGgoAAAANSUhEUgAAACYAAAAeCAIAAADPdvs5AAAAA3NCSVQICAjb4U/gAAAAGXRFWHRT\r\nb2Z0d2FyZQBnbm9tZS1zY3JlZW5zaG907wO/PgAAALpJREFUSInl1t0NgzAMBOC7qPvP1gW6Qjdo\r\nj4f0J4qAJI6NROvniE8+mwCvtzv6imTnyf1K/UclHUFWjIvaIL3CHCABSPKKtJckWfY6zw+sj5dq\r\nISdVIzmj2klzTZG2Rme7NKgOwY6qPrMcUs+2PqchL14P+oyz+fHx77K5Sv8xyxAyZ0uBaxn/SpcU\r\n8NxcosAut1Y3NtjVX7UjZlmpgWTSFyvVQPKB16tSqW53bFnKtyyZvYT3rSsAWADWAlOjseYFfwAA\r\nAABJRU5ErkJggg==\r\n\r\n------=_Part_388314_1108189513.1663969465698--\r\n", + "message_id": "<1126698042.388315.1663969465698@mail.yahoo.com>" + }, + { + "type": "text", + "start": "2022-09-23T21:44:59.000+00:00", + "duration": 0, + "parties": [ + 1 + ], + "mediatype": "multipart/alternative; boundary=\"----=_Part_390234_811845464.1663969499935\"", + "encoding": "none", + "body": "------=_Part_390234_811845464.1663969499935\r\nContent-Type: text/plain; charset=UTF-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\n Hi Bob:Got it. Thanks.\r\n\r\n On Friday, September 23, 2022, 9:44:40 PM UTC, Bob wrote: \r\n \r\n Alice:Please find the image attached.\r\n\r\nRegards,Bob\r\n \r\n------=_Part_390234_811845464.1663969499935\r\nContent-Type: text/html; charset=UTF-8\r\nContent-Transfer-Encoding: 7bit\r\n\r\n
\r\n
Hi Bob:
Got it. Thanks.


\r\n \r\n
\r\n
\r\n \r\n
\r\n On Friday, September 23, 2022, 9:44:40 PM UTC, Bob <b@example.com> wrote:\r\n
\r\n

\r\n

\r\n
Alice:
Please find the image attached.

Regards,
Bob

\r\n
\r\n
\r\n------=_Part_390234_811845464.1663969499935--\r\n", + "message_id": "<2031327240.390235.1663969499936@mail.yahoo.com>" + } + ], + "analysis": [], + "attachments": [], + "created_at": "2026-10-24T01:29:10.590+00:00", + "subject": "Account problem", + "sessions": [ + { + "start": "2022-09-23T21:44:25.000+00:00", + "duration": 34, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0, + 1 + ] + } + ], + "uuid": "01a16b86-acc8-8c6d-b9a2-279e0d16bc46" +} diff --git a/src/__tests__/fixtures/examples/B3-email-thread-text.json b/src/__tests__/fixtures/examples/B3-email-thread-text.json new file mode 100644 index 0000000..d30ecab --- /dev/null +++ b/src/__tests__/fixtures/examples/B3-email-thread-text.json @@ -0,0 +1,71 @@ +{ + "vcon": "0.5.0", + "parties": [ + { + "mailto": "a@example.com", + "name": "Alice" + }, + { + "mailto": "b@example.com", + "name": "Bob" + } + ], + "dialog": [ + { + "type": "text", + "start": "2022-09-23T23:24:59.000+00:00", + "duration": 0, + "parties": [ + 0 + ], + "mediatype": "text/plain", + "encoding": "none", + "body": "Hi Bob:\nI just wanted to follow up to see that your account is ok now.\n\nRegards,\nAlice\n\n", + "message_id": "<1402576211.401234.1663975499936@mail.yahoo.com>" + }, + { + "type": "text", + "start": "2022-09-23T23:34:32.000+00:00", + "duration": 0, + "parties": [ + 1 + ], + "mediatype": "text/plain; charset=UTF-8", + "encoding": "none", + "body": "Hi Alice:\nAll is fine. Thanks.\n\n On Friday, September 23, 2022, 23:24:59 PM UTC, Alice wrote: \n \n Hi Bob:\n I just wanted to follow up to see that your account is ok now.\n \n Regards,\n Alice\n", + "message_id": "<1879233410.402112.1663976072118@mail.yahoo.com>" + }, + { + "type": "text", + "start": "2022-09-23T23:38:12.000+00:00", + "duration": 0, + "parties": [ + 0 + ], + "mediatype": "text/plain", + "encoding": "none", + "body": "Awesome!\n\n On Friday, September 23, 2022, 23:34: PM UTC, Bob wrote: \n\n Hi Alice:\n All is fine. Thanks.\n \n On Friday, September 23, 2022, 23:24:59 PM UTC, Alice wrote: \n \n Hi Bob:\n I just wanted to follow up to see that your account is ok now.\n \n Regards,\n Alice\n", + "message_id": "<1535873320.402417.1663976292034@mail.yahoo.com>" + } + ], + "analysis": [], + "attachments": [], + "created_at": "2026-10-24T01:29:12.007+00:00", + "subject": "Account issue followup", + "sessions": [ + { + "start": "2022-09-23T23:24:59.000+00:00", + "duration": 793, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0, + 1, + 2 + ] + } + ], + "uuid": "01a16b86-b24d-8057-b9a2-279e0d16bc46" +} diff --git a/src/__tests__/fixtures/examples/B4-two-party-call-external-recording.json b/src/__tests__/fixtures/examples/B4-two-party-call-external-recording.json new file mode 100644 index 0000000..f87d55b --- /dev/null +++ b/src/__tests__/fixtures/examples/B4-two-party-call-external-recording.json @@ -0,0 +1,45 @@ +{ + "vcon": "0.5.0", + "created_at": "2022-06-21T13:53:00-04:00", + "parties": [ + { + "tel": "+12345678901", + "name": "Alice" + }, + { + "tel": "+19876543210", + "name": "Bob" + } + ], + "dialog": [ + { + "type": "recording", + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "url": "https://github.com/ietf-wg-vcon/draft-ietf-vcon-vcon-core/raw/refs/heads/main/examples/ab_call_2ch.ogg", + "mediatype": "audio/ogg", + "filename": "ab_call_2ch.ogg", + "content_hash": "sha512-Y-Q9eclT6b5hFyIfLtnFAAXgqFzN5_Cjr3JQ3DMmcnpXHkGMgtvaxrLW2R2OhFTzR-DinyrngBG2w9lTZXr1EQ" + } + ], + "analysis": [], + "attachments": [], + "sessions": [ + { + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0 + ] + } + ], + "uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46" +} diff --git a/src/__tests__/fixtures/examples/B5-two-party-call-with-analysis.json b/src/__tests__/fixtures/examples/B5-two-party-call-with-analysis.json new file mode 100644 index 0000000..f0ef040 --- /dev/null +++ b/src/__tests__/fixtures/examples/B5-two-party-call-with-analysis.json @@ -0,0 +1,1075 @@ +{ + "vcon": "0.5.0", + "created_at": "2022-06-21T13:53:00-04:00", + "parties": [ + { + "tel": "+12345678901", + "name": "Alice" + }, + { + "tel": "+19876543210", + "name": "Bob" + } + ], + "dialog": [ + { + "type": "recording", + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "url": "https://github.com/ietf-wg-vcon/draft-ietf-vcon-vcon-core/raw/refs/heads/main/examples/ab_call_2ch.ogg", + "mediatype": "audio/ogg", + "filename": "ab_call_2ch.ogg", + "content_hash": "sha512-Y-Q9eclT6b5hFyIfLtnFAAXgqFzN5_Cjr3JQ3DMmcnpXHkGMgtvaxrLW2R2OhFTzR-DinyrngBG2w9lTZXr1EQ" + } + ], + "analysis": [ + { + "type": "transcript", + "dialog": 0, + "body": { + "metadata": { + "transaction_key": "deprecated", + "request_id": "01a16b9c-30a8-7941-9b74-a9c73124938a", + "sha256": "460145629244a6c72d4f0b94707ec3ca4e92da1ae11fe1d04a3fc88143795c63", + "created": "2026-10-24T01:52:40.996Z", + "duration": 32.925938, + "channels": 2, + "models": [ + "2187e11a-3532-4498-b076-81fa530bdd49" + ], + "model_info": { + "2187e11a-3532-4498-b076-81fa530bdd49": { + "name": "general-nova-3", + "version": "2025-07-31.0", + "arch": "nova-3" + } + }, + "diarize_info": { + "model_uuid": "a9f85c2b-5afb-4b9d-b49b-492c43a01cfb", + "arch": "v1" + } + }, + "results": { + "channels": [ + { + "alternatives": [ + { + "transcript": "Hi. I'd like to add Foo to my service. My name is Alice and my number is 1234567890. No. Thank you. Goodbye.", + "confidence": 0.99609375, + "words": [ + { + "word": "hi", + "start": 5.52, + "end": 6.16, + "confidence": 0.8781738, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "Hi." + }, + { + "word": "i'd", + "start": 6.24, + "end": 6.56, + "confidence": 0.9951172, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "I'd" + }, + { + "word": "like", + "start": 6.56, + "end": 6.72, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "like" + }, + { + "word": "to", + "start": 6.72, + "end": 6.7999997, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "to" + }, + { + "word": "add", + "start": 6.7999997, + "end": 7.12, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "add" + }, + { + "word": "foo", + "start": 7.12, + "end": 7.52, + "confidence": 0.6496582, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "Foo" + }, + { + "word": "to", + "start": 7.52, + "end": 7.8399997, + "confidence": 0.9902344, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "to" + }, + { + "word": "my", + "start": 7.8399997, + "end": 8, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "my" + }, + { + "word": "service", + "start": 8, + "end": 8.4, + "confidence": 0.99560547, + "speaker": 0, + "speaker_confidence": 0.93691725, + "punctuated_word": "service." + }, + { + "word": "my", + "start": 13.695001, + "end": 13.935, + "confidence": 0.99609375, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "My" + }, + { + "word": "name", + "start": 13.935, + "end": 14.175, + "confidence": 0.9980469, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "name" + }, + { + "word": "is", + "start": 14.175, + "end": 14.255, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "is" + }, + { + "word": "alice", + "start": 14.255, + "end": 14.815001, + "confidence": 0.9902344, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "Alice" + }, + { + "word": "and", + "start": 14.815001, + "end": 15.215, + "confidence": 0.7080078, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "and" + }, + { + "word": "my", + "start": 15.215, + "end": 15.455, + "confidence": 0.99609375, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "my" + }, + { + "word": "number", + "start": 15.455, + "end": 15.695, + "confidence": 0.9970703, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "number" + }, + { + "word": "is", + "start": 15.695, + "end": 16.335, + "confidence": 0.9970703, + "speaker": 0, + "speaker_confidence": 0.9877569, + "punctuated_word": "is" + }, + { + "word": "1234567890", + "start": 16.335, + "end": 20.255001, + "confidence": 0.9845703, + "speaker": 0, + "speaker_confidence": 0.98775685, + "punctuated_word": "1234567890." + }, + { + "word": "no", + "start": 27.820936, + "end": 28.380938, + "confidence": 0.8015137, + "speaker": 0, + "speaker_confidence": 0.89424765, + "punctuated_word": "No." + }, + { + "word": "thank", + "start": 28.380938, + "end": 28.700937, + "confidence": 0.9941406, + "speaker": 0, + "speaker_confidence": 0.89424765, + "punctuated_word": "Thank" + }, + { + "word": "you", + "start": 28.700937, + "end": 29.180937, + "confidence": 0.98657227, + "speaker": 0, + "speaker_confidence": 0.89424765, + "punctuated_word": "you." + }, + { + "word": "goodbye", + "start": 29.180937, + "end": 29.500937, + "confidence": 0.85009766, + "speaker": 0, + "speaker_confidence": 0.89424765, + "punctuated_word": "Goodbye." + } + ], + "paragraphs": { + "transcript": "\nSpeaker 0: Hi. I'd like to add Foo to my service. My name is Alice and my number is 1234567890. No. Thank you.\n\nGoodbye.", + "paragraphs": [ + { + "sentences": [ + { + "text": "Hi.", + "start": 5.52, + "end": 6.16 + }, + { + "text": "I'd like to add Foo to my service.", + "start": 6.24, + "end": 8.4 + }, + { + "text": "My name is Alice and my number is 1234567890.", + "start": 13.695001, + "end": 20.255001 + }, + { + "text": "No.", + "start": 27.820936, + "end": 28.380938 + }, + { + "text": "Thank you.", + "start": 28.380938, + "end": 29.180937 + } + ], + "speaker": 0, + "num_words": 21, + "start": 5.52, + "end": 29.180937 + }, + { + "sentences": [ + { + "text": "Goodbye.", + "start": 29.180937, + "end": 29.500937 + } + ], + "speaker": 0, + "num_words": 1, + "start": 29.180937, + "end": 29.500937 + } + ] + } + } + ] + }, + { + "alternatives": [ + { + "transcript": "Hello. This is example.com. My name is Bob. How can I help you? Okay. Can you give me your name and phone number so I can look up your account? Thank you. Okay. I've added food to your service. Is there anything else I can help you with? Goodbye. Have a nice day.", + "confidence": 1, + "words": [ + { + "word": "hello", + "start": 1.12, + "end": 1.68, + "confidence": 0.9790039, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "Hello." + }, + { + "word": "this", + "start": 1.68, + "end": 2.08, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "This" + }, + { + "word": "is", + "start": 2.08, + "end": 2.24, + "confidence": 0.9951172, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "is" + }, + { + "word": "example.com", + "start": 2.24, + "end": 3.28, + "confidence": 0.939209, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "example.com." + }, + { + "word": "my", + "start": 3.28, + "end": 3.4399998, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "My" + }, + { + "word": "name", + "start": 3.4399998, + "end": 3.6, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "name" + }, + { + "word": "is", + "start": 3.6, + "end": 3.6799998, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "is" + }, + { + "word": "bob", + "start": 3.6799998, + "end": 4.16, + "confidence": 0.99853516, + "speaker": 0, + "speaker_confidence": 0.5035404, + "punctuated_word": "Bob." + }, + { + "word": "how", + "start": 4.16, + "end": 4.4, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.24978054, + "punctuated_word": "How" + }, + { + "word": "can", + "start": 4.4, + "end": 4.56, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.24978054, + "punctuated_word": "can" + }, + { + "word": "i", + "start": 4.56, + "end": 4.64, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.24978054, + "punctuated_word": "I" + }, + { + "word": "help", + "start": 4.64, + "end": 4.88, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.24978054, + "punctuated_word": "help" + }, + { + "word": "you", + "start": 4.88, + "end": 5.36, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.24978054, + "punctuated_word": "you?" + }, + { + "word": "okay", + "start": 9.04, + "end": 9.759999, + "confidence": 0.99853516, + "speaker": 0, + "speaker_confidence": 0.42573488, + "punctuated_word": "Okay." + }, + { + "word": "can", + "start": 10.08, + "end": 10.32, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.42573488, + "punctuated_word": "Can" + }, + { + "word": "you", + "start": 10.32, + "end": 10.4, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.42573488, + "punctuated_word": "you" + }, + { + "word": "give", + "start": 10.4, + "end": 10.559999, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.42573488, + "punctuated_word": "give" + }, + { + "word": "me", + "start": 10.559999, + "end": 10.719999, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.42573488, + "punctuated_word": "me" + }, + { + "word": "your", + "start": 10.719999, + "end": 10.88, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "your" + }, + { + "word": "name", + "start": 10.88, + "end": 11.12, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "name" + }, + { + "word": "and", + "start": 11.12, + "end": 11.28, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "and" + }, + { + "word": "phone", + "start": 11.28, + "end": 11.5199995, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "phone" + }, + { + "word": "number", + "start": 11.5199995, + "end": 11.679999, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "number" + }, + { + "word": "so", + "start": 11.679999, + "end": 11.92, + "confidence": 0.9350586, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "so" + }, + { + "word": "i", + "start": 11.92, + "end": 12.08, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.49732846, + "punctuated_word": "I" + }, + { + "word": "can", + "start": 12.08, + "end": 12.16, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.2417295, + "punctuated_word": "can" + }, + { + "word": "look", + "start": 12.16, + "end": 12.32, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.2417295, + "punctuated_word": "look" + }, + { + "word": "up", + "start": 12.32, + "end": 12.48, + "confidence": 0.9921875, + "speaker": 0, + "speaker_confidence": 0.2417295, + "punctuated_word": "up" + }, + { + "word": "your", + "start": 12.48, + "end": 12.639999, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.2417295, + "punctuated_word": "your" + }, + { + "word": "account", + "start": 12.639999, + "end": 13.04, + "confidence": 0.9980469, + "speaker": 0, + "speaker_confidence": 0.2417295, + "punctuated_word": "account?" + }, + { + "word": "thank", + "start": 20.635, + "end": 20.955, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "Thank" + }, + { + "word": "you", + "start": 20.955, + "end": 21.435, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "you." + }, + { + "word": "okay", + "start": 22.795, + "end": 23.515, + "confidence": 0.9995117, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "Okay." + }, + { + "word": "i've", + "start": 23.994999, + "end": 24.395, + "confidence": 0.99853516, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "I've" + }, + { + "word": "added", + "start": 24.395, + "end": 24.715, + "confidence": 0.99902344, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "added" + }, + { + "word": "food", + "start": 24.715, + "end": 24.955, + "confidence": 0.9580078, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "food" + }, + { + "word": "to", + "start": 24.955, + "end": 25.115, + "confidence": 0.96435547, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "to" + }, + { + "word": "your", + "start": 25.115, + "end": 25.275, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "your" + }, + { + "word": "service", + "start": 25.275, + "end": 25.595001, + "confidence": 0.99560547, + "speaker": 0, + "speaker_confidence": 0.492307, + "punctuated_word": "service." + }, + { + "word": "is", + "start": 25.595001, + "end": 25.755001, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "Is" + }, + { + "word": "there", + "start": 25.755001, + "end": 25.915, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "there" + }, + { + "word": "anything", + "start": 25.915, + "end": 26.154999, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "anything" + }, + { + "word": "else", + "start": 26.154999, + "end": 26.395, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "else" + }, + { + "word": "i", + "start": 26.395, + "end": 26.635, + "confidence": 0.97314453, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "I" + }, + { + "word": "can", + "start": 26.635, + "end": 26.795, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "can" + }, + { + "word": "help", + "start": 26.795, + "end": 26.955, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "help" + }, + { + "word": "you", + "start": 26.955, + "end": 27.035, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "you" + }, + { + "word": "with", + "start": 27.035, + "end": 27.275, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.49394125, + "punctuated_word": "with?" + }, + { + "word": "goodbye", + "start": 30.320875, + "end": 30.960875, + "confidence": 0.99121094, + "speaker": 0, + "speaker_confidence": 0.21964735, + "punctuated_word": "Goodbye." + }, + { + "word": "have", + "start": 30.960875, + "end": 31.200874, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.21964735, + "punctuated_word": "Have" + }, + { + "word": "a", + "start": 31.200874, + "end": 31.360876, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.21964735, + "punctuated_word": "a" + }, + { + "word": "nice", + "start": 31.360876, + "end": 31.520876, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0.21964735, + "punctuated_word": "nice" + }, + { + "word": "day", + "start": 31.520876, + "end": 31.760876, + "confidence": 1, + "speaker": 0, + "speaker_confidence": 0, + "punctuated_word": "day." + } + ], + "paragraphs": { + "transcript": "\nSpeaker 0: Hello. This is example.com. My name is Bob. How can I help you? Okay.\n\nCan you give me your name and phone number so I can look up your account? Thank you. Okay. I've added food to your service. Is there anything else I can help you with?\n\nGoodbye. Have a nice day.", + "paragraphs": [ + { + "sentences": [ + { + "text": "Hello.", + "start": 1.12, + "end": 1.68 + }, + { + "text": "This is example.com.", + "start": 1.68, + "end": 3.28 + }, + { + "text": "My name is Bob.", + "start": 3.28, + "end": 4.16 + }, + { + "text": "How can I help you?", + "start": 4.16, + "end": 5.36 + }, + { + "text": "Okay.", + "start": 9.04, + "end": 9.759999 + } + ], + "speaker": 0, + "num_words": 14, + "start": 1.12, + "end": 9.759999 + }, + { + "sentences": [ + { + "text": "Can you give me your name and phone number so I can look up your account?", + "start": 10.08, + "end": 13.04 + }, + { + "text": "Thank you.", + "start": 20.635, + "end": 21.435 + }, + { + "text": "Okay.", + "start": 22.795, + "end": 23.515 + }, + { + "text": "I've added food to your service.", + "start": 23.994999, + "end": 25.595001 + }, + { + "text": "Is there anything else I can help you with?", + "start": 25.595001, + "end": 27.275 + } + ], + "speaker": 0, + "num_words": 34, + "start": 10.08, + "end": 27.275 + }, + { + "sentences": [ + { + "text": "Goodbye.", + "start": 30.320875, + "end": 30.960875 + }, + { + "text": "Have a nice day.", + "start": 30.960875, + "end": 31.760876 + } + ], + "speaker": 0, + "num_words": 5, + "start": 30.320875, + "end": 31.760876 + } + ] + } + } + ] + } + ], + "paragraphs": { + "transcript": "\nChannel 1: Speaker 0: Hello. This is example.com. My name is Bob. How can I help you?\n\nChannel 0: Hi. I'd like to add Foo to my service.\n\nChannel 1: Okay. Can you give me your name and phone number so I can look up your account?\n\nChannel 0: My name is Alice and my number is 1234567890.\n\nChannel 1: Thank you. Okay. I've added food to your service. Is there anything else I can help you with?\n\nChannel 0: No. Thank you. Goodbye.\n\nChannel 1: Goodbye. Have a nice day.", + "paragraphs": [ + { + "sentences": [ + { + "text": "Hello.", + "start": 1.12, + "end": 1.68 + }, + { + "text": "This is example.com.", + "start": 1.68, + "end": 3.28 + }, + { + "text": "My name is Bob.", + "start": 3.28, + "end": 4.16 + }, + { + "text": "How can I help you?", + "start": 4.16, + "end": 5.36 + } + ], + "speaker": 0, + "channel": 1, + "num_words": 13, + "start": 1.12, + "end": 5.36 + }, + { + "sentences": [ + { + "text": "Hi.", + "start": 5.52, + "end": 6.16 + }, + { + "text": "I'd like to add Foo to my service.", + "start": 6.24, + "end": 8.4 + } + ], + "speaker": 0, + "channel": 0, + "num_words": 9, + "start": 5.52, + "end": 8.4 + }, + { + "sentences": [ + { + "text": "Okay.", + "start": 9.04, + "end": 9.759999 + }, + { + "text": "Can you give me your name and phone number so I can look up your account?", + "start": 10.08, + "end": 13.04 + } + ], + "speaker": 0, + "channel": 1, + "num_words": 17, + "start": 9.04, + "end": 13.04 + }, + { + "sentences": [ + { + "text": "My name is Alice and my number is 1234567890.", + "start": 13.695001, + "end": 20.255001 + } + ], + "speaker": 0, + "channel": 0, + "num_words": 9, + "start": 13.695001, + "end": 20.255001 + }, + { + "sentences": [ + { + "text": "Thank you.", + "start": 20.635, + "end": 21.435 + }, + { + "text": "Okay.", + "start": 22.795, + "end": 23.515 + }, + { + "text": "I've added food to your service.", + "start": 23.994999, + "end": 25.595001 + }, + { + "text": "Is there anything else I can help you with?", + "start": 25.595001, + "end": 27.275 + } + ], + "speaker": 0, + "channel": 1, + "num_words": 18, + "start": 20.635, + "end": 27.275 + }, + { + "sentences": [ + { + "text": "No.", + "start": 27.820936, + "end": 28.380938 + }, + { + "text": "Thank you.", + "start": 28.380938, + "end": 29.180937 + }, + { + "text": "Goodbye.", + "start": 29.180937, + "end": 29.500937 + } + ], + "speaker": 0, + "channel": 0, + "num_words": 4, + "start": 27.820936, + "end": 29.500937 + }, + { + "sentences": [ + { + "text": "Goodbye.", + "start": 30.320875, + "end": 30.960875 + }, + { + "text": "Have a nice day.", + "start": 30.960875, + "end": 31.760876 + } + ], + "speaker": 0, + "channel": 1, + "num_words": 5, + "start": 30.320875, + "end": 31.760876 + } + ] + } + } + }, + "encoding": "json", + "vendor": "deepgram", + "schema": "deepgram_prerecorded", + "product": "transcription" + } + ], + "attachments": [], + "sessions": [ + { + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0 + ] + } + ], + "uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46" +} diff --git a/src/__tests__/fixtures/examples/B6-signed.json b/src/__tests__/fixtures/examples/B6-signed.json new file mode 100644 index 0000000..43c5df8 --- /dev/null +++ b/src/__tests__/fixtures/examples/B6-signed.json @@ -0,0 +1,17 @@ +{ + "payload": "eyJ2Y29uIjoiMC41LjAiLCJjcmVhdGVkX2F0IjoiMjAyMi0wNi0yMVQxMzo1MzowMC0wNDowMCIsInBhcnRpZXMiOlt7InRlbCI6IisxMjM0NTY3ODkwMSIsIm5hbWUiOiJBbGljZSJ9LHsidGVsIjoiKzE5ODc2NTQzMjEwIiwibmFtZSI6IkJvYiJ9XSwiZGlhbG9nIjpbeyJ0eXBlIj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fVotySCXsoMe7luSRYuldn8SBIpKYUGJlpWIi6Gr0mLwHarrYoi9bwtcKAxRNXZiGQghiUw2Zsw+jmgBrEtI4Iarg8wWqJ5Mov7MsTVpnoZ5Xywr0GznDlgcNtyqMibOULeM8yLPQrHn/tQjSiP3eUPz6+Zb9FqzQJCCi2UiauD4mOgzBSCCbew9PDYb2QeMZqNZmN3eVNMV4hh7t9jTc0zqPF5jluddVmpdHxLx/T9XZuSV21p8clNprJNQxprtHpxDxjhNMIrcV39rzi9tNikwmzRMf0r40f/JWnaV668sekDXtvIj8pZwyE4FNuaiJwojkQxDfjqk67Qs5NUQsFcaIwMes8It74ASHm8DUKEhDT2ASgMtUDwKWrOBefrSPqjY7+EMh2yVZnQhMwpx4s7CH0za32Yq+KC8GotHdI6jisDEom7aHglg==" + ], + "uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46" + }, + "signature": "HJA8mITP_gPp5FjIA2qw982rnUP44vDSeJRYGNXCxZhWm1c5dGRTlpbssDFBweCE_eOHpi8O2GhIulx9XBod3NgColJu2FDBC6mmk75ke37A2AmSBuIl6AhQpEkfs6FRunG9OQ3I-r6dok9WHYI7JmgqcZY-2GHvzCIMW3LgaJZ1Vdt7TK3vqMR_Nn8Cpo3jkodtwMAuXivUtHWz4oldkSczuVqUMKtawLIU0GvPMfShR1C7ayuWgXkg7f1yiU9cKNtQM-biEyvIfGe_3tSPl6G09IToJRo-17Ji1qmm1eTaMwudG4hWvFmlvWnQCq-QRFi30gfBYVEYyrAJj7p_Bg", + "protected": "eyJhbGciOiJSUzI1NiJ9" + } + ] +} diff --git a/src/__tests__/fixtures/examples/B7-encrypted.json b/src/__tests__/fixtures/examples/B7-encrypted.json new file mode 100644 index 0000000..179938e --- /dev/null +++ b/src/__tests__/fixtures/examples/B7-encrypted.json @@ -0,0 +1,15 @@ +{ + "protected": "eyJhbGciOiJSU0EtT0FFUCIsImVuYyI6IkEyNTZDQkMtSFM1MTIifQ", + "iv": "2LXY42Qg-9NP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9wgRr3Ef0mnrYVxZzxgt6uIuqJlRjP_FFyjzzWgaL9QlQg8-sHoAUQ8JDRO555sdMFQCpHiTrhQ", + "tag": "hyXd3meC4V_SRrDsobgH4f8skmb0R1XQUD1dNz268FI", + "recipients": [ + { + "encrypted_key": "Sm_D7ScQI9hhTknxXnSeg5ph2WugCTVUxmxJX-jmrGuxFdnLsJO2ww7hczEVsfdCPXXu2WjS2_nGBKr5T8YqfJnGqgvnoeddWCnlhnFDARrQCaj-Ra0rLADoCukdwubwsVnCuVaS1uuLRh0BGLq7GOSug5ANoXDyylfscaGO_2m2Jp1R8fk0G08SZ78SGRexkOhnpDAPFX1kOpVMWzS1ZYmYVTkZxjtv3Sm7YABnhvDhxdxHZFR_n83EYVSjIfenJOPnJ7M_hyWh2eStg2n-V6dpqc_PC9cHB-bGYey_Lnx4kDOiGeqjvg5yo_qYK0PYn-pr59Su0q0qZkp_3g80vQ" + } + ], + "unprotected": { + "uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46", + "cty": "application/vcon" + } +} diff --git a/src/__tests__/fixtures/examples/B8-redacted.json b/src/__tests__/fixtures/examples/B8-redacted.json new file mode 100644 index 0000000..043b84d --- /dev/null +++ b/src/__tests__/fixtures/examples/B8-redacted.json @@ -0,0 +1,165 @@ +{ + "vcon": "0.5.0", + "created_at": "2022-06-21T13:53:00-04:00", + "parties": [ + { + "name": "Alice" + }, + { + "name": "Bob" + } + ], + "dialog": [ + { + "type": "recording", + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "mediatype": "audio/ogg", + "filename": "ab_call_2ch.ogg", + "content_hash": "sha512-Y-Q9eclT6b5hFyIfLtnFAAXgqFzN5_Cjr3JQ3DMmcnpXHkGMgtvaxrLW2R2OhFTzR-DinyrngBG2w9lTZXr1EQ" + } + ], + "analysis": [ + { + "type": "transcript-redacted", + "dialog": 0, + "body": [ + { + "parties": 0, + "start": "2022-06-21T17:53:31.520000+00:00", + "duration": 0.6400000000000006, + "text": "Hi." + }, + { + "parties": 0, + "start": "2022-06-21T17:53:32.240000+00:00", + "duration": 2.16, + "text": "I'd like to add Foo to my service." + }, + { + "parties": 0, + "start": "2022-06-21T17:53:39.695001+00:00", + "duration": 6.5600000000000005, + "text": "My name is Alice and my number is {{BAN}}." + }, + { + "parties": 0, + "start": "2022-06-21T17:53:53.820936+00:00", + "duration": 0.5600020000000008, + "text": "No." + }, + { + "parties": 0, + "start": "2022-06-21T17:53:54.380938+00:00", + "duration": 0.7999989999999997, + "text": "Thank you." + }, + { + "parties": 0, + "start": "2022-06-21T17:53:55.180937+00:00", + "duration": 0.3200000000000003, + "text": "Goodbye." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:27.120000+00:00", + "duration": 0.5599999999999998, + "text": "Hello." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:27.680000+00:00", + "duration": 1.5999999999999999, + "text": "This is {{URL}}." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:29.280000+00:00", + "duration": 0.8800000000000003, + "text": "My name is Bob." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:30.160000+00:00", + "duration": 1.2000000000000002, + "text": "How can I help you?" + }, + { + "parties": 1, + "start": "2022-06-21T17:53:35.040000+00:00", + "duration": 0.7199990000000014, + "text": "{{US_STATE}}." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:36.080000+00:00", + "duration": 2.959999999999999, + "text": "Can you give me your name and phone number so I can look up your account?" + }, + { + "parties": 1, + "start": "2022-06-21T17:53:46.635000+00:00", + "duration": 0.7999999999999972, + "text": "Thank you." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:48.795000+00:00", + "duration": 0.7199999999999989, + "text": "{{US_STATE}}." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:49.994999+00:00", + "duration": 1.600002, + "text": "I've added food to your service." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:51.595001+00:00", + "duration": 1.6799989999999987, + "text": "Is there anything else I can help you with?" + }, + { + "parties": 1, + "start": "2022-06-21T17:53:56.320875+00:00", + "duration": 0.6400000000000006, + "text": "Goodbye." + }, + { + "parties": 1, + "start": "2022-06-21T17:53:56.960875+00:00", + "duration": 0.8000009999999982, + "text": "Have a nice day." + } + ], + "encoding": "json", + "vendor": "CapitalOne", + "schema": "data_labeler_schema", + "product": "dataprofiler" + } + ], + "attachments": [], + "sessions": [ + { + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0 + ] + } + ], + "uuid": "01928e10-193e-8231-b9a2-279e0d16bc46", + "redacted_from": { + "uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46", + "type": "PII Redaction" + } +} diff --git a/src/__tests__/fixtures/examples/B9-amended-signed.json b/src/__tests__/fixtures/examples/B9-amended-signed.json new file mode 100644 index 0000000..a48a977 --- /dev/null +++ b/src/__tests__/fixtures/examples/B9-amended-signed.json @@ -0,0 +1,59 @@ +{ + "vcon": "0.5.0", + "created_at": "2022-06-21T13:53:00-04:00", + "parties": [ + { + "tel": "+12345678901", + "name": "Alice" + }, + { + "tel": "+19876543210", + "name": "Bob" + } + ], + "dialog": [ + { + "type": "recording", + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "url": "https://github.com/ietf-wg-vcon/draft-ietf-vcon-vcon-core/raw/refs/heads/main/examples/ab_call_2ch.ogg", + "mediatype": "audio/ogg", + "filename": "ab_call_2ch.ogg", + "content_hash": "sha512-Y-Q9eclT6b5hFyIfLtnFAAXgqFzN5_Cjr3JQ3DMmcnpXHkGMgtvaxrLW2R2OhFTzR-DinyrngBG2w9lTZXr1EQ" + }, + { + "type": "text", + "start": "2022-06-21T17:53:26.000+00:00", + "parties": [ + 1 + ], + "mediatype": "text/plain", + "body": "Good day!", + "encoding": "none" + } + ], + "analysis": [], + "attachments": [], + "sessions": [ + { + "start": "2022-06-21T17:53:26.000+00:00", + "duration": 32.932396, + "parties": [ + 0, + 1 + ], + "dialog": [ + 0, + 1 + ] + } + ], + "uuid": "01a16b86-9ea3-8a32-a20f-d188127fad29", + "amended_from": { + "uuid": "01a16b86-96e7-80a8-b9a2-279e0d16bc46" + } +} diff --git a/src/__tests__/fixtures/vcon_json_schema.json b/src/__tests__/fixtures/vcon_json_schema.json deleted file mode 100644 index 16826b3..0000000 --- a/src/__tests__/fixtures/vcon_json_schema.json +++ /dev/null @@ -1,529 +0,0 @@ -{ - "$schema": "http://json-schema.org/draft-07/schema#", - "$id": "https://ietf.org/vcon/schemas/unsigned-vcon.json", - "title": "vCon - Unsigned Form", - "description": "JSON schema for the unsigned form of vCon (Conversational Data Container) as defined in RFCXXXX", - "type": "object", - "required": ["uuid", "created_at"], - "properties": { - "vcon": { - "type": "string", - "description": "DEPRECATED: Syntactic version of the JSON format. This was used to indicate schema changes in the Internet-Draft versions", - "const": "0.4.0" - }, - "uuid": { - "type": "string", - "description": "Globally unique identifier for the vCon. SHOULD be a version 8 UUID", - "format": "uuid" - }, - "extensions": { - "type": "array", - "description": "List of names of all vCon extensions used by this vCon", - "items": { - "type": "string" - } - }, - "critical": { - "type": "array", - "description": "List of extension names that a consumer MUST support to safely process this vCon", - "items": { - "type": "string" - } - }, - "created_at": { - "type": "string", - "description": "Creation time of this vCon in RFC3339 format", - "format": "date-time" - }, - "updated_at": { - "type": "string", - "description": "Last modified time of this vCon in RFC3339 format", - "format": "date-time" - }, - "subject": { - "type": "string", - "description": "Subject or topic of the conversation" - }, - "redacted": { - "type": "object", - "description": "Reference to the unredacted or less redacted vCon prior instance", - "required": ["type"], - "properties": { - "uuid": { - "type": "string", - "description": "UUID of the unredacted or less redacted vCon prior instance", - "format": "uuid" - }, - "type": { - "type": "string", - "description": "Type of redaction performed" - }, - "url": { - "type": "string", - "description": "HTTPS URL where the referenced vCon is stored", - "format": "uri" - }, - "content_hash": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ], - "description": "Hash(es) of the external content using format: algorithm-base64url_encoded_hash" - } - }, - "dependencies": { - "url": ["content_hash"] - } - }, - "amended": { - "type": "object", - "description": "Reference to the prior vCon instance version that this vCon amends", - "properties": { - "uuid": { - "type": "string", - "description": "UUID of the prior vCon instance version", - "format": "uuid" - }, - "url": { - "type": "string", - "description": "HTTPS URL where the referenced vCon is stored", - "format": "uri" - }, - "content_hash": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ], - "description": "Hash(es) of the external content (required if url is provided)" - } - }, - "dependencies": { - "url": ["content_hash"] - } - }, - "parties": { - "type": "array", - "description": "Array of Party Objects representing all parties involved in the conversation", - "items": { - "$ref": "#/definitions/Party" - } - }, - "dialog": { - "type": "array", - "description": "Array of Dialog Objects containing the captured conversation content", - "items": { - "$ref": "#/definitions/Dialog" - } - }, - "analysis": { - "type": "array", - "description": "Array of Analysis Objects containing analysis performed on the conversational data", - "items": { - "$ref": "#/definitions/Analysis" - } - }, - "attachments": { - "type": "array", - "description": "Array of Attachment Objects for ancillary documents related to the conversation", - "items": { - "$ref": "#/definitions/Attachment" - } - } - }, - "definitions": { - "Party": { - "type": "object", - "description": "Represents a party involved in the conversation", - "properties": { - "tel": { - "type": "string", - "description": "TEL URL (RFC3966) for the party" - }, - "sip": { - "type": "string", - "description": "SIP URL for the party" - }, - "stir": { - "type": "string", - "description": "STIR PASSporT in JWS Compact Serialization form" - }, - "mailto": { - "type": "string", - "description": "Email address for the party in any common form, including a bare address or a MAILTO URL" - }, - "name": { - "type": "string", - "description": "Name of the party" - }, - "did": { - "type": "string", - "description": "Decentralized Identifier (DID) URI for the party" - }, - "validation": { - "type": "string", - "description": "Label or token identifying the method of identity validation used" - }, - "gmlpos": { - "type": "string", - "description": "Geographic location in GML pos format (latitude longitude)" - }, - "civicaddress": { - "$ref": "#/definitions/Civicaddress" - }, - "uuid": { - "type": "string", - "description": "Unique identifier for the participant" - }, - "type": { - "type": "string", - "description": "Participant type" - }, - "org": { - "type": "string", - "description": "Organization to which the party belongs" - }, - "dept": { - "type": "string", - "description": "Department to which the party belongs" - } - } - }, - "Civicaddress": { - "type": "object", - "description": "Civic address information for a party's location", - "properties": { - "country": {"type": "string"}, - "a1": {"type": "string", "description": "National subdivision (state/province)"}, - "a2": {"type": "string", "description": "County/parish/district"}, - "a3": {"type": "string", "description": "City/township"}, - "a4": {"type": "string", "description": "City division/borough"}, - "a5": {"type": "string", "description": "Neighborhood/block"}, - "a6": {"type": "string", "description": "Street"}, - "prd": {"type": "string", "description": "Leading street direction"}, - "pod": {"type": "string", "description": "Trailing street suffix"}, - "sts": {"type": "string", "description": "Street suffix"}, - "hno": {"type": "string", "description": "House number"}, - "hns": {"type": "string", "description": "House number suffix"}, - "lmk": {"type": "string", "description": "Landmark"}, - "loc": {"type": "string", "description": "Additional location info"}, - "flr": {"type": "string", "description": "Floor"}, - "nam": {"type": "string", "description": "Name/occupant"}, - "pc": {"type": "string", "description": "Postal code"} - } - }, - "Dialog": { - "type": "object", - "description": "Represents a segment of captured conversation", - "required": ["type", "start"], - "properties": { - "type": { - "type": "string", - "enum": ["recording", "text", "transfer", "incomplete", "recording-set"], - "description": "Type of dialog" - }, - "start": { - "type": "string", - "format": "date-time", - "description": "Start time of the dialog in RFC3339 format" - }, - "duration": { - "anyOf": [ - {"type": "integer", "minimum": 0}, - {"type": "number", "minimum": 0} - ], - "description": "Duration in seconds" - }, - "parties": { - "anyOf": [ - {"type": "integer", "minimum": 0}, - {"type": "array", "items": {"type": "integer", "minimum": 0}}, - { - "type": "array", - "items": { - "anyOf": [ - {"type": "integer", "minimum": 0}, - {"type": "array", "items": {"type": "integer", "minimum": 0}}, - {"type": "null"} - ] - } - } - ], - "description": "Index/indices of parties in the parties array" - }, - "originator": { - "type": "integer", - "minimum": 0, - "description": "Index of the originating party if first party is not the originator" - }, - "recordings": { - "type": "array", "items": {"type": "integer", "minimum": 0}, - "description": "recording-set reference to list of indices to recording Dialog Objects" - }, - "recording_set": { - "type": "integer", - "minimum": 0, - "description": "Index of the recording-set Dialog Object that this recording is a part of" - }, - "mediatype": { - "type": "string", - "description": "Media type of the dialog content" - }, - "filename": { - "type": "string", - "description": "Original filename of the dialog content" - }, - "body": { - "description": "Inline content of the dialog (for inline files). Any type for encoding=json, otherwise it must be a string." - }, - "encoding": { - "type": "string", - "enum": ["base64url", "json", "none"], - "description": "Encoding type for inline content" - }, - "url": { - "type": "string", - "format": "uri", - "description": "HTTPS URL for externally referenced content" - }, - "content_hash": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ], - "description": "Hash(es) of external content" - }, - "disposition": { - "type": "string", - "enum": ["no-answer", "congestion", "failed", "busy", "hung-up", "voicemail-no-message"], - "description": "Reason for incomplete dialog (required for incomplete type)" - }, - "session_id": { - "anyOf": [ - {"$ref": "#/definitions/SessionId"}, - {"type": "array", "items": {"$ref": "#/definitions/SessionId"}}, - { - "type": "array", - "items": { - "oneOf": [ - {"$ref": "#/definitions/SessionId"}, - {"type": "array", "items": {"$ref": "#/definitions/SessionId"}} - ] - } - } - ], - "description": "Session ID(s) for the dialog" - }, - "party_history": { - "type": "array", - "items": {"$ref": "#/definitions/PartyHistory"}, - "description": "History of party join/drop/hold/mute events" - }, - "transferee": { - "type": "integer", - "minimum": 0, - "description": "Party index of the transferee (for transfer type)" - }, - "transferor": { - "type": "integer", - "minimum": 0, - "description": "Party index of the transferor (for transfer type)" - }, - "transfer_target": { - "oneOf": [ - {"type": "integer", "minimum": 0}, - {"type": "array", "items": {"type": "integer", "minimum": 0}} - ], - "description": "Party index/indices of the transfer target (for transfer type)" - }, - "original": { - "oneOf": [ - {"type": "integer", "minimum": 0}, - {"type": "array", "items": {"type": "integer", "minimum": 0}} - ], - "description": "Dialog index/indices of original conversation (for transfer type)" - }, - "consultation": { - "oneOf": [ - {"type": "integer", "minimum": 0}, - {"type": "array", "items": {"type": "integer", "minimum": 0}} - ], - "description": "Dialog index/indices of consultation (for transfer type)" - }, - "target_dialog": { - "oneOf": [ - {"type": "integer", "minimum": 0}, - {"type": "array", "items": {"type": "integer", "minimum": 0}} - ], - "description": "Dialog index/indices of target dialog (for transfer type)" - }, - "application": { - "type": "string", - "description": "Application, communication channel or context of the conversation" - }, - "message_id": { - "type": "string", - "description": "Unique message identifier from the messaging system" - } - } - }, - "SessionId": { - "type": "object", - "description": "Session identifier with local and remote UUIDs", - "properties": { - "local": { - "type": "string", - "description": "Local UUID for the session" - }, - "remote": { - "type": "string", - "description": "Remote UUID for the session" - } - } - }, - "PartyHistory": { - "type": "object", - "description": "Records party events during the dialog", - "required": ["party", "time", "event"], - "properties": { - "party": { - "type": "integer", - "minimum": 0, - "description": "Index of the party" - }, - "time": { - "type": "string", - "format": "date-time", - "description": "Time of the event in RFC3339 format" - }, - "event": { - "type": "string", - "enum": ["join", "drop", "hold", "unhold", "mute", "unmute", "keydown", "keyup"], - "description": "Type of event" - }, - "button": { - "type": "string", - "description": "DTMF digit, character or string (required for keydown/keyup events)" - } - } - }, - "Attachment": { - "type": "object", - "description": "Represents an ancillary document related to the conversation", - "required": ["start", "party", "dialog"], - "properties": { - "purpose": { - "type": "string", - "description": "text description of what the attachment is for" - }, - "start": { - "type": "string", - "format": "date-time", - "description": "Time the attachment was sent/exchanged in RFC3339 format" - }, - "party": { - "type": "integer", - "minimum": 0, - "description": "Index of the party that contributed the attachment" - }, - "dialog": { - "type": "integer", - "minimum": 0, - "description": "Index of the dialog this attachment is part of" - }, - "mediatype": { - "type": "string", - "description": "Media type of the attachment" - }, - "filename": { - "type": "string", - "description": "Original filename of the attachment" - }, - "body": { - "description": "Inline content of the attachment (for inline files). Any type for encoding=json, otherwise it must be a string." - }, - "encoding": { - "type": "string", - "enum": ["base64url", "json", "none"], - "description": "Encoding type for inline content" - }, - "url": { - "type": "string", - "format": "uri", - "description": "HTTPS URL for externally referenced attachment" - }, - "content_hash": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ], - "description": "Hash(es) of external content" - } - } - }, - "Analysis": { - "type": "object", - "description": "Represents analysis performed on the conversational data", - "required": ["type", "vendor"], - "properties": { - "type": { - "type": "string", - "description": "Semantic type of analysis (e.g., report, sentiment, summary, transcript, translation, tts)" - }, - "dialog": { - "oneOf": [ - {"type": "integer", "minimum": 0}, - {"type": "array", "items": {"type": "integer", "minimum": 0}} - ], - "description": "Index/indices of dialog objects this analysis is based on" - }, - "attachment": { - "oneOf": [ - {"type": "integer", "minimum": 0}, - {"type": "array", "items": {"type": "integer", "minimum": 0}} - ], - "description": "Index/indices of attachment objects this analysis is based on" - }, - "mediatype": { - "type": "string", - "description": "Media type of the analysis file" - }, - "filename": { - "type": "string", - "description": "Original filename of the analysis data" - }, - "vendor": { - "type": "string", - "description": "Vendor or product name that generated the analysis" - }, - "product": { - "type": "string", - "description": "Product name to differentiate from other vendor products" - }, - "schema": { - "type": "string", - "description": "Token or label for the data format/schema of the analysis" - }, - "body": { - "description": "Inline content of the analysis (for inline files). Any type for encoding=json, otherwise it must be a string." - }, - "encoding": { - "type": "string", - "enum": ["base64url", "json", "none"], - "description": "Encoding type for inline content" - }, - "url": { - "type": "string", - "format": "uri", - "description": "HTTPS URL for externally referenced analysis" - }, - "content_hash": { - "oneOf": [ - {"type": "string"}, - {"type": "array", "items": {"type": "string"}} - ], - "description": "Hash(es) of external content" - } - } - } - } -} From 887065817816508d7df2ba50c841f5ec0f666412 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:36:00 -0500 Subject: [PATCH 2/6] Port the library to vCon core-05 (syntax 0.5.0) Add Session, Session_Reference and Event objects, the per-event-type parameter table, redacted_from/amended_from/redacted_strings, attachment scoping by dialog or session, empty placeholder Dialogs, and validation of the core-05 rules including extensions enforcement. Reject JWS alg none on sign and verify. Add migrate040To050 with a migration report, and migrate 0.4.0 input on load (signed input is not migrated on load). Writers emit 0.5.0. Dialog loses transfer, recording-set, party_history and originator content; the old names stay as deprecated aliases where noted. Co-Authored-By: Claude Opus 5.5 --- src/attachment.ts | 34 +- src/dialog.ts | 187 +++--- src/event.ts | 334 +++++++++++ src/index.ts | 78 ++- src/migration.ts | 1393 +++++++++++++++++++++++++++++++++++++++++++++ src/party.ts | 26 +- src/session.ts | 202 +++++++ src/types.ts | 215 +++++-- src/util.ts | 93 +++ src/validation.ts | 553 ++++++++++++++++++ src/vcon.ts | 539 ++++++++++++++++-- 11 files changed, 3447 insertions(+), 207 deletions(-) create mode 100644 src/event.ts create mode 100644 src/migration.ts create mode 100644 src/session.ts create mode 100644 src/util.ts create mode 100644 src/validation.ts diff --git a/src/attachment.ts b/src/attachment.ts index ba541c9..59483bd 100644 --- a/src/attachment.ts +++ b/src/attachment.ts @@ -7,7 +7,12 @@ function isValidContentHash(value: string): boolean { /** * Attachment class for representing attached files in a vCon. - * Compliant with IETF draft-ietf-vcon-vcon-core + * Compliant with draft-ietf-vcon-vcon-core-05. + * + * An attachment has `party` plus `dialog` (a single index) or `session` (an + * index or list). The class never defaults the scope: the right index depends + * on the vCon. Vcon.addAttachment() defaults it only when the vCon has + * exactly one Session. */ export class Attachment implements Partial { /** Valid encodings per vcon-core */ @@ -16,7 +21,8 @@ export class Attachment implements Partial { purpose?: string; start?: Date | string; party?: number; - dialog?: number | number[]; + dialog?: number; + session?: number | number[]; mediatype?: string; filename?: string; body?: any; @@ -34,10 +40,10 @@ export class Attachment implements Partial { Object.assign(this, params); - // Default party/dialog to 0 (vCon-level) when omitted — spec requires - // both indices on every attachment. + // party defaults to 0 (the tags convention). dialog and session are NOT + // defaulted: core-05 needs at least one of them, and the right value + // depends on the vCon. if (this.party === undefined) this.party = 0; - if (this.dialog === undefined) this.dialog = 0; if (params.body !== undefined && !params.encoding) { this.encoding = 'none'; @@ -122,20 +128,18 @@ export class Attachment implements Partial { validate(): { valid: boolean; errors: string[] } { const errors: string[] = []; - // Core spec requires `purpose`. The one extension exception is the - // lawful_basis attachment (draft-howe-vcon-lawful-basis), which uses - // `type: "lawful_basis"`. - const extType = (this as any).type; - const isLawfulBasisExt = extType === 'lawful_basis'; - if (!this.purpose && !isLawfulBasisExt) { - errors.push('Attachment must have a purpose (or be the lawful_basis extension)'); + if (!this.purpose) { + errors.push('Attachment must have a purpose'); } + if (!this.start) { + errors.push('Attachment.start is required'); + } if (this.party === undefined) { - errors.push('Attachment.party is required (use 0 for vCon-level)'); + errors.push('Attachment.party is required'); } - if (this.dialog === undefined) { - errors.push('Attachment.dialog is required (use 0 for vCon-level)'); + if (this.dialog === undefined && this.session === undefined) { + errors.push('Attachment needs at least one of dialog or session'); } // Cannot have both inline and external data diff --git a/src/dialog.ts b/src/dialog.ts index a9b721a..3a00d5b 100644 --- a/src/dialog.ts +++ b/src/dialog.ts @@ -1,12 +1,13 @@ import { Dialog as DialogType, - PartyHistory, DialogType as DialogTypeEnum, DialogDisposition, Encoding, - SessionId + SessionId, + RedactedSegment } from './types'; -import { PartyHistory as PartyHistoryClass } from './party'; +import { DIALOG_MIME_TYPES, LEGACY_DIALOG_PARAMS, mediatypeOk } from './validation'; +import { parseDateTime, warn } from './util'; /** * Matches a spec-compliant content_hash: "sha512-" + base64url-encoded @@ -20,13 +21,34 @@ function isValidContentHash(value: string): boolean { return SHA512_CONTENT_HASH_RE.test(value); } +/** Parameters of the Dialog constructor. */ +export type DialogParams = Partial & { + type: DialogTypeEnum | string; + start: Date | string; +}; + +/** + * Parameters that core-05 moved off the Dialog (to Session and Event Objects). + * Passing one to the Dialog constructor throws, so a 0.4.0 shaped Dialog cannot + * be built by accident. `transfer` is the 0.4.0 transfer details object. + */ +const REMOVED_PARAMS = [...LEGACY_DIALOG_PARAMS, 'transfer']; + +/** Legacy media Dialog types: built as `recording`. */ +const MEDIA_TYPE_ALIASES = ['audio', 'video']; + /** * Dialog class representing a conversation segment. - * Compliant with the current IETF vCon core draft (draft-ietf-vcon-vcon-core). + * Compliant with draft-ietf-vcon-vcon-core-05. + * + * Under core-05 a Dialog is a recording, text or incomplete (failed setup) + * segment. Transfers, party history and recording sets moved to Event and + * Session Objects. An empty Dialog (`{}`, see Dialog.placeholder()) holds an + * array position so Dialog indices stay stable. */ export class Dialog implements Partial { - /** Valid dialog types per the vCon core draft */ - static readonly DIALOG_TYPES: DialogTypeEnum[] = ['recording', 'text', 'transfer', 'incomplete', 'recording-set']; + /** Valid dialog types per core-05 */ + static readonly DIALOG_TYPES: DialogTypeEnum[] = ['recording', 'text', 'incomplete']; /** Valid dispositions for incomplete dialogs */ static readonly DISPOSITIONS: DialogDisposition[] = [ @@ -38,34 +60,16 @@ export class Dialog implements Partial { 'voicemail-no-message' ]; - /** Supported MIME types for media content */ - static readonly MIME_TYPES = [ - 'text/plain', - 'audio/x-wav', - 'audio/wav', - 'audio/wave', - 'audio/mpeg', - 'audio/mp3', - 'audio/ogg', - 'audio/webm', - 'audio/x-m4a', - 'audio/aac', - 'video/mp4', - 'video/x-mp4', - 'video/ogg', - 'video/webm', - 'multipart/mixed', - 'message/rfc822', - 'application/json' - ]; + /** Supported MIME types for media content (text/*, message/* and multipart/* subtypes are also accepted) */ + static readonly MIME_TYPES: string[] = DIALOG_MIME_TYPES; /** Valid encodings per vcon-core */ static readonly VALID_ENCODINGS: Encoding[] = ['base64url', 'json', 'none']; - readonly type: DialogTypeEnum | string; - readonly start: Date | string; - parties?: number | number[]; - originator?: number; + readonly type?: DialogTypeEnum | string; + readonly start?: Date | string; + /** Contributing parties (the Session lists the receivers) */ + parties?: number | Array; mediatype?: string; filename?: string; body?: string; @@ -75,23 +79,15 @@ export class Dialog implements Partial { duration?: number; disposition?: DialogDisposition | string; session_id?: SessionId | SessionId[]; - party_history?: PartyHistory[]; application?: string; message_id?: string; - recordings?: number[]; - recording_set?: number; + redacted_segments?: RedactedSegment[]; // Legacy/extension fields /** @deprecated Use mediatype instead */ mimetype?: string; alg?: string; signature?: string; - transferee?: number; - transferor?: number; - transfer_target?: number | number[]; - original?: number | number[]; - consultation?: number | number[]; - target_dialog?: number | number[]; provenance?: Record; campaign?: string; interaction?: string; @@ -99,11 +95,24 @@ export class Dialog implements Partial { meta?: Record; [key: string]: any; - constructor(params: Partial & { type: DialogTypeEnum | string; start: Date | string }) { - this.type = params.type; + constructor(params: DialogParams) { + const removed = REMOVED_PARAMS.filter(k => params[k] !== undefined); + if (removed.length) { + throw new Error( + `Dialog parameter(s) ${removed.join(', ')} were removed in vCon 0.5.0: put the receivers and originator ` + + 'on the Session, and record party history and transfers as Event Objects (see Event and PartyHistory.toEvent).' + ); + } + + let type = params.type; + if (typeof type === 'string' && MEDIA_TYPE_ALIASES.includes(type)) { + warn(`Dialog type '${type}' is not defined by core-05; building a 'recording' Dialog.`); + type = 'recording'; + } + this.type = type; this.start = params.start; - // Copy parties - can be number or number[] per vcon-core + // Copy parties - number, list, nested list or null entries per core-05 if (params.parties !== undefined) { this.parties = params.parties; } @@ -121,11 +130,32 @@ export class Dialog implements Partial { } } + /** + * An empty Dialog Object (`{}`), which core-05 permits as a placeholder that + * holds an array position so that Dialog indices do not shift. + */ + static placeholder(): Dialog { + return Object.create(Dialog.prototype) as Dialog; + } + + /** + * Wrap an existing Dialog Object (for reading). Unlike the constructor this + * does not reject 0.4.0 parameters, so it can wrap a Dialog from an + * unmigrated vCon. + */ + static fromDict(data: DialogType): Dialog { + return Object.assign(Object.create(Dialog.prototype), data) as Dialog; + } + + /** True for an empty placeholder Dialog. */ + isPlaceholder(): boolean { + return Object.keys(this.toDict()).length === 0; + } + toDict(): DialogType { - const dict: DialogType = { - type: this.type, - start: this.start instanceof Date ? this.start.toISOString() : this.start - }; + const dict: DialogType = {}; + if (this.type !== undefined) dict.type = this.type; + if (this.start !== undefined) dict.start = this.start instanceof Date ? this.start.toISOString() : this.start; // Add parties if defined if (this.parties !== undefined) { @@ -213,13 +243,6 @@ export class Dialog implements Partial { return this.type === 'recording'; } - /** - * Check if dialog is a recording-set (a collection referencing recording dialogs) - */ - isRecordingSet(): boolean { - return this.type === 'recording-set'; - } - /** * Check if dialog is audio content */ @@ -252,10 +275,12 @@ export class Dialog implements Partial { } /** - * Check if dialog is a transfer type + * @deprecated The transfer Dialog type was removed in 0.5.0; transfers are + * Events. Always returns false. */ isTransfer(): boolean { - return this.type === 'transfer'; + warn('Dialog.isTransfer() is deprecated: core-05 has no transfer Dialog; use transfer Events.'); + return false; } /** @@ -266,21 +291,35 @@ export class Dialog implements Partial { } /** - * Validate the dialog against vcon-core requirements + * Validate the dialog against core-05 requirements */ validate(): { valid: boolean; errors: string[] } { const errors: string[] = []; + if (this.isPlaceholder()) { + return { valid: true, errors }; + } + if (!this.type) { errors.push('Dialog type is required'); + } else if (!Dialog.DIALOG_TYPES.includes(this.type as DialogTypeEnum)) { + errors.push(`Invalid dialog type: ${this.type}. Must be one of: ${Dialog.DIALOG_TYPES.join(', ')}`); } if (!this.start) { errors.push('Dialog start time is required'); + } else if (parseDateTime(this.start instanceof Date ? this.start.toISOString() : this.start) === undefined) { + errors.push('Dialog start must be an ISO 8601 datetime'); } - if (this.type === 'incomplete' && !this.disposition) { - errors.push('Disposition is required for incomplete dialogs'); + if (this.type === 'incomplete') { + if (!this.disposition) { + errors.push('Disposition is required for incomplete dialogs'); + } + // An incomplete Dialog has no content (core-05 section 4.5). + for (const key of ['mediatype', 'filename', 'body', 'encoding', 'url', 'content_hash', 'message_id', 'redacted_segments']) { + if (this[key] !== undefined) errors.push(`Incomplete dialog MUST NOT include ${key}`); + } } if (this.disposition && !Dialog.DISPOSITIONS.includes(this.disposition as DialogDisposition)) { @@ -295,8 +334,12 @@ export class Dialog implements Partial { errors.push(`Invalid encoding: ${this.encoding}. Must be one of: ${Dialog.VALID_ENCODINGS.join(', ')}`); } - // External media MUST carry content_hash (spec §4.3.x) and the hash - // format MUST be sha512-. + if (this.mediatype !== undefined && !mediatypeOk(this.mediatype, Dialog.MIME_TYPES)) { + errors.push(`Invalid mediatype: ${this.mediatype}`); + } + + // External media MUST carry content_hash and the hash format MUST be + // sha512-. if (this.url !== undefined) { if (this.content_hash === undefined) { errors.push('Dialog with external url MUST include content_hash'); @@ -311,30 +354,6 @@ export class Dialog implements Partial { } } - // transfer-type dialogs MUST NOT carry party-conversation fields or content - // (draft-ietf-vcon-vcon-core §4.3 transfer subtype). - if (this.type === 'transfer') { - const forbidden: Array = ['parties', 'originator', 'mediatype', 'filename', 'body', 'url']; - for (const key of forbidden) { - if (this[key as string] !== undefined) { - errors.push(`Transfer dialog MUST NOT include ${String(key)}`); - } - } - } - - if (this.party_history) { - this.party_history.forEach((entry, i) => { - if (!PartyHistoryClass.VALID_EVENTS.includes(entry.event)) { - errors.push( - `Invalid party_history[${i}].event: ${entry.event}. Must be one of: ${PartyHistoryClass.VALID_EVENTS.join(', ')}` - ); - } - if ((entry.event === 'keydown' || entry.event === 'keyup') && !entry.button) { - errors.push(`party_history[${i}]: button is required for ${entry.event} events`); - } - }); - } - return { valid: errors.length === 0, errors diff --git a/src/event.ts b/src/event.ts new file mode 100644 index 0000000..639dac9 --- /dev/null +++ b/src/event.ts @@ -0,0 +1,334 @@ +/** + * Event Object (core-05 section 4.3) and the events array. + * + * An Event is a point-in-time occurrence inside one or more Sessions: a party + * joining or dropping, a key press, a call transfer step, or a change of the + * parties contributing to a recording channel. + * + * The per-type parameter applicability table of section 4.3.1.5 is held in + * EVENT_PARAMETER_RULES and enforced by validateEvent() and by Vcon.isValid(). + * + * Rule codes: + * M the parameter MUST be present + * O the parameter is optional + * SN the parameter SHOULD NOT be present (reported as a warning) + * X the parameter MUST NOT be present + */ +import { Event as EventType } from './types'; +import { ValidateContext } from './session'; +import { isIndex, isPlainObject, parseDateTime, toIso, warn } from './util'; + +export type RuleCode = 'M' | 'O' | 'SN' | 'X'; + +export const PARTY_EVENT_TYPES = ['join', 'drop', 'hold', 'unhold', 'mute', 'unmute']; +export const KEY_EVENT_TYPES = ['keydown', 'keyup']; +export const TRANSFER_EVENT_TYPES = [ + 'consultation-start', + 'blind-transfer', + 'consultative-transfer', + 'transfer-abandoned' +]; +export const CHANNEL_CONTRIBUTORS_EVENT_TYPE = 'channel-contributors'; + +/** Every Event type token defined by core-05 (section 4.3.1). */ +export const CORE_EVENT_TYPES = [ + ...PARTY_EVENT_TYPES, + ...KEY_EVENT_TYPES, + ...TRANSFER_EVENT_TYPES, + CHANNEL_CONTRIBUTORS_EVENT_TYPE +]; + +/** Event parameters in the order of section 4.3. */ +export const EVENT_PARAMETERS = [ + 'type', + 'time', + 'sessions', + 'party', + 'dialog', + 'channel', + 'contributors', + 'button', + 'transferee', + 'transfer_target', + 'consultation', + 'target_session' +] as const; + +type Rules = Record<(typeof EVENT_PARAMETERS)[number], RuleCode>; + +function rules(overrides: Partial = {}): Rules { + return { + type: 'M', + time: 'M', + sessions: 'M', + party: 'M', + dialog: 'SN', + channel: 'X', + contributors: 'X', + button: 'X', + transferee: 'X', + transfer_target: 'X', + consultation: 'X', + target_session: 'X', + ...overrides + }; +} + +/** Parameter applicability by Event type (section 4.3.1.5 tables). */ +export const EVENT_PARAMETER_RULES: Record = {}; +for (const t of PARTY_EVENT_TYPES) EVENT_PARAMETER_RULES[t] = rules(); +for (const t of KEY_EVENT_TYPES) EVENT_PARAMETER_RULES[t] = rules({ button: 'M' }); +EVENT_PARAMETER_RULES['consultation-start'] = rules({ + transferee: 'M', + transfer_target: 'M', + consultation: 'M', + target_session: 'X' +}); +EVENT_PARAMETER_RULES['blind-transfer'] = rules({ + transferee: 'M', + transfer_target: 'M', + consultation: 'X', + target_session: 'M' +}); +EVENT_PARAMETER_RULES['consultative-transfer'] = rules({ + transferee: 'M', + transfer_target: 'M', + consultation: 'M', + target_session: 'M' +}); +EVENT_PARAMETER_RULES['transfer-abandoned'] = rules({ + transferee: 'M', + transfer_target: 'O', + consultation: 'O', + target_session: 'X' +}); +EVENT_PARAMETER_RULES[CHANNEL_CONTRIBUTORS_EVENT_TYPE] = { + type: 'M', + time: 'M', + sessions: 'X', + party: 'X', + dialog: 'M', + channel: 'M', + contributors: 'O', + button: 'X', + transferee: 'X', + transfer_target: 'X', + consultation: 'X', + target_session: 'X' +}; + +function isIndexOrList(value: unknown): boolean { + return isIndex(value) || (Array.isArray(value) && value.every(isIndex)); +} + +/** + * Validate one Event Object against core-05 section 4.3. + * + * SN violations are warnings, M and X violations are errors. An Event whose + * type is not a core token is only checked for `type` and `time` (section 2.5: + * it belongs to an extension). Index values are range-checked only when the + * matching count is supplied. + */ +export function validateEvent( + event: unknown, + ctx: ValidateContext = {} +): { errors: string[]; warnings: string[] } { + const { partyCount, dialogCount, sessionCount } = ctx; + const label = ctx.label ?? 'Event'; + const errors: string[] = []; + const warnings: string[] = []; + if (!isPlainObject(event)) { + return { errors: [`${label} must be a dictionary.`], warnings }; + } + + const etype = event.type; + if (typeof etype !== 'string' || !etype) { + errors.push(`${label} is missing required field: type`); + } + if (!('time' in event)) { + errors.push(`${label} is missing required field: time`); + } else if (parseDateTime(event.time) === undefined) { + errors.push(`${label} has an invalid 'time' format. Must be an ISO 8601 datetime string.`); + } + + const table = typeof etype === 'string' && Object.prototype.hasOwnProperty.call(EVENT_PARAMETER_RULES, etype) + ? EVENT_PARAMETER_RULES[etype] + : undefined; + if (table) { + for (const [param, code] of Object.entries(table)) { + const present = param in event; + if (code === 'M' && !present) { + errors.push(`${label} of type '${etype}' is missing required field: ${param}`); + } else if (code === 'X' && present) { + errors.push(`${label} of type '${etype}' must not have field: ${param}`); + } else if (code === 'SN' && present) { + warnings.push(`${label} of type '${etype}' should not have field: ${param}`); + } + } + } + + const checkIndex = (param: string, count: number | undefined, noun: string): void => { + if (!(param in event)) return; + const val = event[param]; + if (!isIndex(val)) { + errors.push(`${label} field '${param}' must be a non-negative integer.`); + } else if (count !== undefined && val >= count) { + errors.push(`${label} references invalid ${noun} index: ${val}`); + } + }; + checkIndex('party', partyCount, 'party'); + checkIndex('transferee', partyCount, 'party'); + checkIndex('transfer_target', partyCount, 'party'); + checkIndex('consultation', sessionCount, 'session'); + checkIndex('target_session', sessionCount, 'session'); + + if ('dialog' in event) { + const val = event.dialog; + let idxs: number[] = []; + if (isIndex(val)) { + idxs = [val]; + } else if ( + Array.isArray(val) && + typeof etype === 'string' && + !CORE_EVENT_TYPES.includes(etype) && + val.every(isIndex) + ) { + idxs = val as number[]; // extension event types may use an array (4.3.5) + } else { + errors.push(`${label} field 'dialog' must be a non-negative integer.`); + } + for (const v of idxs) { + if (dialogCount !== undefined && v >= dialogCount) { + errors.push(`${label} references invalid dialog index: ${v}`); + } + } + } + + if ('channel' in event && !isIndex(event.channel)) { + errors.push(`${label} field 'channel' must be a non-negative integer.`); + } + + if ('sessions' in event) { + const val = event.sessions; + if (!isIndexOrList(val)) { + errors.push(`${label} field 'sessions' must be an index or a list of indices.`); + } else { + const idxs: number[] = Array.isArray(val) ? val : [val as number]; + if (typeof etype === 'string' && TRANSFER_EVENT_TYPES.includes(etype) && Array.isArray(val)) { + errors.push(`${label} of type '${etype}' must reference a single session index in 'sessions'.`); + } + for (const v of idxs) { + if (sessionCount !== undefined && v >= sessionCount) { + errors.push(`${label} references invalid session index: ${v}`); + } + } + } + } + + if ('contributors' in event) { + const val = event.contributors; + if (val !== null && !isIndexOrList(val)) { + errors.push(`${label} field 'contributors' must be an index, a list of indices or null.`); + } else if (val !== null) { + for (const v of Array.isArray(val) ? val : [val]) { + if (partyCount !== undefined && v >= partyCount) { + errors.push(`${label} references invalid party index: ${v}`); + } + } + } + } + + if ('button' in event && typeof event.button !== 'string') { + errors.push(`${label} field 'button' must be a string.`); + } + + return { errors, warnings }; +} + +export interface EventParams { + /** Event type token, for example "join" or "blind-transfer". */ + type: string; + /** When the event occurred. */ + time: Date | string; + /** Session index or indices (not for channel-contributors). */ + sessions?: number | number[]; + /** Party index (not for channel-contributors). */ + party?: number; + /** Dialog index (channel-contributors; SHOULD NOT be used otherwise). */ + dialog?: number | number[]; + /** Channel index (channel-contributors only). */ + channel?: number; + /** Party index, indices, or null for a channel with no contributor (channel-contributors only). */ + contributors?: number | number[] | null; + /** DTMF digit or key label (keydown and keyup only). */ + button?: string; + transferee?: number; + transfer_target?: number; + consultation?: number; + target_session?: number; + /** + * Apply the parameter applicability table and throw on an M or X violation + * (default true). SN violations log a warning. + */ + validate?: boolean; + /** Parameters defined by a vCon extension. */ + [key: string]: any; +} + +/** An Event Object (core-05 section 4.3). */ +export class Event { + type: string; + time: string; + sessions?: number | number[]; + party?: number; + dialog?: number | number[]; + channel?: number; + contributors?: number | number[] | null; + button?: string; + transferee?: number; + transfer_target?: number; + consultation?: number; + target_session?: number; + /** Extension parameters. */ + extra: Record; + + constructor(params: EventParams) { + const { validate = true, ...rest } = params; + this.type = rest.type; + this.time = toIso(rest.time) as string; + this.sessions = rest.sessions; + this.party = rest.party; + this.dialog = rest.dialog; + this.channel = rest.channel; + this.contributors = rest.contributors; + this.button = rest.button; + this.transferee = rest.transferee; + this.transfer_target = rest.transfer_target; + this.consultation = rest.consultation; + this.target_session = rest.target_session; + this.extra = {}; + for (const [k, v] of Object.entries(rest)) { + if (!(EVENT_PARAMETERS as readonly string[]).includes(k) && v !== undefined) this.extra[k] = v; + } + if (validate) { + const { errors, warnings } = validateEvent(this.toDict()); + for (const w of warnings) warn(w, 'VconWarning'); + if (errors.length) throw new Error(errors.join('; ')); + } + } + + /** Serialize, omitting parameters that are undefined. */ + toDict(): EventType { + const out: Record = {}; + for (const name of EVENT_PARAMETERS) { + const value = this[name]; + if (value !== undefined) out[name] = value; + } + Object.assign(out, this.extra); + return out as EventType; + } + + static fromDict(data: Record, validate = false): Event { + return new Event({ ...(data as EventParams), validate }); + } +} diff --git a/src/index.ts b/src/index.ts index 5fb9263..0cba0b5 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,23 +1,53 @@ -import { Vcon } from './vcon'; +import { Vcon, AlgorithmNotPermittedError, PERMITTED_JWS_ALGORITHMS, VconOptions, KeyInput, JwsAlgorithm } from './vcon'; import { Attachment } from './attachment'; import { Party, PartyHistory } from './party'; -import { Dialog } from './dialog'; +import { Dialog, DialogParams } from './dialog'; +import { Session, SessionReference, SessionParams, validateSession, SESSION_REFERENCE_TYPES } from './session'; +import { + Event, + EventParams, + validateEvent, + EVENT_PARAMETER_RULES, + CORE_EVENT_TYPES, + RuleCode +} from './event'; +import { validateVconDict, extensionsInUse } from './validation'; +import { + migrate040To050, + MigrationError, + MigrationReport, + MigrationResult, + MigrationOptions, + MigrationStep, + MIGRATION_STEPS, + ReportEntry, + ReportKind +} from './migration'; import { VconData, Attachment as AttachmentType, Party as PartyType, Dialog as DialogType, + Session as SessionType, + SessionReference as SessionReferenceData, + SessionReferenceType, + Event as EventType, + EventType as EventTypeToken, Analysis, Encoding, CivicAddress, PartyHistory as PartyHistoryType, Redacted, Amended, + RedactedString, + RedactedSegment, + JwsSignature, DialogType as DialogTypeEnum, DialogDisposition, SessionId, ContentHash, - VCON_VERSION + VCON_VERSION, + LEGACY_VCON_VERSION } from './types'; export { @@ -27,21 +57,61 @@ export { Party, PartyHistory, Dialog, + Session, + SessionReference, + Event, + // Errors + AlgorithmNotPermittedError, + MigrationError, + // Migration + migrate040To050, + MigrationReport, + MIGRATION_STEPS, + // Validation + validateVconDict, + validateSession, + validateEvent, + extensionsInUse, + EVENT_PARAMETER_RULES, + CORE_EVENT_TYPES, + SESSION_REFERENCE_TYPES, + PERMITTED_JWS_ALGORITHMS, // Types + VconOptions, + KeyInput, + JwsAlgorithm, + DialogParams, + SessionParams, + EventParams, + RuleCode, + MigrationResult, + MigrationOptions, + MigrationStep, + ReportEntry, + ReportKind, VconData, AttachmentType, PartyType, DialogType, + SessionType, + SessionReferenceData, + SessionReferenceType, + EventType, + EventTypeToken, Analysis, Encoding, CivicAddress, PartyHistoryType, Redacted, Amended, + RedactedString, + RedactedSegment, + JwsSignature, DialogTypeEnum, DialogDisposition, SessionId, ContentHash, // Constants - VCON_VERSION + VCON_VERSION, + LEGACY_VCON_VERSION }; diff --git a/src/migration.ts b/src/migration.ts new file mode 100644 index 0000000..44a7a60 --- /dev/null +++ b/src/migration.ts @@ -0,0 +1,1393 @@ +/** + * Migrate a vCon from syntax 0.4.0 to 0.5.0 (draft-ietf-vcon-vcon-core-05, Appendix A.1). + * + * The migration is table driven. MIGRATION_STEPS holds one entry per step + * T1..T15 of the ordered transform table; each step is one function that + * mutates a shared context. If a later edit of Appendix A.1 changes one step, + * only that function (or its table entry) needs to change. + * + * Execution order (the draft gives none; this order is inferred so that every + * `dialog` index stays valid): the steps that read the 0.4.0 `dialog` array + * run before any array is rewritten, and T10 blanks the removed Dialogs in + * place at the end, so the array length and every other index are unchanged. + * + * T13 T15 T1 -> T8 T9 T9b T6 -> T2 T7 T4(+T5) T3 -> T10 T10b T10c -> T11 T12 T14 + * + * T4 runs before T3 so that the Sessions T5 creates for a transfer's original, + * consultation and target calls are known when T3 builds the party_history + * Events: an Event lists every Session of the Dialog it came from (AMB-3). + * + * Nothing is invented silently. Every value the draft does not dictate is + * listed in the MigrationReport (kind "inferred"), every field that had to be + * filled by a fallback is listed (kind "fallback"), and every problem the + * migration could not resolve is listed (kind "unresolved"). In strict mode a + * fallback throws MigrationError instead. + * + * A signed 0.4.0 vCon is migrated as the unsigned payload. The migration never + * signs; the report sets resignRequired. + */ +import { EVENT_PARAMETERS } from './event'; +import { DIALOG_MIME_TYPES, extensionsInUse, validateVconDict } from './validation'; +import { base64UrlDecodeToString, clone, isInt, isPlainObject, parseDateTime, repr, reprList } from './util'; + +export const SOURCE_VERSION = '0.4.0'; +export const TARGET_VERSION = '0.5.0'; + +type Dict = Record; + +/** + * Top-level parameters that exist only in 0.5.0. Input that has one of them is + * already 0.5.0 even when it omits the (optional) `vcon` parameter; migrating + * it again would overwrite its `sessions` and `events`. + */ +const V050_ONLY_KEYS = ['sessions', 'events', 'redacted_from', 'amended_from', 'redacted_strings']; + +/** The vCon cannot be migrated (or, in strict mode, a MUST field has no source). */ +export class MigrationError extends Error { + constructor(message: string) { + super(message); + this.name = 'MigrationError'; + Object.setPrototypeOf(this, MigrationError.prototype); + } +} + +// --------------------------------------------------------------------------- +// Report +// --------------------------------------------------------------------------- + +/** A value the draft does not dictate; a documented default was applied. */ +export const INFERRED = 'inferred'; +/** A MUST field with no source was filled with the documented fallback. */ +export const FALLBACK = 'fallback'; +/** A problem left for a person to resolve. */ +export const UNRESOLVED = 'unresolved'; +/** Informational. */ +export const INFO = 'info'; + +export type ReportKind = 'inferred' | 'fallback' | 'unresolved' | 'info'; + +export interface ReportEntry { + step: string; + kind: ReportKind; + message: string; + /** AMB-n identifier from the implementation spec. */ + code?: string; + details: Dict; +} + +/** What a migration did that the draft did not dictate. */ +export class MigrationReport { + sourceVersion?: string; + targetVersion = TARGET_VERSION; + strict: boolean; + /** True when the input was signed: the signature is dropped and the result is unsigned. */ + resignRequired = false; + entries: ReportEntry[] = []; + /** Original content of every Dialog replaced by `{}`, keyed by its (unchanged) index. */ + removedDialogs: Record = {}; + /** Steps that ran, in order. */ + stepsRun: string[] = []; + + constructor(strict = false) { + this.strict = strict; + } + + add(step: string, kind: ReportKind, message: string, code?: string, details: Dict = {}): void { + const entry: ReportEntry = { step, kind, message, details }; + if (code) entry.code = code; + this.entries.push(entry); + } + + private of(kind: ReportKind): ReportEntry[] { + return this.entries.filter(e => e.kind === kind); + } + + get inferred(): ReportEntry[] { + return this.of(INFERRED); + } + get fallbacks(): ReportEntry[] { + return this.of(FALLBACK); + } + get unresolved(): ReportEntry[] { + return this.of(UNRESOLVED); + } + get notes(): ReportEntry[] { + return this.of(INFO); + } + + toDict(): Dict { + return { + source_version: this.sourceVersion ?? null, + target_version: this.targetVersion, + strict: this.strict, + resign_required: this.resignRequired, + steps_run: [...this.stepsRun], + entries: this.entries.map(e => { + const out: Dict = { step: e.step, kind: e.kind, message: e.message }; + if (e.code) out.code = e.code; + if (Object.keys(e.details).length) out.details = e.details; + return out; + }), + removed_dialogs: Object.fromEntries(Object.entries(this.removedDialogs)) + }; + } + + summary(): string { + return ( + `${this.inferred.length} inferred, ${this.fallbacks.length} fallback, ` + + `${this.unresolved.length} unresolved` + + (this.resignRequired ? '; re-signing required' : '') + ); + } +} + +/** Result of a migration. */ +export interface MigrationResult { + vcon: Dict; + report: MigrationReport; +} + +// --------------------------------------------------------------------------- +// Context and helpers +// --------------------------------------------------------------------------- + +const ok = (v: unknown): boolean => parseDateTime(v) !== undefined; +const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); + +function num(seconds: number): number { + return Math.round(seconds * 1e6) / 1e6; +} + +/** Flat list of int party indices of a 0.4.0 Dialog `parties` value. */ +function plainParties(value: unknown): number[] { + const out: number[] = []; + const items = Array.isArray(value) ? value : value === undefined || value === null ? [] : [value]; + for (const v of items) { + if (Array.isArray(v)) out.push(...v.filter(isInt)); + else if (isInt(v)) out.push(v); + } + return out; +} + +function union(lists: number[][]): number[] { + const seen: number[] = []; + for (const lst of lists) for (const v of lst) if (!seen.includes(v)) seen.push(v); + return seen; +} + +function renameKey(d: Dict, oldKey: string, newKey: string): Dict { + return Object.fromEntries(Object.entries(d).map(([k, v]) => [k === oldKey ? newKey : k, v])); +} + +const SESSION_KEY_ORDER = ['start', 'duration', 'parties', 'originator', 'session_id', 'sessions', 'dialog']; + +function orderSession(sess: Dict): Dict { + return Object.fromEntries(SESSION_KEY_ORDER.filter(k => k in sess).map(k => [k, sess[k]])); +} + +class Context { + out: Dict; + src: Dict; + strict: boolean; + report: MigrationReport; + sessions: Dict[] = []; + events: Dict[] = []; + /** receivers contributed to the Session by each (kept) Dialog index */ + receivers = new Map(); + /** originator value taken from each (kept) Dialog index */ + originators = new Map(); + /** Session indices each Dialog index belongs to */ + dialogSessions = new Map(); + /** recording-set Dialog index -> Session index (T7) */ + rsSession = new Map(); + /** transfer Dialog index -> Session index of its original call (T4) */ + transferSession = new Map(); + roleSessions = new Map(); + emptyPartyIdx?: number; + catchAll?: number; + + constructor(data: Dict, strict: boolean, report: MigrationReport) { + this.out = data; + this.src = clone(data); // refreshed by T13 after unwrapping + this.strict = strict; + this.report = report; + } + + // -- source views --------------------------------------------------- + get dialogs(): any[] { + return Array.isArray(this.src.dialog) ? this.src.dialog : []; + } + + /** Dialog index -> removed type, for transfer and recording-set Dialogs. */ + get removed(): Map { + const m = new Map(); + this.dialogs.forEach((d, i) => { + if (isPlainObject(d) && (d.type === 'transfer' || d.type === 'recording-set')) m.set(i, d.type); + }); + return m; + } + + kept(): number[] { + const rem = this.removed; + const out: number[] = []; + this.dialogs.forEach((d, i) => { + if (!rem.has(i) && isPlainObject(d) && Object.keys(d).length > 0) out.push(i); + }); + return out; + } + + // -- helpers -------------------------------------------------------- + /** Record a fallback for a MUST field, or throw in strict mode. */ + needFallback(step: string, message: string, code?: string, details: Dict = {}): void { + if (this.strict) { + throw new MigrationError(`${step}: ${message} (strict mode: no source for a required field)`); + } + this.report.add(step, FALLBACK, message, code, details); + } + + newSession(session: Dict): number { + this.sessions.push(session); + return this.sessions.length - 1; + } + + /** Index of an empty Party Object, appended once (4.3.9: unknown party). */ + emptyParty(step: string, _role: string): number { + if (this.emptyPartyIdx === undefined) { + if (!Array.isArray(this.out.parties)) this.out.parties = []; + this.out.parties.push({}); + this.emptyPartyIdx = this.out.parties.length - 1; + this.report.add( + step, + INFERRED, + `Appended an empty Party Object at parties[${this.emptyPartyIdx}] to stand for unknown parties.`, + undefined, + { party: this.emptyPartyIdx } + ); + } + return this.emptyPartyIdx; + } + + /** Start of a Dialog, or of a recording-set's earliest recording. */ + dialogStart(idx: unknown): string | undefined { + if (!isInt(idx) || idx < 0 || idx >= this.dialogs.length) return undefined; + const d = this.dialogs[idx]; + if (!isPlainObject(d)) return undefined; + if (ok(d.start)) return d.start; + if (d.type === 'recording-set') { + const starts = (Array.isArray(d.recordings) ? d.recordings : []) + .filter((r: unknown) => isInt(r) && r >= 0 && r < this.dialogs.length && isPlainObject(this.dialogs[r as number])) + .map((r: number) => this.dialogs[r].start) + .filter(ok); + if (starts.length) { + return starts.reduce((a: string, b: string) => (parseDateTime(b)! < parseDateTime(a)! ? b : a)); + } + } + return undefined; + } + + /** + * Derived (start, duration) of a group of Dialogs. + * + * start is the earliest Dialog start. duration runs from that start to the + * latest Dialog end (start plus duration, or start when no duration is + * known), and is only derived when at least one Dialog has a duration. + */ + span(idxs: number[]): [string | undefined, number | undefined] { + const items: Array<[number, number]> = []; + for (const i of idxs) { + if (!isPlainObject(this.dialogs[i])) continue; + const s = parseDateTime(this.dialogs[i].start); + if (s !== undefined) items.push([i, s]); + } + if (!items.length) return [undefined, undefined]; + const [firstI, first] = items.reduce((a, b) => (b[1] < a[1] ? b : a)); + const startStr = this.dialogs[firstI].start as string; + const ends: number[] = []; + let anyDuration = false; + for (const [i, s] of items) { + const dur = this.dialogs[i].duration; + if (isNum(dur)) { + anyDuration = true; + ends.push(s / 1000 + dur); + } else { + ends.push(s / 1000); + } + } + if (!anyDuration) return [startStr, undefined]; + return [startStr, num(Math.max(...ends) - first / 1000)]; + } + + /** Build a Session for a group of kept Dialogs from derived values. */ + makeSession(step: string, idxs: number[], label: string): Dict { + const session: Dict = {}; + const [start, duration] = this.span(idxs); + if (start !== undefined) session.start = start; + if (duration !== undefined) session.duration = duration; + const parties = union(idxs.map(i => this.receivers.get(i) ?? [])); + if (parties.length) session.parties = parties; + const orig = idxs.filter(i => this.originators.has(i)).map(i => this.originators.get(i)!); + if (orig.length) { + const chosen = orig[0]; + const others = [...new Set(orig.slice(1).filter(o => o !== chosen))].sort((a, b) => a - b); + if (others.length) { + this.report.add( + step, + UNRESOLVED, + `${label}: Dialogs name different originators; kept ${chosen}, did not record ${JSON.stringify(others)}.`, + undefined, + { kept: chosen, dropped: others } + ); + } + if (!parties.length || chosen !== parties[0]) session.originator = chosen; + } + session.dialog = [...idxs]; + if (start !== undefined || duration !== undefined) { + this.report.add( + step, + INFERRED, + `${label}: start/duration derived from its Dialogs (earliest start; ` + + 'duration to the latest end when any Dialog has a duration).', + undefined, + { start: start ?? null, duration: duration ?? null } + ); + } + return orderSession(session); + } +} + +// --------------------------------------------------------------------------- +// Steps +// --------------------------------------------------------------------------- + +/** T1: `vcon` "0.4.0" -> "0.5.0". */ +function stepT1Version(ctx: Context): void { + if (!('vcon' in ctx.out)) { + ctx.report.add('T1', INFERRED, "Input had no 'vcon' parameter; set to '0.5.0' (AMB-12: writers emit it).", 'AMB-12'); + } + ctx.out.vcon = TARGET_VERSION; +} + +/** + * T2: add one Session which references all (kept) Dialog Objects. + * + * The removed transfer and recording-set positions are skipped (they become + * `{}`; T10). Receivers (T8, T9, T9b) and the originator (T6) have already + * been collected, so the Session is built in one go. + */ +function stepT2Sessions(ctx: Context): void { + const kept = ctx.kept(); + if (!kept.length) return; + ctx.catchAll = ctx.newSession(ctx.makeSession('T2', kept, 'Session 0 (all Dialogs)')); + for (const i of kept) { + const lst = ctx.dialogSessions.get(i) ?? []; + lst.push(ctx.catchAll); + ctx.dialogSessions.set(i, lst); + } + ctx.report.add('T2', INFO, `Added Session ${ctx.catchAll} referencing ${kept.length} Dialog Object(s).`); +} + +/** + * T3: each Dialog `party_history` entry becomes an Event; `event` is renamed `type`. + * + * The Event's `sessions` references the Session(s) for the Dialog it came + * from and the Event does not reference the Dialog (SHOULD NOT, 4.3.5). + */ +function stepT3PartyHistory(ctx: Context): void { + const dialogs = ctx.out.dialog; + if (!Array.isArray(dialogs)) return; + ctx.dialogs.forEach((srcD, i) => { + if (!isPlainObject(srcD) || !('party_history' in srcD)) return; + if (srcD.type === 'transfer') { + ctx.report.add( + 'T3', + UNRESOLVED, + `dialog[${i}] is a transfer Dialog with party_history; the entries are not migrated ` + + '(A.1 covers party_history on non-transfer Dialogs). Original kept in removed_dialogs.', + undefined, + { dialog: i } + ); + return; + } + let sess: number[]; + if (srcD.type === 'recording-set') { + sess = ctx.rsSession.has(i) ? [ctx.rsSession.get(i)!] : []; + } else { + sess = [...(ctx.dialogSessions.get(i) ?? [])].sort((a, b) => a - b); + } + if (sess.length > 1) { + ctx.report.add( + 'T3', + INFERRED, + `dialog[${i}] belongs to Sessions ${JSON.stringify(sess)}; its party_history Events list all of them ` + + "in 'sessions' (4.3.3: an Event applies only to the Sessions listed).", + 'AMB-3', + { dialog: i, sessions: sess } + ); + } + const history = srcD.party_history; + if (!Array.isArray(history)) { + ctx.report.add('T3', UNRESOLVED, `dialog[${i}] party_history is not a list; dropped.`, undefined, { dialog: i }); + } else { + history.forEach((entry: any, n: number) => { + if (!isPlainObject(entry) || !('event' in entry)) { + ctx.report.add('T3', UNRESOLVED, `dialog[${i}].party_history[${n}] has no 'event'; entry not migrated.`, undefined, { + dialog: i, + entry + }); + return; + } + const ev: Dict = { type: entry.event }; + if (ok(entry.time)) { + ev.time = entry.time; + } else { + // MUST field: Dialog start, then the vCon created_at. + let fb = srcD.start; + let src = 'Dialog start'; + if (!ok(fb)) { + fb = ctx.out.created_at; + src = 'vCon created_at'; + } + if (!ok(fb)) { + throw new MigrationError( + `T3: dialog[${i}].party_history[${n}] has no time, and neither the Dialog start ` + + 'nor the vCon created_at can stand in' + ); + } + ctx.needFallback( + 'T3', + `dialog[${i}].party_history[${n}] has no usable time (${repr(entry.time)}); used the ` + + `${src} (${repr(fb)}) as the Event time.`, + undefined, + { dialog: i, entry: n, original_time: entry.time ?? null, source: src, time: fb } + ); + ev.time = fb; + } + if (sess.length) ev.sessions = sess.length === 1 ? sess[0] : sess; + if (isInt(entry.party)) { + ev.party = entry.party; + } else { + ctx.needFallback( + 'T3', + `dialog[${i}].party_history[${n}] has no party; referenced an empty Party Object.`, + undefined, + { dialog: i } + ); + ev.party = ctx.emptyParty('T3', 'party'); + } + if ((entry.event === 'keydown' || entry.event === 'keyup') && 'button' in entry) { + ev.button = entry.button; + } else if ('button' in entry) { + ctx.report.add( + 'T3', + UNRESOLVED, + `dialog[${i}].party_history[${n}] has 'button' on a '${entry.event}' event ` + + '(only keydown and keyup carry it); button not migrated.', + undefined, + { dialog: i, entry: n, dropped: { button: entry.button } } + ); + } + // Parameters a 0.4.0 extension added to the entry: carried onto the Event + // unless the name is a core Event parameter (which would change its meaning). + const unknown: Dict = {}; + for (const [k, v] of Object.entries(entry)) { + if (!['party', 'time', 'event', 'button'].includes(k)) unknown[k] = v; + } + if (Object.keys(unknown).length) { + const carried: Dict = {}; + const dropped: Dict = {}; + for (const [k, v] of Object.entries(unknown)) { + if ((EVENT_PARAMETERS as readonly string[]).includes(k)) dropped[k] = v; + else carried[k] = v; + } + Object.assign(ev, carried); + ctx.report.add( + 'T3', + UNRESOLVED, + `dialog[${i}].party_history[${n}] had non-core parameter(s) ${reprList(Object.keys(unknown).sort())}; ` + + `carried onto the Event: ${reprList(Object.keys(carried).sort())}, dropped (name clashes with a core Event ` + + `parameter): ${reprList(Object.keys(dropped).sort())}. List the defining extension in 'extensions'.`, + undefined, + { dialog: i, entry: n, carried, dropped } + ); + } + ctx.events.push(ev); + }); + } + if (srcD.type !== 'recording-set' && isPlainObject(dialogs[i])) delete dialogs[i].party_history; + }); +} + +/** + * T4 (with T5): each `transfer` Dialog becomes one or two transfer Events. + * + * `transferor` becomes `party`. `original`, `consultation` and + * `target_dialog` become Session indices (T5): the recording-set's Session, + * otherwise a Session that lists that Dialog. + */ +function stepT4Transfers(ctx: Context): void { + const step = 'T4'; + for (const [k, kind] of ctx.removed) { + if (kind !== 'transfer') continue; + const tr = ctx.dialogs[k]; + + /** T5: Session index for a Dialog reference held by a transfer Dialog. */ + const sessionFor = (ref: unknown, role: string): number | undefined => { + if (ref === undefined || ref === null) return undefined; + if (!isInt(ref) || ref < 0 || ref >= ctx.dialogs.length) { + ctx.report.add(step, UNRESOLVED, `transfer dialog[${k}] ${role}=${repr(ref)} is not a Dialog index.`, undefined, { + dialog: k + }); + return undefined; + } + if (ctx.rsSession.has(ref)) { + ctx.report.add( + 'T5', + INFO, + `transfer dialog[${k}] ${role} -> dialog[${ref}] is a recording-set; using its Session ${ctx.rsSession.get(ref)}.` + ); + return ctx.rsSession.get(ref); + } + const removed = ctx.removed; + if (removed.has(ref)) { + const idx = ctx.newSession({}); + ctx.report.add( + 'T5', + UNRESOLVED, + `transfer dialog[${k}] ${role} -> dialog[${ref}] is itself a removed ${removed.get(ref)} Dialog; ` + + `created placeholder Session ${idx} with no parameters.`, + undefined, + { dialog: k } + ); + return idx; + } + if (ctx.roleSessions.has(ref)) return ctx.roleSessions.get(ref); + const sess = ctx.makeSession('T5', [ref], `Session for transfer ${role} (dialog[${ref}])`); + const idx = ctx.newSession(sess); + ctx.roleSessions.set(ref, idx); + const lst = ctx.dialogSessions.get(ref) ?? []; + lst.push(idx); + ctx.dialogSessions.set(ref, lst); + ctx.report.add( + 'T5', + INFERRED, + `transfer dialog[${k}] ${role} -> created Session ${idx} listing dialog[${ref}] ` + + '(A.1: referenced through a Session Object).', + undefined, + { dialog: k, session: idx } + ); + return idx; + }; + + const placeholder = (role: string, why: string, requiredFallback: boolean): number => { + const idx = ctx.newSession({}); + const msg = `transfer dialog[${k}] has no ${role} (${why}); created placeholder Session ${idx} with no parameters (4.3.1.3).`; + if (requiredFallback) ctx.needFallback(step, msg, undefined, { dialog: k, session: idx }); + else ctx.report.add(step, INFERRED, msg, 'AMB-7', { dialog: k, session: idx }); + return idx; + }; + + // Session of the original call (sessions: M, single index). + const origRef = tr.original; + let sidx = sessionFor(origRef, 'original'); + if (sidx === undefined) { + sidx = placeholder('original', "'sessions' is required on every transfer Event", true); + } + ctx.transferSession.set(k, sidx); + + const partyRef = (key: string, role: string, required: boolean): number | undefined => { + const val = tr[key]; + if (isInt(val)) return val; + if (!required) return undefined; + ctx.needFallback( + step, + `transfer dialog[${k}] has no ${key} (${role}); referenced an empty Party Object (4.3.9).`, + undefined, + { dialog: k } + ); + return ctx.emptyParty(step, role); + }; + + const transferor = partyRef('transferor', 'Transferor, becomes party', true); + const transferee = partyRef('transferee', 'Transferee', true); + + const consRef = tr.consultation; + const targetRef = tr.target_dialog; + const hasCons = consRef !== undefined && consRef !== null; + const hasTarget = targetRef !== undefined && targetRef !== null; + let consSess = hasCons ? sessionFor(consRef, 'consultation') : undefined; + if (hasCons && consSess === undefined) { + consSess = placeholder('usable consultation', 'consultation Dialog index could not be resolved', false); + } + let targetSess = hasTarget ? sessionFor(targetRef, 'target_dialog') : undefined; + const hasTargetParty = isInt(tr.transfer_target); + + // Event types (AMB-7). + const types: string[] = []; + if (hasCons) types.push('consultation-start'); + if (hasTarget || hasTargetParty) types.push(hasCons ? 'consultative-transfer' : 'blind-transfer'); + else types.push('transfer-abandoned'); + ctx.report.add( + step, + INFERRED, + `transfer dialog[${k}] mapped to Event type(s) ${reprList(types)} ` + + '(consultation present -> consultation-start + consultative-transfer; otherwise blind-transfer; ' + + 'no target_dialog and no transfer_target -> transfer-abandoned).', + 'AMB-7', + { dialog: k, types } + ); + if (types.includes('blind-transfer') || types.includes('consultative-transfer')) { + if (targetSess === undefined) { + targetSess = placeholder( + 'target_dialog', + 'the target call was not captured; 4.3.1.3 uses a placeholder Session in that case', + false + ); + } + } + + const eventTime = (which: 'consult' | 'transfer'): string => { + const own = tr.start; + if (ok(own)) return own; + const cands: Array<[string | undefined, string]> = []; + if (which === 'consult') { + cands.push([ctx.dialogStart(consRef), `start of consultation dialog[${consRef}]`]); + } else { + cands.push([ctx.dialogStart(targetRef), `start of target dialog[${targetRef}]`]); + if (hasCons) { + const cd = isInt(consRef) && consRef >= 0 && consRef < ctx.dialogs.length ? ctx.dialogs[consRef] : undefined; + const cs = parseDateTime(ctx.dialogStart(consRef)); + const dur = isPlainObject(cd) ? cd.duration : undefined; + if (cs !== undefined && isNum(dur)) { + const end = new Date(cs + dur * 1000).toISOString(); + cands.push([end, `end of consultation dialog[${consRef}] (start + duration)`]); + } + cands.push([ctx.dialogStart(consRef), `start of consultation dialog[${consRef}]`]); + } + } + for (const [value, src] of cands) { + if (value && ok(value)) { + ctx.report.add( + step, + INFERRED, + `transfer dialog[${k}] has no start; Event time taken from the ${src}, ` + + "not from the transfer Dialog's own start.", + 'AMB-7', + { dialog: k, source: src, time: value } + ); + return value; + } + } + const created = ctx.out.created_at; + if (ok(created)) { + ctx.needFallback( + step, + `transfer dialog[${k}] has no start and no other time source; used the vCon created_at ` + + `(${repr(created)}) as the Event time.`, + 'AMB-7', + { dialog: k } + ); + return created; + } + throw new MigrationError(`${step}: transfer dialog[${k}] has no start and the vCon has no created_at; no time can be sourced`); + }; + + for (const t of types) { + const ev: Dict = { type: t }; + ev.time = eventTime(t === 'consultation-start' ? 'consult' : 'transfer'); + ev.sessions = sidx; + ev.party = transferor; + ev.transferee = transferee; + const needTarget = t !== 'transfer-abandoned'; + const tt = partyRef('transfer_target', 'Transfer Target', needTarget); + if (tt !== undefined) ev.transfer_target = tt; + if (t === 'consultation-start' || t === 'consultative-transfer') ev.consultation = consSess; + else if (t === 'transfer-abandoned' && consSess !== undefined) ev.consultation = consSess; + if (t === 'blind-transfer' || t === 'consultative-transfer') ev.target_session = targetSess; + ctx.events.push(ev); + } + const known = [ + 'type', 'start', 'transferee', 'transferor', 'transfer_target', 'original', 'consultation', + 'target_dialog', 'parties', 'party_history' + ]; + const extra = Object.keys(tr).filter(key => !known.includes(key)).sort(); + const hasParties = Array.isArray(tr.parties) ? tr.parties.length > 0 : !!tr.parties; + if (extra.length || hasParties) { + const names = hasParties ? [...extra, 'parties'] : extra; + const dropped: Dict = {}; + for (const f of names) dropped[f] = tr[f]; + ctx.report.add( + step, + UNRESOLVED, + `transfer dialog[${k}] had parameters with no Event equivalent (${reprList(names)}); not migrated. ` + + 'Original kept in report.removedDialogs.', + undefined, + { dialog: k, dropped } + ); + } + } +} + +/** T6: `originator` moves from the Dialog to the Session (only when not the first party). */ +function stepT6Originator(ctx: Context): void { + const dialogs = ctx.out.dialog; + if (!Array.isArray(dialogs)) return; + for (const i of ctx.kept()) { + const d = dialogs[i]; + if (isPlainObject(d) && 'originator' in d) { + const val = d.originator; + delete d.originator; + if (isInt(val)) ctx.originators.set(i, val); + else { + ctx.report.add('T6', UNRESOLVED, `dialog[${i}] originator ${repr(val)} is not a party index; dropped.`, undefined, { + dialog: i + }); + } + } + } +} + +/** + * T7: each `recording-set` Dialog becomes a Session listing its recordings. + * + * The recording-set's own start, duration, parties, session_id and originator + * move to the Session (A.1 is silent: AMB-4). `recording_set` is removed from + * each recording. + * + * Membership is the union of the set's `recordings` list and the recordings + * whose `recording_set` points at it (core-04 made `recordings` MUST and + * `recording_set` SHOULD, so stored data can carry either side only). A + * recording-set listed in another recording-set's `recordings` becomes a + * `child` Session_Reference of that set's Session. Every Session index is + * allocated before any is filled, so a nested set can point forward. + */ +function stepT7RecordingSets(ctx: Context): void { + const dialogs = ctx.out.dialog; + const removed = ctx.removed; + const rsIds = [...removed].filter(([, kind]) => kind === 'recording-set').map(([k]) => k); + for (const k of rsIds) ctx.rsSession.set(k, ctx.newSession({})); + + // recording_set back-references from kept Dialogs. + const back = new Map(); + for (const i of ctx.kept()) { + const ref = ctx.dialogs[i].recording_set; + if (ref === undefined || ref === null) continue; + if (isInt(ref) && ctx.rsSession.has(ref)) { + const lst = back.get(ref) ?? []; + lst.push(i); + back.set(ref, lst); + } else { + ctx.report.add( + 'T7', + UNRESOLVED, + `dialog[${i}] recording_set=${repr(ref)} does not reference a recording-set Dialog; ` + + 'parameter removed, no Session membership derived from it.', + undefined, + { dialog: i, recording_set: ref } + ); + } + } + + for (const k of rsIds) { + const rs = ctx.dialogs[k]; + const sidx = ctx.rsSession.get(k)!; + const recsRaw = rs.recordings; + const recs: number[] = []; + const children: number[] = []; + if (Array.isArray(recsRaw)) { + for (const r of recsRaw) { + if (isInt(r) && ctx.rsSession.has(r) && r !== k) { + const c = ctx.rsSession.get(r)!; + if (!children.includes(c)) children.push(c); + } else if ( + isInt(r) && r >= 0 && r < ctx.dialogs.length && !removed.has(r) && + isPlainObject(ctx.dialogs[r]) && Object.keys(ctx.dialogs[r]).length > 0 + ) { + if (!recs.includes(r)) recs.push(r); + } else { + ctx.report.add( + 'T7', + UNRESOLVED, + `recording-set dialog[${k}] lists recordings entry ${repr(r)}, which is not a kept Dialog or another ` + + 'recording-set; left out of the Session.', + undefined, + { dialog: k, entry: r } + ); + } + } + } else { + ctx.report.add('T7', UNRESOLVED, `recording-set dialog[${k}] has no recordings list.`, undefined, { dialog: k }); + } + const addedBack = (back.get(k) ?? []).filter(i => !recs.includes(i)); + if (addedBack.length) { + recs.push(...addedBack); + ctx.report.add( + 'T7', + INFERRED, + `dialog(s) ${JSON.stringify(addedBack)} name recording-set dialog[${k}] in recording_set but are not in its ` + + `recordings list; added to Session ${sidx}.`, + undefined, + { dialog: k, added: addedBack, session: sidx } + ); + } + const sess: Dict = {}; + const [dStart, dDur] = recs.length ? ctx.span(recs) : [undefined, undefined]; + if (ok(rs.start)) sess.start = rs.start; + else if (dStart !== undefined) sess.start = dStart; + if (isNum(rs.duration)) sess.duration = rs.duration; + else if (dDur !== undefined) sess.duration = dDur; + const rsParties = plainParties(rs.parties); + const parties = rsParties.length ? rsParties : union(recs.map(r => ctx.receivers.get(r) ?? [])); + if (parties.length) sess.parties = parties; + const orig = rs.originator; + if (isInt(orig) && (!parties.length || orig !== parties[0])) { + sess.originator = orig; + } else if (orig !== undefined && orig !== null && !isInt(orig)) { + ctx.report.add('T7', UNRESOLVED, `recording-set dialog[${k}] originator ${repr(orig)} is not a party index; dropped.`, undefined, { + dialog: k + }); + } + const sid = rs.session_id; + if (isPlainObject(sid)) { + sess.session_id = sid; + } else if (Array.isArray(sid) && sid.length === 1 && isPlainObject(sid[0])) { + sess.session_id = sid[0]; + } else if (sid !== undefined && sid !== null) { + ctx.report.add( + 'T7', + UNRESOLVED, + `recording-set dialog[${k}] session_id is not a single SessionId Object; Session.session_id not set.`, + 'AMB-4', + { dialog: k, session_id: sid } + ); + } + if (children.length) { + sess.sessions = children.map(c => ({ session: c, type: 'child' })); + ctx.report.add( + 'T7', + INFERRED, + `recording-set dialog[${k}] lists other recording-set(s); Session ${sidx} references their ` + + `Session(s) ${JSON.stringify(children)} as 'child'.`, + 'AMB-1', + { dialog: k, session: sidx, children } + ); + } + if (recs.length) sess.dialog = recs; + ctx.sessions[sidx] = orderSession(sess); + for (const r of recs) { + const lst = ctx.dialogSessions.get(r) ?? []; + lst.push(sidx); + ctx.dialogSessions.set(r, lst); + } + const fieldsMoved = ['start', 'duration', 'parties', 'session_id', 'originator'].filter(f => f in rs); + ctx.report.add( + 'T7', + INFERRED, + `recording-set dialog[${k}] -> Session ${sidx}; its ${reprList(fieldsMoved)} moved to the Session ` + + '(A.1 silent about them); Session start/duration/parties fall back to values derived from the recordings when absent.', + 'AMB-4', + { dialog: k, session: sidx } + ); + const known = ['type', 'recordings', 'start', 'duration', 'parties', 'session_id', 'originator', 'party_history']; + const extra = Object.keys(rs).filter(key => !known.includes(key)).sort(); + if (extra.length) { + const dropped: Dict = {}; + for (const f of extra) dropped[f] = rs[f]; + ctx.report.add( + 'T7', + UNRESOLVED, + `recording-set dialog[${k}] had parameter(s) ${reprList(extra)} with no Session equivalent; not migrated. ` + + 'Original kept in report.removedDialogs.', + undefined, + { dialog: k, dropped } + ); + } + if (ctx.catchAll !== undefined && recs.length) { + ctx.report.add( + 'T7', + UNRESOLVED, + `Session ${sidx} (recording-set dialog[${k}]) overlaps Session ${ctx.catchAll}, which also lists its ` + + 'recordings; A.1 does not say whether to relate them, so no Session_Reference was added.', + 'AMB-1', + { session: sidx, catch_all: ctx.catchAll } + ); + } + } + // recording_set has been consumed above; recordings is only legal on recording-sets. + if (Array.isArray(dialogs)) { + for (const i of ctx.kept()) { + delete dialogs[i].recording_set; + if ('recordings' in dialogs[i]) { + const val = dialogs[i].recordings; + delete dialogs[i].recordings; + ctx.report.add( + 'T7', + UNRESOLVED, + `dialog[${i}] (${repr(ctx.dialogs[i].type)}) had a recordings parameter, which only a ` + + 'recording-set may carry; removed.', + undefined, + { dialog: i, recordings: val } + ); + } + } + } +} + +function firstSlotIsNull(parties: unknown): boolean { + return Array.isArray(parties) && parties.length > 0 && parties[0] === null; +} + +/** + * The first party slot of a text/incomplete Dialog is null: its sender is unknown. + * + * The next party in the list is a receiver, so promoting it would invent a + * sender. An empty Party Object stands in (4.2.4: "If the originator is not + * known, an empty Party Object ... may be used"), and it becomes the Session + * originator so the first receiver is not implied to be the originator. + */ +function unknownFirstParty(ctx: Context, step: string, i: number, kind: string, role: string): number { + const e = ctx.emptyParty(step, role); + ctx.originators.set(i, e); + ctx.report.add( + step, + UNRESOLVED, + `${kind} dialog[${i}] has null as its first party, so its ${role} is unknown; an empty Party ` + + `Object (parties[${e}]) stands in rather than promoting a receiver.`, + undefined, + { dialog: i, party: e } + ); + return e; +} + +/** T8: a `text` Dialog's `parties` reduce to the sender; all parties go to the Session. */ +function stepT8TextParties(ctx: Context): void { + const dialogs = ctx.out.dialog; + if (!Array.isArray(dialogs)) return; + for (const i of ctx.kept()) { + if (ctx.dialogs[i].type !== 'text') continue; + const p = plainParties(ctx.dialogs[i].parties); + if (!p.length) { + ctx.report.add('T8', UNRESOLVED, `text dialog[${i}] has no parties; sender and receivers unknown.`, undefined, { dialog: i }); + continue; + } + const orig = ctx.dialogs[i].originator; + let sender: number; + if (isInt(orig)) sender = orig; + else if (firstSlotIsNull(ctx.dialogs[i].parties)) sender = unknownFirstParty(ctx, 'T8', i, 'text', 'sender'); + else sender = p[0]; + dialogs[i].parties = [sender]; + ctx.receivers.set(i, p.includes(sender) ? p : [sender, ...p]); + } +} + +/** T9: an `incomplete` Dialog's `parties` reduce to the originator (or first party). */ +function stepT9IncompleteParties(ctx: Context): void { + const dialogs = ctx.out.dialog; + if (!Array.isArray(dialogs)) return; + for (const i of ctx.kept()) { + if (ctx.dialogs[i].type !== 'incomplete') continue; + const p = plainParties(ctx.dialogs[i].parties); + if (!p.length) continue; + const orig = ctx.dialogs[i].originator; + let who: number; + if (isInt(orig)) who = orig; + else if (firstSlotIsNull(ctx.dialogs[i].parties)) who = unknownFirstParty(ctx, 'T9', i, 'incomplete', 'originator'); + else who = p[0]; + dialogs[i].parties = [who]; + ctx.receivers.set(i, p.includes(who) ? p : [who, ...p]); + } +} + +/** T9b: other Dialogs keep `parties` (contributors); the Session gets the union (AMB-6). */ +function stepT9bRecordingParties(ctx: Context): void { + const idxs: number[] = []; + for (const i of ctx.kept()) { + if (ctx.dialogs[i].type === 'text' || ctx.dialogs[i].type === 'incomplete') continue; + const p = plainParties(ctx.dialogs[i].parties); + if (p.length) { + ctx.receivers.set(i, p); + idxs.push(i); + } + } + if (idxs.length) { + ctx.report.add( + 'T9b', + INFERRED, + `Dialog(s) ${JSON.stringify(idxs)} (recording or other type): parties left as the contributors; ` + + 'the Session parties are the union of the contributors across its Dialogs (A.1 gives no rule).', + 'AMB-6', + { dialogs: idxs } + ); + } + const texts = ctx.kept().filter(i => ctx.dialogs[i].type === 'text'); + if (texts.length) { + const sets = new Set(texts.map(i => JSON.stringify([...(ctx.receivers.get(i) ?? [])].sort((a, b) => a - b)))); + if (sets.size > 1) { + ctx.report.add( + 'T8', + UNRESOLVED, + `text Dialogs ${JSON.stringify(texts)} have different receiver sets; they were put in one Session whose parties ` + + 'are the union. 4.5.4 prescribes a parent Session with a child Session per receiver set; that ' + + 'split was not made.', + 'AMB-5', + { dialogs: texts } + ); + } + if ([...sets].some(s => (JSON.parse(s) as number[]).length > 2)) { + ctx.report.add( + 'T8', + UNRESOLVED, + '0.4.0 parties do not distinguish To, Cc and Bcc, so Bcc recipients cannot be identified or excluded.', + 'AMB-5', + { dialogs: texts } + ); + } + } +} + +/** T10: each removed Dialog is replaced in place by `{}` so no index moves. */ +function stepT10BlankRemoved(ctx: Context): void { + const dialogs = ctx.out.dialog; + if (!Array.isArray(dialogs)) return; + for (const [k, kind] of ctx.removed) { + ctx.report.removedDialogs[k] = clone(ctx.dialogs[k]); + dialogs[k] = {}; + ctx.report.add('T10', INFO, `dialog[${k}] (${kind}) replaced by an empty Dialog Object; index ${k} unchanged.`, undefined, { + dialog: k + }); + } + if (dialogs.length !== ctx.dialogs.length) { + throw new MigrationError('T10: dialog array length changed; indices would break'); + } +} + +function mergeIndex(existing: unknown, add: number[]): number | number[] { + const cur = existing === undefined || existing === null ? [] : Array.isArray(existing) ? existing : [existing]; + const merged: number[] = [...cur]; + for (const n of add) if (!merged.includes(n)) merged.push(n); + return merged.length === 1 ? merged[0] : merged; +} + +/** + * AMB-2: re-point analysis and attachment references to removed Dialogs. + * + * Recording-set: Analysis.dialog is expanded to the recordings and `sessions` + * gets the recording-set's Session; an Attachment (single `dialog` index) gets + * `session` instead. Transfer: the reference moves to the Session of the + * transfer's original call. Nothing is left pointing at a `{}` Dialog. + */ +function stepT10bRetarget(ctx: Context): void { + const removed = ctx.removed; + if (!removed.size) return; + + /** (replacement dialog indices, session index) for a removed Dialog. */ + const targets = (e: number): [number[], number | undefined] => { + if (removed.get(e) === 'recording-set') { + const sidx = ctx.rsSession.get(e); + const recs = sidx !== undefined ? ctx.sessions[sidx].dialog ?? [] : []; + return [[...recs], sidx]; + } + return [[], ctx.transferSession.get(e)]; + }; + + (Array.isArray(ctx.out.analysis) ? ctx.out.analysis : []).forEach((an: any, n: number) => { + if (!isPlainObject(an) || !('dialog' in an)) return; + const old = an.dialog; + const items = Array.isArray(old) ? old : [old]; + if (!items.some((x: unknown) => isInt(x) && removed.has(x))) return; + const newDialogs: number[] = []; + const sessAdd: number[] = []; + for (const x of items) { + if (isInt(x) && removed.has(x)) { + const [reps, sidx] = targets(x); + for (const r of reps) if (!newDialogs.includes(r)) newDialogs.push(r); + if (sidx !== undefined) sessAdd.push(sidx); + } else if (!newDialogs.includes(x)) { + newDialogs.push(x); + } + } + if (newDialogs.length) an.dialog = newDialogs.length === 1 && !Array.isArray(old) ? newDialogs[0] : newDialogs; + else delete an.dialog; + if (sessAdd.length) an.sessions = mergeIndex(an.sessions, sessAdd); + ctx.report.add( + 'T10b', + INFERRED, + `analysis[${n}].dialog ${JSON.stringify(old)} pointed at a removed Dialog; now dialog=${JSON.stringify(an.dialog ?? null)}, ` + + `sessions=${JSON.stringify(an.sessions ?? null)}.`, + 'AMB-2', + { analysis: n } + ); + }); + (Array.isArray(ctx.out.attachments) ? ctx.out.attachments : []).forEach((att: any, n: number) => { + if (!isPlainObject(att) || !(isInt(att.dialog) && removed.has(att.dialog))) return; + const e = att.dialog as number; + const [, sidx] = targets(e); + delete att.dialog; + if (sidx !== undefined) { + att.session = mergeIndex(att.session, [sidx]); + ctx.report.add( + 'T10b', + INFERRED, + `attachments[${n}].dialog=${e} pointed at a removed Dialog; replaced by session=${JSON.stringify(att.session)}.`, + 'AMB-2', + { attachment: n } + ); + } else { + ctx.report.add( + 'T10b', + UNRESOLVED, + `attachments[${n}].dialog=${e} pointed at a removed Dialog with no Session to re-point to; ` + + 'the attachment now has neither dialog nor session.', + 'AMB-2', + { attachment: n } + ); + } + }); +} + +/** + * Scope an attachment that has neither `dialog` nor `session`. + * + * Core-04 required `dialog`, but older writers omitted it, so stored data has + * such attachments. Core-05 needs one of `dialog` or `session` (4.6.4). Only + * when the result has exactly one Session is the scope unambiguous (that + * Session is the whole conversation); it is then set and reported. Otherwise + * nothing is invented and the gap is reported. + */ +function stepT10cUnscopedAttachments(ctx: Context): void { + (Array.isArray(ctx.out.attachments) ? ctx.out.attachments : []).forEach((att: any, n: number) => { + if (!isPlainObject(att) || 'dialog' in att || 'session' in att) return; + if (ctx.sessions.length === 1) { + att.session = 0; + ctx.report.add('T10c', INFERRED, `attachments[${n}] had neither dialog nor session; scoped to the only Session (session=0).`, undefined, { + attachment: n, + purpose: att.purpose ?? null + }); + } else { + ctx.report.add( + 'T10c', + UNRESOLVED, + `attachments[${n}] has neither dialog nor session and the vCon has ${ctx.sessions.length} ` + + 'Sessions, so its scope cannot be chosen; set dialog or session by hand.', + undefined, + { attachment: n, purpose: att.purpose ?? null } + ); + } + }); +} + +/** + * T13: a signed vCon is migrated as its unsigned payload; it must be signed again. + * + * `alg: "none"` is no longer permitted, so such a vCon is flagged explicitly. + * The migration never signs. + */ +function stepT13UnwrapSigned(ctx: Context): void { + const out = ctx.out; + if ('ciphertext' in out && ('recipients' in out || 'protected' in out)) { + throw new MigrationError('T13: the input is an encrypted (JWE) vCon; decrypt it before migrating'); + } + if ('payload' in out && 'signatures' in out) { + let payload: any; + try { + payload = JSON.parse(base64UrlDecodeToString(out.payload)); + } catch (e) { + throw new MigrationError(`T13: could not decode the signed vCon payload: ${e instanceof Error ? e.message : String(e)}`); + } + if (!isPlainObject(payload)) throw new MigrationError('T13: the signed vCon payload is not a JSON object'); + const algs: unknown[] = []; + for (const sig of Array.isArray(out.signatures) ? out.signatures : []) { + try { + if (sig.protected) algs.push(JSON.parse(base64UrlDecodeToString(sig.protected)).alg); + if (isPlainObject(sig.header) && 'alg' in sig.header) algs.push(sig.header.alg); + } catch { + continue; + } + } + ctx.out = payload; + ctx.report.resignRequired = true; + ctx.report.add( + 'T13', + UNRESOLVED, + 'The input was signed. It was migrated as the unsigned payload; the signature was dropped. ' + + 'Re-signing is required, and signing changes updated_at (4.1.6).' + ); + if (algs.some(a => typeof a === 'string' && a.toLowerCase() === 'none')) { + ctx.report.add( + 'T13', + UNRESOLVED, + "A signature used alg 'none', which 0.5.0 forbids; sign again with a permitted algorithm." + ); + } + } + ctx.src = clone(ctx.out); + ctx.report.sourceVersion = ctx.out.vcon; +} + +/** T14: `extensions` must list every extension in use (MUST, was SHOULD). */ +function stepT14Extensions(ctx: Context): void { + const { names, unnamed } = extensionsInUse(ctx.out); + const listed: string[] = Array.isArray(ctx.out.extensions) ? [...ctx.out.extensions] : []; + const added: string[] = []; + for (const name of [...names].sort()) { + if (!listed.includes(name)) { + listed.push(name); + added.push(name); + } + } + for (const name of Array.isArray(ctx.out.critical) ? ctx.out.critical : []) { + if (typeof name === 'string' && !listed.includes(name)) { + listed.push(name); + added.push(name); + } + } + if (added.length) { + ctx.out.extensions = listed; + ctx.report.add('T14', INFERRED, `Added extension name(s) ${reprList(added)} to extensions.`, undefined, { added }); + } + if (unnamed.length && !listed.length) { + ctx.report.add( + 'T14', + UNRESOLVED, + 'Values outside the core vocabulary are in use but their defining extension cannot be identified: ' + + unnamed.join('; ') + + '. extensions was not changed.', + undefined, + { uses: unnamed } + ); + } +} + +/** T15: duplicate header parameters in signed or encrypted forms are tolerated on read. */ +function stepT15DuplicateHeaders(ctx: Context): void { + if (ctx.report.resignRequired) { + ctx.report.add( + 'T15', + INFO, + 'Header parameters repeated across JWS headers are not checked or rejected on read; ' + + 'writers must not emit duplicates in 0.5.0.' + ); + } +} + +/** T11 and T12 are renames at the top level; the helper keeps key order. */ +function renameTop(ctx: Context, oldKey: string, newKey: string, step: string): void { + if (oldKey in ctx.out) { + ctx.out = renameKey(ctx.out, oldKey, newKey); + ctx.report.add(step, INFO, `Renamed '${oldKey}' to '${newKey}'.`); + } +} + +/** T11: `redacted` -> `redacted_from` (same fields). */ +const stepT11 = (ctx: Context): void => renameTop(ctx, 'redacted', 'redacted_from', 'T11'); +/** T12: `amended` -> `amended_from` (same fields). */ +const stepT12 = (ctx: Context): void => renameTop(ctx, 'amended', 'amended_from', 'T12'); + +export interface MigrationStep { + id: string; + title: string; + /** Where the draft says it. */ + source: string; + func: (ctx: Context) => void; +} + +/** One entry per step of the ordered transform table (Appendix A.1), in execution order. */ +export const MIGRATION_STEPS: MigrationStep[] = [ + { id: 'T13', title: 'Signed input: migrate the payload, require re-signing', source: 'A.1 bullet 11; 6.2.2', func: stepT13UnwrapSigned }, + { id: 'T15', title: 'Duplicate header parameters tolerated on read', source: 'A.1 bullet 13', func: stepT15DuplicateHeaders }, + { id: 'T1', title: 'vcon 0.4.0 -> 0.5.0', source: 'A.1 bullet 1', func: stepT1Version }, + { id: 'T8', title: 'text Dialog parties -> sender; all parties to Session', source: 'A.1 bullet 6', func: stepT8TextParties }, + { id: 'T9', title: 'incomplete Dialog parties -> originator/first', source: 'A.1 bullet 6', func: stepT9IncompleteParties }, + { id: 'T9b', title: 'other Dialog parties kept; union to Session', source: '4.5.4 (A.1 silent)', func: stepT9bRecordingParties }, + { id: 'T6', title: 'Dialog originator -> Session originator', source: 'A.1 bullet 5', func: stepT6Originator }, + { id: 'T2', title: 'Add a Session referencing all Dialogs', source: 'A.1 bullet 2', func: stepT2Sessions }, + { id: 'T7', title: 'recording-set Dialog -> Session', source: 'A.1 bullet 9', func: stepT7RecordingSets }, + { id: 'T4', title: 'transfer Dialog -> transfer Events (with T5 Session references)', source: 'A.1 bullet 4', func: stepT4Transfers }, + { id: 'T3', title: 'party_history -> Events', source: 'A.1 bullet 3', func: stepT3PartyHistory }, + { id: 'T10', title: 'Removed Dialogs -> {} in place', source: 'A.1 bullet 10; 4.5.1', func: stepT10BlankRemoved }, + { id: 'T10b', title: 'Re-point analysis/attachment references to removed Dialogs', source: 'AMB-2', func: stepT10bRetarget }, + { id: 'T10c', title: 'Scope unscoped attachments to the only Session', source: '4.6.4 (A.1 silent)', func: stepT10cUnscopedAttachments }, + { id: 'T11', title: 'redacted -> redacted_from', source: 'A.1 bullet 7', func: stepT11 }, + { id: 'T12', title: 'amended -> amended_from', source: 'A.1 bullet 8', func: stepT12 }, + { id: 'T14', title: 'extensions lists every extension in use', source: 'A.1 bullet 12; 4.1.3', func: stepT14Extensions } +]; + +export interface MigrationOptions { + /** Throw MigrationError instead of using a fallback for a MUST field with no source. */ + strict?: boolean; +} + +/** + * Migrate a 0.4.0 vCon object (or JSON string) to 0.5.0. + * + * A signed vCon (JWS general form) is migrated as its unsigned payload. The + * input is not modified. The result carries the 0.5.0 object and the report + * listing every inferred value, fallback and unresolved item. + * + * @throws MigrationError the input is not a 0.4.0 vCon, is encrypted, or (strict) + * a required field has no source. + */ +export function migrate040To050(vcon: unknown, options: MigrationOptions = {}): MigrationResult { + const strict = options.strict ?? false; + let input = vcon; + if (typeof input === 'string') { + try { + input = JSON.parse(input); + } catch (e) { + throw new MigrationError(`input is not valid JSON: ${e instanceof Error ? e.message : String(e)}`); + } + } + if (!isPlainObject(input)) throw new MigrationError('input must be a vCon object or JSON string'); + + const data = clone(input); + const report = new MigrationReport(strict); + const ctx = new Context(data, strict, report); + + const version = data.vcon; + if (version !== undefined && version !== null && version !== SOURCE_VERSION && !('payload' in data && 'signatures' in data)) { + throw new MigrationError(`cannot migrate: input vcon is ${repr(version)}, expected ${repr(SOURCE_VERSION)}`); + } + for (const step of MIGRATION_STEPS) { + report.stepsRun.push(step.id); + step.func(ctx); + if (step.id === 'T13') { + const v = ctx.out.vcon; + if (v !== undefined && v !== null && v !== SOURCE_VERSION) { + throw new MigrationError(`cannot migrate: input vcon is ${repr(v)}, expected ${repr(SOURCE_VERSION)}`); + } + if (v === undefined || v === null) { + const markers = V050_ONLY_KEYS.filter(k => k in ctx.out).sort(); + if (markers.length) { + throw new MigrationError( + `cannot migrate: input has no 'vcon' parameter but has 0.5.0-only parameter(s) ${reprList(markers)}; ` + + 'it is already 0.5.0 (vcon is optional there)' + ); + } + report.add('T13', INFO, "Input has no 'vcon' parameter; treated as 0.4.0."); + } + } + } + + const out = ctx.out; + if (ctx.sessions.length) out.sessions = ctx.sessions; + if (ctx.events.length) out.events = ctx.events; + + // Lawful basis attachments keep their 0.4.0 scope (dialog). 0.5.0 scopes them with + // session plus party; adding a Session reference would be inventing a scope. + (Array.isArray(out.attachments) ? out.attachments : []).forEach((att: any, n: number) => { + if (isPlainObject(att) && att.purpose === 'lawful_basis' && !('session' in att)) { + report.add( + 'post', + INFO, + `attachments[${n}] is a lawful_basis attachment scoped by dialog only; it was left as is. ` + + "0.5.0 scopes a lawful basis to Sessions with 'session' (plus 'party'); add it if it covers the Session.", + undefined, + { attachment: n } + ); + } + }); + + // Post-check: the result must satisfy the core-05 rules; anything left is reported. + const { errors } = validateVconDict(out, DIALOG_MIME_TYPES); + for (const err of errors) report.add('post', UNRESOLVED, `Result does not validate: ${err}`); + return { vcon: out, report }; +} diff --git a/src/party.ts b/src/party.ts index 9b33e1e..3e12edc 100644 --- a/src/party.ts +++ b/src/party.ts @@ -1,4 +1,6 @@ import { Party as PartyType, CivicAddress, PartyHistory as PartyHistoryType } from './types'; +import { Event } from './event'; +import { warn } from './util'; /** * Party class representing a conversation participant. @@ -74,8 +76,11 @@ export class Party implements PartyType { } /** - * PartyHistory class for tracking party state changes within a dialog. - * Compliant with IETF draft-ietf-vcon-vcon-core + * PartyHistory class: the 0.4.0 party history entry of a Dialog. + * + * @deprecated core-05 removed `party_history` from the Dialog. A party history + * entry is an Event Object whose `sessions` lists the Session(s) it applies to. + * Constructing a PartyHistory warns; convert it with toEvent(). */ export class PartyHistory implements PartyHistoryType { /** Valid party history events per vcon-core Section 4.3.11.1 */ @@ -96,6 +101,7 @@ export class PartyHistory implements PartyHistoryType { readonly button?: string; constructor(party: number, event: string, time: Date | string, button?: string) { + warn('PartyHistory is deprecated: core-05 has no Dialog party_history; use an Event (PartyHistory.toEvent).'); this.party = party; this.event = event; this.time = time; @@ -112,7 +118,7 @@ export class PartyHistory implements PartyHistoryType { } /** - * Convert to plain object with ISO timestamp + * Convert to plain object with ISO timestamp (the 0.4.0 shape) */ toDict(): PartyHistoryType { const result: PartyHistoryType = { @@ -126,6 +132,20 @@ export class PartyHistory implements PartyHistoryType { return result; } + /** + * Convert to a core-05 Event. `sessions` is the Session index or indices the + * entry applies to (the Sessions that list the Dialog it came from). + */ + toEvent(sessions: number | number[]): Event { + return new Event({ + type: this.event, + time: this.time, + sessions, + party: this.party, + ...(this.button !== undefined ? { button: this.button } : {}) + }); + } + /** * Validate the party history event */ diff --git a/src/session.ts b/src/session.ts new file mode 100644 index 0000000..28aa7dd --- /dev/null +++ b/src/session.ts @@ -0,0 +1,202 @@ +/** + * Session Object and Session_Reference Object (core-05 sections 4.2 and 4.2.8). + * + * A Session groups the Dialog and Event Objects of one conversation (or part of + * one) and records its receivers. A Session Object with no parameters is allowed. + */ +import { SessionId, SessionReference as SessionReferenceType, Session as SessionType } from './types'; +import { isIndex, isPlainObject, parseDateTime, toIso } from './util'; + +/** Session_Reference `type` tokens defined by core-05 (4.2.8.2). Extension values are also allowed. */ +export const SESSION_REFERENCE_TYPES = ['child', 'peer', 'precursor', 'breakout']; + +export const SESSION_PARAMETERS = [ + 'start', + 'duration', + 'parties', + 'originator', + 'session_id', + 'sessions', + 'dialog' +] as const; + +export class SessionReference implements SessionReferenceType { + session: number; + type: string; + description?: string; + + constructor(session: number, type: string, description?: string) { + if (!isIndex(session)) { + throw new Error("Session_Reference 'session' must be a non-negative integer"); + } + if (typeof type !== 'string' || !type) { + throw new Error("Session_Reference 'type' is required"); + } + this.session = session; + this.type = type; + this.description = description; + } + + toDict(): SessionReferenceType { + const out: SessionReferenceType = { session: this.session, type: this.type }; + if (this.description !== undefined) out.description = this.description; + return out; + } +} + +export interface SessionParams { + /** Session start. SHOULD be present. */ + start?: Date | string; + /** Duration in seconds. Absent means the session has no end. */ + duration?: number; + /** Receivers. The first one is the implied originator. */ + parties?: number[]; + /** Originator index, only when it is not the first party. */ + originator?: number; + session_id?: SessionId; + sessions?: Array; + /** Indices of the Dialog Objects in the session. */ + dialog?: number[]; +} + +/** A Session Object. */ +export class Session { + start?: string; + duration?: number; + parties?: number[]; + originator?: number; + session_id?: SessionId; + sessions?: Array; + dialog?: number[]; + + constructor(params: SessionParams = {}) { + this.start = toIso(params.start) as string | undefined; + this.duration = params.duration; + this.parties = params.parties ? [...params.parties] : undefined; + this.originator = params.originator; + this.session_id = params.session_id; + this.sessions = params.sessions ? [...params.sessions] : undefined; + this.dialog = params.dialog ? [...params.dialog] : undefined; + } + + /** Serialize, omitting parameters that are undefined. An empty Session is `{}`. */ + toDict(): SessionType { + const out: SessionType = {}; + for (const name of SESSION_PARAMETERS) { + const value = this[name]; + if (value === undefined) continue; + if (name === 'sessions') { + out.sessions = (value as Array).map(v => + v instanceof SessionReference ? v.toDict() : v + ); + } else { + (out as any)[name] = value; + } + } + return out; + } +} + +export interface ValidateContext { + partyCount?: number; + dialogCount?: number; + sessionCount?: number; + label?: string; +} + +/** Validate one Session Object. Returns `{ errors, warnings }`. */ +export function validateSession( + session: unknown, + ctx: ValidateContext = {} +): { errors: string[]; warnings: string[] } { + const { partyCount, dialogCount, sessionCount } = ctx; + const label = ctx.label ?? 'Session'; + const errors: string[] = []; + const warnings: string[] = []; + if (!isPlainObject(session)) { + return { errors: [`${label} must be a dictionary.`], warnings }; + } + if (Object.keys(session).length === 0) { + return { errors, warnings }; // an empty placeholder Session is permitted + } + + if ('start' in session) { + if (parseDateTime(session.start) === undefined) { + errors.push(`${label} has an invalid 'start' format. Must be an ISO 8601 datetime string.`); + } + } else { + warnings.push(`${label} should have a start parameter.`); + } + + if ('duration' in session) { + const d = session.duration; + if (typeof d !== 'number' || !Number.isFinite(d) || d < 0) { + errors.push(`${label} field 'duration' must be a non-negative number.`); + } + } + + if ('parties' in session) { + const p = session.parties; + if (!Array.isArray(p)) { + errors.push(`${label} field 'parties' must be a list.`); + } else { + for (const idx of p) { + if (!isIndex(idx) || (partyCount !== undefined && idx >= partyCount)) { + errors.push(`${label} references invalid party index: ${idx}`); + } + } + } + } else { + warnings.push(`${label} should have a parties parameter.`); + } + + if ('originator' in session) { + const o = session.originator; + if (!isIndex(o) || (partyCount !== undefined && o >= partyCount)) { + errors.push(`${label} references invalid party index: ${o}`); + } + } + + if ('session_id' in session && !isPlainObject(session.session_id)) { + errors.push(`${label} field 'session_id' must be a SessionId Object.`); + } + + if ('dialog' in session) { + const dl = session.dialog; + if (!Array.isArray(dl)) { + errors.push(`${label} field 'dialog' must be a list.`); + } else { + for (const idx of dl) { + if (!isIndex(idx) || (dialogCount !== undefined && idx >= dialogCount)) { + errors.push(`${label} references invalid dialog index: ${idx}`); + } + } + } + } + + if ('sessions' in session) { + const refs = session.sessions; + if (!Array.isArray(refs)) { + errors.push(`${label} field 'sessions' must be a list.`); + } else { + refs.forEach((ref, n) => { + if (!isPlainObject(ref)) { + errors.push(`${label} sessions[${n}] must be a dictionary.`); + return; + } + for (const req of ['session', 'type']) { + if (!(req in ref)) errors.push(`${label} sessions[${n}] is missing required field: ${req}`); + } + if ('session' in ref) { + if (!isIndex(ref.session) || (sessionCount !== undefined && ref.session >= sessionCount)) { + errors.push(`${label} references invalid session index: ${ref.session}`); + } + } + if ('type' in ref && typeof ref.type !== 'string') { + errors.push(`${label} sessions[${n}] field 'type' must be a string.`); + } + }); + } + } + return { errors, warnings }; +} diff --git a/src/types.ts b/src/types.ts index 673554c..099512e 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,16 +1,15 @@ /** * vCon Type Definitions - * Compliant with the current IETF vCon core draft (draft-ietf-vcon-vcon-core, - * -latest; syntax parameter "0.4.0"). Tracks the authoritative - * vcon_json_schema.json in the draft repo. + * Compliant with draft-ietf-vcon-vcon-core-05 (syntax parameter "0.5.0"). + * Tracks the Appendix C JSON Schema of that draft. * https://datatracker.ietf.org/doc/html/draft-ietf-vcon-vcon-core */ /** Valid encoding types for inline content */ export type Encoding = 'base64url' | 'json' | 'none'; -/** Dialog types as defined in the vCon core draft (incl. recording-set) */ -export type DialogType = 'recording' | 'text' | 'transfer' | 'incomplete' | 'recording-set'; +/** Dialog types defined by core-05. Transfers and recording sets are Events and Sessions now. */ +export type DialogType = 'recording' | 'text' | 'incomplete'; /** Disposition values for incomplete dialogs */ export type DialogDisposition = 'no-answer' | 'congestion' | 'failed' | 'busy' | 'hung-up' | 'voicemail-no-message'; @@ -29,7 +28,10 @@ export interface SessionId { remote: string; } -/** Party history event for tracking party state changes */ +/** + * Party history entry of a 0.4.0 Dialog. + * @deprecated Removed from the Dialog in 0.5.0; use an Event (see PartyHistory.toEvent). + */ export interface PartyHistory { /** Index of the party for this event */ party: number; @@ -123,16 +125,33 @@ export interface Party { [key: string]: any; } -/** Dialog object representing a conversation segment */ +/** Redacted segment of a Dialog's content (core-05 section 4.5) */ +export interface RedactedSegment { + /** Start of the redacted segment (offset into the content) */ + start: number; + /** End of the redacted segment (offset into the content) */ + end: number; + [key: string]: any; +} + +/** + * Dialog object representing a conversation segment. + * + * Under core-05 an empty Dialog (`{}`) is a valid placeholder that holds an + * array position, so `type` is optional on the wire; the Dialog class always + * sets it unless built with Dialog.placeholder(). + */ export interface Dialog { - /** Dialog type: 'recording', 'text', 'transfer', 'incomplete', or 'recording-set' */ - type: DialogType | string; + /** Dialog type: 'recording', 'text' or 'incomplete' (or an extension value) */ + type?: DialogType | string; /** Start time of dialog segment (RFC3339 format) */ - start: Date | string; - /** Party indices contributing to dialog */ - parties?: number | number[]; - /** Originator party index if not first in parties list */ - originator?: number; + start?: Date | string; + /** + * Contributing party indices. An entry may be an index, a list of indices + * (several contributors on one channel) or null (a channel with no + * contributor). The receivers are the `parties` of the Session. + */ + parties?: number | Array; /** Media type string (MIME type) */ mediatype?: string; /** Original filename */ @@ -143,16 +162,12 @@ export interface Dialog { disposition?: DialogDisposition | string; /** Session identifier object(s) */ session_id?: SessionId | SessionId[]; - /** Party event history */ - party_history?: PartyHistory[]; /** Application identifier */ application?: string; /** Message identifier for cross-referencing (e.g., SMTP message-id) */ message_id?: string; - /** recording-set: indices of the recording Dialog Objects in this set */ - recordings?: number[]; - /** Index of the recording-set Dialog Object this recording belongs to */ - recording_set?: number; + /** Segments of the content that were redacted */ + redacted_segments?: RedactedSegment[]; // Inline content (mutually exclusive with url/content_hash) /** Inline content body */ @@ -173,18 +188,6 @@ export interface Dialog { alg?: string; /** Digital signature */ signature?: string; - /** Transfer target party index */ - transferee?: number; - /** Transfer source party index */ - transferor?: number; - /** Transfer target party index/indices */ - transfer_target?: number | number[]; - /** Original dialog index/indices */ - original?: number | number[]; - /** Consultation dialog index/indices */ - consultation?: number | number[]; - /** Target dialog index/indices */ - target_dialog?: number | number[]; /** Generation provenance (draft-howe-vcon-provenance) for machine-generated dialog */ provenance?: Record; /** Campaign identifier (contact center extension) */ @@ -199,14 +202,88 @@ export interface Dialog { [key: string]: any; } +/** Relationship types between Sessions (core-05 section 4.2.8.2) */ +export type SessionReferenceType = 'child' | 'peer' | 'precursor' | 'breakout'; + +/** Session_Reference Object: how another Session relates to this one */ +export interface SessionReference { + /** Index of the referenced Session */ + session: number; + /** child, peer, precursor, breakout, or a value defined by an extension */ + type: SessionReferenceType | string; + description?: string; +} + +/** + * Session Object (core-05 section 4.2). A Session with no parameters is valid. + * The Dialog and Event Objects of a conversation hang off a Session. + */ +export interface Session { + /** Start of the session (SHOULD be present) */ + start?: Date | string; + /** Duration in seconds; absent means the session has no end */ + duration?: number; + /** Receivers. The first party is the implied originator. */ + parties?: number[]; + /** Originator index, only when it is not the first party */ + originator?: number; + session_id?: SessionId; + /** Relationships to other Sessions */ + sessions?: SessionReference[]; + /** Indices of the Dialog Objects in the session */ + dialog?: number[]; + [key: string]: any; +} + +/** Event types defined by core-05 (section 4.3.1) */ +export type EventType = + | 'join' | 'drop' | 'hold' | 'unhold' | 'mute' | 'unmute' + | 'keydown' | 'keyup' + | 'consultation-start' | 'blind-transfer' | 'consultative-transfer' | 'transfer-abandoned' + | 'channel-contributors'; + +/** Event Object (core-05 section 4.3). Per-type parameter rules are in event.ts. */ +export interface Event { + /** Event type token, or a value defined by an extension */ + type: EventType | string; + /** When the event occurred (RFC3339) */ + time: Date | string; + /** Session index or indices the event applies to (not for channel-contributors) */ + sessions?: number | number[]; + /** Party index (the Transferor for transfer types) */ + party?: number; + /** Dialog index (channel-contributors; SHOULD NOT be present otherwise) */ + dialog?: number | number[]; + /** Channel index (channel-contributors) */ + channel?: number; + /** Contributing party index, indices, or null for no contributor (channel-contributors) */ + contributors?: number | number[] | null; + /** DTMF digit or key label (keydown, keyup) */ + button?: string; + /** Party index of the Transferee (transfer types) */ + transferee?: number; + /** Party index of the Transfer Target (transfer types) */ + transfer_target?: number; + /** Session index of the consultation call */ + consultation?: number; + /** Session index of the target call */ + target_session?: number; + /** Parameters defined by an extension */ + [key: string]: any; +} + /** Analysis object for analytical results */ export interface Analysis { /** Analysis type identifier (e.g., report, sentiment, summary, transcript, translation, tts) */ type: string; /** Dialog index/indices analyzed (optional; analysis may key off `attachment` instead) */ dialog?: number | number[]; + /** Session index/indices this analysis is based on */ + sessions?: number | number[]; /** Attachment index/indices this analysis is based on */ attachment?: number | number[]; + /** Other Analysis index/indices this analysis is based on (never itself) */ + analysis?: number | number[]; /** Vendor name (REQUIRED per core schema) */ vendor?: string; /** Product name */ @@ -250,23 +327,25 @@ export interface Analysis { /** * Attachment object for related files. * - * Per draft-ietf-vcon-vcon-core §4.5, core attachments use `purpose` - * (not `type`); `party` and `dialog` indices are REQUIRED. For vCon-level - * attachments where no specific party/dialog applies, use 0/0. + * Per core-05 section 4.6, `purpose`, `start` and `party` are set, plus at + * least one of `dialog` (a single index) or `session` (an index or list). + * The library never invents the scope: Vcon.addAttachment() defaults it only + * when the vCon has exactly one Session. * - * One spec-defined exception: the `lawful_basis` extension attachment - * (draft-howe-vcon-lawful-basis) uses `type: "lawful_basis"`. Callers - * needing that shape must attach it via the catch-all index signature. + * The lawful_basis extension attachment (draft-howe-vcon-lawful-basis) uses + * `purpose: "lawful_basis"`, scoped with `party` plus `session`. */ export interface Attachment { /** Purpose/category of attachment (e.g. "tags", "transcript", "consent") */ purpose?: string; /** Reference time */ start?: Date | string; - /** Related party index (REQUIRED; use 0 for vCon-level) */ + /** Index of the party that contributed the attachment */ party?: number; - /** Related dialog index (REQUIRED; use 0 for vCon-level) */ - dialog?: number | number[]; + /** Related dialog index */ + dialog?: number; + /** Related Session index or indices */ + session?: number | number[]; /** Media type */ mediatype?: string; /** Original filename */ @@ -284,11 +363,11 @@ export interface Attachment { /** Content hash for externally referenced files (single or array for multiple algorithms) */ content_hash?: string | string[]; - /** Allow additional properties for extensions (incl. the lawful_basis `type` field) */ + /** Allow additional properties for extensions */ [key: string]: any; } -/** Redacted object reference per Section 4.1.8.1 */ +/** redacted_from object: reference to the unredacted vCon (core-05 section 4.1.8) */ export interface Redacted { /** UUID of original unredacted vCon */ uuid?: string; @@ -300,7 +379,7 @@ export interface Redacted { content_hash?: string | string[]; } -/** Amended object reference per Section 4.1.9.1 */ +/** amended_from object: reference to the prior vCon version (core-05 section 4.1.9) */ export interface Amended { /** UUID of prior vCon instance version */ uuid?: string; @@ -313,7 +392,7 @@ export interface Amended { export interface VconData { /** Globally unique identifier (preferably UUID v8) */ uuid?: string; - /** vCon version string (deprecated in favor of extensions) */ + /** vCon syntax version. Optional; "0.5.0" for vCons this library writes. */ vcon?: string; /** Conversation subject */ subject?: string; @@ -323,23 +402,53 @@ export interface VconData { updated_at?: Date | string; /** Array of parties in the conversation (mandatory) */ parties?: Party[]; - /** Array of dialog segments */ + /** Array of Session Objects; at least one when dialog or events are non-empty */ + sessions?: Session[]; + /** Array of Event Objects */ + events?: Event[]; + /** Array of dialog segments. An empty object is a valid placeholder. */ dialog?: Dialog[]; /** Array of attachments */ attachments?: Attachment[]; /** Array of analysis results */ analysis?: Analysis[]; - /** Reference to redacted version */ - redacted?: Redacted | boolean; - /** Reference to amended version */ - amended?: Amended | boolean; - /** Names of non-core extensions used */ + /** Reference to the unredacted vCon (exclusive with amended_from) */ + redacted_from?: Redacted; + /** Reference to the prior vCon version (exclusive with redacted_from) */ + amended_from?: Amended; + /** Redacted substrings, referenced as __REDACTED_REF_n in text */ + redacted_strings?: RedactedString[]; + /** Names of non-core extensions used. MUST list every extension in use. */ extensions?: string[]; /** Incompatible extension names requiring explicit support */ critical?: string[]; /** Additional metadata */ meta?: Record; + /** JWS general serialization: base64url payload, set by Vcon.sign() */ + payload?: string; + /** JWS signatures, set by Vcon.sign() */ + signatures?: JwsSignature[]; +} + +/** One signature of a JWS general serialization */ +export interface JwsSignature { + /** base64url JWS protected header */ + protected?: string; + /** Unprotected header */ + header?: Record; + /** base64url signature */ + signature: string; } -/** vCon version constant for vcon-core (note: vcon parameter is DEPRECATED per Section 4.1.1) */ -export const VCON_VERSION = '0.4.0'; +/** Entry of redacted_strings (core-05 section 4.1.16) */ +export interface RedactedString { + /** Reference number, 1 to 99999 */ + ref: number; + [key: string]: any; +} + +/** vCon syntax version this library writes. Readers also accept "0.4.0" and migrate it. */ +export const VCON_VERSION = '0.5.0'; + +/** Syntax version of the previous core draft, accepted on read and migrated. */ +export const LEGACY_VCON_VERSION = '0.4.0'; diff --git a/src/util.ts b/src/util.ts new file mode 100644 index 0000000..2d41cfb --- /dev/null +++ b/src/util.ts @@ -0,0 +1,93 @@ +/** + * Small helpers shared by the model, validation and migration code. + */ + +/** True for a non-negative integer (a valid array index). */ +export function isIndex(value: unknown): value is number { + return typeof value === 'number' && Number.isInteger(value) && value >= 0; +} + +/** True for an integer of any sign. */ +export function isInt(value: unknown): value is number { + return typeof value === 'number' && Number.isInteger(value); +} + +export function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +/** Wrap a scalar in a list; undefined and null become an empty list. */ +export function asList(value: T | T[] | null | undefined): T[] { + if (value === undefined || value === null) return []; + return Array.isArray(value) ? value : [value]; +} + +const DATE_RE = + /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?\s*(Z|z|[+-]\d{2}(?::?\d{2})?)?)?$/; + +/** + * Parse an ISO 8601 / RFC 3339 date-time string to epoch milliseconds, or + * undefined if it is not one. A date-time with no offset is read as UTC, as the + * Python reference does, so results do not depend on the machine's time zone. + */ +export function parseDateTime(value: unknown): number | undefined { + if (typeof value !== 'string') return undefined; + const m = DATE_RE.exec(value.trim()); + if (!m) return undefined; + const [, y, mo, d, h = '00', mi = '00', s = '00', frac = '', tz = 'Z'] = m; + let offset = tz.toUpperCase(); + if (offset !== 'Z') { + const digits = offset.slice(1).replace(':', ''); + offset = offset[0] + digits.slice(0, 2) + ':' + (digits.slice(2) || '00'); + } + const ms = Date.parse(`${y}-${mo}-${d}T${h}:${mi}:${s}${frac}${offset}`); + return Number.isNaN(ms) ? undefined : ms; +} + +/** Convert a Date to an ISO string; pass other values through. */ +export function toIso(value: T | Date): T | string { + return value instanceof Date ? value.toISOString() : value; +} + +/** Deep copy of JSON-compatible data. */ +export function clone(value: T): T { + return value === undefined ? value : JSON.parse(JSON.stringify(value)); +} + +/** + * Emit a deprecation or compatibility warning. Uses process.emitWarning when + * available (so it can be silenced with --no-warnings), else console.warn. + */ +export function warn(message: string, code = 'DeprecationWarning'): void { + if (typeof process !== 'undefined' && typeof process.emitWarning === 'function') { + process.emitWarning(message, code); + } else if (typeof console !== 'undefined') { + console.warn(`${code}: ${message}`); + } +} + +/** Decode a base64url string (padded or not) to a UTF-8 string. Throws on non-base64url input. */ +export function base64UrlDecodeToString(input: string): string { + if (!/^[A-Za-z0-9_-]*={0,2}$/.test(input)) throw new Error('not base64url'); + const b64 = input.replace(/-/g, '+').replace(/_/g, '/'); + const padded = b64 + '='.repeat((4 - (b64.replace(/=+$/, '').length % 4)) % 4); + if (typeof Buffer !== 'undefined') return Buffer.from(padded, 'base64').toString('utf8'); + const bin = atob(padded); + const bytes = Uint8Array.from(bin, c => c.charCodeAt(0)); + return new TextDecoder().decode(bytes); +} + +/** Python-style repr for report messages: strings in single quotes, other values as JSON. */ +export function repr(value: unknown): string { + if (typeof value === 'string') return `'${value.replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`; + if (value === undefined) return 'None'; + if (value === null) return 'None'; + if (value === true) return 'True'; + if (value === false) return 'False'; + return JSON.stringify(value); +} + +/** Python-style repr of a list of strings, e.g. ['a', 'b']. */ +export function reprList(values: unknown[]): string { + return `[${values.map(repr).join(', ')}]`; +} diff --git a/src/validation.ts b/src/validation.ts new file mode 100644 index 0000000..e349d4d --- /dev/null +++ b/src/validation.ts @@ -0,0 +1,553 @@ +/** + * Structural validation of an unsigned vCon object against core-05. + * + * validateVconDict() is the engine behind Vcon.isValid(). It works on plain + * objects so the migration code can reuse it. + */ +import { CORE_EVENT_TYPES, validateEvent } from './event'; +import { SESSION_REFERENCE_TYPES, validateSession } from './session'; +import { asList, isIndex, isPlainObject, parseDateTime } from './util'; + +export const SYNTAX_VERSION = '0.5.0'; + +export const CORE_DIALOG_TYPES = ['recording', 'text', 'incomplete']; +/** + * Dialog types older versions of this library wrote although core-05 does not + * define them. Accepted on read with a warning; the library never writes them. + */ +export const LIBRARY_DIALOG_TYPES = ['audio', 'video']; +export const CORE_ENCODINGS = ['base64url', 'json', 'none']; +export const CORE_DISPOSITIONS = [ + 'no-answer', + 'congestion', + 'failed', + 'busy', + 'hung-up', + 'voicemail-no-message' +]; + +/** Extension names this library recognises, keyed by how they show up. */ +const KNOWN_ATTACHMENT_PURPOSE_EXTENSIONS: Record = { + lawful_basis: 'lawful_basis', + wtf_transcription: 'wtf_transcription' +}; +const KNOWN_ANALYSIS_TYPE_EXTENSIONS: Record = { + wtf_transcription: 'wtf_transcription' +}; + +/** Removed in 0.5.0; their presence means the document is still 0.4.0 shaped. */ +export const LEGACY_TOP_LEVEL: Record = { + redacted: 'redacted_from', + amended: 'amended_from' +}; +export const LEGACY_DIALOG_PARAMS = [ + 'party_history', + 'originator', + 'transferee', + 'transferor', + 'transfer_target', + 'original', + 'consultation', + 'target_dialog', + 'recordings', + 'recording_set' +]; +export const LEGACY_DIALOG_TYPES = ['transfer', 'recording-set']; + +/** Dialog media types the library knows (the draft's list is open-ended; see mediatypeOk). */ +export const DIALOG_MIME_TYPES = [ + 'text/plain', + 'audio/x-wav', + 'audio/wav', + 'audio/wave', + 'audio/mpeg', + 'audio/mp3', + 'audio/ogg', + 'audio/webm', + 'audio/x-m4a', + 'audio/aac', + 'video/mp4', + 'video/x-mp4', + 'video/ogg', + 'video/webm', + 'multipart/mixed', + 'message/rfc822', + 'application/json' +]; + +const REDACTED_REF_RE = /__REDACTED_REF_(\d{1,5})(?!\d)/g; + +/** + * True if `mediatype` is acceptable for a Dialog. Media type parameters + * (`; boundary=...`) are ignored. Any multipart/, message/ or text/ subtype is + * accepted, since the draft's examples use multipart/alternative and the list + * in the draft is open-ended. + */ +export function mediatypeOk(mediatype: unknown, known: string[] = DIALOG_MIME_TYPES): boolean { + if (typeof mediatype !== 'string') return false; + const base = mediatype.split(';', 1)[0].trim().toLowerCase(); + if (known.includes(base)) return true; + return ['multipart/', 'message/', 'text/'].some(p => base.startsWith(p)); +} + +function flattenParties(value: unknown): unknown[] { + const out: unknown[] = []; + for (const v of asList(value)) { + if (Array.isArray(v)) out.push(...v); + else out.push(v); + } + return out; +} + +/** + * Find the vCon extensions the document uses. + * + * `names` holds extension names this library recognises (lawful_basis, + * wtf_transcription). `unnamed` describes each use of a value outside the core + * vocabulary (an Event type, Dialog encoding, disposition or Session_Reference + * type) whose defining extension cannot be identified from the document alone. + */ +export function extensionsInUse(vcon: Record): { names: Set; unnamed: string[] } { + const names = new Set(); + const unnamed: string[] = []; + + asList(vcon.attachments).forEach((att, i) => { + if (!isPlainObject(att)) return; + if (typeof att.purpose === 'string' && Object.prototype.hasOwnProperty.call(KNOWN_ATTACHMENT_PURPOSE_EXTENSIONS, att.purpose)) { + names.add(KNOWN_ATTACHMENT_PURPOSE_EXTENSIONS[att.purpose]); + } + if (att.encoding !== undefined && att.encoding !== null && !CORE_ENCODINGS.includes(att.encoding)) { + unnamed.push(`attachments[${i}] encoding '${att.encoding}'`); + } + }); + asList(vcon.analysis).forEach((an, i) => { + if (!isPlainObject(an)) return; + if (typeof an.type === 'string' && Object.prototype.hasOwnProperty.call(KNOWN_ANALYSIS_TYPE_EXTENSIONS, an.type)) { + names.add(KNOWN_ANALYSIS_TYPE_EXTENSIONS[an.type]); + } + if (an.encoding !== undefined && an.encoding !== null && !CORE_ENCODINGS.includes(an.encoding)) { + unnamed.push(`analysis[${i}] encoding '${an.encoding}'`); + } + }); + asList(vcon.dialog).forEach((d, i) => { + if (!isPlainObject(d) || Object.keys(d).length === 0) return; + if (d.encoding !== undefined && d.encoding !== null && !CORE_ENCODINGS.includes(d.encoding)) { + unnamed.push(`dialog[${i}] encoding '${d.encoding}'`); + } + if (d.type === 'incomplete' && d.disposition !== undefined && d.disposition !== null && !CORE_DISPOSITIONS.includes(d.disposition)) { + unnamed.push(`dialog[${i}] disposition '${d.disposition}'`); + } + }); + asList(vcon.events).forEach((e, i) => { + if (!isPlainObject(e)) return; + if (e.type !== undefined && e.type !== null && !CORE_EVENT_TYPES.includes(e.type)) { + unnamed.push(`events[${i}] type '${e.type}'`); + } + }); + asList(vcon.sessions).forEach((s, i) => { + if (!isPlainObject(s)) return; + asList(s.sessions).forEach((ref, j) => { + if (isPlainObject(ref) && ref.type !== undefined && ref.type !== null && !SESSION_REFERENCE_TYPES.includes(ref.type)) { + unnamed.push(`sessions[${i}].sessions[${j}] type '${ref.type}'`); + } + }); + }); + return { names, unnamed }; +} + +function scanRedactedRefs(obj: unknown, found: Set): void { + if (typeof obj === 'string') { + for (const m of obj.matchAll(REDACTED_REF_RE)) found.add(parseInt(m[1], 10)); + } else if (Array.isArray(obj)) { + obj.forEach(v => scanRedactedRefs(v, found)); + } else if (isPlainObject(obj)) { + Object.values(obj).forEach(v => scanRedactedRefs(v, found)); + } +} + +/** Validate an unsigned vCon object. Returns `{ errors, warnings }`. */ +export function validateVconDict( + vcon: Record, + dialogMimeTypes: string[] = DIALOG_MIME_TYPES +): { errors: string[]; warnings: string[] } { + const errors: string[] = []; + const warnings: string[] = []; + + // --- required fields and version ---------------------------------------- + for (const field of ['uuid', 'created_at']) { + if (!(field in vcon)) errors.push(`Missing required field: ${field}`); + } + for (const ts of ['created_at', 'updated_at']) { + if (ts in vcon && parseDateTime(vcon[ts]) === undefined) { + errors.push(`Invalid ${ts} format. Must be an ISO 8601 datetime string.`); + } + } + if ('vcon' in vcon && vcon.vcon !== SYNTAX_VERSION) { + errors.push( + `Unsupported vcon syntax version '${vcon.vcon}': this library writes '${SYNTAX_VERSION}'. ` + + 'Migrate a 0.4.0 vCon with migrate040To050().' + ); + } + for (const [old, neu] of Object.entries(LEGACY_TOP_LEVEL)) { + if (old in vcon) errors.push(`Legacy 0.4.0 parameter '${old}' was renamed '${neu}' in 0.5.0.`); + } + + // --- parties -------------------------------------------------------------- + let parties: any[] = []; + if ('parties' in vcon) { + if (!Array.isArray(vcon.parties)) { + errors.push("Field 'parties' must be a list."); + } else { + parties = vcon.parties; + parties.forEach((party, i) => { + if (!isPlainObject(party)) errors.push(`Party at index ${i} must be a dictionary.`); + }); + } + } + const partyCount = parties.length; + + let dialogs: any[] = []; + if ('dialog' in vcon) { + if (!Array.isArray(vcon.dialog)) errors.push("Field 'dialog' must be a list."); + else dialogs = vcon.dialog; + } + const dialogCount = dialogs.length; + let sessions: any[] = []; + if ('sessions' in vcon) { + if (!Array.isArray(vcon.sessions)) errors.push("Field 'sessions' must be a list."); + else sessions = vcon.sessions; + } + const sessionCount = sessions.length; + let events: any[] = []; + if ('events' in vcon) { + if (!Array.isArray(vcon.events)) errors.push("Field 'events' must be a list."); + else events = vcon.events; + } + let attachments: any[] = []; + if ('attachments' in vcon) { + if (!Array.isArray(vcon.attachments)) errors.push("Field 'attachments' must be a list."); + else attachments = vcon.attachments; + } + let analyses: any[] = []; + if ('analysis' in vcon) { + if (!Array.isArray(vcon.analysis)) errors.push("Field 'analysis' must be a list."); + else analyses = vcon.analysis; + } + const redacted = isPlainObject(vcon.redacted_from); + + // --- redacted_from / amended_from ---------------------------------------- + if ('redacted_from' in vcon && 'amended_from' in vcon) { + errors.push('redacted_from and amended_from are mutually exclusive.'); + } + if ('redacted_from' in vcon) { + const rf = vcon.redacted_from; + if (!isPlainObject(rf)) { + errors.push("Field 'redacted_from' must be an object."); + } else { + if (!('type' in rf)) errors.push('redacted_from is missing required field: type'); + if ('url' in rf && !('content_hash' in rf)) errors.push('redacted_from with url must include content_hash.'); + } + } + if ('amended_from' in vcon) { + const af = vcon.amended_from; + if (!isPlainObject(af)) { + errors.push("Field 'amended_from' must be an object."); + } else { + if (!('uuid' in af) && !('url' in af)) { + errors.push('amended_from must include uuid, or an external reference (url).'); + } + if ('url' in af && !('content_hash' in af)) errors.push('amended_from with url must include content_hash.'); + } + } + + // --- extensions / critical ----------------------------------------------- + let extListed: any[] = []; + if ('extensions' in vcon) { + if (!Array.isArray(vcon.extensions) || !vcon.extensions.every((x: unknown) => typeof x === 'string')) { + errors.push("Field 'extensions' must be a list of strings."); + } else { + extListed = vcon.extensions; + } + } + let crit: any[] = []; + if ('critical' in vcon) { + if (!Array.isArray(vcon.critical) || !vcon.critical.every((x: unknown) => typeof x === 'string')) { + errors.push("Field 'critical' must be a list of strings."); + } else { + crit = vcon.critical; + } + } + for (const name of crit) { + if (!extListed.includes(name)) { + errors.push(`Extension '${name}' is listed in critical but not in extensions.`); + } + } + const { names: used, unnamed } = extensionsInUse(vcon); + for (const name of [...used].sort()) { + if (!extListed.includes(name)) { + errors.push(`Extension '${name}' is in use but is not listed in the extensions parameter.`); + } + } + if (unnamed.length && extListed.length === 0) { + errors.push( + 'Values outside the core vocabulary are in use but the extensions parameter lists no extension: ' + + unnamed.join('; ') + + '.' + ); + } + + // --- dialog ----------------------------------------------------------------- + dialogs.forEach((dialog, i) => { + if (!isPlainObject(dialog)) { + errors.push(`Dialog at index ${i} must be a dictionary.`); + return; + } + if (Object.keys(dialog).length === 0) return; // empty placeholder Dialog Object (4.5.1) + const dialogType = dialog.type; + if (!('type' in dialog)) { + errors.push(`Dialog at index ${i} is missing required field: type`); + } else if (LEGACY_DIALOG_TYPES.includes(dialogType)) { + errors.push( + `Dialog at index ${i} has type '${dialogType}', which was removed in 0.5.0 ` + + '(use Events and Sessions; migrate with migrate040To050()).' + ); + } else if (LIBRARY_DIALOG_TYPES.includes(dialogType) && extListed.length === 0) { + warnings.push( + `Dialog at index ${i} has type '${dialogType}', which core-05 does not define; ` + + "it is read as 'recording' (written by older library versions)." + ); + } else if ( + !CORE_DIALOG_TYPES.includes(dialogType) && + !LIBRARY_DIALOG_TYPES.includes(dialogType) && + extListed.length === 0 + ) { + // A Dialog type outside the core vocabulary must come from a vCon + // extension, which has to be listed in extensions (4.1.3). + errors.push(`Dialog at index ${i} has an invalid type: ${dialogType}`); + } + for (const legacy of LEGACY_DIALOG_PARAMS) { + if (legacy in dialog) errors.push(`Dialog at index ${i} has parameter '${legacy}', which was removed in 0.5.0.`); + } + if (dialogType === 'incomplete') { + if (!('disposition' in dialog)) errors.push(`Dialog at index ${i} of type 'incomplete' must have a disposition.`); + for (const forbidden of [ + 'mediatype', 'filename', 'body', 'encoding', 'url', 'content_hash', 'message_id', 'redacted_segments' + ]) { + if (forbidden in dialog) { + errors.push(`Dialog at index ${i} of type 'incomplete' must not have field: ${forbidden}`); + } + } + } + + if ('parties' in dialog) { + const dp = dialog.parties; + if (!(Array.isArray(dp) || (typeof dp === 'number' && Number.isInteger(dp)))) { + errors.push(`Dialog at index ${i} field 'parties' must be a list.`); + } else { + for (const partyIdx of flattenParties(dp)) { + if (partyIdx === null) continue; // null placeholder for a channel with no contributor + if (!isIndex(partyIdx) || partyIdx >= partyCount) { + errors.push(`Dialog at index ${i} references invalid party index: ${partyIdx}`); + } + } + } + } + if ('start' in dialog && parseDateTime(dialog.start) === undefined) { + errors.push(`Dialog at index ${i} has an invalid 'start' format. Must be an ISO 8601 datetime string.`); + } + if (dialogType !== 'incomplete') { + const hasContent = 'body' in dialog; + if ('mediatype' in dialog) { + if (!mediatypeOk(dialog.mediatype, dialogMimeTypes)) { + errors.push(`Dialog at index ${i} has an invalid or missing mediatype: ${dialog.mediatype}`); + } + } else if (hasContent) { + errors.push(`Dialog at index ${i} has an invalid or missing mediatype: missing`); + } + } + if ('redacted_segments' in dialog) { + const segs = dialog.redacted_segments; + if (!Array.isArray(segs)) { + errors.push(`Dialog at index ${i} field 'redacted_segments' must be a list.`); + } else { + segs.forEach((seg, n) => { + if (!isPlainObject(seg) || !('start' in seg) || !('end' in seg)) { + errors.push(`Dialog at index ${i} redacted_segments[${n}] requires start and end.`); + } + }); + } + } + }); + + // --- sessions ----------------------------------------------------------------- + if ((dialogCount || events.length) && sessions.length === 0) { + errors.push('At least one Session Object MUST exist if the events array or the dialog array contains Objects.'); + } + sessions.forEach((s, i) => { + const r = validateSession(s, { partyCount, dialogCount, sessionCount, label: `Session at index ${i}` }); + errors.push(...r.errors); + warnings.push(...r.warnings); + }); + const referencedDialogs = new Set(); + for (const s of sessions) { + if (isPlainObject(s) && Array.isArray(s.dialog)) { + for (const x of s.dialog) if (isIndex(x)) referencedDialogs.add(x); + } + } + dialogs.forEach((d, i) => { + if (isPlainObject(d) && Object.keys(d).length > 0 && !referencedDialogs.has(i)) { + warnings.push(`Dialog at index ${i} is not referenced by any Session Object.`); + } + }); + const emptyDialogs = new Set(); + dialogs.forEach((d, i) => { + if (isPlainObject(d) && Object.keys(d).length === 0) emptyDialogs.add(i); + }); + sessions.forEach((s, n) => { + if (!isPlainObject(s)) return; + if (Array.isArray(s.parties) && s.parties.length > 0 && s.originator === s.parties[0]) { + warnings.push( + `Session at index ${n} has originator equal to its first party; originator is ` + + 'only provided when the first party is not the originator (4.2.4).' + ); + } + const listed = asList(s.dialog).filter(isIndex).sort((a, b) => a - b); + for (const x of [...new Set(listed)]) { + if (emptyDialogs.has(x)) warnings.push(`Session at index ${n} lists dialog ${x}, which is an empty placeholder Dialog.`); + } + }); + + // --- events --------------------------------------------------------------------- + events.forEach((ev, i) => { + const r = validateEvent(ev, { partyCount, dialogCount, sessionCount, label: `Event at index ${i}` }); + errors.push(...r.errors); + warnings.push(...r.warnings); + if (isPlainObject(ev) && ev.type === 'channel-contributors' && isIndex(ev.dialog)) { + const di = ev.dialog; + if (di < dialogCount && isPlainObject(dialogs[di]) && dialogs[di].type !== 'recording') { + errors.push(`Event at index ${i} of type 'channel-contributors' must reference a 'recording' Dialog.`); + } + } + }); + + // --- attachments -------------------------------------------------------------- + attachments.forEach((attachment, i) => { + if (!isPlainObject(attachment)) { + errors.push(`Attachment at index ${i} must be a dictionary.`); + return; + } + if (!('purpose' in attachment)) errors.push(`Attachment at index ${i} is missing required field: purpose`); + const hasInline = 'body' in attachment && 'encoding' in attachment; + const hasExternal = 'url' in attachment && 'content_hash' in attachment; + if (!(hasInline || hasExternal || redacted)) { + errors.push(`Attachment at index ${i} must include body+encoding or url+content_hash.`); + } + if ('encoding' in attachment && !CORE_ENCODINGS.includes(attachment.encoding) && extListed.length === 0) { + errors.push(`Attachment at index ${i} has invalid encoding: ${attachment.encoding}`); + } + if ('body' in attachment && attachment.body !== '' && !('mediatype' in attachment)) { + errors.push(`Attachment at index ${i} is missing required field: mediatype (needed for inline content)`); + } + if (!('start' in attachment)) errors.push(`Attachment at index ${i} is missing required field: start`); + if (!('party' in attachment)) { + errors.push(`Attachment at index ${i} is missing required field: party`); + } else if (!isIndex(attachment.party) || attachment.party >= partyCount) { + errors.push(`Attachment at index ${i} references invalid party index: ${attachment.party}`); + } + if (!('dialog' in attachment) && !('session' in attachment)) { + errors.push(`Attachment at index ${i} must have at least one of dialog or session.`); + } + if ('dialog' in attachment) { + const dv = attachment.dialog; + if (!isIndex(dv) || dv >= dialogCount) { + errors.push(`Attachment at index ${i} references invalid dialog index: ${dv}`); + } else if (emptyDialogs.has(dv)) { + warnings.push(`Attachment at index ${i} references dialog ${dv}, an empty placeholder Dialog.`); + } + } + if ('session' in attachment) { + const sv = attachment.session; + const vals = Array.isArray(sv) ? sv : [sv]; + if (Array.isArray(sv) && sv.length === 0) { + errors.push(`Attachment at index ${i} field 'session' must not be empty.`); + } + for (const v of vals) { + if (!isIndex(v) || v >= sessionCount) { + errors.push(`Attachment at index ${i} references invalid session index: ${v}`); + } + } + } + }); + + // --- analysis --------------------------------------------------------------------- + analyses.forEach((analysis, i) => { + if (!isPlainObject(analysis)) { + errors.push(`Analysis at index ${i} must be a dictionary.`); + return; + } + for (const field of ['type', 'vendor']) { + if (!(field in analysis)) errors.push(`Analysis at index ${i} is missing required field: ${field}`); + } + if ('body' in analysis && analysis.body !== '' && !('encoding' in analysis)) { + errors.push(`Analysis at index ${i} is missing required field: encoding`); + } + if ('encoding' in analysis && !CORE_ENCODINGS.includes(analysis.encoding) && extListed.length === 0) { + errors.push(`Analysis at index ${i} has invalid encoding: ${analysis.encoding}`); + } + const refs: Array<[string, number, string]> = [ + ['dialog', dialogCount, 'dialog'], + ['sessions', sessionCount, 'session'], + ['attachment', attachments.length, 'attachment'], + ['analysis', analyses.length, 'analysis'] + ]; + for (const [key, count, noun] of refs) { + if (!(key in analysis)) continue; + const val = analysis[key]; + if (!(typeof val === 'number' || Array.isArray(val))) { + errors.push(`Analysis at index ${i} has an invalid '${key}' reference type.`); + continue; + } + for (const v of Array.isArray(val) ? val : [val]) { + if (!isIndex(v) || v >= count) { + errors.push(`Analysis at index ${i} references invalid ${noun} index: ${v}`); + } else if (key === 'analysis' && v === i) { + errors.push(`Analysis at index ${i} must not reference itself in analysis.`); + } + } + } + if (!['dialog', 'sessions', 'attachment', 'analysis'].some(k => k in analysis)) { + warnings.push(`Analysis at index ${i} should have at least one of dialog, sessions, attachment or analysis.`); + } + }); + + // --- redacted_strings ----------------------------------------------------------- + const refsDeclared = new Set(); + if ('redacted_strings' in vcon) { + const rs = vcon.redacted_strings; + if (!Array.isArray(rs)) { + errors.push("Field 'redacted_strings' must be a list."); + } else { + if (rs.length > 99999) errors.push('A vCon MUST NOT have more than 99999 redacted substrings.'); + rs.forEach((item, n) => { + if (!isPlainObject(item) || !Number.isInteger(item.ref)) { + errors.push(`redacted_strings[${n}] requires an integer ref.`); + return; + } + if (item.ref < 1 || item.ref > 99999) errors.push(`redacted_strings[${n}] ref must be between 1 and 99999.`); + if (refsDeclared.has(item.ref)) errors.push(`redacted_strings[${n}] duplicates ref ${item.ref}.`); + refsDeclared.add(item.ref); + }); + } + } + const found = new Set(); + const rest: Record = {}; + for (const [k, v] of Object.entries(vcon)) if (k !== 'redacted_strings') rest[k] = v; + scanRedactedRefs(rest, found); + for (const ref of [...found].sort((a, b) => a - b)) { + if (!refsDeclared.has(ref)) { + errors.push(`__REDACTED_REF_${ref} appears in the vCon but has no entry in redacted_strings.`); + } + } + + return { errors, warnings }; +} diff --git a/src/vcon.ts b/src/vcon.ts index 6559a3e..16bd6c9 100644 --- a/src/vcon.ts +++ b/src/vcon.ts @@ -1,51 +1,186 @@ import { v4 as uuidv4 } from 'uuid'; +import * as nodeCrypto from 'crypto'; import { VconData, Attachment, Party, Dialog, Analysis, + Session as SessionType, + Event as EventType, Encoding, Redacted, Amended, - VCON_VERSION + RedactedString, + VCON_VERSION, + LEGACY_VCON_VERSION } from './types'; import { Attachment as AttachmentClass } from './attachment'; import { Party as PartyClass } from './party'; import { Dialog as DialogClass } from './dialog'; +import { Session as SessionClass } from './session'; +import { Event as EventClass } from './event'; +import { migrate040To050, MigrationReport } from './migration'; +import { validateVconDict } from './validation'; +import { base64UrlDecodeToString, clone, isPlainObject, warn } from './util'; + +/** A JWS used `alg` "none" (forbidden by core-05) or an unsupported algorithm. */ +export class AlgorithmNotPermittedError extends Error { + constructor(message: string) { + super(message); + this.name = 'AlgorithmNotPermittedError'; + Object.setPrototypeOf(this, AlgorithmNotPermittedError.prototype); + } +} + +/** + * JWS algorithms accepted for signing and verifying. "none" is excluded: + * core-05 section 6.2.2, "The alg parameter MUST NOT have the value none". + */ +export const PERMITTED_JWS_ALGORITHMS = [ + 'RS256', 'RS384', 'RS512', + 'PS256', 'PS384', 'PS512', + 'ES256', 'ES384', 'ES512', + 'EdDSA' +] as const; + +export type JwsAlgorithm = (typeof PERMITTED_JWS_ALGORITHMS)[number]; + +/** Key material accepted by sign() and verify(): a PEM string or buffer, or a KeyObject. */ +export type KeyInput = string | Buffer | nodeCrypto.KeyObject; + +export interface VconOptions { + /** + * Migrate a 0.4.0 vCon to 0.5.0 on load (default true). When false the 0.4.0 + * object is kept untouched and isValid() reports it as not 0.5.0. + */ + migrateLegacy?: boolean; + /** Passed to the migration as `strict`: throw when a required field has no source. */ + strictMigration?: boolean; +} + +/** True if the object declares syntax 0.4.0, directly or in a signed payload. */ +function isLegacy040(dict: any): boolean { + if (!isPlainObject(dict)) return false; + if (dict.vcon === LEGACY_VCON_VERSION) return true; + if (!('vcon' in dict) && typeof dict.payload === 'string' && 'signatures' in dict) { + try { + const payload = JSON.parse(base64UrlDecodeToString(dict.payload)); + return isPlainObject(payload) && payload.vcon === LEGACY_VCON_VERSION; + } catch { + return false; + } + } + return false; +} + +const HASHES: Record = { '256': 'sha256', '384': 'sha384', '512': 'sha512' }; + +function jwsParams(alg: string): { hash: string | null; padding?: number; saltLength?: number; dsaEncoding?: 'ieee-p1363' } { + if (alg === 'EdDSA') return { hash: null }; + const hash = HASHES[alg.slice(2)]; + if (alg.startsWith('RS')) return { hash }; + if (alg.startsWith('PS')) { + return { + hash, + padding: nodeCrypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: nodeCrypto.constants.RSA_PSS_SALTLEN_DIGEST + }; + } + return { hash, dsaEncoding: 'ieee-p1363' }; +} + +function b64url(input: string | Buffer): string { + return (typeof input === 'string' ? Buffer.from(input, 'utf8') : input).toString('base64url'); +} + +function assertPermittedAlg(alg: unknown): asserts alg is JwsAlgorithm { + if (typeof alg !== 'string' || alg.trim().toLowerCase() === 'none') { + throw new AlgorithmNotPermittedError('JWS alg "none" is not permitted (core-05 section 6.2.2)'); + } + if (!(PERMITTED_JWS_ALGORITHMS as readonly string[]).includes(alg)) { + throw new AlgorithmNotPermittedError( + `JWS alg ${JSON.stringify(alg)} is not supported; use one of ${PERMITTED_JWS_ALGORITHMS.join(', ')}` + ); + } +} /** * Main Vcon class for creating and managing vCon conversation containers. - * Compliant with IETF draft-ietf-vcon-vcon-core + * Compliant with draft-ietf-vcon-vcon-core-05 (syntax "0.5.0"). */ export class Vcon { data: VconData; - constructor(vconDict: Partial = {}) { + /** + * MigrationReport when the input was migrated from 0.4.0 on load, else + * undefined. + */ + migrationReport?: MigrationReport; + + /** + * @param vconDict A vCon object. An object that declares `"vcon": "0.4.0"` + * is migrated to 0.5.0 here, using migrate040To050(); the report is kept in + * `migrationReport`. A signed vCon whose payload is 0.4.0 is NOT migrated + * on load, because migrating drops the signature: verify it, then call + * Vcon.migrate040To050(). Any other (or no) `vcon` value is taken as is. + */ + constructor(vconDict: Partial | Record = {}, options: VconOptions = {}) { + const { migrateLegacy = true, strictMigration = false } = options; + let input: Record = vconDict; + + const legacy = isLegacy040(input); + const signedLegacy = legacy && !('vcon' in input); + if (signedLegacy) { + // Migrating rewrites the payload, which drops the signature. Doing that + // implicitly would make verify() impossible and, on a load-and-save path, + // overwrite a signed record with an unsigned one. Keep it signed; migrate + // explicitly with Vcon.migrate040To050() after verifying. + warn('Signed 0.4.0 vCon loaded unmigrated; verify it, then call Vcon.migrate040To050() (the result must be signed again)', 'VconWarning'); + } else if (migrateLegacy && legacy) { + const { vcon: migrated, report } = migrate040To050(input, { strict: strictMigration }); + this.migrationReport = report; + warn(`Migrated vCon ${migrated.uuid} from 0.4.0 to 0.5.0 on load (${report.summary()})`, 'VconWarning'); + input = migrated; + } + + if (legacy && !this.migrationReport) { + // An unmigrated 0.4.0 (or signed 0.4.0) object is kept as is: no defaults + // are added, so legacy parameters and the signature survive. + this.data = clone(input) as VconData; + return; + } + + const created = input.created_at instanceof Date ? input.created_at.toISOString() : input.created_at; this.data = { - uuid: vconDict.uuid || uuidv4(), - vcon: vconDict.vcon || VCON_VERSION, - created_at: vconDict.created_at || new Date().toISOString(), - updated_at: vconDict.updated_at, - parties: vconDict.parties || [], - dialog: vconDict.dialog || [], - attachments: vconDict.attachments || [], - analysis: vconDict.analysis || [], - ...vconDict - }; + uuid: input.uuid || uuidv4(), + // An empty constructor builds a new 0.5.0 vCon. Input that is not empty and + // has no `vcon` stays as it is: the parameter is optional in 0.5.0. + vcon: input.vcon ?? (Object.keys(input).length === 0 ? VCON_VERSION : undefined), + created_at: created || new Date().toISOString(), + updated_at: input.updated_at, + parties: input.parties || [], + dialog: input.dialog || [], + attachments: input.attachments || [], + analysis: input.analysis || [], + ...input + } as VconData; + this.data.created_at = created || this.data.created_at; + if (this.data.vcon === undefined) delete this.data.vcon; } /** - * Create a Vcon from a JSON string + * Create a Vcon from a JSON string. A 0.4.0 vCon is migrated (see the constructor). */ - static buildFromJson(jsonString: string): Vcon { + static buildFromJson(jsonString: string, options: VconOptions = {}): Vcon { + let data: any; try { - const data = JSON.parse(jsonString); - return new Vcon(data); + data = JSON.parse(jsonString); } catch (error: unknown) { const errorMessage = error instanceof Error ? error.message : String(error); throw new Error(`Failed to parse vCon JSON: ${errorMessage}`); } + return new Vcon(data, options); } /** @@ -55,10 +190,22 @@ export class Vcon { return new Vcon(); } - // Tag methods — per speckit, tags are stored as a single attachment with - // purpose="tags", party=0, dialog=0, encoding="json", and a JSON-string - // body. We keep an in-memory dictionary API but always read from / write - // through that attachment. + /** + * Explicitly migrate a 0.4.0 vCon (object or JSON string) and return a Vcon. + * The report is available as `vcon.migrationReport`. Unlike the implicit + * migration on load, this also accepts input with no `vcon` parameter and a + * signed vCon (migrated as its unsigned payload; the result must be signed again). + */ + static migrate040To050(source: string | Record, options: { strict?: boolean } = {}): Vcon { + const { vcon, report } = migrate040To050(source, options); + const obj = new Vcon(vcon, { migrateLegacy: false }); + obj.migrationReport = report; + return obj; + } + + // Tag methods — tags are stored as a single attachment with purpose="tags", + // party=0, encoding="json", and a JSON-string body. We keep an in-memory + // dictionary API but always read from / write through that attachment. private getTagsAttachment(): Attachment | undefined { return this.data.attachments?.find(a => a.purpose === 'tags'); @@ -83,6 +230,44 @@ export class Vcon { return this.decodeTags()[tagName]; } + /** + * Work out the `dialog` / `session` scope for a new attachment. + * + * Core-05 section 4.6 needs at least one of the two. The caller's values are + * used as given and a dialog index is never widened to a Session. With + * neither given, the scope is defaulted only when it is unambiguous: the vCon + * has exactly one Session, which is then the whole conversation. Otherwise + * this throws, because picking a Session (or adding a placeholder one) would + * invent the scope. + * + * `wholeVcon` is for library metadata that describes the whole vCon + * (addTag): every Session is listed, and an empty placeholder Session is + * added when there is none. + */ + private resolveAttachmentScope( + dialog?: number, + session?: number | number[], + wholeVcon = false + ): { dialog?: number; session?: number | number[] } { + const scope: { dialog?: number; session?: number | number[] } = {}; + if (dialog !== undefined) scope.dialog = dialog; + if (session !== undefined) scope.session = session; + if (Object.keys(scope).length) return scope; + if (wholeVcon) { + if (!this.data.sessions || this.data.sessions.length === 0) { + this.data.sessions = [...(this.data.sessions || []), {}]; + warn('Added an empty placeholder Session to scope the tags attachment', 'VconWarning'); + } + return { session: this.data.sessions.map((_, i) => i) }; + } + const count = this.data.sessions?.length ?? 0; + if (count === 1) return { session: 0 }; + throw new Error( + `An attachment needs dialog or session (core-05 section 4.6). The vCon has ${count} Sessions, ` + + 'so no default can be chosen; pass dialog or session (add a Session first with addSession() if the vCon has none).' + ); + } + addTag(tagName: string, tagValue: string): void { const next = { ...this.decodeTags(), [tagName]: tagValue }; const serialized = JSON.stringify(next); @@ -95,12 +280,13 @@ export class Vcon { // Backfill start on a legacy tags attachment that predates this field. if (existing.start === undefined) existing.start = new Date().toISOString(); } else { + const scope = this.resolveAttachmentScope(undefined, undefined, true); this.data.attachments.push({ purpose: 'tags', // `start` is REQUIRED on every attachment per the core schema. start: new Date().toISOString(), party: 0, - dialog: 0, + ...scope, body: serialized, encoding: 'json', mediatype: 'application/json' @@ -116,8 +302,10 @@ export class Vcon { } /** - * Add an attachment. Per draft-ietf-vcon-vcon-core §4.5, `purpose`, - * `party`, and `dialog` are required; party/dialog default to 0 when omitted. + * Add an attachment. Core-05 needs `party` plus `dialog` or `session`. + * `party` defaults to 0 and `start` to the vCon's `created_at`. With neither + * `dialog` nor `session`, the attachment is scoped to the only Session when + * the vCon has exactly one; otherwise this throws rather than inventing a scope. */ addAttachment(params: { purpose: string; @@ -129,9 +317,17 @@ export class Vcon { filename?: string; start?: Date | string; party?: number; - dialog?: number | number[]; + dialog?: number; + session?: number | number[]; }): AttachmentClass { - const attachment = new AttachmentClass(params); + const scope = this.resolveAttachmentScope(params.dialog, params.session); + const attachment = new AttachmentClass({ + ...params, + ...scope, + // The schema requires start on every attachment. + start: params.start ?? this.data.created_at, + mediatype: params.mediatype ?? (params.encoding === 'json' ? 'application/json' : undefined) + }); if (!this.data.attachments) { this.data.attachments = []; } @@ -140,6 +336,18 @@ export class Vcon { return attachment; } + /** Lawful basis attachments (`purpose: "lawful_basis"`), optionally for one party. */ + findLawfulBasisAttachments(party?: number): Attachment[] { + return (this.data.attachments ?? []).filter( + a => a.purpose === 'lawful_basis' && (party === undefined || a.party === party) + ); + } + + /** True if the vCon carries at least one `purpose: "lawful_basis"` attachment. */ + hasLawfulBasis(): boolean { + return this.findLawfulBasisAttachments().length > 0; + } + // Analysis methods findAnalysisByType(type: string): Analysis | undefined { @@ -148,10 +356,14 @@ export class Vcon { addAnalysis(params: { type: string; - /** Dialog index/indices; optional when the analysis keys off `attachment` */ + /** Dialog index/indices; optional */ dialog?: number | number[]; + /** Session index/indices the analysis is based on */ + sessions?: number | number[]; /** Attachment index/indices the analysis is based on */ attachment?: number | number[]; + /** Other Analysis index/indices the analysis is based on (never itself) */ + analysis?: number | number[]; vendor?: string; product?: string; schema?: string; @@ -163,16 +375,16 @@ export class Vcon { filename?: string; provenance?: Record; }): void { - // Per draft-ietf-vcon-vcon-core §4.4 the analysis body MUST be a - // string. When callers hand us an object or array we serialize and - // force encoding="json" so the emitted vCon validates. + // The analysis body MUST be a string. When callers hand us an object or + // array we serialize and force encoding="json" so the emitted vCon validates. const { body, encoding, ...rest } = params; const analysis: Analysis = { ...rest }; if (body !== undefined) { if (typeof body === 'string') { analysis.body = body; - if (encoding) analysis.encoding = encoding; + // inline content needs an encoding (schema); a plain string is "none" + analysis.encoding = encoding ?? 'none'; } else { analysis.body = JSON.stringify(body); analysis.encoding = 'json'; @@ -207,15 +419,94 @@ export class Vcon { findDialog(by: string, val: any): DialogClass | undefined { const dialog = this.data.dialog?.find(d => d[by] === val); - return dialog ? new DialogClass(dialog) : undefined; + return dialog ? DialogClass.fromDict(dialog) : undefined; + } + + findDialogsByType(type: string): Dialog[] { + return (this.data.dialog ?? []).filter(d => d.type === type); } - addDialog(dialog: DialogClass): void { + /** + * Add a Dialog and return its index in the `dialog` array. Use + * Dialog.placeholder() to add an empty Dialog Object (`{}`) that holds a position. + * + * @param session Optional index of an existing Session; the new Dialog's + * index is appended to that Session's `dialog` list. Core-05 requires at + * least one Session when the vCon has Dialogs, so add Sessions with addSession(). + */ + addDialog(dialog: DialogClass, session?: number): number { + if (session !== undefined) { + const count = this.data.sessions?.length ?? 0; + if (!Number.isInteger(session) || session < 0 || session >= count) { + throw new Error(`Invalid session index: ${session}`); + } + } if (!this.data.dialog) { this.data.dialog = []; } this.data.dialog.push(dialog.toDict()); + const index = this.data.dialog.length - 1; + if (session !== undefined) { + const s = this.data.sessions![session]; + (s.dialog = s.dialog ?? []).push(index); + } this.data.updated_at = new Date().toISOString(); + return index; + } + + /** + * Add an `incomplete` Dialog (a conversation that failed to be set up) and + * return its index. An incomplete Dialog has no content; `details` is kept in + * `meta.details`. `parties` is the party that attempted the conversation. + */ + addIncompleteDialog(params: { + start: Date | string; + disposition: string; + details?: Record; + parties?: number[]; + meta?: Record; + session?: number; + }): number { + const meta: Record = { ...(params.meta ?? {}) }; + if (params.details) meta.details = params.details; + const dialog = new DialogClass({ + type: 'incomplete', + start: params.start, + parties: params.parties ?? [], + disposition: params.disposition, + ...(Object.keys(meta).length ? { meta } : {}) + }); + return this.addDialog(dialog, params.session); + } + + // Session and Event methods + + /** + * Add a Session Object and return its index in the `sessions` array. With no + * argument an empty placeholder Session (`{}`) is added, which core-05 permits. + */ + addSession(session?: SessionClass | SessionType): number { + let dict: SessionType; + if (session === undefined) dict = {}; + else if (session instanceof SessionClass) dict = session.toDict(); + else dict = clone(session) as SessionType; + if (!this.data.sessions) this.data.sessions = []; + this.data.sessions.push(dict); + this.data.updated_at = new Date().toISOString(); + return this.data.sessions.length - 1; + } + + /** + * Add an Event Object and return its index in the `events` array. An `Event` + * is checked against the per-type parameter table when it is built; a plain + * object is checked by isValid(). + */ + addEvent(event: EventClass | EventType): number { + const dict = event instanceof EventClass ? event.toDict() : (clone(event) as EventType); + if (!this.data.events) this.data.events = []; + this.data.events.push(dict); + this.data.updated_at = new Date().toISOString(); + return this.data.events.length - 1; } // Serialization methods @@ -234,7 +525,7 @@ export class Vcon { return { ...this.data }; } - // Extension methods (vcon-core-01) + // Extension methods /** * Add an extension name to the extensions array @@ -276,6 +567,123 @@ export class Vcon { return this.data.critical?.includes(name) ?? false; } + // Validation + + /** + * Validate the vCon against the core-05 rules. + * + * Checks required fields and types, that `vcon` (if present) is "0.5.0", + * that Sessions, Events, Dialogs, attachments and analysis reference existing + * objects, the per-event-type parameter table, that at least one Session + * exists when there are Dialogs or Events, that attachments have `party` and + * `dialog` or `session`, that `redacted_from` and `amended_from` are + * exclusive, that `extensions` lists every extension in use (and every + * `critical` entry), and that every `__REDACTED_REF_#` has a + * `redacted_strings` entry. + * + * SHOULD-level findings are not errors; see getValidationWarnings(). + */ + isValid(): { valid: boolean; errors: string[] } { + const { errors } = validateVconDict(clone(this.data) as Record); + return { valid: errors.length === 0, errors }; + } + + /** SHOULD-level findings (for example SHOULD NOT parameters on Events). */ + getValidationWarnings(): string[] { + const data = clone(this.data) as Record; + const { warnings } = validateVconDict(data); + // A lawful_basis attachment is scoped with party plus session (extension draft). + (data.attachments ?? []).forEach((a: any, i: number) => { + if (isPlainObject(a) && a.purpose === 'lawful_basis') { + if (!('party' in a)) warnings.push(`lawful_basis attachment at index ${i} has no party.`); + if (!('session' in a)) warnings.push(`lawful_basis attachment at index ${i} has no session; core-05 scopes a lawful basis to Sessions.`); + } + }); + return warnings; + } + + // Signing (JWS, general serialization with one signature) + + /** + * Generate an RSA 2048 key pair for signing vCons. + */ + static generateKeyPair(): { privateKey: nodeCrypto.KeyObject; publicKey: nodeCrypto.KeyObject } { + return nodeCrypto.generateKeyPairSync('rsa', { modulusLength: 2048 }); + } + + /** + * Sign the vCon using JWS: adds `payload` (the base64url vCon JSON) and + * `signatures` to the object. + * + * @param alg JWS algorithm (default "RS256", the value core-05 says SHOULD be + * used). "none" is rejected (6.2.2). + * @throws AlgorithmNotPermittedError if `alg` is "none" (any case) or is not a permitted algorithm. + */ + sign(privateKey: KeyInput, alg: JwsAlgorithm | string = 'RS256'): void { + assertPermittedAlg(alg); + const body: Record = { ...this.data }; + delete body.payload; + delete body.signatures; + const header = b64url(JSON.stringify({ alg, typ: 'JWS' })); + const payload = b64url(JSON.stringify(body)); + const { hash, padding, saltLength, dsaEncoding } = jwsParams(alg); + const key: any = { key: privateKey }; + if (padding !== undefined) { + key.padding = padding; + key.saltLength = saltLength; + } + if (dsaEncoding) key.dsaEncoding = dsaEncoding; + const signature = nodeCrypto.sign(hash, Buffer.from(`${header}.${payload}`), key); + this.data.signatures = [{ protected: header, signature: b64url(signature) }]; + this.data.payload = payload; + } + + /** + * Verify the JWS signature of the vCon. + * + * @returns true if the signature is valid, false otherwise (including when no + * `alg` is declared, or the signature does not match). + * @throws Error if the vCon is not signed. + * @throws AlgorithmNotPermittedError if the signature declares `alg` "none" + * (in the protected header or the signature's header). Verification is + * refused rather than skipped. + */ + verify(publicKey: KeyInput): boolean { + if (!this.data.signatures || !this.data.payload) { + throw new Error('vCon is not signed'); + } + // Refuse alg "none" before anything else, from either header location. + const sig0 = this.data.signatures[0] ?? {}; + const declared: unknown[] = []; + try { + if (sig0.protected) declared.push(JSON.parse(base64UrlDecodeToString(sig0.protected)).alg); + } catch { + return false; // protected header is not valid base64url JSON + } + if (isPlainObject(sig0.header) && 'alg' in sig0.header) declared.push(sig0.header.alg); + for (const a of declared) { + if (typeof a === 'string' && a.trim().toLowerCase() === 'none') { + throw new AlgorithmNotPermittedError('JWS alg "none" is not permitted (core-05 section 6.2.2)'); + } + } + if (declared.length === 0) return false; // fails closed: no alg declared + const alg = declared[0]; + if (typeof alg !== 'string' || !(PERMITTED_JWS_ALGORITHMS as readonly string[]).includes(alg)) return false; + try { + const { hash, padding, saltLength, dsaEncoding } = jwsParams(alg); + const key: any = { key: publicKey }; + if (padding !== undefined) { + key.padding = padding; + key.saltLength = saltLength; + } + if (dsaEncoding) key.dsaEncoding = dsaEncoding; + const data = Buffer.from(`${sig0.protected}.${this.data.payload}`); + return nodeCrypto.verify(hash, data, key, Buffer.from(sig0.signature, 'base64url')); + } catch { + return false; + } + } + // Property getters get parties(): Party[] { @@ -286,6 +694,14 @@ export class Vcon { return this.data.dialog || []; } + get sessions(): SessionType[] { + return this.data.sessions || []; + } + + get events(): EventType[] { + return this.data.events || []; + } + get attachments(): Attachment[] { return this.data.attachments || []; } @@ -298,8 +714,9 @@ export class Vcon { return this.data.uuid!; } - get vcon(): string { - return this.data.vcon || VCON_VERSION; + /** Syntax version, `"0.5.0"` for vCons this library writes; undefined if the input had none. */ + get vcon(): string | undefined { + return this.data.vcon; } get subject(): string | undefined { @@ -319,30 +736,56 @@ export class Vcon { return this.data.updated_at; } - get redacted(): Redacted | boolean | undefined { - return this.data.redacted; + get redacted_from(): Redacted | undefined { + return this.data.redacted_from; } - set redacted(value: Redacted | boolean | undefined) { - if (value !== undefined && this.data.amended !== undefined) { - throw new Error('vCon cannot set redacted while amended is set; the two are mutually exclusive (draft-ietf-vcon-vcon-core §4.1.8/§4.1.9).'); + set redacted_from(value: Redacted | undefined) { + if (value !== undefined && this.data.amended_from !== undefined) { + throw new Error('vCon cannot set redacted_from while amended_from is set; the two are mutually exclusive.'); } - this.data.redacted = value; + this.data.redacted_from = value; this.data.updated_at = new Date().toISOString(); } - get amended(): Amended | boolean | undefined { - return this.data.amended; + get amended_from(): Amended | undefined { + return this.data.amended_from; } - set amended(value: Amended | boolean | undefined) { - if (value !== undefined && this.data.redacted !== undefined) { - throw new Error('vCon cannot set amended while redacted is set; the two are mutually exclusive (draft-ietf-vcon-vcon-core §4.1.8/§4.1.9).'); + set amended_from(value: Amended | undefined) { + if (value !== undefined && this.data.redacted_from !== undefined) { + throw new Error('vCon cannot set amended_from while redacted_from is set; the two are mutually exclusive.'); } - this.data.amended = value; + this.data.amended_from = value; this.data.updated_at = new Date().toISOString(); } + /** @deprecated 0.4.0 name; use redacted_from. */ + get redacted(): Redacted | undefined { + warn('Vcon.redacted is deprecated; use Vcon.redacted_from (core-05)'); + return this.redacted_from; + } + + set redacted(value: Redacted | undefined) { + warn('Vcon.redacted is deprecated; use Vcon.redacted_from (core-05)'); + this.redacted_from = value; + } + + /** @deprecated 0.4.0 name; use amended_from. */ + get amended(): Amended | undefined { + warn('Vcon.amended is deprecated; use Vcon.amended_from (core-05)'); + return this.amended_from; + } + + set amended(value: Amended | undefined) { + warn('Vcon.amended is deprecated; use Vcon.amended_from (core-05)'); + this.amended_from = value; + } + + get redacted_strings(): RedactedString[] { + return this.data.redacted_strings || []; + } + get extensions(): string[] | undefined { return this.data.extensions; } From f14e87dfff14893b5f600c9899487c55c309aa70 Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:36:00 -0500 Subject: [PATCH 3/6] Test the core-05 port Port the reference tests for migration (index stability, transfer, party_history, recording-set, signed input not migrated on load), Session, Event table, signing and extensions enforcement. Validate the Appendix B examples and library output against the Appendix C JSON schema. Update the existing suites for the removed Dialog types and the new attachment scope. Co-Authored-By: Claude Opus 5.5 --- src/__tests__/attachment.test.ts | 31 +- src/__tests__/core-latest.test.ts | 38 +- src/__tests__/core05-changes.test.ts | 371 +++++++++ src/__tests__/dialog.test.ts | 82 +- src/__tests__/migration.test.ts | 994 +++++++++++++++++++++++ src/__tests__/schema-conformance.test.ts | 158 +++- src/__tests__/session-event.test.ts | 254 ++++++ src/__tests__/validation.test.ts | 34 +- src/__tests__/vcon.test.ts | 57 +- 9 files changed, 1881 insertions(+), 138 deletions(-) create mode 100644 src/__tests__/core05-changes.test.ts create mode 100644 src/__tests__/migration.test.ts create mode 100644 src/__tests__/session-event.test.ts diff --git a/src/__tests__/attachment.test.ts b/src/__tests__/attachment.test.ts index 0611f7c..107d2a9 100644 --- a/src/__tests__/attachment.test.ts +++ b/src/__tests__/attachment.test.ts @@ -62,11 +62,19 @@ describe('Attachment', () => { }).toThrow('Invalid encoding: base64. Must be one of base64url, json, none'); }); - it('should default party and dialog to 0 (vCon-level) when omitted', () => { + it('should default party to 0 but never default dialog or session', () => { const attachment = new Attachment({ purpose: 'tags', body: '{}' }); expect(attachment.party).toBe(0); - expect(attachment.dialog).toBe(0); + expect(attachment.dialog).toBeUndefined(); + expect(attachment.session).toBeUndefined(); + expect(attachment.validate().errors).toContain('Attachment needs at least one of dialog or session'); + }); + + it('should accept a session index or list as the scope', () => { + const a = new Attachment({ purpose: 'note', start: '2026-01-01T00:00:00Z', session: [0, 1], body: 'x' }); + expect(a.validate().valid).toBe(true); + expect(a.toDict().session).toEqual([0, 1]); }); it('should have valid encodings constant', () => { @@ -113,7 +121,8 @@ describe('Attachment', () => { purpose: 'contract', start, party: 0, - dialog: [0, 1], + dialog: 1, + session: [0, 1], mediatype: 'application/pdf', filename: 'contract.pdf', body: 'base64content', @@ -123,7 +132,8 @@ describe('Attachment', () => { expect(attachment.purpose).toBe('contract'); expect(attachment.start).toBe(start); expect(attachment.party).toBe(0); - expect(attachment.dialog).toEqual([0, 1]); + expect(attachment.dialog).toBe(1); + expect(attachment.session).toEqual([0, 1]); expect(attachment.mediatype).toBe('application/pdf'); expect(attachment.filename).toBe('contract.pdf'); }); @@ -141,20 +151,15 @@ describe('Attachment', () => { }); it('should validate attachment correctly', () => { - // Valid attachment with purpose (party/dialog default to 0) - const validWithPurpose = new Attachment({ purpose: 'transcript', body: 'content' }); + // Valid attachment: purpose, start, party (defaults to 0) and a scope + const validWithPurpose = new Attachment({ purpose: 'transcript', body: 'content', start: '2026-01-01T00:00:00Z', dialog: 0 }); expect(validWithPurpose.validate().valid).toBe(true); - // Valid lawful_basis extension attachment (the one allowed `type:` exception) - const lawfulBasis = new Attachment({ body: '{}' } as any); - (lawfulBasis as any).type = 'lawful_basis'; - expect(lawfulBasis.validate().valid).toBe(true); - // Invalid - no purpose - const noPurpose = new Attachment({ body: 'content' }); + const noPurpose = new Attachment({ body: 'content', start: '2026-01-01T00:00:00Z', dialog: 0 }); const result1 = noPurpose.validate(); expect(result1.valid).toBe(false); - expect(result1.errors).toContain('Attachment must have a purpose (or be the lawful_basis extension)'); + expect(result1.errors).toContain('Attachment must have a purpose'); // Invalid - both inline and external data const bothData = new Attachment({ diff --git a/src/__tests__/core-latest.test.ts b/src/__tests__/core-latest.test.ts index 3a509d0..02274c9 100644 --- a/src/__tests__/core-latest.test.ts +++ b/src/__tests__/core-latest.test.ts @@ -5,43 +5,17 @@ import { Party } from '../party'; /** * Round-trip coverage for the additions in the current core draft * (draft-ietf-vcon-vcon-core, past -02) and the provenance extension: - * - recording-set dialog type + recordings[] / recording_set + * - (recording-set and transfer Dialogs are gone in core-05: Sessions and Events) * - Analysis based on an attachment (dialog optional) * - provenance parameter on dialog and analysis * - Party type/org/dept fields */ describe('core-latest additions', () => { - it('supports recording-set dialogs with recordings and recording_set', () => { - const set = new Dialog({ - type: 'recording-set', - start: '2026-01-15T10:30:00Z', - recordings: [1, 2] - }); - expect(set.isRecordingSet()).toBe(true); - expect(Dialog.DIALOG_TYPES).toContain('recording-set'); - - const member = new Dialog({ - type: 'recording', - start: '2026-01-15T10:30:00Z', - parties: [0, 1], - recording_set: 0 - }); - - const dict = set.toDict(); - expect(dict.type).toBe('recording-set'); - expect(dict.recordings).toEqual([1, 2]); - expect(member.toDict().recording_set).toBe(0); - }); - - it('widens transfer index fields to accept arrays', () => { - const d = new Dialog({ - type: 'transfer', - start: '2026-01-15T10:30:00Z', - original: [0, 1], - target_dialog: 2 - }); - expect(d.toDict().original).toEqual([0, 1]); - expect(d.toDict().target_dialog).toBe(2); + it('no longer has recording-set or transfer Dialog types', () => { + expect(Dialog.DIALOG_TYPES).not.toContain('recording-set'); + expect(Dialog.DIALOG_TYPES).not.toContain('transfer'); + expect(() => new Dialog({ type: 'recording', start: '2026-01-15T10:30:00Z', recording_set: 0 })).toThrow(/removed/); + expect(() => new Dialog({ type: 'recording-set', start: '2026-01-15T10:30:00Z', recordings: [1] })).toThrow(/removed/); }); it('allows analysis keyed off an attachment with no dialog', () => { diff --git a/src/__tests__/core05-changes.test.ts b/src/__tests__/core05-changes.test.ts new file mode 100644 index 0000000..de6a352 --- /dev/null +++ b/src/__tests__/core05-changes.test.ts @@ -0,0 +1,371 @@ +import * as crypto from 'crypto'; +import { Vcon, AlgorithmNotPermittedError } from '../vcon'; +import { Dialog } from '../dialog'; +import { Party } from '../party'; + +const T = '2026-01-01T00:00:00Z'; + +function base(): Vcon { + const v = Vcon.buildNew(); + v.addParty(new Party({ name: 'Alice', tel: '+12025550101' })); + v.addParty(new Party({ name: 'Bob', tel: '+12025550102' })); + return v; +} + +function withSession(): Vcon { + const v = base(); + v.addSession({ start: T, parties: [0, 1] }); + return v; +} + +const att = (extra: Record = {}) => ({ + purpose: 'note', start: T, party: 0, body: 'x', encoding: 'none', mediatype: 'text/plain', ...extra +}); + +describe('redacted_from and amended_from', () => { + it('are mutually exclusive in the validator', () => { + const v = base(); + v.data.redacted_from = { type: 'pii' }; + v.data.amended_from = { uuid: 'u' }; + expect(v.isValid().errors).toContain('redacted_from and amended_from are mutually exclusive.'); + }); + + it('needs a content_hash with a url', () => { + const v = base(); + v.redacted_from = { type: 'pii', url: 'https://example.com/o.json' }; + expect(v.isValid().errors).toContain('redacted_from with url must include content_hash.'); + v.redacted_from = undefined; + v.amended_from = { url: 'https://example.com/o.json' }; + expect(v.isValid().errors).toContain('amended_from with url must include content_hash.'); + }); + + it('needs a uuid or url for amended_from, and a type for redacted_from', () => { + const v = base(); + v.amended_from = {}; + expect(v.isValid().errors).toContain('amended_from must include uuid, or an external reference (url).'); + v.amended_from = undefined; + v.redacted_from = {}; + expect(v.isValid().errors).toContain('redacted_from is missing required field: type'); + }); + + it('flags the 0.4.0 names when migration is off', () => { + const v = new Vcon({ vcon: '0.4.0', uuid: 'u', created_at: T, redacted: { type: 'pii' }, parties: [] }, { migrateLegacy: false }); + expect(v.isValid().errors.some(e => /Legacy 0.4.0 parameter 'redacted'/.test(e))).toBe(true); + }); +}); + +describe('attachment scope', () => { + it('needs party plus dialog or session', () => { + const v = withSession(); + v.addDialog(new Dialog({ type: 'text', start: T, parties: [0], body: 'x', mediatype: 'text/plain', encoding: 'none' }), 0); + v.data.attachments = [att()]; + expect(v.isValid().errors).toContain('Attachment at index 0 must have at least one of dialog or session.'); + v.data.attachments = [att({ session: 0 })]; + expect(v.isValid().valid).toBe(true); + v.data.attachments = [att({ dialog: 0 })]; + expect(v.isValid().valid).toBe(true); + v.data.attachments = [att({ dialog: 0, session: [0] })]; + expect(v.isValid().valid).toBe(true); + const { party: _party, ...noParty } = att({ session: 0 }); + v.data.attachments = [noParty]; + expect(v.isValid().errors).toContain('Attachment at index 0 is missing required field: party'); + }); + + it('reports bad references', () => { + const v = withSession(); + v.data.attachments = [att({ session: [0, 4], dialog: 9, party: 7 })]; + const errors = v.isValid().errors; + expect(errors).toContain('Attachment at index 0 references invalid session index: 4'); + expect(errors).toContain('Attachment at index 0 references invalid dialog index: 9'); + expect(errors).toContain('Attachment at index 0 references invalid party index: 7'); + }); + + it('defaults the scope to the only Session', () => { + const v = withSession(); + v.addAttachment({ purpose: 'note', body: 'x', encoding: 'none', mediatype: 'text/plain' }); + expect(v.attachments[0].session).toBe(0); + expect(v.attachments[0].dialog).toBeUndefined(); + expect(v.attachments[0].start).toBe(v.created_at); + expect(v.isValid().valid).toBe(true); + }); + + it('has no default scope with several Sessions or none, and invents no placeholder Session', () => { + const v = withSession(); + v.addSession({ start: T, parties: [0] }); + expect(() => v.addAttachment({ purpose: 'note', body: 'x', encoding: 'none' })).toThrow(/needs dialog or session/); + const none = base(); + expect(() => none.addAttachment({ purpose: 'note', body: 'x', encoding: 'none' })).toThrow(/needs dialog or session/); + expect(none.sessions).toEqual([]); + }); + + it('never widens a dialog index to a Session', () => { + const v = withSession(); + v.addAttachment({ purpose: 'note', dialog: 0, body: 'x', encoding: 'none', mediatype: 'text/plain' }); + expect(v.attachments[0].dialog).toBe(0); + expect('session' in v.attachments[0]).toBe(false); + }); + + it('lets tags describe the whole vCon', () => { + const v = withSession(); + v.addSession({ start: T, parties: [1] }); + v.addTag('k', 'v'); + expect(v.attachments[0].session).toEqual([0, 1]); + expect(v.isValid().valid).toBe(true); + }); + + it('lets a redacted attachment lack content', () => { + const v = withSession(); + v.data.redacted_from = { type: 'pii' }; + v.data.attachments = [{ purpose: 'note', start: T, party: 0, session: 0 }]; + expect(v.isValid().valid).toBe(true); + }); +}); + +describe('analysis references', () => { + it('needs no dialog and checks the new references', () => { + const v = withSession(); + v.addAnalysis({ type: 'summary', vendor: 'v', body: 's', sessions: 0 }); + expect(v.isValid().valid).toBe(true); + v.addAnalysis({ type: 'x', vendor: 'v', body: 's', sessions: 3, attachment: 2, analysis: 1 }); + const errors = v.isValid().errors; + expect(errors).toContain('Analysis at index 1 references invalid session index: 3'); + expect(errors).toContain('Analysis at index 1 references invalid attachment index: 2'); + expect(errors).toContain('Analysis at index 1 must not reference itself in analysis.'); + }); +}); + +describe('Dialog rules', () => { + it('keeps indices with an empty Dialog and accepts nulls and lists in parties', () => { + const v = withSession(); + v.addDialog(Dialog.placeholder()); + v.addDialog(new Dialog({ type: 'recording', start: T, parties: [null, [0, 1]], mediatype: 'audio/wav' }), 0); + expect(v.dialog[0]).toEqual({}); + expect(v.sessions[0].dialog).toEqual([1]); + expect(v.isValid()).toEqual({ valid: true, errors: [] }); + }); + + it('gives an incomplete Dialog no content', () => { + const v = withSession(); + const i = v.addIncompleteDialog({ start: T, disposition: 'no-answer', details: { ring: 45 }, parties: [0], session: 0 }); + expect(v.dialog[i]).toEqual({ type: 'incomplete', start: T, parties: [0], disposition: 'no-answer', meta: { details: { ring: 45 } } }); + expect('body' in v.dialog[i]).toBe(false); + expect(v.isValid().valid).toBe(true); + }); + + it('fails validation on removed types and parameters', () => { + const v = withSession(); + v.data.dialog = [{ type: 'transfer', start: T }, { type: 'recording', start: T, originator: 0, mediatype: 'audio/wav' }]; + const errors = v.isValid().errors; + expect(errors.some(e => /type 'transfer', which was removed in 0.5.0/.test(e))).toBe(true); + expect(errors).toContain("Dialog at index 1 has parameter 'originator', which was removed in 0.5.0."); + }); + + it('accepts mediatype parameters and multipart subtypes', () => { + const v = withSession(); + v.addDialog( + new Dialog({ type: 'text', start: T, parties: [0], mediatype: 'multipart/alternative; boundary=abc', body: 'x', encoding: 'none' }), + 0 + ); + expect(v.isValid().valid).toBe(true); + }); + + it('checks redacted_segments', () => { + const v = withSession(); + v.addDialog(new Dialog({ type: 'text', start: T, parties: [0], body: 'x', mediatype: 'text/plain', encoding: 'none', redacted_segments: [{ start: 0 } as any] }), 0); + expect(v.isValid().errors).toContain('Dialog at index 0 redacted_segments[0] requires start and end.'); + }); + + it('reads audio and video Dialogs with a warning, never as an error', () => { + const v = withSession(); + v.data.dialog = [{ type: 'audio', start: T, parties: [0], mediatype: 'audio/wav' }]; + v.data.sessions![0].dialog = [0]; + expect(v.isValid().valid).toBe(true); + expect(v.getValidationWarnings().some(w => /read as 'recording'/.test(w))).toBe(true); + }); +}); + +describe('extensions enforcement', () => { + it('requires lawful_basis and wtf_transcription to be listed', () => { + const v = withSession(); + v.addAttachment({ purpose: 'lawful_basis', party: 0, session: 0, body: { lawful_basis: 'consent' } as any, encoding: 'json' }); + expect(v.isValid().errors).toContain("Extension 'lawful_basis' is in use but is not listed in the extensions parameter."); + v.addExtension('lawful_basis'); + expect(v.isValid().valid).toBe(true); + v.addAnalysis({ type: 'wtf_transcription', vendor: 'v', body: { a: 1 }, dialog: undefined, sessions: 0 }); + expect(v.isValid().errors).toContain("Extension 'wtf_transcription' is in use but is not listed in the extensions parameter."); + }); + + it('requires critical entries to be listed in extensions', () => { + const v = base(); + v.data.critical = ['x']; + expect(v.isValid().errors).toContain("Extension 'x' is listed in critical but not in extensions."); + v.addCriticalExtension('y'); + expect(v.isValid().errors).toEqual(["Extension 'x' is listed in critical but not in extensions."]); + }); + + it('needs some extension for values outside the core vocabulary', () => { + const v = withSession(); + v.data.dialog = [{ type: 'text', start: T, parties: [0], body: 'x', mediatype: 'text/plain', encoding: 'gzip' }]; + v.data.sessions![0].dialog = [0]; + expect(v.isValid().errors.some(e => /outside the core vocabulary/.test(e))).toBe(true); + v.addExtension('compression'); + expect(v.isValid().valid).toBe(true); + }); + + it('requires a mediatype on inline attachment content', () => { + const v = withSession(); + v.data.attachments = [{ purpose: 'note', start: T, party: 0, session: 0, body: 'x', encoding: 'none' }]; + expect(v.isValid().errors).toContain('Attachment at index 0 is missing required field: mediatype (needed for inline content)'); + }); +}); + +describe('lawful basis', () => { + it('finds lawful_basis attachments and reports a vCon without one', () => { + const v = withSession(); + expect(v.hasLawfulBasis()).toBe(false); + v.data.extensions = ['lawful_basis']; + v.data.attachments = [{ purpose: 'lawful_basis', start: T, party: 1, dialog: undefined, session: 0, body: { lawful_basis: 'consent' }, encoding: 'json', mediatype: 'application/json' }]; + expect(v.hasLawfulBasis()).toBe(true); + expect(v.findLawfulBasisAttachments(1)).toHaveLength(1); + expect(v.findLawfulBasisAttachments(0)).toHaveLength(0); + expect(v.getValidationWarnings().some(w => /lawful_basis/.test(w))).toBe(false); + }); + + it('warns when a lawful_basis attachment has no session or no party', () => { + const v = withSession(); + v.data.extensions = ['lawful_basis']; + v.data.attachments = [{ purpose: 'lawful_basis', start: T, dialog: 0, body: {}, encoding: 'json', mediatype: 'application/json' }]; + const warnings = v.getValidationWarnings(); + expect(warnings.some(w => /no party/.test(w))).toBe(true); + expect(warnings.some(w => /no session/.test(w))).toBe(true); + }); +}); + +describe('redacted_strings', () => { + it('needs an entry for every reference', () => { + const v = withSession(); + v.addDialog(new Dialog({ type: 'text', start: T, parties: [0], body: 'call __REDACTED_REF_7 now', mediatype: 'text/plain', encoding: 'none' }), 0); + expect(v.isValid().errors).toContain('__REDACTED_REF_7 appears in the vCon but has no entry in redacted_strings.'); + v.data.redacted_strings = [{ ref: 7 }]; + expect(v.isValid().valid).toBe(true); + }); + + it('checks the ref range and duplicates', () => { + const v = base(); + v.data.redacted_strings = [{ ref: 0 }, { ref: 5 }, { ref: 5 }, { ref: 100000 }]; + const errors = v.isValid().errors; + expect(errors).toContain('redacted_strings[0] ref must be between 1 and 99999.'); + expect(errors).toContain('redacted_strings[2] duplicates ref 5.'); + expect(errors).toContain('redacted_strings[3] ref must be between 1 and 99999.'); + }); +}); + +describe('version handling', () => { + it('emits 0.5.0 from buildNew', () => { + expect(Vcon.buildNew().vcon).toBe('0.5.0'); + }); + + it('accepts an absent vcon', () => { + const v = new Vcon({ uuid: 'u', created_at: T, parties: [] }); + expect(v.vcon).toBeUndefined(); + expect(v.isValid().valid).toBe(true); + }); + + it('rejects other versions', () => { + const v = new Vcon({ vcon: '0.0.1', uuid: 'u', created_at: T }); + expect(v.isValid().errors.some(e => /Unsupported vcon syntax version '0.0.1'/.test(e))).toBe(true); + }); +}); + +describe('signing', () => { + const { privateKey, publicKey } = Vcon.generateKeyPair(); + + it('rejects alg none on sign, in any case', () => { + const v = base(); + for (const alg of ['none', 'NONE', 'None']) { + expect(() => v.sign(privateKey, alg)).toThrow(AlgorithmNotPermittedError); + } + }); + + it('rejects an unsupported alg', () => { + expect(() => base().sign(privateKey, 'HS256')).toThrow(AlgorithmNotPermittedError); + }); + + it('signs with RS256 by default and verifies', () => { + const v = base(); + v.sign(privateKey); + const header = JSON.parse(Buffer.from(v.data.signatures![0].protected!, 'base64url').toString()); + expect(header.alg).toBe('RS256'); + expect(v.verify(publicKey)).toBe(true); + }); + + it.each(['RS384', 'RS512', 'PS256'])('signs and verifies with %s', alg => { + const v = base(); + v.sign(privateKey, alg); + expect(v.verify(publicKey)).toBe(true); + }); + + it('signs and verifies with ES256 and EdDSA', () => { + const ec = crypto.generateKeyPairSync('ec', { namedCurve: 'P-256' }); + const v = base(); + v.sign(ec.privateKey, 'ES256'); + expect(v.verify(ec.publicKey)).toBe(true); + const ed = crypto.generateKeyPairSync('ed25519'); + const w = base(); + w.sign(ed.privateKey, 'EdDSA'); + expect(w.verify(ed.publicKey)).toBe(true); + }); + + it('refuses alg none in the protected header', () => { + const v = base(); + v.sign(privateKey); + v.data.signatures![0].protected = Buffer.from(JSON.stringify({ alg: 'none' })).toString('base64url'); + expect(() => v.verify(publicKey)).toThrow(AlgorithmNotPermittedError); + }); + + it('refuses alg none in the header object', () => { + const v = base(); + v.sign(privateKey); + v.data.signatures![0].header = { alg: 'None' }; + expect(() => v.verify(publicKey)).toThrow(AlgorithmNotPermittedError); + }); + + it('fails closed without an alg', () => { + const v = base(); + v.sign(privateKey); + v.data.signatures![0].protected = Buffer.from(JSON.stringify({ typ: 'JWS' })).toString('base64url'); + expect(v.verify(publicKey)).toBe(false); + }); + + it('returns false for the wrong key or a tampered payload and throws when unsigned', () => { + const v = base(); + v.sign(privateKey); + expect(v.verify(Vcon.generateKeyPair().publicKey)).toBe(false); + v.data.payload = Buffer.from('{}').toString('base64url'); + expect(v.verify(publicKey)).toBe(false); + expect(() => base().verify(publicKey)).toThrow(/not signed/); + }); + + it('re-signing does not embed the earlier signature in the payload', () => { + const v = base(); + v.sign(privateKey); + v.sign(privateKey); + const payload = JSON.parse(Buffer.from(v.data.payload!, 'base64url').toString()); + expect(payload.signatures).toBeUndefined(); + expect(payload.payload).toBeUndefined(); + }); +}); + +describe('deprecated 0.4.0 API', () => { + it('keeps redacted and amended as aliases that warn', () => { + const spy = jest.spyOn(process, 'emitWarning').mockImplementation(() => undefined); + try { + const v = base(); + v.amended = { uuid: 'u' }; + expect(v.amended_from).toEqual({ uuid: 'u' }); + expect(spy).toHaveBeenCalled(); + } finally { + spy.mockRestore(); + } + }); +}); diff --git a/src/__tests__/dialog.test.ts b/src/__tests__/dialog.test.ts index de0f27d..a14feef 100644 --- a/src/__tests__/dialog.test.ts +++ b/src/__tests__/dialog.test.ts @@ -1,5 +1,4 @@ import { Dialog } from '../dialog'; -import { PartyHistory } from '../party'; describe('Dialog', () => { it('should create a dialog with minimal properties', () => { @@ -40,13 +39,11 @@ describe('Dialog', () => { it('should create a dialog with all properties', () => { const start = new Date(); - const partyHistory = new PartyHistory(0, 'join', start); const dialog = new Dialog({ type: 'text', start, parties: [0, 1], - originator: 0, mediatype: 'text/plain', filename: 'conversation.txt', body: 'Hello!', @@ -54,24 +51,17 @@ describe('Dialog', () => { alg: 'sha256', signature: 'signature', disposition: 'no-answer', - party_history: [partyHistory.toDict()], - transferee: 1, - transferor: 0, - transfer_target: 2, - original: 0, - consultation: 1, - target_dialog: 0, campaign: 'support', interaction: 'call', skill: 'sales', duration: 300, + redacted_segments: [{ start: 0, end: 3 }], meta: { key: 'value' } }); expect(dialog.type).toBe('text'); expect(dialog.start).toBe(start); expect(dialog.parties).toEqual([0, 1]); - expect(dialog.originator).toBe(0); expect(dialog.mediatype).toBe('text/plain'); expect(dialog.filename).toBe('conversation.txt'); expect(dialog.body).toBe('Hello!'); @@ -79,20 +69,29 @@ describe('Dialog', () => { expect(dialog.alg).toBe('sha256'); expect(dialog.signature).toBe('signature'); expect(dialog.disposition).toBe('no-answer'); - expect(dialog.party_history).toBeDefined(); - expect(dialog.transferee).toBe(1); - expect(dialog.transferor).toBe(0); - expect(dialog.transfer_target).toBe(2); - expect(dialog.original).toBe(0); - expect(dialog.consultation).toBe(1); - expect(dialog.target_dialog).toBe(0); expect(dialog.campaign).toBe('support'); expect(dialog.interaction).toBe('call'); expect(dialog.skill).toBe('sales'); expect(dialog.duration).toBe(300); + expect(dialog.redacted_segments).toEqual([{ start: 0, end: 3 }]); expect(dialog.meta).toEqual({ key: 'value' }); }); + it.each([ + 'originator', + 'party_history', + 'transferee', + 'transferor', + 'transfer_target', + 'original', + 'consultation', + 'target_dialog', + 'recordings', + 'recording_set' + ])('rejects the 0.4.0 parameter %s', key => { + expect(() => new Dialog({ type: 'recording', start: new Date(), [key]: 0 })).toThrow(/removed in vCon 0.5.0/); + }); + it('should handle external data with new API', () => { const dialog = new Dialog({ type: 'recording', @@ -146,7 +145,6 @@ describe('Dialog', () => { }); expect(textDialog.isText()).toBe(true); expect(textDialog.isRecording()).toBe(false); - expect(textDialog.isTransfer()).toBe(false); expect(textDialog.isIncomplete()).toBe(false); const recordingDialog = new Dialog({ @@ -157,12 +155,8 @@ describe('Dialog', () => { expect(recordingDialog.isRecording()).toBe(true); expect(recordingDialog.isText()).toBe(false); - const transferDialog = new Dialog({ - type: 'transfer', - start: new Date(), - parties: [0] - }); - expect(transferDialog.isTransfer()).toBe(true); + // isTransfer() is deprecated and always false: transfers are Events now. + expect(textDialog.isTransfer()).toBe(false); const incompleteDialog = new Dialog({ type: 'incomplete', @@ -227,7 +221,7 @@ describe('Dialog', () => { }); it('should have valid dialog types constant', () => { - expect(Dialog.DIALOG_TYPES).toEqual(['recording', 'text', 'transfer', 'incomplete', 'recording-set']); + expect(Dialog.DIALOG_TYPES).toEqual(['recording', 'text', 'incomplete']); }); it('should have valid dispositions constant', () => { @@ -319,4 +313,40 @@ describe('Dialog', () => { remote: '550e8400-e29b-41d4-a716-446655440001' }); }); + + it('builds an empty placeholder Dialog that serializes as {}', () => { + const d = Dialog.placeholder(); + expect(d.isPlaceholder()).toBe(true); + expect(d.toDict()).toEqual({}); + expect(d.validate().valid).toBe(true); + }); + + it('builds a recording Dialog for the legacy audio and video types and warns', () => { + const spy = jest.spyOn(process, 'emitWarning').mockImplementation(() => undefined); + try { + expect(new Dialog({ type: 'audio', start: new Date() }).type).toBe('recording'); + expect(new Dialog({ type: 'video', start: new Date() }).type).toBe('recording'); + expect(spy).toHaveBeenCalledTimes(2); + } finally { + spy.mockRestore(); + } + }); + + it('accepts null and nested entries in parties', () => { + const d = new Dialog({ type: 'recording', start: new Date(), parties: [[0, 2], null, 1] }); + expect(d.toDict().parties).toEqual([[0, 2], null, 1]); + }); + + it('rejects content on an incomplete Dialog', () => { + const d = new Dialog({ type: 'incomplete', start: new Date(), disposition: 'busy', body: 'x', mediatype: 'text/plain' }); + const { valid, errors } = d.validate(); + expect(valid).toBe(false); + expect(errors).toContain('Incomplete dialog MUST NOT include body'); + expect(errors).toContain('Incomplete dialog MUST NOT include mediatype'); + }); + + it('Dialog.fromDict wraps a legacy Dialog without throwing', () => { + const d = Dialog.fromDict({ type: 'transfer', start: '2025-01-01T00:00:00Z', transferor: 0 }); + expect(d.type).toBe('transfer'); + }); }); diff --git a/src/__tests__/migration.test.ts b/src/__tests__/migration.test.ts new file mode 100644 index 0000000..58e1179 --- /dev/null +++ b/src/__tests__/migration.test.ts @@ -0,0 +1,994 @@ +import Ajv, { ValidateFunction } from 'ajv'; +import addFormats from 'ajv-formats'; +import schema from './fixtures/appendix-c-json-schema.json'; +import { Vcon } from '../vcon'; +import { + migrate040To050, + MigrationError, + MigrationReport, + MIGRATION_STEPS, + FALLBACK, + INFERRED, + UNRESOLVED, + ReportEntry +} from '../migration'; + +/** + * Migration of a 0.4.0 vCon to 0.5.0 (Appendix A.1, steps T1 to T15). + * Ported from the reference implementation's test suite. + */ + +const T0 = '2022-06-21T17:53:26.000+00:00'; +const T1 = '2022-06-21T17:54:00.000+00:00'; +const T2 = '2022-06-21T17:55:00.000+00:00'; + +type D = Record; + +function v04(extra: D = {}): D { + return { + vcon: '0.4.0', + uuid: '01a16b86-9a63-8346-b9a2-279e0d16bc46', + created_at: '2022-06-21T13:53:00-04:00', + parties: [{ name: 'Alice' }, { name: 'Bob' }, { name: 'Carol' }], + dialog: [], + analysis: [], + attachments: [], + ...extra + }; +} + +const rec = (extra: D = {}): D => ({ + type: 'recording', start: T0, duration: 10, parties: [0, 1], + mediatype: 'audio/x-wav', url: 'https://e.com/a.wav', content_hash: 'sha512-x', ...extra +}); +const text = (extra: D = {}): D => ({ + type: 'text', start: T1, parties: [0, 1], body: 'hi', encoding: 'none', mediatype: 'text/plain', ...extra +}); + +let validateSchema: ValidateFunction; +beforeAll(() => { + const ajv = new Ajv({ allErrors: true, strict: false }); + addFormats(ajv); + validateSchema = ajv.compile(schema); +}); + +function checkSchema(vcon: D): void { + if (!validateSchema(vcon)) { + throw new Error('migrated vCon failed schema validation: ' + JSON.stringify(validateSchema.errors)); + } +} + +function migrate(d: D, opts: { strict?: boolean } = {}) { + const { vcon, report } = migrate040To050(d, opts); + checkSchema(vcon); + return { out: vcon, report }; +} + +const kinds = (report: MigrationReport, kind: string, step?: string): ReportEntry[] => + report.entries.filter(e => e.kind === kind && (step === undefined || e.step === step)); + +const b64 = (o: unknown): string => Buffer.from(JSON.stringify(o)).toString('base64url'); + +describe('table driven', () => { + it('has one entry per transform step', () => { + const ids = MIGRATION_STEPS.map(s => s.id); + expect([...ids].sort()).toEqual( + ['T1', 'T2', 'T3', 'T4', 'T6', 'T7', 'T8', 'T9', 'T9b', 'T10', 'T11', 'T12', 'T13', 'T14', 'T15', 'T10b', 'T10c'].sort() + ); + expect(new Set(ids).size).toBe(ids.length); + expect(MIGRATION_STEPS.every(s => s.source && s.title && typeof s.func === 'function')).toBe(true); + }); + + it('runs the steps in the documented order', () => { + const { report } = migrate(v04()); + expect(report.stepsRun).toEqual(MIGRATION_STEPS.map(s => s.id)); + const order = report.stepsRun; + for (const step of ['T8', 'T9', 'T9b', 'T6', 'T2', 'T7', 'T3', 'T4']) { + expect(order.indexOf(step)).toBeLessThan(order.indexOf('T10')); + } + }); + + it('does not modify its input', () => { + const d = v04({ dialog: [rec({ originator: 1, party_history: [{ party: 0, time: T0, event: 'join' }] })] }); + const before = JSON.parse(JSON.stringify(d)); + migrate040To050(d); + expect(d).toEqual(before); + }); + + it('accepts a JSON string', () => { + expect(migrate040To050(JSON.stringify(v04({ dialog: [rec()] }))).vcon.vcon).toBe('0.5.0'); + }); + + it('rejects other versions and garbage', () => { + expect(() => migrate040To050({ vcon: '0.5.0', uuid: 'a', created_at: '2022-01-01T00:00:00Z' })).toThrow(/expected '0.4.0'/); + expect(() => migrate040To050('not json')).toThrow(MigrationError); + expect(() => migrate040To050([1])).toThrow(MigrationError); + }); +}); + +describe('already migrated input', () => { + it('refuses a missing vcon with sessions or events instead of migrating again', () => { + const d = { + uuid: 'u', created_at: T0, parties: [{}, {}], dialog: [rec()], + sessions: [{ start: T0, parties: [1, 0], dialog: [0] }], + events: [{ type: 'join', time: T0, sessions: 0, party: 0 }] + }; + expect(() => migrate040To050(d)).toThrow(/already 0.5.0/); + }); + + it.each(['redacted_from', 'amended_from', 'redacted_strings'])('refuses a missing vcon with %s', key => { + const d: D = { uuid: 'u', created_at: T0, [key]: key === 'redacted_strings' ? [] : { uuid: 'x' } }; + expect(() => migrate040To050(d)).toThrow(/already 0.5.0/); + }); + + it('still migrates a plain 0.4.0 shape with no vcon', () => { + const d = v04({ dialog: [rec()] }); + delete d.vcon; + const { vcon } = migrate040To050(d); + expect(vcon.vcon).toBe('0.5.0'); + expect(vcon.sessions[0].dialog).toEqual([0]); + }); +}); + +describe('T1 version', () => { + it('sets the vcon parameter', () => { + expect(migrate(v04()).out.vcon).toBe('0.5.0'); + }); + + it('sets a missing version and reports it', () => { + const d = v04(); + delete d.vcon; + const { vcon, report } = migrate040To050(d); + expect(vcon.vcon).toBe('0.5.0'); + expect(report.inferred.some(e => e.code === 'AMB-12')).toBe(true); + }); +}); + +describe('T2 Session', () => { + it('adds one Session referencing all Dialogs', () => { + const { out } = migrate(v04({ dialog: [rec(), text()] })); + expect(out.sessions).toHaveLength(1); + expect(out.sessions[0].dialog).toEqual([0, 1]); + }); + + it('matches the Appendix B shape for a simple call', () => { + const { out } = migrate(v04({ dialog: [rec({ parties: [0, 1] })] })); + expect(out.sessions).toEqual([{ start: T0, duration: 10, parties: [0, 1], dialog: [0] }]); + }); + + it('makes no Session without dialog', () => { + const { out } = migrate(v04()); + expect('sessions' in out).toBe(false); + expect('events' in out).toBe(false); + }); + + it('skips the removed positions in the dialog list', () => { + const { out } = migrate(v04({ dialog: [rec(), { type: 'recording-set', recordings: [0], start: T0 }, text()] })); + expect(out.sessions[0].dialog).toEqual([0, 2]); + }); + + it('derives start and duration and reports it', () => { + const { out, report } = migrate(v04({ dialog: [rec(), text({ duration: 5 })] })); + expect(out.sessions[0].start).toBe(T0); + expect(out.sessions[0].duration).toBe(39); // T0 .. (T1 + 5s) = 34s + 5s + expect(report.inferred.some(e => e.message.includes('start/duration derived'))).toBe(true); + }); + + it('gives a text-only Session no duration', () => { + expect('duration' in migrate(v04({ dialog: [text()] })).out.sessions[0]).toBe(false); + }); +}); + +describe('T3 party_history', () => { + const HISTORY = [ + { party: 0, time: T0, event: 'join' }, + { party: 1, time: T0, event: 'join' }, + { party: 1, time: T1, event: 'hold' }, + { party: 0, time: T1, event: 'drop' } + ]; + + it('turns entries into Events with event renamed type', () => { + const { out } = migrate(v04({ dialog: [rec({ party_history: HISTORY })] })); + expect(out.events).toEqual([ + { type: 'join', time: T0, sessions: 0, party: 0 }, + { type: 'join', time: T0, sessions: 0, party: 1 }, + { type: 'hold', time: T1, sessions: 0, party: 1 }, + { type: 'drop', time: T1, sessions: 0, party: 0 } + ]); + expect('party_history' in out.dialog[0]).toBe(false); + }); + + it('keeps Events from referencing the Dialog', () => { + const { out } = migrate(v04({ dialog: [rec({ party_history: HISTORY })] })); + expect(out.events.every((e: D) => !('dialog' in e))).toBe(true); + }); + + it('keeps the button on key events', () => { + const { out } = migrate(v04({ dialog: [rec({ party_history: [{ party: 0, time: T0, event: 'keydown', button: '5' }] })] })); + expect(out.events[0]).toEqual({ type: 'keydown', time: T0, sessions: 0, party: 0, button: '5' }); + }); + + it('lists both Sessions when the Dialog is in two', () => { + const d = v04({ dialog: [rec({ party_history: HISTORY.slice(0, 1) }), { type: 'recording-set', recordings: [0], start: T0 }] }); + const { out, report } = migrate(d); + expect(out.events[0].sessions).toEqual([0, 1]); + expect(report.inferred.some(e => e.code === 'AMB-3')).toBe(true); + }); + + it('uses an empty Party Object for a missing party, or throws in strict mode', () => { + const d = v04({ dialog: [rec({ party_history: [{ time: T0, event: 'join' }] })] }); + const { vcon, report } = migrate040To050(d); + expect(vcon.parties[vcon.events[0].party]).toEqual({}); + expect(report.fallbacks.length).toBeGreaterThan(0); + expect(() => migrate040To050(d, { strict: true })).toThrow(/no party/); + }); + + it('falls back to the Dialog start for a missing time', () => { + const d = v04({ dialog: [rec({ party_history: [{ party: 0, event: 'join' }] })] }); + const { vcon, report } = migrate040To050(d); + expect(vcon.events[0].time).toBe(T0); + expect(report.fallbacks.length).toBeGreaterThan(0); + expect(() => migrate040To050(d, { strict: true })).toThrow(MigrationError); + }); + + it('keeps an unparseable time in the report', () => { + const { report } = migrate(v04({ dialog: [rec({ party_history: [{ party: 0, time: 'yesterday-ish', event: 'join' }] })] })); + const fb = kinds(report, FALLBACK, 'T3'); + expect(fb[0].details.original_time).toBe('yesterday-ish'); + }); + + it('falls back to created_at with no time and no Dialog start', () => { + const d = rec({ party_history: [{ party: 0, event: 'join' }] }); + delete d.start; + const { out, report } = migrate(v04({ dialog: [d] })); + expect(out.events[0].time).toBe('2022-06-21T13:53:00-04:00'); + expect(kinds(report, FALLBACK, 'T3')[0].details.source).toBe('vCon created_at'); + expect(() => migrate040To050(v04({ dialog: [d] }), { strict: true })).toThrow(MigrationError); + }); + + it('carries extension parameters but drops names that clash with core Event parameters', () => { + const { out, report } = migrate(v04({ dialog: [rec({ party_history: [{ party: 0, time: T0, event: 'join', x_reason: 'callback', channel: 3 }] })] })); + expect(out.events[0].x_reason).toBe('callback'); + expect('channel' in out.events[0]).toBe(false); + const e = kinds(report, UNRESOLVED, 'T3').find(x => x.message.includes('non-core'))!; + expect(e.details.dropped).toEqual({ channel: 3 }); + }); + + it('migrates party_history on text and incomplete Dialogs', () => { + const { out } = migrate(v04({ + dialog: [ + text({ parties: [0, 1, 2], party_history: [{ party: 1, time: T1, event: 'join' }] }), + { type: 'incomplete', start: T2, parties: [1, 0], disposition: 'busy', party_history: [{ party: 1, time: T2, event: 'drop' }] } + ] + })); + expect(out.events.map((e: D) => e.type)).toEqual(['join', 'drop']); + expect(out.events.every((e: D) => e.sessions === 0 && !('dialog' in e))).toBe(true); + expect(out.dialog.every((d: D) => !('party_history' in d))).toBe(true); + }); + + it('lists the transfer role Sessions of a Dialog on its Events', () => { + // dialog[0] is in a recording-set and is the transfer's original call + const { out } = migrate(v04({ + dialog: [ + rec({ recording_set: 1, party_history: [{ party: 0, time: T0, event: 'join' }] }), + { type: 'recording-set', recordings: [0] }, + { type: 'transfer', transferee: 0, transferor: 1, transfer_target: 2, original: 0, start: T1 } + ] + })); + const sessionsOf0 = out.sessions.map((s: D, n: number) => ((s.dialog ?? []).includes(0) ? n : -1)).filter((n: number) => n >= 0); + const join = out.events.find((e: D) => e.type === 'join'); + expect([...join.sessions].sort()).toEqual([...sessionsOf0].sort()); + expect(sessionsOf0).toHaveLength(3); + }); +}); + +describe('T4 transfer to Events', () => { + const base = (transfer: D) => + v04({ + dialog: [ + rec(), // 0 original call + rec({ start: T1, parties: [1, 2] }), // 1 consultation call + rec({ start: T2, parties: [0, 2] }), // 2 target call + transfer // 3 transfer dialog + ] + }); + + it('migrates a blind transfer', () => { + const { out } = migrate(base({ type: 'transfer', start: T2, transferee: 0, transferor: 1, transfer_target: 2, original: 0, target_dialog: 2 })); + expect(out.events.map((e: D) => e.type)).toEqual(['blind-transfer']); + const e = out.events[0]; + expect([e.party, e.transferee, e.transfer_target, e.time]).toEqual([1, 0, 2, T2]); + expect('consultation' in e).toBe(false); + expect(out.sessions[e.sessions].dialog).toEqual([0]); + expect(out.sessions[e.target_session].dialog).toEqual([2]); + expect(out.dialog[3]).toEqual({}); + expect(out.sessions.flatMap((s: D) => s.dialog ?? [])).not.toContain(3); + }); + + it('emits two Events sharing the consultation Session for a consultative transfer', () => { + const { out } = migrate(base({ type: 'transfer', start: T2, transferee: 0, transferor: 1, transfer_target: 2, original: 0, consultation: 1, target_dialog: 2 })); + expect(out.events.map((e: D) => e.type)).toEqual(['consultation-start', 'consultative-transfer']); + const [cs, ct] = out.events; + expect(cs.consultation).toBe(ct.consultation); + expect(out.sessions[cs.consultation].dialog).toEqual([1]); + expect(out.sessions[ct.target_session].dialog).toEqual([2]); + expect(cs.sessions).toBe(ct.sessions); + expect('target_session' in cs).toBe(false); + expect(ct.party).toBe(1); + expect(cs.party).toBe(1); + }); + + it('reuses the Session of a recording-set original', () => { + const d = v04({ + dialog: [ + rec(), rec({ start: T2 }), + { type: 'recording-set', start: T0, recordings: [0], parties: [0, 1] }, + { type: 'transfer', start: T2, transferee: 0, transferor: 1, transfer_target: 2, original: 2, target_dialog: 1 } + ] + }); + const { out } = migrate(d); + const e = out.events[0]; + expect(out.sessions[e.sessions].dialog).toEqual([0]); + expect(e.sessions).toBe(1); // the recording-set's Session + }); + + it('reports a time taken from another source', () => { + const { out, report } = migrate(base({ type: 'transfer', transferee: 0, transferor: 1, transfer_target: 2, original: 0, target_dialog: 2 })); + expect(out.events[0].time).toBe(T2); + const entries = report.inferred.filter(e => e.code === 'AMB-7' && e.message.includes('Event time taken from')); + expect(entries.length).toBeGreaterThan(0); + expect(entries[0].message).toContain('target dialog[2]'); + }); + + it('takes the consultation time from the consultation call', () => { + const { out, report } = migrate(base({ type: 'transfer', transferee: 0, transferor: 1, transfer_target: 2, original: 0, consultation: 1, target_dialog: 2 })); + expect(out.events[0].time).toBe(T1); + expect(out.events[1].time).toBe(T2); + expect(report.inferred.filter(e => e.message.includes('Event time taken from'))).toHaveLength(2); + }); + + it('falls back to created_at with no time source, or throws', () => { + const d = v04({ dialog: [rec(), { type: 'transfer', transferee: 0, transferor: 1, transfer_target: 2, original: 0 }] }); + const { vcon, report } = migrate040To050(d); + expect(vcon.events[0].time).toBe(d.created_at); + expect(report.fallbacks.some(e => e.message.includes('created_at'))).toBe(true); + expect(() => migrate040To050(d, { strict: true })).toThrow(/no start and no other time source/); + delete d.created_at; + expect(() => migrate040To050(d)).toThrow(/no time can be sourced/); + }); + + it('maps a transfer with no target to transfer-abandoned', () => { + const { out, report } = migrate(base({ type: 'transfer', start: T2, transferee: 0, transferor: 1, original: 0 })); + const e = out.events[0]; + expect(e.type).toBe('transfer-abandoned'); + expect('transfer_target' in e).toBe(false); + expect('target_session' in e).toBe(false); + expect(report.inferred.some(x => x.code === 'AMB-7')).toBe(true); + }); + + it('gives an uncaptured target call a placeholder Session', () => { + const { out, report } = migrate(base({ type: 'transfer', start: T2, transferee: 0, transferor: 1, transfer_target: 2, original: 0 })); + const e = out.events[0]; + expect(e.type).toBe('blind-transfer'); + expect(out.sessions[e.target_session]).toEqual({}); + expect(report.inferred.some(x => x.message.includes('placeholder Session'))).toBe(true); + }); + + it('uses an empty Party Object for a missing transferor, or throws in strict mode', () => { + const t = { type: 'transfer', start: T2, transferee: 0, transfer_target: 2, original: 0, target_dialog: 2 }; + const { vcon, report } = migrate040To050(base(t)); + expect(vcon.parties[vcon.events[0].party]).toEqual({}); + expect(report.fallbacks.length).toBeGreaterThan(0); + expect(() => migrate040To050(base(t), { strict: true })).toThrow(/no transferor/); + }); + + it('gives a missing original a placeholder Session, or throws in strict mode', () => { + const t = { type: 'transfer', start: T2, transferee: 0, transferor: 1, transfer_target: 2, target_dialog: 2 }; + const { vcon, report } = migrate040To050(base(t)); + expect(vcon.sessions[vcon.events[0].sessions]).toEqual({}); + expect(report.fallbacks.length).toBeGreaterThan(0); + expect(() => migrate040To050(base(t), { strict: true })).toThrow(MigrationError); + }); + + it('keeps unmapped transfer content in the report', () => { + const t = { type: 'transfer', start: T2, transferee: 0, transferor: 1, transfer_target: 2, original: 0, target_dialog: 2, transfer: { reason: 'forwarded' } }; + const { report } = migrate040To050(base(t)); + expect(report.removedDialogs[3].transfer).toEqual({ reason: 'forwarded' }); + expect(report.unresolved.some(e => e.message.includes('no Event equivalent'))).toBe(true); + }); + + it('reports a transfer originator', () => { + const { report } = migrate040To050(v04({ + dialog: [rec(), { type: 'transfer', transferee: 0, transferor: 1, transfer_target: 2, original: 0, start: T1, originator: 1 }] + })); + const e = kinds(report, UNRESOLVED, 'T4').find(x => x.message.includes('no Event equivalent'))!; + expect(e.details.dropped.originator).toBe(1); + }); + + it('uses the recording-set Session when the original is a recording-set', () => { + const { out } = migrate(v04({ + dialog: [ + rec({ recording_set: 1 }), { type: 'recording-set', recordings: [0] }, + { type: 'transfer', transferee: 0, transferor: 1, transfer_target: 2, original: 1, target_dialog: 3, start: T1 }, + rec({ parties: [0, 2], start: T2 }) + ] + })); + const ev = out.events[0]; + expect(ev.sessions).toBe(1); + expect(out.sessions[1].dialog).toEqual([0]); + expect(out.sessions[ev.target_session].dialog).toEqual([3]); + }); + + it('produces Events that pass the parameter table', () => { + const t = { type: 'transfer', start: T2, transferee: 0, transferor: 1, transfer_target: 2, original: 0, consultation: 1, target_dialog: 2 }; + const { out, report } = migrate(base(t)); + expect(report.unresolved).toEqual([]); + expect(new Vcon(out).isValid()).toEqual({ valid: true, errors: [] }); + }); +}); + +describe('T6 originator', () => { + it('moves to the Session when it is not the first party', () => { + const { out } = migrate(v04({ dialog: [rec({ parties: [0, 1], originator: 1 })] })); + expect(out.sessions[0].originator).toBe(1); + expect('originator' in out.dialog[0]).toBe(false); + }); + + it('is dropped when it is the first party', () => { + const { out } = migrate(v04({ dialog: [rec({ parties: [0, 1], originator: 0 })] })); + expect('originator' in out.sessions[0]).toBe(false); + expect('originator' in out.dialog[0]).toBe(false); + }); + + it('reports conflicting originators', () => { + const { out, report } = migrate(v04({ dialog: [rec({ parties: [0, 1, 2], originator: 1 }), text({ parties: [0, 1, 2], originator: 2 })] })); + expect(out.sessions[0].originator).toBe(1); + expect(report.unresolved.some(e => e.message.includes('different originators'))).toBe(true); + }); + + it('makes a text sender the originator', () => { + const { out } = migrate(v04({ dialog: [text({ parties: [0, 1, 2], originator: 2 })] })); + expect(out.dialog[0].parties).toEqual([2]); + expect(out.sessions[0].parties).toEqual([0, 1, 2]); + expect(out.sessions[0].originator).toBe(2); + }); +}); + +describe('T7 recording-set', () => { + const d = () => + v04({ + dialog: [ + rec({ recording_set: 2, start: T0, duration: 4, parties: [0, 1] }), + rec({ recording_set: 2, start: T0, duration: 6, parties: [1, 0] }), + { type: 'recording-set', start: T0, duration: 7, parties: [0, 1], originator: 1, session_id: { local: 'l', remote: 'r' }, recordings: [0, 1] } + ] + }); + + it('becomes a Session', () => { + const { out, report } = migrate(d()); + const s = out.sessions[1]; + expect(s.dialog).toEqual([0, 1]); + expect([s.start, s.duration, s.parties, s.originator]).toEqual([T0, 7, [0, 1], 1]); + expect(s.session_id).toEqual({ local: 'l', remote: 'r' }); + expect(report.inferred.some(e => e.code === 'AMB-4')).toBe(true); + expect(report.unresolved.some(e => e.code === 'AMB-1')).toBe(true); + }); + + it('removes recording_set from the recordings', () => { + const { out } = migrate(d()); + expect(out.dialog.slice(0, 2).every((x: D) => !('recording_set' in x))).toBe(true); + }); + + it('blanks and unlists the recording-set Dialog', () => { + const { out, report } = migrate(d()); + expect(out.dialog[2]).toEqual({}); + expect(report.removedDialogs[2].type).toBe('recording-set'); + expect(out.sessions.every((s: D) => !(s.dialog ?? []).includes(2))).toBe(true); + }); + + it('keeps back-reference-only membership', () => { + const { out, report } = migrate(v04({ dialog: [rec({ recording_set: 1 }), { type: 'recording-set', start: T0 }] })); + expect(out.sessions[1].dialog).toEqual([0]); + expect(report.inferred.some(e => e.step === 'T7' && e.message.includes('recording_set'))).toBe(true); + }); + + it('merges a back reference with a partial recordings list', () => { + const { out } = migrate(v04({ dialog: [rec({ recording_set: 2 }), rec({ recording_set: 2 }), { type: 'recording-set', start: T0, recordings: [0] }] })); + expect(out.sessions[1].dialog).toEqual([0, 1]); + }); + + it('reports a recording_set that points nowhere', () => { + const { report } = migrate040To050(v04({ dialog: [rec({ recording_set: 5 })] })); + expect(kinds(report, UNRESOLVED, 'T7').some(e => e.message.includes('recording_set=5'))).toBe(true); + }); + + it('turns a nested recording-set into a child reference', () => { + const { out } = migrate(v04({ dialog: [rec(), rec(), { type: 'recording-set', recordings: [0, 1] }, { type: 'recording-set', recordings: [2] }] })); + expect(out.sessions[2].sessions).toEqual([{ session: 1, type: 'child' }]); + expect(out.sessions[1].dialog).toEqual([0, 1]); + }); + + it('resolves a nested forward reference', () => { + const { out } = migrate(v04({ dialog: [rec(), { type: 'recording-set', recordings: [2] }, { type: 'recording-set', recordings: [0] }] })); + expect(out.sessions[1].sessions).toEqual([{ session: 2, type: 'child' }]); + expect(out.sessions[2].dialog).toEqual([0]); + }); + + it('reports unmapped recording-set fields with their values', () => { + const { report } = migrate040To050(v04({ dialog: [rec({ recording_set: 1 }), { type: 'recording-set', recordings: [0], application: 'pbx', meta: { k: 1 } }] })); + const e = kinds(report, UNRESOLVED, 'T7').find(x => x.message.includes('no Session equivalent'))!; + expect(e.details.dropped).toEqual({ application: 'pbx', meta: { k: 1 } }); + }); +}); + +describe('T8 and T9 parties', () => { + it('reduces text Dialog parties to the sender and moves receivers to the Session', () => { + const { out } = migrate(v04({ dialog: [text({ parties: [0, 1, 2] })] })); + expect(out.dialog[0].parties).toEqual([0]); + expect(out.sessions[0].parties).toEqual([0, 1, 2]); + }); + + it('reports a thread with different receivers instead of splitting it', () => { + const { out, report } = migrate(v04({ dialog: [text({ parties: [0, 1] }), text({ parties: [1, 0, 2] })] })); + expect(out.sessions).toHaveLength(1); + expect(out.dialog.map((x: D) => x.parties)).toEqual([[0], [1]]); + expect(out.sessions[0].parties).toEqual([0, 1, 2]); + expect(report.unresolved.filter(e => e.code === 'AMB-5').length).toBeGreaterThanOrEqual(1); + }); + + it('reduces incomplete Dialog parties to the originator or the first party', () => { + const inc = { type: 'incomplete', start: T0, parties: [2, 0], disposition: 'no-answer' }; + const a = migrate(v04({ dialog: [inc] })).out; + expect(a.dialog[0].parties).toEqual([2]); + expect(a.sessions[0].parties).toEqual([2, 0]); + const b = migrate(v04({ dialog: [{ ...inc, originator: 0 }] })).out; + expect(b.dialog[0].parties).toEqual([0]); + expect(b.sessions[0].originator).toBe(0); + }); + + it('keeps recording parties and unions them into the Session', () => { + const { out, report } = migrate(v04({ dialog: [rec({ parties: [0, 1] }), rec({ parties: [1, 2] })] })); + expect(out.dialog.map((x: D) => x.parties)).toEqual([[0, 1], [1, 2]]); + expect(out.sessions[0].parties).toEqual([0, 1, 2]); + expect(report.inferred.some(e => e.code === 'AMB-6')).toBe(true); + }); + + it('reports a text Dialog without parties', () => { + const t = text(); + delete t.parties; + const { report } = migrate040To050(v04({ dialog: [t] })); + expect(report.unresolved.some(e => e.message.includes('has no parties'))).toBe(true); + }); + + it('does not promote a receiver when the text sender is null', () => { + const { out, report } = migrate(v04({ dialog: [text({ parties: [null, 1, 2] })] })); + const sender = out.dialog[0].parties[0]; + expect([1, 2]).not.toContain(sender); + expect(out.parties[sender]).toEqual({}); + const s = out.sessions[0]; + expect(s.parties[0] === sender || s.originator === sender).toBe(true); + expect(kinds(report, UNRESOLVED, 'T8').some(e => e.message.includes('null'))).toBe(true); + }); + + it('does not promote a receiver when the incomplete originator is null', () => { + const { out } = migrate(v04({ dialog: [{ type: 'incomplete', start: T0, parties: [null, 2], disposition: 'no-answer' }] })); + const who = out.dialog[0].parties[0]; + expect(who).not.toBe(2); + expect(out.parties[who]).toEqual({}); + }); + + it('keeps a null recording channel', () => { + expect(migrate(v04({ dialog: [rec({ parties: [null, 1] })] })).out.dialog[0].parties).toEqual([null, 1]); + }); +}); + +describe('T10 empty Dialogs and AMB-2', () => { + it('blanks removed Dialogs in place', () => { + const d = v04({ + dialog: [ + rec(), + { type: 'transfer', start: T1, transferee: 0, transferor: 1, transfer_target: 2, original: 0, target_dialog: 3 }, + text(), + rec({ start: T2 }) + ] + }); + const { out, report } = migrate(d); + expect(out.dialog).toHaveLength(4); + expect(out.dialog[1]).toEqual({}); + expect([out.dialog[2].type, out.dialog[3].start]).toEqual(['text', T2]); + expect(Object.keys(report.removedDialogs).map(Number)).toEqual([1]); + }); + + it('re-points analysis on a recording-set', () => { + const d = v04({ + dialog: [rec({ recording_set: 1 }), { type: 'recording-set', start: T0, recordings: [0] }], + analysis: [{ type: 'summary', dialog: 1, vendor: 'v', body: 's', encoding: 'none' }] + }); + const { out, report } = migrate(d); + expect([out.analysis[0].dialog, out.analysis[0].sessions]).toEqual([0, 1]); + expect(report.inferred.some(e => e.code === 'AMB-2')).toBe(true); + }); + + it('expands an analysis dialog list', () => { + const d = v04({ + dialog: [rec({ recording_set: 2 }), rec(), { type: 'recording-set', start: T0, recordings: [0] }], + analysis: [{ type: 'summary', dialog: [1, 2], vendor: 'v', body: 's', encoding: 'none' }] + }); + const { out } = migrate(d); + expect(out.analysis[0].dialog).toEqual([1, 0]); + expect(out.analysis[0].sessions).toBe(1); + }); + + it('gives an attachment on a removed Dialog the Session', () => { + const d = v04({ + dialog: [rec({ recording_set: 1 }), { type: 'recording-set', start: T0, recordings: [0] }], + attachments: [{ purpose: 'notes', start: T0, party: 0, dialog: 1, body: 'n', encoding: 'none', mediatype: 'text/plain' }] + }); + const att = migrate(d).out.attachments[0]; + expect('dialog' in att).toBe(false); + expect(att.session).toBe(1); + }); + + it('moves analysis on a transfer Dialog to the original Session', () => { + const d = v04({ + dialog: [rec(), { type: 'transfer', start: T1, transferee: 0, transferor: 1, transfer_target: 2, original: 0, target_dialog: 0 }], + analysis: [{ type: 'report', dialog: 1, vendor: 'v', body: 'why', encoding: 'none' }] + }); + const { out } = migrate(d); + expect('dialog' in out.analysis[0]).toBe(false); + expect(out.analysis[0].sessions).toBe(out.events[0].sessions); + }); + + it('leaves references to kept Dialogs alone', () => { + const d = v04({ + dialog: [rec(), text()], + analysis: [{ type: 'summary', dialog: [0, 1], vendor: 'v', body: 's', encoding: 'none' }], + attachments: [{ purpose: 'notes', start: T0, party: 0, dialog: 1, body: 'n', encoding: 'none', mediatype: 'text/plain' }] + }); + const { out, report } = migrate(d); + expect(out.analysis[0].dialog).toEqual([0, 1]); + expect('sessions' in out.analysis[0]).toBe(false); + expect(out.attachments[0].dialog).toBe(1); + expect(report.entries.filter(e => e.step === 'T10b')).toEqual([]); + }); +}); + +describe('index stability', () => { + const IDENT = ['type', 'start', 'duration', 'mediatype', 'body', 'url', 'disposition']; + const source = () => + v04({ + dialog: [ + rec(), // 0 + { type: 'recording-set', start: T0, recordings: [0, 3], parties: [0, 1] }, // 1 + { type: 'transfer', start: T1, transferee: 0, transferor: 1, transfer_target: 2, original: 1, consultation: 4, target_dialog: 3 }, // 2 + rec({ start: T2, parties: [0, 2], party_history: [{ party: 2, time: T2, event: 'join' }] }), // 3 + text({ parties: [1, 2] }), // 4 + { type: 'incomplete', start: T2, parties: [2, 0], disposition: 'busy' } // 5 + ], + analysis: [ + { type: 'a0', dialog: 0, vendor: 'v', body: 'x', encoding: 'none' }, + { type: 'a3', dialog: [3, 4], vendor: 'v', body: 'x', encoding: 'none' }, + { type: 'a5', dialog: 5, vendor: 'v', body: 'x', encoding: 'none' } + ], + attachments: [ + { purpose: 'p4', start: T0, party: 0, dialog: 4, body: 'x', encoding: 'none', mediatype: 'text/plain' }, + { purpose: 'p5', start: T0, party: 0, dialog: 5, body: 'x', encoding: 'none', mediatype: 'text/plain' } + ] + }); + const ident = (d: D) => Object.fromEntries(IDENT.filter(k => k in d).map(k => [k, d[k]])); + + it('keeps the dialog array length and positions', () => { + const src = source(); + const { out, report } = migrate(src); + expect(out.dialog).toHaveLength(src.dialog.length); + const removed = new Set(Object.keys(report.removedDialogs).map(Number)); + expect([...removed]).toEqual([1, 2]); + src.dialog.forEach((a: D, i: number) => { + if (removed.has(i)) expect(out.dialog[i]).toEqual({}); + else expect(ident(out.dialog[i])).toEqual(ident(a)); + }); + }); + + it('resolves analysis and attachment references to the same Dialog', () => { + const src = source(); + const { out } = migrate(src); + src.analysis.forEach((aSrc: D, n: number) => { + const before = Array.isArray(aSrc.dialog) ? aSrc.dialog : [aSrc.dialog]; + const raw = out.analysis[n].dialog; + const after = raw === undefined ? [] : Array.isArray(raw) ? raw : [raw]; + for (const i of before) { + if (['transfer', 'recording-set'].includes(src.dialog[i].type)) continue; + expect(after).toContain(i); + expect(ident(out.dialog[i])).toEqual(ident(src.dialog[i])); + } + expect(after.every((i: number) => Object.keys(out.dialog[i]).length > 0)).toBe(true); + }); + src.attachments.forEach((tSrc: D, n: number) => { + const i = tSrc.dialog; + expect(out.attachments[n].dialog).toBe(i); + expect(ident(out.dialog[i])).toEqual(ident(src.dialog[i])); + }); + }); + + it('resolves Session and Event references to the intended Dialogs', () => { + const { out } = migrate(source()); + for (const s of out.sessions) for (const i of s.dialog ?? []) expect(Object.keys(out.dialog[i]).length).toBeGreaterThan(0); + const join = out.events.find((e: D) => e.type === 'join'); + const sessions = Array.isArray(join.sessions) ? join.sessions : [join.sessions]; + expect(sessions.some((n: number) => out.sessions[n].dialog.includes(3))).toBe(true); + const byType: Record = {}; + for (const e of out.events) if (e.type !== 'join') byType[e.type] = e; + expect(out.sessions[byType['consultative-transfer'].sessions].dialog).toEqual([0, 3]); + expect(out.sessions[byType['consultative-transfer'].target_session].dialog).toEqual([3]); + expect(out.sessions[byType['consultation-start'].consultation].dialog).toEqual([4]); + }); + + it('would have broken the references if empty Dialogs were filtered first', () => { + const { out } = migrate(source()); + const filtered = out.dialog.filter((d: D) => Object.keys(d).length > 0); + expect(filtered[3].type !== out.dialog[3].type || JSON.stringify(filtered[1]) !== JSON.stringify(out.dialog[1])).toBe(true); + expect([out.dialog[4].type, out.dialog[5].type]).toEqual(['text', 'incomplete']); + for (const s of out.sessions) for (const i of s.dialog ?? []) expect(i).toBeLessThan(out.dialog.length); + }); + + it('resolves every reference in the result', () => { + const { out, report } = migrate(source()); + expect(new Vcon(out).isValid()).toEqual({ valid: true, errors: [] }); + expect(report.unresolved.filter(e => e.step === 'post')).toEqual([]); + }); +}); + +describe('T11 and T12 renames', () => { + it('renames redacted', () => { + const r = { uuid: '01a16b86-96e7-80a8-b9a2-279e0d16bc46', type: 'PII Redaction', url: 'https://e.com/u', content_hash: 'sha512-x' }; + const { out } = migrate(v04({ redacted: r })); + expect(out.redacted_from).toEqual(r); + expect('redacted' in out).toBe(false); + }); + + it('renames amended', () => { + const a = { uuid: '01a16b86-96e7-80a8-b9a2-279e0d16bc46' }; + const { out } = migrate(v04({ amended: a })); + expect(out.amended_from).toEqual(a); + expect('amended' in out).toBe(false); + }); + + it('keeps the key position', () => { + const amended = { uuid: '01a16b86-96e7-80a8-b9a2-279e0d16bc46' }; + const { out } = migrate(v04({ amended })); + expect(Object.keys(out).indexOf('amended_from')).toBe(Object.keys(v04({ amended })).indexOf('amended')); + }); +}); + +describe('T13 signed input', () => { + const signed = (payload: D, alg = 'RS256'): D => ({ + payload: b64(payload), + signatures: [{ protected: b64({ alg }), header: { uuid: 'x' }, signature: 'AAAA' }] + }); + + it('migrates a signed vCon as its unsigned payload', () => { + const { out, report } = migrate(signed(v04({ dialog: [rec()] }))); + expect('signatures' in out || 'payload' in out).toBe(false); + expect(out.vcon).toBe('0.5.0'); + expect(out.sessions).toBeTruthy(); + expect(report.resignRequired).toBe(true); + expect(report.unresolved.some(e => e.message.includes('Re-signing is required'))).toBe(true); + }); + + it('calls out alg none', () => { + const { report } = migrate(signed(v04(), 'none')); + expect(report.unresolved.some(e => e.message.includes("alg 'none'"))).toBe(true); + }); + + it('does not require re-signing for unsigned input', () => { + expect(migrate(v04()).report.resignRequired).toBe(false); + }); + + it('throws on a bad payload', () => { + expect(() => migrate040To050({ payload: '!!!', signatures: [] })).toThrow(/payload/); + }); + + it('throws on encrypted input', () => { + expect(() => migrate040To050({ protected: 'x', ciphertext: 'y', recipients: [] })).toThrow(/decrypt/); + }); + + it('requires the signed payload to be 0.4.0', () => { + expect(() => migrate040To050(signed({ vcon: '0.5.0', uuid: 'a', created_at: '2022-01-01T00:00:00Z' }))).toThrow(/expected '0.4.0'/); + }); + + it('notes T15 for signed input', () => { + const { report } = migrate040To050({ payload: b64(v04()), signatures: [] }); + expect(report.notes.some(e => e.step === 'T15')).toBe(true); + }); +}); + +describe('T14 extensions', () => { + const LB = { purpose: 'lawful_basis', start: T0, party: 0, dialog: 0, body: {}, encoding: 'json', mediatype: 'application/json' }; + + it('adds the extensions in use', () => { + const { out, report } = migrate(v04({ dialog: [rec()], attachments: [LB] })); + expect(out.extensions).toEqual(['lawful_basis']); + expect(report.inferred.some(e => e.message.includes('lawful_basis'))).toBe(true); + }); + + it('keeps and extends an existing list', () => { + const { out } = migrate(v04({ dialog: [rec()], attachments: [LB], extensions: ['x'], critical: ['y'] })); + expect(out.extensions).toEqual(['x', 'lawful_basis', 'y']); + }); + + it('adds wtf_transcription for a WTF analysis', () => { + const { out } = migrate(v04({ dialog: [rec()], analysis: [{ type: 'wtf_transcription', dialog: 0, vendor: 'v', body: {}, encoding: 'json' }] })); + expect(out.extensions).toContain('wtf_transcription'); + }); + + it('reports, and does not invent, an extension it cannot identify', () => { + const { vcon, report } = migrate040To050(v04({ dialog: [rec({ encoding: 'gzip', body: 'x' })] })); + expect('extensions' in vcon).toBe(false); + expect(report.unresolved.some(e => e.message.includes('cannot be identified'))).toBe(true); + }); + + it('changes nothing when no extension is in use', () => { + expect('extensions' in migrate(v04({ dialog: [rec()] })).out).toBe(false); + }); +}); + +describe('T10c unscoped attachments', () => { + const att = (extra: D = {}): D => ({ purpose: 'note', start: T0, party: 0, body: 'x', encoding: 'none', mediatype: 'text/plain', ...extra }); + + it('scopes to the only Session and reports it', () => { + const { out, report } = migrate(v04({ dialog: [rec()], attachments: [att()] })); + expect(out.attachments[0].session).toBe(0); + expect(kinds(report, INFERRED, 'T10c').length).toBeGreaterThan(0); + }); + + it('leaves it unresolved with several Sessions', () => { + const { vcon, report } = migrate040To050(v04({ dialog: [rec({ recording_set: 1 }), { type: 'recording-set', recordings: [0] }], attachments: [att()] })); + expect('session' in vcon.attachments[0] || 'dialog' in vcon.attachments[0]).toBe(false); + expect(kinds(report, UNRESOLVED, 'T10c').length).toBeGreaterThan(0); + }); +}); + +describe('lawful basis survives migration', () => { + const LB = { + purpose: 'lawful_basis', start: T0, party: 0, dialog: 0, body: { lawful_basis: 'consent' }, + encoding: 'json', mediatype: 'application/json' + }; + + it('keeps the attachment unchanged and notes the gap', () => { + const { out, report } = migrate(v04({ dialog: [rec()], attachments: [JSON.parse(JSON.stringify(LB))] })); + expect(out.attachments).toEqual([LB]); + expect('session' in out.attachments[0]).toBe(false); + expect(report.notes.filter(e => e.message.includes('lawful_basis attachment scoped by dialog only'))).toHaveLength(1); + expect(new Vcon(out).findLawfulBasisAttachments().length).toBeGreaterThan(0); + }); + + it('does not flag one that already has a session', () => { + const { report } = migrate(v04({ dialog: [rec()], attachments: [{ ...LB, session: [0] }] })); + expect(report.notes.filter(e => e.message.includes('lawful_basis'))).toEqual([]); + }); + + it('gives an attachment on a removed Dialog the recording-set Session', () => { + const d = v04({ dialog: [rec({ recording_set: 1 }), { type: 'recording-set', start: T0, recordings: [0] }], attachments: [{ ...LB, dialog: 1 }] }); + const { out } = migrate(d); + expect(out.attachments[0].session).toBe(1); + expect('dialog' in out.attachments[0]).toBe(false); + expect(out.attachments[0].purpose).toBe('lawful_basis'); + }); +}); + +describe('report', () => { + it('has a serializable structure', () => { + const { report } = migrate(v04({ dialog: [rec(), text({ parties: [0, 1, 2] })] })); + expect(report).toBeInstanceOf(MigrationReport); + expect([report.sourceVersion, report.targetVersion]).toEqual(['0.4.0', '0.5.0']); + const d = JSON.parse(JSON.stringify(report.toDict())); + expect(d.entries.length).toBeGreaterThan(0); + expect(d.steps_run.length).toBeGreaterThan(0); + expect(report.summary()).toContain('inferred'); + }); + + it('reports post-migration problems', () => { + // An attachment that already lacked party was invalid in 0.4.0 and stays so. + const { report } = migrate040To050(v04({ dialog: [rec()], attachments: [{ purpose: 'x', body: 'b', encoding: 'none' }] })); + expect(report.unresolved.some(e => e.step === 'post' && e.message.includes('party'))).toBe(true); + }); + + it('uses only known kinds', () => { + const { report } = migrate(v04({ dialog: [rec({ originator: 1 }), text({ parties: [0, 1, 2] })] })); + expect(report.entries.every(e => ['inferred', 'fallback', 'unresolved', 'info'].includes(e.kind))).toBe(true); + }); +}); + +describe('readers accept both versions', () => { + let warn: jest.SpyInstance; + beforeEach(() => { + warn = jest.spyOn(process, 'emitWarning').mockImplementation(() => undefined); + }); + afterEach(() => warn.mockRestore()); + + it('migrates 0.4.0 JSON on load', () => { + const v = Vcon.buildFromJson(JSON.stringify(v04({ dialog: [rec({ originator: 1 })] }))); + expect(v.vcon).toBe('0.5.0'); + expect(v.migrationReport).toBeDefined(); + expect(v.sessions[0].originator).toBe(1); + expect(v.isValid()).toEqual({ valid: true, errors: [] }); + }); + + it('does not touch 0.5.0 input', () => { + const src = { vcon: '0.5.0', uuid: 'a', created_at: '2022-01-01T00:00:00Z', parties: [], dialog: [{}], sessions: [{}] }; + const v = new Vcon(JSON.parse(JSON.stringify(src))); + expect(v.migrationReport).toBeUndefined(); + expect(v.data.dialog).toEqual([{}]); + expect(v.data.sessions).toEqual([{}]); + }); + + it('does not migrate input without vcon on load', () => { + const d = v04({ dialog: [rec({ originator: 1 })] }); + delete d.vcon; + const v = new Vcon(d); + expect(v.migrationReport).toBeUndefined(); + expect(v.data.dialog![0].originator).toBe(1); + }); + + it('keeps the raw document with migrateLegacy false', () => { + const v = new Vcon(v04({ dialog: [rec()] }), { migrateLegacy: false }); + expect(v.vcon).toBe('0.4.0'); + expect(v.migrationReport).toBeUndefined(); + expect(v.isValid().valid).toBe(false); + }); + + it('keeps legacy fields when migration is off', () => { + const d = v04({ redacted: { uuid: 'x', type: 'PII' }, dialog: [rec({ originator: 1, party_history: [{ party: 0, time: T0, event: 'join' }] })] }); + const v = new Vcon(d, { migrateLegacy: false }); + expect((v.data as any).redacted).toEqual({ uuid: 'x', type: 'PII' }); + expect(v.data.dialog![0].party_history).toBeTruthy(); + expect(v.data.dialog![0].originator).toBe(1); + }); + + it('explicit migration accepts input with no vcon and returns a Vcon with its report', () => { + const d = v04({ dialog: [rec()] }); + delete d.vcon; + const v = Vcon.migrate040To050(d); + expect(v.vcon).toBe('0.5.0'); + expect(v.migrationReport).toBeDefined(); + expect(v.sessions.length).toBeGreaterThan(0); + }); + + it('strict migration throws through the constructor', () => { + const d = v04({ dialog: [rec(), { type: 'transfer', transferee: 0, transfer_target: 2, original: 0 }] }); + expect(() => new Vcon(d, { strictMigration: true })).toThrow(MigrationError); + }); + + it('writers emit 0.5.0', () => { + const v = Vcon.buildFromJson(JSON.stringify(v04({ dialog: [rec()] }))); + expect(JSON.parse(v.toJson()).vcon).toBe('0.5.0'); + }); +}); + +describe('signed 0.4.0 input is not migrated on load', () => { + const signed = (payload: D): D => ({ + payload: b64(payload), + signatures: [{ protected: b64({ alg: 'RS256' }), signature: 'c2ln', header: { x5c: [] } }] + }); + + it('keeps the signature and payload untouched', () => { + const s = signed(v04({ dialog: [rec()] })); + const spy = jest.spyOn(process, 'emitWarning').mockImplementation(() => undefined); + try { + const v = new Vcon(s); + expect(v.migrationReport).toBeUndefined(); + expect(v.data.signatures).toEqual(s.signatures); + expect(v.data.payload).toBe(s.payload); + expect(Object.keys(v.data).sort()).toEqual(['payload', 'signatures']); // no defaults added + } finally { + spy.mockRestore(); + } + }); + + it('migrates explicitly after verification', () => { + const v = Vcon.migrate040To050(signed(v04({ dialog: [rec()] }))); + expect(v.migrationReport!.resignRequired).toBe(true); + expect('signatures' in v.data).toBe(false); + expect(v.vcon).toBe('0.5.0'); + }); +}); diff --git a/src/__tests__/schema-conformance.test.ts b/src/__tests__/schema-conformance.test.ts index d273706..dfcdd6c 100644 --- a/src/__tests__/schema-conformance.test.ts +++ b/src/__tests__/schema-conformance.test.ts @@ -1,14 +1,19 @@ +import fs from 'fs'; +import path from 'path'; import Ajv, { ValidateFunction } from 'ajv'; import addFormats from 'ajv-formats'; -import schema from './fixtures/vcon_json_schema.json'; +import schema from './fixtures/appendix-c-json-schema.json'; import { Vcon } from '../vcon'; import { Party } from '../party'; import { Dialog } from '../dialog'; +import { Session } from '../session'; +import { Event } from '../event'; /** - * Conformance: whatever the public API emits via toDict() MUST validate against - * the authoritative vCon core JSON Schema (vendored in ./fixtures). This is the - * guard that keeps the hand-rolled validators from silently drifting from the spec. + * Conformance: the Appendix B examples of core-05 load and pass isValid(), and + * whatever the public API emits via toDict() MUST validate against the Appendix + * C JSON Schema of core-05 (vendored in ./fixtures). This is the guard that + * keeps the hand-rolled validators from silently drifting from the spec. */ let validate: ValidateFunction; @@ -18,42 +23,108 @@ beforeAll(() => { validate = ajv.compile(schema); }); -function expectConformant(vcon: Vcon): void { - const ok = validate(vcon.toDict()); +function expectSchemaValid(data: unknown, what = 'vCon'): void { + const ok = validate(data); if (!ok) { throw new Error( - 'vCon failed schema validation:\n' + - (validate.errors || []) - .map(e => ` ${e.instancePath || '(root)'} ${e.message}`) - .join('\n') + `${what} failed schema validation:\n` + + (validate.errors || []).map(e => ` ${e.instancePath || '(root)'} ${e.message}`).join('\n') ); } expect(ok).toBe(true); } -const START = '2026-01-15T10:30:00Z'; +function expectConformant(vcon: Vcon): void { + expectSchemaValid(vcon.toDict()); + expect(vcon.isValid()).toEqual({ valid: true, errors: [] }); +} + +const EXAMPLES_DIR = path.join(__dirname, 'fixtures', 'examples'); +const examples = fs.readdirSync(EXAMPLES_DIR).filter(f => /^B\d-.*\.json$/.test(f)).sort(); +const UNSIGNED = examples.filter(f => ['B1', 'B2', 'B3', 'B4', 'B5', 'B8', 'B9'].includes(f.slice(0, 2))); +const readExample = (prefix: string): any => + JSON.parse(fs.readFileSync(path.join(EXAMPLES_DIR, examples.find(f => f.startsWith(prefix))!), 'utf8')); + +describe('Appendix B examples of core-05', () => { + it('has all nine examples', () => { + expect(examples.map(f => f.slice(0, 2))).toEqual(['B1', 'B2', 'B3', 'B4', 'B5', 'B6', 'B7', 'B8', 'B9']); + }); + + it.each(UNSIGNED)('%s validates against the Appendix C schema', file => { + expectSchemaValid(JSON.parse(fs.readFileSync(path.join(EXAMPLES_DIR, file), 'utf8')), file); + }); + + it.each(UNSIGNED)('%s loads untouched and passes isValid()', file => { + const data = JSON.parse(fs.readFileSync(path.join(EXAMPLES_DIR, file), 'utf8')); + const vcon = Vcon.buildFromJson(JSON.stringify(data)); + expect(vcon.migrationReport).toBeUndefined(); // already 0.5.0 + expect(vcon.vcon).toBe('0.5.0'); + expect(vcon.isValid()).toEqual({ valid: true, errors: [] }); + expect(vcon.sessions).toEqual(data.sessions); + expect(vcon.dialog).toEqual(data.dialog); + expect(vcon.toDict().events).toEqual(data.events); + }); + + it('B6 payload loads and validates', () => { + const envelope = readExample('B6'); + const protectedHeader = JSON.parse(Buffer.from(envelope.signatures[0].protected, 'base64url').toString()); + expect(protectedHeader).toEqual({ alg: 'RS256' }); + const payload = JSON.parse(Buffer.from(envelope.payload, 'base64url').toString()); + expectSchemaValid(payload, 'B6 payload'); + expect(new Vcon(payload).isValid().valid).toBe(true); + }); + + it('B7 is a JWE, not a vCon', () => { + const envelope = readExample('B7'); + for (const key of ['protected', 'iv', 'ciphertext', 'tag', 'recipients', 'unprotected']) { + expect(envelope).toHaveProperty(key); + } + expect(JSON.parse(Buffer.from(envelope.protected, 'base64url').toString()).alg).toBe('RSA-OAEP'); + }); + + it('B1 events use bare integer sessions and no dialog', () => { + const vcon = new Vcon(readExample('B1')); + expect(vcon.events.map(e => e.type)).toEqual(['join', 'join', 'drop', 'drop']); + expect(vcon.events.every(e => e.sessions === 0 && !('dialog' in e))).toBe(true); + }); + + it('B8 and B9 use the renamed parameters', () => { + expect(new Vcon(readExample('B8')).redacted_from?.uuid).toBeTruthy(); + expect(new Vcon(readExample('B9')).amended_from?.uuid).toBeTruthy(); + }); +}); describe('schema conformance of emitted vCons', () => { + const START = '2026-01-15T10:30:00Z'; + const HASH = 'sha512-Tf9OoDQfCoI_FdP08BqxLq4OXaV5zLhR-NvZ3-hMWLLN7iZA50Dh7hctp5Om55Vg5ff5vQWKEqKAQz7W-kZRCg'; + + it('an empty buildNew() validates', () => { + expectConformant(Vcon.buildNew()); + }); + it('a minimal vCon validates', () => { const v = Vcon.buildNew(); v.addParty(new Party({ tel: '+15551234567', name: 'Alice', role: 'customer' })); expectConformant(v); }); - it('a recording-set with member recordings validates', () => { + it('a recording in a Session validates', () => { const v = Vcon.buildNew(); v.addParty(new Party({ tel: '+15551234567' })); - v.addDialog(new Dialog({ type: 'recording-set', start: START, recordings: [1, 2] })); - v.addDialog(new Dialog({ type: 'recording', start: START, parties: [0], recording_set: 0, - url: 'https://media.example.com/a.wav', - content_hash: 'sha512-Tf9OoDQfCoI_FdP08BqxLq4OXaV5zLhR-NvZ3-hMWLLN7iZA50Dh7hctp5Om55Vg5ff5vQWKEqKAQz7W-kZRCg' })); + v.addParty(new Party({ tel: '+15559876543' })); + const s = v.addSession(new Session({ start: START, duration: 60, parties: [0, 1] })); + v.addDialog( + new Dialog({ type: 'recording', start: START, parties: [0, 1], mediatype: 'audio/wav', url: 'https://media.example.com/a.wav', content_hash: HASH }), + s + ); expectConformant(v); }); it('analysis keyed off an attachment (no dialog) validates', () => { const v = Vcon.buildNew(); v.addParty(new Party({ mailto: 'bob@example.com' })); - v.addAttachment({ purpose: 'document', party: 0, dialog: 0, start: START, body: 'x', encoding: 'none' }); + v.addSession({ parties: [0] }); + v.addAttachment({ purpose: 'document', party: 0, start: START, body: 'x', encoding: 'none', mediatype: 'text/plain' }); v.addAnalysis({ type: 'summary', attachment: 0, vendor: 'acme', body: { ok: true } }); expectConformant(v); }); @@ -61,24 +132,59 @@ describe('schema conformance of emitted vCons', () => { it('provenance on dialog and analysis validates', () => { const v = Vcon.buildNew(); v.addParty(new Party({ tel: '+15551234567' })); - v.addDialog(new Dialog({ type: 'text', start: START, parties: [0], body: 'hi', encoding: 'none', - provenance: { model: 'gpt-4', provider: 'openai' } })); + const s = v.addSession({ start: START, parties: [0] }); + v.addDialog( + new Dialog({ type: 'text', start: START, parties: [0], body: 'hi', encoding: 'none', mediatype: 'text/plain', provenance: { model: 'gpt-4', provider: 'openai' } }), + s + ); v.addAnalysis({ type: 'summary', dialog: 0, vendor: 'acme', provenance: { model: 'gpt-4' } }); expectConformant(v); }); - it('a transfer dialog validates', () => { + it('a vCon carrying a tag validates', () => { const v = Vcon.buildNew(); v.addParty(new Party({ tel: '+15551234567' })); - v.addParty(new Party({ tel: '+15559876543' })); - v.addDialog(new Dialog({ type: 'transfer', start: START, transferor: 0, transferee: 1, transfer_target: [1] })); + v.addTag('department', 'sales'); expectConformant(v); }); - it('a vCon carrying a tag validates', () => { + it('a vCon with every object kind validates', () => { const v = Vcon.buildNew(); - v.addParty(new Party({ tel: '+15551234567' })); - v.addTag('department', 'sales'); - expectConformant(v); + v.addParty(new Party({ name: 'Alice', tel: '+12025550101' })); + v.addParty(new Party({ name: 'Bob', tel: '+12025550102' })); + v.addParty(new Party({ name: 'Carol', tel: '+12025550103' })); + v.addSession(new Session({ start: '2026-01-01T00:00:00Z', duration: 60, parties: [0, 1] })); + const s1 = v.addSession(new Session({ start: '2026-01-01T00:00:10Z', duration: 30, parties: [1, 2] })); + const s2 = v.addSession(new Session({ start: '2026-01-01T00:00:45Z', parties: [0, 2] })); + v.data.sessions![0].sessions = [{ session: 1, type: 'child', description: 'consult' }]; + v.addDialog( + new Dialog({ type: 'recording', start: '2026-01-01T00:00:00Z', duration: 60, parties: [[0], [1]], mediatype: 'audio/wav', url: 'https://example.com/a.wav', content_hash: HASH }), + 0 + ); + v.addDialog(new Dialog({ type: 'text', start: '2026-01-01T00:00:10Z', parties: [1], body: 'hello', mediatype: 'text/plain', encoding: 'none' }), 1); + v.addIncompleteDialog({ start: '2026-01-01T00:00:45Z', disposition: 'busy', parties: [0], session: 2 }); + v.addDialog(Dialog.placeholder()); + const T = '2026-01-01T00:00:00Z'; + for (const e of [ + new Event({ type: 'join', time: T, sessions: 0, party: 0 }), + new Event({ type: 'keydown', time: T, sessions: [0, 1], party: 1, button: '#' }), + new Event({ type: 'consultation-start', time: T, sessions: 0, party: 1, transferee: 0, transfer_target: 2, consultation: 1 }), + new Event({ type: 'consultative-transfer', time: T, sessions: 0, party: 1, transferee: 0, transfer_target: 2, consultation: 1, target_session: 2 }), + new Event({ type: 'blind-transfer', time: T, sessions: 0, party: 1, transferee: 0, transfer_target: 2, target_session: 2 }), + new Event({ type: 'transfer-abandoned', time: T, sessions: 0, party: 1, transferee: 0 }), + new Event({ type: 'channel-contributors', time: T, dialog: 0, channel: 1, contributors: [1, 2] }), + new Event({ type: 'channel-contributors', time: T, dialog: 0, channel: 0, contributors: null }) + ]) { + v.addEvent(e); + } + v.addTag('k', 'v'); + v.addAttachment({ purpose: 'note', party: 0, session: [0, 1, 2], body: 'n', encoding: 'none', mediatype: 'text/plain' }); + v.addAnalysis({ type: 'summary', vendor: 'v', body: 's', dialog: 0, sessions: [0], attachment: 0 }); + const out = v.toDict(); + expectSchemaValid(out); + expect(v.isValid()).toEqual({ valid: true, errors: [] }); + expect(out.vcon).toBe('0.5.0'); + expect(out.dialog![3]).toEqual({}); + expect([s1, s2]).toEqual([1, 2]); }); }); diff --git a/src/__tests__/session-event.test.ts b/src/__tests__/session-event.test.ts new file mode 100644 index 0000000..89b15e1 --- /dev/null +++ b/src/__tests__/session-event.test.ts @@ -0,0 +1,254 @@ +import { Vcon } from '../vcon'; +import { Dialog } from '../dialog'; +import { Party, PartyHistory } from '../party'; +import { Session, SessionReference, validateSession } from '../session'; +import { Event, EVENT_PARAMETER_RULES, CORE_EVENT_TYPES, validateEvent } from '../event'; + +const T = '2026-01-01T00:00:00Z'; + +function validEvent(etype: string): Record { + const base: Record = { type: etype, time: T }; + if (etype === 'channel-contributors') return { ...base, dialog: 0, channel: 0 }; + Object.assign(base, { sessions: 0, party: 0 }); + if (etype === 'keydown' || etype === 'keyup') base.button = '5'; + else if (etype === 'consultation-start') Object.assign(base, { transferee: 1, transfer_target: 2, consultation: 1 }); + else if (etype === 'blind-transfer') Object.assign(base, { transferee: 1, transfer_target: 2, target_session: 1 }); + else if (etype === 'consultative-transfer') Object.assign(base, { transferee: 1, transfer_target: 2, consultation: 1, target_session: 2 }); + else if (etype === 'transfer-abandoned') Object.assign(base, { transferee: 1 }); + return base; +} + +const SAMPLE: Record = { + sessions: 0, party: 0, dialog: 0, channel: 0, contributors: [0], button: '1', + transferee: 0, transfer_target: 0, consultation: 0, target_session: 0 +}; + +describe('Session', () => { + it('allows an empty Session', () => { + expect(new Session().toDict()).toEqual({}); + expect(validateSession({})).toEqual({ errors: [], warnings: [] }); + }); + + it('serializes only the parameters that are set', () => { + const s = new Session({ + start: new Date('2026-01-01T00:00:00Z'), + duration: 60, + parties: [0, 1], + originator: 1, + session_id: { local: 'l', remote: 'r' }, + sessions: [new SessionReference(1, 'child', 'consult')], + dialog: [0] + }); + expect(s.toDict()).toEqual({ + start: '2026-01-01T00:00:00.000Z', + duration: 60, + parties: [0, 1], + originator: 1, + session_id: { local: 'l', remote: 'r' }, + sessions: [{ session: 1, type: 'child', description: 'consult' }], + dialog: [0] + }); + }); + + it('requires an index and a type on a Session_Reference', () => { + expect(() => new SessionReference(-1, 'child')).toThrow(); + expect(() => new SessionReference(0, '')).toThrow(); + }); + + it('checks Session_Reference entries', () => { + const { errors } = validateSession({ start: T, parties: [0], sessions: [{ session: 5, type: 'child' }, { type: 'peer' }] }, { sessionCount: 1, partyCount: 1 }); + expect(errors).toContain('Session references invalid session index: 5'); + expect(errors).toContain('Session sessions[1] is missing required field: session'); + }); + + it('addSession returns the index', () => { + const v = Vcon.buildNew(); + expect(v.addSession(new Session({ start: T, parties: [0] }))).toBe(0); + expect(v.addSession()).toBe(1); + expect(v.sessions[1]).toEqual({}); + }); + + it('checks Session dialog and party indices', () => { + const v = Vcon.buildNew(); + v.addParty(new Party({ name: 'A' })); + v.addSession({ start: T, parties: [0, 3], dialog: [7] }); + const { valid, errors } = v.isValid(); + expect(valid).toBe(false); + expect(errors).toContain('Session at index 0 references invalid party index: 3'); + expect(errors).toContain('Session at index 0 references invalid dialog index: 7'); + }); + + it('requires a Session when dialog or events exist', () => { + const v = Vcon.buildNew(); + v.addParty(new Party({ name: 'A' })); + v.addDialog(new Dialog({ type: 'text', start: T, parties: [0], body: 'x', mediatype: 'text/plain', encoding: 'none' })); + expect(v.isValid().errors.some(e => /At least one Session/.test(e))).toBe(true); + v.addSession({ start: T, parties: [0], dialog: [0] }); + expect(v.isValid().valid).toBe(true); + }); + + it('adds a Dialog to a Session and warns about an unreferenced Dialog', () => { + const v = Vcon.buildNew(); + v.addParty(new Party({ name: 'A' })); + v.addSession({ start: T, parties: [0] }); + const d = () => new Dialog({ type: 'text', start: T, parties: [0], body: 'x', mediatype: 'text/plain', encoding: 'none' }); + expect(v.addDialog(d(), 0)).toBe(0); + expect(v.sessions[0].dialog).toEqual([0]); + v.addDialog(d()); + expect(v.getValidationWarnings()).toContain('Dialog at index 1 is not referenced by any Session Object.'); + expect(() => v.addDialog(d(), 4)).toThrow(/Invalid session index/); + }); +}); + +describe('Event table (core-05 4.3.1.5)', () => { + it.each(CORE_EVENT_TYPES)('%s: a minimal valid Event passes', etype => { + expect(validateEvent(validEvent(etype))).toEqual({ errors: [], warnings: [] }); + }); + + it.each(CORE_EVENT_TYPES)('%s: every M parameter is enforced', etype => { + for (const [param, code] of Object.entries(EVENT_PARAMETER_RULES[etype])) { + if (code !== 'M') continue; + const ev = validEvent(etype); + delete ev[param]; + expect(validateEvent(ev).errors.some(e => e.includes(param))).toBe(true); + } + }); + + it.each(CORE_EVENT_TYPES)('%s: every X parameter is rejected', etype => { + for (const [param, code] of Object.entries(EVENT_PARAMETER_RULES[etype])) { + if (code !== 'X') continue; + const ev = validEvent(etype); + ev[param] = SAMPLE[param]; + expect(validateEvent(ev).errors.some(e => e.includes(`must not have field: ${param}`))).toBe(true); + } + }); + + it.each(CORE_EVENT_TYPES)('%s: every SN parameter warns', etype => { + for (const [param, code] of Object.entries(EVENT_PARAMETER_RULES[etype])) { + if (code !== 'SN') continue; + const ev = validEvent(etype); + ev[param] = 0; + const r = validateEvent(ev); + expect(r.errors).toEqual([]); + expect(r.warnings.some(w => w.includes(`should not have field: ${param}`))).toBe(true); + } + }); + + it.each(CORE_EVENT_TYPES)('%s: optional parameters are accepted', etype => { + for (const [param, code] of Object.entries(EVENT_PARAMETER_RULES[etype])) { + if (code !== 'O') continue; + const ev = validEvent(etype); + ev[param] = param === 'contributors' ? null : 1; + expect(validateEvent(ev)).toEqual({ errors: [], warnings: [] }); + } + }); + + it('matches the draft for the transfer types', () => { + const r = EVENT_PARAMETER_RULES; + expect(r['consultation-start'].target_session).toBe('X'); + expect(r['consultation-start'].consultation).toBe('M'); + expect(r['blind-transfer'].consultation).toBe('X'); + expect(r['blind-transfer'].target_session).toBe('M'); + expect(r['consultative-transfer'].consultation).toBe('M'); + expect(r['consultative-transfer'].target_session).toBe('M'); + expect(r['transfer-abandoned'].transfer_target).toBe('O'); + expect(r['transfer-abandoned'].consultation).toBe('O'); + expect(r['transfer-abandoned'].target_session).toBe('X'); + expect(r['channel-contributors'].sessions).toBe('X'); + expect(r['channel-contributors'].party).toBe('X'); + expect(r.keydown.button).toBe('M'); + expect(r.join.button).toBe('X'); + }); + + it('wants a single session index for transfer types', () => { + const ev = validEvent('blind-transfer'); + ev.sessions = [0]; + expect(validateEvent(ev).errors.some(e => /single session index/.test(e))).toBe(true); + }); + + it('accepts a bare integer or a list of sessions on party events', () => { + for (const sessions of [0, [0, 1]]) { + expect(validateEvent({ ...validEvent('join'), sessions }).errors).toEqual([]); + } + }); + + it('requires a parseable time', () => { + const ev = validEvent('join'); + ev.time = 'not a time'; + expect(validateEvent(ev).errors.some(e => /invalid 'time'/.test(e))).toBe(true); + delete ev.time; + expect(validateEvent(ev).errors.some(e => /missing required field: time/.test(e))).toBe(true); + }); + + it('checks an extension Event type for type and time only', () => { + expect(validateEvent({ type: 'tool-call', time: T, tool_name: 'x' })).toEqual({ errors: [], warnings: [] }); + }); + + it('requires channel-contributors to reference a recording Dialog', () => { + const v = Vcon.buildNew(); + v.addParty(new Party({ name: 'A' })); + v.addSession({ start: T, parties: [0] }); + v.addDialog(new Dialog({ type: 'text', start: T, parties: [0], body: 'x', mediatype: 'text/plain', encoding: 'none' }), 0); + v.addEvent(new Event({ type: 'channel-contributors', time: T, dialog: 0, channel: 0, contributors: 0 })); + const { valid, errors } = v.isValid(); + expect(valid).toBe(false); + expect(errors.some(e => e.includes("must reference a 'recording' Dialog"))).toBe(true); + }); +}); + +describe('Event class', () => { + it('round-trips a blind transfer', () => { + const e = new Event({ type: 'blind-transfer', time: new Date(T), sessions: 0, party: 1, transferee: 0, transfer_target: 2, target_session: 1 }); + expect(e.toDict()).toEqual({ + type: 'blind-transfer', time: '2026-01-01T00:00:00.000Z', sessions: 0, party: 1, + transferee: 0, transfer_target: 2, target_session: 1 + }); + expect(Event.fromDict(e.toDict()).toDict()).toEqual(e.toDict()); + }); + + it('enforces the table in the constructor unless validate is false', () => { + expect(() => new Event({ type: 'keydown', time: T, sessions: 0, party: 0 })).toThrow(/button/); + expect(() => new Event({ type: 'join', time: T, sessions: 0, party: 0, button: '1' })).toThrow(/must not have field: button/); + expect(new Event({ type: 'keydown', time: T, validate: false }).type).toBe('keydown'); + }); + + it('keeps contributors null (a channel with no contributor)', () => { + const e = new Event({ type: 'channel-contributors', time: T, dialog: 0, channel: 0, contributors: null }); + expect(e.toDict().contributors).toBeNull(); + }); + + it('carries extension parameters', () => { + const e = new Event({ type: 'tool-call', time: T, tool_name: 'search' }); + expect(e.toDict()).toEqual({ type: 'tool-call', time: T, tool_name: 'search' }); + }); + + it('addEvent checks a plain object at isValid()', () => { + const v = Vcon.buildNew(); + v.addParty(new Party({ name: 'A' })); + v.addSession({ start: T, parties: [0] }); + expect(v.addEvent({ type: 'join', time: T, sessions: 0, party: 0 })).toBe(0); + expect(v.isValid().valid).toBe(true); + v.addEvent({ type: 'keydown', time: T, sessions: 0, party: 0 }); + expect(v.isValid().errors.some(e => /missing required field: button/.test(e))).toBe(true); + }); + + it('an unlisted extension Event type needs some extension in extensions', () => { + const v = Vcon.buildNew(); + v.addParty(new Party({ name: 'A' })); + v.addSession({ start: T, parties: [0] }); + v.addEvent({ type: 'tool-call', time: T, sessions: 0, party: 0 }); + expect(v.isValid().errors.some(e => /outside the core vocabulary/.test(e))).toBe(true); + v.addExtension('agent_session'); + expect(v.isValid().valid).toBe(true); + }); + + it('converts a deprecated PartyHistory to an Event', () => { + const spy = jest.spyOn(process, 'emitWarning').mockImplementation(() => undefined); + try { + const e = new PartyHistory(1, 'keydown', T, '5').toEvent([0, 1]); + expect(e.toDict()).toEqual({ type: 'keydown', time: T, sessions: [0, 1], party: 1, button: '5' }); + } finally { + spy.mockRestore(); + } + }); +}); diff --git a/src/__tests__/validation.test.ts b/src/__tests__/validation.test.ts index d552c3f..a4f78e5 100644 --- a/src/__tests__/validation.test.ts +++ b/src/__tests__/validation.test.ts @@ -1,7 +1,6 @@ import { Vcon } from '../vcon'; import { Dialog } from '../dialog'; import { Attachment } from '../attachment'; -import { PartyHistory } from '../party'; /** * Covers the validate() error branches on Dialog and Attachment that the @@ -39,30 +38,23 @@ describe('Dialog.validate error branches', () => { expect(r.errors.some(e => /both inline .* and external/.test(e))).toBe(true); }); - it('rejects content-bearing fields on a transfer dialog', () => { - const r = new Dialog({ type: 'transfer', start, parties: [0, 1], transferor: 0 }).validate(); - expect(r.errors.some(e => /Transfer dialog MUST NOT include/.test(e))).toBe(true); + it('rejects an unknown dialog type such as the removed transfer type', () => { + const r = new Dialog({ type: 'transfer', start, parties: [0, 1] }).validate(); + expect(r.errors.some(e => /Invalid dialog type: transfer/.test(e))).toBe(true); }); - it('flags a party_history event missing its required button', () => { - const d = new Dialog({ type: 'recording', start, parties: [0] }); - d.party_history = [new PartyHistory(0, 'keydown', start).toDict()]; - const r = d.validate(); - expect(r.errors.some(e => /button is required/.test(e))).toBe(true); + it('rejects a mediatype outside the known set', () => { + const r = new Dialog({ type: 'recording', start, parties: [0], mediatype: 'application/pdf' }).validate(); + expect(r.errors.some(e => /Invalid mediatype/.test(e))).toBe(true); }); }); describe('Attachment.validate error branches', () => { - it('requires a purpose (non-lawful_basis)', () => { + it('requires a purpose', () => { const r = new Attachment({ party: 0, dialog: 0 }).validate(); expect(r.errors.some(e => /must have a purpose/.test(e))).toBe(true); }); - it('accepts the lawful_basis extension without purpose', () => { - const r = new Attachment({ type: 'lawful_basis', party: 0, dialog: 0 } as any).validate(); - expect(r.valid).toBe(true); - }); - it('rejects external url without content_hash', () => { const r = new Attachment({ purpose: 'transcript', party: 0, dialog: 0, url: 'https://x/t.txt' }).validate(); expect(r.errors.some(e => /MUST include content_hash/.test(e))).toBe(true); @@ -78,15 +70,15 @@ describe('Vcon guards', () => { expect(() => Vcon.buildFromJson('{not json')).toThrow(/Failed to parse vCon JSON/); }); - it('throws when setting redacted while amended is set', () => { + it('throws when setting redacted_from while amended_from is set', () => { const v = Vcon.buildNew(); - v.amended = { uuid: '550e8400-e29b-41d4-a716-446655440000' }; - expect(() => { v.redacted = { type: 'pii' }; }).toThrow(/mutually exclusive/); + v.amended_from = { uuid: '550e8400-e29b-41d4-a716-446655440000' }; + expect(() => { v.redacted_from = { type: 'pii' }; }).toThrow(/mutually exclusive/); }); - it('throws when setting amended while redacted is set', () => { + it('throws when setting amended_from while redacted_from is set', () => { const v = Vcon.buildNew(); - v.redacted = { type: 'pii' }; - expect(() => { v.amended = { uuid: '550e8400-e29b-41d4-a716-446655440000' }; }).toThrow(/mutually exclusive/); + v.redacted_from = { type: 'pii' }; + expect(() => { v.amended_from = { uuid: '550e8400-e29b-41d4-a716-446655440000' }; }).toThrow(/mutually exclusive/); }); }); diff --git a/src/__tests__/vcon.test.ts b/src/__tests__/vcon.test.ts index 39a23b8..44c3836 100644 --- a/src/__tests__/vcon.test.ts +++ b/src/__tests__/vcon.test.ts @@ -86,6 +86,7 @@ describe('Vcon', () => { it('should add attachments with new API', () => { const vcon = Vcon.buildNew(); + vcon.addSession({ parties: [0] }); vcon.addAttachment({ purpose: 'document', mediatype: 'application/pdf', @@ -105,6 +106,7 @@ describe('Vcon', () => { it('should find attachments by purpose', () => { const vcon = Vcon.buildNew(); vcon.addAttachment({ + dialog: 0, purpose: 'transcript', body: 'Transcript content', mediatype: 'text/plain' @@ -151,7 +153,10 @@ describe('Vcon', () => { expect(tagsAttachments.length).toBe(1); const att = tagsAttachments[0]; expect(att.party).toBe(0); - expect(att.dialog).toBe(0); + // whole-vCon metadata lists every Session; a placeholder Session is added when there is none + expect(att.dialog).toBeUndefined(); + expect(att.session).toEqual([0]); + expect(vcon.sessions).toEqual([{}]); expect(att.encoding).toBe('json'); expect(typeof att.body).toBe('string'); expect(JSON.parse(att.body as string)).toEqual({ category: 'support', priority: 'high' }); @@ -229,23 +234,34 @@ describe('Vcon extensions (vcon-core)', () => { expect(vcon.critical).toContain('encrypted'); }); - it('should handle redacted property', () => { + it('should handle redacted_from property', () => { const vcon = Vcon.buildNew(); - expect(vcon.redacted).toBeUndefined(); - - vcon.redacted = { uuid: 'original-uuid' }; - expect(vcon.redacted).toEqual({ uuid: 'original-uuid' }); + expect(vcon.redacted_from).toBeUndefined(); - vcon.redacted = true; - expect(vcon.redacted).toBe(true); + vcon.redacted_from = { uuid: 'original-uuid', type: 'pii' }; + expect(vcon.redacted_from).toEqual({ uuid: 'original-uuid', type: 'pii' }); + expect((vcon.toDict() as any).redacted).toBeUndefined(); }); - it('should handle amended property', () => { + it('should handle amended_from property', () => { const vcon = Vcon.buildNew(); - expect(vcon.amended).toBeUndefined(); + expect(vcon.amended_from).toBeUndefined(); - vcon.amended = { uuid: 'amended-uuid' }; - expect(vcon.amended).toEqual({ uuid: 'amended-uuid' }); + vcon.amended_from = { uuid: 'amended-uuid' }; + expect(vcon.amended_from).toEqual({ uuid: 'amended-uuid' }); + }); + + it('keeps redacted and amended as deprecated aliases', () => { + const spy = jest.spyOn(process, 'emitWarning').mockImplementation(() => undefined); + try { + const vcon = Vcon.buildNew(); + vcon.redacted = { uuid: 'original-uuid', type: 'pii' }; + expect(vcon.redacted_from).toEqual({ uuid: 'original-uuid', type: 'pii' }); + expect(vcon.redacted).toEqual({ uuid: 'original-uuid', type: 'pii' }); + expect(spy).toHaveBeenCalled(); + } finally { + spy.mockRestore(); + } }); }); @@ -372,21 +388,22 @@ describe('Vcon analysis with vcon-core fields', () => { }); describe('Vcon vcon-core specific features', () => { - it('should have VCON_VERSION as 0.4.0', () => { - expect(VCON_VERSION).toBe('0.4.0'); + it('should have VCON_VERSION as 0.5.0 and emit it', () => { + expect(VCON_VERSION).toBe('0.5.0'); + expect(JSON.parse(Vcon.buildNew().toJson()).vcon).toBe('0.5.0'); }); - it('should handle redacted with type and content_hash (vcon-core)', () => { + it('should handle redacted_from with type and content_hash (vcon-core)', () => { const vcon = Vcon.buildNew(); - vcon.redacted = { + vcon.redacted_from = { uuid: 'original-uuid', type: 'pii-masked', url: 'https://example.com/original.vcon', content_hash: 'sha512-abc123' }; - expect(vcon.redacted).toEqual({ + expect(vcon.redacted_from).toEqual({ uuid: 'original-uuid', type: 'pii-masked', url: 'https://example.com/original.vcon', @@ -394,16 +411,16 @@ describe('Vcon vcon-core specific features', () => { }); }); - it('should handle amended with url and content_hash (vcon-core)', () => { + it('should handle amended_from with url and content_hash (vcon-core)', () => { const vcon = Vcon.buildNew(); - vcon.amended = { + vcon.amended_from = { uuid: 'prior-uuid', url: 'https://example.com/prior.vcon', content_hash: ['sha512-abc', 'sha256-def'] }; - expect(vcon.amended).toEqual({ + expect(vcon.amended_from).toEqual({ uuid: 'prior-uuid', url: 'https://example.com/prior.vcon', content_hash: ['sha512-abc', 'sha256-def'] From 0bc2099cfa12a98e5781eb63398b3596bbc40d4f Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:36:00 -0500 Subject: [PATCH 4/6] Release 1.0.0: update docs, examples and version Bump to 1.0.0 (breaking: writes syntax 0.5.0). Rewrite the README and the examples for Sessions and Events and add the migration guide. Co-Authored-By: Claude Opus 5.5 --- .vcon-meta.yaml | 2 +- CHANGELOG.md | 96 +++++++- CLAUDE.md | 25 +- README.md | 400 +++++++++++++++++++------------- examples/01-text-chat.ts | 44 ++-- examples/02-call-recording.ts | 56 +++-- examples/03-video-conference.ts | 119 ++++++---- examples/audio-video.ts | 65 +++--- examples/inline-recording.ts | 28 ++- examples/simple.ts | 46 ++-- package-lock.json | 4 +- package.json | 4 +- 12 files changed, 575 insertions(+), 314 deletions(-) diff --git a/.vcon-meta.yaml b/.vcon-meta.yaml index 4521378..08d3289 100644 --- a/.vcon-meta.yaml +++ b/.vcon-meta.yaml @@ -5,7 +5,7 @@ name: vcon-js category: core-library tags: [typescript, javascript, vcon, library, npm] description: "TypeScript/JavaScript library for creating and managing vCons" -spec_version: "0.4.0" +spec_version: "0.5.0" relationships: - type: related-to diff --git a/CHANGELOG.md b/CHANGELOG.md index 080abfd..d8aa518 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,9 +2,101 @@ All notable changes to `vcon-js` are documented here. Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/); this project uses semver -(pre-1.0, so a minor bump may carry breaking changes). +(a major bump carries breaking changes). -The `vcon` syntax parameter is `"0.4.0"` and is independent of the package version. +The `vcon` syntax parameter is `"0.5.0"` and is independent of the package version. + +## [1.0.0] — 2026-11-01 + +Retargets the library to `draft-ietf-vcon-vcon-core-05` (syntax `"0.5.0"`), matching the Python +reference implementation. This is a breaking release: the Dialog Object lost its transfer, +recording-set, party history and originator content, which moved to the new Session and Event +Objects. Readers accept `0.4.0` and `0.5.0`; writers emit `0.5.0`. + +### Added +- `Session` and `SessionReference` (`src/session.ts`), the top-level `sessions` array, + `Vcon.addSession()` and `Vcon.sessions`. +- `Event` (`src/event.ts`), the top-level `events` array, `Vcon.addEvent()` and `Vcon.events`. + The per-event-type parameter table (section 4.3.1.5) is enforced by `new Event(...)`, + `validateEvent()` and `Vcon.isValid()`. +- `redacted_from`, `amended_from` and `redacted_strings` top-level parameters and properties; + Dialog `redacted_segments`; Attachment `session`; Analysis `sessions` and `analysis`. +- Empty Dialog Objects: `Dialog.placeholder()` serializes as `{}`. `Dialog.fromDict()` wraps an + existing Dialog Object for reading. +- `migrate040To050(vcon, { strict })` (`src/migration.ts`), a table driven implementation of + Appendix A.1 (`MIGRATION_STEPS`, one entry per step T1 to T15) that returns + `{ vcon, report }`. The `MigrationReport` lists every inferred value, every fallback for a + required field and every unresolved item, and keeps the original content of removed Dialogs. + `MigrationError` is thrown for input that cannot be migrated and, in strict mode, when a + required field has no source. Signed input is migrated as its unsigned payload and the report + sets `resignRequired`; the library never re-signs. +- `Vcon.migrate040To050()` static method, `Vcon.migrationReport`, and the `migrateLegacy` and + `strictMigration` options on `new Vcon()` and `Vcon.buildFromJson()`. +- `Vcon.isValid()` and `Vcon.getValidationWarnings()`, backed by `validateVconDict()`. +- `Vcon.sign(key, alg = "RS256")`, `Vcon.verify(key)` and `Vcon.generateKeyPair()` (JWS with + Node `crypto`, no new dependency); `AlgorithmNotPermittedError`. This restores a signing + surface that 0.5.2 removed, because core-05 section 6.2.2 now forbids `alg` "none" and the + library needs somewhere to enforce it. +- `Vcon.addIncompleteDialog()`, `Vcon.findDialogsByType()`, `Vcon.findLawfulBasisAttachments()` + and `Vcon.hasLawfulBasis()`. +- Test fixtures: the core-05 Appendix C JSON Schema and the Appendix B examples, under + `src/__tests__/fixtures/`. The Appendix B examples and the library's output are validated + against the schema. Migration, Session, Event, signing and extension-enforcement tests are + ported from the reference implementation. + +### Changed +- **Breaking:** `VCON_VERSION` and `Vcon.buildNew()` emit `"0.5.0"` (was `"0.4.0"`). `Vcon.vcon` + is `undefined` when the input had no `vcon` parameter (it is optional in 0.5.0) instead of + defaulting. +- **Breaking:** a vCon that declares `"vcon": "0.4.0"` is migrated on load, so `vcon.vcon` reads + `"0.5.0"` and Dialog indices are preserved. Use `{ migrateLegacy: false }` to keep the raw + 0.4.0 object. A signed 0.4.0 vCon is kept signed on load; migrate it explicitly after + verifying. +- **Breaking:** `Vcon.redacted` and `Vcon.amended` are now `redacted_from` and `amended_from` + (`VconData.redacted` and `amended` are gone, and the boolean form is gone); the old names remain + as deprecated aliases on `Vcon` that warn. +- **Breaking:** Dialog types are `recording`, `text` and `incomplete`. `new Dialog({ type: 'audio' | 'video' })` + still works but warns and builds a `recording`; on read, `audio` and `video` Dialogs are + accepted and `getValidationWarnings()` notes them. The `transfer` and `recording-set` types are + gone, as are the Dialog parameters `party_history`, `originator`, `transferee`, `transferor`, + `transfer_target`, `original`, `consultation`, `target_dialog`, `recordings`, `recording_set` + and `transfer`; passing one to `new Dialog()` throws. `PartyHistory` is deprecated: it warns + and converts with `toEvent(sessions)`. `Dialog.isTransfer()` warns and returns false; + `Dialog.isRecordingSet()` is removed. `Dialog.type` and `Dialog.start` are optional in the + type, since `{}` is a valid Dialog. +- **Breaking:** Dialog `parties` are the contributors only (a nested list is several + contributors on one channel; `null` is a channel with no contributor). The receivers are the + `parties` of the Session that lists the Dialog. +- **Breaking:** attachments need `party` plus `dialog` (a single index; arrays are no longer + accepted) or `session`. The `dialog` default of `0` is gone. With neither given, + `addAttachment()` uses the only Session when the vCon has exactly one and throws otherwise; no + placeholder Session is added and a given `dialog` index is never widened to a Session. + `addTag()` (whole-vCon metadata) lists every Session and adds an empty placeholder Session + when there is none. `addAttachment()` defaults `start` to `created_at` and `mediatype` to + `application/json` for `encoding: "json"`. `Attachment.validate()` requires `start`, `party` + and `dialog` or `session`, and no longer accepts the `type: "lawful_basis"` form (the + extension uses `purpose: "lawful_basis"`). +- **Breaking:** `addDialog()` returns the new Dialog's index and takes an optional `session`. +- `addAnalysis()` accepts `sessions` and `analysis`, and defaults `encoding` to `"none"` for a + string body, which the schema requires. +- `isValid()` checks: a Session exists when there is dialog or events; all Session, Event, + attachment and analysis references; the Event parameter table; `redacted_from` and + `amended_from` exclusivity; that `extensions` lists every extension in use (`lawful_basis`, + `wtf_transcription`, or any value outside the core vocabulary) and every `critical` entry; + inline attachment `mediatype`; `__REDACTED_REF_#` references against `redacted_strings`; and + that `vcon`, when present, is `"0.5.0"`. +- `Dialog.validate()` rejects unknown Dialog types, content on an `incomplete` Dialog and media + types outside the known set (text, message and multipart subtypes are accepted). +- The vendored test schema is now the core-05 Appendix C schema (was the `0.4.0` schema). + +### Removed +- `Dialog.isRecordingSet()`, the `recording-set` and `transfer` Dialog types and their + parameters (see Changed). + +### Not changed +- Tags keep the JSON-string body and dictionary API. Encryption (JWE) is not implemented. +- The sample `*.vcon.json` files under `examples/` and `test-vcons/` are legacy data and were + not regenerated; the readers migrate them if they declare `0.4.0`. ## [0.5.2] — 2026-08-06 diff --git a/CLAUDE.md b/CLAUDE.md index d8857aa..c9b1f92 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,10 +11,15 @@ This library provides a complete implementation of the vCon specification for Ja ``` src/ ├── types.ts # TypeScript type definitions for vcon-core -├── vcon.ts # Main Vcon class for managing conversation containers -├── party.ts # Party and PartyHistory classes +├── vcon.ts # Main Vcon class: model, validation entry point, JWS sign/verify +├── party.ts # Party and (deprecated) PartyHistory classes ├── dialog.ts # Dialog class for conversation segments +├── session.ts # Session and SessionReference, validateSession +├── event.ts # Event class, the per-type parameter table, validateEvent ├── attachment.ts # Attachment class for related files +├── validation.ts # validateVconDict: the core-05 structural checks behind Vcon.isValid() +├── migration.ts # migrate040To050 and MigrationReport (Appendix A.1) +├── util.ts # Shared helpers (date parsing, base64url, warnings) ├── index.ts # Public API exports └── __tests__/ # Jest test files ├── vcon.test.ts @@ -36,16 +41,18 @@ The main container class. Use `Vcon.buildNew()` to create a new vCon or `Vcon.bu Represents conversation participants with identifiers (tel, sip, mailto, stir, did, uuid) and metadata. ### Dialog -Represents conversation segments. Five types per vcon-core: `recording`, `text`, `transfer`, `incomplete`, `recording-set`. +Represents conversation segments. Three types per core-05: `recording`, `text`, `incomplete`. `{}` is a valid placeholder (`Dialog.placeholder()`). Transfers, party history and recording sets are Event and Session Objects now. ### Attachment Represents attached files. Can be inline (body/encoding) or external (url/content_hash). ## vcon-core Compliance -The library implements draft-ietf-vcon-vcon-core (syntax `"0.4.0"`): +The library implements draft-ietf-vcon-vcon-core-05 (syntax `"0.5.0"`; 0.4.0 is read and migrated): -- **Dialog types**: recording, text, transfer, incomplete, recording-set +- **Dialog types**: recording, text, incomplete (audio/video accepted on read with a warning, never written) +- **Sessions and Events**: top-level `sessions` and `events`; a Session must exist when there is dialog or events +- **Attachments**: `party` plus `dialog` or `session`; scope is never invented - **Dispositions** (for incomplete): no-answer, congestion, failed, busy, hung-up, voicemail-no-message - **Encodings**: base64url, json, none (note: base64 is NOT valid per spec) - **Extensions**: support for `extensions` and `critical` arrays @@ -55,9 +62,11 @@ The library implements draft-ietf-vcon-vcon-core (syntax `"0.4.0"`): ### Compliance non-negotiables baked into the library - **Analysis body is a string.** `addAnalysis` auto-`JSON.stringify`s object/array bodies and forces `encoding: "json"`. -- **Attachments use `purpose`** (the `type` field has been removed). `party` and `dialog` indices default to `0` (vCon-level) when omitted. -- **Tags are attachments.** `vcon.addTag(k, v)` writes to a single `purpose: "tags"` attachment with `encoding: "json"`. `vcon.tags` and `vcon.getTag(k)` read the decoded body back out — there is no top-level `tags` field on the emitted JSON. -- **`redacted` and `amended` are mutually exclusive** — assigning one while the other is set throws. +- **Attachments use `purpose`** (the `type` field has been removed). `party` defaults to `0`; `dialog` or `session` is required and defaulted only when the vCon has exactly one Session. +- **Tags are attachments.** `vcon.addTag(k, v)` writes to a single `purpose: "tags"` attachment with `encoding: "json"`, scoped to every Session. `vcon.tags` and `vcon.getTag(k)` read the decoded body back out — there is no top-level `tags` field on the emitted JSON. +- **`redacted_from` and `amended_from` are mutually exclusive** — assigning one while the other is set throws. `redacted` and `amended` are deprecated aliases. +- **JWS `alg` "none" is rejected** by `sign()` and `verify()`. +- **0.4.0 input is migrated on load** (`migrate040To050`); signed 0.4.0 input is not. - **`group` has been removed** from the public surface (spec reserves it). - **`content_hash` format** is checked by `Dialog.validate()` and `Attachment.validate()`. diff --git a/README.md b/README.md index d7b0479..a07fd0d 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,8 @@ # vcon-js -A JavaScript/TypeScript library for creating and managing vCons (Virtual Conversations), compliant with [IETF draft-ietf-vcon-vcon-core](https://datatracker.ietf.org/doc/html/draft-ietf-vcon-vcon-core). +A JavaScript/TypeScript library for creating and managing vCons (Virtual Conversations), compliant with [IETF draft-ietf-vcon-vcon-core-05](https://datatracker.ietf.org/doc/html/draft-ietf-vcon-vcon-core) (syntax `"0.5.0"`). + +> **Version 1.0.0 is a breaking release.** It writes vCon syntax `0.5.0`. The Dialog Object lost its transfer, recording-set, party history and originator content, which moved to the new Session and Event Objects. The library still reads `0.4.0` vCons and migrates them on load. See [Migrating from 0.4.0](#migrating-from-040) and the [CHANGELOG](CHANGELOG.md). ## Installation @@ -12,42 +14,43 @@ npm install vcon-js ### Creating a new vCon +A conversation hangs off a Session. The Session lists the receivers (the first party is the implied originator), and a Dialog lists only its contributors. Core-05 requires at least one Session when there is dialog or there are events. + ```typescript -import { Vcon, Party, Dialog } from 'vcon-js'; +import { Vcon, Party, Dialog, Session } from 'vcon-js'; // Create a new vCon const vcon = Vcon.buildNew(); // Add parties -const party1 = new Party({ - tel: '+1234567890', - name: 'John Doe', - role: 'agent' -}); -const party2 = new Party({ - tel: '+0987654321', - name: 'Jane Smith', - role: 'customer' -}); - -vcon.addParty(party1); -vcon.addParty(party2); - -// Add a text dialog -const dialog = new Dialog({ - type: 'text', - start: new Date(), - parties: [0, 1], - body: 'Hello, this is a conversation!', - mediatype: 'text/plain' -}); +vcon.addParty(new Party({ tel: '+1234567890', name: 'John Doe', role: 'agent' })); +vcon.addParty(new Party({ tel: '+0987654321', name: 'Jane Smith', role: 'customer' })); + +// Add a Session; its parties are the receivers +const session = vcon.addSession(new Session({ start: new Date(), parties: [0, 1] })); + +// Add a text dialog to the Session. Its parties are the contributors (the sender). +vcon.addDialog( + new Dialog({ + type: 'text', + start: new Date(), + parties: [0], + body: 'Hello, this is a conversation!', + mediatype: 'text/plain', + encoding: 'none' + }), + session +); -vcon.addDialog(dialog); +// Check it against the core-05 rules +const { valid, errors } = vcon.isValid(); // Convert to JSON const json = vcon.toJson(); ``` +`addDialog` and `addIncompleteDialog` return the new Dialog's index. `isValid()` returns `{ valid, errors }`; `getValidationWarnings()` lists SHOULD-level findings. + ### Loading from JSON ```typescript @@ -57,32 +60,35 @@ const jsonString = '...'; // Your vCon JSON string const vcon = Vcon.buildFromJson(jsonString); ``` +A vCon that declares `"vcon": "0.4.0"` is migrated to 0.5.0 on load; the report is in `vcon.migrationReport`. See [Migrating from 0.4.0](#migrating-from-040). + ### Working with Attachments -Per draft-ietf-vcon-vcon-core §4.5, attachments are identified by `purpose` (the legacy `type` field has been removed in v0.4.0). `party` and `dialog` indices are required; both default to `0` (vCon-level) when omitted. +Per core-05 §4.6, an attachment has `purpose`, `start` and `party`, plus `dialog` (a single index) or `session` (an index or list). `party` defaults to 0 and `start` to the vCon's `created_at`. The library never invents the scope: with neither `dialog` nor `session`, `addAttachment` uses the only Session when the vCon has exactly one, and throws otherwise. A `dialog` index is never widened to a Session. ```typescript import { Vcon } from 'vcon-js'; -const vcon = Vcon.buildNew(); - -// Inline attachment +// vcon already has one Session, so the scope defaults to session 0 vcon.addAttachment({ purpose: 'document', mediatype: 'application/pdf', - body: 'base64EncodedContent', + body: 'base64urlEncodedContent', encoding: 'base64url', filename: 'document.pdf', - party: 0, - dialog: 0 + party: 0 }); +// Explicit scope +vcon.addAttachment({ purpose: 'note', body: 'hi', encoding: 'none', mediatype: 'text/plain', party: 1, dialog: 0 }); +vcon.addAttachment({ purpose: 'note', body: 'hi', encoding: 'none', mediatype: 'text/plain', party: 1, session: [0, 1] }); + // External attachment (url + content_hash both required; content_hash must // match sha512-) vcon.addAttachment({ purpose: 'transcript', url: 'https://example.com/transcript.txt', - content_hash: 'sha512-Tf9OoDQfCoI_FdP08BqxLq4OXaV5zLhR-NvZ3-hMWLLN7iZA50Dh7hctp5Om55Vg5ff5vQWKEqKAQz7W-kZRCg==', + content_hash: 'sha512-Tf9OoDQfCoI_FdP08BqxLq4OXaV5zLhR-NvZ3-hMWLLN7iZA50Dh7hctp5Om55Vg5ff5vQWKEqKAQz7W-kZRCg', mediatype: 'text/plain' }); @@ -115,6 +121,7 @@ vcon.addAnalysis({ vcon.addAnalysis({ type: 'transcription', dialog: [0, 1], + sessions: 0, // optional: Session(s) the analysis is based on vendor: 'whisper', url: 'https://example.com/transcription.json', content_hash: 'sha512-xyz789...', @@ -127,21 +134,22 @@ const sentimentAnalysis = vcon.findAnalysisByType('sentiment'); ### Working with Dialog Types -vcon-core defines five dialog types: `recording`, `text`, `transfer`, `incomplete`, and `recording-set`. +Core-05 defines three dialog types: `recording` (audio or video, told apart by `mediatype`), `text`, and `incomplete` (a conversation that failed to be set up, with no content). A Dialog's `parties` are its contributors; a nested list puts several contributors on one channel and `null` marks a channel with no contributor. The receivers are the `parties` of the Session that lists the Dialog. ```typescript import { Dialog } from 'vcon-js'; -// Text dialog +// Text dialog: the sender const textDialog = new Dialog({ type: 'text', start: new Date(), - parties: [0, 1], + parties: [0], body: 'Hello!', - mediatype: 'text/plain' + mediatype: 'text/plain', + encoding: 'none' }); -// Recording dialog with external audio +// Recording dialog with external audio: one channel per contributor const recordingDialog = new Dialog({ type: 'recording', start: new Date(), @@ -154,36 +162,58 @@ recordingDialog.addExternalData( { filename: 'call.wav', content_hash: 'sha512-abc...' } ); -// Incomplete dialog (e.g., no answer) -const incompleteDialog = new Dialog({ - type: 'incomplete', - start: new Date(), - parties: [0], - disposition: 'no-answer' -}); +// Incomplete dialog (e.g., no answer): the party that tried +vcon.addIncompleteDialog({ start: new Date(), disposition: 'no-answer', parties: [0], session: 0 }); -// Check dialog types -console.log(textDialog.isText()); // true -console.log(recordingDialog.isRecording()); // true -console.log(incompleteDialog.isIncomplete()); // true +// An empty placeholder Dialog ({}) holds an array position so indices do not shift +vcon.addDialog(Dialog.placeholder()); ``` -### Recording sets, attachment-based analysis, provenance +`Dialog` rejects the parameters core-05 removed (`originator`, `party_history`, `transferee`, `transferor`, `transfer_target`, `original`, `consultation`, `target_dialog`, `recordings`, `recording_set`). `type: 'audio'` and `type: 'video'` still build a `recording` and emit a deprecation warning; on read they are accepted with a validation warning. -Additions tracking the current core draft: +### Sessions and Events ```typescript -import { Vcon, Dialog } from 'vcon-js'; +import { Vcon, Session, SessionReference, Event } from 'vcon-js'; const vcon = Vcon.buildNew(); +// ... parties, dialogs ... + +// Sessions relate to each other with Session_Reference (child, peer, precursor, breakout) +const call = vcon.addSession(new Session({ start: T, duration: 600, parties: [0, 1] })); +const consult = vcon.addSession(new Session({ + start: T, + parties: [1, 2], + sessions: [new SessionReference(call, 'peer', 'consultation call')] +})); -// A recording-set groups member recording dialogs by index -vcon.addDialog(new Dialog({ type: 'recording-set', start: new Date(), recordings: [1, 2] })); -vcon.addDialog(new Dialog({ type: 'recording', start: new Date(), parties: [0], recording_set: 0, - url: 'https://example.com/a.wav', content_hash: 'sha512-...' })); +// Events: join, drop, hold, unhold, mute, unmute, keydown, keyup, consultation-start, +// blind-transfer, consultative-transfer, transfer-abandoned, channel-contributors. +vcon.addEvent(new Event({ type: 'join', time: T, sessions: call, party: 0 })); +vcon.addEvent(new Event({ type: 'keydown', time: T, sessions: call, party: 0, button: '5' })); +vcon.addEvent(new Event({ + type: 'blind-transfer', + time: T, + sessions: call, // the original call + party: 1, // the Transferor + transferee: 0, + transfer_target: 2, + target_session: consult +})); +``` + +`new Event(...)` enforces the per-type parameter table of core-05 §4.3.1.5 and throws on a missing or forbidden parameter. A plain object passed to `addEvent` is checked by `isValid()`. -// Analysis can key off an attachment instead of a dialog (dialog is optional) +### Attachment-based analysis and provenance + +```typescript +import { Vcon, Dialog } from 'vcon-js'; + +const vcon = Vcon.buildNew(); + +// Analysis can key off an attachment, Session or other analysis instead of a dialog vcon.addAnalysis({ type: 'summary', attachment: 0, vendor: 'acme', body: { text: 'hi' } }); +vcon.addAnalysis({ type: 'summary', sessions: 0, vendor: 'acme', body: 'short summary' }); // Generation provenance (draft-howe-vcon-provenance) on machine-generated dialog or analysis vcon.addAnalysis({ type: 'summary', dialog: 0, vendor: 'acme', @@ -193,13 +223,32 @@ vcon.addAnalysis({ type: 'summary', dialog: 0, vendor: 'acme', Every other extension parameter round-trips untyped via a catch-all, so you can attach any extension's fields without a typed helper. +### Redaction and amendment + +`redacted_from` and `amended_from` (renamed from `redacted` and `amended`) are mutually exclusive. The old property names remain on `Vcon` as deprecated aliases. + +```typescript +vcon.redacted_from = { uuid: '...', type: 'pii', url: 'https://example.com/o.vcon', content_hash: 'sha512-...' }; +// a string can carry __REDACTED_REF_7 if redacted_strings has { ref: 7 } +vcon.data.redacted_strings = [{ ref: 7 }]; +``` + ### Signing -vcon-js does not bundle a signing implementation. It emits the unsigned vCon form; wrap it in -JWS/JWE yourself with a library of your choice (e.g. `jose`). `jose` and `jsonwebtoken` are no -longer dependencies. +`sign()` and `verify()` produce and check a JWS (general serialization with one signature) with Node's `crypto`. `alg` defaults to `RS256`; `none` is rejected on both sides (core-05 §6.2.2) with `AlgorithmNotPermittedError`, and `verify()` returns `false` when no `alg` is declared. + +```typescript +import { Vcon } from 'vcon-js'; + +const { privateKey, publicKey } = Vcon.generateKeyPair(); +vcon.sign(privateKey); // RS256; also RS384/512, PS256/384/512, ES256/384/512, EdDSA +vcon.verify(publicKey); // true +vcon.sign(privateKey, 'none'); // throws AlgorithmNotPermittedError +``` + +Encryption (JWE) is not implemented; wrap the vCon with a library of your choice. -### Working with Extensions (vcon-core) +### Working with Extensions ```typescript import { Vcon } from 'vcon-js'; @@ -217,9 +266,31 @@ console.log(vcon.hasExtension('contact_center')); // true console.log(vcon.isCriticalExtension('encrypted')); // true ``` +`extensions` MUST list every extension in use. `isValid()` reports `lawful_basis` and `wtf_transcription` attachments or analysis that are not listed, every `critical` entry that is not in `extensions`, and values outside the core vocabulary (event types, encodings, dispositions, Session_Reference types) when `extensions` is empty. + +### Lawful basis + +The `lawful_basis` extension records the basis for processing as an attachment with `purpose: "lawful_basis"`, scoped with `party` plus `session`. This library does not create one for you and never invents a basis. Add it yourself, list the extension, and check with `hasLawfulBasis()`: + +```typescript +vcon.addAttachment({ + purpose: 'lawful_basis', + party: 0, + session: 0, + encoding: 'json', + body: { lawful_basis: 'consent', /* ...per the lawful basis extension draft */ } +}); +vcon.addExtension('lawful_basis'); + +vcon.hasLawfulBasis(); // true +vcon.findLawfulBasisAttachments(0); // lawful_basis attachments for party 0 +``` + +`getValidationWarnings()` flags a `lawful_basis` attachment that has no `party` or no `session`. + ### Working with Tags -Tags are stored as a single attachment with `purpose: "tags"`, `party: 0`, `dialog: 0`, and a JSON-string body (per the speckit Tags Convention). The `addTag` / `getTag` / `tags` API hides the encoding — there is no top-level `tags` field in the emitted JSON. +Tags are stored as a single attachment with `purpose: "tags"`, `party: 0`, `session` listing every Session, and a JSON-string body. Tags describe the whole vCon, so if the vCon has no Session, an empty placeholder Session is added to scope the attachment. The `addTag` / `getTag` / `tags` API hides the encoding — there is no top-level `tags` field in the emitted JSON. ```typescript import { Vcon } from 'vcon-js'; @@ -233,49 +304,39 @@ vcon.getTag('category'); // 'support' vcon.tags; // { category: 'support', priority: 'high' } ``` -### Working with Party History +### Migrating from 0.4.0 -Track party events within a dialog (join, drop, hold, unhold, mute, unmute, keydown, keyup): +Readers accept `0.4.0` and `0.5.0`; writers emit `0.5.0`. A 0.4.0 vCon passed to `new Vcon(...)` or `Vcon.buildFromJson(...)` is migrated, following Appendix A.1 of core-05, and the result carries a report of everything the draft did not dictate. ```typescript -import { Dialog, PartyHistory } from 'vcon-js'; - -const dialog = new Dialog({ - type: 'recording', - start: new Date(), - parties: [0, 1] -}); - -// Add party history events -dialog.party_history = [ - new PartyHistory(0, 'join', new Date()).toDict(), - new PartyHistory(1, 'join', new Date(Date.now() + 5000)).toDict(), - new PartyHistory(1, 'hold', new Date(Date.now() + 60000)).toDict(), - new PartyHistory(1, 'unhold', new Date(Date.now() + 120000)).toDict(), - // DTMF keypress events (button parameter required for keydown/keyup) - new PartyHistory(0, 'keydown', new Date(Date.now() + 150000), '5').toDict(), - new PartyHistory(0, 'keyup', new Date(Date.now() + 150100), '5').toDict(), - new PartyHistory(0, 'drop', new Date(Date.now() + 300000)).toDict(), - new PartyHistory(1, 'drop', new Date(Date.now() + 300000)).toDict() -]; +import { Vcon, migrate040To050 } from 'vcon-js'; + +// On load +const vcon = Vcon.buildFromJson(old040Json); +vcon.vcon; // '0.5.0' +vcon.migrationReport?.summary(); // '4 inferred, 0 fallback, 1 unresolved' + +// Or directly, on a plain object +const { vcon: migrated, report } = migrate040To050(old040Object); +report.inferred; // values the migration chose +report.fallbacks; // required fields filled with a documented fallback +report.unresolved; // problems left for a person +report.removedDialogs; // original content of every Dialog replaced by {}, by index + +// Strict mode throws MigrationError instead of using a fallback +migrate040To050(old040Object, { strict: true }); ``` -### Transfer Dialogs +What the migration does: -Represent call transfers between parties: +- Adds one Session that lists every kept Dialog; each `recording-set` Dialog becomes its own Session. +- Turns `party_history` entries into Events and `transfer` Dialogs into transfer Events, with Sessions for the original, consultation and target calls. +- Moves `originator` to the Session, and reduces a text or incomplete Dialog's `parties` to the sender. +- Replaces each removed Dialog with `{}` so no Dialog index changes, and re-points analysis and attachments that referenced one. +- Renames `redacted` and `amended`, and adds the extensions in use to `extensions`. +- Lists every dropped field with its value in the report. It never promotes a receiver to sender when the sender is `null`, and never defaults an attachment's scope unless the result has exactly one Session. -```typescript -import { Dialog } from 'vcon-js'; - -const transferDialog = new Dialog({ - type: 'transfer', - start: new Date(), - parties: [0, 1, 2], // Original caller, original agent, new agent - transferor: 1, // Agent initiating transfer - transferee: 0, // Caller being transferred - transfer_target: 2 // New agent receiving transfer -}); -``` +Signed input is not migrated on load, because migrating drops the signature. Verify it first, then call `Vcon.migrate040To050(signed)`; the report sets `resignRequired`. Pass `{ migrateLegacy: false }` to keep a 0.4.0 object untouched (`isValid()` then reports it as not 0.5.0). ### Working with Message IDs @@ -328,13 +389,18 @@ The main class for working with vCons. #### Static Methods - `buildNew()`: Creates a new vCon with UUID and timestamp -- `buildFromJson(jsonString: string)`: Creates a vCon from JSON string +- `buildFromJson(jsonString, options?)`: Creates a vCon from JSON string; a 0.4.0 vCon is migrated +- `migrate040To050(source, { strict? })`: Explicitly migrates a 0.4.0 vCon (object or JSON, signed or not) and returns a `Vcon` with `migrationReport` +- `generateKeyPair()`: RSA 2048 key pair for `sign()` #### Instance Methods - `addParty(party: Party)`: Adds a party to the vCon -- `addDialog(dialog: Dialog)`: Adds a dialog to the vCon -- `addAttachment(params)`: Adds an attachment (inline or external). `purpose` required; `party`/`dialog` default to 0. +- `addSession(session?)`: Adds a Session (empty if omitted); returns its index +- `addEvent(event)`: Adds an Event; returns its index +- `addDialog(dialog, session?)`: Adds a dialog, optionally to a Session; returns its index +- `addIncompleteDialog(params)`: Adds an `incomplete` dialog; returns its index +- `addAttachment(params)`: Adds an attachment (inline or external). `purpose` required; `party` defaults to 0; `dialog` or `session` required unless the vCon has exactly one Session. - `addAnalysis(params)`: Adds analysis data. Object/array bodies are auto-serialized to a JSON string. - `addTag(tagName, tagValue)`: Adds a tag (writes to the `purpose: "tags"` attachment). - `addExtension(name)`: Adds a non-critical extension @@ -346,25 +412,33 @@ The main class for working with vCons. - `hasExtension(name)`: Checks if extension is used - `isCriticalExtension(name)`: Checks if extension is critical - `getTag(tagName)`: Gets a tag value +- `findLawfulBasisAttachments(party?)`, `hasLawfulBasis()`: Lawful basis attachments +- `isValid()`: `{ valid, errors }` against core-05 +- `getValidationWarnings()`: SHOULD-level findings +- `sign(privateKey, alg?)`, `verify(publicKey)`: JWS; `alg` `none` is rejected - `toJson()`: Converts the vCon to JSON string - `toDict()`: Converts the vCon to a plain object #### Properties - `uuid`: Unique identifier -- `vcon`: Version string +- `vcon`: Syntax version (`"0.5.0"`) +- `migrationReport`: `MigrationReport` when the input was migrated from 0.4.0 - `created_at`: Creation timestamp (RFC3339) - `updated_at`: Last modification timestamp - `subject`: Conversation subject - `parties`: Array of parties +- `sessions`: Array of Session Objects +- `events`: Array of Event Objects - `dialog`: Array of dialogs - `attachments`: Array of attachments - `analysis`: Array of analysis results - `tags`: Decoded tag dictionary (read-through view of the `purpose: "tags"` attachment) - `extensions`: Non-critical extensions array - `critical`: Critical extensions array -- `redacted`: Redaction reference (mutually exclusive with `amended`) -- `amended`: Amendment reference (mutually exclusive with `redacted`) +- `redacted_from`: Reference to the unredacted vCon (mutually exclusive with `amended_from`); `redacted` is a deprecated alias +- `amended_from`: Reference to the prior version (mutually exclusive with `redacted_from`); `amended` is a deprecated alias +- `redacted_strings`: Redacted substring entries - `meta`: Additional metadata ### Party @@ -401,17 +475,16 @@ Class for representing dialogs in a vCon. #### Static Constants ```typescript -Dialog.DIALOG_TYPES // ['recording', 'text', 'transfer', 'incomplete'] +Dialog.DIALOG_TYPES // ['recording', 'text', 'incomplete'] Dialog.DISPOSITIONS // ['no-answer', 'congestion', 'failed', 'busy', 'hung-up', 'voicemail-no-message'] Dialog.VALID_ENCODINGS // ['base64url', 'json', 'none'] ``` #### Properties -- `type: string`: Dialog type (`recording`, `text`, `transfer`, `incomplete`) -- `start: Date | string`: Start time (RFC3339) -- `parties?: number | number[]`: Party indices -- `originator?: number`: Originator party index +- `type?: string`: Dialog type (`recording`, `text`, `incomplete`); absent on a placeholder +- `start?: Date | string`: Start time (RFC3339) +- `parties?: number | Array`: Contributing party indices - `mediatype?: string`: MIME type - `filename?: string`: Original filename - `body?: string`: Inline content @@ -421,7 +494,7 @@ Dialog.VALID_ENCODINGS // ['base64url', 'json', 'none'] - `duration?: number`: Duration in seconds - `disposition?: string`: Disposition for incomplete dialogs - `session_id?: SessionId`: Session identifier (with `local` and `remote` UUIDs per RFC 7989) -- `party_history?: PartyHistory[]`: Party event history +- `redacted_segments?: { start, end }[]`: Redacted segments of the content - `application?: string`: Application that created the dialog (e.g., 'zoom', 'teams') - `message_id?: string`: Message identifier for cross-referencing (e.g., SMTP message-id) @@ -430,11 +503,13 @@ Dialog.VALID_ENCODINGS // ['base64url', 'json', 'none'] - `toDict()`: Converts to plain object - `addExternalData(url, mediatype, options?)`: Adds external data reference - `addInlineData(body, mediatype, options?)`: Adds inline data +- `static placeholder()`, `isPlaceholder()`: An empty Dialog (`{}`) +- `static fromDict(data)`: Wraps an existing Dialog Object for reading - `isExternalData()`: Checks if has external data - `isInlineData()`: Checks if has inline data - `isText()`: Checks if text type - `isRecording()`: Checks if recording type -- `isTransfer()`: Checks if transfer type +- `isTransfer()`: Deprecated, always `false` - `isIncomplete()`: Checks if incomplete type - `isAudio()`: Checks if audio content - `isVideo()`: Checks if video content @@ -454,9 +529,10 @@ Attachment.VALID_ENCODINGS // ['base64url', 'json', 'none'] #### Properties - `purpose?: string`: Purpose/category (REQUIRED in core) -- `start?: Date | string`: Reference time -- `party?: number`: Related party index (defaults to `0`) -- `dialog?: number | number[]`: Related dialog index/indices (defaults to `0`) +- `start?: Date | string`: Reference time (REQUIRED) +- `party?: number`: Contributing party index (defaults to `0`) +- `dialog?: number`: Related dialog index +- `session?: number | number[]`: Related Session index or indices (at least one of `dialog` or `session` is required; neither is defaulted) - `mediatype?: string`: Media type - `filename?: string`: Original filename - `body?: any`: Inline content @@ -473,36 +549,29 @@ Attachment.VALID_ENCODINGS // ['base64url', 'json', 'none'] - `isInlineData()`: Checks if has inline data - `validate()`: Validates against vcon-core -### PartyHistory +### Session -Class for tracking party events within a dialog. +`new Session({ start?, duration?, parties?, originator?, session_id?, sessions?, dialog? })`. `parties` are the receivers (the first is the implied originator); `originator` is only set when it is not the first party. `toDict()` omits unset parameters, and an empty Session is `{}`. `SessionReference(session, type, description?)` is a Session_Reference Object. `validateSession()` checks a Session object. -#### Static Constants +### Event -```typescript -PartyHistory.VALID_EVENTS // ['join', 'drop', 'hold', 'unhold', 'mute', 'unmute', 'keydown', 'keyup'] -``` +`new Event({ type, time, sessions?, party?, dialog?, channel?, contributors?, button?, transferee?, transfer_target?, consultation?, target_session?, ...extension })`. The constructor enforces the parameter table of core-05 §4.3.1.5 (`EVENT_PARAMETER_RULES`; `validate: false` skips it). `validateEvent()` checks an Event object. `CORE_EVENT_TYPES` lists the thirteen core types. + +### PartyHistory (deprecated) -#### Constructor +The 0.4.0 Dialog `party_history` entry. Constructing one warns. Convert it with `toEvent(sessions)`. ```typescript -new PartyHistory(party: number, event: string, time: Date | string, button?: string) +new PartyHistory(party: number, event: string, time: Date | string, button?: string).toEvent(sessions) ``` -#### Properties +### Migration -- `party: number`: Party index -- `event: string`: Event type (`join`, `drop`, `hold`, `unhold`, `mute`, `unmute`, `keydown`, `keyup`) -- `time: Date | string`: Event timestamp -- `button?: string`: DTMF digit or button label (required for `keydown`/`keyup` events) +- `migrate040To050(vcon, { strict? })`: returns `{ vcon, report }`. Throws `MigrationError`. +- `MigrationReport`: `inferred`, `fallbacks`, `unresolved`, `notes`, `removedDialogs`, `resignRequired`, `stepsRun`, `entries`, `summary()`, `toDict()`. +- `MIGRATION_STEPS`: the table of steps T1 to T15 in execution order. -#### Methods - -- `toDict()`: Converts to plain object with ISO timestamp -- `static fromDict(data)`: Creates PartyHistory from plain object -- `validate()`: Validates event type and button requirement - -### SessionId +### SessionId### SessionId Session identifier object per RFC 7989. @@ -516,12 +585,12 @@ Session identifier object per RFC 7989. ```typescript import { VCON_VERSION } from 'vcon-js'; -console.log(VCON_VERSION); // '0.4.0' +console.log(VCON_VERSION); // '0.5.0' ``` ## Tutorial Examples -The `examples/` directory contains three comprehensive tutorials demonstrating real-world usage: +The `examples/` directory contains three comprehensive tutorials demonstrating real-world usage. Each builds a valid core-05 vCon and prints `isValid()`. None of them records a lawful basis; add a `lawful_basis` attachment before using the pattern for real conversations. ### Example 1: Text Chat Conversation @@ -530,6 +599,7 @@ The `examples/` directory contains three comprehensive tutorials demonstrating r A customer support chat conversation demonstrating: - Creating parties with different identifiers (tel, mailto) +- One Session for the chat, with each message a text Dialog from its sender - Building a multi-turn text conversation - Setting conversation subject and tags - Serializing and deserializing vCons @@ -540,14 +610,15 @@ const vcon = Vcon.buildNew(); vcon.addParty(new Party({ tel: '+1-555-123-4567', name: 'Customer', role: 'customer' })); vcon.addParty(new Party({ mailto: 'agent@company.com', name: 'Agent', role: 'agent' })); +const session = vcon.addSession(new Session({ start: new Date(), parties: [0, 1] })); vcon.addDialog(new Dialog({ type: 'text', start: new Date().toISOString(), - parties: [0, 1], - originator: 0, + parties: [0], // the sender body: 'Hi, I need help with my account.', - mediatype: 'text/plain' -})); + mediatype: 'text/plain', + encoding: 'none' +}), session); ``` ### Example 2: Phone Call Recording with Analysis @@ -561,13 +632,14 @@ An insurance claim phone call demonstrating: - Party validation (STIR/SHAKEN) - Multiple analysis types (transcription, sentiment, topic classification) - Contact center extensions -- Party history tracking (join, hold, resume, leave events) +- Call events (join, hold, resume, drop) as Event Objects ```typescript // Quick start - call recording const vcon = Vcon.buildNew(); vcon.addExtension('contact_center'); +const session = vcon.addSession(new Session({ start: new Date(), duration: 847, parties: [0, 1] })); const recordingDialog = new Dialog({ type: 'recording', start: new Date().toISOString(), @@ -575,6 +647,7 @@ const recordingDialog = new Dialog({ duration: 847, campaign: 'claims-inbound' }); +vcon.addDialog(recordingDialog, session); recordingDialog.addExternalData( 'https://storage.example.com/call.wav', @@ -598,13 +671,13 @@ vcon.addAnalysis({ A multi-party product roadmap meeting demonstrating: - 5+ party conferences -- Video recording dialogs -- Incomplete dialogs (failed join attempts) +- Video recording dialogs in a meeting Session +- Join and drop Events +- An incomplete dialog for a failed join attempt, in a Session related to the meeting by a Session_Reference - Multiple attachments (presentations, notes, chat transcripts) - Inline and external content storage -- Group references for meeting series - Meeting-specific analysis (action items, summaries) -- Validation of dialog objects +- Validation of the dialogs and the whole vCon ```typescript // Quick start - video conference @@ -617,25 +690,25 @@ vcon.addExtension('meeting'); vcon.addParty(new Party({ mailto: `${role.toLowerCase()}@company.com`, role: i === 0 ? 'host' : 'participant' })); }); -// Add recording with party history -const videoDialog = new Dialog({ +// Add the meeting Session and its recording +const meeting = vcon.addSession(new Session({ start: new Date(), duration: 3720, parties: [0, 1, 2, 3, 4] })); +vcon.addDialog(new Dialog({ type: 'recording', start: new Date().toISOString(), parties: [0, 1, 2, 3, 4], duration: 3720, application: 'zoom' -}); +}), meeting); -// Add attachments +// Add attachments, scoped to the meeting vcon.addAttachment({ purpose: 'presentation', filename: 'roadmap.pptx', body: '...', - encoding: 'base64url' + encoding: 'base64url', + mediatype: 'application/vnd.openxmlformats-officedocument.presentationml.presentation', + session: meeting }); - -// Link to meeting series -vcon.addGroup({ uuid: 'roadmap-series-2025', type: 'meeting-series' }); ``` ### Running All Examples @@ -652,29 +725,32 @@ npm run examples ## vcon-core Compliance -This library implements the [IETF draft-ietf-vcon-vcon-core](https://datatracker.ietf.org/doc/html/draft-ietf-vcon-vcon-core) specification, including: +This library implements [draft-ietf-vcon-vcon-core-05](https://datatracker.ietf.org/doc/html/draft-ietf-vcon-vcon-core), including: -- **Syntax parameter**: `0.4.0` (note: the `vcon` parameter is DEPRECATED per Section 4.1.1). Unchanged as the draft advanced past -02. -- **Dialog Types**: `recording`, `text`, `transfer`, `incomplete`, `recording-set` -- **Recording sets**: `recordings[]` on a `recording-set` dialog and `recording_set` back-reference on member recordings +- **Syntax parameter**: `0.5.0` written; `0.4.0` read and migrated (Appendix A.1). The `vcon` parameter is optional. +- **Sessions and Events**: top-level `sessions` (with Session_Reference types `child`, `peer`, `precursor`, `breakout`) and `events` arrays; at least one Session when there is dialog or events; the per-type Event parameter table +- **Dialog Types**: `recording`, `text`, `incomplete`; empty `{}` placeholder Dialogs; `audio` and `video` accepted on read with a warning and never written +- **Attachments**: `party` plus `dialog` or `session`; scope is never invented +- **Redaction and amendment**: `redacted_from`, `amended_from` (exclusive), `redacted_strings` with `__REDACTED_REF_#` checks, Dialog `redacted_segments` +- **Signing**: JWS `alg` `none` rejected on sign and verify +- **Extensions**: `extensions` MUST list every extension in use; every `critical` entry must be listed - **Dispositions**: `no-answer`, `congestion`, `failed`, `busy`, `hung-up`, `voicemail-no-message` - **Encodings**: `base64url`, `json`, `none` - **Content Hash**: SHA-512 hash format for external references (supports array for multiple algorithms) -- **Extensions**: `extensions`/`critical` arrays; every extension parameter round-trips untyped, with `provenance` (draft-howe-vcon-provenance) typed on dialog and analysis -- **Analysis source**: keyed off `dialog` and/or `attachment` (`dialog` is optional; `vendor` is required) +- **Analysis source**: keyed off `dialog`, `sessions`, `attachment` and/or `analysis` (all optional; `vendor` is required) - **Party Identifiers**: tel, sip, mailto, stir, did, uuid; plus `type`, `org`, `dept` - **Date Format**: RFC3339 timestamps - **SessionId**: Object with `local` and `remote` UUIDs per RFC 7989 -- **PartyHistory Events**: `join`, `drop`, `hold`, `unhold`, `mute`, `unmute`, `keydown`, `keyup` - **Message ID**: Support for `message_id` parameter in dialogs for cross-referencing -- **Redacted/Amended**: Enhanced with `type`, `url`, and `content_hash` parameters + +The core-05 Appendix B examples and the library's output are validated against the Appendix C JSON Schema in the test suite (`src/__tests__/fixtures/`). ## Development ```bash npm install # Install dependencies npm run build # Compile TypeScript -npm test # Run tests (83 tests) +npm test # Run tests npm run lint # Run ESLint npm run format # Format with Prettier ``` diff --git a/examples/01-text-chat.ts b/examples/01-text-chat.ts index cfbea3f..bfa8373 100644 --- a/examples/01-text-chat.ts +++ b/examples/01-text-chat.ts @@ -5,14 +5,16 @@ * text chat conversation between an agent and a customer. * * Key concepts covered: - * - Creating a new vCon + * - Creating a new vCon (syntax "0.5.0") * - Adding parties with different identifiers - * - Creating text dialogs + * - Grouping the conversation in a Session (core-05) + * - Creating text dialogs: a text Dialog's parties are the sender only, + * the Session lists the receivers * - Adding tags for classification - * - Serializing to JSON + * - Validating and serializing to JSON */ -import { Vcon, Party, Dialog } from '../src'; +import { Vcon, Party, Dialog, Session } from '../src'; console.log('=== Example 1: Text Chat Conversation ===\n'); @@ -42,7 +44,12 @@ const agent = new Party({ vcon.addParty(agent); console.log('Added agent:', agent.name); -// Step 4: Create the conversation (simulating a chat) +// Step 4: Add a Session. Core-05 requires one when there is dialog. The Session +// parties are the receivers; the first party is the implied originator. +const startTime = new Date(); +const session = vcon.addSession(new Session({ start: startTime, parties: [0, 1] })); + +// Step 5: Create the conversation (simulating a chat) const conversationMessages = [ { from: 0, text: "Hi, I'm having trouble logging into my account." }, { from: 1, text: "Hello Alice! I'd be happy to help you with that. Can you tell me what error message you're seeing?" }, @@ -57,18 +64,17 @@ const conversationMessages = [ ]; // Add each message as a dialog -let messageTime = new Date(); +let messageTime = startTime; conversationMessages.forEach((msg) => { const dialog = new Dialog({ type: 'text', start: messageTime.toISOString(), - parties: [0, 1], // Both parties are part of the conversation - originator: msg.from, // Who sent this message + parties: [msg.from], // Contributors only: the sender of this message body: msg.text, mediatype: 'text/plain', encoding: 'none' }); - vcon.addDialog(dialog); + vcon.addDialog(dialog, session); // Simulate time passing between messages (10-30 seconds) messageTime = new Date(messageTime.getTime() + (10 + Math.random() * 20) * 1000); @@ -76,7 +82,7 @@ conversationMessages.forEach((msg) => { console.log(`\nAdded ${conversationMessages.length} dialog messages`); -// Step 5: Set conversation subject and add tags +// Step 6: Set conversation subject and add tags vcon.subject = 'Account Login Issue - Locked Account'; vcon.addTag('category', 'account-support'); vcon.addTag('resolution', 'resolved'); @@ -86,12 +92,23 @@ console.log('\nConversation metadata:'); console.log(` Subject: ${vcon.subject}`); console.log(` Tags: ${JSON.stringify(vcon.tags)}`); -// Step 6: Serialize to JSON +// Step 7: Check the vCon against core-05, then serialize to JSON +const { valid, errors } = vcon.isValid(); +console.log(`\nvCon is valid: ${valid}`); +if (!valid) { + console.log(errors); + process.exit(1); +} +// This example records no lawful basis. Add a purpose "lawful_basis" attachment +// before using this pattern for real conversations. +console.log(`Carries a lawful_basis attachment: ${vcon.hasLawfulBasis()}`); + + const jsonOutput = vcon.toJson(); console.log('\n--- Serialized vCon JSON ---'); console.log(JSON.stringify(JSON.parse(jsonOutput), null, 2)); -// Step 7: Demonstrate loading from JSON +// Step 8: Demonstrate loading from JSON console.log('\n--- Loading vCon from JSON ---'); const loadedVcon = Vcon.buildFromJson(jsonOutput); console.log(`Loaded vCon UUID: ${loadedVcon.uuid}`); @@ -101,7 +118,8 @@ console.log(`Number of dialogs: ${loadedVcon.dialog.length}`); // Print conversation summary console.log('\n--- Conversation Summary ---'); loadedVcon.dialog.forEach((d, i) => { - const sender = loadedVcon.parties[d.originator as number]; + const senderIndex = (d.parties as number[])[0]; + const sender = loadedVcon.parties[senderIndex]; console.log(`[${i + 1}] ${sender.name}: ${d.body}`); }); diff --git a/examples/02-call-recording.ts b/examples/02-call-recording.ts index 333c2d9..7d9c7df 100644 --- a/examples/02-call-recording.ts +++ b/examples/02-call-recording.ts @@ -5,7 +5,8 @@ * with transcription and sentiment analysis. * * Key concepts covered: - * - Recording type dialogs + * - Recording type dialogs inside a Session + * - Party events (join, hold, drop) as Event Objects * - External media references with content_hash * - Adding transcription analysis * - Adding sentiment analysis @@ -13,7 +14,7 @@ * - Party validation and identifiers */ -import { Vcon, Party, Dialog, PartyHistory } from '../src'; +import { Vcon, Party, Dialog, Session, Event } from '../src'; console.log('=== Example 2: Phone Call Recording with Analysis ===\n'); @@ -71,11 +72,18 @@ console.log(` Agent primary ID: ${agentParty.getPrimaryIdentifier()}\n`); const callStart = new Date('2025-01-15T14:30:00-06:00'); const callDuration = 847; // 14 minutes 7 seconds +// The Session lists the receivers. The customer called, so parties [0, 1] makes +// the customer (the first party) the implied originator. +const session = vcon.addSession(new Session({ + start: callStart, + duration: callDuration, + parties: [0, 1] +})); + const recordingDialog = new Dialog({ type: 'recording', start: callStart.toISOString(), - parties: [0, 1], - originator: 0, // Customer initiated the call + parties: [0, 1], // Contributors: one channel per party duration: callDuration, // Contact center specific fields campaign: 'claims-inbound', @@ -89,21 +97,26 @@ recordingDialog.addExternalData( 'audio/wav', { filename: 'call-abc123.wav', - content_hash: 'sha512-Tf9OoDQfCoI_FdP08BqxLq4OXaV5zLhR-NvZ3-hMWLLN7iZA50Dh7hctp5Om55Vg5ff5vQWKEqKAQz7W-kZRCg==' + content_hash: 'sha512-Tf9OoDQfCoI_FdP08BqxLq4OXaV5zLhR-NvZ3-hMWLLN7iZA50Dh7hctp5Om55Vg5ff5vQWKEqKAQz7W-kZRCg' } ); -// Add party history to track call events -recordingDialog.party_history = [ - new PartyHistory(0, 'join', callStart).toDict(), - new PartyHistory(1, 'join', new Date(callStart.getTime() + 15000)).toDict(), // Agent joined after 15s - new PartyHistory(1, 'hold', new Date(callStart.getTime() + 300000)).toDict(), // Put on hold at 5 min - new PartyHistory(1, 'unhold', new Date(callStart.getTime() + 420000)).toDict(), // Resumed at 7 min - new PartyHistory(0, 'drop', new Date(callStart.getTime() + callDuration * 1000)).toDict(), - new PartyHistory(1, 'drop', new Date(callStart.getTime() + callDuration * 1000 + 2000)).toDict() +vcon.addDialog(recordingDialog, session); + +// Track call events with Event Objects. In core-05 these replace the Dialog +// party_history; each Event lists the Session(s) it applies to. +const at = (ms: number) => new Date(callStart.getTime() + ms); +const events = [ + new Event({ type: 'join', time: at(0), sessions: session, party: 0 }), + new Event({ type: 'join', time: at(15000), sessions: session, party: 1 }), // Agent joined after 15s + new Event({ type: 'hold', time: at(300000), sessions: session, party: 1 }), // Put on hold at 5 min + new Event({ type: 'unhold', time: at(420000), sessions: session, party: 1 }), // Resumed at 7 min + new Event({ type: 'drop', time: at(callDuration * 1000), sessions: session, party: 0 }), + new Event({ type: 'drop', time: at(callDuration * 1000 + 2000), sessions: session, party: 1 }) ]; +events.forEach(e => vcon.addEvent(e)); + -vcon.addDialog(recordingDialog); console.log('Call recording details:'); console.log(` Type: ${recordingDialog.type}`); @@ -113,7 +126,7 @@ const hashPreview = Array.isArray(recordingDialog.content_hash) ? recordingDialog.content_hash[0] : recordingDialog.content_hash; console.log(` Content hash: ${hashPreview?.substring(0, 30)}...`); -console.log(` Party events: ${recordingDialog.party_history?.length}\n`); +console.log(` Party events: ${vcon.events.length}\n`); // Step 4: Add transcription analysis vcon.addAnalysis({ @@ -201,12 +214,21 @@ console.log(`Analysis items: ${vcon.analysis.length}`); console.log(`Extensions: ${vcon.extensions?.join(', ')}`); console.log(`Tags: ${JSON.stringify(vcon.tags)}`); -// Step 9: Validate the dialog +// Step 9: Validate the dialog and the whole vCon const validation = recordingDialog.validate(); console.log(`\nDialog validation: ${validation.valid ? 'PASSED' : 'FAILED'}`); if (validation.errors.length > 0) { console.log('Errors:', validation.errors); } +const whole = vcon.isValid(); +console.log(`vCon validation: ${whole.valid ? 'PASSED' : 'FAILED'}`); +if (!whole.valid) { + console.log('Errors:', whole.errors); + process.exit(1); +} +// This example records no lawful basis; a real recorded call needs a +// purpose "lawful_basis" attachment scoped to the Session. +console.log(`Carries a lawful_basis attachment: ${vcon.hasLawfulBasis()}`); // Step 10: Output JSON (truncated for readability) const jsonOutput = JSON.parse(vcon.toJson()); @@ -217,6 +239,8 @@ console.log(JSON.stringify({ subject: jsonOutput.subject, created_at: jsonOutput.created_at, parties: `[${jsonOutput.parties.length} parties]`, + sessions: `[${jsonOutput.sessions.length} session]`, + events: `[${jsonOutput.events.length} events]`, dialog: `[${jsonOutput.dialog.length} dialog - recording type]`, analysis: `[${jsonOutput.analysis.length} analysis items]`, extensions: jsonOutput.extensions, diff --git a/examples/03-video-conference.ts b/examples/03-video-conference.ts index 46a9f1c..3782fdf 100644 --- a/examples/03-video-conference.ts +++ b/examples/03-video-conference.ts @@ -6,15 +6,15 @@ * * Key concepts covered: * - Multi-party conferences (more than 2 parties) - * - Video recording dialogs + * - Video recording dialogs inside Sessions + * - Join and drop Events * - Multiple attachments with different purposes * - Group references for related vCons * - Incomplete dialogs (failed join attempts) * - External and inline content - * - Amendment and redaction references */ -import { Vcon, Party, Dialog } from '../src'; +import { Vcon, Party, Dialog, Session, Event } from '../src'; console.log('=== Example 3: Video Conference with Attachments ===\n'); @@ -70,36 +70,46 @@ parties.forEach(p => vcon.addParty(p)); console.log(`Added ${parties.length} conference participants:`); parties.forEach((p, i) => console.log(` [${i}] ${p.name} (${p.role}) - ${p.meta?.title}`)); -// Step 3: Add an incomplete dialog for a failed join attempt +// Step 3: Add the Sessions. Session 0 is the join attempt that failed; Session 1 +// is the meeting. The first party of a Session is the implied originator. const failedJoinTime = new Date('2025-01-20T09:58:00-08:00'); -const failedJoinDialog = new Dialog({ - type: 'incomplete', - start: failedJoinTime.toISOString(), - parties: 3, // Raj tried to join (single party as integer) +const conferenceStart = new Date('2025-01-20T10:00:00-08:00'); +const conferenceDuration = 3720; // 62 minutes + +const attemptSession = vcon.addSession(new Session({ start: failedJoinTime, parties: [3] })); +const meetingSession = vcon.addSession(new Session({ + start: conferenceStart, + duration: conferenceDuration, + parties: [0, 1, 2, 3, 4], // Sarah (host) started the meeting, so she is first + session_id: { + local: '550e8400-e29b-41d4-a716-446655440000', + remote: '550e8400-e29b-41d4-a716-446655440001' + }, + // The failed attempt came before the meeting + sessions: [{ session: attemptSession, type: 'precursor', description: 'failed join attempt' }] +})); + +// An incomplete dialog for the failed join attempt. It has no content; its +// parties are the party that attempted the call. +vcon.addIncompleteDialog({ + start: failedJoinTime, disposition: 'failed', + parties: [3], // Raj tried to join meta: { error: 'network_timeout', retry_count: 2 - } + }, + session: attemptSession }); -vcon.addDialog(failedJoinDialog); console.log('\nAdded incomplete dialog (failed join attempt)'); // Step 4: Create the main video conference recording -const conferenceStart = new Date('2025-01-20T10:00:00-08:00'); -const conferenceDuration = 3720; // 62 minutes - const videoDialog = new Dialog({ type: 'recording', start: conferenceStart.toISOString(), - parties: [0, 1, 2, 3, 4], // All participants - originator: 0, // Sarah (host) started the meeting + parties: [0, 1, 2, 3, 4], // All participants contribute duration: conferenceDuration, - application: 'zoom', - session_id: { - local: '550e8400-e29b-41d4-a716-446655440000', - remote: '550e8400-e29b-41d4-a716-446655440001' - } + application: 'zoom' }); // Add external video reference @@ -108,33 +118,35 @@ videoDialog.addExternalData( 'video/mp4', { filename: 'q1-roadmap-review-2025-01-20.mp4', - content_hash: 'sha512-fYZelZskZpGMmGOvypQtD7idfJrAyZuvw3SVBN7Zdzm6Q5K76j6r10R6V9NAjEXVrUd9TdL5KbbX-8wOWflvgQ==' + content_hash: 'sha512-fYZelZskZpGMmGOvypQtD7idfJrAyZuvw3SVBN7Zdzm6Q5K76j6r10R6V9NAjEXVrUd9TdL5KbbX-8wOWflvgQ' } ); +vcon.addDialog(videoDialog, meetingSession); + +// Track when participants joined/left with Events (join, drop, hold, unhold, +// mute, unmute, keydown, keyup). Each Event lists the Session(s) it applies to. +const at = (ms: number) => new Date(conferenceStart.getTime() + ms); +const endMs = conferenceDuration * 1000; +[ + { party: 0, type: 'join', ms: 0 }, + { party: 1, type: 'join', ms: 30000 }, + { party: 2, type: 'join', ms: 45000 }, + { party: 4, type: 'join', ms: 60000 }, + { party: 3, type: 'join', ms: 180000 }, // Raj joined late after retry + { party: 2, type: 'drop', ms: 3000000 }, // Emma left at 50min + { party: 0, type: 'drop', ms: endMs }, + { party: 1, type: 'drop', ms: endMs }, + { party: 3, type: 'drop', ms: endMs }, + { party: 4, type: 'drop', ms: endMs } +].forEach(e => vcon.addEvent(new Event({ type: e.type, time: at(e.ms), sessions: meetingSession, party: e.party }))); -// Track when participants joined/left (spec events: join, drop, hold, unhold, mute, unmute, keydown, keyup) -videoDialog.party_history = [ - { party: 0, event: 'join', time: conferenceStart.toISOString() }, - { party: 1, event: 'join', time: new Date(conferenceStart.getTime() + 30000).toISOString() }, - { party: 2, event: 'join', time: new Date(conferenceStart.getTime() + 45000).toISOString() }, - { party: 3, event: 'join', time: new Date(conferenceStart.getTime() + 180000).toISOString() }, // Raj joined late after retry - { party: 4, event: 'join', time: new Date(conferenceStart.getTime() + 60000).toISOString() }, - { party: 2, event: 'drop', time: new Date(conferenceStart.getTime() + 3000000).toISOString() }, // Emma left at 50min - { party: 0, event: 'drop', time: new Date(conferenceStart.getTime() + conferenceDuration * 1000).toISOString() }, - { party: 1, event: 'drop', time: new Date(conferenceStart.getTime() + conferenceDuration * 1000).toISOString() }, - { party: 3, event: 'drop', time: new Date(conferenceStart.getTime() + conferenceDuration * 1000).toISOString() }, - { party: 4, event: 'drop', time: new Date(conferenceStart.getTime() + conferenceDuration * 1000).toISOString() } -]; - -vcon.addDialog(videoDialog); console.log(`Added video recording dialog (${Math.floor(conferenceDuration / 60)} minutes)`); // Step 5: Add a screen sharing segment as a separate dialog const screenShareDialog = new Dialog({ type: 'recording', start: new Date(conferenceStart.getTime() + 600000).toISOString(), // 10 min into meeting - parties: [0, 1, 2, 3, 4], - originator: 0, // Sarah shared her screen + parties: [0], // Sarah shared her screen duration: 1200, // 20 minutes of screen share mediatype: 'video/webm', meta: { content_type: 'screen_share' } @@ -145,11 +157,11 @@ screenShareDialog.addExternalData( 'video/webm', { filename: 'roadmap-screenshare.webm', - content_hash: 'sha512-Y3jOu_FlOcL2Q1F6Z_2cTtkqVuKHQ4-OJQ4Bk7CkqOR-eAYAZuTu_zPMRTRddqZcvVAJI9LSrtDHHzwgmZ5dGw==' + content_hash: 'sha512-Y3jOu_FlOcL2Q1F6Z_2cTtkqVuKHQ4-OJQ4Bk7CkqOR-eAYAZuTu_zPMRTRddqZcvVAJI9LSrtDHHzwgmZ5dGw' } ); -vcon.addDialog(screenShareDialog); +vcon.addDialog(screenShareDialog, meetingSession); console.log('Added screen share recording dialog'); // Step 6: Add attachments @@ -162,7 +174,7 @@ vcon.addAttachment({ body: 'UEsDBBQAAAAIAGiC...', // Truncated base64url content encoding: 'base64url', party: 0, // Shared by Sarah - dialog: 1, // Main recording dialog + dialog: 1, // Main recording dialog (the Dialog index; never widened to a Session) start: new Date(conferenceStart.getTime() + 300000).toISOString() }); console.log('\nAdded presentation attachment'); @@ -171,7 +183,7 @@ console.log('\nAdded presentation attachment'); vcon.addAttachment({ purpose: 'meeting-notes', url: 'https://docs.company.com/meetings/2025-01-20-roadmap-notes.md', - content_hash: 'sha512-AfymyPwHQiWXh1khT2xSPHFOnImhfa4VnY8FmZjE0i1ZECN56dGOuPC4yKB8WIbCYWLrcwoeMm8gJBYNkPbjbA==', + content_hash: 'sha512-AfymyPwHQiWXh1khT2xSPHFOnImhfa4VnY8FmZjE0i1ZECN56dGOuPC4yKB8WIbCYWLrcwoeMm8gJBYNkPbjbA', mediatype: 'text/markdown', filename: 'meeting-notes.md', party: 1, // Mike took notes @@ -183,19 +195,21 @@ console.log('Added meeting notes attachment (external)'); vcon.addAttachment({ purpose: 'action-items', url: 'https://docs.company.com/meetings/2025-01-20-action-items.xlsx', - content_hash: 'sha512-VgnVqYWAYAFRdmHN_HJN9bN-2_BS-aWVPiOZsfm0PLmLU0V0EGTYjJK0PR0ZJ7iZK_QqYJyT-NPlYI4yxF1Wjg==', + content_hash: 'sha512-VgnVqYWAYAFRdmHN_HJN9bN-2_BS-aWVPiOZsfm0PLmLU0V0EGTYjJK0PR0ZJ7iZK_QqYJyT-NPlYI4yxF1Wjg', mediatype: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', filename: 'action-items.xlsx', party: 0, - dialog: [1, 2] // Related to main recording and screen share + session: meetingSession // Related to the whole meeting }); console.log('Added action items spreadsheet'); -// Chat transcript (vCon-level attachment — party/dialog default to 0) +// Chat transcript, scoped to the meeting Session vcon.addAttachment({ purpose: 'chat-transcript', mediatype: 'text/plain', filename: 'meeting-chat.txt', + party: 1, + session: meetingSession, body: `[10:02] Mike Johnson: Good morning everyone! [10:02] Emma Wilson: Morning from London! [10:03] Lisa Kim: Hello from Seoul - it's late here but excited to discuss the roadmap @@ -217,7 +231,7 @@ vcon.addAnalysis({ vendor: 'assembly-ai', product: 'universal-2', url: 'https://storage.company.com/transcripts/2025-01-20-roadmap.json', - content_hash: 'sha512-VgnVqYWAYAFRdmHN_HJN9bN-2_BS-aWVPiOZsfm0PLmLU0V0EGTYjJK0PR0ZJ7iZK_QqYJyT-NPlYI4yxF1Wjg==', + content_hash: 'sha512-VgnVqYWAYAFRdmHN_HJN9bN-2_BS-aWVPiOZsfm0PLmLU0V0EGTYjJK0PR0ZJ7iZK_QqYJyT-NPlYI4yxF1Wjg', mediatype: 'application/json' }); @@ -299,16 +313,23 @@ vcon.analysis.forEach((a, i) => { console.log('\nExtensions:', vcon.extensions); console.log('Tags:', vcon.tags); -// Step 10: Validate dialogs +// Step 10: Validate dialogs, then the whole vCon against core-05 console.log('\n--- Validation ---'); vcon.dialog.forEach((d, i) => { - const dialogObj = new Dialog(d as any); + const dialogObj = Dialog.fromDict(d); const result = dialogObj.validate(); console.log(`Dialog ${i}: ${result.valid ? 'VALID' : 'INVALID'}`); if (result.errors.length > 0) { result.errors.forEach(e => console.log(` - ${e}`)); } }); +const whole = vcon.isValid(); +console.log(`vCon: ${whole.valid ? 'VALID' : 'INVALID'}`); +whole.errors.forEach(e => console.log(` - ${e}`)); +if (!whole.valid) process.exit(1); +// This example records no lawful basis; a real meeting recording needs a +// purpose "lawful_basis" attachment scoped to the Session. +console.log(`Carries a lawful_basis attachment: ${vcon.hasLawfulBasis()}`); // Step 11: Show JSON structure console.log('\n--- vCon JSON Structure ---'); @@ -319,6 +340,8 @@ console.log(`{ subject: "${json.subject}", created_at: "${json.created_at}", parties: [${json.parties.length} parties], + sessions: [${json.sessions.length} sessions], + events: [${json.events.length} events], dialog: [${json.dialog.length} dialogs], attachments: [${json.attachments.length} attachments], analysis: [${json.analysis.length} analysis items], diff --git a/examples/audio-video.ts b/examples/audio-video.ts index 67fbb69..c0adad3 100644 --- a/examples/audio-video.ts +++ b/examples/audio-video.ts @@ -1,4 +1,4 @@ -import { Vcon, Party, Dialog } from '../src'; +import { Vcon, Party, Dialog, Session } from '../src'; // Create a new vCon const vcon = Vcon.buildNew(); @@ -19,62 +19,62 @@ const agent = new Party({ vcon.addParty(caller); vcon.addParty(agent); -// Add a text dialog (initial request) +// Core-05 groups Dialogs in a Session: the receivers are the Session parties +const session = vcon.addSession(new Session({ start: new Date(), parties: [0, 1] })); + +// Add a text dialog (initial request). The sender is the Dialog party. const textDialog = new Dialog({ - type: 'text/plain', + type: 'text', start: new Date(), - parties: [0, 1], - originator: 0, + parties: [0], body: 'I need to schedule a video call for technical support.', - mimetype: 'text/plain' + mediatype: 'text/plain', + encoding: 'none' }); -vcon.addDialog(textDialog); +vcon.addDialog(textDialog, session); -// Add an audio dialog (phone call) +// Add an audio recording (phone call). Core-05 has one 'recording' type for +// audio and video; the media type says which. const audioDialog = new Dialog({ - type: 'audio/wav', + type: 'recording', start: new Date(Date.now() + 1000), // 1 second later parties: [0, 1], - originator: 0, - mimetype: 'audio/wav', - filename: 'call-recording.wav', duration: 300 // 5 minutes }); -// Add external audio data +// Add external audio data (url, media type, then options) audioDialog.addExternalData( 'https://example.com/recordings/call-recording.wav', - 'call-recording.wav', - 'audio/wav' + 'audio/wav', + { + filename: 'call-recording.wav', + content_hash: 'sha512-Tf9OoDQfCoI_FdP08BqxLq4OXaV5zLhR-NvZ3-hMWLLN7iZA50Dh7hctp5Om55Vg5ff5vQWKEqKAQz7W-kZRCg' + } ); -vcon.addDialog(audioDialog); +vcon.addDialog(audioDialog, session); -// Add a video dialog (screen sharing) +// Add a video recording (screen sharing) const videoDialog = new Dialog({ - type: 'video/mp4', + type: 'recording', start: new Date(Date.now() + 310000), // 5 minutes and 10 seconds later - parties: [0, 1], - originator: 1, - mimetype: 'video/mp4', - filename: 'screen-sharing.mp4', + parties: [1], // Jane shares her screen duration: 600 // 10 minutes }); -// Add inline video data (base64 encoded) -videoDialog.addInlineData( - 'base64EncodedVideoContent', - 'screen-sharing.mp4', - 'video/mp4' -); +// Add inline video data (base64url encoded) +videoDialog.addInlineData('base64urlEncodedVideoContent', 'video/mp4', { + encoding: 'base64url', + filename: 'screen-sharing.mp4' +}); -vcon.addDialog(videoDialog); +vcon.addDialog(videoDialog, session); // Add analysis for audio sentiment vcon.addAnalysis({ type: 'sentiment', - dialog: 1, // Analyze the audio dialog + dialog: 1, // Analyze the audio dialog (index 1) vendor: 'sentiment-analyzer', body: { score: 0.7, @@ -112,6 +112,11 @@ console.log('Video dialog:', videoDialog.isVideo()); // true console.log('Audio is external:', audioDialog.isExternalData()); // true console.log('Video is inline:', videoDialog.isInlineData()); // true +// Validate against core-05 +console.log('Valid:', vcon.isValid()); +// No lawful basis is recorded here; add a purpose "lawful_basis" attachment for real use. +console.log('Has lawful basis:', vcon.hasLawfulBasis()); + // Convert to JSON const json = vcon.toJson(); console.log('vCon JSON length:', json.length); diff --git a/examples/inline-recording.ts b/examples/inline-recording.ts index 9ad7997..1bddf8b 100644 --- a/examples/inline-recording.ts +++ b/examples/inline-recording.ts @@ -1,4 +1,4 @@ -import { Vcon, Party, Dialog } from '../src'; +import { Vcon, Party, Dialog, Session } from '../src'; import * as fs from 'fs'; import * as path from 'path'; import * as dotenv from 'dotenv'; @@ -88,12 +88,15 @@ if (fileExtension === '.mp3') { mimeType = 'audio/aac'; } +// Core-05: Dialogs hang off a Session whose parties are the receivers +const session = vcon.addSession(new Session({ start: new Date(), parties: [1, 0] })); // Agent (1) is the originator + // Add an audio dialog with inline recording const audioDialog = new Dialog({ type: 'recording', start: new Date(), - parties: [1, 0], // Agent (1) and Customer (0) - mimetype: mimeType, + parties: [1, 0], // Agent (1) and Customer (0) contribute + mediatype: mimeType, filename: fileName, duration: 0, // Will be updated if available from Deepgram meta: { @@ -105,18 +108,14 @@ const audioDialog = new Dialog({ } }); -// Read the audio file and convert it to base64 +// Read the audio file and convert it to base64url (base64 is not a valid encoding) const audioFileBuffer = fs.readFileSync(inputWavFile); -const base64AudioContent = audioFileBuffer.toString('base64'); +const base64AudioContent = audioFileBuffer.toString('base64url'); -// Add inline audio data (base64 encoded) -audioDialog.addInlineData( - base64AudioContent, - fileName, - mimeType -); +// Add inline audio data (base64url encoded) +audioDialog.addInlineData(base64AudioContent, mimeType, { encoding: 'base64url', filename: fileName }); -vcon.addDialog(audioDialog); +vcon.addDialog(audioDialog, session); // Function to transcribe audio using Deepgram async function transcribeAudio(audioBuffer: Buffer): Promise { @@ -221,6 +220,11 @@ async function processAudioFile() { encoding: 'none' }); + // Validate against core-05. This example records no lawful basis; add a + // purpose "lawful_basis" attachment before using it for real recordings. + console.log('Valid:', vcon.isValid()); + console.log('Has lawful basis:', vcon.hasLawfulBasis()); + // Convert to JSON const json = vcon.toJson(); console.log('vCon JSON length:', json.length); diff --git a/examples/simple.ts b/examples/simple.ts index 4261705..854961a 100644 --- a/examples/simple.ts +++ b/examples/simple.ts @@ -1,4 +1,4 @@ -import { Vcon, Party, Dialog } from '../src'; +import { Vcon, Party, Dialog, Session } from '../src'; // Create a new vCon const vcon = Vcon.buildNew(); @@ -19,36 +19,41 @@ const party2 = new Party({ vcon.addParty(party1); vcon.addParty(party2); -// Add a text dialog +// Add a Session. Core-05 needs one when there is dialog; its parties are the +// receivers and the first party is the implied originator. +const session = vcon.addSession(new Session({ start: new Date(), parties: [0, 1] })); + +// Add a text dialog. A text Dialog's parties are the sender only. const textDialog = new Dialog({ - type: 'text/plain', + type: 'text', start: new Date(), - parties: [0, 1], // References to party indices - originator: 0, + parties: [0], // John sends body: 'Hello, I need help with my account.', - mimetype: 'text/plain' + mediatype: 'text/plain', + encoding: 'none' }); -vcon.addDialog(textDialog); +vcon.addDialog(textDialog, session); // Add a response dialog const responseDialog = new Dialog({ - type: 'text/plain', + type: 'text', start: new Date(Date.now() + 1000), // 1 second later - parties: [0, 1], - originator: 1, + parties: [1], // Jane sends body: 'Hello John, how can I assist you today?', - mimetype: 'text/plain' + mediatype: 'text/plain', + encoding: 'none' }); -vcon.addDialog(responseDialog); +vcon.addDialog(responseDialog, session); -// Add an attachment -vcon.addAttachment( - 'application/pdf', - 'base64EncodedContent', - 'base64' -); +// Add an attachment. With exactly one Session it is scoped to that Session. +vcon.addAttachment({ + purpose: 'document', + mediatype: 'application/pdf', + body: 'base64urlEncodedContent', + encoding: 'base64url' +}); // Add analysis vcon.addAnalysis({ @@ -65,6 +70,11 @@ vcon.addAnalysis({ vcon.addTag('category', 'support'); vcon.addTag('priority', 'medium'); +// Validate against core-05 +console.log('Valid:', vcon.isValid()); +// No lawful basis is recorded here; add a purpose "lawful_basis" attachment for real use. +console.log('Has lawful basis:', vcon.hasLawfulBasis()); + // Convert to JSON const json = vcon.toJson(); console.log('vCon JSON:', json); diff --git a/package-lock.json b/package-lock.json index b17b11d..3369cb5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "vcon-js", - "version": "0.5.2", + "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "vcon-js", - "version": "0.5.2", + "version": "1.0.0", "license": "MIT", "dependencies": { "uuid": "^11.1.1" diff --git a/package.json b/package.json index 2a6d256..7c3a6d0 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "vcon-js", - "version": "0.5.2", - "description": "JavaScript library for creating and managing vCons (Virtual Conversations)", + "version": "1.0.0", + "description": "JavaScript library for creating and managing vCons (Virtual Conversations), core-05 (syntax 0.5.0)", "main": "dist/index.js", "types": "dist/index.d.ts", "files": [ From 0b11ca7151e9abb8ad61d8aee8a5106ed8c8da0a Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Sun, 1 Nov 2026 13:50:53 -0500 Subject: [PATCH 5/6] Match the reference migration on date-time precision and range A differential run against the Python reference found that the port truncated timestamps to milliseconds (wrong Session duration and, for starts under a millisecond apart, the wrong earliest start), rounded durations half up instead of half to even, formatted a derived consultation-end Event time differently, and accepted out-of-range date-times such as February 30 and hour 24 by rolling them over. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++ src/__tests__/migration.test.ts | 57 ++++++++++++++++++++++++ src/__tests__/validation.test.ts | 15 +++++++ src/migration.ts | 75 +++++++++++++++++++++++++++----- src/util.ts | 52 +++++++++++++++++----- 5 files changed, 182 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d8aa518..9fa2f71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -88,6 +88,10 @@ Objects. Readers accept `0.4.0` and `0.5.0`; writers emit `0.5.0`. - `Dialog.validate()` rejects unknown Dialog types, content on an `incomplete` Dialog and media types outside the known set (text, message and multipart subtypes are accepted). - The vendored test schema is now the core-05 Appendix C schema (was the `0.4.0` schema). +- Date-time parsing rejects out-of-range fields (February 30, hour 24, offset of 24 hours) + instead of rolling them over, and keeps microseconds. `migrate040To050` derives Session start + and duration, and a consultation-end Event time, with microsecond precision and the reference's + rounding and formatting, so both libraries produce the same document from the same input. ### Removed - `Dialog.isRecordingSet()`, the `recording-set` and `transfer` Dialog types and their diff --git a/src/__tests__/migration.test.ts b/src/__tests__/migration.test.ts index 58e1179..5f7d014 100644 --- a/src/__tests__/migration.test.ts +++ b/src/__tests__/migration.test.ts @@ -992,3 +992,60 @@ describe('signed 0.4.0 input is not migrated on load', () => { expect(v.vcon).toBe('0.5.0'); }); }); + +/** + * Regressions found by diffing this port against the Python reference + * (every 0.4.0 input from the reference tests plus adversarial ones). + */ +describe('parity with the reference implementation', () => { + it('derives Session duration with microsecond precision', () => { + const { vcon } = migrate040To050(v04({ + dialog: [ + rec({ start: '2022-01-01T00:00:00.123456Z', duration: 10 }), + rec({ start: '2022-01-01T00:00:00.5Z', duration: 10 }) + ] + })); + expect(vcon.sessions[0].duration).toBe(10.376544); + }); + + it('picks the earliest start when two starts differ by less than a millisecond', () => { + const { vcon } = migrate040To050(v04({ + dialog: [ + rec({ start: '2022-01-01T00:00:00.0009Z', duration: 1 }), + rec({ start: '2022-01-01T00:00:00.0001Z', duration: undefined }) + ] + })); + expect(vcon.sessions[0].start).toBe('2022-01-01T00:00:00.0001Z'); + expect(vcon.sessions[0].duration).toBe(1.0008); + }); + + it('rounds durations to six decimals half to even, as round(x, 6) does', () => { + const { vcon } = migrate040To050(v04({ dialog: [rec({ start: '2022-01-01T00:00:00Z', duration: 0.0078125 })] })); + expect(vcon.sessions[0].duration).toBe(0.007812); + }); + + it('formats a derived consultation-end Event time like the reference', () => { + const transfer = { type: 'transfer', transferee: 0, transferor: 1, transfer_target: 2, original: 0, consultation: 1 }; + const half = migrate040To050(v04({ + dialog: [rec(), rec({ start: '2022-01-01T00:01:00Z', duration: 30.5, parties: [1, 2] }), transfer] + })).vcon; + expect(half.events.find((e: D) => e.type === 'consultative-transfer').time).toBe('2022-01-01T00:01:30.500000+00:00'); + const whole = migrate040To050(v04({ + dialog: [rec(), rec({ start: '2022-01-01T00:01:00Z', duration: 60, parties: [1, 2] }), transfer] + })).vcon; + expect(whole.events.find((e: D) => e.type === 'consultative-transfer').time).toBe('2022-01-01T00:02:00+00:00'); + const micro = migrate040To050(v04({ + dialog: [rec(), rec({ start: '2022-01-01T00:01:00.123456+00:00', duration: 0.0000015, parties: [1, 2] }), transfer] + })).vcon; + expect(micro.events.find((e: D) => e.type === 'consultative-transfer').time).toBe('2022-01-01T00:01:00.123457+00:00'); + }); + + it.each(['2022-02-30T00:00:00Z', '2022-01-01T24:00:00Z', '2022-13-01T00:00:00Z', '2022-01-01T00:00:00+24:00'])( + 'does not treat the out-of-range date-time %s as a start', + start => { + const { vcon, report } = migrate040To050(v04({ dialog: [rec({ start })] })); + expect(vcon.sessions[0].start).toBeUndefined(); + expect(report.unresolved.some(e => e.step === 'post')).toBe(true); + } + ); +}); diff --git a/src/__tests__/validation.test.ts b/src/__tests__/validation.test.ts index a4f78e5..5307eb5 100644 --- a/src/__tests__/validation.test.ts +++ b/src/__tests__/validation.test.ts @@ -82,3 +82,18 @@ describe('Vcon guards', () => { expect(() => { v.amended_from = { uuid: '550e8400-e29b-41d4-a716-446655440000' }; }).toThrow(/mutually exclusive/); }); }); + +describe('parseDateTime', () => { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const { parseDateTime, parseDateTimeMicros } = require('../util'); + it('rejects out-of-range fields instead of rolling them over', () => { + for (const v of ['2022-02-30T00:00:00Z', '2021-02-29T00:00:00Z', '2022-01-01T24:00:00Z', '2022-01-01T00:60:00Z', '2022-01-01T00:00:00+24:00']) { + expect(parseDateTime(v)).toBeUndefined(); + } + expect(parseDateTime('2024-02-29T00:00:00Z')).toBe(Date.parse('2024-02-29T00:00:00Z')); + }); + it('keeps microseconds and applies offsets', () => { + expect(parseDateTimeMicros('2022-01-01T05:00:00.1234567+05:00')).toBe(Date.parse('2022-01-01T00:00:00Z') * 1000 + 123456); + expect(parseDateTimeMicros('2022-01-01T00:00:00')).toBe(Date.parse('2022-01-01T00:00:00Z') * 1000); + }); +}); diff --git a/src/migration.ts b/src/migration.ts index 44a7a60..3308046 100644 --- a/src/migration.ts +++ b/src/migration.ts @@ -28,7 +28,16 @@ */ import { EVENT_PARAMETERS } from './event'; import { DIALOG_MIME_TYPES, extensionsInUse, validateVconDict } from './validation'; -import { base64UrlDecodeToString, clone, isInt, isPlainObject, parseDateTime, repr, reprList } from './util'; +import { + base64UrlDecodeToString, + clone, + isInt, + isPlainObject, + parseDateTime, + parseDateTimeMicros, + repr, + reprList +} from './util'; export const SOURCE_VERSION = '0.4.0'; export const TARGET_VERSION = '0.5.0'; @@ -154,8 +163,54 @@ export interface MigrationResult { const ok = (v: unknown): boolean => parseDateTime(v) !== undefined; const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v); -function num(seconds: number): number { - return Math.round(seconds * 1e6) / 1e6; +/** + * Round seconds to six decimals the way the Python reference's round(x, 6) + * does: on the exact binary value, ties to even. Math.round(x * 1e6) / 1e6 + * rounds x * 1e6 (already inexact) and breaks ties upwards, so it disagrees + * with the reference on values such as 0.0078125. + */ +export function num(seconds: number): number { + if (!Number.isFinite(seconds)) return seconds; + const sign = seconds < 0 ? -1 : 1; + const [ip, fp] = Math.abs(seconds).toFixed(100).split('.'); + const keep = fp.slice(0, 6); + const rest = fp.slice(6); + const up = rest[0] > '5' || (rest[0] === '5' && (/[1-9]/.test(rest.slice(1)) || Number(keep[5]) % 2 === 1)); + const digits = (BigInt(ip + keep) + (up ? 1n : 0n)).toString().padStart(7, '0'); + const value = Number(`${digits.slice(0, -6)}.${digits.slice(-6)}`); + return value === 0 ? 0 : sign * value; +} + +/** Epoch seconds (with microseconds) of a date-time string, as Python's datetime.timestamp() gives. */ +const seconds = (v: unknown): number | undefined => { + const us = parseDateTimeMicros(v); + return us === undefined ? undefined : us / 1e6; +}; + +/** Round half to even to an integer (Python's rounding of a float to microseconds). */ +function roundHalfEven(x: number): number { + const r = Math.round(x); + return Math.abs(x % 1) === 0.5 && r % 2 !== 0 ? r - 1 : r; +} + +/** + * The string Python's datetime.fromtimestamp(t, tz=timezone.utc).isoformat() + * gives for epoch seconds t: microsecond precision (rounded half to even), + * the fraction omitted when it is zero, and "+00:00" as the offset. Matching + * it keeps a derived Event time identical across implementations. + */ +export function isoFromSeconds(t: number): string { + let whole = Math.trunc(t); + let us = roundHalfEven((t - whole) * 1e6); + if (us >= 1e6) { + whole += 1; + us -= 1e6; + } else if (us < 0) { + whole -= 1; + us += 1e6; + } + const base = new Date(whole * 1000).toISOString().slice(0, 19); + return base + (us ? '.' + String(us).padStart(6, '0') : '') + '+00:00'; } /** Flat list of int party indices of a 0.4.0 Dialog `parties` value. */ @@ -279,7 +334,7 @@ class Context { .map((r: number) => this.dialogs[r].start) .filter(ok); if (starts.length) { - return starts.reduce((a: string, b: string) => (parseDateTime(b)! < parseDateTime(a)! ? b : a)); + return starts.reduce((a: string, b: string) => (seconds(b)! < seconds(a)! ? b : a)); } } return undefined; @@ -296,7 +351,7 @@ class Context { const items: Array<[number, number]> = []; for (const i of idxs) { if (!isPlainObject(this.dialogs[i])) continue; - const s = parseDateTime(this.dialogs[i].start); + const s = seconds(this.dialogs[i].start); if (s !== undefined) items.push([i, s]); } if (!items.length) return [undefined, undefined]; @@ -308,13 +363,13 @@ class Context { const dur = this.dialogs[i].duration; if (isNum(dur)) { anyDuration = true; - ends.push(s / 1000 + dur); + ends.push(s + dur); } else { - ends.push(s / 1000); + ends.push(s); } } if (!anyDuration) return [startStr, undefined]; - return [startStr, num(Math.max(...ends) - first / 1000)]; + return [startStr, num(Math.max(...ends) - first)]; } /** Build a Session for a group of kept Dialogs from derived values. */ @@ -655,10 +710,10 @@ function stepT4Transfers(ctx: Context): void { cands.push([ctx.dialogStart(targetRef), `start of target dialog[${targetRef}]`]); if (hasCons) { const cd = isInt(consRef) && consRef >= 0 && consRef < ctx.dialogs.length ? ctx.dialogs[consRef] : undefined; - const cs = parseDateTime(ctx.dialogStart(consRef)); + const cs = seconds(ctx.dialogStart(consRef)); const dur = isPlainObject(cd) ? cd.duration : undefined; if (cs !== undefined && isNum(dur)) { - const end = new Date(cs + dur * 1000).toISOString(); + const end = isoFromSeconds(cs + dur); cands.push([end, `end of consultation dialog[${consRef}] (start + duration)`]); } cands.push([ctx.dialogStart(consRef), `start of consultation dialog[${consRef}]`]); diff --git a/src/util.ts b/src/util.ts index 2d41cfb..985d8f7 100644 --- a/src/util.ts +++ b/src/util.ts @@ -25,23 +25,53 @@ export function asList(value: T | T[] | null | undefined): T[] { const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?\s*(Z|z|[+-]\d{2}(?::?\d{2})?)?)?$/; +const DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; + +function isLeapYear(y: number): boolean { + return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0; +} + /** - * Parse an ISO 8601 / RFC 3339 date-time string to epoch milliseconds, or - * undefined if it is not one. A date-time with no offset is read as UTC, as the - * Python reference does, so results do not depend on the machine's time zone. + * Parse an ISO 8601 / RFC 3339 date-time string to integer epoch microseconds, + * or undefined if it is not one. A date-time with no offset is read as UTC, as + * the Python reference does, so results do not depend on the machine's time + * zone. Out-of-range fields (month 13, February 30, hour 24, second 60, an + * offset of 24 hours or more) are rejected rather than rolled over. Fractional + * seconds keep microsecond precision (digits past the sixth are dropped), so + * timestamps written by microsecond-precision writers compare and subtract + * exactly. */ -export function parseDateTime(value: unknown): number | undefined { +export function parseDateTimeMicros(value: unknown): number | undefined { if (typeof value !== 'string') return undefined; const m = DATE_RE.exec(value.trim()); if (!m) return undefined; - const [, y, mo, d, h = '00', mi = '00', s = '00', frac = '', tz = 'Z'] = m; - let offset = tz.toUpperCase(); - if (offset !== 'Z') { - const digits = offset.slice(1).replace(':', ''); - offset = offset[0] + digits.slice(0, 2) + ':' + (digits.slice(2) || '00'); + const [, ys, mos, ds, hs = '00', mis = '00', ss = '00', frac = '', tz = 'Z'] = m; + const [y, mo, d, h, mi, s] = [ys, mos, ds, hs, mis, ss].map(Number); + if (y < 1 || mo < 1 || mo > 12 || d < 1) return undefined; + const dim = mo === 2 && isLeapYear(y) ? 29 : DAYS_IN_MONTH[mo - 1]; + if (d > dim || h > 23 || mi > 59 || s > 59) return undefined; + let offsetMinutes = 0; + const t = tz.toUpperCase(); + if (t !== 'Z') { + const digits = t.slice(1).replace(':', ''); + const oh = Number(digits.slice(0, 2)); + const om = Number(digits.slice(2) || '0'); + if (oh > 23 || om > 59) return undefined; + offsetMinutes = (t[0] === '-' ? -1 : 1) * (oh * 60 + om); } - const ms = Date.parse(`${y}-${mo}-${d}T${h}:${mi}:${s}${frac}${offset}`); - return Number.isNaN(ms) ? undefined : ms; + const date = new Date(Date.UTC(2000, mo - 1, d, h, mi, s)); + date.setUTCFullYear(y); + const micros = frac ? Number(frac.slice(1, 7).padEnd(6, '0')) : 0; + return date.getTime() * 1000 + micros - offsetMinutes * 60_000_000; +} + +/** + * Parse an ISO 8601 / RFC 3339 date-time string to epoch milliseconds, or + * undefined if it is not one. See parseDateTimeMicros for the rules. + */ +export function parseDateTime(value: unknown): number | undefined { + const us = parseDateTimeMicros(value); + return us === undefined ? undefined : Math.floor(us / 1000); } /** Convert a Date to an ISO string; pass other values through. */ From 7f8517a3372bdf2af88d05a56bc802f1b2a630ff Mon Sep 17 00:00:00 2001 From: Thomas Howe Date: Wed, 18 Nov 2026 18:53:12 -0500 Subject: [PATCH 6/6] Report a non-RFC 3339 dialog start in T1, matching the Python reference --- src/__tests__/migration-dialog-dates.test.ts | 27 ++++++++++++++++++++ src/migration.ts | 14 ++++++++++ 2 files changed, 41 insertions(+) create mode 100644 src/__tests__/migration-dialog-dates.test.ts diff --git a/src/__tests__/migration-dialog-dates.test.ts b/src/__tests__/migration-dialog-dates.test.ts new file mode 100644 index 0000000..e9f72bd --- /dev/null +++ b/src/__tests__/migration-dialog-dates.test.ts @@ -0,0 +1,27 @@ +import { migrate040To050, MigrationError } from '../index'; + +const legacy = (start: unknown) => ({ + vcon: '0.4.0', + uuid: '01928e10-193e-8231-b9a2-279e0d16bc46', + created_at: '2024-01-01T00:00:00Z', + parties: [{ tel: '+15551230001' }], + dialog: [{ type: 'text', start, parties: [0], body: 'hi', encoding: 'none', mediatype: 'text/plain' }] +}); + +describe('T1 dialog start check', () => { + it('reports a non-RFC 3339 dialog start as unresolved, like the Python reference', () => { + const { report } = migrate040To050(legacy('{{now}}')); + const t1 = report.unresolved.filter(e => e.step === 'T1'); + expect(t1).toHaveLength(1); + expect(t1[0].message).toBe("dialog[0] start '{{now}}' is not an RFC 3339 date-time; not used to derive a Session start."); + }); + + it('throws in strict mode', () => { + expect(() => migrate040To050(legacy('{{now}}'), { strict: true })).toThrow(MigrationError); + }); + + it('says nothing for a valid start', () => { + const { report } = migrate040To050(legacy('2024-01-01T00:00:00Z')); + expect(report.unresolved.filter(e => e.step === 'T1')).toHaveLength(0); + }); +}); diff --git a/src/migration.ts b/src/migration.ts index 3308046..4134def 100644 --- a/src/migration.ts +++ b/src/migration.ts @@ -415,7 +415,21 @@ class Context { // --------------------------------------------------------------------------- /** T1: `vcon` "0.4.0" -> "0.5.0". */ +/** + * core-05 Date is RFC 3339: a Dialog start that is not one is never used as a + * Session start. Strict mode throws; otherwise the value is reported as unresolved. + */ +function checkDialogDates(ctx: Context): void { + ctx.dialogs.forEach((d, i) => { + if (!isPlainObject(d) || d.start === undefined || d.start === null || parseDateTime(d.start) !== undefined) return; + const msg = `dialog[${i}] start ${repr(d.start)} is not an RFC 3339 date-time`; + if (ctx.strict) throw new MigrationError(`T1: ${msg} (strict mode)`); + ctx.report.add('T1', UNRESOLVED, `${msg}; not used to derive a Session start.`, undefined, { dialog: i, start: d.start }); + }); +} + function stepT1Version(ctx: Context): void { + checkDialogDates(ctx); if (!('vcon' in ctx.out)) { ctx.report.add('T1', INFERRED, "Input had no 'vcon' parameter; set to '0.5.0' (AMB-12: writers emit it).", 'AMB-12'); }