Skip to content

knotkit/wire

Encodes bounded binary envelopes and element codecs for Knotkit structures

import {
class InvalidInputError<Code extends string>

Thrown when a caller passes an argument or object that violates a public contract: an out-of-range value, a malformed id, or an object not produced by the package's own factories.

Abstract so every concrete instance belongs to the throwing package's own subclass, which fixes Code to that package's error-code union and gives .name a package-specific value.

InvalidInputError
,
class ParseError<Code extends string>

Thrown when decoding a serialized payload that is malformed, internally inconsistent, or fails element validation.

Abstract for the same reason as

InvalidInputError

.

ParseError
} from 'knotkit/errors'
import {
function artifactFormat<Kind extends string, Failure extends KnotkitError, InvalidInputCode extends string>(definition: ArtifactFormatDefinition<Kind, Failure, InvalidInputCode>): ArtifactFormat<Kind, Failure>

Declare a module's binary artifact format.

@throws ― {WireInvalidInputError} With INVALID_ARGUMENT when the magic is not four bytes, the payload version or a tag is not a byte, or two kinds share a tag.

artifactFormat
} from 'knotkit/wire'
class
class ExampleParseError
ExampleParseError
extends
class ParseError<Code extends string>

Thrown when decoding a serialized payload that is malformed, internally inconsistent, or fails element validation.

Abstract for the same reason as

InvalidInputError

.

ParseError
<string> {
readonly
ExampleParseError.moduleName: "knotkit/example"
moduleName
= 'knotkit/example'
}
class
class ExampleInvalidInputError
ExampleInvalidInputError
extends
class InvalidInputError<Code extends string>

Thrown when a caller passes an argument or object that violates a public contract: an out-of-range value, a malformed id, or an object not produced by the package's own factories.

Abstract so every concrete instance belongs to the throwing package's own subclass, which fixes Code to that package's error-code union and gives .name a package-specific value.

InvalidInputError
<string> {
readonly
ExampleInvalidInputError.moduleName: "knotkit/example"
moduleName
= 'knotkit/example'
}
const
const FORMAT: ArtifactFormat<"dense" | "sparse", ExampleParseError>
FORMAT
=
artifactFormat<"dense" | "sparse", ExampleParseError, "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED">(definition: ArtifactFormatDefinition<"dense" | "sparse", ExampleParseError, "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED">): ArtifactFormat<"dense" | "sparse", ExampleParseError>

Declare a module's binary artifact format.

@throws ― {WireInvalidInputError} With INVALID_ARGUMENT when the magic is not four bytes, the payload version or a tag is not a byte, or two kinds share a tag.

artifactFormat
({
ArtifactFormatDefinition<Kind extends string, Failure extends KnotkitError, InvalidInputCode extends string>.name: string

How messages name the artifact, such as heap or segmented-trie.

name
: 'example',
ArtifactFormatDefinition<Kind extends string, Failure extends KnotkitError, InvalidInputCode extends string>.magic: Uint8Array<ArrayBufferLike>

The four bytes that identify the owning module.

magic
:
var Uint8Array: Uint8ArrayConstructor

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
.
Uint8ArrayConstructor.of(...items: number[]): Uint8Array<ArrayBuffer>

Returns a new array from a set of elements.

@param ― items A set of elements to include in the new array object.

of
(0x4b, 0x4b, 0x45, 0x58),
ArtifactFormatDefinition<Kind extends string, Failure extends KnotkitError, InvalidInputCode extends string>.payloadVersion: number

The one payload version this release writes and reads. The number is the module's; the comparison is wire's.

payloadVersion
: 1,
ArtifactFormatDefinition<"dense" | "sparse", ExampleParseError, "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED">.kindTags: Readonly<Record<"dense" | "sparse", number>>

The byte each kind is written as. A tag is part of the wire contract, so it is never reused or renumbered.

kindTags
: {
dense: number
dense
: 1,
sparse: number
sparse
: 2 },
ArtifactFormatDefinition<Kind extends string, Failure extends KnotkitError, InvalidInputCode extends string>.sectionTags: readonly number[]

The section tags the module reads. Any other tag is validated and skipped without a copy.

sectionTags
: [1],
ArtifactFormatDefinition<Kind extends string, Failure extends KnotkitError, InvalidInputCode extends string>.wrongFormatHint?: string | undefined

Where a value that is not bytes belongs, appended to the wrong-format message.

wrongFormatHint
: 'use deserializeExampleJson for object projections',
ArtifactFormatDefinition<"dense" | "sparse", ExampleParseError, "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED">.parseError: (code: WireFailureCode, detail: string) => ExampleParseError

Builds the module's parse error from the code it owns for a wire failure reason.

parseError
: (
code: WireFailureCode
code
,
detail: string
detail
) => new
constructor ExampleParseError<string>(code: string, message: string): ExampleParseError
ExampleParseError
(
code: WireFailureCode
code
,
detail: string
detail
),
ArtifactFormatDefinition<"dense" | "sparse", ExampleParseError, "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED">.serializationCodes: Readonly<Record<"INVALID_CODEC_RESULT" | "INVALID_ARGUMENT" | "INVALID_STRING" | "NON_INJECTIVE_CODEC", "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED">>

The module's translation of each wire caller-contract code raised while writing.

serializationCodes
: {
type INVALID_ARGUMENT: "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED"
INVALID_ARGUMENT
: 'SERIALIZATION_LIMIT_EXCEEDED',
type INVALID_STRING: "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED"
INVALID_STRING
: 'SERIALIZATION_LIMIT_EXCEEDED',
type INVALID_CODEC_RESULT: "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED"
INVALID_CODEC_RESULT
: 'INVALID_CODEC_RESULT',
type NON_INJECTIVE_CODEC: "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED"
NON_INJECTIVE_CODEC
: 'NON_INJECTIVE_CODEC',
},
ArtifactFormatDefinition<"dense" | "sparse", ExampleParseError, "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED">.invalidInputError: (code: "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED", detail: string) => KnotkitError

Builds the module's invalid-input error from a translated code.

invalidInputError
: (
code: "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED"
code
,
detail: string
detail
) => new
constructor ExampleInvalidInputError<string>(code: string, message: string): ExampleInvalidInputError
ExampleInvalidInputError
(
code: "INVALID_CODEC_RESULT" | "NON_INJECTIVE_CODEC" | "SERIALIZATION_LIMIT_EXCEEDED"
code
,
detail: string
detail
),
})
const
const bytes: Uint8Array<ArrayBufferLike>
bytes
=
const FORMAT: ArtifactFormat<"dense" | "sparse", ExampleParseError>
FORMAT
.
ArtifactFormat<"dense" | "sparse", ExampleParseError>.serialize: (build: () => ArtifactPayload, options?: ArtifactSerializeOptions) => Uint8Array

Run build and frame its payload under this format's magic and payload version.

@throws ― {KnotkitError} The module's invalid-input error for every wire caller-contract failure raised by build or by the framing; any other error is rethrown untouched.

serialize
(() => ({
ArtifactPayload.packageHeader: Uint8Array<ArrayBufferLike>
packageHeader
:
var Uint8Array: Uint8ArrayConstructor

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
.
Uint8ArrayConstructor.of(...items: number[]): Uint8Array<ArrayBuffer>

Returns a new array from a set of elements.

@param ― items A set of elements to include in the new array object.

of
(
const FORMAT: ArtifactFormat<"dense" | "sparse", ExampleParseError>
FORMAT
.
ArtifactFormat<"dense" | "sparse", ExampleParseError>.kindTag: (kind: "dense" | "sparse") => number

The byte kind is written as.

kindTag
('dense')),
ArtifactPayload.sections: readonly WireSection[]
sections
: [{
WireSection.tag: number
tag
: 1,
WireSection.bytes: Uint8Array<ArrayBufferLike>
bytes
:
var Uint8Array: Uint8ArrayConstructor

A typed array of 8-bit unsigned integer values. The contents are initialized to 0. If the requested number of bytes could not be allocated an exception is raised.

Uint8Array
.
Uint8ArrayConstructor.of(...items: number[]): Uint8Array<ArrayBuffer>

Returns a new array from a set of elements.

@param ― items A set of elements to include in the new array object.

of
(2, 3) }],
}))
const {
const packageHeader: Uint8Array<ArrayBufferLike>
packageHeader
,
const sections: readonly WireSection[]
sections
} =
const FORMAT: ArtifactFormat<"dense" | "sparse", ExampleParseError>
FORMAT
.
ArtifactFormat<"dense" | "sparse", ExampleParseError>.deserialize: (value: unknown) => ArtifactPayload

Validate untrusted input as this format's envelope and return the module-owned bytes.

@throws ― {KnotkitError} The module's parse error: wrong-format for a value that is not a Uint8Array, an envelope reason for malformed bytes, and unsupported-payload-version for another payload version.

deserialize
(
const bytes: Uint8Array<ArrayBufferLike>
bytes
)
const
const kind: "dense" | "sparse"
kind
=
const FORMAT: ArtifactFormat<"dense" | "sparse", ExampleParseError>
FORMAT
.
ArtifactFormat<"dense" | "sparse", ExampleParseError>.kindOf: (tag: number) => "dense" | "sparse"

The kind a header's tag byte names.

@throws ― {KnotkitError} The module's unknown-kind parse error for a tag no kind is written as.

kindOf
(
const packageHeader: Uint8Array<ArrayBufferLike>
packageHeader
[0])
wire.ts
  • encode a package-identified binary artifact with validated section geometry
  • declare a module's binary artifact once so every decoder runs the same prelude and raises the same codes
  • encode generic values with an injected byte codec
  • prove an element codec injective over a run before emitting an artifact
  • share bounded little-endian wire primitives across data-structure packages
  • hand closure state to a package serializer without widening its public interface
{"v":1,"box":[48.2743,94.1597,1043,437.3555],"x":{"s":"log","lim":[11.7126855676,22381.2035667],"inv":false,"g":0,"t":"Payload (bytes)","tk":[[16,"16"],[64,"64"],[256,"256"],[1024,"1,024"],[4096,"4,096"],[16384,"16,384"]],"b":10},"y":{"s":"linear","lim":[-3.2962962963,81.269005848],"inv":false,"g":0,"tk":[[0,"0"],[25,"25"],[50,"50"],[75,"75"]]},"ti":"Framing is a fixed 32 B: 67% of the envelope around a 16-byte payload, 3% at 1 KiB","a":[{"k":"line","c":"#fffff8","s":"x","d":[16,77.7777777778,32,63.6363636364,64,46.6666666667,128,30.4347826087,256,17.9487179487,512,9.85915492958,1024,5.18518518519,2048,2.66159695817,4096,1.34874759152,8192,0.678952473327,16384,0.340632603406],"p":[89.34,108.33,180.6,165.72,271.86,234.59,363.12,300.46,454.38,351.14,545.64,383.97,636.9,402.93,728.16,413.18,819.41,418.5,910.67,421.22,1001.93,422.6]},{"k":"line","c":"#c4501b","s":"x","d":[16,77.7777777778,32,63.6363636364,64,46.6666666667,128,30.4347826087,256,17.9487179487,512,9.85915492958,1024,5.18518518519,2048,2.66159695817,4096,1.34874759152,8192,0.678952473327,16384,0.340632603406],"p":[89.34,108.33,180.6,165.72,271.86,234.59,363.12,300.46,454.38,351.14,545.64,383.97,636.9,402.93,728.16,413.18,819.41,418.5,910.67,421.22,1001.93,422.6]},{"k":"line","c":"#fffff8","s":"x","d":[16,66.6666666667,32,50,64,33.3333333333,128,20,256,11.1111111111,512,5.88235294118,1024,3.0303030303,2048,1.53846153846,4096,0.77519379845,8192,0.389105058366,16384,0.194931773879],"p":[89.34,153.42,180.6,221.06,271.86,288.7,363.12,342.81,454.38,378.89,545.64,400.11,636.9,411.68,728.16,417.73,819.41,420.83,910.67,422.4,1001.93,423.19]},{"k":"line","c":"#1d5fa6","s":"x","d":[16,66.6666666667,32,50,64,33.3333333333,128,20,256,11.1111111111,512,5.88235294118,1024,3.0303030303,2048,1.53846153846,4096,0.77519379845,8192,0.389105058366,16384,0.194931773879],"p":[89.34,153.42,180.6,221.06,271.86,288.7,363.12,342.81,454.38,378.89,545.64,400.11,636.9,411.68,728.16,417.73,819.41,420.83,910.67,422.4,1001.93,423.19]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"}],"lg":[]} 16 64 256 1,024 4,096 16,384 Payload (bytes) 0 25 50 75 56 B with checksum (5% at 1 KiB) 32 B framing only Framing share of the envelope (%) Framing is a fixed 32 B: 67% of the envelope around a 16-byte payload, 3% at 1 KiB
{"v":1,"box":[48.2743,150.6246,588.7795,437.3555],"x":{"s":"log","lim":[11.7126855676,22381.2035667],"inv":false,"g":0,"t":"Payload (bytes)","tk":[[16,"16"],[64,"64"],[256,"256"],[1024,"1,024"],[4096,"4,096"],[16384,"16,384"]],"b":10},"y":{"s":"linear","lim":[-3.2962962963,81.269005848],"inv":false,"g":0,"tk":[[0,"0"],[25,"25"],[50,"50"],[75,"75"]]},"ti":"Framing is a fixed 32 B: 67% of the\nenvelope around a 16-byte payload, 3% at\n1 KiB","a":[{"k":"line","c":"#fffff8","s":"x","d":[16,77.7777777778,32,63.6363636364,64,46.6666666667,128,30.4347826087,256,17.9487179487,512,9.85915492958,1024,5.18518518519,2048,2.66159695817,4096,1.34874759152,8192,0.678952473327,16384,0.340632603406],"p":[70.59,162.46,120.18,210.41,169.76,267.95,219.35,322.99,268.94,365.32,318.53,392.75,368.11,408.6,417.7,417.15,467.29,421.61,516.88,423.88,566.47,425.02]},{"k":"line","c":"#c4501b","s":"x","d":[16,77.7777777778,32,63.6363636364,64,46.6666666667,128,30.4347826087,256,17.9487179487,512,9.85915492958,1024,5.18518518519,2048,2.66159695817,4096,1.34874759152,8192,0.678952473327,16384,0.340632603406],"p":[70.59,162.46,120.18,210.41,169.76,267.95,219.35,322.99,268.94,365.32,318.53,392.75,368.11,408.6,417.7,417.15,467.29,421.61,516.88,423.88,566.47,425.02]},{"k":"line","c":"#fffff8","s":"x","d":[16,66.6666666667,32,50,64,33.3333333333,128,20,256,11.1111111111,512,5.88235294118,1024,3.0303030303,2048,1.53846153846,4096,0.77519379845,8192,0.389105058366,16384,0.194931773879],"p":[70.59,200.14,120.18,256.65,169.76,313.16,219.35,358.37,268.94,388.51,318.53,406.23,368.11,415.9,417.7,420.96,467.29,423.55,516.88,424.86,566.47,425.52]},{"k":"line","c":"#1d5fa6","s":"x","d":[16,66.6666666667,32,50,64,33.3333333333,128,20,256,11.1111111111,512,5.88235294118,1024,3.0303030303,2048,1.53846153846,4096,0.77519379845,8192,0.389105058366,16384,0.194931773879],"p":[70.59,200.14,120.18,256.65,169.76,313.16,219.35,358.37,268.94,388.51,318.53,406.23,368.11,415.9,417.7,420.96,467.29,423.55,516.88,424.86,566.47,425.52]},{"k":"segments","c":"#8c8c84"},{"k":"segments","c":"#8c8c84"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#2b2b28"},{"k":"annotation","c":"#5c5c57"}],"lg":[]} 16 64 256 1,024 4,096 16,384 Payload (bytes) 0 25 50 75 56 B with checksum (5% at 1 KiB) 32 B framing only Framing share of the envelope (%) Framing is a fixed 32 B: 67% of the envelope around a 16-byte payload, 3% at 1 KiB
  • A 16-byte payload adds 32 bytes of framing or 56 bytes with a checksum.
  • Inspected version 1 and recovered 16 payload bytes.
  • The optional checksum detects accidental corruption.

Hover or focus a chart for exact values. Drawn by demo.ts against knotkit/wire.

ExportReturnsDoes
artifactFormatArtifactFormat<Kind, Failure>Declare a module's magic, payload version, kind tags, and section tags once; frame its payloads and run its decoder prelude.
serializeEnvelopeUint8ArrayFrame package bytes into an aligned, sectioned envelope with an optional CRC-32 integrity section.
deserializeEnvelopeWireEnvelopeValidate envelope geometry and hand the owning package its sections.
inspectEnvelopeWireEnvelopePartsTake a valid envelope apart into owned copies of the parts serializeEnvelope takes back, whichever module wrote it.
tamperEnvelopeUint8ArrayCopy a valid artifact and damage the copy so decoding fails for exactly one named reason.
crc32numberChecksum the bytes an integrity section covers.
chooseIntegerWidthIntegerWidthPick the smallest declared little-endian width that holds a maximum, so an artifact spends no bytes on headroom.
integerWidthMaximumnumberThe largest value a declared integer width can hold.
requireSectionWireSectionReturn the only section carrying a tag, or fail with the package's geometry error.
rejectSectionvoidFail when an artifact carries a section tag the package's layout forbids.
stateBridgeStateBridge<State>Package-scoped bridge a factory attaches its closure state through, readable by the package's serializer only.
mapWireSerializationErrorTTranslate wire caller-contract failures into a package's own closed invalid-input codes.

Cost per member. Open a row for every operation.

artifactFormat 4 members
MemberCost
serializeO(bytes)
deserializeO(bytes)
kindTagO(1)
kindOfO(1)
serializeEnvelope 1 members
MemberCost
serializeEnvelopeO(bytes)
deserializeEnvelope 1 members
MemberCost
deserializeEnvelopeO(bytes)
inspectEnvelope 1 members
MemberCost
inspectEnvelopeO(bytes)
tamperEnvelope 1 members
MemberCost
tamperEnvelopeO(bytes)
crc32 1 members
MemberCost
crc32O(bytes)
chooseIntegerWidth 1 members
MemberCost
chooseIntegerWidthO(1)
integerWidthMaximum 1 members
MemberCost
integerWidthMaximumO(1)
requireSection 1 members
MemberCost
requireSectionO(sections)
rejectSection 1 members
MemberCost
rejectSectionO(sections)
stateBridge 2 members
MemberCost
attachO(1)
stateOfO(1)
InputTypeGet one from
generic value encodingElementCodec<T>knotkit/wire
the package's own error codes a wire failure translates toWireSerializationCodeMap<Code>knotkit/wire

Every error this module throws is WireInvalidInputError, with a code from a closed, exported list. Branch on the code; the message is for people.

WireInvalidInputError
INVALID_ARGUMENT
Other
INVALID_STRING INVALID_CODEC_RESULT NON_INJECTIVE_CODEC

Serialization lives in a separate entrypoint, , so code that never saves a structure never loads a parser.

Functions
serializeEnvelope, deserializeEnvelope
Formats
binary
Compatibility
schema-versioned, envelope v1
If you need to…Use instead
persist a Knotkit data structure directlythe structure package's serialize function
produce a human-readable persistence artifactthe structure package's Json serializer
compress a binary artifactCompressionStream

Measured by the suite in packages/wire/__tests__/bench. The numbers come from one machine, so run the suite on yours before deciding on speed alone.

Prompt · knotkit/wire
Use knotkit/wire for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/wire'.

Exports:
- `artifactFormat` → `ArtifactFormat<Kind, Failure>`: Declare a module's magic, payload version, kind tags, and section tags once; frame its payloads and run its decoder prelude.
- `serializeEnvelope` → `Uint8Array`: Frame package bytes into an aligned, sectioned envelope with an optional CRC-32 integrity section.
- `deserializeEnvelope` → `WireEnvelope`: Validate envelope geometry and hand the owning package its sections.
- `inspectEnvelope` → `WireEnvelopeParts`: Take a valid envelope apart into owned copies of the parts serializeEnvelope takes back, whichever module wrote it.
- `tamperEnvelope` → `Uint8Array`: Copy a valid artifact and damage the copy so decoding fails for exactly one named reason.
- `crc32` → `number`: Checksum the bytes an integrity section covers.
- `chooseIntegerWidth` → `IntegerWidth`: Pick the smallest declared little-endian width that holds a maximum, so an artifact spends no bytes on headroom.
- `integerWidthMaximum` → `number`: The largest value a declared integer width can hold.
- `requireSection` → `WireSection`: Return the only section carrying a tag, or fail with the package's geometry error.
- `rejectSection` → `void`: Fail when an artifact carries a section tag the package's layout forbids.
- `stateBridge` → `StateBridge<State>`: Package-scoped bridge a factory attaches its closure state through, readable by the package's serializer only.
- `mapWireSerializationError` → `T`: Translate wire caller-contract failures into a package's own closed invalid-input codes.

Inputs and their sources:
- generic value encoding: `ElementCodec<T>` from `knotkit/wire`
- the package's own error codes a wire failure translates to: `WireSerializationCodeMap<Code>` from `knotkit/wire`

Use something else when:
- persist a Knotkit data structure directly → the structure package's serialize function
- produce a human-readable persistence artifact → the structure package's Json serializer
- compress a binary artifact → CompressionStream

Errors are WireInvalidInputError with a `code` property. Branch on `error.code`, never on the message. Save and load through `undefined` (serializeEnvelope, deserializeEnvelope).

Full page: https://knotkit.jkomyno.dev/modules/wire.md
Types: node_modules/knotkit/wire/ and https://knotkit.jkomyno.dev/reference/knotkit/wire/