uniku 0.0.12 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +63 -13
  2. package/build/{bytes-BBjKLOBR.mjs → bytes-DzcOKIx1.mjs} +1 -1
  3. package/build/{bytes-BBjKLOBR.mjs.map → bytes-DzcOKIx1.mjs.map} +1 -1
  4. package/build/cuid2/cuid2.d.mts.map +1 -1
  5. package/build/cuid2/cuid2.mjs +1 -1
  6. package/build/cuid2/cuid2.mjs.map +1 -1
  7. package/build/ksuid/ksuid.d.mts.map +1 -1
  8. package/build/ksuid/ksuid.mjs +1 -1
  9. package/build/ksuid/ksuid.mjs.map +1 -1
  10. package/build/nanoid/nanoid.d.mts.map +1 -1
  11. package/build/nanoid/nanoid.mjs +1 -1
  12. package/build/nanoid/nanoid.mjs.map +1 -1
  13. package/build/random-CGMm8owG.mjs +2 -0
  14. package/build/random-CGMm8owG.mjs.map +1 -0
  15. package/build/tsconfig.tsbuildinfo +1 -1
  16. package/build/typeid/typeid.d.mts +38 -0
  17. package/build/typeid/typeid.d.mts.map +1 -0
  18. package/build/typeid/typeid.mjs +2 -0
  19. package/build/typeid/typeid.mjs.map +1 -0
  20. package/build/ulid/ulid.d.mts.map +1 -1
  21. package/build/ulid/ulid.mjs +1 -1
  22. package/build/ulid/ulid.mjs.map +1 -1
  23. package/build/uuid/v4.mjs +1 -1
  24. package/build/uuid/v7.d.mts.map +1 -1
  25. package/build/uuid/v7.mjs +1 -1
  26. package/build/uuid/v7.mjs.map +1 -1
  27. package/build/{uuid-QysI8pWE.mjs → uuid-Ub6ladEr.mjs} +1 -1
  28. package/build/{uuid-QysI8pWE.mjs.map → uuid-Ub6ladEr.mjs.map} +1 -1
  29. package/package.json +21 -31
  30. package/src/common/bytes.ts +59 -0
  31. package/src/common/random.ts +66 -0
  32. package/src/cuid2/cuid2.ts +211 -0
  33. package/src/errors.ts +56 -0
  34. package/src/ksuid/base62.ts +103 -0
  35. package/src/ksuid/ksuid.ts +195 -0
  36. package/src/nanoid/nanoid.ts +257 -0
  37. package/src/typeid/typeid.ts +283 -0
  38. package/src/ulid/crockford.ts +249 -0
  39. package/src/ulid/ulid.ts +184 -0
  40. package/src/uuid/common/hex.ts +24 -0
  41. package/src/uuid/common/uuid.ts +157 -0
  42. package/src/uuid/v4.ts +119 -0
  43. package/src/uuid/v7.ts +182 -0
  44. package/build/random-DcKA4vF7.mjs +0 -2
  45. package/build/random-DcKA4vF7.mjs.map +0 -1
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Crockford's Base32 encoding/decoding for ULID.
3
+ * Alphabet excludes I, L, O, U to avoid confusion with similar-looking characters.
4
+ */
5
+
6
+ import { BufferError, ParseError } from '../errors'
7
+
8
+ const ENCODING = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
9
+
10
+ // Pre-computed decoding table covering every UTF-16 code unit charCodeAt can
11
+ // return, so lookups never go out of bounds and a single `=== 255` check
12
+ // rejects invalid input (including non-ASCII) without a per-character range
13
+ // check. Costs 64 KiB once at module load; valid inputs only touch the first
14
+ // 128 bytes, so cache behavior is unaffected.
15
+ const DECODING = new Uint8Array(65536)
16
+ DECODING.fill(255) // 255 = invalid marker
17
+ for (let i = 0; i < ENCODING.length; i += 1) {
18
+ const upper = ENCODING.charCodeAt(i)
19
+ const lower = ENCODING[i].toLowerCase().charCodeAt(0)
20
+ DECODING[upper] = i
21
+ DECODING[lower] = i
22
+ }
23
+
24
+ const TIME_LEN = 10
25
+ const ULID_LEN = 26
26
+
27
+ function invalidCharError(str: string, index: number): ParseError {
28
+ return new ParseError('ULID_INVALID_CHAR', `Invalid ULID character: ${str[index]}`)
29
+ }
30
+
31
+ function timestampOverflowError(): ParseError {
32
+ return new ParseError('ULID_TIMESTAMP_OVERFLOW', 'ULID timestamp exceeds 48 bits')
33
+ }
34
+
35
+ function decodeTimeChars(str: string): number {
36
+ const firstValue = DECODING[str.charCodeAt(0)]
37
+ if (firstValue === 255) {
38
+ throw invalidCharError(str, 0)
39
+ }
40
+
41
+ if (firstValue > 7) {
42
+ throw timestampOverflowError()
43
+ }
44
+
45
+ let time = firstValue
46
+ for (let i = 1; i < TIME_LEN; i += 1) {
47
+ const value = DECODING[str.charCodeAt(i)]
48
+ if (value === 255) {
49
+ throw invalidCharError(str, i)
50
+ }
51
+
52
+ time = time * 32 + value
53
+ }
54
+ return time
55
+ }
56
+
57
+ /**
58
+ * Encode a 48-bit timestamp to a 10-character Crockford Base32 string.
59
+ * Uses unrolled division for performance.
60
+ */
61
+ export function encodeTime(time: number): string {
62
+ // Unrolled encoding - each step divides by 32 and extracts 5 bits
63
+ // Powers of 32: 32^9=0x200000000000, 32^8=0x10000000000, etc.
64
+ return (
65
+ ENCODING[Math.floor(time / 0x200000000000) & 0x1f] +
66
+ ENCODING[Math.floor(time / 0x10000000000) & 0x1f] +
67
+ ENCODING[Math.floor(time / 0x800000000) & 0x1f] +
68
+ ENCODING[Math.floor(time / 0x40000000) & 0x1f] +
69
+ ENCODING[Math.floor(time / 0x2000000) & 0x1f] +
70
+ ENCODING[Math.floor(time / 0x100000) & 0x1f] +
71
+ ENCODING[Math.floor(time / 0x8000) & 0x1f] +
72
+ ENCODING[Math.floor(time / 0x400) & 0x1f] +
73
+ ENCODING[Math.floor(time / 0x20) & 0x1f] +
74
+ ENCODING[time & 0x1f]
75
+ )
76
+ }
77
+
78
+ /**
79
+ * Encode 10 bytes (80 bits) of random data to a 16-character Crockford Base32 string.
80
+ */
81
+ export function encodeRandom(bytes: Uint8Array): string {
82
+ // Each character encodes 5 bits. 80 bits = 16 characters.
83
+ // Single concatenation expression for optimal performance.
84
+ return (
85
+ ENCODING[(bytes[0] >> 3) & 0x1f] +
86
+ ENCODING[((bytes[0] << 2) | (bytes[1] >> 6)) & 0x1f] +
87
+ ENCODING[(bytes[1] >> 1) & 0x1f] +
88
+ ENCODING[((bytes[1] << 4) | (bytes[2] >> 4)) & 0x1f] +
89
+ ENCODING[((bytes[2] << 1) | (bytes[3] >> 7)) & 0x1f] +
90
+ ENCODING[(bytes[3] >> 2) & 0x1f] +
91
+ ENCODING[((bytes[3] << 3) | (bytes[4] >> 5)) & 0x1f] +
92
+ ENCODING[bytes[4] & 0x1f] +
93
+ ENCODING[(bytes[5] >> 3) & 0x1f] +
94
+ ENCODING[((bytes[5] << 2) | (bytes[6] >> 6)) & 0x1f] +
95
+ ENCODING[(bytes[6] >> 1) & 0x1f] +
96
+ ENCODING[((bytes[6] << 4) | (bytes[7] >> 4)) & 0x1f] +
97
+ ENCODING[((bytes[7] << 1) | (bytes[8] >> 7)) & 0x1f] +
98
+ ENCODING[(bytes[8] >> 2) & 0x1f] +
99
+ ENCODING[((bytes[8] << 3) | (bytes[9] >> 5)) & 0x1f] +
100
+ ENCODING[bytes[9] & 0x1f]
101
+ )
102
+ }
103
+
104
+ /**
105
+ * Decode a 10-character ULID timestamp string to Unix epoch milliseconds.
106
+ */
107
+ export function decodeTime(str: string): number {
108
+ if (str.length !== TIME_LEN) {
109
+ throw new ParseError('ULID_INVALID_LENGTH', `ULID timestamp must be ${TIME_LEN} characters`)
110
+ }
111
+ return decodeTimeChars(str)
112
+ }
113
+
114
+ /**
115
+ * Decode the timestamp from a full 26-character ULID string.
116
+ */
117
+ export function decodeUlidTime(str: string): number {
118
+ if (str.length !== ULID_LEN) {
119
+ throw new ParseError('ULID_INVALID_LENGTH', `ULID string must be ${ULID_LEN} characters`)
120
+ }
121
+ return decodeTimeChars(str)
122
+ }
123
+
124
+ /**
125
+ * Decode a 26-character ULID string to 16 bytes.
126
+ * Inlines all lookups to avoid intermediate array allocation.
127
+ */
128
+ export function decodeToBytes(str: string): Uint8Array {
129
+ if (str.length !== ULID_LEN) {
130
+ throw new ParseError('ULID_INVALID_LENGTH', `ULID string must be ${ULID_LEN} characters`)
131
+ }
132
+
133
+ const bytes = new Uint8Array(16)
134
+
135
+ // Inline all 26 character lookups
136
+ const v0 = DECODING[str.charCodeAt(0)]
137
+ const v1 = DECODING[str.charCodeAt(1)]
138
+ const v2 = DECODING[str.charCodeAt(2)]
139
+ const v3 = DECODING[str.charCodeAt(3)]
140
+ const v4 = DECODING[str.charCodeAt(4)]
141
+ const v5 = DECODING[str.charCodeAt(5)]
142
+ const v6 = DECODING[str.charCodeAt(6)]
143
+ const v7 = DECODING[str.charCodeAt(7)]
144
+ const v8 = DECODING[str.charCodeAt(8)]
145
+ const v9 = DECODING[str.charCodeAt(9)]
146
+ const v10 = DECODING[str.charCodeAt(10)]
147
+ const v11 = DECODING[str.charCodeAt(11)]
148
+ const v12 = DECODING[str.charCodeAt(12)]
149
+ const v13 = DECODING[str.charCodeAt(13)]
150
+ const v14 = DECODING[str.charCodeAt(14)]
151
+ const v15 = DECODING[str.charCodeAt(15)]
152
+ const v16 = DECODING[str.charCodeAt(16)]
153
+ const v17 = DECODING[str.charCodeAt(17)]
154
+ const v18 = DECODING[str.charCodeAt(18)]
155
+ const v19 = DECODING[str.charCodeAt(19)]
156
+ const v20 = DECODING[str.charCodeAt(20)]
157
+ const v21 = DECODING[str.charCodeAt(21)]
158
+ const v22 = DECODING[str.charCodeAt(22)]
159
+ const v23 = DECODING[str.charCodeAt(23)]
160
+ const v24 = DECODING[str.charCodeAt(24)]
161
+ const v25 = DECODING[str.charCodeAt(25)]
162
+
163
+ // Validate all characters at once (255 = invalid marker, so any invalid
164
+ // character sets the 0x80 bit in the OR of all values)
165
+ if (
166
+ ((v0 |
167
+ v1 |
168
+ v2 |
169
+ v3 |
170
+ v4 |
171
+ v5 |
172
+ v6 |
173
+ v7 |
174
+ v8 |
175
+ v9 |
176
+ v10 |
177
+ v11 |
178
+ v12 |
179
+ v13 |
180
+ v14 |
181
+ v15 |
182
+ v16 |
183
+ v17 |
184
+ v18 |
185
+ v19 |
186
+ v20 |
187
+ v21 |
188
+ v22 |
189
+ v23 |
190
+ v24 |
191
+ v25) &
192
+ 0x80) !==
193
+ 0
194
+ ) {
195
+ // Find the invalid character for error message
196
+ for (let i = 0; i < ULID_LEN; i += 1) {
197
+ if (DECODING[str.charCodeAt(i)] === 255) {
198
+ throw invalidCharError(str, i)
199
+ }
200
+ }
201
+ }
202
+
203
+ if (v0 > 7) {
204
+ throw timestampOverflowError()
205
+ }
206
+
207
+ // Timestamp: first 10 characters -> bytes 0-5
208
+ bytes[0] = (v0 << 5) | v1
209
+ bytes[1] = (v2 << 3) | (v3 >> 2)
210
+ bytes[2] = (v3 << 6) | (v4 << 1) | (v5 >> 4)
211
+ bytes[3] = (v5 << 4) | (v6 >> 1)
212
+ bytes[4] = (v6 << 7) | (v7 << 2) | (v8 >> 3)
213
+ bytes[5] = (v8 << 5) | v9
214
+
215
+ // Random: last 16 characters -> bytes 6-15
216
+ bytes[6] = (v10 << 3) | (v11 >> 2)
217
+ bytes[7] = (v11 << 6) | (v12 << 1) | (v13 >> 4)
218
+ bytes[8] = (v13 << 4) | (v14 >> 1)
219
+ bytes[9] = (v14 << 7) | (v15 << 2) | (v16 >> 3)
220
+ bytes[10] = (v16 << 5) | v17
221
+ bytes[11] = (v18 << 3) | (v19 >> 2)
222
+ bytes[12] = (v19 << 6) | (v20 << 1) | (v21 >> 4)
223
+ bytes[13] = (v21 << 4) | (v22 >> 1)
224
+ bytes[14] = (v22 << 7) | (v23 << 2) | (v24 >> 3)
225
+ bytes[15] = (v24 << 5) | v25
226
+
227
+ return bytes
228
+ }
229
+
230
+ /**
231
+ * Encode 16 bytes to a 26-character ULID string.
232
+ */
233
+ export function bytesToUlid(bytes: Uint8Array): string {
234
+ if (bytes.length < 16) {
235
+ throw new BufferError('ULID_BYTES_TOO_SHORT', 'Byte array must be at least 16 bytes')
236
+ }
237
+
238
+ // Timestamp: bytes 0-5 -> 10 characters
239
+ let time = 0
240
+ for (let i = 0; i < 6; i += 1) {
241
+ time = time * 256 + bytes[i]
242
+ }
243
+ const timeStr = encodeTime(time)
244
+
245
+ // Random: bytes 6-15 -> 16 characters
246
+ const randomStr = encodeRandom(bytes.subarray(6, 16))
247
+
248
+ return timeStr + randomStr
249
+ }
@@ -0,0 +1,184 @@
1
+ import { incrementBytesInPlace, writeTimestamp48 } from '../common/bytes'
2
+ import { rng } from '../common/random'
3
+ import { BufferError, InvalidInputError } from '../errors'
4
+ import { bytesToUlid, decodeToBytes, decodeUlidTime, encodeRandom, encodeTime } from './crockford'
5
+
6
+ export type UlidOptions = {
7
+ /**
8
+ * 16 bytes of random data to use for ULID generation.
9
+ * Only the first 10 bytes are used.
10
+ */
11
+ random?: Uint8Array
12
+ /**
13
+ * Timestamp in milliseconds since Unix epoch.
14
+ * Defaults to Date.now().
15
+ */
16
+ msecs?: number
17
+ }
18
+
19
+ export type Ulid = {
20
+ (): string
21
+ <TBuf extends Uint8Array = Uint8Array>(options: UlidOptions | undefined, buf: TBuf, offset?: number): TBuf
22
+ (options?: UlidOptions, buf?: undefined, offset?: number): string
23
+ toBytes(id: string): Uint8Array
24
+ fromBytes(bytes: Uint8Array): string
25
+ timestamp(id: string): number
26
+ isValid(id: unknown): id is string
27
+ /** The nil ULID (all zeros) */
28
+ NIL: string
29
+ /** The max ULID (maximum valid value) */
30
+ MAX: string
31
+ }
32
+
33
+ // Validation regex: first char [0-7] to prevent overflow, rest from Crockford alphabet
34
+ const ULID_REGEX = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i
35
+
36
+ type UlidState = {
37
+ msecs: number
38
+ lastRandom: Uint8Array
39
+ }
40
+
41
+ /**
42
+ * Module-level state for maintaining monotonic ordering within the same millisecond.
43
+ *
44
+ * IMPORTANT: This state persists across all ulid() calls in the module's lifetime.
45
+ * - In serverless/edge functions with warm starts, state persists between invocations.
46
+ * - For isolated state, pass explicit `msecs` and `random` via options.
47
+ * - Tests should mock Date.now() or provide explicit options for deterministic behavior.
48
+ */
49
+ const state: UlidState = {
50
+ msecs: -Infinity,
51
+ lastRandom: new Uint8Array(10),
52
+ }
53
+
54
+ function ulidBytes(time: number, random: Uint8Array, buf?: Uint8Array, offset = 0): Uint8Array {
55
+ if (!buf) {
56
+ buf = new Uint8Array(16)
57
+ offset = 0
58
+ } else if (offset < 0 || offset + 16 > buf.length) {
59
+ throw new BufferError(
60
+ 'ULID_BUFFER_OUT_OF_BOUNDS',
61
+ `ULID byte range ${offset}:${offset + 15} is out of buffer bounds`,
62
+ )
63
+ }
64
+
65
+ // Timestamp (48-bit big-endian milliseconds since Unix epoch) -> bytes 0-5
66
+ writeTimestamp48(buf, offset, time)
67
+
68
+ // Random (80 bits) -> bytes 6-15
69
+ for (let i = 0; i < 10; i += 1) {
70
+ buf[offset + 6 + i] = random[i]
71
+ }
72
+
73
+ return buf
74
+ }
75
+
76
+ /*
77
+ * Overload: no buffer => return a ULID string.
78
+ */
79
+ function ulidFn(options?: UlidOptions, buf?: undefined, offset?: number): string
80
+ /*
81
+ * Overload: caller provides a buffer slice to fill with ULID bytes.
82
+ */
83
+ function ulidFn<TBuf extends Uint8Array = Uint8Array>(
84
+ options: UlidOptions | undefined,
85
+ buf: TBuf,
86
+ offset?: number,
87
+ ): TBuf
88
+ function ulidFn<TBuf extends Uint8Array = Uint8Array>(options?: UlidOptions, buf?: TBuf, offset = 0): string | TBuf {
89
+ let time: number
90
+ let random: Uint8Array
91
+
92
+ /**
93
+ * Note: by default, Cloudflare Workers "freezes" time during request handling to prevent
94
+ * side-channel attacks. This means that Date.now() will return the same value for the entire
95
+ * duration of a request.
96
+ * Implications:
97
+ * - all ULIDs generated within a single request will have the same timestamp.
98
+ * - the monotonic ordering will rely entirely on incrementing the random portion.
99
+ */
100
+ const defaultTime = Date.now()
101
+
102
+ if (options) {
103
+ // Explicit options provided - use them directly without monotonic state
104
+ time = options.msecs ?? defaultTime
105
+ if (options.random) {
106
+ if (options.random.length < 10) {
107
+ throw new InvalidInputError('ULID_RANDOM_BYTES_TOO_SHORT', 'Random bytes length must be >= 10 for ULID')
108
+ }
109
+ random = options.random
110
+ } else {
111
+ random = rng()
112
+ }
113
+ } else {
114
+ time = defaultTime
115
+
116
+ if (time > state.msecs) {
117
+ // New millisecond: generate fresh random
118
+ random = rng()
119
+ state.msecs = time
120
+ state.lastRandom.set(random.subarray(0, 10))
121
+ } else {
122
+ // Same millisecond or clock rollback: preserve last timestamp and increment random portion.
123
+ time = state.msecs
124
+ if (!incrementBytesInPlace(state.lastRandom)) {
125
+ state.lastRandom.fill(0xff)
126
+ throw new InvalidInputError(
127
+ 'ULID_RANDOM_OVERFLOW',
128
+ 'ULID random component overflowed while preserving monotonic order',
129
+ )
130
+ }
131
+ random = state.lastRandom
132
+ }
133
+ }
134
+
135
+ if (buf) {
136
+ ulidBytes(time, random, buf, offset)
137
+ return buf
138
+ }
139
+
140
+ // String mode: encode directly without buffer allocation
141
+ return encodeTime(time) + encodeRandom(random)
142
+ }
143
+
144
+ /**
145
+ * Generate a ULID string or write the bytes into a buffer.
146
+ *
147
+ * ULID (Universally Unique Lexicographically Sortable Identifier) is a 128-bit
148
+ * identifier with millisecond timestamp precision and 80 bits of randomness.
149
+ * ULIDs are URL-safe, use Crockford's Base32 encoding, and sort lexicographically
150
+ * by creation time.
151
+ *
152
+ * @example
153
+ * ```ts
154
+ * import { ulid } from 'uniku/ulid'
155
+ *
156
+ * const id = ulid()
157
+ * // => "01HW9T2W9W9YJ3JZ1H4P4M2T8Q"
158
+ *
159
+ * // Extract timestamp
160
+ * const ts = ulid.timestamp(id)
161
+ * console.log(new Date(ts))
162
+ *
163
+ * // Validate
164
+ * ulid.isValid(id) // true
165
+ *
166
+ * // Convert to/from bytes (16 bytes)
167
+ * const bytes = ulid.toBytes(id)
168
+ * const restored = ulid.fromBytes(bytes)
169
+ * ```
170
+ */
171
+ function isValid(id: unknown): id is string {
172
+ return typeof id === 'string' && ULID_REGEX.test(id)
173
+ }
174
+
175
+ export const ulid: Ulid = Object.assign(ulidFn, {
176
+ toBytes: (id: string) => decodeToBytes(id),
177
+ fromBytes: (bytes: Uint8Array) => bytesToUlid(bytes),
178
+ timestamp: (id: string) => decodeUlidTime(id),
179
+ isValid,
180
+ NIL: '00000000000000000000000000',
181
+ MAX: '7ZZZZZZZZZZZZZZZZZZZZZZZZZ',
182
+ })
183
+
184
+ export { BufferError, InvalidInputError, ParseError, UniqueIdError } from '../errors'
@@ -0,0 +1,24 @@
1
+ // ASCII code ranges for hex character validation
2
+ const ASCII_0 = 48 // '0'
3
+ const ASCII_9 = 57 // '9'
4
+ const ASCII_A = 65 // 'A'
5
+ const ASCII_F = 70 // 'F'
6
+ const ASCII_a = 97 // 'a'
7
+ const ASCII_f = 102 // 'f'
8
+
9
+ /**
10
+ * Convert a hex character ASCII code to its numeric value (0-15).
11
+ * Returns -1 for invalid hex characters.
12
+ */
13
+ export function hexValue(code: number): number {
14
+ if (code >= ASCII_0 && code <= ASCII_9) {
15
+ return code - ASCII_0
16
+ }
17
+ if (code >= ASCII_A && code <= ASCII_F) {
18
+ return code - ASCII_A + 10
19
+ }
20
+ if (code >= ASCII_a && code <= ASCII_f) {
21
+ return code - ASCII_a + 10
22
+ }
23
+ return -1 // Invalid hex character
24
+ }
@@ -0,0 +1,157 @@
1
+ import { ParseError } from '../../errors'
2
+ import { hexValue } from './hex'
3
+
4
+ const UUID_BYTE_LENGTH = 16
5
+ const UUID_STRING_LENGTH = 36
6
+
7
+ // Mapping from UUID string position to byte index.
8
+ // -1 indicates a dash position that should be skipped.
9
+ // This avoids intermediate string allocations during parsing.
10
+ const UUID_CHAR_TO_BYTE: number[] = [
11
+ 0,
12
+ 0,
13
+ 1,
14
+ 1,
15
+ 2,
16
+ 2,
17
+ 3,
18
+ 3, // chars 0-7 → bytes 0-3
19
+ -1, // char 8 is '-'
20
+ 4,
21
+ 4,
22
+ 5,
23
+ 5, // chars 9-12 → bytes 4-5
24
+ -1, // char 13 is '-'
25
+ 6,
26
+ 6,
27
+ 7,
28
+ 7, // chars 14-17 → bytes 6-7
29
+ -1, // char 18 is '-'
30
+ 8,
31
+ 8,
32
+ 9,
33
+ 9, // chars 19-22 → bytes 8-9
34
+ -1, // char 23 is '-'
35
+ 10,
36
+ 10,
37
+ 11,
38
+ 11,
39
+ 12,
40
+ 12,
41
+ 13,
42
+ 13,
43
+ 14,
44
+ 14,
45
+ 15,
46
+ 15, // chars 24-35 → bytes 10-15
47
+ ]
48
+
49
+ // Whether each position is the high nibble (true) or low nibble (false)
50
+ const UUID_CHAR_IS_HIGH: boolean[] = [
51
+ true,
52
+ false,
53
+ true,
54
+ false,
55
+ true,
56
+ false,
57
+ true,
58
+ false, // chars 0-7
59
+ false, // dash (ignored)
60
+ true,
61
+ false,
62
+ true,
63
+ false, // chars 9-12
64
+ false, // dash
65
+ true,
66
+ false,
67
+ true,
68
+ false, // chars 14-17
69
+ false, // dash
70
+ true,
71
+ false,
72
+ true,
73
+ false, // chars 19-22
74
+ false, // dash
75
+ true,
76
+ false,
77
+ true,
78
+ false,
79
+ true,
80
+ false,
81
+ true,
82
+ false,
83
+ true,
84
+ false,
85
+ true,
86
+ false, // chars 24-35
87
+ ]
88
+
89
+ // Pre-computed lookup table for byte-to-hex conversion (0x00 -> "00", 0xff -> "ff")
90
+ //
91
+ // Note: this table must remain defined in the same module as `formatUuid`, otherwise the v8 optimizer
92
+ // will cause a performance drop of ~36%.
93
+ const HEX_TABLE: string[] = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'))
94
+
95
+ export function formatUuid(bytes: Uint8Array): string {
96
+ // Direct string concatenation - optimized for V8's string builder.
97
+ // This approach avoids loop overhead and intermediate allocations.
98
+ // See: https://github.com/uuidjs/uuid/pull/434
99
+ return (
100
+ HEX_TABLE[bytes[0]] +
101
+ HEX_TABLE[bytes[1]] +
102
+ HEX_TABLE[bytes[2]] +
103
+ HEX_TABLE[bytes[3]] +
104
+ '-' +
105
+ HEX_TABLE[bytes[4]] +
106
+ HEX_TABLE[bytes[5]] +
107
+ '-' +
108
+ HEX_TABLE[bytes[6]] +
109
+ HEX_TABLE[bytes[7]] +
110
+ '-' +
111
+ HEX_TABLE[bytes[8]] +
112
+ HEX_TABLE[bytes[9]] +
113
+ '-' +
114
+ HEX_TABLE[bytes[10]] +
115
+ HEX_TABLE[bytes[11]] +
116
+ HEX_TABLE[bytes[12]] +
117
+ HEX_TABLE[bytes[13]] +
118
+ HEX_TABLE[bytes[14]] +
119
+ HEX_TABLE[bytes[15]]
120
+ )
121
+ }
122
+
123
+ export function parseUuid(value: string): Uint8Array {
124
+ if (value.length !== UUID_STRING_LENGTH) {
125
+ throw new ParseError('UUID_INVALID_LENGTH', `UUID string must be 36 characters, got ${value.length}`)
126
+ }
127
+
128
+ // Validate separator positions directly (more efficient than full loop)
129
+ if (value[8] !== '-' || value[13] !== '-' || value[18] !== '-' || value[23] !== '-') {
130
+ throw new ParseError(
131
+ 'UUID_INVALID_SEPARATORS',
132
+ `UUID string has invalid separators at positions 8, 13, 18, 23. Received: "${value}"`,
133
+ )
134
+ }
135
+
136
+ // Parse bytes directly from UUID string without intermediate string allocations.
137
+ // This avoids the 9 allocations (5 slices + 4 concatenations) of the naive approach.
138
+ const bytes = new Uint8Array(UUID_BYTE_LENGTH)
139
+
140
+ for (let i = 0; i < UUID_STRING_LENGTH; i += 1) {
141
+ const byteIdx = UUID_CHAR_TO_BYTE[i]
142
+ if (byteIdx === -1) continue // Skip dash positions
143
+
144
+ const nibble = hexValue(value.charCodeAt(i))
145
+ if (nibble === -1) {
146
+ throw new ParseError('UUID_INVALID_HEX_CHAR', `UUID string contains invalid hex character at position ${i}`)
147
+ }
148
+
149
+ if (UUID_CHAR_IS_HIGH[i]) {
150
+ bytes[byteIdx] = nibble << 4
151
+ } else {
152
+ bytes[byteIdx] |= nibble
153
+ }
154
+ }
155
+
156
+ return bytes
157
+ }