3 const common
= require('./common');
4 const { createHash
} = require('crypto');
7 * TODO: base62 would be slightly prettier
8 * TODO: filter potential horrors
10 * @param {number} maxLength
12 async
function newSlug(seed
, maxLength
= 86) {
17 if (typeof seed
!== 'undefined') {
18 const hash
= createHash('sha512');
20 slug
= hash
.digest('base64');
22 const slugRaw
= await common
.randomBytesAsync(Math
.round(maxLength
* 3 / 4));
23 slug
= slugRaw
.toString('base64');
25 return slug
.slice(0, maxLength
).replace('/', '-').replace('+', '.');
29 async
function* makeSlugGenerator(seed
, initialLength
= 5, maxLength
= 22) {
30 let length
= initialLength
;
31 let slug
= await
newSlug(seed
, maxLength
);
33 yield slug
.slice(0, length
);
35 if (length
> maxLength
) {
36 length
= initialLength
;
37 slug
= await
newSlug(undefined, maxLength
); // Hash not suitable, try randomness.