Skip to content
Myr

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

10 files+7 added−588 removed

deleted:async/index.browser.js-67 removed
deleted:async/index.d.ts-56 removed
deleted:async/index.js-73 removed
deleted:test/async.test.js-147 removed
1import { test } from 'uvu'2import { is, match, ok } from 'uvu/assert'34import * as browser from '../async/index.browser.js'5import * as node from '../async/index.js'6import { urlAlphabet } from '../index.js'78test.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})2122test.after(() => {23 Object.defineProperty(global, 'crypto', { value: undefined })24})2526function 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}3334for (let type of ['node', 'browser']) {35 let { customAlphabet, nanoid, random } = type === 'node' ? node : browser3637 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 })4950 test(`${type} / nanoid / changes ID length`, async () => {51 let id = await nanoid(10)52 is(id.length, 10)53 })5455 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 })6364 test(`${type} / nanoid / has flat distribution`, async () => {65 let COUNT = 100 * 100066 let LENGTH = (await nanoid()).length6768 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 })8889 test(`${type} / random / generates small random buffers`, async () => {90 is((await random(10)).length, 10)91 })9293 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 })105106 test(`${type} / customAlphabet / has options`, async () => {107 let nanoidA = customAlphabet('a', 5)108 let id = await nanoidA()109 is(id, 'aaaaa')110 })111112 test(`${type} / customAlphabet / has flat distribution`, async () => {113 let COUNT = 50 * 1000114 let LENGTH = 30115 let ALPHABET = 'abcdefghijklmnopqrstuvwxy'116 let nanoid2 = customAlphabet(ALPHABET, LENGTH)117118 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 })139140 test(`${type} / customAlphabet / changes size`, async () => {141 let nanoidA = customAlphabet('a')142 let id = await nanoidA(10)143 is(id, 'aaaaaaaaaa')144 })145}146147test.run()
modified:test/benchmark.js+1 added-40 removed
modified:package.json+1 added-25 removed
33 unmodified lines
34 ".": {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 lines
104 "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 lines
115 "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 lines
modified:README.id-ID.md+2 added-38 removed
35 unmodified lines
36- [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 lines
76secure-random-string 394,201 ops/sec77uid-safe.sync 393,176 ops/sec78shortid 49,916 ops/sec7981Async:82nanoid/async 135,260 ops/sec83async customAlphabet 136,059 ops/sec84async secure-random-string 135,213 ops/sec85uid-safe 119,587 ops/sec8680Non-secure:81uid 58,860,241 ops/sec82nanoid/non-secure 2,744,615 ops/sec83rndm 2,718,063 ops/sec
39 unmodified lines
123124125## API126134Nano ID memiliki tiga buah API: normal (_blocking_), asinkronus (_asynchronous_), dan _non-secure_.127Nano ID memiliki dua API: normal dan _non-secure_.128129Bawaannya, 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).130131
18 unmodified lines
150151Dapat digunakan pula [custom alphabet](#custom-alphabet-or-size) atau [random generator](#custom-random-bytes-generator) yang lain.152153161### Async162163Untuk menghasilkan bytes yang acak dan aman secara kriptografis, CPU mengumpulkan noise elektromagnetik. Umumnya, entropi sudah dikumpulkan terlebih dahulu.164165Dalam 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).166167Ketika menggunakan API asinkronus dari Nano ID, proses lain dapat berjalan ketika CPU sedang mengumpulkan noise elektromagnetik.168169```js170import { nanoid } from 'nanoid/async'171172async function createUser() {173 user.id = await nanoid()174}175```176177Referensi 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.178179Sayangnya, 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).180181154### Non-Secure155156Konfigurasi 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 lines
174Ketika 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).175176Alfabet harus terbentuk dari 256 simbol atau lebih kecil. Selain itu, keamanan algoritma generasi yang berada di dalam library ini tidak dijamin aman.177206API asinkronus dan non-secure yang dapat dikustomisasi dengan `customAlphabet` pun tersedia disini:178API non-secure yang dapat dikustomisasi dengan `customAlphabet` pun tersedia disini:179180```js209import { customAlphabet } from 'nanoid/async'210const nanoid = customAlphabet('1234567890abcdef', 10)211async function createUser() {212 user.id = await nanoid()213}214```215216```js181import { customAlphabet } from 'nanoid/non-secure'182const nanoid = customAlphabet('1234567890abcdef', 10)183user.id = nanoid()184```
160 unmodified lines
modified:README.md+1 added-46 removed
40 unmodified lines
41* [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 lines
87secure-random-string 394,201 ops/sec88uid-safe.sync 393,176 ops/sec89shortid 49,916 ops/sec9092Async:93nanoid/async 135,260 ops/sec94async customAlphabet 136,059 ops/sec95async secure-random-string 135,213 ops/sec96uid-safe 119,587 ops/sec9791Non-secure:92uid 58,860,241 ops/sec93nanoid/non-secure 2,744,615 ops/sec94rndm 2,718,063 ops/sec
52 unmodified lines
147148149## API150158Nano ID has 3 APIs: normal (blocking), asynchronous, and non-secure.151Nano ID has 2 APIs: normal and non-secure.152153By default, Nano ID uses URL-friendly symbols (`A-Za-z0-9_-`) and returns an ID154with 21 characters (to have a collision probability similar to UUID v4).155
25 unmodified lines
181182[ID collision probability]: https://zelark.github.io/nano-id-cc/183184192### Async193194To generate hardware random bytes, CPU collects electromagnetic noise.195For most cases, entropy will be already collected.196197In the synchronous API during the noise collection, the CPU is busy and198cannot do anything useful (for instance, process another HTTP request).199200Using the asynchronous API of Nano ID, another code can run during201the entropy collection.202203```js204import { nanoid } from 'nanoid/async'205206async function createUser() {207 user.id = await nanoid()208}209```210211Read more about entropy collection in [`crypto.randomBytes`] docs.212213Unfortunately, you will lose performance advantages in a browser214if you use the asynchronous API, because Web Crypto API supports only215synchronous mode.216217[`crypto.randomBytes`]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback218219185### Non-Secure186187By default, Nano ID uses hardware random bytes generation for security188and low collision probability. If you are not so concerned with security,
16 unmodified lines
205model.id = nanoid() //=> "4f90d13a42"206```207208```js244import { customAlphabet } from 'nanoid/async'245const nanoid = customAlphabet('1234567890abcdef', 10)246async function createUser() {247 user.id = await nanoid()248}249```250251```js209import { customAlphabet } from 'nanoid/non-secure'210const nanoid = customAlphabet('1234567890abcdef', 10)211user.id = nanoid()212```
46 unmodified lines
259const { customRandom, urlAlphabet } = require('nanoid')260const nanoid = customRandom(urlAlphabet, 10, random)261```262306Asynchronous and non-secure APIs are not available for `customRandom`.307263Note, that between Nano ID versions we may change random generator264call sequence. If you are using seed-based generators, we do not guarantee265the same result.266
177 unmodified lines
modified:README.ru.md+1 added-51 removed
43 unmodified lines
44- [Безопасность](#безопасность)45- [Подключение](#подключение)46- [API](#api)47 - [Блокирующий](#блокирующий)48 - [Асинхронный](#асинхронный)48 - [Небезопасный](#небезопасный)49 - [Смена алфавита или длины](#смена-алфавита-или-длины)50 - [Смена генератора случайных чисел](#смена-генератора-случайных-чисел)51- [Руководство](#руководство)
39 unmodified lines
91secure-random-string 394,201 ops/sec92uid-safe.sync 393,176 ops/sec93shortid 49,916 ops/sec9496Async:97nanoid/async 135,260 ops/sec98async customAlphabet 136,059 ops/sec99async secure-random-string 135,213 ops/sec100uid-safe 119,587 ops/sec10195Non-secure:96uid 58,860,241 ops/sec97nanoid/non-secure 2,744,615 ops/sec98rndm 2,718,063 ops/sec
55 unmodified lines
154155156## API157165Nano ID разделён на три модуля:166стандартный (блокирующий), асинхронный и небезопасный.158Nano ID разделён на два модуля: стандартный и небезопасный.159160По умолчанию используются символы, безопасные для URL (`A-Za-z0-9_-`).161Длина ID по умолчанию — 21 символ162(чтобы вероятность коллизий была соизмеримой с UUID v4).
20 unmodified lines
183При изменении размера, всегда проверяйте риски184в нашем [калькуляторе коллизий](https://zelark.github.io/nano-id-cc/).185186195### Асинхронный196197Для аппаратной генерации случайных чисел процессор накапливает198электромагнитные шумы. Обычно они накоплены заранее, и получение199случайных чисел происходит быстро. Но могут быть ситуации, когда200системе требуется время на накопление энтропии.201202При использовании синхронного API процесс заблокируется203во время накопления энтропии. Например, веб-сервер не сможет204обрабатывать запрос следующего посетителя, пока не сгенерирует205ID для предыдущего.206207Но если использовать асинхронный API у Nano ID, то процесс будет работать208более эффективно: во время накопления шума сможет выполняться другая задача.209210```js211import { nanoid } from 'nanoid/async'212213async function createUser() {214 user.id = await nanoid()215}216```217218Про ожидание накопления энтропии можно почитать в описании метода219`crypto.randomBytes` в [документации Node.js].220221К сожалению, эта оптимизация имеет смысл только для Node.js. Web Crypto API222в браузерах не имеет асинхронной версии.223224[документации node.js]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback225226187### Небезопасный188189По умолчанию, Nano ID использует аппаратный генератор случайных чисел для190получения непредсказуемых ID и минимизации риска возникновения коллизий
20 unmodified lines
211user.id = nanoid() //=> "4f90d13a42"212```213214```js255import { customAlphabet } from 'nanoid/async'256const nanoid = customAlphabet('1234567890abcdef', 10)257async function createUser() {258 user.id = await nanoid()259}260```261262```js215import { customAlphabet } from 'nanoid/non-secure'216const nanoid = customAlphabet('1234567890abcdef', 10)217user.id = nanoid()218```
47 unmodified lines
266const { customRandom, urlAlphabet } = require('nanoid')267const nanoid = customRandom(urlAlphabet, 10, random)268```269318У асинхронной и небезопасной версий нет `customRandom`.270320271## Руководство272273### React274
147 unmodified lines
modified:README.zh-CN.md+1 added-45 removed
36 unmodified lines
37* [安全性](#安全性)38* [安装](#安装)39* [API](#api)40 * [阻塞](#阻塞)41 * [异步](#异步)41 * [不安全](#不安全)42 * [自定义字母或大小](#自定义字母或大小)43 * [自定义随机字节生成器](#自定义随机字节生成器)44* [用法](#用法)
37 unmodified lines
82secure-random-string 394,201 ops/sec83uid-safe.sync 393,176 ops/sec84shortid 49,916 ops/sec8587Async:88nanoid/async 135,260 ops/sec89async customAlphabet 136,059 ops/sec90async secure-random-string 135,213 ops/sec91uid-safe 119,587 ops/sec9286Non-secure:87uid 58,860,241 ops/sec88nanoid/non-secure 2,744,615 ops/sec89rndm 2,718,063 ops/sec
50 unmodified lines
140141142## API143151Nano ID 有3个 API:正常(阻塞),异步,和不安全。144Nano ID 有2个 API:正常(阻塞),和不安全。145146默认情况下,Nano ID 使用 URL 友好的符号(`A-Za-z0-9_-`)并返回一个147有21个字符(类似 UUID v4 的碰撞概率)的 ID。148
23 unmodified lines
172173[ID 碰撞概率]: https://alex7kom.github.io/nano-nanoid-cc/174175183### 异步184185为了生成硬件随机字节,CPU 会收集电磁噪声。186在大多数情况下,熵已经被收集。187188在同步API的噪声收集期间,CPU将忙于工作,无法执行其他有用的任务(例如,处理另一个HTTP请求)。189190使用Nano ID的异步API,可以在熵收集期间191运行另一个代码。192193```js194import { nanoid } from 'nanoid/async'195196async function createUser() {197 user.id = await nanoid()198}199```200201请阅读 [`crypto.randomBytes`] 文档了解更多关于熵收集的信息。202203不幸的是,您将在浏览器中失去 Web Crypto API 的优势204如果您使用异步 API。那么,目前在浏览器中,205您将受到安全性或异步行为的限制。206207[`crypto.randomBytes`]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback208209176### 不安全177178默认情况下,Nano ID 使用硬件随机字节生成以提供安全性和较低的碰撞概率。如果您对安全性不太担心,您可以在没有硬件随机生成器的环境中使用它179
13 unmodified lines
193model.id = nanoid() //=> "4f90d13a42"194```195196```js231import { customAlphabet } from 'nanoid/async'232const nanoid = customAlphabet('1234567890abcdef', 10)233async function createUser() {234 user.id = await nanoid()235}236```237238```js197import { customAlphabet } from 'nanoid/non-secure'198const nanoid = customAlphabet('1234567890abcdef', 10)199user.id = nanoid()200```
43 unmodified lines
244const { customRandom, urlAlphabet } = require('nanoid')245const nanoid = customRandom(urlAlphabet, 10, random)246```247290异步和非安全的API在 `customRandom` 中不可用。291248请注意,在Nano ID的不同版本之间,我们可能会更改随机生成器的调用顺序。如果您正在使用基于种子的生成器,我们不能保证相同的结果。249250251## 用法
169 unmodified lines