Plugins add support for types that seroval does not handle itself. To use one:
- Install the package that has the plugin, such as
seroval-plugins. - Pass the plugin in the
pluginsoption of the function that sends the value. - Pass the same plugin to the function that decodes the value.
import { serializeAsync } from 'seroval';
import { BlobPlugin } from 'seroval-plugins/web';
const blob = new Blob(['Hello'], { type: 'text/plain' });
await serializeAsync(blob, { plugins: [BlobPlugin] });Every function takes plugins, including fromJSON, fromCrossJSON, createCrossDeserializer, Serializer, binary.serialize and binary.deserialize. The receiver needs a plugin with the same tag as the one the sender used, or decoding throws SerovalMissingPluginError.
When several plugins accept the same value, the first one in the list wins. A plugin can depend on other plugins, which are then added for you.
seroval-plugins
The seroval-plugins package has plugins for common web platform types.
npm install seroval-pluginspnpm add seroval-pluginsyarn add seroval-pluginsbun add seroval-pluginsimport {
FormDataPlugin,
HeadersPlugin,
RequestPlugin,
URLPlugin,
} from 'seroval-plugins/web';Some types can only be read asynchronously. A Blob's bytes, for example, are only available through a promise. Those plugins do not work with the sync functions.
Every plugin has a binary section, so all of them work in binary mode. That includes BlobPlugin, FilePlugin and a FormData with files.
| Plugin | Type | Sync | Async | Streaming | Binary |
|---|---|---|---|---|---|
URLPlugin | URL | ✅ | ✅ | ✅ | ✅ |
URLSearchParamsPlugin | URLSearchParams | ✅ | ✅ | ✅ | ✅ |
HeadersPlugin | Headers | ✅ | ✅ | ✅ | ✅ |
FormDataPlugin | FormData | ✅ 1 | ✅ | ✅ 1 | ✅ |
BlobPlugin | Blob | ❌ | ✅ | ❌ 2 | ✅ |
FilePlugin | File | ❌ | ✅ | ❌ 2 | ✅ |
ReadableStreamPlugin | ReadableStream | ❌ | ✅ | ✅ | ✅ |
RequestPlugin | Request | ❌ | ✅ | ✅ | ✅ |
ResponsePlugin | Response | ❌ | ✅ | ✅ | ✅ |
EventPlugin | Event | ✅ | ✅ | ✅ | ✅ |
CustomEventPlugin | CustomEvent | ✅ | ✅ | ✅ | ✅ |
DOMExceptionPlugin | DOMException | ✅ | ✅ | ✅ | ✅ |
ImageDataPlugin | ImageData | ✅ | ✅ | ✅ | ✅ |
AbortSignalPlugin | AbortSignal | ✅ | ✅ | ✅ | ✅ |
To use every web plugin at once, put FilePlugin first. A File is also a Blob, and the first plugin that matches a value is the one used, so with BlobPlugin first a File comes back as a Blob without its name.
import * as web from 'seroval-plugins/web';
const plugins = [
web.FilePlugin,
...Object.values(web).filter((plugin) => plugin !== web.FilePlugin),
];Writing your own
See Writing plugins. If your plugin decodes data from a client, also read Plugin security.