oculus42 / short-uuid

Translate standard UUIDs into shorter formats and back.
MIT License
439 stars 13 forks source link

crypto.randomUUID() #76

Open MarZab opened 2 months ago

MarZab commented 2 months ago

Is there a plan to replace uuid with crypto.randomUUID() ?

Even the library itself recommends it in cases you only need UUIDv4.

oculus42 commented 2 months ago

71 brought up the possibility of externalizing the generator, which would allow you to use any of the sources. Obviously a breaking change, but there is no need for the library to be included.

The validate command added in 5.2.0 uses uuid for the "rigorous" validation, but that is just a single regex, which would be easy to bring over.

I was playing with emoji support for 6.0, but I think that will end up as a separate library just to keep the complexity down.

This could definitely be 6.0.

oculus42 commented 2 months ago

Right now short takes two arguments: short(alphabet, options). We could accept a function as options.uuid, and default to crypto.randomUUID() if none is passed (and it is available).

This does limit us to Node 20 support, unless we add specific node-only checks for 14.17.0+ where we would have to require('crypto')...

MarZab commented 2 months ago

Actually support for randomUUID only started in Node 19, so it would require passing in 'uuid' regardless.

https://nodejs.org/docs/latest-v19.x/api/crypto.html

oculus42 commented 2 months ago

Added in: v15.6.0, v14.17.0

As of Node 19 it is available on the globalThis. For the older versions we would have to require('crypto').

I wrote a quick proof node script to validate this:

#!/usr/bin/env node
console.log(process.version);
try {
  console.log(crypto.randomUUID());
} catch (e) {
 const crypto = require('crypto');
 console.log('require fallback', crypto.randomUUID());
}

The "fallback" produces a UUID on 14, 16, and 18.

v20.10.0
f93f0bd0-eb12-4eee-8fcc-effc035928f8

v18.18.0
require fallback 742fd1d0-f9b6-4de4-bd75-603f6eb35f1a

v16.20.2
require fallback e05b827e-5ffe-4df3-b67d-fb70b9cec088

v14.21.3
require fallback e6999778-2a7d-4319-b407-381234d9a698

Whether it's worth the logic when the consumer can provide it is a different question.

It also might be better on 6.0.0 to allow the first argument to be an options object.

// Prior to Node 19
const crypto = require('crypto');
const short = require('short-uuid');

// Use flickrBase58 if alphabet not specified in options
const translator = short({ uuid: crypto.randomUUID });