-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathulid.ts
More file actions
158 lines (151 loc) · 4.91 KB
/
ulid.ts
File metadata and controls
158 lines (151 loc) · 4.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
import { incrementBase32 } from "./crockford.js";
import { ENCODING, ENCODING_LEN, RANDOM_LEN, TIME_LEN, TIME_MAX } from "./constants.js";
import { ULIDError, ULIDErrorCode } from "./error.js";
import { PRNG, ULID, ULIDFactory } from "./types.js";
import { randomChar } from "./utils.js";
/**
* Decode time from a ULID
* @param id The ULID
* @returns The decoded timestamp
*/
export function decodeTime(id: ULID): number {
if (id.length !== TIME_LEN + RANDOM_LEN) {
throw new ULIDError(ULIDErrorCode.DecodeTimeValueMalformed, "Malformed ULID");
}
const time = id
.substr(0, TIME_LEN)
.toUpperCase()
.split("")
.reverse()
.reduce((carry, char, index) => {
const encodingIndex = ENCODING.indexOf(char);
if (encodingIndex === -1) {
throw new ULIDError(
ULIDErrorCode.DecodeTimeInvalidCharacter,
`Time decode error: Invalid character: ${char}`
);
}
return (carry += encodingIndex * Math.pow(ENCODING_LEN, index));
}, 0);
if (time > TIME_MAX) {
throw new ULIDError(
ULIDErrorCode.DecodeTimeValueMalformed,
`Malformed ULID: timestamp too large: ${time}`
);
}
return time;
}
/**
* Detect the best PRNG (pseudo-random number generator)
* @param root The root to check from (global/window)
* @returns The PRNG function
*/
export function detectPRNG(root?: any): PRNG {
if (
"getRandomValues" in globalThis.crypto &&
typeof globalThis.crypto.getRandomValues === "function"
) {
return () => {
const buffer = new Uint8Array(1);
globalThis.crypto.getRandomValues(buffer);
return buffer[0] / 0xff;
};
}
throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
}
export function encodeRandom(len: number, prng: PRNG): string {
let str = "";
for (; len > 0; len--) {
str = randomChar(prng) + str;
}
return str;
}
/**
* Encode the time portion of a ULID
* @param now The current timestamp
* @param len Length to generate
* @returns The encoded time
*/
export function encodeTime(now: number, len: number = TIME_LEN): string {
if (isNaN(now)) {
throw new ULIDError(
ULIDErrorCode.EncodeTimeValueMalformed,
`Time must be a number: ${now}`
);
} else if (now > TIME_MAX) {
throw new ULIDError(
ULIDErrorCode.EncodeTimeSizeExceeded,
`Cannot encode a time larger than ${TIME_MAX}: ${now}`
);
} else if (now < 0) {
throw new ULIDError(ULIDErrorCode.EncodeTimeNegative, `Time must be positive: ${now}`);
} else if (Number.isInteger(now) === false) {
throw new ULIDError(
ULIDErrorCode.EncodeTimeValueMalformed,
`Time must be an integer: ${now}`
);
}
let mod: number,
str: string = "";
for (let currentLen = len; currentLen > 0; currentLen--) {
mod = now % ENCODING_LEN;
str = ENCODING.charAt(mod) + str;
now = (now - mod) / ENCODING_LEN;
}
return str;
}
/**
* Check if a ULID is valid
* @param id The ULID to test
* @returns True if valid, false otherwise
* @example
* isValid("01HNZX8JGFACFA36RBXDHEQN6E"); // true
* isValid(""); // false
*/
export function isValid(id: string): boolean {
return (
typeof id === "string" &&
id.length === TIME_LEN + RANDOM_LEN &&
id
.toUpperCase()
.split("")
.every(char => ENCODING.indexOf(char) !== -1)
);
}
/**
* Create a ULID factory to generate monotonically-increasing
* ULIDs
* @param prng The PRNG to use
* @returns A ulid factory
* @example
* const ulid = monotonicFactory();
* ulid(); // "01HNZXD07M5CEN5XA66EMZSRZW"
*/
export function monotonicFactory(prng?: PRNG): ULIDFactory {
const currentPRNG = prng || detectPRNG();
let lastTime: number = 0,
lastRandom: string;
return function _ulid(seedTime?: number): ULID {
const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
if (seed <= lastTime) {
const incrementedRandom = (lastRandom = incrementBase32(lastRandom));
return encodeTime(lastTime, TIME_LEN) + incrementedRandom;
}
lastTime = seed;
const newRandom = (lastRandom = encodeRandom(RANDOM_LEN, currentPRNG));
return encodeTime(seed, TIME_LEN) + newRandom;
};
}
/**
* Generate a ULID
* @param seedTime Optional time seed
* @param prng Optional PRNG function
* @returns A ULID string
* @example
* ulid(); // "01HNZXD07M5CEN5XA66EMZSRZW"
*/
export function ulid(seedTime?: number, prng?: PRNG): ULID {
const currentPRNG = prng || detectPRNG();
const seed = !seedTime || isNaN(seedTime) ? Date.now() : seedTime;
return encodeTime(seed, TIME_LEN) + encodeRandom(RANDOM_LEN, currentPRNG);
}