Move files to subdirs
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 a58703b · Browse files · 28 files·+394 added−395 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
28 files+394 added−395 removed
- tests:+4 added−4 removed
- other:+390 added−391 removed
Provenance
- Commit
a069b8f- Tree
2d4a699- Author
Andrey Sitnik <andrey@sitnik.ru>- Committer
Andrey Sitnik <andrey@sitnik.ru>- Parent
a58703b
28 files changed+394 added−395 removed
added:async/format/index.browser.js+41 added
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('')}added:async/format/index.js+70 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970/** * Secure random string generator with custom alphabet. * * Alphabet must contain 256 symbols or less. Otherwise, the generator * will not be secure. * * @param {asyncGenerator} random The random bytes generator. * @param {string} alphabet Symbols to be used in new random string. * @param {size} size The number of symbols in new random string. * * @return {Promise} Promise with random string. * * @example * const formatAsync = require('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" * }) * * @name formatAsync * @function */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). 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. */added:async/generate/index.js+24 added
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)added:async/random/index.browser.js+6 added
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)))added:async/random/index.js+27 added
123456789101112131415161718192021222324252627let 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) } }) })} else { module.exports = bytes => new Promise((resolve, reject) => { crypto.randomBytes(bytes, (err, buf) => { if (err) { reject(err) } else { resolve(buf) } }) })}added:async/random/index.rn.js+12 added
123456789101112let randomtry { random = require('expo-random')} catch (e) { throw new Error( 'React-Native does not have a built-in secure random generator. ' + 'Install `expo-random` locally or ' + 'if you don’t need unpredictable IDs, you can use `nanoid/non-secure`.' )}
module.exports = bytes => random.getRandomBytesAsync(bytes)deleted:async/format.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.js-70 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970/** * Secure random string generator with custom alphabet. * * Alphabet must contain 256 symbols or less. Otherwise, the generator * will not be secure. * * @param {asyncGenerator} random The random bytes generator. * @param {string} alphabet Symbols to be used in new random string. * @param {size} size The number of symbols in new random string. * * @return {Promise} Promise with random string. * * @example * const formatAsync = require('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" * }) * * @name formatAsync * @function */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). 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.js-24 removed
1-let random = require('./random')2-let format = require('./format')3-4-/**5- * Low-level function to change alphabet and ID size.6- *7- * Alphabet must contain 256 symbols or less. Otherwise, the generator8- * will not be secure.9- *10- * @param {string} alphabet Symbols to be used in ID.11- * @param {number} size The number of symbols in ID.12- *13- * @return {Promise} Promise with random string.14- *15- * @example16- * const generateAsync = require('nanoid/async/generate')17- * generateAsync('0123456789абвгдеё', 5).then(id => {18- * model.id = id //=> "8ё56а"19- * })20- *21- * @name generateAsync22- * @function23- */24-module.exports = format.bind(null, random)deleted:async/random.browser.js-6 removed
1-// This file replaces `async/random.js` in bundlers like webpack or Rollup,2-// according to `browser` config in `package.json`.3-4-module.exports = bytes => Promise.resolve(5- self.crypto.getRandomValues(new Uint8Array(bytes))6-)deleted:async/random.js-27 removed
1-let crypto = require('crypto')2-3-if (crypto.randomFill) {4- // `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,5- // because we can use faster `Buffer.allocUnsafe()`.6- module.exports = bytes => new Promise((resolve, reject) => {7- // `Buffer.allocUnsafe()` faster because it doesn’t clean memory.8- // We do not need it, since we will fill memory with new bytes anyway.9- crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {10- if (err) {11- reject(err)12- } else {13- resolve(buf)14- }15- })16- })17-} else {18- module.exports = bytes => new Promise((resolve, reject) => {19- crypto.randomBytes(bytes, (err, buf) => {20- if (err) {21- reject(err)22- } else {23- resolve(buf)24- }25- })26- })27-}deleted:async/random.rn.js-12 removed
1-let random2-try {3- random = 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-}11-12-module.exports = bytes => random.getRandomBytesAsync(bytes)added:format/index.browser.js+40 added
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+}added:format/index.js+67 added
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+ * @param {generator} random The random bytes generator.8+ * @param {string} alphabet Symbols to be used in new random string.9+ * @param {size} size The number of symbols in new random string.10+ *11+ * @return {string} Random string.12+ *13+ * @example14+ * const format = require('nanoid/format')15+ *16+ * function random (size) {17+ * const result = []18+ * for (let i = 0; i < size; i++) {19+ * result.push(randomByte())20+ * }21+ * return result22+ * }23+ *24+ * format(random, "abcdef", 5) //=> "fbaef"25+ *26+ * @name format27+ * @function28+ */29+module.exports = (random, alphabet, size) => {30+ // We can’t use bytes bigger than the alphabet. To make bytes values closer31+ // to the alphabet, we apply bitmask on them. We look for the closest32+ // `2 ** x - 1` number, which will be bigger than alphabet size. If we have33+ // 30 symbols in the alphabet, we will take 31 (00011111).34+ let mask = (2 << 31 - Math.clz32((alphabet.length - 1) | 1)) - 135+ // Bitmask is not a perfect solution (in our example it will pass 31 bytes,36+ // which is bigger than the alphabet). As a result, we will need more bytes,37+ // than ID size, because we will refuse bytes bigger than the alphabet.38+39+ // Every hardware random generator call is costly,40+ // because we need to wait for entropy collection. This is why often it will41+ // be faster to ask for few extra bytes in advance, to avoid additional calls.42+43+ // Here we calculate how many random bytes should we call in advance.44+ // It depends on ID length, mask / alphabet size and magic number 1.645+ // (which was selected according benchmarks).46+ let step = Math.ceil(1.6 * mask * size / alphabet.length)47+ let id = ''48+49+ while (true) {50+ let bytes = random(step)51+ // Compact alternative for `for (var i = 0; i < step; i++)`52+ let i = step53+ while (i--) {54+ // If random byte is bigger than alphabet even after bitmask,55+ // we refuse it by `|| ''`.56+ id += alphabet[bytes[i] & mask] || ''57+ // More compact than `id.length + 1 === size`58+ if (id.length === +size) return id59+ }60+ }61+}62+63+/**64+ * @callback generator65+ * @param {number} bytes The number of bytes to generate.66+ * @return {number[]} Random bytes.67+ */added:generate/index.js+22 added
1+let random = require('../random')2+let format = require('../format')3+4+/**5+ * Low-level function to change alphabet and ID size.6+ *7+ * Alphabet must contain 256 symbols or less. Otherwise, the generator8+ * will not be secure.9+ *10+ * @param {string} alphabet Symbols to be used in ID.11+ * @param {number} size The number of symbols in ID.12+ *13+ * @return {string} Unique ID.14+ *15+ * @example16+ * const generate = require('nanoid/generate')17+ * model.id = generate('0123456789абвгдеё', 5) //=> "8ё56а"18+ *19+ * @name generate20+ * @function21+ */22+module.exports = format.bind(null, random)added:non-secure/generate/index.js+25 added
1+/**2+ * Generate URL-friendly unique ID. This method use non-secure predictable3+ * random generator with bigger collision probability.4+ *5+ * @param {string} alphabet Symbols to be used in ID.6+ * @param {number} [size=21] The number of symbols in ID.7+ *8+ * @return {string} Random string.9+ *10+ * @example11+ * const nanoid = require('nanoid/non-secure')12+ * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"13+ *14+ * @name nonSecure15+ * @function16+ */17+module.exports = (alphabet, size = 21) => {18+ let id = ''19+ // Complete alternative for `for (var i = 0; i < size; i++)`20+ while (size--) {21+ // `| 0` is compact and faster alternative for `Math.floor()`22+ id += alphabet[Math.random() * alphabet.length | 0]23+ }24+ return id25+}deleted:non-secure/generate.js-25 removed
1-/**2- * Generate URL-friendly unique ID. This method use non-secure predictable3- * random generator with bigger collision probability.4- *5- * @param {string} alphabet Symbols to be used in ID.6- * @param {number} [size=21] The number of symbols in ID.7- *8- * @return {string} Random string.9- *10- * @example11- * const nanoid = require('nanoid/non-secure')12- * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL"13- *14- * @name nonSecure15- * @function16- */17-module.exports = (alphabet, size = 21) => {18- let id = ''19- // Complete alternative for `for (var i = 0; i < size; i++)`20- while (size--) {21- // `| 0` is compact and faster alternative for `Math.floor()`22- id += alphabet[Math.random() * alphabet.length | 0]23- }24- return id25-}added:random/index.browser.js+1 added
1+module.exports = bytes => self.crypto.getRandomValues(new Uint8Array(bytes))added:random/index.js+19 added
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/browser.test.js+4 added-4 removed
8 unmodified lines9 }10 }11 12 let nanoid = require('../index.browser')13-let format = require('../format.browser')14-let random = require('../random.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.browser')17-let asyncRandom = require('../async/random.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 = []72 unmodified linesadded:url/index.js+27 added
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+/**7+ * URL safe symbols.8+ *9+ * @name url10+ * @type {string}11+ *12+ * @example13+ * const url = require('nanoid/url')14+ * generate(url, 10) //=> "Uakgb_J5m9"15+ */16+17+// This alphabet uses a-z A-Z 0-9 _- symbols.18+// Symbols are generated for smaller size.19+// -_zyxwvutsrqponmlkjihgfedcba9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA20+module.exports = '-_'21+let i = 3622+while (i--) {23+ // 36 is radix. Number.prototype.toString(36) returns number24+ // in Base36 representation. Base36 is like hex, but it uses 0–9 and a-z.25+ module.exports += i.toString(36)26+ i > 9 && (module.exports += i.toString(36).toUpperCase())27+}deleted:format.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.js-67 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- * @param {generator} random The random bytes generator.8- * @param {string} alphabet Symbols to be used in new random string.9- * @param {size} size The number of symbols in new random string.10- *11- * @return {string} Random string.12- *13- * @example14- * const format = require('nanoid/format')15- *16- * function random (size) {17- * const result = []18- * for (let i = 0; i < size; i++) {19- * result.push(randomByte())20- * }21- * return result22- * }23- *24- * format(random, "abcdef", 5) //=> "fbaef"25- *26- * @name format27- * @function28- */29-module.exports = (random, alphabet, size) => {30- // We can’t use bytes bigger than the alphabet. To make bytes values closer31- // to the alphabet, we apply bitmask on them. We look for the closest32- // `2 ** x - 1` number, which will be bigger than alphabet size. If we have33- // 30 symbols in the alphabet, we will take 31 (00011111).34- let mask = (2 << 31 - Math.clz32((alphabet.length - 1) | 1)) - 135- // Bitmask is not a perfect solution (in our example it will pass 31 bytes,36- // which is bigger than the alphabet). As a result, we will need more bytes,37- // than ID size, because we will refuse bytes bigger than the alphabet.38-39- // Every hardware random generator call is costly,40- // because we need to wait for entropy collection. This is why often it will41- // be faster to ask for few extra bytes in advance, to avoid additional calls.42-43- // Here we calculate how many random bytes should we call in advance.44- // It depends on ID length, mask / alphabet size and magic number 1.645- // (which was selected according benchmarks).46- let step = Math.ceil(1.6 * mask * size / alphabet.length)47- let id = ''48-49- while (true) {50- let bytes = random(step)51- // Compact alternative for `for (var i = 0; i < step; i++)`52- let i = step53- while (i--) {54- // If random byte is bigger than alphabet even after bitmask,55- // we refuse it by `|| ''`.56- id += alphabet[bytes[i] & mask] || ''57- // More compact than `id.length + 1 === size`58- if (id.length === +size) return id59- }60- }61-}62-63-/**64- * @callback generator65- * @param {number} bytes The number of bytes to generate.66- * @return {number[]} Random bytes.67- */deleted:generate.js-22 removed
1-let random = require('./random')2-let format = require('./format')3-4-/**5- * Low-level function to change alphabet and ID size.6- *7- * Alphabet must contain 256 symbols or less. Otherwise, the generator8- * will not be secure.9- *10- * @param {string} alphabet Symbols to be used in ID.11- * @param {number} size The number of symbols in ID.12- *13- * @return {string} Unique ID.14- *15- * @example16- * const generate = require('nanoid/generate')17- * model.id = generate('0123456789абвгдеё', 5) //=> "8ё56а"18- *19- * @name generate20- * @function21- */22-module.exports = format.bind(null, random)modified:package.json+9 added-10 removed
18 unmodified lines19 "license": "MIT",20 "repository": "ai/nanoid",21 "browser": {22 "./index.js": "./index.browser.js",23- "./format.js": "./format.browser.js",24- "./random.js": "./random.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",26- "./async/format.js": "./async/format.browser.js",27- "./async/random.js": "./async/random.browser.js"26+ "./async/format/index.js": "./async/format/index.browser.js",27+ "./async/random/index.js": "./async/random/index.browser.js"28 },29 "react-native": {30- "./async/random.js": "./async/random.rn.js"30+ "./async/random/index.js": "./async/random/index.rn.js"31 },32 "sideEffects": false,33 "devDependencies": {34 "@logux/eslint-config": "^36.1.1",30 unmodified lines65 "yaspeller-ci": "^1.0.2"66 },67 "size-limit": [68 {69- "path": "index.js",69 "limit": "115 B"70 },71 {73- "path": "generate.js",72+ "path": "generate/index.js",73 "limit": "157 B"74 },75 {77- "path": "url.js",76+ "path": "url/index.js",77 "limit": "50 B"78 },79 {80 "path": "non-secure/index.js",81 "limit": "90 B"82 },83 {85- "path": "non-secure/generate.js",84+ "path": "non-secure/generate/index.js",85 "limit": "47 B"86 },87 {88 "path": "async/index.js",89 "limit": "125 B"90 },91 {93- "path": "async/generate.js",92+ "path": "async/generate/index.js",93 "limit": "177 B"94 }95 ],96 "eslintConfig": {70 unmodified linesdeleted:random.browser.js-1 removed
1-module.exports = bytes => self.crypto.getRandomValues(new Uint8Array(bytes))deleted:random.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-}deleted:url.js-27 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-/**7- * URL safe symbols.8- *9- * @name url10- * @type {string}11- *12- * @example13- * const url = require('nanoid/url')14- * generate(url, 10) //=> "Uakgb_J5m9"15- */16-17-// This alphabet uses a-z A-Z 0-9 _- symbols.18-// Symbols are generated for smaller size.19-// -_zyxwvutsrqponmlkjihgfedcba9876543210ZYXWVUTSRQPONMLKJIHGFEDCBA20-module.exports = '-_'21-let i = 3622-while (i--) {23- // 36 is radix. Number.prototype.toString(36) returns number24- // in Base36 representation. Base36 is like hex, but it uses 0–9 and a-z.25- module.exports += i.toString(36)26- i > 9 && (module.exports += i.toString(36).toUpperCase())27-}