idchunk 2.1.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 +32 -15
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "idchunk",
3
- "version": "2.1.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,26 +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
11
  function getRandomInt(max) {
6
- if (typeof crypto.randomInt === "function") {
7
- return crypto.randomInt(0, max);
12
+ if (nodeCrypto) {
13
+ if (typeof nodeCrypto.randomInt === "function") {
14
+ return nodeCrypto.randomInt(0, max);
15
+ }
16
+ if (typeof nodeCrypto.randomBytes === "function") {
17
+ return nodeCrypto.randomBytes(1)[0] % max;
8
18
  }
9
- const byte = crypto.randomBytes(1)[0];
10
- return byte % max;
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);
11
28
  }
12
29
 
13
30
  function idchunk(length = 10, customValues = DEFAULT_VALUES) {
14
- if (typeof customValues !== "string" || customValues.length === 0) {
15
- throw new Error("customValues must be a non-empty string");
16
- }
31
+ if (typeof customValues !== "string" || customValues.length === 0) {
32
+ throw new Error("customValues must be a non-empty string");
33
+ }
17
34
 
18
- let result = "";
19
- for (let i = 0; i < length; i++) {
20
- const randomIndex = getRandomInt(customValues.length);
21
- result += customValues[randomIndex];
22
- }
23
- return result;
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;
24
41
  }
25
42
 
26
43
  module.exports = idchunk;