UNPKG

11.8 kBMarkdownView Raw
1# Short Unique ID (UUID) Generating Library
2![Tests](https://github.com/jeanlescure/short-unique-id/workflows/tests/badge.svg)
3[![Try short-unique-id on RunKit](https://badge.runkitcdn.com/short-unique-id.svg)](https://npm.runkit.com/short-unique-id)
4[![NPM Downloads](https://img.shields.io/npm/dt/short-unique-id.svg?maxAge=2592000)](https://npmjs.com/package/short-unique-id)
5[![JsDelivr Hits](https://data.jsdelivr.com/v1/package/npm/short-unique-id/badge?style=rounded)](https://www.jsdelivr.com/package/npm/short-unique-id)
6
7<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
8[![9 Contributors](https://img.shields.io/badge/all_contributors-8-purple.svg)](#contributors)
9<!-- ALL-CONTRIBUTORS-BADGE:END -->
10
11Generate random or sequential UUID of any length.
12
13This project is open to updates by its users, I ensure that PRs are relevant to the community.
14In other words, if you find a bug or want a new feature, please help us by becoming one of the
15[contributors](#contributors-) ✌️ ! See the [contributing section](#contributing).
16
17## Like this module? ❤
18
19Please consider:
20
21- [Buying me a coffee](https://www.buymeacoffee.com/jeanlescure) ☕
22- Supporting me on [Patreon](https://www.patreon.com/jeanlescure) 🏆
23- Starring this repo on [Github](https://github.com/jeanlescure/short-unique-id) 🌟
24
25## 📣 v4 Notice
26
27### BREAKING CHANGES
28
29This project has been completely refactored from v3 to be less "Deno centric" and more good 'ol Typescript.
30
31We tried avoiding breaking changes, and generally succeded.
32
33With that said, for Node.js require use-cases:
34
35- The `dist` js files are now generated as UMD, named as `ShortUniqueId`, which means that...
36
37```js
38// ...if you get the error "TypeError: ShortUniqueId is not a constructor" then this
39const { default: ShortUniqueId } = require('short-unique-id');
40
41// must be refactored to this
42const ShortUniqueId = require('short-unique-id');
43```
44
45- The `lib` directory is now completely removed
46
47Also, the following changes might generate errors in some edge-cases:
48
49- The `short_uuid` Deno submodule has been completely removed from this repo and now all the logic lives in `src/index.ts`
50- Typings are no longer under the `typings` directory but are now under the `dist` directory
51- A sourcemap is now included along with the `dist` files
52
53### New Features 🥳
54
55The ability to generate UUIDs that contain a timestamp which can be extracted:
56
57```js
58const uid = new ShortUniqueId();
59
60const uidWithTimestamp = uid.stamp(32);
61console.log(uidWithTimestamp);
62// GDa608f973aRCHLXQYPTbKDbjDeVsSb3
63
64console.log(uid.parseStamp(uidWithTimestamp));
65// 2021-05-03T06:24:58.000Z
66```
67
68Default dictionaries (generated on the spot to reduce memory footprint and
69avoid dictionary injection vulnerabilities):
70
71- number
72- alpha
73- alpha_lower
74- alpha_upper
75- **alphanum** _(default when no dictionary is provided to `new ShortUniqueId()`)_
76- alphanum_lower
77- alphanum_upper
78- hex
79
80```js
81// instantiate using one of the default dictionary strings
82const uid = new ShortUniqueId({
83 dictionary: 'hex', // the default
84});
85
86console.log(uid.dict.join());
87// 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f
88
89// or change the dictionary after instantiation
90uid.setDictionary('alpha_upper');
91
92console.log(uid.dict.join());
93// 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
94```
95
96### Use in CLI
97
98```sh
99$ npm install -g short-unique-id
100
101$ short-unique-id -h
102
103# Usage:
104# node short-unique-id [OPTION]
105
106# Options:
107# -l, --length=ARG character length of the uid to generate.
108# -s, --stamp include timestamp in uid (must be used with --length (-l) of 10 or more).
109# -p, --parse=ARG extract timestamp from stamped uid (ARG).
110# -d, --dictionaryJson=ARG json file with dictionary array.
111# -h, --help display this help
112```
113
114### Use as module
115
116Add to your project:
117
118```js
119// Deno (web module) Import
120import ShortUniqueId from 'https://cdn.jsdelivr.net/npm/short-unique-id@latest/src/index.ts';
121
122// ES6 / TypeScript Import
123import ShortUniqueId from 'short-unique-id';
124
125// Node.js require
126const ShortUniqueId = require('short-unique-id');
127```
128
129Instantiate and use:
130
131```js
132//Instantiate
133const uid = new ShortUniqueId();
134
135// Random UUID
136console.log(uid());
137
138// Sequential UUID
139console.log(uid.seq());
140```
141
142### Use in browser
143
144```html
145<!-- Add source (minified 7.2K) -->
146<script src="https://cdn.jsdelivr.net/npm/short-unique-id@latest/dist/short-unique-id.min.js"></script>
147
148<!-- Usage -->
149<script>
150 // Instantiate
151 var uid = new ShortUniqueId();
152
153 // Random UUID
154 document.write(uid());
155
156 // Sequential UUID
157 document.write(uid.seq());
158</script>
159```
160
161### Options
162
163Options can be passed when instantiating `uid`:
164
165```js
166const options = { ... };
167
168const uid = new ShortUniqueId(options);
169```
170
171For more information take a look at the [docs](https://shortunique.id/interfaces/shortuniqueidoptions.html).
172
173## Available for
174
175- [Node.js (npm)](https://www.npmjs.com/package/short-unique-id)
176- [Deno](https://www.jsdelivr.com/package/npm/short-unique-id?path=src)
177- [Browsers](https://www.jsdelivr.com/package/npm/short-unique-id?path=dist)
178
179## Documentation with Online Short UUID Generator
180
181You can find the docs and online generator at:
182
183<a target="_blank" href="https://shortunique.id">https://shortunique.id</a>
184
185## What is the probability of generating the same id again?
186
187This largely depends on the given dictionary and the selected UUID length.
188
189Out of the box this library provides a shuffled dictionary of digits from
1900 to 9, as well as the alphabet from a to z both in UPPER and lower case,
191with a default UUID length of 6. That gives you a total of 56,800,235,584
192possible UUIDs.
193
194So, given the previous values, the probability of generating a duplicate
195in 1,000,000 rounds is ~0.00000002, or about 1 in 50,000,000.
196
197If you change the dictionary and/or the UUID length then we have provided
198the function `collisionProbability()` function to calculate the probability
199of hitting a duplicate in a given number of rounds (a collision) and the
200function `uniqueness()` which provides a score (from 0 to 1) to rate the
201"quality" of the combination of given dictionary and UUID length (the closer
202to 1, higher the uniqueness and thus better the quality).
203
204To find out more about the math behind these functions please refer to the
205<a target="_blank" href="https://shortunique.id/classes/default.html#collisionprobability">API Reference</a>.
206
207## Acknowledgement and platform support
208
209This repo and npm package started as a straight up manual transpilation to ES6 of the [short-uid](https://github.com/serendipious/nodejs-short-uid) npm package by [Ankit Kuwadekar](https://github.com/serendipious/).
210
211![image depicting over 12000 weekly npm downloads](https://raw.githubusercontent.com/jeanlescure/short-unique-id/main/assets/weekly-downloads.png)
212![image depicting over 100000 weekly cdn hits](https://raw.githubusercontent.com/jeanlescure/short-unique-id/main/assets/weekly-cdn-hits.png)
213
214Since this package is now reporting 12k+ npm weekly downloads and 100k+ weekly cdn hits,
215we've gone ahead and re-written the whole of it in TypeScript and made sure to package
216dist modules compatible with Deno, Node.js and all major Browsers.
217
218## Development
219
220Clone this repo:
221
222```sh
223# SSH
224git clone git@github.com:jeanlescure/short-unique-id.git
225
226# HTTPS
227git clone https://github.com/jeanlescure/short-unique-id.git
228```
229
230Tests run using:
231
232```
233yarn test
234```
235
236## Build
237
238In order to publish the latest changes you must build the distribution files:
239
240```
241yarn build
242```
243
244Then commit all changes and run the release script:
245
246```
247yarn release
248```
249
250## Contributing
251
252Yes, thank you! This plugin is community-driven, most of its features are from different authors.
253Please update the docs and tests and add your name to the `package.json` file.
254
255## Contributors ✨
256
257Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
258
259<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
260<!-- prettier-ignore-start -->
261<!-- markdownlint-disable -->
262<table>
263 <tr>
264 <td align="center"><a href="https://github.com/serendipious"><img src="https://shortunique.id/assets/contributors/serendipious.svg" /></a><table><tbody><tr><td width="150" align="center"><a href="https://github.com/jeanlescure/short-unique-id/commits?author=serendipious" title="Code">💻</a></td></tr></tbody></table></td>
265 <td align="center"><a href="https://jeanlescure.cr"><img src="https://shortunique.id/assets/contributors/jeanlescure.svg" /></a><table><tbody><tr><td width="150" align="center"><a href="#maintenance-jeanlescure" title="Maintenance">🚧</a> <a href="https://github.com/jeanlescure/short-unique-id/commits?author=jeanlescure" title="Code">💻</a> <a href="#content-jeanlescure" title="Content">🖋</a> <a href="https://github.com/jeanlescure/short-unique-id/commits?author=jeanlescure" title="Documentation">📖</a> <a href="https://github.com/jeanlescure/short-unique-id/commits?author=jeanlescure" title="Tests">⚠️</a></td></tr></tbody></table></td>
266 <td align="center"><a href="https://dianalu.design"><img src="https://shortunique.id/assets/contributors/dilescure.svg" /></a><table><tbody><tr><td width="150" align="center"><a href="https://github.com/jeanlescure/short_uuid/commits?author=DiLescure" title="Code">💻</a></td></tr></tbody></table></td>
267 <td align="center"><a href="https://github.com/EmerLM"><img src="https://shortunique.id/assets/contributors/emerlm.svg" /></a><table><tbody><tr><td width="150" align="center"><a href="https://github.com/jeanlescure/short_uuid/commits?author=EmerLM" title="Code">💻</a></td></tr></tbody></table></td>
268 </tr>
269 <tr>
270 <td align="center"><a href="https://github.com/angelnath26"><img src="https://shortunique.id/assets/contributors/angelnath26.svg" /></a><table><tbody><tr><td width="150" align="center"><a href="https://github.com/jeanlescure/short_uuid/commits?author=angelnath26" title="Code">💻</a> <a href="https://github.com/jeanlescure/short_uuid/pulls?q=is%3Apr+reviewed-by%3Aangelnath26" title="Reviewed Pull Requests">👀</a></td></tr></tbody></table></td>
271 <td align="center"><a href="https://twitter.com/jeffturcotte"><img src="https://shortunique.id/assets/contributors/jeffturcotte.svg" /></a><table><tbody><tr><td width="150" align="center"><a href="https://github.com/jeanlescure/short-unique-id/commits?author=jeffturcotte" title="Code">💻</a></td></tr></tbody></table></td>
272 <td align="center"><a href="https://github.com/neversun"><img src="https://shortunique.id/assets/contributors/neversun.svg" /></a><table><tbody><tr><td width="150" align="center"><a href="https://github.com/jeanlescure/short-unique-id/commits?author=neversun" title="Code">💻</a></td></tr></tbody></table></td>
273 <td align="center"><a href="https://github.com/ekelvin"><img src="https://shortunique.id/assets/contributors/ekelvin.svg" /></a><table><tbody><tr><td width="150" align="center"><a href="https://github.com/jeanlescure/short-unique-id/issues/19" title="Ideas, Planning, & Feedback">🤔</a></td></tr></tbody></table></td>
274 </tr>
275 <tr>
276 <td align="center"><a href="https://github.com/anthony-arnold"><img src="https://shortunique.id/assets/contributors/anthony-arnold.svg" /></a><table><tbody><tr><td width="150" align="center"><a href="https://github.com/jeanlescure/short-unique-id/issues/35" title="Security">🛡️</a></td></tr></tbody></table></td>
277 </tr>
278</table>
279
280<!-- markdownlint-enable -->
281<!-- prettier-ignore-end -->
282<!-- ALL-CONTRIBUTORS-LIST:END -->
283
284## License
285
286Copyright (c) 2018-2021 [Short Unique ID Contributors](https://github.com/jeanlescure/short-unique-id/#contributors-).<br/>
287Licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).