mono/packages/core/dist/uuid.js
2025-01-28 13:42:22 +01:00

93 lines
2.8 KiB
JavaScript

/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
'use strict';
class ValueUUID {
_value;
constructor(_value) {
this._value = _value;
// empty
}
asHex() {
return this._value;
}
equals(other) {
return this.asHex() === other.asHex();
}
}
class V4UUID extends ValueUUID {
static _chars = ['0', '1', '2', '3', '4', '5', '6', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
static _timeHighBits = ['8', '9', 'a', 'b'];
static _oneOf(array) {
return array[Math.floor(array.length * Math.random())];
}
static _randomHex() {
return V4UUID._oneOf(V4UUID._chars);
}
constructor() {
super([
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
'-',
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
'-',
'4',
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
'-',
V4UUID._oneOf(V4UUID._timeHighBits),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
'-',
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
V4UUID._randomHex(),
].join(''));
}
}
/**
* An empty UUID that contains only zeros.
*/
export const empty = new ValueUUID('00000000-0000-0000-0000-000000000000');
export function v4() {
return new V4UUID();
}
const _UUIDPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
export function isUUID(value) {
return _UUIDPattern.test(value);
}
/**
* Parses a UUID that is of the format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx.
* @param value A uuid string.
*/
export function parse(value) {
if (!isUUID(value)) {
throw new Error('invalid uuid');
}
return new ValueUUID(value);
}
export function generateUuid() {
return v4().asHex();
}
//# sourceMappingURL=uuid.js.map