You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
▲ Explain the major function of the project and how it works by referencing the most important and relevant code snippets.
The nanoid project is a lightweight, secure, and URL-friendly unique string ID generator for JavaScript. It aims to provide a more efficient and compact alternative to UUIDs.
Here's how it works:
1. Secure Randomness:
index.js: The core of the project relies on the crypto module in Node.js and the Web Crypto API in browsers to generate secure random bytes.
This API uses the Math.random() function, which is less secure and prone to collisions.
In summary, the nanoid project provides a robust and efficient way to generate unique IDs in JavaScript. It prioritizes security and offers flexibility through custom alphabet and random generator options. The non-secure API caters to scenarios where security is not a critical factor.
# Change Log
This project adheres to [Semantic Versioning](http://semver.org/).
## 5.0.7* Fixed Parcel support (by @WilhelmYakunin).
## 5.0.6* Fixed React Native support.
## 5.0.5* Make browser’s version faster by increasing size a little (by Samuel Elgozi).
## 5.0.4* Fixed CLI docs (by @ilyaboka).
## 5.0.3* Fixed CLI docs (by Chris Schmich).
## 5.0.2* Fixed `webcrypto` import (by Divyansh Singh).
## 5.0.1* Fixed Node.js 18 support.
## 5.0* Moved Node.js version to Web Crypto API.
* Removed async API since Web Crypto API has only sync version.
* Removed Node.js 14 and 16 support.
## 4.0.2* Added [link](https://github.com/sponsors/ai) to Github Sponsors.
## 4.0.1* Reduced npm package size (by @HiChen404).
## 4.0* Removed CommonJS support. Nano ID 4 will work only with ESM applications.
We will support 3.x branch with CommonJS for users who can’t migrate to ESM.
* Removed Node.js 10 and Node.js 12 support.
* Reduced npm package size.
## 3.3.7* Fixed `node16` TypeScript support (by Saadi Myftija).
## 3.3.6* Fixed package.
## 3.3.5* Backport funding information.
## 3.3.4* Fixed `--help` in CLI (by @Lete114).
## 3.3.3* Reduced size (by Anton Khlynovskiy).
## 3.3.2* Fixed `enhanced-resolve` support.
## 3.3.1* Reduced package size.
## 3.3* Added `size` argument to function from `customAlphabet` (by Stefan Sundin).
## 3.2* Added `--size` and `--alphabet` arguments to binary (by Vitaly Baev).
## 3.1.32* Reduced `async` exports size (by Artyom Arutyunyan).
* Moved from Jest to uvu (by Vitaly Baev).
## 3.1.31* Fixed collision vulnerability on object in `size` (by Artyom Arutyunyan).
## 3.1.30* Reduced size for project with `brotli` compression (by Anton Khlynovskiy).
## 3.1.29* Reduced npm package size.
## 3.1.28* Reduced npm package size.
## 3.1.27* Cleaned `dependencies` from development tools.
## 3.1.26* Improved performance (by Eitan Har-Shoshanim).
* Reduced npm package size.
## 3.1.25* Fixed `browserify` support.
## 3.1.24* Fixed `browserify` support (by Artur Paikin).
## 3.1.23* Fixed `esbuild` support.
## 3.1.22* Added `default` and `browser.default` to `package.exports`.
## 3.1.21* Reduced npm package size.
## 3.1.20* Fix ES modules support.
## 3.1.19* Reduced `customAlphabet` size (by Enrico Scherlies).
## 3.1.18* Fixed `package.exports`.
## 3.1.17* Added files without `process`.
## 3.1.16* Speeded up Nano ID 4 times (by Peter Boyer).
## 3.1.15* Fixed `package.types` path.
## 3.1.14* Added `package.types`.
## 3.1.13* Removed Node.js 15.0.0 with `randomFillSync` regression from `engines.node`.
## 3.1.12* Improved IE 11 docs.
## 3.1.11* Fixed asynchronous `customAlphabet` in browser (by @LoneRifle).
## 3.1.10* Fix ES modules support.
## 3.1.9* Try to fix React Native Expo support.
## 3.1.8* Add React Native Expo support.
## 3.1.7* Clean up code.
## 3.1.6* Avoid `self` using.
## 3.1.5* Improve IE docs and warning.
## 3.1.4* Restrict old Node.js 13 by `engines.node` (by Cansin Yildiz).
## 3.1.3* Fix ES modules issue with CLI.
## 3.1.2* Add shebang to CLI.
## 3.1.1* Fix CLI.
## 3.1* Add `npx nanoid` CLI.
## 3.0.2* Fix docs (by Dylan Irlbeck ).
## 3.0.1* Fix React Native warning on `non-secure` import (by Jia Huang).
## 3.0**Migration guide:**<https://github.com/ai/nanoid/releases/tag/3.0.0>* Move to ES2016 syntax. You need to use Babel for IE 11.
* Move to named exports `import { nanoid } from 'nanoid'`.
* Move `import url from 'nanoid/url'` to `import { urlAlphabet } from 'nanoid'`.
* Replace `format()` to `customRandom()`.
* Replace `generate()` to `customAlphabet()`.
* Remove `async/format`.
* Remove React Native support for `nanoid/async`.
* Add `nanoid.js` to use directly in browser from CDN.
* Add TypeScript type definitions.
* Add ES modules support for bundlers, Node.js, and React Native.
* Fix React Native support.
* Reduce size.
* Improve docs (by Dair Aidarkhanov).
## 2.1.11* Reduce size (by Anton Evzhakov).
## 2.1.10* Reduce size by 10% (by Anton Khlynovskiy).
## 2.1.9* Reduce `format` and `async/format` size (by Dair Aidarkhanov).
## 2.1.8* Improve React docs (by Nahum Zsilva).
## 2.1.7* Reduce `index`, `async` and `non-secure` size (by @polemius).
## 2.1.6* Reduce size (by Stas Lashmanov).
* Return fast mask for Node.js.
## 2.1.5* Reduce size (by Max Graey).
* Fix IE support.
## 2.1.4* Reduce `generate` size (by Vsevolod Rodionov).
* Reduce `format` and `format` size (by Victor).
* Reduce `async`, `non-secure` and `non-secure/generate` size.
* Speed up `format` and `async/format` (by Max Graey).
* Improve development process on Windows (by Stanislav Lashmanov).
## 2.1.3* Improve performance (by Stephen Richardson).
* Reduce size (by Stephen Richardson).
## 2.1.2* Improve docs.
## 2.1.1* Fix React Native support (by Shawn Hwei).
## 2.1* Improve React Native support (by Sebastian Werner).
## 2.0.4* Improve error text for React Native (by Sebastian Werner).
## 2.0.3* Fix freeze on string in ID length.
## 2.0.2* Improve docs (by Sylvanus Kateile and Mark Stosberg).
## 2.0.1* Reduce npm package size.
* Mark package as not having side effects (by @xiaody).
## 2.0* Use `-` instead of `~` in default alphabet to by file name safe.
* Add `nanoid/non-secure/generate`.
## 1.3.4* Reduce `non-secure` size.
* Add `async` callback type check.
## 1.3.3* Fix `nanoid/async` performance regression.
* Fix old Node.js `not seeded` issue in synchronous version too.
## 1.3.2* Fix random generator `not seeded` issue of old Node.js.
## 1.3.1* Reduce library size.
## 1.3* Add `nanoid/async/format` and `nanoid/async/generate`.
* Improve synchronous API performance.
* Reduce `url` size (by Daniil Poroshin).
* Improve React Native docs (by joelgetaction).
## 1.2.6* Reduce library size (by rqrqrqrq).
## 1.2.5* Fix Node.js 6.11.1 support (by Andrey Belym).
## 1.2.4* Speed up Node.js secure generators (by Dmitriy Tsvettsikh).
## 1.2.3* Fix JSDoc (by Hendry Sadrak).
## 1.2.2* Fix distribution in `nanoid/non-secure` (by Eatall).
## 1.2.1* Fix old Node.js support.
## 1.2* Add `nanoid/async`.
* Fix `nanoid/non-secure` JSDoc.
* Add Chinese documentation (by Wenliang Dai).
* Speed up and reduce size of `nanoid/non-secure` (by Ori Livni).
## 1.1.1* Improve performance and reduce size of non-secure ID generator.
## 1.1* Add non-secure ID generator.
* Suggest to use non-secure ID generator for React Native developers.
* Reduce size.
## 1.0.7* Fix documentation.
## 1.0.6* Fix documentation.
## 1.0.5* Reduce `nanoid/index` size (by Anton Khlynovskiy).
## 1.0.4* Reduce npm package size.
## 1.0.3* Reduce npm package size.
## 1.0.2* Fix Web Workers support (by Zachary Golba).
## 1.0.1* Reduce `nanoid/index` size (by Anton Khlynovskiy).
## 1.0* Use 21 symbols by default (by David Klebanoff).
## 0.2.2* Reduce `nanoid/generate` size (by Anton Khlynovskiy).
* Speed up Node.js random generator.
## 0.2.1* Fix documentation (by Piper Chester).
## 0.2* Add `size` argument to `nanoid()`.
* Improve performance by 50%.
* Reduce library size by 26% (by Vsevolod Rodionov and Oleg Mokhov).
## 0.1.1* Reduce library size by 5%.
## 0.1* Initial release.
ai/nanoid/blob/main/README.id-ID.md:
# Nano ID
<img src="https://ai.github.io/nanoid/logo.svg" align="right"
alt="Logo Nano ID oleh Anton Lovchikov" width="180" height="94">
[English](./README.md) | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | **Bahasa Indonesia**
Sebuah generator ID yang unik dalam bentuk string yang ringan, aman, serta _URL-friendly_ untuk JavaScript.
> "Sebuah tingkat kesempurnaan yang luar biasa,> yang mana tidak mungkin untuk tidak dihormati."-**Ringan.** Hanya 116 bytes (diperkecil dan brotlied). Tidak ada ketergantungan (dependencies) apapun. [Size Limit](https://github.com/ai/size-limit) mengatur ukuran dari generator ini.
-**Aman.** Nano ID menggunakan RNG yang terdapat pada perangkat keras. Dapat digunakan dalam lingkungan seperti klaster.
-**ID yang pendek.** Nano ID menggunakan alfabet yang lebih banyak ketimbang UUID (`A-Za-z0-9_-`), karenanya ukuran ID menjadi berkurang dari 36 menjadi 21 simbol.
-**Portabel.** Nano ID telah dimigrasi untuk [20 bahasa pemrograman lainnya](#bahasa-pemrograman-lainnya).
```jsimport { nanoid } from'nanoid'model.id=nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
Mendukung penjelajah (browser) modern, IE dengan Babel, Node.js, dan React Native.
Made at Evil Martians, product consulting for developer tools.
Nano ID dapat dibandingkan dengan UUID v4 (yang berbasis acak / randomly generated). Nano ID dan UUID v4 memiliki jumlah bita yang mirip pada ID yang dihasilkan (126 bita pada NanoID dan 122 bita pada UUID), karenanya ia memiliki probabilitas collision (konflik / tabrakan) yang hampir serupa:
Agar timbul kemungkinan collison / duplikasi ID satu dalam satu miliar, perlu dihasilkan 103 triliun UUID v4.
Ada dua buah perbedaan antara Nano ID dan UUID v4:
Nano ID menggunakan alfabet yang lebih lebar, karenanya jumlah bita acak dapat 'dikemas' dalam 21 simbol, bukan 36 simbol.
Kode sumber Nano ID empat kali lebih kecil ketimbang uuid/v4: 130 bytes dibanding 423 bytes.
Ketidakpastian. Sebagai ganti untuk penggunaan Math.random(), Nano ID menggunakan modul crypto yang ada di dalam Nodejs dan/atau Web Crypto API dalam penjelajah (browser). Modul-modul ini menggunakan generator acak berbasis perangkat keras yang tidak bisa diprediksi untuk mendapatkan nilai-nilai yang tidak pasti yang aman secara kriptografis.
Keseragaman. Pembagian dengan rumus random % alphabet adalah kesalahan yang seringkali dilakukan ketika merancang sebuah generator ID. Distribusi dari nilai-nilai tersebut tidak akan seimbang; dalam artian ada kesempatan untuk beberapa simbol untuk muncul dibandingkan dengan simbol yang lain. Ini memiliki dampak yang kurang baik, yakni mengurangi jumlah percobaan ketika seseorang mencoba untuk melakukan brute-force attacks. Nano ID menggunakan algoritma yang lebih baik dan sudah diuji untuk keseragamannya.
Terdokumentasi secara baik. Seluruh algoritma Nano ID sudah terdokumentasi. Lihat komentar di kode sumber.
Kerentanan. Untuk melaporkan sebuah security vulnerability atau kerentanan, mohon menggunakan Tidelift Security Contact. Tidelift akan mengkoordinasikan pembetulan dan penyingkapan dari kerentanan tersebut.
Instalasi
npm install nanoid
Nano ID 5 hanya tersedia untuk proyek, pengujian, atau skrip ESM Node.js.
Untuk CommonJS Anda memerlukan Nano ID 3.x (kami masih mendukungnya):
npm install nanoid@3
Apabila ingin 'coba-coba' terlebih dahulu, dapat digunakan Nano ID melalui CDN. Hal ini tidak direkomendasikan untuk digunakan pada lingkungan produksi karena performa pemuatan (loading) yang berkurang.
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).
Blocking
Penggunaan Nano ID yang aman dan yang paling mudah.
Dalam kasus langka, fungsi ini dapat menghambat CPU untuk melakukan proses yang lain ketika dalam proses 'noise-collection' untuk generasi nilai acak (yang dilakukan pada perangkat keras).
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.
customRandom digunakan untuk membuat Nano ID yang mengganti alfabet dan algoritma random bytes generator yang telah diimplementasikan pada versi bawaan (dalam artian menggunakan algoritma sendiri untuk mendapatkan random bytes).
Pada contoh berikut, digunakan seed-based generator:
API asinkronus dan non-secure tidak tersedia untuk fungsi customRandom.
Penggunaan
React
Dalam React, tidak ada cara yang benar bila ingin menggunakan Nano ID untuk prop key, karena key tersebut harus konsisten dalam setiap proses render yang terjadi.
functionTodos({ todos }){return(<ul>{todos.map(todo=>(/* JANGAN DILAKUKAN! */<likey={nanoid()}>{todo.text}</li>))}</ul>)}
Karena hal tersebut, disarankan untuk menggunakan ID yang stabil pada setiap objek yang di-render oleh React.
Apabila tidak memiliki ID yang stabil pada setiap item yang di-render pada React, lebih baik menggunakan indeks sebuah array sebagai key ketimbang menggunakan fungsi nanoid(), seperti berikut:
consttodoItems=todos.map((text,index)=>(/* Tetap tidak direkomendasikan, tetapi lebih disarankan dari 'nanoid()'. Lakukan ini apabila setiap objek / item dalam list tidak ada ID yang stabil. */<likey={index}>{text}</li>))
React Native
React Native tidak memiliki built-in random generator. Digunakan polyfill seperti berikut yang berjalan untuk React Native dan Expo yang bermula dari versi 39.x.
Dalam PouchDB dan CouchDB, ID tidak bisa dimulai dengan underscore _. Sebuah prefix dibutuhkan untuk mencegah hal ini terjadi, karena Nano ID mungkin menggunakan _ sebagai karakter pertama dari ID yang dihasilkan.
ID bawaan dapat diubah dengan opsi berikut:
db.put({_id: 'id'+nanoid(),
…
})
Web Workers
Web Workers tidak memiliki akses untuk secure random generator.
Keamanan sangat penting pada ID yang mana setiap ID harus memiliki sifat tidak bisa diprediksi, seperti pada contoh use-case generasi link pada "access by URL". Apabila tidak memerlukan ID yang tidak bisa diprediksi, tetapi ingin/harus menggunakan Web Workers, dapat digunakan NanoID dengan API non-secure.
Perhatian: ID yang dihasilkan dari non-secure dapat lebih mudah tabrakan / memiliki probabilitas collision yang lebih besar.
CLI
Nano ID dapat didapatkan dengan cara menggunakan npx nanoid pada Terminal. Hanya diperlukan Node.js untuk ini, dan tidak perlu mengunduh dan menginstall Nano ID dalam sistem.
$ npx nanoid
npx: installed 1 in 0.63s
LZfXLFzPPR4NNrgjlWDxn
Bila ingin mengganti alfabet atau ukuran ID, dapat menggunakan nanoid-cli.
Bahasa Pemrograman Lainnya
Nano ID telah bermigrasi ke berbagai macam bahasa. Seluruh versi dapat digunakan untuk mendapatkan ID generator yang sama pada sisi klien dan sisi penyedia layanan (client-side dan server-side).
nanoid-good untuk meyakinkan bahwa ID yang di-generasi tidak memiliki kata-kata yang kurang baik (kasar, tidak sopan, dsb.).
ai/nanoid/blob/main/README.md:
```md
# Nano ID
<img src="https://ai.github.io/nanoid/logo.svg" align="right"
alt="Nano ID logo by Anton Lovchikov" width="180" height="94">
**English** | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md)
A tiny, secure, URL-friendly, unique string ID generator for JavaScript.
> “An amazing level of senseless perfectionism,
> which is simply impossible not to respect.”
* **Small.** 116 bytes (minified and brotlied). No dependencies.
[Size Limit] controls the size.
* **Safe.** It uses hardware random generator. Can be used in clusters.
* **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`).
So ID size was reduced from 36 to 21 symbols.
* **Portable.** Nano ID was ported
to over [20 programming languages](./README.md#other-programming-languages).
```js
import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
Made at Evil Martians, product consulting for developer tools.
Nano ID is quite comparable to UUID v4 (random-based).
It has a similar number of random bits in the ID
(126 in Nano ID and 122 in UUID), so it has a similar collision probability:
For there to be a one in a billion chance of duplication,
103 trillion version 4 IDs must be generated.
There are two main differences between Nano ID and UUID v4:
Nano ID uses a bigger alphabet, so a similar number of random bits
are packed in just 21 symbols instead of 36.
Nano ID code is 4 times smaller than uuid/v4 package:
130 bytes instead of 423.
Unpredictability. Instead of using the unsafe Math.random(), Nano ID
uses the crypto module in Node.js and the Web Crypto API in browsers.
These modules use unpredictable hardware random generator.
Uniformity.random % alphabet is a popular mistake to make when coding
an ID generator. The distribution will not be even; there will be a lower
chance for some symbols to appear compared to others. So, it will reduce
the number of tries when brute-forcing. Nano ID uses a better algorithm
and is tested for uniformity.
Well-documented: all Nano ID hacks are documented. See comments
in the source.
Vulnerabilities: to report a security vulnerability, please use
the Tidelift security contact.
Tidelift will coordinate the fix and disclosure.
Install
npm install nanoid
Nano ID 5 works only with ESM projects, in tests or Node.js scripts.
For CommonJS you need to use Node.js 22 with --experimental-require-module:
node --experimental-require-module app.js
Or you can use Nano ID 3.x (we still support it):
npm install nanoid@3
For quick hacks, you can load Nano ID from CDN. Though, it is not recommended
to be used in production because of the lower loading performance.
By default, Nano ID uses hardware random bytes generation for security
and low collision probability. If you are not so concerned with security,
you can use it for environments without hardware random generators.
Note, that between Nano ID versions we may change random generator
call sequence. If you are using seed-based generators, we do not guarantee
the same result.
Usage
React
There’s no correct way to use Nano ID for React key prop
since it should be consistent among renders.
functionTodos({todos}){return(<ul>{todos.map(todo=>(<likey={nanoid()}> /* DON’T DO IT */
{todo.text}</li>))}</ul>)}
You should rather try to reach for stable ID inside your list item.
In case you don’t have stable IDs you'd rather use index as key
instead of nanoid():
consttodoItems=todos.map((text,index)=><likey={index}> /* Still not recommended but preferred over nanoid().
Only do this if items have no stable IDs. */
{text}</li>)
In case you just need random IDs to link elements like labels
and input fields together, useId is recommended.
That hook was added in React 18.
React Native
React Native does not have built-in random generator. The following polyfill
works for plain React Native and Expo starting with 39.x.
In PouchDB and CouchDB, IDs can’t start with an underscore _.
A prefix is required to prevent this issue, as Nano ID might use a _
at the start of the ID by default.
Override the default ID with the following option:
db.put({_id: 'id'+nanoid(),
…
})
Web Workers
Web Workers do not have access to a secure random generator.
Security is important in IDs when IDs should be unpredictable.
For instance, in "access by URL" link generation.
If you do not need unpredictable IDs, but you need to use Web Workers,
you can use the non‑secure ID generator.
nanoid-good to be sure that your ID doesn’t contain any obscene words.
ai/nanoid/blob/main/README.ru.md:
```md
# Nano ID
<img src="https://ai.github.io/nanoid/logo.svg" align="right"
alt="Логотип Nano ID от Антона Ловчикова" width="180" height="94">
[English](./README.md) | **Русский** | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md)
Генератор уникальных ID для JavaScript — лёгкий, безопасный,
ID можно применять в URL.
> «Поразительный уровень бессмысленного перфекционизма,
> который просто невозможно не уважать»
- **Лёгкий.** 116 байт (после минификации и Brotli). Без зависимостей.
[Size Limit] следит за размером.
- **Безопасный.** Использует аппаратный генератор случайных чисел.
Можно использовать в кластерах машин.
- **Короткие ID.** Используется больший алфавит, чем у UUID (`A-Za-z0-9_-`).
Поэтому длина ID уменьшена с 36 до 21 символа.
- **Работает везде.** Nano ID уже портировали
на [20 языков программирования](#другие-языки-программирования).
```js
import { nanoid } from 'nanoid'
model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
Поддерживает современные браузеры, IE (с Babel), Node.js и React Native.
Сделано в Злых марсианах, продуктовом консалтинге для инструментов разработки.
Nano ID похож на UUID v4 (случайный).
У них сравнимое число битов случайности в ID (126 у Nano ID против 122 у UUID),
поэтому они обладают похожей вероятностью возникновения коллизий
(повторной генерации ранее выданных ID):
Чтобы вероятность повтора приблизилась к 1 на миллиард,
нужно сгенерировать 103 триллиона ID.
Но между ними есть 2 важных отличия:
Nano ID использует более широкий алфавит, и сравнимое количество
битов случайности будут упакованы в более короткую строку
(21 символ, против 36 у UUID).
Код Nano ID в 4 раз меньше, чем у uuid/v4 — 130 байт против 423.
Непредсказуемость. Вместо предсказуемого Math.random(), Nano ID
использует модуль crypto в Node.js и Web Crypto API в браузере.
Эти модули дают доступ к аппаратному генератору случайных чисел.
Равномерность. Например, существует популярная ошибка random % alphabet,
которую часто допускают при разработке генератора ID.
Распределение вероятности для каждого символа может не быть одинаковым.
Из-за неравномерности использования пространства алфавита, на перебор ID
потребуется меньше времени, чем ожидается.
Nano ID использует более совершенный алгоритм,
а равномерность распределения символов покрыта тестами.
Документация: все хитрости Nano ID хорошо документированы — смотрите
комментарии в исходниках.
Уязвимости: если вы нашли уязвимость в Nano ID, свяжитесь с
командой безопасности Tidelift.
Они проконтролируют исправление и проинформируют пользователей.
Подключение
npm install nanoid
Nano ID 5 работает только с ESM-проектами, в тестах или скриптах для Node.js.
Для CommonJS вам нужна Node.js 22 с флагом --experimental-require-module:
node --experimental-require-module app.js
Или возьмите Nano ID 3.x (мы его всё ещё поддерживаем):
npm install nanoid@3
Для быстрого прототипирования вы можете подключить Nano ID с CDN без установки.
Не используйте этот способ на реальном сайте, так как он сильно бьёт
по скорости загрузки сайта.
Nano ID разделён на два модуля: стандартный и небезопасный.
По умолчанию используются символы, безопасные для URL (A-Za-z0-9_-).
Длина ID по умолчанию — 21 символ
(чтобы вероятность коллизий была соизмеримой с UUID v4).
Блокирующий
Безопасный и простой в использовании способ использования Nano ID.
Из-за особенностей работы генератора случайных чисел при использовании этого
способа ЦПУ может иногда простаивать без работы.
По умолчанию, Nano ID использует аппаратный генератор случайных чисел для
получения непредсказуемых ID и минимизации риска возникновения коллизий
(повторной генерации ранее выданных ID). Но если вам не требуется устойчивость
к подбору ID, то вы можете перейти на небезопасный генератор — это полезно
там, где нет доступа к API аппаратного генератора случайных чисел.
Не забудьте проверить риски коллизии вашего алфавита и длины
на нашем калькуляторе. nanoid-dictionary содержит много популярных
примеров альтернативных алфавитов.
Алфавит должен содержать ≤256 символов. Иначе мы не сможем гарантировать
непредсказуемость ID.
Длину ID можно менять не только в customAlphabet(), но и при вызове
генератора, который она вернёт:
Можно сгенерировать уникальный ID прямо из терминала, вызвав npx nanoid.
Для этого в системе должна быть только Node.js. npx сама скачает Nano ID,
если его нет в системе.
$ npx nanoid
npx: installed 1 in 0.63s
LZfXLFzPPR4NNrgjlWDxn
Длину генерируемых ID можно передать в аргументе --size (или -s):
$ npx nanoid --size 10
L3til0JS4z
Изменить алфавит можно при помощи аргумента --alphabet (ли -a)
(в этом случае --size обязателен):
// This file replaces `index.js` in bundlers like webpack or Rollup,// according to `browser` config in `package.json`.import{urlAlphabetasscopedUrlAlphabet}from'./url-alphabet/index.js'export{urlAlphabet}from'./url-alphabet/index.js'exportletrandom=bytes=>crypto.getRandomValues(newUint8Array(bytes))exportletcustomRandom=(alphabet,defaultSize,getRandom)=>{// 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.letmask=(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 integerletstep=-~((1.6*mask*defaultSize)/alphabet.length)return(size=defaultSize)=>{letid=''while(true){letbytes=getRandom(step)// A compact alternative for `for (var i = 0; i < step; i++)`.letj=stepwhile(j--){// Adding `|| ''` refuses a random byte that exceeds the alphabet size.id+=alphabet[bytes[j]&mask]||''if(id.length===size)returnid}}}}exportletcustomAlphabet=(alphabet,size=21)=>customRandom(alphabet,size,random)exportletnanoid=(size=21)=>{letid=''letbytes=crypto.getRandomValues(newUint8Array(size))while(size--){// Using the bitwise AND operator to "cap" the value of// the random byte from 255 to 63, in that way we can make sure// that the value will be a valid index for the "chars" string.id+=scopedUrlAlphabet[bytes[size]&63]}returnid}
ai/nanoid/blob/main/index.d.ts:
/** * Generate secure URL-friendly unique ID. * * By default, the ID will have 21 symbols to have a collision probability * similar to UUID v4. * * ```js * import { nanoid } from 'nanoid' * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" * ``` * * @param size Size of the ID. The default size is 21. * @returns A random string. */exportfunctionnanoid(size?: number): string/** * Generate secure unique ID with custom alphabet. * * 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 random string generator. * * ```js * const { customAlphabet } = require('nanoid') * const nanoid = customAlphabet('0123456789абвгдеё', 5) * nanoid() //=> "8ё56а" * ``` */exportfunctioncustomAlphabet(alphabet: string,defaultSize?: number): (size?: number)=>string/** * Generate unique ID with custom random generator and alphabet. * * Alphabet must contain 256 symbols or less. Otherwise, the generator * will not be secure. * * ```js * import { customRandom } from 'nanoid/format' * * const nanoid = customRandom('abcdef', 5, size => { * const random = [] * for (let i = 0; i < size; i++) { * random.push(randomByte()) * } * return random * }) * * nanoid() //=> "fbaef" * ``` * * @param alphabet Alphabet used to generate a random string. * @param size Size of the random string. * @param random A random bytes generator. * @returns A random string generator. */exportfunctioncustomRandom(alphabet: string,size: number,random: (bytes: number)=>Uint8Array): ()=>string/** * URL safe symbols. * * ```js * import { urlAlphabet } from 'nanoid' * const nanoid = customAlphabet(urlAlphabet, 10) * nanoid() //=> "Uakgb_J5m9" * ``` */exportconsturlAlphabet: string/** * Generate an array of random bytes collected from hardware noise. * * ```js * import { customRandom, random } from 'nanoid' * const nanoid = customRandom("abcdef", 5, random) * ``` * * @param bytes Size of the array. * @returns An array of random bytes. */exportfunctionrandom(bytes: number): Uint8Array
ai/nanoid/blob/main/index.js:
import{webcryptoascrypto}from'node:crypto'import{urlAlphabetasscopedUrlAlphabet}from'./url-alphabet/index.js'export{urlAlphabet}from'./url-alphabet/index.js'// It is best to make fewer, larger requests to the crypto module to// avoid system call overhead. So, random numbers are generated in a// pool. The pool is a Buffer that is larger than the initial random// request size by this multiplier. The pool is enlarged if subsequent// requests exceed the maximum buffer size.constPOOL_SIZE_MULTIPLIER=128letpool,poolOffsetfunctionfillPool(bytes){if(!pool||pool.length<bytes){pool=Buffer.allocUnsafe(bytes*POOL_SIZE_MULTIPLIER)crypto.getRandomValues(pool)poolOffset=0}elseif(poolOffset+bytes>pool.length){crypto.getRandomValues(pool)poolOffset=0}poolOffset+=bytes}exportfunctionrandom(bytes){// `-=` convert `bytes` to number to prevent `valueOf` abusingfillPool((bytes-=0))returnpool.subarray(poolOffset-bytes,poolOffset)}exportfunctioncustomRandom(alphabet,defaultSize,getRandom){// 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).letmask=(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).letstep=Math.ceil((1.6*mask*defaultSize)/alphabet.length)return(size=defaultSize)=>{letid=''while(true){letbytes=getRandom(step)// A compact alternative for `for (let i = 0; i < step; i++)`.leti=stepwhile(i--){// Adding `|| ''` refuses a random byte that exceeds the alphabet size.id+=alphabet[bytes[i]&mask]||''if(id.length===size)returnid}}}}exportfunctioncustomAlphabet(alphabet,size=21){returncustomRandom(alphabet,size,random)}exportfunctionnanoid(size=21){// `-=` convert `size` to number to prevent `valueOf` abusingfillPool((size-=0))letid=''// We are reading directly from the random pool to avoid creating new arrayfor(leti=poolOffset-size;i<poolOffset;i++){// 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+=scopedUrlAlphabet[pool[i]&63]}returnid}
/** * Generate URL-friendly unique ID. This method uses the non-secure * predictable random generator with bigger collision probability. * * ```js * import { nanoid } from 'nanoid/non-secure' * model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqL" * ``` * * @param size Size of the ID. The default size is 21. * @returns A random string. */exportfunctionnanoid(size?: number): string/** * Generate a unique ID based on a custom alphabet. * This method uses the non-secure predictable random generator * with bigger collision probability. * * @param alphabet Alphabet used to generate the ID. * @param defaultSize Size of the ID. The default size is 21. * @returns A random string generator. * * ```js * import { customAlphabet } from 'nanoid/non-secure' * const nanoid = customAlphabet('0123456789абвгдеё', 5) * model.id = //=> "8ё56а" * ``` */exportfunctioncustomAlphabet(alphabet: string,defaultSize?: number): (size?: number)=>string
ai/nanoid/blob/main/non-secure/index.js:
// This alphabet uses `A-Za-z0-9_-` symbols.// The order of characters is optimized for better gzip and brotli compression.// References to the same file (works both for gzip and brotli):// `'use`, `andom`, and `rict'`// References to the brotli default dictionary:// `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf`leturlAlphabet='useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'exportletcustomAlphabet=(alphabet,defaultSize=21)=>{return(size=defaultSize)=>{letid=''// A compact alternative for `for (var i = 0; i < step; i++)`.leti=sizewhile(i--){// `| 0` is more compact and faster than `Math.floor()`.id+=alphabet[(Math.random()*alphabet.length)|0]}returnid}}exportletnanoid=(size=21)=>{letid=''// A compact alternative for `for (var i = 0; i < step; i++)`.leti=sizewhile(i--){// `| 0` is more compact and faster than `Math.floor()`.id+=urlAlphabet[(Math.random()*64)|0]}returnid}
// This alphabet uses `A-Za-z0-9_-` symbols.// The order of characters is optimized for better gzip and brotli compression.// Same as in non-secure/index.jsexportconsturlAlphabet='useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters