-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathulid.ts
More file actions
191 lines (180 loc) · 5.96 KB
/
ulid.ts
File metadata and controls
191 lines (180 loc) · 5.96 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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
import crypto from "node:crypto";
import { incrementBase32 } from "./crockford.js";
import { ENCODING, ENCODING_LEN, ENCODING_LOOKUP, 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
.substring(0, TIME_LEN)
.toUpperCase()
.split("")
.reverse()
.reduce((carry, char, index) => {
const encodingIndex = ENCODING_LOOKUP.get(char);
if (encodingIndex === undefined) {
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;
}
export function detectPRNGMemoized(): () => PRNG {
let prng: PRNG | null = null;
return (): PRNG => {
if (prng === null) {
prng = detectPRNG();
}
return prng;
};
}
// memoized prng detector for performance
const getPRNG = detectPRNGMemoized();
/**
* 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 {
const rootLookup = root || detectRoot();
const globalCrypto =
(rootLookup && (rootLookup.crypto || rootLookup.msCrypto)) ||
(typeof crypto !== "undefined" ? crypto : null);
if (typeof globalCrypto?.getRandomValues === "function") {
const buffer = new Uint8Array(1);
return () => {
globalCrypto.getRandomValues(buffer);
return buffer[0] / 0xff;
};
} else if (typeof globalCrypto?.randomBytes === "function") {
return () => globalCrypto.randomBytes(1).readUInt8() / 0xff;
} else if (crypto?.randomBytes) {
return () => crypto.randomBytes(1).readUInt8() / 0xff;
}
throw new ULIDError(ULIDErrorCode.PRNGDetectFailure, "Failed to find a reliable PRNG");
}
function detectRoot(): any {
if (inWebWorker()) return self;
if (typeof window !== "undefined") {
return window;
}
if (typeof global !== "undefined") {
return global;
}
if (typeof globalThis !== "undefined") {
return globalThis;
}
return null;
}
export function encodeRandom(len: number, prng: PRNG): string {
const str = new Array(len);
for (let currentLen = len; currentLen > 0; currentLen--) {
str[currentLen - 1] = randomChar(prng);
}
return str.join("");
}
/**
* 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 (Number.isInteger(now) === false) {
throw new ULIDError(
ULIDErrorCode.EncodeTimeValueMalformed,
`Time must be an integer: ${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}`);
}
let mod: number;
const str = new Array(len);
for (let currentLen = len; currentLen > 0; currentLen--) {
mod = now % ENCODING_LEN;
str[currentLen - 1] = ENCODING[mod];
now = (now - mod) / ENCODING_LEN;
}
return str.join("");
}
function inWebWorker(): boolean {
// @ts-ignore
return typeof WorkerGlobalScope !== "undefined" && self instanceof WorkerGlobalScope;
}
/**
* 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_LOOKUP.has(char))
);
}
/**
* 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 || getPRNG();
let lastTime: number = 0,
lastRandom: string;
return function _ulid(seedTime?: number): ULID {
const seed = typeof seedTime === 'undefined' ? 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 || getPRNG();
const seed = typeof seedTime === 'undefined' ? Date.now() : seedTime;
return encodeTime(seed, TIME_LEN) + encodeRandom(RANDOM_LEN, currentPRNG);
}