faultferry 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.es.md +220 -0
- package/README.ja.md +220 -0
- package/README.md +219 -2
- package/README.pt.md +220 -0
- package/dist/index.cjs +875 -0
- package/dist/index.d.cts +121 -0
- package/index.d.ts +121 -0
- package/package.json +65 -4
- package/src/index.js +868 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Alexandre Kohler
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.es.md
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
<picture>
|
|
2
|
+
<source media="(prefers-color-scheme: dark)" srcset="assets/banner-dark.svg">
|
|
3
|
+
<img alt="faultferry: envía errores entre procesos y recupéralos intactos" src="assets/banner-light.svg" width="100%">
|
|
4
|
+
</picture>
|
|
5
|
+
|
|
6
|
+
[English](README.md) | [Português (Brasil)](README.pt.md) | **Español** | [日本語](README.ja.md)
|
|
7
|
+
|
|
8
|
+
[](https://github.com/kwy404/faultferry/actions/workflows/ci.yml)
|
|
9
|
+
[](https://www.npmjs.com/package/faultferry)
|
|
10
|
+
[](#tamaño)
|
|
11
|
+
[](package.json)
|
|
12
|
+
[](index.d.ts)
|
|
13
|
+
[](LICENSE)
|
|
14
|
+
|
|
15
|
+
**Serializa errores de JavaScript a JSON plano y deserialízalos de vuelta, sin perder nada.** faultferry conserva la clase, el mensaje, el stack, la cadena de cause (con ciclos), AggregateError, SuppressedError, DOMException, las clases de error propias y los valores lanzados que no son errores, para que puedas enviar errores entre procesos y recuperarlos intactos.
|
|
16
|
+
|
|
17
|
+
`JSON.stringify(new Error('boom'))` devuelve `{}`. Los workers, los procesos hijos, HTTP y las colas de mensajes mueven datos, no errores, así que la clase, la cadena de cause y cada campo propio se pierden por el camino. faultferry convierte cualquier valor lanzado en JSON plano y lo reconstruye al otro lado: la misma clase, mensaje, stack, cadena de cause (ciclos incluidos), miembros de AggregateError, campos de SuppressedError, name y code de DOMException y propiedades propias. Nunca lanza excepciones ante entradas hostiles y no tiene dependencias.
|
|
18
|
+
|
|
19
|
+
Sitio web y playground en vivo: https://kwy404.github.io/faultferry/es/
|
|
20
|
+
|
|
21
|
+
## Instalación
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
npm i faultferry
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Builds ESM y CommonJS, tipos de TypeScript escritos a mano, Node.js 18 o posterior, Bun, Deno y navegadores modernos.
|
|
28
|
+
|
|
29
|
+
## Inicio rápido
|
|
30
|
+
|
|
31
|
+
```js
|
|
32
|
+
import { serialize, deserialize, register } from 'faultferry';
|
|
33
|
+
|
|
34
|
+
class HttpError extends Error {
|
|
35
|
+
constructor(message, status, options) {
|
|
36
|
+
super(message, options);
|
|
37
|
+
this.name = 'HttpError';
|
|
38
|
+
this.status = status;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
register(HttpError); // en ambos lados
|
|
42
|
+
|
|
43
|
+
const error = new HttpError('checkout failed', 502, { cause: new TypeError('fetch failed') });
|
|
44
|
+
|
|
45
|
+
const wire = JSON.stringify(serialize(error));
|
|
46
|
+
const back = deserialize(JSON.parse(wire));
|
|
47
|
+
|
|
48
|
+
back instanceof HttpError; // true
|
|
49
|
+
back.status; // 502
|
|
50
|
+
back.cause instanceof TypeError; // true
|
|
51
|
+
back.stack === error.stack; // true
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
A través de un worker:
|
|
55
|
+
|
|
56
|
+
```js
|
|
57
|
+
// worker.js
|
|
58
|
+
self.onmessage = async ({ data }) => {
|
|
59
|
+
try {
|
|
60
|
+
postMessage({ ok: true, value: await run(data) });
|
|
61
|
+
} catch (error) {
|
|
62
|
+
postMessage({ ok: false, error: serialize(error) });
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// main.js
|
|
67
|
+
worker.onmessage = ({ data }) => {
|
|
68
|
+
if (!data.ok) throw deserialize(data.error);
|
|
69
|
+
};
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
Del servidor al navegador, sin filtrar stack traces:
|
|
73
|
+
|
|
74
|
+
```js
|
|
75
|
+
app.use((error, req, res, next) => {
|
|
76
|
+
res.status(error.status ?? 500).json(serialize(error, { stack: false, maxDepth: 8 }));
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## API
|
|
81
|
+
|
|
82
|
+
### `serialize(value, options?)`
|
|
83
|
+
|
|
84
|
+
Convierte cualquier valor, normalmente algo que se lanzó, en un valor plano que `JSON.stringify`, `postMessage` y `structuredClone` aceptan. Nunca lanza excepciones ante entradas hostiles.
|
|
85
|
+
|
|
86
|
+
| opción | por defecto | significado |
|
|
87
|
+
| --- | --- | --- |
|
|
88
|
+
| `maxDepth` | `32` | Límite de anidamiento. Los contenedores más profundos pasan a ser `"[Object]"`, `"[Array]"`, `"[Map]"` o `"[Set]"`; los errores más profundos conservan solo clase, name y message. |
|
|
89
|
+
| `maxNodes` | `10000` | Total de contenedores y errores copiados antes de aplicar el mismo recorte. |
|
|
90
|
+
| `maxLength` | `Infinity` | String más largo que se conserva. Los más largos se cortan y terminan en `...`. |
|
|
91
|
+
| `maxItems` | `Infinity` | Máximo de elementos de array, claves de objeto y entradas de Map o Set copiados por contenedor. |
|
|
92
|
+
| `stack` | `true` | Incluir stack traces. Pasa `false` antes de enviar errores a clientes no confiables. |
|
|
93
|
+
| `toJSON` | `true` | Respetar los métodos `toJSON()`. En un error, el objeto devuelto reemplaza las propiedades propias enumerables. |
|
|
94
|
+
| `classes` | `[]` | Clases de error extra reconocidas solo en esta llamada. |
|
|
95
|
+
|
|
96
|
+
Un límite negativo o no numérico lanza un `RangeError`; cualquier cosa en `classes` que no sea una clase con nombre lanza un `TypeError`. Son errores de programación, no problemas de la entrada.
|
|
97
|
+
|
|
98
|
+
### `deserialize(data, options?)`
|
|
99
|
+
|
|
100
|
+
Reconstruye un valor producido por `serialize()`. Los errores vuelven como objetos de error reales, con el prototipo correcto. Los constructores nunca se ejecutan, así que los argumentos obligatorios del constructor no importan. Las clases desconocidas vuelven como la clase conocida más cercana (normalmente `Error`) con el `name` original. Nunca lanza excepciones ante entradas hostiles.
|
|
101
|
+
|
|
102
|
+
| opción | por defecto | significado |
|
|
103
|
+
| --- | --- | --- |
|
|
104
|
+
| `maxDepth` | `256` | Límite de anidamiento. Los valores más profundos pasan a ser `undefined`. Mantenlo al menos tan alto como el `maxDepth` del serializador. |
|
|
105
|
+
| `classes` | `[]` | Clases de error extra reconocidas solo en esta llamada. |
|
|
106
|
+
|
|
107
|
+
### `register(ErrorClass, name?)`
|
|
108
|
+
|
|
109
|
+
Registra una clase de error propia con el nombre `name` (por defecto, el nombre de la clase) para que `deserialize()` pueda reconstruir sus instancias. Devuelve la clase. Registra las mismas clases en ambos lados. Los errores nativos siempre se conocen: `Error`, `TypeError`, `RangeError`, `ReferenceError`, `SyntaxError`, `EvalError`, `URIError`, `AggregateError`, `SuppressedError` (donde exista) y `DOMException`.
|
|
110
|
+
|
|
111
|
+
### `unregister(classOrName)`
|
|
112
|
+
|
|
113
|
+
Quita una clase registrada, por clase o por nombre. Devuelve `true` cuando se quitó algo.
|
|
114
|
+
|
|
115
|
+
### `isError(value)`
|
|
116
|
+
|
|
117
|
+
`true` para objetos de error reales, los que tienen la ranura interna `[[ErrorData]]`, incluidos los errores de otros realms como contextos `node:vm` e iframes. Usa el [`Error.isError`](https://tc39.es/proposal-is-error/) nativo cuando el runtime lo tiene. El fallback comprueba `Object.prototype.toString` cuando el valor no tiene un `Symbol.toStringTag` propio de tipo string y, si no, recurre a `structuredClone`, que solo clona como errores a los errores reales. Los objetos que solo heredan de `Error.prototype` no son errores.
|
|
118
|
+
|
|
119
|
+
## El formato en la red
|
|
120
|
+
|
|
121
|
+
Un error se convierte en un objeto con `$error` (la clave del registro), `name`, `message`, `stack` y solo los campos que realmente tenía:
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{
|
|
125
|
+
"$error": "HttpError",
|
|
126
|
+
"name": "HttpError",
|
|
127
|
+
"message": "checkout failed",
|
|
128
|
+
"stack": "HttpError: checkout failed\n at ...",
|
|
129
|
+
"cause": { "$error": "TypeError", "name": "TypeError", "message": "fetch failed", "stack": "..." },
|
|
130
|
+
"props": { "name": "HttpError", "status": 502 }
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
- `cause`, `errors` (AggregateError), `error` y `suppressed` (SuppressedError) solo se escriben cuando son propiedades propias del error.
|
|
135
|
+
- `props` guarda las propiedades propias enumerables, o el resultado de `toJSON()`.
|
|
136
|
+
- `code` se escribe en DOMException para que sea legible; a la vuelta, el name decide el code.
|
|
137
|
+
- Los valores que JSON no puede representar pasan a ser pequeños registros: `{ "$value": "undefined" }`, `NaN`, `Infinity`, `-Infinity`, `-0`, `bigint`, `Date`, `RegExp`, `Map` y `Set`.
|
|
138
|
+
- Los ciclos y las referencias compartidas pasan a ser `{ "$ref": n }`, donde `n` es la posición del contenedor de destino en un recorrido en profundidad. Vuelven con la misma identidad.
|
|
139
|
+
- Un objeto plano cuyas claves coinciden con estas marcas se envuelve en `{ "$escape": ... }`, así los datos nunca se convierten en un error por accidente.
|
|
140
|
+
- Las funciones pasan a ser `"[Function: name]"` y los símbolos `"Symbol(description)"`.
|
|
141
|
+
|
|
142
|
+
## Notas de comportamiento
|
|
143
|
+
|
|
144
|
+
- Las propiedades propias enumerables vuelven enumerables; `message`, `stack`, `cause`, `errors`, `error` y `suppressed` vuelven no enumerables, como las crea el lenguaje ([ECMA-262 InstallErrorCause](https://tc39.es/ecma262/#sec-installerrorcause), [AggregateError](https://tc39.es/ecma262/#sec-aggregate-error-objects)).
|
|
145
|
+
- Un error que nunca tuvo stack vuelve sin stack; el error reconstruido nunca recibe un stack nuevo del lugar donde se ejecutó `deserialize`.
|
|
146
|
+
- Los getters que lanzan excepciones, los proxies revocados y las trampas de prototipo se omiten, nunca terminan en una excepción. Un getter de `message` que lanza se convierte en un mensaje ausente.
|
|
147
|
+
- Las claves `__proto__` se guardan y se restauran como datos normales con `Object.defineProperty`, así que no pueden cambiar un prototipo.
|
|
148
|
+
- Un string lanzado vuelve como el mismo string. Nada se envuelve en un error falso.
|
|
149
|
+
|
|
150
|
+
## Comparado con structuredClone
|
|
151
|
+
|
|
152
|
+
Comprobado en Node 24 por `test/structured-clone.test.js`.
|
|
153
|
+
|
|
154
|
+
| Tras la ida y vuelta | faultferry | structuredClone |
|
|
155
|
+
| --- | --- | --- |
|
|
156
|
+
| Salida | Valor apto para JSON, cualquier transporte | Solo canales de clonación estructurada, sin texto |
|
|
157
|
+
| Instancia de clase propia | La misma clase (registrada) | `Error` a secas |
|
|
158
|
+
| `errors` de AggregateError | Se conserva | Se pierde, vuelve como `Error` |
|
|
159
|
+
| SuppressedError | Se conserva | Se pierde |
|
|
160
|
+
| Propiedades propias (`status`, `code`) | Se conservan | Se descartan |
|
|
161
|
+
| cause circular | Se conserva | Se conserva |
|
|
162
|
+
| name y code de DOMException | Se conservan | Se conservan |
|
|
163
|
+
| Función en una cause o prop | Pasa a ser `"[Function: name]"` | Lanza `DataCloneError` |
|
|
164
|
+
| Proxy en cualquier parte del grafo | Se lee con seguridad o se omite | Lanza `DataCloneError` |
|
|
165
|
+
| Getter de `message` que lanza | Se omite | Lanza excepción |
|
|
166
|
+
|
|
167
|
+
## ¿Por qué no serialize-error?
|
|
168
|
+
|
|
169
|
+
serialize-error es el paquete veterano para esta tarea. faultferry toma decisiones distintas, todas comprobadas con serialize-error 13.1.0 en Node 24 en una carpeta de pruebas:
|
|
170
|
+
|
|
171
|
+
- Allí una cause circular se convierte en el string `"[Circular]"`; aquí se restaura como el mismo objeto.
|
|
172
|
+
- Allí las referencias compartidas se duplican; aquí conservan su identidad.
|
|
173
|
+
- Allí un DOMException vuelve como un Error a secas con `name` y `code`; aquí es un DOMException.
|
|
174
|
+
- Allí se pierden `error` y `suppressed` de SuppressedError; aquí se conservan.
|
|
175
|
+
- Allí los strings lanzados se envuelven en `NonError`; aquí siguen siendo strings. Allí `undefined` se descarta, `NaN` pasa a ser `null`, BigInt pasa a ser `"10n"` y Date pasa a ser string; aquí vuelven como los mismos valores.
|
|
176
|
+
- Un getter de propiedad propia que lanza, o un proxy revocado, hace que serialize-error lance una excepción; faultferry nunca lanza por culpa de la entrada.
|
|
177
|
+
- Las clases propias necesitan `addKnownErrorConstructor` allí y `register` aquí; ambas formas funcionan.
|
|
178
|
+
|
|
179
|
+
serialize-error tiene muchos más usuarios y una trayectoria más larga. Si su formato de salida ya encaja en tu sistema, es una buena elección.
|
|
180
|
+
|
|
181
|
+
## Benchmarks
|
|
182
|
+
|
|
183
|
+
`npm run bench`, operaciones por segundo, mediana de cinco ejecuciones, más es mejor. Node 24.16.0, AMD Ryzen 7 7800X3D, Windows x64, 2026-12-04.
|
|
184
|
+
|
|
185
|
+
| caso | faultferry serialize | serialize-error serialize | faultferry deserialize | serialize-error deserialize | structuredClone (sin JSON) |
|
|
186
|
+
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
187
|
+
| simple TypeError | 1.65M | 893k | 548k | 143k | 697k |
|
|
188
|
+
| cause chain x6 | 319k | 160k | 98k | 10k | 193k |
|
|
189
|
+
| error with props | 821k | 426k | 313k | 121k | 757k |
|
|
190
|
+
| AggregateError x20 | 68k | 40k | 22k | 3k | 638k |
|
|
191
|
+
|
|
192
|
+
Serialize incluye `JSON.stringify`; deserialize incluye `JSON.parse`. structuredClone no produce JSON y descarta los miembros de AggregateError, por eso es tan rápido en ese caso. serialize-error se instala solo para el benchmark y no es una dependencia.
|
|
193
|
+
|
|
194
|
+
## Tamaño
|
|
195
|
+
|
|
196
|
+
4.7 kB con gzip, sin comentarios ni espacios (7.0 kB con gzip tal como se publica, con JSDoc). `npm run size` muestra las cifras. Cero dependencias en tiempo de ejecución, `sideEffects: false`.
|
|
197
|
+
|
|
198
|
+
## Compatibilidad
|
|
199
|
+
|
|
200
|
+
Node.js 18 o posterior (probado con 18, 20, 22 y 24 en CI, en Linux, Windows y macOS), Bun y Deno (smoke tests en CI), navegadores modernos, Web Workers y Service Workers. El soporte de `SuppressedError` se activa donde el runtime lo tiene.
|
|
201
|
+
|
|
202
|
+
## Preguntas frecuentes
|
|
203
|
+
|
|
204
|
+
**¿Por qué `JSON.stringify(error)` devuelve `{}`?** `message`, `stack` y `cause` son propiedades propias no enumerables, y `JSON.stringify` solo escribe las enumerables. `serialize(error)` copia antes esos campos a un objeto plano, y `deserialize` convierte ese objeto otra vez en un error real.
|
|
205
|
+
|
|
206
|
+
**¿Es seguro deserializar datos que llegan de la red?** `deserialize` nunca llama a constructores ni a getters de los datos, nunca cambia prototipos y trata las claves `__proto__` como datos normales. Solo construye las clases que registraste. Pasa `stack: false` al serializar para clientes no confiables.
|
|
207
|
+
|
|
208
|
+
**¿Qué pasa con una clase propia sin registrar?** Viaja como su ancestro conocido más cercano y conserva el nombre, así que un `HttpError` sin registrar vuelve como un `Error` llamado `HttpError` con todas sus propiedades.
|
|
209
|
+
|
|
210
|
+
**¿Funciona con errores de `node:vm` o de iframes?** Sí. Las clases nativas de otro realm se reconocen por su nombre, e `isError` comprueba la ranura interna de error en lugar de `instanceof`.
|
|
211
|
+
|
|
212
|
+
**¿Puedo usarlo con `postMessage` sin JSON?** Sí. La salida de `serialize` es un valor plano, así que puede pasar directamente por `postMessage` o `structuredClone`.
|
|
213
|
+
|
|
214
|
+
## Sitio web
|
|
215
|
+
|
|
216
|
+
El sitio de `docs/` lo genera `scripts/build-site.mjs` a partir de `site/`. Hecho con [Monsoon](https://github.com/kwy404/monsoon), [Voodoo.js](https://github.com/kwy404/Voodoo.js) y [glyphfox](https://github.com/kwy404/glyphfox). Ejecuta `npm run site` y `npm run serve` para verlo en local.
|
|
217
|
+
|
|
218
|
+
## Licencia
|
|
219
|
+
|
|
220
|
+
[MIT](LICENSE), Alexandre Kohler.
|
package/README.ja.md
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
<picture>
|
|
2
|
+
<source media="(prefers-color-scheme: dark)" srcset="assets/banner-dark.svg">
|
|
3
|
+
<img alt="faultferry: エラーをプロセス間で送り、そのままの形で受け取る" src="assets/banner-light.svg" width="100%">
|
|
4
|
+
</picture>
|
|
5
|
+
|
|
6
|
+
[English](README.md) | [Português (Brasil)](README.pt.md) | [Español](README.es.md) | **日本語**
|
|
7
|
+
|
|
8
|
+
[](https://github.com/kwy404/faultferry/actions/workflows/ci.yml)
|
|
9
|
+
[](https://www.npmjs.com/package/faultferry)
|
|
10
|
+
[](#サイズ)
|
|
11
|
+
[](package.json)
|
|
12
|
+
[](index.d.ts)
|
|
13
|
+
[](LICENSE)
|
|
14
|
+
|
|
15
|
+
**JavaScript のエラーをプレーンな JSON にシリアライズし、正確に元へ戻します。** faultferry はクラス、メッセージ、stack、cause チェーン (循環を含む)、AggregateError、SuppressedError、DOMException、独自のエラークラス、エラー以外の throw された値を保つので、エラーをプロセス間で送り、そのままの形で受け取れます。
|
|
16
|
+
|
|
17
|
+
`JSON.stringify(new Error('boom'))` の結果は `{}` です。Worker、子プロセス、HTTP、メッセージキューはデータを運ぶだけでエラーは運ばないため、クラスも cause チェーンも独自フィールドも途中で失われます。faultferry は throw されたあらゆる値をプレーンな JSON に変換し、受け取った側で組み立て直します。クラス、メッセージ、stack、cause チェーン (循環を含む)、AggregateError のメンバー、SuppressedError のフィールド、DOMException の name と code、独自プロパティがそのまま戻ります。悪意のある入力でも例外を投げず、依存関係もありません。
|
|
18
|
+
|
|
19
|
+
Web サイトとライブプレイグラウンド: https://kwy404.github.io/faultferry/ja/
|
|
20
|
+
|
|
21
|
+
## インストール
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
npm i faultferry
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
ESM と CommonJS のビルド、手書きの TypeScript 型定義付き。Node.js 18 以降、Bun、Deno、モダンブラウザで動きます。
|
|
28
|
+
|
|
29
|
+
## クイックスタート
|
|
30
|
+
|
|
31
|
+
```js
|
|
32
|
+
import { serialize, deserialize, register } from 'faultferry';
|
|
33
|
+
|
|
34
|
+
class HttpError extends Error {
|
|
35
|
+
constructor(message, status, options) {
|
|
36
|
+
super(message, options);
|
|
37
|
+
this.name = 'HttpError';
|
|
38
|
+
this.status = status;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
register(HttpError); // 送る側と受け取る側の両方で
|
|
42
|
+
|
|
43
|
+
const error = new HttpError('checkout failed', 502, { cause: new TypeError('fetch failed') });
|
|
44
|
+
|
|
45
|
+
const wire = JSON.stringify(serialize(error));
|
|
46
|
+
const back = deserialize(JSON.parse(wire));
|
|
47
|
+
|
|
48
|
+
back instanceof HttpError; // true
|
|
49
|
+
back.status; // 502
|
|
50
|
+
back.cause instanceof TypeError; // true
|
|
51
|
+
back.stack === error.stack; // true
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Worker をまたぐ場合:
|
|
55
|
+
|
|
56
|
+
```js
|
|
57
|
+
// worker.js
|
|
58
|
+
self.onmessage = async ({ data }) => {
|
|
59
|
+
try {
|
|
60
|
+
postMessage({ ok: true, value: await run(data) });
|
|
61
|
+
} catch (error) {
|
|
62
|
+
postMessage({ ok: false, error: serialize(error) });
|
|
63
|
+
}
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// main.js
|
|
67
|
+
worker.onmessage = ({ data }) => {
|
|
68
|
+
if (!data.ok) throw deserialize(data.error);
|
|
69
|
+
};
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
サーバーからブラウザへ、スタックトレースを漏らさずに送る場合:
|
|
73
|
+
|
|
74
|
+
```js
|
|
75
|
+
app.use((error, req, res, next) => {
|
|
76
|
+
res.status(error.status ?? 500).json(serialize(error, { stack: false, maxDepth: 8 }));
|
|
77
|
+
});
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
## API
|
|
81
|
+
|
|
82
|
+
### `serialize(value, options?)`
|
|
83
|
+
|
|
84
|
+
任意の値 (通常は throw されたもの) を、`JSON.stringify`、`postMessage`、`structuredClone` がそのまま受け付けるプレーンな値に変換します。悪意のある入力でも例外を投げません。
|
|
85
|
+
|
|
86
|
+
| オプション | 既定値 | 意味 |
|
|
87
|
+
| --- | --- | --- |
|
|
88
|
+
| `maxDepth` | `32` | ネストの上限。それより深いコンテナは `"[Object]"`、`"[Array]"`、`"[Map]"`、`"[Set]"` になり、深いエラーはクラス、name、message だけを残します。 |
|
|
89
|
+
| `maxNodes` | `10000` | 同じ切り詰めが始まるまでにコピーするコンテナとエラーの総数。 |
|
|
90
|
+
| `maxLength` | `Infinity` | 残す文字列の最大長。長い文字列は切り詰められ、末尾が `...` になります。 |
|
|
91
|
+
| `maxItems` | `Infinity` | コンテナごとにコピーする配列要素、オブジェクトのキー、Map や Set のエントリの最大数。 |
|
|
92
|
+
| `stack` | `true` | スタックトレースを含めるかどうか。信頼できないクライアントにエラーを送る前には `false` を渡してください。 |
|
|
93
|
+
| `toJSON` | `true` | `toJSON()` メソッドを尊重するかどうか。エラーの場合、返されたオブジェクトが列挙可能な独自プロパティの代わりになります。 |
|
|
94
|
+
| `classes` | `[]` | この呼び出しでのみ認識する追加のエラークラス。 |
|
|
95
|
+
|
|
96
|
+
負の値や数値でない上限は `RangeError` を投げ、`classes` に名前付きクラス以外が含まれると `TypeError` を投げます。これらは入力の問題ではなく、プログラムの誤りです。
|
|
97
|
+
|
|
98
|
+
### `deserialize(data, options?)`
|
|
99
|
+
|
|
100
|
+
`serialize()` が作った値を組み立て直します。エラーは正しいプロトタイプを持つ本物のエラーオブジェクトとして戻ります。コンストラクタは呼ばれないため、必須の引数があっても問題ありません。未知のクラスは、最も近い既知のクラス (通常は `Error`) として元の `name` を持って戻ります。悪意のある入力でも例外を投げません。
|
|
101
|
+
|
|
102
|
+
| オプション | 既定値 | 意味 |
|
|
103
|
+
| --- | --- | --- |
|
|
104
|
+
| `maxDepth` | `256` | ネストの上限。それより深い値は `undefined` になります。シリアライズ側の `maxDepth` 以上にしておいてください。 |
|
|
105
|
+
| `classes` | `[]` | この呼び出しでのみ認識する追加のエラークラス。 |
|
|
106
|
+
|
|
107
|
+
### `register(ErrorClass, name?)`
|
|
108
|
+
|
|
109
|
+
独自のエラークラスを `name` (既定ではクラス名) で登録し、`deserialize()` がそのインスタンスを組み立て直せるようにします。戻り値はクラス自身です。送る側と受け取る側で同じクラスを登録してください。組み込みのエラーは常に認識されます: `Error`、`TypeError`、`RangeError`、`ReferenceError`、`SyntaxError`、`EvalError`、`URIError`、`AggregateError`、`SuppressedError` (存在する環境のみ)、`DOMException`。
|
|
110
|
+
|
|
111
|
+
### `unregister(classOrName)`
|
|
112
|
+
|
|
113
|
+
登録したクラスを、クラスまたは名前で削除します。何かを削除したときは `true` を返します。
|
|
114
|
+
|
|
115
|
+
### `isError(value)`
|
|
116
|
+
|
|
117
|
+
内部スロット `[[ErrorData]]` を持つ本物のエラーオブジェクトなら `true` を返します。`node:vm` のコンテキストや iframe など、別の realm から来たエラーにも対応します。ランタイムにネイティブの [`Error.isError`](https://tc39.es/proposal-is-error/) があればそれを使います。フォールバックでは、値が文字列型の独自 `Symbol.toStringTag` を持たない場合は `Object.prototype.toString` を確認し、持つ場合は本物のエラーだけをエラーとして複製する `structuredClone` に判定を任せます。`Error.prototype` を継承しているだけのオブジェクトはエラーではありません。
|
|
118
|
+
|
|
119
|
+
## 転送フォーマット
|
|
120
|
+
|
|
121
|
+
エラーは `$error` (登録キー)、`name`、`message`、`stack` と、実際に持っていたフィールドだけを持つオブジェクトになります:
|
|
122
|
+
|
|
123
|
+
```json
|
|
124
|
+
{
|
|
125
|
+
"$error": "HttpError",
|
|
126
|
+
"name": "HttpError",
|
|
127
|
+
"message": "checkout failed",
|
|
128
|
+
"stack": "HttpError: checkout failed\n at ...",
|
|
129
|
+
"cause": { "$error": "TypeError", "name": "TypeError", "message": "fetch failed", "stack": "..." },
|
|
130
|
+
"props": { "name": "HttpError", "status": 502 }
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
- `cause`、`errors` (AggregateError)、`error` と `suppressed` (SuppressedError) は、エラー自身の独自プロパティである場合にだけ書き出されます。
|
|
135
|
+
- `props` には列挙可能な独自プロパティ、または `toJSON()` の結果が入ります。
|
|
136
|
+
- DOMException では読みやすさのために `code` を書き出しますが、復元時の code は name で決まります。
|
|
137
|
+
- JSON で表せない値は小さなレコードになります: `{ "$value": "undefined" }`、`NaN`、`Infinity`、`-Infinity`、`-0`、`bigint`、`Date`、`RegExp`、`Map`、`Set`。
|
|
138
|
+
- 循環参照と共有参照は `{ "$ref": n }` になります。`n` は深さ優先でたどったときの参照先コンテナの位置です。復元すると同じ同一性を持ちます。
|
|
139
|
+
- キーがこれらの目印と重なるプレーンなオブジェクトは `{ "$escape": ... }` で包まれるため、データが誤ってエラーになることはありません。
|
|
140
|
+
- 関数は `"[Function: name]"`、シンボルは `"Symbol(description)"` になります。
|
|
141
|
+
|
|
142
|
+
## 動作に関する注意
|
|
143
|
+
|
|
144
|
+
- 列挙可能な独自プロパティは列挙可能なまま戻り、`message`、`stack`、`cause`、`errors`、`error`、`suppressed` は言語が作るときと同じく列挙不可で戻ります ([ECMA-262 InstallErrorCause](https://tc39.es/ecma262/#sec-installerrorcause)、[AggregateError](https://tc39.es/ecma262/#sec-aggregate-error-objects))。
|
|
145
|
+
- もともと stack を持たないエラーは stack なしで戻ります。`deserialize` を実行した場所の新しい stack が付くことはありません。
|
|
146
|
+
- 例外を投げる getter、無効化された Proxy、プロトタイプのトラップはスキップされ、例外にはなりません。例外を投げる `message` の getter は、message がないものとして扱われます。
|
|
147
|
+
- `__proto__` キーは `Object.defineProperty` で普通のデータとして保存、復元されるため、プロトタイプを書き換えることはできません。
|
|
148
|
+
- throw された文字列は同じ文字列として戻ります。偽のエラーで包むことはしません。
|
|
149
|
+
|
|
150
|
+
## structuredClone との比較
|
|
151
|
+
|
|
152
|
+
Node 24 上で `test/structured-clone.test.js` によって確認しています。
|
|
153
|
+
|
|
154
|
+
| 往復したあと | faultferry | structuredClone |
|
|
155
|
+
| --- | --- | --- |
|
|
156
|
+
| 出力 | JSON として安全な値、どんな経路でも可 | 構造化複製のチャネルのみ、テキストにならない |
|
|
157
|
+
| 独自クラスのインスタンス | 同じクラス (登録済みの場合) | ただの `Error` |
|
|
158
|
+
| AggregateError の `errors` | 保持 | 失われ、`Error` として戻る |
|
|
159
|
+
| SuppressedError | 保持 | 失われる |
|
|
160
|
+
| 独自プロパティ (`status`、`code`) | 保持 | 捨てられる |
|
|
161
|
+
| 循環する cause | 保持 | 保持 |
|
|
162
|
+
| DOMException の name と code | 保持 | 保持 |
|
|
163
|
+
| cause やプロパティ内の関数 | `"[Function: name]"` になる | `DataCloneError` を投げる |
|
|
164
|
+
| グラフ内の Proxy | 安全に読むかスキップ | `DataCloneError` を投げる |
|
|
165
|
+
| 例外を投げる `message` の getter | スキップ | 例外を投げる |
|
|
166
|
+
|
|
167
|
+
## serialize-error ではだめなの?
|
|
168
|
+
|
|
169
|
+
serialize-error はこの用途で長く使われてきたパッケージです。faultferry は異なる選択をしています。以下はすべて、作業用フォルダで Node 24 と serialize-error 13.1.0 を使って確認しました:
|
|
170
|
+
|
|
171
|
+
- あちらでは循環する cause は文字列 `"[Circular]"` になりますが、こちらでは同じオブジェクトとして復元されます。
|
|
172
|
+
- あちらでは共有参照は複製されますが、こちらでは同一性が保たれます。
|
|
173
|
+
- あちらでは DOMException は `name` と `code` を持つただの Error として戻りますが、こちらでは DOMException のままです。
|
|
174
|
+
- あちらでは SuppressedError の `error` と `suppressed` が失われますが、こちらでは保持されます。
|
|
175
|
+
- あちらでは throw された文字列は `NonError` で包まれますが、こちらでは文字列のままです。あちらでは `undefined` は捨てられ、`NaN` は `null` に、BigInt は `"10n"` に、Date は文字列になりますが、こちらでは同じ値として戻ります。
|
|
176
|
+
- 例外を投げる独自プロパティの getter や無効化された Proxy があると serialize-error は例外を投げますが、faultferry は入力が原因で例外を投げることはありません。
|
|
177
|
+
- 独自クラスには、あちらでは `addKnownErrorConstructor`、こちらでは `register` が必要です。どちらも機能します。
|
|
178
|
+
|
|
179
|
+
serialize-error のほうが利用者がはるかに多く、実績も長いです。その出力フォーマットがすでにシステムに合っているなら、十分によい選択です。
|
|
180
|
+
|
|
181
|
+
## ベンチマーク
|
|
182
|
+
|
|
183
|
+
`npm run bench`、1 秒あたりの操作回数、5 回計測した中央値、大きいほど高速です。Node 24.16.0、AMD Ryzen 7 7800X3D、Windows x64、2026-12-04。
|
|
184
|
+
|
|
185
|
+
| ケース | faultferry serialize | serialize-error serialize | faultferry deserialize | serialize-error deserialize | structuredClone (JSON なし) |
|
|
186
|
+
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
187
|
+
| simple TypeError | 1.65M | 893k | 548k | 143k | 697k |
|
|
188
|
+
| cause chain x6 | 319k | 160k | 98k | 10k | 193k |
|
|
189
|
+
| error with props | 821k | 426k | 313k | 121k | 757k |
|
|
190
|
+
| AggregateError x20 | 68k | 40k | 22k | 3k | 638k |
|
|
191
|
+
|
|
192
|
+
serialize には `JSON.stringify`、deserialize には `JSON.parse` が含まれます。structuredClone は JSON を出力せず AggregateError のメンバーも捨てるため、そのケースでは非常に速くなります。serialize-error はベンチマークのためだけにインストールしており、依存関係ではありません。
|
|
193
|
+
|
|
194
|
+
## サイズ
|
|
195
|
+
|
|
196
|
+
コメントと空白を除去して gzip 後 4.7 kB (JSDoc を含む公開時のファイルは gzip 後 7.0 kB)。`npm run size` で数値を確認できます。ランタイム依存関係はゼロ、`sideEffects: false` です。
|
|
197
|
+
|
|
198
|
+
## 互換性
|
|
199
|
+
|
|
200
|
+
Node.js 18 以降 (CI で 18、20、22、24 を Linux、Windows、macOS 上でテスト)、Bun と Deno (CI でスモークテスト)、モダンブラウザ、Web Worker、Service Worker。`SuppressedError` への対応は、ランタイムがサポートしている場合に有効になります。
|
|
201
|
+
|
|
202
|
+
## よくある質問
|
|
203
|
+
|
|
204
|
+
**`JSON.stringify(error)` が `{}` になるのはなぜ?** `message`、`stack`、`cause` は列挙可能ではない独自プロパティで、`JSON.stringify` は列挙可能なプロパティしか書き出さないからです。`serialize(error)` はそれらのフィールドを先にプレーンなオブジェクトへコピーし、`deserialize` がそのオブジェクトを本物のエラーに戻します。
|
|
205
|
+
|
|
206
|
+
**ネットワークから来たデータを deserialize しても安全?** `deserialize` はデータ内のコンストラクタや getter を呼ばず、プロトタイプも書き換えず、`__proto__` キーはただのデータとして扱います。組み立てるのは登録したクラスだけです。信頼できないクライアント向けにシリアライズするときは `stack: false` を渡してください。
|
|
207
|
+
|
|
208
|
+
**登録していない独自クラスはどうなる?** 最も近い既知の祖先クラスとして運ばれ、名前は保たれます。登録していない `HttpError` は、`HttpError` という名前を持ち、すべてのプロパティを備えた `Error` として戻ります。
|
|
209
|
+
|
|
210
|
+
**`node:vm` や iframe のエラーにも使える?** はい。別の realm のネイティブクラスは名前で認識され、`isError` は `instanceof` ではなく内部のエラースロットを調べます。
|
|
211
|
+
|
|
212
|
+
**JSON を使わずに `postMessage` で送れる?** はい。`serialize` の出力はプレーンな値なので、そのまま `postMessage` や `structuredClone` に渡せます。
|
|
213
|
+
|
|
214
|
+
## Web サイト
|
|
215
|
+
|
|
216
|
+
`docs/` の Web サイトは、`site/` をもとに `scripts/build-site.mjs` で生成しています。[Monsoon](https://github.com/kwy404/monsoon)、[Voodoo.js](https://github.com/kwy404/Voodoo.js)、[glyphfox](https://github.com/kwy404/glyphfox) で構築。`npm run site` と `npm run serve` でプレビューできます。
|
|
217
|
+
|
|
218
|
+
## ライセンス
|
|
219
|
+
|
|
220
|
+
[MIT](LICENSE)、Alexandre Kohler.
|