idchunk 2.0.0 → 2.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/index.js +37 -10
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "idchunk",
3
- "version": "2.0.0",
3
+ "version": "2.2.0",
4
4
  "description": "Tiny, Fast & Customizable ID Generator",
5
5
  "main": "src/index.js",
6
6
  "files": [
package/src/index.js CHANGED
@@ -1,16 +1,43 @@
1
- const crypto = require("crypto");
1
+ let nodeCrypto;
2
+ try {
3
+ nodeCrypto = require("crypto");
4
+ } catch {
5
+ nodeCrypto = null;
6
+ }
2
7
 
3
- const DEFAULT_VALUES = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
8
+ const DEFAULT_VALUES =
9
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
4
10
 
5
- function idchunk(length = 10, customValues = DEFAULT_VALUES) {
6
- if (typeof customValues !== "string" || customValues.length === 0) {
7
- throw new Error("customValues must be a non-empty string");
11
+ function getRandomInt(max) {
12
+ if (nodeCrypto) {
13
+ if (typeof nodeCrypto.randomInt === "function") {
14
+ return nodeCrypto.randomInt(0, max);
8
15
  }
9
- let result = "";
10
- for (let i = 0; i < length; i++) {
11
- result += customValues[crypto.randomInt(0, customValues.length)];
16
+ if (typeof nodeCrypto.randomBytes === "function") {
17
+ return nodeCrypto.randomBytes(1)[0] % max;
12
18
  }
13
- return result;
19
+ }
20
+
21
+ if (typeof globalThis.crypto !== "undefined" && globalThis.crypto.getRandomValues) {
22
+ const arr = new Uint32Array(1);
23
+ globalThis.crypto.getRandomValues(arr);
24
+ return arr[0] % max;
25
+ }
26
+
27
+ return Math.floor(Math.random() * max);
28
+ }
29
+
30
+ function idchunk(length = 10, customValues = DEFAULT_VALUES) {
31
+ if (typeof customValues !== "string" || customValues.length === 0) {
32
+ throw new Error("customValues must be a non-empty string");
33
+ }
34
+
35
+ let result = "";
36
+ for (let i = 0; i < length; i++) {
37
+ const randomIndex = getRandomInt(customValues.length);
38
+ result += customValues[randomIndex];
39
+ }
40
+ return result;
14
41
  }
15
42
 
16
- module.exports = idchunk;
43
+ module.exports = idchunk;