# knotkit/wire

> Encodes bounded binary envelopes and element codecs for Knotkit structures

## Use

```ts
import { InvalidInputError, ParseError } from 'knotkit/errors'
import { artifactFormat } from 'knotkit/wire'

class ExampleParseError extends ParseError<string> {
  readonly moduleName = 'knotkit/example'
}

class ExampleInvalidInputError extends InvalidInputError<string> {
  readonly moduleName = 'knotkit/example'
}

const FORMAT = artifactFormat({
  name: 'example',
  magic: Uint8Array.of(0x4b, 0x4b, 0x45, 0x58),
  payloadVersion: 1,
  kindTags: { dense: 1, sparse: 2 },
  sectionTags: [1],
  wrongFormatHint: 'use deserializeExampleJson for object projections',
  parseError: (code, detail) => new ExampleParseError(code, detail),
  serializationCodes: {
    INVALID_ARGUMENT: 'SERIALIZATION_LIMIT_EXCEEDED',
    INVALID_STRING: 'SERIALIZATION_LIMIT_EXCEEDED',
    INVALID_CODEC_RESULT: 'INVALID_CODEC_RESULT',
    NON_INJECTIVE_CODEC: 'NON_INJECTIVE_CODEC',
  },
  invalidInputError: (code, detail) => new ExampleInvalidInputError(code, detail),
})

const bytes = FORMAT.serialize(() => ({
  packageHeader: Uint8Array.of(FORMAT.kindTag('dense')),
  sections: [{ tag: 1, bytes: Uint8Array.of(2, 3) }],
}))

const { packageHeader, sections } = FORMAT.deserialize(bytes)
const kind = FORMAT.kindOf(packageHeader[0])
```

## What it solves

* 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

## Worked example

* 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`](https://github.com/jkomyno/knotkit/blob/main/packages/wire/demo.ts) against `knotkit/wire`.

## API

| Export                                                                                      | Returns                         | Does                                                                                                                         |
| ------------------------------------------------------------------------------------------- | ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- |
| [`artifactFormat`](/reference/knotkit/wire/functions/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`](/reference/knotkit/wire/functions/serializeenvelope/)                 | `Uint8Array`                    | Frame package bytes into an aligned, sectioned envelope with an optional CRC-32 integrity section.                           |
| [`deserializeEnvelope`](/reference/knotkit/wire/functions/deserializeenvelope/)             | `WireEnvelope`                  | Validate envelope geometry and hand the owning package its sections.                                                         |
| [`inspectEnvelope`](/reference/knotkit/wire/functions/inspectenvelope/)                     | `WireEnvelopeParts`             | Take a valid envelope apart into owned copies of the parts serializeEnvelope takes back, whichever module wrote it.          |
| [`tamperEnvelope`](/reference/knotkit/wire/functions/tamperenvelope/)                       | `Uint8Array`                    | Copy a valid artifact and damage the copy so decoding fails for exactly one named reason.                                    |
| [`crc32`](/reference/knotkit/wire/functions/crc32/)                                         | `number`                        | Checksum the bytes an integrity section covers.                                                                              |
| [`chooseIntegerWidth`](/reference/knotkit/wire/functions/chooseintegerwidth/)               | `IntegerWidth`                  | Pick the smallest declared little-endian width that holds a maximum, so an artifact spends no bytes on headroom.             |
| [`integerWidthMaximum`](/reference/knotkit/wire/functions/integerwidthmaximum/)             | `number`                        | The largest value a declared integer width can hold.                                                                         |
| [`requireSection`](/reference/knotkit/wire/functions/requiresection/)                       | `WireSection`                   | Return the only section carrying a tag, or fail with the package's geometry error.                                           |
| [`rejectSection`](/reference/knotkit/wire/functions/rejectsection/)                         | `void`                          | Fail when an artifact carries a section tag the package's layout forbids.                                                    |
| [`stateBridge`](/reference/knotkit/wire/functions/statebridge/)                             | `StateBridge<State>`            | Package-scoped bridge a factory attaches its closure state through, readable by the package's serializer only.               |
| [`mapWireSerializationError`](/reference/knotkit/wire/functions/mapwireserializationerror/) | `T`                             | Translate 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

| Member        | Cost     |
| ------------- | -------- |
| `serialize`   | O(bytes) |
| `deserialize` | O(bytes) |
| `kindTag`     | O(1)     |
| `kindOf`      | O(1)     |

`serializeEnvelope` 1 members

| Member              | Cost     |
| ------------------- | -------- |
| `serializeEnvelope` | O(bytes) |

`deserializeEnvelope` 1 members

| Member                | Cost     |
| --------------------- | -------- |
| `deserializeEnvelope` | O(bytes) |

`inspectEnvelope` 1 members

| Member            | Cost     |
| ----------------- | -------- |
| `inspectEnvelope` | O(bytes) |

`tamperEnvelope` 1 members

| Member           | Cost     |
| ---------------- | -------- |
| `tamperEnvelope` | O(bytes) |

`crc32` 1 members

| Member  | Cost     |
| ------- | -------- |
| `crc32` | O(bytes) |

`chooseIntegerWidth` 1 members

| Member               | Cost |
| -------------------- | ---- |
| `chooseIntegerWidth` | O(1) |

`integerWidthMaximum` 1 members

| Member                | Cost |
| --------------------- | ---- |
| `integerWidthMaximum` | O(1) |

`requireSection` 1 members

| Member           | Cost        |
| ---------------- | ----------- |
| `requireSection` | O(sections) |

`rejectSection` 1 members

| Member          | Cost        |
| --------------- | ----------- |
| `rejectSection` | O(sections) |

`stateBridge` 2 members

| Member    | Cost |
| --------- | ---- |
| `attach`  | O(1) |
| `stateOf` | O(1) |

## What you pass in

| Input                                                      | Type                             | Get one from                     |
| ---------------------------------------------------------- | -------------------------------- | -------------------------------- |
| generic value encoding                                     | `ElementCodec<T>`                | [`knotkit/wire`](/modules/wire/) |
| the package's own error codes a wire failure translates to | `WireSerializationCodeMap<Code>` | [`knotkit/wire`](/modules/wire/) |

## Errors

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`

## Save and restore

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

## When not to use it

| If you need to…                               | Use instead                                |
| --------------------------------------------- | ------------------------------------------ |
| 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                          |

## Performance

Measured by the suite in [`packages/wire/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/wire/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/wireCopy prompt

```
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/
```

## See also

* [API reference](/reference/knotkit/wire/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/wire/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/wire/knotkit.capability.json)suggest a change to the source record
