@velajs/errors 1.0.0 → 1.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/CHANGELOG.md +12 -0
- package/README.md +25 -0
- package/dist/fingerprint.d.ts +61 -0
- package/dist/fingerprint.js +169 -0
- package/dist/fingerprint.js.map +1 -0
- package/dist/index.d.ts +179 -11
- package/dist/index.js +197 -6
- package/dist/index.js.map +1 -0
- package/package.json +50 -34
- package/dist/catalog-data.d.ts +0 -76
- package/dist/catalog-data.js +0 -67
- package/dist/catalog.d.ts +0 -15
- package/dist/catalog.js +0 -37
- package/dist/error.d.ts +0 -27
- package/dist/error.js +0 -27
- package/dist/guard.d.ts +0 -16
- package/dist/guard.js +0 -11
- package/dist/invariant.d.ts +0 -3
- package/dist/invariant.js +0 -17
- package/dist/to-error-body.d.ts +0 -34
- package/dist/to-error-body.js +0 -50
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 1.1.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- ac4e9f8: Add the `@velajs/errors/fingerprint` subpath: a zero-dependency, cross-runtime error-grouping hash. `fingerprintError({ functionPath, message, code? })` returns a stable 16-hex-char digest over `functionPath` plus a normalized message bucket — `code` is metadata and never hashed, so redacted wire errors and raw server-side errors group identically. Ships `bucketMessage` (strips URLs, UUIDs, IPs, ids, paths, timestamps; ReDoS-clamped), `FINGERPRINT_VERSION` for persisted-fingerprint migrations, and a portable synchronous `sha256Hex` (content-addressing only, never a security primitive). Grouping approach inspired by @superlog/fingerprint (Apache-2.0), independently implemented.
|
|
8
|
+
|
|
9
|
+
## 1.0.1
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- 49f72ad: Modernize the package build, validation, and release toolchain.
|
|
14
|
+
|
|
3
15
|
All notable changes to `@velajs/errors` are documented here. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
4
16
|
|
|
5
17
|
## 1.0.0
|
package/README.md
CHANGED
|
@@ -73,6 +73,30 @@ return Response.json(body, { status });
|
|
|
73
73
|
|
|
74
74
|
`invariant(condition, message, data?)` narrows types (`asserts condition`) and, on failure, throws an `internal`-coded `VelaError` — always redacted by rule 2. `unreachable(value: never)` is its exhaustiveness-check companion.
|
|
75
75
|
|
|
76
|
+
## Error fingerprinting (`@velajs/errors/fingerprint`)
|
|
77
|
+
|
|
78
|
+
A separate, tree-shakeable subpath that turns noisy repeats of the same error into one stable **issue** identity. It is zero-dependency and computes identically in the browser, the workerd runtime, and Node, so a live in-flight error and one recomputed later from a persisted log row collapse onto the same fingerprint.
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
import { fingerprintError, bucketMessage, FINGERPRINT_VERSION } from '@velajs/errors/fingerprint';
|
|
82
|
+
|
|
83
|
+
// 16-hex-char stable grouping id over functionPath :: bucket(message).
|
|
84
|
+
fingerprintError({ functionPath: 'orders:get', message: 'order 550e8400-… not found' });
|
|
85
|
+
|
|
86
|
+
// The `code` is metadata and is NEVER hashed — the redacted wire view (whose
|
|
87
|
+
// code toErrorBody may rewrite or drop) and the raw server-side error group
|
|
88
|
+
// together. It also works straight off toErrorBody's output:
|
|
89
|
+
const { body } = toErrorBody(err);
|
|
90
|
+
fingerprintError({ functionPath, message: body.error.message, code: body.error.code });
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
- **`fingerprintError({ functionPath, message, code? }): string`** — the stable 16-hex grouping hash. `code` is display metadata only and is never folded into the hash.
|
|
94
|
+
- **`bucketMessage(message): string`** — the exported normalizer. Strips per-occurrence noise (URLs, request/filesystem paths, UUIDs, IPs, long numeric/hex ids, timestamps, emails) so a route-scanner sweep of 404s with varying paths folds to a single fingerprint. Input is clamped (~1 KB) before any regex runs as a ReDoS guard.
|
|
95
|
+
- **`FINGERPRINT_VERSION`** — bump whenever the bucketer heuristics change; changed heuristics re-partition history, so consumers that persist fingerprints store this alongside each hash to know when a recompute is due.
|
|
96
|
+
- **`sha256Hex(input): string`** — the internal portable synchronous SHA-256 (no `node:crypto`, no async `crypto.subtle`), also exported. **Content-addressing / grouping only — never a security or MAC primitive.**
|
|
97
|
+
|
|
98
|
+
> The message-normalization / grouping approach is inspired by [`@superlog/fingerprint`](https://github.com/superloglabs/superlog) (Apache-2.0). This is an independent, clean-room implementation.
|
|
99
|
+
|
|
76
100
|
## API
|
|
77
101
|
|
|
78
102
|
- `VelaError`, `VelaErrorOptions` — the one error and its constructor options.
|
|
@@ -81,3 +105,4 @@ return Response.json(body, { status });
|
|
|
81
105
|
- `defineErrorCatalog`, `composeCatalogs`, `Catalog`, `ErrorCatalogEntry` — catalog authoring.
|
|
82
106
|
- `CORE_CATALOG`, `CORE_ENTRIES`, `CoreErrorCode`, `STATUS_TO_CODE` — the core catalog and its lookups.
|
|
83
107
|
- `invariant`, `unreachable` — internal-coded assertion helpers.
|
|
108
|
+
- `@velajs/errors/fingerprint`: `fingerprintError`, `ErrorFingerprintInput`, `bucketMessage`, `FINGERPRINT_VERSION`, `sha256Hex` — the error-grouping subpath.
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
//#region src/sha256.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Portable, synchronous SHA-256 (FIPS 180-4) returning a lowercase hex digest.
|
|
4
|
+
*
|
|
5
|
+
* Implemented straight from the published standard so this file carries no
|
|
6
|
+
* runtime dependency and produces byte-for-byte identical output on every
|
|
7
|
+
* target Vela supports — browsers, the Cloudflare Workers (workerd) runtime,
|
|
8
|
+
* and Node. Neither built-in alternative fits the fingerprinter:
|
|
9
|
+
* - `node:crypto` (`createHash`) is absent in browsers and needs
|
|
10
|
+
* `nodejs_compat` to load in workerd.
|
|
11
|
+
* - `crypto.subtle.digest` is async, which is clumsy for folding error rows
|
|
12
|
+
* into a group key one synchronous call at a time.
|
|
13
|
+
*
|
|
14
|
+
* SECURITY: this is a plain, non-constant-time digest meant ONLY for
|
|
15
|
+
* content-addressing and grouping keys. Never use it as a MAC, a password hash,
|
|
16
|
+
* or any other authentication or security primitive.
|
|
17
|
+
*/
|
|
18
|
+
declare const sha256Hex: (input: string) => string;
|
|
19
|
+
//#endregion
|
|
20
|
+
//#region src/fingerprint.d.ts
|
|
21
|
+
/**
|
|
22
|
+
* Heuristic generation of {@link bucketMessage}. Bump it whenever the
|
|
23
|
+
* normalizer's rules change: changed heuristics re-partition history (they may
|
|
24
|
+
* split one group into several or merge several into one), so a consumer that
|
|
25
|
+
* persists fingerprints stores this alongside each hash to know which
|
|
26
|
+
* generation produced it and when a recompute/backfill is due.
|
|
27
|
+
*/
|
|
28
|
+
declare const FINGERPRINT_VERSION: number;
|
|
29
|
+
/**
|
|
30
|
+
* Normalize an error message into its grouping bucket: strip per-occurrence
|
|
31
|
+
* noise (urls, uuids, ips, request/filesystem paths, long ids, numbers) and
|
|
32
|
+
* fold whitespace/case, so occurrences of the same logical error collapse to
|
|
33
|
+
* one bucket. Exported for direct testing of the normalization heuristics.
|
|
34
|
+
*/
|
|
35
|
+
declare const bucketMessage: (message: string) => string;
|
|
36
|
+
/** Everything a fingerprint source can supply. */
|
|
37
|
+
interface ErrorFingerprintInput {
|
|
38
|
+
/**
|
|
39
|
+
* What raised the error — the invoked function/route path, e.g.
|
|
40
|
+
* `messages:list`. Part of the grouping key.
|
|
41
|
+
*/
|
|
42
|
+
functionPath: string;
|
|
43
|
+
/** Human-readable message (may embed user input); normalized into the key. */
|
|
44
|
+
message: string;
|
|
45
|
+
/**
|
|
46
|
+
* Machine error code, when known. Pure metadata: **never folded into the
|
|
47
|
+
* hash**, so the redacted wire error (which may rewrite or drop the code) and
|
|
48
|
+
* the raw server-side error still produce the same fingerprint.
|
|
49
|
+
*/
|
|
50
|
+
code?: string;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Fold an error into its stable 16-hex-character grouping fingerprint. Pure and
|
|
54
|
+
* synchronous, safe to call per row when grouping a log page. The same
|
|
55
|
+
* `functionPath` and logically-equal `message` always yield the same hash
|
|
56
|
+
* regardless of the `code` supplied or per-occurrence noise in the message.
|
|
57
|
+
*/
|
|
58
|
+
declare const fingerprintError: (input: ErrorFingerprintInput) => string;
|
|
59
|
+
//#endregion
|
|
60
|
+
export { ErrorFingerprintInput, FINGERPRINT_VERSION, bucketMessage, fingerprintError, sha256Hex };
|
|
61
|
+
//# sourceMappingURL=fingerprint.d.ts.map
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
//#region src/sha256.ts
|
|
2
|
+
/**
|
|
3
|
+
* Portable, synchronous SHA-256 (FIPS 180-4) returning a lowercase hex digest.
|
|
4
|
+
*
|
|
5
|
+
* Implemented straight from the published standard so this file carries no
|
|
6
|
+
* runtime dependency and produces byte-for-byte identical output on every
|
|
7
|
+
* target Vela supports — browsers, the Cloudflare Workers (workerd) runtime,
|
|
8
|
+
* and Node. Neither built-in alternative fits the fingerprinter:
|
|
9
|
+
* - `node:crypto` (`createHash`) is absent in browsers and needs
|
|
10
|
+
* `nodejs_compat` to load in workerd.
|
|
11
|
+
* - `crypto.subtle.digest` is async, which is clumsy for folding error rows
|
|
12
|
+
* into a group key one synchronous call at a time.
|
|
13
|
+
*
|
|
14
|
+
* SECURITY: this is a plain, non-constant-time digest meant ONLY for
|
|
15
|
+
* content-addressing and grouping keys. Never use it as a MAC, a password hash,
|
|
16
|
+
* or any other authentication or security primitive.
|
|
17
|
+
*/
|
|
18
|
+
const BLOCK_BYTES = 64;
|
|
19
|
+
const ROUND = Uint32Array.of(1116352408, 1899447441, 3049323471, 3921009573, 961987163, 1508970993, 2453635748, 2870763221, 3624381080, 310598401, 607225278, 1426881987, 1925078388, 2162078206, 2614888103, 3248222580, 3835390401, 4022224774, 264347078, 604807628, 770255983, 1249150122, 1555081692, 1996064986, 2554220882, 2821834349, 2952996808, 3210313671, 3336571891, 3584528711, 113926993, 338241895, 666307205, 773529912, 1294757372, 1396182291, 1695183700, 1986661051, 2177026350, 2456956037, 2730485921, 2820302411, 3259730800, 3345764771, 3516065817, 3600352804, 4094571909, 275423344, 430227734, 506948616, 659060556, 883997877, 958139571, 1322822218, 1537002063, 1747873779, 1955562222, 2024104815, 2227730452, 2361852424, 2428436474, 2756734187, 3204031479, 3329325298);
|
|
20
|
+
const rotr = (word, bits) => word >>> bits | word << 32 - bits;
|
|
21
|
+
const toHex8 = (word) => (word >>> 0).toString(16).padStart(8, "0");
|
|
22
|
+
const sha256Hex = (input) => {
|
|
23
|
+
const message = new TextEncoder().encode(input);
|
|
24
|
+
const bitLength = message.length * 8;
|
|
25
|
+
const totalBytes = (Math.floor((message.length + 8) / BLOCK_BYTES) + 1) * BLOCK_BYTES;
|
|
26
|
+
const padded = new Uint8Array(totalBytes);
|
|
27
|
+
padded.set(message);
|
|
28
|
+
padded[message.length] = 128;
|
|
29
|
+
const frame = new DataView(padded.buffer);
|
|
30
|
+
frame.setUint32(totalBytes - 8, Math.floor(bitLength / 4294967296), false);
|
|
31
|
+
frame.setUint32(totalBytes - 4, bitLength >>> 0, false);
|
|
32
|
+
let h0 = 1779033703;
|
|
33
|
+
let h1 = 3144134277;
|
|
34
|
+
let h2 = 1013904242;
|
|
35
|
+
let h3 = 2773480762;
|
|
36
|
+
let h4 = 1359893119;
|
|
37
|
+
let h5 = 2600822924;
|
|
38
|
+
let h6 = 528734635;
|
|
39
|
+
let h7 = 1541459225;
|
|
40
|
+
const schedule = /* @__PURE__ */ new Uint32Array(64);
|
|
41
|
+
for (let base = 0; base < totalBytes; base += BLOCK_BYTES) {
|
|
42
|
+
for (let t = 0; t < 16; t += 1) schedule[t] = frame.getUint32(base + t * 4, false);
|
|
43
|
+
for (let t = 16; t < 64; t += 1) {
|
|
44
|
+
const x = schedule[t - 15];
|
|
45
|
+
const y = schedule[t - 2];
|
|
46
|
+
const sigma0 = rotr(x, 7) ^ rotr(x, 18) ^ x >>> 3;
|
|
47
|
+
const sigma1 = rotr(y, 17) ^ rotr(y, 19) ^ y >>> 10;
|
|
48
|
+
schedule[t] = schedule[t - 16] + sigma0 + schedule[t - 7] + sigma1 >>> 0;
|
|
49
|
+
}
|
|
50
|
+
let a = h0;
|
|
51
|
+
let b = h1;
|
|
52
|
+
let c = h2;
|
|
53
|
+
let d = h3;
|
|
54
|
+
let e = h4;
|
|
55
|
+
let f = h5;
|
|
56
|
+
let g = h6;
|
|
57
|
+
let h = h7;
|
|
58
|
+
for (let t = 0; t < 64; t += 1) {
|
|
59
|
+
const bigSigma1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
60
|
+
const choose = e & f ^ ~e & g;
|
|
61
|
+
const t1 = h + bigSigma1 + choose + ROUND[t] + schedule[t] >>> 0;
|
|
62
|
+
const t2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
|
|
63
|
+
h = g;
|
|
64
|
+
g = f;
|
|
65
|
+
f = e;
|
|
66
|
+
e = d + t1 >>> 0;
|
|
67
|
+
d = c;
|
|
68
|
+
c = b;
|
|
69
|
+
b = a;
|
|
70
|
+
a = t1 + t2 >>> 0;
|
|
71
|
+
}
|
|
72
|
+
h0 = h0 + a >>> 0;
|
|
73
|
+
h1 = h1 + b >>> 0;
|
|
74
|
+
h2 = h2 + c >>> 0;
|
|
75
|
+
h3 = h3 + d >>> 0;
|
|
76
|
+
h4 = h4 + e >>> 0;
|
|
77
|
+
h5 = h5 + f >>> 0;
|
|
78
|
+
h6 = h6 + g >>> 0;
|
|
79
|
+
h7 = h7 + h >>> 0;
|
|
80
|
+
}
|
|
81
|
+
return toHex8(h0) + toHex8(h1) + toHex8(h2) + toHex8(h3) + toHex8(h4) + toHex8(h5) + toHex8(h6) + toHex8(h7);
|
|
82
|
+
};
|
|
83
|
+
//#endregion
|
|
84
|
+
//#region src/fingerprint.ts
|
|
85
|
+
/**
|
|
86
|
+
* `@velajs/errors/fingerprint` — zero-dependency, cross-runtime error grouping.
|
|
87
|
+
*
|
|
88
|
+
* Collapses noisy repeats of the same error into one stable "issue" identity: a
|
|
89
|
+
* 16-hex-character hash over the function path plus a *normalized* message, so a
|
|
90
|
+
* live in-flight error and one recomputed later from a persisted log row fold
|
|
91
|
+
* onto the same fingerprint. The machine `code` rides along as metadata and is
|
|
92
|
+
* deliberately excluded from the hash, so the redacted wire view produced by
|
|
93
|
+
* `toErrorBody` and the raw server-side error group together.
|
|
94
|
+
*
|
|
95
|
+
* The digest is a portable synchronous SHA-256 (see `./sha256`) truncated to 16
|
|
96
|
+
* hex chars — content-addressing only, never a security or MAC primitive.
|
|
97
|
+
*
|
|
98
|
+
* The message-normalization / grouping approach is inspired by
|
|
99
|
+
* `@superlog/fingerprint` (Apache-2.0); this is an independent implementation.
|
|
100
|
+
*/
|
|
101
|
+
/**
|
|
102
|
+
* Heuristic generation of {@link bucketMessage}. Bump it whenever the
|
|
103
|
+
* normalizer's rules change: changed heuristics re-partition history (they may
|
|
104
|
+
* split one group into several or merge several into one), so a consumer that
|
|
105
|
+
* persists fingerprints stores this alongside each hash to know which
|
|
106
|
+
* generation produced it and when a recompute/backfill is due.
|
|
107
|
+
*/
|
|
108
|
+
const FINGERPRINT_VERSION = 1;
|
|
109
|
+
/**
|
|
110
|
+
* Upper bound on the raw message length fed to the normalizer's regexes. A few
|
|
111
|
+
* of them (the email and long-run patterns especially) can backtrack
|
|
112
|
+
* super-linearly on a long delimiter-free run, and an error message can carry
|
|
113
|
+
* attacker-influenced input of unbounded size — so clamp first to keep the
|
|
114
|
+
* regex work bounded (a ReDoS guard). The final bucket is capped far below this
|
|
115
|
+
* anyway, so the clamp is transparent for any real message.
|
|
116
|
+
*/
|
|
117
|
+
const MAX_INPUT_LENGTH = 1024;
|
|
118
|
+
/** Cap on the normalized bucket so one runaway message can't bloat the key. */
|
|
119
|
+
const MAX_BUCKET_LENGTH = 160;
|
|
120
|
+
/** Hex length of the truncated digest used as the grouping id. */
|
|
121
|
+
const HASH_LENGTH = 16;
|
|
122
|
+
/** Namespaces the hash so a fingerprint can't collide with another content hash. */
|
|
123
|
+
const SCHEME = "velajs.errors/fingerprint";
|
|
124
|
+
/**
|
|
125
|
+
* Ordered noise-stripping rules applied to a message before hashing. Each
|
|
126
|
+
* replaces a class of per-occurrence identifier with a stable placeholder, so
|
|
127
|
+
* two errors that differ only in their variable parts land in the same bucket.
|
|
128
|
+
* Order matters: broader shapes (urls, timestamps) run before the greedy
|
|
129
|
+
* numeric/id sweeps that would otherwise chew their digits.
|
|
130
|
+
*/
|
|
131
|
+
const NOISE_RULES = [
|
|
132
|
+
[/https?:\/\/\S+/gi, "[url]"],
|
|
133
|
+
[/\b[\w.+-]+@[\w.-]+\.[a-z]{2,}\b/gi, "[email]"],
|
|
134
|
+
[/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, "[uuid]"],
|
|
135
|
+
[/\b\d{4}-\d{2}-\d{2}[t ][\d:.]+z?(?:[+-]\d{2}:?\d{2})?\b/gi, "[time]"],
|
|
136
|
+
[/\b(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?\b/g, "[ip]"],
|
|
137
|
+
[/(^|\s)\/\S*/g, "$1[path]"],
|
|
138
|
+
[/\b[a-z]:\\[^\s]*/gi, "[path]"],
|
|
139
|
+
[/\b0x[0-9a-f]+\b/gi, "[hex]"],
|
|
140
|
+
[/\b[a-z0-9_]{20,}\b/gi, "[id]"],
|
|
141
|
+
[/\b\d+\b/g, "[num]"]
|
|
142
|
+
];
|
|
143
|
+
/**
|
|
144
|
+
* Normalize an error message into its grouping bucket: strip per-occurrence
|
|
145
|
+
* noise (urls, uuids, ips, request/filesystem paths, long ids, numbers) and
|
|
146
|
+
* fold whitespace/case, so occurrences of the same logical error collapse to
|
|
147
|
+
* one bucket. Exported for direct testing of the normalization heuristics.
|
|
148
|
+
*/
|
|
149
|
+
const bucketMessage = (message) => {
|
|
150
|
+
if (message.length === 0) return "";
|
|
151
|
+
let text = message.length > MAX_INPUT_LENGTH ? message.slice(0, MAX_INPUT_LENGTH) : message;
|
|
152
|
+
for (const [pattern, placeholder] of NOISE_RULES) text = text.replace(pattern, placeholder);
|
|
153
|
+
text = text.replace(/\s+/g, " ").trim().toLowerCase();
|
|
154
|
+
return text.length > MAX_BUCKET_LENGTH ? text.slice(0, MAX_BUCKET_LENGTH) : text;
|
|
155
|
+
};
|
|
156
|
+
/**
|
|
157
|
+
* Fold an error into its stable 16-hex-character grouping fingerprint. Pure and
|
|
158
|
+
* synchronous, safe to call per row when grouping a log page. The same
|
|
159
|
+
* `functionPath` and logically-equal `message` always yield the same hash
|
|
160
|
+
* regardless of the `code` supplied or per-occurrence noise in the message.
|
|
161
|
+
*/
|
|
162
|
+
const fingerprintError = (input) => {
|
|
163
|
+
const source = input.functionPath.length > 0 ? input.functionPath : "unknown";
|
|
164
|
+
return sha256Hex(`${SCHEME}\n${source}\n${bucketMessage(input.message)}`).slice(0, HASH_LENGTH);
|
|
165
|
+
};
|
|
166
|
+
//#endregion
|
|
167
|
+
export { FINGERPRINT_VERSION, bucketMessage, fingerprintError, sha256Hex };
|
|
168
|
+
|
|
169
|
+
//# sourceMappingURL=fingerprint.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fingerprint.js","names":[],"sources":["../src/sha256.ts","../src/fingerprint.ts"],"sourcesContent":["/**\n * Portable, synchronous SHA-256 (FIPS 180-4) returning a lowercase hex digest.\n *\n * Implemented straight from the published standard so this file carries no\n * runtime dependency and produces byte-for-byte identical output on every\n * target Vela supports — browsers, the Cloudflare Workers (workerd) runtime,\n * and Node. Neither built-in alternative fits the fingerprinter:\n * - `node:crypto` (`createHash`) is absent in browsers and needs\n * `nodejs_compat` to load in workerd.\n * - `crypto.subtle.digest` is async, which is clumsy for folding error rows\n * into a group key one synchronous call at a time.\n *\n * SECURITY: this is a plain, non-constant-time digest meant ONLY for\n * content-addressing and grouping keys. Never use it as a MAC, a password hash,\n * or any other authentication or security primitive.\n */\n\nconst BLOCK_BYTES = 64;\n\n// Round constants K[0..63]: the first 32 bits of the fractional parts of the\n// cube roots of the first 64 primes (FIPS 180-4 §4.2.2).\nconst ROUND = Uint32Array.of(\n 0x428a2f98,\n 0x71374491,\n 0xb5c0fbcf,\n 0xe9b5dba5,\n 0x3956c25b,\n 0x59f111f1,\n 0x923f82a4,\n 0xab1c5ed5,\n 0xd807aa98,\n 0x12835b01,\n 0x243185be,\n 0x550c7dc3,\n 0x72be5d74,\n 0x80deb1fe,\n 0x9bdc06a7,\n 0xc19bf174,\n 0xe49b69c1,\n 0xefbe4786,\n 0x0fc19dc6,\n 0x240ca1cc,\n 0x2de92c6f,\n 0x4a7484aa,\n 0x5cb0a9dc,\n 0x76f988da,\n 0x983e5152,\n 0xa831c66d,\n 0xb00327c8,\n 0xbf597fc7,\n 0xc6e00bf3,\n 0xd5a79147,\n 0x06ca6351,\n 0x14292967,\n 0x27b70a85,\n 0x2e1b2138,\n 0x4d2c6dfc,\n 0x53380d13,\n 0x650a7354,\n 0x766a0abb,\n 0x81c2c92e,\n 0x92722c85,\n 0xa2bfe8a1,\n 0xa81a664b,\n 0xc24b8b70,\n 0xc76c51a3,\n 0xd192e819,\n 0xd6990624,\n 0xf40e3585,\n 0x106aa070,\n 0x19a4c116,\n 0x1e376c08,\n 0x2748774c,\n 0x34b0bcb5,\n 0x391c0cb3,\n 0x4ed8aa4a,\n 0x5b9cca4f,\n 0x682e6ff3,\n 0x748f82ee,\n 0x78a5636f,\n 0x84c87814,\n 0x8cc70208,\n 0x90befffa,\n 0xa4506ceb,\n 0xbef9a3f7,\n 0xc67178f2,\n);\n\nconst rotr = (word: number, bits: number): number => (word >>> bits) | (word << (32 - bits));\n\nconst toHex8 = (word: number): string => (word >>> 0).toString(16).padStart(8, '0');\n\nexport const sha256Hex = (input: string): string => {\n const message = new TextEncoder().encode(input);\n const bitLength = message.length * 8;\n\n // One 0x80 marker byte, an 8-byte length trailer, zero fill in between, all\n // rounded up to whole 64-byte blocks.\n const totalBytes = (Math.floor((message.length + 8) / BLOCK_BYTES) + 1) * BLOCK_BYTES;\n const padded = new Uint8Array(totalBytes);\n padded.set(message);\n padded[message.length] = 0x80;\n\n const frame = new DataView(padded.buffer);\n // Big-endian 64-bit bit length in the final 8 bytes. Fingerprint inputs are\n // short strings, so the high word stays zero in practice, but compute it\n // anyway for correctness.\n frame.setUint32(totalBytes - 8, Math.floor(bitLength / 0x1_0000_0000), false);\n frame.setUint32(totalBytes - 4, bitLength >>> 0, false);\n\n // Initial state H[0..7]: first 32 bits of the fractional parts of the square\n // roots of the first 8 primes (FIPS 180-4 §5.3.3).\n let h0 = 0x6a09e667;\n let h1 = 0xbb67ae85;\n let h2 = 0x3c6ef372;\n let h3 = 0xa54ff53a;\n let h4 = 0x510e527f;\n let h5 = 0x9b05688c;\n let h6 = 0x1f83d9ab;\n let h7 = 0x5be0cd19;\n\n const schedule = new Uint32Array(64);\n\n for (let base = 0; base < totalBytes; base += BLOCK_BYTES) {\n for (let t = 0; t < 16; t += 1) {\n schedule[t] = frame.getUint32(base + t * 4, false);\n }\n for (let t = 16; t < 64; t += 1) {\n const x = schedule[t - 15] as number;\n const y = schedule[t - 2] as number;\n const sigma0 = rotr(x, 7) ^ rotr(x, 18) ^ (x >>> 3);\n const sigma1 = rotr(y, 17) ^ rotr(y, 19) ^ (y >>> 10);\n schedule[t] =\n ((schedule[t - 16] as number) + sigma0 + (schedule[t - 7] as number) + sigma1) >>> 0;\n }\n\n let a = h0;\n let b = h1;\n let c = h2;\n let d = h3;\n let e = h4;\n let f = h5;\n let g = h6;\n let h = h7;\n\n for (let t = 0; t < 64; t += 1) {\n const bigSigma1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);\n const choose = (e & f) ^ (~e & g);\n const t1 = (h + bigSigma1 + choose + (ROUND[t] as number) + (schedule[t] as number)) >>> 0;\n const bigSigma0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22);\n const majority = (a & b) ^ (a & c) ^ (b & c);\n const t2 = (bigSigma0 + majority) >>> 0;\n\n h = g;\n g = f;\n f = e;\n e = (d + t1) >>> 0;\n d = c;\n c = b;\n b = a;\n a = (t1 + t2) >>> 0;\n }\n\n h0 = (h0 + a) >>> 0;\n h1 = (h1 + b) >>> 0;\n h2 = (h2 + c) >>> 0;\n h3 = (h3 + d) >>> 0;\n h4 = (h4 + e) >>> 0;\n h5 = (h5 + f) >>> 0;\n h6 = (h6 + g) >>> 0;\n h7 = (h7 + h) >>> 0;\n }\n\n return (\n toHex8(h0) +\n toHex8(h1) +\n toHex8(h2) +\n toHex8(h3) +\n toHex8(h4) +\n toHex8(h5) +\n toHex8(h6) +\n toHex8(h7)\n );\n};\n","/**\n * `@velajs/errors/fingerprint` — zero-dependency, cross-runtime error grouping.\n *\n * Collapses noisy repeats of the same error into one stable \"issue\" identity: a\n * 16-hex-character hash over the function path plus a *normalized* message, so a\n * live in-flight error and one recomputed later from a persisted log row fold\n * onto the same fingerprint. The machine `code` rides along as metadata and is\n * deliberately excluded from the hash, so the redacted wire view produced by\n * `toErrorBody` and the raw server-side error group together.\n *\n * The digest is a portable synchronous SHA-256 (see `./sha256`) truncated to 16\n * hex chars — content-addressing only, never a security or MAC primitive.\n *\n * The message-normalization / grouping approach is inspired by\n * `@superlog/fingerprint` (Apache-2.0); this is an independent implementation.\n */\nimport { sha256Hex } from './sha256';\n\n/**\n * Heuristic generation of {@link bucketMessage}. Bump it whenever the\n * normalizer's rules change: changed heuristics re-partition history (they may\n * split one group into several or merge several into one), so a consumer that\n * persists fingerprints stores this alongside each hash to know which\n * generation produced it and when a recompute/backfill is due.\n */\nexport const FINGERPRINT_VERSION: number = 1;\n\n/**\n * Upper bound on the raw message length fed to the normalizer's regexes. A few\n * of them (the email and long-run patterns especially) can backtrack\n * super-linearly on a long delimiter-free run, and an error message can carry\n * attacker-influenced input of unbounded size — so clamp first to keep the\n * regex work bounded (a ReDoS guard). The final bucket is capped far below this\n * anyway, so the clamp is transparent for any real message.\n */\nconst MAX_INPUT_LENGTH = 1024;\n\n/** Cap on the normalized bucket so one runaway message can't bloat the key. */\nconst MAX_BUCKET_LENGTH = 160;\n\n/** Hex length of the truncated digest used as the grouping id. */\nconst HASH_LENGTH = 16;\n\n/** Namespaces the hash so a fingerprint can't collide with another content hash. */\nconst SCHEME = 'velajs.errors/fingerprint';\n\n/**\n * Ordered noise-stripping rules applied to a message before hashing. Each\n * replaces a class of per-occurrence identifier with a stable placeholder, so\n * two errors that differ only in their variable parts land in the same bucket.\n * Order matters: broader shapes (urls, timestamps) run before the greedy\n * numeric/id sweeps that would otherwise chew their digits.\n */\nconst NOISE_RULES: readonly (readonly [RegExp, string])[] = [\n // Whole URLs (before path/number rules can nibble their insides).\n [/https?:\\/\\/\\S+/gi, '[url]'],\n // Email addresses.\n [/\\b[\\w.+-]+@[\\w.-]+\\.[a-z]{2,}\\b/gi, '[email]'],\n // RFC-4122 UUIDs.\n [/\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi, '[uuid]'],\n // ISO-8601-ish timestamps (before the ip/number rules touch their digits).\n [/\\b\\d{4}-\\d{2}-\\d{2}[t ][\\d:.]+z?(?:[+-]\\d{2}:?\\d{2})?\\b/gi, '[time]'],\n // IPv4 addresses with an optional port.\n [/\\b(?:\\d{1,3}\\.){3}\\d{1,3}(?::\\d+)?\\b/g, '[ip]'],\n // Unix-style request/filesystem paths at a token boundary — keeps in-word\n // slashes (client/server, and/or) intact while folding a scanner's probed\n // paths (/wp-admin, /.env, /.git/config) onto one placeholder.\n [/(^|\\s)\\/\\S*/g, '$1[path]'],\n // Windows drive-letter paths.\n [/\\b[a-z]:\\\\[^\\s]*/gi, '[path]'],\n // Hex literals (0x…).\n [/\\b0x[0-9a-f]+\\b/gi, '[hex]'],\n // Long opaque ids: tokens, hashes, base-ish ids. Threshold high enough to\n // spare ordinary words while catching machine identifiers.\n [/\\b[a-z0-9_]{20,}\\b/gi, '[id]'],\n // Any remaining bare integer.\n [/\\b\\d+\\b/g, '[num]'],\n];\n\n/**\n * Normalize an error message into its grouping bucket: strip per-occurrence\n * noise (urls, uuids, ips, request/filesystem paths, long ids, numbers) and\n * fold whitespace/case, so occurrences of the same logical error collapse to\n * one bucket. Exported for direct testing of the normalization heuristics.\n */\nexport const bucketMessage = (message: string): string => {\n if (message.length === 0) {\n return '';\n }\n\n let text = message.length > MAX_INPUT_LENGTH ? message.slice(0, MAX_INPUT_LENGTH) : message;\n\n for (const [pattern, placeholder] of NOISE_RULES) {\n text = text.replace(pattern, placeholder);\n }\n\n text = text.replace(/\\s+/g, ' ').trim().toLowerCase();\n\n return text.length > MAX_BUCKET_LENGTH ? text.slice(0, MAX_BUCKET_LENGTH) : text;\n};\n\n/** Everything a fingerprint source can supply. */\nexport interface ErrorFingerprintInput {\n /**\n * What raised the error — the invoked function/route path, e.g.\n * `messages:list`. Part of the grouping key.\n */\n functionPath: string;\n /** Human-readable message (may embed user input); normalized into the key. */\n message: string;\n /**\n * Machine error code, when known. Pure metadata: **never folded into the\n * hash**, so the redacted wire error (which may rewrite or drop the code) and\n * the raw server-side error still produce the same fingerprint.\n */\n code?: string;\n}\n\n/**\n * Fold an error into its stable 16-hex-character grouping fingerprint. Pure and\n * synchronous, safe to call per row when grouping a log page. The same\n * `functionPath` and logically-equal `message` always yield the same hash\n * regardless of the `code` supplied or per-occurrence noise in the message.\n */\nexport const fingerprintError = (input: ErrorFingerprintInput): string => {\n const source = input.functionPath.length > 0 ? input.functionPath : 'unknown';\n const canonical = `${SCHEME}\\n${source}\\n${bucketMessage(input.message)}`;\n return sha256Hex(canonical).slice(0, HASH_LENGTH);\n};\n\nexport { sha256Hex } from './sha256';\n"],"mappings":";;;;;;;;;;;;;;;;;AAiBA,MAAM,cAAc;AAIpB,MAAM,QAAQ,YAAY,GACxB,YACA,YACA,YACA,Y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
-
|
|
10
|
-
|
|
11
|
-
|
|
1
|
+
//#region src/catalog-data.d.ts
|
|
2
|
+
interface ErrorCatalogEntry {
|
|
3
|
+
status: number;
|
|
4
|
+
title: string;
|
|
5
|
+
hint?: string;
|
|
6
|
+
docsUrl?: string;
|
|
7
|
+
/** Redaction posture: true → message/hint/data are never echoed to clients. */
|
|
8
|
+
internal?: boolean;
|
|
9
|
+
}
|
|
10
|
+
declare const CORE_ENTRIES: {
|
|
11
|
+
readonly bad_request: {
|
|
12
|
+
readonly status: 400;
|
|
13
|
+
readonly title: 'Bad Request';
|
|
14
|
+
};
|
|
15
|
+
readonly unauthorized: {
|
|
16
|
+
readonly status: 401;
|
|
17
|
+
readonly title: 'Unauthorized';
|
|
18
|
+
};
|
|
19
|
+
readonly forbidden: {
|
|
20
|
+
readonly status: 403;
|
|
21
|
+
readonly title: 'Forbidden';
|
|
22
|
+
};
|
|
23
|
+
readonly not_found: {
|
|
24
|
+
readonly status: 404;
|
|
25
|
+
readonly title: 'Not Found';
|
|
26
|
+
};
|
|
27
|
+
readonly method_not_allowed: {
|
|
28
|
+
readonly status: 405;
|
|
29
|
+
readonly title: 'Method Not Allowed';
|
|
30
|
+
};
|
|
31
|
+
readonly conflict: {
|
|
32
|
+
readonly status: 409;
|
|
33
|
+
readonly title: 'Conflict';
|
|
34
|
+
};
|
|
35
|
+
readonly gone: {
|
|
36
|
+
readonly status: 410;
|
|
37
|
+
readonly title: 'Gone';
|
|
38
|
+
};
|
|
39
|
+
readonly payload_too_large: {
|
|
40
|
+
readonly status: 413;
|
|
41
|
+
readonly title: 'Payload Too Large';
|
|
42
|
+
};
|
|
43
|
+
readonly unsupported_media_type: {
|
|
44
|
+
readonly status: 415;
|
|
45
|
+
readonly title: 'Unsupported Media Type';
|
|
46
|
+
};
|
|
47
|
+
readonly unprocessable: {
|
|
48
|
+
readonly status: 422;
|
|
49
|
+
readonly title: 'Unprocessable Entity';
|
|
50
|
+
};
|
|
51
|
+
readonly too_many_requests: {
|
|
52
|
+
readonly status: 429;
|
|
53
|
+
readonly title: 'Too Many Requests';
|
|
54
|
+
};
|
|
55
|
+
readonly internal: {
|
|
56
|
+
readonly status: 500;
|
|
57
|
+
readonly title: 'Internal Server Error';
|
|
58
|
+
readonly internal: true;
|
|
59
|
+
};
|
|
60
|
+
readonly not_implemented: {
|
|
61
|
+
readonly status: 501;
|
|
62
|
+
readonly title: 'Not Implemented';
|
|
63
|
+
};
|
|
64
|
+
readonly bad_gateway: {
|
|
65
|
+
readonly status: 502;
|
|
66
|
+
readonly title: 'Bad Gateway';
|
|
67
|
+
};
|
|
68
|
+
readonly service_unavailable: {
|
|
69
|
+
readonly status: 503;
|
|
70
|
+
readonly title: 'Service Unavailable';
|
|
71
|
+
};
|
|
72
|
+
readonly gateway_timeout: {
|
|
73
|
+
readonly status: 504;
|
|
74
|
+
readonly title: 'Gateway Timeout';
|
|
75
|
+
};
|
|
76
|
+
};
|
|
77
|
+
type CoreErrorCode = keyof typeof CORE_ENTRIES;
|
|
78
|
+
//#endregion
|
|
79
|
+
//#region src/error.d.ts
|
|
80
|
+
interface VelaErrorOptions {
|
|
81
|
+
message?: string;
|
|
82
|
+
status?: number;
|
|
83
|
+
hint?: string;
|
|
84
|
+
docsUrl?: string;
|
|
85
|
+
data?: unknown;
|
|
86
|
+
cause?: unknown;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The one Vela error. Every field is an OWN ENUMERABLE property so the error
|
|
90
|
+
* rides any wire codec / structuredClone / DO-RPC prop-copy with no special
|
|
91
|
+
* serialization path. `type` is the brand `isVelaError` checks — it must
|
|
92
|
+
* survive serialization, which own+enumerable guarantees.
|
|
93
|
+
*/
|
|
94
|
+
declare class VelaError extends Error {
|
|
95
|
+
readonly type = "VelaError";
|
|
96
|
+
readonly code: string;
|
|
97
|
+
readonly status: number;
|
|
98
|
+
readonly hint?: string;
|
|
99
|
+
readonly docsUrl?: string;
|
|
100
|
+
readonly data?: unknown;
|
|
101
|
+
constructor(code: CoreErrorCode, options?: VelaErrorOptions);
|
|
102
|
+
constructor(code: string, options: VelaErrorOptions & {
|
|
103
|
+
status: number;
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
//#endregion
|
|
107
|
+
//#region src/catalog.d.ts
|
|
108
|
+
interface Catalog<C extends string = string> {
|
|
109
|
+
readonly entries: Readonly<Record<C, ErrorCatalogEntry>>;
|
|
110
|
+
/** Typed thrower bound to this catalog's defaults. */
|
|
111
|
+
error(code: C | (string & {}), options?: VelaErrorOptions): VelaError;
|
|
112
|
+
has(code: string): boolean;
|
|
113
|
+
get(code: string): ErrorCatalogEntry | undefined;
|
|
114
|
+
}
|
|
115
|
+
declare const defineErrorCatalog: <const T extends Record<string, ErrorCatalogEntry>>(entries: T) => Catalog<Extract<keyof T, string>>;
|
|
116
|
+
declare const composeCatalogs: (...catalogs: Array<Catalog<string>>) => Catalog<string>;
|
|
117
|
+
declare const CORE_CATALOG: Catalog<CoreErrorCode>;
|
|
118
|
+
declare const STATUS_TO_CODE: Readonly<Record<number, CoreErrorCode>>;
|
|
119
|
+
//#endregion
|
|
120
|
+
//#region src/guard.d.ts
|
|
121
|
+
/**
|
|
122
|
+
* Structural, realm-safe, BRANDED guard. `instanceof VelaError` is unreliable
|
|
123
|
+
* across DO↔worker RPC and for wire-decoded twins; a bare code+status shape
|
|
124
|
+
* check lets foreign driver errors ride the client-echo path. The brand
|
|
125
|
+
* (`type === 'VelaError'`, an own enumerable prop that survives serialization)
|
|
126
|
+
* closes both failure modes. Nothing load-bearing may use `instanceof`.
|
|
127
|
+
*/
|
|
128
|
+
interface VelaErrorLike extends Error {
|
|
129
|
+
type: 'VelaError';
|
|
130
|
+
code: string;
|
|
131
|
+
status: number;
|
|
132
|
+
hint?: string;
|
|
133
|
+
docsUrl?: string;
|
|
134
|
+
data?: unknown;
|
|
135
|
+
}
|
|
136
|
+
declare const isVelaError: (error: unknown) => error is VelaErrorLike;
|
|
137
|
+
//#endregion
|
|
138
|
+
//#region src/to-error-body.d.ts
|
|
139
|
+
interface WireErrorObject {
|
|
140
|
+
code: string;
|
|
141
|
+
message: string;
|
|
142
|
+
hint?: string;
|
|
143
|
+
docsUrl?: string;
|
|
144
|
+
details?: unknown;
|
|
145
|
+
}
|
|
146
|
+
interface ErrorBodyResult {
|
|
147
|
+
body: {
|
|
148
|
+
error: WireErrorObject;
|
|
149
|
+
};
|
|
150
|
+
status: number;
|
|
151
|
+
redacted: boolean;
|
|
152
|
+
}
|
|
153
|
+
interface ToErrorBodyOptions {
|
|
154
|
+
/** Composed catalog; defaults to the core catalog. */
|
|
155
|
+
catalog?: Catalog<string>;
|
|
156
|
+
/** Status used for unbranded errors. Default 500. */
|
|
157
|
+
fallbackStatus?: number;
|
|
158
|
+
redactedMessage?: (status: number) => string;
|
|
159
|
+
/** Injectable wire codec for `data` → `details` (bigint/bytes etc.). */
|
|
160
|
+
encodeData?: (data: unknown) => unknown;
|
|
161
|
+
/** Default true. */
|
|
162
|
+
includeHint?: boolean;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* THE single wire-redaction seam. Every transport edge (HTTP, WS, live, queue
|
|
166
|
+
* reporting) builds its client-bound error content here, so the invariant
|
|
167
|
+
* "unbranded or internal-coded errors never echo their message" holds
|
|
168
|
+
* identically everywhere. `redacted: true` is the caller's signal to log the
|
|
169
|
+
* raw error server-side — this function never logs (zero-dep purity).
|
|
170
|
+
*/
|
|
171
|
+
declare const toErrorBody: (error: unknown, options?: ToErrorBodyOptions) => ErrorBodyResult;
|
|
172
|
+
//#endregion
|
|
173
|
+
//#region src/invariant.d.ts
|
|
174
|
+
/** Throws an internal-coded VelaError — rich in server logs, redacted on the wire. */
|
|
175
|
+
declare function invariant(condition: unknown, message: string, data?: unknown): asserts condition;
|
|
176
|
+
declare function unreachable(value: never, message?: string): never;
|
|
177
|
+
//#endregion
|
|
178
|
+
export { CORE_CATALOG, CORE_ENTRIES, type Catalog, type CoreErrorCode, type ErrorBodyResult, type ErrorCatalogEntry, STATUS_TO_CODE, type ToErrorBodyOptions, VelaError, type VelaErrorLike, type VelaErrorOptions, type WireErrorObject, composeCatalogs, defineErrorCatalog, invariant, isVelaError, toErrorBody, unreachable };
|
|
179
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,197 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
//#region src/catalog-data.ts
|
|
2
|
+
const CORE_ENTRIES = {
|
|
3
|
+
bad_request: {
|
|
4
|
+
status: 400,
|
|
5
|
+
title: "Bad Request"
|
|
6
|
+
},
|
|
7
|
+
unauthorized: {
|
|
8
|
+
status: 401,
|
|
9
|
+
title: "Unauthorized"
|
|
10
|
+
},
|
|
11
|
+
forbidden: {
|
|
12
|
+
status: 403,
|
|
13
|
+
title: "Forbidden"
|
|
14
|
+
},
|
|
15
|
+
not_found: {
|
|
16
|
+
status: 404,
|
|
17
|
+
title: "Not Found"
|
|
18
|
+
},
|
|
19
|
+
method_not_allowed: {
|
|
20
|
+
status: 405,
|
|
21
|
+
title: "Method Not Allowed"
|
|
22
|
+
},
|
|
23
|
+
conflict: {
|
|
24
|
+
status: 409,
|
|
25
|
+
title: "Conflict"
|
|
26
|
+
},
|
|
27
|
+
gone: {
|
|
28
|
+
status: 410,
|
|
29
|
+
title: "Gone"
|
|
30
|
+
},
|
|
31
|
+
payload_too_large: {
|
|
32
|
+
status: 413,
|
|
33
|
+
title: "Payload Too Large"
|
|
34
|
+
},
|
|
35
|
+
unsupported_media_type: {
|
|
36
|
+
status: 415,
|
|
37
|
+
title: "Unsupported Media Type"
|
|
38
|
+
},
|
|
39
|
+
unprocessable: {
|
|
40
|
+
status: 422,
|
|
41
|
+
title: "Unprocessable Entity"
|
|
42
|
+
},
|
|
43
|
+
too_many_requests: {
|
|
44
|
+
status: 429,
|
|
45
|
+
title: "Too Many Requests"
|
|
46
|
+
},
|
|
47
|
+
internal: {
|
|
48
|
+
status: 500,
|
|
49
|
+
title: "Internal Server Error",
|
|
50
|
+
internal: true
|
|
51
|
+
},
|
|
52
|
+
not_implemented: {
|
|
53
|
+
status: 501,
|
|
54
|
+
title: "Not Implemented"
|
|
55
|
+
},
|
|
56
|
+
bad_gateway: {
|
|
57
|
+
status: 502,
|
|
58
|
+
title: "Bad Gateway"
|
|
59
|
+
},
|
|
60
|
+
service_unavailable: {
|
|
61
|
+
status: 503,
|
|
62
|
+
title: "Service Unavailable"
|
|
63
|
+
},
|
|
64
|
+
gateway_timeout: {
|
|
65
|
+
status: 504,
|
|
66
|
+
title: "Gateway Timeout"
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
//#endregion
|
|
70
|
+
//#region src/error.ts
|
|
71
|
+
/**
|
|
72
|
+
* The one Vela error. Every field is an OWN ENUMERABLE property so the error
|
|
73
|
+
* rides any wire codec / structuredClone / DO-RPC prop-copy with no special
|
|
74
|
+
* serialization path. `type` is the brand `isVelaError` checks — it must
|
|
75
|
+
* survive serialization, which own+enumerable guarantees.
|
|
76
|
+
*/
|
|
77
|
+
var VelaError = class extends Error {
|
|
78
|
+
type = "VelaError";
|
|
79
|
+
code;
|
|
80
|
+
status;
|
|
81
|
+
hint;
|
|
82
|
+
docsUrl;
|
|
83
|
+
data;
|
|
84
|
+
constructor(code, options = {}) {
|
|
85
|
+
const entry = CORE_ENTRIES[code];
|
|
86
|
+
super(options.message ?? entry?.title ?? code, options.cause !== void 0 ? { cause: options.cause } : void 0);
|
|
87
|
+
this.name = "VelaError";
|
|
88
|
+
this.code = code;
|
|
89
|
+
this.status = options.status ?? entry?.status ?? 500;
|
|
90
|
+
const hint = options.hint ?? entry?.hint;
|
|
91
|
+
const docsUrl = options.docsUrl ?? entry?.docsUrl;
|
|
92
|
+
if (hint !== void 0) this.hint = hint;
|
|
93
|
+
if (docsUrl !== void 0) this.docsUrl = docsUrl;
|
|
94
|
+
if (options.data !== void 0) this.data = options.data;
|
|
95
|
+
Object.setPrototypeOf(this, new.target.prototype);
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
//#endregion
|
|
99
|
+
//#region src/catalog.ts
|
|
100
|
+
const makeCatalog = (entries) => ({
|
|
101
|
+
entries,
|
|
102
|
+
error(code, options = {}) {
|
|
103
|
+
const entry = entries[code];
|
|
104
|
+
const hint = options.hint ?? entry?.hint;
|
|
105
|
+
const docsUrl = options.docsUrl ?? entry?.docsUrl;
|
|
106
|
+
return new VelaError(code, {
|
|
107
|
+
...options,
|
|
108
|
+
status: options.status ?? entry?.status ?? 500,
|
|
109
|
+
...hint === void 0 ? {} : { hint },
|
|
110
|
+
...docsUrl === void 0 ? {} : { docsUrl }
|
|
111
|
+
});
|
|
112
|
+
},
|
|
113
|
+
has: (code) => Object.hasOwn(entries, code),
|
|
114
|
+
get: (code) => Object.hasOwn(entries, code) ? entries[code] : void 0
|
|
115
|
+
});
|
|
116
|
+
const defineErrorCatalog = (entries) => makeCatalog(entries);
|
|
117
|
+
const composeCatalogs = (...catalogs) => {
|
|
118
|
+
const merged = {};
|
|
119
|
+
for (const catalog of catalogs) for (const [code, entry] of Object.entries(catalog.entries)) {
|
|
120
|
+
if (Object.hasOwn(merged, code)) throw new VelaError("internal", { message: `duplicate error code '${code}' while composing catalogs` });
|
|
121
|
+
merged[code] = entry;
|
|
122
|
+
}
|
|
123
|
+
return makeCatalog(merged);
|
|
124
|
+
};
|
|
125
|
+
const CORE_CATALOG = makeCatalog(CORE_ENTRIES);
|
|
126
|
+
const STATUS_TO_CODE = Object.fromEntries(Object.entries(CORE_ENTRIES).map(([code, e]) => [e.status, code]));
|
|
127
|
+
//#endregion
|
|
128
|
+
//#region src/guard.ts
|
|
129
|
+
const isVelaError = (error) => {
|
|
130
|
+
if (!(error instanceof Error)) return false;
|
|
131
|
+
const candidate = error;
|
|
132
|
+
return typeof candidate.code === "string" && typeof candidate.status === "number" && candidate.type === "VelaError";
|
|
133
|
+
};
|
|
134
|
+
//#endregion
|
|
135
|
+
//#region src/to-error-body.ts
|
|
136
|
+
const defaultRedactedMessage = (status, catalog) => {
|
|
137
|
+
const code = STATUS_TO_CODE[status];
|
|
138
|
+
return code && catalog.get(code)?.title || "Internal Server Error";
|
|
139
|
+
};
|
|
140
|
+
/**
|
|
141
|
+
* THE single wire-redaction seam. Every transport edge (HTTP, WS, live, queue
|
|
142
|
+
* reporting) builds its client-bound error content here, so the invariant
|
|
143
|
+
* "unbranded or internal-coded errors never echo their message" holds
|
|
144
|
+
* identically everywhere. `redacted: true` is the caller's signal to log the
|
|
145
|
+
* raw error server-side — this function never logs (zero-dep purity).
|
|
146
|
+
*/
|
|
147
|
+
const toErrorBody = (error, options = {}) => {
|
|
148
|
+
const catalog = options.catalog ?? CORE_CATALOG;
|
|
149
|
+
const message = options.redactedMessage ?? ((s) => defaultRedactedMessage(s, catalog));
|
|
150
|
+
const redact = (status, code) => ({
|
|
151
|
+
body: { error: {
|
|
152
|
+
code,
|
|
153
|
+
message: message(status)
|
|
154
|
+
} },
|
|
155
|
+
status,
|
|
156
|
+
redacted: true
|
|
157
|
+
});
|
|
158
|
+
if (!isVelaError(error)) {
|
|
159
|
+
const status = options.fallbackStatus ?? 500;
|
|
160
|
+
return redact(status, STATUS_TO_CODE[status] ?? "internal");
|
|
161
|
+
}
|
|
162
|
+
const entry = catalog.get(error.code);
|
|
163
|
+
if (error.code === "internal" || entry?.internal === true) return redact(error.status, error.code);
|
|
164
|
+
const wire = {
|
|
165
|
+
code: error.code,
|
|
166
|
+
message: error.message
|
|
167
|
+
};
|
|
168
|
+
const hint = error.hint ?? entry?.hint;
|
|
169
|
+
if (options.includeHint !== false && hint !== void 0) wire.hint = hint;
|
|
170
|
+
const docsUrl = error.docsUrl ?? entry?.docsUrl;
|
|
171
|
+
if (docsUrl !== void 0) wire.docsUrl = docsUrl;
|
|
172
|
+
if (error.data !== void 0) wire.details = options.encodeData ? options.encodeData(error.data) : error.data;
|
|
173
|
+
return {
|
|
174
|
+
body: { error: wire },
|
|
175
|
+
status: error.status,
|
|
176
|
+
redacted: false
|
|
177
|
+
};
|
|
178
|
+
};
|
|
179
|
+
//#endregion
|
|
180
|
+
//#region src/invariant.ts
|
|
181
|
+
/** Throws an internal-coded VelaError — rich in server logs, redacted on the wire. */
|
|
182
|
+
function invariant(condition, message, data) {
|
|
183
|
+
if (!condition) throw new VelaError("internal", {
|
|
184
|
+
message: `Invariant violation: ${message}`,
|
|
185
|
+
data
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
function unreachable(value, message = "unreachable code reached") {
|
|
189
|
+
throw new VelaError("internal", {
|
|
190
|
+
message,
|
|
191
|
+
data: { value }
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
//#endregion
|
|
195
|
+
export { CORE_CATALOG, CORE_ENTRIES, STATUS_TO_CODE, VelaError, composeCatalogs, defineErrorCatalog, invariant, isVelaError, toErrorBody, unreachable };
|
|
196
|
+
|
|
197
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/catalog-data.ts","../src/error.ts","../src/catalog.ts","../src/guard.ts","../src/to-error-body.ts","../src/invariant.ts"],"sourcesContent":["export interface ErrorCatalogEntry {\n status: number;\n title: string;\n hint?: string;\n docsUrl?: string;\n /** Redaction posture: true → message/hint/data are never echoed to clients. */\n internal?: boolean;\n}\n\nexport const CORE_ENTRIES = {\n bad_request: { status: 400, title: 'Bad Request' },\n unauthorized: { status: 401, title: 'Unauthorized' },\n forbidden: { status: 403, title: 'Forbidden' },\n not_found: { status: 404, title: 'Not Found' },\n method_not_allowed: { status: 405, title: 'Method Not Allowed' },\n conflict: { status: 409, title: 'Conflict' },\n gone: { status: 410, title: 'Gone' },\n payload_too_large: { status: 413, title: 'Payload Too Large' },\n unsupported_media_type: { status: 415, title: 'Unsupported Media Type' },\n unprocessable: { status: 422, title: 'Unprocessable Entity' },\n too_many_requests: { status: 429, title: 'Too Many Requests' },\n internal: { status: 500, title: 'Internal Server Error', internal: true },\n not_implemented: { status: 501, title: 'Not Implemented' },\n bad_gateway: { status: 502, title: 'Bad Gateway' },\n service_unavailable: { status: 503, title: 'Service Unavailable' },\n gateway_timeout: { status: 504, title: 'Gateway Timeout' },\n} as const satisfies Record<string, ErrorCatalogEntry>;\n\nexport type CoreErrorCode = keyof typeof CORE_ENTRIES;\n","import { CORE_ENTRIES, type CoreErrorCode } from './catalog-data';\n\nexport interface VelaErrorOptions {\n message?: string;\n status?: number;\n hint?: string;\n docsUrl?: string;\n data?: unknown;\n cause?: unknown;\n}\n\n/**\n * The one Vela error. Every field is an OWN ENUMERABLE property so the error\n * rides any wire codec / structuredClone / DO-RPC prop-copy with no special\n * serialization path. `type` is the brand `isVelaError` checks — it must\n * survive serialization, which own+enumerable guarantees.\n */\nexport class VelaError extends Error {\n readonly type = 'VelaError';\n readonly code: string;\n readonly status: number;\n readonly hint?: string;\n readonly docsUrl?: string;\n readonly data?: unknown;\n\n constructor(code: CoreErrorCode, options?: VelaErrorOptions);\n constructor(code: string, options: VelaErrorOptions & { status: number });\n constructor(code: string, options: VelaErrorOptions = {}) {\n const entry = (\n CORE_ENTRIES as Record<\n string,\n { status: number; title: string; hint?: string; docsUrl?: string }\n >\n )[code];\n super(\n options.message ?? entry?.title ?? code,\n options.cause !== undefined ? { cause: options.cause } : undefined,\n );\n this.name = 'VelaError';\n this.code = code;\n this.status = options.status ?? entry?.status ?? 500;\n const hint = options.hint ?? entry?.hint;\n const docsUrl = options.docsUrl ?? entry?.docsUrl;\n if (hint !== undefined) this.hint = hint;\n if (docsUrl !== undefined) this.docsUrl = docsUrl;\n if (options.data !== undefined) this.data = options.data;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { CORE_ENTRIES, type CoreErrorCode, type ErrorCatalogEntry } from './catalog-data';\nimport { VelaError, type VelaErrorOptions } from './error';\n\nexport type { CoreErrorCode, ErrorCatalogEntry } from './catalog-data';\nexport { CORE_ENTRIES } from './catalog-data';\n\nexport interface Catalog<C extends string = string> {\n readonly entries: Readonly<Record<C, ErrorCatalogEntry>>;\n /** Typed thrower bound to this catalog's defaults. */\n error(code: C | (string & {}), options?: VelaErrorOptions): VelaError;\n has(code: string): boolean;\n get(code: string): ErrorCatalogEntry | undefined;\n}\n\nconst makeCatalog = <C extends string>(\n entries: Readonly<Record<C, ErrorCatalogEntry>>,\n): Catalog<C> => ({\n entries,\n error(code, options = {}) {\n const entry = (entries as Record<string, ErrorCatalogEntry>)[code];\n const hint = options.hint ?? entry?.hint;\n const docsUrl = options.docsUrl ?? entry?.docsUrl;\n return new VelaError(code, {\n ...options,\n status: options.status ?? entry?.status ?? 500,\n ...(hint === undefined ? {} : { hint }),\n ...(docsUrl === undefined ? {} : { docsUrl }),\n });\n },\n has: (code) => Object.hasOwn(entries, code),\n get: (code) =>\n Object.hasOwn(entries, code) ? (entries as Record<string, ErrorCatalogEntry>)[code] : undefined,\n});\n\nexport const defineErrorCatalog = <const T extends Record<string, ErrorCatalogEntry>>(\n entries: T,\n): Catalog<Extract<keyof T, string>> => makeCatalog(entries);\n\nexport const composeCatalogs = (...catalogs: Array<Catalog<string>>): Catalog<string> => {\n const merged: Record<string, ErrorCatalogEntry> = {};\n for (const catalog of catalogs) {\n for (const [code, entry] of Object.entries<ErrorCatalogEntry>(catalog.entries)) {\n if (Object.hasOwn(merged, code)) {\n throw new VelaError('internal', {\n message: `duplicate error code '${code}' while composing catalogs`,\n });\n }\n merged[code] = entry;\n }\n }\n return makeCatalog(merged);\n};\n\nexport const CORE_CATALOG: Catalog<CoreErrorCode> = makeCatalog(CORE_ENTRIES);\n\nexport const STATUS_TO_CODE: Readonly<Record<number, CoreErrorCode>> = Object.fromEntries(\n (Object.entries(CORE_ENTRIES) as Array<[CoreErrorCode, ErrorCatalogEntry]>).map(([code, e]) => [\n e.status,\n code,\n ]),\n) as Record<number, CoreErrorCode>;\n","/**\n * Structural, realm-safe, BRANDED guard. `instanceof VelaError` is unreliable\n * across DO↔worker RPC and for wire-decoded twins; a bare code+status shape\n * check lets foreign driver errors ride the client-echo path. The brand\n * (`type === 'VelaError'`, an own enumerable prop that survives serialization)\n * closes both failure modes. Nothing load-bearing may use `instanceof`.\n */\nexport interface VelaErrorLike extends Error {\n type: 'VelaError';\n code: string;\n status: number;\n hint?: string;\n docsUrl?: string;\n data?: unknown;\n}\n\nexport const isVelaError = (error: unknown): error is VelaErrorLike => {\n if (!(error instanceof Error)) return false;\n const candidate = error as Partial<VelaErrorLike>;\n return (\n typeof candidate.code === 'string' &&\n typeof candidate.status === 'number' &&\n candidate.type === 'VelaError'\n );\n};\n","import { CORE_CATALOG, STATUS_TO_CODE, type Catalog } from './catalog';\nimport { isVelaError } from './guard';\n\nexport interface WireErrorObject {\n code: string;\n message: string;\n hint?: string;\n docsUrl?: string;\n details?: unknown;\n}\n\nexport interface ErrorBodyResult {\n body: { error: WireErrorObject };\n status: number;\n redacted: boolean;\n}\n\nexport interface ToErrorBodyOptions {\n /** Composed catalog; defaults to the core catalog. */\n catalog?: Catalog<string>;\n /** Status used for unbranded errors. Default 500. */\n fallbackStatus?: number;\n redactedMessage?: (status: number) => string;\n /** Injectable wire codec for `data` → `details` (bigint/bytes etc.). */\n encodeData?: (data: unknown) => unknown;\n /** Default true. */\n includeHint?: boolean;\n}\n\nconst defaultRedactedMessage = (status: number, catalog: Catalog<string>): string => {\n const code = STATUS_TO_CODE[status];\n return (code && catalog.get(code)?.title) || 'Internal Server Error';\n};\n\n/**\n * THE single wire-redaction seam. Every transport edge (HTTP, WS, live, queue\n * reporting) builds its client-bound error content here, so the invariant\n * \"unbranded or internal-coded errors never echo their message\" holds\n * identically everywhere. `redacted: true` is the caller's signal to log the\n * raw error server-side — this function never logs (zero-dep purity).\n */\nexport const toErrorBody = (error: unknown, options: ToErrorBodyOptions = {}): ErrorBodyResult => {\n const catalog = options.catalog ?? CORE_CATALOG;\n const message = options.redactedMessage ?? ((s: number) => defaultRedactedMessage(s, catalog));\n\n const redact = (status: number, code: string): ErrorBodyResult => ({\n body: { error: { code, message: message(status) } },\n status,\n redacted: true,\n });\n\n if (!isVelaError(error)) {\n const status = options.fallbackStatus ?? 500;\n return redact(status, STATUS_TO_CODE[status] ?? 'internal');\n }\n\n const entry = catalog.get(error.code);\n if (error.code === 'internal' || entry?.internal === true) {\n return redact(error.status, error.code);\n }\n\n const wire: WireErrorObject = { code: error.code, message: error.message };\n const hint = error.hint ?? entry?.hint;\n if (options.includeHint !== false && hint !== undefined) wire.hint = hint;\n const docsUrl = error.docsUrl ?? entry?.docsUrl;\n if (docsUrl !== undefined) wire.docsUrl = docsUrl;\n if (error.data !== undefined)\n wire.details = options.encodeData ? options.encodeData(error.data) : error.data;\n return { body: { error: wire }, status: error.status, redacted: false };\n};\n","import { VelaError } from './error';\n\n/** Throws an internal-coded VelaError — rich in server logs, redacted on the wire. */\nexport function invariant(condition: unknown, message: string, data?: unknown): asserts condition {\n if (!condition) {\n throw new VelaError('internal', { message: `Invariant violation: ${message}`, data });\n }\n}\n\nexport function unreachable(value: never, message = 'unreachable code reached'): never {\n throw new VelaError('internal', { message, data: { value } });\n}\n"],"mappings":";AASA,MAAa,eAAe;CAC1B,aAAa;EAAE,QAAQ;EAAK,OAAO;CAAc;CACjD,cAAc;EAAE,QAAQ;EAAK,OAAO;CAAe;CACnD,WAAW;EAAE,QAAQ;EAAK,OAAO;CAAY;CAC7C,WAAW;EAAE,QAAQ;EAAK,OAAO;CAAY;CAC7C,oBAAoB;EAAE,QAAQ;EAAK,OAAO;CAAqB;CAC/D,UAAU;EAAE,QAAQ;EAAK,OAAO;CAAW;CAC3C,MAAM;EAAE,QAAQ;EAAK,OAAO;CAAO;CACnC,mBAAmB;EAAE,QAAQ;EAAK,OAAO;CAAoB;CAC7D,wBAAwB;EAAE,QAAQ;EAAK,OAAO;CAAyB;CACvE,eAAe;EAAE,QAAQ;EAAK,OAAO;CAAuB;CAC5D,mBAAmB;EAAE,QAAQ;EAAK,OAAO;C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;EACvB,MAAM,SAAS,QAAQ,kBAAkB;EACzC,OAAO,OAAO,QAAQ,eAAe,WAAW,UAAU;CAC5D;CAEA,MAAM,QAAQ,QAAQ,IAAI,MAAM,IAAI;CACpC,IAAI,MAAM,SAAS,cAAc,OAAO,aAAa,MACnD,OAAO,OAAO,MAAM,QAAQ,MAAM,IAAI;CAGxC,MAAM,OAAwB;EAAE,MAAM,MAAM;EAAM,SAAS,MAAM;CAAQ;CACzE,MAAM,OAAO,MAAM,QAAQ,OAAO;CAClC,IAAI,QAAQ,gBAAgB,SAAS,SAAS,KAAA,GAAW,KAAK,OAAO;CACrE,MAAM,UAAU,MAAM,WAAW,OAAO;CACxC,IAAI,YAAY,KAAA,GAAW,KAAK,UAAU;CAC1C,IAAI,MAAM,SAAS,KAAA,GACjB,KAAK,UAAU,QAAQ,aAAa,QAAQ,WAAW,MAAM,IAAI,IAAI,MAAM;CAC7E,OAAO;EAAE,MAAM,EAAE,OAAO,KAAK;EAAG,QAAQ,MAAM;EAAQ,UAAU;CAAM;AACxE;;;;AClEA,SAAgB,UAAU,WAAoB,SAAiB,MAAmC;CAChG,IAAI,CAAC,WACH,MAAM,IAAI,UAAU,YAAY;EAAE,SAAS,wBAAwB;EAAW;CAAK,CAAC;AAExF;AAEA,SAAgB,YAAY,OAAc,UAAU,4BAAmC;CACrF,MAAM,IAAI,UAAU,YAAY;EAAE;EAAS,MAAM,EAAE,MAAM;CAAE,CAAC;AAC9D"}
|
package/package.json
CHANGED
|
@@ -1,53 +1,69 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@velajs/errors",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
4
|
"description": "Unified error layer for Vela: branded VelaError, composable error catalogs, and the single toErrorBody wire-redaction seam",
|
|
5
|
-
"type": "module",
|
|
6
|
-
"main": "./dist/index.js",
|
|
7
|
-
"types": "./dist/index.d.ts",
|
|
8
|
-
"exports": {
|
|
9
|
-
".": {
|
|
10
|
-
"types": "./dist/index.d.ts",
|
|
11
|
-
"import": "./dist/index.js"
|
|
12
|
-
}
|
|
13
|
-
},
|
|
14
|
-
"files": [
|
|
15
|
-
"dist",
|
|
16
|
-
"README.md",
|
|
17
|
-
"LICENSE",
|
|
18
|
-
"CHANGELOG.md"
|
|
19
|
-
],
|
|
20
|
-
"sideEffects": false,
|
|
21
5
|
"keywords": [
|
|
22
|
-
"vela",
|
|
23
|
-
"errors",
|
|
24
6
|
"error-catalog",
|
|
7
|
+
"errors",
|
|
8
|
+
"framework",
|
|
25
9
|
"redaction",
|
|
26
|
-
"
|
|
10
|
+
"vela"
|
|
27
11
|
],
|
|
28
|
-
"
|
|
12
|
+
"homepage": "https://github.com/velajs/errors#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/velajs/errors/issues"
|
|
15
|
+
},
|
|
29
16
|
"license": "MIT",
|
|
17
|
+
"author": "ksh",
|
|
30
18
|
"repository": {
|
|
31
19
|
"type": "git",
|
|
32
20
|
"url": "git+https://github.com/velajs/errors.git"
|
|
33
21
|
},
|
|
34
|
-
"
|
|
35
|
-
|
|
36
|
-
"
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
22
|
+
"files": [
|
|
23
|
+
"dist",
|
|
24
|
+
"README.md",
|
|
25
|
+
"LICENSE",
|
|
26
|
+
"CHANGELOG.md"
|
|
27
|
+
],
|
|
28
|
+
"type": "module",
|
|
29
|
+
"sideEffects": false,
|
|
30
|
+
"main": "./dist/index.js",
|
|
31
|
+
"types": "./dist/index.d.ts",
|
|
32
|
+
"exports": {
|
|
33
|
+
".": {
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"import": "./dist/index.js"
|
|
36
|
+
},
|
|
37
|
+
"./fingerprint": {
|
|
38
|
+
"types": "./dist/fingerprint.d.ts",
|
|
39
|
+
"import": "./dist/fingerprint.js"
|
|
40
|
+
}
|
|
40
41
|
},
|
|
41
42
|
"devDependencies": {
|
|
42
|
-
"@
|
|
43
|
-
"@
|
|
44
|
-
"
|
|
45
|
-
"
|
|
46
|
-
"
|
|
43
|
+
"@arethetypeswrong/cli": "^0.18.5",
|
|
44
|
+
"@changesets/cli": "^2.31.0",
|
|
45
|
+
"oxfmt": "^0.58.0",
|
|
46
|
+
"oxlint": "^1.73.0",
|
|
47
|
+
"publint": "^0.3.21",
|
|
48
|
+
"tsdown": "^0.22.4",
|
|
49
|
+
"typescript": "^7.0.2",
|
|
50
|
+
"vitest": "^4.1.10"
|
|
51
|
+
},
|
|
52
|
+
"engines": {
|
|
53
|
+
"node": ">=24"
|
|
47
54
|
},
|
|
48
55
|
"scripts": {
|
|
49
|
-
"build": "
|
|
56
|
+
"build": "tsdown",
|
|
50
57
|
"test": "vitest run",
|
|
51
|
-
"typecheck": "tsc --noEmit -p tsconfig.test.json"
|
|
58
|
+
"typecheck": "tsc --noEmit -p tsconfig.test.json",
|
|
59
|
+
"lint": "oxlint .",
|
|
60
|
+
"format": "oxfmt .",
|
|
61
|
+
"format:check": "oxfmt --check .",
|
|
62
|
+
"publint": "publint",
|
|
63
|
+
"attw": "attw --pack . --profile esm-only",
|
|
64
|
+
"changeset": "changeset",
|
|
65
|
+
"version-packages": "changeset version",
|
|
66
|
+
"release": "pnpm build && changeset publish",
|
|
67
|
+
"verify": "pnpm lint && pnpm format:check && pnpm build && pnpm typecheck && pnpm test && pnpm publint && pnpm attw"
|
|
52
68
|
}
|
|
53
69
|
}
|
package/dist/catalog-data.d.ts
DELETED
|
@@ -1,76 +0,0 @@
|
|
|
1
|
-
export interface ErrorCatalogEntry {
|
|
2
|
-
status: number;
|
|
3
|
-
title: string;
|
|
4
|
-
hint?: string;
|
|
5
|
-
docsUrl?: string;
|
|
6
|
-
/** Redaction posture: true → message/hint/data are never echoed to clients. */
|
|
7
|
-
internal?: boolean;
|
|
8
|
-
}
|
|
9
|
-
export declare const CORE_ENTRIES: {
|
|
10
|
-
readonly bad_request: {
|
|
11
|
-
readonly status: 400;
|
|
12
|
-
readonly title: "Bad Request";
|
|
13
|
-
};
|
|
14
|
-
readonly unauthorized: {
|
|
15
|
-
readonly status: 401;
|
|
16
|
-
readonly title: "Unauthorized";
|
|
17
|
-
};
|
|
18
|
-
readonly forbidden: {
|
|
19
|
-
readonly status: 403;
|
|
20
|
-
readonly title: "Forbidden";
|
|
21
|
-
};
|
|
22
|
-
readonly not_found: {
|
|
23
|
-
readonly status: 404;
|
|
24
|
-
readonly title: "Not Found";
|
|
25
|
-
};
|
|
26
|
-
readonly method_not_allowed: {
|
|
27
|
-
readonly status: 405;
|
|
28
|
-
readonly title: "Method Not Allowed";
|
|
29
|
-
};
|
|
30
|
-
readonly conflict: {
|
|
31
|
-
readonly status: 409;
|
|
32
|
-
readonly title: "Conflict";
|
|
33
|
-
};
|
|
34
|
-
readonly gone: {
|
|
35
|
-
readonly status: 410;
|
|
36
|
-
readonly title: "Gone";
|
|
37
|
-
};
|
|
38
|
-
readonly payload_too_large: {
|
|
39
|
-
readonly status: 413;
|
|
40
|
-
readonly title: "Payload Too Large";
|
|
41
|
-
};
|
|
42
|
-
readonly unsupported_media_type: {
|
|
43
|
-
readonly status: 415;
|
|
44
|
-
readonly title: "Unsupported Media Type";
|
|
45
|
-
};
|
|
46
|
-
readonly unprocessable: {
|
|
47
|
-
readonly status: 422;
|
|
48
|
-
readonly title: "Unprocessable Entity";
|
|
49
|
-
};
|
|
50
|
-
readonly too_many_requests: {
|
|
51
|
-
readonly status: 429;
|
|
52
|
-
readonly title: "Too Many Requests";
|
|
53
|
-
};
|
|
54
|
-
readonly internal: {
|
|
55
|
-
readonly status: 500;
|
|
56
|
-
readonly title: "Internal Server Error";
|
|
57
|
-
readonly internal: true;
|
|
58
|
-
};
|
|
59
|
-
readonly not_implemented: {
|
|
60
|
-
readonly status: 501;
|
|
61
|
-
readonly title: "Not Implemented";
|
|
62
|
-
};
|
|
63
|
-
readonly bad_gateway: {
|
|
64
|
-
readonly status: 502;
|
|
65
|
-
readonly title: "Bad Gateway";
|
|
66
|
-
};
|
|
67
|
-
readonly service_unavailable: {
|
|
68
|
-
readonly status: 503;
|
|
69
|
-
readonly title: "Service Unavailable";
|
|
70
|
-
};
|
|
71
|
-
readonly gateway_timeout: {
|
|
72
|
-
readonly status: 504;
|
|
73
|
-
readonly title: "Gateway Timeout";
|
|
74
|
-
};
|
|
75
|
-
};
|
|
76
|
-
export type CoreErrorCode = keyof typeof CORE_ENTRIES;
|
package/dist/catalog-data.js
DELETED
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
export const CORE_ENTRIES = {
|
|
2
|
-
bad_request: {
|
|
3
|
-
status: 400,
|
|
4
|
-
title: 'Bad Request'
|
|
5
|
-
},
|
|
6
|
-
unauthorized: {
|
|
7
|
-
status: 401,
|
|
8
|
-
title: 'Unauthorized'
|
|
9
|
-
},
|
|
10
|
-
forbidden: {
|
|
11
|
-
status: 403,
|
|
12
|
-
title: 'Forbidden'
|
|
13
|
-
},
|
|
14
|
-
not_found: {
|
|
15
|
-
status: 404,
|
|
16
|
-
title: 'Not Found'
|
|
17
|
-
},
|
|
18
|
-
method_not_allowed: {
|
|
19
|
-
status: 405,
|
|
20
|
-
title: 'Method Not Allowed'
|
|
21
|
-
},
|
|
22
|
-
conflict: {
|
|
23
|
-
status: 409,
|
|
24
|
-
title: 'Conflict'
|
|
25
|
-
},
|
|
26
|
-
gone: {
|
|
27
|
-
status: 410,
|
|
28
|
-
title: 'Gone'
|
|
29
|
-
},
|
|
30
|
-
payload_too_large: {
|
|
31
|
-
status: 413,
|
|
32
|
-
title: 'Payload Too Large'
|
|
33
|
-
},
|
|
34
|
-
unsupported_media_type: {
|
|
35
|
-
status: 415,
|
|
36
|
-
title: 'Unsupported Media Type'
|
|
37
|
-
},
|
|
38
|
-
unprocessable: {
|
|
39
|
-
status: 422,
|
|
40
|
-
title: 'Unprocessable Entity'
|
|
41
|
-
},
|
|
42
|
-
too_many_requests: {
|
|
43
|
-
status: 429,
|
|
44
|
-
title: 'Too Many Requests'
|
|
45
|
-
},
|
|
46
|
-
internal: {
|
|
47
|
-
status: 500,
|
|
48
|
-
title: 'Internal Server Error',
|
|
49
|
-
internal: true
|
|
50
|
-
},
|
|
51
|
-
not_implemented: {
|
|
52
|
-
status: 501,
|
|
53
|
-
title: 'Not Implemented'
|
|
54
|
-
},
|
|
55
|
-
bad_gateway: {
|
|
56
|
-
status: 502,
|
|
57
|
-
title: 'Bad Gateway'
|
|
58
|
-
},
|
|
59
|
-
service_unavailable: {
|
|
60
|
-
status: 503,
|
|
61
|
-
title: 'Service Unavailable'
|
|
62
|
-
},
|
|
63
|
-
gateway_timeout: {
|
|
64
|
-
status: 504,
|
|
65
|
-
title: 'Gateway Timeout'
|
|
66
|
-
}
|
|
67
|
-
};
|
package/dist/catalog.d.ts
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { type CoreErrorCode, type ErrorCatalogEntry } from './catalog-data';
|
|
2
|
-
import { VelaError, type VelaErrorOptions } from './error';
|
|
3
|
-
export type { CoreErrorCode, ErrorCatalogEntry } from './catalog-data';
|
|
4
|
-
export { CORE_ENTRIES } from './catalog-data';
|
|
5
|
-
export interface Catalog<C extends string = string> {
|
|
6
|
-
readonly entries: Readonly<Record<C, ErrorCatalogEntry>>;
|
|
7
|
-
/** Typed thrower bound to this catalog's defaults. */
|
|
8
|
-
error(code: C | (string & {}), options?: VelaErrorOptions): VelaError;
|
|
9
|
-
has(code: string): boolean;
|
|
10
|
-
get(code: string): ErrorCatalogEntry | undefined;
|
|
11
|
-
}
|
|
12
|
-
export declare const defineErrorCatalog: <const T extends Record<string, ErrorCatalogEntry>>(entries: T) => Catalog<Extract<keyof T, string>>;
|
|
13
|
-
export declare const composeCatalogs: (...catalogs: Array<Catalog<string>>) => Catalog<string>;
|
|
14
|
-
export declare const CORE_CATALOG: Catalog<CoreErrorCode>;
|
|
15
|
-
export declare const STATUS_TO_CODE: Readonly<Record<number, CoreErrorCode>>;
|
package/dist/catalog.js
DELETED
|
@@ -1,37 +0,0 @@
|
|
|
1
|
-
import { CORE_ENTRIES } from "./catalog-data.js";
|
|
2
|
-
import { VelaError } from "./error.js";
|
|
3
|
-
export { CORE_ENTRIES } from "./catalog-data.js";
|
|
4
|
-
const makeCatalog = (entries)=>({
|
|
5
|
-
entries,
|
|
6
|
-
error (code, options = {}) {
|
|
7
|
-
const entry = entries[code];
|
|
8
|
-
return new VelaError(code, {
|
|
9
|
-
...options,
|
|
10
|
-
status: options.status ?? entry?.status ?? 500,
|
|
11
|
-
hint: options.hint ?? entry?.hint,
|
|
12
|
-
docsUrl: options.docsUrl ?? entry?.docsUrl
|
|
13
|
-
});
|
|
14
|
-
},
|
|
15
|
-
has: (code)=>Object.hasOwn(entries, code),
|
|
16
|
-
get: (code)=>Object.hasOwn(entries, code) ? entries[code] : undefined
|
|
17
|
-
});
|
|
18
|
-
export const defineErrorCatalog = (entries)=>makeCatalog(entries);
|
|
19
|
-
export const composeCatalogs = (...catalogs)=>{
|
|
20
|
-
const merged = {};
|
|
21
|
-
for (const catalog of catalogs){
|
|
22
|
-
for (const [code, entry] of Object.entries(catalog.entries)){
|
|
23
|
-
if (Object.hasOwn(merged, code)) {
|
|
24
|
-
throw new VelaError('internal', {
|
|
25
|
-
message: `duplicate error code '${code}' while composing catalogs`
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
merged[code] = entry;
|
|
29
|
-
}
|
|
30
|
-
}
|
|
31
|
-
return makeCatalog(merged);
|
|
32
|
-
};
|
|
33
|
-
export const CORE_CATALOG = makeCatalog(CORE_ENTRIES);
|
|
34
|
-
export const STATUS_TO_CODE = Object.fromEntries(Object.entries(CORE_ENTRIES).map(([code, e])=>[
|
|
35
|
-
e.status,
|
|
36
|
-
code
|
|
37
|
-
]));
|
package/dist/error.d.ts
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import { type CoreErrorCode } from './catalog-data';
|
|
2
|
-
export interface VelaErrorOptions {
|
|
3
|
-
message?: string;
|
|
4
|
-
status?: number;
|
|
5
|
-
hint?: string;
|
|
6
|
-
docsUrl?: string;
|
|
7
|
-
data?: unknown;
|
|
8
|
-
cause?: unknown;
|
|
9
|
-
}
|
|
10
|
-
/**
|
|
11
|
-
* The one Vela error. Every field is an OWN ENUMERABLE property so the error
|
|
12
|
-
* rides any wire codec / structuredClone / DO-RPC prop-copy with no special
|
|
13
|
-
* serialization path. `type` is the brand `isVelaError` checks — it must
|
|
14
|
-
* survive serialization, which own+enumerable guarantees.
|
|
15
|
-
*/
|
|
16
|
-
export declare class VelaError extends Error {
|
|
17
|
-
readonly type = "VelaError";
|
|
18
|
-
readonly code: string;
|
|
19
|
-
readonly status: number;
|
|
20
|
-
readonly hint?: string;
|
|
21
|
-
readonly docsUrl?: string;
|
|
22
|
-
readonly data?: unknown;
|
|
23
|
-
constructor(code: CoreErrorCode, options?: VelaErrorOptions);
|
|
24
|
-
constructor(code: string, options: VelaErrorOptions & {
|
|
25
|
-
status: number;
|
|
26
|
-
});
|
|
27
|
-
}
|
package/dist/error.js
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import { CORE_ENTRIES } from "./catalog-data.js";
|
|
2
|
-
/**
|
|
3
|
-
* The one Vela error. Every field is an OWN ENUMERABLE property so the error
|
|
4
|
-
* rides any wire codec / structuredClone / DO-RPC prop-copy with no special
|
|
5
|
-
* serialization path. `type` is the brand `isVelaError` checks — it must
|
|
6
|
-
* survive serialization, which own+enumerable guarantees.
|
|
7
|
-
*/ export class VelaError extends Error {
|
|
8
|
-
type = 'VelaError';
|
|
9
|
-
code;
|
|
10
|
-
status;
|
|
11
|
-
hint;
|
|
12
|
-
docsUrl;
|
|
13
|
-
data;
|
|
14
|
-
constructor(code, options = {}){
|
|
15
|
-
const entry = CORE_ENTRIES[code];
|
|
16
|
-
super(options.message ?? entry?.title ?? code, options.cause !== undefined ? {
|
|
17
|
-
cause: options.cause
|
|
18
|
-
} : undefined);
|
|
19
|
-
this.name = 'VelaError';
|
|
20
|
-
this.code = code;
|
|
21
|
-
this.status = options.status ?? entry?.status ?? 500;
|
|
22
|
-
if (options.hint ?? entry?.hint) this.hint = options.hint ?? entry?.hint;
|
|
23
|
-
if (options.docsUrl ?? entry?.docsUrl) this.docsUrl = options.docsUrl ?? entry?.docsUrl;
|
|
24
|
-
if (options.data !== undefined) this.data = options.data;
|
|
25
|
-
Object.setPrototypeOf(this, new.target.prototype);
|
|
26
|
-
}
|
|
27
|
-
}
|
package/dist/guard.d.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Structural, realm-safe, BRANDED guard. `instanceof VelaError` is unreliable
|
|
3
|
-
* across DO↔worker RPC and for wire-decoded twins; a bare code+status shape
|
|
4
|
-
* check lets foreign driver errors ride the client-echo path. The brand
|
|
5
|
-
* (`type === 'VelaError'`, an own enumerable prop that survives serialization)
|
|
6
|
-
* closes both failure modes. Nothing load-bearing may use `instanceof`.
|
|
7
|
-
*/
|
|
8
|
-
export interface VelaErrorLike extends Error {
|
|
9
|
-
type: 'VelaError';
|
|
10
|
-
code: string;
|
|
11
|
-
status: number;
|
|
12
|
-
hint?: string;
|
|
13
|
-
docsUrl?: string;
|
|
14
|
-
data?: unknown;
|
|
15
|
-
}
|
|
16
|
-
export declare const isVelaError: (error: unknown) => error is VelaErrorLike;
|
package/dist/guard.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Structural, realm-safe, BRANDED guard. `instanceof VelaError` is unreliable
|
|
3
|
-
* across DO↔worker RPC and for wire-decoded twins; a bare code+status shape
|
|
4
|
-
* check lets foreign driver errors ride the client-echo path. The brand
|
|
5
|
-
* (`type === 'VelaError'`, an own enumerable prop that survives serialization)
|
|
6
|
-
* closes both failure modes. Nothing load-bearing may use `instanceof`.
|
|
7
|
-
*/ export const isVelaError = (error)=>{
|
|
8
|
-
if (!(error instanceof Error)) return false;
|
|
9
|
-
const candidate = error;
|
|
10
|
-
return typeof candidate.code === 'string' && typeof candidate.status === 'number' && candidate.type === 'VelaError';
|
|
11
|
-
};
|
package/dist/invariant.d.ts
DELETED
package/dist/invariant.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { VelaError } from "./error.js";
|
|
2
|
-
/** Throws an internal-coded VelaError — rich in server logs, redacted on the wire. */ export function invariant(condition, message, data) {
|
|
3
|
-
if (!condition) {
|
|
4
|
-
throw new VelaError('internal', {
|
|
5
|
-
message: `Invariant violation: ${message}`,
|
|
6
|
-
data
|
|
7
|
-
});
|
|
8
|
-
}
|
|
9
|
-
}
|
|
10
|
-
export function unreachable(value, message = 'unreachable code reached') {
|
|
11
|
-
throw new VelaError('internal', {
|
|
12
|
-
message,
|
|
13
|
-
data: {
|
|
14
|
-
value
|
|
15
|
-
}
|
|
16
|
-
});
|
|
17
|
-
}
|
package/dist/to-error-body.d.ts
DELETED
|
@@ -1,34 +0,0 @@
|
|
|
1
|
-
import { type Catalog } from './catalog';
|
|
2
|
-
export interface WireErrorObject {
|
|
3
|
-
code: string;
|
|
4
|
-
message: string;
|
|
5
|
-
hint?: string;
|
|
6
|
-
docsUrl?: string;
|
|
7
|
-
details?: unknown;
|
|
8
|
-
}
|
|
9
|
-
export interface ErrorBodyResult {
|
|
10
|
-
body: {
|
|
11
|
-
error: WireErrorObject;
|
|
12
|
-
};
|
|
13
|
-
status: number;
|
|
14
|
-
redacted: boolean;
|
|
15
|
-
}
|
|
16
|
-
export interface ToErrorBodyOptions {
|
|
17
|
-
/** Composed catalog; defaults to the core catalog. */
|
|
18
|
-
catalog?: Catalog<string>;
|
|
19
|
-
/** Status used for unbranded errors. Default 500. */
|
|
20
|
-
fallbackStatus?: number;
|
|
21
|
-
redactedMessage?: (status: number) => string;
|
|
22
|
-
/** Injectable wire codec for `data` → `details` (bigint/bytes etc.). */
|
|
23
|
-
encodeData?: (data: unknown) => unknown;
|
|
24
|
-
/** Default true. */
|
|
25
|
-
includeHint?: boolean;
|
|
26
|
-
}
|
|
27
|
-
/**
|
|
28
|
-
* THE single wire-redaction seam. Every transport edge (HTTP, WS, live, queue
|
|
29
|
-
* reporting) builds its client-bound error content here, so the invariant
|
|
30
|
-
* "unbranded or internal-coded errors never echo their message" holds
|
|
31
|
-
* identically everywhere. `redacted: true` is the caller's signal to log the
|
|
32
|
-
* raw error server-side — this function never logs (zero-dep purity).
|
|
33
|
-
*/
|
|
34
|
-
export declare const toErrorBody: (error: unknown, options?: ToErrorBodyOptions) => ErrorBodyResult;
|
package/dist/to-error-body.js
DELETED
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
import { CORE_CATALOG, STATUS_TO_CODE } from "./catalog.js";
|
|
2
|
-
import { isVelaError } from "./guard.js";
|
|
3
|
-
const defaultRedactedMessage = (status, catalog)=>{
|
|
4
|
-
const code = STATUS_TO_CODE[status];
|
|
5
|
-
return code && catalog.get(code)?.title || 'Internal Server Error';
|
|
6
|
-
};
|
|
7
|
-
/**
|
|
8
|
-
* THE single wire-redaction seam. Every transport edge (HTTP, WS, live, queue
|
|
9
|
-
* reporting) builds its client-bound error content here, so the invariant
|
|
10
|
-
* "unbranded or internal-coded errors never echo their message" holds
|
|
11
|
-
* identically everywhere. `redacted: true` is the caller's signal to log the
|
|
12
|
-
* raw error server-side — this function never logs (zero-dep purity).
|
|
13
|
-
*/ export const toErrorBody = (error, options = {})=>{
|
|
14
|
-
const catalog = options.catalog ?? CORE_CATALOG;
|
|
15
|
-
const message = options.redactedMessage ?? ((s)=>defaultRedactedMessage(s, catalog));
|
|
16
|
-
const redact = (status, code)=>({
|
|
17
|
-
body: {
|
|
18
|
-
error: {
|
|
19
|
-
code,
|
|
20
|
-
message: message(status)
|
|
21
|
-
}
|
|
22
|
-
},
|
|
23
|
-
status,
|
|
24
|
-
redacted: true
|
|
25
|
-
});
|
|
26
|
-
if (!isVelaError(error)) {
|
|
27
|
-
const status = options.fallbackStatus ?? 500;
|
|
28
|
-
return redact(status, STATUS_TO_CODE[status] ?? 'internal');
|
|
29
|
-
}
|
|
30
|
-
const entry = catalog.get(error.code);
|
|
31
|
-
if (error.code === 'internal' || entry?.internal === true) {
|
|
32
|
-
return redact(error.status, error.code);
|
|
33
|
-
}
|
|
34
|
-
const wire = {
|
|
35
|
-
code: error.code,
|
|
36
|
-
message: error.message
|
|
37
|
-
};
|
|
38
|
-
const hint = error.hint ?? entry?.hint;
|
|
39
|
-
if (options.includeHint !== false && hint !== undefined) wire.hint = hint;
|
|
40
|
-
const docsUrl = error.docsUrl ?? entry?.docsUrl;
|
|
41
|
-
if (docsUrl !== undefined) wire.docsUrl = docsUrl;
|
|
42
|
-
if (error.data !== undefined) wire.details = options.encodeData ? options.encodeData(error.data) : error.data;
|
|
43
|
-
return {
|
|
44
|
-
body: {
|
|
45
|
-
error: wire
|
|
46
|
-
},
|
|
47
|
-
status: error.status,
|
|
48
|
-
redacted: false
|
|
49
|
-
};
|
|
50
|
-
};
|