bson.mjs 154 KB

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