Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

short-unique-id

Package Overview
Dependencies
Maintainers
1
Versions
43
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

short-unique-id - npm Package Compare versions

Comparing version 4.3.3 to 4.3.4

dist/index.d.ts

643

dist/short-unique-id.js

@@ -1,445 +0,214 @@

(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.ShortUniqueId = factory());
}(this, (function () { 'use strict';
var __defProp = Object.defineProperty;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __markAsModule = (target) => __defProp(target, "__esModule", { value: true });
var __export = (target, all) => {
__markAsModule(target);
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
/*! *****************************************************************************
Copyright (c) Microsoft Corporation.
// src/index.ts
__export(exports, {
DEFAULT_UUID_LENGTH: () => DEFAULT_UUID_LENGTH,
default: () => ShortUniqueId
});
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted.
// package.json
var version = "4.3.4";
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
***************************************************************************** */
/* global Reflect, Promise */
var extendStatics = function(d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
// src/index.ts
var DEFAULT_UUID_LENGTH = 6;
var DEFAULT_OPTIONS = {
dictionary: "alphanum",
shuffle: true,
debug: false,
length: DEFAULT_UUID_LENGTH
};
var _ShortUniqueId = class extends Function {
constructor(argOptions = {}) {
super();
this.dictIndex = 0;
this.dictRange = [];
this.lowerBound = 0;
this.upperBound = 0;
this.dictLength = 0;
this._digit_first_ascii = 48;
this._digit_last_ascii = 58;
this._alpha_lower_first_ascii = 97;
this._alpha_lower_last_ascii = 123;
this._hex_last_ascii = 103;
this._alpha_upper_first_ascii = 65;
this._alpha_upper_last_ascii = 91;
this._number_dict_ranges = {
digits: [this._digit_first_ascii, this._digit_last_ascii]
};
function __extends(d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
var __assign = function() {
__assign = Object.assign || function __assign(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
this._alpha_dict_ranges = {
lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii],
upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii]
};
function __read(o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
this._alpha_lower_dict_ranges = {
lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii]
};
this._alpha_upper_dict_ranges = {
upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii]
};
this._alphanum_dict_ranges = {
digits: [this._digit_first_ascii, this._digit_last_ascii],
lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii],
upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii]
};
this._alphanum_lower_dict_ranges = {
digits: [this._digit_first_ascii, this._digit_last_ascii],
lowerCase: [this._alpha_lower_first_ascii, this._alpha_lower_last_ascii]
};
this._alphanum_upper_dict_ranges = {
digits: [this._digit_first_ascii, this._digit_last_ascii],
upperCase: [this._alpha_upper_first_ascii, this._alpha_upper_last_ascii]
};
this._hex_dict_ranges = {
decDigits: [this._digit_first_ascii, this._digit_last_ascii],
alphaDigits: [this._alpha_lower_first_ascii, this._hex_last_ascii]
};
this.log = (...args) => {
const finalArgs = [...args];
finalArgs[0] = `[short-unique-id] ${args[0]}`;
if (this.debug === true) {
if (typeof console !== "undefined" && console !== null) {
return console.log(...finalArgs);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
}
function __spreadArray(to, from) {
for (var i = 0, il = from.length, j = to.length; i < il; i++, j++)
to[j] = from[i];
return to;
}
var version = "4.3.3";
// @module ShortUniqueId
/**
* 6 was chosen as the default UUID length since for most cases
* it will be more than aptly suitable to provide millions of UUIDs
* with a very low probability of producing a duplicate UUID.
*
* For example, with a dictionary including digits from 0 to 9,
* as well as the alphabet from a to z both in UPPER and lower case,
* the probability of generating a duplicate in 1,000,000 rounds
* is ~0.00000002, or about 1 in 50,000,000.
*/
var DEFAULT_UUID_LENGTH = 6;
var DEFAULT_OPTIONS = {
dictionary: 'alphanum',
shuffle: true,
debug: false,
length: DEFAULT_UUID_LENGTH
}
};
/**
* Generate random or sequential UUID of any length.
*
* ### Use as module
*
* ```js
* // Deno (web module) Import
* import ShortUniqueId from 'https://cdn.jsdelivr.net/npm/short-unique-id@latest/src/index.ts';
*
* // ES6 / TypeScript Import
* import ShortUniqueId from 'short-unique-id';
*
* //or Node.js require
* const ShortUniqueId = require('short-unique-id');
*
* //Instantiate
* const uid = new ShortUniqueId();
*
* // Random UUID
* console.log(uid());
*
* // Sequential UUID
* console.log(uid.seq());
* ```
*
* ### Use in browser
*
* ```html
* <!-- Import -->
* <script src="https://cdn.jsdelivr.net/npm/short-unique-id@latest/dist/short-unique-id.min.js"></script>
*
* <!-- Usage -->
* <script>
* // Instantiate
* var uid = new ShortUniqueId();
*
* // Random UUID
* document.write(uid());
*
* // Sequential UUID
* document.write(uid.seq());
* </script>
* ```
*
* ### Options
*
* Options can be passed when instantiating `uid`:
*
* ```js
* const options = { ... };
*
* const uid = new ShortUniqueId(options);
* ```
*
* For more information take a look at the [ShortUniqueIdOptions type definition](/interfaces/shortuniqueidoptions.html).
*/
var ShortUniqueId = /** @class */ (function (_super) {
__extends(ShortUniqueId, _super);
function ShortUniqueId(argOptions) {
if (argOptions === void 0) { argOptions = {}; }
var _this = _super.call(this) || this;
_this.dictIndex = 0;
_this.dictRange = [];
_this.lowerBound = 0;
_this.upperBound = 0;
_this.dictLength = 0;
_this._digit_first_ascii = 48;
_this._digit_last_ascii = 58;
_this._alpha_lower_first_ascii = 97;
_this._alpha_lower_last_ascii = 123;
_this._hex_last_ascii = 103;
_this._alpha_upper_first_ascii = 65;
_this._alpha_upper_last_ascii = 91;
_this._number_dict_ranges = {
digits: [_this._digit_first_ascii, _this._digit_last_ascii]
};
_this._alpha_dict_ranges = {
lowerCase: [_this._alpha_lower_first_ascii, _this._alpha_lower_last_ascii],
upperCase: [_this._alpha_upper_first_ascii, _this._alpha_upper_last_ascii]
};
_this._alpha_lower_dict_ranges = {
lowerCase: [_this._alpha_lower_first_ascii, _this._alpha_lower_last_ascii]
};
_this._alpha_upper_dict_ranges = {
upperCase: [_this._alpha_upper_first_ascii, _this._alpha_upper_last_ascii]
};
_this._alphanum_dict_ranges = {
digits: [_this._digit_first_ascii, _this._digit_last_ascii],
lowerCase: [_this._alpha_lower_first_ascii, _this._alpha_lower_last_ascii],
upperCase: [_this._alpha_upper_first_ascii, _this._alpha_upper_last_ascii]
};
_this._alphanum_lower_dict_ranges = {
digits: [_this._digit_first_ascii, _this._digit_last_ascii],
lowerCase: [_this._alpha_lower_first_ascii, _this._alpha_lower_last_ascii]
};
_this._alphanum_upper_dict_ranges = {
digits: [_this._digit_first_ascii, _this._digit_last_ascii],
upperCase: [_this._alpha_upper_first_ascii, _this._alpha_upper_last_ascii]
};
_this._hex_dict_ranges = {
decDigits: [_this._digit_first_ascii, _this._digit_last_ascii],
alphaDigits: [_this._alpha_lower_first_ascii, _this._hex_last_ascii]
};
/* tslint:disable consistent-return */
_this.log = function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var finalArgs = __spreadArray([], __read(args));
finalArgs[0] = "[short-unique-id] " + args[0];
/* tslint:disable no-console */
if (_this.debug === true) {
if (typeof console !== 'undefined' && console !== null) {
return console.log.apply(console, __spreadArray([], __read(finalArgs)));
}
}
/* tslint:enable no-console */
};
/* tslint:enable consistent-return */
/** Change the dictionary after initialization. */
_this.setDictionary = function (dictionary, shuffle) {
var finalDict;
if (dictionary && Array.isArray(dictionary) && dictionary.length > 1) {
finalDict = dictionary;
}
else {
finalDict = [];
var i_1;
_this.dictIndex = i_1 = 0;
var rangesName = "_" + dictionary + "_dict_ranges";
var ranges_1 = _this[rangesName];
Object.keys(ranges_1).forEach(function (rangeType) {
var rangeTypeKey = rangeType;
_this.dictRange = ranges_1[rangeTypeKey];
_this.lowerBound = _this.dictRange[0];
_this.upperBound = _this.dictRange[1];
for (_this.dictIndex = i_1 = _this.lowerBound; _this.lowerBound <= _this.upperBound ? i_1 < _this.upperBound : i_1 > _this.upperBound; _this.dictIndex = _this.lowerBound <= _this.upperBound ? i_1 += 1 : i_1 -= 1) {
finalDict.push(String.fromCharCode(_this.dictIndex));
}
});
}
if (shuffle) {
// Shuffle Dictionary to remove selection bias.
var PROBABILITY_1 = 0.5;
finalDict = finalDict.sort(function () { return Math.random() - PROBABILITY_1; });
}
_this.dict = finalDict;
// Cache Dictionary Length for future usage.
_this.dictLength = _this.dict.length; // Resets internal counter.
_this.counter = 0;
};
_this.seq = function () {
return _this.sequentialUUID();
};
/**
* Generates UUID based on internal counter that's incremented after each ID generation.
* @alias `const uid = new ShortUniqueId(); uid.seq();`
*/
_this.sequentialUUID = function () {
var counterDiv;
var counterRem;
var id = '';
counterDiv = _this.counter;
do {
counterRem = counterDiv % _this.dictLength;
counterDiv = Math.trunc(counterDiv / _this.dictLength);
id += _this.dict[counterRem];
} while (counterDiv !== 0);
_this.counter += 1;
return id;
};
/**
* Generates UUID by creating each part randomly.
* @alias `const uid = new ShortUniqueId(); uid(uuidLength: number);`
*/
_this.randomUUID = function (uuidLength) {
if (uuidLength === void 0) { uuidLength = _this.uuidLength || DEFAULT_UUID_LENGTH; }
var id;
var randomPartIdx;
var j;
if ((uuidLength === null || typeof uuidLength === 'undefined') || uuidLength < 1) {
throw new Error('Invalid UUID Length Provided');
}
// Generate random ID parts from Dictionary.
id = '';
for (j = 0; j < uuidLength; j += 1) {
randomPartIdx = parseInt((Math.random() * _this.dictLength).toFixed(0), 10) % _this.dictLength;
id += _this.dict[randomPartIdx];
}
// Return random generated ID.
return id;
};
/**
* Calculates total number of possible UUIDs.
*
* Given that:
*
* - `H` is the total number of possible UUIDs
* - `n` is the number of unique characters in the dictionary
* - `l` is the UUID length
*
* Then `H` is defined as `n` to the power of `l`:
*
* ![](https://render.githubusercontent.com/render/math?math=%5CHuge%20H=n%5El)
*
* This function returns `H`.
*/
_this.availableUUIDs = function (uuidLength) {
if (uuidLength === void 0) { uuidLength = _this.uuidLength; }
return parseFloat(Math.pow(__spreadArray([], __read(new Set(_this.dict))).length, uuidLength).toFixed(0));
};
/**
* Calculates approximate number of hashes before first collision.
*
* Given that:
*
* - `H` is the total number of possible UUIDs, or in terms of this library,
* the result of running `availableUUIDs()`
* - the expected number of values we have to choose before finding the
* first collision can be expressed as the quantity `Q(H)`
*
* Then `Q(H)` can be approximated as the square root of the of the product
* of half of pi times `H`:
*
* ![](https://render.githubusercontent.com/render/math?math=%5CHuge%20Q(H)%5Capprox%5Csqrt%7B%5Cfrac%7B%5Cpi%7D%7B2%7DH%7D)
*
* This function returns `Q(H)`.
*/
_this.approxMaxBeforeCollision = function (rounds) {
if (rounds === void 0) { rounds = _this.availableUUIDs(_this.uuidLength); }
return parseFloat(Math.sqrt((Math.PI / 2) * rounds).toFixed(20));
};
/**
* Calculates probability of generating duplicate UUIDs (a collision) in a
* given number of UUID generation rounds.
*
* Given that:
*
* - `r` is the maximum number of times that `randomUUID()` will be called,
* or better said the number of _rounds_
* - `H` is the total number of possible UUIDs, or in terms of this library,
* the result of running `availableUUIDs()`
*
* Then the probability of collision `p(r; H)` can be approximated as the result
* of dividing the square root of the of the product of half of pi times `H` by `H`:
*
* ![](https://render.githubusercontent.com/render/math?math=%5CHuge%20p(r%3B%20H)%5Capprox%5Cfrac%7B%5Csqrt%7B%5Cfrac%7B%5Cpi%7D%7B2%7Dr%7D%7D%7BH%7D)
*
* This function returns `p(r; H)`.
*
* (Useful if you are wondering _"If I use this lib and expect to perform at most
* `r` rounds of UUID generations, what is the probability that I will hit a duplicate UUID?"_.)
*/
_this.collisionProbability = function (rounds, uuidLength) {
if (rounds === void 0) { rounds = _this.availableUUIDs(_this.uuidLength); }
if (uuidLength === void 0) { uuidLength = _this.uuidLength; }
return parseFloat((_this.approxMaxBeforeCollision(rounds) / _this.availableUUIDs(uuidLength)).toFixed(20));
};
/**
* Calculate a "uniqueness" score (from 0 to 1) of UUIDs based on size of
* dictionary and chosen UUID length.
*
* Given that:
*
* - `H` is the total number of possible UUIDs, or in terms of this library,
* the result of running `availableUUIDs()`
* - `Q(H)` is the approximate number of hashes before first collision,
* or in terms of this library, the result of running `approxMaxBeforeCollision()`
*
* Then `uniqueness` can be expressed as the additive inverse of the probability of
* generating a "word" I had previously generated (a duplicate) at any given iteration
* up to the the total number of possible UUIDs expressed as the quotiend of `Q(H)` and `H`:
*
* ![](https://render.githubusercontent.com/render/math?math=%5CHuge%201-%5Cfrac%7BQ(H)%7D%7BH%7D)
*
* (Useful if you need a value to rate the "quality" of the combination of given dictionary
* and UUID length. The closer to 1, higher the uniqueness and thus better the quality.)
*/
_this.uniqueness = function (rounds) {
if (rounds === void 0) { rounds = _this.availableUUIDs(_this.uuidLength); }
var score = parseFloat((1 - (_this.approxMaxBeforeCollision(rounds) / rounds)).toFixed(20));
return (score > 1) ? (1) : ((score < 0) ? 0 : score);
};
/**
* Return the version of this module.
*/
_this.getVersion = function () {
return _this.version;
};
/**
* Generates a UUID with a timestamp that can be extracted using `uid.parseStamp(stampString);`.
*
* ```js
* const uidWithTimestamp = uid.stamp(32);
* console.log(uidWithTimestamp);
* // GDa608f973aRCHLXQYPTbKDbjDeVsSb3
*
* console.log(uid.parseStamp(uidWithTimestamp));
* // 2021-05-03T06:24:58.000Z
* ```
*/
_this.stamp = function (finalLength) {
if (typeof finalLength !== 'number' || finalLength < 10) {
throw new Error('Param finalLength must be number greater than 10');
}
var hexStamp = Math.floor(+new Date() / 1000).toString(16);
var idLength = finalLength - 9;
var rndIdx = Math.round(Math.random() * ((idLength > 15) ? 15 : idLength));
var id = _this.randomUUID(idLength);
return "" + id.substr(0, rndIdx) + hexStamp + id.substr(rndIdx) + rndIdx.toString(16);
};
/**
* Extracts the date embeded in a UUID generated using the `uid.stamp(finalLength);` method.
*
* ```js
* const uidWithTimestamp = uid.stamp(32);
* console.log(uidWithTimestamp);
* // GDa608f973aRCHLXQYPTbKDbjDeVsSb3
*
* console.log(uid.parseStamp(uidWithTimestamp));
* // 2021-05-03T06:24:58.000Z
* ```
*/
_this.parseStamp = function (stamp) {
if (stamp.length < 10) {
throw new Error('Stamp length invalid');
}
var rndIdx = parseInt(stamp.substr(stamp.length - 1, 1), 16);
return new Date(parseInt(stamp.substr(rndIdx, 8), 16) * 1000);
};
var options = __assign(__assign({}, DEFAULT_OPTIONS), argOptions);
_this.counter = 0;
_this.debug = false;
_this.dict = [];
_this.version = version;
var dictionary = options.dictionary, shuffle = options.shuffle, length = options.length;
_this.uuidLength = length;
_this.setDictionary(dictionary, shuffle);
_this.debug = options.debug;
_this.log(_this.dict);
_this.log(("Generator instantiated with Dictionary Size " + _this.dictLength));
return new Proxy(_this, {
apply: function (target, that, args) { return _this.randomUUID.apply(_this, __spreadArray([], __read(args))); }
});
}
ShortUniqueId["default"] = ShortUniqueId;
return ShortUniqueId;
}(Function));
return ShortUniqueId;
})));
this.setDictionary = (dictionary, shuffle) => {
let finalDict;
if (dictionary && Array.isArray(dictionary) && dictionary.length > 1) {
finalDict = dictionary;
} else {
finalDict = [];
let i;
this.dictIndex = i = 0;
const rangesName = `_${dictionary}_dict_ranges`;
const ranges = this[rangesName];
Object.keys(ranges).forEach((rangeType) => {
const rangeTypeKey = rangeType;
this.dictRange = ranges[rangeTypeKey];
this.lowerBound = this.dictRange[0];
this.upperBound = this.dictRange[1];
for (this.dictIndex = i = this.lowerBound; this.lowerBound <= this.upperBound ? i < this.upperBound : i > this.upperBound; this.dictIndex = this.lowerBound <= this.upperBound ? i += 1 : i -= 1) {
finalDict.push(String.fromCharCode(this.dictIndex));
}
});
}
if (shuffle) {
const PROBABILITY = 0.5;
finalDict = finalDict.sort(() => Math.random() - PROBABILITY);
}
this.dict = finalDict;
this.dictLength = this.dict.length;
this.counter = 0;
};
this.seq = () => {
return this.sequentialUUID();
};
this.sequentialUUID = () => {
let counterDiv;
let counterRem;
let id = "";
counterDiv = this.counter;
do {
counterRem = counterDiv % this.dictLength;
counterDiv = Math.trunc(counterDiv / this.dictLength);
id += this.dict[counterRem];
} while (counterDiv !== 0);
this.counter += 1;
return id;
};
this.randomUUID = (uuidLength = this.uuidLength || DEFAULT_UUID_LENGTH) => {
let id;
let randomPartIdx;
let j;
if (uuidLength === null || typeof uuidLength === "undefined" || uuidLength < 1) {
throw new Error("Invalid UUID Length Provided");
}
const isPositive = uuidLength >= 0;
id = "";
for (j = 0; j < uuidLength; j += 1) {
randomPartIdx = parseInt((Math.random() * this.dictLength).toFixed(0), 10) % this.dictLength;
id += this.dict[randomPartIdx];
}
return id;
};
this.availableUUIDs = (uuidLength = this.uuidLength) => {
return parseFloat(Math.pow([...new Set(this.dict)].length, uuidLength).toFixed(0));
};
this.approxMaxBeforeCollision = (rounds = this.availableUUIDs(this.uuidLength)) => {
return parseFloat(Math.sqrt(Math.PI / 2 * rounds).toFixed(20));
};
this.collisionProbability = (rounds = this.availableUUIDs(this.uuidLength), uuidLength = this.uuidLength) => {
return parseFloat((this.approxMaxBeforeCollision(rounds) / this.availableUUIDs(uuidLength)).toFixed(20));
};
this.uniqueness = (rounds = this.availableUUIDs(this.uuidLength)) => {
const score = parseFloat((1 - this.approxMaxBeforeCollision(rounds) / rounds).toFixed(20));
return score > 1 ? 1 : score < 0 ? 0 : score;
};
this.getVersion = () => {
return this.version;
};
this.stamp = (finalLength) => {
if (typeof finalLength !== "number" || finalLength < 10) {
throw new Error("Param finalLength must be number greater than 10");
}
const hexStamp = Math.floor(+new Date() / 1e3).toString(16);
const idLength = finalLength - 9;
const rndIdx = Math.round(Math.random() * (idLength > 15 ? 15 : idLength));
const id = this.randomUUID(idLength);
return `${id.substr(0, rndIdx)}${hexStamp}${id.substr(rndIdx)}${rndIdx.toString(16)}`;
};
this.parseStamp = (stamp) => {
if (stamp.length < 10) {
throw new Error("Stamp length invalid");
}
const rndIdx = parseInt(stamp.substr(stamp.length - 1, 1), 16);
return new Date(parseInt(stamp.substr(rndIdx, 8), 16) * 1e3);
};
const options = __spreadValues(__spreadValues({}, DEFAULT_OPTIONS), argOptions);
this.counter = 0;
this.debug = false;
this.dict = [];
this.version = version;
const {
dictionary,
shuffle,
length
} = options;
this.uuidLength = length;
this.setDictionary(dictionary, shuffle);
this.debug = options.debug;
this.log(this.dict);
this.log(`Generator instantiated with Dictionary Size ${this.dictLength}`);
return new Proxy(this, {
apply: (target, that, args) => this.randomUUID(...args)
});
}
};
var ShortUniqueId = _ShortUniqueId;
ShortUniqueId.default = _ShortUniqueId;
module.exports = ShortUniqueId;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
DEFAULT_UUID_LENGTH
});
//# sourceMappingURL=short-unique-id.js.map

@@ -1,1 +0,1 @@

(function(global,factory){typeof exports==="object"&&typeof module!=="undefined"?module.exports=factory():typeof define==="function"&&define.amd?define(factory):(global=typeof globalThis!=="undefined"?globalThis:global||self,global.ShortUniqueId=factory())})(this,(function(){"use strict";var extendStatics=function(d,b){extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)if(Object.prototype.hasOwnProperty.call(b,p))d[p]=b[p]};return extendStatics(d,b)};function __extends(d,b){if(typeof b!=="function"&&b!==null)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");extendStatics(d,b);function __(){this.constructor=d}d.prototype=b===null?Object.create(b):(__.prototype=b.prototype,new __)}var __assign=function(){__assign=Object.assign||function __assign(t){for(var s,i=1,n=arguments.length;i<n;i++){s=arguments[i];for(var p in s)if(Object.prototype.hasOwnProperty.call(s,p))t[p]=s[p]}return t};return __assign.apply(this,arguments)};function __read(o,n){var m=typeof Symbol==="function"&&o[Symbol.iterator];if(!m)return o;var i=m.call(o),r,ar=[],e;try{while((n===void 0||n-- >0)&&!(r=i.next()).done)ar.push(r.value)}catch(error){e={error:error}}finally{try{if(r&&!r.done&&(m=i["return"]))m.call(i)}finally{if(e)throw e.error}}return ar}function __spreadArray(to,from){for(var i=0,il=from.length,j=to.length;i<il;i++,j++)to[j]=from[i];return to}var version="4.3.3";var DEFAULT_UUID_LENGTH=6;var DEFAULT_OPTIONS={dictionary:"alphanum",shuffle:true,debug:false,length:DEFAULT_UUID_LENGTH};var ShortUniqueId=function(_super){__extends(ShortUniqueId,_super);function ShortUniqueId(argOptions){if(argOptions===void 0){argOptions={}}var _this=_super.call(this)||this;_this.dictIndex=0;_this.dictRange=[];_this.lowerBound=0;_this.upperBound=0;_this.dictLength=0;_this._digit_first_ascii=48;_this._digit_last_ascii=58;_this._alpha_lower_first_ascii=97;_this._alpha_lower_last_ascii=123;_this._hex_last_ascii=103;_this._alpha_upper_first_ascii=65;_this._alpha_upper_last_ascii=91;_this._number_dict_ranges={digits:[_this._digit_first_ascii,_this._digit_last_ascii]};_this._alpha_dict_ranges={lowerCase:[_this._alpha_lower_first_ascii,_this._alpha_lower_last_ascii],upperCase:[_this._alpha_upper_first_ascii,_this._alpha_upper_last_ascii]};_this._alpha_lower_dict_ranges={lowerCase:[_this._alpha_lower_first_ascii,_this._alpha_lower_last_ascii]};_this._alpha_upper_dict_ranges={upperCase:[_this._alpha_upper_first_ascii,_this._alpha_upper_last_ascii]};_this._alphanum_dict_ranges={digits:[_this._digit_first_ascii,_this._digit_last_ascii],lowerCase:[_this._alpha_lower_first_ascii,_this._alpha_lower_last_ascii],upperCase:[_this._alpha_upper_first_ascii,_this._alpha_upper_last_ascii]};_this._alphanum_lower_dict_ranges={digits:[_this._digit_first_ascii,_this._digit_last_ascii],lowerCase:[_this._alpha_lower_first_ascii,_this._alpha_lower_last_ascii]};_this._alphanum_upper_dict_ranges={digits:[_this._digit_first_ascii,_this._digit_last_ascii],upperCase:[_this._alpha_upper_first_ascii,_this._alpha_upper_last_ascii]};_this._hex_dict_ranges={decDigits:[_this._digit_first_ascii,_this._digit_last_ascii],alphaDigits:[_this._alpha_lower_first_ascii,_this._hex_last_ascii]};_this.log=function(){var args=[];for(var _i=0;_i<arguments.length;_i++){args[_i]=arguments[_i]}var finalArgs=__spreadArray([],__read(args));finalArgs[0]="[short-unique-id] "+args[0];if(_this.debug===true){if(typeof console!=="undefined"&&console!==null){return console.log.apply(console,__spreadArray([],__read(finalArgs)))}}};_this.setDictionary=function(dictionary,shuffle){var finalDict;if(dictionary&&Array.isArray(dictionary)&&dictionary.length>1){finalDict=dictionary}else{finalDict=[];var i_1;_this.dictIndex=i_1=0;var rangesName="_"+dictionary+"_dict_ranges";var ranges_1=_this[rangesName];Object.keys(ranges_1).forEach((function(rangeType){var rangeTypeKey=rangeType;_this.dictRange=ranges_1[rangeTypeKey];_this.lowerBound=_this.dictRange[0];_this.upperBound=_this.dictRange[1];for(_this.dictIndex=i_1=_this.lowerBound;_this.lowerBound<=_this.upperBound?i_1<_this.upperBound:i_1>_this.upperBound;_this.dictIndex=_this.lowerBound<=_this.upperBound?i_1+=1:i_1-=1){finalDict.push(String.fromCharCode(_this.dictIndex))}}))}if(shuffle){var PROBABILITY_1=.5;finalDict=finalDict.sort((function(){return Math.random()-PROBABILITY_1}))}_this.dict=finalDict;_this.dictLength=_this.dict.length;_this.counter=0};_this.seq=function(){return _this.sequentialUUID()};_this.sequentialUUID=function(){var counterDiv;var counterRem;var id="";counterDiv=_this.counter;do{counterRem=counterDiv%_this.dictLength;counterDiv=Math.trunc(counterDiv/_this.dictLength);id+=_this.dict[counterRem]}while(counterDiv!==0);_this.counter+=1;return id};_this.randomUUID=function(uuidLength){if(uuidLength===void 0){uuidLength=_this.uuidLength||DEFAULT_UUID_LENGTH}var id;var randomPartIdx;var j;if(uuidLength===null||typeof uuidLength==="undefined"||uuidLength<1){throw new Error("Invalid UUID Length Provided")}id="";for(j=0;j<uuidLength;j+=1){randomPartIdx=parseInt((Math.random()*_this.dictLength).toFixed(0),10)%_this.dictLength;id+=_this.dict[randomPartIdx]}return id};_this.availableUUIDs=function(uuidLength){if(uuidLength===void 0){uuidLength=_this.uuidLength}return parseFloat(Math.pow(__spreadArray([],__read(new Set(_this.dict))).length,uuidLength).toFixed(0))};_this.approxMaxBeforeCollision=function(rounds){if(rounds===void 0){rounds=_this.availableUUIDs(_this.uuidLength)}return parseFloat(Math.sqrt(Math.PI/2*rounds).toFixed(20))};_this.collisionProbability=function(rounds,uuidLength){if(rounds===void 0){rounds=_this.availableUUIDs(_this.uuidLength)}if(uuidLength===void 0){uuidLength=_this.uuidLength}return parseFloat((_this.approxMaxBeforeCollision(rounds)/_this.availableUUIDs(uuidLength)).toFixed(20))};_this.uniqueness=function(rounds){if(rounds===void 0){rounds=_this.availableUUIDs(_this.uuidLength)}var score=parseFloat((1-_this.approxMaxBeforeCollision(rounds)/rounds).toFixed(20));return score>1?1:score<0?0:score};_this.getVersion=function(){return _this.version};_this.stamp=function(finalLength){if(typeof finalLength!=="number"||finalLength<10){throw new Error("Param finalLength must be number greater than 10")}var hexStamp=Math.floor(+new Date/1e3).toString(16);var idLength=finalLength-9;var rndIdx=Math.round(Math.random()*(idLength>15?15:idLength));var id=_this.randomUUID(idLength);return""+id.substr(0,rndIdx)+hexStamp+id.substr(rndIdx)+rndIdx.toString(16)};_this.parseStamp=function(stamp){if(stamp.length<10){throw new Error("Stamp length invalid")}var rndIdx=parseInt(stamp.substr(stamp.length-1,1),16);return new Date(parseInt(stamp.substr(rndIdx,8),16)*1e3)};var options=__assign(__assign({},DEFAULT_OPTIONS),argOptions);_this.counter=0;_this.debug=false;_this.dict=[];_this.version=version;var dictionary=options.dictionary,shuffle=options.shuffle,length=options.length;_this.uuidLength=length;_this.setDictionary(dictionary,shuffle);_this.debug=options.debug;_this.log(_this.dict);_this.log("Generator instantiated with Dictionary Size "+_this.dictLength);return new Proxy(_this,{apply:function(target,that,args){return _this.randomUUID.apply(_this,__spreadArray([],__read(args)))}})}ShortUniqueId["default"]=ShortUniqueId;return ShortUniqueId}(Function);return ShortUniqueId}));
var u=Object.defineProperty;var c=Object.getOwnPropertySymbols;var m=Object.prototype.hasOwnProperty,f=Object.prototype.propertyIsEnumerable;var g=(r,t,i)=>t in r?u(r,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):r[t]=i,d=(r,t)=>{for(var i in t||(t={}))m.call(t,i)&&g(r,i,t[i]);if(c)for(var i of c(t))f.call(t,i)&&g(r,i,t[i]);return r};var I=r=>u(r,"__esModule",{value:!0});var U=(r,t)=>{I(r);for(var i in t)u(r,i,{get:t[i],enumerable:!0})};U(exports,{DEFAULT_UUID_LENGTH:()=>l,default:()=>a});var b="4.3.4";var l=6,q={dictionary:"alphanum",shuffle:!0,debug:!1,length:l},p=class extends Function{constructor(t={}){super();this.dictIndex=0;this.dictRange=[];this.lowerBound=0;this.upperBound=0;this.dictLength=0;this._digit_first_ascii=48;this._digit_last_ascii=58;this._alpha_lower_first_ascii=97;this._alpha_lower_last_ascii=123;this._hex_last_ascii=103;this._alpha_upper_first_ascii=65;this._alpha_upper_last_ascii=91;this._number_dict_ranges={digits:[this._digit_first_ascii,this._digit_last_ascii]};this._alpha_dict_ranges={lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]};this._alpha_lower_dict_ranges={lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii]};this._alpha_upper_dict_ranges={upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]};this._alphanum_dict_ranges={digits:[this._digit_first_ascii,this._digit_last_ascii],lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]};this._alphanum_lower_dict_ranges={digits:[this._digit_first_ascii,this._digit_last_ascii],lowerCase:[this._alpha_lower_first_ascii,this._alpha_lower_last_ascii]};this._alphanum_upper_dict_ranges={digits:[this._digit_first_ascii,this._digit_last_ascii],upperCase:[this._alpha_upper_first_ascii,this._alpha_upper_last_ascii]};this._hex_dict_ranges={decDigits:[this._digit_first_ascii,this._digit_last_ascii],alphaDigits:[this._alpha_lower_first_ascii,this._hex_last_ascii]};this.log=(...t)=>{let i=[...t];if(i[0]=`[short-unique-id] ${t[0]}`,this.debug===!0&&typeof console!="undefined"&&console!==null)return console.log(...i)};this.setDictionary=(t,i)=>{let e;if(t&&Array.isArray(t)&&t.length>1)e=t;else{e=[];let s;this.dictIndex=s=0;let n=`_${t}_dict_ranges`,o=this[n];Object.keys(o).forEach(_=>{let h=_;for(this.dictRange=o[h],this.lowerBound=this.dictRange[0],this.upperBound=this.dictRange[1],this.dictIndex=s=this.lowerBound;this.lowerBound<=this.upperBound?s<this.upperBound:s>this.upperBound;this.dictIndex=this.lowerBound<=this.upperBound?s+=1:s-=1)e.push(String.fromCharCode(this.dictIndex))})}if(i){let s=.5;e=e.sort(()=>Math.random()-s)}this.dict=e,this.dictLength=this.dict.length,this.counter=0};this.seq=()=>this.sequentialUUID();this.sequentialUUID=()=>{let t,i,e="";t=this.counter;do i=t%this.dictLength,t=Math.trunc(t/this.dictLength),e+=this.dict[i];while(t!==0);return this.counter+=1,e};this.randomUUID=(t=this.uuidLength||l)=>{let i,e,s;if(t===null||typeof t=="undefined"||t<1)throw new Error("Invalid UUID Length Provided");let n=t>=0;for(i="",s=0;s<t;s+=1)e=parseInt((Math.random()*this.dictLength).toFixed(0),10)%this.dictLength,i+=this.dict[e];return i};this.availableUUIDs=(t=this.uuidLength)=>parseFloat(Math.pow([...new Set(this.dict)].length,t).toFixed(0));this.approxMaxBeforeCollision=(t=this.availableUUIDs(this.uuidLength))=>parseFloat(Math.sqrt(Math.PI/2*t).toFixed(20));this.collisionProbability=(t=this.availableUUIDs(this.uuidLength),i=this.uuidLength)=>parseFloat((this.approxMaxBeforeCollision(t)/this.availableUUIDs(i)).toFixed(20));this.uniqueness=(t=this.availableUUIDs(this.uuidLength))=>{let i=parseFloat((1-this.approxMaxBeforeCollision(t)/t).toFixed(20));return i>1?1:i<0?0:i};this.getVersion=()=>this.version;this.stamp=t=>{if(typeof t!="number"||t<10)throw new Error("Param finalLength must be number greater than 10");let i=Math.floor(+new Date/1e3).toString(16),e=t-9,s=Math.round(Math.random()*(e>15?15:e)),n=this.randomUUID(e);return`${n.substr(0,s)}${i}${n.substr(s)}${s.toString(16)}`};this.parseStamp=t=>{if(t.length<10)throw new Error("Stamp length invalid");let i=parseInt(t.substr(t.length-1,1),16);return new Date(parseInt(t.substr(i,8),16)*1e3)};let i=d(d({},q),t);this.counter=0,this.debug=!1,this.dict=[],this.version=b;let{dictionary:e,shuffle:s,length:n}=i;return this.uuidLength=n,this.setDictionary(e,s),this.debug=i.debug,this.log(this.dict),this.log(`Generator instantiated with Dictionary Size ${this.dictLength}`),new Proxy(this,{apply:(o,_,h)=>this.randomUUID(...h)})}},a=p;a.default=p;module.exports=a;0&&(module.exports={DEFAULT_UUID_LENGTH});
{
"name": "short-unique-id",
"version": "4.3.3",
"version": "4.3.4",
"description": "Generate random or sequential UUID of any length",

@@ -30,2 +30,3 @@ "keywords": [

"build": "scripty",
"docs": "scripty",
"release": "standard-version"

@@ -44,15 +45,15 @@ },

"devDependencies": {
"@rollup/plugin-json": "^4.1.0",
"@rollup/plugin-typescript": "^8.2.1",
"@types/node": "^15.0.1",
"rollup": "^2.46.0",
"@types/node": "^16.6.1",
"esbuild": "^0.12.20",
"scripty": "^2.0.0",
"short-unique-id-typedoc-template": "2.0.4",
"standard-version": "^9.2.0",
"terser": "^5.7.0",
"ts-node": "^9.1.1",
"tslib": "^2.2.0",
"standard-version": "^9.3.1",
"ts-node": "^10.2.0",
"tslib": "^2.3.1",
"typedoc": "^0.20.36",
"typescript": "^4.2.4"
"typescript": "4.2.2"
},
"resolutions": {
"trim-newlines": "4.0.2"
}
}

@@ -11,44 +11,62 @@ # Short Unique ID (UUID) Generating Library

Generate random or sequential UUID of any length.
---
This project is open to updates by its users, I ensure that PRs are relevant to the community.
In other words, if you find a bug or want a new feature, please help us by becoming one of the
[contributors](#contributors-) ✌️ ! See the [contributing section](#contributing).
Tiny (4.6kB minified) no-dependency library for generating random or sequential UUID of any length
with exceptionally minuscule probabilies of duplicate IDs.
## Like this module? ❤
```ts
const uid = new ShortUniqueId({ length: 10 });
uid(); // p0ZoB1FwH6
uid(); // mSjGCTfn8w
uid(); // yt4Xx5nHMB
// ...
```
Please consider:
For example, using the default dictionary of numbers and letters (lower and upper case):
- [Buying me a coffee](https://www.buymeacoffee.com/jeanlescure) ☕
- Supporting me on [Patreon](https://www.patreon.com/jeanlescure) 🏆
- Starring this repo on [Github](https://github.com/jeanlescure/short-unique-id) 🌟
```ts
0,1,2,3,4,5,6,7,8,9,
a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,
A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z
```
## 📣 v4 Notice
- if you generate a unique ID of 16 characters (half of the standard UUID of 32 characters)
- generating 100 unique IDs **per second**
### BREAKING CHANGES
#### It would take **~10 thousand years** to have a 1% probability of at least one collision!
This project has been completely refactored from v3 to be less "Deno centric" and more good 'ol Typescript.
To put this into perspective:
We tried avoiding breaking changes, and generally succeded.
- 73 years is the (global) average life expectancy of a human being
- 120 years ago no human ever had set foot on either of the Earth's poles
- 480 years ago Nicolaus Copernicus was still working on his theory of the Earth revolving around the Sun
- 1000 years ago there was no such thing as government-issued paper money (and wouldn't be for about a century)
- 5000 years ago the global population of humans was under 50 million (right now Mexico has a population of 127 million)
With that said, for Node.js require use-cases:
You can calculate duplicate/collision probabilities using the included functions:
- The `dist` js files are now generated as UMD, named as `ShortUniqueId`, which means that...
- [availableUUIDs()](https://shortunique.id/classes/default.html#availableuuids)
- [approxMaxBeforeCollision()](https://shortunique.id/classes/default.html#approxmaxbeforecollision)
- [collisionProbability()](https://shortunique.id/classes/default.html#collisionprobability)
```js
// ...if you get the error "TypeError: ShortUniqueId is not a constructor" then this
const { default: ShortUniqueId } = require('short-unique-id');
_NOTE: 👆 On these links you will also find explanations for the math used within the functions._
// must be refactored to this
const ShortUniqueId = require('short-unique-id');
```
---
- The `lib` directory is now completely removed
## Open source notice
Also, the following changes might generate errors in some edge-cases:
This project is open to updates by its users, I ensure that PRs are relevant to the community.
In other words, if you find a bug or want a new feature, please help us by becoming one of the
[contributors](#contributors-) ✌️ ! See the [contributing section](#contributing).
- The `short_uuid` Deno submodule has been completely removed from this repo and now all the logic lives in `src/index.ts`
- Typings are no longer under the `typings` directory but are now under the `dist` directory
- A sourcemap is now included along with the `dist` files
## Like this module? ❤
Please consider:
- [Buying me a coffee](https://www.buymeacoffee.com/jeanlescure) ☕
- Supporting me on [Patreon](https://www.patreon.com/jeanlescure) 🏆
- Starring this repo on [Github](https://github.com/jeanlescure/short-unique-id) 🌟
## 📣 v4 Notice
### New Features 🥳

@@ -59,2 +77,4 @@

```js
// js/ts
const uid = new ShortUniqueId();

@@ -66,6 +86,19 @@

console.log(uid.parseStamp(uidWithTimestamp));
const recoveredTimestamp = uid.parseStamp(uidWithTimestamp);
console.log(recoveredTimestamp);
// 2021-05-03T06:24:58.000Z
```
```bash
# cli
$ short-unique-id -s -l 42
lW611f30a2ky4276g3l8N7nBHI5AQ5rCiwYzU47HP2
$ short-unique-id -p lW611f30a2ky4276g3l8N7nBHI5AQ5rCiwYzU47HP2
2021-08-20T04:33:38.000Z
```
Default dictionaries (generated on the spot to reduce memory footprint and

@@ -148,3 +181,3 @@ avoid dictionary injection vulnerabilities):

```html
<!-- Add source (minified 7.2K) -->
<!-- Add source (minified 4.6kB) -->
<script src="https://cdn.jsdelivr.net/npm/short-unique-id@latest/dist/short-unique-id.min.js"></script>

@@ -151,0 +184,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc