@eeplatform/basic-edu 1.2.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -707,7 +707,7 @@ var require_papaparse = __commonJS({
707
707
  function ParserHandle(_config) {
708
708
  var MAX_FLOAT = Math.pow(2, 53);
709
709
  var MIN_FLOAT = -MAX_FLOAT;
710
- var FLOAT2 = /^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/;
710
+ var FLOAT = /^\s*-?(\d+\.?|\.\d+|\d+\.\d+)([eE][-+]?\d+)?\s*$/;
711
711
  var ISO_DATE = /^((\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z)))$/;
712
712
  var self2 = this;
713
713
  var _stepCounter = 0;
@@ -818,7 +818,7 @@ var require_papaparse = __commonJS({
818
818
  return _config.skipEmptyLines === "greedy" ? s.join("").trim() === "" : s.length === 1 && s[0].length === 0;
819
819
  }
820
820
  function testFloat(s) {
821
- if (FLOAT2.test(s)) {
821
+ if (FLOAT.test(s)) {
822
822
  var floatValue = parseFloat(s);
823
823
  if (floatValue > MIN_FLOAT && floatValue < MAX_FLOAT) {
824
824
  return true;
@@ -4045,6 +4045,20 @@ function modelDivision(value) {
4045
4045
  throw new Error("Invalid _id.");
4046
4046
  }
4047
4047
  }
4048
+ if (value.region && typeof value.region === "string") {
4049
+ try {
4050
+ value.region = ObjectId9.createFromTime(value.region);
4051
+ } catch (error2) {
4052
+ throw new Error("Invalid region.");
4053
+ }
4054
+ }
4055
+ if (value.superintendent && typeof value.superintendent === "string") {
4056
+ try {
4057
+ value.superintendent = ObjectId9.createFromTime(value.superintendent);
4058
+ } catch (error2) {
4059
+ throw new Error("Invalid superintendent.");
4060
+ }
4061
+ }
4048
4062
  return {
4049
4063
  _id: value._id,
4050
4064
  name: value.name,
@@ -4135,7 +4149,8 @@ function useDivisionRepo() {
4135
4149
  page = 1,
4136
4150
  limit = 10,
4137
4151
  sort = {},
4138
- status = "active"
4152
+ status = "active",
4153
+ region = ""
4139
4154
  } = {}) {
4140
4155
  page = page > 0 ? page - 1 : 0;
4141
4156
  const query = {
@@ -4153,6 +4168,17 @@ function useDivisionRepo() {
4153
4168
  query.$text = { $search: search };
4154
4169
  cacheKeyOptions.search = search;
4155
4170
  }
4171
+ if (region) {
4172
+ try {
4173
+ query.region = new ObjectId10(region);
4174
+ } catch (error) {
4175
+ logger12.log({
4176
+ level: "error",
4177
+ message: "Invalid region ID format."
4178
+ });
4179
+ }
4180
+ cacheKeyOptions.region = region;
4181
+ }
4156
4182
  const cacheKey = makeCacheKey5(namespace_collection, cacheKeyOptions);
4157
4183
  logger12.log({
4158
4184
  level: "info",
@@ -4423,13 +4449,15 @@ function useDivisionController() {
4423
4449
  page: Joi10.number().min(1).optional().allow("", null),
4424
4450
  limit: Joi10.number().min(1).optional().allow("", null),
4425
4451
  search: Joi10.string().optional().allow("", null),
4426
- status: Joi10.string().optional().allow("", null)
4452
+ status: Joi10.string().optional().allow("", null),
4453
+ region: Joi10.string().hex().optional().allow("", null)
4427
4454
  });
4428
4455
  const { error } = validation.validate(query);
4429
4456
  const page = typeof req.query.page === "string" ? Number(req.query.page) : 1;
4430
4457
  const limit = typeof req.query.limit === "string" ? Number(req.query.limit) : 10;
4431
4458
  const search = req.query.search ?? "";
4432
4459
  const status = req.query.status ?? "active";
4460
+ const region = req.query.region ?? "";
4433
4461
  const isPageNumber = isFinite(page);
4434
4462
  if (!isPageNumber) {
4435
4463
  next(new BadRequestError16("Invalid page number."));
@@ -4445,7 +4473,7 @@ function useDivisionController() {
4445
4473
  return;
4446
4474
  }
4447
4475
  try {
4448
- const data = await _getAll({ page, limit, search, status });
4476
+ const data = await _getAll({ page, limit, search, status, region });
4449
4477
  res.json(data);
4450
4478
  return;
4451
4479
  } catch (error2) {
@@ -4568,24 +4596,46 @@ var schemaSchool = Joi11.object({
4568
4596
  _id: Joi11.string().hex().optional().allow(null, ""),
4569
4597
  id: Joi11.string().min(1).max(50).required(),
4570
4598
  name: Joi11.string().min(1).max(100).required(),
4571
- region: Joi11.string().hex().optional().allow(null, ""),
4599
+ region: Joi11.string().hex().required(),
4572
4600
  regionName: Joi11.string().min(1).max(100).optional().allow(null, ""),
4573
- division: Joi11.string().hex().optional().allow(null, ""),
4601
+ division: Joi11.string().hex().required(),
4574
4602
  divisionName: Joi11.string().min(1).max(100).optional().allow(null, ""),
4575
4603
  principal: Joi11.string().hex().optional().allow(null, ""),
4576
4604
  principalName: Joi11.string().min(1).max(100).optional().allow(null, ""),
4577
4605
  street: Joi11.string().max(200).optional().allow(null, ""),
4578
4606
  barangay: Joi11.string().max(200).optional().allow(null, ""),
4579
- city: Joi11.string().max(100).optional().allow(null, ""),
4607
+ cityMunicipality: Joi11.string().max(100).optional().allow(null, ""),
4580
4608
  province: Joi11.string().max(100).optional().allow(null, ""),
4609
+ provincePSGC: Joi11.number().optional().allow(null, ""),
4610
+ cityMunicipalityPSGC: Joi11.number().optional().allow(null, ""),
4581
4611
  postalCode: Joi11.string().max(20).optional().allow(null, ""),
4582
4612
  contactNumber: Joi11.string().max(20).optional().allow(null, ""),
4583
4613
  email: Joi11.string().email().max(100).optional().allow(null, ""),
4614
+ status: Joi11.string().optional().allow(null, ""),
4584
4615
  createdBy: Joi11.string().optional().allow(null, ""),
4585
4616
  createdAt: Joi11.string().isoDate().optional().allow(null, ""),
4586
4617
  updatedAt: Joi11.string().isoDate().optional().allow(null, ""),
4587
4618
  deletedAt: Joi11.string().isoDate().optional().allow(null, "")
4588
4619
  });
4620
+ var schemaSchoolUpdate = Joi11.object({
4621
+ id: Joi11.string().min(1).max(50).required(),
4622
+ name: Joi11.string().min(1).max(100).required(),
4623
+ region: Joi11.string().hex().required(),
4624
+ regionName: Joi11.string().min(1).max(100).optional().allow(null, ""),
4625
+ division: Joi11.string().hex().required(),
4626
+ divisionName: Joi11.string().min(1).max(100).optional().allow(null, ""),
4627
+ principal: Joi11.string().hex().optional().allow(null, ""),
4628
+ principalName: Joi11.string().min(1).max(100).optional().allow(null, ""),
4629
+ street: Joi11.string().max(200).optional().allow(null, ""),
4630
+ barangay: Joi11.string().max(200).optional().allow(null, ""),
4631
+ cityMunicipality: Joi11.string().max(100).optional().allow(null, ""),
4632
+ province: Joi11.string().max(100).optional().allow(null, ""),
4633
+ provincePSGC: Joi11.number().optional().allow(null, ""),
4634
+ cityMunicipalityPSGC: Joi11.number().optional().allow(null, ""),
4635
+ postalCode: Joi11.string().max(20).optional().allow(null, ""),
4636
+ contactNumber: Joi11.string().max(20).optional().allow(null, ""),
4637
+ email: Joi11.string().email().max(100).optional().allow(null, "")
4638
+ });
4589
4639
  function modelSchool(value) {
4590
4640
  const { error } = schemaSchool.validate(value);
4591
4641
  if (error) {
@@ -4598,6 +4648,27 @@ function modelSchool(value) {
4598
4648
  throw new Error("Invalid _id.");
4599
4649
  }
4600
4650
  }
4651
+ if (value.region && typeof value.region === "string") {
4652
+ try {
4653
+ value.region = new ObjectId11(value.region);
4654
+ } catch (error2) {
4655
+ throw new Error("Invalid region.");
4656
+ }
4657
+ }
4658
+ if (value.division && typeof value.division === "string") {
4659
+ try {
4660
+ value.division = new ObjectId11(value.division);
4661
+ } catch (error2) {
4662
+ throw new Error("Invalid region.");
4663
+ }
4664
+ }
4665
+ if (value.principal && typeof value.principal === "string") {
4666
+ try {
4667
+ value.principal = new ObjectId11(value.principal);
4668
+ } catch (error2) {
4669
+ throw new Error("Invalid principal.");
4670
+ }
4671
+ }
4601
4672
  return {
4602
4673
  _id: value._id,
4603
4674
  id: value.id,
@@ -4608,14 +4679,16 @@ function modelSchool(value) {
4608
4679
  divisionName: value.divisionName ?? "",
4609
4680
  principal: value.principal,
4610
4681
  principalName: value.principalName ?? "",
4611
- status: value.status ?? "active",
4612
4682
  street: value.street ?? "",
4613
4683
  barangay: value.barangay ?? "",
4614
- city: value.city ?? "",
4684
+ cityMunicipality: value.cityMunicipality ?? "",
4615
4685
  province: value.province ?? "",
4616
4686
  postalCode: value.postalCode ?? "",
4617
4687
  contactNumber: value.contactNumber ?? "",
4618
4688
  email: value.email ?? "",
4689
+ status: value.status ?? "active",
4690
+ provincePSGC: value.provincePSGC ?? 0,
4691
+ cityMunicipalityPSGC: value.cityMunicipalityPSGC ?? 0,
4619
4692
  createdBy: value.createdBy ?? "",
4620
4693
  createdAt: value.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
4621
4694
  updatedAt: value.updatedAt ?? "",
@@ -4649,7 +4722,7 @@ function useSchoolRepo() {
4649
4722
  { key: { name: 1 } },
4650
4723
  { key: { createdAt: 1 } },
4651
4724
  { key: { name: "text" } },
4652
- { key: { name: 1 }, unique: true, name: "unique_name" }
4725
+ { key: { id: 1, status: 1 }, unique: true, name: "unique_school_id" }
4653
4726
  ]);
4654
4727
  } catch (error) {
4655
4728
  throw new Error("Failed to create index on schools.");
@@ -4668,25 +4741,35 @@ function useSchoolRepo() {
4668
4741
  });
4669
4742
  });
4670
4743
  }
4671
- async function add(value, session) {
4744
+ async function add(value, session, clearCache = true) {
4672
4745
  try {
4673
4746
  value = modelSchool(value);
4674
4747
  const res = await collection.insertOne(value, { session });
4675
- delCachedData();
4748
+ if (clearCache) {
4749
+ delCachedData();
4750
+ }
4676
4751
  return res.insertedId;
4677
4752
  } catch (error) {
4678
4753
  logger13.log({
4679
4754
  level: "error",
4680
- message: error.message
4755
+ message: `Failed to add school: ${error.message}`,
4756
+ metadata: {
4757
+ code: error.code,
4758
+ codeName: error.codeName,
4759
+ errorLabels: error.errorLabelSet ? Array.from(error.errorLabelSet) : [],
4760
+ schoolName: value?.name || "unknown",
4761
+ hasSession: !!session,
4762
+ transactionNumber: error.errorResponse?.txnNumber || "unknown"
4763
+ }
4681
4764
  });
4682
4765
  if (error instanceof AppError6) {
4683
4766
  throw error;
4684
4767
  } else {
4685
4768
  const isDuplicated = error.message.includes("duplicate");
4686
4769
  if (isDuplicated) {
4687
- throw new BadRequestError18("School already exists.");
4770
+ throw new BadRequestError18("Duplicate, school already exists.");
4688
4771
  }
4689
- throw new Error("Failed to create school.");
4772
+ throw new InternalServerError7("Failed to add school.");
4690
4773
  }
4691
4774
  }
4692
4775
  }
@@ -4928,6 +5011,24 @@ function useSchoolRepo() {
4928
5011
  throw new InternalServerError7(`Failed to update school ${field}.`);
4929
5012
  }
4930
5013
  }
5014
+ async function updateById(_id, options, session) {
5015
+ const { error } = schemaSchoolUpdate.validate(options);
5016
+ if (error) {
5017
+ throw new BadRequestError18(`Invalid school data: ${error.message}`);
5018
+ }
5019
+ try {
5020
+ _id = new ObjectId12(_id);
5021
+ } catch (error2) {
5022
+ throw new BadRequestError18("Invalid ID.");
5023
+ }
5024
+ try {
5025
+ await collection.updateOne({ _id }, { $set: options }, { session });
5026
+ delCachedData();
5027
+ return `Successfully updated school.`;
5028
+ } catch (error2) {
5029
+ throw new InternalServerError7(`Failed to update school.`);
5030
+ }
5031
+ }
4931
5032
  async function deleteById(_id) {
4932
5033
  try {
4933
5034
  _id = new ObjectId12(_id);
@@ -4937,7 +5038,7 @@ function useSchoolRepo() {
4937
5038
  try {
4938
5039
  await collection.updateOne(
4939
5040
  { _id },
4940
- { $set: { deletedAt: (/* @__PURE__ */ new Date()).toISOString() } }
5041
+ { $set: { status: "deleted", deletedAt: (/* @__PURE__ */ new Date()).toISOString() } }
4941
5042
  );
4942
5043
  delCachedData();
4943
5044
  return "Successfully deleted school.";
@@ -4953,14 +5054,21 @@ function useSchoolRepo() {
4953
5054
  getPendingByCreatedBy,
4954
5055
  updateStatusById,
4955
5056
  updateFieldById,
5057
+ updateById,
4956
5058
  deleteById,
4957
- getByName
5059
+ getByName,
5060
+ delCachedData
4958
5061
  };
4959
5062
  }
4960
5063
 
4961
5064
  // src/resources/school/school.service.ts
4962
5065
  import { BadRequestError as BadRequestError19, useAtlas as useAtlas9, logger as logger14 } from "@eeplatform/nodejs-utils";
4963
- import { useRoleRepo as useRoleRepo2, useUserRepo, useMemberRepo } from "@eeplatform/core";
5066
+ import {
5067
+ useRoleRepo as useRoleRepo2,
5068
+ useUserRepo,
5069
+ useMemberRepo,
5070
+ usePSGCRepo
5071
+ } from "@eeplatform/core";
4964
5072
 
4965
5073
  // node_modules/xlsx/xlsx.mjs
4966
5074
  var XLSX = {};
@@ -7029,11 +7137,11 @@ var CFB = /* @__PURE__ */ function _CFB() {
7029
7137
  }
7030
7138
  return o;
7031
7139
  }
7032
- var fs;
7140
+ var fs2;
7033
7141
  function get_fs() {
7034
- return fs || (fs = {});
7142
+ return fs2 || (fs2 = {});
7035
7143
  }
7036
- function parse4(file, options) {
7144
+ function parse3(file, options) {
7037
7145
  if (file[0] == 80 && file[1] == 75)
7038
7146
  return parse_zip2(file, options);
7039
7147
  if ((file[0] | 32) == 109 && (file[1] | 32) == 105)
@@ -7354,7 +7462,7 @@ var CFB = /* @__PURE__ */ function _CFB() {
7354
7462
  }
7355
7463
  function read_file(filename2, options) {
7356
7464
  get_fs();
7357
- return parse4(fs.readFileSync(filename2), options);
7465
+ return parse3(fs2.readFileSync(filename2), options);
7358
7466
  }
7359
7467
  function read(blob, options) {
7360
7468
  var type = options && options.type;
@@ -7366,11 +7474,11 @@ var CFB = /* @__PURE__ */ function _CFB() {
7366
7474
  case "file":
7367
7475
  return read_file(blob, options);
7368
7476
  case "base64":
7369
- return parse4(s2a(Base64_decode(blob)), options);
7477
+ return parse3(s2a(Base64_decode(blob)), options);
7370
7478
  case "binary":
7371
- return parse4(s2a(blob), options);
7479
+ return parse3(s2a(blob), options);
7372
7480
  }
7373
- return parse4(
7481
+ return parse3(
7374
7482
  /*::typeof blob == 'string' ? new Buffer(blob, 'utf-8') : */
7375
7483
  blob,
7376
7484
  options
@@ -7736,7 +7844,7 @@ var CFB = /* @__PURE__ */ function _CFB() {
7736
7844
  function write_file(cfb, filename2, options) {
7737
7845
  get_fs();
7738
7846
  var o = _write(cfb, options);
7739
- fs.writeFileSync(filename2, o);
7847
+ fs2.writeFileSync(filename2, o);
7740
7848
  }
7741
7849
  function a2s2(o) {
7742
7850
  var out = new Array(o.length);
@@ -7749,7 +7857,7 @@ var CFB = /* @__PURE__ */ function _CFB() {
7749
7857
  switch (options && options.type || "buffer") {
7750
7858
  case "file":
7751
7859
  get_fs();
7752
- fs.writeFileSync(options.filename, o);
7860
+ fs2.writeFileSync(options.filename, o);
7753
7861
  return o;
7754
7862
  case "binary":
7755
7863
  return typeof o == "string" ? o : a2s2(o);
@@ -8728,7 +8836,7 @@ var CFB = /* @__PURE__ */ function _CFB() {
8728
8836
  }
8729
8837
  exports.find = find;
8730
8838
  exports.read = read;
8731
- exports.parse = parse4;
8839
+ exports.parse = parse3;
8732
8840
  exports.write = write;
8733
8841
  exports.writeFile = write_file;
8734
8842
  exports.utils = {
@@ -32758,7 +32866,7 @@ function sheet_to_json(sheet, opts) {
32758
32866
  return out;
32759
32867
  }
32760
32868
  var qreg = /"/g;
32761
- function make_csv_row(sheet, r, R, cols, fs, rs, FS, o) {
32869
+ function make_csv_row(sheet, r, R, cols, fs2, rs, FS, o) {
32762
32870
  var isempty = true;
32763
32871
  var row = [], txt = "", rr = encode_row(R);
32764
32872
  for (var C = r.s.c; C <= r.e.c; ++C) {
@@ -32771,7 +32879,7 @@ function make_csv_row(sheet, r, R, cols, fs, rs, FS, o) {
32771
32879
  isempty = false;
32772
32880
  txt = "" + (o.rawNumbers && val.t == "n" ? val.v : format_cell(val, null, o));
32773
32881
  for (var i = 0, cc = 0; i !== txt.length; ++i)
32774
- if ((cc = txt.charCodeAt(i)) === fs || cc === rs || cc === 34 || o.forceQuotes) {
32882
+ if ((cc = txt.charCodeAt(i)) === fs2 || cc === rs || cc === 34 || o.forceQuotes) {
32775
32883
  txt = '"' + txt.replace(qreg, '""') + '"';
32776
32884
  break;
32777
32885
  }
@@ -32796,7 +32904,7 @@ function sheet_to_csv(sheet, opts) {
32796
32904
  if (sheet == null || sheet["!ref"] == null)
32797
32905
  return "";
32798
32906
  var r = safe_decode_range(sheet["!ref"]);
32799
- var FS = o.FS !== void 0 ? o.FS : ",", fs = FS.charCodeAt(0);
32907
+ var FS = o.FS !== void 0 ? o.FS : ",", fs2 = FS.charCodeAt(0);
32800
32908
  var RS = o.RS !== void 0 ? o.RS : "\n", rs = RS.charCodeAt(0);
32801
32909
  var endregex = new RegExp((FS == "|" ? "\\|" : FS) + "+$");
32802
32910
  var row = "", cols = [];
@@ -32810,7 +32918,7 @@ function sheet_to_csv(sheet, opts) {
32810
32918
  for (var R = r.s.r; R <= r.e.r; ++R) {
32811
32919
  if ((rowinfo[R] || {}).hidden)
32812
32920
  continue;
32813
- row = make_csv_row(sheet, r, R, cols, fs, rs, FS, o);
32921
+ row = make_csv_row(sheet, r, R, cols, fs2, rs, FS, o);
32814
32922
  if (row == null) {
32815
32923
  continue;
32816
32924
  }
@@ -33119,3218 +33227,16 @@ var version = XLSX.version;
33119
33227
 
33120
33228
  // src/resources/school/school.service.ts
33121
33229
  var Papa = __toESM(require_papaparse());
33122
-
33123
- // node_modules/bson/lib/bson.node.mjs
33124
- import { randomBytes } from "crypto";
33125
- var TypedArrayPrototypeGetSymbolToStringTag = (() => {
33126
- const g = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get;
33127
- return (value) => g.call(value);
33128
- })();
33129
- function isUint8Array(value) {
33130
- return TypedArrayPrototypeGetSymbolToStringTag(value) === "Uint8Array";
33131
- }
33132
- function isAnyArrayBuffer(value) {
33133
- return typeof value === "object" && value != null && Symbol.toStringTag in value && (value[Symbol.toStringTag] === "ArrayBuffer" || value[Symbol.toStringTag] === "SharedArrayBuffer");
33134
- }
33135
- function isRegExp(regexp) {
33136
- return regexp instanceof RegExp || Object.prototype.toString.call(regexp) === "[object RegExp]";
33137
- }
33138
- function isMap(value) {
33139
- return typeof value === "object" && value != null && Symbol.toStringTag in value && value[Symbol.toStringTag] === "Map";
33140
- }
33141
- function isDate(date) {
33142
- return date instanceof Date || Object.prototype.toString.call(date) === "[object Date]";
33143
- }
33144
- function defaultInspect(x, _options) {
33145
- return JSON.stringify(x, (k, v) => {
33146
- if (typeof v === "bigint") {
33147
- return { $numberLong: `${v}` };
33148
- } else if (isMap(v)) {
33149
- return Object.fromEntries(v);
33150
- }
33151
- return v;
33152
- });
33153
- }
33154
- function getStylizeFunction(options) {
33155
- const stylizeExists = options != null && typeof options === "object" && "stylize" in options && typeof options.stylize === "function";
33156
- if (stylizeExists) {
33157
- return options.stylize;
33158
- }
33159
- }
33160
- var BSON_MAJOR_VERSION = 6;
33161
- var BSON_VERSION_SYMBOL = Symbol.for("@@mdb.bson.version");
33162
- var BSON_INT32_MAX = 2147483647;
33163
- var BSON_INT32_MIN = -2147483648;
33164
- var BSON_INT64_MAX = Math.pow(2, 63) - 1;
33165
- var BSON_INT64_MIN = -Math.pow(2, 63);
33166
- var JS_INT_MAX = Math.pow(2, 53);
33167
- var JS_INT_MIN = -Math.pow(2, 53);
33168
- var BSON_BINARY_SUBTYPE_UUID_NEW = 4;
33169
- var BSONType = Object.freeze({
33170
- double: 1,
33171
- string: 2,
33172
- object: 3,
33173
- array: 4,
33174
- binData: 5,
33175
- undefined: 6,
33176
- objectId: 7,
33177
- bool: 8,
33178
- date: 9,
33179
- null: 10,
33180
- regex: 11,
33181
- dbPointer: 12,
33182
- javascript: 13,
33183
- symbol: 14,
33184
- javascriptWithScope: 15,
33185
- int: 16,
33186
- timestamp: 17,
33187
- long: 18,
33188
- decimal: 19,
33189
- minKey: -1,
33190
- maxKey: 127
33191
- });
33192
- var BSONError = class extends Error {
33193
- get bsonError() {
33194
- return true;
33195
- }
33196
- get name() {
33197
- return "BSONError";
33198
- }
33199
- constructor(message, options) {
33200
- super(message, options);
33201
- }
33202
- static isBSONError(value) {
33203
- return value != null && typeof value === "object" && "bsonError" in value && value.bsonError === true && "name" in value && "message" in value && "stack" in value;
33204
- }
33205
- };
33206
- var BSONVersionError = class extends BSONError {
33207
- get name() {
33208
- return "BSONVersionError";
33209
- }
33210
- constructor() {
33211
- super(`Unsupported BSON version, bson types must be from bson ${BSON_MAJOR_VERSION}.x.x`);
33212
- }
33213
- };
33214
- var BSONRuntimeError = class extends BSONError {
33215
- get name() {
33216
- return "BSONRuntimeError";
33217
- }
33218
- constructor(message) {
33219
- super(message);
33220
- }
33221
- };
33222
- var BSONOffsetError = class extends BSONError {
33223
- get name() {
33224
- return "BSONOffsetError";
33225
- }
33226
- constructor(message, offset, options) {
33227
- super(`${message}. offset: ${offset}`, options);
33228
- this.offset = offset;
33229
- }
33230
- };
33231
- var TextDecoderFatal;
33232
- var TextDecoderNonFatal;
33233
- function parseUtf8(buffer2, start, end, fatal) {
33234
- if (fatal) {
33235
- TextDecoderFatal ?? (TextDecoderFatal = new TextDecoder("utf8", { fatal: true }));
33236
- try {
33237
- return TextDecoderFatal.decode(buffer2.subarray(start, end));
33238
- } catch (cause) {
33239
- throw new BSONError("Invalid UTF-8 string in BSON document", { cause });
33240
- }
33241
- }
33242
- TextDecoderNonFatal ?? (TextDecoderNonFatal = new TextDecoder("utf8", { fatal: false }));
33243
- return TextDecoderNonFatal.decode(buffer2.subarray(start, end));
33244
- }
33245
- function tryReadBasicLatin(uint8array, start, end) {
33246
- if (uint8array.length === 0) {
33247
- return "";
33248
- }
33249
- const stringByteLength = end - start;
33250
- if (stringByteLength === 0) {
33251
- return "";
33252
- }
33253
- if (stringByteLength > 20) {
33254
- return null;
33255
- }
33256
- if (stringByteLength === 1 && uint8array[start] < 128) {
33257
- return String.fromCharCode(uint8array[start]);
33258
- }
33259
- if (stringByteLength === 2 && uint8array[start] < 128 && uint8array[start + 1] < 128) {
33260
- return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]);
33261
- }
33262
- if (stringByteLength === 3 && uint8array[start] < 128 && uint8array[start + 1] < 128 && uint8array[start + 2] < 128) {
33263
- return String.fromCharCode(uint8array[start]) + String.fromCharCode(uint8array[start + 1]) + String.fromCharCode(uint8array[start + 2]);
33264
- }
33265
- const latinBytes = [];
33266
- for (let i = start; i < end; i++) {
33267
- const byte = uint8array[i];
33268
- if (byte > 127) {
33269
- return null;
33270
- }
33271
- latinBytes.push(byte);
33272
- }
33273
- return String.fromCharCode(...latinBytes);
33274
- }
33275
- function tryWriteBasicLatin(destination, source, offset) {
33276
- if (source.length === 0)
33277
- return 0;
33278
- if (source.length > 25)
33279
- return null;
33280
- if (destination.length - offset < source.length)
33281
- return null;
33282
- for (let charOffset = 0, destinationOffset = offset; charOffset < source.length; charOffset++, destinationOffset++) {
33283
- const char = source.charCodeAt(charOffset);
33284
- if (char > 127)
33285
- return null;
33286
- destination[destinationOffset] = char;
33287
- }
33288
- return source.length;
33289
- }
33290
- var nodeJsByteUtils = {
33291
- toLocalBufferType(potentialBuffer) {
33292
- if (Buffer.isBuffer(potentialBuffer)) {
33293
- return potentialBuffer;
33294
- }
33295
- if (ArrayBuffer.isView(potentialBuffer)) {
33296
- return Buffer.from(potentialBuffer.buffer, potentialBuffer.byteOffset, potentialBuffer.byteLength);
33297
- }
33298
- const stringTag = potentialBuffer?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialBuffer);
33299
- if (stringTag === "ArrayBuffer" || stringTag === "SharedArrayBuffer" || stringTag === "[object ArrayBuffer]" || stringTag === "[object SharedArrayBuffer]") {
33300
- return Buffer.from(potentialBuffer);
33301
- }
33302
- throw new BSONError(`Cannot create Buffer from the passed potentialBuffer.`);
33303
- },
33304
- allocate(size) {
33305
- return Buffer.alloc(size);
33306
- },
33307
- allocateUnsafe(size) {
33308
- return Buffer.allocUnsafe(size);
33309
- },
33310
- equals(a, b) {
33311
- return nodeJsByteUtils.toLocalBufferType(a).equals(b);
33312
- },
33313
- fromNumberArray(array) {
33314
- return Buffer.from(array);
33315
- },
33316
- fromBase64(base64) {
33317
- return Buffer.from(base64, "base64");
33318
- },
33319
- toBase64(buffer2) {
33320
- return nodeJsByteUtils.toLocalBufferType(buffer2).toString("base64");
33321
- },
33322
- fromISO88591(codePoints) {
33323
- return Buffer.from(codePoints, "binary");
33324
- },
33325
- toISO88591(buffer2) {
33326
- return nodeJsByteUtils.toLocalBufferType(buffer2).toString("binary");
33327
- },
33328
- fromHex(hex) {
33329
- return Buffer.from(hex, "hex");
33330
- },
33331
- toHex(buffer2) {
33332
- return nodeJsByteUtils.toLocalBufferType(buffer2).toString("hex");
33333
- },
33334
- toUTF8(buffer2, start, end, fatal) {
33335
- const basicLatin = end - start <= 20 ? tryReadBasicLatin(buffer2, start, end) : null;
33336
- if (basicLatin != null) {
33337
- return basicLatin;
33338
- }
33339
- const string = nodeJsByteUtils.toLocalBufferType(buffer2).toString("utf8", start, end);
33340
- if (fatal) {
33341
- for (let i = 0; i < string.length; i++) {
33342
- if (string.charCodeAt(i) === 65533) {
33343
- parseUtf8(buffer2, start, end, true);
33344
- break;
33345
- }
33346
- }
33347
- }
33348
- return string;
33349
- },
33350
- utf8ByteLength(input) {
33351
- return Buffer.byteLength(input, "utf8");
33352
- },
33353
- encodeUTF8Into(buffer2, source, byteOffset) {
33354
- const latinBytesWritten = tryWriteBasicLatin(buffer2, source, byteOffset);
33355
- if (latinBytesWritten != null) {
33356
- return latinBytesWritten;
33357
- }
33358
- return nodeJsByteUtils.toLocalBufferType(buffer2).write(source, byteOffset, void 0, "utf8");
33359
- },
33360
- randomBytes,
33361
- swap32(buffer2) {
33362
- return nodeJsByteUtils.toLocalBufferType(buffer2).swap32();
33363
- }
33364
- };
33365
- function isReactNative() {
33366
- const { navigator: navigator2 } = globalThis;
33367
- return typeof navigator2 === "object" && navigator2.product === "ReactNative";
33368
- }
33369
- function webMathRandomBytes(byteLength) {
33370
- if (byteLength < 0) {
33371
- throw new RangeError(`The argument 'byteLength' is invalid. Received ${byteLength}`);
33372
- }
33373
- return webByteUtils.fromNumberArray(Array.from({ length: byteLength }, () => Math.floor(Math.random() * 256)));
33374
- }
33375
- var webRandomBytes = (() => {
33376
- const { crypto } = globalThis;
33377
- if (crypto != null && typeof crypto.getRandomValues === "function") {
33378
- return (byteLength) => {
33379
- return crypto.getRandomValues(webByteUtils.allocate(byteLength));
33380
- };
33381
- } else {
33382
- if (isReactNative()) {
33383
- const { console: console2 } = globalThis;
33384
- console2?.warn?.("BSON: For React Native please polyfill crypto.getRandomValues, e.g. using: https://www.npmjs.com/package/react-native-get-random-values.");
33385
- }
33386
- return webMathRandomBytes;
33387
- }
33388
- })();
33389
- var HEX_DIGIT = /(\d|[a-f])/i;
33390
- var webByteUtils = {
33391
- toLocalBufferType(potentialUint8array) {
33392
- const stringTag = potentialUint8array?.[Symbol.toStringTag] ?? Object.prototype.toString.call(potentialUint8array);
33393
- if (stringTag === "Uint8Array") {
33394
- return potentialUint8array;
33395
- }
33396
- if (ArrayBuffer.isView(potentialUint8array)) {
33397
- return new Uint8Array(potentialUint8array.buffer.slice(potentialUint8array.byteOffset, potentialUint8array.byteOffset + potentialUint8array.byteLength));
33398
- }
33399
- if (stringTag === "ArrayBuffer" || stringTag === "SharedArrayBuffer" || stringTag === "[object ArrayBuffer]" || stringTag === "[object SharedArrayBuffer]") {
33400
- return new Uint8Array(potentialUint8array);
33401
- }
33402
- throw new BSONError(`Cannot make a Uint8Array from passed potentialBuffer.`);
33403
- },
33404
- allocate(size) {
33405
- if (typeof size !== "number") {
33406
- throw new TypeError(`The "size" argument must be of type number. Received ${String(size)}`);
33407
- }
33408
- return new Uint8Array(size);
33409
- },
33410
- allocateUnsafe(size) {
33411
- return webByteUtils.allocate(size);
33412
- },
33413
- equals(a, b) {
33414
- if (a.byteLength !== b.byteLength) {
33415
- return false;
33416
- }
33417
- for (let i = 0; i < a.byteLength; i++) {
33418
- if (a[i] !== b[i]) {
33419
- return false;
33420
- }
33421
- }
33422
- return true;
33423
- },
33424
- fromNumberArray(array) {
33425
- return Uint8Array.from(array);
33426
- },
33427
- fromBase64(base64) {
33428
- return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
33429
- },
33430
- toBase64(uint8array) {
33431
- return btoa(webByteUtils.toISO88591(uint8array));
33432
- },
33433
- fromISO88591(codePoints) {
33434
- return Uint8Array.from(codePoints, (c) => c.charCodeAt(0) & 255);
33435
- },
33436
- toISO88591(uint8array) {
33437
- return Array.from(Uint16Array.from(uint8array), (b) => String.fromCharCode(b)).join("");
33438
- },
33439
- fromHex(hex) {
33440
- const evenLengthHex = hex.length % 2 === 0 ? hex : hex.slice(0, hex.length - 1);
33441
- const buffer2 = [];
33442
- for (let i = 0; i < evenLengthHex.length; i += 2) {
33443
- const firstDigit = evenLengthHex[i];
33444
- const secondDigit = evenLengthHex[i + 1];
33445
- if (!HEX_DIGIT.test(firstDigit)) {
33446
- break;
33447
- }
33448
- if (!HEX_DIGIT.test(secondDigit)) {
33449
- break;
33450
- }
33451
- const hexDigit = Number.parseInt(`${firstDigit}${secondDigit}`, 16);
33452
- buffer2.push(hexDigit);
33453
- }
33454
- return Uint8Array.from(buffer2);
33455
- },
33456
- toHex(uint8array) {
33457
- return Array.from(uint8array, (byte) => byte.toString(16).padStart(2, "0")).join("");
33458
- },
33459
- toUTF8(uint8array, start, end, fatal) {
33460
- const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null;
33461
- if (basicLatin != null) {
33462
- return basicLatin;
33463
- }
33464
- return parseUtf8(uint8array, start, end, fatal);
33465
- },
33466
- utf8ByteLength(input) {
33467
- return new TextEncoder().encode(input).byteLength;
33468
- },
33469
- encodeUTF8Into(uint8array, source, byteOffset) {
33470
- const bytes = new TextEncoder().encode(source);
33471
- uint8array.set(bytes, byteOffset);
33472
- return bytes.byteLength;
33473
- },
33474
- randomBytes: webRandomBytes,
33475
- swap32(buffer2) {
33476
- if (buffer2.length % 4 !== 0) {
33477
- throw new RangeError("Buffer size must be a multiple of 32-bits");
33478
- }
33479
- for (let i = 0; i < buffer2.length; i += 4) {
33480
- const byte0 = buffer2[i];
33481
- const byte1 = buffer2[i + 1];
33482
- const byte2 = buffer2[i + 2];
33483
- const byte3 = buffer2[i + 3];
33484
- buffer2[i] = byte3;
33485
- buffer2[i + 1] = byte2;
33486
- buffer2[i + 2] = byte1;
33487
- buffer2[i + 3] = byte0;
33488
- }
33489
- return buffer2;
33490
- }
33491
- };
33492
- var hasGlobalBuffer = typeof Buffer === "function" && Buffer.prototype?._isBuffer !== true;
33493
- var ByteUtils = hasGlobalBuffer ? nodeJsByteUtils : webByteUtils;
33494
- var BSONValue = class {
33495
- get [BSON_VERSION_SYMBOL]() {
33496
- return BSON_MAJOR_VERSION;
33497
- }
33498
- [Symbol.for("nodejs.util.inspect.custom")](depth, options, inspect) {
33499
- return this.inspect(depth, options, inspect);
33500
- }
33501
- };
33502
- var FLOAT = new Float64Array(1);
33503
- var FLOAT_BYTES = new Uint8Array(FLOAT.buffer, 0, 8);
33504
- FLOAT[0] = -1;
33505
- var isBigEndian = FLOAT_BYTES[7] === 0;
33506
- var NumberUtils = {
33507
- isBigEndian,
33508
- getNonnegativeInt32LE(source, offset) {
33509
- if (source[offset + 3] > 127) {
33510
- throw new RangeError(`Size cannot be negative at offset: ${offset}`);
33511
- }
33512
- return source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24;
33513
- },
33514
- getInt32LE(source, offset) {
33515
- return source[offset] | source[offset + 1] << 8 | source[offset + 2] << 16 | source[offset + 3] << 24;
33516
- },
33517
- getUint32LE(source, offset) {
33518
- return source[offset] + source[offset + 1] * 256 + source[offset + 2] * 65536 + source[offset + 3] * 16777216;
33519
- },
33520
- getUint32BE(source, offset) {
33521
- return source[offset + 3] + source[offset + 2] * 256 + source[offset + 1] * 65536 + source[offset] * 16777216;
33522
- },
33523
- getBigInt64LE(source, offset) {
33524
- const hi = BigInt(source[offset + 4] + source[offset + 5] * 256 + source[offset + 6] * 65536 + (source[offset + 7] << 24));
33525
- const lo = BigInt(source[offset] + source[offset + 1] * 256 + source[offset + 2] * 65536 + source[offset + 3] * 16777216);
33526
- return (hi << BigInt(32)) + lo;
33527
- },
33528
- getFloat64LE: isBigEndian ? (source, offset) => {
33529
- FLOAT_BYTES[7] = source[offset];
33530
- FLOAT_BYTES[6] = source[offset + 1];
33531
- FLOAT_BYTES[5] = source[offset + 2];
33532
- FLOAT_BYTES[4] = source[offset + 3];
33533
- FLOAT_BYTES[3] = source[offset + 4];
33534
- FLOAT_BYTES[2] = source[offset + 5];
33535
- FLOAT_BYTES[1] = source[offset + 6];
33536
- FLOAT_BYTES[0] = source[offset + 7];
33537
- return FLOAT[0];
33538
- } : (source, offset) => {
33539
- FLOAT_BYTES[0] = source[offset];
33540
- FLOAT_BYTES[1] = source[offset + 1];
33541
- FLOAT_BYTES[2] = source[offset + 2];
33542
- FLOAT_BYTES[3] = source[offset + 3];
33543
- FLOAT_BYTES[4] = source[offset + 4];
33544
- FLOAT_BYTES[5] = source[offset + 5];
33545
- FLOAT_BYTES[6] = source[offset + 6];
33546
- FLOAT_BYTES[7] = source[offset + 7];
33547
- return FLOAT[0];
33548
- },
33549
- setInt32BE(destination, offset, value) {
33550
- destination[offset + 3] = value;
33551
- value >>>= 8;
33552
- destination[offset + 2] = value;
33553
- value >>>= 8;
33554
- destination[offset + 1] = value;
33555
- value >>>= 8;
33556
- destination[offset] = value;
33557
- return 4;
33558
- },
33559
- setInt32LE(destination, offset, value) {
33560
- destination[offset] = value;
33561
- value >>>= 8;
33562
- destination[offset + 1] = value;
33563
- value >>>= 8;
33564
- destination[offset + 2] = value;
33565
- value >>>= 8;
33566
- destination[offset + 3] = value;
33567
- return 4;
33568
- },
33569
- setBigInt64LE(destination, offset, value) {
33570
- const mask32bits = BigInt(4294967295);
33571
- let lo = Number(value & mask32bits);
33572
- destination[offset] = lo;
33573
- lo >>= 8;
33574
- destination[offset + 1] = lo;
33575
- lo >>= 8;
33576
- destination[offset + 2] = lo;
33577
- lo >>= 8;
33578
- destination[offset + 3] = lo;
33579
- let hi = Number(value >> BigInt(32) & mask32bits);
33580
- destination[offset + 4] = hi;
33581
- hi >>= 8;
33582
- destination[offset + 5] = hi;
33583
- hi >>= 8;
33584
- destination[offset + 6] = hi;
33585
- hi >>= 8;
33586
- destination[offset + 7] = hi;
33587
- return 8;
33588
- },
33589
- setFloat64LE: isBigEndian ? (destination, offset, value) => {
33590
- FLOAT[0] = value;
33591
- destination[offset] = FLOAT_BYTES[7];
33592
- destination[offset + 1] = FLOAT_BYTES[6];
33593
- destination[offset + 2] = FLOAT_BYTES[5];
33594
- destination[offset + 3] = FLOAT_BYTES[4];
33595
- destination[offset + 4] = FLOAT_BYTES[3];
33596
- destination[offset + 5] = FLOAT_BYTES[2];
33597
- destination[offset + 6] = FLOAT_BYTES[1];
33598
- destination[offset + 7] = FLOAT_BYTES[0];
33599
- return 8;
33600
- } : (destination, offset, value) => {
33601
- FLOAT[0] = value;
33602
- destination[offset] = FLOAT_BYTES[0];
33603
- destination[offset + 1] = FLOAT_BYTES[1];
33604
- destination[offset + 2] = FLOAT_BYTES[2];
33605
- destination[offset + 3] = FLOAT_BYTES[3];
33606
- destination[offset + 4] = FLOAT_BYTES[4];
33607
- destination[offset + 5] = FLOAT_BYTES[5];
33608
- destination[offset + 6] = FLOAT_BYTES[6];
33609
- destination[offset + 7] = FLOAT_BYTES[7];
33610
- return 8;
33611
- }
33612
- };
33613
- var Binary = class extends BSONValue {
33614
- get _bsontype() {
33615
- return "Binary";
33616
- }
33617
- constructor(buffer2, subType) {
33618
- super();
33619
- if (!(buffer2 == null) && typeof buffer2 === "string" && !ArrayBuffer.isView(buffer2) && !isAnyArrayBuffer(buffer2) && !Array.isArray(buffer2)) {
33620
- throw new BSONError("Binary can only be constructed from Uint8Array or number[]");
33621
- }
33622
- this.sub_type = subType ?? Binary.BSON_BINARY_SUBTYPE_DEFAULT;
33623
- if (buffer2 == null) {
33624
- this.buffer = ByteUtils.allocate(Binary.BUFFER_SIZE);
33625
- this.position = 0;
33626
- } else {
33627
- this.buffer = Array.isArray(buffer2) ? ByteUtils.fromNumberArray(buffer2) : ByteUtils.toLocalBufferType(buffer2);
33628
- this.position = this.buffer.byteLength;
33629
- }
33630
- }
33631
- put(byteValue) {
33632
- if (typeof byteValue === "string" && byteValue.length !== 1) {
33633
- throw new BSONError("only accepts single character String");
33634
- } else if (typeof byteValue !== "number" && byteValue.length !== 1)
33635
- throw new BSONError("only accepts single character Uint8Array or Array");
33636
- let decodedByte;
33637
- if (typeof byteValue === "string") {
33638
- decodedByte = byteValue.charCodeAt(0);
33639
- } else if (typeof byteValue === "number") {
33640
- decodedByte = byteValue;
33641
- } else {
33642
- decodedByte = byteValue[0];
33643
- }
33644
- if (decodedByte < 0 || decodedByte > 255) {
33645
- throw new BSONError("only accepts number in a valid unsigned byte range 0-255");
33646
- }
33647
- if (this.buffer.byteLength > this.position) {
33648
- this.buffer[this.position++] = decodedByte;
33649
- } else {
33650
- const newSpace = ByteUtils.allocate(Binary.BUFFER_SIZE + this.buffer.length);
33651
- newSpace.set(this.buffer, 0);
33652
- this.buffer = newSpace;
33653
- this.buffer[this.position++] = decodedByte;
33654
- }
33655
- }
33656
- write(sequence, offset) {
33657
- offset = typeof offset === "number" ? offset : this.position;
33658
- if (this.buffer.byteLength < offset + sequence.length) {
33659
- const newSpace = ByteUtils.allocate(this.buffer.byteLength + sequence.length);
33660
- newSpace.set(this.buffer, 0);
33661
- this.buffer = newSpace;
33662
- }
33663
- if (ArrayBuffer.isView(sequence)) {
33664
- this.buffer.set(ByteUtils.toLocalBufferType(sequence), offset);
33665
- this.position = offset + sequence.byteLength > this.position ? offset + sequence.length : this.position;
33666
- } else if (typeof sequence === "string") {
33667
- throw new BSONError("input cannot be string");
33668
- }
33669
- }
33670
- read(position, length) {
33671
- length = length && length > 0 ? length : this.position;
33672
- const end = position + length;
33673
- return this.buffer.subarray(position, end > this.position ? this.position : end);
33674
- }
33675
- value() {
33676
- return this.buffer.length === this.position ? this.buffer : this.buffer.subarray(0, this.position);
33677
- }
33678
- length() {
33679
- return this.position;
33680
- }
33681
- toJSON() {
33682
- return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
33683
- }
33684
- toString(encoding) {
33685
- if (encoding === "hex")
33686
- return ByteUtils.toHex(this.buffer.subarray(0, this.position));
33687
- if (encoding === "base64")
33688
- return ByteUtils.toBase64(this.buffer.subarray(0, this.position));
33689
- if (encoding === "utf8" || encoding === "utf-8")
33690
- return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
33691
- return ByteUtils.toUTF8(this.buffer, 0, this.position, false);
33692
- }
33693
- toExtendedJSON(options) {
33694
- options = options || {};
33695
- if (this.sub_type === Binary.SUBTYPE_VECTOR) {
33696
- validateBinaryVector(this);
33697
- }
33698
- const base64String = ByteUtils.toBase64(this.buffer);
33699
- const subType = Number(this.sub_type).toString(16);
33700
- if (options.legacy) {
33701
- return {
33702
- $binary: base64String,
33703
- $type: subType.length === 1 ? "0" + subType : subType
33704
- };
33705
- }
33706
- return {
33707
- $binary: {
33708
- base64: base64String,
33709
- subType: subType.length === 1 ? "0" + subType : subType
33710
- }
33711
- };
33712
- }
33713
- toUUID() {
33714
- if (this.sub_type === Binary.SUBTYPE_UUID) {
33715
- return new UUID(this.buffer.subarray(0, this.position));
33716
- }
33717
- throw new BSONError(`Binary sub_type "${this.sub_type}" is not supported for converting to UUID. Only "${Binary.SUBTYPE_UUID}" is currently supported.`);
33718
- }
33719
- static createFromHexString(hex, subType) {
33720
- return new Binary(ByteUtils.fromHex(hex), subType);
33721
- }
33722
- static createFromBase64(base64, subType) {
33723
- return new Binary(ByteUtils.fromBase64(base64), subType);
33724
- }
33725
- static fromExtendedJSON(doc, options) {
33726
- options = options || {};
33727
- let data;
33728
- let type;
33729
- if ("$binary" in doc) {
33730
- if (options.legacy && typeof doc.$binary === "string" && "$type" in doc) {
33731
- type = doc.$type ? parseInt(doc.$type, 16) : 0;
33732
- data = ByteUtils.fromBase64(doc.$binary);
33733
- } else {
33734
- if (typeof doc.$binary !== "string") {
33735
- type = doc.$binary.subType ? parseInt(doc.$binary.subType, 16) : 0;
33736
- data = ByteUtils.fromBase64(doc.$binary.base64);
33737
- }
33738
- }
33739
- } else if ("$uuid" in doc) {
33740
- type = 4;
33741
- data = UUID.bytesFromString(doc.$uuid);
33742
- }
33743
- if (!data) {
33744
- throw new BSONError(`Unexpected Binary Extended JSON format ${JSON.stringify(doc)}`);
33745
- }
33746
- return type === BSON_BINARY_SUBTYPE_UUID_NEW ? new UUID(data) : new Binary(data, type);
33747
- }
33748
- inspect(depth, options, inspect) {
33749
- inspect ?? (inspect = defaultInspect);
33750
- const base64 = ByteUtils.toBase64(this.buffer.subarray(0, this.position));
33751
- const base64Arg = inspect(base64, options);
33752
- const subTypeArg = inspect(this.sub_type, options);
33753
- return `Binary.createFromBase64(${base64Arg}, ${subTypeArg})`;
33754
- }
33755
- toInt8Array() {
33756
- if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
33757
- throw new BSONError("Binary sub_type is not Vector");
33758
- }
33759
- if (this.buffer[0] !== Binary.VECTOR_TYPE.Int8) {
33760
- throw new BSONError("Binary datatype field is not Int8");
33761
- }
33762
- validateBinaryVector(this);
33763
- return new Int8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
33764
- }
33765
- toFloat32Array() {
33766
- if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
33767
- throw new BSONError("Binary sub_type is not Vector");
33768
- }
33769
- if (this.buffer[0] !== Binary.VECTOR_TYPE.Float32) {
33770
- throw new BSONError("Binary datatype field is not Float32");
33771
- }
33772
- validateBinaryVector(this);
33773
- const floatBytes = new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
33774
- if (NumberUtils.isBigEndian)
33775
- ByteUtils.swap32(floatBytes);
33776
- return new Float32Array(floatBytes.buffer);
33777
- }
33778
- toPackedBits() {
33779
- if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
33780
- throw new BSONError("Binary sub_type is not Vector");
33781
- }
33782
- if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
33783
- throw new BSONError("Binary datatype field is not packed bit");
33784
- }
33785
- validateBinaryVector(this);
33786
- return new Uint8Array(this.buffer.buffer.slice(this.buffer.byteOffset + 2, this.buffer.byteOffset + this.position));
33787
- }
33788
- toBits() {
33789
- if (this.sub_type !== Binary.SUBTYPE_VECTOR) {
33790
- throw new BSONError("Binary sub_type is not Vector");
33791
- }
33792
- if (this.buffer[0] !== Binary.VECTOR_TYPE.PackedBit) {
33793
- throw new BSONError("Binary datatype field is not packed bit");
33794
- }
33795
- validateBinaryVector(this);
33796
- const byteCount = this.length() - 2;
33797
- const bitCount = byteCount * 8 - this.buffer[1];
33798
- const bits = new Int8Array(bitCount);
33799
- for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
33800
- const byteOffset = bitOffset / 8 | 0;
33801
- const byte = this.buffer[byteOffset + 2];
33802
- const shift = 7 - bitOffset % 8;
33803
- const bit = byte >> shift & 1;
33804
- bits[bitOffset] = bit;
33805
- }
33806
- return bits;
33807
- }
33808
- static fromInt8Array(array) {
33809
- const buffer2 = ByteUtils.allocate(array.byteLength + 2);
33810
- buffer2[0] = Binary.VECTOR_TYPE.Int8;
33811
- buffer2[1] = 0;
33812
- const intBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
33813
- buffer2.set(intBytes, 2);
33814
- const bin = new this(buffer2, this.SUBTYPE_VECTOR);
33815
- validateBinaryVector(bin);
33816
- return bin;
33817
- }
33818
- static fromFloat32Array(array) {
33819
- const binaryBytes = ByteUtils.allocate(array.byteLength + 2);
33820
- binaryBytes[0] = Binary.VECTOR_TYPE.Float32;
33821
- binaryBytes[1] = 0;
33822
- const floatBytes = new Uint8Array(array.buffer, array.byteOffset, array.byteLength);
33823
- binaryBytes.set(floatBytes, 2);
33824
- if (NumberUtils.isBigEndian)
33825
- ByteUtils.swap32(new Uint8Array(binaryBytes.buffer, 2));
33826
- const bin = new this(binaryBytes, this.SUBTYPE_VECTOR);
33827
- validateBinaryVector(bin);
33828
- return bin;
33829
- }
33830
- static fromPackedBits(array, padding = 0) {
33831
- const buffer2 = ByteUtils.allocate(array.byteLength + 2);
33832
- buffer2[0] = Binary.VECTOR_TYPE.PackedBit;
33833
- buffer2[1] = padding;
33834
- buffer2.set(array, 2);
33835
- const bin = new this(buffer2, this.SUBTYPE_VECTOR);
33836
- validateBinaryVector(bin);
33837
- return bin;
33838
- }
33839
- static fromBits(bits) {
33840
- const byteLength = bits.length + 7 >>> 3;
33841
- const bytes = new Uint8Array(byteLength + 2);
33842
- bytes[0] = Binary.VECTOR_TYPE.PackedBit;
33843
- const remainder = bits.length % 8;
33844
- bytes[1] = remainder === 0 ? 0 : 8 - remainder;
33845
- for (let bitOffset = 0; bitOffset < bits.length; bitOffset++) {
33846
- const byteOffset = bitOffset >>> 3;
33847
- const bit = bits[bitOffset];
33848
- if (bit !== 0 && bit !== 1) {
33849
- throw new BSONError(`Invalid bit value at ${bitOffset}: must be 0 or 1, found ${bits[bitOffset]}`);
33850
- }
33851
- if (bit === 0)
33852
- continue;
33853
- const shift = 7 - bitOffset % 8;
33854
- bytes[byteOffset + 2] |= bit << shift;
33855
- }
33856
- return new this(bytes, Binary.SUBTYPE_VECTOR);
33857
- }
33858
- };
33859
- Binary.BSON_BINARY_SUBTYPE_DEFAULT = 0;
33860
- Binary.BUFFER_SIZE = 256;
33861
- Binary.SUBTYPE_DEFAULT = 0;
33862
- Binary.SUBTYPE_FUNCTION = 1;
33863
- Binary.SUBTYPE_BYTE_ARRAY = 2;
33864
- Binary.SUBTYPE_UUID_OLD = 3;
33865
- Binary.SUBTYPE_UUID = 4;
33866
- Binary.SUBTYPE_MD5 = 5;
33867
- Binary.SUBTYPE_ENCRYPTED = 6;
33868
- Binary.SUBTYPE_COLUMN = 7;
33869
- Binary.SUBTYPE_SENSITIVE = 8;
33870
- Binary.SUBTYPE_VECTOR = 9;
33871
- Binary.SUBTYPE_USER_DEFINED = 128;
33872
- Binary.VECTOR_TYPE = Object.freeze({
33873
- Int8: 3,
33874
- Float32: 39,
33875
- PackedBit: 16
33876
- });
33877
- function validateBinaryVector(vector) {
33878
- if (vector.sub_type !== Binary.SUBTYPE_VECTOR)
33879
- return;
33880
- const size = vector.position;
33881
- const datatype = vector.buffer[0];
33882
- const padding = vector.buffer[1];
33883
- if ((datatype === Binary.VECTOR_TYPE.Float32 || datatype === Binary.VECTOR_TYPE.Int8) && padding !== 0) {
33884
- throw new BSONError("Invalid Vector: padding must be zero for int8 and float32 vectors");
33885
- }
33886
- if (datatype === Binary.VECTOR_TYPE.Float32) {
33887
- if (size !== 0 && size - 2 !== 0 && (size - 2) % 4 !== 0) {
33888
- throw new BSONError("Invalid Vector: Float32 vector must contain a multiple of 4 bytes");
33889
- }
33890
- }
33891
- if (datatype === Binary.VECTOR_TYPE.PackedBit && padding !== 0 && size === 2) {
33892
- throw new BSONError("Invalid Vector: padding must be zero for packed bit vectors that are empty");
33893
- }
33894
- if (datatype === Binary.VECTOR_TYPE.PackedBit && padding > 7) {
33895
- throw new BSONError(`Invalid Vector: padding must be a value between 0 and 7. found: ${padding}`);
33896
- }
33897
- }
33898
- var UUID_BYTE_LENGTH = 16;
33899
- var UUID_WITHOUT_DASHES = /^[0-9A-F]{32}$/i;
33900
- var UUID_WITH_DASHES = /^[0-9A-F]{8}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{4}-[0-9A-F]{12}$/i;
33901
- var UUID = class extends Binary {
33902
- constructor(input) {
33903
- let bytes;
33904
- if (input == null) {
33905
- bytes = UUID.generate();
33906
- } else if (input instanceof UUID) {
33907
- bytes = ByteUtils.toLocalBufferType(new Uint8Array(input.buffer));
33908
- } else if (ArrayBuffer.isView(input) && input.byteLength === UUID_BYTE_LENGTH) {
33909
- bytes = ByteUtils.toLocalBufferType(input);
33910
- } else if (typeof input === "string") {
33911
- bytes = UUID.bytesFromString(input);
33912
- } else {
33913
- 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).");
33914
- }
33915
- super(bytes, BSON_BINARY_SUBTYPE_UUID_NEW);
33916
- }
33917
- get id() {
33918
- return this.buffer;
33919
- }
33920
- set id(value) {
33921
- this.buffer = value;
33922
- }
33923
- toHexString(includeDashes = true) {
33924
- if (includeDashes) {
33925
- return [
33926
- ByteUtils.toHex(this.buffer.subarray(0, 4)),
33927
- ByteUtils.toHex(this.buffer.subarray(4, 6)),
33928
- ByteUtils.toHex(this.buffer.subarray(6, 8)),
33929
- ByteUtils.toHex(this.buffer.subarray(8, 10)),
33930
- ByteUtils.toHex(this.buffer.subarray(10, 16))
33931
- ].join("-");
33932
- }
33933
- return ByteUtils.toHex(this.buffer);
33934
- }
33935
- toString(encoding) {
33936
- if (encoding === "hex")
33937
- return ByteUtils.toHex(this.id);
33938
- if (encoding === "base64")
33939
- return ByteUtils.toBase64(this.id);
33940
- return this.toHexString();
33941
- }
33942
- toJSON() {
33943
- return this.toHexString();
33944
- }
33945
- equals(otherId) {
33946
- if (!otherId) {
33947
- return false;
33948
- }
33949
- if (otherId instanceof UUID) {
33950
- return ByteUtils.equals(otherId.id, this.id);
33951
- }
33952
- try {
33953
- return ByteUtils.equals(new UUID(otherId).id, this.id);
33954
- } catch {
33955
- return false;
33956
- }
33957
- }
33958
- toBinary() {
33959
- return new Binary(this.id, Binary.SUBTYPE_UUID);
33960
- }
33961
- static generate() {
33962
- const bytes = ByteUtils.randomBytes(UUID_BYTE_LENGTH);
33963
- bytes[6] = bytes[6] & 15 | 64;
33964
- bytes[8] = bytes[8] & 63 | 128;
33965
- return bytes;
33966
- }
33967
- static isValid(input) {
33968
- if (!input) {
33969
- return false;
33970
- }
33971
- if (typeof input === "string") {
33972
- return UUID.isValidUUIDString(input);
33973
- }
33974
- if (isUint8Array(input)) {
33975
- return input.byteLength === UUID_BYTE_LENGTH;
33976
- }
33977
- return input._bsontype === "Binary" && input.sub_type === this.SUBTYPE_UUID && input.buffer.byteLength === 16;
33978
- }
33979
- static createFromHexString(hexString) {
33980
- const buffer2 = UUID.bytesFromString(hexString);
33981
- return new UUID(buffer2);
33982
- }
33983
- static createFromBase64(base64) {
33984
- return new UUID(ByteUtils.fromBase64(base64));
33985
- }
33986
- static bytesFromString(representation) {
33987
- if (!UUID.isValidUUIDString(representation)) {
33988
- throw new BSONError("UUID string representation must be 32 hex digits or canonical hyphenated representation");
33989
- }
33990
- return ByteUtils.fromHex(representation.replace(/-/g, ""));
33991
- }
33992
- static isValidUUIDString(representation) {
33993
- return UUID_WITHOUT_DASHES.test(representation) || UUID_WITH_DASHES.test(representation);
33994
- }
33995
- inspect(depth, options, inspect) {
33996
- inspect ?? (inspect = defaultInspect);
33997
- return `new UUID(${inspect(this.toHexString(), options)})`;
33998
- }
33999
- };
34000
- var Code = class extends BSONValue {
34001
- get _bsontype() {
34002
- return "Code";
34003
- }
34004
- constructor(code, scope) {
34005
- super();
34006
- this.code = code.toString();
34007
- this.scope = scope ?? null;
34008
- }
34009
- toJSON() {
34010
- if (this.scope != null) {
34011
- return { code: this.code, scope: this.scope };
34012
- }
34013
- return { code: this.code };
34014
- }
34015
- toExtendedJSON() {
34016
- if (this.scope) {
34017
- return { $code: this.code, $scope: this.scope };
34018
- }
34019
- return { $code: this.code };
34020
- }
34021
- static fromExtendedJSON(doc) {
34022
- return new Code(doc.$code, doc.$scope);
34023
- }
34024
- inspect(depth, options, inspect) {
34025
- inspect ?? (inspect = defaultInspect);
34026
- let parametersString = inspect(this.code, options);
34027
- const multiLineFn = parametersString.includes("\n");
34028
- if (this.scope != null) {
34029
- parametersString += `,${multiLineFn ? "\n" : " "}${inspect(this.scope, options)}`;
34030
- }
34031
- const endingNewline = multiLineFn && this.scope === null;
34032
- return `new Code(${multiLineFn ? "\n" : ""}${parametersString}${endingNewline ? "\n" : ""})`;
34033
- }
34034
- };
34035
- function isDBRefLike(value) {
34036
- return value != null && typeof value === "object" && "$id" in value && value.$id != null && "$ref" in value && typeof value.$ref === "string" && (!("$db" in value) || "$db" in value && typeof value.$db === "string");
34037
- }
34038
- var DBRef = class extends BSONValue {
34039
- get _bsontype() {
34040
- return "DBRef";
34041
- }
34042
- constructor(collection, oid, db, fields) {
34043
- super();
34044
- const parts = collection.split(".");
34045
- if (parts.length === 2) {
34046
- db = parts.shift();
34047
- collection = parts.shift();
34048
- }
34049
- this.collection = collection;
34050
- this.oid = oid;
34051
- this.db = db;
34052
- this.fields = fields || {};
34053
- }
34054
- get namespace() {
34055
- return this.collection;
34056
- }
34057
- set namespace(value) {
34058
- this.collection = value;
34059
- }
34060
- toJSON() {
34061
- const o = Object.assign({
34062
- $ref: this.collection,
34063
- $id: this.oid
34064
- }, this.fields);
34065
- if (this.db != null)
34066
- o.$db = this.db;
34067
- return o;
34068
- }
34069
- toExtendedJSON(options) {
34070
- options = options || {};
34071
- let o = {
34072
- $ref: this.collection,
34073
- $id: this.oid
34074
- };
34075
- if (options.legacy) {
34076
- return o;
34077
- }
34078
- if (this.db)
34079
- o.$db = this.db;
34080
- o = Object.assign(o, this.fields);
34081
- return o;
34082
- }
34083
- static fromExtendedJSON(doc) {
34084
- const copy = Object.assign({}, doc);
34085
- delete copy.$ref;
34086
- delete copy.$id;
34087
- delete copy.$db;
34088
- return new DBRef(doc.$ref, doc.$id, doc.$db, copy);
34089
- }
34090
- inspect(depth, options, inspect) {
34091
- inspect ?? (inspect = defaultInspect);
34092
- const args = [
34093
- inspect(this.namespace, options),
34094
- inspect(this.oid, options),
34095
- ...this.db ? [inspect(this.db, options)] : [],
34096
- ...Object.keys(this.fields).length > 0 ? [inspect(this.fields, options)] : []
34097
- ];
34098
- args[1] = inspect === defaultInspect ? `new ObjectId(${args[1]})` : args[1];
34099
- return `new DBRef(${args.join(", ")})`;
34100
- }
34101
- };
34102
- function removeLeadingZerosAndExplicitPlus(str) {
34103
- if (str === "") {
34104
- return str;
34105
- }
34106
- let startIndex = 0;
34107
- const isNegative = str[startIndex] === "-";
34108
- const isExplicitlyPositive = str[startIndex] === "+";
34109
- if (isExplicitlyPositive || isNegative) {
34110
- startIndex += 1;
34111
- }
34112
- let foundInsignificantZero = false;
34113
- for (; startIndex < str.length && str[startIndex] === "0"; ++startIndex) {
34114
- foundInsignificantZero = true;
34115
- }
34116
- if (!foundInsignificantZero) {
34117
- return isExplicitlyPositive ? str.slice(1) : str;
34118
- }
34119
- return `${isNegative ? "-" : ""}${str.length === startIndex ? "0" : str.slice(startIndex)}`;
34120
- }
34121
- function validateStringCharacters(str, radix) {
34122
- radix = radix ?? 10;
34123
- const validCharacters = "0123456789abcdefghijklmnopqrstuvwxyz".slice(0, radix);
34124
- const regex = new RegExp(`[^-+${validCharacters}]`, "i");
34125
- return regex.test(str) ? false : str;
34126
- }
34127
- var wasm = void 0;
34128
- try {
34129
- 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;
34130
- } catch {
34131
- }
34132
- var TWO_PWR_16_DBL = 1 << 16;
34133
- var TWO_PWR_24_DBL = 1 << 24;
34134
- var TWO_PWR_32_DBL = TWO_PWR_16_DBL * TWO_PWR_16_DBL;
34135
- var TWO_PWR_64_DBL = TWO_PWR_32_DBL * TWO_PWR_32_DBL;
34136
- var TWO_PWR_63_DBL = TWO_PWR_64_DBL / 2;
34137
- var INT_CACHE = {};
34138
- var UINT_CACHE = {};
34139
- var MAX_INT64_STRING_LENGTH = 20;
34140
- var DECIMAL_REG_EX = /^(\+?0|(\+|-)?[1-9][0-9]*)$/;
34141
- var Long = class extends BSONValue {
34142
- get _bsontype() {
34143
- return "Long";
34144
- }
34145
- get __isLong__() {
34146
- return true;
34147
- }
34148
- constructor(lowOrValue = 0, highOrUnsigned, unsigned) {
34149
- super();
34150
- const unsignedBool = typeof highOrUnsigned === "boolean" ? highOrUnsigned : Boolean(unsigned);
34151
- const high = typeof highOrUnsigned === "number" ? highOrUnsigned : 0;
34152
- const res = typeof lowOrValue === "string" ? Long.fromString(lowOrValue, unsignedBool) : typeof lowOrValue === "bigint" ? Long.fromBigInt(lowOrValue, unsignedBool) : { low: lowOrValue | 0, high: high | 0, unsigned: unsignedBool };
34153
- this.low = res.low;
34154
- this.high = res.high;
34155
- this.unsigned = res.unsigned;
34156
- }
34157
- static fromBits(lowBits, highBits, unsigned) {
34158
- return new Long(lowBits, highBits, unsigned);
34159
- }
34160
- static fromInt(value, unsigned) {
34161
- let obj, cachedObj, cache;
34162
- if (unsigned) {
34163
- value >>>= 0;
34164
- if (cache = 0 <= value && value < 256) {
34165
- cachedObj = UINT_CACHE[value];
34166
- if (cachedObj)
34167
- return cachedObj;
34168
- }
34169
- obj = Long.fromBits(value, (value | 0) < 0 ? -1 : 0, true);
34170
- if (cache)
34171
- UINT_CACHE[value] = obj;
34172
- return obj;
34173
- } else {
34174
- value |= 0;
34175
- if (cache = -128 <= value && value < 128) {
34176
- cachedObj = INT_CACHE[value];
34177
- if (cachedObj)
34178
- return cachedObj;
34179
- }
34180
- obj = Long.fromBits(value, value < 0 ? -1 : 0, false);
34181
- if (cache)
34182
- INT_CACHE[value] = obj;
34183
- return obj;
34184
- }
34185
- }
34186
- static fromNumber(value, unsigned) {
34187
- if (isNaN(value))
34188
- return unsigned ? Long.UZERO : Long.ZERO;
34189
- if (unsigned) {
34190
- if (value < 0)
34191
- return Long.UZERO;
34192
- if (value >= TWO_PWR_64_DBL)
34193
- return Long.MAX_UNSIGNED_VALUE;
34194
- } else {
34195
- if (value <= -9223372036854776e3)
34196
- return Long.MIN_VALUE;
34197
- if (value + 1 >= TWO_PWR_63_DBL)
34198
- return Long.MAX_VALUE;
34199
- }
34200
- if (value < 0)
34201
- return Long.fromNumber(-value, unsigned).neg();
34202
- return Long.fromBits(value % TWO_PWR_32_DBL | 0, value / TWO_PWR_32_DBL | 0, unsigned);
34203
- }
34204
- static fromBigInt(value, unsigned) {
34205
- const FROM_BIGINT_BIT_MASK = BigInt(4294967295);
34206
- const FROM_BIGINT_BIT_SHIFT = BigInt(32);
34207
- return new Long(Number(value & FROM_BIGINT_BIT_MASK), Number(value >> FROM_BIGINT_BIT_SHIFT & FROM_BIGINT_BIT_MASK), unsigned);
34208
- }
34209
- static _fromString(str, unsigned, radix) {
34210
- if (str.length === 0)
34211
- throw new BSONError("empty string");
34212
- if (radix < 2 || 36 < radix)
34213
- throw new BSONError("radix");
34214
- let p;
34215
- if ((p = str.indexOf("-")) > 0)
34216
- throw new BSONError("interior hyphen");
34217
- else if (p === 0) {
34218
- return Long._fromString(str.substring(1), unsigned, radix).neg();
34219
- }
34220
- const radixToPower = Long.fromNumber(Math.pow(radix, 8));
34221
- let result = Long.ZERO;
34222
- for (let i = 0; i < str.length; i += 8) {
34223
- const size = Math.min(8, str.length - i), value = parseInt(str.substring(i, i + size), radix);
34224
- if (size < 8) {
34225
- const power = Long.fromNumber(Math.pow(radix, size));
34226
- result = result.mul(power).add(Long.fromNumber(value));
34227
- } else {
34228
- result = result.mul(radixToPower);
34229
- result = result.add(Long.fromNumber(value));
34230
- }
34231
- }
34232
- result.unsigned = unsigned;
34233
- return result;
34234
- }
34235
- static fromStringStrict(str, unsignedOrRadix, radix) {
34236
- let unsigned = false;
34237
- if (typeof unsignedOrRadix === "number") {
34238
- radix = unsignedOrRadix, unsignedOrRadix = false;
34239
- } else {
34240
- unsigned = !!unsignedOrRadix;
34241
- }
34242
- radix ?? (radix = 10);
34243
- if (str.trim() !== str) {
34244
- throw new BSONError(`Input: '${str}' contains leading and/or trailing whitespace`);
34245
- }
34246
- if (!validateStringCharacters(str, radix)) {
34247
- throw new BSONError(`Input: '${str}' contains invalid characters for radix: ${radix}`);
34248
- }
34249
- const cleanedStr = removeLeadingZerosAndExplicitPlus(str);
34250
- const result = Long._fromString(cleanedStr, unsigned, radix);
34251
- if (result.toString(radix).toLowerCase() !== cleanedStr.toLowerCase()) {
34252
- throw new BSONError(`Input: ${str} is not representable as ${result.unsigned ? "an unsigned" : "a signed"} 64-bit Long ${radix != null ? `with radix: ${radix}` : ""}`);
34253
- }
34254
- return result;
34255
- }
34256
- static fromString(str, unsignedOrRadix, radix) {
34257
- let unsigned = false;
34258
- if (typeof unsignedOrRadix === "number") {
34259
- radix = unsignedOrRadix, unsignedOrRadix = false;
34260
- } else {
34261
- unsigned = !!unsignedOrRadix;
34262
- }
34263
- radix ?? (radix = 10);
34264
- if (str === "NaN" && radix < 24) {
34265
- return Long.ZERO;
34266
- } else if ((str === "Infinity" || str === "+Infinity" || str === "-Infinity") && radix < 35) {
34267
- return Long.ZERO;
34268
- }
34269
- return Long._fromString(str, unsigned, radix);
34270
- }
34271
- static fromBytes(bytes, unsigned, le) {
34272
- return le ? Long.fromBytesLE(bytes, unsigned) : Long.fromBytesBE(bytes, unsigned);
34273
- }
34274
- static fromBytesLE(bytes, unsigned) {
34275
- 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);
34276
- }
34277
- static fromBytesBE(bytes, unsigned) {
34278
- 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);
34279
- }
34280
- static isLong(value) {
34281
- return value != null && typeof value === "object" && "__isLong__" in value && value.__isLong__ === true;
34282
- }
34283
- static fromValue(val, unsigned) {
34284
- if (typeof val === "number")
34285
- return Long.fromNumber(val, unsigned);
34286
- if (typeof val === "string")
34287
- return Long.fromString(val, unsigned);
34288
- return Long.fromBits(val.low, val.high, typeof unsigned === "boolean" ? unsigned : val.unsigned);
34289
- }
34290
- add(addend) {
34291
- if (!Long.isLong(addend))
34292
- addend = Long.fromValue(addend);
34293
- const a48 = this.high >>> 16;
34294
- const a32 = this.high & 65535;
34295
- const a16 = this.low >>> 16;
34296
- const a00 = this.low & 65535;
34297
- const b48 = addend.high >>> 16;
34298
- const b32 = addend.high & 65535;
34299
- const b16 = addend.low >>> 16;
34300
- const b00 = addend.low & 65535;
34301
- let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
34302
- c00 += a00 + b00;
34303
- c16 += c00 >>> 16;
34304
- c00 &= 65535;
34305
- c16 += a16 + b16;
34306
- c32 += c16 >>> 16;
34307
- c16 &= 65535;
34308
- c32 += a32 + b32;
34309
- c48 += c32 >>> 16;
34310
- c32 &= 65535;
34311
- c48 += a48 + b48;
34312
- c48 &= 65535;
34313
- return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
34314
- }
34315
- and(other) {
34316
- if (!Long.isLong(other))
34317
- other = Long.fromValue(other);
34318
- return Long.fromBits(this.low & other.low, this.high & other.high, this.unsigned);
34319
- }
34320
- compare(other) {
34321
- if (!Long.isLong(other))
34322
- other = Long.fromValue(other);
34323
- if (this.eq(other))
34324
- return 0;
34325
- const thisNeg = this.isNegative(), otherNeg = other.isNegative();
34326
- if (thisNeg && !otherNeg)
34327
- return -1;
34328
- if (!thisNeg && otherNeg)
34329
- return 1;
34330
- if (!this.unsigned)
34331
- return this.sub(other).isNegative() ? -1 : 1;
34332
- return other.high >>> 0 > this.high >>> 0 || other.high === this.high && other.low >>> 0 > this.low >>> 0 ? -1 : 1;
34333
- }
34334
- comp(other) {
34335
- return this.compare(other);
34336
- }
34337
- divide(divisor) {
34338
- if (!Long.isLong(divisor))
34339
- divisor = Long.fromValue(divisor);
34340
- if (divisor.isZero())
34341
- throw new BSONError("division by zero");
34342
- if (wasm) {
34343
- if (!this.unsigned && this.high === -2147483648 && divisor.low === -1 && divisor.high === -1) {
34344
- return this;
34345
- }
34346
- const low = (this.unsigned ? wasm.div_u : wasm.div_s)(this.low, this.high, divisor.low, divisor.high);
34347
- return Long.fromBits(low, wasm.get_high(), this.unsigned);
34348
- }
34349
- if (this.isZero())
34350
- return this.unsigned ? Long.UZERO : Long.ZERO;
34351
- let approx, rem, res;
34352
- if (!this.unsigned) {
34353
- if (this.eq(Long.MIN_VALUE)) {
34354
- if (divisor.eq(Long.ONE) || divisor.eq(Long.NEG_ONE))
34355
- return Long.MIN_VALUE;
34356
- else if (divisor.eq(Long.MIN_VALUE))
34357
- return Long.ONE;
34358
- else {
34359
- const halfThis = this.shr(1);
34360
- approx = halfThis.div(divisor).shl(1);
34361
- if (approx.eq(Long.ZERO)) {
34362
- return divisor.isNegative() ? Long.ONE : Long.NEG_ONE;
34363
- } else {
34364
- rem = this.sub(divisor.mul(approx));
34365
- res = approx.add(rem.div(divisor));
34366
- return res;
34367
- }
34368
- }
34369
- } else if (divisor.eq(Long.MIN_VALUE))
34370
- return this.unsigned ? Long.UZERO : Long.ZERO;
34371
- if (this.isNegative()) {
34372
- if (divisor.isNegative())
34373
- return this.neg().div(divisor.neg());
34374
- return this.neg().div(divisor).neg();
34375
- } else if (divisor.isNegative())
34376
- return this.div(divisor.neg()).neg();
34377
- res = Long.ZERO;
34378
- } else {
34379
- if (!divisor.unsigned)
34380
- divisor = divisor.toUnsigned();
34381
- if (divisor.gt(this))
34382
- return Long.UZERO;
34383
- if (divisor.gt(this.shru(1)))
34384
- return Long.UONE;
34385
- res = Long.UZERO;
34386
- }
34387
- rem = this;
34388
- while (rem.gte(divisor)) {
34389
- approx = Math.max(1, Math.floor(rem.toNumber() / divisor.toNumber()));
34390
- const log2 = Math.ceil(Math.log(approx) / Math.LN2);
34391
- const delta = log2 <= 48 ? 1 : Math.pow(2, log2 - 48);
34392
- let approxRes = Long.fromNumber(approx);
34393
- let approxRem = approxRes.mul(divisor);
34394
- while (approxRem.isNegative() || approxRem.gt(rem)) {
34395
- approx -= delta;
34396
- approxRes = Long.fromNumber(approx, this.unsigned);
34397
- approxRem = approxRes.mul(divisor);
34398
- }
34399
- if (approxRes.isZero())
34400
- approxRes = Long.ONE;
34401
- res = res.add(approxRes);
34402
- rem = rem.sub(approxRem);
34403
- }
34404
- return res;
34405
- }
34406
- div(divisor) {
34407
- return this.divide(divisor);
34408
- }
34409
- equals(other) {
34410
- if (!Long.isLong(other))
34411
- other = Long.fromValue(other);
34412
- if (this.unsigned !== other.unsigned && this.high >>> 31 === 1 && other.high >>> 31 === 1)
34413
- return false;
34414
- return this.high === other.high && this.low === other.low;
34415
- }
34416
- eq(other) {
34417
- return this.equals(other);
34418
- }
34419
- getHighBits() {
34420
- return this.high;
34421
- }
34422
- getHighBitsUnsigned() {
34423
- return this.high >>> 0;
34424
- }
34425
- getLowBits() {
34426
- return this.low;
34427
- }
34428
- getLowBitsUnsigned() {
34429
- return this.low >>> 0;
34430
- }
34431
- getNumBitsAbs() {
34432
- if (this.isNegative()) {
34433
- return this.eq(Long.MIN_VALUE) ? 64 : this.neg().getNumBitsAbs();
34434
- }
34435
- const val = this.high !== 0 ? this.high : this.low;
34436
- let bit;
34437
- for (bit = 31; bit > 0; bit--)
34438
- if ((val & 1 << bit) !== 0)
34439
- break;
34440
- return this.high !== 0 ? bit + 33 : bit + 1;
34441
- }
34442
- greaterThan(other) {
34443
- return this.comp(other) > 0;
34444
- }
34445
- gt(other) {
34446
- return this.greaterThan(other);
34447
- }
34448
- greaterThanOrEqual(other) {
34449
- return this.comp(other) >= 0;
34450
- }
34451
- gte(other) {
34452
- return this.greaterThanOrEqual(other);
34453
- }
34454
- ge(other) {
34455
- return this.greaterThanOrEqual(other);
34456
- }
34457
- isEven() {
34458
- return (this.low & 1) === 0;
34459
- }
34460
- isNegative() {
34461
- return !this.unsigned && this.high < 0;
34462
- }
34463
- isOdd() {
34464
- return (this.low & 1) === 1;
34465
- }
34466
- isPositive() {
34467
- return this.unsigned || this.high >= 0;
34468
- }
34469
- isZero() {
34470
- return this.high === 0 && this.low === 0;
34471
- }
34472
- lessThan(other) {
34473
- return this.comp(other) < 0;
34474
- }
34475
- lt(other) {
34476
- return this.lessThan(other);
34477
- }
34478
- lessThanOrEqual(other) {
34479
- return this.comp(other) <= 0;
34480
- }
34481
- lte(other) {
34482
- return this.lessThanOrEqual(other);
34483
- }
34484
- modulo(divisor) {
34485
- if (!Long.isLong(divisor))
34486
- divisor = Long.fromValue(divisor);
34487
- if (wasm) {
34488
- const low = (this.unsigned ? wasm.rem_u : wasm.rem_s)(this.low, this.high, divisor.low, divisor.high);
34489
- return Long.fromBits(low, wasm.get_high(), this.unsigned);
34490
- }
34491
- return this.sub(this.div(divisor).mul(divisor));
34492
- }
34493
- mod(divisor) {
34494
- return this.modulo(divisor);
34495
- }
34496
- rem(divisor) {
34497
- return this.modulo(divisor);
34498
- }
34499
- multiply(multiplier) {
34500
- if (this.isZero())
34501
- return Long.ZERO;
34502
- if (!Long.isLong(multiplier))
34503
- multiplier = Long.fromValue(multiplier);
34504
- if (wasm) {
34505
- const low = wasm.mul(this.low, this.high, multiplier.low, multiplier.high);
34506
- return Long.fromBits(low, wasm.get_high(), this.unsigned);
34507
- }
34508
- if (multiplier.isZero())
34509
- return Long.ZERO;
34510
- if (this.eq(Long.MIN_VALUE))
34511
- return multiplier.isOdd() ? Long.MIN_VALUE : Long.ZERO;
34512
- if (multiplier.eq(Long.MIN_VALUE))
34513
- return this.isOdd() ? Long.MIN_VALUE : Long.ZERO;
34514
- if (this.isNegative()) {
34515
- if (multiplier.isNegative())
34516
- return this.neg().mul(multiplier.neg());
34517
- else
34518
- return this.neg().mul(multiplier).neg();
34519
- } else if (multiplier.isNegative())
34520
- return this.mul(multiplier.neg()).neg();
34521
- if (this.lt(Long.TWO_PWR_24) && multiplier.lt(Long.TWO_PWR_24))
34522
- return Long.fromNumber(this.toNumber() * multiplier.toNumber(), this.unsigned);
34523
- const a48 = this.high >>> 16;
34524
- const a32 = this.high & 65535;
34525
- const a16 = this.low >>> 16;
34526
- const a00 = this.low & 65535;
34527
- const b48 = multiplier.high >>> 16;
34528
- const b32 = multiplier.high & 65535;
34529
- const b16 = multiplier.low >>> 16;
34530
- const b00 = multiplier.low & 65535;
34531
- let c48 = 0, c32 = 0, c16 = 0, c00 = 0;
34532
- c00 += a00 * b00;
34533
- c16 += c00 >>> 16;
34534
- c00 &= 65535;
34535
- c16 += a16 * b00;
34536
- c32 += c16 >>> 16;
34537
- c16 &= 65535;
34538
- c16 += a00 * b16;
34539
- c32 += c16 >>> 16;
34540
- c16 &= 65535;
34541
- c32 += a32 * b00;
34542
- c48 += c32 >>> 16;
34543
- c32 &= 65535;
34544
- c32 += a16 * b16;
34545
- c48 += c32 >>> 16;
34546
- c32 &= 65535;
34547
- c32 += a00 * b32;
34548
- c48 += c32 >>> 16;
34549
- c32 &= 65535;
34550
- c48 += a48 * b00 + a32 * b16 + a16 * b32 + a00 * b48;
34551
- c48 &= 65535;
34552
- return Long.fromBits(c16 << 16 | c00, c48 << 16 | c32, this.unsigned);
34553
- }
34554
- mul(multiplier) {
34555
- return this.multiply(multiplier);
34556
- }
34557
- negate() {
34558
- if (!this.unsigned && this.eq(Long.MIN_VALUE))
34559
- return Long.MIN_VALUE;
34560
- return this.not().add(Long.ONE);
34561
- }
34562
- neg() {
34563
- return this.negate();
34564
- }
34565
- not() {
34566
- return Long.fromBits(~this.low, ~this.high, this.unsigned);
34567
- }
34568
- notEquals(other) {
34569
- return !this.equals(other);
34570
- }
34571
- neq(other) {
34572
- return this.notEquals(other);
34573
- }
34574
- ne(other) {
34575
- return this.notEquals(other);
34576
- }
34577
- or(other) {
34578
- if (!Long.isLong(other))
34579
- other = Long.fromValue(other);
34580
- return Long.fromBits(this.low | other.low, this.high | other.high, this.unsigned);
34581
- }
34582
- shiftLeft(numBits) {
34583
- if (Long.isLong(numBits))
34584
- numBits = numBits.toInt();
34585
- if ((numBits &= 63) === 0)
34586
- return this;
34587
- else if (numBits < 32)
34588
- return Long.fromBits(this.low << numBits, this.high << numBits | this.low >>> 32 - numBits, this.unsigned);
34589
- else
34590
- return Long.fromBits(0, this.low << numBits - 32, this.unsigned);
34591
- }
34592
- shl(numBits) {
34593
- return this.shiftLeft(numBits);
34594
- }
34595
- shiftRight(numBits) {
34596
- if (Long.isLong(numBits))
34597
- numBits = numBits.toInt();
34598
- if ((numBits &= 63) === 0)
34599
- return this;
34600
- else if (numBits < 32)
34601
- return Long.fromBits(this.low >>> numBits | this.high << 32 - numBits, this.high >> numBits, this.unsigned);
34602
- else
34603
- return Long.fromBits(this.high >> numBits - 32, this.high >= 0 ? 0 : -1, this.unsigned);
34604
- }
34605
- shr(numBits) {
34606
- return this.shiftRight(numBits);
34607
- }
34608
- shiftRightUnsigned(numBits) {
34609
- if (Long.isLong(numBits))
34610
- numBits = numBits.toInt();
34611
- numBits &= 63;
34612
- if (numBits === 0)
34613
- return this;
34614
- else {
34615
- const high = this.high;
34616
- if (numBits < 32) {
34617
- const low = this.low;
34618
- return Long.fromBits(low >>> numBits | high << 32 - numBits, high >>> numBits, this.unsigned);
34619
- } else if (numBits === 32)
34620
- return Long.fromBits(high, 0, this.unsigned);
34621
- else
34622
- return Long.fromBits(high >>> numBits - 32, 0, this.unsigned);
34623
- }
34624
- }
34625
- shr_u(numBits) {
34626
- return this.shiftRightUnsigned(numBits);
34627
- }
34628
- shru(numBits) {
34629
- return this.shiftRightUnsigned(numBits);
34630
- }
34631
- subtract(subtrahend) {
34632
- if (!Long.isLong(subtrahend))
34633
- subtrahend = Long.fromValue(subtrahend);
34634
- return this.add(subtrahend.neg());
34635
- }
34636
- sub(subtrahend) {
34637
- return this.subtract(subtrahend);
34638
- }
34639
- toInt() {
34640
- return this.unsigned ? this.low >>> 0 : this.low;
34641
- }
34642
- toNumber() {
34643
- if (this.unsigned)
34644
- return (this.high >>> 0) * TWO_PWR_32_DBL + (this.low >>> 0);
34645
- return this.high * TWO_PWR_32_DBL + (this.low >>> 0);
34646
- }
34647
- toBigInt() {
34648
- return BigInt(this.toString());
34649
- }
34650
- toBytes(le) {
34651
- return le ? this.toBytesLE() : this.toBytesBE();
34652
- }
34653
- toBytesLE() {
34654
- const hi = this.high, lo = this.low;
34655
- return [
34656
- lo & 255,
34657
- lo >>> 8 & 255,
34658
- lo >>> 16 & 255,
34659
- lo >>> 24,
34660
- hi & 255,
34661
- hi >>> 8 & 255,
34662
- hi >>> 16 & 255,
34663
- hi >>> 24
34664
- ];
34665
- }
34666
- toBytesBE() {
34667
- const hi = this.high, lo = this.low;
34668
- return [
34669
- hi >>> 24,
34670
- hi >>> 16 & 255,
34671
- hi >>> 8 & 255,
34672
- hi & 255,
34673
- lo >>> 24,
34674
- lo >>> 16 & 255,
34675
- lo >>> 8 & 255,
34676
- lo & 255
34677
- ];
34678
- }
34679
- toSigned() {
34680
- if (!this.unsigned)
34681
- return this;
34682
- return Long.fromBits(this.low, this.high, false);
34683
- }
34684
- toString(radix) {
34685
- radix = radix || 10;
34686
- if (radix < 2 || 36 < radix)
34687
- throw new BSONError("radix");
34688
- if (this.isZero())
34689
- return "0";
34690
- if (this.isNegative()) {
34691
- if (this.eq(Long.MIN_VALUE)) {
34692
- const radixLong = Long.fromNumber(radix), div = this.div(radixLong), rem1 = div.mul(radixLong).sub(this);
34693
- return div.toString(radix) + rem1.toInt().toString(radix);
34694
- } else
34695
- return "-" + this.neg().toString(radix);
34696
- }
34697
- const radixToPower = Long.fromNumber(Math.pow(radix, 6), this.unsigned);
34698
- let rem = this;
34699
- let result = "";
34700
- while (true) {
34701
- const remDiv = rem.div(radixToPower);
34702
- const intval = rem.sub(remDiv.mul(radixToPower)).toInt() >>> 0;
34703
- let digits = intval.toString(radix);
34704
- rem = remDiv;
34705
- if (rem.isZero()) {
34706
- return digits + result;
34707
- } else {
34708
- while (digits.length < 6)
34709
- digits = "0" + digits;
34710
- result = "" + digits + result;
34711
- }
34712
- }
34713
- }
34714
- toUnsigned() {
34715
- if (this.unsigned)
34716
- return this;
34717
- return Long.fromBits(this.low, this.high, true);
34718
- }
34719
- xor(other) {
34720
- if (!Long.isLong(other))
34721
- other = Long.fromValue(other);
34722
- return Long.fromBits(this.low ^ other.low, this.high ^ other.high, this.unsigned);
34723
- }
34724
- eqz() {
34725
- return this.isZero();
34726
- }
34727
- le(other) {
34728
- return this.lessThanOrEqual(other);
34729
- }
34730
- toExtendedJSON(options) {
34731
- if (options && options.relaxed)
34732
- return this.toNumber();
34733
- return { $numberLong: this.toString() };
34734
- }
34735
- static fromExtendedJSON(doc, options) {
34736
- const { useBigInt64 = false, relaxed = true } = { ...options };
34737
- if (doc.$numberLong.length > MAX_INT64_STRING_LENGTH) {
34738
- throw new BSONError("$numberLong string is too long");
34739
- }
34740
- if (!DECIMAL_REG_EX.test(doc.$numberLong)) {
34741
- throw new BSONError(`$numberLong string "${doc.$numberLong}" is in an invalid format`);
34742
- }
34743
- if (useBigInt64) {
34744
- const bigIntResult = BigInt(doc.$numberLong);
34745
- return BigInt.asIntN(64, bigIntResult);
34746
- }
34747
- const longResult = Long.fromString(doc.$numberLong);
34748
- if (relaxed) {
34749
- return longResult.toNumber();
34750
- }
34751
- return longResult;
34752
- }
34753
- inspect(depth, options, inspect) {
34754
- inspect ?? (inspect = defaultInspect);
34755
- const longVal = inspect(this.toString(), options);
34756
- const unsignedVal = this.unsigned ? `, ${inspect(this.unsigned, options)}` : "";
34757
- return `new Long(${longVal}${unsignedVal})`;
34758
- }
34759
- };
34760
- Long.TWO_PWR_24 = Long.fromInt(TWO_PWR_24_DBL);
34761
- Long.MAX_UNSIGNED_VALUE = Long.fromBits(4294967295 | 0, 4294967295 | 0, true);
34762
- Long.ZERO = Long.fromInt(0);
34763
- Long.UZERO = Long.fromInt(0, true);
34764
- Long.ONE = Long.fromInt(1);
34765
- Long.UONE = Long.fromInt(1, true);
34766
- Long.NEG_ONE = Long.fromInt(-1);
34767
- Long.MAX_VALUE = Long.fromBits(4294967295 | 0, 2147483647 | 0, false);
34768
- Long.MIN_VALUE = Long.fromBits(0, 2147483648 | 0, false);
34769
- var PARSE_STRING_REGEXP = /^(\+|-)?(\d+|(\d*\.\d*))?(E|e)?([-+])?(\d+)?$/;
34770
- var PARSE_INF_REGEXP = /^(\+|-)?(Infinity|inf)$/i;
34771
- var PARSE_NAN_REGEXP = /^(\+|-)?NaN$/i;
34772
- var EXPONENT_MAX = 6111;
34773
- var EXPONENT_MIN = -6176;
34774
- var EXPONENT_BIAS = 6176;
34775
- var MAX_DIGITS = 34;
34776
- var NAN_BUFFER = ByteUtils.fromNumberArray([
34777
- 124,
34778
- 0,
34779
- 0,
34780
- 0,
34781
- 0,
34782
- 0,
34783
- 0,
34784
- 0,
34785
- 0,
34786
- 0,
34787
- 0,
34788
- 0,
34789
- 0,
34790
- 0,
34791
- 0,
34792
- 0
34793
- ].reverse());
34794
- var INF_NEGATIVE_BUFFER = ByteUtils.fromNumberArray([
34795
- 248,
34796
- 0,
34797
- 0,
34798
- 0,
34799
- 0,
34800
- 0,
34801
- 0,
34802
- 0,
34803
- 0,
34804
- 0,
34805
- 0,
34806
- 0,
34807
- 0,
34808
- 0,
34809
- 0,
34810
- 0
34811
- ].reverse());
34812
- var INF_POSITIVE_BUFFER = ByteUtils.fromNumberArray([
34813
- 120,
34814
- 0,
34815
- 0,
34816
- 0,
34817
- 0,
34818
- 0,
34819
- 0,
34820
- 0,
34821
- 0,
34822
- 0,
34823
- 0,
34824
- 0,
34825
- 0,
34826
- 0,
34827
- 0,
34828
- 0
34829
- ].reverse());
34830
- var EXPONENT_REGEX = /^([-+])?(\d+)?$/;
34831
- var COMBINATION_MASK = 31;
34832
- var EXPONENT_MASK = 16383;
34833
- var COMBINATION_INFINITY = 30;
34834
- var COMBINATION_NAN = 31;
34835
- function isDigit(value) {
34836
- return !isNaN(parseInt(value, 10));
34837
- }
34838
- function divideu128(value) {
34839
- const DIVISOR = Long.fromNumber(1e3 * 1e3 * 1e3);
34840
- let _rem = Long.fromNumber(0);
34841
- if (!value.parts[0] && !value.parts[1] && !value.parts[2] && !value.parts[3]) {
34842
- return { quotient: value, rem: _rem };
34843
- }
34844
- for (let i = 0; i <= 3; i++) {
34845
- _rem = _rem.shiftLeft(32);
34846
- _rem = _rem.add(new Long(value.parts[i], 0));
34847
- value.parts[i] = _rem.div(DIVISOR).low;
34848
- _rem = _rem.modulo(DIVISOR);
34849
- }
34850
- return { quotient: value, rem: _rem };
34851
- }
34852
- function multiply64x2(left, right) {
34853
- if (!left && !right) {
34854
- return { high: Long.fromNumber(0), low: Long.fromNumber(0) };
34855
- }
34856
- const leftHigh = left.shiftRightUnsigned(32);
34857
- const leftLow = new Long(left.getLowBits(), 0);
34858
- const rightHigh = right.shiftRightUnsigned(32);
34859
- const rightLow = new Long(right.getLowBits(), 0);
34860
- let productHigh = leftHigh.multiply(rightHigh);
34861
- let productMid = leftHigh.multiply(rightLow);
34862
- const productMid2 = leftLow.multiply(rightHigh);
34863
- let productLow = leftLow.multiply(rightLow);
34864
- productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
34865
- productMid = new Long(productMid.getLowBits(), 0).add(productMid2).add(productLow.shiftRightUnsigned(32));
34866
- productHigh = productHigh.add(productMid.shiftRightUnsigned(32));
34867
- productLow = productMid.shiftLeft(32).add(new Long(productLow.getLowBits(), 0));
34868
- return { high: productHigh, low: productLow };
34869
- }
34870
- function lessThan(left, right) {
34871
- const uhleft = left.high >>> 0;
34872
- const uhright = right.high >>> 0;
34873
- if (uhleft < uhright) {
34874
- return true;
34875
- } else if (uhleft === uhright) {
34876
- const ulleft = left.low >>> 0;
34877
- const ulright = right.low >>> 0;
34878
- if (ulleft < ulright)
34879
- return true;
34880
- }
34881
- return false;
34882
- }
34883
- function invalidErr(string, message) {
34884
- throw new BSONError(`"${string}" is not a valid Decimal128 string - ${message}`);
34885
- }
34886
- var Decimal128 = class extends BSONValue {
34887
- get _bsontype() {
34888
- return "Decimal128";
34889
- }
34890
- constructor(bytes) {
34891
- super();
34892
- if (typeof bytes === "string") {
34893
- this.bytes = Decimal128.fromString(bytes).bytes;
34894
- } else if (bytes instanceof Uint8Array || isUint8Array(bytes)) {
34895
- if (bytes.byteLength !== 16) {
34896
- throw new BSONError("Decimal128 must take a Buffer of 16 bytes");
34897
- }
34898
- this.bytes = bytes;
34899
- } else {
34900
- throw new BSONError("Decimal128 must take a Buffer or string");
34901
- }
34902
- }
34903
- static fromString(representation) {
34904
- return Decimal128._fromString(representation, { allowRounding: false });
34905
- }
34906
- static fromStringWithRounding(representation) {
34907
- return Decimal128._fromString(representation, { allowRounding: true });
34908
- }
34909
- static _fromString(representation, options) {
34910
- let isNegative = false;
34911
- let sawSign = false;
34912
- let sawRadix = false;
34913
- let foundNonZero = false;
34914
- let significantDigits = 0;
34915
- let nDigitsRead = 0;
34916
- let nDigits = 0;
34917
- let radixPosition = 0;
34918
- let firstNonZero = 0;
34919
- const digits = [0];
34920
- let nDigitsStored = 0;
34921
- let digitsInsert = 0;
34922
- let lastDigit = 0;
34923
- let exponent = 0;
34924
- let significandHigh = new Long(0, 0);
34925
- let significandLow = new Long(0, 0);
34926
- let biasedExponent = 0;
34927
- let index = 0;
34928
- if (representation.length >= 7e3) {
34929
- throw new BSONError("" + representation + " not a valid Decimal128 string");
34930
- }
34931
- const stringMatch = representation.match(PARSE_STRING_REGEXP);
34932
- const infMatch = representation.match(PARSE_INF_REGEXP);
34933
- const nanMatch = representation.match(PARSE_NAN_REGEXP);
34934
- if (!stringMatch && !infMatch && !nanMatch || representation.length === 0) {
34935
- throw new BSONError("" + representation + " not a valid Decimal128 string");
34936
- }
34937
- if (stringMatch) {
34938
- const unsignedNumber = stringMatch[2];
34939
- const e = stringMatch[4];
34940
- const expSign = stringMatch[5];
34941
- const expNumber = stringMatch[6];
34942
- if (e && expNumber === void 0)
34943
- invalidErr(representation, "missing exponent power");
34944
- if (e && unsignedNumber === void 0)
34945
- invalidErr(representation, "missing exponent base");
34946
- if (e === void 0 && (expSign || expNumber)) {
34947
- invalidErr(representation, "missing e before exponent");
34948
- }
34949
- }
34950
- if (representation[index] === "+" || representation[index] === "-") {
34951
- sawSign = true;
34952
- isNegative = representation[index++] === "-";
34953
- }
34954
- if (!isDigit(representation[index]) && representation[index] !== ".") {
34955
- if (representation[index] === "i" || representation[index] === "I") {
34956
- return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
34957
- } else if (representation[index] === "N") {
34958
- return new Decimal128(NAN_BUFFER);
34959
- }
34960
- }
34961
- while (isDigit(representation[index]) || representation[index] === ".") {
34962
- if (representation[index] === ".") {
34963
- if (sawRadix)
34964
- invalidErr(representation, "contains multiple periods");
34965
- sawRadix = true;
34966
- index = index + 1;
34967
- continue;
34968
- }
34969
- if (nDigitsStored < MAX_DIGITS) {
34970
- if (representation[index] !== "0" || foundNonZero) {
34971
- if (!foundNonZero) {
34972
- firstNonZero = nDigitsRead;
34973
- }
34974
- foundNonZero = true;
34975
- digits[digitsInsert++] = parseInt(representation[index], 10);
34976
- nDigitsStored = nDigitsStored + 1;
34977
- }
34978
- }
34979
- if (foundNonZero)
34980
- nDigits = nDigits + 1;
34981
- if (sawRadix)
34982
- radixPosition = radixPosition + 1;
34983
- nDigitsRead = nDigitsRead + 1;
34984
- index = index + 1;
34985
- }
34986
- if (sawRadix && !nDigitsRead)
34987
- throw new BSONError("" + representation + " not a valid Decimal128 string");
34988
- if (representation[index] === "e" || representation[index] === "E") {
34989
- const match = representation.substr(++index).match(EXPONENT_REGEX);
34990
- if (!match || !match[2])
34991
- return new Decimal128(NAN_BUFFER);
34992
- exponent = parseInt(match[0], 10);
34993
- index = index + match[0].length;
34994
- }
34995
- if (representation[index])
34996
- return new Decimal128(NAN_BUFFER);
34997
- if (!nDigitsStored) {
34998
- digits[0] = 0;
34999
- nDigits = 1;
35000
- nDigitsStored = 1;
35001
- significantDigits = 0;
35002
- } else {
35003
- lastDigit = nDigitsStored - 1;
35004
- significantDigits = nDigits;
35005
- if (significantDigits !== 1) {
35006
- while (representation[firstNonZero + significantDigits - 1 + Number(sawSign) + Number(sawRadix)] === "0") {
35007
- significantDigits = significantDigits - 1;
35008
- }
35009
- }
35010
- }
35011
- if (exponent <= radixPosition && radixPosition > exponent + (1 << 14)) {
35012
- exponent = EXPONENT_MIN;
35013
- } else {
35014
- exponent = exponent - radixPosition;
35015
- }
35016
- while (exponent > EXPONENT_MAX) {
35017
- lastDigit = lastDigit + 1;
35018
- if (lastDigit >= MAX_DIGITS) {
35019
- if (significantDigits === 0) {
35020
- exponent = EXPONENT_MAX;
35021
- break;
35022
- }
35023
- invalidErr(representation, "overflow");
35024
- }
35025
- exponent = exponent - 1;
35026
- }
35027
- if (options.allowRounding) {
35028
- while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
35029
- if (lastDigit === 0 && significantDigits < nDigitsStored) {
35030
- exponent = EXPONENT_MIN;
35031
- significantDigits = 0;
35032
- break;
35033
- }
35034
- if (nDigitsStored < nDigits) {
35035
- nDigits = nDigits - 1;
35036
- } else {
35037
- lastDigit = lastDigit - 1;
35038
- }
35039
- if (exponent < EXPONENT_MAX) {
35040
- exponent = exponent + 1;
35041
- } else {
35042
- const digitsString = digits.join("");
35043
- if (digitsString.match(/^0+$/)) {
35044
- exponent = EXPONENT_MAX;
35045
- break;
35046
- }
35047
- invalidErr(representation, "overflow");
35048
- }
35049
- }
35050
- if (lastDigit + 1 < significantDigits) {
35051
- let endOfString = nDigitsRead;
35052
- if (sawRadix) {
35053
- firstNonZero = firstNonZero + 1;
35054
- endOfString = endOfString + 1;
35055
- }
35056
- if (sawSign) {
35057
- firstNonZero = firstNonZero + 1;
35058
- endOfString = endOfString + 1;
35059
- }
35060
- const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
35061
- let roundBit = 0;
35062
- if (roundDigit >= 5) {
35063
- roundBit = 1;
35064
- if (roundDigit === 5) {
35065
- roundBit = digits[lastDigit] % 2 === 1 ? 1 : 0;
35066
- for (let i = firstNonZero + lastDigit + 2; i < endOfString; i++) {
35067
- if (parseInt(representation[i], 10)) {
35068
- roundBit = 1;
35069
- break;
35070
- }
35071
- }
35072
- }
35073
- }
35074
- if (roundBit) {
35075
- let dIdx = lastDigit;
35076
- for (; dIdx >= 0; dIdx--) {
35077
- if (++digits[dIdx] > 9) {
35078
- digits[dIdx] = 0;
35079
- if (dIdx === 0) {
35080
- if (exponent < EXPONENT_MAX) {
35081
- exponent = exponent + 1;
35082
- digits[dIdx] = 1;
35083
- } else {
35084
- return new Decimal128(isNegative ? INF_NEGATIVE_BUFFER : INF_POSITIVE_BUFFER);
35085
- }
35086
- }
35087
- } else {
35088
- break;
35089
- }
35090
- }
35091
- }
35092
- }
35093
- } else {
35094
- while (exponent < EXPONENT_MIN || nDigitsStored < nDigits) {
35095
- if (lastDigit === 0) {
35096
- if (significantDigits === 0) {
35097
- exponent = EXPONENT_MIN;
35098
- break;
35099
- }
35100
- invalidErr(representation, "exponent underflow");
35101
- }
35102
- if (nDigitsStored < nDigits) {
35103
- if (representation[nDigits - 1 + Number(sawSign) + Number(sawRadix)] !== "0" && significantDigits !== 0) {
35104
- invalidErr(representation, "inexact rounding");
35105
- }
35106
- nDigits = nDigits - 1;
35107
- } else {
35108
- if (digits[lastDigit] !== 0) {
35109
- invalidErr(representation, "inexact rounding");
35110
- }
35111
- lastDigit = lastDigit - 1;
35112
- }
35113
- if (exponent < EXPONENT_MAX) {
35114
- exponent = exponent + 1;
35115
- } else {
35116
- invalidErr(representation, "overflow");
35117
- }
35118
- }
35119
- if (lastDigit + 1 < significantDigits) {
35120
- if (sawRadix) {
35121
- firstNonZero = firstNonZero + 1;
35122
- }
35123
- if (sawSign) {
35124
- firstNonZero = firstNonZero + 1;
35125
- }
35126
- const roundDigit = parseInt(representation[firstNonZero + lastDigit + 1], 10);
35127
- if (roundDigit !== 0) {
35128
- invalidErr(representation, "inexact rounding");
35129
- }
35130
- }
35131
- }
35132
- significandHigh = Long.fromNumber(0);
35133
- significandLow = Long.fromNumber(0);
35134
- if (significantDigits === 0) {
35135
- significandHigh = Long.fromNumber(0);
35136
- significandLow = Long.fromNumber(0);
35137
- } else if (lastDigit < 17) {
35138
- let dIdx = 0;
35139
- significandLow = Long.fromNumber(digits[dIdx++]);
35140
- significandHigh = new Long(0, 0);
35141
- for (; dIdx <= lastDigit; dIdx++) {
35142
- significandLow = significandLow.multiply(Long.fromNumber(10));
35143
- significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
35144
- }
35145
- } else {
35146
- let dIdx = 0;
35147
- significandHigh = Long.fromNumber(digits[dIdx++]);
35148
- for (; dIdx <= lastDigit - 17; dIdx++) {
35149
- significandHigh = significandHigh.multiply(Long.fromNumber(10));
35150
- significandHigh = significandHigh.add(Long.fromNumber(digits[dIdx]));
35151
- }
35152
- significandLow = Long.fromNumber(digits[dIdx++]);
35153
- for (; dIdx <= lastDigit; dIdx++) {
35154
- significandLow = significandLow.multiply(Long.fromNumber(10));
35155
- significandLow = significandLow.add(Long.fromNumber(digits[dIdx]));
35156
- }
35157
- }
35158
- const significand = multiply64x2(significandHigh, Long.fromString("100000000000000000"));
35159
- significand.low = significand.low.add(significandLow);
35160
- if (lessThan(significand.low, significandLow)) {
35161
- significand.high = significand.high.add(Long.fromNumber(1));
35162
- }
35163
- biasedExponent = exponent + EXPONENT_BIAS;
35164
- const dec2 = { low: Long.fromNumber(0), high: Long.fromNumber(0) };
35165
- if (significand.high.shiftRightUnsigned(49).and(Long.fromNumber(1)).equals(Long.fromNumber(1))) {
35166
- dec2.high = dec2.high.or(Long.fromNumber(3).shiftLeft(61));
35167
- dec2.high = dec2.high.or(Long.fromNumber(biasedExponent).and(Long.fromNumber(16383).shiftLeft(47)));
35168
- dec2.high = dec2.high.or(significand.high.and(Long.fromNumber(140737488355327)));
35169
- } else {
35170
- dec2.high = dec2.high.or(Long.fromNumber(biasedExponent & 16383).shiftLeft(49));
35171
- dec2.high = dec2.high.or(significand.high.and(Long.fromNumber(562949953421311)));
35172
- }
35173
- dec2.low = significand.low;
35174
- if (isNegative) {
35175
- dec2.high = dec2.high.or(Long.fromString("9223372036854775808"));
35176
- }
35177
- const buffer2 = ByteUtils.allocateUnsafe(16);
35178
- index = 0;
35179
- buffer2[index++] = dec2.low.low & 255;
35180
- buffer2[index++] = dec2.low.low >> 8 & 255;
35181
- buffer2[index++] = dec2.low.low >> 16 & 255;
35182
- buffer2[index++] = dec2.low.low >> 24 & 255;
35183
- buffer2[index++] = dec2.low.high & 255;
35184
- buffer2[index++] = dec2.low.high >> 8 & 255;
35185
- buffer2[index++] = dec2.low.high >> 16 & 255;
35186
- buffer2[index++] = dec2.low.high >> 24 & 255;
35187
- buffer2[index++] = dec2.high.low & 255;
35188
- buffer2[index++] = dec2.high.low >> 8 & 255;
35189
- buffer2[index++] = dec2.high.low >> 16 & 255;
35190
- buffer2[index++] = dec2.high.low >> 24 & 255;
35191
- buffer2[index++] = dec2.high.high & 255;
35192
- buffer2[index++] = dec2.high.high >> 8 & 255;
35193
- buffer2[index++] = dec2.high.high >> 16 & 255;
35194
- buffer2[index++] = dec2.high.high >> 24 & 255;
35195
- return new Decimal128(buffer2);
35196
- }
35197
- toString() {
35198
- let biased_exponent;
35199
- let significand_digits = 0;
35200
- const significand = new Array(36);
35201
- for (let i = 0; i < significand.length; i++)
35202
- significand[i] = 0;
35203
- let index = 0;
35204
- let is_zero = false;
35205
- let significand_msb;
35206
- let significand128 = { parts: [0, 0, 0, 0] };
35207
- let j, k;
35208
- const string = [];
35209
- index = 0;
35210
- const buffer2 = this.bytes;
35211
- const low = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
35212
- const midl = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
35213
- const midh = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
35214
- const high = buffer2[index++] | buffer2[index++] << 8 | buffer2[index++] << 16 | buffer2[index++] << 24;
35215
- index = 0;
35216
- const dec2 = {
35217
- low: new Long(low, midl),
35218
- high: new Long(midh, high)
35219
- };
35220
- if (dec2.high.lessThan(Long.ZERO)) {
35221
- string.push("-");
35222
- }
35223
- const combination = high >> 26 & COMBINATION_MASK;
35224
- if (combination >> 3 === 3) {
35225
- if (combination === COMBINATION_INFINITY) {
35226
- return string.join("") + "Infinity";
35227
- } else if (combination === COMBINATION_NAN) {
35228
- return "NaN";
35229
- } else {
35230
- biased_exponent = high >> 15 & EXPONENT_MASK;
35231
- significand_msb = 8 + (high >> 14 & 1);
35232
- }
35233
- } else {
35234
- significand_msb = high >> 14 & 7;
35235
- biased_exponent = high >> 17 & EXPONENT_MASK;
35236
- }
35237
- const exponent = biased_exponent - EXPONENT_BIAS;
35238
- significand128.parts[0] = (high & 16383) + ((significand_msb & 15) << 14);
35239
- significand128.parts[1] = midh;
35240
- significand128.parts[2] = midl;
35241
- significand128.parts[3] = low;
35242
- if (significand128.parts[0] === 0 && significand128.parts[1] === 0 && significand128.parts[2] === 0 && significand128.parts[3] === 0) {
35243
- is_zero = true;
35244
- } else {
35245
- for (k = 3; k >= 0; k--) {
35246
- let least_digits = 0;
35247
- const result = divideu128(significand128);
35248
- significand128 = result.quotient;
35249
- least_digits = result.rem.low;
35250
- if (!least_digits)
35251
- continue;
35252
- for (j = 8; j >= 0; j--) {
35253
- significand[k * 9 + j] = least_digits % 10;
35254
- least_digits = Math.floor(least_digits / 10);
35255
- }
35256
- }
35257
- }
35258
- if (is_zero) {
35259
- significand_digits = 1;
35260
- significand[index] = 0;
35261
- } else {
35262
- significand_digits = 36;
35263
- while (!significand[index]) {
35264
- significand_digits = significand_digits - 1;
35265
- index = index + 1;
35266
- }
35267
- }
35268
- const scientific_exponent = significand_digits - 1 + exponent;
35269
- if (scientific_exponent >= 34 || scientific_exponent <= -7 || exponent > 0) {
35270
- if (significand_digits > 34) {
35271
- string.push(`${0}`);
35272
- if (exponent > 0)
35273
- string.push(`E+${exponent}`);
35274
- else if (exponent < 0)
35275
- string.push(`E${exponent}`);
35276
- return string.join("");
35277
- }
35278
- string.push(`${significand[index++]}`);
35279
- significand_digits = significand_digits - 1;
35280
- if (significand_digits) {
35281
- string.push(".");
35282
- }
35283
- for (let i = 0; i < significand_digits; i++) {
35284
- string.push(`${significand[index++]}`);
35285
- }
35286
- string.push("E");
35287
- if (scientific_exponent > 0) {
35288
- string.push(`+${scientific_exponent}`);
35289
- } else {
35290
- string.push(`${scientific_exponent}`);
35291
- }
35292
- } else {
35293
- if (exponent >= 0) {
35294
- for (let i = 0; i < significand_digits; i++) {
35295
- string.push(`${significand[index++]}`);
35296
- }
35297
- } else {
35298
- let radix_position = significand_digits + exponent;
35299
- if (radix_position > 0) {
35300
- for (let i = 0; i < radix_position; i++) {
35301
- string.push(`${significand[index++]}`);
35302
- }
35303
- } else {
35304
- string.push("0");
35305
- }
35306
- string.push(".");
35307
- while (radix_position++ < 0) {
35308
- string.push("0");
35309
- }
35310
- for (let i = 0; i < significand_digits - Math.max(radix_position - 1, 0); i++) {
35311
- string.push(`${significand[index++]}`);
35312
- }
35313
- }
35314
- }
35315
- return string.join("");
35316
- }
35317
- toJSON() {
35318
- return { $numberDecimal: this.toString() };
35319
- }
35320
- toExtendedJSON() {
35321
- return { $numberDecimal: this.toString() };
35322
- }
35323
- static fromExtendedJSON(doc) {
35324
- return Decimal128.fromString(doc.$numberDecimal);
35325
- }
35326
- inspect(depth, options, inspect) {
35327
- inspect ?? (inspect = defaultInspect);
35328
- const d128string = inspect(this.toString(), options);
35329
- return `new Decimal128(${d128string})`;
35330
- }
35331
- };
35332
- var Double = class extends BSONValue {
35333
- get _bsontype() {
35334
- return "Double";
35335
- }
35336
- constructor(value) {
35337
- super();
35338
- if (value instanceof Number) {
35339
- value = value.valueOf();
35340
- }
35341
- this.value = +value;
35342
- }
35343
- static fromString(value) {
35344
- const coercedValue = Number(value);
35345
- if (value === "NaN")
35346
- return new Double(NaN);
35347
- if (value === "Infinity")
35348
- return new Double(Infinity);
35349
- if (value === "-Infinity")
35350
- return new Double(-Infinity);
35351
- if (!Number.isFinite(coercedValue)) {
35352
- throw new BSONError(`Input: ${value} is not representable as a Double`);
35353
- }
35354
- if (value.trim() !== value) {
35355
- throw new BSONError(`Input: '${value}' contains whitespace`);
35356
- }
35357
- if (value === "") {
35358
- throw new BSONError(`Input is an empty string`);
35359
- }
35360
- if (/[^-0-9.+eE]/.test(value)) {
35361
- throw new BSONError(`Input: '${value}' is not in decimal or exponential notation`);
35362
- }
35363
- return new Double(coercedValue);
35364
- }
35365
- valueOf() {
35366
- return this.value;
35367
- }
35368
- toJSON() {
35369
- return this.value;
35370
- }
35371
- toString(radix) {
35372
- return this.value.toString(radix);
35373
- }
35374
- toExtendedJSON(options) {
35375
- if (options && (options.legacy || options.relaxed && isFinite(this.value))) {
35376
- return this.value;
35377
- }
35378
- if (Object.is(Math.sign(this.value), -0)) {
35379
- return { $numberDouble: "-0.0" };
35380
- }
35381
- return {
35382
- $numberDouble: Number.isInteger(this.value) ? this.value.toFixed(1) : this.value.toString()
35383
- };
35384
- }
35385
- static fromExtendedJSON(doc, options) {
35386
- const doubleValue = parseFloat(doc.$numberDouble);
35387
- return options && options.relaxed ? doubleValue : new Double(doubleValue);
35388
- }
35389
- inspect(depth, options, inspect) {
35390
- inspect ?? (inspect = defaultInspect);
35391
- return `new Double(${inspect(this.value, options)})`;
35392
- }
35393
- };
35394
- var Int32 = class extends BSONValue {
35395
- get _bsontype() {
35396
- return "Int32";
35397
- }
35398
- constructor(value) {
35399
- super();
35400
- if (value instanceof Number) {
35401
- value = value.valueOf();
35402
- }
35403
- this.value = +value | 0;
35404
- }
35405
- static fromString(value) {
35406
- const cleanedValue = removeLeadingZerosAndExplicitPlus(value);
35407
- const coercedValue = Number(value);
35408
- if (BSON_INT32_MAX < coercedValue) {
35409
- throw new BSONError(`Input: '${value}' is larger than the maximum value for Int32`);
35410
- } else if (BSON_INT32_MIN > coercedValue) {
35411
- throw new BSONError(`Input: '${value}' is smaller than the minimum value for Int32`);
35412
- } else if (!Number.isSafeInteger(coercedValue)) {
35413
- throw new BSONError(`Input: '${value}' is not a safe integer`);
35414
- } else if (coercedValue.toString() !== cleanedValue) {
35415
- throw new BSONError(`Input: '${value}' is not a valid Int32 string`);
35416
- }
35417
- return new Int32(coercedValue);
35418
- }
35419
- valueOf() {
35420
- return this.value;
35421
- }
35422
- toString(radix) {
35423
- return this.value.toString(radix);
35424
- }
35425
- toJSON() {
35426
- return this.value;
35427
- }
35428
- toExtendedJSON(options) {
35429
- if (options && (options.relaxed || options.legacy))
35430
- return this.value;
35431
- return { $numberInt: this.value.toString() };
35432
- }
35433
- static fromExtendedJSON(doc, options) {
35434
- return options && options.relaxed ? parseInt(doc.$numberInt, 10) : new Int32(doc.$numberInt);
35435
- }
35436
- inspect(depth, options, inspect) {
35437
- inspect ?? (inspect = defaultInspect);
35438
- return `new Int32(${inspect(this.value, options)})`;
35439
- }
35440
- };
35441
- var MaxKey = class extends BSONValue {
35442
- get _bsontype() {
35443
- return "MaxKey";
35444
- }
35445
- toExtendedJSON() {
35446
- return { $maxKey: 1 };
35447
- }
35448
- static fromExtendedJSON() {
35449
- return new MaxKey();
35450
- }
35451
- inspect() {
35452
- return "new MaxKey()";
35453
- }
35454
- };
35455
- var MinKey = class extends BSONValue {
35456
- get _bsontype() {
35457
- return "MinKey";
35458
- }
35459
- toExtendedJSON() {
35460
- return { $minKey: 1 };
35461
- }
35462
- static fromExtendedJSON() {
35463
- return new MinKey();
35464
- }
35465
- inspect() {
35466
- return "new MinKey()";
35467
- }
35468
- };
35469
- var PROCESS_UNIQUE = null;
35470
- var __idCache = /* @__PURE__ */ new WeakMap();
35471
- var ObjectId13 = class extends BSONValue {
35472
- get _bsontype() {
35473
- return "ObjectId";
35474
- }
35475
- constructor(inputId) {
35476
- super();
35477
- let workingId;
35478
- if (typeof inputId === "object" && inputId && "id" in inputId) {
35479
- if (typeof inputId.id !== "string" && !ArrayBuffer.isView(inputId.id)) {
35480
- throw new BSONError("Argument passed in must have an id that is of type string or Buffer");
35481
- }
35482
- if ("toHexString" in inputId && typeof inputId.toHexString === "function") {
35483
- workingId = ByteUtils.fromHex(inputId.toHexString());
35484
- } else {
35485
- workingId = inputId.id;
35486
- }
35487
- } else {
35488
- workingId = inputId;
35489
- }
35490
- if (workingId == null || typeof workingId === "number") {
35491
- this.buffer = ObjectId13.generate(typeof workingId === "number" ? workingId : void 0);
35492
- } else if (ArrayBuffer.isView(workingId) && workingId.byteLength === 12) {
35493
- this.buffer = ByteUtils.toLocalBufferType(workingId);
35494
- } else if (typeof workingId === "string") {
35495
- if (ObjectId13.validateHexString(workingId)) {
35496
- this.buffer = ByteUtils.fromHex(workingId);
35497
- if (ObjectId13.cacheHexString) {
35498
- __idCache.set(this, workingId);
35499
- }
35500
- } else {
35501
- throw new BSONError("input must be a 24 character hex string, 12 byte Uint8Array, or an integer");
35502
- }
35503
- } else {
35504
- throw new BSONError("Argument passed in does not match the accepted types");
35505
- }
35506
- }
35507
- get id() {
35508
- return this.buffer;
35509
- }
35510
- set id(value) {
35511
- this.buffer = value;
35512
- if (ObjectId13.cacheHexString) {
35513
- __idCache.set(this, ByteUtils.toHex(value));
35514
- }
35515
- }
35516
- static validateHexString(string) {
35517
- if (string?.length !== 24)
35518
- return false;
35519
- for (let i = 0; i < 24; i++) {
35520
- const char = string.charCodeAt(i);
35521
- if (char >= 48 && char <= 57 || char >= 97 && char <= 102 || char >= 65 && char <= 70) {
35522
- continue;
35523
- }
35524
- return false;
35525
- }
35526
- return true;
35527
- }
35528
- toHexString() {
35529
- if (ObjectId13.cacheHexString) {
35530
- const __id = __idCache.get(this);
35531
- if (__id)
35532
- return __id;
35533
- }
35534
- const hexString = ByteUtils.toHex(this.id);
35535
- if (ObjectId13.cacheHexString) {
35536
- __idCache.set(this, hexString);
35537
- }
35538
- return hexString;
35539
- }
35540
- static getInc() {
35541
- return ObjectId13.index = (ObjectId13.index + 1) % 16777215;
35542
- }
35543
- static generate(time) {
35544
- if ("number" !== typeof time) {
35545
- time = Math.floor(Date.now() / 1e3);
35546
- }
35547
- const inc = ObjectId13.getInc();
35548
- const buffer2 = ByteUtils.allocateUnsafe(12);
35549
- NumberUtils.setInt32BE(buffer2, 0, time);
35550
- if (PROCESS_UNIQUE === null) {
35551
- PROCESS_UNIQUE = ByteUtils.randomBytes(5);
35552
- }
35553
- buffer2[4] = PROCESS_UNIQUE[0];
35554
- buffer2[5] = PROCESS_UNIQUE[1];
35555
- buffer2[6] = PROCESS_UNIQUE[2];
35556
- buffer2[7] = PROCESS_UNIQUE[3];
35557
- buffer2[8] = PROCESS_UNIQUE[4];
35558
- buffer2[11] = inc & 255;
35559
- buffer2[10] = inc >> 8 & 255;
35560
- buffer2[9] = inc >> 16 & 255;
35561
- return buffer2;
35562
- }
35563
- toString(encoding) {
35564
- if (encoding === "base64")
35565
- return ByteUtils.toBase64(this.id);
35566
- if (encoding === "hex")
35567
- return this.toHexString();
35568
- return this.toHexString();
35569
- }
35570
- toJSON() {
35571
- return this.toHexString();
35572
- }
35573
- static is(variable) {
35574
- return variable != null && typeof variable === "object" && "_bsontype" in variable && variable._bsontype === "ObjectId";
35575
- }
35576
- equals(otherId) {
35577
- if (otherId === void 0 || otherId === null) {
35578
- return false;
35579
- }
35580
- if (ObjectId13.is(otherId)) {
35581
- return this.buffer[11] === otherId.buffer[11] && ByteUtils.equals(this.buffer, otherId.buffer);
35582
- }
35583
- if (typeof otherId === "string") {
35584
- return otherId.toLowerCase() === this.toHexString();
35585
- }
35586
- if (typeof otherId === "object" && typeof otherId.toHexString === "function") {
35587
- const otherIdString = otherId.toHexString();
35588
- const thisIdString = this.toHexString();
35589
- return typeof otherIdString === "string" && otherIdString.toLowerCase() === thisIdString;
35590
- }
35591
- return false;
35592
- }
35593
- getTimestamp() {
35594
- const timestamp = /* @__PURE__ */ new Date();
35595
- const time = NumberUtils.getUint32BE(this.buffer, 0);
35596
- timestamp.setTime(Math.floor(time) * 1e3);
35597
- return timestamp;
35598
- }
35599
- static createPk() {
35600
- return new ObjectId13();
35601
- }
35602
- serializeInto(uint8array, index) {
35603
- uint8array[index] = this.buffer[0];
35604
- uint8array[index + 1] = this.buffer[1];
35605
- uint8array[index + 2] = this.buffer[2];
35606
- uint8array[index + 3] = this.buffer[3];
35607
- uint8array[index + 4] = this.buffer[4];
35608
- uint8array[index + 5] = this.buffer[5];
35609
- uint8array[index + 6] = this.buffer[6];
35610
- uint8array[index + 7] = this.buffer[7];
35611
- uint8array[index + 8] = this.buffer[8];
35612
- uint8array[index + 9] = this.buffer[9];
35613
- uint8array[index + 10] = this.buffer[10];
35614
- uint8array[index + 11] = this.buffer[11];
35615
- return 12;
35616
- }
35617
- static createFromTime(time) {
35618
- const buffer2 = ByteUtils.allocate(12);
35619
- for (let i = 11; i >= 4; i--)
35620
- buffer2[i] = 0;
35621
- NumberUtils.setInt32BE(buffer2, 0, time);
35622
- return new ObjectId13(buffer2);
35623
- }
35624
- static createFromHexString(hexString) {
35625
- if (hexString?.length !== 24) {
35626
- throw new BSONError("hex string must be 24 characters");
35627
- }
35628
- return new ObjectId13(ByteUtils.fromHex(hexString));
35629
- }
35630
- static createFromBase64(base64) {
35631
- if (base64?.length !== 16) {
35632
- throw new BSONError("base64 string must be 16 characters");
35633
- }
35634
- return new ObjectId13(ByteUtils.fromBase64(base64));
35635
- }
35636
- static isValid(id) {
35637
- if (id == null)
35638
- return false;
35639
- if (typeof id === "string")
35640
- return ObjectId13.validateHexString(id);
35641
- try {
35642
- new ObjectId13(id);
35643
- return true;
35644
- } catch {
35645
- return false;
35646
- }
35647
- }
35648
- toExtendedJSON() {
35649
- if (this.toHexString)
35650
- return { $oid: this.toHexString() };
35651
- return { $oid: this.toString("hex") };
35652
- }
35653
- static fromExtendedJSON(doc) {
35654
- return new ObjectId13(doc.$oid);
35655
- }
35656
- isCached() {
35657
- return ObjectId13.cacheHexString && __idCache.has(this);
35658
- }
35659
- inspect(depth, options, inspect) {
35660
- inspect ?? (inspect = defaultInspect);
35661
- return `new ObjectId(${inspect(this.toHexString(), options)})`;
35662
- }
35663
- };
35664
- ObjectId13.index = Math.floor(Math.random() * 16777215);
35665
- function internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined) {
35666
- let totalLength = 4 + 1;
35667
- if (Array.isArray(object)) {
35668
- for (let i = 0; i < object.length; i++) {
35669
- totalLength += calculateElement(i.toString(), object[i], serializeFunctions, true, ignoreUndefined);
35670
- }
35671
- } else {
35672
- if (typeof object?.toBSON === "function") {
35673
- object = object.toBSON();
35674
- }
35675
- for (const key of Object.keys(object)) {
35676
- totalLength += calculateElement(key, object[key], serializeFunctions, false, ignoreUndefined);
35677
- }
35678
- }
35679
- return totalLength;
35680
- }
35681
- function calculateElement(name, value, serializeFunctions = false, isArray = false, ignoreUndefined = false) {
35682
- if (typeof value?.toBSON === "function") {
35683
- value = value.toBSON();
35684
- }
35685
- switch (typeof value) {
35686
- case "string":
35687
- return 1 + ByteUtils.utf8ByteLength(name) + 1 + 4 + ByteUtils.utf8ByteLength(value) + 1;
35688
- case "number":
35689
- if (Math.floor(value) === value && value >= JS_INT_MIN && value <= JS_INT_MAX) {
35690
- if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
35691
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (4 + 1);
35692
- } else {
35693
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
35694
- }
35695
- } else {
35696
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
35697
- }
35698
- case "undefined":
35699
- if (isArray || !ignoreUndefined)
35700
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
35701
- return 0;
35702
- case "boolean":
35703
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 1);
35704
- case "object":
35705
- if (value != null && typeof value._bsontype === "string" && value[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
35706
- throw new BSONVersionError();
35707
- } else if (value == null || value._bsontype === "MinKey" || value._bsontype === "MaxKey") {
35708
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1;
35709
- } else if (value._bsontype === "ObjectId") {
35710
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (12 + 1);
35711
- } else if (value instanceof Date || isDate(value)) {
35712
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
35713
- } else if (ArrayBuffer.isView(value) || value instanceof ArrayBuffer || isAnyArrayBuffer(value)) {
35714
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (1 + 4 + 1) + value.byteLength;
35715
- } else if (value._bsontype === "Long" || value._bsontype === "Double" || value._bsontype === "Timestamp") {
35716
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
35717
- } else if (value._bsontype === "Decimal128") {
35718
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (16 + 1);
35719
- } else if (value._bsontype === "Code") {
35720
- if (value.scope != null && Object.keys(value.scope).length > 0) {
35721
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + 4 + ByteUtils.utf8ByteLength(value.code.toString()) + 1 + internalCalculateObjectSize(value.scope, serializeFunctions, ignoreUndefined);
35722
- } else {
35723
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + ByteUtils.utf8ByteLength(value.code.toString()) + 1;
35724
- }
35725
- } else if (value._bsontype === "Binary") {
35726
- const binary = value;
35727
- if (binary.sub_type === Binary.SUBTYPE_BYTE_ARRAY) {
35728
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1 + 4);
35729
- } else {
35730
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (binary.position + 1 + 4 + 1);
35731
- }
35732
- } else if (value._bsontype === "Symbol") {
35733
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + ByteUtils.utf8ByteLength(value.value) + 4 + 1 + 1;
35734
- } else if (value._bsontype === "DBRef") {
35735
- const ordered_values = Object.assign({
35736
- $ref: value.collection,
35737
- $id: value.oid
35738
- }, value.fields);
35739
- if (value.db != null) {
35740
- ordered_values["$db"] = value.db;
35741
- }
35742
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + internalCalculateObjectSize(ordered_values, serializeFunctions, ignoreUndefined);
35743
- } else if (value instanceof RegExp || isRegExp(value)) {
35744
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + ByteUtils.utf8ByteLength(value.source) + 1 + (value.global ? 1 : 0) + (value.ignoreCase ? 1 : 0) + (value.multiline ? 1 : 0) + 1;
35745
- } else if (value._bsontype === "BSONRegExp") {
35746
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + ByteUtils.utf8ByteLength(value.pattern) + 1 + ByteUtils.utf8ByteLength(value.options) + 1;
35747
- } else {
35748
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + internalCalculateObjectSize(value, serializeFunctions, ignoreUndefined) + 1;
35749
- }
35750
- case "function":
35751
- if (serializeFunctions) {
35752
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + 1 + 4 + ByteUtils.utf8ByteLength(value.toString()) + 1;
35753
- }
35754
- return 0;
35755
- case "bigint":
35756
- return (name != null ? ByteUtils.utf8ByteLength(name) + 1 : 0) + (8 + 1);
35757
- case "symbol":
35758
- return 0;
35759
- default:
35760
- throw new BSONError(`Unrecognized JS type: ${typeof value}`);
35761
- }
35762
- }
35763
- function alphabetize(str) {
35764
- return str.split("").sort().join("");
35765
- }
35766
- var BSONRegExp = class extends BSONValue {
35767
- get _bsontype() {
35768
- return "BSONRegExp";
35769
- }
35770
- constructor(pattern, options) {
35771
- super();
35772
- this.pattern = pattern;
35773
- this.options = alphabetize(options ?? "");
35774
- if (this.pattern.indexOf("\0") !== -1) {
35775
- throw new BSONError(`BSON Regex patterns cannot contain null bytes, found: ${JSON.stringify(this.pattern)}`);
35776
- }
35777
- if (this.options.indexOf("\0") !== -1) {
35778
- throw new BSONError(`BSON Regex options cannot contain null bytes, found: ${JSON.stringify(this.options)}`);
35779
- }
35780
- for (let i = 0; i < this.options.length; i++) {
35781
- if (!(this.options[i] === "i" || this.options[i] === "m" || this.options[i] === "x" || this.options[i] === "l" || this.options[i] === "s" || this.options[i] === "u")) {
35782
- throw new BSONError(`The regular expression option [${this.options[i]}] is not supported`);
35783
- }
35784
- }
35785
- }
35786
- static parseOptions(options) {
35787
- return options ? options.split("").sort().join("") : "";
35788
- }
35789
- toExtendedJSON(options) {
35790
- options = options || {};
35791
- if (options.legacy) {
35792
- return { $regex: this.pattern, $options: this.options };
35793
- }
35794
- return { $regularExpression: { pattern: this.pattern, options: this.options } };
35795
- }
35796
- static fromExtendedJSON(doc) {
35797
- if ("$regex" in doc) {
35798
- if (typeof doc.$regex !== "string") {
35799
- if (doc.$regex._bsontype === "BSONRegExp") {
35800
- return doc;
35801
- }
35802
- } else {
35803
- return new BSONRegExp(doc.$regex, BSONRegExp.parseOptions(doc.$options));
35804
- }
35805
- }
35806
- if ("$regularExpression" in doc) {
35807
- return new BSONRegExp(doc.$regularExpression.pattern, BSONRegExp.parseOptions(doc.$regularExpression.options));
35808
- }
35809
- throw new BSONError(`Unexpected BSONRegExp EJSON object form: ${JSON.stringify(doc)}`);
35810
- }
35811
- inspect(depth, options, inspect) {
35812
- const stylize = getStylizeFunction(options) ?? ((v) => v);
35813
- inspect ?? (inspect = defaultInspect);
35814
- const pattern = stylize(inspect(this.pattern), "regexp");
35815
- const flags = stylize(inspect(this.options), "regexp");
35816
- return `new BSONRegExp(${pattern}, ${flags})`;
35817
- }
35818
- };
35819
- var BSONSymbol = class extends BSONValue {
35820
- get _bsontype() {
35821
- return "BSONSymbol";
35822
- }
35823
- constructor(value) {
35824
- super();
35825
- this.value = value;
35826
- }
35827
- valueOf() {
35828
- return this.value;
35829
- }
35830
- toString() {
35831
- return this.value;
35832
- }
35833
- toJSON() {
35834
- return this.value;
35835
- }
35836
- toExtendedJSON() {
35837
- return { $symbol: this.value };
35838
- }
35839
- static fromExtendedJSON(doc) {
35840
- return new BSONSymbol(doc.$symbol);
35841
- }
35842
- inspect(depth, options, inspect) {
35843
- inspect ?? (inspect = defaultInspect);
35844
- return `new BSONSymbol(${inspect(this.value, options)})`;
35845
- }
35846
- };
35847
- var LongWithoutOverridesClass = Long;
35848
- var Timestamp = class extends LongWithoutOverridesClass {
35849
- get _bsontype() {
35850
- return "Timestamp";
35851
- }
35852
- get i() {
35853
- return this.low >>> 0;
35854
- }
35855
- get t() {
35856
- return this.high >>> 0;
35857
- }
35858
- constructor(low) {
35859
- if (low == null) {
35860
- super(0, 0, true);
35861
- } else if (typeof low === "bigint") {
35862
- super(low, true);
35863
- } else if (Long.isLong(low)) {
35864
- super(low.low, low.high, true);
35865
- } else if (typeof low === "object" && "t" in low && "i" in low) {
35866
- if (typeof low.t !== "number" && (typeof low.t !== "object" || low.t._bsontype !== "Int32")) {
35867
- throw new BSONError("Timestamp constructed from { t, i } must provide t as a number");
35868
- }
35869
- if (typeof low.i !== "number" && (typeof low.i !== "object" || low.i._bsontype !== "Int32")) {
35870
- throw new BSONError("Timestamp constructed from { t, i } must provide i as a number");
35871
- }
35872
- const t = Number(low.t);
35873
- const i = Number(low.i);
35874
- if (t < 0 || Number.isNaN(t)) {
35875
- throw new BSONError("Timestamp constructed from { t, i } must provide a positive t");
35876
- }
35877
- if (i < 0 || Number.isNaN(i)) {
35878
- throw new BSONError("Timestamp constructed from { t, i } must provide a positive i");
35879
- }
35880
- if (t > 4294967295) {
35881
- throw new BSONError("Timestamp constructed from { t, i } must provide t equal or less than uint32 max");
35882
- }
35883
- if (i > 4294967295) {
35884
- throw new BSONError("Timestamp constructed from { t, i } must provide i equal or less than uint32 max");
35885
- }
35886
- super(i, t, true);
35887
- } else {
35888
- throw new BSONError("A Timestamp can only be constructed with: bigint, Long, or { t: number; i: number }");
35889
- }
35890
- }
35891
- toJSON() {
35892
- return {
35893
- $timestamp: this.toString()
35894
- };
35895
- }
35896
- static fromInt(value) {
35897
- return new Timestamp(Long.fromInt(value, true));
35898
- }
35899
- static fromNumber(value) {
35900
- return new Timestamp(Long.fromNumber(value, true));
35901
- }
35902
- static fromBits(lowBits, highBits) {
35903
- return new Timestamp({ i: lowBits, t: highBits });
35904
- }
35905
- static fromString(str, optRadix) {
35906
- return new Timestamp(Long.fromString(str, true, optRadix));
35907
- }
35908
- toExtendedJSON() {
35909
- return { $timestamp: { t: this.t, i: this.i } };
35910
- }
35911
- static fromExtendedJSON(doc) {
35912
- const i = Long.isLong(doc.$timestamp.i) ? doc.$timestamp.i.getLowBitsUnsigned() : doc.$timestamp.i;
35913
- const t = Long.isLong(doc.$timestamp.t) ? doc.$timestamp.t.getLowBitsUnsigned() : doc.$timestamp.t;
35914
- return new Timestamp({ t, i });
35915
- }
35916
- inspect(depth, options, inspect) {
35917
- inspect ?? (inspect = defaultInspect);
35918
- const t = inspect(this.t, options);
35919
- const i = inspect(this.i, options);
35920
- return `new Timestamp({ t: ${t}, i: ${i} })`;
35921
- }
35922
- };
35923
- Timestamp.MAX_VALUE = Long.MAX_UNSIGNED_VALUE;
35924
- var JS_INT_MAX_LONG = Long.fromNumber(JS_INT_MAX);
35925
- var JS_INT_MIN_LONG = Long.fromNumber(JS_INT_MIN);
35926
- function isBSONType(value) {
35927
- return value != null && typeof value === "object" && "_bsontype" in value && typeof value._bsontype === "string";
35928
- }
35929
- var keysToCodecs = {
35930
- $oid: ObjectId13,
35931
- $binary: Binary,
35932
- $uuid: Binary,
35933
- $symbol: BSONSymbol,
35934
- $numberInt: Int32,
35935
- $numberDecimal: Decimal128,
35936
- $numberDouble: Double,
35937
- $numberLong: Long,
35938
- $minKey: MinKey,
35939
- $maxKey: MaxKey,
35940
- $regex: BSONRegExp,
35941
- $regularExpression: BSONRegExp,
35942
- $timestamp: Timestamp
35943
- };
35944
- function deserializeValue(value, options = {}) {
35945
- if (typeof value === "number") {
35946
- const in32BitRange = value <= BSON_INT32_MAX && value >= BSON_INT32_MIN;
35947
- const in64BitRange = value <= BSON_INT64_MAX && value >= BSON_INT64_MIN;
35948
- if (options.relaxed || options.legacy) {
35949
- return value;
35950
- }
35951
- if (Number.isInteger(value) && !Object.is(value, -0)) {
35952
- if (in32BitRange) {
35953
- return new Int32(value);
35954
- }
35955
- if (in64BitRange) {
35956
- if (options.useBigInt64) {
35957
- return BigInt(value);
35958
- }
35959
- return Long.fromNumber(value);
35960
- }
35961
- }
35962
- return new Double(value);
35963
- }
35964
- if (value == null || typeof value !== "object")
35965
- return value;
35966
- if (value.$undefined)
35967
- return null;
35968
- const keys2 = Object.keys(value).filter((k) => k.startsWith("$") && value[k] != null);
35969
- for (let i = 0; i < keys2.length; i++) {
35970
- const c = keysToCodecs[keys2[i]];
35971
- if (c)
35972
- return c.fromExtendedJSON(value, options);
35973
- }
35974
- if (value.$date != null) {
35975
- const d = value.$date;
35976
- const date = /* @__PURE__ */ new Date();
35977
- if (options.legacy) {
35978
- if (typeof d === "number")
35979
- date.setTime(d);
35980
- else if (typeof d === "string")
35981
- date.setTime(Date.parse(d));
35982
- else if (typeof d === "bigint")
35983
- date.setTime(Number(d));
35984
- else
35985
- throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
35986
- } else {
35987
- if (typeof d === "string")
35988
- date.setTime(Date.parse(d));
35989
- else if (Long.isLong(d))
35990
- date.setTime(d.toNumber());
35991
- else if (typeof d === "number" && options.relaxed)
35992
- date.setTime(d);
35993
- else if (typeof d === "bigint")
35994
- date.setTime(Number(d));
35995
- else
35996
- throw new BSONRuntimeError(`Unrecognized type for EJSON date: ${typeof d}`);
35997
- }
35998
- return date;
35999
- }
36000
- if (value.$code != null) {
36001
- const copy = Object.assign({}, value);
36002
- if (value.$scope) {
36003
- copy.$scope = deserializeValue(value.$scope);
36004
- }
36005
- return Code.fromExtendedJSON(value);
36006
- }
36007
- if (isDBRefLike(value) || value.$dbPointer) {
36008
- const v = value.$ref ? value : value.$dbPointer;
36009
- if (v instanceof DBRef)
36010
- return v;
36011
- const dollarKeys = Object.keys(v).filter((k) => k.startsWith("$"));
36012
- let valid = true;
36013
- dollarKeys.forEach((k) => {
36014
- if (["$ref", "$id", "$db"].indexOf(k) === -1)
36015
- valid = false;
36016
- });
36017
- if (valid)
36018
- return DBRef.fromExtendedJSON(v);
36019
- }
36020
- return value;
36021
- }
36022
- function serializeArray(array, options) {
36023
- return array.map((v, index) => {
36024
- options.seenObjects.push({ propertyName: `index ${index}`, obj: null });
36025
- try {
36026
- return serializeValue(v, options);
36027
- } finally {
36028
- options.seenObjects.pop();
36029
- }
36030
- });
36031
- }
36032
- function getISOString(date) {
36033
- const isoStr = date.toISOString();
36034
- return date.getUTCMilliseconds() !== 0 ? isoStr : isoStr.slice(0, -5) + "Z";
36035
- }
36036
- function serializeValue(value, options) {
36037
- if (value instanceof Map || isMap(value)) {
36038
- const obj = /* @__PURE__ */ Object.create(null);
36039
- for (const [k, v] of value) {
36040
- if (typeof k !== "string") {
36041
- throw new BSONError("Can only serialize maps with string keys");
36042
- }
36043
- obj[k] = v;
36044
- }
36045
- return serializeValue(obj, options);
36046
- }
36047
- if ((typeof value === "object" || typeof value === "function") && value !== null) {
36048
- const index = options.seenObjects.findIndex((entry) => entry.obj === value);
36049
- if (index !== -1) {
36050
- const props = options.seenObjects.map((entry) => entry.propertyName);
36051
- const leadingPart = props.slice(0, index).map((prop) => `${prop} -> `).join("");
36052
- const alreadySeen = props[index];
36053
- const circularPart = " -> " + props.slice(index + 1, props.length - 1).map((prop) => `${prop} -> `).join("");
36054
- const current = props[props.length - 1];
36055
- const leadingSpace = " ".repeat(leadingPart.length + alreadySeen.length / 2);
36056
- const dashes = "-".repeat(circularPart.length + (alreadySeen.length + current.length) / 2 - 1);
36057
- throw new BSONError(`Converting circular structure to EJSON:
36058
- ${leadingPart}${alreadySeen}${circularPart}${current}
36059
- ${leadingSpace}\\${dashes}/`);
36060
- }
36061
- options.seenObjects[options.seenObjects.length - 1].obj = value;
36062
- }
36063
- if (Array.isArray(value))
36064
- return serializeArray(value, options);
36065
- if (value === void 0)
36066
- return null;
36067
- if (value instanceof Date || isDate(value)) {
36068
- const dateNum = value.getTime(), inRange = dateNum > -1 && dateNum < 2534023188e5;
36069
- if (options.legacy) {
36070
- return options.relaxed && inRange ? { $date: value.getTime() } : { $date: getISOString(value) };
36071
- }
36072
- return options.relaxed && inRange ? { $date: getISOString(value) } : { $date: { $numberLong: value.getTime().toString() } };
36073
- }
36074
- if (typeof value === "number" && (!options.relaxed || !isFinite(value))) {
36075
- if (Number.isInteger(value) && !Object.is(value, -0)) {
36076
- if (value >= BSON_INT32_MIN && value <= BSON_INT32_MAX) {
36077
- return { $numberInt: value.toString() };
36078
- }
36079
- if (value >= BSON_INT64_MIN && value <= BSON_INT64_MAX) {
36080
- return { $numberLong: value.toString() };
36081
- }
36082
- }
36083
- return { $numberDouble: Object.is(value, -0) ? "-0.0" : value.toString() };
36084
- }
36085
- if (typeof value === "bigint") {
36086
- if (!options.relaxed) {
36087
- return { $numberLong: BigInt.asIntN(64, value).toString() };
36088
- }
36089
- return Number(BigInt.asIntN(64, value));
36090
- }
36091
- if (value instanceof RegExp || isRegExp(value)) {
36092
- let flags = value.flags;
36093
- if (flags === void 0) {
36094
- const match = value.toString().match(/[gimuy]*$/);
36095
- if (match) {
36096
- flags = match[0];
36097
- }
36098
- }
36099
- const rx = new BSONRegExp(value.source, flags);
36100
- return rx.toExtendedJSON(options);
36101
- }
36102
- if (value != null && typeof value === "object")
36103
- return serializeDocument(value, options);
36104
- return value;
36105
- }
36106
- var BSON_TYPE_MAPPINGS = {
36107
- Binary: (o) => new Binary(o.value(), o.sub_type),
36108
- Code: (o) => new Code(o.code, o.scope),
36109
- DBRef: (o) => new DBRef(o.collection || o.namespace, o.oid, o.db, o.fields),
36110
- Decimal128: (o) => new Decimal128(o.bytes),
36111
- Double: (o) => new Double(o.value),
36112
- Int32: (o) => new Int32(o.value),
36113
- 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_),
36114
- MaxKey: () => new MaxKey(),
36115
- MinKey: () => new MinKey(),
36116
- ObjectId: (o) => new ObjectId13(o),
36117
- BSONRegExp: (o) => new BSONRegExp(o.pattern, o.options),
36118
- BSONSymbol: (o) => new BSONSymbol(o.value),
36119
- Timestamp: (o) => Timestamp.fromBits(o.low, o.high)
36120
- };
36121
- function serializeDocument(doc, options) {
36122
- if (doc == null || typeof doc !== "object")
36123
- throw new BSONError("not an object instance");
36124
- const bsontype = doc._bsontype;
36125
- if (typeof bsontype === "undefined") {
36126
- const _doc = {};
36127
- for (const name of Object.keys(doc)) {
36128
- options.seenObjects.push({ propertyName: name, obj: null });
36129
- try {
36130
- const value = serializeValue(doc[name], options);
36131
- if (name === "__proto__") {
36132
- Object.defineProperty(_doc, name, {
36133
- value,
36134
- writable: true,
36135
- enumerable: true,
36136
- configurable: true
36137
- });
36138
- } else {
36139
- _doc[name] = value;
36140
- }
36141
- } finally {
36142
- options.seenObjects.pop();
36143
- }
36144
- }
36145
- return _doc;
36146
- } else if (doc != null && typeof doc === "object" && typeof doc._bsontype === "string" && doc[BSON_VERSION_SYMBOL] !== BSON_MAJOR_VERSION) {
36147
- throw new BSONVersionError();
36148
- } else if (isBSONType(doc)) {
36149
- let outDoc = doc;
36150
- if (typeof outDoc.toExtendedJSON !== "function") {
36151
- const mapper = BSON_TYPE_MAPPINGS[doc._bsontype];
36152
- if (!mapper) {
36153
- throw new BSONError("Unrecognized or invalid _bsontype: " + doc._bsontype);
36154
- }
36155
- outDoc = mapper(outDoc);
36156
- }
36157
- if (bsontype === "Code" && outDoc.scope) {
36158
- outDoc = new Code(outDoc.code, serializeValue(outDoc.scope, options));
36159
- } else if (bsontype === "DBRef" && outDoc.oid) {
36160
- outDoc = new DBRef(serializeValue(outDoc.collection, options), serializeValue(outDoc.oid, options), serializeValue(outDoc.db, options), serializeValue(outDoc.fields, options));
36161
- }
36162
- return outDoc.toExtendedJSON(options);
36163
- } else {
36164
- throw new BSONError("_bsontype must be a string, but was: " + typeof bsontype);
36165
- }
36166
- }
36167
- function parse(text, options) {
36168
- const ejsonOptions = {
36169
- useBigInt64: options?.useBigInt64 ?? false,
36170
- relaxed: options?.relaxed ?? true,
36171
- legacy: options?.legacy ?? false
36172
- };
36173
- return JSON.parse(text, (key, value) => {
36174
- if (key.indexOf("\0") !== -1) {
36175
- throw new BSONError(`BSON Document field names cannot contain null bytes, found: ${JSON.stringify(key)}`);
36176
- }
36177
- return deserializeValue(value, ejsonOptions);
36178
- });
36179
- }
36180
- function stringify(value, replacer, space, options) {
36181
- if (space != null && typeof space === "object") {
36182
- options = space;
36183
- space = 0;
36184
- }
36185
- if (replacer != null && typeof replacer === "object" && !Array.isArray(replacer)) {
36186
- options = replacer;
36187
- replacer = void 0;
36188
- space = 0;
36189
- }
36190
- const serializeOptions = Object.assign({ relaxed: true, legacy: false }, options, {
36191
- seenObjects: [{ propertyName: "(root)", obj: null }]
36192
- });
36193
- const doc = serializeValue(value, serializeOptions);
36194
- return JSON.stringify(doc, replacer, space);
36195
- }
36196
- function EJSONserialize(value, options) {
36197
- options = options || {};
36198
- return JSON.parse(stringify(value, options));
36199
- }
36200
- function EJSONdeserialize(ejson, options) {
36201
- options = options || {};
36202
- return parse(JSON.stringify(ejson), options);
36203
- }
36204
- var EJSON = /* @__PURE__ */ Object.create(null);
36205
- EJSON.parse = parse;
36206
- EJSON.stringify = stringify;
36207
- EJSON.serialize = EJSONserialize;
36208
- EJSON.deserialize = EJSONdeserialize;
36209
- Object.freeze(EJSON);
36210
- var BSONElementType = {
36211
- double: 1,
36212
- string: 2,
36213
- object: 3,
36214
- array: 4,
36215
- binData: 5,
36216
- undefined: 6,
36217
- objectId: 7,
36218
- bool: 8,
36219
- date: 9,
36220
- null: 10,
36221
- regex: 11,
36222
- dbPointer: 12,
36223
- javascript: 13,
36224
- symbol: 14,
36225
- javascriptWithScope: 15,
36226
- int: 16,
36227
- timestamp: 17,
36228
- long: 18,
36229
- decimal: 19,
36230
- minKey: 255,
36231
- maxKey: 127
36232
- };
36233
- function getSize(source, offset) {
36234
- try {
36235
- return NumberUtils.getNonnegativeInt32LE(source, offset);
36236
- } catch (cause) {
36237
- throw new BSONOffsetError("BSON size cannot be negative", offset, { cause });
36238
- }
36239
- }
36240
- function findNull(bytes, offset) {
36241
- let nullTerminatorOffset = offset;
36242
- for (; bytes[nullTerminatorOffset] !== 0; nullTerminatorOffset++)
36243
- ;
36244
- if (nullTerminatorOffset === bytes.length - 1) {
36245
- throw new BSONOffsetError("Null terminator not found", offset);
36246
- }
36247
- return nullTerminatorOffset;
36248
- }
36249
- function parseToElements(bytes, startOffset = 0) {
36250
- startOffset ?? (startOffset = 0);
36251
- if (bytes.length < 5) {
36252
- throw new BSONOffsetError(`Input must be at least 5 bytes, got ${bytes.length} bytes`, startOffset);
36253
- }
36254
- const documentSize = getSize(bytes, startOffset);
36255
- if (documentSize > bytes.length - startOffset) {
36256
- throw new BSONOffsetError(`Parsed documentSize (${documentSize} bytes) does not match input length (${bytes.length} bytes)`, startOffset);
36257
- }
36258
- if (bytes[startOffset + documentSize - 1] !== 0) {
36259
- throw new BSONOffsetError("BSON documents must end in 0x00", startOffset + documentSize);
36260
- }
36261
- const elements = [];
36262
- let offset = startOffset + 4;
36263
- while (offset <= documentSize + startOffset) {
36264
- const type = bytes[offset];
36265
- offset += 1;
36266
- if (type === 0) {
36267
- if (offset - startOffset !== documentSize) {
36268
- throw new BSONOffsetError(`Invalid 0x00 type byte`, offset);
36269
- }
36270
- break;
36271
- }
36272
- const nameOffset = offset;
36273
- const nameLength = findNull(bytes, offset) - nameOffset;
36274
- offset += nameLength + 1;
36275
- let length;
36276
- if (type === BSONElementType.double || type === BSONElementType.long || type === BSONElementType.date || type === BSONElementType.timestamp) {
36277
- length = 8;
36278
- } else if (type === BSONElementType.int) {
36279
- length = 4;
36280
- } else if (type === BSONElementType.objectId) {
36281
- length = 12;
36282
- } else if (type === BSONElementType.decimal) {
36283
- length = 16;
36284
- } else if (type === BSONElementType.bool) {
36285
- length = 1;
36286
- } else if (type === BSONElementType.null || type === BSONElementType.undefined || type === BSONElementType.maxKey || type === BSONElementType.minKey) {
36287
- length = 0;
36288
- } else if (type === BSONElementType.regex) {
36289
- length = findNull(bytes, findNull(bytes, offset) + 1) + 1 - offset;
36290
- } else if (type === BSONElementType.object || type === BSONElementType.array || type === BSONElementType.javascriptWithScope) {
36291
- length = getSize(bytes, offset);
36292
- } else if (type === BSONElementType.string || type === BSONElementType.binData || type === BSONElementType.dbPointer || type === BSONElementType.javascript || type === BSONElementType.symbol) {
36293
- length = getSize(bytes, offset) + 4;
36294
- if (type === BSONElementType.binData) {
36295
- length += 1;
36296
- }
36297
- if (type === BSONElementType.dbPointer) {
36298
- length += 12;
36299
- }
36300
- } else {
36301
- throw new BSONOffsetError(`Invalid 0x${type.toString(16).padStart(2, "0")} type byte`, offset);
36302
- }
36303
- if (length > documentSize) {
36304
- throw new BSONOffsetError("value reports length larger than document", offset);
36305
- }
36306
- elements.push([type, nameOffset, nameLength, offset, length]);
36307
- offset += length;
36308
- }
36309
- return elements;
36310
- }
36311
- var onDemand = /* @__PURE__ */ Object.create(null);
36312
- onDemand.parseToElements = parseToElements;
36313
- onDemand.ByteUtils = ByteUtils;
36314
- onDemand.NumberUtils = NumberUtils;
36315
- Object.freeze(onDemand);
36316
- var MAXSIZE = 1024 * 1024 * 17;
36317
- var buffer = ByteUtils.allocate(MAXSIZE);
36318
- function calculateObjectSize(object, options = {}) {
36319
- options = options || {};
36320
- const serializeFunctions = typeof options.serializeFunctions === "boolean" ? options.serializeFunctions : false;
36321
- const ignoreUndefined = typeof options.ignoreUndefined === "boolean" ? options.ignoreUndefined : true;
36322
- return internalCalculateObjectSize(object, serializeFunctions, ignoreUndefined);
36323
- }
36324
-
36325
- // src/resources/school/school.service.ts
33230
+ import * as fs from "fs";
36326
33231
  function useSchoolService() {
36327
33232
  const {
36328
33233
  add: addSchool,
36329
33234
  getPendingByCreatedBy,
36330
33235
  updateStatusById,
36331
- getById
33236
+ getById,
33237
+ delCachedData: delCachedSchoolData
36332
33238
  } = useSchoolRepo();
36333
- const { addRole } = useRoleRepo2();
33239
+ const { addRole, delCachedData: delCachedRoleData } = useRoleRepo2();
36334
33240
  const { getUserById } = useUserRepo();
36335
33241
  const { add: addMember } = useMemberRepo();
36336
33242
  async function register(value) {
@@ -36468,27 +33374,21 @@ function useSchoolService() {
36468
33374
  await session.endSession();
36469
33375
  }
36470
33376
  }
36471
- async function addBulk(file, region, division) {
36472
- const MAX_SIZE = 16 * 1024 * 1024;
36473
- if (file.size > MAX_SIZE) {
36474
- throw new BadRequestError19(
36475
- "File size exceeds 16MB limit. Please use a smaller file to ensure transaction compatibility."
36476
- );
33377
+ async function addBulk(file, payload) {
33378
+ const isCSV = file.mimetype.includes("csv") || file.originalname.endsWith(".csv");
33379
+ const isExcel = file.mimetype.includes("sheet") || file.originalname.endsWith(".xlsx") || file.originalname.endsWith(".xls");
33380
+ if (!isCSV && !isExcel) {
33381
+ throw new BadRequestError19("Only CSV and Excel files are supported");
36477
33382
  }
36478
- let schools = [];
36479
- const validatedSchools = [];
36480
- const totalSize = validatedSchools.reduce(
36481
- (sum, school) => sum + calculateObjectSize(school),
36482
- 0
36483
- );
33383
+ let rawData = [];
36484
33384
  try {
36485
- if (file.mimetype.includes("sheet") || file.originalname.endsWith(".xlsx") || file.originalname.endsWith(".xls")) {
36486
- const workbook = readSync(file.buffer);
36487
- const sheetName = workbook.SheetNames[0];
36488
- const worksheet = workbook.Sheets[sheetName];
36489
- schools = utils.sheet_to_json(worksheet);
36490
- } else if (file.mimetype.includes("csv") || file.originalname.endsWith(".csv")) {
36491
- const csvText = file.buffer.toString("utf8");
33385
+ if (isExcel) {
33386
+ const fileBuffer = await fs.promises.readFile(file.path);
33387
+ const workbook = readSync(fileBuffer);
33388
+ const worksheet = workbook.Sheets[workbook.SheetNames[0]];
33389
+ rawData = utils.sheet_to_json(worksheet);
33390
+ } else {
33391
+ const csvText = await fs.promises.readFile(file.path, "utf8");
36492
33392
  const parseResult = Papa.parse(csvText, {
36493
33393
  header: true,
36494
33394
  skipEmptyLines: true,
@@ -36499,146 +33399,136 @@ function useSchoolService() {
36499
33399
  `CSV parsing error: ${parseResult.errors[0].message}`
36500
33400
  );
36501
33401
  }
36502
- schools = parseResult.data;
36503
- } else {
36504
- throw new BadRequestError19(
36505
- "Unsupported file type. Please upload an Excel (.xlsx, .xls) or CSV (.csv) file."
36506
- );
33402
+ rawData = parseResult.data;
36507
33403
  }
36508
- if (!schools || schools.length === 0) {
36509
- throw new BadRequestError19("No data found in the uploaded file.");
36510
- }
36511
- const errors = [];
36512
- for (let i = 0; i < schools.length; i++) {
36513
- const schoolData = schools[i];
36514
- const rowNumber = i + 1;
36515
- try {
36516
- const schoolName = schoolData.schoolName || schoolData.name || "";
36517
- const schoolId = schoolData.schoolId || schoolData.id || "";
36518
- const district = schoolData.district || "";
36519
- if (!schoolName.trim()) {
36520
- errors.push(`Row ${rowNumber}: School name is required`);
36521
- continue;
36522
- }
36523
- if (!schoolId.trim()) {
36524
- errors.push(`Row ${rowNumber}: School ID is required`);
36525
- continue;
36526
- }
36527
- if (!district.trim()) {
36528
- errors.push(`Row ${rowNumber}: District is required`);
36529
- continue;
36530
- }
36531
- const school = {
36532
- id: schoolId.trim(),
36533
- name: schoolName.trim(),
36534
- street: district.trim(),
36535
- // Use district as street
36536
- barangay: "",
36537
- city: district.trim(),
36538
- // Use district as city
36539
- province: "",
36540
- // Will need to be set based on region/division
36541
- postalCode: "",
36542
- principalName: "",
36543
- email: "",
36544
- contactNumber: "",
36545
- region,
36546
- regionName: "",
36547
- // Will be populated from region lookup
36548
- division,
36549
- divisionName: "",
36550
- // Will be populated from division lookup
36551
- status: "active"
36552
- };
36553
- const { error } = schemaSchool.validate(school);
36554
- if (error) {
36555
- errors.push(`Row ${rowNumber}: ${error.message}`);
36556
- continue;
36557
- }
36558
- validatedSchools.push(school);
36559
- } catch (error) {
36560
- errors.push(
36561
- `Row ${rowNumber}: ${error.message || "Invalid data format"}`
36562
- );
36563
- }
33404
+ } catch (error) {
33405
+ throw new BadRequestError19(`File parsing error: ${error.message}`);
33406
+ }
33407
+ if (!rawData.length) {
33408
+ throw new BadRequestError19("No data found in file");
33409
+ }
33410
+ const schools = [];
33411
+ const errors = [];
33412
+ for (let i = 0; i < rawData.length; i++) {
33413
+ const row = rawData[i];
33414
+ const rowNum = i + 1;
33415
+ const schoolId = (row.schoolId || row.id || "").toString().trim();
33416
+ const name = (row.name || "").toString().trim();
33417
+ const province = (row.province || "").toString().trim();
33418
+ const cityMunicipality = (row.cityMunicipality || "").toString().trim();
33419
+ if (!schoolId) {
33420
+ errors.push(`Row ${rowNum}: schoolId is required`);
33421
+ continue;
36564
33422
  }
36565
- if (errors.length > 0) {
36566
- throw new BadRequestError19(
36567
- `Validation errors found:
36568
- ${errors.slice(0, 10).join("\n")}${errors.length > 10 ? `
36569
- ... and ${errors.length - 10} more errors` : ""}`
36570
- );
33423
+ if (!name) {
33424
+ errors.push(`Row ${rowNum}: name is required`);
33425
+ continue;
36571
33426
  }
36572
- if (validatedSchools.length === 0) {
36573
- throw new BadRequestError19(
36574
- "No valid school records found after validation."
36575
- );
33427
+ if (!province) {
33428
+ errors.push(`Row ${rowNum}: province is required`);
33429
+ continue;
36576
33430
  }
36577
- if (totalSize > MAX_SIZE) {
36578
- throw new BadRequestError19(
36579
- `Data payload (${Math.round(
36580
- totalSize / 1024 / 1024
36581
- )}MB) exceeds MongoDB transaction limit of 16MB. Please reduce the number of records or split into smaller files.`
36582
- );
33431
+ if (!cityMunicipality) {
33432
+ errors.push(`Row ${rowNum}: city/municipality is required`);
33433
+ continue;
36583
33434
  }
36584
- } catch (error) {
36585
- if (error instanceof BadRequestError19) {
36586
- throw error;
33435
+ const school = {
33436
+ id: schoolId,
33437
+ name,
33438
+ region: payload.region,
33439
+ regionName: payload.regionName,
33440
+ division: payload.division,
33441
+ divisionName: payload.divisionName,
33442
+ province,
33443
+ cityMunicipality,
33444
+ status: "active"
33445
+ };
33446
+ const { error } = schemaSchool.validate(school);
33447
+ if (error) {
33448
+ errors.push(`Row ${rowNum}: ${error.message}`);
33449
+ continue;
36587
33450
  }
36588
- throw new BadRequestError19(`File processing error: ${error.message}`);
33451
+ schools.push(school);
36589
33452
  }
36590
- const session = useAtlas9.getClient()?.startSession();
36591
- if (!session) {
36592
- throw new Error("Unable to start session for bulk school upload.");
33453
+ if (errors.length > 0) {
33454
+ throw new BadRequestError19(
33455
+ `Validation errors:
33456
+ ${errors.slice(0, 5).join("\n")}${errors.length > 5 ? `
33457
+ ...and ${errors.length - 5} more` : ""}`
33458
+ );
36593
33459
  }
36594
- try {
33460
+ const results = {
33461
+ successful: 0,
33462
+ failed: 0,
33463
+ skipped: 0,
33464
+ errors: []
33465
+ };
33466
+ const { getByName: getPSGCByName } = usePSGCRepo();
33467
+ for (let i = 0; i < schools.length; i++) {
33468
+ const session = useAtlas9.getClient()?.startSession();
33469
+ if (!session) {
33470
+ throw new Error("Unable to start MongoDB session");
33471
+ }
36595
33472
  session.startTransaction();
36596
- const results = {
36597
- successful: 0,
36598
- failed: 0,
36599
- errors: []
36600
- };
36601
- for (const school of validatedSchools) {
36602
- try {
36603
- const schoolId = await addSchool(school, session);
36604
- await addRole(
36605
- {
36606
- id: schoolId.toString(),
36607
- type: "basic-edu-school",
36608
- name: "Admin",
36609
- permissions: ["*"],
36610
- status: "active",
36611
- default: true
36612
- },
36613
- session
33473
+ const school = schools[i];
33474
+ try {
33475
+ const provincePSGC = await getPSGCByName({
33476
+ name: school.province ?? "",
33477
+ type: "Prov"
33478
+ });
33479
+ if (!provincePSGC) {
33480
+ throw new BadRequestError19(
33481
+ `Province '${school.province}' not found in PSGC data.`
36614
33482
  );
36615
- results.successful++;
36616
- } catch (error) {
33483
+ }
33484
+ const cityMunPSGC = await getPSGCByName({
33485
+ name: school.cityMunicipality ?? "",
33486
+ cityMunicipality: true,
33487
+ code: provincePSGC.code
33488
+ });
33489
+ if (!cityMunPSGC) {
33490
+ throw new BadRequestError19(
33491
+ `City/Municipality '${school.cityMunicipality}' not found in PSGC data.`
33492
+ );
33493
+ }
33494
+ school.provincePSGC = provincePSGC.code ?? 0;
33495
+ school.cityMunicipalityPSGC = cityMunPSGC.code ?? 0;
33496
+ const schoolId = await addSchool(school, session, false);
33497
+ await addRole(
33498
+ {
33499
+ id: schoolId.toString(),
33500
+ type: "basic-edu-school",
33501
+ name: "Admin",
33502
+ permissions: ["*"],
33503
+ status: "active",
33504
+ default: true
33505
+ },
33506
+ session,
33507
+ false
33508
+ );
33509
+ results.successful++;
33510
+ await session.commitTransaction();
33511
+ } catch (error) {
33512
+ if (String(error.message).toLowerCase().includes("duplicate")) {
33513
+ results.skipped = (results.skipped || 0) + 1;
33514
+ } else {
36617
33515
  results.failed++;
36618
- results.errors.push(`School "${school.name}": ${error.message}`);
33516
+ results.errors.push(`${school.name}: ${error.message}`);
36619
33517
  }
33518
+ await session.abortTransaction();
33519
+ } finally {
33520
+ await session.endSession();
36620
33521
  }
36621
- await session.commitTransaction();
36622
- return {
36623
- message: `Bulk upload completed. ${results.successful} schools added successfully.`,
36624
- details: {
36625
- successful: results.successful,
36626
- failed: results.failed,
36627
- total: validatedSchools.length,
36628
- totalSizeMB: Math.round(totalSize / 1024 / 1024 * 100) / 100,
36629
- errors: results.errors
36630
- }
36631
- };
36632
- } catch (error) {
36633
- logger14.log({
36634
- level: "error",
36635
- message: `Error in bulk school upload: ${error.message}`
36636
- });
36637
- await session.abortTransaction();
36638
- throw error;
36639
- } finally {
36640
- await session.endSession();
36641
33522
  }
33523
+ delCachedSchoolData();
33524
+ delCachedRoleData();
33525
+ return {
33526
+ message: `Processed ${schools.length} schools: ${results.successful} successful, ${results.failed} failed`,
33527
+ successful: results.successful,
33528
+ failed: results.failed,
33529
+ errors: results.errors,
33530
+ skipped: results.skipped
33531
+ };
36642
33532
  }
36643
33533
  return {
36644
33534
  register,
@@ -36655,7 +33545,10 @@ function useSchoolController() {
36655
33545
  const {
36656
33546
  getAll: _getAll,
36657
33547
  getPendingByCreatedBy: _getPendingByCreatedBy,
36658
- updateStatusById: _updateStatusById
33548
+ updateStatusById: _updateStatusById,
33549
+ updateFieldById: _updateFieldById,
33550
+ updateById: _updateById,
33551
+ deleteById: _deleteById
36659
33552
  } = useSchoolRepo();
36660
33553
  const {
36661
33554
  add: _addSchool,
@@ -36794,21 +33687,35 @@ function useSchoolController() {
36794
33687
  }
36795
33688
  async function addBulk(req, res, next) {
36796
33689
  if (!req.file) {
36797
- res.status(400).send("File is required!");
33690
+ res.status(400).json({
33691
+ error: "File is required. Please upload a CSV or Excel file (.csv, .xlsx, .xls)"
33692
+ });
36798
33693
  return;
36799
33694
  }
36800
- const { region, division } = req.body;
33695
+ const { region, regionName, division, divisionName } = req.body;
36801
33696
  const validation = Joi12.object({
36802
33697
  region: Joi12.string().hex().required(),
36803
- division: Joi12.string().hex().required()
33698
+ regionName: Joi12.string().min(1).required(),
33699
+ division: Joi12.string().hex().required(),
33700
+ divisionName: Joi12.string().min(1).required()
33701
+ });
33702
+ const { error } = validation.validate({
33703
+ region,
33704
+ regionName,
33705
+ division,
33706
+ divisionName
36804
33707
  });
36805
- const { error } = validation.validate({ region, division });
36806
33708
  if (error) {
36807
33709
  next(new BadRequestError20(`Validation error: ${error.message}`));
36808
33710
  return;
36809
33711
  }
36810
33712
  try {
36811
- const result = await _addBulk(req.file, region, division);
33713
+ const result = await _addBulk(req.file, {
33714
+ region,
33715
+ regionName,
33716
+ division,
33717
+ divisionName
33718
+ });
36812
33719
  res.status(201).json(result);
36813
33720
  return;
36814
33721
  } catch (error2) {
@@ -36816,6 +33723,69 @@ function useSchoolController() {
36816
33723
  return;
36817
33724
  }
36818
33725
  }
33726
+ async function updateFieldById(req, res, next) {
33727
+ const _id = req.params.id;
33728
+ const { field, value } = req.body;
33729
+ const validation = Joi12.object({
33730
+ _id: Joi12.string().hex().required(),
33731
+ field: Joi12.string().valid("name", "director", "directorName").required(),
33732
+ value: Joi12.string().required()
33733
+ });
33734
+ const { error } = validation.validate({ _id, field, value });
33735
+ if (error) {
33736
+ next(new BadRequestError20(error.message));
33737
+ return;
33738
+ }
33739
+ try {
33740
+ const message = await _updateFieldById({ _id, field, value });
33741
+ res.json({ message });
33742
+ return;
33743
+ } catch (error2) {
33744
+ next(error2);
33745
+ }
33746
+ }
33747
+ async function updateById(req, res, next) {
33748
+ const id = req.params.id;
33749
+ const payload = req.body;
33750
+ const validation = Joi12.object({
33751
+ id: Joi12.string().hex().required()
33752
+ });
33753
+ const { error: idError } = validation.validate({ id });
33754
+ if (idError) {
33755
+ next(new BadRequestError20(idError.message));
33756
+ return;
33757
+ }
33758
+ const { error } = schemaSchoolUpdate.validate(payload);
33759
+ if (error) {
33760
+ next(new BadRequestError20(error.message));
33761
+ return;
33762
+ }
33763
+ try {
33764
+ const message = await _updateById(id, payload);
33765
+ res.json({ message });
33766
+ return;
33767
+ } catch (error2) {
33768
+ next(error2);
33769
+ }
33770
+ }
33771
+ async function deleteById(req, res, next) {
33772
+ const _id = req.params.id;
33773
+ const validation = Joi12.object({
33774
+ _id: Joi12.string().hex().required()
33775
+ });
33776
+ const { error } = validation.validate({ _id });
33777
+ if (error) {
33778
+ next(new BadRequestError20(error.message));
33779
+ return;
33780
+ }
33781
+ try {
33782
+ const message = await _deleteById(_id);
33783
+ res.json({ message });
33784
+ return;
33785
+ } catch (error2) {
33786
+ next(error2);
33787
+ }
33788
+ }
36819
33789
  return {
36820
33790
  add,
36821
33791
  getAll,
@@ -36823,14 +33793,17 @@ function useSchoolController() {
36823
33793
  updateStatusById,
36824
33794
  registerSchool,
36825
33795
  approveSchool,
36826
- addBulk
33796
+ addBulk,
33797
+ updateFieldById,
33798
+ updateById,
33799
+ deleteById
36827
33800
  };
36828
33801
  }
36829
33802
 
36830
33803
  // src/resources/asset/asset.model.ts
36831
33804
  import { BadRequestError as BadRequestError21 } from "@eeplatform/nodejs-utils";
36832
33805
  import Joi13 from "joi";
36833
- import { ObjectId as ObjectId14 } from "mongodb";
33806
+ import { ObjectId as ObjectId13 } from "mongodb";
36834
33807
  var schemaAsset = Joi13.object({
36835
33808
  _id: Joi13.string().hex().optional(),
36836
33809
  school: Joi13.string().hex().required(),
@@ -36880,13 +33853,13 @@ function MAsset(value) {
36880
33853
  }
36881
33854
  if (value._id && typeof value._id === "string") {
36882
33855
  try {
36883
- value._id = new ObjectId14();
33856
+ value._id = new ObjectId13();
36884
33857
  } catch (error2) {
36885
33858
  throw new BadRequestError21("Invalid ID.");
36886
33859
  }
36887
33860
  }
36888
33861
  try {
36889
- value.school = new ObjectId14(value.school);
33862
+ value.school = new ObjectId13(value.school);
36890
33863
  } catch (error2) {
36891
33864
  throw new BadRequestError21("Invalid school ID.");
36892
33865
  }
@@ -36894,7 +33867,7 @@ function MAsset(value) {
36894
33867
  value.updatedAt = value.updatedAt ? new Date(value.updatedAt) : "";
36895
33868
  value.deletedAt = value.deletedAt ? new Date(value.deletedAt) : "";
36896
33869
  return {
36897
- _id: value._id ?? new ObjectId14(),
33870
+ _id: value._id ?? new ObjectId13(),
36898
33871
  school: value.school,
36899
33872
  asset_type: value.asset_type ?? "supply",
36900
33873
  name: value.name,
@@ -36926,7 +33899,7 @@ import {
36926
33899
  useAtlas as useAtlas10,
36927
33900
  useCache as useCache7
36928
33901
  } from "@eeplatform/nodejs-utils";
36929
- import { ObjectId as ObjectId15 } from "mongodb";
33902
+ import { ObjectId as ObjectId14 } from "mongodb";
36930
33903
  function useAssetRepo() {
36931
33904
  const db = useAtlas10.getDb();
36932
33905
  if (!db) {
@@ -36975,7 +33948,7 @@ function useAssetRepo() {
36975
33948
  throw new BadRequestError22(error.message);
36976
33949
  }
36977
33950
  try {
36978
- _id = new ObjectId15(_id);
33951
+ _id = new ObjectId14(_id);
36979
33952
  } catch (error2) {
36980
33953
  throw new BadRequestError22("Invalid ID.");
36981
33954
  }
@@ -36995,7 +33968,7 @@ function useAssetRepo() {
36995
33968
  }
36996
33969
  async function deleteById(_id) {
36997
33970
  try {
36998
- _id = new ObjectId15(_id);
33971
+ _id = new ObjectId14(_id);
36999
33972
  } catch (error) {
37000
33973
  throw new BadRequestError22("Invalid ID.");
37001
33974
  }
@@ -37012,7 +33985,7 @@ function useAssetRepo() {
37012
33985
  }
37013
33986
  async function getById(_id) {
37014
33987
  try {
37015
- _id = new ObjectId15(_id);
33988
+ _id = new ObjectId14(_id);
37016
33989
  } catch (error) {
37017
33990
  throw new BadRequestError22("Invalid ID.");
37018
33991
  }
@@ -37056,7 +34029,7 @@ function useAssetRepo() {
37056
34029
  } = {}) {
37057
34030
  page = page ? page - 1 : 0;
37058
34031
  try {
37059
- school = new ObjectId15(school);
34032
+ school = new ObjectId14(school);
37060
34033
  } catch (error) {
37061
34034
  throw new BadRequestError22("Invalid school ID.");
37062
34035
  }
@@ -37120,7 +34093,7 @@ function useAssetRepo() {
37120
34093
  }
37121
34094
  async function getCategories(school, asset_type) {
37122
34095
  try {
37123
- school = new ObjectId15(school);
34096
+ school = new ObjectId14(school);
37124
34097
  } catch (error) {
37125
34098
  throw new BadRequestError22("Invalid school ID.");
37126
34099
  }
@@ -37177,7 +34150,7 @@ function useAssetRepo() {
37177
34150
  }
37178
34151
  async function getTypes(school, asset_type) {
37179
34152
  try {
37180
- school = new ObjectId15(school);
34153
+ school = new ObjectId14(school);
37181
34154
  } catch (error) {
37182
34155
  throw new BadRequestError22("Invalid school ID.");
37183
34156
  }
@@ -37237,7 +34210,7 @@ function useAssetRepo() {
37237
34210
  }
37238
34211
  async function getUnitsBySchool(school) {
37239
34212
  try {
37240
- school = new ObjectId15(school);
34213
+ school = new ObjectId14(school);
37241
34214
  } catch (error) {
37242
34215
  throw new BadRequestError22("Invalid school ID.");
37243
34216
  }
@@ -37488,7 +34461,7 @@ function useAssetController() {
37488
34461
  // src/resources/stock-card/stock-card.model.ts
37489
34462
  import { BadRequestError as BadRequestError24 } from "@eeplatform/nodejs-utils";
37490
34463
  import Joi15 from "joi";
37491
- import { ObjectId as ObjectId16 } from "mongodb";
34464
+ import { ObjectId as ObjectId15 } from "mongodb";
37492
34465
  var schemaStockCard = Joi15.object({
37493
34466
  _id: Joi15.string().hex().optional().allow("", null),
37494
34467
  school: Joi15.string().hex().required(),
@@ -37515,18 +34488,18 @@ function MStockCard(value) {
37515
34488
  }
37516
34489
  if (value._id && typeof value._id === "string") {
37517
34490
  try {
37518
- value._id = new ObjectId16(value._id);
34491
+ value._id = new ObjectId15(value._id);
37519
34492
  } catch (err) {
37520
34493
  throw new BadRequestError24("Invalid stock card ID.");
37521
34494
  }
37522
34495
  }
37523
34496
  try {
37524
- value.item = new ObjectId16(value.item);
34497
+ value.item = new ObjectId15(value.item);
37525
34498
  } catch (err) {
37526
34499
  throw new BadRequestError24("Invalid item ID.");
37527
34500
  }
37528
34501
  try {
37529
- value.school = new ObjectId16(value.school);
34502
+ value.school = new ObjectId15(value.school);
37530
34503
  } catch (err) {
37531
34504
  throw new BadRequestError24("Invalid school ID.");
37532
34505
  }
@@ -37560,7 +34533,7 @@ import {
37560
34533
  useAtlas as useAtlas11,
37561
34534
  useCache as useCache8
37562
34535
  } from "@eeplatform/nodejs-utils";
37563
- import { ObjectId as ObjectId17 } from "mongodb";
34536
+ import { ObjectId as ObjectId16 } from "mongodb";
37564
34537
  function useStockCardRepository() {
37565
34538
  const db = useAtlas11.getDb();
37566
34539
  if (!db) {
@@ -37604,7 +34577,7 @@ function useStockCardRepository() {
37604
34577
  }
37605
34578
  async function getById(_id) {
37606
34579
  try {
37607
- _id = new ObjectId17(_id);
34580
+ _id = new ObjectId16(_id);
37608
34581
  } catch (error) {
37609
34582
  throw new BadRequestError25("Invalid ID.");
37610
34583
  }
@@ -37640,12 +34613,12 @@ function useStockCardRepository() {
37640
34613
  async function getAll({ page = 1, limit = 20, school = "", sort = { _id: 1 }, id = "" } = {}) {
37641
34614
  page = page ? page - 1 : 0;
37642
34615
  try {
37643
- school = new ObjectId17(school);
34616
+ school = new ObjectId16(school);
37644
34617
  } catch (error) {
37645
34618
  throw new BadRequestError25("Invalid school ID.");
37646
34619
  }
37647
34620
  try {
37648
- id = new ObjectId17(id);
34621
+ id = new ObjectId16(id);
37649
34622
  } catch (error) {
37650
34623
  throw new BadRequestError25("Invalid ID.");
37651
34624
  }
@@ -37703,7 +34676,7 @@ function useStockCardRepository() {
37703
34676
  }
37704
34677
  async function getSuppliers(school) {
37705
34678
  try {
37706
- school = new ObjectId17(school);
34679
+ school = new ObjectId16(school);
37707
34680
  } catch (error) {
37708
34681
  throw new BadRequestError25("Invalid school ID.");
37709
34682
  }
@@ -37908,7 +34881,7 @@ function useStockCardController() {
37908
34881
  // src/resources/plantilla/plantilla.model.ts
37909
34882
  import { BadRequestError as BadRequestError28 } from "@eeplatform/nodejs-utils";
37910
34883
  import Joi17 from "joi";
37911
- import { ObjectId as ObjectId18 } from "mongodb";
34884
+ import { ObjectId as ObjectId17 } from "mongodb";
37912
34885
  var schemaPlantilla = Joi17.object({
37913
34886
  _id: Joi17.string().hex().optional().allow(null, ""),
37914
34887
  org: Joi17.string().hex().required(),
@@ -37939,7 +34912,7 @@ function MPlantilla(data) {
37939
34912
  }
37940
34913
  if (data._id && typeof data._id === "string") {
37941
34914
  try {
37942
- data._id = new ObjectId18(data._id);
34915
+ data._id = new ObjectId17(data._id);
37943
34916
  } catch (error2) {
37944
34917
  throw new BadRequestError28("Invalid _id.");
37945
34918
  }
@@ -37980,7 +34953,7 @@ import {
37980
34953
  useAtlas as useAtlas13,
37981
34954
  useCache as useCache9
37982
34955
  } from "@eeplatform/nodejs-utils";
37983
- import { ObjectId as ObjectId19 } from "mongodb";
34956
+ import { ObjectId as ObjectId18 } from "mongodb";
37984
34957
  function usePlantillaRepo() {
37985
34958
  const db = useAtlas13.getDb();
37986
34959
  if (!db) {
@@ -38027,7 +35000,7 @@ function usePlantillaRepo() {
38027
35000
  }
38028
35001
  async function updateById(_id, value, session) {
38029
35002
  try {
38030
- _id = new ObjectId19(_id);
35003
+ _id = new ObjectId18(_id);
38031
35004
  } catch (error) {
38032
35005
  throw new BadRequestError29("Invalid ID.");
38033
35006
  }
@@ -38070,7 +35043,7 @@ function usePlantillaRepo() {
38070
35043
  }
38071
35044
  if (org) {
38072
35045
  try {
38073
- query.org = new ObjectId19(org);
35046
+ query.org = new ObjectId18(org);
38074
35047
  } catch (error) {
38075
35048
  throw new BadRequestError29("Invalid org ID.");
38076
35049
  }
@@ -38127,7 +35100,7 @@ function usePlantillaRepo() {
38127
35100
  }
38128
35101
  async function getById(_id) {
38129
35102
  try {
38130
- _id = new ObjectId19(_id);
35103
+ _id = new ObjectId18(_id);
38131
35104
  } catch (error) {
38132
35105
  throw new BadRequestError29("Invalid ID.");
38133
35106
  }
@@ -38166,7 +35139,7 @@ function usePlantillaRepo() {
38166
35139
  }
38167
35140
  async function deleteById(_id, session) {
38168
35141
  try {
38169
- _id = new ObjectId19(_id);
35142
+ _id = new ObjectId18(_id);
38170
35143
  } catch (error) {
38171
35144
  throw new BadRequestError29("Invalid ID.");
38172
35145
  }
@@ -38385,12 +35358,12 @@ ${errors.slice(0, 10).join("\n")}${errors.length > 10 ? `
38385
35358
  failed: 0,
38386
35359
  errors: []
38387
35360
  };
38388
- const promises = [];
35361
+ const promises2 = [];
38389
35362
  for (let i = 0; i < validatedPlantillas.length; i++) {
38390
35363
  const plantilla = validatedPlantillas[i];
38391
- promises.push(addPlantilla(plantilla, session, false));
35364
+ promises2.push(addPlantilla(plantilla, session, false));
38392
35365
  }
38393
- await Promise.all(promises);
35366
+ await Promise.all(promises2);
38394
35367
  await delCachedData();
38395
35368
  await session.commitTransaction();
38396
35369
  return {
@@ -38627,6 +35600,7 @@ export {
38627
35600
  schemaPlantilla,
38628
35601
  schemaRegion,
38629
35602
  schemaSchool,
35603
+ schemaSchoolUpdate,
38630
35604
  schemaStockCard,
38631
35605
  useAssetController,
38632
35606
  useAssetRepo,