Socket
Socket
Sign inDemoInstall

bson

Package Overview
Dependencies
Maintainers
2
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 0.4.23 to 0.5.0

HISTORY.md

8

lib/bson/bson.js

@@ -1,2 +0,2 @@

// "use strict"
"use strict"

@@ -13,2 +13,3 @@ var writeIEEE754 = require('./float_parser').writeIEEE754,

Code = require('./code').Code,
Decimal128 = require('./decimal128').Decimal128,
MinKey = require('./min_key').MinKey,

@@ -65,3 +66,3 @@ MaxKey = require('./max_key').MaxKey,

* @param {Boolean} serializeFunctions serialize the javascript functions **(default:false)**.
* @return {Number} returns the new write index in the Buffer.
* @return {Number} returns the index pointing to the last written byte in the buffer.
* @api public

@@ -74,3 +75,3 @@ */

// Return the index
return startIndex + serializationIndex - 1;
return serializationIndex - 1;
}

@@ -327,1 +328,2 @@

module.exports.BSONRegExp = BSONRegExp;
module.exports.Decimal128 = Decimal128;

@@ -13,3 +13,3 @@ /**

this.code = code;
this.scope = scope == null ? {} : scope;
this.scope = scope;
};

@@ -25,2 +25,2 @@

module.exports = Code;
module.exports.Code = Code;
module.exports.Code = Code;

@@ -18,2 +18,3 @@ try {

, './symbol'
, './decimal128'
, './timestamp'

@@ -42,2 +43,3 @@ , './long'].forEach(function (path) {

, './symbol'
, './decimal128'
, './timestamp'

@@ -70,2 +72,3 @@ , './long'

, './symbol'
, './decimal128'
, './timestamp'

@@ -72,0 +75,0 @@ , './long'

@@ -29,7 +29,8 @@ /**

var ObjectID = function ObjectID(id) {
// Duck-typing to support ObjectId from different npm packages
if(id instanceof ObjectID) return id;
if(!(this instanceof ObjectID)) return new ObjectID(id);
// Duck-typing to support ObjectId from different npm packages
if((id instanceof ObjectID) || (id && id.toHexString)) return id;
this._bsontype = 'ObjectID';
var __id = null;

@@ -49,2 +50,5 @@ var valid = ObjectID.isValid(id);

this.id = id;
} else if(id != null && id.toHexString) {
// Duck-typing to support ObjectId from different npm packages
return id;
}

@@ -75,2 +79,8 @@

if(this.id instanceof _Buffer) {
hexString = convertToHex(this.id);
if(ObjectID.cacheHexString) this.__id = hexString;
return hexString;
}
for (var i = 0; i < this.id.length; i++) {

@@ -107,20 +117,41 @@ hexString += hexTable[this.id.charCodeAt(i)];

/**
* Generate a 12 byte id string used in ObjectID's
* Generate a 12 byte id buffer used in ObjectID's
*
* @method
* @param {number} [time] optional parameter allowing to pass in a second based timestamp.
* @return {string} return the 12 byte id binary string.
* @return {Buffer} return the 12 byte id buffer string.
*/
ObjectID.prototype.generate = function(time) {
if ('number' != typeof time) {
time = parseInt(Date.now()/1000,10);
time = ~~(Date.now()/1000);
}
// // Encode low bits
// buffer[index++] = lowBits & 0xff;
// buffer[index++] = (lowBits >> 8) & 0xff;
// buffer[index++] = (lowBits >> 16) & 0xff;
// buffer[index++] = (lowBits >> 24) & 0xff;
var time4Bytes = BinaryParser.encodeInt(time, 32, true, true);
/* for time-based ObjectID the bytes following the time will be zeroed */
var machine3Bytes = BinaryParser.encodeInt(MACHINE_ID, 24, false);
var pid2Bytes = BinaryParser.fromShort((typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF);
var index3Bytes = BinaryParser.encodeInt(this.get_inc(), 24, false, true);
return time4Bytes + machine3Bytes + pid2Bytes + index3Bytes;
// Use pid
var pid = (typeof process === 'undefined' ? Math.floor(Math.random() * 100000) : process.pid) % 0xFFFF;
var inc = this.get_inc();
// Buffer used
var buffer = new Buffer(12);
// Encode time
buffer[0] = time & 0xff;
buffer[1] = (time >> 8) & 0xff;
buffer[2] = (time >> 16) & 0xff;
buffer[3] = (time >> 24) & 0xff;
// Encode machine
buffer[4] = MACHINE_ID & 0xff;
buffer[5] = (MACHINE_ID >> 8) & 0xff;
buffer[6] = (MACHINE_ID >> 16) & 0xff;
// Encode pid
buffer[7] = pid & 0xff;
buffer[8] = (pid >> 8) & 0xff;
// Encode index
buffer[9] = inc & 0xff;
buffer[10] = (inc >> 8) & 0xff;
buffer[11] = (inc >> 16) & 0xff;
// Return the buffer
return buffer;
};

@@ -163,14 +194,18 @@

*/
ObjectID.prototype.equals = function equals (otherID) {
ObjectID.prototype.equals = function equals (otherId) {
var id;
if(otherID != null && (otherID instanceof ObjectID || otherID.toHexString)) {
id = otherID.id;
} else if(typeof otherID == 'string' && ObjectID.isValid(otherID)) {
id = ObjectID.createFromHexString(otherID).id;
if(otherId instanceof ObjectID) {
return this.toString() == otherId.toString();
} else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12 && this.id instanceof _Buffer) {
return otherId === this.id.toString('binary');
} else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 24) {
return otherId === this.toHexString();
} else if(typeof otherId == 'string' && ObjectID.isValid(otherId) && otherId.length == 12) {
return otherId === this.id;
} else if(otherId != null && (otherId instanceof ObjectID || otherId.toHexString)) {
return otherId.toHexString() === this.toHexString();
} else {
return false;
}
return this.id === id;
}

@@ -186,3 +221,4 @@

var timestamp = new Date();
timestamp.setTime(Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true)) * 1000);
var time = this.id[0] | this.id[1] << 8 | this.id[2] << 16 | this.id[3] << 24;
timestamp.setTime(Math.floor(time) * 1000);
return timestamp;

@@ -194,3 +230,3 @@ }

*/
ObjectID.index = parseInt(Math.random() * 0xFFFFFF, 10);
ObjectID.index = ~~(Math.random() * 0xFFFFFF);

@@ -217,2 +253,14 @@ /**

// Lookup tables
var encodeLookup = '0123456789abcdef'.split('')
var decodeLookup = []
var i = 0
while (i < 10) decodeLookup[0x30 + i] = i++
while (i < 16) decodeLookup[0x61 - 10 + i] = i++
var _Buffer = Buffer;
var convertToHex = function(bytes) {
return bytes.toString('hex');
}
/**

@@ -225,24 +273,24 @@ * Creates an ObjectID from a hex string representation of an ObjectID.

*/
ObjectID.createFromHexString = function createFromHexString (hexString) {
ObjectID.createFromHexString = function createFromHexString (string) {
// Throw an error if it's not a valid setup
if(typeof hexString === 'undefined' || hexString != null && hexString.length != 24)
if(typeof string === 'undefined' || string != null && string.length != 24)
throw new Error("Argument passed in must be a single String of 12 bytes or a string of 24 hex characters");
var len = hexString.length;
var length = string.length;
if(len > 12*2) {
if(length > 12*2) {
throw new Error('Id cannot be longer than 12 bytes');
}
var result = ''
, string
, number;
// Calculate lengths
var sizeof = length >> 1;
var array = new _Buffer(sizeof);
var n = 0;
var i = 0;
for (var index = 0; index < len; index += 2) {
string = hexString.substr(index, 2);
number = parseInt(string, 16);
result += BinaryParser.fromByte(number);
while (i < length) {
array[n++] = decodeLookup[string.charCodeAt(i++)] << 4 | decodeLookup[string.charCodeAt(i++)]
}
return new ObjectID(result, hexString);
return new ObjectID(array);
};

@@ -259,10 +307,18 @@

if(typeof id == 'number')
if(typeof id == 'number') {
return true;
}
if(typeof id == 'string') {
return id.length == 12 || (id.length == 24 && checkForHexRegExp.test(id));
}
if(id instanceof ObjectID) {
return true;
}
if(id instanceof _Buffer) {
return true;
}
// Duck-Typing detection of ObjectId like objects

@@ -272,2 +328,3 @@ if(id.toHexString) {

}
return false;

@@ -282,9 +339,10 @@ };

, get: function () {
return Math.floor(BinaryParser.decodeInt(this.id.substring(0,4), 32, true, true));
return this.id[0] | this.id[1] << 8 | this.id[2] << 16 | this.id[3] << 24;
}
, set: function (value) {
var value = BinaryParser.encodeInt(value, 32, true, true);
this.id = value + this.id.substr(4);
// delete this.__id;
this.toHexString();
// Encode time into first 4 bytes
this.id[0] = value & 0xff;
this.id[1] = (value >> 8) & 0xff;
this.id[2] = (value >> 16) & 0xff;
this.id[3] = (value >> 24) & 0xff;
}

@@ -291,0 +349,0 @@ });

@@ -12,2 +12,3 @@ "use strict"

, Code = require('../code').Code
, Decimal128 = require('../decimal128')
, MinKey = require('../min_key').MinKey

@@ -85,2 +86,4 @@ , MaxKey = require('../max_key').MaxKey

return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (8 + 1);
} else if(value instanceof Decimal128 || value['_bsontype'] == 'Decimal128') {
return (name != null ? (Buffer.byteLength(name, 'utf8') + 1) : 0) + (16 + 1);
} else if(value instanceof Code || value['_bsontype'] == 'Code') {

@@ -143,156 +146,2 @@ // Calculate size depending on the availability of a scope

/**
* Contains the function cache if we have that enable to allow for avoiding the eval step on each deserialization, comparison is by md5
*
* @ignore
* @api private
*/
var functionCache = BSON.functionCache = {};
/**
* Number BSON Type
*
* @classconstant BSON_DATA_NUMBER
**/
BSON.BSON_DATA_NUMBER = 1;
/**
* String BSON Type
*
* @classconstant BSON_DATA_STRING
**/
BSON.BSON_DATA_STRING = 2;
/**
* Object BSON Type
*
* @classconstant BSON_DATA_OBJECT
**/
BSON.BSON_DATA_OBJECT = 3;
/**
* Array BSON Type
*
* @classconstant BSON_DATA_ARRAY
**/
BSON.BSON_DATA_ARRAY = 4;
/**
* Binary BSON Type
*
* @classconstant BSON_DATA_BINARY
**/
BSON.BSON_DATA_BINARY = 5;
/**
* ObjectID BSON Type
*
* @classconstant BSON_DATA_OID
**/
BSON.BSON_DATA_OID = 7;
/**
* Boolean BSON Type
*
* @classconstant BSON_DATA_BOOLEAN
**/
BSON.BSON_DATA_BOOLEAN = 8;
/**
* Date BSON Type
*
* @classconstant BSON_DATA_DATE
**/
BSON.BSON_DATA_DATE = 9;
/**
* null BSON Type
*
* @classconstant BSON_DATA_NULL
**/
BSON.BSON_DATA_NULL = 10;
/**
* RegExp BSON Type
*
* @classconstant BSON_DATA_REGEXP
**/
BSON.BSON_DATA_REGEXP = 11;
/**
* Code BSON Type
*
* @classconstant BSON_DATA_CODE
**/
BSON.BSON_DATA_CODE = 13;
/**
* Symbol BSON Type
*
* @classconstant BSON_DATA_SYMBOL
**/
BSON.BSON_DATA_SYMBOL = 14;
/**
* Code with Scope BSON Type
*
* @classconstant BSON_DATA_CODE_W_SCOPE
**/
BSON.BSON_DATA_CODE_W_SCOPE = 15;
/**
* 32 bit Integer BSON Type
*
* @classconstant BSON_DATA_INT
**/
BSON.BSON_DATA_INT = 16;
/**
* Timestamp BSON Type
*
* @classconstant BSON_DATA_TIMESTAMP
**/
BSON.BSON_DATA_TIMESTAMP = 17;
/**
* Long BSON Type
*
* @classconstant BSON_DATA_LONG
**/
BSON.BSON_DATA_LONG = 18;
/**
* MinKey BSON Type
*
* @classconstant BSON_DATA_MIN_KEY
**/
BSON.BSON_DATA_MIN_KEY = 0xff;
/**
* MaxKey BSON Type
*
* @classconstant BSON_DATA_MAX_KEY
**/
BSON.BSON_DATA_MAX_KEY = 0x7f;
/**
* Binary Default Type
*
* @classconstant BSON_BINARY_SUBTYPE_DEFAULT
**/
BSON.BSON_BINARY_SUBTYPE_DEFAULT = 0;
/**
* Binary Function Type
*
* @classconstant BSON_BINARY_SUBTYPE_FUNCTION
**/
BSON.BSON_BINARY_SUBTYPE_FUNCTION = 1;
/**
* Binary Byte Array Type
*
* @classconstant BSON_BINARY_SUBTYPE_BYTE_ARRAY
**/
BSON.BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
/**
* Binary UUID Type
*
* @classconstant BSON_BINARY_SUBTYPE_UUID
**/
BSON.BSON_BINARY_SUBTYPE_UUID = 3;
/**
* Binary MD5 Type
*
* @classconstant BSON_BINARY_SUBTYPE_MD5
**/
BSON.BSON_BINARY_SUBTYPE_MD5 = 4;
/**
* Binary User Defined Type
*
* @classconstant BSON_BINARY_SUBTYPE_USER_DEFINED
**/
BSON.BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
// BSON MAX VALUES

@@ -302,5 +151,2 @@ BSON.BSON_INT32_MAX = 0x7FFFFFFF;

BSON.BSON_INT64_MAX = Math.pow(2, 63) - 1;
BSON.BSON_INT64_MIN = -Math.pow(2, 63);
// JS MAX PRECISE VALUES

@@ -310,6 +156,2 @@ BSON.JS_INT_MAX = 0x20000000000000; // Any integer up to 2^53 can be precisely represented by a double.

// Internal long versions
var JS_INT_MAX_LONG = Long.fromNumber(0x20000000000000); // Any integer up to 2^53 can be precisely represented by a double.
var JS_INT_MIN_LONG = Long.fromNumber(-0x20000000000000); // Any integer down to -2^53 can be precisely represented by a double.
module.exports = calculateObjectSize;

@@ -13,2 +13,3 @@ "use strict"

MaxKey = require('../max_key').MaxKey,
Decimal128 = require('../decimal128'),
DBRef = require('../db_ref').DBRef,

@@ -25,3 +26,3 @@ BSONRegExp = require('../regexp').BSONRegExp,

// Ensure buffer is valid size
if(size < 5 || buffer.length < size) {
if(size < 5 || buffer.length < size || (size + index) < buffer.length) {
throw new Error("corrupt bson message");

@@ -49,2 +50,3 @@ }

var promoteBuffers = options['promoteBuffers'] == null ? false : options['promoteBuffers'];
var startIndex = index;

@@ -62,2 +64,4 @@ // Validate that we have at least 4 bytes of buffer

var object = isArray ? [] : {};
// Used for arrays to skip having to perform utf8 decoding
var arrayIndex = 0;

@@ -69,3 +73,5 @@ // While we have more left data left keep parsing

// If we get a zero it's the last byte, exit
if(elementType == 0) break;
if(elementType == 0) {
break;
}

@@ -81,3 +87,3 @@ // Get the start search index

if(i >= buffer.length) throw new Error("Bad BSON Document: illegal CString")
var name = buffer.toString('utf8', index, i);
var name = isArray ? arrayIndex++ : buffer.toString('utf8', index, i);

@@ -92,4 +98,5 @@ index = i + 1;

} else if(elementType == BSON.BSON_DATA_OID) {
var string = buffer.toString('binary', index, index + 12);
object[name] = new ObjectID(string);
var oid = new Buffer(12);
buffer.copy(oid, 0, index, index + 12);
object[name] = new ObjectID(oid);
index = index + 12;

@@ -106,2 +113,3 @@ } else if(elementType == BSON.BSON_DATA_INT) {

} else if(elementType == BSON.BSON_DATA_BOOLEAN) {
if(buffer[index] != 0 && buffer[index] != 1) throw new Error('illegal boolean type value');
object[name] = buffer[index++] == 1;

@@ -126,2 +134,5 @@ } else if(elementType == BSON.BSON_DATA_OBJECT) {

// Stop index
var stopIndex = index + objectSize;
// All elements of array to be returned as raw bson

@@ -136,4 +147,9 @@ if(fieldsAsRaw && fieldsAsRaw[name]) {

index = index + objectSize;
} else if(elementType == BSON.BSON_DATA_UNDEFINED || elementType == BSON.BSON_DATA_NULL) {
object[name] = null;
if(buffer[index - 1] != 0) throw new Error('invalid array terminator byte');
if(index != stopIndex) throw new Error('corrupted array bson');
} else if(elementType == BSON.BSON_DATA_UNDEFINED) {
object[name] = undefined;
} else if(elementType == BSON.BSON_DATA_NULL) {
object[name] = null;
} else if(elementType == BSON.BSON_DATA_LONG) {

@@ -150,6 +166,25 @@ // Unpack the low and high bits

}
} else if(elementType == BSON.BSON_DATA_DECIMAL128) {
// Buffer to contain the decimal bytes
var bytes = new Buffer(16);
// Copy the next 16 bytes into the bytes buffer
buffer.copy(bytes, 0, index, index + 16);
// Update index
index = index + 16;
// Assign the new Decimal128 value
var decimal128 = new Decimal128(bytes);
// If we have an alternative mapper use that
object[name] = decimal128.toObject ? decimal128.toObject() : decimal128;
} else if(elementType == BSON.BSON_DATA_BINARY) {
var binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
var totalBinarySize = binarySize;
var subType = buffer[index++];
// Decode as raw Buffer object if options specifies it
// Did we have a negative binary size, throw
if(binarySize < 0) throw new Error('Negative binary type element size found');
// Is the length longer than the document
if(binarySize > buffer.length) throw new Error('Binary type size larger than document size');
// Decode as raw Buffer object if options specifies it
if(buffer['slice'] != null) {

@@ -159,3 +194,7 @@ // If we have subtype 2 skip the 4 bytes for the size

binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
if(binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02');
if(binarySize > (totalBinarySize - 4)) throw new Error('Binary type with subtype 0x02 contains to long binary size');
if(binarySize < (totalBinarySize - 4)) throw new Error('Binary type with subtype 0x02 contains to short binary size');
}
if(promoteBuffers) {

@@ -171,3 +210,7 @@ object[name] = buffer.slice(index, index + binarySize);

binarySize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
if(binarySize < 0) throw new Error('Negative binary type element size found for subtype 0x02');
if(binarySize > (totalBinarySize - 4)) throw new Error('Binary type with subtype 0x02 contains to long binary size');
if(binarySize < (totalBinarySize - 4)) throw new Error('Binary type with subtype 0x02 contains to short binary size');
}
// Copy the data

@@ -177,2 +220,3 @@ for(var i = 0; i < binarySize; i++) {

}
if(promoteBuffers) {

@@ -184,2 +228,3 @@ object[name] = _buffer;

}
// Update the index

@@ -289,3 +334,3 @@ index = index + binarySize;

} else {
object[name] = new Code(functionString, {});
object[name] = new Code(functionString);
}

@@ -297,4 +342,13 @@

var totalSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
// Element cannot be shorter than totalSize + stringSize + documentSize + terminator
if(totalSize < (4 + 4 + 4 + 1)) {
throw new Error("code_w_scope total size shorter minimum expected length");
}
// Get the code string size
var stringSize = buffer[index++] | buffer[index++] << 8 | buffer[index++] << 16 | buffer[index++] << 24;
// Check if we have a valid string
if(stringSize <= 0 || stringSize > (buffer.length - index) || buffer[index + stringSize - 1] != 0) throw new Error("bad string length in bson");
// Javascript function

@@ -313,2 +367,12 @@ var functionString = buffer.toString('utf8', index, index + stringSize - 1);

// Check if field length is to short
if(totalSize < (4 + 4 + objectSize + stringSize)) {
throw new Error('code_w_scope total size is to short, truncating scope');
}
// Check if totalSize field is to long
if(totalSize > (4 + 4 + objectSize + stringSize)) {
throw new Error('code_w_scope total size is to long, clips outer document');
}
// If we are evaluating the functions

@@ -331,5 +395,13 @@ if(evalFunctions) {

}
}
} else {
throw new Error("Detected unknown BSON type " + elementType.toString(16) + " for fieldname \"" + name + "\", are you using the latest BSON parser");
}
}
// Check if the deserialization was against a valid array/object
if(size != (index - startIndex)) {
if(isArray) throw new Error('corrupt array bson');
throw new Error('corrupt object bson');
}
// Check if we have a db ref object

@@ -418,3 +490,3 @@ if(object['$id'] != null) object = new DBRef(object['$ref'], object['$id'], object['$db']);

**/
BSON.BSON_DATA_UNDEFINED = 7;
BSON.BSON_DATA_UNDEFINED = 6;
/**

@@ -487,2 +559,8 @@ * ObjectID BSON Type

/**
* Long BSON Type
*
* @classconstant BSON_DATA_DECIMAL128
**/
BSON.BSON_DATA_DECIMAL128 = 19;
/**
* MinKey BSON Type

@@ -489,0 +567,0 @@ *

@@ -15,5 +15,12 @@ "use strict"

MaxKey = require('../max_key').MaxKey,
Decimal128 = require('../decimal128'),
DBRef = require('../db_ref').DBRef,
Binary = require('../binary').Binary;
try {
var _Buffer = Uint8Array;
} catch(e) {
var _Buffer = Buffer;
}
var regexp = /\x00/

@@ -243,3 +250,7 @@

// Write the objectId into the shared buffer
buffer.write(value.id, index, 'binary')
if(typeof value.id == 'string') {
buffer.write(value.id, index, 'binary')
} else {
value.id.copy(buffer, index, 0, 12);
}

@@ -288,2 +299,14 @@ // Ajust index

var serializeDecimal128 = function(buffer, key, value, index) {
buffer[index++] = BSON.BSON_DATA_DECIMAL128;
// Number of written bytes
var numberOfWrittenBytes = buffer.write(key, index, 'utf8');
// Encode the name
index = index + numberOfWrittenBytes;
buffer[index++] = 0;
// Write the data from the value
value.bytes.copy(buffer, index, 0, 16);
return index + 16;
}
var serializeLong = function(buffer, key, value, index) {

@@ -352,3 +375,3 @@ // Write the type

var serializeCode = function(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined) {
if(value.scope != null && Object.keys(value.scope).length > 0) {
if(value.scope && typeof value.scope == 'object') {
// Write the type

@@ -434,2 +457,4 @@ buffer[index++] = BSON.BSON_DATA_CODE_W_SCOPE;

var size = value.position;
// Add the deprecated 02 type 4 bytes of size to total
if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) size = size + 4;
// Write the size of the string to buffer

@@ -445,2 +470,3 @@ buffer[index++] = size & 0xff;

if(value.sub_type == Binary.SUBTYPE_BYTE_ARRAY) {
size = size - 4;
buffer[index++] = size & 0xff;

@@ -558,2 +584,4 @@ buffer[index++] = (size >> 8) & 0xff;

index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
} else if(type == 'object' && value['_bsontype'] == 'Decimal128') {
index = serializeDecimal128(buffer, key, value, index);
} else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') {

@@ -614,6 +642,2 @@ index = serializeLong(buffer, key, value, index);

// console.log("---------------------------------------------------")
// console.dir("key = " + key)
// console.dir("value = " + value)
if(type == 'string') {

@@ -638,2 +662,4 @@ index = serializeString(buffer, key, value, index);

index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
} else if(type == 'object' && value['_bsontype'] == 'Decimal128') {
index = serializeDecimal128(buffer, key, value, index);
} else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') {

@@ -715,2 +741,4 @@ index = serializeLong(buffer, key, value, index);

index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined);
} else if(type == 'object' && value['_bsontype'] == 'Decimal128') {
index = serializeDecimal128(buffer, key, value, index);
} else if(value['_bsontype'] == 'Long' || value['_bsontype'] == 'Timestamp') {

@@ -792,2 +820,8 @@ index = serializeLong(buffer, key, value, index);

/**
* ObjectID BSON Type, deprecated
*
* @classconstant BSON_DATA_UNDEFINED
**/
BSON.BSON_DATA_UNDEFINED = 6;
/**
* ObjectID BSON Type

@@ -859,2 +893,8 @@ *

/**
* Long BSON Type
*
* @classconstant BSON_DATA_DECIMAL128
**/
BSON.BSON_DATA_DECIMAL128 = 19;
/**
* MinKey BSON Type

@@ -871,3 +911,2 @@ *

BSON.BSON_DATA_MAX_KEY = 0x7f;
/**

@@ -874,0 +913,0 @@ * Binary Default Type

@@ -1,27 +0,46 @@

{ "name" : "bson"
, "description" : "A bson parser for node.js and the browser"
, "keywords" : ["mongodb", "bson", "parser"]
, "version" : "0.4.23"
, "author" : "Christian Amor Kvalheim <christkv@gmail.com>"
, "contributors" : []
, "repository" : { "type" : "git"
, "url" : "git://github.com/mongodb/js-bson.git" }
, "bugs" : { "mail" : "node-mongodb-native@googlegroups.com"
, "url" : "https://github.com/mongodb/js-bson/issues" }
, "devDependencies": {
"nodeunit": "0.9.0"
, "gleak": "0.2.3"
, "benchmark": "1.0.0"
, "colors": "1.1.0"
}
, "config": { "native" : false }
, "main": "./lib/bson/index"
, "directories" : { "lib" : "./lib/bson" }
, "engines" : { "node" : ">=0.6.19" }
, "scripts": {
"test" : "nodeunit ./test/node"
{
"name": "bson",
"description": "A bson parser for node.js and the browser",
"keywords": [
"mongodb",
"bson",
"parser"
],
"files": [
"lib",
"browser_build",
"alternate_parsers",
"bower.json",
"tools",
"deserializer_bak.js"
],
"version": "0.5.0",
"author": "Christian Amor Kvalheim <christkv@gmail.com>",
"contributors": [],
"repository": "mongodb/js-bson",
"bugs": {
"mail": "node-mongodb-native@googlegroups.com",
"url": "https://github.com/mongodb/js-bson/issues"
},
"devDependencies": {
"benchmark": "1.0.0",
"colors": "1.1.0",
"gleak": "0.2.3",
"nodeunit": "0.9.0"
},
"config": {
"native": false
},
"main": "./lib/bson/index",
"directories": {
"lib": "./lib/bson"
},
"engines": {
"node": ">=0.6.19"
},
"scripts": {
"test": "nodeunit ./test/node"
},
"browser": "lib/bson/bson.js",
"license": "Apache-2.0"
}
, "browser": "lib/bson/bson.js"
, "license": "Apache-2.0"
}

@@ -1,32 +0,25 @@

Javascript + C++ BSON parser
============================
# BSON parser
This BSON parser is primarily meant to be used with the `mongodb` node.js driver.
However, wonderful tools such as `onejs` can package up a BSON parser that will work in the browser.
The current build is located in the `browser_build/bson.js` file.
If you don't yet know what BSON actually is, read [the spec](http://bsonspec.org).
This package can be used to serialize JSON documents into the BSON format or the other way around. If you want to use it within the browser, give [browserify](https://github.com/substack/node-browserify) a try (it will help you add this package to your bundle). The current build is located in the `browser_build/bson.js` file.
A simple example of how to use BSON in the browser:
```html
<html>
<head>
<script src="https://raw.github.com/mongodb/js-bson/master/browser_build/bson.js">
</script>
</head>
<body onload="start();">
<script src="./browser_build/bson.js"></script>
<script>
function start() {
var BSON = bson().BSON;
var Long = bson().Long;
var BSON = bson().BSON
var Long = bson().Long
var doc = {long: Long.fromNumber(100)}
var doc = { long: Long.fromNumber(100) }
// Serialize a document
var data = BSON.serialize(doc, false, true, false);
var data = BSON.serialize(doc, false, true, false)
// De serialize it again
var doc_2 = BSON.deserialize(data);
var doc_2 = BSON.deserialize(data)
}
</script>
</body>
</html>
```

@@ -36,20 +29,32 @@

```javascript
var bson = require("bson");
var BSON = new bson.BSONPure.BSON();
var Long = bson.BSONPure.Long;
```js
var bson = require('bson')
var BSON = new bson.BSONPure.BSON()
var Long = bson.BSONPure.Long
var doc = {long: Long.fromNumber(100)}
var doc = { long: Long.fromNumber(100) }
// Serialize a document
var data = BSON.serialize(doc, false, true, false);
console.log("data:", data);
var data = BSON.serialize(doc, false, true, false)
console.log('data:', data)
// Deserialize the resulting Buffer
var doc_2 = BSON.deserialize(data);
console.log("doc_2:", doc_2);
var doc_2 = BSON.deserialize(data)
console.log('doc_2:', doc_2)
```
## API
The API consists of two simple methods to serialize/deserialize objects to/from BSON format:
=======
## Installation
`npm install bson`
## API
### BSON serialization and deserialiation
**`new bson.BSONPure.BSON()`** - Creates a new BSON seralizer/deserializer you can use to serialize and deserialize BSON.
* BSON.serialize(object, checkKeys, asBuffer, serializeFunctions)

@@ -61,3 +66,3 @@ * @param {Object} object the Javascript object to serialize.

* @return {TypedArray/Array} returns a TypedArray or Array depending on what your browser supports
* BSON.deserialize(buffer, options, isArray)

@@ -73,1 +78,21 @@ * Options

* @return {Object} returns the deserialized Javascript Object.
### ObjectId
**`bson.ObjectId.isValid(id)`** - Returns true if `id` is a valid number or hexadecimal string representing an ObjectId.
**`bson.ObjectId.createFromHexString(hexString)`** - Returns the ObjectId the `hexString` represents.
**`bson.ObjectId.createFromTime(time)`** - Returns an ObjectId containing the passed time.
* `time` - A Unix timestamp (number of seconds since the epoch).
**`var objectId = new bson.ObjectId(id)`** - Creates a new `ObjectId`.
* `id` - Must either be a 24-character hex string or a 12 byte binary string.
**`objectId.toJSON()`**
**`objectId.toString()`**
**`objectId.toHexString()`** - Returns a hexadecimal string representation of the ObjectId.
**`objectId.equals(otherObjectId)`** - Returns true if the ObjectIds are the same, false otherwise.
**`objectId.getTimestamp()`** - Returns a `Date` object containing the time the objectId was created for.
**`objectId.getTimestamp()`** - Returns a `Date` object containing the time the objectId contains.
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