bson.rn.cjs 155 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159
  1. 'use strict';
  2. function isAnyArrayBuffer(value) {
  3. return ['[object ArrayBuffer]', '[object SharedArrayBuffer]'].includes(Object.prototype.toString.call(value));
  4. }
  5. function isUint8Array(value) {
  6. return Object.prototype.toString.call(value) === '[object Uint8Array]';
  7. }
  8. function isBigInt64Array(value) {
  9. return Object.prototype.toString.call(value) === '[object BigInt64Array]';
  10. }
  11. function isBigUInt64Array(value) {
  12. return Object.prototype.toString.call(value) === '[object BigUint64Array]';
  13. }
  14. function isRegExp(d) {
  15. return Object.prototype.toString.call(d) === '[object RegExp]';
  16. }
  17. function isMap(d) {
  18. return Object.prototype.toString.call(d) === '[object Map]';
  19. }
  20. function isDate(d) {
  21. return Object.prototype.toString.call(d) === '[object Date]';
  22. }
  23. const BSON_MAJOR_VERSION = 5;
  24. const BSON_INT32_MAX = 0x7fffffff;
  25. const BSON_INT32_MIN = -0x80000000;
  26. const BSON_INT64_MAX = Math.pow(2, 63) - 1;
  27. const BSON_INT64_MIN = -Math.pow(2, 63);
  28. const JS_INT_MAX = Math.pow(2, 53);
  29. const JS_INT_MIN = -Math.pow(2, 53);
  30. const BSON_DATA_NUMBER = 1;
  31. const BSON_DATA_STRING = 2;
  32. const BSON_DATA_OBJECT = 3;
  33. const BSON_DATA_ARRAY = 4;
  34. const BSON_DATA_BINARY = 5;
  35. const BSON_DATA_UNDEFINED = 6;
  36. const BSON_DATA_OID = 7;
  37. const BSON_DATA_BOOLEAN = 8;
  38. const BSON_DATA_DATE = 9;
  39. const BSON_DATA_NULL = 10;
  40. const BSON_DATA_REGEXP = 11;
  41. const BSON_DATA_DBPOINTER = 12;
  42. const BSON_DATA_CODE = 13;
  43. const BSON_DATA_SYMBOL = 14;
  44. const BSON_DATA_CODE_W_SCOPE = 15;
  45. const BSON_DATA_INT = 16;
  46. const BSON_DATA_TIMESTAMP = 17;
  47. const BSON_DATA_LONG = 18;
  48. const BSON_DATA_DECIMAL128 = 19;
  49. const BSON_DATA_MIN_KEY = 0xff;
  50. const BSON_DATA_MAX_KEY = 0x7f;
  51. const BSON_BINARY_SUBTYPE_DEFAULT = 0;
  52. const BSON_BINARY_SUBTYPE_FUNCTION = 1;
  53. const BSON_BINARY_SUBTYPE_BYTE_ARRAY = 2;
  54. const BSON_BINARY_SUBTYPE_UUID = 3;
  55. const BSON_BINARY_SUBTYPE_UUID_NEW = 4;
  56. const BSON_BINARY_SUBTYPE_MD5 = 5;
  57. const BSON_BINARY_SUBTYPE_ENCRYPTED = 6;
  58. const BSON_BINARY_SUBTYPE_COLUMN = 7;
  59. const BSON_BINARY_SUBTYPE_USER_DEFINED = 128;
  60. const BSONType = Object.freeze({
  61. double: 1,
  62. string: 2,
  63. object: 3,
  64. array: 4,
  65. binData: 5,
  66. undefined: 6,
  67. objectId: 7,
  68. bool: 8,
  69. date: 9,
  70. null: 10,
  71. regex: 11,
  72. dbPointer: 12,
  73. javascript: 13,
  74. symbol: 14,
  75. javascriptWithScope: 15,
  76. int: 16,
  77. timestamp: 17,
  78. long: 18,
  79. decimal: 19,
  80. minKey: -1,
  81. maxKey: 127
  82. });
  83. class BSONError extends Error {
  84. get bsonError() {
  85. return true;
  86. }
  87. get name() {
  88. return 'BSONError';
  89. }
  90. constructor(message) {
  91. super(message);
  92. }
  93. static isBSONError(value) {
  94. return (value != null &&
  95. typeof value === 'object' &&
  96. 'bsonError' in value &&
  97. value.bsonError === true &&
  98. 'name' in value &&
  99. 'message' in value &&
  100. 'stack' in value);
  101. }
  102. }
  103. class BSONVersionError extends BSONError {
  104. get name() {
  105. return 'BSONVersionError';
  106. }
  107. constructor() {
  108. super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
  109. }
  110. }
  111. class BSONRuntimeError extends BSONError {
  112. get name() {
  113. return 'BSONRuntimeError';
  114. }
  115. constructor(message) {
  116. super(message);
  117. }
  118. }
  119. function nodejsMathRandomBytes(byteLength) {
  120. return nodeJsByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
  121. }
  122. const nodejsRandomBytes = (() => {
  123. try {
  124. return require('crypto').randomBytes;
  125. }
  126. catch {
  127. return nodejsMathRandomBytes;
  128. }
  129. })();
  130. const nodeJsByteUtils = {
  131. toLocalBufferType(potentialBuffer) {
  132. if (Buffer.isBuffer(potentialBuffer)) {
  133. return potentialBuffer;
  134. }
  135. if (ArrayBuffer.isView(potentialBuffer)) {
  136. return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
  137. }
  138. const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);
  139. if (stringTag === 'ArrayBuffer' ||
  140. stringTag === 'SharedArrayBuffer' ||
  141. stringTag === '[object ArrayBuffer]' ||
  142. stringTag === '[object SharedArrayBuffer]') {
  143. return Buffer.from(potentialBuffer);
  144. }
  145. throw new BSONError(`Cannot create Buffer from ${String(potentialBuffer)}`);
  146. },
  147. allocate(size) {
  148. return Buffer.alloc(size);
  149. },
  150. equals(a, b) {
  151. return nodeJsByteUtils.toLocalBufferType(a).equals(b);
  152. },
  153. fromNumberArray(array) {
  154. return Buffer.from(array);
  155. },
  156. fromBase64(base64) {
  157. return Buffer.from(base64, 'base64');
  158. },
  159. toBase64(buffer) {
  160. return nodeJsByteUtils.toLocalBufferType(buffer).toString('base64');
  161. },
  162. fromISO88591(codePoints) {
  163. return Buffer.from(codePoints, 'binary');
  164. },
  165. toISO88591(buffer) {
  166. return nodeJsByteUtils.toLocalBufferType(buffer).toString('binary');
  167. },
  168. fromHex(hex) {
  169. return Buffer.from(hex, 'hex');
  170. },
  171. toHex(buffer) {
  172. return nodeJsByteUtils.toLocalBufferType(buffer).toString('hex');
  173. },
  174. fromUTF8(text) {
  175. return Buffer.from(text, 'utf8');
  176. },
  177. toUTF8(buffer, start, end) {
  178. return nodeJsByteUtils.toLocalBufferType(buffer).toString('utf8', start, end);
  179. },
  180. utf8ByteLength(input) {
  181. return Buffer.byteLength(input, 'utf8');
  182. },
  183. encodeUTF8Into(buffer, source, byteOffset) {
  184. return nodeJsByteUtils.toLocalBufferType(buffer).write(source, byteOffset, undefined, 'utf8');
  185. },
  186. randomBytes: nodejsRandomBytes
  187. };
  188. const { TextEncoder, TextDecoder } = require('../vendor/text-encoding');
  189. const { encode: btoa, decode: atob } = require('../vendor/base64');
  190. function isReactNative() {
  191. const { navigator } = globalThis;
  192. return typeof navigator === 'object' && navigator.product === 'ReactNative';
  193. }
  194. function webMathRandomBytes(byteLength) {
  195. if (byteLength < 0) {
  196. throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
  197. }
  198. return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
  199. }
  200. const webRandomBytes = (() => {
  201. const { crypto } = globalThis;
  202. if (crypto != null && typeof crypto.getRandomValues === 'function') {
  203. return (byteLength) => {
  204. return crypto.getRandomValues(webByteUtils.allocate(byteLength));
  205. };
  206. }
  207. else {
  208. if (isReactNative()) {
  209. const { console } = globalThis;
  210. console?.warn?.('BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.');
  211. }
  212. return webMathRandomBytes;
  213. }
  214. })();
  215. const HEX_DIGIT = /(\d|[a-f])/i;
  216. const webByteUtils = {
  217. toLocalBufferType(potentialUint8array) {
  218. const stringTag = potentialUint8array?.[Symbol.toStringTag] ??
  219. Object.prototype.toString.call(potentialUint8array);
  220. if (stringTag === 'Uint8Array') {
  221. return potentialUint8array;
  222. }
  223. if (ArrayBuffer.isView(potentialUint8array)) {
  224. return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
  225. }
  226. if (stringTag === 'ArrayBuffer' ||
  227. stringTag === 'SharedArrayBuffer' ||
  228. stringTag === '[object ArrayBuffer]' ||
  229. stringTag === '[object SharedArrayBuffer]') {
  230. return new Uint8Array(potentialUint8array);
  231. }
  232. throw new BSONError(`Cannot make a Uint8Array from ${String(potentialUint8array)}`);
  233. },
  234. allocate(size) {
  235. if (typeof size !== 'number') {
  236. throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
  237. }
  238. return new Uint8Array(size);
  239. },
  240. equals(a, b) {
  241. if (a.byteLength !== b.byteLength) {
  242. return false;
  243. }
  244. for (let i = 0; i < a.byteLength; i++) {
  245. if (a[i] !== b[i]) {
  246. return false;
  247. }
  248. }
  249. return true;
  250. },
  251. fromNumberArray(array) {
  252. return Uint8Array.from(array);
  253. },
  254. fromBase64(base64) {
  255. return Uint8Array.from(atob(base64), c => c.charCodeAt(0));
  256. },
  257. toBase64(uint8array) {
  258. return btoa(webByteUtils.toISO88591(uint8array));
  259. },
  260. fromISO88591(codePoints) {
  261. return Uint8Array.from(codePoints, c => c.charCodeAt(0) & 0xff);
  262. },
  263. toISO88591(uint8array) {
  264. return Array.from(Uint16Array.from(uint8array), b => String.fromCharCode(b)).join('');
  265. },
  266. fromHex(hex) {
  267. const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
  268. const buffer = [];
  269. for (let i = 0; i < evenLengthHex.length; i += 2) {
  270. const firstDigit = evenLengthHex[i];
  271. const secondDigit = evenLengthHex[i + 1];
  272. if (!HEX_DIGIT.test(firstDigit)) {
  273. break;
  274. }
  275. if (!HEX_DIGIT.test(secondDigit)) {
  276. break;
  277. }
  278. const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
  279. buffer.push(hexDigit);
  280. }
  281. return Uint8Array.from(buffer);
  282. },
  283. toHex(uint8array) {
  284. return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join('');
  285. },
  286. fromUTF8(text) {
  287. return new TextEncoder().encode(text);
  288. },
  289. toUTF8(uint8array, start, end) {
  290. return new TextDecoder('utf8', { fatal: false }).decode(uint8array.slice(start, end));
  291. },
  292. utf8ByteLength(input) {
  293. return webByteUtils.fromUTF8(input).byteLength;
  294. },
  295. encodeUTF8Into(buffer, source, byteOffset) {
  296. const bytes = webByteUtils.fromUTF8(source);
  297. buffer.set(bytes, byteOffset);
  298. return bytes.byteLength;
  299. },
  300. randomBytes: webRandomBytes
  301. };
  302. const hasGlobalBuffer = typeof Buffer === 'function' && Buffer.prototype?._isBuffer !== true;
  303. const ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
  304. class BSONDataView extends DataView {
  305. static fromUint8Array(input) {
  306. return new DataView(input.buffer, input.byteOffset, input.byteLength);
  307. }
  308. }
  309. class BSONValue {
  310. get [Symbol.for('@@mdb.bson.version')]() {
  311. return BSON_MAJOR_VERSION;
  312. }
  313. }
  314. class Binary extends BSONValue {
  315. get _bsontype() {
  316. return 'Binary';
  317. }
  318. constructor(buffer, subType) {
  319. super();
  320. if (!(buffer == null) &&
  321. !(typeof buffer === 'string') &&
  322. !ArrayBuffer.isView(buffer) &&
  323. !(buffer instanceof ArrayBuffer) &&
  324. !Array.isArray(buffer)) {
  325. throw new BSONError('Binary can only be constructed from string, Buffer, TypedArray, or Array<number>');
  326. }
  327. this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;
  328. if (buffer == null) {
  329. this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
  330. this.position = 0;
  331. }
  332. else {
  333. if (typeof buffer === 'string') {
  334. this.buffer = ByteUtils.fromISO88591(buffer);
  335. }
  336. else if (Array.isArray(buffer)) {
  337. this.buffer = ByteUtils.fromNumberArray(buffer);
  338. }
  339. else {
  340. this.buffer = ByteUtils.toLocalBufferType(buffer);
  341. }
  342. this.position = this.buffer.byteLength;
  343. }
  344. }
  345. put(byteValue) {
  346. if (typeof byteValue === 'string' && byteValue.length !== 1) {
  347. throw new BSONError('only accepts single character String');
  348. }
  349. else if (typeof byteValue !== 'number' && byteValue.length !== 1)
  350. throw new BSONError('only accepts single character Uint8Array or Array');
  351. let decodedByte;
  352. if (typeof byteValue === 'string') {
  353. decodedByte = byteValue.charCodeAt(0);
  354. }
  355. else if (typeof byteValue === 'number') {
  356. decodedByte = byteValue;
  357. }
  358. else {
  359. decodedByte = byteValue[0];
  360. }
  361. if (decodedByte < 0 || decodedByte > 255) {
  362. throw new BSONError('only accepts number in a valid unsigned byte range 0-255');
  363. }
  364. if (this.buffer.byteLength > this.position) {
  365. this.buffer[this.position++] = decodedByte;
  366. }
  367. else {
  368. const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
  369. newSpace.set(this.buffer, 0);
  370. this.buffer = newSpace;
  371. this.buffer[this.position++] = decodedByte;
  372. }
  373. }
  374. write(sequence, offset) {
  375. offset = typeof offset === 'number' ? offset : this.position;
  376. if (this.buffer.byteLength < offset + sequence.length) {
  377. const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
  378. newSpace.set(this.buffer, 0);
  379. this.buffer = newSpace;
  380. }
  381. if (ArrayBuffer.isView(sequence)) {
  382. this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
  383. this.position =
  384. offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
  385. }
  386. else if (typeof sequence === 'string') {
  387. const bytes = ByteUtils.fromISO88591(sequence);
  388. this.buffer.set(bytes, offset);
  389. this.position =
  390. offset + sequence.length > this.position ? offset + sequence.length : this.position;
  391. }
  392. }
  393. read(position, length) {
  394. length = length && length > 0 ? length : this.position;
  395. return this.buffer.slice(position, position + length);
  396. }
  397. value(asRaw) {
  398. asRaw = !!asRaw;
  399. if (asRaw && this.buffer.length === this.position) {
  400. return this.buffer;
  401. }
  402. if (asRaw) {
  403. return this.buffer.slice(0, this.position);
  404. }
  405. return ByteUtils.toISO88591(this.buffer.subarray(0, this.position));
  406. }
  407. length() {
  408. return this.position;
  409. }
  410. toJSON() {
  411. return ByteUtils.toBase64(this.buffer);
  412. }
  413. toString(encoding) {
  414. if (encoding === 'hex')
  415. return ByteUtils.toHex(this.buffer);
  416. if (encoding === 'base64')
  417. return ByteUtils.toBase64(this.buffer);
  418. if (encoding === 'utf8' || encoding === 'utf-8')
  419. return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength);
  420. return ByteUtils.toUTF8(this.buffer, 0, this.buffer.byteLength);
  421. }
  422. toExtendedJSON(options) {
  423. options = options || {};
  424. const base64String = ByteUtils.toBase64(this.buffer);
  425. const subType = Number(this.sub_type).toString(16);
  426. if (options.legacy) {
  427. return {
  428. $binary: base64String,
  429. $type: subType.length === 1 ? '0' + subType : subType
  430. };
  431. }
  432. return {
  433. $binary: {
  434. base64: base64String,
  435. subType: subType.length === 1 ? '0' + subType : subType
  436. }
  437. };
  438. }
  439. toUUID() {
  440. if (this.sub_type === Binary.SUBTYPE_UUID) {
  441. return new UUID(this.buffer.slice(0, this.position));
  442. }
  443. throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`);
  444. }
  445. static createFromHexString(hex, subType) {
  446. return new Binary(ByteUtils.fromHex(hex), subType);
  447. }
  448. static createFromBase64(base64, subType) {
  449. return new Binary(ByteUtils.fromBase64(base64), subType);
  450. }
  451. static fromExtendedJSON(doc, options) {
  452. options = options || {};
  453. let data;
  454. let type;
  455. if ('$binary' in doc) {
  456. if (options.legacy && typeof doc.$binary === 'string' && '$type' in doc) {
  457. type = doc.$type ? parseInt(doc.$type, 16) : 0;
  458. data = ByteUtils.fromBase64(doc.$binary);
  459. }
  460. else {
  461. if (typeof doc.$binary !== 'string') {
  462. type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
  463. data = ByteUtils.fromBase64(doc.$binary.base64);
  464. }
  465. }
  466. }
  467. else if ('$uuid' in doc) {
  468. type = 4;
  469. data = UUID.bytesFromString(doc.$uuid);
  470. }
  471. if (!data) {
  472. throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
  473. }
  474. return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
  475. }
  476. [Symbol.for('nodejs.util.inspect.custom')]() {
  477. return this.inspect();
  478. }
  479. inspect() {
  480. const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
  481. return `Binary.createFromBase64("${base64}", ${this.sub_type})`;
  482. }
  483. }
  484. Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0;
  485. Binary.BUFFER_SIZE = 256;
  486. Binary.SUBTYPE_DEFAULT = 0;
  487. Binary.SUBTYPE_FUNCTION = 1;
  488. Binary.SUBTYPE_BYTE_ARRAY = 2;
  489. Binary.SUBTYPE_UUID_OLD = 3;
  490. Binary.SUBTYPE_UUID = 4;
  491. Binary.SUBTYPE_MD5 = 5;
  492. Binary.SUBTYPE_ENCRYPTED = 6;
  493. Binary.SUBTYPE_COLUMN = 7;
  494. Binary.SUBTYPE_USER_DEFINED = 128;
  495. const UUID_BYTE_LENGTH = 16;
  496. const UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
  497. const UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
  498. class UUID extends Binary {
  499. constructor(input) {
  500. let bytes;
  501. if (input == null) {
  502. bytes = UUID.generate();
  503. }
  504. else if (input instanceof UUID) {
  505. bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
  506. }
  507. else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
  508. bytes = ByteUtils.toLocalBufferType(input);
  509. }
  510. else if (typeof input === 'string') {
  511. bytes = UUID.bytesFromString(input);
  512. }
  513. else {
  514. throw new BSONError('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).');
  515. }
  516. super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
  517. }
  518. get id() {
  519. return this.buffer;
  520. }
  521. set id(value) {
  522. this.buffer = value;
  523. }
  524. toHexString(includeDashes = true) {
  525. if (includeDashes) {
  526. return [
  527. ByteUtils.toHex(this.buffer.subarray(0, 4)),
  528. ByteUtils.toHex(this.buffer.subarray(4, 6)),
  529. ByteUtils.toHex(this.buffer.subarray(6, 8)),
  530. ByteUtils.toHex(this.buffer.subarray(8, 10)),
  531. ByteUtils.toHex(this.buffer.subarray(10, 16))
  532. ].join('-');
  533. }
  534. return ByteUtils.toHex(this.buffer);
  535. }
  536. toString(encoding) {
  537. if (encoding === 'hex')
  538. return ByteUtils.toHex(this.id);
  539. if (encoding === 'base64')
  540. return ByteUtils.toBase64(this.id);
  541. return this.toHexString();
  542. }
  543. toJSON() {
  544. return this.toHexString();
  545. }
  546. equals(otherId) {
  547. if (!otherId) {
  548. return false;
  549. }
  550. if (otherId instanceof UUID) {
  551. return ByteUtils.equals(otherId.id, this.id);
  552. }
  553. try {
  554. return ByteUtils.equals(new UUID(otherId).id, this.id);
  555. }
  556. catch {
  557. return false;
  558. }
  559. }
  560. toBinary() {
  561. return new Binary(this.id, Binary.SUBTYPE_UUID);
  562. }
  563. static generate() {
  564. const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
  565. bytes[6] = (bytes[6] & 0x0f) | 0x40;
  566. bytes[8] = (bytes[8] & 0x3f) | 0x80;
  567. return bytes;
  568. }
  569. static isValid(input) {
  570. if (!input) {
  571. return false;
  572. }
  573. if (typeof input === 'string') {
  574. return UUID.isValidUUIDString(input);
  575. }
  576. if (isUint8Array(input)) {
  577. return input.byteLength === UUID_BYTE_LENGTH;
  578. }
  579. return (input._bsontype === 'Binary' &&
  580. input.sub_type === this.SUBTYPE_UUID &&
  581. input.buffer.byteLength === 16);
  582. }
  583. static createFromHexString(hexString) {
  584. const buffer = UUID.bytesFromString(hexString);
  585. return new UUID(buffer);
  586. }
  587. static createFromBase64(base64) {
  588. return new UUID(ByteUtils.fromBase64(base64));
  589. }
  590. static bytesFromString(representation) {
  591. if (!UUID.isValidUUIDString(representation)) {
  592. throw new BSONError('UUID string representation must be 32 hex digits or canonical hyphenated representation');
  593. }
  594. return ByteUtils.fromHex(representation.replace(/-/g, ''));
  595. }
  596. static isValidUUIDString(representation) {
  597. return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
  598. }
  599. [Symbol.for('nodejs.util.inspect.custom')]() {
  600. return this.inspect();
  601. }
  602. inspect() {
  603. return `new UUID("${this.toHexString()}")`;
  604. }
  605. }
  606. UUID.cacheHexString = false;
  607. class Code extends BSONValue {
  608. get _bsontype() {
  609. return 'Code';
  610. }
  611. constructor(code, scope) {
  612. super();
  613. this.code = code.toString();
  614. this.scope = scope ?? null;
  615. }
  616. toJSON() {
  617. if (this.scope != null) {
  618. return { code: this.code, scope: this.scope };
  619. }
  620. return { code: this.code };
  621. }
  622. toExtendedJSON() {
  623. if (this.scope) {
  624. return { $code: this.code, $scope: this.scope };
  625. }
  626. return { $code: this.code };
  627. }
  628. static fromExtendedJSON(doc) {
  629. return new Code(doc.$code, doc.$scope);
  630. }
  631. [Symbol.for('nodejs.util.inspect.custom')]() {
  632. return this.inspect();
  633. }
  634. inspect() {
  635. const codeJson = this.toJSON();
  636. return `new Code("${String(codeJson.code)}"${codeJson.scope != null ? `, ${JSON.stringify(codeJson.scope)}` : ''})`;
  637. }
  638. }
  639. function isDBRefLike(value) {
  640. return (value != null &&
  641. typeof value === 'object' &&
  642. '$id' in value &&
  643. value.$id != null &&
  644. '$ref' in value &&
  645. typeof value.$ref === 'string' &&
  646. (!('$db' in value) || ('$db' in value && typeof value.$db === 'string')));
  647. }
  648. class DBRef extends BSONValue {
  649. get _bsontype() {
  650. return 'DBRef';
  651. }
  652. constructor(collection, oid, db, fields) {
  653. super();
  654. const parts = collection.split('.');
  655. if (parts.length === 2) {
  656. db = parts.shift();
  657. collection = parts.shift();
  658. }
  659. this.collection = collection;
  660. this.oid = oid;
  661. this.db = db;
  662. this.fields = fields || {};
  663. }
  664. get namespace() {
  665. return this.collection;
  666. }
  667. set namespace(value) {
  668. this.collection = value;
  669. }
  670. toJSON() {
  671. const o = Object.assign({
  672. $ref: this.collection,
  673. $id: this.oid
  674. }, this.fields);
  675. if (this.db != null)
  676. o.$db = this.db;
  677. return o;
  678. }
  679. toExtendedJSON(options) {
  680. options = options || {};
  681. let o = {
  682. $ref: this.collection,
  683. $id: this.oid
  684. };
  685. if (options.legacy) {
  686. return o;
  687. }
  688. if (this.db)
  689. o.$db = this.db;
  690. o = Object.assign(o, this.fields);
  691. return o;
  692. }
  693. static fromExtendedJSON(doc) {
  694. const copy = Object.assign({}, doc);
  695. delete copy.$ref;
  696. delete copy.$id;
  697. delete copy.$db;
  698. return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
  699. }
  700. [Symbol.for('nodejs.util.inspect.custom')]() {
  701. return this.inspect();
  702. }
  703. inspect() {
  704. const oid = this.oid === undefined || this.oid.toString === undefined ? this.oid : this.oid.toString();
  705. return `new DBRef("${this.namespace}", new ObjectId("${String(oid)}")${this.db ? `, "${this.db}"` : ''})`;
  706. }
  707. }
  708. let wasm = undefined;
  709. try {
  710. wasm = new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0, 1, 13, 2, 96, 0, 1, 127, 96, 4, 127, 127, 127, 127, 1, 127, 3, 7, 6, 0, 1, 1, 1, 1, 1, 6, 6, 1, 127, 1, 65, 0, 11, 7, 50, 6, 3, 109, 117, 108, 0, 1, 5, 100, 105, 118, 95, 115, 0, 2, 5, 100, 105, 118, 95, 117, 0, 3, 5, 114, 101, 109, 95, 115, 0, 4, 5, 114, 101, 109, 95, 117, 0, 5, 8, 103, 101, 116, 95, 104, 105, 103, 104, 0, 0, 10, 191, 1, 6, 4, 0, 35, 0, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 126, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 127, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 128, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 129, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11, 36, 1, 1, 126, 32, 0, 173, 32, 1, 173, 66, 32, 134, 132, 32, 2, 173, 32, 3, 173, 66, 32, 134, 132, 130, 34, 4, 66, 32, 135, 167, 36, 0, 32, 4, 167, 11])), {}).exports;
  711. }
  712. catch {
  713. }
  714. const TWO_PWR_16_DBL = 1 << 16;
  715. const TWO_PWR_24_DBL = 1 << 24;
  716. const TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
  717. const TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
  718. const TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
  719. const INT_CACHE = {};
  720. const UINT_CACHE = {};
  721. const MAX_INT64_STRING_LENGTH = 20;
  722. const DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
  723. class Long extends BSONValue {
  724. get _bsontype() {
  725. return 'Long';
  726. }
  727. get __isLong__() {
  728. return true;
  729. }
  730. constructor(low = 0, high, unsigned) {
  731. super();
  732. if (typeof low === 'bigint') {
  733. Object.assign(this, Long.fromBigInt(low, !!high));
  734. }
  735. else if (typeof low === 'string') {
  736. Object.assign(this, Long.fromString(low, !!high));
  737. }
  738. else {
  739. this.low = low | 0;
  740. this.high = high | 0;
  741. this.unsigned = !!unsigned;
  742. }
  743. }
  744. static fromBits(lowBits, highBits, unsigned) {
  745. return new Long(lowBits, highBits, unsigned);
  746. }
  747. static fromInt(value, unsigned) {
  748. let obj, cachedObj, cache;
  749. if (unsigned) {
  750. value >>>= 0;
  751. if ((cache = 0 <= value && value < 256)) {
  752. cachedObj = UINT_CACHE[value];
  753. if (cachedObj)
  754. return cachedObj;
  755. }
  756. obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
  757. if (cache)
  758. UINT_CACHE[value] = obj;
  759. return obj;
  760. }
  761. else {
  762. value |= 0;
  763. if ((cache = -128 <= value && value < 128)) {
  764. cachedObj = INT_CACHE[value];
  765. if (cachedObj)
  766. return cachedObj;
  767. }
  768. obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
  769. if (cache)
  770. INT_CACHE[value] = obj;
  771. return obj;
  772. }
  773. }
  774. static fromNumber(value, unsigned) {
  775. if (isNaN(value))
  776. return unsigned ? Long.UZERO : Long.ZERO;
  777. if (unsigned) {
  778. if (value < 0)
  779. return Long.UZERO;
  780. if (value >= TWO_PWR_64_DBL)
  781. return Long.MAX_UNSIGNED_VALUE;
  782. }
  783. else {
  784. if (value <= -TWO_PWR_63_DBL)
  785. return Long.MIN_VALUE;
  786. if (value + 1 >= TWO_PWR_63_DBL)
  787. return Long.MAX_VALUE;
  788. }
  789. if (value < 0)
  790. return Long.fromNumber(-value, unsigned).neg();
  791. return Long.fromBits(value % TWO_PWR_32_DBL | 0, (value / TWO_PWR_32_DBL) | 0, unsigned);
  792. }
  793. static fromBigInt(value, unsigned) {
  794. return Long.fromString(value.toString(), unsigned);
  795. }
  796. static fromString(str, unsigned, radix) {
  797. if (str.length === 0)
  798. throw new BSONError('empty string');
  799. if (str === 'NaN' || str === 'Infinity' || str === '+Infinity' || str === '-Infinity')
  800. return Long.ZERO;
  801. if (typeof unsigned === 'number') {
  802. (radix = unsigned), (unsigned = false);
  803. }
  804. else {
  805. unsigned = !!unsigned;
  806. }
  807. radix = radix || 10;
  808. if (radix < 2 || 36 < radix)
  809. throw new BSONError('radix');
  810. let p;
  811. if ((p = str.indexOf('-')) > 0)
  812. throw new BSONError('interior hyphen');
  813. else if (p === 0) {
  814. return Long.fromString(str.substring(1), unsigned, radix).neg();
  815. }
  816. const radixToPower = Long.fromNumber(Math.pow(radix, 8));
  817. let result = Long.ZERO;
  818. for (let i = 0; i < str.length; i += 8) {
  819. const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
  820. if (size < 8) {
  821. const power = Long.fromNumber(Math.pow(radix, size));
  822. result = result.mul(power).add(Long.fromNumber(value));
  823. }
  824. else {
  825. result = result.mul(radixToPower);
  826. result = result.add(Long.fromNumber(value));
  827. }
  828. }
  829. result.unsigned = unsigned;
  830. return result;
  831. }
  832. static fromBytes(bytes, unsigned, le) {
  833. return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
  834. }
  835. static fromBytesLE(bytes, unsigned) {
  836. return new Long(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24), bytes[4] | (bytes[5] << 8) | (bytes[6] << 16) | (bytes[7] << 24), unsigned);
  837. }
  838. static fromBytesBE(bytes, unsigned) {
  839. return new Long((bytes[4] << 24) | (bytes[5] << 16) | (bytes[6] << 8) | bytes[7], (bytes[0] << 24) | (bytes[1] << 16) | (bytes[2] << 8) | bytes[3], unsigned);
  840. }
  841. static isLong(value) {
  842. return (value != null &&
  843. typeof value === 'object' &&
  844. '__isLong__' in value &&
  845. value.__isLong__ === true);
  846. }
  847. static fromValue(val, unsigned) {
  848. if (typeof val === 'number')
  849. return Long.fromNumber(val, unsigned);
  850. if (typeof val === 'string')
  851. return Long.fromString(val, unsigned);
  852. return Long.fromBits(val.low, val.high, typeof unsigned === 'boolean' ? unsigned : val.unsigned);
  853. }
  854. add(addend) {
  855. if (!Long.isLong(addend))
  856. addend = Long.fromValue(addend);
  857. const a48 = this.high >>> 16;
  858. const a32 = this.high & 0xffff;
  859. const a16 = this.low >>> 16;
  860. const a00 = this.low & 0xffff;
  861. const b48 = addend.high >>> 16;
  862. const b32 = addend.high & 0xffff;
  863. const b16 = addend.low >>> 16;
  864. const b00 = addend.low & 0xffff;
  865. let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  866. c00 += a00 + b00;
  867. c16 += c00 >>> 16;
  868. c00 &= 0xffff;
  869. c16 += a16 + b16;
  870. c32 += c16 >>> 16;
  871. c16 &= 0xffff;
  872. c32 += a32 + b32;
  873. c48 += c32 >>> 16;
  874. c32 &= 0xffff;
  875. c48 += a48 + b48;
  876. c48 &= 0xffff;
  877. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  878. }
  879. and(other) {
  880. if (!Long.isLong(other))
  881. other = Long.fromValue(other);
  882. return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
  883. }
  884. compare(other) {
  885. if (!Long.isLong(other))
  886. other = Long.fromValue(other);
  887. if (this.eq(other))
  888. return 0;
  889. const thisNeg = this.isNegative(), otherNeg = other.isNegative();
  890. if (thisNeg && !otherNeg)
  891. return -1;
  892. if (!thisNeg && otherNeg)
  893. return 1;
  894. if (!this.unsigned)
  895. return this.sub(other).isNegative() ? -1 : 1;
  896. return other.high >>> 0 > this.high >>> 0 ||
  897. (other.high === this.high && other.low >>> 0 > this.low >>> 0)
  898. ? -1
  899. : 1;
  900. }
  901. comp(other) {
  902. return this.compare(other);
  903. }
  904. divide(divisor) {
  905. if (!Long.isLong(divisor))
  906. divisor = Long.fromValue(divisor);
  907. if (divisor.isZero())
  908. throw new BSONError('division by zero');
  909. if (wasm) {
  910. if (!this.unsigned &&
  911. this.high === -0x80000000 &&
  912. divisor.low === -1 &&
  913. divisor.high === -1) {
  914. return this;
  915. }
  916. const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
  917. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  918. }
  919. if (this.isZero())
  920. return this.unsigned ? Long.UZERO : Long.ZERO;
  921. let approx, rem, res;
  922. if (!this.unsigned) {
  923. if (this.eq(Long.MIN_VALUE)) {
  924. if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
  925. return Long.MIN_VALUE;
  926. else if (divisor.eq(Long.MIN_VALUE))
  927. return Long.ONE;
  928. else {
  929. const halfThis = this.shr(1);
  930. approx = halfThis.div(divisor).shl(1);
  931. if (approx.eq(Long.ZERO)) {
  932. return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
  933. }
  934. else {
  935. rem = this.sub(divisor.mul(approx));
  936. res = approx.add(rem.div(divisor));
  937. return res;
  938. }
  939. }
  940. }
  941. else if (divisor.eq(Long.MIN_VALUE))
  942. return this.unsigned ? Long.UZERO : Long.ZERO;
  943. if (this.isNegative()) {
  944. if (divisor.isNegative())
  945. return this.neg().div(divisor.neg());
  946. return this.neg().div(divisor).neg();
  947. }
  948. else if (divisor.isNegative())
  949. return this.div(divisor.neg()).neg();
  950. res = Long.ZERO;
  951. }
  952. else {
  953. if (!divisor.unsigned)
  954. divisor = divisor.toUnsigned();
  955. if (divisor.gt(this))
  956. return Long.UZERO;
  957. if (divisor.gt(this.shru(1)))
  958. return Long.UONE;
  959. res = Long.UZERO;
  960. }
  961. rem = this;
  962. while (rem.gte(divisor)) {
  963. approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
  964. const log2 = Math.ceil(Math.log(approx) / Math.LN2);
  965. const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
  966. let approxRes = Long.fromNumber(approx);
  967. let approxRem = approxRes.mul(divisor);
  968. while (approxRem.isNegative() || approxRem.gt(rem)) {
  969. approx -= delta;
  970. approxRes = Long.fromNumber(approx, this.unsigned);
  971. approxRem = approxRes.mul(divisor);
  972. }
  973. if (approxRes.isZero())
  974. approxRes = Long.ONE;
  975. res = res.add(approxRes);
  976. rem = rem.sub(approxRem);
  977. }
  978. return res;
  979. }
  980. div(divisor) {
  981. return this.divide(divisor);
  982. }
  983. equals(other) {
  984. if (!Long.isLong(other))
  985. other = Long.fromValue(other);
  986. if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
  987. return false;
  988. return this.high === other.high && this.low === other.low;
  989. }
  990. eq(other) {
  991. return this.equals(other);
  992. }
  993. getHighBits() {
  994. return this.high;
  995. }
  996. getHighBitsUnsigned() {
  997. return this.high >>> 0;
  998. }
  999. getLowBits() {
  1000. return this.low;
  1001. }
  1002. getLowBitsUnsigned() {
  1003. return this.low >>> 0;
  1004. }
  1005. getNumBitsAbs() {
  1006. if (this.isNegative()) {
  1007. return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
  1008. }
  1009. const val = this.high !== 0 ? this.high : this.low;
  1010. let bit;
  1011. for (bit = 31; bit > 0; bit--)
  1012. if ((val & (1 << bit)) !== 0)
  1013. break;
  1014. return this.high !== 0 ? bit + 33 : bit + 1;
  1015. }
  1016. greaterThan(other) {
  1017. return this.comp(other) > 0;
  1018. }
  1019. gt(other) {
  1020. return this.greaterThan(other);
  1021. }
  1022. greaterThanOrEqual(other) {
  1023. return this.comp(other) >= 0;
  1024. }
  1025. gte(other) {
  1026. return this.greaterThanOrEqual(other);
  1027. }
  1028. ge(other) {
  1029. return this.greaterThanOrEqual(other);
  1030. }
  1031. isEven() {
  1032. return (this.low & 1) === 0;
  1033. }
  1034. isNegative() {
  1035. return !this.unsigned && this.high < 0;
  1036. }
  1037. isOdd() {
  1038. return (this.low & 1) === 1;
  1039. }
  1040. isPositive() {
  1041. return this.unsigned || this.high >= 0;
  1042. }
  1043. isZero() {
  1044. return this.high === 0 && this.low === 0;
  1045. }
  1046. lessThan(other) {
  1047. return this.comp(other) < 0;
  1048. }
  1049. lt(other) {
  1050. return this.lessThan(other);
  1051. }
  1052. lessThanOrEqual(other) {
  1053. return this.comp(other) <= 0;
  1054. }
  1055. lte(other) {
  1056. return this.lessThanOrEqual(other);
  1057. }
  1058. modulo(divisor) {
  1059. if (!Long.isLong(divisor))
  1060. divisor = Long.fromValue(divisor);
  1061. if (wasm) {
  1062. const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
  1063. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  1064. }
  1065. return this.sub(this.div(divisor).mul(divisor));
  1066. }
  1067. mod(divisor) {
  1068. return this.modulo(divisor);
  1069. }
  1070. rem(divisor) {
  1071. return this.modulo(divisor);
  1072. }
  1073. multiply(multiplier) {
  1074. if (this.isZero())
  1075. return Long.ZERO;
  1076. if (!Long.isLong(multiplier))
  1077. multiplier = Long.fromValue(multiplier);
  1078. if (wasm) {
  1079. const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
  1080. return Long.fromBits(low, wasm.get_high(), this.unsigned);
  1081. }
  1082. if (multiplier.isZero())
  1083. return Long.ZERO;
  1084. if (this.eq(Long.MIN_VALUE))
  1085. return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  1086. if (multiplier.eq(Long.MIN_VALUE))
  1087. return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
  1088. if (this.isNegative()) {
  1089. if (multiplier.isNegative())
  1090. return this.neg().mul(multiplier.neg());
  1091. else
  1092. return this.neg().mul(multiplier).neg();
  1093. }
  1094. else if (multiplier.isNegative())
  1095. return this.mul(multiplier.neg()).neg();
  1096. if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
  1097. return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
  1098. const a48 = this.high >>> 16;
  1099. const a32 = this.high & 0xffff;
  1100. const a16 = this.low >>> 16;
  1101. const a00 = this.low & 0xffff;
  1102. const b48 = multiplier.high >>> 16;
  1103. const b32 = multiplier.high & 0xffff;
  1104. const b16 = multiplier.low >>> 16;
  1105. const b00 = multiplier.low & 0xffff;
  1106. let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
  1107. c00 += a00 * b00;
  1108. c16 += c00 >>> 16;
  1109. c00 &= 0xffff;
  1110. c16 += a16 * b00;
  1111. c32 += c16 >>> 16;
  1112. c16 &= 0xffff;
  1113. c16 += a00 * b16;
  1114. c32 += c16 >>> 16;
  1115. c16 &= 0xffff;
  1116. c32 += a32 * b00;
  1117. c48 += c32 >>> 16;
  1118. c32 &= 0xffff;
  1119. c32 += a16 * b16;
  1120. c48 += c32 >>> 16;
  1121. c32 &= 0xffff;
  1122. c32 += a00 * b32;
  1123. c48 += c32 >>> 16;
  1124. c32 &= 0xffff;
  1125. c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
  1126. c48 &= 0xffff;
  1127. return Long.fromBits((c16 << 16) | c00, (c48 << 16) | c32, this.unsigned);
  1128. }
  1129. mul(multiplier) {
  1130. return this.multiply(multiplier);
  1131. }
  1132. negate() {
  1133. if (!this.unsigned && this.eq(Long.MIN_VALUE))
  1134. return Long.MIN_VALUE;
  1135. return this.not().add(Long.ONE);
  1136. }
  1137. neg() {
  1138. return this.negate();
  1139. }
  1140. not() {
  1141. return Long.fromBits(~this.low, ~this.high, this.unsigned);
  1142. }
  1143. notEquals(other) {
  1144. return !this.equals(other);
  1145. }
  1146. neq(other) {
  1147. return this.notEquals(other);
  1148. }
  1149. ne(other) {
  1150. return this.notEquals(other);
  1151. }
  1152. or(other) {
  1153. if (!Long.isLong(other))
  1154. other = Long.fromValue(other);
  1155. return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
  1156. }
  1157. shiftLeft(numBits) {
  1158. if (Long.isLong(numBits))
  1159. numBits = numBits.toInt();
  1160. if ((numBits &= 63) === 0)
  1161. return this;
  1162. else if (numBits < 32)
  1163. return Long.fromBits(this.low << numBits, (this.high << numBits) | (this.low >>> (32 - numBits)), this.unsigned);
  1164. else
  1165. return Long.fromBits(0, this.low << (numBits - 32), this.unsigned);
  1166. }
  1167. shl(numBits) {
  1168. return this.shiftLeft(numBits);
  1169. }
  1170. shiftRight(numBits) {
  1171. if (Long.isLong(numBits))
  1172. numBits = numBits.toInt();
  1173. if ((numBits &= 63) === 0)
  1174. return this;
  1175. else if (numBits < 32)
  1176. return Long.fromBits((this.low >>> numBits) | (this.high << (32 - numBits)), this.high >> numBits, this.unsigned);
  1177. else
  1178. return Long.fromBits(this.high >> (numBits - 32), this.high >= 0 ? 0 : -1, this.unsigned);
  1179. }
  1180. shr(numBits) {
  1181. return this.shiftRight(numBits);
  1182. }
  1183. shiftRightUnsigned(numBits) {
  1184. if (Long.isLong(numBits))
  1185. numBits = numBits.toInt();
  1186. numBits &= 63;
  1187. if (numBits === 0)
  1188. return this;
  1189. else {
  1190. const high = this.high;
  1191. if (numBits < 32) {
  1192. const low = this.low;
  1193. return Long.fromBits((low >>> numBits) | (high << (32 - numBits)), high >>> numBits, this.unsigned);
  1194. }
  1195. else if (numBits === 32)
  1196. return Long.fromBits(high, 0, this.unsigned);
  1197. else
  1198. return Long.fromBits(high >>> (numBits - 32), 0, this.unsigned);
  1199. }
  1200. }
  1201. shr_u(numBits) {
  1202. return this.shiftRightUnsigned(numBits);
  1203. }
  1204. shru(numBits) {
  1205. return this.shiftRightUnsigned(numBits);
  1206. }
  1207. subtract(subtrahend) {
  1208. if (!Long.isLong(subtrahend))
  1209. subtrahend = Long.fromValue(subtrahend);
  1210. return this.add(subtrahend.neg());
  1211. }
  1212. sub(subtrahend) {
  1213. return this.subtract(subtrahend);
  1214. }
  1215. toInt() {
  1216. return this.unsigned ? this.low >>> 0 : this.low;
  1217. }
  1218. toNumber() {
  1219. if (this.unsigned)
  1220. return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
  1221. return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
  1222. }
  1223. toBigInt() {
  1224. return BigInt(this.toString());
  1225. }
  1226. toBytes(le) {
  1227. return le ? this.toBytesLE() : this.toBytesBE();
  1228. }
  1229. toBytesLE() {
  1230. const hi = this.high, lo = this.low;
  1231. return [
  1232. lo & 0xff,
  1233. (lo >>> 8) & 0xff,
  1234. (lo >>> 16) & 0xff,
  1235. lo >>> 24,
  1236. hi & 0xff,
  1237. (hi >>> 8) & 0xff,
  1238. (hi >>> 16) & 0xff,
  1239. hi >>> 24
  1240. ];
  1241. }
  1242. toBytesBE() {
  1243. const hi = this.high, lo = this.low;
  1244. return [
  1245. hi >>> 24,
  1246. (hi >>> 16) & 0xff,
  1247. (hi >>> 8) & 0xff,
  1248. hi & 0xff,
  1249. lo >>> 24,
  1250. (lo >>> 16) & 0xff,
  1251. (lo >>> 8) & 0xff,
  1252. lo & 0xff
  1253. ];
  1254. }
  1255. toSigned() {
  1256. if (!this.unsigned)
  1257. return this;
  1258. return Long.fromBits(this.low, this.high, false);
  1259. }
  1260. toString(radix) {
  1261. radix = radix || 10;
  1262. if (radix < 2 || 36 < radix)
  1263. throw new BSONError('radix');
  1264. if (this.isZero())
  1265. return '0';
  1266. if (this.isNegative()) {
  1267. if (this.eq(Long.MIN_VALUE)) {
  1268. const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
  1269. return div.toString(radix) + rem1.toInt().toString(radix);
  1270. }
  1271. else
  1272. return '-' + this.neg().toString(radix);
  1273. }
  1274. const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
  1275. let rem = this;
  1276. let result = '';
  1277. while (true) {
  1278. const remDiv = rem.div(radixToPower);
  1279. const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
  1280. let digits = intval.toString(radix);
  1281. rem = remDiv;
  1282. if (rem.isZero()) {
  1283. return digits + result;
  1284. }
  1285. else {
  1286. while (digits.length < 6)
  1287. digits = '0' + digits;
  1288. result = '' + digits + result;
  1289. }
  1290. }
  1291. }
  1292. toUnsigned() {
  1293. if (this.unsigned)
  1294. return this;
  1295. return Long.fromBits(this.low, this.high, true);
  1296. }
  1297. xor(other) {
  1298. if (!Long.isLong(other))
  1299. other = Long.fromValue(other);
  1300. return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
  1301. }
  1302. eqz() {
  1303. return this.isZero();
  1304. }
  1305. le(other) {
  1306. return this.lessThanOrEqual(other);
  1307. }
  1308. toExtendedJSON(options) {
  1309. if (options && options.relaxed)
  1310. return this.toNumber();
  1311. return { $numberLong: this.toString() };
  1312. }
  1313. static fromExtendedJSON(doc, options) {
  1314. const { useBigInt64 = false, relaxed = true } = { ...options };
  1315. if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
  1316. throw new BSONError('$numberLong string is too long');
  1317. }
  1318. if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
  1319. throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
  1320. }
  1321. if (useBigInt64) {
  1322. const bigIntResult = BigInt(doc.$numberLong);
  1323. return BigInt.asIntN(64, bigIntResult);
  1324. }
  1325. const longResult = Long.fromString(doc.$numberLong);
  1326. if (relaxed) {
  1327. return longResult.toNumber();
  1328. }
  1329. return longResult;
  1330. }
  1331. [Symbol.for('nodejs.util.inspect.custom')]() {
  1332. return this.inspect();
  1333. }
  1334. inspect() {
  1335. return `new Long("${this.toString()}"${this.unsigned ? ', true' : ''})`;
  1336. }
  1337. }
  1338. Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
  1339. Long.MAX_UNSIGNED_VALUE = Long.fromBits(0xffffffff | 0, 0xffffffff | 0, true);
  1340. Long.ZERO = Long.fromInt(0);
  1341. Long.UZERO = Long.fromInt(0, true);
  1342. Long.ONE = Long.fromInt(1);
  1343. Long.UONE = Long.fromInt(1, true);
  1344. Long.NEG_ONE = Long.fromInt(-1);
  1345. Long.MAX_VALUE = Long.fromBits(0xffffffff | 0, 0x7fffffff | 0, false);
  1346. Long.MIN_VALUE = Long.fromBits(0, 0x80000000 | 0, false);
  1347. const PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
  1348. const PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
  1349. const PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
  1350. const EXPONENT_MAX = 6111;
  1351. const EXPONENT_MIN = -6176;
  1352. const EXPONENT_BIAS = 6176;
  1353. const MAX_DIGITS = 34;
  1354. const NAN_BUFFER = ByteUtils.fromNumberArray([
  1355. 0x7c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  1356. ].reverse());
  1357. const INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
  1358. 0xf8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  1359. ].reverse());
  1360. const INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
  1361. 0x78, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
  1362. ].reverse());
  1363. const EXPONENT_REGEX = /^([-+])?(\d+)?$/;
  1364. const COMBINATION_MASK = 0x1f;
  1365. const EXPONENT_MASK = 0x3fff;
  1366. const COMBINATION_INFINITY = 30;
  1367. const COMBINATION_NAN = 31;
  1368. function isDigit(value) {
  1369. return !isNaN(parseInt(value, 10));
  1370. }
  1371. function divideu128(value) {
  1372. const DIVISOR = Long.fromNumber(1000 * 1000 * 1000);
  1373. let _rem = Long.fromNumber(0);
  1374. if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
  1375. return { quotient: value, rem: _rem };
  1376. }
  1377. for (let i = 0; i <= 3; i++) {
  1378. _rem = _rem.shiftLeft(32);
  1379. _rem = _rem.add(new Long(value.parts[i], 0));
  1380. value.parts[i] = _rem.div(DIVISOR).low;
  1381. _rem = _rem.modulo(DIVISOR);
  1382. }
  1383. return { quotient: value, rem: _rem };
  1384. }
  1385. function multiply64x2(left, right) {
  1386. if (!left && !right) {
  1387. return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
  1388. }
  1389. const leftHigh = left.shiftRightUnsigned(32);
  1390. const leftLow = new Long(left.getLowBits(), 0);
  1391. const rightHigh = right.shiftRightUnsigned(32);
  1392. const rightLow = new Long(right.getLowBits(), 0);
  1393. let productHigh = leftHigh.multiply(rightHigh);
  1394. let productMid = leftHigh.multiply(rightLow);
  1395. const productMid2 = leftLow.multiply(rightHigh);
  1396. let productLow = leftLow.multiply(rightLow);
  1397. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  1398. productMid = new Long(productMid.getLowBits(), 0)
  1399. .add(productMid2)
  1400. .add(productLow.shiftRightUnsigned(32));
  1401. productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
  1402. productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
  1403. return { high: productHigh, low: productLow };
  1404. }
  1405. function lessThan(left, right) {
  1406. const uhleft = left.high >>> 0;
  1407. const uhright = right.high >>> 0;
  1408. if (uhleft < uhright) {
  1409. return true;
  1410. }
  1411. else if (uhleft === uhright) {
  1412. const ulleft = left.low >>> 0;
  1413. const ulright = right.low >>> 0;
  1414. if (ulleft < ulright)
  1415. return true;
  1416. }
  1417. return false;
  1418. }
  1419. function invalidErr(string, message) {
  1420. throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
  1421. }
  1422. class Decimal128 extends BSONValue {
  1423. get _bsontype() {
  1424. return 'Decimal128';
  1425. }
  1426. constructor(bytes) {
  1427. super();
  1428. if (typeof bytes === 'string') {
  1429. this.bytes = Decimal128.fromString(bytes).bytes;
  1430. }
  1431. else if (isUint8Array(bytes)) {
  1432. if (bytes.byteLength !== 16) {
  1433. throw new BSONError('Decimal128 must take a Buffer of 16 bytes');
  1434. }
  1435. this.bytes = bytes;
  1436. }
  1437. else {
  1438. throw new BSONError('Decimal128 must take a Buffer or string');
  1439. }
  1440. }
  1441. static fromString(representation) {
  1442. return Decimal128._fromString(representation, { allowRounding: false });
  1443. }
  1444. static fromStringWithRounding(representation) {
  1445. return Decimal128._fromString(representation, { allowRounding: true });
  1446. }
  1447. static _fromString(representation, options) {
  1448. let isNegative = false;
  1449. let sawSign = false;
  1450. let sawRadix = false;
  1451. let foundNonZero = false;
  1452. let significantDigits = 0;
  1453. let nDigitsRead = 0;
  1454. let nDigits = 0;
  1455. let radixPosition = 0;
  1456. let firstNonZero = 0;
  1457. const digits = [0];
  1458. let nDigitsStored = 0;
  1459. let digitsInsert = 0;
  1460. let lastDigit = 0;
  1461. let exponent = 0;
  1462. let significandHigh = new Long(0, 0);
  1463. let significandLow = new Long(0, 0);
  1464. let biasedExponent = 0;
  1465. let index = 0;
  1466. if (representation.length >= 7000) {
  1467. throw new BSONError('' + representation + ' not a valid Decimal128 string');
  1468. }
  1469. const stringMatch = representation.match(PARSE_STRING_REGEXP);
  1470. const infMatch = representation.match(PARSE_INF_REGEXP);
  1471. const nanMatch = representation.match(PARSE_NAN_REGEXP);
  1472. if ((!stringMatch && !infMatch && !nanMatch) || representation.length === 0) {
  1473. throw new BSONError('' + representation + ' not a valid Decimal128 string');
  1474. }
  1475. if (stringMatch) {
  1476. const unsignedNumber = stringMatch[2];
  1477. const e = stringMatch[4];
  1478. const expSign = stringMatch[5];
  1479. const expNumber = stringMatch[6];
  1480. if (e && expNumber === undefined)
  1481. invalidErr(representation, 'missing exponent power');
  1482. if (e && unsignedNumber === undefined)
  1483. invalidErr(representation, 'missing exponent base');
  1484. if (e === undefined && (expSign || expNumber)) {
  1485. invalidErr(representation, 'missing e before exponent');
  1486. }
  1487. }
  1488. if (representation[index] === '+' || representation[index] === '-') {
  1489. sawSign = true;
  1490. isNegative = representation[index++] === '-';
  1491. }
  1492. if (!isDigit(representation[index]) && representation[index] !== '.') {
  1493. if (representation[index] === 'i' || representation[index] === 'I') {
  1494. return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
  1495. }
  1496. else if (representation[index] === 'N') {
  1497. return new Decimal128(NAN_BUFFER);
  1498. }
  1499. }
  1500. while (isDigit(representation[index]) || representation[index] === '.') {
  1501. if (representation[index] === '.') {
  1502. if (sawRadix)
  1503. invalidErr(representation, 'contains multiple periods');
  1504. sawRadix = true;
  1505. index = index + 1;
  1506. continue;
  1507. }
  1508. if (nDigitsStored < MAX_DIGITS) {
  1509. if (representation[index] !== '0' || foundNonZero) {
  1510. if (!foundNonZero) {
  1511. firstNonZero = nDigitsRead;
  1512. }
  1513. foundNonZero = true;
  1514. digits[digitsInsert++] = parseInt(representation[index], 10);
  1515. nDigitsStored = nDigitsStored + 1;
  1516. }
  1517. }
  1518. if (foundNonZero)
  1519. nDigits = nDigits + 1;
  1520. if (sawRadix)
  1521. radixPosition = radixPosition + 1;
  1522. nDigitsRead = nDigitsRead + 1;
  1523. index = index + 1;
  1524. }
  1525. if (sawRadix && !nDigitsRead)
  1526. throw new BSONError('' + representation + ' not a valid Decimal128 string');
  1527. if (representation[index] === 'e' || representation[index] === 'E') {
  1528. const match = representation.substr(++index).match(EXPONENT_REGEX);
  1529. if (!match || !match[2])
  1530. return new Decimal128(NAN_BUFFER);
  1531. exponent = parseInt(match[0], 10);
  1532. index = index + match[0].length;
  1533. }
  1534. if (representation[index])
  1535. return new Decimal128(NAN_BUFFER);
  1536. if (!nDigitsStored) {
  1537. digits[0] = 0;
  1538. nDigits = 1;
  1539. nDigitsStored = 1;
  1540. significantDigits = 0;
  1541. }
  1542. else {
  1543. lastDigit = nDigitsStored - 1;
  1544. significantDigits = nDigits;
  1545. if (significantDigits !== 1) {
  1546. while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === '0') {
  1547. significantDigits = significantDigits - 1;
  1548. }
  1549. }
  1550. }
  1551. if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
  1552. exponent = EXPONENT_MIN;
  1553. }
  1554. else {
  1555. exponent = exponent - radixPosition;
  1556. }
  1557. while (exponent > EXPONENT_MAX) {
  1558. lastDigit = lastDigit + 1;
  1559. if (lastDigit >= MAX_DIGITS) {
  1560. if (significantDigits === 0) {
  1561. exponent = EXPONENT_MAX;
  1562. break;
  1563. }
  1564. invalidErr(representation, 'overflow');
  1565. }
  1566. exponent = exponent - 1;
  1567. }
  1568. if (options.allowRounding) {
  1569. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  1570. if (lastDigit === 0 && significantDigits < nDigitsStored) {
  1571. exponent = EXPONENT_MIN;
  1572. significantDigits = 0;
  1573. break;
  1574. }
  1575. if (nDigitsStored < nDigits) {
  1576. nDigits = nDigits - 1;
  1577. }
  1578. else {
  1579. lastDigit = lastDigit - 1;
  1580. }
  1581. if (exponent < EXPONENT_MAX) {
  1582. exponent = exponent + 1;
  1583. }
  1584. else {
  1585. const digitsString = digits.join('');
  1586. if (digitsString.match(/^0+$/)) {
  1587. exponent = EXPONENT_MAX;
  1588. break;
  1589. }
  1590. invalidErr(representation, 'overflow');
  1591. }
  1592. }
  1593. if (lastDigit + 1 < significantDigits) {
  1594. let endOfString = nDigitsRead;
  1595. if (sawRadix) {
  1596. firstNonZero = firstNonZero + 1;
  1597. endOfString = endOfString + 1;
  1598. }
  1599. if (sawSign) {
  1600. firstNonZero = firstNonZero + 1;
  1601. endOfString = endOfString + 1;
  1602. }
  1603. const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
  1604. let roundBit = 0;
  1605. if (roundDigit >= 5) {
  1606. roundBit = 1;
  1607. if (roundDigit === 5) {
  1608. roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
  1609. for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
  1610. if (parseInt(representation[i], 10)) {
  1611. roundBit = 1;
  1612. break;
  1613. }
  1614. }
  1615. }
  1616. }
  1617. if (roundBit) {
  1618. let dIdx = lastDigit;
  1619. for (; dIdx >= 0; dIdx--) {
  1620. if (++digits[dIdx] > 9) {
  1621. digits[dIdx] = 0;
  1622. if (dIdx === 0) {
  1623. if (exponent < EXPONENT_MAX) {
  1624. exponent = exponent + 1;
  1625. digits[dIdx] = 1;
  1626. }
  1627. else {
  1628. return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
  1629. }
  1630. }
  1631. }
  1632. else {
  1633. break;
  1634. }
  1635. }
  1636. }
  1637. }
  1638. }
  1639. else {
  1640. while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
  1641. if (lastDigit === 0) {
  1642. if (significantDigits === 0) {
  1643. exponent = EXPONENT_MIN;
  1644. break;
  1645. }
  1646. invalidErr(representation, 'exponent underflow');
  1647. }
  1648. if (nDigitsStored < nDigits) {
  1649. if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== '0' &&
  1650. significantDigits !== 0) {
  1651. invalidErr(representation, 'inexact rounding');
  1652. }
  1653. nDigits = nDigits - 1;
  1654. }
  1655. else {
  1656. if (digits[lastDigit] !== 0) {
  1657. invalidErr(representation, 'inexact rounding');
  1658. }
  1659. lastDigit = lastDigit - 1;
  1660. }
  1661. if (exponent < EXPONENT_MAX) {
  1662. exponent = exponent + 1;
  1663. }
  1664. else {
  1665. invalidErr(representation, 'overflow');
  1666. }
  1667. }
  1668. if (lastDigit + 1 < significantDigits) {
  1669. if (sawRadix) {
  1670. firstNonZero = firstNonZero + 1;
  1671. }
  1672. if (sawSign) {
  1673. firstNonZero = firstNonZero + 1;
  1674. }
  1675. const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
  1676. if (roundDigit !== 0) {
  1677. invalidErr(representation, 'inexact rounding');
  1678. }
  1679. }
  1680. }
  1681. significandHigh = Long.fromNumber(0);
  1682. significandLow = Long.fromNumber(0);
  1683. if (significantDigits === 0) {
  1684. significandHigh = Long.fromNumber(0);
  1685. significandLow = Long.fromNumber(0);
  1686. }
  1687. else if (lastDigit < 17) {
  1688. let dIdx = 0;
  1689. significandLow = Long.fromNumber(digits[dIdx++]);
  1690. significandHigh = new Long(0, 0);
  1691. for (; dIdx <= lastDigit; dIdx++) {
  1692. significandLow = significandLow.multiply(Long.fromNumber(10));
  1693. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  1694. }
  1695. }
  1696. else {
  1697. let dIdx = 0;
  1698. significandHigh = Long.fromNumber(digits[dIdx++]);
  1699. for (; dIdx <= lastDigit - 17; dIdx++) {
  1700. significandHigh = significandHigh.multiply(Long.fromNumber(10));
  1701. significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
  1702. }
  1703. significandLow = Long.fromNumber(digits[dIdx++]);
  1704. for (; dIdx <= lastDigit; dIdx++) {
  1705. significandLow = significandLow.multiply(Long.fromNumber(10));
  1706. significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
  1707. }
  1708. }
  1709. const significand = multiply64x2(significandHigh, Long.fromString('100000000000000000'));
  1710. significand.low = significand.low.add(significandLow);
  1711. if (lessThan(significand.low, significandLow)) {
  1712. significand.high = significand.high.add(Long.fromNumber(1));
  1713. }
  1714. biasedExponent = exponent + EXPONENT_BIAS;
  1715. const dec = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
  1716. if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
  1717. dec.high = dec.high.or(Long.fromNumber(0x3).shiftLeft(61));
  1718. dec.high = dec.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(0x3fff).shiftLeft(47)));
  1719. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x7fffffffffff)));
  1720. }
  1721. else {
  1722. dec.high = dec.high.or(Long.fromNumber(biasedExponent & 0x3fff).shiftLeft(49));
  1723. dec.high = dec.high.or(significand.high.and(Long.fromNumber(0x1ffffffffffff)));
  1724. }
  1725. dec.low = significand.low;
  1726. if (isNegative) {
  1727. dec.high = dec.high.or(Long.fromString('9223372036854775808'));
  1728. }
  1729. const buffer = ByteUtils.allocate(16);
  1730. index = 0;
  1731. buffer[index++] = dec.low.low & 0xff;
  1732. buffer[index++] = (dec.low.low >> 8) & 0xff;
  1733. buffer[index++] = (dec.low.low >> 16) & 0xff;
  1734. buffer[index++] = (dec.low.low >> 24) & 0xff;
  1735. buffer[index++] = dec.low.high & 0xff;
  1736. buffer[index++] = (dec.low.high >> 8) & 0xff;
  1737. buffer[index++] = (dec.low.high >> 16) & 0xff;
  1738. buffer[index++] = (dec.low.high >> 24) & 0xff;
  1739. buffer[index++] = dec.high.low & 0xff;
  1740. buffer[index++] = (dec.high.low >> 8) & 0xff;
  1741. buffer[index++] = (dec.high.low >> 16) & 0xff;
  1742. buffer[index++] = (dec.high.low >> 24) & 0xff;
  1743. buffer[index++] = dec.high.high & 0xff;
  1744. buffer[index++] = (dec.high.high >> 8) & 0xff;
  1745. buffer[index++] = (dec.high.high >> 16) & 0xff;
  1746. buffer[index++] = (dec.high.high >> 24) & 0xff;
  1747. return new Decimal128(buffer);
  1748. }
  1749. toString() {
  1750. let biased_exponent;
  1751. let significand_digits = 0;
  1752. const significand = new Array(36);
  1753. for (let i = 0; i < significand.length; i++)
  1754. significand[i] = 0;
  1755. let index = 0;
  1756. let is_zero = false;
  1757. let significand_msb;
  1758. let significand128 = { parts: [0, 0, 0, 0] };
  1759. let j, k;
  1760. const string = [];
  1761. index = 0;
  1762. const buffer = this.bytes;
  1763. const low = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  1764. const midl = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  1765. const midh = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  1766. const high = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  1767. index = 0;
  1768. const dec = {
  1769. low: new Long(low, midl),
  1770. high: new Long(midh, high)
  1771. };
  1772. if (dec.high.lessThan(Long.ZERO)) {
  1773. string.push('-');
  1774. }
  1775. const combination = (high >> 26) & COMBINATION_MASK;
  1776. if (combination >> 3 === 3) {
  1777. if (combination === COMBINATION_INFINITY) {
  1778. return string.join('') + 'Infinity';
  1779. }
  1780. else if (combination === COMBINATION_NAN) {
  1781. return 'NaN';
  1782. }
  1783. else {
  1784. biased_exponent = (high >> 15) & EXPONENT_MASK;
  1785. significand_msb = 0x08 + ((high >> 14) & 0x01);
  1786. }
  1787. }
  1788. else {
  1789. significand_msb = (high >> 14) & 0x07;
  1790. biased_exponent = (high >> 17) & EXPONENT_MASK;
  1791. }
  1792. const exponent = biased_exponent - EXPONENT_BIAS;
  1793. significand128.parts[0] = (high & 0x3fff) + ((significand_msb & 0xf) << 14);
  1794. significand128.parts[1] = midh;
  1795. significand128.parts[2] = midl;
  1796. significand128.parts[3] = low;
  1797. if (significand128.parts[0] === 0 &&
  1798. significand128.parts[1] === 0 &&
  1799. significand128.parts[2] === 0 &&
  1800. significand128.parts[3] === 0) {
  1801. is_zero = true;
  1802. }
  1803. else {
  1804. for (k = 3; k >= 0; k--) {
  1805. let least_digits = 0;
  1806. const result = divideu128(significand128);
  1807. significand128 = result.quotient;
  1808. least_digits = result.rem.low;
  1809. if (!least_digits)
  1810. continue;
  1811. for (j = 8; j >= 0; j--) {
  1812. significand[k * 9 + j] = least_digits % 10;
  1813. least_digits = Math.floor(least_digits / 10);
  1814. }
  1815. }
  1816. }
  1817. if (is_zero) {
  1818. significand_digits = 1;
  1819. significand[index] = 0;
  1820. }
  1821. else {
  1822. significand_digits = 36;
  1823. while (!significand[index]) {
  1824. significand_digits = significand_digits - 1;
  1825. index = index + 1;
  1826. }
  1827. }
  1828. const scientific_exponent = significand_digits - 1 + exponent;
  1829. if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
  1830. if (significand_digits > 34) {
  1831. string.push(`${0}`);
  1832. if (exponent > 0)
  1833. string.push(`E+${exponent}`);
  1834. else if (exponent < 0)
  1835. string.push(`E${exponent}`);
  1836. return string.join('');
  1837. }
  1838. string.push(`${significand[index++]}`);
  1839. significand_digits = significand_digits - 1;
  1840. if (significand_digits) {
  1841. string.push('.');
  1842. }
  1843. for (let i = 0; i < significand_digits; i++) {
  1844. string.push(`${significand[index++]}`);
  1845. }
  1846. string.push('E');
  1847. if (scientific_exponent > 0) {
  1848. string.push(`+${scientific_exponent}`);
  1849. }
  1850. else {
  1851. string.push(`${scientific_exponent}`);
  1852. }
  1853. }
  1854. else {
  1855. if (exponent >= 0) {
  1856. for (let i = 0; i < significand_digits; i++) {
  1857. string.push(`${significand[index++]}`);
  1858. }
  1859. }
  1860. else {
  1861. let radix_position = significand_digits + exponent;
  1862. if (radix_position > 0) {
  1863. for (let i = 0; i < radix_position; i++) {
  1864. string.push(`${significand[index++]}`);
  1865. }
  1866. }
  1867. else {
  1868. string.push('0');
  1869. }
  1870. string.push('.');
  1871. while (radix_position++ < 0) {
  1872. string.push('0');
  1873. }
  1874. for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
  1875. string.push(`${significand[index++]}`);
  1876. }
  1877. }
  1878. }
  1879. return string.join('');
  1880. }
  1881. toJSON() {
  1882. return { $numberDecimal: this.toString() };
  1883. }
  1884. toExtendedJSON() {
  1885. return { $numberDecimal: this.toString() };
  1886. }
  1887. static fromExtendedJSON(doc) {
  1888. return Decimal128.fromString(doc.$numberDecimal);
  1889. }
  1890. [Symbol.for('nodejs.util.inspect.custom')]() {
  1891. return this.inspect();
  1892. }
  1893. inspect() {
  1894. return `new Decimal128("${this.toString()}")`;
  1895. }
  1896. }
  1897. class Double extends BSONValue {
  1898. get _bsontype() {
  1899. return 'Double';
  1900. }
  1901. constructor(value) {
  1902. super();
  1903. if (value instanceof Number) {
  1904. value = value.valueOf();
  1905. }
  1906. this.value = +value;
  1907. }
  1908. valueOf() {
  1909. return this.value;
  1910. }
  1911. toJSON() {
  1912. return this.value;
  1913. }
  1914. toString(radix) {
  1915. return this.value.toString(radix);
  1916. }
  1917. toExtendedJSON(options) {
  1918. if (options && (options.legacy || (options.relaxed && isFinite(this.value)))) {
  1919. return this.value;
  1920. }
  1921. if (Object.is(Math.sign(this.value), -0)) {
  1922. return { $numberDouble: '-0.0' };
  1923. }
  1924. return {
  1925. $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
  1926. };
  1927. }
  1928. static fromExtendedJSON(doc, options) {
  1929. const doubleValue = parseFloat(doc.$numberDouble);
  1930. return options && options.relaxed ? doubleValue : new Double(doubleValue);
  1931. }
  1932. [Symbol.for('nodejs.util.inspect.custom')]() {
  1933. return this.inspect();
  1934. }
  1935. inspect() {
  1936. const eJSON = this.toExtendedJSON();
  1937. return `new Double(${eJSON.$numberDouble})`;
  1938. }
  1939. }
  1940. class Int32 extends BSONValue {
  1941. get _bsontype() {
  1942. return 'Int32';
  1943. }
  1944. constructor(value) {
  1945. super();
  1946. if (value instanceof Number) {
  1947. value = value.valueOf();
  1948. }
  1949. this.value = +value | 0;
  1950. }
  1951. valueOf() {
  1952. return this.value;
  1953. }
  1954. toString(radix) {
  1955. return this.value.toString(radix);
  1956. }
  1957. toJSON() {
  1958. return this.value;
  1959. }
  1960. toExtendedJSON(options) {
  1961. if (options && (options.relaxed || options.legacy))
  1962. return this.value;
  1963. return { $numberInt: this.value.toString() };
  1964. }
  1965. static fromExtendedJSON(doc, options) {
  1966. return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
  1967. }
  1968. [Symbol.for('nodejs.util.inspect.custom')]() {
  1969. return this.inspect();
  1970. }
  1971. inspect() {
  1972. return `new Int32(${this.valueOf()})`;
  1973. }
  1974. }
  1975. class MaxKey extends BSONValue {
  1976. get _bsontype() {
  1977. return 'MaxKey';
  1978. }
  1979. toExtendedJSON() {
  1980. return { $maxKey: 1 };
  1981. }
  1982. static fromExtendedJSON() {
  1983. return new MaxKey();
  1984. }
  1985. [Symbol.for('nodejs.util.inspect.custom')]() {
  1986. return this.inspect();
  1987. }
  1988. inspect() {
  1989. return 'new MaxKey()';
  1990. }
  1991. }
  1992. class MinKey extends BSONValue {
  1993. get _bsontype() {
  1994. return 'MinKey';
  1995. }
  1996. toExtendedJSON() {
  1997. return { $minKey: 1 };
  1998. }
  1999. static fromExtendedJSON() {
  2000. return new MinKey();
  2001. }
  2002. [Symbol.for('nodejs.util.inspect.custom')]() {
  2003. return this.inspect();
  2004. }
  2005. inspect() {
  2006. return 'new MinKey()';
  2007. }
  2008. }
  2009. const checkForHexRegExp = new RegExp('^[0-9a-fA-F]{24}$');
  2010. let PROCESS_UNIQUE = null;
  2011. const kId = Symbol('id');
  2012. class ObjectId extends BSONValue {
  2013. get _bsontype() {
  2014. return 'ObjectId';
  2015. }
  2016. constructor(inputId) {
  2017. super();
  2018. let workingId;
  2019. if (typeof inputId === 'object' && inputId && 'id' in inputId) {
  2020. if (typeof inputId.id !== 'string' && !ArrayBuffer.isView(inputId.id)) {
  2021. throw new BSONError('Argument passed in must have an id that is of type string or Buffer');
  2022. }
  2023. if ('toHexString' in inputId && typeof inputId.toHexString === 'function') {
  2024. workingId = ByteUtils.fromHex(inputId.toHexString());
  2025. }
  2026. else {
  2027. workingId = inputId.id;
  2028. }
  2029. }
  2030. else {
  2031. workingId = inputId;
  2032. }
  2033. if (workingId == null || typeof workingId === 'number') {
  2034. this[kId] = ObjectId.generate(typeof workingId === 'number' ? workingId : undefined);
  2035. }
  2036. else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
  2037. this[kId] = ByteUtils.toLocalBufferType(workingId);
  2038. }
  2039. else if (typeof workingId === 'string') {
  2040. if (workingId.length === 12) {
  2041. const bytes = ByteUtils.fromUTF8(workingId);
  2042. if (bytes.byteLength === 12) {
  2043. this[kId] = bytes;
  2044. }
  2045. else {
  2046. throw new BSONError('Argument passed in must be a string of 12 bytes');
  2047. }
  2048. }
  2049. else if (workingId.length === 24 && checkForHexRegExp.test(workingId)) {
  2050. this[kId] = ByteUtils.fromHex(workingId);
  2051. }
  2052. else {
  2053. throw new BSONError('Argument passed in must be a string of 12 bytes or a string of 24 hex characters or an integer');
  2054. }
  2055. }
  2056. else {
  2057. throw new BSONError('Argument passed in does not match the accepted types');
  2058. }
  2059. if (ObjectId.cacheHexString) {
  2060. this.__id = ByteUtils.toHex(this.id);
  2061. }
  2062. }
  2063. get id() {
  2064. return this[kId];
  2065. }
  2066. set id(value) {
  2067. this[kId] = value;
  2068. if (ObjectId.cacheHexString) {
  2069. this.__id = ByteUtils.toHex(value);
  2070. }
  2071. }
  2072. toHexString() {
  2073. if (ObjectId.cacheHexString && this.__id) {
  2074. return this.__id;
  2075. }
  2076. const hexString = ByteUtils.toHex(this.id);
  2077. if (ObjectId.cacheHexString && !this.__id) {
  2078. this.__id = hexString;
  2079. }
  2080. return hexString;
  2081. }
  2082. static getInc() {
  2083. return (ObjectId.index = (ObjectId.index + 1) % 0xffffff);
  2084. }
  2085. static generate(time) {
  2086. if ('number' !== typeof time) {
  2087. time = Math.floor(Date.now() / 1000);
  2088. }
  2089. const inc = ObjectId.getInc();
  2090. const buffer = ByteUtils.allocate(12);
  2091. BSONDataView.fromUint8Array(buffer).setUint32(0, time, false);
  2092. if (PROCESS_UNIQUE === null) {
  2093. PROCESS_UNIQUE = ByteUtils.randomBytes(5);
  2094. }
  2095. buffer[4] = PROCESS_UNIQUE[0];
  2096. buffer[5] = PROCESS_UNIQUE[1];
  2097. buffer[6] = PROCESS_UNIQUE[2];
  2098. buffer[7] = PROCESS_UNIQUE[3];
  2099. buffer[8] = PROCESS_UNIQUE[4];
  2100. buffer[11] = inc & 0xff;
  2101. buffer[10] = (inc >> 8) & 0xff;
  2102. buffer[9] = (inc >> 16) & 0xff;
  2103. return buffer;
  2104. }
  2105. toString(encoding) {
  2106. if (encoding === 'base64')
  2107. return ByteUtils.toBase64(this.id);
  2108. if (encoding === 'hex')
  2109. return this.toHexString();
  2110. return this.toHexString();
  2111. }
  2112. toJSON() {
  2113. return this.toHexString();
  2114. }
  2115. equals(otherId) {
  2116. if (otherId === undefined || otherId === null) {
  2117. return false;
  2118. }
  2119. if (otherId instanceof ObjectId) {
  2120. return this[kId][11] === otherId[kId][11] && ByteUtils.equals(this[kId], otherId[kId]);
  2121. }
  2122. if (typeof otherId === 'string' &&
  2123. ObjectId.isValid(otherId) &&
  2124. otherId.length === 12 &&
  2125. isUint8Array(this.id)) {
  2126. return ByteUtils.equals(this.id, ByteUtils.fromISO88591(otherId));
  2127. }
  2128. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 24) {
  2129. return otherId.toLowerCase() === this.toHexString();
  2130. }
  2131. if (typeof otherId === 'string' && ObjectId.isValid(otherId) && otherId.length === 12) {
  2132. return ByteUtils.equals(ByteUtils.fromUTF8(otherId), this.id);
  2133. }
  2134. if (typeof otherId === 'object' &&
  2135. 'toHexString' in otherId &&
  2136. typeof otherId.toHexString === 'function') {
  2137. const otherIdString = otherId.toHexString();
  2138. const thisIdString = this.toHexString().toLowerCase();
  2139. return typeof otherIdString === 'string' && otherIdString.toLowerCase() === thisIdString;
  2140. }
  2141. return false;
  2142. }
  2143. getTimestamp() {
  2144. const timestamp = new Date();
  2145. const time = BSONDataView.fromUint8Array(this.id).getUint32(0, false);
  2146. timestamp.setTime(Math.floor(time) * 1000);
  2147. return timestamp;
  2148. }
  2149. static createPk() {
  2150. return new ObjectId();
  2151. }
  2152. static createFromTime(time) {
  2153. const buffer = ByteUtils.fromNumberArray([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]);
  2154. BSONDataView.fromUint8Array(buffer).setUint32(0, time, false);
  2155. return new ObjectId(buffer);
  2156. }
  2157. static createFromHexString(hexString) {
  2158. if (hexString?.length !== 24) {
  2159. throw new BSONError('hex string must be 24 characters');
  2160. }
  2161. return new ObjectId(ByteUtils.fromHex(hexString));
  2162. }
  2163. static createFromBase64(base64) {
  2164. if (base64?.length !== 16) {
  2165. throw new BSONError('base64 string must be 16 characters');
  2166. }
  2167. return new ObjectId(ByteUtils.fromBase64(base64));
  2168. }
  2169. static isValid(id) {
  2170. if (id == null)
  2171. return false;
  2172. try {
  2173. new ObjectId(id);
  2174. return true;
  2175. }
  2176. catch {
  2177. return false;
  2178. }
  2179. }
  2180. toExtendedJSON() {
  2181. if (this.toHexString)
  2182. return { $oid: this.toHexString() };
  2183. return { $oid: this.toString('hex') };
  2184. }
  2185. static fromExtendedJSON(doc) {
  2186. return new ObjectId(doc.$oid);
  2187. }
  2188. [Symbol.for('nodejs.util.inspect.custom')]() {
  2189. return this.inspect();
  2190. }
  2191. inspect() {
  2192. return `new ObjectId("${this.toHexString()}")`;
  2193. }
  2194. }
  2195. ObjectId.index = Math.floor(Math.random() * 0xffffff);
  2196. function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) {
  2197. let totalLength = 4 + 1;
  2198. if (Array.isArray(object)) {
  2199. for (let i = 0; i < object.length; i++) {
  2200. totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
  2201. }
  2202. }
  2203. else {
  2204. if (typeof object?.toBSON === 'function') {
  2205. object = object.toBSON();
  2206. }
  2207. for (const key of Object.keys(object)) {
  2208. totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
  2209. }
  2210. }
  2211. return totalLength;
  2212. }
  2213. function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) {
  2214. if (typeof value?.toBSON === 'function') {
  2215. value = value.toBSON();
  2216. }
  2217. switch (typeof value) {
  2218. case 'string':
  2219. return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
  2220. case 'number':
  2221. if (Math.floor(value) === value &&
  2222. value >= JS_INT_MIN &&
  2223. value <= JS_INT_MAX) {
  2224. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
  2225. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1);
  2226. }
  2227. else {
  2228. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2229. }
  2230. }
  2231. else {
  2232. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2233. }
  2234. case 'undefined':
  2235. if (isArray || !ignoreUndefined)
  2236. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
  2237. return 0;
  2238. case 'boolean':
  2239. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1);
  2240. case 'object':
  2241. if (value != null &&
  2242. typeof value._bsontype === 'string' &&
  2243. value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
  2244. throw new BSONVersionError();
  2245. }
  2246. else if (value == null || value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
  2247. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
  2248. }
  2249. else if (value._bsontype === 'ObjectId') {
  2250. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1);
  2251. }
  2252. else if (value instanceof Date || isDate(value)) {
  2253. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2254. }
  2255. else if (ArrayBuffer.isView(value) ||
  2256. value instanceof ArrayBuffer ||
  2257. isAnyArrayBuffer(value)) {
  2258. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength);
  2259. }
  2260. else if (value._bsontype === 'Long' ||
  2261. value._bsontype === 'Double' ||
  2262. value._bsontype === 'Timestamp') {
  2263. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
  2264. }
  2265. else if (value._bsontype === 'Decimal128') {
  2266. return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1);
  2267. }
  2268. else if (value._bsontype === 'Code') {
  2269. if (value.scope != null && Object.keys(value.scope).length > 0) {
  2270. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2271. 1 +
  2272. 4 +
  2273. 4 +
  2274. ByteUtils.utf8ByteLength(value.code.toString()) +
  2275. 1 +
  2276. internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined));
  2277. }
  2278. else {
  2279. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2280. 1 +
  2281. 4 +
  2282. ByteUtils.utf8ByteLength(value.code.toString()) +
  2283. 1);
  2284. }
  2285. }
  2286. else if (value._bsontype === 'Binary') {
  2287. const binary = value;
  2288. if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  2289. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2290. (binary.position + 1 + 4 + 1 + 4));
  2291. }
  2292. else {
  2293. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1));
  2294. }
  2295. }
  2296. else if (value._bsontype === 'Symbol') {
  2297. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2298. ByteUtils.utf8ByteLength(value.value) +
  2299. 4 +
  2300. 1 +
  2301. 1);
  2302. }
  2303. else if (value._bsontype === 'DBRef') {
  2304. const ordered_values = Object.assign({
  2305. $ref: value.collection,
  2306. $id: value.oid
  2307. }, value.fields);
  2308. if (value.db != null) {
  2309. ordered_values['$db'] = value.db;
  2310. }
  2311. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2312. 1 +
  2313. internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined));
  2314. }
  2315. else if (value instanceof RegExp || isRegExp(value)) {
  2316. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2317. 1 +
  2318. ByteUtils.utf8ByteLength(value.source) +
  2319. 1 +
  2320. (value.global ? 1 : 0) +
  2321. (value.ignoreCase ? 1 : 0) +
  2322. (value.multiline ? 1 : 0) +
  2323. 1);
  2324. }
  2325. else if (value._bsontype === 'BSONRegExp') {
  2326. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2327. 1 +
  2328. ByteUtils.utf8ByteLength(value.pattern) +
  2329. 1 +
  2330. ByteUtils.utf8ByteLength(value.options) +
  2331. 1);
  2332. }
  2333. else {
  2334. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2335. internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) +
  2336. 1);
  2337. }
  2338. case 'function':
  2339. if (serializeFunctions) {
  2340. return ((name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) +
  2341. 1 +
  2342. 4 +
  2343. ByteUtils.utf8ByteLength(value.toString()) +
  2344. 1);
  2345. }
  2346. }
  2347. return 0;
  2348. }
  2349. function alphabetize(str) {
  2350. return str.split('').sort().join('');
  2351. }
  2352. class BSONRegExp extends BSONValue {
  2353. get _bsontype() {
  2354. return 'BSONRegExp';
  2355. }
  2356. constructor(pattern, options) {
  2357. super();
  2358. this.pattern = pattern;
  2359. this.options = alphabetize(options ?? '');
  2360. if (this.pattern.indexOf('\x00') !== -1) {
  2361. throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
  2362. }
  2363. if (this.options.indexOf('\x00') !== -1) {
  2364. throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
  2365. }
  2366. for (let i = 0; i < this.options.length; i++) {
  2367. if (!(this.options[i] === 'i' ||
  2368. this.options[i] === 'm' ||
  2369. this.options[i] === 'x' ||
  2370. this.options[i] === 'l' ||
  2371. this.options[i] === 's' ||
  2372. this.options[i] === 'u')) {
  2373. throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
  2374. }
  2375. }
  2376. }
  2377. static parseOptions(options) {
  2378. return options ? options.split('').sort().join('') : '';
  2379. }
  2380. toExtendedJSON(options) {
  2381. options = options || {};
  2382. if (options.legacy) {
  2383. return { $regex: this.pattern, $options: this.options };
  2384. }
  2385. return { $regularExpression: { pattern: this.pattern, options: this.options } };
  2386. }
  2387. static fromExtendedJSON(doc) {
  2388. if ('$regex' in doc) {
  2389. if (typeof doc.$regex !== 'string') {
  2390. if (doc.$regex._bsontype === 'BSONRegExp') {
  2391. return doc;
  2392. }
  2393. }
  2394. else {
  2395. return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
  2396. }
  2397. }
  2398. if ('$regularExpression' in doc) {
  2399. return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
  2400. }
  2401. throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
  2402. }
  2403. [Symbol.for('nodejs.util.inspect.custom')]() {
  2404. return this.inspect();
  2405. }
  2406. inspect() {
  2407. return `new BSONRegExp(${JSON.stringify(this.pattern)}, ${JSON.stringify(this.options)})`;
  2408. }
  2409. }
  2410. class BSONSymbol extends BSONValue {
  2411. get _bsontype() {
  2412. return 'BSONSymbol';
  2413. }
  2414. constructor(value) {
  2415. super();
  2416. this.value = value;
  2417. }
  2418. valueOf() {
  2419. return this.value;
  2420. }
  2421. toString() {
  2422. return this.value;
  2423. }
  2424. inspect() {
  2425. return `new BSONSymbol("${this.value}")`;
  2426. }
  2427. toJSON() {
  2428. return this.value;
  2429. }
  2430. toExtendedJSON() {
  2431. return { $symbol: this.value };
  2432. }
  2433. static fromExtendedJSON(doc) {
  2434. return new BSONSymbol(doc.$symbol);
  2435. }
  2436. [Symbol.for('nodejs.util.inspect.custom')]() {
  2437. return this.inspect();
  2438. }
  2439. }
  2440. const LongWithoutOverridesClass = Long;
  2441. class Timestamp extends LongWithoutOverridesClass {
  2442. get _bsontype() {
  2443. return 'Timestamp';
  2444. }
  2445. constructor(low) {
  2446. if (low == null) {
  2447. super(0, 0, true);
  2448. }
  2449. else if (typeof low === 'bigint') {
  2450. super(low, true);
  2451. }
  2452. else if (Long.isLong(low)) {
  2453. super(low.low, low.high, true);
  2454. }
  2455. else if (typeof low === 'object' && 't' in low && 'i' in low) {
  2456. if (typeof low.t !== 'number' && (typeof low.t !== 'object' || low.t._bsontype !== 'Int32')) {
  2457. throw new BSONError('Timestamp constructed from { t, i } must provide t as a number');
  2458. }
  2459. if (typeof low.i !== 'number' && (typeof low.i !== 'object' || low.i._bsontype !== 'Int32')) {
  2460. throw new BSONError('Timestamp constructed from { t, i } must provide i as a number');
  2461. }
  2462. const t = Number(low.t);
  2463. const i = Number(low.i);
  2464. if (t < 0 || Number.isNaN(t)) {
  2465. throw new BSONError('Timestamp constructed from { t, i } must provide a positive t');
  2466. }
  2467. if (i < 0 || Number.isNaN(i)) {
  2468. throw new BSONError('Timestamp constructed from { t, i } must provide a positive i');
  2469. }
  2470. if (t > 4294967295) {
  2471. throw new BSONError('Timestamp constructed from { t, i } must provide t equal or less than uint32 max');
  2472. }
  2473. if (i > 4294967295) {
  2474. throw new BSONError('Timestamp constructed from { t, i } must provide i equal or less than uint32 max');
  2475. }
  2476. super(i, t, true);
  2477. }
  2478. else {
  2479. throw new BSONError('A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }');
  2480. }
  2481. }
  2482. toJSON() {
  2483. return {
  2484. $timestamp: this.toString()
  2485. };
  2486. }
  2487. static fromInt(value) {
  2488. return new Timestamp(Long.fromInt(value, true));
  2489. }
  2490. static fromNumber(value) {
  2491. return new Timestamp(Long.fromNumber(value, true));
  2492. }
  2493. static fromBits(lowBits, highBits) {
  2494. return new Timestamp({ i: lowBits, t: highBits });
  2495. }
  2496. static fromString(str, optRadix) {
  2497. return new Timestamp(Long.fromString(str, true, optRadix));
  2498. }
  2499. toExtendedJSON() {
  2500. return { $timestamp: { t: this.high >>> 0, i: this.low >>> 0 } };
  2501. }
  2502. static fromExtendedJSON(doc) {
  2503. const i = Long.isLong(doc.$timestamp.i)
  2504. ? doc.$timestamp.i.getLowBitsUnsigned()
  2505. : doc.$timestamp.i;
  2506. const t = Long.isLong(doc.$timestamp.t)
  2507. ? doc.$timestamp.t.getLowBitsUnsigned()
  2508. : doc.$timestamp.t;
  2509. return new Timestamp({ t, i });
  2510. }
  2511. [Symbol.for('nodejs.util.inspect.custom')]() {
  2512. return this.inspect();
  2513. }
  2514. inspect() {
  2515. return `new Timestamp({ t: ${this.getHighBits()}, i: ${this.getLowBits()} })`;
  2516. }
  2517. }
  2518. Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
  2519. const FIRST_BIT = 0x80;
  2520. const FIRST_TWO_BITS = 0xc0;
  2521. const FIRST_THREE_BITS = 0xe0;
  2522. const FIRST_FOUR_BITS = 0xf0;
  2523. const FIRST_FIVE_BITS = 0xf8;
  2524. const TWO_BIT_CHAR = 0xc0;
  2525. const THREE_BIT_CHAR = 0xe0;
  2526. const FOUR_BIT_CHAR = 0xf0;
  2527. const CONTINUING_CHAR = 0x80;
  2528. function validateUtf8(bytes, start, end) {
  2529. let continuation = 0;
  2530. for (let i = start; i < end; i += 1) {
  2531. const byte = bytes[i];
  2532. if (continuation) {
  2533. if ((byte & FIRST_TWO_BITS) !== CONTINUING_CHAR) {
  2534. return false;
  2535. }
  2536. continuation -= 1;
  2537. }
  2538. else if (byte & FIRST_BIT) {
  2539. if ((byte & FIRST_THREE_BITS) === TWO_BIT_CHAR) {
  2540. continuation = 1;
  2541. }
  2542. else if ((byte & FIRST_FOUR_BITS) === THREE_BIT_CHAR) {
  2543. continuation = 2;
  2544. }
  2545. else if ((byte & FIRST_FIVE_BITS) === FOUR_BIT_CHAR) {
  2546. continuation = 3;
  2547. }
  2548. else {
  2549. return false;
  2550. }
  2551. }
  2552. }
  2553. return !continuation;
  2554. }
  2555. const JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
  2556. const JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
  2557. function internalDeserialize(buffer, options, isArray) {
  2558. options = options == null ? {} : options;
  2559. const index = options && options.index ? options.index : 0;
  2560. const size = buffer[index] |
  2561. (buffer[index + 1] << 8) |
  2562. (buffer[index + 2] << 16) |
  2563. (buffer[index + 3] << 24);
  2564. if (size < 5) {
  2565. throw new BSONError(`bson size must be >= 5, is ${size}`);
  2566. }
  2567. if (options.allowObjectSmallerThanBufferSize && buffer.length < size) {
  2568. throw new BSONError(`buffer length ${buffer.length} must be >= bson size ${size}`);
  2569. }
  2570. if (!options.allowObjectSmallerThanBufferSize && buffer.length !== size) {
  2571. throw new BSONError(`buffer length ${buffer.length} must === bson size ${size}`);
  2572. }
  2573. if (size + index > buffer.byteLength) {
  2574. throw new BSONError(`(bson size ${size} + options.index ${index} must be <= buffer length ${buffer.byteLength})`);
  2575. }
  2576. if (buffer[index + size - 1] !== 0) {
  2577. throw new BSONError("One object, sized correctly, with a spot for an EOO, but the EOO isn't 0x00");
  2578. }
  2579. return deserializeObject(buffer, index, options, isArray);
  2580. }
  2581. const allowedDBRefKeys = /^\$ref$|^\$id$|^\$db$/;
  2582. function deserializeObject(buffer, index, options, isArray = false) {
  2583. const fieldsAsRaw = options['fieldsAsRaw'] == null ? null : options['fieldsAsRaw'];
  2584. const raw = options['raw'] == null ? false : options['raw'];
  2585. const bsonRegExp = typeof options['bsonRegExp'] === 'boolean' ? options['bsonRegExp'] : false;
  2586. const promoteBuffers = options.promoteBuffers ?? false;
  2587. const promoteLongs = options.promoteLongs ?? true;
  2588. const promoteValues = options.promoteValues ?? true;
  2589. const useBigInt64 = options.useBigInt64 ?? false;
  2590. if (useBigInt64 && !promoteValues) {
  2591. throw new BSONError('Must either request bigint or Long for int64 deserialization');
  2592. }
  2593. if (useBigInt64 && !promoteLongs) {
  2594. throw new BSONError('Must either request bigint or Long for int64 deserialization');
  2595. }
  2596. const validation = options.validation == null ? { utf8: true } : options.validation;
  2597. let globalUTFValidation = true;
  2598. let validationSetting;
  2599. const utf8KeysSet = new Set();
  2600. const utf8ValidatedKeys = validation.utf8;
  2601. if (typeof utf8ValidatedKeys === 'boolean') {
  2602. validationSetting = utf8ValidatedKeys;
  2603. }
  2604. else {
  2605. globalUTFValidation = false;
  2606. const utf8ValidationValues = Object.keys(utf8ValidatedKeys).map(function (key) {
  2607. return utf8ValidatedKeys[key];
  2608. });
  2609. if (utf8ValidationValues.length === 0) {
  2610. throw new BSONError('UTF-8 validation setting cannot be empty');
  2611. }
  2612. if (typeof utf8ValidationValues[0] !== 'boolean') {
  2613. throw new BSONError('Invalid UTF-8 validation option, must specify boolean values');
  2614. }
  2615. validationSetting = utf8ValidationValues[0];
  2616. if (!utf8ValidationValues.every(item => item === validationSetting)) {
  2617. throw new BSONError('Invalid UTF-8 validation option - keys must be all true or all false');
  2618. }
  2619. }
  2620. if (!globalUTFValidation) {
  2621. for (const key of Object.keys(utf8ValidatedKeys)) {
  2622. utf8KeysSet.add(key);
  2623. }
  2624. }
  2625. const startIndex = index;
  2626. if (buffer.length < 5)
  2627. throw new BSONError('corrupt bson message < 5 bytes long');
  2628. const size = buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24);
  2629. if (size < 5 || size > buffer.length)
  2630. throw new BSONError('corrupt bson message');
  2631. const object = isArray ? [] : {};
  2632. let arrayIndex = 0;
  2633. const done = false;
  2634. let isPossibleDBRef = isArray ? false : null;
  2635. const dataview = new DataView(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  2636. while (!done) {
  2637. const elementType = buffer[index++];
  2638. if (elementType === 0)
  2639. break;
  2640. let i = index;
  2641. while (buffer[i] !== 0x00 && i < buffer.length) {
  2642. i++;
  2643. }
  2644. if (i >= buffer.byteLength)
  2645. throw new BSONError('Bad BSON Document: illegal CString');
  2646. const name = isArray ? arrayIndex++ : ByteUtils.toUTF8(buffer, index, i);
  2647. let shouldValidateKey = true;
  2648. if (globalUTFValidation || utf8KeysSet.has(name)) {
  2649. shouldValidateKey = validationSetting;
  2650. }
  2651. else {
  2652. shouldValidateKey = !validationSetting;
  2653. }
  2654. if (isPossibleDBRef !== false && name[0] === '$') {
  2655. isPossibleDBRef = allowedDBRefKeys.test(name);
  2656. }
  2657. let value;
  2658. index = i + 1;
  2659. if (elementType === BSON_DATA_STRING) {
  2660. const stringSize = buffer[index++] |
  2661. (buffer[index++] << 8) |
  2662. (buffer[index++] << 16) |
  2663. (buffer[index++] << 24);
  2664. if (stringSize <= 0 ||
  2665. stringSize > buffer.length - index ||
  2666. buffer[index + stringSize - 1] !== 0) {
  2667. throw new BSONError('bad string length in bson');
  2668. }
  2669. value = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  2670. index = index + stringSize;
  2671. }
  2672. else if (elementType === BSON_DATA_OID) {
  2673. const oid = ByteUtils.allocate(12);
  2674. oid.set(buffer.subarray(index, index + 12));
  2675. value = new ObjectId(oid);
  2676. index = index + 12;
  2677. }
  2678. else if (elementType === BSON_DATA_INT && promoteValues === false) {
  2679. value = new Int32(buffer[index++] | (buffer[index++] << 8) | (buffer[index++] << 16) | (buffer[index++] << 24));
  2680. }
  2681. else if (elementType === BSON_DATA_INT) {
  2682. value =
  2683. buffer[index++] |
  2684. (buffer[index++] << 8) |
  2685. (buffer[index++] << 16) |
  2686. (buffer[index++] << 24);
  2687. }
  2688. else if (elementType === BSON_DATA_NUMBER && promoteValues === false) {
  2689. value = new Double(dataview.getFloat64(index, true));
  2690. index = index + 8;
  2691. }
  2692. else if (elementType === BSON_DATA_NUMBER) {
  2693. value = dataview.getFloat64(index, true);
  2694. index = index + 8;
  2695. }
  2696. else if (elementType === BSON_DATA_DATE) {
  2697. const lowBits = buffer[index++] |
  2698. (buffer[index++] << 8) |
  2699. (buffer[index++] << 16) |
  2700. (buffer[index++] << 24);
  2701. const highBits = buffer[index++] |
  2702. (buffer[index++] << 8) |
  2703. (buffer[index++] << 16) |
  2704. (buffer[index++] << 24);
  2705. value = new Date(new Long(lowBits, highBits).toNumber());
  2706. }
  2707. else if (elementType === BSON_DATA_BOOLEAN) {
  2708. if (buffer[index] !== 0 && buffer[index] !== 1)
  2709. throw new BSONError('illegal boolean type value');
  2710. value = buffer[index++] === 1;
  2711. }
  2712. else if (elementType === BSON_DATA_OBJECT) {
  2713. const _index = index;
  2714. const objectSize = buffer[index] |
  2715. (buffer[index + 1] << 8) |
  2716. (buffer[index + 2] << 16) |
  2717. (buffer[index + 3] << 24);
  2718. if (objectSize <= 0 || objectSize > buffer.length - index)
  2719. throw new BSONError('bad embedded document length in bson');
  2720. if (raw) {
  2721. value = buffer.slice(index, index + objectSize);
  2722. }
  2723. else {
  2724. let objectOptions = options;
  2725. if (!globalUTFValidation) {
  2726. objectOptions = { ...options, validation: { utf8: shouldValidateKey } };
  2727. }
  2728. value = deserializeObject(buffer, _index, objectOptions, false);
  2729. }
  2730. index = index + objectSize;
  2731. }
  2732. else if (elementType === BSON_DATA_ARRAY) {
  2733. const _index = index;
  2734. const objectSize = buffer[index] |
  2735. (buffer[index + 1] << 8) |
  2736. (buffer[index + 2] << 16) |
  2737. (buffer[index + 3] << 24);
  2738. let arrayOptions = options;
  2739. const stopIndex = index + objectSize;
  2740. if (fieldsAsRaw && fieldsAsRaw[name]) {
  2741. arrayOptions = { ...options, raw: true };
  2742. }
  2743. if (!globalUTFValidation) {
  2744. arrayOptions = { ...arrayOptions, validation: { utf8: shouldValidateKey } };
  2745. }
  2746. value = deserializeObject(buffer, _index, arrayOptions, true);
  2747. index = index + objectSize;
  2748. if (buffer[index - 1] !== 0)
  2749. throw new BSONError('invalid array terminator byte');
  2750. if (index !== stopIndex)
  2751. throw new BSONError('corrupted array bson');
  2752. }
  2753. else if (elementType === BSON_DATA_UNDEFINED) {
  2754. value = undefined;
  2755. }
  2756. else if (elementType === BSON_DATA_NULL) {
  2757. value = null;
  2758. }
  2759. else if (elementType === BSON_DATA_LONG) {
  2760. const dataview = BSONDataView.fromUint8Array(buffer.subarray(index, index + 8));
  2761. const lowBits = buffer[index++] |
  2762. (buffer[index++] << 8) |
  2763. (buffer[index++] << 16) |
  2764. (buffer[index++] << 24);
  2765. const highBits = buffer[index++] |
  2766. (buffer[index++] << 8) |
  2767. (buffer[index++] << 16) |
  2768. (buffer[index++] << 24);
  2769. const long = new Long(lowBits, highBits);
  2770. if (useBigInt64) {
  2771. value = dataview.getBigInt64(0, true);
  2772. }
  2773. else if (promoteLongs && promoteValues === true) {
  2774. value =
  2775. long.lessThanOrEqual(JS_INT_MAX_LONG) && long.greaterThanOrEqual(JS_INT_MIN_LONG)
  2776. ? long.toNumber()
  2777. : long;
  2778. }
  2779. else {
  2780. value = long;
  2781. }
  2782. }
  2783. else if (elementType === BSON_DATA_DECIMAL128) {
  2784. const bytes = ByteUtils.allocate(16);
  2785. bytes.set(buffer.subarray(index, index + 16), 0);
  2786. index = index + 16;
  2787. value = new Decimal128(bytes);
  2788. }
  2789. else if (elementType === BSON_DATA_BINARY) {
  2790. let binarySize = buffer[index++] |
  2791. (buffer[index++] << 8) |
  2792. (buffer[index++] << 16) |
  2793. (buffer[index++] << 24);
  2794. const totalBinarySize = binarySize;
  2795. const subType = buffer[index++];
  2796. if (binarySize < 0)
  2797. throw new BSONError('Negative binary type element size found');
  2798. if (binarySize > buffer.byteLength)
  2799. throw new BSONError('Binary type size larger than document size');
  2800. if (buffer['slice'] != null) {
  2801. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  2802. binarySize =
  2803. buffer[index++] |
  2804. (buffer[index++] << 8) |
  2805. (buffer[index++] << 16) |
  2806. (buffer[index++] << 24);
  2807. if (binarySize < 0)
  2808. throw new BSONError('Negative binary type element size found for subtype 0x02');
  2809. if (binarySize > totalBinarySize - 4)
  2810. throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
  2811. if (binarySize < totalBinarySize - 4)
  2812. throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
  2813. }
  2814. if (promoteBuffers && promoteValues) {
  2815. value = ByteUtils.toLocalBufferType(buffer.slice(index, index + binarySize));
  2816. }
  2817. else {
  2818. value = new Binary(buffer.slice(index, index + binarySize), subType);
  2819. if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
  2820. value = value.toUUID();
  2821. }
  2822. }
  2823. }
  2824. else {
  2825. const _buffer = ByteUtils.allocate(binarySize);
  2826. if (subType === Binary.SUBTYPE_BYTE_ARRAY) {
  2827. binarySize =
  2828. buffer[index++] |
  2829. (buffer[index++] << 8) |
  2830. (buffer[index++] << 16) |
  2831. (buffer[index++] << 24);
  2832. if (binarySize < 0)
  2833. throw new BSONError('Negative binary type element size found for subtype 0x02');
  2834. if (binarySize > totalBinarySize - 4)
  2835. throw new BSONError('Binary type with subtype 0x02 contains too long binary size');
  2836. if (binarySize < totalBinarySize - 4)
  2837. throw new BSONError('Binary type with subtype 0x02 contains too short binary size');
  2838. }
  2839. for (i = 0; i < binarySize; i++) {
  2840. _buffer[i] = buffer[index + i];
  2841. }
  2842. if (promoteBuffers && promoteValues) {
  2843. value = _buffer;
  2844. }
  2845. else {
  2846. value = new Binary(buffer.slice(index, index + binarySize), subType);
  2847. if (subType === BSON_BINARY_SUBTYPE_UUID_NEW && UUID.isValid(value)) {
  2848. value = value.toUUID();
  2849. }
  2850. }
  2851. }
  2852. index = index + binarySize;
  2853. }
  2854. else if (elementType === BSON_DATA_REGEXP && bsonRegExp === false) {
  2855. i = index;
  2856. while (buffer[i] !== 0x00 && i < buffer.length) {
  2857. i++;
  2858. }
  2859. if (i >= buffer.length)
  2860. throw new BSONError('Bad BSON Document: illegal CString');
  2861. const source = ByteUtils.toUTF8(buffer, index, i);
  2862. index = i + 1;
  2863. i = index;
  2864. while (buffer[i] !== 0x00 && i < buffer.length) {
  2865. i++;
  2866. }
  2867. if (i >= buffer.length)
  2868. throw new BSONError('Bad BSON Document: illegal CString');
  2869. const regExpOptions = ByteUtils.toUTF8(buffer, index, i);
  2870. index = i + 1;
  2871. const optionsArray = new Array(regExpOptions.length);
  2872. for (i = 0; i < regExpOptions.length; i++) {
  2873. switch (regExpOptions[i]) {
  2874. case 'm':
  2875. optionsArray[i] = 'm';
  2876. break;
  2877. case 's':
  2878. optionsArray[i] = 'g';
  2879. break;
  2880. case 'i':
  2881. optionsArray[i] = 'i';
  2882. break;
  2883. }
  2884. }
  2885. value = new RegExp(source, optionsArray.join(''));
  2886. }
  2887. else if (elementType === BSON_DATA_REGEXP && bsonRegExp === true) {
  2888. i = index;
  2889. while (buffer[i] !== 0x00 && i < buffer.length) {
  2890. i++;
  2891. }
  2892. if (i >= buffer.length)
  2893. throw new BSONError('Bad BSON Document: illegal CString');
  2894. const source = ByteUtils.toUTF8(buffer, index, i);
  2895. index = i + 1;
  2896. i = index;
  2897. while (buffer[i] !== 0x00 && i < buffer.length) {
  2898. i++;
  2899. }
  2900. if (i >= buffer.length)
  2901. throw new BSONError('Bad BSON Document: illegal CString');
  2902. const regExpOptions = ByteUtils.toUTF8(buffer, index, i);
  2903. index = i + 1;
  2904. value = new BSONRegExp(source, regExpOptions);
  2905. }
  2906. else if (elementType === BSON_DATA_SYMBOL) {
  2907. const stringSize = buffer[index++] |
  2908. (buffer[index++] << 8) |
  2909. (buffer[index++] << 16) |
  2910. (buffer[index++] << 24);
  2911. if (stringSize <= 0 ||
  2912. stringSize > buffer.length - index ||
  2913. buffer[index + stringSize - 1] !== 0) {
  2914. throw new BSONError('bad string length in bson');
  2915. }
  2916. const symbol = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  2917. value = promoteValues ? symbol : new BSONSymbol(symbol);
  2918. index = index + stringSize;
  2919. }
  2920. else if (elementType === BSON_DATA_TIMESTAMP) {
  2921. const i = buffer[index++] +
  2922. buffer[index++] * (1 << 8) +
  2923. buffer[index++] * (1 << 16) +
  2924. buffer[index++] * (1 << 24);
  2925. const t = buffer[index++] +
  2926. buffer[index++] * (1 << 8) +
  2927. buffer[index++] * (1 << 16) +
  2928. buffer[index++] * (1 << 24);
  2929. value = new Timestamp({ i, t });
  2930. }
  2931. else if (elementType === BSON_DATA_MIN_KEY) {
  2932. value = new MinKey();
  2933. }
  2934. else if (elementType === BSON_DATA_MAX_KEY) {
  2935. value = new MaxKey();
  2936. }
  2937. else if (elementType === BSON_DATA_CODE) {
  2938. const stringSize = buffer[index++] |
  2939. (buffer[index++] << 8) |
  2940. (buffer[index++] << 16) |
  2941. (buffer[index++] << 24);
  2942. if (stringSize <= 0 ||
  2943. stringSize > buffer.length - index ||
  2944. buffer[index + stringSize - 1] !== 0) {
  2945. throw new BSONError('bad string length in bson');
  2946. }
  2947. const functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  2948. value = new Code(functionString);
  2949. index = index + stringSize;
  2950. }
  2951. else if (elementType === BSON_DATA_CODE_W_SCOPE) {
  2952. const totalSize = buffer[index++] |
  2953. (buffer[index++] << 8) |
  2954. (buffer[index++] << 16) |
  2955. (buffer[index++] << 24);
  2956. if (totalSize < 4 + 4 + 4 + 1) {
  2957. throw new BSONError('code_w_scope total size shorter minimum expected length');
  2958. }
  2959. const stringSize = buffer[index++] |
  2960. (buffer[index++] << 8) |
  2961. (buffer[index++] << 16) |
  2962. (buffer[index++] << 24);
  2963. if (stringSize <= 0 ||
  2964. stringSize > buffer.length - index ||
  2965. buffer[index + stringSize - 1] !== 0) {
  2966. throw new BSONError('bad string length in bson');
  2967. }
  2968. const functionString = getValidatedString(buffer, index, index + stringSize - 1, shouldValidateKey);
  2969. index = index + stringSize;
  2970. const _index = index;
  2971. const objectSize = buffer[index] |
  2972. (buffer[index + 1] << 8) |
  2973. (buffer[index + 2] << 16) |
  2974. (buffer[index + 3] << 24);
  2975. const scopeObject = deserializeObject(buffer, _index, options, false);
  2976. index = index + objectSize;
  2977. if (totalSize < 4 + 4 + objectSize + stringSize) {
  2978. throw new BSONError('code_w_scope total size is too short, truncating scope');
  2979. }
  2980. if (totalSize > 4 + 4 + objectSize + stringSize) {
  2981. throw new BSONError('code_w_scope total size is too long, clips outer document');
  2982. }
  2983. value = new Code(functionString, scopeObject);
  2984. }
  2985. else if (elementType === BSON_DATA_DBPOINTER) {
  2986. const stringSize = buffer[index++] |
  2987. (buffer[index++] << 8) |
  2988. (buffer[index++] << 16) |
  2989. (buffer[index++] << 24);
  2990. if (stringSize <= 0 ||
  2991. stringSize > buffer.length - index ||
  2992. buffer[index + stringSize - 1] !== 0)
  2993. throw new BSONError('bad string length in bson');
  2994. if (validation != null && validation.utf8) {
  2995. if (!validateUtf8(buffer, index, index + stringSize - 1)) {
  2996. throw new BSONError('Invalid UTF-8 string in BSON document');
  2997. }
  2998. }
  2999. const namespace = ByteUtils.toUTF8(buffer, index, index + stringSize - 1);
  3000. index = index + stringSize;
  3001. const oidBuffer = ByteUtils.allocate(12);
  3002. oidBuffer.set(buffer.subarray(index, index + 12), 0);
  3003. const oid = new ObjectId(oidBuffer);
  3004. index = index + 12;
  3005. value = new DBRef(namespace, oid);
  3006. }
  3007. else {
  3008. throw new BSONError(`Detected unknown BSON type ${elementType.toString(16)} for fieldname "${name}"`);
  3009. }
  3010. if (name === '__proto__') {
  3011. Object.defineProperty(object, name, {
  3012. value,
  3013. writable: true,
  3014. enumerable: true,
  3015. configurable: true
  3016. });
  3017. }
  3018. else {
  3019. object[name] = value;
  3020. }
  3021. }
  3022. if (size !== index - startIndex) {
  3023. if (isArray)
  3024. throw new BSONError('corrupt array bson');
  3025. throw new BSONError('corrupt object bson');
  3026. }
  3027. if (!isPossibleDBRef)
  3028. return object;
  3029. if (isDBRefLike(object)) {
  3030. const copy = Object.assign({}, object);
  3031. delete copy.$ref;
  3032. delete copy.$id;
  3033. delete copy.$db;
  3034. return new DBRef(object.$ref, object.$id, object.$db, copy);
  3035. }
  3036. return object;
  3037. }
  3038. function getValidatedString(buffer, start, end, shouldValidateUtf8) {
  3039. const value = ByteUtils.toUTF8(buffer, start, end);
  3040. if (shouldValidateUtf8) {
  3041. for (let i = 0; i < value.length; i++) {
  3042. if (value.charCodeAt(i) === 0xfffd) {
  3043. if (!validateUtf8(buffer, start, end)) {
  3044. throw new BSONError('Invalid UTF-8 string in BSON document');
  3045. }
  3046. break;
  3047. }
  3048. }
  3049. }
  3050. return value;
  3051. }
  3052. const regexp = /\x00/;
  3053. const ignoreKeys = new Set(['$db', '$ref', '$id', '$clusterTime']);
  3054. function serializeString(buffer, key, value, index) {
  3055. buffer[index++] = BSON_DATA_STRING;
  3056. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3057. index = index + numberOfWrittenBytes + 1;
  3058. buffer[index - 1] = 0;
  3059. const size = ByteUtils.encodeUTF8Into(buffer, value, index + 4);
  3060. buffer[index + 3] = ((size + 1) >> 24) & 0xff;
  3061. buffer[index + 2] = ((size + 1) >> 16) & 0xff;
  3062. buffer[index + 1] = ((size + 1) >> 8) & 0xff;
  3063. buffer[index] = (size + 1) & 0xff;
  3064. index = index + 4 + size;
  3065. buffer[index++] = 0;
  3066. return index;
  3067. }
  3068. const NUMBER_SPACE = new DataView(new ArrayBuffer(8), 0, 8);
  3069. const FOUR_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 4);
  3070. const EIGHT_BYTE_VIEW_ON_NUMBER = new Uint8Array(NUMBER_SPACE.buffer, 0, 8);
  3071. function serializeNumber(buffer, key, value, index) {
  3072. const isNegativeZero = Object.is(value, -0);
  3073. const type = !isNegativeZero &&
  3074. Number.isSafeInteger(value) &&
  3075. value <= BSON_INT32_MAX &&
  3076. value >= BSON_INT32_MIN
  3077. ? BSON_DATA_INT
  3078. : BSON_DATA_NUMBER;
  3079. if (type === BSON_DATA_INT) {
  3080. NUMBER_SPACE.setInt32(0, value, true);
  3081. }
  3082. else {
  3083. NUMBER_SPACE.setFloat64(0, value, true);
  3084. }
  3085. const bytes = type === BSON_DATA_INT ? FOUR_BYTE_VIEW_ON_NUMBER : EIGHT_BYTE_VIEW_ON_NUMBER;
  3086. buffer[index++] = type;
  3087. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3088. index = index + numberOfWrittenBytes;
  3089. buffer[index++] = 0x00;
  3090. buffer.set(bytes, index);
  3091. index += bytes.byteLength;
  3092. return index;
  3093. }
  3094. function serializeBigInt(buffer, key, value, index) {
  3095. buffer[index++] = BSON_DATA_LONG;
  3096. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3097. index += numberOfWrittenBytes;
  3098. buffer[index++] = 0;
  3099. NUMBER_SPACE.setBigInt64(0, value, true);
  3100. buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index);
  3101. index += EIGHT_BYTE_VIEW_ON_NUMBER.byteLength;
  3102. return index;
  3103. }
  3104. function serializeNull(buffer, key, _, index) {
  3105. buffer[index++] = BSON_DATA_NULL;
  3106. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3107. index = index + numberOfWrittenBytes;
  3108. buffer[index++] = 0;
  3109. return index;
  3110. }
  3111. function serializeBoolean(buffer, key, value, index) {
  3112. buffer[index++] = BSON_DATA_BOOLEAN;
  3113. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3114. index = index + numberOfWrittenBytes;
  3115. buffer[index++] = 0;
  3116. buffer[index++] = value ? 1 : 0;
  3117. return index;
  3118. }
  3119. function serializeDate(buffer, key, value, index) {
  3120. buffer[index++] = BSON_DATA_DATE;
  3121. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3122. index = index + numberOfWrittenBytes;
  3123. buffer[index++] = 0;
  3124. const dateInMilis = Long.fromNumber(value.getTime());
  3125. const lowBits = dateInMilis.getLowBits();
  3126. const highBits = dateInMilis.getHighBits();
  3127. buffer[index++] = lowBits & 0xff;
  3128. buffer[index++] = (lowBits >> 8) & 0xff;
  3129. buffer[index++] = (lowBits >> 16) & 0xff;
  3130. buffer[index++] = (lowBits >> 24) & 0xff;
  3131. buffer[index++] = highBits & 0xff;
  3132. buffer[index++] = (highBits >> 8) & 0xff;
  3133. buffer[index++] = (highBits >> 16) & 0xff;
  3134. buffer[index++] = (highBits >> 24) & 0xff;
  3135. return index;
  3136. }
  3137. function serializeRegExp(buffer, key, value, index) {
  3138. buffer[index++] = BSON_DATA_REGEXP;
  3139. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3140. index = index + numberOfWrittenBytes;
  3141. buffer[index++] = 0;
  3142. if (value.source && value.source.match(regexp) != null) {
  3143. throw new BSONError('value ' + value.source + ' must not contain null bytes');
  3144. }
  3145. index = index + ByteUtils.encodeUTF8Into(buffer, value.source, index);
  3146. buffer[index++] = 0x00;
  3147. if (value.ignoreCase)
  3148. buffer[index++] = 0x69;
  3149. if (value.global)
  3150. buffer[index++] = 0x73;
  3151. if (value.multiline)
  3152. buffer[index++] = 0x6d;
  3153. buffer[index++] = 0x00;
  3154. return index;
  3155. }
  3156. function serializeBSONRegExp(buffer, key, value, index) {
  3157. buffer[index++] = BSON_DATA_REGEXP;
  3158. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3159. index = index + numberOfWrittenBytes;
  3160. buffer[index++] = 0;
  3161. if (value.pattern.match(regexp) != null) {
  3162. throw new BSONError('pattern ' + value.pattern + ' must not contain null bytes');
  3163. }
  3164. index = index + ByteUtils.encodeUTF8Into(buffer, value.pattern, index);
  3165. buffer[index++] = 0x00;
  3166. const sortedOptions = value.options.split('').sort().join('');
  3167. index = index + ByteUtils.encodeUTF8Into(buffer, sortedOptions, index);
  3168. buffer[index++] = 0x00;
  3169. return index;
  3170. }
  3171. function serializeMinMax(buffer, key, value, index) {
  3172. if (value === null) {
  3173. buffer[index++] = BSON_DATA_NULL;
  3174. }
  3175. else if (value._bsontype === 'MinKey') {
  3176. buffer[index++] = BSON_DATA_MIN_KEY;
  3177. }
  3178. else {
  3179. buffer[index++] = BSON_DATA_MAX_KEY;
  3180. }
  3181. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3182. index = index + numberOfWrittenBytes;
  3183. buffer[index++] = 0;
  3184. return index;
  3185. }
  3186. function serializeObjectId(buffer, key, value, index) {
  3187. buffer[index++] = BSON_DATA_OID;
  3188. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3189. index = index + numberOfWrittenBytes;
  3190. buffer[index++] = 0;
  3191. if (isUint8Array(value.id)) {
  3192. buffer.set(value.id.subarray(0, 12), index);
  3193. }
  3194. else {
  3195. throw new BSONError('object [' + JSON.stringify(value) + '] is not a valid ObjectId');
  3196. }
  3197. return index + 12;
  3198. }
  3199. function serializeBuffer(buffer, key, value, index) {
  3200. buffer[index++] = BSON_DATA_BINARY;
  3201. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3202. index = index + numberOfWrittenBytes;
  3203. buffer[index++] = 0;
  3204. const size = value.length;
  3205. buffer[index++] = size & 0xff;
  3206. buffer[index++] = (size >> 8) & 0xff;
  3207. buffer[index++] = (size >> 16) & 0xff;
  3208. buffer[index++] = (size >> 24) & 0xff;
  3209. buffer[index++] = BSON_BINARY_SUBTYPE_DEFAULT;
  3210. buffer.set(value, index);
  3211. index = index + size;
  3212. return index;
  3213. }
  3214. function serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path) {
  3215. if (path.has(value)) {
  3216. throw new BSONError('Cannot convert circular structure to BSON');
  3217. }
  3218. path.add(value);
  3219. buffer[index++] = Array.isArray(value) ? BSON_DATA_ARRAY : BSON_DATA_OBJECT;
  3220. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3221. index = index + numberOfWrittenBytes;
  3222. buffer[index++] = 0;
  3223. const endIndex = serializeInto(buffer, value, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
  3224. path.delete(value);
  3225. return endIndex;
  3226. }
  3227. function serializeDecimal128(buffer, key, value, index) {
  3228. buffer[index++] = BSON_DATA_DECIMAL128;
  3229. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3230. index = index + numberOfWrittenBytes;
  3231. buffer[index++] = 0;
  3232. buffer.set(value.bytes.subarray(0, 16), index);
  3233. return index + 16;
  3234. }
  3235. function serializeLong(buffer, key, value, index) {
  3236. buffer[index++] =
  3237. value._bsontype === 'Long' ? BSON_DATA_LONG : BSON_DATA_TIMESTAMP;
  3238. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3239. index = index + numberOfWrittenBytes;
  3240. buffer[index++] = 0;
  3241. const lowBits = value.getLowBits();
  3242. const highBits = value.getHighBits();
  3243. buffer[index++] = lowBits & 0xff;
  3244. buffer[index++] = (lowBits >> 8) & 0xff;
  3245. buffer[index++] = (lowBits >> 16) & 0xff;
  3246. buffer[index++] = (lowBits >> 24) & 0xff;
  3247. buffer[index++] = highBits & 0xff;
  3248. buffer[index++] = (highBits >> 8) & 0xff;
  3249. buffer[index++] = (highBits >> 16) & 0xff;
  3250. buffer[index++] = (highBits >> 24) & 0xff;
  3251. return index;
  3252. }
  3253. function serializeInt32(buffer, key, value, index) {
  3254. value = value.valueOf();
  3255. buffer[index++] = BSON_DATA_INT;
  3256. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3257. index = index + numberOfWrittenBytes;
  3258. buffer[index++] = 0;
  3259. buffer[index++] = value & 0xff;
  3260. buffer[index++] = (value >> 8) & 0xff;
  3261. buffer[index++] = (value >> 16) & 0xff;
  3262. buffer[index++] = (value >> 24) & 0xff;
  3263. return index;
  3264. }
  3265. function serializeDouble(buffer, key, value, index) {
  3266. buffer[index++] = BSON_DATA_NUMBER;
  3267. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3268. index = index + numberOfWrittenBytes;
  3269. buffer[index++] = 0;
  3270. NUMBER_SPACE.setFloat64(0, value.value, true);
  3271. buffer.set(EIGHT_BYTE_VIEW_ON_NUMBER, index);
  3272. index = index + 8;
  3273. return index;
  3274. }
  3275. function serializeFunction(buffer, key, value, index) {
  3276. buffer[index++] = BSON_DATA_CODE;
  3277. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3278. index = index + numberOfWrittenBytes;
  3279. buffer[index++] = 0;
  3280. const functionString = value.toString();
  3281. const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
  3282. buffer[index] = size & 0xff;
  3283. buffer[index + 1] = (size >> 8) & 0xff;
  3284. buffer[index + 2] = (size >> 16) & 0xff;
  3285. buffer[index + 3] = (size >> 24) & 0xff;
  3286. index = index + 4 + size - 1;
  3287. buffer[index++] = 0;
  3288. return index;
  3289. }
  3290. function serializeCode(buffer, key, value, index, checkKeys = false, depth = 0, serializeFunctions = false, ignoreUndefined = true, path) {
  3291. if (value.scope && typeof value.scope === 'object') {
  3292. buffer[index++] = BSON_DATA_CODE_W_SCOPE;
  3293. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3294. index = index + numberOfWrittenBytes;
  3295. buffer[index++] = 0;
  3296. let startIndex = index;
  3297. const functionString = value.code;
  3298. index = index + 4;
  3299. const codeSize = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
  3300. buffer[index] = codeSize & 0xff;
  3301. buffer[index + 1] = (codeSize >> 8) & 0xff;
  3302. buffer[index + 2] = (codeSize >> 16) & 0xff;
  3303. buffer[index + 3] = (codeSize >> 24) & 0xff;
  3304. buffer[index + 4 + codeSize - 1] = 0;
  3305. index = index + codeSize + 4;
  3306. const endIndex = serializeInto(buffer, value.scope, checkKeys, index, depth + 1, serializeFunctions, ignoreUndefined, path);
  3307. index = endIndex - 1;
  3308. const totalSize = endIndex - startIndex;
  3309. buffer[startIndex++] = totalSize & 0xff;
  3310. buffer[startIndex++] = (totalSize >> 8) & 0xff;
  3311. buffer[startIndex++] = (totalSize >> 16) & 0xff;
  3312. buffer[startIndex++] = (totalSize >> 24) & 0xff;
  3313. buffer[index++] = 0;
  3314. }
  3315. else {
  3316. buffer[index++] = BSON_DATA_CODE;
  3317. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3318. index = index + numberOfWrittenBytes;
  3319. buffer[index++] = 0;
  3320. const functionString = value.code.toString();
  3321. const size = ByteUtils.encodeUTF8Into(buffer, functionString, index + 4) + 1;
  3322. buffer[index] = size & 0xff;
  3323. buffer[index + 1] = (size >> 8) & 0xff;
  3324. buffer[index + 2] = (size >> 16) & 0xff;
  3325. buffer[index + 3] = (size >> 24) & 0xff;
  3326. index = index + 4 + size - 1;
  3327. buffer[index++] = 0;
  3328. }
  3329. return index;
  3330. }
  3331. function serializeBinary(buffer, key, value, index) {
  3332. buffer[index++] = BSON_DATA_BINARY;
  3333. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3334. index = index + numberOfWrittenBytes;
  3335. buffer[index++] = 0;
  3336. const data = value.buffer;
  3337. let size = value.position;
  3338. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY)
  3339. size = size + 4;
  3340. buffer[index++] = size & 0xff;
  3341. buffer[index++] = (size >> 8) & 0xff;
  3342. buffer[index++] = (size >> 16) & 0xff;
  3343. buffer[index++] = (size >> 24) & 0xff;
  3344. buffer[index++] = value.sub_type;
  3345. if (value.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
  3346. size = size - 4;
  3347. buffer[index++] = size & 0xff;
  3348. buffer[index++] = (size >> 8) & 0xff;
  3349. buffer[index++] = (size >> 16) & 0xff;
  3350. buffer[index++] = (size >> 24) & 0xff;
  3351. }
  3352. buffer.set(data, index);
  3353. index = index + value.position;
  3354. return index;
  3355. }
  3356. function serializeSymbol(buffer, key, value, index) {
  3357. buffer[index++] = BSON_DATA_SYMBOL;
  3358. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3359. index = index + numberOfWrittenBytes;
  3360. buffer[index++] = 0;
  3361. const size = ByteUtils.encodeUTF8Into(buffer, value.value, index + 4) + 1;
  3362. buffer[index] = size & 0xff;
  3363. buffer[index + 1] = (size >> 8) & 0xff;
  3364. buffer[index + 2] = (size >> 16) & 0xff;
  3365. buffer[index + 3] = (size >> 24) & 0xff;
  3366. index = index + 4 + size - 1;
  3367. buffer[index++] = 0x00;
  3368. return index;
  3369. }
  3370. function serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path) {
  3371. buffer[index++] = BSON_DATA_OBJECT;
  3372. const numberOfWrittenBytes = ByteUtils.encodeUTF8Into(buffer, key, index);
  3373. index = index + numberOfWrittenBytes;
  3374. buffer[index++] = 0;
  3375. let startIndex = index;
  3376. let output = {
  3377. $ref: value.collection || value.namespace,
  3378. $id: value.oid
  3379. };
  3380. if (value.db != null) {
  3381. output.$db = value.db;
  3382. }
  3383. output = Object.assign(output, value.fields);
  3384. const endIndex = serializeInto(buffer, output, false, index, depth + 1, serializeFunctions, true, path);
  3385. const size = endIndex - startIndex;
  3386. buffer[startIndex++] = size & 0xff;
  3387. buffer[startIndex++] = (size >> 8) & 0xff;
  3388. buffer[startIndex++] = (size >> 16) & 0xff;
  3389. buffer[startIndex++] = (size >> 24) & 0xff;
  3390. return endIndex;
  3391. }
  3392. function serializeInto(buffer, object, checkKeys, startingIndex, depth, serializeFunctions, ignoreUndefined, path) {
  3393. if (path == null) {
  3394. if (object == null) {
  3395. buffer[0] = 0x05;
  3396. buffer[1] = 0x00;
  3397. buffer[2] = 0x00;
  3398. buffer[3] = 0x00;
  3399. buffer[4] = 0x00;
  3400. return 5;
  3401. }
  3402. if (Array.isArray(object)) {
  3403. throw new BSONError('serialize does not support an array as the root input');
  3404. }
  3405. if (typeof object !== 'object') {
  3406. throw new BSONError('serialize does not support non-object as the root input');
  3407. }
  3408. else if ('_bsontype' in object && typeof object._bsontype === 'string') {
  3409. throw new BSONError(`BSON types cannot be serialized as a document`);
  3410. }
  3411. else if (isDate(object) ||
  3412. isRegExp(object) ||
  3413. isUint8Array(object) ||
  3414. isAnyArrayBuffer(object)) {
  3415. throw new BSONError(`date, regexp, typedarray, and arraybuffer cannot be BSON documents`);
  3416. }
  3417. path = new Set();
  3418. }
  3419. path.add(object);
  3420. let index = startingIndex + 4;
  3421. if (Array.isArray(object)) {
  3422. for (let i = 0; i < object.length; i++) {
  3423. const key = `${i}`;
  3424. let value = object[i];
  3425. if (typeof value?.toBSON === 'function') {
  3426. value = value.toBSON();
  3427. }
  3428. if (typeof value === 'string') {
  3429. index = serializeString(buffer, key, value, index);
  3430. }
  3431. else if (typeof value === 'number') {
  3432. index = serializeNumber(buffer, key, value, index);
  3433. }
  3434. else if (typeof value === 'bigint') {
  3435. index = serializeBigInt(buffer, key, value, index);
  3436. }
  3437. else if (typeof value === 'boolean') {
  3438. index = serializeBoolean(buffer, key, value, index);
  3439. }
  3440. else if (value instanceof Date || isDate(value)) {
  3441. index = serializeDate(buffer, key, value, index);
  3442. }
  3443. else if (value === undefined) {
  3444. index = serializeNull(buffer, key, value, index);
  3445. }
  3446. else if (value === null) {
  3447. index = serializeNull(buffer, key, value, index);
  3448. }
  3449. else if (isUint8Array(value)) {
  3450. index = serializeBuffer(buffer, key, value, index);
  3451. }
  3452. else if (value instanceof RegExp || isRegExp(value)) {
  3453. index = serializeRegExp(buffer, key, value, index);
  3454. }
  3455. else if (typeof value === 'object' && value._bsontype == null) {
  3456. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3457. }
  3458. else if (typeof value === 'object' &&
  3459. value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
  3460. throw new BSONVersionError();
  3461. }
  3462. else if (value._bsontype === 'ObjectId') {
  3463. index = serializeObjectId(buffer, key, value, index);
  3464. }
  3465. else if (value._bsontype === 'Decimal128') {
  3466. index = serializeDecimal128(buffer, key, value, index);
  3467. }
  3468. else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
  3469. index = serializeLong(buffer, key, value, index);
  3470. }
  3471. else if (value._bsontype === 'Double') {
  3472. index = serializeDouble(buffer, key, value, index);
  3473. }
  3474. else if (typeof value === 'function' && serializeFunctions) {
  3475. index = serializeFunction(buffer, key, value, index);
  3476. }
  3477. else if (value._bsontype === 'Code') {
  3478. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3479. }
  3480. else if (value._bsontype === 'Binary') {
  3481. index = serializeBinary(buffer, key, value, index);
  3482. }
  3483. else if (value._bsontype === 'BSONSymbol') {
  3484. index = serializeSymbol(buffer, key, value, index);
  3485. }
  3486. else if (value._bsontype === 'DBRef') {
  3487. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
  3488. }
  3489. else if (value._bsontype === 'BSONRegExp') {
  3490. index = serializeBSONRegExp(buffer, key, value, index);
  3491. }
  3492. else if (value._bsontype === 'Int32') {
  3493. index = serializeInt32(buffer, key, value, index);
  3494. }
  3495. else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
  3496. index = serializeMinMax(buffer, key, value, index);
  3497. }
  3498. else if (typeof value._bsontype !== 'undefined') {
  3499. throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
  3500. }
  3501. }
  3502. }
  3503. else if (object instanceof Map || isMap(object)) {
  3504. const iterator = object.entries();
  3505. let done = false;
  3506. while (!done) {
  3507. const entry = iterator.next();
  3508. done = !!entry.done;
  3509. if (done)
  3510. continue;
  3511. const key = entry.value[0];
  3512. let value = entry.value[1];
  3513. if (typeof value?.toBSON === 'function') {
  3514. value = value.toBSON();
  3515. }
  3516. const type = typeof value;
  3517. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  3518. if (key.match(regexp) != null) {
  3519. throw new BSONError('key ' + key + ' must not contain null bytes');
  3520. }
  3521. if (checkKeys) {
  3522. if ('$' === key[0]) {
  3523. throw new BSONError('key ' + key + " must not start with '$'");
  3524. }
  3525. else if (~key.indexOf('.')) {
  3526. throw new BSONError('key ' + key + " must not contain '.'");
  3527. }
  3528. }
  3529. }
  3530. if (type === 'string') {
  3531. index = serializeString(buffer, key, value, index);
  3532. }
  3533. else if (type === 'number') {
  3534. index = serializeNumber(buffer, key, value, index);
  3535. }
  3536. else if (type === 'bigint') {
  3537. index = serializeBigInt(buffer, key, value, index);
  3538. }
  3539. else if (type === 'boolean') {
  3540. index = serializeBoolean(buffer, key, value, index);
  3541. }
  3542. else if (value instanceof Date || isDate(value)) {
  3543. index = serializeDate(buffer, key, value, index);
  3544. }
  3545. else if (value === null || (value === undefined && ignoreUndefined === false)) {
  3546. index = serializeNull(buffer, key, value, index);
  3547. }
  3548. else if (isUint8Array(value)) {
  3549. index = serializeBuffer(buffer, key, value, index);
  3550. }
  3551. else if (value instanceof RegExp || isRegExp(value)) {
  3552. index = serializeRegExp(buffer, key, value, index);
  3553. }
  3554. else if (type === 'object' && value._bsontype == null) {
  3555. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3556. }
  3557. else if (typeof value === 'object' &&
  3558. value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
  3559. throw new BSONVersionError();
  3560. }
  3561. else if (value._bsontype === 'ObjectId') {
  3562. index = serializeObjectId(buffer, key, value, index);
  3563. }
  3564. else if (type === 'object' && value._bsontype === 'Decimal128') {
  3565. index = serializeDecimal128(buffer, key, value, index);
  3566. }
  3567. else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
  3568. index = serializeLong(buffer, key, value, index);
  3569. }
  3570. else if (value._bsontype === 'Double') {
  3571. index = serializeDouble(buffer, key, value, index);
  3572. }
  3573. else if (value._bsontype === 'Code') {
  3574. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3575. }
  3576. else if (typeof value === 'function' && serializeFunctions) {
  3577. index = serializeFunction(buffer, key, value, index);
  3578. }
  3579. else if (value._bsontype === 'Binary') {
  3580. index = serializeBinary(buffer, key, value, index);
  3581. }
  3582. else if (value._bsontype === 'BSONSymbol') {
  3583. index = serializeSymbol(buffer, key, value, index);
  3584. }
  3585. else if (value._bsontype === 'DBRef') {
  3586. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
  3587. }
  3588. else if (value._bsontype === 'BSONRegExp') {
  3589. index = serializeBSONRegExp(buffer, key, value, index);
  3590. }
  3591. else if (value._bsontype === 'Int32') {
  3592. index = serializeInt32(buffer, key, value, index);
  3593. }
  3594. else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
  3595. index = serializeMinMax(buffer, key, value, index);
  3596. }
  3597. else if (typeof value._bsontype !== 'undefined') {
  3598. throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
  3599. }
  3600. }
  3601. }
  3602. else {
  3603. if (typeof object?.toBSON === 'function') {
  3604. object = object.toBSON();
  3605. if (object != null && typeof object !== 'object') {
  3606. throw new BSONError('toBSON function did not return an object');
  3607. }
  3608. }
  3609. for (const key of Object.keys(object)) {
  3610. let value = object[key];
  3611. if (typeof value?.toBSON === 'function') {
  3612. value = value.toBSON();
  3613. }
  3614. const type = typeof value;
  3615. if (typeof key === 'string' && !ignoreKeys.has(key)) {
  3616. if (key.match(regexp) != null) {
  3617. throw new BSONError('key ' + key + ' must not contain null bytes');
  3618. }
  3619. if (checkKeys) {
  3620. if ('$' === key[0]) {
  3621. throw new BSONError('key ' + key + " must not start with '$'");
  3622. }
  3623. else if (~key.indexOf('.')) {
  3624. throw new BSONError('key ' + key + " must not contain '.'");
  3625. }
  3626. }
  3627. }
  3628. if (type === 'string') {
  3629. index = serializeString(buffer, key, value, index);
  3630. }
  3631. else if (type === 'number') {
  3632. index = serializeNumber(buffer, key, value, index);
  3633. }
  3634. else if (type === 'bigint') {
  3635. index = serializeBigInt(buffer, key, value, index);
  3636. }
  3637. else if (type === 'boolean') {
  3638. index = serializeBoolean(buffer, key, value, index);
  3639. }
  3640. else if (value instanceof Date || isDate(value)) {
  3641. index = serializeDate(buffer, key, value, index);
  3642. }
  3643. else if (value === undefined) {
  3644. if (ignoreUndefined === false)
  3645. index = serializeNull(buffer, key, value, index);
  3646. }
  3647. else if (value === null) {
  3648. index = serializeNull(buffer, key, value, index);
  3649. }
  3650. else if (isUint8Array(value)) {
  3651. index = serializeBuffer(buffer, key, value, index);
  3652. }
  3653. else if (value instanceof RegExp || isRegExp(value)) {
  3654. index = serializeRegExp(buffer, key, value, index);
  3655. }
  3656. else if (type === 'object' && value._bsontype == null) {
  3657. index = serializeObject(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3658. }
  3659. else if (typeof value === 'object' &&
  3660. value[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
  3661. throw new BSONVersionError();
  3662. }
  3663. else if (value._bsontype === 'ObjectId') {
  3664. index = serializeObjectId(buffer, key, value, index);
  3665. }
  3666. else if (type === 'object' && value._bsontype === 'Decimal128') {
  3667. index = serializeDecimal128(buffer, key, value, index);
  3668. }
  3669. else if (value._bsontype === 'Long' || value._bsontype === 'Timestamp') {
  3670. index = serializeLong(buffer, key, value, index);
  3671. }
  3672. else if (value._bsontype === 'Double') {
  3673. index = serializeDouble(buffer, key, value, index);
  3674. }
  3675. else if (value._bsontype === 'Code') {
  3676. index = serializeCode(buffer, key, value, index, checkKeys, depth, serializeFunctions, ignoreUndefined, path);
  3677. }
  3678. else if (typeof value === 'function' && serializeFunctions) {
  3679. index = serializeFunction(buffer, key, value, index);
  3680. }
  3681. else if (value._bsontype === 'Binary') {
  3682. index = serializeBinary(buffer, key, value, index);
  3683. }
  3684. else if (value._bsontype === 'BSONSymbol') {
  3685. index = serializeSymbol(buffer, key, value, index);
  3686. }
  3687. else if (value._bsontype === 'DBRef') {
  3688. index = serializeDBRef(buffer, key, value, index, depth, serializeFunctions, path);
  3689. }
  3690. else if (value._bsontype === 'BSONRegExp') {
  3691. index = serializeBSONRegExp(buffer, key, value, index);
  3692. }
  3693. else if (value._bsontype === 'Int32') {
  3694. index = serializeInt32(buffer, key, value, index);
  3695. }
  3696. else if (value._bsontype === 'MinKey' || value._bsontype === 'MaxKey') {
  3697. index = serializeMinMax(buffer, key, value, index);
  3698. }
  3699. else if (typeof value._bsontype !== 'undefined') {
  3700. throw new BSONError(`Unrecognized or invalid _bsontype: ${String(value._bsontype)}`);
  3701. }
  3702. }
  3703. }
  3704. path.delete(object);
  3705. buffer[index++] = 0x00;
  3706. const size = index - startingIndex;
  3707. buffer[startingIndex++] = size & 0xff;
  3708. buffer[startingIndex++] = (size >> 8) & 0xff;
  3709. buffer[startingIndex++] = (size >> 16) & 0xff;
  3710. buffer[startingIndex++] = (size >> 24) & 0xff;
  3711. return index;
  3712. }
  3713. function isBSONType(value) {
  3714. return (value != null &&
  3715. typeof value === 'object' &&
  3716. '_bsontype' in value &&
  3717. typeof value._bsontype === 'string');
  3718. }
  3719. const keysToCodecs = {
  3720. $oid: ObjectId,
  3721. $binary: Binary,
  3722. $uuid: Binary,
  3723. $symbol: BSONSymbol,
  3724. $numberInt: Int32,
  3725. $numberDecimal: Decimal128,
  3726. $numberDouble: Double,
  3727. $numberLong: Long,
  3728. $minKey: MinKey,
  3729. $maxKey: MaxKey,
  3730. $regex: BSONRegExp,
  3731. $regularExpression: BSONRegExp,
  3732. $timestamp: Timestamp
  3733. };
  3734. function deserializeValue(value, options = {}) {
  3735. if (typeof value === 'number') {
  3736. const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
  3737. const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
  3738. if (options.relaxed || options.legacy) {
  3739. return value;
  3740. }
  3741. if (Number.isInteger(value) && !Object.is(value, -0)) {
  3742. if (in32BitRange) {
  3743. return new Int32(value);
  3744. }
  3745. if (in64BitRange) {
  3746. if (options.useBigInt64) {
  3747. return BigInt(value);
  3748. }
  3749. return Long.fromNumber(value);
  3750. }
  3751. }
  3752. return new Double(value);
  3753. }
  3754. if (value == null || typeof value !== 'object')
  3755. return value;
  3756. if (value.$undefined)
  3757. return null;
  3758. const keys = Object.keys(value).filter(k => k.startsWith('$') && value[k] != null);
  3759. for (let i = 0; i < keys.length; i++) {
  3760. const c = keysToCodecs[keys[i]];
  3761. if (c)
  3762. return c.fromExtendedJSON(value, options);
  3763. }
  3764. if (value.$date != null) {
  3765. const d = value.$date;
  3766. const date = new Date();
  3767. if (options.legacy) {
  3768. if (typeof d === 'number')
  3769. date.setTime(d);
  3770. else if (typeof d === 'string')
  3771. date.setTime(Date.parse(d));
  3772. else if (typeof d === 'bigint')
  3773. date.setTime(Number(d));
  3774. else
  3775. throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
  3776. }
  3777. else {
  3778. if (typeof d === 'string')
  3779. date.setTime(Date.parse(d));
  3780. else if (Long.isLong(d))
  3781. date.setTime(d.toNumber());
  3782. else if (typeof d === 'number' && options.relaxed)
  3783. date.setTime(d);
  3784. else if (typeof d === 'bigint')
  3785. date.setTime(Number(d));
  3786. else
  3787. throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
  3788. }
  3789. return date;
  3790. }
  3791. if (value.$code != null) {
  3792. const copy = Object.assign({}, value);
  3793. if (value.$scope) {
  3794. copy.$scope = deserializeValue(value.$scope);
  3795. }
  3796. return Code.fromExtendedJSON(value);
  3797. }
  3798. if (isDBRefLike(value) || value.$dbPointer) {
  3799. const v = value.$ref ? value : value.$dbPointer;
  3800. if (v instanceof DBRef)
  3801. return v;
  3802. const dollarKeys = Object.keys(v).filter(k => k.startsWith('$'));
  3803. let valid = true;
  3804. dollarKeys.forEach(k => {
  3805. if (['$ref', '$id', '$db'].indexOf(k) === -1)
  3806. valid = false;
  3807. });
  3808. if (valid)
  3809. return DBRef.fromExtendedJSON(v);
  3810. }
  3811. return value;
  3812. }
  3813. function serializeArray(array, options) {
  3814. return array.map((v, index) => {
  3815. options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
  3816. try {
  3817. return serializeValue(v, options);
  3818. }
  3819. finally {
  3820. options.seenObjects.pop();
  3821. }
  3822. });
  3823. }
  3824. function getISOString(date) {
  3825. const isoStr = date.toISOString();
  3826. return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + 'Z';
  3827. }
  3828. function serializeValue(value, options) {
  3829. if (value instanceof Map || isMap(value)) {
  3830. const obj = Object.create(null);
  3831. for (const [k, v] of value) {
  3832. if (typeof k !== 'string') {
  3833. throw new BSONError('Can only serialize maps with string keys');
  3834. }
  3835. obj[k] = v;
  3836. }
  3837. return serializeValue(obj, options);
  3838. }
  3839. if ((typeof value === 'object' || typeof value === 'function') && value !== null) {
  3840. const index = options.seenObjects.findIndex(entry => entry.obj === value);
  3841. if (index !== -1) {
  3842. const props = options.seenObjects.map(entry => entry.propertyName);
  3843. const leadingPart = props
  3844. .slice(0, index)
  3845. .map(prop => `${prop} -> `)
  3846. .join('');
  3847. const alreadySeen = props[index];
  3848. const circularPart = ' -> ' +
  3849. props
  3850. .slice(index + 1, props.length - 1)
  3851. .map(prop => `${prop} -> `)
  3852. .join('');
  3853. const current = props[props.length - 1];
  3854. const leadingSpace = ' '.repeat(leadingPart.length + alreadySeen.length / 2);
  3855. const dashes = '-'.repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
  3856. throw new BSONError('Converting circular structure to EJSON:\n' +
  3857. ` ${leadingPart}${alreadySeen}${circularPart}${current}\n` +
  3858. ` ${leadingSpace}\\${dashes}/`);
  3859. }
  3860. options.seenObjects[options.seenObjects.length - 1].obj = value;
  3861. }
  3862. if (Array.isArray(value))
  3863. return serializeArray(value, options);
  3864. if (value === undefined)
  3865. return null;
  3866. if (value instanceof Date || isDate(value)) {
  3867. const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 253402318800000;
  3868. if (options.legacy) {
  3869. return options.relaxed && inRange
  3870. ? { $date: value.getTime() }
  3871. : { $date: getISOString(value) };
  3872. }
  3873. return options.relaxed && inRange
  3874. ? { $date: getISOString(value) }
  3875. : { $date: { $numberLong: value.getTime().toString() } };
  3876. }
  3877. if (typeof value === 'number' && (!options.relaxed || !isFinite(value))) {
  3878. if (Number.isInteger(value) && !Object.is(value, -0)) {
  3879. if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
  3880. return { $numberInt: value.toString() };
  3881. }
  3882. if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
  3883. return { $numberLong: value.toString() };
  3884. }
  3885. }
  3886. return { $numberDouble: Object.is(value, -0) ? '-0.0' : value.toString() };
  3887. }
  3888. if (typeof value === 'bigint') {
  3889. if (!options.relaxed) {
  3890. return { $numberLong: BigInt.asIntN(64, value).toString() };
  3891. }
  3892. return Number(BigInt.asIntN(64, value));
  3893. }
  3894. if (value instanceof RegExp || isRegExp(value)) {
  3895. let flags = value.flags;
  3896. if (flags === undefined) {
  3897. const match = value.toString().match(/[gimuy]*$/);
  3898. if (match) {
  3899. flags = match[0];
  3900. }
  3901. }
  3902. const rx = new BSONRegExp(value.source, flags);
  3903. return rx.toExtendedJSON(options);
  3904. }
  3905. if (value != null && typeof value === 'object')
  3906. return serializeDocument(value, options);
  3907. return value;
  3908. }
  3909. const BSON_TYPE_MAPPINGS = {
  3910. Binary: (o) => new Binary(o.value(), o.sub_type),
  3911. Code: (o) => new Code(o.code, o.scope),
  3912. DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields),
  3913. Decimal128: (o) => new Decimal128(o.bytes),
  3914. Double: (o) => new Double(o.value),
  3915. Int32: (o) => new Int32(o.value),
  3916. Long: (o) => Long.fromBits(o.low != null ? o.low : o.low_, o.low != null ? o.high : o.high_, o.low != null ? o.unsigned : o.unsigned_),
  3917. MaxKey: () => new MaxKey(),
  3918. MinKey: () => new MinKey(),
  3919. ObjectId: (o) => new ObjectId(o),
  3920. BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options),
  3921. BSONSymbol: (o) => new BSONSymbol(o.value),
  3922. Timestamp: (o) => Timestamp.fromBits(o.low, o.high)
  3923. };
  3924. function serializeDocument(doc, options) {
  3925. if (doc == null || typeof doc !== 'object')
  3926. throw new BSONError('not an object instance');
  3927. const bsontype = doc._bsontype;
  3928. if (typeof bsontype === 'undefined') {
  3929. const _doc = {};
  3930. for (const name of Object.keys(doc)) {
  3931. options.seenObjects.push({ propertyName: name, obj: null });
  3932. try {
  3933. const value = serializeValue(doc[name], options);
  3934. if (name === '__proto__') {
  3935. Object.defineProperty(_doc, name, {
  3936. value,
  3937. writable: true,
  3938. enumerable: true,
  3939. configurable: true
  3940. });
  3941. }
  3942. else {
  3943. _doc[name] = value;
  3944. }
  3945. }
  3946. finally {
  3947. options.seenObjects.pop();
  3948. }
  3949. }
  3950. return _doc;
  3951. }
  3952. else if (doc != null &&
  3953. typeof doc === 'object' &&
  3954. typeof doc._bsontype === 'string' &&
  3955. doc[Symbol.for('@@mdb.bson.version')] !== BSON_MAJOR_VERSION) {
  3956. throw new BSONVersionError();
  3957. }
  3958. else if (isBSONType(doc)) {
  3959. let outDoc = doc;
  3960. if (typeof outDoc.toExtendedJSON !== 'function') {
  3961. const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
  3962. if (!mapper) {
  3963. throw new BSONError('Unrecognized or invalid _bsontype: ' + doc._bsontype);
  3964. }
  3965. outDoc = mapper(outDoc);
  3966. }
  3967. if (bsontype === 'Code' && outDoc.scope) {
  3968. outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
  3969. }
  3970. else if (bsontype === 'DBRef' && outDoc.oid) {
  3971. outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
  3972. }
  3973. return outDoc.toExtendedJSON(options);
  3974. }
  3975. else {
  3976. throw new BSONError('_bsontype must be a string, but was: ' + typeof bsontype);
  3977. }
  3978. }
  3979. function parse(text, options) {
  3980. const ejsonOptions = {
  3981. useBigInt64: options?.useBigInt64 ?? false,
  3982. relaxed: options?.relaxed ?? true,
  3983. legacy: options?.legacy ?? false
  3984. };
  3985. return JSON.parse(text, (key, value) => {
  3986. if (key.indexOf('\x00') !== -1) {
  3987. throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
  3988. }
  3989. return deserializeValue(value, ejsonOptions);
  3990. });
  3991. }
  3992. function stringify(value, replacer, space, options) {
  3993. if (space != null && typeof space === 'object') {
  3994. options = space;
  3995. space = 0;
  3996. }
  3997. if (replacer != null && typeof replacer === 'object' && !Array.isArray(replacer)) {
  3998. options = replacer;
  3999. replacer = undefined;
  4000. space = 0;
  4001. }
  4002. const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
  4003. seenObjects: [{ propertyName: '(root)', obj: null }]
  4004. });
  4005. const doc = serializeValue(value, serializeOptions);
  4006. return JSON.stringify(doc, replacer, space);
  4007. }
  4008. function EJSONserialize(value, options) {
  4009. options = options || {};
  4010. return JSON.parse(stringify(value, options));
  4011. }
  4012. function EJSONdeserialize(ejson, options) {
  4013. options = options || {};
  4014. return parse(JSON.stringify(ejson), options);
  4015. }
  4016. const EJSON = Object.create(null);
  4017. EJSON.parse = parse;
  4018. EJSON.stringify = stringify;
  4019. EJSON.serialize = EJSONserialize;
  4020. EJSON.deserialize = EJSONdeserialize;
  4021. Object.freeze(EJSON);
  4022. const MAXSIZE = 1024 * 1024 * 17;
  4023. let buffer = ByteUtils.allocate(MAXSIZE);
  4024. function setInternalBufferSize(size) {
  4025. if (buffer.length < size) {
  4026. buffer = ByteUtils.allocate(size);
  4027. }
  4028. }
  4029. function serialize(object, options = {}) {
  4030. const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  4031. const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4032. const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4033. const minInternalBufferSize = typeof options.minInternalBufferSize === 'number' ? options.minInternalBufferSize : MAXSIZE;
  4034. if (buffer.length < minInternalBufferSize) {
  4035. buffer = ByteUtils.allocate(minInternalBufferSize);
  4036. }
  4037. const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
  4038. const finishedBuffer = ByteUtils.allocate(serializationIndex);
  4039. finishedBuffer.set(buffer.subarray(0, serializationIndex), 0);
  4040. return finishedBuffer;
  4041. }
  4042. function serializeWithBufferAndIndex(object, finalBuffer, options = {}) {
  4043. const checkKeys = typeof options.checkKeys === 'boolean' ? options.checkKeys : false;
  4044. const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4045. const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4046. const startIndex = typeof options.index === 'number' ? options.index : 0;
  4047. const serializationIndex = serializeInto(buffer, object, checkKeys, 0, 0, serializeFunctions, ignoreUndefined, null);
  4048. finalBuffer.set(buffer.subarray(0, serializationIndex), startIndex);
  4049. return startIndex + serializationIndex - 1;
  4050. }
  4051. function deserialize(buffer, options = {}) {
  4052. return internalDeserialize(ByteUtils.toLocalBufferType(buffer), options);
  4053. }
  4054. function calculateObjectSize(object, options = {}) {
  4055. options = options || {};
  4056. const serializeFunctions = typeof options.serializeFunctions === 'boolean' ? options.serializeFunctions : false;
  4057. const ignoreUndefined = typeof options.ignoreUndefined === 'boolean' ? options.ignoreUndefined : true;
  4058. return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined);
  4059. }
  4060. function deserializeStream(data, startIndex, numberOfDocuments, documents, docStartIndex, options) {
  4061. const internalOptions = Object.assign({ allowObjectSmallerThanBufferSize: true, index: 0 }, options);
  4062. const bufferData = ByteUtils.toLocalBufferType(data);
  4063. let index = startIndex;
  4064. for (let i = 0; i < numberOfDocuments; i++) {
  4065. const size = bufferData[index] |
  4066. (bufferData[index + 1] << 8) |
  4067. (bufferData[index + 2] << 16) |
  4068. (bufferData[index + 3] << 24);
  4069. internalOptions.index = index;
  4070. documents[docStartIndex + i] = internalDeserialize(bufferData, internalOptions);
  4071. index = index + size;
  4072. }
  4073. return index;
  4074. }
  4075. var bson = /*#__PURE__*/Object.freeze({
  4076. __proto__: null,
  4077. BSONError: BSONError,
  4078. BSONRegExp: BSONRegExp,
  4079. BSONRuntimeError: BSONRuntimeError,
  4080. BSONSymbol: BSONSymbol,
  4081. BSONType: BSONType,
  4082. BSONValue: BSONValue,
  4083. BSONVersionError: BSONVersionError,
  4084. Binary: Binary,
  4085. Code: Code,
  4086. DBRef: DBRef,
  4087. Decimal128: Decimal128,
  4088. Double: Double,
  4089. EJSON: EJSON,
  4090. Int32: Int32,
  4091. Long: Long,
  4092. MaxKey: MaxKey,
  4093. MinKey: MinKey,
  4094. ObjectId: ObjectId,
  4095. Timestamp: Timestamp,
  4096. UUID: UUID,
  4097. calculateObjectSize: calculateObjectSize,
  4098. deserialize: deserialize,
  4099. deserializeStream: deserializeStream,
  4100. serialize: serialize,
  4101. serializeWithBufferAndIndex: serializeWithBufferAndIndex,
  4102. setInternalBufferSize: setInternalBufferSize
  4103. });
  4104. exports.BSON = bson;
  4105. exports.BSONError = BSONError;
  4106. exports.BSONRegExp = BSONRegExp;
  4107. exports.BSONRuntimeError = BSONRuntimeError;
  4108. exports.BSONSymbol = BSONSymbol;
  4109. exports.BSONType = BSONType;
  4110. exports.BSONValue = BSONValue;
  4111. exports.BSONVersionError = BSONVersionError;
  4112. exports.Binary = Binary;
  4113. exports.Code = Code;
  4114. exports.DBRef = DBRef;
  4115. exports.Decimal128 = Decimal128;
  4116. exports.Double = Double;
  4117. exports.EJSON = EJSON;
  4118. exports.Int32 = Int32;
  4119. exports.Long = Long;
  4120. exports.MaxKey = MaxKey;
  4121. exports.MinKey = MinKey;
  4122. exports.ObjectId = ObjectId;
  4123. exports.Timestamp = Timestamp;
  4124. exports.UUID = UUID;
  4125. exports.calculateObjectSize = calculateObjectSize;
  4126. exports.deserialize = deserialize;
  4127. exports.deserializeStream = deserializeStream;
  4128. exports.serialize = serialize;
  4129. exports.serializeWithBufferAndIndex = serializeWithBufferAndIndex;
  4130. exports.setInternalBufferSize = setInternalBufferSize;
  4131. //# sourceMappingURL=bson.rn.cjs.map