uniku 0.0.4 → 0.0.6

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.
@@ -1,192 +1,2 @@
1
- import { t as rng } from "../random-Dul5R6oJ.mjs";
2
-
3
- //#region src/ulid/common/crockford.ts
4
- const ENCODING = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
5
- const DECODING = new Uint8Array(128);
6
- DECODING.fill(255);
7
- for (let i = 0; i < 32; i += 1) {
8
- const upper = ENCODING.charCodeAt(i);
9
- const lower = ENCODING[i].toLowerCase().charCodeAt(0);
10
- DECODING[upper] = i;
11
- DECODING[lower] = i;
12
- }
13
- const TIME_LEN = 10;
14
- /**
15
- * Encode a 48-bit timestamp to a 10-character Crockford Base32 string.
16
- * Uses unrolled division for performance.
17
- */
18
- function encodeTime(time) {
19
- return ENCODING[Math.floor(time / 35184372088832) & 31] + ENCODING[Math.floor(time / 1099511627776) & 31] + ENCODING[Math.floor(time / 34359738368) & 31] + ENCODING[Math.floor(time / 1073741824) & 31] + ENCODING[Math.floor(time / 33554432) & 31] + ENCODING[Math.floor(time / 1048576) & 31] + ENCODING[Math.floor(time / 32768) & 31] + ENCODING[Math.floor(time / 1024) & 31] + ENCODING[Math.floor(time / 32) & 31] + ENCODING[time & 31];
20
- }
21
- /**
22
- * Encode 10 bytes (80 bits) of random data to a 16-character Crockford Base32 string.
23
- */
24
- function encodeRandom(bytes) {
25
- return ENCODING[bytes[0] >> 3 & 31] + ENCODING[(bytes[0] << 2 | bytes[1] >> 6) & 31] + ENCODING[bytes[1] >> 1 & 31] + ENCODING[(bytes[1] << 4 | bytes[2] >> 4) & 31] + ENCODING[(bytes[2] << 1 | bytes[3] >> 7) & 31] + ENCODING[bytes[3] >> 2 & 31] + ENCODING[(bytes[3] << 3 | bytes[4] >> 5) & 31] + ENCODING[bytes[4] & 31] + ENCODING[bytes[5] >> 3 & 31] + ENCODING[(bytes[5] << 2 | bytes[6] >> 6) & 31] + ENCODING[bytes[6] >> 1 & 31] + ENCODING[(bytes[6] << 4 | bytes[7] >> 4) & 31] + ENCODING[(bytes[7] << 1 | bytes[8] >> 7) & 31] + ENCODING[bytes[8] >> 2 & 31] + ENCODING[(bytes[8] << 3 | bytes[9] >> 5) & 31] + ENCODING[bytes[9] & 31];
26
- }
27
- /**
28
- * Decode the first 10 characters of a ULID string to a timestamp (Unix epoch milliseconds).
29
- */
30
- function decodeTime(str) {
31
- let time = 0;
32
- for (let i = 0; i < TIME_LEN; i += 1) {
33
- const value = DECODING[str.charCodeAt(i)];
34
- if (value === 255) throw new Error(`Invalid ULID character: ${str[i]}`);
35
- time = time * 32 + value;
36
- }
37
- return time;
38
- }
39
- /**
40
- * Decode a 26-character ULID string to 16 bytes.
41
- * Inlines all lookups to avoid intermediate array allocation.
42
- */
43
- function decodeToBytes(str) {
44
- if (str.length !== 26) throw new Error("ULID string must be 26 characters");
45
- const bytes = new Uint8Array(16);
46
- const v0 = DECODING[str.charCodeAt(0)];
47
- const v1 = DECODING[str.charCodeAt(1)];
48
- const v2 = DECODING[str.charCodeAt(2)];
49
- const v3 = DECODING[str.charCodeAt(3)];
50
- const v4 = DECODING[str.charCodeAt(4)];
51
- const v5 = DECODING[str.charCodeAt(5)];
52
- const v6 = DECODING[str.charCodeAt(6)];
53
- const v7 = DECODING[str.charCodeAt(7)];
54
- const v8 = DECODING[str.charCodeAt(8)];
55
- const v9 = DECODING[str.charCodeAt(9)];
56
- const v10 = DECODING[str.charCodeAt(10)];
57
- const v11 = DECODING[str.charCodeAt(11)];
58
- const v12 = DECODING[str.charCodeAt(12)];
59
- const v13 = DECODING[str.charCodeAt(13)];
60
- const v14 = DECODING[str.charCodeAt(14)];
61
- const v15 = DECODING[str.charCodeAt(15)];
62
- const v16 = DECODING[str.charCodeAt(16)];
63
- const v17 = DECODING[str.charCodeAt(17)];
64
- const v18 = DECODING[str.charCodeAt(18)];
65
- const v19 = DECODING[str.charCodeAt(19)];
66
- const v20 = DECODING[str.charCodeAt(20)];
67
- const v21 = DECODING[str.charCodeAt(21)];
68
- const v22 = DECODING[str.charCodeAt(22)];
69
- const v23 = DECODING[str.charCodeAt(23)];
70
- const v24 = DECODING[str.charCodeAt(24)];
71
- const v25 = DECODING[str.charCodeAt(25)];
72
- if ((v0 | v1 | v2 | v3 | v4 | v5 | v6 | v7 | v8 | v9 | v10 | v11 | v12 | v13 | v14 | v15 | v16 | v17 | v18 | v19 | v20 | v21 | v22 | v23 | v24 | v25) & 128) {
73
- for (let i = 0; i < 26; i += 1) if (DECODING[str.charCodeAt(i)] === 255) throw new Error(`Invalid ULID character: ${str[i]}`);
74
- }
75
- bytes[0] = v0 << 5 | v1;
76
- bytes[1] = v2 << 3 | v3 >> 2;
77
- bytes[2] = v3 << 6 | v4 << 1 | v5 >> 4;
78
- bytes[3] = v5 << 4 | v6 >> 1;
79
- bytes[4] = v6 << 7 | v7 << 2 | v8 >> 3;
80
- bytes[5] = v8 << 5 | v9;
81
- bytes[6] = v10 << 3 | v11 >> 2;
82
- bytes[7] = v11 << 6 | v12 << 1 | v13 >> 4;
83
- bytes[8] = v13 << 4 | v14 >> 1;
84
- bytes[9] = v14 << 7 | v15 << 2 | v16 >> 3;
85
- bytes[10] = v16 << 5 | v17;
86
- bytes[11] = v18 << 3 | v19 >> 2;
87
- bytes[12] = v19 << 6 | v20 << 1 | v21 >> 4;
88
- bytes[13] = v21 << 4 | v22 >> 1;
89
- bytes[14] = v22 << 7 | v23 << 2 | v24 >> 3;
90
- bytes[15] = v24 << 5 | v25;
91
- return bytes;
92
- }
93
- /**
94
- * Encode 16 bytes to a 26-character ULID string.
95
- */
96
- function bytesToUlid(bytes) {
97
- if (bytes.length < 16) throw new Error("Byte array must be at least 16 bytes");
98
- let time = 0;
99
- for (let i = 0; i < 6; i += 1) time = time * 256 + bytes[i];
100
- return encodeTime(time) + encodeRandom(bytes.subarray(6, 16));
101
- }
102
-
103
- //#endregion
104
- //#region src/ulid/ulid.ts
105
- const ULID_REGEX = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i;
106
- /**
107
- * Module-level state for maintaining monotonic ordering within the same millisecond.
108
- *
109
- * IMPORTANT: This state persists across all ulid() calls in the module's lifetime.
110
- * - In serverless/edge functions with warm starts, state persists between invocations.
111
- * - For isolated state, pass explicit `msecs` and `random` via options.
112
- * - Tests should mock Date.now() or provide explicit options for deterministic behavior.
113
- */
114
- const state = {
115
- msecs: -Infinity,
116
- lastRandom: new Uint8Array(10)
117
- };
118
- /**
119
- * Increment a byte array by 1, propagating carry from LSB to MSB.
120
- * Returns a new array (does not modify input).
121
- */
122
- function incrementBytes(bytes) {
123
- const result = new Uint8Array(bytes);
124
- for (let i = result.length - 1; i >= 0; i -= 1) {
125
- if (result[i] < 255) {
126
- result[i] += 1;
127
- return result;
128
- }
129
- result[i] = 0;
130
- }
131
- return result;
132
- }
133
- function ulidBytes(time, random, buf, offset = 0) {
134
- if (!buf) {
135
- buf = new Uint8Array(16);
136
- offset = 0;
137
- } else if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`ULID byte range ${offset}:${offset + 15} is out of buffer bounds`);
138
- buf[offset] = time / 1099511627776 & 255;
139
- buf[offset + 1] = time / 4294967296 & 255;
140
- buf[offset + 2] = time / 16777216 & 255;
141
- buf[offset + 3] = time / 65536 & 255;
142
- buf[offset + 4] = time / 256 & 255;
143
- buf[offset + 5] = time & 255;
144
- for (let i = 0; i < 10; i += 1) buf[offset + 6 + i] = random[i];
145
- return buf;
146
- }
147
- function ulidFn(options, buf, offset = 0) {
148
- let time;
149
- let random;
150
- /**
151
- * Note: by default, Cloudflare Workers "freezes" time during request handling to prevent
152
- * side-channel attacks. This means that Date.now() will return the same value for the entire
153
- * duration of a request.
154
- * Implications:
155
- * - all ULIDs generated within a single request will have the same timestamp.
156
- * - the monotonic ordering will rely entirely on incrementing the random portion.
157
- */
158
- const defaultTime = Date.now();
159
- if (options) {
160
- time = options.msecs ?? defaultTime;
161
- random = options.random ?? rng();
162
- } else {
163
- time = defaultTime;
164
- if (time > state.msecs) {
165
- random = rng();
166
- state.msecs = time;
167
- state.lastRandom.set(random.subarray(0, 10));
168
- } else {
169
- random = incrementBytes(state.lastRandom);
170
- state.lastRandom = random;
171
- }
172
- }
173
- if (buf) {
174
- ulidBytes(time, random, buf, offset);
175
- return buf;
176
- }
177
- return encodeTime(time) + encodeRandom(random);
178
- }
179
- /**
180
- * Generate a ULID string or write the bytes into a buffer.
181
- * It also includes helpers to convert to and from byte arrays.
182
- */
183
- const ulid = Object.assign(ulidFn, {
184
- toBytes: (id) => decodeToBytes(id),
185
- fromBytes: (bytes) => bytesToUlid(bytes),
186
- timestamp: (id) => decodeTime(id.slice(0, 10)),
187
- isValid: (id) => ULID_REGEX.test(id)
188
- });
189
-
190
- //#endregion
191
- export { ulid };
1
+ import{t as e}from"../random-pEE8mU9d.mjs";const t=`0123456789ABCDEFGHJKMNPQRSTVWXYZ`,n=new Uint8Array(128);n.fill(255);for(let e=0;e<32;e+=1){let r=t.charCodeAt(e),i=t[e].toLowerCase().charCodeAt(0);n[r]=e,n[i]=e}function r(e){return t[Math.floor(e/35184372088832)&31]+t[Math.floor(e/1099511627776)&31]+t[Math.floor(e/34359738368)&31]+t[Math.floor(e/1073741824)&31]+t[Math.floor(e/33554432)&31]+t[Math.floor(e/1048576)&31]+t[Math.floor(e/32768)&31]+t[Math.floor(e/1024)&31]+t[Math.floor(e/32)&31]+t[e&31]}function i(e){return t[e[0]>>3&31]+t[(e[0]<<2|e[1]>>6)&31]+t[e[1]>>1&31]+t[(e[1]<<4|e[2]>>4)&31]+t[(e[2]<<1|e[3]>>7)&31]+t[e[3]>>2&31]+t[(e[3]<<3|e[4]>>5)&31]+t[e[4]&31]+t[e[5]>>3&31]+t[(e[5]<<2|e[6]>>6)&31]+t[e[6]>>1&31]+t[(e[6]<<4|e[7]>>4)&31]+t[(e[7]<<1|e[8]>>7)&31]+t[e[8]>>2&31]+t[(e[8]<<3|e[9]>>5)&31]+t[e[9]&31]}function a(e){let t=0;for(let r=0;r<10;r+=1){let i=n[e.charCodeAt(r)];if(i===255)throw Error(`Invalid ULID character: ${e[r]}`);t=t*32+i}return t}function o(e){if(e.length!==26)throw Error(`ULID string must be 26 characters`);let t=new Uint8Array(16),r=n[e.charCodeAt(0)],i=n[e.charCodeAt(1)],a=n[e.charCodeAt(2)],o=n[e.charCodeAt(3)],s=n[e.charCodeAt(4)],c=n[e.charCodeAt(5)],l=n[e.charCodeAt(6)],u=n[e.charCodeAt(7)],d=n[e.charCodeAt(8)],f=n[e.charCodeAt(9)],p=n[e.charCodeAt(10)],m=n[e.charCodeAt(11)],h=n[e.charCodeAt(12)],g=n[e.charCodeAt(13)],_=n[e.charCodeAt(14)],v=n[e.charCodeAt(15)],y=n[e.charCodeAt(16)],b=n[e.charCodeAt(17)],x=n[e.charCodeAt(18)],S=n[e.charCodeAt(19)],C=n[e.charCodeAt(20)],w=n[e.charCodeAt(21)],T=n[e.charCodeAt(22)],E=n[e.charCodeAt(23)],D=n[e.charCodeAt(24)],O=n[e.charCodeAt(25)];if((r|i|a|o|s|c|l|u|d|f|p|m|h|g|_|v|y|b|x|S|C|w|T|E|D|O)&128){for(let t=0;t<26;t+=1)if(n[e.charCodeAt(t)]===255)throw Error(`Invalid ULID character: ${e[t]}`)}return t[0]=r<<5|i,t[1]=a<<3|o>>2,t[2]=o<<6|s<<1|c>>4,t[3]=c<<4|l>>1,t[4]=l<<7|u<<2|d>>3,t[5]=d<<5|f,t[6]=p<<3|m>>2,t[7]=m<<6|h<<1|g>>4,t[8]=g<<4|_>>1,t[9]=_<<7|v<<2|y>>3,t[10]=y<<5|b,t[11]=x<<3|S>>2,t[12]=S<<6|C<<1|w>>4,t[13]=w<<4|T>>1,t[14]=T<<7|E<<2|D>>3,t[15]=D<<5|O,t}function s(e){if(e.length<16)throw Error(`Byte array must be at least 16 bytes`);let t=0;for(let n=0;n<6;n+=1)t=t*256+e[n];return r(t)+i(e.subarray(6,16))}const c=/^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i,l={msecs:-1/0,lastRandom:new Uint8Array(10)};function u(e){let t=new Uint8Array(e);for(let e=t.length-1;e>=0;--e){if(t[e]<255)return t[e]+=1,t;t[e]=0}return t}function d(e,t,n,r=0){if(!n)n=new Uint8Array(16),r=0;else if(r<0||r+16>n.length)throw RangeError(`ULID byte range ${r}:${r+15} is out of buffer bounds`);n[r]=e/1099511627776&255,n[r+1]=e/4294967296&255,n[r+2]=e/16777216&255,n[r+3]=e/65536&255,n[r+4]=e/256&255,n[r+5]=e&255;for(let e=0;e<10;e+=1)n[r+6+e]=t[e];return n}function f(t,n,a=0){let o,s,c=Date.now();return t?(o=t.msecs??c,s=t.random??e()):(o=c,o>l.msecs?(s=e(),l.msecs=o,l.lastRandom.set(s.subarray(0,10))):(s=u(l.lastRandom),l.lastRandom=s)),n?(d(o,s,n,a),n):r(o)+i(s)}const p=Object.assign(f,{toBytes:e=>o(e),fromBytes:e=>s(e),timestamp:e=>a(e.slice(0,10)),isValid:e=>c.test(e)});export{p as ulid};
192
2
  //# sourceMappingURL=ulid.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"ulid.mjs","names":["state: UlidState","time: number","random: Uint8Array","ulid: Ulid"],"sources":["../../src/ulid/common/crockford.ts","../../src/ulid/ulid.ts"],"sourcesContent":["// Crockford's Base32 alphabet (excludes I, L, O, U to avoid confusion)\nconst ENCODING = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\n// Pre-computed decoding table indexed by ASCII code (0-127)\n// Uses Uint8Array for cache-efficient lookups via charCodeAt\nconst DECODING = new Uint8Array(128)\nDECODING.fill(255) // 255 = invalid marker\nfor (let i = 0; i < ENCODING.length; i += 1) {\n const upper = ENCODING.charCodeAt(i)\n const lower = ENCODING[i].toLowerCase().charCodeAt(0)\n DECODING[upper] = i\n DECODING[lower] = i\n}\n\nconst TIME_LEN = 10\n\n/**\n * Encode a 48-bit timestamp to a 10-character Crockford Base32 string.\n * Uses unrolled division for performance.\n */\nexport function encodeTime(time: number): string {\n // Unrolled encoding - each step divides by 32 and extracts 5 bits\n // Powers of 32: 32^9=0x200000000000, 32^8=0x10000000000, etc.\n return (\n ENCODING[Math.floor(time / 0x200000000000) & 0x1f] +\n ENCODING[Math.floor(time / 0x10000000000) & 0x1f] +\n ENCODING[Math.floor(time / 0x800000000) & 0x1f] +\n ENCODING[Math.floor(time / 0x40000000) & 0x1f] +\n ENCODING[Math.floor(time / 0x2000000) & 0x1f] +\n ENCODING[Math.floor(time / 0x100000) & 0x1f] +\n ENCODING[Math.floor(time / 0x8000) & 0x1f] +\n ENCODING[Math.floor(time / 0x400) & 0x1f] +\n ENCODING[Math.floor(time / 0x20) & 0x1f] +\n ENCODING[time & 0x1f]\n )\n}\n\n/**\n * Encode 10 bytes (80 bits) of random data to a 16-character Crockford Base32 string.\n */\nexport function encodeRandom(bytes: Uint8Array): string {\n // Each character encodes 5 bits. 80 bits = 16 characters.\n // Single concatenation expression for optimal performance.\n return (\n ENCODING[(bytes[0] >> 3) & 0x1f] +\n ENCODING[((bytes[0] << 2) | (bytes[1] >> 6)) & 0x1f] +\n ENCODING[(bytes[1] >> 1) & 0x1f] +\n ENCODING[((bytes[1] << 4) | (bytes[2] >> 4)) & 0x1f] +\n ENCODING[((bytes[2] << 1) | (bytes[3] >> 7)) & 0x1f] +\n ENCODING[(bytes[3] >> 2) & 0x1f] +\n ENCODING[((bytes[3] << 3) | (bytes[4] >> 5)) & 0x1f] +\n ENCODING[bytes[4] & 0x1f] +\n ENCODING[(bytes[5] >> 3) & 0x1f] +\n ENCODING[((bytes[5] << 2) | (bytes[6] >> 6)) & 0x1f] +\n ENCODING[(bytes[6] >> 1) & 0x1f] +\n ENCODING[((bytes[6] << 4) | (bytes[7] >> 4)) & 0x1f] +\n ENCODING[((bytes[7] << 1) | (bytes[8] >> 7)) & 0x1f] +\n ENCODING[(bytes[8] >> 2) & 0x1f] +\n ENCODING[((bytes[8] << 3) | (bytes[9] >> 5)) & 0x1f] +\n ENCODING[bytes[9] & 0x1f]\n )\n}\n\n/**\n * Decode the first 10 characters of a ULID string to a timestamp (Unix epoch milliseconds).\n */\nexport function decodeTime(str: string): number {\n let time = 0\n for (let i = 0; i < TIME_LEN; i += 1) {\n const value = DECODING[str.charCodeAt(i)]\n if (value === 255) {\n throw new Error(`Invalid ULID character: ${str[i]}`)\n }\n time = time * 32 + value\n }\n return time\n}\n\n/**\n * Decode a 26-character ULID string to 16 bytes.\n * Inlines all lookups to avoid intermediate array allocation.\n */\nexport function decodeToBytes(str: string): Uint8Array {\n if (str.length !== 26) {\n throw new Error('ULID string must be 26 characters')\n }\n\n const bytes = new Uint8Array(16)\n\n // Inline all 26 character lookups\n const v0 = DECODING[str.charCodeAt(0)]\n const v1 = DECODING[str.charCodeAt(1)]\n const v2 = DECODING[str.charCodeAt(2)]\n const v3 = DECODING[str.charCodeAt(3)]\n const v4 = DECODING[str.charCodeAt(4)]\n const v5 = DECODING[str.charCodeAt(5)]\n const v6 = DECODING[str.charCodeAt(6)]\n const v7 = DECODING[str.charCodeAt(7)]\n const v8 = DECODING[str.charCodeAt(8)]\n const v9 = DECODING[str.charCodeAt(9)]\n const v10 = DECODING[str.charCodeAt(10)]\n const v11 = DECODING[str.charCodeAt(11)]\n const v12 = DECODING[str.charCodeAt(12)]\n const v13 = DECODING[str.charCodeAt(13)]\n const v14 = DECODING[str.charCodeAt(14)]\n const v15 = DECODING[str.charCodeAt(15)]\n const v16 = DECODING[str.charCodeAt(16)]\n const v17 = DECODING[str.charCodeAt(17)]\n const v18 = DECODING[str.charCodeAt(18)]\n const v19 = DECODING[str.charCodeAt(19)]\n const v20 = DECODING[str.charCodeAt(20)]\n const v21 = DECODING[str.charCodeAt(21)]\n const v22 = DECODING[str.charCodeAt(22)]\n const v23 = DECODING[str.charCodeAt(23)]\n const v24 = DECODING[str.charCodeAt(24)]\n const v25 = DECODING[str.charCodeAt(25)]\n\n // Validate all characters (255 = invalid marker)\n if (\n (v0 |\n v1 |\n v2 |\n v3 |\n v4 |\n v5 |\n v6 |\n v7 |\n v8 |\n v9 |\n v10 |\n v11 |\n v12 |\n v13 |\n v14 |\n v15 |\n v16 |\n v17 |\n v18 |\n v19 |\n v20 |\n v21 |\n v22 |\n v23 |\n v24 |\n v25) &\n 0x80\n ) {\n // Find the invalid character for error message\n for (let i = 0; i < 26; i += 1) {\n if (DECODING[str.charCodeAt(i)] === 255) {\n throw new Error(`Invalid ULID character: ${str[i]}`)\n }\n }\n }\n\n // Timestamp: first 10 characters -> bytes 0-5\n bytes[0] = (v0 << 5) | v1\n bytes[1] = (v2 << 3) | (v3 >> 2)\n bytes[2] = (v3 << 6) | (v4 << 1) | (v5 >> 4)\n bytes[3] = (v5 << 4) | (v6 >> 1)\n bytes[4] = (v6 << 7) | (v7 << 2) | (v8 >> 3)\n bytes[5] = (v8 << 5) | v9\n\n // Random: last 16 characters -> bytes 6-15\n bytes[6] = (v10 << 3) | (v11 >> 2)\n bytes[7] = (v11 << 6) | (v12 << 1) | (v13 >> 4)\n bytes[8] = (v13 << 4) | (v14 >> 1)\n bytes[9] = (v14 << 7) | (v15 << 2) | (v16 >> 3)\n bytes[10] = (v16 << 5) | v17\n bytes[11] = (v18 << 3) | (v19 >> 2)\n bytes[12] = (v19 << 6) | (v20 << 1) | (v21 >> 4)\n bytes[13] = (v21 << 4) | (v22 >> 1)\n bytes[14] = (v22 << 7) | (v23 << 2) | (v24 >> 3)\n bytes[15] = (v24 << 5) | v25\n\n return bytes\n}\n\n/**\n * Encode 16 bytes to a 26-character ULID string.\n */\nexport function bytesToUlid(bytes: Uint8Array): string {\n if (bytes.length < 16) {\n throw new Error('Byte array must be at least 16 bytes')\n }\n\n // Timestamp: bytes 0-5 -> 10 characters\n let time = 0\n for (let i = 0; i < 6; i += 1) {\n time = time * 256 + bytes[i]\n }\n const timeStr = encodeTime(time)\n\n // Random: bytes 6-15 -> 16 characters\n const randomStr = encodeRandom(bytes.subarray(6, 16))\n\n return timeStr + randomStr\n}\n","import { rng } from '../uuid/common/random'\nimport { bytesToUlid, decodeTime, decodeToBytes, encodeRandom, encodeTime } from './common/crockford'\n\nexport type UlidOptions = {\n /**\n * 16 bytes of random data to use for ULID generation.\n * Only the first 10 bytes are used.\n */\n random?: Uint8Array\n /**\n * Timestamp in milliseconds since Unix epoch.\n * Defaults to Date.now().\n */\n msecs?: number\n}\n\nexport type Ulid = {\n (): string\n <TBuf extends Uint8Array = Uint8Array>(options: UlidOptions | undefined, buf: TBuf, offset?: number): TBuf\n (options?: UlidOptions, 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\n// Validation regex: first char [0-7] to prevent overflow, rest from Crockford alphabet\nconst ULID_REGEX = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i\n\ntype UlidState = {\n msecs: number\n lastRandom: Uint8Array\n}\n\n/**\n * Module-level state for maintaining monotonic ordering within the same millisecond.\n *\n * IMPORTANT: This state persists across all ulid() 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: UlidState = {\n msecs: -Infinity,\n lastRandom: new Uint8Array(10),\n}\n\n/**\n * Increment a byte array by 1, propagating carry from LSB to MSB.\n * Returns a new array (does not modify input).\n */\nfunction incrementBytes(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\nfunction ulidBytes(time: number, random: Uint8Array, buf?: Uint8Array, offset = 0): Uint8Array {\n if (!buf) {\n buf = new Uint8Array(16)\n offset = 0\n } else if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`ULID byte range ${offset}:${offset + 15} is out of buffer bounds`)\n }\n\n // Timestamp (48-bit big-endian milliseconds since Unix epoch) -> bytes 0-5\n buf[offset] = (time / 0x10000000000) & 0xff\n buf[offset + 1] = (time / 0x100000000) & 0xff\n buf[offset + 2] = (time / 0x1000000) & 0xff\n buf[offset + 3] = (time / 0x10000) & 0xff\n buf[offset + 4] = (time / 0x100) & 0xff\n buf[offset + 5] = time & 0xff\n\n // Random (80 bits) -> bytes 6-15\n for (let i = 0; i < 10; i += 1) {\n buf[offset + 6 + i] = random[i]\n }\n\n return buf\n}\n\n/*\n * Overload: no buffer => return a ULID string.\n */\nfunction ulidFn(options?: UlidOptions, buf?: undefined, offset?: number): string\n/*\n * Overload: caller provides a buffer slice to fill with ULID bytes.\n */\nfunction ulidFn<TBuf extends Uint8Array = Uint8Array>(\n options: UlidOptions | undefined,\n buf: TBuf,\n offset?: number,\n): TBuf\nfunction ulidFn<TBuf extends Uint8Array = Uint8Array>(options?: UlidOptions, buf?: TBuf, offset = 0): string | TBuf {\n let time: number\n let random: 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 ULIDs generated within a single request will have the same timestamp.\n * - the monotonic ordering will rely entirely on incrementing the random portion.\n */\n const defaultTime = Date.now()\n\n if (options) {\n // Explicit options provided - use them directly without monotonic state\n time = options.msecs ?? defaultTime\n random = options.random ?? rng()\n } else {\n time = defaultTime\n\n if (time > state.msecs) {\n // New millisecond: generate fresh random\n random = rng()\n state.msecs = time\n state.lastRandom.set(random.subarray(0, 10))\n } else {\n // Same millisecond: increment random portion for monotonic ordering\n random = incrementBytes(state.lastRandom)\n state.lastRandom = random\n }\n }\n\n if (buf) {\n ulidBytes(time, random, buf, offset)\n return buf\n }\n\n // String mode: encode directly without buffer allocation\n return encodeTime(time) + encodeRandom(random)\n}\n\n/**\n * Generate a ULID string or write the bytes into a buffer.\n * It also includes helpers to convert to and from byte arrays.\n */\nexport const ulid: Ulid = Object.assign(ulidFn, {\n toBytes: (id: string) => decodeToBytes(id),\n fromBytes: (bytes: Uint8Array) => bytesToUlid(bytes),\n timestamp: (id: string) => decodeTime(id.slice(0, 10)),\n isValid: (id: string) => ULID_REGEX.test(id),\n})\n"],"mappings":";;;AACA,MAAM,WAAW;AAIjB,MAAM,WAAW,IAAI,WAAW,IAAI;AACpC,SAAS,KAAK,IAAI;AAClB,KAAK,IAAI,IAAI,GAAG,IAAI,IAAiB,KAAK,GAAG;CAC3C,MAAM,QAAQ,SAAS,WAAW,EAAE;CACpC,MAAM,QAAQ,SAAS,GAAG,aAAa,CAAC,WAAW,EAAE;AACrD,UAAS,SAAS;AAClB,UAAS,SAAS;;AAGpB,MAAM,WAAW;;;;;AAMjB,SAAgB,WAAW,MAAsB;AAG/C,QACE,SAAS,KAAK,MAAM,OAAO,eAAe,GAAG,MAC7C,SAAS,KAAK,MAAM,OAAO,cAAc,GAAG,MAC5C,SAAS,KAAK,MAAM,OAAO,YAAY,GAAG,MAC1C,SAAS,KAAK,MAAM,OAAO,WAAW,GAAG,MACzC,SAAS,KAAK,MAAM,OAAO,SAAU,GAAG,MACxC,SAAS,KAAK,MAAM,OAAO,QAAS,GAAG,MACvC,SAAS,KAAK,MAAM,OAAO,MAAO,GAAG,MACrC,SAAS,KAAK,MAAM,OAAO,KAAM,GAAG,MACpC,SAAS,KAAK,MAAM,OAAO,GAAK,GAAG,MACnC,SAAS,OAAO;;;;;AAOpB,SAAgB,aAAa,OAA2B;AAGtD,QACE,SAAU,MAAM,MAAM,IAAK,MAC3B,UAAW,MAAM,MAAM,IAAM,MAAM,MAAM,KAAM,MAC/C,SAAU,MAAM,MAAM,IAAK,MAC3B,UAAW,MAAM,MAAM,IAAM,MAAM,MAAM,KAAM,MAC/C,UAAW,MAAM,MAAM,IAAM,MAAM,MAAM,KAAM,MAC/C,SAAU,MAAM,MAAM,IAAK,MAC3B,UAAW,MAAM,MAAM,IAAM,MAAM,MAAM,KAAM,MAC/C,SAAS,MAAM,KAAK,MACpB,SAAU,MAAM,M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AO;AAGzB,MAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK,EAC3B,KAAI,SAAS,IAAI,KAAK,OAAO;AAG/B,QAAO;;AAeT,SAAS,OAA6C,SAAuB,KAAY,SAAS,GAAkB;CAClH,IAAIC;CACJ,IAAIC;;;;;;;;;CAUJ,MAAM,cAAc,KAAK,KAAK;AAE9B,KAAI,SAAS;AAEX,SAAO,QAAQ,SAAS;AACxB,WAAS,QAAQ,UAAU,KAAK;QAC3B;AACL,SAAO;AAEP,MAAI,OAAO,MAAM,OAAO;AAEtB,YAAS,KAAK;AACd,SAAM,QAAQ;AACd,SAAM,WAAW,IAAI,OAAO,SAAS,GAAG,GAAG,CAAC;SACvC;AAEL,YAAS,eAAe,MAAM,WAAW;AACzC,SAAM,aAAa;;;AAIvB,KAAI,KAAK;AACP,YAAU,MAAM,QAAQ,KAAK,OAAO;AACpC,SAAO;;AAIT,QAAO,WAAW,KAAK,GAAG,aAAa,OAAO;;;;;;AAOhD,MAAaC,OAAa,OAAO,OAAO,QAAQ;CAC9C,UAAU,OAAe,cAAc,GAAG;CAC1C,YAAY,UAAsB,YAAY,MAAM;CACpD,YAAY,OAAe,WAAW,GAAG,MAAM,GAAG,GAAG,CAAC;CACtD,UAAU,OAAe,WAAW,KAAK,GAAG;CAC7C,CAAC"}
1
+ {"version":3,"file":"ulid.mjs","names":["state: UlidState","time: number","random: Uint8Array","ulid: Ulid"],"sources":["../../src/ulid/common/crockford.ts","../../src/ulid/ulid.ts"],"sourcesContent":["// Crockford's Base32 alphabet (excludes I, L, O, U to avoid confusion)\nconst ENCODING = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'\n\n// Pre-computed decoding table indexed by ASCII code (0-127)\n// Uses Uint8Array for cache-efficient lookups via charCodeAt\nconst DECODING = new Uint8Array(128)\nDECODING.fill(255) // 255 = invalid marker\nfor (let i = 0; i < ENCODING.length; i += 1) {\n const upper = ENCODING.charCodeAt(i)\n const lower = ENCODING[i].toLowerCase().charCodeAt(0)\n DECODING[upper] = i\n DECODING[lower] = i\n}\n\nconst TIME_LEN = 10\n\n/**\n * Encode a 48-bit timestamp to a 10-character Crockford Base32 string.\n * Uses unrolled division for performance.\n */\nexport function encodeTime(time: number): string {\n // Unrolled encoding - each step divides by 32 and extracts 5 bits\n // Powers of 32: 32^9=0x200000000000, 32^8=0x10000000000, etc.\n return (\n ENCODING[Math.floor(time / 0x200000000000) & 0x1f] +\n ENCODING[Math.floor(time / 0x10000000000) & 0x1f] +\n ENCODING[Math.floor(time / 0x800000000) & 0x1f] +\n ENCODING[Math.floor(time / 0x40000000) & 0x1f] +\n ENCODING[Math.floor(time / 0x2000000) & 0x1f] +\n ENCODING[Math.floor(time / 0x100000) & 0x1f] +\n ENCODING[Math.floor(time / 0x8000) & 0x1f] +\n ENCODING[Math.floor(time / 0x400) & 0x1f] +\n ENCODING[Math.floor(time / 0x20) & 0x1f] +\n ENCODING[time & 0x1f]\n )\n}\n\n/**\n * Encode 10 bytes (80 bits) of random data to a 16-character Crockford Base32 string.\n */\nexport function encodeRandom(bytes: Uint8Array): string {\n // Each character encodes 5 bits. 80 bits = 16 characters.\n // Single concatenation expression for optimal performance.\n return (\n ENCODING[(bytes[0] >> 3) & 0x1f] +\n ENCODING[((bytes[0] << 2) | (bytes[1] >> 6)) & 0x1f] +\n ENCODING[(bytes[1] >> 1) & 0x1f] +\n ENCODING[((bytes[1] << 4) | (bytes[2] >> 4)) & 0x1f] +\n ENCODING[((bytes[2] << 1) | (bytes[3] >> 7)) & 0x1f] +\n ENCODING[(bytes[3] >> 2) & 0x1f] +\n ENCODING[((bytes[3] << 3) | (bytes[4] >> 5)) & 0x1f] +\n ENCODING[bytes[4] & 0x1f] +\n ENCODING[(bytes[5] >> 3) & 0x1f] +\n ENCODING[((bytes[5] << 2) | (bytes[6] >> 6)) & 0x1f] +\n ENCODING[(bytes[6] >> 1) & 0x1f] +\n ENCODING[((bytes[6] << 4) | (bytes[7] >> 4)) & 0x1f] +\n ENCODING[((bytes[7] << 1) | (bytes[8] >> 7)) & 0x1f] +\n ENCODING[(bytes[8] >> 2) & 0x1f] +\n ENCODING[((bytes[8] << 3) | (bytes[9] >> 5)) & 0x1f] +\n ENCODING[bytes[9] & 0x1f]\n )\n}\n\n/**\n * Decode the first 10 characters of a ULID string to a timestamp (Unix epoch milliseconds).\n */\nexport function decodeTime(str: string): number {\n let time = 0\n for (let i = 0; i < TIME_LEN; i += 1) {\n const value = DECODING[str.charCodeAt(i)]\n if (value === 255) {\n throw new Error(`Invalid ULID character: ${str[i]}`)\n }\n time = time * 32 + value\n }\n return time\n}\n\n/**\n * Decode a 26-character ULID string to 16 bytes.\n * Inlines all lookups to avoid intermediate array allocation.\n */\nexport function decodeToBytes(str: string): Uint8Array {\n if (str.length !== 26) {\n throw new Error('ULID string must be 26 characters')\n }\n\n const bytes = new Uint8Array(16)\n\n // Inline all 26 character lookups\n const v0 = DECODING[str.charCodeAt(0)]\n const v1 = DECODING[str.charCodeAt(1)]\n const v2 = DECODING[str.charCodeAt(2)]\n const v3 = DECODING[str.charCodeAt(3)]\n const v4 = DECODING[str.charCodeAt(4)]\n const v5 = DECODING[str.charCodeAt(5)]\n const v6 = DECODING[str.charCodeAt(6)]\n const v7 = DECODING[str.charCodeAt(7)]\n const v8 = DECODING[str.charCodeAt(8)]\n const v9 = DECODING[str.charCodeAt(9)]\n const v10 = DECODING[str.charCodeAt(10)]\n const v11 = DECODING[str.charCodeAt(11)]\n const v12 = DECODING[str.charCodeAt(12)]\n const v13 = DECODING[str.charCodeAt(13)]\n const v14 = DECODING[str.charCodeAt(14)]\n const v15 = DECODING[str.charCodeAt(15)]\n const v16 = DECODING[str.charCodeAt(16)]\n const v17 = DECODING[str.charCodeAt(17)]\n const v18 = DECODING[str.charCodeAt(18)]\n const v19 = DECODING[str.charCodeAt(19)]\n const v20 = DECODING[str.charCodeAt(20)]\n const v21 = DECODING[str.charCodeAt(21)]\n const v22 = DECODING[str.charCodeAt(22)]\n const v23 = DECODING[str.charCodeAt(23)]\n const v24 = DECODING[str.charCodeAt(24)]\n const v25 = DECODING[str.charCodeAt(25)]\n\n // Validate all characters (255 = invalid marker)\n if (\n (v0 |\n v1 |\n v2 |\n v3 |\n v4 |\n v5 |\n v6 |\n v7 |\n v8 |\n v9 |\n v10 |\n v11 |\n v12 |\n v13 |\n v14 |\n v15 |\n v16 |\n v17 |\n v18 |\n v19 |\n v20 |\n v21 |\n v22 |\n v23 |\n v24 |\n v25) &\n 0x80\n ) {\n // Find the invalid character for error message\n for (let i = 0; i < 26; i += 1) {\n if (DECODING[str.charCodeAt(i)] === 255) {\n throw new Error(`Invalid ULID character: ${str[i]}`)\n }\n }\n }\n\n // Timestamp: first 10 characters -> bytes 0-5\n bytes[0] = (v0 << 5) | v1\n bytes[1] = (v2 << 3) | (v3 >> 2)\n bytes[2] = (v3 << 6) | (v4 << 1) | (v5 >> 4)\n bytes[3] = (v5 << 4) | (v6 >> 1)\n bytes[4] = (v6 << 7) | (v7 << 2) | (v8 >> 3)\n bytes[5] = (v8 << 5) | v9\n\n // Random: last 16 characters -> bytes 6-15\n bytes[6] = (v10 << 3) | (v11 >> 2)\n bytes[7] = (v11 << 6) | (v12 << 1) | (v13 >> 4)\n bytes[8] = (v13 << 4) | (v14 >> 1)\n bytes[9] = (v14 << 7) | (v15 << 2) | (v16 >> 3)\n bytes[10] = (v16 << 5) | v17\n bytes[11] = (v18 << 3) | (v19 >> 2)\n bytes[12] = (v19 << 6) | (v20 << 1) | (v21 >> 4)\n bytes[13] = (v21 << 4) | (v22 >> 1)\n bytes[14] = (v22 << 7) | (v23 << 2) | (v24 >> 3)\n bytes[15] = (v24 << 5) | v25\n\n return bytes\n}\n\n/**\n * Encode 16 bytes to a 26-character ULID string.\n */\nexport function bytesToUlid(bytes: Uint8Array): string {\n if (bytes.length < 16) {\n throw new Error('Byte array must be at least 16 bytes')\n }\n\n // Timestamp: bytes 0-5 -> 10 characters\n let time = 0\n for (let i = 0; i < 6; i += 1) {\n time = time * 256 + bytes[i]\n }\n const timeStr = encodeTime(time)\n\n // Random: bytes 6-15 -> 16 characters\n const randomStr = encodeRandom(bytes.subarray(6, 16))\n\n return timeStr + randomStr\n}\n","import { rng } from '../uuid/common/random'\nimport { bytesToUlid, decodeTime, decodeToBytes, encodeRandom, encodeTime } from './common/crockford'\n\nexport type UlidOptions = {\n /**\n * 16 bytes of random data to use for ULID generation.\n * Only the first 10 bytes are used.\n */\n random?: Uint8Array\n /**\n * Timestamp in milliseconds since Unix epoch.\n * Defaults to Date.now().\n */\n msecs?: number\n}\n\nexport type Ulid = {\n (): string\n <TBuf extends Uint8Array = Uint8Array>(options: UlidOptions | undefined, buf: TBuf, offset?: number): TBuf\n (options?: UlidOptions, 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\n// Validation regex: first char [0-7] to prevent overflow, rest from Crockford alphabet\nconst ULID_REGEX = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i\n\ntype UlidState = {\n msecs: number\n lastRandom: Uint8Array\n}\n\n/**\n * Module-level state for maintaining monotonic ordering within the same millisecond.\n *\n * IMPORTANT: This state persists across all ulid() 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: UlidState = {\n msecs: -Infinity,\n lastRandom: new Uint8Array(10),\n}\n\n/**\n * Increment a byte array by 1, propagating carry from LSB to MSB.\n * Returns a new array (does not modify input).\n */\nfunction incrementBytes(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\nfunction ulidBytes(time: number, random: Uint8Array, buf?: Uint8Array, offset = 0): Uint8Array {\n if (!buf) {\n buf = new Uint8Array(16)\n offset = 0\n } else if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`ULID byte range ${offset}:${offset + 15} is out of buffer bounds`)\n }\n\n // Timestamp (48-bit big-endian milliseconds since Unix epoch) -> bytes 0-5\n buf[offset] = (time / 0x10000000000) & 0xff\n buf[offset + 1] = (time / 0x100000000) & 0xff\n buf[offset + 2] = (time / 0x1000000) & 0xff\n buf[offset + 3] = (time / 0x10000) & 0xff\n buf[offset + 4] = (time / 0x100) & 0xff\n buf[offset + 5] = time & 0xff\n\n // Random (80 bits) -> bytes 6-15\n for (let i = 0; i < 10; i += 1) {\n buf[offset + 6 + i] = random[i]\n }\n\n return buf\n}\n\n/*\n * Overload: no buffer => return a ULID string.\n */\nfunction ulidFn(options?: UlidOptions, buf?: undefined, offset?: number): string\n/*\n * Overload: caller provides a buffer slice to fill with ULID bytes.\n */\nfunction ulidFn<TBuf extends Uint8Array = Uint8Array>(\n options: UlidOptions | undefined,\n buf: TBuf,\n offset?: number,\n): TBuf\nfunction ulidFn<TBuf extends Uint8Array = Uint8Array>(options?: UlidOptions, buf?: TBuf, offset = 0): string | TBuf {\n let time: number\n let random: 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 ULIDs generated within a single request will have the same timestamp.\n * - the monotonic ordering will rely entirely on incrementing the random portion.\n */\n const defaultTime = Date.now()\n\n if (options) {\n // Explicit options provided - use them directly without monotonic state\n time = options.msecs ?? defaultTime\n random = options.random ?? rng()\n } else {\n time = defaultTime\n\n if (time > state.msecs) {\n // New millisecond: generate fresh random\n random = rng()\n state.msecs = time\n state.lastRandom.set(random.subarray(0, 10))\n } else {\n // Same millisecond: increment random portion for monotonic ordering\n random = incrementBytes(state.lastRandom)\n state.lastRandom = random\n }\n }\n\n if (buf) {\n ulidBytes(time, random, buf, offset)\n return buf\n }\n\n // String mode: encode directly without buffer allocation\n return encodeTime(time) + encodeRandom(random)\n}\n\n/**\n * Generate a ULID string or write the bytes into a buffer.\n * It also includes helpers to convert to and from byte arrays.\n */\nexport const ulid: Ulid = Object.assign(ulidFn, {\n toBytes: (id: string) => decodeToBytes(id),\n fromBytes: (bytes: Uint8Array) => bytesToUlid(bytes),\n timestamp: (id: string) => decodeTime(id.slice(0, 10)),\n isValid: (id: string) => ULID_REGEX.test(id),\n})\n"],"mappings":"2CACA,MAAM,EAAW,mCAIX,EAAW,IAAI,WAAW,IAAI,CACpC,EAAS,KAAK,IAAI,CAClB,IAAK,IAAI,EAAI,EAAG,EAAI,GAAiB,GAAK,EAAG,CAC3C,IAAM,EAAQ,EAAS,WAAW,EAAE,CAC9B,EAAQ,EAAS,GAAG,aAAa,CAAC,WAAW,EAAE,CACrD,EAAS,GAAS,EAClB,EAAS,GAAS,EASpB,SAAgB,EAAW,EAAsB,CAG/C,OACE,EAAS,KAAK,MAAM,EAAO,eAAe,CAAG,IAC7C,EAAS,KAAK,MAAM,EAAO,cAAc,CAAG,IAC5C,EAAS,KAAK,MAAM,EAAO,YAAY,CAAG,IAC1C,EAAS,KAAK,MAAM,EAAO,WAAW,CAAG,IACzC,EAAS,KAAK,MAAM,EAAO,SAAU,CAAG,IACxC,EAAS,KAAK,MAAM,EAAO,QAAS,CAAG,IACvC,EAAS,KAAK,MAAM,EAAO,MAAO,CAAG,IACrC,EAAS,KAAK,MAAM,EAAO,KAAM,CAAG,IACpC,EAAS,KAAK,MAAM,EAAO,GAAK,CAAG,IACnC,EAAS,EAAO,IAOpB,SAAgB,EAAa,EAA2B,CAGtD,OACE,EAAU,EAAM,IAAM,EAAK,IAC3B,GAAW,EAAM,IAAM,EAAM,EAAM,IAAM,GAAM,IAC/C,EAAU,EAAM,IAAM,EAAK,IAC3B,GAAW,EAAM,IAAM,EAAM,EAAM,IAAM,GAAM,IAC/C,GAAW,EAAM,IAAM,EAAM,EAAM,IAAM,GAAM,IAC/C,EAAU,EAAM,IAAM,EAAK,IAC3B,GAAW,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AC,EAUE,EAAc,KAAK,KAAK,CA2B9B,OAzBI,GAEF,EAAO,EAAQ,OAAS,EACxB,EAAS,EAAQ,QAAU,GAAK,GAEhC,EAAO,EAEH,EAAO,EAAM,OAEf,EAAS,GAAK,CACd,EAAM,MAAQ,EACd,EAAM,WAAW,IAAI,EAAO,SAAS,EAAG,GAAG,CAAC,GAG5C,EAAS,EAAe,EAAM,WAAW,CACzC,EAAM,WAAa,IAInB,GACF,EAAU,EAAM,EAAQ,EAAK,EAAO,CAC7B,GAIF,EAAW,EAAK,CAAG,EAAa,EAAO,CAOhD,MAAaC,EAAa,OAAO,OAAO,EAAQ,CAC9C,QAAU,GAAe,EAAc,EAAG,CAC1C,UAAY,GAAsB,EAAY,EAAM,CACpD,UAAY,GAAe,EAAW,EAAG,MAAM,EAAG,GAAG,CAAC,CACtD,QAAU,GAAe,EAAW,KAAK,EAAG,CAC7C,CAAC"}
package/build/uuid/v4.mjs CHANGED
@@ -1,35 +1,2 @@
1
- import { t as rng } from "../random-Dul5R6oJ.mjs";
2
- import { n as parseUuid, t as formatUuid } from "../uuid-cJ5hOOIR.mjs";
3
-
4
- //#region src/uuid/v4.ts
5
- const UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
6
- function v4Bytes(rnds, buf, offset = 0) {
7
- if (rnds.length < 16) throw new Error("Random bytes length must be >= 16");
8
- rnds[6] = rnds[6] & 15 | 64;
9
- rnds[8] = rnds[8] & 63 | 128;
10
- if (!buf) return rnds;
11
- if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
12
- for (let i = 0; i < 16; i += 1) buf[offset + i] = rnds[i];
13
- return buf;
14
- }
15
- function v4(options, buf, offset) {
16
- if (globalThis.crypto?.randomUUID && !buf && !options) return globalThis.crypto.randomUUID();
17
- const bytes = v4Bytes(options?.random ?? rng(), buf, offset);
18
- return buf ?? formatUuid(bytes);
19
- }
20
- function isValid(id) {
21
- return UUID_V4_REGEX.test(id);
22
- }
23
- /**
24
- * Generate a UUID v4 string or write the bytes into a buffer.
25
- * It also includes helpers to convert to and from byte arrays.
26
- */
27
- const uuidv4 = Object.assign(v4, {
28
- toBytes: parseUuid,
29
- fromBytes: formatUuid,
30
- isValid
31
- });
32
-
33
- //#endregion
34
- export { uuidv4 };
1
+ import{t as e}from"../random-pEE8mU9d.mjs";import{n as t,t as n}from"../uuid-BWvd3MWD.mjs";const r=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function i(e,t,n=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(e[6]=e[6]&15|64,e[8]=e[8]&63|128,!t)return e;if(n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let r=0;r<16;r+=1)t[n+r]=e[r];return t}function a(t,r,a){if(globalThis.crypto?.randomUUID&&!r&&!t)return globalThis.crypto.randomUUID();let o=i(t?.random??e(),r,a);return r??n(o)}function o(e){return r.test(e)}const s=Object.assign(a,{toBytes:t,fromBytes:n,isValid:o});export{s as uuidv4};
35
2
  //# sourceMappingURL=v4.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"v4.mjs","names":["uuidv4: UuidV4"],"sources":["../../src/uuid/v4.ts"],"sourcesContent":["import { rng } from './common/random'\nimport { formatUuid, parseUuid } from './common/uuid'\n\nexport type Version4Options = {\n /**\n * 16 bytes of random data to use for UUID generation.\n * Note: Bytes at index 6 and 8 will be modified in-place to set version/variant bits.\n */\n random?: Uint8Array\n}\n\nexport type UuidV4 = {\n (): string\n <TBuf extends Uint8Array = Uint8Array>(options: Version4Options | undefined, buf: TBuf, offset?: number): TBuf\n (options?: Version4Options, buf?: undefined, offset?: number): string\n toBytes(id: string): Uint8Array\n fromBytes(bytes: Uint8Array): string\n isValid(id: string): boolean\n}\n\nconst UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\n\nfunction v4Bytes(rnds: Uint8Array, buf?: Uint8Array, offset = 0): Uint8Array {\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16')\n }\n\n // Set RFC 4122 version (4) and variant (10xx) bits.\n // Note: This modifies the input array in-place.\n rnds[6] = (rnds[6] & 0x0f) | 0x40\n rnds[8] = (rnds[8] & 0x3f) | 0x80\n\n if (!buf) {\n // No output buffer provided - return the modified random bytes directly\n return rnds\n }\n\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`)\n }\n\n // Copy 16 UUID bytes into the provided buffer slice.\n for (let i = 0; i < 16; i += 1) {\n buf[offset + i] = rnds[i]\n }\n\n return buf\n}\n\n/*\n * Overload: no buffer => return a UUID string.\n */\nfunction v4(options?: Version4Options, buf?: undefined, offset?: number): string\n/*\n * Overload: caller provides a buffer slice to fill with UUID bytes.\n */\nfunction v4<TBuf extends Uint8Array = Uint8Array>(\n options: Version4Options | undefined,\n buf: TBuf,\n offset?: number,\n): TBuf\nfunction v4<TBuf extends Uint8Array = Uint8Array>(\n options?: Version4Options,\n buf?: TBuf,\n offset?: number,\n): string | TBuf {\n if (globalThis.crypto?.randomUUID && !buf && !options) {\n return globalThis.crypto.randomUUID()\n }\n\n const bytes = v4Bytes(options?.random ?? rng(), buf, offset)\n return buf ?? formatUuid(bytes)\n}\n\nfunction isValid(id: string): boolean {\n return UUID_V4_REGEX.test(id)\n}\n\n/**\n * Generate a UUID v4 string or write the bytes into a buffer.\n * It also includes helpers to convert to and from byte arrays.\n */\nexport const uuidv4: UuidV4 = Object.assign(v4, {\n toBytes: parseUuid,\n fromBytes: formatUuid,\n isValid,\n})\n"],"mappings":";;;;AAoBA,MAAM,gBAAgB;AAEtB,SAAS,QAAQ,MAAkB,KAAkB,SAAS,GAAe;AAC3E,KAAI,KAAK,SAAS,GAChB,OAAM,IAAI,MAAM,oCAAoC;AAKtD,MAAK,KAAM,KAAK,KAAK,KAAQ;AAC7B,MAAK,KAAM,KAAK,KAAK,KAAQ;AAE7B,KAAI,CAAC,IAEH,QAAO;AAGT,KAAI,SAAS,KAAK,SAAS,KAAK,IAAI,OAClC,OAAM,IAAI,WAAW,mBAAmB,OAAO,GAAG,SAAS,GAAG,0BAA0B;AAI1F,MAAK,IAAI,IAAI,GAAG,IAAI,IAAI,KAAK,EAC3B,KAAI,SAAS,KAAK,KAAK;AAGzB,QAAO;;AAeT,SAAS,GACP,SACA,KACA,QACe;AACf,KAAI,WAAW,QAAQ,cAAc,CAAC,OAAO,CAAC,QAC5C,QAAO,WAAW,OAAO,YAAY;CAGvC,MAAM,QAAQ,QAAQ,SAAS,UAAU,KAAK,EAAE,KAAK,OAAO;AAC5D,QAAO,OAAO,WAAW,MAAM;;AAGjC,SAAS,QAAQ,IAAqB;AACpC,QAAO,cAAc,KAAK,GAAG;;;;;;AAO/B,MAAaA,SAAiB,OAAO,OAAO,IAAI;CAC9C,SAAS;CACT,WAAW;CACX;CACD,CAAC"}
1
+ {"version":3,"file":"v4.mjs","names":["uuidv4: UuidV4"],"sources":["../../src/uuid/v4.ts"],"sourcesContent":["import { rng } from './common/random'\nimport { formatUuid, parseUuid } from './common/uuid'\n\nexport type Version4Options = {\n /**\n * 16 bytes of random data to use for UUID generation.\n * Note: Bytes at index 6 and 8 will be modified in-place to set version/variant bits.\n */\n random?: Uint8Array\n}\n\nexport type UuidV4 = {\n (): string\n <TBuf extends Uint8Array = Uint8Array>(options: Version4Options | undefined, buf: TBuf, offset?: number): TBuf\n (options?: Version4Options, buf?: undefined, offset?: number): string\n toBytes(id: string): Uint8Array\n fromBytes(bytes: Uint8Array): string\n isValid(id: string): boolean\n}\n\nconst UUID_V4_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\n\nfunction v4Bytes(rnds: Uint8Array, buf?: Uint8Array, offset = 0): Uint8Array {\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16')\n }\n\n // Set RFC 4122 version (4) and variant (10xx) bits.\n // Note: This modifies the input array in-place.\n rnds[6] = (rnds[6] & 0x0f) | 0x40\n rnds[8] = (rnds[8] & 0x3f) | 0x80\n\n if (!buf) {\n // No output buffer provided - return the modified random bytes directly\n return rnds\n }\n\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`)\n }\n\n // Copy 16 UUID bytes into the provided buffer slice.\n for (let i = 0; i < 16; i += 1) {\n buf[offset + i] = rnds[i]\n }\n\n return buf\n}\n\n/*\n * Overload: no buffer => return a UUID string.\n */\nfunction v4(options?: Version4Options, buf?: undefined, offset?: number): string\n/*\n * Overload: caller provides a buffer slice to fill with UUID bytes.\n */\nfunction v4<TBuf extends Uint8Array = Uint8Array>(\n options: Version4Options | undefined,\n buf: TBuf,\n offset?: number,\n): TBuf\nfunction v4<TBuf extends Uint8Array = Uint8Array>(\n options?: Version4Options,\n buf?: TBuf,\n offset?: number,\n): string | TBuf {\n if (globalThis.crypto?.randomUUID && !buf && !options) {\n return globalThis.crypto.randomUUID()\n }\n\n const bytes = v4Bytes(options?.random ?? rng(), buf, offset)\n return buf ?? formatUuid(bytes)\n}\n\nfunction isValid(id: string): boolean {\n return UUID_V4_REGEX.test(id)\n}\n\n/**\n * Generate a UUID v4 string or write the bytes into a buffer.\n * It also includes helpers to convert to and from byte arrays.\n */\nexport const uuidv4: UuidV4 = Object.assign(v4, {\n toBytes: parseUuid,\n fromBytes: formatUuid,\n isValid,\n})\n"],"mappings":"2FAoBA,MAAM,EAAgB,yEAEtB,SAAS,EAAQ,EAAkB,EAAkB,EAAS,EAAe,CAC3E,GAAI,EAAK,OAAS,GAChB,MAAU,MAAM,oCAAoC,CAQtD,GAHA,EAAK,GAAM,EAAK,GAAK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d.mts","names":["uuidv7: UuidV7"],"sources":["../../src/uuid/v7.ts"],"sourcesContent":[],"mappings":";KAEY,eAAA;EAAZ;AAUA;;;EAEkD,MAAA,CAAA,EAPvC,UAOuC;EAAkC,KAAA,CAAA,EAAA,MAAA;EAAwB,GAAA,CAAA,EAAA,MAAA;CAC/F;AACU,KAJX,MAAA,GAIW;EACJ,EAAA,EAAA,MAAA;EAAA,CAAA,aAHH,UAGG,GAHU,UAGV,CAAA,CAAA,OAAA,EAH+B,eAG/B,GAAA,SAAA,EAAA,GAAA,EAHiE,IAGjE,EAAA,MAAA,CAAA,EAAA,MAAA,CAAA,EAHyF,IAGzF;EAgJnB,CAAA,OAAqB,CAARA,EAlJA,eAkJQ,EAAA,GAAA,CAAA,EAAA,SAAA,EAAA,MAAA,CAAA,EAAA,MAAA,CAAA,EAAA,MAAA;uBAjJE;mBACJ;;;;;;;;cAgJNA,QAAQ"}
package/build/uuid/v7.mjs CHANGED
@@ -1,94 +1,2 @@
1
- import { t as rng } from "../random-Dul5R6oJ.mjs";
2
- import { n as parseUuid, t as formatUuid } from "../uuid-cJ5hOOIR.mjs";
3
-
4
- //#region src/uuid/v7.ts
5
- const UUID_V7_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
6
- /**
7
- * Module-level state for maintaining monotonic ordering within the same millisecond.
8
- *
9
- * IMPORTANT: This state persists across all uuidv7() calls in the module's lifetime.
10
- * - In serverless/edge functions with warm starts, state persists between invocations.
11
- * - For isolated state, pass explicit `msecs` and `seq` via options.
12
- * - Tests should mock Date.now() or provide explicit options for deterministic behavior.
13
- */
14
- const state = {};
15
- function updateV7State(current, now, rnds) {
16
- current.msecs ??= -Infinity;
17
- current.seq ??= 0;
18
- if (now > current.msecs) {
19
- current.seq = rnds[6] << 23 | rnds[7] << 16 | rnds[8] << 8 | rnds[9];
20
- current.msecs = now;
21
- } else {
22
- current.seq = current.seq + 1 | 0;
23
- if (current.seq === 0) current.msecs += 1;
24
- }
25
- return current;
26
- }
27
- function v7Bytes(rnds, msecs, seq, buf, offset = 0) {
28
- if (rnds.length < 16) throw new Error("Random bytes length must be >= 16");
29
- if (!buf) {
30
- buf = new Uint8Array(16);
31
- offset = 0;
32
- } else if (offset < 0 || offset + 16 > buf.length) throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`);
33
- msecs ??= Date.now();
34
- seq ??= rnds[6] * 127 << 24 | rnds[7] << 16 | rnds[8] << 8 | rnds[9];
35
- buf[offset++] = msecs / 1099511627776 & 255;
36
- buf[offset++] = msecs / 4294967296 & 255;
37
- buf[offset++] = msecs / 16777216 & 255;
38
- buf[offset++] = msecs / 65536 & 255;
39
- buf[offset++] = msecs / 256 & 255;
40
- buf[offset++] = msecs & 255;
41
- buf[offset++] = 112 | seq >>> 28 & 15;
42
- buf[offset++] = seq >>> 20 & 255;
43
- buf[offset++] = 128 | seq >>> 14 & 63;
44
- buf[offset++] = seq >>> 6 & 255;
45
- buf[offset++] = seq << 2 & 255 | rnds[10] & 3;
46
- buf[offset++] = rnds[11];
47
- buf[offset++] = rnds[12];
48
- buf[offset++] = rnds[13];
49
- buf[offset++] = rnds[14];
50
- buf[offset++] = rnds[15];
51
- return buf;
52
- }
53
- function v7(options, buf, offset) {
54
- let bytes;
55
- if (options) bytes = v7Bytes(options.random ?? rng(), options.msecs, options.seq, buf, offset);
56
- else {
57
- /**
58
- * Note: by default, Cloudflare Workers "freezes" time during request handling to prevent
59
- * side-channel attacks. This means that Date.now() will return the same value for the entire
60
- * duration of a request.
61
- * Implications:
62
- * - all UUIDv7 generated within a single request will have the same timestamp.
63
- * - the monotonic ordering will rely entirely on the `state.seq` counter
64
- */
65
- const now = Date.now();
66
- const rnds = rng();
67
- updateV7State(state, now, rnds);
68
- bytes = v7Bytes(rnds, state.msecs, state.seq, buf, offset);
69
- }
70
- return buf ?? formatUuid(bytes);
71
- }
72
- function timestamp(id) {
73
- const bytes = parseUuid(id);
74
- let msecs = 0;
75
- for (let i = 0; i < 6; i += 1) msecs = msecs * 256 + bytes[i];
76
- return msecs;
77
- }
78
- function isValid(id) {
79
- return UUID_V7_REGEX.test(id);
80
- }
81
- /**
82
- * Generate a UUID v7 string or write the bytes into a buffer.
83
- * It also includes helpers to convert to and from byte arrays.j
84
- */
85
- const uuidv7 = Object.assign(v7, {
86
- toBytes: parseUuid,
87
- fromBytes: formatUuid,
88
- timestamp,
89
- isValid
90
- });
91
-
92
- //#endregion
93
- export { uuidv7 };
1
+ import{n as e,t}from"../uuid-BWvd3MWD.mjs";const n=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,r=new Uint8Array(256);let i=256;function a(){i>240&&(crypto.getRandomValues(r),i=0);let e=i;return i+=16,r.subarray(e,i)}const o=new Uint8Array(16),s={msecs:-1/0,seq:0};function c(e,t,n,r,i=0){if(e.length<16)throw Error(`Random bytes length must be >= 16`);if(i<0||i+16>r.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return t??=Date.now(),n??=e[6]*127<<24|e[7]<<16|e[8]<<8|e[9],r[i++]=t/1099511627776&255,r[i++]=t/4294967296&255,r[i++]=t/16777216&255,r[i++]=t/65536&255,r[i++]=t/256&255,r[i++]=t&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|e[10]&3,r[i++]=e[11],r[i++]=e[12],r[i++]=e[13],r[i++]=e[14],r[i++]=e[15],r}function l(e,n,r){let i;if(e)i=c(e.random??a(),e.msecs,e.seq,n??o,n?r:0);else{let e=Date.now(),t=a();e>s.msecs?(s.seq=t[6]<<23|t[7]<<16|t[8]<<8|t[9],s.msecs=e):(s.seq=s.seq+1|0,s.seq===0&&s.msecs++),i=c(t,s.msecs,s.seq,n??o,n?r:0)}return n?i:t(i)}function u(t){let n=e(t),r=0;for(let e=0;e<6;e+=1)r=r*256+n[e];return r}function d(e){return n.test(e)}const f=Object.assign(l,{toBytes:e,fromBytes:t,timestamp:u,isValid:d});export{f as uuidv7};
94
2
  //# sourceMappingURL=v7.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"v7.mjs","names":["state: V7State","bytes: Uint8Array","uuidv7: UuidV7"],"sources":["../../src/uuid/v7.ts"],"sourcesContent":["import { rng } from './common/random'\nimport { formatUuid, parseUuid } from './common/uuid'\n\nexport type Version7Options = {\n /**\n * 16 bytes of random data to use for UUID generation.\n * Note: Several bytes will be overwritten with timestamp, version, and variant data.\n */\n random?: Uint8Array\n msecs?: number\n seq?: number\n}\n\nexport type UuidV7 = {\n (): string\n <TBuf extends Uint8Array = Uint8Array>(options: Version7Options | undefined, buf: TBuf, offset?: number): TBuf\n (options?: Version7Options, 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\nconst UUID_V7_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\n\ntype V7State = {\n msecs?: number\n seq?: number\n}\n\n/**\n * Module-level state for maintaining monotonic ordering within the same millisecond.\n *\n * IMPORTANT: This state persists across all uuidv7() 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 `seq` via options.\n * - Tests should mock Date.now() or provide explicit options for deterministic behavior.\n */\nconst state: V7State = {}\n\nfunction updateV7State(current: V7State, now: number, rnds: Uint8Array): V7State {\n // Initialize state on first call (-Infinity ensures any real timestamp is greater)\n current.msecs ??= -Infinity\n current.seq ??= 0\n\n if (now > current.msecs) {\n // New millisecond tick: reseed sequence from random bytes.\n current.seq = (rnds[6] << 23) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]\n current.msecs = now\n } else {\n // Same millisecond: increment sequence, roll over into the next tick if needed.\n current.seq = (current.seq + 1) | 0\n if (current.seq === 0) {\n current.msecs += 1\n }\n }\n\n return current\n}\n\nfunction v7Bytes(rnds: Uint8Array, msecs?: number, seq?: number, buf?: Uint8Array, offset = 0): Uint8Array {\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16')\n }\n\n if (!buf) {\n buf = new Uint8Array(16)\n offset = 0\n } else if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`)\n }\n\n msecs ??= Date.now()\n // Derive a 30-bit sequence if not provided by the caller.\n seq ??= ((rnds[6] * 0x7f) << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]\n\n // Timestamp (48-bit big-endian milliseconds since Unix epoch).\n buf[offset++] = (msecs / 0x10000000000) & 0xff\n buf[offset++] = (msecs / 0x100000000) & 0xff\n buf[offset++] = (msecs / 0x1000000) & 0xff\n buf[offset++] = (msecs / 0x10000) & 0xff\n buf[offset++] = (msecs / 0x100) & 0xff\n buf[offset++] = msecs & 0xff\n\n // Set version (7) and variant (10xx), then pack sequence and random tail bytes.\n buf[offset++] = 0x70 | ((seq >>> 28) & 0x0f)\n buf[offset++] = (seq >>> 20) & 0xff\n buf[offset++] = 0x80 | ((seq >>> 14) & 0x3f)\n buf[offset++] = (seq >>> 6) & 0xff\n // Lower seq bits plus 2 random bits to complete the 128-bit payload.\n buf[offset++] = ((seq << 2) & 0xff) | (rnds[10] & 0x03)\n buf[offset++] = rnds[11]\n buf[offset++] = rnds[12]\n buf[offset++] = rnds[13]\n buf[offset++] = rnds[14]\n buf[offset++] = rnds[15]\n\n return buf\n}\n\n/*\n * Overload: no buffer => return a UUID string.\n */\nfunction v7(options?: Version7Options, buf?: undefined, offset?: number): string\n/*\n * Overload: caller provides a buffer slice to fill with UUID bytes.\n */\nfunction v7<TBuf extends Uint8Array = Uint8Array>(\n options: Version7Options | undefined,\n buf: TBuf,\n offset?: number,\n): TBuf\nfunction v7<TBuf extends Uint8Array = Uint8Array>(\n options?: Version7Options,\n buf?: TBuf,\n offset?: number,\n): string | TBuf {\n let bytes: Uint8Array\n\n if (options) {\n bytes = v7Bytes(options.random ?? rng(), options.msecs, options.seq, buf, offset)\n } else {\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 UUIDv7 generated within a single request will have the same timestamp.\n * - the monotonic ordering will rely entirely on the `state.seq` counter\n */\n const now = Date.now()\n const rnds = rng()\n\n updateV7State(state, now, rnds)\n\n bytes = v7Bytes(rnds, state.msecs, state.seq, buf, offset)\n }\n\n return buf ?? formatUuid(bytes)\n}\n\nfunction timestamp(id: string): number {\n const bytes = parseUuid(id)\n let msecs = 0\n for (let i = 0; i < 6; i += 1) {\n msecs = msecs * 256 + bytes[i]\n }\n return msecs\n}\n\nfunction isValid(id: string): boolean {\n return UUID_V7_REGEX.test(id)\n}\n\n/**\n * Generate a UUID v7 string or write the bytes into a buffer.\n * It also includes helpers to convert to and from byte arrays.j\n */\nexport const uuidv7: UuidV7 = Object.assign(v7, {\n toBytes: parseUuid,\n fromBytes: formatUuid,\n timestamp,\n isValid,\n})\n"],"mappings":";;;;AAuBA,MAAM,gBAAgB;;;;;;;;;AAetB,MAAMA,QAAiB,EAAE;AAEzB,SAAS,cAAc,SAAkB,KAAa,MAA2B;AAE/E,SAAQ,UAAU;AAClB,SAAQ,QAAQ;AAEhB,KAAI,MAAM,QAAQ,OAAO;AAEvB,UAAQ,MAAO,KAAK,MAAM,KAAO,KAAK,MAAM,KAAO,KAAK,MAAM,IAAK,KAAK;AACxE,UAAQ,QAAQ;QACX;AAEL,UAAQ,MAAO,QAAQ,MAAM,IAAK;AAClC,MAAI,QAAQ,QAAQ,EAClB,SAAQ,SAAS;;AAIrB,QAAO;;AAGT,SAAS,QAAQ,MAAkB,OAAgB,KAAc,KAAkB,SAAS,GAAe;AACzG,KAAI,KAAK,SAAS,GACh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AAK,IAAI,IAAI,GAAG,IAAI,GAAG,KAAK,EAC1B,SAAQ,QAAQ,MAAM,MAAM;AAE9B,QAAO;;AAGT,SAAS,QAAQ,IAAqB;AACpC,QAAO,cAAc,KAAK,GAAG;;;;;;AAO/B,MAAaC,SAAiB,OAAO,OAAO,IAAI;CAC9C,SAAS;CACT,WAAW;CACX;CACA;CACD,CAAC"}
1
+ {"version":3,"file":"v7.mjs","names":["state: V7State","bytes: Uint8Array","uuidv7: UuidV7"],"sources":["../../src/uuid/v7.ts"],"sourcesContent":["import { formatUuid, parseUuid } from './common/uuid'\n\nexport type Version7Options = {\n /**\n * 16 bytes of random data to use for UUID generation.\n * Note: Several bytes will be overwritten with timestamp, version, and variant data.\n */\n random?: Uint8Array\n msecs?: number\n seq?: number\n}\n\nexport type UuidV7 = {\n (): string\n <TBuf extends Uint8Array = Uint8Array>(options: Version7Options | undefined, buf: TBuf, offset?: number): TBuf\n (options?: Version7Options, 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\nconst UUID_V7_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i\n\n// Simple random pool (matches uuid npm approach)\nconst POOL_SIZE = 256\nconst rnds8Pool = new Uint8Array(POOL_SIZE)\nlet poolPtr = POOL_SIZE // Start exhausted to trigger first fill\n\nfunction rng(): Uint8Array {\n if (poolPtr > POOL_SIZE - 16) {\n crypto.getRandomValues(rnds8Pool)\n poolPtr = 0\n }\n const start = poolPtr\n poolPtr += 16\n return rnds8Pool.subarray(start, poolPtr)\n}\n\n// Reusable buffer for string output path - avoids allocation per call.\n// Safe because bytes are consumed synchronously by formatUuid().\nconst reusableBuf = new Uint8Array(16)\n\ntype V7State = {\n msecs: number\n seq: number\n}\n\n/**\n * Module-level state for maintaining monotonic ordering within the same millisecond.\n *\n * IMPORTANT: This state persists across all uuidv7() 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 `seq` via options.\n * - Tests should mock Date.now() or provide explicit options for deterministic behavior.\n */\nconst state: V7State = { msecs: -Infinity, seq: 0 }\n\nfunction v7Bytes(\n rnds: Uint8Array,\n msecs: number | undefined,\n seq: number | undefined,\n buf: Uint8Array,\n offset = 0,\n): Uint8Array {\n if (rnds.length < 16) {\n throw new Error('Random bytes length must be >= 16')\n }\n\n if (offset < 0 || offset + 16 > buf.length) {\n throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`)\n }\n\n msecs ??= Date.now()\n // Derive a 30-bit sequence if not provided by the caller.\n seq ??= ((rnds[6] * 0x7f) << 24) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]\n\n // Timestamp (48-bit big-endian milliseconds since Unix epoch).\n buf[offset++] = (msecs / 0x10000000000) & 0xff\n buf[offset++] = (msecs / 0x100000000) & 0xff\n buf[offset++] = (msecs / 0x1000000) & 0xff\n buf[offset++] = (msecs / 0x10000) & 0xff\n buf[offset++] = (msecs / 0x100) & 0xff\n buf[offset++] = msecs & 0xff\n\n // Set version (7) and variant (10xx), then pack sequence and random tail bytes.\n buf[offset++] = 0x70 | ((seq >>> 28) & 0x0f)\n buf[offset++] = (seq >>> 20) & 0xff\n buf[offset++] = 0x80 | ((seq >>> 14) & 0x3f)\n buf[offset++] = (seq >>> 6) & 0xff\n // Lower seq bits plus 2 random bits to complete the 128-bit payload.\n buf[offset++] = ((seq << 2) & 0xff) | (rnds[10] & 0x03)\n buf[offset++] = rnds[11]\n buf[offset++] = rnds[12]\n buf[offset++] = rnds[13]\n buf[offset++] = rnds[14]\n buf[offset++] = rnds[15]\n\n return buf\n}\n\n/*\n * Overload: no buffer => return a UUID string.\n */\nfunction v7(options?: Version7Options, buf?: undefined, offset?: number): string\n/*\n * Overload: caller provides a buffer slice to fill with UUID bytes.\n */\nfunction v7<TBuf extends Uint8Array = Uint8Array>(\n options: Version7Options | undefined,\n buf: TBuf,\n offset?: number,\n): TBuf\nfunction v7<TBuf extends Uint8Array = Uint8Array>(\n options?: Version7Options,\n buf?: TBuf,\n offset?: number,\n): string | TBuf {\n let bytes: Uint8Array\n\n if (options) {\n bytes = v7Bytes(options.random ?? rng(), options.msecs, options.seq, buf ?? reusableBuf, buf ? offset : 0)\n } else {\n // HOT PATH: Inline state management and byte generation for best performance\n const now = Date.now()\n const rnds = rng()\n\n // Update state (inlined for performance)\n if (now > state.msecs) {\n state.seq = (rnds[6] << 23) | (rnds[7] << 16) | (rnds[8] << 8) | rnds[9]\n state.msecs = now\n } else {\n state.seq = (state.seq + 1) | 0\n if (state.seq === 0) {\n state.msecs++\n }\n }\n\n bytes = v7Bytes(rnds, state.msecs, state.seq, buf ?? reusableBuf, buf ? offset : 0)\n }\n\n return buf ? (bytes as TBuf) : formatUuid(bytes)\n}\n\nfunction timestamp(id: string): number {\n const bytes = parseUuid(id)\n let msecs = 0\n for (let i = 0; i < 6; i += 1) {\n msecs = msecs * 256 + bytes[i]\n }\n return msecs\n}\n\nfunction isValid(id: string): boolean {\n return UUID_V7_REGEX.test(id)\n}\n\n/**\n * Generate a UUID v7 string or write the bytes into a buffer.\n * It also includes helpers to convert to and from byte arrays.j\n */\nexport const uuidv7: UuidV7 = Object.assign(v7, {\n toBytes: parseUuid,\n fromBytes: formatUuid,\n timestamp,\n isValid,\n})\n"],"mappings":"2CAsBA,MAAM,EAAgB,yEAIhB,EAAY,IAAI,WAAW,IAAU,CAC3C,IAAI,EAAU,IAEd,SAAS,GAAkB,CACrB,EAAU,MACZ,OAAO,gBAAgB,EAAU,CACjC,EAAU,GAEZ,IAAM,EAAQ,EAEd,MADA,IAAW,GACJ,EAAU,SAAS,EAAO,EAAQ,CAK3C,MAAM,EAAc,IAAI,WAAW,GAAG,CAehCA,EAAiB,CAAE,MAAO,KAAW,IAAK,EAAG,CAEnD,SAAS,EACP,EACA,EACA,EACA,EACA,EA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EAAM,EAAS,EAAE,CAGrF,OAAO,EAAO,EAAiB,EAAW,EAAM,CAGlD,SAAS,EAAU,EAAoB,CACrC,IAAM,EAAQ,EAAU,EAAG,CACvB,EAAQ,EACZ,IAAK,IAAI,EAAI,EAAG,EAAI,EAAG,GAAK,EAC1B,EAAQ,EAAQ,IAAM,EAAM,GAE9B,OAAO,EAGT,SAAS,EAAQ,EAAqB,CACpC,OAAO,EAAc,KAAK,EAAG,CAO/B,MAAaC,EAAiB,OAAO,OAAO,EAAI,CAC9C,QAAS,EACT,UAAW,EACX,YACA,UACD,CAAC"}
@@ -0,0 +1,2 @@
1
+ const e=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,`0`));function t(e){return e>=48&&e<=57?e-48:e>=65&&e<=70?e-65+10:e>=97&&e<=102?e-97+10:-1}function n(e,n){if(e.length!==n.length*2)throw Error(`hex string must be ${n.length*2} chars, got ${e.length}`);for(let r=0;r<n.length;r+=1){let i=t(e.charCodeAt(r*2)),a=t(e.charCodeAt(r*2+1));if(i===-1||a===-1)throw Error(`hex string contains invalid characters`);n[r]=i<<4|a}}function r(t){return e[t[0]]+e[t[1]]+e[t[2]]+e[t[3]]+`-`+e[t[4]]+e[t[5]]+`-`+e[t[6]]+e[t[7]]+`-`+e[t[8]]+e[t[9]]+`-`+e[t[10]]+e[t[11]]+e[t[12]]+e[t[13]]+e[t[14]]+e[t[15]]}function i(e){if(e.length!==36)throw Error(`uuid string must be 36 characters`);if(e[8]!==`-`||e[13]!==`-`||e[18]!==`-`||e[23]!==`-`)throw Error(`uuid string has invalid separators`);let t=e.slice(0,8)+e.slice(9,13)+e.slice(14,18)+e.slice(19,23)+e.slice(24),r=new Uint8Array(16);return n(t,r),r}export{i as n,r as t};
2
+ //# sourceMappingURL=uuid-BWvd3MWD.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"uuid-BWvd3MWD.mjs","names":["HEX_TABLE: string[]"],"sources":["../src/uuid/common/hex.ts","../src/uuid/common/uuid.ts"],"sourcesContent":["// Pre-computed lookup table for byte-to-hex conversion (0x00 -> \"00\", 0xff -> \"ff\")\nexport const HEX_TABLE: string[] = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'))\n\nexport function bytesToHex(bytes: Uint8Array): string {\n // Build string directly, without intermediate array allocation\n let hex = ''\n for (let i = 0; i < bytes.length; i += 1) {\n hex += HEX_TABLE[bytes[i]]\n }\n return hex\n}\n\n// ASCII code ranges for hex character validation\nconst ASCII_0 = 48 // '0'\nconst ASCII_9 = 57 // '9'\nconst ASCII_A = 65 // 'A'\nconst ASCII_F = 70 // 'F'\nconst ASCII_a = 97 // 'a'\nconst ASCII_f = 102 // 'f'\n\nfunction hexValue(code: number): number {\n if (code >= ASCII_0 && code <= ASCII_9) {\n return code - ASCII_0\n }\n if (code >= ASCII_A && code <= ASCII_F) {\n return code - ASCII_A + 10\n }\n if (code >= ASCII_a && code <= ASCII_f) {\n return code - ASCII_a + 10\n }\n return -1 // Invalid hex character\n}\n\nexport function hexToBytes(hex: string, out: Uint8Array): void {\n if (hex.length !== out.length * 2) {\n throw new Error(`hex string must be ${out.length * 2} chars, got ${hex.length}`)\n }\n\n for (let i = 0; i < out.length; i += 1) {\n const hi = hexValue(hex.charCodeAt(i * 2))\n const lo = hexValue(hex.charCodeAt(i * 2 + 1))\n if (hi === -1 || lo === -1) {\n throw new Error('hex string contains invalid characters')\n }\n out[i] = (hi << 4) | lo\n }\n}\n","import { HEX_TABLE, hexToBytes } from './hex'\n\nconst UUID_BYTE_LENGTH = 16\nconst UUID_STRING_LENGTH = 36\n\nexport function formatUuid(bytes: Uint8Array): string {\n // Direct string concatenation - optimized for V8's string builder.\n // This approach avoids loop overhead and intermediate allocations.\n // See: https://github.com/uuidjs/uuid/pull/434\n return (\n HEX_TABLE[bytes[0]] +\n HEX_TABLE[bytes[1]] +\n HEX_TABLE[bytes[2]] +\n HEX_TABLE[bytes[3]] +\n '-' +\n HEX_TABLE[bytes[4]] +\n HEX_TABLE[bytes[5]] +\n '-' +\n HEX_TABLE[bytes[6]] +\n HEX_TABLE[bytes[7]] +\n '-' +\n HEX_TABLE[bytes[8]] +\n HEX_TABLE[bytes[9]] +\n '-' +\n HEX_TABLE[bytes[10]] +\n HEX_TABLE[bytes[11]] +\n HEX_TABLE[bytes[12]] +\n HEX_TABLE[bytes[13]] +\n HEX_TABLE[bytes[14]] +\n HEX_TABLE[bytes[15]]\n )\n}\n\nexport function parseUuid(value: string): Uint8Array {\n if (value.length !== UUID_STRING_LENGTH) {\n throw new Error('uuid string must be 36 characters')\n }\n\n // Validate separator positions directly (more efficient than full loop)\n if (value[8] !== '-' || value[13] !== '-' || value[18] !== '-' || value[23] !== '-') {\n throw new Error('uuid string has invalid separators')\n }\n\n const hex = value.slice(0, 8) + value.slice(9, 13) + value.slice(14, 18) + value.slice(19, 23) + value.slice(24)\n\n const bytes = new Uint8Array(UUID_BYTE_LENGTH)\n hexToBytes(hex, bytes)\n return bytes\n}\n"],"mappings":"AACA,MAAaA,EAAsB,MAAM,KAAK,CAAE,OAAQ,IAAK,EAAG,EAAG,IAAM,EAAE,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAAC,CAmBzG,SAAS,EAAS,EAAsB,CAUtC,OATI,GAAQ,IAAW,GAAQ,GACtB,EAAO,GAEZ,GAAQ,IAAW,GAAQ,GACtB,EAAO,GAAU,GAEtB,GAAQ,IAAW,GAAQ,IACtB,EAAO,GAAU,GAEnB,GAGT,SAAgB,EAAW,EAAa,EAAuB,CAC7D,GAAI,EAAI,SAAW,EAAI,OAAS,EAC9B,MAAU,MAAM,sBAAsB,EAAI,OAAS,EAAE,cAAc,EAAI,SAAS,CAGlF,IAAK,IAAI,EAAI,EAAG,EAAI,EAAI,OAAQ,GAAK,EAAG,CACtC,IAAM,EAAK,EAAS,EAAI,WAAW,EAAI,EAAE,CAAC,CACpC,EAAK,EAAS,EAAI,WAAW,EAAI,EAAI,EAAE,CAAC,CAC9C,GAAI,IAAO,IAAM,IAAO,GACtB,MAAU,MAAM,yCAAyC,CAE3D,EAAI,GAAM,GAAM,EAAK,GCvCzB,SAAgB,EAAW,EAA2B,CAIpD,OACE,EAAU,EAAM,IAChB,EAAU,EAAM,IAChB,EAAU,EAAM,IAChB,EAAU,EAAM,IAChB,IACA,EAAU,EAAM,IAChB,EAAU,EAAM,IAChB,IACA,EAAU,EAAM,IAChB,EAAU,EAAM,IAChB,IACA,EAAU,EAAM,IAChB,EAAU,EAAM,IAChB,IACA,EAAU,EAAM,KAChB,EAAU,EAAM,KAChB,EAAU,EAAM,KAChB,EAAU,EAAM,KAChB,EAAU,EAAM,KAChB,EAAU,EAAM,KAIpB,SAAgB,EAAU,EAA2B,CACnD,GAAI,EAAM,SAAW,GACnB,MAAU,MAAM,oCAAoC,CAItD,GAAI,EAAM,KAAO,KAAO,EAAM,MAAQ,KAAO,EAAM,MAAQ,KAAO,EAAM,MAAQ,IAC9E,MAAU,MAAM,qCAAqC,CAGvD,IAAM,EAAM,EAAM,MAAM,EAAG,EAAE,CAAG,EAAM,MAAM,EAAG,GAAG,CAAG,EAAM,MAAM,GAAI,GAAG,CAAG,EAAM,MAAM,GAAI,GAAG,CAAG,EAAM,MAAM,GAAG,CAE1G,EAAQ,IAAI,WAAW,GAAiB,CAE9C,OADA,EAAW,EAAK,EAAM,CACf"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "private": false,
3
3
  "name": "uniku",
4
- "version": "0.0.4",
4
+ "version": "0.0.6",
5
5
  "description": "Minimal, tree-shakeable UUID utilities for every JavaScript runtime",
6
6
  "author": {
7
7
  "name": "Alberto Schiabel",
@@ -98,13 +98,26 @@
98
98
  "dependencies": {
99
99
  "@noble/hashes": "^2.0.1"
100
100
  },
101
+ "devDependencies": {
102
+ "@paralleldrive/cuid2": "^3.3.0",
103
+ "@types/bun": "^1.3.8",
104
+ "nanoid": "5.0.9",
105
+ "ulid": "2.3.0",
106
+ "uuid": "11.0.5"
107
+ },
101
108
  "scripts": {
102
109
  "clean": "rimraf build .turbo",
103
110
  "build": "tsdown --config-loader unrun",
104
111
  "build:watch": "tsdown --config-loader unrun --watch",
105
112
  "test": "vitest run",
106
113
  "test:unit": "vitest --project unit run",
107
- "bench": "vitest bench",
114
+ "test:integration": "vitest --project integration run",
115
+ "test:e2e": "pnpm --filter @uniku/e2e-cloudflare test:e2e",
116
+ "test:e2e:cloudflare": "pnpm --filter @uniku/e2e-cloudflare test:e2e:cloudflare",
117
+ "bench": "vitest bench --run",
118
+ "bench:compat": "vitest bench ./__tests__/bench/compat.bench.ts --run",
119
+ "bench:summary": "bun scripts/bench-summary.ts",
120
+ "bundle:summary": "bun scripts/bundle-summary.ts",
108
121
  "typecheck": "tsc --noEmit"
109
122
  }
110
123
  }
@@ -1,17 +0,0 @@
1
- //#region src/uuid/common/random.ts
2
- function randomBytes(out) {
3
- globalThis.crypto.getRandomValues(out);
4
- }
5
- /**
6
- * Generate 16 bytes of cryptographically strong random data.
7
- * Used internally by UUID generators.
8
- */
9
- function rng() {
10
- const bytes = new Uint8Array(16);
11
- randomBytes(bytes);
12
- return bytes;
13
- }
14
-
15
- //#endregion
16
- export { rng as t };
17
- //# sourceMappingURL=random-Dul5R6oJ.mjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"random-Dul5R6oJ.mjs","names":[],"sources":["../src/uuid/common/random.ts"],"sourcesContent":["export function randomBytes(out: Uint8Array): void {\n const crypto = globalThis.crypto\n crypto.getRandomValues(out)\n}\n\n/**\n * Generate 16 bytes of cryptographically strong random data.\n * Used internally by UUID generators.\n */\nexport function rng(): Uint8Array {\n const bytes = new Uint8Array(16)\n randomBytes(bytes)\n return bytes\n}\n"],"mappings":";AAAA,SAAgB,YAAY,KAAuB;AAEjD,CADe,WAAW,OACnB,gBAAgB,IAAI;;;;;;AAO7B,SAAgB,MAAkB;CAChC,MAAM,QAAQ,IAAI,WAAW,GAAG;AAChC,aAAY,MAAM;AAClB,QAAO"}
@@ -1,49 +0,0 @@
1
- //#region src/uuid/common/hex.ts
2
- const HEX_TABLE = Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
3
- function bytesToHex(bytes) {
4
- let hex = "";
5
- for (let i = 0; i < bytes.length; i += 1) hex += HEX_TABLE[bytes[i]];
6
- return hex;
7
- }
8
- const ASCII_0 = 48;
9
- const ASCII_9 = 57;
10
- const ASCII_A = 65;
11
- const ASCII_F = 70;
12
- const ASCII_a = 97;
13
- const ASCII_f = 102;
14
- function hexValue(code) {
15
- if (code >= ASCII_0 && code <= ASCII_9) return code - ASCII_0;
16
- if (code >= ASCII_A && code <= ASCII_F) return code - ASCII_A + 10;
17
- if (code >= ASCII_a && code <= ASCII_f) return code - ASCII_a + 10;
18
- return -1;
19
- }
20
- function hexToBytes(hex, out) {
21
- if (hex.length !== out.length * 2) throw new Error(`hex string must be ${out.length * 2} chars, got ${hex.length}`);
22
- for (let i = 0; i < out.length; i += 1) {
23
- const hi = hexValue(hex.charCodeAt(i * 2));
24
- const lo = hexValue(hex.charCodeAt(i * 2 + 1));
25
- if (hi === -1 || lo === -1) throw new Error("hex string contains invalid characters");
26
- out[i] = hi << 4 | lo;
27
- }
28
- }
29
-
30
- //#endregion
31
- //#region src/uuid/common/uuid.ts
32
- const UUID_BYTE_LENGTH = 16;
33
- const UUID_STRING_LENGTH = 36;
34
- function formatUuid(bytes) {
35
- const hex = bytesToHex(bytes);
36
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
37
- }
38
- function parseUuid(value) {
39
- if (value.length !== UUID_STRING_LENGTH) throw new Error("uuid string must be 36 characters");
40
- if (value[8] !== "-" || value[13] !== "-" || value[18] !== "-" || value[23] !== "-") throw new Error("uuid string has invalid separators");
41
- const hex = value.slice(0, 8) + value.slice(9, 13) + value.slice(14, 18) + value.slice(19, 23) + value.slice(24);
42
- const bytes = new Uint8Array(UUID_BYTE_LENGTH);
43
- hexToBytes(hex, bytes);
44
- return bytes;
45
- }
46
-
47
- //#endregion
48
- export { parseUuid as n, formatUuid as t };
49
- //# sourceMappingURL=uuid-cJ5hOOIR.mjs.map