@anizoptera/uuid-slug 0.5.0 → 0.7.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 (141) hide show
  1. package/AGENTS.md +14 -0
  2. package/README.md +54 -140
  3. package/dist/alphabet.d.ts +1 -3
  4. package/dist/alphabet.d.ts.map +1 -1
  5. package/dist/alphabet.js +33 -91
  6. package/dist/alphabet.js.map +1 -1
  7. package/dist/base64url-name.d.ts +1 -3
  8. package/dist/base64url-name.d.ts.map +1 -1
  9. package/dist/base64url-name.js +2 -3
  10. package/dist/errors.d.ts +1 -3
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js +7 -24
  13. package/dist/errors.js.map +1 -1
  14. package/dist/feistel.js +3 -4
  15. package/dist/feistel.js.map +1 -1
  16. package/dist/generation-options.js +2 -3
  17. package/dist/generation-options.js.map +1 -1
  18. package/dist/index.d.ts +10 -10
  19. package/dist/index.js +21 -21
  20. package/dist/instant.js +4 -5
  21. package/dist/instant.js.map +1 -1
  22. package/dist/mask-handle.d.ts +1 -3
  23. package/dist/mask-handle.d.ts.map +1 -1
  24. package/dist/mask-handle.js +19 -17
  25. package/dist/mask-handle.js.map +1 -1
  26. package/dist/mask.d.ts +1 -3
  27. package/dist/mask.d.ts.map +1 -1
  28. package/dist/mask.js +23 -24
  29. package/dist/mask.js.map +1 -1
  30. package/dist/masked-bytes.js +74 -0
  31. package/dist/masked-bytes.js.map +1 -0
  32. package/dist/masking-codec-protocol.js +2 -3
  33. package/dist/masking-codec-protocol.js.map +1 -1
  34. package/dist/masking-codec-types.d.ts +60 -19
  35. package/dist/masking-codec-types.d.ts.map +1 -1
  36. package/dist/masking-codec.d.ts +1 -3
  37. package/dist/masking-codec.d.ts.map +1 -1
  38. package/dist/masking-codec.js +119 -115
  39. package/dist/masking-codec.js.map +1 -1
  40. package/dist/migration.js +39 -40
  41. package/dist/migration.js.map +1 -1
  42. package/dist/node/runtime.js +9 -10
  43. package/dist/node/runtime.js.map +1 -1
  44. package/dist/payload.d.ts +1 -3
  45. package/dist/payload.d.ts.map +1 -1
  46. package/dist/payload.js +65 -64
  47. package/dist/payload.js.map +1 -1
  48. package/dist/runtime/pool.js +2 -3
  49. package/dist/runtime/pool.js.map +1 -1
  50. package/dist/runtime/portable.js +2 -3
  51. package/dist/runtime/portable.js.map +1 -1
  52. package/dist/sentinel.js +2 -3
  53. package/dist/sentinel.js.map +1 -1
  54. package/dist/siphash.js +4 -5
  55. package/dist/siphash.js.map +1 -1
  56. package/dist/slug.d.ts +14 -13
  57. package/dist/slug.d.ts.map +1 -1
  58. package/dist/slug.js +145 -153
  59. package/dist/slug.js.map +1 -1
  60. package/dist/timestamp.d.ts +1 -3
  61. package/dist/timestamp.d.ts.map +1 -1
  62. package/dist/timestamp.js +2 -3
  63. package/dist/timestamp.js.map +1 -1
  64. package/dist/types.d.ts +38 -16
  65. package/dist/types.d.ts.map +1 -1
  66. package/dist/types.js +2 -3
  67. package/dist/types.js.map +1 -1
  68. package/dist/uuid-value-protocol.js +2 -3
  69. package/dist/uuid-value-protocol.js.map +1 -1
  70. package/dist/uuid-value.d.ts +3 -5
  71. package/dist/uuid-value.d.ts.map +1 -1
  72. package/dist/uuid-value.js +74 -78
  73. package/dist/uuid-value.js.map +1 -1
  74. package/dist/uuid.d.ts +6 -8
  75. package/dist/uuid.d.ts.map +1 -1
  76. package/dist/uuid.js +38 -49
  77. package/dist/uuid.js.map +1 -1
  78. package/dist/v4-slug.d.ts +2 -4
  79. package/dist/v4-slug.d.ts.map +1 -1
  80. package/dist/v4-slug.js +6 -7
  81. package/dist/v4-slug.js.map +1 -1
  82. package/dist/v4.d.ts +8 -6
  83. package/dist/v4.d.ts.map +1 -1
  84. package/dist/v4.js +38 -44
  85. package/dist/v4.js.map +1 -1
  86. package/dist/v7-bounds.d.ts +3 -5
  87. package/dist/v7-bounds.d.ts.map +1 -1
  88. package/dist/v7-bounds.js +10 -11
  89. package/dist/v7-bounds.js.map +1 -1
  90. package/dist/v7-generator-input.js +10 -12
  91. package/dist/v7-generator-input.js.map +1 -1
  92. package/dist/v7-generator.d.ts +1 -3
  93. package/dist/v7-generator.d.ts.map +1 -1
  94. package/dist/v7-generator.js +45 -46
  95. package/dist/v7-generator.js.map +1 -1
  96. package/dist/v7-keyless.d.ts +12 -4
  97. package/dist/v7-keyless.d.ts.map +1 -1
  98. package/dist/v7-keyless.js +54 -55
  99. package/dist/v7-keyless.js.map +1 -1
  100. package/dist/v7-payload.js +3 -4
  101. package/dist/v7-payload.js.map +1 -1
  102. package/dist/v7-slug.d.ts +8 -5
  103. package/dist/v7-slug.d.ts.map +1 -1
  104. package/dist/v7-slug.js +69 -70
  105. package/dist/v7-slug.js.map +1 -1
  106. package/dist/v7-timestamp.js +2 -3
  107. package/dist/v7-timestamp.js.map +1 -1
  108. package/dist/v7-value-options.js +2 -3
  109. package/dist/v7-value-options.js.map +1 -1
  110. package/dist/v7-value.d.ts +5 -8
  111. package/dist/v7-value.d.ts.map +1 -1
  112. package/dist/v7-value.js +10 -11
  113. package/dist/v7-value.js.map +1 -1
  114. package/dist/v7.js +16 -17
  115. package/dist/v7.js.map +1 -1
  116. package/package.json +9 -2
  117. package/src/alphabet.ts +82 -237
  118. package/src/errors.ts +27 -40
  119. package/src/feistel.ts +3 -3
  120. package/src/index.ts +3 -0
  121. package/src/mask-handle.ts +7 -11
  122. package/src/mask.ts +16 -14
  123. package/src/masked-bytes.ts +203 -0
  124. package/src/masking-codec-types.ts +124 -24
  125. package/src/masking-codec.ts +43 -42
  126. package/src/migration.ts +8 -7
  127. package/src/payload.ts +69 -51
  128. package/src/runtime/portable.ts +2 -2
  129. package/src/runtime/types.ts +2 -4
  130. package/src/slug.ts +39 -48
  131. package/src/types.ts +107 -17
  132. package/src/uuid-value.ts +2 -9
  133. package/src/uuid.ts +19 -33
  134. package/src/v4.ts +12 -9
  135. package/src/v7-bounds.ts +4 -2
  136. package/src/v7-generator-input.ts +2 -5
  137. package/src/v7-generator.ts +2 -2
  138. package/src/v7-keyless.ts +29 -0
  139. package/src/v7-slug.ts +20 -1
  140. package/src/v7-value.ts +9 -4
  141. package/src/v7.ts +26 -0
package/src/migration.ts CHANGED
@@ -132,7 +132,6 @@ export function createMigration(
132
132
  base32 || safeMasked ? BASE32HEX : BASE64URL,
133
133
  bytes,
134
134
  0,
135
- 16,
136
135
  base32 ? 0 : 4,
137
136
  );
138
137
  if (tail instanceof Error) return tail;
@@ -190,7 +189,7 @@ export function createMigration(
190
189
  ): UuidString | UuidSlugError;
191
190
  function uuidSlugToUuidString<Case extends UuidTextCase>(
192
191
  uuidSlug: string | UuidSlugError,
193
- format: UuidSlugMigrationFormat,
192
+ format: UuidSlugMigrationFormat | undefined,
194
193
  textCase: Case,
195
194
  ): UuidStringFor<Case> | UuidSlugError;
196
195
  function uuidSlugToUuidString<Case extends UuidTextCase>(
@@ -202,9 +201,10 @@ export function createMigration(
202
201
  formatOrCase === undefined || typeof formatOrCase === "string"
203
202
  ? formatOrCase
204
203
  : (stringInput(formatOrCase) ?? formatOrCase);
205
- const format = isUuidTextCase(second) ? undefined : second;
204
+ const secondIsCase = isUuidTextCase(second);
205
+ const format = secondIsCase ? undefined : second;
206
206
  const selectedCase = resolveUuidTextCase(
207
- (isUuidTextCase(second) ? second : textCase) ?? UUID_TEXT_LOWERCASE,
207
+ (secondIsCase ? second : textCase) ?? UUID_TEXT_LOWERCASE,
208
208
  );
209
209
  if (selectedCase instanceof Error) return selectedCase;
210
210
  const result = read(uuidSlug, format as UuidSlugMigrationFormat | undefined, true);
@@ -227,7 +227,7 @@ export function createMigration(
227
227
  ): readonly UuidString[] | UuidSlugError;
228
228
  function uuidSlugToUuidStringCandidates<Case extends UuidTextCase>(
229
229
  uuidSlug: string | UuidSlugError,
230
- format: UuidSlugMigrationFormat,
230
+ format: UuidSlugMigrationFormat | undefined,
231
231
  textCase: Case,
232
232
  ): readonly UuidStringFor<Case>[] | UuidSlugError;
233
233
  function uuidSlugToUuidStringCandidates(
@@ -239,9 +239,10 @@ export function createMigration(
239
239
  formatOrCase === undefined || typeof formatOrCase === "string"
240
240
  ? formatOrCase
241
241
  : (stringInput(formatOrCase) ?? formatOrCase);
242
- const format = isUuidTextCase(second) ? undefined : second;
242
+ const secondIsCase = isUuidTextCase(second);
243
+ const format = secondIsCase ? undefined : second;
243
244
  const selectedCase = resolveUuidTextCase(
244
- (isUuidTextCase(second) ? second : textCase) ?? UUID_TEXT_LOWERCASE,
245
+ (secondIsCase ? second : textCase) ?? UUID_TEXT_LOWERCASE,
245
246
  );
246
247
  if (selectedCase instanceof Error) return selectedCase;
247
248
  const result = read(uuidSlug, format as UuidSlugMigrationFormat | undefined, false);
package/src/payload.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
- import { BASE32HEX, BASE64URL, BASE64URL_NAME, decodeInto, encode, spareBits } from "./alphabet.ts";
3
+ import { BASE32HEX, BASE64URL, BASE64URL_NAME, decodeInto, encode } from "./alphabet.ts";
4
4
  import {
5
5
  INVALID_MASK,
6
6
  INVALID_TIMESTAMP,
@@ -10,7 +10,7 @@ import {
10
10
  } from "./errors.ts";
11
11
  import { mix32, read32 } from "./feistel.ts";
12
12
  import { applyMask } from "./mask-handle.ts";
13
- import { bytesToUuidString } from "./uuid.ts";
13
+ import { formatUuidBytesUnchecked } from "./uuid.ts";
14
14
  import type { UuidV7Mask, MaskedUuidV7Slug, UuidString } from "./types.ts";
15
15
  import type { SlugAlphabet } from "./slug.ts";
16
16
 
@@ -60,22 +60,24 @@ function applyMix(
60
60
  ): undefined | UuidSlugError {
61
61
  try {
62
62
  const cause = applyMask(mask, input, output, direction);
63
- return cause
64
- ? new UuidSlugError(
65
- INVALID_MASK,
66
- `UUIDv7 mask "${mask.diagnosticLabel}" failed while ${direction === MASK_DIRECTION ? MASKING : UNMASKING}.`,
67
- { cause },
68
- )
69
- : undefined;
63
+ return cause ? mixFailure(mask, direction, cause) : undefined;
70
64
  } catch (cause) {
71
- return new UuidSlugError(
72
- INVALID_MASK,
73
- `UUIDv7 mask "${mask.diagnosticLabel}" failed while ${direction === MASK_DIRECTION ? MASKING : UNMASKING}.`,
74
- { cause },
75
- );
65
+ return mixFailure(mask, direction, cause);
76
66
  }
77
67
  }
78
68
 
69
+ function mixFailure(
70
+ mask: UuidV7Mask,
71
+ direction: typeof MASK_DIRECTION | typeof UNMASK_DIRECTION,
72
+ cause: unknown,
73
+ ): UuidSlugError {
74
+ return new UuidSlugError(
75
+ INVALID_MASK,
76
+ `UUIDv7 mask "${mask.diagnosticLabel}" failed while ${direction === MASK_DIRECTION ? MASKING : UNMASKING}.`,
77
+ { cause },
78
+ );
79
+ }
80
+
79
81
  /**
80
82
  * Spread every input word across the check so structured UUID fields do not collapse into a sum.
81
83
  * This avalanche mixer supplies error detection, not authentication or a cryptographic-strength
@@ -99,21 +101,25 @@ function tagFor(bytes: Uint8Array, width: number) {
99
101
  * Encoding must reject an offset at or past 2^42 ms rather than truncate it.
100
102
  */
101
103
  function injectTag(bytes: Uint8Array, tag: number) {
102
- bytes[6] = ((tag & 0x0f) << 4) | ((bytes[6] ?? 0) & 0x0f);
103
- bytes[8] = ((tag & 0x30) << 2) | ((bytes[8] ?? 0) & 0x3f);
104
- bytes[0] = (((tag >>> 6) & 0x3f) << 2) | ((bytes[0] ?? 0) & 0x03);
104
+ bytes[6] = ((tag & 0x0f) << 4) | ((bytes[6] as number) & 0x0f);
105
+ bytes[8] = ((tag & 0x30) << 2) | ((bytes[8] as number) & 0x3f);
106
+ bytes[0] = (((tag >>> 6) & 0x3f) << 2) | ((bytes[0] as number) & 0x03);
105
107
  }
106
108
 
107
109
  /*#__NO_SIDE_EFFECTS__*/
108
110
  function extractTag(bytes: Uint8Array) {
109
- return ((bytes[6] ?? 0) >>> 4) | (((bytes[8] ?? 0) >>> 6) << 4) | (((bytes[0] ?? 0) >>> 2) << 6);
111
+ return (
112
+ ((bytes[6] as number) >>> 4) |
113
+ (((bytes[8] as number) >>> 6) << 4) |
114
+ (((bytes[0] as number) >>> 2) << 6)
115
+ );
110
116
  }
111
117
 
112
118
  /** Puts back the constants the tag displaced, so the block equals the UUID the caller handed in. */
113
119
  function restoreV7(bytes: Uint8Array) {
114
- bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x70;
115
- bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
116
- bytes[0] = (bytes[0] ?? 0) & 0x03;
120
+ bytes[6] = ((bytes[6] as number) & 0x0f) | 0x70;
121
+ bytes[8] = ((bytes[8] as number) & 0x3f) | 0x80;
122
+ bytes[0] = (bytes[0] as number) & 0x03;
117
123
  }
118
124
 
119
125
  /** Restore the fixed ciphertext block without allocating views or per-key buffers. */
@@ -142,24 +148,18 @@ const INNER_TAG_BITS = 12;
142
148
  /**
143
149
  * The existing base64url wire format fixes four outer check bits. Alternate spellings preserve
144
150
  * all 132 bits; the safe base32hex spelling adds three zero padding bits, not more check bits.
151
+ * Four is what 22 base64url characters hold beyond 16 bytes: 132 − 128 bits.
145
152
  */
146
- const OUTER_TAG_BITS = spareBits(BASE64URL, 16);
153
+ const OUTER_TAG_BITS = 4;
147
154
  const TAG_BITS = INNER_TAG_BITS + OUTER_TAG_BITS;
148
155
 
149
- /**
150
- * Mask a private block in place. Callers must own `raw`: tag injection destroys its UUID bytes.
151
- * This separate entry keeps mutation impossible on the ordinary caller-owned byte path while a
152
- * freshly parsed UUID string can avoid an otherwise redundant copy.
153
- */
154
- export function ownedUuidV7BytesToMaskedSlug(
156
+ /** Mutate one owned UUIDv7 block; the returned outer check belongs only to text encodings. */
157
+ export function maskUuidV7Block(
155
158
  raw: Uint8Array,
156
159
  mask: UuidV7Mask,
157
- alphabet: SlugAlphabet = BASE64URL_NAME,
158
- reserved?: { readonly size: number; has(slug: string): boolean },
159
- timestampRangeStartUnixMs = 0,
160
- ): MaskedUuidV7Slug | UuidSlugError {
161
- // Truncating instead would make encoding non-injective — two UUIDs would share one slug, and no
162
- // decoder could ever tell which was meant. Refusing is the only recoverable answer.
160
+ timestampRangeStartUnixMs: number,
161
+ ): number | UuidSlugError {
162
+ // Truncation would map different UUIDs to one value in every representation.
163
163
  const timestamp = readUnixMs(raw);
164
164
  const timestampOffset = timestamp - timestampRangeStartUnixMs;
165
165
  if (timestampOffset < 0 || timestampOffset > MAX_MASKED_UUID_V7_TIMESTAMP_OFFSET_MS)
@@ -170,11 +170,26 @@ export function ownedUuidV7BytesToMaskedSlug(
170
170
  const tag = tagFor(raw, TAG_BITS);
171
171
  writeUnixMs(raw, timestampOffset);
172
172
  injectTag(raw, tag >>> OUTER_TAG_BITS);
173
- // Every mask receives an isolated block. Reusing that block as output removes a second
174
- // allocation; built-in transforms read all words before writing and custom transforms copy input.
173
+ // Built-in transforms read all words before writing; custom transforms copy input, so private
174
+ // in-place output avoids another array without exposing caller bytes.
175
175
  const failed = applyMix(mask, raw, raw, MASK_DIRECTION);
176
- if (failed) return failed;
177
- const tail = tag & ((1 << OUTER_TAG_BITS) - 1);
176
+ return failed ?? tag & ((1 << OUTER_TAG_BITS) - 1);
177
+ }
178
+
179
+ /**
180
+ * Mask a private block in place. Callers must own `raw`: tag injection destroys its UUID bytes.
181
+ * This separate entry keeps mutation impossible on the ordinary caller-owned byte path while a
182
+ * freshly parsed UUID string can avoid an otherwise redundant copy.
183
+ */
184
+ export function ownedUuidV7BytesToMaskedSlug(
185
+ raw: Uint8Array,
186
+ mask: UuidV7Mask,
187
+ alphabet: SlugAlphabet = BASE64URL_NAME,
188
+ reserved?: { readonly size: number; has(slug: string): boolean },
189
+ timestampRangeStartUnixMs = 0,
190
+ ): MaskedUuidV7Slug | UuidSlugError {
191
+ const tail = maskUuidV7Block(raw, mask, timestampRangeStartUnixMs);
192
+ if (typeof tail !== "number") return tail;
178
193
  // Raw sentinels have zero outer bits. Only that tail can collide with retained base64 reads;
179
194
  // other writes need neither a second encoding nor a lookup for a collision that cannot occur.
180
195
  // Skipping the lookup matters: on V8 it hashed and flattened every base64url slug
@@ -218,7 +233,6 @@ export function unmaskSlug(
218
233
  slug.length === 27 ? BASE32HEX : BASE64URL,
219
234
  mixed,
220
235
  0,
221
- 16,
222
236
  OUTER_TAG_BITS,
223
237
  );
224
238
  if (outerTag instanceof Error) return outerTag;
@@ -253,8 +267,8 @@ export function decodeFirstMaskedCandidate(
253
267
  const decoded = unmix(mixed.slice(), outerTag, mask);
254
268
  if (isUuidSlugError(decoded)) return decoded;
255
269
  if (decoded) {
256
- const uuid = bytesToUuidString(decoded);
257
- if (uuid instanceof Error) return uuid;
270
+ // unmix returns the private, validated 16-byte block; formatting cannot reject its size.
271
+ const uuid = formatUuidBytesUnchecked(decoded);
258
272
  if (!candidates.includes(uuid)) candidates.push(uuid);
259
273
  break;
260
274
  }
@@ -269,15 +283,13 @@ export function decodeMaskedCandidates(
269
283
  masks: readonly UuidV7MaskRange[],
270
284
  candidates: UuidString[] = [],
271
285
  ): UuidString[] | UuidSlugError {
272
- if (!masks.length) return candidates;
273
- const working = mixed.slice();
274
286
  const firstMask = masks[0];
275
287
  if (!firstMask) return candidates;
288
+ const working = mixed.slice();
276
289
  const firstDecoded = unmix(working, outerTag, firstMask);
277
290
  if (isUuidSlugError(firstDecoded)) return firstDecoded;
278
291
  if (firstDecoded) {
279
- const uuid = bytesToUuidString(firstDecoded);
280
- if (uuid instanceof Error) return uuid;
292
+ const uuid = formatUuidBytesUnchecked(firstDecoded);
281
293
  if (!candidates.includes(uuid)) candidates.push(uuid);
282
294
  }
283
295
  if (masks.length === 1) return candidates;
@@ -294,17 +306,16 @@ export function decodeMaskedCandidates(
294
306
  // A failed callback means the candidate list is incomplete, not that its key mismatched.
295
307
  if (isUuidSlugError(decoded)) return decoded;
296
308
  if (decoded) {
297
- const uuid = bytesToUuidString(decoded);
298
- if (uuid instanceof Error) return uuid;
309
+ const uuid = formatUuidBytesUnchecked(decoded);
299
310
  if (!candidates.includes(uuid)) candidates.push(uuid);
300
311
  }
301
312
  }
302
313
  return candidates;
303
314
  }
304
315
 
305
- function unmix(
316
+ export function unmix(
306
317
  mixed: Uint8Array,
307
- outerTag: number,
318
+ outerTag: number | undefined,
308
319
  range: UuidV7MaskRange,
309
320
  ): Uint8Array | undefined | UuidSlugError {
310
321
  // `mixed` is already private to this mask attempt, so the same alias-safe transform contract
@@ -313,9 +324,16 @@ function unmix(
313
324
  if (failed) return failed;
314
325
  // Both halves come out of the same decryption, so a wrong key garbles the observed check as
315
326
  // thoroughly as the payload: the tag needs no key of its own to tell keys apart.
316
- const foundTag = (extractTag(mixed) << OUTER_TAG_BITS) | outerTag;
327
+ const innerTag = extractTag(mixed);
317
328
  restoreV7(mixed);
318
329
  writeUnixMs(mixed, readUnixMs(mixed) + range.timestampRangeStartUnixMs);
319
- if (tagFor(mixed, TAG_BITS) !== foundTag) return undefined;
330
+ const expectedTag = tagFor(mixed, TAG_BITS);
331
+ // Binary omits only the text tail; both readers restore and check the same UUID block.
332
+ if (
333
+ outerTag === undefined
334
+ ? expectedTag >>> OUTER_TAG_BITS !== innerTag
335
+ : expectedTag !== ((innerTag << OUTER_TAG_BITS) | outerTag)
336
+ )
337
+ return undefined;
320
338
  return mixed;
321
339
  }
@@ -40,10 +40,10 @@ if (
40
40
  type Latin1Buffer = Uint8Array & {
41
41
  toString(encoding: "latin1", start: number, end: number): string;
42
42
  };
43
- type HostBuffer = { alloc(size: number): Latin1Buffer } | undefined;
43
+ type HostBuffer = { alloc(size: number): Latin1Buffer };
44
44
 
45
45
  /** Build scratch text through a Node-compatible `Buffer` constructor. */
46
- export function bufferLatin1Scratch(hostBuffer: NonNullable<HostBuffer>) {
46
+ export function bufferLatin1Scratch(hostBuffer: HostBuffer) {
47
47
  return (length: number): Latin1Scratch => {
48
48
  const bytes = hostBuffer.alloc(length);
49
49
  return { bytes, text: () => bytes.toString("latin1", 0, length) };
@@ -11,10 +11,8 @@ export interface Runtime {
11
11
  * admits one. Narrowing here makes that refusal unrepresentable instead of a throw.
12
12
  */
13
13
  fillRandom(this: void, bytes: Uint8Array<ArrayBuffer>): undefined | UuidSlugError;
14
- /**
15
- * Hooks are detached from the adapter, so `this: void` rejects implementations that depend on
16
- * method binding.
17
- */
14
+ // Hooks are detached from the adapter, so `this: void` rejects implementations that depend on
15
+ // method binding.
18
16
  /** Native UUIDv4 text; default calls trust the proper native generator's result directly. */
19
17
  uuidV4?(this: void): string;
20
18
  /** Native current-time UUIDv7 text; configured clocks and sequence state stay on generators. */
package/src/slug.ts CHANGED
@@ -55,6 +55,7 @@ import type {
55
55
  UuidV7StringFor,
56
56
  UuidVersion,
57
57
  KeylessUuidInput,
58
+ UnmaskedUuidInput,
58
59
  } from "./types.ts";
59
60
  import { UUID_TEXT_LOWERCASE } from "./types.ts";
60
61
  import { uuidValueBytes } from "./uuid-value-protocol.ts";
@@ -76,9 +77,6 @@ import {
76
77
  uuidVersion,
77
78
  } from "./uuid.ts";
78
79
 
79
- export { isUuidSlugError } from "./errors.ts";
80
- export { UuidSlugError };
81
- export type { UuidSlugErrorCode } from "./errors.ts";
82
80
  export type { PlainUuidSlug, PlainUuidV4Slug, PlainUuidV7Slug } from "./types.ts";
83
81
 
84
82
  const UUID_V7_TIMESTAMP_ONLY = "Timestamp is only defined for UUIDv7.";
@@ -160,17 +158,12 @@ const BYTE_OFFSET_NEEDS_BYTES =
160
158
  */
161
159
  export type SlugAlphabet = typeof BASE64URL_NAME | typeof BASE32HEX_NAME;
162
160
 
163
- const SLUG_ALPHABET_CODECS = {
164
- base32hex: BASE32HEX,
165
- base64url: BASE64URL,
166
- } as const satisfies Record<SlugAlphabet, Alphabet>;
167
-
168
161
  /** Reject values outside the public alphabet union when untyped JavaScript bypasses TypeScript. */
169
162
  /*#__NO_SIDE_EFFECTS__*/
170
163
  export function resolveSlugAlphabet(alphabet: SlugAlphabet): Alphabet | UuidSlugError {
171
164
  const name = typeof alphabet === "string" ? alphabet : stringInput(alphabet);
172
165
  // Fixed comparisons avoid an own-property call and keyed lookup on every conversion.
173
- // Packed complete-call comparisons favor this over SLUG_ALPHABET_CODECS; remeasure if
166
+ // Packed complete-call comparisons favor this over a name-keyed lookup object; remeasure if
174
167
  // the supported alphabet vocabulary grows. Wrapper normalization remains shared.
175
168
  if (name === BASE64URL_NAME) return BASE64URL;
176
169
  if (name === BASE32HEX_NAME) return BASE32HEX;
@@ -180,38 +173,33 @@ export function resolveSlugAlphabet(alphabet: SlugAlphabet): Alphabet | UuidSlug
180
173
  );
181
174
  }
182
175
 
183
- /** Characters needed for 16 bytes: 22 in base64url, 26 in base32hex. */
184
- /*#__NO_SIDE_EFFECTS__*/
185
- function slugLength(alpha: Alphabet) {
186
- return Math.ceil(128 / alpha.bitsPerChar);
187
- }
188
-
189
176
  /**
190
177
  * Length -> alphabet, which is why decoding takes no alphabet argument: the two lengths are
191
178
  * disjoint, so a slug names its own encoding and a caller cannot pick the wrong one. Indexed
192
179
  * rather than searched because every decode and every type guard pays this lookup.
180
+ * The index is the characters 16 bytes need: ceil(128 / 6) = 22 in base64url, ceil(128 / 5) = 26
181
+ * in base32hex.
193
182
  */
194
- const SLUG_ALPHABET_BY_LENGTH: readonly (Alphabet | undefined)[] = /*#__PURE__*/ Object.values(
195
- SLUG_ALPHABET_CODECS,
196
- ).reduce<(Alphabet | undefined)[]>((table, alpha) => {
197
- table[slugLength(alpha)] = alpha;
183
+ const SLUG_ALPHABET_BY_LENGTH: readonly (Alphabet | undefined)[] = /*#__PURE__*/ (() => {
184
+ const table: (Alphabet | undefined)[] = [];
185
+ table[22] = BASE64URL;
186
+ table[26] = BASE32HEX;
198
187
  return table;
199
- }, []);
188
+ })();
200
189
 
201
- const SLUG_LENGTHS = /*#__PURE__*/ Object.values(SLUG_ALPHABET_CODECS)
202
- .map((alpha) => `${slugLength(alpha)} (${alpha.name})`)
203
- .join(ALTERNATIVE_SEPARATOR);
190
+ const SLUG_LENGTHS = `26 (${BASE32HEX_NAME})${ALTERNATIVE_SEPARATOR}22 (${BASE64URL_NAME})`;
204
191
 
205
192
  /**
206
193
  * Encode a standalone 16-byte UUID as a plain slug, using base64url by default. An `ArrayBuffer`
207
194
  * uses its whole contents; a `DataView` uses its declared range. Invalid input or alphabet returns
208
195
  * `UuidSlugError`. A preceding `UuidSlugError` is returned unchanged.
196
+ * TypeScript rejects known masked bytes; decode them with their masking codec first.
209
197
  *
210
198
  * @param bytes - One exact 16-byte UUID source.
211
199
  * @param alphabet - Output spelling. Omit for the shorter 22-character base64url form.
212
200
  */
213
201
  export function uuidBytesToPlainSlug(
214
- bytes: UuidByteInput | UuidSlugError,
202
+ bytes: UnmaskedUuidInput<Readonly<UuidByteInput> | UuidSlugError>,
215
203
  alphabet?: SlugAlphabet,
216
204
  ): PlainUuidSlug | UuidSlugError;
217
205
  /**
@@ -223,7 +211,7 @@ export function uuidBytesToPlainSlug(
223
211
  * @param alphabet - Output spelling. Omit for the shorter 22-character base64url form.
224
212
  */
225
213
  export function uuidBytesToPlainSlug(
226
- bytes: Uint8Array | UuidSlugError,
214
+ bytes: UnmaskedUuidInput<Readonly<Uint8Array> | UuidSlugError>,
227
215
  byteOffset: number,
228
216
  alphabet?: SlugAlphabet,
229
217
  ): PlainUuidSlug | UuidSlugError;
@@ -318,18 +306,13 @@ export function plainSlugToUuidBytes(
318
306
  ? checkRange(16, outputOffset, 16)
319
307
  : checkByteRange(output, outputOffset, 16);
320
308
  if (badRange) return badRange;
309
+ // A caller buffer must stay unchanged on failure, so invalid input is decoded into a throwaway
310
+ // array only to get the same diagnostic the no-buffer path returns. Valid input never allocates.
321
311
  if (output && !isEncoded(slug, alpha, 16, true)) {
322
- for (let i = 0; i < slug.length; i += 1) {
323
- const code = slug.charCodeAt(i);
324
- if (code >= 128 || (alpha.decode[code] as number) < 0)
325
- return new UuidSlugError(
326
- alpha.code,
327
- `Invalid ${alpha.name} character ${JSON.stringify(slug[i])} at offset ${i}.`,
328
- );
329
- }
330
- return new UuidSlugError(alpha.code, `${alpha.name} value has non-canonical trailing bits.`);
312
+ const failed = decodeInto(slug, alpha, new Uint8Array(16), 0);
313
+ if (failed instanceof Error) return failed;
331
314
  }
332
- const result = decodeInto(slug, alpha, target, outputOffset, 16);
315
+ const result = decodeInto(slug, alpha, target, outputOffset);
333
316
  return result instanceof Error ? result : target;
334
317
  }
335
318
 
@@ -403,9 +386,7 @@ export function plainSlugToUuidString(
403
386
  // Normalize before scratch is live, then decode and format without caller callbacks. Revisit
404
387
  // reuse if either operation gains callbacks; failed writes cannot escape this private buffer.
405
388
  // The public byte decoder owns invalid-length diagnostics, so keep that exceptional path shared.
406
- const decoded = alpha
407
- ? decodeInto(slug, alpha, textSlugScratch, 0, 16)
408
- : plainSlugToUuidBytes(slug);
389
+ const decoded = alpha ? decodeInto(slug, alpha, textSlugScratch, 0) : plainSlugToUuidBytes(slug);
409
390
  if (decoded instanceof Error) return decoded;
410
391
  // A successful decode yields exactly 16 bytes, so the checked formatter would repeat work.
411
392
  return formatUuidBytesUnchecked(textSlugScratch, 0, selectedCase);
@@ -450,7 +431,8 @@ export function readObjectUuidInput(uuid: unknown): Uint8Array | string | UuidSl
450
431
  */
451
432
  export function extractUuidVersion<Input extends UuidInput>(
452
433
  uuid: KeylessUuidInput<Input>,
453
- ): UuidVersion | UuidSlugError {
434
+ ): UuidVersion | UuidSlugError;
435
+ export function extractUuidVersion(uuid: unknown): UuidVersion | UuidSlugError {
454
436
  const localBytes = exactLocalUuidBytes(uuid);
455
437
  if (localBytes) return uuidVersion(localBytes, 0);
456
438
  const bytes = decodeKeylessUuid(uuid);
@@ -460,6 +442,7 @@ export function extractUuidVersion<Input extends UuidInput>(
460
442
 
461
443
  /**
462
444
  * Convert UUID text, bytes, or a plain UUID slug to new or caller-owned UUID bytes.
445
+ * Decode masked bytes with their masking codec before calling this reader.
463
446
  * Only `Uint8Array` input accepts a non-zero offset; `0` means the same as omitting it.
464
447
  *
465
448
  * @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
@@ -472,9 +455,12 @@ export function uuidToBytes<Input extends UuidInput, Output extends Uint8Array>(
472
455
  output: Output,
473
456
  outputOffset?: number,
474
457
  ): UuidOutput<Output> | UuidSlugError;
475
- export function uuidToBytes(uuid: Uint8Array, byteOffset: number): UuidBytesResult<Uint8Array>;
476
- export function uuidToBytes<Output extends Uint8Array>(
477
- uuid: Uint8Array,
458
+ export function uuidToBytes<Input extends Uint8Array>(
459
+ uuid: KeylessUuidInput<Input>,
460
+ byteOffset: number,
461
+ ): UuidBytesResult<Uint8Array>;
462
+ export function uuidToBytes<Output extends Uint8Array, Input extends Uint8Array = Uint8Array>(
463
+ uuid: KeylessUuidInput<Input>,
478
464
  byteOffset: number,
479
465
  output: Output,
480
466
  outputOffset?: number,
@@ -521,6 +507,7 @@ export function uuidToBytes(
521
507
 
522
508
  /**
523
509
  * Convert UUID text, bytes, or a plain UUID slug to normalized UUID text.
510
+ * Decode masked bytes with their masking codec before calling this reader.
524
511
  * Only `Uint8Array` input accepts a non-zero offset; `0` means the same as omitting it.
525
512
  *
526
513
  * @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
@@ -532,8 +519,11 @@ export function uuidToString<
532
519
  uuid: KeylessUuidInput<Input>,
533
520
  ...textCase: UuidTextCaseArguments<Case>
534
521
  ): UuidStringResult<Input, Case>;
535
- export function uuidToString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
536
- uuid: Uint8Array,
522
+ export function uuidToString<
523
+ Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE,
524
+ Input extends Uint8Array = Uint8Array,
525
+ >(
526
+ uuid: KeylessUuidInput<Input>,
537
527
  byteOffset: number,
538
528
  ...textCase: UuidTextCaseArguments<Case>
539
529
  ): UuidStringResult<Uint8Array, Case>;
@@ -575,7 +565,7 @@ export function uuidToString(
575
565
  const decoded =
576
566
  typeof input === "string"
577
567
  ? alpha
578
- ? decodeInto(input, alpha, textSlugScratch, 0, 16)
568
+ ? decodeInto(input, alpha, textSlugScratch, 0)
579
569
  : uuidStringToBytes(input)
580
570
  : input;
581
571
  const bytes = typeof decoded === "number" ? textSlugScratch : decoded;
@@ -589,6 +579,7 @@ export function uuidToString(
589
579
 
590
580
  /**
591
581
  * Convert UUID text, bytes, or a plain UUID slug to a plain slug.
582
+ * Decode masked bytes with their masking codec before calling this reader.
592
583
  * Only `Uint8Array` input accepts a non-zero offset; `0` means the same as omitting it.
593
584
  *
594
585
  * @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
@@ -597,8 +588,8 @@ export function uuidToPlainSlug<Input extends UuidInput>(
597
588
  uuid: KeylessUuidInput<Input>,
598
589
  alphabet?: SlugAlphabet,
599
590
  ): PlainUuidSlugResult<Input>;
600
- export function uuidToPlainSlug(
601
- uuid: Uint8Array,
591
+ export function uuidToPlainSlug<Input extends Uint8Array>(
592
+ uuid: KeylessUuidInput<Input>,
602
593
  byteOffset: number,
603
594
  alphabet?: SlugAlphabet,
604
595
  ): PlainUuidSlugResult<Uint8Array>;
@@ -873,7 +864,7 @@ export function validatePlainUuidV7SlugUnixMs(
873
864
  // validator captures all byte fields before caller-owned window accessors can reenter.
874
865
  const alpha = SLUG_ALPHABET_BY_LENGTH[plainSlug.length];
875
866
  const decoded = alpha
876
- ? decodeInto(plainSlug, alpha, textSlugScratch, 0, 16)
867
+ ? decodeInto(plainSlug, alpha, textSlugScratch, 0)
877
868
  : plainSlugToUuidBytes(plainSlug);
878
869
  if (decoded instanceof Error) return decoded;
879
870
  const bytes = typeof decoded === "number" ? textSlugScratch : decoded;