bson.bundle.js 174 KB

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