gs-idb-pro 0.1.0 → 0.1.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/README.md +3 -0
- package/lib/index.cjs +1 -1
- package/lib/index.js +1 -1
- package/lib/index.web.js +1 -1
- package/package.json +10 -2
package/README.md
CHANGED
package/lib/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("gs-base"),t=require("gs-idb-basic");const r=Symbol("save"),a=Symbol("delete"),n=Object.freeze({key:({primaryKey:e})=>({value:e}),value:({value:e})=>({value:e}),keyValue:({primaryKey:e,value:t})=>({value:[e,t]})});function s(e){if(Array.isArray(e))return{key:e[1],value:e[0]};if("value"in e){const{key:t,value:r}=e;return{key:t,value:r}}throw new Error(`not include value in invalid DBRecord:${JSON.stringify(e)}`)}const i=Symbol("break"),o=Symbol("finished"),c=Symbol("continue"),u=Symbol("continue key"),d=Symbol("next key"),h=Symbol("continue primary key"),l=Symbol("next primary key");function m(e){return e instanceof IDBObjectStore||e instanceof IDBIndex}const f=Object.freeze({keyPath:"id",autoIncrement:!0,addedTimeField:!0,updatedTimeField:!0}),y=Object.freeze({addedTimeField:"added_at",softDeletedField:"deleted",updatedCountField:"updated_count",updatedTimeField:"updated_at"}),p=e=>e instanceof Date?e.getTime():e;function g(e){if(t.isDbQueryOrNull(e))return e;const r=e;if("lt"in r&&"gt"in r){if(p(r.gt)>p(r.lt))throw new Error(`Invalid IDBRange: gt (${r.gt}) cannot be greater than lt (${r.lt})`);return IDBKeyRange.bound(r.gt,r.lt,!0,!0)}if("lt"in r&&"gte"in r){if(p(r.gte)>p(r.lt))throw new Error(`Invalid IDBRange: gte (${r.gte}) cannot be greater than lt (${r.lt})`);return IDBKeyRange.bound(r.gte,r.lt,!1,!0)}if("lte"in r&&"gt"in r){if(p(r.gt)>p(r.lte))throw new Error(`Invalid IDBRange: gt (${r.gt}) cannot be greater than lte (${r.lte})`);return IDBKeyRange.bound(r.gt,r.lte,!0,!1)}if("lte"in r&&"gte"in r){if(p(r.gte)>p(r.lte))throw new Error(`Invalid IDBRange: gte (${r.gte}) cannot be greater than lte (${r.lte})`);return IDBKeyRange.bound(r.gte,r.lte,!1,!1)}return"lt"in r?IDBKeyRange.upperBound(r.lt,!0):"lte"in r?IDBKeyRange.upperBound(r.lte,!1):"gt"in r?IDBKeyRange.lowerBound(r.gt,!0):"gte"in r?IDBKeyRange.lowerBound(r.gte,!1):void 0}function b(e){return null!=g(e)}async function S(e,r,a){const{query:n,direction:s="prev",preSkip:i,startKey:o,startPrimaryKey:c}=r,u=e.openCursor(g(n),s);return i&&(await t.requestDbResult(u)).advance(i),o&&(c?(await t.requestDbResult(u)).continuePrimaryKey(o,c):(await t.requestDbResult(u)).continue(o)),u}function w(t,r,a){return Array.isArray(t)?r=>e.copyFields({},r,t):e.isFunction(t)?t:r?e=>e:a?(e,t)=>[e,t]:(e,t)=>({key:e,value:t})}class x{idbPro;target;#e;constructor(e,t){this.idbPro=t,this.#e=e.storeSchema,this.target=e.target,m(e.target)&&(this.tx=this.#t)}get storeName(){return this.nativeStore?.name||this.target.store}get storeSchema(){if(this.#e)return this.#e;const e=this.idbPro.getStoreSchema(this.storeName);return Object.isFrozen(e)&&(this.#e=e),e}get factory(){return this.idbPro.factory}get nativeStore(){const{target:e}=this;return e instanceof IDBObjectStore?e:e instanceof IDBIndex?e.objectStore:void 0}get keyPath(){const{target:e}=this;if(m(e))return e.keyPath;const{storeSchema:t}=this,{index:r}=e;return r?t.indexSchemas.find(e=>e.name===r)?.keyPath:t.keyPath}async forEach(t,r){return t=e.isFunction(t)?{fn:t}:t,r?this.cursorResult(t,!1):this.cursorVoid(t,!1)}async tx(e,t,r){let{target:a}=this;const{store:n,index:s}=a,i=await this.idbPro.openNativeDb();let o,c;try{o=i.transaction(n,!0===e?"readwrite":"readonly"),a=c=o.objectStore(n),s&&(a=a.index(s))}catch(e){throw i.close(),e}if(!t)return Object.freeze({db:i,tx:o,nativeStore:c,target:a});try{if(!0===e){const e=await t(a,c);return o.commit(),e}return t(a)}catch(e){throw!1!==r&&o.abort(),e}finally{i.close()}}openCursor(e,t){return this.tx(t,t=>new Promise(async(r,a)=>{const{fn:n}=e,s=await S(t,e);s.onsuccess=async()=>{s.result?!1===await n(s.result)&&r():r()},s.onerror=()=>a(s.error)}))}cursorVoid({query:t,direction:n,preSkip:s,startKey:o,startPrimaryKey:c,fn:d},l){let m=0;return this.openCursor({query:t,direction:n,preSkip:s,startKey:o,startPrimaryKey:c,fn:async t=>{const{value:n,primaryKey:s}=t,o=await d(n,s,m++),{control:c,key:f,primaryKey:y,modify:p,value:g}=e.isObject(o)?o:{control:o};switch(l&&(p===r?t.update(g||n):p===a&&t.delete()),c){case i:return!1;case u:t.continue(f);break;case h:t.continuePrimaryKey(f,y);break;default:t.continue()}}},!0)}async cursorResult({query:e,direction:t,preSkip:n,startKey:s,startPrimaryKey:c,fn:m,mapper:f},y){const{keyPath:p,defaultGetMapper:g}=this.storeSchema,b=w(f||g,p),S=[];let x=0;return await this.openCursor({query:e,direction:t,preSkip:n,startKey:s,startPrimaryKey:c,fn:async e=>{const{value:t,primaryKey:n}=e,{control:s,value:c,key:f,primaryKey:p,modify:g}=await(m?.(t,n,x,S))||{};switch(y&&(g===r?e.update(c||t):g===a&&e.delete()),(!s||s===o||s===d||s===l)&&S.push(b(c||t,p||n,x)),s){case i:case o:return!1;case d:case u:e.continue(f);break;case l:case h:e.continuePrimaryKey(f,p);break;default:e.continue()}x++}},y),S}#t(e,t){const{target:r}=this,a=r instanceof IDBObjectStore?r:r.objectStore;return t?t(r,a):Object.freeze({nativeStore:a,target:r})}}class D{idbPro;schemas;#r;constructor(e,t){this.idbPro=e,this.schemas=t}get storeNames(){return this.#r||(this.#r=Array.from(new Set(this.schemas.map(e=>e.target.store))))}read(e){return this.tx("newReader",e)}write(e,t=!0){return this.tx("newWriter",e,!0,t)}export(){return this.tx("newReader",async(...e)=>{const t={};for(const r of e)t[r.storeName]=await r.export();return t})}import(e,t,r){return r||(r="addOrChangeMany"),this.tx("newWriter",async(...a)=>{const n={};a=Array.from(new Map(a.map(e=>[e.storeName,e.asStore(!0)])).values());for(const s of a){const{storeName:a}=s,i=e[a];i&&(n[a]=await s[r](i,t))}if(t)return n},!0)}async tx(e,t,r,a){const{idbPro:n,schemas:s}=this,{factory:i}=n.schema,o=await n.openNativeDb();try{const c=o.transaction(this.storeNames,r?"readwrite":"readonly");try{const a=s.map(({storeSchema:t,target:r})=>{let a=c.objectStore(r.store);return r.index&&(a=a.index(r.index)),i[e]({storeSchema:t,target:a},n)});if(r){const e=await t(...a);return c.commit(),e}return await t(...a)}catch(e){throw!1!==a&&c.abort(),e}}finally{o.close()}}}class v extends x{direction;query;writable;parser;endsWithNull;preSkip;startKey;startPrimaryKey;constructor(t,r,a){if(super(t,r),!a)return;const{parser:s}=a;this.direction=a.direction,this.query=a.query,this.writable=!!a.writable,this.endsWithNull=!!a.endsWithNull,this.preSkip=a.preSkip,this.startKey=a.startKey,this.startPrimaryKey=a.startPrimaryKey,s&&(this.parser=e.isFunction(s)?s:n[s])}async*[Symbol.asyncIterator](){const{parser:e,writable:r,endsWithNull:a}=this,{db:n,tx:s,target:o}=await this.tx(r);try{const n=await S(o,this);let c;if(e)for(;c=await t.requestDbResult(n);){const{control:t,value:r}=await e(c);if(t||(yield r),t===i)break;c.continue()}else{let e=!1;const r=()=>{e=!0};for(;!e&&(c=await t.requestDbResult(n));)yield{cursor:c,end:r}}r&&s?.commit(),a&&!c&&(yield null)}finally{n?.close()}}}function k(t,r,a,n){const s=e.isObject(t)?t:{};return e.isFunction(t)?s.fn=t:b(t)&&(s.query=t),e.isFunction(r)?s.fn=r:r&&(s.direction=r),a&&(s.direction=a),n?s.limit=n:s.limit||(s.limit=1e3),s.maxEmptyChecks||(s.maxEmptyChecks=2e4),s}async function P(t,r,a){r.size||(r.size=100),r.nextSkip||(r.nextSkip=0);const{query:n,direction:s,total:i,maxEmptyChecks:o,fn:c}=r;return await t.batchRead(async t=>(i||(r.total=await t.count({query:n,direction:s,maxEmptyChecks:o,fn:c}),r.pages=Math.ceil(r.total/r.size)),r.total<1?{info:e.deepFreeze(r),rows:[]}:c?await async function(e,t,r){t.maxEmptyChecks||(t.maxEmptyChecks=2e4);const{page:a,query:n,direction:s,nextSkip:i}=t,{keyPath:o}=e.storeSchema;return 1===a?await q(e,await S(e.target,{query:n,direction:s}),t,o):r&&i&&a-r.page===1?await q(e,await S(e.target,{query:n,direction:s,preSkip:i}),t,o):await q(e,await S(e.target,{query:n,direction:s}),t,o,!0)}(t,r,a):await async function(t,r){const{keyPath:a}=t.storeSchema,{page:n,query:s,direction:i,size:o,mapper:c}=r,u=(n-1)*o,d=await t.filter({query:s,preSkip:u,direction:i,limit:o,mapper:w(c,a,!0)});return r.nextSkip=u+d.length,{info:e.deepFreeze(r),rows:d}}(t,r)))}async function q({storeSchema:{defaultGetMapper:t}},r,a,n,s){const{page:i,size:o,total:c,maxEmptyChecks:u,fn:d}=a,h=w(a.mapper||t,n,!0),l=[],m=(i-1)*a.size;if(m>=c)return{info:e.deepFreeze(a),rows:[]};let f=0;return await new Promise(async(e,t)=>{let a=0,n=0;const i=async()=>{const{result:t}=r;if(!t)return e();let{value:n,primaryKey:s}=t;if(await d(n,s,f)?(a=0,l.push(h(n,s,f))):a++,l.length>=o||a>=u)return e();f++,t.continue()};r.onerror=()=>t(r.error),r.onsuccess=s?async()=>{const{result:t}=r;if(!t)return e();let{value:s,primaryKey:o}=t;if(await d(s,o,f)?(a=0,n++):a++,n>=m||a>=u)return f=a=0,r.onsuccess=i,void t.continue();t.continue(),f++}:i}),f&&(a.nextSkip+=f+1),{info:e.deepFreeze(a),rows:l}}class O extends x{all(r,a){const n={};return e.isNumber(a)&&(n.limit=a),b(r)?n.query=r:e.isObject(r)&&Object.assign(n,r),this.tx(!1,e=>t.requestDbResult(e.getAll(g(n.query),n.limit||1e3)))}async count(e,r,a){const n=k(e,r,a),{query:s,direction:i,fn:o}=n;if(!o)return await this.tx(!1,e=>t.requestDbResult(e.count(g(s))));const{maxEmptyChecks:c}=n,u=o;let d=0,h=0,l=0;return await this.openCursor({query:s,direction:i,fn:e=>{if(u(e.value,e.primaryKey,l++))d++,h=0;else if(++h>=c)return!1;e.continue()}}),d}get(e){return this.tx(!1,r=>t.requestDbResult(r.get(g(e))))}getMany(t,r){return this.batchRead(async a=>{const n=await e.asyncMap(t,e=>a.get(e));return r?n.filter(e=>e):n})}getRange(e,t){return this.forEach({query:e,direction:t},!0)}async getRangeMany(t,r,a){return(await this.batchRead(a=>e.asyncMap(t,e=>a.getRange(e,r)))).flat()}index(e,t){let{target:r}=this;return r instanceof IDBIndex&&(r=r.objectStore),r instanceof IDBObjectStore?(r=r.index(e),this.createOperator(r,t)):this.idbPro.store(r.store,e)}asStore(e){let{target:t}=this;if(t instanceof IDBObjectStore)return this;if(t instanceof IDBIndex)t=t.objectStore;else{if(!("index"in t))return this;t={store:t.store}}return this.createOperator(t,e)}batchRead(e){return m(this.target)?e(this):this.tx(!1,t=>e(this.idbPro.schema.factory.newReader({storeSchema:this.storeSchema,target:t},this.idbPro)))}iterator(t,r){const a={};return e.isString(r)&&(a.direction=r),b(t)?a.query=t:e.isObject(t)&&Object.assign(a,t),new v({storeSchema:this.storeSchema,target:this.target},this.idbPro,{...a,parser:"value"})}async filter(e,t,r,a){const n=k(e,t,r,a),{maxEmptyChecks:s,limit:u,fn:d}=n,{keyPath:h,defaultGetMapper:l}=this.storeSchema,m=w(n.mapper||l,h,!0);if(!d)return await this.forEach({...n,mapper:m,fn:(e,t,r)=>{if(r>=u-1)return{control:o}}},!0);let f=0;return this.forEach({...n,mapper:m,fn:(e,t,r,a)=>(e=m(e,t,r),d(e,t,r)?(f=0,a.length>=u-1?{control:o}:void 0):++f>=s?{control:i}:{control:c})},!0)}async find(e,t,r){const[a]=await this.filter(e,t,r,1);return a}async page(e,t){const r={...e};return r.page=t||e?.page||1,P(this,r,e)}nextPage(e){return this.page(e,e.page+1)}export(e,t){const r=k(e,t),{keyPath:a,exportMapper:n,name:s,defaultGetMapper:i}=this.storeSchema;if(!a&&Array.isArray(n))throw new Error(`When store [ ${s} ] keyPath does not exist, exportMapper does not support string[].`);return r.direction="next",r.mapper=w(n||i,a,!0),r.limit=r.maxEmptyChecks=Number.MAX_SAFE_INTEGER,this.filter(r)}asMap(){let{target:e}=this;return e instanceof IDBIndex?e=e.objectStore:e instanceof IDBObjectStore||(e={store:e.store}),this.factory.newDbMap({target:e},this.idbPro)}createOperator(e,t){const{idbPro:r}=this,a=this.storeSchema,n={storeSchema:Object.isFrozen(a)?a:void 0,target:e};return t?this.factory.newWriter(n,r):this.factory.newReader(n,r)}}function I(e,t){if(!Array.isArray(e))return{[e]:t};const r={},a=e;for(let e=0;e<a.length;e++)r[a[e]]=t[e];return r}function R(e,t){if(!Array.isArray(e))return t[e];const r=[];for(const a of e){if(!t[a])return;r.push(t[a])}return r}function F(t,r){if(!r||!(r instanceof Object)||Array.isArray(r))return r;const{addedTimeField:a,updatedTimeField:n,updatedCountField:s,softDeletedField:i}=t;return r={...r},a?.name&&!e.isNumber(r[a.name])&&(r[a.name]=Date.now()),n?.name&&!e.isNumber(r[n.name])&&(r[n.name]=Date.now()),i?.name&&!e.isNumber(r[i.name])&&(r[i.name]=0),s?.name&&(r[s.name]=0),r}function M(e,t,r){if(!t||!(t instanceof Object)||Array.isArray(t))return t;const{updatedTimeField:a,updatedCountField:n}=e;return t={...r,...t},a.name&&(t[a.name]=Date.now()),n.name&&(t[n.name]=(t[n.name]||0)+1),t}class E extends O{add(e){return this.changeByPk({record:e,fn:async(e,r,a,n,s)=>{const{storeSchema:i}=this;return a=F(i,a),s?[{...a,...I(s,await t.requestDbResult(e.add(a)))},r]:[a,await t.requestDbResult(e.add(a,r))]}})}addMany(t,r){return this.batchWrite(a=>r?e.asyncMap(t,e=>a.add(e)):e.asyncForEach(t,e=>a.add(e)),!0)}addOrSkip(e){return this.batchWrite(async r=>{const{keyPath:a,defaultGetMapper:n}=r.storeSchema,{key:i,value:o}=a?{key:R(a,e),value:e}:s(e);if(i){const e=await t.requestDbResult(r.nativeStore.get(i));if(e)return w(n,a)?.(e,i)}if(r.target instanceof IDBIndex){const{keyPath:t}=r,a=R(t,o);if(!a)return r.add(e);let n=await r.find(a);if(n)return n}return r.add(e)})}addOrSkipMany(t,r){return this.batchWrite(a=>r?e.asyncMap(t,e=>a.addOrSkip(e)):e.asyncForEach(t,e=>a.addOrSkip(e)),!0)}replace(e){return this.changeByPk({record:e,getOld:!0,fn:async(e,r,a,n,s)=>{const{storeSchema:i}=this,{updatedTimeField:o,updatedCountField:c,addedTimeField:u}=i;return a=n?M(i,a,{[o.name]:n[o.name],[c.name]:n[c.name],[u.name]:n[u.name]}):F(i,a),s?[{...a,...I(s,await t.requestDbResult(e.put(a)))},r]:[a,await t.requestDbResult(e.put(a,r))]}})}replaceMany(t,r){return this.batchWrite(a=>r?e.asyncMap(t,e=>a.replace(e)):e.asyncForEach(t,e=>a.replace(e)),!0)}change(e,r){return this.changeByPk({record:e,getOld:!0,requiredOld:r,requiredPk:r,fn:async(e,r,a,n,s)=>{const{storeSchema:i}=this;if(n)return a=M(i,a,n),s?[{...a,...I(s,await t.requestDbResult(e.put(a)))},r]:[a,await t.requestDbResult(e.put(a,r))]}})}changeMany(t,r){const{returns:a,throwIfMissing:n}=e.isBoolean(r)?{returns:r}:r||{};return this.batchWrite(r=>a?e.asyncMap(t,e=>r.change(e,n)):e.asyncForEach(t,e=>r.change(e,n)),!0)}addOrChange(e){return this.changeByPk({record:e,getOld:!0,fn:async(e,r,a,n,s)=>{const{storeSchema:i}=this;return n?(a=M(i,a,n),s?[{...a,...I(s,await t.requestDbResult(e.put(a)))},r]:[a,await t.requestDbResult(e.put(a,r))]):(a=F(i,a),s?[{...a,...I(s,await t.requestDbResult(e.add(a)))},r]:[a,await t.requestDbResult(e.add(a,r))])}})}addOrChangeMany(t,r){return this.batchWrite(a=>r?e.asyncMap(t,e=>a.addOrChange(e)):e.asyncForEach(t,e=>a.addOrChange(e)),!0)}delete(e,t){return this.changeByPk({pk:e,getOld:t,fn:(e,r,a,n)=>{if(e.delete(r),t)return[n,r]}})}deleteMany(t,r){return this.batchWrite(a=>r?e.asyncMap(t,e=>a.delete(e,!0)):e.asyncForEach(t,e=>a.delete(e)),!0)}deleteRange(t,n){const{returns:s,physical:i,direction:o}=e.isBoolean(n)?{returns:n}:n||{},{name:c}=this.storeSchema.softDeletedField||{};return this.cursor({query:t,direction:o,fn:e=>i||!c?{modify:a}:(e[c]=1,{modify:r})},s)}deleteRangeMany(t,r){const a=e.isBoolean(r)?{returns:r}:r;return this.batchWrite(r=>a?.returns?e.asyncMap(t,e=>r.deleteRange(e,a)):e.asyncForEach(t,e=>r.deleteRange(e,a)),!0)}changeRange(e,t){let{direction:a="next",query:n,newValue:s}="newValue"in e?e:{newValue:e};if(n||(n=R(this.keyPath,s)),!n)throw new Error(`query is required:${JSON.stringify(e)}`);return this.cursor({query:n,direction:a,fn:e=>e instanceof Object?{modify:r,value:{...e,...s}}:{modify:r,value:s}},t)}changeRangeMany(t,r){return this.batchWrite(a=>r?e.asyncMap(t,e=>a.changeRange(e,r)):e.asyncForEach(t,e=>a.changeRange(e,r)),!0)}cursor(t,r){return(t=e.isFunction(t)?{fn:t}:t||{}).fn?r?this.cursorResult(t,!0):this.cursorVoid(t,!0):new v(this,this.idbPro)}batchWrite(e,t){const{target:r}=this;if(m(r))try{return e(this)}catch(e){throw!1!==t&&(r instanceof IDBIndex?r.objectStore:r).transaction.abort(),e}return this.tx(!0,t=>e(this.idbPro.schema.factory.newWriter({storeSchema:this.storeSchema,target:t},this.idbPro)),t)}changeByPk({pk:e,record:r,fn:a,requiredPk:n,getOld:i,requiredOld:o,saveMapper:c,getMapper:u}){const{storeSchema:d}=this,{keyPath:h,defaultSaveMapper:l,defaultGetMapper:m}=d;return r&&(c||l)&&(r=w(c||l,h)?.(r)),this.batchWrite(async c=>{let d,l=r;if(e)d=g(e);else if(h)d=R(h,r);else{const{key:e,value:t}=s(r);d=e,l=t}if(n&&!d)throw new Error(`key is required: ${JSON.stringify(r)}`);const f=d&&(i||o)?await t.requestDbResult(c.nativeStore.get(d)):void 0;if(o&&!f)throw new Error(`record not found: ${JSON.stringify(r)}`);const y=await a(c.nativeStore,d,l,f,h);if(y)return w(u||m,h)?.(y[0],y[1])})}}class j extends x{get size(){return this.tx(!1,e=>t.requestDbResult(e.count()))}delete(e){return this.tx(!0,async(t,r)=>{r.delete(e)})}batch(e){const{idbPro:t,storeSchema:r,factory:a}=this;return this.tx(!0,async(n,s)=>await e(a.newDbMap({storeSchema:r,target:s},t)))}asStore(e){const{factory:t}=this.idbPro.schema;return e?t.newWriter(this,this.idbPro):t.newReader({target:this.target},this.idbPro)}entries(){return new v({target:this.target},this.idbPro,{parser:"keyValue"})}async get(e,r){return await this.tx(!1,r=>t.requestDbResult(r.get(e)))||r}getMany(e){return this.tx(!1,async r=>{const a=[];for(const n of e)a.push(await t.requestDbResult(r.get(n)));return a})}async has(e){return!!await this.get(e)}keys(){return new v({storeSchema:this.storeSchema,target:this.target},this.idbPro,{parser:"key"})}set(e,r){return this.tx(!0,async(a,n)=>{await t.requestDbResult(n.put(r,e))})}setMany(e){return this.tx(!0,async(t,r)=>{for(const[t,a]of e)r.put(a,t)})}values(){return new v({storeSchema:this.storeSchema,target:this.target},this.idbPro,{parser:"value"})}}function N(e,t){if(e==t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}return!1}const B=({stores:e,schema:t})=>{const r=t.storeSchemas;let a="";for(const t of e){const e=r.find(e=>e.name===t.name);if(e){if(!N(t.keyPath,e.keyPath)){a=`store [ ${t.name} ] keyPath not equal,schema.keyPath:${e.keyPath},store.keyPath:${t.keyPath}[]`;break}if(!t.autoIncrement!=!e.autoIncrement){a=`store [ ${t.name} ] autoIncrement not equal`;break}}}return!a||`The existing database is inconsistent with the definition and cannot be corrected: ${a}`},C=async t=>{let r=B(t);return e.isString(r)||(r=K(t)),r},K=({stores:e,schema:t})=>{const r=t.storeSchemas,a=e.map(e=>e.name);let n="";const s=r.map(e=>e.name).filter(e=>!a.includes(e));if(s.length)n=`store [ ${s.join(",")} ] not exist`;else for(const t of e){const e=r.find(e=>e.name===t.name);if(e&&(n=$(t,Array.from(t.indexNames),e.indexSchemas),n))break}return!n||`The existing database Store index is inconsistent with the definition and requires a database version upgrade to be fixed: ${n}`};function $(e,t,r){if(t.length!==r.length)return`store [ ${e.name} ] index count not equal`;for(const a of t){const t=r.find(e=>e.name===a);if(!t)return`store [ ${e.name} ] index [ ${a} ] not exist`;const n=e.index(a);if(!t.unique!=!n.unique)return`store [ ${e.name} ] index [ ${a} ] unique not equal`;if(!t.multiEntry!=!n.multiEntry)return`store [ ${e.name} ] index [ ${a} ] multiEntry not equal`;if(!N(t.keyPath,n.keyPath))return`store [ ${e.name} ] index [ ${a} ] keyPath not equal`}return""}class A{upgradeContext;storeSchema;nativeStore;#a;constructor(e,t,r){this.upgradeContext=e,this.storeSchema=t,this.nativeStore=r}get writer(){return this.#a||(this.#a=this.upgradeContext.dbSchema.factory?.newWriter({target:this.nativeStore,storeSchema:this.storeSchema}))}add(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.addMany(t,r):Promise.resolve()}addOrChange(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.addOrChangeMany(t,r):Promise.resolve()}async call(e,t){if(this.upgradeContext.versionIn(e))return await t(this.writer,this.upgradeContext)}replace(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.replaceMany(t,r):Promise.resolve()}}const T=Object.freeze({newDataOperators:(e,t)=>new D(t,e),newDbMap:(e,t)=>new j(e,t),newReader:(e,t)=>new O(e,t),newStoreUpgradeable:(e,t,r)=>new A(r,t,e),newWriter:(e,t)=>new E(e,t)});function V(t,r,a,n){const s=function(t,r,a){if(!1===t)return!1;if(e.isString(t))return{name:t};if(e.isObject(t)){const a=t;return e.isBoolean(a.name)&&(a.name=r),t}if(!0===t||a)return{name:r};return!1}(r,a,n);if(!s)return s;const i=s;if(!1!==i.isIndexed){i.isIndexed||(i.isIndexed=!0);const{name:e}=i,r=t.indexSchemas;r.some(t=>t===e||t.name===e)||r.push(e)}return i}function W(t,r){let a=e.isString(t)?{name:t}:t;return r&&(a={...r,...a}),a.indexSchemas||(a.indexSchemas=[]),function(e){Object.isFrozen(e)||(e.addedTimeField=V(e,e.addedTimeField,"added_at",!0),e.updatedTimeField=V(e,e.updatedTimeField,"updated_at",!0),e.updatedCountField=V(e,e.updatedCountField,"updated_count",!1),e.softDeletedField=V(e,e.softDeletedField,"deleted",!1))}(a),Object.isFrozen(a)||(a.indexSchemas=a.indexSchemas.map(z)),function(e){if(!e.keyPath&&e.defaultData?.length)for(const t of e.defaultData)if(!Array.isArray(t)&&!("value"in t))throw new Error(`When \`defaultData\` must contain \`value\` fields or be an array:${JSON.stringify(t)}`)}(a),a}function z(t){const r=e.isString(t)?{name:t}:t;return r.keyPath||(r.keyPath=r.name),r}const _=e=>{const{versionDiffValidate:t,versionSameValidate:r,factory:a}=e;return e.storeSchemas||(e.storeSchemas=[]),e.storeTemplate||(e.storeTemplate={...f}),!t&&!1!==t&&(e.versionDiffValidate=B),!r&&!1!==r&&(e.versionSameValidate=C),a?a!==T&&(e.factory={...T,...a}):e.factory=T,e.storeSchemas=e.storeSchemas.map(t=>W(t,e.storeTemplate)),e};function U(e,t){(function(e,t){return e.unique===t.unique&&e.multiEntry===t.multiEntry&&N(t.keyPath,e.keyPath)})(e.index(t.name),t)||(e.deleteIndex(t.name),J(e,t))}function J(e,t){try{e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multiEntry})}catch{throw new Error(`store [ ${e.name} ] index [ ${t.name} ] create error: ${JSON.stringify(t)}`)}}function G(e,t){return e.database.objectStoreNames.contains(t.name)?function(e,t){const{indexSchemas:r}=e,a=t.indexNames,n=r.map(e=>e.name);for(const e of Array.from(a))n.includes(e)||t.deleteIndex(e);for(const e of r)a.contains(e.name)?U(t,e):J(t,e);return t}(t,e.transaction?.objectStore(t.name)):function(e,t){const r=t.createObjectStore(e.name,{keyPath:e.keyPath,autoIncrement:e.autoIncrement});for(const t of e.indexSchemas)J(r,t);return r}(t,e.database)}class Q{database;newVersion;oldVersion;dbSchema;transaction;#n={};constructor(e){this.database=e.database,this.newVersion=e.newVersion,this.oldVersion=e.oldVersion,this.dbSchema=e.dbSchema,this.transaction=e.transaction}deleteStoreIfExists(e){const t=this.database;t.objectStoreNames.contains(e)&&t.deleteObjectStore(e)}destroy(){try{e.destroyRecords(this.#n)}finally{for(const e of Object.keys(this.#n))delete this.#n[e]}}store(e){if(e in this.#n)return this.#n[e];const{factory:t}=this.dbSchema,{storeSchemas:r}=this.dbSchema,a=r.find(t=>t.name===e),n=G(this,a);return this.#n[e]=t.newStoreUpgradeable(n,a,this)}versionIn({oldMin:e,oldMax:t,newMax:r,newMin:a}){if(void 0===t&&void 0===r&&void 0===e&&void 0===a)throw new Error(`versionIn bounds must not be empty ${JSON.stringify({oldMax:t,newMax:r,oldMin:e,newMin:a})}`);if(t<e)throw new Error(`oldMax (${t}) cannot be less than oldMin (${e})`);if(r<a)throw new Error(`newMax (${r}) cannot be less than newMin (${a})`);const{oldVersion:n,newVersion:s}=this;return!(void 0!==e&&n<e||void 0!==t&&n>t||void 0!==a&&s<a)&&!(void 0!==r&&s>r)}}function L(t,r){let{store:a,index:n}=t;const{storeTemplate:s}=r,{storeSchemas:i=[]}=r,o=e.isString(a)?a:a.name,c=i.findIndex(e=>e===o||e.name===o),u=c>-1&&i[c];let d;d=e.isString(a)?u||o:!u||e.isString(u)||a===u?a:{...u,...a},(n||u?.indexSchemas?.length||a?.indexSchemas?.length)&&(e.isString(d)&&(d={name:d}),d.indexSchemas=function(t,r,a){a&&r.push(a);for(const a of r){const r=e.isString(a)?a:a.name,n=t.findIndex(e=>e===r||e.name===r);if(n>-1){const r=t[n];e.isString(r)?t[n]=a:e.isString(a)||(t[n]=Object.assign(r,a))}else t.push(a)}return t}(u.indexSchemas||[],a.indexSchemas||[],n));const h=W(d,s);c>-1?i[c]=h:i.push(h),r.storeSchemas=i;const l={store:o};return n&&(l.index=e.isString(n)?n:n.name),{target:l}}const X=Object.assign({name:"",addedTimeField:!1,autoIncrement:!1,indexSchemas:[],keyPath:void 0,softDeletedField:!1,updatedCountField:!1,updatedTimeField:!1});class H{static#s;#i;#o;#c={};constructor(t,r){this.#i=t=e.isString(t)?{name:t}:t,Array.isArray(t.storeSchemas)||(t.storeSchemas=[]),e.isObject(t.storeTemplate)||(t.storeTemplate=f),r&&(this.#o=!0)}static get defaultDb(){return this.#s||(this.#s=new H(t.DefaultDbName))}get initialized(){return Object.isFrozen(this.#i)}get schema(){return this.#i}get storeNames(){return Array.from(new Set(this.#i.storeSchemas.map(t=>e.isString(t)?t:t.name)))}get factory(){return this.#i.factory||(this.#i.factory=T)}static releaseDefaultDB(){this.#s=void 0}static async openExistDb(e){const{generateDbSchema:t}=await Promise.resolve().then(function(){return te});return new H(await t(e))}static store(e,t){return H.defaultDb.store(e,t)}static stores(e){return H.defaultDb.stores(e)}static map(e,t){return H.defaultDb.map(e,t)}async openNativeDb(){const r=this.#i=e.deepFreeze(this.initSchema());await this.#u();const{name:a,version:n}=r;return await t.openDb({name:a,version:n,onupgradeneeded:(t,a,n)=>async function(t,r,a,n){const{storeSchemas:s,beforeUpgrade:i,afterUpgrade:o,version:c}=t,{newVersion:u=c,oldVersion:d}=a,{transaction:h}=n,l=new Q({database:r,newVersion:u,oldVersion:d,dbSchema:t,transaction:h});try{const t=[];if(e.isFunction(i))try{await i(l)}catch(e){t.push(e)}for(const e of s.map(e=>e.name))try{l.store(e)}catch(e){t.push(e)}for(const{name:e,defaultData:r}of s)if(r)try{await l.store(e).add({oldMax:0},r)}catch(e){t.push(e)}for(const{name:e,versionData:r}of s)if(r)for(const{version:a,data:n,use:s="addOrChange"}of r)try{await l.store(e)[s](a,n)}catch(e){t.push(e)}for(const{name:e,storeDefined:r}of s)try{await(r?.(l.store(e)))}catch(e){t.push(e)}if(e.isFunction(o))try{await o(l)}catch(e){t.push(e)}if(!t.length)return;throw 1===t.length?t[0]:new AggregateError(t,"Database upgrade error")}finally{e.destroy(l)}}(r,t,a,n)})}store(e,t){const r=e.store?e:{store:e};return r.store||(r.store=e),r.index||(r.index=t),this.factory.newWriter(L(r,this.schema),this)}stores(t){const{schema:r}=this,a=t.map(t=>L(e.isString(t)?{store:t}:t,r));return this.factory.newDataOperators(a,this)}initSchema(){if(this.initialized)return this.#i;const{validateSchemaWithDefaults:e=_}=this.#i;return this.#i=e(this.#i)}async traceSchema(t){await e.logJson(this.schema,t)}map(r,a){const n=e.isString(r)?r:e.isString(a)?a:t.DefaultStorageStoreName;Array.isArray(r)&&(a=r);const{storeSchemas:s}=this.schema;return s.find(e=>e.name===n||e===n)||s.push({...X,name:n,defaultData:a}),this.factory.newDbMap({target:{store:n}},this)}export(){return this.stores(this.storeNames).export()}import(e,t,r){return this.stores(this.storeNames).import(e,t,r)}getStoreSchema(t){if(t in this.#c)return this.#c[t];const r=this.schema.storeSchemas.findIndex(e=>e===t||e.name===t);let a=this.schema.storeSchemas[r];return this.initialized?this.#c[t]=a:e.isString(a)&&(this.schema.storeSchemas[r]=a={name:a}),a}async#u(){let r=this.#o;if(void 0===r&&(r=this.#o=await async function(r){const{name:a,version:n}=r,s=await t.findExistDb(a);if(!s)return!0;const{versionDiffValidate:i,versionSameValidate:o}=r,c=await t.openDb(a);try{if(r.version<c.version)return"The existing database version is greater than the current version";const u=void 0===r.version||c.version===r.version?o:i;if(!u)return!0;const d=Array.from(c.objectStoreNames);if(d.length<1)return`The existing database [ ${a} ] is empty`;const h=await t.readTx(c,d),l=await u({schema:r,db:c,stores:h});if(e.isString(l)||n!==s.version)return l}finally{c?.close()}return!0}(this.#i)),!0===r)return!0;if(e.isString(r))throw new Error(r)}}function Y(e,t){const r=Array.from(e.indexNames).map(t=>e.index(t)),a=[],n=[];for(const{name:e,keyPath:t,unique:s,multiEntry:i}of r)Array.isArray(t)?n.push(...t):n.push(t),a.push({name:e,keyPath:t,unique:s,multiEntry:i});const s=new Set(n);return{indexSchemas:a,addedTimeField:Z(t.addedTimeField,s),updatedTimeField:Z(t.updatedTimeField,s),updatedCountField:Z(t.updatedCountField,s),softDeletedField:Z(t.softDeletedField,s)}}function Z(e,t){return!!t.has(e)&&{name:e,isIndexed:!1}}async function ee(r,a){if(!await t.findExistDb(r))throw new Error(`db [ ${r} ] not exist`);let{asString:n,specialFields:s=y,dataExportTarget:i}=a||{};!0===n&&(n=160),isNaN(n)||n<1&&(n=1);let o=await function(e,r){return t.openDb(e,async function(e){const t=Array.from(e.objectStoreNames),a=e.transaction(t,"readonly");try{return{name:e.name,version:e.version,storeSchemas:t.map(e=>function(e,t){const{name:r,keyPath:a,autoIncrement:n}=e;return{name:r,keyPath:a,autoIncrement:n,...Y(e,t)}}(a.objectStore(e),r))}}finally{a.abort()}})}(r,s);return i&&await async function(t,r){const a=await new H(e.copyObject(t),!0).export();for(const e of t.storeSchemas){const n=a[e.name];n?.length&&("defaultData"===r?e.defaultData=n:"versionData"===r&&(e.versionData||(e.versionData=[]),e.versionData.push({version:{oldMax:t.version},data:n})))}return t}(o,i),n?await e.toJson({rootData$:o,spaceEffectiveLength:n}):o}var te=Object.freeze({__proto__:null,generateDbSchema:ee});exports.Break=i,exports.Continue=c,exports.ContinueKey=u,exports.ContinuePrimaryKey=h,exports.DataOperationBase=x,exports.DataOperators=D,exports.DataReader=O,exports.DataWriter=E,exports.DbIterator=v,exports.DbIteratorParsers=n,exports.DbMap=j,exports.Delete=a,exports.Finished=o,exports.IDbPro=H,exports.NextKey=d,exports.NextPrimaryKey=l,exports.Save=r,exports.StoreUpgradeable=A,exports.UpgradeContext=Q,exports.dbMap=function(e,t){return H.defaultDb.map(e,t)},exports.dbStore=function(e,t){return H.defaultDb.store(e,t)},exports.dbStores=function(e){return H.defaultDb.stores(e)},exports.defaultSpecialFields=y,exports.defaultStoreSchemaTemplate=f,exports.generateDbSchema=ee,exports.isIDbQuery=b,exports.isNativeTarget=m,exports.parseDbNoneKeyPathRecord=s,exports.parseIDbQuery=g,exports.releaseDefaultDB=function(){H.releaseDefaultDB()},exports.validateSchemaWithDefaults=_,exports.versionDiffValidate=B,exports.versionSameValidate=C;
|
|
1
|
+
"use strict";var e=require("gs-base"),t=require("gs-idb-basic");const r=Symbol("save"),a=Symbol("delete"),n=Object.freeze({key:({primaryKey:e})=>({value:e}),value:({value:e})=>({value:e}),keyValue:({primaryKey:e,value:t})=>({value:[e,t]})});function s(e){if(Array.isArray(e))return{key:e[1],value:e[0]};if("value"in e){const{key:t,value:r}=e;return{key:t,value:r}}throw new Error(`not include value in invalid DBRecord:${JSON.stringify(e)}`)}const i=Symbol("break"),o=Symbol("finished"),c=Symbol("continue"),u=Symbol("continue key"),d=Symbol("next key"),h=Symbol("continue primary key"),l=Symbol("next primary key");function m(e){return e instanceof IDBObjectStore||e instanceof IDBIndex}const f=Object.freeze({keyPath:"id",autoIncrement:!0,addedTimeField:!0,updatedTimeField:!0}),y=Object.freeze({addedTimeField:"added_at",softDeletedField:"deleted",updatedCountField:"updated_count",updatedTimeField:"updated_at"}),p=e=>e instanceof Date?e.getTime():e;function g(e){if(t.isDbQueryOrNull(e))return e;const r=e;if("lt"in r&&"gt"in r){if(p(r.gt)>p(r.lt))throw new Error(`Invalid IDBRange: gt (${r.gt}) cannot be greater than lt (${r.lt})`);return IDBKeyRange.bound(r.gt,r.lt,!0,!0)}if("lt"in r&&"gte"in r){if(p(r.gte)>p(r.lt))throw new Error(`Invalid IDBRange: gte (${r.gte}) cannot be greater than lt (${r.lt})`);return IDBKeyRange.bound(r.gte,r.lt,!1,!0)}if("lte"in r&&"gt"in r){if(p(r.gt)>p(r.lte))throw new Error(`Invalid IDBRange: gt (${r.gt}) cannot be greater than lte (${r.lte})`);return IDBKeyRange.bound(r.gt,r.lte,!0,!1)}if("lte"in r&&"gte"in r){if(p(r.gte)>p(r.lte))throw new Error(`Invalid IDBRange: gte (${r.gte}) cannot be greater than lte (${r.lte})`);return IDBKeyRange.bound(r.gte,r.lte,!1,!1)}return"lt"in r?IDBKeyRange.upperBound(r.lt,!0):"lte"in r?IDBKeyRange.upperBound(r.lte,!1):"gt"in r?IDBKeyRange.lowerBound(r.gt,!0):"gte"in r?IDBKeyRange.lowerBound(r.gte,!1):void 0}function b(e){return null!=g(e)}async function S(e,r,a){const{query:n,direction:s="prev",preSkip:i,startKey:o,startPrimaryKey:c}=r,u=e.openCursor(g(n),s);return i&&(await t.requestDbResult(u)).advance(i),o&&(c?(await t.requestDbResult(u)).continuePrimaryKey(o,c):(await t.requestDbResult(u)).continue(o)),u}function w(t,r,a){return Array.isArray(t)?r=>e.copyFields({},r,t):e.isFunction(t)?t:r?e=>e:a?(e,t)=>[e,t]:(e,t)=>({key:e,value:t})}class x{idbPro;target;#e;constructor(e,t){this.idbPro=t,this.#e=e.storeSchema,this.target=e.target,m(e.target)&&(this.tx=this.#t)}get storeName(){return this.nativeStore?.name||this.target.store}get storeSchema(){if(this.#e)return this.#e;const e=this.idbPro.getStoreSchema(this.storeName);return Object.isFrozen(e)&&(this.#e=e),e}get factory(){return this.idbPro.factory}get nativeStore(){const{target:e}=this;return e instanceof IDBObjectStore?e:e instanceof IDBIndex?e.objectStore:void 0}get keyPath(){const{target:e}=this;if(m(e))return e.keyPath;const{storeSchema:t}=this,{index:r}=e;return r?t.indexSchemas.find(e=>e.name===r)?.keyPath:t.keyPath}async forEach(t,r){return t=e.isFunction(t)?{fn:t}:t,r?this.cursorResult(t,!1):this.cursorVoid(t,!1)}async tx(e,t,r){let{target:a}=this;const{store:n,index:s}=a,i=await this.idbPro.openNativeDb();let o,c;try{o=i.transaction(n,!0===e?"readwrite":"readonly"),a=c=o.objectStore(n),s&&(a=a.index(s))}catch(e){throw i.close(),e}if(!t)return Object.freeze({db:i,tx:o,nativeStore:c,target:a});try{if(!0===e){const e=await t(a,c);return o.commit(),e}return t(a)}catch(e){throw!1!==r&&o.abort(),e}finally{i.close()}}openCursor(e,t){return this.tx(t,t=>new Promise(async(r,a)=>{const{fn:n}=e,s=await S(t,e);s.onsuccess=async()=>{s.result?!1===await n(s.result)&&r():r()},s.onerror=()=>a(s.error)}))}cursorVoid({query:t,direction:n,preSkip:s,startKey:o,startPrimaryKey:c,fn:d},l){let m=0;return this.openCursor({query:t,direction:n,preSkip:s,startKey:o,startPrimaryKey:c,fn:async t=>{const{value:n,primaryKey:s}=t,o=await d(n,s,m++),{control:c,key:f,primaryKey:y,modify:p,value:g}=e.isObject(o)?o:{control:o};switch(l&&(p===r?t.update(g||n):p===a&&t.delete()),c){case i:return!1;case u:t.continue(f);break;case h:t.continuePrimaryKey(f,y);break;default:t.continue()}}},!0)}async cursorResult({query:e,direction:t,preSkip:n,startKey:s,startPrimaryKey:c,fn:m,mapper:f},y){const{keyPath:p,defaultGetMapper:g}=this.storeSchema,b=w(f||g,p),S=[];let x=0;return await this.openCursor({query:e,direction:t,preSkip:n,startKey:s,startPrimaryKey:c,fn:async e=>{const{value:t,primaryKey:n}=e,{control:s,value:c,key:f,primaryKey:p,modify:g}=await(m?.(t,n,x,S))||{};switch(y&&(g===r?e.update(c||t):g===a&&e.delete()),(!s||s===o||s===d||s===l)&&S.push(b(c||t,p||n,x)),s){case i:case o:return!1;case d:case u:e.continue(f);break;case l:case h:e.continuePrimaryKey(f,p);break;default:e.continue()}x++}},y),S}#t(e,t){const{target:r}=this,a=r instanceof IDBObjectStore?r:r.objectStore;return t?t(r,a):Object.freeze({nativeStore:a,target:r})}}class D{idbPro;schemas;#r;constructor(e,t){this.idbPro=e,this.schemas=t}get storeNames(){return this.#r||(this.#r=Array.from(new Set(this.schemas.map(e=>e.target.store))))}read(e){return this.tx("newReader",e)}write(e,t=!0){return this.tx("newWriter",e,!0,t)}export(){return this.tx("newReader",async(...e)=>{const t={};for(const r of e)t[r.storeName]=await r.export();return t})}import(e,t,r){return r||(r="addOrChangeMany"),this.tx("newWriter",async(...a)=>{const n={};a=Array.from(new Map(a.map(e=>[e.storeName,e.asStore(!0)])).values());for(const s of a){const{storeName:a}=s,i=e[a];i&&(n[a]=await s[r](i,t))}if(t)return n},!0)}async tx(e,t,r,a){const{idbPro:n,schemas:s}=this,{factory:i}=n.schema,o=await n.openNativeDb();try{const c=o.transaction(this.storeNames,r?"readwrite":"readonly");try{const a=s.map(({storeSchema:t,target:r})=>{let a=c.objectStore(r.store);return r.index&&(a=a.index(r.index)),i[e]({storeSchema:t,target:a},n)});if(r){const e=await t(...a);return c.commit(),e}return await t(...a)}catch(e){throw!1!==a&&c.abort(),e}}finally{o.close()}}}class v extends x{direction;query;writable;parser;endsWithNull;preSkip;startKey;startPrimaryKey;constructor(t,r,a){if(super(t,r),!a)return;const{parser:s}=a;this.direction=a.direction,this.query=a.query,this.writable=!!a.writable,this.endsWithNull=!!a.endsWithNull,this.preSkip=a.preSkip,this.startKey=a.startKey,this.startPrimaryKey=a.startPrimaryKey,s&&(this.parser=e.isFunction(s)?s:n[s])}async*[Symbol.asyncIterator](){const{parser:e,writable:r,endsWithNull:a}=this,{db:n,tx:s,target:o}=await this.tx(r);try{const n=await S(o,this);let c;if(e)for(;c=await t.requestDbResult(n);){const{control:t,value:r}=await e(c);if(t||(yield r),t===i)break;c.continue()}else{let e=!1;const r=()=>{e=!0};for(;!e&&(c=await t.requestDbResult(n));)yield{cursor:c,end:r}}r&&s?.commit(),a&&!c&&(yield null)}finally{n?.close()}}}function k(t,r,a,n){const s=e.isObject(t)?t:{};return e.isFunction(t)?s.fn=t:b(t)&&(s.query=t),e.isFunction(r)?s.fn=r:r&&(s.direction=r),a&&(s.direction=a),n?s.limit=n:s.limit||(s.limit=1e3),s.maxEmptyChecks||(s.maxEmptyChecks=2e4),s}async function P(t,r,a){r.size||(r.size=100),r.nextSkip||(r.nextSkip=0);const{query:n,direction:s,total:i,maxEmptyChecks:o,fn:c}=r;return await t.batchRead(async t=>(i||(r.total=await t.count({query:n,direction:s,maxEmptyChecks:o,fn:c}),r.pages=Math.ceil(r.total/r.size)),r.total<1?{info:e.deepFreeze(r),rows:[]}:c?await async function(e,t,r){t.maxEmptyChecks||(t.maxEmptyChecks=2e4);const{page:a,query:n,direction:s,nextSkip:i}=t,{keyPath:o}=e.storeSchema;return 1===a?await q(e,await S(e.target,{query:n,direction:s}),t,o):r&&i&&a-r.page===1?await q(e,await S(e.target,{query:n,direction:s,preSkip:i}),t,o):await q(e,await S(e.target,{query:n,direction:s}),t,o,!0)}(t,r,a):await async function(t,r){const{keyPath:a}=t.storeSchema,{page:n,query:s,direction:i,size:o,mapper:c}=r,u=(n-1)*o,d=await t.filter({query:s,preSkip:u,direction:i,limit:o,mapper:w(c,a,!0)});return r.nextSkip=u+d.length,{info:e.deepFreeze(r),rows:d}}(t,r)))}async function q({storeSchema:{defaultGetMapper:t}},r,a,n,s){const{page:i,size:o,total:c,maxEmptyChecks:u,fn:d}=a,h=w(a.mapper||t,n,!0),l=[],m=(i-1)*a.size;if(m>=c)return{info:e.deepFreeze(a),rows:[]};let f=0;return await new Promise(async(e,t)=>{let a=0,n=0;const i=async()=>{const{result:t}=r;if(!t)return e();let{value:n,primaryKey:s}=t;if(await d(n,s,f)?(a=0,l.push(h(n,s,f))):a++,l.length>=o||a>=u)return e();f++,t.continue()};r.onerror=()=>t(r.error),r.onsuccess=s?async()=>{const{result:t}=r;if(!t)return e();let{value:s,primaryKey:o}=t;if(await d(s,o,f)?(a=0,n++):a++,n>=m||a>=u)return f=a=0,r.onsuccess=i,void t.continue();t.continue(),f++}:i}),f&&(a.nextSkip+=f+1),{info:e.deepFreeze(a),rows:l}}class O extends x{all(r,a){const n={};return e.isNumber(a)&&(n.limit=a),b(r)?n.query=r:e.isObject(r)&&Object.assign(n,r),this.tx(!1,e=>t.requestDbResult(e.getAll(g(n.query),n.limit||1e3)))}async count(e,r,a){const n=k(e,r,a),{query:s,direction:i,fn:o}=n;if(!o)return await this.tx(!1,e=>t.requestDbResult(e.count(g(s))));const{maxEmptyChecks:c}=n,u=o;let d=0,h=0,l=0;return await this.openCursor({query:s,direction:i,fn:e=>{if(u(e.value,e.primaryKey,l++))d++,h=0;else if(++h>=c)return!1;e.continue()}}),d}get(e){return this.tx(!1,r=>t.requestDbResult(r.get(g(e))))}getMany(t,r){return this.batchRead(async a=>{const n=await e.asyncMap(t,e=>a.get(e));return r?n.filter(e=>e):n})}getRange(e,t){return this.forEach({query:e,direction:t},!0)}async getRangeMany(t,r,a){return(await this.batchRead(a=>e.asyncMap(t,e=>a.getRange(e,r)))).flat()}index(e,t){let{target:r}=this;return r instanceof IDBIndex&&(r=r.objectStore),r instanceof IDBObjectStore?(r=r.index(e),this.createOperator(r,t)):this.idbPro.store(r.store,e)}asStore(e){let{target:t}=this;if(t instanceof IDBObjectStore)return this;if(t instanceof IDBIndex)t=t.objectStore;else{if(!("index"in t))return this;t={store:t.store}}return this.createOperator(t,e)}batchRead(e){return m(this.target)?e(this):this.tx(!1,t=>e(this.idbPro.schema.factory.newReader({storeSchema:this.storeSchema,target:t},this.idbPro)))}iterator(t,r){const a={};return e.isString(r)&&(a.direction=r),b(t)?a.query=t:e.isObject(t)&&Object.assign(a,t),new v({storeSchema:this.storeSchema,target:this.target},this.idbPro,{...a,parser:"value"})}async filter(e,t,r,a){const n=k(e,t,r,a),{maxEmptyChecks:s,limit:u,fn:d}=n,{keyPath:h,defaultGetMapper:l}=this.storeSchema,m=w(n.mapper||l,h,!0);if(!d)return await this.forEach({...n,mapper:m,fn:(e,t,r)=>{if(r>=u-1)return{control:o}}},!0);let f=0;return this.forEach({...n,mapper:m,fn:(e,t,r,a)=>d(e,t,r)?(f=0,a.length>=u-1?{control:o}:void 0):++f>=s?{control:i}:{control:c}},!0)}async find(e,t,r){const[a]=await this.filter(e,t,r,1);return a}async page(e,t){const r={...e};return r.page=t||e?.page||1,P(this,r,e)}nextPage(e){return this.page(e,e.page+1)}export(e,t){const r=k(e,t),{keyPath:a,exportMapper:n,name:s,defaultGetMapper:i}=this.storeSchema;if(!a&&Array.isArray(n))throw new Error(`When store [ ${s} ] keyPath does not exist, exportMapper does not support string[].`);return r.direction="next",r.mapper=w(n||i,a,!0),r.limit=r.maxEmptyChecks=Number.MAX_SAFE_INTEGER,this.filter(r)}asMap(){let{target:e}=this;return e instanceof IDBIndex?e=e.objectStore:e instanceof IDBObjectStore||(e={store:e.store}),this.factory.newDbMap({target:e},this.idbPro)}createOperator(e,t){const{idbPro:r}=this,a=this.storeSchema,n={storeSchema:Object.isFrozen(a)?a:void 0,target:e};return t?this.factory.newWriter(n,r):this.factory.newReader(n,r)}}function I(e,t){if(!Array.isArray(e))return{[e]:t};const r={},a=e;for(let e=0;e<a.length;e++)r[a[e]]=t[e];return r}function R(e,t){if(!Array.isArray(e))return t[e];const r=[];for(const a of e){if(!t[a])return;r.push(t[a])}return r}function F(t,r){if(!r||!(r instanceof Object)||Array.isArray(r))return r;const{addedTimeField:a,updatedTimeField:n,updatedCountField:s,softDeletedField:i}=t;return r={...r},a?.name&&!e.isNumber(r[a.name])&&(r[a.name]=Date.now()),n?.name&&!e.isNumber(r[n.name])&&(r[n.name]=Date.now()),i?.name&&!e.isNumber(r[i.name])&&(r[i.name]=0),s?.name&&(r[s.name]=0),r}function M(e,t,r){if(!t||!(t instanceof Object)||Array.isArray(t))return t;const{updatedTimeField:a,updatedCountField:n}=e;return t={...r,...t},a.name&&(t[a.name]=Date.now()),n.name&&(t[n.name]=(t[n.name]||0)+1),t}class E extends O{add(e){return this.changeByPk({record:e,fn:async(e,r,a,n,s)=>{const{storeSchema:i}=this;return a=F(i,a),s?[{...a,...I(s,await t.requestDbResult(e.add(a)))},r]:[a,await t.requestDbResult(e.add(a,r))]}})}addMany(t,r){return this.batchWrite(a=>r?e.asyncMap(t,e=>a.add(e)):e.asyncForEach(t,e=>a.add(e)),!0)}addOrSkip(e){return this.batchWrite(async r=>{const{keyPath:a,defaultGetMapper:n}=r.storeSchema,{key:i,value:o}=a?{key:R(a,e),value:e}:s(e);if(i){const e=await t.requestDbResult(r.nativeStore.get(i));if(e)return w(n,a)?.(e,i)}if(r.target instanceof IDBIndex){const{keyPath:t}=r,a=R(t,o);if(!a)return r.add(e);let n=await r.find(a);if(n)return n}return r.add(e)})}addOrSkipMany(t,r){return this.batchWrite(a=>r?e.asyncMap(t,e=>a.addOrSkip(e)):e.asyncForEach(t,e=>a.addOrSkip(e)),!0)}replace(e){return this.changeByPk({record:e,getOld:!0,fn:async(e,r,a,n,s)=>{const{storeSchema:i}=this,{updatedTimeField:o,updatedCountField:c,addedTimeField:u}=i;return a=n?M(i,a,{[o.name]:n[o.name],[c.name]:n[c.name],[u.name]:n[u.name]}):F(i,a),s?[{...a,...I(s,await t.requestDbResult(e.put(a)))},r]:[a,await t.requestDbResult(e.put(a,r))]}})}replaceMany(t,r){return this.batchWrite(a=>r?e.asyncMap(t,e=>a.replace(e)):e.asyncForEach(t,e=>a.replace(e)),!0)}change(e,r){return this.changeByPk({record:e,getOld:!0,requiredOld:r,requiredPk:r,fn:async(e,r,a,n,s)=>{const{storeSchema:i}=this;if(n)return a=M(i,a,n),s?[{...a,...I(s,await t.requestDbResult(e.put(a)))},r]:[a,await t.requestDbResult(e.put(a,r))]}})}changeMany(t,r){const{returns:a,throwIfMissing:n}=e.isBoolean(r)?{returns:r}:r||{};return this.batchWrite(r=>a?e.asyncMap(t,e=>r.change(e,n)):e.asyncForEach(t,e=>r.change(e,n)),!0)}addOrChange(e){return this.changeByPk({record:e,getOld:!0,fn:async(e,r,a,n,s)=>{const{storeSchema:i}=this;return n?(a=M(i,a,n),s?[{...a,...I(s,await t.requestDbResult(e.put(a)))},r]:[a,await t.requestDbResult(e.put(a,r))]):(a=F(i,a),s?[{...a,...I(s,await t.requestDbResult(e.add(a)))},r]:[a,await t.requestDbResult(e.add(a,r))])}})}addOrChangeMany(t,r){return this.batchWrite(a=>r?e.asyncMap(t,e=>a.addOrChange(e)):e.asyncForEach(t,e=>a.addOrChange(e)),!0)}delete(e,t){return this.changeByPk({pk:e,getOld:t,fn:(e,r,a,n)=>{if(e.delete(r),t)return[n,r]}})}deleteMany(t,r){return this.batchWrite(a=>r?e.asyncMap(t,e=>a.delete(e,!0)):e.asyncForEach(t,e=>a.delete(e)),!0)}deleteRange(t,n){const{returns:s,physical:i,direction:o}=e.isBoolean(n)?{returns:n}:n||{},{name:c}=this.storeSchema.softDeletedField||{};return this.cursor({query:t,direction:o,fn:e=>i||!c?{modify:a}:(e[c]=1,{modify:r})},s)}deleteRangeMany(t,r){const a=e.isBoolean(r)?{returns:r}:r;return this.batchWrite(r=>a?.returns?e.asyncMap(t,e=>r.deleteRange(e,a)):e.asyncForEach(t,e=>r.deleteRange(e,a)),!0)}changeRange(e,t){let{direction:a="next",query:n,newValue:s}="newValue"in e?e:{newValue:e};if(n||(n=R(this.keyPath,s)),!n)throw new Error(`query is required:${JSON.stringify(e)}`);return this.cursor({query:n,direction:a,fn:e=>e instanceof Object?{modify:r,value:{...e,...s}}:{modify:r,value:s}},t)}changeRangeMany(t,r){return this.batchWrite(a=>r?e.asyncMap(t,e=>a.changeRange(e,r)):e.asyncForEach(t,e=>a.changeRange(e,r)),!0)}cursor(t,r){return(t=e.isFunction(t)?{fn:t}:t||{}).fn?r?this.cursorResult(t,!0):this.cursorVoid(t,!0):new v(this,this.idbPro)}batchWrite(e,t){const{target:r}=this;if(m(r))try{return e(this)}catch(e){throw!1!==t&&(r instanceof IDBIndex?r.objectStore:r).transaction.abort(),e}return this.tx(!0,t=>e(this.idbPro.schema.factory.newWriter({storeSchema:this.storeSchema,target:t},this.idbPro)),t)}changeByPk({pk:e,record:r,fn:a,requiredPk:n,getOld:i,requiredOld:o,saveMapper:c,getMapper:u}){const{storeSchema:d}=this,{keyPath:h,defaultSaveMapper:l,defaultGetMapper:m}=d;return r&&(c||l)&&(r=w(c||l,h)?.(r)),this.batchWrite(async c=>{let d,l=r;if(e)d=g(e);else if(h)d=R(h,r);else{const{key:e,value:t}=s(r);d=e,l=t}if(n&&!d)throw new Error(`key is required: ${JSON.stringify(r)}`);const f=d&&(i||o)?await t.requestDbResult(c.nativeStore.get(d)):void 0;if(o&&!f)throw new Error(`record not found: ${JSON.stringify(r)}`);const y=await a(c.nativeStore,d,l,f,h);if(y)return w(u||m,h)?.(y[0],y[1])})}}class j extends x{get size(){return this.tx(!1,e=>t.requestDbResult(e.count()))}delete(e){return this.tx(!0,async(t,r)=>{r.delete(e)})}batch(e){const{idbPro:t,storeSchema:r,factory:a}=this;return this.tx(!0,async(n,s)=>await e(a.newDbMap({storeSchema:r,target:s},t)))}asStore(e){const{factory:t}=this.idbPro.schema;return e?t.newWriter(this,this.idbPro):t.newReader({target:this.target},this.idbPro)}entries(){return new v({target:this.target},this.idbPro,{parser:"keyValue"})}async get(e,r){return await this.tx(!1,r=>t.requestDbResult(r.get(e)))||r}getMany(e){return this.tx(!1,async r=>{const a=[];for(const n of e)a.push(await t.requestDbResult(r.get(n)));return a})}async has(e){return!!await this.get(e)}keys(){return new v({storeSchema:this.storeSchema,target:this.target},this.idbPro,{parser:"key"})}set(e,r){return this.tx(!0,async(a,n)=>{await t.requestDbResult(n.put(r,e))})}setMany(e){return this.tx(!0,async(t,r)=>{for(const[t,a]of e)r.put(a,t)})}values(){return new v({storeSchema:this.storeSchema,target:this.target},this.idbPro,{parser:"value"})}}function N(e,t){if(e==t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}return!1}const B=({stores:e,schema:t})=>{const r=t.storeSchemas;let a="";for(const t of e){const e=r.find(e=>e.name===t.name);if(e){if(!N(t.keyPath,e.keyPath)){a=`store [ ${t.name} ] keyPath not equal,schema.keyPath:${e.keyPath},store.keyPath:${t.keyPath}[]`;break}if(!t.autoIncrement!=!e.autoIncrement){a=`store [ ${t.name} ] autoIncrement not equal`;break}}}return!a||`The existing database is inconsistent with the definition and cannot be corrected: ${a}`},C=async t=>{let r=B(t);return e.isString(r)||(r=K(t)),r},K=({stores:e,schema:t})=>{const r=t.storeSchemas,a=e.map(e=>e.name);let n="";const s=r.map(e=>e.name).filter(e=>!a.includes(e));if(s.length)n=`store [ ${s.join(",")} ] not exist`;else for(const t of e){const e=r.find(e=>e.name===t.name);if(e&&(n=$(t,Array.from(t.indexNames),e.indexSchemas),n))break}return!n||`The existing database Store index is inconsistent with the definition and requires a database version upgrade to be fixed: ${n}`};function $(e,t,r){if(t.length!==r.length)return`store [ ${e.name} ] index count not equal`;for(const a of t){const t=r.find(e=>e.name===a);if(!t)return`store [ ${e.name} ] index [ ${a} ] not exist`;const n=e.index(a);if(!t.unique!=!n.unique)return`store [ ${e.name} ] index [ ${a} ] unique not equal`;if(!t.multiEntry!=!n.multiEntry)return`store [ ${e.name} ] index [ ${a} ] multiEntry not equal`;if(!N(t.keyPath,n.keyPath))return`store [ ${e.name} ] index [ ${a} ] keyPath not equal`}return""}class A{upgradeContext;storeSchema;nativeStore;#a;constructor(e,t,r){this.upgradeContext=e,this.storeSchema=t,this.nativeStore=r}get writer(){return this.#a||(this.#a=this.upgradeContext.dbSchema.factory?.newWriter({target:this.nativeStore,storeSchema:this.storeSchema}))}add(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.addMany(t,r):Promise.resolve()}addOrChange(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.addOrChangeMany(t,r):Promise.resolve()}async call(e,t){if(this.upgradeContext.versionIn(e))return await t(this.writer,this.upgradeContext)}replace(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.replaceMany(t,r):Promise.resolve()}}const T=Object.freeze({newDataOperators:(e,t)=>new D(t,e),newDbMap:(e,t)=>new j(e,t),newReader:(e,t)=>new O(e,t),newStoreUpgradeable:(e,t,r)=>new A(r,t,e),newWriter:(e,t)=>new E(e,t)});function V(t,r,a,n){const s=function(t,r,a){if(!1===t)return!1;if(e.isString(t))return{name:t};if(e.isObject(t)){const a=t;return e.isBoolean(a.name)&&(a.name=r),t}if(!0===t||a)return{name:r};return!1}(r,a,n);if(!s)return s;const i=s;if(!1!==i.isIndexed){i.isIndexed||(i.isIndexed=!0);const{name:e}=i,r=t.indexSchemas;r.some(t=>t===e||t.name===e)||r.push(e)}return i}function W(t,r){let a=e.isString(t)?{name:t}:t;return r&&(a={...r,...a}),a.indexSchemas||(a.indexSchemas=[]),function(e){Object.isFrozen(e)||(e.addedTimeField=V(e,e.addedTimeField,"added_at",!0),e.updatedTimeField=V(e,e.updatedTimeField,"updated_at",!0),e.updatedCountField=V(e,e.updatedCountField,"updated_count",!1),e.softDeletedField=V(e,e.softDeletedField,"deleted",!1))}(a),Object.isFrozen(a)||(a.indexSchemas=a.indexSchemas.map(z)),function(e){if(!e.keyPath&&e.defaultData?.length)for(const t of e.defaultData)if(!Array.isArray(t)&&!("value"in t))throw new Error(`When \`defaultData\` must contain \`value\` fields or be an array:${JSON.stringify(t)}`)}(a),a}function z(t){const r=e.isString(t)?{name:t}:t;return r.keyPath||(r.keyPath=r.name),r}const _=e=>{const{versionDiffValidate:t,versionSameValidate:r,factory:a}=e;return e.storeSchemas||(e.storeSchemas=[]),e.storeTemplate||(e.storeTemplate={...f}),!t&&!1!==t&&(e.versionDiffValidate=B),!r&&!1!==r&&(e.versionSameValidate=C),a?a!==T&&(e.factory={...T,...a}):e.factory=T,e.storeSchemas=e.storeSchemas.map(t=>W(t,e.storeTemplate)),e};function U(e,t){(function(e,t){return e.unique===t.unique&&e.multiEntry===t.multiEntry&&N(t.keyPath,e.keyPath)})(e.index(t.name),t)||(e.deleteIndex(t.name),J(e,t))}function J(e,t){try{e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multiEntry})}catch{throw new Error(`store [ ${e.name} ] index [ ${t.name} ] create error: ${JSON.stringify(t)}`)}}function G(e,t){return e.database.objectStoreNames.contains(t.name)?function(e,t){const{indexSchemas:r}=e,a=t.indexNames,n=r.map(e=>e.name);for(const e of Array.from(a))n.includes(e)||t.deleteIndex(e);for(const e of r)a.contains(e.name)?U(t,e):J(t,e);return t}(t,e.transaction?.objectStore(t.name)):function(e,t){const r=t.createObjectStore(e.name,{keyPath:e.keyPath,autoIncrement:e.autoIncrement});for(const t of e.indexSchemas)J(r,t);return r}(t,e.database)}class Q{database;newVersion;oldVersion;dbSchema;transaction;#n={};constructor(e){this.database=e.database,this.newVersion=e.newVersion,this.oldVersion=e.oldVersion,this.dbSchema=e.dbSchema,this.transaction=e.transaction}deleteStoreIfExists(e){const t=this.database;t.objectStoreNames.contains(e)&&t.deleteObjectStore(e)}destroy(){try{e.destroyRecords(this.#n)}finally{for(const e of Object.keys(this.#n))delete this.#n[e]}}store(e){if(e in this.#n)return this.#n[e];const{factory:t}=this.dbSchema,{storeSchemas:r}=this.dbSchema,a=r.find(t=>t.name===e),n=G(this,a);return this.#n[e]=t.newStoreUpgradeable(n,a,this)}versionIn({oldMin:e,oldMax:t,newMax:r,newMin:a}){if(void 0===t&&void 0===r&&void 0===e&&void 0===a)throw new Error(`versionIn bounds must not be empty ${JSON.stringify({oldMax:t,newMax:r,oldMin:e,newMin:a})}`);if(t<e)throw new Error(`oldMax (${t}) cannot be less than oldMin (${e})`);if(r<a)throw new Error(`newMax (${r}) cannot be less than newMin (${a})`);const{oldVersion:n,newVersion:s}=this;return!(void 0!==e&&n<e||void 0!==t&&n>t||void 0!==a&&s<a)&&!(void 0!==r&&s>r)}}function L(t,r){let{store:a,index:n}=t;const{storeTemplate:s}=r,{storeSchemas:i=[]}=r,o=e.isString(a)?a:a.name,c=i.findIndex(e=>e===o||e.name===o),u=c>-1&&i[c];let d;d=e.isString(a)?u||o:!u||e.isString(u)||a===u?a:{...u,...a},(n||u?.indexSchemas?.length||a?.indexSchemas?.length)&&(e.isString(d)&&(d={name:d}),d.indexSchemas=function(t,r,a){a&&r.push(a);for(const a of r){const r=e.isString(a)?a:a.name,n=t.findIndex(e=>e===r||e.name===r);if(n>-1){const r=t[n];e.isString(r)?t[n]=a:e.isString(a)||(t[n]=Object.assign(r,a))}else t.push(a)}return t}(u.indexSchemas||[],a.indexSchemas||[],n));const h=W(d,s);c>-1?i[c]=h:i.push(h),r.storeSchemas=i;const l={store:o};return n&&(l.index=e.isString(n)?n:n.name),{target:l}}const X=Object.assign({name:"",addedTimeField:!1,autoIncrement:!1,indexSchemas:[],keyPath:void 0,softDeletedField:!1,updatedCountField:!1,updatedTimeField:!1});class H{static#s;#i;#o;#c={};constructor(t,r){this.#i=t=e.isString(t)?{name:t}:t,Array.isArray(t.storeSchemas)||(t.storeSchemas=[]),e.isObject(t.storeTemplate)||(t.storeTemplate=f),r&&(this.#o=!0)}static get defaultDb(){return this.#s||(this.#s=new H(t.DefaultDbName))}get initialized(){return Object.isFrozen(this.#i)}get schema(){return this.#i}get storeNames(){return Array.from(new Set(this.#i.storeSchemas.map(t=>e.isString(t)?t:t.name)))}get factory(){return this.#i.factory||(this.#i.factory=T)}static releaseDefaultDB(){this.#s=void 0}static async openExistDb(e){const{generateDbSchema:t}=await Promise.resolve().then(function(){return te});return new H(await t(e))}static store(e,t){return H.defaultDb.store(e,t)}static stores(e){return H.defaultDb.stores(e)}static map(e,t){return H.defaultDb.map(e,t)}async openNativeDb(){const r=this.#i=e.deepFreeze(this.initSchema());await this.#u();const{name:a,version:n}=r;return await t.openDb({name:a,version:n,onupgradeneeded:(t,a,n)=>async function(t,r,a,n){const{storeSchemas:s,beforeUpgrade:i,afterUpgrade:o,version:c}=t,{newVersion:u=c,oldVersion:d}=a,{transaction:h}=n,l=new Q({database:r,newVersion:u,oldVersion:d,dbSchema:t,transaction:h});try{const t=[];if(e.isFunction(i))try{await i(l)}catch(e){t.push(e)}for(const e of s.map(e=>e.name))try{l.store(e)}catch(e){t.push(e)}for(const{name:e,defaultData:r}of s)if(r)try{await l.store(e).add({oldMax:0},r)}catch(e){t.push(e)}for(const{name:e,versionData:r}of s)if(r)for(const{version:a,data:n,use:s="addOrChange"}of r)try{await l.store(e)[s](a,n)}catch(e){t.push(e)}for(const{name:e,storeDefined:r}of s)try{await(r?.(l.store(e)))}catch(e){t.push(e)}if(e.isFunction(o))try{await o(l)}catch(e){t.push(e)}if(!t.length)return;throw 1===t.length?t[0]:new AggregateError(t,"Database upgrade error")}finally{e.destroy(l)}}(r,t,a,n)})}store(e,t){const r=e.store?e:{store:e};return r.store||(r.store=e),r.index||(r.index=t),this.factory.newWriter(L(r,this.schema),this)}stores(t){const{schema:r}=this,a=t.map(t=>L(e.isString(t)?{store:t}:t,r));return this.factory.newDataOperators(a,this)}initSchema(){if(this.initialized)return this.#i;const{validateSchemaWithDefaults:e=_}=this.#i;return this.#i=e(this.#i)}async traceSchema(t){await e.logJson(this.schema,t)}map(r,a){const n=e.isString(r)?r:e.isString(a)?a:t.DefaultStorageStoreName;Array.isArray(r)&&(a=r);const{storeSchemas:s}=this.schema;return s.find(e=>e.name===n||e===n)||s.push({...X,name:n,defaultData:a}),this.factory.newDbMap({target:{store:n}},this)}export(){return this.stores(this.storeNames).export()}import(e,t,r){return this.stores(this.storeNames).import(e,t,r)}getStoreSchema(t){if(t in this.#c)return this.#c[t];const r=this.schema.storeSchemas.findIndex(e=>e===t||e.name===t);let a=this.schema.storeSchemas[r];return this.initialized?this.#c[t]=a:e.isString(a)&&(this.schema.storeSchemas[r]=a={name:a}),a}async#u(){let r=this.#o;if(void 0===r&&(r=this.#o=await async function(r){const{name:a,version:n}=r,s=await t.findExistDb(a);if(!s)return!0;const{versionDiffValidate:i,versionSameValidate:o}=r,c=await t.openDb(a);try{if(r.version<c.version)return"The existing database version is greater than the current version";const u=void 0===r.version||c.version===r.version?o:i;if(!u)return!0;const d=Array.from(c.objectStoreNames);if(d.length<1)return`The existing database [ ${a} ] is empty`;const h=await t.readTx(c,d),l=await u({schema:r,db:c,stores:h});if(e.isString(l)||n!==s.version)return l}finally{c?.close()}return!0}(this.#i)),!0===r)return!0;if(e.isString(r))throw new Error(r)}}function Y(e,t){const r=Array.from(e.indexNames).map(t=>e.index(t)),a=[],n=[];for(const{name:e,keyPath:t,unique:s,multiEntry:i}of r)Array.isArray(t)?n.push(...t):n.push(t),a.push({name:e,keyPath:t,unique:s,multiEntry:i});const s=new Set(n);return{indexSchemas:a,addedTimeField:Z(t.addedTimeField,s),updatedTimeField:Z(t.updatedTimeField,s),updatedCountField:Z(t.updatedCountField,s),softDeletedField:Z(t.softDeletedField,s)}}function Z(e,t){return!!t.has(e)&&{name:e,isIndexed:!1}}async function ee(r,a){if(!await t.findExistDb(r))throw new Error(`db [ ${r} ] not exist`);let{asString:n,specialFields:s=y,dataExportTarget:i}=a||{};!0===n&&(n=160),isNaN(n)||n<1&&(n=1);let o=await function(e,r){return t.openDb(e,async function(e){const t=Array.from(e.objectStoreNames),a=e.transaction(t,"readonly");try{return{name:e.name,version:e.version,storeSchemas:t.map(e=>function(e,t){const{name:r,keyPath:a,autoIncrement:n}=e;return{name:r,keyPath:a,autoIncrement:n,...Y(e,t)}}(a.objectStore(e),r))}}finally{a.abort()}})}(r,s);return i&&await async function(t,r){const a=await new H(e.copyObject(t),!0).export();for(const e of t.storeSchemas){const n=a[e.name];n?.length&&("defaultData"===r?e.defaultData=n:"versionData"===r&&(e.versionData||(e.versionData=[]),e.versionData.push({version:{oldMax:t.version},data:n})))}return t}(o,i),n?await e.toJson({rootData$:o,spaceEffectiveLength:n}):o}var te=Object.freeze({__proto__:null,generateDbSchema:ee});exports.Break=i,exports.Continue=c,exports.ContinueKey=u,exports.ContinuePrimaryKey=h,exports.DataOperationBase=x,exports.DataOperators=D,exports.DataReader=O,exports.DataWriter=E,exports.DbIterator=v,exports.DbIteratorParsers=n,exports.DbMap=j,exports.Delete=a,exports.Finished=o,exports.IDbPro=H,exports.NextKey=d,exports.NextPrimaryKey=l,exports.Save=r,exports.StoreUpgradeable=A,exports.UpgradeContext=Q,exports.dbMap=function(e,t){return H.defaultDb.map(e,t)},exports.dbStore=function(e,t){return H.defaultDb.store(e,t)},exports.dbStores=function(e){return H.defaultDb.stores(e)},exports.defaultSpecialFields=y,exports.defaultStoreSchemaTemplate=f,exports.generateDbSchema=ee,exports.isIDbQuery=b,exports.isNativeTarget=m,exports.parseDbNoneKeyPathRecord=s,exports.parseIDbQuery=g,exports.releaseDefaultDB=function(){H.releaseDefaultDB()},exports.validateSchemaWithDefaults=_,exports.versionDiffValidate=B,exports.versionSameValidate=C;
|
package/lib/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{copyFields as e,isFunction as t,isObject as r,deepFreeze as a,isNumber as n,asyncMap as i,isString as s,asyncForEach as o,isBoolean as c,destroyRecords as u,destroy as d,logJson as h,toJson as m,copyObject as l}from"gs-base";import{isDbQueryOrNull as f,requestDbResult as y,findExistDb as p,openDb as g,readTx as w,DefaultDbName as S,DefaultStorageStoreName as b}from"gs-idb-basic";const x=Symbol("save"),v=Symbol("delete"),k=Object.freeze({key:({primaryKey:e})=>({value:e}),value:({value:e})=>({value:e}),keyValue:({primaryKey:e,value:t})=>({value:[e,t]})});function P(e){if(Array.isArray(e))return{key:e[1],value:e[0]};if("value"in e){const{key:t,value:r}=e;return{key:t,value:r}}throw new Error(`not include value in invalid DBRecord:${JSON.stringify(e)}`)}const D=Symbol("break"),I=Symbol("finished"),O=Symbol("continue"),M=Symbol("continue key"),q=Symbol("next key"),E=Symbol("continue primary key"),j=Symbol("next primary key");function F(e){return e instanceof IDBObjectStore||e instanceof IDBIndex}const R=Object.freeze({keyPath:"id",autoIncrement:!0,addedTimeField:!0,updatedTimeField:!0}),$=Object.freeze({addedTimeField:"added_at",softDeletedField:"deleted",updatedCountField:"updated_count",updatedTimeField:"updated_at"}),B=e=>e instanceof Date?e.getTime():e;function C(e){if(f(e))return e;const t=e;if("lt"in t&&"gt"in t){if(B(t.gt)>B(t.lt))throw new Error(`Invalid IDBRange: gt (${t.gt}) cannot be greater than lt (${t.lt})`);return IDBKeyRange.bound(t.gt,t.lt,!0,!0)}if("lt"in t&&"gte"in t){if(B(t.gte)>B(t.lt))throw new Error(`Invalid IDBRange: gte (${t.gte}) cannot be greater than lt (${t.lt})`);return IDBKeyRange.bound(t.gte,t.lt,!1,!0)}if("lte"in t&&"gt"in t){if(B(t.gt)>B(t.lte))throw new Error(`Invalid IDBRange: gt (${t.gt}) cannot be greater than lte (${t.lte})`);return IDBKeyRange.bound(t.gt,t.lte,!0,!1)}if("lte"in t&&"gte"in t){if(B(t.gte)>B(t.lte))throw new Error(`Invalid IDBRange: gte (${t.gte}) cannot be greater than lte (${t.lte})`);return IDBKeyRange.bound(t.gte,t.lte,!1,!1)}return"lt"in t?IDBKeyRange.upperBound(t.lt,!0):"lte"in t?IDBKeyRange.upperBound(t.lte,!1):"gt"in t?IDBKeyRange.lowerBound(t.gt,!0):"gte"in t?IDBKeyRange.lowerBound(t.gte,!1):void 0}function A(e){return null!=C(e)}async function N(e,t,r){const{query:a,direction:n="prev",preSkip:i,startKey:s,startPrimaryKey:o}=t,c=e.openCursor(C(a),n);return i&&(await y(c)).advance(i),s&&(o?(await y(c)).continuePrimaryKey(s,o):(await y(c)).continue(s)),c}function K(r,a,n){return Array.isArray(r)?t=>e({},t,r):t(r)?r:a?e=>e:n?(e,t)=>[e,t]:(e,t)=>({key:e,value:t})}class T{idbPro;target;#e;constructor(e,t){this.idbPro=t,this.#e=e.storeSchema,this.target=e.target,F(e.target)&&(this.tx=this.#t)}get storeName(){return this.nativeStore?.name||this.target.store}get storeSchema(){if(this.#e)return this.#e;const e=this.idbPro.getStoreSchema(this.storeName);return Object.isFrozen(e)&&(this.#e=e),e}get factory(){return this.idbPro.factory}get nativeStore(){const{target:e}=this;return e instanceof IDBObjectStore?e:e instanceof IDBIndex?e.objectStore:void 0}get keyPath(){const{target:e}=this;if(F(e))return e.keyPath;const{storeSchema:t}=this,{index:r}=e;return r?t.indexSchemas.find(e=>e.name===r)?.keyPath:t.keyPath}async forEach(e,r){return e=t(e)?{fn:e}:e,r?this.cursorResult(e,!1):this.cursorVoid(e,!1)}async tx(e,t,r){let{target:a}=this;const{store:n,index:i}=a,s=await this.idbPro.openNativeDb();let o,c;try{o=s.transaction(n,!0===e?"readwrite":"readonly"),a=c=o.objectStore(n),i&&(a=a.index(i))}catch(e){throw s.close(),e}if(!t)return Object.freeze({db:s,tx:o,nativeStore:c,target:a});try{if(!0===e){const e=await t(a,c);return o.commit(),e}return t(a)}catch(e){throw!1!==r&&o.abort(),e}finally{s.close()}}openCursor(e,t){return this.tx(t,t=>new Promise(async(r,a)=>{const{fn:n}=e,i=await N(t,e);i.onsuccess=async()=>{i.result?!1===await n(i.result)&&r():r()},i.onerror=()=>a(i.error)}))}cursorVoid({query:e,direction:t,preSkip:a,startKey:n,startPrimaryKey:i,fn:s},o){let c=0;return this.openCursor({query:e,direction:t,preSkip:a,startKey:n,startPrimaryKey:i,fn:async e=>{const{value:t,primaryKey:a}=e,n=await s(t,a,c++),{control:i,key:u,primaryKey:d,modify:h,value:m}=r(n)?n:{control:n};switch(o&&(h===x?e.update(m||t):h===v&&e.delete()),i){case D:return!1;case M:e.continue(u);break;case E:e.continuePrimaryKey(u,d);break;default:e.continue()}}},!0)}async cursorResult({query:e,direction:t,preSkip:r,startKey:a,startPrimaryKey:n,fn:i,mapper:s},o){const{keyPath:c,defaultGetMapper:u}=this.storeSchema,d=K(s||u,c),h=[];let m=0;return await this.openCursor({query:e,direction:t,preSkip:r,startKey:a,startPrimaryKey:n,fn:async e=>{const{value:t,primaryKey:r}=e,{control:a,value:n,key:s,primaryKey:c,modify:u}=await(i?.(t,r,m,h))||{};switch(o&&(u===x?e.update(n||t):u===v&&e.delete()),(!a||a===I||a===q||a===j)&&h.push(d(n||t,c||r,m)),a){case D:case I:return!1;case q:case M:e.continue(s);break;case j:case E:e.continuePrimaryKey(s,c);break;default:e.continue()}m++}},o),h}#t(e,t){const{target:r}=this,a=r instanceof IDBObjectStore?r:r.objectStore;return t?t(r,a):Object.freeze({nativeStore:a,target:r})}}class V{idbPro;schemas;#r;constructor(e,t){this.idbPro=e,this.schemas=t}get storeNames(){return this.#r||(this.#r=Array.from(new Set(this.schemas.map(e=>e.target.store))))}read(e){return this.tx("newReader",e)}write(e,t=!0){return this.tx("newWriter",e,!0,t)}export(){return this.tx("newReader",async(...e)=>{const t={};for(const r of e)t[r.storeName]=await r.export();return t})}import(e,t,r){return r||(r="addOrChangeMany"),this.tx("newWriter",async(...a)=>{const n={};a=Array.from(new Map(a.map(e=>[e.storeName,e.asStore(!0)])).values());for(const i of a){const{storeName:a}=i,s=e[a];s&&(n[a]=await i[r](s,t))}if(t)return n},!0)}async tx(e,t,r,a){const{idbPro:n,schemas:i}=this,{factory:s}=n.schema,o=await n.openNativeDb();try{const c=o.transaction(this.storeNames,r?"readwrite":"readonly");try{const a=i.map(({storeSchema:t,target:r})=>{let a=c.objectStore(r.store);return r.index&&(a=a.index(r.index)),s[e]({storeSchema:t,target:a},n)});if(r){const e=await t(...a);return c.commit(),e}return await t(...a)}catch(e){throw!1!==a&&c.abort(),e}}finally{o.close()}}}class W extends T{direction;query;writable;parser;endsWithNull;preSkip;startKey;startPrimaryKey;constructor(e,r,a){if(super(e,r),!a)return;const{parser:n}=a;this.direction=a.direction,this.query=a.query,this.writable=!!a.writable,this.endsWithNull=!!a.endsWithNull,this.preSkip=a.preSkip,this.startKey=a.startKey,this.startPrimaryKey=a.startPrimaryKey,n&&(this.parser=t(n)?n:k[n])}async*[Symbol.asyncIterator](){const{parser:e,writable:t,endsWithNull:r}=this,{db:a,tx:n,target:i}=await this.tx(t);try{const a=await N(i,this);let s;if(e)for(;s=await y(a);){const{control:t,value:r}=await e(s);if(t||(yield r),t===D)break;s.continue()}else{let e=!1;const t=()=>{e=!0};for(;!e&&(s=await y(a));)yield{cursor:s,end:t}}t&&n?.commit(),r&&!s&&(yield null)}finally{a?.close()}}}function z(e,a,n,i){const s=r(e)?e:{};return t(e)?s.fn=e:A(e)&&(s.query=e),t(a)?s.fn=a:a&&(s.direction=a),n&&(s.direction=n),i?s.limit=i:s.limit||(s.limit=1e3),s.maxEmptyChecks||(s.maxEmptyChecks=2e4),s}async function _(e,t,r){t.size||(t.size=100),t.nextSkip||(t.nextSkip=0);const{query:n,direction:i,total:s,maxEmptyChecks:o,fn:c}=t;return await e.batchRead(async e=>(s||(t.total=await e.count({query:n,direction:i,maxEmptyChecks:o,fn:c}),t.pages=Math.ceil(t.total/t.size)),t.total<1?{info:a(t),rows:[]}:c?await async function(e,t,r){t.maxEmptyChecks||(t.maxEmptyChecks=2e4);const{page:a,query:n,direction:i,nextSkip:s}=t,{keyPath:o}=e.storeSchema;return 1===a?await U(e,await N(e.target,{query:n,direction:i}),t,o):r&&s&&a-r.page===1?await U(e,await N(e.target,{query:n,direction:i,preSkip:s}),t,o):await U(e,await N(e.target,{query:n,direction:i}),t,o,!0)}(e,t,r):await async function(e,t){const{keyPath:r}=e.storeSchema,{page:n,query:i,direction:s,size:o,mapper:c}=t,u=(n-1)*o,d=await e.filter({query:i,preSkip:u,direction:s,limit:o,mapper:K(c,r,!0)});return t.nextSkip=u+d.length,{info:a(t),rows:d}}(e,t)))}async function U({storeSchema:{defaultGetMapper:e}},t,r,n,i){const{page:s,size:o,total:c,maxEmptyChecks:u,fn:d}=r,h=K(r.mapper||e,n,!0),m=[],l=(s-1)*r.size;if(l>=c)return{info:a(r),rows:[]};let f=0;return await new Promise(async(e,r)=>{let a=0,n=0;const s=async()=>{const{result:r}=t;if(!r)return e();let{value:n,primaryKey:i}=r;if(await d(n,i,f)?(a=0,m.push(h(n,i,f))):a++,m.length>=o||a>=u)return e();f++,r.continue()};t.onerror=()=>r(t.error),t.onsuccess=i?async()=>{const{result:r}=t;if(!r)return e();let{value:i,primaryKey:o}=r;if(await d(i,o,f)?(a=0,n++):a++,n>=l||a>=u)return f=a=0,t.onsuccess=s,void r.continue();r.continue(),f++}:s}),f&&(r.nextSkip+=f+1),{info:a(r),rows:m}}class G extends T{all(e,t){const a={};return n(t)&&(a.limit=t),A(e)?a.query=e:r(e)&&Object.assign(a,e),this.tx(!1,e=>y(e.getAll(C(a.query),a.limit||1e3)))}async count(e,t,r){const a=z(e,t,r),{query:n,direction:i,fn:s}=a;if(!s)return await this.tx(!1,e=>y(e.count(C(n))));const{maxEmptyChecks:o}=a,c=s;let u=0,d=0,h=0;return await this.openCursor({query:n,direction:i,fn:e=>{if(c(e.value,e.primaryKey,h++))u++,d=0;else if(++d>=o)return!1;e.continue()}}),u}get(e){return this.tx(!1,t=>y(t.get(C(e))))}getMany(e,t){return this.batchRead(async r=>{const a=await i(e,e=>r.get(e));return t?a.filter(e=>e):a})}getRange(e,t){return this.forEach({query:e,direction:t},!0)}async getRangeMany(e,t,r){return(await this.batchRead(r=>i(e,e=>r.getRange(e,t)))).flat()}index(e,t){let{target:r}=this;return r instanceof IDBIndex&&(r=r.objectStore),r instanceof IDBObjectStore?(r=r.index(e),this.createOperator(r,t)):this.idbPro.store(r.store,e)}asStore(e){let{target:t}=this;if(t instanceof IDBObjectStore)return this;if(t instanceof IDBIndex)t=t.objectStore;else{if(!("index"in t))return this;t={store:t.store}}return this.createOperator(t,e)}batchRead(e){return F(this.target)?e(this):this.tx(!1,t=>e(this.idbPro.schema.factory.newReader({storeSchema:this.storeSchema,target:t},this.idbPro)))}iterator(e,t){const a={};return s(t)&&(a.direction=t),A(e)?a.query=e:r(e)&&Object.assign(a,e),new W({storeSchema:this.storeSchema,target:this.target},this.idbPro,{...a,parser:"value"})}async filter(e,t,r,a){const n=z(e,t,r,a),{maxEmptyChecks:i,limit:s,fn:o}=n,{keyPath:c,defaultGetMapper:u}=this.storeSchema,d=K(n.mapper||u,c,!0);if(!o)return await this.forEach({...n,mapper:d,fn:(e,t,r)=>{if(r>=s-1)return{control:I}}},!0);let h=0;return this.forEach({...n,mapper:d,fn:(e,t,r,a)=>(e=d(e,t,r),o(e,t,r)?(h=0,a.length>=s-1?{control:I}:void 0):++h>=i?{control:D}:{control:O})},!0)}async find(e,t,r){const[a]=await this.filter(e,t,r,1);return a}async page(e,t){const r={...e};return r.page=t||e?.page||1,_(this,r,e)}nextPage(e){return this.page(e,e.page+1)}export(e,t){const r=z(e,t),{keyPath:a,exportMapper:n,name:i,defaultGetMapper:s}=this.storeSchema;if(!a&&Array.isArray(n))throw new Error(`When store [ ${i} ] keyPath does not exist, exportMapper does not support string[].`);return r.direction="next",r.mapper=K(n||s,a,!0),r.limit=r.maxEmptyChecks=Number.MAX_SAFE_INTEGER,this.filter(r)}asMap(){let{target:e}=this;return e instanceof IDBIndex?e=e.objectStore:e instanceof IDBObjectStore||(e={store:e.store}),this.factory.newDbMap({target:e},this.idbPro)}createOperator(e,t){const{idbPro:r}=this,a=this.storeSchema,n={storeSchema:Object.isFrozen(a)?a:void 0,target:e};return t?this.factory.newWriter(n,r):this.factory.newReader(n,r)}}function J(e,t){if(!Array.isArray(e))return{[e]:t};const r={},a=e;for(let e=0;e<a.length;e++)r[a[e]]=t[e];return r}function L(e,t){if(!Array.isArray(e))return t[e];const r=[];for(const a of e){if(!t[a])return;r.push(t[a])}return r}function X(e,t){if(!t||!(t instanceof Object)||Array.isArray(t))return t;const{addedTimeField:r,updatedTimeField:a,updatedCountField:i,softDeletedField:s}=e;return t={...t},r?.name&&!n(t[r.name])&&(t[r.name]=Date.now()),a?.name&&!n(t[a.name])&&(t[a.name]=Date.now()),s?.name&&!n(t[s.name])&&(t[s.name]=0),i?.name&&(t[i.name]=0),t}function H(e,t,r){if(!t||!(t instanceof Object)||Array.isArray(t))return t;const{updatedTimeField:a,updatedCountField:n}=e;return t={...r,...t},a.name&&(t[a.name]=Date.now()),n.name&&(t[n.name]=(t[n.name]||0)+1),t}class Q extends G{add(e){return this.changeByPk({record:e,fn:async(e,t,r,a,n)=>{const{storeSchema:i}=this;return r=X(i,r),n?[{...r,...J(n,await y(e.add(r)))},t]:[r,await y(e.add(r,t))]}})}addMany(e,t){return this.batchWrite(r=>t?i(e,e=>r.add(e)):o(e,e=>r.add(e)),!0)}addOrSkip(e){return this.batchWrite(async t=>{const{keyPath:r,defaultGetMapper:a}=t.storeSchema,{key:n,value:i}=r?{key:L(r,e),value:e}:P(e);if(n){const e=await y(t.nativeStore.get(n));if(e)return K(a,r)?.(e,n)}if(t.target instanceof IDBIndex){const{keyPath:r}=t,a=L(r,i);if(!a)return t.add(e);let n=await t.find(a);if(n)return n}return t.add(e)})}addOrSkipMany(e,t){return this.batchWrite(r=>t?i(e,e=>r.addOrSkip(e)):o(e,e=>r.addOrSkip(e)),!0)}replace(e){return this.changeByPk({record:e,getOld:!0,fn:async(e,t,r,a,n)=>{const{storeSchema:i}=this,{updatedTimeField:s,updatedCountField:o,addedTimeField:c}=i;return r=a?H(i,r,{[s.name]:a[s.name],[o.name]:a[o.name],[c.name]:a[c.name]}):X(i,r),n?[{...r,...J(n,await y(e.put(r)))},t]:[r,await y(e.put(r,t))]}})}replaceMany(e,t){return this.batchWrite(r=>t?i(e,e=>r.replace(e)):o(e,e=>r.replace(e)),!0)}change(e,t){return this.changeByPk({record:e,getOld:!0,requiredOld:t,requiredPk:t,fn:async(e,t,r,a,n)=>{const{storeSchema:i}=this;if(a)return r=H(i,r,a),n?[{...r,...J(n,await y(e.put(r)))},t]:[r,await y(e.put(r,t))]}})}changeMany(e,t){const{returns:r,throwIfMissing:a}=c(t)?{returns:t}:t||{};return this.batchWrite(t=>r?i(e,e=>t.change(e,a)):o(e,e=>t.change(e,a)),!0)}addOrChange(e){return this.changeByPk({record:e,getOld:!0,fn:async(e,t,r,a,n)=>{const{storeSchema:i}=this;return a?(r=H(i,r,a),n?[{...r,...J(n,await y(e.put(r)))},t]:[r,await y(e.put(r,t))]):(r=X(i,r),n?[{...r,...J(n,await y(e.add(r)))},t]:[r,await y(e.add(r,t))])}})}addOrChangeMany(e,t){return this.batchWrite(r=>t?i(e,e=>r.addOrChange(e)):o(e,e=>r.addOrChange(e)),!0)}delete(e,t){return this.changeByPk({pk:e,getOld:t,fn:(e,r,a,n)=>{if(e.delete(r),t)return[n,r]}})}deleteMany(e,t){return this.batchWrite(r=>t?i(e,e=>r.delete(e,!0)):o(e,e=>r.delete(e)),!0)}deleteRange(e,t){const{returns:r,physical:a,direction:n}=c(t)?{returns:t}:t||{},{name:i}=this.storeSchema.softDeletedField||{};return this.cursor({query:e,direction:n,fn:e=>a||!i?{modify:v}:(e[i]=1,{modify:x})},r)}deleteRangeMany(e,t){const r=c(t)?{returns:t}:t;return this.batchWrite(t=>r?.returns?i(e,e=>t.deleteRange(e,r)):o(e,e=>t.deleteRange(e,r)),!0)}changeRange(e,t){let{direction:r="next",query:a,newValue:n}="newValue"in e?e:{newValue:e};if(a||(a=L(this.keyPath,n)),!a)throw new Error(`query is required:${JSON.stringify(e)}`);return this.cursor({query:a,direction:r,fn:e=>e instanceof Object?{modify:x,value:{...e,...n}}:{modify:x,value:n}},t)}changeRangeMany(e,t){return this.batchWrite(r=>t?i(e,e=>r.changeRange(e,t)):o(e,e=>r.changeRange(e,t)),!0)}cursor(e,r){return(e=t(e)?{fn:e}:e||{}).fn?r?this.cursorResult(e,!0):this.cursorVoid(e,!0):new W(this,this.idbPro)}batchWrite(e,t){const{target:r}=this;if(F(r))try{return e(this)}catch(e){throw!1!==t&&(r instanceof IDBIndex?r.objectStore:r).transaction.abort(),e}return this.tx(!0,t=>e(this.idbPro.schema.factory.newWriter({storeSchema:this.storeSchema,target:t},this.idbPro)),t)}changeByPk({pk:e,record:t,fn:r,requiredPk:a,getOld:n,requiredOld:i,saveMapper:s,getMapper:o}){const{storeSchema:c}=this,{keyPath:u,defaultSaveMapper:d,defaultGetMapper:h}=c;return t&&(s||d)&&(t=K(s||d,u)?.(t)),this.batchWrite(async s=>{let c,d=t;if(e)c=C(e);else if(u)c=L(u,t);else{const{key:e,value:r}=P(t);c=e,d=r}if(a&&!c)throw new Error(`key is required: ${JSON.stringify(t)}`);const m=c&&(n||i)?await y(s.nativeStore.get(c)):void 0;if(i&&!m)throw new Error(`record not found: ${JSON.stringify(t)}`);const l=await r(s.nativeStore,c,d,m,u);if(l)return K(o||h,u)?.(l[0],l[1])})}}class Y extends T{get size(){return this.tx(!1,e=>y(e.count()))}delete(e){return this.tx(!0,async(t,r)=>{r.delete(e)})}batch(e){const{idbPro:t,storeSchema:r,factory:a}=this;return this.tx(!0,async(n,i)=>await e(a.newDbMap({storeSchema:r,target:i},t)))}asStore(e){const{factory:t}=this.idbPro.schema;return e?t.newWriter(this,this.idbPro):t.newReader({target:this.target},this.idbPro)}entries(){return new W({target:this.target},this.idbPro,{parser:"keyValue"})}async get(e,t){return await this.tx(!1,t=>y(t.get(e)))||t}getMany(e){return this.tx(!1,async t=>{const r=[];for(const a of e)r.push(await y(t.get(a)));return r})}async has(e){return!!await this.get(e)}keys(){return new W({storeSchema:this.storeSchema,target:this.target},this.idbPro,{parser:"key"})}set(e,t){return this.tx(!0,async(r,a)=>{await y(a.put(t,e))})}setMany(e){return this.tx(!0,async(t,r)=>{for(const[t,a]of e)r.put(a,t)})}values(){return new W({storeSchema:this.storeSchema,target:this.target},this.idbPro,{parser:"value"})}}function Z(e,t){if(e==t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}return!1}const ee=({stores:e,schema:t})=>{const r=t.storeSchemas;let a="";for(const t of e){const e=r.find(e=>e.name===t.name);if(e){if(!Z(t.keyPath,e.keyPath)){a=`store [ ${t.name} ] keyPath not equal,schema.keyPath:${e.keyPath},store.keyPath:${t.keyPath}[]`;break}if(!t.autoIncrement!=!e.autoIncrement){a=`store [ ${t.name} ] autoIncrement not equal`;break}}}return!a||`The existing database is inconsistent with the definition and cannot be corrected: ${a}`},te=async e=>{let t=ee(e);return s(t)||(t=re(e)),t},re=({stores:e,schema:t})=>{const r=t.storeSchemas,a=e.map(e=>e.name);let n="";const i=r.map(e=>e.name).filter(e=>!a.includes(e));if(i.length)n=`store [ ${i.join(",")} ] not exist`;else for(const t of e){const e=r.find(e=>e.name===t.name);if(e&&(n=ae(t,Array.from(t.indexNames),e.indexSchemas),n))break}return!n||`The existing database Store index is inconsistent with the definition and requires a database version upgrade to be fixed: ${n}`};function ae(e,t,r){if(t.length!==r.length)return`store [ ${e.name} ] index count not equal`;for(const a of t){const t=r.find(e=>e.name===a);if(!t)return`store [ ${e.name} ] index [ ${a} ] not exist`;const n=e.index(a);if(!t.unique!=!n.unique)return`store [ ${e.name} ] index [ ${a} ] unique not equal`;if(!t.multiEntry!=!n.multiEntry)return`store [ ${e.name} ] index [ ${a} ] multiEntry not equal`;if(!Z(t.keyPath,n.keyPath))return`store [ ${e.name} ] index [ ${a} ] keyPath not equal`}return""}class ne{upgradeContext;storeSchema;nativeStore;#a;constructor(e,t,r){this.upgradeContext=e,this.storeSchema=t,this.nativeStore=r}get writer(){return this.#a||(this.#a=this.upgradeContext.dbSchema.factory?.newWriter({target:this.nativeStore,storeSchema:this.storeSchema}))}add(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.addMany(t,r):Promise.resolve()}addOrChange(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.addOrChangeMany(t,r):Promise.resolve()}async call(e,t){if(this.upgradeContext.versionIn(e))return await t(this.writer,this.upgradeContext)}replace(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.replaceMany(t,r):Promise.resolve()}}const ie=Object.freeze({newDataOperators:(e,t)=>new V(t,e),newDbMap:(e,t)=>new Y(e,t),newReader:(e,t)=>new G(e,t),newStoreUpgradeable:(e,t,r)=>new ne(r,t,e),newWriter:(e,t)=>new Q(e,t)});function se(e,t,a,n){const i=function(e,t,a){if(!1===e)return!1;if(s(e))return{name:e};if(r(e)){const r=e;return c(r.name)&&(r.name=t),e}if(!0===e||a)return{name:t};return!1}(t,a,n);if(!i)return i;const o=i;if(!1!==o.isIndexed){o.isIndexed||(o.isIndexed=!0);const{name:t}=o,r=e.indexSchemas;r.some(e=>e===t||e.name===t)||r.push(t)}return o}function oe(e,t){let r=s(e)?{name:e}:e;return t&&(r={...t,...r}),r.indexSchemas||(r.indexSchemas=[]),function(e){Object.isFrozen(e)||(e.addedTimeField=se(e,e.addedTimeField,"added_at",!0),e.updatedTimeField=se(e,e.updatedTimeField,"updated_at",!0),e.updatedCountField=se(e,e.updatedCountField,"updated_count",!1),e.softDeletedField=se(e,e.softDeletedField,"deleted",!1))}(r),Object.isFrozen(r)||(r.indexSchemas=r.indexSchemas.map(ce)),function(e){if(!e.keyPath&&e.defaultData?.length)for(const t of e.defaultData)if(!Array.isArray(t)&&!("value"in t))throw new Error(`When \`defaultData\` must contain \`value\` fields or be an array:${JSON.stringify(t)}`)}(r),r}function ce(e){const t=s(e)?{name:e}:e;return t.keyPath||(t.keyPath=t.name),t}const ue=e=>{const{versionDiffValidate:t,versionSameValidate:r,factory:a}=e;return e.storeSchemas||(e.storeSchemas=[]),e.storeTemplate||(e.storeTemplate={...R}),!t&&!1!==t&&(e.versionDiffValidate=ee),!r&&!1!==r&&(e.versionSameValidate=te),a?a!==ie&&(e.factory={...ie,...a}):e.factory=ie,e.storeSchemas=e.storeSchemas.map(t=>oe(t,e.storeTemplate)),e};function de(e,t){(function(e,t){return e.unique===t.unique&&e.multiEntry===t.multiEntry&&Z(t.keyPath,e.keyPath)})(e.index(t.name),t)||(e.deleteIndex(t.name),he(e,t))}function he(e,t){try{e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multiEntry})}catch{throw new Error(`store [ ${e.name} ] index [ ${t.name} ] create error: ${JSON.stringify(t)}`)}}function me(e,t){return e.database.objectStoreNames.contains(t.name)?function(e,t){const{indexSchemas:r}=e,a=t.indexNames,n=r.map(e=>e.name);for(const e of Array.from(a))n.includes(e)||t.deleteIndex(e);for(const e of r)a.contains(e.name)?de(t,e):he(t,e);return t}(t,e.transaction?.objectStore(t.name)):function(e,t){const r=t.createObjectStore(e.name,{keyPath:e.keyPath,autoIncrement:e.autoIncrement});for(const t of e.indexSchemas)he(r,t);return r}(t,e.database)}class le{database;newVersion;oldVersion;dbSchema;transaction;#n={};constructor(e){this.database=e.database,this.newVersion=e.newVersion,this.oldVersion=e.oldVersion,this.dbSchema=e.dbSchema,this.transaction=e.transaction}deleteStoreIfExists(e){const t=this.database;t.objectStoreNames.contains(e)&&t.deleteObjectStore(e)}destroy(){try{u(this.#n)}finally{for(const e of Object.keys(this.#n))delete this.#n[e]}}store(e){if(e in this.#n)return this.#n[e];const{factory:t}=this.dbSchema,{storeSchemas:r}=this.dbSchema,a=r.find(t=>t.name===e),n=me(this,a);return this.#n[e]=t.newStoreUpgradeable(n,a,this)}versionIn({oldMin:e,oldMax:t,newMax:r,newMin:a}){if(void 0===t&&void 0===r&&void 0===e&&void 0===a)throw new Error(`versionIn bounds must not be empty ${JSON.stringify({oldMax:t,newMax:r,oldMin:e,newMin:a})}`);if(t<e)throw new Error(`oldMax (${t}) cannot be less than oldMin (${e})`);if(r<a)throw new Error(`newMax (${r}) cannot be less than newMin (${a})`);const{oldVersion:n,newVersion:i}=this;return!(void 0!==e&&n<e||void 0!==t&&n>t||void 0!==a&&i<a)&&!(void 0!==r&&i>r)}}function fe(e,t){let{store:r,index:a}=e;const{storeTemplate:n}=t,{storeSchemas:i=[]}=t,o=s(r)?r:r.name,c=i.findIndex(e=>e===o||e.name===o),u=c>-1&&i[c];let d;d=s(r)?u||o:!u||s(u)||r===u?r:{...u,...r},(a||u?.indexSchemas?.length||r?.indexSchemas?.length)&&(s(d)&&(d={name:d}),d.indexSchemas=function(e,t,r){r&&t.push(r);for(const r of t){const t=s(r)?r:r.name,a=e.findIndex(e=>e===t||e.name===t);if(a>-1){const t=e[a];s(t)?e[a]=r:s(r)||(e[a]=Object.assign(t,r))}else e.push(r)}return e}(u.indexSchemas||[],r.indexSchemas||[],a));const h=oe(d,n);c>-1?i[c]=h:i.push(h),t.storeSchemas=i;const m={store:o};return a&&(m.index=s(a)?a:a.name),{target:m}}const ye=Object.assign({name:"",addedTimeField:!1,autoIncrement:!1,indexSchemas:[],keyPath:void 0,softDeletedField:!1,updatedCountField:!1,updatedTimeField:!1});class pe{static#i;#s;#o;#c={};constructor(e,t){this.#s=e=s(e)?{name:e}:e,Array.isArray(e.storeSchemas)||(e.storeSchemas=[]),r(e.storeTemplate)||(e.storeTemplate=R),t&&(this.#o=!0)}static get defaultDb(){return this.#i||(this.#i=new pe(S))}get initialized(){return Object.isFrozen(this.#s)}get schema(){return this.#s}get storeNames(){return Array.from(new Set(this.#s.storeSchemas.map(e=>s(e)?e:e.name)))}get factory(){return this.#s.factory||(this.#s.factory=ie)}static releaseDefaultDB(){this.#i=void 0}static async openExistDb(e){const{generateDbSchema:t}=await Promise.resolve().then(function(){return Pe});return new pe(await t(e))}static store(e,t){return pe.defaultDb.store(e,t)}static stores(e){return pe.defaultDb.stores(e)}static map(e,t){return pe.defaultDb.map(e,t)}async openNativeDb(){const e=this.#s=a(this.initSchema());await this.#u();const{name:r,version:n}=e;return await g({name:r,version:n,onupgradeneeded:(r,a,n)=>async function(e,r,a,n){const{storeSchemas:i,beforeUpgrade:s,afterUpgrade:o,version:c}=e,{newVersion:u=c,oldVersion:h}=a,{transaction:m}=n,l=new le({database:r,newVersion:u,oldVersion:h,dbSchema:e,transaction:m});try{const e=[];if(t(s))try{await s(l)}catch(t){e.push(t)}for(const t of i.map(e=>e.name))try{l.store(t)}catch(t){e.push(t)}for(const{name:t,defaultData:r}of i)if(r)try{await l.store(t).add({oldMax:0},r)}catch(t){e.push(t)}for(const{name:t,versionData:r}of i)if(r)for(const{version:a,data:n,use:i="addOrChange"}of r)try{await l.store(t)[i](a,n)}catch(t){e.push(t)}for(const{name:t,storeDefined:r}of i)try{await(r?.(l.store(t)))}catch(t){e.push(t)}if(t(o))try{await o(l)}catch(t){e.push(t)}if(!e.length)return;throw 1===e.length?e[0]:new AggregateError(e,"Database upgrade error")}finally{d(l)}}(e,r,a,n)})}store(e,t){const r=e.store?e:{store:e};return r.store||(r.store=e),r.index||(r.index=t),this.factory.newWriter(fe(r,this.schema),this)}stores(e){const{schema:t}=this,r=e.map(e=>fe(s(e)?{store:e}:e,t));return this.factory.newDataOperators(r,this)}initSchema(){if(this.initialized)return this.#s;const{validateSchemaWithDefaults:e=ue}=this.#s;return this.#s=e(this.#s)}async traceSchema(e){await h(this.schema,e)}map(e,t){const r=s(e)?e:s(t)?t:b;Array.isArray(e)&&(t=e);const{storeSchemas:a}=this.schema;return a.find(e=>e.name===r||e===r)||a.push({...ye,name:r,defaultData:t}),this.factory.newDbMap({target:{store:r}},this)}export(){return this.stores(this.storeNames).export()}import(e,t,r){return this.stores(this.storeNames).import(e,t,r)}getStoreSchema(e){if(e in this.#c)return this.#c[e];const t=this.schema.storeSchemas.findIndex(t=>t===e||t.name===e);let r=this.schema.storeSchemas[t];return this.initialized?this.#c[e]=r:s(r)&&(this.schema.storeSchemas[t]=r={name:r}),r}async#u(){let e=this.#o;if(void 0===e&&(e=this.#o=await async function(e){const{name:t,version:r}=e,a=await p(t);if(!a)return!0;const{versionDiffValidate:n,versionSameValidate:i}=e,o=await g(t);try{if(e.version<o.version)return"The existing database version is greater than the current version";const c=void 0===e.version||o.version===e.version?i:n;if(!c)return!0;const u=Array.from(o.objectStoreNames);if(u.length<1)return`The existing database [ ${t} ] is empty`;const d=await w(o,u),h=await c({schema:e,db:o,stores:d});if(s(h)||r!==a.version)return h}finally{o?.close()}return!0}(this.#s)),!0===e)return!0;if(s(e))throw new Error(e)}}function ge(e,t){return pe.defaultDb.store(e,t)}function we(e,t){return pe.defaultDb.map(e,t)}function Se(e){return pe.defaultDb.stores(e)}function be(){pe.releaseDefaultDB()}function xe(e,t){const r=Array.from(e.indexNames).map(t=>e.index(t)),a=[],n=[];for(const{name:e,keyPath:t,unique:i,multiEntry:s}of r)Array.isArray(t)?n.push(...t):n.push(t),a.push({name:e,keyPath:t,unique:i,multiEntry:s});const i=new Set(n);return{indexSchemas:a,addedTimeField:ve(t.addedTimeField,i),updatedTimeField:ve(t.updatedTimeField,i),updatedCountField:ve(t.updatedCountField,i),softDeletedField:ve(t.softDeletedField,i)}}function ve(e,t){return!!t.has(e)&&{name:e,isIndexed:!1}}async function ke(e,t){if(!await p(e))throw new Error(`db [ ${e} ] not exist`);let{asString:r,specialFields:a=$,dataExportTarget:n}=t||{};!0===r&&(r=160),isNaN(r)||r<1&&(r=1);let i=await function(e,t){return g(e,async function(e){const r=Array.from(e.objectStoreNames),a=e.transaction(r,"readonly");try{return{name:e.name,version:e.version,storeSchemas:r.map(e=>function(e,t){const{name:r,keyPath:a,autoIncrement:n}=e;return{name:r,keyPath:a,autoIncrement:n,...xe(e,t)}}(a.objectStore(e),t))}}finally{a.abort()}})}(e,a);return n&&await async function(e,t){const r=await new pe(l(e),!0).export();for(const a of e.storeSchemas){const n=r[a.name];n?.length&&("defaultData"===t?a.defaultData=n:"versionData"===t&&(a.versionData||(a.versionData=[]),a.versionData.push({version:{oldMax:e.version},data:n})))}return e}(i,n),r?await m({rootData$:i,spaceEffectiveLength:r}):i}var Pe=Object.freeze({__proto__:null,generateDbSchema:ke});export{D as Break,O as Continue,M as ContinueKey,E as ContinuePrimaryKey,T as DataOperationBase,V as DataOperators,G as DataReader,Q as DataWriter,W as DbIterator,k as DbIteratorParsers,Y as DbMap,v as Delete,I as Finished,pe as IDbPro,q as NextKey,j as NextPrimaryKey,x as Save,ne as StoreUpgradeable,le as UpgradeContext,we as dbMap,ge as dbStore,Se as dbStores,$ as defaultSpecialFields,R as defaultStoreSchemaTemplate,ke as generateDbSchema,A as isIDbQuery,F as isNativeTarget,P as parseDbNoneKeyPathRecord,C as parseIDbQuery,be as releaseDefaultDB,ue as validateSchemaWithDefaults,ee as versionDiffValidate,te as versionSameValidate};
|
|
1
|
+
import{copyFields as e,isFunction as t,isObject as r,deepFreeze as a,isNumber as n,asyncMap as i,isString as s,asyncForEach as o,isBoolean as c,destroyRecords as u,destroy as d,logJson as h,toJson as m,copyObject as l}from"gs-base";import{isDbQueryOrNull as f,requestDbResult as y,findExistDb as p,openDb as g,readTx as w,DefaultDbName as S,DefaultStorageStoreName as b}from"gs-idb-basic";const x=Symbol("save"),v=Symbol("delete"),k=Object.freeze({key:({primaryKey:e})=>({value:e}),value:({value:e})=>({value:e}),keyValue:({primaryKey:e,value:t})=>({value:[e,t]})});function P(e){if(Array.isArray(e))return{key:e[1],value:e[0]};if("value"in e){const{key:t,value:r}=e;return{key:t,value:r}}throw new Error(`not include value in invalid DBRecord:${JSON.stringify(e)}`)}const D=Symbol("break"),I=Symbol("finished"),O=Symbol("continue"),M=Symbol("continue key"),q=Symbol("next key"),E=Symbol("continue primary key"),j=Symbol("next primary key");function F(e){return e instanceof IDBObjectStore||e instanceof IDBIndex}const R=Object.freeze({keyPath:"id",autoIncrement:!0,addedTimeField:!0,updatedTimeField:!0}),$=Object.freeze({addedTimeField:"added_at",softDeletedField:"deleted",updatedCountField:"updated_count",updatedTimeField:"updated_at"}),B=e=>e instanceof Date?e.getTime():e;function C(e){if(f(e))return e;const t=e;if("lt"in t&&"gt"in t){if(B(t.gt)>B(t.lt))throw new Error(`Invalid IDBRange: gt (${t.gt}) cannot be greater than lt (${t.lt})`);return IDBKeyRange.bound(t.gt,t.lt,!0,!0)}if("lt"in t&&"gte"in t){if(B(t.gte)>B(t.lt))throw new Error(`Invalid IDBRange: gte (${t.gte}) cannot be greater than lt (${t.lt})`);return IDBKeyRange.bound(t.gte,t.lt,!1,!0)}if("lte"in t&&"gt"in t){if(B(t.gt)>B(t.lte))throw new Error(`Invalid IDBRange: gt (${t.gt}) cannot be greater than lte (${t.lte})`);return IDBKeyRange.bound(t.gt,t.lte,!0,!1)}if("lte"in t&&"gte"in t){if(B(t.gte)>B(t.lte))throw new Error(`Invalid IDBRange: gte (${t.gte}) cannot be greater than lte (${t.lte})`);return IDBKeyRange.bound(t.gte,t.lte,!1,!1)}return"lt"in t?IDBKeyRange.upperBound(t.lt,!0):"lte"in t?IDBKeyRange.upperBound(t.lte,!1):"gt"in t?IDBKeyRange.lowerBound(t.gt,!0):"gte"in t?IDBKeyRange.lowerBound(t.gte,!1):void 0}function A(e){return null!=C(e)}async function N(e,t,r){const{query:a,direction:n="prev",preSkip:i,startKey:s,startPrimaryKey:o}=t,c=e.openCursor(C(a),n);return i&&(await y(c)).advance(i),s&&(o?(await y(c)).continuePrimaryKey(s,o):(await y(c)).continue(s)),c}function K(r,a,n){return Array.isArray(r)?t=>e({},t,r):t(r)?r:a?e=>e:n?(e,t)=>[e,t]:(e,t)=>({key:e,value:t})}class T{idbPro;target;#e;constructor(e,t){this.idbPro=t,this.#e=e.storeSchema,this.target=e.target,F(e.target)&&(this.tx=this.#t)}get storeName(){return this.nativeStore?.name||this.target.store}get storeSchema(){if(this.#e)return this.#e;const e=this.idbPro.getStoreSchema(this.storeName);return Object.isFrozen(e)&&(this.#e=e),e}get factory(){return this.idbPro.factory}get nativeStore(){const{target:e}=this;return e instanceof IDBObjectStore?e:e instanceof IDBIndex?e.objectStore:void 0}get keyPath(){const{target:e}=this;if(F(e))return e.keyPath;const{storeSchema:t}=this,{index:r}=e;return r?t.indexSchemas.find(e=>e.name===r)?.keyPath:t.keyPath}async forEach(e,r){return e=t(e)?{fn:e}:e,r?this.cursorResult(e,!1):this.cursorVoid(e,!1)}async tx(e,t,r){let{target:a}=this;const{store:n,index:i}=a,s=await this.idbPro.openNativeDb();let o,c;try{o=s.transaction(n,!0===e?"readwrite":"readonly"),a=c=o.objectStore(n),i&&(a=a.index(i))}catch(e){throw s.close(),e}if(!t)return Object.freeze({db:s,tx:o,nativeStore:c,target:a});try{if(!0===e){const e=await t(a,c);return o.commit(),e}return t(a)}catch(e){throw!1!==r&&o.abort(),e}finally{s.close()}}openCursor(e,t){return this.tx(t,t=>new Promise(async(r,a)=>{const{fn:n}=e,i=await N(t,e);i.onsuccess=async()=>{i.result?!1===await n(i.result)&&r():r()},i.onerror=()=>a(i.error)}))}cursorVoid({query:e,direction:t,preSkip:a,startKey:n,startPrimaryKey:i,fn:s},o){let c=0;return this.openCursor({query:e,direction:t,preSkip:a,startKey:n,startPrimaryKey:i,fn:async e=>{const{value:t,primaryKey:a}=e,n=await s(t,a,c++),{control:i,key:u,primaryKey:d,modify:h,value:m}=r(n)?n:{control:n};switch(o&&(h===x?e.update(m||t):h===v&&e.delete()),i){case D:return!1;case M:e.continue(u);break;case E:e.continuePrimaryKey(u,d);break;default:e.continue()}}},!0)}async cursorResult({query:e,direction:t,preSkip:r,startKey:a,startPrimaryKey:n,fn:i,mapper:s},o){const{keyPath:c,defaultGetMapper:u}=this.storeSchema,d=K(s||u,c),h=[];let m=0;return await this.openCursor({query:e,direction:t,preSkip:r,startKey:a,startPrimaryKey:n,fn:async e=>{const{value:t,primaryKey:r}=e,{control:a,value:n,key:s,primaryKey:c,modify:u}=await(i?.(t,r,m,h))||{};switch(o&&(u===x?e.update(n||t):u===v&&e.delete()),(!a||a===I||a===q||a===j)&&h.push(d(n||t,c||r,m)),a){case D:case I:return!1;case q:case M:e.continue(s);break;case j:case E:e.continuePrimaryKey(s,c);break;default:e.continue()}m++}},o),h}#t(e,t){const{target:r}=this,a=r instanceof IDBObjectStore?r:r.objectStore;return t?t(r,a):Object.freeze({nativeStore:a,target:r})}}class V{idbPro;schemas;#r;constructor(e,t){this.idbPro=e,this.schemas=t}get storeNames(){return this.#r||(this.#r=Array.from(new Set(this.schemas.map(e=>e.target.store))))}read(e){return this.tx("newReader",e)}write(e,t=!0){return this.tx("newWriter",e,!0,t)}export(){return this.tx("newReader",async(...e)=>{const t={};for(const r of e)t[r.storeName]=await r.export();return t})}import(e,t,r){return r||(r="addOrChangeMany"),this.tx("newWriter",async(...a)=>{const n={};a=Array.from(new Map(a.map(e=>[e.storeName,e.asStore(!0)])).values());for(const i of a){const{storeName:a}=i,s=e[a];s&&(n[a]=await i[r](s,t))}if(t)return n},!0)}async tx(e,t,r,a){const{idbPro:n,schemas:i}=this,{factory:s}=n.schema,o=await n.openNativeDb();try{const c=o.transaction(this.storeNames,r?"readwrite":"readonly");try{const a=i.map(({storeSchema:t,target:r})=>{let a=c.objectStore(r.store);return r.index&&(a=a.index(r.index)),s[e]({storeSchema:t,target:a},n)});if(r){const e=await t(...a);return c.commit(),e}return await t(...a)}catch(e){throw!1!==a&&c.abort(),e}}finally{o.close()}}}class W extends T{direction;query;writable;parser;endsWithNull;preSkip;startKey;startPrimaryKey;constructor(e,r,a){if(super(e,r),!a)return;const{parser:n}=a;this.direction=a.direction,this.query=a.query,this.writable=!!a.writable,this.endsWithNull=!!a.endsWithNull,this.preSkip=a.preSkip,this.startKey=a.startKey,this.startPrimaryKey=a.startPrimaryKey,n&&(this.parser=t(n)?n:k[n])}async*[Symbol.asyncIterator](){const{parser:e,writable:t,endsWithNull:r}=this,{db:a,tx:n,target:i}=await this.tx(t);try{const a=await N(i,this);let s;if(e)for(;s=await y(a);){const{control:t,value:r}=await e(s);if(t||(yield r),t===D)break;s.continue()}else{let e=!1;const t=()=>{e=!0};for(;!e&&(s=await y(a));)yield{cursor:s,end:t}}t&&n?.commit(),r&&!s&&(yield null)}finally{a?.close()}}}function z(e,a,n,i){const s=r(e)?e:{};return t(e)?s.fn=e:A(e)&&(s.query=e),t(a)?s.fn=a:a&&(s.direction=a),n&&(s.direction=n),i?s.limit=i:s.limit||(s.limit=1e3),s.maxEmptyChecks||(s.maxEmptyChecks=2e4),s}async function _(e,t,r){t.size||(t.size=100),t.nextSkip||(t.nextSkip=0);const{query:n,direction:i,total:s,maxEmptyChecks:o,fn:c}=t;return await e.batchRead(async e=>(s||(t.total=await e.count({query:n,direction:i,maxEmptyChecks:o,fn:c}),t.pages=Math.ceil(t.total/t.size)),t.total<1?{info:a(t),rows:[]}:c?await async function(e,t,r){t.maxEmptyChecks||(t.maxEmptyChecks=2e4);const{page:a,query:n,direction:i,nextSkip:s}=t,{keyPath:o}=e.storeSchema;return 1===a?await U(e,await N(e.target,{query:n,direction:i}),t,o):r&&s&&a-r.page===1?await U(e,await N(e.target,{query:n,direction:i,preSkip:s}),t,o):await U(e,await N(e.target,{query:n,direction:i}),t,o,!0)}(e,t,r):await async function(e,t){const{keyPath:r}=e.storeSchema,{page:n,query:i,direction:s,size:o,mapper:c}=t,u=(n-1)*o,d=await e.filter({query:i,preSkip:u,direction:s,limit:o,mapper:K(c,r,!0)});return t.nextSkip=u+d.length,{info:a(t),rows:d}}(e,t)))}async function U({storeSchema:{defaultGetMapper:e}},t,r,n,i){const{page:s,size:o,total:c,maxEmptyChecks:u,fn:d}=r,h=K(r.mapper||e,n,!0),m=[],l=(s-1)*r.size;if(l>=c)return{info:a(r),rows:[]};let f=0;return await new Promise(async(e,r)=>{let a=0,n=0;const s=async()=>{const{result:r}=t;if(!r)return e();let{value:n,primaryKey:i}=r;if(await d(n,i,f)?(a=0,m.push(h(n,i,f))):a++,m.length>=o||a>=u)return e();f++,r.continue()};t.onerror=()=>r(t.error),t.onsuccess=i?async()=>{const{result:r}=t;if(!r)return e();let{value:i,primaryKey:o}=r;if(await d(i,o,f)?(a=0,n++):a++,n>=l||a>=u)return f=a=0,t.onsuccess=s,void r.continue();r.continue(),f++}:s}),f&&(r.nextSkip+=f+1),{info:a(r),rows:m}}class G extends T{all(e,t){const a={};return n(t)&&(a.limit=t),A(e)?a.query=e:r(e)&&Object.assign(a,e),this.tx(!1,e=>y(e.getAll(C(a.query),a.limit||1e3)))}async count(e,t,r){const a=z(e,t,r),{query:n,direction:i,fn:s}=a;if(!s)return await this.tx(!1,e=>y(e.count(C(n))));const{maxEmptyChecks:o}=a,c=s;let u=0,d=0,h=0;return await this.openCursor({query:n,direction:i,fn:e=>{if(c(e.value,e.primaryKey,h++))u++,d=0;else if(++d>=o)return!1;e.continue()}}),u}get(e){return this.tx(!1,t=>y(t.get(C(e))))}getMany(e,t){return this.batchRead(async r=>{const a=await i(e,e=>r.get(e));return t?a.filter(e=>e):a})}getRange(e,t){return this.forEach({query:e,direction:t},!0)}async getRangeMany(e,t,r){return(await this.batchRead(r=>i(e,e=>r.getRange(e,t)))).flat()}index(e,t){let{target:r}=this;return r instanceof IDBIndex&&(r=r.objectStore),r instanceof IDBObjectStore?(r=r.index(e),this.createOperator(r,t)):this.idbPro.store(r.store,e)}asStore(e){let{target:t}=this;if(t instanceof IDBObjectStore)return this;if(t instanceof IDBIndex)t=t.objectStore;else{if(!("index"in t))return this;t={store:t.store}}return this.createOperator(t,e)}batchRead(e){return F(this.target)?e(this):this.tx(!1,t=>e(this.idbPro.schema.factory.newReader({storeSchema:this.storeSchema,target:t},this.idbPro)))}iterator(e,t){const a={};return s(t)&&(a.direction=t),A(e)?a.query=e:r(e)&&Object.assign(a,e),new W({storeSchema:this.storeSchema,target:this.target},this.idbPro,{...a,parser:"value"})}async filter(e,t,r,a){const n=z(e,t,r,a),{maxEmptyChecks:i,limit:s,fn:o}=n,{keyPath:c,defaultGetMapper:u}=this.storeSchema,d=K(n.mapper||u,c,!0);if(!o)return await this.forEach({...n,mapper:d,fn:(e,t,r)=>{if(r>=s-1)return{control:I}}},!0);let h=0;return this.forEach({...n,mapper:d,fn:(e,t,r,a)=>o(e,t,r)?(h=0,a.length>=s-1?{control:I}:void 0):++h>=i?{control:D}:{control:O}},!0)}async find(e,t,r){const[a]=await this.filter(e,t,r,1);return a}async page(e,t){const r={...e};return r.page=t||e?.page||1,_(this,r,e)}nextPage(e){return this.page(e,e.page+1)}export(e,t){const r=z(e,t),{keyPath:a,exportMapper:n,name:i,defaultGetMapper:s}=this.storeSchema;if(!a&&Array.isArray(n))throw new Error(`When store [ ${i} ] keyPath does not exist, exportMapper does not support string[].`);return r.direction="next",r.mapper=K(n||s,a,!0),r.limit=r.maxEmptyChecks=Number.MAX_SAFE_INTEGER,this.filter(r)}asMap(){let{target:e}=this;return e instanceof IDBIndex?e=e.objectStore:e instanceof IDBObjectStore||(e={store:e.store}),this.factory.newDbMap({target:e},this.idbPro)}createOperator(e,t){const{idbPro:r}=this,a=this.storeSchema,n={storeSchema:Object.isFrozen(a)?a:void 0,target:e};return t?this.factory.newWriter(n,r):this.factory.newReader(n,r)}}function J(e,t){if(!Array.isArray(e))return{[e]:t};const r={},a=e;for(let e=0;e<a.length;e++)r[a[e]]=t[e];return r}function L(e,t){if(!Array.isArray(e))return t[e];const r=[];for(const a of e){if(!t[a])return;r.push(t[a])}return r}function X(e,t){if(!t||!(t instanceof Object)||Array.isArray(t))return t;const{addedTimeField:r,updatedTimeField:a,updatedCountField:i,softDeletedField:s}=e;return t={...t},r?.name&&!n(t[r.name])&&(t[r.name]=Date.now()),a?.name&&!n(t[a.name])&&(t[a.name]=Date.now()),s?.name&&!n(t[s.name])&&(t[s.name]=0),i?.name&&(t[i.name]=0),t}function H(e,t,r){if(!t||!(t instanceof Object)||Array.isArray(t))return t;const{updatedTimeField:a,updatedCountField:n}=e;return t={...r,...t},a.name&&(t[a.name]=Date.now()),n.name&&(t[n.name]=(t[n.name]||0)+1),t}class Q extends G{add(e){return this.changeByPk({record:e,fn:async(e,t,r,a,n)=>{const{storeSchema:i}=this;return r=X(i,r),n?[{...r,...J(n,await y(e.add(r)))},t]:[r,await y(e.add(r,t))]}})}addMany(e,t){return this.batchWrite(r=>t?i(e,e=>r.add(e)):o(e,e=>r.add(e)),!0)}addOrSkip(e){return this.batchWrite(async t=>{const{keyPath:r,defaultGetMapper:a}=t.storeSchema,{key:n,value:i}=r?{key:L(r,e),value:e}:P(e);if(n){const e=await y(t.nativeStore.get(n));if(e)return K(a,r)?.(e,n)}if(t.target instanceof IDBIndex){const{keyPath:r}=t,a=L(r,i);if(!a)return t.add(e);let n=await t.find(a);if(n)return n}return t.add(e)})}addOrSkipMany(e,t){return this.batchWrite(r=>t?i(e,e=>r.addOrSkip(e)):o(e,e=>r.addOrSkip(e)),!0)}replace(e){return this.changeByPk({record:e,getOld:!0,fn:async(e,t,r,a,n)=>{const{storeSchema:i}=this,{updatedTimeField:s,updatedCountField:o,addedTimeField:c}=i;return r=a?H(i,r,{[s.name]:a[s.name],[o.name]:a[o.name],[c.name]:a[c.name]}):X(i,r),n?[{...r,...J(n,await y(e.put(r)))},t]:[r,await y(e.put(r,t))]}})}replaceMany(e,t){return this.batchWrite(r=>t?i(e,e=>r.replace(e)):o(e,e=>r.replace(e)),!0)}change(e,t){return this.changeByPk({record:e,getOld:!0,requiredOld:t,requiredPk:t,fn:async(e,t,r,a,n)=>{const{storeSchema:i}=this;if(a)return r=H(i,r,a),n?[{...r,...J(n,await y(e.put(r)))},t]:[r,await y(e.put(r,t))]}})}changeMany(e,t){const{returns:r,throwIfMissing:a}=c(t)?{returns:t}:t||{};return this.batchWrite(t=>r?i(e,e=>t.change(e,a)):o(e,e=>t.change(e,a)),!0)}addOrChange(e){return this.changeByPk({record:e,getOld:!0,fn:async(e,t,r,a,n)=>{const{storeSchema:i}=this;return a?(r=H(i,r,a),n?[{...r,...J(n,await y(e.put(r)))},t]:[r,await y(e.put(r,t))]):(r=X(i,r),n?[{...r,...J(n,await y(e.add(r)))},t]:[r,await y(e.add(r,t))])}})}addOrChangeMany(e,t){return this.batchWrite(r=>t?i(e,e=>r.addOrChange(e)):o(e,e=>r.addOrChange(e)),!0)}delete(e,t){return this.changeByPk({pk:e,getOld:t,fn:(e,r,a,n)=>{if(e.delete(r),t)return[n,r]}})}deleteMany(e,t){return this.batchWrite(r=>t?i(e,e=>r.delete(e,!0)):o(e,e=>r.delete(e)),!0)}deleteRange(e,t){const{returns:r,physical:a,direction:n}=c(t)?{returns:t}:t||{},{name:i}=this.storeSchema.softDeletedField||{};return this.cursor({query:e,direction:n,fn:e=>a||!i?{modify:v}:(e[i]=1,{modify:x})},r)}deleteRangeMany(e,t){const r=c(t)?{returns:t}:t;return this.batchWrite(t=>r?.returns?i(e,e=>t.deleteRange(e,r)):o(e,e=>t.deleteRange(e,r)),!0)}changeRange(e,t){let{direction:r="next",query:a,newValue:n}="newValue"in e?e:{newValue:e};if(a||(a=L(this.keyPath,n)),!a)throw new Error(`query is required:${JSON.stringify(e)}`);return this.cursor({query:a,direction:r,fn:e=>e instanceof Object?{modify:x,value:{...e,...n}}:{modify:x,value:n}},t)}changeRangeMany(e,t){return this.batchWrite(r=>t?i(e,e=>r.changeRange(e,t)):o(e,e=>r.changeRange(e,t)),!0)}cursor(e,r){return(e=t(e)?{fn:e}:e||{}).fn?r?this.cursorResult(e,!0):this.cursorVoid(e,!0):new W(this,this.idbPro)}batchWrite(e,t){const{target:r}=this;if(F(r))try{return e(this)}catch(e){throw!1!==t&&(r instanceof IDBIndex?r.objectStore:r).transaction.abort(),e}return this.tx(!0,t=>e(this.idbPro.schema.factory.newWriter({storeSchema:this.storeSchema,target:t},this.idbPro)),t)}changeByPk({pk:e,record:t,fn:r,requiredPk:a,getOld:n,requiredOld:i,saveMapper:s,getMapper:o}){const{storeSchema:c}=this,{keyPath:u,defaultSaveMapper:d,defaultGetMapper:h}=c;return t&&(s||d)&&(t=K(s||d,u)?.(t)),this.batchWrite(async s=>{let c,d=t;if(e)c=C(e);else if(u)c=L(u,t);else{const{key:e,value:r}=P(t);c=e,d=r}if(a&&!c)throw new Error(`key is required: ${JSON.stringify(t)}`);const m=c&&(n||i)?await y(s.nativeStore.get(c)):void 0;if(i&&!m)throw new Error(`record not found: ${JSON.stringify(t)}`);const l=await r(s.nativeStore,c,d,m,u);if(l)return K(o||h,u)?.(l[0],l[1])})}}class Y extends T{get size(){return this.tx(!1,e=>y(e.count()))}delete(e){return this.tx(!0,async(t,r)=>{r.delete(e)})}batch(e){const{idbPro:t,storeSchema:r,factory:a}=this;return this.tx(!0,async(n,i)=>await e(a.newDbMap({storeSchema:r,target:i},t)))}asStore(e){const{factory:t}=this.idbPro.schema;return e?t.newWriter(this,this.idbPro):t.newReader({target:this.target},this.idbPro)}entries(){return new W({target:this.target},this.idbPro,{parser:"keyValue"})}async get(e,t){return await this.tx(!1,t=>y(t.get(e)))||t}getMany(e){return this.tx(!1,async t=>{const r=[];for(const a of e)r.push(await y(t.get(a)));return r})}async has(e){return!!await this.get(e)}keys(){return new W({storeSchema:this.storeSchema,target:this.target},this.idbPro,{parser:"key"})}set(e,t){return this.tx(!0,async(r,a)=>{await y(a.put(t,e))})}setMany(e){return this.tx(!0,async(t,r)=>{for(const[t,a]of e)r.put(a,t)})}values(){return new W({storeSchema:this.storeSchema,target:this.target},this.idbPro,{parser:"value"})}}function Z(e,t){if(e==t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}return!1}const ee=({stores:e,schema:t})=>{const r=t.storeSchemas;let a="";for(const t of e){const e=r.find(e=>e.name===t.name);if(e){if(!Z(t.keyPath,e.keyPath)){a=`store [ ${t.name} ] keyPath not equal,schema.keyPath:${e.keyPath},store.keyPath:${t.keyPath}[]`;break}if(!t.autoIncrement!=!e.autoIncrement){a=`store [ ${t.name} ] autoIncrement not equal`;break}}}return!a||`The existing database is inconsistent with the definition and cannot be corrected: ${a}`},te=async e=>{let t=ee(e);return s(t)||(t=re(e)),t},re=({stores:e,schema:t})=>{const r=t.storeSchemas,a=e.map(e=>e.name);let n="";const i=r.map(e=>e.name).filter(e=>!a.includes(e));if(i.length)n=`store [ ${i.join(",")} ] not exist`;else for(const t of e){const e=r.find(e=>e.name===t.name);if(e&&(n=ae(t,Array.from(t.indexNames),e.indexSchemas),n))break}return!n||`The existing database Store index is inconsistent with the definition and requires a database version upgrade to be fixed: ${n}`};function ae(e,t,r){if(t.length!==r.length)return`store [ ${e.name} ] index count not equal`;for(const a of t){const t=r.find(e=>e.name===a);if(!t)return`store [ ${e.name} ] index [ ${a} ] not exist`;const n=e.index(a);if(!t.unique!=!n.unique)return`store [ ${e.name} ] index [ ${a} ] unique not equal`;if(!t.multiEntry!=!n.multiEntry)return`store [ ${e.name} ] index [ ${a} ] multiEntry not equal`;if(!Z(t.keyPath,n.keyPath))return`store [ ${e.name} ] index [ ${a} ] keyPath not equal`}return""}class ne{upgradeContext;storeSchema;nativeStore;#a;constructor(e,t,r){this.upgradeContext=e,this.storeSchema=t,this.nativeStore=r}get writer(){return this.#a||(this.#a=this.upgradeContext.dbSchema.factory?.newWriter({target:this.nativeStore,storeSchema:this.storeSchema}))}add(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.addMany(t,r):Promise.resolve()}addOrChange(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.addOrChangeMany(t,r):Promise.resolve()}async call(e,t){if(this.upgradeContext.versionIn(e))return await t(this.writer,this.upgradeContext)}replace(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.replaceMany(t,r):Promise.resolve()}}const ie=Object.freeze({newDataOperators:(e,t)=>new V(t,e),newDbMap:(e,t)=>new Y(e,t),newReader:(e,t)=>new G(e,t),newStoreUpgradeable:(e,t,r)=>new ne(r,t,e),newWriter:(e,t)=>new Q(e,t)});function se(e,t,a,n){const i=function(e,t,a){if(!1===e)return!1;if(s(e))return{name:e};if(r(e)){const r=e;return c(r.name)&&(r.name=t),e}if(!0===e||a)return{name:t};return!1}(t,a,n);if(!i)return i;const o=i;if(!1!==o.isIndexed){o.isIndexed||(o.isIndexed=!0);const{name:t}=o,r=e.indexSchemas;r.some(e=>e===t||e.name===t)||r.push(t)}return o}function oe(e,t){let r=s(e)?{name:e}:e;return t&&(r={...t,...r}),r.indexSchemas||(r.indexSchemas=[]),function(e){Object.isFrozen(e)||(e.addedTimeField=se(e,e.addedTimeField,"added_at",!0),e.updatedTimeField=se(e,e.updatedTimeField,"updated_at",!0),e.updatedCountField=se(e,e.updatedCountField,"updated_count",!1),e.softDeletedField=se(e,e.softDeletedField,"deleted",!1))}(r),Object.isFrozen(r)||(r.indexSchemas=r.indexSchemas.map(ce)),function(e){if(!e.keyPath&&e.defaultData?.length)for(const t of e.defaultData)if(!Array.isArray(t)&&!("value"in t))throw new Error(`When \`defaultData\` must contain \`value\` fields or be an array:${JSON.stringify(t)}`)}(r),r}function ce(e){const t=s(e)?{name:e}:e;return t.keyPath||(t.keyPath=t.name),t}const ue=e=>{const{versionDiffValidate:t,versionSameValidate:r,factory:a}=e;return e.storeSchemas||(e.storeSchemas=[]),e.storeTemplate||(e.storeTemplate={...R}),!t&&!1!==t&&(e.versionDiffValidate=ee),!r&&!1!==r&&(e.versionSameValidate=te),a?a!==ie&&(e.factory={...ie,...a}):e.factory=ie,e.storeSchemas=e.storeSchemas.map(t=>oe(t,e.storeTemplate)),e};function de(e,t){(function(e,t){return e.unique===t.unique&&e.multiEntry===t.multiEntry&&Z(t.keyPath,e.keyPath)})(e.index(t.name),t)||(e.deleteIndex(t.name),he(e,t))}function he(e,t){try{e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multiEntry})}catch{throw new Error(`store [ ${e.name} ] index [ ${t.name} ] create error: ${JSON.stringify(t)}`)}}function me(e,t){return e.database.objectStoreNames.contains(t.name)?function(e,t){const{indexSchemas:r}=e,a=t.indexNames,n=r.map(e=>e.name);for(const e of Array.from(a))n.includes(e)||t.deleteIndex(e);for(const e of r)a.contains(e.name)?de(t,e):he(t,e);return t}(t,e.transaction?.objectStore(t.name)):function(e,t){const r=t.createObjectStore(e.name,{keyPath:e.keyPath,autoIncrement:e.autoIncrement});for(const t of e.indexSchemas)he(r,t);return r}(t,e.database)}class le{database;newVersion;oldVersion;dbSchema;transaction;#n={};constructor(e){this.database=e.database,this.newVersion=e.newVersion,this.oldVersion=e.oldVersion,this.dbSchema=e.dbSchema,this.transaction=e.transaction}deleteStoreIfExists(e){const t=this.database;t.objectStoreNames.contains(e)&&t.deleteObjectStore(e)}destroy(){try{u(this.#n)}finally{for(const e of Object.keys(this.#n))delete this.#n[e]}}store(e){if(e in this.#n)return this.#n[e];const{factory:t}=this.dbSchema,{storeSchemas:r}=this.dbSchema,a=r.find(t=>t.name===e),n=me(this,a);return this.#n[e]=t.newStoreUpgradeable(n,a,this)}versionIn({oldMin:e,oldMax:t,newMax:r,newMin:a}){if(void 0===t&&void 0===r&&void 0===e&&void 0===a)throw new Error(`versionIn bounds must not be empty ${JSON.stringify({oldMax:t,newMax:r,oldMin:e,newMin:a})}`);if(t<e)throw new Error(`oldMax (${t}) cannot be less than oldMin (${e})`);if(r<a)throw new Error(`newMax (${r}) cannot be less than newMin (${a})`);const{oldVersion:n,newVersion:i}=this;return!(void 0!==e&&n<e||void 0!==t&&n>t||void 0!==a&&i<a)&&!(void 0!==r&&i>r)}}function fe(e,t){let{store:r,index:a}=e;const{storeTemplate:n}=t,{storeSchemas:i=[]}=t,o=s(r)?r:r.name,c=i.findIndex(e=>e===o||e.name===o),u=c>-1&&i[c];let d;d=s(r)?u||o:!u||s(u)||r===u?r:{...u,...r},(a||u?.indexSchemas?.length||r?.indexSchemas?.length)&&(s(d)&&(d={name:d}),d.indexSchemas=function(e,t,r){r&&t.push(r);for(const r of t){const t=s(r)?r:r.name,a=e.findIndex(e=>e===t||e.name===t);if(a>-1){const t=e[a];s(t)?e[a]=r:s(r)||(e[a]=Object.assign(t,r))}else e.push(r)}return e}(u.indexSchemas||[],r.indexSchemas||[],a));const h=oe(d,n);c>-1?i[c]=h:i.push(h),t.storeSchemas=i;const m={store:o};return a&&(m.index=s(a)?a:a.name),{target:m}}const ye=Object.assign({name:"",addedTimeField:!1,autoIncrement:!1,indexSchemas:[],keyPath:void 0,softDeletedField:!1,updatedCountField:!1,updatedTimeField:!1});class pe{static#i;#s;#o;#c={};constructor(e,t){this.#s=e=s(e)?{name:e}:e,Array.isArray(e.storeSchemas)||(e.storeSchemas=[]),r(e.storeTemplate)||(e.storeTemplate=R),t&&(this.#o=!0)}static get defaultDb(){return this.#i||(this.#i=new pe(S))}get initialized(){return Object.isFrozen(this.#s)}get schema(){return this.#s}get storeNames(){return Array.from(new Set(this.#s.storeSchemas.map(e=>s(e)?e:e.name)))}get factory(){return this.#s.factory||(this.#s.factory=ie)}static releaseDefaultDB(){this.#i=void 0}static async openExistDb(e){const{generateDbSchema:t}=await Promise.resolve().then(function(){return Pe});return new pe(await t(e))}static store(e,t){return pe.defaultDb.store(e,t)}static stores(e){return pe.defaultDb.stores(e)}static map(e,t){return pe.defaultDb.map(e,t)}async openNativeDb(){const e=this.#s=a(this.initSchema());await this.#u();const{name:r,version:n}=e;return await g({name:r,version:n,onupgradeneeded:(r,a,n)=>async function(e,r,a,n){const{storeSchemas:i,beforeUpgrade:s,afterUpgrade:o,version:c}=e,{newVersion:u=c,oldVersion:h}=a,{transaction:m}=n,l=new le({database:r,newVersion:u,oldVersion:h,dbSchema:e,transaction:m});try{const e=[];if(t(s))try{await s(l)}catch(t){e.push(t)}for(const t of i.map(e=>e.name))try{l.store(t)}catch(t){e.push(t)}for(const{name:t,defaultData:r}of i)if(r)try{await l.store(t).add({oldMax:0},r)}catch(t){e.push(t)}for(const{name:t,versionData:r}of i)if(r)for(const{version:a,data:n,use:i="addOrChange"}of r)try{await l.store(t)[i](a,n)}catch(t){e.push(t)}for(const{name:t,storeDefined:r}of i)try{await(r?.(l.store(t)))}catch(t){e.push(t)}if(t(o))try{await o(l)}catch(t){e.push(t)}if(!e.length)return;throw 1===e.length?e[0]:new AggregateError(e,"Database upgrade error")}finally{d(l)}}(e,r,a,n)})}store(e,t){const r=e.store?e:{store:e};return r.store||(r.store=e),r.index||(r.index=t),this.factory.newWriter(fe(r,this.schema),this)}stores(e){const{schema:t}=this,r=e.map(e=>fe(s(e)?{store:e}:e,t));return this.factory.newDataOperators(r,this)}initSchema(){if(this.initialized)return this.#s;const{validateSchemaWithDefaults:e=ue}=this.#s;return this.#s=e(this.#s)}async traceSchema(e){await h(this.schema,e)}map(e,t){const r=s(e)?e:s(t)?t:b;Array.isArray(e)&&(t=e);const{storeSchemas:a}=this.schema;return a.find(e=>e.name===r||e===r)||a.push({...ye,name:r,defaultData:t}),this.factory.newDbMap({target:{store:r}},this)}export(){return this.stores(this.storeNames).export()}import(e,t,r){return this.stores(this.storeNames).import(e,t,r)}getStoreSchema(e){if(e in this.#c)return this.#c[e];const t=this.schema.storeSchemas.findIndex(t=>t===e||t.name===e);let r=this.schema.storeSchemas[t];return this.initialized?this.#c[e]=r:s(r)&&(this.schema.storeSchemas[t]=r={name:r}),r}async#u(){let e=this.#o;if(void 0===e&&(e=this.#o=await async function(e){const{name:t,version:r}=e,a=await p(t);if(!a)return!0;const{versionDiffValidate:n,versionSameValidate:i}=e,o=await g(t);try{if(e.version<o.version)return"The existing database version is greater than the current version";const c=void 0===e.version||o.version===e.version?i:n;if(!c)return!0;const u=Array.from(o.objectStoreNames);if(u.length<1)return`The existing database [ ${t} ] is empty`;const d=await w(o,u),h=await c({schema:e,db:o,stores:d});if(s(h)||r!==a.version)return h}finally{o?.close()}return!0}(this.#s)),!0===e)return!0;if(s(e))throw new Error(e)}}function ge(e,t){return pe.defaultDb.store(e,t)}function we(e,t){return pe.defaultDb.map(e,t)}function Se(e){return pe.defaultDb.stores(e)}function be(){pe.releaseDefaultDB()}function xe(e,t){const r=Array.from(e.indexNames).map(t=>e.index(t)),a=[],n=[];for(const{name:e,keyPath:t,unique:i,multiEntry:s}of r)Array.isArray(t)?n.push(...t):n.push(t),a.push({name:e,keyPath:t,unique:i,multiEntry:s});const i=new Set(n);return{indexSchemas:a,addedTimeField:ve(t.addedTimeField,i),updatedTimeField:ve(t.updatedTimeField,i),updatedCountField:ve(t.updatedCountField,i),softDeletedField:ve(t.softDeletedField,i)}}function ve(e,t){return!!t.has(e)&&{name:e,isIndexed:!1}}async function ke(e,t){if(!await p(e))throw new Error(`db [ ${e} ] not exist`);let{asString:r,specialFields:a=$,dataExportTarget:n}=t||{};!0===r&&(r=160),isNaN(r)||r<1&&(r=1);let i=await function(e,t){return g(e,async function(e){const r=Array.from(e.objectStoreNames),a=e.transaction(r,"readonly");try{return{name:e.name,version:e.version,storeSchemas:r.map(e=>function(e,t){const{name:r,keyPath:a,autoIncrement:n}=e;return{name:r,keyPath:a,autoIncrement:n,...xe(e,t)}}(a.objectStore(e),t))}}finally{a.abort()}})}(e,a);return n&&await async function(e,t){const r=await new pe(l(e),!0).export();for(const a of e.storeSchemas){const n=r[a.name];n?.length&&("defaultData"===t?a.defaultData=n:"versionData"===t&&(a.versionData||(a.versionData=[]),a.versionData.push({version:{oldMax:e.version},data:n})))}return e}(i,n),r?await m({rootData$:i,spaceEffectiveLength:r}):i}var Pe=Object.freeze({__proto__:null,generateDbSchema:ke});export{D as Break,O as Continue,M as ContinueKey,E as ContinuePrimaryKey,T as DataOperationBase,V as DataOperators,G as DataReader,Q as DataWriter,W as DbIterator,k as DbIteratorParsers,Y as DbMap,v as Delete,I as Finished,pe as IDbPro,q as NextKey,j as NextPrimaryKey,x as Save,ne as StoreUpgradeable,le as UpgradeContext,we as dbMap,ge as dbStore,Se as dbStores,$ as defaultSpecialFields,R as defaultStoreSchemaTemplate,ke as generateDbSchema,A as isIDbQuery,F as isNativeTarget,P as parseDbNoneKeyPathRecord,C as parseIDbQuery,be as releaseDefaultDB,ue as validateSchemaWithDefaults,ee as versionDiffValidate,te as versionSameValidate};
|
package/lib/index.web.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=Symbol("save"),t=Symbol("delete"),r=Object.freeze({key:({primaryKey:e})=>({value:e}),value:({value:e})=>({value:e}),keyValue:({primaryKey:e,value:t})=>({value:[e,t]})});function n(e){if(Array.isArray(e))return{key:e[1],value:e[0]};if("value"in e){const{key:t,value:r}=e;return{key:t,value:r}}throw new Error(`not include value in invalid DBRecord:${JSON.stringify(e)}`)}const a=Symbol("break"),i=Symbol("finished"),s=Symbol("continue"),o=Symbol("continue key"),c=Symbol("next key"),u=Symbol("continue primary key"),h=Symbol("next primary key");function d(e){return e instanceof IDBObjectStore||e instanceof IDBIndex}const f=Object.freeze({keyPath:"id",autoIncrement:!0,addedTimeField:!0,updatedTimeField:!0}),l=Object.freeze({addedTimeField:"added_at",softDeletedField:"deleted",updatedCountField:"updated_count",updatedTimeField:"updated_at"});function y(e){return e instanceof Function||"function"==typeof e}function m(e){return!0===e||!1===e||e instanceof Boolean||"boolean"==typeof e}function p(e){return"number"==typeof e||e instanceof Number}function g(e){return"string"==typeof e||e instanceof String}function w(e){return e&&(t=e,!(Array.isArray(t)||t instanceof Array||t?.constructor===Array))&&!y(e)&&(e instanceof Object||"object"==typeof e);var t}function b(e){return null!=e&&y(e[Symbol.iterator])}function S(e){return null!=e&&y(e[Symbol.asyncIterator])}function x(e){return null!=e&&"function"==typeof e.next}async function v(e,t){for(let r=0;r<e.length;r++)await t(e[r])}async function k(e,t){const r=await e,n=[];for(let e=0;e<r.length;e++)n.push(await t(r[e],e,r));return n}function D(e){if("object"!=typeof e||null===e||e instanceof Date||e instanceof Function||e instanceof RegExp||typeof Element<"u"&&e instanceof Element)return e;if(e instanceof Set){const t=new Set;for(const r of e)t.add(D(r));return t}if(e instanceof Map){const t=new Map;for(const[r,n]of e)t.set(D(r),D(n));return t}if(Array.isArray(e)){const t=[];for(const r of e)t.push(D(r));return t}const t={};for(const[r,n]of Object.entries(e))t[r]=D(n);return t}function P(e){return Object.freeze(e),Object.getOwnPropertyNames(e).forEach(t=>{const r=e[t];null!==r&&("object"==typeof r||"function"==typeof r)&&!Object.isFrozen(r)&&P(r)}),e}class ${rootData$;space;showFn;spaceEffectiveLength;out;type;ignoreCircularRef;constructor(e){let t=0;w(e[t])&&e[t].rootData$&&Object.assign(this,e[t++]),t<1&&(this.rootData$=e[t++]);const r=e.slice(t),n=r.filter(e=>p(e));void 0===this.out&&(this.out=r.find(e=>y(e))||null),void 0===this.showFn&&(this.showFn=!!r.find(e=>m(e))),void 0===this.spaceEffectiveLength&&(this.spaceEffectiveLength=n[0]||100),void 0===this.space&&(this.space=n[1]||2),void 0===this.type&&(this.type=r.find(e=>g(e))||"js"),void 0===this.ignoreCircularRef&&(this.ignoreCircularRef=!0)}destroy(){this.out=null,this.rootData$=null}}async function O(e,t,r){if("string"==typeof(e=await e)||e instanceof Date)return JSON.stringify(e);if(e instanceof Function)return t.showFn?e.toString():"undefined";if("object"!=typeof e||null===e)return e+"";if(e instanceof RegExp)return e.toString();if(typeof Element<"u"&&e instanceof Element)return"undefined";if(r.has(e)){if(t.ignoreCircularRef)return;throw new Error("circular reference")}r.add(e);try{return"json"===t.type?await async function(e,t,r){const n=[];if(Array.isArray(e)||e instanceof Set||b(e)&&!(e instanceof Map)){for(const a of e)if(void 0!==a&&(!y(a)||t.showFn)){const e=await O(a,t,r);void 0!==e&&n.push(e)}const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`[${a}${s()}${i}]`:"[]"}if(S(e)||x(e)){for await(const a of e)if(void 0!==a&&(!y(a)||t.showFn)){const e=await O(a,t,r);void 0!==e&&n.push(e)}const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`[${a}${s()}${i}]`:"[]"}let a=e instanceof Map?e.entries():Object.entries(e);for(const[e,i]of a)if(void 0!==i&&(!y(i)||t.showFn)){const a=await O(i,t,r);void 0!==a&&n.push(`"${e}": ${a}`)}const{spaceStart:i,spaceEnd:s,arrJoin:o}=E(n,t);return n.length?`[${i}${o()}${s}]`:"[]"}(e,t,r):await async function(e,t,r){const n=[];if(e instanceof Set){for(const a of e)(!y(a)||t.showFn)&&n.push(await O(a,t,r));const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`new Set([${a}${s()}${i}])`:"[]"}if(e instanceof Map){for(const[a,i]of e)(!y(i)||t.showFn)&&n.push(`${I(await O(a,t,r))}: ${await O(i,t,r)}`);const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`new Map(Object.entries({${a}${s()}${i}})`:"new Map()"}if(Array.isArray(e)||b(e)){for(const a of e)(!y(a)||t.showFn)&&n.push(await O(a,t,r));const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`[${a}${s()}${i}]`:"[]"}if(x(e)||S(e)){for await(const a of e)(!y(a)||t.showFn)&&n.push(await O(a,t,r));const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`[${a}${s()}${i}]`:"[]"}for(const[a,i]of Object.entries(e))(!y(i)||t.showFn)&&n.push(`${I(a)}: ${await O(i,t,r)}`);const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`{${a}${s()}${i}}`:"{}"}(e,t,r)}finally{r.delete(e)}}function E(e,t){let r=t.space;e.reduce((e,t)=>e+t.length,0)<t.spaceEffectiveLength&&(r=0);const n=r?"\n"+"".padStart(r):"",a=r?"\n":"",i=r?"\n".padEnd(r+1):",";return{spaceStart:n,spaceEnd:a,arrJoin:r?()=>e.join(",\n").replace(/\n/g,i):()=>e.join(",")}}function I(e){return/^[a-z_]+\w*$/i.test(e)?e:`"${e}"`}async function j(...e){const t=new $(e),r=new Set;try{const e=await O(t.rootData$,t,r);if(!t.out)return e;t.out(e)}finally{r.clear(),t.destroy()}}function F(e){return e instanceof Function||"function"==typeof e}function M(e){return"string"==typeof e||e instanceof String}var A,q;function R(e){return"string"==typeof(t=e)||"number"==typeof t||t instanceof String||t instanceof Number||e instanceof Date||e instanceof ArrayBuffer||Array.isArray(e)&&e.every(R);var t}function B(e){return null==e||function(e){return e instanceof IDBKeyRange||R(e)}(e)}async function C(e){return(await indexedDB.databases()).find(t=>t.name===e)}async function N(e,t){const r=M(e)?{name:e}:e;F(t)&&(r.onsuccess=t);const{name:n,onsuccess:a,onupgradeneeded:i,version:s}=r;return function(e,t,r){return new Promise(async(n,a)=>{let i=!1;e.onsuccess=async()=>{if(!i)if(t)try{n(await t(e.result))}catch(e){a(e)}finally{e.result?.close?.()}else n(e.result)},e.onblocked=e.onerror=e=>a(e.target.error),r&&(e.onupgradeneeded=async t=>{try{await r(e.result,t,e)}catch(e){i=!0,a(e)}})})}(indexedDB.open(n,s),a,i)}function K(e,t,r){return function(e,t,...r){return new Promise(async(n,a)=>{let i=0;const s=F(r[i])?r[i++]:void 0,o=r[i]?"readwrite":"readonly",c=e instanceof IDBDatabase?e:await N(e),u=Array.isArray(t)?t:[t],h=c.transaction(u.map(e=>M(e)?e:e.store),o),d=u.map(e=>{if(M(e))return h.objectStore(e);const{store:t,index:r}=e;return M(r)?h.objectStore(t).index(r):h.objectStore(t)});if(s)try{n(await s(...d)),o?h.commit():h.abort()}catch(e){h.abort(),a(e)}finally{c.close()}else n(d)})}(e,t,r,!1)}function T(e){return new Promise(async(t,r)=>{e.onsuccess=()=>{try{t(e.result)}catch(e){r(e)}},e.onerror=e=>r(e.target.error)})}(q=A||(A={}))[q.True=1]="True",q[q.False=0]="False";const V=e=>e instanceof Date?e.getTime():e;function W(e){if(B(e))return e;const t=e;if("lt"in t&&"gt"in t){if(V(t.gt)>V(t.lt))throw new Error(`Invalid IDBRange: gt (${t.gt}) cannot be greater than lt (${t.lt})`);return IDBKeyRange.bound(t.gt,t.lt,!0,!0)}if("lt"in t&&"gte"in t){if(V(t.gte)>V(t.lt))throw new Error(`Invalid IDBRange: gte (${t.gte}) cannot be greater than lt (${t.lt})`);return IDBKeyRange.bound(t.gte,t.lt,!1,!0)}if("lte"in t&&"gt"in t){if(V(t.gt)>V(t.lte))throw new Error(`Invalid IDBRange: gt (${t.gt}) cannot be greater than lte (${t.lte})`);return IDBKeyRange.bound(t.gt,t.lte,!0,!1)}if("lte"in t&&"gte"in t){if(V(t.gte)>V(t.lte))throw new Error(`Invalid IDBRange: gte (${t.gte}) cannot be greater than lte (${t.lte})`);return IDBKeyRange.bound(t.gte,t.lte,!1,!1)}return"lt"in t?IDBKeyRange.upperBound(t.lt,!0):"lte"in t?IDBKeyRange.upperBound(t.lte,!1):"gt"in t?IDBKeyRange.lowerBound(t.gt,!0):"gte"in t?IDBKeyRange.lowerBound(t.gte,!1):void 0}function z(e){return null!=W(e)}async function _(e,t,r){const{query:n,direction:a="prev",preSkip:i,startKey:s,startPrimaryKey:o}=t,c=e.openCursor(W(n),a);return i&&(await T(c)).advance(i),s&&(o?(await T(c)).continuePrimaryKey(s,o):(await T(c)).continue(s)),c}function J(e,t,r){return Array.isArray(e)?t=>function(e,t,r){if(r?.length)for(const n of r)t.hasOwnProperty(n)&&(e[n]=t[n]);else Object.assign(e,t);return e}({},t,e):y(e)?e:t?e=>e:r?(e,t)=>[e,t]:(e,t)=>({key:e,value:t})}class U{idbPro;target;#e;constructor(e,t){this.idbPro=t,this.#e=e.storeSchema,this.target=e.target,d(e.target)&&(this.tx=this.#t)}get storeName(){return this.nativeStore?.name||this.target.store}get storeSchema(){if(this.#e)return this.#e;const e=this.idbPro.getStoreSchema(this.storeName);return Object.isFrozen(e)&&(this.#e=e),e}get factory(){return this.idbPro.factory}get nativeStore(){const{target:e}=this;return e instanceof IDBObjectStore?e:e instanceof IDBIndex?e.objectStore:void 0}get keyPath(){const{target:e}=this;if(d(e))return e.keyPath;const{storeSchema:t}=this,{index:r}=e;return r?t.indexSchemas.find(e=>e.name===r)?.keyPath:t.keyPath}async forEach(e,t){return e=y(e)?{fn:e}:e,t?this.cursorResult(e,!1):this.cursorVoid(e,!1)}async tx(e,t,r){let{target:n}=this;const{store:a,index:i}=n,s=await this.idbPro.openNativeDb();let o,c;try{o=s.transaction(a,!0===e?"readwrite":"readonly"),n=c=o.objectStore(a),i&&(n=n.index(i))}catch(e){throw s.close(),e}if(!t)return Object.freeze({db:s,tx:o,nativeStore:c,target:n});try{if(!0===e){const e=await t(n,c);return o.commit(),e}return t(n)}catch(e){throw!1!==r&&o.abort(),e}finally{s.close()}}openCursor(e,t){return this.tx(t,t=>new Promise(async(r,n)=>{const{fn:a}=e,i=await _(t,e);i.onsuccess=async()=>{i.result?!1===await a(i.result)&&r():r()},i.onerror=()=>n(i.error)}))}cursorVoid({query:r,direction:n,preSkip:i,startKey:s,startPrimaryKey:c,fn:h},d){let f=0;return this.openCursor({query:r,direction:n,preSkip:i,startKey:s,startPrimaryKey:c,fn:async r=>{const{value:n,primaryKey:i}=r,s=await h(n,i,f++),{control:c,key:l,primaryKey:y,modify:m,value:p}=w(s)?s:{control:s};switch(d&&(m===e?r.update(p||n):m===t&&r.delete()),c){case a:return!1;case o:r.continue(l);break;case u:r.continuePrimaryKey(l,y);break;default:r.continue()}}},!0)}async cursorResult({query:r,direction:n,preSkip:s,startKey:d,startPrimaryKey:f,fn:l,mapper:y},m){const{keyPath:p,defaultGetMapper:g}=this.storeSchema,w=J(y||g,p),b=[];let S=0;return await this.openCursor({query:r,direction:n,preSkip:s,startKey:d,startPrimaryKey:f,fn:async r=>{const{value:n,primaryKey:s}=r,{control:d,value:f,key:y,primaryKey:p,modify:g}=await(l?.(n,s,S,b))||{};switch(m&&(g===e?r.update(f||n):g===t&&r.delete()),(!d||d===i||d===c||d===h)&&b.push(w(f||n,p||s,S)),d){case a:case i:return!1;case c:case o:r.continue(y);break;case h:case u:r.continuePrimaryKey(y,p);break;default:r.continue()}S++}},m),b}#t(e,t){const{target:r}=this,n=r instanceof IDBObjectStore?r:r.objectStore;return t?t(r,n):Object.freeze({nativeStore:n,target:r})}}class G{idbPro;schemas;#r;constructor(e,t){this.idbPro=e,this.schemas=t}get storeNames(){return this.#r||(this.#r=Array.from(new Set(this.schemas.map(e=>e.target.store))))}read(e){return this.tx("newReader",e)}write(e,t=!0){return this.tx("newWriter",e,!0,t)}export(){return this.tx("newReader",async(...e)=>{const t={};for(const r of e)t[r.storeName]=await r.export();return t})}import(e,t,r){return r||(r="addOrChangeMany"),this.tx("newWriter",async(...n)=>{const a={};n=Array.from(new Map(n.map(e=>[e.storeName,e.asStore(!0)])).values());for(const i of n){const{storeName:n}=i,s=e[n];s&&(a[n]=await i[r](s,t))}if(t)return a},!0)}async tx(e,t,r,n){const{idbPro:a,schemas:i}=this,{factory:s}=a.schema,o=await a.openNativeDb();try{const c=o.transaction(this.storeNames,r?"readwrite":"readonly");try{const n=i.map(({storeSchema:t,target:r})=>{let n=c.objectStore(r.store);return r.index&&(n=n.index(r.index)),s[e]({storeSchema:t,target:n},a)});if(r){const e=await t(...n);return c.commit(),e}return await t(...n)}catch(e){throw!1!==n&&c.abort(),e}}finally{o.close()}}}class L extends U{direction;query;writable;parser;endsWithNull;preSkip;startKey;startPrimaryKey;constructor(e,t,n){if(super(e,t),!n)return;const{parser:a}=n;this.direction=n.direction,this.query=n.query,this.writable=!!n.writable,this.endsWithNull=!!n.endsWithNull,this.preSkip=n.preSkip,this.startKey=n.startKey,this.startPrimaryKey=n.startPrimaryKey,a&&(this.parser=y(a)?a:r[a])}async*[Symbol.asyncIterator](){const{parser:e,writable:t,endsWithNull:r}=this,{db:n,tx:i,target:s}=await this.tx(t);try{const n=await _(s,this);let o;if(e)for(;o=await T(n);){const{control:t,value:r}=await e(o);if(t||(yield r),t===a)break;o.continue()}else{let e=!1;const t=()=>{e=!0};for(;!e&&(o=await T(n));)yield{cursor:o,end:t}}t&&i?.commit(),r&&!o&&(yield null)}finally{n?.close()}}}function X(e,t,r,n){const a=w(e)?e:{};return y(e)?a.fn=e:z(e)&&(a.query=e),y(t)?a.fn=t:t&&(a.direction=t),r&&(a.direction=r),n?a.limit=n:a.limit||(a.limit=1e3),a.maxEmptyChecks||(a.maxEmptyChecks=2e4),a}async function H(e,t,r){t.size||(t.size=100),t.nextSkip||(t.nextSkip=0);const{query:n,direction:a,total:i,maxEmptyChecks:s,fn:o}=t;return await e.batchRead(async e=>(i||(t.total=await e.count({query:n,direction:a,maxEmptyChecks:s,fn:o}),t.pages=Math.ceil(t.total/t.size)),t.total<1?{info:P(t),rows:[]}:o?await async function(e,t,r){t.maxEmptyChecks||(t.maxEmptyChecks=2e4);const{page:n,query:a,direction:i,nextSkip:s}=t,{keyPath:o}=e.storeSchema;return 1===n?await Q(e,await _(e.target,{query:a,direction:i}),t,o):r&&s&&n-r.page===1?await Q(e,await _(e.target,{query:a,direction:i,preSkip:s}),t,o):await Q(e,await _(e.target,{query:a,direction:i}),t,o,!0)}(e,t,r):await async function(e,t){const{keyPath:r}=e.storeSchema,{page:n,query:a,direction:i,size:s,mapper:o}=t,c=(n-1)*s,u=await e.filter({query:a,preSkip:c,direction:i,limit:s,mapper:J(o,r,!0)});return t.nextSkip=c+u.length,{info:P(t),rows:u}}(e,t)))}async function Q({storeSchema:{defaultGetMapper:e}},t,r,n,a){const{page:i,size:s,total:o,maxEmptyChecks:c,fn:u}=r,h=J(r.mapper||e,n,!0),d=[],f=(i-1)*r.size;if(f>=o)return{info:P(r),rows:[]};let l=0;return await new Promise(async(e,r)=>{let n=0,i=0;const o=async()=>{const{result:r}=t;if(!r)return e();let{value:a,primaryKey:i}=r;if(await u(a,i,l)?(n=0,d.push(h(a,i,l))):n++,d.length>=s||n>=c)return e();l++,r.continue()};t.onerror=()=>r(t.error),t.onsuccess=a?async()=>{const{result:r}=t;if(!r)return e();let{value:a,primaryKey:s}=r;if(await u(a,s,l)?(n=0,i++):n++,i>=f||n>=c)return l=n=0,t.onsuccess=o,void r.continue();r.continue(),l++}:o}),l&&(r.nextSkip+=l+1),{info:P(r),rows:d}}class Y extends U{all(e,t){const r={};return p(t)&&(r.limit=t),z(e)?r.query=e:w(e)&&Object.assign(r,e),this.tx(!1,e=>T(e.getAll(W(r.query),r.limit||1e3)))}async count(e,t,r){const n=X(e,t,r),{query:a,direction:i,fn:s}=n;if(!s)return await this.tx(!1,e=>T(e.count(W(a))));const{maxEmptyChecks:o}=n,c=s;let u=0,h=0,d=0;return await this.openCursor({query:a,direction:i,fn:e=>{if(c(e.value,e.primaryKey,d++))u++,h=0;else if(++h>=o)return!1;e.continue()}}),u}get(e){return this.tx(!1,t=>T(t.get(W(e))))}getMany(e,t){return this.batchRead(async r=>{const n=await k(e,e=>r.get(e));return t?n.filter(e=>e):n})}getRange(e,t){return this.forEach({query:e,direction:t},!0)}async getRangeMany(e,t,r){return(await this.batchRead(r=>k(e,e=>r.getRange(e,t)))).flat()}index(e,t){let{target:r}=this;return r instanceof IDBIndex&&(r=r.objectStore),r instanceof IDBObjectStore?(r=r.index(e),this.createOperator(r,t)):this.idbPro.store(r.store,e)}asStore(e){let{target:t}=this;if(t instanceof IDBObjectStore)return this;if(t instanceof IDBIndex)t=t.objectStore;else{if(!("index"in t))return this;t={store:t.store}}return this.createOperator(t,e)}batchRead(e){return d(this.target)?e(this):this.tx(!1,t=>e(this.idbPro.schema.factory.newReader({storeSchema:this.storeSchema,target:t},this.idbPro)))}iterator(e,t){const r={};return g(t)&&(r.direction=t),z(e)?r.query=e:w(e)&&Object.assign(r,e),new L({storeSchema:this.storeSchema,target:this.target},this.idbPro,{...r,parser:"value"})}async filter(e,t,r,n){const o=X(e,t,r,n),{maxEmptyChecks:c,limit:u,fn:h}=o,{keyPath:d,defaultGetMapper:f}=this.storeSchema,l=J(o.mapper||f,d,!0);if(!h)return await this.forEach({...o,mapper:l,fn:(e,t,r)=>{if(r>=u-1)return{control:i}}},!0);let y=0;return this.forEach({...o,mapper:l,fn:(e,t,r,n)=>(e=l(e,t,r),h(e,t,r)?(y=0,n.length>=u-1?{control:i}:void 0):++y>=c?{control:a}:{control:s})},!0)}async find(e,t,r){const[n]=await this.filter(e,t,r,1);return n}async page(e,t){const r={...e};return r.page=t||e?.page||1,H(this,r,e)}nextPage(e){return this.page(e,e.page+1)}export(e,t){const r=X(e,t),{keyPath:n,exportMapper:a,name:i,defaultGetMapper:s}=this.storeSchema;if(!n&&Array.isArray(a))throw new Error(`When store [ ${i} ] keyPath does not exist, exportMapper does not support string[].`);return r.direction="next",r.mapper=J(a||s,n,!0),r.limit=r.maxEmptyChecks=Number.MAX_SAFE_INTEGER,this.filter(r)}asMap(){let{target:e}=this;return e instanceof IDBIndex?e=e.objectStore:e instanceof IDBObjectStore||(e={store:e.store}),this.factory.newDbMap({target:e},this.idbPro)}createOperator(e,t){const{idbPro:r}=this,n=this.storeSchema,a={storeSchema:Object.isFrozen(n)?n:void 0,target:e};return t?this.factory.newWriter(a,r):this.factory.newReader(a,r)}}function Z(e,t){if(!Array.isArray(e))return{[e]:t};const r={},n=e;for(let e=0;e<n.length;e++)r[n[e]]=t[e];return r}function ee(e,t){if(!Array.isArray(e))return t[e];const r=[];for(const n of e){if(!t[n])return;r.push(t[n])}return r}function te(e,t){if(!t||!(t instanceof Object)||Array.isArray(t))return t;const{addedTimeField:r,updatedTimeField:n,updatedCountField:a,softDeletedField:i}=e;return t={...t},r?.name&&!p(t[r.name])&&(t[r.name]=Date.now()),n?.name&&!p(t[n.name])&&(t[n.name]=Date.now()),i?.name&&!p(t[i.name])&&(t[i.name]=0),a?.name&&(t[a.name]=0),t}function re(e,t,r){if(!t||!(t instanceof Object)||Array.isArray(t))return t;const{updatedTimeField:n,updatedCountField:a}=e;return t={...r,...t},n.name&&(t[n.name]=Date.now()),a.name&&(t[a.name]=(t[a.name]||0)+1),t}class ne extends Y{add(e){return this.changeByPk({record:e,fn:async(e,t,r,n,a)=>{const{storeSchema:i}=this;return r=te(i,r),a?[{...r,...Z(a,await T(e.add(r)))},t]:[r,await T(e.add(r,t))]}})}addMany(e,t){return this.batchWrite(r=>t?k(e,e=>r.add(e)):v(e,e=>r.add(e)),!0)}addOrSkip(e){return this.batchWrite(async t=>{const{keyPath:r,defaultGetMapper:a}=t.storeSchema,{key:i,value:s}=r?{key:ee(r,e),value:e}:n(e);if(i){const e=await T(t.nativeStore.get(i));if(e)return J(a,r)?.(e,i)}if(t.target instanceof IDBIndex){const{keyPath:r}=t,n=ee(r,s);if(!n)return t.add(e);let a=await t.find(n);if(a)return a}return t.add(e)})}addOrSkipMany(e,t){return this.batchWrite(r=>t?k(e,e=>r.addOrSkip(e)):v(e,e=>r.addOrSkip(e)),!0)}replace(e){return this.changeByPk({record:e,getOld:!0,fn:async(e,t,r,n,a)=>{const{storeSchema:i}=this,{updatedTimeField:s,updatedCountField:o,addedTimeField:c}=i;return r=n?re(i,r,{[s.name]:n[s.name],[o.name]:n[o.name],[c.name]:n[c.name]}):te(i,r),a?[{...r,...Z(a,await T(e.put(r)))},t]:[r,await T(e.put(r,t))]}})}replaceMany(e,t){return this.batchWrite(r=>t?k(e,e=>r.replace(e)):v(e,e=>r.replace(e)),!0)}change(e,t){return this.changeByPk({record:e,getOld:!0,requiredOld:t,requiredPk:t,fn:async(e,t,r,n,a)=>{const{storeSchema:i}=this;if(n)return r=re(i,r,n),a?[{...r,...Z(a,await T(e.put(r)))},t]:[r,await T(e.put(r,t))]}})}changeMany(e,t){const{returns:r,throwIfMissing:n}=m(t)?{returns:t}:t||{};return this.batchWrite(t=>r?k(e,e=>t.change(e,n)):v(e,e=>t.change(e,n)),!0)}addOrChange(e){return this.changeByPk({record:e,getOld:!0,fn:async(e,t,r,n,a)=>{const{storeSchema:i}=this;return n?(r=re(i,r,n),a?[{...r,...Z(a,await T(e.put(r)))},t]:[r,await T(e.put(r,t))]):(r=te(i,r),a?[{...r,...Z(a,await T(e.add(r)))},t]:[r,await T(e.add(r,t))])}})}addOrChangeMany(e,t){return this.batchWrite(r=>t?k(e,e=>r.addOrChange(e)):v(e,e=>r.addOrChange(e)),!0)}delete(e,t){return this.changeByPk({pk:e,getOld:t,fn:(e,r,n,a)=>{if(e.delete(r),t)return[a,r]}})}deleteMany(e,t){return this.batchWrite(r=>t?k(e,e=>r.delete(e,!0)):v(e,e=>r.delete(e)),!0)}deleteRange(r,n){const{returns:a,physical:i,direction:s}=m(n)?{returns:n}:n||{},{name:o}=this.storeSchema.softDeletedField||{};return this.cursor({query:r,direction:s,fn:r=>i||!o?{modify:t}:(r[o]=1,{modify:e})},a)}deleteRangeMany(e,t){const r=m(t)?{returns:t}:t;return this.batchWrite(t=>r?.returns?k(e,e=>t.deleteRange(e,r)):v(e,e=>t.deleteRange(e,r)),!0)}changeRange(t,r){let{direction:n="next",query:a,newValue:i}="newValue"in t?t:{newValue:t};if(a||(a=ee(this.keyPath,i)),!a)throw new Error(`query is required:${JSON.stringify(t)}`);return this.cursor({query:a,direction:n,fn:t=>t instanceof Object?{modify:e,value:{...t,...i}}:{modify:e,value:i}},r)}changeRangeMany(e,t){return this.batchWrite(r=>t?k(e,e=>r.changeRange(e,t)):v(e,e=>r.changeRange(e,t)),!0)}cursor(e,t){return(e=y(e)?{fn:e}:e||{}).fn?t?this.cursorResult(e,!0):this.cursorVoid(e,!0):new L(this,this.idbPro)}batchWrite(e,t){const{target:r}=this;if(d(r))try{return e(this)}catch(e){throw!1!==t&&(r instanceof IDBIndex?r.objectStore:r).transaction.abort(),e}return this.tx(!0,t=>e(this.idbPro.schema.factory.newWriter({storeSchema:this.storeSchema,target:t},this.idbPro)),t)}changeByPk({pk:e,record:t,fn:r,requiredPk:a,getOld:i,requiredOld:s,saveMapper:o,getMapper:c}){const{storeSchema:u}=this,{keyPath:h,defaultSaveMapper:d,defaultGetMapper:f}=u;return t&&(o||d)&&(t=J(o||d,h)?.(t)),this.batchWrite(async o=>{let u,d=t;if(e)u=W(e);else if(h)u=ee(h,t);else{const{key:e,value:r}=n(t);u=e,d=r}if(a&&!u)throw new Error(`key is required: ${JSON.stringify(t)}`);const l=u&&(i||s)?await T(o.nativeStore.get(u)):void 0;if(s&&!l)throw new Error(`record not found: ${JSON.stringify(t)}`);const y=await r(o.nativeStore,u,d,l,h);if(y)return J(c||f,h)?.(y[0],y[1])})}}class ae extends U{get size(){return this.tx(!1,e=>T(e.count()))}delete(e){return this.tx(!0,async(t,r)=>{r.delete(e)})}batch(e){const{idbPro:t,storeSchema:r,factory:n}=this;return this.tx(!0,async(a,i)=>await e(n.newDbMap({storeSchema:r,target:i},t)))}asStore(e){const{factory:t}=this.idbPro.schema;return e?t.newWriter(this,this.idbPro):t.newReader({target:this.target},this.idbPro)}entries(){return new L({target:this.target},this.idbPro,{parser:"keyValue"})}async get(e,t){return await this.tx(!1,t=>T(t.get(e)))||t}getMany(e){return this.tx(!1,async t=>{const r=[];for(const n of e)r.push(await T(t.get(n)));return r})}async has(e){return!!await this.get(e)}keys(){return new L({storeSchema:this.storeSchema,target:this.target},this.idbPro,{parser:"key"})}set(e,t){return this.tx(!0,async(r,n)=>{await T(n.put(t,e))})}setMany(e){return this.tx(!0,async(t,r)=>{for(const[t,n]of e)r.put(n,t)})}values(){return new L({storeSchema:this.storeSchema,target:this.target},this.idbPro,{parser:"value"})}}function ie(e,t){if(e==t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}return!1}const se=({stores:e,schema:t})=>{const r=t.storeSchemas;let n="";for(const t of e){const e=r.find(e=>e.name===t.name);if(e){if(!ie(t.keyPath,e.keyPath)){n=`store [ ${t.name} ] keyPath not equal,schema.keyPath:${e.keyPath},store.keyPath:${t.keyPath}[]`;break}if(!t.autoIncrement!=!e.autoIncrement){n=`store [ ${t.name} ] autoIncrement not equal`;break}}}return!n||`The existing database is inconsistent with the definition and cannot be corrected: ${n}`},oe=async e=>{let t=se(e);return g(t)||(t=ce(e)),t},ce=({stores:e,schema:t})=>{const r=t.storeSchemas,n=e.map(e=>e.name);let a="";const i=r.map(e=>e.name).filter(e=>!n.includes(e));if(i.length)a=`store [ ${i.join(",")} ] not exist`;else for(const t of e){const e=r.find(e=>e.name===t.name);if(e&&(a=ue(t,Array.from(t.indexNames),e.indexSchemas),a))break}return!a||`The existing database Store index is inconsistent with the definition and requires a database version upgrade to be fixed: ${a}`};function ue(e,t,r){if(t.length!==r.length)return`store [ ${e.name} ] index count not equal`;for(const n of t){const t=r.find(e=>e.name===n);if(!t)return`store [ ${e.name} ] index [ ${n} ] not exist`;const a=e.index(n);if(!t.unique!=!a.unique)return`store [ ${e.name} ] index [ ${n} ] unique not equal`;if(!t.multiEntry!=!a.multiEntry)return`store [ ${e.name} ] index [ ${n} ] multiEntry not equal`;if(!ie(t.keyPath,a.keyPath))return`store [ ${e.name} ] index [ ${n} ] keyPath not equal`}return""}class he{upgradeContext;storeSchema;nativeStore;#n;constructor(e,t,r){this.upgradeContext=e,this.storeSchema=t,this.nativeStore=r}get writer(){return this.#n||(this.#n=this.upgradeContext.dbSchema.factory?.newWriter({target:this.nativeStore,storeSchema:this.storeSchema}))}add(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.addMany(t,r):Promise.resolve()}addOrChange(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.addOrChangeMany(t,r):Promise.resolve()}async call(e,t){if(this.upgradeContext.versionIn(e))return await t(this.writer,this.upgradeContext)}replace(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.replaceMany(t,r):Promise.resolve()}}const de=Object.freeze({newDataOperators:(e,t)=>new G(t,e),newDbMap:(e,t)=>new ae(e,t),newReader:(e,t)=>new Y(e,t),newStoreUpgradeable:(e,t,r)=>new he(r,t,e),newWriter:(e,t)=>new ne(e,t)});function fe(e,t,r,n){const a=function(e,t,r){if(!1===e)return!1;if(g(e))return{name:e};if(w(e)){const r=e;return m(r.name)&&(r.name=t),e}if(!0===e||r)return{name:t};return!1}(t,r,n);if(!a)return a;const i=a;if(!1!==i.isIndexed){i.isIndexed||(i.isIndexed=!0);const{name:t}=i,r=e.indexSchemas;r.some(e=>e===t||e.name===t)||r.push(t)}return i}function le(e,t){let r=g(e)?{name:e}:e;return t&&(r={...t,...r}),r.indexSchemas||(r.indexSchemas=[]),function(e){Object.isFrozen(e)||(e.addedTimeField=fe(e,e.addedTimeField,"added_at",!0),e.updatedTimeField=fe(e,e.updatedTimeField,"updated_at",!0),e.updatedCountField=fe(e,e.updatedCountField,"updated_count",!1),e.softDeletedField=fe(e,e.softDeletedField,"deleted",!1))}(r),Object.isFrozen(r)||(r.indexSchemas=r.indexSchemas.map(ye)),function(e){if(!e.keyPath&&e.defaultData?.length)for(const t of e.defaultData)if(!Array.isArray(t)&&!("value"in t))throw new Error(`When \`defaultData\` must contain \`value\` fields or be an array:${JSON.stringify(t)}`)}(r),r}function ye(e){const t=g(e)?{name:e}:e;return t.keyPath||(t.keyPath=t.name),t}const me=e=>{const{versionDiffValidate:t,versionSameValidate:r,factory:n}=e;return e.storeSchemas||(e.storeSchemas=[]),e.storeTemplate||(e.storeTemplate={...f}),!t&&!1!==t&&(e.versionDiffValidate=se),!r&&!1!==r&&(e.versionSameValidate=oe),n?n!==de&&(e.factory={...de,...n}):e.factory=de,e.storeSchemas=e.storeSchemas.map(t=>le(t,e.storeTemplate)),e};function pe(e,t){(function(e,t){return e.unique===t.unique&&e.multiEntry===t.multiEntry&&ie(t.keyPath,e.keyPath)})(e.index(t.name),t)||(e.deleteIndex(t.name),ge(e,t))}function ge(e,t){try{e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multiEntry})}catch{throw new Error(`store [ ${e.name} ] index [ ${t.name} ] create error: ${JSON.stringify(t)}`)}}function we(e,t){return e.database.objectStoreNames.contains(t.name)?function(e,t){const{indexSchemas:r}=e,n=t.indexNames,a=r.map(e=>e.name);for(const e of Array.from(n))a.includes(e)||t.deleteIndex(e);for(const e of r)n.contains(e.name)?pe(t,e):ge(t,e);return t}(t,e.transaction?.objectStore(t.name)):function(e,t){const r=t.createObjectStore(e.name,{keyPath:e.keyPath,autoIncrement:e.autoIncrement});for(const t of e.indexSchemas)ge(r,t);return r}(t,e.database)}class be{database;newVersion;oldVersion;dbSchema;transaction;#a={};constructor(e){this.database=e.database,this.newVersion=e.newVersion,this.oldVersion=e.oldVersion,this.dbSchema=e.dbSchema,this.transaction=e.transaction}deleteStoreIfExists(e){const t=this.database;t.objectStoreNames.contains(e)&&t.deleteObjectStore(e)}destroy(){try{!function(...e){for(const t of e)if(t)for(const e of Object.keys(t))try{t[e]?.destroy?.()}catch{}finally{delete t[e]}}(this.#a)}finally{for(const e of Object.keys(this.#a))delete this.#a[e]}}store(e){if(e in this.#a)return this.#a[e];const{factory:t}=this.dbSchema,{storeSchemas:r}=this.dbSchema,n=r.find(t=>t.name===e),a=we(this,n);return this.#a[e]=t.newStoreUpgradeable(a,n,this)}versionIn({oldMin:e,oldMax:t,newMax:r,newMin:n}){if(void 0===t&&void 0===r&&void 0===e&&void 0===n)throw new Error(`versionIn bounds must not be empty ${JSON.stringify({oldMax:t,newMax:r,oldMin:e,newMin:n})}`);if(t<e)throw new Error(`oldMax (${t}) cannot be less than oldMin (${e})`);if(r<n)throw new Error(`newMax (${r}) cannot be less than newMin (${n})`);const{oldVersion:a,newVersion:i}=this;return!(void 0!==e&&a<e||void 0!==t&&a>t||void 0!==n&&i<n)&&!(void 0!==r&&i>r)}}function Se(e,t){let{store:r,index:n}=e;const{storeTemplate:a}=t,{storeSchemas:i=[]}=t,s=g(r)?r:r.name,o=i.findIndex(e=>e===s||e.name===s),c=o>-1&&i[o];let u;u=g(r)?c||s:!c||g(c)||r===c?r:{...c,...r},(n||c?.indexSchemas?.length||r?.indexSchemas?.length)&&(g(u)&&(u={name:u}),u.indexSchemas=function(e,t,r){r&&t.push(r);for(const r of t){const t=g(r)?r:r.name,n=e.findIndex(e=>e===t||e.name===t);if(n>-1){const t=e[n];g(t)?e[n]=r:g(r)||(e[n]=Object.assign(t,r))}else e.push(r)}return e}(c.indexSchemas||[],r.indexSchemas||[],n));const h=le(u,a);o>-1?i[o]=h:i.push(h),t.storeSchemas=i;const d={store:s};return n&&(d.index=g(n)?n:n.name),{target:d}}const xe=Object.assign({name:"",addedTimeField:!1,autoIncrement:!1,indexSchemas:[],keyPath:void 0,softDeletedField:!1,updatedCountField:!1,updatedTimeField:!1});class ve{static#i;#s;#o;#c={};constructor(e,t){this.#s=e=g(e)?{name:e}:e,Array.isArray(e.storeSchemas)||(e.storeSchemas=[]),w(e.storeTemplate)||(e.storeTemplate=f),t&&(this.#o=!0)}static get defaultDb(){return this.#i||(this.#i=new ve("gs-idb"))}get initialized(){return Object.isFrozen(this.#s)}get schema(){return this.#s}get storeNames(){return Array.from(new Set(this.#s.storeSchemas.map(e=>g(e)?e:e.name)))}get factory(){return this.#s.factory||(this.#s.factory=de)}static releaseDefaultDB(){this.#i=void 0}static async openExistDb(e){const{generateDbSchema:t}=await Promise.resolve().then(function(){return je});return new ve(await t(e))}static store(e,t){return ve.defaultDb.store(e,t)}static stores(e){return ve.defaultDb.stores(e)}static map(e,t){return ve.defaultDb.map(e,t)}async openNativeDb(){const e=this.#s=P(this.initSchema());await this.#u();const{name:t,version:r}=e;return await N({name:t,version:r,onupgradeneeded:(t,r,n)=>async function(e,t,r,n){const{storeSchemas:a,beforeUpgrade:i,afterUpgrade:s,version:o}=e,{newVersion:c=o,oldVersion:u}=r,{transaction:h}=n,d=new be({database:t,newVersion:c,oldVersion:u,dbSchema:e,transaction:h});try{const e=[];if(y(i))try{await i(d)}catch(t){e.push(t)}for(const t of a.map(e=>e.name))try{d.store(t)}catch(t){e.push(t)}for(const{name:t,defaultData:r}of a)if(r)try{await d.store(t).add({oldMax:0},r)}catch(t){e.push(t)}for(const{name:t,versionData:r}of a)if(r)for(const{version:n,data:a,use:i="addOrChange"}of r)try{await d.store(t)[i](n,a)}catch(t){e.push(t)}for(const{name:t,storeDefined:r}of a)try{await(r?.(d.store(t)))}catch(t){e.push(t)}if(y(s))try{await s(d)}catch(t){e.push(t)}if(!e.length)return;throw 1===e.length?e[0]:new AggregateError(e,"Database upgrade error")}finally{!function(e){try{e?.destroy?.()}catch{}}(d)}}(e,t,r,n)})}store(e,t){const r=e.store?e:{store:e};return r.store||(r.store=e),r.index||(r.index=t),this.factory.newWriter(Se(r,this.schema),this)}stores(e){const{schema:t}=this,r=e.map(e=>Se(g(e)?{store:e}:e,t));return this.factory.newDataOperators(r,this)}initSchema(){if(this.initialized)return this.#s;const{validateSchemaWithDefaults:e=me}=this.#s;return this.#s=e(this.#s)}async traceSchema(e){await async function(...e){const t=globalThis.top?.console?.log||console.log;e.push(t),await j(...e)}(this.schema,e)}map(e,t){const r=g(e)?e:g(t)?t:"gs-storage-map";Array.isArray(e)&&(t=e);const{storeSchemas:n}=this.schema;return n.find(e=>e.name===r||e===r)||n.push({...xe,name:r,defaultData:t}),this.factory.newDbMap({target:{store:r}},this)}export(){return this.stores(this.storeNames).export()}import(e,t,r){return this.stores(this.storeNames).import(e,t,r)}getStoreSchema(e){if(e in this.#c)return this.#c[e];const t=this.schema.storeSchemas.findIndex(t=>t===e||t.name===e);let r=this.schema.storeSchemas[t];return this.initialized?this.#c[e]=r:g(r)&&(this.schema.storeSchemas[t]=r={name:r}),r}async#u(){let e=this.#o;if(void 0===e&&(e=this.#o=await async function(e){const{name:t,version:r}=e,n=await C(t);if(!n)return!0;const{versionDiffValidate:a,versionSameValidate:i}=e,s=await N(t);try{if(e.version<s.version)return"The existing database version is greater than the current version";const o=void 0===e.version||s.version===e.version?i:a;if(!o)return!0;const c=Array.from(s.objectStoreNames);if(c.length<1)return`The existing database [ ${t} ] is empty`;const u=await K(s,c),h=await o({schema:e,db:s,stores:u});if(g(h)||r!==n.version)return h}finally{s?.close()}return!0}(this.#s)),!0===e)return!0;if(g(e))throw new Error(e)}}function ke(e,t){return ve.defaultDb.store(e,t)}function De(e,t){return ve.defaultDb.map(e,t)}function Pe(e){return ve.defaultDb.stores(e)}function $e(){ve.releaseDefaultDB()}function Oe(e,t){const r=Array.from(e.indexNames).map(t=>e.index(t)),n=[],a=[];for(const{name:e,keyPath:t,unique:i,multiEntry:s}of r)Array.isArray(t)?a.push(...t):a.push(t),n.push({name:e,keyPath:t,unique:i,multiEntry:s});const i=new Set(a);return{indexSchemas:n,addedTimeField:Ee(t.addedTimeField,i),updatedTimeField:Ee(t.updatedTimeField,i),updatedCountField:Ee(t.updatedCountField,i),softDeletedField:Ee(t.softDeletedField,i)}}function Ee(e,t){return!!t.has(e)&&{name:e,isIndexed:!1}}async function Ie(e,t){if(!await C(e))throw new Error(`db [ ${e} ] not exist`);let{asString:r,specialFields:n=l,dataExportTarget:a}=t||{};!0===r&&(r=160),isNaN(r)||r<1&&(r=1);let i=await function(e,t){return N(e,async function(e){const r=Array.from(e.objectStoreNames),n=e.transaction(r,"readonly");try{return{name:e.name,version:e.version,storeSchemas:r.map(e=>function(e,t){const{name:r,keyPath:n,autoIncrement:a}=e;return{name:r,keyPath:n,autoIncrement:a,...Oe(e,t)}}(n.objectStore(e),t))}}finally{n.abort()}})}(e,n);return a&&await async function(e,t){const r=await new ve(D(e),!0).export();for(const n of e.storeSchemas){const a=r[n.name];a?.length&&("defaultData"===t?n.defaultData=a:"versionData"===t&&(n.versionData||(n.versionData=[]),n.versionData.push({version:{oldMax:e.version},data:a})))}return e}(i,a),r?await j({rootData$:i,spaceEffectiveLength:r}):i}var je=Object.freeze({__proto__:null,generateDbSchema:Ie});export{a as Break,s as Continue,o as ContinueKey,u as ContinuePrimaryKey,U as DataOperationBase,G as DataOperators,Y as DataReader,ne as DataWriter,L as DbIterator,r as DbIteratorParsers,ae as DbMap,t as Delete,i as Finished,ve as IDbPro,c as NextKey,h as NextPrimaryKey,e as Save,he as StoreUpgradeable,be as UpgradeContext,De as dbMap,ke as dbStore,Pe as dbStores,l as defaultSpecialFields,f as defaultStoreSchemaTemplate,Ie as generateDbSchema,z as isIDbQuery,d as isNativeTarget,n as parseDbNoneKeyPathRecord,W as parseIDbQuery,$e as releaseDefaultDB,me as validateSchemaWithDefaults,se as versionDiffValidate,oe as versionSameValidate};
|
|
1
|
+
const e=Symbol("save"),t=Symbol("delete"),r=Object.freeze({key:({primaryKey:e})=>({value:e}),value:({value:e})=>({value:e}),keyValue:({primaryKey:e,value:t})=>({value:[e,t]})});function n(e){if(Array.isArray(e))return{key:e[1],value:e[0]};if("value"in e){const{key:t,value:r}=e;return{key:t,value:r}}throw new Error(`not include value in invalid DBRecord:${JSON.stringify(e)}`)}const a=Symbol("break"),i=Symbol("finished"),s=Symbol("continue"),o=Symbol("continue key"),c=Symbol("next key"),u=Symbol("continue primary key"),h=Symbol("next primary key");function d(e){return e instanceof IDBObjectStore||e instanceof IDBIndex}const f=Object.freeze({keyPath:"id",autoIncrement:!0,addedTimeField:!0,updatedTimeField:!0}),l=Object.freeze({addedTimeField:"added_at",softDeletedField:"deleted",updatedCountField:"updated_count",updatedTimeField:"updated_at"});function y(e){return e instanceof Function||"function"==typeof e}function m(e){return!0===e||!1===e||e instanceof Boolean||"boolean"==typeof e}function p(e){return"number"==typeof e||e instanceof Number}function g(e){return"string"==typeof e||e instanceof String}function w(e){return e&&(t=e,!(Array.isArray(t)||t instanceof Array||t?.constructor===Array))&&!y(e)&&(e instanceof Object||"object"==typeof e);var t}function b(e){return null!=e&&y(e[Symbol.iterator])}function S(e){return null!=e&&y(e[Symbol.asyncIterator])}function x(e){return null!=e&&"function"==typeof e.next}async function v(e,t){for(let r=0;r<e.length;r++)await t(e[r])}async function k(e,t){const r=await e,n=[];for(let e=0;e<r.length;e++)n.push(await t(r[e],e,r));return n}function D(e){if("object"!=typeof e||null===e||e instanceof Date||e instanceof Function||e instanceof RegExp||typeof Element<"u"&&e instanceof Element)return e;if(e instanceof Set){const t=new Set;for(const r of e)t.add(D(r));return t}if(e instanceof Map){const t=new Map;for(const[r,n]of e)t.set(D(r),D(n));return t}if(Array.isArray(e)){const t=[];for(const r of e)t.push(D(r));return t}const t={};for(const[r,n]of Object.entries(e))t[r]=D(n);return t}function P(e){return Object.freeze(e),Object.getOwnPropertyNames(e).forEach(t=>{const r=e[t];null!==r&&("object"==typeof r||"function"==typeof r)&&!Object.isFrozen(r)&&P(r)}),e}class ${rootData$;space;showFn;spaceEffectiveLength;out;type;ignoreCircularRef;constructor(e){let t=0;w(e[t])&&e[t].rootData$&&Object.assign(this,e[t++]),t<1&&(this.rootData$=e[t++]);const r=e.slice(t),n=r.filter(e=>p(e));void 0===this.out&&(this.out=r.find(e=>y(e))||null),void 0===this.showFn&&(this.showFn=!!r.find(e=>m(e))),void 0===this.spaceEffectiveLength&&(this.spaceEffectiveLength=n[0]||100),void 0===this.space&&(this.space=n[1]||2),void 0===this.type&&(this.type=r.find(e=>g(e))||"js"),void 0===this.ignoreCircularRef&&(this.ignoreCircularRef=!0)}destroy(){this.out=null,this.rootData$=null}}async function O(e,t,r){if("string"==typeof(e=await e)||e instanceof Date)return JSON.stringify(e);if(e instanceof Function)return t.showFn?e.toString():"undefined";if("object"!=typeof e||null===e)return e+"";if(e instanceof RegExp)return e.toString();if(typeof Element<"u"&&e instanceof Element)return"undefined";if(r.has(e)){if(t.ignoreCircularRef)return;throw new Error("circular reference")}r.add(e);try{return"json"===t.type?await async function(e,t,r){const n=[];if(Array.isArray(e)||e instanceof Set||b(e)&&!(e instanceof Map)){for(const a of e)if(void 0!==a&&(!y(a)||t.showFn)){const e=await O(a,t,r);void 0!==e&&n.push(e)}const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`[${a}${s()}${i}]`:"[]"}if(S(e)||x(e)){for await(const a of e)if(void 0!==a&&(!y(a)||t.showFn)){const e=await O(a,t,r);void 0!==e&&n.push(e)}const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`[${a}${s()}${i}]`:"[]"}let a=e instanceof Map?e.entries():Object.entries(e);for(const[e,i]of a)if(void 0!==i&&(!y(i)||t.showFn)){const a=await O(i,t,r);void 0!==a&&n.push(`"${e}": ${a}`)}const{spaceStart:i,spaceEnd:s,arrJoin:o}=E(n,t);return n.length?`[${i}${o()}${s}]`:"[]"}(e,t,r):await async function(e,t,r){const n=[];if(e instanceof Set){for(const a of e)(!y(a)||t.showFn)&&n.push(await O(a,t,r));const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`new Set([${a}${s()}${i}])`:"[]"}if(e instanceof Map){for(const[a,i]of e)(!y(i)||t.showFn)&&n.push(`${I(await O(a,t,r))}: ${await O(i,t,r)}`);const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`new Map(Object.entries({${a}${s()}${i}})`:"new Map()"}if(Array.isArray(e)||b(e)){for(const a of e)(!y(a)||t.showFn)&&n.push(await O(a,t,r));const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`[${a}${s()}${i}]`:"[]"}if(x(e)||S(e)){for await(const a of e)(!y(a)||t.showFn)&&n.push(await O(a,t,r));const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`[${a}${s()}${i}]`:"[]"}for(const[a,i]of Object.entries(e))(!y(i)||t.showFn)&&n.push(`${I(a)}: ${await O(i,t,r)}`);const{spaceStart:a,spaceEnd:i,arrJoin:s}=E(n,t);return n.length?`{${a}${s()}${i}}`:"{}"}(e,t,r)}finally{r.delete(e)}}function E(e,t){let r=t.space;e.reduce((e,t)=>e+t.length,0)<t.spaceEffectiveLength&&(r=0);const n=r?"\n"+"".padStart(r):"",a=r?"\n":"",i=r?"\n".padEnd(r+1):",";return{spaceStart:n,spaceEnd:a,arrJoin:r?()=>e.join(",\n").replace(/\n/g,i):()=>e.join(",")}}function I(e){return/^[a-z_]+\w*$/i.test(e)?e:`"${e}"`}async function j(...e){const t=new $(e),r=new Set;try{const e=await O(t.rootData$,t,r);if(!t.out)return e;t.out(e)}finally{r.clear(),t.destroy()}}function F(e){return e instanceof Function||"function"==typeof e}function M(e){return"string"==typeof e||e instanceof String}var A,q;function R(e){return"string"==typeof(t=e)||"number"==typeof t||t instanceof String||t instanceof Number||e instanceof Date||e instanceof ArrayBuffer||Array.isArray(e)&&e.every(R);var t}function B(e){return null==e||function(e){return e instanceof IDBKeyRange||R(e)}(e)}async function C(e){return(await indexedDB.databases()).find(t=>t.name===e)}async function N(e,t){const r=M(e)?{name:e}:e;F(t)&&(r.onsuccess=t);const{name:n,onsuccess:a,onupgradeneeded:i,version:s}=r;return function(e,t,r){return new Promise(async(n,a)=>{let i=!1;e.onsuccess=async()=>{if(!i)if(t)try{n(await t(e.result))}catch(e){a(e)}finally{e.result?.close?.()}else n(e.result)},e.onblocked=e.onerror=e=>a(e.target.error),r&&(e.onupgradeneeded=async t=>{try{await r(e.result,t,e)}catch(e){i=!0,a(e)}})})}(indexedDB.open(n,s),a,i)}function K(e,t,r){return function(e,t,...r){return new Promise(async(n,a)=>{let i=0;const s=F(r[i])?r[i++]:void 0,o=r[i]?"readwrite":"readonly",c=e instanceof IDBDatabase?e:await N(e),u=Array.isArray(t)?t:[t],h=c.transaction(u.map(e=>M(e)?e:e.store),o),d=u.map(e=>{if(M(e))return h.objectStore(e);const{store:t,index:r}=e;return M(r)?h.objectStore(t).index(r):h.objectStore(t)});if(s)try{n(await s(...d)),o?h.commit():h.abort()}catch(e){h.abort(),a(e)}finally{c.close()}else n(d)})}(e,t,r,!1)}function T(e){return new Promise(async(t,r)=>{e.onsuccess=()=>{try{t(e.result)}catch(e){r(e)}},e.onerror=e=>r(e.target.error)})}(q=A||(A={}))[q.True=1]="True",q[q.False=0]="False";const V=e=>e instanceof Date?e.getTime():e;function W(e){if(B(e))return e;const t=e;if("lt"in t&&"gt"in t){if(V(t.gt)>V(t.lt))throw new Error(`Invalid IDBRange: gt (${t.gt}) cannot be greater than lt (${t.lt})`);return IDBKeyRange.bound(t.gt,t.lt,!0,!0)}if("lt"in t&&"gte"in t){if(V(t.gte)>V(t.lt))throw new Error(`Invalid IDBRange: gte (${t.gte}) cannot be greater than lt (${t.lt})`);return IDBKeyRange.bound(t.gte,t.lt,!1,!0)}if("lte"in t&&"gt"in t){if(V(t.gt)>V(t.lte))throw new Error(`Invalid IDBRange: gt (${t.gt}) cannot be greater than lte (${t.lte})`);return IDBKeyRange.bound(t.gt,t.lte,!0,!1)}if("lte"in t&&"gte"in t){if(V(t.gte)>V(t.lte))throw new Error(`Invalid IDBRange: gte (${t.gte}) cannot be greater than lte (${t.lte})`);return IDBKeyRange.bound(t.gte,t.lte,!1,!1)}return"lt"in t?IDBKeyRange.upperBound(t.lt,!0):"lte"in t?IDBKeyRange.upperBound(t.lte,!1):"gt"in t?IDBKeyRange.lowerBound(t.gt,!0):"gte"in t?IDBKeyRange.lowerBound(t.gte,!1):void 0}function z(e){return null!=W(e)}async function _(e,t,r){const{query:n,direction:a="prev",preSkip:i,startKey:s,startPrimaryKey:o}=t,c=e.openCursor(W(n),a);return i&&(await T(c)).advance(i),s&&(o?(await T(c)).continuePrimaryKey(s,o):(await T(c)).continue(s)),c}function J(e,t,r){return Array.isArray(e)?t=>function(e,t,r){if(r?.length)for(const n of r)t.hasOwnProperty(n)&&(e[n]=t[n]);else Object.assign(e,t);return e}({},t,e):y(e)?e:t?e=>e:r?(e,t)=>[e,t]:(e,t)=>({key:e,value:t})}class U{idbPro;target;#e;constructor(e,t){this.idbPro=t,this.#e=e.storeSchema,this.target=e.target,d(e.target)&&(this.tx=this.#t)}get storeName(){return this.nativeStore?.name||this.target.store}get storeSchema(){if(this.#e)return this.#e;const e=this.idbPro.getStoreSchema(this.storeName);return Object.isFrozen(e)&&(this.#e=e),e}get factory(){return this.idbPro.factory}get nativeStore(){const{target:e}=this;return e instanceof IDBObjectStore?e:e instanceof IDBIndex?e.objectStore:void 0}get keyPath(){const{target:e}=this;if(d(e))return e.keyPath;const{storeSchema:t}=this,{index:r}=e;return r?t.indexSchemas.find(e=>e.name===r)?.keyPath:t.keyPath}async forEach(e,t){return e=y(e)?{fn:e}:e,t?this.cursorResult(e,!1):this.cursorVoid(e,!1)}async tx(e,t,r){let{target:n}=this;const{store:a,index:i}=n,s=await this.idbPro.openNativeDb();let o,c;try{o=s.transaction(a,!0===e?"readwrite":"readonly"),n=c=o.objectStore(a),i&&(n=n.index(i))}catch(e){throw s.close(),e}if(!t)return Object.freeze({db:s,tx:o,nativeStore:c,target:n});try{if(!0===e){const e=await t(n,c);return o.commit(),e}return t(n)}catch(e){throw!1!==r&&o.abort(),e}finally{s.close()}}openCursor(e,t){return this.tx(t,t=>new Promise(async(r,n)=>{const{fn:a}=e,i=await _(t,e);i.onsuccess=async()=>{i.result?!1===await a(i.result)&&r():r()},i.onerror=()=>n(i.error)}))}cursorVoid({query:r,direction:n,preSkip:i,startKey:s,startPrimaryKey:c,fn:h},d){let f=0;return this.openCursor({query:r,direction:n,preSkip:i,startKey:s,startPrimaryKey:c,fn:async r=>{const{value:n,primaryKey:i}=r,s=await h(n,i,f++),{control:c,key:l,primaryKey:y,modify:m,value:p}=w(s)?s:{control:s};switch(d&&(m===e?r.update(p||n):m===t&&r.delete()),c){case a:return!1;case o:r.continue(l);break;case u:r.continuePrimaryKey(l,y);break;default:r.continue()}}},!0)}async cursorResult({query:r,direction:n,preSkip:s,startKey:d,startPrimaryKey:f,fn:l,mapper:y},m){const{keyPath:p,defaultGetMapper:g}=this.storeSchema,w=J(y||g,p),b=[];let S=0;return await this.openCursor({query:r,direction:n,preSkip:s,startKey:d,startPrimaryKey:f,fn:async r=>{const{value:n,primaryKey:s}=r,{control:d,value:f,key:y,primaryKey:p,modify:g}=await(l?.(n,s,S,b))||{};switch(m&&(g===e?r.update(f||n):g===t&&r.delete()),(!d||d===i||d===c||d===h)&&b.push(w(f||n,p||s,S)),d){case a:case i:return!1;case c:case o:r.continue(y);break;case h:case u:r.continuePrimaryKey(y,p);break;default:r.continue()}S++}},m),b}#t(e,t){const{target:r}=this,n=r instanceof IDBObjectStore?r:r.objectStore;return t?t(r,n):Object.freeze({nativeStore:n,target:r})}}class G{idbPro;schemas;#r;constructor(e,t){this.idbPro=e,this.schemas=t}get storeNames(){return this.#r||(this.#r=Array.from(new Set(this.schemas.map(e=>e.target.store))))}read(e){return this.tx("newReader",e)}write(e,t=!0){return this.tx("newWriter",e,!0,t)}export(){return this.tx("newReader",async(...e)=>{const t={};for(const r of e)t[r.storeName]=await r.export();return t})}import(e,t,r){return r||(r="addOrChangeMany"),this.tx("newWriter",async(...n)=>{const a={};n=Array.from(new Map(n.map(e=>[e.storeName,e.asStore(!0)])).values());for(const i of n){const{storeName:n}=i,s=e[n];s&&(a[n]=await i[r](s,t))}if(t)return a},!0)}async tx(e,t,r,n){const{idbPro:a,schemas:i}=this,{factory:s}=a.schema,o=await a.openNativeDb();try{const c=o.transaction(this.storeNames,r?"readwrite":"readonly");try{const n=i.map(({storeSchema:t,target:r})=>{let n=c.objectStore(r.store);return r.index&&(n=n.index(r.index)),s[e]({storeSchema:t,target:n},a)});if(r){const e=await t(...n);return c.commit(),e}return await t(...n)}catch(e){throw!1!==n&&c.abort(),e}}finally{o.close()}}}class L extends U{direction;query;writable;parser;endsWithNull;preSkip;startKey;startPrimaryKey;constructor(e,t,n){if(super(e,t),!n)return;const{parser:a}=n;this.direction=n.direction,this.query=n.query,this.writable=!!n.writable,this.endsWithNull=!!n.endsWithNull,this.preSkip=n.preSkip,this.startKey=n.startKey,this.startPrimaryKey=n.startPrimaryKey,a&&(this.parser=y(a)?a:r[a])}async*[Symbol.asyncIterator](){const{parser:e,writable:t,endsWithNull:r}=this,{db:n,tx:i,target:s}=await this.tx(t);try{const n=await _(s,this);let o;if(e)for(;o=await T(n);){const{control:t,value:r}=await e(o);if(t||(yield r),t===a)break;o.continue()}else{let e=!1;const t=()=>{e=!0};for(;!e&&(o=await T(n));)yield{cursor:o,end:t}}t&&i?.commit(),r&&!o&&(yield null)}finally{n?.close()}}}function X(e,t,r,n){const a=w(e)?e:{};return y(e)?a.fn=e:z(e)&&(a.query=e),y(t)?a.fn=t:t&&(a.direction=t),r&&(a.direction=r),n?a.limit=n:a.limit||(a.limit=1e3),a.maxEmptyChecks||(a.maxEmptyChecks=2e4),a}async function H(e,t,r){t.size||(t.size=100),t.nextSkip||(t.nextSkip=0);const{query:n,direction:a,total:i,maxEmptyChecks:s,fn:o}=t;return await e.batchRead(async e=>(i||(t.total=await e.count({query:n,direction:a,maxEmptyChecks:s,fn:o}),t.pages=Math.ceil(t.total/t.size)),t.total<1?{info:P(t),rows:[]}:o?await async function(e,t,r){t.maxEmptyChecks||(t.maxEmptyChecks=2e4);const{page:n,query:a,direction:i,nextSkip:s}=t,{keyPath:o}=e.storeSchema;return 1===n?await Q(e,await _(e.target,{query:a,direction:i}),t,o):r&&s&&n-r.page===1?await Q(e,await _(e.target,{query:a,direction:i,preSkip:s}),t,o):await Q(e,await _(e.target,{query:a,direction:i}),t,o,!0)}(e,t,r):await async function(e,t){const{keyPath:r}=e.storeSchema,{page:n,query:a,direction:i,size:s,mapper:o}=t,c=(n-1)*s,u=await e.filter({query:a,preSkip:c,direction:i,limit:s,mapper:J(o,r,!0)});return t.nextSkip=c+u.length,{info:P(t),rows:u}}(e,t)))}async function Q({storeSchema:{defaultGetMapper:e}},t,r,n,a){const{page:i,size:s,total:o,maxEmptyChecks:c,fn:u}=r,h=J(r.mapper||e,n,!0),d=[],f=(i-1)*r.size;if(f>=o)return{info:P(r),rows:[]};let l=0;return await new Promise(async(e,r)=>{let n=0,i=0;const o=async()=>{const{result:r}=t;if(!r)return e();let{value:a,primaryKey:i}=r;if(await u(a,i,l)?(n=0,d.push(h(a,i,l))):n++,d.length>=s||n>=c)return e();l++,r.continue()};t.onerror=()=>r(t.error),t.onsuccess=a?async()=>{const{result:r}=t;if(!r)return e();let{value:a,primaryKey:s}=r;if(await u(a,s,l)?(n=0,i++):n++,i>=f||n>=c)return l=n=0,t.onsuccess=o,void r.continue();r.continue(),l++}:o}),l&&(r.nextSkip+=l+1),{info:P(r),rows:d}}class Y extends U{all(e,t){const r={};return p(t)&&(r.limit=t),z(e)?r.query=e:w(e)&&Object.assign(r,e),this.tx(!1,e=>T(e.getAll(W(r.query),r.limit||1e3)))}async count(e,t,r){const n=X(e,t,r),{query:a,direction:i,fn:s}=n;if(!s)return await this.tx(!1,e=>T(e.count(W(a))));const{maxEmptyChecks:o}=n,c=s;let u=0,h=0,d=0;return await this.openCursor({query:a,direction:i,fn:e=>{if(c(e.value,e.primaryKey,d++))u++,h=0;else if(++h>=o)return!1;e.continue()}}),u}get(e){return this.tx(!1,t=>T(t.get(W(e))))}getMany(e,t){return this.batchRead(async r=>{const n=await k(e,e=>r.get(e));return t?n.filter(e=>e):n})}getRange(e,t){return this.forEach({query:e,direction:t},!0)}async getRangeMany(e,t,r){return(await this.batchRead(r=>k(e,e=>r.getRange(e,t)))).flat()}index(e,t){let{target:r}=this;return r instanceof IDBIndex&&(r=r.objectStore),r instanceof IDBObjectStore?(r=r.index(e),this.createOperator(r,t)):this.idbPro.store(r.store,e)}asStore(e){let{target:t}=this;if(t instanceof IDBObjectStore)return this;if(t instanceof IDBIndex)t=t.objectStore;else{if(!("index"in t))return this;t={store:t.store}}return this.createOperator(t,e)}batchRead(e){return d(this.target)?e(this):this.tx(!1,t=>e(this.idbPro.schema.factory.newReader({storeSchema:this.storeSchema,target:t},this.idbPro)))}iterator(e,t){const r={};return g(t)&&(r.direction=t),z(e)?r.query=e:w(e)&&Object.assign(r,e),new L({storeSchema:this.storeSchema,target:this.target},this.idbPro,{...r,parser:"value"})}async filter(e,t,r,n){const o=X(e,t,r,n),{maxEmptyChecks:c,limit:u,fn:h}=o,{keyPath:d,defaultGetMapper:f}=this.storeSchema,l=J(o.mapper||f,d,!0);if(!h)return await this.forEach({...o,mapper:l,fn:(e,t,r)=>{if(r>=u-1)return{control:i}}},!0);let y=0;return this.forEach({...o,mapper:l,fn:(e,t,r,n)=>h(e,t,r)?(y=0,n.length>=u-1?{control:i}:void 0):++y>=c?{control:a}:{control:s}},!0)}async find(e,t,r){const[n]=await this.filter(e,t,r,1);return n}async page(e,t){const r={...e};return r.page=t||e?.page||1,H(this,r,e)}nextPage(e){return this.page(e,e.page+1)}export(e,t){const r=X(e,t),{keyPath:n,exportMapper:a,name:i,defaultGetMapper:s}=this.storeSchema;if(!n&&Array.isArray(a))throw new Error(`When store [ ${i} ] keyPath does not exist, exportMapper does not support string[].`);return r.direction="next",r.mapper=J(a||s,n,!0),r.limit=r.maxEmptyChecks=Number.MAX_SAFE_INTEGER,this.filter(r)}asMap(){let{target:e}=this;return e instanceof IDBIndex?e=e.objectStore:e instanceof IDBObjectStore||(e={store:e.store}),this.factory.newDbMap({target:e},this.idbPro)}createOperator(e,t){const{idbPro:r}=this,n=this.storeSchema,a={storeSchema:Object.isFrozen(n)?n:void 0,target:e};return t?this.factory.newWriter(a,r):this.factory.newReader(a,r)}}function Z(e,t){if(!Array.isArray(e))return{[e]:t};const r={},n=e;for(let e=0;e<n.length;e++)r[n[e]]=t[e];return r}function ee(e,t){if(!Array.isArray(e))return t[e];const r=[];for(const n of e){if(!t[n])return;r.push(t[n])}return r}function te(e,t){if(!t||!(t instanceof Object)||Array.isArray(t))return t;const{addedTimeField:r,updatedTimeField:n,updatedCountField:a,softDeletedField:i}=e;return t={...t},r?.name&&!p(t[r.name])&&(t[r.name]=Date.now()),n?.name&&!p(t[n.name])&&(t[n.name]=Date.now()),i?.name&&!p(t[i.name])&&(t[i.name]=0),a?.name&&(t[a.name]=0),t}function re(e,t,r){if(!t||!(t instanceof Object)||Array.isArray(t))return t;const{updatedTimeField:n,updatedCountField:a}=e;return t={...r,...t},n.name&&(t[n.name]=Date.now()),a.name&&(t[a.name]=(t[a.name]||0)+1),t}class ne extends Y{add(e){return this.changeByPk({record:e,fn:async(e,t,r,n,a)=>{const{storeSchema:i}=this;return r=te(i,r),a?[{...r,...Z(a,await T(e.add(r)))},t]:[r,await T(e.add(r,t))]}})}addMany(e,t){return this.batchWrite(r=>t?k(e,e=>r.add(e)):v(e,e=>r.add(e)),!0)}addOrSkip(e){return this.batchWrite(async t=>{const{keyPath:r,defaultGetMapper:a}=t.storeSchema,{key:i,value:s}=r?{key:ee(r,e),value:e}:n(e);if(i){const e=await T(t.nativeStore.get(i));if(e)return J(a,r)?.(e,i)}if(t.target instanceof IDBIndex){const{keyPath:r}=t,n=ee(r,s);if(!n)return t.add(e);let a=await t.find(n);if(a)return a}return t.add(e)})}addOrSkipMany(e,t){return this.batchWrite(r=>t?k(e,e=>r.addOrSkip(e)):v(e,e=>r.addOrSkip(e)),!0)}replace(e){return this.changeByPk({record:e,getOld:!0,fn:async(e,t,r,n,a)=>{const{storeSchema:i}=this,{updatedTimeField:s,updatedCountField:o,addedTimeField:c}=i;return r=n?re(i,r,{[s.name]:n[s.name],[o.name]:n[o.name],[c.name]:n[c.name]}):te(i,r),a?[{...r,...Z(a,await T(e.put(r)))},t]:[r,await T(e.put(r,t))]}})}replaceMany(e,t){return this.batchWrite(r=>t?k(e,e=>r.replace(e)):v(e,e=>r.replace(e)),!0)}change(e,t){return this.changeByPk({record:e,getOld:!0,requiredOld:t,requiredPk:t,fn:async(e,t,r,n,a)=>{const{storeSchema:i}=this;if(n)return r=re(i,r,n),a?[{...r,...Z(a,await T(e.put(r)))},t]:[r,await T(e.put(r,t))]}})}changeMany(e,t){const{returns:r,throwIfMissing:n}=m(t)?{returns:t}:t||{};return this.batchWrite(t=>r?k(e,e=>t.change(e,n)):v(e,e=>t.change(e,n)),!0)}addOrChange(e){return this.changeByPk({record:e,getOld:!0,fn:async(e,t,r,n,a)=>{const{storeSchema:i}=this;return n?(r=re(i,r,n),a?[{...r,...Z(a,await T(e.put(r)))},t]:[r,await T(e.put(r,t))]):(r=te(i,r),a?[{...r,...Z(a,await T(e.add(r)))},t]:[r,await T(e.add(r,t))])}})}addOrChangeMany(e,t){return this.batchWrite(r=>t?k(e,e=>r.addOrChange(e)):v(e,e=>r.addOrChange(e)),!0)}delete(e,t){return this.changeByPk({pk:e,getOld:t,fn:(e,r,n,a)=>{if(e.delete(r),t)return[a,r]}})}deleteMany(e,t){return this.batchWrite(r=>t?k(e,e=>r.delete(e,!0)):v(e,e=>r.delete(e)),!0)}deleteRange(r,n){const{returns:a,physical:i,direction:s}=m(n)?{returns:n}:n||{},{name:o}=this.storeSchema.softDeletedField||{};return this.cursor({query:r,direction:s,fn:r=>i||!o?{modify:t}:(r[o]=1,{modify:e})},a)}deleteRangeMany(e,t){const r=m(t)?{returns:t}:t;return this.batchWrite(t=>r?.returns?k(e,e=>t.deleteRange(e,r)):v(e,e=>t.deleteRange(e,r)),!0)}changeRange(t,r){let{direction:n="next",query:a,newValue:i}="newValue"in t?t:{newValue:t};if(a||(a=ee(this.keyPath,i)),!a)throw new Error(`query is required:${JSON.stringify(t)}`);return this.cursor({query:a,direction:n,fn:t=>t instanceof Object?{modify:e,value:{...t,...i}}:{modify:e,value:i}},r)}changeRangeMany(e,t){return this.batchWrite(r=>t?k(e,e=>r.changeRange(e,t)):v(e,e=>r.changeRange(e,t)),!0)}cursor(e,t){return(e=y(e)?{fn:e}:e||{}).fn?t?this.cursorResult(e,!0):this.cursorVoid(e,!0):new L(this,this.idbPro)}batchWrite(e,t){const{target:r}=this;if(d(r))try{return e(this)}catch(e){throw!1!==t&&(r instanceof IDBIndex?r.objectStore:r).transaction.abort(),e}return this.tx(!0,t=>e(this.idbPro.schema.factory.newWriter({storeSchema:this.storeSchema,target:t},this.idbPro)),t)}changeByPk({pk:e,record:t,fn:r,requiredPk:a,getOld:i,requiredOld:s,saveMapper:o,getMapper:c}){const{storeSchema:u}=this,{keyPath:h,defaultSaveMapper:d,defaultGetMapper:f}=u;return t&&(o||d)&&(t=J(o||d,h)?.(t)),this.batchWrite(async o=>{let u,d=t;if(e)u=W(e);else if(h)u=ee(h,t);else{const{key:e,value:r}=n(t);u=e,d=r}if(a&&!u)throw new Error(`key is required: ${JSON.stringify(t)}`);const l=u&&(i||s)?await T(o.nativeStore.get(u)):void 0;if(s&&!l)throw new Error(`record not found: ${JSON.stringify(t)}`);const y=await r(o.nativeStore,u,d,l,h);if(y)return J(c||f,h)?.(y[0],y[1])})}}class ae extends U{get size(){return this.tx(!1,e=>T(e.count()))}delete(e){return this.tx(!0,async(t,r)=>{r.delete(e)})}batch(e){const{idbPro:t,storeSchema:r,factory:n}=this;return this.tx(!0,async(a,i)=>await e(n.newDbMap({storeSchema:r,target:i},t)))}asStore(e){const{factory:t}=this.idbPro.schema;return e?t.newWriter(this,this.idbPro):t.newReader({target:this.target},this.idbPro)}entries(){return new L({target:this.target},this.idbPro,{parser:"keyValue"})}async get(e,t){return await this.tx(!1,t=>T(t.get(e)))||t}getMany(e){return this.tx(!1,async t=>{const r=[];for(const n of e)r.push(await T(t.get(n)));return r})}async has(e){return!!await this.get(e)}keys(){return new L({storeSchema:this.storeSchema,target:this.target},this.idbPro,{parser:"key"})}set(e,t){return this.tx(!0,async(r,n)=>{await T(n.put(t,e))})}setMany(e){return this.tx(!0,async(t,r)=>{for(const[t,n]of e)r.put(n,t)})}values(){return new L({storeSchema:this.storeSchema,target:this.target},this.idbPro,{parser:"value"})}}function ie(e,t){if(e==t)return!0;if(typeof e!=typeof t)return!1;if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}return!1}const se=({stores:e,schema:t})=>{const r=t.storeSchemas;let n="";for(const t of e){const e=r.find(e=>e.name===t.name);if(e){if(!ie(t.keyPath,e.keyPath)){n=`store [ ${t.name} ] keyPath not equal,schema.keyPath:${e.keyPath},store.keyPath:${t.keyPath}[]`;break}if(!t.autoIncrement!=!e.autoIncrement){n=`store [ ${t.name} ] autoIncrement not equal`;break}}}return!n||`The existing database is inconsistent with the definition and cannot be corrected: ${n}`},oe=async e=>{let t=se(e);return g(t)||(t=ce(e)),t},ce=({stores:e,schema:t})=>{const r=t.storeSchemas,n=e.map(e=>e.name);let a="";const i=r.map(e=>e.name).filter(e=>!n.includes(e));if(i.length)a=`store [ ${i.join(",")} ] not exist`;else for(const t of e){const e=r.find(e=>e.name===t.name);if(e&&(a=ue(t,Array.from(t.indexNames),e.indexSchemas),a))break}return!a||`The existing database Store index is inconsistent with the definition and requires a database version upgrade to be fixed: ${a}`};function ue(e,t,r){if(t.length!==r.length)return`store [ ${e.name} ] index count not equal`;for(const n of t){const t=r.find(e=>e.name===n);if(!t)return`store [ ${e.name} ] index [ ${n} ] not exist`;const a=e.index(n);if(!t.unique!=!a.unique)return`store [ ${e.name} ] index [ ${n} ] unique not equal`;if(!t.multiEntry!=!a.multiEntry)return`store [ ${e.name} ] index [ ${n} ] multiEntry not equal`;if(!ie(t.keyPath,a.keyPath))return`store [ ${e.name} ] index [ ${n} ] keyPath not equal`}return""}class he{upgradeContext;storeSchema;nativeStore;#n;constructor(e,t,r){this.upgradeContext=e,this.storeSchema=t,this.nativeStore=r}get writer(){return this.#n||(this.#n=this.upgradeContext.dbSchema.factory?.newWriter({target:this.nativeStore,storeSchema:this.storeSchema}))}add(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.addMany(t,r):Promise.resolve()}addOrChange(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.addOrChangeMany(t,r):Promise.resolve()}async call(e,t){if(this.upgradeContext.versionIn(e))return await t(this.writer,this.upgradeContext)}replace(e,t,r){return this.upgradeContext.versionIn(e)?this.writer.replaceMany(t,r):Promise.resolve()}}const de=Object.freeze({newDataOperators:(e,t)=>new G(t,e),newDbMap:(e,t)=>new ae(e,t),newReader:(e,t)=>new Y(e,t),newStoreUpgradeable:(e,t,r)=>new he(r,t,e),newWriter:(e,t)=>new ne(e,t)});function fe(e,t,r,n){const a=function(e,t,r){if(!1===e)return!1;if(g(e))return{name:e};if(w(e)){const r=e;return m(r.name)&&(r.name=t),e}if(!0===e||r)return{name:t};return!1}(t,r,n);if(!a)return a;const i=a;if(!1!==i.isIndexed){i.isIndexed||(i.isIndexed=!0);const{name:t}=i,r=e.indexSchemas;r.some(e=>e===t||e.name===t)||r.push(t)}return i}function le(e,t){let r=g(e)?{name:e}:e;return t&&(r={...t,...r}),r.indexSchemas||(r.indexSchemas=[]),function(e){Object.isFrozen(e)||(e.addedTimeField=fe(e,e.addedTimeField,"added_at",!0),e.updatedTimeField=fe(e,e.updatedTimeField,"updated_at",!0),e.updatedCountField=fe(e,e.updatedCountField,"updated_count",!1),e.softDeletedField=fe(e,e.softDeletedField,"deleted",!1))}(r),Object.isFrozen(r)||(r.indexSchemas=r.indexSchemas.map(ye)),function(e){if(!e.keyPath&&e.defaultData?.length)for(const t of e.defaultData)if(!Array.isArray(t)&&!("value"in t))throw new Error(`When \`defaultData\` must contain \`value\` fields or be an array:${JSON.stringify(t)}`)}(r),r}function ye(e){const t=g(e)?{name:e}:e;return t.keyPath||(t.keyPath=t.name),t}const me=e=>{const{versionDiffValidate:t,versionSameValidate:r,factory:n}=e;return e.storeSchemas||(e.storeSchemas=[]),e.storeTemplate||(e.storeTemplate={...f}),!t&&!1!==t&&(e.versionDiffValidate=se),!r&&!1!==r&&(e.versionSameValidate=oe),n?n!==de&&(e.factory={...de,...n}):e.factory=de,e.storeSchemas=e.storeSchemas.map(t=>le(t,e.storeTemplate)),e};function pe(e,t){(function(e,t){return e.unique===t.unique&&e.multiEntry===t.multiEntry&&ie(t.keyPath,e.keyPath)})(e.index(t.name),t)||(e.deleteIndex(t.name),ge(e,t))}function ge(e,t){try{e.createIndex(t.name,t.keyPath,{unique:t.unique,multiEntry:t.multiEntry})}catch{throw new Error(`store [ ${e.name} ] index [ ${t.name} ] create error: ${JSON.stringify(t)}`)}}function we(e,t){return e.database.objectStoreNames.contains(t.name)?function(e,t){const{indexSchemas:r}=e,n=t.indexNames,a=r.map(e=>e.name);for(const e of Array.from(n))a.includes(e)||t.deleteIndex(e);for(const e of r)n.contains(e.name)?pe(t,e):ge(t,e);return t}(t,e.transaction?.objectStore(t.name)):function(e,t){const r=t.createObjectStore(e.name,{keyPath:e.keyPath,autoIncrement:e.autoIncrement});for(const t of e.indexSchemas)ge(r,t);return r}(t,e.database)}class be{database;newVersion;oldVersion;dbSchema;transaction;#a={};constructor(e){this.database=e.database,this.newVersion=e.newVersion,this.oldVersion=e.oldVersion,this.dbSchema=e.dbSchema,this.transaction=e.transaction}deleteStoreIfExists(e){const t=this.database;t.objectStoreNames.contains(e)&&t.deleteObjectStore(e)}destroy(){try{!function(...e){for(const t of e)if(t)for(const e of Object.keys(t))try{t[e]?.destroy?.()}catch{}finally{delete t[e]}}(this.#a)}finally{for(const e of Object.keys(this.#a))delete this.#a[e]}}store(e){if(e in this.#a)return this.#a[e];const{factory:t}=this.dbSchema,{storeSchemas:r}=this.dbSchema,n=r.find(t=>t.name===e),a=we(this,n);return this.#a[e]=t.newStoreUpgradeable(a,n,this)}versionIn({oldMin:e,oldMax:t,newMax:r,newMin:n}){if(void 0===t&&void 0===r&&void 0===e&&void 0===n)throw new Error(`versionIn bounds must not be empty ${JSON.stringify({oldMax:t,newMax:r,oldMin:e,newMin:n})}`);if(t<e)throw new Error(`oldMax (${t}) cannot be less than oldMin (${e})`);if(r<n)throw new Error(`newMax (${r}) cannot be less than newMin (${n})`);const{oldVersion:a,newVersion:i}=this;return!(void 0!==e&&a<e||void 0!==t&&a>t||void 0!==n&&i<n)&&!(void 0!==r&&i>r)}}function Se(e,t){let{store:r,index:n}=e;const{storeTemplate:a}=t,{storeSchemas:i=[]}=t,s=g(r)?r:r.name,o=i.findIndex(e=>e===s||e.name===s),c=o>-1&&i[o];let u;u=g(r)?c||s:!c||g(c)||r===c?r:{...c,...r},(n||c?.indexSchemas?.length||r?.indexSchemas?.length)&&(g(u)&&(u={name:u}),u.indexSchemas=function(e,t,r){r&&t.push(r);for(const r of t){const t=g(r)?r:r.name,n=e.findIndex(e=>e===t||e.name===t);if(n>-1){const t=e[n];g(t)?e[n]=r:g(r)||(e[n]=Object.assign(t,r))}else e.push(r)}return e}(c.indexSchemas||[],r.indexSchemas||[],n));const h=le(u,a);o>-1?i[o]=h:i.push(h),t.storeSchemas=i;const d={store:s};return n&&(d.index=g(n)?n:n.name),{target:d}}const xe=Object.assign({name:"",addedTimeField:!1,autoIncrement:!1,indexSchemas:[],keyPath:void 0,softDeletedField:!1,updatedCountField:!1,updatedTimeField:!1});class ve{static#i;#s;#o;#c={};constructor(e,t){this.#s=e=g(e)?{name:e}:e,Array.isArray(e.storeSchemas)||(e.storeSchemas=[]),w(e.storeTemplate)||(e.storeTemplate=f),t&&(this.#o=!0)}static get defaultDb(){return this.#i||(this.#i=new ve("gs-idb"))}get initialized(){return Object.isFrozen(this.#s)}get schema(){return this.#s}get storeNames(){return Array.from(new Set(this.#s.storeSchemas.map(e=>g(e)?e:e.name)))}get factory(){return this.#s.factory||(this.#s.factory=de)}static releaseDefaultDB(){this.#i=void 0}static async openExistDb(e){const{generateDbSchema:t}=await Promise.resolve().then(function(){return je});return new ve(await t(e))}static store(e,t){return ve.defaultDb.store(e,t)}static stores(e){return ve.defaultDb.stores(e)}static map(e,t){return ve.defaultDb.map(e,t)}async openNativeDb(){const e=this.#s=P(this.initSchema());await this.#u();const{name:t,version:r}=e;return await N({name:t,version:r,onupgradeneeded:(t,r,n)=>async function(e,t,r,n){const{storeSchemas:a,beforeUpgrade:i,afterUpgrade:s,version:o}=e,{newVersion:c=o,oldVersion:u}=r,{transaction:h}=n,d=new be({database:t,newVersion:c,oldVersion:u,dbSchema:e,transaction:h});try{const e=[];if(y(i))try{await i(d)}catch(t){e.push(t)}for(const t of a.map(e=>e.name))try{d.store(t)}catch(t){e.push(t)}for(const{name:t,defaultData:r}of a)if(r)try{await d.store(t).add({oldMax:0},r)}catch(t){e.push(t)}for(const{name:t,versionData:r}of a)if(r)for(const{version:n,data:a,use:i="addOrChange"}of r)try{await d.store(t)[i](n,a)}catch(t){e.push(t)}for(const{name:t,storeDefined:r}of a)try{await(r?.(d.store(t)))}catch(t){e.push(t)}if(y(s))try{await s(d)}catch(t){e.push(t)}if(!e.length)return;throw 1===e.length?e[0]:new AggregateError(e,"Database upgrade error")}finally{!function(e){try{e?.destroy?.()}catch{}}(d)}}(e,t,r,n)})}store(e,t){const r=e.store?e:{store:e};return r.store||(r.store=e),r.index||(r.index=t),this.factory.newWriter(Se(r,this.schema),this)}stores(e){const{schema:t}=this,r=e.map(e=>Se(g(e)?{store:e}:e,t));return this.factory.newDataOperators(r,this)}initSchema(){if(this.initialized)return this.#s;const{validateSchemaWithDefaults:e=me}=this.#s;return this.#s=e(this.#s)}async traceSchema(e){await async function(...e){const t=globalThis.top?.console?.log||console.log;e.push(t),await j(...e)}(this.schema,e)}map(e,t){const r=g(e)?e:g(t)?t:"gs-storage-map";Array.isArray(e)&&(t=e);const{storeSchemas:n}=this.schema;return n.find(e=>e.name===r||e===r)||n.push({...xe,name:r,defaultData:t}),this.factory.newDbMap({target:{store:r}},this)}export(){return this.stores(this.storeNames).export()}import(e,t,r){return this.stores(this.storeNames).import(e,t,r)}getStoreSchema(e){if(e in this.#c)return this.#c[e];const t=this.schema.storeSchemas.findIndex(t=>t===e||t.name===e);let r=this.schema.storeSchemas[t];return this.initialized?this.#c[e]=r:g(r)&&(this.schema.storeSchemas[t]=r={name:r}),r}async#u(){let e=this.#o;if(void 0===e&&(e=this.#o=await async function(e){const{name:t,version:r}=e,n=await C(t);if(!n)return!0;const{versionDiffValidate:a,versionSameValidate:i}=e,s=await N(t);try{if(e.version<s.version)return"The existing database version is greater than the current version";const o=void 0===e.version||s.version===e.version?i:a;if(!o)return!0;const c=Array.from(s.objectStoreNames);if(c.length<1)return`The existing database [ ${t} ] is empty`;const u=await K(s,c),h=await o({schema:e,db:s,stores:u});if(g(h)||r!==n.version)return h}finally{s?.close()}return!0}(this.#s)),!0===e)return!0;if(g(e))throw new Error(e)}}function ke(e,t){return ve.defaultDb.store(e,t)}function De(e,t){return ve.defaultDb.map(e,t)}function Pe(e){return ve.defaultDb.stores(e)}function $e(){ve.releaseDefaultDB()}function Oe(e,t){const r=Array.from(e.indexNames).map(t=>e.index(t)),n=[],a=[];for(const{name:e,keyPath:t,unique:i,multiEntry:s}of r)Array.isArray(t)?a.push(...t):a.push(t),n.push({name:e,keyPath:t,unique:i,multiEntry:s});const i=new Set(a);return{indexSchemas:n,addedTimeField:Ee(t.addedTimeField,i),updatedTimeField:Ee(t.updatedTimeField,i),updatedCountField:Ee(t.updatedCountField,i),softDeletedField:Ee(t.softDeletedField,i)}}function Ee(e,t){return!!t.has(e)&&{name:e,isIndexed:!1}}async function Ie(e,t){if(!await C(e))throw new Error(`db [ ${e} ] not exist`);let{asString:r,specialFields:n=l,dataExportTarget:a}=t||{};!0===r&&(r=160),isNaN(r)||r<1&&(r=1);let i=await function(e,t){return N(e,async function(e){const r=Array.from(e.objectStoreNames),n=e.transaction(r,"readonly");try{return{name:e.name,version:e.version,storeSchemas:r.map(e=>function(e,t){const{name:r,keyPath:n,autoIncrement:a}=e;return{name:r,keyPath:n,autoIncrement:a,...Oe(e,t)}}(n.objectStore(e),t))}}finally{n.abort()}})}(e,n);return a&&await async function(e,t){const r=await new ve(D(e),!0).export();for(const n of e.storeSchemas){const a=r[n.name];a?.length&&("defaultData"===t?n.defaultData=a:"versionData"===t&&(n.versionData||(n.versionData=[]),n.versionData.push({version:{oldMax:e.version},data:a})))}return e}(i,a),r?await j({rootData$:i,spaceEffectiveLength:r}):i}var je=Object.freeze({__proto__:null,generateDbSchema:Ie});export{a as Break,s as Continue,o as ContinueKey,u as ContinuePrimaryKey,U as DataOperationBase,G as DataOperators,Y as DataReader,ne as DataWriter,L as DbIterator,r as DbIteratorParsers,ae as DbMap,t as Delete,i as Finished,ve as IDbPro,c as NextKey,h as NextPrimaryKey,e as Save,he as StoreUpgradeable,be as UpgradeContext,De as dbMap,ke as dbStore,Pe as dbStores,l as defaultSpecialFields,f as defaultStoreSchemaTemplate,Ie as generateDbSchema,z as isIDbQuery,d as isNativeTarget,n as parseDbNoneKeyPathRecord,W as parseIDbQuery,$e as releaseDefaultDB,me as validateSchemaWithDefaults,se as versionDiffValidate,oe as versionSameValidate};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "gs-idb-pro",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.1",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "lib/index.cjs",
|
|
6
6
|
"module": "lib/index.js",
|
|
@@ -13,5 +13,13 @@
|
|
|
13
13
|
"dependencies": {
|
|
14
14
|
"gs-base": "latest",
|
|
15
15
|
"gs-idb-basic": "latest"
|
|
16
|
-
}
|
|
16
|
+
},
|
|
17
|
+
"keywords": [
|
|
18
|
+
"indexedDB",
|
|
19
|
+
"webSQL",
|
|
20
|
+
"idb",
|
|
21
|
+
"orm",
|
|
22
|
+
"数据库",
|
|
23
|
+
"浏览器数据库"
|
|
24
|
+
]
|
|
17
25
|
}
|