Skip to content

Commit

Permalink
docs: update docs for v5
Browse files Browse the repository at this point in the history
  • Loading branch information
jeanlescure committed Sep 4, 2023
1 parent 0e7f350 commit 5fed48e
Show file tree
Hide file tree
Showing 43 changed files with 13,345 additions and 7,242 deletions.
7 changes: 2 additions & 5 deletions .github/workflows/main.yml
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,8 @@ jobs:
with:
node-version: '14.x'

- name: Install PNPM
run: npm install -g pnpm

- name: Install Dependencies
run: pnpm i
run: npm i

- name: Test
run: pnpm test
run: npm run test
88 changes: 69 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,22 @@

---

Tiny (4.6kB minified) no-dependency library for generating random or sequential UUID of any length
Tiny (6.7kB minified) no-dependency library for generating random or sequential UUID of any length
with exceptionally minuscule probabilies of duplicate IDs.

```ts
const uid = new ShortUniqueId({ length: 10 });
uid(); // p0ZoB1FwH6
uid(); // mSjGCTfn8w
uid(); // yt4Xx5nHMB
uid.rnd(); // p0ZoB1FwH6
uid.rnd(); // mSjGCTfn8w
uid.rnd(); // yt4Xx5nHMB
// ...

// or

const { randomUUID } = new ShortUniqueId({ length: 10 });
randomUUID(); // e8Civ0HoDy
randomUUID(); // iPjiGoHXAK
randomUUID(); // n528gSMwTN
// ...
```

Expand Down Expand Up @@ -54,7 +62,8 @@ _NOTE: 👆 On these links you will also find explanations for the math used wit

## Open source notice

This project is open to updates by its users, I ensure that PRs are relevant to the community.
This project is part of the [Open Collective](https://opencollective.com/simplyhexagonal) project [Simply Hexagonal](https://simplyhexagonal.org)
and is open to updates by its users, we 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).

Expand All @@ -66,9 +75,16 @@ Please consider:
- Supporting me on [Patreon](https://www.patreon.com/jeanlescure) 🏆
- Starring this repo on [Github](https://github.com/jeanlescure/short-unique-id) 🌟

## 📣 v4 Notice
## 📣 v5 Notice

In order to improve security compliance we have removed the ability to use a ShortUniqueId as a
function, i.e. `const uid = new ShortUniqueId(); uid();` is no longer supported.

### New Features 🥳
If you plan to upgrade to v5 make sure to refactor `uid();` to `uid.rnd();` in your code beforehand.

For more information regarding this decision you can view [issue #53](https://github.com/simplyhexagonal/short-unique-id/issues/53).

### Features

The ability to generate UUIDs that contain a timestamp which can be extracted:

Expand Down Expand Up @@ -113,7 +129,7 @@ avoid dictionary injection vulnerabilities):
```js
// instantiate using one of the default dictionary strings
const uid = new ShortUniqueId({
dictionary: 'hex', // the default
dictionary: 'hex',
});

console.log(uid.dict.join());
Expand All @@ -126,19 +142,33 @@ console.log(uid.dict.join());
// 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
```

Ability to use custom formatting.

Where `$r` is random UUID, `$s` is sequential UUID, and `$t` is timestamp UUID:

```js
const timestamp = new Date('2023-01-29T03:21:21.000Z');
const result = uid.formattedUUID('Time: $t0 ID: $s2-$r4', timestamp); // timestamp is optional

console.log(result);
// Time: 63d5e631 ID: 0b-aaab
```

### Use in CLI

```sh
$ npm install -g short-unique-id
$ npm install --global short-unique-id

$ suid -h

# Usage:
# node short-unique-id [OPTION]

#
# Options:
# -l, --length=ARG character length of the uid to generate.
# -s, --stamp include timestamp in uid (must be used with --length (-l) of 10 or more).
# -t, --timestamp=ARG custom timestamp to parse (must be used along with -s, --stamp, -f, or --format).
# -f, --format=ARG string representing custom format to generate id with.
# -p, --parse=ARG extract timestamp from stamped uid (ARG).
# -d, --dictionaryJson=ARG json file with dictionary array.
# -h, --help display this help
Expand All @@ -149,14 +179,14 @@ $ suid -h
Add to your project:

```js
// Deno (web module) Import
import ShortUniqueId from 'https://esm.sh/short-unique-id';

// ES6 / TypeScript Import
import ShortUniqueId from 'short-unique-id';

// Node.js require
const ShortUniqueId = require('short-unique-id');

// Deno (web module) Import
import ShortUniqueId from 'https://esm.sh/short-unique-id';
```

Instantiate and use:
Expand All @@ -166,12 +196,28 @@ Instantiate and use:
const uid = new ShortUniqueId();

// Random UUID
console.log(uid());
console.log(uid.rnd());

// Sequential UUID
console.log(uid.seq());
```

alternatively using destructuring assignment:

```js
// Instantiate and destructure (long method name recommended for code readability)
const { randomUUID, sequentialUUID } = new ShortUniqueId();

// Random UUID
console.log(randomUUID());

// Sequential UUID
console.log(sequentialUUID());
```

_NOTE:_ we made sure to use `bind()` on all ShortUniqueId methods to ensure that any options
passed when creating the instance will be respected by the destructured methods.

### Use in browser

```html
Expand All @@ -184,7 +230,7 @@ console.log(uid.seq());
var uid = new ShortUniqueId();
// Random UUID
document.write(uid());
document.write(uid.rnd());
// Sequential UUID
document.write(uid.seq());
Expand Down Expand Up @@ -241,13 +287,17 @@ To find out more about the math behind these functions please refer to the

This 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/).

![image depicting over 12000 weekly npm downloads](https://raw.githubusercontent.com/jeanlescure/short-unique-id/main/assets/weekly-downloads.png)
![image depicting over 100000 weekly cdn hits](https://raw.githubusercontent.com/jeanlescure/short-unique-id/main/assets/weekly-cdn-hits.png)
![image depicting over 200000 weekly npm downloads](https://raw.githubusercontent.com/jeanlescure/short-unique-id/main/assets/weekly-downloads.png)
![image depicting over 16000000 weekly cdn hits](https://raw.githubusercontent.com/jeanlescure/short-unique-id/main/assets/weekly-cdn-hits.png)

Since this package is now reporting 12k+ npm weekly downloads and 100k+ weekly cdn hits,
Since this package is now reporting 200k+ npm weekly downloads and 16M+ weekly cdn hits,
we've gone ahead and re-written the whole of it in TypeScript and made sure to package
dist modules compatible with Deno, Node.js and all major Browsers.

## Sponsors

- [Clever Synapse](https://cleversynapse.com)

## Development

Clone this repo:
Expand Down Expand Up @@ -319,5 +369,5 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d

## License

Copyright (c) 2018-2021 [Short Unique ID Contributors](https://github.com/jeanlescure/short-unique-id/#contributors-).<br/>
Copyright (c) 2018-2023 [Short Unique ID Contributors](https://github.com/jeanlescure/short-unique-id/#contributors-).<br/>
Licensed under the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0).
Binary file modified assets/weekly-cdn-hits.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified assets/weekly-downloads.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 7 additions & 3 deletions bin/short-unique-id
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
#!/usr/bin/env node
const fs = require('fs');
const assert = require('assert');
const ShortUniqueId = require('short-unique-id');
const ShortUniqueId = require('../dist/short-unique-id');

const [,, ...args] = process.argv;

const {options} = require('./getopts').create([
['l' , 'length=ARG', 'character length of the uid to generate.'],
['s' , 'stamp', 'include timestamp in uid (must be used with --length (-l) of 10 or more).'],
['t' , 'timestamp=ARG', 'custom timestamp to parse (must be used along with -s, --stamp, -f, or --format).'],
['f' , 'format=ARG', 'string representing custom format to generate id with.'],
['p' , 'parse=ARG', 'extract timestamp from stamped uid (ARG).'],
['d' , 'dictionaryJson=ARG', 'json file with dictionary array.'],
])
Expand Down Expand Up @@ -48,8 +50,10 @@ if ('dictionaryJson' in options) {

const uid = new ShortUniqueId(uidOps);

if ('stamp' in options) {
console.log(uid.stamp(uidOps.length || 10));
if ('format' in options) {
console.log(uid.formattedUUID(options.format, new Date(options.timestamp || Date.now())));
} else if ('stamp' in options) {
console.log(uid.stamp(uidOps.length || 10, new Date(options.timestamp || Date.now())));
} else if ('parse' in options) {
console.log(uid.parseStamp(options.parse));
} else {
Expand Down
37 changes: 27 additions & 10 deletions dist/short-unique-id.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
interface ShortUniqueIdRanges {
[k: string]: [number, number];
}
declare type defaultDictionaries = 'number' | 'alpha' | 'alpha_lower' | 'alpha_upper' | 'alphanum' | 'alphanum_lower' | 'alphanum_upper' | 'hex';
interface ShortUniqueIdRangesMap {
[k: string]: ShortUniqueIdRanges;
}
type defaultDictionaries = 'number' | 'alpha' | 'alpha_lower' | 'alpha_upper' | 'alphanum' | 'alphanum_lower' | 'alphanum_upper' | 'hex';
/**
* ```js
* {
Expand All @@ -21,6 +24,8 @@ export interface ShortUniqueIdOptions {
debug: boolean;
/** From 1 to infinity, the length you wish your UUID to be */
length: number;
/** From 0 to infinity, the current value for the sequential UUID counter */
counter: number;
}
/**
* 6 was chosen as the default UUID length since for most cases
Expand All @@ -45,14 +50,14 @@ export declare const DEFAULT_UUID_LENGTH: number;
* // ES6 / TypeScript Import
* import ShortUniqueId from 'short-unique-id';
*
* //or Node.js require
* // or Node.js require
* const ShortUniqueId = require('short-unique-id');
*
* //Instantiate
* // Instantiate
* const uid = new ShortUniqueId();
*
* // Random UUID
* console.log(uid());
* console.log(uid.rnd());
*
* // Sequential UUID
* console.log(uid.seq());
Expand All @@ -70,7 +75,7 @@ export declare const DEFAULT_UUID_LENGTH: number;
* var uid = new ShortUniqueId();
*
* // Random UUID
* document.write(uid());
* document.write(uid.rnd());
*
* // Sequential UUID
* document.write(uid.seq());
Expand All @@ -89,7 +94,7 @@ export declare const DEFAULT_UUID_LENGTH: number;
*
* For more information take a look at the [ShortUniqueIdOptions type definition](/interfaces/shortuniqueidoptions.html).
*/
export default class ShortUniqueId extends Function {
export default class ShortUniqueId {
static default: typeof ShortUniqueId;
counter: number;
debug: boolean;
Expand All @@ -116,20 +121,28 @@ export default class ShortUniqueId extends Function {
protected _alphanum_lower_dict_ranges: ShortUniqueIdRanges;
protected _alphanum_upper_dict_ranges: ShortUniqueIdRanges;
protected _hex_dict_ranges: ShortUniqueIdRanges;
protected _dict_ranges: ShortUniqueIdRangesMap;
protected log: (...args: any[]) => void;
/** Change the dictionary after initialization. */
setDictionary: (dictionary: string[] | defaultDictionaries, shuffle?: boolean | undefined) => void;
setDictionary: (dictionary: string[] | defaultDictionaries, shuffle?: boolean) => void;
seq: () => string;
/**
* Generates UUID based on internal counter that's incremented after each ID generation.
* @alias `const uid = new ShortUniqueId(); uid.seq();`
*/
sequentialUUID: () => string;
rnd: (uuidLength?: number) => string;
/**
* Generates UUID by creating each part randomly.
* @alias `const uid = new ShortUniqueId(); uid(uuidLength: number);`
* @alias `const uid = new ShortUniqueId(); uid.rnd(uuidLength: number);`
*/
randomUUID: (uuidLength?: number) => string;
fmt: (format: string, date?: Date) => string;
/**
* Generates custom UUID with the provided format string.
* @alias `const uid = new ShortUniqueId(); uid.fmt(format: string);`
*/
formattedUUID: (format: string, date?: Date) => string;
/**
* Calculates total number of possible UUIDs.
*
Expand Down Expand Up @@ -227,7 +240,7 @@ export default class ShortUniqueId extends Function {
* // 2021-05-03T06:24:58.000Z
* ```
*/
stamp: (finalLength: number) => string;
stamp: (finalLength: number, date?: Date) => string;
/**
* Extracts the date embeded in a UUID generated using the `uid.stamp(finalLength);` method.
*
Expand All @@ -240,7 +253,11 @@ export default class ShortUniqueId extends Function {
* // 2021-05-03T06:24:58.000Z
* ```
*/
parseStamp: (stamp: string) => Date;
parseStamp: (suid: string, format?: string) => Date;
/**
* Set the counter to a specific value.
*/
setCounter: (counter: number) => void;
constructor(argOptions?: Partial<ShortUniqueIdOptions>);
}
export {};
Loading

0 comments on commit 5fed48e

Please sign in to comment.