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