@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
@@ -28,8 +28,11 @@ import {
28
28
  noMaskedSlugMatch,
29
29
  unmaskSlug,
30
30
  } from "./payload.ts";
31
+ import type { UuidV7MaskRange } from "./payload.ts";
32
+ import { MAX_UUID_V7_UNIX_MS } from "./v7-timestamp.ts";
31
33
  import { createMigration } from "./migration.ts";
32
34
  import { findSentinel } from "./sentinel.ts";
35
+ import { createMaskedByteMethods } from "./masked-bytes.ts";
33
36
  import { registerMaskingCodec } from "./masking-codec-protocol.ts";
34
37
  import { isMaskHandle } from "./mask-handle.ts";
35
38
  import { deriveUuidV7Mask } from "./mask.ts";
@@ -91,7 +94,7 @@ import {
91
94
  } from "./uuid.ts";
92
95
  import type { UuidV7TimestampWindow, UuidV7SentinelConfig } from "./types.ts";
93
96
  import type { SlugAlphabet } from "./slug.ts";
94
- import { createUuidValue, parseUuidWithCodec } from "./uuid-value.ts";
97
+ import { createUuidValue, parseUuid } from "./uuid-value.ts";
95
98
  import { generateUuidV7ValueWithGenerator, readUuidV7ValueOptions } from "./v7-value-options.ts";
96
99
  import { generateUuidV7BytesWithGenerator, readUuidV7Generator } from "./v7-generator-input.ts";
97
100
  import { readGenerationOptions } from "./generation-options.ts";
@@ -124,8 +127,7 @@ const SENTINEL_OPTIONS = {
124
127
  uuid: true,
125
128
  } as const satisfies Record<keyof UuidV7SentinelConfig, true>;
126
129
  const MASKED_PAIR_GENERATION_OPTIONS = {
127
- at: true,
128
- generator: true,
130
+ ...UUID_V7_MASKING_CODEC_VALUE_OPTIONS,
129
131
  textCase: true,
130
132
  } as const satisfies Record<keyof GenerateUuidV7WithMaskedSlugOptions, true>;
131
133
  type EncodedSentinelIndex = {
@@ -167,8 +169,7 @@ const EMPTY_SENTINEL_STATE: SentinelState = Object.freeze({
167
169
  function maskFromOption(
168
170
  mask: UuidV7Mask | UuidV7MaskOptions | UuidSlugError,
169
171
  ): UuidV7Mask | UuidSlugError {
170
- if (isUuidSlugError(mask)) return mask;
171
- if (isMaskHandle(mask)) return mask;
172
+ if (isUuidSlugError(mask) || isMaskHandle(mask)) return mask;
172
173
  if (typeof mask !== "object" || mask === null)
173
174
  return new UuidSlugError(
174
175
  INVALID_MASK,
@@ -177,7 +178,6 @@ function maskFromOption(
177
178
  return deriveUuidV7Mask(mask);
178
179
  }
179
180
 
180
- const MAX_UUID_V7_UNIX_MS = 2 ** 48 - 1;
181
181
  const MAX_TIMESTAMP_RANGE_START_UNIX_MS =
182
182
  MAX_UUID_V7_UNIX_MS - MAX_MASKED_UUID_V7_TIMESTAMP_OFFSET_MS;
183
183
 
@@ -340,13 +340,9 @@ function createSentinels(
340
340
  export function createUuidV7MaskingCodec(
341
341
  options: UuidV7MaskingCodecOptions,
342
342
  ): UuidV7MaskingCodec | UuidSlugError {
343
- try {
344
- // Codec generation keeps every failure as a value: a configured timestamp range can reject
345
- // the current time, so no codec generation call is free of fallible input.
346
- return buildUuidSlugCodec(options, generateDefaultUuidV7Bytes);
347
- } catch (cause) {
348
- return new UuidSlugError(INVALID_MASK, CODEC_CONSTRUCTION_FAILED, { cause });
349
- }
343
+ // Codec generation keeps every failure as a value: a configured timestamp range can reject
344
+ // the current time, so no codec generation call is free of fallible input.
345
+ return createUuidV7MaskingCodecWithGenerator(options, generateDefaultUuidV7Bytes);
350
346
  }
351
347
 
352
348
  /** Internal seam for exercising generator failures without weakening public generation. */
@@ -396,7 +392,7 @@ function buildUuidSlugCodec(
396
392
  const current = { mask: handle, timestampRangeStartUnixMs: currentTimestampRangeStart };
397
393
  // Decode tries exactly the caller's masks in order. Every added mask increases false
398
394
  // acceptance, and the first passing mask decides the result, so no fallback is added here.
399
- const previousMasks: { mask: UuidV7Mask; timestampRangeStartUnixMs: number }[] = [];
395
+ const previousMasks: UuidV7MaskRange[] = [];
400
396
  const previousMaskOptions = options.previousMasks ?? [];
401
397
  if (!Array.isArray(previousMaskOptions))
402
398
  return new UuidSlugError(
@@ -497,17 +493,12 @@ function buildUuidSlugCodec(
497
493
  }
498
494
  // Branch after common validation so ordinary callers retain one plain borrowed-byte route.
499
495
  // Split guard helpers slowed that Bun route; reconsider only with packed mixed-workload evidence.
500
- if (owned)
501
- return ownedUuidV7BytesToMaskedSlug(
502
- bytes,
503
- handle,
504
- maskedSlugAlphabet,
505
- sentinels.bySlug,
506
- currentTimestampRangeStart,
507
- );
508
- encodeScratch.set(bytes);
496
+ if (!owned) {
497
+ encodeScratch.set(bytes);
498
+ bytes = encodeScratch;
499
+ }
509
500
  return ownedUuidV7BytesToMaskedSlug(
510
- encodeScratch,
501
+ bytes,
511
502
  handle,
512
503
  maskedSlugAlphabet,
513
504
  sentinels.bySlug,
@@ -555,7 +546,7 @@ function buildUuidSlugCodec(
555
546
  // function past the size JavaScriptCore inlines into a small caller, which costs Bun sentinel
556
547
  // reads a few nanoseconds; moving it into a helper cost more because Bun did not inline the
557
548
  // helper either. Recheck `sentinel.base32.decode` on Bun when this function changes
558
- // (bench/PERFORMANCE.md).
549
+ // (bench/decisions.md).
559
550
  if (uuid.length === 36) {
560
551
  if (selectedCase === UUID_TEXT_LOWERCASE && isUuidString(uuid))
561
552
  return uuid as UuidStringFor<Case>;
@@ -600,14 +591,13 @@ function buildUuidSlugCodec(
600
591
  // stays here: sending a masked slug to the keyless reader would decode a different UUID.
601
592
  const readsAtOffset = typeof outputOrByteOffset === "number";
602
593
  if (readsAtOffset && (isUint8Array(uuid) || outputOrByteOffset !== 0))
603
- return outputOrOutputOffset === undefined
604
- ? keylessUuidToBytes(uuid as Uint8Array, outputOrByteOffset)
605
- : keylessUuidToBytes(
606
- uuid as Uint8Array,
607
- outputOrByteOffset,
608
- outputOrOutputOffset as Uint8Array,
609
- offsetAfterOutput,
610
- );
594
+ // The keyless reader treats an undefined output like an omitted one, so one call covers both.
595
+ return keylessUuidToBytes(
596
+ uuid as Uint8Array,
597
+ outputOrByteOffset,
598
+ outputOrOutputOffset as Uint8Array,
599
+ offsetAfterOutput,
600
+ );
611
601
  const output = readsAtOffset ? outputOrOutputOffset : outputOrByteOffset;
612
602
  const outputOffset = readsAtOffset
613
603
  ? offsetAfterOutput
@@ -846,14 +836,16 @@ function buildUuidSlugCodec(
846
836
  return bytes instanceof Error ? bytes : extractUuidV7Payload(bytes, layout);
847
837
  }
848
838
 
849
- function createUuidSlugMigrationDecoder(
850
- migrationOptions?: undefined,
851
- ): UuidSlugMigrationDecoder<typeof SEEDED_MASK_FORMAT>;
839
+ function createUuidSlugMigrationDecoder(): UuidSlugMigrationDecoder<typeof SEEDED_MASK_FORMAT>;
852
840
  // Structural typing permits extra keys and accessors; createMigration can reject either even
853
841
  // when boolean fields type-check. Only omission removes that configuration failure boundary.
854
- function createUuidSlugMigrationDecoder<const Options extends UuidSlugMigrationOptions>(
855
- migrationOptions: Options | undefined,
856
- ): UuidSlugMigrationDecoder<EnabledMigrationFormat<Options>> | UuidSlugError;
842
+ function createUuidSlugMigrationDecoder<
843
+ const Options extends UuidSlugMigrationOptions | undefined,
844
+ >(
845
+ migrationOptions: Options,
846
+ ):
847
+ | UuidSlugMigrationDecoder<EnabledMigrationFormat<NonNullable<Options>>>
848
+ | (Options extends undefined ? never : UuidSlugError);
857
849
  function createUuidSlugMigrationDecoder(
858
850
  migrationOptions?: UuidSlugMigrationOptions,
859
851
  ): UuidSlugMigrationDecoder<typeof SEEDED_MASK_FORMAT> | UuidSlugError {
@@ -892,18 +884,27 @@ function buildUuidSlugCodec(
892
884
  const generator = readUuidV7Generator(values.generator);
893
885
  if (generator instanceof Error) return generator;
894
886
  if (generator) return generateUuidV7ValueWithGenerator(generator, values, maskingCodec);
895
- const generated = !Object.hasOwn(values, AT_OPTION)
896
- ? generateDefaultUuidV7Bytes()
897
- : generateDefaultUuidV7Bytes({ at: values.at as UuidV7Instant });
887
+ // Public codecs inject the package default, whose bytes and failures every module-level route
888
+ // already returns directly; the shared helper's generator re-read, try/catch and validation
889
+ // measured slower on every engine (`bench/decisions.md` §Default value generation). Injected
890
+ // generators keep its containment of thrown and malformed results. Remeasure if the helper
891
+ // loses its try/catch or validation.
892
+ const generated =
893
+ generateBytes !== generateDefaultUuidV7Bytes
894
+ ? generateCodecBytesFromValues(values)
895
+ : !Object.hasOwn(values, AT_OPTION)
896
+ ? generateBytes()
897
+ : generateBytes({ at: values.at as UuidV7Instant });
898
898
  return generated instanceof Error
899
899
  ? generated
900
900
  : createUuidValue<7, true, true>(generated, maskingCodec, uuidV7DefaultPayloadLayout());
901
901
  }
902
902
 
903
903
  const maskingCodec: UuidV7MaskingCodec = {
904
+ ...createMaskedByteMethods(decodeUuid, current, previousMasks, sentinels.encoded),
904
905
  sentinels: sentinels.sentinels,
905
906
  generateUuidV7Value,
906
- parseUuid: (uuid) => parseUuidWithCodec(uuid, maskingCodec),
907
+ parseUuid: (uuid) => parseUuid(uuid, maskingCodec),
907
908
  uuidToString,
908
909
  uuidToBytes,
909
910
  uuidToPlainSlug,
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,15 +170,30 @@ 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
181
- // (bench/PERFORMANCE.md).
196
+ // (bench/decisions.md).
182
197
  const canonical =
183
198
  alphabet === BASE64URL_NAME || (tail === 0 && reserved?.size)
184
199
  ? encode(raw, BASE64URL, tail, OUTER_TAG_BITS)
@@ -203,7 +218,7 @@ export const noMaskedSlugMatch = /* @__NO_SIDE_EFFECTS__ */ (): UuidSlugError =>
203
218
  * Decode a masked slug and return `undefined` when every mask's check rejects it. Source-specific
204
219
  * readers report that miss with `noMaskedSlugMatch`; a codec reading an ambiguous 22-character slug
205
220
  * takes the plain reading instead, so the miss builds no error. Readers call this directly: a wrapper
206
- * that built the error slowed the masked-slug text reader on Node (bench/PERFORMANCE.md).
221
+ * that built the error slowed the masked-slug text reader on Node (bench/decisions.md).
207
222
  */
208
223
  export function unmaskSlug(
209
224
  slug: string,
@@ -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
  }
@@ -26,7 +26,7 @@ else if (globalThis.crypto.randomUUID)
26
26
 
27
27
  // Native UUIDv7 can advance logical time during counter overflow; defaults do not forbid that.
28
28
  // Select it only when complete-call gains preserve configured-call speed and resource efficiency.
29
- // Explicit generators keep their clock controls; bench/PERFORMANCE.md owns drift and cost evidence.
29
+ // Explicit generators keep their clock controls; bench/decisions.md owns drift and cost evidence.
30
30
  const nativeUuidV7 = (globalThis as { Bun?: { randomUUIDv7?: (encoding?: "base64url") => string } })
31
31
  .Bun?.randomUUIDv7;
32
32
  if (typeof nativeUuidV7 === "function") {
@@ -35,7 +35,7 @@ if (nodeOptions?.includes("jitless")) {
35
35
 
36
36
  /**
37
37
  * Node's native UTF-8 encoder materially reduces string-seed construction; the portable adapter
38
- * remains the compatibility boundary. bench/PERFORMANCE.md owns the measured runtime scope.
38
+ * remains the compatibility boundary. bench/decisions.md owns the measured runtime scope.
39
39
  */
40
40
  export const encodeUtf8 = /* @__NO_SIDE_EFFECTS__ */ (text: string): Uint8Array =>
41
41
  Buffer.from(text, "utf8");
@@ -53,7 +53,7 @@ const nodeRuntime: Runtime = {
53
53
  }),
54
54
  // Pooled formatting wins with the JIT; native text wins without it. Missing native capability
55
55
  // stays undefined so the generator uses its tested portable fallback. Remeasure both modes
56
- // after Node changes; bench/PERFORMANCE.md owns the compared calls and resource limits.
56
+ // after Node changes; bench/decisions.md owns the compared calls and resource limits.
57
57
  ...(jitless ? { jitless: true, uuidV4: crypto.randomUUID } : {}),
58
58
  };
59
59
 
@@ -55,7 +55,7 @@ export function pooledFill(
55
55
  // Continuation draws need four bytes. Fixed stores avoid their loop without another view
56
56
  // or retained buffer. Owned draws use four-byte blocks, reusing each source offset rather
57
57
  // than repeating its arithmetic. Blocks keep the body smaller than fully expanded stores;
58
- // other lengths keep the indexed loop. Complete-call comparisons in bench/PERFORMANCE.md
58
+ // other lengths keep the indexed loop. Complete-call comparisons in bench/decisions.md
59
59
  // decide this shape, not copy-only timing. Remeasure if draw widths
60
60
  // or the runtime's typed-array handling change.
61
61
  if (length === 4) {
@@ -29,7 +29,7 @@ const runtimeCapabilities: Runtime = {
29
29
  // WebKit's fixed formatter slowed unrelated successful calls in mixed comparisons. Native hex
30
30
  // did not reproduce a repeated loss while other engines retain their fixed writers. This identity
31
31
  // selects cost only; absent hex support still uses the portable writer. Remeasure after browser
32
- // changes (bench/PERFORMANCE.md); the shared ASCII decoder also slowed slug output.
32
+ // changes (bench/decisions.md); the shared ASCII decoder also slowed slug output.
33
33
  if (
34
34
  typeof navigator !== "undefined" &&
35
35
  navigator.vendor === "Apple Computer, Inc." &&
@@ -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. */