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.
- package/README.md +63 -13
- package/build/{bytes-BBjKLOBR.mjs → bytes-DzcOKIx1.mjs} +1 -1
- package/build/{bytes-BBjKLOBR.mjs.map → bytes-DzcOKIx1.mjs.map} +1 -1
- package/build/cuid2/cuid2.d.mts.map +1 -1
- package/build/cuid2/cuid2.mjs +1 -1
- package/build/cuid2/cuid2.mjs.map +1 -1
- package/build/ksuid/ksuid.d.mts.map +1 -1
- package/build/ksuid/ksuid.mjs +1 -1
- package/build/ksuid/ksuid.mjs.map +1 -1
- package/build/nanoid/nanoid.d.mts.map +1 -1
- package/build/nanoid/nanoid.mjs +1 -1
- package/build/nanoid/nanoid.mjs.map +1 -1
- package/build/random-CGMm8owG.mjs +2 -0
- package/build/random-CGMm8owG.mjs.map +1 -0
- package/build/tsconfig.tsbuildinfo +1 -1
- package/build/typeid/typeid.d.mts +38 -0
- package/build/typeid/typeid.d.mts.map +1 -0
- package/build/typeid/typeid.mjs +2 -0
- package/build/typeid/typeid.mjs.map +1 -0
- package/build/ulid/ulid.d.mts.map +1 -1
- package/build/ulid/ulid.mjs +1 -1
- package/build/ulid/ulid.mjs.map +1 -1
- package/build/uuid/v4.mjs +1 -1
- package/build/uuid/v7.d.mts.map +1 -1
- package/build/uuid/v7.mjs +1 -1
- package/build/uuid/v7.mjs.map +1 -1
- package/build/{uuid-QysI8pWE.mjs → uuid-Ub6ladEr.mjs} +1 -1
- package/build/{uuid-QysI8pWE.mjs.map → uuid-Ub6ladEr.mjs.map} +1 -1
- package/package.json +21 -31
- package/src/common/bytes.ts +59 -0
- package/src/common/random.ts +66 -0
- package/src/cuid2/cuid2.ts +211 -0
- package/src/errors.ts +56 -0
- package/src/ksuid/base62.ts +103 -0
- package/src/ksuid/ksuid.ts +195 -0
- package/src/nanoid/nanoid.ts +257 -0
- package/src/typeid/typeid.ts +283 -0
- package/src/ulid/crockford.ts +249 -0
- package/src/ulid/ulid.ts +184 -0
- package/src/uuid/common/hex.ts +24 -0
- package/src/uuid/common/uuid.ts +157 -0
- package/src/uuid/v4.ts +119 -0
- package/src/uuid/v7.ts +182 -0
- package/build/random-DcKA4vF7.mjs +0 -2
- package/build/random-DcKA4vF7.mjs.map +0 -1
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
import { InvalidInputError } from '../errors'
|
|
2
|
+
|
|
3
|
+
/** Default URL-safe alphabet (64 characters): A-Z, a-z, 0-9, underscore, hyphen */
|
|
4
|
+
export const URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'
|
|
5
|
+
|
|
6
|
+
const DEFAULT_SIZE = 21
|
|
7
|
+
const MAX_SIZE = 2048
|
|
8
|
+
const NANOID_REGEX = /^[A-Za-z0-9_-]+$/
|
|
9
|
+
|
|
10
|
+
// Keep Nanoid's private pool for its default hot path. It consumes `size`
|
|
11
|
+
// bytes directly without the shared helper's UUID/CUID2-oriented branches.
|
|
12
|
+
const POOL_SIZE_MULTIPLIER = 128
|
|
13
|
+
const MAX_POOL_SIZE = 65_536
|
|
14
|
+
let pool: Uint8Array | undefined
|
|
15
|
+
let poolOffset = 0
|
|
16
|
+
|
|
17
|
+
function fillPool(bytes: number): void {
|
|
18
|
+
const size = Math.min(bytes * POOL_SIZE_MULTIPLIER, MAX_POOL_SIZE)
|
|
19
|
+
if (!pool || pool.length < size) {
|
|
20
|
+
pool = new Uint8Array(size)
|
|
21
|
+
crypto.getRandomValues(pool)
|
|
22
|
+
poolOffset = 0
|
|
23
|
+
} else if (poolOffset + bytes > pool.length) {
|
|
24
|
+
crypto.getRandomValues(pool)
|
|
25
|
+
poolOffset = 0
|
|
26
|
+
}
|
|
27
|
+
poolOffset += bytes
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function defaultAlphabetFromPool(size: number): string {
|
|
31
|
+
fillPool(size)
|
|
32
|
+
let id = ''
|
|
33
|
+
for (let i = poolOffset - size; i < poolOffset; i++) {
|
|
34
|
+
id += URL_ALPHABET[pool![i] & 63]
|
|
35
|
+
}
|
|
36
|
+
return id
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export type NanoidOptions = {
|
|
40
|
+
/**
|
|
41
|
+
* Random bytes for deterministic output (testing).
|
|
42
|
+
* For power-of-2 alphabets (2, 4, 8, 16, 32, 64, 128, 256): exactly `size` bytes needed.
|
|
43
|
+
* For other alphabets: ~size * 2 bytes needed (rejection sampling).
|
|
44
|
+
*/
|
|
45
|
+
random?: Uint8Array
|
|
46
|
+
/**
|
|
47
|
+
* Custom alphabet to use. Default: URL-safe A-Za-z0-9_-
|
|
48
|
+
* Must be 2-256 printable ASCII characters (32-126) with no duplicates.
|
|
49
|
+
*/
|
|
50
|
+
alphabet?: string
|
|
51
|
+
/**
|
|
52
|
+
* Length of generated ID. Default: 21. Maximum: 2048.
|
|
53
|
+
*/
|
|
54
|
+
size?: number
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export type Nanoid = {
|
|
58
|
+
/** Generate nanoid with default settings */
|
|
59
|
+
(): string
|
|
60
|
+
/** Generate nanoid with custom size */
|
|
61
|
+
(size: number): string
|
|
62
|
+
/** Generate nanoid with options */
|
|
63
|
+
(options: NanoidOptions): string
|
|
64
|
+
/**
|
|
65
|
+
* Validate a nanoid string against the default URL-safe alphabet.
|
|
66
|
+
* Note: Does not validate IDs generated with custom alphabets.
|
|
67
|
+
*/
|
|
68
|
+
isValid(id: unknown): id is string
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Validate alphabet: 2-256 printable ASCII chars, no duplicates
|
|
73
|
+
*/
|
|
74
|
+
function validateAlphabet(alphabet: string): void {
|
|
75
|
+
if (alphabet.length < 2) {
|
|
76
|
+
throw new InvalidInputError('NANOID_ALPHABET_TOO_SHORT', 'Alphabet must contain at least 2 characters')
|
|
77
|
+
}
|
|
78
|
+
if (alphabet.length > 256) {
|
|
79
|
+
throw new InvalidInputError('NANOID_ALPHABET_TOO_LONG', 'Alphabet must not exceed 256 characters')
|
|
80
|
+
}
|
|
81
|
+
const seen = new Set<string>()
|
|
82
|
+
for (const char of alphabet) {
|
|
83
|
+
const code = char.charCodeAt(0)
|
|
84
|
+
if (code < 32 || code > 126) {
|
|
85
|
+
throw new InvalidInputError(
|
|
86
|
+
'NANOID_ALPHABET_INVALID_CHAR',
|
|
87
|
+
'Alphabet must contain only printable ASCII characters (32-126)',
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
if (seen.has(char)) {
|
|
91
|
+
throw new InvalidInputError('NANOID_ALPHABET_DUPLICATE', `Duplicate character in alphabet: "${char}"`)
|
|
92
|
+
}
|
|
93
|
+
seen.add(char)
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Validate size parameter
|
|
99
|
+
*/
|
|
100
|
+
function validateSize(size: number): void {
|
|
101
|
+
if (!Number.isInteger(size) || size < 0) {
|
|
102
|
+
throw new InvalidInputError('NANOID_SIZE_INVALID', 'Size must be a non-negative integer')
|
|
103
|
+
}
|
|
104
|
+
if (size > MAX_SIZE) {
|
|
105
|
+
throw new InvalidInputError('NANOID_SIZE_TOO_LARGE', `Size must not exceed ${MAX_SIZE}`)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Overloads
|
|
110
|
+
function nanoidFn(): string
|
|
111
|
+
function nanoidFn(size: number): string
|
|
112
|
+
function nanoidFn(options: NanoidOptions): string
|
|
113
|
+
function nanoidFn(sizeOrOptions?: number | NanoidOptions): string {
|
|
114
|
+
// ULTRA-FAST PATH: No arguments = default nanoid
|
|
115
|
+
// Uses simple pooled random bytes (npm nanoid style) for best performance
|
|
116
|
+
if (sizeOrOptions === undefined) {
|
|
117
|
+
return defaultAlphabetFromPool(DEFAULT_SIZE)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
let size = DEFAULT_SIZE
|
|
121
|
+
let alphabet = URL_ALPHABET
|
|
122
|
+
let randomBytes: Uint8Array | undefined
|
|
123
|
+
|
|
124
|
+
if (typeof sizeOrOptions === 'number') {
|
|
125
|
+
size = sizeOrOptions
|
|
126
|
+
} else {
|
|
127
|
+
size = sizeOrOptions.size ?? DEFAULT_SIZE
|
|
128
|
+
alphabet = sizeOrOptions.alphabet ?? URL_ALPHABET
|
|
129
|
+
randomBytes = sizeOrOptions.random
|
|
130
|
+
if (sizeOrOptions.alphabet !== undefined) {
|
|
131
|
+
validateAlphabet(alphabet)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
validateSize(size)
|
|
136
|
+
|
|
137
|
+
if (size === 0) return ''
|
|
138
|
+
|
|
139
|
+
if (alphabet === URL_ALPHABET && randomBytes === undefined) {
|
|
140
|
+
return defaultAlphabetFromPool(size)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const alphabetLen = alphabet.length
|
|
144
|
+
|
|
145
|
+
// FAST PATH: Power-of-2 alphabet (includes default 64-char)
|
|
146
|
+
// No rejection needed - each byte maps directly to a character
|
|
147
|
+
if ((alphabetLen & (alphabetLen - 1)) === 0) {
|
|
148
|
+
const mask = alphabetLen - 1
|
|
149
|
+
if (randomBytes && randomBytes.length < size) {
|
|
150
|
+
throw new InvalidInputError(
|
|
151
|
+
'NANOID_RANDOM_BYTES_INSUFFICIENT',
|
|
152
|
+
`Insufficient random bytes: need ${size}, have ${randomBytes.length}`,
|
|
153
|
+
)
|
|
154
|
+
}
|
|
155
|
+
const bytes = randomBytes?.subarray(0, size) ?? globalThis.crypto.getRandomValues(new Uint8Array(size))
|
|
156
|
+
let id = ''
|
|
157
|
+
for (let i = 0; i < size; i++) {
|
|
158
|
+
id += alphabet[bytes[i] & mask]
|
|
159
|
+
}
|
|
160
|
+
return id
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// SLOW PATH: Rejection sampling for non-power-of-2 alphabets
|
|
164
|
+
// Calculate mask: smallest power-of-2 minus 1 that covers alphabet size
|
|
165
|
+
const mask = (2 << (31 - Math.clz32((alphabetLen - 1) | 1))) - 1
|
|
166
|
+
// Calculate step: random bytes per batch (1.6x accounts for rejection)
|
|
167
|
+
const step = Math.ceil((1.6 * mask * size) / alphabetLen)
|
|
168
|
+
|
|
169
|
+
let id = ''
|
|
170
|
+
let randomOffset = 0
|
|
171
|
+
|
|
172
|
+
while (id.length < size) {
|
|
173
|
+
let bytes: Uint8Array
|
|
174
|
+
if (randomBytes) {
|
|
175
|
+
if (randomBytes.length - randomOffset < step) {
|
|
176
|
+
throw new InvalidInputError(
|
|
177
|
+
'NANOID_RANDOM_BYTES_INSUFFICIENT',
|
|
178
|
+
`Insufficient random bytes: need at least ${step} more, have ${randomBytes.length - randomOffset}`,
|
|
179
|
+
)
|
|
180
|
+
}
|
|
181
|
+
bytes = randomBytes.subarray(randomOffset, randomOffset + step)
|
|
182
|
+
randomOffset += step
|
|
183
|
+
} else {
|
|
184
|
+
bytes = globalThis.crypto.getRandomValues(new Uint8Array(step))
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
for (let i = 0; i < bytes.length && id.length < size; i++) {
|
|
188
|
+
const index = bytes[i] & mask
|
|
189
|
+
if (index < alphabetLen) {
|
|
190
|
+
id += alphabet[index]
|
|
191
|
+
}
|
|
192
|
+
// Otherwise reject and continue (no modulo bias)
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
return id
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Validate a nanoid string against the default URL-safe alphabet.
|
|
201
|
+
* Note: Does not validate IDs generated with custom alphabets.
|
|
202
|
+
*/
|
|
203
|
+
function isValid(id: unknown): id is string {
|
|
204
|
+
return typeof id === 'string' && id.length > 0 && NANOID_REGEX.test(id)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Generate a URL-friendly unique string ID.
|
|
209
|
+
*
|
|
210
|
+
* Nanoid is a tiny, secure, URL-friendly unique string ID generator.
|
|
211
|
+
* It uses a URL-safe alphabet (A-Za-z0-9_-) and generates 21-character
|
|
212
|
+
* IDs by default with 126 bits of entropy.
|
|
213
|
+
*
|
|
214
|
+
* Unlike UUID v7 or ULID, nanoid is NOT time-ordered. Use it for:
|
|
215
|
+
* - URL shorteners
|
|
216
|
+
* - Session tokens
|
|
217
|
+
* - Invite codes
|
|
218
|
+
* - Any case where you need short, random IDs
|
|
219
|
+
*
|
|
220
|
+
* @example Basic usage
|
|
221
|
+
* ```ts
|
|
222
|
+
* import { nanoid } from 'uniku/nanoid'
|
|
223
|
+
*
|
|
224
|
+
* const id = nanoid()
|
|
225
|
+
* // => "V1StGXR8_Z5jdHi6B-myT"
|
|
226
|
+
* ```
|
|
227
|
+
*
|
|
228
|
+
* @example Custom size
|
|
229
|
+
* ```ts
|
|
230
|
+
* const shortId = nanoid(10)
|
|
231
|
+
* // => "IRFa-VaY2b"
|
|
232
|
+
* ```
|
|
233
|
+
*
|
|
234
|
+
* @example Custom alphabet (hex)
|
|
235
|
+
* ```ts
|
|
236
|
+
* const hexId = nanoid({ alphabet: '0123456789abcdef', size: 12 })
|
|
237
|
+
* // => "4f90d13a42bc"
|
|
238
|
+
* ```
|
|
239
|
+
*
|
|
240
|
+
* @example Validation
|
|
241
|
+
* ```ts
|
|
242
|
+
* const maybeId: unknown = getUserInput()
|
|
243
|
+
* if (nanoid.isValid(maybeId)) {
|
|
244
|
+
* // TypeScript knows maybeId is string
|
|
245
|
+
* console.log(maybeId.length)
|
|
246
|
+
* }
|
|
247
|
+
* ```
|
|
248
|
+
*
|
|
249
|
+
* @throws {InvalidInputError} Size must be between 0 and 2048
|
|
250
|
+
* @throws {InvalidInputError} Alphabet must contain 2-256 unique printable ASCII characters
|
|
251
|
+
* @throws {InvalidInputError} Insufficient random bytes for requested size
|
|
252
|
+
*/
|
|
253
|
+
export const nanoid: Nanoid = Object.assign(nanoidFn, {
|
|
254
|
+
isValid,
|
|
255
|
+
})
|
|
256
|
+
|
|
257
|
+
export { InvalidInputError, UniqueIdError } from '../errors'
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { InvalidInputError, ParseError } from '../errors'
|
|
2
|
+
import type { UuidV7Options } from '../uuid/v7'
|
|
3
|
+
import { uuidv7 } from '../uuid/v7'
|
|
4
|
+
|
|
5
|
+
export type TypeidOptions = UuidV7Options
|
|
6
|
+
|
|
7
|
+
export type Typeid = {
|
|
8
|
+
(prefix: string, options?: TypeidOptions): string
|
|
9
|
+
toBytes(id: string): Uint8Array
|
|
10
|
+
fromBytes(prefix: string, bytes: Uint8Array): string
|
|
11
|
+
toUuid(id: string): string
|
|
12
|
+
fromUuid(prefix: string, uuid: string): string
|
|
13
|
+
timestamp(id: string): number
|
|
14
|
+
prefix(id: string): string
|
|
15
|
+
suffix(id: string): string
|
|
16
|
+
isValid(id: unknown): id is string
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const TYPEID_SUFFIX_LENGTH = 26
|
|
20
|
+
const TYPEID_UUID_BYTE_LENGTH = 16
|
|
21
|
+
const TYPEID_ALPHABET = '0123456789abcdefghjkmnpqrstvwxyz'
|
|
22
|
+
|
|
23
|
+
const BASE32_DECODE: number[] = Array.from({ length: 128 }, () => -1)
|
|
24
|
+
for (let i = 0; i < TYPEID_ALPHABET.length; i += 1) {
|
|
25
|
+
BASE32_DECODE[TYPEID_ALPHABET.charCodeAt(i)] = i
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
type ParsedTypeid = {
|
|
29
|
+
prefix: string
|
|
30
|
+
suffix: string
|
|
31
|
+
bytes: Uint8Array
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function assertValidPrefix(prefix: string): void {
|
|
35
|
+
if (prefix.length === 0) {
|
|
36
|
+
return
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (prefix.length > 63) {
|
|
40
|
+
throw new InvalidInputError('TYPEID_PREFIX_TOO_LONG', 'TypeID prefix must be at most 63 characters')
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
for (let i = 0; i < prefix.length; i += 1) {
|
|
44
|
+
const code = prefix.charCodeAt(i)
|
|
45
|
+
const isLowercaseLetter = code >= 97 && code <= 122
|
|
46
|
+
const isUnderscore = code === 95
|
|
47
|
+
|
|
48
|
+
if (!isLowercaseLetter && !isUnderscore) {
|
|
49
|
+
throw new InvalidInputError(
|
|
50
|
+
'TYPEID_PREFIX_INVALID_CHARACTER',
|
|
51
|
+
'TypeID prefix must contain only lowercase ASCII letters and underscores',
|
|
52
|
+
)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if ((i === 0 || i === prefix.length - 1) && !isLowercaseLetter) {
|
|
56
|
+
throw new InvalidInputError('TYPEID_PREFIX_INVALID_BOUNDARY', 'TypeID prefix must start and end with a-z')
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function decodeSuffixValue(suffix: string, index: number): number {
|
|
62
|
+
const code = suffix.charCodeAt(index)
|
|
63
|
+
const value = code < BASE32_DECODE.length ? BASE32_DECODE[code] : -1
|
|
64
|
+
|
|
65
|
+
if (value === -1) {
|
|
66
|
+
throw new ParseError(
|
|
67
|
+
'TYPEID_SUFFIX_INVALID_CHARACTER',
|
|
68
|
+
`TypeID suffix contains invalid character at position ${index}`,
|
|
69
|
+
)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return value
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function assertValidSuffixShape(suffix: string): void {
|
|
76
|
+
if (suffix.length !== TYPEID_SUFFIX_LENGTH) {
|
|
77
|
+
throw new ParseError('TYPEID_SUFFIX_INVALID_LENGTH', `TypeID suffix must be 26 characters, got ${suffix.length}`)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
if (suffix[0] > '7') {
|
|
81
|
+
throw new ParseError('TYPEID_SUFFIX_OVERFLOW', 'TypeID suffix must encode a 128-bit value')
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function encodeBytesToSuffix(bytes: Uint8Array): string {
|
|
86
|
+
if (bytes.length !== TYPEID_UUID_BYTE_LENGTH) {
|
|
87
|
+
throw new InvalidInputError('TYPEID_UUID_BYTES_INVALID_LENGTH', `UUID bytes must be 16 bytes, got ${bytes.length}`)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
return (
|
|
91
|
+
TYPEID_ALPHABET[(bytes[0] & 0xe0) >> 5] +
|
|
92
|
+
TYPEID_ALPHABET[bytes[0] & 0x1f] +
|
|
93
|
+
TYPEID_ALPHABET[(bytes[1] & 0xf8) >> 3] +
|
|
94
|
+
TYPEID_ALPHABET[((bytes[1] & 0x07) << 2) | ((bytes[2] & 0xc0) >> 6)] +
|
|
95
|
+
TYPEID_ALPHABET[(bytes[2] & 0x3e) >> 1] +
|
|
96
|
+
TYPEID_ALPHABET[((bytes[2] & 0x01) << 4) | ((bytes[3] & 0xf0) >> 4)] +
|
|
97
|
+
TYPEID_ALPHABET[((bytes[3] & 0x0f) << 1) | ((bytes[4] & 0x80) >> 7)] +
|
|
98
|
+
TYPEID_ALPHABET[(bytes[4] & 0x7c) >> 2] +
|
|
99
|
+
TYPEID_ALPHABET[((bytes[4] & 0x03) << 3) | ((bytes[5] & 0xe0) >> 5)] +
|
|
100
|
+
TYPEID_ALPHABET[bytes[5] & 0x1f] +
|
|
101
|
+
TYPEID_ALPHABET[(bytes[6] & 0xf8) >> 3] +
|
|
102
|
+
TYPEID_ALPHABET[((bytes[6] & 0x07) << 2) | ((bytes[7] & 0xc0) >> 6)] +
|
|
103
|
+
TYPEID_ALPHABET[(bytes[7] & 0x3e) >> 1] +
|
|
104
|
+
TYPEID_ALPHABET[((bytes[7] & 0x01) << 4) | ((bytes[8] & 0xf0) >> 4)] +
|
|
105
|
+
TYPEID_ALPHABET[((bytes[8] & 0x0f) << 1) | ((bytes[9] & 0x80) >> 7)] +
|
|
106
|
+
TYPEID_ALPHABET[(bytes[9] & 0x7c) >> 2] +
|
|
107
|
+
TYPEID_ALPHABET[((bytes[9] & 0x03) << 3) | ((bytes[10] & 0xe0) >> 5)] +
|
|
108
|
+
TYPEID_ALPHABET[bytes[10] & 0x1f] +
|
|
109
|
+
TYPEID_ALPHABET[(bytes[11] & 0xf8) >> 3] +
|
|
110
|
+
TYPEID_ALPHABET[((bytes[11] & 0x07) << 2) | ((bytes[12] & 0xc0) >> 6)] +
|
|
111
|
+
TYPEID_ALPHABET[(bytes[12] & 0x3e) >> 1] +
|
|
112
|
+
TYPEID_ALPHABET[((bytes[12] & 0x01) << 4) | ((bytes[13] & 0xf0) >> 4)] +
|
|
113
|
+
TYPEID_ALPHABET[((bytes[13] & 0x0f) << 1) | ((bytes[14] & 0x80) >> 7)] +
|
|
114
|
+
TYPEID_ALPHABET[(bytes[14] & 0x7c) >> 2] +
|
|
115
|
+
TYPEID_ALPHABET[((bytes[14] & 0x03) << 3) | ((bytes[15] & 0xe0) >> 5)] +
|
|
116
|
+
TYPEID_ALPHABET[bytes[15] & 0x1f]
|
|
117
|
+
)
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function decodeSuffixToBytes(suffix: string): Uint8Array {
|
|
121
|
+
assertValidSuffixShape(suffix)
|
|
122
|
+
|
|
123
|
+
const values = new Array<number>(TYPEID_SUFFIX_LENGTH)
|
|
124
|
+
for (let i = 0; i < TYPEID_SUFFIX_LENGTH; i += 1) {
|
|
125
|
+
values[i] = decodeSuffixValue(suffix, i)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const bytes = new Uint8Array(TYPEID_UUID_BYTE_LENGTH)
|
|
129
|
+
bytes[0] = (values[0] << 5) | values[1]
|
|
130
|
+
bytes[1] = (values[2] << 3) | (values[3] >> 2)
|
|
131
|
+
bytes[2] = ((values[3] & 0x03) << 6) | (values[4] << 1) | (values[5] >> 4)
|
|
132
|
+
bytes[3] = ((values[5] & 0x0f) << 4) | (values[6] >> 1)
|
|
133
|
+
bytes[4] = ((values[6] & 0x01) << 7) | (values[7] << 2) | (values[8] >> 3)
|
|
134
|
+
bytes[5] = ((values[8] & 0x07) << 5) | values[9]
|
|
135
|
+
bytes[6] = (values[10] << 3) | (values[11] >> 2)
|
|
136
|
+
bytes[7] = ((values[11] & 0x03) << 6) | (values[12] << 1) | (values[13] >> 4)
|
|
137
|
+
bytes[8] = ((values[13] & 0x0f) << 4) | (values[14] >> 1)
|
|
138
|
+
bytes[9] = ((values[14] & 0x01) << 7) | (values[15] << 2) | (values[16] >> 3)
|
|
139
|
+
bytes[10] = ((values[16] & 0x07) << 5) | values[17]
|
|
140
|
+
bytes[11] = (values[18] << 3) | (values[19] >> 2)
|
|
141
|
+
bytes[12] = ((values[19] & 0x03) << 6) | (values[20] << 1) | (values[21] >> 4)
|
|
142
|
+
bytes[13] = ((values[21] & 0x0f) << 4) | (values[22] >> 1)
|
|
143
|
+
bytes[14] = ((values[22] & 0x01) << 7) | (values[23] << 2) | (values[24] >> 3)
|
|
144
|
+
bytes[15] = ((values[24] & 0x07) << 5) | values[25]
|
|
145
|
+
|
|
146
|
+
return bytes
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function assertUuidV7Bytes(bytes: Uint8Array): void {
|
|
150
|
+
if (bytes.length !== TYPEID_UUID_BYTE_LENGTH) {
|
|
151
|
+
throw new InvalidInputError('TYPEID_UUID_BYTES_INVALID_LENGTH', `UUID bytes must be 16 bytes, got ${bytes.length}`)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (bytes[6] >> 4 !== 7 || (bytes[8] & 0xc0) !== 0x80) {
|
|
155
|
+
throw new InvalidInputError('TYPEID_UUID_NOT_V7', 'TypeID UUID bytes must encode a UUID v7 value')
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function uuidV7BytesFromSuffix(suffix: string): Uint8Array {
|
|
160
|
+
const bytes = decodeSuffixToBytes(suffix)
|
|
161
|
+
assertUuidV7Bytes(bytes)
|
|
162
|
+
return bytes
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function uuidV7BytesFromUuid(uuid: string): Uint8Array {
|
|
166
|
+
if (!uuidv7.isValid(uuid)) {
|
|
167
|
+
throw new InvalidInputError('TYPEID_UUID_NOT_V7', 'TypeID can only wrap UUID v7 values')
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
return uuidv7.toBytes(uuid)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function parseTypeid(id: string): ParsedTypeid {
|
|
174
|
+
const separatorIndex = id.lastIndexOf('_')
|
|
175
|
+
|
|
176
|
+
if (separatorIndex === 0) {
|
|
177
|
+
throw new ParseError('TYPEID_INVALID_FORMAT', 'TypeID must not start with "_"')
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const prefix = separatorIndex === -1 ? '' : id.slice(0, separatorIndex)
|
|
181
|
+
const suffix = separatorIndex === -1 ? id : id.slice(separatorIndex + 1)
|
|
182
|
+
|
|
183
|
+
assertValidPrefix(prefix)
|
|
184
|
+
const bytes = uuidV7BytesFromSuffix(suffix)
|
|
185
|
+
|
|
186
|
+
return { prefix, suffix, bytes }
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function joinPrefixAndSuffix(prefix: string, suffix: string): string {
|
|
190
|
+
return prefix === '' ? suffix : `${prefix}_${suffix}`
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function formatTypeidFromUuidV7Bytes(prefix: string, bytes: Uint8Array): string {
|
|
194
|
+
assertValidPrefix(prefix)
|
|
195
|
+
assertUuidV7Bytes(bytes)
|
|
196
|
+
return joinPrefixAndSuffix(prefix, encodeBytesToSuffix(bytes))
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function timestampFromUuidV7Bytes(bytes: Uint8Array): number {
|
|
200
|
+
let msecs = 0
|
|
201
|
+
for (let i = 0; i < 6; i += 1) {
|
|
202
|
+
msecs = msecs * 256 + bytes[i]
|
|
203
|
+
}
|
|
204
|
+
return msecs
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function typeidFn(prefix: string, options?: TypeidOptions): string {
|
|
208
|
+
const bytes = uuidv7(options, new Uint8Array(TYPEID_UUID_BYTE_LENGTH))
|
|
209
|
+
return formatTypeidFromUuidV7Bytes(prefix, bytes)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function typeidToBytes(id: string): Uint8Array {
|
|
213
|
+
return parseTypeid(id).bytes
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function typeidFromBytes(prefix: string, bytes: Uint8Array): string {
|
|
217
|
+
return formatTypeidFromUuidV7Bytes(prefix, bytes)
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function typeidToUuid(id: string): string {
|
|
221
|
+
return uuidv7.fromBytes(typeidToBytes(id))
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function typeidFromUuid(prefix: string, uuid: string): string {
|
|
225
|
+
return formatTypeidFromUuidV7Bytes(prefix, uuidV7BytesFromUuid(uuid))
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function timestamp(id: string): number {
|
|
229
|
+
return timestampFromUuidV7Bytes(parseTypeid(id).bytes)
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function prefix(id: string): string {
|
|
233
|
+
return parseTypeid(id).prefix
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function suffix(id: string): string {
|
|
237
|
+
return parseTypeid(id).suffix
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function isValid(id: unknown): id is string {
|
|
241
|
+
if (typeof id !== 'string') {
|
|
242
|
+
return false
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
try {
|
|
246
|
+
parseTypeid(id)
|
|
247
|
+
} catch {
|
|
248
|
+
return false
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return true
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Generate a TypeID string backed by UUID v7.
|
|
256
|
+
*
|
|
257
|
+
* TypeID combines a lowercase snake_case type prefix with a 26-character
|
|
258
|
+
* modified base32 encoding of a UUID v7, producing sortable domain identifiers
|
|
259
|
+
* such as `user_01h2xcejqtf2nbrexx3vqjhp41`.
|
|
260
|
+
*
|
|
261
|
+
* @example
|
|
262
|
+
* ```ts
|
|
263
|
+
* import { typeid } from 'uniku/typeid'
|
|
264
|
+
*
|
|
265
|
+
* const id = typeid('user')
|
|
266
|
+
* // => "user_01h2xcejqtf2nbrexx3vqjhp41"
|
|
267
|
+
*
|
|
268
|
+
* const uuid = typeid.toUuid(id)
|
|
269
|
+
* const restored = typeid.fromUuid('user', uuid)
|
|
270
|
+
* ```
|
|
271
|
+
*/
|
|
272
|
+
export const typeid: Typeid = Object.assign(typeidFn, {
|
|
273
|
+
toBytes: typeidToBytes,
|
|
274
|
+
fromBytes: typeidFromBytes,
|
|
275
|
+
toUuid: typeidToUuid,
|
|
276
|
+
fromUuid: typeidFromUuid,
|
|
277
|
+
timestamp,
|
|
278
|
+
prefix,
|
|
279
|
+
suffix,
|
|
280
|
+
isValid,
|
|
281
|
+
})
|
|
282
|
+
|
|
283
|
+
export { BufferError, InvalidInputError, ParseError, UniqueIdError } from '../errors'
|