@hyperfrontend/network-protocol/browser/data

data

Browser-side data payload factory and encrypt/decrypt helpers built on the Web Crypto API.

Overview

A Data<T> is the structured envelope that wraps every application message inside a packet (pid, id, sequence, key, message, schema, schemaHash). This entry point binds the runtime-agnostic lib/data factory to @hyperfrontend/cryptography/browser, so createData hashes via Web Crypto and encryptData / decryptData use AES-GCM via crypto.subtle.

Usage

import { createData, encryptData, decryptData } from '@hyperfrontend/network-protocol/browser/data'

const data = createData({ type: 'greeting', content: 'hello' })

const encrypted = await encryptData(data, password)
const restored = await decryptData(encrypted, password)

Notes

  • createData derives a stable schemaHash from the inferred JSON schema so receivers can detect message-shape changes.
  • Serialization helpers (serializeData, deserializeData, asJSONString, parseJSONString, isJSONString) are re-exported for callers that need to manipulate the payload outside the queue pipeline.
  • Validation helpers (isValidId, isValidPid, isValidSequence, isValidMessage, isValidSchema, isValidSchemaHash, isValidUnencryptedData, isValidUnserializedData, isValidSerializedData) are exposed for upstream guards.
  • The Node counterpart lives at /node/data and uses Node's crypto module instead.

API Reference

ƒ Functions

§function

asJSONString<T>(value: string): JSONString<T>

Safely cast a string to JSONString after validation. Use this when you know the string is valid JSON.

Parameters

NameTypeDescription
§value
string
The string value to cast as JSONString

Returns

JSONString<T>
The value cast as a JSONString type

Example

Casting a validated string

const jsonStr = asJSONString<User>('{"name":"Alice"}')
§function

deserializeData<T>(serialized: SerializedData<T>): Data<T>

Convert SerializedData to Data by parsing the message.

Parameters

NameTypeDescription
§serialized
SerializedData<T>
The serialized data to deserialize

Returns

Data<T>
The deserialized data with parsed message

Example

Deserializing data with JSON message

const data = deserializeData({ ...metadata, message: '{"action":"update"}' })
// => { ...metadata, message: { action: 'update' } }
§function

isJSONString<T>(value: unknown): unknown

Type guard to check if a value is a JSONString.

Parameters

NameTypeDescription
§value
unknown
The value to check

Returns

unknown
True if the value is a string type, false otherwise

Example

Checking JSON string types

isJSONString('{"key":"value"}')
// => true

isJSONString({ key: 'value' })
// => false
§function

isValidId(id: unknown): boolean

Validates whether the provided value is a valid data message ID. The ID must be a 36-character string in UUID v4 format.

Parameters

NameTypeDescription
§id
unknown
The value to validate as a data message ID

Returns

boolean
True if the value is a valid UUID v4 string, false otherwise

Example

Validating data message IDs

isValidId('550e8400-e29b-41d4-a716-446655440000')
// => true

isValidId('invalid-id')
// => false
§function

isValidMessage<T>(message: T): boolean

Validates whether the provided message contains only valid, serializable data. Traverses the entire message structure to ensure all values are serializable types.

Parameters

NameTypeDescription
§message
T
The message to validate

Returns

boolean
True if all message data is valid and serializable, false otherwise

Example

Validating message serializability

isValidMessage({ name: 'Alice', items: [1, 2, 3] })
// => true

isValidMessage({ callback: () => {} })
// => false (functions are not serializable)
§function

isValidPid(pid: unknown): boolean

Validates whether the provided value is a valid protocol ID (PID). The PID must be a 36-character string in UUID v4 format.

Parameters

NameTypeDescription
§pid
unknown
The value to validate as a protocol ID

Returns

boolean
True if the value is a valid UUID v4 string, false otherwise

Example

Validating protocol IDs

isValidPid('550e8400-e29b-41d4-a716-446655440000')
// => true

isValidPid('not-a-uuid')
// => false
§function

isValidSchema(schema: unknown): boolean

Validates whether the provided value is a valid JSON Schema v4 schema. Uses the jsonschema validator to check compliance with the JSON Schema Draft v4 specification.

Parameters

NameTypeDescription
§schema
unknown
The value to validate as a JSON Schema

Returns

boolean
True if the value is a valid JSON Schema v4 schema, false otherwise

Example

Validating JSON schemas

isValidSchema({ type: 'object', properties: { name: { type: 'string' } } })
// => true

isValidSchema({ type: 'invalid-type' })
// => false
§function

isValidSchemaHash(schemaHash: unknown): boolean

Validates whether the provided value is a valid schema hash. The hash must be a valid SHA-256 hash string.

Parameters

NameTypeDescription
§schemaHash
unknown
The value to validate as a schema hash

Returns

boolean
True if the value is a valid SHA-256 hash, false otherwise

Example

Validating schema hashes

isValidSchemaHash('e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855')
// => true

isValidSchemaHash('invalid-hash')
// => false
§function

isValidSequence(sequence: unknown): boolean

Validates whether the provided value is a valid schema sequence number. The sequence must be a positive number greater than zero.

Parameters

NameTypeDescription
§sequence
unknown
The value to validate as a sequence number

Returns

boolean
True if the value is a positive number, false otherwise

Example

Validating sequence numbers

isValidSequence(1)
// => true

isValidSequence(0)
// => false
§function

isValidSerializedData(data: unknown): boolean

Validates whether the provided value is valid serialized data. Serialized data must be a non-empty string.

Parameters

NameTypeDescription
§data
unknown
The value to validate as serialized data

Returns

boolean
True if the value is a non-empty string, false otherwise

Example

Validating serialized data

isValidSerializedData('{"key":"value"}')
// => true

isValidSerializedData('')
// => false
§function

isValidUnencryptedData(data: unknown): boolean

Validates whether the provided value is valid unencrypted data. Checks that all required data fields are present and valid, including PID, ID, sequence number, message content, schema, and schema hash.

Parameters

NameTypeDescription
§data
unknown
The value to validate as unencrypted data

Returns

boolean
True if the value is a valid unencrypted data object, false otherwise

Example

Validating complete unencrypted data objects

isValidUnencryptedData({
  pid: '550e8400-e29b-41d4-a716-446655440000',
  id: '6ba7b810-9dad-11d1-80b4-00c04fd430c8',
  sequence: 1,
  message: { action: 'update' },
  schema: { type: 'object' },
  schemaHash: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',
})
// => true
§function

isValidUnserializedData(data: unknown): boolean

Validates whether the provided value is valid unserialized data. Unserialized data must be a Uint8Array instance.
Note: Uses multiple checks to handle cross-realm scenarios (e.g., jsdom in tests) where instanceof Uint8Array may fail due to different global contexts.

Parameters

NameTypeDescription
§data
unknown
The value to validate as unserialized data

Returns

boolean
True if the value is a Uint8Array, false otherwise

Example

Validating Uint8Array data

isValidUnserializedData(new Uint8Array([1, 2, 3]))
// => true

isValidUnserializedData('string-data')
// => false
§function

parseJSONString<T>(jsonString: JSONString<T>): T

Parse a JSONString back to its original type.

Parameters

NameTypeDescription
§jsonString
JSONString<T>
The JSON string to parse

Returns

T
The parsed object of type T

Example

Parsing a JSON string to typed object

const user = parseJSONString<User>('{"name":"Alice"}')
// => { name: 'Alice' }
§function

serializeData<T>(data: Data<T>): SerializedData<T>

Convert Data to SerializedData by stringifying the message.

Parameters

NameTypeDescription
§data
Data<T>
The data to serialize

Returns

SerializedData<T>
The serialized data with stringified message

Example

Serializing data for transmission

const serialized = serializeData({ ...metadata, message: { action: 'update' } })
// => { ...metadata, message: '{"action":"update"}' }

Interfaces

§interface

Data

Logical view of Data with deserialized message. This represents data after the message has been parsed from JSON. Use this type when working with the actual message object.

Properties

§readonly id:string
Identifies this message
§readonly key:string
A key used to encrypt a reply with
§readonly message:T
Contents of a message (deserialized)
§readonly pid:string
Identifies a process
§readonly schema:Schema
Schema of a message
§readonly schemaHash:string
Hash derived from the schema
§readonly sequence:number
A counter that increments by 1, representing steps of a process
§interface

SerializedData

Serialized wire format for Data. This represents data as it's stored, transmitted, and encrypted. The message field is always a JSON string representation.

Properties

§readonly id:string
Identifies this message
§readonly key:string
A key used to encrypt a reply with
§readonly message:JSONString<T>
Contents of a message as JSON string
§readonly pid:string
Identifies a process
§readonly schema:Schema
Schema of a message
§readonly schemaHash:string
Hash derived from the schema
§readonly sequence:number
A counter that increments by 1, representing steps of a process
§interface

State

Traversal state for message validation.

Properties

§valid:boolean
Whether the current traversal state is valid.

Types

§type

DataCreater

Creates SerializedData from a message. Returns the wire format with JSON-serialized message.
type DataCreater = (pid: string, sequence: number, message: T) => Promise<SerializedData<T>>
§type

DataDecrypter

Decrypts binary data back to SerializedData. Returns the wire format with JSON string message.
type DataDecrypter = (data: Uint8Array, password: string) => Promise<SerializedData<T>>
§type

DataEncrypter

Encrypts SerializedData to binary format. Takes the wire format (with JSON string message) and encrypts it.
type DataEncrypter = (data: SerializedData<T>, password: string) => Promise<Uint8Array>
§type

JSONString

Branded type representing a JSON-serialized string of type T. This is a nominal type that carries information about what type the string represents when parsed, while remaining a string at runtime.
type JSONString = string & { __jsonBrand: unknown; __type: T }
§type

SchemaCreater

Creates a schema from input data.
type SchemaCreater = (data: unknown) => Schema

Variables

§type

createData

§type

decryptData

§type

encryptData

§type

getSchema

Creates a JSON schema from the provided data.