@pixagram/lacerta-db 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Pixa.Pics
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/browser.js ADDED
@@ -0,0 +1,10 @@
1
+ import {Database, Document, Collection} from "./index.js";
2
+ if(typeof window != "undefined"){
3
+ window.Database = Database;
4
+ window.Document = Document;
5
+ window.Collection = Collection;
6
+ }else {
7
+ self.Database = Database;
8
+ self.Document = Document;
9
+ self.Collection = Collection;
10
+ }
@@ -0,0 +1 @@
1
+ (t=>{var e={};function a(r){var s;return(e[r]||(s=e[r]={i:r,l:!1,exports:{}},t[r].call(s.exports,s,s.exports,a),s.l=!0,s)).exports}a.m=t,a.c=e,a.d=function(t,e,r){a.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},a.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},a.t=function(t,e){if(1&e&&(t=a(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(a.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var s in t)a.d(r,s,function(e){return t[e]}.bind(null,s));return r},a.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return a.d(e,"a",e),e},a.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},a.p="",a(a.s=2)})([function(t,e,a){a.r(e);var r=a(1);class s{constructor(t){this.arrayType=t,this.bitMask=this.calculateBitMask()}calculateBitMask(){var t={Uint8Array:255,Uint16Array:65535,Uint32Array:4294967295};if(this.arrayType.name in t)return t[this.arrayType.name];throw new Error("Unsupported array type: "+this.arrayType.name)}performDeltaEncoding(t){this.validateInputType(t,"performDeltaEncoding");var e,a=new this.arrayType(t.length),r=0|t.length,s=0;for(a[0]=0|t[0],s=1;(0|s)<(0|r);s=s+1|0)e=t[s]-t[s-1]&this.bitMask,a[s]=0|e;return a}performDeltaDecoding(t){this.validateInputType(t,"performDeltaDecoding");var e,a=new this.arrayType(t.length),r=0|t.length,s=0;for(a[0]=0|t[0],s=1;(0|s)<(0|r);s=s+1|0)e=a[s-1]+t[s]&this.bitMask,a[s]=0|e;return a}validateInputType(t,e){if(!(t instanceof this.arrayType))throw new Error(`Input data type does not match for method ${e}. Expected: `+this.arrayType.name)}}class i{constructor(t){this.bitArray=new Uint8Array(t+7>>3)}setBit(t,e){var a=1<<(t|=0)%8;this.bitArray[t=t/8|0]=(e|=0)?this.bitArray[t]|a:this.bitArray[t]&~a}getBit(t){return this.bitArray[(t|=0)/8|0]&1<<t%8?1:0}}var n=new class{constructor(){this.deltaEncoder8Bit=new s(Uint8Array),this.deltaEncoder16Bit=new s(Uint16Array),this.deltaEncoder32Bit=new s(Uint32Array)}getDeltaEncoder(t){switch(t){case"Uint8Array":case"Int8Array":case"Uint8ClampedArray":return this.deltaEncoder8Bit;case"Uint16Array":case"Int16Array":return this.deltaEncoder16Bit;case"Uint32Array":case"Int32Array":case"Float32Array":case"Float64Array":return this.deltaEncoder32Bit;default:throw new Error("Unknown TypedArray type.")}}compress(t){var e=t.constructor,a=e.name,r=t.length,s=this.getDeltaEncoder(a).performDeltaEncoding(new e(t.buffer)),n=new i(t.length),o=[];let c=s[0];o.push(c);for(let t=1;t<s.length;t++)s[t]===c?n.setBit(t,!0):(o.push(s[t]),c=s[t]);return this.packData(o,n,r,e.BYTES_PER_ELEMENT)}packData(t,e,a,r){r=t.length*r;var s=(e=e.bitArray).length;return(s=new Uint8Array(9+r+s))[0]=this.getDataTypeId(t),s.set(this.convertLengthToBytes(r),1),s.set(this.convertLengthToBytes(a),5),s.set(t,9),s.set(e,9+r),s}convertLengthToBytes(t){return Uint8Array.of(t>>0&255,t>>8&255,t>>16&255,t>>24&255)}getDataTypeId(t){return{Uint8Array:1,Int8Array:2,Uint8ClampedArray:3,Uint16Array:4,Int16Array:5,Uint32Array:6,Int32Array:7,Float32Array:8,Float64Array:9}[t.constructor.name]||0}decompress(t){var e=t[0],a=this.extractLengthFromBytes(t,1),r=this.extractLengthFromBytes(t,5),s=new Uint8Array(t.subarray(9,9+a)),n=(t=new Uint8Array(t.subarray(9+a)),new(a=this.getArrayConstructorByTypeId(e))(s.buffer)),o=new i(8*t.length),c=(o.bitArray=t,new a(r));let h=0;for(let t=0;(0|t)<(0|r);t=t+1|0)o.getBit(t)?c[t]=c[t-1|0]:c[t]=n[h++];return this.getDeltaEncoder(a.name).performDeltaDecoding(c)}extractLengthFromBytes(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24}getArrayConstructorByTypeId(t){return{1:Uint8Array,2:Int8Array,3:Uint8ClampedArray,4:Uint16Array,5:Int16Array,6:Uint32Array,7:Int32Array,8:Float32Array,9:Float64Array}[t]||Uint8Array}},o=class{constructor(t){this._buffers=new WeakMap,this._store={},this._nextId=0,this._compress=t?n.compress.bind(n):function(t){return t},this._decompress=t?n.decompress.bind(n):function(t){return t}}_generateId(){var t=this._nextId;return this._nextId++,t}clear(){this._buffers=new WeakMap,this._store={},this._nextId=0}insert(t,e){if(void 0===e){if(this._buffers.has(t))return this._buffers.get(t);e=this._generateId()}else if(this._store.hasOwnProperty(e))throw new Error(`ID ${e} is already in use.`);return e=parseInt(e),this._buffers.set(t,e),this._store[e]=t,e}retrieve(t){return this._store[parseInt(t)]}retrieveAll(){var t={},e=Object.entries(this._store);for(let s=0;s<e.length;s++){var[a,r]=e[s],r=this._compress(new Uint8Array(r)).buffer;t[parseInt(a)]=r}return t}insertAll(t){var e=Object.entries(t);for(let t=0;t<e.length;t++){var[a,r]=e[t],r=this._decompress(new Uint8Array(r)).buffer;this.insert(r,parseInt(a))}}},c=new class{constructor(){this._packBufferTemp8=new Uint8Array(15e3),this._headerByteLength=0,this._offset=0,this._b64=new r.B64chromium,this._b64Base64ToBytes=this._b64.base64ToBytes.bind(this._b64),this._b64BytesToBase64=this._b64.bytesToBase64.bind(this._b64),this._textDecoder=new TextDecoder,this._textDecoderFunction=this._textDecoder.decode.bind(this._textDecoder),this._textEncoder=new TextEncoder,this._textEncoderFunction=this._textEncoder.encode.bind(this._textEncoder),this._textEncoderIntoFunction=this._textEncoder.encodeInto.bind(this._textEncoder),this.encodeOtherBound=this.encodeOther.bind(this),this.decodeOtherBound=this.decodeOther.bind(this),this.stringifyBound=this._innerStringify.bind(this),this.parseBound=this._innerParse.bind(this),this.use_compressor=!1,this._setEngine()}_setEngine(){this.engine=new class{constructor(t,e,a,r,s,i,n,c,h){this._hasher=new class{constructor(t){this._chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",this._charLookup={};for(let t=0;t<this._chars.length;t++)this._charLookup[this._chars[t]]=t;this._bitPerChar=6,this._accumulatorBitNumber=32,this._outputLength=Math.max(1,Math.min(0|t,this._accumulatorBitNumber/this._bitPerChar|0)),this._primes=Uint32Array.of(2654435761,2246822519,3266489917,668265263),this._values=new Uint32Array(this._primes.length+2),this.imul=Math.imul,this.rotl=function(t,e){return(t>>>=0)<<(e&=31)|t>>>32-e}}get outputLength(){return this._outputLength}get chars(){return this._chars}get finalValue(){return this._values[4]}set finalValue(t){return this._values[4]=(0|t)>>>0}get primes(){return this._primes}get values(){return this._values}get accumulator(){return this._values}get charLookup(){return this._charLookup}getCharValue(t){return 63&this.charLookup[t]}aggregateCharValue(t,e,a,r){return t<<18|e<<12|a<<6|r}getCharByOffset(t){return this.chars[63&t]}hash(t){this.values.fill(0);for(var e=0,a=0,r=t.length,s=r>>2>>2;e<s;a=++e<<4)this.accumulator[0]=this.accumulator[0]+this.imul(this.aggregateCharValue(this.getCharValue(t[a]),this.getCharValue(t[a+1|0]),this.getCharValue(t[a+2|0]),this.getCharValue(t[a+3|0])),this.primes[0]),this.accumulator[1]=this.accumulator[1]+this.imul(this.aggregateCharValue(this.getCharValue(t[a+4|0]),this.getCharValue(t[a+5|0]),this.getCharValue(t[a+6|0]),this.getCharValue(t[a+7|0])),this.primes[1]),this.accumulator[2]=this.accumulator[2]+this.imul(this.aggregateCharValue(this.getCharValue(t[a+8|0]),this.getCharValue(t[a+9|0]),this.getCharValue(t[a+10|0]),this.getCharValue(t[a+11|0])),this.primes[2]),this.accumulator[3]=this.accumulator[3]+this.imul(this.aggregateCharValue(this.getCharValue(t[a+12|0]),this.getCharValue(t[a+13|0]),this.getCharValue(t[a+14|0]),this.getCharValue(t[a+15|0])),this.primes[3]);for(e<<=2;(0|e)<(0|r);a=(e=(e+1|0)>>>0)<<2)this.accumulator[3&e]=this.accumulator[3&e]+this.imul(this.aggregateCharValue(this.getCharValue(t[a])||0,this.getCharValue(t[a+1|0])||0,this.getCharValue(t[a+2|0])||0,this.getCharValue(t[a+3|0]))||0,this.primes[3&e]);this.finalValue=this.rotl(this.accumulator[0],1)+this.rotl(this.accumulator[1],7)+this.rotl(this.accumulator[2],12)+this.rotl(this.accumulator[3],18)>>>0;for(var i,n=0,o=new Array(this.outputLength);n<this.outputLength;n++)i=63&this.finalValue,o[n]=this.getCharByOffset(i),this.finalValue=(this.finalValue-i)/64>>>0;return o.join("")}}(1),this.hashThis=r||this._hasher.hash.bind(this._hasher),this.base=t||"data:joyson/",this.shortBase=e||"d:j/",this.baseLength=this.base.length,this.shortBaseLength=this.shortBase.length,this.encapsulate=a||function(t){return JSON.stringify(t)},this.encodeObjectOut=s||function(t){return t},this.decodeObjectOut=i||function(t){return t},this.stringifyOut=n||JSON.stringify,this.parseOut=c||JSON.parse,this._initializeErrorConstructors(),this.arrayBufferIDManager=new o(h),this._initializeBufferConstructors(),this._initializeDynamicTypes(["object","number","bigint","map","set","date","string","error","regexp","buffer","boolean","static"])}_initializeDynamicTypes(t){this.dynamicValues={},this.dynamicValuesIdKey={};for(var e=0;e<t.length;e++){var a=t[e];this.dynamicValues[a]={},this.dynamicValues[a].name=a,this.dynamicValues[a].str=this.base+this.dynamicValues[a].name+";",this.dynamicValues[a].id=this.hashThis(this.dynamicValues[a].name),this.dynamicValues[a].shortStr=this.shortBase+this.dynamicValues[a].id+";",this.dynamicValues[a].strCode=new Uint8Array(this.dynamicValues[a].str.split("").map((function(t){return t.charCodeAt(0)}))),this.dynamicValues[a].shortStrCode=new Uint8Array(this.dynamicValues[a].shortStr.split("").map((function(t){return t.charCodeAt(0)}))),this.dynamicValues[a].strLen=this.dynamicValues[a].str.length,this.dynamicValues[a].shortStrLen=this.dynamicValues[a].shortStr.length,this.dynamicValuesIdKey[this.dynamicValues[a].id]=this.dynamicValues[a].name}}_initializeErrorConstructors(){this.errorConstructors={Error:Error,TypeError:TypeError,SyntaxError:SyntaxError,ReferenceError:ReferenceError,RangeError:RangeError,EvalError:EvalError,URIError:URIError,DOMException:DOMException}}_initializeBufferConstructors(){this.bufferConstructors={ArrayBuffer:ArrayBuffer,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int8Array:Int8Array,Uint16Array:Uint16Array,Int16Array:Int16Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Float32Array:Float32Array,Float64Array:Float64Array}}clear(){this.arrayBufferIDManager.clear()}getAllArrayBuffer(){var t=this.arrayBufferIDManager.retrieveAll();return this.clear(),t}setAllArrayBuffer(t){this.clear(),this.arrayBufferIDManager.insertAll(t)}_isNotNumber(t){return isNaN(t)}_isNotFiniteNumber(t){return!isFinite(t)}_isNotObject(t){return null===t}_isNotString(t){return t.includes("\0")}_isError(t){return void 0!==t.name&&t.name in this.errorConstructors}_isBuffer(t){return(t instanceof ArrayBuffer||"object"==typeof t.buffer)&&(t.constructor||{}).name in this.bufferConstructors}_mustDecodeOfType(t){if("string"==typeof t){if(t.startsWith(this.shortBase))return 2;if(t.startsWith(this.base))return 1}return 0}_dataTypeNameFromKey(t){return this.dynamicValuesIdKey[t]}_decode(t,e){var a=t.slice(e?this.shortBaseLength:this.baseLength).split(";"),r=a[0],s=a[1];switch(e?this._dataTypeNameFromKey(r):r){case"static":return this.decodeStatic(s);case"number":return this.decodeSpecialNumber(s);case"bigint":return this.decodeBigNumber(s);case"string":return this.decodeSpecialString(s);case"boolean":return this.decodeBoolean(s);case"map":return this.decodeMap(s);case"set":return this.decodeSet(s);case"date":return this.decodeDate(s);case"regexp":return this.decodeRegexp(s);case"error":return this.decodeError(s);case"buffer":return this.decodeBuffer(s);case"object":return this.decodeSpecialObject(s);default:return this.decodeObjectOut(t,e)}}decode(t,e){switch(this._mustDecodeOfType(t)){case 0:return"object"==typeof t?this.decodeObjectOut(t,e):t;case 1:return this._decode(t,!1);case 2:return this._decode(t,!0)}}decodeStatic(t){switch(t){case"nan":return NaN;case"null":return null;case"undefined":return}}decodeSpecialNumber(t){switch(t){case"nan":return NaN;case"infinity":return 1/0;case"-infinity":return-1/0;case"epsilon":return Number.EPSILON;case"-epsilon":return-Number.EPSILON;case"-0":return parseInt("-0");default:return Number(t)}}decodeBigNumber(t){return BigInt(t)}decodeSpecialString(t){return atob(t)}decodeBoolean(t){return"true"===t}decodeMap(t){return t=atob(t),t=this.parseOut(t),new Map(t)}decodeSet(t){return t=atob(t),t=this.parseOut(t),new Set(t)}decodeDate(t){return new Date(t)||new Date(NaN)}decodeRegexp(t){t=t.split(":");var e=atob(t[0]);t=atob(t[1]);return new RegExp(e,t)}decodeError(t){t=t.split(":");var e=atob(t[0]);t=atob(t[1]);return new this.errorConstructors[e](t)}decodeBuffer(t){var e="ArrayBuffer"===(a=(t=t.split(":"))[0]),a=this.bufferConstructors[a],r=parseInt(t[1],16),s=parseInt(t[2],16);t=parseInt(t[3],16),t=this.arrayBufferIDManager.retrieve(t);return e?t:new a(t,r,s)}decodeSpecialObject(t){return t=atob(t),t=this.parseOut(t),Object(t)}_encodeFinal(t,e,a){return a?this.dynamicValues[t].shortStr+e:this.encapsulate(this.dynamicValues[t].str+e)}encode(t,e){switch(typeof t){case"undefined":return this.encodeStatic(t,e);case"number":return this._isNotNumber(t)?this.encodeStatic(t,e):this.encodeNumber(t,e);case"bigint":return this.encodeBigNumber(t,e);case"string":return this._isNotString(t)?this.encodeSpecialString(t,e):this.encodeString(t,e);case"boolean":return this.encodeBoolean(t,e);case"object":return this._isNotObject(t)?this.encodeStatic(t,e):"function"==typeof t.get?this.encodeMap(t,e):"function"==typeof t.delete?this.encodeSet(t,e):"function"==typeof t.toISOString?this.encodeDate(t,e):"function"==typeof t.exec?this.encodeRegexp(t,e):t!==t.valueOf()?this.encodeSpecialObject(t,e):this._isError(t)?this.encodeError(t,e):this._isBuffer(t)?this.encodeBuffer(t,e):this.encodeObject(t,e)}}encodeStatic(t,e){var a;switch(typeof t){case"number":a="nan";break;case"object":a="null";break;case"undefined":a="undefined"}return this._encodeFinal("static",a,e)}encodeNumber(t,e){var a;switch(t){case NaN:a="nan";break;case 1/0:a="infinity";break;case-1/0:a="-infinity";break;case Number.EPSILON:a="epsilon";break;case-Number.EPSILON:a="-epsilon";break;default:if("-0"===Number(t).toLocaleString())a="-0";else{if(!this._isNotFiniteNumber(t))return e?t:""+t;a=t}}return this._encodeFinal("number",a,e)}encodeBigNumber(t,e){return t=t.toString(),this._encodeFinal("bigint",t,e)}encodeSpecialString(t,e){return t=btoa(t),this._encodeFinal("string",t,e)}encodeString(t,e){return e?""+t:this.encapsulate(t)}encodeBoolean(t,e){return this._encodeFinal("boolean",t?"true":"false",e)}encodeMap(t,e){return t=Object.entries(Object.fromEntries(t)),t=this.stringifyOut(t),t=btoa(t),this._encodeFinal("map",t,e)}encodeSet(t,e){return t=Array.from(t),t=this.stringifyOut(t),t=btoa(t),this._encodeFinal("set",t,e)}encodeDate(t,e){return t=t.toISOString(),this._encodeFinal("date",t,e)}encodeRegexp(t,e){return t=[btoa(t.source),btoa(t.flags)],this._encodeFinal("regexp",t.join(":"),e)}encodeSpecialObject(t,e){return t=this.stringifyOut(t.valueOf()),t=btoa(t),this._encodeFinal("object",t,e)}encodeError(t,e){return t=[btoa(t.name),btoa(t.message)],this._encodeFinal("error",t.join(":"),e)}encodeBuffer(t,e){var a=(i=void 0===t.buffer)?"ArrayBuffer":t.constructor.name,r=t.byteOffset,s=i?t.byteLength:t.length,i=i?t:t.buffer;t=this.arrayBufferIDManager.insert(i),i=[a,parseInt(r).toString(16),parseInt(s).toString(16),parseInt(t).toString(16)];return this._encodeFinal("buffer",i.join(":"),e)}encodeObject(t,e){return this.encodeObjectOut(t,e)}}(void 0,void 0,void 0,void 0,this.encodeOtherBound,this.decodeOtherBound,this.stringifyBound,this.parseBound,this.use_compressor)}get compress(){return this.use_compressor}set compress(t){this.use_compressor=Boolean(t),this._setEngine()}_getComparator(){return function(t){return function(e){return function(a,r){return a={key:a,value:e[a]},t(a,{key:r,value:e[r]})}}}}_stringifyObject(t){if(Array.isArray(t)){for(var e=0,a=t.length,r=((s=Object.keys(t)).length,new Array(a));(0|e)<(0|a);e=(e+1|0)>>>0)r[e]=this.engine.encode(t[e],!1);return"["+r.join(",")+"]"}for(var s,i,n=this._getComparator(),o="",c=(e=0,a=0|(s=Object.keys(t).sort(n&&n(t))).length,"");(0|e)<(0|a);e=(e+1|0)>>>0)if(o=s[e]+"",i=this.engine.encode(t[o],!1))switch(0<(0|c.length)&&(c+=","),0|(0===o.length||o.includes("\0")||o.startsWith("$"))){case 0:c+=this.engine.encode(o,!1)+":"+i;break;case 1:c+='"$'+btoa("$"+o)+'":'+i}return"{"+c+"}"}encodeOther(t,e){return e?this._packObject(t):this._stringifyObject(t)}decodeOther(t,e){return e?this._unpackObject(t):this._parseObject(t)}_stringify(t,e){var a={};if(a.header=this.engine.encode(t,!1),!e){var r,s=this.engine.getAllArrayBuffer();for(r in a.buffers={},s)a.buffers[r]=this._b64BytesToBase64(new Uint8Array(s[r]))}return JSON.stringify(a)}stringify(t){return this._stringify(t,!1)}_innerStringify(t){return this._stringify(t,!0)}_parseObject(t){if(Array.isArray(t)){for(var e=[],a=0,r=t.length;(0|a)<(0|r);a=(a+1|0)>>>0)e.push(this.engine.decode(t[a]));return e}var s,i,n={},o=Object.keys(t),c="";for(a=0,r=0|o.length;(0|a)<(0|r);a=(a+1|0)>>>0)switch(c=o[a],s=this._keyMustDecode(c),i=this.engine.decode(t[c]),0|s){case 0:n[c]=i;break;case 1:n[atob(c.slice(1)).slice(1)]=i}return n}_parse(t,e){var a,r;t=JSON.parse(t);return e||(a=this._b64Base64ToBytes,r={},Object.entries(t.buffers).forEach((function(t){var e=t[0];r[e]=a(t[1]).buffer})),this.engine.setAllArrayBuffer(r)),this.engine.decode(JSON.parse(t.header))}parse(t){return this._parse(t,!1)}_innerParse(t){return this._parse(t,!0)}_packObject(t){if(Array.isArray(t)){for(var e=[],a=0,r=t.length;(0|a)<(0|r);a=(a+1|0)>>>0)e.push(this.engine.encode(t[a],!0));return e}var s,i={},n=Object.keys(t),o="";for(a=0,r=0|n.length;(0|a)<(0|r);a=(a+1|0)>>>0)if(o=n[a]+"",s=this.engine.encode(t[o],!0))switch(0|(""===o||o.includes("\0")||o.startsWith("$"))){case 0:i[this.engine.encode(o,!0)]=s;break;case 1:i["$"+btoa("$"+o)]=s}return i}pack(t){t=JSON.stringify(this.engine.encode(t,!0));var e=this.engine.getAllArrayBuffer(),a=0,r=Object.keys(e).length;for(n in e)a+=e[n].byteLength;var s=2*t.length+5,i=s+a+4;if((i=(this._packBufferTemp8.length<i&&(this._packBufferTemp8=new Uint8Array(i)),this._textEncoderIntoFunction(t,this._packBufferTemp8.subarray(4,4+s)))).written>s)throw new Error("Header in json is too fat!");t=i.written;var n,o=(this._packBufferTemp8[0]=t>>0&255,this._packBufferTemp8[1]=t>>8&255,this._packBufferTemp8[2]=t>>16&255,this._packBufferTemp8[3]=t>>24&255,t);a=4;for(n in this._packBufferTemp8[o+a]=r>>0&255,this._packBufferTemp8[o+a+1]=r>>8&255,this._packBufferTemp8[o+a+2]=r>>16&255,this._packBufferTemp8[o+a+3]=r>>24&255,a+=4,e){var c=e[n],h=c.byteLength;this._packBufferTemp8[o+a]=h>>0&255,this._packBufferTemp8[o+a+1]=h>>8&255,this._packBufferTemp8[o+a+2]=h>>16&255,this._packBufferTemp8[o+a+3]=h>>24&255,a+=4,this._packBufferTemp8.set(new Uint8Array(c),o+a),a+=h}return this._packBufferTemp8.slice(0,o+a)}_keyMustDecode(t){return t.startsWith("$")}_unpackObject(t){if(Array.isArray(t)){for(var e=[],a=0,r=t.length;(0|a)<(0|r);a=(a+1|0)>>>0)e.push(this.engine.decode(t[a],!0));return e}var s,i,n={},o=Object.keys(t),c="";for(a=0,r=0|o.length;(0|a)<(0|r);a=(a+1|0)>>>0)switch(c=o[a],s=this._keyMustDecode(c),i=this.engine.decode(t[c],!0),0|s){case 0:n[c]=i;break;case 1:n[atob(c.slice(1)).slice(1)]=i}return n}unpack(t){for(var e=4+(t[0]<<0|t[1]<<8|t[2]<<16|t[3]<<24),a=4+e,r=JSON.parse(this._textDecoderFunction(t.subarray(4,e))),s=t[e]<<0|t[1+e]<<8|t[2+e]<<16|t[3+e]<<24,i={},n=a,o=0;o<s;o++){var c=t[n]<<0|t[n+1]<<8|t[n+2]<<16|t[n+3]<<24;n+=4,i[o]=t.buffer.slice(n,n+c),n+=c}return this.engine.setAllArrayBuffer(i),this.engine.decode(r,!0)}};a.d(e,"Database",(function(){return D})),a.d(e,"Document",(function(){return B})),a.d(e,"Collection",(function(){return T}));class h{static async saveAttachments(t,e,a,r){var s,i=[];let n=await navigator.storage.getDirectory();for(s of[t,e,a])n=await n.getDirectoryHandle(s,{create:!0});for(let s=0;s<r.length;s++){var o=s.toString(),c=await(await n.getFileHandle(o,{create:!0})).createWritable();c=(await c.write(r[s].data),await c.close(),t+`/${e}/${a}/`+o);i.push(c)}return i}static async getAttachments(t){var e,a=[],r=await navigator.storage.getDirectory();for(e of t)try{var s=e.split("/");let t=r;for(let e=0;e<s.length-1;e++)t=await t.getDirectoryHandle(s[e]);var i=await(await t.getFileHandle(s[s.length-1])).getFile();a.push({path:e,data:i})}catch(t){console.error(`Error retrieving attachment at "${e}": `+t.message)}return a}static async deleteAttachments(t,e,a){var r=[t,e,a];let s=await navigator.storage.getDirectory();for(let t=0;t<r.length-1;t++)s=await s.getDirectoryHandle(r[t]);try{await s.removeEntry(r[r.length-1],{recursive:!0})}catch(t){console.error(`Error deleting attachments for document "${a}": `+t.message)}}toString(){return"[OPFSUtility]"}}class d{static async compress(t){t="string"==typeof t?(new TextEncoder).encode(t):t;var e=new CompressionStream("deflate"),a=e.writable.getWriter();return a.write(t),a.close(),this._streamToUint8Array(e.readable)}static async decompress(t){var e=new DecompressionStream("deflate"),a=e.writable.getWriter();return a.write(t),a.close(),this._streamToUint8Array(e.readable)}static async _streamToUint8Array(t){var e=t.getReader(),a=[];let r=0;for(;;){var{value:s,done:i}=await e.read();if(i)break;a.push(s),r+=s.length}var n,o=new Uint8Array(r);let c=0;for(n of a)o.set(n,c),c+=n.length;return o}toString(){return"[BrowserCompressionUtility]"}}class u{static async encrypt(t,e){var a=crypto.getRandomValues(new Uint8Array(16)),r=(e=await this._deriveKey(e,a),crypto.getRandomValues(new Uint8Array(12))),s=await this._generateChecksum(t);t=this._combineDataAndChecksum(t,s),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,t);return this._wrapIntoUint8Array(a,r,new Uint8Array(s))}static async decrypt(t,e){var{salt:t,iv:a,encryptedData:r}=this._unwrapUint8Array(t),a=(e=await this._deriveKey(e,t),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},e,r),new Uint8Array(t)),{data:e,checksum:r}=this._separateDataAndChecksum(a);t=await this._generateChecksum(e);if(this._verifyChecksum(t,r))return e;throw new Error("Data integrity check failed. The data has been tampered with.")}static async _deriveKey(t,e){var a=new TextEncoder;a=await crypto.subtle.importKey("raw",a.encode(t),{name:"PBKDF2"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:6e5,hash:"SHA-512"},a,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async _generateChecksum(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}static _verifyChecksum(t,e){if(t.length!==e.length)return!1;for(let a=0;a<t.length;a++)if(t[a]!==e[a])return!1;return!0}static _combineDataAndChecksum(t,e){var a=new Uint8Array(t.length+e.length);return a.set(t),a.set(e,t.length),a}static _separateDataAndChecksum(t){var e=t.length-32;return{data:t.slice(0,e),checksum:t.slice(e)}}static _wrapIntoUint8Array(t,e,a){var r=new Uint8Array(t.length+e.length+a.length);return r.set(t,0),r.set(e,t.length),r.set(a,t.length+e.length),r}static _unwrapUint8Array(t){return{salt:t.slice(0,16),iv:t.slice(16,28),encryptedData:t.slice(28)}}toString(){return"[BrowserEncryptionUtility]"}}class l{static openDatabase(t,e=null,a=null){return new Promise((r,s)=>{let i;(i=e?indexedDB.open(t,e):indexedDB.open(t)).onupgradeneeded=e=>{var r=e.target.result,s=e.oldVersion;e=e.newVersion;console.log(`Upgrading database "${t}" from version ${s} to `+e),a&&a(r,s,e)},i.onsuccess=e=>{(e=e.target.result).onclose=()=>{console.log(`Database "${t}" connection is closing.`)},r(e)},i.onerror=e=>{s(new Error(`Failed to open database "${t}": `+e.target.error.message))}})}static async performTransaction(t,e,a,r,s=3,i=null){let n=null;for(let h=0;h<=s;h++)try{if(!t)throw new Error("Database connection is not available.");let s=t.transaction(Array.isArray(e)?e:[e],a);var o=Array.isArray(e)?e.map(t=>s.objectStore(t)):[s.objectStore(e)],c=i||Date.now()+"_"+Math.random();let h=await r(...o,c);return new Promise((t,e)=>{s.oncomplete=()=>t(h),s.onerror=()=>{n=new Error("Transaction failed: "+(s.error?s.error.message:"unknown error")),e(n)},s.onabort=()=>{n=new Error("Transaction aborted: "+(s.error?s.error.message:"unknown reason")),e(n)}})}catch(t){n=t,h<s&&(console.warn(`Transaction failed, retrying... (${s-h} attempts left): `+t.message),await new Promise(t=>setTimeout(t,100*Math.pow(2,h))))}throw new Error(`Transaction ultimately failed after ${s+1} attempts: `+n.message)}static add(t,e){return new Promise((a,r)=>{var s=t.add(e);s.onsuccess=()=>a(),s.onerror=t=>r("Failed to insert record: "+t.target.error.message)})}static put(t,e){return new Promise((a,r)=>{var s=t.put(e);s.onsuccess=()=>a(),s.onerror=t=>r("Failed to put record: "+t.target.error.message)})}static delete(t,e){return new Promise((a,r)=>{var s=t.delete(e);s.onsuccess=()=>a(),s.onerror=t=>r("Failed to delete record: "+t.target.error.message)})}static get(t,e){return new Promise((a,r)=>{var s=t.get(e);s.onsuccess=t=>a(t.target.result),s.onerror=t=>r(`Failed to retrieve record with key ${e}: `+t.target.error.message)})}static getAll(t){return new Promise((e,a)=>{var r=t.getAll();r.onsuccess=t=>e(t.target.result),r.onerror=t=>a("Failed to retrieve records: "+t.target.error.message)})}static count(t){return new Promise((e,a)=>{var r=t.count();r.onsuccess=t=>e(t.target.result),r.onerror=t=>a("Failed to count records: "+t.target.error.message)})}static clear(t){return new Promise((e,a)=>{var r=t.clear();r.onsuccess=()=>e(),r.onerror=t=>a("Failed to clear store: "+t.target.error.message)})}static deleteDatabase(t){return new Promise((e,a)=>{var r=indexedDB.deleteDatabase(t);r.onsuccess=()=>e(),r.onerror=t=>a("Failed to delete database: "+t.target.error.message)})}static iterateCursor(t,e){return new Promise((a,r)=>{var s=t.openCursor();s.onsuccess=t=>{(t=t.target.result)?(e(t.value,t.key),t.continue()):a()},s.onerror=t=>r("Cursor iteration failed: "+t.target.error.message)})}toString(){return"[IndexedDBUtility]"}}class m{static getItem(t){return(t=localStorage.getItem(t))?c.parse(t):null}static setItem(t,e){localStorage.setItem(t,c.stringify(e))}static removeItem(t){localStorage.removeItem(t)}static clear(){localStorage.clear()}toString(){return"[LocalStorageUtility]"}}class _{constructor(){this.queue=[],this.locked=!1}async acquire(){return new Promise(t=>{this.locked?this.queue.push(t):(this.locked=!0,t())})}release(){0<this.queue.length?this.queue.shift()():this.locked=!1}async runExclusive(t){await this.acquire();try{return await t()}finally{this.release()}}toString(){return`[AsyncMutex locked:${this.locked} queue:${this.queue.length}]`}}class g{constructor(t){this._dbName=t,this._metadataKey=`lacertadb_${this._dbName}_metadata`,this._collections=new Map,this._metadata=this._loadMetadata(),this._mutex=new _}async saveMetadata(){return this._mutex.runExclusive(()=>{m.setItem(this.metadataKey,this.getRawMetadata())})}async adjustTotals(t,e){return this._mutex.runExclusive(()=>{this.data.totalSizeKB+=t,this.data.totalLength+=e,this.data.modifiedAt=Date.now()})}_loadMetadata(){var t=m.getItem(this.metadataKey);if(t){for(var e in t.collections){var a=t.collections[e];a=new b(e,this,a);this.collections.set(e,a)}return t}return{name:this._dbName,collections:{},totalSizeKB:0,totalLength:0,modifiedAt:Date.now()}}get data(){return this._metadata}set data(t){this._metadata=t}get name(){return this.data.name}get metadataKey(){return this._metadataKey}get collections(){return this._collections}set collections(t){this._collections=t}get totalSizeKB(){return this.data.totalSizeKB}get totalLength(){return this.data.totalLength}get modifiedAt(){return this.data.modifiedAt}getCollectionMetadata(t){var e;return this.collections.has(t)||(e=new b(t,this),this.collections.set(t,e),this.data.collections[t]=e.getRawMetadata(),this.data.modifiedAt=Date.now()),this.collections.get(t)}getCollectionMetadataData(t){return(t=this.getCollectionMetadata(t))?t.getRawMetadata():{}}removeCollectionMetadata(t){var e=this.collections.get(t);e&&(this.data.totalSizeKB-=e.sizeKB,this.data.totalLength-=e.length,this.collections.delete(t),delete this.data.collections[t],this.data.modifiedAt=Date.now())}getCollectionNames(){return Array.from(this.collections.keys())}getRawMetadata(){for(var[t,e]of this._collections.entries())this.data.collections[t]=e.getRawMetadata();return this.data}setRawMetadata(t){for(var e in this._metadata=t,this._collections.clear(),t.collections){var a=t.collections[e];a=new b(e,this,a);this._collections.set(e,a)}}get dbName(){return this._dbName}get key(){return this._metadataKey}toString(){return`[DatabaseMetadata: ${this.name} | Collections: ${this.collections.size} | Size: ${this.totalSizeKB.toFixed(2)}KB | Documents: ${this.totalLength}]`}}class f extends Error{constructor(t,e,a=null){super(t),this.name="LacertaDBError",this.code=e,this.originalError=a,this.timestamp=Date.now()}toString(){return`[LacertaDBError ${this.code}: ${this.message} at ${new Date(this.timestamp).toISOString()}]`}}let y="COLLECTION_NOT_FOUND",p="COLLECTION_EXISTS";class b{constructor(t,e,a=null){this._collectionName=t,this._databaseMetadata=e,a?this._metadata=a:(this._metadata={name:t,sizeKB:0,length:0,createdAt:Date.now(),modifiedAt:Date.now(),documentSizes:{},documentModifiedAt:{},documentPermanent:{},documentAttachments:{}},this._databaseMetadata.data.collections[t]=this._metadata,this._databaseMetadata.data.modifiedAt=Date.now())}get name(){return this._collectionName}get keys(){return Object.keys(this.documentSizes)}get collectionName(){return this.name}get sizeKB(){return this._metadata.sizeKB}get length(){return this._metadata.length}get modifiedAt(){return this._metadata.modifiedAt}get metadata(){return this._metadata}set metadata(t){return this._metadata=t}get data(){return this.metadata}set data(t){this.metadata=t}get databaseMetadata(){return this._databaseMetadata}set databaseMetadata(t){this._databaseMetadata=t}get documentSizes(){return this.metadata.documentSizes}get documentModifiedAt(){return this.metadata.documentModifiedAt}get documentPermanent(){return this.metadata.documentPermanent}get documentAttachments(){return this.metadata.documentAttachments}set documentSizes(t){this.metadata.documentSizes=t}set documentModifiedAt(t){this.metadata.documentModifiedAt=t}set documentPermanent(t){this.metadata.documentPermanent=t}set documentAttachments(t){this.metadata.documentAttachments=t}updateDocument(t,e,a=!1,r=0){var s=!this.keys.includes(t),i=e-(this.documentSizes[t]||0);s=s?1:0;this.documentSizes[t]=e,this.documentModifiedAt[t]=Date.now(),this.documentPermanent[t]=a?1:0,this.documentAttachments[t]=r,this.metadata.sizeKB+=i,this.metadata.length+=s,this.metadata.modifiedAt=Date.now(),this.databaseMetadata.adjustTotals(i,s)}deleteDocument(t){var e;return t in this.documentSizes&&(e=this.documentSizes[t],delete this.documentSizes[t],delete this.documentModifiedAt[t],delete this.documentPermanent[t],delete this.documentAttachments[t],this.metadata.sizeKB-=e,--this.metadata.length,this.metadata.modifiedAt=Date.now(),this.databaseMetadata.adjustTotals(-e,-1),!0)}updateDocuments(t){for(var{docId:e,docSizeKB:a,isPermanent:r,attachmentCount:s}of t)this.updateDocument(e,a,r,s||0)}getRawMetadata(){return this.metadata}setRawMetadata(t){this.metadata=t}toString(){return`[CollectionMetadata: ${this.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`}}class w{constructor(t,e=null,a=null){this.success=t,this.data=e,this.error=a}toString(){return`[LacertaDBResult success:${this.success} ${this.error?"error:"+this.error:""}]`}}class A{constructor(t){this._dbName=t,this._metadataKey=`lacertadb_${this._dbName}_quickstore_metadata`,this._documentKeyPrefix=`lacertadb_${this._dbName}_quickstore_data_`,this._metadata=this._loadMetadata()}_loadMetadata(){return m.getItem(this._metadataKey)||{totalSizeKB:0,totalLength:0,documentSizesKB:{},documentModificationTime:{},documentPermanent:{}}}_saveMetadata(){m.setItem(this._metadataKey,this._metadata)}setDocumentSync(t,e=null){e=(t=new B(t,e)).packSync();var a=t._id,r=t._permanent||!1,s=(e=c.stringify({_id:t._id,_created:t._created,_modified:t._modified,_permanent:r,_encrypted:t._encrypted,_compressed:t._compressed,packedData:e}),this._documentKeyPrefix+a);localStorage.setItem(s,e),s=e.length/1024;return(e=!(a in this._metadata.documentSizesKB))?this._metadata.totalLength+=1:this._metadata.totalSizeKB-=this._metadata.documentSizesKB[a],this._metadata.documentSizesKB[a]=s,this._metadata.documentModificationTime[a]=t._modified,this._metadata.documentPermanent[a]=r,this._metadata.totalSizeKB+=s,this._saveMetadata(),e}deleteDocumentSync(t,e=!1){var a;return!(this._metadata.documentPermanent[t]&&!e||(e=this._documentKeyPrefix+t,a=this._metadata.documentSizesKB[t]||0,!localStorage.getItem(e))||(localStorage.removeItem(e),delete this._metadata.documentSizesKB[t],delete this._metadata.documentModificationTime[t],delete this._metadata.documentPermanent[t],this._metadata.totalSizeKB-=a,--this._metadata.totalLength,this._saveMetadata(),0))}getAllKeys(){return Object.keys(this._metadata.documentSizesKB)}getDocumentSync(t,e=null){t=this._documentKeyPrefix+t;return(t=localStorage.getItem(t))?(t=c.parse(t),new B(t,e).unpackSync()):null}toString(){return`[QuickStore: ${this._dbName} | Size: ${this._metadata.totalSizeKB.toFixed(2)}KB | Documents: ${this._metadata.totalLength}]`}}class v{constructor(){this.queue=[],this.processing=!1}async execute(t){return new Promise((e,a)=>{this.queue.push({operation:t,resolve:e,reject:a}),this.process()})}async process(){if(!this.processing&&0!==this.queue.length){for(this.processing=!0;0<this.queue.length;){var{operation:t,resolve:e,reject:a}=this.queue.shift();try{e(await t())}catch(t){a(t)}}this.processing=!1}}toString(){return`[TransactionManager processing:${this.processing} queue:${this.queue.length}]`}}class S{constructor(){this._listeners={beforeAdd:[],afterAdd:[],beforeDelete:[],afterDelete:[],beforeGet:[],afterGet:[]}}on(t,e){if(!this._listeners[t])throw new Error(`Event "${t}" is not supported.`);this._listeners[t].push(e)}off(t,e){this._listeners[t]&&-1<(e=this._listeners[t].indexOf(e))&&this._listeners[t].splice(e,1)}_emit(t,...e){if(this._listeners[t])for(var a of this._listeners[t])a(...e)}_cleanup(){for(var t in this._listeners)this._listeners[t]=[]}toString(){return`[Observer listeners:{${Object.entries(this._listeners).map(([t,e])=>t+":"+e.length).join(" ")}}]`}}class D{constructor(t,e={}){this._dbName=t,this._db=null,this._collections=new Map,this._metadata=new g(t),this._settings=new C(t,e),this._quickStore=new A(this._dbName),this._settings.init()}get quickStore(){return this._quickStore}async init(){var t;for(t of(this.db=await l.openDatabase(this.name,void 0,(t,e,a)=>{this._upgradeDatabase(t,e,a)}),this.data.getCollectionNames())){var e=new T(this,t,this.settings);await e.init(),this.collections.set(t,e)}}_createDataStores(t){for(var e of this.collections.keys())this._createDataStore(t,e)}_createDataStore(t,e){t.objectStoreNames.contains(e)||t.createObjectStore(e,{keyPath:"_id"})}_upgradeDatabase(t,e,a){console.log(`Upgrading database "${this.name}" from version ${e} to `+a),t.objectStoreNames.contains("_metadata")||t.createObjectStore("_metadata",{keyPath:"_id"})}async createCollection(t){var e;return this.collections.has(t)?(console.log(`Collection "${t}" already exists.`),new w(!1,this.collections.get(t),new f(`Collection "${t}" already exists`,p))):(this.db.objectStoreNames.contains(t)||(e=this.db.version+1,this.db.close(),this.db=await l.openDatabase(this.name,e,(e,a,r)=>{this._createDataStore(e,t)})),await(e=new T(this,t,this.settings)).init(),this.collections.set(t,e),this.data.getCollectionMetadata(t),await this.data.saveMetadata(),new w(!0,e))}async deleteCollection(t){var e;return this.collections.has(t)?(await(e=this.collections.get(t)).close(),e.observer._cleanup(),await l.performTransaction(this.db,t,"readwrite",t=>l.clear(t)),this.collections.delete(t),this.data.removeCollectionMetadata(t),await this.data.saveMetadata(),new w(!0,null)):new w(!1,null,new f(`Collection "${t}" does not exist`,y))}async getCollection(t){var e;return this.collections.has(t)?new w(!0,this.collections.get(t)):this.db.objectStoreNames.contains(t)?(await(e=new T(this,t,this.settings)).init(),this.collections.set(t,e),new w(!0,e)):new w(!1,null,new f(`Collection "${t}" does not exist`,y))}async close(){var t;for(t of this.collectionsArray)await t.close();this.db&&(this.db.close(),this.db=null)}async deleteDatabase(){await this.close(),await l.deleteDatabase(this.name),m.removeItem(this.data.metadataKey),this.settings.clear(),this.data=null}get name(){return this._dbName}get db(){return this._db}set db(t){this._db=t}get data(){return this.metadata}set data(t){this.metadata=t}get collectionsArray(){return Array.from(this.collections.values())}get collections(){return this._collections}get metadata(){return this._metadata}set metadata(t){this._metadata=t}get totalSizeKB(){return this.data.totalSizeKB}get totalLength(){return this.data.totalLength}get modifiedAt(){return this.data.modifiedAt}get settings(){return this._settings}get settingsData(){return this.settings.data}toString(){return`[Database: ${this.name} | Collections: ${this.collections.size} | Size: ${this.totalSizeKB.toFixed(2)}KB | Documents: ${this.totalLength}]`}}class B{constructor(t,e=null){this._id=t._id||this._generateId(),this._created=t._created||Date.now(),this._permanent=!!t._permanent,this._encrypted=t._encrypted||!!e,this._compressed=t._compressed||!1,this._attachments=t._attachments||t.attachments||[],t.packedData?(this._packedData=t.packedData,this._modified=t._modified||Date.now(),this._data=null):(this._data=t.data||{},this._modified=Date.now(),this._packedData=new Uint8Array(0)),this._encryptionKey=e||""}get attachments(){return this._attachments}set attachments(t){this._attachments=t}get data(){return this._data}get packedData(){return this._packedData}get encryptionKey(){return this._encryptionKey}set data(t){this._data=t}set packedData(t){this._packedData=t}set encryptionKey(t){this._encryptionKey=t}static hasAttachments(t){return t._attachments&&0<t._attachments.length||t.attachments&&0<t.attachments.length}static async getAttachments(t,e,a){var r;return B.hasAttachments(t)?(r=t._attachments||t.attachments,t.attachments=await h.getAttachments(r),Promise.resolve(t)):[]}static isEncrypted(t){return t._encrypted&&t.packedData}static async decryptDocument(t,e){if(B.isEncrypted(t))return e=await u.decrypt(t.packedData,e),e=c.unpack(e),{_id:t._id,_created:t._created,_modified:t._modified,_encrypted:!0,_compressed:t._compressed,_permanent:!!t._permanent,attachments:t.attachments,data:e};throw new Error("Document is not encrypted.")}async pack(){if(!this.data)throw new Error("No data to pack");let t=c.pack(this.data);return this._compressed&&(t=await this._compressData(t)),this._encrypted&&(t=await this._encryptData(t)),this.packedData=t}packSync(){if(!this.data)throw new Error("No data to pack");if(this._encrypted)throw new Error("Packing synchronously a document being encrypted is impossible.");if(this._compressed)throw new Error("Packing synchronously a document being compressed is impossible.");var t=c.pack(this.data);return this.packedData=t}async unpack(){if(!this.data&&0<this.packedData.length){let t=this.packedData;this._encrypted&&(t=await this._decryptData(t)),this._compressed&&(t=await this._decompressData(t)),this.data=c.unpack(t)}return this.data}unpackSync(){if(!this.data&&0<this.packedData.length){if(this._encrypted)throw new Error("Unpacking synchronously a document being encrypted is impossible.");if(this._compressed)throw new Error("Unpacking synchronously a document being compressed is impossible.");this.data=c.unpack(this.packedData)}return this.data}async _encryptData(t){var e=this.encryptionKey;return u.encrypt(t,e)}async _decryptData(t){var e=this.encryptionKey;return u.decrypt(t,e)}async _compressData(t){return d.compress(t)}async _decompressData(t){return d.decompress(t)}_generateId(){return"xxxx-xxxx-xxxx".replace(/[x]/g,()=>(16*Math.random()|0).toString(16))}async objectOutput(t=!1){this.data||await this.unpack();var e={_id:this._id,_created:this._created,_modified:this._modified,_permanent:this._permanent,_encrypted:this._encrypted,_compressed:this._compressed,attachments:this.attachments,data:this.data};return t&&0<this.attachments.length&&(t=await h.getAttachments(this.attachments),e.attachments=t),e}async databaseOutput(){return this.packedData&&0!==this.packedData.length||await this.pack(),{_id:this._id,_created:this._created,_modified:this._modified,_permanent:!!this._permanent,_compressed:this._compressed,_encrypted:this._encrypted,attachments:this.attachments,packedData:this.packedData}}toString(){return`[Document: ${this._id} | Created: ${new Date(this._created).toISOString()} | Encrypted: ${this._encrypted} | Compressed: ${this._compressed} | Permanent: ${this._permanent}]`}}class C{constructor(t,e={}){this._dbName=t,this._settingsKey=`lacertadb_${this._dbName}_settings`,this._data=this._loadSettings(),this._mergeSettings(e)}init(){if(this.set("sizeLimitKB",this.get("sizeLimitKB")||1/0),this.set("bufferLimitKB",this.get("bufferLimitKB")||-.2*this.get("sizeLimitKB")),this.get("bufferLimitKB")<-.8*this.get("sizeLimitKB"))throw new Error("Buffer limit cannot be below -80% of the size limit.");this.set("freeSpaceEvery",this._validateFreeSpaceSetting(this.get("freeSpaceEvery")))}_validateFreeSpaceSetting(t=1e4){if(void 0===t||!1===t||0===t)return 1/0;if(t<1e3&&0!==t)throw new Error("Invalid freeSpaceEvery value. It must be 0, Infinity, or above 1000.");return 1e3<=t&&t<1e4&&console.warn("Warning: freeSpaceEvery value is between 1000 and 10000, which may lead to frequent freeing."),t}_loadSettings(){return m.getItem(this.settingsKey)||{}}_saveSettings(){m.setItem(this.settingsKey,this.data)}_mergeSettings(t){this.data=Object.assign(this.data,t),this._saveSettings()}get(t){return this.data[t]}set(t,e){this.data[t]=e,this._saveSettings()}remove(t){delete this.data[t],this._saveSettings()}clear(){this.data={},this._saveSettings()}get dbName(){return this._dbName}get data(){return this._data}set data(t){this._data=t}get settingsKey(){return this._settingsKey}toString(){return`[Settings: ${this.dbName} | SizeLimit: ${this.get("sizeLimitKB")}KB | BufferLimit: ${this.get("bufferLimitKB")}KB]`}}class T{constructor(t,e,a){this._database=t,this._collectionName=e,this._settings=a,this._metadata=null,this._lastFreeSpaceTime=0,this._observer=new S,this._transactionManager=new v,this._freeSpaceInterval=null,this._freeSpaceHandler=null}get observer(){return this._observer}async createIndex(t,e={}){let a=e.name||t.replace(/\./g,"_");var r=this.database.db.version+1;this.database.db.close(),this.database.db=await l.openDatabase(this.database.name,r,r=>{r.objectStoreNames.contains(this.name)&&!(r=r.transaction([this.name]).objectStore(this.name)).indexNames.contains(a)&&r.createIndex(a,t,{unique:e.unique||!1,multiEntry:e.multiEntry||!1})})}async init(){this.metadata=this.database.metadata.getCollectionMetadata(this.name),this.settingsData.freeSpaceEvery!==1/0&&(this._freeSpaceHandler=()=>this._maybeFreeSpace(),this._freeSpaceInterval=setInterval(this._freeSpaceHandler,this.settingsData.freeSpaceEvery))}get name(){return this._collectionName}get sizes(){return this.metadataData.documentSizes||{}}get modifications(){return this.metadataData.documentModifiedAt||{}}get attachments(){return this.metadataData.documentAttachments||{}}get permanents(){return this.metadataData.documentPermanent||{}}get keys(){return Object.keys(this.sizes)}get documentsMetadata(){var t,e=this.keys,a=this.sizes,r=this.modifications,s=this.permanents,i=this.attachments,n=new Array(e.length),o=0;for(t of e)n[o++]={id:t,size:a[t],modified:r[t],permanent:s[t],attachment:i[t]};return n}get settings(){return this._settings}get settingsData(){return this.settings.data}set settings(t){this._settings=t}get lastFreeSpaceTime(){return this._lastFreeSpaceTime}set lastFreeSpaceTime(t){this._lastFreeSpaceTime=t}get database(){return this._database}get metadata(){return this.database.metadata.getCollectionMetadata(this.name)}get metadataData(){return this.metadata.getRawMetadata()}set metadata(t){this._metadata=t}get sizeKB(){return this.metadataData.sizeKB}get length(){return this.metadataData.length}get totalSizeKB(){return this.sizeKB}get totalLength(){return this.length}get modifiedAt(){return this.metadataData.modifiedAt}get isFreeSpaceEnabled(){return this.settingsData.freeSpaceEvery!==1/0}get shouldRunFreeSpaceSize(){return this.totalSizeKB>this.settingsData.sizeLimitKB+this.settingsData.bufferLimitKB}get shouldRunFreeSpaceTime(){return this.isFreeSpaceEnabled&&Date.now()-this.lastFreeSpaceTime>=this.settingsData.freeSpaceEvery}async _maybeFreeSpace(){if(this.shouldRunFreeSpaceSize||this.shouldRunFreeSpaceTime)return this.freeSpace(this.settingsData.sizeLimitKB)}async addDocument(t,e=null){return this._transactionManager.execute(async()=>{this.observer._emit("beforeAdd",t);var a=new B(t,e),r=[];if(B.hasAttachments(t)){var s=t._attachments||t.attachments;for(let t=0;t<s.length;t++)r.push(`${this.database.name}/${this.name}/${a._id}/`+t);a._attachments=r}let i=await a.databaseOutput();var n,o=i._id,c=i._permanent||!1,d=i.packedData.byteLength/1024;let u=!(o in this.metadataData.documentSizes);try{await l.performTransaction(this.database.db,this.name,"readwrite",t=>u?l.add(t,i):l.put(t,i)),0<r.length&&(n=t._attachments||t.attachments,await h.saveAttachments(this.database.name,this.name,a._id,n)),this.metadata.updateDocument(o,d,c,r.length),await this.database.metadata.saveMetadata()}catch(n){if(0<r.length)try{await h.deleteAttachments(this.database.name,this.name,a._id)}catch(n){}throw n}return await this._maybeFreeSpace(),this.observer._emit("afterAdd",t),u})}async getDocument(t,e=null,a=!1){if(this.observer._emit("beforeGet",t),t in this.metadataData.documentSizes){var r=await l.performTransaction(this.database.db,this.name,"readonly",e=>l.get(e,t));if(r){let t;if(B.isEncrypted(r)){if(!e)return!1;t=new B(r,e)}else t=new B(r);return e=await t.objectOutput(a),this.observer._emit("afterGet",e),e}}return!1}async getDocuments(t,e=null,a=!1){let r=[],s=t.filter(t=>t in this.metadataData.documentSizes);return 0!==s.length&&await l.performTransaction(this.database.db,this.name,"readonly",async t=>{var i,n=s.map(e=>l.get(t,e));for(i of await Promise.all(n))if(i){let t;if(B.isEncrypted(i)){if(!e)continue;t=new B(i,e)}else t=new B(i);var o=await t.objectOutput(a);r.push(o)}}),r}async deleteDocument(t,e=!1){return this.observer._emit("beforeDelete",t),!(this.permanents[t]&&!e)&&t in this.sizes&&(0<(this.metadata.documentAttachments[t]||0)&&await h.deleteAttachments(this.database.name,this.name,t),await l.performTransaction(this.database.db,this.name,"readwrite",e=>l.delete(e,t)),this.metadata.deleteDocument(t),await this.database.metadata.saveMetadata(),this.observer._emit("afterDelete",t),!0)}async freeSpace(t){let e;this.lastFreeSpaceTime=Date.now();var a,r=this.sizeKB;if(0<=t){if(r<=t)return 0;e=r-t}else t=r-(e=-t);let s=0;for([a]of Object.entries(this.metadataData.documentModifiedAt).filter(([t])=>!this.metadataData.documentPermanent[t]).sort((t,e)=>t[1]-e[1]))if(this.sizeKB>t){if(s+=this.metadataData.documentSizes[a],await this.deleteDocument(a,!0),s>=e)break}return s}async query(t={},e={}){let{encryptionKey:a=null,limit:r=1/0,offset:s=0,orderBy:i=null,index:n=null}=e,o=[],c=0,h=0;return await l.performTransaction(this.database.db,this.name,"readonly",async e=>{let d=e,u=(n&&e.indexNames.contains(n)&&(d=e.index(n)),i?d.openCursor(null,"asc"===i?"next":"prev"):d.openCursor());return new Promise((e,i)=>{u.onsuccess=async i=>{if(!(i=i.target.result)||c>=r)e(o);else{var n,d=i.value;if(h<s)h++;else{let e;if(B.isEncrypted(d)){if(!a)return void i.continue();e=new B(d,a)}else e=new B(d);if(0<Object.keys(t).length){var u,l=await e.objectOutput();let a=!0;for(u in t)if((u.includes(".")?(n=l.data,u.split(".").reduce((t,e)=>(t||{})[e],n)):l.data[u])!==t[u]){a=!1;break}if(!a)return void i.continue()}o.push(await e.objectOutput()),c++}i.continue()}},u.onerror=()=>i(u.error)})}),o}async close(){this._freeSpaceInterval&&(clearInterval(this._freeSpaceInterval),this._freeSpaceInterval=null,this._freeSpaceHandler=null)}toString(){return`[Collection: ${this.name} | Database: ${this.database.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`}}},function(t,e,a){var r=(()=>{var t=new ArrayBuffer(2560),e=new Uint8Array(t,0,256),a=new Uint8Array(t,256,256),r=new Uint32Array(t,512,128),s=new Uint32Array(t,1024,128),i=new Uint32Array(t,1536,128),n=new Uint32Array(t,2048,128);e.set(Uint8Array.from("AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHHIIIIJJJJKKKKLLLLMMMMNNNNOOOOPPPPQQQQRRRRSSSSTTTTUUUUVVVVWWWWXXXXYYYYZZZZaaaabbbbccccddddeeeeffffgggghhhhiiiijjjjkkkkllllmmmmnnnnooooppppqqqqrrrrssssttttuuuuvvvvwwwwxxxxyyyyzzzz0000111122223333444455556666777788889999++++////".split("").map((function(t){return 255&t.charCodeAt(0)})))),a.set(Uint8Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map((function(t){return 255&t.charCodeAt(0)})))),r.set(new Uint32Array(128).fill(33554431)),s.set(new Uint32Array(128).fill(33554431)),i.set(new Uint32Array(128).fill(33554431)),n.set(new Uint32Array(128).fill(33554431)),Object.entries({43:[248,57347,8392448,4063232],47:[252,61443,12586752,4128768],48:[208,16387,3328,3407872],49:[212,20483,4197632,3473408],50:[216,24579,8391936,3538944],51:[220,28675,12586240,3604480],52:[224,32771,3584,3670016],53:[228,36867,4197888,3735552],54:[232,40963,8392192,3801088],55:[236,45059,12586496,3866624],56:[240,49155,3840,3932160],57:[244,53251,4198144,3997696],65:[0,0,0,0],66:[4,4096,4194304,65536],67:[8,8192,8388608,131072],68:[12,12288,12582912,196608],69:[16,16384,256,262144],70:[20,20480,4194560,327680],71:[24,24576,8388864,393216],72:[28,28672,12583168,458752],73:[32,32768,512,524288],74:[36,36864,4194816,589824],75:[40,40960,8389120,655360],76:[44,45056,12583424,720896],77:[48,49152,768,786432],78:[52,53248,4195072,851968],79:[56,57344,8389376,917504],80:[60,61440,12583680,983040],81:[64,1,1024,1048576],82:[68,4097,4195328,1114112],83:[72,8193,8389632,1179648],84:[76,12289,12583936,1245184],85:[80,16385,1280,1310720],86:[84,20481,4195584,1376256],87:[88,24577,8389888,1441792],88:[92,28673,12584192,1507328],89:[96,32769,1536,1572864],90:[100,36865,4195840,1638400],97:[104,40961,8390144,1703936],98:[108,45057,12584448,1769472],99:[112,49153,1792,1835008],100:[116,53249,4196096,1900544],101:[120,57345,8390400,1966080],102:[124,61441,12584704,2031616],103:[128,2,2048,2097152],104:[132,4098,4196352,2162688],105:[136,8194,8390656,2228224],106:[140,12290,12584960,2293760],107:[144,16386,2304,2359296],108:[148,20482,4196608,2424832],109:[152,24578,8390912,2490368],110:[156,28674,12585216,2555904],111:[160,32770,2560,2621440],112:[164,36866,4196864,2686976],113:[168,40962,8391168,2752512],114:[172,45058,12585472,2818048],115:[176,49154,2816,2883584],116:[180,53250,4197120,2949120],117:[184,57346,8391424,3014656],118:[188,61442,12585728,3080192],119:[192,3,3072,3145728],120:[196,4099,4197376,3211264],121:[200,8195,8391680,3276800],122:[204,12291,12585984,3342336]}).forEach((function(t){r[parseInt(t[0])]=4294967295&t[1][0],s[parseInt(t[0])]=4294967295&t[1][1],i[parseInt(t[0])]=4294967295&t[1][2],n[parseInt(t[0])]=4294967295&t[1][3]}));class o{constructor(){this._CHNK_L_=Math.pow(108,2)/2|0,this._CHNK_L_STR_=3*this._CHNK_L_|0,this._CHNK_L_BUFF_=4*this._CHNK_L_|0,this._PAD_C_=255&"=".charCodeAt(0),this._E0_=e.slice(0,e.length),this._E1_=a.slice(0,a.length),this._D0_=r.slice(0,r.length),this._D1_=s.slice(0,s.length),this._D2_=i.slice(0,i.length),this._D3_=n.slice(0,n.length),this._AB_=new ArrayBuffer(this._CHNK_L_BUFF_+4|0),this._u32aT_=new Uint32Array(this._AB_,0,1),this._u8aT_=new Uint8Array(this._AB_,0,3),this._T_=new Uint8Array(this._AB_,4,0|this._CHNK_L_BUFF_)}get PAD_C(){return 255&this._PAD_C_}get CHNK_L_STR(){return 0|this._CHNK_L_STR_}get u32aT0(){return this._u32aT_[0]}set u32aT0(t){this._u32aT_[0]=(0|t)>>>0}get u8aTa(){return this._u8aT_[0]}get u8aTb(){return this._u8aT_[1]}get u8aTc(){return this._u8aT_[2]}_base64_decode_u32ax1(t,e){this.u32aT0=this._D0_[255&t.charCodeAt(e=(0|e)>>>0)]|this._D1_[255&t.charCodeAt(e+1|0)]|this._D2_[255&t.charCodeAt(e+2|0)]|this._D3_[255&t.charCodeAt(e+3|0)]}_base64_encode_u8ax4(t,e,a){this._T_[0|(e=(0|e)>>>0)]=this._E0_[t[(0|(a=(0|a)>>>0))>>>0]],this._T_[e+1|0]=this._E1_[(3&t[(0|a)>>>0])<<4|t[(a+1|0)>>>0]>>4&15],this._T_[e+2|0]=this._E1_[(15&t[(a+1|0)>>>0])<<2|t[(a+2|0)>>>0]>>6&3],this._T_[e+3|0]=this._E1_[t[(a+2|0)>>>0]]}_base64_encode_final(t,e,a,r){switch(r=(0|r)>>>0,((a=(0|a)>>>0)-(e=(0|e)>>>0)|0)>>>0){case 1:return this._T_[0|r]=this._E0_[t[(0|e)>>>0]],this._T_[r+1|0]=this._E1_[(3&t[(0|e)>>>0])<<4|t[(e+1|0)>>>0]>>4&15],this._T_[r+2|0]=this._PAD_C_,this._T_[r+3|0]=this._PAD_C_,this._T_.subarray(0,0|(r=r+4|0));case 2:return this._T_[0|r]=this._E0_[t[(0|e)>>>0]],this._T_[r+1|0]=this._E1_[(3&t[(0|e)>>>0])<<4|t[(e+1|0)>>>0]>>4&15],this._T_[r+2|0]=this._E1_[(15&t[(e+1|0)>>>0])<<2|t[(e+2|0)>>>0]>>6&3],this._T_[r+3|0]=this._PAD_C_,this._T_.subarray(0,0|(r=r+4|0));case 0:return this._T_.subarray(0,0|r);default:return this._T_}}_base64_decode_final(t,e,a,r,s){switch(a=(0|a)>>>0,r=(0|r)>>>0,0|(s=(0|s)>>>0)){case 0:return this.u32aT0=(this._D0_[e.charCodeAt(0|a)]|this._D1_[e.charCodeAt(a+1|0)]|this._D2_[e.charCodeAt(a+2|0)]|this._D3_[e.charCodeAt(a+3|0)]|0)>>>0,t[0|r]=255&this.u32aT0,t[r+1|0]=this.u32aT0>>8&255,t[r+2|0]=this.u32aT0>>16&255,r+3|0;case 1:return this.u32aT0=(0|this._D0_[e.charCodeAt(0|a)])>>>0,t[0|r]=255&this.u32aT0,r+1|0;case 2:return this.u32aT0=(this._D0_[e.charCodeAt(0|a)]|this._D1_[e.charCodeAt(a+1|0)]|0)>>>0,t[0|r]=255&this.u32aT0,r+1|0;default:return this.u32aT0=(this._D0_[e.charCodeAt(0|a)]|this._D1_[e.charCodeAt(a+1|0)]|this._D2_[e.charCodeAt(a+2|0)]|0)>>>0,t[0|r]=255&this.u32aT0,t[r+1|0]=this.u32aT0>>8&255,r+2|0}}_base64_store_u8ax3(t,e){t[e=(0|e)>>>0]=this.u8aTa,t[e+1|0]=this.u8aTb,t[e+2|0]=this.u8aTc}get_max_round_str(t){return 0|Math.ceil(t/this.CHNK_L_STR)}base64_encode(t,e){var a=0|t.length,r=(e|=0)*this.CHNK_L_STR|0,s=0,i=Math.min(r+this.CHNK_L_STR|0,0|a)-2|0;if(0<(0|i))for(;(0|r)<(0|i);r=(r+3|0)>>>0,s=s+4|0)this._base64_encode_u8ax4(t,s,r);return o.encodeChars_(this._base64_encode_final(t,r,a,s))}bytesToBase64(t){for(var e="",a=0,r=this.get_max_round_str(t.length);(0|a)<(0|r);a=(a+1|0)>>>0)e+=this.base64_encode(t,0|a);return e}base64ToBytes(t){var e,a,r=0|t.length,s=0,i=0,n=0;if(0==(0|r))return new Uint8Array(0);for(t.charCodeAt(r-1|0)===this.PAD_C&&(n=n+1|0,t.charCodeAt((r=r-1|0)-1|0)===this.PAD_C)&&(r=r-1|0,n=n+1|0),e=new Uint8Array(t.length/4*3-n),a=0==(0|(n=3&r))?(r>>>2)-1|0:r>>>2;(0|s)<(0|a);s=(s+1|0)>>>0)this._base64_decode_u32ax1(t,s<<2),this._base64_store_u8ax3(e,i),i=i+3|0;return this._base64_decode_final(e,t,s<<=2,i,n),e}}return o.charCode_=function(t){return 255&t.charCodeAt(0)},o.charCodeAt_=function(t,e){return 255&t.charCodeAt(0|e)},o.encodeChars_=function(t){return 0<(0|t.length)?String.fromCharCode.apply(null,t):""},o})();t.exports={B64chromium:r}},function(t,e,a){a.r(e),e=a(0),"undefined"!=typeof window?(window.Database=e.Database,window.Document=e.Document,window.Collection=e.Collection):(self.Database=e.Database,self.Document=e.Document,self.Collection=e.Collection)}]);
@@ -0,0 +1 @@
1
+ (t=>{var e={};function a(r){var s;return(e[r]||(s=e[r]={i:r,l:!1,exports:{}},t[r].call(s.exports,s,s.exports,a),s.l=!0,s)).exports}a.m=t,a.c=e,a.d=function(t,e,r){a.o(t,e)||Object.defineProperty(t,e,{enumerable:!0,get:r})},a.r=function(t){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(t,"__esModule",{value:!0})},a.t=function(t,e){if(1&e&&(t=a(t)),8&e)return t;if(4&e&&"object"==typeof t&&t&&t.__esModule)return t;var r=Object.create(null);if(a.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:t}),2&e&&"string"!=typeof t)for(var s in t)a.d(r,s,function(e){return t[e]}.bind(null,s));return r},a.n=function(t){var e=t&&t.__esModule?function(){return t.default}:function(){return t};return a.d(e,"a",e),e},a.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},a.p="",a(a.s=0)})([function(t,e,a){a.r(e);var r=a(1);class s{constructor(t){this.arrayType=t,this.bitMask=this.calculateBitMask()}calculateBitMask(){var t={Uint8Array:255,Uint16Array:65535,Uint32Array:4294967295};if(this.arrayType.name in t)return t[this.arrayType.name];throw new Error("Unsupported array type: "+this.arrayType.name)}performDeltaEncoding(t){this.validateInputType(t,"performDeltaEncoding");var e,a=new this.arrayType(t.length),r=0|t.length,s=0;for(a[0]=0|t[0],s=1;(0|s)<(0|r);s=s+1|0)e=t[s]-t[s-1]&this.bitMask,a[s]=0|e;return a}performDeltaDecoding(t){this.validateInputType(t,"performDeltaDecoding");var e,a=new this.arrayType(t.length),r=0|t.length,s=0;for(a[0]=0|t[0],s=1;(0|s)<(0|r);s=s+1|0)e=a[s-1]+t[s]&this.bitMask,a[s]=0|e;return a}validateInputType(t,e){if(!(t instanceof this.arrayType))throw new Error(`Input data type does not match for method ${e}. Expected: `+this.arrayType.name)}}class i{constructor(t){this.bitArray=new Uint8Array(t+7>>3)}setBit(t,e){var a=1<<(t|=0)%8;this.bitArray[t=t/8|0]=(e|=0)?this.bitArray[t]|a:this.bitArray[t]&~a}getBit(t){return this.bitArray[(t|=0)/8|0]&1<<t%8?1:0}}var n=new class{constructor(){this.deltaEncoder8Bit=new s(Uint8Array),this.deltaEncoder16Bit=new s(Uint16Array),this.deltaEncoder32Bit=new s(Uint32Array)}getDeltaEncoder(t){switch(t){case"Uint8Array":case"Int8Array":case"Uint8ClampedArray":return this.deltaEncoder8Bit;case"Uint16Array":case"Int16Array":return this.deltaEncoder16Bit;case"Uint32Array":case"Int32Array":case"Float32Array":case"Float64Array":return this.deltaEncoder32Bit;default:throw new Error("Unknown TypedArray type.")}}compress(t){var e=t.constructor,a=e.name,r=t.length,s=this.getDeltaEncoder(a).performDeltaEncoding(new e(t.buffer)),n=new i(t.length),o=[];let c=s[0];o.push(c);for(let t=1;t<s.length;t++)s[t]===c?n.setBit(t,!0):(o.push(s[t]),c=s[t]);return this.packData(o,n,r,e.BYTES_PER_ELEMENT)}packData(t,e,a,r){r=t.length*r;var s=(e=e.bitArray).length;return(s=new Uint8Array(9+r+s))[0]=this.getDataTypeId(t),s.set(this.convertLengthToBytes(r),1),s.set(this.convertLengthToBytes(a),5),s.set(t,9),s.set(e,9+r),s}convertLengthToBytes(t){return Uint8Array.of(t>>0&255,t>>8&255,t>>16&255,t>>24&255)}getDataTypeId(t){return{Uint8Array:1,Int8Array:2,Uint8ClampedArray:3,Uint16Array:4,Int16Array:5,Uint32Array:6,Int32Array:7,Float32Array:8,Float64Array:9}[t.constructor.name]||0}decompress(t){var e=t[0],a=this.extractLengthFromBytes(t,1),r=this.extractLengthFromBytes(t,5),s=new Uint8Array(t.subarray(9,9+a)),n=(t=new Uint8Array(t.subarray(9+a)),new(a=this.getArrayConstructorByTypeId(e))(s.buffer)),o=new i(8*t.length),c=(o.bitArray=t,new a(r));let h=0;for(let t=0;(0|t)<(0|r);t=t+1|0)o.getBit(t)?c[t]=c[t-1|0]:c[t]=n[h++];return this.getDeltaEncoder(a.name).performDeltaDecoding(c)}extractLengthFromBytes(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16|t[e+3]<<24}getArrayConstructorByTypeId(t){return{1:Uint8Array,2:Int8Array,3:Uint8ClampedArray,4:Uint16Array,5:Int16Array,6:Uint32Array,7:Int32Array,8:Float32Array,9:Float64Array}[t]||Uint8Array}},o=class{constructor(t){this._buffers=new WeakMap,this._store={},this._nextId=0,this._compress=t?n.compress.bind(n):function(t){return t},this._decompress=t?n.decompress.bind(n):function(t){return t}}_generateId(){var t=this._nextId;return this._nextId++,t}clear(){this._buffers=new WeakMap,this._store={},this._nextId=0}insert(t,e){if(void 0===e){if(this._buffers.has(t))return this._buffers.get(t);e=this._generateId()}else if(this._store.hasOwnProperty(e))throw new Error(`ID ${e} is already in use.`);return e=parseInt(e),this._buffers.set(t,e),this._store[e]=t,e}retrieve(t){return this._store[parseInt(t)]}retrieveAll(){var t={},e=Object.entries(this._store);for(let s=0;s<e.length;s++){var[a,r]=e[s],r=this._compress(new Uint8Array(r)).buffer;t[parseInt(a)]=r}return t}insertAll(t){var e=Object.entries(t);for(let t=0;t<e.length;t++){var[a,r]=e[t],r=this._decompress(new Uint8Array(r)).buffer;this.insert(r,parseInt(a))}}},c=new class{constructor(){this._packBufferTemp8=new Uint8Array(15e3),this._headerByteLength=0,this._offset=0,this._b64=new r.B64chromium,this._b64Base64ToBytes=this._b64.base64ToBytes.bind(this._b64),this._b64BytesToBase64=this._b64.bytesToBase64.bind(this._b64),this._textDecoder=new TextDecoder,this._textDecoderFunction=this._textDecoder.decode.bind(this._textDecoder),this._textEncoder=new TextEncoder,this._textEncoderFunction=this._textEncoder.encode.bind(this._textEncoder),this._textEncoderIntoFunction=this._textEncoder.encodeInto.bind(this._textEncoder),this.encodeOtherBound=this.encodeOther.bind(this),this.decodeOtherBound=this.decodeOther.bind(this),this.stringifyBound=this._innerStringify.bind(this),this.parseBound=this._innerParse.bind(this),this.use_compressor=!1,this._setEngine()}_setEngine(){this.engine=new class{constructor(t,e,a,r,s,i,n,c,h){this._hasher=new class{constructor(t){this._chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",this._charLookup={};for(let t=0;t<this._chars.length;t++)this._charLookup[this._chars[t]]=t;this._bitPerChar=6,this._accumulatorBitNumber=32,this._outputLength=Math.max(1,Math.min(0|t,this._accumulatorBitNumber/this._bitPerChar|0)),this._primes=Uint32Array.of(2654435761,2246822519,3266489917,668265263),this._values=new Uint32Array(this._primes.length+2),this.imul=Math.imul,this.rotl=function(t,e){return(t>>>=0)<<(e&=31)|t>>>32-e}}get outputLength(){return this._outputLength}get chars(){return this._chars}get finalValue(){return this._values[4]}set finalValue(t){return this._values[4]=(0|t)>>>0}get primes(){return this._primes}get values(){return this._values}get accumulator(){return this._values}get charLookup(){return this._charLookup}getCharValue(t){return 63&this.charLookup[t]}aggregateCharValue(t,e,a,r){return t<<18|e<<12|a<<6|r}getCharByOffset(t){return this.chars[63&t]}hash(t){this.values.fill(0);for(var e=0,a=0,r=t.length,s=r>>2>>2;e<s;a=++e<<4)this.accumulator[0]=this.accumulator[0]+this.imul(this.aggregateCharValue(this.getCharValue(t[a]),this.getCharValue(t[a+1|0]),this.getCharValue(t[a+2|0]),this.getCharValue(t[a+3|0])),this.primes[0]),this.accumulator[1]=this.accumulator[1]+this.imul(this.aggregateCharValue(this.getCharValue(t[a+4|0]),this.getCharValue(t[a+5|0]),this.getCharValue(t[a+6|0]),this.getCharValue(t[a+7|0])),this.primes[1]),this.accumulator[2]=this.accumulator[2]+this.imul(this.aggregateCharValue(this.getCharValue(t[a+8|0]),this.getCharValue(t[a+9|0]),this.getCharValue(t[a+10|0]),this.getCharValue(t[a+11|0])),this.primes[2]),this.accumulator[3]=this.accumulator[3]+this.imul(this.aggregateCharValue(this.getCharValue(t[a+12|0]),this.getCharValue(t[a+13|0]),this.getCharValue(t[a+14|0]),this.getCharValue(t[a+15|0])),this.primes[3]);for(e<<=2;(0|e)<(0|r);a=(e=(e+1|0)>>>0)<<2)this.accumulator[3&e]=this.accumulator[3&e]+this.imul(this.aggregateCharValue(this.getCharValue(t[a])||0,this.getCharValue(t[a+1|0])||0,this.getCharValue(t[a+2|0])||0,this.getCharValue(t[a+3|0]))||0,this.primes[3&e]);this.finalValue=this.rotl(this.accumulator[0],1)+this.rotl(this.accumulator[1],7)+this.rotl(this.accumulator[2],12)+this.rotl(this.accumulator[3],18)>>>0;for(var i,n=0,o=new Array(this.outputLength);n<this.outputLength;n++)i=63&this.finalValue,o[n]=this.getCharByOffset(i),this.finalValue=(this.finalValue-i)/64>>>0;return o.join("")}}(1),this.hashThis=r||this._hasher.hash.bind(this._hasher),this.base=t||"data:joyson/",this.shortBase=e||"d:j/",this.baseLength=this.base.length,this.shortBaseLength=this.shortBase.length,this.encapsulate=a||function(t){return JSON.stringify(t)},this.encodeObjectOut=s||function(t){return t},this.decodeObjectOut=i||function(t){return t},this.stringifyOut=n||JSON.stringify,this.parseOut=c||JSON.parse,this._initializeErrorConstructors(),this.arrayBufferIDManager=new o(h),this._initializeBufferConstructors(),this._initializeDynamicTypes(["object","number","bigint","map","set","date","string","error","regexp","buffer","boolean","static"])}_initializeDynamicTypes(t){this.dynamicValues={},this.dynamicValuesIdKey={};for(var e=0;e<t.length;e++){var a=t[e];this.dynamicValues[a]={},this.dynamicValues[a].name=a,this.dynamicValues[a].str=this.base+this.dynamicValues[a].name+";",this.dynamicValues[a].id=this.hashThis(this.dynamicValues[a].name),this.dynamicValues[a].shortStr=this.shortBase+this.dynamicValues[a].id+";",this.dynamicValues[a].strCode=new Uint8Array(this.dynamicValues[a].str.split("").map((function(t){return t.charCodeAt(0)}))),this.dynamicValues[a].shortStrCode=new Uint8Array(this.dynamicValues[a].shortStr.split("").map((function(t){return t.charCodeAt(0)}))),this.dynamicValues[a].strLen=this.dynamicValues[a].str.length,this.dynamicValues[a].shortStrLen=this.dynamicValues[a].shortStr.length,this.dynamicValuesIdKey[this.dynamicValues[a].id]=this.dynamicValues[a].name}}_initializeErrorConstructors(){this.errorConstructors={Error:Error,TypeError:TypeError,SyntaxError:SyntaxError,ReferenceError:ReferenceError,RangeError:RangeError,EvalError:EvalError,URIError:URIError,DOMException:DOMException}}_initializeBufferConstructors(){this.bufferConstructors={ArrayBuffer:ArrayBuffer,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int8Array:Int8Array,Uint16Array:Uint16Array,Int16Array:Int16Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Float32Array:Float32Array,Float64Array:Float64Array}}clear(){this.arrayBufferIDManager.clear()}getAllArrayBuffer(){var t=this.arrayBufferIDManager.retrieveAll();return this.clear(),t}setAllArrayBuffer(t){this.clear(),this.arrayBufferIDManager.insertAll(t)}_isNotNumber(t){return isNaN(t)}_isNotFiniteNumber(t){return!isFinite(t)}_isNotObject(t){return null===t}_isNotString(t){return t.includes("\0")}_isError(t){return void 0!==t.name&&t.name in this.errorConstructors}_isBuffer(t){return(t instanceof ArrayBuffer||"object"==typeof t.buffer)&&(t.constructor||{}).name in this.bufferConstructors}_mustDecodeOfType(t){if("string"==typeof t){if(t.startsWith(this.shortBase))return 2;if(t.startsWith(this.base))return 1}return 0}_dataTypeNameFromKey(t){return this.dynamicValuesIdKey[t]}_decode(t,e){var a=t.slice(e?this.shortBaseLength:this.baseLength).split(";"),r=a[0],s=a[1];switch(e?this._dataTypeNameFromKey(r):r){case"static":return this.decodeStatic(s);case"number":return this.decodeSpecialNumber(s);case"bigint":return this.decodeBigNumber(s);case"string":return this.decodeSpecialString(s);case"boolean":return this.decodeBoolean(s);case"map":return this.decodeMap(s);case"set":return this.decodeSet(s);case"date":return this.decodeDate(s);case"regexp":return this.decodeRegexp(s);case"error":return this.decodeError(s);case"buffer":return this.decodeBuffer(s);case"object":return this.decodeSpecialObject(s);default:return this.decodeObjectOut(t,e)}}decode(t,e){switch(this._mustDecodeOfType(t)){case 0:return"object"==typeof t?this.decodeObjectOut(t,e):t;case 1:return this._decode(t,!1);case 2:return this._decode(t,!0)}}decodeStatic(t){switch(t){case"nan":return NaN;case"null":return null;case"undefined":return}}decodeSpecialNumber(t){switch(t){case"nan":return NaN;case"infinity":return 1/0;case"-infinity":return-1/0;case"epsilon":return Number.EPSILON;case"-epsilon":return-Number.EPSILON;case"-0":return parseInt("-0");default:return Number(t)}}decodeBigNumber(t){return BigInt(t)}decodeSpecialString(t){return atob(t)}decodeBoolean(t){return"true"===t}decodeMap(t){return t=atob(t),t=this.parseOut(t),new Map(t)}decodeSet(t){return t=atob(t),t=this.parseOut(t),new Set(t)}decodeDate(t){return new Date(t)||new Date(NaN)}decodeRegexp(t){t=t.split(":");var e=atob(t[0]);t=atob(t[1]);return new RegExp(e,t)}decodeError(t){t=t.split(":");var e=atob(t[0]);t=atob(t[1]);return new this.errorConstructors[e](t)}decodeBuffer(t){var e="ArrayBuffer"===(a=(t=t.split(":"))[0]),a=this.bufferConstructors[a],r=parseInt(t[1],16),s=parseInt(t[2],16);t=parseInt(t[3],16),t=this.arrayBufferIDManager.retrieve(t);return e?t:new a(t,r,s)}decodeSpecialObject(t){return t=atob(t),t=this.parseOut(t),Object(t)}_encodeFinal(t,e,a){return a?this.dynamicValues[t].shortStr+e:this.encapsulate(this.dynamicValues[t].str+e)}encode(t,e){switch(typeof t){case"undefined":return this.encodeStatic(t,e);case"number":return this._isNotNumber(t)?this.encodeStatic(t,e):this.encodeNumber(t,e);case"bigint":return this.encodeBigNumber(t,e);case"string":return this._isNotString(t)?this.encodeSpecialString(t,e):this.encodeString(t,e);case"boolean":return this.encodeBoolean(t,e);case"object":return this._isNotObject(t)?this.encodeStatic(t,e):"function"==typeof t.get?this.encodeMap(t,e):"function"==typeof t.delete?this.encodeSet(t,e):"function"==typeof t.toISOString?this.encodeDate(t,e):"function"==typeof t.exec?this.encodeRegexp(t,e):t!==t.valueOf()?this.encodeSpecialObject(t,e):this._isError(t)?this.encodeError(t,e):this._isBuffer(t)?this.encodeBuffer(t,e):this.encodeObject(t,e)}}encodeStatic(t,e){var a;switch(typeof t){case"number":a="nan";break;case"object":a="null";break;case"undefined":a="undefined"}return this._encodeFinal("static",a,e)}encodeNumber(t,e){var a;switch(t){case NaN:a="nan";break;case 1/0:a="infinity";break;case-1/0:a="-infinity";break;case Number.EPSILON:a="epsilon";break;case-Number.EPSILON:a="-epsilon";break;default:if("-0"===Number(t).toLocaleString())a="-0";else{if(!this._isNotFiniteNumber(t))return e?t:""+t;a=t}}return this._encodeFinal("number",a,e)}encodeBigNumber(t,e){return t=t.toString(),this._encodeFinal("bigint",t,e)}encodeSpecialString(t,e){return t=btoa(t),this._encodeFinal("string",t,e)}encodeString(t,e){return e?""+t:this.encapsulate(t)}encodeBoolean(t,e){return this._encodeFinal("boolean",t?"true":"false",e)}encodeMap(t,e){return t=Object.entries(Object.fromEntries(t)),t=this.stringifyOut(t),t=btoa(t),this._encodeFinal("map",t,e)}encodeSet(t,e){return t=Array.from(t),t=this.stringifyOut(t),t=btoa(t),this._encodeFinal("set",t,e)}encodeDate(t,e){return t=t.toISOString(),this._encodeFinal("date",t,e)}encodeRegexp(t,e){return t=[btoa(t.source),btoa(t.flags)],this._encodeFinal("regexp",t.join(":"),e)}encodeSpecialObject(t,e){return t=this.stringifyOut(t.valueOf()),t=btoa(t),this._encodeFinal("object",t,e)}encodeError(t,e){return t=[btoa(t.name),btoa(t.message)],this._encodeFinal("error",t.join(":"),e)}encodeBuffer(t,e){var a=(i=void 0===t.buffer)?"ArrayBuffer":t.constructor.name,r=t.byteOffset,s=i?t.byteLength:t.length,i=i?t:t.buffer;t=this.arrayBufferIDManager.insert(i),i=[a,parseInt(r).toString(16),parseInt(s).toString(16),parseInt(t).toString(16)];return this._encodeFinal("buffer",i.join(":"),e)}encodeObject(t,e){return this.encodeObjectOut(t,e)}}(void 0,void 0,void 0,void 0,this.encodeOtherBound,this.decodeOtherBound,this.stringifyBound,this.parseBound,this.use_compressor)}get compress(){return this.use_compressor}set compress(t){this.use_compressor=Boolean(t),this._setEngine()}_getComparator(){return function(t){return function(e){return function(a,r){return a={key:a,value:e[a]},t(a,{key:r,value:e[r]})}}}}_stringifyObject(t){if(Array.isArray(t)){for(var e=0,a=t.length,r=((s=Object.keys(t)).length,new Array(a));(0|e)<(0|a);e=(e+1|0)>>>0)r[e]=this.engine.encode(t[e],!1);return"["+r.join(",")+"]"}for(var s,i,n=this._getComparator(),o="",c=(e=0,a=0|(s=Object.keys(t).sort(n&&n(t))).length,"");(0|e)<(0|a);e=(e+1|0)>>>0)if(o=s[e]+"",i=this.engine.encode(t[o],!1))switch(0<(0|c.length)&&(c+=","),0|(0===o.length||o.includes("\0")||o.startsWith("$"))){case 0:c+=this.engine.encode(o,!1)+":"+i;break;case 1:c+='"$'+btoa("$"+o)+'":'+i}return"{"+c+"}"}encodeOther(t,e){return e?this._packObject(t):this._stringifyObject(t)}decodeOther(t,e){return e?this._unpackObject(t):this._parseObject(t)}_stringify(t,e){var a={};if(a.header=this.engine.encode(t,!1),!e){var r,s=this.engine.getAllArrayBuffer();for(r in a.buffers={},s)a.buffers[r]=this._b64BytesToBase64(new Uint8Array(s[r]))}return JSON.stringify(a)}stringify(t){return this._stringify(t,!1)}_innerStringify(t){return this._stringify(t,!0)}_parseObject(t){if(Array.isArray(t)){for(var e=[],a=0,r=t.length;(0|a)<(0|r);a=(a+1|0)>>>0)e.push(this.engine.decode(t[a]));return e}var s,i,n={},o=Object.keys(t),c="";for(a=0,r=0|o.length;(0|a)<(0|r);a=(a+1|0)>>>0)switch(c=o[a],s=this._keyMustDecode(c),i=this.engine.decode(t[c]),0|s){case 0:n[c]=i;break;case 1:n[atob(c.slice(1)).slice(1)]=i}return n}_parse(t,e){var a,r;t=JSON.parse(t);return e||(a=this._b64Base64ToBytes,r={},Object.entries(t.buffers).forEach((function(t){var e=t[0];r[e]=a(t[1]).buffer})),this.engine.setAllArrayBuffer(r)),this.engine.decode(JSON.parse(t.header))}parse(t){return this._parse(t,!1)}_innerParse(t){return this._parse(t,!0)}_packObject(t){if(Array.isArray(t)){for(var e=[],a=0,r=t.length;(0|a)<(0|r);a=(a+1|0)>>>0)e.push(this.engine.encode(t[a],!0));return e}var s,i={},n=Object.keys(t),o="";for(a=0,r=0|n.length;(0|a)<(0|r);a=(a+1|0)>>>0)if(o=n[a]+"",s=this.engine.encode(t[o],!0))switch(0|(""===o||o.includes("\0")||o.startsWith("$"))){case 0:i[this.engine.encode(o,!0)]=s;break;case 1:i["$"+btoa("$"+o)]=s}return i}pack(t){t=JSON.stringify(this.engine.encode(t,!0));var e=this.engine.getAllArrayBuffer(),a=0,r=Object.keys(e).length;for(n in e)a+=e[n].byteLength;var s=2*t.length+5,i=s+a+4;if((i=(this._packBufferTemp8.length<i&&(this._packBufferTemp8=new Uint8Array(i)),this._textEncoderIntoFunction(t,this._packBufferTemp8.subarray(4,4+s)))).written>s)throw new Error("Header in json is too fat!");t=i.written;var n,o=(this._packBufferTemp8[0]=t>>0&255,this._packBufferTemp8[1]=t>>8&255,this._packBufferTemp8[2]=t>>16&255,this._packBufferTemp8[3]=t>>24&255,t);a=4;for(n in this._packBufferTemp8[o+a]=r>>0&255,this._packBufferTemp8[o+a+1]=r>>8&255,this._packBufferTemp8[o+a+2]=r>>16&255,this._packBufferTemp8[o+a+3]=r>>24&255,a+=4,e){var c=e[n],h=c.byteLength;this._packBufferTemp8[o+a]=h>>0&255,this._packBufferTemp8[o+a+1]=h>>8&255,this._packBufferTemp8[o+a+2]=h>>16&255,this._packBufferTemp8[o+a+3]=h>>24&255,a+=4,this._packBufferTemp8.set(new Uint8Array(c),o+a),a+=h}return this._packBufferTemp8.slice(0,o+a)}_keyMustDecode(t){return t.startsWith("$")}_unpackObject(t){if(Array.isArray(t)){for(var e=[],a=0,r=t.length;(0|a)<(0|r);a=(a+1|0)>>>0)e.push(this.engine.decode(t[a],!0));return e}var s,i,n={},o=Object.keys(t),c="";for(a=0,r=0|o.length;(0|a)<(0|r);a=(a+1|0)>>>0)switch(c=o[a],s=this._keyMustDecode(c),i=this.engine.decode(t[c],!0),0|s){case 0:n[c]=i;break;case 1:n[atob(c.slice(1)).slice(1)]=i}return n}unpack(t){for(var e=4+(t[0]<<0|t[1]<<8|t[2]<<16|t[3]<<24),a=4+e,r=JSON.parse(this._textDecoderFunction(t.subarray(4,e))),s=t[e]<<0|t[1+e]<<8|t[2+e]<<16|t[3+e]<<24,i={},n=a,o=0;o<s;o++){var c=t[n]<<0|t[n+1]<<8|t[n+2]<<16|t[n+3]<<24;n+=4,i[o]=t.buffer.slice(n,n+c),n+=c}return this.engine.setAllArrayBuffer(i),this.engine.decode(r,!0)}};a.d(e,"Database",(function(){return D})),a.d(e,"Document",(function(){return B})),a.d(e,"Collection",(function(){return T}));class h{static async saveAttachments(t,e,a,r){var s,i=[];let n=await navigator.storage.getDirectory();for(s of[t,e,a])n=await n.getDirectoryHandle(s,{create:!0});for(let s=0;s<r.length;s++){var o=s.toString(),c=await(await n.getFileHandle(o,{create:!0})).createWritable();c=(await c.write(r[s].data),await c.close(),t+`/${e}/${a}/`+o);i.push(c)}return i}static async getAttachments(t){var e,a=[],r=await navigator.storage.getDirectory();for(e of t)try{var s=e.split("/");let t=r;for(let e=0;e<s.length-1;e++)t=await t.getDirectoryHandle(s[e]);var i=await(await t.getFileHandle(s[s.length-1])).getFile();a.push({path:e,data:i})}catch(t){console.error(`Error retrieving attachment at "${e}": `+t.message)}return a}static async deleteAttachments(t,e,a){var r=[t,e,a];let s=await navigator.storage.getDirectory();for(let t=0;t<r.length-1;t++)s=await s.getDirectoryHandle(r[t]);try{await s.removeEntry(r[r.length-1],{recursive:!0})}catch(t){console.error(`Error deleting attachments for document "${a}": `+t.message)}}toString(){return"[OPFSUtility]"}}class d{static async compress(t){t="string"==typeof t?(new TextEncoder).encode(t):t;var e=new CompressionStream("deflate"),a=e.writable.getWriter();return a.write(t),a.close(),this._streamToUint8Array(e.readable)}static async decompress(t){var e=new DecompressionStream("deflate"),a=e.writable.getWriter();return a.write(t),a.close(),this._streamToUint8Array(e.readable)}static async _streamToUint8Array(t){var e=t.getReader(),a=[];let r=0;for(;;){var{value:s,done:i}=await e.read();if(i)break;a.push(s),r+=s.length}var n,o=new Uint8Array(r);let c=0;for(n of a)o.set(n,c),c+=n.length;return o}toString(){return"[BrowserCompressionUtility]"}}class u{static async encrypt(t,e){var a=crypto.getRandomValues(new Uint8Array(16)),r=(e=await this._deriveKey(e,a),crypto.getRandomValues(new Uint8Array(12))),s=await this._generateChecksum(t);t=this._combineDataAndChecksum(t,s),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},e,t);return this._wrapIntoUint8Array(a,r,new Uint8Array(s))}static async decrypt(t,e){var{salt:t,iv:a,encryptedData:r}=this._unwrapUint8Array(t),a=(e=await this._deriveKey(e,t),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},e,r),new Uint8Array(t)),{data:e,checksum:r}=this._separateDataAndChecksum(a);t=await this._generateChecksum(e);if(this._verifyChecksum(t,r))return e;throw new Error("Data integrity check failed. The data has been tampered with.")}static async _deriveKey(t,e){var a=new TextEncoder;a=await crypto.subtle.importKey("raw",a.encode(t),{name:"PBKDF2"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:6e5,hash:"SHA-512"},a,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}static async _generateChecksum(t){return new Uint8Array(await crypto.subtle.digest("SHA-256",t))}static _verifyChecksum(t,e){if(t.length!==e.length)return!1;for(let a=0;a<t.length;a++)if(t[a]!==e[a])return!1;return!0}static _combineDataAndChecksum(t,e){var a=new Uint8Array(t.length+e.length);return a.set(t),a.set(e,t.length),a}static _separateDataAndChecksum(t){var e=t.length-32;return{data:t.slice(0,e),checksum:t.slice(e)}}static _wrapIntoUint8Array(t,e,a){var r=new Uint8Array(t.length+e.length+a.length);return r.set(t,0),r.set(e,t.length),r.set(a,t.length+e.length),r}static _unwrapUint8Array(t){return{salt:t.slice(0,16),iv:t.slice(16,28),encryptedData:t.slice(28)}}toString(){return"[BrowserEncryptionUtility]"}}class l{static openDatabase(t,e=null,a=null){return new Promise((r,s)=>{let i;(i=e?indexedDB.open(t,e):indexedDB.open(t)).onupgradeneeded=e=>{var r=e.target.result,s=e.oldVersion;e=e.newVersion;console.log(`Upgrading database "${t}" from version ${s} to `+e),a&&a(r,s,e)},i.onsuccess=e=>{(e=e.target.result).onclose=()=>{console.log(`Database "${t}" connection is closing.`)},r(e)},i.onerror=e=>{s(new Error(`Failed to open database "${t}": `+e.target.error.message))}})}static async performTransaction(t,e,a,r,s=3,i=null){let n=null;for(let h=0;h<=s;h++)try{if(!t)throw new Error("Database connection is not available.");let s=t.transaction(Array.isArray(e)?e:[e],a);var o=Array.isArray(e)?e.map(t=>s.objectStore(t)):[s.objectStore(e)],c=i||Date.now()+"_"+Math.random();let h=await r(...o,c);return new Promise((t,e)=>{s.oncomplete=()=>t(h),s.onerror=()=>{n=new Error("Transaction failed: "+(s.error?s.error.message:"unknown error")),e(n)},s.onabort=()=>{n=new Error("Transaction aborted: "+(s.error?s.error.message:"unknown reason")),e(n)}})}catch(t){n=t,h<s&&(console.warn(`Transaction failed, retrying... (${s-h} attempts left): `+t.message),await new Promise(t=>setTimeout(t,100*Math.pow(2,h))))}throw new Error(`Transaction ultimately failed after ${s+1} attempts: `+n.message)}static add(t,e){return new Promise((a,r)=>{var s=t.add(e);s.onsuccess=()=>a(),s.onerror=t=>r("Failed to insert record: "+t.target.error.message)})}static put(t,e){return new Promise((a,r)=>{var s=t.put(e);s.onsuccess=()=>a(),s.onerror=t=>r("Failed to put record: "+t.target.error.message)})}static delete(t,e){return new Promise((a,r)=>{var s=t.delete(e);s.onsuccess=()=>a(),s.onerror=t=>r("Failed to delete record: "+t.target.error.message)})}static get(t,e){return new Promise((a,r)=>{var s=t.get(e);s.onsuccess=t=>a(t.target.result),s.onerror=t=>r(`Failed to retrieve record with key ${e}: `+t.target.error.message)})}static getAll(t){return new Promise((e,a)=>{var r=t.getAll();r.onsuccess=t=>e(t.target.result),r.onerror=t=>a("Failed to retrieve records: "+t.target.error.message)})}static count(t){return new Promise((e,a)=>{var r=t.count();r.onsuccess=t=>e(t.target.result),r.onerror=t=>a("Failed to count records: "+t.target.error.message)})}static clear(t){return new Promise((e,a)=>{var r=t.clear();r.onsuccess=()=>e(),r.onerror=t=>a("Failed to clear store: "+t.target.error.message)})}static deleteDatabase(t){return new Promise((e,a)=>{var r=indexedDB.deleteDatabase(t);r.onsuccess=()=>e(),r.onerror=t=>a("Failed to delete database: "+t.target.error.message)})}static iterateCursor(t,e){return new Promise((a,r)=>{var s=t.openCursor();s.onsuccess=t=>{(t=t.target.result)?(e(t.value,t.key),t.continue()):a()},s.onerror=t=>r("Cursor iteration failed: "+t.target.error.message)})}toString(){return"[IndexedDBUtility]"}}class m{static getItem(t){return(t=localStorage.getItem(t))?c.parse(t):null}static setItem(t,e){localStorage.setItem(t,c.stringify(e))}static removeItem(t){localStorage.removeItem(t)}static clear(){localStorage.clear()}toString(){return"[LocalStorageUtility]"}}class _{constructor(){this.queue=[],this.locked=!1}async acquire(){return new Promise(t=>{this.locked?this.queue.push(t):(this.locked=!0,t())})}release(){0<this.queue.length?this.queue.shift()():this.locked=!1}async runExclusive(t){await this.acquire();try{return await t()}finally{this.release()}}toString(){return`[AsyncMutex locked:${this.locked} queue:${this.queue.length}]`}}class g{constructor(t){this._dbName=t,this._metadataKey=`lacertadb_${this._dbName}_metadata`,this._collections=new Map,this._metadata=this._loadMetadata(),this._mutex=new _}async saveMetadata(){return this._mutex.runExclusive(()=>{m.setItem(this.metadataKey,this.getRawMetadata())})}async adjustTotals(t,e){return this._mutex.runExclusive(()=>{this.data.totalSizeKB+=t,this.data.totalLength+=e,this.data.modifiedAt=Date.now()})}_loadMetadata(){var t=m.getItem(this.metadataKey);if(t){for(var e in t.collections){var a=t.collections[e];a=new b(e,this,a);this.collections.set(e,a)}return t}return{name:this._dbName,collections:{},totalSizeKB:0,totalLength:0,modifiedAt:Date.now()}}get data(){return this._metadata}set data(t){this._metadata=t}get name(){return this.data.name}get metadataKey(){return this._metadataKey}get collections(){return this._collections}set collections(t){this._collections=t}get totalSizeKB(){return this.data.totalSizeKB}get totalLength(){return this.data.totalLength}get modifiedAt(){return this.data.modifiedAt}getCollectionMetadata(t){var e;return this.collections.has(t)||(e=new b(t,this),this.collections.set(t,e),this.data.collections[t]=e.getRawMetadata(),this.data.modifiedAt=Date.now()),this.collections.get(t)}getCollectionMetadataData(t){return(t=this.getCollectionMetadata(t))?t.getRawMetadata():{}}removeCollectionMetadata(t){var e=this.collections.get(t);e&&(this.data.totalSizeKB-=e.sizeKB,this.data.totalLength-=e.length,this.collections.delete(t),delete this.data.collections[t],this.data.modifiedAt=Date.now())}getCollectionNames(){return Array.from(this.collections.keys())}getRawMetadata(){for(var[t,e]of this._collections.entries())this.data.collections[t]=e.getRawMetadata();return this.data}setRawMetadata(t){for(var e in this._metadata=t,this._collections.clear(),t.collections){var a=t.collections[e];a=new b(e,this,a);this._collections.set(e,a)}}get dbName(){return this._dbName}get key(){return this._metadataKey}toString(){return`[DatabaseMetadata: ${this.name} | Collections: ${this.collections.size} | Size: ${this.totalSizeKB.toFixed(2)}KB | Documents: ${this.totalLength}]`}}class f extends Error{constructor(t,e,a=null){super(t),this.name="LacertaDBError",this.code=e,this.originalError=a,this.timestamp=Date.now()}toString(){return`[LacertaDBError ${this.code}: ${this.message} at ${new Date(this.timestamp).toISOString()}]`}}let y="COLLECTION_NOT_FOUND",p="COLLECTION_EXISTS";class b{constructor(t,e,a=null){this._collectionName=t,this._databaseMetadata=e,a?this._metadata=a:(this._metadata={name:t,sizeKB:0,length:0,createdAt:Date.now(),modifiedAt:Date.now(),documentSizes:{},documentModifiedAt:{},documentPermanent:{},documentAttachments:{}},this._databaseMetadata.data.collections[t]=this._metadata,this._databaseMetadata.data.modifiedAt=Date.now())}get name(){return this._collectionName}get keys(){return Object.keys(this.documentSizes)}get collectionName(){return this.name}get sizeKB(){return this._metadata.sizeKB}get length(){return this._metadata.length}get modifiedAt(){return this._metadata.modifiedAt}get metadata(){return this._metadata}set metadata(t){return this._metadata=t}get data(){return this.metadata}set data(t){this.metadata=t}get databaseMetadata(){return this._databaseMetadata}set databaseMetadata(t){this._databaseMetadata=t}get documentSizes(){return this.metadata.documentSizes}get documentModifiedAt(){return this.metadata.documentModifiedAt}get documentPermanent(){return this.metadata.documentPermanent}get documentAttachments(){return this.metadata.documentAttachments}set documentSizes(t){this.metadata.documentSizes=t}set documentModifiedAt(t){this.metadata.documentModifiedAt=t}set documentPermanent(t){this.metadata.documentPermanent=t}set documentAttachments(t){this.metadata.documentAttachments=t}updateDocument(t,e,a=!1,r=0){var s=!this.keys.includes(t),i=e-(this.documentSizes[t]||0);s=s?1:0;this.documentSizes[t]=e,this.documentModifiedAt[t]=Date.now(),this.documentPermanent[t]=a?1:0,this.documentAttachments[t]=r,this.metadata.sizeKB+=i,this.metadata.length+=s,this.metadata.modifiedAt=Date.now(),this.databaseMetadata.adjustTotals(i,s)}deleteDocument(t){var e;return t in this.documentSizes&&(e=this.documentSizes[t],delete this.documentSizes[t],delete this.documentModifiedAt[t],delete this.documentPermanent[t],delete this.documentAttachments[t],this.metadata.sizeKB-=e,--this.metadata.length,this.metadata.modifiedAt=Date.now(),this.databaseMetadata.adjustTotals(-e,-1),!0)}updateDocuments(t){for(var{docId:e,docSizeKB:a,isPermanent:r,attachmentCount:s}of t)this.updateDocument(e,a,r,s||0)}getRawMetadata(){return this.metadata}setRawMetadata(t){this.metadata=t}toString(){return`[CollectionMetadata: ${this.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`}}class w{constructor(t,e=null,a=null){this.success=t,this.data=e,this.error=a}toString(){return`[LacertaDBResult success:${this.success} ${this.error?"error:"+this.error:""}]`}}class A{constructor(t){this._dbName=t,this._metadataKey=`lacertadb_${this._dbName}_quickstore_metadata`,this._documentKeyPrefix=`lacertadb_${this._dbName}_quickstore_data_`,this._metadata=this._loadMetadata()}_loadMetadata(){return m.getItem(this._metadataKey)||{totalSizeKB:0,totalLength:0,documentSizesKB:{},documentModificationTime:{},documentPermanent:{}}}_saveMetadata(){m.setItem(this._metadataKey,this._metadata)}setDocumentSync(t,e=null){e=(t=new B(t,e)).packSync();var a=t._id,r=t._permanent||!1,s=(e=c.stringify({_id:t._id,_created:t._created,_modified:t._modified,_permanent:r,_encrypted:t._encrypted,_compressed:t._compressed,packedData:e}),this._documentKeyPrefix+a);localStorage.setItem(s,e),s=e.length/1024;return(e=!(a in this._metadata.documentSizesKB))?this._metadata.totalLength+=1:this._metadata.totalSizeKB-=this._metadata.documentSizesKB[a],this._metadata.documentSizesKB[a]=s,this._metadata.documentModificationTime[a]=t._modified,this._metadata.documentPermanent[a]=r,this._metadata.totalSizeKB+=s,this._saveMetadata(),e}deleteDocumentSync(t,e=!1){var a;return!(this._metadata.documentPermanent[t]&&!e||(e=this._documentKeyPrefix+t,a=this._metadata.documentSizesKB[t]||0,!localStorage.getItem(e))||(localStorage.removeItem(e),delete this._metadata.documentSizesKB[t],delete this._metadata.documentModificationTime[t],delete this._metadata.documentPermanent[t],this._metadata.totalSizeKB-=a,--this._metadata.totalLength,this._saveMetadata(),0))}getAllKeys(){return Object.keys(this._metadata.documentSizesKB)}getDocumentSync(t,e=null){t=this._documentKeyPrefix+t;return(t=localStorage.getItem(t))?(t=c.parse(t),new B(t,e).unpackSync()):null}toString(){return`[QuickStore: ${this._dbName} | Size: ${this._metadata.totalSizeKB.toFixed(2)}KB | Documents: ${this._metadata.totalLength}]`}}class v{constructor(){this.queue=[],this.processing=!1}async execute(t){return new Promise((e,a)=>{this.queue.push({operation:t,resolve:e,reject:a}),this.process()})}async process(){if(!this.processing&&0!==this.queue.length){for(this.processing=!0;0<this.queue.length;){var{operation:t,resolve:e,reject:a}=this.queue.shift();try{e(await t())}catch(t){a(t)}}this.processing=!1}}toString(){return`[TransactionManager processing:${this.processing} queue:${this.queue.length}]`}}class S{constructor(){this._listeners={beforeAdd:[],afterAdd:[],beforeDelete:[],afterDelete:[],beforeGet:[],afterGet:[]}}on(t,e){if(!this._listeners[t])throw new Error(`Event "${t}" is not supported.`);this._listeners[t].push(e)}off(t,e){this._listeners[t]&&-1<(e=this._listeners[t].indexOf(e))&&this._listeners[t].splice(e,1)}_emit(t,...e){if(this._listeners[t])for(var a of this._listeners[t])a(...e)}_cleanup(){for(var t in this._listeners)this._listeners[t]=[]}toString(){return`[Observer listeners:{${Object.entries(this._listeners).map(([t,e])=>t+":"+e.length).join(" ")}}]`}}class D{constructor(t,e={}){this._dbName=t,this._db=null,this._collections=new Map,this._metadata=new g(t),this._settings=new C(t,e),this._quickStore=new A(this._dbName),this._settings.init()}get quickStore(){return this._quickStore}async init(){var t;for(t of(this.db=await l.openDatabase(this.name,void 0,(t,e,a)=>{this._upgradeDatabase(t,e,a)}),this.data.getCollectionNames())){var e=new T(this,t,this.settings);await e.init(),this.collections.set(t,e)}}_createDataStores(t){for(var e of this.collections.keys())this._createDataStore(t,e)}_createDataStore(t,e){t.objectStoreNames.contains(e)||t.createObjectStore(e,{keyPath:"_id"})}_upgradeDatabase(t,e,a){console.log(`Upgrading database "${this.name}" from version ${e} to `+a),t.objectStoreNames.contains("_metadata")||t.createObjectStore("_metadata",{keyPath:"_id"})}async createCollection(t){var e;return this.collections.has(t)?(console.log(`Collection "${t}" already exists.`),new w(!1,this.collections.get(t),new f(`Collection "${t}" already exists`,p))):(this.db.objectStoreNames.contains(t)||(e=this.db.version+1,this.db.close(),this.db=await l.openDatabase(this.name,e,(e,a,r)=>{this._createDataStore(e,t)})),await(e=new T(this,t,this.settings)).init(),this.collections.set(t,e),this.data.getCollectionMetadata(t),await this.data.saveMetadata(),new w(!0,e))}async deleteCollection(t){var e;return this.collections.has(t)?(await(e=this.collections.get(t)).close(),e.observer._cleanup(),await l.performTransaction(this.db,t,"readwrite",t=>l.clear(t)),this.collections.delete(t),this.data.removeCollectionMetadata(t),await this.data.saveMetadata(),new w(!0,null)):new w(!1,null,new f(`Collection "${t}" does not exist`,y))}async getCollection(t){var e;return this.collections.has(t)?new w(!0,this.collections.get(t)):this.db.objectStoreNames.contains(t)?(await(e=new T(this,t,this.settings)).init(),this.collections.set(t,e),new w(!0,e)):new w(!1,null,new f(`Collection "${t}" does not exist`,y))}async close(){var t;for(t of this.collectionsArray)await t.close();this.db&&(this.db.close(),this.db=null)}async deleteDatabase(){await this.close(),await l.deleteDatabase(this.name),m.removeItem(this.data.metadataKey),this.settings.clear(),this.data=null}get name(){return this._dbName}get db(){return this._db}set db(t){this._db=t}get data(){return this.metadata}set data(t){this.metadata=t}get collectionsArray(){return Array.from(this.collections.values())}get collections(){return this._collections}get metadata(){return this._metadata}set metadata(t){this._metadata=t}get totalSizeKB(){return this.data.totalSizeKB}get totalLength(){return this.data.totalLength}get modifiedAt(){return this.data.modifiedAt}get settings(){return this._settings}get settingsData(){return this.settings.data}toString(){return`[Database: ${this.name} | Collections: ${this.collections.size} | Size: ${this.totalSizeKB.toFixed(2)}KB | Documents: ${this.totalLength}]`}}class B{constructor(t,e=null){this._id=t._id||this._generateId(),this._created=t._created||Date.now(),this._permanent=!!t._permanent,this._encrypted=t._encrypted||!!e,this._compressed=t._compressed||!1,this._attachments=t._attachments||t.attachments||[],t.packedData?(this._packedData=t.packedData,this._modified=t._modified||Date.now(),this._data=null):(this._data=t.data||{},this._modified=Date.now(),this._packedData=new Uint8Array(0)),this._encryptionKey=e||""}get attachments(){return this._attachments}set attachments(t){this._attachments=t}get data(){return this._data}get packedData(){return this._packedData}get encryptionKey(){return this._encryptionKey}set data(t){this._data=t}set packedData(t){this._packedData=t}set encryptionKey(t){this._encryptionKey=t}static hasAttachments(t){return t._attachments&&0<t._attachments.length||t.attachments&&0<t.attachments.length}static async getAttachments(t,e,a){var r;return B.hasAttachments(t)?(r=t._attachments||t.attachments,t.attachments=await h.getAttachments(r),Promise.resolve(t)):[]}static isEncrypted(t){return t._encrypted&&t.packedData}static async decryptDocument(t,e){if(B.isEncrypted(t))return e=await u.decrypt(t.packedData,e),e=c.unpack(e),{_id:t._id,_created:t._created,_modified:t._modified,_encrypted:!0,_compressed:t._compressed,_permanent:!!t._permanent,attachments:t.attachments,data:e};throw new Error("Document is not encrypted.")}async pack(){if(!this.data)throw new Error("No data to pack");let t=c.pack(this.data);return this._compressed&&(t=await this._compressData(t)),this._encrypted&&(t=await this._encryptData(t)),this.packedData=t}packSync(){if(!this.data)throw new Error("No data to pack");if(this._encrypted)throw new Error("Packing synchronously a document being encrypted is impossible.");if(this._compressed)throw new Error("Packing synchronously a document being compressed is impossible.");var t=c.pack(this.data);return this.packedData=t}async unpack(){if(!this.data&&0<this.packedData.length){let t=this.packedData;this._encrypted&&(t=await this._decryptData(t)),this._compressed&&(t=await this._decompressData(t)),this.data=c.unpack(t)}return this.data}unpackSync(){if(!this.data&&0<this.packedData.length){if(this._encrypted)throw new Error("Unpacking synchronously a document being encrypted is impossible.");if(this._compressed)throw new Error("Unpacking synchronously a document being compressed is impossible.");this.data=c.unpack(this.packedData)}return this.data}async _encryptData(t){var e=this.encryptionKey;return u.encrypt(t,e)}async _decryptData(t){var e=this.encryptionKey;return u.decrypt(t,e)}async _compressData(t){return d.compress(t)}async _decompressData(t){return d.decompress(t)}_generateId(){return"xxxx-xxxx-xxxx".replace(/[x]/g,()=>(16*Math.random()|0).toString(16))}async objectOutput(t=!1){this.data||await this.unpack();var e={_id:this._id,_created:this._created,_modified:this._modified,_permanent:this._permanent,_encrypted:this._encrypted,_compressed:this._compressed,attachments:this.attachments,data:this.data};return t&&0<this.attachments.length&&(t=await h.getAttachments(this.attachments),e.attachments=t),e}async databaseOutput(){return this.packedData&&0!==this.packedData.length||await this.pack(),{_id:this._id,_created:this._created,_modified:this._modified,_permanent:!!this._permanent,_compressed:this._compressed,_encrypted:this._encrypted,attachments:this.attachments,packedData:this.packedData}}toString(){return`[Document: ${this._id} | Created: ${new Date(this._created).toISOString()} | Encrypted: ${this._encrypted} | Compressed: ${this._compressed} | Permanent: ${this._permanent}]`}}class C{constructor(t,e={}){this._dbName=t,this._settingsKey=`lacertadb_${this._dbName}_settings`,this._data=this._loadSettings(),this._mergeSettings(e)}init(){if(this.set("sizeLimitKB",this.get("sizeLimitKB")||1/0),this.set("bufferLimitKB",this.get("bufferLimitKB")||-.2*this.get("sizeLimitKB")),this.get("bufferLimitKB")<-.8*this.get("sizeLimitKB"))throw new Error("Buffer limit cannot be below -80% of the size limit.");this.set("freeSpaceEvery",this._validateFreeSpaceSetting(this.get("freeSpaceEvery")))}_validateFreeSpaceSetting(t=1e4){if(void 0===t||!1===t||0===t)return 1/0;if(t<1e3&&0!==t)throw new Error("Invalid freeSpaceEvery value. It must be 0, Infinity, or above 1000.");return 1e3<=t&&t<1e4&&console.warn("Warning: freeSpaceEvery value is between 1000 and 10000, which may lead to frequent freeing."),t}_loadSettings(){return m.getItem(this.settingsKey)||{}}_saveSettings(){m.setItem(this.settingsKey,this.data)}_mergeSettings(t){this.data=Object.assign(this.data,t),this._saveSettings()}get(t){return this.data[t]}set(t,e){this.data[t]=e,this._saveSettings()}remove(t){delete this.data[t],this._saveSettings()}clear(){this.data={},this._saveSettings()}get dbName(){return this._dbName}get data(){return this._data}set data(t){this._data=t}get settingsKey(){return this._settingsKey}toString(){return`[Settings: ${this.dbName} | SizeLimit: ${this.get("sizeLimitKB")}KB | BufferLimit: ${this.get("bufferLimitKB")}KB]`}}class T{constructor(t,e,a){this._database=t,this._collectionName=e,this._settings=a,this._metadata=null,this._lastFreeSpaceTime=0,this._observer=new S,this._transactionManager=new v,this._freeSpaceInterval=null,this._freeSpaceHandler=null}get observer(){return this._observer}async createIndex(t,e={}){let a=e.name||t.replace(/\./g,"_");var r=this.database.db.version+1;this.database.db.close(),this.database.db=await l.openDatabase(this.database.name,r,r=>{r.objectStoreNames.contains(this.name)&&!(r=r.transaction([this.name]).objectStore(this.name)).indexNames.contains(a)&&r.createIndex(a,t,{unique:e.unique||!1,multiEntry:e.multiEntry||!1})})}async init(){this.metadata=this.database.metadata.getCollectionMetadata(this.name),this.settingsData.freeSpaceEvery!==1/0&&(this._freeSpaceHandler=()=>this._maybeFreeSpace(),this._freeSpaceInterval=setInterval(this._freeSpaceHandler,this.settingsData.freeSpaceEvery))}get name(){return this._collectionName}get sizes(){return this.metadataData.documentSizes||{}}get modifications(){return this.metadataData.documentModifiedAt||{}}get attachments(){return this.metadataData.documentAttachments||{}}get permanents(){return this.metadataData.documentPermanent||{}}get keys(){return Object.keys(this.sizes)}get documentsMetadata(){var t,e=this.keys,a=this.sizes,r=this.modifications,s=this.permanents,i=this.attachments,n=new Array(e.length),o=0;for(t of e)n[o++]={id:t,size:a[t],modified:r[t],permanent:s[t],attachment:i[t]};return n}get settings(){return this._settings}get settingsData(){return this.settings.data}set settings(t){this._settings=t}get lastFreeSpaceTime(){return this._lastFreeSpaceTime}set lastFreeSpaceTime(t){this._lastFreeSpaceTime=t}get database(){return this._database}get metadata(){return this.database.metadata.getCollectionMetadata(this.name)}get metadataData(){return this.metadata.getRawMetadata()}set metadata(t){this._metadata=t}get sizeKB(){return this.metadataData.sizeKB}get length(){return this.metadataData.length}get totalSizeKB(){return this.sizeKB}get totalLength(){return this.length}get modifiedAt(){return this.metadataData.modifiedAt}get isFreeSpaceEnabled(){return this.settingsData.freeSpaceEvery!==1/0}get shouldRunFreeSpaceSize(){return this.totalSizeKB>this.settingsData.sizeLimitKB+this.settingsData.bufferLimitKB}get shouldRunFreeSpaceTime(){return this.isFreeSpaceEnabled&&Date.now()-this.lastFreeSpaceTime>=this.settingsData.freeSpaceEvery}async _maybeFreeSpace(){if(this.shouldRunFreeSpaceSize||this.shouldRunFreeSpaceTime)return this.freeSpace(this.settingsData.sizeLimitKB)}async addDocument(t,e=null){return this._transactionManager.execute(async()=>{this.observer._emit("beforeAdd",t);var a=new B(t,e),r=[];if(B.hasAttachments(t)){var s=t._attachments||t.attachments;for(let t=0;t<s.length;t++)r.push(`${this.database.name}/${this.name}/${a._id}/`+t);a._attachments=r}let i=await a.databaseOutput();var n,o=i._id,c=i._permanent||!1,d=i.packedData.byteLength/1024;let u=!(o in this.metadataData.documentSizes);try{await l.performTransaction(this.database.db,this.name,"readwrite",t=>u?l.add(t,i):l.put(t,i)),0<r.length&&(n=t._attachments||t.attachments,await h.saveAttachments(this.database.name,this.name,a._id,n)),this.metadata.updateDocument(o,d,c,r.length),await this.database.metadata.saveMetadata()}catch(n){if(0<r.length)try{await h.deleteAttachments(this.database.name,this.name,a._id)}catch(n){}throw n}return await this._maybeFreeSpace(),this.observer._emit("afterAdd",t),u})}async getDocument(t,e=null,a=!1){if(this.observer._emit("beforeGet",t),t in this.metadataData.documentSizes){var r=await l.performTransaction(this.database.db,this.name,"readonly",e=>l.get(e,t));if(r){let t;if(B.isEncrypted(r)){if(!e)return!1;t=new B(r,e)}else t=new B(r);return e=await t.objectOutput(a),this.observer._emit("afterGet",e),e}}return!1}async getDocuments(t,e=null,a=!1){let r=[],s=t.filter(t=>t in this.metadataData.documentSizes);return 0!==s.length&&await l.performTransaction(this.database.db,this.name,"readonly",async t=>{var i,n=s.map(e=>l.get(t,e));for(i of await Promise.all(n))if(i){let t;if(B.isEncrypted(i)){if(!e)continue;t=new B(i,e)}else t=new B(i);var o=await t.objectOutput(a);r.push(o)}}),r}async deleteDocument(t,e=!1){return this.observer._emit("beforeDelete",t),!(this.permanents[t]&&!e)&&t in this.sizes&&(0<(this.metadata.documentAttachments[t]||0)&&await h.deleteAttachments(this.database.name,this.name,t),await l.performTransaction(this.database.db,this.name,"readwrite",e=>l.delete(e,t)),this.metadata.deleteDocument(t),await this.database.metadata.saveMetadata(),this.observer._emit("afterDelete",t),!0)}async freeSpace(t){let e;this.lastFreeSpaceTime=Date.now();var a,r=this.sizeKB;if(0<=t){if(r<=t)return 0;e=r-t}else t=r-(e=-t);let s=0;for([a]of Object.entries(this.metadataData.documentModifiedAt).filter(([t])=>!this.metadataData.documentPermanent[t]).sort((t,e)=>t[1]-e[1]))if(this.sizeKB>t){if(s+=this.metadataData.documentSizes[a],await this.deleteDocument(a,!0),s>=e)break}return s}async query(t={},e={}){let{encryptionKey:a=null,limit:r=1/0,offset:s=0,orderBy:i=null,index:n=null}=e,o=[],c=0,h=0;return await l.performTransaction(this.database.db,this.name,"readonly",async e=>{let d=e,u=(n&&e.indexNames.contains(n)&&(d=e.index(n)),i?d.openCursor(null,"asc"===i?"next":"prev"):d.openCursor());return new Promise((e,i)=>{u.onsuccess=async i=>{if(!(i=i.target.result)||c>=r)e(o);else{var n,d=i.value;if(h<s)h++;else{let e;if(B.isEncrypted(d)){if(!a)return void i.continue();e=new B(d,a)}else e=new B(d);if(0<Object.keys(t).length){var u,l=await e.objectOutput();let a=!0;for(u in t)if((u.includes(".")?(n=l.data,u.split(".").reduce((t,e)=>(t||{})[e],n)):l.data[u])!==t[u]){a=!1;break}if(!a)return void i.continue()}o.push(await e.objectOutput()),c++}i.continue()}},u.onerror=()=>i(u.error)})}),o}async close(){this._freeSpaceInterval&&(clearInterval(this._freeSpaceInterval),this._freeSpaceInterval=null,this._freeSpaceHandler=null)}toString(){return`[Collection: ${this.name} | Database: ${this.database.name} | Size: ${this.sizeKB.toFixed(2)}KB | Documents: ${this.length}]`}}},function(t,e,a){var r=(()=>{var t=new ArrayBuffer(2560),e=new Uint8Array(t,0,256),a=new Uint8Array(t,256,256),r=new Uint32Array(t,512,128),s=new Uint32Array(t,1024,128),i=new Uint32Array(t,1536,128),n=new Uint32Array(t,2048,128);e.set(Uint8Array.from("AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHHIIIIJJJJKKKKLLLLMMMMNNNNOOOOPPPPQQQQRRRRSSSSTTTTUUUUVVVVWWWWXXXXYYYYZZZZaaaabbbbccccddddeeeeffffgggghhhhiiiijjjjkkkkllllmmmmnnnnooooppppqqqqrrrrssssttttuuuuvvvvwwwwxxxxyyyyzzzz0000111122223333444455556666777788889999++++////".split("").map((function(t){return 255&t.charCodeAt(0)})))),a.set(Uint8Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("").map((function(t){return 255&t.charCodeAt(0)})))),r.set(new Uint32Array(128).fill(33554431)),s.set(new Uint32Array(128).fill(33554431)),i.set(new Uint32Array(128).fill(33554431)),n.set(new Uint32Array(128).fill(33554431)),Object.entries({43:[248,57347,8392448,4063232],47:[252,61443,12586752,4128768],48:[208,16387,3328,3407872],49:[212,20483,4197632,3473408],50:[216,24579,8391936,3538944],51:[220,28675,12586240,3604480],52:[224,32771,3584,3670016],53:[228,36867,4197888,3735552],54:[232,40963,8392192,3801088],55:[236,45059,12586496,3866624],56:[240,49155,3840,3932160],57:[244,53251,4198144,3997696],65:[0,0,0,0],66:[4,4096,4194304,65536],67:[8,8192,8388608,131072],68:[12,12288,12582912,196608],69:[16,16384,256,262144],70:[20,20480,4194560,327680],71:[24,24576,8388864,393216],72:[28,28672,12583168,458752],73:[32,32768,512,524288],74:[36,36864,4194816,589824],75:[40,40960,8389120,655360],76:[44,45056,12583424,720896],77:[48,49152,768,786432],78:[52,53248,4195072,851968],79:[56,57344,8389376,917504],80:[60,61440,12583680,983040],81:[64,1,1024,1048576],82:[68,4097,4195328,1114112],83:[72,8193,8389632,1179648],84:[76,12289,12583936,1245184],85:[80,16385,1280,1310720],86:[84,20481,4195584,1376256],87:[88,24577,8389888,1441792],88:[92,28673,12584192,1507328],89:[96,32769,1536,1572864],90:[100,36865,4195840,1638400],97:[104,40961,8390144,1703936],98:[108,45057,12584448,1769472],99:[112,49153,1792,1835008],100:[116,53249,4196096,1900544],101:[120,57345,8390400,1966080],102:[124,61441,12584704,2031616],103:[128,2,2048,2097152],104:[132,4098,4196352,2162688],105:[136,8194,8390656,2228224],106:[140,12290,12584960,2293760],107:[144,16386,2304,2359296],108:[148,20482,4196608,2424832],109:[152,24578,8390912,2490368],110:[156,28674,12585216,2555904],111:[160,32770,2560,2621440],112:[164,36866,4196864,2686976],113:[168,40962,8391168,2752512],114:[172,45058,12585472,2818048],115:[176,49154,2816,2883584],116:[180,53250,4197120,2949120],117:[184,57346,8391424,3014656],118:[188,61442,12585728,3080192],119:[192,3,3072,3145728],120:[196,4099,4197376,3211264],121:[200,8195,8391680,3276800],122:[204,12291,12585984,3342336]}).forEach((function(t){r[parseInt(t[0])]=4294967295&t[1][0],s[parseInt(t[0])]=4294967295&t[1][1],i[parseInt(t[0])]=4294967295&t[1][2],n[parseInt(t[0])]=4294967295&t[1][3]}));class o{constructor(){this._CHNK_L_=Math.pow(108,2)/2|0,this._CHNK_L_STR_=3*this._CHNK_L_|0,this._CHNK_L_BUFF_=4*this._CHNK_L_|0,this._PAD_C_=255&"=".charCodeAt(0),this._E0_=e.slice(0,e.length),this._E1_=a.slice(0,a.length),this._D0_=r.slice(0,r.length),this._D1_=s.slice(0,s.length),this._D2_=i.slice(0,i.length),this._D3_=n.slice(0,n.length),this._AB_=new ArrayBuffer(this._CHNK_L_BUFF_+4|0),this._u32aT_=new Uint32Array(this._AB_,0,1),this._u8aT_=new Uint8Array(this._AB_,0,3),this._T_=new Uint8Array(this._AB_,4,0|this._CHNK_L_BUFF_)}get PAD_C(){return 255&this._PAD_C_}get CHNK_L_STR(){return 0|this._CHNK_L_STR_}get u32aT0(){return this._u32aT_[0]}set u32aT0(t){this._u32aT_[0]=(0|t)>>>0}get u8aTa(){return this._u8aT_[0]}get u8aTb(){return this._u8aT_[1]}get u8aTc(){return this._u8aT_[2]}_base64_decode_u32ax1(t,e){this.u32aT0=this._D0_[255&t.charCodeAt(e=(0|e)>>>0)]|this._D1_[255&t.charCodeAt(e+1|0)]|this._D2_[255&t.charCodeAt(e+2|0)]|this._D3_[255&t.charCodeAt(e+3|0)]}_base64_encode_u8ax4(t,e,a){this._T_[0|(e=(0|e)>>>0)]=this._E0_[t[(0|(a=(0|a)>>>0))>>>0]],this._T_[e+1|0]=this._E1_[(3&t[(0|a)>>>0])<<4|t[(a+1|0)>>>0]>>4&15],this._T_[e+2|0]=this._E1_[(15&t[(a+1|0)>>>0])<<2|t[(a+2|0)>>>0]>>6&3],this._T_[e+3|0]=this._E1_[t[(a+2|0)>>>0]]}_base64_encode_final(t,e,a,r){switch(r=(0|r)>>>0,((a=(0|a)>>>0)-(e=(0|e)>>>0)|0)>>>0){case 1:return this._T_[0|r]=this._E0_[t[(0|e)>>>0]],this._T_[r+1|0]=this._E1_[(3&t[(0|e)>>>0])<<4|t[(e+1|0)>>>0]>>4&15],this._T_[r+2|0]=this._PAD_C_,this._T_[r+3|0]=this._PAD_C_,this._T_.subarray(0,0|(r=r+4|0));case 2:return this._T_[0|r]=this._E0_[t[(0|e)>>>0]],this._T_[r+1|0]=this._E1_[(3&t[(0|e)>>>0])<<4|t[(e+1|0)>>>0]>>4&15],this._T_[r+2|0]=this._E1_[(15&t[(e+1|0)>>>0])<<2|t[(e+2|0)>>>0]>>6&3],this._T_[r+3|0]=this._PAD_C_,this._T_.subarray(0,0|(r=r+4|0));case 0:return this._T_.subarray(0,0|r);default:return this._T_}}_base64_decode_final(t,e,a,r,s){switch(a=(0|a)>>>0,r=(0|r)>>>0,0|(s=(0|s)>>>0)){case 0:return this.u32aT0=(this._D0_[e.charCodeAt(0|a)]|this._D1_[e.charCodeAt(a+1|0)]|this._D2_[e.charCodeAt(a+2|0)]|this._D3_[e.charCodeAt(a+3|0)]|0)>>>0,t[0|r]=255&this.u32aT0,t[r+1|0]=this.u32aT0>>8&255,t[r+2|0]=this.u32aT0>>16&255,r+3|0;case 1:return this.u32aT0=(0|this._D0_[e.charCodeAt(0|a)])>>>0,t[0|r]=255&this.u32aT0,r+1|0;case 2:return this.u32aT0=(this._D0_[e.charCodeAt(0|a)]|this._D1_[e.charCodeAt(a+1|0)]|0)>>>0,t[0|r]=255&this.u32aT0,r+1|0;default:return this.u32aT0=(this._D0_[e.charCodeAt(0|a)]|this._D1_[e.charCodeAt(a+1|0)]|this._D2_[e.charCodeAt(a+2|0)]|0)>>>0,t[0|r]=255&this.u32aT0,t[r+1|0]=this.u32aT0>>8&255,r+2|0}}_base64_store_u8ax3(t,e){t[e=(0|e)>>>0]=this.u8aTa,t[e+1|0]=this.u8aTb,t[e+2|0]=this.u8aTc}get_max_round_str(t){return 0|Math.ceil(t/this.CHNK_L_STR)}base64_encode(t,e){var a=0|t.length,r=(e|=0)*this.CHNK_L_STR|0,s=0,i=Math.min(r+this.CHNK_L_STR|0,0|a)-2|0;if(0<(0|i))for(;(0|r)<(0|i);r=(r+3|0)>>>0,s=s+4|0)this._base64_encode_u8ax4(t,s,r);return o.encodeChars_(this._base64_encode_final(t,r,a,s))}bytesToBase64(t){for(var e="",a=0,r=this.get_max_round_str(t.length);(0|a)<(0|r);a=(a+1|0)>>>0)e+=this.base64_encode(t,0|a);return e}base64ToBytes(t){var e,a,r=0|t.length,s=0,i=0,n=0;if(0==(0|r))return new Uint8Array(0);for(t.charCodeAt(r-1|0)===this.PAD_C&&(n=n+1|0,t.charCodeAt((r=r-1|0)-1|0)===this.PAD_C)&&(r=r-1|0,n=n+1|0),e=new Uint8Array(t.length/4*3-n),a=0==(0|(n=3&r))?(r>>>2)-1|0:r>>>2;(0|s)<(0|a);s=(s+1|0)>>>0)this._base64_decode_u32ax1(t,s<<2),this._base64_store_u8ax3(e,i),i=i+3|0;return this._base64_decode_final(e,t,s<<=2,i,n),e}}return o.charCode_=function(t){return 255&t.charCodeAt(0)},o.charCodeAt_=function(t,e){return 255&t.charCodeAt(0|e)},o.encodeChars_=function(t){return 0<(0|t.length)?String.fromCharCode.apply(null,t):""},o})();t.exports={B64chromium:r}}]);