import{ConstraintError}from"./errors.js";import extractKey from"./extractKey.js";import RecordStore from"./RecordStore.js";import valueToKey from"./valueToKey.js";class Index{deleted=!1;initialized=!1;records=new RecordStore;constructor(rawObjectStore,name,keyPath,multiEntry,unique){this.rawObjectStore=rawObjectStore,this.name=name,this.keyPath=keyPath,this.multiEntry=multiEntry,this.unique=unique}getKey(key){const record=this.records.get(key);return void 0!==record?record.value:void 0}getAllKeys(range,count){void 0!==count&&0!==count||(count=1/0);const records=[];for(const record of this.records.values(range))if(records.push(structuredClone(record.value)),records.length>=count)break;return records}getValue(key){const record=this.records.get(key);return void 0!==record?this.rawObjectStore.getValue(record.value):void 0}getAllValues(range,count){void 0!==count&&0!==count||(count=1/0);const records=[];for(const record of this.records.values(range))if(records.push(this.rawObjectStore.getValue(record.value)),records.length>=count)break;return records}storeRecord(newRecord){let indexKey;try{indexKey=extractKey(this.keyPath,newRecord.value)}catch(err){if("DataError"===err.name)return;throw err}if(this.multiEntry&&Array.isArray(indexKey)){const keep=[];for(const part of indexKey)if(keep.indexOf(part)<0)try{keep.push(valueToKey(part))}catch(err){}indexKey=keep}else try{valueToKey(indexKey)}catch(e){return}if(this.multiEntry&&Array.isArray(indexKey)){if(this.unique)for(const individualIndexKey of indexKey){if(this.records.get(individualIndexKey))throw new ConstraintError}}else if(this.unique){if(this.records.get(indexKey))throw new ConstraintError}if(this.multiEntry&&Array.isArray(indexKey))for(const individualIndexKey of indexKey)this.records.add({key:individualIndexKey,value:newRecord.key});else this.records.add({key:indexKey,value:newRecord.key})}initialize(transaction){if(this.initialized)throw new Error("Index already initialized");transaction._execRequestAsync({operation:()=>{try{for(const record of this.rawObjectStore.records.values())this.storeRecord(record);this.initialized=!0}catch(err){transaction._abort(err.name)}},source:null})}count(range){let count=0;for(const record of this.records.values(range))count+=1;return count}}export default Index;