cuid-range
Version:
Generate and validate CUID between two bounds. Useful for order-preserving pagination keys, gap insertion, or sequence IDs.
85 lines (83 loc) • 2.83 kB
JavaScript
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
generateCuidBetween: () => generateCuidBetween,
isCuidBetween: () => isCuidBetween
});
module.exports = __toCommonJS(index_exports);
var ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
var MIN = 0;
var MAX = ALPHABET.length - 1;
function assertAllInAlphabet(s) {
for (const ch of s) {
if (ALPHABET.indexOf(ch) === -1) throw new Error("Invalid CUID");
}
}
function validateRange(start, end) {
if (start.length === 0) throw new Error("Invalid CUID range");
if (start.length > end.length) throw new Error("Invalid CUID range");
assertAllInAlphabet(start);
assertAllInAlphabet(end);
if (start > end) throw new Error("Invalid CUID range");
}
function generateCuidBetween(start, end) {
if (start === end) {
assertAllInAlphabet(start);
return start;
}
validateRange(start, end);
const length = Math.max(start.length, end.length);
let res = "";
let prefixStart = true;
let prefixEnd = true;
for (let i = 0; i < length; i++) {
const sCh = prefixStart ? start[i] ?? ALPHABET[MIN] : ALPHABET[MIN];
const eCh = prefixEnd ? end[i] ?? ALPHABET[MAX] : ALPHABET[MAX];
const sIdx = ALPHABET.indexOf(sCh);
const eIdx = ALPHABET.indexOf(eCh);
if (sIdx === -1 || eIdx === -1 || sIdx > eIdx) {
throw new Error("Invalid CUID range");
}
const range = ALPHABET.substring(sIdx, eIdx + 1);
const pick = range[Math.floor(Math.random() * range.length)];
res += pick;
if (prefixStart) {
prefixStart = pick === (start[i] ?? ALPHABET[MIN]);
}
if (prefixEnd) {
prefixEnd = pick === (end[i] ?? ALPHABET[MAX]);
}
}
return res;
}
function isCuidBetween(cuid, start, end) {
assertAllInAlphabet(cuid);
if (start === end) {
assertAllInAlphabet(start);
return cuid === start;
}
validateRange(start, end);
return start <= cuid && cuid <= end;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
generateCuidBetween,
isCuidBetween
});