babymongo 0.2.0
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/LICENSE +27 -0
- package/README.md +712 -0
- package/dist/babymongo-browser.min.js +2 -0
- package/dist/babymongo-browser.min.js.map +1 -0
- package/dist/babymongo-node.min.js +2 -0
- package/dist/babymongo-node.min.js.map +1 -0
- package/dist/babymongo-server-worker.js +2 -0
- package/dist/babymongo-server-worker.js.map +1 -0
- package/package.json +70 -0
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
var e,t={exports:{}};var n=function(){if(e)return t.exports;e=1;var n,r="object"==typeof Reflect?Reflect:null,i=r&&"function"==typeof r.apply?r.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};n=r&&"function"==typeof r.ownKeys?r.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var s=Number.isNaN||function(e){return e!=e};function o(){o.init.call(this)}t.exports=o,t.exports.once=function(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,s),r(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}m(e,t,s,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&m(e,"error",t,n)}(e,i,{once:!0})})},o.EventEmitter=o,o.prototype._events=void 0,o.prototype._eventsCount=0,o.prototype._maxListeners=void 0;var a=10;function c(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function l(e){return void 0===e._maxListeners?o.defaultMaxListeners:e._maxListeners}function u(e,t,n,r){var i,s,o,a;if(c(n),void 0===(s=e._events)?(s=e._events=/* @__PURE__ */Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),o=s[t]),void 0===o)o=s[t]=n,++e._eventsCount;else if("function"==typeof o?o=s[t]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),(i=l(e))>0&&o.length>i&&!o.warned){o.warned=!0;var u=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=o.length,a=u,console&&console.warn&&console.warn(a)}return e}function h(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function f(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=h.bind(r);return i.listener=n,r.wrapFn=i,i}function d(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):g(i,i.length)}function p(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function g(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function m(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,function i(s){r.once&&e.removeEventListener(t,i),n(s)})}}return Object.defineProperty(o,"defaultMaxListeners",{enumerable:!0,get:function(){return a},set:function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");a=e}}),o.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=/* @__PURE__ */Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},o.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||s(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},o.prototype.getMaxListeners=function(){return l(this)},o.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var r="error"===e,s=this._events;if(void 0!==s)r=r&&void 0===s.error;else if(!r)return!1;if(r){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)i(c,this,t);else{var l=c.length,u=g(c,l);for(n=0;n<l;++n)i(u[n],this,t)}return!0},o.prototype.addListener=function(e,t){return u(this,e,t,!1)},o.prototype.on=o.prototype.addListener,o.prototype.prependListener=function(e,t){return u(this,e,t,!0)},o.prototype.once=function(e,t){return c(t),this.on(e,f(this,e,t)),this},o.prototype.prependOnceListener=function(e,t){return c(t),this.prependListener(e,f(this,e,t)),this},o.prototype.removeListener=function(e,t){var n,r,i,s,o;if(c(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0===--this._eventsCount?this._events=/* @__PURE__ */Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){o=n[s].listener,i=s;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,o||t)}return this},o.prototype.off=o.prototype.removeListener,o.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=/* @__PURE__ */Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0===--this._eventsCount?this._events=/* @__PURE__ */Object.create(null):delete n[e]),this;if(0===arguments.length){var i,s=Object.keys(n);for(r=0;r<s.length;++r)"removeListener"!==(i=s[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=/* @__PURE__ */Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},o.prototype.listeners=function(e){return d(this,e,!0)},o.prototype.rawListeners=function(e){return d(this,e,!1)},o.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},o.prototype.listenerCount=p,o.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]},t.exports}();const r=0,i=1,s=2,o=3,a=4,c=5,l=6,u=7,h=8,f=9,d=16,p=17;class g{constructor(e){if(null==e)this.id=g.generate();else if("string"==typeof e){if(!g.isValid(e))throw new Error(`Argument passed in must be a string of 24 hex characters, got: ${e}`);this.id=e.toLowerCase()}else if(e instanceof Uint8Array&&12===e.length)this.id=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join("");else{if(!(e instanceof g))throw new Error("Argument passed in must be a string of 24 hex characters or an ObjectId");this.id=e.id}}toString(){return this.id}toHexString(){return this.id}getTimestamp(){const e=parseInt(this.id.substring(0,8),16);return new Date(1e3*e)}equals(e){if(!(e instanceof g))throw new Error("Can only compare with another ObjectId");return this.id===e.id}compare(e){if(!(e instanceof g))throw new Error("Can only compare with another ObjectId");return this.id.localeCompare(e.id)}toJSON(){return this.id}inspect(){return`ObjectId("${this.id}")`}toBytes(){const e=new Uint8Array(12);for(let t=0;t<12;t++)e[t]=parseInt(this.id.substring(2*t,2*t+2),16);return e}static isValid(e){return!!e&&("string"==typeof e&&(24===e.length&&/^[0-9a-fA-F]{24}$/.test(e)))}static createFromTime(e){const t=("00000000"+Math.floor(e/1e3).toString(16)).slice(-8);return new g(t+"0000000000000000")}static generate(){const e=Math.floor(Date.now()/1e3),t="undefined"!=typeof crypto&&crypto.getRandomValues?new Uint8Array(8):null;let n="";if(t){crypto.getRandomValues(t);for(let e=0;e<t.length;e++)n+=("0"+t[e].toString(16)).slice(-2)}else n=Math.random().toString(16).slice(2).padEnd(8,"0").slice(0,8)+Math.random().toString(16).slice(2).padEnd(8,"0").slice(0,8);return(("00000000"+e.toString(16)).slice(-8)+n).slice(0,24)}}class m{constructor(e){if(null==e)throw new Error("Pointer offset must be a number");if("number"!=typeof e)throw new Error("Pointer offset must be a number");if(!Number.isInteger(e))throw new Error("Pointer offset must be an integer");if(e<0)throw new Error("Pointer offset must be non-negative");if(e>Number.MAX_SAFE_INTEGER)throw new Error("Pointer offset exceeds maximum safe integer");this.offset=e}valueOf(){return this.offset}toString(){return this.offset.toString()}toJSON(){return this.offset}inspect(){return`Pointer(${this.offset})`}equals(e){return e instanceof m&&this.offset===e.offset}}function y(e){const t=[];!function e(n){if(null===n)t.push(new Uint8Array([r]));else if(!1===n)t.push(new Uint8Array([i]));else if(!0===n)t.push(new Uint8Array([s]));else if(n instanceof g)t.push(new Uint8Array([l])),t.push(n.toBytes());else if(n instanceof Date){t.push(new Uint8Array([u]));const e=new ArrayBuffer(8);new DataView(e).setBigInt64(0,BigInt(n.getTime()),!0),t.push(new Uint8Array(e))}else if(n instanceof m){t.push(new Uint8Array([h]));const e=new ArrayBuffer(8);new DataView(e).setBigUint64(0,BigInt(n.offset),!0),t.push(new Uint8Array(e))}else if(n instanceof Uint8Array){t.push(new Uint8Array([f]));const e=new ArrayBuffer(4);new DataView(e).setUint32(0,n.length,!0),t.push(new Uint8Array(e)),t.push(n)}else if("number"==typeof n)if(Number.isInteger(n)&&Number.isSafeInteger(n)){t.push(new Uint8Array([o]));const e=new ArrayBuffer(8);new DataView(e).setBigInt64(0,BigInt(n),!0),t.push(new Uint8Array(e))}else{t.push(new Uint8Array([a]));const e=new ArrayBuffer(8);new DataView(e).setFloat64(0,n,!0),t.push(new Uint8Array(e))}else if("string"==typeof n){t.push(new Uint8Array([c]));const e=(new TextEncoder).encode(n),r=new ArrayBuffer(4);new DataView(r).setUint32(0,e.length,!0),t.push(new Uint8Array(r)),t.push(e)}else if(Array.isArray(n)){const r=[],i=new ArrayBuffer(4);new DataView(i).setUint32(0,n.length,!0),r.push(new Uint8Array(i));const s=t.length;for(const t of n)e(t);const o=t.splice(s);r.push(...o);const a=r.reduce((e,t)=>e+t.length,0);t.push(new Uint8Array([d]));const c=new ArrayBuffer(4);new DataView(c).setUint32(0,a,!0),t.push(new Uint8Array(c)),t.push(...r)}else{if("object"!=typeof n)throw new Error("Unsupported type: "+typeof n);{const r=[],i=Object.keys(n),s=new ArrayBuffer(4);new DataView(s).setUint32(0,i.length,!0),r.push(new Uint8Array(s));const o=t.length;for(const u of i){const r=(new TextEncoder).encode(u),i=new ArrayBuffer(4);new DataView(i).setUint32(0,r.length,!0),t.push(new Uint8Array(i)),t.push(r),e(n[u])}const a=t.splice(o);r.push(...a);const c=r.reduce((e,t)=>e+t.length,0);t.push(new Uint8Array([p]));const l=new ArrayBuffer(4);new DataView(l).setUint32(0,c,!0),t.push(new Uint8Array(l)),t.push(...r)}}}(e);const n=t.reduce((e,t)=>e+t.length,0),y=new Uint8Array(n);let w=0;for(const r of t)y.set(r,w),w+=r.length;return y}function w(e){let t=0;return function n(){if(t>=e.length)throw new Error("Unexpected end of data");const y=e[t++];switch(y){case r:return null;case i:return!1;case s:return!0;case o:{if(t+4>e.length)throw new Error("Unexpected end of data for INT");const n=new DataView(e.buffer,e.byteOffset+t,8).getBigInt64(0,!0);if(t+=8,n<BigInt(Number.MIN_SAFE_INTEGER)||n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("Decoded integer exceeds safe range");return Number(n)}case a:{if(t+8>e.length)throw new Error("Unexpected end of data for FLOAT");const n=new DataView(e.buffer,e.byteOffset+t,8).getFloat64(0,!0);return t+=8,n}case c:{if(t+4>e.length)throw new Error("Unexpected end of data for STRING length");const n=new DataView(e.buffer,e.byteOffset+t,4).getUint32(0,!0);if(t+=4,t+n>e.length)throw new Error("Unexpected end of data for STRING content");const r=e.slice(t,t+n);return t+=n,(new TextDecoder).decode(r)}case l:{if(t+12>e.length)throw new Error("Unexpected end of data for OID");const n=e.slice(t,t+12);return t+=12,new g(n)}case u:{if(t+8>e.length)throw new Error("Unexpected end of data for DATE");const n=new DataView(e.buffer,e.byteOffset+t,8).getBigInt64(0,!0);return t+=8,new Date(Number(n))}case h:{if(t+8>e.length)throw new Error("Unexpected end of data for POINTER");const n=new DataView(e.buffer,e.byteOffset+t,8).getBigUint64(0,!0);if(t+=8,n>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("Pointer offset out of valid range");return new m(Number(n))}case f:{if(t+4>e.length)throw new Error("Unexpected end of data for BINARY length");const n=new DataView(e.buffer,e.byteOffset+t,4).getUint32(0,!0);if(t+=4,t+n>e.length)throw new Error("Unexpected end of data for BINARY content");const r=e.slice(t,t+n);return t+=n,r}case d:{if(t+4>e.length)throw new Error("Unexpected end of data for ARRAY size");const r=new DataView(e.buffer,e.byteOffset+t,4).getUint32(0,!0);if(t+=4,t+r>e.length)throw new Error("Unexpected end of data for ARRAY content");const i=new DataView(e.buffer,e.byteOffset+t,4).getUint32(0,!0);t+=4;const s=[];for(let e=0;e<i;e++)s.push(n());return s}case p:{if(t+4>e.length)throw new Error("Unexpected end of data for OBJECT size");const r=new DataView(e.buffer,e.byteOffset+t,4).getUint32(0,!0);if(t+=4,t+r>e.length)throw new Error("Unexpected end of data for OBJECT content");const i=new DataView(e.buffer,e.byteOffset+t,4).getUint32(0,!0);t+=4;const s={};for(let o=0;o<i;o++){if(t+4>e.length)throw new Error("Unexpected end of data for OBJECT key length");const r=new DataView(e.buffer,e.byteOffset+t,4).getUint32(0,!0);if(t+=4,t+r>e.length)throw new Error("Unexpected end of data for OBJECT key");const i=e.slice(t,t+r);t+=r;s[(new TextDecoder).decode(i)]=n()}return s}default:throw new Error(`Unknown type byte: 0x${y.toString(16)}`)}}()}class b{constructor(e){if(!e)throw new Error("FileSystemSyncAccessHandle is required");this.syncAccessHandle=e}#e(e,t){const n=new Uint8Array(t),r=this.syncAccessHandle.read(n,{at:e});return r<t?n.slice(0,r):n}getFileSize(){return this.syncAccessHandle.getSize()}write(e){const t=y(e);this.syncAccessHandle.truncate(0),this.syncAccessHandle.write(t,{at:0})}read(e=new m(0)){const t=this.getFileSize();if(0===t)throw new Error("File is empty");const n=e.valueOf();if(n<0||n>=t)throw new Error(`Pointer offset ${e} out of file bounds [0, ${t})`);return w(this.#e(n,t-n))}append(e){const t=y(e),n=this.getFileSize();this.syncAccessHandle.write(t,{at:n})}flush(){this.syncAccessHandle.flush()}*scan(){const e=this.getFileSize();if(0===e)return;let t=0;for(;t<e;){const e=(e=>{let t=this.#e(e,1);const n=t[0];switch(n){case r:case i:case s:return 1;case o:case a:case u:case h:return 9;case l:return 13;case c:t=this.#e(e+1,4);return 5+new DataView(t.buffer,t.byteOffset,4).getUint32(0,!0);case f:t=this.#e(e+1,4);return 5+new DataView(t.buffer,t.byteOffset,4).getUint32(0,!0);case d:t=this.#e(e+1,4);return 5+new DataView(t.buffer,t.byteOffset,4).getUint32(0,!0);case p:t=this.#e(e+1,4);return 5+new DataView(t.buffer,t.byteOffset,4).getUint32(0,!0);default:throw new Error(`Unknown type byte: 0x${n.toString(16)}`)}})(t),n=this.#e(t,e);t+=e,yield w(n)}}}function x(e,t){return e instanceof g||t instanceof g?e instanceof g&&t instanceof g||e instanceof g&&"string"==typeof t?e.equals(t):t instanceof g&&"string"==typeof e&&t.equals(e):e==t}function _(e){if("object"!=typeof e||null===e)return e;if(e instanceof g)return new g(e.id);if(e instanceof Date)return new Date(e.getTime());var t,n,r;for(r in t=Array.isArray(e)?[]:{},e)n=e[r],t[r]="object"==typeof n&&null!==n?_(n):n;return t}function v(e,t){for(var n=t.split("."),r=e[n[0]],i=1;i<n.length;i++){if(null==r||null==r)return r;var s=n[i],o=parseInt(s,10);r=N(r)&&!isNaN(o)&&o>=0&&o<r.length?r[o]:r[s]}return r}function $(e,t){for(var n=t.split("."),r=[e],i=0;i<n.length;i++){for(var s=n[i],o=parseInt(s,10),a=[],c=0;c<r.length;c++){var l=r[c];if(null!=l&&null!=l)if(N(l)&&!isNaN(o)&&o>=0)o<l.length&&a.push(l[o]);else if(N(l))for(var u=0;u<l.length;u++)null!=l[u]&&null!=l[u]&&"object"==typeof l[u]&&a.push(l[u][s]);else"object"==typeof l&&a.push(l[s])}r=a}if(0!==(r=r.filter(function(e){return void 0!==e})).length)return 1===r.length?r[0]:r}function I(e,t,n){if(-1!==t.indexOf("$[]"))return function(e,t,n){for(var r=t.split("."),i=e,s=0;s<r.length;s++){var o=r[s];if("$[]"===o){if(!Array.isArray(i))throw new Error("The positional operator did not find the match needed from the query.");for(var a=r.slice(s+1).join("."),c=0;c<i.length;c++)a?I(i[c],a,n):i[c]=n;return}var l=parseInt(o,10);if(N(i)&&!isNaN(l)&&l>=0)i=i[l];else{if(null==i[o]||null==i[o]){var u=s+1<r.length?r[s+1]:null;if("$[]"===u)i[o]=[];else{var h=parseInt(u,10);!isNaN(h)&&h>=0?i[o]=[]:i[o]={}}}i=i[o]}}}(e,t,n);for(var r=t.split("."),i=e,s=0;s<r.length-1;s++){var o=r[s],a=parseInt(o,10);if(N(i)&&!isNaN(a)&&a>=0){for(;i.length<=a;)i.push(void 0);if(null==i[a]||null==i[a]){var c=r[s+1],l=parseInt(c,10);!isNaN(l)&&l>=0?i[a]=[]:i[a]={}}i=i[a]}else{if(null==i[o]||null==i[o]){c=r[s+1],l=parseInt(c,10);!isNaN(l)&&l>=0?i[o]=[]:i[o]={}}i=i[o]}}var u=r[r.length-1],h=parseInt(u,10);if(N(i)&&!isNaN(h)&&h>=0){for(;i.length<=h;)i.push(void 0);i[h]=n}else i[u]=n}function N(e){return Array==e.constructor}function S(e){var t=[];for(var n in e)if(e.hasOwnProperty(n)){var r={};r[n]=e[n],t.push(r)}return t}function O(e,t){for(var n=0;n<t.length;n++)if(x(t[n],e))return!0;return!1}function A(e,t){if(e.length!=t.length)return!1;for(var n=0;n<e.length;n++)if(!x(e[n],t[n])){if(typeof e[n]!=typeof t[n])return!1;if("object"==typeof e[n]&&null!==e[n]){if(N(e[n])){if(!A(e[n],t[n]))return!1}else if(!C(e[n],t[n]))return!1}else if(!x(e[n],t[n]))return!1}return!0}function C(e,t){for(var n in e)if(e.hasOwnProperty(n)){if(!t.hasOwnProperty(n))return!1;if(!x(e[n],t[n])){if(typeof e[n]!=typeof t[n])return!1;if("object"==typeof e[n]&&null!==e[n]){if(N(e[n])){if(!A(e[n],t[n]))return!1}else if(!C(e[n],t[n]))return!1}else if(!x(e[n],t[n]))return!1}}for(var n in t)if(t.hasOwnProperty(n)&&!e.hasOwnProperty(n))return!1;return!0}function E(e,t){var n={},r=Object.keys(e);if(0==r.length)return t;for(var i=!1,s=!1,o=0;o<r.length;o++)"_id"!==r[o]&&(e[r[o]]?i=!0:s=!0);if(i&&s)throw{$err:"Can't canonicalize query: BadValue Projection cannot have a mix of inclusion and exclusion.",code:17287};if(e[r[0]]||i){0!==e._id&&!1!==e._id&&(n._id=_(t._id));for(o=0;o<r.length;o++)if("_id"!==r[o]&&e[r[o]]){var a=v(t,u=r[o]);void 0!==a&&I(n,u,_(a))}}else{for(var c in t)if(t.hasOwnProperty(c)){var l=t[c];"object"!=typeof l||null===l||N(l)?N(l)?n[c]=l.slice():n[c]=l:n[c]=_(l)}for(o=0;o<r.length;o++)if(!e[r[o]]){var u,h=(u=r[o]).split(".");if(1===h.length)delete n[u];else{for(var f=n,d=0;d<h.length-1&&(null!=f&&null!=f);d++)f=f[h[d]];null!=f&&null!=f&&delete f[h[h.length-1]]}}}return n}const j=2,D=8,k=17287,P=26,M=27,L=85,T=11e3,F=2,B=31254,z=999;class U extends Error{constructor(e,t={}){super(e),this.name="MongoError",this.code=t.code||D,this.codeName=this._getCodeName(this.code),this.$err=e,t.collection&&(this.collection=t.collection),t.database&&(this.database=t.database),t.operation&&(this.operation=t.operation),t.query&&(this.query=t.query),t.document&&(this.document=t.document),t.field&&(this.field=t.field),t.index&&(this.index=t.index),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}_getCodeName(e){return{0:"OK",1:"InternalError",2:"BadValue",4:"NoSuchKey",5:"GraphContainsCycle",6:"HostUnreachable",7:"HostNotFound",8:"UnknownError",10:"CannotMutateObject",11:"UserNotFound",12:"UnsupportedFormat",13:"Unauthorized",14:"TypeMismatch",15:"Overflow",16:"InvalidLength",17:"ProtocolError",18:"AuthenticationFailed",20:"IllegalOperation",26:"NamespaceNotFound",27:"IndexNotFound",28:"PathNotViable",43:"CursorNotFound",48:"NamespaceExists",59:"CommandNotFound",67:"CannotCreateIndex",68:"IndexExists",73:"InvalidNamespace",85:"IndexOptionsConflict",112:"WriteConflict",121:"DocumentValidationFailure",171:"CannotIndexParallelArrays",197:"InvalidIndexSpecificationOption",998:"OperationNotSupported",999:"NotImplemented",11e3:"DuplicateKey",11001:"DuplicateKeyUpdate",17287:"FailedToParse"}[e]||"UnknownError"}toJSON(){const e={name:this.name,message:this.message,code:this.code,codeName:this.codeName};return this.collection&&(e.collection=this.collection),this.database&&(e.database=this.database),this.operation&&(e.operation=this.operation),this.index&&(e.index=this.index),this.indexName&&(e.indexName=this.indexName),this.field&&(e.field=this.field),this.query&&(e.query=this.query),this.document&&(e.document=this.document),this.namespace&&(e.namespace=this.namespace),this.cursorId&&(e.cursorId=this.cursorId),this.feature&&(e.feature=this.feature),this.keyPattern&&(e.keyPattern=this.keyPattern),this.keyValue&&(e.keyValue=this.keyValue),this.writeErrors&&(e.writeErrors=this.writeErrors),e}}class R extends U{constructor(e,t={}){super(e,t),this.name="IndexError"}}class q extends R{constructor(e,t={}){super(`Index '${e}' not found`,{...t,code:M,index:e}),this.name="IndexNotFoundError",this.indexName=e}}class V extends U{constructor(e,t={}){super(e,t),this.name="QueryError",this.code=t.code||F}}class H extends U{constructor(e,t={}){super(`${e} is not implemented in babymongo`,{...t,code:z}),this.name="NotImplementedError",this.feature=e}}class W extends U{constructor(e,t,n,r={}){super(`Bad value for field '${e}': ${n}`,{...r,code:j,field:e}),this.name="BadValueError",this.value=t}}class Q{constructor(e,t,n,r,i){if(this.collection=e,this.query=t,this.projection=n,this._documentsPromise=r instanceof Promise?r:Promise.resolve(r),this.documents=null,this._initialized=!1,this.SortedCursor=i,n&&Object.keys(n).length>0){const t=Object.keys(n);let r=!1,i=!1;for(let e=0;e<t.length;e++)"_id"!==t[e]&&(n[t[e]]?r=!0:i=!0);if(r&&i)throw new V("Can't canonicalize query: BadValue Projection cannot have a mix of inclusion and exclusion.",{code:k,collection:e.name})}this.pos=0,this._limit=0,this._skip=0,this._closed=!1}async _ensureInitialized(){this._initialized||(this.documents=await this._documentsPromise,this._initialized=!0)}batchSize(e){return this._batchSize=e,this}close(){this._closed=!0,this.documents&&(this.pos=this.documents.length)}comment(e){return this._comment=e,this}async count(){return await this._ensureInitialized(),this.documents.length}explain(e="queryPlanner"){return{queryPlanner:{plannerVersion:1,namespace:`${this.collection.db?.name||"db"}.${this.collection.name}`,indexFilterSet:!1,parsedQuery:this.query,winningPlan:{stage:"COLLSCAN",filter:this.query,direction:"forward"}},executionStats:"executionStats"===e||"allPlansExecution"===e?{executionSuccess:!0,nReturned:this.documents?this.documents.length:0,executionTimeMillis:0,totalKeysExamined:0,totalDocsExamined:this.documents?this.documents.length:0}:void 0,ok:1}}async forEach(e){for(await this._ensureInitialized();await this.hasNext();)await e(await this.next())}async hasNext(){if(this._closed)return!1;let e;return await this._ensureInitialized(),0===this.pos&&this._skip>0&&(this.pos=Math.min(this._skip,this.documents.length)),e=this._limit>0?Math.min(this._skip+this._limit,this.documents.length):this.documents.length,this.pos<e}hint(e){return this._hint=e,this}async itcount(){await this._ensureInitialized();let e=0;for(;await this.hasNext();)await this.next(),e++;return e}limit(e){return this._limit=e,this}async map(e){await this._ensureInitialized();const t=[];for(;await this.hasNext();)t.push(await e(await this.next()));return t}maxScan(e){return this._maxScan=e,this}maxTimeMS(e){return this._maxTimeMS=e,this}max(e){return this._maxIndexBounds=e,this}min(e){return this._minIndexBounds=e,this}async next(){if(!(await this.hasNext()))throw new V("Error: error hasNext: false",{collection:this.collection.name});const e=this.documents[this.pos++];return this.projection?E(this.projection,e):e}noCursorTimeout(){return this._noCursorTimeout=!0,this}objsLeftInBatch(){return this.documents?this.size():0}pretty(){return this._pretty=!0,this}readConcern(e){return this._readConcern=e,this}readPref(e,t){return this._readPref={mode:e,tagSet:t},this}returnKey(e=!0){return this._returnKey=e,this}showRecordId(e=!0){return this._showRecordId=e,this}size(){if(!this.documents)return 0;const e=this.documents.length-this.pos;if(this._limit>0){const t=this._skip+this._limit;return Math.min(t-this.pos,e)}return e}skip(e){return this._skip=e,0===this.pos&&this.documents&&(this.pos=Math.min(e,this.documents.length)),this}isClosed(){return!0===this._closed}snapshot(){throw new H("snapshot")}sort(e){return new this.SortedCursor(this.collection,this.query,this,e)}allowDiskUse(e=!0){return this._allowDiskUse=e,this}collation(e){return this._collation=e,this}tailable(){throw new H("tailable")}async toArray(){await this._ensureInitialized();const e=[];for(;await this.hasNext();)e.push(await this.next());return e}async*[Symbol.asyncIterator](){for(await this._ensureInitialized();await this.hasNext();)yield await this.next()}}class J{constructor(e,t,n,r){this.collection=e,this.query=t,this.sortSpec=r,this.pos=0,this._cursor=n,this._sort=r,this._initialized=!1,this.items=null}async _ensureInitialized(){if(this._initialized)return;for(await this._cursor._ensureInitialized(),this.items=[];await this._cursor.hasNext();)this.items.push(await this._cursor.next());const e=Object.keys(this._sort);this.items.sort(function(t,n){for(let r=0;r<e.length;r++){if(null==t[e[r]]&&null!=n[e[r]])return-1*this._sort[e[r]];if(null!=t[e[r]]&&null==n[e[r]])return 1*this._sort[e[r]];if(t[e[r]]<n[e[r]])return-1*this._sort[e[r]];if(t[e[r]]>n[e[r]])return 1*this._sort[e[r]]}return 0}.bind(this)),this._initialized=!0}batchSize(){throw"Not Implemented"}close(){throw"Not Implemented"}comment(){throw"Not Implemented"}async count(){return await this._ensureInitialized(),this.items.length}explain(){throw"Not Implemented"}async forEach(e){for(await this._ensureInitialized();await this.hasNext();)await e(await this.next())}async hasNext(){return await this._ensureInitialized(),this.pos<this.items.length}hint(){throw"Not Implemented"}itcount(){throw"Not Implemented"}async limit(e){return await this._ensureInitialized(),this.items=this.items.slice(0,e),this}async map(e){await this._ensureInitialized();const t=[];for(;await this.hasNext();)t.push(await e(await this.next()));return t}maxScan(){throw"Not Implemented"}maxTimeMS(){throw"Not Implemented"}max(){throw"Not Implemented"}min(){throw"Not Implemented"}async next(){return await this._ensureInitialized(),this.items[this.pos++]}noCursorTimeout(){throw"Not Implemented"}objsLeftInBatch(){throw"Not Implemented"}pretty(){throw"Not Implemented"}readConcern(){throw"Not Implemented"}readPref(){throw"Not Implemented"}returnKey(){throw"Not Implemented"}showRecordId(){throw"Not Implemented"}size(){throw"Not Implemented"}async skip(e){for(await this._ensureInitialized();e>0;)await this.next(),e--;return this}snapshot(){throw"Not Implemented"}sort(e){return new J(this.collection,this.query,this,e)}tailable(){throw"Not Implemented"}async toArray(){await this._ensureInitialized();const e=[];for(;await this.hasNext();)e.push(this.next());return e}async*[Symbol.asyncIterator](){for(await this._ensureInitialized();await this.hasNext();)yield await this.next()}}const K={ational:"ate",tional:"tion",enci:"ence",anci:"ance",izer:"ize",bli:"ble",alli:"al",entli:"ent",eli:"e",ousli:"ous",ization:"ize",ation:"ate",ator:"ate",alism:"al",iveness:"ive",fulness:"ful",ousness:"ous",aliti:"al",iviti:"ive",biliti:"ble",logi:"log"},G={icate:"ic",ative:"",alize:"al",iciti:"ic",ical:"ic",ful:"",ness:""},Y="[aeiouy]",X="([^aeiou][^aeiouy]*)",Z="("+Y+"[aeiou]*)",ee=new RegExp("^"+X+"?"+Z+X),te=new RegExp("^"+X+"?"+Z+X+Z+"?$"),ne=new RegExp("^"+X+"?("+Z+X+"){2,}"),re=new RegExp("^"+X+"?"+Y),ie=new RegExp("^"+X+Y+"[^aeiouwxy]$"),se=/ll$/,oe=/^(.+?)e$/,ae=/^(.+?)y$/,ce=/^(.+?(s|t))(ion)$/,le=/^(.+?)(ed|ing)$/,ue=/(at|bl|iz)$/,he=/^(.+?)eed$/,fe=/^.+?[^s]s$/,de=/^.+?(ss|i)es$/,pe=/([^aeiouylsz])\1$/,ge=/^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/,me=/^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/,ye=/^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;function we(e){let t=String(e).toLowerCase();if(t.length<3)return t;let n,r=!1;return 121===t.codePointAt(0)&&(r=!0,t="Y"+t.slice(1)),de.test(t)?t=t.slice(0,-2):fe.test(t)&&(t=t.slice(0,-1)),(n=he.exec(t))?ee.test(n[1])&&(t=t.slice(0,-1)):(n=le.exec(t))&&re.test(n[1])&&(t=n[1],ue.test(t)?t+="e":pe.test(t)?t=t.slice(0,-1):ie.test(t)&&(t+="e")),(n=ae.exec(t))&&re.test(n[1])&&(t=n[1]+"i"),(n=ge.exec(t))&&ee.test(n[1])&&(t=n[1]+K[n[2]]),(n=me.exec(t))&&ee.test(n[1])&&(t=n[1]+G[n[2]]),(n=ye.exec(t))?ne.test(n[1])&&(t=n[1]):(n=ce.exec(t))&&ne.test(n[1])&&(t=n[1]),(n=oe.exec(t))&&(ne.test(n[1])||te.test(n[1])&&!ie.test(n[1]))&&(t=n[1]),se.test(t)&&ne.test(t)&&(t=t.slice(0,-1)),r&&(t="y"+t.slice(1)),t}class be{constructor(e,t,n,r,i,s){this.id=e,this.isLeaf=t,this.keys=n,this.values=r,this.children=i;for(let o of i)if(!(o instanceof m))throw new Error("Children must be Pointer objects");this.next=s}}class xe{constructor(e,t=3){if(t<3)throw new Error("B+ tree order must be at least 3");this.file=new b(e),this.order=t,this.minKeys=Math.ceil(t/2)-1,this.isOpen=!1,this.rootPointer=null,this.nextNodeId=0,this._size=0}async open(){if(this.isOpen)throw new Error("Tree is already open");this.file.getFileSize()>0?this._loadMetadata():this._initializeNewTree(),this.isOpen=!0}async close(){this.isOpen&&(this.file&&this.file.syncAccessHandle&&(this.file.flush(),await this.file.syncAccessHandle.close()),this.isOpen=!1)}_initializeNewTree(){const e=new be(0,!0,[],[],[],null);this.nextNodeId=1,this._size=0;const t=this._saveNode(e);this.rootPointer=t,this._saveMetadata()}_saveMetadata(){const e={version:1,maxEntries:this.order,minEntries:this.minKeys,size:this._size,rootPointer:this.rootPointer,nextId:this.nextNodeId};this.file.append(e)}_loadMetadata(){const e=this.file.getFileSize();if(e<135)throw new Error("Invalid tree file");const t=e-135,n=this.file.read(t);if(!n||void 0===n.maxEntries)throw new Error("Failed to read metadata: missing required fields");this.order=n.maxEntries,this.minKeys=n.minEntries,this._size=n.size,this.nextNodeId=n.nextId,this.rootPointer=n.rootPointer}_saveNode(e){const t=this.file.getFileSize();return this.file.append(e),new m(t)}_loadNode(e){if(!(e instanceof m))throw new Error("Expected Pointer object");const t=this.file.read(e);return new be(t.id,t.isLeaf,t.keys,t.values,t.children,t.next)}_loadRoot(){return this._loadNode(this.rootPointer)}search(e){const t=this._loadRoot();return this._searchNode(t,e)}_searchNode(e,t){if(!e.isLeaf){let n=0;for(;n<e.keys.length&&t>=e.keys[n];)n++;const r=this._loadNode(e.children[n]);return this._searchNode(r,t)}for(let n=0;n<e.keys.length;n++)if(t===e.keys[n])return e.values[n]}add(e,t){const n=this._loadRoot(),r=this._addToNode(n,e,t);let i;if(r.newNode)i=r.newNode;else{const e=this._saveNode(r.left),t=this._saveNode(r.right);i=new be(this.nextNodeId++,!1,[r.splitKey],[],[e,t],null)}const s=this._saveNode(i);this.rootPointer=s,this._size++,this._saveMetadata()}_addToNode(e,t,n){if(e.isLeaf){const r=[...e.keys],i=[...e.values],s=r.indexOf(t);if(-1!==s)return i[s]=n,{newNode:new be(e.id,!0,r,i,[],null)};let o=0;for(;o<r.length&&t>r[o];)o++;if(r.splice(o,0,t),i.splice(o,0,n),r.length<this.order)return{newNode:new be(e.id,!0,r,i,[],null)};{const t=Math.ceil(r.length/2),n=r.slice(0,t),s=i.slice(0,t),o=r.slice(t),a=i.slice(t),c=new be(this.nextNodeId++,!0,o,a,[],null);return{left:new be(e.id,!0,n,s,[],null),right:c,splitKey:o[0]}}}{const r=[...e.keys],i=[...e.children];let s=0;for(;s<r.length&&t>=r[s];)s++;const o=this._loadNode(i[s]),a=this._addToNode(o,t,n);if(a.newNode){const t=this._saveNode(a.newNode);return i[s]=t,{newNode:new be(e.id,!1,r,[],i,null)}}{const t=this._saveNode(a.left),n=this._saveNode(a.right);if(r.splice(s,0,a.splitKey),i.splice(s,1,t,n),r.length<this.order)return{newNode:new be(e.id,!1,r,[],i,null)};{const t=Math.ceil(r.length/2)-1,n=r[t],s=r.slice(0,t),o=r.slice(t+1),a=i.slice(0,t+1),c=i.slice(t+1);return{left:new be(e.id,!1,s,[],a,null),right:new be(this.nextNodeId++,!1,o,[],c,null),splitKey:n}}}}}delete(e){const t=this._loadRoot(),n=this._deleteFromNode(t,e);if(!n)return;let r=n;0===r.keys.length&&!r.isLeaf&&r.children.length>0&&(r=this._loadNode(r.children[0]));const i=this._saveNode(r);this.rootPointer=i,this._size--,this._saveMetadata()}_deleteFromNode(e,t){if(e.isLeaf){const n=e.keys.indexOf(t);if(-1===n)return null;const r=[...e.keys],i=[...e.values];return r.splice(n,1),i.splice(n,1),new be(e.id,!0,r,i,[],e.next)}{let n=0;for(;n<e.keys.length&&t>=e.keys[n];)n++;const r=this._loadNode(e.children[n]),i=this._deleteFromNode(r,t);if(!i)return null;const s=[...e.children],o=this._saveNode(i);return s[n]=o,new be(e.id,!1,[...e.keys],[],s,null)}}toArray(){const e=[];return this._collectAllEntries(this._loadRoot(),e),e}async*[Symbol.asyncIterator](){if(!this.isOpen)throw new Error("Tree must be open before iteration");0!==this._size&&(yield*this._iterateNode(this._loadRoot()))}*_iterateNode(e){if(e.isLeaf)for(let t=0;t<e.keys.length;t++)yield{key:e.keys[t],value:e.values[t]};else for(const t of e.children){const e=this._loadNode(t);yield*this._iterateNode(e)}}_collectAllEntries(e,t){if(e.isLeaf)for(let n=0;n<e.keys.length;n++)t.push({key:e.keys[n],value:e.values[n]});else for(const n of e.children){const e=this._loadNode(n);this._collectAllEntries(e,t)}}size(){return this._size}isEmpty(){return 0===this._size}rangeSearch(e,t){const n=[];return this._rangeSearchNode(this._loadRoot(),e,t,n),n}_rangeSearchNode(e,t,n,r){if(e.isLeaf)for(let i=0;i<e.keys.length;i++)e.keys[i]>=t&&e.keys[i]<=n&&r.push({key:e.keys[i],value:e.values[i]});else for(const i of e.children){const e=this._loadNode(i);this._rangeSearchNode(e,t,n,r)}}getHeight(){let e=0,t=this._loadRoot();for(;!t.isLeaf;)e++,t=this._loadNode(t.children[0]);return e}async compact(e){if(!this.isOpen)throw new Error("Tree file is not open");if(!e)throw new Error("Destination sync handle is required for compaction");const t=this.file.getFileSize(),n=this.toArray(),r=new xe(e,this.order);await r.open();for(const s of n)await r.add(s.key,s.value);const i=r.file.getFileSize();return await r.close(),{oldSize:t,newSize:i,bytesSaved:Math.max(0,t-i)}}}const _e=/* @__PURE__ */new Set(["a","about","after","all","also","am","an","and","another","any","are","around","as","at","be","because","been","before","being","between","both","but","by","came","can","come","could","did","do","each","for","from","get","got","has","had","he","have","her","here","him","himself","his","how","i","if","in","into","is","it","like","make","many","me","might","more","most","much","must","my","never","now","of","on","only","or","other","our","out","over","said","same","see","should","since","some","still","such","take","than","that","the","their","them","then","there","these","they","this","those","through","to","too","under","up","very","was","way","we","well","were","what","where","which","while","who","with","would","you","your"]);function ve(e){if("string"!=typeof e)return[];return e.toLowerCase().split(/\W+/).filter(e=>e.length>0).filter(e=>!_e.has(e))}class $e{constructor(e={}){const{order:t=16,trees:n}=e;this.order=t,this.index=n?.index||null,this.documentTerms=n?.documentTerms||null,this.documentLengths=n?.documentLengths||null,this.isOpen=!1}async open(){if(this.isOpen)throw new Error("TextIndex is already open");if(!this.index||!this.documentTerms||!this.documentLengths)throw new Error("Trees must be initialized before opening");await Promise.all([this.index.open(),this.documentTerms.open(),this.documentLengths.open()]),this.isOpen=!0}async close(){this.isOpen&&(await Promise.all([this.index.close(),this.documentTerms.close(),this.documentLengths.close()]),this.isOpen=!1)}_ensureOpen(){if(!this.isOpen)throw new Error("TextIndex is not open")}async add(e,t){if(this._ensureOpen(),!e)throw new Error("Document ID is required");const n=ve(t),r=/* @__PURE__ */new Map;n.forEach(e=>{const t=we(e);r.set(t,(r.get(t)||0)+1)});for(const[o,a]of r.entries()){const t=await this.index.search(o)||{};t[e]=a,await this.index.add(o,t)}const i={...await this.documentTerms.search(e)||{}};r.forEach((e,t)=>{i[t]=e});const s=Object.values(i).reduce((e,t)=>e+t,0);await this.documentTerms.add(e,i),await this.documentLengths.add(e,s)}async remove(e){this._ensureOpen();const t=await this.documentTerms.search(e);if(!t)return!1;for(const[n]of Object.entries(t)){const t=await this.index.search(n)||{};delete t[e],0===Object.keys(t).length?await this.index.delete(n):await this.index.add(n,t)}return await this.documentTerms.delete(e),await this.documentLengths.delete(e),!0}async query(e,t={scored:!0,requireAll:!1}){this._ensureOpen();const n=ve(e);if(0===n.length)return[];const r=n.map(e=>we(e)),i=[...new Set(r)];if(t.requireAll){const e=[];for(const n of i){const t=await this.index.search(n);e.push(new Set(Object.keys(t||{})))}if(0===e.length)return[];const t=new Set(e[0]);for(let n=1;n<e.length;n++)for(const r of[...t])e[n].has(r)||t.delete(r);return Array.from(t)}const s=await this.documentLengths.toArray(),o=new Map(s.map(({key:e,value:t})=>[String(e),t||1])),a=s.length,c=/* @__PURE__ */new Map;for(const h of i){const e=await this.index.search(h),t=e?Object.keys(e).length:0;t>0&&c.set(h,Math.log(a/t))}const l=/* @__PURE__ */new Map;for(const h of i){const e=await this.index.search(h);if(e)for(const[t,n]of Object.entries(e)){const e=n/(o.get(t)||1),r=c.get(h)||0,i=l.get(t)||0;l.set(t,i+e*r)}}for(const[h,f]of l.entries()){const e=await this.documentTerms.search(h)||{},t=i.filter(t=>!!e[t]).length/i.length;l.set(h,f*(1+t))}const u=Array.from(l.entries()).map(([e,t])=>({id:e,score:t})).sort((e,t)=>t.score-e.score);return!1===t.scored?u.map(e=>e.id):u}async getTermCount(){this._ensureOpen();return(await this.index.toArray()).length}async getDocumentCount(){this._ensureOpen();return(await this.documentTerms.toArray()).length}async clear(){this._ensureOpen();const[e,t,n]=await Promise.all([this.index.toArray(),this.documentTerms.toArray(),this.documentLengths.toArray()]);for(const r of e)await this.index.delete(r.key);for(const r of t)await this.documentTerms.delete(r.key);for(const r of n)await this.documentLengths.delete(r.key)}async compact({index:e,documentTerms:t,documentLengths:n}){if(this._ensureOpen(),!e||!t||!n)throw new Error("Destination trees must be provided for compaction");const r=await this.index.compact(e.file.syncAccessHandle),i=await this.documentTerms.compact(t.file.syncAccessHandle),s=await this.documentLengths.compact(n.file.syncAccessHandle);return await this.close(),this.isOpen=!1,{terms:r,documents:i,lengths:s}}}function Ie(e,t){if(null==e)return e;if("boolean"==typeof e||"number"==typeof e)return e;if("string"==typeof e)return e.startsWith("$$")?"$$KEEP"===e||"$$PRUNE"===e||"$$DESCEND"===e?e:v(t,e.substring(2)):"$"===e.charAt(0)?v(t,e.substring(1)):e;if("object"==typeof e){if(Array.isArray(e))return e.map(e=>Ie(e,t));const n=Object.keys(e);if(0===n.length)return e;const r=n[0];if("$"===r.charAt(0)){return function(e,t,n){switch(e){case"$add":return function(e,t){if(!Array.isArray(e))return null;let n=0;for(const r of e){const e=Ie(r,t);e instanceof Date?n+=e.getTime():"number"==typeof e&&(n+=e)}return n}(t,n);case"$subtract":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);if(n instanceof Date&&r instanceof Date)return n.getTime()-r.getTime();if(n instanceof Date&&"number"==typeof r)return new Date(n.getTime()-r);if("number"==typeof n&&"number"==typeof r)return n-r;return null}(t,n);case"$multiply":return function(e,t){if(!Array.isArray(e))return null;let n=1;for(const r of e){const e=Ie(r,t);"number"==typeof e&&(n*=e)}return n}(t,n);case"$divide":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);if("number"==typeof n&&"number"==typeof r&&0!==r)return n/r;return null}(t,n);case"$mod":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);if("number"==typeof n&&"number"==typeof r&&0!==r)return n%r;return null}(t,n);case"$pow":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);if("number"==typeof n&&"number"==typeof r)return Math.pow(n,r);return null}(t,n);case"$sqrt":return function(e,t){const n=Ie(e,t);if("number"==typeof n&&n>=0)return Math.sqrt(n);return null}(t,n);case"$abs":return function(e,t){const n=Ie(e,t);if("number"==typeof n)return Math.abs(n);return null}(t,n);case"$ceil":return function(e,t){const n=Ie(e,t);if("number"==typeof n)return Math.ceil(n);return null}(t,n);case"$floor":return function(e,t){const n=Ie(e,t);if("number"==typeof n)return Math.floor(n);return null}(t,n);case"$trunc":return function(e,t){const n=Ie(e,t);if("number"==typeof n)return Math.trunc(n);return null}(t,n);case"$round":return function(e,t){const n=Ie(Array.isArray(e)?e[0]:e,t),r=Array.isArray(e)&&void 0!==e[1]?Ie(e[1],t):0;if("number"==typeof n&&"number"==typeof r){const e=Math.pow(10,r);return Math.round(n*e)/e}return null}(t,n);case"$concat":return function(e,t){if(!Array.isArray(e))return null;let n="";for(const r of e){const e=Ie(r,t);null!=e&&(n+=String(e))}return n}(t,n);case"$substr":return function(e,t){if(!Array.isArray(e)||e.length<3)return null;const n=String(Ie(e[0],t)||""),r=Ie(e[1],t),i=Ie(e[2],t);if("number"==typeof r&&"number"==typeof i)return n.substr(r,i);return null}(t,n);case"$toLower":return function(e,t){const n=Ie(e,t);return null!=n?String(n).toLowerCase():""}(t,n);case"$toUpper":return function(e,t){const n=Ie(e,t);return null!=n?String(n).toUpperCase():""}(t,n);case"$trim":return function(e,t){const n=Ie("object"==typeof e&&e.input?e.input:e,t),r=e.chars?Ie(e.chars,t):null;let i=null!=n?String(n):"";if(r){const e=new RegExp(`^[${Ne(r)}]+|[${Ne(r)}]+$`,"g");return i.replace(e,"")}return i.trim()}(t,n);case"$ltrim":return function(e,t){const n=Ie("object"==typeof e&&e.input?e.input:e,t),r=e.chars?Ie(e.chars,t):null;let i=null!=n?String(n):"";if(r){const e=new RegExp(`^[${Ne(r)}]+`,"g");return i.replace(e,"")}return i.replace(/^\s+/,"")}(t,n);case"$rtrim":return function(e,t){const n=Ie("object"==typeof e&&e.input?e.input:e,t),r=e.chars?Ie(e.chars,t):null;let i=null!=n?String(n):"";if(r){const e=new RegExp(`[${Ne(r)}]+$`,"g");return i.replace(e,"")}return i.replace(/\s+$/,"")}(t,n);case"$split":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=String(Ie(e[0],t)||""),r=String(Ie(e[1],t)||"");return n.split(r)}(t,n);case"$strLenCP":return function(e,t){const n=Ie(e,t);return null!=n?String(n).length:0}(t,n);case"$strcasecmp":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=String(Ie(e[0],t)||"").toLowerCase(),r=String(Ie(e[1],t)||"").toLowerCase();return n<r?-1:n>r?1:0}(t,n);case"$indexOfCP":return function(e,t){if(!Array.isArray(e)||e.length<2)return null;const n=String(Ie(e[0],t)||""),r=String(Ie(e[1],t)||""),i=void 0!==e[2]?Ie(e[2],t):0,s=void 0!==e[3]?Ie(e[3],t):n.length,o=n.substring(i,s).indexOf(r);return-1===o?-1:o+i}(t,n);case"$replaceOne":return function(e,t){const n=String(Ie(e.input,t)||""),r=String(Ie(e.find,t)||""),i=String(Ie(e.replacement,t)||"");return n.replace(r,i)}(t,n);case"$replaceAll":return function(e,t){const n=String(Ie(e.input,t)||""),r=String(Ie(e.find,t)||""),i=String(Ie(e.replacement,t)||"");return n.split(r).join(i)}(t,n);case"$cmp":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);return n<r?-1:n>r?1:0}(t,n);case"$eq":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);return n===r}(t,n);case"$ne":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);return n!==r}(t,n);case"$gt":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);return n>r}(t,n);case"$gte":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);return n>=r}(t,n);case"$lt":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);return n<r}(t,n);case"$lte":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);return n<=r}(t,n);case"$and":return function(e,t){if(!Array.isArray(e))return null;for(const n of e){if(!Ie(n,t))return!1}return!0}(t,n);case"$or":return function(e,t){if(!Array.isArray(e))return null;for(const n of e){if(Ie(n,t))return!0}return!1}(t,n);case"$not":return function(e,t){const n=Ie(Array.isArray(e)?e[0]:e,t);return!n}(t,n);case"$cond":return function(e,t){let n,r,i;if(Array.isArray(e)){if(3!==e.length)return null;[n,r,i]=e}else{if("object"!=typeof e)return null;n=e.if,r=e.then,i=e.else}const s=Ie(n,t);return Ie(s?r:i,t)}(t,n);case"$ifNull":return function(e,t){if(!Array.isArray(e)||e.length<2)return null;for(let n=0;n<e.length;n++){const r=Ie(e[n],t);if(null!=r)return r}return null}(t,n);case"$switch":return function(e,t){if("object"!=typeof e||!Array.isArray(e.branches))return null;for(const n of e.branches){if(Ie(n.case,t))return Ie(n.then,t)}return void 0!==e.default?Ie(e.default,t):null}(t,n);case"$year":return function(e,t){const n=Ie(e,t);if(n instanceof Date)return n.getUTCFullYear();return null}(t,n);case"$month":return function(e,t){const n=Ie(e,t);if(n instanceof Date)return n.getUTCMonth()+1;return null}(t,n);case"$dayOfMonth":return function(e,t){const n=Ie(e,t);if(n instanceof Date)return n.getUTCDate();return null}(t,n);case"$dayOfWeek":return function(e,t){const n=Ie(e,t);if(n instanceof Date)return n.getUTCDay()+1;return null}(t,n);case"$dayOfYear":return function(e,t){const n=Ie(e,t);if(n instanceof Date){const e=new Date(Date.UTC(n.getUTCFullYear(),0,0)),t=n-e,r=864e5;return Math.floor(t/r)}return null}(t,n);case"$hour":return function(e,t){const n=Ie(e,t);if(n instanceof Date)return n.getUTCHours();return null}(t,n);case"$minute":return function(e,t){const n=Ie(e,t);if(n instanceof Date)return n.getUTCMinutes();return null}(t,n);case"$second":return function(e,t){const n=Ie(e,t);if(n instanceof Date)return n.getUTCSeconds();return null}(t,n);case"$millisecond":return function(e,t){const n=Ie(e,t);if(n instanceof Date)return n.getUTCMilliseconds();return null}(t,n);case"$week":return function(e,t){const n=Ie(e,t);if(n instanceof Date){const e=new Date(Date.UTC(n.getUTCFullYear(),0,1));return Math.ceil(((n-e)/864e5+e.getUTCDay()+1)/7)-1}return null}(t,n);case"$isoWeek":return function(e,t){const n=Ie(e,t);if(n instanceof Date){const e=new Date(n.valueOf()),t=(n.getUTCDay()+6)%7;e.setUTCDate(e.getUTCDate()-t+3);const r=e.valueOf();return e.setUTCMonth(0,1),4!==e.getUTCDay()&&e.setUTCMonth(0,1+(4-e.getUTCDay()+7)%7),1+Math.ceil((r-e)/6048e5)}return null}(t,n);case"$isoWeekYear":return function(e,t){const n=Ie(e,t);if(n instanceof Date){const e=new Date(n.valueOf());return e.setUTCDate(e.getUTCDate()-(n.getUTCDay()+6)%7+3),e.getUTCFullYear()}return null}(t,n);case"$dateToString":return function(e,t){const n=e.format?Ie(e.format,t):"%Y-%m-%dT%H:%M:%S.%LZ",r=Ie(e.date,t);return r instanceof Date?n.replace("%Y",r.getUTCFullYear()).replace("%m",String(r.getUTCMonth()+1).padStart(2,"0")).replace("%d",String(r.getUTCDate()).padStart(2,"0")).replace("%H",String(r.getUTCHours()).padStart(2,"0")).replace("%M",String(r.getUTCMinutes()).padStart(2,"0")).replace("%S",String(r.getUTCSeconds()).padStart(2,"0")).replace("%L",String(r.getUTCMilliseconds()).padStart(3,"0")):null}(t,n);case"$toDate":return function(e,t){const n=Ie(e,t);if(n instanceof Date)return n;if("string"==typeof n||"number"==typeof n){const e=new Date(n);return isNaN(e.getTime())?null:e}return null}(t,n);case"$arrayElemAt":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);if(!Array.isArray(n)||"number"!=typeof r)return null;const i=r<0?n.length+r:r;return n[i]}(t,n);case"$concatArrays":return function(e,t){if(!Array.isArray(e))return null;const n=[];for(const r of e){const e=Ie(r,t);Array.isArray(e)&&n.push(...e)}return n}(t,n);case"$filter":return function(e,t){const n=Ie(e.input,t),r=e.as||"this",i=e.cond;return Array.isArray(n)?n.filter(e=>{const n={...t,[r]:e};return Ie(i,n)}):null}(t,n);case"$in":return function(e,t){if(!Array.isArray(e)||2!==e.length)return null;const n=Ie(e[0],t),r=Ie(e[1],t);return!!Array.isArray(r)&&r.includes(n)}(t,n);case"$indexOfArray":return function(e,t){if(!Array.isArray(e)||e.length<2)return null;const n=Ie(e[0],t),r=Ie(e[1],t),i=void 0!==e[2]?Ie(e[2],t):0,s=void 0!==e[3]?Ie(e[3],t):n.length;if(!Array.isArray(n))return null;for(let o=i;o<s&&o<n.length;o++)if(n[o]===r)return o;return-1}(t,n);case"$isArray":return function(e,t){const n=Ie(e,t);return Array.isArray(n)}(t,n);case"$map":return function(e,t){const n=Ie(e.input,t),r=e.as||"this",i=e.in;return Array.isArray(n)?n.map(e=>{const n={...t,[r]:e};return Ie(i,n)}):null}(t,n);case"$reduce":return function(e,t){const n=Ie(e.input,t),r=Ie(e.initialValue,t),i=e.in;if(!Array.isArray(n))return null;let s=r;for(const o of n){s=Ie(i,{...t,value:s,this:o})}return s}(t,n);case"$size":return function(e,t){const n=Ie(e,t);return Array.isArray(n)?n.length:null}(t,n);case"$slice":return function(e,t){if(!Array.isArray(e)||e.length<2)return null;const n=Ie(e[0],t);if(!Array.isArray(n))return null;if(2===e.length){const r=Ie(e[1],t);return r>=0?n.slice(0,r):n.slice(r)}{const r=Ie(e[1],t),i=Ie(e[2],t);return n.slice(r,r+i)}}(t,n);case"$reverseArray":return function(e,t){const n=Ie(e,t);return Array.isArray(n)?n.slice().reverse():null}(t,n);case"$zip":return function(e,t){const n=e.inputs?Ie(e.inputs,t):null,r=e.useLongestLength||!1,i=e.defaults;if(!Array.isArray(n))return null;const s=n.map(e=>Ie(e,t));if(!s.every(e=>Array.isArray(e)))return null;const o=Math.max(...s.map(e=>e.length)),a=r?o:Math.min(...s.map(e=>e.length)),c=[];for(let l=0;l<a;l++){const e=[];for(let t=0;t<s.length;t++)l<s[t].length?e.push(s[t][l]):i&&t<i.length?e.push(i[t]):e.push(null);c.push(e)}return c}(t,n);case"$type":return function(e,t){const n=Ie(e,t);return null===n?"null":void 0===n?"missing":"boolean"==typeof n?"bool":"number"==typeof n?Number.isInteger(n)?"int":"double":"string"==typeof n?"string":n instanceof Date?"date":Array.isArray(n)?"array":"object"==typeof n?"object":"unknown"}(t,n);case"$convert":return function(e,t){const n=Ie(e.input,t),r=e.to,i=e.onError,s=e.onNull;if(null===n)return void 0!==s?Ie(s,t):null;try{switch(r){case"double":case"decimal":return parseFloat(n);case"int":case"long":return parseInt(n);case"bool":return Boolean(n);case"string":return String(n);case"date":return new Date(n);default:return n}}catch(o){return void 0!==i?Ie(i,t):null}}(t,n);case"$toBool":return function(e,t){const n=Ie(e,t);return Boolean(n)}(t,n);case"$toDecimal":return function(e,t){const n=Ie(e,t);return parseFloat(n)}(t,n);case"$toDouble":return function(e,t){const n=Ie(e,t);return parseFloat(n)}(t,n);case"$toInt":return function(e,t){const n=Ie(e,t);return parseInt(n)}(t,n);case"$toLong":return function(e,t){const n=Ie(e,t);return parseInt(n)}(t,n);case"$toString":return function(e,t){const n=Ie(e,t);return null==n?null:String(n)}(t,n);case"$objectToArray":return function(e,t){const n=Ie(e,t);if("object"!=typeof n||null===n||Array.isArray(n))return null;return Object.keys(n).map(e=>({k:e,v:n[e]}))}(t,n);case"$arrayToObject":return function(e,t){const n=Ie(e,t);if(!Array.isArray(n))return null;const r={};for(const i of n)Array.isArray(i)&&2===i.length?r[i[0]]=i[1]:"object"==typeof i&&void 0!==i.k&&void 0!==i.v&&(r[i.k]=i.v);return r}(t,n);case"$mergeObjects":return function(e,t){if(!Array.isArray(e))return Ie(e,t);const n={};for(const r of e){const e=Ie(r,t);"object"!=typeof e||null===e||Array.isArray(e)||Object.assign(n,e)}return n}(t,n);case"$literal":return t;default:throw new Error(`Unsupported aggregation operator: ${e}`)}}(r,e[r],t)}{const r={};for(const i of n)r[i]=Ie(e[i],t);return r}}return e}function Ne(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}const Se={1:"double",2:"string",3:"object",4:"array",5:"binData",6:"undefined",7:"objectId",8:"bool",9:"date",10:"null",11:"regex",13:"javascript",15:"javascriptWithScope",16:"int",17:"timestamp",18:"long",19:"decimal",127:"maxKey","-1":"minKey"},Oe=Object.entries(Se).reduce((e,[t,n])=>(e[n]=parseInt(t),e),{});function Ae(e,t){if(N(t)){for(let n=0;n<t.length;n++)if(Ae(e,t[n]))return!0;return!1}const n="number"==typeof t?t:Oe[t],r=Se[n]||t;return null===e?"null"===r||10===n:void 0===e?"undefined"===r||6===n:"number"==typeof e?Number.isInteger(e)?"int"===r||16===n:"double"===r||1===n:"string"==typeof e?"string"===r||2===n:"boolean"==typeof e?"bool"===r||8===n:e instanceof Date?"date"===r||9===n:e instanceof g?"objectId"===r||7===n:e instanceof RegExp?"regex"===r||11===n:N(e)?"array"===r||4===n:"object"==typeof e?"object"===r||3===n:typeof e===t}function Ce(e){if(N(e)){let t=0;for(let n=0;n<e.length;n++)t|=1<<e[n];return t}return"number"==typeof e?e:0}function Ee(e,t){if("number"!=typeof e)return!1;const n=Ce(t);return(e&n)===n}function je(e,t){if("number"!=typeof e)return!1;return 0===(e&Ce(t))}function De(e,t){if("number"!=typeof e)return!1;return 0!==(e&Ce(t))}function ke(e,t){if("number"!=typeof e)return!1;const n=Ce(t);return(e&n)!==n}function Pe(e,t){if(t.type){const n=N(e)?"array":null===e?"null":typeof e;if(t.type!==n)return!1}if(t.required&&N(t.required))for(let n=0;n<t.required.length;n++)if(!(t.required[n]in e))return!1;if(t.properties)for(const n in t.properties){if(!(n in e))return!1;const r=t.properties[n];if(!Pe(e[n],r))return!1}if(void 0!==t.minimum&&"number"==typeof e&&e<t.minimum)return!1;if(void 0!==t.maximum&&"number"==typeof e&&e>t.maximum)return!1;if(void 0!==t.minLength&&"string"==typeof e&&e.length<t.minLength)return!1;if(void 0!==t.maxLength&&"string"==typeof e&&e.length>t.maxLength)return!1;if(t.pattern&&"string"==typeof e){if(!new RegExp(t.pattern).test(e))return!1}return!(t.enum&&N(t.enum)&&!t.enum.includes(e))}function Me(e,t){return e instanceof g&&t instanceof g?e.equals(t):e==t}function Le(e,t,n){let r=e,i=t;switch(e instanceof g&&(r=e.toString()),t instanceof g&&(i=t.toString()),n){case">":return r>i;case">=":return r>=i;case"<":return r<i;case"<=":return r<=i;default:return!1}}function Te(e,t){if(void 0===e)return!1;if(null===e)return t(e);if(N(e)){for(var n=0;n<e.length;n++)if(t(e[n]))return!0;return!1}return t(e)}function Fe(e){if("string"!=typeof e)return[];return ve(e).map(e=>we(e))}function Be(e,t){if("string"!=typeof e)return!1;const n=new Set(Fe(e));return Fe(t).some(e=>n.has(e))}function ze(e,t){try{if(!Array.isArray(t)||2!==t.length)return!1;const n=t[0][0],r=t[0][1],i=t[1][0];return Ue(e,n,i,t[1][1],r)}catch(n){return!1}}function Ue(e,t,n,r,i){if(!e)return!1;if("FeatureCollection"===e.type&&e.features&&e.features.length>0){for(const s of e.features)if(s.geometry&&!Ue(s.geometry,t,n,r,i))return!1;return!0}if("Feature"===e.type&&e.geometry)return Ue(e.geometry,t,n,r,i);if("Point"===e.type&&e.coordinates){const[s,o]=e.coordinates;if("number"==typeof s&&"number"==typeof o)return s>=t&&s<=n&&o>=r&&o<=i}if("Polygon"===e.type&&e.coordinates&&e.coordinates.length>0){for(const s of e.coordinates)for(const e of s){const s=e[0],o=e[1];if(s<t||s>n||o<r||o>i)return!1}return!0}return!1}function Re(e){if(!e)return null;if("FeatureCollection"===e.type&&e.features&&e.features.length>0){const t=e.features[0];if(t.geometry)return Re(t.geometry)}if("Feature"===e.type&&e.geometry)return Re(e.geometry);if("Point"===e.type&&e.coordinates){const[t,n]=e.coordinates;if("number"==typeof t&&"number"==typeof n)return{lat:n,lng:t}}if("Polygon"===e.type&&e.coordinates&&e.coordinates.length>0){const t=e.coordinates[0];if(t.length>0){let e=0,n=0;for(const r of t)n+=r[0],e+=r[1];return{lat:e/t.length,lng:n/t.length}}}return null}function qe(e,t,n,r){const i=(n-e)*Math.PI/180,s=(r-t)*Math.PI/180,o=Math.sin(i/2)*Math.sin(i/2)+Math.cos(e*Math.PI/180)*Math.cos(n*Math.PI/180)*Math.sin(s/2)*Math.sin(s/2);return 6371*(2*Math.atan2(Math.sqrt(o),Math.sqrt(1-o)))}function Ve(e,t,n,r){const i=Re(e);if(!i)return!1;return 1e3*qe(i.lat,i.lng,n,t)<=r}function He(e,t){if(!e||!t)return!1;const n=Re(t);if(!n)return!1;const r=Re(e);if(!r)return!1;if("Polygon"===t.type&&"Point"===e.type)return We(r.lng,r.lat,t.coordinates[0]);if("Polygon"===e.type&&"Point"===t.type){const n=t.coordinates;return We(n[0],n[1],e.coordinates[0])}if("Point"===e.type&&"Point"===t.type){return qe(r.lat,r.lng,n.lat,n.lng)<.001}return!1}function We(e,t,n){let r=!1;for(let i=0,s=n.length-1;i<n.length;s=i++){const o=n[i][0],a=n[i][1],c=n[s][0],l=n[s][1];a>t!=l>t&&e<(c-o)*(t-a)/(l-a)+o&&(r=!r)}return r}function Qe(e,t){if("function"==typeof t)try{return t.call(e)}catch(n){return!1}else if("string"==typeof t)try{return new Function("return "+t).call(e)}catch(n){return!1}return!1}function Je(e,t){var n=Object.keys(t)[0],r=t[n];if("$"!=n.charAt(0))return Ke(e,n,r);if("$and"==n)return Ge(e,r);if("$or"==n)return function(e,t){for(var n=0;n<t.length;n++)if(Je(e,t[n]))return!0;return!1}(e,r);if("$not"==n)return function(e,t){return!Je(e,t)}(e,r);if("$nor"==n)return function(e,t){for(var n=0;n<t.length;n++)if(Je(e,t[n]))return!1;return!0}(e,r);if("$where"==n)return Qe(e,r);if("$comment"==n)return!0;if("$jsonSchema"==n)return Pe(e,r);if("$text"==n){return function(e,t){return!(!e||"object"!=typeof e)&&function e(n){if("string"==typeof n)return Be(n,t);if("object"!=typeof n||null===n)return!1;if(N(n)){for(let t=0;t<n.length;t++)if(e(n[t]))return!0;return!1}for(const t in n)if(n.hasOwnProperty(t)&&e(n[t]))return!0;return!1}(e)}(e,r.$search||r)}if("$expr"!=n)throw{$err:"Can't canonicalize query: BadValue unknown top level operator: "+n,code:17287};try{return Ie(r,e)}catch(i){return!1}}function Ke(e,t,n){var r=$(e,t);if("string"==typeof n)return Te(r,function(e){return Me(e,n)});if("number"==typeof n)return Te(r,function(e){return Me(e,n)});if("boolean"==typeof n)return Te(r,function(e){return Me(e,n)});if(n instanceof g)return Te(r,function(e){return Me(e,n)});if("object"==typeof n){if(n instanceof RegExp)return null!=r&&Te(r,function(e){return e&&e.match(n)});if(N(n))return null!=r&&Te(r,function(e){return e&&A(e,n)});var i=Object.keys(n);if("$"==i[0].charAt(0)){for(var s=0;s<i.length;s++){var o=Object.keys(n)[s],a=n[o];if("$eq"==o){if(!Te(r,function(e){return Me(e,a)}))return!1}else if("$gt"==o){if(!Te(r,function(e){return Le(e,a,">")}))return!1}else if("$gte"==o){if(!Te(r,function(e){return Le(e,a,">=")}))return!1}else if("$lt"==o){if(!Te(r,function(e){return Le(e,a,"<")}))return!1}else if("$lte"==o){if(!Te(r,function(e){return Le(e,a,"<=")}))return!1}else if("$ne"==o){if(!Te(r,function(e){return!Me(e,a)}))return!1}else if("$in"==o){if(!Te(r,function(e){return O(e,a)}))return!1}else if("$nin"==o){if(Te(r,function(e){return O(e,a)}))return!1}else if("$exists"==o){var c=v(e,t);if(a?null==c:null!=c)return!1}else if("$type"==o){if(void 0===r){if(6!==("number"==typeof a?a:Oe[a]))return!1}else if(!Ae(r,a))return!1}else if("$mod"==o){if(2!=a.length)throw{$err:"Can't canonicalize query: BadValue malformed mod, not enough elements",code:17287};if(!Te(r,function(e){return null!=e&&e%a[0]==a[1]}))return!1}else if("$regex"==o){var l=a,u=n.$options||"",h="string"==typeof l?new RegExp(l,u):l;if(!Te(r,function(e){return null!=e&&h.test(e)}))return!1}else{if("$options"==o)continue;if("$text"==o){if(!Te(r,function(e){return null!=e&&Be(e,a)}))return!1}else if("$expr"==o)try{if(!Ie(a,e))return!1}catch(S){return!1}else if("$geoWithin"==o){if(!Te(r,function(e){return null!=e&&ze(e,a)}))return!1}else if("$near"==o||"$nearSphere"==o){let e;if(a.$geometry?e=a.$geometry.coordinates:a.coordinates?e=a.coordinates:Array.isArray(a)&&(e=a),!(e&&e.length>=2))return!1;{const[t,n]=e,i=a.$maxDistance||1e6;if(!Te(r,function(e){return null!=e&&Ve(e,t,n,i)}))return!1}}else if("$geoIntersects"==o){const e=a.$geometry||a;if(!Te(r,function(t){return null!=t&&He(t,e)}))return!1}else if("$not"==o){if(Ke(e,t,a))return!1}else if("$all"==o){if(null==(d=v(e,t))||!N(d))return!1;for(var f=0;f<a.length;f++)if(!O(a[f],d))return!1}else if("$elemMatch"==o){var d;if(null==(d=v(e,t))||!N(d))return!1;var p=!1;for(f=0;f<d.length;f++){var m=d[f];if("object"!=typeof m||N(m)){for(var y=!0,w=Object.keys(a),b=0;b<w.length;b++){var x=w[b],_=a[x];("$gte"!=x||m>=_)&&("$gt"!=x||m>_)&&("$lte"!=x||m<=_)&&("$lt"!=x||m<_)?"$eq"==x&&m!=_||"$ne"==x&&m==_?y=!1:"$in"!=x||O(m,_)?"$nin"==x&&O(m,_)&&(y=!1):y=!1:y=!1}if(y){p=!0;break}}else if(Ye(m,a)){p=!0;break}}if(!p)return!1}else if("$size"==o){var I=v(e,t);if(null==I||!N(I))return!1;if(I.length!=a)return!1}else if("$bitsAllSet"==o){if(!Te(r,function(e){return Ee(e,a)}))return!1}else if("$bitsAllClear"==o){if(!Te(r,function(e){return je(e,a)}))return!1}else if("$bitsAnySet"==o){if(!Te(r,function(e){return De(e,a)}))return!1}else{if("$bitsAnyClear"!=o)throw{$err:"Can't canonicalize query: BadValue unknown operator: "+o,code:17287};if(!Te(r,function(e){return ke(e,a)}))return!1}}}return!0}return v(e,t)&&C(v(e,t),n)}}function Ge(e,t){for(var n=0;n<t.length;n++)if(!Je(e,t[n]))return!1;return!0}function Ye(e,t){return Ge(e,S(t))}function Xe(e,t){const n={};return{matched:Ze(e,S(t),n),arrayFilters:n}}function Ze(e,t,n){for(var r=0;r<t.length;r++)if(!et(e,t[r],n))return!1;return!0}function et(e,t,n){var r=Object.keys(t)[0],i=t[r];if("$"!=r.charAt(0))return function(e,t,n,r){const i=t.split(".")[0],s=$(e,t),o=(n,s)=>{if(void 0===n)return!1;if(null===n)return s(n);if(N(n)){if(N(v(e,i))){for(var o=0;o<n.length;o++)if(s(n[o]))return r[t]=o,!0;return!1}}return Te(n,s)};if("string"==typeof n)return o(s,function(e){return Me(e,n)});if("number"==typeof n)return o(s,function(e){return Me(e,n)});if("boolean"==typeof n)return o(s,function(e){return Me(e,n)});if(n instanceof g)return o(s,function(e){return Me(e,n)});if("object"==typeof n){if(n instanceof RegExp)return null!=s&&o(s,function(e){return e&&e.match(n)});if(N(n))return null!=s&&o(s,function(e){return e&&A(e,n)});var a=Object.keys(n);if("$"==a[0].charAt(0)){for(var c=0;c<a.length;c++){var l=a[c],u=n[l];if("$eq"==l){if(!o(s,function(e){return Me(e,u)}))return!1}else if("$gt"==l){if(!o(s,function(e){return Le(e,u,">")}))return!1}else if("$gte"==l){if(!o(s,function(e){return Le(e,u,">=")}))return!1}else if("$lt"==l){if(!o(s,function(e){return Le(e,u,"<")}))return!1}else if("$lte"==l){if(!o(s,function(e){return Le(e,u,"<=")}))return!1}else if("$ne"==l){if(!o(s,function(e){return!Me(e,u)}))return!1}else if("$in"==l){if(!o(s,function(e){return O(e,u)}))return!1}else if("$nin"==l){if(o(s,function(e){return O(e,u)}))return!1}else{if("$elemMatch"==l){var h=v(e,t);if(null==h||!N(h))return!1;for(var f=0;f<h.length;f++){var d=h[f];if("object"!=typeof d||N(d)){for(var p=!0,m=Object.keys(u),y=0;y<m.length;y++){var w=m[y],b=u[w];("$gte"!=w||d>=b)&&("$gt"!=w||d>b)&&("$lte"!=w||d<=b)&&("$lt"!=w||d<b)?("$eq"==w&&d!=b||"$ne"==w&&d==b)&&(p=!1):p=!1}if(p)return r[t]=f,!0}else if(Ye(d,u))return r[t]=f,!0}return!1}if(!Ke(e,t,n))return!1}}return!0}return null!=s&&o(s,function(e){return C(e,n)})}return!1}(e,r,i,n);if("$and"==r)return Ze(e,i,n);if("$or"==r)return function(e,t,n){for(var r=0;r<t.length;r++)if(et(e,t[r],n))return!0;return!1}(e,i,n);if("$not"==r)return!Je(e,i);if("$nor"==r)return function(e,t,n){for(var r=0;r<t.length;r++)if(et(e,t[r],n))return!1;return!0}(e,i,n);if("$where"==r)return Qe(e,i);if("$comment"==r)return!0;if("$jsonSchema"==r)return Pe(e,i);if("$expr"!=r)throw{$err:"Can't canonicalize query: BadValue unknown top level operator: "+r,code:17287};try{return Ie(i,e)}catch(s){return!1}}function tt(e){return e.split(".").map(e=>{const t=function(e){const t=e.match(/^\$\[([^\]]+)\]$/);return t?t[1]:null}(e);return{segment:e,isFilteredPositional:null!==t,identifier:t}})}function nt(e,t,n,r,i){!function e(s,o,a){if(o>=t.length)return;const c=t[o],l=o===t.length-1;if(c.isFilteredPositional){const a=c.identifier,u=i?i.find(e=>Object.keys(e).some(e=>e.startsWith(a+".")||e===a)):null;if(!i){if(!s[c.segment]){const e=t[o+1];e&&e.isFilteredPositional?s[c.segment]=[]:s[c.segment]={}}return void(l?rt(s,c.segment,n,r):e(s[c.segment],o+1))}if(!N(s))return s[c.segment]||(s[c.segment]={}),void(l?rt(s,c.segment,n,r):e(s[c.segment],o+1));for(let t=0;t<s.length;t++){const i=s[t];let c=!0;if(u){let e={},t=!1;if(Object.keys(u).forEach(n=>{if(n.startsWith(a+".")){const t=n.substring(a.length+1);e[t]=u[n]}else n===a&&(e=u[n],t=!0)}),t){c=Ye({value:i},{value:e})}else c=Ye(i,e)}c&&(l?rt(s,t,n,r):null!=i&&e(s[t],o+1))}}else{if((void 0===s[c.segment]||null===s[c.segment])&&!l){const e=t[o+1];e&&e.isFilteredPositional?s[c.segment]=[]:s[c.segment]={}}l?rt(s,c.segment,n,r):void 0!==s[c.segment]&&null!==s[c.segment]&&e(s[c.segment],o+1)}}(e,0)}function rt(e,t,n,r){switch(r){case"$set":default:e[t]=n;break;case"$inc":void 0===e[t]&&(e[t]=0),e[t]+=n;break;case"$mul":e[t]=e[t]*n;break;case"$min":e[t]=Math.min(e[t],n);break;case"$max":e[t]=Math.max(e[t],n);break;case"$unset":delete e[t]}}function it(e){return/\$\[[^\]]+\]/.test(e)}function st(e){return-1!==e.indexOf("$[]")}function ot(e,t,n){for(var r=t.split("."),i=e,s=0;s<r.length;s++){var o=r[s];if("$[]"===o){if(!Array.isArray(i))return;for(var a=r.slice(s+1).join("."),c=0;c<i.length;c++)if(a)if(-1!==a.indexOf("$[]"))ot(i[c],a,n);else{var l=n(v(i[c],a));I(i[c],a,l)}else i[c]=n(i[c]);return}if(null==i||null==i)return;i=i[o]}}function at(e,t){if(!t||!e.includes("$"))return e;const n=e.split("."),r=n.indexOf("$");if(-1===r)return e;const i=n.slice(0,r).join(".");let s=null;for(const o in t)if(o===i||o.startsWith(i+".")){s=t[o];break}return null!=s?(n[r]=s.toString(),n.join(".")):e}function ct(e,t,n,r,i){for(var s=Object.keys(e),o=0;o<s.length;o++){var a=s[o],c=e[a];if("$inc"==a)for(var l=Object.keys(c),u=0;u<l.length;u++){var h=at(l[u],r),f=c[l[u]];if(it(h)){if(!i)throw new Error("arrayFilters option is required when using filtered positional operator $[<identifier>]");nt(t,tt(h),f,"$inc",i)}else if(st(h))ot(t,h,function(e){return(void 0===e?0:e)+f});else{null==(d=v(t,h))&&(d=0),I(t,h,d+f)}}else if("$mul"==a)for(l=Object.keys(c),u=0;u<l.length;u++){h=at(l[u],r),f=c[l[u]];if(it(h)){if(!i)throw new Error("arrayFilters option is required when using filtered positional operator $[<identifier>]");nt(t,tt(h),f,"$mul",i)}else if(st(h))ot(t,h,function(e){return e*f});else{null==(d=v(t,h))&&(d=0),I(t,h,d*f)}}else if("$rename"==a)for(l=Object.keys(c),u=0;u<l.length;u++){h=at(l[u],r);t[at(c[l[u]],r)]=t[h],delete t[h]}else if("$setOnInsert"==a&&n)for(l=Object.keys(c),u=0;u<l.length;u++){t[h=at(l[u],r)]=c[l[u]]}else if("$set"==a)for(l=Object.keys(c),u=0;u<l.length;u++){if(it(h=at(l[u],r))){if(!i)throw new Error("arrayFilters option is required when using filtered positional operator $[<identifier>]");nt(t,tt(h),c[l[u]],"$set",i)}else I(t,h,c[l[u]])}else if("$unset"==a)for(l=Object.keys(c),u=0;u<l.length;u++){delete t[h=at(l[u],r)]}else if("$min"==a)for(l=Object.keys(c),u=0;u<l.length;u++){h=at(l[u],r),f=c[l[u]];if(it(h)){if(!i)throw new Error("arrayFilters option is required when using filtered positional operator $[<identifier>]");nt(t,tt(h),f,"$min",i)}else if(st(h))ot(t,h,function(e){return Math.min(e,f)});else{var d=v(t,h);I(t,h,Math.min(d,f))}}else if("$max"==a)for(l=Object.keys(c),u=0;u<l.length;u++){h=at(l[u],r),f=c[l[u]];if(it(h)){if(!i)throw new Error("arrayFilters option is required when using filtered positional operator $[<identifier>]");nt(t,tt(h),f,"$max",i)}else if(st(h))ot(t,h,function(e){return Math.max(e,f)});else{d=v(t,h);I(t,h,Math.max(d,f))}}else if("$currentDate"==a)for(l=Object.keys(c),u=0;u<l.length;u++){h=at(l[u],r);var p=c[l[u]];!0===p||"object"==typeof p&&p.$type,I(t,h,/* @__PURE__ */new Date)}else if("$addToSet"==a)for(l=Object.keys(c),u=0;u<l.length;u++){h=at(l[u],r);var g=c[l[u]];(P=v(t,h))&&Array.isArray(P)&&P.push(g)}else if("$pop"==a)for(l=Object.keys(c),u=0;u<l.length;u++){h=at(l[u],r);var m=c[l[u]];(P=v(t,h))&&Array.isArray(P)&&(1==m?P.pop():-1==m&&P.shift())}else if("$pull"==a)for(l=Object.keys(c),u=0;u<l.length;u++){h=at(l[u],r);var y=c[l[u]];if(null!=($=v(t,h))&&Array.isArray($)){for(var w=[],b=0;b<$.length;b++){var x=$[b],_=!1;if("object"!=typeof y||null===y||Array.isArray(y))_=x==y;else if("object"!=typeof x||null===x||Array.isArray(x))_=Ke({__temp:x},"__temp",y);else _=Ye(x,y);_||w.push(x)}I(t,h,w)}}else if("$pullAll"==a)for(l=Object.keys(c),u=0;u<l.length;u++){var $=v(t,h=at(l[u],r)),N=c[l[u]];for(w=[],b=0;b<$.length;b++){for(var S=!1,O=0;O<N.length;O++)if($[b]==N[O]){S=!0;break}S||w.push($[b])}I(t,h,w)}else if("$pushAll"==a)for(l=Object.keys(c),u=0;u<l.length;u++){h=at(l[u],r);var A=c[l[u]];if((P=v(t,h))&&Array.isArray(P))for(b=0;b<A.length;b++)P.push(A[b])}else if("$push"==a)for(l=Object.keys(c),u=0;u<l.length;u++){h=at(l[u],r);var C=c[l[u]];if(null!==C&&"object"==typeof C&&(void 0!==C.$each||void 0!==C.$position||void 0!==C.$slice||void 0!==C.$sort)){(P=v(t,h))||I(t,h,P=[]);var E=void 0!==C.$each?C.$each:[C],j=void 0!==C.$position?C.$position:P.length;if(j<0&&(j=Math.max(0,P.length+j)),P.splice(j,0,...E),void 0!==C.$sort){var D=C.$sort;"number"==typeof D?P.sort(function(e,t){return e<t?D>0?-1:1:e>t?D>0?1:-1:0}):"object"==typeof D&&P.sort(function(e,t){for(var n=Object.keys(D),r=0;r<n.length;r++){var i=n[r],s=D[i],o=v(e,i),a=v(t,i);if(o<a)return s>0?-1:1;if(o>a)return s>0?1:-1}return 0})}if(void 0!==C.$slice){var k=C.$slice;if(k<0)I(t,h,P.slice(k));else if(0===k)I(t,h,[]);else{I(t,h,P.slice(0,k))}}}else{var P;(P=v(t,h))&&Array.isArray(P)&&P.push(C)}}else{if("$bit"!=a)throw"unknown update operator: "+a;h=at((l=Object.keys(c))[0],r);var M=c[l[0]],L=Object.keys(M)[0],T=M[L];d=v(t,h);if("and"==L)I(t,h,d&T);else if("or"==L)I(t,h,d|T);else{if("xor"!=L)throw"unknown $bit operator: "+L;I(t,h,d^T)}}}}function lt(e,t,n){for(var r={_id:n},i=!0,s=Object.keys(t),o=0;o<s.length;o++)if("$"==s[o].charAt(0)){i=!1;break}if(i)for(o=0;o<s.length;o++)r[s[o]]=t[s[o]];else{var a=Object.keys(e);for(o=0;o<a.length;o++)r[a[o]]=e[a[o]];ct(t,r,!0)}return r}class ut{constructor(e,t,n,r={}){this.name=e,this.keys=t,this.storage=n,this.options=r}add(e){throw new Error("add() must be implemented by subclass")}remove(e){throw new Error("remove() must be implemented by subclass")}update(e,t){this.remove(e),this.add(t)}query(e){throw new Error("query() must be implemented by subclass")}clear(){throw new Error("clear() must be implemented by subclass")}getSpec(){return{name:this.name,key:this.keys}}}const ht=".version.json",ft=16384;function dt(e,t){const n=Number(t);if(!Number.isFinite(n))throw new Error(`Invalid version value: ${t}`);if(n<0)throw new Error(`Version must be non-negative: ${n}`);return 0===n?e:`${e}.v${n}`}function pt(e){const t={currentVersion:0,refCounts:{}};if(!e||"object"!=typeof e)return t;const n=Number(e.currentVersion);if(t.currentVersion=Number.isFinite(n)?n:0,e.refCounts&&"object"==typeof e.refCounts)for(const[r,i]of Object.entries(e.refCounts)){const e=Number(i);Number.isFinite(e)&&e>0?t.refCounts[String(r)]=e:(!Number.isFinite(e)||e<0)&&console.warn(`Ignoring invalid ref count for version ${r}: ${i}`)}return t}function gt(e){const t=e.split("/").filter(Boolean),n=t.pop();if(!n)throw new Error(`Invalid storage path: ${e}`);return{parts:t,filename:n}}async function mt(e,t){let n=await globalThis.navigator.storage.getDirectory();for(const r of e)n=await n.getDirectoryHandle(r,{create:t});return n}async function yt(e){const{parts:t}=gt(e);0!==t.length&&await mt(t,!0)}async function wt(e,{create:t}={}){const{parts:n,filename:r}=gt(e);return(await mt(n,!!t)).getFileHandle(r,{create:t})}async function bt(e){const t=`${e}${ht}`;try{const e=await wt(t,{create:!1}),n=await e.getFile(),r=await n.text();return r&&""!==r.trim()?pt(JSON.parse(r)):pt()}catch(n){if("NotFoundError"===n?.name||"ENOENT"===n?.code)return pt();throw n}}async function xt(e,t){const n=`${e}${ht}`;await yt(n);const r=await wt(n,{create:!0}),i=await r.createWritable();await i.write(JSON.stringify(t)),await i.close()}async function _t(e,t,n,r){if(t===n.currentVersion)return;const i=String(t);n.refCounts[i]||await async function(e,t,n){const r=dt(e,t);for(const i of n){const e=i?`${r}${i}`:r;await St(e)}}(e,t,r)}async function vt(e){const t=await bt(e),n=t.currentVersion,r=String(n);return t.refCounts[r]=(t.refCounts[r]||0)+1,await xt(e,t),{version:n,path:dt(e,n)}}async function $t(e,t,{suffixes:n=[""]}={}){const r=await bt(e),i=String(t);r.refCounts[i]&&(r.refCounts[i]-=1,r.refCounts[i]<=0&&delete r.refCounts[i]),await _t(e,t,r,n),await xt(e,r)}async function It(e,t,n,{suffixes:r=[""]}={}){const i=await bt(e),s=Number(t);i.currentVersion=Number.isFinite(s)?s:i.currentVersion;const o=String(i.currentVersion);i.refCounts[o]||(i.refCounts[o]=0),await _t(e,n,i,r),await xt(e,i)}async function Nt(e){return(await bt(e)).currentVersion}async function St(e){try{const{parts:t,filename:n}=gt(e),r=await mt(t,!1);await r.removeEntry(n)}catch(t){if("NotFoundError"===t?.name||"ENOENT"===t?.code)return;throw t}}async function Ot(e,{reset:t=!1}={}){t&&await St(e),await yt(e);return(await wt(e,{create:!0})).createSyncAccessHandle()}class At extends ut{constructor(e,t,n,r={}){super(e,t,n,r),this.storageFilePath=n,this.storageVersionedPath=null,this.storageVersion=0,this._releaseStorage=null,this.data=null,this.syncHandle=null,this.isOpen=!1}async open(){if(!this.isOpen)try{const{version:e,path:t}=await vt(this.storageFilePath);this.storageVersion=e,this.storageVersionedPath=t,this._releaseStorage=()=>$t(this.storageFilePath,e);const n=this.storageVersionedPath.split("/").filter(Boolean),r=n.pop();if(!r)throw new Error(`Invalid storage path: ${this.storageVersionedPath}`);let i=await globalThis.navigator.storage.getDirectory();for(const o of n)i=await i.getDirectoryHandle(o,{create:!0});const s=await i.getFileHandle(r,{create:!0});this.syncHandle=await s.createSyncAccessHandle(),this.data=new xe(this.syncHandle,50),await this.data.open(),this.isOpen=!0}catch(e){if(!e.message||!(e.message.includes("Unknown type byte")||e.message.includes("Failed to read metadata")||e.message.includes("Invalid tree file")))throw e;{if(this.syncHandle){try{await this.syncHandle.close()}catch(t){}this.syncHandle=null}const e=this.storageVersionedPath.split("/").filter(Boolean),n=e.pop();if(!n)throw new Error(`Invalid storage path: ${this.storageVersionedPath}`);let r=await globalThis.navigator.storage.getDirectory();for(const t of e)r=await r.getDirectoryHandle(t,{create:!0});try{await r.removeEntry(n)}catch(t){}const i=await r.getFileHandle(n,{create:!0});this.syncHandle=await i.createSyncAccessHandle(),this.data=new xe(this.syncHandle,50),await this.data.open(),this.isOpen=!0}}}async close(){if(this.isOpen){try{await this._maybeCompact(),await this.data.close()}catch(e){if(!e.message||!e.message.includes("File is not open"))throw e}this.isOpen=!1,this._releaseStorage&&(await this._releaseStorage(),this._releaseStorage=null)}else this._releaseStorage&&(await this._releaseStorage(),this._releaseStorage=null)}async _maybeCompact(){if(!this.data||!this.data.file)return;const e=await Nt(this.storageFilePath);if(e!==this.storageVersion)return;const t=this.data.file.getFileSize();if(!t||t<ft)return;const n=e+1,r=dt(this.storageFilePath,n),i=await Ot(r,{reset:!0});await this.data.compact(i),await It(this.storageFilePath,n,e)}extractIndexKey(e){const t=Object.keys(this.keys);if(0===t.length)return null;if(1===t.length){const n=v(e,t[0]);return void 0===n?null:n}const n=[];for(let r=0;r<t.length;r++){const i=v(e,t[r]);if(void 0===i)return null;n.push(i)}return n.join("\0")}async add(e){this.isOpen||await this.open();const t=this.extractIndexKey(e);if(null!==t){const n=e._id.toString(),r=await this.data.search(t);let i;if(Array.isArray(r)){if(r.includes(n))return;i=[...r,n]}else i=r?r===n?[r]:[r,n]:[n];await this.data.add(t,i)}}async remove(e){this.isOpen||await this.open();const t=this.extractIndexKey(e);if(null!==t){const n=e._id.toString(),r=await this.data.search(t);if(Array.isArray(r)){const e=r.filter(e=>e!==n);e.length>0?await this.data.add(t,e):await this.data.delete(t)}else r===n&&await this.data.delete(t)}}async query(e){const t=Object.keys(e),n=Object.keys(this.keys);if(1!==n.length)return null;const r=n[0];if(-1===t.indexOf(r))return null;const i=e[r];if("object"!=typeof i||null===i){const e=i;return await this.data.search(e)||[]}return"object"!=typeof i||Array.isArray(i)?null:await this._queryWithOperators(r,i)}async _queryWithOperators(e,t){const n=Object.keys(t),r=/* @__PURE__ */new Set;if(n.some(e=>["$gt","$gte","$lt","$lte"].includes(e))){const e=n.includes("$gt")||n.includes("$gte"),i=n.includes("$lt")||n.includes("$lte");if(e&&i){const e=n.includes("$gte")?t.$gte:n.includes("$gt")?t.$gt:-1/0,i=n.includes("$lte")?t.$lte:n.includes("$lt")?t.$lt:1/0,s=await this.data.rangeSearch(e,i);for(const o of s){const e=o.key,i=o.value;let s=!0;!n.includes("$gt")||e>t.$gt||(s=!1),!n.includes("$gte")||e>=t.$gte||(s=!1),!n.includes("$lt")||e<t.$lt||(s=!1),!n.includes("$lte")||e<=t.$lte||(s=!1),s&&i&&(Array.isArray(i)?i.forEach(e=>r.add(e)):r.add(i))}return Array.from(r)}{const e=await this.data.toArray();for(const i of e){const e=i.key,s=i.value;let o=!0;for(const r of n){const n=t[r];("$gt"!==r||e>n)&&("$gte"!==r||e>=n)&&("$lt"!==r||e<n)&&("$lte"!==r||e<=n)?("$eq"===r&&e!==n||"$ne"===r&&e===n)&&(o=!1):o=!1}o&&s&&(Array.isArray(s)?s.forEach(e=>r.add(e)):r.add(s))}return Array.from(r)}}if(n.includes("$in")){const e=t.$in;if(Array.isArray(e)){for(const t of e){const e=await this.data.search(t);e&&(Array.isArray(e)?e.forEach(e=>r.add(e)):r.add(e))}return Array.from(r)}}if(n.includes("$eq")){const e=t.$eq,n=await this.data.search(e);return n?Array.isArray(n)?n:[n]:[]}if(n.includes("$ne")){const e=t.$ne,n=await this.data.toArray();for(const t of n)t.key!==e&&t.value&&(Array.isArray(t.value)?t.value.forEach(e=>r.add(e)):r.add(t.value));return Array.from(r)}return null}async clear(){this.isOpen&&await this.close();const e=await Nt(this.storageFilePath),t=dt(this.storageFilePath,e).split("/").filter(Boolean),n=t.pop();let r=await globalThis.navigator.storage.getDirectory();for(const s of t)r=await r.getDirectoryHandle(s,{create:!0});try{await r.removeEntry(n)}catch(i){}await this.open()}}const Ct=["-terms.bj","-documents.bj","-lengths.bj"];class Et extends ut{constructor(e,t,n,r={}){super(e,t,n),this.storageBasePath=n,this.storageVersion=0,this.versionedBasePath=null,this._releaseStorage=null,this.textIndex=null,this.syncHandles=[],this.isOpen=!1,this.indexedFields=[];for(const i in t)"text"===t[i]&&this.indexedFields.push(i);if(0===this.indexedFields.length)throw new Error('Text index must have at least one field with type "text"')}async open(){if(!this.isOpen)try{const{version:e,path:t}=await vt(this.storageBasePath);this.storageVersion=e,this.versionedBasePath=t,this._releaseStorage=()=>$t(this.storageBasePath,e,{suffixes:Ct});const n=await this._createBPlusTree(this._getActiveBasePath()+"-terms.bj"),r=await this._createBPlusTree(this._getActiveBasePath()+"-documents.bj"),i=await this._createBPlusTree(this._getActiveBasePath()+"-lengths.bj");this.textIndex=new $e({order:16,trees:{index:n,documentTerms:r,documentLengths:i}}),await this.textIndex.open(),this.isOpen=!0}catch(e){if(!("ENOENT"===e.code||e.message&&(e.message.includes("Failed to read metadata")||e.message.includes("missing required fields")||e.message.includes("Unknown type byte")||e.message.includes("Invalid")||e.message.includes("file too small"))))throw e;{await this._closeSyncHandles(),await this._deleteIndexFiles(),await this._ensureDirectoryForFile(this._getActiveBasePath()+"-terms.bj");const e=await this._createBPlusTree(this._getActiveBasePath()+"-terms.bj"),t=await this._createBPlusTree(this._getActiveBasePath()+"-documents.bj"),n=await this._createBPlusTree(this._getActiveBasePath()+"-lengths.bj");this.textIndex=new $e({order:16,trees:{index:e,documentTerms:t,documentLengths:n}}),await this.textIndex.open(),this.isOpen=!0}}}async _createBPlusTree(e){const t=e.split("/").filter(Boolean),n=t.pop();if(!n)throw new Error(`Invalid storage path: ${e}`);let r=await globalThis.navigator.storage.getDirectory();for(const o of t)r=await r.getDirectoryHandle(o,{create:!0});const i=await r.getFileHandle(n,{create:!0}),s=await i.createSyncAccessHandle();return this.syncHandles.push(s),new xe(s,16)}async _closeSyncHandles(){for(const t of this.syncHandles)try{await t.close()}catch(e){}this.syncHandles=[]}_getActiveBasePath(){return this.versionedBasePath||this.storageBasePath}async _deleteIndexFiles(e=this._getActiveBasePath()){for(const t of Ct)await this._deleteFile(e+t)}async _deleteFile(e){if(e)try{const t=e.split("/").filter(Boolean),n=t.pop();if(!n)throw new Error(`Invalid storage path: ${e}`);let r=await globalThis.navigator.storage.getDirectory();for(const e of t)r=await r.getDirectoryHandle(e,{create:!1});await r.removeEntry(n)}catch(t){}}async _ensureDirectoryForFile(e){if(!e)return;const t=e.split("/").filter(Boolean);if(t.pop(),0!==t.length)try{let e=await globalThis.navigator.storage.getDirectory();for(const n of t)e=await e.getDirectoryHandle(n,{create:!0})}catch(n){if("EEXIST"!==n.code)throw n}}async close(){if(this.isOpen){if(await this._maybeCompact(),this.textIndex?.isOpen)try{await this.textIndex.close()}catch(e){if(!e.message||!e.message.includes("File is not open"))throw e}this.isOpen=!1}this._releaseStorage&&(await this._releaseStorage(),this._releaseStorage=null)}async _maybeCompact(){if(!this.textIndex?.index?.file||!this.textIndex?.documentTerms?.file||!this.textIndex?.documentLengths?.file)return!1;const e=await Nt(this.storageBasePath);if(e!==this.storageVersion)return!1;const t=this.textIndex.index.file.getFileSize()+this.textIndex.documentTerms.file.getFileSize()+this.textIndex.documentLengths.file.getFileSize();if(!t||t<ft)return!1;const n=e+1,r=dt(this.storageBasePath,n),i=await Ot(`${r}-terms.bj`,{reset:!0}),s=await Ot(`${r}-documents.bj`,{reset:!0}),o=await Ot(`${r}-lengths.bj`,{reset:!0}),a=new xe(i,16),c=new xe(s,16),l=new xe(o,16);return await this.textIndex.compact({index:a,documentTerms:c,documentLengths:l}),await It(this.storageBasePath,n,e,{suffixes:Ct}),await this._closeSyncHandles(),!0}_extractText(e){const t=[];for(const n of this.indexedFields){const r=v(e,n);null!=r&&t.push(String(r))}return t.join(" ")}async add(e){if(!e._id)throw new Error("Document must have an _id field");const t=this._extractText(e);t&&await this.textIndex.add(String(e._id),t)}async remove(e){e._id&&await this.textIndex.remove(String(e._id))}query(e){return null}async search(e,t={}){return await this.textIndex.query(e,{scored:!1,...t})}async clear(){this.isOpen&&await this.close();const e=await Nt(this.storageBasePath),t=dt(this.storageBasePath,e);await this._deleteIndexFiles(t),await this.open()}getSpec(){return{name:this.name,key:this.keys,textIndexVersion:3,weights:this._getWeights()}}_getWeights(){const e={};for(const t of this.indexedFields)e[t]=1;return e}}function jt(e,t,n,r){const i=(n-e)*Math.PI/180,s=(r-t)*Math.PI/180,o=Math.sin(i/2)*Math.sin(i/2)+Math.cos(e*Math.PI/180)*Math.cos(n*Math.PI/180)*Math.sin(s/2)*Math.sin(s/2);return 6371*(2*Math.atan2(Math.sqrt(o),Math.sqrt(1-o)))}function Dt(e,t){return!(e.maxLat<t.minLat||e.minLat>t.maxLat||e.maxLng<t.minLng||e.minLng>t.maxLng)}function kt(e){return(e.maxLat-e.minLat)*(e.maxLng-e.minLng)}function Pt(e,t){return{minLat:Math.min(e.minLat,t.minLat),maxLat:Math.max(e.maxLat,t.maxLat),minLng:Math.min(e.minLng,t.minLng),maxLng:Math.max(e.maxLng,t.maxLng)}}function Mt(e,t){return kt(Pt(e,t))-kt(e)}class Lt{constructor(e,t){this.rtree=e,this.id=t.id,this.isLeaf=t.isLeaf,this.children=t.children||[],this.bbox=t.bbox}updateBBox(){if(0===this.children.length)return void(this.bbox=null);let e=1/0,t=-1/0,n=1/0,r=-1/0;for(const i of this.children){let s;if(this.isLeaf)s=i.bbox;else{s=this.rtree._loadNode(i).bbox}s&&(e=Math.min(e,s.minLat),t=Math.max(t,s.maxLat),n=Math.min(n,s.minLng),r=Math.max(r,s.maxLng))}this.bbox={minLat:e,maxLat:t,minLng:n,maxLng:r},this.rtree._saveNode(this)}toJSON(){return{id:this.id,isLeaf:this.isLeaf,children:this.children,bbox:this.bbox}}}class Tt{constructor(e,t=9){this.file=new b(e),this.maxEntries=t,this.minEntries=Math.max(2,Math.ceil(t/2)),this.rootPointer=null,this.nextId=1,this._size=0,this.isOpen=!1}async open(){if(this.isOpen)throw new Error("R-tree is already open");this.file.getFileSize()>0?this._loadFromFile():this._initializeNewTree(),this.isOpen=!0}async close(){this.isOpen&&(this._writeMetadata(),this.file&&this.file.syncAccessHandle&&(this.file.flush(),await this.file.syncAccessHandle.close()),this.isOpen=!1)}_initializeNewTree(){const e=new Lt(this,{id:0,isLeaf:!0,children:[],bbox:null});this.nextId=1,this._size=0,this.rootPointer=this._saveNode(e),this._writeMetadata()}_writeMetadata(){const e={version:1,maxEntries:this.maxEntries,minEntries:this.minEntries,size:this._size,rootPointer:this.rootPointer,nextId:this.nextId};this.file.append(e)}_loadFromFile(){const e=this.file.getFileSize();if(e<135)throw new Error("Invalid R-tree file format: file too small for metadata");const t=e-135,n=this.file.read(t);this.maxEntries=n.maxEntries,this.minEntries=n.minEntries,this._size=n.size,this.rootPointer=n.rootPointer,this.nextId=n.nextId}_saveNode(e){const t=e.toJSON(),n=this.file.getFileSize();return this.file.append(t),new m(n)}_loadNode(e){if(!(e instanceof m))throw new Error("Expected Pointer object");const t=e.valueOf(),n=this.file.read(t);return new Lt(this,n)}_loadRoot(){return this._loadNode(this.rootPointer)}insert(e,t,n){if(!this.isOpen)throw new Error("R-tree file must be opened before use");if(!(n instanceof g))throw new Error("objectId must be an instance of ObjectId to insert into rtree");const r={bbox:{minLat:e,maxLat:e,minLng:t,maxLng:t},lat:e,lng:t,objectId:n},i=this._loadRoot(),s=this._insert(r,i,1);if(s.split){const e=new Lt(this,{id:this.nextId++,isLeaf:!1,children:s.pointers,bbox:null});e.updateBBox(),this.rootPointer=this._saveNode(e)}else this.rootPointer=s.pointer;this._size++,this._writeMetadata()}_insert(e,t,n){if(t.isLeaf){if(t.children.push(e),t.updateBBox(),t.children.length>this.maxEntries){const[e,n]=this._split(t);return{split:!0,pointers:[e,n]}}return{split:!1,pointer:this._saveNode(t)}}{const r=this._chooseSubtree(e.bbox,t),i=this._loadNode(r),s=this._insert(e,i,n+1);if(s.split){let e=-1;for(let n=0;n<t.children.length;n++)if(t.children[n].valueOf()===r.valueOf()){e=n;break}if(-1!==e?(t.children[e]=s.pointers[0],t.children.push(s.pointers[1])):(t.children.push(s.pointers[0]),t.children.push(s.pointers[1])),t.updateBBox(),t.children.length>this.maxEntries){const[e,n]=this._split(t);return{split:!0,pointers:[e,n]}}}else{let e=-1;for(let n=0;n<t.children.length;n++)if(t.children[n].valueOf()===r.valueOf()){e=n;break}-1!==e&&(t.children[e]=s.pointer),t.updateBBox()}return{split:!1,pointer:this._saveNode(t)}}}_chooseSubtree(e,t){let n=1/0,r=1/0,i=null;for(const s of t.children){if(!(s instanceof m))throw new Error("Expected Pointer in _chooseSubtree, got: "+typeof s);const t=this._loadNode(s),o=Mt(t.bbox,e),a=kt(t.bbox);(o<n||o===n&&a<r)&&(n=o,r=a,i=s)}return i}_split(e){const t=e.children,n=e.isLeaf;let r=-1/0,i=0,s=1;for(let c=0;c<t.length;c++)for(let e=c+1;e<t.length;e++){let o,a;if(n)o=t[c].bbox,a=t[e].bbox;else{const n=this._loadNode(t[c]),r=this._loadNode(t[e]);o=n.bbox,a=r.bbox}const l=kt(Pt(o,a));l>r&&(r=l,i=c,s=e)}const o=new Lt(this,{id:this.nextId++,isLeaf:n,children:[t[i]],bbox:null}),a=new Lt(this,{id:this.nextId++,isLeaf:n,children:[t[s]],bbox:null});for(let c=0;c<t.length;c++){if(c===i||c===s)continue;const e=t[c];let r;if(n)r=e.bbox;else{r=this._loadNode(e).bbox}o.updateBBox(),a.updateBBox();const l=o.bbox?Mt(o.bbox,r):0,u=a.bbox?Mt(a.bbox,r):0;l<u?o.children.push(e):u<l?a.children.push(e):o.children.length<=a.children.length?o.children.push(e):a.children.push(e)}o.updateBBox(),a.updateBBox();return[this._saveNode(o),this._saveNode(a)]}searchBBox(e){if(!this.isOpen)throw new Error("R-tree file must be opened before use");const t=[],n=this._loadRoot();return this._searchBBox(e,n,t),t}_searchBBox(e,t,n){if(t.bbox&&Dt(e,t.bbox))if(t.isLeaf)for(const r of t.children)Dt(e,r.bbox)&&n.push({objectId:r.objectId,lat:r.lat,lng:r.lng});else for(const r of t.children){const t=this._loadNode(r);this._searchBBox(e,t,n)}}searchRadius(e,t,n){const r=function(e,t,n){const r=n/111,i=n/(111*Math.cos(e*Math.PI/180));return{minLat:e-r,maxLat:e+r,minLng:t-i,maxLng:t+i}}(e,t,n),i=this._loadRoot(),s=[];this._searchBBoxEntries(r,i,s);const o=[];for(const a of s){const r=jt(e,t,a.lat,a.lng);r<=n&&o.push({objectId:a.objectId,lat:a.lat,lng:a.lng,distance:r})}return o}_searchBBoxEntries(e,t,n){if(t.bbox&&Dt(e,t.bbox))if(t.isLeaf)for(const r of t.children)Dt(e,r.bbox)&&n.push(r);else for(const r of t.children){const t=this._loadNode(r);this._searchBBoxEntries(e,t,n)}}remove(e){if(!this.isOpen)throw new Error("R-tree file must be opened before use");if(!(e instanceof g))throw new Error("objectId must be an instance of ObjectId to remove from rtree");const t=this._loadRoot(),n=this._remove(e,t);if(!n.found)return!1;if(n.underflow&&n.children)if(0===n.children.length){const e=new Lt(this,{id:this.nextId++,isLeaf:!0,children:[],bbox:null});this.rootPointer=this._saveNode(e)}else if(1!==n.children.length||n.isLeaf){const e=new Lt(this,{id:t.id,isLeaf:n.isLeaf,children:n.children,bbox:null});e.updateBBox(),this.rootPointer=this._saveNode(e)}else this.rootPointer=n.children[0];else n.pointer&&(this.rootPointer=n.pointer);return this._size--,this._writeMetadata(),!0}_remove(e,t){if(t.isLeaf){const n=t.children.length;if(t.children=t.children.filter(t=>!t.objectId.equals(e)),t.children.length===n)return{found:!1};t.updateBBox();const r=this._saveNode(t);return{found:!0,underflow:t.children.length<this.minEntries&&t.children.length>0,pointer:r,children:t.children,isLeaf:!0}}{let n=[...t.children];for(let r=0;r<n.length;r++){const i=n[r],s=this._loadNode(i),o=this._remove(e,s);if(o.found){if(o.underflow){const e=this._handleUnderflow(t,r,s,o);e.merged?n=e.children:n[r]=o.pointer}else n[r]=o.pointer;const e=new Lt(this,{id:t.id,isLeaf:!1,children:n,bbox:null});e.updateBBox();const i=this._saveNode(e);return{found:!0,underflow:n.length<this.minEntries&&n.length>0,pointer:i,children:n,isLeaf:!1}}}return{found:!1}}}_handleUnderflow(e,t,n,r){const i=[];if(t>0){const n=e.children[t-1],r=this._loadNode(n);i.push({index:t-1,node:r,pointer:n})}if(t<e.children.length-1){const n=e.children[t+1],r=this._loadNode(n);i.push({index:t+1,node:r,pointer:n})}for(const s of i)if(s.node.children.length>this.minEntries){const i=[...r.children,...s.node.children],o=Math.ceil(i.length/2),a=i.slice(0,o),c=i.slice(o),l=new Lt(this,{id:n.id,isLeaf:r.isLeaf,children:a,bbox:null});l.updateBBox();const u=new Lt(this,{id:s.node.id,isLeaf:s.node.isLeaf,children:c,bbox:null});u.updateBBox();const h=this._saveNode(l),f=this._saveNode(u),d=[...e.children],p=Math.min(t,s.index),g=Math.max(t,s.index);return d[p]=h,d[g]=f,{merged:!0,children:d}}if(i.length>0){const n=i[0],s=[...r.children,...n.node.children],o=new Lt(this,{id:this.nextId++,isLeaf:r.isLeaf,children:s,bbox:null});o.updateBBox();const a=this._saveNode(o),c=e.children.filter((e,r)=>r!==t&&r!==n.index);return c.push(a),{merged:!0,children:c}}return{merged:!1}}size(){return this._size}async clear(){const e=new Lt(this,{id:this.nextId++,isLeaf:!0,children:[],bbox:null});this.rootPointer=this._saveNode(e),this._size=0,this._writeMetadata()}async compact(e){if(!this.isOpen)throw new Error("R-tree file must be opened before use");if(!e)throw new Error("Destination sync handle is required for compaction");this._writeMetadata();const t=this.file.getFileSize(),n=new Tt(e,this.maxEntries);await n.open(),n.minEntries=this.minEntries,n.nextId=this.nextId,n._size=this._size;const r=/* @__PURE__ */new Map,i=e=>{const t=e.valueOf();if(r.has(t))return r.get(t);const s=this._loadNode(e),o=[];if(s.isLeaf)for(const n of s.children)o.push(n);else for(const n of s.children){const e=i(n);o.push(e)}const a=new Lt(n,{id:s.id,isLeaf:s.isLeaf,children:o,bbox:s.bbox}),c=n._saveNode(a);return r.set(t,c),c},s=i(this.rootPointer);n.rootPointer=s,n._writeMetadata();const o=n.file.getFileSize();return await n.close(),{oldSize:t,newSize:o,bytesSaved:Math.max(0,t-o)}}}class Ft extends ut{constructor(e,t,n,r={}){super(e,t,n,r),this.geoField=Object.keys(t)[0],this.storageFilePath=n,this.rtree=null,this.syncHandle=null,this.isOpen=!1}async open(){if(!this.isOpen)try{const e=this.storageFilePath.split("/").filter(Boolean),t=e.pop();if(!t)throw new Error(`Invalid storage path: ${this.storageFilePath}`);let n=await globalThis.navigator.storage.getDirectory();for(const i of e)n=await n.getDirectoryHandle(i,{create:!0});const r=await n.getFileHandle(t,{create:!0});this.syncHandle=await r.createSyncAccessHandle(),this.rtree=new Tt(this.syncHandle,9),await this.rtree.open(),this.isOpen=!0}catch(e){if(!("ENOENT"===e.code||e.message&&(e.message.includes("Invalid R-tree")||e.message.includes("file too small")||e.message.includes("Failed to read metadata")||e.message.includes("Unknown type byte"))))throw e;{if(this.syncHandle){try{await this.syncHandle.close()}catch(t){}this.syncHandle=null}const e=this.storageFilePath.split("/").filter(Boolean),n=e.pop();if(!n)throw new Error(`Invalid storage path: ${this.storageFilePath}`);let r=await globalThis.navigator.storage.getDirectory();for(const t of e)r=await r.getDirectoryHandle(t,{create:!0});try{await r.removeEntry(n)}catch(t){}const i=await r.getFileHandle(n,{create:!0});this.syncHandle=await i.createSyncAccessHandle(),this.rtree=new Tt(this.syncHandle,9),await this.rtree.open(),this.isOpen=!0}}}async close(){if(this.isOpen){try{await this.rtree.close()}catch(e){if(!e.message||!e.message.includes("File is not open"))throw e}this.isOpen=!1}}_extractCoordinates(e){if(!e)return null;if("FeatureCollection"===e.type&&e.features&&e.features.length>0){const t=e.features[0];if(t.geometry)return this._extractCoordinates(t.geometry)}if("Feature"===e.type&&e.geometry)return this._extractCoordinates(e.geometry);if("Point"===e.type&&e.coordinates){const[t,n]=e.coordinates;if("number"==typeof t&&"number"==typeof n)return{lat:n,lng:t}}if("Polygon"===e.type&&e.coordinates&&e.coordinates.length>0){const t=e.coordinates[0];if(t.length>0){let e=0,n=0;for(const r of t)n+=r[0],e+=r[1];return{lat:e/t.length,lng:n/t.length}}}return null}async add(e){if(!e._id)throw new Error("Document must have an _id field");const t=v(e,this.geoField),n=this._extractCoordinates(t);n&&await this.rtree.insert(n.lat,n.lng,e._id)}async remove(e){if(e._id){if(!(e._id instanceof g))throw console.error(e),new Error("Document _id must be an ObjectId to remove from geospatial index");await this.rtree.remove(e._id)}}async query(e){if(this.isOpen||await this.open(),!e[this.geoField])return null;const t=e[this.geoField];if(t.$geoWithin){const e=t.$geoWithin;if(Array.isArray(e)&&2===e.length){const t=e[0][0],n=e[0][1],r=e[1][0],i=e[1][1];return(await this.rtree.searchBBox({minLat:i,maxLat:n,minLng:t,maxLng:r})).map(e=>e.objectId.toString())}}if(t.$near){const e=t.$near;let n;if(e.$geometry)n=e.$geometry.coordinates;else if(e.coordinates)n=e.coordinates;else{if(!Array.isArray(e))return null;n=e}if(!n||n.length<2)return null;const[r,i]=n,s=(e.$maxDistance||1e6)/1e3,o=await this.rtree.searchRadius(i,r,s);return o.sort((e,t)=>e.distance-t.distance),o.map(e=>e.objectId.toString())}if(t.$nearSphere){const e=t.$nearSphere;let n;if(e.$geometry)n=e.$geometry.coordinates;else if(e.coordinates)n=e.coordinates;else{if(!Array.isArray(e))return null;n=e}if(!n||n.length<2)return null;const[r,i]=n,s=(e.$maxDistance||1e6)/1e3,o=await this.rtree.searchRadius(i,r,s);return o.sort((e,t)=>e.distance-t.distance),o.map(e=>e.objectId.toString())}if(t.$geoIntersects){const e=t.$geoIntersects;let n;if(!e.$geometry)return null;if(n=e.$geometry,!n||!n.type)return null;if("Point"===n.type){const[e,t]=n.coordinates,r=1e-4;return(await this.rtree.searchBBox({minLat:t-r,maxLat:t+r,minLng:e-r,maxLng:e+r})).map(e=>e.objectId.toString())}if("Polygon"===n.type){const e=n.coordinates;if(!e||0===e.length)return null;const t=e[0];if(!t||t.length<3)return null;let r=1/0,i=-1/0,s=1/0,o=-1/0;for(const n of t){const[e,t]=n;r=Math.min(r,t),i=Math.max(i,t),s=Math.min(s,e),o=Math.max(o,e)}return(await this.rtree.searchBBox({minLat:r,maxLat:i,minLng:s,maxLng:o})).filter(e=>this._pointInPolygon(e.lat,e.lng,t)).map(e=>e.objectId.toString())}return null}return null}_pointInPolygon(e,t,n){let r=!1;for(let i=0,s=n.length-1;i<n.length;s=i++){const[o,a]=n[i],[c,l]=n[s];a>e!=l>e&&t<(c-o)*(e-a)/(l-a)+o&&(r=!r)}return r}async clear(){await this.close();try{const e=this.storageFilePath.split("/").filter(Boolean),t=e.pop();let n=await globalThis.navigator.storage.getDirectory();for(const r of e)n=await n.getDirectoryHandle(r,{create:!1});await n.removeEntry(t)}catch(e){if(!e||"NotFoundError"!==e.name)throw e}await this.open()}getSpec(){return{name:this.name,key:this.keys,"2dsphereIndexVersion":3}}}class Bt{constructor(){this.type="full_scan",this.indexes=[],this.indexScans=[],this.estimatedCost=1/0,this.indexOnly=!1}}class zt{constructor(e){this.indexes=e}plan(e){const t=new Bt;if(!e||0===Object.keys(e).length)return t;const n=this._analyzeQuery(e);if(n.hasTextSearch){const t=this._planTextSearch(e,n);if(t)return t}if(n.hasGeoQuery){const t=this._planGeoQuery(e,n);if(t)return t}if("and"===n.type){const t=this._planAndQuery(e,n);if("full_scan"!==t.type)return t}if("or"===n.type){const t=this._planOrQuery(e,n);if("full_scan"!==t.type)return t}const r=this._planSimpleQuery(e);return"full_scan"!==r.type?r:t}_analyzeQuery(e){const t={type:"simple",fields:[],operators:{},hasTextSearch:!1,hasGeoQuery:!1,conditions:[]},n=Object.keys(e);if(1===n.length){const r=n[0];if("$and"===r){t.type="and",t.conditions=e.$and;for(const e of t.conditions){const n=this._analyzeQuery(e);t.fields.push(...n.fields),n.hasTextSearch&&(t.hasTextSearch=!0),n.hasGeoQuery&&(t.hasGeoQuery=!0)}return t}if("$or"===r){t.type="or",t.conditions=e.$or;for(const e of t.conditions){const n=this._analyzeQuery(e);t.fields.push(...n.fields),n.hasTextSearch&&(t.hasTextSearch=!0),n.hasGeoQuery&&(t.hasGeoQuery=!0)}return t}}for(const r of n){if(r.startsWith("$"))continue;t.fields.push(r);const n=e[r];if("object"==typeof n&&null!==n&&!Array.isArray(n)){const e=Object.keys(n);t.operators[r]=e,e.includes("$text")&&(t.hasTextSearch=!0),e.some(e=>["$geoWithin","$geoIntersects","$near","$nearSphere"].includes(e))&&(t.hasGeoQuery=!0)}}return n.length>1&&(t.type="and"),t}_planTextSearch(e,t){for(const[n,r]of this.indexes)if(r instanceof Et){const t=this._extractTextQuery(e);if(t){const e=new Bt;return e.type="index_scan",e.indexes=[n],e.indexScans=[{indexName:n,index:r,textQuery:t}],e.estimatedCost=100,e.indexOnly=!0,e}}return null}_extractTextQuery(e){for(const t in e){const n=e[t];if("object"==typeof n&&null!==n&&n.$text)return"string"==typeof n.$text?n.$text:n.$text.$search}return null}_planGeoQuery(e,t){for(const[n,r]of this.indexes)if(r instanceof Ft){const t=new Bt;return t.type="index_scan",t.indexes=[n],t.indexScans=[{indexName:n,index:r,query:e}],t.estimatedCost=100,t.indexOnly=!0,t}return null}_planAndQuery(e,t){const n=new Bt;let r;r=e.$and?e.$and:Object.keys(e).map(t=>({[t]:e[t]}));const i=[];for(const s of r){const e=this._planSimpleQuery(s);"index_scan"===e.type&&i.push(e.indexScans[0])}return i.length>1?(n.type="index_intersection",n.indexScans=i,n.indexes=i.map(e=>e.indexName),n.estimatedCost=50,n):1===i.length?(n.type="index_scan",n.indexScans=[i[0]],n.indexes=[i[0].indexName],n.estimatedCost=50,n):n}_planOrQuery(e,t){const n=new Bt;if(!e.$or)return n;const r=e.$or,i=[];for(const s of r){const e=this._planSimpleQuery(s);"index_scan"===e.type&&i.push(e.indexScans[0])}return i.length>0?(n.type="index_union",n.indexScans=i,n.indexes=i.map(e=>e.indexName),n.estimatedCost=100*i.length,n):n}_planSimpleQuery(e){const t=new Bt;if(0===Object.keys(e).length)return t;for(const[n,r]of this.indexes)if(!(r instanceof Et||r instanceof Ft)&&this._canIndexHandleQuery(r,e))return t.type="index_scan",t.indexes=[n],t.indexScans=[{indexName:n,index:r,query:e}],t.estimatedCost=50,t;return t}async _executeIndexScan(e){const{index:t,query:n,textQuery:r}=e;if("function"!=typeof t.open||void 0===t.isOpen||t.isOpen||await t.open(),void 0!==r)return await t.search(r);if(void 0!==n){const e=await t.query(n);return null!==e?e:[]}return void 0!==e.docIds?e.docIds:[]}_canIndexHandleQuery(e,t){const n=Object.keys(t),r=Object.keys(e.keys);if(1!==r.length)return!1;const i=r[0];return-1!==n.indexOf(i)}async execute(e){if("full_scan"===e.type)return null;if("index_scan"===e.type){const t=e.indexScans[0];return await this._executeIndexScan(t)}if("index_intersection"===e.type){if(0===e.indexScans.length)return null;const t=[];for(const i of e.indexScans)t.push({docIds:await this._executeIndexScan(i),indexName:i.indexName});const n=t.slice().sort((e,t)=>e.docIds.length-t.docIds.length);let r=new Set(n[0].docIds);for(let e=1;e<n.length;e++){const t=new Set(n[e].docIds);if(r=new Set([...r].filter(e=>t.has(e))),0===r.size)break}return Array.from(r)}if("index_union"===e.type){const t=/* @__PURE__ */new Set;for(const n of e.indexScans){(await this._executeIndexScan(n)).forEach(e=>t.add(e))}return Array.from(t)}return null}}class Ut extends n.EventEmitter{constructor(e,t=[],n={}){super(),this.target=e,this.pipeline=t,this.options=n,this.closed=!1,this._listeners=/* @__PURE__ */new Map,this._changeCounter=0,this._startWatching()}_isDB(e){return e&&"string"==typeof e.dbName&&"function"==typeof e.getCollectionNames&&e.collections instanceof Map}_isServer(e){return e&&e.databases instanceof Map&&"function"==typeof e._getDB}_isMongoClient(e){return e&&"function"==typeof e.connect&&"function"==typeof e.db&&"MongoClient"===e.constructor.name}_startWatching(){if(this.closed)return;const e=this._getCollectionsToWatch();for(const t of e)this._watchCollection(t);this._isServer(this.target)&&this._interceptServerDBCreation(),this._isDB(this.target)&&this._interceptDBCollectionCreation(),this._isMongoClient(this.target)&&this._interceptClientDBCreation()}_getCollectionsToWatch(){const e=[];if(this._isServer(this.target)){for(const[t,n]of this.target.databases){const t=n.getCollectionNames();for(const r of t){const t=n[r];t&&t.isCollection&&e.push(t)}}return e}if(this._isMongoClient(this.target))return this._monitorClient(),e;if(this._isDB(this.target)){const t=this.target.getCollectionNames();for(const n of t){const t=this.target[n];t&&t.isCollection&&e.push(t)}this._monitorDB()}return this.target.isCollection&&e.push(this.target),e}_watchCollection(e){if(this.closed)return;if(!e)return;if("function"!=typeof e.on)return;if(!e.isCollection)return;if(this._listeners.has(e))return;const t={insert:t=>this._emitChange("insert",e,t),update:(t,n)=>this._emitChange("update",e,t,n),replace:t=>this._emitChange("replace",e,t),delete:t=>this._emitChange("delete",e,t)};this._listeners.set(e,t),e.on("insert",t.insert),e.on("update",t.update),e.on("replace",t.replace),e.on("delete",t.delete)}_emitChange(e,t,n,r=null){if(this.closed)return;const i=this._createChangeEvent(e,t,n,r);this._matchesPipeline(i)&&this.emit("change",i)}_createChangeEvent(e,t,n,r){const i={_id:{_data:btoa(String(++this._changeCounter))},operationType:e,clusterTime:/* @__PURE__ */new Date,ns:{db:t.db.dbName,coll:t.name},documentKey:{_id:n._id}};switch(e){case"insert":case"replace":i.fullDocument=n;break;case"update":i.updateDescription=r||{updatedFields:{},removedFields:[],truncatedArrays:[]},"updateLookup"===this.options.fullDocument&&(i.fullDocument=n)}return i}_matchesPipeline(e){if(!this.pipeline||0===this.pipeline.length)return!0;for(const t of this.pipeline)if(t.$match&&!Ye(e,t.$match))return!1;return!0}_getNestedValue(e,t){return t.split(".").reduce((e,t)=>e?.[t],e)}_monitorClient(){}_interceptClientDBCreation(){const e=this.target,t=e.db.bind(e),n=this;this._watchedDBs=/* @__PURE__ */new Map,e.db=function(e,r){const i=t(e,r),s=i.dbName;if(!n._watchedDBs.has(s)){n._watchedDBs.set(s,i);const e=i.getCollectionNames();for(const t of e){const e=i[t];e&&e.isCollection&&!n._listeners.has(e)&&n._watchCollection(e)}n._interceptDBCollectionCreationForClient(i)}return i},this._originalClientMethods={db:t}}_interceptServerDBCreation(){const e=this.target,t=e._getDB.bind(e),n=this;this._watchedDBs=/* @__PURE__ */new Map,e._getDB=function(e){const r=t(e);if(!n._watchedDBs.has(e)){n._watchedDBs.set(e,r);const t=r.getCollectionNames();for(const e of t){const t=r[e];t&&t.isCollection&&!n._listeners.has(t)&&n._watchCollection(t)}n._interceptDBCollectionCreationForServer(r)}return r},this._originalServerMethods={_getDB:t}}_interceptDBCollectionCreationForServer(e){const t=e.collection.bind(e),n=e.createCollection.bind(e),r=this;e.collection=function(e){const n=t(e);return n&&n.isCollection&&!r._listeners.has(n)&&r._watchCollection(n),n},e.createCollection=function(t){n(t);const i=e[t];i&&i.isCollection&&!r._listeners.has(i)&&r._watchCollection(i)}}_interceptDBCollectionCreationForClient(e){const t=e.collection.bind(e),n=e.createCollection.bind(e),r=this;e.collection=function(e){const n=t(e);return n&&n.isCollection&&!r._listeners.has(n)&&r._watchCollection(n),n},e.createCollection=function(t){n(t);const i=e[t];i&&i.isCollection&&!r._listeners.has(i)&&r._watchCollection(i)}}_monitorDB(){}_interceptDBCollectionCreation(){const e=this.target,t=e.getCollection.bind(e),n=e.createCollection?e.createCollection.bind(e):null,r=this;e.getCollection=function(e){const n=t(e);return n&&n.isCollection&&!r._listeners.has(n)&&r._watchCollection(n),n},n&&(e.createCollection=function(t){n(t);const i=e[t];i&&i.isCollection&&!r._listeners.has(i)&&r._watchCollection(i)}),this._originalDBMethods={getCollection:t,createCollection:n}}close(){if(!this.closed){this.closed=!0;for(const[e,t]of this._listeners)e.off("insert",t.insert),e.off("update",t.update),e.off("replace",t.replace),e.off("delete",t.delete);this._listeners.clear(),this._originalServerMethods&&"Server"===this.target.constructor.name&&(this.target._getDB=this._originalServerMethods._getDB),this._originalDBMethods&&"DB"===this.target.constructor.name&&(this.target.collection=this._originalDBMethods.collection,this.target.createCollection=this._originalDBMethods.createCollection),this._originalClientMethods&&"MongoClient"===this.target.constructor.name&&(this.target.db=this._originalClientMethods.db),this.emit("close"),this.removeAllListeners()}}get isClosed(){return this.closed}async*[Symbol.asyncIterator](){const e=[];let t=null,n=!1;const r=n=>{t?(t({value:n,done:!1}),t=null):e.push(n)},i=()=>{n=!0,t&&(t({done:!0}),t=null)},s=e=>{t&&(t(Promise.reject(e)),t=null)};this.on("change",r),this.on("close",i),this.on("error",s);try{for(;!n;)if(e.length>0)yield e.shift();else{const e=await new Promise(e=>{t=e,n&&e({done:!0})});if(e.done)break;yield e.value}}finally{this.off("change",r),this.off("close",i),this.off("error",s)}}async next(){return new Promise((e,t)=>{const n=t=>{s(),e(t)},r=()=>{s(),e(null)},i=e=>{s(),t(e)},s=()=>{this.off("change",n),this.off("close",r),this.off("error",i)};this.closed?e(null):(this.once("change",n),this.once("close",r),this.once("error",i))})}}const Rt=new class{constructor(e=!1){this.enabled=e,this.timings=[],this.nestedLevel=0}setEnabled(e){this.enabled=e}start(e,t,n={}){return this.enabled?{category:e,operation:t,details:n,startTime:performance.now(),nestedLevel:this.nestedLevel++}:null}end(e,t={}){if(!this.enabled||!e)return;this.nestedLevel>0&&this.nestedLevel--;const n=performance.now()-e.startTime;this.timings.push({category:e.category,operation:e.operation,duration:n,details:{...e.details,...t},nestedLevel:e.nestedLevel,timestamp:e.startTime})}getTimings(){return this.timings}getTimingsByCategory(){const e={};for(const t of this.timings)e[t.category]||(e[t.category]=[]),e[t.category].push(t);return e}getSummary(){const e={};for(const t of this.timings){const n=`${t.category}.${t.operation}`;e[n]||(e[n]={category:t.category,operation:t.operation,count:0,total:0,min:1/0,max:-1/0,avg:0});const r=e[n];r.count++,r.total+=t.duration,r.min=Math.min(r.min,t.duration),r.max=Math.max(r.max,t.duration),r.avg=r.total/r.count}return Object.values(e)}clear(){this.timings=[],this.nestedLevel=0}formatTimings(){const e=this.getSummary();if(0===e.length)return"No timing data collected";let t="\n"+"=".repeat(80)+"\n";t+="PERFORMANCE TIMING REPORT\n",t+="=".repeat(80)+"\n\n";const n={};for(const r of e)n[r.category]||(n[r.category]=[]),n[r.category].push(r);for(const[r,i]of Object.entries(n)){t+=`${r.toUpperCase()}\n`,t+="-".repeat(80)+"\n",t+="Operation".padEnd(30)+"Count".padStart(8)+"Total(ms)".padStart(12)+"Avg(ms)".padStart(12)+"Min(ms)".padStart(12)+"Max(ms)".padStart(12)+"\n",t+="-".repeat(80)+"\n";for(const e of i)t+=e.operation.padEnd(30)+e.count.toString().padStart(8)+e.total.toFixed(3).padStart(12)+e.avg.toFixed(3).padStart(12)+e.min.toFixed(3).padStart(12)+e.max.toFixed(3).padStart(12)+"\n";t+="\n"}return t+="=".repeat(80)+"\n",t}}(!1);class qt extends n.EventEmitter{constructor(e,t,n={}){super(),this.db=e,this.name=t,this.path=`${this.db.baseFolder}/${this.db.dbName}/${this.name}`,this.documentsPath=`${this.path}/documents.bj`,this.documentsVersionedPath=null,this.documentsVersion=0,this._releaseDocuments=null,this.order=n.bPlusTreeOrder||50,this.documents=null,this.indexes=/* @__PURE__ */new Map,this._initialized=!1,this.isCollection=!0,this.queryPlanner=new zt(this.indexes)}async _initialize(){if(this._initialized)return;if(!globalThis.navigator||!globalThis.navigator.storage||"function"!=typeof globalThis.navigator.storage.getDirectory)throw new Error("OPFS not available: navigator.storage.getDirectory is missing");const{version:e,path:t}=await vt(this.documentsPath);this.documentsVersion=e,this.documentsVersionedPath=t,this._releaseDocuments=()=>$t(this.documentsPath,e);let n=await this._ensureDirectoryForFile(this.documentsVersionedPath);n||(n=await globalThis.navigator.storage.getDirectory());const r=this.documentsVersionedPath.split("/").filter(Boolean),i=r[r.length-1];if(!i)throw new Error(`Invalid documents path: ${this.documentsVersionedPath}`);const s=await n.getFileHandle(i,{create:!0}),o=await s.createSyncAccessHandle();this.documents=new xe(o,this.order),await this.documents.open(),await this._loadIndexes(),this._initialized=!0}async _ensureDirectoryForFile(e){if(!e)return;const t=e.split("/").filter(Boolean);if(t.pop(),0!==t.length)try{let e=await globalThis.navigator.storage.getDirectory();for(const n of t)e=await e.getDirectoryHandle(n,{create:!0});return e}catch(n){if("EEXIST"!==n.code)throw n}}async _loadIndexes(){let e;try{const t=this.path.split("/").filter(Boolean);let n=await globalThis.navigator.storage.getDirectory();for(const e of t)n=await n.getDirectoryHandle(e,{create:!1});e=n}catch(t){if("NotFoundError"===t?.name||"ENOENT"===t?.code)return;throw t}for await(const[n,r]of e.entries()){if("file"!==r.kind)continue;const e=/\.v\d+(?=-|$)/,i=n.replace(e,"");let s;if(i.endsWith(".textindex-documents.bj"))s="text";else if(i.endsWith(".rtree.bj"))s="geospatial";else{if(!i.endsWith(".bplustree.bj"))continue;s="regular"}const o=i.replace(/\.textindex-documents\.bj$/,"").replace(/\.rtree\.bj$/,"").replace(/\.bplustree\.bj$/,"");if(this.indexes.has(o))continue;const a=this._parseIndexName(o,s);if(!a)continue;let c;if("text"===s){const e=await this._getIndexPath(o,s);c=new Et(o,a,e,{})}else if("geospatial"===s){const e=await this._getIndexPath(o,s);c=new Ft(o,a,e,{})}else{const e=await this._getIndexPath(o,s);c=new At(o,a,e,{})}try{await c.open(),this.indexes.set(o,c)}catch(t){}}}_parseIndexName(e,t){const n=e.split("_");if(n.length<2||n.length%2!=0)return null;const r={};for(let i=0;i<n.length;i+=2){const e=n[i],s=n[i+1];if(!e||void 0===s)return null;if("text"===t||"text"===s)r[e]="text";else if("geospatial"===t||"2dsphere"===s||"2d"===s)r[e]="2d"===s?"2d":"2dsphere";else{const t=Number(s);if(Number.isNaN(t)||1!==t&&-1!==t)return null;r[e]=t}}return r}async close(){if(this._initialized){for(const[e,t]of this.indexes)await t.close();await this._maybeCompactDocuments(),await this.documents.close(),this._releaseDocuments&&(await this._releaseDocuments(),this._releaseDocuments=null)}}async _maybeCompactDocuments(){if(!this.documents||!this.documents.file)return;const e=await Nt(this.documentsPath);if(e!==this.documentsVersion)return;const t=this.documents.file.getFileSize();if(!t||t<ft)return;const n=e+1,r=dt(this.documentsPath,n),i=await Ot(r,{reset:!0});await this.documents.compact(i),await It(this.documentsPath,n,e)}generateIndexName(e){const t=[];for(const n in e)e.hasOwnProperty(n)&&t.push(n+"_"+e[n]);return t.join("_")}isTextIndex(e){for(const t in e)if("text"===e[t])return!0;return!1}isGeospatialIndex(e){for(const t in e)if("2dsphere"===e[t]||"2d"===e[t])return!0;return!1}async _getIndexPath(e,t){const n=String(e).replace(/[^a-zA-Z0-9_-]/g,"_");return"text"===t?`${this.path}/${n}.textindex`:"geospatial"===t?`${this.path}/${n}.rtree.bj`:`${this.path}/${n}.bplustree.bj`}async _buildIndex(e,t,n={}){let r,i,s;this._initialized||await this._initialize(),this.isTextIndex(t)?(s="text",i=await this._getIndexPath(e,s),r=new Et(e,t,i,n)):this.isGeospatialIndex(t)?(s="geospatial",i=await this._getIndexPath(e,s),r=new Ft(e,t,i,n)):(s="regular",i=await this._getIndexPath(e,s),r=new At(e,t,i,n)),await r.open(),"function"==typeof r.clear&&await r.clear();for await(const o of this.documents)o&&o.value&&await r.add(o.value);return this.indexes.set(e,r),r}async updateIndexesOnInsert(e){const t=[];for(const[n,r]of this.indexes)t.push((async()=>{await this._ensureIndexOpen(r),await r.add(e)})());t.length>0&&await Promise.all(t)}async updateIndexesOnDelete(e){const t=[];for(const[n,r]of this.indexes)t.push((async()=>{await this._ensureIndexOpen(r),await r.remove(e)})());t.length>0&&await Promise.all(t)}async _ensureIndexOpen(e){e&&"function"==typeof e.open&&!e.isOpen&&await e.open()}planQuery(e){const t=this.queryPlanner.plan(e);return{useIndex:"full_scan"!==t.type,planType:t.type,indexNames:t.indexes,docIds:null,estimatedCost:t.estimatedCost,indexOnly:t.indexOnly||!1}}async planQueryAsync(e){const t=this.queryPlanner.plan(e),n=await this.queryPlanner.execute(t);return{useIndex:"full_scan"!==t.type,planType:t.type,indexNames:t.indexes,docIds:n,estimatedCost:t.estimatedCost,indexOnly:t.indexOnly||!1}}getTextIndex(e){for(const[t,n]of this.indexes)if(n instanceof Et&&n.indexedFields.includes(e))return n;return null}async aggregate(e){const t=Rt.start("collection","aggregate",{collection:this.name,stageCount:e?.length||0});if(!e||!N(e))throw new V("Pipeline must be an array",{collection:this.name,code:k});const n=Rt.start("collection","aggregate.loadDocuments");let r=[];const i=this.find({});for(await i._ensureInitialized();await i.hasNext();)r.push(await i.next());Rt.end(n,{docCount:r.length});for(let s=0;s<e.length;s++){const t=e[s],n=Object.keys(t);if(1!==n.length)throw new V("Each pipeline stage must have exactly one key",{collection:this.name,code:k});const i=n[0],o=t[i],a=Rt.start("collection",`aggregate.${i}`,{inputDocs:r.length});if("$match"===i){const e=[];for(let t=0;t<r.length;t++)Ye(r[t],o)&&e.push(r[t]);r=e,Rt.end(a,{outputDocs:r.length})}else if("$project"===i){const e=[];for(let t=0;t<r.length;t++)e.push(Vt(o,r[t]));r=e,Rt.end(a,{outputDocs:r.length})}else if("$addFields"===i||"$set"===i){const e=[];for(let t=0;t<r.length;t++){const n=_(r[t]);for(const e in o){const i=o[e];n[e]=Ie(i,r[t])}e.push(n)}r=e,Rt.end(a,{outputDocs:r.length})}else if("$unset"===i){const e=[];let t=[];"string"==typeof o?t=[o]:Array.isArray(o)?t=o:"object"==typeof o&&(t=Object.keys(o));for(let n=0;n<r.length;n++){const i=_(r[n]);for(let e=0;e<t.length;e++){const n=t[e],r=n.split(".");if(1===r.length)delete i[n];else{let e=i;for(let t=0;t<r.length-1&&(null!=e&&null!=e);t++)e=e[r[t]];null!=e&&null!=e&&delete e[r[r.length-1]]}}e.push(i)}r=e,Rt.end(a,{outputDocs:r.length})}else if("$sort"===i){const e=Object.keys(o);r.sort(function(t,n){for(let r=0;r<e.length;r++){const i=e[r];if(void 0===t[i]&&void 0!==n[i])return-1*o[i];if(void 0!==t[i]&&void 0===n[i])return 1*o[i];if(t[i]<n[i])return-1*o[i];if(t[i]>n[i])return 1*o[i]}return 0}),Rt.end(a,{outputDocs:r.length})}else if("$limit"===i)r=r.slice(0,o),Rt.end(a,{outputDocs:r.length});else if("$skip"===i)r=r.slice(o),Rt.end(a,{outputDocs:r.length});else if("$group"===i){const e={},t=o._id;for(let i=0;i<r.length;i++){const n=r[i];let s;s=null==t?null:Ie(t,n);const o=JSON.stringify(s);e[o]||(e[o]={_id:s,docs:[],accumulators:{}}),e[o].docs.push(n)}const n=[];for(const r in e){const t=e[r],i={_id:t._id};for(const e in o){if("_id"===e)continue;const n=o[e],r=Object.keys(n);if(1!==r.length)continue;const s=r[0],a=n[s];if("$sum"===s){let n=0;for(let e=0;e<t.docs.length;e++){const r=Ie(a,t.docs[e]);"number"==typeof r?n+=r:null!=r&&(n+=Number(r)||0)}i[e]=n}else if("$avg"===s){let n=0,r=0;for(let e=0;e<t.docs.length;e++){const i=Ie(a,t.docs[e]);null!=i&&(n+=Number(i)||0,r++)}i[e]=r>0?n/r:0}else if("$min"===s){let n;for(let e=0;e<t.docs.length;e++){const r=Ie(a,t.docs[e]);void 0!==r&&(void 0===n||r<n)&&(n=r)}i[e]=n}else if("$max"===s){let n;for(let e=0;e<t.docs.length;e++){const r=Ie(a,t.docs[e]);void 0!==r&&(void 0===n||r>n)&&(n=r)}i[e]=n}else if("$push"===s){const n=[];for(let e=0;e<t.docs.length;e++){const r=Ie(a,t.docs[e]);n.push(r)}i[e]=n}else if("$addToSet"===s){const n={};for(let e=0;e<t.docs.length;e++){const r=Ie(a,t.docs[e]);n[JSON.stringify(r)]=r}const r=[];for(const e in n)r.push(n[e]);i[e]=r}else if("$first"===s)t.docs.length>0&&(i[e]=Ie(a,t.docs[0]));else if("$last"===s)t.docs.length>0&&(i[e]=Ie(a,t.docs[t.docs.length-1]));else if("$stdDevPop"===s){const n=[];for(let e=0;e<t.docs.length;e++){const r=Ie(a,t.docs[e]);"number"==typeof r&&n.push(r)}if(n.length>0){const t=n.reduce((e,t)=>e+t,0)/n.length,r=n.reduce((e,n)=>e+Math.pow(n-t,2),0)/n.length;i[e]=Math.sqrt(r)}else i[e]=0}else if("$stdDevSamp"===s){const n=[];for(let e=0;e<t.docs.length;e++){const r=Ie(a,t.docs[e]);"number"==typeof r&&n.push(r)}if(n.length>1){const t=n.reduce((e,t)=>e+t,0)/n.length,r=n.reduce((e,n)=>e+Math.pow(n-t,2),0)/(n.length-1);i[e]=Math.sqrt(r)}else i[e]=0}else if("$mergeObjects"===s){const n={};for(let e=0;e<t.docs.length;e++){const r=Ie(a,t.docs[e]);"object"!=typeof r||null===r||Array.isArray(r)||Object.assign(n,r)}i[e]=n}}n.push(i)}r=n,Rt.end(a,{outputDocs:r.length,groupCount:Object.keys(e).length})}else if("$count"===i)r=[{[o]:r.length}],Rt.end(a,{outputDocs:r.length});else if("$unwind"===i){const e=[];let t=o;"string"==typeof t&&"$"===t.charAt(0)&&(t=t.substring(1));for(let n=0;n<r.length;n++){const i=r[n],s=v(i,t);if(s&&N(s)&&s.length>0)for(let n=0;n<s.length;n++){const r=_(i),o=t.split(".");let a=r;for(let e=0;e<o.length-1;e++)a[o[e]]||(a[o[e]]={}),a=a[o[e]];a[o[o.length-1]]=s[n],e.push(r)}}r=e,Rt.end(a,{outputDocs:r.length})}else if("$sortByCount"===i){const e={};for(let t=0;t<r.length;t++){const n=r[t],i=Ie(o,n),s=JSON.stringify(i);e[s]||(e[s]={_id:i,count:0}),e[s].count++}r=Object.values(e).sort((e,t)=>t.count-e.count)}else if("$replaceRoot"===i||"$replaceWith"===i){const e=[],t="$replaceRoot"===i?o.newRoot:o;for(let n=0;n<r.length;n++){const i=Ie(t,r[n]);if("object"!=typeof i||null===i||Array.isArray(i))throw new V("$replaceRoot expression must evaluate to an object",{collection:this.name,code:k});e.push(i)}r=e}else if("$sample"===i){const e=o.size||1;if("number"!=typeof e||e<0)throw new V("$sample size must be a non-negative number",{collection:this.name,code:k});const t=[...r];for(let n=t.length-1;n>0;n--){const e=Math.floor(Math.random()*(n+1));[t[n],t[e]]=[t[e],t[n]]}r=t.slice(0,Math.min(e,t.length))}else if("$bucket"===i){if(!o.groupBy||!o.boundaries)throw new V("$bucket requires groupBy and boundaries",{collection:this.name,code:k});const e=o.boundaries,t=o.default,n=o.output||{count:{$sum:1}},i={};for(let r=0;r<e.length-1;r++){i[JSON.stringify(e[r])]={_id:e[r],docs:[]}}void 0!==t&&(i.default={_id:t,docs:[]});for(let a=0;a<r.length;a++){const n=r[a],s=Ie(o.groupBy,n);let c=!1;for(let t=0;t<e.length-1;t++)if(s>=e[t]&&s<e[t+1]){i[JSON.stringify(e[t])].docs.push(n),c=!0;break}c||void 0===t||i.default.docs.push(n)}const s=[];for(const r in i){const e=i[r];if(0===e.docs.length)continue;const t={_id:e._id};for(const r in n){const i=n[r],s=Object.keys(i);if(1!==s.length)continue;const o=s[0],a=i[o];if("$sum"===o){let n=0;for(let t=0;t<e.docs.length;t++){const r=Ie(a,e.docs[t]);"number"==typeof r?n+=r:null!=r&&(n+=Number(r)||0)}t[r]=n}else if("$avg"===o){let n=0,i=0;for(let t=0;t<e.docs.length;t++){const r=Ie(a,e.docs[t]);null!=r&&(n+=Number(r)||0,i++)}t[r]=i>0?n/i:0}else if("$push"===o){const n=[];for(let t=0;t<e.docs.length;t++){const r=Ie(a,e.docs[t]);n.push(r)}t[r]=n}else if("$addToSet"===o){const n={};for(let t=0;t<e.docs.length;t++){const r=Ie(a,e.docs[t]);n[JSON.stringify(r)]=r}t[r]=Object.values(n)}}s.push(t)}r=s.sort((e,t)=>e._id<t._id?-1:e._id>t._id?1:0)}else if("$bucketAuto"===i){if(!o.groupBy||!o.buckets)throw new V("$bucketAuto requires groupBy and buckets",{collection:this.name,code:k});const e=o.buckets,t=o.output||{count:{$sum:1}};if(0===r.length)r=[];else{const n=r.map(e=>({value:Ie(o.groupBy,e),doc:e})).sort((e,t)=>e.value<t.value?-1:e.value>t.value?1:0),i=Math.ceil(n.length/e),s=[];for(let t=0;t<e&&t*i<n.length;t++){const e=t*i,r=Math.min((t+1)*i,n.length),o=n.slice(e,r);if(0===o.length)continue;const a={_id:{min:o[0].value,max:(n.length,o[o.length-1].value)},docs:o.map(e=>e.doc)};s.push(a)}const a=[];for(let e=0;e<s.length;e++){const n=s[e],r={_id:n._id};for(const e in t){const i=t[e],s=Object.keys(i);if(1!==s.length)continue;const o=s[0],a=i[o];if("$sum"===o){let t=0;for(let e=0;e<n.docs.length;e++){const r=Ie(a,n.docs[e]);"number"==typeof r?t+=r:null!=r&&(t+=Number(r)||0)}r[e]=t}else if("$avg"===o){let t=0,i=0;for(let e=0;e<n.docs.length;e++){const r=Ie(a,n.docs[e]);null!=r&&(t+=Number(r)||0,i++)}r[e]=i>0?t/i:0}else if("$push"===o){const t=[];for(let e=0;e<n.docs.length;e++){const r=Ie(a,n.docs[e]);t.push(r)}r[e]=t}}a.push(r)}r=a}}else if("$out"===i){const e=o;if("string"!=typeof e)throw new V("$out requires a string collection name",{collection:this.name,code:k});this.db.collections.has(e)&&await this.db.dropCollection(e);const t=this.db[e];for(let n=0;n<r.length;n++){const e=r[n],i=e._id;"object"==typeof i&&i.toString?i.toString():String(i),await t.insertOne(e)}r=[]}else if("$merge"===i){let e,t="_id",n="merge",i="insert";if("string"==typeof o?e=o:"object"==typeof o&&(e=o.into,t=o.on||t,n=o.whenMatched||n,i=o.whenNotMatched||i),!e)throw new V("$merge requires a target collection",{collection:this.name,code:k});const s=this.db[e];for(let o=0;o<r.length;o++){const e=r[o],a="string"==typeof t?t:t[0],c=v(e,a),l=s.find({[a]:c});await l._ensureInitialized();const u=await l.hasNext()?await l.next():null;if(u){if("replace"===n)await s.replaceOne({_id:u._id},e);else if("merge"===n){const t=Object.assign({},u,e);await s.replaceOne({_id:u._id},t)}else if("keepExisting"===n);else if("fail"===n)throw new V("$merge failed: duplicate key",{collection:this.name,code:T})}else if("insert"===i)await s.insertOne(e);else if("discard"===i);else if("fail"===i)throw new V("$merge failed: document not found",{collection:this.name,code:k})}r=[]}else if("$lookup"===i){if(!(o.from&&o.localField&&o.foreignField&&o.as))throw new V("$lookup requires from, localField, foreignField, and as",{collection:this.name,code:k});if(!this.db.getCollectionNames().includes(o.from))throw new V("$lookup: collection not found: "+o.from,{collection:this.name,code:P});const e=this.db[o.from],t=[];for(let n=0;n<r.length;n++){const i=_(r[n]),s=v(i,o.localField),a=[],c=e.find({[o.foreignField]:s});for(await c._ensureInitialized();await c.hasNext();)a.push(await c.next());i[o.as]=a,t.push(i)}r=t}else if("$graphLookup"===i){if(!(o.from&&o.startWith&&o.connectFromField&&o.connectToField&&o.as))throw new V("$graphLookup requires from, startWith, connectFromField, connectToField, and as",{collection:this.name,code:k});if(!this.db.getCollectionNames().includes(o.from))throw new V("$graphLookup: collection not found: "+o.from,{collection:this.name,code:P});const e=this.db[o.from],t=void 0!==o.maxDepth?o.maxDepth:Number.MAX_SAFE_INTEGER,n=o.depthField,i=o.restrictSearchWithMatch,s=[];for(let a=0;a<r.length;a++){const c=_(r[a]),l=Ie(o.startWith,r[a]),u=/* @__PURE__ */new Set,h=[],f=[{value:l,depth:0}];for(;f.length>0;){const{value:r,depth:s}=f.shift();if(s>t)continue;const a=JSON.stringify(r);if(u.has(a))continue;u.add(a);let c={[o.connectToField]:r};i&&(c={$and:[c,i]});const l=e.find(c);for(await l._ensureInitialized();await l.hasNext();){const e=await l.next(),t=_(e);n&&(t[n]=s),h.push(t);const r=v(e,o.connectFromField);null!=r&&f.push({value:r,depth:s+1})}}c[o.as]=h,s.push(c)}r=s}else if("$facet"===i){if("object"!=typeof o||Array.isArray(o))throw new V("$facet requires an object with pipeline definitions",{collection:this.name,code:k});const e={};for(const t in o){const n=o[t];if(!Array.isArray(n))throw new V("$facet pipeline must be an array",{collection:this.name,code:k});let i=r.map(e=>_(e));for(let e=0;e<n.length;e++){const t=n[e],r=Object.keys(t);if(1!==r.length)throw new V("Each pipeline stage must have exactly one key",{collection:this.name,code:k});const s=r[0],o=t[s];if("$match"===s){const e=[];for(let t=0;t<i.length;t++)Ye(i[t],o)&&e.push(i[t]);i=e}else if("$project"===s){const e=[];for(let t=0;t<i.length;t++)e.push(Vt(o,i[t]));i=e}else if("$limit"===s)i=i.slice(0,o);else if("$skip"===s)i=i.slice(o);else if("$sort"===s){const e=Object.keys(o);i.sort(function(t,n){for(let r=0;r<e.length;r++){const i=e[r];if(void 0===t[i]&&void 0!==n[i])return-1*o[i];if(void 0!==t[i]&&void 0===n[i])return 1*o[i];if(t[i]<n[i])return-1*o[i];if(t[i]>n[i])return 1*o[i]}return 0})}else if("$count"===s)i=[{[o]:i.length}];else if("$group"===s){const e={},t=o._id;for(let r=0;r<i.length;r++){const n=i[r];let s;s=null==t?null:Ie(t,n);const o=JSON.stringify(s);e[o]||(e[o]={_id:s,docs:[],accumulators:{}}),e[o].docs.push(n)}const n=[];for(const r in e){const t=e[r],i={_id:t._id};for(const e in o){if("_id"===e)continue;const n=o[e],r=Object.keys(n);if(1!==r.length)continue;const s=r[0],a=n[s];if("$sum"===s){let n=0;for(let e=0;e<t.docs.length;e++){const r=Ie(a,t.docs[e]);"number"==typeof r?n+=r:null!=r&&(n+=Number(r)||0)}i[e]=n}else if("$avg"===s){let n=0,r=0;for(let e=0;e<t.docs.length;e++){const i=Ie(a,t.docs[e]);null!=i&&(n+=Number(i)||0,r++)}i[e]=r>0?n/r:0}else if("$max"===s){let n;for(let e=0;e<t.docs.length;e++){const r=Ie(a,t.docs[e]);void 0!==r&&(void 0===n||r>n)&&(n=r)}i[e]=n}}n.push(i)}i=n}else if("$sortByCount"===s){const e={};for(let t=0;t<i.length;t++){const n=i[t],r=Ie(o,n),s=JSON.stringify(r);e[s]||(e[s]={_id:r,count:0}),e[s].count++}i=Object.values(e).sort((e,t)=>t.count-e.count)}else if("$sample"===s){const e=o.size||1,t=[...i];for(let n=t.length-1;n>0;n--){const e=Math.floor(Math.random()*(n+1));[t[n],t[e]]=[t[e],t[n]]}i=t.slice(0,Math.min(e,t.length))}else if("$bucket"===s){const e=o.boundaries,t=o.default,n=o.output||{count:{$sum:1}},r={};for(let i=0;i<e.length-1;i++){r[JSON.stringify(e[i])]={_id:e[i],docs:[]}}void 0!==t&&(r.default={_id:t,docs:[]});for(let a=0;a<i.length;a++){const n=i[a],s=Ie(o.groupBy,n);let c=!1;for(let t=0;t<e.length-1;t++)if(s>=e[t]&&s<e[t+1]){r[JSON.stringify(e[t])].docs.push(n),c=!0;break}c||void 0===t||r.default.docs.push(n)}const s=[];for(const i in r){const e=r[i];if(0===e.docs.length)continue;const t={_id:e._id};for(const r in n){const i=n[r],s=Object.keys(i);if(1!==s.length)continue;const o=s[0],a=i[o];if("$sum"===o){let n=0;for(let t=0;t<e.docs.length;t++){const r=Ie(a,e.docs[t]);"number"==typeof r?n+=r:null!=r&&(n+=Number(r)||0)}t[r]=n}}s.push(t)}i=s.sort((e,t)=>e._id<t._id?-1:e._id>t._id?1:0)}}e[t]=i}r=[e]}else if("$redact"===i){const e=[];for(let t=0;t<r.length;t++){const n=r[t],i=Ie(o,n);if("$$DESCEND"===i)e.push(n);else{if("$$PRUNE"===i)continue;("$$KEEP"===i||i)&&e.push(n)}}r=e}else{if("$geoNear"!==i)throw Rt.end(a,{error:!0,stageType:i}),new V("Unsupported aggregation stage: "+i,{collection:this.name,code:k});{if(!o.near||!o.distanceField)throw new V("$geoNear requires near and distanceField",{collection:this.name,code:k});const e=o.near,t=o.distanceField,n=o.maxDistance,i=o.minDistance||0,s=!1!==o.spherical,c=o.key||"location",l=[];for(let o=0;o<r.length;o++){const a=_(r[o]),u=v(a,c);if(!u||!Array.isArray(u)||u.length<2)continue;let h;if(s){const t=6371e3,n=e[1]*Math.PI/180,r=u[1]*Math.PI/180,i=(u[1]-e[1])*Math.PI/180,s=(u[0]-e[0])*Math.PI/180,o=Math.sin(i/2)*Math.sin(i/2)+Math.cos(n)*Math.cos(r)*Math.sin(s/2)*Math.sin(s/2);h=t*(2*Math.atan2(Math.sqrt(o),Math.sqrt(1-o)))}else{const t=u[0]-e[0],n=u[1]-e[1];h=Math.sqrt(t*t+n*n)}h>=i&&(!n||h<=n)&&(a[t]=h,l.push(a))}l.sort((e,n)=>e[t]-n[t]),r=o.limit?l.slice(0,o.limit):l,Rt.end(a,{outputDocs:r.length})}}}return Rt.end(t,{resultCount:r.length}),r}async bulkWrite(){throw new H("bulkWrite",{collection:this.name})}async count(){this._initialized||await this._initialize();let e=0;for await(const t of this.documents)e++;return e}async copyTo(e){this.db.createCollection(e);const t=this.db.getCollection(e);let n=0;const r=this.find({});for(await r._ensureInitialized();await r.hasNext();)await t.insertOne(await r.next()),n++;return n}async createIndex(e,t){if(this._initialized||await this._initialize(),!e||"object"!=typeof e||Array.isArray(e))throw new W("keys",e,"createIndex requires a key specification object",{collection:this.name});const n=t&&t.name?t.name:this.generateIndexName(e);if(this.indexes.has(n)){const t=this.indexes.get(n);if(JSON.stringify(t.keys)!==JSON.stringify(e))throw new R("Index with name '"+n+"' already exists with a different key specification",{code:L,index:n,collection:this.name});return n}return await this._buildIndex(n,e,t),n}dataSize(){throw new H("dataSize",{collection:this.name})}async deleteOne(e){const t=await this.findOne(e);return t?(await this.updateIndexesOnDelete(t),await this.documents.delete(t._id.toString()),this.emit("delete",{_id:t._id}),{deletedCount:1}):{deletedCount:0}}async deleteMany(e){const t=this.find(e);await t._ensureInitialized();const n=[],r=[];for(;await t.hasNext();){const e=await t.next();n.push(e._id),r.push(e)}const i=n.length;for(let s=0;s<n.length;s++)await this.updateIndexesOnDelete(r[s]),this.documents.delete(n[s].toString()),this.emit("delete",{_id:n[s]});return{deletedCount:i}}async distinct(e,t){const n={},r=this.find(t);for(await r._ensureInitialized();await r.hasNext();){const t=await r.next();t[e]&&(n[t[e]]=!0)}return Object.keys(n)}async drop(){this._initialized||await this._initialize();for(const[i,s]of this.indexes)s&&"function"==typeof s.close&&await s.close();this.documents&&"function"==typeof this.documents.close&&await this.documents.close(),this._releaseDocuments&&(await this._releaseDocuments(),this._releaseDocuments=null);try{const e=this.path.split("/").filter(Boolean);let t=await globalThis.navigator.storage.getDirectory();for(const n of e)t=await t.getDirectoryHandle(n,{create:!1});const r=[];for await(const[n,i]of t.entries())r.push(n);for(const i of r)try{await t.removeEntry(i,{recursive:!1})}catch(n){}}catch(r){}const e=this.path.split("/").filter(Boolean),t=e.pop();try{let r=await globalThis.navigator.storage.getDirectory();for(const t of e)r=await r.getDirectoryHandle(t,{create:!1});try{await r.removeEntry(t,{recursive:!0})}catch(n){if("TypeError"!==n.name&&!n.message?.includes("recursive"))throw n;await r.removeEntry(t)}}catch(r){if("NotFoundError"!==r.name&&"ENOENT"!==r.code)throw r}return this.documents=null,this.indexes.clear(),this._initialized=!1,this.db.collections.delete(this.name),this.emit("drop",{collection:this.name}),{ok:1}}async dropIndex(e){if(!this.indexes.has(e))throw new q(e,{collection:this.name});const t=this.indexes.get(e);return t&&"function"==typeof t.clear&&await t.clear(),t&&"function"==typeof t.close&&await t.close(),this.indexes.delete(e),{nIndexesWas:this.indexes.size+1,ok:1}}async dropIndexes(){const e=this.indexes.size;for(const[t,n]of this.indexes)n&&"function"==typeof n.clear&&await n.clear(),n&&"function"==typeof n.close&&await n.close();return this.indexes.clear(),{nIndexesWas:e,msg:"non-_id indexes dropped",ok:1}}ensureIndex(){throw new H("ensureIndex",{collection:this.name})}explain(){throw new H("explain",{collection:this.name})}find(e,t){this._validateProjection(t);const n=this._findInternal(e,t);return new Q(this,e,t,n,J)}_validateProjection(e){if(!e||0===Object.keys(e).length)return;const t=Object.keys(e);let n=!1,r=!1;for(const i of t)if("_id"!==i&&(e[i]?n=!0:r=!0,n&&r))break;if(n&&r)throw new V("Cannot do exclusion on field in inclusion projection",{code:B,collection:this.name})}async _findInternal(e,t){const n=Rt.start("collection","find",{collection:this.name});this._initialized||await this._initialize();const r=null==e?{}:e,i=this._extractNearSpec(r),s=[],o={};if(this.indexes.size>0){const e=Rt.start("collection","find.queryPlanning"),t=await this.planQueryAsync(r);if(Rt.end(e,{useIndex:t.useIndex,docIdsCount:t.docIds?.length||0}),t.useIndex&&t.docIds&&t.docIds.length>0){const e=Rt.start("collection","find.indexLookup");for(const n of t.docIds)if(!o[n]){const e=await this.documents.search(n);e&&Ye(e,r)&&(o[n]=!0,s.push(e))}Rt.end(e,{docsFound:s.length})}else{const e=Rt.start("collection","find.fullScan");for await(const t of this.documents)t&&t.value&&!o[t.value._id]&&Ye(t.value,r)&&(o[t.value._id]=!0,s.push(t.value));Rt.end(e,{docsFound:s.length})}}else{const e=Rt.start("collection","find.fullScan");for await(const t of this.documents)t&&t.value&&!o[t.value._id]&&Ye(t.value,r)&&(o[t.value._id]=!0,s.push(t.value));Rt.end(e,{docsFound:s.length})}if(i){const e=Rt.start("collection","find.nearSort");this._sortByNearDistance(s,i),Rt.end(e)}const a=Rt.start("collection","find.projection"),c=s.map(e=>t?E(t,_(e)):_(e));return Rt.end(a,{docsProcessed:c.length}),Rt.end(n,{docsReturned:c.length,hasIndexes:this.indexes.size>0}),c}_extractNearSpec(e){for(const t of Object.keys(e||{})){if(t.startsWith("$"))continue;const n=e[t];if(n&&"object"==typeof n){if(n.$near){const e=this._parseNearCoordinates(n.$near);if(e)return{field:t,...e}}if(n.$nearSphere){const e=this._parseNearCoordinates(n.$nearSphere);if(e)return{field:t,...e}}}}return null}_parseNearCoordinates(e){let t;if(e&&"object"==typeof e&&(e.$geometry&&e.$geometry.coordinates?t=e.$geometry.coordinates:e.coordinates?t=e.coordinates:Array.isArray(e)&&(t=e)),!t||t.length<2)return null;const[n,r]=t;return"number"!=typeof r||"number"!=typeof n?null:{lat:r,lng:n}}_extractPointCoordinates(e){if(!e)return null;if("FeatureCollection"===e.type&&Array.isArray(e.features)&&e.features.length>0)return this._extractPointCoordinates(e.features[0].geometry);if("Feature"===e.type&&e.geometry)return this._extractPointCoordinates(e.geometry);if("Point"===e.type&&Array.isArray(e.coordinates)&&e.coordinates.length>=2){const[t,n]=e.coordinates;if("number"==typeof n&&"number"==typeof t)return{lat:n,lng:t}}return null}_sortByNearDistance(e,t){const{field:n,lat:r,lng:i}=t;e.sort((e,t)=>{const s=this._extractPointCoordinates(v(e,n)),o=this._extractPointCoordinates(v(t,n));return(s?this._haversineDistance(s.lat,s.lng,r,i):1/0)-(o?this._haversineDistance(o.lat,o.lng,r,i):1/0)})}_haversineDistance(e,t,n,r){const i=(n-e)*Math.PI/180,s=(r-t)*Math.PI/180,o=Math.sin(i/2)*Math.sin(i/2)+Math.cos(e*Math.PI/180)*Math.cos(n*Math.PI/180)*Math.sin(s/2)*Math.sin(s/2);return 6371*(2*Math.atan2(Math.sqrt(o),Math.sqrt(1-o)))}findAndModify(){throw new H("findAndModify",{collection:this.name})}async findOne(e,t){const n=this.find(e,t);return await n._ensureInitialized(),await n.hasNext()?await n.next():null}async findOneAndDelete(e,t){let n=this.find(e);if(t&&t.sort?(n=n.sort(t.sort),await n._ensureInitialized()):await n._ensureInitialized(),!(await n.hasNext()))return null;const r=await n.next();return await this.documents.delete(r._id.toString()),t&&t.projection?E(t.projection,r):r}async findOneAndReplace(e,t,n){let r=this.find(e);if(n&&n.sort?(r=r.sort(n.sort),await r._ensureInitialized()):await r._ensureInitialized(),!(await r.hasNext()))return null;const i=await r.next();return t._id=i._id,await this.documents.add(i._id.toString(),t),n&&n.returnNewDocument?n&&n.projection?E(n.projection,t):t:n&&n.projection?E(n.projection,i):i}async findOneAndUpdate(e,t,n){let r=this.find(e);if(n&&n.sort?(r=r.sort(n.sort),await r._ensureInitialized()):await r._ensureInitialized(),!(await r.hasNext()))return null;const i=await r.next(),s=Object.assign({},i);return ct(t,s,!1,Xe(i,e).arrayFilters,n&&n.arrayFilters),await this.documents.add(i._id.toString(),s),n&&n.returnNewDocument?n&&n.projection?E(n.projection,s):s:n&&n.projection?E(n.projection,i):i}getIndexes(){const e=[];for(const[t,n]of this.indexes)e.push(n.getSpec());return e}getShardDistribution(){throw new H("getShardDistribution",{collection:this.name})}getShardVersion(){throw new H("getShardVersion",{collection:this.name})}getStore(){return this.documents}group(){throw new H("group",{collection:this.name})}async insert(e){return Array==e.constructor?await this.insertMany(e):await this.insertOne(e)}async insertOne(e){const t=Rt.start("collection","insertOne",{collection:this.name});this._initialized||await this._initialize(),null==e._id&&(e._id=new g);const n=Rt.start("collection","insertOne.store");await this.documents.add(e._id.toString(),e),Rt.end(n);const r=Rt.start("collection","insertOne.updateIndexes");return await this.updateIndexesOnInsert(e),Rt.end(r,{indexCount:this.indexes.size}),this.emit("insert",e),Rt.end(t),{insertedId:e._id}}async insertMany(e){const t=Rt.start("collection","insertMany",{collection:this.name,docCount:e.length});this._initialized||await this._initialize();const n=[];for(let r=0;r<e.length;r++){const t=await this.insertOne(e[r]);n.push(t.insertedId)}return Rt.end(t,{insertedCount:n.length}),{insertedIds:n}}isCapped(){throw new H("isCapped",{collection:this.name})}mapReduce(){throw new H("mapReduce",{collection:this.name})}reIndex(){throw new H("reIndex",{collection:this.name})}async replaceOne(e,t,n){const r={},i=this.find(e);if(await i._ensureInitialized(),r.matchedCount=await i.count(),0==r.matchedCount){if(r.modifiedCount=0,n&&n.upsert){const e=t;e._id=new g,await this.documents.add(e._id.toString(),e),await this.updateIndexesOnInsert(e),this.emit("insert",e),r.upsertedId=e._id}}else{r.modifiedCount=1;const e=await i.next();await this.updateIndexesOnDelete(e),t._id=e._id,this.documents.add(e._id.toString(),t),await this.updateIndexesOnInsert(t),this.emit("replace",t)}return r}async remove(e,t){const n=this.find(e);if(await n._ensureInitialized(),await n.hasNext())if(!0===t||t&&t.justOne){const e=await n.next();await this.updateIndexesOnDelete(e),this.documents.delete(e._id.toString())}else for(;await n.hasNext();){const e=await n.next();await this.updateIndexesOnDelete(e),this.documents.delete(e._id.toString())}}renameCollection(){throw new H("renameCollection",{collection:this.name})}save(){throw new H("save",{collection:this.name})}stats(){throw new H("stats",{collection:this.name})}storageSize(){throw new H("storageSize",{collection:this.name})}totalSize(){throw new H("totalSize",{collection:this.name})}totalIndexSize(){throw new H("totalIndexSize",{collection:this.name})}async update(e,t,n){const r=this.find(e);if(await r._ensureInitialized(),await r.hasNext())if(n&&n.multi)for(;await r.hasNext();){const i=await r.next(),s=Xe(i,e).arrayFilters,o=n&&n.arrayFilters;await this.updateIndexesOnDelete(i),ct(t,i,!1,s,o),await this.documents.add(i._id.toString(),i),await this.updateIndexesOnInsert(i)}else{const i=await r.next(),s=Xe(i,e).arrayFilters,o=n&&n.arrayFilters;await this.updateIndexesOnDelete(i),ct(t,i,!1,s,o),await this.documents.add(i._id.toString(),i),await this.updateIndexesOnInsert(i)}else if(n&&n.upsert){const n=lt(e,t,new g);await this.documents.add(n._id.toString(),n),await this.updateIndexesOnInsert(n)}}async updateOne(e,t,n){const r=Rt.start("collection","updateOne",{collection:this.name}),i=Rt.start("collection","updateOne.find"),s=this.find(e);if(await s._ensureInitialized(),Rt.end(i),await s.hasNext()){const r=await s.next(),i=JSON.parse(JSON.stringify(r)),o=Xe(r,e).arrayFilters,a=n&&n.arrayFilters,c=Rt.start("collection","updateOne.updateIndexesOnDelete");await this.updateIndexesOnDelete(r),Rt.end(c);const l=Rt.start("collection","updateOne.applyUpdates");ct(t,r,!1,o,a),Rt.end(l);const u=Rt.start("collection","updateOne.store");this.documents.add(r._id.toString(),r),Rt.end(u);const h=Rt.start("collection","updateOne.updateIndexesOnInsert");await this.updateIndexesOnInsert(r),Rt.end(h,{indexCount:this.indexes.size});const f=this._getUpdateDescription(i,r);this.emit("update",r,f)}else if(n&&n.upsert){const n=lt(e,t,new g);this.documents.add(n._id.toString(),n),await this.updateIndexesOnInsert(n),this.emit("insert",n)}Rt.end(r)}async updateMany(e,t,n){const r=Rt.start("collection","updateMany",{collection:this.name}),i=Rt.start("collection","updateMany.find"),s=this.find(e);await s._ensureInitialized(),Rt.end(i);let o=0;if(await s.hasNext())for(;await s.hasNext();){const r=await s.next(),i=JSON.parse(JSON.stringify(r)),a=Xe(r,e).arrayFilters,c=n&&n.arrayFilters;await this.updateIndexesOnDelete(r),ct(t,r,!1,a,c),this.documents.add(r._id.toString(),r),await this.updateIndexesOnInsert(r);const l=this._getUpdateDescription(i,r);this.emit("update",r,l),o++}else if(n&&n.upsert){const n=lt(e,t,new g);this.documents.add(n._id.toString(),n),await this.updateIndexesOnInsert(n),this.emit("insert",n)}Rt.end(r,{updatedCount:o})}validate(){throw new H("validate",{collection:this.name})}_getUpdateDescription(e,t){const n={},r=[];for(const i in t)"_id"!==i&&JSON.stringify(e[i])!==JSON.stringify(t[i])&&(n[i]=t[i]);for(const i in e)"_id"!==i&&(i in t||r.push(i));return{updatedFields:n,removedFields:r,truncatedArrays:[]}}watch(e=[],t={}){return new Ut(this,e,t)}}function Vt(e,t){const n={},r=Object.keys(e);let i=!1,s=!1;for(const o of r){if("_id"===o)continue;const t=e[o];1===t||!0===t?i=!0:0===t||!1===t||(s=!0)}if(s||i){0!==e._id&&!1!==e._id&&(n._id=t._id);for(const i of r){const r=e[i];"_id"===i?0!==r&&!1!==r||delete n._id:n[i]=1===r||!0===r?v(t,i):Ie(r,t)}}else{for(const e in t)t.hasOwnProperty(e)&&(n[e]=t[e]);for(const t of r)0!==e[t]&&!1!==e[t]||delete n[t]}return n}class Ht{constructor(e){this.options=e||{},this.baseFolder=this.options.baseFolder||"babymongo",this.dbName=this.options.dbName||"default",this.dbFolder=`${this.baseFolder}/${this.dbName}`,this.collections=/* @__PURE__ */new Map;const t=new Proxy(this,{get:(e,t,n)=>t in e?Reflect.get(e,t,n):"symbol"==typeof t||t.startsWith("_")?void 0:"string"==typeof t?e.getCollection(t):void 0});return this._proxy=t,t}async close(){for(const[e,t]of this.collections)await t.close()}cloneCollection(){throw new H("cloneCollection",{database:this.dbName})}cloneDatabase(){throw new H("cloneDatabase",{database:this.dbName})}commandHelp(){throw new H("commandHelp",{database:this.dbName})}copyDatabase(){throw new H("copyDatabase",{database:this.dbName})}createCollection(e){return this.collections.has(e)||this.collections.set(e,new qt(this,e)),{ok:1}}currentOp(){throw new H("currentOp",{database:this.dbName})}async dropCollection(e){if(this.collections.has(e)){const t=this.collections.get(e);"function"==typeof t.drop&&await t.drop(),this.collections.delete(e)}}async dropDatabase(){for(const[r,i]of this.collections)await i.drop();this.collections.clear();const e=this.dbFolder.split("/").filter(Boolean),t=e.pop();try{let n=await globalThis.navigator.storage.getDirectory();for(const t of e)n=await n.getDirectoryHandle(t,{create:!1});await n.removeEntry(t,{recursive:!0})}catch(n){if("NotFoundError"!==n.name&&"ENOENT"!==n.code)throw n}return{ok:1}}eval(){throw new H("eval",{database:this.dbName})}fsyncLock(){throw new H("fsyncLock",{database:this.dbName})}fsyncUnlock(){throw new H("fsyncUnlock",{database:this.dbName})}getCollection(e){if(!this.collections.has(e)){const t=this._proxy||this;this.collections.set(e,new qt(t,e))}return this.collections.get(e)}collection(e){return this.getCollection(e)}getCollectionInfos(){throw new H("getCollectionInfos",{database:this.dbName})}getCollectionNames(){return Array.from(this.collections.keys())}getLastError(){throw new H("getLastError",{database:this.dbName})}getLastErrorObj(){throw new H("getLastErrorObj",{database:this.dbName})}getLogComponents(){throw new H("getLogComponents",{database:this.dbName})}getMongo(){throw new H("getMongo",{database:this.dbName})}getName(){throw new H("getName",{database:this.dbName})}getPrevError(){throw new H("getPrevError",{database:this.dbName})}getProfilingLevel(){throw new H("getProfilingLevel",{database:this.dbName})}getProfilingStatus(){throw new H("getProfilingStatus",{database:this.dbName})}getReplicationInfo(){throw new H("getReplicationInfo",{database:this.dbName})}getSiblingDB(){throw new H("getSiblingDB",{database:this.dbName})}help(){console.log(" help mr mapreduce"),console.log(" db.foo.find() list objects in collection foo"),console.log(" db.foo.find( { a : 1 } ) list objects in foo where a == 1"),console.log(" it result of the last line evaluated; use to further iterate")}hostInfo(){throw new H("hostInfo",{database:this.dbName})}isMaster(){throw new H("isMaster",{database:this.dbName})}killOp(){throw new H("killOp",{database:this.dbName})}listCommands(){throw new H("listCommands",{database:this.dbName})}loadServerScripts(){throw new H("loadServerScripts",{database:this.dbName})}logout(){throw new H("logout",{database:this.dbName})}printCollectionStats(){throw new H("printCollectionStats",{database:this.dbName})}printReplicationInfo(){throw new H("printReplicationInfo",{database:this.dbName})}printShardingStatus(){throw new H("printShardingStatus",{database:this.dbName})}printSlaveReplicationInfo(){throw new H("printSlaveReplicationInfo",{database:this.dbName})}repairDatabase(){throw new H("repairDatabase",{database:this.dbName})}resetError(){throw new H("resetError",{database:this.dbName})}runCommand(){throw new H("runCommand",{database:this.dbName})}serverBuildInfo(){throw new H("serverBuildInfo",{database:this.dbName})}serverCmdLineOpts(){throw new H("serverCmdLineOpts",{database:this.dbName})}serverStatus(){throw new H("serverStatus",{database:this.dbName})}setLogLevel(){throw new H("setLogLevel",{database:this.dbName})}setProfilingLevel(){throw new H("setProfilingLevel",{database:this.dbName})}shutdownServer(){throw new H("shutdownServer",{database:this.dbName})}stats(){throw new H("stats",{database:this.dbName})}version(){throw new H("version",{database:this.dbName})}upgradeCheck(){throw new H("upgradeCheck",{database:this.dbName})}upgradeCheckAllDBs(){throw new H("upgradeCheckAllDBs",{database:this.dbName})}watch(e=[],t={}){return new Ut(this,e,t)}}class Wt{constructor(e={},t=()=>{}){this.options=e,this.databases=/* @__PURE__ */new Map,this.postEvent=t,this.cursors=/* @__PURE__ */new Map,this.cursorCounter=1,this.streams=/* @__PURE__ */new Map,this.streamCounter=1}async dispatch(e){const{target:t,database:n,collection:r,method:i,args:s=[],cursorId:o,streamId:a,cursorOpts:c}=e;if("cursor"===t)return await this._cursorOp(o,i,s);if("changestream"===t)return await this._changeStreamOp(a,i,s);if("client"===t)return await this._call(this,i,s);if(!t||!n||!i)throw new Error("Invalid request payload");const l=this._getDB(n);if("db"===t)return await this._call(l,i,s);if("collection"===t){if(!r)throw new Error("Collection name required for collection target");const e=l.collection(r);return await this._call(e,i,s,c)}throw new Error(`Unknown target: ${t}`)}_getDB(e){if(this.databases.has(e))return this.databases.get(e);const t=new Ht({...this.options,dbName:e});return this.databases.set(e,t),t}async _call(e,t,n,r){if("function"!=typeof e[t])throw new Error(`Method ${t} not found on target`);const i=e[t](...n||[]),s=i&&"function"==typeof i.then?await i:i;return s&&"function"==typeof s.hasNext&&"function"==typeof s.next?await this._registerCursor(s,r):"aggregate"===t&&Array.isArray(s)?await this._registerArrayAsCursor(s):s&&"ChangeStream"===s.constructor?.name||s&&"function"==typeof s.on&&s.hasOwnProperty("pipeline")&&s.hasOwnProperty("_changeCounter")?this._registerChangeStream(s):s}async _registerCursor(e,t={}){t.sort&&(e=e.sort(t.sort)),t.skip&&(e=await e.skip(t.skip)),t.limit&&(e=await e.limit(t.limit)),t.min&&e.min&&(e=e.min(t.min)),t.max&&e.max&&(e=e.max(t.max)),t.hint&&e.hint&&(e=e.hint(t.hint)),t.comment&&e.comment&&(e=e.comment(t.comment)),t.maxTimeMS&&e.maxTimeMS&&(e=e.maxTimeMS(t.maxTimeMS)),t.maxScan&&e.maxScan&&(e=e.maxScan(t.maxScan)),t.returnKey&&e.returnKey&&(e=e.returnKey(t.returnKey)),t.showRecordId&&e.showRecordId&&(e=e.showRecordId(t.showRecordId)),t.collation&&e.collation&&(e=e.collation(t.collation));const n="cur_"+this.cursorCounter++,r=this.options.batchSize||100,i=[];for(;i.length<r&&await e.hasNext();)i.push(await e.next());const s=!(await e.hasNext());return s||this.cursors.set(n,e),{cursorId:n,batch:i,exhausted:s,batchSize:r}}async _registerArrayAsCursor(e){const t="cur_"+this.cursorCounter++,n=this.options.batchSize||100,r=e.slice(0,n),i=e.length<=n;if(!i){const r={position:n,array:e,async hasNext(){return this.position<this.array.length},async next(){if(this.position>=this.array.length)throw new Error("No more documents");return this.array[this.position++]}};this.cursors.set(t,r)}return{cursorId:t,batch:r,exhausted:i,batchSize:n}}async _cursorOp(e,t,n=[]){if(!e)throw new Error("cursorId required");const r=this.cursors.get(e);if(!r){if("close"===t)return{closed:!0};throw new Error(`Cursor not found: ${e}`)}if("close"===t)return this.cursors.delete(e),{closed:!0};if("getMore"===t){const t=(n?.[0]||{}).batchSize||100,i=[];for(;i.length<t&&await r.hasNext();)i.push(await r.next());const s=!(await r.hasNext());return s&&this.cursors.delete(e),{batch:i,exhausted:s,batchSize:t}}throw new Error(`Unknown cursor method: ${t}`)}_registerChangeStream(e){const t="cs_"+this.streamCounter++,n={change:e=>this.postEvent({type:"event",event:"changeStream",payload:{streamId:t,type:"change",data:e}}),error:e=>this.postEvent({type:"event",event:"changeStream",payload:{streamId:t,type:"error",data:{name:e?.name,message:e?.message,stack:e?.stack}}}),close:()=>this.postEvent({type:"event",event:"changeStream",payload:{streamId:t,type:"close"}})};return e.on("change",n.change),e.on("error",n.error),e.on("close",n.close),this.streams.set(t,{stream:e,handlers:n}),{streamId:t}}async _changeStreamOp(e,t){if(!e)throw new Error("streamId required");const n=this.streams.get(e);if(!n)return{closed:!0};if("close"===t){const{stream:t,handlers:r}=n;return t.off("change",r.change),t.off("error",r.error),t.off("close",r.close),"function"==typeof t.close&&await t.close(),this.streams.delete(e),{closed:!0}}throw new Error(`Unknown change stream method: ${t}`)}watch(e=[],t={}){return new Ut(this,e,t)}}function Qt(e,t=/* @__PURE__ */new WeakSet){if(null==e)return e;if("function"==typeof e)return{__function:e.toString()};if(e&&"object"==typeof e&&"function"==typeof e.toString)try{const t=e.toString();if(t&&24===t.length&&/^[0-9a-f]{24}$/i.test(t)&&e.constructor&&"ObjectId"===e.constructor.name)return{__objectId:t}}catch(n){}if(e instanceof g)return{__objectId:e.toString()};if(e instanceof Date)return{__date:e.toISOString()};if("object"==typeof e){if(t.has(e))return;t.add(e)}if(Array.isArray(e))return e.map(e=>Qt(e,t));if("object"==typeof e){const n={};for(const[r,i]of Object.entries(e))n[r]=Qt(i,t);return n}return e}function Jt(e){if(null==e)return e;if("object"==typeof e&&e.__function)return"string"==typeof e.__function?`(${e.__function}).call(this)`:void 0;if("object"==typeof e&&e.__objectId)return new g(e.__objectId);if("object"==typeof e&&e.__date)return new Date(e.__date);if(Array.isArray(e))return e.map(Jt);if("object"==typeof e){const t={};for(const[n,r]of Object.entries(e))t[n]=Jt(r);return t}return e}const Kt="undefined"!=typeof process&&!!process.versions?.node;let Gt,Yt=null;async function Xt(e,t){if(!e||"request"!==e.type)return;Yt&&await Yt;const{id:n,payload:r}=e,i=Jt(r),s=function(e){return Gt||(Gt=new Wt({},e)),Gt}(t);try{const e=await s.dispatch(i);t({type:"response",id:n,success:!0,result:Qt(e)})}catch(o){t({type:"response",id:n,success:!1,error:{name:o?.name,message:o?.message,stack:o?.stack,code:o?.code,$err:o?.$err}})}}Kt&&(Yt=Promise.resolve().then(()=>{const e=new Function("spec","return import(spec)");return Promise.all([e("path"),e("url"),e("node-opfs")])}).then(([e,t,n])=>{const r=e.default,{fileURLToPath:i}=t,{StorageManager:s}=n,o=i(import.meta.url),a=r.dirname(o),c=r.resolve(a,".."),l=new s(r.join(c,".opfs")),u={storage:{getDirectory:()=>l.getDirectory()}};void 0===globalThis.navigator?globalThis.navigator=u:globalThis.navigator.storage=u.storage}).catch(()=>{})),async function(){if(Kt){const{parentPort:e}=await import("worker_threads"),t=t=>e.postMessage(t);e.on("message",e=>Xt(e,t))}else{const e=e=>self.postMessage(e);self.onmessage=t=>Xt(t.data,e)}}().catch(e=>{console.error("Worker initialization failed:",e),"undefined"!=typeof process?process.exit(1):self.postMessage({type:"error",error:e.message})});
|
|
2
|
+
//# sourceMappingURL=babymongo-server-worker.js.map
|