(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i{try{var s=this.uint8.from(atob(t),t=>t.charCodeAt(0)),n=s.slice(0,16),h=s.slice(16),o=await this.key(e),a=await this.crypto.subtle.decrypt({name:"AES-CBC",iv:n},o,h);r((new TextDecoder).decode(a))}catch(t){i("Invalid 'secret key'")}})},CrypThor.prototype.key=async function(t){try{var e=new this.txEnc,r=await this.crypto.subtle.importKey("raw",e.encode(t),{name:"PBKDF2"},!1,["deriveBits","deriveKey"]);return this.crypto.subtle.deriveKey({name:"PBKDF2",salt:new this.uint8(this.salt),iterations:Math.max(100,this.iterations),hash:this.hash},r,{name:"AES-CBC",length:256},!0,["encrypt","decrypt"])}catch(t){return"https only"}};var _default=exports.default=CrypThor; },{}],2:[function(require,module,exports){ "use strict";function shortStack(r){if(r.stack){const t=r.stack.split("\n");r.stack=t.map(r=>{const t=r.match(/\((http:\/\/.*?\/)([^\/]+\/.*):(\d+:\d+)\)/);return t?r.replace(t[1],"/"):r}).join("\n")}}Object.defineProperty(exports,"__esModule",{value:!0}),exports.MerlinOperatorsError=exports.MerlinInvalidOptionError=exports.MerlinError=void 0;class MerlinError extends Error{constructor(r){super(r),this.name="MerlinDB Error",shortStack(this)}}exports.MerlinError=MerlinError;class MerlinOperatorsError extends Error{constructor(r){super(r),this.name="MerlinDB Operators Error",shortStack(this)}}exports.MerlinOperatorsError=MerlinOperatorsError;class MerlinInvalidOptionError extends Error{constructor(r){super(r),this.name="MerlinDB Invalid Option Error",shortStack(this)}}exports.MerlinInvalidOptionError=MerlinInvalidOptionError; },{}],3:[function(require,module,exports){ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"MerlinDB",{enumerable:!0,get:function(){return _merlinDb.MerlinDB}}),Object.defineProperty(exports,"ObjectId",{enumerable:!0,get:function(){return _merlinDb.ObjectId}}),Object.defineProperty(exports,"Schema",{enumerable:!0,get:function(){return _merlinDb.Schema}});var _merlinDb=require("./merlin-db.js");window.MerlinDB=_merlinDb.MerlinDB,window.ObjectId=_merlinDb.ObjectId,window.Schema=_merlinDb.Schema; },{"./merlin-db.js":4}],4:[function(require,module,exports){ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.MerlinDB=MerlinDB,Object.defineProperty(exports,"ObjectId",{enumerable:!0,get:function(){return _query.ObjectId}}),exports.Schema=Schema;var _errors=require("./errors.js"),_query=_interopRequireWildcard(require("./query.js"));function _getRequireWildcardCache(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,r=new WeakMap;return(_getRequireWildcardCache=function(e){return e?r:t})(e)}function _interopRequireWildcard(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=_getRequireWildcardCache(t);if(r&&r.has(e))return r.get(e);var n={__proto__:null},a=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&{}.hasOwnProperty.call(e,o)){var s=a?Object.getOwnPropertyDescriptor(e,o):null;s&&(s.get||s.set)?Object.defineProperty(n,o,s):n[o]=e[o]}return n.default=e,r&&r.set(e,n),n}function MerlinDB(){if(!(this instanceof MerlinDB))return new MerlinDB;this.models=[],this.dbApi=window.indexedDB}function Schema(e){return e=e||{}}function setSchema(e,t){t&&(Object.entries(e).forEach(e=>{e[1]=e[1].unique||!1,"id_"!=e[0]&&t.createIndex(e[0],e[0],{unique:e[1]})}),t.createIndex("id_","id_",{unique:!0}),t.createIndex("$order","$order",{unique:!0}))}function isModel(e,t){return e.objectStoreNames.contains(t)}MerlinDB.prototype.model=function(e,t){if(!t)throw new _errors.MerlinError("Define an Schema");return new _query.default(t,this,e)},MerlinDB.prototype.version=function(e){return new Promise(t=>{this.dbApi.open(e||this.dbName).onsuccess=(e=>{var r=e.target.result;t(r.version),r.close()})})},MerlinDB.prototype.dbOpen=function(){return new Promise(e=>{this.dbApi.open(this.dbName).onsuccess=(t=>{var r=t.target.result;e(r)})})},MerlinDB.prototype.connect=function(e){var t=this;return t.dbName=e,new Promise((e,r)=>{t.open=t.dbApi.open(t.dbName),t.open.onsuccess=(t=>{var r=t.target.result;e({status:200,message:"Database connected"}),r.close()}),t.open.onerror=(e=>{r({status:400,message:e})})})},MerlinDB.prototype.dropDatabase=function(e){var t=this;return new Promise(async(r,n)=>{var a=await t.dbApi.databases(e);a=Object.values(a);var o=new Promise(t=>{for(const r of a)if(r.name===e)return t(!0);t(!1)});if(!await o)return n({status:400,message:`There's no '${e}' database!`});t.dbApi.deleteDatabase(e).onsuccess=(e=>{r({status:200,message:"Database deleted successfully"})})})},MerlinDB.prototype.databaseSize=function(e){return e=e||{},new Promise((t,r)=>{var n=this.dbApi.open(this.dbName),a=0;n.onsuccess=(r=>{var n=r.target.result,o=Object.values(n.objectStoreNames);if(0===o.length)return n.close(),t(0);o.forEach((r,s)=>{n.transaction([r],"readonly").objectStore(r).getAll().onsuccess=(r=>{if(r.target.result.forEach(e=>{a+=JSON.stringify(e).length}),s===o.length-1){if(e.format)return(a=(new _query.default).formatDataSize(a,e))[1]?void t(a[0]+a[1]):t(a[0]);t(a)}n.close()})})})})},MerlinDB.prototype.getMemInfo=function(e){e=e||{};var t=window.navigator;return new Promise((r,n)=>{t.storage&&t.storage.estimate?t.storage.estimate().then(t=>{var n={total:t.quota,used:t.usage};if(n.remainder=n.total-n.used,e.format){for(const t in n)n[t]=(new _query.default).formatDataSize(n[t],e),e.string?n[t]=n[t][0]+n[t][1]:n[t]=n[t][0];return r(n)}r(n)}):n("There's no StorageManager API.")})},MerlinDB.prototype.dropAll=function(e){e=e||[];var t=0,r=0,n=[];return new Promise(async(a,o)=>{var s=await this.dbApi.databases();if(0===s.length)return a({deleteDbCount:0,hasDatabase:"NO"});s.forEach(async o=>{t++,-1===e.indexOf(o.name)&&(n.push(o.name),r++,this.dropDatabase(o.name),s.length===t&&a({deleteDbCount:r,status:200,databasesDeleted:n}))})})},MerlinDB.prototype.info=function(e){return e=e||{},new Promise(async(t,r)=>{t({estimatedSize:await this.databaseSize(e.sizes),merlinDB:{databases:await this.dbApi.databases(),models:await this.getModels()}})})},MerlinDB.prototype.createModel=function(e,t){return new Promise(async(r,n)=>{var a=await this.version();this.dbApi.open(this.dbName,a+1).onupgradeneeded=(a=>{var o=a.target.result;if(o.objectStoreNames.contains(e))return n(`'${e}' model already exists!`),o.close();var s=o.createObjectStore(e,{keyPath:"id_"});setSchema(t,s),this.getModel(e).then(t=>{r({status:200,message:`Model '${e}' created!`,modelInfo:t})}),o.close()})})},MerlinDB.prototype.deleteModel=function(e){var t=this;return new Promise((r,n)=>{t.dbApi.open(t.dbName).onsuccess=(a=>{var o=a.target.result,s=o.version+1;if(!isModel(o,e))return o.close(),void n(`'${e}' model not found!`);o.close();var i=t.dbApi.open(t.dbName,s);i.onupgradeneeded=function(t){(o=t.target.result).deleteObjectStore(e)},i.onsuccess=(n=>{n.target.result.close(),t.dbApi.open(t.dbName).onsuccess=(t=>{t.target.result.close(),r(`${e} was deleted!`)})}),i.onerror=(t=>{n(`'${e}' model not found!`)}),o.close()})})},MerlinDB.prototype.renameModel=function(e,t,r){if("object"!=typeof r||Array.isArray(r)||!r)throw new _errors.MerlinError("Please define your 'actual schema' in renameModel method!");return new Promise(async(n,a)=>{var o=this.model(e,r);try{await this.getModel(e)}catch(e){return a(e)}try{await this.createModel(t,r)}catch(e){return a(e)}var s=await o.find(),i=this.model(t,r);i=await i.insert(s),this.deleteModel(e),n({oldModel:e,newModel:t,renamed:!0,data:i.data,status:"Successful"})})},MerlinDB.prototype.getModels=function(){return new Promise(async(e,t)=>{var r=await this.dbApi.open(this.dbName),n=[];r.onsuccess=(r=>{var a=r.target.result,o=Object.values(a.objectStoreNames);if(0===o.length)return a.close(),void t({modelsCount:0,anyModel:"NO"});o.forEach(t=>{var r=a.transaction([t],"readonly"),o=r.objectStore(t),s=o.index("id_").getAll(),i=0,c=0;s.onsuccess=(e=>{e.target.result.forEach(e=>{i+=JSON.stringify(e).length,c++}),n.push({name:t,indexes:Object.values(o.indexNames),size:i+" bytes",records:c})}),r.oncomplete=(t=>{e(n)})}),a.close()})})},MerlinDB.prototype.getModel=function(e){if("string"!=typeof e)throw new _errors.MerlinError("Define an string with your modelName");return new Promise(async(t,r)=>{(await this.dbApi.open(this.dbName)).onsuccess=(n=>{var a=n.target.result;if(!a.objectStoreNames.contains(e))return a.close(),r(`There's no '${e}' model in your Database!`);var o=a.transaction([e],"readonly").objectStore(e),s=o.index("id_").getAll(),i=0,c=0;s.onsuccess=(r=>{r.target.result.forEach(e=>{i+=JSON.stringify(e).length,c++}),t({name:e,indexes:Object.values(o.indexNames),size:i+" bytes",records:c})}),a.close()})})},MerlinDB.prototype.Schema=Schema; },{"./errors.js":2,"./query.js":7}],5:[function(require,module,exports){ "use strict";function ObjectId(){return this instanceof ObjectId?this:new ObjectId}function generate(t){return Math.floor(Date.now()/1e3).toString(16)+btoa(navigator.userAgent).substring(0,6)+Math.floor(65535*Math.random()).toString(16).padStart(4,"0")+(t=(t+1)%16777215).toString(16).padStart(6,"0")}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0,ObjectId.prototype.toString=function(){return generate(Math.floor(16777215*Math.random()))},ObjectId.prototype.unlimited=function(t){t=t||24;for(var e="",r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",o=r.length,n=0;n=arguments[1])},Operators.prototype.$gte=function(){return this.errorNumber(arguments[0],"$gte"),this.command(arguments[0]>arguments[1])},Operators.prototype.checkIn=function(r){var t=!0;return r[0].forEach(e=>{e===r[1]&&(t=!1),e instanceof RegExp&&e.test(r[1])&&(t=!1)}),t},Operators.prototype.$in=function(){return this.errorArray(arguments[0],"$in"),this.command(this.checkIn(arguments))},Operators.prototype.$lt=function(){return this.errorNumber(arguments[0],"$lt"),this.command(arguments[0]<=arguments[1])},Operators.prototype.$lte=function(){return this.errorNumber(arguments[0],"$lte"),this.command(arguments[0]{e instanceof RegExp?e.test(r[1])&&(t=!0):e===r[1]&&(t=!0)})}return t},Operators.prototype.$ne=function(){return this.errorNe(arguments[0],"$ne",arguments[2]),this.command(arguments[0]===arguments[1])},Operators.prototype.$nin=function(){if(this.errorNe(arguments[0],"$nin",arguments[2]),arguments[0],!Array.isArray(arguments[0]))throw new Error("Ivaliasd as '$ne'");if(arguments[0],Array.isArray(arguments[0]))return this.$ninArray(arguments)},Operators.prototype.firstEnc=function(r,t,e){return this[(r=this.entries(r)[0])[0]](r[1],t)},Operators.prototype.$and=function(r,t,e){var o=!1;return this.entries(r).forEach(r=>{this.firstEnc(r[1],t[r[0]])&&(o=!0)}),o},Operators.prototype.$not=function(r,t){var e=!1;return this[(r=this.entries(r)[0])[0]](r[1],t)||(e=!0),e},Operators.prototype.$nor=function(r,t){var e=!1,o=this;return r.forEach(r=>{if("object"==typeof(r=this.entries(r)[0])[1]){var n=this.entries(r[1])[0];o[n[0]](n[1],t[r[0]])||(e=!0)}else t[r[0]]===r[1]&&(e=!0)}),e},Operators.prototype.$or=function(r,t){var e=!0,o=this;return r.forEach(r=>{if("object"==typeof(r=this.entries(r)[0])[1]){var n=this.entries(r[1])[0];o[n[0]](n[1],t[r[0]])||(e=!1)}else!t[r[0]]!==r[1]&&(e=!1)}),e},Operators.prototype.$regex=function(){var r=arguments;if(!this.regexTransformer(r[0]).test(r[1]))return!0},Operators.prototype.regexTransformer=function(r){if(r instanceof RegExp||"string"==typeof r)return new RegExp(r);if(Array.isArray(r)&&r.length>=1&&"string"==typeof r[0])return new RegExp(r[0],r[1]||"");throw new Error(`Invalid regex ${r}`)},Operators.prototype.$exists=function(){var r=arguments,t=this,e=r[1][0][r[1][1]],o=0;if("boolean"!=typeof r[0])throw new _errors.MerlinOperatorsError(`Invalid type '${r[0]}'`);return this.entries(r[1][2]).forEach(r=>{"$exists"!==r[0]&&t[r[0]](r[1],e)&&e&&o++}),e||o++,r[0]||o++,1==o},Operators.prototype.$type=function(){var r=arguments,t=!0;return r[0]=Array.isArray(r[0])?r[0]:Array(r[0]),r[0]=this.typesIndex[r[0]]||r[0],r[1]=r[3][r[4]]?r[1]:void 0,-1!==r[0].indexOf(typeof r[1])&&(t=!1),t},Operators.prototype.$mod=function(){var r=arguments,t=!0;return r[1]%r[0][0]===r[0][1]&&(t=!1),t},Operators.prototype.$text=function(){var r=arguments,t=!0,e=Object.values(r[0]);return new RegExp(e[0]).test(r[1][e[1]])&&(t=!1),t},Operators.prototype.$where=function(){var r=arguments[0],t=!0;return r[0].call(r[1])&&(t=!1),t},Operators.prototype.$all=function(){var r=arguments,t=!0;return!r[3][r[4]]||(r[0].every(t=>r[3][r[4]].includes(t))&&(t=!1),t)},Operators.prototype.$size=function(){var r=arguments,t=!0;return!r[3][r[4]]||(r[3][r[4]].length==r[0]&&(t=!1),t)},Operators.prototype.setValue=function(r,t,e,o){var n=t.split("."),i=n.pop(),s=n.reduce((r,t)=>r[t]=r[t]||{},r);return o?(!s[i]&&(s[i]=0),s[i]+=e,s):(s[i]=e,s)},Operators.prototype.$set=function(r,t,e){!t&&e&&(t={});for(const e in r)this.setValue(t,e,r[e]);return t},Operators.prototype.$inc=function(r,t){if(!t)return{};for(const e in r)this.setValue(t,e,r[e],"inc");return t},Operators.prototype.command=function(){if(arguments[0])return!0},Operators.prototype.errorNumber=function(){if("number"!=typeof arguments[0])throw new _errors.MerlinOperatorsError(`'${arguments[1]}' needs to be a number!`)},Operators.prototype.errorNe=function(){if(arguments[2].null&&arguments[2].$ne){if(-1===arguments[2].null)throw new _errors.MerlinOperatorsError("'null' is not allowed!");if(-1==arguments[2].$ne[typeof arguments[0]])throw new _errors.MerlinOperatorsError(`'${arguments[0]}' is an invalid value!`)}},Operators.prototype.errorArray=function(){if(!Array.isArray(arguments[0]))throw new _errors.MerlinOperatorsError(`'${arguments[1]}' needs to be an array!`)};var _default=exports.default=Operators; },{"./errors.js":2}],7:[function(require,module,exports){ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"ObjectId",{enumerable:!0,get:function(){return _objectId.default}}),exports.default=Query;var _index=_interopRequireDefault(require("./crypthor/index.js")),_errors=require("./errors.js"),_objectId=_interopRequireDefault(require("./objectId.js")),_operators=_interopRequireDefault(require("./operators.js")),_validator=_interopRequireDefault(require("./validator.js"));function _interopRequireDefault(e){return e&&e.__esModule?e:{default:e}}function Query(e,r,t){return this.schema=e,this.merlin=r,this.modelName=t,this.error={},this.index=0,this.controller={},this.entries=Object.entries,this.firstOperators=["$and","$nor","$or","$text","$where"],this}Query.prototype.existsId=function(e,r,t){var n=this;r.id_=(new _objectId.default).toString(),e.get(r.id_).onsuccess=(o=>{o.target.result?n.existsId(e,r,t):t(r)})},Query.prototype.TypeError=function(e,r,t){if(-1==r.indexOf(typeof e))throw new Error(`{{'${t}' method}} must be a '${r.join(",")}'!`)},Query.prototype.insertCollection=async function(e,r,t){var n=!t||!1!==t.ordered,o=[],i=[],s=this,a=s.merlin,u=new Promise(e=>{a.dbApi.open(a.dbName).onsuccess=(r=>{var t=r.target.result;e(t)})});function c(e){return new Promise(async r=>{u.transaction([s.modelName],"readwrite").objectStore(s.modelName).add(e).onsuccess=(t=>{setTimeout(()=>{o.push(e.id_),i.push(e),r()},1)})})}u=await u;for(const r of e)n&&(r.$order=r.$order||Date.now()),r.id_=r.id_||(new _objectId.default).toString(),await c(r);var l={acknowledged:!0};o.length>1&&(l.insertedIds=o,l.data=i),1==o.length&&(l.insertedId=o[0],l.data=e[0]),u.close(),r(l)},Query.prototype.promise=function(e){return new Promise(e)},Query.prototype.cursorFind=function(e,r,t){var n=t.target.result;if(this.hasQueryResult)return e.result=this.hasQueryResult,r(e.result);n?(e.result.push(n.value),n.continue()):(this.hasQueryResult=e.result,r(e.result))},Query.prototype.delaySimulation=function(e,r,t){clearTimeout(n);var n=setTimeout(()=>{e(t||[])},r||2e3)},Query.prototype.prettyPrint=function(e){return JSON.stringify(e,null,2)},Query.prototype.checkQuery=function(e){return new Promise(r=>{for(const n in e.query){var t=e.query[n];if("object"!=typeof t&&t&&-1===n.indexOf(".")&&"function"!=typeof t&&!Array.isArray(t))return r([n,t])}r([!1,!1])})},Query.prototype.getQueries=function(e,r){return new Promise(t=>{var n=this;e.result=[];var o=this.merlin;o.dbApi.open(o.dbName).onsuccess=async function(o){var i=e.maxTimeMS;e.maxTimeMS&&(e.maxTimeMS=setTimeout(()=>{r(`Error: operation exceeded time ${i}ms!`)},e.maxTimeMS));var s=o.target.result;if(!s.objectStoreNames.contains(n.modelName))return t([]),s.close();var a=s.transaction([n.modelName],"readwrite").objectStore(n.modelName);if(e.hint){if(!a.indexNames.contains(e.hint))return r(`There's no '${e.hint}' index using hint!`);a=a.index(e.hint)}var u=a.openCursor(),[c,l]=await n.checkQuery(e);c&&(a.index(c).getAll(l).onsuccess=(r=>{var n=r.target.result;return e.store=a,e.dbResult=s,t(n)}));u.onsuccess=n.cursorFind.bind(n,e,t),e.store=a,e.dbResult=s}})},Query.prototype.sortByCriteria=function(e,r){return e=e||[],"function"==typeof r?e.sort(r):(r=r||(e[0]&&e[0].$order?{$order:1}:{}),r=Object.entries(r),e.sort((e,t)=>{for(const[n,o]of r){if(e[n]t[n])return o}return 0}))},Query.prototype.deleteOne_=function(e,r,t){e.delete(r.id_).onsuccess=(()=>{t("Deleted!")})},Query.prototype.updateOne_=function(e,r,t){e.put(r).onsuccess=(()=>{t("Successfully.")})},Query.prototype.forEachController=function(e,r){var t=this;function n(){return new Promise(r=>{this.save&&delete this.save,this.delete&&delete this.delete,t.updateOne_(e.store,this,r)})}function o(){return new Promise(r=>{this.save&&delete this.save,this.delete&&delete this.delete,t.deleteOne_(e.store,this,r)})}e.result.forEach(r=>{r.save=n,r.delete=o,e.forEach(r)}),r("Using forEach method!")},Query.prototype.returnKeyController=function(e,r){var t=[];return e.result[0].id_||r("There is no key in the query"),e.result.forEach(e=>{t.push({id_:e.id_})}),t},Query.prototype.mapController=function(e){return e.result.map(r=>e.map(r))},Query.prototype.filterMaxValues=function(e){return e.result.filter(r=>Object.keys(e.max).every(t=>r[t]<=e.max[t]))},Query.prototype.filterMinValues=function(e){return e.result.filter(r=>Object.keys(e.min).every(t=>r[t]>=e.min[t]))},Query.prototype.operators=function(e,r,t,n){var o=r[t]||r,i=e;if(-1!==this.firstOperators.indexOf(t))return(new _operators.default)[t](e,o,n,r,t);if(!(e=Object.entries(e)[0]))throw new _errors.MerlinInvalidOptionError(`Invalid option value in '${t}'`);if(o=this.getProperty(r,t),"$exists"===e[0]&&(o=[r,t,i]),!_operators.default.prototype[e[0]])throw new _errors.MerlinInvalidOptionError(`Invalid option '${e[0]}'`);return(new _operators.default)[e[0]](e[1],o,n,r,t)},Query.prototype.getProperty=function(e,r){return r.split(".").reduce(function(e,r){return e?e[r]:void 0},e||self)},Query.prototype.criteria=async function(e,r,t){if(!(r instanceof Object)||Array.isArray(r))throw new Error("Query needs to be an '{}', or 'null'");if(!Object.keys(r).length)return e;for(var n=[],o=0;o{r.onsuccess=(r=>{e(r.target.result.version),r.target.result.close()})})},Query.prototype.dbOpen=function(e){var r=this.merlin,t=r.dbApi.open(r.dbName,e),n=this;return new Promise(r=>{t.onsuccess=(t=>{var o=t.target.result;if(!o.objectStoreNames.contains(n.modelName))return o.close(),n.dbOpen(e);var i=o.transaction([n.modelName],"readwrite"),s=i.objectStore(n.modelName);r([s,o,i])})})},Query.prototype.upgrade=function(e){var r=this.merlin,t=r.dbApi.open(r.dbName,e+1);return new Promise(e=>{t.onupgradeneeded=(r=>{var t=r.target;e(t)})})},Query.prototype.sort=function(e){return this.TypeError(e,["object","function"],"sort"),this.controller[this.index].sort=e,this},Query.prototype.limit=function(e){return this.TypeError(e,["number"],"limit"),this.controller[this.index].limit=e,this},Query.prototype.skip=function(e){return this.TypeError(e,["number"],"skip"),this.controller[this.index].skip=e,this},Query.prototype.forEach=function(e){return this.TypeError(e,["function"],"forEach"),this.controller[this.index].forEach=e,this},Query.prototype.pretty=function(){return this.controller[this.index].pretty=!0,this},Query.prototype.map=function(e){return this.TypeError(e,["function"],"map"),this.controller[this.index].map=e,this},Query.prototype.maxTimeMS=function(e){return this.TypeError(e,["number"],"maxTimeMS"),this.controller[this.index].maxTimeMS=e,this},Query.prototype.hint=function(e){return"object"==typeof e&&(e=Object.keys(e)[0]),this.TypeError(e,["string","object"],"hint"),this.controller[this.index].hint=e||"id_",this},Query.prototype.returnKey=function(){return this.controller[this.index].returnKey=!0,this},Query.prototype.size=function(){return this.controller[this.index].size=!0,this},Query.prototype.max=function(e){return this.TypeError(e,["object"],"max"),this.controller[this.index].max=e,this},Query.prototype.min=function(e){return this.TypeError(e,["object"],"min"),this.controller[this.index].min=e,this},Query.prototype.lilit=function(){return this.controller[this.index].lilit=!0,this},Query.prototype.encrypt=function(e,r){return new Promise(async t=>{var n=new _index.default({hash:e.hash||null,iterations:e.iterations||null,strength:e.strength||null,salt:e.salt||null});r.forEach(async r=>{for(const t of e.fields)r[t]=await n.encrypt(r[t],e.secretKey)}),setTimeout(()=>{t(r)},500*r.length)})},Query.prototype.decrypt=function(e,r){var t=!1,n=null;return new Promise(async(o,i)=>{var s=new _index.default({hash:e.hash||null,iterations:e.iterations||null,strength:e.strength||null,salt:e.salt||null});if(e&&!e.fields)throw new _errors.MerlinError("Define 'fields' option");if(e&&!e.secretKey)throw new _errors.MerlinError("Define 'secretKey' option");r.forEach(r=>{for(const n of e.fields)s.decrypt(r[n],e.secretKey).then(e=>{r[n]=e}).catch(e=>{t=!0,i({[n]:r[n],message:e})})}),clearTimeout(n),n=setTimeout(()=>{if(t)return clearTimeout(n);o(r)},500*r.length)})},Query.prototype.getModel=function(e){return new Promise(r=>{this.merlin.getModel(e).then(e=>{r(!0)}).catch(async t=>{this.merlin.createModel(e,this.schema).then(e=>{r(!0)})})})},Query.prototype.insert=async function(e,r){this.TypeError(e,["object"],"insert"),this.error.insert=[],e=e.length?e:[e];var t=new Promise(async(t,n)=>{var o=await new _validator.default(e,this.schema,this);if("object"!=typeof o)return n(o);await this.getModel(this.modelName),this.insertCollection(e,t,r)});return this.then=t.then.bind(t),this.catch=t.catch.bind(t),this},Query.prototype.insertOne=function(e,r){if("object"!=typeof e||!e||Array.isArray(e))throw new _errors.MerlinError("'data' param needs to be an object!");return e=[e],this.insert(e,r)},Query.prototype.insertMany=function(e,r){if(!e||!Array.isArray(e))throw new _errors.MerlinError("'data' param needs to be an array!");if(0===e.length)throw new _errors.MerlinError("Define an item to insert into the database!");return this.insert(e,r)},Query.prototype.toFilter=async function(e,r,t,n){var o=await this.getQueries.bind(this,e,t)();if(0==o.length)return e.dbResult&&e.dbResult.close(),r("There's no data to recovery");if(clearTimeout(e.maxTimeMS),o=await this.criteria(o,e.query,n),this.sortByCriteria(o,e.sort),e.skip=e.skip||0,e.limit=e.limit||0,e.lilit&&(o="I am your mother and I will control you and your soul!! haha"),e.min&&(o=this.filterMinValues(e)),e.max&&(o=this.filterMaxValues(e)),e.result=o.slice(e.skip),e.result=o.slice(e.skip,e.limit?e.skip+e.limit:void 0),e.forEach)return e.dbResult.close(),this.forEachController(e,r);if(e.map)return e.dbResult.close(),this.mapController(e);e.returnKey&&(e.result=this.returnKeyController(e,t)),e.size&&(e.result=e.result.length),e.pretty&&(e.result=prettyPrint(e.result)),e.dbResult.close();var i=JSON.stringify(e.result);return JSON.parse(i)},Query.prototype.balance=function(e,r,t){e=e||{},this.index++,this.controller[this.index]={},this.controller[this.index].query=e;var n=new Promise((e,n)=>{t(this.toFilter.bind(this,this.controller[this.index],e,n,r)(),e,n)});return this.then=n.then.bind(n),this.catch=n.catch.bind(n),this},Query.prototype.find=function(e,r){var t=this;return this.balance(e,r,async function(e,n,o){if(r&&r.decrypt)return e=await e,t.decrypt(r.decrypt,e).then(e=>{n(e)}).catch(e=>{o(e)});n(e)})},Query.prototype.findOne=function(e,r){var t=this;if(Array.isArray(e)||"object"!=typeof e||!find)throw new _errors.MerlinError("'filter' param needs to be an 'object' type");return this.balance(e,r,async function(e,n,o){if(e=(e=await e)||[],r&&r.decrypt)return e=await e,t.decrypt(r.decrypt,e).then(e=>{n(e[0])}).catch(e=>{o(e)});n(e[0])})},Query.prototype.findMany=function(e,r){var t=this;if(Array.isArray(e)||"object"!=typeof e||!find)throw new _errors.MerlinError("'filter' param needs to be an 'object' type");return this.balance(e,r,async function(e,n){if(e=(e=await e)||[],r&&r.decrypt)return e=await e,n(e=await t.decrypt(r.decrypt,e));n(e)})},Query.prototype.findOneAndDelete=function(e,r){var t=this;if(!e||"object"!=typeof e||Array.isArray(e))throw new _errors.MerlinError("'filter' param needs to be an object {}");return this.balance(e,r,async function(e,r){if(!(e=(e=await e)[0]||void 0))return r({acknowledged:!0,deletedCount:0});var n=JSON.stringify(e),[o,i]=await t.dbOpen();o.delete(e.id_).onsuccess=(()=>{r(JSON.parse(n))}),i.close()})},Query.prototype.findOneAndReplace=function(e,r,t){var n=this;if(!e||"object"!=typeof e||Array.isArray(e))throw new _errors.MerlinError("'filter' param needs to be an object {}");if(!r||"object"!=typeof r||Array.isArray(r))throw new _errors.MerlinError("'replace' param needs to be an object {}");return this.balance(e,t,async function(e,o){if(!(e=(e=await e)[0]||void 0)&&t&&!t.upsert||!e&&!t)return o({acknowledged:!0,replacedCount:0});var i={},s=e||void 0;if(s=JSON.stringify(s||{acknowledged:!1,noData:!0}),i.id_=e.id_,i.$order=e.$order||null,t&&t.upsert&&!e){var a=(new _objectId.default).toString();i.id_=a}var[u,c]=await n.dbOpen();for(const e in r)i[e]=r[e];u.put(i).onsuccess=(()=>{i=i,t&&"before"==t.returnDocument&&(i=JSON.parse(s)),o(i)}),c.close()})},Query.prototype.findOneAndUpdate=function(e,r,t){var n=this;if(!e||"object"!=typeof e||Array.isArray(e))throw new _errors.MerlinError("'filter' param needs to be an object {}");if(!r||"object"!=typeof r||Array.isArray(r))throw new _errors.MerlinError("'update' param needs to be an object {}");return this.balance(e,t,async function(e,o){if(!(e=(e=(e=await e)||[])[0]||void 0)&&t&&!t.upsert||!e&&!t)return o({acknowledged:!0,replacedCount:0});if(t&&t.upsert&&!e){var i=(new _objectId.default).toString();(e={}).id_=i}var s=JSON.stringify(e),[a,u]=await n.dbOpen();for(const t in r){if(!_operators.default.prototype[t])throw new _errors.MerlinError(`There is no '$${t}' in update method, try ($set, $inc)!`);(new _operators.default)[t](r[t],e)}a.put(e).onsuccess=(()=>{t&&t.new?o(e):o(JSON.parse(s))}),u.close()})},Query.prototype.unavailable=function(e){return new Promise((r,t)=>{t(`Sorry, the '${e}' method will be available in the next versions!`)})},Query.prototype.aggregate=function(){return this.unavailable("aggregate")},Query.prototype.bulkWrite=function(e){return this.unavailable("bulkWrite")},Query.prototype.creatingIndex=async function(){var e=arguments,r=this,t=this.merlin,n=e[0],o="",i=e[1],s="prev",a=await this.version.call(this),u=t.dbApi.open(t.dbName,a+1);i.name||n.forEach(e=>{o+=e+"_"}),o=e[1].name||o.slice(0,-1),1!==i.direction&&i.direction||(s="next"),u.onupgradeneeded=function(t){var a=t.target.transaction.objectStore(r.modelName);if(a.indexNames.contains(o))return e[3](`Index '${o}' already exists in your model!`);a.createIndex(o,n,{unique:i.unique,locale:i.locale||void 0,direction:s})},u.onsuccess=function(r){e[4]===e[5]&&e[2](`'${e[5]+1}' indexes created successfully`),e[4]||e[2](`index ${o} created!`),r.target.result.close()}},Query.prototype.createIndex=function(e,r){return new Promise(this.creatingIndex.bind(this,e,r))},Query.prototype.createIndexes=function(e,r){if(!Array.isArray(e))throw new _errors.MerlinError("'keyPatterns' param needs to be an Array!");var t=e.length-1;return new Promise((n,o)=>{e.forEach((e,i)=>{this.creatingIndex(e,r,n,o,t,i)})})},Query.prototype.$where=async function(){if(arguments.length<=1){this.index++,this.controller[this.index]={};var e=await this.getQueries.bind(this,this.controller)(),r=[];e.forEach(e=>{(new _operators.default).$where(arguments,arguments[1]=e)||r.push(e)});var t=new Promise(e=>{e(r)});return this.catch=t.catch.bind(t),this.then=t.then.bind(t),this}return(new _operators.default).$where(arguments)},Query.prototype.formatDataSize=function(e,r){r.format=r.format.toLowerCase();var t={kb:1,mb:2,gb:3}[r.format],n={kb:" kB",mb:" MB",gb:" GB"}[r.format],o={kb:2,mb:2,gb:6}[r.format];return t=(e/1024**t).toFixed(o),t=Number(t),r.string&&(t=t.toLocaleString(r.locale||"en-US",{minimumFractionDigits:2,maximumFractionDigits:2})),[t,r.string?n:null]},Query.prototype.dataSize=function(e){var r=this,t=this.merlin;return new Promise(n=>{t.dbApi.open(t.dbName).onsuccess=function(t){var o=t.target.result.transaction([r.modelName],"readonly").objectStore(r.modelName).getAll(),i=0;o.onsuccess=(t=>{t.target.result.forEach(e=>{i+=JSON.stringify(e).length});var o=[i,e&&e.string?" bytes":null];e&&e.format&&(o=r.formatDataSize(i,e)),n(o[0]+o[1])})}})},Query.prototype.estimatedDocumentCount=function(){return new Promise(async(e,r)=>{var[t,n]=await this.dbOpen();n.transaction([this.modelName],"readonly").objectStore(this.modelName).count().onsuccess=(r=>{e(r.target.result)}),n.close()})},Query.prototype.countDocuments=function(e,r){if(!(e instanceof Object))throw new _errors.MerlinError("Invalid 'filter' type, define an object");return this.balance(e,r,async function(e,r){r((e=(e=await e)||[]).length)})},Query.prototype.deleteOne=function(e,r){if(!(e instanceof Object))throw new _errors.MerlinError("Invalid 'filter' type, define an object");var t=this;return this.balance(e,r,async function(e,r){e=(e=(e=await e)||[])[0]||void 0;var n=JSON.stringify(e);if(e&&0!==e.length){var[o,i]=await t.dbOpen();o.delete(e.id_).onsuccess=(()=>{r({acknowledged:!0,deletedCount:1,data:JSON.parse(n)})}),i.close()}else r({acknowledged:!0,deletedCount:0})})},Query.prototype.deleteMany=function(e,r){if(!(e instanceof Object))throw new _errors.MerlinError("Invalid 'filter' type, define an object");var t=this;return this.balance(e,r,async function(e,r){if((e=(e=(e=await e)||[])||void 0)&&0!==e.length){var[n,o]=await t.dbOpen(),i=0;e.forEach(e=>{n.delete(e.id_),i++}),r({acknowledged:!0,deletedCount:i}),o.close()}else r({acknowledged:!0,deletedCount:0})})},Query.prototype.distinct=function(e,r){if("string"!=typeof e)throw new _errors.MerlinError("Invalid 'filter' type, define an string");e=e.split(".");var t=[];return this.balance({},r,async function(r,n){(r=(r=(r=await r)||[])||void 0).forEach(r=>{-1==t.indexOf(r[e[0]])&&t.push(r[e[0]])}),n(t)})},Query.prototype.dropIndex=function(e){return new Promise(async(r,t)=>{var n=await this.version(),o=await this.upgrade(n,!0),i=o.transaction.objectStore(this.modelName);if(!i.indexNames.contains(e))return t(`There's no index '${e}' in your '${this.modelName}'`);i.deleteIndex(e),r({msg:`index '${e}' dropped for collection!`,ok:1}),o.result.close()})},Query.prototype.dropIndexes=function(e){var r=this;if(!Array.isArray(e))throw new _errors.MerlinError("'indexesName' needs to be an array!");return new Promise(async(t,n)=>{var o=await this.version(),i=await this.upgrade(o,!0),s=i.transaction.objectStore(this.modelName),a=[];for(const t of e){if(!s.indexNames.contains(t))return n(`There's no index '${t}' in your '${r.modelName}'`);a.push(t),s.deleteIndex(t)}t({droppedIndexes:a,msg:"indexes dropped for collection",ok:1}),i.result.close()})},Query.prototype.drop=function(){return new Promise(async(e,r)=>{var t=await this.version(),n=await this.upgrade(t);if(!(n=n.result).objectStoreNames.contains(this.modelName))return n.close(),e({status:400,message:`There's no ${this.modelName} model!`});n.deleteObjectStore(this.modelName),e({status:200,message:`'${this.modelName}' model deleted!`}),n.close()})},Query.prototype.modifyFields=function(e,r){var t={};return e&&(r=this.entries(r)).forEach(n=>{for(const o in e)n[0]===o&&1===e[o]&&(t[o]=n[1]),n[0]===o&&-1===e[o]&&delete(t=r)[n[0]]}),t},Query.prototype.findAndModify=function(e){if(!(e instanceof Object))throw new _errors.MerlinError("Invalid 'options' type, define an object");if(!e.query)throw new _errors.MerlinError("Define an 'query' property in your option!");var r=this;return this.balance(e.query,e,async function(t,n){t=(t=(t=await t)||[])[0]||void 0;var o=JSON.stringify(t),i={};if(!t&&e.remove)return n({});var[s,a]=await r.dbOpen();if(e.remove)return i=r.modifyFields(e.fields,t),s.delete(t.id_).onsuccess=(()=>{n(i)}),void a.close();if(!e.update)throw a.close(),new _errors.MerlinError("You need define an 'update' or 'remove' option");var u=r.entries(e.update)[0];if(!_operators.default.prototype[u[0]])throw a.close(),new _errors.MerlinError(`Invalid '${u[0]}' property!`);t=(new _operators.default)[u[0]](u[1],t,e&&e.upsert),i=r.modifyFields(e.fields,t),t.id_||(t.id_=(new _objectId.default).toString(),s.add(t)),s.put(t).onsuccess=(()=>{var t=null;e.new?t=i:(t=JSON.parse(o),t=r.modifyFields(e.fields,t)),n(t)}),a.close()})},Query.prototype.getIndexes=function(){return new Promise(async(e,r)=>{var[t,n]=await this.dbOpen(),o=[];if(0===t.indexNames.length)return n.close(),e({indexesCount:0});this.entries(t.indexNames).forEach(e=>{o[e[0]]={v_:e[0],status:"active",name:e[1]}}),e(o),n.close()})},Query.prototype.updateOne=function(e,r,t){return this.findOneAndUpdate(e,r,t)},Query.prototype.updateMany=function(e,r,t){var n=this;if(!e||"object"!=typeof e||Array.isArray(e))throw new _errors.MerlinError("'filter' param needs to be an object {}");if(!r||"object"!=typeof r||Array.isArray(r))throw new _errors.MerlinError("'update' param needs to be an object {}");return this.balance(e,t,async function(e,o){if(!(e=(e=(e=await e)||[])||void 0)&&t&&!t.upsert||!e&&!t)return o({acknowledged:!0,replacedCount:0});if(t&&t.upsert&&!e){var i=(new _objectId.default).toString();(e={}).id_=i}var s=JSON.stringify(e),[a,u]=await n.dbOpen();e.forEach(e=>{for(const o in r){if(!_operators.default.prototype[o])throw new _errors.MerlinError(`There is no '$${o}' in update method, try ($set, $inc)!`);var n=(new _operators.default)[o](r[o],e,t&&t.upsert);a.put(n)}}),a.transaction.oncomplete=function(){t&&t.new?o(e):o(JSON.parse(s))},u.close()})},Query.prototype.byId=function(e){return new Promise(async(r,t)=>{if("string"!=typeof e&&"number"!=typeof e)throw new _errors.MerlinError("'id' property needs to be an (number or string);");var[n,o]=await this.dbOpen();n.index("id_").get(e).onsuccess=(e=>{var t=e.target.result;if(!t)return r({});r(t)}),o.close()})},Query.prototype.findById=async function(e,r){var t=await this.byId(e),n={};if(!r||!r.fields)return t;if(r.fields&&!Object.keys(r.fields).length)throw new _errors.MerlinError("Define an 'fields' or remove in options param!");for(const e in t)r&&1===r.fields[e]&&(n[e]=t[e]),r&&-1===r.fields[e]&&(delete t[e],n=t);return n},Query.prototype.findByIdAndDelete=function(e){return new Promise(async r=>{var t=await this.byId(e),n=JSON.stringify(t);if(!Object.keys(t).length)return r({acknowledged:!0,deletedCount:0});var[o,i]=await this.dbOpen();o.delete(t.id_).onsuccess=(()=>{r({acknowledged:!0,deletedCount:1,data:JSON.parse(n)})}),i.close()})},Query.prototype.findByIdAndUpdate=function(e,r,t){return new Promise(async n=>{var o=await this.byId(e);if(!Object.keys(o).length)return n({acknowledged:!0,updatedCount:0});var[i,s]=await this.dbOpen(),a=JSON.stringify(o);for(const e in r)(new _operators.default)[e](r[e],o);i.put(o).onsuccess=(()=>{t&&t.new||(o=JSON.parse(a)),n(o)}),s.close()})}; },{"./crypthor/index.js":1,"./errors.js":2,"./objectId.js":5,"./operators.js":6,"./validator.js":9}],8:[function(require,module,exports){ "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var _default=exports.default={email:/^[a-zA-Z0-9!#$%&*_=.+}/?'{~|~-]{2,}(?{e(this.validateSchema())})}Validator.prototype.validateSchema=async function(){for(var e of this.data){for(var t in this.schema){var i=this.schema[t],a=e[t],r=await this.validateField(a,i,t,e);if(r)return r}delete e.$message;var n=Object.keys(e).find(e=>!(e in this.schema));if(n)return`${n} is not a valid property!`}return this.data},Validator.prototype.validateField=async function(e,t,i,a){if("function"==typeof t.required&&t.required.call(a))return r=a.$message||`Invalid ${i}!`;if(t.required&&[void 0,null].includes(e))return r=this.convertMsg(t.min[1],e)||`${i} is required!`;var r,n=!!e||""===e;if(t.type=t.type||t,t.type&&n){r=void 0,"string"==typeof t.type[1]&&(r=t.type[1],t.type=t.type[0]);var s=t.type.toString(),o=-1===(s=(s=s.match(/(Date|Function|String|Boolean|Number|Array|Object)/g,"")).join(", ").toLowerCase()).indexOf(typeof e);if(r=r||`Type of ${i} needs to be an ${s}!`,-1!==s.indexOf("date")&&!this.isDate(e))return r;if(-1!==s.indexOf("array")&&!Array.isArray(e)&&o)return r;if(o&&-1===s.indexOf("date")&&-1===s.indexOf("array"))return r}if(t.validateEmail){var u=t.validateEmail,l=u[2]||_regex.default.email;if(l=new RegExp(l),"string"!=typeof e||!l.test(e))return u[1]||"invalid email"}if(t.encrypt){var d=new _index.default(t.encrypt);d=await d.encrypt(e[0],e[1]),a[i]=d}if(t.min&&(v=t.min[0]||t.min)>e)return this.convertMsg(t.min[1],e)||`The min allowed for ${i} is ${v}!`;if(t.max&&(m=t.max[0]||t.max)m)return this.convertMsg(f[1],e)||`The value ${e} has a lot of characters; it's quite long.`}if(t.minList&&e.length<(t.minList[0]||t.minList))return t.maxList[1]||`You need at least ${t.minList} ${i}!`;if(t.maxList&&e.length>(t.maxList[0]||t.maxList))return t.maxList[1]||`Maximum ${t.maxList} ${i} are allowed!`;if(t.maxLength){var c=t.minLength,v=c[0]|c;if(e.length{r.onsuccess=(r=>{var n=r.target.result;if(!n.objectStoreNames.contains(i.modelName))return n.close(),a(!1);n.transaction([i.modelName],"readonly").objectStore(i.modelName).index(t).get(e).onsuccess=(e=>{if(e.target.result)return a(!0);a(!1)}),n.close()})})};var _default=exports.default=Validator; },{"./crypthor/index.js":1,"./regex.js":8}]},{},[3]);