extended_json.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.EJSON = exports.isBSONType = void 0;
  4. var binary_1 = require("./binary");
  5. var code_1 = require("./code");
  6. var db_ref_1 = require("./db_ref");
  7. var decimal128_1 = require("./decimal128");
  8. var double_1 = require("./double");
  9. var error_1 = require("./error");
  10. var int_32_1 = require("./int_32");
  11. var long_1 = require("./long");
  12. var max_key_1 = require("./max_key");
  13. var min_key_1 = require("./min_key");
  14. var objectid_1 = require("./objectid");
  15. var utils_1 = require("./parser/utils");
  16. var regexp_1 = require("./regexp");
  17. var symbol_1 = require("./symbol");
  18. var timestamp_1 = require("./timestamp");
  19. function isBSONType(value) {
  20. return (utils_1.isObjectLike(value) && Reflect.has(value, '_bsontype') && typeof value._bsontype === 'string');
  21. }
  22. exports.isBSONType = isBSONType;
  23. // INT32 boundaries
  24. var BSON_INT32_MAX = 0x7fffffff;
  25. var BSON_INT32_MIN = -0x80000000;
  26. // INT64 boundaries
  27. var BSON_INT64_MAX = 0x7fffffffffffffff;
  28. var BSON_INT64_MIN = -0x8000000000000000;
  29. // all the types where we don't need to do any special processing and can just pass the EJSON
  30. //straight to type.fromExtendedJSON
  31. var keysToCodecs = {
  32. $oid: objectid_1.ObjectId,
  33. $binary: binary_1.Binary,
  34. $uuid: binary_1.Binary,
  35. $symbol: symbol_1.BSONSymbol,
  36. $numberInt: int_32_1.Int32,
  37. $numberDecimal: decimal128_1.Decimal128,
  38. $numberDouble: double_1.Double,
  39. $numberLong: long_1.Long,
  40. $minKey: min_key_1.MinKey,
  41. $maxKey: max_key_1.MaxKey,
  42. $regex: regexp_1.BSONRegExp,
  43. $regularExpression: regexp_1.BSONRegExp,
  44. $timestamp: timestamp_1.Timestamp
  45. };
  46. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  47. function deserializeValue(value, options) {
  48. if (options === void 0) { options = {}; }
  49. if (typeof value === 'number') {
  50. if (options.relaxed || options.legacy) {
  51. return value;
  52. }
  53. // if it's an integer, should interpret as smallest BSON integer
  54. // that can represent it exactly. (if out of range, interpret as double.)
  55. if (Math.floor(value) === value) {
  56. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX)
  57. return new int_32_1.Int32(value);
  58. if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX)
  59. return long_1.Long.fromNumber(value);
  60. }
  61. // If the number is a non-integer or out of integer range, should interpret as BSON Double.
  62. return new double_1.Double(value);
  63. }
  64. // from here on out we're looking for bson types, so bail if its not an object
  65. if (value == null || typeof value !== 'object')
  66. return value;
  67. // upgrade deprecated undefined to null
  68. if (value.$undefined)
  69. return null;
  70. var keys = Object.keys(value).filter(function (k) { return k.startsWith('$') && value[k] != null; });
  71. for (var i = 0; i < keys.length; i++) {
  72. var c = keysToCodecs[keys[i]];
  73. if (c)
  74. return c.fromExtendedJSON(value, options);
  75. }
  76. if (value.$date != null) {
  77. var d = value.$date;
  78. var date = new Date();
  79. if (options.legacy) {
  80. if (typeof d === 'number')
  81. date.setTime(d);
  82. else if (typeof d === 'string')
  83. date.setTime(Date.parse(d));
  84. }
  85. else {
  86. if (typeof d === 'string')
  87. date.setTime(Date.parse(d));
  88. else if (long_1.Long.isLong(d))
  89. date.setTime(d.toNumber());
  90. else if (typeof d === 'number' && options.relaxed)
  91. date.setTime(d);
  92. }
  93. return date;
  94. }
  95. if (value.$code != null) {
  96. var copy = Object.assign({}, value);
  97. if (value.$scope) {
  98. copy.$scope = deserializeValue(value.$scope);
  99. }
  100. return code_1.Code.fromExtendedJSON(value);
  101. }
  102. if (db_ref_1.isDBRefLike(value) || value.$dbPointer) {
  103. var v = value.$ref ? value : value.$dbPointer;
  104. // we run into this in a "degenerate EJSON" case (with $id and $ref order flipped)
  105. // because of the order JSON.parse goes through the document
  106. if (v instanceof db_ref_1.DBRef)
  107. return v;
  108. var dollarKeys = Object.keys(v).filter(function (k) { return k.startsWith('$'); });
  109. var valid_1 = true;
  110. dollarKeys.forEach(function (k) {
  111. if (['$ref', '$id', '$db'].indexOf(k) === -1)
  112. valid_1 = false;
  113. });
  114. // only make DBRef if $ keys are all valid
  115. if (valid_1)
  116. return db_ref_1.DBRef.fromExtendedJSON(v);
  117. }
  118. return value;
  119. }
  120. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  121. function serializeArray(array, options) {
  122. return array.map(function (v, index) {
  123. options.seenObjects.push({ propertyName: "index " + index, obj: null });
  124. try {
  125. return serializeValue(v, options);
  126. }
  127. finally {
  128. options.seenObjects.pop();
  129. }
  130. });
  131. }
  132. function getISOString(date) {
  133. var isoStr = date.toISOString();
  134. // we should only show milliseconds in timestamp if they're non-zero
  135. return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
  136. }
  137. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  138. function serializeValue(value, options) {
  139. if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
  140. var index = options.seenObjects.findIndex(function (entry) { return entry.obj === value; });
  141. if (index !== -1) {
  142. var props = options.seenObjects.map(function (entry) { return entry.propertyName; });
  143. var leadingPart = props
  144. .slice(0, index)
  145. .map(function (prop) { return prop + " -> "; })
  146. .join('');
  147. var alreadySeen = props[index];
  148. var circularPart = ' -> ' +
  149. props
  150. .slice(index + 1, props.length - 1)
  151. .map(function (prop) { return prop + " -> "; })
  152. .join('');
  153. var current = props[props.length - 1];
  154. var leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
  155. var dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
  156. throw new error_1.BSONTypeError('Converting circular structure to EJSON:\n' +
  157. (" " + leadingPart + alreadySeen + circularPart + current + "\n") +
  158. (" " + leadingSpace + "\\" + dashes + "/"));
  159. }
  160. options.seenObjects[options.seenObjects.length - 1].obj = value;
  161. }
  162. if (Array.isArray(value))
  163. return serializeArray(value, options);
  164. if (value === undefined)
  165. return null;
  166. if (value instanceof Date || utils_1.isDate(value)) {
  167. var dateNum = value.getTime(),
  168. // is it in year range 1970-9999?
  169. inRange = dateNum > -1 && dateNum < 253402318800000;
  170. if (options.legacy) {
  171. return options.relaxed && inRange
  172. ? { $date: value.getTime() }
  173. : { $date: getISOString(value) };
  174. }
  175. return options.relaxed && inRange
  176. ? { $date: getISOString(value) }
  177. : { $date: { $numberLong: value.getTime().toString() } };
  178. }
  179. if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
  180. // it's an integer
  181. if (Math.floor(value) === value) {
  182. var int32Range = value >= BSON_INT32_MIN && value <= BSON_INT32_MAX, int64Range = value >= BSON_INT64_MIN && value <= BSON_INT64_MAX;
  183. // interpret as being of the smallest BSON integer type that can represent the number exactly
  184. if (int32Range)
  185. return { $numberInt: value.toString() };
  186. if (int64Range)
  187. return { $numberLong: value.toString() };
  188. }
  189. return { $numberDouble: value.toString() };
  190. }
  191. if (value instanceof RegExp || utils_1.isRegExp(value)) {
  192. var flags = value.flags;
  193. if (flags === undefined) {
  194. var match = value.toString().match(/[gimuy]*$/);
  195. if (match) {
  196. flags = match[0];
  197. }
  198. }
  199. var rx = new regexp_1.BSONRegExp(value.source, flags);
  200. return rx.toExtendedJSON(options);
  201. }
  202. if (value != null && typeof value === 'object')
  203. return serializeDocument(value, options);
  204. return value;
  205. }
  206. var BSON_TYPE_MAPPINGS = {
  207. Binary: function (o) { return new binary_1.Binary(o.value(), o.sub_type); },
  208. Code: function (o) { return new code_1.Code(o.code, o.scope); },
  209. DBRef: function (o) { return new db_ref_1.DBRef(o.collection || o.namespace, o.oid, o.db, o.fields); },
  210. Decimal128: function (o) { return new decimal128_1.Decimal128(o.bytes); },
  211. Double: function (o) { return new double_1.Double(o.value); },
  212. Int32: function (o) { return new int_32_1.Int32(o.value); },
  213. Long: function (o) {
  214. return long_1.Long.fromBits(
  215. // underscore variants for 1.x backwards compatibility
  216. o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_);
  217. },
  218. MaxKey: function () { return new max_key_1.MaxKey(); },
  219. MinKey: function () { return new min_key_1.MinKey(); },
  220. ObjectID: function (o) { return new objectid_1.ObjectId(o); },
  221. ObjectId: function (o) { return new objectid_1.ObjectId(o); },
  222. BSONRegExp: function (o) { return new regexp_1.BSONRegExp(o.pattern, o.options); },
  223. Symbol: function (o) { return new symbol_1.BSONSymbol(o.value); },
  224. Timestamp: function (o) { return timestamp_1.Timestamp.fromBits(o.low, o.high); }
  225. };
  226. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  227. function serializeDocument(doc, options) {
  228. if (doc == null || typeof doc !== 'object')
  229. throw new error_1.BSONError('not an object instance');
  230. var bsontype = doc._bsontype;
  231. if (typeof bsontype === 'undefined') {
  232. // It's a regular object. Recursively serialize its property values.
  233. var _doc = {};
  234. for (var name in doc) {
  235. options.seenObjects.push({ propertyName: name, obj: null });
  236. try {
  237. _doc[name] = serializeValue(doc[name], options);
  238. }
  239. finally {
  240. options.seenObjects.pop();
  241. }
  242. }
  243. return _doc;
  244. }
  245. else if (isBSONType(doc)) {
  246. // the "document" is really just a BSON type object
  247. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  248. var outDoc = doc;
  249. if (typeof outDoc.toExtendedJSON !== 'function') {
  250. // There's no EJSON serialization function on the object. It's probably an
  251. // object created by a previous version of this library (or another library)
  252. // that's duck-typing objects to look like they were generated by this library).
  253. // Copy the object into this library's version of that type.
  254. var mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
  255. if (!mapper) {
  256. throw new error_1.BSONTypeError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
  257. }
  258. outDoc = mapper(outDoc);
  259. }
  260. // Two BSON types may have nested objects that may need to be serialized too
  261. if (bsontype === 'Code' && outDoc.scope) {
  262. outDoc = new code_1.Code(outDoc.code, serializeValue(outDoc.scope, options));
  263. }
  264. else if (bsontype === 'DBRef' && outDoc.oid) {
  265. outDoc = new db_ref_1.DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
  266. }
  267. return outDoc.toExtendedJSON(options);
  268. }
  269. else {
  270. throw new error_1.BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
  271. }
  272. }
  273. /**
  274. * EJSON parse / stringify API
  275. * @public
  276. */
  277. // the namespace here is used to emulate `export * as EJSON from '...'`
  278. // which as of now (sept 2020) api-extractor does not support
  279. // eslint-disable-next-line @typescript-eslint/no-namespace
  280. var EJSON;
  281. (function (EJSON) {
  282. /**
  283. * Parse an Extended JSON string, constructing the JavaScript value or object described by that
  284. * string.
  285. *
  286. * @example
  287. * ```js
  288. * const { EJSON } = require('bson');
  289. * const text = '{ "int32": { "$numberInt": "10" } }';
  290. *
  291. * // prints { int32: { [String: '10'] _bsontype: 'Int32', value: '10' } }
  292. * console.log(EJSON.parse(text, { relaxed: false }));
  293. *
  294. * // prints { int32: 10 }
  295. * console.log(EJSON.parse(text));
  296. * ```
  297. */
  298. function parse(text, options) {
  299. var finalOptions = Object.assign({}, { relaxed: true, legacy: false }, options);
  300. // relaxed implies not strict
  301. if (typeof finalOptions.relaxed === 'boolean')
  302. finalOptions.strict = !finalOptions.relaxed;
  303. if (typeof finalOptions.strict === 'boolean')
  304. finalOptions.relaxed = !finalOptions.strict;
  305. return JSON.parse(text, function (key, value) {
  306. if (key.indexOf('\x00') !== -1) {
  307. throw new error_1.BSONError("BSON Document field names cannot contain null bytes, found: " + JSON.stringify(key));
  308. }
  309. return deserializeValue(value, finalOptions);
  310. });
  311. }
  312. EJSON.parse = parse;
  313. /**
  314. * Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer
  315. * function is specified or optionally including only the specified properties if a replacer array
  316. * is specified.
  317. *
  318. * @param value - The value to convert to extended JSON
  319. * @param replacer - A function that alters the behavior of the stringification process, or an array of String and Number objects that serve as a whitelist for selecting/filtering the properties of the value object to be included in the JSON string. If this value is null or not provided, all properties of the object are included in the resulting JSON string
  320. * @param space - A String or Number object that's used to insert white space into the output JSON string for readability purposes.
  321. * @param options - Optional settings
  322. *
  323. * @example
  324. * ```js
  325. * const { EJSON } = require('bson');
  326. * const Int32 = require('mongodb').Int32;
  327. * const doc = { int32: new Int32(10) };
  328. *
  329. * // prints '{"int32":{"$numberInt":"10"}}'
  330. * console.log(EJSON.stringify(doc, { relaxed: false }));
  331. *
  332. * // prints '{"int32":10}'
  333. * console.log(EJSON.stringify(doc));
  334. * ```
  335. */
  336. function stringify(value,
  337. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  338. replacer, space, options) {
  339. if (space != null && typeof space === 'object') {
  340. options = space;
  341. space = 0;
  342. }
  343. if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
  344. options = replacer;
  345. replacer = undefined;
  346. space = 0;
  347. }
  348. var serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
  349. seenObjects: [{ propertyName: '(root)', obj: null }]
  350. });
  351. var doc = serializeValue(value, serializeOptions);
  352. return JSON.stringify(doc, replacer, space);
  353. }
  354. EJSON.stringify = stringify;
  355. /**
  356. * Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.
  357. *
  358. * @param value - The object to serialize
  359. * @param options - Optional settings passed to the `stringify` function
  360. */
  361. function serialize(value, options) {
  362. options = options || {};
  363. return JSON.parse(stringify(value, options));
  364. }
  365. EJSON.serialize = serialize;
  366. /**
  367. * Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types
  368. *
  369. * @param ejson - The Extended JSON object to deserialize
  370. * @param options - Optional settings passed to the parse method
  371. */
  372. function deserialize(ejson, options) {
  373. options = options || {};
  374. return parse(JSON.stringify(ejson), options);
  375. }
  376. EJSON.deserialize = deserialize;
  377. })(EJSON = exports.EJSON || (exports.EJSON = {}));
  378. //# sourceMappingURL=extended_json.js.map