Socket
Socket
Sign inDemoInstall

bson

Package Overview
Dependencies
Maintainers
5
Versions
162
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

bson - npm Package Compare versions

Comparing version 4.2.3 to 4.3.0

lib/uuid_utils.js

2

bower.json

@@ -25,3 +25,3 @@ {

],
"version": "4.2.3"
"version": "4.3.0"
}

@@ -65,2 +65,3 @@ import { Buffer } from 'buffer';

/* Excluded from this release type: toExtendedJSON */
/* Excluded from this release type: toUUID */
/* Excluded from this release type: fromExtendedJSON */

@@ -99,2 +100,3 @@ inspect(): string;

Long: typeof Long;
UUID: typeof UUID;
Map: MapConstructor;

@@ -468,2 +470,3 @@ MaxKey: typeof MaxKey;

declare const kId: unique symbol;
declare const kId_2: unique symbol;
/**

@@ -985,6 +988,62 @@ * A class representing a 64-bit integer

export declare type TimestampOverrides = '_bsontype' | 'toExtendedJSON' | 'fromExtendedJSON' | 'inspect';
/**
* A class representation of the BSON UUID type.
* @public
*/
export declare class UUID {
_bsontype: 'UUID';
static cacheHexString: boolean;
/* Excluded from this release type: [kId] */
/* Excluded from this release type: __id */
/**
* Create an UUID type
*
* @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
*/
constructor(input?: string | Buffer | UUID);
/*
* The UUID bytes
* @readonly
*/
id: Buffer;
/**
* Generate a 16 byte uuid v4 buffer used in UUIDs
*/
/**
* Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
* @param includeDashes - should the string exclude dash-separators.
* */
toHexString(includeDashes?: boolean): string;
/* Excluded from this release type: toString */
/* Excluded from this release type: toJSON */
/**
* Compares the equality of this UUID with `otherID`.
*
* @param otherId - UUID instance to compare against.
*/
equals(otherId: string | Buffer | UUID): boolean;
/**
* Creates a Binary instance from the current UUID.
*/
toBinary(): Binary;
/**
* Generates a populated buffer containing a v4 uuid
*/
static generate(): Buffer;
/**
* Checks if a value is a valid bson UUID
* @param input - UUID, string or Buffer to validate.
*/
static isValid(input: string | Buffer | UUID): boolean;
/**
* Creates an UUID from a hex string representation of an UUID.
* @param hexString - 32 or 36 character hex string (dashes excluded/included).
*/
static createFromHexString(hexString: string): UUID;
inspect(): string;
}
/** @public */
export declare interface UUIDExtended {
export declare type UUIDExtended = {
$uuid: string;
}
};
export {};

@@ -5,2 +5,9 @@ # Changelog

## [4.3.0](https://github.com/mongodb/js-bson/compare/v4.2.3...v4.3.0) (2021-04-06)
### Features
* UUID convenience class ([#425](https://github.com/mongodb/js-bson/issues/425)) ([76e1826](https://github.com/mongodb/js-bson/commit/76e1826eed852d4cca9fafabbcf826af1367c9af))
### [4.2.3](https://github.com/mongodb/js-bson/compare/v4.2.2...v4.2.3) (2021-03-02)

@@ -7,0 +14,0 @@

@@ -6,2 +6,3 @@ "use strict";

var ensure_buffer_1 = require("./ensure_buffer");
var uuid_utils_1 = require("./uuid_utils");
var uuid_1 = require("./uuid");

@@ -172,2 +173,9 @@ /**

/** @internal */
Binary.prototype.toUUID = function () {
if (this.sub_type === Binary.SUBTYPE_UUID) {
return new uuid_1.UUID(this.buffer.slice(0, this.position));
}
throw new Error("Binary sub_type \"" + this.sub_type + "\" is not supported for converting to UUID. Only \"" + Binary.SUBTYPE_UUID + "\" is currently supported.");
};
/** @internal */
Binary.fromExtendedJSON = function (doc, options) {

@@ -191,3 +199,3 @@ options = options || {};

type = 4;
data = buffer_1.Buffer.from(uuid_1.parseUUID(doc.$uuid));
data = uuid_utils_1.uuidHexStringToBuffer(doc.$uuid);
}

@@ -194,0 +202,0 @@ if (!data) {

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deserializeStream = exports.calculateObjectSize = exports.deserialize = exports.serializeWithBufferAndIndex = exports.serialize = exports.setInternalBufferSize = exports.ObjectID = exports.Decimal128 = exports.BSONRegExp = exports.MaxKey = exports.MinKey = exports.Int32 = exports.Double = exports.Timestamp = exports.Long = exports.ObjectId = exports.Binary = exports.DBRef = exports.BSONSymbol = exports.Map = exports.Code = exports.LongWithoutOverridesClass = exports.EJSON = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_STRING = exports.BSON_DATA_REGEXP = exports.BSON_DATA_OID = exports.BSON_DATA_OBJECT = exports.BSON_DATA_NUMBER = exports.BSON_DATA_NULL = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_LONG = exports.BSON_DATA_INT = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_DATE = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_CODE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = void 0;
exports.ObjectID = exports.Decimal128 = exports.BSONRegExp = exports.MaxKey = exports.MinKey = exports.Int32 = exports.Double = exports.Timestamp = exports.Long = exports.UUID = exports.ObjectId = exports.Binary = exports.DBRef = exports.BSONSymbol = exports.Map = exports.Code = exports.LongWithoutOverridesClass = exports.EJSON = exports.BSON_INT64_MIN = exports.BSON_INT64_MAX = exports.BSON_INT32_MIN = exports.BSON_INT32_MAX = exports.BSON_DATA_UNDEFINED = exports.BSON_DATA_TIMESTAMP = exports.BSON_DATA_SYMBOL = exports.BSON_DATA_STRING = exports.BSON_DATA_REGEXP = exports.BSON_DATA_OID = exports.BSON_DATA_OBJECT = exports.BSON_DATA_NUMBER = exports.BSON_DATA_NULL = exports.BSON_DATA_MIN_KEY = exports.BSON_DATA_MAX_KEY = exports.BSON_DATA_LONG = exports.BSON_DATA_INT = exports.BSON_DATA_DECIMAL128 = exports.BSON_DATA_DBPOINTER = exports.BSON_DATA_DATE = exports.BSON_DATA_CODE_W_SCOPE = exports.BSON_DATA_CODE = exports.BSON_DATA_BOOLEAN = exports.BSON_DATA_BINARY = exports.BSON_DATA_ARRAY = exports.BSON_BINARY_SUBTYPE_UUID_NEW = exports.BSON_BINARY_SUBTYPE_UUID = exports.BSON_BINARY_SUBTYPE_USER_DEFINED = exports.BSON_BINARY_SUBTYPE_MD5 = exports.BSON_BINARY_SUBTYPE_FUNCTION = exports.BSON_BINARY_SUBTYPE_DEFAULT = exports.BSON_BINARY_SUBTYPE_BYTE_ARRAY = void 0;
exports.deserializeStream = exports.calculateObjectSize = exports.deserialize = exports.serializeWithBufferAndIndex = exports.serialize = exports.setInternalBufferSize = void 0;
var buffer_1 = require("buffer");

@@ -40,2 +41,4 @@ var binary_1 = require("./binary");

Object.defineProperty(exports, "Timestamp", { enumerable: true, get: function () { return timestamp_1.Timestamp; } });
var uuid_1 = require("./uuid");
Object.defineProperty(exports, "UUID", { enumerable: true, get: function () { return uuid_1.UUID; } });
var constants_1 = require("./constants");

@@ -224,2 +227,3 @@ Object.defineProperty(exports, "BSON_BINARY_SUBTYPE_BYTE_ARRAY", { enumerable: true, get: function () { return constants_1.BSON_BINARY_SUBTYPE_BYTE_ARRAY; } });

Long: long_1.Long,
UUID: uuid_1.UUID,
Map: map_1.Map,

@@ -226,0 +230,0 @@ MaxKey: max_key_1.MaxKey,

@@ -191,3 +191,3 @@ "use strict";

otherId.length === 12 &&
this.id instanceof buffer_1.Buffer) {
buffer_1.Buffer.isBuffer(this.id)) {
return otherId === this.id.toString('binary');

@@ -260,3 +260,3 @@ }

}
if (id instanceof buffer_1.Buffer && id.length === 12) {
if (buffer_1.Buffer.isBuffer(id) && id.length === 12) {
return true;

@@ -263,0 +263,0 @@ }

"use strict";
var __spreadArrays = (this && this.__spreadArrays) || function () {
for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
for (var r = Array(s), k = 0, i = 0; i < il; i++)
for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
r[k] = a[j];
return r;
};
Object.defineProperty(exports, "__esModule", { value: true });

@@ -20,3 +13,8 @@ exports.deprecate = exports.isObjectLike = exports.isDate = exports.isBuffer = exports.haveBuffer = exports.isBigUInt64Array = exports.isBigInt64Array = exports.isUint8Array = exports.randomBytes = exports.normalizedFunctionString = void 0;

exports.normalizedFunctionString = normalizedFunctionString;
function insecureRandomBytes(size) {
var isReactNative = typeof global.navigator === 'object' && global.navigator.product === 'ReactNative';
var insecureWarning = isReactNative
? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'
: 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.';
var insecureRandomBytes = function insecureRandomBytes(size) {
console.warn(insecureWarning);
var result = buffer_1.Buffer.alloc(size);

@@ -26,11 +24,19 @@ for (var i = 0; i < size; ++i)

return result;
}
exports.randomBytes = insecureRandomBytes;
if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
exports.randomBytes = function (size) { return window.crypto.getRandomValues(buffer_1.Buffer.alloc(size)); };
}
else {
};
var detectRandomBytes = function () {
if (typeof window !== 'undefined') {
// browser crypto implementation(s)
var target_1 = window.crypto || window.msCrypto; // allow for IE11
if (target_1 && target_1.getRandomValues) {
return function (size) { return target_1.getRandomValues(buffer_1.Buffer.alloc(size)); };
}
}
if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) {
// allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global
return function (size) { return global.crypto.getRandomValues(buffer_1.Buffer.alloc(size)); };
}
var requiredRandomBytes;
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
exports.randomBytes = require('crypto').randomBytes;
requiredRandomBytes = require('crypto').randomBytes;
}

@@ -41,6 +47,5 @@ catch (e) {

// NOTE: in transpiled cases the above require might return null/undefined
if (exports.randomBytes == null) {
exports.randomBytes = insecureRandomBytes;
}
}
return requiredRandomBytes || insecureRandomBytes;
};
exports.randomBytes = detectRandomBytes();
function isUint8Array(value) {

@@ -98,3 +103,3 @@ return Object.prototype.toString.call(value) === '[object Uint8Array]';

}
return fn.apply.apply(fn, __spreadArrays([this], args));
return fn.apply(this, args);
}

@@ -101,0 +106,0 @@ return deprecated;

@@ -10,2 +10,4 @@ "use strict";

return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);

@@ -12,0 +14,0 @@ function __() { this.constructor = d; }

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseUUID = void 0;
exports.UUID = void 0;
var buffer_1 = require("buffer");
var ensure_buffer_1 = require("./ensure_buffer");
var binary_1 = require("./binary");
var uuid_utils_1 = require("./uuid_utils");
var utils_1 = require("./parser/utils");
var BYTE_LENGTH = 16;
var kId = Symbol('id');
/**
* UUID regular expression pattern copied from `uuid` npm module.
* @see https://github.com/uuidjs/uuid/blob/master/src/regex.js
* A class representation of the BSON UUID type.
* @public
*/
var UUID_RX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
/**
* Parser function copied from `uuid` npm module.
* @see https://github.com/uuidjs/uuid/blob/master/src/parse.js
* @internal
*/
function parseUUID(uuid) {
if (typeof uuid !== 'string') {
throw new TypeError('Invalid type for UUID, expected string but got ' + typeof uuid);
var UUID = /** @class */ (function () {
/**
* Create an UUID type
*
* @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
*/
function UUID(input) {
if (typeof input === 'undefined') {
// The most common use case (blank id, new UUID() instance)
this.id = UUID.generate();
}
else if (input instanceof UUID) {
this[kId] = buffer_1.Buffer.from(input.id);
this.__id = input.__id;
}
else if ((buffer_1.Buffer.isBuffer(input) || ArrayBuffer.isView(input)) &&
input.byteLength === BYTE_LENGTH) {
this.id = ensure_buffer_1.ensureBuffer(input);
}
else if (typeof input === 'string') {
this.id = uuid_utils_1.uuidHexStringToBuffer(input);
}
else {
throw new TypeError('Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).');
}
}
if (!UUID_RX.test(uuid)) {
throw new TypeError('Invalid format for UUID: ' + uuid);
}
var v;
var arr = new Uint8Array(16);
// Parse ########-....-....-....-............
arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
arr[1] = (v >>> 16) & 0xff;
arr[2] = (v >>> 8) & 0xff;
arr[3] = v & 0xff;
// Parse ........-####-....-....-............
arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
arr[5] = v & 0xff;
// Parse ........-....-####-....-............
arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
arr[7] = v & 0xff;
// Parse ........-....-....-####-............
arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
arr[9] = v & 0xff;
// Parse ........-....-....-....-############
// (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
arr[10] = ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff;
arr[11] = (v / 0x100000000) & 0xff;
arr[12] = (v >>> 24) & 0xff;
arr[13] = (v >>> 16) & 0xff;
arr[14] = (v >>> 8) & 0xff;
arr[15] = v & 0xff;
return arr;
}
exports.parseUUID = parseUUID;
Object.defineProperty(UUID.prototype, "id", {
/**
* The UUID bytes
* @readonly
*/
get: function () {
return this[kId];
},
set: function (value) {
this[kId] = value;
if (UUID.cacheHexString) {
this.__id = uuid_utils_1.bufferToUuidHexString(value);
}
},
enumerable: false,
configurable: true
});
/**
* Generate a 16 byte uuid v4 buffer used in UUIDs
*/
/**
* Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
* @param includeDashes - should the string exclude dash-separators.
* */
UUID.prototype.toHexString = function (includeDashes) {
if (includeDashes === void 0) { includeDashes = true; }
if (UUID.cacheHexString && this.__id) {
return this.__id;
}
var uuidHexString = uuid_utils_1.bufferToUuidHexString(this.id, includeDashes);
if (UUID.cacheHexString) {
this.__id = uuidHexString;
}
return uuidHexString;
};
/**
* Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
* @internal
*/
UUID.prototype.toString = function (encoding) {
return encoding ? this.id.toString(encoding) : this.toHexString();
};
/**
* Converts the id into its JSON string representation. A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
* @internal
*/
UUID.prototype.toJSON = function () {
return this.toHexString();
};
/**
* Compares the equality of this UUID with `otherID`.
*
* @param otherId - UUID instance to compare against.
*/
UUID.prototype.equals = function (otherId) {
if (!otherId) {
return false;
}
if (otherId instanceof UUID) {
return otherId.id.equals(this.id);
}
try {
return new UUID(otherId).id.equals(this.id);
}
catch (_a) {
return false;
}
};
/**
* Creates a Binary instance from the current UUID.
*/
UUID.prototype.toBinary = function () {
return new binary_1.Binary(this.id, binary_1.Binary.SUBTYPE_UUID);
};
/**
* Generates a populated buffer containing a v4 uuid
*/
UUID.generate = function () {
var bytes = utils_1.randomBytes(BYTE_LENGTH);
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
// Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
return buffer_1.Buffer.from(bytes);
};
/**
* Checks if a value is a valid bson UUID
* @param input - UUID, string or Buffer to validate.
*/
UUID.isValid = function (input) {
if (!input) {
return false;
}
if (input instanceof UUID) {
return true;
}
if (typeof input === 'string') {
return uuid_utils_1.uuidValidateString(input);
}
if (buffer_1.Buffer.isBuffer(input)) {
// check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3)
if (input.length !== BYTE_LENGTH) {
return false;
}
try {
// get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx
// check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx
return parseInt(input[6].toString(16)[0], 10) === binary_1.Binary.SUBTYPE_UUID;
}
catch (_a) {
return false;
}
}
return false;
};
/**
* Creates an UUID from a hex string representation of an UUID.
* @param hexString - 32 or 36 character hex string (dashes excluded/included).
*/
UUID.createFromHexString = function (hexString) {
var buffer = uuid_utils_1.uuidHexStringToBuffer(hexString);
return new UUID(buffer);
};
/**
* Converts to a string representation of this Id.
*
* @returns return the 36 character hex string representation.
* @internal
*/
UUID.prototype[Symbol.for('nodejs.util.inspect.custom')] = function () {
return this.inspect();
};
UUID.prototype.inspect = function () {
return "new UUID(\"" + this.toHexString() + "\")";
};
return UUID;
}());
exports.UUID = UUID;
Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' });
//# sourceMappingURL=uuid.js.map

@@ -18,3 +18,3 @@ {

"types": "bson.d.ts",
"version": "4.2.3",
"version": "4.3.0",
"author": "Christian Amor Kvalheim <christkv@gmail.com>",

@@ -67,3 +67,4 @@ "license": "Apache-2.0",

"typescript": "^4.0.2",
"typescript-cached-transpile": "0.0.6"
"typescript-cached-transpile": "0.0.6",
"uuid": "^8.3.2"
},

@@ -70,0 +71,0 @@ "config": {

import { Buffer } from 'buffer';
import { ensureBuffer } from './ensure_buffer';
import { uuidHexStringToBuffer } from './uuid_utils';
import { UUID, UUIDExtended } from './uuid';
import type { EJSONOptions } from './extended_json';
import { parseUUID, UUIDExtended } from './uuid';

@@ -234,2 +235,13 @@ /** @public */

/** @internal */
toUUID(): UUID {
if (this.sub_type === Binary.SUBTYPE_UUID) {
return new UUID(this.buffer.slice(0, this.position));
}
throw new Error(
`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`
);
}
/** @internal */
static fromExtendedJSON(

@@ -254,3 +266,3 @@ doc: BinaryExtendedLegacy | BinaryExtended | UUIDExtended,

type = 4;
data = Buffer.from(parseUUID(doc.$uuid));
data = uuidHexStringToBuffer(doc.$uuid);
}

@@ -257,0 +269,0 @@ if (!data) {

@@ -22,2 +22,3 @@ import { Buffer } from 'buffer';

import { Timestamp } from './timestamp';
import { UUID } from './uuid';
export { BinaryExtended, BinaryExtendedLegacy, BinarySequence } from './binary';

@@ -85,2 +86,3 @@ export { CodeExtended } from './code';

ObjectId,
UUID,
Long,

@@ -312,2 +314,3 @@ Timestamp,

Long,
UUID,
Map,

@@ -314,0 +317,0 @@ MaxKey,

@@ -232,3 +232,3 @@ import { Buffer } from 'buffer';

otherId.length === 12 &&
this.id instanceof Buffer
Buffer.isBuffer(this.id)
) {

@@ -319,3 +319,3 @@ return otherId === this.id.toString('binary');

if (id instanceof Buffer && id.length === 12) {
if (Buffer.isBuffer(id) && id.length === 12) {
return true;

@@ -322,0 +322,0 @@ }

import { Buffer } from 'buffer';
type RandomBytesFunction = (size: number) => Uint8Array;
/**

@@ -11,7 +13,16 @@ * Normalizes our expected stringified form of a function across versions of node

function insecureRandomBytes(size: number): Uint8Array {
const isReactNative =
typeof global.navigator === 'object' && global.navigator.product === 'ReactNative';
const insecureWarning = isReactNative
? 'BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.'
: 'BSON: No cryptographic implementation for random bytes present, falling back to a less secure implementation.';
const insecureRandomBytes: RandomBytesFunction = function insecureRandomBytes(size: number) {
console.warn(insecureWarning);
const result = Buffer.alloc(size);
for (let i = 0; i < size; ++i) result[i] = Math.floor(Math.random() * 256);
return result;
}
};

@@ -26,9 +37,20 @@ /* We do not want to have to include DOM types just for this check */

export let randomBytes = insecureRandomBytes;
if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
randomBytes = size => window.crypto.getRandomValues(Buffer.alloc(size));
} else {
const detectRandomBytes = (): RandomBytesFunction => {
if (typeof window !== 'undefined') {
// browser crypto implementation(s)
const target = window.crypto || window.msCrypto; // allow for IE11
if (target && target.getRandomValues) {
return size => target.getRandomValues(Buffer.alloc(size));
}
}
if (typeof global !== 'undefined' && global.crypto && global.crypto.getRandomValues) {
// allow for RN packages such as https://www.npmjs.com/package/react-native-get-random-values to populate global
return size => global.crypto.getRandomValues(Buffer.alloc(size));
}
let requiredRandomBytes: RandomBytesFunction | null | undefined;
try {
// eslint-disable-next-line @typescript-eslint/no-var-requires
randomBytes = require('crypto').randomBytes;
requiredRandomBytes = require('crypto').randomBytes;
} catch (e) {

@@ -39,7 +61,8 @@ // keep the fallback

// NOTE: in transpiled cases the above require might return null/undefined
if (randomBytes == null) {
randomBytes = insecureRandomBytes;
}
}
return requiredRandomBytes || insecureRandomBytes;
};
export const randomBytes = detectRandomBytes();
export function isUint8Array(value: unknown): value is Uint8Array {

@@ -93,5 +116,5 @@ return Object.prototype.toString.call(value) === '[object Uint8Array]';

}
return fn.apply(this, ...args);
return fn.apply(this, args);
}
return (deprecated as unknown) as T;
}

@@ -1,57 +0,212 @@

/**
* UUID regular expression pattern copied from `uuid` npm module.
* @see https://github.com/uuidjs/uuid/blob/master/src/regex.js
*/
const UUID_RX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
import { Buffer } from 'buffer';
import { ensureBuffer } from './ensure_buffer';
import { Binary } from './binary';
import { bufferToUuidHexString, uuidHexStringToBuffer, uuidValidateString } from './uuid_utils';
import { randomBytes } from './parser/utils';
/** @public */
export interface UUIDExtended {
export type UUIDExtended = {
$uuid: string;
}
};
const BYTE_LENGTH = 16;
const kId = Symbol('id');
/**
* Parser function copied from `uuid` npm module.
* @see https://github.com/uuidjs/uuid/blob/master/src/parse.js
* @internal
* A class representation of the BSON UUID type.
* @public
*/
export function parseUUID(uuid: string): Uint8Array {
if (typeof uuid !== 'string') {
throw new TypeError('Invalid type for UUID, expected string but got ' + typeof uuid);
export class UUID {
// This property is not meant for direct serialization, but simply an indication that this type originates from this package.
_bsontype!: 'UUID';
static cacheHexString: boolean;
/** UUID Bytes @internal */
private [kId]: Buffer;
/** UUID hexString cache @internal */
private __id?: string;
/**
* Create an UUID type
*
* @param input - Can be a 32 or 36 character hex string (dashes excluded/included) or a 16 byte binary Buffer.
*/
constructor(input?: string | Buffer | UUID) {
if (typeof input === 'undefined') {
// The most common use case (blank id, new UUID() instance)
this.id = UUID.generate();
} else if (input instanceof UUID) {
this[kId] = Buffer.from(input.id);
this.__id = input.__id;
} else if (
(Buffer.isBuffer(input) || ArrayBuffer.isView(input)) &&
input.byteLength === BYTE_LENGTH
) {
this.id = ensureBuffer(input);
} else if (typeof input === 'string') {
this.id = uuidHexStringToBuffer(input);
} else {
throw new TypeError(
'Argument passed in UUID constructor must be a UUID, a 16 byte Buffer or a 32/36 character hex string (dashes excluded/included, format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx).'
);
}
}
if (!UUID_RX.test(uuid)) {
throw new TypeError('Invalid format for UUID: ' + uuid);
/**
* The UUID bytes
* @readonly
*/
get id(): Buffer {
return this[kId];
}
let v;
const arr = new Uint8Array(16);
set id(value: Buffer) {
this[kId] = value;
// Parse ########-....-....-....-............
arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
arr[1] = (v >>> 16) & 0xff;
arr[2] = (v >>> 8) & 0xff;
arr[3] = v & 0xff;
if (UUID.cacheHexString) {
this.__id = bufferToUuidHexString(value);
}
}
// Parse ........-####-....-....-............
arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
arr[5] = v & 0xff;
/**
* Generate a 16 byte uuid v4 buffer used in UUIDs
*/
// Parse ........-....-####-....-............
arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
arr[7] = v & 0xff;
/**
* Returns the UUID id as a 32 or 36 character hex string representation, excluding/including dashes (defaults to 36 character dash separated)
* @param includeDashes - should the string exclude dash-separators.
* */
toHexString(includeDashes = true): string {
if (UUID.cacheHexString && this.__id) {
return this.__id;
}
// Parse ........-....-....-####-............
arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
arr[9] = v & 0xff;
const uuidHexString = bufferToUuidHexString(this.id, includeDashes);
// Parse ........-....-....-....-############
// (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
arr[10] = ((v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000) & 0xff;
arr[11] = (v / 0x100000000) & 0xff;
arr[12] = (v >>> 24) & 0xff;
arr[13] = (v >>> 16) & 0xff;
arr[14] = (v >>> 8) & 0xff;
arr[15] = v & 0xff;
if (UUID.cacheHexString) {
this.__id = uuidHexString;
}
return arr;
return uuidHexString;
}
/**
* Converts the id into a 36 character (dashes included) hex string, unless a encoding is specified.
* @internal
*/
toString(encoding?: string): string {
return encoding ? this.id.toString(encoding) : this.toHexString();
}
/**
* Converts the id into its JSON string representation. A 36 character (dashes included) hex string in the format: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx
* @internal
*/
toJSON(): string {
return this.toHexString();
}
/**
* Compares the equality of this UUID with `otherID`.
*
* @param otherId - UUID instance to compare against.
*/
equals(otherId: string | Buffer | UUID): boolean {
if (!otherId) {
return false;
}
if (otherId instanceof UUID) {
return otherId.id.equals(this.id);
}
try {
return new UUID(otherId).id.equals(this.id);
} catch {
return false;
}
}
/**
* Creates a Binary instance from the current UUID.
*/
toBinary(): Binary {
return new Binary(this.id, Binary.SUBTYPE_UUID);
}
/**
* Generates a populated buffer containing a v4 uuid
*/
static generate(): Buffer {
const bytes = randomBytes(BYTE_LENGTH);
// Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
// Kindly borrowed from https://github.com/uuidjs/uuid/blob/master/src/v4.js
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
return Buffer.from(bytes);
}
/**
* Checks if a value is a valid bson UUID
* @param input - UUID, string or Buffer to validate.
*/
static isValid(input: string | Buffer | UUID): boolean {
if (!input) {
return false;
}
if (input instanceof UUID) {
return true;
}
if (typeof input === 'string') {
return uuidValidateString(input);
}
if (Buffer.isBuffer(input)) {
// check for length & uuid version (https://tools.ietf.org/html/rfc4122#section-4.1.3)
if (input.length !== BYTE_LENGTH) {
return false;
}
try {
// get this byte as hex: xxxxxxxx-xxxx-XXxx-xxxx-xxxxxxxxxxxx
// check first part as uuid version: xxxxxxxx-xxxx-Xxxx-xxxx-xxxxxxxxxxxx
return parseInt(input[6].toString(16)[0], 10) === Binary.SUBTYPE_UUID;
} catch {
return false;
}
}
return false;
}
/**
* Creates an UUID from a hex string representation of an UUID.
* @param hexString - 32 or 36 character hex string (dashes excluded/included).
*/
static createFromHexString(hexString: string): UUID {
const buffer = uuidHexStringToBuffer(hexString);
return new UUID(buffer);
}
/**
* Converts to a string representation of this Id.
*
* @returns return the 36 character hex string representation.
* @internal
*/
[Symbol.for('nodejs.util.inspect.custom')](): string {
return this.inspect();
}
inspect(): string {
return `new UUID("${this.toHexString()}")`;
}
}
Object.defineProperty(UUID.prototype, '_bsontype', { value: 'UUID' });

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc