Remove async API
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 60e1c23 · Browse files · 10 files·+7 added−588 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+7 added−588 removed
- tests:+1 added−187 removed
- other:+6 added−401 removed
Provenance
- Commit
c0572e2- Tree
beca8d2- Author
Andrey Sitnik <andrey@sitnik.ru>- Committer
Andrey Sitnik <andrey@sitnik.ru>- Parent
60e1c23
10 files changed+7 added−588 removed
deleted:async/index.browser.js-67 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667export let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
export let customAlphabet = (alphabet, defaultSize = 21) => { // First, a bitmask is necessary to generate the ID. The bitmask makes bytes // values closer to the alphabet size. The bitmask calculates the closest // `2^31 - 1` number, which exceeds the alphabet size. // For example, the bitmask for the alphabet size 30 is 31 (00011111). // `Math.clz32` is not used, because it is not available in browsers. let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1 // Though, the bitmask solution is not perfect since the bytes exceeding // the alphabet size are refused. Therefore, to reliably generate the ID, // the random bytes redundancy has to be satisfied.
// Note: every hardware random generator call is performance expensive, // because the system call for entropy collection takes a lot of time. // So, to avoid additional system calls, extra bytes are requested in advance.
// Next, a step determines how many random bytes to generate. // The number of random bytes gets decided upon the ID size, mask, // alphabet size, and magic number 1.6 (using 1.6 peaks at performance // according to benchmarks).
// `-~f => Math.ceil(f)` if f is a float // `-~i => i + 1` if i is an integer let step = -~((1.6 * mask * defaultSize) / alphabet.length)
return async (size = defaultSize) => { let id = '' while (true) { let bytes = crypto.getRandomValues(new Uint8Array(step)) // A compact alternative for `for (var i = 0; i < step; i++)`. let i = step while (i--) { // Adding `|| ''` refuses a random byte that exceeds the alphabet size. id += alphabet[bytes[i] & mask] || '' if (id.length === size) return id } } }}
export let nanoid = async (size = 21) => { let id = '' let bytes = crypto.getRandomValues(new Uint8Array(size))
// A compact alternative for `for (var i = 0; i < step; i++)`. while (size--) { // It is incorrect to use bytes exceeding the alphabet size. // The following mask reduces the random byte in the 0-255 value // range to the 0-63 value range. Therefore, adding hacks, such // as empty string fallback or magic numbers, is unneccessary because // the bitmask trims bytes down to the alphabet size. let byte = bytes[size] & 63 if (byte < 36) { // `0-9a-z` id += byte.toString(36) } else if (byte < 62) { // `A-Z` id += (byte - 26).toString(36).toUpperCase() } else if (byte < 63) { id += '_' } else { id += '-' } } return id}deleted:async/index.d.ts-56 removed
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556/** * Generate secure URL-friendly unique ID. The non-blocking version. * * By default, the ID will have 21 symbols to have a collision probability * similar to UUID v4. * * ```js * import { nanoid } from 'nanoid/async' * nanoid().then(id => { * model.id = id * }) * ``` * * @param size Size of the ID. The default size is 21. * @returns A promise with a random string. */export function nanoid(size?: number): Promise<string>
/** * A low-level function. * Generate secure unique ID with custom alphabet. The non-blocking version. * * Alphabet must contain 256 symbols or less. Otherwise, the generator * will not be secure. * * @param alphabet Alphabet used to generate the ID. * @param defaultSize Size of the ID. The default size is 21. * @returns A function that returns a promise with a random string. * * ```js * import { customAlphabet } from 'nanoid/async' * const nanoid = customAlphabet('0123456789абвгдеё', 5) * nanoid().then(id => { * model.id = id //=> "8ё56а" * }) * ``` */export function customAlphabet( alphabet: string, defaultSize?: number): (size?: number) => Promise<string>
/** * Generate an array of random bytes collected from hardware noise. * * ```js * import { random } from 'nanoid/async' * random(5).then(bytes => { * bytes //=> [10, 67, 212, 67, 89] * }) * ``` * * @param bytes Size of the array. * @returns A promise with a random bytes array. */export function random(bytes: number): Promise<Uint8Array>deleted:async/index.js-73 removed
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273import { randomFill } from 'node:crypto'
import { urlAlphabet } from '../url-alphabet/index.js'
// `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,// because it is possible to use in combination with `Buffer.allocUnsafe()`.export function random(bytes) { return new Promise((resolve, reject) => { // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory. // Memory flushing is unnecessary since the buffer allocation itself resets // the memory with the new bytes. randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { if (err) { /* c8 ignore next */ reject(err) } else { resolve(buf) } }) })}
export function customAlphabet(alphabet, defaultSize = 21) { // First, a bitmask is necessary to generate the ID. The bitmask makes bytes // values closer to the alphabet size. The bitmask calculates the closest // `2^31 - 1` number, which exceeds the alphabet size. // For example, the bitmask for the alphabet size 30 is 31 (00011111). let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1 // Though, the bitmask solution is not perfect since the bytes exceeding // the alphabet size are refused. Therefore, to reliably generate the ID, // the random bytes redundancy has to be satisfied.
// Note: every hardware random generator call is performance expensive, // because the system call for entropy collection takes a lot of time. // So, to avoid additional system calls, extra bytes are requested in advance.
// Next, a step determines how many random bytes to generate. // The number of random bytes gets decided upon the ID size, mask, // alphabet size, and magic number 1.6 (using 1.6 peaks at performance // according to benchmarks). let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
let tick = (id, size = defaultSize) => random(step).then(bytes => { // A compact alternative for `for (var i = 0; i < step; i++)`. let i = step while (i--) { // Adding `|| ''` refuses a random byte that exceeds the alphabet size. id += alphabet[bytes[i] & mask] || '' if (id.length === size) return id } /* c8 ignore next */ return tick(id, size) })
return size => tick('', size)}
export function nanoid(size = 21) { return random(size).then(bytes => { let id = '' // A compact alternative for `for (var i = 0; i < step; i++)`. while (size--) { // It is incorrect to use bytes exceeding the alphabet size. // The following mask reduces the random byte in the 0-255 value // range to the 0-63 value range. Therefore, adding hacks, such // as empty string fallback or magic numbers, is unnecessary because // the bitmask trims bytes down to the alphabet size. id += urlAlphabet[bytes[size] & 63] } return id })}deleted:test/async.test.js-147 removed
1-import { test } from 'uvu'2-import { is, match, ok } from 'uvu/assert'3-4-import * as browser from '../async/index.browser.js'5-import * as node from '../async/index.js'6-import { urlAlphabet } from '../index.js'7-8-test.before(() => {9- Object.defineProperty(global, 'crypto', {10- configurable: true,11- value: {12- getRandomValues(array) {13- for (let i = 0; i < array.length; i++) {14- array[i] = Math.floor(Math.random() * 256)15- }16- return array17- }18- }19- })20-})21-22-test.after(() => {23- Object.defineProperty(global, 'crypto', { value: undefined })24-})25-26-function times(size, callback) {27- let array = []28- for (let i = 0; i < size; i++) {29- array.push(1)30- }31- return array.map(callback)32-}33-34-for (let type of ['node', 'browser']) {35- let { customAlphabet, nanoid, random } = type === 'node' ? node : browser36-37- test(`${type} / nanoid / generates URL-friendly IDs`, async () => {38- await Promise.all(39- times(100, async () => {40- let id = await nanoid()41- is(id.length, 21)42- is(typeof id, 'string')43- for (let char of id) {44- match(urlAlphabet, new RegExp(char, 'g'))45- }46- })47- )48- })49-50- test(`${type} / nanoid / changes ID length`, async () => {51- let id = await nanoid(10)52- is(id.length, 10)53- })54-55- test(`${type} / nanoid / has no collisions`, async () => {56- let ids = await Promise.all(times(50 * 1000, () => nanoid()))57- ids.reduce((used, id) => {58- is(used[id], undefined)59- used[id] = true60- return used61- }, [])62- })63-64- test(`${type} / nanoid / has flat distribution`, async () => {65- let COUNT = 100 * 100066- let LENGTH = (await nanoid()).length67-68- let chars = {}69- await Promise.all(70- times(COUNT, async () => {71- let id = await nanoid()72- for (let char of id) {73- if (!chars[char]) chars[char] = 074- chars[char] += 175- }76- })77- )78- is(Object.keys(chars).length, urlAlphabet.length)79- let max = 080- let min = Number.MAX_SAFE_INTEGER81- for (let k in chars) {82- let distribution = (chars[k] * urlAlphabet.length) / (COUNT * LENGTH)83- if (distribution > max) max = distribution84- if (distribution < min) min = distribution85- }86- ok(max - min <= 0.05)87- })88-89- test(`${type} / random / generates small random buffers`, async () => {90- is((await random(10)).length, 10)91- })92-93- test(`${type} / random / generates random buffers`, async () => {94- let numbers = {}95- let bytes = await random(10000)96- is(bytes.length, 10000)97- for (let byte of bytes) {98- if (!numbers[byte]) numbers[byte] = 099- numbers[byte] += 1100- is(typeof byte, 'number')101- ok(byte <= 255)102- ok(byte >= 0)103- }104- })105-106- test(`${type} / customAlphabet / has options`, async () => {107- let nanoidA = customAlphabet('a', 5)108- let id = await nanoidA()109- is(id, 'aaaaa')110- })111-112- test(`${type} / customAlphabet / has flat distribution`, async () => {113- let COUNT = 50 * 1000114- let LENGTH = 30115- let ALPHABET = 'abcdefghijklmnopqrstuvwxy'116- let nanoid2 = customAlphabet(ALPHABET, LENGTH)117-118- let chars = {}119- await Promise.all(120- times(100, async () => {121- let id = await nanoid2()122- is(id.length, LENGTH)123- for (let char of id) {124- if (!chars[char]) chars[char] = 0125- chars[char] += 1126- }127- })128- )129- is(Object.keys(chars).length, ALPHABET.length)130- let max = 0131- let min = Number.MAX_SAFE_INTEGER132- for (let k in chars) {133- let distribution = (chars[k] * ALPHABET.length) / (COUNT * LENGTH)134- if (distribution > max) max = distribution135- if (distribution < min) min = distribution136- }137- ok(max - min <= 0.05)138- })139-140- test(`${type} / customAlphabet / changes size`, async () => {141- let nanoidA = customAlphabet('a')142- let id = await nanoidA(10)143- is(id, 'aaaaaaaaaa')144- })145-}146-147-test.run()modified:test/benchmark.js+1 added-40 removed
11 unmodified lines1213141516171819161718192021262223242530 unmodified lines565758596566676869707172737475767778798081828384858687888990919293949596606162634 unmodified lines6869707110911011172737475767711 unmodified linesimport uidSafe from 'uid-safe'import { uid as uidSecure } from 'uid/secure'import { v4 as uuid4 } from 'uuid'
import { customAlphabet as aCustomAlphabet, nanoid as aNanoid} from '../async/index.js'import { customAlphabet, nanoid } from '../index.js'import { nanoid as nonSecure } from '../non-secure/index.js'
let suite = new benchmark.Suite()
let nanoid2 = customAlphabet('1234567890abcdef-', 10)let asyncNanoid2 = aCustomAlphabet('1234567890abcdef-', 10)
function formatNumber(number) { return String(number) .replace(/\d{3}$/, ',$&')30 unmodified lines }) .add('shortid', () => { shortid() }) .add('nanoid/async', { defer: true, fn(defer) { aNanoid().then(() => { defer.resolve() }) } }) .add('async customAlphabet', { defer: true, fn(defer) { asyncNanoid2().then(() => { defer.resolve() }) } }) .add('async secure-random-string', { defer: true, fn(defer) { srs(() => { defer.resolve() }) } }) .add('uid-safe', { defer: true, fn(defer) { uidSafe(14).then(() => { defer.resolve() }) } }) .add('uid', () => { uid(32) }) .add('nanoid/non-secure', () => {4 unmodified lines }) .on('cycle', event => { let name = event.target.name.padEnd('async secure-random-string'.length) let hz = formatNumber(event.target.hz.toFixed(0)).padStart(10) if (event.target.name === 'nanoid/async') { name = '\nAsync:\n' + name } else if (event.target.name === 'uid') { if (event.target.name === 'uid') { name = '\nNon-secure:\n' + name } process.stdout.write(`${name}${pico.bold(hz)}${pico.dim(' ops/sec')}\n`) }) .run()modified:package.json+1 added-25 removed
33 unmodified lines34 ".": {35 "browser": "./index.browser.js",36 "default": "./index.js"37 },38- "./async": {39- "browser": "./async/index.browser.js",40- "default": "./async/index.js"41- },38 "./non-secure": "./non-secure/index.js",39 "./package.json": "./package.json"40 },41 "browser": {46- "./index.js": "./index.browser.js",47- "./async/index.js": "./async/index.browser.js"42+ "./index.js": "./index.browser.js"43 },44 "bin": "./bin/nanoid.js",45 "sideEffects": false,46 "types": "./index.d.ts",57 unmodified lines104 "path": "non-secure/index.js",105 "limit": "69 B"106 },107 {113- "name": "async nanoid",114- "import": "{ nanoid }",115- "path": "async/index.js",116- "limit": "136 B"117- },118- {119- "name": "async customAlphabet",120- "import": "{ customAlphabet }",121- "path": "async/index.js",122- "limit": "157 B"123- },124- {108 "name": "Brotli all",109 "brotli": true,110 "import": "{ nanoid, customAlphabet, urlAlphabet }",111 "limit": "260 B"3 unmodified lines115 "brotli": true,116 "import": "{ nanoid, customAlphabet }",117 "path": "non-secure/index.js",118 "limit": "116 B"136- },137- {138- "name": "Brotli async",139- "brotli": true,140- "import": "{ nanoid, customAlphabet }",141- "path": "async/index.js",142- "limit": "211 B"119 }120 ],121 "eslintConfig": {122 "extends": "@logux/eslint-config",32 unmodified linesmodified:README.id-ID.md+2 added-38 removed
35 unmodified lines36 - [Keamanan](#keamanan)37 - [Instalasi](#instalasi)38 - [API](#api)39 - [Blocking](#blocking)40- - [Async](#async)40 - [Non-Secure](#non-secure)41 - [Alfabet dan Ukuran (Custom)](#alfabet-dan-ukuran-penyesuaian)42 - [Generasi Random Bytes (Custom)](#generasi-random-bytes-custom)43 - [Penggunaan](#penggunaan)32 unmodified lines76 secure-random-string 394,201 ops/sec77 uid-safe.sync 393,176 ops/sec78 shortid 49,916 ops/sec79 81-Async:82-nanoid/async 135,260 ops/sec83-async customAlphabet 136,059 ops/sec84-async secure-random-string 135,213 ops/sec85-uid-safe 119,587 ops/sec86-80 Non-secure:81 uid 58,860,241 ops/sec82 nanoid/non-secure 2,744,615 ops/sec83 rndm 2,718,063 ops/sec39 unmodified lines123 124 125 ## API126 134-Nano ID memiliki tiga buah API: normal (_blocking_), asinkronus (_asynchronous_), dan _non-secure_.127+Nano ID memiliki dua API: normal dan _non-secure_.128 129 Bawaannya, Nano ID menggunakan simbol yang _URL-friendly_ (`A-Za-z0-9_-`) dan mengembalikan ID dengan 21 karakter (untuk memiliki probabilitas collision / tabrakan yang mirip dengan UUID v4).130 131 18 unmodified lines150 151 Dapat digunakan pula [custom alphabet](#custom-alphabet-or-size) atau [random generator](#custom-random-bytes-generator) yang lain.152 153 161-### Async162-163-Untuk menghasilkan bytes yang acak dan aman secara kriptografis, CPU mengumpulkan noise elektromagnetik. Umumnya, entropi sudah dikumpulkan terlebih dahulu.164-165-Dalam API sinkronus, pada saat CPU mengumpulkan noise elektromagnetik, CPU berada dalam situasi 'busy' dan tidak dapat melakukan proses yang lain (contohnya yakni memorses permintaan HTTP).166-167-Ketika menggunakan API asinkronus dari Nano ID, proses lain dapat berjalan ketika CPU sedang mengumpulkan noise elektromagnetik.168-169-```js170-import { nanoid } from 'nanoid/async'171-172-async function createUser() {173- user.id = await nanoid()174-}175-```176-177-Referensi lebih lanjut tentang entropi dapat dilihat pada dokumentasi fungsi [`crypto.randomBytes`](https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback) milik Node.js.178-179-Sayangnya, keuntungan Web Crypto API akan hilang di browser apabila menggunakan API asinkronus ini. Untuk sekarang, browser dibatasi hanya menggunakan API sinkronus (untuk keamanan) atau API asinkronus (lebih cepat, tetapi karena keuntungan Web Crypto hilang, keamanannya sedikit lebih rendah ketimbang penggunaan API sinkronus).180-181-154 ### Non-Secure155 156 Konfigurasi bawaan Nano ID menggunakan random bytes generator yang berasal dari perangkat keras untuk keamanan dan probabilitas collision yang rendah. Apabila tidak terlalu memikirkan soal keamanan, dapat pula menggunakan non-secure generator yang lebih cepat.157 16 unmodified lines174 Ketika menggunakan fungsi ini, jangan lupa untuk memeriksa keamanan alfabet dan ukuran ID dalam [ID collision probability calculator](https://alex7kom.github.io/nano-nanoid-cc/). Untuk lebih banyak alfabet, dapat menggunakan [`nanoid-dictionary`](https://github.com/CyberAP/nanoid-dictionary).175 176 Alfabet harus terbentuk dari 256 simbol atau lebih kecil. Selain itu, keamanan algoritma generasi yang berada di dalam library ini tidak dijamin aman.177 206-API asinkronus dan non-secure yang dapat dikustomisasi dengan `customAlphabet` pun tersedia disini:178+API non-secure yang dapat dikustomisasi dengan `customAlphabet` pun tersedia disini:179 180 ```js209-import { customAlphabet } from 'nanoid/async'210-const nanoid = customAlphabet('1234567890abcdef', 10)211-async function createUser() {212- user.id = await nanoid()213-}214-```215-216-```js181 import { customAlphabet } from 'nanoid/non-secure'182 const nanoid = customAlphabet('1234567890abcdef', 10)183 user.id = nanoid()184 ```160 unmodified linesmodified:README.md+1 added-46 removed
40 unmodified lines41 * [Security](#security)42 * [Install](#install)43 * [API](#api)44 * [Blocking](#blocking)45- * [Async](#async)45 * [Non-Secure](#non-secure)46 * [Custom Alphabet or Size](#custom-alphabet-or-size)47 * [Custom Random Bytes Generator](#custom-random-bytes-generator)48 * [Usage](#usage)38 unmodified lines87 secure-random-string 394,201 ops/sec88 uid-safe.sync 393,176 ops/sec89 shortid 49,916 ops/sec90 92-Async:93-nanoid/async 135,260 ops/sec94-async customAlphabet 136,059 ops/sec95-async secure-random-string 135,213 ops/sec96-uid-safe 119,587 ops/sec97-91 Non-secure:92 uid 58,860,241 ops/sec93 nanoid/non-secure 2,744,615 ops/sec94 rndm 2,718,063 ops/sec52 unmodified lines147 148 149 ## API150 158-Nano ID has 3 APIs: normal (blocking), asynchronous, and non-secure.151+Nano ID has 2 APIs: normal and non-secure.152 153 By default, Nano ID uses URL-friendly symbols (`A-Za-z0-9_-`) and returns an ID154 with 21 characters (to have a collision probability similar to UUID v4).155 25 unmodified lines181 182 [ID collision probability]: https://zelark.github.io/nano-id-cc/183 184 192-### Async193-194-To generate hardware random bytes, CPU collects electromagnetic noise.195-For most cases, entropy will be already collected.196-197-In the synchronous API during the noise collection, the CPU is busy and198-cannot do anything useful (for instance, process another HTTP request).199-200-Using the asynchronous API of Nano ID, another code can run during201-the entropy collection.202-203-```js204-import { nanoid } from 'nanoid/async'205-206-async function createUser() {207- user.id = await nanoid()208-}209-```210-211-Read more about entropy collection in [`crypto.randomBytes`] docs.212-213-Unfortunately, you will lose performance advantages in a browser214-if you use the asynchronous API, because Web Crypto API supports only215-synchronous mode.216-217-[`crypto.randomBytes`]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback218-219-185 ### Non-Secure186 187 By default, Nano ID uses hardware random bytes generation for security188 and low collision probability. If you are not so concerned with security,16 unmodified lines205 model.id = nanoid() //=> "4f90d13a42"206 ```207 208 ```js244-import { customAlphabet } from 'nanoid/async'245-const nanoid = customAlphabet('1234567890abcdef', 10)246-async function createUser() {247- user.id = await nanoid()248-}249-```250-251-```js209 import { customAlphabet } from 'nanoid/non-secure'210 const nanoid = customAlphabet('1234567890abcdef', 10)211 user.id = nanoid()212 ```46 unmodified lines259 const { customRandom, urlAlphabet } = require('nanoid')260 const nanoid = customRandom(urlAlphabet, 10, random)261 ```262 306-Asynchronous and non-secure APIs are not available for `customRandom`.307-263 Note, that between Nano ID versions we may change random generator264 call sequence. If you are using seed-based generators, we do not guarantee265 the same result.266 177 unmodified linesmodified:README.ru.md+1 added-51 removed
43 unmodified lines44 - [Безопасность](#безопасность)45 - [Подключение](#подключение)46 - [API](#api)47 - [Блокирующий](#блокирующий)48- - [Асинхронный](#асинхронный)48 - [Небезопасный](#небезопасный)49 - [Смена алфавита или длины](#смена-алфавита-или-длины)50 - [Смена генератора случайных чисел](#смена-генератора-случайных-чисел)51 - [Руководство](#руководство)39 unmodified lines91 secure-random-string 394,201 ops/sec92 uid-safe.sync 393,176 ops/sec93 shortid 49,916 ops/sec94 96-Async:97-nanoid/async 135,260 ops/sec98-async customAlphabet 136,059 ops/sec99-async secure-random-string 135,213 ops/sec100-uid-safe 119,587 ops/sec101-95 Non-secure:96 uid 58,860,241 ops/sec97 nanoid/non-secure 2,744,615 ops/sec98 rndm 2,718,063 ops/sec55 unmodified lines154 155 156 ## API157 165-Nano ID разделён на три модуля:166-стандартный (блокирующий), асинхронный и небезопасный.158+Nano ID разделён на два модуля: стандартный и небезопасный.159 160 По умолчанию используются символы, безопасные для URL (`A-Za-z0-9_-`).161 Длина ID по умолчанию — 21 символ162 (чтобы вероятность коллизий была соизмеримой с UUID v4).20 unmodified lines183 При изменении размера, всегда проверяйте риски184 в нашем [калькуляторе коллизий](https://zelark.github.io/nano-id-cc/).185 186 195-### Асинхронный196-197-Для аппаратной генерации случайных чисел процессор накапливает198-электромагнитные шумы. Обычно они накоплены заранее, и получение199-случайных чисел происходит быстро. Но могут быть ситуации, когда200-системе требуется время на накопление энтропии.201-202-При использовании синхронного API процесс заблокируется203-во время накопления энтропии. Например, веб-сервер не сможет204-обрабатывать запрос следующего посетителя, пока не сгенерирует205-ID для предыдущего.206-207-Но если использовать асинхронный API у Nano ID, то процесс будет работать208-более эффективно: во время накопления шума сможет выполняться другая задача.209-210-```js211-import { nanoid } from 'nanoid/async'212-213-async function createUser() {214- user.id = await nanoid()215-}216-```217-218-Про ожидание накопления энтропии можно почитать в описании метода219-`crypto.randomBytes` в [документации Node.js].220-221-К сожалению, эта оптимизация имеет смысл только для Node.js. Web Crypto API222-в браузерах не имеет асинхронной версии.223-224-[документации node.js]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback225-226-187 ### Небезопасный188 189 По умолчанию, Nano ID использует аппаратный генератор случайных чисел для190 получения непредсказуемых ID и минимизации риска возникновения коллизий20 unmodified lines211 user.id = nanoid() //=> "4f90d13a42"212 ```213 214 ```js255-import { customAlphabet } from 'nanoid/async'256-const nanoid = customAlphabet('1234567890abcdef', 10)257-async function createUser() {258- user.id = await nanoid()259-}260-```261-262-```js215 import { customAlphabet } from 'nanoid/non-secure'216 const nanoid = customAlphabet('1234567890abcdef', 10)217 user.id = nanoid()218 ```47 unmodified lines266 const { customRandom, urlAlphabet } = require('nanoid')267 const nanoid = customRandom(urlAlphabet, 10, random)268 ```269 318-У асинхронной и небезопасной версий нет `customRandom`.270 320-271 ## Руководство272 273 ### React274 147 unmodified linesmodified:README.zh-CN.md+1 added-45 removed
36 unmodified lines37 * [安全性](#安全性)38 * [安装](#安装)39 * [API](#api)40 * [阻塞](#阻塞)41- * [异步](#异步)41 * [不安全](#不安全)42 * [自定义字母或大小](#自定义字母或大小)43 * [自定义随机字节生成器](#自定义随机字节生成器)44 * [用法](#用法)37 unmodified lines82 secure-random-string 394,201 ops/sec83 uid-safe.sync 393,176 ops/sec84 shortid 49,916 ops/sec85 87-Async:88-nanoid/async 135,260 ops/sec89-async customAlphabet 136,059 ops/sec90-async secure-random-string 135,213 ops/sec91-uid-safe 119,587 ops/sec92-86 Non-secure:87 uid 58,860,241 ops/sec88 nanoid/non-secure 2,744,615 ops/sec89 rndm 2,718,063 ops/sec50 unmodified lines140 141 142 ## API143 151-Nano ID 有3个 API:正常(阻塞),异步,和不安全。144+Nano ID 有2个 API:正常(阻塞),和不安全。145 146 默认情况下,Nano ID 使用 URL 友好的符号(`A-Za-z0-9_-`)并返回一个147 有21个字符(类似 UUID v4 的碰撞概率)的 ID。148 23 unmodified lines172 173 [ID 碰撞概率]: https://alex7kom.github.io/nano-nanoid-cc/174 175 183-### 异步184-185-为了生成硬件随机字节,CPU 会收集电磁噪声。186-在大多数情况下,熵已经被收集。187-188-在同步API的噪声收集期间,CPU将忙于工作,无法执行其他有用的任务(例如,处理另一个HTTP请求)。189-190-使用Nano ID的异步API,可以在熵收集期间191-运行另一个代码。192-193-```js194-import { nanoid } from 'nanoid/async'195-196-async function createUser() {197- user.id = await nanoid()198-}199-```200-201-请阅读 [`crypto.randomBytes`] 文档了解更多关于熵收集的信息。202-203-不幸的是,您将在浏览器中失去 Web Crypto API 的优势204-如果您使用异步 API。那么,目前在浏览器中,205-您将受到安全性或异步行为的限制。206-207-[`crypto.randomBytes`]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback208-209-176 ### 不安全177 178 默认情况下,Nano ID 使用硬件随机字节生成以提供安全性和较低的碰撞概率。如果您对安全性不太担心,您可以在没有硬件随机生成器的环境中使用它179 13 unmodified lines193 model.id = nanoid() //=> "4f90d13a42"194 ```195 196 ```js231-import { customAlphabet } from 'nanoid/async'232-const nanoid = customAlphabet('1234567890abcdef', 10)233-async function createUser() {234- user.id = await nanoid()235-}236-```237-238-```js197 import { customAlphabet } from 'nanoid/non-secure'198 const nanoid = customAlphabet('1234567890abcdef', 10)199 user.id = nanoid()200 ```43 unmodified lines244 const { customRandom, urlAlphabet } = require('nanoid')245 const nanoid = customRandom(urlAlphabet, 10, random)246 ```247 290-异步和非安全的API在 `customRandom` 中不可用。291-248 请注意,在Nano ID的不同版本之间,我们可能会更改随机生成器的调用顺序。如果您正在使用基于种子的生成器,我们不能保证相同的结果。249 250 251 ## 用法169 unmodified lines