@anizoptera/uuid-slug 0.3.0 → 0.4.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 (202) hide show
  1. package/LICENSE +54 -31
  2. package/README.md +1052 -261
  3. package/dist/alphabet.d.ts +5 -17
  4. package/dist/alphabet.d.ts.map +1 -1
  5. package/dist/alphabet.js +146 -112
  6. package/dist/alphabet.js.map +1 -1
  7. package/dist/base64url-name.d.ts +7 -0
  8. package/dist/base64url-name.d.ts.map +1 -0
  9. package/dist/base64url-name.js +8 -0
  10. package/dist/base64url-name.js.map +1 -0
  11. package/dist/errors.d.ts +50 -9
  12. package/dist/errors.d.ts.map +1 -1
  13. package/dist/errors.js +145 -63
  14. package/dist/errors.js.map +1 -1
  15. package/dist/feistel.js +29 -95
  16. package/dist/feistel.js.map +1 -1
  17. package/dist/generation-options.js +20 -0
  18. package/dist/generation-options.js.map +1 -0
  19. package/dist/index.d.ts +22 -10
  20. package/dist/index.js +21 -9
  21. package/dist/instant.js +83 -0
  22. package/dist/instant.js.map +1 -0
  23. package/dist/mask-handle.d.ts +16 -0
  24. package/dist/mask-handle.d.ts.map +1 -0
  25. package/dist/mask-handle.js +60 -0
  26. package/dist/mask-handle.js.map +1 -0
  27. package/dist/mask.d.ts +27 -0
  28. package/dist/mask.d.ts.map +1 -0
  29. package/dist/mask.js +151 -95
  30. package/dist/mask.js.map +1 -1
  31. package/dist/masking-codec-protocol.js +23 -0
  32. package/dist/masking-codec-protocol.js.map +1 -0
  33. package/dist/masking-codec-types.d.ts +245 -0
  34. package/dist/masking-codec-types.d.ts.map +1 -0
  35. package/dist/masking-codec.d.ts +19 -0
  36. package/dist/masking-codec.d.ts.map +1 -0
  37. package/dist/masking-codec.js +391 -0
  38. package/dist/masking-codec.js.map +1 -0
  39. package/dist/migration.js +114 -51
  40. package/dist/migration.js.map +1 -1
  41. package/dist/node/runtime.js +39 -0
  42. package/dist/node/runtime.js.map +1 -0
  43. package/dist/payload.d.ts +7 -0
  44. package/dist/payload.d.ts.map +1 -0
  45. package/dist/payload.js +118 -0
  46. package/dist/payload.js.map +1 -0
  47. package/dist/runtime/pool.js +21 -46
  48. package/dist/runtime/pool.js.map +1 -1
  49. package/dist/runtime/portable.js +27 -0
  50. package/dist/runtime/portable.js.map +1 -0
  51. package/dist/sentinel.js +10 -0
  52. package/dist/sentinel.js.map +1 -0
  53. package/dist/siphash.js +20 -99
  54. package/dist/siphash.js.map +1 -1
  55. package/dist/slug.d.ts +169 -0
  56. package/dist/slug.d.ts.map +1 -0
  57. package/dist/slug.js +268 -0
  58. package/dist/slug.js.map +1 -0
  59. package/dist/timestamp.d.ts +19 -0
  60. package/dist/timestamp.d.ts.map +1 -0
  61. package/dist/timestamp.js +44 -0
  62. package/dist/timestamp.js.map +1 -0
  63. package/dist/types.d.ts +480 -200
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +8 -0
  66. package/dist/types.js.map +1 -0
  67. package/dist/uuid-value-protocol.js +46 -0
  68. package/dist/uuid-value-protocol.js.map +1 -0
  69. package/dist/uuid-value.d.ts +17 -0
  70. package/dist/uuid-value.d.ts.map +1 -0
  71. package/dist/uuid-value.js +127 -0
  72. package/dist/uuid-value.js.map +1 -0
  73. package/dist/uuid.d.ts +51 -64
  74. package/dist/uuid.d.ts.map +1 -1
  75. package/dist/uuid.js +203 -199
  76. package/dist/uuid.js.map +1 -1
  77. package/dist/v4-slug.d.ts +16 -0
  78. package/dist/v4-slug.d.ts.map +1 -0
  79. package/dist/v4-slug.js +16 -0
  80. package/dist/v4-slug.js.map +1 -0
  81. package/dist/v4.d.ts +42 -0
  82. package/dist/v4.d.ts.map +1 -0
  83. package/dist/v4.js +85 -0
  84. package/dist/v4.js.map +1 -0
  85. package/dist/v7-bounds.d.ts +36 -0
  86. package/dist/v7-bounds.d.ts.map +1 -0
  87. package/dist/v7-bounds.js +49 -0
  88. package/dist/v7-bounds.js.map +1 -0
  89. package/dist/v7-generator-input.js +75 -0
  90. package/dist/v7-generator-input.js.map +1 -0
  91. package/dist/v7-generator.d.ts +43 -0
  92. package/dist/v7-generator.d.ts.map +1 -0
  93. package/dist/v7-generator.js +105 -0
  94. package/dist/v7-generator.js.map +1 -0
  95. package/dist/v7-keyless.d.ts +46 -0
  96. package/dist/v7-keyless.d.ts.map +1 -0
  97. package/dist/v7-keyless.js +106 -0
  98. package/dist/v7-keyless.js.map +1 -0
  99. package/dist/v7-payload.js +54 -0
  100. package/dist/v7-payload.js.map +1 -0
  101. package/dist/v7-slug.d.ts +46 -0
  102. package/dist/v7-slug.d.ts.map +1 -0
  103. package/dist/v7-slug.js +127 -0
  104. package/dist/v7-slug.js.map +1 -0
  105. package/dist/v7-timestamp.js +9 -0
  106. package/dist/v7-timestamp.js.map +1 -0
  107. package/dist/v7-value-options.js +28 -0
  108. package/dist/v7-value-options.js.map +1 -0
  109. package/dist/v7-value.d.ts +23 -0
  110. package/dist/v7-value.d.ts.map +1 -0
  111. package/dist/v7-value.js +31 -0
  112. package/dist/v7-value.js.map +1 -0
  113. package/dist/v7.js +127 -171
  114. package/dist/v7.js.map +1 -1
  115. package/package.json +14 -9
  116. package/src/alphabet.ts +456 -27
  117. package/src/base64url-name.ts +5 -0
  118. package/src/errors.ts +373 -37
  119. package/src/feistel.ts +69 -56
  120. package/src/generation-options.ts +48 -0
  121. package/src/index.ts +134 -80
  122. package/src/instant.ts +196 -0
  123. package/src/keyless.ts +7 -134
  124. package/src/mask-handle.ts +141 -0
  125. package/src/mask.ts +354 -129
  126. package/src/masking-codec-protocol.ts +29 -0
  127. package/src/masking-codec-types.ts +380 -0
  128. package/src/masking-codec.ts +923 -0
  129. package/src/migration.ts +195 -42
  130. package/src/payload.ts +321 -0
  131. package/src/runtime/bun.ts +30 -49
  132. package/src/runtime/node.ts +43 -24
  133. package/src/runtime/pool.ts +49 -21
  134. package/src/runtime/portable.ts +68 -0
  135. package/src/runtime/types.ts +23 -35
  136. package/src/sentinel.ts +13 -0
  137. package/src/siphash.ts +5 -4
  138. package/src/slug.ts +884 -0
  139. package/src/timestamp.ts +122 -0
  140. package/src/types.ts +759 -205
  141. package/src/uuid-value-protocol.ts +77 -0
  142. package/src/uuid-value.ts +341 -0
  143. package/src/uuid.ts +514 -234
  144. package/src/v4-slug.ts +27 -0
  145. package/src/v4.ts +234 -0
  146. package/src/v7-bounds.ts +171 -0
  147. package/src/v7-generator-input.ts +169 -0
  148. package/src/v7-generator.ts +245 -0
  149. package/src/v7-keyless.ts +354 -0
  150. package/src/v7-payload.ts +121 -0
  151. package/src/v7-slug.ts +293 -0
  152. package/src/v7-timestamp.ts +21 -0
  153. package/src/v7-value-options.ts +62 -0
  154. package/src/v7-value.ts +54 -0
  155. package/src/v7.ts +377 -200
  156. package/dist/base64url.d.ts +0 -20
  157. package/dist/base64url.d.ts.map +0 -1
  158. package/dist/base64url.js +0 -33
  159. package/dist/base64url.js.map +0 -1
  160. package/dist/codec.d.ts +0 -17
  161. package/dist/codec.d.ts.map +0 -1
  162. package/dist/codec.js +0 -192
  163. package/dist/codec.js.map +0 -1
  164. package/dist/keyless.d.ts +0 -31
  165. package/dist/keyless.d.ts.map +0 -1
  166. package/dist/keyless.js +0 -93
  167. package/dist/keyless.js.map +0 -1
  168. package/dist/legacy-mask.js +0 -55
  169. package/dist/legacy-mask.js.map +0 -1
  170. package/dist/node/alphabet.js +0 -130
  171. package/dist/node/base64url.js +0 -31
  172. package/dist/node/codec.js +0 -190
  173. package/dist/node/errors.js +0 -78
  174. package/dist/node/feistel.js +0 -103
  175. package/dist/node/index.js +0 -10
  176. package/dist/node/keyless.js +0 -91
  177. package/dist/node/legacy-mask.js +0 -53
  178. package/dist/node/mask.js +0 -106
  179. package/dist/node/migration.js +0 -64
  180. package/dist/node/runtime/node.js +0 -33
  181. package/dist/node/runtime/pool.js +0 -53
  182. package/dist/node/schema.js +0 -214
  183. package/dist/node/siphash.js +0 -106
  184. package/dist/node/uuid.js +0 -226
  185. package/dist/node/v7.js +0 -185
  186. package/dist/node/yield.js +0 -20
  187. package/dist/runtime/web.js +0 -39
  188. package/dist/runtime/web.js.map +0 -1
  189. package/dist/schema.d.ts +0 -20
  190. package/dist/schema.d.ts.map +0 -1
  191. package/dist/schema.js +0 -216
  192. package/dist/schema.js.map +0 -1
  193. package/dist/v7.d.ts +0 -12
  194. package/dist/v7.d.ts.map +0 -1
  195. package/dist/yield.js +0 -22
  196. package/dist/yield.js.map +0 -1
  197. package/src/base64url.ts +0 -41
  198. package/src/codec.ts +0 -320
  199. package/src/legacy-mask.ts +0 -25
  200. package/src/runtime/web.ts +0 -48
  201. package/src/schema.ts +0 -300
  202. package/src/yield.ts +0 -22
package/src/uuid.ts CHANGED
@@ -1,297 +1,577 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
 
3
- import { BASE32HEX, BASE64URL, decodeInto, encode, isEncoded } from "./alphabet";
4
- import type { Alphabet } from "./alphabet";
5
- import { checkRange, UuidSlugError } from "./errors";
3
+ import {
4
+ checkByteRange,
5
+ checkRange,
6
+ INVALID_BUFFER,
7
+ INVALID_OPTIONS,
8
+ INVALID_UUID,
9
+ isUuidSlugError,
10
+ isUint8Array,
11
+ normalizeUuidStringInput,
12
+ stringInput,
13
+ uuidByteView,
14
+ UuidSlugError,
15
+ } from "./errors.ts";
16
+ import { runtime } from "#runtime";
17
+ import type { Latin1Scratch } from "./runtime/types.ts";
18
+ import { UUID_TEXT_LOWERCASE, UUID_TEXT_UPPERCASE } from "./types.ts";
6
19
  import type {
7
- UuidSlug,
20
+ PreserveUuidVersion,
21
+ UuidBytes,
22
+ UuidByteInput,
23
+ UuidV4Bytes,
24
+ UuidV7Bytes,
8
25
  UuidString,
9
- UuidV4Slug,
26
+ UuidStringFor,
27
+ UuidText,
28
+ UuidOutput,
29
+ UuidTextCase,
30
+ UuidTextCaseArguments,
31
+ UuidStringInput,
10
32
  UuidV4String,
11
- UuidV7Slug,
33
+ UuidV4Text,
12
34
  UuidV7String,
13
- } from "./types";
35
+ UuidV7Text,
36
+ UuidVersion,
37
+ } from "./types.ts";
38
+
39
+ export { isUuidSlugError } from "./errors.ts";
40
+ export { UuidSlugError };
41
+ export type { UuidSlugErrorCode } from "./errors.ts";
42
+ export type { UuidBytes, UuidString } from "./types.ts";
43
+
44
+ /** Report byte input that does not hold exactly one 16-byte UUID. */
45
+ export const invalidUuidBytes = /* @__NO_SIDE_EFFECTS__ */ (): UuidSlugError =>
46
+ new UuidSlugError(INVALID_BUFFER, "UUID byte input must contain exactly 16 bytes.");
47
+
48
+ /** Borrow one exact UUID payload from any supported byte source. */
49
+ /*#__NO_SIDE_EFFECTS__*/
50
+ export function exactUuidByteView(value: unknown): Uint8Array | UuidSlugError {
51
+ if (isUuidSlugError(value)) return value;
52
+ const bytes = uuidByteView(value);
53
+ return bytes?.length === 16 ? bytes : invalidUuidBytes();
54
+ }
55
+
56
+ /** The canonical all-zero UUID value, without a version or issuance claim. */
57
+ export const NIL_UUID = "00000000-0000-0000-0000-000000000000" as UuidString;
58
+ /** The canonical all-one UUID value, without a version or issuance claim. */
59
+ export const MAX_UUID = "ffffffff-ffff-ffff-ffff-ffffffffffff" as UuidString;
14
60
 
15
61
  const HEX = "0123456789abcdef";
16
- // Probe once and allocate the byte-pair fallback only on engines that need it.
17
- const nativeToHex = (Uint8Array.prototype as { toHex?: () => string }).toHex;
18
- const HEX_BYTES = nativeToHex
19
- ? []
20
- : /*#__PURE__*/ Array.from(
21
- { length: 256 },
22
- (_, byte) => (HEX[byte >>> 4] as string) + (HEX[byte & 15] as string),
23
- );
62
+ const UPPERCASE_HEX = "0123456789ABCDEF";
63
+ const UUID_SEPARATOR = "-";
64
+
65
+ /** Keep case-option validation identical across every UUID-text writer. */
66
+ export const isUuidTextCase = (value: unknown): value is UuidTextCase =>
67
+ value === UUID_TEXT_LOWERCASE || value === UUID_TEXT_UPPERCASE;
68
+
69
+ /** Normalize a JavaScript string wrapper, then validate the public UUID text spelling. */
70
+ export function resolveUuidTextCase(value: unknown): UuidTextCase | UuidSlugError {
71
+ if (value === UUID_TEXT_LOWERCASE || value === UUID_TEXT_UPPERCASE) return value;
72
+ const textCase = stringInput(value);
73
+ return isUuidTextCase(textCase) ? textCase : invalidUuidTextCase();
74
+ }
75
+ export function invalidUuidTextCase(): UuidSlugError {
76
+ return new UuidSlugError(INVALID_OPTIONS, "UUID text case must be lowercase or uppercase.");
77
+ }
78
+ const createLatin1Scratch = runtime.latin1Scratch;
79
+ const nativeToHex = runtime.uuidHex;
24
80
  const HEX_DECODE = new Int8Array(128).fill(-1);
25
81
  for (let i = 0; i < 10; i += 1) HEX_DECODE[48 + i] = i;
26
82
  for (let i = 0; i < 6; i += 1) HEX_DECODE[97 + i] = 10 + i;
83
+ // Nibbles of both hex cases; 0x100 marks every other ASCII character so OR-ed pairs expose it.
84
+ const HEX_NIBBLES = new Uint16Array(128).fill(0x100);
85
+ for (let i = 0; i < 16; i += 1) {
86
+ HEX_NIBBLES[HEX.charCodeAt(i)] = i;
87
+ HEX_NIBBLES[UPPERCASE_HEX.charCodeAt(i)] = i;
88
+ }
89
+ // Bun's Latin-1 writer and the fixed writer share lazily built case tables; native hex needs none.
90
+ // bench/PERFORMANCE.md owns the comparison and recheck conditions. Tables are built on first use.
91
+ let uuidTextScratch: Latin1Scratch | undefined;
92
+ let lowercaseHexCodes: Uint8Array | undefined;
93
+ let uppercaseHexCodes: Uint8Array | undefined;
94
+ function hexCodes(digits: string): Uint8Array {
95
+ const codes = new Uint8Array(512);
96
+ for (let byte = 0; byte < 256; byte += 1) {
97
+ codes[byte * 2] = digits.charCodeAt(byte >>> 4);
98
+ codes[byte * 2 + 1] = digits.charCodeAt(byte & 15);
99
+ }
100
+ return codes;
101
+ }
102
+ function createUuidTextScratch(create: NonNullable<typeof createLatin1Scratch>): Latin1Scratch {
103
+ const scratch = create(UUID_LENGTH);
104
+ // Hyphens never move, so only the hex digits are written per call.
105
+ for (const hyphen of [8, 13, 18, 23]) scratch.bytes[hyphen] = UUID_SEPARATOR.charCodeAt(0);
106
+ return scratch;
107
+ }
108
+ /**
109
+ * Format through one native byte-to-string call instead of hex strings, slices, and concatenation;
110
+ * the result is also flat text that a reader need not flatten. The scratch is safe to share because
111
+ * nothing between these writes and the read can re-enter formatting.
112
+ */
113
+ function formatUuidBytesLatin1(
114
+ create: NonNullable<typeof createLatin1Scratch>,
115
+ bytes: Uint8Array,
116
+ offset: number,
117
+ textCase: UuidTextCase,
118
+ ): string {
119
+ const scratch = (uuidTextScratch ??= createUuidTextScratch(create));
120
+ const codes =
121
+ textCase === UUID_TEXT_UPPERCASE
122
+ ? (uppercaseHexCodes ??= hexCodes(UPPERCASE_HEX))
123
+ : (lowercaseHexCodes ??= hexCodes(HEX));
124
+ const text = scratch.bytes;
125
+ // Fixed positions remove the loop and offset-table reads on Bun's selected writer.
126
+ // The indexed loop loses repeated complete text calls; bench/PERFORMANCE.md owns the evidence.
127
+ // Keep native string construction and shared storage; remeasure after JSC or writer changes.
128
+ const code0 = (bytes[offset + 0] as number) * 2;
129
+ text[0] = codes[code0] as number;
130
+ text[1] = codes[code0 + 1] as number;
131
+ const code1 = (bytes[offset + 1] as number) * 2;
132
+ text[2] = codes[code1] as number;
133
+ text[3] = codes[code1 + 1] as number;
134
+ const code2 = (bytes[offset + 2] as number) * 2;
135
+ text[4] = codes[code2] as number;
136
+ text[5] = codes[code2 + 1] as number;
137
+ const code3 = (bytes[offset + 3] as number) * 2;
138
+ text[6] = codes[code3] as number;
139
+ text[7] = codes[code3 + 1] as number;
140
+ const code4 = (bytes[offset + 4] as number) * 2;
141
+ text[9] = codes[code4] as number;
142
+ text[10] = codes[code4 + 1] as number;
143
+ const code5 = (bytes[offset + 5] as number) * 2;
144
+ text[11] = codes[code5] as number;
145
+ text[12] = codes[code5 + 1] as number;
146
+ const code6 = (bytes[offset + 6] as number) * 2;
147
+ text[14] = codes[code6] as number;
148
+ text[15] = codes[code6 + 1] as number;
149
+ const code7 = (bytes[offset + 7] as number) * 2;
150
+ text[16] = codes[code7] as number;
151
+ text[17] = codes[code7 + 1] as number;
152
+ const code8 = (bytes[offset + 8] as number) * 2;
153
+ text[19] = codes[code8] as number;
154
+ text[20] = codes[code8 + 1] as number;
155
+ const code9 = (bytes[offset + 9] as number) * 2;
156
+ text[21] = codes[code9] as number;
157
+ text[22] = codes[code9 + 1] as number;
158
+ const code10 = (bytes[offset + 10] as number) * 2;
159
+ text[24] = codes[code10] as number;
160
+ text[25] = codes[code10 + 1] as number;
161
+ const code11 = (bytes[offset + 11] as number) * 2;
162
+ text[26] = codes[code11] as number;
163
+ text[27] = codes[code11 + 1] as number;
164
+ const code12 = (bytes[offset + 12] as number) * 2;
165
+ text[28] = codes[code12] as number;
166
+ text[29] = codes[code12 + 1] as number;
167
+ const code13 = (bytes[offset + 13] as number) * 2;
168
+ text[30] = codes[code13] as number;
169
+ text[31] = codes[code13 + 1] as number;
170
+ const code14 = (bytes[offset + 14] as number) * 2;
171
+ text[32] = codes[code14] as number;
172
+ text[33] = codes[code14 + 1] as number;
173
+ const code15 = (bytes[offset + 15] as number) * 2;
174
+ text[34] = codes[code15] as number;
175
+ text[35] = codes[code15 + 1] as number;
176
+ return scratch.text();
177
+ }
178
+ // Caller-owned output must stay unchanged when text fails, so its bytes are decoded here first.
179
+ const decodedUuidScratch = new Uint8Array(16);
27
180
 
28
181
  const UUID_LENGTH = 36;
182
+ const COMPACT_UUID_LENGTH = 32;
183
+ const UUID_URN_LENGTH = 45;
184
+ const BRACED_UUID_LENGTH = 38;
185
+ const UUID_URN_PREFIX = "urn:uuid:";
186
+ const INVALID_UUID_TEXT_START = -2;
187
+ const COMPACT_UUID_TEXT_START = -1;
29
188
  const UUID_BYTE_OFFSETS = [0, 2, 4, 6, 9, 11, 14, 16, 19, 21, 24, 26, 28, 30, 32, 34] as const;
30
189
 
31
- /**
32
- * The alphabets a plain slug may be written in. base64url is the default and the shortest;
33
- * base32hex costs four more characters and buys the one property base64url cannot offer: its
34
- * characters are in ASCII order, so base32hex slugs of UUIDv7s sort chronologically as plain
35
- * strings. Only the lowercase spelling decodes — the table is built from `chars` — so slugs have
36
- * no second spelling, as everywhere else in this format.
37
- *
38
- * MASKED slugs are always base64url (Art's ruling, 2026-08-12). Sort order there would be order of
39
- * ciphertext, which carries nothing, so the extra characters would buy only the case-insensitivity.
40
- */
41
- const SLUG_ALPHABETS: { base32hex: Alphabet; base64url: Alphabet } = {
42
- base32hex: BASE32HEX,
43
- base64url: BASE64URL,
44
- } as const;
45
-
46
- /**
47
- * Callers name an alphabet rather than passing one. `Alphabet` holds a decode table and a bit
48
- * width — internals that would become public surface the moment the type escaped — and accepting
49
- * an arbitrary one would also open a second extension point beside `MaskSchema`, which this
50
- * package documents as its only one. A union of two names cannot be widened by a caller at all, so
51
- * there is nothing to validate.
52
- */
53
- export type SlugAlphabet = keyof typeof SLUG_ALPHABETS;
190
+ /** Return the first canonical UUID character, or the compact/invalid sentinel. */
191
+ /*#__NO_SIDE_EFFECTS__*/
192
+ function uuidTextStart(value: string): number {
193
+ if (value.length === COMPACT_UUID_LENGTH) return COMPACT_UUID_TEXT_START;
194
+ if (value.length === UUID_LENGTH) return 0;
195
+ if (value.length === BRACED_UUID_LENGTH && value[0] === "{" && value[37] === "}") return 1;
196
+ if (value.length === UUID_URN_LENGTH) {
197
+ for (let index = 0; index < UUID_URN_PREFIX.length; index += 1)
198
+ if ((value.charCodeAt(index) | 32) !== UUID_URN_PREFIX.charCodeAt(index))
199
+ return INVALID_UUID_TEXT_START;
200
+ return UUID_URN_PREFIX.length;
201
+ }
202
+ return INVALID_UUID_TEXT_START;
203
+ }
54
204
 
55
- /** Reject inherited property names as well as unknown names from JavaScript callers. */
56
- export function resolveSlugAlphabet(alphabet: SlugAlphabet): Alphabet | UuidSlugError {
57
- return Object.hasOwn(SLUG_ALPHABETS, alphabet)
58
- ? SLUG_ALPHABETS[alphabet]
59
- : new UuidSlugError(
60
- "invalid_uuid_slug",
61
- `Unknown slug alphabet "${alphabet}"; expected ${Object.keys(SLUG_ALPHABETS).join(" or ")}.`,
62
- );
205
+ /*#__NO_SIDE_EFFECTS__*/
206
+ function lowercaseHexValue(code: number) {
207
+ return HEX_DECODE[code] ?? -1;
63
208
  }
64
209
 
65
- /** Characters needed for 16 bytes: 22 in base64url, 26 in base32hex. */
66
- function slugLength(alpha: Alphabet) {
67
- return Math.ceil(128 / alpha.bitsPerChar);
210
+ /*#__NO_SIDE_EFFECTS__*/
211
+ function parsedHexValue(code: number) {
212
+ return code >= 65 && code <= 70 ? code - 55 : lowercaseHexValue(code);
68
213
  }
69
214
 
70
215
  /**
71
- * Length -> alphabet, which is why decoding takes no alphabet argument: the two lengths are
72
- * disjoint, so a slug names its own encoding and a caller cannot pick the wrong one. Indexed
73
- * rather than searched because every decode and every type guard pays this lookup.
216
+ * Parse accepted mixed-case UUID text into a new plain 16-byte `Uint8Array`. Accept canonical or
217
+ * compact text, a UUID URN, or brace-wrapped canonical text. Known slug values are rejected by
218
+ * TypeScript; invalid text returns `UuidSlugError`. A preceding `UuidSlugError` is returned unchanged.
219
+ *
220
+ * @param uuid - UUID text in an accepted spelling. JavaScript also accepts a genuine `String` object.
221
+ */
222
+ export function uuidStringToBytes<Input extends string | UuidSlugError>(
223
+ uuid: UuidStringInput<Input>,
224
+ ): PreserveUuidVersion<Input, UuidBytes, UuidV4Bytes, UuidV7Bytes> | UuidSlugError;
225
+ /**
226
+ * Parse accepted mixed-case UUID text into caller-owned storage after validating the full input.
227
+ * A preceding `UuidSlugError` is returned unchanged without writing.
228
+ *
229
+ * @param uuid - UUID text in an accepted spelling. JavaScript also accepts a genuine `String` object.
230
+ * @param output - Caller-owned array that receives the 16 UUID bytes.
231
+ * @param outputOffset - Zero-based index where writing starts. Omit to start at index 0. Bytes
232
+ * outside the written range stay unchanged.
74
233
  */
75
- const SLUG_ALPHABET_BY_LENGTH: readonly (Alphabet | undefined)[] = Object.values(
76
- SLUG_ALPHABETS,
77
- ).reduce<(Alphabet | undefined)[]>((table, alpha) => {
78
- table[slugLength(alpha)] = alpha;
79
- return table;
80
- }, []);
81
-
82
- const SLUG_LENGTHS = Object.values(SLUG_ALPHABETS)
83
- .map((alpha) => `${slugLength(alpha)} (${alpha.name})`)
84
- .join(" or ");
85
-
86
- function hexValue(code: number) {
87
- return HEX_DECODE[code] ?? -1;
88
- }
89
-
90
- export function parseUuid(uuid: string, out?: Uint8Array, offset = 0): UuidSlugError | Uint8Array {
91
- if (uuid.length !== UUID_LENGTH)
92
- return new UuidSlugError("invalid_uuid", "UUID must be 36 characters.");
93
- if (uuid[8] !== "-" || uuid[13] !== "-" || uuid[18] !== "-" || uuid[23] !== "-") {
94
- return new UuidSlugError("invalid_uuid", "UUID hyphen positions are invalid.");
234
+ export function uuidStringToBytes<Input extends string | UuidSlugError, Output extends Uint8Array>(
235
+ uuid: UuidStringInput<Input>,
236
+ output: Output,
237
+ outputOffset?: number,
238
+ ): UuidOutput<Output> | UuidSlugError;
239
+ export function uuidStringToBytes(
240
+ uuid: string | UuidSlugError,
241
+ out?: Uint8Array,
242
+ offset = 0,
243
+ ): Uint8Array | UuidSlugError {
244
+ let uuidText = uuid;
245
+ if (typeof uuidText !== "string") {
246
+ uuidText = normalizeUuidStringInput(uuidText);
247
+ if (typeof uuidText !== "string") return uuidText;
95
248
  }
96
-
97
- const target = out ?? new Uint8Array(16);
98
- const badRange = checkRange(target.length, offset, 16);
249
+ const textStart = uuidTextStart(uuidText);
250
+ if (textStart === INVALID_UUID_TEXT_START)
251
+ return new UuidSlugError(
252
+ INVALID_UUID,
253
+ "UUID must be canonical, compact, a UUID URN, or brace-wrapped canonical text.",
254
+ );
255
+ const hyphenated = textStart !== COMPACT_UUID_TEXT_START;
256
+ if (
257
+ hyphenated &&
258
+ (uuidText[textStart + 8] !== UUID_SEPARATOR ||
259
+ uuidText[textStart + 13] !== UUID_SEPARATOR ||
260
+ uuidText[textStart + 18] !== UUID_SEPARATOR ||
261
+ uuidText[textStart + 23] !== UUID_SEPARATOR)
262
+ )
263
+ return new UuidSlugError(INVALID_UUID, "UUID hyphen positions are invalid.");
264
+
265
+ const badRange = out === undefined ? checkRange(16, offset, 16) : checkByteRange(out, offset, 16);
99
266
  if (badRange) return badRange;
100
267
 
101
- for (let byteIndex = 0; byteIndex < UUID_BYTE_OFFSETS.length; byteIndex += 1) {
102
- const textOffset = UUID_BYTE_OFFSETS[byteIndex] as number;
103
- const high = hexValue(uuid.charCodeAt(textOffset));
104
- const low = hexValue(uuid.charCodeAt(textOffset + 1));
105
- if (high < 0 || low < 0)
106
- return new UuidSlugError("invalid_uuid", `Invalid UUID hex at offset ${textOffset}.`);
107
- target[offset + byteIndex] = (high << 4) | low;
268
+ // One pass decodes and validates: OR-ing every character code and every decoded pair exposes a
269
+ // non-ASCII or non-hex character after the loop. Validating before a second decoding pass cost
270
+ // about twice as much on Node and three times on Bun (bench/PERFORMANCE.md). Only failing text
271
+ // pays a second scan, which locates the offset for the message.
272
+ const target = out === undefined ? new Uint8Array(16) : decodedUuidScratch;
273
+ let codes = 0;
274
+ let pairs = 0;
275
+ for (let byteIndex = 0; byteIndex < 16; byteIndex += 1) {
276
+ const textOffset = hyphenated
277
+ ? textStart + (UUID_BYTE_OFFSETS[byteIndex] as number)
278
+ : byteIndex * 2;
279
+ const high = uuidText.charCodeAt(textOffset);
280
+ const low = uuidText.charCodeAt(textOffset + 1);
281
+ const pair = ((HEX_NIBBLES[high & 127] as number) << 4) | (HEX_NIBBLES[low & 127] as number);
282
+ codes |= high | low;
283
+ pairs |= pair;
284
+ target[byteIndex] = pair;
285
+ }
286
+ if (codes < 128 && pairs < 256) {
287
+ if (out === undefined) return target;
288
+ // A byte loop rather than `set`: the native call made Bun text-to-slug conversion slower
289
+ // (bench/PERFORMANCE.md).
290
+ for (let byteIndex = 0; byteIndex < 16; byteIndex += 1)
291
+ out[offset + byteIndex] = target[byteIndex] as number;
292
+ return out;
293
+ }
294
+ // Name the first invalid pair with the same test as the decoding pass, so the scan stops within
295
+ // the 16 pairs even if the two ever disagree.
296
+ let textOffset = 0;
297
+ for (let byteIndex = 0; byteIndex < 16; byteIndex += 1) {
298
+ textOffset = hyphenated ? textStart + (UUID_BYTE_OFFSETS[byteIndex] as number) : byteIndex * 2;
299
+ const high = uuidText.charCodeAt(textOffset);
300
+ const low = uuidText.charCodeAt(textOffset + 1);
301
+ if (
302
+ (high | low) > 127 ||
303
+ (HEX_NIBBLES[high] as number) > 15 ||
304
+ (HEX_NIBBLES[low] as number) > 15
305
+ )
306
+ break;
108
307
  }
109
- return target;
308
+ return new UuidSlugError(
309
+ INVALID_UUID,
310
+ `Invalid UUID hex at offset ${textOffset}; use 0-9, a-f, or A-F.`,
311
+ );
110
312
  }
111
313
 
112
- export function formatUuid(bytes: Uint8Array, offset = 0): UuidSlugError | UuidString {
113
- const badRange = checkRange(bytes.length, offset, 16);
314
+ /**
315
+ * Format 16 bytes as standard hyphenated UUID text without assigning a version. A standalone
316
+ * `ArrayBuffer` uses its whole contents; a `DataView` uses its declared range. Only `Uint8Array`
317
+ * input accepts an explicit offset. Invalid input returns `invalid_buffer`, and a preceding
318
+ * `UuidSlugError` is returned unchanged.
319
+ *
320
+ * @param bytes - One supported UUID byte source.
321
+ * @param textCase - Built-in output spelling. Omit for lowercase.
322
+ * @defaultValue `UUID_TEXT_LOWERCASE`
323
+ * @param byteOffset - Zero-based index where the UUID starts. Omit for a standalone UUID.
324
+ */
325
+ export function bytesToUuidString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
326
+ bytes: UuidByteInput | UuidSlugError,
327
+ ...textCase: UuidTextCaseArguments<Case>
328
+ ): UuidStringFor<Case> | UuidSlugError;
329
+ export function bytesToUuidString<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
330
+ bytes: Uint8Array | UuidSlugError,
331
+ byteOffset: number,
332
+ ...textCase: UuidTextCaseArguments<Case>
333
+ ): UuidStringFor<Case> | UuidSlugError;
334
+ /*#__NO_SIDE_EFFECTS__*/
335
+ export function bytesToUuidString(
336
+ bytes: UuidByteInput | UuidSlugError,
337
+ offsetOrCase: number | UuidTextCase = 0,
338
+ textCase: UuidTextCase = UUID_TEXT_LOWERCASE,
339
+ ): UuidString | string | UuidSlugError {
340
+ const view = isUint8Array(bytes) ? bytes : exactUuidByteView(bytes);
341
+ if (view instanceof Error) return view;
342
+ const caseIsSecond =
343
+ typeof offsetOrCase === "string"
344
+ ? Number.isNaN(Number(offsetOrCase))
345
+ : typeof offsetOrCase !== "number";
346
+ const byteOffset = (caseIsSecond ? 0 : offsetOrCase) as number;
347
+ const selectedCase = resolveUuidTextCase(caseIsSecond ? offsetOrCase : textCase);
348
+ if (selectedCase instanceof Error) return selectedCase;
349
+ const badRange = checkRange(view.length, byteOffset, 16);
114
350
  if (badRange) return badRange;
115
351
  if (nativeToHex) {
116
- const hex = nativeToHex.call(bytes.length === 16 ? bytes : bytes.subarray(offset, offset + 16));
117
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
352
+ // A small existing view avoids another view; a larger buffer must not encode unrelated bytes.
353
+ const hex =
354
+ view.length <= 32
355
+ ? nativeToHex(view)
356
+ : nativeToHex(view.subarray(byteOffset, byteOffset + 16));
357
+ const offset = view.length <= 32 ? byteOffset * 2 : 0;
358
+ const uuid = hyphenateHex(hex, offset);
359
+ return selectedCase === UUID_TEXT_UPPERCASE ? uuid.toUpperCase() : uuid;
118
360
  }
119
- let out = "";
120
- for (let i = 0; i < 16; i += 1) {
121
- if (i === 4 || i === 6 || i === 8 || i === 10) out += "-";
122
- const byte = bytes[offset + i] ?? 0;
123
- out += HEX_BYTES[byte];
361
+ return formatUuidBytesUnchecked(view, byteOffset, selectedCase);
362
+ }
363
+
364
+ const hyphenateHex = /* @__NO_SIDE_EFFECTS__ */ (hex: string, offset: number): UuidString =>
365
+ `${hex.slice(offset, offset + 8)}-${hex.slice(offset + 8, offset + 12)}-${hex.slice(offset + 12, offset + 16)}-${hex.slice(offset + 16, offset + 20)}-${hex.slice(offset + 20, offset + 32)}` as UuidString;
366
+
367
+ /** Format a complete UUID byte range already validated by its caller. */
368
+ /*#__NO_SIDE_EFFECTS__*/
369
+ export function formatUuidBytesUnchecked<Case extends UuidTextCase = typeof UUID_TEXT_LOWERCASE>(
370
+ bytes: Uint8Array,
371
+ offset = 0,
372
+ textCase: Case = UUID_TEXT_LOWERCASE as Case,
373
+ ): UuidStringFor<Case> {
374
+ // Bun retains its Latin-1 writer. A fixed argument list makes one flat string without
375
+ // temporary bytes, intermediate hex or concatenation. WebKit selects native hex to avoid
376
+ // repeated mixed-workload losses; remeasure both paths after engine changes
377
+ // (bench/PERFORMANCE.md). Keep case selection and fixed writing together to avoid another call.
378
+ if (createLatin1Scratch)
379
+ return formatUuidBytesLatin1(
380
+ createLatin1Scratch,
381
+ bytes,
382
+ offset,
383
+ textCase,
384
+ ) as UuidStringFor<Case>;
385
+ if (nativeToHex) {
386
+ const uuid = hyphenateHex(nativeToHex(bytes), offset * 2);
387
+ return (textCase === UUID_TEXT_UPPERCASE ? uuid.toUpperCase() : uuid) as UuidStringFor<Case>;
124
388
  }
125
- return out;
389
+ const codes =
390
+ textCase === UUID_TEXT_UPPERCASE
391
+ ? (uppercaseHexCodes ??= hexCodes(UPPERCASE_HEX))
392
+ : (lowercaseHexCodes ??= hexCodes(HEX));
393
+ const a = (bytes[offset] as number) * 2;
394
+ const b = (bytes[offset + 1] as number) * 2;
395
+ const c = (bytes[offset + 2] as number) * 2;
396
+ const d = (bytes[offset + 3] as number) * 2;
397
+ const e = (bytes[offset + 4] as number) * 2;
398
+ const f = (bytes[offset + 5] as number) * 2;
399
+ const g = (bytes[offset + 6] as number) * 2;
400
+ const h = (bytes[offset + 7] as number) * 2;
401
+ const i = (bytes[offset + 8] as number) * 2;
402
+ const j = (bytes[offset + 9] as number) * 2;
403
+ const k = (bytes[offset + 10] as number) * 2;
404
+ const l = (bytes[offset + 11] as number) * 2;
405
+ const m = (bytes[offset + 12] as number) * 2;
406
+ const n = (bytes[offset + 13] as number) * 2;
407
+ const o = (bytes[offset + 14] as number) * 2;
408
+ const p = (bytes[offset + 15] as number) * 2;
409
+ return String.fromCharCode(
410
+ codes[a] as number,
411
+ codes[a + 1] as number,
412
+ codes[b] as number,
413
+ codes[b + 1] as number,
414
+ codes[c] as number,
415
+ codes[c + 1] as number,
416
+ codes[d] as number,
417
+ codes[d + 1] as number,
418
+ 45,
419
+ codes[e] as number,
420
+ codes[e + 1] as number,
421
+ codes[f] as number,
422
+ codes[f + 1] as number,
423
+ 45,
424
+ codes[g] as number,
425
+ codes[g + 1] as number,
426
+ codes[h] as number,
427
+ codes[h + 1] as number,
428
+ 45,
429
+ codes[i] as number,
430
+ codes[i + 1] as number,
431
+ codes[j] as number,
432
+ codes[j + 1] as number,
433
+ 45,
434
+ codes[k] as number,
435
+ codes[k + 1] as number,
436
+ codes[l] as number,
437
+ codes[l + 1] as number,
438
+ codes[m] as number,
439
+ codes[m + 1] as number,
440
+ codes[n] as number,
441
+ codes[n + 1] as number,
442
+ codes[o] as number,
443
+ codes[o + 1] as number,
444
+ codes[p] as number,
445
+ codes[p + 1] as number,
446
+ ) as UuidStringFor<Case>;
126
447
  }
127
448
 
128
- export function uuidVersion(bytes: Uint8Array, offset = 0): number {
129
- return (bytes[offset + 6] ?? 0) >>> 4;
449
+ /*#__NO_SIDE_EFFECTS__*/
450
+ export function uuidVersion(bytes: Uint8Array, offset = 0): UuidVersion {
451
+ return ((bytes[offset + 6] ?? 0) >>> 4) as UuidVersion;
130
452
  }
131
453
 
454
+ /*#__NO_SIDE_EFFECTS__*/
132
455
  export function isRfcVariant(bytes: Uint8Array, offset = 0): boolean {
133
456
  return (bytes[offset + 8] ?? 0) >>> 6 === 0b10;
134
457
  }
135
458
 
136
- // Predicates inspect the same hex table as parsing without allocating output bytes or Errors.
137
- export function isUuidString(uuid: null | string | undefined): uuid is UuidString {
138
- if (!uuid || uuid.length !== UUID_LENGTH) return false;
139
- if (uuid[8] !== "-" || uuid[13] !== "-" || uuid[18] !== "-" || uuid[23] !== "-") return false;
459
+ // Accepted-text parsing uses the shared hex table without allocating output bytes or Errors.
460
+ /** Check accepted UUID text without claiming a version, variant, or issuance. */
461
+ /*#__NO_SIDE_EFFECTS__*/
462
+ export function isUuidText(value: unknown): value is UuidText {
463
+ if (typeof value !== "string") return false;
464
+ const textStart = uuidTextStart(value);
465
+ if (textStart === INVALID_UUID_TEXT_START) return false;
466
+ const hyphenated = textStart !== COMPACT_UUID_TEXT_START;
467
+ if (
468
+ hyphenated &&
469
+ (value[textStart + 8] !== UUID_SEPARATOR ||
470
+ value[textStart + 13] !== UUID_SEPARATOR ||
471
+ value[textStart + 18] !== UUID_SEPARATOR ||
472
+ value[textStart + 23] !== UUID_SEPARATOR)
473
+ )
474
+ return false;
140
475
  for (let i = 0; i < UUID_BYTE_OFFSETS.length; i += 1) {
141
- const offset = UUID_BYTE_OFFSETS[i] as number;
142
- if (hexValue(uuid.charCodeAt(offset)) < 0 || hexValue(uuid.charCodeAt(offset + 1)) < 0)
476
+ const offset = hyphenated ? textStart + (UUID_BYTE_OFFSETS[i] as number) : i * 2;
477
+ if (
478
+ parsedHexValue(value.charCodeAt(offset)) < 0 ||
479
+ parsedHexValue(value.charCodeAt(offset + 1)) < 0
480
+ )
143
481
  return false;
144
482
  }
145
483
  return true;
146
484
  }
147
485
 
148
- /** The string has already passed canonical validation, so the variant digit is a known hex value. */
149
- function stringHasRfcVariant(uuid: string): boolean {
150
- return (HEX_DECODE[uuid.charCodeAt(19)] as number) >>> 2 === 2;
151
- }
152
-
153
- export function isUuidV4String(uuid: null | string | undefined): uuid is UuidV4String {
154
- return isUuidString(uuid) && uuid[14] === "4" && stringHasRfcVariant(uuid);
155
- }
156
-
157
- export function isUuidV7String(uuid: null | string | undefined): uuid is UuidV7String {
158
- return isUuidString(uuid) && uuid[14] === "7" && stringHasRfcVariant(uuid);
159
- }
160
-
161
- /**
162
- * The only BYTE-level predicate, and the asymmetry against `isUuidV4String` is deliberate: masking
163
- * accepts v7 alone, so a caller holding raw bytes has a reason to ask this and none to ask the v4
164
- * question. `isUuidV4Bytes` is absent because nothing needs it, not because it was overlooked —
165
- * add it when a caller appears, never for symmetry, since an export is permanent surface.
166
- */
167
- export function isUuidV7Bytes(bytes: Uint8Array): boolean {
168
- return bytes.length === 16 && uuidVersion(bytes) === 7 && isRfcVariant(bytes);
169
- }
170
-
171
- export function formatUuidSlug(
172
- bytes: Uint8Array,
173
- offset = 0,
174
- alphabet: SlugAlphabet = "base64url",
175
- ): UuidSlugError | UuidSlug {
176
- const badRange = checkRange(bytes.length, offset, 16);
177
- if (badRange) return badRange;
178
- // Unreachable from TypeScript, where the name is a two-member union. Reached from JavaScript,
179
- // which is why it answers rather than indexing into `undefined`.
180
- const alpha = resolveSlugAlphabet(alphabet);
181
- if (alpha instanceof Error) return alpha;
182
- return encode(bytes.length === 16 ? bytes : bytes.subarray(offset, offset + 16), alpha);
183
- }
184
-
185
- /** Accepts either alphabet; the length says which, so there is nothing to pass and nothing to get wrong. */
186
- export function parseUuidSlug(
187
- slug: string,
188
- out?: Uint8Array,
189
- offset = 0,
190
- ): UuidSlugError | Uint8Array {
191
- const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];
192
- if (!alpha)
193
- return new UuidSlugError(
194
- "invalid_uuid_slug",
195
- `UUID slug must be ${SLUG_LENGTHS} characters, got ${slug.length}.`,
196
- );
197
- const target = out ?? new Uint8Array(16);
198
- const result = decodeInto(slug, alpha, target, offset, 16);
199
- return result instanceof Error ? result : target;
200
- }
201
-
202
- export function uuidToSlug(
203
- uuid: string,
204
- alphabet: SlugAlphabet = "base64url",
205
- ): UuidSlugError | UuidSlug {
206
- const bytes = parseUuid(uuid);
207
- if (bytes instanceof Error) return bytes;
208
- return formatUuidSlug(bytes, 0, alphabet);
486
+ // Canonical guards stay regular expressions: a character loop measured slower on Node and Bun
487
+ // (bench/PERFORMANCE.md, Canonical UUID text).
488
+ // Pair repetition improves canonical calls, but slows Bun's successful base32 normalization.
489
+ // Reuse its existing Latin-1 selection once; neither pattern needs a builder or per-call dispatch.
490
+ // Remeasure normalization if this capability moves to another adapter (bench/PERFORMANCE.md).
491
+ const UUID_RE = createLatin1Scratch
492
+ ? /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
493
+ : /^(?:[0-9a-f][0-9a-f]){4}-(?:[0-9a-f][0-9a-f]){2}-(?:[0-9a-f][0-9a-f]){2}-(?:[0-9a-f][0-9a-f]){2}-(?:[0-9a-f][0-9a-f]){6}$/;
494
+ const UUID_V4_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
495
+ const UUID_V7_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
496
+ const UUID_V7_TEXT_RE = /*#__PURE__*/ new RegExp(UUID_V7_RE.source, "i");
497
+
498
+ /** Check accepted UUID text with version 4 and RFC variant bits. */
499
+ /*#__NO_SIDE_EFFECTS__*/
500
+ export function isUuidV4Text(value: unknown): value is UuidV4Text {
501
+ if (!isUuidText(value)) return false;
502
+ const textStart = uuidTextStart(value);
503
+ const variant = parsedHexValue(
504
+ value.charCodeAt(textStart === COMPACT_UUID_TEXT_START ? 16 : textStart + 19),
505
+ );
506
+ return (
507
+ parsedHexValue(
508
+ value.charCodeAt(textStart === COMPACT_UUID_TEXT_START ? 12 : textStart + 14),
509
+ ) === 4 &&
510
+ variant >= 8 &&
511
+ variant <= 11
512
+ );
209
513
  }
210
514
 
211
- export function slugToUuid(slug: string): UuidSlugError | UuidString {
212
- const bytes = parseUuidSlug(slug);
213
- if (bytes instanceof Error) return bytes;
214
- return formatUuid(bytes);
515
+ /** Check accepted UUID text with version 7 and RFC variant bits. */
516
+ /*#__NO_SIDE_EFFECTS__*/
517
+ export function isUuidV7Text(value: unknown): value is UuidV7Text {
518
+ // Canonical text uses the same syntax with either case, avoiding the full digit loop before
519
+ // timestamp parsing. Other spellings retain their existing checks; remeasure after engine or
520
+ // accepted-syntax changes (bench/PERFORMANCE.md).
521
+ if (typeof value === "string" && value.length === UUID_LENGTH) return UUID_V7_TEXT_RE.test(value);
522
+ if (!isUuidText(value)) return false;
523
+ const textStart = uuidTextStart(value);
524
+ const variant = parsedHexValue(
525
+ value.charCodeAt(textStart === COMPACT_UUID_TEXT_START ? 16 : textStart + 19),
526
+ );
527
+ return (
528
+ parsedHexValue(
529
+ value.charCodeAt(textStart === COMPACT_UUID_TEXT_START ? 12 : textStart + 14),
530
+ ) === 7 &&
531
+ variant >= 8 &&
532
+ variant <= 11
533
+ );
215
534
  }
216
535
 
217
- export function isUuidSlug(slug: null | string | undefined): slug is UuidSlug {
218
- if (!slug) return false;
219
- const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length];
220
- return alpha !== undefined && isEncoded(slug, alpha, 16);
536
+ /** Check canonical lowercase UUID text without claiming a version, variant, or issuance. */
537
+ export function isUuidString(value: unknown): value is UuidString {
538
+ return typeof value === "string" && UUID_RE.test(value);
221
539
  }
222
-
223
- /** Read only the version/variant bytes after canonical validation, without decoding a whole UUID. */
224
- function slugByte(slug: string, alpha: Alphabet, offset: number): number {
225
- const start = Math.floor((offset * 8) / alpha.bitsPerChar);
226
- const end = Math.floor((offset * 8 + 7) / alpha.bitsPerChar);
227
- let value = 0;
228
- for (let i = start; i <= end; i += 1)
229
- value = (value << alpha.bitsPerChar) | (alpha.decode[slug.charCodeAt(i)] as number);
230
- return (value >>> ((end + 1) * alpha.bitsPerChar - (offset + 1) * 8)) & 255;
540
+ /** Check canonical lowercase UUIDv4 text with RFC variant bits. */
541
+ export function isUuidV4String(value: unknown): value is UuidV4String {
542
+ return typeof value === "string" && UUID_V4_RE.test(value);
231
543
  }
232
-
233
- function isVersionedSlug(slug: null | string | undefined, version: number): boolean {
234
- if (!isUuidSlug(slug)) return false;
235
- const alpha = SLUG_ALPHABET_BY_LENGTH[slug.length] as Alphabet;
236
- return slugByte(slug, alpha, 6) >>> 4 === version && slugByte(slug, alpha, 8) >>> 6 === 2;
544
+ /** Check canonical lowercase UUIDv7 text with RFC variant bits. */
545
+ export function isUuidV7String(value: unknown): value is UuidV7String {
546
+ return typeof value === "string" && UUID_V7_RE.test(value);
237
547
  }
238
548
 
239
- export function isUuidV4Slug(slug: null | string | undefined): slug is UuidV4Slug {
240
- return isVersionedSlug(slug, 4);
549
+ /** Check for a 16-byte `Uint8Array` without claiming a UUID version or issuance. */
550
+ /*#__NO_SIDE_EFFECTS__*/
551
+ export function isUuidBytes(value: unknown): value is UuidBytes {
552
+ return isUint8Array(value) && value.length === 16;
241
553
  }
242
554
 
243
- export function isUuidV7Slug(slug: null | string | undefined): slug is UuidV7Slug {
244
- return isVersionedSlug(slug, 7);
555
+ /** Check for exactly 16 UUIDv4 bytes with the RFC variant required by generation. */
556
+ /*#__NO_SIDE_EFFECTS__*/
557
+ export function isUuidV4Bytes(value: unknown): value is UuidV4Bytes {
558
+ return isUuidBytes(value) && uuidVersion(value) === 4 && isRfcVariant(value);
245
559
  }
246
560
 
247
561
  /**
248
- * The 48-bit millisecond a UUIDv7 was minted at.
249
- *
250
- * It REFUSES anything that is not a v7, which is the whole point of the return type: the first six
251
- * bytes of a v4 are random, so reading them yields a confident, well-formed date drawn uniformly
252
- * from the next nine thousand years. A caller that passed the wrong version got that date silently,
253
- * and a freshness check built on it would accept or reject by coin flip while looking correct.
254
- *
255
- * Short input is reported separately from wrong version, because `uuidVersion` reads a missing byte
256
- * as zero and would otherwise blame a truncated buffer for holding a v0.
562
+ * Check for exactly 16 UUIDv7 bytes with the RFC variant required by masking and timestamps.
563
+ * General byte input can use `bytesToUuidString`; this narrower predicate proves the version those
564
+ * v7-only operations require.
257
565
  */
258
- export function extractUuidV7Timestamp(bytes: Uint8Array, offset = 0): UuidSlugError | number {
259
- const badRange = checkRange(bytes.length, offset, 16);
260
- if (badRange) return badRange;
261
- if (uuidVersion(bytes, offset) !== 7 || !isRfcVariant(bytes, offset))
262
- return new UuidSlugError("invalid_uuid_version", "Timestamp is only defined for UUIDv7.");
263
- let timestamp = 0;
264
- for (let i = 0; i < 6; i += 1) timestamp = timestamp * 256 + (bytes[offset + i] ?? 0);
265
- return timestamp;
566
+ /*#__NO_SIDE_EFFECTS__*/
567
+ export function isUuidV7Bytes(value: unknown): value is UuidV7Bytes {
568
+ return isUuidBytes(value) && uuidVersion(value) === 7 && isRfcVariant(value);
266
569
  }
267
570
 
268
- /**
269
- * Whether a v7's 74 random bits are anything other than all-zero or all-one — the two patterns a
270
- * generator produces when its entropy source is absent rather than working.
271
- *
272
- * Out of range answers `false`, and the direction is the whole point. Without the check the reads
273
- * below fall through `?? 0`, so a missing byte is indistinguishable from a zero byte and only ever
274
- * in the reassuring direction: a short buffer reported entropy PRESENT, and an offset past the end
275
- * reported the degenerate case for data that was never examined. Both are answers about bytes the
276
- * caller does not have. `false` is the honest one — it means "cannot be shown to carry entropy",
277
- * which is what a caller acts on, and it is what a truly degenerate id gets too.
278
- *
279
- * Boolean rather than `UuidSlugError | boolean` because the sole use is a guard in a condition; an error
280
- * return would have every call site unwrap a value it is already treating as a yes/no.
281
- */
282
- export function hasUuidV7Entropy(bytes: Uint8Array, offset = 0): boolean {
283
- if (checkRange(bytes.length, offset, 16)) return false;
284
- const randA = (((bytes[offset + 6] ?? 0) & 0x0f) << 8) | (bytes[offset + 7] ?? 0);
285
- const randBFirst = (bytes[offset + 8] ?? 0) & 0x3f;
286
- let restZero = true;
287
- let restMax = true;
288
- for (let i = 9; i < 16; i += 1) {
289
- const byte = bytes[offset + i] ?? 0;
290
- if (byte !== 0x00) restZero = false;
291
- if (byte !== 0xff) restMax = false;
292
- }
293
- return (
294
- !(randA === 0 && randBFirst === 0 && restZero) &&
295
- !(randA === 0x0fff && randBFirst === 0x3f && restMax)
296
- );
571
+ /** Read one 48-bit big-endian timestamp without allocating an intermediate representation. */
572
+ /*#__NO_SIDE_EFFECTS__*/
573
+ export function uuidTimestampFromBytesUnchecked(bytes: Uint8Array, byteOffset: number): number {
574
+ let timestamp = 0;
575
+ for (let i = 0; i < 6; i += 1) timestamp = timestamp * 256 + (bytes[byteOffset + i] ?? 0);
576
+ return timestamp;
297
577
  }