diff --git a/cuid.d.ts b/cuid.d.ts index 3923838..661636c 100644 --- a/cuid.d.ts +++ b/cuid.d.ts @@ -1,5 +1,6 @@ declare module '@bugsnag/cuid' { - function cuid(): string + export function fingerprint(): string + export function isCuid(value: unknown): value is string - export default cuid + export default function cuid(): string } diff --git a/index.js b/index.js index d6a7f5f..609c515 100644 --- a/index.js +++ b/index.js @@ -11,6 +11,7 @@ */ var fingerprint = require('./lib/fingerprint.js'); +var isCuid = require('./lib/is-cuid.js'); var pad = require('./lib/pad.js'); var c = 0, @@ -38,7 +39,7 @@ function cuid () { // timestamp // warning: this exposes the exact date and time // that the uid was created. - timestamp = (new Date().getTime()).toString(base), + timestamp = new Date().getTime().toString(base), // Prevent same-machine collisions. counter = pad(safeCounter().toString(base), blockSize), @@ -55,5 +56,6 @@ function cuid () { } cuid.fingerprint = fingerprint; +cuid.isCuid = isCuid; module.exports = cuid; diff --git a/lib/is-cuid.js b/lib/is-cuid.js new file mode 100644 index 0000000..db7d8f4 --- /dev/null +++ b/lib/is-cuid.js @@ -0,0 +1,8 @@ +/** + * Check the provided value is a valid device id + * @param {unknown} value + * @returns + */ +module.exports = function isCuid (value) { + return typeof value === 'string' && (/^c[a-z0-9]{20,32}$/).test(value); +}; diff --git a/test/test.js b/test/test.js index 10cfb5b..83197af 100644 --- a/test/test.js +++ b/test/test.js @@ -46,3 +46,22 @@ describe('cuid collisions', function () { expect(collisionTest(cuid)).toBe(true); }); }); + +describe('isCuid()', function () { + it('should return true for generated cuids', function () { + expect(cuid.isCuid(cuid())).toBe(true); + }); + + it('should return false for strings that are too short', function () { + expect(cuid.isCuid('cuidistooshort')).toBe(false); + }); + + it('should return false for strings that are too long', function () { + expect(cuid.isCuid('cuidismorethan32characterssoisnotvalid')).toBe(false); + }); + + it('should return false for strings that do not match the format', function () { + expect(cuid.isCuid('doesnotbeginwithacsoisinvalid')).toBe(false); + expect(cuid.isCuid('contains-invalid-characters')).toBe(false); + }); +});