uniku 0.0.7 → 0.0.10
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 +107 -20
- package/build/bytes-BBjKLOBR.mjs +2 -0
- package/build/bytes-BBjKLOBR.mjs.map +1 -0
- package/build/cuid2/cuid2.d.mts +3 -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/errors.d.mts +38 -0
- package/build/errors.d.mts.map +1 -0
- package/build/errors.mjs +2 -0
- package/build/errors.mjs.map +1 -0
- package/build/ksuid/ksuid.d.mts +8 -2
- 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 +46 -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-DcKA4vF7.mjs +2 -0
- package/build/random-DcKA4vF7.mjs.map +1 -0
- package/build/ulid/ulid.d.mts +8 -6
- 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.d.mts +30 -6
- package/build/uuid/v4.d.mts.map +1 -1
- package/build/uuid/v4.mjs +1 -1
- package/build/uuid/v4.mjs.map +1 -1
- package/build/uuid/v7.d.mts +34 -6
- 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 +2 -0
- package/build/uuid-QysI8pWE.mjs.map +1 -0
- package/package.json +15 -6
- package/build/random-CPlgK_62.mjs +0 -2
- package/build/random-CPlgK_62.mjs.map +0 -1
- package/build/tsconfig.tsbuildinfo +0 -1
- package/build/uuid-DcbjGX9x.mjs +0 -2
- package/build/uuid-DcbjGX9x.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -24,7 +24,7 @@ console.log(first < second && second < third) // true
|
|
|
24
24
|
|
|
25
25
|
## At a Glance
|
|
26
26
|
|
|
27
|
-
| | uniku | uuid | nanoid | ulid | cuid2 | ksuid |
|
|
27
|
+
| | uniku | [uuid](https://github.com/uuidjs/uuid) | [nanoid](https://github.com/ai/nanoid) | [ulid](https://github.com/ulid/javascript) | [cuid2](https://github.com/paralleldrive/cuid2) | [ksuid](https://github.com/owpz/ksuid) |
|
|
28
28
|
|--------------------|:-----:|:----:|:------:|:----:|:-----:|:-----:|
|
|
29
29
|
| UUID v4 | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ |
|
|
30
30
|
| UUID v7 | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ |
|
|
@@ -56,24 +56,99 @@ Uses `globalThis.crypto` (Web Crypto API) — no Node.js-specific APIs.
|
|
|
56
56
|
|
|
57
57
|
| Generator | uniku vs npm |
|
|
58
58
|
|-----------|-------------:|
|
|
59
|
-
| ULID |
|
|
60
|
-
| CUID2 |
|
|
61
|
-
|
|
|
62
|
-
|
|
|
63
|
-
|
|
|
64
|
-
|
|
|
65
|
-
|
|
66
|
-
<sub>*UUID v7 tradeoff: uniku prioritizes strict monotonic sequencing for database use cases.</sub>
|
|
59
|
+
| ULID | **85× faster** |
|
|
60
|
+
| CUID2 | **8× faster** |
|
|
61
|
+
| KSUID | **1.5× faster** |
|
|
62
|
+
| UUID v7 | **1.1× faster** |
|
|
63
|
+
| Nanoid | **~comparable speed** |
|
|
64
|
+
| UUID v4 | npm is 1.1× faster |
|
|
67
65
|
|
|
68
66
|
## Which ID Should I Use?
|
|
69
67
|
|
|
68
|
+
### Quick Recommendations
|
|
69
|
+
|
|
70
70
|
| Use Case | Recommended | Why |
|
|
71
71
|
|----------|-------------|-----|
|
|
72
72
|
| Database primary keys | **UUID v7** or **ULID** | Time-ordered for index efficiency |
|
|
73
73
|
| URL shorteners | **Nanoid** | Compact, URL-safe characters |
|
|
74
74
|
| Prevent enumeration | **CUID2** | Non-sequential, secure |
|
|
75
75
|
| Maximum compatibility | **UUID v4** | Universal standard |
|
|
76
|
-
| Distributed systems | **
|
|
76
|
+
| Distributed systems (high entropy) | **KSUID** | 128-bit payload, second precision |
|
|
77
|
+
|
|
78
|
+
### Detailed Guide
|
|
79
|
+
|
|
80
|
+
**UUID v4** — Use when you need maximum compatibility with existing systems.
|
|
81
|
+
- 36 characters, 122-bit entropy
|
|
82
|
+
- Universally supported by databases (native `UUID` type)
|
|
83
|
+
- Not time-ordered (random distribution)
|
|
84
|
+
- Best for: Legacy systems, cross-platform compatibility
|
|
85
|
+
|
|
86
|
+
**UUID v7** — Use for database primary keys when you need RFC compliance.
|
|
87
|
+
- 36 characters, time-ordered with millisecond precision
|
|
88
|
+
- Native database support as `UUID` type
|
|
89
|
+
- Strictly monotonic within same millisecond
|
|
90
|
+
- Best for: PostgreSQL/MySQL primary keys, API identifiers
|
|
91
|
+
|
|
92
|
+
**ULID** — Use for database primary keys when you want URL-safe IDs.
|
|
93
|
+
- 26 characters, time-ordered with millisecond precision
|
|
94
|
+
- URL-safe (no hyphens), case-insensitive
|
|
95
|
+
- 80-bit random entropy per millisecond
|
|
96
|
+
- Best for: APIs, URLs, distributed systems needing sortability
|
|
97
|
+
|
|
98
|
+
**KSUID** — Use when you need highest collision resistance.
|
|
99
|
+
- 27 characters, time-ordered with second precision
|
|
100
|
+
- URL-safe, 128-bit random entropy (highest of all formats)
|
|
101
|
+
- Best for: Very high-volume distributed systems, event sourcing
|
|
102
|
+
|
|
103
|
+
**Nanoid** — Use for short, URL-friendly identifiers.
|
|
104
|
+
- 21 characters (configurable), 126-bit entropy
|
|
105
|
+
- Customizable alphabet and length
|
|
106
|
+
- Not time-ordered
|
|
107
|
+
- Best for: URL shorteners, session tokens, invite codes
|
|
108
|
+
|
|
109
|
+
**CUID2** — Use when ID unpredictability matters.
|
|
110
|
+
- 24 characters (configurable), hash-based
|
|
111
|
+
- Non-sequential, prevents enumeration attacks
|
|
112
|
+
- Not time-ordered
|
|
113
|
+
- Best for: User-facing IDs where security matters
|
|
114
|
+
|
|
115
|
+
### Binary Serialization: When to Use `toBytes()`
|
|
116
|
+
|
|
117
|
+
Formats with binary representations (UUID, ULID, KSUID) support `toBytes()` and `fromBytes()` for efficient storage:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
// Store as BINARY(16) instead of VARCHAR(36)
|
|
121
|
+
const bytes = uuidv7.toBytes(id) // 16 bytes
|
|
122
|
+
db.insert({ id: bytes })
|
|
123
|
+
|
|
124
|
+
// Retrieve and convert back
|
|
125
|
+
const id = uuidv7.fromBytes(row.id)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
**Benefits of binary storage:**
|
|
129
|
+
- **Up to 50% smaller**: E.g., 16 bytes vs 36 characters for UUID
|
|
130
|
+
- **Faster indexing**: Binary comparison is faster than string comparison
|
|
131
|
+
- **Reduced I/O**: Less data transferred between app and database
|
|
132
|
+
|
|
133
|
+
**When to use binary:**
|
|
134
|
+
- High-volume tables (millions of rows)
|
|
135
|
+
- Performance-critical queries on ID columns
|
|
136
|
+
- Storage cost is a concern
|
|
137
|
+
|
|
138
|
+
**When to keep strings:**
|
|
139
|
+
- Debugging/logging convenience
|
|
140
|
+
- API responses (humans read them)
|
|
141
|
+
- Small tables where savings are negligible
|
|
142
|
+
|
|
143
|
+
| Format | String Length | Binary Size | Savings |
|
|
144
|
+
|--------|--------------|-------------|---------|
|
|
145
|
+
| UUID v4/v7 | 36 chars | 16 bytes | 56% |
|
|
146
|
+
| ULID | 26 chars | 16 bytes | 38% |
|
|
147
|
+
| KSUID | 27 chars | 20 bytes | 26% |
|
|
148
|
+
| Nanoid | 21 chars | N/A | - |
|
|
149
|
+
| CUID2 | 24 chars | N/A | - |
|
|
150
|
+
|
|
151
|
+
> **Note**: Nanoid and CUID2 don't have binary representations because they're string-native formats with no canonical byte encoding.
|
|
77
152
|
|
|
78
153
|
## Installation
|
|
79
154
|
|
|
@@ -98,12 +173,12 @@ deno install npm:uniku
|
|
|
98
173
|
|
|
99
174
|
| Import | Minified + gzipped |
|
|
100
175
|
|--------|-------------------:|
|
|
101
|
-
| `uniku/uuid/v4` | ~
|
|
176
|
+
| `uniku/uuid/v4` | ~940 B |
|
|
102
177
|
| `uniku/uuid/v7` | ~1.1 KB |
|
|
103
178
|
| `uniku/ulid` | ~1.5 KB |
|
|
104
179
|
| `uniku/cuid2` | ~1.1 KB* |
|
|
105
|
-
| `uniku/nanoid` | ~
|
|
106
|
-
| `uniku/ksuid` | ~1.
|
|
180
|
+
| `uniku/nanoid` | ~938 B |
|
|
181
|
+
| `uniku/ksuid` | ~1.0 KB |
|
|
107
182
|
|
|
108
183
|
## Quick Start
|
|
109
184
|
|
|
@@ -246,21 +321,26 @@ const ts = ksuid.timestamp(id)
|
|
|
246
321
|
### `uuidv4` (from `uniku/uuid/v4`)
|
|
247
322
|
|
|
248
323
|
```ts
|
|
249
|
-
uuidv4(options?:
|
|
250
|
-
uuidv4(options:
|
|
324
|
+
uuidv4(options?: UuidV4Options): string
|
|
325
|
+
uuidv4(options: UuidV4Options | undefined, buf: Uint8Array, offset?: number): Uint8Array
|
|
251
326
|
uuidv4.toBytes(id: string): Uint8Array
|
|
252
327
|
uuidv4.fromBytes(bytes: Uint8Array): string
|
|
328
|
+
uuidv4.isValid(id: unknown): id is string
|
|
329
|
+
uuidv4.NIL // "00000000-0000-0000-0000-000000000000"
|
|
330
|
+
uuidv4.MAX // "ffffffff-ffff-ffff-ffff-ffffffffffff"
|
|
253
331
|
```
|
|
254
332
|
|
|
255
333
|
### `uuidv7` (from `uniku/uuid/v7`)
|
|
256
334
|
|
|
257
335
|
```ts
|
|
258
|
-
uuidv7(options?:
|
|
259
|
-
uuidv7(options:
|
|
336
|
+
uuidv7(options?: UuidV7Options): string
|
|
337
|
+
uuidv7(options: UuidV7Options | undefined, buf: Uint8Array, offset?: number): Uint8Array
|
|
260
338
|
uuidv7.toBytes(id: string): Uint8Array
|
|
261
339
|
uuidv7.fromBytes(bytes: Uint8Array): string
|
|
262
340
|
uuidv7.timestamp(id: string): number
|
|
263
|
-
uuidv7.isValid(id:
|
|
341
|
+
uuidv7.isValid(id: unknown): id is string
|
|
342
|
+
uuidv7.NIL // "00000000-0000-0000-0000-000000000000"
|
|
343
|
+
uuidv7.MAX // "ffffffff-ffff-ffff-ffff-ffffffffffff"
|
|
264
344
|
```
|
|
265
345
|
|
|
266
346
|
### `ulid` (from `uniku/ulid`)
|
|
@@ -271,7 +351,9 @@ ulid(options: UlidOptions | undefined, buf: Uint8Array, offset?: number): Uint8A
|
|
|
271
351
|
ulid.toBytes(id: string): Uint8Array
|
|
272
352
|
ulid.fromBytes(bytes: Uint8Array): string
|
|
273
353
|
ulid.timestamp(id: string): number
|
|
274
|
-
ulid.isValid(id:
|
|
354
|
+
ulid.isValid(id: unknown): id is string
|
|
355
|
+
ulid.NIL // "00000000000000000000000000"
|
|
356
|
+
ulid.MAX // "7ZZZZZZZZZZZZZZZZZZZZZZZZZ"
|
|
275
357
|
```
|
|
276
358
|
|
|
277
359
|
### `cuid2` (from `uniku/cuid2`)
|
|
@@ -288,6 +370,9 @@ nanoid(): string
|
|
|
288
370
|
nanoid(size: number): string
|
|
289
371
|
nanoid(options: NanoidOptions): string
|
|
290
372
|
nanoid.isValid(id: unknown): id is string
|
|
373
|
+
|
|
374
|
+
// Constant
|
|
375
|
+
URL_ALPHABET // "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-"
|
|
291
376
|
```
|
|
292
377
|
|
|
293
378
|
### `ksuid` (from `uniku/ksuid`)
|
|
@@ -298,7 +383,9 @@ ksuid(options: KsuidOptions | undefined, buf: Uint8Array, offset?: number): Uint
|
|
|
298
383
|
ksuid.toBytes(id: string): Uint8Array
|
|
299
384
|
ksuid.fromBytes(bytes: Uint8Array): string
|
|
300
385
|
ksuid.timestamp(id: string): number
|
|
301
|
-
ksuid.isValid(id:
|
|
386
|
+
ksuid.isValid(id: unknown): id is string
|
|
387
|
+
ksuid.NIL // "000000000000000000000000000"
|
|
388
|
+
ksuid.MAX // "aWgEPTl1tmebfsQzFP4bxwgy80V"
|
|
302
389
|
```
|
|
303
390
|
|
|
304
391
|
## Documentation
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
function e(e){for(let t=e.length-1;t>=0;--t){if(e[t]<255)return e[t]+=1,!0;e[t]=0}return!1}function t(e,t,n){e[t]=n/1099511627776&255,e[t+1]=n/4294967296&255,e[t+2]=n/16777216&255,e[t+3]=n/65536&255,e[t+4]=n/256&255,e[t+5]=n&255}function n(e,t,n){e[t]=n>>>24&255,e[t+1]=n>>>16&255,e[t+2]=n>>>8&255,e[t+3]=n&255}export{n,t as r,e as t};
|
|
2
|
+
//# sourceMappingURL=bytes-BBjKLOBR.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bytes-BBjKLOBR.mjs","names":[],"sources":["../src/common/bytes.ts"],"sourcesContent":["/**\n * Common byte manipulation utilities shared across ID generators.\n */\n\n/**\n * Increment a byte array by 1 in-place, propagating carry from LSB to MSB.\n * Mutates the input array directly - no allocation.\n *\n * Used by ULID and KSUID for monotonic ordering within the same time unit.\n *\n * @returns true if increment succeeded, false if all bytes overflowed to 0\n */\nexport function incrementBytesInPlace(bytes: Uint8Array): boolean {\n for (let i = bytes.length - 1; i >= 0; i -= 1) {\n if (bytes[i] < 255) {\n bytes[i] += 1\n return true\n }\n bytes[i] = 0\n }\n\n // All bytes overflowed to 0 - astronomically unlikely (1 in 2^80 for ULID, 1 in 2^128 for KSUID)\n return false\n}\n\n/**\n * Write a 48-bit timestamp as big-endian bytes.\n * Used by UUID v7 and ULID for millisecond-precision timestamps.\n *\n * @param buf - Target buffer\n * @param offset - Starting byte offset\n * @param msecs - Milliseconds since Unix epoch (must fit in 48 bits)\n */\nexport function writeTimestamp48(buf: Uint8Array, offset: number, msecs: number): void {\n buf[offset] = (msecs / 0x10000000000) & 0xff\n buf[offset + 1] = (msecs / 0x100000000) & 0xff\n buf[offset + 2] = (msecs / 0x1000000) & 0xff\n buf[offset + 3] = (msecs / 0x10000) & 0xff\n buf[offset + 4] = (msecs / 0x100) & 0xff\n buf[offset + 5] = msecs & 0xff\n}\n\n/**\n * Write a 32-bit timestamp as big-endian bytes.\n * Used by KSUID for second-precision timestamps.\n *\n * `writeTimestamp32(buf, offset, timestamp)` is equivalent to `new DataView(buf.buffer, offset, 4).setUint32(offset, timestamp, false)`,\n * but it's faster because it doesn't require creating a DataView object.\n *\n * @param buf - Target buffer\n * @param offset - Starting byte offset\n * @param secs - Seconds (must fit in 32 bits)\n */\nexport function writeTimestamp32(buf: Uint8Array, offset: number, secs: number): void {\n buf[offset] = (secs >>> 24) & 0xff\n buf[offset + 1] = (secs >>> 16) & 0xff\n buf[offset + 2] = (secs >>> 8) & 0xff\n buf[offset + 3] = secs & 0xff\n}\n"],"mappings":"AAYA,SAAgB,EAAsB,EAA4B,CAChE,IAAK,IAAI,EAAI,EAAM,OAAS,EAAG,GAAK,EAAG,IAAQ,CAC7C,GAAI,EAAM,GAAK,IAEb,MADA,GAAM,IAAM,EACL,GAET,EAAM,GAAK,EAIb,MAAO,GAWT,SAAgB,EAAiB,EAAiB,EAAgB,EAAqB,CACrF,EAAI,GAAW,EAAQ,cAAiB,IACxC,EAAI,EAAS,GAAM,EAAQ,WAAe,IAC1C,EAAI,EAAS,GAAM,EAAQ,SAAa,IACxC,EAAI,EAAS,GAAM,EAAQ,MAAW,IACtC,EAAI,EAAS,GAAM,EAAQ,IAAS,IACpC,EAAI,EAAS,GAAK,EAAQ,IAc5B,SAAgB,EAAiB,EAAiB,EAAgB,EAAoB,CACpF,EAAI,GAAW,IAAS,GAAM,IAC9B,EAAI,EAAS,GAAM,IAAS,GAAM,IAClC,EAAI,EAAS,GAAM,IAAS,EAAK,IACjC,EAAI,EAAS,GAAK,EAAO"}
|
package/build/cuid2/cuid2.d.mts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { InvalidInputError, UniqueIdError } from "../errors.mjs";
|
|
2
|
+
|
|
1
3
|
//#region src/cuid2/cuid2.d.ts
|
|
2
4
|
type Cuid2Options = {
|
|
3
5
|
/**
|
|
@@ -47,5 +49,5 @@ type Cuid2 = {
|
|
|
47
49
|
*/
|
|
48
50
|
declare const cuid2: Cuid2;
|
|
49
51
|
//#endregion
|
|
50
|
-
export { Cuid2, Cuid2Options, cuid2 };
|
|
52
|
+
export { Cuid2, Cuid2Options, InvalidInputError, UniqueIdError, cuid2 };
|
|
51
53
|
//# sourceMappingURL=cuid2.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cuid2.d.mts","names":["cuid2: Cuid2"],"sources":["../../src/cuid2/cuid2.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"cuid2.d.mts","names":["cuid2: Cuid2"],"sources":["../../src/cuid2/cuid2.ts"],"sourcesContent":[],"mappings":";;;KAIY,YAAA;;;AAAZ;AAeA;EA4MA,MAAaA,CAAAA,EAAAA,MAAO;;;;;;;WA/MT;;KAGC,KAAA;aACC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA2MAA,OAAO"}
|
package/build/cuid2/cuid2.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{InvalidInputError as e,UniqueIdError as t}from"../errors.mjs";import{sha3_512 as n}from"@noble/hashes/sha3.js";function r(e){let t=4+e*128,n,r=!1;if(typeof SharedArrayBuffer<`u`)try{n=new SharedArrayBuffer(t),r=!0}catch{n=new ArrayBuffer(t)}else n=new ArrayBuffer(t);let i=new Int32Array(n,0,1),a=new Uint8Array(n,4);return crypto.getRandomValues(a),{buffer:n,bytes:a,offset:i,useAtomics:r}}function i(e,t){if(e.useAtomics){let n=Atomics.add(e.offset,0,t);return n+t<=e.bytes.length?n:Atomics.compareExchange(e.offset,0,n+t,t)===n+t?(crypto.getRandomValues(e.bytes),0):i(e,t)}else{let n=e.offset[0];return n+t>e.bytes.length&&(crypto.getRandomValues(e.bytes),n=0),e.offset[0]=n+t,n}}function a(e,t){let n=i(e,t);return e.bytes.subarray(n,n+t)}const o=/^[a-z][0-9a-z]+$/,s=`0123456789abcdefghijklmnopqrstuvwxyz`,c=new TextEncoder;let l;function u(){return l||=r(4),l}const d={counter:void 0,fingerprint:void 0};function f(){let e=a(u(),4);return((e[0]<<24|e[1]<<16|e[2]<<8|e[3])>>>0)%476782368}function p(e){let t=0n;for(let n of e)t=t*256n+BigInt(n);return t}function m(e){if(e===0n)return`0`;let t=[];for(;e>0n;)t.push(s[Number(e%36n)]),e/=36n;return t.reverse().join(``)}function h(e){return`abcdefghijklmnopqrstuvwxyz`[Math.floor(e()*26)]}function g(e,t){let n=Array(e);for(let r=0;r<e;r++)n[r]=s[Math.floor(t()*36)];return n.join(``)}function _(e){return n(c.encode(e))}function v(){let e=y;return m(p(_(Object.keys(globalThis).toString()+g(32,e)))).slice(1,33)}function y(){let e=u(),t=i(e,4),n=e.bytes;return(n[t]*16777216+n[t+1]*65536+n[t+2]*256+n[t+3])/4294967296}function b(t){if(t){if(t.length===0)throw new e(`CUID2_RANDOM_BYTES_EMPTY`,`Random byte array cannot be empty`);let n=0;return()=>{let e=t[n%t.length]/256;return n+=1,e}}return y}function x(t){let n=t?.length??24;if(n<2||n>32)throw new e(`CUID2_LENGTH_OUT_OF_RANGE`,`CUID2 length must be between 2 and 32. Received: ${n}`);let r=b(t?.random);d.counter===void 0&&(d.counter=f()),d.fingerprint===void 0&&(d.fingerprint=v());let i=h(r),a=Date.now().toString(36);d.counter+=1;let o=d.counter.toString(36);return i+m(p(_(a+g(n,r)+o+d.fingerprint))).slice(1,n)}function S(e){return typeof e==`string`&&e.length>=2&&e.length<=32&&o.test(e)}const C=Object.assign(x,{isValid:S});export{e as InvalidInputError,t as UniqueIdError,C as cuid2};
|
|
2
2
|
//# sourceMappingURL=cuid2.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cuid2.mjs","names":["buffer: SharedArrayBuffer | ArrayBuffer","pool","pool: RandomPool | undefined","state: { counter: number | undefined; fingerprint: string | undefined }","chars: string[]","cuid2: Cuid2"],"sources":["../../src/common/random-pool.ts","../../src/cuid2/cuid2.ts"],"sourcesContent":["/**\n * Thread-safe random byte pool utilities using Atomics (when SharedArrayBuffer is available).\n * Falls back to regular pooling in environments without SharedArrayBuffer.\n *\n * This module provides STATELESS utilities - each consumer creates and manages its own pool.\n * Pass the pool state to each function (C-style) for explicit, predictable behavior.\n *\n * @example\n * ```ts\n * // Each module creates its own pool\n * let pool: RandomPool | undefined\n *\n * function getBytes(count: number): number {\n * if (!pool) pool = createPool(count)\n * return getPooledBytes(pool, count)\n * }\n * ```\n */\n\nconst POOL_SIZE_MULTIPLIER = 128\nconst POOL_HEADER_SIZE = 4 // 4 bytes for Int32 offset counter\n\n/**\n * Pool state - passed to all pool functions.\n * Each module creates and owns its own pool instance.\n */\nexport type RandomPool = {\n buffer: SharedArrayBuffer | ArrayBuffer\n bytes: Uint8Array\n offset: Int32Array\n useAtomics: boolean\n}\n\n/**\n * Create a new random pool. Uses SharedArrayBuffer + Atomics when available\n * for thread-safety in Web Worker scenarios.\n *\n * @param minSize - Minimum bytes needed per request (pool = minSize * 128)\n */\nexport function createPool(minSize: number): RandomPool {\n const poolSize = minSize * POOL_SIZE_MULTIPLIER\n const totalSize = POOL_HEADER_SIZE + poolSize\n\n let buffer: SharedArrayBuffer | ArrayBuffer\n let useAtomics = false\n\n // Try SharedArrayBuffer first (thread-safe with Atomics)\n if (typeof SharedArrayBuffer !== 'undefined') {\n try {\n buffer = new SharedArrayBuffer(totalSize)\n useAtomics = true\n } catch {\n // SharedArrayBuffer may be disabled (security restrictions)\n buffer = new ArrayBuffer(totalSize)\n }\n } else {\n buffer = new ArrayBuffer(totalSize)\n }\n\n // First 4 bytes = atomic offset counter, rest = random bytes\n const offset = new Int32Array(buffer, 0, 1)\n const bytes = new Uint8Array(buffer, POOL_HEADER_SIZE)\n crypto.getRandomValues(bytes)\n\n return { buffer, bytes, offset, useAtomics }\n}\n\n/**\n * Get pooled random bytes. Thread-safe when SharedArrayBuffer is available.\n * Returns the starting index in the pool for the requested bytes.\n *\n * @param pool - The pool state (from createPool)\n * @param count - Number of bytes needed\n * @returns Starting offset in pool.bytes\n *\n * @example\n * ```ts\n * const offset = getPooledBytes(pool, 21)\n * for (let i = offset; i < offset + 21; i++) {\n * // Use pool.bytes[i]\n * }\n * ```\n */\nexport function getPooledBytes(pool: RandomPool, count: number): number {\n if (pool.useAtomics) {\n // Thread-safe path using Atomics\n const startOffset = Atomics.add(pool.offset, 0, count)\n\n if (startOffset + count <= pool.bytes.length) {\n return startOffset\n }\n\n // Pool exhausted - need to refill\n // Use compareExchange to ensure only one thread refills\n const resetResult = Atomics.compareExchange(pool.offset, 0, startOffset + count, count)\n if (resetResult === startOffset + count) {\n // We won the race - refill the pool\n crypto.getRandomValues(pool.bytes)\n return 0\n }\n\n // Another thread is refilling or already refilled - retry\n return getPooledBytes(pool, count)\n } else {\n // Single-threaded path\n let currentOffset = pool.offset[0]\n\n if (currentOffset + count > pool.bytes.length) {\n crypto.getRandomValues(pool.bytes)\n currentOffset = 0\n }\n\n pool.offset[0] = currentOffset + count\n return currentOffset\n }\n}\n\n/**\n * Get a Uint8Array slice of random bytes from the pool.\n *\n * Note: Returns a subarray VIEW into the pool. If you need the bytes to persist\n * beyond the current synchronous operation, use getRandomBytesCopy() instead.\n *\n * @param pool - The pool state\n * @param count - Number of bytes needed\n */\nexport function getRandomBytes(pool: RandomPool, count: number): Uint8Array {\n const offset = getPooledBytes(pool, count)\n return pool.bytes.subarray(offset, offset + count)\n}\n\n/**\n * Get a COPY of random bytes from the pool.\n * Use this when bytes need to persist (e.g., returned to caller who may use them later).\n *\n * @param pool - The pool state\n * @param count - Number of bytes needed\n */\nexport function getRandomBytesCopy(pool: RandomPool, count: number): Uint8Array {\n const offset = getPooledBytes(pool, count)\n return pool.bytes.slice(offset, offset + count)\n}\n\n/**\n * Fill the provided buffer with random bytes from the pool.\n *\n * @param pool - The pool state\n * @param out - Buffer to fill\n */\nexport function fillRandomBytes(pool: RandomPool, out: Uint8Array): void {\n const offset = getPooledBytes(pool, out.length)\n out.set(pool.bytes.subarray(offset, offset + out.length))\n}\n","import { sha3_512 } from '@noble/hashes/sha3.js'\nimport { createPool, getPooledBytes, getRandomBytes, type RandomPool } from '../common/random-pool'\n\nexport type Cuid2Options = {\n /**\n * Length of the generated ID (2-32 characters).\n * Default: 24\n */\n length?: number\n /**\n * Custom random bytes for deterministic testing.\n * Must be at least 1 byte. For adequate entropy, use at least 16 bytes.\n * Note: The fingerprint always uses cryptographically secure random bytes,\n * regardless of this option.\n */\n random?: Uint8Array\n}\n\nexport type Cuid2 = {\n (options?: Cuid2Options): string\n isValid(id: unknown): id is string\n}\n\nconst DEFAULT_LENGTH = 24\nconst MAX_LENGTH = 32\nconst MIN_LENGTH = 2\n\n// Maximum initial counter value from cuid2 spec - provides ~29 bits of\n// initial entropy to prevent cross-process collisions at startup\nconst INITIAL_COUNT_MAX = 476782367\n\n// Validation regex: first char must be a-z, rest can be a-z or 0-9\nconst CUID2_REGEX = /^[a-z][0-9a-z]+$/\n\n// Base36 alphabet\nconst ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'\nconst LETTER_ALPHABET = 'abcdefghijklmnopqrstuvwxyz'\n\n// Reusable TextEncoder instance (stateless, safe to share)\nconst textEncoder = new TextEncoder()\n\n// CUID2's own pool - lazily initialized on first use\n// Uses 4 bytes per random() call\nlet pool: RandomPool | undefined\n\nfunction ensurePool(): RandomPool {\n if (!pool) pool = createPool(4)\n return pool\n}\n\n/**\n * Module-level state for counter and fingerprint.\n * Counter is initialized lazily on first call to prevent unnecessary crypto operations.\n * Fingerprint is also generated lazily on first call.\n */\nconst state: { counter: number | undefined; fingerprint: string | undefined } = {\n counter: undefined,\n fingerprint: undefined,\n}\n\n/**\n * Initialize counter using crypto for consistency with other entropy sources.\n */\nfunction initializeCounter(): number {\n const buffer = getRandomBytes(ensurePool(), 4)\n return (((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]) >>> 0) % (INITIAL_COUNT_MAX + 1)\n}\n\n// --- Base36 utilities ---\n\nfunction bufToBigInt(buf: Uint8Array): bigint {\n let value = 0n\n for (const byte of buf) {\n value = value * 256n + BigInt(byte)\n }\n return value\n}\n\nfunction bigIntToBase36(value: bigint): string {\n if (value === 0n) return '0'\n const chars: string[] = []\n while (value > 0n) {\n chars.push(ALPHABET[Number(value % 36n)])\n value = value / 36n\n }\n return chars.reverse().join('')\n}\n\nfunction randomLetter(random: () => number): string {\n return LETTER_ALPHABET[Math.floor(random() * 26)]\n}\n\nfunction createEntropy(length: number, random: () => number): string {\n const chars = new Array<string>(length)\n for (let i = 0; i < length; i++) {\n chars[i] = ALPHABET[Math.floor(random() * 36)]\n }\n return chars.join('')\n}\n\n// --- SHA3 hash wrapper ---\n\nfunction hash(input: string): Uint8Array {\n return sha3_512(textEncoder.encode(input))\n}\n\n// --- Fingerprint generation ---\n\nconst BIG_LENGTH = 32\n\nfunction createFingerprint(): string {\n // Always use CSPRNG for fingerprint to ensure security regardless of custom random option\n const random = getCryptoRandom\n const globals = Object.keys(globalThis).toString()\n const sourceString = globals + createEntropy(BIG_LENGTH, random)\n const hashed = hash(sourceString)\n return bigIntToBase36(bufToBigInt(hashed)).slice(1, BIG_LENGTH + 1)\n}\n\n// --- Random function factory ---\n\n/**\n * Get a random number in [0, 1) using CUID2's own random pool.\n * Thread-safe when SharedArrayBuffer is available.\n */\nfunction getCryptoRandom(): number {\n const p = ensurePool()\n const offset = getPooledBytes(p, 4)\n const bytes = p.bytes\n const value =\n (bytes[offset] * 0x1000000 + bytes[offset + 1] * 0x10000 + bytes[offset + 2] * 0x100 + bytes[offset + 3]) /\n 0x100000000\n return value\n}\n\nfunction getRandomFn(random?: Uint8Array): () => number {\n if (random) {\n if (random.length === 0) {\n throw new Error('Random byte array cannot be empty')\n }\n let index = 0\n return () => {\n const value = random[index % random.length] / 256\n index += 1\n return value\n }\n }\n return getCryptoRandom\n}\n\n// --- Main generator ---\n\nfunction cuid2Fn(options?: Cuid2Options): string {\n const length = options?.length ?? DEFAULT_LENGTH\n\n if (length < MIN_LENGTH || length > MAX_LENGTH) {\n throw new RangeError(`CUID2 length must be between ${MIN_LENGTH} and ${MAX_LENGTH}. Received: ${length}`)\n }\n\n const random = getRandomFn(options?.random)\n\n // Initialize counter lazily on first call\n if (state.counter === undefined) {\n state.counter = initializeCounter()\n }\n\n // Initialize fingerprint lazily on first call (always uses CSPRNG)\n if (state.fingerprint === undefined) {\n state.fingerprint = createFingerprint()\n }\n\n const firstLetter = randomLetter(random)\n const time = Date.now().toString(36)\n state.counter += 1\n const count = state.counter.toString(36)\n const salt = createEntropy(length, random)\n\n const hashInput = time + salt + count + state.fingerprint\n const hashed = hash(hashInput)\n const base36Hash = bigIntToBase36(bufToBigInt(hashed))\n\n // Drop first char of hash to avoid histogram bias, prepend random letter\n return firstLetter + base36Hash.slice(1, length)\n}\n\n// --- Validation (type guard) ---\n\nfunction isValid(id: unknown): id is string {\n return typeof id === 'string' && id.length >= MIN_LENGTH && id.length <= MAX_LENGTH && CUID2_REGEX.test(id)\n}\n\n/**\n * Generate a CUID2 string.\n *\n * CUID2 is a secure, collision-resistant identifier that hashes multiple\n * entropy sources using SHA3-512. Unlike time-ordered IDs (ULID, UUID v7),\n * CUID2 prevents enumeration attacks by making IDs non-predictable.\n *\n * Note: CUID2 does not provide toBytes/fromBytes because it is a string-native\n * format with no canonical binary representation (unlike UUID's 16-byte format).\n *\n * @example\n * ```ts\n * import { cuid2 } from 'uniku/cuid2'\n *\n * const id = cuid2()\n * // => \"pfh0haxfpzowht3oi213cqos\"\n *\n * // Custom length\n * const shortId = cuid2({ length: 10 })\n * // => \"tz4a98xxat\"\n *\n * // Validation (type guard)\n * const maybeId: unknown = getUserInput()\n * if (cuid2.isValid(maybeId)) {\n * console.log(maybeId.length) // TypeScript knows maybeId is string\n * }\n * ```\n */\nexport const cuid2: Cuid2 = Object.assign(cuid2Fn, {\n isValid,\n})\n"],"mappings":"iDAuCA,SAAgB,EAAW,EAA6B,CAEtD,IAAM,EAAY,EADD,EAAU,IAGvBA,EACA,EAAa,GAGjB,GAAI,OAAO,kBAAsB,IAC/B,GAAI,CACF,EAAS,IAAI,kBAAkB,EAAU,CACzC,EAAa,QACP,CAEN,EAAS,IAAI,YAAY,EAAU,MAGrC,EAAS,IAAI,YAAY,EAAU,CAIrC,IAAM,EAAS,IAAI,WAAW,EAAQ,EAAG,EAAE,CACrC,EAAQ,IAAI,WAAW,EAAQ,EAAiB,CAGtD,OAFA,OAAO,gBAAgB,EAAM,CAEtB,CAAE,SAAQ,QAAO,SAAQ,aAAY,CAmB9C,SAAgB,EAAe,EAAkB,EAAuB,CACtE,GAAIC,EAAK,WAAY,CAEnB,IAAM,EAAc,QAAQ,IAAIA,EAAK,OAAQ,EAAG,EAAM,CAgBtD,OAdI,EAAc,GAASA,EAAK,MAAM,OAC7B,EAKW,QAAQ,gBAAgBA,EAAK,OAAQ,EAAG,EAAc,EAAO,EAAM,GACnE,EAAc,GAEhC,OAAO,gBAAgBA,EAAK,MAAM,CAC3B,GAIF,EAAeA,EAAM,EAAM,KAC7B,CAEL,IAAI,EAAgBA,EAAK,OAAO,GAQhC,OANI,EAAgB,EAAQA,EAAK,MAAM,SACrC,OAAO,gBAAgBA,EAAK,MAAM,CAClC,EAAgB,GAGlB,EAAK,OAAO,GAAK,EAAgB,EAC1B,GAaX,SAAgB,EAAe,EAAkB,EAA2B,CAC1E,IAAM,EAAS,EAAeA,EAAM,EAAM,CAC1C,OAAOA,EAAK,MAAM,SAAS,EAAQ,EAAS,EAAM,CCzGpD,MASM,EAAc,mBAGd,EAAW,uCAIX,EAAc,IAAI,YAIxB,IAAI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AAY,EAAM,EAAS,GAAK,MAAU,EAAM,EAAS,GAAK,IAAQ,EAAM,EAAS,IACtG,WAIJ,SAAS,EAAY,EAAmC,CACtD,GAAI,EAAQ,CACV,GAAI,EAAO,SAAW,EACpB,MAAU,MAAM,oCAAoC,CAEtD,IAAI,EAAQ,EACZ,UAAa,CACX,IAAM,EAAQ,EAAO,EAAQ,EAAO,QAAU,IAE9C,MADA,IAAS,EACF,GAGX,OAAO,EAKT,SAAS,EAAQ,EAAgC,CAC/C,IAAM,EAAS,GAAS,QAAU,GAElC,GAAI,EAAS,GAAc,EAAS,GAClC,MAAU,WAAW,oDAA2E,IAAS,CAG3G,IAAM,EAAS,EAAY,GAAS,OAAO,CAGvC,EAAM,UAAY,IAAA,KACpB,EAAM,QAAU,GAAmB,EAIjC,EAAM,cAAgB,IAAA,KACxB,EAAM,YAAc,GAAmB,EAGzC,IAAM,EAAc,EAAa,EAAO,CAClC,EAAO,KAAK,KAAK,CAAC,SAAS,GAAG,CACpC,EAAM,SAAW,EACjB,IAAM,EAAQ,EAAM,QAAQ,SAAS,GAAG,CAQxC,OAAO,EAHY,EAAe,EADnB,EADG,EAFL,EAAc,EAAQ,EAAO,CAEV,EAAQ,EAAM,YAChB,CACuB,CAAC,CAGtB,MAAM,EAAG,EAAO,CAKlD,SAAS,EAAQ,EAA2B,CAC1C,OAAO,OAAO,GAAO,UAAY,EAAG,QAAU,GAAc,EAAG,QAAU,IAAc,EAAY,KAAK,EAAG,CA+B7G,MAAaC,EAAe,OAAO,OAAO,EAAS,CACjD,UACD,CAAC"}
|
|
1
|
+
{"version":3,"file":"cuid2.mjs","names":["buffer: SharedArrayBuffer | ArrayBuffer","pool","pool: RandomPool | undefined","state: { counter: number | undefined; fingerprint: string | undefined }","chars: string[]","cuid2: Cuid2"],"sources":["../../src/common/random-pool.ts","../../src/cuid2/cuid2.ts"],"sourcesContent":["/**\n * Thread-safe random byte pool utilities using Atomics (when SharedArrayBuffer is available).\n * Falls back to regular pooling in environments without SharedArrayBuffer.\n *\n * This module provides STATELESS utilities - each consumer creates and manages its own pool.\n * Pass the pool state to each function (C-style) for explicit, predictable behavior.\n *\n * @example\n * ```ts\n * // Each module creates its own pool\n * let pool: RandomPool | undefined\n *\n * function getBytes(count: number): number {\n * if (!pool) pool = createPool(count)\n * return getPooledBytes(pool, count)\n * }\n * ```\n */\n\nconst POOL_SIZE_MULTIPLIER = 128\nconst POOL_HEADER_SIZE = 4 // 4 bytes for Int32 offset counter\n\n/**\n * Pool state - passed to all pool functions.\n * Each module creates and owns its own pool instance.\n */\nexport type RandomPool = {\n buffer: SharedArrayBuffer | ArrayBuffer\n bytes: Uint8Array\n offset: Int32Array\n useAtomics: boolean\n}\n\n/**\n * Create a new random pool. Uses SharedArrayBuffer + Atomics when available\n * for thread-safety in Web Worker scenarios.\n *\n * @param minSize - Minimum bytes needed per request (pool = minSize * 128)\n */\nexport function createPool(minSize: number): RandomPool {\n const poolSize = minSize * POOL_SIZE_MULTIPLIER\n const totalSize = POOL_HEADER_SIZE + poolSize\n\n let buffer: SharedArrayBuffer | ArrayBuffer\n let useAtomics = false\n\n // Try SharedArrayBuffer first (thread-safe with Atomics)\n if (typeof SharedArrayBuffer !== 'undefined') {\n try {\n buffer = new SharedArrayBuffer(totalSize)\n useAtomics = true\n } catch {\n // SharedArrayBuffer may be disabled (security restrictions)\n buffer = new ArrayBuffer(totalSize)\n }\n } else {\n buffer = new ArrayBuffer(totalSize)\n }\n\n // First 4 bytes = atomic offset counter, rest = random bytes\n const offset = new Int32Array(buffer, 0, 1)\n const bytes = new Uint8Array(buffer, POOL_HEADER_SIZE)\n crypto.getRandomValues(bytes)\n\n return { buffer, bytes, offset, useAtomics }\n}\n\n/**\n * Get pooled random bytes. Thread-safe when SharedArrayBuffer is available.\n * Returns the starting index in the pool for the requested bytes.\n *\n * @param pool - The pool state (from createPool)\n * @param count - Number of bytes needed\n * @returns Starting offset in pool.bytes\n *\n * @example\n * ```ts\n * const offset = getPooledBytes(pool, 21)\n * for (let i = offset; i < offset + 21; i++) {\n * // Use pool.bytes[i]\n * }\n * ```\n */\nexport function getPooledBytes(pool: RandomPool, count: number): number {\n if (pool.useAtomics) {\n // Thread-safe path using Atomics\n const startOffset = Atomics.add(pool.offset, 0, count)\n\n if (startOffset + count <= pool.bytes.length) {\n return startOffset\n }\n\n // Pool exhausted - need to refill\n // Use compareExchange to ensure only one thread refills\n const resetResult = Atomics.compareExchange(pool.offset, 0, startOffset + count, count)\n if (resetResult === startOffset + count) {\n // We won the race - refill the pool\n crypto.getRandomValues(pool.bytes)\n return 0\n }\n\n // Another thread is refilling or already refilled - retry\n return getPooledBytes(pool, count)\n } else {\n // Single-threaded path\n let currentOffset = pool.offset[0]\n\n if (currentOffset + count > pool.bytes.length) {\n crypto.getRandomValues(pool.bytes)\n currentOffset = 0\n }\n\n pool.offset[0] = currentOffset + count\n return currentOffset\n }\n}\n\n/**\n * Get a Uint8Array slice of random bytes from the pool.\n *\n * Note: Returns a subarray VIEW into the pool. If you need the bytes to persist\n * beyond the current synchronous operation, use getRandomBytesCopy() instead.\n *\n * @param pool - The pool state\n * @param count - Number of bytes needed\n */\nexport function getRandomBytes(pool: RandomPool, count: number): Uint8Array {\n const offset = getPooledBytes(pool, count)\n return pool.bytes.subarray(offset, offset + count)\n}\n\n/**\n * Get a COPY of random bytes from the pool.\n * Use this when bytes need to persist (e.g., returned to caller who may use them later).\n *\n * @param pool - The pool state\n * @param count - Number of bytes needed\n */\nexport function getRandomBytesCopy(pool: RandomPool, count: number): Uint8Array {\n const offset = getPooledBytes(pool, count)\n return pool.bytes.slice(offset, offset + count)\n}\n\n/**\n * Fill the provided buffer with random bytes from the pool.\n *\n * @param pool - The pool state\n * @param out - Buffer to fill\n */\nexport function fillRandomBytes(pool: RandomPool, out: Uint8Array): void {\n const offset = getPooledBytes(pool, out.length)\n out.set(pool.bytes.subarray(offset, offset + out.length))\n}\n","import { sha3_512 } from '@noble/hashes/sha3.js'\nimport { createPool, getPooledBytes, getRandomBytes, type RandomPool } from '../common/random-pool'\nimport { InvalidInputError } from '../errors'\n\nexport type Cuid2Options = {\n /**\n * Length of the generated ID (2-32 characters).\n * Default: 24\n */\n length?: number\n /**\n * Custom random bytes for deterministic testing.\n * Must be at least 1 byte. For adequate entropy, use at least 16 bytes.\n * Note: The fingerprint always uses cryptographically secure random bytes,\n * regardless of this option.\n */\n random?: Uint8Array\n}\n\nexport type Cuid2 = {\n (options?: Cuid2Options): string\n isValid(id: unknown): id is string\n}\n\nconst DEFAULT_LENGTH = 24\nconst MAX_LENGTH = 32\nconst MIN_LENGTH = 2\n\n// Maximum initial counter value from cuid2 spec - provides ~29 bits of\n// initial entropy to prevent cross-process collisions at startup\nconst INITIAL_COUNT_MAX = 476782367\n\n// Validation regex: first char must be a-z, rest can be a-z or 0-9\nconst CUID2_REGEX = /^[a-z][0-9a-z]+$/\n\n// Base36 alphabet\nconst ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'\nconst LETTER_ALPHABET = 'abcdefghijklmnopqrstuvwxyz'\n\n// Reusable TextEncoder instance (stateless, safe to share)\nconst textEncoder = new TextEncoder()\n\n// CUID2's own pool - lazily initialized on first use\n// Uses 4 bytes per random() call\nlet pool: RandomPool | undefined\n\nfunction ensurePool(): RandomPool {\n if (!pool) pool = createPool(4)\n return pool\n}\n\n/**\n * Module-level state for counter and fingerprint.\n * Counter is initialized lazily on first call to prevent unnecessary crypto operations.\n * Fingerprint is also generated lazily on first call.\n */\nconst state: { counter: number | undefined; fingerprint: string | undefined } = {\n counter: undefined,\n fingerprint: undefined,\n}\n\n/**\n * Initialize counter using crypto for consistency with other entropy sources.\n */\nfunction initializeCounter(): number {\n const buffer = getRandomBytes(ensurePool(), 4)\n return (((buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | buffer[3]) >>> 0) % (INITIAL_COUNT_MAX + 1)\n}\n\n// --- Base36 utilities ---\n\nfunction bufToBigInt(buf: Uint8Array): bigint {\n let value = 0n\n for (const byte of buf) {\n value = value * 256n + BigInt(byte)\n }\n return value\n}\n\nfunction bigIntToBase36(value: bigint): string {\n if (value === 0n) return '0'\n const chars: string[] = []\n while (value > 0n) {\n chars.push(ALPHABET[Number(value % 36n)])\n value = value / 36n\n }\n return chars.reverse().join('')\n}\n\nfunction randomLetter(random: () => number): string {\n return LETTER_ALPHABET[Math.floor(random() * 26)]\n}\n\nfunction createEntropy(length: number, random: () => number): string {\n const chars = new Array<string>(length)\n for (let i = 0; i < length; i++) {\n chars[i] = ALPHABET[Math.floor(random() * 36)]\n }\n return chars.join('')\n}\n\n// --- SHA3 hash wrapper ---\n\nfunction hash(input: string): Uint8Array {\n return sha3_512(textEncoder.encode(input))\n}\n\n// --- Fingerprint generation ---\n\nconst BIG_LENGTH = 32\n\nfunction createFingerprint(): string {\n // Always use CSPRNG for fingerprint to ensure security regardless of custom random option\n const random = getCryptoRandom\n const globals = Object.keys(globalThis).toString()\n const sourceString = globals + createEntropy(BIG_LENGTH, random)\n const hashed = hash(sourceString)\n return bigIntToBase36(bufToBigInt(hashed)).slice(1, BIG_LENGTH + 1)\n}\n\n// --- Random function factory ---\n\n/**\n * Get a random number in [0, 1) using CUID2's own random pool.\n * Thread-safe when SharedArrayBuffer is available.\n */\nfunction getCryptoRandom(): number {\n const p = ensurePool()\n const offset = getPooledBytes(p, 4)\n const bytes = p.bytes\n const value =\n (bytes[offset] * 0x1000000 + bytes[offset + 1] * 0x10000 + bytes[offset + 2] * 0x100 + bytes[offset + 3]) /\n 0x100000000\n return value\n}\n\nfunction getRandomFn(random?: Uint8Array): () => number {\n if (random) {\n if (random.length === 0) {\n throw new InvalidInputError('CUID2_RANDOM_BYTES_EMPTY', 'Random byte array cannot be empty')\n }\n let index = 0\n return () => {\n const value = random[index % random.length] / 256\n index += 1\n return value\n }\n }\n return getCryptoRandom\n}\n\n// --- Main generator ---\n\nfunction cuid2Fn(options?: Cuid2Options): string {\n const length = options?.length ?? DEFAULT_LENGTH\n\n if (length < MIN_LENGTH || length > MAX_LENGTH) {\n throw new InvalidInputError(\n 'CUID2_LENGTH_OUT_OF_RANGE',\n `CUID2 length must be between ${MIN_LENGTH} and ${MAX_LENGTH}. Received: ${length}`,\n )\n }\n\n const random = getRandomFn(options?.random)\n\n // Initialize counter lazily on first call\n if (state.counter === undefined) {\n state.counter = initializeCounter()\n }\n\n // Initialize fingerprint lazily on first call (always uses CSPRNG)\n if (state.fingerprint === undefined) {\n state.fingerprint = createFingerprint()\n }\n\n const firstLetter = randomLetter(random)\n const time = Date.now().toString(36)\n state.counter += 1\n const count = state.counter.toString(36)\n const salt = createEntropy(length, random)\n\n const hashInput = time + salt + count + state.fingerprint\n const hashed = hash(hashInput)\n const base36Hash = bigIntToBase36(bufToBigInt(hashed))\n\n // Drop first char of hash to avoid histogram bias, prepend random letter\n return firstLetter + base36Hash.slice(1, length)\n}\n\n// --- Validation (type guard) ---\n\nfunction isValid(id: unknown): id is string {\n return typeof id === 'string' && id.length >= MIN_LENGTH && id.length <= MAX_LENGTH && CUID2_REGEX.test(id)\n}\n\n/**\n * Generate a CUID2 string.\n *\n * CUID2 is a secure, collision-resistant identifier that hashes multiple\n * entropy sources using SHA3-512. Unlike time-ordered IDs (ULID, UUID v7),\n * CUID2 prevents enumeration attacks by making IDs non-predictable.\n *\n * Note: CUID2 does not provide toBytes/fromBytes because it is a string-native\n * format with no canonical binary representation (unlike UUID's 16-byte format).\n *\n * @example\n * ```ts\n * import { cuid2 } from 'uniku/cuid2'\n *\n * const id = cuid2()\n * // => \"pfh0haxfpzowht3oi213cqos\"\n *\n * // Custom length\n * const shortId = cuid2({ length: 10 })\n * // => \"tz4a98xxat\"\n *\n * // Validation (type guard)\n * const maybeId: unknown = getUserInput()\n * if (cuid2.isValid(maybeId)) {\n * console.log(maybeId.length) // TypeScript knows maybeId is string\n * }\n * ```\n */\nexport const cuid2: Cuid2 = Object.assign(cuid2Fn, {\n isValid,\n})\n\nexport { InvalidInputError, UniqueIdError } from '../errors'\n"],"mappings":"sHAuC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F,IAAI,EAAQ,EACZ,UAAa,CACX,IAAM,EAAQ,EAAO,EAAQ,EAAO,QAAU,IAE9C,MADA,IAAS,EACF,GAGX,OAAO,EAKT,SAAS,EAAQ,EAAgC,CAC/C,IAAM,EAAS,GAAS,QAAU,GAElC,GAAI,EAAS,GAAc,EAAS,GAClC,MAAM,IAAI,EACR,4BACA,oDAA2E,IAC5E,CAGH,IAAM,EAAS,EAAY,GAAS,OAAO,CAGvC,EAAM,UAAY,IAAA,KACpB,EAAM,QAAU,GAAmB,EAIjC,EAAM,cAAgB,IAAA,KACxB,EAAM,YAAc,GAAmB,EAGzC,IAAM,EAAc,EAAa,EAAO,CAClC,EAAO,KAAK,KAAK,CAAC,SAAS,GAAG,CACpC,EAAM,SAAW,EACjB,IAAM,EAAQ,EAAM,QAAQ,SAAS,GAAG,CAQxC,OAAO,EAHY,EAAe,EADnB,EADG,EAFL,EAAc,EAAQ,EAAO,CAEV,EAAQ,EAAM,YAChB,CACuB,CAAC,CAGtB,MAAM,EAAG,EAAO,CAKlD,SAAS,EAAQ,EAA2B,CAC1C,OAAO,OAAO,GAAO,UAAY,EAAG,QAAU,GAAc,EAAG,QAAU,IAAc,EAAY,KAAK,EAAG,CA+B7G,MAAaC,EAAe,OAAO,OAAO,EAAS,CACjD,UACD,CAAC"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
//#region src/errors.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Base error for all uniku errors.
|
|
4
|
+
* Provides `_tag` for discriminated matching (compatible with Effect's `catchTag`)
|
|
5
|
+
* and `code` for machine-readable error identification.
|
|
6
|
+
*/
|
|
7
|
+
declare abstract class UniqueIdError extends Error {
|
|
8
|
+
abstract readonly _tag: string;
|
|
9
|
+
abstract readonly code: string;
|
|
10
|
+
constructor(message: string);
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Thrown when generator arguments are invalid (bad size, alphabet, length, timestamp, version).
|
|
14
|
+
*/
|
|
15
|
+
declare class InvalidInputError extends UniqueIdError {
|
|
16
|
+
readonly code: string;
|
|
17
|
+
readonly _tag: "InvalidInputError";
|
|
18
|
+
constructor(code: string, message: string);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Thrown when parsing/decoding an ID string that has invalid format or characters.
|
|
22
|
+
*/
|
|
23
|
+
declare class ParseError extends UniqueIdError {
|
|
24
|
+
readonly code: string;
|
|
25
|
+
readonly _tag: "ParseError";
|
|
26
|
+
constructor(code: string, message: string);
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Thrown when a byte array or buffer is too short or an offset is out of bounds.
|
|
30
|
+
*/
|
|
31
|
+
declare class BufferError extends UniqueIdError {
|
|
32
|
+
readonly code: string;
|
|
33
|
+
readonly _tag: "BufferError";
|
|
34
|
+
constructor(code: string, message: string);
|
|
35
|
+
}
|
|
36
|
+
//#endregion
|
|
37
|
+
export { BufferError, InvalidInputError, ParseError, UniqueIdError };
|
|
38
|
+
//# sourceMappingURL=errors.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.mts","names":["code: string"],"sources":["../src/errors.ts"],"sourcesContent":[],"mappings":";;AAKA;AAaA;AAcA;AAcA;uBAzCsB,aAAA,SAAsB,KAAA;;;;;;;;cAa/B,iBAAA,SAA0B,aAAA;;;;;;;;cAc1B,UAAA,SAAmB,aAAA;;;;;;;;cAcnB,WAAA,SAAoB,aAAA"}
|
package/build/errors.mjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e=class extends Error{constructor(e){super(e),this.name=this.constructor.name}},t=class extends e{_tag=`InvalidInputError`;constructor(e,t){super(t),this.code=e}},n=class extends e{_tag=`ParseError`;constructor(e,t){super(t),this.code=e}},r=class extends e{_tag=`BufferError`;constructor(e,t){super(t),this.code=e}};export{r as BufferError,t as InvalidInputError,n as ParseError,e as UniqueIdError};
|
|
2
|
+
//# sourceMappingURL=errors.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.mjs","names":["code: string"],"sources":["../src/errors.ts"],"sourcesContent":["/**\n * Base error for all uniku errors.\n * Provides `_tag` for discriminated matching (compatible with Effect's `catchTag`)\n * and `code` for machine-readable error identification.\n */\nexport abstract class UniqueIdError extends Error {\n abstract readonly _tag: string\n abstract readonly code: string\n\n constructor(message: string) {\n super(message)\n this.name = this.constructor.name\n }\n}\n\n/**\n * Thrown when generator arguments are invalid (bad size, alphabet, length, timestamp, version).\n */\nexport class InvalidInputError extends UniqueIdError {\n readonly _tag = 'InvalidInputError' as const\n\n constructor(\n readonly code: string,\n message: string,\n ) {\n super(message)\n }\n}\n\n/**\n * Thrown when parsing/decoding an ID string that has invalid format or characters.\n */\nexport class ParseError extends UniqueIdError {\n readonly _tag = 'ParseError' as const\n\n constructor(\n readonly code: string,\n message: string,\n ) {\n super(message)\n }\n}\n\n/**\n * Thrown when a byte array or buffer is too short or an offset is out of bounds.\n */\nexport class BufferError extends UniqueIdError {\n readonly _tag = 'BufferError' as const\n\n constructor(\n readonly code: string,\n message: string,\n ) {\n super(message)\n }\n}\n"],"mappings":"AAKA,IAAsB,EAAtB,cAA4C,KAAM,CAIhD,YAAY,EAAiB,CAC3B,MAAM,EAAQ,CACd,KAAK,KAAO,KAAK,YAAY,OAOpB,EAAb,cAAuC,CAAc,CACnD,KAAgB,oBAEhB,YACE,EACA,EACA,CACA,MAAM,EAAQ,CAHL,KAAA,KAAA,IAUA,EAAb,cAAgC,CAAc,CAC5C,KAAgB,aAEhB,YACE,EACA,EACA,CACA,MAAM,EAAQ,CAHL,KAAA,KAAA,IAUA,EAAb,cAAiC,CAAc,CAC7C,KAAgB,cAEhB,YACE,EACA,EACA,CACA,MAAM,EAAQ,CAHL,KAAA,KAAA"}
|
package/build/ksuid/ksuid.d.mts
CHANGED
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { BufferError, InvalidInputError, ParseError, UniqueIdError } from "../errors.mjs";
|
|
2
|
+
|
|
1
3
|
//#region src/ksuid/ksuid.d.ts
|
|
2
4
|
type KsuidOptions = {
|
|
3
5
|
/**
|
|
@@ -18,7 +20,11 @@ type Ksuid = {
|
|
|
18
20
|
toBytes(id: string): Uint8Array;
|
|
19
21
|
fromBytes(bytes: Uint8Array): string;
|
|
20
22
|
timestamp(id: string): number;
|
|
21
|
-
isValid(id:
|
|
23
|
+
isValid(id: unknown): id is string;
|
|
24
|
+
/** The nil KSUID (all zeros) */
|
|
25
|
+
NIL: string;
|
|
26
|
+
/** The max KSUID (maximum valid value) */
|
|
27
|
+
MAX: string;
|
|
22
28
|
};
|
|
23
29
|
/**
|
|
24
30
|
* Generate a KSUID string or write the bytes into a buffer.
|
|
@@ -26,5 +32,5 @@ type Ksuid = {
|
|
|
26
32
|
*/
|
|
27
33
|
declare const ksuid: Ksuid;
|
|
28
34
|
//#endregion
|
|
29
|
-
export { Ksuid, KsuidOptions, ksuid };
|
|
35
|
+
export { BufferError, InvalidInputError, Ksuid, KsuidOptions, ParseError, UniqueIdError, ksuid };
|
|
30
36
|
//# sourceMappingURL=ksuid.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ksuid.d.mts","names":["ksuid: Ksuid"],"sources":["../../src/ksuid/ksuid.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"ksuid.d.mts","names":["ksuid: Ksuid"],"sources":["../../src/ksuid/ksuid.ts"],"sourcesContent":[],"mappings":";;;KA4BY,YAAA;;;AAAZ;EAaA,MAAY,CAAA,EATD,UASC;EAEI;;;;;EACH,IAAA,CAAA,EAAA,MAAA;CACU;AACJ,KALP,KAAA,GAKO;EAAA,EAAA,EAAA,MAAA;EAgInB,CAAA,aAnIgB,UAmII,GAnIS,UAmIT,CAAA,CAAA,OAAA,EAnI8B,YAmI9B,GAAA,SAAA,EAAA,GAAA,EAnI6D,IAmI7D,EAAA,MAAA,CAAA,EAAA,MAAA,CAAA,EAnIqF,IAmIrF;aAlIP;uBACU;mBACJ;;;;;;;;;;;;cAgINA,OAAO"}
|
package/build/ksuid/ksuid.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as
|
|
1
|
+
import{BufferError as e,InvalidInputError as t,ParseError as n,UniqueIdError as r}from"../errors.mjs";import{n as i}from"../bytes-BBjKLOBR.mjs";import{t as a}from"../random-DcKA4vF7.mjs";const o=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`,s=62n,c=new Uint8Array(128);c.fill(255);for(let e=0;e<62;e+=1)c[o.charCodeAt(e)]=e;function l(t){if(t.length<20)throw new e(`KSUID_BYTES_TOO_SHORT`,`KSUID bytes must be at least 20 bytes, got ${t.length}`);let n=0n;for(let e=0;e<20;e+=1)n=n<<8n|BigInt(t[e]);let r=``;for(;n>0n;){let e=n%s;n/=s,r=o[Number(e)]+r}return r.padStart(27,`0`)}function u(e){if(e.length!==27)throw new n(`KSUID_INVALID_LENGTH`,`KSUID string must be 27 characters, got ${e.length}`);let t=0n;for(let r=0;r<27;r+=1){let i=e.charCodeAt(r);if(i>=128)throw new n(`KSUID_INVALID_CHAR`,`Invalid KSUID character: ${e[r]}`);let a=c[i];if(a===255)throw new n(`KSUID_INVALID_CHAR`,`Invalid KSUID character: ${e[r]}`);t=t*s+BigInt(a)}let r=new Uint8Array(20);for(let e=19;e>=0;--e)r[e]=Number(t&255n),t>>=8n;return r}const d=14e8,f=/^[0-9A-Za-z]{27}$/;function p(t,n,r,a=0){if(!r)r=new Uint8Array(20),a=0;else if(a<0||a+20>r.length)throw new e(`KSUID_BUFFER_OUT_OF_BOUNDS`,`KSUID byte range ${a}:${a+20-1} is out of buffer bounds`);i(r,a,t),r.set(n.subarray(4,20),a+4);for(let e=0;e<16;e+=1)r[a+4+e]=n[e];return r}function m(e,n,r=0){if(e){if(e.random&&e.random.length<16)throw new t(`KSUID_RANDOM_BYTES_TOO_SHORT`,`Random bytes length must be >= 16 for KSUID`);if(e.secs&&e.secs<d)throw new t(`KSUID_TIMESTAMP_TOO_LOW`,`Timestamp must be >= KSUID epoch`);e.secs&&(e.secs-=d)}let i=e?.secs??Math.floor(Date.now()/1e3-d),o=e?.random??a();return n?(p(i,o,n,r),n):l(p(i,o))}function h(e){return u(e)}function g(e){return l(e)}function _(e){let t=u(e);return(((t[0]<<24|t[1]<<16|t[2]<<8|t[3])>>>0)+d)*1e3}function v(e){return typeof e==`string`&&e.length===27&&f.test(e)}const y=Object.assign(m,{toBytes:h,fromBytes:g,timestamp:_,isValid:v,NIL:`000000000000000000000000000`,MAX:`aWgEPTl1tmebfsQzFP4bxwgy80V`});export{e as BufferError,t as InvalidInputError,n as ParseError,r as UniqueIdError,y as ksuid};
|
|
2
2
|
//# sourceMappingURL=ksuid.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ksuid.mjs","names":["KSUID_BYTES","KSUID_STRING_LEN","state: KsuidState","secs: number","payload: Uint8Array","ksuid: Ksuid"],"sources":["../../src/ksuid/common/base62.ts","../../src/ksuid/ksuid.ts"],"sourcesContent":["/**\n * Base62 encoding/decoding for KSUID.\n * Alphabet: 0-9A-Za-z (standard Base62 ordering)\n *\n * KSUID binary format: 20 bytes (160 bits)\n * - 4 bytes: timestamp (seconds since KSUID epoch)\n * - 16 bytes: payload (cryptographically random)\n *\n * String format: 27 characters of Base62\n */\n\n// Base62 alphabet: digits (0-9), uppercase (A-Z), lowercase (a-z)\nconst ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\nconst BASE = 62n\nconst KSUID_BYTES = 20\nconst KSUID_STRING_LEN = 27\n\n// Pre-computed decode table indexed by ASCII code (0-127)\n// Uses Uint8Array for cache-efficient lookups via charCodeAt\n// Note: Base62 is case-sensitive - 'A' (value 10) and 'a' (value 36) are different\nconst DECODING = new Uint8Array(128)\nDECODING.fill(255) // 255 = invalid marker\n\nfor (let i = 0; i < ALPHABET.length; i += 1) {\n DECODING[ALPHABET.charCodeAt(i)] = i\n}\n\n/**\n * Encode a 20-byte KSUID to a 27-character Base62 string.\n *\n * Algorithm: Convert the 160-bit number to base 62 using BigInt.\n * V8 has highly optimized BigInt operations for this size.\n */\nexport function encodeBase62(bytes: Uint8Array): string {\n if (bytes.length < KSUID_BYTES) {\n throw new Error(`KSUID bytes must be at least ${KSUID_BYTES} bytes, got ${bytes.length}`)\n }\n\n // Convert bytes to BigInt (big-endian)\n let num = 0n\n for (let i = 0; i < KSUID_BYTES; i += 1) {\n num = (num << 8n) | BigInt(bytes[i])\n }\n\n // Convert to Base62 string (build from right to left)\n const result = new Array<string>(KSUID_STRING_LEN)\n\n for (let i = KSUID_STRING_LEN - 1; i >= 0; i -= 1) {\n result[i] = ALPHABET[Number(num % BASE)]\n num = num / BASE\n }\n\n return result.join('')\n}\n\n/**\n * Decode a 27-character Base62 string to a 20-byte KSUID.\n *\n * Algorithm: Convert Base62 string to BigInt, then to bytes.\n * V8 has highly optimized BigInt operations.\n */\nexport function decodeBase62(str: string): Uint8Array {\n if (str.length !== KSUID_STRING_LEN) {\n throw new Error(`KSUID string must be ${KSUID_STRING_LEN} characters, got ${str.length}`)\n }\n\n // Convert Base62 string to BigInt\n let num = 0n\n for (let i = 0; i < KSUID_STRING_LEN; i += 1) {\n const code = str.charCodeAt(i)\n if (code >= 128) {\n throw new Error(`Invalid KSUID character: ${str[i]}`)\n }\n const value = DECODING[code]\n if (value === 255) {\n throw new Error(`Invalid KSUID character: ${str[i]}`)\n }\n num = num * BASE + BigInt(value)\n }\n\n // Convert BigInt to bytes (big-endian)\n const bytes = new Uint8Array(KSUID_BYTES)\n for (let i = KSUID_BYTES - 1; i >= 0; i -= 1) {\n bytes[i] = Number(num & 0xffn)\n num = num >> 8n\n }\n\n return bytes\n}\n","import { rng } from '../uuid/common/random'\nimport { decodeBase62, encodeBase62 } from './common/base62'\n\n/**\n * KSUID (K-Sortable Unique Identifier)\n *\n * A 160-bit identifier consisting of:\n * - 4 bytes: timestamp (seconds since KSUID epoch: May 13, 2014)\n * - 16 bytes: cryptographically random payload\n *\n * Encoded as a 27-character Base62 string.\n */\n\n// KSUID epoch: May 13, 2014 00:00:00 UTC (Unix timestamp in seconds)\nconst KSUID_EPOCH = 1400000000\n\nconst KSUID_BYTES = 20\nconst KSUID_STRING_LEN = 27\nconst TIMESTAMP_BYTES = 4\nconst PAYLOAD_BYTES = 16\n\n// Validation regex: 27 alphanumeric characters (case-insensitive)\nconst KSUID_REGEX = /^[0-9A-Za-z]{27}$/\n\nexport type KsuidOptions = {\n /**\n * 16 bytes of random data to use for KSUID payload.\n */\n random?: Uint8Array\n /**\n * Timestamp in seconds since Unix epoch.\n * Defaults to Math.floor(Date.now() / 1000).\n * KSUID natively uses second precision.\n */\n secs?: number\n}\n\nexport type Ksuid = {\n (): string\n <TBuf extends Uint8Array = Uint8Array>(options: KsuidOptions | undefined, buf: TBuf, offset?: number): TBuf\n (options?: KsuidOptions, buf?: undefined, offset?: number): string\n toBytes(id: string): Uint8Array\n fromBytes(bytes: Uint8Array): string\n timestamp(id: string): number\n isValid(id: string): boolean\n}\n\ntype KsuidState = {\n secs: number\n lastPayload: Uint8Array\n}\n\n/**\n * Module-level state for maintaining monotonic ordering within the same second.\n *\n * IMPORTANT: This state persists across all ksuid() calls in the module's lifetime.\n * - In serverless/edge functions with warm starts, state persists between invocations.\n * - For isolated state, pass explicit `msecs` and `random` via options.\n * - Tests should mock Date.now() or provide explicit options for deterministic behavior.\n */\nconst state: KsuidState = {\n secs: -Infinity,\n lastPayload: new Uint8Array(PAYLOAD_BYTES),\n}\n\n/**\n * Increment a 16-byte array by 1, propagating carry from LSB to MSB.\n * Returns a new array (does not modify input).\n */\nfunction incrementPayload(bytes: Uint8Array): Uint8Array {\n const result = new Uint8Array(bytes)\n for (let i = result.length - 1; i >= 0; i -= 1) {\n if (result[i] < 255) {\n result[i] += 1\n return result\n }\n result[i] = 0\n }\n return result\n}\n\n/**\n * Write KSUID bytes to a buffer.\n */\nfunction ksuidBytes(secs: number, payload: Uint8Array, buf?: Uint8Array, offset = 0): Uint8Array {\n if (!buf) {\n buf = new Uint8Array(KSUID_BYTES)\n offset = 0\n } else if (offset < 0 || offset + KSUID_BYTES > buf.length) {\n throw new RangeError(`KSUID byte range ${offset}:${offset + KSUID_BYTES - 1} is out of buffer bounds`)\n }\n\n // Timestamp (32-bit big-endian seconds since KSUID epoch) -> bytes 0-3\n buf[offset] = (secs >>> 24) & 0xff\n buf[offset + 1] = (secs >>> 16) & 0xff\n buf[offset + 2] = (secs >>> 8) & 0xff\n buf[offset + 3] = secs & 0xff\n\n // Payload (128 bits) -> bytes 4-19\n for (let i = 0; i < PAYLOAD_BYTES; i += 1) {\n buf[offset + TIMESTAMP_BYTES + i] = payload[i]\n }\n\n return buf\n}\n\n/*\n * Overload: no buffer => return a KSUID string.\n */\nfunction ksuidFn(options?: KsuidOptions, buf?: undefined, offset?: number): string\n/*\n * Overload: caller provides a buffer slice to fill with KSUID bytes.\n */\nfunction ksuidFn<TBuf extends Uint8Array = Uint8Array>(\n options: KsuidOptions | undefined,\n buf: TBuf,\n offset?: number,\n): TBuf\nfunction ksuidFn<TBuf extends Uint8Array = Uint8Array>(options?: KsuidOptions, buf?: TBuf, offset = 0): string | TBuf {\n let secs: number\n let payload: Uint8Array\n\n /**\n * Note: by default, Cloudflare Workers \"freezes\" time during request handling to prevent\n * side-channel attacks. This means that Date.now() will return the same value for the entire\n * duration of a request.\n * Implications:\n * - all KSUIDs generated within a single request will have the same timestamp.\n * - the monotonic ordering will rely entirely on incrementing the payload portion.\n */\n const now = Date.now()\n const defaultSecs = Math.floor(now / 1000) - KSUID_EPOCH\n\n if (options) {\n // Explicit options provided - use them directly without monotonic state\n secs = options.secs !== undefined ? options.secs - KSUID_EPOCH : defaultSecs\n\n if (options.random) {\n payload = options.random\n } else {\n payload = rng()\n }\n } else {\n secs = defaultSecs\n\n if (secs > state.secs) {\n // New second: generate fresh random payload\n payload = rng()\n state.secs = secs\n state.lastPayload.set(payload.subarray(0, PAYLOAD_BYTES))\n } else {\n // Same second: increment payload for monotonic ordering\n payload = incrementPayload(state.lastPayload)\n state.lastPayload = payload\n }\n }\n\n if (buf) {\n ksuidBytes(secs, payload, buf, offset)\n return buf\n }\n\n // String mode: create bytes then encode to Base62\n const bytes = ksuidBytes(secs, payload)\n return encodeBase62(bytes)\n}\n\n/**\n * Convert a KSUID string to 20 bytes.\n * Case-insensitive: accepts uppercase, lowercase, or mixed case.\n */\nfunction toBytes(id: string): Uint8Array {\n return decodeBase62(id)\n}\n\n/**\n * Convert 20 bytes to a KSUID string.\n */\nfunction fromBytes(bytes: Uint8Array): string {\n return encodeBase62(bytes)\n}\n\n/**\n * Extract the timestamp from a KSUID string.\n * Returns Unix timestamp in milliseconds for API consistency with ulid/uuidv7.\n * Note: KSUID only has second precision, so the returned value will always end in 000.\n */\nfunction timestamp(id: string): number {\n const bytes = decodeBase62(id)\n // First 4 bytes are big-endian timestamp (seconds since KSUID epoch)\n const secs = ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0\n // Add KSUID epoch and convert to milliseconds\n return (secs + KSUID_EPOCH) * 1000\n}\n\n/**\n * Validate a KSUID string.\n * Case-insensitive: accepts uppercase, lowercase, or mixed case.\n */\nfunction isValid(id: string): boolean {\n return typeof id === 'string' && id.length === KSUID_STRING_LEN && KSUID_REGEX.test(id)\n}\n\n/**\n * Generate a KSUID string or write the bytes into a buffer.\n * Also includes helpers to convert to and from byte arrays.\n */\nexport const ksuid: Ksuid = Object.assign(ksuidFn, {\n toBytes,\n fromBytes,\n timestamp,\n isValid,\n})\n"],"mappings":"2CAYA,MAAM,EAAW,iEACX,EAAO,IAOP,EAAW,IAAI,WAAW,IAAI,CACpC,EAAS,KAAK,IAAI,CAElB,IAAK,IAAI,EAAI,EAAG,EAAI,GAAiB,GAAK,EACxC,EAAS,EAAS,WAAW,EAAE,EAAI,EASrC,SAAgB,EAAa,EAA2B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AAG,CAOzF,MAAaC,EAAe,OAAO,OAAO,EAAS,CACjD,UACA,YACA,YACA,UACD,CAAC"}
|
|
1
|
+
{"version":3,"file":"ksuid.mjs","names":["KSUID_BYTES","KSUID_STRING_LEN","timestamp","ksuid: Ksuid"],"sources":["../../src/ksuid/base62.ts","../../src/ksuid/ksuid.ts"],"sourcesContent":["/**\n * Note: once ES2025 is widely adopted, we can use the built-in `Uint8Array.prototype.toHex` method.\n */\n// import { toHex } from 'hextreme'\n\nimport { BufferError, ParseError } from '../errors'\n\n/**\n * Base62 encoding/decoding for KSUID.\n * Alphabet: 0-9A-Za-z (standard Base62 ordering)\n *\n * KSUID binary format: 20 bytes (160 bits)\n * - 4 bytes: timestamp (seconds since KSUID epoch)\n * - 16 bytes: payload (cryptographically random)\n *\n * String format: 27 characters of Base62\n */\n\n// Base62 alphabet: digits (0-9), uppercase (A-Z), lowercase (a-z)\nconst BASE62_ALPHABET = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'\nconst BASE = 62n\nconst KSUID_BYTES = 20\nconst KSUID_STRING_LEN = 27\n\n// Pre-computed decode table indexed by ASCII code (0-127)\n// Uses Uint8Array for cache-efficient lookups via charCodeAt\n// Note: Base62 is case-sensitive - 'A' (value 10) and 'a' (value 36) are different\nconst DECODING = new Uint8Array(128)\nDECODING.fill(255) // 255 = invalid marker\n\nfor (let i = 0; i < BASE62_ALPHABET.length; i += 1) {\n DECODING[BASE62_ALPHABET.charCodeAt(i)] = i\n}\n\n/**\n * Encode a 20-byte KSUID to a 27-character Base62 string.\n *\n * Algorithm: Convert the 160-bit number to base 62 using BigInt.\n * V8 has highly optimized BigInt operations for this size.\n */\nexport function encodeBase62(bytes: Uint8Array): string {\n if (bytes.length < KSUID_BYTES) {\n throw new BufferError(\n 'KSUID_BYTES_TOO_SHORT',\n `KSUID bytes must be at least ${KSUID_BYTES} bytes, got ${bytes.length}`,\n )\n }\n\n // Convert bytes to BigInt (big-endian)\n let num = 0n\n for (let i = 0; i < KSUID_BYTES; i += 1) {\n num = (num << 8n) | BigInt(bytes[i])\n }\n\n // Convert to Base62 string (build from right to left)\n // Direct string concatenation is faster than array + join in V8\n let encoded = ''\n while (num > 0n) {\n const remainder = num % BASE\n num = num / BASE\n encoded = BASE62_ALPHABET[Number(remainder)] + encoded\n }\n\n // Pad the result with the zero-character ('0') to ensure a fixed length\n return encoded.padStart(KSUID_STRING_LEN, '0')\n}\n\n/**\n * Decode a 27-character Base62 string to a 20-byte KSUID.\n *\n * Algorithm: Convert Base62 string to BigInt, then to bytes.\n * V8 has highly optimized BigInt operations.\n */\nexport function decodeBase62(str: string): Uint8Array {\n if (str.length !== KSUID_STRING_LEN) {\n throw new ParseError(\n 'KSUID_INVALID_LENGTH',\n `KSUID string must be ${KSUID_STRING_LEN} characters, got ${str.length}`,\n )\n }\n\n // Convert Base62 string to BigInt\n let num = 0n\n for (let i = 0; i < KSUID_STRING_LEN; i += 1) {\n const code = str.charCodeAt(i)\n if (code >= 128) {\n throw new ParseError('KSUID_INVALID_CHAR', `Invalid KSUID character: ${str[i]}`)\n }\n const value = DECODING[code]\n if (value === 255) {\n throw new ParseError('KSUID_INVALID_CHAR', `Invalid KSUID character: ${str[i]}`)\n }\n num = num * BASE + BigInt(value)\n }\n\n // Convert BigInt to bytes (big-endian)\n const bytes = new Uint8Array(KSUID_BYTES)\n for (let i = KSUID_BYTES - 1; i >= 0; i -= 1) {\n bytes[i] = Number(num & 0xffn)\n num = num >> 8n\n }\n\n return bytes\n}\n","import { writeTimestamp32 } from '../common/bytes'\nimport { rng } from '../common/random'\nimport { BufferError, InvalidInputError } from '../errors'\nimport { decodeBase62, encodeBase62 } from './base62'\n\n/**\n * KSUID (K-Sortable Unique Identifier)\n *\n * A 160-bit identifier consisting of:\n * - 4 bytes: timestamp (seconds since KSUID epoch: May 13, 2014)\n * - 16 bytes: cryptographically random payload\n *\n * Encoded as a 27-character Base62 string.\n */\n\n// KSUID epoch: May 13, 2014 00:00:00 UTC (Unix timestamp in seconds)\nconst KSUID_EPOCH = 1400000000\n\nconst KSUID_BYTES = 20\nconst KSUID_STRING_LEN = 27\nconst TIMESTAMP_BYTES = 4\nconst PAYLOAD_BYTES = 16\n\n// Validation regex: 27 alphanumeric characters\n// Note: Both cases are valid Base62 characters, but they decode to different values\n// (e.g., 'A' = 10, 'a' = 36). The regex validates format, not semantic equivalence.\nconst KSUID_REGEX = /^[0-9A-Za-z]{27}$/\n\nexport type KsuidOptions = {\n /**\n * 16 bytes of random data to use for KSUID payload.\n */\n random?: Uint8Array\n /**\n * Timestamp in seconds since Unix epoch.\n * Defaults to Math.floor(Date.now() / 1000).\n * KSUID natively uses second precision.\n */\n secs?: number\n}\n\nexport type Ksuid = {\n (): string\n <TBuf extends Uint8Array = Uint8Array>(options: KsuidOptions | undefined, buf: TBuf, offset?: number): TBuf\n (options?: KsuidOptions, buf?: undefined, offset?: number): string\n toBytes(id: string): Uint8Array\n fromBytes(bytes: Uint8Array): string\n timestamp(id: string): number\n isValid(id: unknown): id is string\n /** The nil KSUID (all zeros) */\n NIL: string\n /** The max KSUID (maximum valid value) */\n MAX: string\n}\n\n/**\n * Write KSUID bytes to a buffer.\n */\nfunction ksuidBytes(timestamp: number, payload: Uint8Array, buf?: Uint8Array, offset = 0): Uint8Array {\n if (!buf) {\n buf = new Uint8Array(KSUID_BYTES)\n offset = 0\n } else if (offset < 0 || offset + KSUID_BYTES > buf.length) {\n throw new BufferError(\n 'KSUID_BUFFER_OUT_OF_BOUNDS',\n `KSUID byte range ${offset}:${offset + KSUID_BYTES - 1} is out of buffer bounds`,\n )\n }\n\n // Timestamp (32-bit big-endian seconds since KSUID epoch) -> bytes 0-3\n writeTimestamp32(buf, offset, timestamp)\n\n // Payload (128 bits) -> bytes 4-19\n // copy from payload[TIMESTAMP_BYTES] into buf\n buf.set(payload.subarray(TIMESTAMP_BYTES, TIMESTAMP_BYTES + PAYLOAD_BYTES), offset + TIMESTAMP_BYTES)\n for (let i = 0; i < PAYLOAD_BYTES; i += 1) {\n buf[offset + TIMESTAMP_BYTES + i] = payload[i]\n }\n\n return buf\n}\n\n/*\n * Overload: no buffer => return a KSUID string.\n */\nfunction ksuidFn(options?: KsuidOptions, buf?: undefined, offset?: number): string\n/*\n * Overload: caller provides a buffer slice to fill with KSUID bytes.\n */\nfunction ksuidFn<TBuf extends Uint8Array = Uint8Array>(\n options: KsuidOptions | undefined,\n buf: TBuf,\n offset?: number,\n): TBuf\nfunction ksuidFn<TBuf extends Uint8Array = Uint8Array>(options?: KsuidOptions, buf?: TBuf, offset = 0): string | TBuf {\n if (options) {\n if (options.random && options.random.length < PAYLOAD_BYTES) {\n throw new InvalidInputError('KSUID_RANDOM_BYTES_TOO_SHORT', 'Random bytes length must be >= 16 for KSUID')\n }\n\n if (options.secs && options.secs < KSUID_EPOCH) {\n throw new InvalidInputError('KSUID_TIMESTAMP_TOO_LOW', 'Timestamp must be >= KSUID epoch')\n }\n\n if (options.secs) {\n options.secs = options.secs - KSUID_EPOCH\n }\n }\n\n /**\n * Note: by default, Cloudflare Workers \"freezes\" time during request handling to prevent\n * side-channel attacks. This means that Date.now() will return the same value for the entire\n * duration of a request.\n * Implications:\n * - all KSUIDs generated within a single request will have the same timestamp.\n */\n const timestamp = options?.secs ?? Math.floor(Date.now() / 1000 - KSUID_EPOCH)\n const payload = options?.random ?? rng()\n\n if (buf) {\n ksuidBytes(timestamp, payload, buf, offset)\n return buf\n }\n\n const bytes = ksuidBytes(timestamp, payload)\n\n // String mode: create bytes then encode to Base62\n return encodeBase62(bytes)\n}\n\n/**\n * Convert a KSUID string to 20 bytes.\n *\n * Note: Base62 is case-sensitive. 'A' (value 10) and 'a' (value 36) decode\n * to different byte values. This function accepts both cases as valid input.\n */\nfunction toBytes(id: string): Uint8Array {\n return decodeBase62(id)\n}\n\n/**\n * Convert 20 bytes to a KSUID string.\n */\nfunction fromBytes(bytes: Uint8Array): string {\n return encodeBase62(bytes)\n}\n\n/**\n * Extract the timestamp from a KSUID string.\n * Returns Unix timestamp in milliseconds for API consistency with ulid/uuidv7.\n * Note: KSUID only has second precision, so the returned value will always end in 000.\n */\nfunction timestamp(id: string): number {\n const bytes = decodeBase62(id)\n // First 4 bytes are big-endian timestamp (seconds since KSUID epoch)\n const secs = ((bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3]) >>> 0\n // Add KSUID epoch and convert to milliseconds\n return (secs + KSUID_EPOCH) * 1000\n}\n\n/**\n * Validate a KSUID string format.\n *\n * Note: Both uppercase and lowercase letters are valid Base62 characters,\n * but they represent different values (e.g., 'A' = 10, 'a' = 36).\n */\nfunction isValid(id: unknown): id is string {\n return typeof id === 'string' && id.length === KSUID_STRING_LEN && KSUID_REGEX.test(id)\n}\n\n/**\n * Generate a KSUID string or write the bytes into a buffer.\n * Also includes helpers to convert to and from byte arrays.\n */\nexport const ksuid: Ksuid = Object.assign(ksuidFn, {\n toBytes,\n fromBytes,\n timestamp,\n isValid,\n NIL: '000000000000000000000000000',\n MAX: 'aWgEPTl1tmebfsQzFP4bxwgy80V',\n})\n\nexport { BufferError, InvalidInputError, ParseError, UniqueIdError } from '../errors'\n"],"mappings":"2LAmBA,MAAM,EAAkB,iEAClB,EAAO,IAOP,EAAW,IAAI,WAAW,IAAI,CACpC,EAAS,KAAK,IAAI,CAElB,IAAK,IAAI,EAAI,EAAG,EAAI,GAAwB,GAAK,EAC/C,EAAS,EAAgB,WAAW,EAAE,EAAI,EAS5C,SAAgB,EAAa,EAA2B,CACtD,GAAI,EAAM,OAASA,GACjB,MAAM,IAAI,EACR,wBACA,8CAA0D,EAAM,SACjE,CAIH,IAAI,EAAM,GACV,IAAK,IAAI,EAAI,EAAG,EAAIA,GAAa,GAAK,EACpC,EAAO,GAAO,GAAM,OAAO,EAAM,GAAG,CAKtC,IAAI,EAAU,GACd,KAAO,EAAM,IAAI,CACf,IAAM,EAAY,EAAM,EACxB,GAAY,EACZ,EAAU,EAAgB,OAAO,EAAU,EAAI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,EAAQ,KAAO,EACjC,MAAM,IAAI,EAAkB,0BAA2B,mCAAmC,CAGxF,EAAQ,OACV,EAAQ,MAAsB,GAWlC,IAAMA,EAAY,GAAS,MAAQ,KAAK,MAAM,KAAK,KAAK,CAAG,IAAO,EAAY,CACxE,EAAU,GAAS,QAAU,GAAK,CAUxC,OARI,GACF,EAAWA,EAAW,EAAS,EAAK,EAAO,CACpC,GAMF,EAHO,EAAWA,EAAW,EAAQ,CAGlB,CAS5B,SAAS,EAAQ,EAAwB,CACvC,OAAO,EAAa,EAAG,CAMzB,SAAS,EAAU,EAA2B,CAC5C,OAAO,EAAa,EAAM,CAQ5B,SAAS,EAAU,EAAoB,CACrC,IAAM,EAAQ,EAAa,EAAG,CAI9B,SAFe,EAAM,IAAM,GAAO,EAAM,IAAM,GAAO,EAAM,IAAM,EAAK,EAAM,MAAQ,GAErE,GAAe,IAShC,SAAS,EAAQ,EAA2B,CAC1C,OAAO,OAAO,GAAO,UAAY,EAAG,SAAW,IAAoB,EAAY,KAAK,EAAG,CAOzF,MAAaC,EAAe,OAAO,OAAO,EAAS,CACjD,UACA,YACA,YACA,UACA,IAAK,8BACL,IAAK,8BACN,CAAC"}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { InvalidInputError, UniqueIdError } from "../errors.mjs";
|
|
2
|
+
|
|
1
3
|
//#region src/nanoid/nanoid.d.ts
|
|
2
4
|
/** Default URL-safe alphabet (64 characters): A-Z, a-z, 0-9, underscore, hyphen */
|
|
3
5
|
declare const URL_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-";
|
|
@@ -33,8 +35,51 @@ type Nanoid = {
|
|
|
33
35
|
};
|
|
34
36
|
/**
|
|
35
37
|
* Generate a URL-friendly unique string ID.
|
|
38
|
+
*
|
|
39
|
+
* Nanoid is a tiny, secure, URL-friendly unique string ID generator.
|
|
40
|
+
* It uses a URL-safe alphabet (A-Za-z0-9_-) and generates 21-character
|
|
41
|
+
* IDs by default with 126 bits of entropy.
|
|
42
|
+
*
|
|
43
|
+
* Unlike UUID v7 or ULID, nanoid is NOT time-ordered. Use it for:
|
|
44
|
+
* - URL shorteners
|
|
45
|
+
* - Session tokens
|
|
46
|
+
* - Invite codes
|
|
47
|
+
* - Any case where you need short, random IDs
|
|
48
|
+
*
|
|
49
|
+
* @example Basic usage
|
|
50
|
+
* ```ts
|
|
51
|
+
* import { nanoid } from 'uniku/nanoid'
|
|
52
|
+
*
|
|
53
|
+
* const id = nanoid()
|
|
54
|
+
* // => "V1StGXR8_Z5jdHi6B-myT"
|
|
55
|
+
* ```
|
|
56
|
+
*
|
|
57
|
+
* @example Custom size
|
|
58
|
+
* ```ts
|
|
59
|
+
* const shortId = nanoid(10)
|
|
60
|
+
* // => "IRFa-VaY2b"
|
|
61
|
+
* ```
|
|
62
|
+
*
|
|
63
|
+
* @example Custom alphabet (hex)
|
|
64
|
+
* ```ts
|
|
65
|
+
* const hexId = nanoid({ alphabet: '0123456789abcdef', size: 12 })
|
|
66
|
+
* // => "4f90d13a42bc"
|
|
67
|
+
* ```
|
|
68
|
+
*
|
|
69
|
+
* @example Validation
|
|
70
|
+
* ```ts
|
|
71
|
+
* const maybeId: unknown = getUserInput()
|
|
72
|
+
* if (nanoid.isValid(maybeId)) {
|
|
73
|
+
* // TypeScript knows maybeId is string
|
|
74
|
+
* console.log(maybeId.length)
|
|
75
|
+
* }
|
|
76
|
+
* ```
|
|
77
|
+
*
|
|
78
|
+
* @throws {InvalidInputError} Size must be between 0 and 2048
|
|
79
|
+
* @throws {InvalidInputError} Alphabet must contain 2-256 unique printable ASCII characters
|
|
80
|
+
* @throws {InvalidInputError} Insufficient random bytes for requested size
|
|
36
81
|
*/
|
|
37
82
|
declare const nanoid: Nanoid;
|
|
38
83
|
//#endregion
|
|
39
|
-
export { Nanoid, NanoidOptions, URL_ALPHABET, nanoid };
|
|
84
|
+
export { InvalidInputError, Nanoid, NanoidOptions, URL_ALPHABET, UniqueIdError, nanoid };
|
|
40
85
|
//# sourceMappingURL=nanoid.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nanoid.d.mts","names":["nanoid: Nanoid"],"sources":["../../src/nanoid/nanoid.ts"],"sourcesContent":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"nanoid.d.mts","names":["nanoid: Nanoid"],"sources":["../../src/nanoid/nanoid.ts"],"sourcesContent":[],"mappings":";;;;cAGa,YAAA;KAwBD,aAAA;EAxBZ;AAwBA;AAkBA;AAqMA;;WAjNW;;;;;;;;;;;KAYC,MAAA;;;;;;YAMA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cA+LCA,QAAQ"}
|
package/build/nanoid/nanoid.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const
|
|
1
|
+
import{InvalidInputError as e,UniqueIdError as t}from"../errors.mjs";const n=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-`,r=2048,i=/^[A-Za-z0-9_-]+$/;let a,o=0;function s(e){let t=e*128;!a||a.length<t?(a=new Uint8Array(t),crypto.getRandomValues(a),o=0):o+e>a.length&&(crypto.getRandomValues(a),o=0),o+=e}function c(t){if(t.length<2)throw new e(`NANOID_ALPHABET_TOO_SHORT`,`Alphabet must contain at least 2 characters`);if(t.length>256)throw new e(`NANOID_ALPHABET_TOO_LONG`,`Alphabet must not exceed 256 characters`);let n=new Set;for(let r of t){let t=r.charCodeAt(0);if(t<32||t>126)throw new e(`NANOID_ALPHABET_INVALID_CHAR`,`Alphabet must contain only printable ASCII characters (32-126)`);if(n.has(r))throw new e(`NANOID_ALPHABET_DUPLICATE`,`Duplicate character in alphabet: "${r}"`);n.add(r)}}function l(t){if(!Number.isInteger(t)||t<0)throw new e(`NANOID_SIZE_INVALID`,`Size must be a non-negative integer`);if(t>r)throw new e(`NANOID_SIZE_TOO_LARGE`,`Size must not exceed ${r}`)}function u(t){if(t===void 0){s(21);let e=``;for(let t=o-21;t<o;t++)e+=n[a[t]&63];return e}let r=21,i=n,u;if(typeof t==`number`?r=t:(r=t.size??21,i=t.alphabet??n,u=t.random,t.alphabet!==void 0&&c(i)),l(r),r===0)return``;let d=i.length;if(!(d&d-1)){let t=d-1;if(u&&u.length<r)throw new e(`NANOID_RANDOM_BYTES_INSUFFICIENT`,`Insufficient random bytes: need ${r}, have ${u.length}`);let n=u?.subarray(0,r)??globalThis.crypto.getRandomValues(new Uint8Array(r)),a=``;for(let e=0;e<r;e++)a+=i[n[e]&t];return a}let f=(2<<31-Math.clz32(d-1|1))-1,p=Math.ceil(1.6*f*r/d),m=``,h=0;for(;m.length<r;){let t;if(u){if(u.length-h<p)throw new e(`NANOID_RANDOM_BYTES_INSUFFICIENT`,`Insufficient random bytes: need at least ${p} more, have ${u.length-h}`);t=u.subarray(h,h+p),h+=p}else t=globalThis.crypto.getRandomValues(new Uint8Array(p));for(let e=0;e<t.length&&m.length<r;e++){let n=t[e]&f;n<d&&(m+=i[n])}}return m}function d(e){return typeof e==`string`&&e.length>0&&i.test(e)}const f=Object.assign(u,{isValid:d});export{e as InvalidInputError,n as URL_ALPHABET,t as UniqueIdError,f as nanoid};
|
|
2
2
|
//# sourceMappingURL=nanoid.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nanoid.mjs","names":["pool: Uint8Array | undefined","id","randomBytes: Uint8Array | undefined","mask","bytes: Uint8Array","nanoid: Nanoid"],"sources":["../../src/nanoid/nanoid.ts"],"sourcesContent":["/** Default URL-safe alphabet (64 characters): A-Z, a-z, 0-9, underscore, hyphen */\nexport const URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'\n\nconst DEFAULT_SIZE = 21\nconst MAX_SIZE = 2048\nconst NANOID_REGEX = /^[A-Za-z0-9_-]+$/\n\n// Simple random pool for ultra-fast path (npm nanoid style - no thread-safety overhead)\nconst POOL_SIZE_MULTIPLIER = 128\nlet pool: Uint8Array | undefined\nlet poolOffset = 0\n\nfunction fillPool(bytes: number): void {\n const size = bytes * POOL_SIZE_MULTIPLIER\n if (!pool || pool.length < size) {\n pool = new Uint8Array(size)\n crypto.getRandomValues(pool)\n poolOffset = 0\n } else if (poolOffset + bytes > pool.length) {\n crypto.getRandomValues(pool)\n poolOffset = 0\n }\n poolOffset += bytes\n}\n\nexport type NanoidOptions = {\n /**\n * Random bytes for deterministic output (testing).\n * For power-of-2 alphabets (2, 4, 8, 16, 32, 64, 128, 256): exactly `size` bytes needed.\n * For other alphabets: ~size * 2 bytes needed (rejection sampling).\n */\n random?: Uint8Array\n /**\n * Custom alphabet to use. Default: URL-safe A-Za-z0-9_-\n * Must be 2-256 printable ASCII characters (32-126) with no duplicates.\n */\n alphabet?: string\n /**\n * Length of generated ID. Default: 21. Maximum: 2048.\n */\n size?: number\n}\n\nexport type Nanoid = {\n /** Generate nanoid with default settings */\n (): string\n /** Generate nanoid with custom size */\n (size: number): string\n /** Generate nanoid with options */\n (options: NanoidOptions): string\n /**\n * Validate a nanoid string against the default URL-safe alphabet.\n * Note: Does not validate IDs generated with custom alphabets.\n */\n isValid(id: unknown): id is string\n}\n\n/**\n * Validate alphabet: 2-256 printable ASCII chars, no duplicates\n */\nfunction validateAlphabet(alphabet: string): void {\n if (alphabet.length < 2) {\n throw new Error('Alphabet must contain at least 2 characters')\n }\n if (alphabet.length > 256) {\n throw new Error('Alphabet must not exceed 256 characters')\n }\n const seen = new Set<string>()\n for (const char of alphabet) {\n const code = char.charCodeAt(0)\n if (code < 32 || code > 126) {\n throw new Error('Alphabet must contain only printable ASCII characters (32-126)')\n }\n if (seen.has(char)) {\n throw new Error(`Duplicate character in alphabet: \"${char}\"`)\n }\n seen.add(char)\n }\n}\n\n/**\n * Validate size parameter\n */\nfunction validateSize(size: number): void {\n if (!Number.isInteger(size) || size < 0) {\n throw new RangeError('Size must be a non-negative integer')\n }\n if (size > MAX_SIZE) {\n throw new RangeError(`Size must not exceed ${MAX_SIZE}`)\n }\n}\n\n// Overloads\nfunction nanoidFn(): string\nfunction nanoidFn(size: number): string\nfunction nanoidFn(options: NanoidOptions): string\nfunction nanoidFn(sizeOrOptions?: number | NanoidOptions): string {\n // ULTRA-FAST PATH: No arguments = default nanoid\n // Uses simple pooled random bytes (npm nanoid style) for best performance\n if (sizeOrOptions === undefined) {\n fillPool(DEFAULT_SIZE)\n let id = ''\n for (let i = poolOffset - DEFAULT_SIZE; i < poolOffset; i++) {\n id += URL_ALPHABET[pool![i] & 63]\n }\n return id\n }\n\n let size = DEFAULT_SIZE\n let alphabet = URL_ALPHABET\n let randomBytes: Uint8Array | undefined\n\n if (typeof sizeOrOptions === 'number') {\n size = sizeOrOptions\n } else {\n size = sizeOrOptions.size ?? DEFAULT_SIZE\n alphabet = sizeOrOptions.alphabet ?? URL_ALPHABET\n randomBytes = sizeOrOptions.random\n if (sizeOrOptions.alphabet !== undefined) {\n validateAlphabet(alphabet)\n }\n }\n\n validateSize(size)\n\n if (size === 0) return ''\n\n const alphabetLen = alphabet.length\n\n // FAST PATH: Power-of-2 alphabet (includes default 64-char)\n // No rejection needed - each byte maps directly to a character\n if ((alphabetLen & (alphabetLen - 1)) === 0) {\n const mask = alphabetLen - 1\n if (randomBytes && randomBytes.length < size) {\n throw new Error(`Insufficient random bytes: need ${size}, have ${randomBytes.length}`)\n }\n const bytes = randomBytes?.subarray(0, size) ?? globalThis.crypto.getRandomValues(new Uint8Array(size))\n let id = ''\n for (let i = 0; i < size; i++) {\n id += alphabet[bytes[i] & mask]\n }\n return id\n }\n\n // SLOW PATH: Rejection sampling for non-power-of-2 alphabets\n // Calculate mask: smallest power-of-2 minus 1 that covers alphabet size\n const mask = (2 << (31 - Math.clz32((alphabetLen - 1) | 1))) - 1\n // Calculate step: random bytes per batch (1.6x accounts for rejection)\n const step = Math.ceil((1.6 * mask * size) / alphabetLen)\n\n let id = ''\n let randomOffset = 0\n\n while (id.length < size) {\n let bytes: Uint8Array\n if (randomBytes) {\n if (randomBytes.length - randomOffset < step) {\n throw new Error(\n `Insufficient random bytes: need at least ${step} more, have ${randomBytes.length - randomOffset}`,\n )\n }\n bytes = randomBytes.subarray(randomOffset, randomOffset + step)\n randomOffset += step\n } else {\n bytes = globalThis.crypto.getRandomValues(new Uint8Array(step))\n }\n\n for (let i = 0; i < bytes.length && id.length < size; i++) {\n const index = bytes[i] & mask\n if (index < alphabetLen) {\n id += alphabet[index]\n }\n // Otherwise reject and continue (no modulo bias)\n }\n }\n\n return id\n}\n\n/**\n * Validate a nanoid string against the default URL-safe alphabet.\n * Note: Does not validate IDs generated with custom alphabets.\n */\nfunction isValid(id: unknown): id is string {\n return typeof id === 'string' && id.length > 0 && NANOID_REGEX.test(id)\n}\n\n/**\n * Generate a URL-friendly unique string ID.\n */\nexport const nanoid: Nanoid = Object.assign(nanoidFn, {\n isValid,\n})\n"],"mappings":"AACA,MAAa,EAAe,mEAGtB,EAAW,KACX,EAAe,mBAIrB,IAAIA,EACA,EAAa,EAEjB,SAAS,EAAS,EAAqB,CACrC,IAAM,EAAO,EAAQ,IACjB,CAAC,GAAQ,EAAK,OAAS,GACzB,EAAO,IAAI,WAAW,EAAK,CAC3B,OAAO,gBAAgB,EAAK,CAC5B,EAAa,GACJ,EAAa,EAAQ,EAAK,SACnC,OAAO,gBAAgB,EAAK,CAC5B,EAAa,GAEf,GAAc,EAsChB,SAAS,EAAiB,EAAwB,CAChD,GAAI,EAAS,OAAS,EACpB,MAAU,MAAM,8CAA8C,CAEhE,GAAI,EAAS,OAAS,IACpB,MAAU,MAAM,0CAA0C,CAE5D,IAAM,EAAO,IAAI,IACjB,IAAK,IAAM,KAAQ,EAAU,CAC3B,IAAM,EAAO,EAAK,WAAW,EAAE,CAC/B,GAAI,EAAO,IAAM,EAAO,IACtB,MAAU,MAAM,iEAAiE,CAEnF,GAAI,EAAK,IAAI,EAAK,CAChB,MAAU,MAAM,qCAAqC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,EAAK,cAAc,EAAY,OAAS,IACrF,CAEH,EAAQ,EAAY,SAAS,EAAc,EAAe,EAAK,CAC/D,GAAgB,OAEhB,EAAQ,WAAW,OAAO,gBAAgB,IAAI,WAAW,EAAK,CAAC,CAGjE,IAAK,IAAI,EAAI,EAAG,EAAI,EAAM,QAAU,EAAG,OAAS,EAAM,IAAK,CACzD,IAAM,EAAQ,EAAM,GAAK,EACrB,EAAQ,IACV,GAAM,EAAS,KAMrB,OAAO,EAOT,SAAS,EAAQ,EAA2B,CAC1C,OAAO,OAAO,GAAO,UAAY,EAAG,OAAS,GAAK,EAAa,KAAK,EAAG,CAMzE,MAAaC,EAAiB,OAAO,OAAO,EAAU,CACpD,UACD,CAAC"}
|
|
1
|
+
{"version":3,"file":"nanoid.mjs","names":["pool: Uint8Array | undefined","id","randomBytes: Uint8Array | undefined","mask","bytes: Uint8Array","nanoid: Nanoid"],"sources":["../../src/nanoid/nanoid.ts"],"sourcesContent":["import { InvalidInputError } from '../errors'\n\n/** Default URL-safe alphabet (64 characters): A-Z, a-z, 0-9, underscore, hyphen */\nexport const URL_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'\n\nconst DEFAULT_SIZE = 21\nconst MAX_SIZE = 2048\nconst NANOID_REGEX = /^[A-Za-z0-9_-]+$/\n\n// Simple random pool for ultra-fast path (npm nanoid style - no thread-safety overhead)\nconst POOL_SIZE_MULTIPLIER = 128\nlet pool: Uint8Array | undefined\nlet poolOffset = 0\n\nfunction fillPool(bytes: number): void {\n const size = bytes * POOL_SIZE_MULTIPLIER\n if (!pool || pool.length < size) {\n pool = new Uint8Array(size)\n crypto.getRandomValues(pool)\n poolOffset = 0\n } else if (poolOffset + bytes > pool.length) {\n crypto.getRandomValues(pool)\n poolOffset = 0\n }\n poolOffset += bytes\n}\n\nexport type NanoidOptions = {\n /**\n * Random bytes for deterministic output (testing).\n * For power-of-2 alphabets (2, 4, 8, 16, 32, 64, 128, 256): exactly `size` bytes needed.\n * For other alphabets: ~size * 2 bytes needed (rejection sampling).\n */\n random?: Uint8Array\n /**\n * Custom alphabet to use. Default: URL-safe A-Za-z0-9_-\n * Must be 2-256 printable ASCII characters (32-126) with no duplicates.\n */\n alphabet?: string\n /**\n * Length of generated ID. Default: 21. Maximum: 2048.\n */\n size?: number\n}\n\nexport type Nanoid = {\n /** Generate nanoid with default settings */\n (): string\n /** Generate nanoid with custom size */\n (size: number): string\n /** Generate nanoid with options */\n (options: NanoidOptions): string\n /**\n * Validate a nanoid string against the default URL-safe alphabet.\n * Note: Does not validate IDs generated with custom alphabets.\n */\n isValid(id: unknown): id is string\n}\n\n/**\n * Validate alphabet: 2-256 printable ASCII chars, no duplicates\n */\nfunction validateAlphabet(alphabet: string): void {\n if (alphabet.length < 2) {\n throw new InvalidInputError('NANOID_ALPHABET_TOO_SHORT', 'Alphabet must contain at least 2 characters')\n }\n if (alphabet.length > 256) {\n throw new InvalidInputError('NANOID_ALPHABET_TOO_LONG', 'Alphabet must not exceed 256 characters')\n }\n const seen = new Set<string>()\n for (const char of alphabet) {\n const code = char.charCodeAt(0)\n if (code < 32 || code > 126) {\n throw new InvalidInputError(\n 'NANOID_ALPHABET_INVALID_CHAR',\n 'Alphabet must contain only printable ASCII characters (32-126)',\n )\n }\n if (seen.has(char)) {\n throw new InvalidInputError('NANOID_ALPHABET_DUPLICATE', `Duplicate character in alphabet: \"${char}\"`)\n }\n seen.add(char)\n }\n}\n\n/**\n * Validate size parameter\n */\nfunction validateSize(size: number): void {\n if (!Number.isInteger(size) || size < 0) {\n throw new InvalidInputError('NANOID_SIZE_INVALID', 'Size must be a non-negative integer')\n }\n if (size > MAX_SIZE) {\n throw new InvalidInputError('NANOID_SIZE_TOO_LARGE', `Size must not exceed ${MAX_SIZE}`)\n }\n}\n\n// Overloads\nfunction nanoidFn(): string\nfunction nanoidFn(size: number): string\nfunction nanoidFn(options: NanoidOptions): string\nfunction nanoidFn(sizeOrOptions?: number | NanoidOptions): string {\n // ULTRA-FAST PATH: No arguments = default nanoid\n // Uses simple pooled random bytes (npm nanoid style) for best performance\n if (sizeOrOptions === undefined) {\n fillPool(DEFAULT_SIZE)\n let id = ''\n for (let i = poolOffset - DEFAULT_SIZE; i < poolOffset; i++) {\n id += URL_ALPHABET[pool![i] & 63]\n }\n return id\n }\n\n let size = DEFAULT_SIZE\n let alphabet = URL_ALPHABET\n let randomBytes: Uint8Array | undefined\n\n if (typeof sizeOrOptions === 'number') {\n size = sizeOrOptions\n } else {\n size = sizeOrOptions.size ?? DEFAULT_SIZE\n alphabet = sizeOrOptions.alphabet ?? URL_ALPHABET\n randomBytes = sizeOrOptions.random\n if (sizeOrOptions.alphabet !== undefined) {\n validateAlphabet(alphabet)\n }\n }\n\n validateSize(size)\n\n if (size === 0) return ''\n\n const alphabetLen = alphabet.length\n\n // FAST PATH: Power-of-2 alphabet (includes default 64-char)\n // No rejection needed - each byte maps directly to a character\n if ((alphabetLen & (alphabetLen - 1)) === 0) {\n const mask = alphabetLen - 1\n if (randomBytes && randomBytes.length < size) {\n throw new InvalidInputError(\n 'NANOID_RANDOM_BYTES_INSUFFICIENT',\n `Insufficient random bytes: need ${size}, have ${randomBytes.length}`,\n )\n }\n const bytes = randomBytes?.subarray(0, size) ?? globalThis.crypto.getRandomValues(new Uint8Array(size))\n let id = ''\n for (let i = 0; i < size; i++) {\n id += alphabet[bytes[i] & mask]\n }\n return id\n }\n\n // SLOW PATH: Rejection sampling for non-power-of-2 alphabets\n // Calculate mask: smallest power-of-2 minus 1 that covers alphabet size\n const mask = (2 << (31 - Math.clz32((alphabetLen - 1) | 1))) - 1\n // Calculate step: random bytes per batch (1.6x accounts for rejection)\n const step = Math.ceil((1.6 * mask * size) / alphabetLen)\n\n let id = ''\n let randomOffset = 0\n\n while (id.length < size) {\n let bytes: Uint8Array\n if (randomBytes) {\n if (randomBytes.length - randomOffset < step) {\n throw new InvalidInputError(\n 'NANOID_RANDOM_BYTES_INSUFFICIENT',\n `Insufficient random bytes: need at least ${step} more, have ${randomBytes.length - randomOffset}`,\n )\n }\n bytes = randomBytes.subarray(randomOffset, randomOffset + step)\n randomOffset += step\n } else {\n bytes = globalThis.crypto.getRandomValues(new Uint8Array(step))\n }\n\n for (let i = 0; i < bytes.length && id.length < size; i++) {\n const index = bytes[i] & mask\n if (index < alphabetLen) {\n id += alphabet[index]\n }\n // Otherwise reject and continue (no modulo bias)\n }\n }\n\n return id\n}\n\n/**\n * Validate a nanoid string against the default URL-safe alphabet.\n * Note: Does not validate IDs generated with custom alphabets.\n */\nfunction isValid(id: unknown): id is string {\n return typeof id === 'string' && id.length > 0 && NANOID_REGEX.test(id)\n}\n\n/**\n * Generate a URL-friendly unique string ID.\n *\n * Nanoid is a tiny, secure, URL-friendly unique string ID generator.\n * It uses a URL-safe alphabet (A-Za-z0-9_-) and generates 21-character\n * IDs by default with 126 bits of entropy.\n *\n * Unlike UUID v7 or ULID, nanoid is NOT time-ordered. Use it for:\n * - URL shorteners\n * - Session tokens\n * - Invite codes\n * - Any case where you need short, random IDs\n *\n * @example Basic usage\n * ```ts\n * import { nanoid } from 'uniku/nanoid'\n *\n * const id = nanoid()\n * // => \"V1StGXR8_Z5jdHi6B-myT\"\n * ```\n *\n * @example Custom size\n * ```ts\n * const shortId = nanoid(10)\n * // => \"IRFa-VaY2b\"\n * ```\n *\n * @example Custom alphabet (hex)\n * ```ts\n * const hexId = nanoid({ alphabet: '0123456789abcdef', size: 12 })\n * // => \"4f90d13a42bc\"\n * ```\n *\n * @example Validation\n * ```ts\n * const maybeId: unknown = getUserInput()\n * if (nanoid.isValid(maybeId)) {\n * // TypeScript knows maybeId is string\n * console.log(maybeId.length)\n * }\n * ```\n *\n * @throws {InvalidInputError} Size must be between 0 and 2048\n * @throws {InvalidInputError} Alphabet must contain 2-256 unique printable ASCII characters\n * @throws {InvalidInputError} Insufficient random bytes for requested size\n */\nexport const nanoid: Nanoid = Object.assign(nanoidFn, {\n isValid,\n})\n\nexport { In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