UNPKG

2.62 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.BASE_UUID = void 0;
4exports.generate = generate;
5exports.isValid = isValid;
6exports.unparse = unparse;
7exports.write = write;
8exports.toShortForm = toShortForm;
9exports.toLongForm = toLongForm;
10const tslib_1 = require("tslib");
11const crypto_1 = tslib_1.__importDefault(require("crypto"));
12exports.BASE_UUID = "-0000-1000-8000-0026BB765291";
13// http://stackoverflow.com/a/25951500/66673
14function generate(data) {
15 const sha1sum = crypto_1.default.createHash("sha1");
16 sha1sum.update(data);
17 const s = sha1sum.digest("hex");
18 let i = -1;
19 return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
20 i += 1;
21 switch (c) {
22 case "y":
23 return ((parseInt("0x" + s[i], 16) & 0x3) | 0x8).toString(16);
24 case "x":
25 default:
26 return s[i];
27 }
28 });
29}
30const VALID_UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
31function isValid(UUID) {
32 return VALID_UUID_REGEX.test(UUID);
33}
34function unparse(buf, offset = 0) {
35 let i = offset;
36 return buf.toString("hex", i, (i += 4)) + "-" +
37 buf.toString("hex", i, (i += 2)) + "-" +
38 buf.toString("hex", i, (i += 2)) + "-" +
39 buf.toString("hex", i, (i += 2)) + "-" +
40 buf.toString("hex", i, i + 6);
41}
42function write(uuid, buf, offset = 0) {
43 const buffer = Buffer.from(uuid.replace(/-/g, ""), "hex");
44 if (buf) {
45 buffer.copy(buf, offset);
46 return buf;
47 }
48 else {
49 return buffer;
50 }
51}
52const SHORT_FORM_REGEX = /^0*([0-9a-f]{1,8})-([0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
53function toShortForm(uuid, base = exports.BASE_UUID) {
54 if (!isValid(uuid)) {
55 throw new TypeError("uuid was not a valid UUID or short form UUID");
56 }
57 if (base && !isValid("00000000" + base)) {
58 throw new TypeError("base was not a valid base UUID");
59 }
60 if (base && !uuid.endsWith(base)) {
61 return uuid.toUpperCase();
62 }
63 return uuid.replace(SHORT_FORM_REGEX, "$1").toUpperCase();
64}
65const VALID_SHORT_REGEX = /^[0-9a-f]{1,8}$/i;
66function toLongForm(uuid, base = exports.BASE_UUID) {
67 if (isValid(uuid)) {
68 return uuid.toUpperCase();
69 }
70 if (!VALID_SHORT_REGEX.test(uuid)) {
71 throw new TypeError("uuid was not a valid UUID or short form UUID");
72 }
73 if (!isValid("00000000" + base)) {
74 throw new TypeError("base was not a valid base UUID");
75 }
76 return (("00000000" + uuid).substr(-8) + base).toUpperCase();
77}
78//# sourceMappingURL=uuid.js.map
\No newline at end of file