@anizoptera/uuid-slug 0.4.0 → 0.6.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.
Files changed (132) hide show
  1. package/README.md +232 -1062
  2. package/dist/alphabet.d.ts +1 -3
  3. package/dist/alphabet.d.ts.map +1 -1
  4. package/dist/alphabet.js +32 -90
  5. package/dist/alphabet.js.map +1 -1
  6. package/dist/base64url-name.d.ts +1 -3
  7. package/dist/base64url-name.d.ts.map +1 -1
  8. package/dist/base64url-name.js +2 -3
  9. package/dist/errors.d.ts +1 -3
  10. package/dist/errors.d.ts.map +1 -1
  11. package/dist/errors.js +7 -24
  12. package/dist/errors.js.map +1 -1
  13. package/dist/feistel.js +1 -2
  14. package/dist/generation-options.js +2 -3
  15. package/dist/index.d.ts +10 -10
  16. package/dist/index.js +21 -21
  17. package/dist/instant.js +2 -3
  18. package/dist/mask-handle.d.ts +1 -3
  19. package/dist/mask-handle.d.ts.map +1 -1
  20. package/dist/mask-handle.js +19 -17
  21. package/dist/mask-handle.js.map +1 -1
  22. package/dist/mask.d.ts +1 -3
  23. package/dist/mask.d.ts.map +1 -1
  24. package/dist/mask.js +23 -24
  25. package/dist/mask.js.map +1 -1
  26. package/dist/masked-bytes.js +74 -0
  27. package/dist/masked-bytes.js.map +1 -0
  28. package/dist/masking-codec-protocol.js +2 -3
  29. package/dist/masking-codec-types.d.ts +60 -19
  30. package/dist/masking-codec-types.d.ts.map +1 -1
  31. package/dist/masking-codec.d.ts +1 -3
  32. package/dist/masking-codec.d.ts.map +1 -1
  33. package/dist/masking-codec.js +115 -111
  34. package/dist/masking-codec.js.map +1 -1
  35. package/dist/migration.js +39 -40
  36. package/dist/migration.js.map +1 -1
  37. package/dist/node/runtime.js +2 -3
  38. package/dist/payload.d.ts +1 -3
  39. package/dist/payload.d.ts.map +1 -1
  40. package/dist/payload.js +65 -64
  41. package/dist/payload.js.map +1 -1
  42. package/dist/runtime/pool.js +2 -3
  43. package/dist/runtime/portable.js +2 -3
  44. package/dist/runtime/portable.js.map +1 -1
  45. package/dist/sentinel.js +2 -3
  46. package/dist/siphash.js +1 -2
  47. package/dist/slug.d.ts +14 -13
  48. package/dist/slug.d.ts.map +1 -1
  49. package/dist/slug.js +144 -152
  50. package/dist/slug.js.map +1 -1
  51. package/dist/timestamp.d.ts +1 -3
  52. package/dist/timestamp.d.ts.map +1 -1
  53. package/dist/timestamp.js +2 -3
  54. package/dist/types.d.ts +38 -16
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/types.js +2 -3
  57. package/dist/types.js.map +1 -1
  58. package/dist/uuid-value-protocol.js +2 -3
  59. package/dist/uuid-value.d.ts +3 -5
  60. package/dist/uuid-value.d.ts.map +1 -1
  61. package/dist/uuid-value.js +74 -78
  62. package/dist/uuid-value.js.map +1 -1
  63. package/dist/uuid.d.ts +6 -8
  64. package/dist/uuid.d.ts.map +1 -1
  65. package/dist/uuid.js +34 -45
  66. package/dist/uuid.js.map +1 -1
  67. package/dist/v4-slug.d.ts +2 -4
  68. package/dist/v4-slug.d.ts.map +1 -1
  69. package/dist/v4-slug.js +6 -7
  70. package/dist/v4.d.ts +8 -6
  71. package/dist/v4.d.ts.map +1 -1
  72. package/dist/v4.js +3 -9
  73. package/dist/v4.js.map +1 -1
  74. package/dist/v7-bounds.d.ts +3 -5
  75. package/dist/v7-bounds.d.ts.map +1 -1
  76. package/dist/v7-bounds.js +8 -9
  77. package/dist/v7-bounds.js.map +1 -1
  78. package/dist/v7-generator-input.js +10 -11
  79. package/dist/v7-generator-input.js.map +1 -1
  80. package/dist/v7-generator.d.ts +1 -3
  81. package/dist/v7-generator.d.ts.map +1 -1
  82. package/dist/v7-generator.js +13 -14
  83. package/dist/v7-keyless.d.ts +12 -4
  84. package/dist/v7-keyless.d.ts.map +1 -1
  85. package/dist/v7-keyless.js +2 -3
  86. package/dist/v7-keyless.js.map +1 -1
  87. package/dist/v7-payload.js +2 -3
  88. package/dist/v7-slug.d.ts +8 -5
  89. package/dist/v7-slug.d.ts.map +1 -1
  90. package/dist/v7-slug.js +28 -29
  91. package/dist/v7-slug.js.map +1 -1
  92. package/dist/v7-timestamp.js +2 -3
  93. package/dist/v7-value-options.js +2 -3
  94. package/dist/v7-value.d.ts +5 -8
  95. package/dist/v7-value.d.ts.map +1 -1
  96. package/dist/v7-value.js +10 -11
  97. package/dist/v7-value.js.map +1 -1
  98. package/dist/v7.js +16 -17
  99. package/dist/v7.js.map +1 -1
  100. package/package.json +6 -4
  101. package/src/alphabet.ts +84 -239
  102. package/src/errors.ts +30 -43
  103. package/src/feistel.ts +4 -4
  104. package/src/generation-options.ts +1 -1
  105. package/src/index.ts +3 -0
  106. package/src/mask-handle.ts +7 -11
  107. package/src/mask.ts +16 -14
  108. package/src/masked-bytes.ts +203 -0
  109. package/src/masking-codec-protocol.ts +1 -1
  110. package/src/masking-codec-types.ts +124 -24
  111. package/src/masking-codec.ts +44 -43
  112. package/src/migration.ts +8 -7
  113. package/src/payload.ts +71 -53
  114. package/src/runtime/bun.ts +1 -1
  115. package/src/runtime/node.ts +2 -2
  116. package/src/runtime/pool.ts +1 -1
  117. package/src/runtime/portable.ts +3 -3
  118. package/src/runtime/types.ts +2 -4
  119. package/src/slug.ts +45 -54
  120. package/src/types.ts +108 -17
  121. package/src/uuid-value-protocol.ts +1 -1
  122. package/src/uuid-value.ts +3 -10
  123. package/src/uuid.ts +27 -41
  124. package/src/v4.ts +14 -11
  125. package/src/v7-bounds.ts +7 -5
  126. package/src/v7-generator-input.ts +4 -7
  127. package/src/v7-generator.ts +2 -2
  128. package/src/v7-keyless.ts +35 -6
  129. package/src/v7-payload.ts +1 -1
  130. package/src/v7-slug.ts +21 -2
  131. package/src/v7-value.ts +9 -4
  132. package/src/v7.ts +27 -1
package/src/alphabet.ts CHANGED
@@ -10,10 +10,18 @@ import type { Latin1Scratch } from "./runtime/types.ts";
10
10
  export const BASE32HEX_NAME = "base32hex";
11
11
  export { BASE64URL_NAME } from "./base64url-name.ts";
12
12
 
13
+ /** Follows the alphabet name in every decoder error for set unused bits. */
14
+ const NON_CANONICAL_TRAILING_BITS = " value has non-canonical trailing bits";
15
+
13
16
  /**
14
17
  * A power-of-two alphabet plus its reverse lookup. Encoding is pure bit packing, so the only
15
- * character set and bits per character define the wire format. Fixed UUID writers specialize
16
- * that format; the generic accumulator uses the same tables for other payload lengths.
18
+ * character set and bits per character define the wire format.
19
+ *
20
+ * Every slug holds exactly one 16-byte UUID, plus an optional 4-bit masked check tail, so the
21
+ * writers and readers below handle only that shape, with no any-length bit accumulator or native
22
+ * `toBase64` delegation behind them: nothing calls another shape. A new payload length needs its
23
+ * own fixed path, because the generic loop measured slower on every engine (bench/decisions.md
24
+ * §Fixed-size portable base64url encoding and its siblings).
17
25
  */
18
26
  export interface Alphabet {
19
27
  readonly bitsPerChar: number;
@@ -73,18 +81,6 @@ export const BASE32HEX: Alphabet = /*#__PURE__*/ alphabet(
73
81
  true,
74
82
  );
75
83
 
76
- // Native encoding is strict on output; decoding stays here because it must reject aliases,
77
- // whitespace and nonzero padding that platform decoders may accept.
78
- const denoVersion = (globalThis as { Deno?: { version?: { deno?: string } } }).Deno?.version?.deno;
79
- const availableNativeToBase64 = (
80
- Uint8Array.prototype as {
81
- toBase64?: (options: { alphabet: typeof BASE64URL_NAME; omitPadding: boolean }) => string;
82
- }
83
- ).toBase64;
84
- // Deno 2.9.6 implements this capability but takes longer than the fixed 16-byte encoder. Treat
85
- // that implementation as unavailable until a Deno update overturns the repeated public-route result.
86
- const nativeToBase64 = denoVersion === undefined ? availableNativeToBase64 : undefined;
87
- const BASE64_OPTIONS = { alphabet: BASE64URL_NAME, omitPadding: true } as const;
88
84
  const createLatin1Scratch = runtime.latin1Scratch;
89
85
  let base64urlScratch: Latin1Scratch | undefined;
90
86
  let base32hexScratch: Latin1Scratch | undefined;
@@ -97,18 +93,6 @@ function characterCodes(alpha: Alphabet): Uint8Array {
97
93
  return Uint8Array.from(alpha.chars, (character) => character.charCodeAt(0));
98
94
  }
99
95
 
100
- /**
101
- * Bits left over when `byteLength` bytes are written in this alphabet. A slug rounds up to whole
102
- * characters, so the final character has spare low bits that carry no data: 4 for 16 bytes in
103
- * base64url (22 chars = 132 bits), 2 in base32hex (26 chars = 130 bits). Callers may spend them
104
- * on a trailing value at zero cost in length — see `encode`.
105
- */
106
- /*#__NO_SIDE_EFFECTS__*/
107
- export function spareBits(alpha: Alphabet, byteLength: number): number {
108
- const bits = byteLength * 8;
109
- return (alpha.bitsPerChar - (bits % alpha.bitsPerChar)) % alpha.bitsPerChar;
110
- }
111
-
112
96
  /** Boolean validation needs no output buffer or diagnostic allocation. */
113
97
  /*#__NO_SIDE_EFFECTS__*/
114
98
  export function isEncoded(
@@ -150,42 +134,20 @@ function firstInvalidCharacter(alpha: Alphabet, value: string): UuidSlugError {
150
134
  }
151
135
 
152
136
  /**
153
- * Pack bytes, optionally followed by `tailBits` low bits of `tail`, into `alpha`.
154
- *
155
- * `tailBits` MUST NOT exceed `spareBits`, otherwise the result grows a character. Passing
156
- * `tail = 0` reproduces a plain encoding byte for byte, which is what keeps identifiers issued
157
- * before the tail existed valid afterwards.
137
+ * Pack one 16-byte UUID payload, optionally followed by the 4-bit masked check `tail`, into `alpha`:
138
+ * 22 base64url characters either way (the tail fills the final character's spare bits), or 26
139
+ * base32hex characters plain and 27 masked. With `tailBits = 0`, `tail` must be 0: that keeps a
140
+ * plain encoding byte for byte equal to the identifiers issued before the tail existed.
158
141
  */
159
142
  /*#__NO_SIDE_EFFECTS__*/
160
- export function encode(bytes: Uint8Array, alpha: Alphabet, tail = 0, tailBits = 0): string {
161
- if (createLatin1Scratch && bytes.length === 16) {
162
- if (alpha === BASE64URL && (tailBits === 0 || tailBits === 4))
163
- return encodeBase64urlLatin1(createLatin1Scratch, bytes, tail);
164
- if (alpha === BASE32HEX && (tailBits === 0 || tailBits === 2 || tailBits === 4))
165
- return encodeBase32hexLatin1(createLatin1Scratch, bytes, tail, tailBits);
166
- }
167
- if (bytes.length === 16) {
168
- if (alpha === BASE64URL && (tailBits === 0 || tailBits === 4))
169
- return writeBase64url(bytes, (base64urlCodes ??= characterCodes(BASE64URL)), tail);
170
- if (alpha === BASE32HEX && (tailBits === 0 || tailBits === 2 || tailBits === 4))
171
- return writeBase32hex(bytes, (base32hexCodes ??= characterCodes(BASE32HEX)), tail, tailBits);
172
- }
173
- if (
174
- nativeToBase64 &&
175
- alpha === BASE64URL &&
176
- tailBits >= 0 &&
177
- tailBits <= spareBits(alpha, bytes.length)
178
- ) {
179
- const encoded = nativeToBase64.call(bytes, BASE64_OPTIONS);
180
- if (tailBits === 0) return encoded;
181
- // The native result zeroes padding. Spend only those spare low bits on the mask check;
182
- // replacing the final character leaves the UUID payload and the wire length unchanged.
183
- const last = encoded.length - 1;
184
- const digit = alpha.decode[encoded.charCodeAt(last)] as number;
185
- const trailing = (tail & ((1 << tailBits) - 1)) << (spareBits(alpha, bytes.length) - tailBits);
186
- return encoded.slice(0, last) + alpha.chars[digit | trailing];
187
- }
188
- return encodePortable(bytes, alpha, tail, tailBits);
143
+ export function encode(bytes: Uint8Array, alpha: Alphabet, tail = 0, tailBits: 0 | 4 = 0): string {
144
+ if (createLatin1Scratch)
145
+ return alpha === BASE64URL
146
+ ? encodeBase64urlLatin1(createLatin1Scratch, bytes, tail)
147
+ : encodeBase32hexLatin1(createLatin1Scratch, bytes, tail, tailBits);
148
+ return alpha === BASE64URL
149
+ ? writeBase64url(bytes, (base64urlCodes ??= characterCodes(BASE64URL)), tail)
150
+ : writeBase32hex(bytes, (base32hexCodes ??= characterCodes(BASE32HEX)), tail, tailBits);
189
151
  }
190
152
 
191
153
  /**
@@ -226,7 +188,7 @@ function encodeBase32hexLatin1(
226
188
  create: NonNullable<typeof createLatin1Scratch>,
227
189
  bytes: Uint8Array,
228
190
  tail: number,
229
- tailBits: number,
191
+ tailBits: 0 | 4,
230
192
  ): string {
231
193
  const scratch =
232
194
  tailBits === 4 ? (maskedBase32hexScratch ??= create(27)) : (base32hexScratch ??= create(26));
@@ -256,119 +218,34 @@ function encodeBase32hexLatin1(
256
218
  return scratch.text();
257
219
  }
258
220
 
259
- /** Encode without runtime-native delegation so fallback performance can be measured directly. */
260
- /*#__NO_SIDE_EFFECTS__*/
261
- export function encodePortable(bytes: Uint8Array, alpha: Alphabet, tail = 0, tailBits = 0): string {
262
- // UUID routes always encode one 16-byte block. Fixed groups remove the generic accumulator;
263
- // keep the generic path for every other supported shape and tail width.
264
- if (alpha === BASE64URL && bytes.length === 16 && (tailBits === 0 || tailBits === 4)) {
265
- let encoded = "";
266
- for (let offset = 0; offset < 15; offset += 3) {
267
- const block =
268
- ((bytes[offset] as number) << 16) |
269
- ((bytes[offset + 1] as number) << 8) |
270
- (bytes[offset + 2] as number);
271
- encoded +=
272
- (alpha.chars[block >>> 18] as string) +
273
- (alpha.chars[(block >>> 12) & 63] as string) +
274
- (alpha.chars[(block >>> 6) & 63] as string) +
275
- (alpha.chars[block & 63] as string);
276
- }
277
- const last = bytes[15] as number;
278
- return (
279
- encoded +
280
- (alpha.chars[last >>> 2] as string) +
281
- (alpha.chars[((last & 3) << 4) | (tail & 15)] as string)
282
- );
283
- }
284
- if (
285
- alpha === BASE32HEX &&
286
- bytes.length === 16 &&
287
- (tailBits === 0 || tailBits === 2 || tailBits === 4)
288
- ) {
289
- let encoded = "";
290
- const chars = alpha.chars;
291
- for (let offset = 0; offset < 15; offset += 5) {
292
- const a = bytes[offset] as number;
293
- const b = bytes[offset + 1] as number;
294
- const c = bytes[offset + 2] as number;
295
- const d = bytes[offset + 3] as number;
296
- const e = bytes[offset + 4] as number;
297
- encoded +=
298
- (chars[a >>> 3] as string) +
299
- (chars[((a & 7) << 2) | (b >>> 6)] as string) +
300
- (chars[(b >>> 1) & 31] as string) +
301
- (chars[((b & 1) << 4) | (c >>> 4)] as string) +
302
- (chars[((c & 15) << 1) | (d >>> 7)] as string) +
303
- (chars[(d >>> 2) & 31] as string) +
304
- (chars[((d & 3) << 3) | (e >>> 5)] as string) +
305
- (chars[e & 31] as string);
306
- }
307
- const last = bytes[15] as number;
308
- if (tailBits === 4)
309
- return (
310
- encoded +
311
- chars[last >>> 3] +
312
- chars[((last & 7) << 2) | ((tail >>> 2) & 3)] +
313
- chars[(tail & 3) << 3]
314
- );
315
- return encoded + chars[last >>> 3] + chars[((last & 7) << 2) | (tail & 3)];
316
- }
317
- const { bitsPerChar, chars } = alpha;
318
- const mask = (1 << bitsPerChar) - 1;
319
- let out = "";
320
- let acc = 0;
321
- let bits = 0;
322
- for (let i = 0; i < bytes.length; i += 1) {
323
- // At most bitsPerChar-1 bits are held over, so `acc` peaks at 13 bits and stays in int32.
324
- acc = (acc << 8) | (bytes[i] as number);
325
- bits += 8;
326
- while (bits >= bitsPerChar) {
327
- bits -= bitsPerChar;
328
- out += chars[(acc >>> bits) & mask];
329
- }
330
- }
331
- if (tailBits > 0) {
332
- acc = (acc << tailBits) | (tail & ((1 << tailBits) - 1));
333
- bits += tailBits;
334
- while (bits >= bitsPerChar) {
335
- bits -= bitsPerChar;
336
- out += chars[(acc >>> bits) & mask];
337
- }
338
- }
339
- if (bits > 0) out += chars[(acc << (bitsPerChar - bits)) & mask];
340
- return out;
341
- }
342
-
343
221
  /**
344
- * Inverse of `encode`, writing into a caller-owned buffer so the slug paths need no intermediate
345
- * allocation. Returns the trailing value (0 when `tailBits` is 0), or an Error.
222
+ * Inverse of `encode`: write one 16-byte UUID payload into a caller-owned buffer so the slug paths
223
+ * need no intermediate allocation. Returns the trailing value (0 when `tailBits` is 0), or an Error.
346
224
  *
347
225
  * Rejects any character outside the alphabet, and any padding bit that is not zero. Without that
348
226
  * last check one identifier would have several valid spellings, so a corrupted slug could decode
349
- * successfully instead of being refused.
227
+ * successfully instead of being refused. Platform base64 decoders are not used for the same reason:
228
+ * they may accept whitespace, padding or nonzero trailing bits.
350
229
  */
351
230
  export function decodeInto(
352
231
  value: string,
353
232
  alpha: Alphabet,
354
233
  out: Uint8Array,
355
234
  offset: number,
356
- byteLength: number,
357
- tailBits = 0,
235
+ tailBits: 0 | 4 = 0,
358
236
  ): number | UuidSlugError {
359
237
  const { bitsPerChar, decode: table, code, name } = alpha;
360
- const expected = Math.ceil((byteLength * 8 + tailBits) / bitsPerChar);
238
+ const expected = Math.ceil((128 + tailBits) / bitsPerChar);
361
239
  if (value.length !== expected)
362
240
  return new UuidSlugError(code, `Expected ${expected} ${name} characters, got ${value.length}.`);
363
- const badRange = checkRange(out.length, offset, byteLength);
241
+ const badRange = checkRange(out.length, offset, 16);
364
242
  if (badRange) return badRange;
365
243
 
366
- // UUID base64url has five complete groups and one byte. Decode that fixed wire shape directly;
367
- // keep the accumulator below for every other byte length, alphabet, and tail width.
368
- // Fixed paths check every character once after the loop: ORing the codes exposes any code
244
+ // Base64url: five complete four-character groups and one byte.
245
+ // Both paths check every character once after the loop: ORing the codes exposes any code
369
246
  // above 127, whose low bits the table read would alias, and ORing the digits turns any -1
370
- // negative. A branch per character was slower on Node and Bun (bench/PERFORMANCE.md).
371
- if (alpha === BASE64URL && byteLength === 16 && (tailBits === 0 || tailBits === 4)) {
247
+ // negative. A branch per character was slower on Node and Bun (bench/decisions.md).
248
+ if (alpha === BASE64URL) {
372
249
  let codes = 0;
373
250
  let digits = 0;
374
251
  let written = offset;
@@ -402,96 +279,64 @@ export function decodeInto(
402
279
  if ((last & 15) !== 0)
403
280
  return new UuidSlugError(
404
281
  code,
405
- `${name} value has non-canonical trailing bits; a masked slug of this length decodes only through its codec.`,
282
+ `${name}${NON_CANONICAL_TRAILING_BITS}; a masked slug of this length decodes only through its codec.`,
406
283
  );
407
284
  return 0;
408
285
  }
409
286
 
410
- // UUID base32hex has three complete eight-character groups and one byte; a 4-bit masked tail adds
411
- // a 27th character. Fixed byte formulas remove the general accumulator and its length guards.
412
- if (
413
- alpha === BASE32HEX &&
414
- byteLength === 16 &&
415
- (tailBits === 0 || tailBits === 2 || tailBits === 4)
416
- ) {
417
- let codes = 0;
418
- let digits = 0;
419
- let written = offset;
420
- for (let start = 0; start < 24; start += 8) {
421
- // Eight 5-bit digits exceed int32, so each byte is assembled from the digits it spans.
422
- const d0 = value.charCodeAt(start);
423
- const d1 = value.charCodeAt(start + 1);
424
- const d2 = value.charCodeAt(start + 2);
425
- const d3 = value.charCodeAt(start + 3);
426
- const d4 = value.charCodeAt(start + 4);
427
- const d5 = value.charCodeAt(start + 5);
428
- const d6 = value.charCodeAt(start + 6);
429
- const d7 = value.charCodeAt(start + 7);
430
- codes |= d0 | d1 | d2 | d3 | d4 | d5 | d6 | d7;
431
- const v0 = table[d0 & 127] as number;
432
- const v1 = table[d1 & 127] as number;
433
- const v2 = table[d2 & 127] as number;
434
- const v3 = table[d3 & 127] as number;
435
- const v4 = table[d4 & 127] as number;
436
- const v5 = table[d5 & 127] as number;
437
- const v6 = table[d6 & 127] as number;
438
- const v7 = table[d7 & 127] as number;
439
- digits |= v0 | v1 | v2 | v3 | v4 | v5 | v6 | v7;
440
- out[written] = (v0 << 3) | (v1 >>> 2);
441
- out[written + 1] = (v1 << 6) | (v2 << 1) | (v3 >>> 4);
442
- out[written + 2] = (v3 << 4) | (v4 >>> 1);
443
- out[written + 3] = (v4 << 7) | (v5 << 2) | (v6 >>> 3);
444
- out[written + 4] = (v6 << 5) | v7;
445
- written += 5;
446
- }
447
- const firstCode = value.charCodeAt(24);
448
- const lastCode = value.charCodeAt(25);
449
- // Only a 27-character value has this code; reading past a 26-character value would return NaN.
450
- const paddingCode = tailBits === 4 ? value.charCodeAt(26) : 48;
451
- const first = table[firstCode & 127] as number;
452
- const last = table[lastCode & 127] as number;
453
- const padding = table[paddingCode & 127] as number;
454
- if ((codes | firstCode | lastCode | paddingCode) > 127 || (digits | first | last | padding) < 0)
455
- return firstInvalidCharacter(alpha, value);
456
- out[written] = (first << 3) | (last >>> 2);
457
- if (tailBits === 4) {
458
- if ((padding & 7) !== 0)
459
- return new UuidSlugError(code, `${name} value has non-canonical trailing bits.`);
460
- return ((last & 3) << 2) | (padding >>> 3);
461
- }
462
- if (tailBits === 2) return last & 3;
463
- if ((last & 3) !== 0)
464
- return new UuidSlugError(code, `${name} value has non-canonical trailing bits.`);
465
- return 0;
466
- }
467
-
468
- let acc = 0;
469
- let bits = 0;
470
- let written = 0;
471
- for (let i = 0; i < value.length; i += 1) {
472
- const charCode = value.charCodeAt(i);
473
- const digit = charCode < 128 ? (table[charCode] as number) : -1;
474
- if (digit < 0) return invalidCharacter(alpha, value, i);
475
- acc = (acc << bitsPerChar) | digit;
476
- bits += bitsPerChar;
477
- while (bits >= 8 && written < byteLength) {
478
- bits -= 8;
479
- out[offset + written] = (acc >>> bits) & 0xff;
480
- written += 1;
481
- }
287
+ // Base32hex: three complete eight-character groups and one byte; a 4-bit masked tail adds a
288
+ // 27th character.
289
+ let codes = 0;
290
+ let digits = 0;
291
+ let written = offset;
292
+ for (let start = 0; start < 24; start += 8) {
293
+ // Eight 5-bit digits exceed int32, so each byte is assembled from the digits it spans.
294
+ const d0 = value.charCodeAt(start);
295
+ const d1 = value.charCodeAt(start + 1);
296
+ const d2 = value.charCodeAt(start + 2);
297
+ const d3 = value.charCodeAt(start + 3);
298
+ const d4 = value.charCodeAt(start + 4);
299
+ const d5 = value.charCodeAt(start + 5);
300
+ const d6 = value.charCodeAt(start + 6);
301
+ const d7 = value.charCodeAt(start + 7);
302
+ codes |= d0 | d1 | d2 | d3 | d4 | d5 | d6 | d7;
303
+ const v0 = table[d0 & 127] as number;
304
+ const v1 = table[d1 & 127] as number;
305
+ const v2 = table[d2 & 127] as number;
306
+ const v3 = table[d3 & 127] as number;
307
+ const v4 = table[d4 & 127] as number;
308
+ const v5 = table[d5 & 127] as number;
309
+ const v6 = table[d6 & 127] as number;
310
+ const v7 = table[d7 & 127] as number;
311
+ digits |= v0 | v1 | v2 | v3 | v4 | v5 | v6 | v7;
312
+ out[written] = (v0 << 3) | (v1 >>> 2);
313
+ out[written + 1] = (v1 << 6) | (v2 << 1) | (v3 >>> 4);
314
+ out[written + 2] = (v3 << 4) | (v4 >>> 1);
315
+ out[written + 3] = (v4 << 7) | (v5 << 2) | (v6 >>> 3);
316
+ out[written + 4] = (v6 << 5) | v7;
317
+ written += 5;
482
318
  }
483
- let tail = 0;
484
- if (tailBits > 0) {
485
- bits -= tailBits;
486
- tail = (acc >>> bits) & ((1 << tailBits) - 1);
319
+ const firstCode = value.charCodeAt(24);
320
+ const lastCode = value.charCodeAt(25);
321
+ // Only a 27-character value has this code; reading past a 26-character value would return NaN.
322
+ const paddingCode = tailBits === 4 ? value.charCodeAt(26) : 48;
323
+ const first = table[firstCode & 127] as number;
324
+ const last = table[lastCode & 127] as number;
325
+ const padding = table[paddingCode & 127] as number;
326
+ if ((codes | firstCode | lastCode | paddingCode) > 127 || (digits | first | last | padding) < 0)
327
+ return firstInvalidCharacter(alpha, value);
328
+ out[written] = (first << 3) | (last >>> 2);
329
+ if (tailBits === 4) {
330
+ if ((padding & 7) !== 0)
331
+ return new UuidSlugError(code, `${name}${NON_CANONICAL_TRAILING_BITS}.`);
332
+ return ((last & 3) << 2) | (padding >>> 3);
487
333
  }
488
- if (bits > 0 && (acc & ((1 << bits) - 1)) !== 0)
489
- return new UuidSlugError(code, `${name} value has non-canonical trailing bits.`);
490
- return tail;
334
+ if ((last & 3) !== 0) return new UuidSlugError(code, `${name}${NON_CANONICAL_TRAILING_BITS}.`);
335
+ return 0;
491
336
  }
492
337
 
493
338
  // Fixed 16-byte groups avoid per-character concatenation and temporary text buffers on V8.
494
- // Bun keeps its Latin-1 writer; remeasure after engine changes (bench/PERFORMANCE.md).
339
+ // Bun keeps its Latin-1 writer; remeasure after engine changes (bench/decisions.md).
495
340
  // Character tables belong to the alphabet owner; callers select only supported tail widths.
496
341
  /*#__NO_SIDE_EFFECTS__*/
497
342
  function writeBase64url(bytes: Uint8Array, codes: Uint8Array, tail: number): string {
@@ -532,7 +377,7 @@ function writeBase32hex(
532
377
  bytes: Uint8Array,
533
378
  codes: Uint8Array,
534
379
  tail: number,
535
- tailBits: number,
380
+ tailBits: 0 | 4,
536
381
  ): string {
537
382
  const a = bytes[0] as number,
538
383
  b = bytes[1] as number,
package/src/errors.ts CHANGED
@@ -119,12 +119,12 @@ export class UuidSlugError extends Error {
119
119
 
120
120
  // One immutable prototype property avoids adding storage to every error while preserving the same
121
121
  // marker across realms and duplicate package copies. Remeasure if supported engines change their
122
- // prototype-property access or Error layout; benchmark evidence belongs in bench/PERFORMANCE.md.
122
+ // prototype-property access or Error layout; benchmark evidence belongs in bench/decisions.md.
123
123
  Object.defineProperty(UuidSlugError.prototype, ERROR_MARKER, { value: true });
124
124
 
125
125
  // Keep local identity before the costlier cross-realm capability, but isolate the probes: a proxy
126
126
  // that blocks one operation must not suppress a later independent one. Remeasure if Error branding
127
- // or inlining changes in a supported engine; results and statistical limits live in PERFORMANCE.md.
127
+ // or inlining changes in a supported engine; results and statistical limits live in bench/decisions.md.
128
128
  /*#__NO_SIDE_EFFECTS__*/
129
129
  function hasErrorBrand(candidate: object): boolean {
130
130
  try {
@@ -180,16 +180,9 @@ export function exactLocalUuidBytes(value: unknown): Uint8Array | undefined {
180
180
  }
181
181
  }
182
182
 
183
- /** Recognize local Errors first, then use native or portable cross-realm recognition. */
184
- /*#__NO_SIDE_EFFECTS__*/
185
- export function isError(value: unknown): value is Error {
186
- if (typeof value !== OBJECT_TYPE || value === null) return false;
187
- return hasErrorBrand(value as object);
188
- }
189
-
190
183
  // A slot probe is the only proof of a genuine buffer, but calling one on anything else
191
184
  // throws, and building that native TypeError costs three orders of magnitude more than the checks
192
- // below (bench/PERFORMANCE.md). For buffers, local identity answers the common case without reading
185
+ // below (bench/decisions.md). For buffers, local identity answers the common case without reading
193
186
  // the tag at all; the tag then recognizes another realm's value. The tag is caller-visible, so a value
194
187
  // carrying its own Symbol.toStringTag still reaches the probe and keeps its acceptance, and that
195
188
  // own-property lookup runs only after the tag misses. Only a value whose realm re-tagged the
@@ -218,16 +211,29 @@ export function stringInput(value: unknown): string | undefined {
218
211
  }
219
212
  }
220
213
 
221
- /** Normalize UUID string input while preserving a preceding package failure. */
214
+ /**
215
+ * Normalize UUID string input while preserving a preceding package failure. No `typeof` fast path:
216
+ * every caller tests for a primitive string before calling, and `stringInput` accepts one anyway.
217
+ */
222
218
  export function normalizeUuidStringInput(value: unknown): string | UuidSlugError {
223
- if (typeof value === "string") return value;
224
- return stringInput(value) ?? invalidUuidStringInput(value);
219
+ return (
220
+ stringInput(value) ??
221
+ (isUuidSlugError(value) ? value : new UuidSlugError(INVALID_UUID, "UUID must be text."))
222
+ );
225
223
  }
226
224
 
227
- /** Normalize slug input while preserving a preceding package failure. */
225
+ /**
226
+ * Normalize slug input while preserving a preceding package failure. Codec and migration callers pass
227
+ * strings unchecked, so the `typeof` fast path stays.
228
+ */
228
229
  export function normalizeUuidSlugInput(value: unknown): string | UuidSlugError {
229
230
  if (typeof value === "string") return value;
230
- return stringInput(value) ?? invalidUuidSlugInput(value);
231
+ return (
232
+ stringInput(value) ??
233
+ (isUuidSlugError(value)
234
+ ? value
235
+ : new UuidSlugError(INVALID_UUID_SLUG, "UUID slug must be a string."))
236
+ );
231
237
  }
232
238
 
233
239
  /** Describe rejected values without executing object coercion or inspecting caller properties. */
@@ -355,27 +361,14 @@ export function checkByteRange(
355
361
  return checkRange(bytes.length, offset, need);
356
362
  }
357
363
 
358
- /** Preserve a preceding failure or reject an untyped value that is not UUID text. */
359
- /*#__NO_SIDE_EFFECTS__*/
360
- export function invalidUuidStringInput(value: unknown): UuidSlugError {
361
- return isUuidSlugError(value) ? value : new UuidSlugError(INVALID_UUID, "UUID must be text.");
362
- }
363
-
364
- /** Preserve a preceding failure or reject an untyped value that is not a UUID slug. */
365
- /*#__NO_SIDE_EFFECTS__*/
366
- export function invalidUuidSlugInput(value: unknown): UuidSlugError {
367
- return isUuidSlugError(value)
368
- ? value
369
- : new UuidSlugError(INVALID_UUID_SLUG, "UUID slug must be a string.");
370
- }
371
-
372
364
  /** Preserve failures from an injected or platform entropy source without changing successful draws. */
373
365
  export const randomFailure = /* @__NO_SIDE_EFFECTS__ */ (
374
366
  value: unknown,
375
367
  ): undefined | UuidSlugError => {
376
368
  if (value === undefined) return undefined;
377
369
  if (isUuidSlugError(value)) return value;
378
- return isError(value)
370
+ // Local Errors first, then native or portable cross-realm recognition.
371
+ return typeof value === OBJECT_TYPE && value !== null && hasErrorBrand(value)
379
372
  ? new UuidSlugError(RNG_UNAVAILABLE, RANDOM_FAILURE_MESSAGE, { cause: value })
380
373
  : undefined;
381
374
  };
@@ -401,18 +394,6 @@ export function generatedOrThrow<Value>(result: Value | UuidSlugError): Value {
401
394
  return result;
402
395
  }
403
396
 
404
- /** Keep both failed implementations inspectable when an optional native shortcut also fails. */
405
- /*#__NO_SIDE_EFFECTS__*/
406
- export function failedFallback(
407
- nativeCause: unknown,
408
- fallback: UuidSlugError,
409
- message: string,
410
- ): UuidSlugError {
411
- return new UuidSlugError(fallback.code, fallback.message, {
412
- cause: new AggregateError([nativeCause, fallback], message),
413
- });
414
- }
415
-
416
397
  /** Run the portable generator once after native generation failed; dual failures keep both causes. */
417
398
  export function portableAfterNative<FallbackArgument>(
418
399
  nativeCause: unknown,
@@ -422,7 +403,13 @@ export function portableAfterNative<FallbackArgument>(
422
403
  ): string | UuidSlugError {
423
404
  const result = fallback(fallbackArgument);
424
405
  return result instanceof Error
425
- ? failedFallback(nativeCause, result, `Native and portable ${operation} failed.`)
406
+ ? // Keep both failed implementations inspectable.
407
+ new UuidSlugError(result.code, result.message, {
408
+ cause: new AggregateError(
409
+ [nativeCause, result],
410
+ `Native and portable ${operation} failed.`,
411
+ ),
412
+ })
426
413
  : result;
427
414
  }
428
415
 
package/src/feistel.ts CHANGED
@@ -16,9 +16,9 @@ const ROUNDS = 4;
16
16
  export const FEISTEL_KEY_WORDS = ROUNDS * 2;
17
17
 
18
18
  /**
19
- * The `lowbias32` finalizer: an integer hash with near-ideal avalanche for its size. No longer the
20
- * round function — see above — but still what `mask.ts` derives its check tag with, where the input
21
- * is public and an unkeyed mixer is the right tool.
19
+ * The `lowbias32` finalizer: an integer hash with near-ideal avalanche for its size.
20
+ * `payload.ts` derives its check tag with it: the input is public, so an unkeyed mixer suffices
21
+ * (the keyed round function is HalfSipHash, above).
22
22
  */
23
23
  /*#__NO_SIDE_EFFECTS__*/
24
24
  export function mix32(value: number): number {
@@ -70,7 +70,7 @@ export function feistel16(
70
70
  const key = (direction === "mask" ? round : ROUNDS - 1 - round) * 2;
71
71
  // The round function is `halfSipHash(keys[key], keys[key + 1], [right0, right1], 8)`, written
72
72
  // out for its fixed two-word message: the call through word arrays cost about a fifth more of
73
- // the network on Node and Bun (bench/PERFORMANCE.md). The fixed vector in `feistel.test.ts`
73
+ // the network on Node and Bun (bench/decisions.md). The fixed vector in `feistel.test.ts`
74
74
  // and the wire-format vectors hold it to issued slugs.
75
75
  const key0 = keys[key] as number;
76
76
  const key1 = keys[key + 1] as number;
@@ -28,7 +28,7 @@ export function readGenerationOptions(
28
28
  return new UuidSlugError(INVALID_OPTIONS, `Unknown ${operation} option: ${unknown}.`);
29
29
  const source = options as GenerationOptionValues;
30
30
  // Direct assignments build one object; a conditional spread per option allocated a temporary
31
- // object for each (bench/PERFORMANCE.md). Each accepted own property is read once, in this
31
+ // object for each (bench/decisions.md). Each accepted own property is read once, in this
32
32
  // order. Callers resolve `alphabet` and `textCase`, which also unwraps `String` objects.
33
33
  const values: { -readonly [Key in keyof GenerationOptionValues]: unknown } = {};
34
34
  if (accepted.alphabet && Object.hasOwn(source, "alphabet")) values.alphabet = source.alphabet;
package/src/index.ts CHANGED
@@ -55,6 +55,9 @@ export type {
55
55
  UuidSlugMigrationFormat,
56
56
  MaskedUuidV7Slug,
57
57
  MaskedOrSentinelUuidV7Slug,
58
+ MaskedUuidV7Bytes,
59
+ SentinelUuidV7Bytes,
60
+ MaskedOrSentinelUuidV7Bytes,
58
61
  SentinelUuidV7Slug,
59
62
  UuidBytes,
60
63
  UuidByteInput,
@@ -112,15 +112,9 @@ export function createCustomUuidV7Mask(
112
112
  Uint8Array.from({ length: 16 }, (_, index) => index * 17),
113
113
  ]) {
114
114
  const mixed = runCustom(mask, probe);
115
- if (isUuidSlugError(mixed))
116
- return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, {
117
- cause: mixed,
118
- });
115
+ if (isUuidSlugError(mixed)) return customMaskFailure(mixed);
119
116
  const restored = runCustom(unmask, mixed);
120
- if (isUuidSlugError(restored))
121
- return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, {
122
- cause: restored,
123
- });
117
+ if (isUuidSlugError(restored)) return customMaskFailure(restored);
124
118
  if (restored.some((byte, index) => byte !== probe[index]))
125
119
  return new UuidSlugError(
126
120
  INVALID_MASK,
@@ -134,8 +128,10 @@ export function createCustomUuidV7Mask(
134
128
  return undefined;
135
129
  });
136
130
  } catch (cause) {
137
- return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, {
138
- cause,
139
- });
131
+ return customMaskFailure(cause);
140
132
  }
141
133
  }
134
+
135
+ function customMaskFailure(cause: unknown): UuidSlugError {
136
+ return new UuidSlugError(INVALID_MASK, CUSTOM_MASK_FAILURE_MESSAGE, { cause });
137
+ }