Move to ESM name export
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Andrey Sitnik · committed by Andrey Sitnik · parent 58b7f94 · Browse files · 47 files·+853 added−1149 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
47 files+853 added−1149 removed
- tests:+384 added−592 removed
- other:+469 added−557 removed
Provenance
- Commit
4c7548a- Tree
a1b5e76- Author
Andrey Sitnik <andrey@sitnik.ru>- Committer
Andrey Sitnik <andrey@sitnik.ru>- Parent
58b7f94
47 files changed+853 added−1149 removed
deleted:async/format/index.browser.js-41 removed
1234567891011121314151617181920212223242526272829303132333435363738394041// This file replaces `async/format.js` in bundlers like webpack or Rollup,// according to `browser` config in `package.json`.
module.exports = (random, alphabet, size) => { // We can’t use bytes bigger than the alphabet. To make bytes values closer // to the alphabet, we apply bitmask on them. We look for the closest // `2 ** x - 1` number, which will be bigger than alphabet size. If we have // 30 symbols in the alphabet, we will take 31 (00011111). // We do not use faster Math.clz32, because it is not available in browsers. let mask = (2 << Math.log(alphabet.length - 1) / Math.LN2) - 1 // Bitmask is not a perfect solution (in our example it will pass 31 bytes, // which is bigger than the alphabet). As a result, we will need more bytes, // than ID size, because we will refuse bytes bigger than the alphabet.
// Every hardware random generator call is costly, // because we need to wait for entropy collection. This is why often it will // be faster to ask for few extra bytes in advance, to avoid additional calls.
// Here we calculate how many random bytes should we call in advance. // It depends on ID length, mask / alphabet size and magic number 1.6 // (which was selected according benchmarks).
// -~f => Math.ceil(f) if n is float number // -~i => i + 1 if n is integer number let step = -~(1.6 * mask * size / alphabet.length)
let tick = id => random(step).then(bytes => { // Compact alternative for `for (var i = 0; i < step; i++)` let i = step while (i--) { // If random byte is bigger than alphabet even after bitmask, // we refuse it by `|| ''`. id += alphabet[bytes[i] & mask] || '' // More compact than `id.length + 1 === size` if (id.length === +size) return id } return tick(id) })
return tick('')}deleted:async/format/index.d.ts-33 removed
123456789101112131415161718192021222324252627282930313233/** * Secure random string generator with custom alphabet. * Non-blocking version. * * Alphabet must contain 256 symbols or less. Otherwise, the generator * will not be secure. * * ```js * import format from 'nanoid/async/format' * * function random (size) { * const result = [] * for (let i = 0; i < size; i++) { * result.push(randomByte()) * } * return Promise.resolve(result) * } * * formatAsync(random, "abcdef", 5).then(id => { * model.id = id //=> "fbaef" * }) * ``` * * @param random The random bytes generator. * @param alphabet Symbols to be used in new random string. * @param size The number of symbols in new random string. * @return Promise with random string. */export default function format ( random: (bytes: number) => Promise<Uint8Array>, alphabet: string, size?: number): stringdeleted:async/format/index.js-40 removed
12345678910111213141516171819202122232425262728293031323334353637383940module.exports = (random, alphabet, size = 21) => { // We can’t use bytes bigger than the alphabet. To make bytes values closer // to the alphabet, we apply bitmask on them. We look for the closest // `2 ** x - 1` number, which will be bigger than alphabet size. If we have // 30 symbols in the alphabet, we will take 31 (00011111). let mask = (2 << 31 - Math.clz32((alphabet.length - 1) | 1)) - 1 // Bitmask is not a perfect solution (in our example it will pass 31 bytes, // which is bigger than the alphabet). As a result, we will need more bytes, // than ID size, because we will refuse bytes bigger than the alphabet.
// Every hardware random generator call is costly, // because we need to wait for entropy collection. This is why often it will // be faster to ask for few extra bytes in advance, to avoid additional calls.
// Here we calculate how many random bytes should we call in advance. // It depends on ID length, mask / alphabet size and magic number 1.6 // (which was selected according benchmarks). let step = Math.ceil(1.6 * mask * size / alphabet.length)
let tick = id => random(step).then(bytes => { // Compact alternative for `for (var i = 0; i < step; i++)` let i = step while (i--) { // If random byte is bigger than alphabet even after bitmask, // we refuse it by `|| ''`. id += alphabet[bytes[i] & mask] || '' // More compact than `id.length + 1 === size` if (id.length === +size) return id } return tick(id) })
return tick('')}
/** * @callback asyncGenerator * @param {number} bytes The number of bytes to generate. * @return {Promise} Promise with array of random bytes. */deleted:async/generate/index.d.ts-22 removed
12345678910111213141516171819202122/** * Low-level function to change alphabet and ID size. * Non-blocking version. * * Alphabet must contain 256 symbols or less. Otherwise, the generator * will not be secure. * * @param alphabet Symbols to be used in ID. * @param size The number of symbols in ID. Defauls is 21. * @return Promise with random string. * * ```js * const nanoid = require('nanoid/async/generate') * generateAsync('0123456789абвгдеё', 5).then(id => { * model.id = id //=> "8ё56а" * }) * ``` */export default function generate ( alphabet: string, size?: number): Promise<string>deleted:async/generate/index.js-24 removed
123456789101112131415161718192021222324let random = require('../random')let format = require('../format')
/** * Low-level function to change alphabet and ID size. * * Alphabet must contain 256 symbols or less. Otherwise, the generator * will not be secure. * * @param {string} alphabet Symbols to be used in ID. * @param {number} size The number of symbols in ID. * * @return {Promise} Promise with random string. * * @example * const generateAsync = require('nanoid/async/generate') * generateAsync('0123456789абвгдеё', 5).then(id => { * model.id = id //=> "8ё56а" * }) * * @name generateAsync * @function */module.exports = format.bind(null, random)deleted:async/random/index.browser.js-6 removed
123456// This file replaces `async/random.js` in bundlers like webpack or Rollup,// according to `browser` config in `package.json`.
module.exports = bytes => Promise.resolve( self.crypto.getRandomValues(new Uint8Array(bytes)))deleted:async/random/index.d.ts-15 removed
123456789101112131415/** * Return array with random bytes from hardware random generator. * Non-blocking version. * * ```js * import random from 'nanoid/async/random' * import format from 'nanoid/async/format' * * format(random, "abcdef", 5) //=> "fbaef" * ``` * * @param bytes The size of array. * @returns Promise with array of random bytes. */export default function random (bytes: number): Promise<Uint8Array>modified:async/random/index.js+14 added-24 removed
123456789101112131434567891011121315141718192021222324252627151617let crypto = require('crypto')
if (crypto.randomFill) { // `crypto.randomFill()` is a little faster than `crypto.randomBytes()`, // because we can use faster `Buffer.allocUnsafe()`. module.exports = bytes => new Promise((resolve, reject) => { // `Buffer.allocUnsafe()` faster because it doesn’t clean memory. // We do not need it, since we will fill memory with new bytes anyway. crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { if (err) { reject(err) } else { resolve(buf) }// `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,// because we can use faster `Buffer.allocUnsafe()`.let random = bytes => new Promise((resolve, reject) => { // `Buffer.allocUnsafe()` faster because it doesn’t clean memory. // We do not need it, since we will fill memory with new bytes anyway. crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { if (err) { reject(err) } else { resolve(buf) } }) })} else { module.exports = bytes => new Promise((resolve, reject) => { crypto.randomBytes(bytes, (err, buf) => { if (err) { reject(err) } else { resolve(buf) } }) })}})
module.exports = { random }modified:async/random/index.rn.js+4 added-11 removed
1-let random2-try {3- random = require('expo-random')1+let expoRandom = require('expo-random')4-} catch (e) {5- throw new Error(6- 'React-Native does not have a built-in secure random generator. ' +7- 'Install `expo-random` locally or ' +8- 'if you don’t need unpredictable IDs, you can use `nanoid/non-secure`.'9- )10-}2 12-module.exports = bytes => random.getRandomBytesAsync(bytes)3+let random = bytes => expoRandom.getRandomBytesAsync(bytes)4+5+module.exports = { random }modified:async/index.browser.js+50 added-19 removed
1-// This file replaces `async/index.js` in bundlers like webpack or Rollup,2-// according to `browser` config in `package.json`.1+let nanoid2 = (alphabet, size = 21) => {2+ // We can’t use bytes bigger than the alphabet. To make bytes values closer3+ // to the alphabet, we apply bitmask on them. We look for the closest4+ // `2 ** x - 1` number, which will be bigger than alphabet size. If we have5+ // 30 symbols in the alphabet, we will take 31 (00011111).6+ // We do not use faster Math.clz32, because it is not available in browsers.7+ let mask = (2 << Math.log(alphabet.length - 1) / Math.LN2) - 18+ // Bitmask is not a perfect solution (in our example it will pass 31 bytes,9+ // which is bigger than the alphabet). As a result, we will need more bytes,10+ // than ID size, because we will refuse bytes bigger than the alphabet.11 4-// This alphabet uses a-z A-Z 0-9 _- symbols.5-// Symbols are generated for smaller size.6-// -_zyxwvutsrqponmlkjihgfedcba9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA7-let url = '-_'8-// Loop from 36 to 0 (from z to a and 9 to 0 in Base36).9-let i = 3610-while (i--) {11- // 36 is radix. Number.prototype.toString(36) returns number12- // in Base36 representation. Base36 is like hex, but it uses 0–9 and a-z.13- url += i.toString(36)12+ // Every hardware random generator call is costly,13+ // because we need to wait for entropy collection. This is why often it will14+ // be faster to ask for few extra bytes in advance, to avoid additional calls.15+16+ // Here we calculate how many random bytes should we call in advance.17+ // It depends on ID length, mask / alphabet size and magic number 1.618+ // (which was selected according benchmarks).19+20+ // -~f => Math.ceil(f) if n is float number21+ // -~i => i + 1 if n is integer number22+ let step = -~(1.6 * mask * size / alphabet.length)23+ let id = ''24+25+ while (true) {26+ let bytes = self.crypto.getRandomValues(new Uint8Array(step))27+ // Compact alternative for `for (var j = 0; j < step; j++)`28+ let i = step29+ while (i--) {30+ // If random byte is bigger than alphabet even after bitmask,31+ // we refuse it by `|| ''`.32+ id += alphabet[bytes[i] & mask] || ''33+ // More compact than `id.length + 1 === size`34+ if (id.length === +size) return id35+ }36+ }37 }15-// Loop from 36 to 10 (from Z to A in Base36).16-i = 3617-while (i-- - 10) {18- url += i.toString(36).toUpperCase()19-}38 21-module.exports = function (size = 21) {39+let nanoid = (size = 21) => {40 let id = ''41 let bytes = self.crypto.getRandomValues(new Uint8Array(size))42 43 // Compact alternative for `for (var i = 0; i < size; i++)`1 unmodified line45 // We can’t use bytes bigger than the alphabet. 63 is 00111111 bitmask.46 // This mask reduces random byte 0-255 to 0-63 values.47 // There is no need in `|| ''` and `* 1.6` hacks in here,48 // because bitmask trim bytes exact to alphabet size.31- id += url[bytes[i] & 63]49+ let byte = bytes[size] & 6350+ if (byte < 36) {51+ // 0-9a-z52+ id += byte.toString(36)53+ } else if (byte < 62) {54+ // A-Z55+ id += (byte - 26).toString(36).toUpperCase()56+ } else if (byte < 63) {57+ id += '_'58+ } else {59+ id += '-'60+ }61 }62 return Promise.resolve(id)63 }64+65+module.exports = { nanoid, nanoid2 }modified:async/index.d.ts+22 added-2 removed
3 unmodified lines4 * By default, ID will have 21 symbols to have a collision probability similar5 * to UUID v4.6 *7 * ```js8- * import nanoid from 'nanoid/async'8+ * import { nanoid } from 'nanoid/async'9 * nanoid().then(id => {10 * model.id = id11 * })12 * ```13 *14 * @param size The number of symbols in ID. Default is 21.15 * @return Promise with random string.16 */17-export default function nanoid (size?: number): Promise<string>17+export function nanoid (size?: number): Promise<string>18+19+/**20+ * Low-level function21+ * Generate secure unique ID with custom alphabet. Non-blocking version.22+ *23+ * Alphabet must contain 256 symbols or less. Otherwise, the generator24+ * will not be secure.25+ *26+ * @param alphabet Symbols to be used in ID.27+ * @param size The number of symbols in ID. Defauls is 21.28+ * @return Promise with random string.29+ *30+ * ```js31+ * const { nanoid2 } = require('nanoid/async')32+ * generate('0123456789абвгдеё', 5).then(id => {33+ * model.id = id //=> "8ё56а"34+ * })35+ * ```36+ */37+export function nanoid2 (alphabet: string, size?: number): Promise<string>modified:async/index.js+42 added-4 removed
1-let random = require('./random')2-let url = require('../url')1+let { random } = require('./random')2 3+let { urlAlphabet } = require('..')4+5+let nanoid2 = (alphabet, size = 21) => {6+ // We can’t use bytes bigger than the alphabet. To make bytes values closer7+ // to the alphabet, we apply bitmask on them. We look for the closest8+ // `2 ** x - 1` number, which will be bigger than alphabet size. If we have9+ // 30 symbols in the alphabet, we will take 31 (00011111).10+ let mask = (2 << 31 - Math.clz32((alphabet.length - 1) | 1)) - 111+ // Bitmask is not a perfect solution (in our example it will pass 31 bytes,12+ // which is bigger than the alphabet). As a result, we will need more bytes,13+ // than ID size, because we will refuse bytes bigger than the alphabet.14+15+ // Every hardware random generator call is costly,16+ // because we need to wait for entropy collection. This is why often it will17+ // be faster to ask for few extra bytes in advance, to avoid additional calls.18+19+ // Here we calculate how many random bytes should we call in advance.20+ // It depends on ID length, mask / alphabet size and magic number 1.621+ // (which was selected according benchmarks).22+ let step = Math.ceil(1.6 * mask * size / alphabet.length)23+24+ let tick = id => random(step).then(bytes => {25+ // Compact alternative for `for (var i = 0; i < step; i++)`26+ let i = step27+ while (i--) {28+ // If random byte is bigger than alphabet even after bitmask,29+ // we refuse it by `|| ''`.30+ id += alphabet[bytes[i] & mask] || ''31+ // More compact than `id.length + 1 === size`32+ if (id.length === +size) return id33+ }34+ return tick(id)35+ })36+37+ return tick('')38+}39+4-module.exports = (size = 21) => random(size).then(bytes => {40+let nanoid = (size = 21) => random(size).then(bytes => {41 let id = ''42 // Compact alternative for `for (var i = 0; i < size; i++)`43 while (size--) {44 // We can’t use bytes bigger than the alphabet. 63 is 00111111 bitmask.45 // This mask reduces random byte 0-255 to 0-63 values.46 // There is no need in `|| ''` and `* 1.6` hacks in here,47 // because bitmask trim bytes exact to alphabet size.12- id += url[bytes[size] & 63]48+ id += urlAlphabet[bytes[size] & 63]49 }50 return id51 })52+53+module.exports = { nanoid, nanoid2 }deleted:format/index.browser.js-40 removed
1-// This file replaces `format.js` in bundlers like webpack or Rollup,2-// according to `browser` config in `package.json`.3-4-module.exports = (random, alphabet, size) => {5- // We can’t use bytes bigger than the alphabet. To make bytes values closer6- // to the alphabet, we apply bitmask on them. We look for the closest7- // `2 ** x - 1` number, which will be bigger than alphabet size. If we have8- // 30 symbols in the alphabet, we will take 31 (00011111).9- // We do not use faster Math.clz32, because it is not available in browsers.10- let mask = (2 << Math.log(alphabet.length - 1) / Math.LN2) - 111- // Bitmask is not a perfect solution (in our example it will pass 31 bytes,12- // which is bigger than the alphabet). As a result, we will need more bytes,13- // than ID size, because we will refuse bytes bigger than the alphabet.14-15- // Every hardware random generator call is costly,16- // because we need to wait for entropy collection. This is why often it will17- // be faster to ask for few extra bytes in advance, to avoid additional calls.18-19- // Here we calculate how many random bytes should we call in advance.20- // It depends on ID length, mask / alphabet size and magic number 1.621- // (which was selected according benchmarks).22-23- // -~f => Math.ceil(f) if n is float number24- // -~i => i + 1 if n is integer number25- let step = -~(1.6 * mask * size / alphabet.length)26- let id = ''27-28- while (true) {29- let bytes = random(step)30- // Compact alternative for `for (var i = 0; i < step; i++)`31- let i = step32- while (i--) {33- // If random byte is bigger than alphabet even after bitmask,34- // we refuse it by `|| ''`.35- id += alphabet[bytes[i] & mask] || ''36- // More compact than `id.length + 1 === size`37- if (id.length === +size) return id38- }39- }40-}deleted:format/index.d.ts-30 removed
1-/**2- * Secure random string generator with custom alphabet.3- *4- * Alphabet must contain 256 symbols or less. Otherwise, the generator5- * will not be secure.6- *7- * ```js8- * import format from 'nanoid/format'9- *10- * function random (size) {11- * const result = []12- * for (let i = 0; i < size; i++) {13- * result.push(randomByte())14- * }15- * return result16- * }17- *18- * format(random, "abcdef", 5) //=> "fbaef"19- * ```20- *21- * @param random The random bytes generator.22- * @param alphabet Symbols to be used in new random string.23- * @param size The number of symbols in new random string.24- * @returns Random string.25- */26-export default function format (27- random: (bytes: number) => Uint8Array,28- alphabet: string,29- size?: number30-): stringdeleted:format/index.js-33 removed
1-module.exports = (random, alphabet, size = 21) => {2- // We can’t use bytes bigger than the alphabet. To make bytes values closer3- // to the alphabet, we apply bitmask on them. We look for the closest4- // `2 ** x - 1` number, which will be bigger than alphabet size. If we have5- // 30 symbols in the alphabet, we will take 31 (00011111).6- let mask = (2 << 31 - Math.clz32((alphabet.length - 1) | 1)) - 17- // Bitmask is not a perfect solution (in our example it will pass 31 bytes,8- // which is bigger than the alphabet). As a result, we will need more bytes,9- // than ID size, because we will refuse bytes bigger than the alphabet.10-11- // Every hardware random generator call is costly,12- // because we need to wait for entropy collection. This is why often it will13- // be faster to ask for few extra bytes in advance, to avoid additional calls.14-15- // Here we calculate how many random bytes should we call in advance.16- // It depends on ID length, mask / alphabet size and magic number 1.617- // (which was selected according benchmarks).18- let step = Math.ceil(1.6 * mask * size / alphabet.length)19- let id = ''20-21- while (true) {22- let bytes = random(step)23- // Compact alternative for `for (var i = 0; i < step; i++)`24- let i = step25- while (i--) {26- // If random byte is bigger than alphabet even after bitmask,27- // we refuse it by `|| ''`.28- id += alphabet[bytes[i] & mask] || ''29- // More compact than `id.length + 1 === size`30- if (id.length === +size) return id31- }32- }33-}deleted:generate/index.d.ts-16 removed
1-/**2- * Low-level function to change alphabet and ID size.3- *4- * Alphabet must contain 256 symbols or less. Otherwise, the generator5- * will not be secure.6- *7- * @param alphabet Symbols to be used in ID.8- * @param size The number of symbols in ID. Defauls is 21.9- * @returns Random string.10- *11- * ```js12- * const nanoid = require('nanoid/generate')13- * model.id = generate('0123456789абвгдеё', 5) //=> "8ё56а"14- * ```15- */16-export default function generate (alphabet: string, size?: number): stringdeleted:generate/index.js-4 removed
1-let random = require('../random')2-let format = require('../format')3-4-module.exports = format.bind(null, random)deleted:non-secure/generate/index.d.ts-14 removed
1-/**2- * Generate URL-friendly unique ID. This method use non-secure predictable3- * random generator with bigger collision probability.4- *5- * @param alphabet Symbols to be used in ID.6- * @param size The number of symbols in ID. Defauls is 21.7- * @returns Random string.8- *9- * ```js10- * const nanoid = require('nanoid/non-secure/generate')11- * model.id = generate('0123456789абвгдеё', 5) //=> "8ё56а"12- * ```13- */14-export default function generate (alphabet: string, size?: number): stringdeleted:non-secure/generate/index.js-9 removed
1-module.exports = (alphabet, size = 21) => {2- let id = ''3- // Complete alternative for `for (var i = 0; i < size; i++)`4- while (size--) {5- // `| 0` is compact and faster alternative for `Math.floor()`6- id += alphabet[Math.random() * alphabet.length | 0]7- }8- return id9-}modified:non-secure/index.d.ts+17 added-2 removed
1 unmodified line2 * Generate URL-friendly unique ID. This method use non-secure predictable3 * random generator with bigger collision probability.4 *5 * ```js6- * import nanoid from 'nanoid/non-secure'6+ * import { nanoid } from 'nanoid/non-secure'7 * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"8 * ```9 *10 * @param size The number of symbols in ID. Default is 21.11 * @returns Random string.12 */13-export default function nanoid (size?: number): string13+export function nanoid (size?: number): string14+15+/**16+ * Generate unique ID with custom alphabet. This method use non-secure17+ * predictable random generator with bigger collision probability.18+ *19+ * @param alphabet Symbols to be used in ID.20+ * @param size The number of symbols in ID. Defauls is 21.21+ * @returns Random string.22+ *23+ * ```js24+ * const { nanoid2 } = require('nanoid/non-secure')25+ * model.id = generate('0123456789абвгдеё', 5) //=> "8ё56а"26+ * ```27+ */28+export function nanoid2 (alphabet: string, size?: number): stringmodified:non-secure/index.js+23 added-17 removed
1-// This alphabet uses a-z A-Z 0-9 _- symbols.2-// Symbols are generated for smaller size.3-// -_zyxwvutsrqponmlkjihgfedcba9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA4-let url = '-_'5-// Loop from 36 to 0 (from z to a and 9 to 0 in Base36).6-let i = 367-while (i--) {8- // 36 is radix. Number.prototype.toString(36) returns number9- // in Base36 representation. Base36 is like hex, but it uses 0–9 and a-z.10- url += i.toString(36)1+let nanoid2 = (alphabet, size = 21) => {2+ let id = ''3+ // Complete alternative for `for (var i = 0; i < size; i++)`4+ while (size--) {5+ // `| 0` is compact and faster alternative for `Math.floor()`6+ id += alphabet[Math.random() * alphabet.length | 0]7+ }8+ return id9 }12-// Loop from 36 to 10 (from Z to A in Base36).13-i = 3614-while (i-- - 10) {15- url += i.toString(36).toUpperCase()16-}10 18-module.exports = (size = 21) => {11+let nanoid = (size = 21) => {12 let id = ''13 // Compact alternative for `for (var i = 0; i < size; i++)`14 while (size--) {15 // `| 0` is compact and faster alternative for `Math.floor()`23- id += url[Math.random() * 64 | 0]16+ let byte = Math.random() * 64 | 017+ if (byte < 36) {18+ // 0-9a-z19+ id += byte.toString(36)20+ } else if (byte < 62) {21+ // A-Z22+ id += (byte - 26).toString(36).toUpperCase()23+ } else if (byte < 63) {24+ id += '_'25+ } else {26+ id += '-'27+ }28 }29 return id30 }31+32+module.exports = { nanoid, nanoid2 }deleted:random/index.browser.js-1 removed
1-module.exports = bytes => self.crypto.getRandomValues(new Uint8Array(bytes))deleted:random/index.d.ts-14 removed
1-/**2- * Return array with random bytes from hardware random generator.3- *4- * ```js5- * import random from 'nanoid/random'6- * import format from 'nanoid/format'7- *8- * format(random, "abcdef", 5) //=> "fbaef"9- * ```10- *11- * @param bytes The size of array.12- * @returns Arrays with random bytes.13- */14-export default function random (bytes: number): Uint8Arraydeleted:random/index.js-19 removed
1-let crypto = require('crypto')2-3-if (crypto.randomFillSync) {4- // We reuse buffers with the same size to avoid memory fragmentations5- // for better performance6- let buffers = { }7- module.exports = bytes => {8- let buffer = buffers[bytes]9- if (!buffer) {10- // `Buffer.allocUnsafe()` faster because it doesn’t clean memory.11- // We do not need it, since we will fill memory with new bytes anyway.12- buffer = Buffer.allocUnsafe(bytes)13- if (bytes <= 255) buffers[bytes] = buffer14- }15- return crypto.randomFillSync(buffer)16- }17-} else {18- module.exports = crypto.randomBytes19-}modified:test/demo/index.js+7 added-9 removed
1-let shortid = require('shortid')2-let uuid4 = require('uuid/v4')3-let rndm = require('rndm')4-let uid = require('uid-safe')1+import shortid from 'shortid'2+import { v4 as uuid4 } from 'uuid'3+import rndm from 'rndm'4+import uid from 'uid-safe'5 6-let nonSecure = require('../../non-secure')7-let generate = require('../../generate')8-let random = require('../../random')9-let nanoid = require('../../')6+import { nanoid, nanoid2, random } from '../../'7+import { nanoid as nonSecure } from '../../non-secure'8 9 const COUNT = 50 * 100010 const ALPHABET = 'abcdefghijklmnopqrstuvwxyz'11 const LENGTH = ALPHABET.length57 unmodified lines69 }70 return result71 }),72 () => printDistr('nanoid', () => nanoid()),75- () => printDistr('nanoid/generate', () => generate(ALPHABET, LENGTH)),73+ () => printDistr('nanoid2', () => nanoid2(ALPHABET, LENGTH)),74 () => printDistr('uid.sync', () => uid.sync(21)),75 () => printDistr('uuid/v4', () => uuid4()),76 () => printDistr('shortid', () => shortid()),77 () => printDistr('rndm', () => rndm()),20 unmodified linesdeleted:test/async-format.test.js-35 removed
1-let format = require('../async/format')2-let random = require('../async/random')3-4-it('supports generator', async () => {5- let sequence = [2, 255, 3, 7, 7, 7, 7, 7, 0, 1]6- async function customRandom (size) {7- let bytes = []8- for (let i = 0; i < size; i += sequence.length) {9- bytes = bytes.concat(sequence.slice(0, size - i))10- }11- return bytes12- }13- expect(await format(customRandom, 'abcde', 4)).toEqual('adca')14- expect(await format(customRandom, 'abcde', 14)).toEqual('cbadcbadcbadcc')15-})16-17-it('respects size', async () => {18- expect(await format(random, 'abcde', 4)).toHaveLength(4)19- expect(await format(random, 'abcde', 20)).toHaveLength(20)20-})21-22-it('is ready for errors', async () => {23- let error = new Error('test')24- async function brokenRandom () {25- throw error26- }27-28- let catched29- try {30- await format(brokenRandom, 'abc', 4)31- } catch (e) {32- catched = e33- }34- expect(catched).toBe(error)35-})deleted:test/async-generate.test.js-44 removed
1-let generate = require('../async/generate')2-3-function times (size, callback) {4- let array = []5- for (let i = 0; i < 100; i++) {6- array.push(1)7- }8- return array.map(callback)9-}10-11-it('has options', async () => {12- let id = await generate('a', 5)13- expect(id).toEqual('aaaaa')14-})15-16-it('accepts string', async () => {17- let id = await generate('a', '5')18- expect(id).toEqual('aaaaa')19-})20-21-it('has flat distribution', async () => {22- let COUNT = 100 * 100023- let LENGTH = 524- let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'25-26- let chars = { }27- await Promise.all(times(100, async () => {28- let id = await generate(ALPHABET, LENGTH)29- expect(id).toHaveLength(LENGTH)30- for (let char of id) {31- if (!chars[char]) chars[char] = 032- chars[char] += 133- }34- }))35- expect(Object.keys(chars)).toHaveLength(ALPHABET.length)36- let max = 037- let min = Number.MAX_SAFE_INTEGER38- for (let k in chars) {39- let distribution = (chars[k] * ALPHABET.length) / (COUNT * LENGTH)40- if (distribution > max) max = distribution41- if (distribution < min) min = distribution42- }43- expect(max - min).toBeLessThanOrEqual(0.05)44-})deleted:test/async-random.test.js-74 removed
1-let crypto = require('crypto')2-3-let random = require('../async/random')4-5-function mock (callback) {6- crypto.randomFill = callback7- jest.resetModules()8- random = require('../async/random')9-}10-11-let originFill = crypto.randomFill12-let randomBytes = crypto.randomBytes13-afterEach(() => {14- mock(originFill)15- crypto.randomBytes = randomBytes16-})17-18-it('generates random buffers', async () => {19- let bytes = await random(10000)20- expect(bytes).toHaveLength(10000)21- let numbers = { }22- for (let byte of bytes) {23- if (!numbers[byte]) numbers[byte] = 024- numbers[byte] += 125- expect(typeof byte).toEqual('number')26- expect(byte).toBeLessThanOrEqual(255)27- expect(byte).toBeGreaterThanOrEqual(0)28- }29-})30-31-it('supports old Node.js', async () => {32- mock(undefined)33- let bytes = await random(10000)34- expect(bytes).toHaveLength(10000)35- let numbers = { }36- for (let byte of bytes) {37- if (!numbers[byte]) numbers[byte] = 038- numbers[byte] += 139- expect(typeof byte).toEqual('number')40- expect(byte).toBeLessThanOrEqual(255)41- expect(byte).toBeGreaterThanOrEqual(0)42- }43-})44-45-it('is ready for error', async () => {46- let error = new Error('test')47- mock((size, callback) => {48- callback(error)49- })50-51- let catched52- try {53- await random(10000)54- } catch (e) {55- catched = e56- }57- expect(catched).toBe(error)58-})59-60-it('is ready for error from old API', async () => {61- let error = new Error('test')62- mock(undefined)63- crypto.randomBytes = function (size, callback) {64- callback(error)65- }66-67- let catched68- try {69- await random(10000)70- } catch (e) {71- catched = e72- }73- expect(catched).toBe(error)74-})modified:test/async.test.js+126 added-83 removed
1 let crypto = require('crypto')2 3-let async = require('../async')4-let url = require('../url')3+global.self = {4+ crypto: {5+ getRandomValues (array) {6+ for (let i = 0; i < array.length; i++) {7+ array[i] = Math.floor(Math.random() * 256)8+ }9+ return array10+ }11+ }12+}13 14+let browser = require('../async/index.browser.js')15+let node = require('../async/index.js')16+17+let { urlAlphabet } = require('..')18+19 function times (size, callback) {20 let array = []8- for (let i = 0; i < 100; i++) {21+ for (let i = 0; i < size; i++) {22 array.push(1)23 }24 return array.map(callback)25 }26 14-function mock (callback) {15- crypto.randomFill = callback16- jest.resetModules()17- async = require('../async')18-}27+for (let type of ['node', 'browser']) {28+ describe(`${ type }`, () => {29+ let { nanoid, nanoid2 } = type === 'node' ? node : browser30 31+ describe('nanoid', () => {32+ function mock (callback) {33+ crypto.randomFill = callback34+ jest.resetModules()35+ nanoid = require('../async').nanoid36+ }37+ if (type === 'node') {20-let originFill = crypto.randomFill21-afterEach(() => {22- mock(originFill)23-})38+ let originFill = crypto.randomFill39+ afterEach(() => {40+ mock(originFill)41+ })42+ }43 25-it('generates URL-friendly IDs', async () => {26- await Promise.all(times(100, async () => {27- let id = await async()28- expect(id).toHaveLength(21)29- expect(typeof id).toEqual('string')30- for (let char of id) {31- expect(url).toContain(char)32- }33- }))34-})44+ it('generates URL-friendly IDs', async () => {45+ await Promise.all(times(100, async () => {46+ let id = await nanoid()47+ expect(id).toHaveLength(21)48+ expect(typeof id).toEqual('string')49+ for (let char of id) {50+ expect(urlAlphabet).toContain(char)51+ }52+ }))53+ })54 36-it('supports old Node.js', async () => {37- mock(undefined)38- await Promise.all(times(100, async () => {39- let id = await async()40- expect(id).toHaveLength(21)41- }))42-})55+ it('changes ID length', async () => {56+ let id = await nanoid(10)57+ expect(id).toHaveLength(10)58+ })59 44-it('changes ID length', async () => {45- let id = await async(10)46- expect(id).toHaveLength(10)47-})60+ it('has no collisions', async () => {61+ let ids = await Promise.all(times(100 * 1000, () => nanoid()))62+ ids.reduce((used, id) => {63+ expect(used[id]).toBeUndefined()64+ used[id] = true65+ return used66+ }, [])67+ })68 49-it('throws on string', async () => {50- let error51- try {52- await async('10')53- } catch (e) {54- error = e55- }56- expect(error.message).toContain('"size" argument must be')57-})69+ it('has flat distribution', async () => {70+ let COUNT = 100 * 100071+ let LENGTH = (await nanoid()).length72 59-it('has no collisions', async () => {60- let ids = await Promise.all(times(100 * 1000, () => async()))61- ids.reduce((used, id) => {62- expect(used[id]).toBeUndefined()63- used[id] = true64- return used65- }, [])66-})73+ let chars = { }74+ await Promise.all(times(COUNT, async () => {75+ let id = await nanoid()76+ for (let char of id) {77+ if (!chars[char]) chars[char] = 078+ chars[char] += 179+ }80+ }))81+ expect(Object.keys(chars)).toHaveLength(urlAlphabet.length)82+ let max = 083+ let min = Number.MAX_SAFE_INTEGER84+ for (let k in chars) {85+ let distribution = (chars[k] * urlAlphabet.length) / (COUNT * LENGTH)86+ if (distribution > max) max = distribution87+ if (distribution < min) min = distribution88+ }89+ expect(max - min).toBeLessThanOrEqual(0.05)90+ })91 68-it('has flat distribution', async () => {69- let COUNT = 100 * 100070- let LENGTH = async().length92+ if (type === 'node') {93+ it('rejects Promise on error', async () => {94+ let error = new Error('test')95+ mock((buffer, callback) => {96+ callback(error)97+ })98+ let catched99+ try {100+ await nanoid()101+ } catch (e) {102+ catched = e103+ }104+ expect(catched).toBe(error)105+ })106+ }107+ })108 72- let chars = { }73- await Promise.all(times(COUNT, async () => {74- let id = await async()75- for (let char of id) {76- if (!chars[char]) chars[char] = 077- chars[char] += 178- }79- }))80- expect(Object.keys(chars)).toHaveLength(url.length)81- let max = 082- let min = Number.MAX_SAFE_INTEGER83- for (let k in chars) {84- let distribution = (chars[k] * url.length) / (COUNT * LENGTH)85- if (distribution > max) max = distribution86- if (distribution < min) min = distribution87- }88- expect(max - min).toBeLessThanOrEqual(0.05)89-})109+ describe('nanoid2', () => {110+ it('has options', async () => {111+ let id = await nanoid2('a', 5)112+ expect(id).toEqual('aaaaa')113+ })114 91-it('rejects Promise on error', async () => {92- let error = new Error('test')93- mock((buffer, callback) => {94- callback(error)115+ it('accepts string', async () => {116+ let id = await nanoid2('a', '5')117+ expect(id).toEqual('aaaaa')118+ })119+120+ it('has flat distribution', async () => {121+ let COUNT = 100 * 1000122+ let LENGTH = 5123+ let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'124+125+ let chars = { }126+ await Promise.all(times(100, async () => {127+ let id = await nanoid2(ALPHABET, LENGTH)128+ expect(id).toHaveLength(LENGTH)129+ for (let char of id) {130+ if (!chars[char]) chars[char] = 0131+ chars[char] += 1132+ }133+ }))134+ expect(Object.keys(chars)).toHaveLength(ALPHABET.length)135+ let max = 0136+ let min = Number.MAX_SAFE_INTEGER137+ for (let k in chars) {138+ let distribution = (chars[k] * ALPHABET.length) / (COUNT * LENGTH)139+ if (distribution > max) max = distribution140+ if (distribution < min) min = distribution141+ }142+ expect(max - min).toBeLessThanOrEqual(0.05)143+ })144+ })145 })96- let catched97- try {98- await async()99- } catch (e) {100- catched = e101- }146+}102- expect(catched).toBe(error)103-})modified:test/benchmark+17 added-19 removed
1 #!/usr/bin/env node2 3+let { v4: uuid4 } = require('uuid')4 let benchmark = require('benchmark')5 let shortid = require('shortid')5-let uuid4 = require('uuid/v4')6 let chalk = require('chalk')7 let rndm = require('rndm')8 let srs = require('secure-random-string')9 let uid = require('uid-safe')10 11-let asyncGenerate = require('../async/generate')12-let nonSecure = require('../non-secure')13-let generate = require('../generate')14-let nanoid = require('../')15-let async = require('../async')11+let { nanoid: asyncNanoid, nanoid2: asyncNanoid2 } = require('../async')12+let { nanoid: nonSecure } = require('../non-secure')13+let { nanoid, nanoid2 } = require('../')14 15 let suite = new benchmark.Suite()16 17 function formatNumber (number) {5 unmodified lines23 suite24 .add('nanoid', () => {25 nanoid()26 })29- .add('nanoid/generate', () => {30- generate('1234567890abcdef-', 10)27+ .add('nanoid2', () => {28+ nanoid2('1234567890abcdef-', 10)29 })30 .add('uid.sync', () => {31 uid.sync(14)32 })35- .add('uuid/v4', () => {33+ .add('uuid v4', () => {34 uuid4()35 })36 .add('secure-random-string', () => {37 srs()38 })39 .add('shortid', () => {40 shortid()41 })44- .add('nanoid/async', {42+ .add('async nanoid', {43 defer: true,44 fn (defer) {47- async().then(() => {45+ asyncNanoid().then(() => {46 defer.resolve()47 })48 }49 })52- .add('nanoid/async/generate', {50+ .add('async nanoid2', {51 defer: true,52 fn (defer) {55- asyncGenerate('1234567890abcdef-', 10).then(() => {53+ asyncNanoid2('1234567890abcdef-', 10).then(() => {54 defer.resolve()55 })56 }57 })60- .add('secure-random-string', {58+ .add('async secure-random-string', {59 defer: true,60 fn (defer) {61 srs(() => {62 defer.resolve()7 unmodified lines70 defer.resolve()71 })72 }73 })76- .add('nanoid/non-secure', () => {74+ .add('non-secure nanoid', () => {75 nonSecure()76 })77 .add('rndm', () => {78 rndm(21)79 })80 .on('cycle', event => {83- let name = event.target.name.padEnd('nanoid/async/generate'.length)81+ let name = event.target.name.padEnd('async secure-random-string'.length)82 let hz = formatNumber(event.target.hz.toFixed(0)).padStart(9)85- if (event.target.name === 'nanoid/async') {83+ if (event.target.name === 'async nanoid') {84 name = '\nAsync:\n' + name87- } else if (event.target.name === 'nanoid/non-secure') {85+ } else if (event.target.name === 'non-secure nanoid') {86 name = '\nNon-secure:\n' + name87 }90- process.stdout.write(`${ name } ${ chalk.bold(hz) } ops/sec\n`)88+ process.stdout.write(`${ name }${ chalk.bold(hz) } ops/sec\n`)89 })90 .run()deleted:test/browser.test.js-93 removed
1-global.self = {2- crypto: {3- getRandomValues (array) {4- for (let i = 0; i < array.length; i++) {5- array[i] = Math.floor(Math.random() * 256)6- }7- return array8- }9- }10-}11-12-let nanoid = require('../index.browser')13-let format = require('../format/index.browser')14-let random = require('../random/index.browser')15-let async = require('../async/index.browser')16-let asyncFormat = require('../async/format/index.browser')17-let asyncRandom = require('../async/random/index.browser')18-let url = require('../url')19-20-function times (size, callback) {21- let array = []22- for (let i = 0; i < 100; i++) {23- array.push(1)24- }25- return array.map(callback)26-}27-28-it('generates URL-friendly IDs', () => {29- for (let i = 0; i < 100; i++) {30- let id = nanoid()31- expect(id).toHaveLength(21)32- expect(typeof id).toEqual('string')33- for (let char of id) {34- expect(url).toContain(char)35- }36- }37-})38-39-it('changes ID length', () => {40- expect(nanoid(10)).toHaveLength(10)41-})42-43-it('supports generator', () => {44- let sequence = [2, 255, 3, 7, 7, 7, 7, 7, 0, 1]45- function customRandom (size) {46- let bytes = []47- for (let i = 0; i < size; i += sequence.length) {48- bytes = bytes.concat(sequence.slice(0, size - i))49- }50- return bytes51- }52- expect(format(customRandom, 'abcde', 4)).toEqual('adca')53- expect(format(customRandom, 'abcde', 20)).toEqual('dcbadcbadcbadcbadcdc')54-})55-56-it('respects size', () => {57- expect(format(random, 'abcde', 4)).toHaveLength(4)58- expect(format(random, 'abcde', 20)).toHaveLength(20)59-})60-61-it('generates IDs with Promise', async () => {62- await Promise.all(times(100, async () => {63- let id = await async()64- expect(id).toHaveLength(21)65- expect(typeof id).toEqual('string')66- for (let char of id) {67- expect(url).toContain(char)68- }69- }))70-})71-72-it('changes ID length in async', async () => {73- let id = await async(10)74- expect(id).toHaveLength(10)75-})76-77-it('supports async generator', async () => {78- let sequence = [2, 255, 3, 7, 7, 7, 7, 7, 0, 1]79- async function customRandom (size) {80- let bytes = []81- for (let i = 0; i < size; i += sequence.length) {82- bytes = bytes.concat(sequence.slice(0, size - i))83- }84- return bytes85- }86- expect(await asyncFormat(customRandom, 'abcde', 4)).toEqual('adca')87- expect(await asyncFormat(customRandom, 'abcde', 14)).toEqual('cbadcbadcbadcc')88-})89-90-it('respects size for async', async () => {91- expect(await asyncFormat(asyncRandom, 'abcde', 4)).toHaveLength(4)92- expect(await asyncFormat(asyncRandom, 'abcde', 20)).toHaveLength(20)93-})deleted:test/format.test.js-20 removed
1-let format = require('../format')2-let random = require('../random')3-4-it('supports generator', () => {5- let sequence = [2, 255, 3, 7, 7, 7, 7, 7, 0, 1]6- function customRandom (size) {7- let bytes = []8- for (let i = 0; i < size; i += sequence.length) {9- bytes = bytes.concat(sequence.slice(0, size - i))10- }11- return bytes12- }13- expect(format(customRandom, 'abcde', 4)).toEqual('adca')14- expect(format(customRandom, 'abcde', 18)).toEqual('cbadcbadcbadcbadcc')15-})16-17-it('respects size', () => {18- expect(format(random, 'abcde', 4)).toHaveLength(4)19- expect(format(random, 'abcde', 20)).toHaveLength(20)20-})deleted:test/generate.test.js-35 removed
1-let generate = require('../generate')2-3-it('has options', () => {4- expect(generate('a', 5)).toEqual('aaaaa')5-})6-7-it('accepts string', () => {8- expect(generate('a', '5')).toEqual('aaaaa')9-})10-11-it('has flat distribution', () => {12- let COUNT = 100 * 100013- let LENGTH = 514- let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'15-16- let chars = { }17- for (let i = 0; i < COUNT; i++) {18- let id = generate(ALPHABET, LENGTH)19- for (let char of id) {20- if (!chars[char]) chars[char] = 021- chars[char] += 122- }23- }24-25- expect(Object.keys(chars)).toHaveLength(ALPHABET.length)26-27- let max = 028- let min = Number.MAX_SAFE_INTEGER29- for (let k in chars) {30- let distribution = (chars[k] * ALPHABET.length) / (COUNT * LENGTH)31- if (distribution > max) max = distribution32- if (distribution < min) min = distribution33- }34- expect(max - min).toBeLessThanOrEqual(0.05)35-})modified:test/index.test.js+153 added-46 removed
1-let nanoid = require('../')2-let url = require('../url')3-4-it('generates URL-friendly IDs', () => {5- for (let i = 0; i < 100; i++) {6- let id = nanoid()7- expect(id).toHaveLength(21)8- expect(typeof id).toEqual('string')9- for (let char of id) {10- expect(url).toContain(char)1+global.self = {2+ crypto: {3+ getRandomValues (array) {4+ for (let i = 0; i < array.length; i++) {5+ array[i] = Math.floor(Math.random() * 256)6+ }7+ return array8 }9 }13-})10+}11 15-it('changes ID length', () => {16- expect(nanoid(10)).toHaveLength(10)17-})12+let browser = require('../index.browser.js')13+let node = require('../index.js')14 19-it('accepts string', () => {20- expect(nanoid('10')).toHaveLength(10)21-})15+for (let type of ['node', 'browser']) {16+ describe(`${ type }`, () => {17+ let { nanoid, nanoid2, nanoid3, random, urlAlphabet } =18+ type === 'node' ? node : browser19 23-it('has no collisions', () => {24- let used = { }25- for (let i = 0; i < 100 * 1000; i++) {26- let id = nanoid()27- expect(used[id]).toBeUndefined()28- used[id] = true29- }30-})20+ describe('nanoid', () => {21+ it('generates URL-friendly IDs', () => {22+ for (let i = 0; i < 100; i++) {23+ let id = nanoid()24+ expect(id).toHaveLength(21)25+ expect(typeof id).toEqual('string')26+ for (let char of id) {27+ expect(urlAlphabet).toContain(char)28+ }29+ }30+ })31 32-it('has flat distribution', () => {33- let COUNT = 100 * 100034- let LENGTH = nanoid().length32+ it('changes ID length', () => {33+ expect(nanoid(10)).toHaveLength(10)34+ })35 36- let chars = { }37- for (let i = 0; i < COUNT; i++) {38- let id = nanoid()39- for (let char of id) {40- if (!chars[char]) chars[char] = 041- chars[char] += 142- }43- }36+ it('accepts string', () => {37+ expect(nanoid('10')).toHaveLength(10)38+ })39 45- expect(Object.keys(chars)).toHaveLength(url.length)40+ it('has no collisions', () => {41+ let used = { }42+ for (let i = 0; i < 100 * 1000; i++) {43+ let id = nanoid()44+ expect(used[id]).toBeUndefined()45+ used[id] = true46+ }47+ })48 49+ it('has flat distribution', () => {50+ let COUNT = 100 * 100051+ let LENGTH = nanoid().length52+53+ let chars = { }54+ for (let i = 0; i < COUNT; i++) {55+ let id = nanoid()56+ for (let char of id) {57+ if (!chars[char]) chars[char] = 058+ chars[char] += 159+ }60+ }61+62+ expect(Object.keys(chars)).toHaveLength(urlAlphabet.length)63+47- let max = 048- let min = Number.MAX_SAFE_INTEGER49- for (let k in chars) {50- let distribution = (chars[k] * url.length) / (COUNT * LENGTH)51- if (distribution > max) max = distribution52- if (distribution < min) min = distribution53- }54- expect(max - min).toBeLessThanOrEqual(0.05)55-})64+ let max = 065+ let min = Number.MAX_SAFE_INTEGER66+ for (let k in chars) {67+ let distribution = (chars[k] * urlAlphabet.length) / (COUNT * LENGTH)68+ if (distribution > max) max = distribution69+ if (distribution < min) min = distribution70+ }71+ expect(max - min).toBeLessThanOrEqual(0.05)72+ })73+ })74+75+ describe('nanoid2', () => {76+ it('has options', () => {77+ expect(nanoid2('a', 5)).toEqual('aaaaa')78+ })79+80+ it('accepts string', () => {81+ expect(nanoid2('a', '5')).toEqual('aaaaa')82+ })83+84+ it('has flat distribution', () => {85+ let COUNT = 100 * 100086+ let LENGTH = 587+ let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'88+89+ let chars = { }90+ for (let i = 0; i < COUNT; i++) {91+ let id = nanoid2(ALPHABET, LENGTH)92+ for (let char of id) {93+ if (!chars[char]) chars[char] = 094+ chars[char] += 195+ }96+ }97+98+ expect(Object.keys(chars)).toHaveLength(ALPHABET.length)99+100+ let max = 0101+ let min = Number.MAX_SAFE_INTEGER102+ for (let k in chars) {103+ let distribution = (chars[k] * ALPHABET.length) / (COUNT * LENGTH)104+ if (distribution > max) max = distribution105+ if (distribution < min) min = distribution106+ }107+ expect(max - min).toBeLessThanOrEqual(0.05)108+ })109+ })110+111+ describe('nanoid3', () => {112+ it('supports generator', () => {113+ let sequence = [2, 255, 3, 7, 7, 7, 7, 7, 0, 1]114+ function customRandom (size) {115+ let bytes = []116+ for (let i = 0; i < size; i += sequence.length) {117+ bytes = bytes.concat(sequence.slice(0, size - i))118+ }119+ return bytes120+ }121+ expect(nanoid3(customRandom, 'abcde', 4)).toEqual('adca')122+ expect(nanoid3(customRandom, 'abcde', 18)).toEqual('cbadcbadcbadcbadcc')123+ })124+125+ it('respects size', () => {126+ expect(nanoid3(random, 'abcde', 4)).toHaveLength(4)127+ expect(nanoid3(random, 'abcde', 20)).toHaveLength(20)128+ })129+ })130+131+ describe('urlAlphabet', () => {132+ it('is string', () => {133+ expect(typeof urlAlphabet).toEqual('string')134+ })135+136+ it('has no duplicates', () => {137+ for (let i = 0; i < urlAlphabet.length; i++) {138+ expect(urlAlphabet.lastIndexOf(urlAlphabet[i])).toEqual(i)139+ }140+ })141+ })142+143+ describe('random', () => {144+ it('generates small random buffers', () => {145+ expect(random(10)).toHaveLength(10)146+ })147+148+ it('generates random buffers', () => {149+ let numbers = { }150+ let bytes = random(10000)151+ expect(bytes).toHaveLength(10000)152+ for (let byte of bytes) {153+ if (!numbers[byte]) numbers[byte] = 0154+ numbers[byte] += 1155+ expect(typeof byte).toEqual('number')156+ expect(byte).toBeLessThanOrEqual(255)157+ expect(byte).toBeGreaterThanOrEqual(0)158+ }159+ })160+ })161+ })162+}deleted:test/non-secure-generate.test.js-35 removed
1-let generate = require('../non-secure/generate')2-3-it('has options', () => {4- expect(generate('a', 5)).toEqual('aaaaa')5-})6-7-it('accepts string', () => {8- expect(generate('a', '5')).toEqual('aaaaa')9-})10-11-it('has flat distribution', () => {12- let COUNT = 100 * 100013- let LENGTH = 514- let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'15-16- let chars = { }17- for (let i = 0; i < COUNT; i++) {18- let id = generate(ALPHABET, LENGTH)19- for (let char of id) {20- if (!chars[char]) chars[char] = 021- chars[char] += 122- }23- }24-25- expect(Object.keys(chars)).toHaveLength(ALPHABET.length)26-27- let max = 028- let min = Number.MAX_SAFE_INTEGER29- for (let k in chars) {30- let distribution = (chars[k] * ALPHABET.length) / (COUNT * LENGTH)31- if (distribution > max) max = distribution32- if (distribution < min) min = distribution33- }34- expect(max - min).toBeLessThanOrEqual(0.05)35-})modified:test/non-secure.test.js+81 added-42 removed
1-let nonSecure = require('../non-secure')2-let url = require('../url')1+let { nanoid, nanoid2 } = require('../non-secure')2 3+let { urlAlphabet } = require('..')4+5+describe('nanoid', () => {4-it('generates URL-friendly IDs', () => {5- for (let i = 0; i < 10; i++) {6- let id = nonSecure()7- expect(id).toHaveLength(21)8- for (let char of id) {9- expect(url).toContain(char)6+ it('generates URL-friendly IDs', () => {7+ for (let i = 0; i < 10; i++) {8+ let id = nanoid()9+ expect(id).toHaveLength(21)10+ for (let char of id) {11+ expect(urlAlphabet).toContain(char)12+ }13 }11- }12-})14+ })15 14-it('changes ID length', () => {15- expect(nonSecure(10)).toHaveLength(10)16-})16+ it('changes ID length', () => {17+ expect(nanoid(10)).toHaveLength(10)18+ })19 18-it('accepts string', () => {19- expect(nonSecure('10')).toHaveLength(10)20-})20+ it('accepts string', () => {21+ expect(nanoid('10')).toHaveLength(10)22+ })23 22-it('has no collisions', () => {23- let used = { }24- for (let i = 0; i < 100 * 1000; i++) {25- let id = nonSecure()26- expect(used[id]).toBeUndefined()27- used[id] = true28- }24+ it('has no collisions', () => {25+ let used = { }26+ for (let i = 0; i < 100 * 1000; i++) {27+ let id = nanoid()28+ expect(used[id]).toBeUndefined()29+ used[id] = true30+ }31+ })32+33+ it('has flat distribution', () => {34+ let COUNT = 100 * 100035+ let LENGTH = nanoid().length36+37+ let chars = { }38+ for (let i = 0; i < COUNT; i++) {39+ let id = nanoid()40+ for (let char of id) {41+ if (!chars[char]) chars[char] = 042+ chars[char] += 143+ }44+ }45+46+ expect(Object.keys(chars)).toHaveLength(urlAlphabet.length)47+48+ let max = 049+ let min = Number.MAX_SAFE_INTEGER50+ for (let k in chars) {51+ let distribution = (chars[k] * urlAlphabet.length) / (COUNT * LENGTH)52+ if (distribution > max) max = distribution53+ if (distribution < min) min = distribution54+ }55+ expect(max - min).toBeLessThanOrEqual(0.05)56+ })57 })58 31-it('has flat distribution', () => {32- let COUNT = 100 * 100033- let LENGTH = nonSecure().length59+describe('nanoid2', () => {60+ it('has options', () => {61+ expect(nanoid2('a', 5)).toEqual('aaaaa')62+ })63 64+ it('accepts string', () => {65+ expect(nanoid2('a', '5')).toEqual('aaaaa')66+ })67+68+ it('has flat distribution', () => {69+ let COUNT = 100 * 100070+ let LENGTH = 571+ let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'72+35- let chars = { }36- for (let i = 0; i < COUNT; i++) {37- let id = nonSecure()38- for (let char of id) {39- if (!chars[char]) chars[char] = 040- chars[char] += 173+ let chars = { }74+ for (let i = 0; i < COUNT; i++) {75+ let id = nanoid2(ALPHABET, LENGTH)76+ for (let char of id) {77+ if (!chars[char]) chars[char] = 078+ chars[char] += 179+ }80 }42- }81 44- expect(Object.keys(chars)).toHaveLength(url.length)82+ expect(Object.keys(chars)).toHaveLength(ALPHABET.length)83 46- let max = 047- let min = Number.MAX_SAFE_INTEGER48- for (let k in chars) {49- let distribution = (chars[k] * url.length) / (COUNT * LENGTH)50- if (distribution > max) max = distribution51- if (distribution < min) min = distribution52- }53- expect(max - min).toBeLessThanOrEqual(0.05)84+ let max = 085+ let min = Number.MAX_SAFE_INTEGER86+ for (let k in chars) {87+ let distribution = (chars[k] * ALPHABET.length) / (COUNT * LENGTH)88+ if (distribution > max) max = distribution89+ if (distribution < min) min = distribution90+ }91+ expect(max - min).toBeLessThanOrEqual(0.05)92+ })93 })deleted:test/random.test.js-46 removed
1-let crypto = require('crypto')2-3-let random = require('../random')4-5-function mock (callback) {6- crypto.randomFillSync = callback7- jest.resetModules()8- random = require('../random')9-}10-11-let originFillSync = crypto.randomFillSync12-afterEach(() => {13- mock(originFillSync)14-})15-16-it('generates small random buffers', () => {17- expect(random(10)).toHaveLength(10)18-})19-20-it('generates random buffers', () => {21- let numbers = { }22- let bytes = random(10000)23- expect(bytes).toHaveLength(10000)24- for (let byte of bytes) {25- if (!numbers[byte]) numbers[byte] = 026- numbers[byte] += 127- expect(typeof byte).toEqual('number')28- expect(byte).toBeLessThanOrEqual(255)29- expect(byte).toBeGreaterThanOrEqual(0)30- }31-})32-33-it('supports old Node.js', () => {34- mock(undefined)35-36- let numbers = { }37- let bytes = random(10000)38- expect(bytes).toHaveLength(10000)39- for (let byte of bytes) {40- if (!numbers[byte]) numbers[byte] = 041- numbers[byte] += 142- expect(typeof byte).toEqual('number')43- expect(byte).toBeLessThanOrEqual(255)44- expect(byte).toBeGreaterThanOrEqual(0)45- }46-})deleted:test/url.test.js-11 removed
1-let url = require('../url')2-3-it('is string', () => {4- expect(typeof url).toEqual('string')5-})6-7-it('has no duplicates', () => {8- for (let i = 0; i < url.length; i++) {9- expect(url.lastIndexOf(url[i])).toEqual(i)10- }11-})deleted:url/index.d.ts-11 removed
1-/**2- * URL safe symbols.3- *4- * ```js5- * import url from 'nanoid/url'6- * generate(url, 10) //=> "Uakgb_J5m9"7- * ```8- */9-declare const url: string10-11-export default urldeleted:url/index.js-16 removed
1-// This alphabet uses a-z A-Z 0-9 _- symbols.2-// Despite the fact the source code is quite long, its entropy3-// is low and there are lots of duplicates - just what compressors4-// like GZIP and Brotli likes the best.5-6-// This alphabet uses a-z A-Z 0-9 _- symbols.7-// Symbols are generated for smaller size.8-// -_zyxwvutsrqponmlkjihgfedcba9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA9-module.exports = '-_'10-let i = 3611-while (i--) {12- // 36 is radix. Number.prototype.toString(36) returns number13- // in Base36 representation. Base36 is like hex, but it uses 0–9 and a-z.14- module.exports += i.toString(36)15- i > 9 && (module.exports += i.toString(36).toUpperCase())16-}modified:.npmignore+1 added-1 removed
8 unmodified lines9 .gitpod.yml10 11 img/12 .cache13-**/types.ts13+**/*.test.jsmodified:index.browser.js+79 added-19 removed
25 unmodified lines26 )27 }28 }29 30+// This alphabet uses a-z A-Z 0-9 _- symbols. Symbols order was changed31+// for better gzip compression. We use genetic algorithm to find the best order.32+let urlAlphabet =33+ 'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'34+30-// This alphabet uses a-z A-Z 0-9 _- symbols.31-// Symbols are generated for smaller size.32-// -_zyxwvutsrqponmlkjihgfedcba9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA33-let url = '-_'34-// Loop from 36 to 0 (from z to a and 9 to 0 in Base36).35-let i = 3636-while (i--) {37- // 36 is radix. Number.prototype.toString(36) returns number38- // in Base36 representation. Base36 is like hex, but it uses 0–9 and a-z.39- url += i.toString(36)35+// // This alphabet uses a-z A-Z 0-9 _- symbols.36+// // Symbols are generated for smaller size.37+// // -_zyxwvutsrqponmlkjihgfedcba9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA38+// let urlAlphabet = '-_'39+// // Loop from 36 to 0 (from z to a and 9 to 0 in Base36).40+// let i = 3641+// while (i--) {42+// // 36 is radix. Number.prototype.toString(36) returns number43+// // in Base36 representation. Base36 is like hex, but it uses 0–9 and a-z.44+// urlAlphabet += i.toString(36)45+// }46+// // Loop from 36 to 10 (from Z to A in Base36).47+// i = 3648+// while (i-- - 10) {49+// urlAlphabet += i.toString(36).toUpperCase()50+// }51+52+let random = bytes => self.crypto.getRandomValues(new Uint8Array(bytes))53+54+let nanoid3 = (getRandom, alphabet, size) => {55+ // We can’t use bytes bigger than the alphabet. To make bytes values closer56+ // to the alphabet, we apply bitmask on them. We look for the closest57+ // `2 ** x - 1` number, which will be bigger than alphabet size. If we have58+ // 30 symbols in the alphabet, we will take 31 (00011111).59+ // We do not use faster Math.clz32, because it is not available in browsers.60+ let mask = (2 << Math.log(alphabet.length - 1) / Math.LN2) - 161+ // Bitmask is not a perfect solution (in our example it will pass 31 bytes,62+ // which is bigger than the alphabet). As a result, we will need more bytes,63+ // than ID size, because we will refuse bytes bigger than the alphabet.64+65+ // Every hardware random generator call is costly,66+ // because we need to wait for entropy collection. This is why often it will67+ // be faster to ask for few extra bytes in advance, to avoid additional calls.68+69+ // Here we calculate how many random bytes should we call in advance.70+ // It depends on ID length, mask / alphabet size and magic number 1.671+ // (which was selected according benchmarks).72+73+ // -~f => Math.ceil(f) if n is float number74+ // -~i => i + 1 if n is integer number75+ let step = -~(1.6 * mask * size / alphabet.length)76+ let id = ''77+78+ while (true) {79+ let bytes = getRandom(step)80+ // Compact alternative for `for (var j = 0; j < step; j++)`81+ let j = step82+ while (j--) {83+ // If random byte is bigger than alphabet even after bitmask,84+ // we refuse it by `|| ''`.85+ id += alphabet[bytes[j] & mask] || ''86+ // More compact than `id.length + 1 === size`87+ if (id.length === +size) return id88+ }89+ }90 }41-// Loop from 36 to 10 (from Z to A in Base36).42-i = 3643-while (i-- - 10) {44- url += i.toString(36).toUpperCase()45-}91 47-module.exports = (size = 21) => {92+let nanoid2 = (alphabet, size) => nanoid3(random, alphabet, size)93+94+let nanoid = (size = 21) => {95 let id = ''96 let bytes = self.crypto.getRandomValues(new Uint8Array(size))50- i = size97 98 // Compact alternative for `for (var i = 0; i < size; i++)`53- while (i--) {99+ while (size--) {100 // We can’t use bytes bigger than the alphabet. 63 is 00111111 bitmask.101 // This mask reduces random byte 0-255 to 0-63 values.102 // There is no need in `|| ''` and `* 1.6` hacks in here,103 // because bitmask trim bytes exact to alphabet size.58- id += url[bytes[i] & 63]104+ let byte = bytes[size] & 63105+ if (byte < 36) {106+ // 0-9a-z107+ id += byte.toString(36)108+ } else if (byte < 62) {109+ // A-Z110+ id += (byte - 26).toString(36).toUpperCase()111+ } else if (byte < 63) {112+ id += '_'113+ } else {114+ id += '-'115+ }116+ // id += urlAlphabet[bytes[i] & 63]117 }118 return id119 }120+121+module.exports = { nanoid, nanoid2, nanoid3, urlAlphabet, random }modified:index.d.ts+73 added-2 removed
3 unmodified lines4 * By default, ID will have 21 symbols to have a collision probability similar5 * to UUID v4.6 *7 * ```js8- * import nanoid from 'nanoid'8+ * import { nanoid } from 'nanoid'9 * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"10 * ```11 *12 * @param size The number of symbols in ID. Default is 21.13 * @returns Random string.14 */15-export default function nanoid (size?: number): string15+export function nanoid (size?: number): string16+17+/**18+ * Generate secure unique ID with custom alphabet.19+ *20+ * Alphabet must contain 256 symbols or less. Otherwise, the generator21+ * will not be secure.22+ *23+ * @param alphabet Symbols to be used in ID.24+ * @param size The number of symbols in ID. Defauls is 21.25+ * @returns Random string.26+ *27+ * ```js28+ * const { nanoid2 } = require('nanoid')29+ * model.id = nanoid2('0123456789абвгдеё', 5) //=> "8ё56а"30+ * ```31+ */32+export function nanoid2 (alphabet: string, size?: number): string33+34+/**35+ * Generate unique ID with custom random generator and alphabet.36+ *37+ * Alphabet must contain 256 symbols or less. Otherwise, the generator38+ * will not be secure.39+ *40+ * ```js41+ * import { nanoid3 } from 'nanoid/format'42+ *43+ * function random (size) {44+ * const result = []45+ * for (let i = 0; i < size; i++) {46+ * result.push(randomByte())47+ * }48+ * return result49+ * }50+ *51+ * nanoid3(random, "abcdef", 5) //=> "fbaef"52+ * ```53+ *54+ * @param random The random bytes generator.55+ * @param alphabet Symbols to be used in new random string.56+ * @param size The number of symbols in new random string.57+ * @returns Random string.58+ */59+export function nanoid3 (60+ random: (bytes: number) => Uint8Array,61+ alphabet: string,62+ size?: number63+): string64+65+/**66+ * URL safe symbols.67+ *68+ * ```js69+ * import { urlAlphabet } from 'nanoid'70+ * generate(url, 10) //=> "Uakgb_J5m9"71+ * ```72+ */73+export const urlAlphabet: string74+75+/**76+ * Return array with random bytes from hardware random generator.77+ *78+ * ```js79+ * import { nanoid3, random } from 'nanoid'80+ * nanoid3(random, "abcdef", 5) //=> "fbaef"81+ * ```82+ *83+ * @param bytes The size of array.84+ * @returns Arrays with random bytes.85+ */86+export function random (bytes: number): Uint8Arraymodified:index.js+58 added-4 removed
1-let random = require('./random')2-let url = require('./url')1+let crypto = require('crypto')2 4-module.exports = (size = 21) => {3+let urlAlphabet =4+ '_-0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'5+6+// We reuse buffers with the same size to avoid memory fragmentations7+// for better performance8+let buffers = { }9+let random = bytes => {10+ let buffer = buffers[bytes]11+ if (!buffer) {12+ // `Buffer.allocUnsafe()` faster because it doesn’t clean memory.13+ // We do not need it, since we will fill memory with new bytes anyway.14+ buffer = Buffer.allocUnsafe(bytes)15+ if (bytes <= 255) buffers[bytes] = buffer16+ }17+ return crypto.randomFillSync(buffer)18+}19+20+let nanoid3 = (getRandom, alphabet, size = 21) => {21+ // We can’t use bytes bigger than the alphabet. To make bytes values closer22+ // to the alphabet, we apply bitmask on them. We look for the closest23+ // `2 ** x - 1` number, which will be bigger than alphabet size. If we have24+ // 30 symbols in the alphabet, we will take 31 (00011111).25+ let mask = (2 << 31 - Math.clz32((alphabet.length - 1) | 1)) - 126+ // Bitmask is not a perfect solution (in our example it will pass 31 bytes,27+ // which is bigger than the alphabet). As a result, we will need more bytes,28+ // than ID size, because we will refuse bytes bigger than the alphabet.29+30+ // Every hardware random generator call is costly,31+ // because we need to wait for entropy collection. This is why often it will32+ // be faster to ask for few extra bytes in advance, to avoid additional calls.33+34+ // Here we calculate how many random bytes should we call in advance.35+ // It depends on ID length, mask / alphabet size and magic number 1.636+ // (which was selected according benchmarks).37+ let step = Math.ceil(1.6 * mask * size / alphabet.length)38+ let id = ''39+40+ while (true) {41+ let bytes = getRandom(step)42+ // Compact alternative for `for (var i = 0; i < step; i++)`43+ let i = step44+ while (i--) {45+ // If random byte is bigger than alphabet even after bitmask,46+ // we refuse it by `|| ''`.47+ id += alphabet[bytes[i] & mask] || ''48+ // More compact than `id.length + 1 === size`49+ if (id.length === +size) return id50+ }51+ }52+}53+54+let nanoid2 = nanoid3.bind(null, random)55+56+let nanoid = (size = 21) => {57 let bytes = random(size)58 let id = ''59 // Compact alternative for `for (var i = 0; i < size; i++)`60 while (size--) {61 // We can’t use bytes bigger than the alphabet. 63 is 00111111 bitmask.62 // This mask reduces random byte 0-255 to 0-63 values.63 // There is no need in `|| ''` and `* 1.6` hacks in here,64 // because bitmask trim bytes exact to alphabet size.13- id += url[bytes[size] & 63]65+ id += urlAlphabet[bytes[size] & 63]66 }67 return id68 }69+70+module.exports = { nanoid, nanoid2, nanoid3, urlAlphabet, random }modified:package.json+26 added-14 removed
1 {2 "name": "nanoid",3 "version": "2.1.11",4- "description": "A tiny (115 bytes), secure URL-friendly unique string ID generator",4+ "description": "A tiny (110 bytes), secure URL-friendly unique string ID generator",5 "keywords": [6 "uuid",7 "random",8 "id",12 unmodified lines21 "browser": {22 "./index.js": "./index.browser.js",23 "./format/index.js": "./format/index.browser.js",24 "./random/index.js": "./random/index.browser.js",25- "./async/index.js": "./async/index.browser.js",25 "./async/format/index.js": "./async/format/index.browser.js",26 "./async/random/index.js": "./async/random/index.browser.js"27 },28 "react-native": {2 unmodified lines31 "sideEffects": false,32 "devDependencies": {33 "@logux/eslint-config": "^36.1.1",34 "@logux/sharec-config": "^0.6.2",35+ "@size-limit/dual-publish": "^4.4.0",36 "@size-limit/preset-small-lib": "^4.4.0",37 "benchmark": "^2.1.4",38 "chalk": "^3.0.0",39 "check-dts": "^0.1.4",40- "clean-publish": "^1.1.6",40+ "dual-publish": "^0.6.1",41 "eslint": "^6.8.0",42 "eslint-ci": "^1.0.0",43 "eslint-config-standard": "^14.1.0",44 "eslint-plugin-es5": "^1.5.0",21 unmodified lines66 "yaspeller-ci": "^1.0.2"67 },68 "size-limit": [69 {70+ "name": "nanoid",71+ "import": "{ nanoid }",70- "limit": "115 B"72+ "limit": "110 B"73 },74 {73- "path": "generate/index.js",74- "limit": "157 B"75+ "name": "nanoid2",76+ "import": "{ nanoid2 }",77+ "limit": "144 B"78 },79 {77- "path": "url/index.js",78- "limit": "50 B"80+ "name": "urlAlphabet",81+ "import": "{ urlAlphabet }",82+ "limit": "59 B"83 },84 {85+ "name": "non-secure nanoid",86+ "import": "{ nanoid }",87 "path": "non-secure/index.js",82- "limit": "90 B"88+ "limit": "85 B"89 },90 {91+ "name": "non-secure nanoid2",92+ "import": "{ nanoid2 }",85- "path": "non-secure/generate/index.js",86- "limit": "47 B"93+ "path": "non-secure/index.js",94+ "limit": "44 B"95 },96 {97+ "name": "async nanoid",98+ "import": "{ nanoid }",99 "path": "async/index.js",90- "limit": "125 B"100+ "limit": "120 B"101 },102 {103+ "name": "async nanoid2",104+ "import": "{ nanoid2 }",93- "path": "async/generate/index.js",94- "limit": "177 B"105+ "path": "async/index.js",106+ "limit": "130 B"107 }108 ],109 "eslintConfig": {110 "extends": "@logux/eslint-config",69 unmodified linesmodified:README.md+33 added-41 removed
3 unmodified lines4 alt="Nano ID logo by Anton Lovchikov" width="180" height="94">5 6 A tiny, secure, URL-friendly, unique string ID generator for JavaScript.7 8-* **Small.** 115 bytes (minified and gzipped). No dependencies.8+* **Small.** 110 bytes (minified and gzipped). No dependencies.9 [Size Limit] controls the size.10 * **Safe.** It uses cryptographically strong random APIs.11 Can be used in clusters.12 * **Fast.** It’s 16% faster than UUID.13 * **Compact.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`).14 So ID size was reduced from 36 to 21 symbols.15 16 ```js17-const nanoid = require('nanoid')17+import { nanoid } from 'nanoid'18 model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"19 ```20 21-Supports [all browsers], Node.js and React Native.21+Supports modern browsers, IE with Babel, Node.js and React Native.22 23 Try to make us smaller in [online tool].24 25-[all browsers]: http://caniuse.com/#feat=getrandomvalues25 [online tool]: https://gitpod.io/#https://github.com/ai/nanoid/26 [Size Limit]: https://github.com/ai/size-limit27 28 <a href="https://evilmartians.com/?utm_source=nanoid">34 unmodified lines63 There are three main differences between Nano ID and UUID v4:64 65 1. Nano ID uses a bigger alphabet, so a similar number of random bits66 are packed in just 21 symbols instead of 36.68-2. Nano ID code is 4 times less than `uuid/v4` package:69- 115 bytes instead of 435.67+2. Nano ID code is 3 times less than `uuid/v4` package:68+ 110 bytes instead of 345.69 3. Because of memory allocation tricks, Nano ID is 16% faster than UUID.70 71 72 ## Benchmark64 unmodified lines137 The main module uses URL-friendly symbols (`A-Za-z0-9_-`) and returns an ID138 with 21 characters (to have a collision probability similar to UUID v4).139 140 ```js142-const nanoid = require('nanoid')141+import { nanoid } from 'nanoid'142 model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"143 ```144 145 If you want to reduce ID length (and increase collisions probability),46 unmodified lines192 2. Import it before Nano ID.193 194 ```js195 import 'react-native-get-random-values'197-import nanoid from 'nanoid'196+import { nanoid } from 'nanoid'197 ```198 199+For `nanoid/async` you need to install [`expo-random`].200+201 [`react-native-get-random-values`]: https://github.com/LinusU/react-native-get-random-values202+[`expo-random`]: https://www.npmjs.com/package/expo-random203 204 205 ### PouchDB and CouchDB206 34 unmodified lines241 you can use non‑secure ID generator. Note, that they have bigger collision242 probability.243 244 ```js243-const nanoid = require('nanoid/non-secure')245+import { nanoid } from 'nanoid/non-secure'246 nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"247 ```248 249 32 unmodified lines282 If we will use asynchronous API for random generator,283 another code could be executed during the entropy collection.284 285 ```js284-const nanoid = require('nanoid/async')286+import { nanoid } from 'nanoid/async'287 288 async function createUser () {289 user.id = await nanoid()290 }9 unmodified lines300 and low collision probability. If you don’t need it, you can use301 very fast non-secure generator.302 303 ```js302-const nonSecure = require('nanoid/non-secure')303-const id = nonSecure() //=> "Uakgb_J5m9g-0JDMbcJqLJ"304+import { nanoid } from 'nanoid/non-secure'305+const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"306 ```307 308 Note that it is predictable and have bigger collision probability.309 310 311 ### Custom Alphabet or Length312 311-If you want to change the ID's alphabet or length312-you can use the low-level `generate` module.313+`nanoid2` allows you to change ID’s alphabet. It has `2` in the name,314+because it accepts 2 arguments (alphabet and optional size) in contrast315+to `nanoid`, which accepts only 1 argument (optional size).316 317 ```js315-const generate = require('nanoid/generate')316-model.id = generate('1234567890abcdef', 10) //=> "4f90d13a42"318+import { nanoid2 } from 'nanoid'319+model.id = nanoid2('1234567890abcdef', 10) //=> "4f90d13a42"320 ```321 322 Check the safety of your custom alphabet and ID length323 in our [ID collision probability] calculator.4 unmodified lines328 329 Asynchronous and non-secure API is also available:330 331 ```js329-const generate = require('nanoid/async/generate')332+import { nanoid2 } from 'nanoid/async'333 async function createUser () {331- user.id = await generate('1234567890abcdef', 10)334+ user.id = await nanoid2('1234567890abcdef', 10)335 }336 ```337 338 ```js336-const generate = require('nanoid/non-secure/generate')337-339+import { nanoid2 } from 'nanoid/non-secure'340 user.id = generate('1234567890abcdef', 10)341 ```342 343 [ID collision probability]: https://alex7kom.github.io/nano-nanoid-cc/1 unmodified line345 346 347 ### Custom Random Bytes Generator348 347-You can replace the default safe random generator using the `format` module.349+You can replace the default safe random generator using the `nanoid3` module.350 For instance, to use a seed-based generator.351 352+This function has `3` in the name, because it accepts 3 arguments353+(generator, alphabet and size).354+355 ```js351-const format = require('nanoid/format')356+import { nanoid3 } from 'nanoid`357 358 function random (size) {359 const result = []360 for (let i = 0; i < size; i++) {1 unmodified line362 }363 return result364 }365 361-format(random, 'abcdef', 10) //=> "fbaefaadeb"366+nanoid3(random, 'abcdef', 10) //=> "fbaefaadeb"367 ```368 369 `random` callback must accept the array size and return an array370 with random numbers.371 367-If you want to use the same URL-friendly symbols with `format`,368-you can get the default alphabet from the `url` file.372+If you want to use the same URL-friendly symbols with `nanoid3`,373+you can get the default alphabet from the `urlAlphabet`.374 375 ```js371-const url = require('nanoid/url')372-format(random, url, 10) //=> "93ce_Ltuub"376+const { nanoid3, urlAlphabet } = require('nanoid')377+nanoid3(random, urlAlphabet, 10) //=> "93ce_Ltuub"378 ```379 375-Asynchronous API is also available:376-377-```js378-const format = require('nanoid/async/format')379-const url = require('nanoid/url')380-381-function random (size) {382- return new Promise(…)383-}384-385-async function createUser () {386- user.id = await format(random, url, 10)387-}388-```380+Asynchronous and non-secure APIs are not available for `nanoid3`.modified:yarn.lock+27 added-9 removed
1056 unmodified lines1057 integrity sha512-Debi3Baff1Qu1Unc3mjJ96MgpbwTn43S1+9yJ0llWygPwDNu2aaWBD6yc9y/Z8XDRNhx7U+u2UDg2OGQXkclUQ==1058 dependencies:1059 type-detect "4.0.8"1060 1061+"@size-limit/dual-publish@^4.4.0":1062+ version "4.4.0"1063+ resolved "https://registry.yarnpkg.com/@size-limit/dual-publish/-/dual-publish-4.4.0.tgz#b57baa3388537b0a6aa268cbbf2b06579d07174f"1064+ integrity sha512-9eyjalC37V48pGgVBwDLd+jknJomgLqHWRpF4LyKShHHR+FjkMSMTRGRHQtoXieftML5Dta/n8h4KS7yjFhzzw==1065+ dependencies:1066+ rimraf "^3.0.2"1067+1068 "@size-limit/file@4.4.0":1069 version "4.4.0"1070 resolved "https://registry.yarnpkg.com/@size-limit/file/-/file-4.4.0.tgz#add2c76cdb817b193c621b471570482bcae5a2a2"1071 integrity sha512-AUL6TZ1qdg2IDvHfaFzU2d6nOpIyEWJFsK7P61DkIq4jO0GfeVgAUgBqEqJbhxT5qqKOs01UWussyVbG+EgmpA==2001 unmodified lines3073 version "5.0.1"3074 resolved "https://registry.yarnpkg.com/dotenv/-/dotenv-5.0.1.tgz#a5317459bd3d79ab88cff6e44057a6a3fbb1fcef"3075 integrity sha512-4As8uPrjfwb7VXC+WnLCbXK7y+Ueb2B3zgNCePYfhxS1PYeaO1YTeplffTEcbfLhvFNGLAz90VvJs9yomG7bow==3076 3077+dual-publish@^0.6.1:3078+ version "0.6.1"3079+ resolved "https://registry.yarnpkg.com/dual-publish/-/dual-publish-0.6.1.tgz#98cef3212f1fd50053d90dc1e2a4b3afc3990588"3080+ integrity sha512-JKyTy2LidGiT6AAySxIsVkZxCODxSC25S21O9Aj3KimLyBBVhci9yizGXU+fU1ypuRWo5aAkwoM3564dvv4B6g==3081+ dependencies:3082+ chalk "^3.0.0"3083+ clean-publish "^1.1.6"3084+ globby "^11.0.0"3085+ line-column "^1.0.2"3086+ rimraf "^3.0.2"3087+3088 duplexer2@~0.1.4:3089 version "0.1.4"3090 resolved "https://registry.yarnpkg.com/duplexer2/-/duplexer2-0.1.4.tgz#8b12dab878c0d69e3e7891051662a32fc6bddcc1"3091 integrity sha1-ixLauHjA1p4+eJEFFmKjL8a93ME=902 unmodified lines3994 resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"3995 integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8=3996 3997 fsevents@^1.2.7:3980- version "1.2.11"3981- resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.11.tgz#67bf57f4758f02ede88fb2a1712fef4d15358be3"3982- integrity sha512-+ux3lx6peh0BpvY0JebGyZoiR4D+oYzdPZMKJwkZ+sFkNJzpL7tXc/wehS49gUAxg3tmMHPHZkA8JU2rhhgDHw==3998+ version "1.2.12"3999+ resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-1.2.12.tgz#db7e0d8ec3b0b45724fd4d83d43554a8f1f0de5c"4000+ integrity sha512-Ggd/Ktt7E7I8pxZRbGIs7vwqAPscSESMrCSkx2FtWeqmheJgCo2R74fTsZFCifr0VTPwqRpPv17+6b8Zp7th0Q==4001 dependencies:4002 bindings "^1.5.0"4003 nan "^2.12.1"4004 2900 unmodified lines6905 css-selector-tokenizer "^0.7.0"6906 postcss "^6.0.1"6907 6908 postcss-modules-scope@^2.1.1:6891- version "2.1.1"6892- resolved "https://registry.yarnpkg.com/postcss-modules-scope/-/postcss-modules-scope-2.1.1.tgz#33d4fc946602eb5e9355c4165d68a10727689dba"6893- integrity sha512-OXRUPecnHCg8b9xWvldG/jUpRIGPNRka0r4D4j0ESUU2/5IOnpsjfPPmDprM3Ih8CgZ8FXjWqaniK5v4rWt3oQ==6909+ version "2.2.0"6910+ resolved "https://registry.yarnpkg.com/postcss-modules-scope/-/postcss-modules-scope-2.2.0.tgz#385cae013cc7743f5a7d7602d1073a89eaae62ee"6911+ integrity sha512-YyEgsTMRpNd+HmyC7H/mh3y+MeFWevy7V1evVhJWewmMbjDHIbZbOXICC2y+m1xI1UVfIT1HMW/O04Hxyu9oXQ==6912 dependencies:6913 postcss "^7.0.6"6914 postcss-selector-parser "^6.0.0"6915 427 unmodified lines7343 iconv-lite "0.4.24"7344 unpipe "1.0.0"7345 7346 react-is@^16.12.0:7329- version "16.13.0"7330- resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.0.tgz#0f37c3613c34fe6b37cd7f763a0d6293ab15c527"7331- integrity sha512-GFMtL0vHkiBv9HluwNZTggSn/sCyEt9n02aM0dSAjGGyqyNlAyftYm4phPxdvCigG15JreC5biwxCgTAJZ7yAA==7347+ version "16.13.1"7348+ resolved "https://registry.yarnpkg.com/react-is/-/react-is-16.13.1.tgz#789729a4dc36de2999dc156dd6c1d9c18cea56a4"7349+ integrity sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==7350 7351 read-pkg-up@^2.0.0:7352 version "2.0.0"7353 resolved "https://registry.yarnpkg.com/read-pkg-up/-/read-pkg-up-2.0.0.tgz#6b72a8048984e0c41e79510fd5e9fa99b3b549be"2034 unmodified lines