Files
Obsidian/.obsidian/plugins/obsidian-livesync/main.js
2026-02-04 17:04:00 +08:00

19 lines
2.3 MiB
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD AND TERSER
if you want to view the source, please visit the github repository of this plugin
*/
"use strict";function Logger(message,level,key3){_logger(message,level,key3)}function __logger(message,baseLevel,flagsOrKey,key3){let level=baseLevel;"string"==typeof flagsOrKey?key3=flagsOrKey:void 0!==flagsOrKey&&(level|=flagsOrKey);_logger(message,level,key3)}function info(message,flagsOrKey,key3){__logger(message,LEVEL_INFO,flagsOrKey,key3)}function isMetaEntry(entry){return"children"in entry}function statusDisplay(status){return status?"EXPERIMENTAL"==status?" (Experimental)":"ALPHA"==status?" (Alpha)":"BETA"==status?" (Beta)":` (${status})`:""}function confName(key3,alt=""){var _a8,_b5;return key3 in configurationNames?`${null==(_a8=configurationNames[key3])?void 0:_a8.name}${statusDisplay(null==(_b5=configurationNames[key3])?void 0:_b5.status)}`:`${alt||""}`}function numeric(str){return isNaN(str)?str.charCodeAt(0):parseInt(str,10)}function escapeBraces(str){return str.replace(slashPattern,escSlash).replace(openPattern,escOpen).replace(closePattern,escClose).replace(commaPattern,escComma).replace(periodPattern,escPeriod)}function unescapeBraces(str){return str.replace(escSlashPattern,"\\").replace(escOpenPattern,"{").replace(escClosePattern,"}").replace(escCommaPattern,",").replace(escPeriodPattern,".")}function parseCommaParts(str){if(!str)return[""];const parts=[],m3=balanced("{","}",str);if(!m3)return str.split(",");const{pre,body,post}=m3,p4=pre.split(",");p4[p4.length-1]+="{"+body+"}";const postParts=parseCommaParts(post);if(post.length){p4[p4.length-1]+=postParts.shift();p4.push.apply(p4,postParts)}parts.push.apply(parts,p4);return parts}function expand(str){if(!str)return[];"{}"===str.slice(0,2)&&(str="\\{\\}"+str.slice(2));return expand_(escapeBraces(str),!0).map(unescapeBraces)}function embrace(str){return"{"+str+"}"}function isPadded(el){return/^-?0\d/.test(el)}function lte(i2,y2){return i2<=y2}function gte(i2,y2){return i2>=y2}function expand_(str,isTop){const expansions=[],m3=balanced("{","}",str);if(!m3)return[str];const pre=m3.pre,post=m3.post.length?expand_(m3.post,!1):[""];if(/\$$/.test(m3.pre))for(let k2=0;k2<post.length;k2++){const expansion=pre+"{"+m3.body+"}"+post[k2];expansions.push(expansion)}else{const isNumericSequence=/^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m3.body),isAlphaSequence=/^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m3.body),isSequence=isNumericSequence||isAlphaSequence,isOptions=m3.body.indexOf(",")>=0;if(!isSequence&&!isOptions)return m3.post.match(/,(?!,).*\}/)?expand_(str=m3.pre+"{"+m3.body+escClose+m3.post):[str];let n3,N3;if(isSequence)n3=m3.body.split(/\.\./);else{n3=parseCommaParts(m3.body);if(1===n3.length&&void 0!==n3[0]){n3=expand_(n3[0],!1).map(embrace);if(1===n3.length)return post.map((p4=>m3.pre+n3[0]+p4))}}if(isSequence&&void 0!==n3[0]&&void 0!==n3[1]){const x2=numeric(n3[0]),y2=numeric(n3[1]),width=Math.max(n3[0].length,n3[1].length);let incr=3===n3.length&&void 0!==n3[2]?Math.abs(numeric(n3[2])):1,test=lte;if(y2<x2){incr*=-1;test=gte}const pad2=n3.some(isPadded);N3=[];for(let i2=x2;test(i2,y2);i2+=incr){let c3;if(isAlphaSequence){c3=String.fromCharCode(i2);"\\"===c3&&(c3="")}else{c3=String(i2);if(pad2){const need=width-c3.length;if(need>0){const z2=new Array(need+1).join("0");c3=i2<0?"-"+z2+c3.slice(1):z2+c3}}}N3.push(c3)}}else{N3=[];for(let j2=0;j2<n3.length;j2++)N3.push.apply(N3,expand_(n3[j2],!1))}for(let j2=0;j2<N3.length;j2++)for(let k2=0;k2<post.length;k2++){const expansion=pre+N3[j2]+post[k2];(!isTop||isSequence||expansion)&&expansions.push(expansion)}}return expansions}async function getWebCrypto(){if(webcrypto)return webcrypto;if(globalThis.crypto)return webcrypto=globalThis.crypto;{const module2=await import("crypto");return webcrypto=module2.webcrypto}}function base64ToArrayBufferNative(base64){if(0===base64.length)return new ArrayBuffer(0);try{if("string"==typeof base64)return Uint8Array.fromBase64(base64).buffer;const bufItems=base64.map((e3=>Uint8Array.fromBase64(e3).buffer)),len=bufItems.reduce(((p4,c3)=>p4+c3.byteLength),0),joinedArray=new Uint8Array(len);let offset=0;bufItems.forEach((e3=>{joinedArray.set(new Uint8Array(e3),offset);offset+=e3.byteLength}));return joinedArray.buffer}catch(ex){Logger("Base64 Decode error",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);return new ArrayBuffer(0)}}function base64ToArrayBufferInternalBrowser(base64){try{const binary_string=globalThis.atob(base64),len=binary_string.length,bytes=new Uint8Array(len);for(let i2=0;i2<len;i2++)bytes[i2]=binary_string.charCodeAt(i2);return bytes.buffer}catch(ex){Logger("Base64 Decode error",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);return new ArrayBuffer(0)}}function arrayBufferToBase64internalBrowser(buffer){return new Promise(((res2,rej)=>{const blob=new Blob([buffer],{type:"application/octet-binary"}),reader=new FileReader;reader.onload=function(evt){var _a8,_b5;const dataURI=(null==(_b5=null==(_a8=evt.target)?void 0:_a8.result)?void 0:_b5.toString())||"";if(0!=buffer.byteLength&&(""==dataURI||"data:"==dataURI))return rej(new TypeError("Could not parse the encoded string"));const result=dataURI.substring(dataURI.indexOf(",")+1);res2(result)};reader.readAsDataURL(blob)}))}function writeString(string){if(string.length>128)return te.encode(string);const buffer=new Uint8Array(4*string.length),length=string.length;let index6=0,chr=0,idx2=0;for(;idx2<length;){chr=string.charCodeAt(idx2++);if(chr<128)buffer[index6++]=chr;else if(chr<2048){buffer[index6++]=192|chr>>>6;buffer[index6++]=128|63&chr}else if(chr<55296||chr>57343){buffer[index6++]=224|chr>>>12;buffer[index6++]=128|chr>>>6&63;buffer[index6++]=128|63&chr}else{chr=65536+(chr-55296<<10|string.charCodeAt(idx2++)-56320);buffer[index6++]=240|chr>>>18;buffer[index6++]=128|chr>>>12&63;buffer[index6++]=128|chr>>>6&63;buffer[index6++]=128|63&chr}}return buffer.slice(0,index6)}function readString(buffer){const length=buffer.length;if(length>128)return td.decode(buffer);let index6=0;const end=length;let string="";for(;index6<end;){const chunk=[],cEnd=Math.min(index6+QUANTUM,end);for(;index6<cEnd;){const chr=buffer[index6++];if(chr<128)chunk.push(chr);else if(192==(224&chr))chunk.push((31&chr)<<6|63&buffer[index6++]);else if(224==(240&chr))chunk.push((15&chr)<<12|(63&buffer[index6++])<<6|63&buffer[index6++]);else if(240==(248&chr)){let code=(7&chr)<<18|(63&buffer[index6++])<<12|(63&buffer[index6++])<<6|63&buffer[index6++];if(code<65536)chunk.push(code);else{code-=65536;chunk.push(55296+(code>>>10),56320+(1023&code))}}}string+=String.fromCharCode(...chunk)}return string}function*arrayToChunkedArray(arr,chunkLength){const source2=[...arr];for(;source2.length;){const s2=source2.splice(0,chunkLength);yield s2}}function unique(arr){return[...new Set(arr)]}function createTypedArrayReader(buffer){let offset=0;return{read(length){const result=buffer.slice(offset,offset+length);offset+=length;return result},readAll(){const result=buffer.slice(offset);offset=buffer.length;return result}}}function concatUInt8Array(arrays){const totalLength=arrays.reduce(((sum2,arr)=>sum2+arr.length),0),result=new Uint8Array(totalLength);let offset=0;for(const array of arrays){result.set(array,offset);offset+=array.length}return result}function decodeToArrayBuffer(src){if(1==src.length)return _decodeToArrayBuffer(src[0]);const bufItems=src.map((e3=>_decodeToArrayBuffer(e3))),len=bufItems.reduce(((p4,c3)=>p4+c3.byteLength),0),joinedArray=new Uint8Array(len);let offset=0;bufItems.forEach((e3=>{joinedArray.set(new Uint8Array(e3),offset);offset+=e3.byteLength}));return joinedArray.buffer}function _decodeToArrayBuffer(src){const out=new Uint8Array(src.length),len=src.length;for(let i2=0;i2<len;i2++){const char=src.charCodeAt(i2);out[i2]=char>=38&&char<=126&&58!=char?char:revTable[char]}return out.buffer}function concatUInt8Array2(arrays){const length=arrays.reduce(((acc,cur)=>acc+cur.length),0),result=new Uint8Array(length);let pos=0;for(const array of arrays){result.set(array,pos);pos+=array.length}return result}function decodeBinary(src){if(0==src.length)return(new Uint8Array).buffer;if("string"==typeof src){if("%"===src[0])return _decodeToArrayBuffer(src.substring(1))}else if("%"===src[0][0]){const[head2,...last]=src;return decodeToArrayBuffer([head2.substring(1),...last])}return base64ToArrayBuffer(src)}function replaceAll(str,search,replace){return"replaceAll"in String.prototype?str.replaceAll(search,replace):str.split(search).join(replace)}function replaceAllPairs(str,...fromTo){let r4=`${str}`;for(const[from,to]of fromTo)r4=replaceAll(r4,from,to);return r4}function escapeStringToHTML(str){return str?str.replace(/[<>&"'`]/g,(match3=>({"<":"&lt;",">":"&gt;","&":"&amp;",'"':"&quot;","'":"&#39;","`":"&#x60;"}[match3]))):""}function versionNumberString2Number(version2){return version2.split(".").reverse().map(((e3,i2)=>e3/1*1e3**i2)).reduce(((prev,current)=>prev+current),0)}function isValidFilenameInWidows(filename){return!/[\u0000-\u001f]|[\\":?<>|*#]/g.test(filename)&&!/(\\|\/)(COM\d|LPT\d|CON|PRN|AUX|NUL|CLOCK$)($|\.)/gi.test(filename)}function isValidFilenameInDarwin(filename){return!/[\u0000-\u001f]|[:]/g.test(filename)}function isValidFilenameInLinux(filename){return!/[\u0000-\u001f]|[:]/g.test(filename)}function isValidFilenameInAndroid(filename){return!/[\u0000-\u001f]|[\\":?<>|*#]/g.test(filename)}function isFilePath(path2){return-1===path2.indexOf(":")}function stripAllPrefixes(prefixedPath){if(isFilePath(prefixedPath))return prefixedPath;const[,body]=expandFilePathPrefix(prefixedPath);return stripAllPrefixes(body)}function addPrefix(path2,prefix){return prefix&&path2.startsWith(prefix)?path2:`${null!=prefix?prefix:""}${path2}`}function expandFilePathPrefix(path2){let[prefix,body]=path2.split(":",2);if(body)prefix+=":";else{body=prefix;prefix=""}return[prefix,body]}function expandDocumentIDPrefix(id){let[prefix,body]=id.split(":",2);if(body)prefix+=":";else{body=prefix;prefix=""}return[prefix,body]}function hashString(key3){return _hashString(key3)}async function path2id_base(filenameSrc,obfuscatePassphrase,caseInsensitive){if(filenameSrc.startsWith(PREFIX_OBFUSCATED))return`${filenameSrc}`;let filename=`${filenameSrc}`;const newPrefix=obfuscatePassphrase?PREFIX_OBFUSCATED:"";caseInsensitive&&(filename=filename.toLowerCase());let x2=filename;x2.startsWith("_")&&(x2="/"+x2);if(!obfuscatePassphrase)return newPrefix+x2;const[prefix,body]=expandFilePathPrefix(x2);if(body.startsWith(PREFIX_OBFUSCATED))return newPrefix+x2;const hashedPassphrase=await hashString(obfuscatePassphrase);return prefix+newPrefix+await hashString(`${hashedPassphrase}:${filename}`)}function id2path_base(id,entry){if(entry&&(null==entry?void 0:entry.path))return id2path_base(entry.path);if(id.startsWith(PREFIX_OBFUSCATED))throw new Error("Entry has been obfuscated!");const[prefix,body]=expandDocumentIDPrefix(id);if(body.startsWith(PREFIX_OBFUSCATED))throw new Error("Entry has been obfuscated!");return body.startsWith("/")?body.substring(1):prefix+body}function getPath(entry){return id2path_base(entry._id,entry)}function stripPrefix(prefixedPath){const[prefix,body]=prefixedPath.split(":",2);return body||prefix}function shouldBeIgnored(filename){return filename==FLAGMD_REDFLAG||filename==FLAGMD_REDFLAG2||filename==FLAGMD_REDFLAG2_HR||filename==FLAGMD_REDFLAG3||filename==FLAGMD_REDFLAG3_HR||!!filename.startsWith(PREFIXMD_LOGFILE)||!!filename.startsWith(PREFIXMD_LOGFILE_UC)}function isPlainText(filename){return!!(filename.endsWith(".md")||filename.endsWith(".txt")||filename.endsWith(".svg")||filename.endsWith(".html")||filename.endsWith(".csv")||filename.endsWith(".css")||filename.endsWith(".js")||filename.endsWith(".xml")||filename.endsWith(".canvas"))}function shouldSplitAsPlainText(filename){return!!filename.endsWith(".md")||!!filename.endsWith(".txt")||!!filename.endsWith(".canvas")}function isAccepted(path2,ignore){if(-1!==path2.indexOf("./")||-1!==path2.indexOf("../"))return!1;const patterns=ignore.map((e3=>e3.trim())).filter((e3=>e3.length>0&&!e3.startsWith("#")));let result;for(const pattern of patterns){if(pattern.endsWith("/")&&minimatch(path2,`${pattern}**`,matchOpts))return!1;const newResult=pattern.startsWith("!");(minimatch(path2,pattern,matchOpts)||!pattern.endsWith("/")&&minimatch(path2,pattern+"/**",matchOpts))&&(result=newResult)}return result}async function isAcceptedAll(path2,ignoreFiles,getList){const intermediatePaths=unique(path2.substring(0,path2.lastIndexOf("/")).split("/").reduce(((p4,c3)=>[...p4,p4[p4.length-1]+"/"+c3]),[""]).map((e3=>e3.substring(1)))).reverse();for(const intermediatePath of intermediatePaths)for(const ignoreFile of ignoreFiles){const ignoreFilePath=intermediatePath+"/"+ignoreFile,list=await getList(ignoreFilePath);if(!1===list)continue;const result=isAccepted(path2.substring(intermediatePath.length?intermediatePath.length+1:0),list);if(void 0!==result)return result}return!0}async function isSomeResolved(promises){return 0!=promises.length&&await Promise.race([...promises,Promise.resolve(UNRESOLVED)])!==UNRESOLVED}function fireAndForget(p4){if("function"==typeof p4)return fireAndForget(p4());p4.then(noop).catch(noop)}function yieldMicrotask(){return new Promise((res2=>queueMicrotask(res2)))}function yieldAnimationFrame(){return new Promise((res2=>requestAnimationFrame(res2)))}function yieldNextAnimationFrame(){return currentYieldingAnimationFrame||(currentYieldingAnimationFrame=(async()=>{const ret=await yieldAnimationFrame();currentYieldingAnimationFrame=void 0;return ret})())}function cancelableDelay(timeout,cancel2=TIMED_OUT_SIGNAL){let timer;const promise=promiseWithResolvers();timer=setTimeout((()=>{timer=void 0;promise.resolve(cancel2)}),timeout);return{promise:promise.promise,cancel(){if(timer){clearTimeout(timer);timer=void 0}}}}function Semaphore(limit){let counter=0;const _limit=limit,queue2=[];return{get waiting(){return queue2.length},async tryAcquire(quantity=1,timeout){if(counter<_limit){counter+=quantity;return()=>{this.release(quantity)}}const d4=cancelableDelay(timeout,TIMED_OUT_SIGNAL),aq2=this.acquire(quantity),p4=await Promise.race([d4.promise,aq2]);if(p4===TIMED_OUT_SIGNAL){fireAndForget((()=>aq2.then((release=>release()))));return!1}return p4},async acquire(quantity=1){if(counter<_limit){counter+=quantity;return()=>this.release()}const n3=promiseWithResolvers();queue2.push(n3);await n3.promise;return()=>{this.release(quantity)}},release(quantity=1){if(queue2.length>0){const next2=queue2.shift();next2&&fireAndForget((async()=>await yieldMicrotask().then((()=>next2.resolve()))))}else counter>0&&(counter-=quantity)}}}function isCloudantURI(uri){return-1!==uri.indexOf(".cloudantnosqldb.")||-1!==uri.indexOf(".cloudant.com")}function isErrorOfMissingDoc(ex){return 404==(ex&&(null==ex?void 0:ex.status))}function isValidLength(len){return len>=1&&len<=5}function encodeObjectAsArray(obj){if(Array.isArray(obj))return ARRAY_MARKER+encodeAnyArray(obj,!0);const objArray=[...Object.entries(obj)].flat();return OBJECT_MARKER+encodeAnyArray(objArray,!0)}function decodeObjectFromArray(str){if(str[0]==ARRAY_MARKER)return decodeAnyArray(str.substring(1));if(str[0]==OBJECT_MARKER){const arr=decodeAnyArray(str.substring(1)),entries2=[];for(let i2=0;i2<arr.length;i2+=2){const key3=arr[i2],value=arr[i2+1];entries2.push([key3,value])}return Object.fromEntries(entries2)}return JSON.parse(str)}function encodeAnyArray(obj,safer=!1){return obj.map((v2=>{if(void 0===v2)return"u";if(null===v2)return"n";if(!1===v2)return"f";if(!0===v2)return"t";if("number"==typeof v2){const isFloat=!Number.isInteger(v2),b36=v2.toString(36),strNum=v2.toString(),expression=isFloat||b36.length>strNum.length?"n":"N",encodedStr="N"==expression?b36:strNum,len=encodedStr.length.toString(36),lenLen2=len.length;if(!isValidLength(lenLen2))throw new Error("Number length exceeds maximum encodable length of 5 in base36.");return prefixMapNumber[expression][lenLen2]+len+encodedStr}let str,prefix;if("string"==typeof v2){str=v2;prefix="s"}else{prefix="o";const objectStr=JSON.stringify(v2),containUndefined=-1!==Object.values(v2).indexOf(void 0);if(!safer||containUndefined){const objectEncoded=encodeObjectAsArray(v2);str=containUndefined||objectEncoded.length<objectStr.length?objectEncoded:objectStr}else str=objectStr}const length=str.length.toString(36),lenLen=length.length;if(!isValidLength(lenLen))throw new Error("String/Object length exceeds maximum encodable length of 5 in base36.");return prefixMapObject[prefix][lenLen]+length+str})).join("")}function isDecodeMapConstantKey(key3){return key3 in decodeMapConstant}function isDecodePrefixMapNumberKey(key3){return key3 in decodePrefixMapNumber}function isDecodePrefixMapObjectKey(key3){return key3 in decodePrefixMapObject}function decodeAnyArray(str){const result=[];let i2=0;for(;i2<str.length;){const char=str[i2];i2++;if(isDecodeMapConstantKey(char))result.push(decodeMapConstant[char]);else if(isDecodePrefixMapNumberKey(char)){const{prefix,len}=decodePrefixMapNumber[char],lenStr=str.substring(i2,i2+len);i2+=len;const lenNum=parseInt(lenStr,36),value=str.substring(i2,i2+lenNum);i2+=lenNum;"N"==prefix?result.push(parseInt(value,36)):result.push(parseFloat(value))}else{if(!isDecodePrefixMapObjectKey(char))throw new Error(`Invalid encoding at position ${i2-1}: unexpected character '${char}'`);{const{prefix,len}=decodePrefixMapObject[char],lenStr=str.substring(i2,i2+len);i2+=len;const lenNum=parseInt(lenStr,36),value=str.substring(i2,i2+lenNum);i2+=lenNum;"s"==prefix?result.push(value):result.push(decodeObjectFromArray(value))}}}return result}function extractObject(template,obj){const ret={...template};for(const key3 in ret)ret[key3]=obj[key3];return ret}function isObjectDifferent(a2,b3,ignoreUndefined=!1){if(typeof a2!=typeof b3)return!0;if("object"==typeof a2){if(null===a2||null===b3)return a2!==b3;const keys3=[...new Set([...Object.keys(a2),...Object.keys(b3)])];return ignoreUndefined?keys3.map((key3=>void 0!==(null==a2?void 0:a2[key3])&&void 0!==(null==b3?void 0:b3[key3])&&isObjectDifferent(null==a2?void 0:a2[key3],null==b3?void 0:b3[key3]))).some((e3=>1==e3)):keys3.map((key3=>isObjectDifferent(key3 in a2?a2[key3]:SYMBOL_A,key3 in b3?b3[key3]:SYMBOL_B))).some((e3=>1==e3))}return a2!==b3}async function waitForSignal(id,timeout){return await globalSlipBoard.awaitNext(GENERIC_COMPATIBILITY_SIGNAL,id,{timeout})!==TIMED_OUT_SIGNAL}function sendSignal(id){globalSlipBoard.submit(GENERIC_COMPATIBILITY_SIGNAL,id)}function sendValue(id,result){globalSlipBoard.submit(GENERIC_COMPATIBILITY_VALUE,id,result)}function sizeToHumanReadable(size){const units=["B","KB","MB","GB","TB"];let i2=0;for(;size>=1024&&i2<units.length;){size/=1024;i2++}return size.toFixed(2)+units[i2]}function resolveWithIgnoreKnownError(p4,def){return new Promise(((res2,rej)=>{p4.then(res2).catch((ex=>isErrorOfMissingDoc(ex)?res2(def):rej(ex)))}))}function getDocData(doc){return"string"==typeof doc?doc:doc.join("")}function getDocDataAsArray(doc){return"string"==typeof doc?[doc]:doc}function isTextBlob(blob){return"text/plain"===blob.type}function createTextBlob(data){const d4=Array.isArray(data)?data:[data];return new Blob(d4,{endings:"transparent",type:"text/plain"})}function createBinaryBlob(data){return new Blob([data],{endings:"transparent",type:"application/octet-stream"})}function createBlob(data){return data instanceof Blob?data:data instanceof Uint8Array||data instanceof ArrayBuffer?createBinaryBlob(data):createTextBlob(data)}function isTextDocument(doc){return"plain"==doc.type||"plain"==doc.datatype||!!isPlainText(doc.path)}function readAsBlob(doc){return isTextDocument(doc)?createTextBlob(doc.data):createBinaryBlob(decodeBinary(doc.data))}function readContent(doc){return isTextDocument(doc)?getDocData(doc.data):decodeBinary(doc.data)}async function isDocContentSame(docA,docB){const blob1=createBlob(docA),blob2=createBlob(docB);if(blob1.size!=blob2.size)return!1;if(isIndexDBCmpExist)return 0===globalThis.indexedDB.cmp(await blob1.arrayBuffer(),await blob2.arrayBuffer());const length=blob1.size;let i2=0;for(;i2<length;){const ab1=await blob1.slice(i2,i2+1e4).arrayBuffer(),ab2=await blob2.slice(i2,i2+1e4).arrayBuffer();i2+=1e4;if(await arrayBufferToBase64Single(ab1)!=await arrayBufferToBase64Single(ab2))return!1}return!0}function isObfuscatedEntry(doc){return!!doc._id.startsWith(PREFIX_OBFUSCATED)}function isEncryptedChunkEntry(doc){return!!doc._id.startsWith(PREFIX_ENCRYPTED_CHUNK)}function isSyncInfoEntry(doc){return doc._id==SYNCINFO_ID}function determineTypeFromBlob(data){return isTextBlob(data)?"plain":"newnote"}function determineType(path2,data){return data instanceof Blob?determineTypeFromBlob(data):isPlainText(path2)?"plain":data instanceof Uint8Array||data instanceof ArrayBuffer?"newnote":"plain"}function isAnyNote(doc){return"type"in doc&&("newnote"==doc.type||"plain"==doc.type)}function isLoadedEntry(doc){return"type"in doc&&("newnote"==doc.type||"plain"==doc.type)&&"data"in doc}function isDeletedEntry(doc){return doc._deleted||doc.deleted||!1}function createSavingEntryFromLoadedEntry(doc){const data=readAsBlob(doc),type=determineType(doc.path,data);return{...doc,data,datatype:type,type,children:[]}}function setAllItems(set2,items){items.forEach((e3=>set2.add(e3)));return set2}function escapeNewLineFromString(str){return-1===str.indexOf("\n")&&-1===str.indexOf("\r")?str:"\\f"+str.replace(/(\n|\r|\\)/g,(m3=>`${map[m3]}`))}function unescapeNewLineFromString(str){return str.startsWith("\\f")?str.substring(2).replace(/(\\n|\\r|\\\\)/g,(m3=>`${revMap2[m3]}`)):str}function escapeMarkdownValue(value){return"string"==typeof value?replaceAllPairs(value,["|","\\|"],["`","\\`"]):value}function timeDeltaToHumanReadable(delta){const sec=delta/1e3;if(sec<60)return`${sec.toFixed(2)}s`;const min=sec/60;if(min<60)return`${min.toFixed(2)}m`;const hour=min/60;if(hour<24)return`${hour.toFixed(2)}h`;const day=hour/24;return day<365?`${day.toFixed(2)}d`:`${(day/365).toFixed(2)}y`}async function wrapException(func){try{return await func()}catch(ex){return ex instanceof Error?ex:new Error(ex)}}function isDirty(key3,value){if(previousValues.get(key3)===value)return!1;previousValues.set(key3,value);return!0}function isSensibleMargeApplicable(path2){return!!path2.endsWith(".md")}function isObjectMargeApplicable(path2){return!!path2.endsWith(".canvas")||!!path2.endsWith(".json")}function tryParseJSON(str,fallbackValue){try{return JSON.parse(str)}catch(e3){return fallbackValue}}function unorderedArrayToObject(obj){return obj.map((e3=>({[e3.id]:e3}))).reduce(((p4,c3)=>({...p4,...c3})),{})}function objectToUnorderedArray(obj){const entries2=Object.entries(obj);if(entries2.some((e3=>{var _a8;return e3[0]!=(null==(_a8=e3[1])?void 0:_a8.id)})))throw new Error("Item looks like not unordered array");return entries2.map((e3=>e3[1]))}function generatePatchUnorderedArray(from,to){if(from.every((e3=>"object"==typeof e3&&"id"in e3))&&to.every((e3=>"object"==typeof e3&&"id"in e3))){const diff=generatePatchObj(unorderedArrayToObject(from),unorderedArrayToObject(to));return Object.keys(diff).length>0?{[MARK_ISARRAY]:diff}:{}}return{[MARK_SWAPPED]:to}}function generatePatchObj(from,to){const entries2=Object.entries(from),tempMap=new Map(entries2),ret={},newEntries=Object.entries(to);for(const[key3,value]of newEntries)if(tempMap.has(key3)){const v2=tempMap.get(key3);if(typeof v2!=typeof value||Array.isArray(v2)!==Array.isArray(value))ret[key3]={[MARK_SWAPPED]:value};else if(null===v2&&null===value);else if(null===v2&&null!==value)ret[key3]={[MARK_SWAPPED]:value};else if(null!==v2&&null===value)ret[key3]={[MARK_SWAPPED]:value};else if("object"!=typeof v2||"object"!=typeof value||Array.isArray(v2)||Array.isArray(value))if("object"==typeof v2&&"object"==typeof value&&Array.isArray(v2)&&Array.isArray(value)){const wk2=generatePatchUnorderedArray(v2,value);Object.keys(wk2).length>0&&(ret[key3]=wk2)}else"object"!=typeof v2&&"object"!=typeof value?JSON.stringify(tempMap.get(key3))!==JSON.stringify(value)&&(ret[key3]=value):JSON.stringify(tempMap.get(key3))!==JSON.stringify(value)&&(ret[key3]={[MARK_SWAPPED]:value});else{const wk2=generatePatchObj(v2,value);Object.keys(wk2).length>0&&(ret[key3]=wk2)}tempMap.delete(key3)}else{ret[key3]=value;tempMap.delete(key3)}for(const[key3]of tempMap)ret[key3]=MARK_DELETED;return ret}function applyPatch(from,patch){const ret=from,patches=Object.entries(patch);for(const[key3,value]of patches)if(value!=MARK_DELETED)if(null!==value)if("object"==typeof value){if(MARK_SWAPPED in value){ret[key3]=value[MARK_SWAPPED];continue}if(MARK_ISARRAY in value){key3 in ret||(ret[key3]=[]);if(!Array.isArray(ret[key3]))throw new Error("Patch target type is mismatched (array to something)");const appliedArray=objectToUnorderedArray(applyPatch(unorderedArrayToObject(ret[key3]),value[MARK_ISARRAY]));ret[key3]=[...appliedArray]}else{if(!(key3 in ret)){ret[key3]=value;continue}ret[key3]=applyPatch(ret[key3],value)}}else ret[key3]=value;else ret[key3]=null;else delete ret[key3];return ret}function mergeObject(objA,objB){const newEntries=Object.entries(objB),ret={...objA};if(typeof objA!=typeof objB||Array.isArray(objA)!==Array.isArray(objB))return objB;for(const[key3,v2]of newEntries)if(key3 in ret){const value=ret[key3];typeof v2!=typeof value||Array.isArray(v2)!==Array.isArray(value)?ret[key3]=v2:"object"!=typeof v2||"object"!=typeof value||Array.isArray(v2)||Array.isArray(value)?"object"==typeof v2&&"object"==typeof value&&Array.isArray(v2)&&Array.isArray(value)?ret[key3]=[...new Set([...v2,...value])]:ret[key3]=v2:ret[key3]=mergeObject(v2,value)}else ret[key3]=v2;const retSorted=Object.fromEntries(Object.entries(ret).sort(((a2,b3)=>a2[0]<b3[0]?-1:a2[0]>b3[0]?1:0)));return Array.isArray(objA)&&Array.isArray(objB)?Object.values(retSorted):retSorted}function flattenObject(obj,path2=[]){if("object"!=typeof obj)return[[path2.join("."),obj]];if(null===obj)return[[path2.join("."),null]];if(Array.isArray(obj))return[[path2.join("."),JSON.stringify(obj)]];const e3=Object.entries(obj),ret=[];for(const[key3,value]of e3){const p4=flattenObject(value,[...path2,key3]);ret.push(...p4)}return ret}function parseHeaderValues(strHeader){const headers={},lines=strHeader.split("\n");for(const line of lines){const[key3,value]=line.split(":",2).map((e3=>e3.trim()));key3&&value&&(headers[key3]=value)}return headers}function parseCustomRegExp(regexp){return regexp.startsWith("!!")?[!0,regexp.slice(2)]:[!1,regexp]}function isValidRegExp(regexp){try{const[,exp]=parseCustomRegExp(regexp);new RegExp(exp);return!0}catch(e3){return!1}}function isInvertedRegExp(regexp){const[negate3]=parseCustomRegExp(regexp);return negate3}function parseCustomRegExpList(list,flags2,delimiter){const d4=null!=delimiter?delimiter:",";return list.replace(/\n| /g,"").split(d4).filter((e3=>e3)).map((e3=>new CustomRegExp(e3,flags2)))}function constructCustomRegExpList(items,delimiter){return items.map((e3=>`${e3}`)).join(`${delimiter}`)}function splitCustomRegExpList(list,delimiter){const d4=delimiter;return list.split(d4).filter((e3=>e3))}function getFileRegExp(settings,key3){const flagCase=settings.handleFilenameCaseSensitive?"":"i";return parseCustomRegExpList(settings[key3],flagCase,"syncInternalFilesIgnorePatterns"===key3||"syncInternalFilesTargetPatterns"===key3||"syncInternalFileOverwritePatterns"===key3?",":"|[]|")}function copyTo(source2,target){for(const key3 of Object.keys(target))target[key3]=source2[key3]}function pickBucketSyncSettings(setting){return{bucket:setting.bucket,region:setting.region,endpoint:setting.endpoint,accessKey:setting.accessKey,secretKey:setting.secretKey,bucketPrefix:setting.bucketPrefix,forcePathStyle:setting.forcePathStyle,useCustomRequestHandler:setting.useCustomRequestHandler,bucketCustomHeaders:setting.bucketCustomHeaders}}function pickCouchDBSyncSettings(setting){return{couchDB_URI:setting.couchDB_URI,couchDB_USER:setting.couchDB_USER,couchDB_PASSWORD:setting.couchDB_PASSWORD,couchDB_DBNAME:setting.couchDB_DBNAME,useRequestAPI:setting.useRequestAPI,couchDB_CustomHeaders:setting.couchDB_CustomHeaders,jwtAlgorithm:setting.jwtAlgorithm,jwtExpDuration:setting.jwtExpDuration,jwtKey:setting.jwtKey,jwtKid:setting.jwtKid,jwtSub:setting.jwtSub,useJWT:setting.useJWT}}function pickEncryptionSettings(setting){return{E2EEAlgorithm:setting.E2EEAlgorithm,encrypt:setting.encrypt,passphrase:setting.passphrase,usePathObfuscation:setting.usePathObfuscation}}function pickP2PSyncSettings(setting){return{P2P_Enabled:setting.P2P_Enabled,P2P_AppID:setting.P2P_AppID,P2P_roomID:setting.P2P_roomID,P2P_passphrase:setting.P2P_passphrase,P2P_relays:setting.P2P_relays,P2P_AutoStart:setting.P2P_AutoStart,P2P_AutoBroadcast:setting.P2P_AutoBroadcast,P2P_DevicePeerName:setting.P2P_DevicePeerName||"",P2P_turnServers:setting.P2P_turnServers,P2P_turnUsername:setting.P2P_turnUsername,P2P_turnCredential:setting.P2P_turnCredential}}function buildChunkMap(chunks){const map4=new Map;for(const chunk of chunks)map4.set(chunk._id,chunk);return map4}function withTimeout(proc,timeout,onTimedOut){return new Promise(((resolve,reject)=>{const timer=setTimeout((()=>{resolve(onTimedOut())}),timeout);proc.then(resolve).catch(reject).finally((()=>{clearTimeout(timer)}))}))}function getError(error){return error instanceof Error?error:"error"in error&&error.error instanceof Error?error.error:void 0}function isMissingError(error){return"status"in error&&404===error.status||"error"in error&&"not_found"===error.error||"error"in error&&isMissingError(error.error)}function isChunkDoc(doc){return doc&&"string"==typeof doc._id&&"leaf"===doc.type}function getNoFromRev(rev3){return rev3?parseInt(rev3.split("-")[0]):0}function serialized(key3,proc){var _a8;const prev=serializedMap.get(key3),p4=promiseWithResolvers();queueCount.set(key3,(null!=(_a8=queueCount.get(key3))?_a8:0)+1);const nextTask=async()=>{try{p4.resolve(await proc())}catch(ex){p4.reject(ex)}finally{const count=queueCount.get(key3)-1;if(0===count){serializedMap.delete(key3);queueCount.delete(key3)}else queueCount.set(key3,count)}};if(prev){const newP=prev.then((()=>nextTask()));serializedMap.set(key3,newP)}else serializedMap.set(key3,nextTask());return p4.promise}function shareRunningResult(key3,proc){const prev=shareSerializedMap.get(key3);if(prev)return prev;const p4=promiseWithResolvers();shareSerializedMap.set(key3,p4.promise);const task=async()=>{try{p4.resolve(await proc())}catch(ex){p4.reject(ex)}finally{shareSerializedMap.delete(key3)}};fireAndForget((()=>task()));return p4.promise}function skipIfDuplicated(key3,proc){if(skipDuplicatedMap.get(key3))return Promise.resolve(null);const p4=promiseWithResolvers();skipDuplicatedMap.set(key3,p4.promise);const task=async()=>{try{p4.resolve(await proc())}catch(ex){p4.reject(ex)}finally{skipDuplicatedMap.delete(key3)}};fireAndForget((()=>task()));return p4.promise}async function scheduleOnceIfDuplicated(key3,proc){if(isLockAcquired(key3)){waitingProcessMap.set(key3,proc);return Promise.resolve(void 0)}return await serialized(key3,proc).then((()=>{const nextProc=waitingProcessMap.get(key3);if(nextProc){waitingProcessMap.delete(key3);return scheduleOnceIfDuplicated(key3,nextProc)}}))}function isLockAcquired(key3){var _a8;return(null!=(_a8=queueCount.get(key3))?_a8:0)>0}function unwrapTaskResult(result){if("ok"in result)return result.ok;if("err"in result)return result.err;throw new Error("Argument Exception: Could not unwrap")}function isTaskWaiting(task){if(task instanceof Promise)return!1;if(task instanceof Function)return!0;throw new Error("Invalid state")}async function wrapEachProcess(key3,task){try{return{key:key3,ok:await task}}catch(ex){return{key:key3,err:ex instanceof Error?ex:new Error(`${ex}`)}}}async function*processAllTasksWithConcurrencyLimit(limit,tasks3){const nowProcessing=new Map;let idx2=0;const pendingTasks=tasks3.reverse();for(;pendingTasks.length>0||nowProcessing.size>0;){L2:for(;nowProcessing.size<limit&&pendingTasks.length>0;){const task=pendingTasks.pop();if(void 0===task)break L2;idx2++;const wrappedPromise=wrapEachProcess(idx2,isTaskWaiting(task)?task():task);nowProcessing.set(idx2,wrappedPromise)}const done=await Promise.race(nowProcessing.values());nowProcessing.delete(done.key);yield done}}async function mapAllTasksWithConcurrencyLimit(limit,tasks3){const results=new Map;for await(const v2 of processAllTasksWithConcurrencyLimit(limit,tasks3))results.set(v2.key,v2);return[...results.entries()].sort(((a2,b3)=>a2[0]-b3[0])).map((e3=>e3[1]))}function scheduleTask(key3,timeout,proc,skipIfTaskExist){if(tasks.has(key3)){if(skipIfTaskExist)return;cancelTask(key3)}const newTask=setTimeout((()=>{tasks.delete(key3);proc()}),timeout);tasks.set(key3,newTask)}function cancelTask(key3){const old=tasks.get(key3);if(old){clearTimeout(old);tasks.delete(key3)}}function cancelAllTasks(){for(const v2 of tasks.keys())cancelTask(v2)}function cancelPeriodicTask(key3){if(key3 in intervals){clearInterval(intervals[key3]);delete intervals[key3]}}function cancelAllPeriodicTask(){for(const v2 in intervals)cancelPeriodicTask(v2)}function isWaitingForTimeout(key3){return waitingItems.has(key3)}function initializeStores(vaultName){sameChangePairs=new PersistentMap(`ls-persist-same-changes-${vaultName}`)}function generateCredentialObject(settings){return settings.useJWT?{jwtAlgorithm:settings.jwtAlgorithm,jwtKey:settings.jwtKey,jwtKid:settings.jwtKid,jwtSub:settings.jwtSub,jwtExpDuration:settings.jwtExpDuration,type:"jwt"}:{username:settings.couchDB_USER,password:settings.couchDB_PASSWORD,type:"basic"}}async function path2id(filename,obfuscatePassphrase,caseInsensitive){const temp=filename.split(":"),path2=temp.pop(),normalizedPath=normalizePath(path2);temp.push(normalizedPath);const fixedPath=temp.join(":");return await path2id_base(fixedPath,obfuscatePassphrase,caseInsensitive)}function id2path(id,entry){const temp=id2path_base(id,entry).split(":"),path2=temp.pop(),normalizedPath=normalizePath(path2);temp.push(normalizedPath);return temp.join(":")}function getPath2(entry){return id2path(entry._id,entry)}function getPathWithoutPrefix2(entry){return stripAllPrefixes(getPath2(entry))}function getPathFromTFile(file){return file.path}function isInternalFile(file){return"string"==typeof file?file.startsWith(ICHeader):!!file.isInternal}function getStoragePathFromUXFileInfo(file){return stripAllPrefixes("string"==typeof file?file:file.path)}function getDatabasePathFromUXFileInfo(file){if("string"==typeof file&&file.startsWith(ICXHeader))return file;const prefix=isInternalFile(file)?ICHeader:"";return"string"==typeof file?prefix+stripAllPrefixes(file):prefix+stripAllPrefixes(file.path)}function memoObject(key3,obj){memos[key3]=obj;return memos[key3]}async function memoIfNotExist(key3,func){if(!(key3 in memos)){const w2=func(),v2=w2 instanceof Promise?await w2:w2;memos[key3]=v2}return memos[key3]}function retrieveMemoObject(key3){return key3 in memos&&memos[key3]}function disposeMemoObject(key3){delete memos[key3]}function isValidPath(filename){if(import_obsidian.Platform.isDesktop)return"darwin"==process.platform?isValidFilenameInDarwin(filename):"linux"==process.platform?isValidFilenameInLinux(filename):isValidFilenameInWidows(filename);if(import_obsidian.Platform.isAndroidApp)return isValidFilenameInAndroid(filename);if(import_obsidian.Platform.isIosApp)return isValidFilenameInDarwin(filename);Logger("Could not determine platform for checking filename",LOG_LEVEL_VERBOSE);return isValidFilenameInWidows(filename)}function isInternalMetadata(id){return id.startsWith(ICHeader)}function stripInternalMetadataPrefix(id){return id.substring(ICHeaderLength)}function isChunk(str){return str.startsWith(CHeader)}function isPluginMetadata(str){return str.startsWith(PSCHeader)}function isCustomisationSyncMetadata(str){return str.startsWith(ICXHeader)}function requestToCouchDBWithCredentials(baseUri,credentials,origin2="",key3,body,method,customHeaders){return _requestToCouchDB(baseUri,credentials,origin2,"_node/_local/_config"+(key3?"/"+key3:""),body,method,customHeaders)}function compareMTime(baseMTime,targetMTime){const truncatedBaseMTime=~~(baseMTime/resolution)*resolution,truncatedTargetMTime=~~(targetMTime/resolution)*resolution;if(truncatedBaseMTime==truncatedTargetMTime)return EVEN;if(truncatedBaseMTime>truncatedTargetMTime)return BASE_IS_NEW;if(truncatedBaseMTime<truncatedTargetMTime)return TARGET_IS_NEW;throw new Error("Unexpected error")}function getKey(file){return"string"==typeof file?file:stripAllPrefixes(file.path)}function markChangesAreSame(file,mtime1,mtime2){if(mtime1===mtime2)return!0;const key3=getKey(file),pairs=sameChangePairs.get(key3,[])||[];pairs.some((e3=>e3==mtime1||e3==mtime2))?sameChangePairs.set(key3,[...new Set([...pairs,mtime1,mtime2])]):sameChangePairs.set(key3,[mtime1,mtime2])}function unmarkChanges(file){const key3=getKey(file);sameChangePairs.delete(key3)}function isMarkedAsSameChanges(file,mtimes){const key3=getKey(file),pairs=sameChangePairs.get(key3,[])||[];if(mtimes.every((e3=>-1!==pairs.indexOf(e3))))return EVEN}function compareFileFreshness(baseFile,checkTarget){var _a8,_b5,_c3,_d2,_e2,_f;if(void 0===baseFile&&null==checkTarget)return EVEN;if(null==baseFile)return TARGET_IS_NEW;if(null==checkTarget)return BASE_IS_NEW;const modifiedBase="stat"in baseFile?null!=(_b5=null==(_a8=null==baseFile?void 0:baseFile.stat)?void 0:_a8.mtime)?_b5:0:null!=(_c3=null==baseFile?void 0:baseFile.mtime)?_c3:0,modifiedTarget="stat"in checkTarget?null!=(_e2=null==(_d2=null==checkTarget?void 0:checkTarget.stat)?void 0:_d2.mtime)?_e2:0:null!=(_f=null==checkTarget?void 0:checkTarget.mtime)?_f:0;return modifiedBase&&modifiedTarget&&isMarkedAsSameChanges(baseFile,[modifiedBase,modifiedTarget])?EVEN:compareMTime(modifiedBase,modifiedTarget)}function useMemo({key:key3,forceUpdate,validator},updateFunc){const cached=_cached.get(key3),context2=(null==cached?void 0:cached.context)||new Map;if(cached&&!forceUpdate&&(!validator||validator&&!validator(context2)))return cached.value;const value=updateFunc(context2,null==cached?void 0:cached.value);value!==(null==cached?void 0:cached.value)&&_cached.set(key3,{value,context:context2});return value}function displayRev(rev3){const[number,hash3]=rev3.split("-");return`${number}-${hash3.substring(0,6)}`}function getDocProps(doc){const id=doc._id,shortenedId=id.substring(0,10),prefixedPath=getPath2(doc),path2=stripAllPrefixes(prefixedPath),rev3=doc._rev,revDisplay=rev3?displayRev(rev3):"0-NOREVS",shortenedPath=path2.substring(0,10);return{id,rev:rev3,revDisplay,prefixedPath,path:path2,isDeleted:doc._deleted||doc.deleted||!1,shortenedId,shortenedPath}}function getLogLevel(showNotice){return showNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO}async function autosaveCache(db,mapKey){var _a8;const savedData=null!=(_a8=await db.get(mapKey))?_a8:new Map,_commit2=()=>{try{scheduleTask("commit-map-save-"+mapKey,250,(async()=>{await db.set(mapKey,savedData)}))}catch(e3){}};return{set(key3,value){const modified=savedData.get(key3)!==value,result=savedData.set(key3,value);modified&&_commit2();return result},clear(){savedData.clear();_commit2()},delete(key3){const result=savedData.delete(key3);result&&_commit2();return result},get:key3=>savedData.get(key3),has:key3=>savedData.has(key3),keys:()=>savedData.keys(),get size(){return savedData.size}}}function onlyInNTimes(n3,proc){let counter=0;return function(){counter++%n3==0&&proc(counter)}}function rateLimitedSharedExecution(key3,interval,proc){key3 in waitingTasks||(waitingTasks[key3]={task:void 0,previous:0,leastNext:0});if(waitingTasks[key3].task){waitingTasks[key3].leastNext=Date.now()+interval;return waitingTasks[key3].task.promise}const previous=waitingTasks[key3].previous,delay2=0==previous?0:Math.max(interval-(Date.now()-previous),0),task=promiseWithResolver();task.promise.finally((()=>{if(waitingTasks[key3].task===task){waitingTasks[key3].task=void 0;waitingTasks[key3].previous=Math.max(Date.now(),waitingTasks[key3].leastNext)}}));waitingTasks[key3]={task,previous:Date.now(),leastNext:Date.now()+interval};scheduleTask("thin-out-"+key3,delay2,(async()=>{try{task.resolve(await proc())}catch(ex){task.reject(ex)}}));return task.promise}function updatePreviousExecutionTime(key3,timeDelta=0){key3 in waitingTasks||(waitingTasks[key3]={task:void 0,previous:0,leastNext:0});waitingTasks[key3].leastNext=Math.max(Date.now()+timeDelta,waitingTasks[key3].leastNext)}function reactiveSource(initialValue){return _reactive({initialValue})}function reactive(expression,initialValue){return _reactive({expression,initialValue})}function resetTopologicalSortCacheFor(ids){ids.forEach((id=>topologicalSortCache.delete(id)));topologicalSortCache.forEach(((value,key3)=>{ids.includes(key3)||topologicalSortCache.delete(key3)}))}function topologicalSort(startNode){if(topologicalSortCache.has(startNode.id)){const ref=topologicalSortCache.get(startNode.id);if(ref){const result2=ref.map((e3=>e3.instance.deref())).filter((e3=>e3));if(result2.length===ref.length)return result2}}const visited=new Set,sorted=[],recursionStack=new Set;(function visit(node){if(!visited.has(node)){if(recursionStack.has(node))throw new Error("Circular dependency detected!");visited.add(node);recursionStack.add(node);for(const dependant of node.dependants)visit(dependant);sorted.push(node);recursionStack.delete(node)}})(startNode);const result=sorted.reverse();topologicalSortCache.set(startNode.id,result.map((e3=>({id:e3.id,instance:new FallbackWeakRef(e3)}))));return result}function _reactive({expression,initialValue,isSource}){let value,_isDirty=!1;const id=_reactiveSourceId++,changeHandlers=new Set,instance3={id,dependants:new Set,_markDirty(){_isDirty||(_isDirty=!0)},markDirty(){topologicalSort(instance3).forEach((node=>node._markDirty()))},_rippleChanged(){changeHandlers.forEach((e3=>e3(instance3)))},rippleChanged(){topologicalSort(instance3).forEach((node=>node._rippleChanged()))},markClean(){_isDirty=!1},get isDirty(){return _isDirty},get value(){if(context&&!instance3.dependants.has(context)){instance3.dependants.add(context);resetTopologicalSortCacheFor([instance3.id,context.id])}if(_isDirty){if(expression){const oldValue=value,newValue=expression();isObjectDifferent(oldValue,newValue)&&(value=newValue)}instance3.markClean()}return value},set value(newValue){if(_isDirty&&!expression)value=newValue;else if(isObjectDifferent(value,newValue)){value=newValue;if(!_isDirty){instance3.markDirty();instance3.rippleChanged()}}},onChanged(handler){changeHandlers.add(handler)},offChanged(handler){changeHandlers.delete(handler)}};value=function initialize(){const previousContext=context;context=instance3;const r4=expression?expression(initialValue):initialValue;context=previousContext;return r4}();return instance3}function computed(expression){const v2=reactive(expression);return()=>v2.value}function __$checkInstanceBinding(instance3){const thisName=instance3.constructor.name,functions=[];for(const key3 of Object.getOwnPropertyNames(Object.getPrototypeOf(instance3)))key3.startsWith("_")&&!key3.startsWith("__")&&"function"==typeof instance3[key3]&&functions.push(`${thisName}.${key3}`);const functionsOnBindFunction=[],functionsOnBindFunctionMatch=instance3.onBindFunction.toString().match(/this\.(_[a-zA-Z0-9_]+)/g);functionsOnBindFunctionMatch&&functionsOnBindFunction.push(...functionsOnBindFunctionMatch.map((f4=>`${thisName}.${f4.replace(/this\./,"")}`)));const setOfThisFunctions=new Set(functions),setOfOnBindFunctions=new Set(functionsOnBindFunction),setAll=new Set([...setOfThisFunctions,...setOfOnBindFunctions]),missingInThis=[...setAll].filter((e3=>!setOfThisFunctions.has(e3))),missingInOnBind=[...setAll].filter((e3=>!setOfOnBindFunctions.has(e3)));missingInThis.length>0&&Logger(`[${thisName}] ⚠️ Missing functions in this: ${missingInThis.join(", ")}`);missingInOnBind.length>0&&Logger(`[${thisName}] ⚠️ Missing functions in onBindFunction: ${missingInOnBind.join(", ")}`);0==missingInThis.length&&0==missingInOnBind.length&&Logger(`[${thisName}] All functions are properly bound`,LOG_LEVEL_DEBUG)}function is_function(thing){return"function"==typeof thing}function run(fn){return fn()}function run_all(arr){for(var i2=0;i2<arr.length;i2++)arr[i2]()}function deferred(){var resolve,reject;return{promise:new Promise(((res2,rej)=>{resolve=res2;reject=rej})),resolve,reject}}function to_array(value,n3){if(Array.isArray(value))return value;if(void 0===n3||!(Symbol.iterator in value))return Array.from(value);const array=[];for(const element2 of value){array.push(element2);if(array.length===n3)break}return array}function lifecycle_outside_component(name){if(dev_fallback_default){const error=new Error(`lifecycle_outside_component\n\`${name}(...)\` can only be used during component initialisation\nhttps://svelte.dev/e/lifecycle_outside_component`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function async_derived_orphan(){if(dev_fallback_default){const error=new Error("async_derived_orphan\nCannot create a `$derived(...)` with an `await` expression outside of an effect tree\nhttps://svelte.dev/e/async_derived_orphan");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/async_derived_orphan")}function bind_invalid_checkbox_value(){if(dev_fallback_default){const error=new Error("bind_invalid_checkbox_value\nUsing `bind:value` together with a checkbox input is not allowed. Use `bind:checked` instead\nhttps://svelte.dev/e/bind_invalid_checkbox_value");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/bind_invalid_checkbox_value")}function derived_references_self(){if(dev_fallback_default){const error=new Error("derived_references_self\nA derived value cannot reference itself recursively\nhttps://svelte.dev/e/derived_references_self");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/derived_references_self")}function effect_in_teardown(rune){if(dev_fallback_default){const error=new Error(`effect_in_teardown\n\`${rune}\` cannot be used inside an effect cleanup function\nhttps://svelte.dev/e/effect_in_teardown`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/effect_in_teardown")}function effect_in_unowned_derived(){if(dev_fallback_default){const error=new Error("effect_in_unowned_derived\nEffect cannot be created inside a `$derived` value that was not itself created inside an effect\nhttps://svelte.dev/e/effect_in_unowned_derived");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function effect_orphan(rune){if(dev_fallback_default){const error=new Error(`effect_orphan\n\`${rune}\` can only be used inside an effect (e.g. during component initialisation)\nhttps://svelte.dev/e/effect_orphan`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/effect_orphan")}function effect_update_depth_exceeded(){if(dev_fallback_default){const error=new Error("effect_update_depth_exceeded\nMaximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state\nhttps://svelte.dev/e/effect_update_depth_exceeded");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function flush_sync_in_effect(){if(dev_fallback_default){const error=new Error("flush_sync_in_effect\nCannot use `flushSync` inside an effect\nhttps://svelte.dev/e/flush_sync_in_effect");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/flush_sync_in_effect")}function invalid_snippet(){if(dev_fallback_default){const error=new Error("invalid_snippet\nCould not `{@render}` snippet due to the expression being `null` or `undefined`. Consider using optional chaining `{@render snippet?.()}`\nhttps://svelte.dev/e/invalid_snippet");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/invalid_snippet")}function props_invalid_value(key3){if(dev_fallback_default){const error=new Error(`props_invalid_value\nCannot do \`bind:${key3}={undefined}\` when \`${key3}\` has a fallback value\nhttps://svelte.dev/e/props_invalid_value`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/props_invalid_value")}function rune_outside_svelte(rune){if(dev_fallback_default){const error=new Error(`rune_outside_svelte\nThe \`${rune}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files\nhttps://svelte.dev/e/rune_outside_svelte`);error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/rune_outside_svelte")}function set_context_after_init(){if(dev_fallback_default){const error=new Error("set_context_after_init\n`setContext` must be called when a component first initializes, not in a subsequent effect or after an `await` expression\nhttps://svelte.dev/e/set_context_after_init");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/set_context_after_init")}function state_descriptors_fixed(){if(dev_fallback_default){const error=new Error("state_descriptors_fixed\nProperty descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`.\nhttps://svelte.dev/e/state_descriptors_fixed");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function state_prototype_fixed(){if(dev_fallback_default){const error=new Error("state_prototype_fixed\nCannot set prototype of `$state` object\nhttps://svelte.dev/e/state_prototype_fixed");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/state_prototype_fixed")}function state_unsafe_mutation(){if(dev_fallback_default){const error=new Error("state_unsafe_mutation\nUpdating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`\nhttps://svelte.dev/e/state_unsafe_mutation");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function svelte_boundary_reset_onerror(){if(dev_fallback_default){const error=new Error("svelte_boundary_reset_onerror\nA `<svelte:boundary>` `reset` function cannot be called while an error is still being handled\nhttps://svelte.dev/e/svelte_boundary_reset_onerror");error.name="Svelte error";throw error}throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}function await_reactivity_loss(name){dev_fallback_default?console.warn(`%c[svelte] await_reactivity_loss\n%cDetected reactivity loss when reading \`${name}\`. This happens when state is read in an async function after an earlier \`await\`\nhttps://svelte.dev/e/await_reactivity_loss`,bold,normal):console.warn("https://svelte.dev/e/await_reactivity_loss")}function await_waterfall(name,location){dev_fallback_default?console.warn(`%c[svelte] await_waterfall\n%cAn async derived, \`${name}\` (${location}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app\nhttps://svelte.dev/e/await_waterfall`,bold,normal):console.warn("https://svelte.dev/e/await_waterfall")}function hydration_attribute_changed(attribute,html2,value){dev_fallback_default?console.warn(`%c[svelte] hydration_attribute_changed\n%cThe \`${attribute}\` attribute on \`${html2}\` changed its value between server and client renders. The client value, \`${value}\`, will be ignored in favour of the server value\nhttps://svelte.dev/e/hydration_attribute_changed`,bold,normal):console.warn("https://svelte.dev/e/hydration_attribute_changed")}function hydration_mismatch(location){dev_fallback_default?console.warn(`%c[svelte] hydration_mismatch\n%c${location?`Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${location}`:"Hydration failed because the initial UI does not match what was rendered on the server"}\nhttps://svelte.dev/e/hydration_mismatch`,bold,normal):console.warn("https://svelte.dev/e/hydration_mismatch")}function lifecycle_double_unmount(){dev_fallback_default?console.warn("%c[svelte] lifecycle_double_unmount\n%cTried to unmount a component that was not mounted\nhttps://svelte.dev/e/lifecycle_double_unmount",bold,normal):console.warn("https://svelte.dev/e/lifecycle_double_unmount")}function select_multiple_invalid_value(){dev_fallback_default?console.warn("%c[svelte] select_multiple_invalid_value\n%cThe `value` property of a `<select multiple>` element should be an array, but it received a non-array value. The selection will be kept as is.\nhttps://svelte.dev/e/select_multiple_invalid_value",bold,normal):console.warn("https://svelte.dev/e/select_multiple_invalid_value")}function state_proxy_equality_mismatch(operator){dev_fallback_default?console.warn(`%c[svelte] state_proxy_equality_mismatch\n%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${operator}\` will produce unexpected results\nhttps://svelte.dev/e/state_proxy_equality_mismatch`,bold,normal):console.warn("https://svelte.dev/e/state_proxy_equality_mismatch")}function state_proxy_unmount(){dev_fallback_default?console.warn("%c[svelte] state_proxy_unmount\n%cTried to unmount a state proxy, rather than a component\nhttps://svelte.dev/e/state_proxy_unmount",bold,normal):console.warn("https://svelte.dev/e/state_proxy_unmount")}function svelte_boundary_reset_noop(){dev_fallback_default?console.warn("%c[svelte] svelte_boundary_reset_noop\n%cA `<svelte:boundary>` `reset` function only resets the boundary the first time it is called\nhttps://svelte.dev/e/svelte_boundary_reset_noop",bold,normal):console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}function set_hydrating(value){hydrating=value}function set_hydrate_node(node){if(null===node){hydration_mismatch();throw HYDRATION_ERROR}return hydrate_node=node}function hydrate_next(){return set_hydrate_node(get_next_sibling(hydrate_node))}function reset(node){if(hydrating){if(null!==get_next_sibling(hydrate_node)){hydration_mismatch();throw HYDRATION_ERROR}hydrate_node=node}}function next(count=1){var i2,node;if(hydrating){i2=count;node=hydrate_node;for(;i2--;)node=get_next_sibling(node);hydrate_node=node}}function skip_nodes(remove=!0){for(var data,next2,depth=0,node=hydrate_node;;){if(node.nodeType===COMMENT_NODE)if((data=node.data)===HYDRATION_END){if(0===depth)return node;depth-=1}else data!==HYDRATION_START&&data!==HYDRATION_START_ELSE||(depth+=1);next2=get_next_sibling(node);remove&&node.remove();node=next2}}function read_hydration_instruction(node){if(!node||node.nodeType!==COMMENT_NODE){hydration_mismatch();throw HYDRATION_ERROR}return node.data}function equals(value){return value===this.v}function safe_not_equal(a2,b3){return a2!=a2?b3==b3:a2!==b3||null!==a2&&"object"==typeof a2||"function"==typeof a2}function safe_equals(value){return!safe_not_equal(value,this.v)}function get_stack(label2){let error=Error();const stack2=error.stack;if(!stack2)return null;const lines=stack2.split("\n"),new_lines=["\n"];for(let i2=0;i2<lines.length;i2++){const line=lines[i2];if("Error"!==line){if(line.includes("validate_each_keys"))return null;line.includes("svelte/src/internal")||new_lines.push(line)}}if(1===new_lines.length)return null;define_property(error,"stack",{value:new_lines.join("\n")});define_property(error,"name",{value:`${label2}Error`});return error}function tag(source2,label2){source2.label=label2;tag_proxy(source2.v,label2);return source2}function tag_proxy(value,label2){var _a8;null==(_a8=null==value?void 0:value[PROXY_PATH_SYMBOL])||_a8.call(value,label2);return value}function set_component_context(context2){component_context=context2}function set_dev_stack(stack2){dev_stack=stack2}function set_dev_current_component_function(fn){dev_current_component_function=fn}function getContext(key3){return get_or_init_context_map("getContext").get(key3)}function setContext(key3,context2){var flags2;const context_map=get_or_init_context_map("setContext");if(async_mode_flag){flags2=active_effect.f;!active_reaction&&flags2&BRANCH_EFFECT&&!(flags2&EFFECT_RAN)||set_context_after_init()}context_map.set(key3,context2);return context2}function push(props,runes=!1,fn){component_context={p:component_context,c:null,e:null,s:props,x:null,l:legacy_mode_flag&&!runes?{s:null,u:null,$:[]}:null};if(dev_fallback_default){component_context.function=fn;dev_current_component_function=fn}}function pop(component2){var _a8,fn,context2=component_context,effects=context2.e;if(null!==effects){context2.e=null;for(fn of effects)create_user_effect(fn)}void 0!==component2&&(context2.x=component2);component_context=context2.p;dev_fallback_default&&(dev_current_component_function=null!=(_a8=null==component_context?void 0:component_context.function)?_a8:null);return null!=component2?component2:{}}function is_runes(){return!legacy_mode_flag||null!==component_context&&null===component_context.l}function get_or_init_context_map(name){var _a8;null===component_context&&lifecycle_outside_component(name);return null!=(_a8=component_context.c)?_a8:component_context.c=new Map(get_parent_context(component_context)||void 0)}function get_parent_context(component_context2){let parent=component_context2.p;for(;null!==parent;){const context_map=parent.c;if(null!==context_map)return context_map;parent=parent.p}return null}function run_micro_tasks(){var tasks3=micro_tasks;micro_tasks=[];run_all(tasks3)}function queue_micro_task(fn){if(0===micro_tasks.length&&!is_flushing_sync){var tasks3=micro_tasks;queueMicrotask((()=>{tasks3===micro_tasks&&run_micro_tasks()}))}micro_tasks.push(fn)}function flush_tasks(){for(;micro_tasks.length>0;)run_micro_tasks()}function handle_error(error){var effect2=active_effect;if(null===effect2){active_reaction.f|=ERROR_VALUE;return error}dev_fallback_default&&error instanceof Error&&!adjustments.has(error)&&adjustments.set(error,get_adjustments(error,effect2));if(effect2.f&EFFECT_RAN)invoke_error_boundary(error,effect2);else{if(!(effect2.f&BOUNDARY_EFFECT)){!effect2.parent&&error instanceof Error&&apply_adjustments(error);throw error}effect2.b.error(error)}}function invoke_error_boundary(error,effect2){for(;null!==effect2;){if(effect2.f&BOUNDARY_EFFECT)try{effect2.b.error(error);return}catch(e3){error=e3}effect2=effect2.parent}error instanceof Error&&apply_adjustments(error);throw error}function get_adjustments(error,effect2){var _a8,_b5,_c3,indent,component_stack,context2;const message_descriptor=get_descriptor(error,"message");if(!message_descriptor||message_descriptor.configurable){component_stack=`\n${indent=is_firefox?" ":"\t"}in ${(null==(_a8=effect2.fn)?void 0:_a8.name)||"<unknown>"}`;context2=effect2.ctx;for(;null!==context2;){component_stack+=`\n${indent}in ${null==(_b5=context2.function)?void 0:_b5[FILENAME].split("/").pop()}`;context2=context2.p}return{message:error.message+`\n${component_stack}\n`,stack:null==(_c3=error.stack)?void 0:_c3.split("\n").filter((line=>!line.includes("svelte/src/internal"))).join("\n")}}}function apply_adjustments(error){const adjusted=adjustments.get(error);if(adjusted){define_property(error,"message",{value:adjusted.message});define_property(error,"stack",{value:adjusted.stack})}}function flushSync(fn){var was_flushing_sync,result;async_mode_flag&&null!==active_effect&&flush_sync_in_effect();was_flushing_sync=is_flushing_sync;is_flushing_sync=!0;try{if(fn){null!==current_batch&&flush_effects();result=fn()}for(;;){flush_tasks();if(0===queued_root_effects.length){null==current_batch||current_batch.flush();if(0===queued_root_effects.length){last_scheduled_effect=null;return result}}flush_effects()}}finally{is_flushing_sync=was_flushing_sync}}function flush_effects(){var _a8,flush_count,batch,updates,entry,was_updating_effect=is_updating_effect;is_flushing=!0;try{flush_count=0;set_is_updating_effect(!0);for(;queued_root_effects.length>0;){batch=Batch.ensure();if(flush_count++>1e3){if(dev_fallback_default){updates=new Map;for(const source2 of batch.current.keys())for(const[stack2,update2]of null!=(_a8=source2.updated)?_a8:[]){if(!(entry=updates.get(stack2))){entry={error:update2.error,count:0};updates.set(stack2,entry)}entry.count+=update2.count}for(const update2 of updates.values())console.error(update2.error)}infinite_loop_guard()}batch.process(queued_root_effects);old_values.clear()}}finally{is_flushing=!1;set_is_updating_effect(was_updating_effect);last_scheduled_effect=null}}function infinite_loop_guard(){try{effect_update_depth_exceeded()}catch(error){dev_fallback_default&&define_property(error,"stack",{value:""});invoke_error_boundary(error,last_scheduled_effect)}}function flush_queued_effects(effects){var i2,effect2,length=effects.length;if(0!==length){i2=0;for(;i2<length;)if(!((effect2=effects[i2++]).f&(DESTROYED|INERT))&&is_dirty(effect2)){eager_block_effects=[];update_effect(effect2);null===effect2.deps&&null===effect2.first&&null===effect2.nodes_start&&(null===effect2.teardown&&null===effect2.ac?unlink_effect(effect2):effect2.fn=null);if((null==eager_block_effects?void 0:eager_block_effects.length)>0){old_values.clear();for(const e3 of eager_block_effects)update_effect(e3);eager_block_effects=[]}}eager_block_effects=null}}function mark_effects(value,sources){if(null!==value.reactions)for(const reaction of value.reactions){const flags2=reaction.f;if(flags2&DERIVED)mark_effects(reaction,sources);else if(flags2&(ASYNC|BLOCK_EFFECT)&&depends_on(reaction,sources)){set_signal_status(reaction,DIRTY);schedule_effect(reaction)}}}function depends_on(reaction,sources){if(null!==reaction.deps)for(const dep of reaction.deps){if(sources.includes(dep))return!0;if(dep.f&DERIVED&&depends_on(dep,sources))return!0}return!1}function schedule_effect(signal){for(var flags2,effect2=last_scheduled_effect=signal;null!==effect2.parent;){flags2=(effect2=effect2.parent).f;if(is_flushing&&effect2===active_effect&&flags2&BLOCK_EFFECT)return;if(flags2&(ROOT_EFFECT|BRANCH_EFFECT)){if(!(flags2&CLEAN))return;effect2.f^=CLEAN}}queued_root_effects.push(effect2)}function createSubscriber(start){let stop,subscribers=0,version2=source(0);dev_fallback_default&&tag(version2,"createSubscriber version");return()=>{if(effect_tracking()){get(version2);render_effect((()=>{0===subscribers&&(stop=untrack((()=>start((()=>increment(version2))))));subscribers+=1;return()=>{queue_micro_task((()=>{subscribers-=1;if(0===subscribers){null==stop||stop();stop=void 0;increment(version2)}}))}}))}}}function boundary(node,props,children){new Boundary(node,props,children)}function flatten(sync3,async2,fn){var batch,parent,restore,was_hydrating;const d4=is_runes()?derived:derived_safe_equal;if(0!==async2.length){batch=current_batch;parent=active_effect;restore=capture();was_hydrating=hydrating;Promise.all(async2.map((expression=>async_derived(expression)))).then((result=>{restore();try{fn([...sync3.map(d4),...result])}catch(error){parent.f&DESTROYED||invoke_error_boundary(error,parent)}was_hydrating&&set_hydrating(!1);null==batch||batch.deactivate();unset_context()})).catch((error=>{invoke_error_boundary(error,parent)}))}else fn(sync3.map(d4))}function capture(){var previous_hydrate_node,previous_dev_stack,previous_effect=active_effect,previous_reaction=active_reaction,previous_component_context=component_context,previous_batch2=current_batch,was_hydrating=hydrating;was_hydrating&&(previous_hydrate_node=hydrate_node);dev_fallback_default&&(previous_dev_stack=dev_stack);return function restore(){set_active_effect(previous_effect);set_active_reaction(previous_reaction);set_component_context(previous_component_context);null==previous_batch2||previous_batch2.activate();if(was_hydrating){set_hydrating(!0);set_hydrate_node(previous_hydrate_node)}if(dev_fallback_default){set_from_async_derived(null);set_dev_stack(previous_dev_stack)}}}function unset_context(){set_active_effect(null);set_active_reaction(null);set_component_context(null);if(dev_fallback_default){set_from_async_derived(null);set_dev_stack(null)}}function set_from_async_derived(v2){current_async_effect=v2}function derived(fn){var flags2=DERIVED|DIRTY,parent_derived=null!==active_reaction&&active_reaction.f&DERIVED?active_reaction:null;null===active_effect||null!==parent_derived&&parent_derived.f&UNOWNED?flags2|=UNOWNED:active_effect.f|=EFFECT_PRESERVED;const signal={ctx:component_context,deps:null,effects:null,equals,f:flags2,fn,reactions:null,rv:0,v:UNINITIALIZED,wv:0,parent:null!=parent_derived?parent_derived:active_effect,ac:null};dev_fallback_default&&tracing_mode_flag&&(signal.created=get_stack("CreatedAt"));return signal}function async_derived(fn,location){var boundary2,promise,signal,should_suspend,deferreds;let parent=active_effect;null===parent&&async_derived_orphan();boundary2=parent.b;promise=void 0;signal=source(UNINITIALIZED);should_suspend=!active_reaction;deferreds=new Map;async_effect((()=>{var _a8,d4,batch,pending3;dev_fallback_default&&(current_async_effect=active_effect);d4=deferred();promise=d4.promise;try{Promise.resolve(fn()).then(d4.resolve,d4.reject).then(unset_context)}catch(error){d4.reject(error);unset_context()}dev_fallback_default&&(current_async_effect=null);batch=current_batch;pending3=boundary2.is_pending();if(should_suspend){boundary2.update_pending_count(1);if(!pending3){batch.increment();null==(_a8=deferreds.get(batch))||_a8.reject(STALE_REACTION);deferreds.delete(batch);deferreds.set(batch,d4)}}const handler=(value,error=void 0)=>{current_async_effect=null;pending3||batch.activate();if(error){if(error!==STALE_REACTION){signal.f|=ERROR_VALUE;internal_set(signal,error)}}else{signal.f&ERROR_VALUE&&(signal.f^=ERROR_VALUE);internal_set(signal,value);for(const[b3,d5]of deferreds){deferreds.delete(b3);if(b3===batch)break;d5.reject(STALE_REACTION)}if(dev_fallback_default&&void 0!==location){recent_async_deriveds.add(signal);setTimeout((()=>{if(recent_async_deriveds.has(signal)){await_waterfall(signal.label,location);recent_async_deriveds.delete(signal)}}))}}if(should_suspend){boundary2.update_pending_count(-1);pending3||batch.decrement()}};d4.promise.then(handler,(e3=>handler(null,e3||"unknown")))}));teardown((()=>{for(const d4 of deferreds.values())d4.reject(STALE_REACTION)}));dev_fallback_default&&(signal.f|=ASYNC);return new Promise((fulfil=>{(function next2(p4){function go(){p4===promise?fulfil(signal):next2(promise)}p4.then(go,go)})(promise)}))}function user_derived(fn){const d4=derived(fn);async_mode_flag||push_reaction_value(d4);return d4}function derived_safe_equal(fn){const signal=derived(fn);signal.equals=safe_equals;return signal}function destroy_derived_effects(derived3){var i2,effects=derived3.effects;if(null!==effects){derived3.effects=null;for(i2=0;i2<effects.length;i2+=1)destroy_effect(effects[i2])}}function get_derived_parent_effect(derived3){for(var parent=derived3.parent;null!==parent;){if(!(parent.f&DERIVED))return parent;parent=parent.parent}return null}function execute_derived(derived3){var value,prev_active_effect=active_effect;set_active_effect(get_derived_parent_effect(derived3));if(dev_fallback_default){let prev_inspect_effects=inspect_effects;set_inspect_effects(new Set);try{stack.includes(derived3)&&derived_references_self();stack.push(derived3);destroy_derived_effects(derived3);value=update_reaction(derived3)}finally{set_active_effect(prev_active_effect);set_inspect_effects(prev_inspect_effects);stack.pop()}}else try{destroy_derived_effects(derived3);value=update_reaction(derived3)}finally{set_active_effect(prev_active_effect)}return value}function update_derived(derived3){var value=execute_derived(derived3);if(!derived3.equals(value)){derived3.v=value;derived3.wv=increment_write_version()}is_destroying_effect||(null!==batch_values?batch_values.set(derived3,derived3.v):set_signal_status(derived3,(skip_reaction||derived3.f&UNOWNED)&&null!==derived3.deps?MAYBE_DIRTY:CLEAN))}function set_inspect_effects(v2){inspect_effects=v2}function set_inspect_effects_deferred(){inspect_effects_deferred=!0}function source(v2,stack2){var signal={f:0,v:v2,reactions:null,equals,rv:0,wv:0};if(dev_fallback_default&&tracing_mode_flag){signal.created=null!=stack2?stack2:get_stack("CreatedAt");signal.updated=null;signal.set_during_effect=!1;signal.trace=null}return signal}function state(v2,stack2){const s2=source(v2,stack2);push_reaction_value(s2);return s2}function mutable_source(initial_value,immutable=!1,trackable=!0){var _a8,_b5;const s2=source(initial_value);immutable||(s2.equals=safe_equals);legacy_mode_flag&&trackable&&null!==component_context&&null!==component_context.l&&(null!=(_b5=(_a8=component_context.l).s)?_b5:_a8.s=[]).push(s2);return s2}function set(source2,value,should_proxy=!1){var _a8;null!==active_reaction&&(!untracking||active_reaction.f&INSPECT_EFFECT)&&is_runes()&&active_reaction.f&(DERIVED|BLOCK_EFFECT|ASYNC|INSPECT_EFFECT)&&!(null==(_a8=current_sources)?void 0:_a8.includes(source2))&&state_unsafe_mutation();let new_value=should_proxy?proxy(value):value;dev_fallback_default&&tag_proxy(new_value,source2.label);return internal_set(source2,new_value)}function internal_set(source2,value){var old_value;if(!source2.equals(value)){old_value=source2.v;is_destroying_effect?old_values.set(source2,value):old_values.set(source2,old_value);source2.v=value;Batch.ensure().capture(source2,old_value);if(dev_fallback_default){if(tracing_mode_flag||null!==active_effect){const error=get_stack("UpdatedAt");if(null!==error){null!=source2.updated||(source2.updated=new Map);let entry=source2.updated.get(error.stack);if(!entry){entry={error,count:0};source2.updated.set(error.stack,entry)}entry.count++}}null!==active_effect&&(source2.set_during_effect=!0)}if(source2.f&DERIVED){source2.f&DIRTY&&execute_derived(source2);set_signal_status(source2,source2.f&UNOWNED?MAYBE_DIRTY:CLEAN)}source2.wv=increment_write_version();mark_reactions(source2,DIRTY);is_runes()&&null!==active_effect&&active_effect.f&CLEAN&&!(active_effect.f&(BRANCH_EFFECT|ROOT_EFFECT))&&(null===untracked_writes?set_untracked_writes([source2]):untracked_writes.push(source2));dev_fallback_default&&inspect_effects.size>0&&!inspect_effects_deferred&&flush_inspect_effects()}return value}function flush_inspect_effects(){inspect_effects_deferred=!1;const inspects=Array.from(inspect_effects);for(const effect2 of inspects){effect2.f&CLEAN&&set_signal_status(effect2,MAYBE_DIRTY);is_dirty(effect2)&&update_effect(effect2)}inspect_effects.clear()}function update(source2,d4=1){var value=get(source2),result=1===d4?value++:value--;set(source2,value);return result}function increment(source2){set(source2,source2.v+1)}function mark_reactions(signal,status){var runes,length,i2,reaction,flags2,not_dirty,reactions=signal.reactions;if(null!==reactions){runes=is_runes();length=reactions.length;for(i2=0;i2<length;i2++){flags2=(reaction=reactions[i2]).f;if(runes||reaction!==active_effect)if(dev_fallback_default&&flags2&INSPECT_EFFECT)inspect_effects.add(reaction);else{(not_dirty=!(flags2&DIRTY))&&set_signal_status(reaction,status);if(flags2&DERIVED)mark_reactions(reaction,MAYBE_DIRTY);else if(not_dirty){flags2&BLOCK_EFFECT&&null!==eager_block_effects&&eager_block_effects.push(reaction);schedule_effect(reaction)}}}}}function proxy(value){function update_path(new_path){if(!updating){updating=!0;tag(version2,`${path2=new_path} version`);for(const[prop2,source2]of sources)tag(source2,get_label(path2,prop2));updating=!1}}var sources,is_proxied_array,version2,stack2,parent_version,with_parent,path2;if("object"!=typeof value||null===value||STATE_SYMBOL in value)return value;const prototype=get_prototype_of(value);if(prototype!==object_prototype&&prototype!==array_prototype)return value;sources=new Map;is_proxied_array=is_array(value);version2=state(0);stack2=dev_fallback_default&&tracing_mode_flag?get_stack("CreatedAt"):null;parent_version=update_version;with_parent=fn=>{var reaction,version3,result;if(update_version===parent_version)return fn();reaction=active_reaction;version3=update_version;set_active_reaction(null);set_update_version(parent_version);result=fn();set_active_reaction(reaction);set_update_version(version3);return result};if(is_proxied_array){sources.set("length",state(value.length,stack2));dev_fallback_default&&(value=inspectable_array(value))}path2="";let updating=!1;return new Proxy(value,{defineProperty(_,prop2,descriptor){"value"in descriptor&&!1!==descriptor.configurable&&!1!==descriptor.enumerable&&!1!==descriptor.writable||state_descriptors_fixed();var s2=sources.get(prop2);void 0===s2?s2=with_parent((()=>{var s3=state(descriptor.value,stack2);sources.set(prop2,s3);dev_fallback_default&&"string"==typeof prop2&&tag(s3,get_label(path2,prop2));return s3})):set(s2,descriptor.value,!0);return!0},deleteProperty(target,prop2){var s2=sources.get(prop2);if(void 0===s2){if(prop2 in target){const s3=with_parent((()=>state(UNINITIALIZED,stack2)));sources.set(prop2,s3);increment(version2);dev_fallback_default&&tag(s3,get_label(path2,prop2))}}else{set(s2,UNINITIALIZED);increment(version2)}return!0},get(target,prop2,receiver){var _a8,s2,exists,v2;if(prop2===STATE_SYMBOL)return value;if(dev_fallback_default&&prop2===PROXY_PATH_SYMBOL)return update_path;s2=sources.get(prop2);exists=prop2 in target;if(void 0===s2&&(!exists||(null==(_a8=get_descriptor(target,prop2))?void 0:_a8.writable))){s2=with_parent((()=>{var s3=state(proxy(exists?target[prop2]:UNINITIALIZED),stack2);dev_fallback_default&&tag(s3,get_label(path2,prop2));return s3}));sources.set(prop2,s2)}return void 0!==s2?(v2=get(s2))===UNINITIALIZED?void 0:v2:Reflect.get(target,prop2,receiver)},getOwnPropertyDescriptor(target,prop2){var s2,source2,value2,descriptor=Reflect.getOwnPropertyDescriptor(target,prop2);if(descriptor&&"value"in descriptor)(s2=sources.get(prop2))&&(descriptor.value=get(s2));else if(void 0===descriptor){value2=null==(source2=sources.get(prop2))?void 0:source2.v;if(void 0!==source2&&value2!==UNINITIALIZED)return{enumerable:!0,configurable:!0,value:value2,writable:!0}}return descriptor},has(target,prop2){var _a8,s2,has;if(prop2===STATE_SYMBOL)return!0;s2=sources.get(prop2);has=void 0!==s2&&s2.v!==UNINITIALIZED||Reflect.has(target,prop2);if(void 0!==s2||null!==active_effect&&(!has||(null==(_a8=get_descriptor(target,prop2))?void 0:_a8.writable))){if(void 0===s2){s2=with_parent((()=>{var s3=state(has?proxy(target[prop2]):UNINITIALIZED,stack2);dev_fallback_default&&tag(s3,get_label(path2,prop2));return s3}));sources.set(prop2,s2)}if(get(s2)===UNINITIALIZED)return!1}return has},set(target,prop2,value2,receiver){var _a8,i2,other_s,descriptor,ls,n3,s2=sources.get(prop2),has=prop2 in target;if(is_proxied_array&&"length"===prop2)for(i2=value2;i2<s2.v;i2+=1)if(void 0!==(other_s=sources.get(i2+"")))set(other_s,UNINITIALIZED);else if(i2 in target){other_s=with_parent((()=>state(UNINITIALIZED,stack2)));sources.set(i2+"",other_s);dev_fallback_default&&tag(other_s,get_label(path2,i2))}if(void 0===s2){if(!has||(null==(_a8=get_descriptor(target,prop2))?void 0:_a8.writable)){s2=with_parent((()=>state(void 0,stack2)));dev_fallback_default&&tag(s2,get_label(path2,prop2));set(s2,proxy(value2));sources.set(prop2,s2)}}else{has=s2.v!==UNINITIALIZED;set(s2,with_parent((()=>proxy(value2))))}(null==(descriptor=Reflect.getOwnPropertyDescriptor(target,prop2))?void 0:descriptor.set)&&descriptor.set.call(receiver,value2);if(!has){if(is_proxied_array&&"string"==typeof prop2){ls=sources.get("length");n3=Number(prop2);Number.isInteger(n3)&&n3>=ls.v&&set(ls,n3+1)}increment(version2)}return!0},ownKeys(target){var own_keys;get(version2);own_keys=Reflect.ownKeys(target).filter((key4=>{var source3=sources.get(key4);return void 0===source3||source3.v!==UNINITIALIZED}));for(var[key3,source2]of sources)source2.v===UNINITIALIZED||key3 in target||own_keys.push(key3);return own_keys},setPrototypeOf(){state_prototype_fixed()}})}function get_label(path2,prop2){var _a8;return"symbol"==typeof prop2?`${path2}[Symbol(${null!=(_a8=prop2.description)?_a8:""})]`:regex_is_valid_identifier.test(prop2)?`${path2}.${prop2}`:/^\d+$/.test(prop2)?`${path2}[${prop2}]`:`${path2}['${prop2}']`}function get_proxied_value(value){try{if(null!==value&&"object"==typeof value&&STATE_SYMBOL in value)return value[STATE_SYMBOL]}catch(e3){}return value}function is(a2,b3){return Object.is(get_proxied_value(a2),get_proxied_value(b3))}function inspectable_array(array){return new Proxy(array,{get(target,prop2,receiver){var value=Reflect.get(target,prop2,receiver);return ARRAY_MUTATING_METHODS.has(prop2)?function(...args){set_inspect_effects_deferred();var result=value.apply(this,args);flush_inspect_effects();return result}:value}})}function init_array_prototype_warnings(){const array_prototype2=Array.prototype,cleanup=Array.__svelte_cleanup;cleanup&&cleanup();const{indexOf,lastIndexOf,includes}=array_prototype2;array_prototype2.indexOf=function(item,from_index){const index6=indexOf.call(this,item,from_index);if(-1===index6)for(let i2=null!=from_index?from_index:0;i2<this.length;i2+=1)if(get_proxied_value(this[i2])===item){state_proxy_equality_mismatch("array.indexOf(...)");break}return index6};array_prototype2.lastIndexOf=function(item,from_index){const index6=lastIndexOf.call(this,item,null!=from_index?from_index:this.length-1);if(-1===index6)for(let i2=0;i2<=(null!=from_index?from_index:this.length-1);i2+=1)if(get_proxied_value(this[i2])===item){state_proxy_equality_mismatch("array.lastIndexOf(...)");break}return index6};array_prototype2.includes=function(item,from_index){const has=includes.call(this,item,from_index);if(!has)for(let i2=0;i2<this.length;i2+=1)if(get_proxied_value(this[i2])===item){state_proxy_equality_mismatch("array.includes(...)");break}return has};Array.__svelte_cleanup=()=>{array_prototype2.indexOf=indexOf;array_prototype2.lastIndexOf=lastIndexOf;array_prototype2.includes=includes}}function init_operations(){var element_prototype,node_prototype,text_prototype;if(void 0===$window){$window=window;document;is_firefox=/Firefox/.test(navigator.userAgent);element_prototype=Element.prototype;node_prototype=Node.prototype;text_prototype=Text.prototype;first_child_getter=get_descriptor(node_prototype,"firstChild").get;next_sibling_getter=get_descriptor(node_prototype,"nextSibling").get;if(is_extensible(element_prototype)){element_prototype.__click=void 0;element_prototype.__className=void 0;element_prototype.__attributes=null;element_prototype.__style=void 0;element_prototype.__e=void 0}is_extensible(text_prototype)&&(text_prototype.__t=void 0);if(dev_fallback_default){element_prototype.__svelte_meta=null;init_array_prototype_warnings()}}}function create_text(value=""){return document.createTextNode(value)}function get_first_child(node){return first_child_getter.call(node)}function get_next_sibling(node){return next_sibling_getter.call(node)}function child(node,is_text){var child2,text2;if(!hydrating)return get_first_child(node);if(null===(child2=get_first_child(hydrate_node)))child2=hydrate_node.appendChild(create_text());else if(is_text&&child2.nodeType!==TEXT_NODE){text2=create_text();null==child2||child2.before(text2);set_hydrate_node(text2);return text2}set_hydrate_node(child2);return child2}function first_child(fragment,is_text=!1){var _a8,_b5,first,text2;if(!hydrating)return(first=get_first_child(fragment))instanceof Comment&&""===first.data?get_next_sibling(first):first;if(is_text&&(null==(_a8=hydrate_node)?void 0:_a8.nodeType)!==TEXT_NODE){text2=create_text();null==(_b5=hydrate_node)||_b5.before(text2);set_hydrate_node(text2);return text2}return hydrate_node}function sibling(node,count=1,is_text=!1){var last_sibling,text2;let next_sibling=hydrating?hydrate_node:node;for(;count--;){last_sibling=next_sibling;next_sibling=get_next_sibling(next_sibling)}if(!hydrating)return next_sibling;if(is_text&&(null==next_sibling?void 0:next_sibling.nodeType)!==TEXT_NODE){text2=create_text();null===next_sibling?null==last_sibling||last_sibling.after(text2):next_sibling.before(text2);set_hydrate_node(text2);return text2}set_hydrate_node(next_sibling);return next_sibling}function clear_text_content(node){node.textContent=""}function should_defer_append(){return!!async_mode_flag&&null===eager_block_effects&&!!(active_effect.f&EFFECT_RAN)}function remove_textarea_child(dom){hydrating&&null!==get_first_child(dom)&&clear_text_content(dom)}function add_form_reset_listener(){if(!listening_to_form_reset){listening_to_form_reset=!0;document.addEventListener("reset",(evt=>{Promise.resolve().then((()=>{var _a8;if(!evt.defaultPrevented)for(const e3 of evt.target.elements)null==(_a8=e3.__on_r)||_a8.call(e3)}))}),{capture:!0})}}function without_reactive_context(fn){var previous_reaction=active_reaction,previous_effect=active_effect;set_active_reaction(null);set_active_effect(null);try{return fn()}finally{set_active_reaction(previous_reaction);set_active_effect(previous_effect)}}function listen_to_event_and_reset_event(element2,event2,handler,on_reset=handler){element2.addEventListener(event2,(()=>without_reactive_context(handler)));const prev=element2.__on_r;element2.__on_r=prev?()=>{prev();on_reset(!0)}:()=>on_reset(!0);add_form_reset_listener()}function validate_effect(rune){null===active_effect&&null===active_reaction&&effect_orphan(rune);null!==active_reaction&&active_reaction.f&UNOWNED&&null===active_effect&&effect_in_unowned_derived();is_destroying_effect&&effect_in_teardown(rune)}function push_effect(effect2,parent_effect){var parent_last=parent_effect.last;if(null===parent_last)parent_effect.last=parent_effect.first=effect2;else{parent_last.next=effect2;effect2.prev=parent_last;parent_effect.last=effect2}}function create_effect(type,fn,sync3,push2=!0){var _a8,effect2,e3,derived3,parent=active_effect;if(dev_fallback_default)for(;null!==parent&&parent.f&INSPECT_EFFECT;)parent=parent.parent;null!==parent&&parent.f&INERT&&(type|=INERT);effect2={ctx:component_context,deps:null,nodes_start:null,nodes_end:null,f:type|DIRTY,first:null,fn,last:null,next:null,parent,b:parent&&parent.b,prev:null,teardown:null,transitions:null,wv:0,ac:null};dev_fallback_default&&(effect2.component_function=dev_current_component_function);if(sync3)try{update_effect(effect2);effect2.f|=EFFECT_RAN}catch(e4){destroy_effect(effect2);throw e4}else null!==fn&&schedule_effect(effect2);if(push2){e3=effect2;!sync3||null!==e3.deps||null!==e3.teardown||null!==e3.nodes_start||e3.first!==e3.last||e3.f&EFFECT_PRESERVED||(e3=e3.first);if(null!==e3){e3.parent=parent;null!==parent&&push_effect(e3,parent);null!==active_reaction&&active_reaction.f&DERIVED&&!(type&ROOT_EFFECT)&&(null!=(_a8=(derived3=active_reaction).effects)?_a8:derived3.effects=[]).push(e3)}}return effect2}function effect_tracking(){return null!==active_reaction&&!untracking}function teardown(fn){const effect2=create_effect(RENDER_EFFECT,null,!1);set_signal_status(effect2,CLEAN);effect2.teardown=fn;return effect2}function user_effect(fn){var _a8,flags2,context2;validate_effect("$effect");dev_fallback_default&&define_property(fn,"name",{value:"$effect"});flags2=active_effect.f;if(active_reaction||!(flags2&BRANCH_EFFECT)||flags2&EFFECT_RAN)return create_user_effect(fn);(null!=(_a8=(context2=component_context).e)?_a8:context2.e=[]).push(fn)}function create_user_effect(fn){return create_effect(EFFECT|USER_EFFECT,fn,!1)}function user_pre_effect(fn){validate_effect("$effect.pre");dev_fallback_default&&define_property(fn,"name",{value:"$effect.pre"});return create_effect(RENDER_EFFECT|USER_EFFECT,fn,!0)}function component_root(fn){Batch.ensure();const effect2=create_effect(ROOT_EFFECT|EFFECT_PRESERVED,fn,!0);return(options={})=>new Promise((fulfil=>{if(options.outro)pause_effect(effect2,(()=>{destroy_effect(effect2);fulfil(void 0)}));else{destroy_effect(effect2);fulfil(void 0)}}))}function effect(fn){return create_effect(EFFECT,fn,!1)}function legacy_pre_effect(deps,fn){var token={effect:null,ran:!1,deps};component_context.l.$.push(token);token.effect=render_effect((()=>{deps();if(!token.ran){token.ran=!0;untrack(fn)}}))}function legacy_pre_effect_reset(){var context2=component_context;render_effect((()=>{var token,effect2;for(token of context2.l.$){token.deps();(effect2=token.effect).f&CLEAN&&set_signal_status(effect2,MAYBE_DIRTY);is_dirty(effect2)&&update_effect(effect2);token.ran=!1}}))}function async_effect(fn){return create_effect(ASYNC|EFFECT_PRESERVED,fn,!0)}function render_effect(fn,flags2=0){return create_effect(RENDER_EFFECT|flags2,fn,!0)}function template_effect(fn,sync3=[],async2=[]){flatten(sync3,async2,(values=>{create_effect(RENDER_EFFECT,(()=>fn(...values.map(get))),!0)}))}function block(fn,flags2=0){var effect2=create_effect(BLOCK_EFFECT|flags2,fn,!0);dev_fallback_default&&(effect2.dev_stack=dev_stack);return effect2}function branch(fn,push2=!0){return create_effect(BRANCH_EFFECT|EFFECT_PRESERVED,fn,!0,push2)}function execute_effect_teardown(effect2){var teardown2=effect2.teardown;if(null!==teardown2){const previously_destroying_effect=is_destroying_effect,previous_reaction=active_reaction;set_is_destroying_effect(!0);set_active_reaction(null);try{teardown2.call(null)}finally{set_is_destroying_effect(previously_destroying_effect);set_active_reaction(previous_reaction)}}}function destroy_effect_children(signal,remove_dom=!1){var next2,effect2=signal.first;signal.first=signal.last=null;for(;null!==effect2;){const controller=effect2.ac;null!==controller&&without_reactive_context((()=>{controller.abort(STALE_REACTION)}));next2=effect2.next;effect2.f&ROOT_EFFECT?effect2.parent=null:destroy_effect(effect2,remove_dom);effect2=next2}}function destroy_block_effect_children(signal){for(var next2,effect2=signal.first;null!==effect2;){next2=effect2.next;effect2.f&BRANCH_EFFECT||destroy_effect(effect2);effect2=next2}}function destroy_effect(effect2,remove_dom=!0){var transitions,parent,removed=!1;if((remove_dom||effect2.f&HEAD_EFFECT)&&null!==effect2.nodes_start&&null!==effect2.nodes_end){remove_effect_dom(effect2.nodes_start,effect2.nodes_end);removed=!0}destroy_effect_children(effect2,remove_dom&&!removed);remove_reactions(effect2,0);set_signal_status(effect2,DESTROYED);if(null!==(transitions=effect2.transitions))for(const transition2 of transitions)transition2.stop();execute_effect_teardown(effect2);null!==(parent=effect2.parent)&&null!==parent.first&&unlink_effect(effect2);dev_fallback_default&&(effect2.component_function=null);effect2.next=effect2.prev=effect2.teardown=effect2.ctx=effect2.deps=effect2.fn=effect2.nodes_start=effect2.nodes_end=effect2.ac=null}function remove_effect_dom(node,end){for(;null!==node;){var next2=node===end?null:get_next_sibling(node);node.remove();node=next2}}function unlink_effect(effect2){var parent=effect2.parent,prev=effect2.prev,next2=effect2.next;null!==prev&&(prev.next=next2);null!==next2&&(next2.prev=prev);if(null!==parent){parent.first===effect2&&(parent.first=next2);parent.last===effect2&&(parent.last=prev)}}function pause_effect(effect2,callback,destroy2=!0){var transitions=[];pause_children(effect2,transitions,!0);run_out_transitions(transitions,(()=>{destroy2&&destroy_effect(effect2);callback&&callback()}))}function run_out_transitions(transitions,fn){var check,transition2,remaining=transitions.length;if(remaining>0){check=()=>--remaining||fn();for(transition2 of transitions)transition2.out(check)}else fn()}function pause_children(effect2,transitions,local){var child2,sibling2;if(!(effect2.f&INERT)){effect2.f^=INERT;if(null!==effect2.transitions)for(const transition2 of effect2.transitions)(transition2.is_global||local)&&transitions.push(transition2);child2=effect2.first;for(;null!==child2;){sibling2=child2.next;pause_children(child2,transitions,!!(child2.f&EFFECT_TRANSPARENT||child2.f&BRANCH_EFFECT)&&local);child2=sibling2}}}function resume_effect(effect2){resume_children(effect2,!0)}function resume_children(effect2,local){var child2,sibling2;if(effect2.f&INERT){effect2.f^=INERT;if(!(effect2.f&CLEAN)){set_signal_status(effect2,DIRTY);schedule_effect(effect2)}child2=effect2.first;for(;null!==child2;){sibling2=child2.next;resume_children(child2,!!(child2.f&EFFECT_TRANSPARENT||child2.f&BRANCH_EFFECT)&&local);child2=sibling2}if(null!==effect2.transitions)for(const transition2 of effect2.transitions)(transition2.is_global||local)&&transition2.in()}}function move_effect(effect2,fragment){for(var next2,node=effect2.nodes_start,end=effect2.nodes_end;null!==node;){next2=node===end?null:get_next_sibling(node);fragment.append(node);node=next2}}function capture_signals(fn){var signal,previous_captured_signals=captured_signals;try{captured_signals=new Set;untrack(fn);if(null!==previous_captured_signals)for(signal of captured_signals)previous_captured_signals.add(signal);return captured_signals}finally{captured_signals=previous_captured_signals}}function invalidate_inner_signals(fn){for(var signal of capture_signals(fn))internal_set(signal,signal.v)}function set_is_updating_effect(value){is_updating_effect=value}function set_is_destroying_effect(value){is_destroying_effect=value}function set_active_reaction(reaction){active_reaction=reaction}function set_active_effect(effect2){active_effect=effect2}function push_reaction_value(value){null!==active_reaction&&(!async_mode_flag||active_reaction.f&DERIVED)&&(null===current_sources?current_sources=[value]:current_sources.push(value))}function set_untracked_writes(value){untracked_writes=value}function set_update_version(value){update_version=value}function increment_write_version(){return++write_version}function is_dirty(reaction){var _a8,_b5,dependencies,is_unowned,i2,dependency,is_disconnected,is_unowned_connected,length,derived3,parent,flags2=reaction.f;if(flags2&DIRTY)return!0;if(flags2&MAYBE_DIRTY){dependencies=reaction.deps;is_unowned=!!(flags2&UNOWNED);if(null!==dependencies){is_disconnected=!!(flags2&DISCONNECTED);is_unowned_connected=is_unowned&&null!==active_effect&&!skip_reaction;length=dependencies.length;if((is_disconnected||is_unowned_connected)&&(null===active_effect||!(active_effect.f&DESTROYED))){parent=(derived3=reaction).parent;for(i2=0;i2<length;i2++){dependency=dependencies[i2];!is_disconnected&&(null==(_a8=null==dependency?void 0:dependency.reactions)?void 0:_a8.includes(derived3))||(null!=(_b5=dependency.reactions)?_b5:dependency.reactions=[]).push(derived3)}is_disconnected&&(derived3.f^=DISCONNECTED);!is_unowned_connected||null===parent||parent.f&UNOWNED||(derived3.f^=UNOWNED)}for(i2=0;i2<length;i2++){is_dirty(dependency=dependencies[i2])&&update_derived(dependency);if(dependency.wv>reaction.wv)return!0}}is_unowned&&(null===active_effect||skip_reaction)||set_signal_status(reaction,CLEAN)}return!1}function schedule_possible_effect_self_invalidation(signal,effect2,root40=!0){var i2,reaction,reactions=signal.reactions;if(null!==reactions&&(async_mode_flag||!(null==current_sources?void 0:current_sources.includes(signal))))for(i2=0;i2<reactions.length;i2++)if((reaction=reactions[i2]).f&DERIVED)schedule_possible_effect_self_invalidation(reaction,effect2,!1);else if(effect2===reaction){root40?set_signal_status(reaction,DIRTY):reaction.f&CLEAN&&set_signal_status(reaction,MAYBE_DIRTY);schedule_effect(reaction)}}function update_reaction(reaction){var _a8,_b5,result,deps,i2,previous_deps=new_deps,previous_skipped_deps=skipped_deps,previous_untracked_writes=untracked_writes,previous_reaction=active_reaction,previous_skip_reaction=skip_reaction,previous_sources=current_sources,previous_component_context=component_context,previous_untracking=untracking,previous_update_version=update_version,flags2=reaction.f;new_deps=null;skipped_deps=0;untracked_writes=null;skip_reaction=!!(flags2&UNOWNED)&&(untracking||!is_updating_effect||null===active_reaction);active_reaction=flags2&(BRANCH_EFFECT|ROOT_EFFECT)?null:reaction;current_sources=null;set_component_context(reaction.ctx);untracking=!1;update_version=++read_version;if(null!==reaction.ac){without_reactive_context((()=>{reaction.ac.abort(STALE_REACTION)}));reaction.ac=null}try{reaction.f|=REACTION_IS_UPDATING;result=(0,reaction.fn)();deps=reaction.deps;if(null!==new_deps){remove_reactions(reaction,skipped_deps);if(null!==deps&&skipped_deps>0){deps.length=skipped_deps+new_deps.length;for(i2=0;i2<new_deps.length;i2++)deps[skipped_deps+i2]=new_deps[i2]}else reaction.deps=deps=new_deps;if(!skip_reaction||flags2&DERIVED&&null!==reaction.reactions)for(i2=skipped_deps;i2<deps.length;i2++)(null!=(_b5=(_a8=deps[i2]).reactions)?_b5:_a8.reactions=[]).push(reaction)}else if(null!==deps&&skipped_deps<deps.length){remove_reactions(reaction,skipped_deps);deps.length=skipped_deps}if(is_runes()&&null!==untracked_writes&&!untracking&&null!==deps&&!(reaction.f&(DERIVED|MAYBE_DIRTY|DIRTY)))for(i2=0;i2<untracked_writes.length;i2++)schedule_possible_effect_self_invalidation(untracked_writes[i2],reaction);if(null!==previous_reaction&&previous_reaction!==reaction){read_version++;null!==untracked_writes&&(null===previous_untracked_writes?previous_untracked_writes=untracked_writes:previous_untracked_writes.push(...untracked_writes))}reaction.f&ERROR_VALUE&&(reaction.f^=ERROR_VALUE);return result}catch(error){return handle_error(error)}finally{reaction.f^=REACTION_IS_UPDATING;new_deps=previous_deps;skipped_deps=previous_skipped_deps;untracked_writes=previous_untracked_writes;active_reaction=previous_reaction;skip_reaction=previous_skip_reaction;current_sources=previous_sources;set_component_context(previous_component_context);untracking=previous_untracking;update_version=previous_update_version}}function remove_reaction(signal,dependency){var index6,new_length;let reactions=dependency.reactions;if(null!==reactions&&-1!==(index6=index_of.call(reactions,signal)))if(0==(new_length=reactions.length-1))reactions=dependency.reactions=null;else{reactions[index6]=reactions[new_length];reactions.pop()}if(null===reactions&&dependency.f&DERIVED&&(null===new_deps||!new_deps.includes(dependency))){set_signal_status(dependency,MAYBE_DIRTY);dependency.f&(UNOWNED|DISCONNECTED)||(dependency.f^=DISCONNECTED);destroy_derived_effects(dependency);remove_reactions(dependency,0)}}function remove_reactions(signal,start_index){var i2,dependencies=signal.deps;if(null!==dependencies)for(i2=start_index;i2<dependencies.length;i2++)remove_reaction(signal,dependencies[i2])}function update_effect(effect2){var _a8,previous_effect,was_updating_effect,previous_component_fn,previous_stack,teardown2,dep,flags2=effect2.f;if(!(flags2&DESTROYED)){set_signal_status(effect2,CLEAN);previous_effect=active_effect;was_updating_effect=is_updating_effect;active_effect=effect2;is_updating_effect=!0;if(dev_fallback_default){previous_component_fn=dev_current_component_function;set_dev_current_component_function(effect2.component_function);previous_stack=dev_stack;set_dev_stack(null!=(_a8=effect2.dev_stack)?_a8:dev_stack)}try{flags2&BLOCK_EFFECT?destroy_block_effect_children(effect2):destroy_effect_children(effect2);execute_effect_teardown(effect2);teardown2=update_reaction(effect2);effect2.teardown="function"==typeof teardown2?teardown2:null;effect2.wv=write_version;if(dev_fallback_default&&tracing_mode_flag&&effect2.f&DIRTY&&null!==effect2.deps)for(dep of effect2.deps)if(dep.set_during_effect){dep.wv=increment_write_version();dep.set_during_effect=!1}}finally{is_updating_effect=was_updating_effect;active_effect=previous_effect;if(dev_fallback_default){set_dev_current_component_function(previous_component_fn);set_dev_stack(previous_stack)}}}}async function tick(){if(async_mode_flag)return new Promise((f4=>{requestAnimationFrame((()=>f4()));setTimeout((()=>f4()))}));await Promise.resolve();flushSync()}function get(signal){var _a8,_b5,_c3,_d2,_e2,deps,reactions,derived3,parent,tracking,was_read,trace2,entry,last,value,is_derived=!!(signal.f&DERIVED);null==(_a8=captured_signals)||_a8.add(signal);if(null===active_reaction||untracking)is_derived&&null===signal.deps&&null===signal.effects&&(null===(parent=(derived3=signal).parent)||parent.f&UNOWNED||(derived3.f^=UNOWNED));else if(!(null!==active_effect&&active_effect.f&DESTROYED||(null==current_sources?void 0:current_sources.includes(signal)))){deps=active_reaction.deps;if(active_reaction.f&REACTION_IS_UPDATING){if(signal.rv<read_version){signal.rv=read_version;null===new_deps&&null!==deps&&deps[skipped_deps]===signal?skipped_deps++:null===new_deps?new_deps=[signal]:skip_reaction&&new_deps.includes(signal)||new_deps.push(signal)}}else{(null!=(_b5=active_reaction.deps)?_b5:active_reaction.deps=[]).push(signal);null===(reactions=signal.reactions)?signal.reactions=[active_reaction]:reactions.includes(active_reaction)||reactions.push(active_reaction)}}if(dev_fallback_default){if(current_async_effect){tracking=!!(current_async_effect.f&REACTION_IS_UPDATING);was_read=null==(_c3=current_async_effect.deps)?void 0:_c3.includes(signal);if(!tracking&&!untracking&&!was_read){await_reactivity_loss(signal.label);(trace2=get_stack("TracedAt"))&&console.warn(trace2)}}recent_async_deriveds.delete(signal);if(tracing_mode_flag&&!untracking&&null!==tracing_expressions&&null!==active_reaction&&tracing_expressions.reaction===active_reaction)if(signal.trace)signal.trace();else if(trace2=get_stack("TracedAt")){if(void 0===(entry=tracing_expressions.entries.get(signal))){entry={traces:[]};tracing_expressions.entries.set(signal,entry)}last=entry.traces[entry.traces.length-1];trace2.stack!==(null==last?void 0:last.stack)&&entry.traces.push(trace2)}}if(is_destroying_effect){if(old_values.has(signal))return old_values.get(signal);if(is_derived){value=(derived3=signal).v;(derived3.f&CLEAN||null===derived3.reactions)&&!depends_on_old_values(derived3)||(value=execute_derived(derived3));old_values.set(derived3,value);return value}}else if(is_derived){derived3=signal;if(null==(_d2=batch_values)?void 0:_d2.has(derived3))return batch_values.get(derived3);is_dirty(derived3)&&update_derived(derived3)}if(null==(_e2=batch_values)?void 0:_e2.has(signal))return batch_values.get(signal);if(signal.f&ERROR_VALUE)throw signal.v;return signal.v}function depends_on_old_values(derived3){if(derived3.v===UNINITIALIZED)return!0;if(null===derived3.deps)return!1;for(const dep of derived3.deps){if(old_values.has(dep))return!0;if(dep.f&DERIVED&&depends_on_old_values(dep))return!0}return!1}function untrack(fn){var previous_untracking=untracking;try{untracking=!0;return fn()}finally{untracking=previous_untracking}}function set_signal_status(signal,status){signal.f=signal.f&STATUS_MASK|status}function deep_read_state(value){if("object"==typeof value&&value&&!(value instanceof EventTarget))if(STATE_SYMBOL in value)deep_read(value);else if(!Array.isArray(value))for(let key3 in value){const prop2=value[key3];"object"==typeof prop2&&prop2&&STATE_SYMBOL in prop2&&deep_read(prop2)}}function deep_read(value,visited=new Set){if(!("object"!=typeof value||null===value||value instanceof EventTarget||visited.has(value))){visited.add(value);value instanceof Date&&value.getTime();for(let key3 in value)try{deep_read(value[key3],visited)}catch(e3){}const proto=get_prototype_of(value);if(proto!==Object.prototype&&proto!==Array.prototype&&proto!==Map.prototype&&proto!==Set.prototype&&proto!==Date.prototype){const descriptors=get_descriptors(proto);for(let key3 in descriptors){const get4=descriptors[key3].get;if(get4)try{get4.call(value)}catch(e3){}}}}}function create_event(event_name,dom,handler,options={}){function target_handler(event2){options.capture||handle_event_propagation.call(dom,event2);if(!event2.cancelBubble)return without_reactive_context((()=>null==handler?void 0:handler.call(this,event2)))}event_name.startsWith("pointer")||event_name.startsWith("touch")||"wheel"===event_name?queue_micro_task((()=>{dom.addEventListener(event_name,target_handler,options)})):dom.addEventListener(event_name,target_handler,options);return target_handler}function event(event_name,dom,handler,capture2,passive2){var options={capture:capture2,passive:passive2},target_handler=create_event(event_name,dom,handler,options);(dom===document.body||dom===window||dom===document||dom instanceof HTMLMediaElement)&&teardown((()=>{dom.removeEventListener(event_name,target_handler,options)}))}function delegate(events){var i2,fn;for(i2=0;i2<events.length;i2++)all_registered_events.add(events[i2]);for(fn of root_event_handles)fn(events)}function handle_event_propagation(event2){var _a8,handled_at,at_idx,handler_idx,previous_reaction,previous_effect,throw_error,other_errors,parent_element,delegated,handler_element=this,owner_document=handler_element.ownerDocument,event_name=event2.type,path2=(null==(_a8=event2.composedPath)?void 0:_a8.call(event2))||[],current_target=path2[0]||event2.target,path_idx=0;if(handled_at=event2==event2&&event2.__root){if(-1!==(at_idx=path2.indexOf(handled_at))&&(handler_element===document||handler_element===window)){event2.__root=handler_element;return}if(-1===(handler_idx=path2.indexOf(handler_element)))return;at_idx<=handler_idx&&(path_idx=at_idx)}if((current_target=path2[path_idx]||event2.target)!==handler_element){define_property(event2,"currentTarget",{configurable:!0,get:()=>current_target||owner_document});previous_reaction=active_reaction;previous_effect=active_effect;set_active_reaction(null);set_active_effect(null);try{other_errors=[];for(;null!==current_target;){parent_element=current_target.assignedSlot||current_target.parentNode||current_target.host||null;try{if(null!=(delegated=current_target["__"+event_name])&&(!current_target.disabled||event2.target===current_target))if(is_array(delegated)){var[fn,...data]=delegated;fn.apply(current_target,[event2,...data])}else delegated.call(current_target,event2)}catch(error){throw_error?other_errors.push(error):throw_error=error}if(event2.cancelBubble||parent_element===handler_element||null===parent_element)break;current_target=parent_element}if(throw_error){for(let error of other_errors)queueMicrotask((()=>{throw error}));throw throw_error}}finally{event2.__root=handler_element;delete event2.currentTarget;set_active_reaction(previous_reaction);set_active_effect(previous_effect)}}}function create_fragment_from_html(html2){var elem=document.createElement("template");elem.innerHTML=html2.replaceAll("<!>","\x3c!----\x3e");return elem.content}function assign_nodes(start,end){var effect2=active_effect;if(null===effect2.nodes_start){effect2.nodes_start=start;effect2.nodes_end=end}}function from_html(content,flags2){var node,is_fragment=!!(flags2&TEMPLATE_FRAGMENT),use_import_node=!!(flags2&TEMPLATE_USE_IMPORT_NODE),has_start=!content.startsWith("<!>");return()=>{var clone3;if(hydrating){assign_nodes(hydrate_node,null);return hydrate_node}if(void 0===node){node=create_fragment_from_html(has_start?content:"<!>"+content);is_fragment||(node=get_first_child(node))}clone3=use_import_node||is_firefox?document.importNode(node,!0):node.cloneNode(!0);is_fragment?assign_nodes(get_first_child(clone3),clone3.lastChild):assign_nodes(clone3,clone3);return clone3}}function text(value=""){var t3,node;if(!hydrating){assign_nodes(t3=create_text(value+""),t3);return t3}if((node=hydrate_node).nodeType!==TEXT_NODE){node.before(node=create_text());set_hydrate_node(node)}assign_nodes(node,node);return node}function comment(){var frag,start,anchor;if(hydrating){assign_nodes(hydrate_node,null);return hydrate_node}frag=document.createDocumentFragment();start=document.createComment("");anchor=create_text();frag.append(start,anchor);assign_nodes(start,anchor);return frag}function append(anchor,dom){if(hydrating){active_effect.nodes_end=hydrate_node;hydrate_next()}else null!==anchor&&anchor.before(dom)}function is_passive_event(name){return PASSIVE_EVENTS.includes(name)}function set_text(text2,value){var _a8,str=null==value?"":"object"==typeof value?value+"":value;if(str!==(null!=(_a8=text2.__t)?_a8:text2.__t=text2.nodeValue)){text2.__t=str;text2.nodeValue=str+""}}function mount(component2,options){return _mount(component2,options)}function _mount(Component,{target,anchor,props={},events,context:context2,intro=!0}){var registered_events,event_handle,component2,unmount2;init_operations();registered_events=new Set;event_handle=events2=>{var i2,event_name,passive2,n3;for(i2=0;i2<events2.length;i2++){event_name=events2[i2];if(!registered_events.has(event_name)){registered_events.add(event_name);passive2=is_passive_event(event_name);target.addEventListener(event_name,handle_event_propagation,{passive:passive2});if(void 0===(n3=document_listeners.get(event_name))){document.addEventListener(event_name,handle_event_propagation,{passive:passive2});document_listeners.set(event_name,1)}else document_listeners.set(event_name,n3+1)}}};event_handle(array_from(all_registered_events));root_event_handles.add(event_handle);component2=void 0;unmount2=component_root((()=>{var anchor_node=null!=anchor?anchor:target.appendChild(create_text());boundary(anchor_node,{pending:()=>{}},(anchor_node2=>{if(context2){push({});component_context.c=context2}events&&(props.$$events=events);hydrating&&assign_nodes(anchor_node2,null);component2=Component(anchor_node2,props)||{};if(hydrating){active_effect.nodes_end=hydrate_node;if(null===hydrate_node||hydrate_node.nodeType!==COMMENT_NODE||hydrate_node.data!==HYDRATION_END){hydration_mismatch();throw HYDRATION_ERROR}}context2&&pop()}));return()=>{var _a8,event_name,n3;for(event_name of registered_events){target.removeEventListener(event_name,handle_event_propagation);n3=document_listeners.get(event_name);if(0==--n3){document.removeEventListener(event_name,handle_event_propagation);document_listeners.delete(event_name)}else document_listeners.set(event_name,n3)}root_event_handles.delete(event_handle);anchor_node!==anchor&&(null==(_a8=anchor_node.parentNode)||_a8.removeChild(anchor_node))}}));mounted_components.set(component2,unmount2);return component2}function unmount(component2,options){const fn=mounted_components.get(component2);if(fn){mounted_components.delete(component2);return fn(options)}dev_fallback_default&&(STATE_SYMBOL in component2?state_proxy_unmount():lifecycle_double_unmount());return Promise.resolve()}function snippet(node,get_snippet,...args){var branches=new BranchManager(node);block((()=>{var _a8;const snippet2=null!=(_a8=get_snippet())?_a8:null;dev_fallback_default&&null==snippet2&&invalid_snippet();branches.ensure(snippet2,snippet2&&(anchor=>snippet2(anchor,...args)))}),EFFECT_TRANSPARENT)}function onMount(fn){null===component_context&&lifecycle_outside_component("onMount");legacy_mode_flag&&null!==component_context.l?init_update_callbacks(component_context).m.push(fn):user_effect((()=>{const cleanup=untrack(fn);if("function"==typeof cleanup)return cleanup}))}function onDestroy(fn){null===component_context&&lifecycle_outside_component("onDestroy");onMount((()=>()=>untrack(fn)))}function init_update_callbacks(context2){var _a8,l2=context2.l;return null!=(_a8=l2.u)?_a8:l2.u={a:[],b:[],m:[]}}function register_style(hash3,style){var styles=all_styles.get(hash3);if(!styles){styles=new Set;all_styles.set(hash3,styles)}styles.add(style)}function if_block(node,fn,elseif=!1){function update_branch(condition,fn2){if(hydrating&&condition===(read_hydration_instruction(node)===HYDRATION_START_ELSE)){var anchor=skip_nodes();set_hydrate_node(anchor);branches.anchor=anchor;set_hydrating(!1);branches.ensure(condition,fn2);set_hydrating(!0)}else branches.ensure(condition,fn2)}var branches;hydrating&&hydrate_next();branches=new BranchManager(node);block((()=>{var has_branch=!1;fn(((fn2,flag=!0)=>{has_branch=!0;update_branch(flag,fn2)}));has_branch||update_branch(!1,null)}),elseif?EFFECT_TRANSPARENT:0)}function index(_,i2){return i2}function pause_effects(state2,items,controlled_anchor){var i2,is_controlled,parent_node,items_map=state2.items,transitions=[],length=items.length;for(i2=0;i2<length;i2++)pause_children(items[i2].e,transitions,!0);if(is_controlled=length>0&&0===transitions.length&&null!==controlled_anchor){clear_text_content(parent_node=controlled_anchor.parentNode);parent_node.append(controlled_anchor);items_map.clear();link(state2,items[0].prev,items[length-1].next)}run_out_transitions(transitions,(()=>{var i3,item;for(i3=0;i3<length;i3++){item=items[i3];if(!is_controlled){items_map.delete(item.k);link(state2,item.prev,item.next)}destroy_effect(item.e,!is_controlled)}}))}function each(node,flags2,get_collection,get_key,render_fn,fallback_fn=null){function commit(){reconcile(each_effect,array,state2,offscreen_items,anchor,render_fn,flags2,get_key,get_collection);null!==fallback_fn&&(0===array.length?fallback2?resume_effect(fallback2):fallback2=branch((()=>fallback_fn(anchor))):null!==fallback2&&pause_effect(fallback2,(()=>{fallback2=null})))}var parent_node,fallback2,was_empty,offscreen_items,each_array,array,each_effect,anchor=node,state2={flags:flags2,items:new Map,first:null};if(flags2&EACH_IS_CONTROLLED){parent_node=node;anchor=hydrating?set_hydrate_node(get_first_child(parent_node)):parent_node.appendChild(create_text())}hydrating&&hydrate_next();fallback2=null;was_empty=!1;offscreen_items=new Map;each_array=derived_safe_equal((()=>{var collection=get_collection();return is_array(collection)?collection:null==collection?[]:array_from(collection)}));block((()=>{var _a8,length,prev,item,i2,value,key3,keys3,batch,existing;null!=each_effect||(each_effect=active_effect);length=(array=get(each_array)).length;if(was_empty&&0===length)return;was_empty=0===length;let mismatch=!1;if(hydrating&&read_hydration_instruction(anchor)===HYDRATION_START_ELSE!=(0===length)){set_hydrate_node(anchor=skip_nodes());set_hydrating(!1);mismatch=!0}if(hydrating){prev=null;for(i2=0;i2<length;i2++){if(hydrate_node.nodeType===COMMENT_NODE&&hydrate_node.data===HYDRATION_END){anchor=hydrate_node;mismatch=!0;set_hydrating(!1);break}value=array[i2];key3=get_key(value,i2);item=create_item(hydrate_node,state2,prev,null,value,key3,i2,render_fn,flags2,get_collection);state2.items.set(key3,item);prev=item}length>0&&set_hydrate_node(skip_nodes())}if(hydrating)0===length&&fallback_fn&&(fallback2=branch((()=>fallback_fn(anchor))));else if(should_defer_append()){keys3=new Set;batch=current_batch;for(i2=0;i2<length;i2+=1){value=array[i2];key3=get_key(value,i2);if(existing=null!=(_a8=state2.items.get(key3))?_a8:offscreen_items.get(key3))flags2&(EACH_ITEM_REACTIVE|EACH_INDEX_REACTIVE)&&update_item(existing,value,i2,flags2);else{item=create_item(null,state2,null,null,value,key3,i2,render_fn,flags2,get_collection,!0);offscreen_items.set(key3,item)}keys3.add(key3)}for(const[key4,item2]of state2.items)keys3.has(key4)||batch.skipped_effects.add(item2.e);batch.add_callback(commit)}else commit();mismatch&&set_hydrating(!0);get(each_array)}));hydrating&&(anchor=hydrate_node)}function reconcile(each_effect,array,state2,offscreen_items,anchor,render_fn,flags2,get_key,get_collection){var _a8,_b5,_c3,_d2,seen,to_animate,value,key3,item,i2,pending3,next2,start,j2,a2,b3,to_destroy,destroy_length,controlled_anchor,unused,is_animated=!!(flags2&EACH_IS_ANIMATED),should_update=!!(flags2&(EACH_ITEM_REACTIVE|EACH_INDEX_REACTIVE)),length=array.length,items=state2.items,current=state2.first,prev=null,matched=[],stashed=[];if(is_animated)for(i2=0;i2<length;i2+=1){key3=get_key(value=array[i2],i2);if(void 0!==(item=items.get(key3))){null==(_a8=item.a)||_a8.measure();(null!=to_animate?to_animate:to_animate=new Set).add(item)}}for(i2=0;i2<length;i2+=1){key3=get_key(value=array[i2],i2);if(void 0!==(item=items.get(key3))){should_update&&update_item(item,value,i2,flags2);if(item.e.f&INERT){resume_effect(item.e);if(is_animated){null==(_b5=item.a)||_b5.unfix();(null!=to_animate?to_animate:to_animate=new Set).delete(item)}}if(item!==current){if(void 0!==seen&&seen.has(item)){if(matched.length<stashed.length){prev=(start=stashed[0]).prev;a2=matched[0];b3=matched[matched.length-1];for(j2=0;j2<matched.length;j2+=1)move(matched[j2],start,anchor);for(j2=0;j2<stashed.length;j2+=1)seen.delete(stashed[j2]);link(state2,a2.prev,b3.next);link(state2,prev,a2);link(state2,b3,start);current=start;prev=b3;i2-=1;matched=[];stashed=[]}else{seen.delete(item);move(item,current,anchor);link(state2,item.prev,item.next);link(state2,item,null===prev?state2.first:prev.next);link(state2,prev,item);prev=item}continue}matched=[];stashed=[];for(;null!==current&&current.k!==key3;){current.e.f&INERT||(null!=seen?seen:seen=new Set).add(current);stashed.push(current);current=current.next}if(null===current)continue;item=current}matched.push(item);prev=item;current=item.next}else{if(void 0!==(pending3=offscreen_items.get(key3))){offscreen_items.delete(key3);items.set(key3,pending3);next2=prev?prev.next:current;link(state2,prev,pending3);link(state2,pending3,next2);move(pending3,next2,anchor);prev=pending3}else prev=create_item(current?current.e.nodes_start:anchor,state2,prev,null===prev?state2.first:prev.next,value,key3,i2,render_fn,flags2,get_collection);items.set(key3,prev);matched=[];stashed=[];current=prev.next}}if(null!==current||void 0!==seen){to_destroy=void 0===seen?[]:array_from(seen);for(;null!==current;){current.e.f&INERT||to_destroy.push(current);current=current.next}if((destroy_length=to_destroy.length)>0){controlled_anchor=flags2&EACH_IS_CONTROLLED&&0===length?anchor:null;if(is_animated){for(i2=0;i2<destroy_length;i2+=1)null==(_c3=to_destroy[i2].a)||_c3.measure();for(i2=0;i2<destroy_length;i2+=1)null==(_d2=to_destroy[i2].a)||_d2.fix()}pause_effects(state2,to_destroy,controlled_anchor)}}is_animated&&queue_micro_task((()=>{var _a9;if(void 0!==to_animate)for(item of to_animate)null==(_a9=item.a)||_a9.apply()}));each_effect.first=state2.first&&state2.first.e;each_effect.last=prev&&prev.e;for(unused of offscreen_items.values())destroy_effect(unused.e);offscreen_items.clear()}function update_item(item,value,index6,type){type&EACH_ITEM_REACTIVE&&internal_set(item.v,value);type&EACH_INDEX_REACTIVE?internal_set(item.i,index6):item.i=index6}function create_item(anchor,state2,prev,next2,value,key3,index6,render_fn,flags2,get_collection,deferred2){var item,previous_each_item=current_each_item,reactive2=!!(flags2&EACH_ITEM_REACTIVE),v2=reactive2?flags2&EACH_ITEM_IMMUTABLE?source(value):mutable_source(value,!1,!1):value,i2=flags2&EACH_INDEX_REACTIVE?source(index6):index6;dev_fallback_default&&reactive2&&(v2.trace=()=>{var collection_index="number"==typeof i2?index6:i2.v;get_collection()[collection_index]});current_each_item=item={i:i2,v:v2,k:key3,a:null,e:null,prev,next:next2};try{null===anchor&&document.createDocumentFragment().append(anchor=create_text());item.e=branch((()=>render_fn(anchor,v2,i2,get_collection)),hydrating);item.e.prev=prev&&prev.e;item.e.next=next2&&next2.e;if(null===prev)deferred2||(state2.first=item);else{prev.next=item;prev.e.next=item.e}if(null!==next2){next2.prev=item;next2.e.prev=item.e}return item}finally{current_each_item=previous_each_item}}function move(item,next2,anchor){for(var next_node,end=item.next?item.next.e.nodes_start:anchor,dest=next2?next2.e.nodes_start:anchor,node=item.e.nodes_start;null!==node&&node!==end;){next_node=get_next_sibling(node);dest.before(node);node=next_node}}function link(state2,prev,next2){if(null===prev)state2.first=next2;else{prev.next=next2;prev.e.next=next2&&next2.e}if(null!==next2){next2.prev=prev;next2.e.prev=prev&&prev.e}}function append_styles(anchor,css){effect((()=>{var _a8,root40=anchor.getRootNode(),target=root40.host?root40:null!=(_a8=root40.head)?_a8:root40.ownerDocument.head;if(!target.querySelector("#"+css.hash)){const style=document.createElement("style");style.id=css.hash;style.textContent=css.code;target.appendChild(style);dev_fallback_default&&register_style(css.hash,style)}}))}function r(e3){var t3,f4,o2,n3="";if("string"==typeof e3||"number"==typeof e3)n3+=e3;else if("object"==typeof e3)if(Array.isArray(e3)){o2=e3.length;for(t3=0;t3<o2;t3++)e3[t3]&&(f4=r(e3[t3]))&&(n3&&(n3+=" "),n3+=f4)}else for(f4 in e3)e3[f4]&&(n3&&(n3+=" "),n3+=f4);return n3}function clsx(){for(var e3,t3,f4=0,n3="",o2=arguments.length;f4<o2;f4++)(e3=arguments[f4])&&(t3=r(e3))&&(n3&&(n3+=" "),n3+=t3);return n3}function clsx2(value){return"object"==typeof value?clsx(value):null!=value?value:""}function to_class(value,hash3,directives){var key3,len,a2,b3,classname=null==value?"":""+value;hash3&&(classname=classname?classname+" "+hash3:hash3);if(directives)for(key3 in directives)if(directives[key3])classname=classname?classname+" "+key3:key3;else if(classname.length){len=key3.length;a2=0;for(;(a2=classname.indexOf(key3,a2))>=0;){b3=a2+len;0!==a2&&!whitespace.includes(classname[a2-1])||b3!==classname.length&&!whitespace.includes(classname[b3])?a2=b3:classname=(0===a2?"":classname.substring(0,a2))+classname.substring(b3+1)}}return""===classname?null:classname}function set_class(dom,is_html,value,hash3,prev_classes,next_classes){var next_class_name,key3,is_present,prev=dom.__className;if(hydrating||prev!==value||void 0===prev){next_class_name=to_class(value,hash3,next_classes);hydrating&&next_class_name===dom.getAttribute("class")||(null==next_class_name?dom.removeAttribute("class"):is_html?dom.className=next_class_name:dom.setAttribute("class",next_class_name));dom.__className=value}else if(next_classes&&prev_classes!==next_classes)for(key3 in next_classes){is_present=!!next_classes[key3];null!=prev_classes&&is_present===!!prev_classes[key3]||dom.classList.toggle(key3,is_present)}return next_classes}function select_option(select,value,mounting=!1){var option;if(select.multiple){if(null==value)return;if(!is_array(value))return select_multiple_invalid_value();for(option of select.options)option.selected=value.includes(get_option_value(option))}else{for(option of select.options)if(is(get_option_value(option),value)){option.selected=!0;return}mounting&&void 0===value||(select.selectedIndex=-1)}}function init_select(select){var observer=new MutationObserver((()=>{select_option(select,select.__value)}));observer.observe(select,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["value"]});teardown((()=>{observer.disconnect()}))}function bind_select_value(select,get4,set2=get4){var batches2=new WeakSet,mounting=!0;listen_to_event_and_reset_event(select,"change",(is_reset=>{var _a8,value,selected_option,query3=is_reset?"[selected]":":checked";value=select.multiple?[].map.call(select.querySelectorAll(query3),get_option_value):(selected_option=null!=(_a8=select.querySelector(query3))?_a8:select.querySelector("option:not([disabled])"))&&get_option_value(selected_option);set2(value);null!==current_batch&&batches2.add(current_batch)}));effect((()=>{var _a8,batch,selected_option,value=get4();if(select===document.activeElement){batch=null!=(_a8=previous_batch)?_a8:current_batch;if(batches2.has(batch))return}select_option(select,value,mounting);if(mounting&&void 0===value&&null!==(selected_option=select.querySelector(":checked"))){value=get_option_value(selected_option);set2(value)}select.__value=value;mounting=!1}));init_select(select)}function get_option_value(option){return"__value"in option?option.__value:option.value}function remove_input_defaults(input){var already_removed,remove_defaults;if(hydrating){already_removed=!1;remove_defaults=()=>{var value,checked;if(!already_removed){already_removed=!0;if(input.hasAttribute("value")){value=input.value;set_attribute2(input,"value",null);input.value=value}if(input.hasAttribute("checked")){checked=input.checked;set_attribute2(input,"checked",null);input.checked=checked}}};input.__on_r=remove_defaults;queue_micro_task(remove_defaults);add_form_reset_listener()}}function set_value(element2,value){var attributes=get_attributes(element2);attributes.value!==(attributes.value=null!=value?value:void 0)&&(element2.value!==value||0===value&&"PROGRESS"===element2.nodeName)&&(element2.value=null!=value?value:"")}function set_attribute2(element2,attribute,value,skip_warning){var attributes=get_attributes(element2);if(hydrating){attributes[attribute]=element2.getAttribute(attribute);if("src"===attribute||"srcset"===attribute||"href"===attribute&&"LINK"===element2.nodeName){skip_warning||check_src_in_dev_hydration(element2,attribute,null!=value?value:"");return}}if(attributes[attribute]!==(attributes[attribute]=value)){"loading"===attribute&&(element2[LOADING_ATTR_SYMBOL]=value);null==value?element2.removeAttribute(attribute):"string"!=typeof value&&get_setters(element2).includes(attribute)?element2[attribute]=value:element2.setAttribute(attribute,value)}}function get_attributes(element2){var _a8;return null!=(_a8=element2.__attributes)?_a8:element2.__attributes={[IS_CUSTOM_ELEMENT]:element2.nodeName.includes("-"),[IS_HTML]:element2.namespaceURI===NAMESPACE_HTML}}function get_setters(element2){var descriptors,proto,element_proto,key3,cache_key=element2.getAttribute("is")||element2.nodeName,setters=setters_cache.get(cache_key);if(setters)return setters;setters_cache.set(cache_key,setters=[]);proto=element2;element_proto=Element.prototype;for(;element_proto!==proto;){descriptors=get_descriptors(proto);for(key3 in descriptors)descriptors[key3].set&&setters.push(key3);proto=get_prototype_of(proto)}return setters}function check_src_in_dev_hydration(element2,attribute,value){var _a8;dev_fallback_default&&("srcset"===attribute&&srcset_url_equal(element2,value)||src_url_equal(null!=(_a8=element2.getAttribute(attribute))?_a8:"",value)||hydration_attribute_changed(attribute,element2.outerHTML.replace(element2.innerHTML,element2.innerHTML&&"..."),String(value)))}function src_url_equal(element_src,url){return element_src===url||new URL(element_src,document.baseURI).href===new URL(url,document.baseURI).href}function split_srcset(srcset){return srcset.split(",").map((src=>src.trim().split(" ").filter(Boolean)))}function srcset_url_equal(element2,srcset){var element_urls=split_srcset(element2.srcset),urls=split_srcset(srcset);return urls.length===element_urls.length&&urls.every((([url,width],i2)=>width===element_urls[i2][1]&&(src_url_equal(element_urls[i2][0],url)||src_url_equal(url,element_urls[i2][0]))))}function bind_value(input,get4,set2=get4){var batches2=new WeakSet;listen_to_event_and_reset_event(input,"input",(async is_reset=>{var value,start,end,length,new_length;dev_fallback_default&&"checkbox"===input.type&&bind_invalid_checkbox_value();value=is_reset?input.defaultValue:input.value;value=is_numberlike_input(input)?to_number(value):value;set2(value);null!==current_batch&&batches2.add(current_batch);await tick();if(value!==(value=get4())){start=input.selectionStart;end=input.selectionEnd;length=input.value.length;input.value=null!=value?value:"";if(null!==end){new_length=input.value.length;if(start===end&&end===length&&new_length>length){input.selectionStart=new_length;input.selectionEnd=new_length}else{input.selectionStart=start;input.selectionEnd=Math.min(end,new_length)}}}}));if(hydrating&&input.defaultValue!==input.value||null==untrack(get4)&&input.value){set2(is_numberlike_input(input)?to_number(input.value):input.value);null!==current_batch&&batches2.add(current_batch)}render_effect((()=>{var _a8,value,batch;dev_fallback_default&&"checkbox"===input.type&&bind_invalid_checkbox_value();value=get4();if(input===document.activeElement){batch=null!=(_a8=previous_batch)?_a8:current_batch;if(batches2.has(batch))return}is_numberlike_input(input)&&value===to_number(input.value)||("date"!==input.type||value||input.value)&&value!==input.value&&(input.value=null!=value?value:"")}))}function bind_group(inputs,group_index,input,get4,set2=get4){var _a8,index6,is_checkbox="checkbox"===input.getAttribute("type"),binding_group=inputs;let hydration_mismatch2=!1;if(null!==group_index)for(index6 of group_index)binding_group=null!=(_a8=binding_group[index6])?_a8:binding_group[index6]=[];binding_group.push(input);listen_to_event_and_reset_event(input,"change",(()=>{var value=input.__value;is_checkbox&&(value=get_binding_group_value(binding_group,value,input.checked));set2(value)}),(()=>set2(is_checkbox?[]:null)));render_effect((()=>{var value=get4();if(hydrating&&input.defaultChecked!==input.checked)hydration_mismatch2=!0;else if(is_checkbox){value=value||[];input.checked=value.includes(input.__value)}else input.checked=is(input.__value,value)}));teardown((()=>{var index7=binding_group.indexOf(input);-1!==index7&&binding_group.splice(index7,1)}));if(!pending2.has(binding_group)){pending2.add(binding_group);queue_micro_task((()=>{binding_group.sort(((a2,b3)=>4===a2.compareDocumentPosition(b3)?-1:1));pending2.delete(binding_group)}))}queue_micro_task((()=>{var value,hydration_input;if(hydration_mismatch2){value=is_checkbox?get_binding_group_value(binding_group,value,input.checked):null==(hydration_input=binding_group.find((input2=>input2.checked)))?void 0:hydration_input.__value;set2(value)}}))}function bind_checked(input,get4,set2=get4){listen_to_event_and_reset_event(input,"change",(is_reset=>{var value=is_reset?input.defaultChecked:input.checked;set2(value)}));(hydrating&&input.defaultChecked!==input.checked||null==untrack(get4))&&set2(input.checked);render_effect((()=>{var value=get4();input.checked=Boolean(value)}))}function get_binding_group_value(group,__value,checked){var i2,value=new Set;for(i2=0;i2<group.length;i2+=1)group[i2].checked&&value.add(group[i2].__value);checked||value.delete(__value);return Array.from(value)}function is_numberlike_input(input){var type=input.type;return"number"===type||"range"===type}function to_number(value){return""===value?null:+value}function is_bound_this(bound_value,element_or_component){return bound_value===element_or_component||(null==bound_value?void 0:bound_value[STATE_SYMBOL])===element_or_component}function bind_this(element_or_component={},update2,get_value,get_parts){effect((()=>{var old_parts,parts;render_effect((()=>{old_parts=parts;parts=(null==get_parts?void 0:get_parts())||[];untrack((()=>{if(element_or_component!==get_value(...parts)){update2(element_or_component,...parts);old_parts&&is_bound_this(get_value(...old_parts),element_or_component)&&update2(null,...old_parts)}}))}));return()=>{queue_micro_task((()=>{parts&&is_bound_this(get_value(...parts),element_or_component)&&update2(null,...parts)}))}}));return element_or_component}function bind_property(property,event_name,element2,set2,get4){var handler=()=>{set2(element2[property])};element2.addEventListener(event_name,handler);get4?render_effect((()=>{element2[property]=get4()})):handler();element2!==document.body&&element2!==window&&element2!==document||teardown((()=>{element2.removeEventListener(event_name,handler)}))}function init(immutable=!1){const context2=component_context,callbacks=context2.l.u;if(!callbacks)return;let props=()=>deep_read_state(context2.s);if(immutable){let version2=0,prev={};const d4=derived((()=>{let changed=!1;const props2=context2.s;for(const key3 in props2)if(props2[key3]!==prev[key3]){prev[key3]=props2[key3];changed=!0}changed&&version2++;return version2}));props=()=>get(d4)}callbacks.b.length&&user_pre_effect((()=>{observe_all(context2,props);run_all(callbacks.b)}));user_effect((()=>{const fns=untrack((()=>callbacks.m.map(run)));return()=>{for(const fn of fns)"function"==typeof fn&&fn()}}));callbacks.a.length&&user_effect((()=>{observe_all(context2,props);run_all(callbacks.a)}))}function observe_all(context2,props){if(context2.l.s)for(const signal of context2.l.s)get(signal);props()}function subscribe_to_store(store,run3,invalidate){if(null==store){run3(void 0);invalidate&&invalidate(void 0);return noop2}const unsub=untrack((()=>store.subscribe(run3,invalidate)));return unsub.unsubscribe?()=>unsub.unsubscribe():unsub}function writable(value,start=noop2){function set2(new_value){if(safe_not_equal(value,new_value)){value=new_value;if(stop){const run_queue=!subscriber_queue.length;for(const subscriber of subscribers){subscriber[1]();subscriber_queue.push(subscriber,value)}if(run_queue){for(let i2=0;i2<subscriber_queue.length;i2+=2)subscriber_queue[i2][0](subscriber_queue[i2+1]);subscriber_queue.length=0}}}}function update2(fn){set2(fn(value))}let stop=null;const subscribers=new Set;return{set:set2,update:update2,subscribe:function subscribe2(run3,invalidate=noop2){const subscriber=[run3,invalidate];subscribers.add(subscriber);1===subscribers.size&&(stop=start(set2,update2)||noop2);run3(value);return()=>{subscribers.delete(subscriber);if(0===subscribers.size&&stop){stop();stop=null}}}}}function get2(store){let value;subscribe_to_store(store,(_=>value=_))();return value}function store_get(store,store_name,stores){var _a8,is_synchronous_callback;const entry=null!=(_a8=stores[store_name])?_a8:stores[store_name]={store:null,source:mutable_source(void 0),unsubscribe:noop2};dev_fallback_default&&(entry.source.label=store_name);if(entry.store!==store&&!(IS_UNMOUNTED in stores)){entry.unsubscribe();entry.store=null!=store?store:null;if(null==store){entry.source.v=void 0;entry.unsubscribe=noop2}else{is_synchronous_callback=!0;entry.unsubscribe=subscribe_to_store(store,(v2=>{is_synchronous_callback?entry.source.v=v2:set(entry.source,v2)}));is_synchronous_callback=!1}}return store&&IS_UNMOUNTED in stores?get2(store):get(entry.source)}function setup_stores(){const stores={};return[stores,function cleanup(){teardown((()=>{for(var store_name in stores)stores[store_name].unsubscribe();define_property(stores,IS_UNMOUNTED,{enumerable:!1,value:!0})}))}]}function capture_store_binding(fn){var previous_is_store_binding=is_store_binding;try{is_store_binding=!1;return[fn(),is_store_binding]}finally{is_store_binding=previous_is_store_binding}}function spread_props(...props){return new Proxy({props},spread_props_handler)}function prop(props,key3,flags2,fallback2){var _a8,_b5,setter,is_entry_props,initial_value,is_store_sub,getter,legacy_parent,overridden,d4,parent_effect,runes=!legacy_mode_flag||!!(flags2&PROPS_IS_RUNES),bindable=!!(flags2&PROPS_IS_BINDABLE),lazy=!!(flags2&PROPS_IS_LAZY_INITIAL),fallback_value=fallback2,fallback_dirty=!0,get_fallback=()=>{if(fallback_dirty){fallback_dirty=!1;fallback_value=lazy?untrack(fallback2):fallback2}return fallback_value};if(bindable){is_entry_props=STATE_SYMBOL in props||LEGACY_PROPS in props;setter=null!=(_b5=null==(_a8=get_descriptor(props,key3))?void 0:_a8.set)?_b5:is_entry_props&&key3 in props?v2=>props[key3]=v2:void 0}is_store_sub=!1;bindable?[initial_value,is_store_sub]=capture_store_binding((()=>props[key3])):initial_value=props[key3];if(void 0===initial_value&&void 0!==fallback2){initial_value=get_fallback();if(setter){runes&&props_invalid_value(key3);setter(initial_value)}}getter=runes?()=>{var value=props[key3];if(void 0===value)return get_fallback();fallback_dirty=!0;return value}:()=>{var value=props[key3];void 0!==value&&(fallback_value=void 0);return void 0===value?fallback_value:value};if(runes&&!(flags2&PROPS_IS_UPDATED))return getter;if(setter){legacy_parent=props.$$legacy;return function(value,mutation){if(arguments.length>0){runes&&mutation&&!legacy_parent&&!is_store_sub||setter(mutation?getter():value);return value}return getter()}}overridden=!1;d4=(flags2&PROPS_IS_IMMUTABLE?derived:derived_safe_equal)((()=>{overridden=!1;return getter()}));dev_fallback_default&&(d4.label=key3);bindable&&get(d4);parent_effect=active_effect;return function(value,mutation){if(arguments.length>0){const new_value=mutation?get(d4):runes&&bindable?proxy(value):value;set(d4,new_value);overridden=!0;void 0!==fallback_value&&(fallback_value=new_value);return value}return is_destroying_effect&&overridden||parent_effect.f&DESTROYED?d4.v:get(d4)}}function expandKeywords(message,lang,recurseLimit=10){if(recurseLimit<=0){Logger("ExpandKeywords hit the recursion limit, returning the current state. but this is not expected. May recursive referenced.");return message}const keywords=Object.entries(message).map((([key3,value])=>[key3,value[lang]])).map((([key3,value])=>[`${key3.startsWith("K.")?key3.substring(2):key3}`,value])).map((([key3,value])=>[[`%{${key3}}`,value]])).flat().sort(((a2,b3)=>{var _a8,_b5,_c3,_d2;return(null!=(_b5=null==(_a8=a2[1])?void 0:_a8.length)?_b5:0)-(null!=(_d2=null==(_c3=b3[1])?void 0:_c3.length)?_d2:0)})),ret={...message};let isChanged=!1;for(const key3 of Object.keys(message))if(lang in ret[key3])for(const[keyword,replacement]of keywords)if(ret[key3][lang].includes(keyword)){ret[key3][lang]=ret[key3][lang].split(keyword).join(replacement);isChanged=!0}return isChanged?expandKeywords(ret,lang,recurseLimit--):ret}function __onMissingTranslation(callback){__onMissingTranslations=callback}function setLang(lang){if(lang!==currentLang){currentLang=lang;msgCache.clear()}}function _getMessage(key3,lang){var _a8;if(""==key3.trim())return key3;const msgs=null!=(_a8=allMessages[key3])?_a8:void 0;""==lang&&(lang="def");let msg=null==msgs?void 0:msgs[lang];if(!msg){if(-1===missingTranslations.indexOf(key3)){__onMissingTranslations(key3);missingTranslations.push(key3)}msg=null==msgs?void 0:msgs.def}return null!=msg?msg:key3}function getMessage(key3){if(msgCache.has(key3))return msgCache.get(key3);const msg=_getMessage(key3,currentLang);msgCache.set(key3,msg);return msg}function $t(message,lang){return void 0!==lang?_getMessage(message,lang):getMessage(message)}function $msg(key3,params={},lang){let msg=$t(key3,lang);for(const[placeholder,value]of Object.entries(params)){const regex=new RegExp(`\\\${${placeholder}}`,"g");msg=msg.replace(regex,value)}return msg}function LogPane($$anchor,$$props){function updateLog(logs){const e3=logs.value;if(!get(suspended)){set(messages,[...e3],!0);setTimeout((()=>{scroll&&(scroll.scrollTop=scroll.scrollHeight)}),10)}}var div,div_1,div_2,label2,input,span,text2,label_1,input_1,span_1,text_1,label_2,input_2,span_2,text_2,div_3;push($$props,!0);append_styles($$anchor,$$css);let unsubscribe2,scroll,messages=state(proxy([])),wrapRight=state(!1),autoScroll=state(!0),suspended=state(!1);onMount((async()=>{const _logMessages=reactive((()=>logMessages.value));_logMessages.onChanged(updateLog);Logger($msg("logPane.logWindowOpened",{},currentLang));unsubscribe2=()=>_logMessages.offChanged(updateLog)}));onDestroy((()=>{unsubscribe2&&unsubscribe2()}));div_1=child(div=root());div_2=child(div_1);label2=child(div_2);remove_input_defaults(input=child(label2));span=sibling(input,2);text2=child(span,!0);reset(span);reset(label2);remove_input_defaults(input_1=child(label_1=sibling(label2,2)));span_1=sibling(input_1,2);text_1=child(span_1,!0);reset(span_1);reset(label_1);remove_input_defaults(input_2=child(label_2=sibling(label_1,2)));span_2=sibling(input_2,2);text_2=child(span_2,!0);reset(span_2);reset(label_2);sibling(label_2,4).__click=[on_click,function closeDialogue(){$$props.close()}];reset(div_2);reset(div_1);each(div_3=sibling(div_1,2),21,(()=>get(messages)),index,(($$anchor2,line)=>{var text_3,pre=root_1();let classes;text_3=child(pre,!0);reset(pre);template_effect(($0=>{classes=set_class(pre,1,"svelte-o3lsbg",null,classes,$0);set_text(text_3,get(line))}),[()=>({"wrap-right":get(wrapRight)})]);append($$anchor2,pre)}));reset(div_3);bind_this(div_3,($$value=>scroll=$$value),(()=>scroll));reset(div);template_effect((($0,$1,$2)=>{set_text(text2,$0);set_text(text_1,$1);set_text(text_2,$2)}),[()=>$msg("logPane.wrap",{},currentLang),()=>$msg("logPane.autoScroll",{},currentLang),()=>$msg("logPane.pause",{},currentLang)]);bind_checked(input,(()=>get(wrapRight)),($$value=>set(wrapRight,$$value)));bind_checked(input_1,(()=>get(autoScroll)),($$value=>set(autoScroll,$$value)));bind_checked(input_2,(()=>get(suspended)),($$value=>set(suspended,$$value)));append($$anchor,div);pop()}function createHostingDB(env){let db=env.db;return{info:()=>db.info(),changes:options=>db.changes(options),revsDiff:diff=>db.revsDiff(diff),bulkDocs:(docs,options)=>db.bulkDocs(docs,options),bulkGet:options=>db.bulkGet(options),put:(doc,options)=>db.put(doc,options),get:(id,options)=>db.get(id,options),_stopHosting:()=>{db=void 0}}}function mixedHash(str,seed,fnv1aHash_=epochFNV1a){let h1=seed,fnv1aHash=fnv1aHash_;const len=str.length;for(let i2=0;i2<len;i2++){let k1=str.charCodeAt(i2);fnv1aHash^=k1;fnv1aHash=Math.imul(fnv1aHash,16777619)>>>0;k1*=c1;k1=k1<<r1|k1>>>32-r1;k1*=c2;h1^=k1;h1=h1<<r2|h1>>>32-r2;h1=h1*m+n}h1^=len;h1^=h1>>>16;h1=Math.imul(h1,2246822507);h1^=h1>>>13;h1=Math.imul(h1,3266489909);h1^=h1>>>16;return[h1>>>0,fnv1aHash]}function fallbackMixedHashEach(src){let m3=1,f4=epochFNV1a;[m3,f4]=mixedHash(`${src.length}${src}`,m3,f4);return`${m3.toString(36)}${f4.toString(36)}`}async function sha12(src){const bytes=writeString(src),digest=await globalThis.crypto.subtle.digest({name:"SHA-1"},bytes);return await arrayBufferToBase64Single(digest)}function setConfirmInstance(api){if(!instance){instance=api;p.resolve(api)}instance=api}function getConfirmInstance(){return instance?Promise.resolve(instance):p.promise}function getReplicatorInstance(){return replicatorInstanceGetter()}function setReplicatorFunc(func){replicatorInstanceGetter=func}async function upsert(db,id,func){try{const updated=func(await db.get(id)),result=await db.put(updated,{});if(result&&result.ok)return updated;throw new Error("Failed to update")}catch(ex){if("not_found"===ex.name){const result=await db.put(func({_id:id}),{});if(result&&result.ok)return func({_id:id});throw new Error("Failed to insert")}throw ex}}async function replicateShim(targetDB,sourceDB,progress,option={}){try{const targetDBInfo=await targetDB.info(),sourceDBInfo=await sourceDB.info(),sourceMaxSeq=sourceDBInfo.update_seq,maxNumSeq=Number.parseInt(`${sourceMaxSeq}`.split("-")[0]);await serialized(`replication-${targetDBInfo.db_name}-${sourceDBInfo.db_name}`,(async()=>{var _a8,_b5,_c3;Logger(`Replication from ${sourceDBInfo.db_name} to ${targetDBInfo.db_name}\nSource: ${sourceDBInfo.db_name} (${sourceDBInfo.update_seq})\nTarget: ${targetDBInfo.db_name} (${targetDBInfo.update_seq})`,LOG_LEVEL_VERBOSE);const targetDBName=targetDBInfo.db_name,sourceDBName=sourceDBInfo.db_name,sourceCheckpointID=`_local/replication-checkpoint-mark-${targetDBName}-${sourceDBName}`,sourceCheckpointData=await upsert(sourceDB,sourceCheckpointID,(doc=>{var _a9;const previousMark=null!=(_a9=doc.mark)?_a9:(new Date).getTime().toString(),mark2=option.rewind?(new Date).getTime().toString():previousMark;return{...doc,mark:mark2}}));Logger(`Replication from ${sourceDBName} to ${targetDBName} with mark ${sourceCheckpointData.mark}`,LOG_LEVEL_VERBOSE);const targetCheckpointID=`_local/replication-checkpoint-${targetDBName}-${sourceCheckpointData.mark}`;let since=(await upsert(targetDB,targetCheckpointID,(doc=>{var _a9;return{...doc,since:null!=(_a9=doc.since)?_a9:""}}))).since;Logger(`Replication from ${sourceDBName} to ${targetDBName} / since ${since}`,LOG_LEVEL_VERBOSE);const batch_size=null!=(_a8=option.batch_size)?_a8:33;for(;;){const changes3=await sourceDB.changes({since,style:"all_docs",limit:batch_size});if(0===changes3.results.length)break;if(null==(_c3=null==(_b5=option.controller)?void 0:_b5.signal)?void 0:_c3.aborted)break;const changesResults=changes3.results,diffCheckParam=changesResults.map((e3=>[e3.id,e3.changes.map((e4=>e4.rev))])).reduce(((acc,[id,revs])=>{var _a9;return{...acc,[id]:[...null!=(_a9=acc[id])?_a9:[],...revs]}}),{}),diff=await targetDB.revsDiff(diffCheckParam),request2=Object.entries(diff).filter((e3=>void 0!==e3[1].missing)).map((e3=>[e3[0],e3[1].missing])).map((([id,revs])=>revs.map((rev3=>({id,rev:rev3}))))).flat();if(0!==request2.length){const fetchedMissingDocs=(await sourceDB.bulkGet({docs:request2,revs:!0})).results.map((e3=>e3.docs)).flat().filter((e3=>"ok"in e3)).map((e3=>e3.ok)),processedDocs=(await targetDB.bulkDocs(fetchedMissingDocs,{new_edits:!1}),(await targetDB.bulkGet({docs:[...new Set(changesResults.map((e3=>({id:e3.id}))))]})).results.map((e3=>e3.docs)).flat().filter((e3=>"ok"in e3)).map((e3=>e3.ok)).map((e3=>({doc:e3,seq:Math.max.apply(void 0,[changesResults.filter((e22=>e22.id===e3._id)).map((e22=>`${e22.seq}`.split("-")[0])).map((e22=>parseInt(e22))).reduce(((a2,b3)=>Math.max(a2,b3)),0),0])}))).sort(((a2,b3)=>a2.seq-b3.seq)).map((e3=>e3.doc))),allSecs=Number.parseInt(`${changes3.last_seq}`.split("-")[0]);try{await progress(processedDocs,{lastSeq:allSecs,maxSeqInBatch:maxNumSeq})}catch(ex){Logger("Failed to process the progress on shim-replication");Logger(ex,LOG_LEVEL_VERBOSE)}since=changes3.last_seq}else since=changes3.last_seq;await upsert(targetDB,targetCheckpointID,(doc=>({...doc,since})))}}))}catch(ex){Logger("Failed to replicate the database",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE)}Logger("Replication has been completed",LOG_LEVEL_VERBOSE)}function createPBKDF2Salt(){return webcrypto2.getRandomValues(new Uint8Array(PBKDF2_SALT_LENGTH))}async function deriveKey(passphrase,pbkdf2Salt,hkdfSalt){const masterKey=await deriveMasterKey(passphrase,pbkdf2Salt);return await webcrypto2.subtle.deriveKey({name:"HKDF",salt:hkdfSalt,info:new Uint8Array,hash:"SHA-256"},masterKey,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function encryptData(key3,iv,data){return await webcrypto2.subtle.encrypt({name:"AES-GCM",iv,tagLength:gcmTagLength},key3,data)}async function _encrypt(input,passphrase,pbkdf2Salt){const hkdfSalt=webcrypto2.getRandomValues(new Uint8Array(HKDF_SALT_LENGTH)),key3=await deriveKey(passphrase,pbkdf2Salt,hkdfSalt),iv=webcrypto2.getRandomValues(new Uint8Array(IV_LENGTH)),encryptedDataArrayBuffer=await encryptData(key3,iv,input);return[iv,hkdfSalt,new Uint8Array(encryptedDataArrayBuffer)]}async function encryptBinary(input,passphrase,pbkdf2Salt){const[iv,hkdfSalt,encryptedData]=await _encrypt(input,passphrase,pbkdf2Salt),totalLength=iv.length+hkdfSalt.length+encryptedData.length,result=new Uint8Array(totalLength);result.set(iv,0);result.set(hkdfSalt,iv.length);result.set(encryptedData,iv.length+hkdfSalt.length);return result}async function encrypt2(input,passphrase,pbkdf2Salt){const inputBuffer=writeString(input),encrypted=await encryptBinary(inputBuffer,passphrase,pbkdf2Salt),inBase64=await arrayBufferToBase64Single(encrypted);return`${HKDF_ENCRYPTED_PREFIX}${inBase64}`}async function _decrypt(iv,pbkdf2Salt,hkdfSalt,encryptedData,passphrase){const key3=await deriveKey(passphrase,pbkdf2Salt,hkdfSalt),decryptedDataArrayBuffer=await webcrypto2.subtle.decrypt({name:"AES-GCM",iv,tagLength:gcmTagLength},key3,encryptedData);return new Uint8Array(decryptedDataArrayBuffer)}async function decryptBinary(binary,passphrase,pbkdf2Salt){if(binary.length<IV_LENGTH+HKDF_SALT_LENGTH)throw new Error("Invalid binary data length. Expected at least ivLength + saltLength bytes.");const iv=binary.slice(0,IV_LENGTH),hkdfSalt=binary.slice(IV_LENGTH,IV_LENGTH+HKDF_SALT_LENGTH),encryptedData=binary.slice(IV_LENGTH+HKDF_SALT_LENGTH);return await _decrypt(iv,pbkdf2Salt,hkdfSalt,encryptedData,passphrase)}async function decrypt2(input,passphrase,pbkdf2Salt){if(!input.startsWith(HKDF_ENCRYPTED_PREFIX))throw new Error(`Invalid input format. Expected input to start with '${HKDF_ENCRYPTED_PREFIX}'.`);const headerLength=HKDF_ENCRYPTED_PREFIX.length,encryptedData=base64ToArrayBuffer(input.slice(headerLength));return readString(await decryptBinary(new Uint8Array(encryptedData),passphrase,pbkdf2Salt))}async function testEncryptionFeature(){const testValue="Supercalifragilisticexpialidocious1234567890!@#$%^&*()_+[]{}|;':\",.<>?✔️✔️⚡𠮷𠮷",pbkdf2Salt=createPBKDF2Salt();try{const encrypted=await encrypt2(testValue,"test-passphrase",pbkdf2Salt);if(await decrypt2(encrypted,"test-passphrase",pbkdf2Salt)!==testValue)throw new Error("Decryption did not return the original value.");Logger("Encryption feature test passed.",LOG_LEVEL_VERBOSE);return!0}catch(error){Logger("WARNING! Your device would not support encryption.",LOG_LEVEL_VERBOSE);Logger(error,LOG_LEVEL_VERBOSE);return!1}}function getSessionPBKDFSalt(refresh=!1){(void 0===_sessionPBKDFSalt||refresh)&&(_sessionPBKDFSalt=createPBKDF2Salt());return _sessionPBKDFSalt}async function encryptWithEphemeralSaltBinary(input,passphrase,refresh=!1){const pbkdf2Salt=getSessionPBKDFSalt(refresh);return concatUInt8Array([pbkdf2Salt,...await _encrypt(input,passphrase,pbkdf2Salt)])}async function encryptWithEphemeralSalt(input,passphrase,refresh=!1){const encrypted=await encryptWithEphemeralSaltBinary(writeString(input),passphrase,refresh),inBase64=await arrayBufferToBase64Single(encrypted);return`${HKDF_SALTED_ENCRYPTED_PREFIX}${inBase64}`}async function decryptWithEphemeralSaltBinary(input,passphrase){if(input.length<IV_LENGTH+HKDF_SALT_LENGTH+PBKDF2_SALT_LENGTH)throw new Error("Invalid binary data length.");const r4=createTypedArrayReader(input),pbkdf2Salt=r4.read(PBKDF2_SALT_LENGTH),iv=r4.read(IV_LENGTH),hkdfSalt=r4.read(HKDF_SALT_LENGTH),encryptedData=r4.readAll();return await _decrypt(iv,pbkdf2Salt,hkdfSalt,encryptedData,passphrase)}async function decryptWithEphemeralSalt(input,passphrase){if(!input.startsWith(HKDF_SALTED_ENCRYPTED_PREFIX))throw new Error(`Invalid input format. Expected input to start with '${HKDF_SALTED_ENCRYPTED_PREFIX}'.`);const headerLength=HKDF_SALTED_ENCRYPTED_PREFIX.length,encryptedData=base64ToArrayBuffer(input.slice(headerLength));return readString(await decryptWithEphemeralSaltBinary(new Uint8Array(encryptedData),passphrase))}async function encrypt3(data,passphrase){return await encryptWithEphemeralSalt(data,passphrase,!0)}async function decrypt3(encryptedData,passphrase){return await decryptWithEphemeralSalt(encryptedData,passphrase)}async function getHashedStringWithCurrentTime(source2){const salt=(~~((new Date).getTime()/1e3/180)).toString(36),salt2=await sha12(salt);return await sha12(salt2+source2)}function removeP2PReplicatorInstance(){setReplicatorFunc((()=>{}))}function addP2PEventHandlers(instance3){eventHub.onEvent(EVENT_ADVERTISEMENT_RECEIVED,(peerId=>{var _a8;return null==(_a8=instance3._replicatorInstance)?void 0:_a8.onNewPeer(peerId)}));eventHub.onEvent(EVENT_DEVICE_LEAVED,(info3=>{var _a8;return null==(_a8=instance3._replicatorInstance)?void 0:_a8.onPeerLeaved(info3)}));eventHub.onEvent(EVENT_REQUEST_STATUS,(()=>{var _a8;null==(_a8=instance3._replicatorInstance)||_a8.requestStatus()}));eventHub.onEvent(EVENT_DATABASE_REBUILT,(async()=>{await instance3.initialiseP2PReplicator()}));eventHub.onEvent(EVENT_P2P_REQUEST_FORCE_OPEN,(()=>{instance3.open()}));eventHub.onEvent(EVENT_PLATFORM_UNLOADED,(()=>{instance3.close()}));eventHub.onEvent(EVENT_SETTING_SAVED,(async settings=>{await instance3.initialiseP2PReplicator()}))}async function openP2PReplicator(instance3){var _a8;if(instance3.settings.P2P_Enabled)if(instance3._replicatorInstance)await(null==(_a8=instance3._replicatorInstance)?void 0:_a8.open());else{await instance3.initialiseP2PReplicator();await instance3._replicatorInstance.open()}else instance3._notice($msg("P2P.NotEnabled"))}async function closeP2PReplicator(instance3){var _a8;await(null==(_a8=instance3._replicatorInstance)?void 0:_a8.close());instance3._replicatorInstance=void 0}function addLog(log2){recentLogs=[...recentLogs,log2].splice(-200);logMessages.value=recentLogs}function apply2(__1,docA,docB,mode,callback,docToString,objBA,objAB){if(get(docA)&&get(docB)){if(get(docA)._id==get(docB)._id){if("A"==get(mode))return callback()(get(docA)._rev,void 0);if("B"==get(mode))return callback()(get(docB)._rev,void 0)}else{if("A"==get(mode))return callback()(void 0,docToString(get(docA)));if("B"==get(mode))return callback()(void 0,docToString(get(docB)))}if("BA"==get(mode))return callback()(void 0,JSON.stringify(get(objBA),null,2));if("AB"==get(mode))return callback()(void 0,JSON.stringify(get(objAB),null,2));callback()(void 0,void 0)}}function cancel(__2,callback){callback()(void 0,void 0)}function JsonResolvePane($$anchor,$$props){function parseJson(json){if(!1===json)return!1;try{return JSON.parse(json)}catch(ex){return!1}}function docToString(doc){return"plain"==doc.datatype?getDocData(doc.data):readString(new Uint8Array(decodeBinary(doc.data)))}function revStringToRevNumber(rev3){return rev3?rev3.split("-")[0]:""}function getDiff(left,right){const dmp=new import_diff_match_patch.diff_match_patch,mapLeft=dmp.diff_linesToChars_(left,right),diffLeftSrc=dmp.diff_main(mapLeft.chars1,mapLeft.chars2,!1);dmp.diff_charsToLines_(diffLeftSrc,mapLeft.lineArray);return diffLeftSrc}function getJsonDiff(a2,b3){return getDiff(JSON.stringify(a2,null,2),JSON.stringify(b3,null,2))}var fragment,h22,text2,node,consequent,alternate_1;push($$props,!0);append_styles($$anchor,$$css2);const binding_group=[];let docs=prop($$props,"docs",27,(()=>proxy([]))),callback=prop($$props,"callback",11,(async(_,__)=>{Promise.resolve()})),filename=prop($$props,"filename",11,""),nameA=prop($$props,"nameA",11,"A"),nameB=prop($$props,"nameB",11,"B"),defaultSelect=prop($$props,"defaultSelect",11,""),keepOrder=prop($$props,"keepOrder",11,!1),hideLocal=prop($$props,"hideLocal",11,!1);const docsArray=user_derived((()=>docs()&&docs().length>=1?keepOrder()||docs()[0].mtime<docs()[1].mtime?{a:docs()[0],b:docs()[1]}:{a:docs()[1],b:docs()[0]}:{a:!1,b:!1})),docA=user_derived((()=>get(docsArray).a)),docB=user_derived((()=>get(docsArray).b)),docAContent=user_derived((()=>get(docA)&&docToString(get(docA)))),docBContent=user_derived((()=>get(docB)&&docToString(get(docB)))),objA=user_derived((()=>parseJson(get(docAContent))||{})),objB=user_derived((()=>parseJson(get(docBContent))||{})),objAB=user_derived((()=>mergeObject(get(objA),get(objB)))),objBAw=user_derived((()=>mergeObject(get(objB),get(objA)))),objBA=user_derived((()=>!!isObjectDifferent(get(objBAw),get(objAB))&&get(objBAw)));let diffs=user_derived((()=>get(objA)&&get(selectedObj)?getJsonDiff(get(objA),get(selectedObj)):[])),mode=state(proxy(defaultSelect()));const mergedObjs=user_derived((()=>({"":!1,A:get(objA),B:get(objB),AB:get(objAB),BA:get(objBA)})));let selectedObj=user_derived((()=>get(mode)in get(mergedObjs)?get(mergedObjs)[get(mode)]:{}));proxy([]);const modes=user_derived((()=>{let newModes=[];if(!hideLocal()){newModes.push(["","Not now"]);newModes.push(["A",nameA()||"A"])}newModes.push(["B",nameB()||"B"]);newModes.push(["AB",`${nameA()||"A"} + ${nameB()||"B"}`]);newModes.push(["BA",`${nameB()||"B"} + ${nameA()||"A"}`]);return newModes}));h22=first_child(fragment=root2());text2=child(h22,!0);reset(h22);node=sibling(h22,2);consequent=$$anchor2=>{var fragment_1=root_12(),div=sibling(first_child(fragment_1),2);child(div).__click=[apply2,docA,docB,mode,callback,docToString,objBA,objAB];reset(div);append($$anchor2,fragment_1)};alternate_1=$$anchor2=>{var node_2,consequent_2,alternate,div_4,table2,tbody,tr,th,text_4,td3,node_3,consequent_3,text_6,td_1,text_7,tr_1,th_1,text_8,td_2,node_4,consequent_4,text_10,td_3,text_11,div_5,node_5,consequent_5,fragment_2=root_2(),div_1=first_child(fragment_2);each(div_1,21,(()=>get(modes)),index,(($$anchor3,m3)=>{var fragment_3=comment(),node_1=first_child(fragment_3),consequent_1=$$anchor4=>{var input_value,div_2,text_1,label2=root_4(),input=child(label2);remove_input_defaults(input);div_2=sibling(input,2);text_1=child(div_2,!0);reset(div_2);reset(label2);template_effect((()=>{var _a8;set_class(label2,1,"sls-setting-label "+(get(m3)[0]==get(mode)?"selected":""),"svelte-1ah3y1j");input_value!==(input_value=get(m3)[0])&&(input.value=null!=(_a8=input.__value=get(m3)[0])?_a8:"");set_text(text_1,get(m3)[1])}));bind_group(binding_group,[],input,(()=>{get(m3)[0];return get(mode)}),($$value=>set(mode,$$value)));append($$anchor4,label2)};if_block(node_1,($$render=>{""!=get(m3)[0]&&0==get(mergedObjs)[get(m3)[0]]||$$render(consequent_1)}));append($$anchor3,fragment_3)}));reset(div_1);node_2=sibling(div_1,2);consequent_2=$$anchor3=>{var div_3=root_5();each(div_3,21,(()=>get(diffs)),index,(($$anchor4,diff)=>{var span=root_6(),text_2=child(span,!0);reset(span);template_effect((()=>{set_class(span,1,clsx2(get(diff)[0]==import_diff_match_patch.DIFF_DELETE?"deleted":get(diff)[0]==import_diff_match_patch.DIFF_INSERT?"added":"normal"),"svelte-1ah3y1j");set_text(text_2,get(diff)[1])}));append($$anchor4,span)}));reset(div_3);append($$anchor3,div_3)};alternate=$$anchor3=>{append($$anchor3,text("NO PREVIEW"))};if_block(node_2,($$render=>{0!=get(selectedObj)?$$render(consequent_2):$$render(alternate,!1)}));table2=child(div_4=sibling(node_2,2));tbody=child(table2);tr=child(tbody);th=child(tr);text_4=child(th,!0);reset(th);node_3=child(td3=sibling(th));consequent_3=$$anchor3=>{var text_5=text();template_effect(($0=>set_text(text_5,`Rev:${null!=$0?$0:""}`)),[()=>revStringToRevNumber(get(docA)._rev)]);append($$anchor3,text_5)};if_block(node_3,($$render=>{get(docA)._id==get(docB)._id&&$$render(consequent_3)}));text_6=sibling(node_3);reset(td3);td_1=sibling(td3);text_7=child(td_1);reset(td_1);reset(tr);th_1=child(tr_1=sibling(tr));text_8=child(th_1,!0);reset(th_1);node_4=child(td_2=sibling(th_1));consequent_4=$$anchor3=>{var text_9=text();template_effect(($0=>set_text(text_9,`Rev:${null!=$0?$0:""}`)),[()=>revStringToRevNumber(get(docB)._rev)]);append($$anchor3,text_9)};if_block(node_4,($$render=>{get(docA)._id==get(docB)._id&&$$render(consequent_4)}));text_10=sibling(node_4);reset(td_2);td_3=sibling(td_2);text_11=child(td_3);reset(td_3);reset(tr_1);reset(tbody);reset(table2);reset(div_4);node_5=child(div_5=sibling(div_4,2));consequent_5=$$anchor3=>{var button_1=root_10();button_1.__click=[cancel,callback];append($$anchor3,button_1)};if_block(node_5,($$render=>{hideLocal()&&$$render(consequent_5)}));sibling(node_5,2).__click=[apply2,docA,docB,mode,callback,docToString,objBA,objAB];reset(div_5);template_effect((($0,$1)=>{var _a8,_b5;set_text(text_4,nameA());set_text(text_6,` ${null!=$0?$0:""}`);set_text(text_7,`${null!=(_a8=get(docAContent)&&get(docAContent).length)?_a8:""} letters`);set_text(text_8,nameB());set_text(text_10,` ${null!=$1?$1:""}`);set_text(text_11,`${null!=(_b5=get(docBContent)&&get(docBContent).length)?_b5:""} letters`)}),[()=>new Date(get(docA).mtime).toLocaleString(),()=>new Date(get(docB).mtime).toLocaleString()]);append($$anchor2,fragment_2)};if_block(node,($$render=>{get(docA)&&get(docB)?$$render(alternate_1,!1):$$render(consequent)}));template_effect((()=>set_text(text2,filename())));append($$anchor,fragment);pop()}function stopAllRunningProcessors(){const processors=[...allRunningProcessors];for(const processor of processors)processor.terminate()}function getComparingMTime(doc,includeDeleted=!1){var _a8,_b5,_c3;if(null===doc)return 0;if(!1===doc)return 0;if(void 0===doc)return 0;if(!includeDeleted){if("deleted"in doc&&doc.deleted)return 0;if("_deleted"in doc&&doc._deleted)return 0}return"stat"in doc?null!=(_b5=null==(_a8=doc.stat)?void 0:_a8.mtime)?_b5:0:null!=(_c3=doc.mtime)?_c3:0}async function e(){function c3(t3,n4){if(e3.buffer.byteLength<t3+n4){const r5=Math.ceil((t3+n4-e3.buffer.byteLength)/65536);e3.grow(r5),a2=new Uint8Array(e3.buffer)}}function l2(t3,e4,n4,r5,i3,o3){c3(t3);const h4=new Uint8Array(t3);return a2.set(h4),n4(0,e4),h4.set(a2.slice(0,t3)),{update(e5){let n5;return a2.set(h4),"string"==typeof e5?(c3(3*e5.length,t3),n5=b3.encodeInto(e5,a2.subarray(t3)).written):(c3(e5.byteLength,t3),a2.set(e5,t3),n5=e5.byteLength),r5(0,t3,n5),h4.set(a2.slice(0,t3)),this},digest:()=>(a2.set(h4),o3(i3(0)))}}function d4(t3){return t3>>>0}function y2(t3){return t3&f4}function p4(t3){let e4=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return c3(3*t3.length,0),d4(n3(0,b3.encodeInto(t3,a2).written,e4))}function v2(t3){let e4=arguments.length>1&&void 0!==arguments[1]?arguments[1]:w2;return c3(3*t3.length,0),y2(r4(0,b3.encodeInto(t3,a2).written,e4))}const{instance:{exports:{mem:e3,xxh32:n3,xxh64:r4,init32:i2,update32:o2,digest32:h3,init64:s2,update64:u2,digest64:g2}}}=await WebAssembly.instantiate(t);let a2=new Uint8Array(e3.buffer);const f4=BigInt(2)**BigInt(64)-BigInt(1),b3=new TextEncoder,w2=BigInt(0);return{h32:p4,h32ToString(t3){return p4(t3,arguments.length>1&&void 0!==arguments[1]?arguments[1]:0).toString(16).padStart(8,"0")},h32Raw(t3){let e4=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return c3(t3.byteLength,0),a2.set(t3),d4(n3(0,t3.byteLength,e4))},create32(){return l2(48,arguments.length>0&&void 0!==arguments[0]?arguments[0]:0,i2,o2,h3,d4)},h64:v2,h64ToString(t3){return v2(t3,arguments.length>1&&void 0!==arguments[1]?arguments[1]:w2).toString(16).padStart(16,"0")},h64Raw(t3){let e4=arguments.length>1&&void 0!==arguments[1]?arguments[1]:w2;return c3(t3.byteLength,0),a2.set(t3),y2(r4(0,t3.byteLength,e4))},create64(){return l2(88,arguments.length>0&&void 0!==arguments[0]?arguments[0]:w2,s2,u2,g2,y2)}}}function digestHash(src){let hash3="";for(const v2 of src)hash3=hashFunc(hash3+v2);return""==hash3?hashFunc("**"):hash3}function PluginCombo($$anchor,$$props){async function comparePlugin(local,remote){var _a8,_b5;let freshness2="",version3="",contentCheck=!1,canApply2=!1;if(local||remote)if(local&&!remote)freshness2="Local only";else if(remote&&!local){freshness2="Remote only";canApply2=!0}else{const dtDiff=(null!==(_a8=null==local?void 0:local.mtime)&&void 0!==_a8?_a8:0)-(null!==(_b5=null==remote?void 0:remote.mtime)&&void 0!==_b5?_b5:0),diff=timeDeltaToHumanReadable(Math.abs(dtDiff));if(dtDiff/1e3<-10){freshness2=`Newer (${diff})`;canApply2=!0;contentCheck=!0}else if(dtDiff/1e3>10){freshness2=`Older (${diff})`;canApply2=!0;contentCheck=!0}else{freshness2="Same";canApply2=!1;contentCheck=!0}}else freshness2="";const localVersionStr=(null==local?void 0:local.version)||"0.0.0",remoteVersionStr=(null==remote?void 0:remote.version)||"0.0.0";if((null==local?void 0:local.version)||(null==remote?void 0:remote.version)){const compare3=`${localVersionStr}`.localeCompare(remoteVersionStr,void 0,{numeric:!0});0==compare3?version3="Same":compare3<0?version3=`Lower (${localVersionStr} < ${remoteVersionStr})`:compare3>0&&(version3=`Higher (${localVersionStr} > ${remoteVersionStr})`)}if(contentCheck&&local&&remote){const{canApply:canApply3,equivalency:equivalency3,canCompare:canCompare3}=await checkEquivalency(local,remote);return{canApply:canApply3,freshness:freshness2,equivalency:equivalency3,version:version3,canCompare:canCompare3}}return{canApply:canApply2,freshness:freshness2,equivalency:"",version:version3,canCompare:!1}}async function checkEquivalency(local,remote){let equivalency2="",canApply2=!1,canCompare2=!1;const matchingStatus=[...new Set([...local.files.map((e3=>e3.filename)),...remote.files.map((e3=>e3.filename))])].map((filename=>{const localFile=local.files.find((e3=>e3.filename==filename)),remoteFile=remote.files.find((e3=>e3.filename==filename));return localFile||remoteFile?localFile&&!remoteFile?2:!localFile&&remoteFile?8:localFile&&remoteFile&&getDocData(localFile.data)==getDocData(remoteFile.data)?4:16:0})).reduce(((p4,c3)=>p4|c3),0);if(4==matchingStatus){equivalency2="Same";canApply2=!1}else if(matchingStatus<=4){equivalency2="Same or local only";canApply2=!1}else if(16==matchingStatus){canApply2=!0;canCompare2=!0;equivalency2="Different"}else{canApply2=!0;canCompare2=!0;equivalency2="Mixed"}return{equivalency:equivalency2,canApply:canApply2,canCompare:canCompare2}}async function performCompare(local,remote){const result=await comparePlugin(local,remote);set(canApply,result.canApply);set(freshness,result.freshness);set(equivalency,result.equivalency);set(version2,result.version);set(canCompare,result.canCompare);set(pickToCompare,!1);get(canCompare)&&((null==local?void 0:local.files.length)==(null==remote?void 0:remote.files.length)&&1==(null==local?void 0:local.files.length)&&(null==local?void 0:local.files[0].filename)==(null==remote?void 0:remote.files[0].filename)?set(pickToCompare,!1):set(pickToCompare,!0))}async function updateTerms(list2,selectNewest2,isMaintenanceMode2){const local=list2.find((e3=>e3.term==thisTerm()));if(isMaintenanceMode2)set(terms,[...new Set(list2.map((e3=>e3.term)))]);else if(hideNotApplicable()){const termsTmp=[],wk2=[...new Set(list2.map((e3=>e3.term)))];for(const termName of wk2){const remote=list2.find((e3=>e3.term==termName));(await comparePlugin(local,remote)).canApply&&termsTmp.push(termName)}set(terms,[...termsTmp])}else set(terms,[...new Set(list2.map((e3=>e3.term)))].filter((e3=>e3!=thisTerm())));let newest=local;if(selectNewest2){for(const term of get(terms)){const remote=list2.find((e3=>e3.term==term));remote&&remote.mtime&&((null==newest?void 0:newest.mtime)||0)<remote.mtime&&(newest=remote)}newest&&newest.term!=thisTerm()&&selected(newest.term)}get(terms).indexOf(selected())<0&&selected("")}async function applySelected(){const local=list().find((e3=>e3.term==thisTerm())),selectedItem=list().find((e3=>e3.term==selected()));selectedItem&&await applyData()(selectedItem)&&addOn.updatePluginList(!0,null==local?void 0:local.documentPath)}async function compareSelected(){const local=list().find((e3=>e3.term==thisTerm())),selectedItem=list().find((e3=>e3.term==selected()));await compareItems(local,selectedItem)}async function compareItems(local,remote,filename){if(local&&remote){if(!filename){await compareData()(local,remote)&&addOn.updatePluginList(!0,local.documentPath);return}{const localCopy=local instanceof PluginDataExDisplayV2?new PluginDataExDisplayV2(local):{...local},remoteCopy=remote instanceof PluginDataExDisplayV2?new PluginDataExDisplayV2(remote):{...remote};localCopy.files=localCopy.files.filter((e3=>e3.filename==filename));remoteCopy.files=remoteCopy.files.filter((e3=>e3.filename==filename));await compareData()(localCopy,remoteCopy,!0)&&addOn.updatePluginList(!0,local.documentPath)}}else remote||local?remote?local||Logger("Could not locally item",LOG_LEVEL_INFO):Logger("Could not find remote item",LOG_LEVEL_INFO):Logger("Could not find both remote and local item",LOG_LEVEL_INFO)}async function pickCompareItem(evt){const local=list().find((e3=>e3.term==thisTerm())),selectedItem=list().find((e3=>e3.term==selected()));if(!local)return;if(!selectedItem)return;const menu=new import_obsidian.Menu;menu.addItem((item=>item.setTitle("Compare file").setIsLabel(!0)));menu.addSeparator();const files=unique(local.files.map((e3=>e3.filename)).concat(selectedItem.files.map((e3=>e3.filename)))),convDate=dt=>dt?new Date(dt.mtime).toLocaleString():"(Missing)";for(const filename of files)menu.addItem((item=>{const localFile=local.files.find((e3=>e3.filename==filename)),remoteFile=selectedItem.files.find((e3=>e3.filename==filename)),title=`${filename} (${convDate(localFile)} <--\x3e ${convDate(remoteFile)})`;item.setTitle(title).onClick((e3=>compareItems(local,selectedItem,filename)))}));menu.showAtMouseEvent(evt)}async function deleteSelected(){const selectedItem=list().find((e3=>e3.term==selected()));selectedItem&&await deleteData()(selectedItem)&&addOn.reloadPluginList(!0)}async function duplicateItem(){const local=list().find((e3=>e3.term==thisTerm()));if(!local){Logger("Could not find local item",LOG_LEVEL_VERBOSE);return}const duplicateTermName=await plugin3().confirm.askString("Duplicate","device name","");if(duplicateTermName){if(duplicateTermName.contains("/")){Logger('We can not use "/" to the device name',LOG_LEVEL_NOTICE);return}const key3=`${plugin3().app.vault.configDir}/${local.files[0].filename}`;await addOn.storeCustomizationFiles(key3,duplicateTermName);await addOn.updatePluginList(!1,addOn.filenameToUnifiedKey(key3,duplicateTermName))}}var fragment,node,consequent_6,alternate_4;push($$props,!1);append_styles($$anchor,$$css3);let list=prop($$props,"list",24,(()=>[])),thisTerm=prop($$props,"thisTerm",8,""),hideNotApplicable=prop($$props,"hideNotApplicable",8,!1),selectNewest=prop($$props,"selectNewest",8,0),selectNewestStyle=prop($$props,"selectNewestStyle",8,0),applyAllPluse=prop($$props,"applyAllPluse",8,0),applyData=prop($$props,"applyData",8),compareData=prop($$props,"compareData",8),deleteData=prop($$props,"deleteData",8),hidden=prop($$props,"hidden",8),plugin3=prop($$props,"plugin",8),isMaintenanceMode=prop($$props,"isMaintenanceMode",8,!1),isFlagged=prop($$props,"isFlagged",8,!1);const addOn=plugin3().getAddOn(ConfigSync.name);if(!addOn){Logger(`Could not load the add-on ${ConfigSync.name}`,LOG_LEVEL_INFO);throw new Error(`Could not load the add-on ${ConfigSync.name}`)}let selected=prop($$props,"selected",12,""),freshness=mutable_source(""),equivalency=mutable_source(""),version2=mutable_source(""),canApply=mutable_source(!1),canCompare=mutable_source(!1),pickToCompare=mutable_source(!1),currentSelectNewest=mutable_source(0),currentApplyAll=mutable_source(0),terms=mutable_source([]);legacy_pre_effect((()=>(deep_read_state(selectNewest()),get(currentSelectNewest),deep_read_state(selectNewestStyle()),deep_read_state(isFlagged()),deep_read_state(list()),deep_read_state(isMaintenanceMode()))),(()=>{let doSelectNewest=!1;selectNewest()!=get(currentSelectNewest)&&(1==selectNewestStyle()?doSelectNewest=!0:2==selectNewestStyle()?doSelectNewest=isFlagged():3==selectNewestStyle()&&selected(""));updateTerms(list(),doSelectNewest,isMaintenanceMode());set(currentSelectNewest,selectNewest())}));legacy_pre_effect((()=>(deep_read_state(applyAllPluse()),get(currentApplyAll),deep_read_state(selected()),deep_read_state(hidden()))),(()=>{const doApply=applyAllPluse()!=get(currentApplyAll);set(currentApplyAll,applyAllPluse());doApply&&selected()&&(hidden()||applySelected())}));legacy_pre_effect((()=>(deep_read_state(selected()),deep_read_state(thisTerm()),deep_read_state(list()))),(()=>{set(freshness,"");set(equivalency,"");set(version2,"");set(canApply,!1);if(""==selected());else if(selected()==thisTerm()){set(freshness,"This device");set(canApply,!1)}else performCompare(list().find((e3=>e3.term==thisTerm())),list().find((e3=>e3.term==selected())))}));legacy_pre_effect_reset();init();node=first_child(fragment=comment());consequent_6=$$anchor2=>{var fragment_1=root_13(),node_1=sibling(first_child(fragment_1),2),consequent_5=$$anchor3=>{var span_2,text_1,span_3,text_2,select,option,node_3,consequent_2,alternate_2,node_6,consequent_4,fragment_2=root_22(),span=first_child(fragment_2),span_1=child(span),text2=child(span_1,!0);reset(span_1);span_2=sibling(span_1,2);text_1=child(span_2,!0);reset(span_2);span_3=sibling(span_2,2);text_2=child(span_3,!0);reset(span_3);reset(span);select=sibling(span,2);template_effect((()=>{selected();invalidate_inner_signals((()=>{get(terms)}))}));(option=child(select)).value=option.__value="";each(sibling(option),1,(()=>get(terms)),index,(($$anchor4,term)=>{var option_1_value,option_1=root_3(),text_3=child(option_1,!0);reset(option_1);option_1_value={};template_effect((()=>{var _a8;set_text(text_3,get(term));option_1_value!==(option_1_value=get(term))&&(option_1.value=null!=(_a8=option_1.__value=get(term))?_a8:"")}));append($$anchor4,option_1)}));reset(select);node_3=sibling(select,2);consequent_2=$$anchor4=>{var fragment_3=root_42(),node_4=first_child(fragment_3),consequent_1=$$anchor5=>{var fragment_4=comment(),node_5=first_child(fragment_4),consequent=$$anchor6=>{var button=root_62();event("click",button,pickCompareItem);append($$anchor6,button)},alternate=$$anchor6=>{var button_1=root_7();event("click",button_1,compareSelected);append($$anchor6,button_1)};if_block(node_5,($$render=>{get(pickToCompare)?$$render(consequent):$$render(alternate,!1)}));append($$anchor5,fragment_4)},alternate_1=$$anchor5=>{append($$anchor5,root_8())};if_block(node_4,($$render=>{get(canCompare)?$$render(consequent_1):$$render(alternate_1,!1)}));event("click",sibling(node_4,2),applySelected);append($$anchor4,fragment_3)};alternate_2=$$anchor4=>{var fragment_5=root_9();next(2);append($$anchor4,fragment_5)};if_block(node_3,($$render=>{get(canApply)||isMaintenanceMode()&&""!=selected()?$$render(consequent_2):$$render(alternate_2,!1)}));node_6=sibling(node_3,2);consequent_4=$$anchor4=>{var fragment_6=comment(),node_7=first_child(fragment_6),consequent_3=$$anchor5=>{var button_4=root_11();event("click",button_4,deleteSelected);append($$anchor5,button_4)},alternate_3=$$anchor5=>{var button_5=root_122();event("click",button_5,duplicateItem);append($$anchor5,button_5)};if_block(node_7,($$render=>{""!=selected()?$$render(consequent_3):$$render(alternate_3,!1)}));append($$anchor4,fragment_6)};if_block(node_6,($$render=>{isMaintenanceMode()&&$$render(consequent_4)}));template_effect((()=>{set_text(text2,get(freshness));set_text(text_1,get(equivalency));set_text(text_2,get(version2))}));bind_select_value(select,selected);append($$anchor3,fragment_2)};if_block(node_1,($$render=>{hidden()||$$render(consequent_5)}));append($$anchor2,fragment_1)};alternate_4=$$anchor2=>{var fragment_7=root_132();next(6);append($$anchor2,fragment_7)};if_block(node,($$render=>{get(terms),untrack((()=>get(terms).length>0))?$$render(consequent_6):$$render(alternate_4,!1)}));append($$anchor,fragment);pop()}function PluginPane($$anchor,$$props){async function requestUpdate(){await addOn.updatePluginList(!0)}async function requestReload(){await addOn.reloadPluginList(!0)}function filterList(list2,categories){return list2.filter((e3=>-1!==categories.indexOf(e3.category))).sort(((a2,b3)=>`${a2.category}-${a2.name}`.localeCompare(`${b3.category}-${b3.name}`)))}function groupBy(items,key3){let ret={};for(const v2 of items){const k2=key3 in v2?v2[key3]:"";ret[k2]=ret[k2]||[];ret[k2].push(v2)}for(const k2 in ret)ret[k2]=ret[k2].sort(((a2,b3)=>`${a2.category}-${a2.name}`.localeCompare(`${b3.category}-${b3.name}`)));return Object.entries(ret).sort((([a2],[b3])=>`${a2}`.localeCompare(`${b3}`)))}async function scanAgain(){await addOn.scanAllConfigFiles(!0);await requestUpdate()}async function replicate2(){await plugin3().services.replication.replicate(!0)}function selectAllNewest(selectMode){update(selectNewestPulse);set(selectNewestStyle,selectMode?1:2)}function resetSelectNewest(){update(selectNewestPulse);set(selectNewestStyle,3)}function applyAll(){update(applyAllPluse)}async function applyData(data){return await addOn.applyData(data)}async function compareData(docA,docB,compareEach=!1){return await addOn.compareUsingDisplayData(docA,docB,compareEach)}async function deleteData(data){return await addOn.deleteData(data)}function askMode(evt,title,key3){var _a8;const menu=new import_obsidian.Menu;menu.addItem((item=>item.setTitle(title).setIsLabel(!0)));menu.addSeparator();const prevMode=null!==(_a8=automaticList.get(key3))&&void 0!==_a8?_a8:MODE_SELECTIVE;for(const mode of[MODE_SELECTIVE,MODE_AUTOMATIC,MODE_PAUSED,MODE_SHINY])menu.addItem((item=>{item.setTitle(`${getIcon(mode)}:${TITLES[mode]}`).onClick((e3=>{mode===MODE_AUTOMATIC?askOverwriteModeForAutomatic(evt,key3):setMode(key3,mode)})).setChecked(prevMode==mode).setDisabled(prevMode==mode)}));menu.showAtMouseEvent(evt)}function applyAutomaticSync(key3,direction){var _a8,_b5;setMode(key3,MODE_AUTOMATIC);const configDir=normalizePath(plugin3().app.vault.configDir),files=(null!==(_b5=null===(_a8=plugin3().settings.pluginSyncExtendedSetting[key3])||void 0===_a8?void 0:_a8.files)&&void 0!==_b5?_b5:[]).map((e3=>`${configDir}/${e3}`));addOnHiddenFileSync.initialiseInternalFileSync(direction,!0,files)}function askOverwriteModeForAutomatic(evt,key3){const menu=new import_obsidian.Menu;menu.addItem((item=>item.setTitle("Initial Action").setIsLabel(!0)));menu.addSeparator();menu.addItem((item=>{item.setTitle("↑: Overwrite Remote").onClick((e3=>{applyAutomaticSync(key3,"pushForce")}))})).addItem((item=>{item.setTitle("↓: Overwrite Local").onClick((e3=>{applyAutomaticSync(key3,"pullForce")}))})).addItem((item=>{item.setTitle("⇅: Use newer").onClick((e3=>{applyAutomaticSync(key3,"safe")}))}));menu.showAtMouseEvent(evt)}function setMode(key3,mode){if(key3.startsWith(PREFIX_PLUGIN_ALL+"/")){setMode(PREFIX_PLUGIN_DATA+key3.substring(PREFIX_PLUGIN_ALL.length),mode);setMode(PREFIX_PLUGIN_MAIN+key3.substring(PREFIX_PLUGIN_ALL.length),mode);return}const files=unique(get(list).filter((e3=>`${e3.category}/${e3.name}`==key3)).map((e3=>e3.files)).flat().map((e3=>e3.filename)));if(mode==MODE_SELECTIVE){automaticList.delete(key3);delete plugin3().settings.pluginSyncExtendedSetting[key3];set(automaticListDisp,automaticList)}else{automaticList.set(key3,mode);set(automaticListDisp,automaticList);key3 in plugin3().settings.pluginSyncExtendedSetting||plugin3(plugin3().settings.pluginSyncExtendedSetting[key3]={key:key3,mode,files:[]},!0);plugin3(plugin3().settings.pluginSyncExtendedSetting[key3].files=files,!0);plugin3(plugin3().settings.pluginSyncExtendedSetting[key3].mode=mode,!0)}plugin3().services.setting.saveSettingData()}function getIcon(mode){if(mode in ICONS)return ICONS[mode]}function computeDisplayKeys(list2){return[...list2,...Object.keys(plugin3().settings.pluginSyncExtendedSetting).map((e3=>`${e3}///`.split("/"))).filter((e3=>e3[0]&&e3[1])).map((e3=>({category:e3[0],name:e3[1],displayName:e3[1]})))].sort(((a2,b3)=>{var _a8,_b5;return(null!==(_a8=a2.displayName)&&void 0!==_a8?_a8:a2.name).localeCompare(null!==(_b5=b3.displayName)&&void 0!==_b5?_b5:b3.name)})).reduce(((p4,c3)=>{var _a8,_b5;return{...p4,[c3.category]:unique(c3.category in p4?[...p4[c3.category],null!==(_a8=c3.displayName)&&void 0!==_a8?_a8:c3.name]:[null!==(_b5=c3.displayName)&&void 0!==_b5?_b5:c3.name])}}),{})}async function deleteAllItems(term){const deleteItems=get(list).filter((e3=>e3.term==term));for(const item of deleteItems)await deleteData(item);addOn.reloadPluginList(!0)}function updateNameMap(e3){const items=[...e3.entries()].map((([k2,v2])=>[k2.split("/").slice(-2).join("/"),v2.name])),newMap=new Map(items);if(newMap.size==get(nameMap).size){let diff=!1;for(const[k2,v2]of newMap)if(get(nameMap).get(k2)!=v2){diff=!0;break}if(!diff)return}set(nameMap,newMap)}var fragment,div,div_1,button,button_1,button_2,node,consequent,div_2,button_4,button_5,button_6,button_7,div_3,node_1,consequent_1,div_4,node_2,consequent_2,alternate_5,node_13,consequent_10,div_32,label_1,input,div_33,label_2,input_1;push($$props,!1);append_styles($$anchor,$$css4);const $pluginManifestStore=()=>store_get(pluginManifestStore,"$pluginManifestStore",$$stores),$pluginV2Progress=()=>store_get(pluginV2Progress,"$pluginV2Progress",$$stores),[$$stores,$$cleanup]=setup_stores(),hideNotApplicable=mutable_source(),thisTerm=mutable_source(),options=mutable_source();let plugin3=prop($$props,"plugin",12);const addOn=plugin3().getAddOn(ConfigSync.name);if(!addOn){const msg="AddOn Module (ConfigSync) has not been loaded. This is very unexpected situation. Please report this issue.";Logger(msg,LOG_LEVEL_NOTICE);throw new Error(msg)}const addOnHiddenFileSync=plugin3().getAddOn(HiddenFileSync.name);if(!addOnHiddenFileSync){const msg="AddOn Module (HiddenFileSync) has not been loaded. This is very unexpected situation. Please report this issue.";Logger(msg,LOG_LEVEL_NOTICE);throw new Error(msg)}let list=mutable_source([]),selectNewestPulse=mutable_source(0),selectNewestStyle=mutable_source(0),hideEven=mutable_source(!1),loading=mutable_source(!1),applyAllPluse=mutable_source(0),isMaintenanceMode=mutable_source(!1),allTerms=mutable_source([]);pluginList.subscribe((e3=>{set(list,e3);set(allTerms,unique(get(list).map((e4=>e4.term))))}));pluginIsEnumerating.subscribe((e3=>{set(loading,e3)}));onMount((async()=>{requestUpdate()}));const displays={CONFIG:"Configuration",THEME:"Themes",SNIPPET:"Snippets"},ICONS={[MODE_SELECTIVE]:"🔀",[MODE_PAUSED]:"⛔",[MODE_AUTOMATIC]:"✨",[MODE_SHINY]:"🚩"},TITLES={[MODE_SELECTIVE]:"Selective",[MODE_PAUSED]:"Ignore",[MODE_AUTOMATIC]:"Automatic",[MODE_SHINY]:"Flagged Selective"},PREFIX_PLUGIN_ALL="PLUGIN_ALL",PREFIX_PLUGIN_DATA="PLUGIN_DATA",PREFIX_PLUGIN_MAIN="PLUGIN_MAIN";let automaticList=new Map,automaticListDisp=mutable_source(new Map);for(const{key:key3,mode}of Object.values(plugin3().settings.pluginSyncExtendedSetting))automaticList.set(key3,mode);set(automaticListDisp,automaticList);let displayKeys=mutable_source({}),deleteTerm=mutable_source(""),nameMap=mutable_source(new Map),displayEntries=mutable_source([]),pluginEntries=mutable_source([]),useSyncPluginEtc=plugin3().settings.usePluginEtc;legacy_pre_effect((()=>{}),(()=>{set(hideNotApplicable,!1)}));legacy_pre_effect((()=>deep_read_state(plugin3())),(()=>{set(thisTerm,plugin3().services.setting.getDeviceAndVaultName())}));legacy_pre_effect((()=>(get(thisTerm),get(hideNotApplicable),get(selectNewestPulse),get(selectNewestStyle),get(applyAllPluse),deep_read_state(plugin3()),get(isMaintenanceMode))),(()=>{set(options,{thisTerm:get(thisTerm),hideNotApplicable:get(hideNotApplicable),selectNewest:get(selectNewestPulse),selectNewestStyle:get(selectNewestStyle),applyAllPluse:get(applyAllPluse),applyData,compareData,deleteData,plugin:plugin3(),isMaintenanceMode:get(isMaintenanceMode)})}));legacy_pre_effect((()=>get(list)),(()=>{set(displayKeys,computeDisplayKeys(get(list)))}));legacy_pre_effect((()=>$pluginManifestStore()),(()=>{updateNameMap($pluginManifestStore())}));legacy_pre_effect((()=>get(displayKeys)),(()=>{set(displayEntries,Object.entries(displays).filter((([key3,_])=>key3 in get(displayKeys))))}));legacy_pre_effect((()=>get(list)),(()=>{set(pluginEntries,groupBy(filterList(get(list),["PLUGIN_MAIN","PLUGIN_DATA","PLUGIN_ETC"]),"name"))}));legacy_pre_effect_reset();init();div_1=child(div=first_child(fragment=root3()));button_1=sibling(button=child(div_1),2);button_2=sibling(button_1,2);node=sibling(button_2,2);consequent=$$anchor2=>{var button_3=root_14();event("click",button_3,(()=>requestReload()));append($$anchor2,button_3)};if_block(node,($$render=>{get(isMaintenanceMode)&&$$render(consequent)}));reset(div_1);div_2=sibling(div_1,2);(button_5=sibling(button_4=child(div_2),2)).textContent="🚩 Select Flagged Shiny";button_6=sibling(button_5,2);button_7=sibling(button_6,2);reset(div_2);reset(div);node_1=child(div_3=sibling(div,2));consequent_1=$$anchor2=>{var span=root_23(),text2=child(span);reset(span);template_effect((()=>set_text(text2,"Updating list..."+(0==$pluginV2Progress()?"":` (${$pluginV2Progress()})`))));append($$anchor2,span)};if_block(node_1,($$render=>{(get(loading)||0!==$pluginV2Progress())&&$$render(consequent_1)}));reset(div_3);node_2=child(div_4=sibling(div_3,2));consequent_2=$$anchor2=>{append($$anchor2,root_32())};alternate_5=$$anchor2=>{var div_11,fragment_1=root_43(),node_3=first_child(fragment_1);each(node_3,1,(()=>get(displayEntries)),index,(($$anchor3,$$item)=>{var div_6,h3,text_1,$$array=user_derived((()=>to_array(get($$item),2)));let key3=()=>get($$array)[0],label2=()=>get($$array)[1];h3=child(div_6=root_52());text_1=child(h3,!0);reset(h3);each(sibling(h3,2),1,(()=>(get(displayKeys),key3(),untrack((()=>get(displayKeys)[key3()])))),index,(($$anchor4,name)=>{var div_7,div_8,button_8,text_2,span_1,text_3,div_9,node_5,consequent_3,alternate;const bindKey=derived_safe_equal((()=>`${key3()}/${get(name)}`)),mode=derived_safe_equal((()=>(get(automaticListDisp),deep_read_state(get(bindKey)),deep_read_state(MODE_SELECTIVE),untrack((()=>{var _a8;return null!=(_a8=get(automaticListDisp).get(get(bindKey)))?_a8:MODE_SELECTIVE})))));div_8=child(div_7=root_63());button_8=child(div_8);text_2=child(button_8,!0);reset(button_8);span_1=sibling(button_8,2);text_3=child(span_1,!0);reset(span_1);reset(div_8);node_5=child(div_9=sibling(div_8,2));consequent_3=$$anchor5=>{{let $0=derived_safe_equal((()=>get(mode)==MODE_SHINY)),$1=derived_safe_equal((()=>(get(list),key3(),get(name),untrack((()=>get(list).filter((e3=>e3.category==key3()&&e3.name==get(name))))))));PluginCombo($$anchor5,spread_props((()=>get(options)),{get isFlagged(){return get($0)},get list(){return get($1)},hidden:!1}))}};alternate=$$anchor5=>{var div_10=root_82(),text_4=child(div_10,!0);reset(div_10);template_effect((()=>set_text(text_4,(deep_read_state(get(mode)),untrack((()=>TITLES[get(mode)]))))));append($$anchor5,div_10)};if_block(node_5,($$render=>{get(mode)==MODE_SELECTIVE||get(mode)==MODE_SHINY?$$render(consequent_3):$$render(alternate,!1)}));reset(div_9);reset(div_7);template_effect((($0,$1)=>{set_class(div_7,1,"labelrow "+(get(hideEven)?"hideeven":""),"svelte-10jah2g");set_text(text_2,$0);set_text(text_3,$1)}),[()=>(deep_read_state(get(mode)),untrack((()=>getIcon(get(mode))))),()=>(key3(),get(nameMap),get(name),untrack((()=>"THEME"==key3()&&get(nameMap).get(`themes/${get(name)}`)||get(name))))]);event("click",button_8,(evt=>askMode(evt,`${key3()}/${get(name)}`,get(bindKey))));append($$anchor4,div_7)}));reset(div_6);template_effect((()=>set_text(text_1,label2())));append($$anchor3,div_6)}));div_11=sibling(node_3,2);each(sibling(child(div_11),2),1,(()=>get(pluginEntries)),index,(($$anchor3,$$item)=>{var fragment_3,div_12,div_13,button_9,text_5,span_2,text_6,div_14,node_7,consequent_4,node_8,consequent_9,alternate_4,$$array_1=user_derived((()=>to_array(get($$item),2)));let name=()=>get($$array_1)[0],listX=()=>get($$array_1)[1];const bindKeyAll=derived_safe_equal((()=>`${PREFIX_PLUGIN_ALL}/${name()}`)),modeAll=derived_safe_equal((()=>(get(automaticListDisp),deep_read_state(get(bindKeyAll)),deep_read_state(MODE_SELECTIVE),untrack((()=>{var _a8;return null!=(_a8=get(automaticListDisp).get(get(bindKeyAll)))?_a8:MODE_SELECTIVE}))))),bindKeyMain=derived_safe_equal((()=>`${PREFIX_PLUGIN_MAIN}/${name()}`)),modeMain=derived_safe_equal((()=>(get(automaticListDisp),deep_read_state(get(bindKeyMain)),deep_read_state(MODE_SELECTIVE),untrack((()=>{var _a8;return null!=(_a8=get(automaticListDisp).get(get(bindKeyMain)))?_a8:MODE_SELECTIVE}))))),bindKeyData=derived_safe_equal((()=>`${PREFIX_PLUGIN_DATA}/${name()}`)),modeData=derived_safe_equal((()=>(get(automaticListDisp),deep_read_state(get(bindKeyData)),deep_read_state(MODE_SELECTIVE),untrack((()=>{var _a8;return null!=(_a8=get(automaticListDisp).get(get(bindKeyData)))?_a8:MODE_SELECTIVE}))))),bindKeyETC=derived_safe_equal((()=>`PLUGIN_ETC/${name()}`)),modeEtc=derived_safe_equal((()=>(get(automaticListDisp),deep_read_state(get(bindKeyETC)),deep_read_state(MODE_SELECTIVE),untrack((()=>{var _a8;return null!=(_a8=get(automaticListDisp).get(get(bindKeyETC)))?_a8:MODE_SELECTIVE})))));fragment_3=root_92();div_13=child(div_12=first_child(fragment_3));button_9=child(div_13);text_5=child(button_9,!0);reset(button_9);span_2=sibling(button_9,2);text_6=child(span_2,!0);reset(span_2);reset(div_13);node_7=child(div_14=sibling(div_13,2));consequent_4=$$anchor4=>{{let $0=derived_safe_equal((()=>get(modeAll)==MODE_SHINY));PluginCombo($$anchor4,spread_props((()=>get(options)),{get isFlagged(){return get($0)},get list(){return listX()},hidden:!0}))}};if_block(node_7,($$render=>{get(modeAll)!=MODE_SELECTIVE&&get(modeAll)!=MODE_SHINY||$$render(consequent_4)}));reset(div_14);reset(div_12);node_8=sibling(div_12,2);consequent_9=$$anchor4=>{var div_17,node_9,consequent_5,alternate_1,div_19,div_20,button_11,text_9,div_21,node_10,consequent_6,alternate_2,node_11,consequent_8,fragment_5=root_112(),div_15=first_child(fragment_5),div_16=child(div_15),button_10=child(div_16),text_7=child(button_10,!0);reset(button_10);next(2);reset(div_16);node_9=child(div_17=sibling(div_16,2));consequent_5=$$anchor5=>{{let $0=derived_safe_equal((()=>get(modeMain)==MODE_SHINY)),$1=derived_safe_equal((()=>(listX(),untrack((()=>filterList(listX(),["PLUGIN_MAIN"]))))));PluginCombo($$anchor5,spread_props((()=>get(options)),{get isFlagged(){return get($0)},get list(){return get($1)},hidden:!1}))}};alternate_1=$$anchor5=>{var div_18=root_133(),text_8=child(div_18,!0);reset(div_18);template_effect((()=>set_text(text_8,(deep_read_state(get(modeMain)),untrack((()=>TITLES[get(modeMain)]))))));append($$anchor5,div_18)};if_block(node_9,($$render=>{get(modeMain)==MODE_SELECTIVE||get(modeMain)==MODE_SHINY?$$render(consequent_5):$$render(alternate_1,!1)}));reset(div_17);reset(div_15);div_20=child(div_19=sibling(div_15,2));button_11=child(div_20);text_9=child(button_11,!0);reset(button_11);next(2);reset(div_20);node_10=child(div_21=sibling(div_20,2));consequent_6=$$anchor5=>{{let $0=derived_safe_equal((()=>get(modeData)==MODE_SHINY)),$1=derived_safe_equal((()=>(listX(),untrack((()=>filterList(listX(),["PLUGIN_DATA"]))))));PluginCombo($$anchor5,spread_props((()=>get(options)),{get isFlagged(){return get($0)},get list(){return get($1)},hidden:!1}))}};alternate_2=$$anchor5=>{var div_22=root_15(),text_10=child(div_22,!0);reset(div_22);template_effect((()=>set_text(text_10,(deep_read_state(get(modeData)),untrack((()=>TITLES[get(modeData)]))))));append($$anchor5,div_22)};if_block(node_10,($$render=>{get(modeData)==MODE_SELECTIVE||get(modeData)==MODE_SHINY?$$render(consequent_6):$$render(alternate_2,!1)}));reset(div_21);reset(div_19);node_11=sibling(div_19,2);consequent_8=$$anchor5=>{var div_25,node_12,consequent_7,alternate_3,div_23=root_16(),div_24=child(div_23),button_12=child(div_24),text_11=child(button_12,!0);reset(button_12);next(2);reset(div_24);node_12=child(div_25=sibling(div_24,2));consequent_7=$$anchor6=>{{let $0=derived_safe_equal((()=>get(modeEtc)==MODE_SHINY)),$1=derived_safe_equal((()=>(listX(),untrack((()=>filterList(listX(),["PLUGIN_ETC"]))))));PluginCombo($$anchor6,spread_props((()=>get(options)),{get isFlagged(){return get($0)},get list(){return get($1)},hidden:!1}))}};alternate_3=$$anchor6=>{var div_26=root_18(),text_12=child(div_26,!0);reset(div_26);template_effect((()=>set_text(text_12,(deep_read_state(get(modeEtc)),untrack((()=>TITLES[get(modeEtc)]))))));append($$anchor6,div_26)};if_block(node_12,($$render=>{get(modeEtc)==MODE_SELECTIVE||get(modeEtc)==MODE_SHINY?$$render(consequent_7):$$render(alternate_3,!1)}));reset(div_25);reset(div_23);template_effect(($0=>{set_class(div_23,1,"filerow "+(get(hideEven)?"hideeven":""),"svelte-10jah2g");set_text(text_11,$0)}),[()=>(deep_read_state(get(modeEtc)),untrack((()=>getIcon(get(modeEtc)))))]);event("click",button_12,(evt=>askMode(evt,`PLUGIN_ETC/${name()}`,get(bindKeyETC))));append($$anchor5,div_23)};if_block(node_11,($$render=>{useSyncPluginEtc&&$$render(consequent_8)}));template_effect((($0,$1)=>{set_class(div_15,1,"filerow "+(get(hideEven)?"hideeven":""),"svelte-10jah2g");set_text(text_7,$0);set_class(div_19,1,"filerow "+(get(hideEven)?"hideeven":""),"svelte-10jah2g");set_text(text_9,$1)}),[()=>(deep_read_state(get(modeMain)),untrack((()=>getIcon(get(modeMain))))),()=>(deep_read_state(get(modeData)),untrack((()=>getIcon(get(modeData)))))]);event("click",button_10,(evt=>askMode(evt,`${PREFIX_PLUGIN_MAIN}/${name()}/MAIN`,get(bindKeyMain))));event("click",button_11,(evt=>askMode(evt,`${PREFIX_PLUGIN_DATA}/${name()}`,get(bindKeyData))));append($$anchor4,fragment_5)};alternate_4=$$anchor4=>{var div_27=root_19(),div_28=child(div_27),text_13=child(div_28,!0);reset(div_28);reset(div_27);template_effect((()=>set_text(text_13,(deep_read_state(get(modeAll)),untrack((()=>TITLES[get(modeAll)]))))));append($$anchor4,div_27)};if_block(node_8,($$render=>{get(modeAll)==MODE_SELECTIVE||get(modeAll)==MODE_SHINY?$$render(consequent_9):$$render(alternate_4,!1)}));template_effect((($0,$1)=>{set_class(div_12,1,"labelrow "+(get(hideEven)?"hideeven":""),"svelte-10jah2g");set_text(text_5,$0);set_text(text_6,$1)}),[()=>(deep_read_state(get(modeAll)),untrack((()=>getIcon(get(modeAll))))),()=>(get(nameMap),name(),untrack((()=>get(nameMap).get(`plugins/${name()}`)||name())))]);event("click",button_9,(evt=>askMode(evt,`${PREFIX_PLUGIN_ALL}/${name()}`,get(bindKeyAll))));append($$anchor3,fragment_3)}));reset(div_11);append($$anchor2,fragment_1)};if_block(node_2,($$render=>{get(list),untrack((()=>0==get(list).length))?$$render(consequent_2):$$render(alternate_5,!1)}));reset(div_4);node_13=sibling(div_4,2);consequent_10=$$anchor2=>{var button_13,div_29=root_20(),div_30=child(div_29),div_31=sibling(child(div_30),2),select=sibling(child(div_31),2);template_effect((()=>{get(deleteTerm);invalidate_inner_signals((()=>{get(allTerms)}))}));each(select,5,(()=>get(allTerms)),index,(($$anchor3,term)=>{var option_value,option=root_21(),text_14=child(option,!0);reset(option);option_value={};template_effect((()=>{var _a8;set_text(text_14,get(term));option_value!==(option_value=get(term))&&(option.value=null!=(_a8=option.__value=get(term))?_a8:"")}));append($$anchor3,option)}));reset(select);button_13=sibling(select,2);reset(div_31);reset(div_30);reset(div_29);bind_select_value(select,(()=>get(deleteTerm)),($$value=>set(deleteTerm,$$value)));event("click",button_13,(evt=>{deleteAllItems(get(deleteTerm))}));append($$anchor2,div_29)};if_block(node_13,($$render=>{get(isMaintenanceMode)&&$$render(consequent_10)}));label_1=child(div_32=sibling(node_13,2));remove_input_defaults(input=sibling(child(label_1)));reset(label_1);reset(div_32);label_2=child(div_33=sibling(div_32,2));remove_input_defaults(input_1=sibling(child(label_2)));reset(label_2);reset(div_33);event("click",button,(()=>scanAgain()));event("click",button_1,(()=>replicate2()));event("click",button_2,(()=>requestUpdate()));event("click",button_4,(()=>selectAllNewest(!0)));event("click",button_5,(()=>selectAllNewest(!1)));event("click",button_6,(()=>resetSelectNewest()));event("click",button_7,(()=>applyAll()));bind_checked(input,(()=>get(hideEven)),($$value=>set(hideEven,$$value)));bind_checked(input_1,(()=>get(isMaintenanceMode)),($$value=>set(isMaintenanceMode,$$value)));append($$anchor,fragment);pop();$$cleanup()}function serialize(data){var _a8,_b5,_c3,_d2,_e2;let ret="";ret+=":";ret+=data.category+d+data.name+d+data.term+d2;ret+=(null!=(_a8=data.version)?_a8:"")+d2;ret+=data.mtime+d2;for(const file of data.files){ret+=file.filename+d+(null!=(_b5=file.displayName)?_b5:"")+d+(null!=(_c3=file.version)?_c3:"")+d2;const hash3=digestHash(null!=(_d2=file.data)?_d2:[]);ret+=file.mtime+d+file.size+d+hash3+d2;for(const data2 of null!=(_e2=file.data)?_e2:[])ret+=data2+d;ret+=d2}return ret}function splitWithDelimiters(sources){const result=[];for(const str of sources){let startIndex=0;const maxLen=str.length;let i1,i22,i2=-1;do{i1=str.indexOf(d,startIndex);i22=str.indexOf(d2,startIndex);if(-1==i1&&-1==i22)break;i2=-1==i1?i22:-1==i22||i1<i22?i1:i22;result.push(str.slice(startIndex,i2+1));startIndex=i2+1}while(i2<maxLen);startIndex<maxLen&&result.push(str.slice(startIndex))}""==sources[sources.length-1]&&result.push("");return result}function getTokenizer(source2){const sources=splitWithDelimiters(source2);sources[0]=sources[0].substring(1);let pos=0,lineRunOut=!1;return{next(){if(lineRunOut)return"";if(pos>=sources.length)return"";const item=sources[pos];item.endsWith(d2)?lineRunOut=!0:pos++;return item.endsWith(d)||item.endsWith(d2)?item.substring(0,item.length-1):item+this.next()},nextLine(){if(lineRunOut)pos++;else{for(;!sources[pos].endsWith(d2);){pos++;if(pos>=sources.length)break}pos++}lineRunOut=!1}}}function deserialize2(str){const tokens=getTokenizer(str),category=tokens.next(),name=tokens.next(),term=tokens.next();tokens.nextLine();const version2=tokens.next();tokens.nextLine();const mtime=Number(tokens.next());tokens.nextLine();const result=Object.assign({},{category,name,term,version:version2,mtime,files:[]});let filename="";do{filename=tokens.next();if(!filename)break;const displayName=tokens.next(),version3=tokens.next();tokens.nextLine();const mtime2=Number(tokens.next()),size=Number(tokens.next()),hash3=tokens.next();tokens.nextLine();const data=[];let piece="";do{piece=tokens.next();if(""==piece)break;data.push(piece)}while(""!=piece);result.files.push({filename,displayName,version:version3,mtime:mtime2,size,data,hash:hash3});tokens.nextLine()}while(filename);return result}function deserialize(str,def){try{return":"==str[0][0]?deserialize2(str):JSON.parse(str.join(""))}catch(e3){try{return(0,import_obsidian.parseYaml)(str.join(""))}catch(e4){return def}}}function categoryToFolder(category,configDir=""){switch(category){case"CONFIG":return`${configDir}/`;case"THEME":return`${configDir}/themes/`;case"SNIPPET":return`${configDir}/snippets/`;case"PLUGIN_MAIN":return`${configDir}/plugins/`;case"PLUGIN_DATA":return`${configDir}/plugins/`;case"PLUGIN_ETC":return`${configDir}/plugins/`;default:return""}}function setManifest(key3,manifest){const old=pluginManifests.get(key3);if(!old||isObjectDifferent(manifest,old)){pluginManifests.set(key3,manifest);pluginManifestStore.set(pluginManifests)}}function cloneQuery(query3){return Object.keys(query3).reduce(((carry,paramName)=>{const param=query3[paramName];return{...carry,[paramName]:Array.isArray(param)?[...param]:param}}),{})}function isValidHostname(hostname){return/^[a-z0-9][a-z0-9\.\-]*[a-z0-9]$/.test(hostname)}function addExpectContinueMiddleware(options){return next2=>async args=>{var _a8,_b5;const{request:request2}=args;HttpRequest.isInstance(request2)&&request2.body&&"node"===options.runtime&&"FetchHttpHandler"!==(null==(_b5=null==(_a8=options.requestHandler)?void 0:_a8.constructor)?void 0:_b5.name)&&(request2.headers={...request2.headers,Expect:"100-continue"});return next2({...args,request:request2})}}function setCredentialFeature(credentials,feature,value){credentials.$source||(credentials.$source={});credentials.$source[feature]=value;return credentials}function setFeature(context2,feature,value){context2.__aws_sdk_context?context2.__aws_sdk_context.features||(context2.__aws_sdk_context.features={}):context2.__aws_sdk_context={features:{}};context2.__aws_sdk_context.features[feature]=value}function convertHttpAuthSchemesToMap(httpAuthSchemes){const map4=new Map;for(const scheme of httpAuthSchemes)map4.set(scheme.schemeId,scheme);return map4}function getSerdePlugin(config,serializer,deserializer){return{applyToStack:commandStack=>{commandStack.add(deserializerMiddleware(config,deserializer),deserializerMiddlewareOption);commandStack.add(serializerMiddleware(config,serializer),serializerMiddlewareOption)}}}function toBase64(_input){let input;input="string"==typeof _input?fromUtf8(_input):_input;const isArrayLike="object"==typeof input&&"number"==typeof input.length,isUint8Array="object"==typeof input&&"number"==typeof input.byteOffset&&"number"==typeof input.byteLength;if(!isArrayLike&&!isUint8Array)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let str="";for(let i2=0;i2<input.length;i2+=3){let bits2=0,bitLength=0;for(let j2=i2,limit=Math.min(i2+3,input.length);j2<limit;j2++){bits2|=input[j2]<<(limit-j2-1)*bitsPerByte;bitLength+=bitsPerByte}const bitClusterCount=Math.ceil(bitLength/bitsPerLetter);bits2<<=bitClusterCount*bitsPerLetter-bitLength;for(let k2=1;k2<=bitClusterCount;k2++){const offset=(bitClusterCount-k2)*bitsPerLetter;str+=alphabetByValue[(bits2&maxLetterValue<<offset)>>offset]}str+="==".slice(0,4-bitClusterCount)}return str}function transformToString(payload,encoding="utf-8"){return"base64"===encoding?toBase64(payload):toUtf8(payload)}function transformFromString(str,encoding){return"base64"===encoding?Uint8ArrayBlobAdapter.mutate(fromBase64(str)):Uint8ArrayBlobAdapter.mutate(fromUtf8(str))}function merge(buffers,mode,chunk){switch(mode){case 0:buffers[0]+=chunk;return sizeOf(buffers[0]);case 1:case 2:buffers[mode].push(chunk);return sizeOf(buffers[mode])}}function flush(buffers,mode){switch(mode){case 0:const s2=buffers[0];buffers[0]="";return s2;case 1:case 2:return buffers[mode].flush()}throw new Error(`@smithy/util-stream - invalid index ${mode} given to flush()`)}function sizeOf(chunk){var _a8,_b5;return null!=(_b5=null!=(_a8=null==chunk?void 0:chunk.byteLength)?_a8:null==chunk?void 0:chunk.length)?_b5:0}function modeOf(chunk,allowBuffer=!0){return allowBuffer&&"undefined"!=typeof Buffer&&chunk instanceof Buffer?2:chunk instanceof Uint8Array?1:"string"==typeof chunk?0:-1}async function headStream(stream,bytes){var _a8;let byteLengthCounter=0;const chunks=[],reader=stream.getReader();let isDone=!1;for(;!isDone;){const{done,value}=await reader.read();if(value){chunks.push(value);byteLengthCounter+=null!=(_a8=null==value?void 0:value.byteLength)?_a8:0}if(byteLengthCounter>=bytes)break;isDone=done}reader.releaseLock();const collected=new Uint8Array(Math.min(bytes,byteLengthCounter));let offset=0;for(const chunk of chunks){if(chunk.byteLength>collected.byteLength-offset){collected.set(chunk.subarray(0,collected.byteLength-offset),offset);break}collected.set(chunk,offset);offset+=chunk.length}return collected}function buildQueryString(query3){const parts=[];for(let key3 of Object.keys(query3).sort()){const value=query3[key3];key3=escapeUri(key3);if(Array.isArray(value))for(let i2=0,iLen=value.length;i2<iLen;i2++)parts.push(`${key3}=${escapeUri(value[i2])}`);else{let qsEntry=key3;(value||"string"==typeof value)&&(qsEntry+=`=${escapeUri(value)}`);parts.push(qsEntry)}}return parts.join("&")}function createRequest(url,requestOptions){return new Request(url,requestOptions)}function requestTimeout(timeoutInMs=0){return new Promise(((resolve,reject)=>{timeoutInMs&&setTimeout((()=>{const timeoutError=new Error(`Request did not complete within ${timeoutInMs} ms`);timeoutError.name="TimeoutError";reject(timeoutError)}),timeoutInMs)}))}async function collectBlob(blob){const base64=await readToBase64(blob),arrayBuffer=fromBase64(base64);return new Uint8Array(arrayBuffer)}async function collectStream(stream){const chunks=[],reader=stream.getReader();let isDone=!1,length=0;for(;!isDone;){const{done,value}=await reader.read();if(value){chunks.push(value);length+=value.length}isDone=done}const collected=new Uint8Array(length);let offset=0;for(const chunk of chunks){collected.set(chunk,offset);offset+=chunk.length}return collected}function readToBase64(blob){return new Promise(((resolve,reject)=>{const reader=new FileReader;reader.onloadend=()=>{var _a8;if(2!==reader.readyState)return reject(new Error("Reader aborted too early"));const result=null!=(_a8=reader.result)?_a8:"",commaIndex=result.indexOf(","),dataOffset=commaIndex>-1?commaIndex+1:result.length;resolve(result.substring(dataOffset))};reader.onabort=()=>reject(new Error("Read aborted"));reader.onerror=()=>reject(reader.error);reader.readAsDataURL(blob)}))}function fromHex(encoded){if(encoded.length%2!=0)throw new Error("Hex encoded strings must have an even number length");const out=new Uint8Array(encoded.length/2);for(let i2=0;i2<encoded.length;i2+=2){const encodedByte=encoded.slice(i2,i2+2).toLowerCase();if(!(encodedByte in HEX_TO_SHORT))throw new Error(`Cannot decode unrecognized sequence ${encodedByte} as hexadecimal`);out[i2/2]=HEX_TO_SHORT[encodedByte]}return out}function toHex2(bytes){let out="";for(let i2=0;i2<bytes.byteLength;i2++)out+=SHORT_TO_HEX[bytes[i2]];return out}async function splitStream(stream){"function"==typeof stream.stream&&(stream=stream.stream());return stream.tee()}function extendedEncodeURIComponent(str){return encodeURIComponent(str).replace(/[!'()*]/g,(function(c3){return"%"+c3.charCodeAt(0).toString(16).toUpperCase()}))}function requestBuilder(input,context2){return new RequestBuilder(input,context2)}function setFeature2(context2,feature,value){context2.__smithy_context?context2.__smithy_context.features||(context2.__smithy_context.features={}):context2.__smithy_context={features:{}};context2.__smithy_context.features[feature]=value}function negate(bytes){for(let i2=0;i2<8;i2++)bytes[i2]^=255;for(let i2=7;i2>-1;i2--){bytes[i2]++;if(0!==bytes[i2])break}}function normalizeCredentialProvider(config,{credentials,credentialDefaultProvider}){let credentialsProvider;credentialsProvider=credentials?(null==credentials?void 0:credentials.memoized)?credentials:memoizeIdentityProvider(credentials,isIdentityExpired,doesIdentityRequireRefresh):credentialDefaultProvider?normalizeProvider2(credentialDefaultProvider(Object.assign({},config,{parentClientConfig:config}))):async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")};credentialsProvider.memoized=!0;return credentialsProvider}function bindCallerConfig(config,credentialsProvider){if(credentialsProvider.configBound)return credentialsProvider;const fn=async options=>credentialsProvider({...options,callerClientConfig:config});fn.memoized=credentialsProvider.memoized;fn.configBound=!0;return fn}function dateToUtcString(date){const year=date.getUTCFullYear(),month=date.getUTCMonth(),dayOfWeek=date.getUTCDay(),dayOfMonthInt=date.getUTCDate(),hoursInt=date.getUTCHours(),minutesInt=date.getUTCMinutes(),secondsInt=date.getUTCSeconds(),dayOfMonthString=dayOfMonthInt<10?`0${dayOfMonthInt}`:`${dayOfMonthInt}`,hoursString=hoursInt<10?`0${hoursInt}`:`${hoursInt}`,minutesString=minutesInt<10?`0${minutesInt}`:`${minutesInt}`,secondsString=secondsInt<10?`0${secondsInt}`:`${secondsInt}`;return`${DAYS[dayOfWeek]}, ${dayOfMonthString} ${MONTHS[month]} ${year} ${hoursString}:${minutesString}:${secondsString} GMT`}function map2(arg0,arg1,arg2){let target,filter4,instructions;if(void 0===arg1&&void 0===arg2){target={};instructions=arg0}else{target=arg0;if("function"==typeof arg1){filter4=arg1;instructions=arg2;return mapWithFilter(target,filter4,instructions)}instructions=arg1}for(const key3 of Object.keys(instructions))Array.isArray(instructions[key3])?applyInstruction(target,null,instructions,key3):target[key3]=instructions[key3];return target}function quoteHeader(part){(part.includes(",")||part.includes('"'))&&(part=`"${part.replace(/"/g,'\\"')}"`);return part}function __awaiter(thisArg,_arguments,P3,generator){function adopt(value){return value instanceof P3?value:new P3((function(resolve){resolve(value)}))}return new(P3||(P3=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e3){reject(e3)}}function rejected(value){try{step(generator.throw(value))}catch(e3){reject(e3)}}function step(result){result.done?resolve(result.value):adopt(result.value).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))}function __generator(thisArg,body){function verb(n3){return function(v2){return step([n3,v2])}}function step(op){if(f4)throw new TypeError("Generator is already executing.");for(;g2&&(g2=0,op[0]&&(_=0)),_;)try{if(f4=1,y2&&(t3=2&op[0]?y2.return:op[0]?y2.throw||((t3=y2.return)&&t3.call(y2),0):y2.next)&&!(t3=t3.call(y2,op[1])).done)return t3;(y2=0,t3)&&(op=[2&op[0],t3.value]);switch(op[0]){case 0:case 1:t3=op;break;case 4:_.label++;return{value:op[1],done:!1};case 5:_.label++;y2=op[1];op=[0];continue;case 7:op=_.ops.pop();_.trys.pop();continue;default:if(!(t3=_.trys,t3=t3.length>0&&t3[t3.length-1])&&(6===op[0]||2===op[0])){_=0;continue}if(3===op[0]&&(!t3||op[1]>t3[0]&&op[1]<t3[3])){_.label=op[1];break}if(6===op[0]&&_.label<t3[1]){_.label=t3[1];t3=op;break}if(t3&&_.label<t3[2]){_.label=t3[2];_.ops.push(op);break}t3[2]&&_.ops.pop();_.trys.pop();continue}op=body.call(thisArg,_)}catch(e3){op=[6,e3];y2=0}finally{f4=t3=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}var f4,y2,t3,_={label:0,sent:function(){if(1&t3[0])throw t3[1];return t3[1]},trys:[],ops:[]},g2=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return g2.next=verb(0),g2.throw=verb(1),g2.return=verb(2),"function"==typeof Symbol&&(g2[Symbol.iterator]=function(){return this}),g2}function __values(o2){var s2="function"==typeof Symbol&&Symbol.iterator,m3=s2&&o2[s2],i2=0;if(m3)return m3.call(o2);if(o2&&"number"==typeof o2.length)return{next:function(){o2&&i2>=o2.length&&(o2=void 0);return{value:o2&&o2[i2++],done:!o2}}};throw new TypeError(s2?"Object is not iterable.":"Symbol.iterator is not defined.")}function convertToBuffer(data){return data instanceof Uint8Array?data:"string"==typeof data?fromUtf83(data):ArrayBuffer.isView(data)?new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(data)}function isEmptyData(data){return"string"==typeof data?0===data.length:0===data.byteLength}function numToUint8(num){return new Uint8Array([(4278190080&num)>>24,(16711680&num)>>16,(65280&num)>>8,255&num])}function uint32ArrayFrom(a_lookUpTable2){var return_array,a_index;if(!Uint32Array.from){return_array=new Uint32Array(a_lookUpTable2.length);a_index=0;for(;a_index<a_lookUpTable2.length;){return_array[a_index]=a_lookUpTable2[a_index];a_index+=1}return return_array}return Uint32Array.from(a_lookUpTable2)}function resolveHostHeaderConfig(input){return input}function checkContentLengthHeader(){return(next2,context2)=>async args=>{var _a8;const{request:request2}=args;if(HttpRequest.isInstance(request2)&&!(CONTENT_LENGTH_HEADER in request2.headers)&&!(DECODED_CONTENT_LENGTH_HEADER in request2.headers)){const message="Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.";"function"!=typeof(null==(_a8=null==context2?void 0:context2.logger)?void 0:_a8.warn)||context2.logger instanceof NoOpLogger?console.warn(message):context2.logger.warn(message)}return next2({...args})}}function regionRedirectMiddleware(clientConfig){return(next2,context2)=>async args=>{var _a8,_b5,_c3;try{return await next2(args)}catch(err3){if(clientConfig.followRegionRedirects&&(301===(null==(_a8=null==err3?void 0:err3.$metadata)?void 0:_a8.httpStatusCode)||400===(null==(_b5=null==err3?void 0:err3.$metadata)?void 0:_b5.httpStatusCode)&&"IllegalLocationConstraintException"===(null==err3?void 0:err3.name))){try{const actualRegion=err3.$response.headers["x-amz-bucket-region"];null==(_c3=context2.logger)||_c3.debug(`Redirecting from ${await clientConfig.region()} to ${actualRegion}`);context2.__s3RegionRedirect=actualRegion}catch(e3){throw new Error("Region redirect failed: "+e3)}return next2(args)}throw err3}}}function getCredentialsWithoutSessionToken(credentials){return{accessKeyId:credentials.accessKeyId,secretAccessKey:credentials.secretAccessKey,expiration:credentials.expiration}}function setSingleOverride(privateAccess,credentialsWithoutSessionToken){const id=setTimeout((()=>{throw new Error("SignatureV4S3Express credential override was created but not called.")}),10),currentCredentialProvider=privateAccess.credentialProvider;privateAccess.credentialProvider=()=>{clearTimeout(id);privateAccess.credentialProvider=currentCredentialProvider;return Promise.resolve(credentialsWithoutSessionToken)}}function bucketEndpointMiddleware(options){return(next2,context2)=>async args=>{var _a8,_b5,_c3,_d2;if(options.bucketEndpoint){const endpoint=context2.endpointV2;if(endpoint){const bucket=args.input.Bucket;if("string"==typeof bucket)try{const bucketEndpointUrl=new URL(bucket);context2.endpointV2={...endpoint,url:bucketEndpointUrl}}catch(e3){const warning=`@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${bucket} could not be parsed as URL.`;"NoOpLogger"===(null==(_b5=null==(_a8=context2.logger)?void 0:_a8.constructor)?void 0:_b5.name)?console.warn(warning):null==(_d2=null==(_c3=context2.logger)?void 0:_c3.warn)||_d2.call(_c3,warning);throw e3}}}return next2(args)}}function validateBucketNameMiddleware({bucketEndpoint}){return next2=>async args=>{const{input:{Bucket}}=args;if(!bucketEndpoint&&"string"==typeof Bucket&&!validate(Bucket)&&Bucket.indexOf("/")>=0){const err3=new Error(`Bucket name shouldn't contain '/', received '${Bucket}'`);err3.name="InvalidBucketName";throw err3}return next2({...args})}}function isValidUserAgentAppId(appId){return void 0===appId||"string"==typeof appId&&appId.length<=50}function resolveUserAgentConfig(input){var _a8;const normalizedAppIdProvider=normalizeProvider2(null!=(_a8=input.userAgentAppId)?_a8:DEFAULT_UA_APP_ID),{customUserAgent}=input;return Object.assign(input,{customUserAgent:"string"==typeof customUserAgent?[[customUserAgent]]:customUserAgent,userAgentAppId:async()=>{var _a9,_b5;const appId=await normalizedAppIdProvider();if(!isValidUserAgentAppId(appId)){const logger2="NoOpLogger"!==(null==(_b5=null==(_a9=input.logger)?void 0:_a9.constructor)?void 0:_b5.name)&&input.logger?input.logger:console;"string"!=typeof appId?null==logger2||logger2.warn("userAgentAppId must be a string or undefined."):appId.length>50&&(null==logger2||logger2.warn("The provided userAgentAppId exceeds the maximum length of 50 characters."))}return appId}})}function toDebugString(input){return"object"!=typeof input||null==input?input:"ref"in input?`$${toDebugString(input.ref)}`:"fn"in input?`${input.fn}(${(input.argv||[]).map(toDebugString).join(", ")})`:JSON.stringify(input,null,2)}async function checkFeatures(context2,config,args){var _a8,_b5,_c3,_d2,_e2,_f,_g,_h;const request2=args.request;"rpc-v2-cbor"===(null==(_a8=null==request2?void 0:request2.headers)?void 0:_a8["smithy-protocol"])&&setFeature(context2,"PROTOCOL_RPC_V2_CBOR","M");if("function"==typeof config.retryStrategy){const retryStrategy=await config.retryStrategy();"function"==typeof retryStrategy.acquireInitialRetryToken?(null==(_c3=null==(_b5=retryStrategy.constructor)?void 0:_b5.name)?void 0:_c3.includes("Adaptive"))?setFeature(context2,"RETRY_MODE_ADAPTIVE","F"):setFeature(context2,"RETRY_MODE_STANDARD","E"):setFeature(context2,"RETRY_MODE_LEGACY","D")}if("function"==typeof config.accountIdEndpointMode){const endpointV2=context2.endpointV2;String(null==(_d2=null==endpointV2?void 0:endpointV2.url)?void 0:_d2.hostname).match(ACCOUNT_ID_ENDPOINT_REGEX)&&setFeature(context2,"ACCOUNT_ID_ENDPOINT","O");switch(await(null==(_e2=config.accountIdEndpointMode)?void 0:_e2.call(config))){case"disabled":setFeature(context2,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":setFeature(context2,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":setFeature(context2,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const identity=null==(_g=null==(_f=context2.__smithy_context)?void 0:_f.selectedHttpAuthScheme)?void 0:_g.identity;if(null==identity?void 0:identity.$source){const credentials=identity;credentials.accountId&&setFeature(context2,"RESOLVED_ACCOUNT_ID","T");for(const[key3,value]of Object.entries(null!=(_h=credentials.$source)?_h:{}))setFeature(context2,key3,value)}}function encodeFeatures(features){let buffer="";for(const key3 in features){const val2=features[key3];if(!(buffer.length+val2.length+1<=BYTE_LIMIT))break;buffer.length?buffer+=","+val2:buffer+=val2}return buffer}function contentLengthMiddleware(bodyLengthChecker){return next2=>async args=>{const request2=args.request;if(HttpRequest.isInstance(request2)){const{body,headers}=request2;if(body&&-1===Object.keys(headers).map((str=>str.toLowerCase())).indexOf(CONTENT_LENGTH_HEADER2))try{const length=bodyLengthChecker(body);request2.headers={...request2.headers,[CONTENT_LENGTH_HEADER2]:String(length)}}catch(error){}}return next2({...args,request:request2})}}function parseQueryString(querystring){const query3={};if(querystring=querystring.replace(/^\?/,""))for(const pair of querystring.split("&")){let[key3,value=null]=pair.split("=");key3=decodeURIComponent(key3);value&&(value=decodeURIComponent(value));key3 in query3?Array.isArray(query3[key3])?query3[key3].push(value):query3[key3]=[query3[key3],value]:query3[key3]=value}return query3}function rng(){if(!getRandomValues&&!(getRandomValues="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues(rnds8)}function unsafeStringify(arr,offset=0){return byteToHex[arr[offset+0]]+byteToHex[arr[offset+1]]+byteToHex[arr[offset+2]]+byteToHex[arr[offset+3]]+"-"+byteToHex[arr[offset+4]]+byteToHex[arr[offset+5]]+"-"+byteToHex[arr[offset+6]]+byteToHex[arr[offset+7]]+"-"+byteToHex[arr[offset+8]]+byteToHex[arr[offset+9]]+"-"+byteToHex[arr[offset+10]]+byteToHex[arr[offset+11]]+byteToHex[arr[offset+12]]+byteToHex[arr[offset+13]]+byteToHex[arr[offset+14]]+byteToHex[arr[offset+15]]}function createAwsAuthSigv4HttpAuthOption(authParameters){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"s3",region:authParameters.region},propertiesExtractor:(config,context2)=>({signingProperties:{config,context:context2}})}}function createAwsAuthSigv4aHttpAuthOption(authParameters){return{schemeId:"aws.auth#sigv4a",signingProperties:{name:"s3",region:authParameters.region},propertiesExtractor:(config,context2)=>({signingProperties:{config,context:context2}})}}function escapeAttribute(value){return value.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}function escapeElement(value){return value.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/'/g,"&apos;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/\r/g,"&#x0D;").replace(/\n/g,"&#x0A;").replace(/\u0085/g,"&#x85;").replace(/\u2028/,"&#x2028;")}function isEmptyData2(data){return"string"==typeof data?0===data.length:0===data.byteLength}function locateWindow(){return"undefined"!=typeof window?window:"undefined"!=typeof self?self:fallbackWindow}function convertToBuffer2(data){return"string"==typeof data?fromUtf84(data):ArrayBuffer.isView(data)?new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(data)}function supportsWebCrypto(window2){return!(!supportsSecureRandom(window2)||"object"!=typeof window2.crypto.subtle)&&supportsSubtleCrypto(window2.crypto.subtle)}function supportsSecureRandom(window2){return"object"==typeof window2&&"object"==typeof window2.crypto&&"function"==typeof window2.crypto.getRandomValues}function supportsSubtleCrypto(subtle2){return subtle2&&subtleCryptoMethods.every((function(methodName){return"function"==typeof subtle2[methodName]}))}function bufferFromSecret(secret){var bufferHash,buffer,input=convertToBuffer(secret);if(input.byteLength>BLOCK_SIZE){(bufferHash=new RawSha256).update(input);input=bufferHash.digest()}(buffer=new Uint8Array(BLOCK_SIZE)).set(input);return buffer}function negate2(bytes){for(let i2=0;i2<8;i2++)bytes[i2]^=255;for(let i2=7;i2>-1;i2--){bytes[i2]++;if(0!==bytes[i2])break}}function splitMessage({byteLength,byteOffset,buffer}){if(byteLength<MINIMUM_MESSAGE_LENGTH)throw new Error("Provided message too short to accommodate event stream message overhead");const view=new DataView(buffer,byteOffset,byteLength),messageLength=view.getUint32(0,!1);if(byteLength!==messageLength)throw new Error("Reported message length does not match received message length");const headerLength=view.getUint32(PRELUDE_MEMBER_LENGTH,!1),expectedPreludeChecksum=view.getUint32(PRELUDE_LENGTH,!1),expectedMessageChecksum=view.getUint32(byteLength-CHECKSUM_LENGTH,!1),checksummer=(new Crc32).update(new Uint8Array(buffer,byteOffset,PRELUDE_LENGTH));if(expectedPreludeChecksum!==checksummer.digest())throw new Error(`The prelude checksum specified in the message (${expectedPreludeChecksum}) does not match the calculated CRC32 checksum (${checksummer.digest()})`);checksummer.update(new Uint8Array(buffer,byteOffset+PRELUDE_LENGTH,byteLength-(PRELUDE_LENGTH+CHECKSUM_LENGTH)));if(expectedMessageChecksum!==checksummer.digest())throw new Error(`The message checksum (${checksummer.digest()}) did not match the expected value of ${expectedMessageChecksum}`);return{headers:new DataView(buffer,byteOffset+PRELUDE_LENGTH+CHECKSUM_LENGTH,headerLength),body:new Uint8Array(buffer,byteOffset+PRELUDE_LENGTH+CHECKSUM_LENGTH+headerLength,messageLength-headerLength-(PRELUDE_LENGTH+CHECKSUM_LENGTH+CHECKSUM_LENGTH))}}function getChunkedStream(source2){let currentMessageTotalLength=0,currentMessagePendingLength=0,currentMessage=null,messageLengthBuffer=null;const allocateMessage=size=>{if("number"!=typeof size)throw new Error("Attempted to allocate an event message where size was not a number: "+size);currentMessageTotalLength=size;currentMessagePendingLength=4;currentMessage=new Uint8Array(size);new DataView(currentMessage.buffer).setUint32(0,size,!1)};return{[Symbol.asyncIterator]:async function*(){const sourceIterator=source2[Symbol.asyncIterator]();for(;;){const{value,done}=await sourceIterator.next();if(done){if(!currentMessageTotalLength)return;if(currentMessageTotalLength!==currentMessagePendingLength)throw new Error("Truncated event message received.");yield currentMessage;return}const chunkLength=value.length;let currentOffset=0;for(;currentOffset<chunkLength;){if(!currentMessage){const bytesRemaining=chunkLength-currentOffset;messageLengthBuffer||(messageLengthBuffer=new Uint8Array(4));const numBytesForTotal=Math.min(4-currentMessagePendingLength,bytesRemaining);messageLengthBuffer.set(value.slice(currentOffset,currentOffset+numBytesForTotal),currentMessagePendingLength);currentMessagePendingLength+=numBytesForTotal;currentOffset+=numBytesForTotal;if(currentMessagePendingLength<4)break;allocateMessage(new DataView(messageLengthBuffer.buffer).getUint32(0,!1));messageLengthBuffer=null}const numBytesToWrite=Math.min(currentMessageTotalLength-currentMessagePendingLength,chunkLength-currentOffset);currentMessage.set(value.slice(currentOffset,currentOffset+numBytesToWrite),currentMessagePendingLength);currentMessagePendingLength+=numBytesToWrite;currentOffset+=numBytesToWrite;if(currentMessageTotalLength&&currentMessageTotalLength===currentMessagePendingLength){yield currentMessage;currentMessage=null;currentMessageTotalLength=0;currentMessagePendingLength=0}}}}}}function getMessageUnmarshaller(deserializer,toUtf82){return async function(message){const{value:messageType}=message.headers[":message-type"];if("error"===messageType){const unmodeledError=new Error(message.headers[":error-message"].value||"UnknownError");unmodeledError.name=message.headers[":error-code"].value;throw unmodeledError}if("exception"===messageType){const code=message.headers[":exception-type"].value,exception={[code]:message},deserializedException=await deserializer(exception);if(deserializedException.$unknown){const error=new Error(toUtf82(message.body));error.name=code;throw error}throw deserializedException[code]}if("event"===messageType){const event2={[message.headers[":event-type"].value]:message},deserialized=await deserializer(event2);if(deserialized.$unknown)return;return deserialized}throw Error(`Unrecognizable event type: ${message.headers[":event-type"].value}`)}}async function blobReader(blob,onChunk,chunkSize2=1048576){const size=blob.size;let totalBytesRead=0;for(;totalBytesRead<size;){const slice=blob.slice(totalBytesRead,Math.min(size,totalBytesRead+chunkSize2));onChunk(new Uint8Array(await slice.arrayBuffer()));totalBytesRead+=slice.size}}function cmn(q2,a2,b3,x2,s2,t3){return((a2=(a2+q2&4294967295)+(x2+t3&4294967295)&4294967295)<<s2|a2>>>32-s2)+b3&4294967295}function ff(a2,b3,c3,d4,x2,s2,t3){return cmn(b3&c3|~b3&d4,a2,b3,x2,s2,t3)}function gg(a2,b3,c3,d4,x2,s2,t3){return cmn(b3&d4|c3&~d4,a2,b3,x2,s2,t3)}function hh(a2,b3,c3,d4,x2,s2,t3){return cmn(b3^c3^d4,a2,b3,x2,s2,t3)}function ii(a2,b3,c3,d4,x2,s2,t3){return cmn(c3^(b3|~d4),a2,b3,x2,s2,t3)}function isEmptyData3(data){return"string"==typeof data?0===data.length:0===data.byteLength}function convertToBuffer3(data){return"string"==typeof data?fromUtf8(data):ArrayBuffer.isView(data)?new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(data)}function ssecMiddleware(options){return next2=>async args=>{const input={...args.input},properties=[{target:"SSECustomerKey",hash:"SSECustomerKeyMD5"},{target:"CopySourceSSECustomerKey",hash:"CopySourceSSECustomerKeyMD5"}];for(const prop2 of properties){const value=input[prop2.target];if(value){let valueForHash;if("string"==typeof value)if(isValidBase64EncodedSSECustomerKey(value,options))valueForHash=options.base64Decoder(value);else{valueForHash=options.utf8Decoder(value);input[prop2.target]=options.base64Encoder(valueForHash)}else{valueForHash=ArrayBuffer.isView(value)?new Uint8Array(value.buffer,value.byteOffset,value.byteLength):new Uint8Array(value);input[prop2.target]=options.base64Encoder(valueForHash)}const hash3=new options.md5;hash3.update(valueForHash);input[prop2.hash]=options.base64Encoder(await hash3.digest())}}return next2({...args,input})}}function isValidBase64EncodedSSECustomerKey(str,options){if(!/^(?:[A-Za-z0-9+/]{4})*([A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str))return!1;try{return 32===options.base64Decoder(str).length}catch(e3){return!1}}function locationConstraintMiddleware(options){return next2=>async args=>{const{CreateBucketConfiguration}=args.input,region=await options.region();(null==CreateBucketConfiguration?void 0:CreateBucketConfiguration.LocationConstraint)||(null==CreateBucketConfiguration?void 0:CreateBucketConfiguration.Location)||(args={...args,input:{...args.input,CreateBucketConfiguration:"us-east-1"===region?void 0:{LocationConstraint:region}}});return next2(args)}}function deflateSync(data,opts){return dopt(data,opts||{},0,0)}function inflateSync(data,opts){return inflt(data,{i:2},opts&&opts.out,opts&&opts.dictionary)}async function _compressText(text2){const converted=tryConvertBase64ToArrayBuffer(text2),data=new Uint8Array(converted||await new Blob([text2],{type:"application/octet-stream"}).arrayBuffer());if(0==data.buffer.byteLength)return"";const df=await wrappedDeflate(new Uint8Array(data),{consume:!0,level:8});return(converted?"~":"")+await arrayBufferToBase64Single(df)}async function _decompressText(compressed,_useUTF16=!1){if(0==compressed.length)return"";const converted="~"==compressed[0],src=compressed.substring(converted?1:0);if(0==src.length)return"";const ab2=new Uint8Array(base64ToArrayBuffer(src));if(0==ab2.length)return"";const ret=await wrappedInflate(new Uint8Array(ab2),{consume:!0});if(converted)return await arrayBufferToBase64Single(ret);const response=new Blob([ret]);return await response.text()}async function compressDoc(doc){if(!("data"in doc))return doc;if("string"!=typeof doc.data)return doc;if(doc.data.startsWith(MARK_SHIFT_COMPRESSED))return doc;const oldData=doc.data,compressed=await _compressText(oldData),newData=MARK_SHIFT_COMPRESSED+compressed;doc.data.length>newData.length&&(doc.data=newData);return doc}async function decompressDoc(doc){if(!("data"in doc))return doc;if("string"!=typeof doc.data)return doc;doc.data.startsWith(MARK_SHIFT_COMPRESSED)&&(doc.data=await _decompressText(doc.data.substring(MARK_SHIFT_COMPRESSED.length)));return doc}function wrapFflateFunc(func){return(data,opts)=>new Promise(((res2,rej)=>{func(data,opts,((err3,result)=>{err3?rej(err3):res2(new Uint8Array(result))}))}))}function generateId(prefix){if(++idx>1e4){series=`${Date.now()}`;idx=0}return`${PREFIX_TRENCH}-${prefix}-${series}-${idx+1e7}`}function createRange(prefix,series2){return[`${PREFIX_TRENCH}-${prefix}-${series2}-`,`${PREFIX_TRENCH}-${prefix}-${series2}.`]}function createId(prefix,series2,idx2){return`${PREFIX_TRENCH}-${prefix}-${series2}-${idx2+1e7}`}function createSyncParamsHanderForServer(key3,options){if(_handlers.has(key3))return _handlers.get(key3);const handler=createSyncParamsHandler(options);_handlers.set(key3,handler);return handler}function clearHandlers(){_handlers.clear()}function createSyncParamsHandler({put,get:get4,create}){let taskFetchParameters;const _fetchSyncParameters=async()=>{let syncParams;try{let shouldRetry=!1;do{shouldRetry=!1;try{syncParams=await get4();Logger("Fetched synchronisation parameters",LOG_LEVEL_INFO)}catch(ex){if(!LiveSyncError.isCausedBy(ex,SyncParamsNotFoundError))throw ex;{Logger("Synchronisation parameters not found, creating new ones",LOG_LEVEL_INFO);const newSyncParams=await create();if(!await put(newSyncParams)){Logger("Failed to store initial synchronisation parameters",LOG_LEVEL_INFO);throw new SyncParamsUpdateError("Failed to store initial synchronisation parameters")}Logger("Initial synchronisation parameters stored successfully, retrying fetch",LOG_LEVEL_INFO);shouldRetry=!0}}}while(shouldRetry);if(!syncParams)throw new SyncParamsFetchError("Unexpected empty synchronisation parameters");if(!syncParams.pbkdf2salt){Logger("Synchronisation parameters do not have PBKDF2 salt, generating a new salt",LOG_LEVEL_INFO);const salt=await arrayBufferToBase64Single(createPBKDF2Salt());if(!salt){Logger("Failed to generate PBKDF2 salt",LOG_LEVEL_INFO);throw new SyncParamsFetchError("Failed to generate PBKDF2 salt")}syncParams.pbkdf2salt=salt;if(!await put(syncParams)){Logger("Failed to store synchronisation parameters with new PBKDF2 salt",LOG_LEVEL_INFO);throw new SyncParamsUpdateError("Failed to store synchronisation parameters with new PBKDF2 salt")}syncParams=await get4()}if(!syncParams)throw new Error("Failed to prepare synchronisation key in synchronisation parameters");Logger("Synchronisation parameters fetched successfully",LOG_LEVEL_INFO);if(!syncParams.pbkdf2saltDecoded){const decodedSalt=new Uint8Array(base64ToArrayBufferInternalBrowser(syncParams.pbkdf2salt));if(!decodedSalt)throw new SyncParamsFetchError("Failed to decode PBKDF2 salt");syncParams.pbkdf2saltDecoded=decodedSalt}return syncParams}catch(ex){Logger("Failed to fetch synchronisation parameters",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE);taskFetchParameters=void 0;return!1}},fetchSyncParameters=(refresh=!1)=>{if(taskFetchParameters&&!refresh)return taskFetchParameters;taskFetchParameters=_fetchSyncParameters();return taskFetchParameters};return{fetch:fetchSyncParameters,getPBKDF2Salt:async(refresh=!1)=>{const syncParams=await fetchSyncParameters(refresh);if(!syncParams){Logger("Failed to fetch synchronisation parameters",LOG_LEVEL_INFO);throw new SyncParamsFetchError("Failed to fetch synchronisation parameters")}return syncParams.pbkdf2saltDecoded}}}function serializeDoc(doc){if(doc._id.startsWith("h:")){const writeData=escapeNewLineFromString(doc.data);return te4.encode(`~${doc._id}${UNIT_SPLIT}${writeData}${RECORD_SPLIT}`)}return te4.encode(JSON.stringify(doc)+RECORD_SPLIT)}function resetV3Buf(){_nonceV3[0]=0;const _wk=webcrypto3.getRandomValues(new Uint8Array(12));bufV3.set(_wk);bufV3.set(_nonceV3,8)}function incIV(){_nonceV3[0]++;bufV3.set(_nonceV3,8);_nonceV3[0]>1500&&resetV3Buf();return bufV3}async function generateKey(passphrase){const passphraseBin=(new TextEncoder).encode(passphrase),salt=(await webcrypto3.subtle.digest("SHA-256",new Uint8Array([...passphraseBin,...SALT]))).slice(0,16),baseKey=await webcrypto3.subtle.importKey("raw",passphraseBin,"PBKDF2",!1,["deriveBits","deriveKey"]),pbkdf2Params={name:"PBKDF2",hash:"SHA-256",salt,iterations:1e5};return await webcrypto3.subtle.deriveKey(pbkdf2Params,baseKey,{name:"AES-GCM",length:256},!1,["decrypt","encrypt"])}async function encryptV3(input,passphrase){if(previousPassphrase!==passphrase){resetV3Buf();const key3=await generateKey(passphrase);encryptionKey=key3;previousPassphrase=passphrase}const iv=incIV(),dataBuf=writeString(input),encryptedDataArrayBuffer=await webcrypto3.subtle.encrypt({name:"AES-GCM",iv},encryptionKey,dataBuf),encryptedData2=""+await arrayBufferToBase64Single(new Uint8Array(encryptedDataArrayBuffer));return`%~${uint8ArrayToHexString(iv)}${encryptedData2}`}async function decryptV3(encryptedResult,passphrase){if(previousDecryptionPassphrase!==passphrase){const key3=await generateKey(passphrase);decryptionKey=key3;previousDecryptionPassphrase=passphrase}const ivStr=encryptedResult.substring(2,26),encryptedData=encryptedResult.substring(26),iv=hexStringToUint8Array(ivStr),encryptedDataArrayBuffer=base64ToArrayBuffer(encryptedData),dataBuffer=await webcrypto3.subtle.decrypt({name:"AES-GCM",iv},decryptionKey,encryptedDataArrayBuffer);return readString(new Uint8Array(dataBuffer))}async function obfuscatePath(path2,passphrase,autoCalculateIterations){const dataBuf=writeString(path2),[key3,salt,iv]=await getKeyForObfuscatePath(passphrase,dataBuf,autoCalculateIterations),encryptedDataArrayBuffer=await webcrypto4.subtle.encrypt({name:"AES-GCM",iv},key3,dataBuf),encryptedData2=await arrayBufferToBase64Single(new Uint8Array(encryptedDataArrayBuffer));return`%${uint8ArrayToHexString(iv)}${uint8ArrayToHexString(salt)}${encryptedData2}`}function isPathProbablyObfuscated(path2){return path2.startsWith("%")&&path2.length>64}async function getKeyForObfuscatePath(passphrase,dataBuf,autoCalculateIterations){const passphraseLen=15-passphrase.length,iteration=autoCalculateIterations?1e3*(passphraseLen>0?passphraseLen:0)+121-passphraseLen:1e5,passphraseBin=(new TextEncoder).encode(passphrase),digest=await webcrypto4.subtle.digest({name:"SHA-256"},passphraseBin),buf2=new Uint8Array(await webcrypto4.subtle.digest({name:"SHA-256"},new Uint8Array([...dataBuf,...passphraseBin]))),salt=buf2.slice(0,16),iv=buf2.slice(16,32),keyMaterial=await webcrypto4.subtle.importKey("raw",digest,{name:"PBKDF2"},!1,["deriveKey"]);return[await webcrypto4.subtle.deriveKey({name:"PBKDF2",salt,iterations:iteration,hash:"SHA-256"},keyMaterial,{name:"AES-GCM",length:256},!1,["encrypt"]),salt,iv]}async function getKeyForEncrypt(passphrase,autoCalculateIterations){const buffKey=`${passphrase}-${autoCalculateIterations}`,f4=KeyBuffs.get(buffKey);if(f4){f4.count--;if(f4.count>0)return[f4.key,f4.salt];f4.count--}const passphraseLen=15-passphrase.length,iteration=autoCalculateIterations?1e3*(passphraseLen>0?passphraseLen:0)+121-passphraseLen:1e5,passphraseBin=(new TextEncoder).encode(passphrase),digest=await webcrypto5.subtle.digest({name:"SHA-256"},passphraseBin),keyMaterial=await webcrypto5.subtle.importKey("raw",digest,{name:"PBKDF2"},!1,["deriveKey"]),salt=webcrypto5.getRandomValues(new Uint8Array(16)),key3=await webcrypto5.subtle.deriveKey({name:"PBKDF2",salt,iterations:iteration,hash:"SHA-256"},keyMaterial,{name:"AES-GCM",length:256},!1,["encrypt"]);KeyBuffs.set(buffKey,{key:key3,salt,count:KEY_RECYCLE_COUNT});return[key3,salt]}async function getKeyForDecryption(passphrase,salt,autoCalculateIterations){if(--keyGCCount<0){keyGCCount=KEY_RECYCLE_COUNT;const threshold=(decKeyIdx-decKeyMin)/2;for(const[key4,buff]of decKeyBuffs){buff.count<threshold&&decKeyBuffs.delete(key4);decKeyMin=decKeyIdx}}decKeyIdx++;const bufKey=passphrase+uint8ArrayToHexString(salt)+autoCalculateIterations,f4=decKeyBuffs.get(bufKey);if(f4){f4.count=decKeyIdx;return[f4.key,f4.salt]}const passphraseLen=15-passphrase.length,iteration=autoCalculateIterations?1e3*(passphraseLen>0?passphraseLen:0)+121-passphraseLen:1e5,passphraseBin=(new TextEncoder).encode(passphrase),digest=await webcrypto5.subtle.digest({name:"SHA-256"},passphraseBin),keyMaterial=await webcrypto5.subtle.importKey("raw",digest,{name:"PBKDF2"},!1,["deriveKey"]),key3=await webcrypto5.subtle.deriveKey({name:"PBKDF2",salt,iterations:iteration,hash:"SHA-256"},keyMaterial,{name:"AES-GCM",length:256},!1,["decrypt"]);decKeyBuffs.set(bufKey,{key:key3,salt,count:0});return[key3,salt]}function getSemiStaticField(reset2){return null==semiStaticFieldBuffer||reset2?semiStaticFieldBuffer=webcrypto5.getRandomValues(new Uint8Array(12)):semiStaticFieldBuffer}function getNonce(){nonceBuffer[0]++;nonceBuffer[0]>1e4&&getSemiStaticField(!0);return nonceBuffer}async function encrypt4(input,passphrase,autoCalculateIterations){const[key3,salt]=await getKeyForEncrypt(passphrase,autoCalculateIterations),fixedPart=getSemiStaticField(),invocationPart=getNonce(),iv=new Uint8Array([...fixedPart,...new Uint8Array(invocationPart.buffer)]),dataBuf=writeString(input),encryptedDataArrayBuffer=await webcrypto5.subtle.encrypt({name:"AES-GCM",iv},key3,dataBuf),encryptedData2=""+await arrayBufferToBase64Single(new Uint8Array(encryptedDataArrayBuffer));return`%${uint8ArrayToHexString(iv)}${uint8ArrayToHexString(salt)}${encryptedData2}`}async function decryptV2(encryptedResult,passphrase,autoCalculateIterations){try{const ivStr=encryptedResult.substring(1,33),salt=encryptedResult.substring(33,65),encryptedData=encryptedResult.substring(65),[key3]=await getKeyForDecryption(passphrase,hexStringToUint8Array(salt),autoCalculateIterations),iv=hexStringToUint8Array(ivStr),encryptedDataArrayBuffer=decodeBinary(encryptedData),dataBuffer=await webcrypto5.subtle.decrypt({name:"AES-GCM",iv},key3,encryptedDataArrayBuffer);return readString(new Uint8Array(dataBuffer))}catch(ex){Logger("Couldn't decode! You should wrong the passphrases (V2)",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);throw ex}}async function decrypt4(encryptedResult,passphrase,autoCalculateIterations){try{if("%"==encryptedResult[0])return"~"===encryptedResult[1]?decryptV3(encryptedResult,passphrase):decryptV2(encryptedResult,passphrase,autoCalculateIterations);if(!encryptedResult.startsWith("[")||!encryptedResult.endsWith("]"))throw new Error("Encrypted data corrupted!");const w2=encryptedResult.substring(1,encryptedResult.length-1).split(",").map((e3=>'"'==e3[0]?e3.substring(1,e3.length-1):e3)),[encryptedData,ivString,salt]=w2,[key3]=await getKeyForDecryption(passphrase,hexStringToUint8Array(salt),autoCalculateIterations),iv=hexStringToUint8Array(ivString),encryptedDataBin=atob(encryptedData),len=encryptedDataBin.length,encryptedDataArrayBuffer=new Uint8Array(len);for(let i2=len;i2>=0;--i2)encryptedDataArrayBuffer[i2]=encryptedDataBin.charCodeAt(i2);const plainStringBuffer=await webcrypto5.subtle.decrypt({name:"AES-GCM",iv},key3,encryptedDataArrayBuffer),plainStringified=readString(new Uint8Array(plainStringBuffer));return JSON.parse(plainStringified)}catch(ex){Logger("Couldn't decode! You should wrong the passphrases",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);throw ex}}async function testCryptV3(){const src="✨supercalifragilisticexpialidocious✨⛰",encoded=await encryptV3(src,"passwordTest");if(src!=await decrypt4(encoded,"passwordTest",!1)){Logger("WARNING! Your device would not support encryption V3.",LOG_LEVEL_VERBOSE);return!1}Logger("CRYPT LOGIC (V3) OK",LOG_LEVEL_VERBOSE);return!0}async function testCrypt(){const src="✨supercalifragilisticexpialidocious✨⛰",encoded=await encrypt4(src,"passwordTest",!1);if(src!=await decrypt4(encoded,"passwordTest",!1)){Logger("WARNING! Your device would not support encryption.",LOG_LEVEL_VERBOSE);return!1}{Logger("CRYPT LOGIC OK",LOG_LEVEL_VERBOSE);const w2=writeString(src),encodedBinary=await encryptBinary2(w2,"passwordTest",!1),decryptedBinary=await decryptBinary2(encodedBinary,"passwordTest",!1);if(w2.join("-")!==decryptedBinary.join("-")){Logger("WARNING! Your device would not support encryption (Binary).",LOG_LEVEL_VERBOSE);return!1}Logger("CRYPT LOGIC OK (Binary)",LOG_LEVEL_VERBOSE);return await testCryptV3()&&await testEncryptionFeature()}}async function encryptBinary2(input,passphrase,autoCalculateIterations){const[key3,salt]=await getKeyForEncrypt(passphrase,autoCalculateIterations),fixedPart=getSemiStaticField(),invocationPart=getNonce(),iv=new Uint8Array([...fixedPart,...new Uint8Array(invocationPart.buffer)]),dataBuf=input,encryptedDataArrayBuffer=new Uint8Array(await webcrypto5.subtle.encrypt({name:"AES-GCM",iv},key3,dataBuf)),ret=new Uint8Array(encryptedDataArrayBuffer.byteLength+iv.byteLength+salt.byteLength);ret.set(iv,0);ret.set(salt,iv.byteLength);ret.set(encryptedDataArrayBuffer,iv.byteLength+salt.byteLength);return ret}async function decryptBinary2(encryptedResult,passphrase,autoCalculateIterations){try{const iv=encryptedResult.slice(0,16),salt=encryptedResult.slice(16,32),encryptedData=encryptedResult.slice(32),[key3]=await getKeyForDecryption(passphrase,salt,autoCalculateIterations),dataBuffer=await webcrypto5.subtle.decrypt({name:"AES-GCM",iv},key3,encryptedData);return new Uint8Array(dataBuffer)}catch(ex){Logger("Couldn't decode! You should wrong the passphrases (V2 Bin)",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);throw ex}}async function ensureRemoteIsCompatible(infoSrc,setting,deviceNodeID,currentVersionRange3,nodeDeviceInfo,updateCallback){var _a8,_b5,_c3,_d2;const now3=Date.now(),baseMilestone={_id:MILESTONE_DOCID,type:"milestoneinfo",created:new Date/1,locked:!1,accepted_nodes:[deviceNodeID],node_chunk_info:{[deviceNodeID]:currentVersionRange3},node_info:{[deviceNodeID]:{...nodeDeviceInfo,last_connected:0,progress:""}},tweak_values:{}};let remoteMilestone=infoSrc;remoteMilestone||(remoteMilestone=baseMilestone);const currentTweakValues=extractObject(TweakValuesTemplate,setting);remoteMilestone.node_chunk_info={...baseMilestone.node_chunk_info,...remoteMilestone.node_chunk_info};let writeMilestone=remoteMilestone.node_chunk_info[deviceNodeID].min!=currentVersionRange3.min||remoteMilestone.node_chunk_info[deviceNodeID].max!=currentVersionRange3.max||isObjectDifferent(null==(_a8=remoteMilestone.tweak_values)?void 0:_a8[deviceNodeID],currentTweakValues)||void 0===remoteMilestone._rev||!(DEVICE_ID_PREFERRED in remoteMilestone.tweak_values);remoteMilestone.node_info||(remoteMilestone.node_info={});if(!(deviceNodeID in remoteMilestone.node_info)){remoteMilestone.node_info[deviceNodeID]={...nodeDeviceInfo,last_connected:0,progress:""};writeMilestone=!0}const info3=remoteMilestone.node_info[deviceNodeID],keys3=["device_name","app_version","plugin_version","vault_name","progress"];for(const key3 of keys3)if(info3[key3]!=nodeDeviceInfo[key3]){remoteMilestone.node_info[deviceNodeID][key3]=nodeDeviceInfo[key3];writeMilestone=!0}if(now3-(remoteMilestone.node_info[deviceNodeID].last_connected||0)>6e4){remoteMilestone.node_info[deviceNodeID].last_connected=now3;writeMilestone=!0}if(writeMilestone){remoteMilestone.node_chunk_info[deviceNodeID].min=currentVersionRange3.min;remoteMilestone.node_chunk_info[deviceNodeID].max=currentVersionRange3.max;remoteMilestone.tweak_values={...null!=(_b5=remoteMilestone.tweak_values)?_b5:{},[deviceNodeID]:currentTweakValues};DEVICE_ID_PREFERRED in remoteMilestone.tweak_values||(remoteMilestone.tweak_values[DEVICE_ID_PREFERRED]=currentTweakValues);await updateCallback(remoteMilestone)}let globalMin=currentVersionRange3.min,globalMax=currentVersionRange3.max;for(const nodeId of remoteMilestone.accepted_nodes)if(nodeId!=deviceNodeID)if(nodeId in remoteMilestone.node_chunk_info){const nodeInfo=remoteMilestone.node_chunk_info[nodeId];globalMin=Math.max(nodeInfo.min,globalMin);globalMax=Math.min(nodeInfo.max,globalMax)}else{globalMin=0;globalMax=0}if(globalMax<globalMin&&!setting.ignoreVersionCheck)return"INCOMPATIBLE";if(!setting.disableCheckingConfigMismatch){const preferred_tweak=null!=(_d2=null==(_c3=remoteMilestone.tweak_values)?void 0:_c3[DEVICE_ID_PREFERRED])?_d2:currentTweakValues,current_tweak=currentTweakValues;if(isObjectDifferent(extractObject(TweakValuesShouldMatchedTemplate,{...TweakValuesDefault,...preferred_tweak}),extractObject(TweakValuesShouldMatchedTemplate,{...TweakValuesDefault,...current_tweak}),!0))return["MISMATCHED",preferred_tweak]}return remoteMilestone.locked?-1==remoteMilestone.accepted_nodes.indexOf(deviceNodeID)?remoteMilestone.cleaned?"NODE_CLEANED":"NODE_LOCKED":"LOCKED":"OK"}async function ensureDatabaseIsCompatible(db,setting,deviceNodeID,currentVersionRange3,nodeDeviceInfo){const remoteMilestone=await resolveWithIgnoreKnownError(db.get(MILESTONE_DOCID),!1);return await ensureRemoteIsCompatible(remoteMilestone,setting,deviceNodeID,currentVersionRange3,nodeDeviceInfo,(async info3=>{await db.put(info3)}))}async function countCompromisedChunks(db){try{Logger("Counting compromised chunks...",LOG_LEVEL_VERBOSE);const task1=db.find(SELECTOR_COMPROMISED_CHUNK_1),task2=db.find(SELECTOR_COMPROMISED_CHUNK_2),[result1,result2]=await Promise.all([task1,task2]);return result1.docs.length+result2.docs.length}catch(ex){Logger("Error counting compromised chunks!",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}function inlineWorker(scriptText){let blob=new Blob([scriptText],{type:"text/javascript"}),url=URL.createObjectURL(blob),worker=new Worker(url);URL.revokeObjectURL(url);return worker}function Worker2(){return inlineWorker('var Nn=Object.defineProperty,Fn=Object.defineProperties;var kn=Object.getOwnPropertyDescriptors;var gt=Object.getOwnPropertySymbols;var Un=Object.prototype.hasOwnProperty,Mn=Object.prototype.propertyIsEnumerable;var ie=(n,e)=>(e=Symbol[n])?e:Symbol.for("Symbol."+n),We=n=>{throw TypeError(n)};var He=(n,e,t)=>e in n?Nn(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,G=(n,e)=>{for(var t in e||(e={}))Un.call(e,t)&&He(n,t,e[t]);if(gt)for(var t of gt(e))Mn.call(e,t)&&He(n,t,e[t]);return n},oe=(n,e)=>Fn(n,kn(e));var P=(n,e,t)=>He(n,typeof e!="symbol"?e+"":e,t),Ge=(n,e,t)=>e.has(n)||We("Cannot "+t);var p=(n,e,t)=>(Ge(n,e,"read from private field"),t?t.call(n):e.get(n)),v=(n,e,t)=>e.has(n)?We("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),w=(n,e,t,r)=>(Ge(n,e,"write to private field"),r?r.call(n,t):e.set(n,t),t),J=(n,e,t)=>(Ge(n,e,"access private method"),t);var j=function(n,e){this[0]=n,this[1]=e},Se=(n,e,t)=>{var r=(o,a,c,u)=>{try{var l=t[o](a),h=(a=l.value)instanceof j,y=l.done;Promise.resolve(h?a[0]:a).then(d=>h?r(o==="return"?o:"next",a[1]?{done:d.done,value:d.value}:d,c,u):c({value:d,done:y})).catch(d=>r("throw",d,c,u))}catch(d){u(d)}},s=o=>i[o]=a=>new Promise((c,u)=>r(o,a,c,u)),i={};return t=t.apply(n,e),i[ie("asyncIterator")]=()=>i,s("next"),s("throw"),s("return"),i},M=n=>{var e=n[ie("asyncIterator")],t=!1,r,s={};return e==null?(e=n[ie("iterator")](),r=i=>s[i]=o=>e[i](o)):(e=e.call(n),r=i=>s[i]=o=>{if(t){if(t=!1,i==="throw")throw o;return o}return t=!0,{done:!1,value:new j(new Promise(a=>{var c=e[i](o);c instanceof Object||We("Object expected"),a(c)}),1)}}),s[ie("iterator")]=()=>s,r("next"),"throw"in e?r("throw"):s.throw=i=>{throw i},"return"in e&&r("return"),s},je=(n,e,t)=>(e=n[ie("asyncIterator")])?e.call(n):(n=n[ie("iterator")](),e={},t=(r,s)=>(s=n[r])&&(e[r]=i=>new Promise((o,a,c)=>(i=s.call(n,i),c=i.done,Promise.resolve(i.value).then(u=>o({value:u,done:c}),a)))),t("next"),t("return"),e);var Kn={minLogLevel:32},Vn=function(e,t=32,r){if(t<Kn.minLogLevel)return;let i=new Date().toLocaleString(),o=typeof e=="string"?e:e instanceof Error?`${e.name}:${e.message}`:JSON.stringify(e,null,2),a=`${i}\t${t}\t${o}`;t&1?console.debug(a):t&4?console.warn(a):t&8?console.error(a):t&2?console.info(a):console.log(a),e instanceof Error&&console.dir(e.stack)},Hn=Vn;function L(n,e,t){Hn(n,e,t)}var mt=typeof Uint8Array!="undefined"&&typeof Uint8Array.prototype.toBase64=="function"&&typeof Uint8Array.fromBase64=="function";function Et(n){if(n.length===0)return new ArrayBuffer(0);try{if(typeof n=="string")return Uint8Array.fromBase64(n).buffer;let e=n.map(i=>Uint8Array.fromBase64(i).buffer),t=e.reduce((i,o)=>i+o.byteLength,0),r=new Uint8Array(t),s=0;return e.forEach(i=>{r.set(new Uint8Array(i),s),s+=i.byteLength}),r.buffer}catch(e){return L("Base64 Decode error",16),L(e,16),new ArrayBuffer(0)}}function bt(n){if(typeof n=="string")return xe(n);let e=n.map(i=>xe(i)),t=e.reduce((i,o)=>i+o.byteLength,0),r=new Uint8Array(t),s=0;return e.forEach(i=>{r.set(new Uint8Array(i),s),s+=i.byteLength}),r.buffer}var X=mt?Et:bt;function xe(n){try{let e=globalThis.atob(n),t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return r.buffer}catch(e){return L("Base64 Decode error",16),L(e,16),new ArrayBuffer(0)}}var Di=3*5e7;function Wn(n){return new Promise((e,t)=>{let r=new Blob([n],{type:"application/octet-binary"}),s=new FileReader;s.onload=function(i){var c,u;let o=((u=(c=i.target)==null?void 0:c.result)==null?void 0:u.toString())||"";if(n.byteLength!=0&&(o==""||o=="data:"))return t(new TypeError("Could not parse the encoded string"));let a=o.substring(o.indexOf(",")+1);e(a)},s.readAsDataURL(r)})}async function St(n){let e=n instanceof Uint8Array?n:new Uint8Array(n);return e.byteLength<At?btoa(String.fromCharCode.apply(null,[...e])):await Wn(e)}function xt(n){let e=n instanceof Uint8Array?n:new Uint8Array(n);return Promise.resolve(e.toBase64())}var O=mt?xt:St;var At=32768,Gn=new TextEncoder,jn=new TextDecoder;function C(n){if(n.length>128)return Gn.encode(n);let e=new Uint8Array(n.length*4),t=n.length,r=0,s=0,i=0;for(;i<t;)s=n.charCodeAt(i++),s<128?e[r++]=s:s<2048?(e[r++]=192|s>>>6,e[r++]=128|s&63):s<55296||s>57343?(e[r++]=224|s>>>12,e[r++]=128|s>>>6&63,e[r++]=128|s&63):(s=(s-55296<<10|n.charCodeAt(i++)-56320)+65536,e[r++]=240|s>>>18,e[r++]=128|s>>>12&63,e[r++]=128|s>>>6&63,e[r++]=128|s&63);return e.slice(0,r)}function F(n){let e=n.length;if(e>128)return jn.decode(n);let t=0,r=e,s="";for(;t<r;){let i=[],o=Math.min(t+At,r);for(;t<o;){let a=n[t++];if(a<128)i.push(a);else if((a&224)===192)i.push((a&31)<<6|n[t++]&63);else if((a&240)===224)i.push((a&15)<<12|(n[t++]&63)<<6|n[t++]&63);else if((a&248)===240){let c=(a&7)<<18|(n[t++]&63)<<12|(n[t++]&63)<<6|n[t++]&63;c<65536?i.push(c):(c-=65536,i.push((c>>>10)+55296,(c&1023)+56320))}}s+=String.fromCharCode(...i)}return s}function*wt(n,e){for(let t=n;t<=e;t++)yield t}var Ri=1024*1024*30,$n={},Pt={};[...wt(192,447)].forEach((n,e)=>{$n[e]=n,Pt[n]=e});function $e(n){if(n.length==1)return Ae(n[0]);let e=n.map(i=>Ae(i)),t=e.reduce((i,o)=>i+o.byteLength,0),r=new Uint8Array(t),s=0;return e.forEach(i=>{r.set(new Uint8Array(i),s),s+=i.byteLength}),r.buffer}function Ae(n){let e=new Uint8Array(n.length),t=n.length;for(let r=0;r<t;r++){let s=n.charCodeAt(r);s>=38&&s<=126&&s!=58?e[r]=s:e[r]=Pt[s]}return e.buffer}var Tt={},_t={};for(let n=0;n<256;n++)Tt[`00${n.toString(16)}`.slice(-2)]=n,_t[n]=`00${n.toString(16)}`.slice(-2);var Ct=typeof Uint8Array!="undefined"&&typeof Uint8Array.prototype.toBase64=="function"&&typeof Uint8Array.fromBase64=="function",$=Ct?Dt:Ot;function Dt(n){return Uint8Array.fromHex(n)}function Ot(n){let e=n.length/2,t=new Uint8Array(e);for(let r=0;r<e;r++)t[r]=Tt[n[r*2]+n[r*2+1]];return t}var N=Ct?Lt:It;function It(n){return[...n].map(e=>_t[e]).join("")}function Lt(n){return n.toHex()}function we(n){if(n.length==0)return new Uint8Array().buffer;if(typeof n=="string"){if(n[0]==="%")return Ae(n.substring(1))}else if(n[0][0]==="%"){let[e,...t]=n;return $e([e.substring(1),...t])}return X(n)}var Pe=class{constructor(e,t,r=!1){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map([])}),Object.defineProperty(this,"revCache",{enumerable:!0,configurable:!0,writable:!0,value:new Map([])}),Object.defineProperty(this,"maxCache",{enumerable:!0,configurable:!0,writable:!0,value:200}),Object.defineProperty(this,"maxCachedLength",{enumerable:!0,configurable:!0,writable:!0,value:5e7}),Object.defineProperty(this,"cachedLength",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"enableReversed",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.maxCache=e||200,this.maxCachedLength=(t||1)*1e6,this.enableReversed=!r,L(`Cache initialized ${this.maxCache} / ${this.maxCachedLength}`,16)}clear(){this.cache.clear(),this.revCache.clear()}has(e){return this.cache.has(e)}get(e){let t=this.cache.get(e);return t&&(this.cache.delete(e),this.cache.set(e,t),this.enableReversed&&(this.revCache.delete(t),this.revCache.set(t,e))),t}revGet(e){let t=this.revCache.get(e);return t&&(this.cache.delete(t),this.revCache.delete(e),this.cache.set(t,e),this.revCache.set(e,t)),t}set(e,t){if(this.cache.set(e,t),this.enableReversed&&this.revCache.set(t,e),this.cachedLength+=`${t}`.length,this.cache.size>this.maxCache||this.cachedLength>this.maxCachedLength){for(let[r,s]of this.cache)if(this.cache.delete(r),this.enableReversed&&this.revCache.delete(s),this.cachedLength-=`${s}`.length,this.cache.size<=this.maxCache&&this.cachedLength<=this.maxCachedLength)break}}};var ze=(n,e,t)=>{let r=n instanceof RegExp?Rt(n,t):n,s=e instanceof RegExp?Rt(e,t):e,i=r!==null&&s!=null&&Xn(r,s,t);return i&&{start:i[0],end:i[1],pre:t.slice(0,i[0]),body:t.slice(i[0]+r.length,i[1]),post:t.slice(i[1]+s.length)}},Rt=(n,e)=>{let t=e.match(n);return t?t[0]:null},Xn=(n,e,t)=>{let r,s,i,o,a,c=t.indexOf(n),u=t.indexOf(e,c+1),l=c;if(c>=0&&u>0){if(n===e)return[c,u];for(r=[],i=t.length;l>=0&&!a;){if(l===c)r.push(l),c=t.indexOf(n,l+1);else if(r.length===1){let h=r.pop();h!==void 0&&(a=[h,u])}else s=r.pop(),s!==void 0&&s<i&&(i=s,o=u),u=t.indexOf(e,l+1);l=c<u&&c>=0?c:u}r.length&&o!==void 0&&(a=[i,o])}return a};var Bt="\\0SLASH"+Math.random()+"\\0",vt="\\0OPEN"+Math.random()+"\\0",Je="\\0CLOSE"+Math.random()+"\\0",Nt="\\0COMMA"+Math.random()+"\\0",Ft="\\0PERIOD"+Math.random()+"\\0",qn=new RegExp(Bt,"g"),Zn=new RegExp(vt,"g"),Qn=new RegExp(Je,"g"),er=new RegExp(Nt,"g"),tr=new RegExp(Ft,"g"),nr=/\\\\\\\\/g,rr=/\\\\{/g,sr=/\\\\}/g,ir=/\\\\,/g,or=/\\\\./g;function Ye(n){return isNaN(n)?n.charCodeAt(0):parseInt(n,10)}function ar(n){return n.replace(nr,Bt).replace(rr,vt).replace(sr,Je).replace(ir,Nt).replace(or,Ft)}function cr(n){return n.replace(qn,"\\\\").replace(Zn,"{").replace(Qn,"}").replace(er,",").replace(tr,".")}function kt(n){if(!n)return[""];let e=[],t=ze("{","}",n);if(!t)return n.split(",");let{pre:r,body:s,post:i}=t,o=r.split(",");o[o.length-1]+="{"+s+"}";let a=kt(i);return i.length&&(o[o.length-1]+=a.shift(),o.push.apply(o,a)),e.push.apply(e,o),e}function Ut(n){return n?(n.slice(0,2)==="{}"&&(n="\\\\{\\\\}"+n.slice(2)),pe(ar(n),!0).map(cr)):[]}function lr(n){return"{"+n+"}"}function ur(n){return/^-?0\\d/.test(n)}function fr(n,e){return n<=e}function pr(n,e){return n>=e}function pe(n,e){let t=[],r=ze("{","}",n);if(!r)return[n];let s=r.pre,i=r.post.length?pe(r.post,!1):[""];if(/\\$$/.test(r.pre))for(let o=0;o<i.length;o++){let a=s+"{"+r.body+"}"+i[o];t.push(a)}else{let o=/^-?\\d+\\.\\.-?\\d+(?:\\.\\.-?\\d+)?$/.test(r.body),a=/^[a-zA-Z]\\.\\.[a-zA-Z](?:\\.\\.-?\\d+)?$/.test(r.body),c=o||a,u=r.body.indexOf(",")>=0;if(!c&&!u)return r.post.match(/,(?!,).*\\}/)?(n=r.pre+"{"+r.body+Je+r.post,pe(n)):[n];let l;if(c)l=r.body.split(/\\.\\./);else if(l=kt(r.body),l.length===1&&l[0]!==void 0&&(l=pe(l[0],!1).map(lr),l.length===1))return i.map(y=>r.pre+l[0]+y);let h;if(c&&l[0]!==void 0&&l[1]!==void 0){let y=Ye(l[0]),d=Ye(l[1]),E=Math.max(l[0].length,l[1].length),f=l.length===3&&l[2]!==void 0?Math.abs(Ye(l[2])):1,b=fr;d<y&&(f*=-1,b=pr);let x=l.some(ur);h=[];for(let m=y;b(m,d);m+=f){let S;if(a)S=String.fromCharCode(m),S==="\\\\"&&(S="");else if(S=String(m),x){let W=E-S.length;if(W>0){let V=new Array(W+1).join("0");m<0?S="-"+V+S.slice(1):S=V+S}}h.push(S)}}else{h=[];for(let y=0;y<l.length;y++)h.push.apply(h,pe(l[y],!1))}for(let y=0;y<h.length;y++)for(let d=0;d<i.length;d++){let E=s+h[y]+i[d];(!e||c||E)&&t.push(E)}}return t}var ye=n=>{if(typeof n!="string")throw new TypeError("invalid pattern");if(n.length>65536)throw new TypeError("pattern is too long")};var yr={"[:alnum:]":["\\\\p{L}\\\\p{Nl}\\\\p{Nd}",!0],"[:alpha:]":["\\\\p{L}\\\\p{Nl}",!0],"[:ascii:]":["\\\\x00-\\\\x7f",!1],"[:blank:]":["\\\\p{Zs}\\\\t",!0],"[:cntrl:]":["\\\\p{Cc}",!0],"[:digit:]":["\\\\p{Nd}",!0],"[:graph:]":["\\\\p{Z}\\\\p{C}",!0,!0],"[:lower:]":["\\\\p{Ll}",!0],"[:print:]":["\\\\p{C}",!0],"[:punct:]":["\\\\p{P}",!0],"[:space:]":["\\\\p{Z}\\\\t\\\\r\\\\n\\\\v\\\\f",!0],"[:upper:]":["\\\\p{Lu}",!0],"[:word:]":["\\\\p{L}\\\\p{Nl}\\\\p{Nd}\\\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},he=n=>n.replace(/[[\\]\\\\-]/g,"\\\\$&"),hr=n=>n.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g,"\\\\$&"),Mt=n=>n.join(""),Kt=(n,e)=>{let t=e;if(n.charAt(t)!=="[")throw new Error("not in a brace expression");let r=[],s=[],i=t+1,o=!1,a=!1,c=!1,u=!1,l=t,h="";e:for(;i<n.length;){let f=n.charAt(i);if((f==="!"||f==="^")&&i===t+1){u=!0,i++;continue}if(f==="]"&&o&&!c){l=i+1;break}if(o=!0,f==="\\\\"&&!c){c=!0,i++;continue}if(f==="["&&!c){for(let[b,[g,x,m]]of Object.entries(yr))if(n.startsWith(b,i)){if(h)return["$.",!1,n.length-t,!0];i+=b.length,m?s.push(g):r.push(g),a=a||x;continue e}}if(c=!1,h){f>h?r.push(he(h)+"-"+he(f)):f===h&&r.push(he(f)),h="",i++;continue}if(n.startsWith("-]",i+1)){r.push(he(f+"-")),i+=2;continue}if(n.startsWith("-",i+1)){h=f,i+=2;continue}r.push(he(f)),i++}if(l<i)return["",!1,0,!1];if(!r.length&&!s.length)return["$.",!1,n.length-t,!0];if(s.length===0&&r.length===1&&/^\\\\?.$/.test(r[0])&&!u){let f=r[0].length===2?r[0].slice(-1):r[0];return[hr(f),!1,l-t,!1]}let y="["+(u?"^":"")+Mt(r)+"]",d="["+(u?"":"^")+Mt(s)+"]";return[r.length&&s.length?"("+y+"|"+d+")":r.length?y:d,a,l-t,!0]};var q=(n,{windowsPathsNoEscape:e=!1,magicalBraces:t=!0}={})=>t?e?n.replace(/\\[([^\\/\\\\])\\]/g,"$1"):n.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g,"$1$2").replace(/\\\\([^\\/])/g,"$1"):e?n.replace(/\\[([^\\/\\\\{}])\\]/g,"$1"):n.replace(/((?!\\\\).|^)\\[([^\\/\\\\{}])\\]/g,"$1$2").replace(/\\\\([^\\/{}])/g,"$1");var dr=new Set(["!","?","+","*","@"]),Vt=n=>dr.has(n),gr="(?!(?:^|/)\\\\.\\\\.?(?:$|/))",Te="(?!\\\\.)",mr=new Set(["[","."]),Er=new Set(["..","."]),br=new Set("().*{}+?[]^$\\\\!"),Sr=n=>n.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g,"\\\\$&"),qe="[^/]",Ht=qe+"*?",Wt=qe+"+?",_,D,z,A,T,Z,ne,Q,H,re,de,se,Gt,ee,_e,Xe,jt,B=class B{constructor(e,t,r={}){v(this,se);P(this,"type");v(this,_);v(this,D);v(this,z,!1);v(this,A,[]);v(this,T);v(this,Z);v(this,ne);v(this,Q,!1);v(this,H);v(this,re);v(this,de,!1);this.type=e,e&&w(this,D,!0),w(this,T,t),w(this,_,p(this,T)?p(p(this,T),_):this),w(this,H,p(this,_)===this?r:p(p(this,_),H)),w(this,ne,p(this,_)===this?[]:p(p(this,_),ne)),e==="!"&&!p(p(this,_),Q)&&p(this,ne).push(this),w(this,Z,p(this,T)?p(p(this,T),A).length:0)}get hasMagic(){if(p(this,D)!==void 0)return p(this,D);for(let e of p(this,A))if(typeof e!="string"&&(e.type||e.hasMagic))return w(this,D,!0);return p(this,D)}toString(){return p(this,re)!==void 0?p(this,re):this.type?w(this,re,this.type+"("+p(this,A).map(e=>String(e)).join("|")+")"):w(this,re,p(this,A).map(e=>String(e)).join(""))}push(...e){for(let t of e)if(t!==""){if(typeof t!="string"&&!(t instanceof B&&p(t,T)===this))throw new Error("invalid part: "+t);p(this,A).push(t)}}toJSON(){var t;let e=this.type===null?p(this,A).slice().map(r=>typeof r=="string"?r:r.toJSON()):[this.type,...p(this,A).map(r=>r.toJSON())];return this.isStart()&&!this.type&&e.unshift([]),this.isEnd()&&(this===p(this,_)||p(p(this,_),Q)&&((t=p(this,T))==null?void 0:t.type)==="!")&&e.push({}),e}isStart(){var t;if(p(this,_)===this)return!0;if(!((t=p(this,T))!=null&&t.isStart()))return!1;if(p(this,Z)===0)return!0;let e=p(this,T);for(let r=0;r<p(this,Z);r++){let s=p(e,A)[r];if(!(s instanceof B&&s.type==="!"))return!1}return!0}isEnd(){var t,r,s;if(p(this,_)===this||((t=p(this,T))==null?void 0:t.type)==="!")return!0;if(!((r=p(this,T))!=null&&r.isEnd()))return!1;if(!this.type)return(s=p(this,T))==null?void 0:s.isEnd();let e=p(this,T)?p(p(this,T),A).length:0;return p(this,Z)===e-1}copyIn(e){typeof e=="string"?this.push(e):this.push(e.clone(this))}clone(e){let t=new B(this.type,e);for(let r of p(this,A))t.copyIn(r);return t}static fromGlob(e,t={}){var s;let r=new B(null,void 0,t);return J(s=B,ee,_e).call(s,e,r,0,t),r}toMMPattern(){if(this!==p(this,_))return p(this,_).toMMPattern();let e=this.toString(),[t,r,s,i]=this.toRegExpSource();if(!(s||p(this,D)||p(this,H).nocase&&!p(this,H).nocaseMagicOnly&&e.toUpperCase()!==e.toLowerCase()))return r;let a=(p(this,H).nocase?"i":"")+(i?"u":"");return Object.assign(new RegExp(`^${t}$`,a),{_src:t,_glob:e})}get options(){return p(this,H)}toRegExpSource(e){var c;let t=e!=null?e:!!p(this,H).dot;if(p(this,_)===this&&J(this,se,Gt).call(this),!this.type){let u=this.isStart()&&this.isEnd()&&!p(this,A).some(E=>typeof E!="string"),l=p(this,A).map(E=>{var m;let[f,b,g,x]=typeof E=="string"?J(m=B,ee,jt).call(m,E,p(this,D),u):E.toRegExpSource(e);return w(this,D,p(this,D)||g),w(this,z,p(this,z)||x),f}).join(""),h="";if(this.isStart()&&typeof p(this,A)[0]=="string"&&!(p(this,A).length===1&&Er.has(p(this,A)[0]))){let f=mr,b=t&&f.has(l.charAt(0))||l.startsWith("\\\\.")&&f.has(l.charAt(2))||l.startsWith("\\\\.\\\\.")&&f.has(l.charAt(4)),g=!t&&!e&&f.has(l.charAt(0));h=b?gr:g?Te:""}let y="";return this.isEnd()&&p(p(this,_),Q)&&((c=p(this,T))==null?void 0:c.type)==="!"&&(y="(?:$|\\\\/)"),[h+l+y,q(l),w(this,D,!!p(this,D)),p(this,z)]}let r=this.type==="*"||this.type==="+",s=this.type==="!"?"(?:(?!(?:":"(?:",i=J(this,se,Xe).call(this,t);if(this.isStart()&&this.isEnd()&&!i&&this.type!=="!"){let u=this.toString();return w(this,A,[u]),this.type=null,w(this,D,void 0),[u,q(this.toString()),!1,!1]}let o=!r||e||t||!Te?"":J(this,se,Xe).call(this,!0);o===i&&(o=""),o&&(i=`(?:${i})(?:${o})*?`);let a="";if(this.type==="!"&&p(this,de))a=(this.isStart()&&!t?Te:"")+Wt;else{let u=this.type==="!"?"))"+(this.isStart()&&!t&&!e?Te:"")+Ht+")":this.type==="@"?")":this.type==="?"?")?":this.type==="+"&&o?")":this.type==="*"&&o?")?":`)${this.type}`;a=s+i+u}return[a,q(i),w(this,D,!!p(this,D)),p(this,z)]}};_=new WeakMap,D=new WeakMap,z=new WeakMap,A=new WeakMap,T=new WeakMap,Z=new WeakMap,ne=new WeakMap,Q=new WeakMap,H=new WeakMap,re=new WeakMap,de=new WeakMap,se=new WeakSet,Gt=function(){if(this!==p(this,_))throw new Error("should only call on root");if(p(this,Q))return this;this.toString(),w(this,Q,!0);let e;for(;e=p(this,ne).pop();){if(e.type!=="!")continue;let t=e,r=p(t,T);for(;r;){for(let s=p(t,Z)+1;!r.type&&s<p(r,A).length;s++)for(let i of p(e,A)){if(typeof i=="string")throw new Error("string part in extglob AST??");i.copyIn(p(r,A)[s])}t=r,r=p(t,T)}}return this},ee=new WeakSet,_e=function(e,t,r,s){var d,E;let i=!1,o=!1,a=-1,c=!1;if(t.type===null){let f=r,b="";for(;f<e.length;){let g=e.charAt(f++);if(i||g==="\\\\"){i=!i,b+=g;continue}if(o){f===a+1?(g==="^"||g==="!")&&(c=!0):g==="]"&&!(f===a+2&&c)&&(o=!1),b+=g;continue}else if(g==="["){o=!0,a=f,c=!1,b+=g;continue}if(!s.noext&&Vt(g)&&e.charAt(f)==="("){t.push(b),b="";let x=new B(g,t);f=J(d=B,ee,_e).call(d,e,x,f,s),t.push(x);continue}b+=g}return t.push(b),f}let u=r+1,l=new B(null,t),h=[],y="";for(;u<e.length;){let f=e.charAt(u++);if(i||f==="\\\\"){i=!i,y+=f;continue}if(o){u===a+1?(f==="^"||f==="!")&&(c=!0):f==="]"&&!(u===a+2&&c)&&(o=!1),y+=f;continue}else if(f==="["){o=!0,a=u,c=!1,y+=f;continue}if(Vt(f)&&e.charAt(u)==="("){l.push(y),y="";let b=new B(f,l);l.push(b),u=J(E=B,ee,_e).call(E,e,b,u,s);continue}if(f==="|"){l.push(y),y="",h.push(l),l=new B(null,t);continue}if(f===")")return y===""&&p(t,A).length===0&&w(t,de,!0),l.push(y),y="",t.push(...h,l),u;y+=f}return t.type=null,w(t,D,void 0),w(t,A,[e.substring(r-1)]),u},Xe=function(e){return p(this,A).map(t=>{if(typeof t=="string")throw new Error("string type in extglob ast??");let[r,s,i,o]=t.toRegExpSource(e);return w(this,z,p(this,z)||o),r}).filter(t=>!(this.isStart()&&this.isEnd())||!!t).join("|")},jt=function(e,t,r=!1){let s=!1,i="",o=!1;for(let a=0;a<e.length;a++){let c=e.charAt(a);if(s){s=!1,i+=(br.has(c)?"\\\\":"")+c;continue}if(c==="\\\\"){a===e.length-1?i+="\\\\\\\\":s=!0;continue}if(c==="["){let[u,l,h,y]=Kt(e,a);if(h){i+=u,o=o||l,a+=h-1,t=t||y;continue}}if(c==="*"){i+=r&&e==="*"?Wt:Ht,t=!0;continue}if(c==="?"){i+=qe,t=!0;continue}i+=Sr(c)}return[i,q(e),!!t,o]},v(B,ee);var ae=B;var Ze=(n,{windowsPathsNoEscape:e=!1,magicalBraces:t=!1}={})=>t?e?n.replace(/[?*()[\\]{}]/g,"[$&]"):n.replace(/[?*()[\\]\\\\{}]/g,"\\\\$&"):e?n.replace(/[?*()[\\]]/g,"[$&]"):n.replace(/[?*()[\\]\\\\]/g,"\\\\$&");var I=(n,e,t={})=>(ye(e),!t.nocomment&&e.charAt(0)==="#"?!1:new ce(e,t).match(n)),xr=/^\\*+([^+@!?\\*\\[\\(]*)$/,Ar=n=>e=>!e.startsWith(".")&&e.endsWith(n),wr=n=>e=>e.endsWith(n),Pr=n=>(n=n.toLowerCase(),e=>!e.startsWith(".")&&e.toLowerCase().endsWith(n)),Tr=n=>(n=n.toLowerCase(),e=>e.toLowerCase().endsWith(n)),_r=/^\\*+\\.\\*+$/,Cr=n=>!n.startsWith(".")&&n.includes("."),Dr=n=>n!=="."&&n!==".."&&n.includes("."),Or=/^\\.\\*+$/,Ir=n=>n!=="."&&n!==".."&&n.startsWith("."),Lr=/^\\*+$/,Rr=n=>n.length!==0&&!n.startsWith("."),Br=n=>n.length!==0&&n!=="."&&n!=="..",vr=/^\\?+([^+@!?\\*\\[\\(]*)?$/,Nr=([n,e=""])=>{let t=Yt([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},Fr=([n,e=""])=>{let t=Jt([n]);return e?(e=e.toLowerCase(),r=>t(r)&&r.toLowerCase().endsWith(e)):t},kr=([n,e=""])=>{let t=Jt([n]);return e?r=>t(r)&&r.endsWith(e):t},Ur=([n,e=""])=>{let t=Yt([n]);return e?r=>t(r)&&r.endsWith(e):t},Yt=([n])=>{let e=n.length;return t=>t.length===e&&!t.startsWith(".")},Jt=([n])=>{let e=n.length;return t=>t.length===e&&t!=="."&&t!==".."},Xt=typeof process=="object"&&process?typeof process.env=="object"&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix",$t={win32:{sep:"\\\\"},posix:{sep:"/"}},Mr=Xt==="win32"?$t.win32.sep:$t.posix.sep;I.sep=Mr;var U=Symbol("globstar **");I.GLOBSTAR=U;var Kr="[^/]",Vr=Kr+"*?",Hr="(?:(?!(?:\\\\/|^)(?:\\\\.{1,2})($|\\\\/)).)*?",Wr="(?:(?!(?:\\\\/|^)\\\\.).)*?",Gr=(n,e={})=>t=>I(t,n,e);I.filter=Gr;var k=(n,e={})=>Object.assign({},n,e),jr=n=>{if(!n||typeof n!="object"||!Object.keys(n).length)return I;let e=I;return Object.assign((r,s,i={})=>e(r,s,k(n,i)),{Minimatch:class extends e.Minimatch{constructor(s,i={}){super(s,k(n,i))}static defaults(s){return e.defaults(k(n,s)).Minimatch}},AST:class extends e.AST{constructor(s,i,o={}){super(s,i,k(n,o))}static fromGlob(s,i={}){return e.AST.fromGlob(s,k(n,i))}},unescape:(r,s={})=>e.unescape(r,k(n,s)),escape:(r,s={})=>e.escape(r,k(n,s)),filter:(r,s={})=>e.filter(r,k(n,s)),defaults:r=>e.defaults(k(n,r)),makeRe:(r,s={})=>e.makeRe(r,k(n,s)),braceExpand:(r,s={})=>e.braceExpand(r,k(n,s)),match:(r,s,i={})=>e.match(r,s,k(n,i)),sep:e.sep,GLOBSTAR:U})};I.defaults=jr;var qt=(n,e={})=>(ye(n),e.nobrace||!/\\{(?:(?!\\{).)*\\}/.test(n)?[n]:Ut(n));I.braceExpand=qt;var $r=(n,e={})=>new ce(n,e).makeRe();I.makeRe=$r;var zr=(n,e,t={})=>{let r=new ce(e,t);return n=n.filter(s=>r.match(s)),r.options.nonull&&!n.length&&n.push(e),n};I.match=zr;var zt=/[?*]|[+@!]\\(.*?\\)|\\[|\\]/,Yr=n=>n.replace(/[-[\\]{}()*+?.,\\\\^$|#\\s]/g,"\\\\$&"),ce=class{constructor(e,t={}){P(this,"options");P(this,"set");P(this,"pattern");P(this,"windowsPathsNoEscape");P(this,"nonegate");P(this,"negate");P(this,"comment");P(this,"empty");P(this,"preserveMultipleSlashes");P(this,"partial");P(this,"globSet");P(this,"globParts");P(this,"nocase");P(this,"isWindows");P(this,"platform");P(this,"windowsNoMagicRoot");P(this,"regexp");ye(e),t=t||{},this.options=t,this.pattern=e,this.platform=t.platform||Xt,this.isWindows=this.platform==="win32",this.windowsPathsNoEscape=!!t.windowsPathsNoEscape||t.allowWindowsEscape===!1,this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\\\/g,"/")),this.preserveMultipleSlashes=!!t.preserveMultipleSlashes,this.regexp=null,this.negate=!1,this.nonegate=!!t.nonegate,this.comment=!1,this.empty=!1,this.partial=!!t.partial,this.nocase=!!this.options.nocase,this.windowsNoMagicRoot=t.windowsNoMagicRoot!==void 0?t.windowsNoMagicRoot:!!(this.isWindows&&this.nocase),this.globSet=[],this.globParts=[],this.set=[],this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(let e of this.set)for(let t of e)if(typeof t!="string")return!0;return!1}debug(...e){}make(){let e=this.pattern,t=this.options;if(!t.nocomment&&e.charAt(0)==="#"){this.comment=!0;return}if(!e){this.empty=!0;return}this.parseNegate(),this.globSet=[...new Set(this.braceExpand())],t.debug&&(this.debug=(...i)=>console.error(...i)),this.debug(this.pattern,this.globSet);let r=this.globSet.map(i=>this.slashSplit(i));this.globParts=this.preprocess(r),this.debug(this.pattern,this.globParts);let s=this.globParts.map((i,o,a)=>{if(this.isWindows&&this.windowsNoMagicRoot){let c=i[0]===""&&i[1]===""&&(i[2]==="?"||!zt.test(i[2]))&&!zt.test(i[3]),u=/^[a-z]:/i.test(i[0]);if(c)return[...i.slice(0,4),...i.slice(4).map(l=>this.parse(l))];if(u)return[i[0],...i.slice(1).map(l=>this.parse(l))]}return i.map(c=>this.parse(c))});if(this.debug(this.pattern,s),this.set=s.filter(i=>i.indexOf(!1)===-1),this.isWindows)for(let i=0;i<this.set.length;i++){let o=this.set[i];o[0]===""&&o[1]===""&&this.globParts[i][2]==="?"&&typeof o[3]=="string"&&/^[a-z]:$/i.test(o[3])&&(o[2]="?")}this.debug(this.pattern,this.set)}preprocess(e){if(this.options.noglobstar)for(let r=0;r<e.length;r++)for(let s=0;s<e[r].length;s++)e[r][s]==="**"&&(e[r][s]="*");let{optimizationLevel:t=1}=this.options;return t>=2?(e=this.firstPhasePreProcess(e),e=this.secondPhasePreProcess(e)):t>=1?e=this.levelOneOptimize(e):e=this.adjascentGlobstarOptimize(e),e}adjascentGlobstarOptimize(e){return e.map(t=>{let r=-1;for(;(r=t.indexOf("**",r+1))!==-1;){let s=r;for(;t[s+1]==="**";)s++;s!==r&&t.splice(r,s-r)}return t})}levelOneOptimize(e){return e.map(t=>(t=t.reduce((r,s)=>{let i=r[r.length-1];return s==="**"&&i==="**"?r:s===".."&&i&&i!==".."&&i!=="."&&i!=="**"?(r.pop(),r):(r.push(s),r)},[]),t.length===0?[""]:t))}levelTwoFileOptimize(e){Array.isArray(e)||(e=this.slashSplit(e));let t=!1;do{if(t=!1,!this.preserveMultipleSlashes){for(let s=1;s<e.length-1;s++){let i=e[s];s===1&&i===""&&e[0]===""||(i==="."||i==="")&&(t=!0,e.splice(s,1),s--)}e[0]==="."&&e.length===2&&(e[1]==="."||e[1]==="")&&(t=!0,e.pop())}let r=0;for(;(r=e.indexOf("..",r+1))!==-1;){let s=e[r-1];s&&s!=="."&&s!==".."&&s!=="**"&&(t=!0,e.splice(r-1,2),r-=2)}}while(t);return e.length===0?[""]:e}firstPhasePreProcess(e){let t=!1;do{t=!1;for(let r of e){let s=-1;for(;(s=r.indexOf("**",s+1))!==-1;){let o=s;for(;r[o+1]==="**";)o++;o>s&&r.splice(s+1,o-s);let a=r[s+1],c=r[s+2],u=r[s+3];if(a!==".."||!c||c==="."||c===".."||!u||u==="."||u==="..")continue;t=!0,r.splice(s,1);let l=r.slice(0);l[s]="**",e.push(l),s--}if(!this.preserveMultipleSlashes){for(let o=1;o<r.length-1;o++){let a=r[o];o===1&&a===""&&r[0]===""||(a==="."||a==="")&&(t=!0,r.splice(o,1),o--)}r[0]==="."&&r.length===2&&(r[1]==="."||r[1]==="")&&(t=!0,r.pop())}let i=0;for(;(i=r.indexOf("..",i+1))!==-1;){let o=r[i-1];if(o&&o!=="."&&o!==".."&&o!=="**"){t=!0;let c=i===1&&r[i+1]==="**"?["."]:[];r.splice(i-1,2,...c),r.length===0&&r.push(""),i-=2}}}}while(t);return e}secondPhasePreProcess(e){for(let t=0;t<e.length-1;t++)for(let r=t+1;r<e.length;r++){let s=this.partsMatch(e[t],e[r],!this.preserveMultipleSlashes);if(s){e[t]=[],e[r]=s;break}}return e.filter(t=>t.length)}partsMatch(e,t,r=!1){let s=0,i=0,o=[],a="";for(;s<e.length&&i<t.length;)if(e[s]===t[i])o.push(a==="b"?t[i]:e[s]),s++,i++;else if(r&&e[s]==="**"&&t[i]===e[s+1])o.push(e[s]),s++;else if(r&&t[i]==="**"&&e[s]===t[i+1])o.push(t[i]),i++;else if(e[s]==="*"&&t[i]&&(this.options.dot||!t[i].startsWith("."))&&t[i]!=="**"){if(a==="b")return!1;a="a",o.push(e[s]),s++,i++}else if(t[i]==="*"&&e[s]&&(this.options.dot||!e[s].startsWith("."))&&e[s]!=="**"){if(a==="a")return!1;a="b",o.push(t[i]),s++,i++}else return!1;return e.length===t.length&&o}parseNegate(){if(this.nonegate)return;let e=this.pattern,t=!1,r=0;for(let s=0;s<e.length&&e.charAt(s)==="!";s++)t=!t,r++;r&&(this.pattern=e.slice(r)),this.negate=t}matchOne(e,t,r=!1){let s=this.options;if(this.isWindows){let f=typeof e[0]=="string"&&/^[a-z]:$/i.test(e[0]),b=!f&&e[0]===""&&e[1]===""&&e[2]==="?"&&/^[a-z]:$/i.test(e[3]),g=typeof t[0]=="string"&&/^[a-z]:$/i.test(t[0]),x=!g&&t[0]===""&&t[1]===""&&t[2]==="?"&&typeof t[3]=="string"&&/^[a-z]:$/i.test(t[3]),m=b?3:f?0:void 0,S=x?3:g?0:void 0;if(typeof m=="number"&&typeof S=="number"){let[W,V]=[e[m],t[S]];W.toLowerCase()===V.toLowerCase()&&(t[S]=W,S>m?t=t.slice(S):m>S&&(e=e.slice(m)))}}let{optimizationLevel:i=1}=this.options;i>=2&&(e=this.levelTwoFileOptimize(e)),this.debug("matchOne",this,{file:e,pattern:t}),this.debug("matchOne",e.length,t.length);for(var o=0,a=0,c=e.length,u=t.length;o<c&&a<u;o++,a++){this.debug("matchOne loop");var l=t[a],h=e[o];if(this.debug(t,l,h),l===!1)return!1;if(l===U){this.debug("GLOBSTAR",[t,l,h]);var y=o,d=a+1;if(d===u){for(this.debug("** at the end");o<c;o++)if(e[o]==="."||e[o]===".."||!s.dot&&e[o].charAt(0)===".")return!1;return!0}for(;y<c;){var E=e[y];if(this.debug(`\nglobstar while`,e,y,t,d,E),this.matchOne(e.slice(y),t.slice(d),r))return this.debug("globstar found match!",y,c,E),!0;if(E==="."||E===".."||!s.dot&&E.charAt(0)==="."){this.debug("dot detected!",e,y,t,d);break}this.debug("globstar swallow a segment, and continue"),y++}return!!(r&&(this.debug(`\n>>> no match, partial?`,e,y,t,d),y===c))}let f;if(typeof l=="string"?(f=h===l,this.debug("string match",l,h,f)):(f=l.test(h),this.debug("pattern match",l,h,f)),!f)return!1}if(o===c&&a===u)return!0;if(o===c)return r;if(a===u)return o===c-1&&e[o]==="";throw new Error("wtf?")}braceExpand(){return qt(this.pattern,this.options)}parse(e){ye(e);let t=this.options;if(e==="**")return U;if(e==="")return"";let r,s=null;(r=e.match(Lr))?s=t.dot?Br:Rr:(r=e.match(xr))?s=(t.nocase?t.dot?Tr:Pr:t.dot?wr:Ar)(r[1]):(r=e.match(vr))?s=(t.nocase?t.dot?Fr:Nr:t.dot?kr:Ur)(r):(r=e.match(_r))?s=t.dot?Dr:Cr:(r=e.match(Or))&&(s=Ir);let i=ae.fromGlob(e,this.options).toMMPattern();return s&&typeof i=="object"&&Reflect.defineProperty(i,"test",{value:s}),i}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let e=this.set;if(!e.length)return this.regexp=!1,this.regexp;let t=this.options,r=t.noglobstar?Vr:t.dot?Hr:Wr,s=new Set(t.nocase?["i"]:[]),i=e.map(c=>{let u=c.map(h=>{if(h instanceof RegExp)for(let y of h.flags.split(""))s.add(y);return typeof h=="string"?Yr(h):h===U?U:h._src});u.forEach((h,y)=>{let d=u[y+1],E=u[y-1];h!==U||E===U||(E===void 0?d!==void 0&&d!==U?u[y+1]="(?:\\\\/|"+r+"\\\\/)?"+d:u[y]=r:d===void 0?u[y-1]=E+"(?:\\\\/|\\\\/"+r+")?":d!==U&&(u[y-1]=E+"(?:\\\\/|\\\\/"+r+"\\\\/)"+d,u[y+1]=U))});let l=u.filter(h=>h!==U);if(this.partial&&l.length>=1){let h=[];for(let y=1;y<=l.length;y++)h.push(l.slice(0,y).join("/"));return"(?:"+h.join("|")+")"}return l.join("/")}).join("|"),[o,a]=e.length>1?["(?:",")"]:["",""];i="^"+o+i+a+"$",this.partial&&(i="^(?:\\\\/|"+o+i.slice(1,-1)+a+")$"),this.negate&&(i="^(?!"+i+").+$");try{this.regexp=new RegExp(i,[...s].join(""))}catch(c){this.regexp=!1}return this.regexp}slashSplit(e){return this.preserveMultipleSlashes?e.split("/"):this.isWindows&&/^\\/\\/[^\\/]+/.test(e)?["",...e.split(/\\/+/)]:e.split(/\\/+/)}match(e,t=this.partial){if(this.debug("match",e,this.pattern),this.comment)return!1;if(this.empty)return e==="";if(e==="/"&&t)return!0;let r=this.options;this.isWindows&&(e=e.split("\\\\").join("/"));let s=this.slashSplit(e);this.debug(this.pattern,"split",s);let i=this.set;this.debug(this.pattern,"set",i);let o=s[s.length-1];if(!o)for(let a=s.length-2;!o&&a>=0;a--)o=s[a];for(let a=0;a<i.length;a++){let c=i[a],u=s;if(r.matchBase&&c.length===1&&(u=[o]),this.matchOne(u,c,t))return r.flipNegate?!0:!this.negate}return r.flipNegate?!1:this.negate}static defaults(e){return I.defaults(e).Minimatch}};I.AST=ae;I.Minimatch=ce;I.escape=Ze;I.unescape=q;var le;async function Zt(){return le||(globalThis.crypto?(le=globalThis.crypto,le):(le=(await import("crypto")).webcrypto,le))}var Qt=Symbol("timed out"),Jr=Symbol("NotFound");var ko=Symbol("cancelled"),Uo=Symbol("auto_merged"),Mo=Symbol("not_conflicted"),Ko=Symbol("missing_or_error"),Vo=Symbol("leave_to_subsequent_proc"),Ho=Symbol("infinity");var Xr=10,qr=Xr,Qe={REMOTE_COUCHDB:"",REMOTE_MINIO:"MINIO",REMOTE_P2P:"ONLY_P2P"},Zr=Qe.REMOTE_COUCHDB,Wo=Qe.REMOTE_MINIO,Go=Qe.REMOTE_P2P;var Qr={P2P_Enabled:!1,P2P_AutoAccepting:0,P2P_AppID:"self-hosted-livesync",P2P_roomID:"",P2P_passphrase:"",P2P_relays:"wss://exp-relay.vrtmrz.net/",P2P_AutoBroadcast:!1,P2P_AutoStart:!1,P2P_AutoSyncPeers:"",P2P_AutoWatchPeers:"",P2P_SyncOnReplication:"",P2P_RebuildFrom:"",P2P_AutoAcceptingPeers:"",P2P_AutoDenyingPeers:"",P2P_IsHeadless:!1,P2P_DevicePeerName:"",P2P_turnServers:"",P2P_turnUsername:"",P2P_turnCredential:""};var Ce={V1:"",V2:"v2",ForceV1:"forceV1"};var tn={V1:"v1",V2:"v2",V2Segmenter:"v2-segmenter",RabinKarp:"v3-rabin-karp"},en=oe(G({remoteType:Zr,useCustomRequestHandler:!1,couchDB_URI:"",couchDB_USER:"",couchDB_PASSWORD:"",couchDB_DBNAME:"",liveSync:!1,syncOnSave:!1,syncOnStart:!1,savingDelay:200,lessInformationInLog:!1,gcDelay:300,versionUpFlash:"",minimumChunkSize:20,longLineThreshold:250,showVerboseLog:!1,suspendFileWatching:!1,trashInsteadDelete:!0,periodicReplication:!1,periodicReplicationInterval:60,syncOnFileOpen:!1,encrypt:!1,passphrase:"",usePathObfuscation:!1,doNotDeleteFolder:!1,resolveConflictsByNewerFile:!1,batchSave:!1,batchSaveMinimumDelay:5,batchSaveMaximumDelay:60,deviceAndVaultName:"",usePluginSettings:!1,showOwnPlugins:!1,showStatusOnEditor:!0,showStatusOnStatusbar:!0,showOnlyIconsOnEditor:!1,hideFileWarningNotice:!1,usePluginSync:!1,autoSweepPlugins:!1,autoSweepPluginsPeriodic:!1,notifyPluginOrSettingUpdated:!1,checkIntegrityOnSave:!1,batch_size:25,batches_limit:25,useHistory:!1,disableRequestURI:!1,skipOlderFilesOnSync:!0,checkConflictOnlyOnOpen:!1,showMergeDialogOnlyOnActive:!1,syncInternalFiles:!1,syncInternalFilesBeforeReplication:!1,syncInternalFilesIgnorePatterns:"\\\\/node_modules\\\\/, \\\\/\\\\.git\\\\/, \\\\/obsidian-livesync\\\\/",syncInternalFilesTargetPatterns:"",syncInternalFilesInterval:60,additionalSuffixOfDatabaseName:"",ignoreVersionCheck:!1,lastReadUpdates:0,deleteMetadataOfDeletedFiles:!1,syncIgnoreRegEx:"",syncOnlyRegEx:"",customChunkSize:0,readChunksOnline:!0,watchInternalFileChanges:!0,automaticallyDeleteMetadataOfDeletedFiles:0,disableMarkdownAutoMerge:!1,writeDocumentsIfConflicted:!1,useDynamicIterationCount:!1,syncAfterMerge:!1,configPassphraseStore:"",encryptedPassphrase:"",encryptedCouchDBConnection:"",permitEmptyPassphrase:!1,useIndexedDBAdapter:!1,useTimeouts:!1,writeLogToTheFile:!1,doNotPaceReplication:!1,hashCacheMaxCount:300,hashCacheMaxAmount:50,concurrencyOfReadChunksOnline:40,minimumIntervalOfReadChunksOnline:50,hashAlg:"xxhash64",suspendParseReplicationResult:!1,doNotSuspendOnFetching:!1,useIgnoreFiles:!1,ignoreFiles:".gitignore",syncOnEditorSave:!1,pluginSyncExtendedSetting:{},syncMaxSizeInMB:50,settingSyncFile:"",writeCredentialsForSettingSync:!1,notifyAllSettingSyncFile:!1,isConfigured:void 0,settingVersion:qr,enableCompression:!1,accessKey:"",bucket:"",endpoint:"",region:"auto",secretKey:"",useEden:!1,maxChunksInEden:10,maxTotalLengthInEden:1024,maxAgeInEden:10,disableCheckingConfigMismatch:!1,displayLanguage:"",enableChunkSplitterV2:!1,disableWorkerForGeneratingChunks:!1,processSmallFilesInUIThread:!1,notifyThresholdOfRemoteStorageSize:-1,usePluginSyncV2:!1,usePluginEtc:!1,handleFilenameCaseSensitive:void 0,doNotUseFixedRevisionForChunks:!0,showLongerLogInsideEditor:!1,sendChunksBulk:!1,sendChunksBulkMaxSize:1,useSegmenter:!1,useAdvancedMode:!1,usePowerUserMode:!1,useEdgeCaseMode:!1,enableDebugTools:!1,suppressNotifyHiddenFilesChange:!1,syncMinimumInterval:2e3},Qr),{doctorProcessedVersion:"",bucketCustomHeaders:"",couchDB_CustomHeaders:"",useJWT:!1,jwtAlgorithm:"",jwtKey:"",jwtKid:"",jwtSub:"",jwtExpDuration:5,useRequestAPI:!1,bucketPrefix:"",chunkSplitterVersion:"",E2EEAlgorithm:Ce.V2,processSizeMismatchedFiles:!1,forcePathStyle:!0,syncInternalFileOverwritePatterns:"",useOnlyLocalChunk:!1});var et={syncMaxSizeInMB:50,chunkSplitterVersion:"v3-rabin-karp",doNotUseFixedRevisionForChunks:!1,usePluginSyncV2:!0,handleFilenameCaseSensitive:!1,E2EEAlgorithm:Ce.V2},jo=oe(G({},et),{customChunkSize:0,sendChunksBulkMaxSize:1,concurrencyOfReadChunksOnline:100,minimumIntervalOfReadChunksOnline:333}),$o=oe(G({},et),{customChunkSize:50,sendChunksBulkMaxSize:1,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:25}),zo=oe(G({},et),{customChunkSize:10,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:25}),ue={NOTE_LEGACY:"notes",NOTE_BINARY:"newnote",NOTE_PLAIN:"plain",INTERNAL_FILE:"internalfile",CHUNK:"leaf",CHUNK_PACK:"chunkpack",VERSION_INFO:"versioninfo",SYNC_INFO:"syncinfo",SYNC_PARAMETERS:"sync-parameters",MILESTONE_INFO:"milestoneinfo",NODE_INFO:"nodeinfo"},Yo=[ue.NOTE_LEGACY,ue.NOTE_BINARY,ue.NOTE_PLAIN],Jo=[ue.CHUNK,ue.CHUNK_PACK];var es={minimumChunkSize:20,longLineThreshold:250,encrypt:!1,usePathObfuscation:!1,enableCompression:!1,useEden:!1,customChunkSize:0,useDynamicIterationCount:!1,hashAlg:"xxhash64",enableChunkSplitterV2:!1,maxChunksInEden:10,maxTotalLengthInEden:1024,maxAgeInEden:10,usePluginSyncV2:!1,handleFilenameCaseSensitive:!1,doNotUseFixedRevisionForChunks:!0,useSegmenter:!1,E2EEAlgorithm:Ce.V2,chunkSplitterVersion:tn.RabinKarp};var ts={useIgnoreFiles:!1,useCustomRequestHandler:!1,batch_size:25,batches_limit:25,useTimeouts:!1,readChunksOnline:!0,hashCacheMaxCount:300,hashCacheMaxAmount:50,concurrencyOfReadChunksOnline:40,minimumIntervalOfReadChunksOnline:50,ignoreFiles:".gitignore",syncMaxSizeInMB:50,enableChunkSplitterV2:!1,usePluginSyncV2:!0,handleFilenameCaseSensitive:!1,doNotUseFixedRevisionForChunks:!1,E2EEAlgorithm:Ce.V2,chunkSplitterVersion:tn.RabinKarp},Xo={usePluginSyncV2:!1,E2EEAlgorithm:en.E2EEAlgorithm,chunkSplitterVersion:en.chunkSplitterVersion};var qo=G(G({},ts),es);var tt={SUSPEND_ALL:"redflag.md",REBUILD_ALL:"redflag2.md",FETCH_ALL:"redflag3.md"},nn={REBUILD_ALL:"flag_rebuild.md",FETCH_ALL:"flag_fetch.md"},ns=tt.SUSPEND_ALL,rs=tt.REBUILD_ALL,ss=nn.REBUILD_ALL,is=tt.FETCH_ALL,os=nn.FETCH_ALL;var as={UNSET:void 0,LEGACY:1,ADVANCED_E2EE:2},cs="_local/obsidian_livesync_sync_parameters";var Zo={_id:cs,type:ue.SYNC_PARAMETERS,protocolVersion:as.ADVANCED_E2EE,pbkdf2salt:""};var ua=rn(async n=>{let e=C(n),t=await Zt(),r=await t.subtle.digest("SHA-256",e),s=n.length;for(let i=0;i<s;i++)r=await t.subtle.digest("SHA-256",e);return N(new Uint8Array(r))});var pa=Symbol("UNRESOLVED");function fs(){let n,e;return{promise:new Promise((r,s)=>{n=r,e=s}),resolve:n,reject:e}}function ps(){let n=Promise.withResolvers(),{promise:e,resolve:t,reject:r}=n;return{promise:e,resolve:t,reject:r}}var ys="withResolvers"in Promise?ps:fs,ge=ys;var sn=()=>{};function te(n){if(typeof n=="function")return te(n());n.then(sn).catch(sn)}function De(){return new Promise(n=>queueMicrotask(n))}var me=Symbol("timed out");function Oe(n,e=me){let t,r=ge();return t=setTimeout(()=>{t=void 0,r.resolve(e)},n),{promise:r.promise,cancel(){t&&(clearTimeout(t),t=void 0)}}}function nt(n){let e=0,t=n,r=[];return{get waiting(){return r.length},async tryAcquire(i=1,o){if(e<t)return e+=i,()=>{this.release(i)};let a=Oe(o,me),c=this.acquire(i),u=await Promise.race([a.promise,c]);return u===me?(te(()=>c.then(l=>l())),!1):u},async acquire(i=1){if(e<t)return e+=i,()=>this.release();let o=ge();return r.push(o),await o.promise,()=>{this.release(i)}},release(i=1){if(r.length>0){let o=r.shift();o&&te(async()=>await De().then(()=>o.resolve()))}else e>0&&(e-=i)}}}var hs={s:{1:"V",2:"W",3:"X",4:"Y",5:"Z"},o:{1:"v",2:"w",3:"x",4:"y",5:"z"}},Sa=Object.fromEntries(Object.entries(hs).flatMap(([n,e])=>Object.entries(e).map(([t,r])=>[r,{prefix:n,len:parseInt(t)}]))),ds={n:{1:"a",2:"b",3:"c",4:"d",5:"e"},N:{1:"A",2:"B",3:"C",4:"D",5:"E"}},xa=Object.fromEntries(Object.entries(ds).flatMap(([n,e])=>Object.entries(e).map(([t,r])=>[r,{prefix:n,len:parseInt(t)}])));var Ta=Symbol("a"),_a=Symbol("b");var Ie=class{constructor(){Object.defineProperty(this,"_clip",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}isAwaiting(e,t){return this._clip.has(`${String(e)}:${t}`)}issueAndProceed(e,t="",r){return this.isAwaiting(e,t)||te(async()=>{try{let s=await r.callback();this.submit(e,t,s)}catch(s){r.submitAsSuccess?this.submit(e,t,r.transformError?r.transformError(s):s):r.dropSlipWithRisks?this._clip.delete(e):this.reject(e,t,s)}}),this.awaitNext(e,t)}async awaitNext(e,t="",{timeout:r,onNotAwaited:s}={timeout:void 0,onNotAwaited:void 0}){let i=this._clip.get(`${String(e)}:${t}`);if(i||(i=ge(),i.promise=i.promise.then(o=>o).finally(()=>{this._clip.delete(`${String(e)}:${t}`)}),this._clip.set(`${String(e)}:${t}`,i),s&&te(async()=>(await De(),s()))),r){let o=Oe(r);return Promise.race([o.promise,i.promise.then(a=>a).finally(()=>o.cancel())])}return await i.promise}submit(e,t,r){let s=this._clip.get(`${String(e)}:${t}`);s&&s.resolve(r)}submitToAll(e,t,r){for(let[s,i]of this._clip.entries())`${String(s)}`.startsWith(`${String(e)}:${t}`)&&i.resolve(r)}reject(e,t="",r){let s=this._clip.get(`${String(e)}:${t}`);s&&s.reject(r)}},gs=new Ie;var on,cc=typeof((on=globalThis==null?void 0:globalThis.indexedDB)==null?void 0:on.cmp)!="undefined";function rn(n){let e=new Pe(100,1e5,!0);return t=>{if(e.has(t))return e.get(t);let s=n(t);return e.set(t,s),s}}var lc=nt(50);var rt="",uc=`${rt}__DELETED`,fc=`${rt}__ARRAY`,pc=`${rt}__SWAP`;function an(n,e){try{return n()}catch(t){return e(t)}}function Le(n){return n.type==="text/plain"}function*As(n,e){let t="";e:do{let r=n.shift();if(typeof r=="undefined"){yield t;break e}if(r.startsWith("```")||r.startsWith(" ```")||r.startsWith(" ```")||r.startsWith(" ```")){yield t,t=r+(n.length!=0?`\n`:"");t:do{let a=n.shift();if(typeof a=="undefined")break t;t+=a+(n.length!=0?`\n`:"")}while(n.length>0&&!(n[0].startsWith("```")||n[0].startsWith(" ```")||n[0].startsWith(" ```")||n[0].startsWith(" ```")));let s=t.endsWith("="),i=t.length>2048,o=n.shift();if(typeof o!="undefined"&&(t+=o,t+=n.length!=0?`\n`:""),!s&&!i){let a=/(.*?[;,:<])/g,c=t.split(a).filter(u=>u!="");for(let u of c)yield u}else yield t;t=""}else t+=r+(n.length!=0?`\n`:""),(t.length>=e||n.length==0||n[0]=="#"||t[0]=="#")&&(yield t,t="")}while(n.length>0)}var ln=10,un="Segmenter"in Intl?an(()=>new Intl.Segmenter(navigator.language,{granularity:"sentence"}),n=>{L(`Failed to create Intl.Segmenter: ${n.message}`,16)}):void 0;function*Ee(n,e){let t=n;do{let r=e,s=t.substring(0,r);t=t.substring(r),yield s}while(t!="")}function*cn(n,e,t){let r=un.segment(n),s="",i="";for(let o of r){let a=o.segment;s==a||i.length<t?(i+=a,s=a):(s=a,i.length>0&&(yield*M(Ee(i,e))),i=a)}i.length>0&&(yield*M(Ee(i,e)))}function*ws(n){for(let e of n){let t=-1,r=-1;do{if(r=e.indexOf(`\n`,t),r==-1){yield e.substring(t);break}for(;e[r]==`\n`;)r++;yield e.substring(t,r),t=r}while(r!=-1)}}function Ps(n,e,t){let s=ws(typeof n=="string"?[n]:n),i=0,o=!1,a=!1;return function*(){let c=[];for(let u of s)u.startsWith("````")?i==0?(i=4,a=!0):i==4&&(i=0,o=!0):u.startsWith("```")&&(i==0?(i=3,a=!0):i==3&&(i=0,o=!0)),a&&(c.length>0&&(yield*M(cn(c.join(""),e,t)),c.length=0),a=!1),c.push(u),o&&(c.length>0&&(yield*M(Ee(c.join(""),e)),c.length=0),o=!1);c.length>0&&(i==0?yield*M(cn(c.join(""),e,t)):yield*M(Ee(c.join(""),e)))}}function Ts(n,e,t){return function*(){yield*M(Ee(n,e))}}function _s(n,e,t,r,s){return!s||!un?Cs(n,e,t,r):t?Ps(n,e,r):Ts(n,e,r)}function Cs(n,e,t,r){let s=typeof n=="string"?[n]:n;return function*(){for(let o of s)if(t){let a=o.split(`\n`),c=As(a,r);for(let u of c){let l=u;do{let h=e;l.charCodeAt(h-1)!=l.codePointAt(h-1)&&h++,yield l.substring(0,h),l=l.substring(h)}while(l!="")}}else{let a=o;do{let c=e,u=a.substring(0,c);a=a.substring(c),yield u}while(a!="")}}}function*Ds(n,e,t=25,r){let s="",i=!1,o=e.length;for(let a of n){let c=a.length;if(r&&c>r){yield s+a,i=!1,s="";continue}let u=-1,l=0;e:do{if(u=a.indexOf(e,l),u==-1)break e;s+=a.slice(l,u)+e,s.length>t?(yield s,s="",i=!1):i=!0,l=u+o}while(u<c);(l!=u||l==-1&&u==-1)&&(s+=a.slice(l),i=!0)}i&&(yield s)}function*fn(n,e){let t=n.length;if(t>e){let r=0;do{let s=r+e;if(s>t){yield n.substring(r);break}for(;n.charCodeAt(s-1)!=n.codePointAt(s-1);)s++;yield n.substring(r,s),r=s}while(r<t)}else yield n}function*Os(n,e){for(let t of n)yield*M(fn(t,e))}function*Is(n){for(let e of n)yield e}var Ls=100;async function pn(n,e,t,r,s,i){if(n.size==0)return function*(){};if(Le(n)){let d=await n.text();if(!t){let m=fn(d,e);return function*(){yield*M(m)}}let E=d.length,f=r;for(;E/f>Ls;)f+=r;let b=Is([d]),g=Ds(b,`\n`,f),x=Os(g,e);return function*(){yield*M(x)}}let o=!1,a=0;s&&s.endsWith(".pdf")?a=47:s&&s.endsWith(".json")&&(o=!0,a=44);let l=Math.max(o?100:1e5,Math.min(1e8,n.size)),h=1,y=l;for(;y>10;)y/=12.5,h++;return r=Math.floor(10**(h-1)),function(){return Se(this,null,function*(){let E=n.size,f=0,b=new Uint8Array(yield new j(n.arrayBuffer()));do{let g=f+r,x=f+e,m,S=b.indexOf(a,g);S==-1&&(S=b.indexOf(ln,g)),S==-1?m=x:m=S<x?S:x,yield yield new j(O(b.slice(f,m))),f=m}while(f<E)})}}async function yn(n,e,t,r,s,i){if(Le(n))return _s(await n.text(),e,t,r,i!=null?i:!1);let o=0,a=!1;s&&s.endsWith(".pdf")?o=47:s&&s.endsWith(".json")&&(a=!0,o=44);let l=Math.max(a?100:1e5,Math.min(1e8,n.size)),h=1,y=l;for(;y>10;)y/=12.5,h++;return r=Math.floor(10**(h-1)),function(){return Se(this,null,function*(){let E=n.size,f=0;do{let b=e,g=new Uint8Array(yield new j(n.slice(f,f+e).arrayBuffer())),x=g.indexOf(o,r);b=x==-1?e:Math.min(e,x),x==-1&&(x=g.indexOf(ln,r));let m=g.slice(0,b);f+=m.length,yield yield new j(O(m))}while(f<E)})}}async function hn(n,e,t,r,s,i){let o=t||Le(n),a=o?128:1024*4,c=o?20:12,u=Math.max(a,Math.floor(n.size/c)),l=Math.min(e,u*5),h=Math.min(Math.max(Math.floor(u/4),r),l),y=48,d=u,E=1,f=31,b=1;for(let Ke=0;Ke<y-1;Ke++)b=Math.imul(b,f);let g=new Uint8Array(await n.arrayBuffer()),x=0,m=0,S=0,W=Le(n),V=g.length;return function(){return Se(this,null,function*(){for(;x<V;){let ht=g[x];if(x>=S+y){let be=g[x-y],vn=Math.imul(be,b);m=m-vn|0,m=Math.imul(m,f),m=m+ht|0}else m=Math.imul(m,f),m=m+ht|0;let dt=x-S+1,Ve=!1;if(dt>=h&&(m>>>0)%d===E&&(Ve=!0),dt>=l&&(Ve=!0),Ve){let be=!0;W&&x+1<V&&(g[x+1]&192)===128&&(be=!1),be&&(W?yield Promise.resolve(F(g.subarray(S,x+1))):yield yield new j(O(g.subarray(S,x+1))),S=x+1)}x++}S<V&&(W?yield Promise.resolve(F(g.subarray(S,V))):yield yield new j(O(g.subarray(S,V))))})}}function Re(n,e,t){self.postMessage({key:n,seq:e,result:t})}function Rs(n){let e=n,t=0;return function(r){r===null?(t===0&&Re(e,t++,""),Re(e,t++,null)):Re(e,t++,r)}}async function dn(n){let e=n.key,t=n.dataSrc,r=n.pieceSize,s=n.plainSplit,i=n.minimumChunkSize,o=n.filename,a=n.useSegmenter,u=await(n.splitVersion==3?hn:n.splitVersion==2?pn:yn)(t,r,s,i,o,a),l=Rs(e);try{for(var h=je(u()),y,d,E;y=!(d=await h.next()).done;y=!1){let f=d.value;l(f)}}catch(d){E=[d]}finally{try{y&&(d=h.return)&&await d.call(h)}finally{if(E)throw E[0]}}l(null)}var Be=globalThis.crypto,Bs="fancySyncForYou!",vs=new TextEncoder().encode(Bs);var Ic=new Uint32Array(1),Lc=new Uint8Array(12);async function En(n){let e=new TextEncoder().encode(n),r=(await Be.subtle.digest("SHA-256",new Uint8Array([...e,...vs]))).slice(0,16),s=await Be.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits","deriveKey"]),i={name:"PBKDF2",hash:"SHA-256",salt:r,iterations:1e5};return await Be.subtle.deriveKey(i,s,{name:"AES-GCM",length:256},!1,["decrypt","encrypt"])}var gn="",mn;async function it(n,e){gn!==e&&(mn=await En(e),gn=e);let t=n.substring(2,26),r=n.substring(26),s=$(t),i=X(r),o=await Be.subtle.decrypt({name:"AES-GCM",iv:s},mn,i);return F(new Uint8Array(o))}var Ns=Symbol("undefined");function ve(n,e,t){if(n<=0)throw new Error("Buffer length must be greater than 0");let r=new Map,s=i=>i.length>0&&typeof i[0]=="string"?i[0]:JSON.stringify(i,(o,a)=>a===void 0?Ns:a);return function(...i){let o=t?t(i):s(i);if(r.has(o)){let c=r.get(o);return r.delete(o),r.set(o,c),c}let a=e(...i);if(r.set(o,a),a.catch(()=>{r.get(o)===a&&r.delete(o)}),r.size>n){let c=r.keys().next().value;c&&r.delete(c)}return a}}var Y=globalThis.crypto,fe=12,Fs=31e4,Ne=32;var bn=128,Fe="%=";var ks=ve(10,async(n,e)=>{let t=C(n),r=await Y.subtle.importKey("raw",t,{name:"PBKDF2",length:256},!1,["deriveKey"]),s=await Y.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:Fs,hash:"SHA-256"},r,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),i=await Y.subtle.exportKey("raw",s);return await Y.subtle.importKey("raw",i,{name:"HKDF"},!1,["deriveKey"])},([n,e])=>`${n}-${N(e)}`);async function Sn(n,e,t){let r=await ks(n,e);return await Y.subtle.deriveKey({name:"HKDF",salt:t,info:new Uint8Array,hash:"SHA-256"},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Us(n,e,t){return await Y.subtle.encrypt({name:"AES-GCM",iv:e,tagLength:bn},n,t)}async function Ms(n,e,t){let r=Y.getRandomValues(new Uint8Array(Ne)),s=await Sn(e,t,r),i=Y.getRandomValues(new Uint8Array(fe)),o=await Us(s,i,n),a=new Uint8Array(o);return[i,r,a]}async function Ks(n,e,t){let[r,s,i]=await Ms(n,e,t),o=r.length+s.length+i.length,a=new Uint8Array(o);return a.set(r,0),a.set(s,r.length),a.set(i,r.length+s.length),a}async function xn(n,e,t){let r=C(n),s=await Ks(r,e,t),i=await O(s);return`${Fe}${i}`}async function Vs(n,e,t,r,s){let i=await Sn(s,e,t),o=await Y.subtle.decrypt({name:"AES-GCM",iv:n,tagLength:bn},i,r);return new Uint8Array(o)}async function Hs(n,e,t){if(n.length<fe+Ne)throw new Error("Invalid binary data length. Expected at least ivLength + saltLength bytes.");let r=n.slice(0,fe),s=n.slice(fe,fe+Ne),i=n.slice(fe+Ne);return await Vs(r,t,s,i,e)}async function An(n,e,t){if(!n.startsWith(Fe))throw new Error(`Invalid input format. Expected input to start with \'${Fe}\'.`);let r=Fe.length,s=X(n.slice(r)),i=await Hs(new Uint8Array(s),e,t);return F(i)}var Wc=globalThis.crypto;var wn=new Map,ke=new Map,ct=100,Ue,ot=new Uint32Array(1),K=globalThis.crypto;async function zs(n,e){let t=`${n}-${e}`,r=wn.get(t);if(r){if(r.count--,r.count>0)return[r.key,r.salt];r.count--}let s=15-n.length,i=e?(s>0?s:0)*1e3+121-s:1e5,o=new TextEncoder().encode(n),a=await K.subtle.digest({name:"SHA-256"},o),c=await K.subtle.importKey("raw",a,{name:"PBKDF2"},!1,["deriveKey"]),u=K.getRandomValues(new Uint8Array(16)),l=await K.subtle.deriveKey({name:"PBKDF2",salt:u,iterations:i,hash:"SHA-256"},c,{name:"AES-GCM",length:256},!1,["encrypt"]);return wn.set(t,{key:l,salt:u,count:ct}),[l,u]}var at=ct*5,Me=0,Pn=0;async function Tn(n,e,t){if(at--,at<0){at=ct;let h=(Me-Pn)/2;for(let[y,d]of ke)d.count<h&&ke.delete(y),Pn=Me}Me++;let r=n+N(e)+t,s=ke.get(r);if(s)return s.count=Me,[s.key,s.salt];let i=15-n.length,o=t?(i>0?i:0)*1e3+121-i:1e5,a=new TextEncoder().encode(n),c=await K.subtle.digest({name:"SHA-256"},a),u=await K.subtle.importKey("raw",c,{name:"PBKDF2"},!1,["deriveKey"]),l=await K.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:o,hash:"SHA-256"},u,{name:"AES-GCM",length:256},!1,["decrypt"]);return ke.set(r,{key:l,salt:e,count:0}),[l,e]}function _n(n){return Ue!=null&&!n||(Ue=K.getRandomValues(new Uint8Array(12))),Ue}function Ys(){return ot[0]++,ot[0]>1e4&&_n(!0),ot}async function lt(n,e,t){let[r,s]=await zs(e,t),i=_n(),o=Ys(),a=new Uint8Array([...i,...new Uint8Array(o.buffer)]),c=C(n),u=await K.subtle.encrypt({name:"AES-GCM",iv:a},r,c),l=""+await O(new Uint8Array(u));return`%${N(a)}${N(s)}${l}`}async function Js(n,e,t){try{let r=n.substring(1,33),s=n.substring(33,65),i=n.substring(65),[o]=await Tn(e,$(s),t),a=$(r),c=we(i),u=await K.subtle.decrypt({name:"AES-GCM",iv:a},o,c);return F(new Uint8Array(u))}catch(r){throw L("Couldn\'t decode! You should wrong the passphrases (V2)",16),L(r,16),r}}async function ut(n,e,t){try{if(n[0]=="%")return n[1]==="~"?it(n,e):Js(n,e,t);if(!n.startsWith("[")||!n.endsWith("]"))throw new Error("Encrypted data corrupted!");let r=n.substring(1,n.length-1).split(",").map(f=>f[0]==\'"\'?f.substring(1,f.length-1):f),[s,i,o]=r,[a]=await Tn(e,$(o),t),c=$(i),u=atob(s),l=u.length,h=new Uint8Array(l);for(let f=l;f>=0;--f)h[f]=u.charCodeAt(f);let y=await K.subtle.decrypt({name:"AES-GCM",iv:c},a,h),d=F(new Uint8Array(y));return JSON.parse(d)}catch(r){throw L("Couldn\'t decode! You should wrong the passphrases",16),L(r,16),r}}var el=new Uint8Array([83,97,108,116,101,100,95,95]);var ft=globalThis.crypto||window.crypto;var Cn=new Uint8Array([1,0,1]);var Dn=new Uint8Array([10,244,193]),On=new Uint8Array([10,244,194]);var Bn=globalThis.crypto;async function xi(n,e){let t=C(n),r=await Bn.subtle.importKey("raw",t,{name:"HKDF"},!1,["deriveKey"]);return await Bn.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:e,info:new Uint8Array([])},r,{name:"HMAC",hash:"SHA-256",length:256},!1,["sign"])}var Ll=ve(10,xi,([n,e])=>`${C(n)}-${N(e)}`);async function yt(n){let e=n.key,{type:t,input:r,passphrase:s}=n;try{if(t=="encrypt"){let i=n.autoCalculateIterations,o=await lt(r,s,i);self.postMessage({key:e,result:o})}else if(t=="decrypt"){let i=n.autoCalculateIterations,o=await ut(r,s,i);self.postMessage({key:e,result:o})}else if(t=="encryptHKDF"){let i=n.pbkdf2Salt,o=await xn(r,s,i);self.postMessage({key:e,result:o})}else if(t=="decryptHKDF"){let i=n.pbkdf2Salt,o=await An(r,s,i);self.postMessage({key:e,result:o})}}catch(i){self.postMessage({key:e,error:i})}}self.onmessage=n=>{let e=n.data.data;if(e.type==="split")return dn(e);if(e.type==="encrypt"||e.type==="decrypt")return yt(e);if(e.type==="encryptHKDF"||e.type==="decryptHKDF")return yt(e);self.postMessage({key:e.key,error:new Error("Invalid type")})};\n/*! Bundled license information:\n\noctagonal-wheels/dist/encryption/asymmetric/common.js:\n (* istanbul ignore next -- @preserve *)\n*/\n')}function encryptionOnWorker(data){const process2=startWorker(data);return(async()=>{const ret=await process2.task.promise;process2.finalize();return ret})()}function encryptionHKDFOnWorker(data){const process2=startWorker(data);return(async()=>{const ret=await process2.task.promise;process2.finalize();return ret})()}function handleTaskEncrypt(process2,data){const key3=data.key,task=process2.task;"result"in data?task.resolve(data.result):data.error?task.reject(data.error):task.reject(new Error("Unknown error in background encryption"));tasks2.delete(key3)}function _splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,splitVersion,useSegmenter){const process2=startWorker({type:"split",dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter,splitVersion}),_key=process2.key,stream=new TransformStream({transform:(chunk,controller)=>{null!==chunk?controller.enqueue(chunk):controller.terminate()},flush:()=>{}});workerStreams.set(_key,stream);const reader=stream.readable.getReader(),writer=stream.writable.getWriter();writers.set(_key,writer);return async function*(){try{let done=!1;do{const results=await reader.read();done=results.done;if(done)break;yield results.value}while(!done)}catch(ex){Logger(`Error in worker stream for key ${_key}`);Logger(ex,LOG_LEVEL_VERBOSE);throw ex}finally{process2.finalize();workerStreams.delete(_key);writers.delete(_key)}}}function handleTaskSplit(process2,data){const key3=data.key;if(!("result"in data)){responseBuf.delete(key3);const reportError=data.error||new Error("Unknown error in background splitting");writerPromise=writerPromise.then((async()=>{const writer=writers.get(key3);writer&&await writer.abort(reportError)}))}let thisBuf=responseBuf.get(key3);if(!thisBuf){thisBuf=new Map;responseBuf.set(key3,thisBuf)}const seq=data.seq;thisBuf.set(seq,null===data.result?SYMBOL_END_OF_DATA:data.result);responseBuf.set(key3,thisBuf);const keys3=Array.from(thisBuf.keys()).sort(((a2,b3)=>a2-b3)),max3=keys3[keys3.length-1];for(let i2=0;i2<=max3;i2++){const result=thisBuf.get(i2);if(void 0===result)break;if(result!==SYMBOL_USED){thisBuf.set(i2,SYMBOL_USED);responseBuf.set(key3,thisBuf);writerPromise=writerPromise.then((async()=>{const writer=writers.get(key3);if(!writer)throw new Error(`Invalid writer for key ${key3} in background splitting`);await writer.write(result===SYMBOL_END_OF_DATA?null:result)}))}}}function splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter){return _splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,1,null!=useSegmenter&&useSegmenter)}function splitPieces2WorkerV2(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter){return _splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,2,null!=useSegmenter&&useSegmenter)}function splitPieces2WorkerRabinKarp(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter){return _splitPieces2Worker(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,3,null!=useSegmenter&&useSegmenter)}function encryptHKDFWorker(input,passphrase,pbkdf2Salt){return encryptionHKDFOnWorker({type:"encryptHKDF",input,passphrase,pbkdf2Salt})}function initialiseWorkers(){const maxConcurrency=~~((navigator.hardwareConcurrency||8)/2);return Array.from({length:maxConcurrency},(()=>({worker:Worker2(),processing:0})))}function initialiseWorkerModule(){if(workers.length>0){terminateWorker();workers=[]}workers=initialiseWorkers();for(const inst of workers){inst.worker.onmessage=({data})=>{const key3=data.key,process2=tasks2.get(key3);process2?"split"===process2.type?handleTaskSplit(0,data):"encrypt"===process2.type||"decrypt"===process2.type||"encryptHKDF"===process2.type||"decryptHKDF"===process2.type?handleTaskEncrypt(process2,data):info("Invalid response type"+process2):info(`Invalid key ${key3} of background processing`,LOG_KIND_ERROR)};inst.worker.onerror=()=>{inst.worker.terminate();workers.splice(workers.indexOf(inst),1)}}eventHub.on(EVENT_PLATFORM_UNLOADED,(()=>{terminateWorker()}))}function nextWorker(){if(void 0===workers||0===workers.length)throw new Error("No available workers");const inst=workers[roundRobinIdx];roundRobinIdx=(roundRobinIdx+1)%workers.length;return inst}function startWorker(data){const _key=key2++,inst=nextWorker(),item={key:_key,task:promiseWithResolver(),type:data.type,finalize:()=>{inst.processing--}};tasks2.set(_key,item);inst.processing++;inst.worker.postMessage({data:{...data,key:_key}});return item}function terminateWorker(){for(const inst of workers)inst.worker.terminate()}function getEncryptionVersion(data){return"e_"in data&&!0===data.e_?data.data.startsWith(Encrypt_HKDF_Header)?EncryptionVersions_HKDF:data.data.startsWith(Encrypt_OLD_Header)?EncryptionVersions_ENCRYPTED:EncryptionVersions_UNKNOWN:EncryptionVersions_UNENCRYPTED}async function tryDecryptV1AsFallback(encryptedData,passphrase,useDynamicIterationCount){try{return await decrypt5(encryptedData,passphrase,useDynamicIterationCount)}catch(ex){try{Logger("Failed to decrypt with V1 method. Fallback to disable useDynamicIterationCount.",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);return await decrypt5(encryptedData,passphrase,!1)}catch(ex2){Logger("Completely failed to decrypt with V1 method.",LOG_LEVEL_VERBOSE);Logger(ex2,LOG_LEVEL_VERBOSE);return!1}}}function isEncryptedMeta(doc){return"path"in doc&&doc.path.startsWith(ENCRYPTED_META_PREFIX)}async function encryptMetaWithHKDF(doc,passphrase,pbkdf2Salt){if(isEncryptedMeta(doc))return doc.path;const props={path:getPath(doc),mtime:doc.mtime,ctime:doc.ctime,size:doc.size,children:isMetaEntry(doc)?doc.children:void 0},propStr=JSON.stringify(props),encryptedMeta=await encryptHKDFWorker(propStr,passphrase,pbkdf2Salt);return ENCRYPTED_META_PREFIX+encryptedMeta}async function decryptMetaWithHKDF(meta,passphrase,pbkdf2Salt){if(!meta.startsWith(ENCRYPTED_META_PREFIX))throw new Error("Meta is not encrypted with HKDF.");const encryptedMeta=meta.slice(ENCRYPTED_META_PREFIX.length),props=await decryptHKDF(encryptedMeta,passphrase,pbkdf2Salt);return JSON.parse(props)}async function incomingEncryptHKDF(doc,passphrase,useDynamicIterationCount,getPBKDF2Salt){const saveDoc={...doc};if(isEncryptedChunkEntry(saveDoc)||isSyncInfoEntry(saveDoc))try{const encryptionVersion=getEncryptionVersion(saveDoc);if(encryptionVersion===EncryptionVersions_ENCRYPTED){if(!1===await tryDecryptV1AsFallback(saveDoc.data,passphrase,useDynamicIterationCount)){Logger(MESSAGE_FALLBACK_DECRYPT_FAILED,LOG_LEVEL_NOTICE);throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED)}const pbkdf2salt=await getPBKDF2Salt();saveDoc.data=await encryptHKDF(saveDoc.data,passphrase,pbkdf2salt);saveDoc.e_=!0}if(encryptionVersion===EncryptionVersions_HKDF);else if(encryptionVersion===EncryptionVersions_UNENCRYPTED){const pbkdf2salt=await getPBKDF2Salt();saveDoc.data=await encryptHKDF(saveDoc.data,passphrase,pbkdf2salt);saveDoc.e_=!0}}catch(ex){Logger(ENCRYPTION_HKDF_FAILED,LOG_LEVEL_NOTICE);Logger(ex);throw ex}if(shouldEncryptEdenHKDF(saveDoc)){const pbkdf2salt=await getPBKDF2Salt();try{saveDoc.eden={[EDEN_ENCRYPTED_KEY_HKDF]:{data:await encryptHKDF(JSON.stringify(saveDoc.eden),passphrase,pbkdf2salt),epoch:999999}}}catch(ex){Logger(`${ENCRYPTION_HKDF_FAILED} on Eden`,LOG_LEVEL_NOTICE);Logger(ex);throw ex}}if(isObfuscatedEntry(saveDoc)){const pbkdf2salt=await getPBKDF2Salt();if(!isEncryptedMeta(saveDoc))try{saveDoc.path=await encryptMetaWithHKDF(saveDoc,passphrase,pbkdf2salt);saveDoc.mtime=0;saveDoc.ctime=0;saveDoc.size=0;"children"in saveDoc&&(saveDoc.children=[])}catch(ex){Logger(`${ENCRYPTION_HKDF_FAILED} on Metadata`,LOG_LEVEL_NOTICE);Logger(ex);throw ex}}return saveDoc}async function outgoingDecryptHKDF(doc,migrationDecrypt,decrypted,passphrase,useDynamicIterationCount,getPBKDF2Salt){const loadDoc={...doc};if(isEncryptedChunkEntry(loadDoc)||isSyncInfoEntry(loadDoc))try{const encryptionVersion=getEncryptionVersion(loadDoc);if(encryptionVersion===EncryptionVersions_HKDF){const pbkdf2salt=await getPBKDF2Salt();loadDoc.data=await decryptHKDF(loadDoc.data,passphrase,pbkdf2salt);delete loadDoc.e_}else if(encryptionVersion===EncryptionVersions_ENCRYPTED){const decryptedData=await tryDecryptV1AsFallback(loadDoc.data,passphrase,useDynamicIterationCount);if(!1===decryptedData){Logger(MESSAGE_FALLBACK_DECRYPT_FAILED,LOG_LEVEL_NOTICE);throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED)}loadDoc.data=decryptedData;delete loadDoc.e_}else if(encryptionVersion!==EncryptionVersions_UNENCRYPTED){Logger("Unknown encryption version. Cannot decrypt.",LOG_LEVEL_NOTICE);throw new Error("Unknown encryption version. Cannot decrypt.")}}catch(ex){Logger(DECRYPTION_HKDF_FAILED,LOG_LEVEL_NOTICE);Logger(ex);throw ex}if(isObfuscatedEntry(loadDoc)){const path2=getPath(loadDoc);if(isEncryptedMeta(loadDoc)){const pbkdf2salt=await getPBKDF2Salt();try{const metadata=await decryptMetaWithHKDF(path2,passphrase,pbkdf2salt);for(const key3 of Object.keys(metadata))loadDoc[key3]=metadata[key3]}catch(ex){Logger(`${DECRYPTION_HKDF_FAILED} on Path`,LOG_LEVEL_NOTICE);Logger(ex);throw ex}}else if(isPathProbablyObfuscated(path2)){const decryptedPath=await tryDecryptV1AsFallback(path2,passphrase,useDynamicIterationCount);if(!1===decryptedPath){Logger(`${MESSAGE_FALLBACK_DECRYPT_FAILED} on Path`,LOG_LEVEL_NOTICE);throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED)}loadDoc.path=decryptedPath}}let readEden={},edenDecrypted=!1;if(shouldDecryptEden(loadDoc))try{const decryptedEden=await tryDecryptV1AsFallback(loadDoc.eden[EDEN_ENCRYPTED_KEY].data,passphrase,useDynamicIterationCount);if(!1===decryptedEden)throw new Error(MESSAGE_FALLBACK_DECRYPT_FAILED);readEden={...readEden,...JSON.parse(decryptedEden)};edenDecrypted=!0}catch(ex){Logger(`${DECRYPTION_FALLBACK_FAILED} on Eden`,LOG_LEVEL_NOTICE);Logger(ex);throw ex}if(shouldDecryptEdenHKDF(loadDoc)){const pbkdf2salt=await getPBKDF2Salt();try{const decryptedEdenData=await decryptHKDF(loadDoc.eden[EDEN_ENCRYPTED_KEY_HKDF].data,passphrase,pbkdf2salt);readEden={...readEden,...JSON.parse(decryptedEdenData)};edenDecrypted=!0}catch(ex){Logger(`${DECRYPTION_HKDF_FAILED} on Eden`,LOG_LEVEL_NOTICE);Logger(ex);throw ex}}edenDecrypted&&(loadDoc.eden=readEden);return loadDoc}async function incomingEncryptV1(doc,passphrase,useDynamicIterationCount){const saveDoc={...doc};if(isEncryptedChunkEntry(saveDoc)||isSyncInfoEntry(saveDoc))try{if(!("e_"in saveDoc)){saveDoc.data=await encrypt5(saveDoc.data,passphrase,useDynamicIterationCount);saveDoc.e_=!0}}catch(ex){Logger("Encryption failed.",LOG_LEVEL_NOTICE);Logger(ex);throw ex}shouldEncryptEden(saveDoc)&&(saveDoc.eden={[EDEN_ENCRYPTED_KEY]:{data:await encrypt5(JSON.stringify(saveDoc.eden),passphrase,useDynamicIterationCount),epoch:999999}});if(isObfuscatedEntry(saveDoc))try{const path2=getPath(saveDoc);isPathProbablyObfuscated(path2)||(saveDoc.path=await obfuscatePath(path2,passphrase,useDynamicIterationCount))}catch(ex){Logger("Encryption failed.",LOG_LEVEL_NOTICE);Logger(ex);throw ex}return saveDoc}async function outgoingDecryptV1(doc,migrationDecrypt,decrypted,passphrase,useDynamicIterationCount){var _a8,_b5;const loadDoc={...doc},_isChunkOrSyncInfo=isEncryptedChunkEntry(loadDoc)||isSyncInfoEntry(loadDoc),_isObfuscatedEntry=isObfuscatedEntry(loadDoc),_shouldDecryptEden=shouldDecryptEden(loadDoc);if(_isChunkOrSyncInfo||_isObfuscatedEntry||_shouldDecryptEden){if(migrationDecrypt&&decrypted.has(loadDoc._id))return loadDoc;try{if(_isChunkOrSyncInfo){loadDoc.data=await decrypt5(loadDoc.data,passphrase,useDynamicIterationCount);delete loadDoc.e_}else if("e_"in loadDoc){loadDoc.data=await decrypt5(loadDoc.data,passphrase,useDynamicIterationCount);delete loadDoc.e_}if(_isObfuscatedEntry){const path2=getPath(loadDoc);isPathProbablyObfuscated(path2)&&(loadDoc.path=await decrypt5(path2,passphrase,useDynamicIterationCount))}_shouldDecryptEden&&(loadDoc.eden=JSON.parse(await decrypt5(loadDoc.eden[EDEN_ENCRYPTED_KEY].data,passphrase,useDynamicIterationCount)));migrationDecrypt&&decrypted.set(loadDoc._id,!0)}catch(ex){if(!useDynamicIterationCount){Logger("Decryption failed.",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);Logger(`id:${loadDoc._id}-${null==(_b5=loadDoc._rev)?void 0:_b5.substring(0,10)}`,LOG_LEVEL_VERBOSE);throw ex}try{_isChunkOrSyncInfo&&(loadDoc.data=await decrypt5(loadDoc.data,passphrase,!1));if(_isObfuscatedEntry){const path2=getPath(loadDoc);isPathProbablyObfuscated(path2)&&(loadDoc.path=await decrypt5(path2,passphrase,!1))}_shouldDecryptEden&&(loadDoc.eden=JSON.parse(await decrypt5(loadDoc.eden[EDEN_ENCRYPTED_KEY].data,passphrase,!1)));migrationDecrypt&&decrypted.set(loadDoc._id,!0)}catch(ex2){if(migrationDecrypt&&"SyntaxError"==ex2.name)return loadDoc;Logger("Decryption failed.",LOG_LEVEL_NOTICE);Logger(ex2,LOG_LEVEL_VERBOSE);Logger(`id:${loadDoc._id}-${null==(_a8=loadDoc._rev)?void 0:_a8.substring(0,10)}`,LOG_LEVEL_VERBOSE);throw ex2}}}return loadDoc}function disableEncryption(){preprocessOutgoing=async doc=>await Promise.resolve(doc)}function shouldEncryptEden(doc){return"eden"in doc&&!(EDEN_ENCRYPTED_KEY in doc.eden)}function shouldEncryptEdenHKDF(doc){return"eden"in doc&&!(EDEN_ENCRYPTED_KEY_HKDF in doc.eden)&&0!==Object.keys(doc.eden).length}function shouldDecryptEden(doc){return"eden"in doc&&EDEN_ENCRYPTED_KEY in doc.eden}function shouldDecryptEdenHKDF(doc){return"eden"in doc&&EDEN_ENCRYPTED_KEY_HKDF in doc.eden}async function*genReplication(s2,signal){const inbox=new Inbox(1e4),push2=function(e3){serialized("replicationResult",(async()=>{signal.aborted||(inbox.isDisposed?Logger("Inbox is disposed",LOG_LEVEL_VERBOSE):await inbox.post(e3))}))};s2.on("complete",(result=>push2(["complete",result])));s2.on("change",(result=>push2(["change",result])));s2.on("active",(()=>push2(["active"])));s2.on("denied",(err3=>push2(["denied",err3])));s2.on("error",(err3=>push2(["error",err3])));s2.on("paused",(err3=>push2(["paused",err3])));s2.then((()=>push2(["finally"]))).catch((()=>push2(["finally"])));const abortSymbol=Symbol("abort"),abortPromise=promiseWithResolver();signal.addEventListener("abort",(()=>{abortPromise.resolve(abortSymbol)}));try{for(;!inbox.isDisposed&&!signal.aborted;){const r4=await inbox.pick(void 0,[abortPromise.promise]);if(r4===NOT_AVAILABLE)break;yield r4}}catch(ex){if(!(ex instanceof Error&&"AbortError"==ex.name))throw ex;Logger("Replication aborted",LOG_LEVEL_VERBOSE)}finally{s2.cancel();inbox.dispose()}}function clearResult(name){measures.set(name,[0,0])}async function measureEach(name,proc){var _a8;const[times,spent]=null!=(_a8=measures.get(name))?_a8:[0,0],start=performance.now(),result=proc();result instanceof Promise&&await result;const end=performance.now();measures.set(name,[times+1,spent+(end-start)])}function formatNumber(num){return num.toLocaleString("en-US",{maximumFractionDigits:2})}async function measure(name,proc,times=1e4,duration=1e3){const from=Date.now();let last=times;clearResult(name);do{await measureEach(name,proc)}while(last-- >0&&Date.now()-from<duration);return[name,measures.get(name)]}async function formatPerfResults(items){return"| Name | Runs | Each | Total |\n| --- | --- | --- | --- | \n"+items.map((e3=>`| ${e3[0]} | ${e3[1][0]} | ${0!=e3[1][0]?formatNumber(e3[1][1]/e3[1][0]):"-"} | ${formatNumber(e3[1][0])} |`)).join("\n")}async function perf_trench(plugin3){clearResult("trench");const trench=new Trench(plugin3.simpleStore),result=[];result.push(await measure("trench-short-string",(async()=>{const p4=trench.evacuate("string");await p4()})));{const testBinary=await plugin3.storageAccess.readHiddenFileBinary("testdata/10kb.png"),uint8Array=new Uint8Array(testBinary);result.push(await measure("trench-binary-10kb",(async()=>{const p4=trench.evacuate(uint8Array);await p4()})))}{const testBinary=await plugin3.storageAccess.readHiddenFileBinary("testdata/100kb.jpeg"),uint8Array=new Uint8Array(testBinary);result.push(await measure("trench-binary-100kb",(async()=>{const p4=trench.evacuate(uint8Array);await p4()})))}{const testBinary=await plugin3.storageAccess.readHiddenFileBinary("testdata/1mb.png"),uint8Array=new Uint8Array(testBinary);result.push(await measure("trench-binary-1mb",(async()=>{const p4=trench.evacuate(uint8Array);await p4()})))}return formatPerfResults(result)}function TestPane($$anchor,$$props){async function performTest(){try{set(testRunning,!0);set(performanceTestResult,await perf_trench(plugin3()))}finally{set(testRunning,!1)}}function clearResult2(){moduleDev().testResults.update((v2=>[]))}function clearPerfTestResult(){get(prefTestResultEl).empty()}function moduleMultiDeviceTest(){if(!get(moduleTesting)){set(moduleTesting,!0);plugin3().services.test.testMultiDevice().finally((()=>{set(moduleTesting,!1)}))}}function moduleSingleDeviceTest(){if(!get(moduleTesting)){set(moduleTesting,!0);plugin3().services.test.test().finally((()=>{set(moduleTesting,!1)}))}}async function allTest(){if(!get(moduleTesting)){set(moduleTesting,!0);try{await plugin3().services.test.test();await plugin3().services.test.testMultiDevice()}finally{set(moduleTesting,!1)}}}var fragment,button,button_1,button_2,button_3,node,pre_1,text_2,button_4,button_5;push($$props,!1);append_styles($$anchor,$$css5);const $results=()=>store_get(results,"$results",$$stores),[$$stores,$$cleanup]=setup_stores(),resultLines=mutable_source();let plugin3=prop($$props,"plugin",8),moduleDev=prop($$props,"moduleDev",8),performanceTestResult=mutable_source(""),testRunning=mutable_source(!1),prefTestResultEl=mutable_source(),isReady=mutable_source(!1);onMount((async()=>{set(isReady,!0);eventHub.onceEvent(EVENT_LAYOUT_READY,(async()=>{if(await plugin3().storageAccess.isExistsIncludeHidden("_AUTO_TEST.md")){new import_obsidian.Notice("Auto test file found, running tests...");fireAndForget((async()=>{await allTest()}))}}))}));let moduleTesting=mutable_source(!1);const results=moduleDev().testResults;let syncStatus=mutable_source([]);eventHub.onEvent("debug-sync-status",(status=>{set(syncStatus,[...status])}));legacy_pre_effect((()=>(get(performanceTestResult),get(isReady),import_obsidian.MarkdownRenderer,deep_read_state(plugin3()),get(prefTestResultEl))),(()=>{""!=get(performanceTestResult)&&get(isReady)&&import_obsidian.MarkdownRenderer.render(plugin3().app,get(performanceTestResult),get(prefTestResultEl),"/",plugin3())}));legacy_pre_effect((()=>$results()),(()=>{set(resultLines,$results())}));legacy_pre_effect_reset();init();fragment=root4();button=sibling(first_child(fragment),4);button_1=sibling(button,2);button_2=sibling(button_1,2);button_3=sibling(button_2,2);each(node=sibling(button_3,2),1,(()=>get(resultLines)),index,(($$anchor2,$$item)=>{var details,summary,text2,pre,text_1,$$array=user_derived((()=>to_array(get($$item),3)));let result=()=>get($$array)[0],line=()=>get($$array)[1],message=()=>get($$array)[2];summary=child(details=root_17());text2=child(summary);reset(summary);pre=sibling(summary,2);text_1=child(pre,!0);reset(pre);reset(details);template_effect((()=>{var _a8;details.open=!result();set_text(text2,`[${result()?"PASS":"FAILED"}] ${null!=(_a8=line())?_a8:""}`);set_text(text_1,message())}));append($$anchor2,details)}));pre_1=sibling(node,4);text_2=child(pre_1,!0);reset(pre_1);button_4=sibling(pre_1,4);button_5=sibling(button_4,2);bind_this(sibling(button_5,2),($$value=>set(prefTestResultEl,$$value)),(()=>get(prefTestResultEl)));template_effect(($0=>{button.disabled=get(moduleTesting);button_1.disabled=get(moduleTesting);button_2.disabled=get(moduleTesting);set_text(text_2,$0);button_4.disabled=get(testRunning)}),[()=>(get(syncStatus),untrack((()=>get(syncStatus).join("\n"))))]);event("click",button,(()=>moduleMultiDeviceTest()));event("click",button_1,(()=>moduleSingleDeviceTest()));event("click",button_2,(()=>allTest()));event("click",button_3,(()=>clearResult2()));event("click",button_4,(()=>performTest()));event("click",button_5,(()=>clearPerfTestResult()));append($$anchor,fragment);pop();$$cleanup()}function toArrayBuffer(arr){return arr instanceof Uint8Array||arr instanceof DataView?arr.buffer:arr}function TFileToUXFileInfoStub(file,deleted){if(!(file instanceof import_obsidian.TFile))throw new Error("Invalid file type");return{name:file.name,path:file.path,isFolder:!1,stat:{size:file.stat.size,mtime:file.stat.mtime,ctime:file.stat.ctime,type:"file"},deleted}}function InternalFileToUXFileInfoStub(filename,deleted){return{name:filename.split("/").pop(),path:filename,isFolder:!1,stat:void 0,isInternal:!0,deleted}}function TFolderToUXFileInfoStub(file){var _a8;return{name:file.name,path:file.path,parent:null==(_a8=file.parent)?void 0:_a8.path,isFolder:!0,children:file.children.map((e3=>TFileToUXFileInfoStub(e3)))}}function confirmWithMessage(plugin3,title,contentMd,buttons,defaultAction,timeout){return new Promise((res2=>{new MessageBox(plugin3,title,contentMd,buttons,defaultAction,timeout,!1,(result=>res2(result))).open()}))}function confirmWithMessageWithWideButton(plugin3,title,contentMd,buttons,defaultAction,timeout){return new Promise((res2=>{new MessageBox(plugin3,title,contentMd,buttons,defaultAction,timeout,!0,(result=>res2(result))).open()}))}function translateInfo(infoSrc){if(!infoSrc)return!1;const info3={...infoSrc};info3.name=$t(info3.name);info3.desc&&(info3.desc=$t(info3.desc));return info3}function _getConfig(key3){return key3 in configurationNames?configurationNames[key3]:key3 in SettingInformation&&SettingInformation[key3]}function getConfig(key3){return translateInfo(_getConfig(key3))}function getConfName(key3){const conf=getConfig(key3);return conf?conf.name:`${key3} (No info)`}function checkUnsuitableValues(setting,regulation=DoctorRegulation){var _a8,_b5;const result={version:regulation.version,rules:{}};for(const key3 in regulation.rules){if(!regulation.rules.hasOwnProperty(key3))continue;const rule=regulation.rules[key3];if(!rule)continue;const value=setting[key3];if(rule.value!==value){if("number"==typeof value&&"min"in rule&&"max"in rule){const min=null!=(_a8=rule.min)?_a8:Number.MIN_SAFE_INTEGER,max3=null!=(_b5=rule.max)?_b5:Number.MAX_SAFE_INTEGER;if(value>=min&&value<=max3){Logger(`Rule satisfied: ${key3} is ${value} between ${min} and ${max3}`);continue}}if(!rule.detectionFunc||rule.detectionFunc(setting)){result.rules[key3]=rule;Logger(`Rule violation: ${key3} is ${value} but should be ${rule.value}`)}else Logger(`Rule condition satisfied: ${key3} is ${value}, and detection function returned false`)}else Logger(`Rule satisfied: ${key3} is ${value}`)}return result}async function performDoctorConsultation(env,settings,{localRebuild=RebuildOptions_ConfirmIfRequired,remoteRebuild=RebuildOptions_ConfirmIfRequired,activateReason="updated",forceRescan=!1}){function getResult(){return{settings,shouldRebuild,shouldRebuildLocal,isModified}}var _a8,_b5,_c3;let shouldRebuild=!1,shouldRebuildLocal=!1,isModified=!1;const r4=checkUnsuitableValues(settings);if(!forceRescan&&r4.version==settings.doctorProcessedVersion){Logger((Object.keys(r4.rules).length>0?"Issues found":"No issues found")+" but marked as to be silent",LOG_LEVEL_VERBOSE);return getResult()}if(0==Object.entries(r4.rules).length){Logger($msg("Doctor.Message.NoIssues"),"updated"!==activateReason?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return getResult()}{const OPT_YES=`${$msg("Doctor.Button.Yes")}`,OPT_NO=`${$msg("Doctor.Button.No")}`,OPT_DISMISS=`${$msg("Doctor.Button.DismissThisVersion")}`,issues2=Object.keys(r4.rules).map((key3=>`- ${getConfName(key3)}`)).join("\n"),msg=await env.confirm.askSelectStringDialogue($msg("Doctor.Dialogue.Main",{activateReason,issues:issues2}),[OPT_YES,OPT_NO,OPT_DISMISS],{title:$msg("Doctor.Dialogue.Title"),defaultAction:OPT_YES});if(msg==OPT_DISMISS){settings.doctorProcessedVersion=r4.version;isModified=!0;Logger("Marked as to be silent",LOG_LEVEL_VERBOSE);return{settings,shouldRebuild,shouldRebuildLocal,isModified}}if(msg!=OPT_YES)return getResult();const issueItems=Object.entries(r4.rules);Logger(`${issueItems.length} Issue(s) found `,LOG_LEVEL_VERBOSE);let idx2=0;const applySettings={},OPT_FIX=`${$msg("Doctor.Button.Fix")}`,OPT_SKIP=`${$msg("Doctor.Button.Skip")}`,OPTION_FIX_WITHOUT_REBUILD=`${$msg("Doctor.Button.FixButNoRebuild")}`;let skipped=0;for(const[key3,value]of issueItems){const levelMap={[1]:$msg("Doctor.Level.Necessary"),[2]:$msg("Doctor.Level.Recommended"),[3]:$msg("Doctor.Level.Optional"),[0]:$msg("Doctor.Level.Must")},level=value.level?levelMap[value.level]:"Unknown",options=[OPT_FIX];let askRebuild=!1,askRebuildLocal=!1;if(value.requireRebuild)if(remoteRebuild==RebuildOptions_AutomaticAcceptable){askRebuild=!1;shouldRebuild=!0}else if(remoteRebuild==RebuildOptions_ConfirmIfRequired)askRebuild=!0;else if(remoteRebuild==RebuildOptions_SkipEvenIfRequired){askRebuild=!1;shouldRebuild=!1}if(value.requireRebuildLocal)if(localRebuild==RebuildOptions_AutomaticAcceptable){askRebuildLocal=!1;shouldRebuildLocal=!0}else if(localRebuild==RebuildOptions_ConfirmIfRequired)askRebuildLocal=!0;else if(localRebuild==RebuildOptions_SkipEvenIfRequired){askRebuildLocal=!1;shouldRebuildLocal=!1}(askRebuild||askRebuildLocal)&&options.push(OPTION_FIX_WITHOUT_REBUILD);options.push(OPT_SKIP);const note=`${askRebuild?$msg("Doctor.Message.RebuildRequired"):""}${askRebuildLocal?$msg("Doctor.Message.RebuildLocalRequired"):""}`,ret=await env.confirm.askSelectStringDialogue($msg("Doctor.Dialogue.MainFix",{name:getConfName(key3),current:`${settings[key3]}`,reason:null!=(_c3=null!=(_b5=null==(_a8=value.reasonFunc)?void 0:_a8.call(value,settings))?_b5:value.reason)?_c3:" N/A ",ideal:`${value.valueDisplayFunc?value.valueDisplayFunc(settings):value.value}`,level:`${level}`,note}),options,{title:$msg("Doctor.Dialogue.TitleFix",{current:""+ ++idx2,total:`${issueItems.length}`}),defaultAction:OPT_FIX});if(ret==OPT_FIX||ret==OPTION_FIX_WITHOUT_REBUILD){applySettings[key3]=value.value;if(ret==OPT_FIX){shouldRebuild=shouldRebuild||askRebuild||!1;shouldRebuildLocal=shouldRebuildLocal||askRebuildLocal||!1}isModified=!0}else skipped++}Object.keys(applySettings).length>0&&(settings={...settings,...applySettings});if(0==skipped){settings.doctorProcessedVersion=r4.version;isModified=!0}else if("no"==await env.confirm.askYesNoDialog($msg("Doctor.Message.SomeSkipped"),{title:$msg("Doctor.Dialogue.TitleAlmostDone"),defaultOption:"No"})){settings.doctorProcessedVersion=r4.version;isModified=!0}}return getResult()}function setupDialogContext(controls){setContext(CONTEXT_DIALOG_CONTROLS,controls)}function getDialogContext(){return getContext(CONTEXT_DIALOG_CONTROLS)}function DialogHost($$anchor,$$props){var div;push($$props,!0);append_styles($$anchor,$$css6);const contextProps={setTitle:$$props.setTitle,closeDialog:$$props.closeDialog,setResult:$$props.setResult,getInitialData:$$props.getInitialData};null===$$props.onSetupContext||void 0===$$props.onSetupContext||$$props.onSetupContext(contextProps);let thisElement;(0,$$props.mountComponent)(child(div=root5()),{setResult:result=>{$$props.setResult(result);$$props.closeDialog()},get getInitialData(){return $$props.getInitialData}});reset(div);bind_this(div,($$value=>thisElement=$$value),(()=>thisElement));append($$anchor,div);pop()}async function openSvelteDialog(plugin3,component2,initialData){const dialog=new SvelteDialog(plugin3,component2,initialData);dialog.open();return await dialog.waitForClose()}function getObsidianDialogContext(){return getDialogContext()}function DialogHeader($$anchor,$$props){var div,h22,text2,node,consequent;push($$props,!0);append_styles($$anchor,$$css7);user_effect((()=>{$$props.title&&context2.setTitle(`${$$props.title}${$$props.subtitle?` - ${$$props.subtitle}`:""}`)}));const context2=getDialogContext();onMount((async()=>{var _a8;context2.setTitle(`${$$props.title}${$$props.subtitle?` - ${$$props.subtitle}`:""}`);await tick();null===(_a8=document.querySelector(".modal"))||void 0===_a8||_a8.scrollTo(0,0)}));h22=child(div=root6());text2=child(h22,!0);reset(h22);node=sibling(h22,2);consequent=$$anchor2=>{var h4=root_110(),text_1=child(h4,!0);reset(h4);template_effect((()=>set_text(text_1,$$props.subtitle)));append($$anchor2,h4)};if_block(node,($$render=>{$$props.subtitle&&$$render(consequent)}));reset(div);template_effect((()=>set_text(text2,$$props.title)));append($$anchor,div);pop()}function Guidance($$anchor,$$props){"use strict";var div,node,consequent;const cssClass=user_derived((()=>$$props.important?"guidance important":"guidance"));node=child(div=root7());consequent=$$anchor2=>{var h3=root_111(),text2=child(h3,!0);reset(h3);template_effect((()=>set_text(text2,$$props.title)));append($$anchor2,h3)};if_block(node,($$render=>{$$props.title&&$$render(consequent)}));snippet(sibling(node,2),(()=>{var _a8;return null!=(_a8=$$props.children)?_a8:noop2}));reset(div);template_effect((()=>set_class(div,1,clsx2(get(cssClass)))));append($$anchor,div)}function onclick(_,$$props){fireAndForget((async()=>$$props.commit()))}function Decision($$anchor,$$props){var button,text2;push($$props,!0);(button=root8()).__click=[onclick,$$props];text2=child(button,!0);reset(button);template_effect((()=>{var _a8;set_class(button,1,`button ${null!=(_a8=$$props.additionalClasses)?_a8:""} ${$$props.important?"mod-cta":""} ${$$props.destructive?"mod-destructive":""}`);button.disabled=$$props.disabled;set_text(text2,$$props.title)}));append($$anchor,button);pop()}function Question($$anchor,$$props){var div,node,consequent,div_1;push($$props,!0);append_styles($$anchor,$$css8);setContext("radioGroup",Math.random().toString(36).substring(2,15));node=child(div=root9());consequent=$$anchor2=>{var h3=root_113();snippet(child(h3),(()=>{var _a8;return null!=(_a8=$$props.question)?_a8:noop2}));reset(h3);append($$anchor2,h3)};if_block(node,($$render=>{$$props.question&&$$render(consequent)}));snippet(child(div_1=sibling(node,2)),(()=>{var _a8;return null!=(_a8=$$props.children)?_a8:noop2}));reset(div_1);reset(div);append($$anchor,div);pop()}function Option($$anchor,$$props){var div,label2,div_1,input,input_value,span,text2,div_2,node,consequent,alternate;push($$props,!0);append_styles($$anchor,$$css9);const definedGroupContext=getContext("radioGroup");let value=prop($$props,"value",15);const actualGroup=null!==$$props.group&&void 0!==$$props.group?$$props.group:definedGroupContext;label2=child(div=root10());div_1=child(label2);remove_input_defaults(input=child(div_1));span=sibling(input,2);text2=child(span,!0);reset(span);reset(div_1);node=child(div_2=sibling(div_1,2));consequent=$$anchor2=>{var fragment=comment();snippet(first_child(fragment),(()=>$$props.noteOnSelected));append($$anchor2,fragment)};alternate=$$anchor2=>{var fragment_1=comment(),node_2=first_child(fragment_1),consequent_1=$$anchor3=>{var fragment_2=comment();snippet(first_child(fragment_2),(()=>$$props.noteOnUnselected));append($$anchor3,fragment_2)};if_block(node_2,($$render=>{value()!==$$props.selectedValue&&$$props.noteOnUnselected&&$$render(consequent_1)}),!0);append($$anchor2,fragment_1)};if_block(node,($$render=>{value()===$$props.selectedValue&&$$props.noteOnSelected?$$render(consequent):$$render(alternate,!1)}));snippet(sibling(node,2),(()=>{var _a8;return null!=(_a8=$$props.children)?_a8:noop2}));reset(div_2);reset(label2);reset(div);template_effect((()=>{var _a8;set_class(div,1,"option-container "+(value()===$$props.selectedValue?"selected":""),"svelte-1h8m5at");set_attribute2(input,"name",actualGroup);input_value!==(input_value=$$props.selectedValue)&&(input.value=null!=(_a8=input.__value=$$props.selectedValue)?_a8:"");set_text(text2,$$props.title)}));bind_group([],[],input,(()=>{$$props.selectedValue;return value()}),value);append($$anchor,div);pop()}function Options($$anchor,$$props){var div;push($$props,!0);setContext("radioGroup",Math.random().toString(36).substring(2,15));snippet(child(div=root11()),(()=>{var _a8;return null!=(_a8=$$props.children)?_a8:noop2}));reset(div);append($$anchor,div);pop()}function Instruction($$anchor,$$props){var div=root12();snippet(child(div),(()=>{var _a8;return null!=(_a8=$$props.children)?_a8:noop2}));reset(div);append($$anchor,div)}function UserDecisions($$anchor,$$props){var div=root13(),node=child(div),consequent=$$anchor2=>{var fragment=comment();snippet(first_child(fragment),(()=>$$props.children));append($$anchor2,fragment)};if_block(node,($$render=>{$$props.children&&$$render(consequent)}));reset(div);append($$anchor,div)}function Intro($$anchor,$$props){var fragment,node,node_1,node_2;push($$props,!0);let userType=state("cancelled"),proceedTitle=user_derived((()=>"new-user"===get(userType)?"Yes, I want to set up a new synchronisation":"existing-user"===get(userType)?"Yes, I want to add this device to my existing synchronisation":"Please select an option to proceed"));const canProceed=user_derived((()=>"new-user"===get(userType)||"existing-user"===get(userType)));DialogHeader(node=first_child(fragment=root14()),{title:"Welcome to Self-hosted LiveSync"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("We will now guide you through a few questions to simplify the synchronisation setup."))},$$slots:{default:!0}});Instruction(node_2=sibling(node_1,2),{children:($$anchor2,$$slotProps)=>{var fragment_1=root_24(),node_3=first_child(fragment_1);Question(node_3,{children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("First, please select the option that best describes your current situation."))},$$slots:{default:!0}});Options(sibling(node_3,2),{children:($$anchor3,$$slotProps2)=>{var fragment_2=root_44(),node_5=first_child(fragment_2);Option(node_5,{selectedValue:"new-user",title:"I am setting this up for the first time",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("(Select this if you are configuring this device as the first synchronisation device.) This option is\n suitable if you are new to LiveSync and want to set it up from scratch."))},$$slots:{default:!0}});Option(sibling(node_5,2),{selectedValue:"existing-user",title:"I am adding a device to an existing synchronisation setup",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("(Select this if you are already using synchronisation on another computer or smartphone.) This option is\n suitable if you are new to LiveSync and want to set it up from scratch."))},$$slots:{default:!0}});append($$anchor3,fragment_2)},$$slots:{default:!0}});append($$anchor2,fragment_1)},$$slots:{default:!0}});UserDecisions(sibling(node_2,2),{children:($$anchor2,$$slotProps)=>{var fragment_3=root_72(),node_8=first_child(fragment_3);let $0=user_derived((()=>!get(canProceed)));Decision(node_8,{get title(){return get(proceedTitle)},get important(){return get(canProceed)},get disabled(){return get($0)},commit:()=>$$props.setResult(get(userType))});Decision(sibling(node_8,2),{title:"No, please take me back",commit:()=>$$props.setResult("cancelled")});append($$anchor2,fragment_3)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function InfoNote($$anchor,$$props){"use strict";var fragment,node,consequent_1;const isInfo=prop($$props,"info",3,!0),derivedCssClass=user_derived((()=>$$props.error?"note-error":$$props.warning?"note-important":isInfo()?"note":""));node=first_child(fragment=comment());consequent_1=$$anchor2=>{var div=root_114(),node_1=child(div),consequent=$$anchor3=>{var h3=root_25(),text2=child(h3,!0);reset(h3);template_effect((()=>set_text(text2,$$props.title)));append($$anchor3,h3)};if_block(node_1,($$render=>{$$props.title&&$$render(consequent)}));snippet(sibling(node_1,2),(()=>{var _a8;return null!=(_a8=$$props.children)?_a8:noop2}));reset(div);template_effect((()=>{var _a8;return set_class(div,1,(null!=(_a8=$$props.cssClass)?_a8:"")+" "+get(derivedCssClass))}));append($$anchor2,div)};if_block(node,($$render=>{void 0!==$$props.visible&&!0!==$$props.visible||$$render(consequent_1)}));append($$anchor,fragment)}function ExtraItems($$anchor,$$props){"use strict";var div,details=root15(),summary=child(details),text2=child(summary,!0);reset(summary);snippet(child(div=sibling(summary,2)),(()=>{var _a8;return null!=(_a8=$$props.children)?_a8:noop2}));reset(div);reset(details);template_effect((()=>set_text(text2,$$props.title)));append($$anchor,details)}function Check($$anchor,$$props){var fragment,label2,input,span,text2,div,node,consequent,alternate;push($$props,!0);append_styles($$anchor,$$css10);let value=prop($$props,"value",15);remove_input_defaults(input=child(label2=first_child(fragment=root16())));span=sibling(input,2);text2=child(span,!0);reset(span);reset(label2);node=child(div=sibling(label2,2));consequent=$$anchor2=>{var fragment_1=comment();snippet(first_child(fragment_1),(()=>$$props.noteOnSelected));append($$anchor2,fragment_1)};alternate=$$anchor2=>{var fragment_2=comment(),node_2=first_child(fragment_2),consequent_1=$$anchor3=>{var fragment_3=comment();snippet(first_child(fragment_3),(()=>$$props.noteOnUnselected));append($$anchor3,fragment_3)};if_block(node_2,($$render=>{!value()&&$$props.noteOnUnselected&&$$render(consequent_1)}),!0);append($$anchor2,fragment_2)};if_block(node,($$render=>{value()&&$$props.noteOnSelected?$$render(consequent):$$render(alternate,!1)}));snippet(sibling(node,2),(()=>{var _a8;return null!=(_a8=$$props.children)?_a8:noop2}));reset(div);template_effect((()=>set_text(text2,$$props.title)));bind_checked(input,value);append($$anchor,fragment);pop()}function SelectMethodNewUser($$anchor,$$props){var fragment,node,node_1,node_2;push($$props,!0);let userType=state("cancelled"),proceedTitle=user_derived((()=>"use-setup-uri"===get(userType)?"Proceed with Setup URI":"configure-manually"===get(userType)?"I know my server details, let me enter them":"Please select an option to proceed"));const canProceed=user_derived((()=>"use-setup-uri"===get(userType)||"configure-manually"===get(userType)));DialogHeader(node=first_child(fragment=root17()),{title:"Connection Method"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("We will now proceed with the server configuration."))},$$slots:{default:!0}});Instruction(node_2=sibling(node_1,2),{children:($$anchor2,$$slotProps)=>{var fragment_1=root_26(),node_3=first_child(fragment_1);Question(node_3,{children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("How would you like to configure the connection to your server?"))},$$slots:{default:!0}});Options(sibling(node_3,2),{children:($$anchor3,$$slotProps2)=>{var fragment_2=root_45(),node_5=first_child(fragment_2);Option(node_5,{selectedValue:"use-setup-uri",title:"Use a Setup URI (Recommended)",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("A Setup URI is a single string of text containing your server address and authentication details. Using a\n URI, if one was generated by your server installation script, provides a simple and secure configuration."))},$$slots:{default:!0}});Option(sibling(node_5,2),{selectedValue:"configure-manually",title:"Enter the server information manually",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("This is an advanced option for users who do not have a URI or who wish to configure detailed settings."))},$$slots:{default:!0}});append($$anchor3,fragment_2)},$$slots:{default:!0}});append($$anchor2,fragment_1)},$$slots:{default:!0}});UserDecisions(sibling(node_2,2),{children:($$anchor2,$$slotProps)=>{var fragment_3=root_73(),node_8=first_child(fragment_3);let $0=user_derived((()=>!get(canProceed)));Decision(node_8,{get title(){return get(proceedTitle)},get important(){return get(canProceed)},get disabled(){return get($0)},commit:()=>$$props.setResult(get(userType))});Decision(sibling(node_8,2),{title:"Cancel",commit:()=>$$props.setResult("cancelled")});append($$anchor2,fragment_3)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function SelectMethodExisting($$anchor,$$props){var fragment,node,node_1,node_2;push($$props,!0);let userType=state("cancelled"),proceedTitle=user_derived((()=>"use-setup-uri"===get(userType)?"Proceed with Setup URI":"configure-manually"===get(userType)?"I know my server details, let me enter them":"scan-qr-code"===get(userType)?"Scan the QR code displayed on an active device using this device's camera.":"Please select an option to proceed"));const canProceed=user_derived((()=>"use-setup-uri"===get(userType)||"configure-manually"===get(userType)||"scan-qr-code"===get(userType)));DialogHeader(node=first_child(fragment=root18()),{title:"Device Setup Method"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("You are adding this device to an existing synchronisation setup."))},$$slots:{default:!0}});Instruction(node_2=sibling(node_1,2),{children:($$anchor2,$$slotProps)=>{var fragment_1=root_27(),node_3=first_child(fragment_1);Question(node_3,{children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("Please select a method to import the settings from another device."))},$$slots:{default:!0}});Options(sibling(node_3,2),{children:($$anchor3,$$slotProps2)=>{var node_6,fragment_2=root_46(),node_5=first_child(fragment_2);Option(node_5,{selectedValue:"use-setup-uri",title:"Use a Setup URI (Recommended)",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("Paste the Setup URI generated from one of your active devices."))},$$slots:{default:!0}});Option(node_6=sibling(node_5,2),{selectedValue:"scan-qr-code",title:"Scan a QR Code (Recommended for mobile)",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("Scan the QR code displayed on an active device using this device's camera."))},$$slots:{default:!0}});Option(sibling(node_6,2),{selectedValue:"configure-manually",title:"Enter the server information manually",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("Configure the same server information as your other devices again, manually, very advanced users only."))},$$slots:{default:!0}});append($$anchor3,fragment_2)},$$slots:{default:!0}});append($$anchor2,fragment_1)},$$slots:{default:!0}});UserDecisions(sibling(node_2,2),{children:($$anchor2,$$slotProps)=>{var fragment_3=root_83(),node_9=first_child(fragment_3);let $0=user_derived((()=>!get(canProceed)));Decision(node_9,{get title(){return get(proceedTitle)},get important(){return get(canProceed)},get disabled(){return get($0)},commit:()=>$$props.setResult(get(userType))});Decision(sibling(node_9,2),{title:"Cancel",commit:()=>$$props.setResult("cancelled")});append($$anchor2,fragment_3)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function ScanQRCode($$anchor,$$props){var fragment,node,node_1,node_2;push($$props,!0);DialogHeader(node=first_child(fragment=root19()),{title:"Scan QR Code"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("Please follow the steps below to import settings from your existing device."))},$$slots:{default:!0}});Instruction(node_2=sibling(node_1,2),{children:($$anchor2,$$slotProps)=>{append($$anchor2,root_28())},$$slots:{default:!0}});UserDecisions(sibling(node_2,2),{children:($$anchor2,$$slotProps)=>{Decision($$anchor2,{title:"Close this dialog",important:!0,commit:()=>$$props.setResult("close")})},$$slots:{default:!0}});append($$anchor,fragment);pop()}function InputRow($$anchor,$$props){"use strict";var label_1=root20(),span=child(label_1),text2=child(span,!0);reset(span);snippet(sibling(span,2),(()=>{var _a8;return null!=(_a8=$$props.children)?_a8:noop2}));reset(label_1);template_effect((()=>set_text(text2,$$props.label)));append($$anchor,label_1)}function Password($$anchor,$$props){var fragment,input,input_1;push($$props,!0);let value=prop($$props,"value",15),name=prop($$props,"name",3,"password"),placeholder=prop($$props,"placeholder",3,"Enter your password"),disabled=prop($$props,"disabled",3,!1),required=prop($$props,"required",3,!1),showPassword=state(!1);const type=user_derived((()=>get(showPassword)?"text":"password"));fragment=root21();remove_input_defaults(input=first_child(fragment));remove_input_defaults(input_1=sibling(input,2));template_effect((()=>{set_attribute2(input,"type",get(type));set_attribute2(input,"name",name());set_attribute2(input,"placeholder",placeholder());input.disabled=disabled();input.required=required()}));bind_value(input,value);bind_checked(input_1,(()=>get(showPassword)),($$value=>set(showPassword,$$value)));append($$anchor,fragment);pop()}async function encryptString(source2,passphrase){return source2.startsWith(ENCRYPT_V2_PREFIX)||source2.startsWith(HKDF_SALTED_ENCRYPTED_PREFIX)?source2:await encryptWithEphemeralSalt(source2,passphrase)}async function tryDecryption(trials){for(const trial of trials)try{return await trial()}catch(error){Logger(`Decryption trial failed: ${error}`,LOG_LEVEL_VERBOSE)}throw new Error("All decryption trials failed")}async function decryptString(encrypted,passphrase){if(encrypted.startsWith(HKDF_SALTED_ENCRYPTED_PREFIX))return decryptWithEphemeralSalt(encrypted,passphrase);if(encrypted.startsWith(ENCRYPT_V2_PREFIX)||encrypted.startsWith(ENCRYPT_V3_PREFIX)||encrypted.startsWith(ENCRYPT_V1_PREFIX_PROBABLY))return await tryDecryption([async()=>await decrypt4(encrypted,passphrase,!1),async()=>await decrypt4(encrypted,passphrase,!0)]);throw new Error("Unsupported encryption format")}function UseSetupURI($$anchor,$$props){async function processSetupURI(){set(error,"");if(get(seemsValid))if(get(passphrase))try{const settingPieces=get(setupURI).substring(configURIBase.length),encodedConfig=decodeURIComponent(settingPieces),newConf=await JSON.parse(await decryptString(encodedConfig,get(passphrase)));$$props.setResult(newConf);return}catch(e3){set(error,"Failed to parse Setup-URI.");return}else set(error,"Passphrase is required.")}async function canProceed(){var _a8;return null!==(_a8=await processSetupURI())&&void 0!==_a8&&_a8}var fragment,node,node_1,node_2,node_3,node_4,node_5,node_6;push($$props,!0);let setupURI=state(""),passphrase=state(""),error=state("");onMount((()=>{if($$props.getInitialData){const initialURI=$$props.getInitialData();initialURI&&set(setupURI,initialURI,!0)}}));const seemsValid=user_derived((()=>get(setupURI).startsWith(configURIBase)));DialogHeader(node=first_child(fragment=root22()),{title:"Enter Setup URI"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{next();var fragment_1=root_115();next(2);append($$anchor2,fragment_1)},$$slots:{default:!0}});InputRow(node_2=sibling(node_1,2),{label:"Setup-URI",children:($$anchor2,$$slotProps)=>{var input=root_29();remove_input_defaults(input);bind_value(input,(()=>get(setupURI)),($$value=>set(setupURI,$$value)));append($$anchor2,input)},$$slots:{default:!0}});InfoNote(node_3=sibling(node_2,2),{get visible(){return get(seemsValid)},children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("The Setup-URI is valid and ready to use."))},$$slots:{default:!0}});node_4=sibling(node_3,2);{let $0=user_derived((()=>!get(seemsValid)&&""!=get(setupURI).trim()));InfoNote(node_4,{warning:!0,get visible(){return get($0)},children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("The Setup-URI does not appear to be valid. Please check that you have copied it correctly."))},$$slots:{default:!0}})}InputRow(node_5=sibling(node_4,2),{label:"Passphrase",children:($$anchor2,$$slotProps)=>{Password($$anchor2,{placeholder:"Enter your passphrase",required:!0,get value(){return get(passphrase)},set value($$value){set(passphrase,$$value,!0)}})},$$slots:{default:!0}});node_6=sibling(node_5,2);{let $0=user_derived((()=>""!=get(error).trim()));InfoNote(node_6,{error:!0,get visible(){return get($0)},children:($$anchor2,$$slotProps)=>{next();var text_2=text();template_effect((()=>set_text(text_2,get(error))));append($$anchor2,text_2)},$$slots:{default:!0}})}UserDecisions(sibling(node_6,2),{children:($$anchor2,$$slotProps)=>{var fragment_4=root_74(),node_8=first_child(fragment_4);Decision(node_8,{title:"Test Settings and Continue",important:!0,disabled:!canProceed,commit:()=>processSetupURI()});Decision(sibling(node_8,2),{title:"Cancel",commit:()=>$$props.setResult("cancelled")});append($$anchor2,fragment_4)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function OutroNewUser($$anchor,$$props){var fragment,node,node_1,node_2;push($$props,!0);DialogHeader(node=first_child(fragment=root23()),{title:"Setup Complete: Preparing to Initialise Server"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{var fragment_1=root_116();next(2);append($$anchor2,fragment_1)},$$slots:{default:!0}});Instruction(node_2=sibling(node_1,2),{children:($$anchor2,$$slotProps)=>{Question($$anchor2,{children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("Please select the button below to restart and proceed to the final confirmation."))},$$slots:{default:!0}})},$$slots:{default:!0}});UserDecisions(sibling(node_2,2),{children:($$anchor2,$$slotProps)=>{var fragment_3=root_47(),node_4=first_child(fragment_3);Decision(node_4,{title:"Restart and Initialise Server",important:!0,commit:()=>$$props.setResult("apply")});Decision(sibling(node_4,2),{title:"No, please take me back",commit:()=>$$props.setResult("cancelled")});append($$anchor2,fragment_3)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function OutroExistingUser($$anchor,$$props){var fragment,node,node_1,node_2;push($$props,!0);DialogHeader(node=first_child(fragment=root24()),{title:"Setup Complete: Preparing to Fetch Synchronisation Data"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{var fragment_1=root_117();next(2);append($$anchor2,fragment_1)},$$slots:{default:!0}});Instruction(node_2=sibling(node_1,2),{children:($$anchor2,$$slotProps)=>{Question($$anchor2,{children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("Please select the button below to restart and proceed to the data fetching confirmation."))},$$slots:{default:!0}})},$$slots:{default:!0}});UserDecisions(sibling(node_2,2),{children:($$anchor2,$$slotProps)=>{var fragment_3=root_48(),node_4=first_child(fragment_3);Decision(node_4,{title:"Restart and Fetch Data",important:!0,commit:()=>$$props.setResult("apply")});Decision(sibling(node_4,2),{title:"No, please take me back",commit:()=>$$props.setResult("cancelled")});append($$anchor2,fragment_3)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function OutroAskUserMode($$anchor,$$props){var fragment,node,node_1,node_2;push($$props,!0);let userType=state("cancelled");const canProceed=user_derived((()=>"existing-user"===get(userType)||"new-user"===get(userType)||"compatible-existing-user"===get(userType))),proceedMessage=user_derived((()=>"new-user"===get(userType)||"existing-user"===get(userType)?"Proceed to the next step.":"compatible-existing-user"===get(userType)?"Apply the settings":"Please select an option to proceed"));DialogHeader(node=first_child(fragment=root25()),{title:"Mostly Complete: Decision Required"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{next();var fragment_1=root_118();next();append($$anchor2,fragment_1)},$$slots:{default:!0}});Instruction(node_2=sibling(node_1,2),{children:($$anchor2,$$slotProps)=>{var node_4,node_5,fragment_2=root_210(),node_3=first_child(fragment_2);Question(node_3,{children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("Please select your situation."))},$$slots:{default:!0}});Option(node_4=sibling(node_3,2),{title:"I am setting up a new server for the first time / I want to reset my existing server.",selectedValue:"new-user",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor3,$$slotProps2)=>{InfoNote($$anchor3,{children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("Selecting this option will result in the current data on this device being used to initialise the server.\n Any existing data on the server will be completely overwritten."))},$$slots:{default:!0}})},$$slots:{default:!0}});Option(node_5=sibling(node_4,2),{title:"My remote server is already set up. I want to join this device.",selectedValue:"existing-user",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor3,$$slotProps2)=>{InfoNote($$anchor3,{children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("Selecting this option will result in this device joining the existing server. You need to fetching the\n existing synchronisation data from the server to this device."))},$$slots:{default:!0}})},$$slots:{default:!0}});Option(sibling(node_5,2),{title:"The remote is already set up, and the configuration is compatible (or got compatible by this operation).",selectedValue:"compatible-existing-user",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor3,$$slotProps2)=>{InfoNote($$anchor3,{warning:!0,children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("Unless you are certain, selecting this options is bit dangerous. It assumes that the server configuration is\n compatible with this device. If this is not the case, data loss may occur. Please ensure you know what you\n are doing."))},$$slots:{default:!0}})},$$slots:{default:!0}});append($$anchor2,fragment_2)},$$slots:{default:!0}});UserDecisions(sibling(node_2,2),{children:($$anchor2,$$slotProps)=>{var fragment_6=root_102(),node_8=first_child(fragment_6);let $0=user_derived((()=>!get(canProceed)));Decision(node_8,{get title(){return get(proceedMessage)},important:!0,get disabled(){return get($0)},commit:()=>$$props.setResult(get(userType))});Decision(sibling(node_8,2),{title:"No, please take me back",commit:()=>$$props.setResult("cancelled")});append($$anchor2,fragment_6)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function SetupRemote($$anchor,$$props){var fragment,node,node_1;push($$props,!0);let userType=state("cancelled"),proceedTitle=user_derived((()=>"couchdb"===get(userType)?"Continue to CouchDB setup":"bucket"===get(userType)?"Continue to S3/MinIO/R2 setup":"p2p"===get(userType)?"Continue to Peer-to-Peer only setup":"Please select an option to proceed"));const canProceed=user_derived((()=>"couchdb"===get(userType)||"bucket"===get(userType)||"p2p"===get(userType)));DialogHeader(node=first_child(fragment=root26()),{title:"Enter Server Information"});Instruction(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{var fragment_1=root_119(),node_2=first_child(fragment_1);Question(node_2,{children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("Please select the type of server to which you are connecting."))},$$slots:{default:!0}});Options(sibling(node_2,2),{children:($$anchor3,$$slotProps2)=>{var node_5,fragment_2=root_33(),node_4=first_child(fragment_2);Option(node_4,{selectedValue:"couchdb",title:"CouchDB",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("This is the most suitable synchronisation method for the design. All functions are available. You must have\n set up a CouchDB instance."))},$$slots:{default:!0}});Option(node_5=sibling(node_4,2),{selectedValue:"bucket",title:"S3/MinIO/R2 Object Storage",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("Synchronisation utilising journal files. You must have set up an S3/MinIO/R2 compatible object storage."))},$$slots:{default:!0}});Option(sibling(node_5,2),{selectedValue:"p2p",title:"Peer-to-Peer only",get value(){return get(userType)},set value($$value){set(userType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("This is an experimental feature enabling direct synchronisation between devices. No server is required, but\n both devices must be online at the same time for synchronisation to occur, and some features may be limited.\n Internet connection is only required to signalling (detecting peers) and not for data transfer."))},$$slots:{default:!0}});append($$anchor3,fragment_2)},$$slots:{default:!0}});append($$anchor2,fragment_1)},$$slots:{default:!0}});UserDecisions(sibling(node_1,2),{children:($$anchor2,$$slotProps)=>{var fragment_3=root_75(),node_8=first_child(fragment_3);let $0=user_derived((()=>!get(canProceed)));Decision(node_8,{get title(){return get(proceedTitle)},get important(){return get(canProceed)},get disabled(){return get($0)},commit:()=>$$props.setResult(get(userType))});Decision(sibling(node_8,2),{title:"No, please take me back",commit:()=>$$props.setResult("cancelled")});append($$anchor2,fragment_3)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function isGreaterThanOrEqual(baseVersion,version2){const versionParts=`${baseVersion}.0.0.0`.split("."),targetParts=version2.split(".");for(let i2=0;i2<targetParts.length;i2++){const result=versionParts[i2].localeCompare(targetParts[i2],void 0,{numeric:!0});if(result>0)return!0;if(result<0)return!1}return!0}async function updateRemoteSetting(setting,key3,value){const customHeaders=parseHeaderValues(setting.couchDB_CustomHeaders),credential=generateCredentialObject(setting),res2=await requestToCouchDBWithCredentials(setting.couchDB_URI,credential,void 0,key3,value,void 0,customHeaders);return 200==res2.status||res2.text||"Unknown error"}function PanelCouchDBCheck($$anchor,$$props){async function testAndFixSettings(){set(detectedIssues,[],!0);try{const fixResults=await checkConfig($$props.trialRemoteSetting);console.dir(fixResults);set(detectedIssues,fixResults,!0)}catch(e3){console.error("Error during testAndFixSettings:",e3);get(detectedIssues).push({message:`Error during testAndFixSettings: ${e3}`,result:"error",classes:[]})}}function isErrorResult(result2){return"result"in result2&&"error"===result2.result}function isFixableError(result2){return isErrorResult(result2)&&"fix"in result2&&"function"==typeof result2.fix}function isSuccessResult(result2){return"result"in result2&&"ok"===result2.result}async function fixIssue(issue){try{set(processing,!0);await issue.fix()}catch(e3){console.error("Error during fixIssue:",e3)}await testAndFixSettings();set(processing,!1)}var fragment,node_1,div_3,details,summary,node_2,consequent_1,alternate_1,node_4,consequent_3;push($$props,!0);append_styles($$anchor,$$css11);const result=($$anchor2,issue=noop2)=>{var node,consequent,div=root_120(),div_1=child(div),text2=child(div_1,!0);reset(div_1);node=sibling(div_1,2);consequent=$$anchor3=>{var div_2=root_211(),button=child(div_2);button.__click=[on_click2,fixIssue,issue];reset(div_2);template_effect((()=>button.disabled=get(processing)));append($$anchor3,div_2)};if_block(node,($$render=>{isFixableError(issue())&&$$render(consequent)}));reset(div);template_effect(($0=>{set_class(div,1,`check-result ${null!=$0?$0:""}`,"svelte-a38xug");set_text(text2,issue().message)}),[()=>isErrorResult(issue())?"error":isSuccessResult(issue())?"success":""]);append($$anchor2,div)};let detectedIssues=state(proxy([])),processing=state(!1);const errorIssueCount=user_derived((()=>get(detectedIssues).filter((issue=>isErrorResult(issue))).length)),isAllSuccess=user_derived((()=>!(get(errorIssueCount)>0&&get(detectedIssues).length>0)));UserDecisions(node_1=first_child(fragment=root27()),{children:($$anchor2,$$slotProps)=>{Decision($$anchor2,{title:"Detect and Fix CouchDB Issues",important:!0,commit:testAndFixSettings})},$$slots:{default:!0}});div_3=sibling(node_1,2);details=child(div_3);summary=child(details);node_2=child(summary);consequent_1=$$anchor2=>{append($$anchor2,text("No checks have been performed yet."))};alternate_1=$$anchor2=>{var fragment_2=comment(),node_3=first_child(fragment_2),consequent_2=$$anchor3=>{append($$anchor3,text("All checks passed successfully!"))},alternate=$$anchor3=>{var text_3=text();template_effect((()=>{var _a8;return set_text(text_3,`${null!=(_a8=get(errorIssueCount))?_a8:""} issue(s) detected!`)}));append($$anchor3,text_3)};if_block(node_3,($$render=>{get(isAllSuccess)?$$render(consequent_2):$$render(alternate,!1)}),!0);append($$anchor2,fragment_2)};if_block(node_2,($$render=>{0===get(detectedIssues).length?$$render(consequent_1):$$render(alternate_1,!1)}));reset(summary);node_4=sibling(summary,2);consequent_3=$$anchor2=>{var fragment_4=root_84();each(sibling(first_child(fragment_4),2),17,(()=>get(detectedIssues)),index,(($$anchor3,issue)=>{result($$anchor3,(()=>get(issue)))}));append($$anchor2,fragment_4)};if_block(node_4,($$render=>{get(detectedIssues).length>0&&$$render(consequent_3)}));reset(details);reset(div_3);template_effect((()=>details.open=!get(isAllSuccess)));append($$anchor,fragment);pop()}function SetupRemoteCouchDB($$anchor,$$props){function generateSetting(){const trialSettings={...{...syncSetting}},preferredSetting=isCloudantURI(syncSetting.couchDB_URI)?PREFERRED_SETTING_CLOUDANT:PREFERRED_SETTING_SELF_HOSTED;return{...DEFAULT_SETTINGS,...preferredSetting,remoteType:RemoteTypes_REMOTE_COUCHDB,...trialSettings}}async function checkConnection(){try{set(processing,!0);const trialRemoteSetting=generateSetting(),replicator=await context2.services.replicator.getNewReplicator(trialRemoteSetting);if(!replicator)return"Failed to create replicator instance.";try{return await replicator.tryConnectRemote(trialRemoteSetting,!1)?"":"Failed to connect to the server. Please check your settings."}catch(e3){return`Failed to connect to the server: ${e3}`}}finally{set(processing,!1)}}async function checkAndCommit(){set(error,"");try{set(error,await checkConnection()||"",!0);if(!get(error)){const setting=generateSetting();$$props.setResult(pickCouchDBSyncSettings(setting));return}}catch(e3){set(error,`Error during connection test: ${e3}`);return}}function commit(){const setting=pickCouchDBSyncSettings(generateSetting());$$props.setResult(setting)}function cancel2(){$$props.setResult("cancelled")}var fragment,node,node_1,node_2,node_3,node_4,node_5,node_6,node_7,node_8,node_9,node_10,node_11,node_20,node_21,node_22,consequent,alternate;push($$props,!0);let syncSetting=proxy({...pickCouchDBSyncSettings(DEFAULT_SETTINGS)});onMount((()=>{if($$props.getInitialData){const initialData=$$props.getInitialData();initialData&&copyTo(initialData,syncSetting)}}));let error=state("");const context2=getObsidianDialogContext();let processing=state(!1);const isURIInsecure=user_derived((()=>!(!syncSetting.couchDB_URI||!syncSetting.couchDB_URI.startsWith("http://")))),isUseJWT=user_derived((()=>syncSetting.useJWT)),canProceed=user_derived((()=>syncSetting.couchDB_URI.trim().length>0&&syncSetting.couchDB_USER.trim().length>0&&syncSetting.couchDB_PASSWORD.trim().length>0&&syncSetting.couchDB_DBNAME.trim().length>0&&(!get(isUseJWT)||syncSetting.jwtKey.trim().length>0))),testSettings=user_derived((()=>generateSetting()));DialogHeader(node=first_child(fragment=root28()),{title:"CouchDB Configuration"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("Please enter the CouchDB server information below."))},$$slots:{default:!0}});InputRow(node_2=sibling(node_1,2),{label:"URL",children:($$anchor2,$$slotProps)=>{var input=root_212();remove_input_defaults(input);bind_value(input,(()=>syncSetting.couchDB_URI),($$value=>syncSetting.couchDB_URI=$$value));append($$anchor2,input)},$$slots:{default:!0}});InfoNote(node_3=sibling(node_2,2),{warning:!0,get visible(){return get(isURIInsecure)},children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("We can use only Secure (HTTPS) connections on Obsidian Mobile."))},$$slots:{default:!0}});InputRow(node_4=sibling(node_3,2),{label:"Username",children:($$anchor2,$$slotProps)=>{var input_1=root_49();remove_input_defaults(input_1);bind_value(input_1,(()=>syncSetting.couchDB_USER),($$value=>syncSetting.couchDB_USER=$$value));append($$anchor2,input_1)},$$slots:{default:!0}});InputRow(node_5=sibling(node_4,2),{label:"Password",children:($$anchor2,$$slotProps)=>{Password($$anchor2,{name:"couchdb-password",placeholder:"Enter your password",required:!0,get value(){return syncSetting.couchDB_PASSWORD},set value($$value){syncSetting.couchDB_PASSWORD=$$value}})},$$slots:{default:!0}});InputRow(node_6=sibling(node_5,2),{label:"Database Name",children:($$anchor2,$$slotProps)=>{var input_2=root_64();remove_input_defaults(input_2);bind_value(input_2,(()=>syncSetting.couchDB_DBNAME),($$value=>syncSetting.couchDB_DBNAME=$$value));append($$anchor2,input_2)},$$slots:{default:!0}});InfoNote(node_7=sibling(node_6,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("You cannot use capital letters, spaces, or special characters in the database name. And not allowed to start with an\n underscore (_)."))},$$slots:{default:!0}});InputRow(node_8=sibling(node_7,2),{label:"Use Internal API",children:($$anchor2,$$slotProps)=>{var input_3=root_85();remove_input_defaults(input_3);bind_checked(input_3,(()=>syncSetting.useRequestAPI),($$value=>syncSetting.useRequestAPI=$$value));append($$anchor2,input_3)},$$slots:{default:!0}});InfoNote(node_9=sibling(node_8,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("If you cannot avoid CORS issues, you might want to try this option. It uses Obsidian's internal API to communicate\n with the CouchDB server. Not compliant with web standards, but works. Note that this might break in future Obsidian\n versions."))},$$slots:{default:!0}});ExtraItems(node_10=sibling(node_9,2),{title:"Advanced Settings",children:($$anchor2,$$slotProps)=>{InputRow($$anchor2,{label:"Custom Headers",children:($$anchor3,$$slotProps2)=>{var textarea=root_1110();remove_textarea_child(textarea);bind_value(textarea,(()=>syncSetting.couchDB_CustomHeaders),($$value=>syncSetting.couchDB_CustomHeaders=$$value));append($$anchor3,textarea)},$$slots:{default:!0}})},$$slots:{default:!0}});ExtraItems(node_11=sibling(node_10,2),{title:"Experimental Settings",children:($$anchor2,$$slotProps)=>{var node_13,node_14,node_15,node_16,node_17,node_18,fragment_3=root_123(),node_12=first_child(fragment_3);InputRow(node_12,{label:"Use JWT Authentication",children:($$anchor3,$$slotProps2)=>{var input_4=root_134();remove_input_defaults(input_4);bind_checked(input_4,(()=>syncSetting.useJWT),($$value=>syncSetting.useJWT=$$value));append($$anchor3,input_4)},$$slots:{default:!0}});InputRow(node_13=sibling(node_12,2),{label:"JWT Algorithm",children:($$anchor3,$$slotProps2)=>{var option_1,option_2,option_3,select=root_142(),option=child(select);option.value=option.__value="HS256";(option_1=sibling(option)).value=option_1.__value="HS512";(option_2=sibling(option_1)).value=option_2.__value="ES256";(option_3=sibling(option_2)).value=option_3.__value="ES512";reset(select);template_effect((()=>select.disabled=!get(isUseJWT)));bind_select_value(select,(()=>syncSetting.jwtAlgorithm),($$value=>syncSetting.jwtAlgorithm=$$value));append($$anchor3,select)},$$slots:{default:!0}});InputRow(node_14=sibling(node_13,2),{label:"JWT Expiration Duration (minutes)",children:($$anchor3,$$slotProps2)=>{var input_5=root_152();remove_input_defaults(input_5);template_effect((()=>input_5.disabled=!get(isUseJWT)));bind_value(input_5,(()=>`${syncSetting.jwtExpDuration}`),(v2=>syncSetting.jwtExpDuration=parseInt(v2)||0));append($$anchor3,input_5)},$$slots:{default:!0}});InputRow(node_15=sibling(node_14,2),{label:"JWT Key",children:($$anchor3,$$slotProps2)=>{var textarea_1=root_162();remove_textarea_child(textarea_1);template_effect((()=>textarea_1.disabled=!get(isUseJWT)));bind_value(textarea_1,(()=>syncSetting.jwtKey),($$value=>syncSetting.jwtKey=$$value));append($$anchor3,textarea_1)},$$slots:{default:!0}});InfoNote(node_16=sibling(node_15,2),{children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("For HS256/HS512 algorithms, provide the shared secret key. For ES256/ES512 algorithms, provide the pkcs8\n PEM-formatted private key."))},$$slots:{default:!0}});InputRow(node_17=sibling(node_16,2),{label:"JWT Key ID (kid)",children:($$anchor3,$$slotProps2)=>{var input_6=root_182();remove_input_defaults(input_6);template_effect((()=>input_6.disabled=!get(isUseJWT)));bind_value(input_6,(()=>syncSetting.jwtKid),($$value=>syncSetting.jwtKid=$$value));append($$anchor3,input_6)},$$slots:{default:!0}});InputRow(node_18=sibling(node_17,2),{label:"JWT Subject (sub)",children:($$anchor3,$$slotProps2)=>{var input_7=root_192();remove_input_defaults(input_7);template_effect((()=>input_7.disabled=!get(isUseJWT)));bind_value(input_7,(()=>syncSetting.jwtSub),($$value=>syncSetting.jwtSub=$$value));append($$anchor3,input_7)},$$slots:{default:!0}});InfoNote(sibling(node_18,2),{warning:!0,children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("JWT (JSON Web Token) authentication allows you to securely authenticate with the CouchDB server using tokens.\n Ensure that your CouchDB server is configured to accept JWTs and that the provided key and settings match the\n server's configuration. Incidentally, I have not verified it very thoroughly."))},$$slots:{default:!0}});append($$anchor2,fragment_3)},$$slots:{default:!0}});PanelCouchDBCheck(node_20=sibling(node_11,2),{get trialRemoteSetting(){return get(testSettings)}});node_21=sibling(node_20,4);{let $0=user_derived((()=>""!==get(error)));InfoNote(node_21,{error:!0,get visible(){return get($0)},children:($$anchor2,$$slotProps)=>{next();var text_6=text();template_effect((()=>set_text(text_6,get(error))));append($$anchor2,text_6)},$$slots:{default:!0}})}node_22=sibling(node_21,2);consequent=$$anchor2=>{append($$anchor2,text("Checking connection... Please wait."))};alternate=$$anchor2=>{UserDecisions($$anchor2,{children:($$anchor3,$$slotProps)=>{var node_24,fragment_6=root_242(),node_23=first_child(fragment_6);let $0=user_derived((()=>!get(canProceed)));Decision(node_23,{title:"Test Settings and Continue",important:!0,get disabled(){return get($0)},commit:()=>checkAndCommit()});Decision(node_24=sibling(node_23,2),{title:"Continue anyway",commit:()=>commit()});Decision(sibling(node_24,2),{title:"Cancel",commit:()=>cancel2()});append($$anchor3,fragment_6)},$$slots:{default:!0}})};if_block(node_22,($$render=>{get(processing)?$$render(consequent):$$render(alternate,!1)}));append($$anchor,fragment);pop()}function SetupRemoteBucket($$anchor,$$props){function generateSetting(){const trialSettings={...{...syncSetting}};return{...DEFAULT_SETTINGS,...PREFERRED_JOURNAL_SYNC,remoteType:RemoteTypes_REMOTE_MINIO,...trialSettings}}async function checkConnection(){try{set(processing,!0);const trialRemoteSetting=generateSetting(),replicator=await context2.services.replicator.getNewReplicator(trialRemoteSetting);if(!replicator)return"Failed to create replicator instance.";try{return await replicator.tryConnectRemote(trialRemoteSetting,!1)?"":"Failed to connect to the server. Please check your settings."}catch(e3){return`Failed to connect to the server: ${e3}`}}finally{set(processing,!1)}}async function checkAndCommit(){set(error,"");try{set(error,await checkConnection()||"",!0);if(!get(error)){const setting=generateSetting();$$props.setResult(pickBucketSyncSettings(setting));return}}catch(e3){set(error,`Error during connection test: ${e3}`);return}}function commit(){const setting=pickBucketSyncSettings(generateSetting());$$props.setResult(setting)}function cancel2(){$$props.setResult("cancelled")}var fragment,node,node_1,node_2,node_3,node_4,node_5,node_6,node_7,node_8,node_9,node_10,node_11,node_12,node_13,node_14,node_15,consequent,alternate;push($$props,!0);let syncSetting=proxy({...pickBucketSyncSettings(DEFAULT_SETTINGS)});onMount((()=>{if($$props.getInitialData){const initialData=$$props.getInitialData();initialData&&copyTo(initialData,syncSetting)}}));let error=state("");const context2=getObsidianDialogContext(),isEndpointSecure=user_derived((()=>syncSetting.endpoint.trim().toLowerCase().startsWith("https://"))),isEndpointInsecure=user_derived((()=>syncSetting.endpoint.trim().toLowerCase().startsWith("http://"))),isEndpointSupplied=user_derived((()=>get(isEndpointInsecure)||get(isEndpointSecure))),canProceed=user_derived((()=>""!==syncSetting.accessKey.trim()&&""!==syncSetting.secretKey.trim()&&""!==syncSetting.bucket.trim()&&""!==syncSetting.endpoint.trim()&&""!==syncSetting.region.trim()&&get(isEndpointSupplied)));let processing=state(!1);DialogHeader(node=first_child(fragment=root29()),{title:"S3/MinIO/R2 Configuration"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("Please enter the details required to connect to your S3/MinIO/R2 compatible object storage service."))},$$slots:{default:!0}});InputRow(node_2=sibling(node_1,2),{label:"Endpoint URL",children:($$anchor2,$$slotProps)=>{var input=root_213();remove_input_defaults(input);bind_value(input,(()=>syncSetting.endpoint),($$value=>syncSetting.endpoint=$$value));append($$anchor2,input)},$$slots:{default:!0}});InfoNote(node_3=sibling(node_2,2),{warning:!0,get visible(){return get(isEndpointInsecure)},children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("We can use only Secure (HTTPS) connections on Obsidian Mobile."))},$$slots:{default:!0}});InputRow(node_4=sibling(node_3,2),{label:"Access Key ID",children:($$anchor2,$$slotProps)=>{var input_1=root_410();remove_input_defaults(input_1);bind_value(input_1,(()=>syncSetting.accessKey),($$value=>syncSetting.accessKey=$$value));append($$anchor2,input_1)},$$slots:{default:!0}});InputRow(node_5=sibling(node_4,2),{label:"Secret Access Key",children:($$anchor2,$$slotProps)=>{Password($$anchor2,{name:"s3-secret-access-key",placeholder:"Enter your Secret Access Key",required:!0,get value(){return syncSetting.secretKey},set value($$value){syncSetting.secretKey=$$value}})},$$slots:{default:!0}});InputRow(node_6=sibling(node_5,2),{label:"Bucket Name",children:($$anchor2,$$slotProps)=>{var input_2=root_65();remove_input_defaults(input_2);bind_value(input_2,(()=>syncSetting.bucket),($$value=>syncSetting.bucket=$$value));append($$anchor2,input_2)},$$slots:{default:!0}});InputRow(node_7=sibling(node_6,2),{label:"Region",children:($$anchor2,$$slotProps)=>{var input_3=root_76();remove_input_defaults(input_3);bind_value(input_3,(()=>syncSetting.region),($$value=>syncSetting.region=$$value));append($$anchor2,input_3)},$$slots:{default:!0}});InputRow(node_8=sibling(node_7,2),{label:"Use Path-Style Access",children:($$anchor2,$$slotProps)=>{var input_4=root_86();remove_input_defaults(input_4);bind_checked(input_4,(()=>syncSetting.forcePathStyle),($$value=>syncSetting.forcePathStyle=$$value));append($$anchor2,input_4)},$$slots:{default:!0}});InputRow(node_9=sibling(node_8,2),{label:"Folder Prefix",children:($$anchor2,$$slotProps)=>{var input_5=root_93();remove_input_defaults(input_5);bind_value(input_5,(()=>syncSetting.bucketPrefix),($$value=>syncSetting.bucketPrefix=$$value));append($$anchor2,input_5)},$$slots:{default:!0}});InfoNote(node_10=sibling(node_9,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("If you want to store the data in a specific folder within the bucket, you can specify a folder prefix here.\n Otherwise, leave it blank to store data at the root of the bucket."))},$$slots:{default:!0}});InputRow(node_11=sibling(node_10,2),{label:"Use internal API",children:($$anchor2,$$slotProps)=>{var input_6=root_1111();remove_input_defaults(input_6);bind_checked(input_6,(()=>syncSetting.useCustomRequestHandler),($$value=>syncSetting.useCustomRequestHandler=$$value));append($$anchor2,input_6)},$$slots:{default:!0}});InfoNote(node_12=sibling(node_11,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("If you cannot avoid CORS issues, you might want to try this option. It uses Obsidian's internal API to communicate\n with the S3 server. Not compliant with web standards, but works. Note that this might break in future Obsidian\n versions."))},$$slots:{default:!0}});ExtraItems(node_13=sibling(node_12,2),{title:"Advanced Settings",children:($$anchor2,$$slotProps)=>{InputRow($$anchor2,{label:"Custom Headers",children:($$anchor3,$$slotProps2)=>{var textarea=root_143();remove_textarea_child(textarea);bind_value(textarea,(()=>syncSetting.bucketCustomHeaders),($$value=>syncSetting.bucketCustomHeaders=$$value));append($$anchor3,textarea)},$$slots:{default:!0}})},$$slots:{default:!0}});node_14=sibling(node_13,2);{let $0=user_derived((()=>""!==get(error)));InfoNote(node_14,{error:!0,get visible(){return get($0)},children:($$anchor2,$$slotProps)=>{next();var text_4=text();template_effect((()=>set_text(text_4,get(error))));append($$anchor2,text_4)},$$slots:{default:!0}})}node_15=sibling(node_14,2);consequent=$$anchor2=>{append($$anchor2,text("Checking connection... Please wait."))};alternate=$$anchor2=>{UserDecisions($$anchor2,{children:($$anchor3,$$slotProps)=>{var node_17,fragment_5=root_183(),node_16=first_child(fragment_5);let $0=user_derived((()=>!get(canProceed)));Decision(node_16,{title:"Test Settings and Continue",important:!0,get disabled(){return get($0)},commit:()=>checkAndCommit()});Decision(node_17=sibling(node_16,2),{title:"Continue anyway",commit:()=>commit()});Decision(sibling(node_17,2),{title:"Cancel",commit:()=>cancel2()});append($$anchor3,fragment_5)},$$slots:{default:!0}})};if_block(node_15,($$render=>{get(processing)?$$render(consequent):$$render(alternate,!1)}));append($$anchor,fragment);pop()}function createError(error,reason){function CustomPouchError(reason2){var i2,len,names=Object.getOwnPropertyNames(error);for(i2=0,len=names.length;i2<len;i2++)"function"!=typeof error[names[i2]]&&(this[names[i2]]=error[names[i2]]);void 0===this.stack&&(this.stack=(new Error).stack);void 0!==reason2&&(this.reason=reason2)}CustomPouchError.prototype=PouchError.prototype;return new CustomPouchError(reason)}function generateErrorFromResponse(err3){if("object"!=typeof err3){var data=err3;(err3=UNKNOWN_ERROR).data=data}if("error"in err3&&"conflict"===err3.error){err3.name="conflict";err3.status=409}"name"in err3||(err3.name=err3.error||"unknown");"status"in err3||(err3.status=500);"message"in err3||(err3.message=err3.message||err3.reason);"stack"in err3||(err3.stack=(new Error).stack);return err3}function rng2(){if(!getRandomValues2&&!(getRandomValues2="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return getRandomValues2(rnds82)}function createBlob2(parts,properties){var builder,i2;parts=parts||[];properties=properties||{};try{return new Blob(parts,properties)}catch(e3){if("TypeError"!==e3.name)throw e3;builder=new("undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder);for(i2=0;i2<parts.length;i2+=1)builder.append(parts[i2]);return builder.getBlob(properties.type)}}function binaryStringToArrayBuffer(bin){var i2,length=bin.length,buf=new ArrayBuffer(length),arr=new Uint8Array(buf);for(i2=0;i2<length;i2++)arr[i2]=bin.charCodeAt(i2);return buf}function binStringToBluffer(binString,type){return createBlob2([binaryStringToArrayBuffer(binString)],{type})}function b64ToBluffer(b64,type){return binStringToBluffer(thisAtob(b64),type)}function arrayBufferToBinaryString(buffer){var i2,binary="",bytes=new Uint8Array(buffer),length=bytes.byteLength;for(i2=0;i2<length;i2++)binary+=String.fromCharCode(bytes[i2]);return binary}function readAsBinaryString(blob,callback){var reader=new FileReader,hasBinaryString="function"==typeof reader.readAsBinaryString;reader.onloadend=function(e3){var result=e3.target.result||"";if(hasBinaryString)return callback(result);callback(arrayBufferToBinaryString(result))};hasBinaryString?reader.readAsBinaryString(blob):reader.readAsArrayBuffer(blob)}function blobToBinaryString(blobOrBuffer,callback){readAsBinaryString(blobOrBuffer,(function(bin){callback(bin)}))}function blobToBase64(blobOrBuffer,callback){blobToBinaryString(blobOrBuffer,(function(base64){callback(thisBtoa(base64))}))}function readAsArrayBuffer(blob,callback){var reader=new FileReader;reader.onloadend=function(e3){var result=e3.target.result||new ArrayBuffer(0);callback(result)};reader.readAsArrayBuffer(blob)}function rawToBase64(raw){return thisBtoa(raw)}function appendBlob(buffer,blob,start,end,callback){(start>0||end<blob.size)&&(blob=blob.slice(start,end));readAsArrayBuffer(blob,(function(arrayBuffer){buffer.append(arrayBuffer);callback()}))}function appendString(buffer,string,start,end,callback){(start>0||end<string.length)&&(string=string.substring(start,end));buffer.appendBinary(string);callback()}function binaryMd5(data,callback){function next2(){setImmediateShim(loadNextChunk)}function done(){var base64=rawToBase64(buffer.end(!0));callback(base64);buffer.destroy()}function loadNextChunk(){var start=currentChunk*chunkSize2;currentChunk++;append2(buffer,data,start,start+chunkSize2,currentChunk<chunks?next2:done)}var inputIsString="string"==typeof data,len=inputIsString?data.length:data.size,chunkSize2=Math.min(MD5_CHUNK_SIZE,len),chunks=Math.ceil(len/chunkSize2),currentChunk=0,buffer=inputIsString?new import_spark_md5.default:new import_spark_md5.default.ArrayBuffer,append2=inputIsString?appendString:appendBlob;loadNextChunk()}function stringMd5(string){return import_spark_md5.default.hash(string)}function isBinaryObject(object){return"undefined"!=typeof ArrayBuffer&&object instanceof ArrayBuffer||"undefined"!=typeof Blob&&object instanceof Blob}function cloneBinaryObject(object){return object instanceof ArrayBuffer?object.slice(0):object.slice(0,object.size,object.type)}function isPlainObject(value){var Ctor,proto=Object.getPrototypeOf(value);return null===proto||"function"==typeof(Ctor=proto.constructor)&&Ctor instanceof Ctor&&funcToString.call(Ctor)==objectCtorString}function clone2(object){var newObject,i2,len,value;if(!object||"object"!=typeof object)return object;if(Array.isArray(object)){newObject=[];for(i2=0,len=object.length;i2<len;i2++)newObject[i2]=clone2(object[i2]);return newObject}if(object instanceof Date&&isFinite(object))return object.toISOString();if(isBinaryObject(object))return cloneBinaryObject(object);if(!isPlainObject(object))return object;newObject={};for(i2 in object)Object.prototype.hasOwnProperty.call(object,i2)&&void 0!==(value=clone2(object[i2]))&&(newObject[i2]=value);return newObject}function once2(fun){var called=!1;return function(...args){if(called)throw new Error("once called more than once");called=!0;fun.apply(this,args)}}function toPromise(func){return function(...args){var self3,usedCB,promise;args=clone2(args);self3=this;usedCB="function"==typeof args[args.length-1]&&args.pop();promise=new Promise((function(fulfill,reject){var resp,callback;try{callback=once2((function(err3,mesg){err3?reject(err3):fulfill(mesg)}));args.push(callback);(resp=func.apply(self3,args))&&"function"==typeof resp.then&&fulfill(resp)}catch(e3){reject(e3)}}));usedCB&&promise.then((function(result){usedCB(null,result)}),usedCB);return promise}}function logApiCall(self3,name,args){var logArgs,i2,origCallback;if(self3.constructor.listeners("debug").length){logArgs=["api",self3.name,name];for(i2=0;i2<args.length-1;i2++)logArgs.push(args[i2]);self3.constructor.emit("debug",logArgs);origCallback=args[args.length-1];args[args.length-1]=function(err3,res2){var responseArgs=["api",self3.name,name];responseArgs=responseArgs.concat(err3?["error",err3]:["success",res2]);self3.constructor.emit("debug",responseArgs);origCallback(err3,res2)}}}function adapterFun(name,callback){return toPromise((function(...args){if(this._closed)return Promise.reject(new Error("database is closed"));if(this._destroyed)return Promise.reject(new Error("database is destroyed"));var self3=this;logApiCall(self3,name,args);return this.taskqueue.isReady?callback.apply(this,args):new Promise((function(fulfill,reject){self3.taskqueue.addTask((function(failed2){failed2?reject(failed2):fulfill(self3[name].apply(self3,args))}))}))}))}function pick(obj,arr){var i2,len,prop2,res2={};for(i2=0,len=arr.length;i2<len;i2++)(prop2=arr[i2])in obj&&(res2[prop2]=obj[prop2]);return res2}function identityFunction(x2){return x2}function formatResultForOpenRevsGet(result){return[{ok:result}]}function bulkGet(db,opts,callback){function collapseResultsAndFinish(){var results=[];perDocResults.forEach((function(res2){res2.docs.forEach((function(info3){results.push({id:res2.id,docs:[info3]})}))}));callback(null,{results})}function checkDone(){++numDone===numDocs&&collapseResultsAndFinish()}function gotResult(docIndex,id,docs){perDocResults[docIndex]={id,docs};checkDone()}function nextBatch(){var upTo,batch;if(!(i2>=allRequests.length)){upTo=Math.min(i2+MAX_NUM_CONCURRENT_REQUESTS,allRequests.length);processBatch(batch=allRequests.slice(i2,upTo),i2);i2+=batch.length}}function processBatch(batch,offset){batch.forEach((function(docId,j2){var formatResult,docIdx=offset+j2,docRequests=requestsById.get(docId),docOpts=pick(docRequests[0],["atts_since","attachments"]);docOpts.open_revs=docRequests.map((function(request2){return request2.rev}));docOpts.open_revs=docOpts.open_revs.filter(identityFunction);formatResult=identityFunction;if(0===docOpts.open_revs.length){delete docOpts.open_revs;formatResult=formatResultForOpenRevsGet}["revs","attachments","binary","ajax","latest"].forEach((function(param){param in opts&&(docOpts[param]=opts[param])}));db.get(docId,docOpts,(function(err3,res2){var result;result=err3?[{error:err3}]:formatResult(res2);gotResult(docIdx,docId,result);nextBatch()}))}))}var numDocs,numDone,perDocResults,allRequests,i2,requests=opts.docs,requestsById=new Map;requests.forEach((function(request2){requestsById.has(request2.id)?requestsById.get(request2.id).push(request2):requestsById.set(request2.id,[request2])}));numDocs=requestsById.size;numDone=0;perDocResults=new Array(numDocs);allRequests=[];requestsById.forEach((function(value,key3){allRequests.push(key3)}));i2=0;nextBatch()}function hasLocalStorage(){return hasLocal}function guardedConsole(method){if("undefined"!=typeof console&&"function"==typeof console[method]){var args=Array.prototype.slice.call(arguments,1);console[method].apply(console,args)}}function randomNumber(min,max3){min=parseInt(min,10)||0;(max3=parseInt(max3,10))!=max3||max3<=min?max3=(min||1)<<1:max3+=1;if(max3>6e5){min=3e5;max3=6e5}return~~((max3-min)*Math.random()+min)}function defaultBackOff(min){var max3=0;min||(max3=2e3);return randomNumber(min,max3)}function explainError(status,str){guardedConsole("info","The above "+status+" is totally normal. "+str)}function tryFilter(filter4,doc,req){try{return!filter4(doc,req)}catch(err3){var msg="Filter function threw: "+err3.toString();return createError(BAD_REQUEST,msg)}}function filterChange(opts){var req={},hasFilter=opts.filter&&"function"==typeof opts.filter;req.query=opts.query_params;return function filter4(change){var filterReturn,att;change.doc||(change.doc={});if("object"==typeof(filterReturn=hasFilter&&tryFilter(opts.filter,change.doc,req)))return filterReturn;if(filterReturn)return!1;if(opts.include_docs){if(!opts.attachments)for(att in change.doc._attachments)Object.prototype.hasOwnProperty.call(change.doc._attachments,att)&&(change.doc._attachments[att].stub=!0)}else delete change.doc;return!0}}function invalidIdError(id){var err3;id?"string"!=typeof id?err3=createError(INVALID_ID):/^_/.test(id)&&!/^_(design|local)/.test(id)&&(err3=createError(RESERVED_ID)):err3=createError(MISSING_ID);if(err3)throw err3}function isRemote(db){if("boolean"==typeof db._remote)return db._remote;if("function"==typeof db.type){guardedConsole("warn","db.type() is deprecated and will be removed in a future version of PouchDB");return"http"===db.type()}return!1}function listenerCount(ee,type){return"listenerCount"in ee?ee.listenerCount(type):import_events15.default.listenerCount(ee,type)}function parseDesignDocFunctionName(s2){if(!s2)return null;var parts=s2.split("/");return 2===parts.length?parts:1===parts.length?[s2,s2]:null}function normalizeDesignDocFunctionName(s2){var normalized=parseDesignDocFunctionName(s2);return normalized?normalized.join("/"):null}function parseUri(str){for(var key3,value,encoded,m3=parser.exec(str),uri={},i2=14;i2--;){key3=keys2[i2];value=m3[i2]||"";encoded=-1!==["user","password"].indexOf(key3);uri[key3]=encoded?decodeURIComponent(value):value}uri[qName]={};uri[keys2[12]].replace(qParser,(function($0,$1,$2){$1&&(uri[qName][$1]=$2)}));return uri}function scopeEval(source2,scope){var key3,keys3=[],values=[];for(key3 in scope)if(Object.prototype.hasOwnProperty.call(scope,key3)){keys3.push(key3);values.push(scope[key3])}keys3.push(source2);return Function.apply(null,keys3).apply(null,values)}function upsert2(db,docId,diffFun){return db.get(docId).catch((function(err3){if(404!==err3.status)throw err3;return{}})).then((function(doc){var docRev=doc._rev,newDoc=diffFun(doc);if(!newDoc)return{updated:!1,rev:docRev};newDoc._id=docId;newDoc._rev=docRev;return tryAndPut(db,newDoc,diffFun)}))}function tryAndPut(db,doc,diffFun){return db.put(doc).then((function(res2){return{updated:!0,rev:res2.rev}}),(function(err3){if(409!==err3.status)throw err3;return upsert2(db,doc._id,diffFun)}))}function rev2(doc,deterministic_revs){if(!deterministic_revs)return v4_default2().replace(/-/g,"").toLowerCase();var mutateableDoc=Object.assign({},doc);delete mutateableDoc._rev_tree;return stringMd5(JSON.stringify(mutateableDoc))}function winningRev(metadata){for(var winningId,winningPos,winningDeleted,node,tree,branches,pos,i2,len,deleted,id,toVisit=metadata.rev_tree.slice();node=toVisit.pop();){branches=(tree=node.ids)[2];pos=node.pos;if(branches.length)for(i2=0,len=branches.length;i2<len;i2++)toVisit.push({pos:pos+1,ids:branches[i2]});else{deleted=!!tree[1].deleted;id=tree[0];if(!winningId||(winningDeleted!==deleted?winningDeleted:winningPos!==pos?winningPos<pos:winningId<id)){winningId=id;winningPos=pos;winningDeleted=deleted}}}return winningPos+"-"+winningId}function traverseRevTree(revs,callback){for(var node,pos,tree,branches,newCtx,i2,len,toVisit=revs.slice();node=toVisit.pop();){pos=node.pos;newCtx=callback(0===(branches=(tree=node.ids)[2]).length,pos,tree[0],node.ctx,tree[1]);for(i2=0,len=branches.length;i2<len;i2++)toVisit.push({pos:pos+1,ids:branches[i2],ctx:newCtx})}}function sortByPos(a2,b3){return a2.pos-b3.pos}function collectLeaves(revs){var i2,len,leaves=[];traverseRevTree(revs,(function(isLeaf,pos,id,acc,opts){isLeaf&&leaves.push({rev:pos+"-"+id,pos,opts})}));leaves.sort(sortByPos).reverse();for(i2=0,len=leaves.length;i2<len;i2++)delete leaves[i2].pos;return leaves}function collectConflicts(metadata){var i2,len,leaf,win=winningRev(metadata),leaves=collectLeaves(metadata.rev_tree),conflicts=[];for(i2=0,len=leaves.length;i2<len;i2++)(leaf=leaves[i2]).rev===win||leaf.opts.deleted||conflicts.push(leaf.rev);return conflicts}function compactTree(metadata){var revs=[];traverseRevTree(metadata.rev_tree,(function(isLeaf,pos,revHash,ctx,opts){if("available"===opts.status&&!isLeaf){revs.push(pos+"-"+revHash);opts.status="missing"}}));return revs}function findPathToLeaf(revs,targetRev){let path2=[];const toVisit=revs.slice();let node;for(;node=toVisit.pop();){const{pos,ids:tree}=node,rev3=`${pos}-${tree[0]}`,branches=tree[2];path2.push(rev3);if(rev3===targetRev){if(0!==branches.length)throw new Error("The requested revision is not a leaf");return path2.reverse()}(0===branches.length||branches.length>1)&&(path2=[]);for(let i2=0,len=branches.length;i2<len;i2++)toVisit.push({pos:pos+1,ids:branches[i2]})}if(0===path2.length)throw new Error("The requested revision does not exist");return path2.reverse()}function rootToLeaf(revs){for(var node,pos,tree,id,opts,branches,isLeaf,history,i2,len,paths=[],toVisit=revs.slice();node=toVisit.pop();){pos=node.pos;id=(tree=node.ids)[0];opts=tree[1];isLeaf=0===(branches=tree[2]).length;(history=node.history?node.history.slice():[]).push({id,opts});isLeaf&&paths.push({pos:pos+1-history.length,ids:history});for(i2=0,len=branches.length;i2<len;i2++)toVisit.push({pos:pos+1,ids:branches[i2],history})}return paths.reverse()}function sortByPos$1(a2,b3){return a2.pos-b3.pos}function binarySearch(arr,item,comparator){for(var mid,low=0,high=arr.length;low<high;)comparator(arr[mid=low+high>>>1],item)<0?low=mid+1:high=mid;return low}function insertSorted(arr,item,comparator){var idx2=binarySearch(arr,item,comparator);arr.splice(idx2,0,item)}function pathToTree(path2,numStemmed){var root40,leaf,i2,len,node,currentLeaf;for(i2=numStemmed,len=path2.length;i2<len;i2++){currentLeaf=[(node=path2[i2]).id,node.opts,[]];if(leaf){leaf[2].push(currentLeaf);leaf=currentLeaf}else root40=leaf=currentLeaf}return root40}function compareTree(a2,b3){return a2[0]<b3[0]?-1:1}function mergeTree(in_tree1,in_tree2){for(var item,tree1,tree2,i2,merged,j2,queue2=[{tree1:in_tree1,tree2:in_tree2}],conflicts=!1;queue2.length>0;){tree1=(item=queue2.pop()).tree1;tree2=item.tree2;(tree1[1].status||tree2[1].status)&&(tree1[1].status="available"===tree1[1].status||"available"===tree2[1].status?"available":"missing");for(i2=0;i2<tree2[2].length;i2++)if(tree1[2][0]){merged=!1;for(j2=0;j2<tree1[2].length;j2++)if(tree1[2][j2][0]===tree2[2][i2][0]){queue2.push({tree1:tree1[2][j2],tree2:tree2[2][i2]});merged=!0}if(!merged){conflicts="new_branch";insertSorted(tree1[2],tree2[2][i2],compareTree)}}else{conflicts="new_leaf";tree1[2][0]=tree2[2][i2]}}return{conflicts,tree:in_tree1}}function doMerge(tree,path2,dontExpand){var res2,i2,len,branch2,t1,t22,diff,candidateParents,trees,item,elements,j2,elementsLen,el,restree=[],conflicts=!1,merged=!1;if(!tree.length)return{tree:[path2],conflicts:"new_leaf"};for(i2=0,len=tree.length;i2<len;i2++)if((branch2=tree[i2]).pos===path2.pos&&branch2.ids[0]===path2.ids[0]){res2=mergeTree(branch2.ids,path2.ids);restree.push({pos:branch2.pos,ids:res2.tree});conflicts=conflicts||res2.conflicts;merged=!0}else if(!0!==dontExpand){t1=branch2.pos<path2.pos?branch2:path2;diff=(t22=branch2.pos<path2.pos?path2:branch2).pos-t1.pos;candidateParents=[];(trees=[]).push({ids:t1.ids,diff,parent:null,parentIdx:null});for(;trees.length>0;)if(0!==(item=trees.pop()).diff)for(j2=0,elementsLen=(elements=item.ids[2]).length;j2<elementsLen;j2++)trees.push({ids:elements[j2],diff:item.diff-1,parent:item.ids,parentIdx:j2});else item.ids[0]===t22.ids[0]&&candidateParents.push(item);if(el=candidateParents[0]){res2=mergeTree(el.ids,t22.ids);el.parent[2][el.parentIdx]=res2.tree;restree.push({pos:t1.pos,ids:t1.ids});conflicts=conflicts||res2.conflicts;merged=!0}else restree.push(branch2)}else restree.push(branch2);merged||restree.push(path2);restree.sort(sortByPos$1);return{tree:restree,conflicts:conflicts||"internal_node"}}function stem(tree,depth){var stemmedRevs,result,i2,len,path2,stemmed,node,numStemmed,s2,rev3,paths=rootToLeaf(tree);for(i2=0,len=paths.length;i2<len;i2++){if((stemmed=(path2=paths[i2]).ids).length>depth){stemmedRevs||(stemmedRevs={});numStemmed=stemmed.length-depth;node={pos:path2.pos+numStemmed,ids:pathToTree(stemmed,numStemmed)};for(s2=0;s2<numStemmed;s2++){rev3=path2.pos+s2+"-"+stemmed[s2].id;stemmedRevs[rev3]=!0}}else node={pos:path2.pos,ids:pathToTree(stemmed,0)};result=result?doMerge(result,node,!0).tree:[node]}stemmedRevs&&traverseRevTree(result,(function(isLeaf,pos,revHash){delete stemmedRevs[pos+"-"+revHash]}));return{tree:result,revs:stemmedRevs?Object.keys(stemmedRevs):[]}}function merge2(tree,path2,depth){var newTree=doMerge(tree,path2),stemmed=stem(newTree.tree,depth);return{tree:stemmed.tree,stemmedRevs:stemmed.revs,conflicts:newTree.conflicts}}function removeLeafFromRevTree(tree,leafRev){return tree.flatMap((path2=>(path2=removeLeafFromPath(path2,leafRev))?[path2]:[]))}function removeLeafFromPath(path2,leafRev){const tree=clone2(path2),toVisit=[tree];let node;for(;node=toVisit.pop();){const{pos,ids:[id,,branches],parent}=node;if(0===branches.length&&`${pos}-${id}`===leafRev){if(!parent)return null;parent.ids[2]=parent.ids[2].filter((function(branchNode){return branchNode[0]!==id}));return tree}for(let i2=0,len=branches.length;i2<len;i2++)toVisit.push({pos:pos+1,ids:branches[i2],parent:node})}return tree}function revExists(revs,rev3){for(var node,branches,i2,len,toVisit=revs.slice(),splitRev=rev3.split("-"),targetPos=parseInt(splitRev[0],10),targetId=splitRev[1];node=toVisit.pop();){if(node.pos===targetPos&&node.ids[0]===targetId)return!0;for(i2=0,len=(branches=node.ids[2]).length;i2<len;i2++)toVisit.push({pos:node.pos+1,ids:branches[i2]})}return!1}function getTrees(node){return node.ids}function isDeleted(metadata,rev3){var id,toVisit,tree;rev3||(rev3=winningRev(metadata));id=rev3.substring(rev3.indexOf("-")+1);toVisit=metadata.rev_tree.map(getTrees);for(;tree=toVisit.pop();){if(tree[0]===id)return!!tree[1].deleted;toVisit=toVisit.concat(tree[2])}}function isLocalId(id){return"string"==typeof id&&id.startsWith("_local/")}function latest(rev3,metadata){for(var node,pos,tree,id,opts,branches,isLeaf,history,i2,len,historyNode,j2,l2,toVisit=metadata.rev_tree.slice();node=toVisit.pop();){pos=node.pos;id=(tree=node.ids)[0];opts=tree[1];isLeaf=0===(branches=tree[2]).length;(history=node.history?node.history.slice():[]).push({id,pos,opts});if(isLeaf)for(i2=0,len=history.length;i2<len;i2++)if((historyNode=history[i2]).pos+"-"+historyNode.id===rev3)return pos+"-"+id;for(j2=0,l2=branches.length;j2<l2;j2++)toVisit.push({pos:pos+1,ids:branches[j2],history})}throw new Error("Unable to resolve latest revision for id "+metadata.id+", rev "+rev3)}function pad(str,padWith,upToLength){for(var padding="",targetLength=upToLength-str.length;padding.length<targetLength;)padding+=padWith;return padding}function padLeft(str,padWith,upToLength){return pad(str,padWith,upToLength)+str}function collate(a2,b3){var ai2,bi2;if(a2===b3)return 0;a2=normalizeKey(a2);b3=normalizeKey(b3);if((ai2=collationIndex(a2))-(bi2=collationIndex(b3))!=0)return ai2-bi2;switch(typeof a2){case"number":return a2-b3;case"boolean":return a2<b3?-1:1;case"string":return stringCollate(a2,b3)}return Array.isArray(a2)?arrayCollate(a2,b3):objectCollate(a2,b3)}function normalizeKey(key3){var origKey,len,i2,k2,val2;switch(typeof key3){case"undefined":return null;case"number":return key3===1/0||key3===-1/0||isNaN(key3)?null:key3;case"object":origKey=key3;if(Array.isArray(key3)){len=key3.length;key3=new Array(len);for(i2=0;i2<len;i2++)key3[i2]=normalizeKey(origKey[i2])}else{if(key3 instanceof Date)return key3.toJSON();if(null!==key3){key3={};for(k2 in origKey)Object.prototype.hasOwnProperty.call(origKey,k2)&&void 0!==(val2=origKey[k2])&&(key3[k2]=normalizeKey(val2))}}}return key3}function indexify(key3){var isArray2,arr,i2,len,result,objKey;if(null!==key3)switch(typeof key3){case"boolean":return key3?1:0;case"number":return numToIndexableString(key3);case"string":return key3.replace(/\u0002/g,"").replace(/\u0001/g,"").replace(/\u0000/g,"");case"object":i2=-1;len=(arr=(isArray2=Array.isArray(key3))?key3:Object.keys(key3)).length;result="";if(isArray2)for(;++i2<len;)result+=toIndexableString(arr[i2]);else for(;++i2<len;)result+=toIndexableString(objKey=arr[i2])+toIndexableString(key3[objKey]);return result}return""}function toIndexableString(key3){return collationIndex(key3=normalizeKey(key3))+SEP+indexify(key3)+"\0"}function parseNumber2(str,i2){var num,neg,numAsString,magAsString,magnitude,ch4,originalIdx=i2;if("1"===str[i2]){num=0;i2++}else{neg="0"===str[i2];i2++;numAsString="";magAsString=str.substring(i2,i2+MAGNITUDE_DIGITS);magnitude=parseInt(magAsString,10)+MIN_MAGNITUDE;neg&&(magnitude=-magnitude);i2+=MAGNITUDE_DIGITS;for(;"\0"!==(ch4=str[i2]);){numAsString+=ch4;i2++}num=1===(numAsString=numAsString.split(".")).length?parseInt(numAsString,10):parseFloat(numAsString[0]+"."+numAsString[1]);neg&&(num-=10);0!==magnitude&&(num=parseFloat(num+"e"+magnitude))}return{num,length:i2-originalIdx}}function pop2(stack2,metaStack){var lastMetaElement,element2,lastElementIndex,obj=stack2.pop();if(metaStack.length){if(obj===(lastMetaElement=metaStack[metaStack.length-1]).element){metaStack.pop();lastMetaElement=metaStack[metaStack.length-1]}element2=lastMetaElement.element;lastElementIndex=lastMetaElement.index;Array.isArray(element2)?element2.push(obj):lastElementIndex===stack2.length-2?element2[stack2.pop()]=obj:stack2.push(obj)}}function parseIndexableString(str){for(var collationIndex2,parsedNum,parsedStr,ch4,arrayElement,objElement,stack2=[],metaStack=[],i2=0;;)if("\0"!==(collationIndex2=str[i2++]))switch(collationIndex2){case"1":stack2.push(null);break;case"2":stack2.push("1"===str[i2]);i2++;break;case"3":parsedNum=parseNumber2(str,i2);stack2.push(parsedNum.num);i2+=parsedNum.length;break;case"4":parsedStr="";for(;"\0"!==(ch4=str[i2]);){parsedStr+=ch4;i2++}parsedStr=parsedStr.replace(/\u0001\u0001/g,"\0").replace(/\u0001\u0002/g,"").replace(/\u0002\u0002/g,"");stack2.push(parsedStr);break;case"5":arrayElement={element:[],index:stack2.length};stack2.push(arrayElement.element);metaStack.push(arrayElement);break;case"6":objElement={element:{},index:stack2.length};stack2.push(objElement.element);metaStack.push(objElement);break;default:throw new Error("bad collationIndex or unexpectedly reached end of input: "+collationIndex2)}else{if(1===stack2.length)return stack2.pop();pop2(stack2,metaStack)}}function arrayCollate(a2,b3){var i2,sort,len=Math.min(a2.length,b3.length);for(i2=0;i2<len;i2++)if(0!==(sort=collate(a2[i2],b3[i2])))return sort;return a2.length===b3.length?0:a2.length>b3.length?1:-1}function stringCollate(a2,b3){return a2===b3?0:a2>b3?1:-1}function objectCollate(a2,b3){var i2,sort,ak2=Object.keys(a2),bk2=Object.keys(b3),len=Math.min(ak2.length,bk2.length);for(i2=0;i2<len;i2++){if(0!==(sort=collate(ak2[i2],bk2[i2])))return sort;if(0!==(sort=collate(a2[ak2[i2]],b3[bk2[i2]])))return sort}return ak2.length===bk2.length?0:ak2.length>bk2.length?1:-1}function collationIndex(x2){var idx2=["boolean","number","string","object"].indexOf(typeof x2);return~idx2?null===x2?1:Array.isArray(x2)?5:idx2<3?idx2+2:idx2+3:Array.isArray(x2)?5:void 0}function numToIndexableString(num){var expFormat,magnitude,neg,result,magString,factor,factorStr;if(0===num)return"1";expFormat=num.toExponential().split(/e\+?/);magnitude=parseInt(expFormat[1],10);result=(neg=num<0)?"0":"2";magString=padLeft(((neg?-magnitude:magnitude)-MIN_MAGNITUDE).toString(),"0",MAGNITUDE_DIGITS);result+=SEP+magString;factor=Math.abs(parseFloat(expFormat[0]));neg&&(factor=10-factor);factorStr=(factorStr=factor.toFixed(20)).replace(/\.?0+$/,"");return result+(SEP+factorStr)}function getFieldFromDoc(doc,parsedField){var i2,len,value=doc;for(i2=0,len=parsedField.length;i2<len&&(value=value[parsedField[i2]]);i2++);return value}function setFieldInDoc(doc,parsedField,value){var i2,len,elem;for(i2=0,len=parsedField.length;i2<len-1;i2++)doc=doc[elem=parsedField[i2]]=doc[elem]||{};doc[parsedField[len-1]]=value}function compare2(left,right){return left<right?-1:left>right?1:0}function parseField(fieldName){var i2,len,ch4,fields=[],current="";for(i2=0,len=fieldName.length;i2<len;i2++){ch4=fieldName[i2];if(i2>0&&"\\"===fieldName[i2-1]&&("$"===ch4||"."===ch4))current=current.substring(0,current.length-1)+ch4;else if("."===ch4){fields.push(current);current=""}else current+=ch4}fields.push(current);return fields}function isCombinationalField(field){return combinationFields.indexOf(field)>-1}function getKey2(obj){return Object.keys(obj)[0]}function getValue(obj){return obj[getKey2(obj)]}function mergeAndedSelectors(selectors){var res2={},first={$or:!0,$nor:!0};selectors.forEach((function(selector){Object.keys(selector).forEach((function(field){var entries2,fieldMatchers,matcher=selector[field];"object"!=typeof matcher&&(matcher={$eq:matcher});if(isCombinationalField(field))if(matcher instanceof Array){if(first[field]){first[field]=!1;res2[field]=matcher;return}entries2=[];res2[field].forEach((function(existing){Object.keys(matcher).forEach((function(key3){var m3=matcher[key3],longest=Math.max(Object.keys(existing).length,Object.keys(m3).length),merged=mergeAndedSelectors([existing,m3]);Object.keys(merged).length<=longest||entries2.push(merged)}))}));res2[field]=entries2}else res2[field]=mergeAndedSelectors([matcher]);else{fieldMatchers=res2[field]=res2[field]||{};Object.keys(matcher).forEach((function(operator){var value=matcher[operator];if("$gt"===operator||"$gte"===operator)return mergeGtGte(operator,value,fieldMatchers);if("$lt"===operator||"$lte"===operator)return mergeLtLte(operator,value,fieldMatchers);if("$ne"===operator)return mergeNe(value,fieldMatchers);if("$eq"===operator)return mergeEq(value,fieldMatchers);if("$regex"===operator)return mergeRegex(value,fieldMatchers);fieldMatchers[operator]=value}))}}))}));return res2}function mergeGtGte(operator,value,fieldMatchers){if(void 0===fieldMatchers.$eq)if(void 0!==fieldMatchers.$gte){if("$gte"===operator)value>fieldMatchers.$gte&&(fieldMatchers.$gte=value);else if(value>=fieldMatchers.$gte){delete fieldMatchers.$gte;fieldMatchers.$gt=value}}else if(void 0!==fieldMatchers.$gt)if("$gte"===operator){if(value>fieldMatchers.$gt){delete fieldMatchers.$gt;fieldMatchers.$gte=value}}else value>fieldMatchers.$gt&&(fieldMatchers.$gt=value);else fieldMatchers[operator]=value}function mergeLtLte(operator,value,fieldMatchers){if(void 0===fieldMatchers.$eq)if(void 0!==fieldMatchers.$lte){if("$lte"===operator)value<fieldMatchers.$lte&&(fieldMatchers.$lte=value);else if(value<=fieldMatchers.$lte){delete fieldMatchers.$lte;fieldMatchers.$lt=value}}else if(void 0!==fieldMatchers.$lt)if("$lte"===operator){if(value<fieldMatchers.$lt){delete fieldMatchers.$lt;fieldMatchers.$lte=value}}else value<fieldMatchers.$lt&&(fieldMatchers.$lt=value);else fieldMatchers[operator]=value}function mergeNe(value,fieldMatchers){"$ne"in fieldMatchers?fieldMatchers.$ne.push(value):fieldMatchers.$ne=[value]}function mergeEq(value,fieldMatchers){delete fieldMatchers.$gt;delete fieldMatchers.$gte;delete fieldMatchers.$lt;delete fieldMatchers.$lte;delete fieldMatchers.$ne;fieldMatchers.$eq=value}function mergeRegex(value,fieldMatchers){"$regex"in fieldMatchers?fieldMatchers.$regex.push(value):fieldMatchers.$regex=[value]}function mergeAndedSelectorsNested(obj){var prop2,i2,value;for(prop2 in obj){if(Array.isArray(obj))for(i2 in obj)obj[i2].$and&&(obj[i2]=mergeAndedSelectors(obj[i2].$and));"object"==typeof(value=obj[prop2])&&mergeAndedSelectorsNested(value)}return obj}function isAndInSelector(obj,isAnd){var prop2,value;for(prop2 in obj){"$and"===prop2&&(isAnd=!0);"object"==typeof(value=obj[prop2])&&(isAnd=isAndInSelector(value,isAnd))}return isAnd}function massageSelector(input){var fields,i2,field,matcher,result=clone2(input);isAndInSelector(result,!1)&&"$and"in(result=mergeAndedSelectorsNested(result))&&(result=mergeAndedSelectors(result.$and));["$or","$nor"].forEach((function(orOrNor){orOrNor in result&&result[orOrNor].forEach((function(subSelector){var i3,field2,matcher2,fields2=Object.keys(subSelector);for(i3=0;i3<fields2.length;i3++)"object"==typeof(matcher2=subSelector[field2=fields2[i3]])&&null!==matcher2||(subSelector[field2]={$eq:matcher2})}))}));"$not"in result&&(result.$not=mergeAndedSelectors([result.$not]));fields=Object.keys(result);for(i2=0;i2<fields.length;i2++){field=fields[i2];"object"==typeof(matcher=result[field])&&null!==matcher||(matcher={$eq:matcher});result[field]=matcher}normalizeArrayOperators(result);return result}function normalizeArrayOperators(selector){Object.keys(selector).forEach((function(field){var matcher=selector[field];Array.isArray(matcher)?matcher.forEach((function(matcherItem){matcherItem&&"object"==typeof matcherItem&&normalizeArrayOperators(matcherItem)})):"$ne"===field?selector.$ne=[matcher]:"$regex"===field?selector.$regex=[matcher]:matcher&&"object"==typeof matcher&&normalizeArrayOperators(matcher)}))}function createFieldSorter(sort){function getFieldValuesAsArray(doc){return sort.map((function(sorting){var parsedField=parseField(getKey2(sorting));return getFieldFromDoc(doc,parsedField)}))}return function(aRow,bRow){var collation=collate(getFieldValuesAsArray(aRow.doc),getFieldValuesAsArray(bRow.doc));return 0!==collation?collation:compare2(aRow.doc._id,bRow.doc._id)}}function filterInMemoryFields(rows,requestDef,inMemoryFields){var fieldSorter,skip,limit;rows=rows.filter((function(row){return rowFilter(row.doc,requestDef.selector,inMemoryFields)}));if(requestDef.sort){fieldSorter=createFieldSorter(requestDef.sort);rows=rows.sort(fieldSorter);"string"!=typeof requestDef.sort[0]&&"desc"===getValue(requestDef.sort[0])&&(rows=rows.reverse())}if("limit"in requestDef||"skip"in requestDef){skip=requestDef.skip||0;limit=("limit"in requestDef?requestDef.limit:rows.length)+skip;rows=rows.slice(skip,limit)}return rows}function rowFilter(doc,selector,inMemoryFields){return inMemoryFields.every((function(field){var matcher=selector[field],parsedField=parseField(field),docFieldValue=getFieldFromDoc(doc,parsedField);return isCombinationalField(field)?matchCominationalSelector(field,matcher,doc):matchSelector(matcher,doc,parsedField,docFieldValue)}))}function matchSelector(matcher,doc,parsedField,docFieldValue){return!matcher||("object"==typeof matcher?Object.keys(matcher).every((function(maybeUserOperator){var subParsedField,subDocFieldValue,userValue=matcher[maybeUserOperator];if(0===maybeUserOperator.indexOf("$"))return match2(maybeUserOperator,doc,userValue,parsedField,docFieldValue);subParsedField=parseField(maybeUserOperator);if(void 0===docFieldValue&&"object"!=typeof userValue&&subParsedField.length>0)return!1;subDocFieldValue=getFieldFromDoc(docFieldValue,subParsedField);return"object"==typeof userValue?matchSelector(userValue,doc,parsedField,subDocFieldValue):match2("$eq",doc,userValue,subParsedField,subDocFieldValue)})):matcher===docFieldValue)}function matchCominationalSelector(field,matcher,doc){return"$or"===field?matcher.some((function(orMatchers){return rowFilter(doc,orMatchers,Object.keys(orMatchers))})):"$not"===field?!rowFilter(doc,matcher,Object.keys(matcher)):!matcher.find((function(orMatchers){return rowFilter(doc,orMatchers,Object.keys(orMatchers))}))}function match2(userOperator,doc,userValue,parsedField,docFieldValue){if(!matchers[userOperator])throw new Error('unknown operator "'+userOperator+'" - should be one of $eq, $lte, $lt, $gt, $gte, $exists, $ne, $in, $nin, $size, $mod, $regex, $elemMatch, $type, $allMatch or $all');return matchers[userOperator](doc,userValue,parsedField,docFieldValue)}function fieldExists(docFieldValue){return null!=docFieldValue}function fieldIsNotUndefined(docFieldValue){return void 0!==docFieldValue}function modField(docFieldValue,userValue){return"number"==typeof docFieldValue&&parseInt(docFieldValue,10)===docFieldValue&&docFieldValue%userValue[0]===userValue[1]}function arrayContainsValue(docFieldValue,userValue){return userValue.some((function(val2){return docFieldValue instanceof Array?docFieldValue.some((function(docFieldValueItem){return 0===collate(val2,docFieldValueItem)})):0===collate(val2,docFieldValue)}))}function arrayContainsAllValues(docFieldValue,userValue){return userValue.every((function(val2){return docFieldValue.some((function(docFieldValueItem){return 0===collate(val2,docFieldValueItem)}))}))}function arraySize(docFieldValue,userValue){return docFieldValue.length===userValue}function regexMatch(docFieldValue,userValue){return new RegExp(userValue).test(docFieldValue)}function typeMatch(docFieldValue,userValue){switch(userValue){case"null":return null===docFieldValue;case"boolean":return"boolean"==typeof docFieldValue;case"number":return"number"==typeof docFieldValue;case"string":return"string"==typeof docFieldValue;case"array":return docFieldValue instanceof Array;case"object":return"[object Object]"==={}.toString.call(docFieldValue)}}function matchesSelector(doc,selector){var rowsMatched;if("object"!=typeof selector)throw new Error("Selector error: expected a JSON object");return(rowsMatched=filterInMemoryFields([{doc}],{selector:selector=massageSelector(selector)},Object.keys(selector)))&&1===rowsMatched.length}function evalFilter(input){return scopeEval('"use strict";\nreturn '+input+";",{})}function evalView(input){return scopeEval(["return function(doc) {",' "use strict";'," var emitted = false;"," var emit = function (a, b) {"," emitted = true;"," };"," var view = "+input+";"," view(doc);"," if (emitted) {"," return true;"," }","};"].join("\n"),{})}function validate4(opts,callback){if(opts.selector&&opts.filter&&"_selector"!==opts.filter){var filterName="string"==typeof opts.filter?opts.filter:"function";return callback(new Error('selector invalid for filter "'+filterName+'"'))}callback()}function normalize(opts){opts.view&&!opts.filter&&(opts.filter="_view");opts.selector&&!opts.filter&&(opts.filter="_selector");opts.filter&&"string"==typeof opts.filter&&("_view"===opts.filter?opts.view=normalizeDesignDocFunctionName(opts.view):opts.filter=normalizeDesignDocFunctionName(opts.filter))}function shouldFilter(changesHandler,opts){return opts.filter&&"string"==typeof opts.filter&&!opts.doc_ids&&!isRemote(changesHandler.db)}function filter2(changesHandler,opts){var err3,viewName,filterName,callback=opts.complete;if("_view"===opts.filter){if(!opts.view||"string"!=typeof opts.view){err3=createError(BAD_REQUEST,"`view` filter parameter not found or invalid.");return callback(err3)}viewName=parseDesignDocFunctionName(opts.view);changesHandler.db.get("_design/"+viewName[0],(function(err4,ddoc){if(changesHandler.isCancelled)return callback(null,{status:"cancelled"});if(err4)return callback(generateErrorFromResponse(err4));var mapFun=ddoc&&ddoc.views&&ddoc.views[viewName[1]]&&ddoc.views[viewName[1]].map;if(!mapFun)return callback(createError(MISSING_DOC,ddoc.views?"missing json key: "+viewName[1]:"missing json key: views"));opts.filter=evalView(mapFun);changesHandler.doChanges(opts)}))}else if(opts.selector){opts.filter=function(doc){return matchesSelector(doc,opts.selector)};changesHandler.doChanges(opts)}else{filterName=parseDesignDocFunctionName(opts.filter);changesHandler.db.get("_design/"+filterName[0],(function(err4,ddoc){if(changesHandler.isCancelled)return callback(null,{status:"cancelled"});if(err4)return callback(generateErrorFromResponse(err4));var filterFun=ddoc&&ddoc.filters&&ddoc.filters[filterName[1]];if(!filterFun)return callback(createError(MISSING_DOC,ddoc&&ddoc.filters?"missing json key: "+filterName[1]:"missing json key: filters"));opts.filter=evalFilter(filterFun);changesHandler.doChanges(opts)}))}}function tryCatchInChangeListener(self3,change,pending3,lastSeq){try{self3.emit("change",change,pending3,lastSeq)}catch(e3){guardedConsole("error",'Error in .on("change", function):',e3)}}function processChange(doc,metadata,opts){var change,changeList=[{rev:doc._rev}];"all_docs"===opts.style&&(changeList=collectLeaves(metadata.rev_tree).map((function(x2){return{rev:x2.rev}})));change={id:metadata.id,changes:changeList,doc};isDeleted(metadata,doc._rev)&&(change.deleted=!0);if(opts.conflicts){change.doc._conflicts=collectConflicts(metadata);change.doc._conflicts.length||delete change.doc._conflicts}return change}function yankError(callback,docId){return function(err3,results){if(err3||results[0]&&results[0].error){(err3=err3||results[0]).docId=docId;callback(err3)}else callback(null,results.length?results[0]:results)}}function cleanDocs(docs){var i2,doc,atts,j2,att;for(i2=0;i2<docs.length;i2++)if((doc=docs[i2])._deleted)delete doc._attachments;else if(doc._attachments){atts=Object.keys(doc._attachments);for(j2=0;j2<atts.length;j2++){att=atts[j2];doc._attachments[att]=pick(doc._attachments[att],["data","digest","content_type","length","revpos","stub"])}}}function compareByIdThenRev(a2,b3){return a2._id===b3._id?(a2._revisions?a2._revisions.start:0)-(b3._revisions?b3._revisions.start:0):a2._id<b3._id?-1:1}function computeHeight(revs){var height={},edges=[];traverseRevTree(revs,(function(isLeaf,pos,id,prnt){var rev$$1=pos+"-"+id;isLeaf&&(height[rev$$1]=0);void 0!==prnt&&edges.push({from:prnt,to:rev$$1});return rev$$1}));edges.reverse();edges.forEach((function(edge){void 0===height[edge.from]?height[edge.from]=1+height[edge.to]:height[edge.from]=Math.min(height[edge.from],1+height[edge.to])}));return height}function allDocsKeysParse(opts){var keys3="limit"in opts?opts.keys.slice(opts.skip,opts.limit+opts.skip):opts.skip>0?opts.keys.slice(opts.skip):opts.keys;opts.keys=keys3;opts.skip=0;delete opts.limit;if(opts.descending){keys3.reverse();opts.descending=!1}}function doNextCompaction(self3){var task=self3._compactionQueue[0],opts=task.opts,callback=task.callback;self3.get("_local/compaction").catch((function(){return!1})).then((function(doc){doc&&doc.last_seq&&(opts.last_seq=doc.last_seq);self3._compact(opts,(function(err3,res2){err3?callback(err3):callback(null,res2);nextTick((function(){self3._compactionQueue.shift();self3._compactionQueue.length&&doNextCompaction(self3)}))}))}))}function appendPurgeSeq(db,docId,rev$$1){return db.get("_local/purges").then((function(doc){const purgeSeq=doc.purgeSeq+1;doc.purges.push({docId,rev:rev$$1,purgeSeq});doc.purges.length>self.purged_infos_limit&&doc.purges.splice(0,doc.purges.length-self.purged_infos_limit);doc.purgeSeq=purgeSeq;return doc})).catch((function(err3){if(404!==err3.status)throw err3;return{_id:"_local/purges",purges:[{docId,rev:rev$$1,purgeSeq:0}],purgeSeq:0}})).then((function(doc){return db.put(doc)}))}function attachmentNameError(name){return"_"===name.charAt(0)&&name+" is not a valid attachment name, attachment names cannot start with '_'"}function isNotSingleDoc(doc){return null===doc||"object"!=typeof doc||Array.isArray(doc)}function isValidRev(rev$$1){return"string"==typeof rev$$1&&validRevRegex.test(rev$$1)}function parseAdapter(name,opts){var adapters,preferredAdapters,prefix,adapterName,i2,adapter,match3=name.match(/([a-z-]*):\/\/(.*)/);if(match3)return{name:/https?/.test(match3[1])?match3[1]+"://"+match3[2]:match3[2],adapter:match3[1]};adapters=PouchDB.adapters;preferredAdapters=PouchDB.preferredAdapters;prefix=PouchDB.prefix;if(!(adapterName=opts.adapter))for(i2=0;i2<preferredAdapters.length&&"idb"===(adapterName=preferredAdapters[i2])&&"websql"in adapters&&hasLocalStorage()&&localStorage["_pouch__websqldb_"+prefix+name];++i2)guardedConsole("log",'PouchDB is downgrading "'+name+'" to WebSQL to avoid data loss, because it was already opened with WebSQL.');return{name:(adapter=adapters[adapterName])&&"use_prefix"in adapter&&!adapter.use_prefix?name:prefix+name,adapter:adapterName}}function inherits(A2,B2){A2.prototype=Object.create(B2.prototype,{constructor:{value:A2}})}function createClass(parent,init3){let klass=function(...args){if(!(this instanceof klass))return new klass(...args);init3.apply(this,args)};inherits(klass,parent);return klass}function prepareForDestruction(self3){function onDestroyed(from_constructor){self3.removeListener("closed",onClosed);from_constructor||self3.constructor.emit("destroyed",self3.name)}function onClosed(){self3.removeListener("destroyed",onDestroyed);self3.constructor.emit("unref",self3)}self3.once("destroyed",onDestroyed);self3.once("closed",onClosed);self3.constructor.emit("ref",self3)}function safeJsonParse(str){try{return JSON.parse(str)}catch(e3){return import_vuvuzela.default.parse(str)}}function safeJsonStringify(json){try{return JSON.stringify(json)}catch(e3){return import_vuvuzela.default.stringify(json)}}function checkBlobSupport(txn,store,docIdOrCreateDoc){return new Promise((function(resolve){var blob$$1=createBlob2([""]);let req;if("function"==typeof docIdOrCreateDoc){const doc=docIdOrCreateDoc(blob$$1);req=txn.objectStore(store).put(doc)}else{const docId=docIdOrCreateDoc;req=txn.objectStore(store).put(blob$$1,docId)}req.onsuccess=function(){var matchedChrome=navigator.userAgent.match(/Chrome\/(\d+)/),matchedEdge=navigator.userAgent.match(/Edge\//);resolve(matchedEdge||!matchedChrome||parseInt(matchedChrome[1],10)>=43)};req.onerror=txn.onabort=function(e3){e3.preventDefault();e3.stopPropagation();resolve(!1)}})).catch((function(){return!1}))}function toObject(array){return array.reduce((function(obj,item){obj[item]=!0;return obj}),{})}function parseRevisionInfo(rev$$1){var idx2,left,right;if(!/^\d+-/.test(rev$$1))return createError(INVALID_REV);idx2=rev$$1.indexOf("-");left=rev$$1.substring(0,idx2);right=rev$$1.substring(idx2+1);return{prefix:parseInt(left,10),id:right}}function makeRevTreeFromRevisions(revisions,opts){var i2,len,pos=revisions.start-revisions.ids.length+1,revisionIds=revisions.ids,ids=[revisionIds[0],opts,[]];for(i2=1,len=revisionIds.length;i2<len;i2++)ids=[revisionIds[i2],{status:"missing"},[ids]];return[{pos,ids}]}function parseDoc(doc,newEdits,dbOpts){var nRevNum,newRevId,revInfo,opts,result,key3,specialKey,error;dbOpts||(dbOpts={deterministic_revs:!0});opts={status:"available"};doc._deleted&&(opts.deleted=!0);if(newEdits){doc._id||(doc._id=uuid());newRevId=rev2(doc,dbOpts.deterministic_revs);if(doc._rev){if((revInfo=parseRevisionInfo(doc._rev)).error)return revInfo;doc._rev_tree=[{pos:revInfo.prefix,ids:[revInfo.id,{status:"missing"},[[newRevId,opts,[]]]]}];nRevNum=revInfo.prefix+1}else{doc._rev_tree=[{pos:1,ids:[newRevId,opts,[]]}];nRevNum=1}}else{if(doc._revisions){doc._rev_tree=makeRevTreeFromRevisions(doc._revisions,opts);nRevNum=doc._revisions.start;newRevId=doc._revisions.ids[0]}if(!doc._rev_tree){if((revInfo=parseRevisionInfo(doc._rev)).error)return revInfo;nRevNum=revInfo.prefix;newRevId=revInfo.id;doc._rev_tree=[{pos:nRevNum,ids:[newRevId,opts,[]]}]}}invalidIdError(doc._id);doc._rev=nRevNum+"-"+newRevId;result={metadata:{},data:{}};for(key3 in doc)if(Object.prototype.hasOwnProperty.call(doc,key3)){if((specialKey="_"===key3[0])&&!reservedWords[key3]){(error=createError(DOC_VALIDATION,key3)).message=DOC_VALIDATION.message+": "+key3;throw error}specialKey&&!dataWords[key3]?result.metadata[key3.slice(1)]=doc[key3]:result.data[key3]=doc[key3]}return result}function parseBase64(data){try{return thisAtob(data)}catch(e3){return{error:createError(BAD_ARG,"Attachment is not a valid base64 string")}}}function preprocessString(att,blobType,callback){var asBinary=parseBase64(att.data);if(asBinary.error)return callback(asBinary.error);att.length=asBinary.length;att.data="blob"===blobType?binStringToBluffer(asBinary,att.content_type):"base64"===blobType?thisBtoa(asBinary):asBinary;binaryMd5(asBinary,(function(result){att.digest="md5-"+result;callback()}))}function preprocessBlob(att,blobType,callback){binaryMd5(att.data,(function(md5){att.digest="md5-"+md5;att.length=att.data.size||att.data.length||0;"binary"===blobType?blobToBinaryString(att.data,(function(binString){att.data=binString;callback()})):"base64"===blobType?blobToBase64(att.data,(function(b64){att.data=b64;callback()})):callback()}))}function preprocessAttachment(att,blobType,callback){if(att.stub)return callback();"string"==typeof att.data?preprocessString(att,blobType,callback):preprocessBlob(att,blobType,callback)}function preprocessAttachments(docInfos,blobType,callback){function done(){docv++;docInfos.length===docv&&(overallErr?callback(overallErr):callback())}var docv,overallErr;if(!docInfos.length)return callback();docv=0;docInfos.forEach((function(docInfo){function processedAttachment(err3){overallErr=err3;++recv===attachments.length&&done()}var key3,attachments=docInfo.data&&docInfo.data._attachments?Object.keys(docInfo.data._attachments):[],recv=0;if(!attachments.length)return done();for(key3 in docInfo.data._attachments)Object.prototype.hasOwnProperty.call(docInfo.data._attachments,key3)&&preprocessAttachment(docInfo.data._attachments[key3],blobType,processedAttachment)}))}function updateDoc(revLimit,prev,docInfo,results,i2,cb2,writeDoc,newEdits){var previousWinningRev,previouslyDeleted,deleted,isRoot,newDoc,merged,err3,newRev,winningRev$$1,winningRevIsDeleted,delta;if(revExists(prev.rev_tree,docInfo.metadata.rev)&&!newEdits){results[i2]=docInfo;return cb2()}previousWinningRev=prev.winningRev||winningRev(prev);previouslyDeleted="deleted"in prev?prev.deleted:isDeleted(prev,previousWinningRev);deleted="deleted"in docInfo.metadata?docInfo.metadata.deleted:isDeleted(docInfo.metadata);isRoot=/^1-/.test(docInfo.metadata.rev);if(previouslyDeleted&&!deleted&&newEdits&&isRoot){(newDoc=docInfo.data)._rev=previousWinningRev;newDoc._id=docInfo.metadata.id;docInfo=parseDoc(newDoc,newEdits)}merged=merge2(prev.rev_tree,docInfo.metadata.rev_tree[0],revLimit);if(newEdits&&(previouslyDeleted&&deleted&&"new_leaf"!==merged.conflicts||!previouslyDeleted&&"new_leaf"!==merged.conflicts||previouslyDeleted&&!deleted&&"new_branch"===merged.conflicts)){err3=createError(REV_CONFLICT);results[i2]=err3;return cb2()}newRev=docInfo.metadata.rev;docInfo.metadata.rev_tree=merged.tree;docInfo.stemmedRevs=merged.stemmedRevs||[];prev.rev_map&&(docInfo.metadata.rev_map=prev.rev_map);winningRev$$1=winningRev(docInfo.metadata);delta=previouslyDeleted===(winningRevIsDeleted=isDeleted(docInfo.metadata,winningRev$$1))?0:previouslyDeleted<winningRevIsDeleted?-1:1;writeDoc(docInfo,winningRev$$1,winningRevIsDeleted,newRev===winningRev$$1?winningRevIsDeleted:isDeleted(docInfo.metadata,newRev),!0,delta,i2,cb2)}function rootIsMissing(docInfo){return"missing"===docInfo.metadata.rev_tree[0].ids[1].status}function processDocs(revLimit,docInfos,api,fetchedDocs,tx,results,writeDoc,opts,overallCallback){function insertDoc(docInfo,resultsIdx,callback){var err3,winningRev$$1=winningRev(docInfo.metadata),deleted=isDeleted(docInfo.metadata,winningRev$$1);if("was_delete"in opts&&deleted){results[resultsIdx]=createError(MISSING_DOC,"deleted");return callback()}if(newEdits&&rootIsMissing(docInfo)){err3=createError(REV_CONFLICT);results[resultsIdx]=err3;return callback()}writeDoc(docInfo,winningRev$$1,deleted,deleted,!1,deleted?0:1,resultsIdx,callback)}function checkAllDocsDone(){++docsDone===docsToDo&&overallCallback&&overallCallback()}var newEdits,idsToDocs,docsDone,docsToDo;revLimit=revLimit||1e3;newEdits=opts.new_edits;idsToDocs=new Map;docsDone=0;docsToDo=docInfos.length;docInfos.forEach((function(currentDoc,resultsIdx){var fun,id;if(currentDoc._id&&isLocalId(currentDoc._id)){fun=currentDoc._deleted?"_removeLocal":"_putLocal";api[fun](currentDoc,{ctx:tx},(function(err3,res2){results[resultsIdx]=err3||res2;checkAllDocsDone()}))}else{id=currentDoc.metadata.id;if(idsToDocs.has(id)){docsToDo--;idsToDocs.get(id).push([currentDoc,resultsIdx])}else idsToDocs.set(id,[[currentDoc,resultsIdx]])}}));idsToDocs.forEach((function(docs,id){function docWritten(){++numDone<docs.length?nextDoc():checkAllDocsDone()}function nextDoc(){var merged,value=docs[numDone],currentDoc=value[0],resultsIdx=value[1];if(fetchedDocs.has(id))updateDoc(revLimit,fetchedDocs.get(id),currentDoc,results,resultsIdx,docWritten,writeDoc,newEdits);else{merged=merge2([],currentDoc.metadata.rev_tree[0],revLimit);currentDoc.metadata.rev_tree=merged.tree;currentDoc.stemmedRevs=merged.stemmedRevs||[];insertDoc(currentDoc,resultsIdx,docWritten)}}var numDone=0;nextDoc()}))}function idbError(callback){return function(evt){var message="unknown_error";evt.target&&evt.target.error&&(message=evt.target.error.name||evt.target.error.message);callback(createError(IDB_ERROR,message,evt.type))}}function encodeMetadata(metadata,winningRev$$1,deleted){return{data:safeJsonStringify(metadata),winningRev:winningRev$$1,deletedOrLocal:deleted?"1":"0",seq:metadata.seq,id:metadata.id}}function decodeMetadata(storedObject){if(!storedObject)return null;var metadata=safeJsonParse(storedObject.data);metadata.winningRev=storedObject.winningRev;metadata.deleted="1"===storedObject.deletedOrLocal;metadata.seq=storedObject.seq;return metadata}function decodeDoc(doc){if(!doc)return doc;var idx2=doc._doc_id_rev.lastIndexOf(":");doc._id=doc._doc_id_rev.substring(0,idx2-1);doc._rev=doc._doc_id_rev.substring(idx2+1);delete doc._doc_id_rev;return doc}function readBlobData(body,type,asBlob,callback){asBlob?callback(body?"string"!=typeof body?body:b64ToBluffer(body,type):createBlob2([""],{type})):body?"string"!=typeof body?readAsBinaryString(body,(function(binary){callback(thisBtoa(binary))})):callback(body):callback("")}function fetchAttachmentsIfNecessary(doc,opts,txn,cb2){function checkDone(){++numDone===attachments.length&&cb2&&cb2()}function fetchAttachment(doc2,att){var attObj=doc2._attachments[att],digest=attObj.digest;txn.objectStore(ATTACH_STORE).get(digest).onsuccess=function(e3){attObj.body=e3.target.result.body;checkDone()}}var numDone,attachments=Object.keys(doc._attachments||{});if(!attachments.length)return cb2&&cb2();numDone=0;attachments.forEach((function(att){if(opts.attachments&&opts.include_docs)fetchAttachment(doc,att);else{doc._attachments[att].stub=!0;checkDone()}}))}function postProcessAttachments(results,asBlob){return Promise.all(results.map((function(row){if(row.doc&&row.doc._attachments){var attNames=Object.keys(row.doc._attachments);return Promise.all(attNames.map((function(att){var body,type,attObj=row.doc._attachments[att];if("body"in attObj){body=attObj.body;type=attObj.content_type;return new Promise((function(resolve){readBlobData(body,type,asBlob,(function(data){row.doc._attachments[att]=Object.assign(pick(attObj,["digest","content_type"]),{data});resolve()}))}))}})))}})))}function compactRevs(revs,docId,txn){function checkDone(){--count||deleteOrphanedAttachments()}function deleteOrphanedAttachments(){possiblyOrphanedDigests.length&&possiblyOrphanedDigests.forEach((function(digest){attAndSeqStore.index("digestSeq").count(IDBKeyRange.bound(digest+"::",digest+"::￿",!1,!1)).onsuccess=function(e3){e3.target.result||attStore.delete(digest)}}))}var possiblyOrphanedDigests=[],seqStore=txn.objectStore(BY_SEQ_STORE),attStore=txn.objectStore(ATTACH_STORE),attAndSeqStore=txn.objectStore(ATTACH_AND_SEQ_STORE),count=revs.length;revs.forEach((function(rev3){var index6=seqStore.index("_doc_id_rev"),key3=docId+"::"+rev3;index6.getKey(key3).onsuccess=function(e3){var seq=e3.target.result;if("number"!=typeof seq)return checkDone();seqStore.delete(seq);attAndSeqStore.index("seq").openCursor(IDBKeyRange.only(seq)).onsuccess=function(event2){var digest,cursor2=event2.target.result;if(cursor2){digest=cursor2.value.digestSeq.split("::")[0];possiblyOrphanedDigests.push(digest);attAndSeqStore.delete(cursor2.primaryKey);cursor2.continue()}else checkDone()}}}))}function openTransactionSafely(idb,stores,mode){try{return{txn:idb.transaction(stores,mode)}}catch(err3){return{error:err3}}}function idbBulkDocs(dbOpts,req,opts,api,idb,callback){function startTransaction(){var txnResult=openTransactionSafely(idb,[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE,LOCAL_STORE,ATTACH_AND_SEQ_STORE,META_STORE],"readwrite");if(txnResult.error)return callback(txnResult.error);(txn=txnResult.txn).onabort=idbError(callback);txn.ontimeout=idbError(callback);txn.oncomplete=complete;docStore=txn.objectStore(DOC_STORE);bySeqStore=txn.objectStore(BY_SEQ_STORE);attachStore=txn.objectStore(ATTACH_STORE);attachAndSeqStore=txn.objectStore(ATTACH_AND_SEQ_STORE);(metaStore=txn.objectStore(META_STORE)).get(META_STORE).onsuccess=function(e3){metaDoc=e3.target.result;updateDocCountIfReady()};verifyAttachments((function(err3){if(err3){preconditionErrored=!0;return callback(err3)}fetchExistingDocs()}))}function onAllDocsProcessed(){allDocsProcessed=!0;updateDocCountIfReady()}function idbProcessDocs(){processDocs(dbOpts.revs_limit,docInfos,api,fetchedDocs,txn,results,writeDoc,opts,onAllDocsProcessed)}function updateDocCountIfReady(){if(metaDoc&&allDocsProcessed){metaDoc.docCount+=docCountDelta;metaStore.put(metaDoc)}}function fetchExistingDocs(){function checkDone(){++numFetched===docInfos.length&&idbProcessDocs()}function readMetadata(event2){var metadata=decodeMetadata(event2.target.result);metadata&&fetchedDocs.set(metadata.id,metadata);checkDone()}var numFetched,i3,len2,docInfo;if(docInfos.length){numFetched=0;for(i3=0,len2=docInfos.length;i3<len2;i3++)(docInfo=docInfos[i3])._id&&isLocalId(docInfo._id)?checkDone():docStore.get(docInfo.metadata.id).onsuccess=readMetadata}}function complete(){if(!preconditionErrored){changesHandler$1.notify(api._meta.name);callback(null,results)}}function verifyAttachment(digest,callback2){attachStore.get(digest).onsuccess=function(e3){if(e3.target.result)callback2();else{var err3=createError(MISSING_STUB,"unknown stub attachment with digest "+digest);err3.status=412;callback2(err3)}}}function verifyAttachments(finish){function checkDone(){++numDone===digests.length&&finish(err3)}var numDone,err3,digests=[];docInfos.forEach((function(docInfo){docInfo.data&&docInfo.data._attachments&&Object.keys(docInfo.data._attachments).forEach((function(filename){var att=docInfo.data._attachments[filename];att.stub&&digests.push(att.digest)}))}));if(!digests.length)return finish();numDone=0;digests.forEach((function(digest){verifyAttachment(digest,(function(attErr){attErr&&!err3&&(err3=attErr);checkDone()}))}))}function writeDoc(docInfo,winningRev$$1,winningRevIsDeleted,newRevIsDeleted,isUpdate,delta,resultsIdx,callback2){var doc2;docInfo.metadata.winningRev=winningRev$$1;docInfo.metadata.deleted=winningRevIsDeleted;(doc2=docInfo.data)._id=docInfo.metadata.id;doc2._rev=docInfo.metadata.rev;newRevIsDeleted&&(doc2._deleted=!0);if(doc2._attachments&&Object.keys(doc2._attachments).length)return writeAttachments(docInfo,winningRev$$1,winningRevIsDeleted,isUpdate,resultsIdx,callback2);docCountDelta+=delta;updateDocCountIfReady();finishDoc(docInfo,winningRev$$1,winningRevIsDeleted,isUpdate,resultsIdx,callback2)}function finishDoc(docInfo,winningRev$$1,winningRevIsDeleted,isUpdate,resultsIdx,callback2){function afterPutDoc(e3){var metadataToStore,revsToDelete=docInfo.stemmedRevs||[];isUpdate&&api.auto_compaction&&(revsToDelete=revsToDelete.concat(compactTree(docInfo.metadata)));revsToDelete&&revsToDelete.length&&compactRevs(revsToDelete,docInfo.metadata.id,txn);metadata.seq=e3.target.result;metadataToStore=encodeMetadata(metadata,winningRev$$1,winningRevIsDeleted);docStore.put(metadataToStore).onsuccess=afterPutMetadata}function afterPutMetadata(){results[resultsIdx]={ok:!0,id:metadata.id,rev:metadata.rev};fetchedDocs.set(docInfo.metadata.id,docInfo.metadata);insertAttachmentMappings(docInfo,metadata.seq,callback2)}var putReq,doc2=docInfo.data,metadata=docInfo.metadata;doc2._doc_id_rev=metadata.id+"::"+metadata.rev;delete doc2._id;delete doc2._rev;(putReq=bySeqStore.put(doc2)).onsuccess=afterPutDoc;putReq.onerror=function afterPutDocError(e3){e3.preventDefault();e3.stopPropagation();bySeqStore.index("_doc_id_rev").getKey(doc2._doc_id_rev).onsuccess=function(e4){bySeqStore.put(doc2,e4.target.result).onsuccess=afterPutDoc}}}function writeAttachments(docInfo,winningRev$$1,winningRevIsDeleted,isUpdate,resultsIdx,callback2){function collectResults(){numDone===attachments.length&&finishDoc(docInfo,winningRev$$1,winningRevIsDeleted,isUpdate,resultsIdx,callback2)}function attachmentSaved(){numDone++;collectResults()}var doc2=docInfo.data,numDone=0,attachments=Object.keys(doc2._attachments);attachments.forEach((function(key3){var data,att=docInfo.data._attachments[key3];if(att.stub){numDone++;collectResults()}else{data=att.data;delete att.data;att.revpos=parseInt(winningRev$$1,10);saveAttachment(att.digest,data,attachmentSaved)}}))}function insertAttachmentMappings(docInfo,seq,callback2){function checkDone(){++attsAdded===attsToAdd.length&&callback2()}function add(att){var digest=docInfo.data._attachments[att].digest,req2=attachAndSeqStore.put({seq,digestSeq:digest+"::"+seq});req2.onsuccess=checkDone;req2.onerror=function(e3){e3.preventDefault();e3.stopPropagation();checkDone()}}var i3,attsAdded=0,attsToAdd=Object.keys(docInfo.data._attachments||{});if(!attsToAdd.length)return callback2();for(i3=0;i3<attsToAdd.length;i3++)add(attsToAdd[i3])}function saveAttachment(digest,data,callback2){attachStore.count(digest).onsuccess=function(e3){var newAtt;if(e3.target.result)return callback2();newAtt={digest,body:data};attachStore.put(newAtt).onsuccess=callback2}}var txn,docStore,bySeqStore,attachStore,attachAndSeqStore,metaStore,docInfoError,metaDoc,i2,len,doc,allDocsProcessed,docCountDelta,results,fetchedDocs,preconditionErrored,blobType,docInfos=req.docs;for(i2=0,len=docInfos.length;i2<len;i2++)(doc=docInfos[i2])._id&&isLocalId(doc._id)||(doc=docInfos[i2]=parseDoc(doc,opts.new_edits,dbOpts)).error&&!docInfoError&&(docInfoError=doc);if(docInfoError)return callback(docInfoError);allDocsProcessed=!1;docCountDelta=0;results=new Array(docInfos.length);fetchedDocs=new Map;preconditionErrored=!1;blobType=api._meta.blobSupport?"blob":"base64";preprocessAttachments(docInfos,blobType,(function(err3){if(err3)return callback(err3);startTransaction()}))}function runBatchedCursor(objectStore,keyRange,descending,batchSize,onBatch){function onGetAll(e3){valuesBatch=e3.target.result;keysBatch&&onBatch(keysBatch,valuesBatch,pseudoCursor)}function onGetAllKeys(e3){keysBatch=e3.target.result;valuesBatch&&onBatch(keysBatch,valuesBatch,pseudoCursor)}function onCursor(e3){var cursor=e3.target.result;if(!cursor)return onBatch();onBatch([cursor.key],[cursor.value],cursor)}var keysBatch,valuesBatch,pseudoCursor;-1===batchSize&&(batchSize=1e3);if("function"==typeof objectStore.getAll&&"function"==typeof objectStore.getAllKeys&&batchSize>1&&!descending){pseudoCursor={continue:function continuePseudoCursor(){var lastKey,newKeyRange;if(!keysBatch.length)return onBatch();lastKey=keysBatch[keysBatch.length-1];if(keyRange&&keyRange.upper)try{newKeyRange=IDBKeyRange.bound(lastKey,keyRange.upper,!0,keyRange.upperOpen)}catch(e3){if("DataError"===e3.name&&0===e3.code)return onBatch()}else newKeyRange=IDBKeyRange.lowerBound(lastKey,!0);keyRange=newKeyRange;keysBatch=null;valuesBatch=null;objectStore.getAll(keyRange,batchSize).onsuccess=onGetAll;objectStore.getAllKeys(keyRange,batchSize).onsuccess=onGetAllKeys}};objectStore.getAll(keyRange,batchSize).onsuccess=onGetAll;objectStore.getAllKeys(keyRange,batchSize).onsuccess=onGetAllKeys}else descending?objectStore.openCursor(keyRange,"prev").onsuccess=onCursor:objectStore.openCursor(keyRange).onsuccess=onCursor}function getAll(objectStore,keyRange,onSuccess){if("function"!=typeof objectStore.getAll){var values=[];objectStore.openCursor(keyRange).onsuccess=function onCursor(e3){var cursor=e3.target.result;if(cursor){values.push(cursor.value);cursor.continue()}else onSuccess({target:{result:values}})}}else objectStore.getAll(keyRange).onsuccess=onSuccess}function allDocsKeys(keys3,docStore,onBatch){var valuesBatch=new Array(keys3.length),count=0;keys3.forEach((function(key3,index6){docStore.get(key3).onsuccess=function(event2){event2.target.result?valuesBatch[index6]=event2.target.result:valuesBatch[index6]={key:key3,error:"not_found"};++count===keys3.length&&onBatch(keys3,valuesBatch,{})}}))}function createKeyRange(start,end,inclusiveEnd,key3,descending){try{if(start&&end)return descending?IDBKeyRange.bound(end,start,!inclusiveEnd,!1):IDBKeyRange.bound(start,end,!1,!inclusiveEnd);if(start)return descending?IDBKeyRange.upperBound(start):IDBKeyRange.lowerBound(start);if(end)return descending?IDBKeyRange.lowerBound(end,!inclusiveEnd):IDBKeyRange.upperBound(end,!inclusiveEnd);if(key3)return IDBKeyRange.only(key3)}catch(e3){return{error:e3}}return null}function idbAllDocs(opts,idb,callback){function fetchDocAsynchronously(metadata,row,winningRev$$1){var key4=metadata.id+"::"+winningRev$$1;docIdRevIndex.get(key4).onsuccess=function onGetDoc(e3){row.doc=decodeDoc(e3.target.result)||{};if(opts.conflicts){var conflicts=collectConflicts(metadata);conflicts.length&&(row.doc._conflicts=conflicts)}fetchAttachmentsIfNecessary(row.doc,opts,txn)}}function allDocsInner(winningRev$$1,metadata){var row={id:metadata.id,key:metadata.id,value:{rev:winningRev$$1}};if(metadata.deleted){if(keys3){results.push(row);row.value.deleted=!0;row.doc=null}}else if(skip--<=0){results.push(row);opts.include_docs&&fetchDocAsynchronously(metadata,row,winningRev$$1)}}function processBatch(batchValues){var i2,len,batchValue,metadata;for(i2=0,len=batchValues.length;i2<len&&results.length!==limit;i2++)(batchValue=batchValues[i2]).error&&keys3?results.push(batchValue):allDocsInner((metadata=decodeMetadata(batchValue)).winningRev,metadata)}function onBatch(batchKeys,batchValues,cursor){if(cursor){processBatch(batchValues);results.length<limit&&cursor.continue()}}function onResultsReady(){var returnVal={total_rows:docCount,offset:opts.skip,rows:results};opts.update_seq&&void 0!==updateSeq&&(returnVal.update_seq=updateSeq);callback(null,returnVal)}var keyRange,keyRangeError,stores,txnResult,txn,docStore,seqStore,metaStore,docIdRevIndex,results,docCount,updateSeq,start="startkey"in opts&&opts.startkey,end="endkey"in opts&&opts.endkey,key3="key"in opts&&opts.key,keys3="keys"in opts&&opts.keys,skip=opts.skip||0,limit="number"==typeof opts.limit?opts.limit:-1,inclusiveEnd=!1!==opts.inclusive_end;if(!keys3&&(keyRangeError=(keyRange=createKeyRange(start,end,inclusiveEnd,key3,opts.descending))&&keyRange.error)&&("DataError"!==keyRangeError.name||0!==keyRangeError.code))return callback(createError(IDB_ERROR,keyRangeError.name,keyRangeError.message));stores=[DOC_STORE,BY_SEQ_STORE,META_STORE];opts.attachments&&stores.push(ATTACH_STORE);if((txnResult=openTransactionSafely(idb,stores,"readonly")).error)return callback(txnResult.error);(txn=txnResult.txn).oncomplete=function onTxnComplete(){opts.attachments?postProcessAttachments(results,opts.binary).then(onResultsReady):onResultsReady()};txn.onabort=idbError(callback);docStore=txn.objectStore(DOC_STORE);seqStore=txn.objectStore(BY_SEQ_STORE);metaStore=txn.objectStore(META_STORE);docIdRevIndex=seqStore.index("_doc_id_rev");results=[];metaStore.get(META_STORE).onsuccess=function(e3){docCount=e3.target.result.docCount};opts.update_seq&&(seqStore.openKeyCursor(null,"prev").onsuccess=e3=>{var cursor=e3.target.result;cursor&&cursor.key&&(updateSeq=cursor.key)});if(!keyRangeError&&0!==limit){if(keys3)return allDocsKeys(keys3,docStore,onBatch);if(-1===limit)return getAll(docStore,keyRange,(function onGetAll(e3){var values=e3.target.result;opts.descending&&(values=values.reverse());processBatch(values)}));runBatchedCursor(docStore,keyRange,opts.descending,limit+skip,onBatch)}}function countDocs(txn,cb2){txn.objectStore(DOC_STORE).index("deletedOrLocal").count(IDBKeyRange.only("0")).onsuccess=function(e3){cb2(e3.target.result)}}function tryCode(fun,err3,res2,PouchDB2){try{fun(err3,res2)}catch(err4){PouchDB2.emit("error",err4)}}function applyNext(){if(!running&&queue.length){running=!0;queue.shift()()}}function enqueueTask(action2,callback,PouchDB2){queue.push((function runAction(){action2((function runCallback(err3,res2){tryCode(callback,err3,res2,PouchDB2);running=!1;nextTick((function runNext(){applyNext()}))}))}));applyNext()}function changes(opts,api,dbName,idb){function onGetMetadata(doc,seq,metadata,cb2){var docIdRev;if(metadata.seq!==seq)return cb2();if(metadata.winningRev===doc._rev)return cb2(metadata,doc);docIdRev=doc._id+"::"+metadata.winningRev;docIdRevIndex.get(docIdRev).onsuccess=function(e3){cb2(metadata,decodeDoc(e3.target.result))}}function fetchWinningDocAndMetadata(doc,seq,cb2){if(docIds&&!docIds.has(doc._id))return cb2();var metadata=docIdsToMetadata.get(doc._id);if(metadata)return onGetMetadata(doc,seq,metadata,cb2);docStore.get(doc._id).onsuccess=function(e3){metadata=decodeMetadata(e3.target.result);docIdsToMetadata.set(doc._id,metadata);onGetMetadata(doc,seq,metadata,cb2)}}function finish(){opts.complete(null,{results,last_seq:lastSeq})}var id,docIds,lastSeq,limit,results,numResults,filter4,docIdsToMetadata,txn,bySeqStore,docStore,docIdRevIndex,objectStores,txnResult;if((opts=clone2(opts)).continuous){id=dbName+":"+uuid();changesHandler$1.addListener(dbName,id,api,opts);changesHandler$1.notify(dbName);return{cancel:function(){changesHandler$1.removeListener(dbName,id)}}}docIds=opts.doc_ids&&new Set(opts.doc_ids);opts.since=opts.since||0;lastSeq=opts.since;0===(limit="limit"in opts?opts.limit:-1)&&(limit=1);results=[];numResults=0;filter4=filterChange(opts);docIdsToMetadata=new Map;objectStores=[DOC_STORE,BY_SEQ_STORE];opts.attachments&&objectStores.push(ATTACH_STORE);if((txnResult=openTransactionSafely(idb,objectStores,"readonly")).error)return opts.complete(txnResult.error);(txn=txnResult.txn).onabort=idbError(opts.complete);txn.oncomplete=function onTxnComplete(){!opts.continuous&&opts.attachments?postProcessAttachments(results).then(finish):finish()};bySeqStore=txn.objectStore(BY_SEQ_STORE);docStore=txn.objectStore(DOC_STORE);docIdRevIndex=bySeqStore.index("_doc_id_rev");runBatchedCursor(bySeqStore,opts.since&&!opts.descending?IDBKeyRange.lowerBound(opts.since,!0):null,opts.descending,limit,(function onBatch(batchKeys,batchValues,cursor){function processMetadataAndWinningDoc(metadata,winningDoc){var filtered,change=opts.processChange(winningDoc,metadata,opts);lastSeq=change.seq=metadata.seq;if("object"==typeof(filtered=filter4(change)))return Promise.reject(filtered);if(!filtered)return Promise.resolve();numResults++;opts.return_docs&&results.push(change);return opts.attachments&&opts.include_docs?new Promise((function(resolve){fetchAttachmentsIfNecessary(winningDoc,opts,txn,(function(){postProcessAttachments([change],opts.binary).then((function(){resolve(change)}))}))})):Promise.resolve(change)}function onBatchDone(){var i2,len,winningDoc,metadata,promises=[];for(i2=0,len=winningDocs.length;i2<len&&numResults!==limit;i2++)if(winningDoc=winningDocs[i2]){metadata=metadatas[i2];promises.push(processMetadataAndWinningDoc(metadata,winningDoc))}Promise.all(promises).then((function(changes3){for(var i3=0,len2=changes3.length;i3<len2;i3++)changes3[i3]&&opts.onChange(changes3[i3])})).catch(opts.complete);numResults!==limit&&cursor.continue()}var winningDocs,metadatas,numDone;if(cursor&&batchKeys.length){winningDocs=new Array(batchKeys.length);metadatas=new Array(batchKeys.length);numDone=0;batchValues.forEach((function(value,i2){fetchWinningDocAndMetadata(decodeDoc(value),batchKeys[i2],(function(metadata,winningDoc){metadatas[i2]=metadata;winningDocs[i2]=winningDoc;++numDone===batchKeys.length&&onBatchDone()}))}))}}))}function IdbPouch(opts,callback){var api=this;enqueueTask((function(thisCallback){init2(api,opts,thisCallback)}),callback,api.constructor)}function init2(api,opts,callback){function enrichCallbackError(callback2){return function(error,result){error&&error instanceof Error&&!error.reason&&idbGlobalFailureError&&(error.reason=idbGlobalFailureError);callback2(error,result)}}function createSchema(db){var attAndSeqStore,docStore=db.createObjectStore(DOC_STORE,{keyPath:"id"});db.createObjectStore(BY_SEQ_STORE,{autoIncrement:!0}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0});db.createObjectStore(ATTACH_STORE,{keyPath:"digest"});db.createObjectStore(META_STORE,{keyPath:"id",autoIncrement:!1});db.createObjectStore(DETECT_BLOB_SUPPORT_STORE);docStore.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1});db.createObjectStore(LOCAL_STORE,{keyPath:"_id"});(attAndSeqStore=db.createObjectStore(ATTACH_AND_SEQ_STORE,{autoIncrement:!0})).createIndex("seq","seq");attAndSeqStore.createIndex("digestSeq","digestSeq",{unique:!0})}function addDeletedOrLocalIndex(txn,callback2){var docStore=txn.objectStore(DOC_STORE);docStore.createIndex("deletedOrLocal","deletedOrLocal",{unique:!1});docStore.openCursor().onsuccess=function(event2){var metadata,deleted,cursor=event2.target.result;if(cursor){deleted=isDeleted(metadata=cursor.value);metadata.deletedOrLocal=deleted?"1":"0";docStore.put(metadata);cursor.continue()}else callback2()}}function createLocalStoreSchema(db){db.createObjectStore(LOCAL_STORE,{keyPath:"_id"}).createIndex("_doc_id_rev","_doc_id_rev",{unique:!0})}function migrateLocalStore(txn,cb2){var localStore=txn.objectStore(LOCAL_STORE),docStore=txn.objectStore(DOC_STORE),seqStore=txn.objectStore(BY_SEQ_STORE);docStore.openCursor().onsuccess=function(event2){var metadata,docId,local,rev3,docIdRev,start,end,index6,range3,seqCursor,cursor2=event2.target.result;if(cursor2){local=isLocalId(docId=(metadata=cursor2.value).id);rev3=winningRev(metadata);if(local){docIdRev=docId+"::"+rev3;start=docId+"::";end=docId+"::~";index6=seqStore.index("_doc_id_rev");range3=IDBKeyRange.bound(start,end,!1,!1);(seqCursor=index6.openCursor(range3)).onsuccess=function(e3){if(seqCursor=e3.target.result){var data=seqCursor.value;data._doc_id_rev===docIdRev&&localStore.put(data);seqStore.delete(seqCursor.primaryKey);seqCursor.continue()}else{docStore.delete(cursor2.primaryKey);cursor2.continue()}}}else cursor2.continue()}else cb2&&cb2()}}function addAttachAndSeqStore(db){var attAndSeqStore=db.createObjectStore(ATTACH_AND_SEQ_STORE,{autoIncrement:!0});attAndSeqStore.createIndex("seq","seq");attAndSeqStore.createIndex("digestSeq","digestSeq",{unique:!0})}function migrateAttsAndSeqs(txn,callback2){var seqStore=txn.objectStore(BY_SEQ_STORE),attStore=txn.objectStore(ATTACH_STORE),attAndSeqStore=txn.objectStore(ATTACH_AND_SEQ_STORE);attStore.count().onsuccess=function(e3){if(!e3.target.result)return callback2();seqStore.openCursor().onsuccess=function(e4){var doc,seq,atts,digestMap,j2,digests,digest,cursor=e4.target.result;if(!cursor)return callback2();doc=cursor.value;seq=cursor.primaryKey;atts=Object.keys(doc._attachments||{});digestMap={};for(j2=0;j2<atts.length;j2++)digestMap[doc._attachments[atts[j2]].digest]=!0;digests=Object.keys(digestMap);for(j2=0;j2<digests.length;j2++){digest=digests[j2];attAndSeqStore.put({seq,digestSeq:digest+"::"+seq})}cursor.continue()}}}function migrateMetadata(txn){function decodeMetadataCompat(storedObject){if(!storedObject.data){storedObject.deleted="1"===storedObject.deletedOrLocal;return storedObject}return decodeMetadata(storedObject)}var bySeqStore=txn.objectStore(BY_SEQ_STORE),docStore=txn.objectStore(DOC_STORE);docStore.openCursor().onsuccess=function(e3){function onGetMetadataSeq(){var metadataToStore=encodeMetadata(metadata,metadata.winningRev,metadata.deleted);docStore.put(metadataToStore).onsuccess=function(){cursor2.continue()}}var metadata,cursor2=e3.target.result;if(cursor2){(metadata=decodeMetadataCompat(cursor2.value)).winningRev=metadata.winningRev||winningRev(metadata);if(metadata.seq)return onGetMetadataSeq();(function fetchMetadataSeq(){var start=metadata.id+"::",end=metadata.id+"::￿",req2=bySeqStore.index("_doc_id_rev").openCursor(IDBKeyRange.bound(start,end)),metadataSeq=0;req2.onsuccess=function(e4){var seq,cursor3=e4.target.result;if(!cursor3){metadata.seq=metadataSeq;return onGetMetadataSeq()}(seq=cursor3.primaryKey)>metadataSeq&&(metadataSeq=seq);cursor3.continue()}})()}}}var cached,req,dbName=opts.name,idb=null,idbGlobalFailureError=null;api._meta=null;api._remote=!1;api.type=function(){return"idb"};api._id=toPromise((function(callback2){callback2(null,api._meta.instanceId)}));api._bulkDocs=function idb_bulkDocs(req2,reqOpts,callback2){idbBulkDocs(opts,req2,reqOpts,api,idb,enrichCallbackError(callback2))};api._get=function idb_get(id,opts2,callback2){function finish(){callback2(err3,{doc,metadata,ctx:txn})}var doc,metadata,err3,txnResult,txn=opts2.ctx;if(!txn){if((txnResult=openTransactionSafely(idb,[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE],"readonly")).error)return callback2(txnResult.error);txn=txnResult.txn}txn.objectStore(DOC_STORE).get(id).onsuccess=function(e3){var rev3,objectStore,key3;if(!(metadata=decodeMetadata(e3.target.result))){err3=createError(MISSING_DOC,"missing");return finish()}if(opts2.rev)rev3=opts2.latest?latest(opts2.rev,metadata):opts2.rev;else{rev3=metadata.winningRev;if(isDeleted(metadata)){err3=createError(MISSING_DOC,"deleted");return finish()}}objectStore=txn.objectStore(BY_SEQ_STORE);key3=metadata.id+"::"+rev3;objectStore.index("_doc_id_rev").get(key3).onsuccess=function(e4){(doc=e4.target.result)&&(doc=decodeDoc(doc));if(!doc){err3=createError(MISSING_DOC,"missing");return finish()}finish()}}};api._getAttachment=function(docId,attachId,attachment,opts2,callback2){var txn,txnResult,digest,type;if(opts2.ctx)txn=opts2.ctx;else{if((txnResult=openTransactionSafely(idb,[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE],"readonly")).error)return callback2(txnResult.error);txn=txnResult.txn}digest=attachment.digest;type=attachment.content_type;txn.objectStore(ATTACH_STORE).get(digest).onsuccess=function(e3){readBlobData(e3.target.result.body,type,opts2.binary,(function(blobData){callback2(null,blobData)}))}};api._info=function idb_info(callback2){var updateSeq,docCount,txn,txnResult=openTransactionSafely(idb,[META_STORE,BY_SEQ_STORE],"readonly");if(txnResult.error)return callback2(txnResult.error);(txn=txnResult.txn).objectStore(META_STORE).get(META_STORE).onsuccess=function(e3){docCount=e3.target.result.docCount};txn.objectStore(BY_SEQ_STORE).openKeyCursor(null,"prev").onsuccess=function(e3){var cursor=e3.target.result;updateSeq=cursor?cursor.key:0};txn.oncomplete=function(){callback2(null,{doc_count:docCount,update_seq:updateSeq,idb_attachment_format:api._meta.blobSupport?"binary":"base64"})}};api._allDocs=function idb_allDocs(opts2,callback2){idbAllDocs(opts2,idb,enrichCallbackError(callback2))};api._changes=function idbChanges2(opts2){return changes(opts2,api,dbName,idb)};api._close=function(callback2){idb.close();cachedDBs.delete(dbName);callback2()};api._getRevisionTree=function(docId,callback2){var txnResult=openTransactionSafely(idb,[DOC_STORE],"readonly");if(txnResult.error)return callback2(txnResult.error);txnResult.txn.objectStore(DOC_STORE).get(docId).onsuccess=function(event2){var doc=decodeMetadata(event2.target.result);doc?callback2(null,doc.rev_tree):callback2(createError(MISSING_DOC))}};api._doCompaction=function(docId,revs,callback2){var txn,txnResult=openTransactionSafely(idb,[DOC_STORE,BY_SEQ_STORE,ATTACH_STORE,ATTACH_AND_SEQ_STORE],"readwrite");if(txnResult.error)return callback2(txnResult.error);(txn=txnResult.txn).objectStore(DOC_STORE).get(docId).onsuccess=function(event2){var winningRev$$1,deleted,metadata=decodeMetadata(event2.target.result);traverseRevTree(metadata.rev_tree,(function(isLeaf,pos,revHash,ctx,opts2){var rev3=pos+"-"+revHash;-1!==revs.indexOf(rev3)&&(opts2.status="missing")}));compactRevs(revs,docId,txn);winningRev$$1=metadata.winningRev;deleted=metadata.deleted;txn.objectStore(DOC_STORE).put(encodeMetadata(metadata,winningRev$$1,deleted))};txn.onabort=idbError(callback2);txn.oncomplete=function(){callback2()}};api._getLocal=function(id,callback2){var req2,txnResult=openTransactionSafely(idb,[LOCAL_STORE],"readonly");if(txnResult.error)return callback2(txnResult.error);(req2=txnResult.txn.objectStore(LOCAL_STORE).get(id)).onerror=idbError(callback2);req2.onsuccess=function(e3){var doc=e3.target.result;if(doc){delete doc._doc_id_rev;callback2(null,doc)}else callback2(createError(MISSING_DOC))}};api._putLocal=function(doc,opts2,callback2){var oldRev,id,tx,ret,txnResult,oStore,req2;if("function"==typeof opts2){callback2=opts2;opts2={}}delete doc._revisions;oldRev=doc._rev;id=doc._id;doc._rev=oldRev?"0-"+(parseInt(oldRev.split("-")[1],10)+1):"0-1";if(!(tx=opts2.ctx)){if((txnResult=openTransactionSafely(idb,[LOCAL_STORE],"readwrite")).error)return callback2(txnResult.error);(tx=txnResult.txn).onerror=idbError(callback2);tx.oncomplete=function(){ret&&callback2(null,ret)}}oStore=tx.objectStore(LOCAL_STORE);if(oldRev)(req2=oStore.get(id)).onsuccess=function(e3){var oldDoc=e3.target.result;oldDoc&&oldDoc._rev===oldRev?oStore.put(doc).onsuccess=function(){ret={ok:!0,id:doc._id,rev:doc._rev};opts2.ctx&&callback2(null,ret)}:callback2(createError(REV_CONFLICT))};else{(req2=oStore.add(doc)).onerror=function(e3){callback2(createError(REV_CONFLICT));e3.preventDefault();e3.stopPropagation()};req2.onsuccess=function(){ret={ok:!0,id:doc._id,rev:doc._rev};opts2.ctx&&callback2(null,ret)}}};api._removeLocal=function(doc,opts2,callback2){var tx,txnResult,ret,id,oStore,req2;if("function"==typeof opts2){callback2=opts2;opts2={}}if(!(tx=opts2.ctx)){if((txnResult=openTransactionSafely(idb,[LOCAL_STORE],"readwrite")).error)return callback2(txnResult.error);(tx=txnResult.txn).oncomplete=function(){ret&&callback2(null,ret)}}id=doc._id;(req2=(oStore=tx.objectStore(LOCAL_STORE)).get(id)).onerror=idbError(callback2);req2.onsuccess=function(e3){var oldDoc=e3.target.result;if(oldDoc&&oldDoc._rev===doc._rev){oStore.delete(id);ret={ok:!0,id,rev:"0-0"};opts2.ctx&&callback2(null,ret)}else callback2(createError(MISSING_DOC))}};api._destroy=function(opts2,callback2){var openReq,req2;changesHandler$1.removeAllListeners(dbName);if((openReq=openReqList.get(dbName))&&openReq.result){openReq.result.close();cachedDBs.delete(dbName)}(req2=indexedDB.deleteDatabase(dbName)).onsuccess=function(){openReqList.delete(dbName);hasLocalStorage()&&dbName in localStorage&&delete localStorage[dbName];callback2(null,{ok:!0})};req2.onerror=idbError(callback2)};if(cached=cachedDBs.get(dbName)){idb=cached.idb;api._meta=cached.global;return nextTick((function(){callback(null,api)}))}req=indexedDB.open(dbName,ADAPTER_VERSION);openReqList.set(dbName,req);req.onupgradeneeded=function(e3){var txn,migrations,i2,db=e3.target.result;if(e3.oldVersion<1)return createSchema(db);txn=e3.currentTarget.transaction;e3.oldVersion<3&&createLocalStoreSchema(db);e3.oldVersion<4&&addAttachAndSeqStore(db);migrations=[addDeletedOrLocalIndex,migrateLocalStore,migrateAttsAndSeqs,migrateMetadata];i2=e3.oldVersion;(function next2(){var migration=migrations[i2-1];i2++;migration&&migration(txn,next2)})()};req.onsuccess=function(e3){function completeSetup(){if(void 0!==blobSupport&&storedMetaDoc){api._meta={name:dbName,instanceId,blobSupport};cachedDBs.set(dbName,{idb,global:api._meta});callback(null,api)}}function storeMetaDocIfReady(){if(void 0!==docCount&&void 0!==metaDoc){var instanceKey=dbName+"_id";instanceKey in metaDoc?instanceId=metaDoc[instanceKey]:metaDoc[instanceKey]=instanceId=uuid();metaDoc.docCount=docCount;txn.objectStore(META_STORE).put(metaDoc)}}var txn,storedMetaDoc,metaDoc,docCount,blobSupport,instanceId;(idb=e3.target.result).onversionchange=function(){idb.close();cachedDBs.delete(dbName)};idb.onabort=function(e4){guardedConsole("error","Database has a global failure",e4.target.error);idbGlobalFailureError=e4.target.error;idb.close();cachedDBs.delete(dbName)};txn=idb.transaction([META_STORE,DETECT_BLOB_SUPPORT_STORE,DOC_STORE],"readwrite");storedMetaDoc=!1;txn.objectStore(META_STORE).get(META_STORE).onsuccess=function(e4){metaDoc=e4.target.result||{id:META_STORE};storeMetaDocIfReady()};countDocs(txn,(function(count){docCount=count;storeMetaDocIfReady()}));blobSupportPromise||(blobSupportPromise=checkBlobSupport(txn,DETECT_BLOB_SUPPORT_STORE,"key"));blobSupportPromise.then((function(val2){blobSupport=val2;completeSetup()}));txn.oncomplete=function(){storedMetaDoc=!0;completeSetup()};txn.onabort=idbError(callback)};req.onerror=function(e3){var msg=e3.target.error&&e3.target.error.message;msg?-1!==msg.indexOf("stored database is a higher version")&&(msg=new Error('This DB was created with the newer "indexeddb" adapter, but you are trying to open it with the older "idb" adapter')):msg="Failed to open indexedDB, are you in private browsing mode?";guardedConsole("error",msg);callback(createError(IDB_ERROR,msg))}}function needsSanitise(name,isPath){return isPath?TEST_PATH_INVALID.test(name):TEST_KEY_INVALID.test(name)}function sanitise(name,isPath){const correctCharacters=function(match3){let good="";for(let i2=0;i2<match3.length;i2++){const code=match3.charCodeAt(i2);if(code===IS_DOT&&isPath&&0===i2)good+=".";else{if(code===SLASH&&isPath)continue;good+="_c"+code+"_"}}return good};return isPath?name.replace(PATH_INVALID,correctCharacters):name.replace(KEY_INVALID,correctCharacters)}function needsRewrite(data){for(const key3 of Object.keys(data)){if(needsSanitise(key3))return!0;if(null===data[key3]||"boolean"==typeof data[key3])return!0;if("object"==typeof data[key3])return needsRewrite(data[key3])}}function rewrite(data){if(!needsRewrite(data))return!1;const isArray2=Array.isArray(data),clone3=isArray2?[]:{};Object.keys(data).forEach((function(key3){const safeKey=isArray2?key3:sanitise(key3);null===data[key3]?clone3[safeKey]=IDB_NULL:"boolean"==typeof data[key3]?clone3[safeKey]=data[key3]?IDB_TRUE:IDB_FALSE:"object"==typeof data[key3]?clone3[safeKey]=rewrite(data[key3]):clone3[safeKey]=data[key3]}));return clone3}function idbError2(callback){return function(evt){let message="unknown_error";evt.target&&evt.target.error&&(message=evt.target.error.name||evt.target.error.message);callback(createError(IDB_ERROR,message,evt.type))}}function processAttachment(name,src,doc,isBinary,attachmentFormat){delete doc._attachments[name].stub;if("base64"===attachmentFormat){if(isBinary){const att=src.attachments[doc._attachments[name].digest];doc._attachments[name].data=b64ToBluffer(att.data,att.content_type)}else doc._attachments[name].data=src.attachments[doc._attachments[name].digest].data;delete doc._attachments[name].length;return Promise.resolve()}if(isBinary){doc._attachments[name].data=src.attachments[doc._attachments[name].digest].data;return Promise.resolve()}return new Promise((function(resolve){readAsBinaryString(src.attachments[doc._attachments[name].digest].data,(function(binString){doc._attachments[name].data=thisBtoa(binString);delete doc._attachments[name].length;resolve()}))}))}function rawIndexFields(ddoc,viewName){return(ddoc.views[viewName].options&&ddoc.views[viewName].options.def&&ddoc.views[viewName].options.def.fields||[]).map((function(field){return"string"==typeof field?field:Object.keys(field)[0]}))}function isPartialFilterView(ddoc,viewName){return viewName in ddoc.views&&ddoc.views[viewName].options&&ddoc.views[viewName].options.def&&ddoc.views[viewName].options.def.partial_filter_selector}function naturalIndexName(fields){return"_find_idx/"+fields.join("/")}function correctIndexFields(fields){return["deleted"].concat(fields.map((function(field){return["_id","_rev","_deleted","_attachments"].includes(field)?field.substr(1):"data."+sanitise(field,!0)})))}function createIdbVersion(){return versionMultiplier*POUCHDB_IDB_VERSION+(new Date).getTime()}function getPouchDbVersion(version2){return Math.floor(version2/versionMultiplier)}function maintainNativeIndexes(openReq,reject){const docStore=openReq.transaction.objectStore(DOC_STORE2);docStore.getAll(IDBKeyRange.bound("_design/","_design/￿")).onsuccess=function(e3){const results=e3.target.result,existingIndexNames=Array.from(docStore.indexNames),expectedIndexes=results.filter((function(row){return 0===row.deleted&&row.revs[row.rev].data.views})).map((function(row){return row.revs[row.rev].data})).reduce((function(indexes2,ddoc){return Object.keys(ddoc.views).reduce((function(acc,viewName){const fields=rawIndexFields(ddoc,viewName);fields&&fields.length>0&&(acc[naturalIndexName(fields)]=correctIndexFields(fields));return acc}),indexes2)}),{}),expectedIndexNames=Object.keys(expectedIndexes),systemIndexNames=["seq","deleted,id"];existingIndexNames.forEach((function(index6){-1===systemIndexNames.indexOf(index6)&&-1===expectedIndexNames.indexOf(index6)&&docStore.deleteIndex(index6)}));const newIndexNames=expectedIndexNames.filter((function(ei){return-1===existingIndexNames.indexOf(ei)}));try{newIndexNames.forEach((function(indexName){docStore.createIndex(indexName,expectedIndexes[indexName])}))}catch(err3){reject(err3)}}}function upgradePouchDbSchema(dbName,db,tx,pouchdbVersion){if(pouchdbVersion<1){db.createObjectStore(DOC_STORE2,{keyPath:"id"}).createIndex("seq","seq",{unique:!0});db.createObjectStore(META_LOCAL_STORE,{keyPath:"id"})}if(pouchdbVersion<2){const docStore=tx.objectStore(DOC_STORE2);docStore.createIndex("deleted,id",["deleted","id"],{unique:!0});dbName.includes("-mrview-")&&docStore.deleteIndex("seq")}}function openDatabase(openDatabases2,api,opts,resolve,reject){const openReq=opts.versionChangedWhileOpen?indexedDB.open(opts.name):indexedDB.open(opts.name,createIdbVersion());openReq.onupgradeneeded=function(e3){if(e3.oldVersion>0&&e3.oldVersion<versionMultiplier)throw new Error('Incorrect adapter: you should specify the "idb" adapter to open this DB');if(0===e3.oldVersion&&e3.newVersion<versionMultiplier){indexedDB.deleteDatabase(opts.name);throw new Error("Database was deleted while open")}const tx=e3.target.transaction,db=e3.target.result,pouchdbVersion=getPouchDbVersion(e3.oldVersion);upgradePouchDbSchema(opts.name,db,tx,pouchdbVersion);maintainNativeIndexes(openReq,reject);if(pouchdbVersion<2){const docStore=openReq.transaction.objectStore(DOC_STORE2),metaStore=openReq.transaction.objectStore(META_LOCAL_STORE);docStore.openCursor().onsuccess=event2=>{const cursor=event2.target.result;if(!cursor)return;const doc=cursor.value;if(!isLocalId(doc.id))return cursor.continue();metaStore.put(doc).onsuccess=()=>{cursor.delete(doc).onsuccess=()=>{cursor.continue()}}}}};openReq.onblocked=function(e3){console.error("onblocked, this should never happen",e3)};openReq.onsuccess=function(e3){const idb=e3.target.result;idb.onabort=function(e4){console.error("Database has a global failure",e4.target.error);delete openDatabases2[opts.name];idb.close()};idb.onversionchange=function(){console.log("Database was made stale, closing handle");openDatabases2[opts.name].versionChangedWhileOpen=!0;idb.close()};idb.onclose=function(){console.log("Database was made stale, closing handle");opts.name in openDatabases2&&(openDatabases2[opts.name].versionChangedWhileOpen=!0)};let metadata={id:META_LOCAL_STORE};const txn=idb.transaction([META_LOCAL_STORE],"readwrite");txn.oncomplete=function(){resolve({idb,metadata})};const metaStore=txn.objectStore(META_LOCAL_STORE);metaStore.get(META_LOCAL_STORE).onsuccess=function(e4){metadata=e4.target.result||metadata;let changed=!1;if(!("doc_count"in metadata)){changed=!0;metadata.doc_count=0}if(!("seq"in metadata)){changed=!0;metadata.seq=0}if(!("db_uuid"in metadata)){changed=!0;metadata.db_uuid=uuid()}if("idb_attachment_format"in metadata){if(changed){api.blobSupport=metadata.idb_attachment_format;metaStore.put(metadata)}}else checkBlobSupport(txn,META_LOCAL_STORE,(blob=>({id:"blob-support",blob}))).then((blobSupport=>{api.blobSupport=metadata.idb_attachment_format=blobSupport?"binary":"base64";metaStore.put(metadata)}))}};openReq.onerror=function(e3){reject(e3.target.error)}}function setup(openDatabases2,api,opts){if(!openDatabases2[opts.name]||openDatabases2[opts.name].versionChangedWhileOpen){opts.versionChangedWhileOpen=openDatabases2[opts.name]&&openDatabases2[opts.name].versionChangedWhileOpen;openDatabases2[opts.name]=new Promise((function(resolve,reject){openDatabase(openDatabases2,api,opts,resolve,reject)}))}return openDatabases2[opts.name]}function info2(metadata,callback){callback(null,{doc_count:metadata.doc_count,update_seq:metadata.seq})}function get3(txn,id,opts,callback){if(txn.error)return callback(txn.error);txn.txn.objectStore(DOC_STORE2).get(id).onsuccess=function(e3){const doc=e3.target.result;let rev3;rev3=opts.rev?opts.latest?latest(opts.rev,doc):opts.rev:doc&&doc.rev;if(!doc||doc.deleted&&!opts.rev||!(rev3 in doc.revs)){callback(createError(MISSING_DOC,"missing"));return}const result=doc.revs[rev3].data;result._id=doc.id;result._rev=rev3;callback(null,{doc:result,metadata:doc,ctx:txn})}}function getLocal(txn,id,api,callback){if(txn.error)return callback(txn.error);txn.txn.objectStore(META_LOCAL_STORE).get(id).onsuccess=function(e3){const doc=e3.target.result;if(!doc){callback(createError(MISSING_DOC,"missing"));return}const result=doc.revs[doc.rev].data;result._id=doc.id;result._rev=doc.rev;if(result._attachments){const processing=[];for(const name in result._attachments)processing.push(processAttachment(name,doc,result,BINARY_ATTACHMENTS,api.blobSupport));Promise.all(processing).then((()=>callback(null,result))).catch(callback)}else callback(null,result)}}function getAttachment(docId,attachId,attachment,opts,cb2){if(isLocalId(docId)){cb2(createError(MISSING_DOC,"missing"));return}const data=opts.metadata.attachments[attachment.digest].data;if("string"!=typeof data){if(opts.binary)return cb2(null,data);readAsBinaryString(data,(function(binString){cb2(null,thisBtoa(binString))}))}else opts.binary?cb2(null,b64ToBluffer(data,attachment.content_type)):cb2(null,data)}function bulkDocs(api,req,opts,metadata,dbOpts,idbChanges2,callback){function docsRevsLimit(doc){return isLocalId(doc.id)?1:revsLimit}function rootIsMissing2(doc){return"missing"===doc.rev_tree[0].ids[1].status}function fetchExistingDocs(txn2,docs2){function readDone(e3){e3.target.result&&(oldDocs[e3.target.result.id]=e3.target.result);++fetched===docs2.length&&processDocs2(txn2,docs2,oldDocs)}let fetched=0;const oldDocs={};docs2.forEach((function(doc){const docStore=isLocalId(doc.id)?META_LOCAL_STORE:DOC_STORE2;txn2.objectStore(docStore).get(doc.id).onsuccess=readDone}))}function revHasAttachment(doc,rev3,digest){return doc.revs[rev3]&&doc.revs[rev3].data._attachments&&Object.values(doc.revs[rev3].data._attachments).find((function(att){return att.digest===digest}))}function processDocs2(txn2,docs2,oldDocs){docs2.forEach((function(doc,i2){let newDoc;if("was_delete"in opts&&!Object.prototype.hasOwnProperty.call(oldDocs,doc.id))newDoc=createError(MISSING_DOC,"deleted");else if(opts.new_edits&&!Object.prototype.hasOwnProperty.call(oldDocs,doc.id)&&rootIsMissing2(doc))newDoc=createError(REV_CONFLICT);else if(Object.prototype.hasOwnProperty.call(oldDocs,doc.id)){newDoc=update2(0,doc,oldDocs[doc.id]);if(0==newDoc)return}else{const merged=merge2([],doc.rev_tree[0],docsRevsLimit(doc));doc.rev_tree=merged.tree;doc.stemmedRevs=merged.stemmedRevs;newDoc=doc;newDoc.isNewDoc=!0;newDoc.wasDeleted=doc.revs[doc.rev].deleted?1:0}if(newDoc.error)results[i2]=newDoc;else{oldDocs[newDoc.id]=newDoc;lastWriteIndex=i2;write(txn2,newDoc,i2)}}))}function convertDocFormat(doc){const newDoc={id:doc.metadata.id,rev:doc.metadata.rev,rev_tree:doc.metadata.rev_tree,revs:doc.metadata.revs||{}};newDoc.revs[newDoc.rev]={data:doc.data,deleted:doc.metadata.deleted};return newDoc}function update2(txn2,doc,oldDoc){if(doc.rev in oldDoc.revs&&!opts.new_edits)return!1;const isRoot=/^1-/.test(doc.rev);if(oldDoc.deleted&&!doc.deleted&&opts.new_edits&&isRoot){const tmp=doc.revs[doc.rev].data;tmp._rev=oldDoc.rev;tmp._id=oldDoc.id;doc=convertDocFormat(parseDoc(tmp,opts.new_edits,dbOpts))}const merged=merge2(oldDoc.rev_tree,doc.rev_tree[0],docsRevsLimit(doc));doc.stemmedRevs=merged.stemmedRevs;doc.rev_tree=merged.tree;const revs=oldDoc.revs;revs[doc.rev]=doc.revs[doc.rev];doc.revs=revs;doc.attachments=oldDoc.attachments;if(opts.new_edits&&(oldDoc.deleted&&doc.deleted||!oldDoc.deleted&&"new_leaf"!==merged.conflicts||oldDoc.deleted&&!doc.deleted&&"new_branch"===merged.conflicts||oldDoc.rev===doc.rev))return createError(REV_CONFLICT);doc.wasDeleted=oldDoc.deleted;return doc}function write(txn2,doc,i2){const winningRev$$1=winningRev(doc),writtenRev=doc.rev,isLocal=isLocalId(doc.id),theDoc=doc.revs[winningRev$$1].data,isNewDoc=doc.isNewDoc;if(rewriteEnabled){const result=rewrite(theDoc);if(result){doc.data=result;delete doc.data._attachments}else doc.data=theDoc}else doc.data=theDoc;doc.rev=winningRev$$1;doc.deleted=doc.revs[winningRev$$1].deleted?1:0;if(!isLocal){doc.seq=++metadata.seq;let delta=0;doc.isNewDoc?delta=doc.deleted?0:1:doc.wasDeleted!==doc.deleted&&(delta=doc.deleted?-1:1);metadata.doc_count+=delta}delete doc.isNewDoc;delete doc.wasDeleted;let revsToDelete=doc.stemmedRevs||[];if(autoCompaction&&!isNewDoc){const result=compactTree(doc);result.length&&(revsToDelete=revsToDelete.concat(result))}revsToDelete.length&&revsToDelete.forEach((function(rev3){delete doc.revs[rev3]}));delete doc.stemmedRevs;"attachments"in doc||(doc.attachments={});if(theDoc._attachments)for(const k2 in theDoc._attachments){const attachment=theDoc._attachments[k2];if(attachment.stub){if(!(attachment.digest in doc.attachments)){error=createError(MISSING_STUB);txn2.abort();return}revHasAttachment(doc,writtenRev,attachment.digest)&&(doc.attachments[attachment.digest].revs[writtenRev]=!0)}else{doc.attachments[attachment.digest]=attachment;doc.attachments[attachment.digest].revs={};doc.attachments[attachment.digest].revs[writtenRev]=!0;theDoc._attachments[k2]={stub:!0,digest:attachment.digest,content_type:attachment.content_type,length:attachment.length,revpos:parseInt(writtenRev,10)}}}if(isLocal&&doc.deleted){txn2.objectStore(META_LOCAL_STORE).delete(doc.id).onsuccess=function(){results[i2]={ok:!0,id:doc.id,rev:"0-0"}};updateSeq(i2);return}const docStore=isLocal?META_LOCAL_STORE:DOC_STORE2;txn2.objectStore(docStore).put(doc).onsuccess=function(){results[i2]={ok:!0,id:doc.id,rev:writtenRev};updateSeq(i2)}}function updateSeq(i2){i2===lastWriteIndex&&txn.objectStore(META_LOCAL_STORE).put(metadata)}function preProcessAttachment(attachment){if(attachment.stub)return Promise.resolve(attachment);let binData;if("string"==typeof attachment.data){try{binData=thisAtob(attachment.data)}catch(e3){return Promise.reject(createError(BAD_ARG,"Attachment is not a valid base64 string"))}"binary"===metadata.idb_attachment_format&&(attachment.data=binStringToBluffer(binData,attachment.content_type))}else{binData=attachment.data;if("base64"===metadata.idb_attachment_format)return new Promise((resolve=>{blobToBase64(attachment.data,(function(b64){attachment.data=b64;binaryMd5(binData,(function(result){attachment.digest="md5-"+result;attachment.length=binData.size||binData.length||0;resolve(attachment)}))}))}))}return new Promise((function(resolve){binaryMd5(binData,(function(result){attachment.digest="md5-"+result;attachment.length=binData.size||binData.length||0;resolve(attachment)}))}))}let txn,error;const results=[],docs=[];let lastWriteIndex;const revsLimit=dbOpts.revs_limit||1e3,rewriteEnabled=-1===dbOpts.name.indexOf("-mrview-"),autoCompaction=dbOpts.auto_compaction;for(let i2=0,len=req.docs.length;i2<len;i2++){let result;try{result=parseDoc(req.docs[i2],opts.new_edits,dbOpts)}catch(err3){result=err3}if(result.error)return callback(result);docs.push(convertDocFormat(result))}(function preProcessAttachments(){const promises=docs.map((function(doc){const data=doc.revs[doc.rev].data;if(!data._attachments)return Promise.resolve(data);const attachments=Object.keys(data._attachments).map((function(k2){data._attachments[k2].name=k2;return preProcessAttachment(data._attachments[k2])}));return Promise.all(attachments).then((function(newAttachments){const processed={};newAttachments.forEach((function(attachment){processed[attachment.name]=attachment;delete attachment.name}));data._attachments=processed;return data}))}));return Promise.all(promises)})().then((function(){api._openTransactionSafely([DOC_STORE2,META_LOCAL_STORE],"readwrite",(function(err3,_txn){if(err3)return callback(err3);txn=_txn;txn.onabort=function(){callback(error||createError(UNKNOWN_ERROR,"transaction was aborted"))};txn.ontimeout=idbError2(callback);txn.oncomplete=function(){idbChanges2.notify(dbOpts.name);callback(null,results)};fetchExistingDocs(txn,docs)}))})).catch((function(err3){callback(err3)}))}function allDocsKeys2(keys3,docStore,allDocsInner){const valuesBatch=new Array(keys3.length);let count=0;keys3.forEach((function(key3,index6){docStore.get(key3).onsuccess=function(event2){event2.target.result?valuesBatch[index6]=event2.target.result:valuesBatch[index6]={key:key3,error:"not_found"};count++;count===keys3.length&&valuesBatch.forEach((function(doc){allDocsInner(doc)}))}}))}function createKeyRange2(start,end,inclusiveStart,inclusiveEnd,key3,descending){try{return key3?IDBKeyRange.only([0,key3]):descending?IDBKeyRange.bound(end,start,!inclusiveEnd,!inclusiveStart):IDBKeyRange.bound(start,end,!inclusiveStart,!inclusiveEnd)}catch(e3){return{error:e3}}}function handleKeyRangeError(opts,metadata,err3,callback){if("DataError"===err3.name&&0===err3.code){const returnVal={total_rows:metadata.doc_count,offset:opts.skip,rows:[]};opts.update_seq&&(returnVal.update_seq=metadata.seq);return callback(null,returnVal)}callback(createError(IDB_ERROR,err3.name,err3.message))}function allDocs(txn,metadata,opts,callback){function include_doc(row,doc){const docData=doc.revs[doc.rev].data;row.doc=docData;row.doc._id=doc.id;row.doc._rev=doc.rev;if(opts.conflicts){const conflicts=collectConflicts(doc);conflicts.length&&(row.doc._conflicts=conflicts)}if(opts.attachments&&docData._attachments)for(const name in docData._attachments)processing.push(processAttachment(name,doc,row.doc,opts.binary,metadata.idb_attachment_format))}function onTxnComplete(){const returnVal={total_rows:metadata.doc_count,offset:0,rows:results};opts.update_seq&&(returnVal.update_seq=metadata.seq);processing.length?Promise.all(processing).then((function(){callback(null,returnVal)})):callback(null,returnVal)}async function fetchResults(){function fetchNextBatch(kr2){return new Promise((resolve=>{dbIndex.getAll(kr2,100).onsuccess=e3=>{const batch=e3.target.result;for(let i2=0;i2<batch.length;++i2){const doc=batch[i2],row={id:doc.id,key:doc.id,value:{rev:doc.rev}};opts.include_docs&&include_doc(row,doc);results.push(row)}if(batch.length>=100){const lastSeenKey=[0,batch[batch.length-1].id],startKey=descending?kr2.upper:lastSeenKey,endKey=descending?lastSeenKey:kr2.upper;if(startKey[1]!==endKey[1])return resolve(createKeyRange2(startKey,endKey,!!descending,!descending&&inclusiveEnd,key3,descending))}return resolve()}}))}let kr=keyRange;do{kr=await fetchNextBatch(kr)}while(kr);descending&&results.reverse();return txn.txn.commit()}if(txn.error)return callback(txn.error);if(0===opts.limit){const returnVal={total_rows:metadata.doc_count,offset:opts.skip,rows:[]};opts.update_seq&&(returnVal.update_seq=metadata.seq);return callback(null,returnVal)}const results=[],processing=[],key3="key"in opts&&opts.key,keys3="keys"in opts&&opts.keys;let skip=opts.skip||0,limit="number"==typeof opts.limit?opts.limit:void 0;const inclusiveEnd=!1!==opts.inclusive_end,descending="descending"in opts&&opts.descending?"prev":null,start="startkey"in opts?opts.startkey:descending?"￿":"",end="endkey"in opts?opts.endkey:descending?"":"￿",docStore=txn.txn.objectStore(DOC_STORE2);if(keys3){txn.txn.oncomplete=onTxnComplete;return allDocsKeys2(keys3,docStore,(doc=>{if(doc.error)return results.push(doc);const row={id:doc.id,key:doc.id,value:{rev:doc.rev}};if(doc.deleted){row.value.deleted=!0;row.doc=null}else opts.include_docs&&include_doc(row,doc);results.push(row)}))}let keyRange=createKeyRange2([0,start],[0,end],!0,inclusiveEnd,key3,descending);if(keyRange.error)return handleKeyRangeError(opts,metadata,keyRange.error,callback);txn.txn.oncomplete=onTxnComplete;const dbIndex=docStore.index("deleted,id");if(skip||limit){let firstKey,limitKey=limit>0;dbIndex.openKeyCursor(keyRange,descending||"next").onsuccess=e3=>{const cursor=e3.target.result;if(skip){if(!cursor)return txn.txn.commit();cursor.advance(skip);skip=0}else{if(void 0===firstKey){firstKey=cursor&&cursor.key;if(!firstKey)return txn.txn.commit()}if(limit){if(limit>1&&cursor){cursor.advance(limit-1);limit=void 0;return}limit=void 0}limitKey&&(limitKey=cursor&&cursor.key);limitKey||(limitKey=descending?keyRange.lower:keyRange.upper);keyRange=createKeyRange2(firstKey,limitKey,!0,inclusiveEnd,key3,descending);if(keyRange.error){txn.txn.abort();return handleKeyRangeError(opts,metadata,keyRange.error,callback)}fetchResults()}}}else fetchResults()}function changes2(txn,idbChanges2,api,dbOpts,opts){if(txn.error)return opts.complete(txn.error);if(opts.continuous){const id=dbOpts.name+":"+uuid();idbChanges2.addListener(dbOpts.name,id,api,opts);idbChanges2.notify(dbOpts.name);return{cancel:function(){idbChanges2.removeListener(dbOpts.name,id)}}}let limit="limit"in opts?opts.limit:-1;0===limit&&(limit=1);const store=txn.txn.objectStore(DOC_STORE2).index("seq"),filter4=filterChange(opts);let received=0,lastSeq=opts.since||0;const results=[],processing=[];let req;req=opts.descending?store.openCursor(null,"prev"):store.openCursor(IDBKeyRange.lowerBound(opts.since,!0));txn.txn.oncomplete=function onTxnComplete(){Promise.all(processing).then((function(){opts.complete(null,{results,last_seq:lastSeq})}))};req.onsuccess=function onReqSuccess(e3){if(!e3.target.result)return;const cursor=e3.target.result,doc=cursor.value;doc.data=doc.revs[doc.rev].data;doc.data._id=doc.id;doc.data._rev=doc.rev;doc.deleted&&(doc.data._deleted=!0);if(opts.doc_ids&&-1===opts.doc_ids.indexOf(doc.id))return cursor.continue();const change=opts.processChange(doc.data,doc,opts);change.seq=doc.seq;lastSeq=doc.seq;const filtered=filter4(change);if("object"==typeof filtered)return opts.complete(filtered);if(filtered){received++;opts.return_docs&&results.push(change);if(opts.include_docs&&opts.attachments&&doc.data._attachments){const promises=[];for(const name in doc.data._attachments){const p4=processAttachment(name,doc,change.doc,opts.binary,api.blobSupport);promises.push(p4);processing.push(p4)}Promise.all(promises).then((function(){opts.onChange(change)}))}else opts.onChange(change)}received!==limit&&cursor.continue()}}function getRevisionTree(txn,id,callback){if(txn.error)return callback(txn.error);txn.txn.objectStore(DOC_STORE2).get(id).onsuccess=function(e3){e3.target.result?callback(null,e3.target.result.rev_tree):callback(createError(MISSING_DOC))}}function doCompaction(txn,id,revs,callback){if(txn.error)return callback(txn.error);const docStore=txn.txn.objectStore(DOC_STORE2);docStore.get(id).onsuccess=function(e3){const doc=e3.target.result;traverseRevTree(doc.rev_tree,(function(isLeaf,pos,revHash,ctx,opts){const rev3=pos+"-"+revHash;-1!==revs.indexOf(rev3)&&(opts.status="missing")}));const attachments=[];revs.forEach((function(rev3){if(rev3 in doc.revs){if(doc.revs[rev3].data._attachments)for(const k2 in doc.revs[rev3].data._attachments)attachments.push(doc.revs[rev3].data._attachments[k2].digest);delete doc.revs[rev3]}}));attachments.forEach((function(digest){revs.forEach((function(rev3){delete doc.attachments[digest].revs[rev3]}));Object.keys(doc.attachments[digest].revs).length||delete doc.attachments[digest]}));docStore.put(doc)};txn.txn.oncomplete=function(){callback()}}function destroy(dbOpts,openDatabases2,idbChanges2,callback){function doDestroy(){indexedDB.deleteDatabase(dbOpts.name).onsuccess=function(){delete openDatabases2[dbOpts.name];callback(null,{ok:!0})}}idbChanges2.removeAllListeners(dbOpts.name);dbOpts.name in openDatabases2?openDatabases2[dbOpts.name].then((function(res2){res2.idb.close();doDestroy()})):doDestroy()}function externaliseRecord(idbDoc){const doc=idbDoc.revs[idbDoc.rev].data;doc._id=idbDoc.id;doc._rev=idbDoc.rev;idbDoc.deleted&&(doc._deleted=!0);return doc}function generateKeyRange(opts){function defined(obj,k2){return void 0!==obj[k2]}function convert(key3,exact){return[0].concat(key3).map((function(k2){if(null===k2&&exact)return IDB_NULL;if(!0===k2)return IDB_TRUE;if(!1===k2)return IDB_FALSE;if(!exact){if(k2===COUCH_COLLATE_LO)return IDB_COLLATE_LO;if(Object.prototype.hasOwnProperty.call(k2,COUCH_COLLATE_HI))return IDB_COLLATE_HI}return k2}))}defined(opts,"inclusive_end")||(opts.inclusive_end=!0);defined(opts,"inclusive_start")||(opts.inclusive_start=!0);if(opts.descending){const realEndkey=opts.startkey,realInclusiveEnd=opts.inclusive_start;opts.startkey=opts.endkey;opts.endkey=realEndkey;opts.inclusive_start=opts.inclusive_end;opts.inclusive_end=realInclusiveEnd}try{return defined(opts,"key")?IDBKeyRange.only(convert(opts.key,!0)):defined(opts,"startkey")&&!defined(opts,"endkey")?IDBKeyRange.bound(convert(opts.startkey),[1],!opts.inclusive_start,!0):!defined(opts,"startkey")&&defined(opts,"endkey")?IDBKeyRange.upperBound(convert(opts.endkey),!opts.inclusive_end):defined(opts,"startkey")&&defined(opts,"endkey")?IDBKeyRange.bound(convert(opts.startkey),convert(opts.endkey),!opts.inclusive_start,!opts.inclusive_end):IDBKeyRange.only([0])}catch(err3){console.error("Could not generate keyRange",err3,opts);throw Error("Could not generate key range with "+JSON.stringify(opts))}}function getIndexHandle(pdb,fields,reject){const indexName=naturalIndexName(fields);return new Promise((function(resolve){pdb._openTransactionSafely([DOC_STORE2],"readonly",(function(err3,txn){if(err3)return idbError2(reject)(err3);txn.onabort=idbError2(reject);txn.ontimeout=idbError2(reject);-1===Array.from(txn.objectStore(DOC_STORE2).indexNames).indexOf(indexName)?pdb._freshen().then((function(){return getIndexHandle(pdb,fields,reject)})).then(resolve):resolve(txn.objectStore(DOC_STORE2).index(indexName))}))}))}function query(idb,signature,opts,fallback2){const pdb=this,parts=signature.split("/");return new Promise((function(resolve,reject){pdb.get("_design/"+parts[0]).then((function(ddoc){if(isPartialFilterView(ddoc,parts[1]))return fallback2(signature,opts).then(resolve,reject);const fields=rawIndexFields(ddoc,parts[1]);if(!fields)throw new Error("ddoc "+ddoc._id+" with view "+parts[1]+" does not have map.options.def.fields defined.");let skip=opts.skip,limit=Number.isInteger(opts.limit)&&opts.limit;return getIndexHandle(pdb,fields,reject).then((function(indexHandle){const keyRange=generateKeyRange(opts),req=indexHandle.openCursor(keyRange,opts.descending?"prev":"next"),rows=[];req.onerror=idbError2(reject);req.onsuccess=function(e3){const cursor=e3.target.result;if(!cursor||0===limit)return resolve({rows});if(skip){cursor.advance(skip);skip=!1}else{limit&&(limit-=1);rows.push({doc:externaliseRecord(cursor.value)});cursor.continue()}}}))})).catch(reject)}))}function viewCleanup(idb,fallback2){return fallback2()}function purgeAttachments(doc,revs){if(!doc.attachments)return{};for(let key3 in doc.attachments){const attachment=doc.attachments[key3];for(let rev3 of revs)attachment.revs[rev3]&&delete attachment.revs[rev3];0===Object.keys(attachment.revs).length&&delete doc.attachments[key3]}return doc.attachments}function purge(txn,docId,revs,callback){if(txn.error)return callback(txn.error);const docStore=txn.txn.objectStore(DOC_STORE2),deletedRevs=[];let documentWasRemovedCompletely=!1;docStore.get(docId).onsuccess=e3=>{const doc=e3.target.result;for(const rev3 of revs){doc.rev_tree=removeLeafFromRevTree(doc.rev_tree,rev3);delete doc.revs[rev3];deletedRevs.push(rev3)}if(0!==doc.rev_tree.length){doc.rev=winningRev(doc);doc.data=doc.revs[doc.rev].data;doc.attachments=purgeAttachments(doc,revs);docStore.put(doc)}else{docStore.delete(doc.id);documentWasRemovedCompletely=!0}};txn.txn.oncomplete=function(){callback(null,{ok:!0,deletedRevs,documentWasRemovedCompletely})}}function IndexeddbPouch(dbOpts,callback){dbOpts.view_adapter&&console.log("Please note that the indexeddb adapter manages _find indexes itself, therefore it is not using your specified view_adapter");const api=this;let metadata={};const $=function(fun){return function(){const args=Array.prototype.slice.call(arguments);setup(openDatabases,api,dbOpts).then((function(res2){metadata=res2.metadata;args.unshift(res2.idb);fun.apply(api,args)})).catch((function(err3){const last=args.pop();"function"==typeof last?last(err3):console.error(err3)}))}},$p=function(fun){return function(){const args=Array.prototype.slice.call(arguments);return setup(openDatabases,api,dbOpts).then((function(res2){metadata=res2.metadata;args.unshift(res2.idb);return fun.apply(api,args)}))}},$t2=function(fun,stores,mode){mode=mode||"readonly";return function(){const args=Array.prototype.slice.call(arguments),txn={};setup(openDatabases,api,dbOpts).then((function(res2){metadata=res2.metadata;txn.txn=res2.idb.transaction(stores,mode)})).catch((function(err3){console.error("Failed to establish transaction safely");console.error(err3);txn.error=err3})).then((function(){args.unshift(txn);fun.apply(api,args)}))}};api._openTransactionSafely=function(stores,mode,callback2){$t2((function(txn,callback3){callback3(txn.error,txn.txn)}),stores,mode)(callback2)};api._remote=!1;api.type=function(){return ADAPTER_NAME};api._id=$((function(_,cb2){cb2(null,metadata.db_uuid)}));api._info=$((function(_,cb2){return info2(metadata,cb2)}));api._get=$t2(get3,[DOC_STORE2]);api._getLocal=$t2((function(txn,id,callback2){return getLocal(txn,id,api,callback2)}),[META_LOCAL_STORE]);api._bulkDocs=$((function(_,req,opts,callback2){bulkDocs(api,req,opts,metadata,dbOpts,idbChanges,callback2)}));api._allDocs=$t2((function(txn,opts,cb2){allDocs(txn,metadata,opts,cb2)}),[DOC_STORE2]);api._getAttachment=getAttachment;api._changes=$t2((function(txn,opts){changes2(txn,idbChanges,api,dbOpts,opts)}),[DOC_STORE2]);api._getRevisionTree=$t2(getRevisionTree,[DOC_STORE2]);api._doCompaction=$t2(doCompaction,[DOC_STORE2],"readwrite");api._customFindAbstractMapper={query:$p(query),viewCleanup:$p(viewCleanup)};api._destroy=function(opts,callback2){return destroy(dbOpts,openDatabases,idbChanges,callback2)};api._close=$((function(db,cb2){delete openDatabases[dbOpts.name];db.close();cb2()}));api._freshen=function(){return new Promise((function(resolve){api._close((function(){$(resolve)()}))}))};api._purge=$t2(purge,[DOC_STORE2],"readwrite");setTimeout((function(){callback(null,api)}))}function pool(promiseFactories,limit){return new Promise((function(resolve,reject){function runNext(){running2++;promiseFactories[current++]().then(onSuccess,onError)}function doNext(){++done===len?err3?reject(err3):resolve():runNextBatch()}function onSuccess(){running2--;doNext()}function onError(thisErr){running2--;err3=err3||thisErr;doNext()}function runNextBatch(){for(;running2<limit&&current<len;)runNext()}var err3,running2=0,current=0,done=0,len=promiseFactories.length;runNextBatch()}))}function readAttachmentsAsBlobOrBuffer(row){const doc=row.doc||row.ok,atts=doc&&doc._attachments;atts&&Object.keys(atts).forEach((function(filename){const att=atts[filename];att.data=b64ToBluffer(att.data,att.content_type)}))}function encodeDocId(id){return/^_design/.test(id)?"_design/"+encodeURIComponent(id.slice(8)):id.startsWith("_local/")?"_local/"+encodeURIComponent(id.slice(7)):encodeURIComponent(id)}function preprocessAttachments2(doc){return doc._attachments&&Object.keys(doc._attachments)?Promise.all(Object.keys(doc._attachments).map((function(key3){const attachment=doc._attachments[key3];if(attachment.data&&"string"!=typeof attachment.data)return new Promise((function(resolve){blobToBase64(attachment.data,resolve)})).then((function(b64){attachment.data=b64}))}))):Promise.resolve()}function hasUrlPrefix(opts){if(!opts.prefix)return!1;const protocol=parseUri(opts.prefix).protocol;return"http"===protocol||"https"===protocol}function getHost(name,opts){if(hasUrlPrefix(opts)){const dbName=opts.name.substr(opts.prefix.length);name=opts.prefix.replace(/\/?$/,"/")+encodeURIComponent(dbName)}const uri=parseUri(name);(uri.user||uri.password)&&(uri.auth={username:uri.user,password:uri.password});const parts=uri.path.replace(/(^\/|\/$)/g,"").split("/");uri.db=parts.pop();-1===uri.db.indexOf("%")&&(uri.db=encodeURIComponent(uri.db));uri.path=parts.join("/");return uri}function genDBUrl(opts,path2){return genUrl(opts,opts.db+"/"+path2)}function genUrl(opts,path2){const pathDel=opts.path?"/":"";return opts.protocol+"://"+opts.host+(opts.port?":"+opts.port:"")+"/"+opts.path+pathDel+path2}function paramsToStr(params){const paramKeys=Object.keys(params);return 0===paramKeys.length?"":"?"+paramKeys.map((key3=>key3+"="+encodeURIComponent(params[key3]))).join("&")}function shouldCacheBust(opts){const ua="undefined"!=typeof navigator&&navigator.userAgent?navigator.userAgent.toLowerCase():"",isIE=-1!==ua.indexOf("msie"),isTrident=-1!==ua.indexOf("trident"),isEdge=-1!==ua.indexOf("edge"),isGET=!("method"in opts)||"GET"===opts.method;return(isIE||isTrident||isEdge)&&isGET}function HttpPouch(opts,callback){function adapterFun$$1(name,fun){return adapterFun(name,(function(...args){setup2().then((function(){return fun.apply(this,args)})).catch((function(e3){args.pop()(e3)}))})).bind(api)}async function fetchJSON(url,options){const result={};(options=options||{}).headers=options.headers||new h2;options.headers.get("Content-Type")||options.headers.set("Content-Type","application/json");options.headers.get("Accept")||options.headers.set("Accept","application/json");const response=await ourFetch(url,options);result.ok=response.ok;result.status=response.status;const json=await response.json();result.data=json;if(!result.ok){result.data.status=result.status;throw generateErrorFromResponse(result.data)}Array.isArray(result.data)&&(result.data=result.data.map((function(v2){return v2.error||v2.missing?generateErrorFromResponse(v2):v2})));return result}async function setup2(){if(opts.skip_setup)return Promise.resolve();if(setupPromise)return setupPromise;setupPromise=fetchJSON(dbUrl).catch((function(err3){if(err3&&err3.status&&404===err3.status){explainError(404,"PouchDB is just detecting if the remote exists.");return fetchJSON(dbUrl,{method:"PUT"})}return Promise.reject(err3)})).catch((function(err3){return!(!err3||!err3.status||412!==err3.status)||Promise.reject(err3)}));setupPromise.catch((function(){setupPromise=null}));return setupPromise}function encodeAttachmentId(attachmentId){return attachmentId.split("/").map(encodeURIComponent).join("/")}const api=this,host=getHost(opts.name,opts),dbUrl=genDBUrl(host,"");opts=clone2(opts);const ourFetch=async function(url,options){(options=options||{}).headers=options.headers||new h2;options.credentials="include";if(opts.auth||host.auth){const nAuth=opts.auth||host.auth,str=nAuth.username+":"+nAuth.password,token=thisBtoa(unescape(encodeURIComponent(str)));options.headers.set("Authorization","Basic "+token)}const headers=opts.headers||{};Object.keys(headers).forEach((function(key3){options.headers.append(key3,headers[key3])}));shouldCacheBust(options)&&(url+=(-1===url.indexOf("?")?"?":"&")+"_nonce="+Date.now());const fetchFun=opts.fetch||f3;return await fetchFun(url,options)};let setupPromise;nextTick((function(){callback(null,api)}));api._remote=!0;api.type=function(){return"http"};api.id=adapterFun$$1("id",(async function(callback2){let result;try{const response=await ourFetch(genUrl(host,""));result=await response.json()}catch(err3){result={}}callback2(null,result&&result.uuid?result.uuid+host.db:genDBUrl(host,""))}));api.compact=adapterFun$$1("compact",(async function(opts2,callback2){if("function"==typeof opts2){callback2=opts2;opts2={}}opts2=clone2(opts2);await fetchJSON(genDBUrl(host,"_compact"),{method:"POST"});(function ping(){api.info((function(err3,res2){res2&&!res2.compact_running?callback2(null,{ok:!0}):setTimeout(ping,opts2.interval||200)}))})()}));api.bulkGet=adapterFun("bulkGet",(function(opts2,callback2){async function doBulkGet(cb2){const params={};opts2.revs&&(params.revs=!0);opts2.attachments&&(params.attachments=!0);opts2.latest&&(params.latest=!0);try{const result=await fetchJSON(genDBUrl(host,"_bulk_get"+paramsToStr(params)),{method:"POST",body:JSON.stringify({docs:opts2.docs})});opts2.attachments&&opts2.binary&&result.data.results.forEach((function(res2){res2.docs.forEach(readAttachmentsAsBlobOrBuffer)}));cb2(null,result.data)}catch(error){cb2(error)}}function doBulkGetShim(){function onResult(batchNum){return function(err3,res2){results[batchNum]=res2.results;++numDone===numBatches&&callback2(null,{results:results.flat()})}}const batchSize=MAX_SIMULTANEOUS_REVS,numBatches=Math.ceil(opts2.docs.length/batchSize);let numDone=0;const results=new Array(numBatches);for(let i2=0;i2<numBatches;i2++){const subOpts=pick(opts2,["revs","attachments","binary","latest"]);subOpts.docs=opts2.docs.slice(i2*batchSize,Math.min(opts2.docs.length,(i2+1)*batchSize));bulkGet(self3,subOpts,onResult(i2))}}const self3=this,dbUrl2=genUrl(host,""),supportsBulkGet=supportsBulkGetMap[dbUrl2];"boolean"!=typeof supportsBulkGet?doBulkGet((function(err3,res2){if(err3){supportsBulkGetMap[dbUrl2]=!1;explainError(err3.status,"PouchDB is just detecting if the remote supports the _bulk_get API.");doBulkGetShim()}else{supportsBulkGetMap[dbUrl2]=!0;callback2(null,res2)}})):supportsBulkGet?doBulkGet(callback2):doBulkGetShim()}));api._info=async function(callback2){try{await setup2();const response=await ourFetch(genDBUrl(host,"")),info3=await response.json();info3.host=genDBUrl(host,"");callback2(null,info3)}catch(err3){callback2(err3)}};api.fetch=async function(path2,options){await setup2();const url="/"===path2.substring(0,1)?genUrl(host,path2.substring(1)):genDBUrl(host,path2);return ourFetch(url,options)};api.get=adapterFun$$1("get",(async function(id,opts2,callback2){function fetchAttachments(doc){async function fetchData(filename){const att=atts[filename],path2=encodeDocId(doc._id)+"/"+encodeAttachmentId(filename)+"?rev="+doc._rev,response=await ourFetch(genDBUrl(host,path2));let blob,data;blob="buffer"in response?await response.buffer():await response.blob();if(opts2.binary){const typeFieldDescriptor=Object.getOwnPropertyDescriptor(blob.__proto__,"type");typeFieldDescriptor&&!typeFieldDescriptor.set||(blob.type=att.content_type);data=blob}else data=await new Promise((function(resolve){blobToBase64(blob,resolve)}));delete att.stub;delete att.length;att.data=data}const atts=doc._attachments,filenames=atts&&Object.keys(atts);if(atts&&filenames.length)return pool(filenames.map((function(filename){return function(){return fetchData(filename)}})),5)}if("function"==typeof opts2){callback2=opts2;opts2={}}const params={};(opts2=clone2(opts2)).revs&&(params.revs=!0);opts2.revs_info&&(params.revs_info=!0);opts2.latest&&(params.latest=!0);if(opts2.open_revs){"all"!==opts2.open_revs&&(opts2.open_revs=JSON.stringify(opts2.open_revs));params.open_revs=opts2.open_revs}opts2.rev&&(params.rev=opts2.rev);opts2.conflicts&&(params.conflicts=opts2.conflicts);opts2.update_seq&&(params.update_seq=opts2.update_seq);id=encodeDocId(id);const url=genDBUrl(host,id+paramsToStr(params));try{const res2=await fetchJSON(url);opts2.attachments&&await function fetchAllAttachments(docOrDocs){return Array.isArray(docOrDocs)?Promise.all(docOrDocs.map((function(doc){if(doc.ok)return fetchAttachments(doc.ok)}))):fetchAttachments(docOrDocs)}(res2.data);callback2(null,res2.data)}catch(error){error.docId=id;callback2(error)}}));api.remove=adapterFun$$1("remove",(async function(docOrId,optsOrRev,opts2,cb2){let doc;if("string"==typeof optsOrRev){doc={_id:docOrId,_rev:optsOrRev};if("function"==typeof opts2){cb2=opts2;opts2={}}}else{doc=docOrId;if("function"==typeof optsOrRev){cb2=optsOrRev;opts2={}}else{cb2=opts2;opts2=optsOrRev}}const rev3=doc._rev||opts2.rev,url=genDBUrl(host,encodeDocId(doc._id))+"?rev="+rev3;try{cb2(null,(await fetchJSON(url,{method:"DELETE"})).data)}catch(error){cb2(error)}}));api.getAttachment=adapterFun$$1("getAttachment",(async function(docId,attachmentId,opts2,callback2){if("function"==typeof opts2){callback2=opts2;opts2={}}const params=opts2.rev?"?rev="+opts2.rev:"",url=genDBUrl(host,encodeDocId(docId))+"/"+encodeAttachmentId(attachmentId)+params;let contentType;try{const response=await ourFetch(url,{method:"GET"});if(!response.ok)throw response;contentType=response.headers.get("content-type");let blob;blob="undefined"==typeof process||process.browser||"function"!=typeof response.buffer?await response.blob():await response.buffer();if("undefined"!=typeof process&&!process.browser){const typeFieldDescriptor=Object.getOwnPropertyDescriptor(blob.__proto__,"type");typeFieldDescriptor&&!typeFieldDescriptor.set||(blob.type=contentType)}callback2(null,blob)}catch(err3){callback2(err3)}}));api.removeAttachment=adapterFun$$1("removeAttachment",(async function(docId,attachmentId,rev3,callback2){const url=genDBUrl(host,encodeDocId(docId)+"/"+encodeAttachmentId(attachmentId))+"?rev="+rev3;try{callback2(null,(await fetchJSON(url,{method:"DELETE"})).data)}catch(error){callback2(error)}}));api.putAttachment=adapterFun$$1("putAttachment",(async function(docId,attachmentId,rev3,blob,type,callback2){if("function"==typeof type){callback2=type;type=blob;blob=rev3;rev3=null}const id=encodeDocId(docId)+"/"+encodeAttachmentId(attachmentId);let url=genDBUrl(host,id);rev3&&(url+="?rev="+rev3);if("string"==typeof blob){let binary;try{binary=thisAtob(blob)}catch(err3){return callback2(createError(BAD_ARG,"Attachment is not a valid base64 string"))}blob=binary?binStringToBluffer(binary,type):""}try{callback2(null,(await fetchJSON(url,{headers:new h2({"Content-Type":type}),method:"PUT",body:blob})).data)}catch(error){callback2(error)}}));api._bulkDocs=async function(req,opts2,callback2){req.new_edits=opts2.new_edits;try{await setup2();await Promise.all(req.docs.map(preprocessAttachments2));callback2(null,(await fetchJSON(genDBUrl(host,"_bulk_docs"),{method:"POST",body:JSON.stringify(req)})).data)}catch(error){callback2(error)}};api._put=async function(doc,opts2,callback2){try{await setup2();await preprocessAttachments2(doc);callback2(null,(await fetchJSON(genDBUrl(host,encodeDocId(doc._id)),{method:"PUT",body:JSON.stringify(doc)})).data)}catch(error){error.docId=doc&&doc._id;callback2(error)}};api.allDocs=adapterFun$$1("allDocs",(async function(opts2,callback2){if("function"==typeof opts2){callback2=opts2;opts2={}}const params={};let body,method="GET";(opts2=clone2(opts2)).conflicts&&(params.conflicts=!0);opts2.update_seq&&(params.update_seq=!0);opts2.descending&&(params.descending=!0);opts2.include_docs&&(params.include_docs=!0);opts2.attachments&&(params.attachments=!0);opts2.key&&(params.key=JSON.stringify(opts2.key));opts2.start_key&&(opts2.startkey=opts2.start_key);opts2.startkey&&(params.startkey=JSON.stringify(opts2.startkey));opts2.end_key&&(opts2.endkey=opts2.end_key);opts2.endkey&&(params.endkey=JSON.stringify(opts2.endkey));void 0!==opts2.inclusive_end&&(params.inclusive_end=!!opts2.inclusive_end);void 0!==opts2.limit&&(params.limit=opts2.limit);void 0!==opts2.skip&&(params.skip=opts2.skip);const paramStr=paramsToStr(params);if(void 0!==opts2.keys){method="POST";body={keys:opts2.keys}}try{const result=await fetchJSON(genDBUrl(host,"_all_docs"+paramStr),{method,body:JSON.stringify(body)});opts2.include_docs&&opts2.attachments&&opts2.binary&&result.data.rows.forEach(readAttachmentsAsBlobOrBuffer);callback2(null,result.data)}catch(error){callback2(error)}}));api._changes=function(opts2){const batchSize="batch_size"in opts2?opts2.batch_size:CHANGES_BATCH_SIZE;(opts2=clone2(opts2)).continuous&&!("heartbeat"in opts2)&&(opts2.heartbeat=DEFAULT_HEARTBEAT);let requestTimeout2="timeout"in opts2?opts2.timeout:3e4;"timeout"in opts2&&opts2.timeout&&requestTimeout2-opts2.timeout<CHANGES_TIMEOUT_BUFFER&&(requestTimeout2=opts2.timeout+CHANGES_TIMEOUT_BUFFER);"heartbeat"in opts2&&opts2.heartbeat&&requestTimeout2-opts2.heartbeat<CHANGES_TIMEOUT_BUFFER&&(requestTimeout2=opts2.heartbeat+CHANGES_TIMEOUT_BUFFER);const params={};"timeout"in opts2&&opts2.timeout&&(params.timeout=opts2.timeout);const limit=void 0!==opts2.limit&&opts2.limit;let leftToFetch=limit;opts2.style&&(params.style=opts2.style);(opts2.include_docs||opts2.filter&&"function"==typeof opts2.filter)&&(params.include_docs=!0);opts2.attachments&&(params.attachments=!0);opts2.continuous&&(params.feed="longpoll");opts2.seq_interval&&(params.seq_interval=opts2.seq_interval);opts2.conflicts&&(params.conflicts=!0);opts2.descending&&(params.descending=!0);opts2.update_seq&&(params.update_seq=!0);"heartbeat"in opts2&&opts2.heartbeat&&(params.heartbeat=opts2.heartbeat);opts2.filter&&"string"==typeof opts2.filter&&(params.filter=opts2.filter);if(opts2.view&&"string"==typeof opts2.view){params.filter="_view";params.view=opts2.view}if(opts2.query_params&&"object"==typeof opts2.query_params)for(const param_name in opts2.query_params)Object.prototype.hasOwnProperty.call(opts2.query_params,param_name)&&(params[param_name]=opts2.query_params[param_name]);let body,method="GET";if(opts2.doc_ids){params.filter="_doc_ids";method="POST";body={doc_ids:opts2.doc_ids}}else if(opts2.selector){params.filter="_selector";method="POST";body={selector:opts2.selector}}const controller=new AbortController;let lastFetchedSeq;const fetchData=async function(since,callback2){if(opts2.aborted)return;params.since=since;"object"==typeof params.since&&(params.since=JSON.stringify(params.since));opts2.descending?limit&&(params.limit=leftToFetch):params.limit=!limit||leftToFetch>batchSize?batchSize:leftToFetch;const url=genDBUrl(host,"_changes"+paramsToStr(params)),fetchOpts={signal:controller.signal,method,body:JSON.stringify(body)};lastFetchedSeq=since;if(!opts2.aborted)try{await setup2();callback2(null,(await fetchJSON(url,fetchOpts)).data)}catch(error){callback2(error)}},results={results:[]},fetched=function(err3,res2){if(opts2.aborted)return;let raw_results_length=0;if(res2&&res2.results){raw_results_length=res2.results.length;results.last_seq=res2.last_seq;let pending3=null,lastSeq=null;"number"==typeof res2.pending&&(pending3=res2.pending);"string"!=typeof results.last_seq&&"number"!=typeof results.last_seq||(lastSeq=results.last_seq);({}).query=opts2.query_params;res2.results=res2.results.filter((function(c3){leftToFetch--;const ret=filterChange(opts2)(c3);if(ret){opts2.include_docs&&opts2.attachments&&opts2.binary&&readAttachmentsAsBlobOrBuffer(c3);opts2.return_docs&&results.results.push(c3);opts2.onChange(c3,pending3,lastSeq)}return ret}))}else if(err3){opts2.aborted=!0;opts2.complete(err3);return}res2&&res2.last_seq&&(lastFetchedSeq=res2.last_seq);const finished=limit&&leftToFetch<=0||res2&&raw_results_length<batchSize||opts2.descending;(!opts2.continuous||limit&&leftToFetch<=0)&&finished?opts2.complete(null,results):nextTick((function(){fetchData(lastFetchedSeq,fetched)}))};fetchData(opts2.since||0,fetched);return{cancel:function(){opts2.aborted=!0;controller.abort()}}};api.revsDiff=adapterFun$$1("revsDiff",(async function(req,opts2,callback2){if("function"==typeof opts2){callback2=opts2;opts2={}}try{callback2(null,(await fetchJSON(genDBUrl(host,"_revs_diff"),{method:"POST",body:JSON.stringify(req)})).data)}catch(error){callback2(error)}}));api._close=function(callback2){callback2()};api._destroy=async function(options,callback2){try{callback2(null,await fetchJSON(genDBUrl(host,""),{method:"DELETE"}))}catch(error){404===error.status?callback2(null,{ok:!0}):callback2(error)}}}function promisedCallback(promise,callback){callback&&promise.then((function(res2){nextTick((function(){callback(null,res2)}))}),(function(reason){nextTick((function(){callback(reason)}))}));return promise}function callbackify(fun){return function(...args){var cb2=args.pop(),promise=fun.apply(this,args);"function"==typeof cb2&&promisedCallback(promise,cb2);return promise}}function fin(promise,finalPromiseFactory){return promise.then((function(res2){return finalPromiseFactory().then((function(){return res2}))}),(function(reason){return finalPromiseFactory().then((function(){throw reason}))}))}function sequentialize(queue2,promiseFactory){return function(){var args=arguments,that=this;return queue2.add((function(){return promiseFactory.apply(that,args)}))}}function uniq(arr){var theSet=new Set(arr),result=new Array(theSet.size),index6=-1;theSet.forEach((function(value){result[++index6]=value}));return result}function mapToKeysArray(map4){var result=new Array(map4.size),index6=-1;map4.forEach((function(value,key3){result[++index6]=key3}));return result}function stringify3(input){if(!input)return"undefined";switch(typeof input){case"function":return input.toString();case"string":return input.toString();default:return JSON.stringify(input)}}function createViewSignature(mapFun,reduceFun){return stringify3(mapFun)+stringify3(reduceFun)+"undefined"}async function createView(sourceDB,viewName,mapFun,reduceFun,temporary,localDocName2){const viewSignature=createViewSignature(mapFun,reduceFun);let cachedViews;if(!temporary){cachedViews=sourceDB._cachedViews=sourceDB._cachedViews||{};if(cachedViews[viewSignature])return cachedViews[viewSignature]}const promiseForView=sourceDB.info().then((async function(info3){const depDbName=info3.db_name+"-mrview-"+(temporary?"temp":stringMd5(viewSignature));await upsert2(sourceDB,"_local/"+localDocName2,(function diffFunction(doc){doc.views=doc.views||{};let fullViewName=viewName;-1===fullViewName.indexOf("/")&&(fullViewName=viewName+"/"+viewName);const depDbs=doc.views[fullViewName]=doc.views[fullViewName]||{};if(!depDbs[depDbName]){depDbs[depDbName]=!0;return doc}}));const db=(await sourceDB.registerDependentDatabase(depDbName)).db;db.auto_compaction=!0;const view={name:depDbName,db,sourceDB,adapter:sourceDB.adapter,mapFun,reduceFun};let lastSeqDoc;try{lastSeqDoc=await view.db.get("_local/lastSeq")}catch(err3){if(404!==err3.status)throw err3}view.seq=lastSeqDoc?lastSeqDoc.seq:0;cachedViews&&view.db.once("destroyed",(function(){delete cachedViews[viewSignature]}));return view}));cachedViews&&(cachedViews[viewSignature]=promiseForView);return promiseForView}function parseViewName(name){return-1===name.indexOf("/")?[name,name]:name.split("/")}function isGenOne(changes3){return 1===changes3.length&&/^1-/.test(changes3[0].rev)}function emitError(db,e3,data){try{db.emit("error",e3)}catch(err3){guardedConsole("error","The user's map/reduce function threw an uncaught error.\nYou can debug this error by doing:\nmyDatabase.on('error', function (err) { debugger; });\nPlease double-check your map/reduce function.");guardedConsole("error",e3,data)}}function createBuiltInError(name){return new BuiltInError("builtin "+name+" function requires map values to be numbers or number arrays")}function sum(values){var i2,len,num,j2,jLen,jNum,result=0;for(i2=0,len=values.length;i2<len;i2++)if("number"!=typeof(num=values[i2])){if(!Array.isArray(num))throw createBuiltInError("_sum");result="number"==typeof result?[result]:result;for(j2=0,jLen=num.length;j2<jLen;j2++){if("number"!=typeof(jNum=num[j2]))throw createBuiltInError("_sum");void 0===result[j2]?result.push(jNum):result[j2]+=jNum}}else"number"==typeof result?result+=num:result[0]+=num;return result}function evalFunctionWithEval(func,emit2){return scopeEval("return ("+func.replace(/;\s*$/,"")+");",{emit:emit2,sum,log,isArray,toJSON})}function getBuiltIn(reduceFunString){if(/^_sum/.test(reduceFunString))return builtInReduce__sum;if(/^_count/.test(reduceFunString))return builtInReduce__count;if(/^_stats/.test(reduceFunString))return builtInReduce__stats;if(/^_/.test(reduceFunString))throw new Error(reduceFunString+" is not a supported reduce function.")}function updateCheckpoint(db,id,checkpoint,session,returnValue){return db.get(id).catch((function(err3){if(404===err3.status){"http"!==db.adapter&&"https"!==db.adapter||explainError(404,"PouchDB is just checking if a remote checkpoint exists.");return{session_id:session,_id:id,history:[],replicator:REPLICATOR,version:CHECKPOINT_VERSION}}throw err3})).then((function(doc){if(!returnValue.cancelled&&doc.last_seq!==checkpoint){doc.history=(doc.history||[]).filter((function(item){return item.session_id!==session}));doc.history.unshift({last_seq:checkpoint,session_id:session});doc.history=doc.history.slice(0,CHECKPOINT_HISTORY_SIZE);doc.version=CHECKPOINT_VERSION;doc.replicator=REPLICATOR;doc.session_id=session;doc.last_seq=checkpoint;return db.put(doc).catch((function(err3){if(409===err3.status)return updateCheckpoint(db,id,checkpoint,session,returnValue);throw err3}))}}))}function compareReplicationLogs(srcDoc,tgtDoc){return srcDoc.session_id===tgtDoc.session_id?{last_seq:srcDoc.last_seq,history:srcDoc.history}:compareReplicationHistory(srcDoc.history,tgtDoc.history)}function compareReplicationHistory(sourceHistory,targetHistory){var S2=sourceHistory[0],sourceRest=sourceHistory.slice(1),T2=targetHistory[0],targetRest=targetHistory.slice(1);return S2&&0!==targetHistory.length?hasSessionId(S2.session_id,targetHistory)?{last_seq:S2.last_seq,history:sourceHistory}:hasSessionId(T2.session_id,sourceRest)?{last_seq:T2.last_seq,history:targetRest}:compareReplicationHistory(sourceRest,targetRest):{last_seq:LOWEST_SEQ,history:[]}}function hasSessionId(sessionId,history){var props=history[0],rest=history.slice(1);return!(!sessionId||0===history.length)&&(sessionId===props.session_id||hasSessionId(sessionId,rest))}function isForbiddenError(err3){return"number"==typeof err3.status&&4===Math.floor(err3.status/100)}function sortObjectPropertiesByKey(queryParams){return Object.keys(queryParams).sort(collate).reduce((function(result,key3){result[key3]=queryParams[key3];return result}),{})}function fileHasChanged(localDoc,remoteDoc,filename){return!localDoc._attachments||!localDoc._attachments[filename]||localDoc._attachments[filename].digest!==remoteDoc._attachments[filename].digest}function getDocAttachments(db,doc){var filenames=Object.keys(doc._attachments);return Promise.all(filenames.map((function(filename){return db.getAttachment(doc._id,filename,{rev:doc._rev})})))}function getDocAttachmentsFromTargetOrSource(target,src,doc){var doCheckForLocalAttachments=isRemote(src)&&!isRemote(target),filenames=Object.keys(doc._attachments);return doCheckForLocalAttachments?target.get(doc._id).then((function(localDoc){return Promise.all(filenames.map((function(filename){return fileHasChanged(localDoc,doc,filename)?src.getAttachment(doc._id,filename):target.getAttachment(localDoc._id,filename)})))})).catch((function(error){if(404!==error.status)throw error;return getDocAttachments(src,doc)})):getDocAttachments(src,doc)}function createBulkGetOpts(diffs){var requests=[];Object.keys(diffs).forEach((function(id){diffs[id].missing.forEach((function(missingRev){requests.push({id,rev:missingRev})}))}));return{docs:requests,revs:!0,latest:!0}}function getDocs(src,target,diffs,state2){diffs=clone2(diffs);var resultDocs=[],ok=!0;return Promise.resolve().then((function getAllDocs(){var bulkGetOpts=createBulkGetOpts(diffs);if(bulkGetOpts.docs.length)return src.bulkGet(bulkGetOpts).then((function(bulkGetResponse){if(state2.cancelled)throw new Error("cancelled");return Promise.all(bulkGetResponse.results.map((function(bulkGetInfo){return Promise.all(bulkGetInfo.docs.map((function(doc){var remoteDoc=doc.ok;doc.error&&(ok=!1);return remoteDoc&&remoteDoc._attachments?getDocAttachmentsFromTargetOrSource(target,src,remoteDoc).then((attachments=>{var filenames=Object.keys(remoteDoc._attachments);attachments.forEach((function(attachment,i2){var att=remoteDoc._attachments[filenames[i2]];delete att.stub;delete att.length;att.data=attachment}));return remoteDoc})):remoteDoc})))}))).then((function(results){resultDocs=resultDocs.concat(results.flat().filter(Boolean))}))}))})).then((function returnResult(){return{ok,docs:resultDocs}}))}function backOff(opts,returnValue,error,callback){var backOffSet,removeBackOffSetter;if(!1!==opts.retry){"function"!=typeof opts.back_off_function&&(opts.back_off_function=defaultBackOff);returnValue.emit("requestError",error);if("active"===returnValue.state||"pending"===returnValue.state){returnValue.emit("paused",error);returnValue.state="stopped";backOffSet=function backoffTimeSet(){opts.current_back_off=STARTING_BACK_OFF};removeBackOffSetter=function removeBackOffTimeSet(){returnValue.removeListener("active",backOffSet)};returnValue.once("paused",removeBackOffSetter);returnValue.once("active",backOffSet)}opts.current_back_off=opts.current_back_off||STARTING_BACK_OFF;opts.current_back_off=opts.back_off_function(opts.current_back_off);setTimeout(callback,opts.current_back_off)}else{returnValue.emit("error",error);returnValue.removeAllListeners()}}function replicate(src,target,opts,returnValue,result){function initCheckpointer(){return checkpointer?Promise.resolve():index_es_default7(src,target,opts).then((function(res2){repId=res2;var checkpointOpts;checkpointOpts=!1===opts.checkpoint?{writeSourceCheckpoint:!1,writeTargetCheckpoint:!1}:"source"===opts.checkpoint?{writeSourceCheckpoint:!0,writeTargetCheckpoint:!1}:"target"===opts.checkpoint?{writeSourceCheckpoint:!1,writeTargetCheckpoint:!0}:{writeSourceCheckpoint:!0,writeTargetCheckpoint:!0};checkpointer=new index_es_default6(src,target,repId,returnValue,checkpointOpts)}))}function writeDocs(){var docs,bulkOpts;changedDocs=[];if(0!==currentBatch.docs.length){docs=currentBatch.docs;bulkOpts={timeout:opts.timeout};return target.bulkDocs({docs,new_edits:!1},bulkOpts).then((function(res2){var errorsById,errorsNo;if(returnValue.cancelled){completeReplication();throw new Error("cancelled")}errorsById=Object.create(null);res2.forEach((function(res3){res3.error&&(errorsById[res3.id]=res3)}));errorsNo=Object.keys(errorsById).length;result.doc_write_failures+=errorsNo;result.docs_written+=docs.length-errorsNo;docs.forEach((function(doc){var errorName,error=errorsById[doc._id];if(error){result.errors.push(error);if("unauthorized"!==(errorName=(error.name||"").toLowerCase())&&"forbidden"!==errorName)throw error;returnValue.emit("denied",clone2(error))}else changedDocs.push(doc)}))}),(function(err3){result.doc_write_failures+=docs.length;throw err3}))}}function finishBatch(){if(currentBatch.error)throw new Error("There was a problem getting docs.");result.last_seq=last_seq=currentBatch.seq;var outResult=clone2(result);if(changedDocs.length){outResult.docs=changedDocs;if("number"==typeof currentBatch.pending){outResult.pending=currentBatch.pending;delete currentBatch.pending}returnValue.emit("change",outResult)}writingCheckpoint=!0;src.info().then((function(info3){var completed,total_items,task=src.activeTasks.get(taskId);if(currentBatch&&task){completed=task.completed_items||0;total_items=parseInt(info3.update_seq,10)-parseInt(initial_last_seq,10);src.activeTasks.update(taskId,{completed_items:completed+currentBatch.changes.length,total_items})}}));return checkpointer.writeCheckpoint(currentBatch.seq,session).then((function(){returnValue.emit("checkpoint",{checkpoint:currentBatch.seq});writingCheckpoint=!1;if(returnValue.cancelled){completeReplication();throw new Error("cancelled")}currentBatch=void 0;getChanges()})).catch((function(err3){onCheckpointError(err3);throw err3}))}function getDiffs(){var diff={};currentBatch.changes.forEach((function(change){returnValue.emit("checkpoint",{revs_diff:change});"_user/"!==change.id&&(diff[change.id]=change.changes.map((function(x2){return x2.rev})))}));return target.revsDiff(diff).then((function(diffs){if(returnValue.cancelled){completeReplication();throw new Error("cancelled")}currentBatch.diffs=diffs}))}function getBatchDocs(){return getDocs(src,target,currentBatch.diffs,returnValue).then((function(got){currentBatch.error=!got.ok;got.docs.forEach((function(doc){delete currentBatch.diffs[doc._id];result.docs_read++;currentBatch.docs.push(doc)}))}))}function startNextBatch(){if(!returnValue.cancelled&&!currentBatch)if(0!==batches2.length){currentBatch=batches2.shift();returnValue.emit("checkpoint",{start_next_batch:currentBatch.seq});getDiffs().then(getBatchDocs).then(writeDocs).then(finishBatch).then(startNextBatch).catch((function(err3){abortReplication("batch processing terminated with error",err3)}))}else processPendingBatch(!0)}function processPendingBatch(immediate){if(0!==pendingBatch.changes.length){if(immediate||changesCompleted||pendingBatch.changes.length>=batch_size){batches2.push(pendingBatch);pendingBatch={seq:0,changes:[],docs:[]};if("pending"===returnValue.state||"stopped"===returnValue.state){returnValue.state="active";returnValue.emit("active")}startNextBatch()}}else if(0===batches2.length&&!currentBatch){if(continuous&&changesOpts.live||changesCompleted){returnValue.state="pending";returnValue.emit("paused")}changesCompleted&&completeReplication()}}function abortReplication(reason,err3){if(!replicationCompleted){err3.message||(err3.message=reason);result.ok=!1;result.status="aborting";batches2=[];pendingBatch={seq:0,changes:[],docs:[]};completeReplication(err3)}}function completeReplication(fatalError){if(!replicationCompleted){if(returnValue.cancelled){result.status="cancelled";if(writingCheckpoint)return}result.status=result.status||"complete";result.end_time=(new Date).toISOString();result.last_seq=last_seq;replicationCompleted=!0;src.activeTasks.remove(taskId,fatalError);if(fatalError){(fatalError=createError(fatalError)).result=result;var errorName=(fatalError.name||"").toLowerCase();if("unauthorized"===errorName||"forbidden"===errorName){returnValue.emit("error",fatalError);returnValue.removeAllListeners()}else backOff(opts,returnValue,fatalError,(function(){replicate(src,target,opts,returnValue)}))}else{returnValue.emit("complete",result);returnValue.removeAllListeners()}}}function onChange(change,pending3,lastSeq){var task,completed;if(returnValue.cancelled)return completeReplication();"number"==typeof pending3&&(pendingBatch.pending=pending3);if(filterChange(opts)(change)){pendingBatch.seq=change.seq||lastSeq;pendingBatch.changes.push(change);returnValue.emit("checkpoint",{pending_batch:pendingBatch.seq});nextTick((function(){processPendingBatch(0===batches2.length&&changesOpts.live)}))}else if(task=src.activeTasks.get(taskId)){completed=task.completed_items||0;src.activeTasks.update(taskId,{completed_items:++completed})}}function onChangesComplete(changes3){changesPending=!1;if(returnValue.cancelled)return completeReplication();if(changes3.results.length>0){changesOpts.since=changes3.results[changes3.results.length-1].seq;getChanges();processPendingBatch(!0)}else{var complete=function(){if(continuous){changesOpts.live=!0;getChanges()}else changesCompleted=!0;processPendingBatch(!0)};if(currentBatch||0!==changes3.results.length)complete();else{writingCheckpoint=!0;checkpointer.writeCheckpoint(changes3.last_seq,session).then((function(){writingCheckpoint=!1;result.last_seq=last_seq=changes3.last_seq;if(returnValue.cancelled){completeReplication();throw new Error("cancelled")}complete()})).catch(onCheckpointError)}}}function onChangesError(err3){changesPending=!1;if(returnValue.cancelled)return completeReplication();abortReplication("changes rejected",err3)}function getChanges(){function abortChanges(){changes3.cancel()}function removeListener(){returnValue.removeListener("cancel",abortChanges)}if(!changesPending&&!changesCompleted&&batches2.length<batches_limit){changesPending=!0;if(returnValue._changes){returnValue.removeListener("cancel",returnValue._abortChanges);returnValue._changes.cancel()}returnValue.once("cancel",abortChanges);var changes3=src.changes(changesOpts).on("change",onChange);changes3.then(removeListener,removeListener);changes3.then(onChangesComplete).catch(onChangesError);if(opts.retry){returnValue._changes=changes3;returnValue._abortChanges=abortChanges}}}function createTask(checkpoint){return src.info().then((function(info3){var total_items=void 0===opts.since?parseInt(info3.update_seq,10)-parseInt(checkpoint,10):parseInt(info3.update_seq,10);taskId=src.activeTasks.add({name:`${continuous?"continuous ":""}replication from ${info3.db_name}`,total_items});return checkpoint}))}function startChanges(){initCheckpointer().then((function(){if(!returnValue.cancelled)return checkpointer.getCheckpoint().then(createTask).then((function(checkpoint){initial_last_seq=checkpoint;changesOpts={since:last_seq=checkpoint,limit:batch_size,batch_size,style,doc_ids,selector,return_docs:!0};opts.filter&&("string"!=typeof opts.filter?changesOpts.include_docs=!0:changesOpts.filter=opts.filter);"heartbeat"in opts&&(changesOpts.heartbeat=opts.heartbeat);"timeout"in opts&&(changesOpts.timeout=opts.timeout);opts.query_params&&(changesOpts.query_params=opts.query_params);opts.view&&(changesOpts.view=opts.view);getChanges()}));completeReplication()})).catch((function(err3){abortReplication("getCheckpoint rejected with ",err3)}))}function onCheckpointError(err3){writingCheckpoint=!1;abortReplication("writeCheckpoint completed with error",err3)}var currentBatch,repId,checkpointer,taskId,changesOpts,batches2=[],pendingBatch={seq:0,changes:[],docs:[]},writingCheckpoint=!1,changesCompleted=!1,replicationCompleted=!1,initial_last_seq=0,last_seq=0,continuous=opts.continuous||opts.live||!1,batch_size=opts.batch_size||100,batches_limit=opts.batches_limit||10,style=opts.style||"all_docs",changesPending=!1,doc_ids=opts.doc_ids,selector=opts.selector,changedDocs=[],session=uuid();result=result||{ok:!0,start_time:(new Date).toISOString(),docs_read:0,docs_written:0,doc_write_failures:0,errors:[]};changesOpts={};returnValue.ready(src,target);if(returnValue.cancelled)completeReplication();else{if(!returnValue._addedListeners){returnValue.once("cancel",completeReplication);if("function"==typeof opts.complete){returnValue.once("error",opts.complete);returnValue.once("complete",(function(result2){opts.complete(null,result2)}))}returnValue._addedListeners=!0}void 0===opts.since?startChanges():initCheckpointer().then((function(){writingCheckpoint=!0;return checkpointer.writeCheckpoint(opts.since,session)})).then((function(){writingCheckpoint=!1;if(returnValue.cancelled)completeReplication();else{last_seq=opts.since;startChanges()}})).catch(onCheckpointError)}}function toPouch(db,opts){var PouchConstructor=opts.PouchConstructor;return"string"==typeof db?new PouchConstructor(db,opts):db}function replicateWrapper(src,target,opts,callback){var replicateRet;if("function"==typeof opts){callback=opts;opts={}}void 0===opts&&(opts={});if(opts.doc_ids&&!Array.isArray(opts.doc_ids))throw createError(BAD_REQUEST,"`doc_ids` filter parameter is not a list.");opts.complete=callback;(opts=clone2(opts)).continuous=opts.continuous||opts.live;opts.retry="retry"in opts&&opts.retry;opts.PouchConstructor=opts.PouchConstructor||this;replicateRet=new Replication(opts);replicate(toPouch(src,opts),toPouch(target,opts),opts,replicateRet);return replicateRet}function sync(src,target,opts,callback){if("function"==typeof opts){callback=opts;opts={}}void 0===opts&&(opts={});(opts=clone2(opts)).PouchConstructor=opts.PouchConstructor||this;src=toPouch(src,opts);target=toPouch(target,opts);return new Sync(src,target,opts,callback)}function mergeObjects(arr){const res2={};for(const element2 of arr)Object.assign(res2,element2);return res2}function pick2(obj,arr){const res2={};for(const field of arr){const parsedField=parseField(field),value=getFieldFromDoc(obj,parsedField);void 0!==value&&setFieldInDoc(res2,parsedField,value)}return res2}function oneArrayIsSubArrayOfOther(left,right){for(let i2=0,len=Math.min(left.length,right.length);i2<len;i2++)if(left[i2]!==right[i2])return!1;return!0}function oneArrayIsStrictSubArrayOfOther(left,right){return!(left.length>right.length)&&oneArrayIsSubArrayOfOther(left,right)}function oneSetIsSubArrayOfOther(left,right){left=left.slice();for(const field of right){if(!left.length)break;const leftIdx=left.indexOf(field);if(-1===leftIdx)return!1;left.splice(leftIdx,1)}return!0}function arrayToObject(arr){const res2={};for(const field of arr)res2[field]=!0;return res2}function max2(arr,fun){let max3=null,maxScore=-1;for(const element2 of arr){const score=fun(element2);if(score>maxScore){maxScore=score;max3=element2}}return max3}function arrayEquals(arr1,arr2){if(arr1.length!==arr2.length)return!1;for(let i2=0,len=arr1.length;i2<len;i2++)if(arr1[i2]!==arr2[i2])return!1;return!0}function uniq2(arr){return Array.from(new Set(arr))}function resolveToCallback(fun){return function(...args){const maybeCallback=args[args.length-1];if("function"!=typeof maybeCallback)return fun.apply(this,args);{const fulfilled=maybeCallback.bind(null,null),rejected=maybeCallback.bind(null);fun.apply(this,args.slice(0,-1)).then(fulfilled,rejected)}}}function massageCreateIndexRequest(requestDef){(requestDef=clone2(requestDef)).index||(requestDef.index={});for(const key3 of["type","name","ddoc"])if(requestDef.index[key3]){requestDef[key3]=requestDef.index[key3];delete requestDef.index[key3]}if(requestDef.fields){requestDef.index.fields=requestDef.fields;delete requestDef.fields}requestDef.type||(requestDef.type="json");return requestDef}function isNonNullObject(value){return"object"==typeof value&&null!==value}function checkFieldValueType(name,value,isHttp){let message="",received=value,addReceived=!0;-1!==["$in","$nin","$or","$and","$mod","$nor","$all"].indexOf(name)&&(Array.isArray(value)||(message="Query operator "+name+" must be an array."));-1!==["$not","$elemMatch","$allMatch"].indexOf(name)&&(!Array.isArray(value)&&isNonNullObject(value)||(message="Query operator "+name+" must be an object."));if("$mod"===name&&Array.isArray(value))if(2!==value.length)message="Query operator $mod must be in the format [divisor, remainder], where divisor and remainder are both integers.";else{const divisor=value[0],mod=value[1];if(0===divisor){message="Query operator $mod's divisor cannot be 0, cannot divide by zero.";addReceived=!1}if("number"!=typeof divisor||parseInt(divisor,10)!==divisor){message="Query operator $mod's divisor is not an integer.";received=divisor}if(parseInt(mod,10)!==mod){message="Query operator $mod's remainder is not an integer.";received=mod}}"$exists"===name&&"boolean"!=typeof value&&(message="Query operator $exists must be a boolean.");if("$type"===name){const allowed=["null","boolean","number","string","array","object"],allowedStr='"'+allowed.slice(0,allowed.length-1).join('", "')+'", or "'+allowed[allowed.length-1]+'"';("string"!=typeof value||-1==allowed.indexOf(value))&&(message="Query operator $type must be a string. Supported values: "+allowedStr+".")}"$size"===name&&parseInt(value,10)!==value&&(message="Query operator $size must be a integer.");"$regex"===name&&"string"!=typeof value&&(isHttp?message="Query operator $regex must be a string.":value instanceof RegExp||(message="Query operator $regex must be a string or an instance of a javascript regular expression."));if(message){addReceived&&(message+=" Received"+(null===received?" ":Array.isArray(received)?" array":" "+typeof received)+": "+(isNonNullObject(received)?JSON.stringify(received,null,"\t"):received));throw new Error(message)}}function validateSelector(input,isHttp){if(Array.isArray(input))for(const entry of input)isNonNullObject(entry)&&validateSelector(entry,isHttp);else for(const[key3,value]of Object.entries(input)){-1!==requireValidation.indexOf(key3)&&checkFieldValueType(key3,value,isHttp);-1===equalityOperators.indexOf(key3)&&-1===arrayTypeComparisonOperators.indexOf(key3)&&isNonNullObject(value)&&validateSelector(value,isHttp)}}async function dbFetch(db,path2,opts){if(opts.body){opts.body=JSON.stringify(opts.body);opts.headers=new h2({"Content-type":"application/json"})}const response=await db.fetch(path2,opts),json=await response.json();if(!response.ok){json.status=response.status;throw generateErrorFromResponse(createError(json))}return json}async function createIndex(db,requestDef){return await dbFetch(db,"_index",{method:"POST",body:massageCreateIndexRequest(requestDef)})}async function find(db,requestDef){validateSelector(requestDef.selector,!0);return await dbFetch(db,"_find",{method:"POST",body:requestDef})}async function explain(db,requestDef){return await dbFetch(db,"_explain",{method:"POST",body:requestDef})}async function getIndexes(db){return await dbFetch(db,"_index",{method:"GET"})}async function deleteIndex(db,indexDef){const ddoc=indexDef.ddoc,type=indexDef.type||"json",name=indexDef.name;if(!ddoc)throw new Error("you must provide an index's ddoc");if(!name)throw new Error("you must provide an index's name");const url="_index/"+[ddoc,type,name].map(encodeURIComponent).join("/");return await dbFetch(db,url,{method:"DELETE"})}function getDeepValue(value,path2){for(const key3 of path2)if(void 0===(value=value[key3]))return;return value}function createDeepMultiMapper(fields,emit2,selector){return function(doc){if(selector&&!matchesSelector(doc,selector))return;const toEmit=[];for(const field of fields){const value=getDeepValue(doc,parseField(field));if(void 0===value)return;toEmit.push(value)}emit2(toEmit)}}function createDeepSingleMapper(field,emit2,selector){const parsedField=parseField(field);return function(doc){if(selector&&!matchesSelector(doc,selector))return;const value=getDeepValue(doc,parsedField);void 0!==value&&emit2(value)}}function createShallowSingleMapper(field,emit2,selector){return function(doc){selector&&!matchesSelector(doc,selector)||emit2(doc[field])}}function createShallowMultiMapper(fields,emit2,selector){return function(doc){if(selector&&!matchesSelector(doc,selector))return;const toEmit=fields.map((field=>doc[field]));emit2(toEmit)}}function checkShallow(fields){return fields.every((field=>-1===field.indexOf(".")))}function createMapper(fields,emit2,selector){const isShallow=checkShallow(fields),isSingle=1===fields.length;return isShallow?isSingle?createShallowSingleMapper(fields[0],emit2,selector):createShallowMultiMapper(fields,emit2,selector):isSingle?createDeepSingleMapper(fields[0],emit2,selector):createDeepMultiMapper(fields,emit2,selector)}function abstractMapper$1(db){return db._customFindAbstractMapper?{query:function addQueryFallback(signature,opts){const fallback2=abstractMapper.query.bind(this);return db._customFindAbstractMapper.query.call(this,signature,opts,fallback2)},viewCleanup:function addViewCleanupFallback(){const fallback2=abstractMapper.viewCleanup.bind(this);return db._customFindAbstractMapper.viewCleanup.call(this,fallback2)}}:abstractMapper}function massageSort(sort){if(!Array.isArray(sort))throw new Error("invalid sort json - should be an array");return sort.map((function(sorting){if("string"==typeof sorting){const obj={};obj[sorting]="asc";return obj}return sorting}))}function massageUseIndex(useIndex){let cleanedUseIndex=[];"string"==typeof useIndex?cleanedUseIndex.push(useIndex):cleanedUseIndex=useIndex;return cleanedUseIndex.map((function(name){return name.replace(ddocIdPrefix,"")}))}function massageIndexDef(indexDef){indexDef.fields=indexDef.fields.map((function(field){if("string"==typeof field){const obj={};obj[field]="asc";return obj}return field}));indexDef.partial_filter_selector&&(indexDef.partial_filter_selector=massageSelector(indexDef.partial_filter_selector));return indexDef}function getKeyFromDoc(doc,index6){return index6.def.fields.map((obj=>{const field=getKey2(obj);return getFieldFromDoc(doc,parseField(field))}))}function filterInclusiveStart(rows,targetValue,index6){const indexFields=index6.def.fields;let startAt=0;for(const row of rows){let docKey=getKeyFromDoc(row.doc,index6);if(1===indexFields.length)docKey=docKey[0];else for(;docKey.length>targetValue.length;)docKey.pop();if(Math.abs(collate(docKey,targetValue))>0)break;++startAt}return startAt>0?rows.slice(startAt):rows}function reverseOptions(opts){const newOpts=clone2(opts);delete newOpts.startkey;delete newOpts.endkey;delete newOpts.inclusive_start;delete newOpts.inclusive_end;"endkey"in opts&&(newOpts.startkey=opts.endkey);"startkey"in opts&&(newOpts.endkey=opts.startkey);"inclusive_start"in opts&&(newOpts.inclusive_end=opts.inclusive_start);"inclusive_end"in opts&&(newOpts.inclusive_start=opts.inclusive_end);return newOpts}function validateIndex(index6){const ascFields=index6.fields.filter((function(field){return"asc"===getValue(field)}));if(0!==ascFields.length&&ascFields.length!==index6.fields.length)throw new Error("unsupported mixed sorting")}function validateSort(requestDef,index6){if(index6.defaultUsed&&requestDef.sort){const noneIdSorts=requestDef.sort.filter((function(sortItem){return"_id"!==Object.keys(sortItem)[0]})).map((function(sortItem){return Object.keys(sortItem)[0]}));if(noneIdSorts.length>0)throw new Error('Cannot sort on field(s) "'+noneIdSorts.join(",")+'" when using the default index')}index6.defaultUsed}function validateFindRequest(requestDef){if("object"!=typeof requestDef.selector)throw new Error("you must provide a selector when you find()")}function getUserFields(selector,sort){const selectorFields=Object.keys(selector),sortFields=sort?sort.map(getKey2):[];let userFields;userFields=selectorFields.length>=sortFields.length?selectorFields:sortFields;if(0===sortFields.length)return{fields:userFields};userFields=userFields.sort((function(left,right){let leftIdx=sortFields.indexOf(left);-1===leftIdx&&(leftIdx=Number.MAX_VALUE);let rightIdx=sortFields.indexOf(right);-1===rightIdx&&(rightIdx=Number.MAX_VALUE);return leftIdx<rightIdx?-1:leftIdx>rightIdx?1:0}));return{fields:userFields,sortOrder:sort.map(getKey2)}}async function createIndex$1(db,requestDef){function getMd5(){return md5||(md5=stringMd5(JSON.stringify(requestDef)))}const originalIndexDef=clone2((requestDef=massageCreateIndexRequest(requestDef)).index);requestDef.index=massageIndexDef(requestDef.index);validateIndex(requestDef.index);let md5;const viewName=requestDef.name||"idx-"+getMd5(),ddocName=requestDef.ddoc||"idx-"+getMd5(),ddocId="_design/"+ddocName;let hasInvalidLanguage=!1,viewExists=!1;db.constructor.emit("debug",["find","creating index",ddocId]);await upsert2(db,ddocId,(function updateDdoc(doc){doc._rev&&"query"!==doc.language&&(hasInvalidLanguage=!0);doc.language="query";doc.views=doc.views||{};viewExists=!!doc.views[viewName];if(viewExists)return!1;doc.views[viewName]={map:{fields:mergeObjects(requestDef.index.fields),partial_filter_selector:requestDef.index.partial_filter_selector},reduce:"_count",options:{def:originalIndexDef}};return doc}));if(hasInvalidLanguage)throw new Error('invalid language for ddoc with id "'+ddocId+'" (should be "query")');const signature=ddocName+"/"+viewName;await abstractMapper$1(db).query.call(db,signature,{limit:0,reduce:!1});return{id:ddocId,name:viewName,result:viewExists?"exists":"created"}}async function getIndexes$1(db){const allDocsRes=await db.allDocs({startkey:"_design/",endkey:"_design/￿",include_docs:!0}),res2={indexes:[{ddoc:null,name:"_all_docs",type:"special",def:{fields:[{_id:"asc"}]}}]};res2.indexes=flatten2(res2.indexes,allDocsRes.rows.filter((function(row){return"query"===row.doc.language})).map((function(row){return(void 0!==row.doc.views?Object.keys(row.doc.views):[]).map((function(viewName){const view=row.doc.views[viewName];return{ddoc:row.id,name:viewName,type:"json",def:massageIndexDef(view.options.def)}}))})));res2.indexes.sort((function(left,right){return compare2(left.name,right.name)}));res2.total_rows=res2.indexes.length;return res2}function checkFieldInIndex(index6,field){return index6.def.fields.some((key3=>getKey2(key3)===field))}function userOperatorLosesPrecision(selector,field){return"$eq"!==getKey2(selector[field])}function sortFieldsByIndex(userFields,index6){const indexFields=index6.def.fields.map(getKey2);return userFields.slice().sort((function(a2,b3){let aIdx=indexFields.indexOf(a2),bIdx=indexFields.indexOf(b3);-1===aIdx&&(aIdx=Number.MAX_VALUE);-1===bIdx&&(bIdx=Number.MAX_VALUE);return compare2(aIdx,bIdx)}))}function getBasicInMemoryFields(index6,selector,userFields){let needToFilterInMemory=!1;for(let i2=0,len=(userFields=sortFieldsByIndex(userFields,index6)).length;i2<len;i2++){const field=userFields[i2];if(needToFilterInMemory||!checkFieldInIndex(index6,field))return userFields.slice(i2);i2<len-1&&userOperatorLosesPrecision(selector,field)&&(needToFilterInMemory=!0)}return[]}function getInMemoryFieldsFromNe(selector){const fields=[];for(const[field,matcher]of Object.entries(selector))for(const operator of Object.keys(matcher))"$ne"===operator&&fields.push(field);return fields}function getInMemoryFields(coreInMemoryFields,index6,selector,userFields){return sortFieldsByIndex(uniq2(flatten2(coreInMemoryFields,getBasicInMemoryFields(index6,selector,userFields),getInMemoryFieldsFromNe(selector))),index6)}function checkIndexFieldsMatch(indexFields,sortOrder,fields){if(sortOrder){const sortMatches=oneArrayIsStrictSubArrayOfOther(sortOrder,indexFields),selectorMatches=oneArrayIsSubArrayOfOther(fields,indexFields);return sortMatches&&selectorMatches}return oneSetIsSubArrayOfOther(fields,indexFields)}function isNonLogicalMatcher(matcher){return-1===logicalMatchers.indexOf(matcher)}function checkFieldsLogicallySound(indexFields,selector){const matcher=selector[indexFields[0]];return void 0===matcher||!(1===Object.keys(matcher).length&&"$ne"===getKey2(matcher))}function checkIndexMatches(index6,sortOrder,fields,selector){const indexFields=index6.def.fields.map(getKey2);return!!checkIndexFieldsMatch(indexFields,sortOrder,fields)&&checkFieldsLogicallySound(indexFields,selector)}function findMatchingIndexes(selector,userFields,sortOrder,indexes2){return indexes2.filter((function(index6){return checkIndexMatches(index6,sortOrder,userFields,selector)}))}function findBestMatchingIndex(selector,userFields,sortOrder,indexes2,useIndex){const matchingIndexes=findMatchingIndexes(selector,userFields,sortOrder,indexes2);if(0===matchingIndexes.length){if(useIndex)throw{error:"no_usable_index",message:"There is no index available for this selector."};const defaultIndex=indexes2[0];defaultIndex.defaultUsed=!0;return defaultIndex}if(1===matchingIndexes.length&&!useIndex)return matchingIndexes[0];const userFieldsMap=arrayToObject(userFields);if(useIndex){const useIndexDdoc="_design/"+useIndex[0],useIndexName=2===useIndex.length&&useIndex[1],index6=matchingIndexes.find((function(index7){return!(!useIndexName||index7.ddoc!==useIndexDdoc||useIndexName!==index7.name)||index7.ddoc===useIndexDdoc}));if(!index6)throw{error:"unknown_error",message:"Could not find that index or could not use that index for the query"};return index6}return max2(matchingIndexes,(function scoreIndex(index6){const indexFields=index6.def.fields.map(getKey2);let score=0;for(const indexField of indexFields)userFieldsMap[indexField]&&score++;return score}))}function getSingleFieldQueryOptsFor(userOperator,userValue){switch(userOperator){case"$eq":return{key:userValue};case"$lte":return{endkey:userValue};case"$gte":return{startkey:userValue};case"$lt":return{endkey:userValue,inclusive_end:!1};case"$gt":return{startkey:userValue,inclusive_start:!1}}return{startkey:COLLATE_LO}}function getSingleFieldCoreQueryPlan(selector,index6){const field=getKey2(index6.def.fields[0]),matcher=selector[field]||{},inMemoryFields=[],userOperators=Object.keys(matcher);let combinedOpts;for(const userOperator of userOperators){isNonLogicalMatcher(userOperator)&&inMemoryFields.push(field);const newQueryOpts=getSingleFieldQueryOptsFor(userOperator,matcher[userOperator]);combinedOpts=combinedOpts?mergeObjects([combinedOpts,newQueryOpts]):newQueryOpts}return{queryOpts:combinedOpts,inMemoryFields}}function getMultiFieldCoreQueryPlan(userOperator,userValue){switch(userOperator){case"$eq":return{startkey:userValue,endkey:userValue};case"$lte":return{endkey:userValue};case"$gte":return{startkey:userValue};case"$lt":return{endkey:userValue,inclusive_end:!1};case"$gt":return{startkey:userValue,inclusive_start:!1}}}function getMultiFieldQueryOpts(selector,index6){function finish(i2){!1!==inclusiveStart&&startkey.push(COLLATE_LO);!1!==inclusiveEnd&&endkey.push(COLLATE_HI);inMemoryFields=indexFields.slice(i2)}const indexFields=index6.def.fields.map(getKey2);let inMemoryFields=[];const startkey=[],endkey=[];let inclusiveStart,inclusiveEnd;for(let i2=0,len=indexFields.length;i2<len;i2++){const matcher=selector[indexFields[i2]];if(!matcher||!Object.keys(matcher).length){finish(i2);break}if(Object.keys(matcher).some(isNonLogicalMatcher)){finish(i2);break}if(i2>0){const usingGtlt="$gt"in matcher||"$gte"in matcher||"$lt"in matcher||"$lte"in matcher,previousKeys=Object.keys(selector[indexFields[i2-1]]),previousWasEq=arrayEquals(previousKeys,["$eq"]),previousWasSame=arrayEquals(previousKeys,Object.keys(matcher));if(usingGtlt&&!previousWasEq&&!previousWasSame){finish(i2);break}}const userOperators=Object.keys(matcher);let combinedOpts=null;for(const userOperator of userOperators){const newOpts=getMultiFieldCoreQueryPlan(userOperator,matcher[userOperator]);combinedOpts=combinedOpts?mergeObjects([combinedOpts,newOpts]):newOpts}startkey.push("startkey"in combinedOpts?combinedOpts.startkey:COLLATE_LO);endkey.push("endkey"in combinedOpts?combinedOpts.endkey:COLLATE_HI);"inclusive_start"in combinedOpts&&(inclusiveStart=combinedOpts.inclusive_start);"inclusive_end"in combinedOpts&&(inclusiveEnd=combinedOpts.inclusive_end)}const res2={startkey,endkey};void 0!==inclusiveStart&&(res2.inclusive_start=inclusiveStart);void 0!==inclusiveEnd&&(res2.inclusive_end=inclusiveEnd);return{queryOpts:res2,inMemoryFields}}function shouldShortCircuit(selector){return Object.keys(selector).map((function(key3){return selector[key3]})).some((function(val2){return"object"==typeof val2&&0===Object.keys(val2).length}))}function getDefaultQueryPlan(selector){return{queryOpts:{startkey:null},inMemoryFields:[Object.keys(selector)]}}function getCoreQueryPlan(selector,index6){return index6.defaultUsed?getDefaultQueryPlan(selector):1===index6.def.fields.length?getSingleFieldCoreQueryPlan(selector,index6):getMultiFieldQueryOpts(selector,index6)}function planQuery(request2,indexes2){const selector=request2.selector,sort=request2.sort;if(shouldShortCircuit(selector))return Object.assign({},SHORT_CIRCUIT_QUERY,{index:indexes2[0]});const userFieldsRes=getUserFields(selector,sort),userFields=userFieldsRes.fields,index6=findBestMatchingIndex(selector,userFields,userFieldsRes.sortOrder,indexes2,request2.use_index),coreQueryPlan=getCoreQueryPlan(selector,index6);return{queryOpts:coreQueryPlan.queryOpts,index:index6,inMemoryFields:getInMemoryFields(coreQueryPlan.inMemoryFields,index6,selector,userFields)}}function indexToSignature(index6){return index6.ddoc.substring(8)+"/"+index6.name}async function doAllDocs(db,originalOpts){const opts=clone2(originalOpts);if(opts.descending){"endkey"in opts&&"string"!=typeof opts.endkey&&(opts.endkey="");"startkey"in opts&&"string"!=typeof opts.startkey&&(opts.limit=0)}else{"startkey"in opts&&"string"!=typeof opts.startkey&&(opts.startkey="");"endkey"in opts&&"string"!=typeof opts.endkey&&(opts.limit=0)}"key"in opts&&"string"!=typeof opts.key&&(opts.limit=0);if(opts.limit>0&&opts.indexes_count){opts.original_limit=opts.limit;opts.limit+=opts.indexes_count}const res2=await db.allDocs(opts);res2.rows=res2.rows.filter((function(row){return!/^_design\//.test(row.id)}));opts.original_limit&&(opts.limit=opts.original_limit);res2.rows=res2.rows.slice(0,opts.limit);return res2}async function queryAllOrIndex(db,opts,indexToUse){return"_all_docs"===indexToUse.name?doAllDocs(db,opts):abstractMapper$1(db).query.call(db,indexToSignature(indexToUse),opts)}async function find$1(db,requestDef,explain2){if(requestDef.selector){validateSelector(requestDef.selector,!1);requestDef.selector=massageSelector(requestDef.selector)}requestDef.sort&&(requestDef.sort=massageSort(requestDef.sort));requestDef.use_index&&(requestDef.use_index=massageUseIndex(requestDef.use_index));"limit"in requestDef||(requestDef.limit=25);validateFindRequest(requestDef);const getIndexesRes=await getIndexes$1(db);db.constructor.emit("debug",["find","planning query",requestDef]);const queryPlan=planQuery(requestDef,getIndexesRes.indexes);db.constructor.emit("debug",["find","query plan",queryPlan]);const indexToUse=queryPlan.index;validateSort(requestDef,indexToUse);let opts=Object.assign({include_docs:!0,reduce:!1,indexes_count:getIndexesRes.total_rows},queryPlan.queryOpts);if("startkey"in opts&&"endkey"in opts&&collate(opts.startkey,opts.endkey)>0)return{docs:[]};if(requestDef.sort&&"string"!=typeof requestDef.sort[0]&&"desc"===getValue(requestDef.sort[0])){opts.descending=!0;opts=reverseOptions(opts)}if(!queryPlan.inMemoryFields.length){opts.limit=requestDef.limit;"skip"in requestDef&&(opts.skip=requestDef.skip)}if(explain2)return Promise.resolve(queryPlan,opts);const res2=await queryAllOrIndex(db,opts,indexToUse);!1===opts.inclusive_start&&(res2.rows=filterInclusiveStart(res2.rows,opts.startkey,indexToUse));queryPlan.inMemoryFields.length&&(res2.rows=filterInMemoryFields(res2.rows,requestDef,queryPlan.inMemoryFields));const resp={docs:res2.rows.map((function(row){const doc=row.doc;return requestDef.fields?pick2(doc,requestDef.fields):doc}))};indexToUse.defaultUsed&&(resp.warning="No matching index found, create an index to optimize query time.");return resp}async function explain$1(db,requestDef){const queryPlan=await find$1(db,requestDef,!0);return{dbname:db.name,index:queryPlan.index,selector:requestDef.selector,range:{start_key:queryPlan.queryOpts.startkey,end_key:queryPlan.queryOpts.endkey},opts:{use_index:requestDef.use_index||[],bookmark:"nil",limit:requestDef.limit,skip:requestDef.skip,sort:requestDef.sort||{},fields:requestDef.fields,conflicts:!1,r:[49]},limit:requestDef.limit,skip:requestDef.skip||0,fields:requestDef.fields}}async function deleteIndex$1(db,index6){if(!index6.ddoc)throw new Error("you must supply an index.ddoc when deleting");if(!index6.name)throw new Error("you must supply an index.name when deleting");const docId=index6.ddoc,viewName=index6.name;await upsert2(db,docId,(function deltaFun(doc){if(1===Object.keys(doc.views).length&&doc.views[viewName])return{_id:docId,_deleted:!0};delete doc.views[viewName];return doc}));await abstractMapper$1(db).viewCleanup.apply(db);return{ok:!0}}function appendPurgeSeqs(db,docs){return db.get("_local/purges").then((function(doc){for(const[docId,rev$$1]of docs){const purgeSeq=doc.purgeSeq+1;doc.purges.push({docId,rev:rev$$1,purgeSeq});doc.purges.length>db.purged_infos_limit&&doc.purges.splice(0,doc.purges.length-db.purged_infos_limit);doc.purgeSeq=purgeSeq}return doc})).catch((function(err3){if(404!==err3.status)throw err3;return{_id:"_local/purges",purges:docs.map((([docId,rev$$1],idx2)=>({docId,rev:rev$$1,purgeSeq:idx2}))),purgeSeq:docs.length}})).then((function(doc){return db.put(doc)}))}function SetupRemoteP2P($$anchor,$$props){function generateSetting(){const trialSettings={...{...P2P_DEFAULT_SETTINGS,...syncSetting,P2P_Enabled:!0}};return{...DEFAULT_SETTINGS,...PREFERRED_BASE,remoteType:RemoteTypes_REMOTE_P2P,...trialSettings}}async function checkConnection(){try{set(processing,!0);const trialRemoteSetting=generateSetting(),map4=new Map,store={get:key3=>Promise.resolve(map4.get(key3)||null),set:(key3,value)=>{map4.set(key3,value);return Promise.resolve()},delete:key3=>{map4.delete(key3);return Promise.resolve()},keys:()=>Promise.resolve(Array.from(map4.keys()))},dummyPouch=new index_es_default("dummy"),env={settings:trialRemoteSetting,processReplicatedDocs:async docs=>{},confirm:context2.plugin.confirm,db:dummyPouch,simpleStore:store,deviceName:syncSetting.P2P_DevicePeerName||"unnamed-device",platform:"setup-wizard"},replicator=new TrysteroReplicator(env);try{await replicator.setOnSetup();await replicator.allowReconnection();await replicator.open();for(let i2=0;i2<10;i2++){await new Promise((resolve=>setTimeout(resolve,1e3)));if(replicator.knownAdvertisements.length>0)break}return 0===replicator.knownAdvertisements.length?"Your settings seem correct, but no other peers were found.":""}catch(e3){return`Failed to connect to other peers: ${e3}`}finally{try{replicator.close();dummyPouch.destroy()}catch(e3){console.error(e3)}}}finally{set(processing,!1)}}function setDefaultRelay(){syncSetting.P2P_relays=P2P_DEFAULT_SETTINGS.P2P_relays}function generateDefaultGroupId(){const randomValues=new Uint16Array(4);crypto.getRandomValues(randomValues);const a2=Math.floor(randomValues[0]/65536*1e3),b3=Math.floor(randomValues[1]/65536*1e3),c3=Math.floor(randomValues[2]/65536*1e3),d4=Math.floor(randomValues[3]/65536*46656);syncSetting.P2P_roomID=`${a2.toString().padStart(3,"0")}-${b3.toString().padStart(3,"0")}-${c3.toString().padStart(3,"0")}-${d4.toString(36).padStart(3,"0")}`}async function checkAndCommit(){set(error,"");try{set(error,await checkConnection()||"",!0);if(!get(error)){const setting=generateSetting();$$props.setResult(pickP2PSyncSettings(setting));return}}catch(e3){set(error,`Error during connection test: ${e3}`);return}}function commit(){const setting=pickP2PSyncSettings(generateSetting());$$props.setResult(setting)}function cancel2(){$$props.setResult("cancelled")}var fragment,node,node_1,node_2,node_3,node_4,node_5,node_6,node_7,node_8,node_9,node_10,node_11,node_12,node_18,node_19,consequent,alternate;push($$props,!0);let syncSetting=proxy({...pickP2PSyncSettings(DEFAULT_SETTINGS)});const context2=getObsidianDialogContext();let error=state("");onMount((()=>{if($$props.getInitialData){const initialData=$$props.getInitialData();initialData&&copyTo(initialData,syncSetting);context2.services.config.getSmallConfig(SETTING_KEY_P2P_DEVICE_NAME)?syncSetting.P2P_DevicePeerName=context2.services.config.getSmallConfig(SETTING_KEY_P2P_DEVICE_NAME):syncSetting.P2P_DevicePeerName=""}}));let processing=state(!1);const canProceed=user_derived((()=>{var _a8;return""!==syncSetting.P2P_relays.trim()&&""!==syncSetting.P2P_roomID.trim()&&""!==syncSetting.P2P_passphrase.trim()&&""!==(null!==(_a8=syncSetting.P2P_DevicePeerName)&&void 0!==_a8?_a8:"").trim()}));DialogHeader(node=first_child(fragment=root30()),{title:"P2P Configuration"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("Please enter the Peer-to-Peer Synchronisation information below."))},$$slots:{default:!0}});InputRow(node_2=sibling(node_1,2),{label:"Enabled",children:($$anchor2,$$slotProps)=>{var input=root_214();remove_input_defaults(input);bind_checked(input,(()=>syncSetting.P2P_Enabled),($$value=>syncSetting.P2P_Enabled=$$value));append($$anchor2,input)},$$slots:{default:!0}});InputRow(node_3=sibling(node_2,2),{label:"Relay URL",children:($$anchor2,$$slotProps)=>{var fragment_1=root_34(),input_1=first_child(fragment_1);remove_input_defaults(input_1);sibling(input_1,2).__click=[on_click3,setDefaultRelay];bind_value(input_1,(()=>syncSetting.P2P_relays),($$value=>syncSetting.P2P_relays=$$value));append($$anchor2,fragment_1)},$$slots:{default:!0}});InputRow(node_4=sibling(node_3,2),{label:"Group ID",children:($$anchor2,$$slotProps)=>{var fragment_2=root_411(),input_2=first_child(fragment_2);remove_input_defaults(input_2);sibling(input_2,2).__click=[on_click_1,generateDefaultGroupId];bind_value(input_2,(()=>syncSetting.P2P_roomID),($$value=>syncSetting.P2P_roomID=$$value));append($$anchor2,fragment_2)},$$slots:{default:!0}});InputRow(node_5=sibling(node_4,2),{label:"Passphrase",children:($$anchor2,$$slotProps)=>{Password($$anchor2,{name:"p2p-password",placeholder:"Enter your passphrase",get value(){return syncSetting.P2P_passphrase},set value($$value){syncSetting.P2P_passphrase=$$value}})},$$slots:{default:!0}});InfoNote(node_6=sibling(node_5,2),{children:($$anchor2,$$slotProps)=>{next();var fragment_4=root_66();next(2);append($$anchor2,fragment_4)},$$slots:{default:!0}});InputRow(node_7=sibling(node_6,2),{label:"Device Peer ID",children:($$anchor2,$$slotProps)=>{var input_3=root_77();remove_input_defaults(input_3);bind_value(input_3,(()=>syncSetting.P2P_DevicePeerName),($$value=>syncSetting.P2P_DevicePeerName=$$value));append($$anchor2,input_3)},$$slots:{default:!0}});InputRow(node_8=sibling(node_7,2),{label:"Auto Start P2P Connection",children:($$anchor2,$$slotProps)=>{var input_4=root_87();remove_input_defaults(input_4);bind_checked(input_4,(()=>syncSetting.P2P_AutoStart),($$value=>syncSetting.P2P_AutoStart=$$value));append($$anchor2,input_4)},$$slots:{default:!0}});InfoNote(node_9=sibling(node_8,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text('If "Auto Start P2P Connection" is enabled, the P2P connection will be started automatically when the plug-in\n launches.'))},$$slots:{default:!0}});InputRow(node_10=sibling(node_9,2),{label:"Auto Broadcast Changes",children:($$anchor2,$$slotProps)=>{var input_5=root_103();remove_input_defaults(input_5);bind_checked(input_5,(()=>syncSetting.P2P_AutoBroadcast),($$value=>syncSetting.P2P_AutoBroadcast=$$value));append($$anchor2,input_5)},$$slots:{default:!0}});InfoNote(node_11=sibling(node_10,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text('If "Auto Broadcast Changes" is enabled, changes will be automatically broadcasted to connected peers without\n requiring manual intervention. This requests peers to fetch this device\'s changes.'))},$$slots:{default:!0}});ExtraItems(node_12=sibling(node_11,2),{title:"Advanced Settings",children:($$anchor2,$$slotProps)=>{var node_14,node_15,node_16,fragment_5=root_124(),node_13=first_child(fragment_5);InfoNote(node_13,{children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("TURN server settings are only necessary if you are behind a strict NAT or firewall that prevents direct P2P\n connections. In most cases, you can leave these fields blank."))},$$slots:{default:!0}});InfoNote(node_14=sibling(node_13,2),{warning:!0,children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("Using public TURN servers may have privacy implications, as your data will be relayed through third-party\n servers. Even if your data are encrypted, your existence may be known to them. Please ensure you trust the TURN\n server provider before using their services. Also your `network administrator` too. You should consider setting\n up your own TURN server for your FQDN, if possible."))},$$slots:{default:!0}});InputRow(node_15=sibling(node_14,2),{label:"TURN Server URLs (comma-separated)",children:($$anchor3,$$slotProps2)=>{var textarea=root_153();remove_textarea_child(textarea);bind_value(textarea,(()=>syncSetting.P2P_turnServers),($$value=>syncSetting.P2P_turnServers=$$value));append($$anchor3,textarea)},$$slots:{default:!0}});InputRow(node_16=sibling(node_15,2),{label:"TURN Username",children:($$anchor3,$$slotProps2)=>{var input_6=root_163();remove_input_defaults(input_6);bind_value(input_6,(()=>syncSetting.P2P_turnUsername),($$value=>syncSetting.P2P_turnUsername=$$value));append($$anchor3,input_6)},$$slots:{default:!0}});InputRow(sibling(node_16,2),{label:"TURN Credential",children:($$anchor3,$$slotProps2)=>{Password($$anchor3,{name:"p2p-turn-credential",placeholder:"Enter TURN credential",get value(){return syncSetting.P2P_turnCredential},set value($$value){syncSetting.P2P_turnCredential=$$value}})},$$slots:{default:!0}});append($$anchor2,fragment_5)},$$slots:{default:!0}});node_18=sibling(node_12,2);{let $0=user_derived((()=>""!==get(error)));InfoNote(node_18,{error:!0,get visible(){return get($0)},children:($$anchor2,$$slotProps)=>{next();var text_5=text();template_effect((()=>set_text(text_5,get(error))));append($$anchor2,text_5)},$$slots:{default:!0}})}node_19=sibling(node_18,2);consequent=$$anchor2=>{append($$anchor2,text("Checking connection... Please wait."))};alternate=$$anchor2=>{UserDecisions($$anchor2,{children:($$anchor3,$$slotProps)=>{var node_21,fragment_9=root_215(),node_20=first_child(fragment_9);let $0=user_derived((()=>!get(canProceed)));Decision(node_20,{title:"Test Settings and Continue",important:!0,get disabled(){return get($0)},commit:()=>checkAndCommit()});Decision(node_21=sibling(node_20,2),{title:"Continue anyway",commit:()=>commit()});Decision(sibling(node_21,2),{title:"Cancel",commit:()=>cancel2()});append($$anchor3,fragment_9)},$$slots:{default:!0}})};if_block(node_19,($$render=>{get(processing)?$$render(consequent):$$render(alternate,!1)}));append($$anchor,fragment);pop()}function SetupRemoteE2EE($$anchor,$$props){function commit(){$$props.setResult(pickEncryptionSettings(encryptionSettings))}var fragment,node,node_1,node_2,node_4,node_5,node_6,node_7,node_8,node_12;push($$props,!0);let encryptionSettings=proxy({encrypt:!0,passphrase:"",E2EEAlgorithm:DEFAULT_SETTINGS.E2EEAlgorithm,usePathObfuscation:!0});onMount((()=>{if($$props.getInitialData){const initialData=$$props.getInitialData();initialData&&copyTo(initialData,encryptionSettings)}}));let e2eeValid=user_derived((()=>!encryptionSettings.encrypt||encryptionSettings.passphrase.trim().length>=1));DialogHeader(node=first_child(fragment=root31()),{title:"End-to-End Encryption"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("Please configure your end-to-end encryption settings."))},$$slots:{default:!0}});InputRow(node_2=sibling(node_1,2),{label:"End-to-End Encryption",children:($$anchor2,$$slotProps)=>{var node_3,fragment_1=root_216(),input=first_child(fragment_1);remove_input_defaults(input);node_3=sibling(input,2);{let $0=user_derived((()=>!encryptionSettings.encrypt));Password(node_3,{name:"e2ee-passphrase",placeholder:"Enter your passphrase",get disabled(){return get($0)},get required(){return encryptionSettings.encrypt},get value(){return encryptionSettings.passphrase},set value($$value){encryptionSettings.passphrase=$$value}})}bind_checked(input,(()=>encryptionSettings.encrypt),($$value=>encryptionSettings.encrypt=$$value));append($$anchor2,fragment_1)},$$slots:{default:!0}});InfoNote(node_4=sibling(node_2,2),{title:"Strongly Recommended",children:($$anchor2,$$slotProps)=>{next();var fragment_2=root_35();next(2);append($$anchor2,fragment_2)},$$slots:{default:!0}});InfoNote(node_5=sibling(node_4,2),{warning:!0,children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("This setting must be the same even when connecting to multiple synchronisation destinations."))},$$slots:{default:!0}});InputRow(node_6=sibling(node_5,2),{label:"Obfuscate Properties",children:($$anchor2,$$slotProps)=>{var input_1=root_53();remove_input_defaults(input_1);template_effect((()=>input_1.disabled=!encryptionSettings.encrypt));bind_checked(input_1,(()=>encryptionSettings.usePathObfuscation),($$value=>encryptionSettings.usePathObfuscation=$$value));append($$anchor2,input_1)},$$slots:{default:!0}});InfoNote(node_7=sibling(node_6,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("Obfuscating properties (e.g., path of file, size, creation and modification dates) adds an additional layer of\n security by making it harder to identify the structure and names of your files and folders on the remote server.\n This helps protect your privacy and makes it more difficult for unauthorized users to infer information about your\n data."))},$$slots:{default:!0}});ExtraItems(node_8=sibling(node_7,2),{title:"Advanced",children:($$anchor2,$$slotProps)=>{var node_10,fragment_3=root_78(),node_9=first_child(fragment_3);InputRow(node_9,{label:"Encryption Algorithm",children:($$anchor3,$$slotProps2)=>{var select=root_88();each(select,21,(()=>Object.values(E2EEAlgorithms)),index,(($$anchor4,alg)=>{var option_value,option=root_94(),text_3=child(option,!0);reset(option);option_value={};template_effect((()=>{var _a8,_b5;set_text(text_3,null!=(_a8=E2EEAlgorithmNames[get(alg)])?_a8:get(alg));option_value!==(option_value=get(alg))&&(option.value=null!=(_b5=option.__value=get(alg))?_b5:"")}));append($$anchor4,option)}));reset(select);template_effect((()=>select.disabled=!encryptionSettings.encrypt));bind_select_value(select,(()=>encryptionSettings.E2EEAlgorithm),($$value=>encryptionSettings.E2EEAlgorithm=$$value));append($$anchor3,select)},$$slots:{default:!0}});InfoNote(node_10=sibling(node_9,2),{children:($$anchor3,$$slotProps2)=>{next();var text_4=text();template_effect((()=>{var _a8;return set_text(text_4,`In most cases, you should stick with the default algorithm (${null!=(_a8=E2EEAlgorithmNames[DEFAULT_SETTINGS.E2EEAlgorithm])?_a8:""}), This setting is only required if you have an existing Vault encrypted in a different format.`)}));append($$anchor3,text_4)},$$slots:{default:!0}});InfoNote(sibling(node_10,2),{warning:!0,children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("Changing the encryption algorithm will prevent access to any data previously encrypted with a different\n algorithm. Ensure that all your devices are configured to use the same algorithm to maintain access to your\n data."))},$$slots:{default:!0}});append($$anchor2,fragment_3)},$$slots:{default:!0}});InfoNote(node_12=sibling(node_8,2),{warning:!0,children:($$anchor2,$$slotProps)=>{var fragment_5=root_125();next(2);append($$anchor2,fragment_5)},$$slots:{default:!0}});UserDecisions(sibling(node_12,2),{children:($$anchor2,$$slotProps)=>{var fragment_6=root_135(),node_14=first_child(fragment_6);let $0=user_derived((()=>!get(e2eeValid)));Decision(node_14,{title:"Proceed",important:!0,get disabled(){return get($0)},commit:()=>commit()});Decision(sibling(node_14,2),{title:"Cancel",commit:()=>$$props.setResult("cancelled")});append($$anchor2,fragment_6)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function encodeSettingsToQRCodeData(settings){const settingArr=[],fullIndexes=Object.entries(KeyIndexOfSettings);for(const[settingKey,index6]of fullIndexes){const settingValue=settings[settingKey];index6<0||(settingArr[index6]=settingValue)}return encodeAnyArray(settingArr)}function decodeSettingsFromQRCodeData(qr){const settingArr=decodeAnyArray(qr),fullIndexes=Object.entries(KeyIndexOfSettings),newSettings={...DEFAULT_SETTINGS};for(const[settingKey,index6]of fullIndexes){if(index6<0)continue;if(index6>=settingArr.length)continue;const settingValue=settingArr[index6];newSettings[settingKey]=settingValue}return newSettings}function encodeQR(settingString,format){const qr=(0,import_qrcode_generator.default)(0,"L"),uri=`${configURIBaseQR}${encodeURIComponent(settingString)}`;try{qr.addData(uri);qr.make()}catch(ex){Logger(`Failed to encode QR Code (${(null==ex?void 0:ex.message)||String(ex)})`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return""}return 0===format?qr.createSvgTag(3):1===format?qr.createASCII(3):""}async function encodeSettingsToSetupURI(settingString,passphrase,removeProperties=["pluginSyncExtendedSetting"],skipDefaultValue=!1){const setting={...settingString};if(skipDefaultValue){const keys3=Object.keys(setting);for(const k2 of keys3)JSON.stringify(k2 in setting?setting[k2]:"")==JSON.stringify(k2 in DEFAULT_SETTINGS?DEFAULT_SETTINGS[k2]:"*")&&delete setting[k2]}for(const prop2 of[...removeProperties])delete setting[prop2];for(const prop2 of necessaryErasureProperties)setting[prop2]="";const encryptedSetting=encodeURIComponent(await encryptString(JSON.stringify(setting),passphrase));return`${configURIBase}${encryptedSetting} `}function FetchEverything($$anchor,$$props){function commit(){$$props.setResult({vault:get(vaultType),backup:get(backupType),extra:{preventFetchingConfig:get(preventFetchingConfig)}})}var fragment,node,node_1,node_2,node_3,node_10,node_17;push($$props,!0);let vaultType=state("cancelled"),backupType=state("cancelled");const canProceed=user_derived((()=>!("identical"!==get(vaultType)&&"independent"!==get(vaultType)&&"unbalanced"!==get(vaultType)||"backup_done"!==get(backupType)&&"backup_skipped"!==get(backupType))));let preventFetchingConfig=state(!1);DialogHeader(node=first_child(fragment=root32()),{title:"Reset Synchronisation on This Device"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("This will rebuild the local database on this device using the most recent data from the server. This action is\n designed to resolve synchronisation inconsistencies and restore correct functionality."))},$$slots:{default:!0}});Guidance(node_2=sibling(node_1,2),{important:!0,title:"⚠️ Important Notice",children:($$anchor2,$$slotProps)=>{var fragment_1=root_217();next(2);append($$anchor2,fragment_1)},$$slots:{default:!0}});Instruction(node_3=sibling(node_2,4),{children:($$anchor2,$$slotProps)=>{var fragment_2=root_36(),node_4=first_child(fragment_2);Question(node_4,{children:($$anchor3,$$slotProps2)=>{var fragment_3=root_412();next();append($$anchor3,fragment_3)},$$slots:{default:!0}});Options(sibling(node_4,2),{children:($$anchor3,$$slotProps2)=>{var node_7,fragment_4=root_54(),node_6=first_child(fragment_4);Option(node_6,{selectedValue:"identical",title:"The files in this Vault are almost identical to the server's.",get value(){return get(vaultType)},set value($$value){set(vaultType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("(e.g., immediately after restoring on another computer, or having recovered from a backup)"))},$$slots:{default:!0}});Option(node_7=sibling(node_6,2),{selectedValue:"independent",title:"This Vault is empty, or contains only new files that are not on the server.",get value(){return get(vaultType)},set value($$value){set(vaultType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("(e.g., setting up for the first time on a new smartphone, starting from a clean slate)"))},$$slots:{default:!0}});Option(sibling(node_7,2),{selectedValue:"unbalanced",title:"There may be differences between the files in this Vault and the server.",get value(){return get(vaultType)},set value($$value){set(vaultType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{var fragment_5;next();InfoNote(sibling(first_child(fragment_5=root_89())),{info:!0,children:($$anchor5,$$slotProps4)=>{next();append($$anchor5,text("In this scenario, Self-hosted LiveSync will recreate metadata for every file and deliberately generate\n conflicts. Where the file content is identical, these conflicts will be resolved automatically."))},$$slots:{default:!0}});append($$anchor4,fragment_5)},$$slots:{default:!0}});append($$anchor3,fragment_4)},$$slots:{default:!0}});append($$anchor2,fragment_2)},$$slots:{default:!0}});Instruction(node_10=sibling(node_3,4),{children:($$anchor2,$$slotProps)=>{var node_12,fragment_6=root_104(),node_11=first_child(fragment_6);Question(node_11,{children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("Have you created a backup before proceeding?"))},$$slots:{default:!0}});InfoNote(node_12=sibling(node_11,2),{children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("We recommend that you copy your Vault folder to a safe location. This will provide a safeguard in case a large\n number of conflicts arise, or if you accidentally synchronise with an incorrect destination."))},$$slots:{default:!0}});Options(sibling(node_12,2),{children:($$anchor3,$$slotProps2)=>{var node_15,fragment_7=root_136(),node_14=first_child(fragment_7);Option(node_14,{selectedValue:"backup_done",title:"I have created a backup of my Vault.",get value(){return get(backupType)},set value($$value){set(backupType,$$value,!0)}});Option(node_15=sibling(node_14,2),{selectedValue:"backup_skipped",title:"I understand the risks and will proceed without a backup.",get value(){return get(backupType)},set value($$value){set(backupType,$$value,!0)}});Option(sibling(node_15,2),{selectedValue:"unable_to_backup",title:"I am unable to create a backup of my Vault.",get value(){return get(backupType)},set value($$value){set(backupType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{{let $0=user_derived((()=>"unable_to_backup"===get(backupType)));InfoNote($$anchor4,{error:!0,get visible(){return get($0)},children:($$anchor5,$$slotProps4)=>{var fragment_9=root_154();next(3);append($$anchor5,fragment_9)},$$slots:{default:!0}})}},$$slots:{default:!0}});append($$anchor3,fragment_7)},$$slots:{default:!0}});append($$anchor2,fragment_6)},$$slots:{default:!0}});Instruction(node_17=sibling(node_10,2),{children:($$anchor2,$$slotProps)=>{ExtraItems($$anchor2,{title:"Advanced",children:($$anchor3,$$slotProps2)=>{Check($$anchor3,{title:"Prevent fetching configuration from server",get value(){return get(preventFetchingConfig)},set value($$value){set(preventFetchingConfig,$$value,!0)}})},$$slots:{default:!0}})},$$slots:{default:!0}});UserDecisions(sibling(node_17,2),{children:($$anchor2,$$slotProps)=>{var fragment_12=root_184(),node_19=first_child(fragment_12);let $0=user_derived((()=>!get(canProceed)));Decision(node_19,{title:"Reset and Resume Synchronisation",important:!0,get disabled(){return get($0)},commit:()=>commit()});Decision(sibling(node_19,2),{title:"Cancel",commit:()=>$$props.setResult("cancelled")});append($$anchor2,fragment_12)},$$slots:{default:!0}});append($$anchor,fragment);pop()}function RebuildEverything($$anchor,$$props){function commit(){$$props.setResult({backup:get(backupType),extra:{preventFetchingConfig:get(preventFetchingConfig)}})}var fragment,node,node_1,node_2,node_3,node_9,node_16;push($$props,!0);let backupType=state("cancelled"),confirmationCheck1=state(!1),confirmationCheck2=state(!1),confirmationCheck3=state(!1);const canProceed=user_derived((()=>("backup_done"===get(backupType)||"backup_skipped"===get(backupType))&&get(confirmationCheck1)&&get(confirmationCheck2)&&get(confirmationCheck3)));let preventFetchingConfig=state(!1);DialogHeader(node=first_child(fragment=root33()),{title:"Final Confirmation: Overwrite Server Data with This Device's Files"});Guidance(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{next();var fragment_1=root_121();next(2);append($$anchor2,fragment_1)},$$slots:{default:!0}});InfoNote(node_2=sibling(node_1,2),{children:($$anchor2,$$slotProps)=>{next();append($$anchor2,text("You should perform this operation only in exceptional circumstances, such as when the server data is completely\n corrupted, when changes on all other devices are no longer needed, or when the database size has become unusually\n large in comparison to the Vault size."))},$$slots:{default:!0}});Guidance(node_3=sibling(node_2,2),{important:!0,title:"⚠️ Please Confirm the Following",children:($$anchor2,$$slotProps)=>{var node_7,fragment_2=root_37(),node_4=first_child(fragment_2);Check(node_4,{title:"I understand that all changes made on other smartphones or computers possibly could be lost.",get value(){return get(confirmationCheck1)},set value($$value){set(confirmationCheck1,$$value,!0)},children:($$anchor3,$$slotProps2)=>{var fragment_3=root_413(),node_5=first_child(fragment_3);InfoNote(node_5,{children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("There is a way to resolve this on other devices."))},$$slots:{default:!0}});InfoNote(sibling(node_5,2),{children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("Of course, we can back up the data before proceeding."))},$$slots:{default:!0}});append($$anchor3,fragment_3)},$$slots:{default:!0}});Check(node_7=sibling(node_4,2),{title:"I understand that other devices will no longer be able to synchronise, and will need to be reset the synchronisation information.",get value(){return get(confirmationCheck2)},set value($$value){set(confirmationCheck2,$$value,!0)},children:($$anchor3,$$slotProps2)=>{InfoNote($$anchor3,{children:($$anchor4,$$slotProps3)=>{next();append($$anchor4,text("by resetting the remote, you will be informed on other devices."))},$$slots:{default:!0}})},$$slots:{default:!0}});Check(sibling(node_7,2),{title:"I understand that this action is irreversible once performed.",get value(){return get(confirmationCheck3)},set value($$value){set(confirmationCheck3,$$value,!0)}});append($$anchor2,fragment_2)},$$slots:{default:!0}});Instruction(node_9=sibling(node_3,4),{children:($$anchor2,$$slotProps)=>{var node_11,fragment_5=root_95(),node_10=first_child(fragment_5);Question(node_10,{children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("Have you created a backup before proceeding?"))},$$slots:{default:!0}});InfoNote(node_11=sibling(node_10,2),{warning:!0,children:($$anchor3,$$slotProps2)=>{next();append($$anchor3,text("This is an extremely powerful operation. We strongly recommend that you copy your Vault folder to a safe\n location."))},$$slots:{default:!0}});Options(sibling(node_11,2),{children:($$anchor3,$$slotProps2)=>{var node_14,fragment_6=root_126(),node_13=first_child(fragment_6);Option(node_13,{selectedValue:"backup_done",title:"I have created a backup of my Vault.",get value(){return get(backupType)},set value($$value){set(backupType,$$value,!0)}});Option(node_14=sibling(node_13,2),{selectedValue:"backup_skipped",title:"I understand the risks and will proceed without a backup.",get value(){return get(backupType)},set value($$value){set(backupType,$$value,!0)}});Option(sibling(node_14,2),{selectedValue:"unable_to_backup",title:"I am unable to create a backup of my Vaults.",get value(){return get(backupType)},set value($$value){set(backupType,$$value,!0)},children:($$anchor4,$$slotProps3)=>{{let $0=user_derived((()=>"unable_to_backup"===get(backupType)));InfoNote($$anchor4,{error:!0,get visible(){return get($0)},children:($$anchor5,$$slotProps4)=>{append($$anchor5,root_144())},$$slots:{default:!0}})}},$$slots:{default:!0}});append($$anchor3,fragment_6)},$$slots:{default:!0}});append($$anchor2,fragment_5)},$$slots:{default:!0}});Instruction(node_16=sibling(node_9,2),{children:($$anchor2,$$slotProps)=>{ExtraItems($$anchor2,{title:"Advanced",children:($$anchor3,$$slotProps2)=>{Check($$anchor3,{title:"Prevent fetching configuration from server",get value(){return get(preventFetchingConfig)},set value($$value){set(preventFetchingConfig,$$value,!0)}})},$$slots:{default:!0}})},$$slots:{default:!0}});UserDecisions(sibling(node_16,2),{children:($$anchor2,$$slotProps)=>{var fragment_10=root_172(),node_18=first_child(fragment_10);let $0=user_derived((()=>!get(canProceed)));Decision(node_18,{title:"I Understand, Overwrite Server",important:!0,get disabled(){return get($0)},commit:()=>commit()});Decision(sibling(node_18,2),{title:"Cancel",commit:()=>$$props.setResult("cancelled")});append($$anchor2,fragment_10)},$$slots:{default:!0}});append($$anchor,fragment);pop()}async function fetchByAPI(request2,errorAsResult=!1){return await(0,import_obsidian.requestUrl)({...request2,throw:!errorAsResult})}function setStyle(el,styleHead,condition){if(condition()){el.addClass(`${styleHead}-enabled`);el.removeClass(`${styleHead}-disabled`)}else{el.addClass(`${styleHead}-disabled`);el.removeClass(`${styleHead}-enabled`)}}function visibleOnly(cond){return()=>({visibility:cond()})}function enableOnly(cond){return()=>({disabled:!cond()})}function getLevelStr(level){return level==LEVEL_POWER_USER?$msg("obsidianLiveSyncSettingTab.levelPowerUser"):level==LEVEL_ADVANCED?$msg("obsidianLiveSyncSettingTab.levelAdvanced"):level==LEVEL_EDGE_CASE?$msg("obsidianLiveSyncSettingTab.levelEdgeCase"):""}function findAttrFromParent(el,attr2){let current=el;for(;current;){const value=current.getAttribute(attr2);if(value)return value;current=current.parentElement}return""}function wrapMemo(func){let buf;return arg=>{if(buf!==arg){func(arg);buf=arg}}}function paneChangeLog(paneEl){var _a8,_b5;const cx2=this.createEl(paneEl,"div",{cls:"op-warn-info"},void 0,visibleOnly((()=>!this.isConfiguredAs("versionUpFlash",""))));this.createEl(cx2,"div",{text:this.editingSettings.versionUpFlash},void 0);this.createEl(cx2,"button",{text:$msg("obsidianLiveSyncSettingTab.btnGotItAndUpdated")},(e3=>{e3.addClass("mod-cta");e3.addEventListener("click",(()=>{fireAndForget((async()=>{this.editingSettings.versionUpFlash="";await this.saveAllDirtySettings()}))}))}));const informationDivEl=this.createEl(paneEl,"div",{text:""}),tmpDiv=createDiv();tmpDiv.addClass("op-warn-info");tmpDiv.innerHTML=`<p>${$msg("obsidianLiveSyncSettingTab.msgNewVersionNote")}</p><button>${$msg("obsidianLiveSyncSettingTab.optionOkReadEverything")}</button>`;if(lastVersion>((null==(_a8=this.editingSettings)?void 0:_a8.lastReadUpdates)||0)){const informationButtonDiv=informationDivEl.appendChild(tmpDiv);null==(_b5=informationButtonDiv.querySelector("button"))||_b5.addEventListener("click",(()=>{fireAndForget((async()=>{this.editingSettings.lastReadUpdates=lastVersion;await this.saveAllDirtySettings();informationButtonDiv.remove()}))}))}fireAndForget((()=>import_obsidian.MarkdownRenderer.render(this.plugin.app,updateInformation,informationDivEl,"/",this.plugin)))}function paneSetup(paneEl,{addPanel,addPane}){addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleQuickSetup")).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameConnectSetupURI")).setDesc($msg("obsidianLiveSyncSettingTab.descConnectSetupURI")).addButton((text2=>{text2.setButtonText($msg("obsidianLiveSyncSettingTab.btnUse")).onClick((()=>{this.closeSetting();eventHub.emitEvent(EVENT_REQUEST_OPEN_SETUP_URI2)}))}));new LiveSyncSetting(paneEl2).setName("Rerun Onboarding Wizard").setDesc("Rerun the onboarding wizard to set up Self-hosted LiveSync again.").addButton((text2=>{text2.setButtonText("Rerun Wizard").onClick((async()=>{const setupManager=this.plugin.getModule(SetupManager);await setupManager.onOnboard("existing-user")}))}));new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameEnableLiveSync")).setDesc($msg("obsidianLiveSyncSettingTab.descEnableLiveSync")).addOnUpdate(visibleOnly((()=>!this.isConfiguredAs("isConfigured",!0)))).addButton((text2=>{text2.setButtonText($msg("obsidianLiveSyncSettingTab.btnEnable")).onClick((async()=>{this.editingSettings.isConfigured=!0;await this.saveAllDirtySettings();this.services.appLifecycle.askRestart()}))}))}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleSetupOtherDevices"),void 0,visibleOnly((()=>this.isConfiguredAs("isConfigured",!0)))).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameCopySetupURI")).setDesc($msg("obsidianLiveSyncSettingTab.descCopySetupURI")).addButton((text2=>{text2.setButtonText($msg("obsidianLiveSyncSettingTab.btnCopy")).onClick((()=>{eventHub.emitEvent(EVENT_REQUEST_COPY_SETUP_URI2)}))}));new LiveSyncSetting(paneEl2).setName($msg("Setup.ShowQRCode")).setDesc($msg("Setup.ShowQRCode.Desc")).addButton((text2=>{text2.setButtonText($msg("Setup.ShowQRCode")).onClick((()=>{eventHub.emitEvent(EVENT_REQUEST_SHOW_SETUP_QR)}))}))}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleReset")).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameDiscardSettings")).addButton((text2=>{text2.setButtonText($msg("obsidianLiveSyncSettingTab.btnDiscard")).onClick((async()=>{if("yes"==await this.plugin.confirm.askYesNoDialog($msg("obsidianLiveSyncSettingTab.msgDiscardConfirmation"),{defaultOption:"No"})){this.editingSettings={...this.editingSettings,...DEFAULT_SETTINGS};await this.saveAllDirtySettings();this.plugin.settings={...DEFAULT_SETTINGS};await this.services.setting.saveSettingData();await this.services.database.resetDatabase();this.services.appLifecycle.askRestart()}})).setWarning()})).addOnUpdate(visibleOnly((()=>this.isConfiguredAs("isConfigured",!0))))}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleExtraFeatures")).then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("useAdvancedMode");new LiveSyncSetting(paneEl2).autoWireToggle("usePowerUserMode");new LiveSyncSetting(paneEl2).autoWireToggle("useEdgeCaseMode");this.addOnSaved("useAdvancedMode",(()=>this.display()));this.addOnSaved("usePowerUserMode",(()=>this.display()));this.addOnSaved("useEdgeCaseMode",(()=>this.display()))}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleOnlineTips")).then((paneEl2=>{const repo="vrtmrz/obsidian-livesync",topPath=$msg("obsidianLiveSyncSettingTab.linkTroubleshooting"),rawRepoURI=`https://raw.githubusercontent.com/${repo}/main`;this.createEl(paneEl2,"div","",(el=>el.innerHTML=`<a href='https://github.com/${repo}/blob/main${topPath}' target="_blank">${$msg("obsidianLiveSyncSettingTab.linkOpenInBrowser")}</a>`));const troubleShootEl=this.createEl(paneEl2,"div",{text:"",cls:"sls-troubleshoot-preview"}),loadMarkdownPage=async(pathAll,basePathParam="")=>{var _a8,_b5;troubleShootEl.style.minHeight=troubleShootEl.clientHeight+"px";troubleShootEl.empty();const directoryArr=(pathAll.startsWith("/")?pathAll:`${basePathParam}/${pathAll}`).split("/"),filename=directoryArr.pop(),basePath=directoryArr.join("/");let remoteTroubleShootMDSrc="";try{remoteTroubleShootMDSrc=await(0,import_obsidian.request)(`${rawRepoURI}${basePath}/${filename}`)}catch(ex){remoteTroubleShootMDSrc=`${$msg("obsidianLiveSyncSettingTab.logErrorOccurred")}\n${ex.toString()}`}const remoteTroubleShootMD=remoteTroubleShootMDSrc.replace(/\((.*?(.png)|(.jpg))\)/g,`(${rawRepoURI}${basePath}/$1)`);await import_obsidian.MarkdownRenderer.render(this.plugin.app,`<a class='sls-troubleshoot-anchor'></a> [${$msg("obsidianLiveSyncSettingTab.linkTipsAndTroubleshooting")}](${topPath}) [${$msg("obsidianLiveSyncSettingTab.linkPageTop")}](${filename})\n\n${remoteTroubleShootMD}`,troubleShootEl,`${rawRepoURI}`,this.plugin);null==(_b5=null==(_a8=troubleShootEl.querySelector(".sls-troubleshoot-anchor"))?void 0:_a8.parentElement)||_b5.setCssStyles({position:"sticky",top:"-1em",backgroundColor:"var(--modal-background)"});troubleShootEl.querySelectorAll("a.internal-link").forEach((anchorEl=>{anchorEl.addEventListener("click",(evt=>{fireAndForget((async()=>{const uri=anchorEl.getAttr("data-href");if(uri)if(uri.startsWith("#")){evt.preventDefault();const p4=Array.from(troubleShootEl.querySelectorAll("[data-heading]")).find((e3=>{var _a9;return(null==(_a9=e3.getAttr("data-heading"))?void 0:_a9.toLowerCase().split(" ").join("-"))==uri.substring(1).toLowerCase()}));if(p4){p4.setCssStyles({scrollMargin:"3em"});p4.scrollIntoView({behavior:"instant",block:"start"})}}else{evt.preventDefault();await loadMarkdownPage(uri,basePath);troubleShootEl.setCssStyles({scrollMargin:"1em"});troubleShootEl.scrollIntoView({behavior:"instant",block:"start"})}}))}))}));troubleShootEl.style.minHeight=""};loadMarkdownPage(topPath)}))}function paneGeneral(paneEl,{addPanel,addPane}){addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleAppearance")).then((paneEl2=>{const languages=Object.fromEntries([...SUPPORTED_I18N_LANGS.map((e3=>[e3,$t(`lang-${e3}`)]))]);new LiveSyncSetting(paneEl2).autoWireDropDown("displayLanguage",{options:languages});this.addOnSaved("displayLanguage",(()=>this.display()));new LiveSyncSetting(paneEl2).autoWireToggle("showStatusOnEditor");new LiveSyncSetting(paneEl2).autoWireToggle("showOnlyIconsOnEditor",{onUpdate:visibleOnly((()=>this.isConfiguredAs("showStatusOnEditor",!0)))});new LiveSyncSetting(paneEl2).autoWireToggle("showStatusOnStatusbar");new LiveSyncSetting(paneEl2).autoWireToggle("hideFileWarningNotice")}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleLogging")).then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireToggle("lessInformationInLog");new LiveSyncSetting(paneEl2).autoWireToggle("showVerboseLog",{onUpdate:visibleOnly((()=>this.isConfiguredAs("lessInformationInLog",!1)))})}));new LiveSyncSetting(paneEl).setClass("wizardOnly").addButton((button=>button.setButtonText($msg("obsidianLiveSyncSettingTab.btnNext")).setCta().onClick((()=>{this.changeDisplay("0")}))))}function InfoTable($$anchor,$$props){var div,div_1;append_styles($$anchor,$$css12);const infoEntries=user_derived((()=>Object.entries(null!==$$props.info&&void 0!==$$props.info?$$props.info:{})));each(div_1=child(div=root34()),21,(()=>get(infoEntries)),index,(($$anchor2,$$item)=>{var fragment,div_2,div_3,text2,div_4,div_5,text_1,$$array=user_derived((()=>to_array(get($$item),2)));let key3=()=>get($$array)[0],value=()=>get($$array)[1];fragment=root_127();div_3=child(div_2=first_child(fragment));text2=child(div_3,!0);reset(div_3);reset(div_2);div_5=child(div_4=sibling(div_2,2));text_1=child(div_5,!0);reset(div_5);reset(div_4);template_effect((()=>{set_attribute2(div_2,"aria-label",key3());set_text(text2,key3());set_attribute2(div_4,"aria-label",key3());set_text(text_1,value())}));append($$anchor2,fragment)}));reset(div_1);reset(div);append($$anchor,div)}function InfoPanel($$anchor,$$props){push($$props,!0);const $port=()=>store_get($$props.port,"$port",$$stores),[$$stores,$$cleanup]=setup_stores(),info3=user_derived((()=>{var _a8;return null!==(_a8=null===$port()||void 0===$port()?void 0:$port().info)&&void 0!==_a8?_a8:{}}));InfoTable($$anchor,{get info(){return get(info3)}});pop();$$cleanup()}function getP2PConfigSummary(setting,additional={},showAdvanced=!1){return{...getSummaryFromPartialSettings({...pickP2PSyncSettings(setting)},showAdvanced),...additional}}function getBucketConfigSummary(setting,showAdvanced=!1){return getSummaryFromPartialSettings(pickBucketSyncSettings(setting),showAdvanced)}function getCouchDBConfigSummary(setting,showAdvanced=!1){return getSummaryFromPartialSettings(pickCouchDBSyncSettings(setting),showAdvanced||setting.useJWT)}function getE2EEConfigSummary(setting,showAdvanced=!1){return getSummaryFromPartialSettings(pickEncryptionSettings(setting),showAdvanced)}function getSummaryFromPartialSettings(setting,showAdvanced=!1){const outputSummary={};for(const key3 of Object.keys(setting)){const config=getConfig(key3);if(!config)continue;if(config.isAdvanced&&!showAdvanced)continue;const value="E2EEAlgorithm"!=key3?`${setting[key3]}`:E2EEAlgorithmNames[`${setting[key3]}`],displayValue=config.isHidden?"•".repeat(value.length):escapeStringToHTML(value);outputSummary[config.name]=displayValue}return outputSummary}async function copyMigrationDocs(docName,dbFrom,dbTo){try{const doc=await dbFrom.get(docName);delete doc._rev;await dbTo.put(doc)}catch(e3){if(404===e3.status)return;throw e3}}async function migrateDatabases(operationName,from,openTo){const dbTo=await openTo();await dbTo.info();Logger(`Opening destination database for migration: ${operationName}.`,LOG_LEVEL_NOTICE,"migration");await dbTo.destroy();Logger(`Destroyed existing destination database for migration: ${operationName}.`,LOG_LEVEL_NOTICE,"migration");const dbTo2=await openTo(),info22=await dbTo2.info();console.log(info22);Logger(`Re-created destination database for migration: ${operationName}.`,LOG_LEVEL_NOTICE,"migration");const totalDocs=(await from.info()).doc_count||0;if(!(await from.replicate.to(dbTo2,{style:"all_docs"}).on("change",(info4=>{Logger(`Replicating... Docs replicated: ${info4.docs_written} / ${totalDocs}`,LOG_LEVEL_NOTICE,"migration")}))).ok)throw new Error(`Replication failed for migration: ${operationName}.`);Logger(`Replication completed for migration: ${operationName}.`,LOG_LEVEL_NOTICE,"migration");await copyMigrationDocs(MILESTONE_DOCID,from,dbTo2);await copyMigrationDocs(NODEINFO_DOCID,from,dbTo2);Logger(`Copied migration documents for migration: ${operationName}.`,LOG_LEVEL_NOTICE,"migration");await dbTo2.close();return!0}function getSettingsFromEditingSettings(editingSettings){const workObj={...editingSettings},keys3=Object.keys(OnDialogSettingsDefault);for(const k2 of keys3)delete workObj[k2];return workObj}function paneRemoteConfig(paneEl,{addPanel,addPane}){const remoteNameMap={[REMOTE_COUCHDB]:$msg("obsidianLiveSyncSettingTab.optionCouchDB"),[REMOTE_MINIO]:$msg("obsidianLiveSyncSettingTab.optionMinioS3R2"),[REMOTE_P2P]:"Only Peer-to-Peer"};{const E2EESummaryWritable=writable({info:getE2EEConfigSummary({...this.editingSettings})}),updateE2EESummary=()=>{E2EESummaryWritable.set({info:getE2EEConfigSummary(this.editingSettings)})};addPanel(paneEl,"E2EE Configuration",(()=>{})).then((paneEl2=>{new SveltePanel(InfoPanel,paneEl2,E2EESummaryWritable);new LiveSyncSetting(paneEl2).setName("Configure E2EE").addButton((button=>button.onClick((async()=>{const setupManager=this.plugin.getModule(SetupManager),originalSettings=getSettingsFromEditingSettings(this.editingSettings);await setupManager.onlyE2EEConfiguration("unknown",originalSettings);updateE2EESummary()})).setButtonText("Configure").setWarning())).addButton((button=>button.onClick((async()=>{const setupManager=this.plugin.getModule(SetupManager),originalSettings=getSettingsFromEditingSettings(this.editingSettings);await setupManager.onConfigureManually(originalSettings,"unknown");updateE2EESummary()})).setButtonText("Configure And Change Remote").setWarning()));updateE2EESummary()}))}addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleRemoteServer"),(()=>{})).then((paneEl2=>{const setting=new LiveSyncSetting(paneEl2).setName("Active Remote Configuration");setting.controlEl.createDiv({}).setText(`${remoteNameMap[this.editingSettings.remoteType]||" - "}`);setting.addButton((button=>button.setButtonText("Change Remote and Setup").setCta().onClick((async()=>{const setupManager=this.plugin.getModule(SetupManager),originalSettings=getSettingsFromEditingSettings(this.editingSettings);await setupManager.onSelectServer(originalSettings,"unknown")}))))}));{const summaryWritable=writable({info:getCouchDBConfigSummary(this.editingSettings)}),updateSummary=()=>{summaryWritable.set({info:getCouchDBConfigSummary(this.editingSettings)})};addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleCouchDB"),(()=>{})).then((paneEl2=>{new SveltePanel(InfoPanel,paneEl2,summaryWritable);new LiveSyncSetting(paneEl2).setName("Configure Remote").addButton((button=>button.setButtonText("Configure").setCta().onClick((async()=>{const setupManager=this.plugin.getModule(SetupManager),originalSettings=getSettingsFromEditingSettings(this.editingSettings);await setupManager.onCouchDBManualSetup("unknown",originalSettings,this.editingSettings.remoteType===REMOTE_COUCHDB);updateSummary()})))).addOnUpdate((()=>toggleActiveSyncClass(paneEl2,(()=>this.editingSettings.remoteType===REMOTE_COUCHDB))))}))}{const summaryWritable=writable({info:getBucketConfigSummary(this.editingSettings)}),updateSummary=()=>{summaryWritable.set({info:getBucketConfigSummary(this.editingSettings)})};addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleMinioS3R2"),(()=>{})).then((paneEl2=>{new SveltePanel(InfoPanel,paneEl2,summaryWritable);new LiveSyncSetting(paneEl2).setName("Configure Remote").addButton((button=>button.setButtonText("Configure").setCta().onClick((async()=>{const setupManager=this.plugin.getModule(SetupManager),originalSettings=getSettingsFromEditingSettings(this.editingSettings);await setupManager.onBucketManualSetup("unknown",originalSettings,this.editingSettings.remoteType===REMOTE_MINIO);updateSummary()})))).addOnUpdate((()=>toggleActiveSyncClass(paneEl2,(()=>this.editingSettings.remoteType===REMOTE_MINIO))))}))}{const getDevicePeerId=()=>this.services.config.getSmallConfig(SETTING_KEY_P2P_DEVICE_NAME)||"",summaryWritable=writable({info:getP2PConfigSummary(this.editingSettings,{"Device Peer ID":getDevicePeerId()})}),updateSummary=()=>{summaryWritable.set({info:getP2PConfigSummary(this.editingSettings,{"Device Peer ID":getDevicePeerId()})})};addPanel(paneEl,"Peer-to-Peer Synchronisation",(()=>{})).then((paneEl2=>{new SveltePanel(InfoPanel,paneEl2,summaryWritable);new LiveSyncSetting(paneEl2).setName("Configure Remote").addButton((button=>button.setButtonText("Configure").setCta().onClick((async()=>{const setupManager=this.plugin.getModule(SetupManager),originalSettings=getSettingsFromEditingSettings(this.editingSettings);await setupManager.onP2PManualSetup("unknown",originalSettings,this.editingSettings.remoteType===REMOTE_P2P);updateSummary()})))).addOnUpdate((()=>toggleActiveSyncClass(paneEl2,(()=>this.editingSettings.remoteType===REMOTE_P2P||this.editingSettings.P2P_Enabled))))}))}addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleNotification"),(()=>{})).then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireNumeric("notifyThresholdOfRemoteStorageSize",{}).setClass("wizardHidden")}))}function MultipleRegExpControl($$anchor,$$props){function revert2(){patterns([...originals()])}function checkRegExp(pattern){return isValidRegExp(pattern)?"✔":"⚠"}function remove(idx2){patterns(patterns()[idx2]="",!0)}function add(){patterns([...patterns(),""])}var ul,node,li_1,label_1,button_1,li_2,button_2,button_3;push($$props,!1);append_styles($$anchor,$$css13);const statusName=mutable_source(),modified=mutable_source(),isInvertedExp=mutable_source();let patterns=prop($$props,"patterns",28,(()=>[])),originals=prop($$props,"originals",24,(()=>[])),apply3=prop($$props,"apply",8,(_=>Promise.resolve()));legacy_pre_effect((()=>deep_read_state(patterns())),(()=>{set(statusName,patterns().map((e3=>checkRegExp(e3))))}));legacy_pre_effect((()=>(deep_read_state(patterns()),deep_read_state(originals()))),(()=>{set(modified,patterns().map(((e3,i2)=>{var _a8;return e3!=(null!==(_a8=null===originals()||void 0===originals()?void 0:originals()[i2])&&void 0!==_a8?_a8:"")?"✏ ":""})))}));legacy_pre_effect((()=>(deep_read_state(patterns()),isInvertedRegExp)),(()=>{set(isInvertedExp,patterns().map((e3=>isInvertedRegExp(e3))))}));legacy_pre_effect_reset();init();each(node=child(ul=root35()),1,patterns,index,(($$anchor2,pattern,idx2)=>{var span,text_1,input,button,li=root_128(),label2=child(li),text2=child(label2);reset(label2);span=sibling(label2,2);text_1=child(span,!0);reset(span);remove_input_defaults(input=sibling(span,2));button=sibling(input,2);reset(li);template_effect((()=>{var _a8,_b5;set_text(text2,`${null!=(_a8=(get(modified),untrack((()=>get(modified)[idx2]))))?_a8:""}${null!=(_b5=(get(statusName),untrack((()=>get(statusName)[idx2]))))?_b5:""}`);set_text(text_1,(get(isInvertedExp),untrack((()=>get(isInvertedExp)[idx2]?"INVERTED":""))));set_class(input,1,clsx2((get(modified),untrack((()=>get(modified)[idx2])))),"svelte-9kxeje")}));bind_value(input,(()=>patterns()[idx2]),($$value=>(patterns()[idx2]=$$value,invalidate_inner_signals((()=>patterns())))));event("click",button,(()=>remove(idx2)));append($$anchor2,li)}));label_1=child(li_1=sibling(node,2));button_1=child(label_1);reset(label_1);reset(li_1);li_2=sibling(li_1,2);button_2=child(li_2);button_3=sibling(button_2,2);reset(li_2);reset(ul);template_effect((($0,$1)=>{button_2.disabled=$0;button_3.disabled=$1}),[()=>(get(statusName),get(modified),untrack((()=>get(statusName).some((e3=>"⚠"===e3))||get(modified).every((e3=>""===e3))))),()=>(get(statusName),get(modified),untrack((()=>get(statusName).some((e3=>"⚠"===e3))||get(modified).every((e3=>""===e3)))))]);event("click",button_1,(()=>add()));event("click",button_2,(()=>apply3()(patterns())));event("click",button_3,(()=>revert2()));append($$anchor,ul);pop()}function paneSelector(paneEl,{addPanel}){addPanel(paneEl,"Normal Files").then((paneEl2=>{paneEl2.addClass("wizardHidden");mount(MultipleRegExpControl,{target:new LiveSyncSetting(paneEl2).setName("Synchronising files").setDesc("(RegExp) Empty to sync all files. Set filter as a regular expression to limit synchronising files.").setClass("wizardHidden").controlEl,props:{patterns:splitCustomRegExpList(this.editingSettings.syncOnlyRegEx,"|[]|"),originals:splitCustomRegExpList(this.editingSettings.syncOnlyRegEx,"|[]|"),apply:async newPatterns=>{this.editingSettings.syncOnlyRegEx=constructCustomRegExpList(newPatterns,"|[]|");await this.saveAllDirtySettings();this.display()}}});mount(MultipleRegExpControl,{target:new LiveSyncSetting(paneEl2).setName("Non-Synchronising files").setDesc("(RegExp) If this is set, any changes to local and remote files that match this will be skipped.").setClass("wizardHidden").controlEl,props:{patterns:splitCustomRegExpList(this.editingSettings.syncIgnoreRegEx,"|[]|"),originals:splitCustomRegExpList(this.editingSettings.syncIgnoreRegEx,"|[]|"),apply:async newPatterns=>{this.editingSettings.syncIgnoreRegEx=constructCustomRegExpList(newPatterns,"|[]|");await this.saveAllDirtySettings();this.display()}}});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("syncMaxSizeInMB",{clampMin:0});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("useIgnoreFiles");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireTextArea("ignoreFiles",{onUpdate:visibleOnly((()=>this.isConfiguredAs("useIgnoreFiles",!0)))})}));addPanel(paneEl,"Hidden Files",void 0,void 0,LEVEL_ADVANCED).then((paneEl2=>{const targetPatternSetting=new LiveSyncSetting(paneEl2).setName("Target patterns").setClass("wizardHidden").setDesc("Patterns to match files for syncing"),patTarget=splitCustomRegExpList(this.editingSettings.syncInternalFilesTargetPatterns,",");mount(MultipleRegExpControl,{target:targetPatternSetting.controlEl,props:{patterns:patTarget,originals:[...patTarget],apply:async newPatterns=>{this.editingSettings.syncInternalFilesTargetPatterns=constructCustomRegExpList(newPatterns,",");await this.saveAllDirtySettings();this.display()}}});const defaultSkipPattern="\\/node_modules\\/, \\/\\.git\\/, ^\\.git\\/, \\/obsidian-livesync\\/",defaultSkipPatternXPlat=defaultSkipPattern+",\\/workspace$ ,\\/workspace.json$,\\/workspace-mobile.json$",pat=splitCustomRegExpList(this.editingSettings.syncInternalFilesIgnorePatterns,",");mount(MultipleRegExpControl,{target:new LiveSyncSetting(paneEl2).setName("Ignore patterns").setClass("wizardHidden").setDesc("").controlEl,props:{patterns:pat,originals:[...pat],apply:async newPatterns=>{this.editingSettings.syncInternalFilesIgnorePatterns=constructCustomRegExpList(newPatterns,",");await this.saveAllDirtySettings();this.display()}}});const addDefaultPatterns=async patterns=>{const oldList=splitCustomRegExpList(this.editingSettings.syncInternalFilesIgnorePatterns,","),newList=splitCustomRegExpList(patterns,","),allSet=new Set([...oldList,...newList]);this.editingSettings.syncInternalFilesIgnorePatterns=constructCustomRegExpList([...allSet],",");await this.saveAllDirtySettings();this.display()};new LiveSyncSetting(paneEl2).setName("Add default patterns").setClass("wizardHidden").addButton((button=>{button.setButtonText("Default").onClick((async()=>{await addDefaultPatterns(defaultSkipPattern)}))})).addButton((button=>{button.setButtonText("Cross-platform").onClick((async()=>{await addDefaultPatterns(defaultSkipPatternXPlat)}))}));const overwritePatterns=new LiveSyncSetting(paneEl2).setName("Overwrite patterns").setClass("wizardHidden").setDesc("Patterns to match files for overwriting instead of merging"),patTarget2=splitCustomRegExpList(this.editingSettings.syncInternalFileOverwritePatterns,",");mount(MultipleRegExpControl,{target:overwritePatterns.controlEl,props:{patterns:patTarget2,originals:[...patTarget2],apply:async newPatterns=>{this.editingSettings.syncInternalFileOverwritePatterns=constructCustomRegExpList(newPatterns,",");await this.saveAllDirtySettings();this.display()}}})}))}function paneSyncSettings(paneEl,{addPanel,addPane}){this.createEl(paneEl,"div",{text:$msg("obsidianLiveSyncSettingTab.msgSelectAndApplyPreset"),cls:"wizardOnly"}).addClasses(["op-warn-info"]);addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleSynchronizationPreset")).then((paneEl2=>{const options=this.editingSettings.remoteType==REMOTE_COUCHDB?{NONE:"",LIVESYNC:$msg("obsidianLiveSyncSettingTab.optionLiveSync"),PERIODIC:$msg("obsidianLiveSyncSettingTab.optionPeriodicWithBatch"),DISABLE:$msg("obsidianLiveSyncSettingTab.optionDisableAllAutomatic")}:{NONE:"",PERIODIC:$msg("obsidianLiveSyncSettingTab.optionPeriodicWithBatch"),DISABLE:$msg("obsidianLiveSyncSettingTab.optionDisableAllAutomatic")};new LiveSyncSetting(paneEl2).autoWireDropDown("preset",{options,holdValue:!0}).addButton((button=>{button.setButtonText($msg("obsidianLiveSyncSettingTab.btnApply"));button.onClick((async()=>{await this.saveAllDirtySettings()}))}));this.addOnSaved("preset",(async currentPreset=>{if(""==currentPreset){Logger($msg("obsidianLiveSyncSettingTab.logSelectAnyPreset"),LOG_LEVEL_NOTICE);return}const presetAllDisabled={batchSave:!1,liveSync:!1,periodicReplication:!1,syncOnSave:!1,syncOnEditorSave:!1,syncOnStart:!1,syncOnFileOpen:!1,syncAfterMerge:!1},presetLiveSync={...presetAllDisabled,liveSync:!0},presetPeriodic={...presetAllDisabled,batchSave:!0,periodicReplication:!0,syncOnSave:!1,syncOnEditorSave:!1,syncOnStart:!0,syncOnFileOpen:!0,syncAfterMerge:!0};if("LIVESYNC"==currentPreset){this.editingSettings={...this.editingSettings,...presetLiveSync};Logger($msg("obsidianLiveSyncSettingTab.logConfiguredLiveSync"),LOG_LEVEL_NOTICE)}else if("PERIODIC"==currentPreset){this.editingSettings={...this.editingSettings,...presetPeriodic};Logger($msg("obsidianLiveSyncSettingTab.logConfiguredPeriodic"),LOG_LEVEL_NOTICE)}else{Logger($msg("obsidianLiveSyncSettingTab.logConfiguredDisabled"),LOG_LEVEL_NOTICE);this.editingSettings={...this.editingSettings,...presetAllDisabled}}if(this.inWizard){this.closeSetting();this.inWizard=!1;if(this.editingSettings.isConfigured)if(this.isNeedRebuildLocal()||this.isNeedRebuildRemote())await this.confirmRebuild();else{await this.saveAllDirtySettings();await this.services.setting.realiseSetting();this.services.appLifecycle.askRestart()}else{this.editingSettings.isConfigured=!0;await this.saveAllDirtySettings();await this.services.setting.realiseSetting();await this.rebuildDB("localOnly");"yes"==await this.plugin.confirm.askYesNoDialog($msg("obsidianLiveSyncSettingTab.msgGenerateSetupURI"),{defaultOption:"Yes",title:$msg("obsidianLiveSyncSettingTab.titleCongratulations")})&&eventHub.emitEvent(EVENT_REQUEST_COPY_SETUP_URI2)}}else{await this.saveAllDirtySettings();await this.services.setting.realiseSetting()}}))}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleSynchronizationMethod")).then((paneEl2=>{paneEl2.addClass("wizardHidden");const onlyOnNonLiveSync=visibleOnly((()=>!this.isConfiguredAs("syncMode","LIVESYNC"))),onlyOnPeriodic=visibleOnly((()=>this.isConfiguredAs("syncMode","PERIODIC"))),optionsSyncMode=this.editingSettings.remoteType==REMOTE_COUCHDB?{ONEVENTS:$msg("obsidianLiveSyncSettingTab.optionOnEvents"),PERIODIC:$msg("obsidianLiveSyncSettingTab.optionPeriodicAndEvents"),LIVESYNC:$msg("obsidianLiveSyncSettingTab.optionLiveSync")}:{ONEVENTS:$msg("obsidianLiveSyncSettingTab.optionOnEvents"),PERIODIC:$msg("obsidianLiveSyncSettingTab.optionPeriodicAndEvents")};new LiveSyncSetting(paneEl2).autoWireDropDown("syncMode",{options:optionsSyncMode}).setClass("wizardHidden");this.addOnSaved("syncMode",(async value=>{this.editingSettings.liveSync=!1;this.editingSettings.periodicReplication=!1;"LIVESYNC"==value?this.editingSettings.liveSync=!0:"PERIODIC"==value&&(this.editingSettings.periodicReplication=!0);await this.saveSettings(["liveSync","periodicReplication"]);await this.services.setting.realiseSetting()}));new LiveSyncSetting(paneEl2).autoWireNumeric("periodicReplicationInterval",{clampMax:5e3,onUpdate:onlyOnPeriodic}).setClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireNumeric("syncMinimumInterval",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("syncOnSave",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("syncOnEditorSave",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("syncOnFileOpen",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("syncOnStart",{onUpdate:onlyOnNonLiveSync});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("syncAfterMerge",{onUpdate:onlyOnNonLiveSync})}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleUpdateThinning"),void 0,visibleOnly((()=>!this.isConfiguredAs("syncMode","LIVESYNC")))).then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("batchSave");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("batchSaveMinimumDelay",{acceptZero:!0,onUpdate:visibleOnly((()=>this.isConfiguredAs("batchSave",!0)))});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("batchSaveMaximumDelay",{acceptZero:!0,onUpdate:visibleOnly((()=>this.isConfiguredAs("batchSave",!0)))})}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleDeletionPropagation"),void 0,void 0,LEVEL_ADVANCED).then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("trashInsteadDelete");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("doNotDeleteFolder")}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleConflictResolution"),void 0,void 0,LEVEL_ADVANCED).then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("resolveConflictsByNewerFile");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("checkConflictOnlyOnOpen");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("showMergeDialogOnlyOnActive")}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleSyncSettingsViaMarkdown"),void 0,void 0,LEVEL_ADVANCED).then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireText("settingSyncFile",{holdValue:!0}).addApplyButton(["settingSyncFile"]);new LiveSyncSetting(paneEl2).autoWireToggle("writeCredentialsForSettingSync");new LiveSyncSetting(paneEl2).autoWireToggle("notifyAllSettingSyncFile")}));addPanel(paneEl,$msg("obsidianLiveSyncSettingTab.titleHiddenFiles"),void 0,void 0,LEVEL_ADVANCED).then((paneEl2=>{paneEl2.addClass("wizardHidden");const LABEL_ENABLED=$msg("obsidianLiveSyncSettingTab.labelEnabled"),LABEL_DISABLED=$msg("obsidianLiveSyncSettingTab.labelDisabled");new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameHiddenFileSynchronization")).setClass("wizardHidden").settingEl.createDiv("").innerText=this.editingSettings.syncInternalFiles?LABEL_ENABLED:LABEL_DISABLED;this.editingSettings.syncInternalFiles?new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameDisableHiddenFileSync")).setClass("wizardHidden").addButton((button=>{button.setButtonText($msg("obsidianLiveSyncSettingTab.btnDisable")).onClick((async()=>{this.editingSettings.syncInternalFiles=!1;await this.saveAllDirtySettings();this.display()}))})):new LiveSyncSetting(paneEl2).setName($msg("obsidianLiveSyncSettingTab.nameEnableHiddenFileSync")).setClass("wizardHidden").addButton((button=>{button.setButtonText("Merge").onClick((async()=>{this.closeSetting();await this.services.setting.enableOptionalFeature("MERGE")}))})).addButton((button=>{button.setButtonText("Fetch").onClick((async()=>{this.closeSetting();await this.services.setting.enableOptionalFeature("FETCH")}))})).addButton((button=>{button.setButtonText("Overwrite").onClick((async()=>{this.closeSetting();await this.services.setting.enableOptionalFeature("OVERWRITE")}))}));new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("suppressNotifyHiddenFilesChange",{});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("syncInternalFilesBeforeReplication",{onUpdate:visibleOnly((()=>this.isConfiguredAs("watchInternalFileChanges",!0)))});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("syncInternalFilesInterval",{clampMin:10,acceptZero:!0})}))}function paneCustomisationSync(paneEl,{addPanel}){addPanel(paneEl,"Customization Sync").then((paneEl2=>{const enableOnlyOnPluginSyncIsNotEnabled=enableOnly((()=>this.isConfiguredAs("usePluginSync",!1))),visibleOnlyOnPluginSyncEnabled=visibleOnly((()=>this.isConfiguredAs("usePluginSync",!0)));this.createEl(paneEl2,"div",{text:"Please set device name to identify this device. This name should be unique among your devices. While not configured, we cannot enable this feature.",cls:"op-warn"},(c3=>{}),visibleOnly((()=>this.isConfiguredAs("deviceAndVaultName",""))));this.createEl(paneEl2,"div",{text:"We cannot change the device name while this feature is enabled. Please disable this feature to change the device name.",cls:"op-warn-info"},(c3=>{}),visibleOnly((()=>this.isConfiguredAs("usePluginSync",!0))));new LiveSyncSetting(paneEl2).autoWireText("deviceAndVaultName",{placeHolder:"desktop",onUpdate:enableOnlyOnPluginSyncIsNotEnabled});new LiveSyncSetting(paneEl2).autoWireToggle("usePluginSyncV2");new LiveSyncSetting(paneEl2).autoWireToggle("usePluginSync",{onUpdate:enableOnly((()=>!this.isConfiguredAs("deviceAndVaultName","")))});new LiveSyncSetting(paneEl2).autoWireToggle("autoSweepPlugins",{onUpdate:visibleOnlyOnPluginSyncEnabled});new LiveSyncSetting(paneEl2).autoWireToggle("autoSweepPluginsPeriodic",{onUpdate:visibleOnly((()=>this.isConfiguredAs("usePluginSync",!0)&&this.isConfiguredAs("autoSweepPlugins",!0)))});new LiveSyncSetting(paneEl2).autoWireToggle("notifyPluginOrSettingUpdated",{onUpdate:visibleOnlyOnPluginSyncEnabled});new LiveSyncSetting(paneEl2).setName("Open").setDesc("Open the dialog").addButton((button=>{button.setButtonText("Open").setDisabled(!1).onClick((()=>{eventHub.emitEvent(EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG2)}))})).addOnUpdate(visibleOnlyOnPluginSyncEnabled)}))}function paneHatch(paneEl,{addPanel}){addPanel(paneEl,$msg("Setting.TroubleShooting")).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName($msg("Setting.TroubleShooting.Doctor")).setDesc($msg("Setting.TroubleShooting.Doctor.Desc")).addButton((button=>button.setButtonText("Run Doctor").setCta().setDisabled(!1).onClick((()=>{this.closeSetting();eventHub.emitEvent(EVENT_REQUEST_RUN_DOCTOR,"you wanted(Thank you)!")}))));new LiveSyncSetting(paneEl2).setName($msg("Setting.TroubleShooting.ScanBrokenFiles")).setDesc($msg("Setting.TroubleShooting.ScanBrokenFiles.Desc")).addButton((button=>button.setButtonText("Scan for Broken files").setCta().setDisabled(!1).onClick((()=>{this.closeSetting();eventHub.emitEvent(EVENT_REQUEST_RUN_FIX_INCOMPLETE)}))));new LiveSyncSetting(paneEl2).setName("Prepare the 'report' to create an issue").addButton((button=>button.setButtonText("Copy Report to clipboard").setCta().setDisabled(!1).onClick((async()=>{let responseConfig={};const REDACTED="𝑅𝐸𝐷𝐴𝐶𝑇𝐸𝐷";if(this.editingSettings.remoteType==REMOTE_COUCHDB)try{const credential=generateCredentialObject(this.editingSettings),customHeaders=parseHeaderValues(this.editingSettings.couchDB_CustomHeaders),r4=await requestToCouchDBWithCredentials(this.editingSettings.couchDB_URI,credential,window.origin,void 0,void 0,void 0,customHeaders);Logger(JSON.stringify(r4.json,null,2));responseConfig=r4.json;responseConfig.couch_httpd_auth.secret=REDACTED;responseConfig.couch_httpd_auth.authentication_db=REDACTED;responseConfig.couch_httpd_auth.authentication_redirect=REDACTED;responseConfig.couchdb.uuid=REDACTED;responseConfig.admins=REDACTED;delete responseConfig.jwt_keys;"secret"in responseConfig.chttpd_auth&&(responseConfig.chttpd_auth.secret=REDACTED)}catch(ex){Logger(ex,LOG_LEVEL_VERBOSE);responseConfig={error:"Requesting information from the remote CouchDB has failed. If you are using IBM Cloudant, this is normal behaviour."}}else this.editingSettings.remoteType==REMOTE_MINIO&&(responseConfig={error:"Object Storage Synchronisation"});const defaultKeys=Object.keys(DEFAULT_SETTINGS),pluginConfig=JSON.parse(JSON.stringify(this.editingSettings)),pluginKeys=Object.keys(pluginConfig);for(const key3 of pluginKeys)defaultKeys.includes(key3)||delete pluginConfig[key3];pluginConfig.couchDB_DBNAME=REDACTED;pluginConfig.couchDB_PASSWORD=REDACTED;const scheme=pluginConfig.couchDB_URI.startsWith("http:")?"(HTTP)":pluginConfig.couchDB_URI.startsWith("https:")?"(HTTPS)":"";pluginConfig.couchDB_URI=isCloudantURI(pluginConfig.couchDB_URI)?"cloudant":`self-hosted${scheme}`;pluginConfig.couchDB_USER=REDACTED;pluginConfig.passphrase=REDACTED;pluginConfig.encryptedPassphrase=REDACTED;pluginConfig.encryptedCouchDBConnection=REDACTED;pluginConfig.accessKey=REDACTED;pluginConfig.secretKey=REDACTED;const redact=source2=>`${REDACTED}(${source2.length} letters)`;pluginConfig.region=redact(pluginConfig.region);pluginConfig.bucket=redact(pluginConfig.bucket);pluginConfig.pluginSyncExtendedSetting={};pluginConfig.P2P_AppID=redact(pluginConfig.P2P_AppID);pluginConfig.P2P_passphrase=redact(pluginConfig.P2P_passphrase);pluginConfig.P2P_roomID=redact(pluginConfig.P2P_roomID);pluginConfig.P2P_relays=redact(pluginConfig.P2P_relays);pluginConfig.jwtKey=redact(pluginConfig.jwtKey);pluginConfig.jwtSub=redact(pluginConfig.jwtSub);pluginConfig.jwtKid=redact(pluginConfig.jwtKid);pluginConfig.bucketCustomHeaders=redact(pluginConfig.bucketCustomHeaders);pluginConfig.couchDB_CustomHeaders=redact(pluginConfig.couchDB_CustomHeaders);pluginConfig.P2P_turnCredential=redact(pluginConfig.P2P_turnCredential);pluginConfig.P2P_turnUsername=redact(pluginConfig.P2P_turnUsername);pluginConfig.P2P_turnServers=`(${pluginConfig.P2P_turnServers.split(",").length} servers configured)`;const endpoint=pluginConfig.endpoint;if(""==endpoint)pluginConfig.endpoint="Not configured or AWS";else{const endpointScheme=pluginConfig.endpoint.startsWith("http:")?"(HTTP)":pluginConfig.endpoint.startsWith("https:")?"(HTTPS)":"";pluginConfig.endpoint=`${-1!==endpoint.indexOf(".r2.cloudflarestorage.")?"R2":"self-hosted?"}(${endpointScheme})`}const obsidianInfo={navigator:navigator.userAgent,fileSystem:this.plugin.services.vault.isStorageInsensitive()?"insensitive":"sensitive"},msgConfig=`# ---- Obsidian info ----\n${(0,import_obsidian.stringifyYaml)(obsidianInfo)}\n---\n# ---- remote config ----\n${(0,import_obsidian.stringifyYaml)(responseConfig)}\n---\n# ---- Plug-in config ----\n${(0,import_obsidian.stringifyYaml)({version:this.manifestVersion,...pluginConfig})}`;console.log(msgConfig);await this.services.UI.promptCopyToClipboard("Generated report",msgConfig)}))));new LiveSyncSetting(paneEl2).setName("Analyse database usage").setDesc("Analyse database usage and generate a TSV report for diagnosis yourself. You can paste the generated report with any spreadsheet you like.").addButton((button=>button.setButtonText("Analyse").onClick((()=>{eventHub.emitEvent(EVENT_ANALYSE_DB_USAGE)}))));new LiveSyncSetting(paneEl2).setName("Reset notification threshold and check the remote database usage").setDesc("Reset the remote storage size threshold and check the remote storage size again.").addButton((button=>button.setButtonText("Check").onClick((()=>{eventHub.emitEvent(EVENT_REQUEST_CHECK_REMOTE_SIZE)}))));new LiveSyncSetting(paneEl2).autoWireToggle("writeLogToTheFile")}));addPanel(paneEl,"Scram Switches").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("suspendFileWatching");this.addOnSaved("suspendFileWatching",(()=>this.services.appLifecycle.askRestart()));new LiveSyncSetting(paneEl2).autoWireToggle("suspendParseReplicationResult");this.addOnSaved("suspendParseReplicationResult",(()=>this.services.appLifecycle.askRestart()))}));addPanel(paneEl,"Recovery and Repair").then((paneEl2=>{const addResult=async(path2,file,fileOnDB)=>{const storageFileStat=file?await this.plugin.storageAccess.statHidden(file):null;resultArea.appendChild(this.createEl(resultArea,"div",{},(el=>{el.appendChild(this.createEl(el,"h6",{text:path2}));el.appendChild(this.createEl(el,"div",{},(infoGroupEl=>{infoGroupEl.appendChild(this.createEl(infoGroupEl,"div",{text:"Storage : Modified: "+(storageFileStat?`${new Date(storageFileStat.mtime).toLocaleString()}, Size:${storageFileStat.size}`:"Missing:")}));infoGroupEl.appendChild(this.createEl(infoGroupEl,"div",{text:"Database: Modified: "+(fileOnDB?`${new Date(fileOnDB.mtime).toLocaleString()}, Size:${fileOnDB.size} (actual size:${readAsBlob(fileOnDB).size})`:"Missing:")}))})));fileOnDB&&file&&el.appendChild(this.createEl(el,"button",{text:"Show history"},(buttonEl=>{buttonEl.onClickEvent((()=>{eventHub.emitEvent(EVENT_REQUEST_SHOW_HISTORY,{file,fileOnDB})}))})));file&&el.appendChild(this.createEl(el,"button",{text:"Storage -> Database"},(buttonEl=>{buttonEl.onClickEvent((async()=>{if(file.startsWith(".")){const addOn=this.plugin.getAddOn(HiddenFileSync.name);if(addOn){const file2=(await addOn.scanInternalFiles()).find((e3=>e3.path==path2));if(!file2){Logger(`Failed to find the file in the internal files: ${path2}`,LOG_LEVEL_NOTICE);return}if(!await addOn.storeInternalFileToDatabase(file2,!0)){Logger(`Failed to store the file to the database (Hidden file): ${file2}`,LOG_LEVEL_NOTICE);return}}}else if(!await this.plugin.fileHandler.storeFileToDB(file,!0)){Logger(`Failed to store the file to the database: ${file}`,LOG_LEVEL_NOTICE);return}el.remove()}))})));fileOnDB&&el.appendChild(this.createEl(el,"button",{text:"Database -> Storage"},(buttonEl=>{buttonEl.onClickEvent((async()=>{if(fileOnDB.path.startsWith(ICHeader)){const addOn=this.plugin.getAddOn(HiddenFileSync.name);if(addOn&&!await addOn.extractInternalFileFromDatabase(path2,!0)){Logger(`Failed to store the file to the database (Hidden file): ${file}`,LOG_LEVEL_NOTICE);return}}else if(!await this.plugin.fileHandler.dbToStorage(fileOnDB,null,!0)){Logger(`Failed to store the file to the storage: ${fileOnDB.path}`,LOG_LEVEL_NOTICE);return}el.remove()}))})));return el})))},checkBetweenStorageAndDatabase=async(file,fileOnDB)=>{const dataContent=readAsBlob(fileOnDB),content=createBlob(await this.plugin.storageAccess.readHiddenFileBinary(file));if(await isDocContentSame(content,dataContent))Logger(`Compare: SAME: ${file}`);else{Logger(`Compare: CONTENT IS NOT MATCHED! ${file}`,LOG_LEVEL_NOTICE);addResult(file,file,fileOnDB)}};new LiveSyncSetting(paneEl2).setName("Recreate missing chunks for all files").setDesc("This will recreate chunks for all files. If there were missing chunks, this may fix the errors.").addButton((button=>button.setButtonText("Recreate all").setCta().onClick((async()=>{await this.plugin.fileHandler.createAllChunks(!0)}))));new LiveSyncSetting(paneEl2).setName("Resolve All conflicted files by the newer one").setDesc("Resolve all conflicted files by the newer one. Caution: This will overwrite the older one, and cannot resurrect the overwritten one.").addButton((button=>button.setButtonText("Resolve All").setCta().onClick((async()=>{await this.plugin.rebuilder.resolveAllConflictedFilesByNewerOnes()}))));new LiveSyncSetting(paneEl2).setName("Verify and repair all files").setDesc("Compare the content of files between on local database and storage. If not matched, you will be asked which one you want to keep.").addButton((button=>button.setButtonText("Verify all").setDisabled(!1).setCta().onClick((async()=>{Logger("Start verifying all files",LOG_LEVEL_NOTICE,"verify");const ignorePatterns=getFileRegExp(this.plugin.settings,"syncInternalFilesIgnorePatterns"),targetPatterns=getFileRegExp(this.plugin.settings,"syncInternalFilesTargetPatterns");this.plugin.localDatabase.clearCaches();Logger("Start verifying all files",LOG_LEVEL_NOTICE,"verify");const files=this.plugin.settings.syncInternalFiles?await this.plugin.storageAccess.getFilesIncludeHidden("/",targetPatterns,ignorePatterns):await this.plugin.storageAccess.getFileNames(),documents=[],adn=this.plugin.localDatabase.findAllDocs();for await(const i3 of adn){const path2=getPath2(i3);path2.startsWith(ICXHeader)||path2.startsWith(PSCHeader)||!this.plugin.settings.syncInternalFiles&&path2.startsWith(ICHeader)||documents.push(stripAllPrefixes(path2))}const allPaths=[...new Set([...documents,...files])];let i2=0;const incProc=()=>{i2++;i2%25==0&&Logger(`Checking ${i2}/${allPaths.length} files \n`,LOG_LEVEL_NOTICE,"verify-processed")},semaphore=Semaphore(10),processes=allPaths.map((async path2=>{try{if(shouldBeIgnored(path2))return incProc();const stat=!!await this.plugin.storageAccess.isExistsIncludeHidden(path2)&&await this.plugin.storageAccess.statHidden(path2),fileOnStorage=null!=stat&&stat;if(!await this.services.vault.isTargetFile(path2))return incProc();const releaser=await semaphore.acquire(1);if(fileOnStorage&&this.services.vault.isFileSizeTooLarge(fileOnStorage.size))return incProc();try{const dbPath=path2.startsWith(".")?addPrefix(path2,ICHeader):path2,fileOnDB=await this.plugin.localDatabase.getDBEntry(dbPath);if(fileOnDB&&this.services.vault.isFileSizeTooLarge(fileOnDB.size))return incProc();if(!fileOnDB&&fileOnStorage){Logger(`Compare: Not found on the local database: ${path2}`,LOG_LEVEL_NOTICE);addResult(path2,path2,!1);return incProc()}if(fileOnDB&&!fileOnStorage){Logger(`Compare: Not found on the storage: ${path2}`,LOG_LEVEL_NOTICE);addResult(path2,!1,fileOnDB);return incProc()}fileOnStorage&&fileOnDB&&await checkBetweenStorageAndDatabase(path2,fileOnDB)}catch(ex){Logger(`Error while processing ${path2}`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}finally{releaser();incProc()}}catch(ex){Logger(`Error while processing without semaphore ${path2}`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}}));await Promise.all(processes);Logger("done",LOG_LEVEL_NOTICE,"verify")}))));const resultArea=paneEl2.createDiv({text:""});new LiveSyncSetting(paneEl2).setName("Check and convert non-path-obfuscated files").setDesc("").addButton((button=>button.setButtonText("Perform").setDisabled(!1).setWarning().onClick((async()=>{var _a8,_b5,_c3;for await(const docName of this.plugin.localDatabase.findAllDocNames())if(!docName.startsWith("f:")){const idEncoded=await this.services.path.path2id(docName),doc=await this.plugin.localDatabase.getRaw(docName);if(!doc)continue;if("newnote"!=doc.type&&"plain"!=doc.type)continue;if(null!=(_a8=null==doc?void 0:doc.deleted)&&_a8)continue;const newDoc={...doc};newDoc._id=idEncoded;newDoc.path=docName;delete newDoc._rev;try{const obfuscatedDoc=await this.plugin.localDatabase.getRaw(idEncoded,{revs_info:!0});null==(_b5=obfuscatedDoc._revs_info)||_b5.shift();const previousRev=null==(_c3=obfuscatedDoc._revs_info)?void 0:_c3.shift();newDoc._rev=previousRev?previousRev.rev:"1-"+`00000000000000000000000000000000${~~(1e9*Math.random())}${~~(1e9*Math.random())}${~~(1e9*Math.random())}${~~(1e9*Math.random())}`.slice(-32);const ret=await this.plugin.localDatabase.putRaw(newDoc,{force:!0});if(ret.ok){Logger(`${docName} has been converted as conflicted document`,LOG_LEVEL_NOTICE);doc._deleted=!0;(await this.plugin.localDatabase.putRaw(doc)).ok&&Logger(`Old ${docName} has been deleted`,LOG_LEVEL_NOTICE);await this.services.conflict.queueCheckForIfOpen(docName)}else{Logger(`Converting ${docName} Failed!`,LOG_LEVEL_NOTICE);Logger(ret,LOG_LEVEL_VERBOSE)}}catch(ex){if(404==(null==ex?void 0:ex.status)){if((await this.plugin.localDatabase.putRaw(newDoc)).ok){Logger(`${docName} has been converted`,LOG_LEVEL_NOTICE);doc._deleted=!0;(await this.plugin.localDatabase.putRaw(doc)).ok&&Logger(`Old ${docName} has been deleted`,LOG_LEVEL_NOTICE)}}else{Logger(`Something went wrong while converting ${docName}`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}}}Logger("Converting finished",LOG_LEVEL_NOTICE)}))))}));addPanel(paneEl,"Reset").then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Back to non-configured").addButton((button=>button.setButtonText("Back").setDisabled(!1).onClick((async()=>{this.editingSettings.isConfigured=!1;await this.saveAllDirtySettings();this.services.appLifecycle.askRestart()}))));new LiveSyncSetting(paneEl2).setName("Delete all customization sync data").addButton((button=>button.setButtonText("Delete").setDisabled(!1).setWarning().onClick((async()=>{Logger("Deleting customization sync data",LOG_LEVEL_NOTICE);const newData=(await this.plugin.localDatabase.allDocsRaw({startkey:"ix:",endkey:"ix:􏿿",include_docs:!0})).rows.map((e3=>({...e3.doc,_deleted:!0})));Logger(`${(await this.plugin.localDatabase.bulkDocsRaw(newData)).length} items have been removed, to confirm how many items are left, please perform it again.`,LOG_LEVEL_NOTICE)}))))}))}function paneAdvanced(paneEl,{addPanel}){addPanel(paneEl,"Memory cache").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireNumeric("hashCacheMaxCount",{clampMin:10})}));addPanel(paneEl,"Local Database Tweak").then((paneEl2=>{paneEl2.addClass("wizardHidden");const items=ChunkAlgorithmNames;new LiveSyncSetting(paneEl2).autoWireDropDown("chunkSplitterVersion",{options:items});new LiveSyncSetting(paneEl2).autoWireNumeric("customChunkSize",{clampMin:0,acceptZero:!0})}));addPanel(paneEl,"Transfer Tweak").then((paneEl2=>{new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("readChunksOnline",{onUpdate:this.onlyOnCouchDB});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("useOnlyLocalChunk",{onUpdate:this.onlyOnCouchDB});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("concurrencyOfReadChunksOnline",{clampMin:10,onUpdate:this.onlyOnCouchDB});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("minimumIntervalOfReadChunksOnline",{clampMin:10,onUpdate:this.onlyOnCouchDB})}))}function panePowerUsers(paneEl,{addPanel}){addPanel(paneEl,"CouchDB Connection Tweak",void 0,this.onlyOnCouchDB).then((paneEl2=>{paneEl2.addClass("wizardHidden");this.createEl(paneEl2,"div",{text:"If you reached the payload size limit when using IBM Cloudant, please decrease batch size and batch limit to a lower value."},void 0,this.onlyOnCouchDB).addClass("wizardHidden");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("batch_size",{clampMin:2,onUpdate:this.onlyOnCouchDB});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("batches_limit",{clampMin:2,onUpdate:this.onlyOnCouchDB});new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("useTimeouts",{onUpdate:this.onlyOnCouchDB})}));addPanel(paneEl,"Configuration Encryption").then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Encrypting sensitive configuration items").autoWireDropDown("configPassphraseStore",{options:{"":"Default",LOCALSTORAGE:"Use a custom passphrase",ASK_AT_LAUNCH:"Ask an passphrase at every launch"},holdValue:!0}).setClass("wizardHidden");new LiveSyncSetting(paneEl2).autoWireText("configPassphrase",{isPassword:!0,holdValue:!0}).setClass("wizardHidden").addOnUpdate((()=>({disabled:!this.isConfiguredAs("configPassphraseStore","LOCALSTORAGE")})));new LiveSyncSetting(paneEl2).addApplyButton(["configPassphrase","configPassphraseStore"]).setClass("wizardHidden")}));addPanel(paneEl,"Developer").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("enableDebugTools").setClass("wizardHidden")}))}function panePatches(paneEl,{addPanel}){addPanel(paneEl,"Compatibility (Metadata)").then((paneEl2=>{new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("deleteMetadataOfDeletedFiles");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireNumeric("automaticallyDeleteMetadataOfDeletedFiles",{onUpdate:visibleOnly((()=>this.isConfiguredAs("deleteMetadataOfDeletedFiles",!0)))})}));addPanel(paneEl,"Compatibility (Conflict Behaviour)").then((paneEl2=>{paneEl2.addClass("wizardHidden");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("disableMarkdownAutoMerge");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("writeDocumentsIfConflicted")}));addPanel(paneEl,"Compatibility (Database structure)").then((paneEl2=>{const migrateAllToIndexedDB=async()=>{const dbToName=this.plugin.localDatabase.dbname+SuffixDatabaseName+ExtraSuffixIndexedDB,options={adapter:"indexeddb",purged_infos_limit:1,auto_compaction:!1,deterministic_revs:!0};if(await migrateDatabases("to IndexedDB",this.plugin.localDatabase.localDatabase,(()=>new index_es_default(dbToName,options)))){Logger("Migration to IndexedDB completed. Obsidian will be restarted with new configuration immediately.",LOG_LEVEL_NOTICE);this.plugin.settings.useIndexedDBAdapter=!0;await this.services.setting.saveSettingData();this.services.appLifecycle.performRestart()}},migrateAllToIDB=async()=>{const dbToName=this.plugin.localDatabase.dbname+SuffixDatabaseName,options={adapter:"idb",auto_compaction:!1,deterministic_revs:!0};if(await migrateDatabases("to IDB",this.plugin.localDatabase.localDatabase,(()=>new index_es_default(dbToName,options)))){Logger("Migration to IDB completed. Obsidian will be restarted with new configuration immediately.",LOG_LEVEL_NOTICE);this.plugin.settings.useIndexedDBAdapter=!1;await this.services.setting.saveSettingData();this.services.appLifecycle.performRestart()}};{const infoClass=this.editingSettings.useIndexedDBAdapter?"op-warn":"op-warn-info";paneEl2.createDiv({text:"The IndexedDB adapter often offers superior performance in certain scenarios, but it has been found to cause memory leaks when used with LiveSync mode. When using LiveSync mode, please use IDB adapter instead.",cls:infoClass});paneEl2.createDiv({text:"Changing this setting requires migrating existing data (a bit time may be taken) and restarting Obsidian. Please make sure to back up your data before proceeding.",cls:"op-warn-info"});const setting=new LiveSyncSetting(paneEl2).setName("Database Adapter").setDesc("Select the database adapter to use. ");setting.controlEl.createDiv({}).setText("Current adapter: "+(this.editingSettings.useIndexedDBAdapter?"IndexedDB":"IDB"));this.editingSettings.useIndexedDBAdapter?setting.addButton((button=>{button.setButtonText("Switch to IDB").onClick((async()=>{Logger("Migrating all data to IDB...",LOG_LEVEL_NOTICE);await migrateAllToIDB();Logger("Migration to IDB completed. Please switch the adapter and restart Obsidian.",LOG_LEVEL_NOTICE)}))})):setting.addButton((button=>{button.setButtonText("Switch to IndexedDB").onClick((async()=>{Logger("Migrating all data to IndexedDB...",LOG_LEVEL_NOTICE);await migrateAllToIndexedDB();Logger("Migration to IndexedDB completed. Please switch the adapter and restart Obsidian.",LOG_LEVEL_NOTICE)}))}))}new LiveSyncSetting(paneEl2).autoWireToggle("handleFilenameCaseSensitive",{holdValue:!0}).setClass("wizardHidden")}));addPanel(paneEl,"Compatibility (Internal API Usage)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("watchInternalFileChanges",{invert:!0})}));addPanel(paneEl,"Compatibility (Remote Database)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireDropDown("E2EEAlgorithm",{options:E2EEAlgorithmNames})}));new LiveSyncSetting(paneEl).autoWireToggle("useDynamicIterationCount",{holdValue:!0,onUpdate:visibleOnly((()=>this.isConfiguredAs("E2EEAlgorithm",E2EEAlgorithms.ForceV1)||this.isConfiguredAs("E2EEAlgorithm",E2EEAlgorithms.V1)))});addPanel(paneEl,"Edge case addressing (Database)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireText("additionalSuffixOfDatabaseName",{holdValue:!0}).addApplyButton(["additionalSuffixOfDatabaseName"]);this.addOnSaved("additionalSuffixOfDatabaseName",(async key3=>{Logger("Suffix has been changed. Reopening database...",LOG_LEVEL_NOTICE);await this.services.databaseEvents.initialiseDatabase()}));new LiveSyncSetting(paneEl2).autoWireDropDown("hashAlg",{options:{"":"Old Algorithm",xxhash32:"xxhash32 (Fast but less collision resistance)",xxhash64:"xxhash64 (Fastest)","mixed-purejs":"PureJS fallback (Fast, W/O WebAssembly)",sha1:"Older fallback (Slow, W/O WebAssembly)"}});this.addOnSaved("hashAlg",(async()=>{await this.plugin.localDatabase._prepareHashFunctions()}))}));addPanel(paneEl,"Edge case addressing (Behaviour)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("doNotSuspendOnFetching");new LiveSyncSetting(paneEl2).setClass("wizardHidden").autoWireToggle("doNotDeleteFolder");new LiveSyncSetting(paneEl2).autoWireToggle("processSizeMismatchedFiles")}));addPanel(paneEl,"Edge case addressing (Processing)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("disableWorkerForGeneratingChunks");new LiveSyncSetting(paneEl2).autoWireToggle("processSmallFilesInUIThread",{onUpdate:visibleOnly((()=>this.isConfiguredAs("disableWorkerForGeneratingChunks",!1)))})}));addPanel(paneEl,"Compatibility (Trouble addressed)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("disableCheckingConfigMismatch")}));addPanel(paneEl,"Remote Database Tweak (In sunset)").then((paneEl2=>{new LiveSyncSetting(paneEl2).autoWireToggle("enableCompression").setClass("wizardHidden")}))}function paneMaintenance(paneEl,{addPanel}){this.createEl(paneEl,"div",{text:"The remote database is locked for synchronization to prevent vault corruption because this device isn't marked as 'resolved'. Please backup your vault, reset the local database, and select 'Mark this device as resolved'. This warning will persist until the device is confirmed as resolved by replication.",cls:"op-warn"},(c3=>{this.createEl(c3,"button",{text:"I've made a backup, mark this device 'resolved'",cls:"mod-warning"},(e3=>{e3.addEventListener("click",(()=>{fireAndForget((async()=>{await this.services.remote.markResolved();this.display()}))}))}))}),visibleOnly((()=>{var _a8,_b5;return null==(_b5=null==(_a8=this.plugin)?void 0:_a8.replicator)?void 0:_b5.remoteLockedAndDeviceNotAccepted})));this.createEl(paneEl,"div",{text:"To prevent unwanted vault corruption, the remote database has been locked for synchronization. (This device is marked 'resolved') When all your devices are marked 'resolved', unlock the database. This warning kept showing until confirming the device is resolved by the replication",cls:"op-warn"},(c3=>this.createEl(c3,"button",{text:"I'm ready, unlock the database",cls:"mod-warning"},(e3=>{e3.addEventListener("click",(()=>{fireAndForget((async()=>{await this.services.remote.markUnlocked();this.display()}))}))}))),visibleOnly((()=>{var _a8,_b5;return null==(_b5=null==(_a8=this.plugin)?void 0:_a8.replicator)?void 0:_b5.remoteLocked})));addPanel(paneEl,"Scram!").then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Lock Server").setDesc("Lock the remote server to prevent synchronization with other devices.").addButton((button=>button.setButtonText("Lock").setDisabled(!1).setWarning().onClick((async()=>{await this.services.remote.markLocked()})))).addOnUpdate(this.onlyOnCouchDBOrMinIO);new LiveSyncSetting(paneEl2).setName("Emergency restart").setDesc("Disables all synchronization and restart.").addButton((button=>button.setButtonText("Flag and restart").setDisabled(!1).setWarning().onClick((async()=>{await this.plugin.storageAccess.writeFileAuto(FLAGMD_REDFLAG,"");this.services.appLifecycle.performRestart()}))))}));addPanel(paneEl,"Reset Synchronisation information").then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Reset Synchronisation on This Device").setDesc("Restore or reconstruct local database from remote.").addButton((button=>button.setButtonText("Schedule and Restart").setCta().setDisabled(!1).onClick((async()=>{await this.plugin.storageAccess.writeFileAuto(FlagFilesHumanReadable_FETCH_ALL,"");this.services.appLifecycle.performRestart()}))));new LiveSyncSetting(paneEl2).setName("Overwrite Server Data with This Device's Files").setDesc("Rebuild local and remote database with local files.").addButton((button=>button.setButtonText("Schedule and Restart").setCta().setDisabled(!1).onClick((async()=>{await this.plugin.storageAccess.writeFileAuto(FlagFilesHumanReadable_REBUILD_ALL,"");this.services.appLifecycle.performRestart()}))))}));addPanel(paneEl,"Syncing",(()=>{}),this.onlyOnCouchDBOrMinIO).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Resend").setDesc("Resend all chunks to the remote.").addButton((button=>button.setButtonText("Send chunks").setWarning().setDisabled(!1).onClick((async()=>{this.plugin.replicator instanceof LiveSyncCouchDBReplicator&&await this.plugin.replicator.sendChunks(this.plugin.settings,void 0,!0,0)})))).addOnUpdate(this.onlyOnCouchDB);new LiveSyncSetting(paneEl2).setName("Reset journal received history").setDesc("Initialise journal received history. On the next sync, every item except this device sent will be downloaded again.").addButton((button=>button.setButtonText("Reset received").setWarning().setDisabled(!1).onClick((async()=>{await this.getMinioJournalSyncClient().updateCheckPointInfo((info3=>({...info3,receivedFiles:new Set,knownIDs:new Set})));Logger("Journal received history has been cleared.",LOG_LEVEL_NOTICE)})))).addOnUpdate(this.onlyOnMinIO);new LiveSyncSetting(paneEl2).setName("Reset journal sent history").setDesc("Initialise journal sent history. On the next sync, every item except this device received will be sent again.").addButton((button=>button.setButtonText("Reset sent history").setWarning().setDisabled(!1).onClick((async()=>{await this.getMinioJournalSyncClient().updateCheckPointInfo((info3=>({...info3,lastLocalSeq:0,sentIDs:new Set,sentFiles:new Set})));Logger("Journal sent history has been cleared.",LOG_LEVEL_NOTICE)})))).addOnUpdate(this.onlyOnMinIO)}));addPanel(paneEl,"Garbage Collection V3 (Beta)",(e3=>e3),this.onlyOnP2POrCouchDB).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Perform Garbage Collection").setDesc("Perform Garbage Collection to remove unused chunks and reduce database size.").addButton((button=>button.setButtonText("Perform Garbage Collection").setDisabled(!1).onClick((()=>{this.closeSetting();eventHub.emitEvent(EVENT_REQUEST_PERFORM_GC_V3)}))))}));addPanel(paneEl,"Rebuilding Operations (Remote Only)",(()=>{}),this.onlyOnCouchDBOrMinIO).then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Perform cleanup").setDesc("Reduces storage space by discarding all non-latest revisions. This requires the same amount of free space on the remote server and the local client.").addButton((button=>button.setButtonText("Perform").setDisabled(!1).onClick((async()=>{const replicator=this.plugin.replicator;Logger("Cleanup has been began",LOG_LEVEL_NOTICE,"compaction");await replicator.compactRemote(this.editingSettings)?Logger("Cleanup has been completed!",LOG_LEVEL_NOTICE,"compaction"):Logger("Cleanup has been failed!",LOG_LEVEL_NOTICE,"compaction")})))).addOnUpdate(this.onlyOnCouchDB);new LiveSyncSetting(paneEl2).setName("Overwrite remote").setDesc("Overwrite remote with local DB and passphrase.").addButton((button=>button.setButtonText("Send").setWarning().setDisabled(!1).onClick((async()=>{await this.rebuildDB("remoteOnly")}))));new LiveSyncSetting(paneEl2).setName("Reset all journal counter").setDesc("Initialise all journal history, On the next sync, every item will be received and sent.").addButton((button=>button.setButtonText("Reset all").setWarning().setDisabled(!1).onClick((async()=>{await this.getMinioJournalSyncClient().resetCheckpointInfo();Logger("Journal exchange history has been cleared.",LOG_LEVEL_NOTICE)})))).addOnUpdate(this.onlyOnMinIO);new LiveSyncSetting(paneEl2).setName("Purge all journal counter").setDesc("Purge all download/upload cache.").addButton((button=>button.setButtonText("Reset all").setWarning().setDisabled(!1).onClick((async()=>{await this.getMinioJournalSyncClient().resetAllCaches();Logger("Journal download/upload cache has been cleared.",LOG_LEVEL_NOTICE)})))).addOnUpdate(this.onlyOnMinIO);new LiveSyncSetting(paneEl2).setName("Fresh Start Wipe").setDesc("Delete all data on the remote server.").addButton((button=>button.setButtonText("Delete").setWarning().setDisabled(!1).onClick((async()=>{await this.getMinioJournalSyncClient().updateCheckPointInfo((info3=>({...info3,receivedFiles:new Set,knownIDs:new Set,lastLocalSeq:0,sentIDs:new Set,sentFiles:new Set})));await this.resetRemoteBucket();Logger("Deleted all data on remote server",LOG_LEVEL_NOTICE)})))).addOnUpdate(this.onlyOnMinIO)}));addPanel(paneEl,"Reset").then((paneEl2=>{new LiveSyncSetting(paneEl2).setName("Delete local database to reset or uninstall Self-hosted LiveSync").addButton((button=>button.setButtonText("Delete").setWarning().setDisabled(!1).onClick((async()=>{await this.services.database.resetDatabase();await this.services.databaseEvents.initialiseDatabase()}))))}))}function createStub(name,key3,value,panel,pane){var _a8;{pane in stubs||(stubs[pane]={});panel in stubs[pane]||(stubs[pane][panel]=new Map);const old=null!=(_a8=stubs[pane][panel].get(name))?_a8:{};stubs[pane][panel].set(name,{...old,[key3]:value});scheduleTask("update-stub",100,(()=>{eventHub.emitEvent("document-stub-created",{toc,stub:stubs})}))}}function isImage(path2){const ext2=path2.split(".").splice(-1)[0].toLowerCase();return["png","jpg","jpeg","gif","bmp","webp"].includes(ext2)}function isComparableText(path2){const ext2=path2.split(".").splice(-1)[0].toLowerCase();return isPlainText(path2)||["md","mdx","txt","json"].includes(ext2)}function isComparableTextDecode(path2){const ext2=path2.split(".").splice(-1)[0].toLowerCase();return["json"].includes(ext2)}function readDocument(w2){if(0==w2.data.length)return"";if(isImage(w2.path))return new Uint8Array(decodeBinary(w2.data));if("plain"==w2.type||"plain"==w2.datatype)return getDocData(w2.data);if(isComparableTextDecode(w2.path))return readString(new Uint8Array(decodeBinary(w2.data)));if(isComparableText(w2.path))return getDocData(w2.data);try{return readString(new Uint8Array(decodeBinary(w2.data)))}catch(ex){Logger(ex,LOG_LEVEL_VERBOSE)}return getDocData(w2.data)}function GlobalHistory($$anchor,$$props){function mtimeToDate(mtime){return new Date(mtime).toLocaleString()}async function fetchChanges(){var _a8,_b5,_c3;try{const db=plugin3().localDatabase;let result=[];for await(const docA of db.findAllNormalDocs()){if(docA.mtime<get(range_from_epoch))continue;if(!isAnyNote(docA))continue;const path2=getPath2(docA),isPlain=isPlainText(docA.path);let p4;const reversedRevs=(null!==(_a8=(await db.getRaw(docA._id,{revs_info:!0}))._revs_info)&&void 0!==_a8?_a8:[]).reverse(),DIFF_DELETE4=-1,DIFF_EQUAL4=0,DIFF_INSERT4=1;for(const revInfo of reversedRevs)if("available"==revInfo.status){const doc=!isPlain&&get(showDiffInfo)||get(checkStorageDiff)&&revInfo.rev==docA._rev?await db.getDBEntry(path2,{rev:revInfo.rev},!1,!1,!0):await db.getDBEntryMeta(path2,{rev:revInfo.rev},!0);if(!1===doc)continue;const rev3=revInfo.rev,mtime="mtime"in doc?doc.mtime:0;if(get(range_from_epoch)>mtime)continue;if(get(range_to_epoch)<mtime)continue;let diffDetail="";if(get(showDiffInfo)&&!isPlain){const data=getDocData(doc.data);void 0===p4&&(p4=data);if(p4!=data){const dmp=new import_diff_match_patch.diff_match_patch,diff=dmp.diff_main(p4,data);dmp.diff_cleanupSemantic(diff);p4=data;const pxInit={[DIFF_DELETE4]:0,[DIFF_EQUAL4]:0,[DIFF_INSERT4]:0},px=diff.reduce(((p5,c3)=>{var _a9;return{...p5,[c3[0]]:(null!==(_a9=p5[c3[0]])&&void 0!==_a9?_a9:0)+c3[1].length}}),pxInit);diffDetail=`-${px[DIFF_DELETE4]}, +${px[DIFF_INSERT4]}`}}const isDeleted2=doc._deleted||(null==doc?void 0:doc.deleted)||!1;isDeleted2&&(diffDetail+=" 🗑️");if(rev3==docA._rev&&get(checkStorageDiff)&&await plugin3().storageAccess.isExistsIncludeHidden(stripAllPrefixes(getPath2(docA)))){const data=await plugin3().storageAccess.readHiddenFileBinary(stripAllPrefixes(getPath2(docA))),d4=readAsBlob(doc);diffDetail+=await isDocContentSame(data,d4)?" ⚖️":" ⚠️"}const docPath=getPath2(doc),[filename,...pathItems]=docPath.split("/").reverse();let chunksStatus="";if(get(showChunkCorrected)){const chunks=null!==(_b5=null==doc?void 0:doc.children)&&void 0!==_b5?_b5:[],loadedChunks=await db.allDocsRaw({keys:[...chunks]}),totalCount=loadedChunks.rows.length,errorCount=loadedChunks.rows.filter((e3=>"error"in e3)).length;chunksStatus=0==errorCount?`✅ ${totalCount}`:`🔎 ${errorCount} ✅ ${totalCount}`}result.push({id:doc._id,rev:doc._rev,path:docPath,dirname:pathItems.reverse().join("/"),filename,mtime,mtimeDisp:mtimeToDate(mtime),size:null!==(_c3=null==doc?void 0:doc.size)&&void 0!==_c3?_c3:0,isDeleted:isDeleted2,changes:diffDetail,chunks:chunksStatus,isPlain})}}return[...result].sort(((a2,b3)=>b3.mtime-a2.mtime))}finally{set(loading,!1)}}async function getHistory(showDiffInfo2,showChunkCorrected2,checkStorageDiff2){set(loading,!0);const newDisplay=[],page=await fetchChanges();newDisplay.push(...page);set(history,[...newDisplay])}function nextWeek(){set(dispDateTo,new Date(get(range_to_epoch)-timezoneOffset+6048e5).toISOString().split("T")[0])}function prevWeek(){set(dispDateFrom,new Date(get(range_from_epoch)-timezoneOffset-6048e5).toISOString().split("T")[0])}function showHistory(file,rev3){new DocumentHistoryModal(plugin3().app,plugin3(),file,void 0,rev3).open()}function openFile(file){plugin3().app.workspace.openLinkText(file,file)}var div,div_1,div_2,input,div_3,input_1,div_4,label2,input_2,label_1,input_3,label_2,input_4,node,consequent,table2,tbody,tr,node_1,consequent_1,tr_1,td3,node_2,consequent_2,alternate,node_3,tr_3,td_6,node_6,consequent_5,alternate_2;push($$props,!1);append_styles($$anchor,$$css14);let plugin3=prop($$props,"plugin",8),showDiffInfo=mutable_source(!1),showChunkCorrected=mutable_source(!1),checkStorageDiff=mutable_source(!1),range_from_epoch=mutable_source(Date.now()-6048e5),range_to_epoch=mutable_source(Date.now()+1728e5);const timezoneOffset=(new Date).getTimezoneOffset();let dispDateFrom=mutable_source(new Date(get(range_from_epoch)-timezoneOffset).toISOString().split("T")[0]),dispDateTo=mutable_source(new Date(get(range_to_epoch)-timezoneOffset).toISOString().split("T")[0]),history=mutable_source([]),loading=mutable_source(!1);onMount((async()=>{await getHistory(get(showDiffInfo),get(showChunkCorrected),get(checkStorageDiff))}));onDestroy((()=>{}));legacy_pre_effect((()=>(get(dispDateFrom),get(dispDateTo),get(showDiffInfo),get(showChunkCorrected),get(checkStorageDiff))),(()=>{set(range_from_epoch,new Date(get(dispDateFrom)).getTime()+timezoneOffset);set(range_to_epoch,new Date(get(dispDateTo)).getTime()+timezoneOffset);getHistory(get(showDiffInfo),get(showChunkCorrected),get(checkStorageDiff))}));legacy_pre_effect_reset();init();div_1=sibling(child(div=root36()),2);div_2=child(div_1);remove_input_defaults(input=sibling(child(div_2)));reset(div_2);div_3=sibling(div_2,2);remove_input_defaults(input_1=sibling(child(div_3)));reset(div_3);div_4=sibling(div_3,2);label2=sibling(child(div_4),2);remove_input_defaults(input_2=child(label2));next();reset(label2);label_1=sibling(label2,2);remove_input_defaults(input_3=child(label_1));next();reset(label_1);label_2=sibling(label_1,2);remove_input_defaults(input_4=child(label_2));next();reset(label_2);reset(div_4);reset(div_1);node=sibling(div_1,2);consequent=$$anchor2=>{append($$anchor2,root_129())};if_block(node,($$render=>{get(loading)&&$$render(consequent)}));tbody=child(table2=sibling(node,2));tr=child(tbody);node_1=sibling(child(tr),4);consequent_1=$$anchor2=>{append($$anchor2,root_218())};if_block(node_1,($$render=>{get(showChunkCorrected)&&$$render(consequent_1)}));reset(tr);td3=child(tr_1=sibling(tr));node_2=child(td3);consequent_2=$$anchor2=>{append($$anchor2,root_38())};alternate=$$anchor2=>{var div_7=root_414(),button=child(div_7);reset(div_7);event("click",button,(()=>nextWeek()));append($$anchor2,div_7)};if_block(node_2,($$render=>{get(loading)?$$render(consequent_2):$$render(alternate,!1)}));reset(td3);reset(tr_1);each(node_3=sibling(tr_1),1,(()=>get(history)),index,(($$anchor2,entry)=>{var td_2,div_8,span,text_1,span_1,a_1,text_2,td_3,span_2,node_4,consequent_3,alternate_1,td_4,text_5,node_5,consequent_4,tr_2=root_55(),td_1=child(tr_2),text2=child(td_1,!0);reset(td_1);div_8=child(td_2=sibling(td_1));span=child(div_8);text_1=child(span);reset(span);a_1=child(span_1=sibling(span,2));text_2=child(a_1,!0);reset(a_1);reset(span_1);reset(div_8);reset(td_2);span_2=child(td_3=sibling(td_2));node_4=child(span_2);consequent_3=$$anchor3=>{var a_2=root_67(),text_3=child(a_2,!0);reset(a_2);template_effect((()=>set_text(text_3,(get(entry),untrack((()=>get(entry).rev))))));event("click",a_2,(()=>{var _a8;return showHistory(get(entry).path,(null==(_a8=get(entry))?void 0:_a8.rev)||"")}));append($$anchor3,a_2)};alternate_1=$$anchor3=>{var text_4=text();template_effect((()=>set_text(text_4,(get(entry),untrack((()=>get(entry).rev))))));append($$anchor3,text_4)};if_block(node_4,($$render=>{get(entry),untrack((()=>get(entry).isPlain))?$$render(consequent_3):$$render(alternate_1,!1)}));reset(span_2);reset(td_3);td_4=sibling(td_3);text_5=child(td_4,!0);reset(td_4);node_5=sibling(td_4);consequent_4=$$anchor3=>{var td_5=root_810(),text_6=child(td_5,!0);reset(td_5);template_effect((()=>set_text(text_6,(get(entry),untrack((()=>get(entry).chunks))))));append($$anchor3,td_5)};if_block(node_5,($$render=>{get(showChunkCorrected)&&$$render(consequent_4)}));reset(tr_2);template_effect(($0=>{set_text(text2,(get(entry),untrack((()=>get(entry).mtimeDisp))));set_text(text_1,`/${null!=$0?$0:""}`);set_text(text_2,(get(entry),untrack((()=>get(entry).filename))));set_text(text_5,(get(entry),untrack((()=>get(entry).changes))))}),[()=>(get(entry),untrack((()=>get(entry).dirname.split("/").join("/"))))]);event("click",a_1,(()=>openFile(get(entry).path)));append($$anchor2,tr_2)}));td_6=child(tr_3=sibling(node_3));node_6=child(td_6);consequent_5=$$anchor2=>{append($$anchor2,root_96())};alternate_2=$$anchor2=>{var div_10=root_105(),button_1=child(div_10);reset(div_10);event("click",button_1,(()=>prevWeek()));append($$anchor2,div_10)};if_block(node_6,($$render=>{get(loading)?$$render(consequent_5):$$render(alternate_2,!1)}));reset(td_6);reset(tr_3);reset(tbody);reset(table2);reset(div);template_effect((()=>{input.disabled=get(loading);input_1.disabled=get(loading);input_2.disabled=get(loading);input_3.disabled=get(loading);input_4.disabled=get(loading)}));bind_value(input,(()=>get(dispDateFrom)),($$value=>set(dispDateFrom,$$value)));bind_value(input_1,(()=>get(dispDateTo)),($$value=>set(dispDateTo,$$value)));bind_checked(input_2,(()=>get(showDiffInfo)),($$value=>set(showDiffInfo,$$value)));bind_checked(input_3,(()=>get(showChunkCorrected)),($$value=>set(showChunkCorrected,$$value)));bind_checked(input_4,(()=>get(checkStorageDiff)),($$value=>set(checkStorageDiff,$$value)));append($$anchor,div);pop()}async function*withConcurrency(iterable,callback,concurrency){const processes=new Set,mapTaskToPromise=new Map;let serial=0;const enqueue=item=>{const idx2=serial++,promise=(async()=>[idx2,await callback(item)])();processes.add(promise);mapTaskToPromise.set(idx2,promise)},consume=async()=>{const r4=await Promise.race(processes),item=mapTaskToPromise.get(r4[0]);processes.delete(item);mapTaskToPromise.delete(r4[0]);return r4[1]};for await(const t3 of iterable){for(;processes.size>=concurrency;)yield await consume();enqueue(t3)}for(;processes.size>0;)yield await consume()}function getIdbProxyableTypes(){return idbProxyableTypes||(idbProxyableTypes=[IDBDatabase,IDBObjectStore,IDBIndex,IDBCursor,IDBTransaction])}function getCursorAdvanceMethods(){return cursorAdvanceMethods||(cursorAdvanceMethods=[IDBCursor.prototype.advance,IDBCursor.prototype.continue,IDBCursor.prototype.continuePrimaryKey])}function promisifyRequest(request2){const promise=new Promise(((resolve,reject)=>{const unlisten=()=>{request2.removeEventListener("success",success);request2.removeEventListener("error",error)},success=()=>{resolve(wrap(request2.result));unlisten()},error=()=>{reject(request2.error);unlisten()};request2.addEventListener("success",success);request2.addEventListener("error",error)}));reverseTransformCache.set(promise,request2);return promise}function cacheDonePromiseForTransaction(tx){if(transactionDoneMap.has(tx))return;const done=new Promise(((resolve,reject)=>{const unlisten=()=>{tx.removeEventListener("complete",complete);tx.removeEventListener("error",error);tx.removeEventListener("abort",error)},complete=()=>{resolve();unlisten()},error=()=>{reject(tx.error||new DOMException("AbortError","AbortError"));unlisten()};tx.addEventListener("complete",complete);tx.addEventListener("error",error);tx.addEventListener("abort",error)}));transactionDoneMap.set(tx,done)}function replaceTraps(callback){idbProxyTraps=callback(idbProxyTraps)}function wrapFunction(func){return getCursorAdvanceMethods().includes(func)?function(...args){func.apply(unwrap(this),args);return wrap(this.request)}:function(...args){return wrap(func.apply(unwrap(this),args))}}function transformCachableValue(value){if("function"==typeof value)return wrapFunction(value);value instanceof IDBTransaction&&cacheDonePromiseForTransaction(value);return instanceOfAny(value,getIdbProxyableTypes())?new Proxy(value,idbProxyTraps):value}function wrap(value){if(value instanceof IDBRequest)return promisifyRequest(value);if(transformCache.has(value))return transformCache.get(value);const newValue=transformCachableValue(value);if(newValue!==value){transformCache.set(value,newValue);reverseTransformCache.set(newValue,value)}return newValue}function openDB(name,version2,{blocked,upgrade,blocking,terminated}={}){const request2=indexedDB.open(name,version2),openPromise=wrap(request2);upgrade&&request2.addEventListener("upgradeneeded",(event2=>{upgrade(wrap(request2.result),event2.oldVersion,event2.newVersion,wrap(request2.transaction),event2)}));blocked&&request2.addEventListener("blocked",(event2=>blocked(event2.oldVersion,event2.newVersion,event2)));openPromise.then((db=>{terminated&&db.addEventListener("close",(()=>terminated()));blocking&&db.addEventListener("versionchange",(event2=>blocking(event2.oldVersion,event2.newVersion,event2)))})).catch((()=>{}));return openPromise}function deleteDB(name,{blocked}={}){const request2=indexedDB.deleteDatabase(name);blocked&&request2.addEventListener("blocked",(event2=>blocked(event2.oldVersion,event2)));return wrap(request2).then((()=>{}))}function getMethod(target,prop2){if(!(target instanceof IDBDatabase)||prop2 in target||"string"!=typeof prop2)return;if(cachedMethods.get(prop2))return cachedMethods.get(prop2);const targetFuncName=prop2.replace(/FromIndex$/,""),useIndex=prop2!==targetFuncName,isWrite=writeMethods.includes(targetFuncName);if(!(targetFuncName in(useIndex?IDBIndex:IDBObjectStore).prototype)||!isWrite&&!readMethods.includes(targetFuncName))return;const method=async function(storeName,...args){const tx=this.transaction(storeName,isWrite?"readwrite":"readonly");let target2=tx.store;useIndex&&(target2=target2.index(args.shift()));return(await Promise.all([target2[targetFuncName](...args),isWrite&&tx.done]))[0]};cachedMethods.set(prop2,method);return method}async function*iterate(...args){let cursor=this;cursor instanceof IDBCursor||(cursor=await cursor.openCursor(...args));if(!cursor)return;const proxiedCursor=new Proxy(cursor,cursorIteratorTraps);ittrProxiedCursorToOriginalProxy.set(proxiedCursor,cursor);reverseTransformCache.set(proxiedCursor,unwrap(cursor));for(;cursor;){yield proxiedCursor;cursor=await(advanceResults.get(proxiedCursor)||cursor.continue());advanceResults.delete(proxiedCursor)}}function isIteratorProp(target,prop2){return prop2===Symbol.asyncIterator&&instanceOfAny(target,[IDBIndex,IDBObjectStore,IDBCursor])||"iterate"===prop2&&instanceOfAny(target,[IDBIndex,IDBObjectStore])}async function OpenKeyValueDatabase(dbKey){return await serialized(`OpenKeyValueDatabase-${dbKey}`,(async()=>{const cachedDB=databaseCache.get(dbKey);if(cachedDB){if(!cachedDB.isDestroyed)return cachedDB;await cachedDB.ensuredDestroyed;databaseCache.delete(dbKey)}const newDB=new IDBKeyValueDatabase(dbKey);try{await newDB.getIsReady();databaseCache.set(dbKey,newDB);return newDB}catch(e3){databaseCache.delete(dbKey);throw e3}}))}async function purgeUnreferencedChunks(db,dryRun,connSetting,performCompact=!1){const info3=await db.info();let resultCount=0;const getSize=function(info4,key3){var _a8,_b5;return Number.parseInt(null!=(_b5=null==(_a8=null==info4?void 0:info4.sizes)?void 0:_a8[key3])?_b5:0)},keySuffix=connSetting?"-remote":"-local";Logger(`${dryRun?"Counting":"Cleaning"} ${connSetting?"remote":"local"} database`,LOG_LEVEL_NOTICE);connSetting&&Logger(`Database active-size: ${sizeToHumanReadable(getSize(info3,"active"))}, external-size:${sizeToHumanReadable(getSize(info3,"external"))}, file-size: ${sizeToHumanReadable(getSize(info3,"file"))}`,LOG_LEVEL_NOTICE);Logger(`Collecting unreferenced chunks on ${info3.db_name}`,LOG_LEVEL_NOTICE,"gc-count-chunk"+keySuffix);const chunks=await collectUnreferencedChunks(db);resultCount=chunks.length;if(0==chunks.length)Logger(`No unreferenced chunks! ${info3.db_name}`,LOG_LEVEL_NOTICE,"gc-count-chunk"+keySuffix);else{Logger(`Number of unreferenced chunks on ${info3.db_name}: ${chunks.length}`,LOG_LEVEL_NOTICE,"gc-count-chunk"+keySuffix);if(dryRun){Logger(`DryRun of cleaning ${connSetting?"remote":"local"} database up: Done`,LOG_LEVEL_NOTICE);return resultCount}if(connSetting){Logger("Cleaning unreferenced chunks on remote",LOG_LEVEL_NOTICE,"gc-purge"+keySuffix);await purgeChunksRemote(connSetting,chunks)}else{Logger("Cleaning unreferenced chunks on local",LOG_LEVEL_NOTICE,"gc-purge"+keySuffix);await purgeChunksLocal(db,chunks)}Logger("Cleaning unreferenced chunks done!",LOG_LEVEL_NOTICE,"gc-purge"+keySuffix)}if(performCompact){Logger("Compacting database...",LOG_LEVEL_NOTICE,"gc-compact"+keySuffix);await db.compact();Logger("Compacting database done",LOG_LEVEL_NOTICE,"gc-compact"+keySuffix)}if(connSetting){const endInfo=await db.info();Logger(`Processed database active-size: ${sizeToHumanReadable(getSize(endInfo,"active"))}, external-size:${sizeToHumanReadable(getSize(endInfo,"external"))}, file-size: ${sizeToHumanReadable(getSize(endInfo,"file"))}`,LOG_LEVEL_NOTICE);Logger(`Reduced sizes: active-size: ${sizeToHumanReadable(getSize(info3,"active")-getSize(endInfo,"active"))}, external-size:${sizeToHumanReadable(getSize(info3,"external")-getSize(endInfo,"external"))}, file-size: ${sizeToHumanReadable(getSize(info3,"file")-getSize(endInfo,"file"))}`,LOG_LEVEL_NOTICE)}Logger(`Cleaning ${connSetting?"remote":"local"} database up: Done`,LOG_LEVEL_NOTICE);return resultCount}function transferChunks(key3,label2,dbFrom,dbTo,items){let totalProcessed=0;const total=items.length;return new QueueProcessor((async batched=>{const requestItems=batched.map((e3=>e3.id));return(await dbTo.allDocs({keys:requestItems})).rows.filter((e3=>"error"in e3&&"not_found"==e3.error)).map((e3=>e3.key))}),{batchSize:50,concurrentLimit:5,suspended:!0,delay:100},items).pipeTo(new QueueProcessor((async chunkIds=>(await dbFrom.allDocs({keys:chunkIds,include_docs:!0})).rows.filter((e3=>!("error"in e3))).map((e3=>e3.doc))),{batchSize:25,concurrentLimit:1,suspended:!0,delay:100})).pipeTo(new QueueProcessor((async docs=>{try{await dbTo.bulkDocs(docs,{new_edits:!1})}catch(ex){Logger(`${label2}: Something went wrong on balancing`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}finally{totalProcessed+=docs.length;Logger(`${label2}: ${totalProcessed} / ${total}`,LOG_LEVEL_NOTICE,"balance-"+key3)}}),{batchSize:100,delay:100,concurrentLimit:2,suspended:!1})).startPipeline().waitForAllDoneAndTerminate()}async function balanceChunkPurgedDBs(local,remote){Logger("Complement missing chunks between databases",LOG_LEVEL_NOTICE);try{const{onlyOnLocal,onlyOnRemote}=await collectUnbalancedChunkIDs(local,remote),localToRemote=transferChunks("l2r","local -> remote",local,remote,onlyOnLocal),remoteToLocal=transferChunks("r2l","remote -> local",remote,local,onlyOnRemote);await Promise.all([localToRemote,remoteToLocal]);Logger("local -> remote: Done",LOG_LEVEL_NOTICE,"balance-l2r");Logger("remote -> local: Done",LOG_LEVEL_NOTICE,"balance-r2l")}catch(ex){Logger("Something went wrong on balancing!",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}Logger("Complement completed!",LOG_LEVEL_NOTICE)}async function fetchAllUsedChunks(local,remote){try{const chunksOnRemote=await collectChunks(remote,"INUSE");await transferChunks("r2l","remote -> local",remote,local,chunksOnRemote);Logger("remote -> local: Done",LOG_LEVEL_NOTICE,"balance-r2l")}catch(ex){Logger("Something went wrong on balancing!",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE)}}async function purgeChunksLocal(db,docs){await serialized("purge-local",(async()=>{try{Logger(`Purging unused ${docs.length} chunks `,LOG_LEVEL_NOTICE,"purge-local-backup");const batchDocsBackup=arrayToChunkedArray(docs,100);let total={ok:0,exist:0,error:0};for(const docsInBatch of batchDocsBackup){const backupDocs=(await db.allDocs({keys:docsInBatch.map((e3=>e3.id)),include_docs:!0})).rows.filter((e3=>"doc"in e3)).map((e3=>{const chunk={...e3.doc};delete chunk._rev;chunk._id=`_local/${chunk._id}`;return chunk})),ret=await db.bulkDocs(backupDocs);total=ret.map((e3=>({ok:"ok"in e3?1:0,exist:"status"in e3&&409==e3.status?1:0,error:"status"in e3&&409!=e3.status?1:0}))).reduce(((p4,c3)=>({ok:p4.ok+c3.ok,exist:p4.exist+c3.exist,error:p4.error+c3.error})),total);Logger(`Local chunk backed up: new:${total.ok} ,exist:${total.exist}, error:${total.error}`,LOG_LEVEL_NOTICE,"purge-local-backup");const erroredItems=ret.filter((e3=>"error"in e3&&409!=e3.status));for(const item of erroredItems)Logger(`Failed to back up: ${item.id} / ${item.rev}`,LOG_LEVEL_VERBOSE)}}catch(ex){Logger("Could not back up chunks");Logger(ex,LOG_LEVEL_VERBOSE)}Logger(`Purging unused ${docs.length} chunks... `,LOG_LEVEL_NOTICE,"purge-local");const batchDocs=arrayToChunkedArray(docs,100);let totalRemoved=0;for(const docsInBatch of batchDocs){const removed=await db.purgeMulti(docsInBatch.map((e3=>[e3.id,e3.rev])));totalRemoved+=Object.values(removed).filter((e3=>"ok"in e3)).length;Logger(`Purging: ${totalRemoved} / ${docs.length}`,LOG_LEVEL_NOTICE,"purge-local")}Logger(`Purging unused chunks done!: ${totalRemoved} chunks has been deleted.`,LOG_LEVEL_NOTICE,"purge-local")}))}async function collectUnbalancedChunkIDs(local,remote){const chunksOnLocal=await collectChunks(local,"INUSE"),chunksOnRemote=await collectChunks(remote,"INUSE");return{onlyOnLocal:chunksOnLocal.filter((e3=>!chunksOnRemote.some((ee=>ee.id==e3.id)))),onlyOnRemote:chunksOnRemote.filter((e3=>!chunksOnLocal.some((ee=>ee.id==e3.id))))}}async function collectChunks(db,type){const rows=await collectChunksUsage(db),ids=("ALL"==type?rows:rows.filter((e3=>"DANGLING"==type?0==e3.value:0!=e3.value))).flatMap((e3=>e3.key));return(await db.allDocs({keys:ids})).rows.filter((e3=>!("error"in e3))).map((e3=>({id:e3.id,rev:e3.value.rev})))}async function prepareChunkDesignDoc(db){var _a8;const chunkDesignDoc={_id:"_design/chunks",_rev:void 0,ver:2,views:{collectDangling:{map:(function(doc){doc._id.startsWith("h:")?emit([doc._id],0):"children"in doc&&doc.children.forEach((e3=>emit([e3],1)))}).toString(),reduce:"_sum"}}};let updateDDoc=!1;try{const old=await db.get(chunkDesignDoc._id);if(null!=(_a8=null==old?void 0:old.ver)?_a8:0<chunkDesignDoc.ver){chunkDesignDoc._rev=old._rev;updateDDoc=!0}}catch(ex){if(404!=ex.status){Logger("Failed to make design document for operating chunks");Logger(ex,LOG_LEVEL_VERBOSE);return!1}updateDDoc=!0}try{updateDDoc&&await db.put(chunkDesignDoc)}catch(ex){Logger("Failed to make design document for operating chunks");Logger(ex,LOG_LEVEL_VERBOSE);return!1}return!0}async function collectChunksUsage(db){if(!await prepareChunkDesignDoc(db)){Logger("Could not prepare design document for operating chunks");return[]}return(await db.query("chunks/collectDangling",{reduce:!0,group:!0})).rows}function collectUnreferencedChunks(db){return collectChunks(db,"DANGLING")}async function purgeChunksRemote(setting,docs){await serialized("purge-remote",(async()=>{const buffer=function makeChunkedArrayFromArray(items){const chunked=[];for(let i2=0;i2<items.length;i2+=100)chunked.push(items.slice(i2,i2+100));return chunked}(docs);for(const chunkedPayload of buffer){const rets=await _requestToCouchDBFetch(`${setting.couchDB_URI}/${setting.couchDB_DBNAME}`,setting.couchDB_USER,setting.couchDB_PASSWORD,"_purge",Object.fromEntries(chunkedPayload.map((e3=>[e3.id,[e3.rev]]))),"POST");Logger(JSON.stringify(await rets.json()),LOG_LEVEL_VERBOSE)}}))}function shortenId(id){return id.length>10?id.substring(0,10):id}function shortenRev(rev3){return rev3?rev3.length>10?rev3.substring(0,10):rev3:"undefined"}function isTextBlob2(blob){return"text/plain"===blob.type}function*pickPiece(leftData,minimumChunkSize){let buffer="";L1:do{const curLine=leftData.shift();if(void 0===curLine){yield buffer;break L1}if(curLine.startsWith("```")||curLine.startsWith(" ```")||curLine.startsWith(" ```")||curLine.startsWith(" ```")){yield buffer;buffer=curLine+(0!=leftData.length?"\n":"");L2:do{const curPx=leftData.shift();if(void 0===curPx)break L2;buffer+=curPx+(0!=leftData.length?"\n":"")}while(leftData.length>0&&!(leftData[0].startsWith("```")||leftData[0].startsWith(" ```")||leftData[0].startsWith(" ```")||leftData[0].startsWith(" ```")));const isLooksLikeBASE64=buffer.endsWith("="),maybeUneditable=buffer.length>2048,endOfCodeBlock=leftData.shift();if(void 0!==endOfCodeBlock){buffer+=endOfCodeBlock;buffer+=0!=leftData.length?"\n":""}if(isLooksLikeBASE64||maybeUneditable)yield buffer;else{const splitExpr=/(.*?[;,:<])/g,sx=buffer.split(splitExpr).filter((e3=>""!=e3));for(const v2 of sx)yield v2}buffer=""}else{buffer+=curLine+(0!=leftData.length?"\n":"");if(buffer.length>=minimumChunkSize||0==leftData.length||"#"==leftData[0]||"#"==buffer[0]){yield buffer;buffer=""}}}while(leftData.length>0)}function*splitStringWithinLength(text2,pieceSize){let leftData=text2;do{const splitSize=pieceSize,piece=leftData.substring(0,splitSize);leftData=leftData.substring(splitSize);yield piece}while(""!=leftData)}function*splitTextInSegment(text2,pieceSize,minimumChunkSize){const segments=segmenter.segment(text2);let prev="",buf="";for(const seg of segments){const buffer=seg.segment;if(prev==buffer||buf.length<minimumChunkSize){buf+=buffer;prev=buffer}else{prev=buffer;buf.length>0&&(yield*splitStringWithinLength(buf,pieceSize));buf=buffer}}buf.length>0&&(yield*splitStringWithinLength(buf,pieceSize))}function*splitInNewLine(texts){for(const text2 of texts){let start=-1,end=-1;do{end=text2.indexOf("\n",start);if(-1==end){yield text2.substring(start);break}for(;"\n"==text2[end];)end++;yield text2.substring(start,end);start=end}while(-1!=end)}}function splitPiecesTextV2(dataSrc,pieceSize,minimumChunkSize){const dataListAll=splitInNewLine("string"==typeof dataSrc?[dataSrc]:dataSrc);let inCodeBlock=0,flush2=!1,flushBefore=!1;return function*(){const buf=[];for(const line of dataListAll){if(line.startsWith("````")){if(0==inCodeBlock){inCodeBlock=4;flushBefore=!0}else if(4==inCodeBlock){inCodeBlock=0;flush2=!0}}else if(line.startsWith("```"))if(0==inCodeBlock){inCodeBlock=3;flushBefore=!0}else if(3==inCodeBlock){inCodeBlock=0;flush2=!0}if(flushBefore){if(buf.length>0){yield*splitTextInSegment(buf.join(""),pieceSize,minimumChunkSize);buf.length=0}flushBefore=!1}buf.push(line);if(flush2){if(buf.length>0){yield*splitStringWithinLength(buf.join(""),pieceSize);buf.length=0}flush2=!1}}buf.length>0&&(0==inCodeBlock?yield*splitTextInSegment(buf.join(""),pieceSize,minimumChunkSize):yield*splitStringWithinLength(buf.join(""),pieceSize))}}function binaryTextSplit(data,pieceSize,minimumChunkSize){return function*pieces(){yield*splitStringWithinLength(data,pieceSize)}}function splitPiecesText(dataSrc,pieceSize,plainSplit,minimumChunkSize,useSegmenter){return useSegmenter&&segmenter?plainSplit?splitPiecesTextV2(dataSrc,pieceSize,minimumChunkSize):binaryTextSplit(dataSrc,pieceSize):splitPiecesTextV1(dataSrc,pieceSize,plainSplit,minimumChunkSize)}function splitPiecesTextV1(dataSrc,pieceSize,plainSplit,minimumChunkSize){const dataList="string"==typeof dataSrc?[dataSrc]:dataSrc;return function*pieces(){for(const data of dataList)if(plainSplit){const f4=pickPiece(data.split("\n"),minimumChunkSize);for(const piece of f4){let buffer=piece;do{let ps=pieceSize;buffer.charCodeAt(ps-1)!=buffer.codePointAt(ps-1)&&ps++;yield buffer.substring(0,ps);buffer=buffer.substring(ps)}while(""!=buffer)}}else{let leftData=data;do{const splitSize=pieceSize,piece=leftData.substring(0,splitSize);leftData=leftData.substring(splitSize);yield piece}while(""!=leftData)}}}function*splitByDelimiterWithMinLength(sources,delimiter,minimumChunkLength=25,splitThreshold){let buf="",last=!1;const dl=delimiter.length;for(const source2 of sources){const max3=source2.length;if(splitThreshold&&max3>splitThreshold){yield buf+source2;last=!1;buf="";continue}let i2=-1,prev=0;L1:do{i2=source2.indexOf(delimiter,prev);if(-1==i2)break L1;buf+=source2.slice(prev,i2)+delimiter;if(buf.length>minimumChunkLength){yield buf;buf="";last=!1}else last=!0;prev=i2+dl}while(i2<max3);if(prev!=i2||-1==prev&&-1==i2){buf+=source2.slice(prev);last=!0}}last&&(yield buf)}function*chunkStringGenerator(source2,maxLength){const strLen=source2.length;if(strLen>maxLength){let from=0;do{let end=from+maxLength;if(end>strLen){yield source2.substring(from);break}for(;source2.charCodeAt(end-1)!=source2.codePointAt(end-1);)end++;yield source2.substring(from,end);from=end}while(from<strLen)}else yield source2}function*chunkStringGeneratorFromGenerator(sources,maxLength){for(const source2 of sources)yield*chunkStringGenerator(source2,maxLength)}function*stringGenerator(sources){for(const str of sources)yield str}async function splitPieces2V2(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter){if(0==dataSrc.size)return function*noItems(){};if(isTextBlob2(dataSrc)){const text2=await dataSrc.text();if(!plainSplit){const gen2=chunkStringGenerator(text2,pieceSize);return function*pieces(){yield*gen2}}const textLen=text2.length;let xMinimumChunkSize=minimumChunkSize;for(;textLen/xMinimumChunkSize>MAX_ITEMS;)xMinimumChunkSize+=minimumChunkSize;const gen=chunkStringGeneratorFromGenerator(splitByDelimiterWithMinLength(stringGenerator([text2]),"\n",xMinimumChunkSize),pieceSize);return function*pieces(){yield*gen}}let canBeSmall=!1,delimiter=0;if(filename&&filename.endsWith(".pdf"))delimiter="/".charCodeAt(0);else if(filename&&filename.endsWith(".json")){canBeSmall=!0;delimiter=",".charCodeAt(0)}const clampMin=canBeSmall?100:1e5;let step=1,w2=Math.max(clampMin,Math.min(1e8,dataSrc.size));for(;w2>10;){w2/=12.5;step++}minimumChunkSize=Math.floor(10**(step-1));return async function*piecesBlob(){const size=dataSrc.size;let i2=0;const buf=new Uint8Array(await dataSrc.arrayBuffer());do{const findStart=i2+minimumChunkSize,defaultSplitEnd=i2+pieceSize;let splitEnd,i1=buf.indexOf(delimiter,findStart);-1==i1&&(i1=buf.indexOf(charNewLine,findStart));splitEnd=-1==i1?defaultSplitEnd:i1<defaultSplitEnd?i1:defaultSplitEnd;yield await arrayBufferToBase64Single(buf.slice(i2,splitEnd));i2=splitEnd}while(i2<size)}}async function splitPieces2(dataSrc,pieceSize,plainSplit,minimumChunkSize,filename,useSegmenter){if(isTextBlob2(dataSrc))return splitPiecesText(await dataSrc.text(),pieceSize,plainSplit,minimumChunkSize,null!=useSegmenter&&useSegmenter);let delimiter=0,canBeSmall=!1;if(filename&&filename.endsWith(".pdf"))delimiter="/".charCodeAt(0);else if(filename&&filename.endsWith(".json")){canBeSmall=!0;delimiter=",".charCodeAt(0)}const clampMin=canBeSmall?100:1e5;let step=1,w2=Math.max(clampMin,Math.min(1e8,dataSrc.size));for(;w2>10;){w2/=12.5;step++}minimumChunkSize=Math.floor(10**(step-1));return async function*piecesBlob(){const size=dataSrc.size;let i2=0;do{let splitSize=pieceSize;const currentData=new Uint8Array(await dataSrc.slice(i2,i2+pieceSize).arrayBuffer());let nextIdx=currentData.indexOf(delimiter,minimumChunkSize);splitSize=-1==nextIdx?pieceSize:Math.min(pieceSize,nextIdx);-1==nextIdx&&(nextIdx=currentData.indexOf(charNewLine,minimumChunkSize));const piece=currentData.slice(0,splitSize);i2+=piece.length;const b64=await arrayBufferToBase64Single(piece);yield b64}while(i2<size)}}async function splitPiecesRabinKarp(dataSrc,absoluteMaxPieceSize,doPlainSplit,minimumChunkSize,_filename,_useSegmenter){const plainSplit=doPlainSplit||isTextBlob2(dataSrc),minPieceSize=plainSplit?128:4096,splitPieceCount=plainSplit?20:12,avgChunkSize=Math.max(minPieceSize,Math.floor(dataSrc.size/splitPieceCount)),maxChunkSize=Math.min(absoluteMaxPieceSize,5*avgChunkSize),minChunkSize=Math.min(Math.max(Math.floor(avgChunkSize/4),minimumChunkSize),maxChunkSize),hashModulus=avgChunkSize;let P_pow_w=1;for(let i2=0;i2<47;i2++)P_pow_w=Math.imul(P_pow_w,31);const buffer=new Uint8Array(await dataSrc.arrayBuffer());let pos=0,hash3=0,start=0;const isText=isTextBlob2(dataSrc),length=buffer.length;return async function*piecesBlob(){for(;pos<length;){const byte=buffer[pos];if(pos>=start+48){const oldByte=buffer[pos-48],oldByteTerm=Math.imul(oldByte,P_pow_w);hash3=hash3-oldByteTerm|0;hash3=Math.imul(hash3,31);hash3=hash3+byte|0}else{hash3=Math.imul(hash3,31);hash3=hash3+byte|0}const currentChunkSize=pos-start+1;let isBoundaryCandidate=!1;currentChunkSize>=minChunkSize&&(hash3>>>0)%hashModulus==1&&(isBoundaryCandidate=!0);currentChunkSize>=maxChunkSize&&(isBoundaryCandidate=!0);if(isBoundaryCandidate){let isSafeBoundary=!0;isText&&pos+1<length&&128==(192&buffer[pos+1])&&(isSafeBoundary=!1);if(isSafeBoundary){isText?yield Promise.resolve(readString(buffer.subarray(start,pos+1))):yield await arrayBufferToBase64Single(buffer.subarray(start,pos+1));start=pos+1}}pos++}start<length&&(isText?yield Promise.resolve(readString(buffer.subarray(start,length))):yield await arrayBufferToBase64Single(buffer.subarray(start,length)))}}function startWatching(_,replicator,peer){replicator.watchPeer(get(peer).peerId)}function stopWatching(__1,replicator,peer){replicator.unwatchPeer(get(peer).peerId)}function sync2(__2,replicator,peer){replicator.sync(get(peer).peerId,!1)}function moreMenu(evt,peer){eventHub.emitEvent(EVENT_P2P_PEER_SHOW_EXTRA_MENU,{peer:get(peer),event:evt})}function PeerStatusRow($$anchor,$$props){function select(d4,cond,def){return d4 in cond?cond[d4]:def}function makeDecision(isAccepted3,isTemporary){var _a8,_b5;null===(_b5=null===(_a8=cmdReplicator._replicatorInstance)||void 0===_a8?void 0:_a8.server)||void 0===_b5||_b5.makeDecision({peerId:get(peer).peerId,name:get(peer).name,decision:isAccepted3,isTemporary})}function revokeDecision(){var _a8,_b5;null===(_b5=null===(_a8=cmdReplicator._replicatorInstance)||void 0===_a8?void 0:_a8.server)||void 0===_b5||_b5.revokeDecision({peerId:get(peer).peerId,name:get(peer).name})}var tr,td3,div,div_1,span,text2,div_2,span_1,text_1,div_3,div_4,span_2,text_2,node,consequent,div_6,td_1,div_7,div_8,node_1,consequent_3,alternate,td_2,node_4,consequent_5;push($$props,!0);append_styles($$anchor,$$css15);let peer=user_derived((()=>$$props.peerStatus)),statusChips=user_derived((()=>[get(peer).isWatching?["WATCHING"]:[],get(peer).isFetching?["FETCHING"]:[],get(peer).isSending?["SENDING"]:[]].flat())),acceptedStatusChip=user_derived((()=>select(get(peer).accepted.toString(),{["Accepted"]:"ACCEPTED",["Accepted in session"]:"ACCEPTED (in session)",["Denied in session"]:"DENIED (in session)",["Denied"]:"DENIED",["Unknown"]:"NEW"},"")));const classList={["SENDING"]:"connected",["FETCHING"]:"connected",["WATCHING"]:"connected-live",["WAITING"]:"waiting",["ACCEPTED"]:"accepted",["DENIED"]:"denied",["NEW"]:"unknown"};let isAccepted2=user_derived((()=>"Accepted"===get(peer).accepted||"Accepted in session"===get(peer).accepted)),isDenied=user_derived((()=>"Denied"===get(peer).accepted||"Denied in session"===get(peer).accepted)),isNew=user_derived((()=>"Unknown"===get(peer).accepted));const cmdReplicator=getContext("getReplicator")(),replicator=cmdReplicator._replicatorInstance,peerAttrLabels=user_derived((()=>{const attrs=[];get(peer).syncOnConnect&&attrs.push("✔ SYNC");get(peer).watchOnConnect&&attrs.push("✔ WATCH");get(peer).syncOnReplicationCommand&&attrs.push("✔ SELECT");return attrs}));td3=child(tr=root37());div=child(td3);div_1=child(div);span=child(div_1);text2=child(span,!0);reset(span);reset(div_1);span_1=child(div_2=sibling(div_1,2));text_1=child(span_1);reset(span_1);reset(div_2);reset(div);div_4=child(div_3=sibling(div,2));span_2=child(div_4);text_2=child(span_2,!0);reset(span_2);reset(div_4);node=sibling(div_4,2);consequent=$$anchor2=>{var div_5=root_130();each(div_5,21,(()=>get(statusChips)),index,(($$anchor3,chip)=>{var span_3=root_219(),text_3=child(span_3,!0);reset(span_3);template_effect(($0=>{set_class(span_3,1,`chip ${null!=$0?$0:""}`,"svelte-8nqxsr");set_text(text_3,get(chip))}),[()=>select(get(chip),classList)]);append($$anchor3,span_3)}));reset(div_5);append($$anchor2,div_5)};if_block(node,($$render=>{get(isAccepted2)&&$$render(consequent)}));each(div_6=sibling(node,2),21,(()=>get(peerAttrLabels)),index,(($$anchor2,attr2)=>{var span_4=root_39(),text_4=child(span_4,!0);reset(span_4);template_effect((()=>set_text(text_4,get(attr2))));append($$anchor2,span_4)}));reset(div_6);reset(div_3);reset(td3);div_7=child(td_1=sibling(td3));div_8=child(div_7);node_1=child(div_8);consequent_3=$$anchor2=>{var node_3,consequent_2,fragment=root_415(),node_2=first_child(fragment),consequent_1=$$anchor3=>{var fragment_1=root_56(),button=first_child(fragment_1);button.__click=[on_click4,makeDecision];sibling(button,2).__click=[on_click_12,makeDecision];append($$anchor3,fragment_1)};if_block(node_2,($$render=>{get(isAccepted2)||$$render(consequent_1)}));node_3=sibling(node_2,2);consequent_2=$$anchor3=>{var fragment_2=root_68(),button_2=first_child(fragment_2);button_2.__click=[on_click_2,makeDecision];sibling(button_2,2).__click=[on_click_3,makeDecision];append($$anchor3,fragment_2)};if_block(node_3,($$render=>{get(isDenied)||$$render(consequent_2)}));append($$anchor2,fragment)};alternate=$$anchor2=>{var button_4=root_79();button_4.__click=[on_click_4,revokeDecision];append($$anchor2,button_4)};if_block(node_1,($$render=>{get(isNew)?$$render(consequent_3):$$render(alternate,!1)}));reset(div_8);reset(div_7);reset(td_1);node_4=child(td_2=sibling(td_1));consequent_5=$$anchor2=>{var node_5,consequent_4,alternate_1,div_9=root_811(),div_10=child(div_9),button_5=child(div_10);button_5.__click=[sync2,replicator,peer];node_5=sibling(button_5,2);consequent_4=$$anchor3=>{var button_6=root_97();button_6.__click=[stopWatching,replicator,peer];append($$anchor3,button_6)};alternate_1=$$anchor3=>{var button_7=root_106();button_7.__click=[startWatching,replicator,peer];append($$anchor3,button_7)};if_block(node_5,($$render=>{get(peer).isWatching?$$render(consequent_4):$$render(alternate_1,!1)}));sibling(node_5,2).__click=[moreMenu,peer];reset(div_10);reset(div_9);template_effect((()=>button_5.disabled=get(peer).isSending||get(peer).isFetching));append($$anchor2,div_9)};if_block(node_4,($$render=>{get(isAccepted2)&&$$render(consequent_5)}));reset(td_2);reset(tr);template_effect(($0=>{var _a8;set_text(text2,get(peer).name);set_text(text_1,`(${null!=(_a8=get(peer).peerId)?_a8:""})`);set_class(span_2,1,`chip ${null!=$0?$0:""}`,"svelte-8nqxsr");set_text(text_2,get(acceptedStatusChip))}),[()=>select(get(acceptedStatusChip),classList)]);append($$anchor,tr);pop()}async function saveAndApply(_,plugin3,eP2PEnabled,eRelay,eRoomId,ePassword,eAppId,eAutoAccept,eAutoStart,eAutoBroadcast,$$props,eDeviceName,deviceName){const newSettings={...plugin3().settings,P2P_Enabled:get(eP2PEnabled),P2P_relays:get(eRelay),P2P_roomID:get(eRoomId),P2P_passphrase:get(ePassword),P2P_AppID:get(eAppId),P2P_AutoAccepting:get(eAutoAccept)?1:0,P2P_AutoStart:get(eAutoStart),P2P_AutoBroadcast:get(eAutoBroadcast)};plugin3().settings=newSettings;$$props.cmdSync.setConfig(SETTING_KEY_P2P_DEVICE_NAME,get(eDeviceName));set(deviceName,get(eDeviceName),!0);await plugin3().saveSettings()}async function revert(__1,eP2PEnabled,settings,eRelay,eRoomId,ePassword,eAppId,eAutoAccept,eAutoStart,eAutoBroadcast){set(eP2PEnabled,get(settings).P2P_Enabled,!0);set(eRelay,get(settings).P2P_relays,!0);set(eRoomId,get(settings).P2P_roomID,!0);set(ePassword,get(settings).P2P_passphrase,!0);set(eAppId,get(settings).P2P_AppID,!0);set(eAutoAccept,1==get(settings).P2P_AutoAccepting);set(eAutoStart,get(settings).P2P_AutoStart,!0);set(eAutoBroadcast,get(settings).P2P_AutoBroadcast,!0)}async function openServer(__2,$$props){await $$props.cmdSync.open()}function startBroadcasting(__3,$$props){$$props.cmdSync.enableBroadcastCastings()}function stopBroadcasting(__4,$$props){$$props.cmdSync.disableBroadcastCastings()}function P2PReplicatorPane($$anchor,$$props){function useDefaultRelay(){set(eRelay,DEFAULT_SETTINGS.P2P_relays,!0)}function _generateRandom(){return(Math.floor(1e3*Math.random())+1e3).toString().substring(1)}function generateRandom(length){let buf="";for(;buf.length<length;)buf+="-"+_generateRandom();return buf.substring(1,length)}function chooseRandom(){set(eRoomId,generateRandom(12)+"-"+Math.random().toString(36).substring(2,5))}async function closeServer(){await $$props.cmdSync.close()}var _a8,_b5,_c3,article,details,summary,text2,p4,text_1,p_1,text_2,node_1,consequent,alternate,div,div_1,node_2,consequent_1,alternate_1,div_2,node_3,consequent_2,alternate_3,div_3,table_1,tbody_1;push($$props,!0);append_styles($$anchor,$$css16);let plugin3=prop($$props,"plugin",7);setContext("getReplicator",(()=>$$props.cmdSync));const initialSettings={...plugin3().settings};let settings=state(proxy(initialSettings));const initialDeviceName=null!==(_a8=$$props.cmdSync.getConfig(SETTING_KEY_P2P_DEVICE_NAME))&&void 0!==_a8?_a8:plugin3().services.vault.getVaultName();let deviceName=state(proxy(initialDeviceName)),eP2PEnabled=state(proxy(initialSettings.P2P_Enabled)),eRelay=state(proxy(initialSettings.P2P_relays)),eRoomId=state(proxy(initialSettings.P2P_roomID)),ePassword=state(proxy(initialSettings.P2P_passphrase)),eAppId=state(proxy(initialSettings.P2P_AppID)),eDeviceName=state(proxy(initialDeviceName)),eAutoAccept=state(1==initialSettings.P2P_AutoAccepting),eAutoStart=state(proxy(initialSettings.P2P_AutoStart)),eAutoBroadcast=state(proxy(initialSettings.P2P_AutoBroadcast));const isP2PEnabledModified=user_derived((()=>get(eP2PEnabled)!==get(settings).P2P_Enabled)),isRelayModified=user_derived((()=>get(eRelay)!==get(settings).P2P_relays)),isRoomIdModified=user_derived((()=>get(eRoomId)!==get(settings).P2P_roomID)),isPasswordModified=user_derived((()=>get(ePassword)!==get(settings).P2P_passphrase)),isAppIdModified=user_derived((()=>get(eAppId)!==get(settings).P2P_AppID)),isDeviceNameModified=user_derived((()=>get(eDeviceName)!==get(deviceName))),isAutoAcceptModified=user_derived((()=>get(eAutoAccept)!==(1==get(settings).P2P_AutoAccepting))),isAutoStartModified=user_derived((()=>get(eAutoStart)!==get(settings).P2P_AutoStart)),isAutoBroadcastModified=user_derived((()=>get(eAutoBroadcast)!==get(settings).P2P_AutoBroadcast)),isAnyModified=user_derived((()=>get(isP2PEnabledModified)||get(isRelayModified)||get(isRoomIdModified)||get(isPasswordModified)||get(isAppIdModified)||get(isDeviceNameModified)||get(isAutoAcceptModified)||get(isAutoStartModified)||get(isAutoBroadcastModified)));let serverInfo=state(void 0),replicatorInfo=state(void 0);const applyLoadSettings=(d4,force)=>{const{P2P_relays,P2P_roomID,P2P_passphrase,P2P_AppID,P2P_AutoAccepting}=d4;!force&&get(isP2PEnabledModified)||set(eP2PEnabled,d4.P2P_Enabled,!0);!force&&get(isRelayModified)||set(eRelay,P2P_relays,!0);!force&&get(isRoomIdModified)||set(eRoomId,P2P_roomID,!0);!force&&get(isPasswordModified)||set(ePassword,P2P_passphrase,!0);!force&&get(isAppIdModified)||set(eAppId,P2P_AppID,!0);const newAutoAccept=1===P2P_AutoAccepting;!force&&get(isAutoAcceptModified)||set(eAutoAccept,newAutoAccept);!force&&get(isAutoStartModified)||set(eAutoStart,d4.P2P_AutoStart,!0);!force&&get(isAutoBroadcastModified)||set(eAutoBroadcast,d4.P2P_AutoBroadcast,!0);set(settings,d4,!0)};onMount((()=>{const r4=eventHub.onEvent("setting-saved",(async d4=>{applyLoadSettings(d4,!1);closeServer()})),r22=(eventHub.onEvent(EVENT_LAYOUT_READY,(()=>{applyLoadSettings(plugin3().settings,!0)})),eventHub.onEvent(EVENT_SERVER_STATUS,(status=>{var _a9;set(serverInfo,status,!0);set(advertisements,null!==(_a9=null==status?void 0:status.knownAdvertisements)&&void 0!==_a9?_a9:[],!0)}))),r32=eventHub.onEvent(EVENT_P2P_REPLICATOR_STATUS,(status=>{set(replicatorInfo,status,!0)}));eventHub.emitEvent(EVENT_REQUEST_STATUS);return()=>{r4();r22();r32()}}));let isConnected=user_derived((()=>{var _a9;return null!==(_a9=null===get(serverInfo)||void 0===get(serverInfo)?void 0:get(serverInfo).isConnected)&&void 0!==_a9&&_a9})),serverPeerId=user_derived((()=>{var _a9;return null!==(_a9=null===get(serverInfo)||void 0===get(serverInfo)?void 0:get(serverInfo).serverPeerId)&&void 0!==_a9?_a9:""})),advertisements=state(proxy([])),autoSyncPeers=user_derived((()=>get(settings).P2P_AutoSyncPeers.split(",").map((e3=>e3.trim())).filter((e3=>e3)))),autoWatchPeers=user_derived((()=>get(settings).P2P_AutoWatchPeers.split(",").map((e3=>e3.trim())).filter((e3=>e3)))),syncOnCommand=user_derived((()=>get(settings).P2P_SyncOnReplication.split(",").map((e3=>e3.trim())).filter((e3=>e3))));const peers=user_derived((()=>get(advertisements).map((ad2=>{let accepted;const isTemporaryAccepted=ad2.isTemporaryAccepted;accepted=void 0===isTemporaryAccepted?void 0===ad2.isAccepted?"Unknown":ad2.isAccepted?"Accepted":"Denied":!0===isTemporaryAccepted?"Accepted in session":"Denied in session";const isFetching=-1!==(null===get(replicatorInfo)||void 0===get(replicatorInfo)?void 0:get(replicatorInfo).replicatingFrom.indexOf(ad2.peerId)),isSending=-1!==(null===get(replicatorInfo)||void 0===get(replicatorInfo)?void 0:get(replicatorInfo).replicatingTo.indexOf(ad2.peerId)),isWatching=-1!==(null===get(replicatorInfo)||void 0===get(replicatorInfo)?void 0:get(replicatorInfo).watchingPeers.indexOf(ad2.peerId)),syncOnStart=-1!==get(autoSyncPeers).indexOf(ad2.name),watchOnStart=-1!==get(autoWatchPeers).indexOf(ad2.name),syncOnReplicationCommand=-1!==get(syncOnCommand).indexOf(ad2.name);return{name:ad2.name,peerId:ad2.peerId,accepted,status:ad2.isAccepted?"Connected":"Disconnected",isSending,isFetching,isWatching,syncOnConnect:syncOnStart,watchOnConnect:watchOnStart,syncOnReplicationCommand}})))),initialDialogStatus=(()=>{var _a9;try{return JSON.parse(null!==(_a9=$$props.cmdSync.getConfig("p2p-dialog-status"))&&void 0!==_a9?_a9:"{}")}catch(e3){return{}}})();let isNoticeOpened=state(proxy(null===(_b5=initialDialogStatus.notice)||void 0===_b5||_b5)),isSettingOpened=state(proxy(null===(_c3=initialDialogStatus.setting)||void 0===_c3||_c3));user_effect((()=>{const dialogStatus={notice:get(isNoticeOpened),setting:get(isSettingOpened)};$$props.cmdSync.setConfig("p2p-dialog-status",JSON.stringify(dialogStatus))}));let isObsidian=user_derived((()=>"obsidian"===plugin3().services.API.getPlatform()));details=sibling(child(article=root38()),2);summary=child(details);text2=child(summary,!0);reset(summary);p4=sibling(summary,2);text_1=child(p4,!0);reset(p4);p_1=sibling(p4,2);text_2=child(p_1,!0);reset(p_1);each(sibling(p_1,2),17,(()=>$msg("P2P.Note.description").split("\n\n")),index,(($$anchor2,paragraph)=>{var p_2=root_131(),text_3=child(p_2,!0);reset(p_2);template_effect((()=>set_text(text_3,get(paragraph))));append($$anchor2,p_2)}));reset(details);node_1=sibling(details,4);consequent=$$anchor2=>{append($$anchor2,text("You can configure in the Obsidian Plugin Settings."))};alternate=$$anchor2=>{var table2,tbody,tr,td3,label2,input,tr_1,td_1,label_1,input_1,tr_2,td_2,label_2,input_2,tr_3,td_3,label_3,input_3,tr_4,td_4,label_4,input_4,tr_5,td_5,label_5,input_5,tr_6,td_6,label_6,input_6,button_2,button_3,details_1=root_310(),summary_1=child(details_1),text_5=child(summary_1,!0);reset(summary_1);tbody=child(table2=sibling(summary_1,2));tr=child(tbody);td3=sibling(child(tr));label2=child(td3);remove_input_defaults(input=child(label2));reset(label2);reset(td3);reset(tr);tr_1=sibling(tr);td_1=sibling(child(tr_1));label_1=child(td_1);remove_input_defaults(input_1=child(label_1));sibling(input_1,2).__click=[on_click5,useDefaultRelay];reset(label_1);reset(td_1);reset(tr_1);tr_2=sibling(tr_1);td_2=sibling(child(tr_2));label_2=child(td_2);remove_input_defaults(input_2=child(label_2));sibling(input_2,2).__click=[on_click_13,chooseRandom];reset(label_2);next(2);reset(td_2);reset(tr_2);tr_3=sibling(tr_2);td_3=sibling(child(tr_3));label_3=child(td_3);remove_input_defaults(input_3=child(label_3));reset(label_3);next(2);reset(td_3);reset(tr_3);tr_4=sibling(tr_3);td_4=sibling(child(tr_4));label_4=child(td_4);remove_input_defaults(input_4=child(label_4));reset(label_4);next(2);reset(td_4);reset(tr_4);tr_5=sibling(tr_4);td_5=sibling(child(tr_5));label_5=child(td_5);remove_input_defaults(input_5=child(label_5));reset(label_5);reset(td_5);reset(tr_5);tr_6=sibling(tr_5);td_6=sibling(child(tr_6));label_6=child(td_6);remove_input_defaults(input_6=child(label_6));reset(label_6);reset(td_6);reset(tr_6);reset(tbody);reset(table2);(button_2=sibling(table2,2)).__click=[saveAndApply,plugin3,eP2PEnabled,eRelay,eRoomId,ePassword,eAppId,eAutoAccept,eAutoStart,eAutoBroadcast,$$props,eDeviceName,deviceName];(button_3=sibling(button_2,2)).__click=[revert,eP2PEnabled,settings,eRelay,eRoomId,ePassword,eAppId,eAutoAccept,eAutoStart,eAutoBroadcast];reset(details_1);template_effect((()=>{set_text(text_5,get(eRelay));set_class(label2,1,clsx2({"is-dirty":get(isP2PEnabledModified)}),"svelte-2cmos");set_class(label_1,1,clsx2({"is-dirty":get(isRelayModified)}),"svelte-2cmos");set_class(label_2,1,clsx2({"is-dirty":get(isRoomIdModified)}),"svelte-2cmos");set_class(label_3,1,clsx2({"is-dirty":get(isPasswordModified)}),"svelte-2cmos");set_class(label_4,1,clsx2({"is-dirty":get(isDeviceNameModified)}),"svelte-2cmos");set_class(label_5,1,clsx2({"is-dirty":get(isAutoStartModified)}),"svelte-2cmos");set_class(label_6,1,clsx2({"is-dirty":get(isAutoBroadcastModified)}),"svelte-2cmos");button_2.disabled=!get(isAnyModified);button_3.disabled=!get(isAnyModified)}));bind_checked(input,(()=>get(eP2PEnabled)),($$value=>set(eP2PEnabled,$$value)));bind_value(input_1,(()=>get(eRelay)),($$value=>set(eRelay,$$value)));bind_value(input_2,(()=>get(eRoomId)),($$value=>set(eRoomId,$$value)));bind_value(input_3,(()=>get(ePassword)),($$value=>set(ePassword,$$value)));bind_value(input_4,(()=>get(eDeviceName)),($$value=>set(eDeviceName,$$value)));bind_checked(input_5,(()=>get(eAutoStart)),($$value=>set(eAutoStart,$$value)));bind_checked(input_6,(()=>get(eAutoBroadcast)),($$value=>set(eAutoBroadcast,$$value)));bind_property("open","toggle",details_1,($$value=>set(isSettingOpened,$$value)),(()=>get(isSettingOpened)));append($$anchor2,details_1)};if_block(node_1,($$render=>{get(isObsidian)?$$render(consequent):$$render(alternate,!1)}));div=sibling(node_1,2);div_1=sibling(child(div),2);node_2=child(div_1);consequent_1=$$anchor2=>{append($$anchor2,root_416())};alternate_1=$$anchor2=>{var p_4=root_57(),text_6=child(p_4);reset(p_4);template_effect((()=>{var _a9;return set_text(text_6,`Connected to Signaling Server (as Peer ID: ${null!=(_a9=get(serverPeerId))?_a9:""})`)}));append($$anchor2,p_4)};if_block(node_2,($$render=>{get(isConnected)?$$render(alternate_1,!1):$$render(consequent_1)}));reset(div_1);node_3=child(div_2=sibling(div_1,2));consequent_2=$$anchor2=>{var button_4=root_69();button_4.__click=[openServer,$$props];append($$anchor2,button_4)};alternate_3=$$anchor2=>{var node_4,consequent_4,fragment=root_710(),button_5=first_child(fragment);button_5.__click=closeServer;node_4=sibling(button_5,2);consequent_4=$$anchor3=>{var fragment_1=comment(),node_5=first_child(fragment_1),consequent_3=$$anchor4=>{var button_6=root_98();button_6.__click=[stopBroadcasting,$$props];append($$anchor4,button_6)},alternate_2=$$anchor4=>{var button_7=root_107();button_7.__click=[startBroadcasting,$$props];append($$anchor4,button_7)};if_block(node_5,($$render=>{var _a9;(null==(_a9=get(replicatorInfo))?void 0:_a9.isBroadcasting)?$$render(consequent_3):$$render(alternate_2,!1)}));append($$anchor3,fragment_1)};if_block(node_4,($$render=>{var _a9;void 0!==(null==(_a9=get(replicatorInfo))?void 0:_a9.isBroadcasting)&&$$render(consequent_4)}));next(2);append($$anchor2,fragment)};if_block(node_3,($$render=>{get(isConnected)?$$render(alternate_3,!1):$$render(consequent_2)}));reset(div_2);reset(div);div_3=sibling(div,2);table_1=sibling(child(div_3),2);each(tbody_1=sibling(child(table_1)),21,(()=>get(peers)),index,(($$anchor2,peer)=>{PeerStatusRow($$anchor2,{get peerStatus(){return get(peer)}})}));reset(tbody_1);reset(table_1);reset(div_3);reset(article);template_effect((($0,$1,$2)=>{set_text(text2,$0);set_text(text_1,$1);set_text(text_2,$2)}),[()=>$msg("P2P.Note.Summary"),()=>$msg("P2P.Note.important_note"),()=>$msg("P2P.Note.important_note_sub")]);bind_property("open","toggle",details,($$value=>set(isNoticeOpened,$$value)),(()=>get(isNoticeOpened)));append($$anchor,article);pop()}function addToList(item,list){return unique(list.split(",").map((e3=>e3.trim())).concat(item).filter((p4=>p4))).join(",")}function removeFromList(item,list){return list.split(",").map((e3=>e3.trim())).filter((p4=>p4!==item)).filter((p4=>p4)).join(",")}function setEnvironmentInstance(env){if(instance2)instance2=env;else{instance2=env;p3.resolve(env)}}function getWebCrypto2(){if(webcrypto6)return Promise.resolve(webcrypto6);if(globalThis.crypto){webcrypto6=globalThis.crypto;return Promise.resolve(webcrypto6)}throw new Error("WebCrypto not available")}function getPlatformName(){return import_obsidian4.Platform.isAndroidApp?"android-app":import_obsidian4.Platform.isIosApp?"ios":import_obsidian4.Platform.isMacOS?"macos":import_obsidian4.Platform.isMobileApp?"mobile-app":import_obsidian4.Platform.isMobile?"mobile":import_obsidian4.Platform.isSafari?"safari":import_obsidian4.Platform.isDesktop?"desktop":import_obsidian4.Platform.isDesktopApp?"desktop-app":"unknown-obsidian"}function _getFunction(throughHole,key3){return throughHole.getFunction(key3)}function _getBindFunction(throughHole,key3){return func=>{Logger(`Binding function ${key3}`,LOG_LEVEL_DEBUG);throughHole.bindFunction(key3,func)}}function bindMethod(throughHole,key3){return[_getFunction(throughHole,key3),_getBindFunction(throughHole,key3)]}function DialogueToCopy($$anchor,$$props){function commit(){$$props.setResult("ok")}async function copyToClipboard(){await navigator.clipboard.writeText(get(dataToCopy));set(copied,!0)}var fragment,node,node_1,node_3;push($$props,!0);append_styles($$anchor,$$css17);let dataToCopy=state(""),title=state(void 0),copied=state(!1);onMount((()=>{if($$props.getInitialData){const initialData=$$props.getInitialData();if(initialData){set(dataToCopy,initialData.dataToCopy,!0);set(title,initialData.title,!0)}}}));node=first_child(fragment=root39());{let $0=user_derived((()=>get(title)||"Data"));DialogHeader(node,{get title(){var _a8;return`Your ${null!=(_a8=get($0))?_a8:""} is ready to be copied`}})}Instruction(node_1=sibling(node,2),{children:($$anchor2,$$slotProps)=>{{let $0=user_derived((()=>get(title)||"Data to Copy"));InputRow($$anchor2,{get label(){return get($0)},children:($$anchor3,$$slotProps2)=>{var button,node_2,consequent,alternate,fragment_2=root_220(),textarea=first_child(fragment_2);remove_textarea_child(textarea);(button=sibling(textarea,2)).__click=[on_click6,copyToClipboard];node_2=child(button);consequent=$$anchor4=>{append($$anchor4,text("📋"))};alternate=$$anchor4=>{append($$anchor4,text("✔️"))};if_block(node_2,($$render=>{get(copied)?$$render(alternate,!1):$$render(consequent)}));reset(button);template_effect((()=>set_value(textarea,get(dataToCopy))));append($$anchor3,fragment_2)},$$slots:{default:!0}})}},$$slots:{default:!0}});InfoNote(node_3=sibling(node_1,2),{get visible(){return get(copied)},children:($$anchor2,$$slotProps)=>{next();var text_2=text();template_effect((()=>{var _a8;return set_text(text_2,`Your ${null!=(_a8=get(title)||"data")?_a8:""} has been copied to the clipboard.`)}));append($$anchor2,text_2)},$$slots:{default:!0}});UserDecisions(sibling(node_3,2),{children:($$anchor2,$$slotProps)=>{Decision($$anchor2,{title:"OK",important:!0,commit})},$$slots:{default:!0}});append($$anchor,fragment);pop()}var LOG_LEVEL_DEBUG,LOG_LEVEL_VERBOSE,LOG_LEVEL_INFO,LOG_LEVEL_NOTICE,LOG_KIND_ERROR,LEVEL_INFO,LEVEL_NOTICE,defaultLoggerEnv_minLogLevel,_logger,RESULT_TIMED_OUT,CANCELLED,AUTO_MERGED,NOT_CONFLICTED,MISSING_OR_ERROR,LEAVE_TO_SUBSEQUENT,MILESTONE_DOCID,NODEINFO_DOCID,MODE_SELECTIVE,MODE_AUTOMATIC,MODE_PAUSED,MODE_SHINY,RemoteTypes_REMOTE_COUCHDB,RemoteTypes_REMOTE_MINIO,RemoteTypes_REMOTE_P2P,REMOTE_COUCHDB,REMOTE_MINIO,REMOTE_P2P,AutoAccepting,P2P_DEFAULT_SETTINGS,E2EEAlgorithmNames,E2EEAlgorithms,ChunkAlgorithmNames,DEFAULT_SETTINGS,KeyIndexOfSettings,PREFERRED_BASE,PREFERRED_SETTING_CLOUDANT,PREFERRED_SETTING_SELF_HOSTED,PREFERRED_JOURNAL_SYNC,TweakValuesShouldMatchedTemplate,IncompatibleChanges,CompatibleButLossyChanges,IncompatibleChangesInSpecificPattern,TweakValuesRecommendedTemplate,TweakValuesDefault,configurationNames,LEVEL_ADVANCED,LEVEL_POWER_USER,LEVEL_EDGE_CASE,TweakValuesTemplate,DEVICE_ID_PREFERRED,PREFIXMD_LOGFILE,PREFIXMD_LOGFILE_UC,FlagFilesHumanReadable_REBUILD_ALL,FlagFilesHumanReadable_FETCH_ALL,FLAGMD_REDFLAG,FLAGMD_REDFLAG2,FLAGMD_REDFLAG2_HR,FLAGMD_REDFLAG3,FLAGMD_REDFLAG3_HR,SYNCINFO_ID,PREFIX_OBFUSCATED,PREFIX_ENCRYPTED_CHUNK,DEFAULT_SYNC_PARAMETERS,SETTING_KEY_P2P_DEVICE_NAME,configURIBase,configURIBaseQR,SuffixDatabaseName,ExtraSuffixIndexedDB,import_obsidian,import_obsidian2,import_diff_match_patch,normalizePath,LRUCache,balanced,maybeMatch,range,escSlash,escOpen,escClose,escComma,escPeriod,escSlashPattern,escOpenPattern,escClosePattern,escCommaPattern,escPeriodPattern,slashPattern,openPattern,closePattern,commaPattern,periodPattern,assertValidPattern,posixClasses,braceEscape,regexpEscape,rangesToString,parseClass,unescape2,_root,_hasMagic,_uflag,_parts,_parent,_parentIndex,_negs,_filledNegs,_options,_toString,_emptyExt,_AST_instances,fillNegs_fn,_AST_static,parseAST_fn,partsToRegExp_fn,parseGlob_fn,types,isExtglobType,addPatternStart,justDots,reSpecials,regExpEscape,_AST,AST,escape,minimatch,starDotExtRE,starDotExtTest,starDotExtTestDot,starDotExtTestNocase,starDotExtTestNocaseDot,starDotStarRE,starDotStarTest,starDotStarTestDot,dotStarRE,dotStarTest,starRE,starTest,starTestDot,qmarksRE,qmarksTestNocase,qmarksTestNocaseDot,qmarksTestDot,qmarksTest,qmarksTestNoExt,qmarksTestNoExtDot,defaultPlatform,path_posix,sep,GLOBSTAR,filter,ext,defaults,braceExpand,makeRe,match,globMagic,regExpEscape2,Minimatch,webcrypto,isProposalArrayBufferBase64Available,base64ToArrayBuffer,arrayBufferToBase64Single,arrayBufferToBase64,QUANTUM,te,td,base64ToString,regexpBase64,tryConvertBase64ToArrayBuffer,table,revTable,revMap,numMap,isProposalArrayBufferBase64Available2,hexStringToUint8Array,uint8ArrayToHexString,_hashString,matchOpts,delay,UNRESOLVED,polyfilledFunc,promiseWithResolvers,promiseWithResolver,noop,currentYieldingAnimationFrame,TIMED_OUT_SIGNAL,isValidRemoteCouchDBURI,_requestToCouchDBFetch,prefixMapObject,decodePrefixMapObject,prefixMapNumber,decodePrefixMapNumber,ARRAY_MARKER,OBJECT_MARKER,decodeMapConstant,SYMBOL_A,SYMBOL_B,GENERIC_COMPATIBILITY_VALUE,GENERIC_COMPATIBILITY_SIGNAL,globalSlipBoard,throttle,_a,isIndexDBCmpExist,globalConcurrencyController,map,revMap2,previousValues,MARK_DELETED,MARK_ISARRAY,MARK_SWAPPED,CustomRegExp,_a2,FallbackWeakRef,LiveSyncError,LiveSyncFatalError,ChunkFetcher,EVENT_CHUNK_FETCHED,ChunkManager,EventHub,InterceptiveEventTarget,WrappedEvent,eventHub,LiveSyncLocalDB,LiveSyncAbstractReplicator,CHeader,PSCHeader,ICHeader,ICHeaderLength,ICXHeader,serializedMap,queueCount,waitingProcessMap,shareSerializedMap,skipDuplicatedMap,tasks,intervals,waitingItems,PersistentMap,sameChangePairs,EVENT_LAYOUT_READY,EVENT_SETTING_SAVED,EVENT_DATABASE_REBUILT,EVENT_REQUEST_OPEN_SETUP_URI2,EVENT_REQUEST_COPY_SETUP_URI2,EVENT_REQUEST_SHOW_SETUP_QR,EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG2,EVENT_REQUEST_RUN_DOCTOR,EVENT_REQUEST_RUN_FIX_INCOMPLETE,EVENT_ANALYSE_DB_USAGE,EVENT_REQUEST_PERFORM_GC_V3,EVENT_REQUEST_CHECK_REMOTE_SIZE,Computed,BasicHeaderGenerator,JWTTokenGenerator,AuthorizationHeaderGenerator,memos,PeriodicProcessor,_requestToCouchDB,BASE_IS_NEW,TARGET_IS_NEW,EVEN,resolution,_cached,waitingTasks,context,topologicalSortCache,_reactiveSourceId,collectingChunks,pluginScanningCount,hiddenFilesProcessingCount,hiddenFilesEventCount,logMessages,AbstractModule,AbstractObsidianModule,_a3,_b,_c,EACH_ITEM_REACTIVE,EACH_INDEX_REACTIVE,EACH_IS_CONTROLLED,EACH_IS_ANIMATED,EACH_ITEM_IMMUTABLE,PROPS_IS_IMMUTABLE,PROPS_IS_RUNES,PROPS_IS_UPDATED,PROPS_IS_BINDABLE,PROPS_IS_LAZY_INITIAL,TEMPLATE_FRAGMENT,TEMPLATE_USE_IMPORT_NODE,HYDRATION_START,HYDRATION_START_ELSE,HYDRATION_END,HYDRATION_ERROR,UNINITIALIZED,FILENAME,NAMESPACE_HTML,_a4,_b2,node_env,dev_fallback_default,is_array,index_of,array_from,define_property,get_descriptor,get_descriptors,object_prototype,array_prototype,get_prototype_of,is_extensible,noop2,DERIVED,EFFECT,RENDER_EFFECT,BLOCK_EFFECT,BRANCH_EFFECT,ROOT_EFFECT,BOUNDARY_EFFECT,UNOWNED,DISCONNECTED,CLEAN,DIRTY,MAYBE_DIRTY,INERT,DESTROYED,EFFECT_RAN,EFFECT_TRANSPARENT,INSPECT_EFFECT,HEAD_EFFECT,EFFECT_PRESERVED,USER_EFFECT,REACTION_IS_UPDATING,ASYNC,ERROR_VALUE,STATE_SYMBOL,LEGACY_PROPS,LOADING_ATTR_SYMBOL,PROXY_PATH_SYMBOL,STALE_REACTION,TEXT_NODE,COMMENT_NODE,bold,normal,hydrating,hydrate_node,async_mode_flag,legacy_mode_flag,tracing_mode_flag,tracing_expressions,component_context,dev_stack,dev_current_component_function,micro_tasks,adjustments,_previous,_callbacks,_pending,_deferred,_render_effects,_effects,_block_effects,_dirty_effects,_maybe_dirty_effects,_Batch_instances,traverse_effect_tree_fn,defer_effects_fn,commit_fn,batches,current_batch,previous_batch,batch_values,effect_pending_updates,queued_root_effects,last_scheduled_effect,is_flushing,is_flushing_sync,_Batch,Batch,eager_block_effects,_pending2,_anchor,_hydrate_open,_props,_children,_effect,_main_effect,_pending_effect,_failed_effect,_offscreen_fragment,_local_pending_count,_pending_count,_is_creating_fallback,_effect_pending,_effect_pending_update,_effect_pending_subscriber,_Boundary_instances,hydrate_resolved_content_fn,hydrate_pending_content_fn,run_fn,show_pending_snippet_fn,update_pending_count_fn,flags,Boundary,current_async_effect,recent_async_deriveds,stack,inspect_effects,old_values,inspect_effects_deferred,regex_is_valid_identifier,ARRAY_MUTATING_METHODS,$window,is_firefox,first_child_getter,next_sibling_getter,listening_to_form_reset,captured_signals,is_updating_effect,is_destroying_effect,active_reaction,untracking,active_effect,current_sources,new_deps,skipped_deps,untracked_writes,write_version,read_version,update_version,skip_reaction,STATUS_MASK,all_registered_events,root_event_handles,PASSIVE_EVENTS,document_listeners,mounted_components,_batches,_onscreen,_offscreen,_transition,_commit,BranchManager,all_styles,current_each_item,whitespace,IS_CUSTOM_ELEMENT,IS_HTML,setters_cache,pending2,_listeners,_observer,_options2,_ResizeObserverSingleton_instances,getObserver_fn,_ResizeObserverSingleton,subscriber_queue,is_store_binding,IS_UNMOUNTED,spread_props_handler,_allMessages,SUPPORTED_I18N_LANGS,expandedMessage,allMessages,currentLang,missingTranslations,__onMissingTranslations,msgCache,on_click,root_1,root,$$css,SvelteItemView,LogPaneView,EVENT_PLATFORM_UNLOADED,APIBase,secp256k1_CURVE,L,lengths,captureTrace,err,isBig,isStr,isBytes,abytes,u8n,padh,bytesToHex,_ch,hexToBytes,cr,subtle,concatBytes,randomBytes,big,arange,M,modN,invert,callHash,apoint,koblitz,FpIsValid,FpIsValidNot0,FnIsValidNot0,isEven,u8of,getPrefix,lift_x,_Point,Point,G,I,doubleScalarMulUns,bytesToNumBE,sliceBytesNumBE,B256,numTo32b,secretKeyToScalar,getPublicKey,assertSigFormat,SIG_COMPACT,SIG_RECOVERED,SIG_DER,ALL_SIG,hashes,randomSecretKey,createKeygen,getTag,taggedHash,taggedHashAsync,extpubSchnorr,bytesModN,challenge,challengeAsync,pubSchnorr,keygenSchnorr,prepSigSchnorr,extractK,createSigSchnorr,E_INVSIG,callSyncAsyncFn,_verifSchnorr,verifySchnorr,verifySchnorrAsync,schnorr,pwindows,precompute,Gpows,ctneg,wNAF,alloc,genId,selfId,all,isBrowser,noOp,mkErr,encoder,decoder,encodeBytes,decodeBytes,toHex,topicPath,shuffle,getRelays,toJson,fromJson,strToNum,socketRetryPeriods,reconnectionLockingPromise,resolver,pauseRelayReconnection,resumeRelayReconnection,makeSocket,socketGetter,watchOnline,strToSha1,pack,unpack,hashWith,sha1,genKey,encrypt,decrypt,peer_default,defaultIceServers,TypedArray,progressIndex,payloadIndex,chunkSize,internalNs,room_default,strategy_default,clients,pubkey,subIdToTopic,msgHandlers,kindCache,now2,topicToKind,createEvent,subscribe,unsubscribe,joinRoom,getRelaySockets,defaultRelayUrls,ResponsePreventedError,DeviceDecisions,StoredMapLike,TrysteroReplicatorP2PClient,epochFNV1a,c1,c2,r1,r2,m,n,EVENT_SERVER_STATUS,EVENT_ADVERTISEMENT_RECEIVED,EVENT_DEVICE_LEAVED,EVENT_REQUEST_STATUS,EVENT_P2P_REQUEST_FORCE_OPEN,EVENT_P2P_REPLICATOR_STATUS,TrysteroReplicatorP2PServer,p,instance,replicatorInstanceGetter,LiveSyncTrysteroReplicator,UNDEFINED,webcrypto2,IV_LENGTH,HKDF_SALT_LENGTH,PBKDF2_SALT_LENGTH,gcmTagLength,HKDF_ENCRYPTED_PREFIX,HKDF_SALTED_ENCRYPTED_PREFIX,deriveMasterKey,_sessionPBKDFSalt,TrysteroReplicator,P2PLogCollector,recentLogEntries,recentLogs,ModuleLog,noticeIndex,LiveSyncCommands,root_12,root_4,root_6,root_5,root_10,root_2,root2,$$css2,JsonResolveModal,PaceMaker,NOT_AVAILABLE,READY_PICK_SIGNAL,READY_POST_SIGNAL,DISPOSE_ERROR,SyncInbox,Inbox,ClerkState,SENTINEL_FINISHED,SENTINEL_FLUSH,ClerkBase,Clerk,ClerkGroup,Notifier,allRunningProcessors,QueueProcessor,HiddenFileSync,t,hashFunc,globalSlipBoard2,import_diff_match_patch2,ConflictResolveModal,root_3,root_62,root_7,root_8,root_42,root_9,root_11,root_122,root_22,root_13,root_132,$$css3,root_14,root_23,root_32,root_82,root_63,root_52,root_133,root_15,root_18,root_16,root_112,root_19,root_92,root_43,root_21,root_20,root3,$$css4,PluginDialogModal,d,d2,DUMMY_HEAD,DUMMY_END,pluginList,pluginIsEnumerating,pluginV2Progress,pluginManifests,pluginManifestStore,PluginDataExDisplayV2,ConfigSync,getHttpHandlerExtensionConfiguration,resolveHttpHandlerRuntimeConfig,HttpAuthLocation,HttpApiKeyAuthLocation,EndpointURLScheme,AlgorithmId,FieldPosition,SMITHY_CONTEXT_KEY,IniSectionType,RequestHandlerProtocol,HttpRequest,HttpResponse,addExpectContinueMiddlewareOptions,getAddExpectContinuePlugin,RequestChecksumCalculation,DEFAULT_REQUEST_CHECKSUM_CALCULATION,ResponseChecksumValidation,DEFAULT_RESPONSE_CHECKSUM_VALIDATION,ChecksumAlgorithm,ChecksumLocation,DEFAULT_CHECKSUM_ALGORITHM,SelectorType,getDateHeader,getSkewCorrectedDate,isClockSkewed,getUpdatedSystemClockOffset,throwSigningPropertyError,validateSigningProperties,AwsSdkSigV4Signer,AwsSdkSigV4ASigner,getSmithyContext2,normalizeProvider,resolveAuthOptions,httpAuthSchemeMiddleware,httpAuthSchemeEndpointRuleSetMiddlewareOptions,getHttpAuthSchemeEndpointRuleSetPlugin,deserializerMiddleware,findHeader,serializerMiddleware,deserializerMiddlewareOption,serializerMiddlewareOption,defaultErrorHandler,defaultSuccessHandler,httpSigningMiddleware,httpSigningMiddlewareOptions,getHttpSigningPlugin,normalizeProvider2,alphabetByEncoding,alphabetByValue,bitsPerLetter,bitsPerByte,maxLetterValue,fromBase64,fromUtf8,toUint8Array,toUtf8,Uint8ArrayBlobAdapter,ReadableStreamRef,ChecksumStream,isReadableStream,createChecksumStream,ByteArrayCollector,createBufferedReadable,getAwsChunkedEncodingStream,escapeUri,hexEncode,keepAliveSupport,FetchHttpHandler,streamCollector,SHORT_TO_HEX,HEX_TO_SHORT,sdkStreamMixin,isBlobInstance,collectBody,resolvedPath,RequestBuilder,DefaultIdentityProviderConfig,isIdentityExpired,doesIdentityRequireRefresh,memoizeIdentityProvider,memoize,resolveAwsSdkSigV4AConfig,AMZ_DATE_QUERY_PARAM,AMZ_DATE_HEADER,GENERATED_HEADERS,SIGNATURE_HEADER,TOKEN_HEADER,ALWAYS_UNSIGNABLE_HEADERS,PROXY_HEADER_PATTERN,SEC_HEADER_PATTERN,EVENT_ALGORITHM_IDENTIFIER,signingKeyCache,cacheQueue,createScope,getSigningKey,hmac,getCanonicalHeaders,isArrayBuffer,getPayloadHash,HeaderFormatter,HEADER_VALUE_TYPE,UUID_PATTERN,Int64,hasHeader,moveHeadersToQuery,prepareRequest,getCanonicalQuery,iso8601,toDate,SignatureV4Base,SignatureV4,resolveAwsSdkSigV4Config,getAllAliases,getMiddlewareNameWithAliases,constructStack,stepWeights,priorityWeights,Client,Command,ClassBuilder,SENSITIVE_STRING,createAggregatedClient,parseBoolean,expectNumber,MAX_FLOAT,expectFloat32,expectLong,expectInt32,expectShort,expectByte,expectSizedInt,castInt,expectNonNull,expectObject,expectString,expectUnion,strictParseFloat32,NUMBER_REGEX,parseNumber,strictParseLong,strictParseInt32,strictParseShort,strictParseByte,stackTraceWarning,logger,DAYS,MONTHS,RFC3339_WITH_OFFSET,parseRfc3339DateTimeWithOffset,IMF_FIXDATE,RFC_850_DATE,ASC_TIME,parseRfc7231DateTime,buildDate,parseTwoDigitYear,adjustRfc850Year,parseMonthByShortName,DAYS_IN_MONTH,validateDayOfMonth,isLeapYear,parseDateValue,parseMilliseconds,parseOffsetToMilliseconds,stripLeadingZeroes,ServiceException,decorateServiceException,throwDefaultError,withBaseException,deserializeMetadata,loadConfigsForDefaultMode,getChecksumConfiguration2,resolveChecksumRuntimeConfig2,getRetryConfiguration,resolveRetryRuntimeConfig,getDefaultExtensionConfiguration,resolveDefaultRuntimeConfig2,getArrayIfSingleItem,getValueFromTextNode,isSerializableHeaderValue,LazyJsonString,NoOpLogger,mapWithFilter,applyInstruction,nonNullish,pass,serializeDateTime,collectBodyString,import_fast_xml_parser,parseXmlBody,parseXmlErrorBody,loadRestXmlErrorCode,CLIENT_SUPPORTED_ALGORITHMS,PRIORITY_ORDER_ALGORITHMS,getChecksumAlgorithmForRequest,getChecksumLocationName,hasHeader2,hasHeaderWithPrefix,isStreaming,__assign,fromUtf82,fromUtf83,AwsCrc32c,Crc32c,lookupTable,AwsCrc32,Crc32,lookupTable2,getCrc32ChecksumAlgorithmFunction,selectChecksumAlgorithmFunction,stringHasher,flexibleChecksumsMiddlewareOptions,flexibleChecksumsMiddleware,flexibleChecksumsInputMiddlewareOptions,flexibleChecksumsInputMiddleware,getChecksumAlgorithmListForResponse,isChecksumWithPartNumber,getChecksum,validateChecksumFromResponse,flexibleChecksumsResponseMiddlewareOptions,flexibleChecksumsResponseMiddleware,getFlexibleChecksumsPlugin,resolveFlexibleChecksumsConfig,hostHeaderMiddleware,hostHeaderMiddlewareOptions,getHostHeaderPlugin,loggerMiddleware,loggerMiddlewareOptions,getLoggerPlugin,recursionDetectionMiddleware,addRecursionDetectionMiddlewareOptions,getRecursionDetectionPlugin,CONTENT_LENGTH_HEADER,DECODED_CONTENT_LENGTH_HEADER,checkContentLengthHeaderMiddlewareOptions,getCheckContentLengthHeaderPlugin,regionRedirectEndpointMiddleware,regionRedirectEndpointMiddlewareOptions,regionRedirectMiddlewareOptions,getRegionRedirectMiddlewarePlugin,s3ExpiresMiddleware,s3ExpiresMiddlewareOptions,getS3ExpiresMiddlewarePlugin,_S3ExpressIdentityCache,S3ExpressIdentityCache,S3ExpressIdentityCacheEntry,_S3ExpressIdentityProviderImpl,S3ExpressIdentityProviderImpl,SelectorType2,SESSION_TOKEN_QUERY_PARAM,SESSION_TOKEN_HEADER,SignatureV4S3Express,s3ExpressMiddleware,s3ExpressMiddlewareOptions,getS3ExpressPlugin,signS3Express,defaultErrorHandler2,defaultSuccessHandler2,s3ExpressHttpSigningMiddleware,getS3ExpressHttpSigningPlugin,resolveS3Config,THROW_IF_EMPTY_BODY,throw200ExceptionsMiddleware,collectBody2,throw200ExceptionsMiddlewareOptions,getThrow200ExceptionsPlugin,validate,bucketEndpointMiddlewareOptions,validateBucketNameMiddlewareOptions,getValidateBucketNamePlugin,DEFAULT_UA_APP_ID,EndpointCache,IP_V4_REGEX,isIpAddress,VALID_HOST_LABEL_REGEX,isValidHostLabel,customEndpointFunctions,EndpointError,booleanEquals,getAttrPathList,getAttr,isSet,not,DEFAULT_PORTS,endpointFunctions,evaluateTemplate,getReferenceValue,evaluateExpression,callFunction,evaluateCondition,evaluateConditions,getEndpointHeaders,getEndpointProperty,getEndpointProperties,getEndpointUrl,evaluateEndpointRule,evaluateErrorRule,evaluateTreeRule,evaluateRules,resolveEndpoint,isVirtualHostableS3Bucket,selectedPartitionsInfo,getUserAgentPrefix,awsEndpointFunctions,ACCOUNT_ID_ENDPOINT_REGEX,UA_NAME_ESCAPE_REGEX,UA_VALUE_ESCAPE_REGEX,BYTE_LIMIT,userAgentMiddleware,escapeUserAgent,getUserAgentMiddlewareOptions,getUserAgentPlugin,isFipsRegion,getRealRegion,resolveRegionConfig,resolveEventStreamSerdeConfig,CONTENT_LENGTH_HEADER2,contentLengthMiddlewareOptions,getContentLengthPlugin,resolveParamsForS3,DOMAIN_PATTERN,IP_ADDRESS_PATTERN,DOTS_PATTERN,isDnsCompatibleBucketName,isArnBucketName,createConfigValueProvider,getEndpointFromConfig,parseUrl,toEndpointV1,getEndpointFromInstructions,resolveParams,endpointMiddleware,endpointMiddlewareOptions,getEndpointPlugin,resolveEndpointConfig,RETRY_MODES,DEFAULT_RETRY_MODE,CLOCK_SKEW_ERROR_CODES,THROTTLING_ERROR_CODES,TRANSIENT_ERROR_CODES,TRANSIENT_ERROR_STATUS_CODES,NODEJS_TIMEOUT_ERROR_CODES,isClockSkewCorrectedError,isBrowserNetworkError,isThrottlingError,isTransientError,isServerError,DefaultRateLimiter,getDefaultRetryBackoffStrategy,createDefaultRetryToken,StandardRetryStrategy,AdaptiveRetryStrategy,ConfiguredRetryStrategy,getRandomValues,rnds8,byteToHex,randomUUID,native_default,v4_default,asSdkError,resolveRetryConfig,isStreamingPayload,retryMiddleware,isRetryStrategyV2,getRetryErrorInfo,getRetryErrorType,retryMiddlewareOptions,getRetryPlugin,getRetryAfterHint,SignatureV4MultiRegion,cp,cq,cr2,cs,ct,cu,cv,cw,cx,cy,cz,cA,cB,cC,cD,cE,cF,c,d3,e2,f,g,h,i,j,k,l,m2,n2,o,p2,q,r3,s,t2,u,v,w,x,y,z,A,B,C2,D,E,F,G2,H,J,K,L3,M2,N2,O,P2,Q,R,S,T,U,V,W2,X,Y,Z,aa,ab,ac,ad,ae,af,ag,ah,ai,aj,ak,al,am,an,ao,ap,aq,ar,as,at,au,av,aw,ax,ay,az,aA,aB,aC,aD,aE,aF,aG,aH,aI,aJ,aK,aL,aM,aN,aO,aP,aQ,aR,aS,aT,aU,aV,aW,aX,aY,aZ,ba,bb,bc,bd,be,bf,bg,bh,bi,bj,bk,bl,bm,bn,bo,bp,bq,br,bs,bt,bu,bv,bw,bx,by,bz,bA,bB,bC,bD,bE,bF,bG,bH,bI,bJ,bK,bL,bM,bN,bO,bP,bQ,bR,bS,bT,bU,bV,bW,bX,bY,bZ,ca,cb,cc,cd,ce,cf,cg,ch,ci,cj,ck,cl,cm,cn,co,ruleSet,cache,defaultEndpointResolver,defaultS3HttpAuthSchemeParametersProvider,defaultS3HttpAuthSchemeProvider,resolveHttpAuthSchemeConfig,resolveClientEndpointParameters,commonParams,S3ServiceException,NoSuchUpload,ObjectNotInActiveTierError,BucketAlreadyExists,BucketAlreadyOwnedByYou,NoSuchBucket,AnalyticsFilter,MetricsFilter,InvalidObjectState,NoSuchKey,NotFound,CompleteMultipartUploadOutputFilterSensitiveLog,CompleteMultipartUploadRequestFilterSensitiveLog,CopyObjectOutputFilterSensitiveLog,CopyObjectRequestFilterSensitiveLog,CreateMultipartUploadOutputFilterSensitiveLog,CreateMultipartUploadRequestFilterSensitiveLog,SessionCredentialsFilterSensitiveLog,CreateSessionOutputFilterSensitiveLog,CreateSessionRequestFilterSensitiveLog,ServerSideEncryptionByDefaultFilterSensitiveLog,ServerSideEncryptionRuleFilterSensitiveLog,ServerSideEncryptionConfigurationFilterSensitiveLog,GetBucketEncryptionOutputFilterSensitiveLog,SSEKMSFilterSensitiveLog,InventoryEncryptionFilterSensitiveLog,InventoryS3BucketDestinationFilterSensitiveLog,InventoryDestinationFilterSensitiveLog,InventoryConfigurationFilterSensitiveLog,GetBucketInventoryConfigurationOutputFilterSensitiveLog,GetObjectOutputFilterSensitiveLog,GetObjectRequestFilterSensitiveLog,GetObjectAttributesRequestFilterSensitiveLog,GetObjectTorrentOutputFilterSensitiveLog,HeadObjectOutputFilterSensitiveLog,HeadObjectRequestFilterSensitiveLog,ListBucketInventoryConfigurationsOutputFilterSensitiveLog,ListPartsRequestFilterSensitiveLog,XmlText,XmlNode,EncryptionTypeMismatch,InvalidRequest,InvalidWriteOffset,TooManyParts,ObjectAlreadyInActiveTierError,SelectObjectContentEventStream,PutBucketEncryptionRequestFilterSensitiveLog,PutBucketInventoryConfigurationRequestFilterSensitiveLog,PutObjectOutputFilterSensitiveLog,PutObjectRequestFilterSensitiveLog,EncryptionFilterSensitiveLog,S3LocationFilterSensitiveLog,OutputLocationFilterSensitiveLog,RestoreRequestFilterSensitiveLog,RestoreObjectRequestFilterSensitiveLog,SelectObjectContentOutputFilterSensitiveLog,SelectObjectContentRequestFilterSensitiveLog,UploadPartOutputFilterSensitiveLog,UploadPartRequestFilterSensitiveLog,UploadPartCopyOutputFilterSensitiveLog,UploadPartCopyRequestFilterSensitiveLog,WriteGetObjectResponseRequestFilterSensitiveLog,se_AbortMultipartUploadCommand,se_CompleteMultipartUploadCommand,se_CopyObjectCommand,se_CreateBucketCommand,se_CreateBucketMetadataTableConfigurationCommand,se_CreateMultipartUploadCommand,se_CreateSessionCommand,se_DeleteBucketCommand,se_DeleteBucketAnalyticsConfigurationCommand,se_DeleteBucketCorsCommand,se_DeleteBucketEncryptionCommand,se_DeleteBucketIntelligentTieringConfigurationCommand,se_DeleteBucketInventoryConfigurationCommand,se_DeleteBucketLifecycleCommand,se_DeleteBucketMetadataTableConfigurationCommand,se_DeleteBucketMetricsConfigurationCommand,se_DeleteBucketOwnershipControlsCommand,se_DeleteBucketPolicyCommand,se_DeleteBucketReplicationCommand,se_DeleteBucketTaggingCommand,se_DeleteBucketWebsiteCommand,se_DeleteObjectCommand,se_DeleteObjectsCommand,se_DeleteObjectTaggingCommand,se_DeletePublicAccessBlockCommand,se_GetBucketAccelerateConfigurationCommand,se_GetBucketAclCommand,se_GetBucketAnalyticsConfigurationCommand,se_GetBucketCorsCommand,se_GetBucketEncryptionCommand,se_GetBucketIntelligentTieringConfigurationCommand,se_GetBucketInventoryConfigurationCommand,se_GetBucketLifecycleConfigurationCommand,se_GetBucketLocationCommand,se_GetBucketLoggingCommand,se_GetBucketMetadataTableConfigurationCommand,se_GetBucketMetricsConfigurationCommand,se_GetBucketNotificationConfigurationCommand,se_GetBucketOwnershipControlsCommand,se_GetBucketPolicyCommand,se_GetBucketPolicyStatusCommand,se_GetBucketReplicationCommand,se_GetBucketRequestPaymentCommand,se_GetBucketTaggingCommand,se_GetBucketVersioningCommand,se_GetBucketWebsiteCommand,se_GetObjectCommand,se_GetObjectAclCommand,se_GetObjectAttributesCommand,se_GetObjectLegalHoldCommand,se_GetObjectLockConfigurationCommand,se_GetObjectRetentionCommand,se_GetObjectTaggingCommand,se_GetObjectTorrentCommand,se_GetPublicAccessBlockCommand,se_HeadBucketCommand,se_HeadObjectCommand,se_ListBucketAnalyticsConfigurationsCommand,se_ListBucketIntelligentTieringConfigurationsCommand,se_ListBucketInventoryConfigurationsCommand,se_ListBucketMetricsConfigurationsCommand,se_ListBucketsCommand,se_ListDirectoryBucketsCommand,se_ListMultipartUploadsCommand,se_ListObjectsCommand,se_ListObjectsV2Command,se_ListObjectVersionsCommand,se_ListPartsCommand,se_PutBucketAccelerateConfigurationCommand,se_PutBucketAclCommand,se_PutBucketAnalyticsConfigurationCommand,se_PutBucketCorsCommand,se_PutBucketEncryptionCommand,se_PutBucketIntelligentTieringConfigurationCommand,se_PutBucketInventoryConfigurationCommand,se_PutBucketLifecycleConfigurationCommand,se_PutBucketLoggingCommand,se_PutBucketMetricsConfigurationCommand,se_PutBucketNotificationConfigurationCommand,se_PutBucketOwnershipControlsCommand,se_PutBucketPolicyCommand,se_PutBucketReplicationCommand,se_PutBucketRequestPaymentCommand,se_PutBucketTaggingCommand,se_PutBucketVersioningCommand,se_PutBucketWebsiteCommand,se_PutObjectCommand,se_PutObjectAclCommand,se_PutObjectLegalHoldCommand,se_PutObjectLockConfigurationCommand,se_PutObjectRetentionCommand,se_PutObjectTaggingCommand,se_PutPublicAccessBlockCommand,se_RestoreObjectCommand,se_SelectObjectContentCommand,se_UploadPartCommand,se_UploadPartCopyCommand,se_WriteGetObjectResponseCommand,de_AbortMultipartUploadCommand,de_CompleteMultipartUploadCommand,de_CopyObjectCommand,de_CreateBucketCommand,de_CreateBucketMetadataTableConfigurationCommand,de_CreateMultipartUploadCommand,de_CreateSessionCommand,de_DeleteBucketCommand,de_DeleteBucketAnalyticsConfigurationCommand,de_DeleteBucketCorsCommand,de_DeleteBucketEncryptionCommand,de_DeleteBucketIntelligentTieringConfigurationCommand,de_DeleteBucketInventoryConfigurationCommand,de_DeleteBucketLifecycleCommand,de_DeleteBucketMetadataTableConfigurationCommand,de_DeleteBucketMetricsConfigurationCommand,de_DeleteBucketOwnershipControlsCommand,de_DeleteBucketPolicyCommand,de_DeleteBucketReplicationCommand,de_DeleteBucketTaggingCommand,de_DeleteBucketWebsiteCommand,de_DeleteObjectCommand,de_DeleteObjectsCommand,de_DeleteObjectTaggingCommand,de_DeletePublicAccessBlockCommand,de_GetBucketAccelerateConfigurationCommand,de_GetBucketAclCommand,de_GetBucketAnalyticsConfigurationCommand,de_GetBucketCorsCommand,de_GetBucketEncryptionCommand,de_GetBucketIntelligentTieringConfigurationCommand,de_GetBucketInventoryConfigurationCommand,de_GetBucketLifecycleConfigurationCommand,de_GetBucketLocationCommand,de_GetBucketLoggingCommand,de_GetBucketMetadataTableConfigurationCommand,de_GetBucketMetricsConfigurationCommand,de_GetBucketNotificationConfigurationCommand,de_GetBucketOwnershipControlsCommand,de_GetBucketPolicyCommand,de_GetBucketPolicyStatusCommand,de_GetBucketReplicationCommand,de_GetBucketRequestPaymentCommand,de_GetBucketTaggingCommand,de_GetBucketVersioningCommand,de_GetBucketWebsiteCommand,de_GetObjectCommand,de_GetObjectAclCommand,de_GetObjectAttributesCommand,de_GetObjectLegalHoldCommand,de_GetObjectLockConfigurationCommand,de_GetObjectRetentionCommand,de_GetObjectTaggingCommand,de_GetObjectTorrentCommand,de_GetPublicAccessBlockCommand,de_HeadBucketCommand,de_HeadObjectCommand,de_ListBucketAnalyticsConfigurationsCommand,de_ListBucketIntelligentTieringConfigurationsCommand,de_ListBucketInventoryConfigurationsCommand,de_ListBucketMetricsConfigurationsCommand,de_ListBucketsCommand,de_ListDirectoryBucketsCommand,de_ListMultipartUploadsCommand,de_ListObjectsCommand,de_ListObjectsV2Command,de_ListObjectVersionsCommand,de_ListPartsCommand,de_PutBucketAccelerateConfigurationCommand,de_PutBucketAclCommand,de_PutBucketAnalyticsConfigurationCommand,de_PutBucketCorsCommand,de_PutBucketEncryptionCommand,de_PutBucketIntelligentTieringConfigurationCommand,de_PutBucketInventoryConfigurationCommand,de_PutBucketLifecycleConfigurationCommand,de_PutBucketLoggingCommand,de_PutBucketMetricsConfigurationCommand,de_PutBucketNotificationConfigurationCommand,de_PutBucketOwnershipControlsCommand,de_PutBucketPolicyCommand,de_PutBucketReplicationCommand,de_PutBucketRequestPaymentCommand,de_PutBucketTaggingCommand,de_PutBucketVersioningCommand,de_PutBucketWebsiteCommand,de_PutObjectCommand,de_PutObjectAclCommand,de_PutObjectLegalHoldCommand,de_PutObjectLockConfigurationCommand,de_PutObjectRetentionCommand,de_PutObjectTaggingCommand,de_PutPublicAccessBlockCommand,de_RestoreObjectCommand,de_SelectObjectContentCommand,de_UploadPartCommand,de_UploadPartCopyCommand,de_WriteGetObjectResponseCommand,de_CommandError,throwDefaultError2,de_BucketAlreadyExistsRes,de_BucketAlreadyOwnedByYouRes,de_EncryptionTypeMismatchRes,de_InvalidObjectStateRes,de_InvalidRequestRes,de_InvalidWriteOffsetRes,de_NoSuchBucketRes,de_NoSuchKeyRes,de_NoSuchUploadRes,de_NotFoundRes,de_ObjectAlreadyInActiveTierErrorRes,de_ObjectNotInActiveTierErrorRes,de_TooManyPartsRes,de_SelectObjectContentEventStream,de_ContinuationEvent_event,de_EndEvent_event,de_ProgressEvent_event,de_RecordsEvent_event,de_StatsEvent_event,se_AbortIncompleteMultipartUpload,se_AccelerateConfiguration,se_AccessControlPolicy,se_AccessControlTranslation,se_AllowedHeaders,se_AllowedMethods,se_AllowedOrigins,se_AnalyticsAndOperator,se_AnalyticsConfiguration,se_AnalyticsExportDestination,se_AnalyticsFilter,se_AnalyticsS3BucketDestination,se_BucketInfo,se_BucketLifecycleConfiguration,se_BucketLoggingStatus,se_CompletedMultipartUpload,se_CompletedPart,se_CompletedPartList,se_Condition,se_CORSConfiguration,se_CORSRule,se_CORSRules,se_CreateBucketConfiguration,se_CSVInput,se_CSVOutput,se_DefaultRetention,se_Delete,se_DeleteMarkerReplication,se_Destination,se_Encryption,se_EncryptionConfiguration,se_ErrorDocument,se_EventBridgeConfiguration,se_EventList,se_ExistingObjectReplication,se_ExposeHeaders,se_FilterRule,se_FilterRuleList,se_GlacierJobParameters,se_Grant,se_Grantee,se_Grants,se_IndexDocument,se_InputSerialization,se_IntelligentTieringAndOperator,se_IntelligentTieringConfiguration,se_IntelligentTieringFilter,se_InventoryConfiguration,se_InventoryDestination,se_InventoryEncryption,se_InventoryFilter,se_InventoryOptionalFields,se_InventoryS3BucketDestination,se_InventorySchedule,se_JSONInput,se_JSONOutput,se_LambdaFunctionConfiguration,se_LambdaFunctionConfigurationList,se_LifecycleExpiration,se_LifecycleRule,se_LifecycleRuleAndOperator,se_LifecycleRuleFilter,se_LifecycleRules,se_LocationInfo,se_LoggingEnabled,se_MetadataEntry,se_MetadataTableConfiguration,se_Metrics,se_MetricsAndOperator,se_MetricsConfiguration,se_MetricsFilter,se_NoncurrentVersionExpiration,se_NoncurrentVersionTransition,se_NoncurrentVersionTransitionList,se_NotificationConfiguration,se_NotificationConfigurationFilter,se_ObjectIdentifier,se_ObjectIdentifierList,se_ObjectLockConfiguration,se_ObjectLockLegalHold,se_ObjectLockRetention,se_ObjectLockRule,se_OutputLocation,se_OutputSerialization,se_Owner,se_OwnershipControls,se_OwnershipControlsRule,se_OwnershipControlsRules,se_ParquetInput,se_PartitionedPrefix,se_PublicAccessBlockConfiguration,se_QueueConfiguration,se_QueueConfigurationList,se_Redirect,se_RedirectAllRequestsTo,se_ReplicaModifications,se_ReplicationConfiguration,se_ReplicationRule,se_ReplicationRuleAndOperator,se_ReplicationRuleFilter,se_ReplicationRules,se_ReplicationTime,se_ReplicationTimeValue,se_RequestPaymentConfiguration,se_RequestProgress,se_RestoreRequest,se_RoutingRule,se_RoutingRules,se_S3KeyFilter,se_S3Location,se_S3TablesDestination,se_ScanRange,se_SelectParameters,se_ServerSideEncryptionByDefault,se_ServerSideEncryptionConfiguration,se_ServerSideEncryptionRule,se_ServerSideEncryptionRules,se_SimplePrefix,se_SourceSelectionCriteria,se_SSEKMS,se_SseKmsEncryptedObjects,se_SSES3,se_StorageClassAnalysis,se_StorageClassAnalysisDataExport,se_Tag,se_Tagging,se_TagSet,se_TargetGrant,se_TargetGrants,se_TargetObjectKeyFormat,se_Tiering,se_TieringList,se_TopicConfiguration,se_TopicConfigurationList,se_Transition,se_TransitionList,se_UserMetadata,se_VersioningConfiguration,se_WebsiteConfiguration,de_AbortIncompleteMultipartUpload,de_AccessControlTranslation,de_AllowedHeaders,de_AllowedMethods,de_AllowedOrigins,de_AnalyticsAndOperator,de_AnalyticsConfiguration,de_AnalyticsConfigurationList,de_AnalyticsExportDestination,de_AnalyticsFilter,de_AnalyticsS3BucketDestination,de_Bucket,de_Buckets,de_Checksum,de_ChecksumAlgorithmList,de_CommonPrefix,de_CommonPrefixList,de_Condition,de_ContinuationEvent,de_CopyObjectResult,de_CopyPartResult,de_CORSRule,de_CORSRules,de_DefaultRetention,de_DeletedObject,de_DeletedObjects,de_DeleteMarkerEntry,de_DeleteMarkerReplication,de_DeleteMarkers,de_Destination,de_EncryptionConfiguration,de_EndEvent,de__Error,de_ErrorDetails,de_ErrorDocument,de_Errors,de_EventBridgeConfiguration,de_EventList,de_ExistingObjectReplication,de_ExposeHeaders,de_FilterRule,de_FilterRuleList,de_GetBucketMetadataTableConfigurationResult,de_GetObjectAttributesParts,de_Grant,de_Grantee,de_Grants,de_IndexDocument,de_Initiator,de_IntelligentTieringAndOperator,de_IntelligentTieringConfiguration,de_IntelligentTieringConfigurationList,de_IntelligentTieringFilter,de_InventoryConfiguration,de_InventoryConfigurationList,de_InventoryDestination,de_InventoryEncryption,de_InventoryFilter,de_InventoryOptionalFields,de_InventoryS3BucketDestination,de_InventorySchedule,de_LambdaFunctionConfiguration,de_LambdaFunctionConfigurationList,de_LifecycleExpiration,de_LifecycleRule,de_LifecycleRuleAndOperator,de_LifecycleRuleFilter,de_LifecycleRules,de_LoggingEnabled,de_MetadataTableConfigurationResult,de_Metrics,de_MetricsAndOperator,de_MetricsConfiguration,de_MetricsConfigurationList,de_MetricsFilter,de_MultipartUpload,de_MultipartUploadList,de_NoncurrentVersionExpiration,de_NoncurrentVersionTransition,de_NoncurrentVersionTransitionList,de_NotificationConfigurationFilter,de__Object,de_ObjectList,de_ObjectLockConfiguration,de_ObjectLockLegalHold,de_ObjectLockRetention,de_ObjectLockRule,de_ObjectPart,de_ObjectVersion,de_ObjectVersionList,de_Owner,de_OwnershipControls,de_OwnershipControlsRule,de_OwnershipControlsRules,de_Part,de_PartitionedPrefix,de_Parts,de_PartsList,de_PolicyStatus,de_Progress,de_PublicAccessBlockConfiguration,de_QueueConfiguration,de_QueueConfigurationList,de_Redirect,de_RedirectAllRequestsTo,de_ReplicaModifications,de_ReplicationConfiguration,de_ReplicationRule,de_ReplicationRuleAndOperator,de_ReplicationRuleFilter,de_ReplicationRules,de_ReplicationTime,de_ReplicationTimeValue,de_RestoreStatus,de_RoutingRule,de_RoutingRules,de_S3KeyFilter,de_S3TablesDestinationResult,de_ServerSideEncryptionByDefault,de_ServerSideEncryptionConfiguration,de_ServerSideEncryptionRule,de_ServerSideEncryptionRules,de_SessionCredentials,de_SimplePrefix,de_SourceSelectionCriteria,de_SSEKMS,de_SseKmsEncryptedObjects,de_SSES3,de_Stats,de_StorageClassAnalysis,de_StorageClassAnalysisDataExport,de_Tag,de_TagSet,de_TargetGrant,de_TargetGrants,de_TargetObjectKeyFormat,de_Tiering,de_TieringList,de_TopicConfiguration,de_TopicConfigurationList,de_Transition,de_TransitionList,deserializeMetadata2,collectBodyString2,_A,_AAO,_AC,_ACL,_ACLc,_ACLn,_ACP,_ACT,_ACc,_AD,_AED,_AF,_AH,_AHl,_AI,_AIMU,_AIc,_AKI,_AM,_AMl,_AO,_AOl,_APA,_APAc,_AQRD,_AR,_ARI,_AS,_ASBD,_ASEFF,_ASSEBD,_AT,_Ac,_B,_BAI,_BAS,_BGR,_BI,_BKE,_BLC,_BLCu,_BLN,_BLP,_BLS,_BLT,_BN,_BP,_BPA,_BPP,_BR,_BRy,_BS,_BT,_BVS,_Bu,_C,_CA,_CACL,_CBC,_CC,_CCRC,_CCRCC,_CCRCNVME,_CD,_CDr,_CE,_CF,_CFC,_CL,_CLo,_CM,_CMD,_CMU,_CORSC,_CORSR,_CORSRu,_CP,_CPo,_CR,_CRSBA,_CS,_CSHA,_CSHAh,_CSIM,_CSIMS,_CSINM,_CSIUS,_CSR,_CSSSECA,_CSSSECK,_CSSSECKMD,_CSV,_CSVI,_CSVIn,_CSVO,_CT,_CTo,_CTom,_CTon,_Ch,_Co,_Cod,_Com,_Con,_D,_DAI,_DE,_DM,_DMR,_DMRS,_DMVI,_DMe,_DN,_DR,_DRe,_Da,_Dat,_De,_Del,_Des,_Desc,_E,_EA,_EBC,_EBO,_EC,_ECn,_ED,_EH,_EHx,_EM,_EODM,_EOR,_EORS,_ERP,_ES,_ESBO,_ESx,_ET,_ETa,_ETn,_ETv,_ETx,_En,_Ena,_End,_Er,_Err,_Ev,_Eve,_Ex,_Exp,_F,_FD,_FHI,_FO,_FR,_FRN,_FRV,_FRi,_Fi,_Fo,_Fr,_G,_GFC,_GJP,_GR,_GRACP,_GW,_GWACP,_Gr,_Gra,_HECRE,_HN,_HRC,_I,_IC,_ICL,_ID,_ID_,_IDn,_IE,_IEn,_IF,_IFn,_IFnv,_II,_IIOV,_IL,_IM,_IMIT,_IMLMT,_IMS,_IMSf,_INM,_IOF,_IOV,_IP,_IPA,_IRIP,_IS,_ISBD,_ISn,_IT,_ITAO,_ITAT,_ITC,_ITCL,_ITD,_ITF,_ITI,_ITS,_IUS,_In,_Ini,_JSON,_JSONI,_JSONO,_JSONT,_K,_KC,_KI,_KM,_KMSC,_KMSKI,_KMSMKID,_KPE,_L,_LC,_LE,_LEi,_LFA,_LFC,_LFCa,_LI,_LM,_LMT,_LNAS,_LP,_LR,_LRAO,_LRF,_LT,_M,_MAO,_MAS,_MB,_MC,_MCL,_MD,_MDB,_MDf,_ME,_MF,_MFA,_MFAD,_MI,_MK,_MKe,_MM,_MOS,_MP,_MS,_MTC,_MTCR,_MU,_MV,_Me,_Mes,_Mi,_Mo,_N,_NC,_NCF,_NCT,_ND,_NI,_NKM,_NM,_NNV,_NPNM,_NUIM,_NVE,_NVIM,_NVT,_NVTo,_O,_OA,_OC,_OCACL,_OCR,_OF,_OI,_OK,_OL,_OLC,_OLE,_OLEFB,_OLLH,_OLLHS,_OLM,_OLR,_OLRM,_OLRUD,_OLRb,_OO,_OOA,_OOw,_OP,_OS,_OSGT,_OSGTB,_OSLT,_OSLTB,_OSV,_OSb,_OVI,_Ob,_P,_PABC,_PC,_PDS,_PI,_PN,_PNM,_PP,_Pa,_Par,_Parq,_Part,_Pe,_Pr,_Pri,_Q,_QA,_QC,_QCu,_QCuo,_QEC,_QF,_Qu,_R,_RART,_RC,_RCC,_RCD,_RCE,_RCL,_RCT,_RCe,_RD,_RE,_RED,_RKKID,_RKPW,_RKW,_RM,_RMS,_ROP,_RP,_RPB,_RPC,_RPe,_RR,_RRAO,_RRF,_RRS,_RRT,_RRe,_RRes,_RRo,_RRou,_RS,_RSe,_RT,_RTS,_RTV,_RTe,_RUD,_Re,_Red,_Ro,_Ru,_Rul,_S,_SA,_SAK,_SBD,_SC,_SCA,_SCADE,_SCASV,_SCt,_SDV,_SK,_SKEO,_SKEOS,_SKF,_SKe,_SL,_SM,_SOCR,_SP,_SPi,_SR,_SS,_SSC,_SSE,_SSEA,_SSEBD,_SSEC,_SSECA,_SSECK,_SSECKMD,_SSEKMS,_SSEKMSEC,_SSEKMSKI,_SSER,_SSES,_ST,_STBA,_STD,_STDR,_STN,_S_,_Sc,_Se,_Si,_St,_Su,_T,_TA,_TAa,_TB,_TBA,_TC,_TCo,_TCop,_TD,_TDMOS,_TG,_TGa,_TN,_TNa,_TOKF,_TP,_TPC,_TS,_TSC,_Ta,_Tag,_Ti,_Tie,_Tier,_Tim,_To,_Top,_Tr,_Tra,_Ty,_U,_UI,_UIM,_UM,_URI,_Up,_V,_VC,_VCe,_VI,_VIM,_Va,_Ve,_WC,_WOB,_WRL,_Y,_a5,_ac,_acl,_ar,_at,_br,_c2,_cc,_cd,_ce,_cl,_cl_,_cm,_cr,_ct,_ct_,_d,_de,_e,_en,_et,_eta,_ex,_fo,_i,_im,_ims,_in,_inm,_it,_ius,_km,_l,_lh,_lm,_lo,_log,_lt,_m,_mT,_ma,_mb,_mdb,_me,_mk,_mp,_mu,_n,_oC,_ol,_p,_pAB,_pN,_pS,_pnm,_pr,_r,_rP,_ra,_rcc,_rcd,_rce,_rcl,_rct,_re,_res,_ret,_s,_sa,_se,_st,_t,_to,_u,_uI,_uim,_v,_vI,_ve,_ver,_vim,_w,_x,_xaa,_xaad,_xaapa,_xaari,_xaas,_xabgr,_xabln,_xablt,_xabole,_xabolt,_xabr,_xaca,_xacc,_xacc_,_xacc__,_xacm,_xacrsba,_xacs,_xacs_,_xacs__,_xacsim,_xacsims,_xacsinm,_xacsius,_xacsm,_xacsr,_xacssseca,_xacssseck,_xacssseckm,_xacsvi,_xact,_xadm,_xae,_xaebo,_xafec,_xafem,_xafhar,_xafhcc,_xafhcd,_xafhce,_xafhcl,_xafhcr,_xafhct,_xafhe,_xafhe_,_xafhlm,_xafhxacc,_xafhxacc_,_xafhxacc__,_xafhxacs,_xafhxacs_,_xafhxadm,_xafhxae,_xafhxamm,_xafhxampc,_xafhxaollh,_xafhxaolm,_xafhxaolrud,_xafhxar,_xafhxarc,_xafhxars,_xafhxasc,_xafhxasse,_xafhxasseakki,_xafhxassebke,_xafhxasseca,_xafhxasseckm,_xafhxatc,_xafhxavi,_xafs,_xagfc,_xagr,_xagra,_xagw,_xagwa,_xaimit,_xaimlmt,_xaims,_xam,_xamd,_xamm,_xamos,_xamp,_xampc,_xaoa,_xaollh,_xaolm,_xaolrud,_xaoo,_xaooa,_xaos,_xapnm,_xar,_xarc,_xarop,_xarp,_xarr,_xars,_xart,_xasc,_xasca,_xasdv,_xasebo,_xasse,_xasseakki,_xassebke,_xassec,_xasseca,_xasseck,_xasseckm,_xat,_xatc,_xatd,_xatdmos,_xavi,_xawob,_xawrl,_xi,CreateSessionCommand,fromUtf84,SHA_1_HASH,SHA_1_HMAC_ALGO,EMPTY_DATA_SHA_1,fallbackWindow,Sha1,subtleCryptoMethods,Sha12,SHA_256_HASH,SHA_256_HMAC_ALGO,EMPTY_DATA_SHA_256,Sha256,BLOCK_SIZE,KEY,INIT,MAX_HASHABLE_LENGTH,RawSha256,Sha2562,Sha2563,import_bowser,createDefaultUserAgentProvider,Int642,HeaderMarshaller,HEADER_VALUE_TYPE2,BOOLEAN_TAG,BYTE_TAG,SHORT_TAG,INT_TAG,LONG_TAG,BINARY_TAG,STRING_TAG,TIMESTAMP_TAG,UUID_TAG,UUID_PATTERN2,PRELUDE_MEMBER_LENGTH,PRELUDE_LENGTH,CHECKSUM_LENGTH,MINIMUM_MESSAGE_LENGTH,EventStreamCodec,MessageDecoderStream,MessageEncoderStream,SmithyMessageDecoderStream,SmithyMessageEncoderStream,EventStreamMarshaller,readableStreamtoIterable,iterableToReadableStream,EventStreamMarshaller2,isReadableStream2,eventStreamSerdeProvider2,blobHasher,invalidProvider,INIT2,Md5,TEXT_ENCODER,calculateBodyLength,getRuntimeConfig,DEFAULTS_MODE_OPTIONS,import_bowser2,resolveDefaultsModeConfig,isMobileBrowser,getRuntimeConfig2,getAwsRegionExtensionConfiguration,resolveAwsRegionExtensionConfiguration,getHttpAuthExtensionConfiguration,resolveHttpAuthRuntimeConfig,resolveRuntimeExtensions,S3Client,AbortMultipartUploadCommand,ssecMiddlewareOptions,getSsecPlugin,CompleteMultipartUploadCommand,CopyObjectCommand,locationConstraintMiddlewareOptions,getLocationConstraintPlugin,CreateBucketCommand,CreateBucketMetadataTableConfigurationCommand,CreateMultipartUploadCommand,DeleteBucketAnalyticsConfigurationCommand,DeleteBucketCommand,DeleteBucketCorsCommand,DeleteBucketEncryptionCommand,DeleteBucketIntelligentTieringConfigurationCommand,DeleteBucketInventoryConfigurationCommand,DeleteBucketLifecycleCommand,DeleteBucketMetadataTableConfigurationCommand,DeleteBucketMetricsConfigurationCommand,DeleteBucketOwnershipControlsCommand,DeleteBucketPolicyCommand,DeleteBucketReplicationCommand,DeleteBucketTaggingCommand,DeleteBucketWebsiteCommand,DeleteObjectCommand,DeleteObjectsCommand,DeleteObjectTaggingCommand,DeletePublicAccessBlockCommand,GetBucketAccelerateConfigurationCommand,GetBucketAclCommand,GetBucketAnalyticsConfigurationCommand,GetBucketCorsCommand,GetBucketEncryptionCommand,GetBucketIntelligentTieringConfigurationCommand,GetBucketInventoryConfigurationCommand,GetBucketLifecycleConfigurationCommand,GetBucketLocationCommand,GetBucketLoggingCommand,GetBucketMetadataTableConfigurationCommand,GetBucketMetricsConfigurationCommand,GetBucketNotificationConfigurationCommand,GetBucketOwnershipControlsCommand,GetBucketPolicyCommand,GetBucketPolicyStatusCommand,GetBucketReplicationCommand,GetBucketRequestPaymentCommand,GetBucketTaggingCommand,GetBucketVersioningCommand,GetBucketWebsiteCommand,GetObjectAclCommand,GetObjectAttributesCommand,GetObjectCommand,GetObjectLegalHoldCommand,GetObjectLockConfigurationCommand,GetObjectRetentionCommand,GetObjectTaggingCommand,GetObjectTorrentCommand,GetPublicAccessBlockCommand,HeadBucketCommand,HeadObjectCommand,ListBucketAnalyticsConfigurationsCommand,ListBucketIntelligentTieringConfigurationsCommand,ListBucketInventoryConfigurationsCommand,ListBucketMetricsConfigurationsCommand,ListBucketsCommand,ListDirectoryBucketsCommand,ListMultipartUploadsCommand,ListObjectsCommand,ListObjectsV2Command,ListObjectVersionsCommand,ListPartsCommand,PutBucketAccelerateConfigurationCommand,PutBucketAclCommand,PutBucketAnalyticsConfigurationCommand,PutBucketCorsCommand,PutBucketEncryptionCommand,PutBucketIntelligentTieringConfigurationCommand,PutBucketInventoryConfigurationCommand,PutBucketLifecycleConfigurationCommand,PutBucketLoggingCommand,PutBucketMetricsConfigurationCommand,PutBucketNotificationConfigurationCommand,PutBucketOwnershipControlsCommand,PutBucketPolicyCommand,PutBucketReplicationCommand,PutBucketRequestPaymentCommand,PutBucketTaggingCommand,PutBucketVersioningCommand,PutBucketWebsiteCommand,PutObjectAclCommand,PutObjectCommand,PutObjectLegalHoldCommand,PutObjectLockConfigurationCommand,PutObjectRetentionCommand,PutObjectTaggingCommand,PutPublicAccessBlockCommand,RestoreObjectCommand,SelectObjectContentCommand,UploadPartCommand,UploadPartCopyCommand,WriteGetObjectResponseCommand,S3,applyMd5BodyChecksumMiddleware,hasHeader3,ch2,wk,u8,u16,i32,fleb,fdeb,clim,freb,_a6,fl,revfl,_b4,fd,revfd,rev,hMap,flt,fdt,flm,flrm,fdm,fdrm,max,bits,bits16,shft,slc,ec,err2,inflt,wbits,wbits16,hTree,ln,lc,clen,wfblk,wblk,deo,et,dflt,dopt,mrg,wcln,ch3,cbfs,wrkr,bInflt,bDflt,pbf,gopt,cbify,fltn,td2,x2,i2,wrappedInflate,wrappedDeflate,replicationFilter,MARK_SHIFT_COMPRESSED,CheckPointInfoDefault,PREFIX_TRENCH,idx,series,indexes,inProgress,failed,Trench,_handlers,SyncParamsHandlerError,SyncParamsFetchError,SyncParamsNotFoundError,SyncParamsUpdateError,RECORD_SPLIT,UNIT_SPLIT,te4,JournalSyncAbstract,webcrypto3,SALT,previousPassphrase,encryptionKey,_nonceV3,bufV3,previousDecryptionPassphrase,decryptionKey,webcrypto4,ENCRYPT_V1_PREFIX_PROBABLY,ENCRYPT_V2_PREFIX,ENCRYPT_V3_PREFIX,KeyBuffs,decKeyBuffs,KEY_RECYCLE_COUNT,semiStaticFieldBuffer,nonceBuffer,webcrypto5,keyGCCount,decKeyIdx,decKeyMin,JournalSyncMinio,MILSTONE_DOCID,currentVersionRange,LiveSyncJournalReplicator,checkRemoteVersion,bumpRemoteVersion,checkSyncInfo,SELECTOR_COMPROMISED_CHUNK_1,SELECTOR_COMPROMISED_CHUNK_2,SYMBOL_USED,SYMBOL_END_OF_DATA,workerStreams,writers,responseBuf,writerPromise,tasks2,workers,key2,roundRobinIdx,encrypt5,decrypt5,encryptHKDF,decryptHKDF,Encrypt_HKDF_Header,Encrypt_OLD_Header,EncryptionVersions_UNENCRYPTED,EncryptionVersions_ENCRYPTED,EncryptionVersions_HKDF,EncryptionVersions_UNKNOWN,ENCRYPTED_META_PREFIX,MESSAGE_FALLBACK_DECRYPT_FAILED,ENCRYPTION_HKDF_FAILED,DECRYPTION_HKDF_FAILED,DECRYPTION_FALLBACK_FAILED,preprocessOutgoing,enableEncryption,EDEN_ENCRYPTED_KEY,EDEN_ENCRYPTED_KEY_HKDF,currentVersionRange2,selectorOnDemandPull,LiveSyncCouchDBReplicator,measures,root_17,root4,$$css5,TestPaneView,ModuleDev,SerializedFileAccess,StorageEventManager,StorageEventManagerObsidian,ModuleFileAccessObsidian,AutoClosableModal,InputStringDialog,PopoverSelectString,MessageBox,askYesNo,askSelectString,askString,ModuleInputUIObsidian,_a7,OnDialogSettingsDefault,SettingInformation,ConditionType,RuleLevel,DoctorRegulationV0_25_27,DoctorRegulation,RebuildOptions_AutomaticAcceptable,RebuildOptions_ConfirmIfRequired,RebuildOptions_SkipEvenIfRequired,CONTEXT_DIALOG_CONTROLS,root5,$$css6,SvelteDialog,SvelteDialogManager,root_110,root6,$$css7,root_111,root7,root8,root_113,root9,$$css8,root10,$$css9,root11,root12,root13,root_44,root_24,root_72,root14,root_25,root_114,root15,root16,$$css10,root_45,root_26,root_73,root17,root_46,root_27,root_83,root18,root_28,root19,root20,root21,root_115,root_29,root_74,root22,root_116,root_47,root23,root_117,root_48,root24,root_118,root_210,root_102,root25,root_33,root_119,root_75,root26,checkConfig,on_click2,root_211,root_120,root_84,root27,$$css11,root_212,root_49,root_64,root_85,root_1110,root_134,root_142,root_152,root_162,root_182,root_192,root_123,root_242,root28,root_213,root_410,root_65,root_76,root_86,root_93,root_1111,root_143,root_183,root29,PouchError,MISSING_BULK_DOCS,MISSING_DOC,REV_CONFLICT,INVALID_ID,MISSING_ID,RESERVED_ID,UNKNOWN_ERROR,BAD_ARG,QUERY_PARSE_ERROR,DOC_VALIDATION,BAD_REQUEST,NOT_AN_OBJECT,IDB_ERROR,INVALID_REV,MISSING_STUB,getRandomValues2,rnds82,regex_default2,validate_default2,byteToHex2,stringify_default2,v4_default2,thisAtob,thisBtoa,import_spark_md5,setImmediateShim,MD5_CHUNK_SIZE,import_events15,funcToString,objectCtorString,MAX_NUM_CONCURRENT_REQUESTS,hasLocal,nextTick,Changes,keys2,qName,qParser,parser,uuid,f3,h2,MIN_MAGNITUDE,MAGNITUDE_DIGITS,SEP,combinationFields,matchers,index_browser_es_default,import_events16,Changes2,validRevRegex,AbstractPouchDB,TaskQueue,PouchInternal,PouchDB,ActiveTasks,eventEmitter,index_es_default,import_vuvuzela,reservedWords,dataWords,ADAPTER_VERSION,DOC_STORE,BY_SEQ_STORE,ATTACH_STORE,ATTACH_AND_SEQ_STORE,META_STORE,LOCAL_STORE,DETECT_BLOB_SUPPORT_STORE,changesHandler$1,running,queue,cachedDBs,blobSupportPromise,openReqList,index_es_default2,IDB_NULL,IDB_FALSE,IDB_TRUE,TEST_KEY_INVALID,TEST_PATH_INVALID,KEY_INVALID,PATH_INVALID,SLASH,IS_DOT,DOC_STORE2,META_LOCAL_STORE,POUCHDB_IDB_VERSION,versionMultiplier,BINARY_ATTACHMENTS,COUCH_COLLATE_LO,COUCH_COLLATE_HI,IDB_COLLATE_LO,IDB_COLLATE_HI,ADAPTER_NAME,idbChanges,openDatabases,index_es_default3,CHANGES_BATCH_SIZE,MAX_SIMULTANEOUS_REVS,CHANGES_TIMEOUT_BUFFER,DEFAULT_HEARTBEAT,supportsBulkGetMap,index_es_default4,QueryParseError,NotFoundError,BuiltInError,TaskQueue2,persistentQueues,tempViewQueue,index_es_default5,log,isArray,toJSON,builtInReduce__sum,builtInReduce__count,builtInReduce__stats,abstract,index_browser_es_default2,CHECKPOINT_VERSION,REPLICATOR,CHECKPOINT_HISTORY_SIZE,LOWEST_SEQ,CheckpointerInternal,comparisons,index_es_default6,index_es_default7,import_events17,STARTING_BACK_OFF,Replication,Sync,index_es_default8,nativeFlat,polyFlat,flatten2,requireValidation,arrayTypeComparisonOperators,equalityOperators,abstractMapper,ddocIdPrefix,COLLATE_LO,COLLATE_HI,SHORT_CIRCUIT_QUERY,logicalMatchers,plugin2,index_browser_es_default3,import_transform_pouch,root_214,on_click3,root_34,on_click_1,root_411,root_66,root_77,root_87,root_103,root_153,root_163,root_124,root_215,root30,root_216,root_35,root_53,root_94,root_88,root_78,root_125,root_135,root31,import_qrcode_generator,OutputFormat,necessaryErasureProperties,UserMode,SetupManager,ModuleMigration,ModuleCheckRemoteSize,import_diff_match_patch3,ModuleConflictResolver,ModuleInteractiveConflictResolver,ModuleObsidianSettings,root_217,root_412,root_89,root_54,root_36,root_154,root_136,root_104,root_184,root32,root_121,root_413,root_37,root_144,root_126,root_95,root_172,root33,ModuleRedFlag,ModuleObsidianMenu,ModuleSetupObsidian,ModuleDatabaseFileAccess,ModuleFileHandler,ObsHttpHandler,ModuleObsidianAPI,ModuleObsidianEvents,setLevelClass,LiveSyncSetting,updateInformation,lastVersion,SveltePanel,root_127,root34,$$css12,toggleActiveSyncClass,root_128,root35,$$css13,EVENT_REQUEST_SHOW_HISTORY,toc,stubs,ObsidianLiveSyncSettingTab,ModuleObsidianSettingDialogue,DocumentHistoryModal,ModuleObsidianDocumentHistory,root_129,root_218,root_38,root_414,root_67,root_810,root_55,root_96,root_105,root36,$$css14,GlobalHistoryView,ModuleObsidianGlobalHistory,SETTING_HEADER,ModuleObsidianSettingsAsMarkdown,ModuleInitializerFile,instanceOfAny,idbProxyableTypes,cursorAdvanceMethods,transactionDoneMap,transformCache,reverseTransformCache,idbProxyTraps,unwrap,readMethods,writeMethods,cachedMethods,advanceMethodProps,methodMap,advanceResults,ittrProxiedCursorToOriginalProxy,cursorIteratorTraps,databaseCache,IDBKeyValueDatabase,ModuleKeyValueDB,ModulePouchDB,ReplicateResultProcessor,ModuleReplicator,ModuleReplicatorCouchDB,ModuleReplicatorMinIO,ModuleTargetFilter,ModulePeriodicProcess,ModuleRemoteGovernor,ContentSplitterCore,ContentSplitterBase,charNewLine,segmenter,MAX_ITEMS,ContentSplitterRabinKarp,ContentSplitters,ContentSplitter,ChangeManager,import_diff_match_patch4,ConflictManager,EntryManager,HashManagerCore,XXHashHashManager,XXHash32RawHashManager,XXHash64HashManager,FallbackWasmHashManager,PureJSHashManager,HashManagers,HashManager,NetworkManager,NetworkManagerBrowser,LiveSyncManagers,ModuleLocalDatabaseObsidian,ModuleConflictChecker,ModuleResolvingMismatchedTweaks,ModuleIntegratedTest,ModuleRebuilder,ModuleReplicateTest,ModuleLiveSyncMain,ModuleExtraSyncObsidian,LocalDatabaseMaintenance,EVENT_P2P_PEER_SHOW_EXTRA_MENU,AcceptedStatus,ConnectionStatus,root_219,root_130,root_39,on_click4,on_click_12,root_56,on_click_2,on_click_3,root_68,root_415,on_click_4,root_79,root_97,root_106,root_811,root37,$$css15,root_131,on_click5,on_click_13,root_310,root_416,root_57,root_69,root_98,root_107,root_710,root38,$$css16,P2PReplicatorPaneView,ObsidianAPIBase,instance2,p3,import_obsidian4,webcrypto6,Environment,P2PReplicator,ServiceHub,HubService,ServiceBase,APIService,PathService,DatabaseService,DatabaseEventService,FileProcessingService,ReplicatorService,ReplicationService,RemoteService,ConflictService,AppLifecycleService,SettingService,TweakValueService,VaultService,TestService,UIService,ConfigService,ConfigServiceBrowserCompat,ThroughHole,ChannelBase,Pipeline,Switch,AN_ERROR_OCCURRED,Survey,Broadcaster,ServiceBackend,InjectableAPIService,InjectablePathService,InjectableDatabaseService,InjectableDatabaseEventService,InjectableReplicatorService,InjectableFileProcessingService,InjectableReplicationService,InjectableRemoteService,InjectableConflictService,InjectableAppLifecycleService,InjectableSettingService,InjectableTweakValueService,InjectableVaultService,InjectableTestService,InjectableServiceHub,on_click6,root_220,root39,$$css17,ObsidianUIService,ObsidianAPIService,ObsidianPathService,ObsidianDatabaseService,ObsidianReplicatorService,ObsidianFileProcessingService,ObsidianReplicationService,ObsidianRemoteService,ObsidianConflictService,ObsidianAppLifecycleService,ObsidianSettingService,ObsidianTweakValueService,ObsidianVaultService,ObsidianTestService,ObsidianConfigService,ObsidianServiceHub,ObsidianLiveSyncPlugin,__create=Object.create,__defProp=Object.defineProperty,__getOwnPropDesc=Object.getOwnPropertyDescriptor,__getOwnPropNames=Object.getOwnPropertyNames,__getProtoOf=Object.getPrototypeOf,__hasOwnProp=Object.prototype.hasOwnProperty,__typeError=msg=>{throw TypeError(msg)},__defNormalProp=(obj,key3,value)=>key3 in obj?__defProp(obj,key3,{enumerable:!0,configurable:!0,writable:!0,value}):obj[key3]=value,__commonJS=(cb2,mod)=>function __require(){return mod||(0,cb2[__getOwnPropNames(cb2)[0]])((mod={exports:{}}).exports,mod),mod.exports},__export=(target,all2)=>{for(var name in all2)__defProp(target,name,{get:all2[name],enumerable:!0})},__copyProps=(to,from,except,desc)=>{if(from&&"object"==typeof from||"function"==typeof from)for(let key3 of __getOwnPropNames(from))__hasOwnProp.call(to,key3)||key3===except||__defProp(to,key3,{get:()=>from[key3],enumerable:!(desc=__getOwnPropDesc(from,key3))||desc.enumerable});return to},__toESM=(mod,isNodeMode,target)=>(target=null!=mod?__create(__getProtoOf(mod)):{},__copyProps(!isNodeMode&&mod&&mod.__esModule?target:__defProp(target,"default",{value:mod,enumerable:!0}),mod)),__toCommonJS=mod=>__copyProps(__defProp({},"__esModule",{value:!0}),mod),__publicField=(obj,key3,value)=>__defNormalProp(obj,"symbol"!=typeof key3?key3+"":key3,value),__accessCheck=(obj,member,msg)=>member.has(obj)||__typeError("Cannot "+msg),__privateGet=(obj,member,getter)=>(__accessCheck(obj,member,"read from private field"),getter?getter.call(obj):member.get(obj)),__privateAdd=(obj,member,value)=>member.has(obj)?__typeError("Cannot add the same private member more than once"):member instanceof WeakSet?member.add(obj):member.set(obj,value),__privateSet=(obj,member,value,setter)=>(__accessCheck(obj,member,"write to private field"),setter?setter.call(obj,value):member.set(obj,value),value),__privateMethod=(obj,member,method)=>(__accessCheck(obj,member,"access private method"),method),require_diff_match_patch=__commonJS({"node_modules/diff-match-patch/index.js"(exports,module2){var diff_match_patch4=function(){this.Diff_Timeout=1;this.Diff_EditCost=4;this.Match_Threshold=.5;this.Match_Distance=1e3;this.Patch_DeleteThreshold=.5;this.Patch_Margin=4;this.Match_MaxBits=32};diff_match_patch4.Diff=function(op,text2){return[op,text2]};diff_match_patch4.prototype.diff_main=function(text1,text2,opt_checklines,opt_deadline){var deadline,checklines,commonlength,commonprefix,commonsuffix,diffs;void 0===opt_deadline&&(opt_deadline=this.Diff_Timeout<=0?Number.MAX_VALUE:(new Date).getTime()+1e3*this.Diff_Timeout);deadline=opt_deadline;if(null==text1||null==text2)throw new Error("Null input. (diff_main)");if(text1==text2)return text1?[new diff_match_patch4.Diff(0,text1)]:[];void 0===opt_checklines&&(opt_checklines=!0);checklines=opt_checklines;commonlength=this.diff_commonPrefix(text1,text2);commonprefix=text1.substring(0,commonlength);text1=text1.substring(commonlength);text2=text2.substring(commonlength);commonlength=this.diff_commonSuffix(text1,text2);commonsuffix=text1.substring(text1.length-commonlength);text1=text1.substring(0,text1.length-commonlength);text2=text2.substring(0,text2.length-commonlength);diffs=this.diff_compute_(text1,text2,checklines,deadline);commonprefix&&diffs.unshift(new diff_match_patch4.Diff(0,commonprefix));commonsuffix&&diffs.push(new diff_match_patch4.Diff(0,commonsuffix));this.diff_cleanupMerge(diffs);return diffs};diff_match_patch4.prototype.diff_compute_=function(text1,text2,checklines,deadline){var diffs,longtext,shorttext,i2,hm,text1_a,text1_b,text2_a,text2_b,mid_common,diffs_a,diffs_b;if(!text1)return[new diff_match_patch4.Diff(1,text2)];if(!text2)return[new diff_match_patch4.Diff(-1,text1)];longtext=text1.length>text2.length?text1:text2;shorttext=text1.length>text2.length?text2:text1;if(-1!=(i2=longtext.indexOf(shorttext))){diffs=[new diff_match_patch4.Diff(1,longtext.substring(0,i2)),new diff_match_patch4.Diff(0,shorttext),new diff_match_patch4.Diff(1,longtext.substring(i2+shorttext.length))];text1.length>text2.length&&(diffs[0][0]=diffs[2][0]=-1);return diffs}if(1==shorttext.length)return[new diff_match_patch4.Diff(-1,text1),new diff_match_patch4.Diff(1,text2)];if(hm=this.diff_halfMatch_(text1,text2)){text1_a=hm[0];text1_b=hm[1];text2_a=hm[2];text2_b=hm[3];mid_common=hm[4];diffs_a=this.diff_main(text1_a,text2_a,checklines,deadline);diffs_b=this.diff_main(text1_b,text2_b,checklines,deadline);return diffs_a.concat([new diff_match_patch4.Diff(0,mid_common)],diffs_b)}return checklines&&text1.length>100&&text2.length>100?this.diff_lineMode_(text1,text2,deadline):this.diff_bisect_(text1,text2,deadline)};diff_match_patch4.prototype.diff_lineMode_=function(text1,text2,deadline){var linearray,diffs,pointer,count_delete,count_insert,text_delete,text_insert,subDiff,j2,a2=this.diff_linesToChars_(text1,text2);text1=a2.chars1;text2=a2.chars2;linearray=a2.lineArray;diffs=this.diff_main(text1,text2,!1,deadline);this.diff_charsToLines_(diffs,linearray);this.diff_cleanupSemantic(diffs);diffs.push(new diff_match_patch4.Diff(0,""));pointer=0;count_delete=0;count_insert=0;text_delete="";text_insert="";for(;pointer<diffs.length;){switch(diffs[pointer][0]){case 1:count_insert++;text_insert+=diffs[pointer][1];break;case-1:count_delete++;text_delete+=diffs[pointer][1];break;case 0:if(count_delete>=1&&count_insert>=1){diffs.splice(pointer-count_delete-count_insert,count_delete+count_insert);pointer=pointer-count_delete-count_insert;for(j2=(subDiff=this.diff_main(text_delete,text_insert,!1,deadline)).length-1;j2>=0;j2--)diffs.splice(pointer,0,subDiff[j2]);pointer+=subDiff.length}count_insert=0;count_delete=0;text_delete="";text_insert="";break}pointer++}diffs.pop();return diffs};diff_match_patch4.prototype.diff_bisect_=function(text1,text2,deadline){var x2,delta,front,k1start,k1end,k2start,k2end,d4,k1,k1_offset,x1,y1,k2_offset,x22,k2,y2,text1_length=text1.length,text2_length=text2.length,max_d=Math.ceil((text1_length+text2_length)/2),v_offset=max_d,v_length=2*max_d,v1=new Array(v_length),v2=new Array(v_length);for(x2=0;x2<v_length;x2++){v1[x2]=-1;v2[x2]=-1}v1[v_offset+1]=0;v2[v_offset+1]=0;front=(delta=text1_length-text2_length)%2!=0;k1start=0;k1end=0;k2start=0;k2end=0;for(d4=0;d4<max_d&&!((new Date).getTime()>deadline);d4++){for(k1=-d4+k1start;k1<=d4-k1end;k1+=2){k1_offset=v_offset+k1;y1=(x1=k1==-d4||k1!=d4&&v1[k1_offset-1]<v1[k1_offset+1]?v1[k1_offset+1]:v1[k1_offset-1]+1)-k1;for(;x1<text1_length&&y1<text2_length&&text1.charAt(x1)==text2.charAt(y1);){x1++;y1++}v1[k1_offset]=x1;if(x1>text1_length)k1end+=2;else if(y1>text2_length)k1start+=2;else if(front&&(k2_offset=v_offset+delta-k1)>=0&&k2_offset<v_length&&-1!=v2[k2_offset]&&x1>=(x22=text1_length-v2[k2_offset]))return this.diff_bisectSplit_(text1,text2,x1,y1,deadline)}for(k2=-d4+k2start;k2<=d4-k2end;k2+=2){k2_offset=v_offset+k2;y2=(x22=k2==-d4||k2!=d4&&v2[k2_offset-1]<v2[k2_offset+1]?v2[k2_offset+1]:v2[k2_offset-1]+1)-k2;for(;x22<text1_length&&y2<text2_length&&text1.charAt(text1_length-x22-1)==text2.charAt(text2_length-y2-1);){x22++;y2++}v2[k2_offset]=x22;if(x22>text1_length)k2end+=2;else if(y2>text2_length)k2start+=2;else if(!front&&(k1_offset=v_offset+delta-k2)>=0&&k1_offset<v_length&&-1!=v1[k1_offset]){y1=v_offset+(x1=v1[k1_offset])-k1_offset;if(x1>=(x22=text1_length-x22))return this.diff_bisectSplit_(text1,text2,x1,y1,deadline)}}}return[new diff_match_patch4.Diff(-1,text1),new diff_match_patch4.Diff(1,text2)]};diff_match_patch4.prototype.diff_bisectSplit_=function(text1,text2,x2,y2,deadline){var text1a=text1.substring(0,x2),text2a=text2.substring(0,y2),text1b=text1.substring(x2),text2b=text2.substring(y2),diffs=this.diff_main(text1a,text2a,!1,deadline),diffsb=this.diff_main(text1b,text2b,!1,deadline);return diffs.concat(diffsb)};diff_match_patch4.prototype.diff_linesToChars_=function(text1,text2){function diff_linesToCharsMunge_(text3){for(var line,chars="",lineStart=0,lineEnd=-1,lineArrayLength=lineArray.length;lineEnd<text3.length-1;){-1==(lineEnd=text3.indexOf("\n",lineStart))&&(lineEnd=text3.length-1);line=text3.substring(lineStart,lineEnd+1);if(lineHash.hasOwnProperty?lineHash.hasOwnProperty(line):void 0!==lineHash[line])chars+=String.fromCharCode(lineHash[line]);else{if(lineArrayLength==maxLines){line=text3.substring(lineStart);lineEnd=text3.length}chars+=String.fromCharCode(lineArrayLength);lineHash[line]=lineArrayLength;lineArray[lineArrayLength++]=line}lineStart=lineEnd+1}return chars}var maxLines,chars1,lineArray=[],lineHash={};lineArray[0]="";maxLines=4e4;chars1=diff_linesToCharsMunge_(text1);maxLines=65535;return{chars1,chars2:diff_linesToCharsMunge_(text2),lineArray}};diff_match_patch4.prototype.diff_charsToLines_=function(diffs,lineArray){var i2,chars,text2,j2;for(i2=0;i2<diffs.length;i2++){chars=diffs[i2][1];text2=[];for(j2=0;j2<chars.length;j2++)text2[j2]=lineArray[chars.charCodeAt(j2)];diffs[i2][1]=text2.join("")}};diff_match_patch4.prototype.diff_commonPrefix=function(text1,text2){var pointermin,pointermax,pointermid,pointerstart;if(!text1||!text2||text1.charAt(0)!=text2.charAt(0))return 0;pointermin=0;pointermid=pointermax=Math.min(text1.length,text2.length);pointerstart=0;for(;pointermin<pointermid;){text1.substring(pointerstart,pointermid)==text2.substring(pointerstart,pointermid)?pointerstart=pointermin=pointermid:pointermax=pointermid;pointermid=Math.floor((pointermax-pointermin)/2+pointermin)}return pointermid};diff_match_patch4.prototype.diff_commonSuffix=function(text1,text2){var pointermin,pointermax,pointermid,pointerend;if(!text1||!text2||text1.charAt(text1.length-1)!=text2.charAt(text2.length-1))return 0;pointermin=0;pointermid=pointermax=Math.min(text1.length,text2.length);pointerend=0;for(;pointermin<pointermid;){text1.substring(text1.length-pointermid,text1.length-pointerend)==text2.substring(text2.length-pointermid,text2.length-pointerend)?pointerend=pointermin=pointermid:pointermax=pointermid;pointermid=Math.floor((pointermax-pointermin)/2+pointermin)}return pointermid};diff_match_patch4.prototype.diff_commonOverlap_=function(text1,text2){var text_length,best,length,pattern,found,text1_length=text1.length,text2_length=text2.length;if(0==text1_length||0==text2_length)return 0;text1_length>text2_length?text1=text1.substring(text1_length-text2_length):text1_length<text2_length&&(text2=text2.substring(0,text1_length));text_length=Math.min(text1_length,text2_length);if(text1==text2)return text_length;best=0;length=1;for(;;){pattern=text1.substring(text_length-length);if(-1==(found=text2.indexOf(pattern)))return best;length+=found;if(0==found||text1.substring(text_length-length)==text2.substring(0,length)){best=length;length++}}};diff_match_patch4.prototype.diff_halfMatch_=function(text1,text2){function diff_halfMatchI_(longtext2,shorttext2,i2){for(var best_longtext_a,best_longtext_b,best_shorttext_a,best_shorttext_b,prefixLength,suffixLength,seed=longtext2.substring(i2,i2+Math.floor(longtext2.length/4)),j2=-1,best_common="";-1!=(j2=shorttext2.indexOf(seed,j2+1));){prefixLength=dmp.diff_commonPrefix(longtext2.substring(i2),shorttext2.substring(j2));suffixLength=dmp.diff_commonSuffix(longtext2.substring(0,i2),shorttext2.substring(0,j2));if(best_common.length<suffixLength+prefixLength){best_common=shorttext2.substring(j2-suffixLength,j2)+shorttext2.substring(j2,j2+prefixLength);best_longtext_a=longtext2.substring(0,i2-suffixLength);best_longtext_b=longtext2.substring(i2+prefixLength);best_shorttext_a=shorttext2.substring(0,j2-suffixLength);best_shorttext_b=shorttext2.substring(j2+prefixLength)}}return 2*best_common.length>=longtext2.length?[best_longtext_a,best_longtext_b,best_shorttext_a,best_shorttext_b,best_common]:null}var longtext,shorttext,dmp,hm1,hm2,hm,text1_a,text1_b,text2_a,text2_b;if(this.Diff_Timeout<=0)return null;longtext=text1.length>text2.length?text1:text2;shorttext=text1.length>text2.length?text2:text1;if(longtext.length<4||2*shorttext.length<longtext.length)return null;dmp=this;hm1=diff_halfMatchI_(longtext,shorttext,Math.ceil(longtext.length/4));hm2=diff_halfMatchI_(longtext,shorttext,Math.ceil(longtext.length/2));if(!hm1&&!hm2)return null;hm=hm2?hm1&&hm1[4].length>hm2[4].length?hm1:hm2:hm1;if(text1.length>text2.length){text1_a=hm[0];text1_b=hm[1];text2_a=hm[2];text2_b=hm[3]}else{text2_a=hm[0];text2_b=hm[1];text1_a=hm[2];text1_b=hm[3]}return[text1_a,text1_b,text2_a,text2_b,hm[4]]};diff_match_patch4.prototype.diff_cleanupSemantic=function(diffs){for(var deletion,insertion,overlap_length1,overlap_length2,changes3=!1,equalities=[],equalitiesLength=0,lastEquality=null,pointer=0,length_insertions1=0,length_deletions1=0,length_insertions2=0,length_deletions2=0;pointer<diffs.length;){if(0==diffs[pointer][0]){equalities[equalitiesLength++]=pointer;length_insertions1=length_insertions2;length_deletions1=length_deletions2;length_insertions2=0;length_deletions2=0;lastEquality=diffs[pointer][1]}else{1==diffs[pointer][0]?length_insertions2+=diffs[pointer][1].length:length_deletions2+=diffs[pointer][1].length;if(lastEquality&&lastEquality.length<=Math.max(length_insertions1,length_deletions1)&&lastEquality.length<=Math.max(length_insertions2,length_deletions2)){diffs.splice(equalities[equalitiesLength-1],0,new diff_match_patch4.Diff(-1,lastEquality));diffs[equalities[equalitiesLength-1]+1][0]=1;equalitiesLength--;pointer=--equalitiesLength>0?equalities[equalitiesLength-1]:-1;length_insertions1=0;length_deletions1=0;length_insertions2=0;length_deletions2=0;lastEquality=null;changes3=!0}}pointer++}changes3&&this.diff_cleanupMerge(diffs);this.diff_cleanupSemanticLossless(diffs);pointer=1;for(;pointer<diffs.length;){if(-1==diffs[pointer-1][0]&&1==diffs[pointer][0]){deletion=diffs[pointer-1][1];insertion=diffs[pointer][1];if((overlap_length1=this.diff_commonOverlap_(deletion,insertion))>=(overlap_length2=this.diff_commonOverlap_(insertion,deletion))){if(overlap_length1>=deletion.length/2||overlap_length1>=insertion.length/2){diffs.splice(pointer,0,new diff_match_patch4.Diff(0,insertion.substring(0,overlap_length1)));diffs[pointer-1][1]=deletion.substring(0,deletion.length-overlap_length1);diffs[pointer+1][1]=insertion.substring(overlap_length1);pointer++}}else if(overlap_length2>=deletion.length/2||overlap_length2>=insertion.length/2){diffs.splice(pointer,0,new diff_match_patch4.Diff(0,deletion.substring(0,overlap_length2)));diffs[pointer-1][0]=1;diffs[pointer-1][1]=insertion.substring(0,insertion.length-overlap_length2);diffs[pointer+1][0]=-1;diffs[pointer+1][1]=deletion.substring(overlap_length2);pointer++}pointer++}pointer++}};diff_match_patch4.prototype.diff_cleanupSemanticLossless=function(diffs){function diff_cleanupSemanticScore_(one,two){var char1,char2,nonAlphaNumeric1,nonAlphaNumeric2,whitespace1,whitespace2,lineBreak1,lineBreak2,blankLine1,blankLine2;if(!one||!two)return 6;char1=one.charAt(one.length-1);char2=two.charAt(0);nonAlphaNumeric1=char1.match(diff_match_patch4.nonAlphaNumericRegex_);nonAlphaNumeric2=char2.match(diff_match_patch4.nonAlphaNumericRegex_);whitespace1=nonAlphaNumeric1&&char1.match(diff_match_patch4.whitespaceRegex_);whitespace2=nonAlphaNumeric2&&char2.match(diff_match_patch4.whitespaceRegex_);lineBreak1=whitespace1&&char1.match(diff_match_patch4.linebreakRegex_);lineBreak2=whitespace2&&char2.match(diff_match_patch4.linebreakRegex_);blankLine1=lineBreak1&&one.match(diff_match_patch4.blanklineEndRegex_);blankLine2=lineBreak2&&two.match(diff_match_patch4.blanklineStartRegex_);return blankLine1||blankLine2?5:lineBreak1||lineBreak2?4:nonAlphaNumeric1&&!whitespace1&&whitespace2?3:whitespace1||whitespace2?2:nonAlphaNumeric1||nonAlphaNumeric2?1:0}for(var equality1,edit,equality2,commonOffset,commonString,bestEquality1,bestEdit,bestEquality2,bestScore,score,pointer=1;pointer<diffs.length-1;){if(0==diffs[pointer-1][0]&&0==diffs[pointer+1][0]){equality1=diffs[pointer-1][1];edit=diffs[pointer][1];equality2=diffs[pointer+1][1];if(commonOffset=this.diff_commonSuffix(equality1,edit)){commonString=edit.substring(edit.length-commonOffset);equality1=equality1.substring(0,equality1.length-commonOffset);edit=commonString+edit.substring(0,edit.length-commonOffset);equality2=commonString+equality2}bestEquality1=equality1;bestEdit=edit;bestEquality2=equality2;bestScore=diff_cleanupSemanticScore_(equality1,edit)+diff_cleanupSemanticScore_(edit,equality2);for(;edit.charAt(0)===equality2.charAt(0);){equality1+=edit.charAt(0);edit=edit.substring(1)+equality2.charAt(0);equality2=equality2.substring(1);if((score=diff_cleanupSemanticScore_(equality1,edit)+diff_cleanupSemanticScore_(edit,equality2))>=bestScore){bestScore=score;bestEquality1=equality1;bestEdit=edit;bestEquality2=equality2}}if(diffs[pointer-1][1]!=bestEquality1){if(bestEquality1)diffs[pointer-1][1]=bestEquality1;else{diffs.splice(pointer-1,1);pointer--}diffs[pointer][1]=bestEdit;if(bestEquality2)diffs[pointer+1][1]=bestEquality2;else{diffs.splice(pointer+1,1);pointer--}}}pointer++}};diff_match_patch4.nonAlphaNumericRegex_=/[^a-zA-Z0-9]/;diff_match_patch4.whitespaceRegex_=/\s/;diff_match_patch4.linebreakRegex_=/[\r\n]/;diff_match_patch4.blanklineEndRegex_=/\n\r?\n$/;diff_match_patch4.blanklineStartRegex_=/^\r?\n\r?\n/;diff_match_patch4.prototype.diff_cleanupEfficiency=function(diffs){for(var changes3=!1,equalities=[],equalitiesLength=0,lastEquality=null,pointer=0,pre_ins=!1,pre_del=!1,post_ins=!1,post_del=!1;pointer<diffs.length;){if(0==diffs[pointer][0]){if(diffs[pointer][1].length<this.Diff_EditCost&&(post_ins||post_del)){equalities[equalitiesLength++]=pointer;pre_ins=post_ins;pre_del=post_del;lastEquality=diffs[pointer][1]}else{equalitiesLength=0;lastEquality=null}post_ins=post_del=!1}else{-1==diffs[pointer][0]?post_del=!0:post_ins=!0;if(lastEquality&&(pre_ins&&pre_del&&post_ins&&post_del||lastEquality.length<this.Diff_EditCost/2&&pre_ins+pre_del+post_ins+post_del==3)){diffs.splice(equalities[equalitiesLength-1],0,new diff_match_patch4.Diff(-1,lastEquality));diffs[equalities[equalitiesLength-1]+1][0]=1;equalitiesLength--;lastEquality=null;if(pre_ins&&pre_del){post_ins=post_del=!0;equalitiesLength=0}else{pointer=--equalitiesLength>0?equalities[equalitiesLength-1]:-1;post_ins=post_del=!1}changes3=!0}}pointer++}changes3&&this.diff_cleanupMerge(diffs)};diff_match_patch4.prototype.diff_cleanupMerge=function(diffs){var pointer,count_delete,count_insert,text_delete,text_insert,commonlength,changes3;diffs.push(new diff_match_patch4.Diff(0,""));pointer=0;count_delete=0;count_insert=0;text_delete="";text_insert="";for(;pointer<diffs.length;)switch(diffs[pointer][0]){case 1:count_insert++;text_insert+=diffs[pointer][1];pointer++;break;case-1:count_delete++;text_delete+=diffs[pointer][1];pointer++;break;case 0:if(count_delete+count_insert>1){if(0!==count_delete&&0!==count_insert){if(0!==(commonlength=this.diff_commonPrefix(text_insert,text_delete))){if(pointer-count_delete-count_insert>0&&0==diffs[pointer-count_delete-count_insert-1][0])diffs[pointer-count_delete-count_insert-1][1]+=text_insert.substring(0,commonlength);else{diffs.splice(0,0,new diff_match_patch4.Diff(0,text_insert.substring(0,commonlength)));pointer++}text_insert=text_insert.substring(commonlength);text_delete=text_delete.substring(commonlength)}if(0!==(commonlength=this.diff_commonSuffix(text_insert,text_delete))){diffs[pointer][1]=text_insert.substring(text_insert.length-commonlength)+diffs[pointer][1];text_insert=text_insert.substring(0,text_insert.length-commonlength);text_delete=text_delete.substring(0,text_delete.length-commonlength)}}pointer-=count_delete+count_insert;diffs.splice(pointer,count_delete+count_insert);if(text_delete.length){diffs.splice(pointer,0,new diff_match_patch4.Diff(-1,text_delete));pointer++}if(text_insert.length){diffs.splice(pointer,0,new diff_match_patch4.Diff(1,text_insert));pointer++}pointer++}else if(0!==pointer&&0==diffs[pointer-1][0]){diffs[pointer-1][1]+=diffs[pointer][1];diffs.splice(pointer,1)}else pointer++;count_insert=0;count_delete=0;text_delete="";text_insert="";break}""===diffs[diffs.length-1][1]&&diffs.pop();changes3=!1;pointer=1;for(;pointer<diffs.length-1;){if(0==diffs[pointer-1][0]&&0==diffs[pointer+1][0])if(diffs[pointer][1].substring(diffs[pointer][1].length-diffs[pointer-1][1].length)==diffs[pointer-1][1]){diffs[pointer][1]=diffs[pointer-1][1]+diffs[pointer][1].substring(0,diffs[pointer][1].length-diffs[pointer-1][1].length);diffs[pointer+1][1]=diffs[pointer-1][1]+diffs[pointer+1][1];diffs.splice(pointer-1,1);changes3=!0}else if(diffs[pointer][1].substring(0,diffs[pointer+1][1].length)==diffs[pointer+1][1]){diffs[pointer-1][1]+=diffs[pointer+1][1];diffs[pointer][1]=diffs[pointer][1].substring(diffs[pointer+1][1].length)+diffs[pointer+1][1];diffs.splice(pointer+1,1);changes3=!0}pointer++}changes3&&this.diff_cleanupMerge(diffs)};diff_match_patch4.prototype.diff_xIndex=function(diffs,loc){var x2,chars1=0,chars2=0,last_chars1=0,last_chars2=0;for(x2=0;x2<diffs.length;x2++){1!==diffs[x2][0]&&(chars1+=diffs[x2][1].length);-1!==diffs[x2][0]&&(chars2+=diffs[x2][1].length);if(chars1>loc)break;last_chars1=chars1;last_chars2=chars2}return diffs.length!=x2&&-1===diffs[x2][0]?last_chars2:last_chars2+(loc-last_chars1)};diff_match_patch4.prototype.diff_prettyHtml=function(diffs){var x2,op,text2,html2=[],pattern_amp=/&/g,pattern_lt=/</g,pattern_gt=/>/g,pattern_para=/\n/g;for(x2=0;x2<diffs.length;x2++){op=diffs[x2][0];text2=diffs[x2][1].replace(pattern_amp,"&amp;").replace(pattern_lt,"&lt;").replace(pattern_gt,"&gt;").replace(pattern_para,"&para;<br>");switch(op){case 1:html2[x2]='<ins style="background:#e6ffe6;">'+text2+"</ins>";break;case-1:html2[x2]='<del style="background:#ffe6e6;">'+text2+"</del>";break;case 0:html2[x2]="<span>"+text2+"</span>";break}}return html2.join("")};diff_match_patch4.prototype.diff_text1=function(diffs){var x2,text2=[];for(x2=0;x2<diffs.length;x2++)1!==diffs[x2][0]&&(text2[x2]=diffs[x2][1]);return text2.join("")};diff_match_patch4.prototype.diff_text2=function(diffs){var x2,text2=[];for(x2=0;x2<diffs.length;x2++)-1!==diffs[x2][0]&&(text2[x2]=diffs[x2][1]);return text2.join("")};diff_match_patch4.prototype.diff_levenshtein=function(diffs){var x2,op,data,levenshtein=0,insertions=0,deletions=0;for(x2=0;x2<diffs.length;x2++){op=diffs[x2][0];data=diffs[x2][1];switch(op){case 1:insertions+=data.length;break;case-1:deletions+=data.length;break;case 0:levenshtein+=Math.max(insertions,deletions);insertions=0;deletions=0;break}}return levenshtein+Math.max(insertions,deletions)};diff_match_patch4.prototype.diff_toDelta=function(diffs){var x2,text2=[];for(x2=0;x2<diffs.length;x2++)switch(diffs[x2][0]){case 1:text2[x2]="+"+encodeURI(diffs[x2][1]);break;case-1:text2[x2]="-"+diffs[x2][1].length;break;case 0:text2[x2]="="+diffs[x2][1].length;break}return text2.join("\t").replace(/%20/g," ")};diff_match_patch4.prototype.diff_fromDelta=function(text1,delta){var x2,param,n3,text2,diffs=[],diffsLength=0,pointer=0,tokens=delta.split(/\t/g);for(x2=0;x2<tokens.length;x2++){param=tokens[x2].substring(1);switch(tokens[x2].charAt(0)){case"+":try{diffs[diffsLength++]=new diff_match_patch4.Diff(1,decodeURI(param))}catch(ex){throw new Error("Illegal escape in diff_fromDelta: "+param)}break;case"-":case"=":n3=parseInt(param,10);if(isNaN(n3)||n3<0)throw new Error("Invalid number in diff_fromDelta: "+param);text2=text1.substring(pointer,pointer+=n3);"="==tokens[x2].charAt(0)?diffs[diffsLength++]=new diff_match_patch4.Diff(0,text2):diffs[diffsLength++]=new diff_match_patch4.Diff(-1,text2);break;default:if(tokens[x2])throw new Error("Invalid diff operation in diff_fromDelta: "+tokens[x2])}}if(pointer!=text1.length)throw new Error("Delta length ("+pointer+") does not equal source text length ("+text1.length+").");return diffs};diff_match_patch4.prototype.match_main=function(text2,pattern,loc){if(null==text2||null==pattern||null==loc)throw new Error("Null input. (match_main)");loc=Math.max(0,Math.min(loc,text2.length));return text2==pattern?0:text2.length?text2.substring(loc,loc+pattern.length)==pattern?loc:this.match_bitap_(text2,pattern,loc):-1};diff_match_patch4.prototype.match_bitap_=function(text2,pattern,loc){function match_bitapScore_(e3,x2){var accuracy=e3/pattern.length,proximity=Math.abs(loc-x2);return dmp.Match_Distance?accuracy+proximity/dmp.Match_Distance:proximity?1:accuracy}var s2,dmp,score_threshold,best_loc,matchmask,bin_min,bin_mid,bin_max,last_rd,d4,start,finish,rd,j2,charMatch,score;if(pattern.length>this.Match_MaxBits)throw new Error("Pattern too long for this browser.");s2=this.match_alphabet_(pattern);dmp=this;score_threshold=this.Match_Threshold;if(-1!=(best_loc=text2.indexOf(pattern,loc))){score_threshold=Math.min(match_bitapScore_(0,best_loc),score_threshold);-1!=(best_loc=text2.lastIndexOf(pattern,loc+pattern.length))&&(score_threshold=Math.min(match_bitapScore_(0,best_loc),score_threshold))}matchmask=1<<pattern.length-1;best_loc=-1;bin_max=pattern.length+text2.length;for(d4=0;d4<pattern.length;d4++){bin_min=0;bin_mid=bin_max;for(;bin_min<bin_mid;){match_bitapScore_(d4,loc+bin_mid)<=score_threshold?bin_min=bin_mid:bin_max=bin_mid;bin_mid=Math.floor((bin_max-bin_min)/2+bin_min)}bin_max=bin_mid;start=Math.max(1,loc-bin_mid+1);finish=Math.min(loc+bin_mid,text2.length)+pattern.length;(rd=Array(finish+2))[finish+1]=(1<<d4)-1;for(j2=finish;j2>=start;j2--){charMatch=s2[text2.charAt(j2-1)];rd[j2]=0===d4?(rd[j2+1]<<1|1)&charMatch:(rd[j2+1]<<1|1)&charMatch|(last_rd[j2+1]|last_rd[j2])<<1|1|last_rd[j2+1];if(rd[j2]&matchmask&&(score=match_bitapScore_(d4,j2-1))<=score_threshold){score_threshold=score;if(!((best_loc=j2-1)>loc))break;start=Math.max(1,2*loc-best_loc)}}if(match_bitapScore_(d4+1,loc)>score_threshold)break;last_rd=rd}return best_loc};diff_match_patch4.prototype.match_alphabet_=function(pattern){var i2,s2={};for(i2=0;i2<pattern.length;i2++)s2[pattern.charAt(i2)]=0;for(i2=0;i2<pattern.length;i2++)s2[pattern.charAt(i2)]|=1<<pattern.length-i2-1;return s2};diff_match_patch4.prototype.patch_addContext_=function(patch,text2){var pattern,padding,prefix,suffix;if(0!=text2.length){if(null===patch.start2)throw Error("patch not initialized");pattern=text2.substring(patch.start2,patch.start2+patch.length1);padding=0;for(;text2.indexOf(pattern)!=text2.lastIndexOf(pattern)&&pattern.length<this.Match_MaxBits-this.Patch_Margin-this.Patch_Margin;){padding+=this.Patch_Margin;pattern=text2.substring(patch.start2-padding,patch.start2+patch.length1+padding)}padding+=this.Patch_Margin;(prefix=text2.substring(patch.start2-padding,patch.start2))&&patch.diffs.unshift(new diff_match_patch4.Diff(0,prefix));(suffix=text2.substring(patch.start2+patch.length1,patch.start2+patch.length1+padding))&&patch.diffs.push(new diff_match_patch4.Diff(0,suffix));patch.start1-=prefix.length;patch.start2-=prefix.length;patch.length1+=prefix.length+suffix.length;patch.length2+=prefix.length+suffix.length}};diff_match_patch4.prototype.patch_make=function(a2,opt_b,opt_c){var text1,diffs,patches,patch,patchDiffLength,char_count1,char_count2,prepatch_text,postpatch_text,x2,diff_type,diff_text;if("string"==typeof a2&&"string"==typeof opt_b&&void 0===opt_c){text1=a2;if((diffs=this.diff_main(text1,opt_b,!0)).length>2){this.diff_cleanupSemantic(diffs);this.diff_cleanupEfficiency(diffs)}}else if(a2&&"object"==typeof a2&&void 0===opt_b&&void 0===opt_c){diffs=a2;text1=this.diff_text1(diffs)}else if("string"==typeof a2&&opt_b&&"object"==typeof opt_b&&void 0===opt_c){text1=a2;diffs=opt_b}else{if("string"!=typeof a2||"string"!=typeof opt_b||!opt_c||"object"!=typeof opt_c)throw new Error("Unknown call format to patch_make.");text1=a2;diffs=opt_c}if(0===diffs.length)return[];patches=[];patch=new diff_match_patch4.patch_obj;patchDiffLength=0;char_count1=0;char_count2=0;prepatch_text=text1;postpatch_text=text1;for(x2=0;x2<diffs.length;x2++){diff_type=diffs[x2][0];diff_text=diffs[x2][1];if(!patchDiffLength&&0!==diff_type){patch.start1=char_count1;patch.start2=char_count2}switch(diff_type){case 1:patch.diffs[patchDiffLength++]=diffs[x2];patch.length2+=diff_text.length;postpatch_text=postpatch_text.substring(0,char_count2)+diff_text+postpatch_text.substring(char_count2);break;case-1:patch.length1+=diff_text.length;patch.diffs[patchDiffLength++]=diffs[x2];postpatch_text=postpatch_text.substring(0,char_count2)+postpatch_text.substring(char_count2+diff_text.length);break;case 0:if(diff_text.length<=2*this.Patch_Margin&&patchDiffLength&&diffs.length!=x2+1){patch.diffs[patchDiffLength++]=diffs[x2];patch.length1+=diff_text.length;patch.length2+=diff_text.length}else if(diff_text.length>=2*this.Patch_Margin&&patchDiffLength){this.patch_addContext_(patch,prepatch_text);patches.push(patch);patch=new diff_match_patch4.patch_obj;patchDiffLength=0;prepatch_text=postpatch_text;char_count1=char_count2}break}1!==diff_type&&(char_count1+=diff_text.length);-1!==diff_type&&(char_count2+=diff_text.length)}if(patchDiffLength){this.patch_addContext_(patch,prepatch_text);patches.push(patch)}return patches};diff_match_patch4.prototype.patch_deepCopy=function(patches){var x2,patch,patchCopy,y2,patchesCopy=[];for(x2=0;x2<patches.length;x2++){patch=patches[x2];(patchCopy=new diff_match_patch4.patch_obj).diffs=[];for(y2=0;y2<patch.diffs.length;y2++)patchCopy.diffs[y2]=new diff_match_patch4.Diff(patch.diffs[y2][0],patch.diffs[y2][1]);patchCopy.start1=patch.start1;patchCopy.start2=patch.start2;patchCopy.length1=patch.length1;patchCopy.length2=patch.length2;patchesCopy[x2]=patchCopy}return patchesCopy};diff_match_patch4.prototype.patch_apply=function(patches,text2){var nullPadding,delta,results,x2,expected_loc,text1,start_loc,end_loc,text22,diffs,index1,index22,y2,mod;if(0==patches.length)return[text2,[]];patches=this.patch_deepCopy(patches);text2=(nullPadding=this.patch_addPadding(patches))+text2+nullPadding;this.patch_splitMax(patches);delta=0;results=[];for(x2=0;x2<patches.length;x2++){expected_loc=patches[x2].start2+delta;end_loc=-1;(text1=this.diff_text1(patches[x2].diffs)).length>this.Match_MaxBits?-1!=(start_loc=this.match_main(text2,text1.substring(0,this.Match_MaxBits),expected_loc))&&(-1==(end_loc=this.match_main(text2,text1.substring(text1.length-this.Match_MaxBits),expected_loc+text1.length-this.Match_MaxBits))||start_loc>=end_loc)&&(start_loc=-1):start_loc=this.match_main(text2,text1,expected_loc);if(-1==start_loc){results[x2]=!1;delta-=patches[x2].length2-patches[x2].length1}else{results[x2]=!0;delta=start_loc-expected_loc;if(text1==(text22=-1==end_loc?text2.substring(start_loc,start_loc+text1.length):text2.substring(start_loc,end_loc+this.Match_MaxBits)))text2=text2.substring(0,start_loc)+this.diff_text2(patches[x2].diffs)+text2.substring(start_loc+text1.length);else{diffs=this.diff_main(text1,text22,!1);if(text1.length>this.Match_MaxBits&&this.diff_levenshtein(diffs)/text1.length>this.Patch_DeleteThreshold)results[x2]=!1;else{this.diff_cleanupSemanticLossless(diffs);index1=0;for(y2=0;y2<patches[x2].diffs.length;y2++){0!==(mod=patches[x2].diffs[y2])[0]&&(index22=this.diff_xIndex(diffs,index1));1===mod[0]?text2=text2.substring(0,start_loc+index22)+mod[1]+text2.substring(start_loc+index22):-1===mod[0]&&(text2=text2.substring(0,start_loc+index22)+text2.substring(start_loc+this.diff_xIndex(diffs,index1+mod[1].length)));-1!==mod[0]&&(index1+=mod[1].length)}}}}}return[text2=text2.substring(nullPadding.length,text2.length-nullPadding.length),results]};diff_match_patch4.prototype.patch_addPadding=function(patches){var x2,patch,diffs,extraLength,paddingLength=this.Patch_Margin,nullPadding="";for(x2=1;x2<=paddingLength;x2++)nullPadding+=String.fromCharCode(x2);for(x2=0;x2<patches.length;x2++){patches[x2].start1+=paddingLength;patches[x2].start2+=paddingLength}if(0==(diffs=(patch=patches[0]).diffs).length||0!=diffs[0][0]){diffs.unshift(new diff_match_patch4.Diff(0,nullPadding));patch.start1-=paddingLength;patch.start2-=paddingLength;patch.length1+=paddingLength;patch.length2+=paddingLength}else if(paddingLength>diffs[0][1].length){extraLength=paddingLength-diffs[0][1].length;diffs[0][1]=nullPadding.substring(diffs[0][1].length)+diffs[0][1];patch.start1-=extraLength;patch.start2-=extraLength;patch.length1+=extraLength;patch.length2+=extraLength}if(0==(diffs=(patch=patches[patches.length-1]).diffs).length||0!=diffs[diffs.length-1][0]){diffs.push(new diff_match_patch4.Diff(0,nullPadding));patch.length1+=paddingLength;patch.length2+=paddingLength}else if(paddingLength>diffs[diffs.length-1][1].length){extraLength=paddingLength-diffs[diffs.length-1][1].length;diffs[diffs.length-1][1]+=nullPadding.substring(0,extraLength);patch.length1+=extraLength;patch.length2+=extraLength}return nullPadding};diff_match_patch4.prototype.patch_splitMax=function(patches){var x2,bigpatch,start1,start2,precontext,patch,empty2,diff_type,diff_text,postcontext,patch_size=this.Match_MaxBits;for(x2=0;x2<patches.length;x2++)if(!(patches[x2].length1<=patch_size)){bigpatch=patches[x2];patches.splice(x2--,1);start1=bigpatch.start1;start2=bigpatch.start2;precontext="";for(;0!==bigpatch.diffs.length;){empty2=!0;(patch=new diff_match_patch4.patch_obj).start1=start1-precontext.length;patch.start2=start2-precontext.length;if(""!==precontext){patch.length1=patch.length2=precontext.length;patch.diffs.push(new diff_match_patch4.Diff(0,precontext))}for(;0!==bigpatch.diffs.length&&patch.length1<patch_size-this.Patch_Margin;){diff_type=bigpatch.diffs[0][0];diff_text=bigpatch.diffs[0][1];if(1===diff_type){patch.length2+=diff_text.length;start2+=diff_text.length;patch.diffs.push(bigpatch.diffs.shift());empty2=!1}else if(-1===diff_type&&1==patch.diffs.length&&0==patch.diffs[0][0]&&diff_text.length>2*patch_size){patch.length1+=diff_text.length;start1+=diff_text.length;empty2=!1;patch.diffs.push(new diff_match_patch4.Diff(diff_type,diff_text));bigpatch.diffs.shift()}else{diff_text=diff_text.substring(0,patch_size-patch.length1-this.Patch_Margin);patch.length1+=diff_text.length;start1+=diff_text.length;if(0===diff_type){patch.length2+=diff_text.length;start2+=diff_text.length}else empty2=!1;patch.diffs.push(new diff_match_patch4.Diff(diff_type,diff_text));diff_text==bigpatch.diffs[0][1]?bigpatch.diffs.shift():bigpatch.diffs[0][1]=bigpatch.diffs[0][1].substring(diff_text.length)}}precontext=(precontext=this.diff_text2(patch.diffs)).substring(precontext.length-this.Patch_Margin);if(""!==(postcontext=this.diff_text1(bigpatch.diffs).substring(0,this.Patch_Margin))){patch.length1+=postcontext.length;patch.length2+=postcontext.length;0!==patch.diffs.length&&0===patch.diffs[patch.diffs.length-1][0]?patch.diffs[patch.diffs.length-1][1]+=postcontext:patch.diffs.push(new diff_match_patch4.Diff(0,postcontext))}empty2||patches.splice(++x2,0,patch)}}};diff_match_patch4.prototype.patch_toText=function(patches){var x2,text2=[];for(x2=0;x2<patches.length;x2++)text2[x2]=patches[x2];return text2.join("")};diff_match_patch4.prototype.patch_fromText=function(textline){var text2,textPointer,patchHeader,m3,patch,sign2,line,patches=[];if(!textline)return patches;text2=textline.split("\n");textPointer=0;patchHeader=/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/;for(;textPointer<text2.length;){if(!(m3=text2[textPointer].match(patchHeader)))throw new Error("Invalid patch string: "+text2[textPointer]);patch=new diff_match_patch4.patch_obj;patches.push(patch);patch.start1=parseInt(m3[1],10);if(""===m3[2]){patch.start1--;patch.length1=1}else if("0"==m3[2])patch.length1=0;else{patch.start1--;patch.length1=parseInt(m3[2],10)}patch.start2=parseInt(m3[3],10);if(""===m3[4]){patch.start2--;patch.length2=1}else if("0"==m3[4])patch.length2=0;else{patch.start2--;patch.length2=parseInt(m3[4],10)}textPointer++;for(;textPointer<text2.length;){sign2=text2[textPointer].charAt(0);try{line=decodeURI(text2[textPointer].substring(1))}catch(ex){throw new Error("Illegal escape in patch_fromText: "+line)}if("-"==sign2)patch.diffs.push(new diff_match_patch4.Diff(-1,line));else if("+"==sign2)patch.diffs.push(new diff_match_patch4.Diff(1,line));else if(" "==sign2)patch.diffs.push(new diff_match_patch4.Diff(0,line));else{if("@"==sign2)break;if(""!==sign2)throw new Error('Invalid patch mode "'+sign2+'" in: '+line)}textPointer++}}return patches};diff_match_patch4.patch_obj=function(){this.diffs=[];this.start1=null;this.start2=null;this.length1=0;this.length2=0};diff_match_patch4.patch_obj.prototype.toString=function(){var text2,op,x2;text2=["@@ -"+(0===this.length1?this.start1+",0":1==this.length1?this.start1+1:this.start1+1+","+this.length1)+" +"+(0===this.length2?this.start2+",0":1==this.length2?this.start2+1:this.start2+1+","+this.length2)+" @@\n"];for(x2=0;x2<this.diffs.length;x2++){switch(this.diffs[x2][0]){case 1:op="+";break;case-1:op="-";break;case 0:op=" ";break}text2[x2+1]=op+encodeURI(this.diffs[x2][1])+"\n"}return text2.join("").replace(/%20/g," ")};module2.exports=diff_match_patch4;module2.exports.diff_match_patch=diff_match_patch4;module2.exports.DIFF_DELETE=-1;module2.exports.DIFF_INSERT=1;module2.exports.DIFF_EQUAL=0}}),require_util=__commonJS({"node_modules/fast-xml-parser/src/util.js"(exports){"use strict";var nameStartChar=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",nameRegexp="["+nameStartChar+"]["+nameStartChar+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*",regexName=new RegExp("^"+nameRegexp+"$");exports.isExist=function(v2){return void 0!==v2};exports.isEmptyObject=function(obj){return 0===Object.keys(obj).length};exports.merge=function(target,a2,arrayMode){if(a2){const keys3=Object.keys(a2),len=keys3.length;for(let i2=0;i2<len;i2++)target[keys3[i2]]="strict"===arrayMode?[a2[keys3[i2]]]:a2[keys3[i2]]}};exports.getValue=function(v2){return exports.isExist(v2)?v2:""};exports.isName=function(string){return!(null==regexName.exec(string))};exports.getAllMatches=function(string,regex){const matches=[];let match3=regex.exec(string);for(;match3;){const allmatches=[];allmatches.startIndex=regex.lastIndex-match3[0].length;const len=match3.length;for(let index6=0;index6<len;index6++)allmatches.push(match3[index6]);matches.push(allmatches);match3=regex.exec(string)}return matches};exports.nameRegexp=nameRegexp}}),require_validator=__commonJS({"node_modules/fast-xml-parser/src/validator.js"(exports){"use strict";function isWhiteSpace(char){return" "===char||"\t"===char||"\n"===char||"\r"===char}function readPI(xmlData,i2){const start=i2;for(;i2<xmlData.length;i2++)if("?"!=xmlData[i2]&&" "!=xmlData[i2]);else{const tagname=xmlData.substr(start,i2-start);if(i2>5&&"xml"===tagname)return getErrorObject("InvalidXml","XML declaration allowed only at the start of the document.",getLineNumberForPosition(xmlData,i2));if("?"==xmlData[i2]&&">"==xmlData[i2+1]){i2++;break}}return i2}function readCommentAndCDATA(xmlData,i2){if(xmlData.length>i2+5&&"-"===xmlData[i2+1]&&"-"===xmlData[i2+2]){for(i2+=3;i2<xmlData.length;i2++)if("-"===xmlData[i2]&&"-"===xmlData[i2+1]&&">"===xmlData[i2+2]){i2+=2;break}}else if(xmlData.length>i2+8&&"D"===xmlData[i2+1]&&"O"===xmlData[i2+2]&&"C"===xmlData[i2+3]&&"T"===xmlData[i2+4]&&"Y"===xmlData[i2+5]&&"P"===xmlData[i2+6]&&"E"===xmlData[i2+7]){let angleBracketsCount=1;for(i2+=8;i2<xmlData.length;i2++)if("<"===xmlData[i2])angleBracketsCount++;else if(">"===xmlData[i2]){angleBracketsCount--;if(0===angleBracketsCount)break}}else if(xmlData.length>i2+9&&"["===xmlData[i2+1]&&"C"===xmlData[i2+2]&&"D"===xmlData[i2+3]&&"A"===xmlData[i2+4]&&"T"===xmlData[i2+5]&&"A"===xmlData[i2+6]&&"["===xmlData[i2+7])for(i2+=8;i2<xmlData.length;i2++)if("]"===xmlData[i2]&&"]"===xmlData[i2+1]&&">"===xmlData[i2+2]){i2+=2;break}return i2}function readAttributeStr(xmlData,i2){let attrStr="",startChar="",tagClosed=!1;for(;i2<xmlData.length;i2++){if(xmlData[i2]===doubleQuote||xmlData[i2]===singleQuote)""===startChar?startChar=xmlData[i2]:startChar!==xmlData[i2]||(startChar="");else if(">"===xmlData[i2]&&""===startChar){tagClosed=!0;break}attrStr+=xmlData[i2]}return""===startChar&&{value:attrStr,index:i2,tagClosed}}function validateAttributeString(attrStr,options){const matches=util.getAllMatches(attrStr,validAttrStrRegxp),attrNames={};for(let i2=0;i2<matches.length;i2++){if(0===matches[i2][1].length)return getErrorObject("InvalidAttr","Attribute '"+matches[i2][2]+"' has no space in starting.",getPositionFromMatch(matches[i2]));if(void 0!==matches[i2][3]&&void 0===matches[i2][4])return getErrorObject("InvalidAttr","Attribute '"+matches[i2][2]+"' is without value.",getPositionFromMatch(matches[i2]));if(void 0===matches[i2][3]&&!options.allowBooleanAttributes)return getErrorObject("InvalidAttr","boolean attribute '"+matches[i2][2]+"' is not allowed.",getPositionFromMatch(matches[i2]));const attrName=matches[i2][2];if(!validateAttrName(attrName))return getErrorObject("InvalidAttr","Attribute '"+attrName+"' is an invalid name.",getPositionFromMatch(matches[i2]));if(attrNames.hasOwnProperty(attrName))return getErrorObject("InvalidAttr","Attribute '"+attrName+"' is repeated.",getPositionFromMatch(matches[i2]));attrNames[attrName]=1}return!0}function validateNumberAmpersand(xmlData,i2){let re=/\d/;if("x"===xmlData[i2]){i2++;re=/[\da-fA-F]/}for(;i2<xmlData.length;i2++){if(";"===xmlData[i2])return i2;if(!xmlData[i2].match(re))break}return-1}function validateAmpersand(xmlData,i2){if(";"===xmlData[++i2])return-1;if("#"===xmlData[i2])return validateNumberAmpersand(xmlData,++i2);let count=0;for(;i2<xmlData.length;i2++,count++)if(!(xmlData[i2].match(/\w/)&&count<20)){if(";"===xmlData[i2])break;return-1}return i2}function getErrorObject(code,message,lineNumber){return{err:{code,msg:message,line:lineNumber.line||lineNumber,col:lineNumber.col}}}function validateAttrName(attrName){return util.isName(attrName)}function validateTagName(tagname){return util.isName(tagname)}function getLineNumberForPosition(xmlData,index6){const lines=xmlData.substring(0,index6).split(/\r?\n/);return{line:lines.length,col:lines[lines.length-1].length+1}}function getPositionFromMatch(match3){return match3.startIndex+match3[1].length}var doubleQuote,singleQuote,validAttrStrRegxp,util=require_util(),defaultOptions={allowBooleanAttributes:!1,unpairedTags:[]};exports.validate=function(xmlData,options){options=Object.assign({},defaultOptions,options);const tags=[];let tagFound=!1,reachedRoot=!1;"\ufeff"===xmlData[0]&&(xmlData=xmlData.substr(1));for(let i2=0;i2<xmlData.length;i2++)if("<"===xmlData[i2]&&"?"===xmlData[i2+1]){i2+=2;i2=readPI(xmlData,i2);if(i2.err)return i2}else{if("<"!==xmlData[i2]){if(isWhiteSpace(xmlData[i2]))continue;return getErrorObject("InvalidChar","char '"+xmlData[i2]+"' is not expected.",getLineNumberForPosition(xmlData,i2))}{let tagStartPos=i2;i2++;if("!"===xmlData[i2]){i2=readCommentAndCDATA(xmlData,i2);continue}{let closingTag=!1;if("/"===xmlData[i2]){closingTag=!0;i2++}let tagName="";for(;i2<xmlData.length&&">"!==xmlData[i2]&&" "!==xmlData[i2]&&"\t"!==xmlData[i2]&&"\n"!==xmlData[i2]&&"\r"!==xmlData[i2];i2++)tagName+=xmlData[i2];tagName=tagName.trim();if("/"===tagName[tagName.length-1]){tagName=tagName.substring(0,tagName.length-1);i2--}if(!validateTagName(tagName)){let msg;msg=0===tagName.trim().length?"Invalid space after '<'.":"Tag '"+tagName+"' is an invalid name.";return getErrorObject("InvalidTag",msg,getLineNumberForPosition(xmlData,i2))}const result=readAttributeStr(xmlData,i2);if(!1===result)return getErrorObject("InvalidAttr","Attributes for '"+tagName+"' have open quote.",getLineNumberForPosition(xmlData,i2));let attrStr=result.value;i2=result.index;if("/"===attrStr[attrStr.length-1]){const attrStrStart=i2-attrStr.length;attrStr=attrStr.substring(0,attrStr.length-1);const isValid=validateAttributeString(attrStr,options);if(!0!==isValid)return getErrorObject(isValid.err.code,isValid.err.msg,getLineNumberForPosition(xmlData,attrStrStart+isValid.err.line));tagFound=!0}else if(closingTag){if(!result.tagClosed)return getErrorObject("InvalidTag","Closing tag '"+tagName+"' doesn't have proper closing.",getLineNumberForPosition(xmlData,i2));if(attrStr.trim().length>0)return getErrorObject("InvalidTag","Closing tag '"+tagName+"' can't have attributes or invalid starting.",getLineNumberForPosition(xmlData,tagStartPos));if(0===tags.length)return getErrorObject("InvalidTag","Closing tag '"+tagName+"' has not been opened.",getLineNumberForPosition(xmlData,tagStartPos));{const otg=tags.pop();if(tagName!==otg.tagName){let openPos=getLineNumberForPosition(xmlData,otg.tagStartPos);return getErrorObject("InvalidTag","Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.",getLineNumberForPosition(xmlData,tagStartPos))}0==tags.length&&(reachedRoot=!0)}}else{const isValid=validateAttributeString(attrStr,options);if(!0!==isValid)return getErrorObject(isValid.err.code,isValid.err.msg,getLineNumberForPosition(xmlData,i2-attrStr.length+isValid.err.line));if(!0===reachedRoot)return getErrorObject("InvalidXml","Multiple possible root nodes found.",getLineNumberForPosition(xmlData,i2));-1!==options.unpairedTags.indexOf(tagName)||tags.push({tagName,tagStartPos});tagFound=!0}for(i2++;i2<xmlData.length;i2++)if("<"===xmlData[i2]){if("!"===xmlData[i2+1]){i2++;i2=readCommentAndCDATA(xmlData,i2);continue}if("?"!==xmlData[i2+1])break;i2=readPI(xmlData,++i2);if(i2.err)return i2}else if("&"===xmlData[i2]){const afterAmp=validateAmpersand(xmlData,i2);if(-1==afterAmp)return getErrorObject("InvalidChar","char '&' is not expected.",getLineNumberForPosition(xmlData,i2));i2=afterAmp}else if(!0===reachedRoot&&!isWhiteSpace(xmlData[i2]))return getErrorObject("InvalidXml","Extra text at the end",getLineNumberForPosition(xmlData,i2));"<"===xmlData[i2]&&i2--}}}return tagFound?1==tags.length?getErrorObject("InvalidTag","Unclosed tag '"+tags[0].tagName+"'.",getLineNumberForPosition(xmlData,tags[0].tagStartPos)):!(tags.length>0)||getErrorObject("InvalidXml","Invalid '"+JSON.stringify(tags.map((t3=>t3.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):getErrorObject("InvalidXml","Start tag expected.",1)};doubleQuote='"';singleQuote="'";validAttrStrRegxp=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g")}}),require_OptionsBuilder=__commonJS({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(exports){var defaultOptions={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(tagName,val2){return val2},attributeValueProcessor:function(attrName,val2){return val2},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(tagName,jPath,attrs){return tagName}};exports.buildOptions=function(options){return Object.assign({},defaultOptions,options)};exports.defaultOptions=defaultOptions}}),require_xmlNode=__commonJS({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(exports,module2){"use strict";module2.exports=class{constructor(tagname){this.tagname=tagname;this.child=[];this[":@"]={}}add(key3,val2){"__proto__"===key3&&(key3="#__proto__");this.child.push({[key3]:val2})}addChild(node){"__proto__"===node.tagname&&(node.tagname="#__proto__");node[":@"]&&Object.keys(node[":@"]).length>0?this.child.push({[node.tagname]:node.child,[":@"]:node[":@"]}):this.child.push({[node.tagname]:node.child})}}}}),require_DocTypeReader=__commonJS({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(exports,module2){function readEntityExp(xmlData,i2){let entityName2="";for(;i2<xmlData.length&&"'"!==xmlData[i2]&&'"'!==xmlData[i2];i2++)entityName2+=xmlData[i2];entityName2=entityName2.trim();if(-1!==entityName2.indexOf(" "))throw new Error("External entites are not supported");const startChar=xmlData[i2++];let val2="";for(;i2<xmlData.length&&xmlData[i2]!==startChar;i2++)val2+=xmlData[i2];return[entityName2,val2,i2]}function isComment(xmlData,i2){return"!"===xmlData[i2+1]&&"-"===xmlData[i2+2]&&"-"===xmlData[i2+3]}function isEntity(xmlData,i2){return"!"===xmlData[i2+1]&&"E"===xmlData[i2+2]&&"N"===xmlData[i2+3]&&"T"===xmlData[i2+4]&&"I"===xmlData[i2+5]&&"T"===xmlData[i2+6]&&"Y"===xmlData[i2+7]}function isElement(xmlData,i2){return"!"===xmlData[i2+1]&&"E"===xmlData[i2+2]&&"L"===xmlData[i2+3]&&"E"===xmlData[i2+4]&&"M"===xmlData[i2+5]&&"E"===xmlData[i2+6]&&"N"===xmlData[i2+7]&&"T"===xmlData[i2+8]}function isAttlist(xmlData,i2){return"!"===xmlData[i2+1]&&"A"===xmlData[i2+2]&&"T"===xmlData[i2+3]&&"T"===xmlData[i2+4]&&"L"===xmlData[i2+5]&&"I"===xmlData[i2+6]&&"S"===xmlData[i2+7]&&"T"===xmlData[i2+8]}function isNotation(xmlData,i2){return"!"===xmlData[i2+1]&&"N"===xmlData[i2+2]&&"O"===xmlData[i2+3]&&"T"===xmlData[i2+4]&&"A"===xmlData[i2+5]&&"T"===xmlData[i2+6]&&"I"===xmlData[i2+7]&&"O"===xmlData[i2+8]&&"N"===xmlData[i2+9]}function validateEntityName(name){if(util.isName(name))return name;throw new Error(`Invalid entity name ${name}`)}var util=require_util();module2.exports=function readDocType(xmlData,i2){const entities={};if("O"!==xmlData[i2+3]||"C"!==xmlData[i2+4]||"T"!==xmlData[i2+5]||"Y"!==xmlData[i2+6]||"P"!==xmlData[i2+7]||"E"!==xmlData[i2+8])throw new Error("Invalid Tag instead of DOCTYPE");{i2+=9;let angleBracketsCount=1,hasBody=!1,comment2=!1,exp="";for(;i2<xmlData.length;i2++)if("<"!==xmlData[i2]||comment2)if(">"===xmlData[i2]){if(comment2){if("-"===xmlData[i2-1]&&"-"===xmlData[i2-2]){comment2=!1;angleBracketsCount--}}else angleBracketsCount--;if(0===angleBracketsCount)break}else"["===xmlData[i2]?hasBody=!0:exp+=xmlData[i2];else{if(hasBody&&isEntity(xmlData,i2)){i2+=7;[entityName,val,i2]=readEntityExp(xmlData,i2+1);-1===val.indexOf("&")&&(entities[validateEntityName(entityName)]={regx:RegExp(`&${entityName};`,"g"),val})}else if(hasBody&&isElement(xmlData,i2))i2+=8;else if(hasBody&&isAttlist(xmlData,i2))i2+=8;else if(hasBody&&isNotation(xmlData,i2))i2+=9;else{if(!isComment)throw new Error("Invalid DOCTYPE");comment2=!0}angleBracketsCount++;exp=""}if(0!==angleBracketsCount)throw new Error("Unclosed DOCTYPE")}return{entities,i:i2}}}}),require_strnum=__commonJS({"node_modules/strnum/strnum.js"(exports,module2){function trimZeros(numStr){if(numStr&&-1!==numStr.indexOf(".")){"."===(numStr=numStr.replace(/0+$/,""))?numStr="0":"."===numStr[0]?numStr="0"+numStr:"."===numStr[numStr.length-1]&&(numStr=numStr.substr(0,numStr.length-1));return numStr}return numStr}function parse_int(numStr,base){if(parseInt)return parseInt(numStr,base);if(Number.parseInt)return Number.parseInt(numStr,base);if(window&&window.parseInt)return window.parseInt(numStr,base);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}var hexRegex=/^[-+]?0x[a-fA-F0-9]+$/,numRegex=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,consider={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};module2.exports=function toNumber(str,options={}){options=Object.assign({},consider,options);if(!str||"string"!=typeof str)return str;let trimmedStr=str.trim();if(void 0!==options.skipLike&&options.skipLike.test(trimmedStr))return str;if("0"===str)return 0;if(options.hex&&hexRegex.test(trimmedStr))return parse_int(trimmedStr,16);if(-1!==trimmedStr.search(/[eE]/)){const notation=trimmedStr.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);if(notation){if(options.leadingZeros)trimmedStr=(notation[1]||"")+notation[3];else if("0"!==notation[2]||"."!==notation[3][0])return str;return options.eNotation?Number(trimmedStr):str}return str}{const match3=numRegex.exec(trimmedStr);if(match3){const sign2=match3[1],leadingZeros=match3[2];let numTrimmedByZeros=trimZeros(match3[3]);if(!options.leadingZeros&&leadingZeros.length>0&&sign2&&"."!==trimmedStr[2])return str;if(!options.leadingZeros&&leadingZeros.length>0&&!sign2&&"."!==trimmedStr[1])return str;if(options.leadingZeros&&leadingZeros===str)return 0;{const num=Number(trimmedStr),numStr=""+num;return-1!==numStr.search(/[eE]/)?options.eNotation?num:str:-1!==trimmedStr.indexOf(".")?"0"===numStr&&""===numTrimmedByZeros||numStr===numTrimmedByZeros||sign2&&numStr==="-"+numTrimmedByZeros?num:str:leadingZeros?numTrimmedByZeros===numStr||sign2+numTrimmedByZeros===numStr?num:str:trimmedStr===numStr||trimmedStr===sign2+numStr?num:str}}return str}}}}),require_OrderedObjParser=__commonJS({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(exports,module2){"use strict";function addExternalEntities(externalEntities){const entKeys=Object.keys(externalEntities);for(let i2=0;i2<entKeys.length;i2++){const ent=entKeys[i2];this.lastEntities[ent]={regex:new RegExp("&"+ent+";","g"),val:externalEntities[ent]}}}function parseTextData(val2,tagName,jPath,dontTrim,hasAttributes,isLeafNode,escapeEntities){if(void 0!==val2){this.options.trimValues&&!dontTrim&&(val2=val2.trim());if(val2.length>0){escapeEntities||(val2=this.replaceEntitiesValue(val2));const newval=this.options.tagValueProcessor(tagName,val2,jPath,hasAttributes,isLeafNode);return null==newval?val2:typeof newval!=typeof val2||newval!==val2?newval:this.options.trimValues||val2.trim()===val2?parseValue(val2,this.options.parseTagValue,this.options.numberParseOptions):val2}}}function resolveNameSpace(tagname){if(this.options.removeNSPrefix){const tags=tagname.split(":"),prefix="/"===tagname.charAt(0)?"/":"";if("xmlns"===tags[0])return"";2===tags.length&&(tagname=prefix+tags[1])}return tagname}function buildAttributesMap(attrStr,jPath,tagName){if(!this.options.ignoreAttributes&&"string"==typeof attrStr){const matches=util.getAllMatches(attrStr,attrsRegx),len=matches.length,attrs={};for(let i2=0;i2<len;i2++){const attrName=this.resolveNameSpace(matches[i2][1]);let oldVal=matches[i2][4],aName=this.options.attributeNamePrefix+attrName;if(attrName.length){this.options.transformAttributeName&&(aName=this.options.transformAttributeName(aName));"__proto__"===aName&&(aName="#__proto__");if(void 0!==oldVal){this.options.trimValues&&(oldVal=oldVal.trim());oldVal=this.replaceEntitiesValue(oldVal);const newVal=this.options.attributeValueProcessor(attrName,oldVal,jPath);attrs[aName]=null==newVal?oldVal:typeof newVal!=typeof oldVal||newVal!==oldVal?newVal:parseValue(oldVal,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(attrs[aName]=!0)}}if(!Object.keys(attrs).length)return;if(this.options.attributesGroupName){const attrCollection={};attrCollection[this.options.attributesGroupName]=attrs;return attrCollection}return attrs}}function addChild(currentNode,childNode,jPath){const result=this.options.updateTag(childNode.tagname,jPath,childNode[":@"]);if(!1===result);else if("string"==typeof result){childNode.tagname=result;currentNode.addChild(childNode)}else currentNode.addChild(childNode)}function saveTextToParentTag(textData,currentNode,jPath,isLeafNode){if(textData){void 0===isLeafNode&&(isLeafNode=0===Object.keys(currentNode.child).length);void 0!==(textData=this.parseTextData(textData,currentNode.tagname,jPath,!1,!!currentNode[":@"]&&0!==Object.keys(currentNode[":@"]).length,isLeafNode))&&""!==textData&&currentNode.add(this.options.textNodeName,textData);textData=""}return textData}function isItStopNode(stopNodes,jPath,currentTagName){const allNodesExp="*."+currentTagName;for(const stopNodePath in stopNodes){const stopNodeExp=stopNodes[stopNodePath];if(allNodesExp===stopNodeExp||jPath===stopNodeExp)return!0}return!1}function tagExpWithClosingIndex(xmlData,i2,closingChar=">"){let attrBoundary,tagExp="";for(let index6=i2;index6<xmlData.length;index6++){let ch4=xmlData[index6];if(attrBoundary)ch4===attrBoundary&&(attrBoundary="");else if('"'===ch4||"'"===ch4)attrBoundary=ch4;else if(ch4===closingChar[0]){if(!closingChar[1])return{data:tagExp,index:index6};if(xmlData[index6+1]===closingChar[1])return{data:tagExp,index:index6}}else"\t"===ch4&&(ch4=" ");tagExp+=ch4}}function findClosingIndex(xmlData,str,i2,errMsg){const closingIndex=xmlData.indexOf(str,i2);if(-1===closingIndex)throw new Error(errMsg);return closingIndex+str.length-1}function readTagExp(xmlData,i2,removeNSPrefix,closingChar=">"){const result=tagExpWithClosingIndex(xmlData,i2+1,closingChar);if(!result)return;let tagExp=result.data;const closeIndex=result.index,separatorIndex=tagExp.search(/\s/);let tagName=tagExp,attrExpPresent=!0;if(-1!==separatorIndex){tagName=tagExp.substring(0,separatorIndex);tagExp=tagExp.substring(separatorIndex+1).trimStart()}const rawTagName=tagName;if(removeNSPrefix){const colonIndex=tagName.indexOf(":");if(-1!==colonIndex){tagName=tagName.substr(colonIndex+1);attrExpPresent=tagName!==result.data.substr(colonIndex+1)}}return{tagName,tagExp,closeIndex,attrExpPresent,rawTagName}}function readStopNodeData(xmlData,tagName,i2){const startIndex=i2;let openTagCount=1;for(;i2<xmlData.length;i2++)if("<"===xmlData[i2])if("/"===xmlData[i2+1]){const closeIndex=findClosingIndex(xmlData,">",i2,`${tagName} is not closed`);if(xmlData.substring(i2+2,closeIndex).trim()===tagName){openTagCount--;if(0===openTagCount)return{tagContent:xmlData.substring(startIndex,i2),i:closeIndex}}i2=closeIndex}else if("?"===xmlData[i2+1])i2=findClosingIndex(xmlData,"?>",i2+1,"StopNode is not closed.");else if("!--"===xmlData.substr(i2+1,3))i2=findClosingIndex(xmlData,"--\x3e",i2+3,"StopNode is not closed.");else if("!["===xmlData.substr(i2+1,2))i2=findClosingIndex(xmlData,"]]>",i2,"StopNode is not closed.")-2;else{const tagData=readTagExp(xmlData,i2,">");if(tagData){(tagData&&tagData.tagName)===tagName&&"/"!==tagData.tagExp[tagData.tagExp.length-1]&&openTagCount++;i2=tagData.closeIndex}}}function parseValue(val2,shouldParse,options){if(shouldParse&&"string"==typeof val2){const newval=val2.trim();return"true"===newval||"false"!==newval&&toNumber(val2,options)}return util.isExist(val2)?val2:""}var util=require_util(),xmlNode=require_xmlNode(),readDocType=require_DocTypeReader(),toNumber=require_strnum(),attrsRegx=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm"),parseXml=function(xmlData){xmlData=xmlData.replace(/\r\n?/g,"\n");const xmlObj=new xmlNode("!xml");let currentNode=xmlObj,textData="",jPath="";for(let i2=0;i2<xmlData.length;i2++)if("<"===xmlData[i2])if("/"===xmlData[i2+1]){const closeIndex=findClosingIndex(xmlData,">",i2,"Closing Tag is not closed.");let tagName=xmlData.substring(i2+2,closeIndex).trim();if(this.options.removeNSPrefix){const colonIndex=tagName.indexOf(":");-1!==colonIndex&&(tagName=tagName.substr(colonIndex+1))}this.options.transformTagName&&(tagName=this.options.transformTagName(tagName));currentNode&&(textData=this.saveTextToParentTag(textData,currentNode,jPath));const lastTagName=jPath.substring(jPath.lastIndexOf(".")+1);if(tagName&&-1!==this.options.unpairedTags.indexOf(tagName))throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);let propIndex=0;if(lastTagName&&-1!==this.options.unpairedTags.indexOf(lastTagName)){propIndex=jPath.lastIndexOf(".",jPath.lastIndexOf(".")-1);this.tagsNodeStack.pop()}else propIndex=jPath.lastIndexOf(".");jPath=jPath.substring(0,propIndex);currentNode=this.tagsNodeStack.pop();textData="";i2=closeIndex}else if("?"===xmlData[i2+1]){let tagData=readTagExp(xmlData,i2,!1,"?>");if(!tagData)throw new Error("Pi Tag is not closed.");textData=this.saveTextToParentTag(textData,currentNode,jPath);if(this.options.ignoreDeclaration&&"?xml"===tagData.tagName||this.options.ignorePiTags);else{const childNode=new xmlNode(tagData.tagName);childNode.add(this.options.textNodeName,"");tagData.tagName!==tagData.tagExp&&tagData.attrExpPresent&&(childNode[":@"]=this.buildAttributesMap(tagData.tagExp,jPath,tagData.tagName));this.addChild(currentNode,childNode,jPath)}i2=tagData.closeIndex+1}else if("!--"===xmlData.substr(i2+1,3)){const endIndex=findClosingIndex(xmlData,"--\x3e",i2+4,"Comment is not closed.");if(this.options.commentPropName){const comment2=xmlData.substring(i2+4,endIndex-2);textData=this.saveTextToParentTag(textData,currentNode,jPath);currentNode.add(this.options.commentPropName,[{[this.options.textNodeName]:comment2}])}i2=endIndex}else if("!D"===xmlData.substr(i2+1,2)){const result=readDocType(xmlData,i2);this.docTypeEntities=result.entities;i2=result.i}else if("!["===xmlData.substr(i2+1,2)){const closeIndex=findClosingIndex(xmlData,"]]>",i2,"CDATA is not closed.")-2,tagExp=xmlData.substring(i2+9,closeIndex);textData=this.saveTextToParentTag(textData,currentNode,jPath);let val2=this.parseTextData(tagExp,currentNode.tagname,jPath,!0,!1,!0,!0);null==val2&&(val2="");this.options.cdataPropName?currentNode.add(this.options.cdataPropName,[{[this.options.textNodeName]:tagExp}]):currentNode.add(this.options.textNodeName,val2);i2=closeIndex+2}else{let result=readTagExp(xmlData,i2,this.options.removeNSPrefix),tagName=result.tagName;const rawTagName=result.rawTagName;let tagExp=result.tagExp,attrExpPresent=result.attrExpPresent,closeIndex=result.closeIndex;this.options.transformTagName&&(tagName=this.options.transformTagName(tagName));currentNode&&textData&&"!xml"!==currentNode.tagname&&(textData=this.saveTextToParentTag(textData,currentNode,jPath,!1));const lastTag=currentNode;if(lastTag&&-1!==this.options.unpairedTags.indexOf(lastTag.tagname)){currentNode=this.tagsNodeStack.pop();jPath=jPath.substring(0,jPath.lastIndexOf("."))}tagName!==xmlObj.tagname&&(jPath+=jPath?"."+tagName:tagName);if(this.isItStopNode(this.options.stopNodes,jPath,tagName)){let tagContent="";if(tagExp.length>0&&tagExp.lastIndexOf("/")===tagExp.length-1){if("/"===tagName[tagName.length-1]){tagName=tagName.substr(0,tagName.length-1);jPath=jPath.substr(0,jPath.length-1);tagExp=tagName}else tagExp=tagExp.substr(0,tagExp.length-1);i2=result.closeIndex}else if(-1!==this.options.unpairedTags.indexOf(tagName))i2=result.closeIndex;else{const result2=this.readStopNodeData(xmlData,rawTagName,closeIndex+1);if(!result2)throw new Error(`Unexpected end of ${rawTagName}`);i2=result2.i;tagContent=result2.tagContent}const childNode=new xmlNode(tagName);tagName!==tagExp&&attrExpPresent&&(childNode[":@"]=this.buildAttributesMap(tagExp,jPath,tagName));tagContent&&(tagContent=this.parseTextData(tagContent,tagName,jPath,!0,attrExpPresent,!0,!0));jPath=jPath.substr(0,jPath.lastIndexOf("."));childNode.add(this.options.textNodeName,tagContent);this.addChild(currentNode,childNode,jPath)}else{if(tagExp.length>0&&tagExp.lastIndexOf("/")===tagExp.length-1){if("/"===tagName[tagName.length-1]){tagName=tagName.substr(0,tagName.length-1);jPath=jPath.substr(0,jPath.length-1);tagExp=tagName}else tagExp=tagExp.substr(0,tagExp.length-1);this.options.transformTagName&&(tagName=this.options.transformTagName(tagName));const childNode=new xmlNode(tagName);tagName!==tagExp&&attrExpPresent&&(childNode[":@"]=this.buildAttributesMap(tagExp,jPath,tagName));this.addChild(currentNode,childNode,jPath);jPath=jPath.substr(0,jPath.lastIndexOf("."))}else{const childNode=new xmlNode(tagName);this.tagsNodeStack.push(currentNode);tagName!==tagExp&&attrExpPresent&&(childNode[":@"]=this.buildAttributesMap(tagExp,jPath,tagName));this.addChild(currentNode,childNode,jPath);currentNode=childNode}textData="";i2=closeIndex}}else textData+=xmlData[i2];return xmlObj.child},replaceEntitiesValue=function(val2){if(this.options.processEntities){for(let entityName2 in this.docTypeEntities){const entity=this.docTypeEntities[entityName2];val2=val2.replace(entity.regx,entity.val)}for(let entityName2 in this.lastEntities){const entity=this.lastEntities[entityName2];val2=val2.replace(entity.regex,entity.val)}if(this.options.htmlEntities)for(let entityName2 in this.htmlEntities){const entity=this.htmlEntities[entityName2];val2=val2.replace(entity.regex,entity.val)}val2=val2.replace(this.ampEntity.regex,this.ampEntity.val)}return val2};module2.exports=class{constructor(options){this.options=options;this.currentNode=null;this.tagsNodeStack=[];this.docTypeEntities={};this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}};this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"};this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(_,str)=>String.fromCharCode(Number.parseInt(str,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(_,str)=>String.fromCharCode(Number.parseInt(str,16))}};this.addExternalEntities=addExternalEntities;this.parseXml=parseXml;this.parseTextData=parseTextData;this.resolveNameSpace=resolveNameSpace;this.buildAttributesMap=buildAttributesMap;this.isItStopNode=isItStopNode;this.replaceEntitiesValue=replaceEntitiesValue;this.readStopNodeData=readStopNodeData;this.saveTextToParentTag=saveTextToParentTag;this.addChild=addChild}}}}),require_node2json=__commonJS({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(exports){"use strict";function compress(arr,options,jPath){let text2;const compressedObj={};for(let i2=0;i2<arr.length;i2++){const tagObj=arr[i2],property=propName(tagObj);let newJpath="";newJpath=void 0===jPath?property:jPath+"."+property;if(property===options.textNodeName)void 0===text2?text2=tagObj[property]:text2+=""+tagObj[property];else{if(void 0===property)continue;if(tagObj[property]){let val2=compress(tagObj[property],options,newJpath);const isLeaf=isLeafTag(val2,options);tagObj[":@"]?assignAttributes(val2,tagObj[":@"],newJpath,options):1!==Object.keys(val2).length||void 0===val2[options.textNodeName]||options.alwaysCreateTextNode?0===Object.keys(val2).length&&(options.alwaysCreateTextNode?val2[options.textNodeName]="":val2=""):val2=val2[options.textNodeName];if(void 0!==compressedObj[property]&&compressedObj.hasOwnProperty(property)){Array.isArray(compressedObj[property])||(compressedObj[property]=[compressedObj[property]]);compressedObj[property].push(val2)}else options.isArray(property,newJpath,isLeaf)?compressedObj[property]=[val2]:compressedObj[property]=val2}}}"string"==typeof text2?text2.length>0&&(compressedObj[options.textNodeName]=text2):void 0!==text2&&(compressedObj[options.textNodeName]=text2);return compressedObj}function propName(obj){const keys3=Object.keys(obj);for(let i2=0;i2<keys3.length;i2++){const key3=keys3[i2];if(":@"!==key3)return key3}}function assignAttributes(obj,attrMap,jpath,options){if(attrMap){const keys3=Object.keys(attrMap),len=keys3.length;for(let i2=0;i2<len;i2++){const atrrName=keys3[i2];options.isArray(atrrName,jpath+"."+atrrName,!0,!0)?obj[atrrName]=[attrMap[atrrName]]:obj[atrrName]=attrMap[atrrName]}}}function isLeafTag(obj,options){const{textNodeName}=options,propCount=Object.keys(obj).length;return 0===propCount||!(1!==propCount||!obj[textNodeName]&&"boolean"!=typeof obj[textNodeName]&&0!==obj[textNodeName])}exports.prettify=function prettify(node,options){return compress(node,options)}}}),require_XMLParser=__commonJS({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(exports,module2){var OrderedObjParser,validator,XMLParser2,{buildOptions}=require_OptionsBuilder();OrderedObjParser=require_OrderedObjParser();var{prettify}=require_node2json();validator=require_validator();XMLParser2=class{constructor(options){this.externalEntities={};this.options=buildOptions(options)}parse(xmlData,validationOption){if("string"==typeof xmlData);else{if(!xmlData.toString)throw new Error("XML data is accepted in String or Bytes[] form.");xmlData=xmlData.toString()}if(validationOption){!0===validationOption&&(validationOption={});const result=validator.validate(xmlData,validationOption);if(!0!==result)throw Error(`${result.err.msg}:${result.err.line}:${result.err.col}`)}const orderedObjParser=new OrderedObjParser(this.options);orderedObjParser.addExternalEntities(this.externalEntities);const orderedResult=orderedObjParser.parseXml(xmlData);return this.options.preserveOrder||void 0===orderedResult?orderedResult:prettify(orderedResult,this.options)}addEntity(key3,value){if(-1!==value.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==key3.indexOf("&")||-1!==key3.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===value)throw new Error("An entity with value '&' is not permitted");this.externalEntities[key3]=value}};module2.exports=XMLParser2}}),require_orderedJs2Xml=__commonJS({"node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js"(exports,module2){function arrToStr(arr,options,jPath,indentation){let xmlStr="",isPreviousElementTag=!1;for(let i2=0;i2<arr.length;i2++){const tagObj=arr[i2],tagName=propName(tagObj);if(void 0===tagName)continue;let newJPath="";newJPath=0===jPath.length?tagName:`${jPath}.${tagName}`;if(tagName===options.textNodeName){let tagText=tagObj[tagName];if(!isStopNode(newJPath,options)){tagText=options.tagValueProcessor(tagName,tagText);tagText=replaceEntitiesValue(tagText,options)}isPreviousElementTag&&(xmlStr+=indentation);xmlStr+=tagText;isPreviousElementTag=!1;continue}if(tagName===options.cdataPropName){isPreviousElementTag&&(xmlStr+=indentation);xmlStr+=`<![CDATA[${tagObj[tagName][0][options.textNodeName]}]]>`;isPreviousElementTag=!1;continue}if(tagName===options.commentPropName){xmlStr+=indentation+`\x3c!--${tagObj[tagName][0][options.textNodeName]}--\x3e`;isPreviousElementTag=!0;continue}if("?"===tagName[0]){const attStr2=attr_to_str(tagObj[":@"],options),tempInd="?xml"===tagName?"":indentation;let piTextNodeName=tagObj[tagName][0][options.textNodeName];piTextNodeName=0!==piTextNodeName.length?" "+piTextNodeName:"";xmlStr+=tempInd+`<${tagName}${piTextNodeName}${attStr2}?>`;isPreviousElementTag=!0;continue}let newIdentation=indentation;""!==newIdentation&&(newIdentation+=options.indentBy);const tagStart=indentation+`<${tagName}${attr_to_str(tagObj[":@"],options)}`,tagValue=arrToStr(tagObj[tagName],options,newJPath,newIdentation);if(-1!==options.unpairedTags.indexOf(tagName))options.suppressUnpairedNode?xmlStr+=tagStart+">":xmlStr+=tagStart+"/>";else if(tagValue&&0!==tagValue.length||!options.suppressEmptyNode)if(tagValue&&tagValue.endsWith(">"))xmlStr+=tagStart+`>${tagValue}${indentation}</${tagName}>`;else{xmlStr+=tagStart+">";tagValue&&""!==indentation&&(tagValue.includes("/>")||tagValue.includes("</"))?xmlStr+=indentation+options.indentBy+tagValue+indentation:xmlStr+=tagValue;xmlStr+=`</${tagName}>`}else xmlStr+=tagStart+"/>";isPreviousElementTag=!0}return xmlStr}function propName(obj){const keys3=Object.keys(obj);for(let i2=0;i2<keys3.length;i2++){const key3=keys3[i2];if(obj.hasOwnProperty(key3)&&":@"!==key3)return key3}}function attr_to_str(attrMap,options){let attrStr="";if(attrMap&&!options.ignoreAttributes)for(let attr2 in attrMap){if(!attrMap.hasOwnProperty(attr2))continue;let attrVal=options.attributeValueProcessor(attr2,attrMap[attr2]);attrVal=replaceEntitiesValue(attrVal,options);!0===attrVal&&options.suppressBooleanAttributes?attrStr+=` ${attr2.substr(options.attributeNamePrefix.length)}`:attrStr+=` ${attr2.substr(options.attributeNamePrefix.length)}="${attrVal}"`}return attrStr}function isStopNode(jPath,options){let tagName=(jPath=jPath.substr(0,jPath.length-options.textNodeName.length-1)).substr(jPath.lastIndexOf(".")+1);for(let index6 in options.stopNodes)if(options.stopNodes[index6]===jPath||options.stopNodes[index6]==="*."+tagName)return!0;return!1}function replaceEntitiesValue(textValue,options){if(textValue&&textValue.length>0&&options.processEntities)for(let i2=0;i2<options.entities.length;i2++){const entity=options.entities[i2];textValue=textValue.replace(entity.regex,entity.val)}return textValue}module2.exports=function toXml(jArray,options){let indentation="";options.format&&options.indentBy.length>0&&(indentation="\n");return arrToStr(jArray,options,"",indentation)}}}),require_json2xml=__commonJS({"node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js"(exports,module2){"use strict";function Builder(options){this.options=Object.assign({},defaultOptions,options);if(this.options.ignoreAttributes||this.options.attributesGroupName)this.isAttribute=function(){return!1};else{this.attrPrefixLen=this.options.attributeNamePrefix.length;this.isAttribute=isAttribute}this.processTextOrObjNode=processTextOrObjNode;if(this.options.format){this.indentate=indentate;this.tagEndChar=">\n";this.newLine="\n"}else{this.indentate=function(){return""};this.tagEndChar=">";this.newLine=""}}function processTextOrObjNode(object,key3,level){const result=this.j2x(object,level+1);return void 0!==object[this.options.textNodeName]&&1===Object.keys(object).length?this.buildTextValNode(object[this.options.textNodeName],key3,result.attrStr,level):this.buildObjectNode(result.val,key3,result.attrStr,level)}function indentate(level){return this.options.indentBy.repeat(level)}function isAttribute(name){return!(!name.startsWith(this.options.attributeNamePrefix)||name===this.options.textNodeName)&&name.substr(this.attrPrefixLen)}var buildFromOrderedJs=require_orderedJs2Xml(),defaultOptions={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(key3,a2){return a2},attributeValueProcessor:function(attrName,a2){return a2},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};Builder.prototype.build=function(jObj){if(this.options.preserveOrder)return buildFromOrderedJs(jObj,this.options);Array.isArray(jObj)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(jObj={[this.options.arrayNodeName]:jObj});return this.j2x(jObj,0).val};Builder.prototype.j2x=function(jObj,level){let attrStr="",val2="";for(let key3 in jObj)if(Object.prototype.hasOwnProperty.call(jObj,key3))if(void 0===jObj[key3])this.isAttribute(key3)&&(val2+="");else if(null===jObj[key3])this.isAttribute(key3)?val2+="":"?"===key3[0]?val2+=this.indentate(level)+"<"+key3+"?"+this.tagEndChar:val2+=this.indentate(level)+"<"+key3+"/"+this.tagEndChar;else if(jObj[key3]instanceof Date)val2+=this.buildTextValNode(jObj[key3],key3,"",level);else if("object"!=typeof jObj[key3]){const attr2=this.isAttribute(key3);if(attr2)attrStr+=this.buildAttrPairStr(attr2,""+jObj[key3]);else if(key3===this.options.textNodeName){let newval=this.options.tagValueProcessor(key3,""+jObj[key3]);val2+=this.replaceEntitiesValue(newval)}else val2+=this.buildTextValNode(jObj[key3],key3,"",level)}else if(Array.isArray(jObj[key3])){const arrLen=jObj[key3].length;let listTagVal="",listTagAttr="";for(let j2=0;j2<arrLen;j2++){const item=jObj[key3][j2];if(void 0===item);else if(null===item)"?"===key3[0]?val2+=this.indentate(level)+"<"+key3+"?"+this.tagEndChar:val2+=this.indentate(level)+"<"+key3+"/"+this.tagEndChar;else if("object"==typeof item)if(this.options.oneListGroup){const result=this.j2x(item,level+1);listTagVal+=result.val;this.options.attributesGroupName&&item.hasOwnProperty(this.options.attributesGroupName)&&(listTagAttr+=result.attrStr)}else listTagVal+=this.processTextOrObjNode(item,key3,level);else if(this.options.oneListGroup){let textValue=this.options.tagValueProcessor(key3,item);textValue=this.replaceEntitiesValue(textValue);listTagVal+=textValue}else listTagVal+=this.buildTextValNode(item,key3,"",level)}this.options.oneListGroup&&(listTagVal=this.buildObjectNode(listTagVal,key3,listTagAttr,level));val2+=listTagVal}else if(this.options.attributesGroupName&&key3===this.options.attributesGroupName){const Ks=Object.keys(jObj[key3]),L4=Ks.length;for(let j2=0;j2<L4;j2++)attrStr+=this.buildAttrPairStr(Ks[j2],""+jObj[key3][Ks[j2]])}else val2+=this.processTextOrObjNode(jObj[key3],key3,level);return{attrStr,val:val2}};Builder.prototype.buildAttrPairStr=function(attrName,val2){val2=this.options.attributeValueProcessor(attrName,""+val2);val2=this.replaceEntitiesValue(val2);return this.options.suppressBooleanAttributes&&"true"===val2?" "+attrName:" "+attrName+'="'+val2+'"'};Builder.prototype.buildObjectNode=function(val2,key3,attrStr,level){if(""===val2)return"?"===key3[0]?this.indentate(level)+"<"+key3+attrStr+"?"+this.tagEndChar:this.indentate(level)+"<"+key3+attrStr+this.closeTag(key3)+this.tagEndChar;{let tagEndExp="</"+key3+this.tagEndChar,piClosingChar="";if("?"===key3[0]){piClosingChar="?";tagEndExp=""}return!attrStr&&""!==attrStr||-1!==val2.indexOf("<")?!1!==this.options.commentPropName&&key3===this.options.commentPropName&&0===piClosingChar.length?this.indentate(level)+`\x3c!--${val2}--\x3e`+this.newLine:this.indentate(level)+"<"+key3+attrStr+piClosingChar+this.tagEndChar+val2+this.indentate(level)+tagEndExp:this.indentate(level)+"<"+key3+attrStr+piClosingChar+">"+val2+tagEndExp}};Builder.prototype.closeTag=function(key3){let closeTag="";-1!==this.options.unpairedTags.indexOf(key3)?this.options.suppressUnpairedNode||(closeTag="/"):closeTag=this.options.suppressEmptyNode?"/":`></${key3}`;return closeTag};Builder.prototype.buildTextValNode=function(val2,key3,attrStr,level){if(!1!==this.options.cdataPropName&&key3===this.options.cdataPropName)return this.indentate(level)+`<![CDATA[${val2}]]>`+this.newLine;if(!1!==this.options.commentPropName&&key3===this.options.commentPropName)return this.indentate(level)+`\x3c!--${val2}--\x3e`+this.newLine;if("?"===key3[0])return this.indentate(level)+"<"+key3+attrStr+"?"+this.tagEndChar;{let textValue=this.options.tagValueProcessor(key3,val2);textValue=this.replaceEntitiesValue(textValue);return""===textValue?this.indentate(level)+"<"+key3+attrStr+this.closeTag(key3)+this.tagEndChar:this.indentate(level)+"<"+key3+attrStr+">"+textValue+"</"+key3+this.tagEndChar}};Builder.prototype.replaceEntitiesValue=function(textValue){if(textValue&&textValue.length>0&&this.options.processEntities)for(let i2=0;i2<this.options.entities.length;i2++){const entity=this.options.entities[i2];textValue=textValue.replace(entity.regex,entity.val)}return textValue};module2.exports=Builder}}),require_fxp=__commonJS({"node_modules/fast-xml-parser/src/fxp.js"(exports,module2){"use strict";var validator=require_validator(),XMLParser2=require_XMLParser(),XMLBuilder=require_json2xml();module2.exports={XMLParser:XMLParser2,XMLValidator:validator,XMLBuilder}}}),require_es5=__commonJS({"node_modules/bowser/es5.js"(exports,module2){!function(e3,t3){"object"==typeof exports&&"object"==typeof module2?module2.exports=t3():"function"==typeof define&&define.amd?define([],t3):"object"==typeof exports?exports.bowser=t3():e3.bowser=t3()}(exports,(function(){return function(e3){function r4(n3){if(t3[n3])return t3[n3].exports;var i2=t3[n3]={i:n3,l:!1,exports:{}};return e3[n3].call(i2.exports,i2,i2.exports,r4),i2.l=!0,i2.exports}var t3={};return r4.m=e3,r4.c=t3,r4.d=function(e4,t4,n3){r4.o(e4,t4)||Object.defineProperty(e4,t4,{enumerable:!0,get:n3})},r4.r=function(e4){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e4,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e4,"__esModule",{value:!0})},r4.t=function(e4,t4){var n3,i2;if(1&t4&&(e4=r4(e4)),8&t4)return e4;if(4&t4&&"object"==typeof e4&&e4&&e4.__esModule)return e4;n3=Object.create(null);if(r4.r(n3),Object.defineProperty(n3,"default",{enumerable:!0,value:e4}),2&t4&&"string"!=typeof e4)for(i2 in e4)r4.d(n3,i2,(function(t5){return e4[t5]}).bind(null,i2));return n3},r4.n=function(e4){var t4=e4&&e4.__esModule?function(){return e4.default}:function(){return e4};return r4.d(t4,"a",t4),t4},r4.o=function(e4,t4){return Object.prototype.hasOwnProperty.call(e4,t4)},r4.p="",r4(r4.s=90)}({17:function(e3,t3,r4){"use strict";t3.__esModule=!0,t3.default=void 0;var n3=r4(18),i2=function(){function e4(){}return e4.getFirstMatch=function(e5,t4){var r5=t4.match(e5);return r5&&r5.length>0&&r5[1]||""},e4.getSecondMatch=function(e5,t4){var r5=t4.match(e5);return r5&&r5.length>1&&r5[2]||""},e4.matchAndReturnConst=function(e5,t4,r5){if(e5.test(t4))return r5},e4.getWindowsVersionName=function(e5){switch(e5){case"NT":return"NT";case"XP":return"XP";case"NT 5.0":return"2000";case"NT 5.1":return"XP";case"NT 5.2":return"2003";case"NT 6.0":return"Vista";case"NT 6.1":return"7";case"NT 6.2":return"8";case"NT 6.3":return"8.1";case"NT 10.0":return"10";default:return}},e4.getMacOSVersionName=function(e5){var t4=e5.split(".").splice(0,2).map((function(e6){return parseInt(e6,10)||0}));if(t4.push(0),10===t4[0])switch(t4[1]){case 5:return"Leopard";case 6:return"Snow Leopard";case 7:return"Lion";case 8:return"Mountain Lion";case 9:return"Mavericks";case 10:return"Yosemite";case 11:return"El Capitan";case 12:return"Sierra";case 13:return"High Sierra";case 14:return"Mojave";case 15:return"Catalina";default:return}},e4.getAndroidVersionName=function(e5){var t4=e5.split(".").splice(0,2).map((function(e6){return parseInt(e6,10)||0}));if(t4.push(0),!(1===t4[0]&&t4[1]<5))return 1===t4[0]&&t4[1]<6?"Cupcake":1===t4[0]&&t4[1]>=6?"Donut":2===t4[0]&&t4[1]<2?"Eclair":2===t4[0]&&2===t4[1]?"Froyo":2===t4[0]&&t4[1]>2?"Gingerbread":3===t4[0]?"Honeycomb":4===t4[0]&&t4[1]<1?"Ice Cream Sandwich":4===t4[0]&&t4[1]<4?"Jelly Bean":4===t4[0]&&t4[1]>=4?"KitKat":5===t4[0]?"Lollipop":6===t4[0]?"Marshmallow":7===t4[0]?"Nougat":8===t4[0]?"Oreo":9===t4[0]?"Pie":void 0},e4.getVersionPrecision=function(e5){return e5.split(".").length},e4.compareVersions=function(t4,r5,n4){void 0===n4&&(n4=!1);var i3=e4.getVersionPrecision(t4),s2=e4.getVersionPrecision(r5),a2=Math.max(i3,s2),o2=0,u2=e4.map([t4,r5],(function(t5){var r6=a2-e4.getVersionPrecision(t5),n5=t5+new Array(r6+1).join(".0");return e4.map(n5.split("."),(function(e5){return new Array(20-e5.length).join("0")+e5})).reverse()}));for(n4&&(o2=a2-Math.min(i3,s2)),a2-=1;a2>=o2;){if(u2[0][a2]>u2[1][a2])return 1;if(u2[0][a2]===u2[1][a2]){if(a2===o2)return 0;a2-=1}else if(u2[0][a2]<u2[1][a2])return-1}},e4.map=function(e5,t4){var r5,n4=[];if(Array.prototype.map)return Array.prototype.map.call(e5,t4);for(r5=0;r5<e5.length;r5+=1)n4.push(t4(e5[r5]));return n4},e4.find=function(e5,t4){var r5,n4,i3;if(Array.prototype.find)return Array.prototype.find.call(e5,t4);for(r5=0,n4=e5.length;r5<n4;r5+=1)if(t4(i3=e5[r5],r5))return i3},e4.assign=function(e5){var t4,r5,n4,i3,s2,a2,o2;for(n4=e5,i3=arguments.length,s2=new Array(i3>1?i3-1:0),a2=1;a2<i3;a2++)s2[a2-1]=arguments[a2];if(Object.assign)return Object.assign.apply(Object,[e5].concat(s2));o2=function(){var e6=s2[t4];"object"==typeof e6&&null!==e6&&Object.keys(e6).forEach((function(t5){n4[t5]=e6[t5]}))};for(t4=0,r5=s2.length;t4<r5;t4+=1)o2();return e5},e4.getBrowserAlias=function(e5){return n3.BROWSER_ALIASES_MAP[e5]},e4.getBrowserTypeByAlias=function(e5){return n3.BROWSER_MAP[e5]||""},e4}();t3.default=i2,e3.exports=t3.default},18:function(e3,t3,r4){"use strict";t3.__esModule=!0,t3.ENGINE_MAP=t3.OS_MAP=t3.PLATFORMS_MAP=t3.BROWSER_MAP=t3.BROWSER_ALIASES_MAP=void 0;t3.BROWSER_ALIASES_MAP={"Amazon Silk":"amazon_silk","Android Browser":"android",Bada:"bada",BlackBerry:"blackberry",Chrome:"chrome",Chromium:"chromium",Electron:"electron",Epiphany:"epiphany",Firefox:"firefox",Focus:"focus",Generic:"generic","Google Search":"google_search",Googlebot:"googlebot","Internet Explorer":"ie","K-Meleon":"k_meleon",Maxthon:"maxthon","Microsoft Edge":"edge","MZ Browser":"mz","NAVER Whale Browser":"naver",Opera:"opera","Opera Coast":"opera_coast",PhantomJS:"phantomjs",Puffin:"puffin",QupZilla:"qupzilla",QQ:"qq",QQLite:"qqlite",Safari:"safari",Sailfish:"sailfish","Samsung Internet for Android":"samsung_internet",SeaMonkey:"seamonkey",Sleipnir:"sleipnir",Swing:"swing",Tizen:"tizen","UC Browser":"uc",Vivaldi:"vivaldi","WebOS Browser":"webos",WeChat:"wechat","Yandex Browser":"yandex",Roku:"roku"};t3.BROWSER_MAP={amazon_silk:"Amazon Silk",android:"Android Browser",bada:"Bada",blackberry:"BlackBerry",chrome:"Chrome",chromium:"Chromium",electron:"Electron",epiphany:"Epiphany",firefox:"Firefox",focus:"Focus",generic:"Generic",googlebot:"Googlebot",google_search:"Google Search",ie:"Internet Explorer",k_meleon:"K-Meleon",maxthon:"Maxthon",edge:"Microsoft Edge",mz:"MZ Browser",naver:"NAVER Whale Browser",opera:"Opera",opera_coast:"Opera Coast",phantomjs:"PhantomJS",puffin:"Puffin",qupzilla:"QupZilla",qq:"QQ Browser",qqlite:"QQ Browser Lite",safari:"Safari",sailfish:"Sailfish",samsung_internet:"Samsung Internet for Android",seamonkey:"SeaMonkey",sleipnir:"Sleipnir",swing:"Swing",tizen:"Tizen",uc:"UC Browser",vivaldi:"Vivaldi",webos:"WebOS Browser",wechat:"WeChat",yandex:"Yandex Browser"};t3.PLATFORMS_MAP={tablet:"tablet",mobile:"mobile",desktop:"desktop",tv:"tv"};t3.OS_MAP={WindowsPhone:"Windows Phone",Windows:"Windows",MacOS:"macOS",iOS:"iOS",Android:"Android",WebOS:"WebOS",BlackBerry:"BlackBerry",Bada:"Bada",Tizen:"Tizen",Linux:"Linux",ChromeOS:"Chrome OS",PlayStation4:"PlayStation 4",Roku:"Roku"};t3.ENGINE_MAP={EdgeHTML:"EdgeHTML",Blink:"Blink",Trident:"Trident",Presto:"Presto",Gecko:"Gecko",WebKit:"WebKit"}},90:function(e3,t3,r4){"use strict";function a2(e4,t4){var r5,n4;for(r5=0;r5<t4.length;r5++)(n4=t4[r5]).enumerable=n4.enumerable||!1,n4.configurable=!0,"value"in n4&&(n4.writable=!0),Object.defineProperty(e4,n4.key,n4)}var n3,i2,s2,o2;t3.__esModule=!0,t3.default=void 0;i2=(n3=r4(91))&&n3.__esModule?n3:{default:n3},s2=r4(18);o2=function(){function e4(){}var n4;return e4.getParser=function(e5,t5){if(void 0===t5&&(t5=!1),"string"!=typeof e5)throw new Error("UserAgent should be a string");return new i2.default(e5,t5)},e4.parse=function(e5){return new i2.default(e5).getResult()},(n4=[{key:"BROWSER_MAP",get:function(){return s2.BROWSER_MAP}},{key:"ENGINE_MAP",get:function(){return s2.ENGINE_MAP}},{key:"OS_MAP",get:function(){return s2.OS_MAP}},{key:"PLATFORMS_MAP",get:function(){return s2.PLATFORMS_MAP}}])&&a2(e4,n4),e4}();t3.default=o2,e3.exports=t3.default},91:function(e3,t3,r4){"use strict";function u2(e4){return e4&&e4.__esModule?e4:{default:e4}}var n3,i2,s2,a2,o2,d4;t3.__esModule=!0,t3.default=void 0;n3=u2(r4(92)),i2=u2(r4(93)),s2=u2(r4(94)),a2=u2(r4(95)),o2=u2(r4(17));d4=function(){function e4(e5,t5){if(void 0===t5&&(t5=!1),null==e5||""===e5)throw new Error("UserAgent parameter can't be empty");this._ua=e5,this.parsedResult={},!0!==t5&&this.parse()}var t4=e4.prototype;return t4.getUA=function(){return this._ua},t4.test=function(e5){return e5.test(this._ua)},t4.parseBrowser=function(){var t5,e5=this;this.parsedResult.browser={};return(t5=o2.default.find(n3.default,(function(t6){if("function"==typeof t6.test)return t6.test(e5);if(t6.test instanceof Array)return t6.test.some((function(t7){return e5.test(t7)}));throw new Error("Browser's test function is not valid")})))&&(this.parsedResult.browser=t5.describe(this.getUA())),this.parsedResult.browser},t4.getBrowser=function(){return this.parsedResult.browser?this.parsedResult.browser:this.parseBrowser()},t4.getBrowserName=function(e5){return e5?String(this.getBrowser().name).toLowerCase()||"":this.getBrowser().name||""},t4.getBrowserVersion=function(){return this.getBrowser().version},t4.getOS=function(){return this.parsedResult.os?this.parsedResult.os:this.parseOS()},t4.parseOS=function(){var t5,e5=this;this.parsedResult.os={};return(t5=o2.default.find(i2.default,(function(t6){if("function"==typeof t6.test)return t6.test(e5);if(t6.test instanceof Array)return t6.test.some((function(t7){return e5.test(t7)}));throw new Error("Browser's test function is not valid")})))&&(this.parsedResult.os=t5.describe(this.getUA())),this.parsedResult.os},t4.getOSName=function(e5){var t5=this.getOS().name;return e5?String(t5).toLowerCase()||"":t5||""},t4.getOSVersion=function(){return this.getOS().version},t4.getPlatform=function(){return this.parsedResult.platform?this.parsedResult.platform:this.parsePlatform()},t4.getPlatformType=function(e5){void 0===e5&&(e5=!1);var t5=this.getPlatform().type;return e5?String(t5).toLowerCase()||"":t5||""},t4.parsePlatform=function(){var t5,e5=this;this.parsedResult.platform={};return(t5=o2.default.find(s2.default,(function(t6){if("function"==typeof t6.test)return t6.test(e5);if(t6.test instanceof Array)return t6.test.some((function(t7){return e5.test(t7)}));throw new Error("Browser's test function is not valid")})))&&(this.parsedResult.platform=t5.describe(this.getUA())),this.parsedResult.platform},t4.getEngine=function(){return this.parsedResult.engine?this.parsedResult.engine:this.parseEngine()},t4.getEngineName=function(e5){return e5?String(this.getEngine().name).toLowerCase()||"":this.getEngine().name||""},t4.parseEngine=function(){var t5,e5=this;this.parsedResult.engine={};return(t5=o2.default.find(a2.default,(function(t6){if("function"==typeof t6.test)return t6.test(e5);if(t6.test instanceof Array)return t6.test.some((function(t7){return e5.test(t7)}));throw new Error("Browser's test function is not valid")})))&&(this.parsedResult.engine=t5.describe(this.getUA())),this.parsedResult.engine},t4.parse=function(){return this.parseBrowser(),this.parseOS(),this.parsePlatform(),this.parseEngine(),this},t4.getResult=function(){return o2.default.assign({},this.parsedResult)},t4.satisfies=function(e5){var a3,u3,d5,c3,f4,l2,h3,t5=this,r5={},n4=0,i3={},s3=0;if(Object.keys(e5).forEach((function(t6){var a4=e5[t6];"string"==typeof a4?(i3[t6]=a4,s3+=1):"object"==typeof a4&&(r5[t6]=a4,n4+=1)})),n4>0){a3=Object.keys(r5);if((u3=o2.default.find(a3,(function(e6){return t5.isOS(e6)})))&&void 0!==(d5=this.satisfies(r5[u3])))return d5;if((c3=o2.default.find(a3,(function(e6){return t5.isPlatform(e6)})))&&void 0!==(f4=this.satisfies(r5[c3])))return f4}if(s3>0){l2=Object.keys(i3);if(void 0!==(h3=o2.default.find(l2,(function(e6){return t5.isBrowser(e6,!0)}))))return this.compareVersion(i3[h3])}},t4.isBrowser=function(e5,t5){void 0===t5&&(t5=!1);var r5=this.getBrowserName().toLowerCase(),n4=e5.toLowerCase(),i3=o2.default.getBrowserTypeByAlias(n4);return t5&&i3&&(n4=i3.toLowerCase()),n4===r5},t4.compareVersion=function(e5){var t5=[0],r5=e5,n4=!1,i3=this.getBrowserVersion();if("string"==typeof i3)return">"===e5[0]||"<"===e5[0]?(r5=e5.substr(1),"="===e5[1]?(n4=!0,r5=e5.substr(2)):t5=[],">"===e5[0]?t5.push(1):t5.push(-1)):"="===e5[0]?r5=e5.substr(1):"~"===e5[0]&&(n4=!0,r5=e5.substr(1)),t5.indexOf(o2.default.compareVersions(i3,r5,n4))>-1},t4.isOS=function(e5){return this.getOSName(!0)===String(e5).toLowerCase()},t4.isPlatform=function(e5){return this.getPlatformType(!0)===String(e5).toLowerCase()},t4.isEngine=function(e5){return this.getEngineName(!0)===String(e5).toLowerCase()},t4.is=function(e5,t5){return void 0===t5&&(t5=!1),this.isBrowser(e5,t5)||this.isOS(e5)||this.isPlatform(e5)},t4.some=function(e5){var t5=this;return void 0===e5&&(e5=[]),e5.some((function(e6){return t5.is(e6)}))},e4}();t3.default=d4,e3.exports=t3.default},92:function(e3,t3,r4){"use strict";var n3,i2,s2,a2;t3.__esModule=!0,t3.default=void 0;i2=(n3=r4(17))&&n3.__esModule?n3:{default:n3};s2=/version\/(\d+(\.?_?\d+)+)/i,a2=[{test:[/googlebot/i],describe:function(e4){var t4={name:"Googlebot"},r5=i2.default.getFirstMatch(/googlebot\/(\d+(\.\d+))/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/opera/i],describe:function(e4){var t4={name:"Opera"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:opera)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/opr\/|opios/i],describe:function(e4){var t4={name:"Opera"},r5=i2.default.getFirstMatch(/(?:opr|opios)[\s/](\S+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/SamsungBrowser/i],describe:function(e4){var t4={name:"Samsung Internet for Android"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:SamsungBrowser)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/Whale/i],describe:function(e4){var t4={name:"NAVER Whale Browser"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:whale)[\s/](\d+(?:\.\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/MZBrowser/i],describe:function(e4){var t4={name:"MZ Browser"},r5=i2.default.getFirstMatch(/(?:MZBrowser)[\s/](\d+(?:\.\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/focus/i],describe:function(e4){var t4={name:"Focus"},r5=i2.default.getFirstMatch(/(?:focus)[\s/](\d+(?:\.\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/swing/i],describe:function(e4){var t4={name:"Swing"},r5=i2.default.getFirstMatch(/(?:swing)[\s/](\d+(?:\.\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/coast/i],describe:function(e4){var t4={name:"Opera Coast"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:coast)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/opt\/\d+(?:.?_?\d+)+/i],describe:function(e4){var t4={name:"Opera Touch"},r5=i2.default.getFirstMatch(/(?:opt)[\s/](\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/yabrowser/i],describe:function(e4){var t4={name:"Yandex Browser"},r5=i2.default.getFirstMatch(/(?:yabrowser)[\s/](\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/ucbrowser/i],describe:function(e4){var t4={name:"UC Browser"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:ucbrowser)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/Maxthon|mxios/i],describe:function(e4){var t4={name:"Maxthon"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:Maxthon|mxios)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/epiphany/i],describe:function(e4){var t4={name:"Epiphany"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:epiphany)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/puffin/i],describe:function(e4){var t4={name:"Puffin"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:puffin)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/sleipnir/i],describe:function(e4){var t4={name:"Sleipnir"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:sleipnir)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/k-meleon/i],describe:function(e4){var t4={name:"K-Meleon"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/(?:k-meleon)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/micromessenger/i],describe:function(e4){var t4={name:"WeChat"},r5=i2.default.getFirstMatch(/(?:micromessenger)[\s/](\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/qqbrowser/i],describe:function(e4){var t4={name:/qqbrowserlite/i.test(e4)?"QQ Browser Lite":"QQ Browser"},r5=i2.default.getFirstMatch(/(?:qqbrowserlite|qqbrowser)[/](\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/msie|trident/i],describe:function(e4){var t4={name:"Internet Explorer"},r5=i2.default.getFirstMatch(/(?:msie |rv:)(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/\sedg\//i],describe:function(e4){var t4={name:"Microsoft Edge"},r5=i2.default.getFirstMatch(/\sedg\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/edg([ea]|ios)/i],describe:function(e4){var t4={name:"Microsoft Edge"},r5=i2.default.getSecondMatch(/edg([ea]|ios)\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/vivaldi/i],describe:function(e4){var t4={name:"Vivaldi"},r5=i2.default.getFirstMatch(/vivaldi\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/seamonkey/i],describe:function(e4){var t4={name:"SeaMonkey"},r5=i2.default.getFirstMatch(/seamonkey\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/sailfish/i],describe:function(e4){var t4={name:"Sailfish"},r5=i2.default.getFirstMatch(/sailfish\s?browser\/(\d+(\.\d+)?)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/silk/i],describe:function(e4){var t4={name:"Amazon Silk"},r5=i2.default.getFirstMatch(/silk\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/phantom/i],describe:function(e4){var t4={name:"PhantomJS"},r5=i2.default.getFirstMatch(/phantomjs\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/slimerjs/i],describe:function(e4){var t4={name:"SlimerJS"},r5=i2.default.getFirstMatch(/slimerjs\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e4){var t4={name:"BlackBerry"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/blackberry[\d]+\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/(web|hpw)[o0]s/i],describe:function(e4){var t4={name:"WebOS Browser"},r5=i2.default.getFirstMatch(s2,e4)||i2.default.getFirstMatch(/w(?:eb)?[o0]sbrowser\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/bada/i],describe:function(e4){var t4={name:"Bada"},r5=i2.default.getFirstMatch(/dolfin\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/tizen/i],describe:function(e4){var t4={name:"Tizen"},r5=i2.default.getFirstMatch(/(?:tizen\s?)?browser\/(\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/qupzilla/i],describe:function(e4){var t4={name:"QupZilla"},r5=i2.default.getFirstMatch(/(?:qupzilla)[\s/](\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/firefox|iceweasel|fxios/i],describe:function(e4){var t4={name:"Firefox"},r5=i2.default.getFirstMatch(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/electron/i],describe:function(e4){var t4={name:"Electron"},r5=i2.default.getFirstMatch(/(?:electron)\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/MiuiBrowser/i],describe:function(e4){var t4={name:"Miui"},r5=i2.default.getFirstMatch(/(?:MiuiBrowser)[\s/](\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/chromium/i],describe:function(e4){var t4={name:"Chromium"},r5=i2.default.getFirstMatch(/(?:chromium)[\s/](\d+(\.?_?\d+)+)/i,e4)||i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/chrome|crios|crmo/i],describe:function(e4){var t4={name:"Chrome"},r5=i2.default.getFirstMatch(/(?:chrome|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/GSA/i],describe:function(e4){var t4={name:"Google Search"},r5=i2.default.getFirstMatch(/(?:GSA)\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:function(e4){var t4=!e4.test(/like android/i),r5=e4.test(/android/i);return t4&&r5},describe:function(e4){var t4={name:"Android Browser"},r5=i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/playstation 4/i],describe:function(e4){var t4={name:"PlayStation 4"},r5=i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/safari|applewebkit/i],describe:function(e4){var t4={name:"Safari"},r5=i2.default.getFirstMatch(s2,e4);return r5&&(t4.version=r5),t4}},{test:[/.*/i],describe:function(e4){var t4=-1!==e4.search("\\(")?/^(.*)\/(.*)[ \t]\((.*)/:/^(.*)\/(.*) /;return{name:i2.default.getFirstMatch(t4,e4),version:i2.default.getSecondMatch(t4,e4)}}}];t3.default=a2,e3.exports=t3.default},93:function(e3,t3,r4){"use strict";var n3,i2,s2,a2;t3.__esModule=!0,t3.default=void 0;i2=(n3=r4(17))&&n3.__esModule?n3:{default:n3},s2=r4(18);a2=[{test:[/Roku\/DVP/],describe:function(e4){var t4=i2.default.getFirstMatch(/Roku\/DVP-(\d+\.\d+)/i,e4);return{name:s2.OS_MAP.Roku,version:t4}}},{test:[/windows phone/i],describe:function(e4){var t4=i2.default.getFirstMatch(/windows phone (?:os)?\s?(\d+(\.\d+)*)/i,e4);return{name:s2.OS_MAP.WindowsPhone,version:t4}}},{test:[/windows /i],describe:function(e4){var t4=i2.default.getFirstMatch(/Windows ((NT|XP)( \d\d?.\d)?)/i,e4),r5=i2.default.getWindowsVersionName(t4);return{name:s2.OS_MAP.Windows,version:t4,versionName:r5}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(e4){var t4={name:s2.OS_MAP.iOS},r5=i2.default.getSecondMatch(/(Version\/)(\d[\d.]+)/,e4);return r5&&(t4.version=r5),t4}},{test:[/macintosh/i],describe:function(e4){var t4=i2.default.getFirstMatch(/mac os x (\d+(\.?_?\d+)+)/i,e4).replace(/[_\s]/g,"."),r5=i2.default.getMacOSVersionName(t4),n4={name:s2.OS_MAP.MacOS,version:t4};return r5&&(n4.versionName=r5),n4}},{test:[/(ipod|iphone|ipad)/i],describe:function(e4){var t4=i2.default.getFirstMatch(/os (\d+([_\s]\d+)*) like mac os x/i,e4).replace(/[_\s]/g,".");return{name:s2.OS_MAP.iOS,version:t4}}},{test:function(e4){var t4=!e4.test(/like android/i),r5=e4.test(/android/i);return t4&&r5},describe:function(e4){var t4=i2.default.getFirstMatch(/android[\s/-](\d+(\.\d+)*)/i,e4),r5=i2.default.getAndroidVersionName(t4),n4={name:s2.OS_MAP.Android,version:t4};return r5&&(n4.versionName=r5),n4}},{test:[/(web|hpw)[o0]s/i],describe:function(e4){var t4=i2.default.getFirstMatch(/(?:web|hpw)[o0]s\/(\d+(\.\d+)*)/i,e4),r5={name:s2.OS_MAP.WebOS};return t4&&t4.length&&(r5.version=t4),r5}},{test:[/blackberry|\bbb\d+/i,/rim\stablet/i],describe:function(e4){var t4=i2.default.getFirstMatch(/rim\stablet\sos\s(\d+(\.\d+)*)/i,e4)||i2.default.getFirstMatch(/blackberry\d+\/(\d+([_\s]\d+)*)/i,e4)||i2.default.getFirstMatch(/\bbb(\d+)/i,e4);return{name:s2.OS_MAP.BlackBerry,version:t4}}},{test:[/bada/i],describe:function(e4){var t4=i2.default.getFirstMatch(/bada\/(\d+(\.\d+)*)/i,e4);return{name:s2.OS_MAP.Bada,version:t4}}},{test:[/tizen/i],describe:function(e4){var t4=i2.default.getFirstMatch(/tizen[/\s](\d+(\.\d+)*)/i,e4);return{name:s2.OS_MAP.Tizen,version:t4}}},{test:[/linux/i],describe:function(){return{name:s2.OS_MAP.Linux}}},{test:[/CrOS/],describe:function(){return{name:s2.OS_MAP.ChromeOS}}},{test:[/PlayStation 4/],describe:function(e4){var t4=i2.default.getFirstMatch(/PlayStation 4[/\s](\d+(\.\d+)*)/i,e4);return{name:s2.OS_MAP.PlayStation4,version:t4}}}];t3.default=a2,e3.exports=t3.default},94:function(e3,t3,r4){"use strict";var n3,i2,s2,a2;t3.__esModule=!0,t3.default=void 0;i2=(n3=r4(17))&&n3.__esModule?n3:{default:n3},s2=r4(18);a2=[{test:[/googlebot/i],describe:function(){return{type:"bot",vendor:"Google"}}},{test:[/huawei/i],describe:function(e4){var t4=i2.default.getFirstMatch(/(can-l01)/i,e4)&&"Nova",r5={type:s2.PLATFORMS_MAP.mobile,vendor:"Huawei"};return t4&&(r5.model=t4),r5}},{test:[/nexus\s*(?:7|8|9|10).*/i],describe:function(){return{type:s2.PLATFORMS_MAP.tablet,vendor:"Nexus"}}},{test:[/ipad/i],describe:function(){return{type:s2.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/Macintosh(.*?) FxiOS(.*?)\//],describe:function(){return{type:s2.PLATFORMS_MAP.tablet,vendor:"Apple",model:"iPad"}}},{test:[/kftt build/i],describe:function(){return{type:s2.PLATFORMS_MAP.tablet,vendor:"Amazon",model:"Kindle Fire HD 7"}}},{test:[/silk/i],describe:function(){return{type:s2.PLATFORMS_MAP.tablet,vendor:"Amazon"}}},{test:[/tablet(?! pc)/i],describe:function(){return{type:s2.PLATFORMS_MAP.tablet}}},{test:function(e4){var t4=e4.test(/ipod|iphone/i),r5=e4.test(/like (ipod|iphone)/i);return t4&&!r5},describe:function(e4){var t4=i2.default.getFirstMatch(/(ipod|iphone)/i,e4);return{type:s2.PLATFORMS_MAP.mobile,vendor:"Apple",model:t4}}},{test:[/nexus\s*[0-6].*/i,/galaxy nexus/i],describe:function(){return{type:s2.PLATFORMS_MAP.mobile,vendor:"Nexus"}}},{test:[/[^-]mobi/i],describe:function(){return{type:s2.PLATFORMS_MAP.mobile}}},{test:function(e4){return"blackberry"===e4.getBrowserName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.mobile,vendor:"BlackBerry"}}},{test:function(e4){return"bada"===e4.getBrowserName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.mobile}}},{test:function(e4){return"windows phone"===e4.getBrowserName()},describe:function(){return{type:s2.PLATFORMS_MAP.mobile,vendor:"Microsoft"}}},{test:function(e4){var t4=Number(String(e4.getOSVersion()).split(".")[0]);return"android"===e4.getOSName(!0)&&t4>=3},describe:function(){return{type:s2.PLATFORMS_MAP.tablet}}},{test:function(e4){return"android"===e4.getOSName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.mobile}}},{test:function(e4){return"macos"===e4.getOSName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.desktop,vendor:"Apple"}}},{test:function(e4){return"windows"===e4.getOSName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.desktop}}},{test:function(e4){return"linux"===e4.getOSName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.desktop}}},{test:function(e4){return"playstation 4"===e4.getOSName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.tv}}},{test:function(e4){return"roku"===e4.getOSName(!0)},describe:function(){return{type:s2.PLATFORMS_MAP.tv}}}];t3.default=a2,e3.exports=t3.default},95:function(e3,t3,r4){"use strict";var n3,i2,s2,a2;t3.__esModule=!0,t3.default=void 0;i2=(n3=r4(17))&&n3.__esModule?n3:{default:n3},s2=r4(18);a2=[{test:function(e4){return"microsoft edge"===e4.getBrowserName(!0)},describe:function(e4){if(/\sedg\//i.test(e4))return{name:s2.ENGINE_MAP.Blink};var t4=i2.default.getFirstMatch(/edge\/(\d+(\.?_?\d+)+)/i,e4);return{name:s2.ENGINE_MAP.EdgeHTML,version:t4}}},{test:[/trident/i],describe:function(e4){var t4={name:s2.ENGINE_MAP.Trident},r5=i2.default.getFirstMatch(/trident\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:function(e4){return e4.test(/presto/i)},describe:function(e4){var t4={name:s2.ENGINE_MAP.Presto},r5=i2.default.getFirstMatch(/presto\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:function(e4){var t4=e4.test(/gecko/i),r5=e4.test(/like gecko/i);return t4&&!r5},describe:function(e4){var t4={name:s2.ENGINE_MAP.Gecko},r5=i2.default.getFirstMatch(/gecko\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}},{test:[/(apple)?webkit\/537\.36/i],describe:function(){return{name:s2.ENGINE_MAP.Blink}}},{test:[/(apple)?webkit/i],describe:function(e4){var t4={name:s2.ENGINE_MAP.WebKit},r5=i2.default.getFirstMatch(/webkit\/(\d+(\.?_?\d+)+)/i,e4);return r5&&(t4.version=r5),t4}}];t3.default=a2,e3.exports=t3.default}})}))}}),require_events=__commonJS({"node_modules/events/events.js"(exports,module2){"use strict";function ProcessEmitWarning(warning){console&&console.warn&&console.warn(warning)}function EventEmitter2(){EventEmitter2.init.call(this)}function checkListener(listener){if("function"!=typeof listener)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof listener)}function _getMaxListeners(that){return void 0===that._maxListeners?EventEmitter2.defaultMaxListeners:that._maxListeners}function _addListener(target,type,listener,prepend){var m3,events,existing,w2;checkListener(listener);if(void 0===(events=target._events)){events=target._events=Object.create(null);target._eventsCount=0}else{if(void 0!==events.newListener){target.emit("newListener",type,listener.listener?listener.listener:listener);events=target._events}existing=events[type]}if(void 0===existing){existing=events[type]=listener;++target._eventsCount}else{"function"==typeof existing?existing=events[type]=prepend?[listener,existing]:[existing,listener]:prepend?existing.unshift(listener):existing.push(listener);if((m3=_getMaxListeners(target))>0&&existing.length>m3&&!existing.warned){existing.warned=!0;(w2=new Error("Possible EventEmitter memory leak detected. "+existing.length+" "+String(type)+" listeners added. Use emitter.setMaxListeners() to increase limit")).name="MaxListenersExceededWarning";w2.emitter=target;w2.type=type;w2.count=existing.length;ProcessEmitWarning(w2)}}return target}function onceWrapper(){if(!this.fired){this.target.removeListener(this.type,this.wrapFn);this.fired=!0;return 0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}}function _onceWrap(target,type,listener){var state2={fired:!1,wrapFn:void 0,target,type,listener},wrapped=onceWrapper.bind(state2);wrapped.listener=listener;state2.wrapFn=wrapped;return wrapped}function _listeners2(target,type,unwrap2){var evlistener,events=target._events;return void 0===events||void 0===(evlistener=events[type])?[]:"function"==typeof evlistener?unwrap2?[evlistener.listener||evlistener]:[evlistener]:unwrap2?unwrapListeners(evlistener):arrayClone(evlistener,evlistener.length)}function listenerCount2(type){var evlistener,events=this._events;if(void 0!==events){if("function"==typeof(evlistener=events[type]))return 1;if(void 0!==evlistener)return evlistener.length}return 0}function arrayClone(arr,n3){var i2,copy=new Array(n3);for(i2=0;i2<n3;++i2)copy[i2]=arr[i2];return copy}function spliceOne(list,index6){for(;index6+1<list.length;index6++)list[index6]=list[index6+1];list.pop()}function unwrapListeners(arr){var i2,ret=new Array(arr.length);for(i2=0;i2<ret.length;++i2)ret[i2]=arr[i2].listener||arr[i2];return ret}function addErrorHandlerIfEventEmitter(emitter,handler,flags2){"function"==typeof emitter.on&&eventTargetAgnosticAddListener(emitter,"error",handler,flags2)}function eventTargetAgnosticAddListener(emitter,name,listener,flags2){if("function"==typeof emitter.on)flags2.once?emitter.once(name,listener):emitter.on(name,listener);else{if("function"!=typeof emitter.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof emitter);emitter.addEventListener(name,(function wrapListener(arg){flags2.once&&emitter.removeEventListener(name,wrapListener);listener(arg)}))}}var ReflectOwnKeys,NumberIsNaN,defaultMaxListeners,R2="object"==typeof Reflect?Reflect:null,ReflectApply=R2&&"function"==typeof R2.apply?R2.apply:function ReflectApply2(target,receiver,args){return Function.prototype.apply.call(target,receiver,args)};ReflectOwnKeys=R2&&"function"==typeof R2.ownKeys?R2.ownKeys:Object.getOwnPropertySymbols?function ReflectOwnKeys2(target){return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target))}:function ReflectOwnKeys2(target){return Object.getOwnPropertyNames(target)};NumberIsNaN=Number.isNaN||function NumberIsNaN2(value){return value!=value};module2.exports=EventEmitter2;module2.exports.once=function once3(emitter,name){return new Promise((function(resolve,reject){function errorListener(err3){emitter.removeListener(name,resolver2);reject(err3)}function resolver2(){"function"==typeof emitter.removeListener&&emitter.removeListener("error",errorListener);resolve([].slice.call(arguments))}eventTargetAgnosticAddListener(emitter,name,resolver2,{once:!0});"error"!==name&&addErrorHandlerIfEventEmitter(emitter,errorListener,{once:!0})}))};EventEmitter2.EventEmitter=EventEmitter2;EventEmitter2.prototype._events=void 0;EventEmitter2.prototype._eventsCount=0;EventEmitter2.prototype._maxListeners=void 0;defaultMaxListeners=10;Object.defineProperty(EventEmitter2,"defaultMaxListeners",{enumerable:!0,get:function(){return defaultMaxListeners},set:function(arg){if("number"!=typeof arg||arg<0||NumberIsNaN(arg))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+arg+".");defaultMaxListeners=arg}});EventEmitter2.init=function(){if(void 0===this._events||this._events===Object.getPrototypeOf(this)._events){this._events=Object.create(null);this._eventsCount=0}this._maxListeners=this._maxListeners||void 0};EventEmitter2.prototype.setMaxListeners=function setMaxListeners(n3){if("number"!=typeof n3||n3<0||NumberIsNaN(n3))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+n3+".");this._maxListeners=n3;return this};EventEmitter2.prototype.getMaxListeners=function getMaxListeners(){return _getMaxListeners(this)};EventEmitter2.prototype.emit=function emit2(type){var i2,doError,events,er,err3,handler,len,listeners,args=[];for(i2=1;i2<arguments.length;i2++)args.push(arguments[i2]);doError="error"===type;if(void 0!==(events=this._events))doError=doError&&void 0===events.error;else if(!doError)return!1;if(doError){args.length>0&&(er=args[0]);if(er instanceof Error)throw er;(err3=new Error("Unhandled error."+(er?" ("+er.message+")":""))).context=er;throw err3}if(void 0===(handler=events[type]))return!1;if("function"==typeof handler)ReflectApply(handler,this,args);else{listeners=arrayClone(handler,len=handler.length);for(i2=0;i2<len;++i2)ReflectApply(listeners[i2],this,args)}return!0};EventEmitter2.prototype.addListener=function addListener(type,listener){return _addListener(this,type,listener,!1)};EventEmitter2.prototype.on=EventEmitter2.prototype.addListener;EventEmitter2.prototype.prependListener=function prependListener(type,listener){return _addListener(this,type,listener,!0)};EventEmitter2.prototype.once=function once4(type,listener){checkListener(listener);this.on(type,_onceWrap(this,type,listener));return this};EventEmitter2.prototype.prependOnceListener=function prependOnceListener(type,listener){checkListener(listener);this.prependListener(type,_onceWrap(this,type,listener));return this};EventEmitter2.prototype.removeListener=function removeListener(type,listener){var list,events,position,i2,originalListener;checkListener(listener);if(void 0===(events=this._events))return this;if(void 0===(list=events[type]))return this;if(list===listener||list.listener===listener)if(0==--this._eventsCount)this._events=Object.create(null);else{delete events[type];events.removeListener&&this.emit("removeListener",type,list.listener||listener)}else if("function"!=typeof list){position=-1;for(i2=list.length-1;i2>=0;i2--)if(list[i2]===listener||list[i2].listener===listener){originalListener=list[i2].listener;position=i2;break}if(position<0)return this;0===position?list.shift():spliceOne(list,position);1===list.length&&(events[type]=list[0]);void 0!==events.removeListener&&this.emit("removeListener",type,originalListener||listener)}return this};EventEmitter2.prototype.off=EventEmitter2.prototype.removeListener;EventEmitter2.prototype.removeAllListeners=function removeAllListeners(type){var listeners,i2,keys3,key3,events=this._events;if(void 0===events)return this;if(void 0===events.removeListener){if(0===arguments.length){this._events=Object.create(null);this._eventsCount=0}else void 0!==events[type]&&(0==--this._eventsCount?this._events=Object.create(null):delete events[type]);return this}if(0===arguments.length){keys3=Object.keys(events);for(i2=0;i2<keys3.length;++i2)"removeListener"!==(key3=keys3[i2])&&this.removeAllListeners(key3);this.removeAllListeners("removeListener");this._events=Object.create(null);this._eventsCount=0;return this}if("function"==typeof(listeners=events[type]))this.removeListener(type,listeners);else if(void 0!==listeners)for(i2=listeners.length-1;i2>=0;i2--)this.removeListener(type,listeners[i2]);return this};EventEmitter2.prototype.listeners=function listeners(type){return _listeners2(this,type,!0)};EventEmitter2.prototype.rawListeners=function rawListeners(type){return _listeners2(this,type,!1)};EventEmitter2.listenerCount=function(emitter,type){return"function"==typeof emitter.listenerCount?emitter.listenerCount(type):listenerCount2.call(emitter,type)};EventEmitter2.prototype.listenerCount=listenerCount2;EventEmitter2.prototype.eventNames=function eventNames(){return this._eventsCount>0?ReflectOwnKeys(this._events):[]}}}),require_spark_md5=__commonJS({"node_modules/spark-md5/spark-md5.js"(exports,module2){(function(factory){if("object"==typeof exports)module2.exports=factory();else if("function"==typeof define&&define.amd)define(factory);else{var glob;try{glob=window}catch(e3){glob=self}glob.SparkMD5=factory()}})((function(undefined2){"use strict";function md5cycle(x2,k2){var a2=x2[0],b3=x2[1],c3=x2[2],d4=x2[3];b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&c3|~b3&d4)+k2[0]-680876936|0)<<7|a2>>>25)+b3|0)&b3|~a2&c3)+k2[1]-389564586|0)<<12|d4>>>20)+a2|0)&a2|~d4&b3)+k2[2]+606105819|0)<<17|c3>>>15)+d4|0)&d4|~c3&a2)+k2[3]-1044525330|0)<<22|b3>>>10)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&c3|~b3&d4)+k2[4]-176418897|0)<<7|a2>>>25)+b3|0)&b3|~a2&c3)+k2[5]+1200080426|0)<<12|d4>>>20)+a2|0)&a2|~d4&b3)+k2[6]-1473231341|0)<<17|c3>>>15)+d4|0)&d4|~c3&a2)+k2[7]-45705983|0)<<22|b3>>>10)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&c3|~b3&d4)+k2[8]+1770035416|0)<<7|a2>>>25)+b3|0)&b3|~a2&c3)+k2[9]-1958414417|0)<<12|d4>>>20)+a2|0)&a2|~d4&b3)+k2[10]-42063|0)<<17|c3>>>15)+d4|0)&d4|~c3&a2)+k2[11]-1990404162|0)<<22|b3>>>10)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&c3|~b3&d4)+k2[12]+1804603682|0)<<7|a2>>>25)+b3|0)&b3|~a2&c3)+k2[13]-40341101|0)<<12|d4>>>20)+a2|0)&a2|~d4&b3)+k2[14]-1502002290|0)<<17|c3>>>15)+d4|0)&d4|~c3&a2)+k2[15]+1236535329|0)<<22|b3>>>10)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&d4|c3&~d4)+k2[1]-165796510|0)<<5|a2>>>27)+b3|0)&c3|b3&~c3)+k2[6]-1069501632|0)<<9|d4>>>23)+a2|0)&b3|a2&~b3)+k2[11]+643717713|0)<<14|c3>>>18)+d4|0)&a2|d4&~a2)+k2[0]-373897302|0)<<20|b3>>>12)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&d4|c3&~d4)+k2[5]-701558691|0)<<5|a2>>>27)+b3|0)&c3|b3&~c3)+k2[10]+38016083|0)<<9|d4>>>23)+a2|0)&b3|a2&~b3)+k2[15]-660478335|0)<<14|c3>>>18)+d4|0)&a2|d4&~a2)+k2[4]-405537848|0)<<20|b3>>>12)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&d4|c3&~d4)+k2[9]+568446438|0)<<5|a2>>>27)+b3|0)&c3|b3&~c3)+k2[14]-1019803690|0)<<9|d4>>>23)+a2|0)&b3|a2&~b3)+k2[3]-187363961|0)<<14|c3>>>18)+d4|0)&a2|d4&~a2)+k2[8]+1163531501|0)<<20|b3>>>12)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3&d4|c3&~d4)+k2[13]-1444681467|0)<<5|a2>>>27)+b3|0)&c3|b3&~c3)+k2[2]-51403784|0)<<9|d4>>>23)+a2|0)&b3|a2&~b3)+k2[7]+1735328473|0)<<14|c3>>>18)+d4|0)&a2|d4&~a2)+k2[12]-1926607734|0)<<20|b3>>>12)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3^c3^d4)+k2[5]-378558|0)<<4|a2>>>28)+b3|0)^b3^c3)+k2[8]-2022574463|0)<<11|d4>>>21)+a2|0)^a2^b3)+k2[11]+1839030562|0)<<16|c3>>>16)+d4|0)^d4^a2)+k2[14]-35309556|0)<<23|b3>>>9)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3^c3^d4)+k2[1]-1530992060|0)<<4|a2>>>28)+b3|0)^b3^c3)+k2[4]+1272893353|0)<<11|d4>>>21)+a2|0)^a2^b3)+k2[7]-155497632|0)<<16|c3>>>16)+d4|0)^d4^a2)+k2[10]-1094730640|0)<<23|b3>>>9)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3^c3^d4)+k2[13]+681279174|0)<<4|a2>>>28)+b3|0)^b3^c3)+k2[0]-358537222|0)<<11|d4>>>21)+a2|0)^a2^b3)+k2[3]-722521979|0)<<16|c3>>>16)+d4|0)^d4^a2)+k2[6]+76029189|0)<<23|b3>>>9)+c3|0;b3=((b3+=((c3=((c3+=((d4=((d4+=((a2=((a2+=(b3^c3^d4)+k2[9]-640364487|0)<<4|a2>>>28)+b3|0)^b3^c3)+k2[12]-421815835|0)<<11|d4>>>21)+a2|0)^a2^b3)+k2[15]+530742520|0)<<16|c3>>>16)+d4|0)^d4^a2)+k2[2]-995338651|0)<<23|b3>>>9)+c3|0;b3=((b3+=((d4=((d4+=(b3^((a2=((a2+=(c3^(b3|~d4))+k2[0]-198630844|0)<<6|a2>>>26)+b3|0)|~c3))+k2[7]+1126891415|0)<<10|d4>>>22)+a2|0)^((c3=((c3+=(a2^(d4|~b3))+k2[14]-1416354905|0)<<15|c3>>>17)+d4|0)|~a2))+k2[5]-57434055|0)<<21|b3>>>11)+c3|0;b3=((b3+=((d4=((d4+=(b3^((a2=((a2+=(c3^(b3|~d4))+k2[12]+1700485571|0)<<6|a2>>>26)+b3|0)|~c3))+k2[3]-1894986606|0)<<10|d4>>>22)+a2|0)^((c3=((c3+=(a2^(d4|~b3))+k2[10]-1051523|0)<<15|c3>>>17)+d4|0)|~a2))+k2[1]-2054922799|0)<<21|b3>>>11)+c3|0;b3=((b3+=((d4=((d4+=(b3^((a2=((a2+=(c3^(b3|~d4))+k2[8]+1873313359|0)<<6|a2>>>26)+b3|0)|~c3))+k2[15]-30611744|0)<<10|d4>>>22)+a2|0)^((c3=((c3+=(a2^(d4|~b3))+k2[6]-1560198380|0)<<15|c3>>>17)+d4|0)|~a2))+k2[13]+1309151649|0)<<21|b3>>>11)+c3|0;b3=((b3+=((d4=((d4+=(b3^((a2=((a2+=(c3^(b3|~d4))+k2[4]-145523070|0)<<6|a2>>>26)+b3|0)|~c3))+k2[11]-1120210379|0)<<10|d4>>>22)+a2|0)^((c3=((c3+=(a2^(d4|~b3))+k2[2]+718787259|0)<<15|c3>>>17)+d4|0)|~a2))+k2[9]-343485551|0)<<21|b3>>>11)+c3|0;x2[0]=a2+x2[0]|0;x2[1]=b3+x2[1]|0;x2[2]=c3+x2[2]|0;x2[3]=d4+x2[3]|0}function md5blk(s2){var i2,md5blks=[];for(i2=0;i2<64;i2+=4)md5blks[i2>>2]=s2.charCodeAt(i2)+(s2.charCodeAt(i2+1)<<8)+(s2.charCodeAt(i2+2)<<16)+(s2.charCodeAt(i2+3)<<24);return md5blks}function md5blk_array(a2){var i2,md5blks=[];for(i2=0;i2<64;i2+=4)md5blks[i2>>2]=a2[i2]+(a2[i2+1]<<8)+(a2[i2+2]<<16)+(a2[i2+3]<<24);return md5blks}function md51(s2){var i2,length,tail,tmp,lo,hi,n3=s2.length,state2=[1732584193,-271733879,-1732584194,271733878];for(i2=64;i2<=n3;i2+=64)md5cycle(state2,md5blk(s2.substring(i2-64,i2)));length=(s2=s2.substring(i2-64)).length;tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i2=0;i2<length;i2+=1)tail[i2>>2]|=s2.charCodeAt(i2)<<(i2%4<<3);tail[i2>>2]|=128<<(i2%4<<3);if(i2>55){md5cycle(state2,tail);for(i2=0;i2<16;i2+=1)tail[i2]=0}tmp=(tmp=8*n3).toString(16).match(/(.*?)(.{0,8})$/);lo=parseInt(tmp[2],16);hi=parseInt(tmp[1],16)||0;tail[14]=lo;tail[15]=hi;md5cycle(state2,tail);return state2}function md51_array(a2){var i2,length,tail,tmp,lo,hi,n3=a2.length,state2=[1732584193,-271733879,-1732584194,271733878];for(i2=64;i2<=n3;i2+=64)md5cycle(state2,md5blk_array(a2.subarray(i2-64,i2)));length=(a2=i2-64<n3?a2.subarray(i2-64):new Uint8Array(0)).length;tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i2=0;i2<length;i2+=1)tail[i2>>2]|=a2[i2]<<(i2%4<<3);tail[i2>>2]|=128<<(i2%4<<3);if(i2>55){md5cycle(state2,tail);for(i2=0;i2<16;i2+=1)tail[i2]=0}tmp=(tmp=8*n3).toString(16).match(/(.*?)(.{0,8})$/);lo=parseInt(tmp[2],16);hi=parseInt(tmp[1],16)||0;tail[14]=lo;tail[15]=hi;md5cycle(state2,tail);return state2}function rhex(n3){var j2,s2="";for(j2=0;j2<4;j2+=1)s2+=hex_chr[n3>>8*j2+4&15]+hex_chr[n3>>8*j2&15];return s2}function hex(x2){var i2;for(i2=0;i2<x2.length;i2+=1)x2[i2]=rhex(x2[i2]);return x2.join("")}function toUtf82(str){/[\u0080-\uFFFF]/.test(str)&&(str=unescape(encodeURIComponent(str)));return str}function utf8Str2ArrayBuffer(str,returnUInt8Array){var i2,length=str.length,buff=new ArrayBuffer(length),arr=new Uint8Array(buff);for(i2=0;i2<length;i2+=1)arr[i2]=str.charCodeAt(i2);return returnUInt8Array?arr:buff}function arrayBuffer2Utf8Str(buff){return String.fromCharCode.apply(null,new Uint8Array(buff))}function concatenateArrayBuffers(first,second,returnUInt8Array){var result=new Uint8Array(first.byteLength+second.byteLength);result.set(new Uint8Array(first));result.set(new Uint8Array(second),first.byteLength);return returnUInt8Array?result:result.buffer}function hexToBinaryString(hex2){var x2,bytes=[],length=hex2.length;for(x2=0;x2<length-1;x2+=2)bytes.push(parseInt(hex2.substr(x2,2),16));return String.fromCharCode.apply(String,bytes)}function SparkMD5(){this.reset()}var hex_chr=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f"];hex(md51("hello"));"undefined"==typeof ArrayBuffer||ArrayBuffer.prototype.slice||function(){function clamp(val2,length){return(val2=0|val2||0)<0?Math.max(val2+length,0):Math.min(val2,length)}ArrayBuffer.prototype.slice=function(from,to){var num,target,targetArray,sourceArray,length=this.byteLength,begin=clamp(from,length),end=length;to!==undefined2&&(end=clamp(to,length));if(begin>end)return new ArrayBuffer(0);num=end-begin;target=new ArrayBuffer(num);targetArray=new Uint8Array(target);sourceArray=new Uint8Array(this,begin,num);targetArray.set(sourceArray);return target}}();SparkMD5.prototype.append=function(str){this.appendBinary(toUtf82(str));return this};SparkMD5.prototype.appendBinary=function(contents){this._buff+=contents;this._length+=contents.length;var i2,length=this._buff.length;for(i2=64;i2<=length;i2+=64)md5cycle(this._hash,md5blk(this._buff.substring(i2-64,i2)));this._buff=this._buff.substring(i2-64);return this};SparkMD5.prototype.end=function(raw){var i2,ret,buff=this._buff,length=buff.length,tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i2=0;i2<length;i2+=1)tail[i2>>2]|=buff.charCodeAt(i2)<<(i2%4<<3);this._finish(tail,length);ret=hex(this._hash);raw&&(ret=hexToBinaryString(ret));this.reset();return ret};SparkMD5.prototype.reset=function(){this._buff="";this._length=0;this._hash=[1732584193,-271733879,-1732584194,271733878];return this};SparkMD5.prototype.getState=function(){return{buff:this._buff,length:this._length,hash:this._hash.slice()}};SparkMD5.prototype.setState=function(state2){this._buff=state2.buff;this._length=state2.length;this._hash=state2.hash;return this};SparkMD5.prototype.destroy=function(){delete this._hash;delete this._buff;delete this._length};SparkMD5.prototype._finish=function(tail,length){var tmp,lo,hi,i2=length;tail[i2>>2]|=128<<(i2%4<<3);if(i2>55){md5cycle(this._hash,tail);for(i2=0;i2<16;i2+=1)tail[i2]=0}tmp=(tmp=8*this._length).toString(16).match(/(.*?)(.{0,8})$/);lo=parseInt(tmp[2],16);hi=parseInt(tmp[1],16)||0;tail[14]=lo;tail[15]=hi;md5cycle(this._hash,tail)};SparkMD5.hash=function(str,raw){return SparkMD5.hashBinary(toUtf82(str),raw)};SparkMD5.hashBinary=function(content,raw){var ret=hex(md51(content));return raw?hexToBinaryString(ret):ret};SparkMD5.ArrayBuffer=function(){this.reset()};SparkMD5.ArrayBuffer.prototype.append=function(arr){var i2,buff=concatenateArrayBuffers(this._buff.buffer,arr,!0),length=buff.length;this._length+=arr.byteLength;for(i2=64;i2<=length;i2+=64)md5cycle(this._hash,md5blk_array(buff.subarray(i2-64,i2)));this._buff=i2-64<length?new Uint8Array(buff.buffer.slice(i2-64)):new Uint8Array(0);return this};SparkMD5.ArrayBuffer.prototype.end=function(raw){var i2,ret,buff=this._buff,length=buff.length,tail=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(i2=0;i2<length;i2+=1)tail[i2>>2]|=buff[i2]<<(i2%4<<3);this._finish(tail,length);ret=hex(this._hash);raw&&(ret=hexToBinaryString(ret));this.reset();return ret};SparkMD5.ArrayBuffer.prototype.reset=function(){this._buff=new Uint8Array(0);this._length=0;this._hash=[1732584193,-271733879,-1732584194,271733878];return this};SparkMD5.ArrayBuffer.prototype.getState=function(){var state2=SparkMD5.prototype.getState.call(this);state2.buff=arrayBuffer2Utf8Str(state2.buff);return state2};SparkMD5.ArrayBuffer.prototype.setState=function(state2){state2.buff=utf8Str2ArrayBuffer(state2.buff,!0);return SparkMD5.prototype.setState.call(this,state2)};SparkMD5.ArrayBuffer.prototype.destroy=SparkMD5.prototype.destroy;SparkMD5.ArrayBuffer.prototype._finish=SparkMD5.prototype._finish;SparkMD5.ArrayBuffer.hash=function(arr,raw){var ret=hex(md51_array(new Uint8Array(arr)));return raw?hexToBinaryString(ret):ret};return SparkMD5}))}}),require_vuvuzela=__commonJS({"node_modules/vuvuzela/index.js"(exports){"use strict";function pop3(obj,stack2,metaStack){var element2,lastElementIndex,lastMetaElement=metaStack[metaStack.length-1];if(obj===lastMetaElement.element){metaStack.pop();lastMetaElement=metaStack[metaStack.length-1]}element2=lastMetaElement.element;lastElementIndex=lastMetaElement.index;Array.isArray(element2)?element2.push(obj):lastElementIndex===stack2.length-2?element2[stack2.pop()]=obj:stack2.push(obj)}exports.stringify=function stringify4(input){var res2,next2,obj,val2,i2,arrayPrefix,keys3,k2,key3,value,objPrefix,queue2=[];queue2.push({obj:input});res2="";for(;next2=queue2.pop();){obj=next2.obj;res2+=next2.prefix||"";if(val2=next2.val||"")res2+=val2;else if("object"!=typeof obj)res2+=void 0===obj?null:JSON.stringify(obj);else if(null===obj)res2+="null";else if(Array.isArray(obj)){queue2.push({val:"]"});for(i2=obj.length-1;i2>=0;i2--){arrayPrefix=0===i2?"":",";queue2.push({obj:obj[i2],prefix:arrayPrefix})}queue2.push({val:"["})}else{keys3=[];for(k2 in obj)obj.hasOwnProperty(k2)&&keys3.push(k2);queue2.push({val:"}"});for(i2=keys3.length-1;i2>=0;i2--){value=obj[key3=keys3[i2]];objPrefix=i2>0?",":"";objPrefix+=JSON.stringify(key3)+":";queue2.push({obj:value,prefix:objPrefix})}queue2.push({val:"{"})}}return res2};exports.parse=function(str){for(var collationIndex2,parsedNum,numChar,parsedString,lastCh,numConsecutiveSlashes,ch4,arrayElement,objElement,stack2=[],metaStack=[],i2=0;;)if("}"!==(collationIndex2=str[i2++])&&"]"!==collationIndex2&&void 0!==collationIndex2)switch(collationIndex2){case" ":case"\t":case"\n":case":":case",":break;case"n":i2+=3;pop3(null,stack2,metaStack);break;case"t":i2+=3;pop3(!0,stack2,metaStack);break;case"f":i2+=4;pop3(!1,stack2,metaStack);break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":case"8":case"9":case"-":parsedNum="";i2--;for(;;){numChar=str[i2++];if(!/[\d\.\-e\+]/.test(numChar)){i2--;break}parsedNum+=numChar}pop3(parseFloat(parsedNum),stack2,metaStack);break;case'"':parsedString="";lastCh=void 0;numConsecutiveSlashes=0;for(;'"'!==(ch4=str[i2++])||"\\"===lastCh&&numConsecutiveSlashes%2==1;){parsedString+=ch4;"\\"===(lastCh=ch4)?numConsecutiveSlashes++:numConsecutiveSlashes=0}pop3(JSON.parse('"'+parsedString+'"'),stack2,metaStack);break;case"[":arrayElement={element:[],index:stack2.length};stack2.push(arrayElement.element);metaStack.push(arrayElement);break;case"{":objElement={element:{},index:stack2.length};stack2.push(objElement.element);metaStack.push(objElement);break;default:throw new Error("unexpectedly reached end of input: "+collationIndex2)}else{if(1===stack2.length)return stack2.pop();pop3(stack2.pop(),stack2,metaStack)}}}}),require_pouchdb_wrappers=__commonJS({"node_modules/pouchdb-wrappers/index.js"(exports,module2){"use strict";function nodify(promise,callback){promise.then(((...args)=>{callback(null,...args)})).catch((err3=>{callback(err3)}))}function replacementMethod(base,method){return function(...args){function doMethod(){let callback=null;const minArgs="query"===method?1:0;args.length>minArgs&&"function"==typeof args[args.length-1]&&(callback=args.pop());let prev=base._originals[method].bind(base);for(const handler of base._handlers[method])prev=handler.bind(base,prev);const result=prev(...args);result.then&&callback&&nodify(result,callback);return result}return"changes"!==method&&base.taskqueue&&!base.taskqueue.isReady?new Promise(((resolve,reject)=>{base.taskqueue.addTask((error=>{error?reject(error):resolve()}))})).then(doMethod):doMethod()}}var toExport={install:function installWrappers(base,handlers2={}){if(!base._originals||!base._handlers){base._originals={};base._handlers={}}for(const[method,handler]of Object.entries(handlers2)){if(!(method in base))throw new Error(`Method '${method}' does not exist on given base, so it cannot be wrapped.`);method in base._originals||(base._originals[method]=base[method]);if(method in base._handlers)base._handlers[method].unshift(handler);else{base._handlers[method]=[handler];base[method]=replacementMethod(base,method)}}},uninstall:function uninstallWrappers(base,handlers2){if(!base._originals||!base._handlers)throw new Error("No wrapper methods installed, so no methods can be uninstalled.");for(const[method,handler]of Object.entries(handlers2)){const errorMessage=`Wrapper method for '${method}' not installed: ${handler.toString()}`;if(!(method in base._handlers))throw new Error(errorMessage);const i2=base._handlers[method].indexOf(handler);if(-1===i2)throw new Error(errorMessage);base._handlers[method].splice(i2,1)}}};try{module2.exports=toExport}catch(e3){}try{window.PouchDBWrappers=toExport}catch(e3){}}}),require_transform_pouch=__commonJS({"node_modules/transform-pouch/index.js"(exports,module2){"use strict";function isntInternalKey(key3){return"_"!==key3[0]}function isUntransformable(doc){return!("string"!=typeof doc._id||!/^_local/.test(doc._id))||!!doc._deleted&&0===Object.keys(doc).filter(isntInternalKey).length}function transform2(config){const incoming=function(doc){return!isUntransformable(doc)&&config.incoming?config.incoming(doc):doc},outgoing=function(doc){return!isUntransformable(doc)&&config.outgoing?config.outgoing(doc):doc},handlers2={async get(orig,...args){const response=await orig(...args);if(Array.isArray(response)){await Promise.all(response.map((async row=>{row.ok&&(row.ok=await outgoing(row.ok))})));return response}return outgoing(response)},async bulkDocs(orig,docs,...args){docs.docs?docs.docs=await Promise.all(docs.docs.map(incoming)):docs=await Promise.all(docs.map(incoming));return orig(docs,...args)},async allDocs(orig,...args){const response=await orig(...args);await Promise.all(response.rows.map((async row=>{row.doc&&(row.doc=await outgoing(row.doc))})));return response},async bulkGet(orig,...args){const mapDoc=async doc=>doc.ok?{ok:await outgoing(doc.ok)}:doc;let{results,...res2}=await orig(...args);results=await Promise.all(results.map((async result=>{const{id,docs}=result;return id&&docs&&Array.isArray(docs)?{id,docs:await Promise.all(docs.map(mapDoc))}:result})));return{results,...res2}},changes(orig,...args){async function modifyChange(change){if(change.doc){change.doc=await outgoing(change.doc);return change}return change}async function modifyChanges(res2){if(res2.results){res2.results=await Promise.all(res2.results.map(modifyChange));return res2}return res2}const changes3=orig(...args),{on:origOn,then:origThen}=changes3;return Object.assign(changes3,{on(event2,listener){const origListener=listener;"change"===event2?listener=async change=>{origListener(await modifyChange(change))}:"complete"===event2&&(listener=async res2=>{origListener(await modifyChanges(res2))});return origOn.call(changes3,event2,listener)},then:(resolve,reject)=>origThen.call(changes3,modifyChanges).then(resolve,reject)})}};if("http"===this.type()){handlers2.put=async function(orig,doc,...args){return orig(doc=await incoming(doc),...args)};handlers2.query=async function(orig,...args){const response=await orig(...args);await Promise.all(response.rows.map((async row=>{row.doc&&(row.doc=await outgoing(row.doc))})));return response}}wrappers.install(this,handlers2)}var wrappers=require_pouchdb_wrappers();module2.exports={transform:transform2,filter:transform2};"undefined"!=typeof window&&window.PouchDB&&window.PouchDB.plugin(exports)}}),require_qrcode=__commonJS({"node_modules/qrcode-generator/qrcode.js"(exports,module2){var qrcode2=function(){function qrPolynomial(num,shift){var _num,_this;if(void 0===num.length)throw num.length+"/"+shift;_num=function(){for(var _num2,i2,offset=0;offset<num.length&&0==num[offset];)offset+=1;_num2=new Array(num.length-offset+shift);for(i2=0;i2<num.length-offset;i2+=1)_num2[i2]=num[i2+offset];return _num2}();(_this={}).getAt=function(index6){return _num[index6]};_this.getLength=function(){return _num.length};_this.multiply=function(e3){var i2,j2,num2=new Array(_this.getLength()+e3.getLength()-1);for(i2=0;i2<_this.getLength();i2+=1)for(j2=0;j2<e3.getLength();j2+=1)num2[i2+j2]^=QRMath.gexp(QRMath.glog(_this.getAt(i2))+QRMath.glog(e3.getAt(j2)));return qrPolynomial(num2,0)};_this.mod=function(e3){var ratio,num2,i2;if(_this.getLength()-e3.getLength()<0)return _this;ratio=QRMath.glog(_this.getAt(0))-QRMath.glog(e3.getAt(0));num2=new Array(_this.getLength());for(i2=0;i2<_this.getLength();i2+=1)num2[i2]=_this.getAt(i2);for(i2=0;i2<e3.getLength();i2+=1)num2[i2]^=QRMath.gexp(QRMath.glog(e3.getAt(i2))+ratio);return qrPolynomial(num2,0).mod(e3)};return _this}var QRErrorCorrectionLevel,QRUtil,QRMath,QRRSBlock,qrBitBuffer,qrNumber,qrAlphaNum,qr8BitByte,qrKanji,byteArrayOutputStream,base64EncodeOutputStream,base64DecodeInputStream,gifImage,createDataURL,qrcode3=function(typeNumber,errorCorrectionLevel){var escapeXml,_createHalfASCII,_typeNumber=typeNumber,_errorCorrectionLevel=QRErrorCorrectionLevel[errorCorrectionLevel],_modules=null,_moduleCount=0,_dataCache=null,_dataList=[],_this={},makeImpl=function(test,maskPattern){_modules=function(moduleCount){var row,col,modules=new Array(moduleCount);for(row=0;row<moduleCount;row+=1){modules[row]=new Array(moduleCount);for(col=0;col<moduleCount;col+=1)modules[row][col]=null}return modules}(_moduleCount=4*_typeNumber+17);setupPositionProbePattern(0,0);setupPositionProbePattern(_moduleCount-7,0);setupPositionProbePattern(0,_moduleCount-7);setupPositionAdjustPattern();setupTimingPattern();setupTypeInfo(test,maskPattern);_typeNumber>=7&&setupTypeNumber(test);null==_dataCache&&(_dataCache=createData(_typeNumber,_errorCorrectionLevel,_dataList));mapData(_dataCache,maskPattern)},setupPositionProbePattern=function(row,col){var r4,c3;for(r4=-1;r4<=7;r4+=1)if(!(row+r4<=-1||_moduleCount<=row+r4))for(c3=-1;c3<=7;c3+=1)col+c3<=-1||_moduleCount<=col+c3||(_modules[row+r4][col+c3]=0<=r4&&r4<=6&&(0==c3||6==c3)||0<=c3&&c3<=6&&(0==r4||6==r4)||2<=r4&&r4<=4&&2<=c3&&c3<=4)},getBestMaskPattern=function(){var i2,lostPoint,minLostPoint=0,pattern=0;for(i2=0;i2<8;i2+=1){makeImpl(!0,i2);lostPoint=QRUtil.getLostPoint(_this);if(0==i2||minLostPoint>lostPoint){minLostPoint=lostPoint;pattern=i2}}return pattern},setupTimingPattern=function(){var r4,c3;for(r4=8;r4<_moduleCount-8;r4+=1)null==_modules[r4][6]&&(_modules[r4][6]=r4%2==0);for(c3=8;c3<_moduleCount-8;c3+=1)null==_modules[6][c3]&&(_modules[6][c3]=c3%2==0)},setupPositionAdjustPattern=function(){var i2,j2,row,col,r4,c3,pos=QRUtil.getPatternPosition(_typeNumber);for(i2=0;i2<pos.length;i2+=1)for(j2=0;j2<pos.length;j2+=1){row=pos[i2];col=pos[j2];if(null==_modules[row][col])for(r4=-2;r4<=2;r4+=1)for(c3=-2;c3<=2;c3+=1)_modules[row+r4][col+c3]=-2==r4||2==r4||-2==c3||2==c3||0==r4&&0==c3}},setupTypeNumber=function(test){var i2,mod,bits2=QRUtil.getBCHTypeNumber(_typeNumber);for(i2=0;i2<18;i2+=1){mod=!test&&1==(bits2>>i2&1);_modules[Math.floor(i2/3)][i2%3+_moduleCount-8-3]=mod}for(i2=0;i2<18;i2+=1){mod=!test&&1==(bits2>>i2&1);_modules[i2%3+_moduleCount-8-3][Math.floor(i2/3)]=mod}},setupTypeInfo=function(test,maskPattern){var i2,mod,data=_errorCorrectionLevel<<3|maskPattern,bits2=QRUtil.getBCHTypeInfo(data);for(i2=0;i2<15;i2+=1){mod=!test&&1==(bits2>>i2&1);i2<6?_modules[i2][8]=mod:i2<8?_modules[i2+1][8]=mod:_modules[_moduleCount-15+i2][8]=mod}for(i2=0;i2<15;i2+=1){mod=!test&&1==(bits2>>i2&1);i2<8?_modules[8][_moduleCount-i2-1]=mod:i2<9?_modules[8][15-i2-1+1]=mod:_modules[8][15-i2-1]=mod}_modules[_moduleCount-8][8]=!test},mapData=function(data,maskPattern){var col,c3,dark,inc=-1,row=_moduleCount-1,bitIndex=7,byteIndex=0,maskFunc=QRUtil.getMaskFunction(maskPattern);for(col=_moduleCount-1;col>0;col-=2){6==col&&(col-=1);for(;;){for(c3=0;c3<2;c3+=1)if(null==_modules[row][col-c3]){dark=!1;byteIndex<data.length&&(dark=1==(data[byteIndex]>>>bitIndex&1));maskFunc(row,col-c3)&&(dark=!dark);_modules[row][col-c3]=dark;if(-1==(bitIndex-=1)){byteIndex+=1;bitIndex=7}}if((row+=inc)<0||_moduleCount<=row){row-=inc;inc=-inc;break}}}},createBytes=function(buffer,rsBlocks){var r4,dcCount,ecCount,i2,rsPoly,modPoly,modIndex,totalCodeCount,data,index6,offset=0,maxDcCount=0,maxEcCount=0,dcdata=new Array(rsBlocks.length),ecdata=new Array(rsBlocks.length);for(r4=0;r4<rsBlocks.length;r4+=1){dcCount=rsBlocks[r4].dataCount;ecCount=rsBlocks[r4].totalCount-dcCount;maxDcCount=Math.max(maxDcCount,dcCount);maxEcCount=Math.max(maxEcCount,ecCount);dcdata[r4]=new Array(dcCount);for(i2=0;i2<dcdata[r4].length;i2+=1)dcdata[r4][i2]=255&buffer.getBuffer()[i2+offset];offset+=dcCount;rsPoly=QRUtil.getErrorCorrectPolynomial(ecCount);modPoly=qrPolynomial(dcdata[r4],rsPoly.getLength()-1).mod(rsPoly);ecdata[r4]=new Array(rsPoly.getLength()-1);for(i2=0;i2<ecdata[r4].length;i2+=1){modIndex=i2+modPoly.getLength()-ecdata[r4].length;ecdata[r4][i2]=modIndex>=0?modPoly.getAt(modIndex):0}}totalCodeCount=0;for(i2=0;i2<rsBlocks.length;i2+=1)totalCodeCount+=rsBlocks[i2].totalCount;data=new Array(totalCodeCount);index6=0;for(i2=0;i2<maxDcCount;i2+=1)for(r4=0;r4<rsBlocks.length;r4+=1)if(i2<dcdata[r4].length){data[index6]=dcdata[r4][i2];index6+=1}for(i2=0;i2<maxEcCount;i2+=1)for(r4=0;r4<rsBlocks.length;r4+=1)if(i2<ecdata[r4].length){data[index6]=ecdata[r4][i2];index6+=1}return data},createData=function(typeNumber2,errorCorrectionLevel2,dataList){var i2,data,totalDataCount,rsBlocks=QRRSBlock.getRSBlocks(typeNumber2,errorCorrectionLevel2),buffer=qrBitBuffer();for(i2=0;i2<dataList.length;i2+=1){data=dataList[i2];buffer.put(data.getMode(),4);buffer.put(data.getLength(),QRUtil.getLengthInBits(data.getMode(),typeNumber2));data.write(buffer)}totalDataCount=0;for(i2=0;i2<rsBlocks.length;i2+=1)totalDataCount+=rsBlocks[i2].dataCount;if(buffer.getLengthInBits()>8*totalDataCount)throw"code length overflow. ("+buffer.getLengthInBits()+">"+8*totalDataCount+")";buffer.getLengthInBits()+4<=8*totalDataCount&&buffer.put(0,4);for(;buffer.getLengthInBits()%8!=0;)buffer.putBit(!1);for(;!(buffer.getLengthInBits()>=8*totalDataCount);){buffer.put(236,8);if(buffer.getLengthInBits()>=8*totalDataCount)break;buffer.put(17,8)}return createBytes(buffer,rsBlocks)};_this.addData=function(data,mode){var newData=null;switch(mode=mode||"Byte"){case"Numeric":newData=qrNumber(data);break;case"Alphanumeric":newData=qrAlphaNum(data);break;case"Byte":newData=qr8BitByte(data);break;case"Kanji":newData=qrKanji(data);break;default:throw"mode:"+mode}_dataList.push(newData);_dataCache=null};_this.isDark=function(row,col){if(row<0||_moduleCount<=row||col<0||_moduleCount<=col)throw row+","+col;return _modules[row][col]};_this.getModuleCount=function(){return _moduleCount};_this.make=function(){var typeNumber2,rsBlocks,buffer,i2,data,totalDataCount;if(_typeNumber<1){typeNumber2=1;for(;typeNumber2<40;typeNumber2++){rsBlocks=QRRSBlock.getRSBlocks(typeNumber2,_errorCorrectionLevel);buffer=qrBitBuffer();for(i2=0;i2<_dataList.length;i2++){data=_dataList[i2];buffer.put(data.getMode(),4);buffer.put(data.getLength(),QRUtil.getLengthInBits(data.getMode(),typeNumber2));data.write(buffer)}totalDataCount=0;for(i2=0;i2<rsBlocks.length;i2++)totalDataCount+=rsBlocks[i2].dataCount;if(buffer.getLengthInBits()<=8*totalDataCount)break}_typeNumber=typeNumber2}makeImpl(!1,getBestMaskPattern())};_this.createTableTag=function(cellSize,margin){var qrHtml,r4,c3;cellSize=cellSize||2;qrHtml="";qrHtml+='<table style="';qrHtml+=" border-width: 0px; border-style: none;";qrHtml+=" border-collapse: collapse;";qrHtml+=" padding: 0px; margin: "+(margin=void 0===margin?4*cellSize:margin)+"px;";qrHtml+='">';qrHtml+="<tbody>";for(r4=0;r4<_this.getModuleCount();r4+=1){qrHtml+="<tr>";for(c3=0;c3<_this.getModuleCount();c3+=1){qrHtml+='<td style="';qrHtml+=" border-width: 0px; border-style: none;";qrHtml+=" border-collapse: collapse;";qrHtml+=" padding: 0px; margin: 0px;";qrHtml+=" width: "+cellSize+"px;";qrHtml+=" height: "+cellSize+"px;";qrHtml+=" background-color: ";qrHtml+=_this.isDark(r4,c3)?"#000000":"#ffffff";qrHtml+=";";qrHtml+='"/>'}qrHtml+="</tr>"}return(qrHtml+="</tbody>")+"</table>"};_this.createSvgTag=function(cellSize,margin,alt,title){var size,c3,r4,mr,qrSvg,rect,opts={};if("object"==typeof arguments[0]){cellSize=(opts=arguments[0]).cellSize;margin=opts.margin;alt=opts.alt;title=opts.title}cellSize=cellSize||2;margin=void 0===margin?4*cellSize:margin;(alt="string"==typeof alt?{text:alt}:alt||{}).text=alt.text||null;alt.id=alt.text?alt.id||"qrcode-description":null;(title="string"==typeof title?{text:title}:title||{}).text=title.text||null;title.id=title.text?title.id||"qrcode-title":null;size=_this.getModuleCount()*cellSize+2*margin;qrSvg="";rect="l"+cellSize+",0 0,"+cellSize+" -"+cellSize+",0 0,-"+cellSize+"z ";qrSvg+='<svg version="1.1" xmlns="http://www.w3.org/2000/svg"';qrSvg+=opts.scalable?"":' width="'+size+'px" height="'+size+'px"';qrSvg+=' viewBox="0 0 '+size+" "+size+'" ';qrSvg+=' preserveAspectRatio="xMinYMin meet"';qrSvg+=title.text||alt.text?' role="img" aria-labelledby="'+escapeXml([title.id,alt.id].join(" ").trim())+'"':"";qrSvg+=">";qrSvg+=title.text?'<title id="'+escapeXml(title.id)+'">'+escapeXml(title.text)+"</title>":"";qrSvg+=alt.text?'<description id="'+escapeXml(alt.id)+'">'+escapeXml(alt.text)+"</description>":"";qrSvg+='<rect width="100%" height="100%" fill="white" cx="0" cy="0"/>';qrSvg+='<path d="';for(r4=0;r4<_this.getModuleCount();r4+=1){mr=r4*cellSize+margin;for(c3=0;c3<_this.getModuleCount();c3+=1)_this.isDark(r4,c3)&&(qrSvg+="M"+(c3*cellSize+margin)+","+mr+rect)}return(qrSvg+='" stroke="transparent" fill="black"/>')+"</svg>"};_this.createDataURL=function(cellSize,margin){var size,min,max3;cellSize=cellSize||2;margin=void 0===margin?4*cellSize:margin;size=_this.getModuleCount()*cellSize+2*margin;min=margin;max3=size-margin;return createDataURL(size,size,(function(x2,y2){var c3,r4;if(min<=x2&&x2<max3&&min<=y2&&y2<max3){c3=Math.floor((x2-min)/cellSize);r4=Math.floor((y2-min)/cellSize);return _this.isDark(r4,c3)?0:1}return 1}))};_this.createImgTag=function(cellSize,margin,alt){var size,img;cellSize=cellSize||2;margin=void 0===margin?4*cellSize:margin;size=_this.getModuleCount()*cellSize+2*margin;img="";img+="<img";img+=' src="';img+=_this.createDataURL(cellSize,margin);img+='"';img+=' width="';img+=size;img+='"';img+=' height="';img+=size;img+='"';if(alt){img+=' alt="';img+=escapeXml(alt);img+='"'}return img+"/>"};escapeXml=function(s2){var i2,c3,escaped="";for(i2=0;i2<s2.length;i2+=1)switch(c3=s2.charAt(i2)){case"<":escaped+="&lt;";break;case">":escaped+="&gt;";break;case"&":escaped+="&amp;";break;case'"':escaped+="&quot;";break;default:escaped+=c3;break}return escaped};_createHalfASCII=function(margin){var size,min,max3,y2,x2,r12,r22,p4,blocks,blocksLastLineNoMargin,ascii;min=margin=void 0===margin?2:margin;max3=(size=1*_this.getModuleCount()+2*margin)-margin;blocks={"██":"█","█ ":"▀"," █":"▄"," ":" "};blocksLastLineNoMargin={"██":"▀","█ ":"▀"," █":" "," ":" "};ascii="";for(y2=0;y2<size;y2+=2){r12=Math.floor((y2-min)/1);r22=Math.floor((y2+1-min)/1);for(x2=0;x2<size;x2+=1){p4="█";min<=x2&&x2<max3&&min<=y2&&y2<max3&&_this.isDark(r12,Math.floor((x2-min)/1))&&(p4=" ");min<=x2&&x2<max3&&min<=y2+1&&y2+1<max3&&_this.isDark(r22,Math.floor((x2-min)/1))?p4+=" ":p4+="█";ascii+=margin<1&&y2+1>=max3?blocksLastLineNoMargin[p4]:blocks[p4]}ascii+="\n"}return size%2&&margin>0?ascii.substring(0,ascii.length-size-1)+Array(size+1).join("▀"):ascii.substring(0,ascii.length-1)};_this.createASCII=function(cellSize,margin){var size,min,max3,y2,x2,r4,p4,white,black,ascii,line;if((cellSize=cellSize||1)<2)return _createHalfASCII(margin);cellSize-=1;min=margin=void 0===margin?2*cellSize:margin;max3=(size=_this.getModuleCount()*cellSize+2*margin)-margin;white=Array(cellSize+1).join("██");black=Array(cellSize+1).join(" ");ascii="";line="";for(y2=0;y2<size;y2+=1){r4=Math.floor((y2-min)/cellSize);line="";for(x2=0;x2<size;x2+=1){p4=1;min<=x2&&x2<max3&&min<=y2&&y2<max3&&_this.isDark(r4,Math.floor((x2-min)/cellSize))&&(p4=0);line+=p4?white:black}for(r4=0;r4<cellSize;r4+=1)ascii+=line+"\n"}return ascii.substring(0,ascii.length-1)};_this.renderTo2dContext=function(context2,cellSize){var length,row,col;cellSize=cellSize||2;length=_this.getModuleCount();for(row=0;row<length;row++)for(col=0;col<length;col++){context2.fillStyle=_this.isDark(row,col)?"black":"white";context2.fillRect(row*cellSize,col*cellSize,cellSize,cellSize)}};return _this};qrcode3.stringToBytesFuncs={default:function(s2){var i2,c3,bytes=[];for(i2=0;i2<s2.length;i2+=1){c3=s2.charCodeAt(i2);bytes.push(255&c3)}return bytes}};qrcode3.stringToBytes=qrcode3.stringToBytesFuncs.default;qrcode3.createStringToBytes=function(unicodeData,numChars){var unicodeMap=function(){for(var b0,b1,v2,bin=base64DecodeInputStream(unicodeData),read=function(){var b5=bin.read();if(-1==b5)throw"eof";return b5},count=0,unicodeMap2={};-1!=(b0=bin.read());){b1=read();v2=read()<<8|read();unicodeMap2[String.fromCharCode(b0<<8|b1)]=v2;count+=1}if(count!=numChars)throw count+" != "+numChars;return unicodeMap2}(),unknownChar="?".charCodeAt(0);return function(s2){var i2,c3,b3,bytes=[];for(i2=0;i2<s2.length;i2+=1)if((c3=s2.charCodeAt(i2))<128)bytes.push(c3);else if("number"==typeof(b3=unicodeMap[s2.charAt(i2)]))if((255&b3)==b3)bytes.push(b3);else{bytes.push(b3>>>8);bytes.push(255&b3)}else bytes.push(unknownChar);return bytes}};QRErrorCorrectionLevel={L:1,M:0,Q:3,H:2};QRUtil=function(){var PATTERN_POSITION_TABLE=[[],[6,18],[6,22],[6,26],[6,30],[6,34],[6,22,38],[6,24,42],[6,26,46],[6,28,50],[6,30,54],[6,32,58],[6,34,62],[6,26,46,66],[6,26,48,70],[6,26,50,74],[6,30,54,78],[6,30,56,82],[6,30,58,86],[6,34,62,90],[6,28,50,72,94],[6,26,50,74,98],[6,30,54,78,102],[6,28,54,80,106],[6,32,58,84,110],[6,30,58,86,114],[6,34,62,90,118],[6,26,50,74,98,122],[6,30,54,78,102,126],[6,26,52,78,104,130],[6,30,56,82,108,134],[6,34,60,86,112,138],[6,30,58,86,114,142],[6,34,62,90,118,146],[6,30,54,78,102,126,150],[6,24,50,76,102,128,154],[6,28,54,80,106,132,158],[6,32,58,84,110,136,162],[6,26,54,82,110,138,166],[6,30,58,86,114,142,170]],_this={},getBCHDigit=function(data){for(var digit=0;0!=data;){digit+=1;data>>>=1}return digit};_this.getBCHTypeInfo=function(data){for(var d4=data<<10;getBCHDigit(d4)-getBCHDigit(1335)>=0;)d4^=1335<<getBCHDigit(d4)-getBCHDigit(1335);return 21522^(data<<10|d4)};_this.getBCHTypeNumber=function(data){for(var d4=data<<12;getBCHDigit(d4)-getBCHDigit(7973)>=0;)d4^=7973<<getBCHDigit(d4)-getBCHDigit(7973);return data<<12|d4};_this.getPatternPosition=function(typeNumber){return PATTERN_POSITION_TABLE[typeNumber-1]};_this.getMaskFunction=function(maskPattern){switch(maskPattern){case 0:return function(i2,j2){return(i2+j2)%2==0};case 1:return function(i2,j2){return i2%2==0};case 2:return function(i2,j2){return j2%3==0};case 3:return function(i2,j2){return(i2+j2)%3==0};case 4:return function(i2,j2){return(Math.floor(i2/2)+Math.floor(j2/3))%2==0};case 5:return function(i2,j2){return i2*j2%2+i2*j2%3==0};case 6:return function(i2,j2){return(i2*j2%2+i2*j2%3)%2==0};case 7:return function(i2,j2){return(i2*j2%3+(i2+j2)%2)%2==0};default:throw"bad maskPattern:"+maskPattern}};_this.getErrorCorrectPolynomial=function(errorCorrectLength){var i2,a2=qrPolynomial([1],0);for(i2=0;i2<errorCorrectLength;i2+=1)a2=a2.multiply(qrPolynomial([1,QRMath.gexp(i2)],0));return a2};_this.getLengthInBits=function(mode,type){if(1<=type&&type<10)switch(mode){case 1:return 10;case 2:return 9;case 4:return 8;case 8:return 8;default:throw"mode:"+mode}else if(type<27)switch(mode){case 1:return 12;case 2:return 11;case 4:return 16;case 8:return 10;default:throw"mode:"+mode}else{if(!(type<41))throw"type:"+type;switch(mode){case 1:return 14;case 2:return 13;case 4:return 16;case 8:return 12;default:throw"mode:"+mode}}};_this.getLostPoint=function(qrcode4){var row,col,sameCount,dark,r4,c3,count,darkCount,moduleCount=qrcode4.getModuleCount(),lostPoint=0;for(row=0;row<moduleCount;row+=1)for(col=0;col<moduleCount;col+=1){sameCount=0;dark=qrcode4.isDark(row,col);for(r4=-1;r4<=1;r4+=1)if(!(row+r4<0||moduleCount<=row+r4))for(c3=-1;c3<=1;c3+=1)col+c3<0||moduleCount<=col+c3||0==r4&&0==c3||dark==qrcode4.isDark(row+r4,col+c3)&&(sameCount+=1);sameCount>5&&(lostPoint+=3+sameCount-5)}for(row=0;row<moduleCount-1;row+=1)for(col=0;col<moduleCount-1;col+=1){count=0;qrcode4.isDark(row,col)&&(count+=1);qrcode4.isDark(row+1,col)&&(count+=1);qrcode4.isDark(row,col+1)&&(count+=1);qrcode4.isDark(row+1,col+1)&&(count+=1);0!=count&&4!=count||(lostPoint+=3)}for(row=0;row<moduleCount;row+=1)for(col=0;col<moduleCount-6;col+=1)qrcode4.isDark(row,col)&&!qrcode4.isDark(row,col+1)&&qrcode4.isDark(row,col+2)&&qrcode4.isDark(row,col+3)&&qrcode4.isDark(row,col+4)&&!qrcode4.isDark(row,col+5)&&qrcode4.isDark(row,col+6)&&(lostPoint+=40);for(col=0;col<moduleCount;col+=1)for(row=0;row<moduleCount-6;row+=1)qrcode4.isDark(row,col)&&!qrcode4.isDark(row+1,col)&&qrcode4.isDark(row+2,col)&&qrcode4.isDark(row+3,col)&&qrcode4.isDark(row+4,col)&&!qrcode4.isDark(row+5,col)&&qrcode4.isDark(row+6,col)&&(lostPoint+=40);darkCount=0;for(col=0;col<moduleCount;col+=1)for(row=0;row<moduleCount;row+=1)qrcode4.isDark(row,col)&&(darkCount+=1);return lostPoint+Math.abs(100*darkCount/moduleCount/moduleCount-50)/5*10};return _this}();QRMath=function(){var i2,_this,EXP_TABLE=new Array(256),LOG_TABLE=new Array(256);for(i2=0;i2<8;i2+=1)EXP_TABLE[i2]=1<<i2;for(i2=8;i2<256;i2+=1)EXP_TABLE[i2]=EXP_TABLE[i2-4]^EXP_TABLE[i2-5]^EXP_TABLE[i2-6]^EXP_TABLE[i2-8];for(i2=0;i2<255;i2+=1)LOG_TABLE[EXP_TABLE[i2]]=i2;(_this={}).glog=function(n3){if(n3<1)throw"glog("+n3+")";return LOG_TABLE[n3]};_this.gexp=function(n3){for(;n3<0;)n3+=255;for(;n3>=256;)n3-=255;return EXP_TABLE[n3]};return _this}();QRRSBlock=function(){var RS_BLOCK_TABLE=[[1,26,19],[1,26,16],[1,26,13],[1,26,9],[1,44,34],[1,44,28],[1,44,22],[1,44,16],[1,70,55],[1,70,44],[2,35,17],[2,35,13],[1,100,80],[2,50,32],[2,50,24],[4,25,9],[1,134,108],[2,67,43],[2,33,15,2,34,16],[2,33,11,2,34,12],[2,86,68],[4,43,27],[4,43,19],[4,43,15],[2,98,78],[4,49,31],[2,32,14,4,33,15],[4,39,13,1,40,14],[2,121,97],[2,60,38,2,61,39],[4,40,18,2,41,19],[4,40,14,2,41,15],[2,146,116],[3,58,36,2,59,37],[4,36,16,4,37,17],[4,36,12,4,37,13],[2,86,68,2,87,69],[4,69,43,1,70,44],[6,43,19,2,44,20],[6,43,15,2,44,16],[4,101,81],[1,80,50,4,81,51],[4,50,22,4,51,23],[3,36,12,8,37,13],[2,116,92,2,117,93],[6,58,36,2,59,37],[4,46,20,6,47,21],[7,42,14,4,43,15],[4,133,107],[8,59,37,1,60,38],[8,44,20,4,45,21],[12,33,11,4,34,12],[3,145,115,1,146,116],[4,64,40,5,65,41],[11,36,16,5,37,17],[11,36,12,5,37,13],[5,109,87,1,110,88],[5,65,41,5,66,42],[5,54,24,7,55,25],[11,36,12,7,37,13],[5,122,98,1,123,99],[7,73,45,3,74,46],[15,43,19,2,44,20],[3,45,15,13,46,16],[1,135,107,5,136,108],[10,74,46,1,75,47],[1,50,22,15,51,23],[2,42,14,17,43,15],[5,150,120,1,151,121],[9,69,43,4,70,44],[17,50,22,1,51,23],[2,42,14,19,43,15],[3,141,113,4,142,114],[3,70,44,11,71,45],[17,47,21,4,48,22],[9,39,13,16,40,14],[3,135,107,5,136,108],[3,67,41,13,68,42],[15,54,24,5,55,25],[15,43,15,10,44,16],[4,144,116,4,145,117],[17,68,42],[17,50,22,6,51,23],[19,46,16,6,47,17],[2,139,111,7,140,112],[17,74,46],[7,54,24,16,55,25],[34,37,13],[4,151,121,5,152,122],[4,75,47,14,76,48],[11,54,24,14,55,25],[16,45,15,14,46,16],[6,147,117,4,148,118],[6,73,45,14,74,46],[11,54,24,16,55,25],[30,46,16,2,47,17],[8,132,106,4,133,107],[8,75,47,13,76,48],[7,54,24,22,55,25],[22,45,15,13,46,16],[10,142,114,2,143,115],[19,74,46,4,75,47],[28,50,22,6,51,23],[33,46,16,4,47,17],[8,152,122,4,153,123],[22,73,45,3,74,46],[8,53,23,26,54,24],[12,45,15,28,46,16],[3,147,117,10,148,118],[3,73,45,23,74,46],[4,54,24,31,55,25],[11,45,15,31,46,16],[7,146,116,7,147,117],[21,73,45,7,74,46],[1,53,23,37,54,24],[19,45,15,26,46,16],[5,145,115,10,146,116],[19,75,47,10,76,48],[15,54,24,25,55,25],[23,45,15,25,46,16],[13,145,115,3,146,116],[2,74,46,29,75,47],[42,54,24,1,55,25],[23,45,15,28,46,16],[17,145,115],[10,74,46,23,75,47],[10,54,24,35,55,25],[19,45,15,35,46,16],[17,145,115,1,146,116],[14,74,46,21,75,47],[29,54,24,19,55,25],[11,45,15,46,46,16],[13,145,115,6,146,116],[14,74,46,23,75,47],[44,54,24,7,55,25],[59,46,16,1,47,17],[12,151,121,7,152,122],[12,75,47,26,76,48],[39,54,24,14,55,25],[22,45,15,41,46,16],[6,151,121,14,152,122],[6,75,47,34,76,48],[46,54,24,10,55,25],[2,45,15,64,46,16],[17,152,122,4,153,123],[29,74,46,14,75,47],[49,54,24,10,55,25],[24,45,15,46,46,16],[4,152,122,18,153,123],[13,74,46,32,75,47],[48,54,24,14,55,25],[42,45,15,32,46,16],[20,147,117,4,148,118],[40,75,47,7,76,48],[43,54,24,22,55,25],[10,45,15,67,46,16],[19,148,118,6,149,119],[18,75,47,31,76,48],[34,54,24,34,55,25],[20,45,15,61,46,16]],qrRSBlock=function(totalCount,dataCount){var _this2={};_this2.totalCount=totalCount;_this2.dataCount=dataCount;return _this2},_this={},getRsBlockTable=function(typeNumber,errorCorrectionLevel){switch(errorCorrectionLevel){case QRErrorCorrectionLevel.L:return RS_BLOCK_TABLE[4*(typeNumber-1)+0];case QRErrorCorrectionLevel.M:return RS_BLOCK_TABLE[4*(typeNumber-1)+1];case QRErrorCorrectionLevel.Q:return RS_BLOCK_TABLE[4*(typeNumber-1)+2];case QRErrorCorrectionLevel.H:return RS_BLOCK_TABLE[4*(typeNumber-1)+3];default:return}};_this.getRSBlocks=function(typeNumber,errorCorrectionLevel){var length,list,i2,count,totalCount,dataCount,j2,rsBlock=getRsBlockTable(typeNumber,errorCorrectionLevel);if(void 0===rsBlock)throw"bad rs block @ typeNumber:"+typeNumber+"/errorCorrectionLevel:"+errorCorrectionLevel;length=rsBlock.length/3;list=[];for(i2=0;i2<length;i2+=1){count=rsBlock[3*i2+0];totalCount=rsBlock[3*i2+1];dataCount=rsBlock[3*i2+2];for(j2=0;j2<count;j2+=1)list.push(qrRSBlock(totalCount,dataCount))}return list};return _this}();qrBitBuffer=function(){var _buffer=[],_length=0,_this={getBuffer:function(){return _buffer},getAt:function(index6){var bufIndex=Math.floor(index6/8);return 1==(_buffer[bufIndex]>>>7-index6%8&1)},put:function(num,length){for(var i2=0;i2<length;i2+=1)_this.putBit(1==(num>>>length-i2-1&1))},getLengthInBits:function(){return _length},putBit:function(bit){var bufIndex=Math.floor(_length/8);_buffer.length<=bufIndex&&_buffer.push(0);bit&&(_buffer[bufIndex]|=128>>>_length%8);_length+=1}};return _this};qrNumber=function(data){var strToNum2,chatToNum,_data2=data,_this={getMode:function(){return 1},getLength:function(buffer){return _data2.length},write:function(buffer){for(var data2=_data2,i2=0;i2+2<data2.length;){buffer.put(strToNum2(data2.substring(i2,i2+3)),10);i2+=3}i2<data2.length&&(data2.length-i2==1?buffer.put(strToNum2(data2.substring(i2,i2+1)),4):data2.length-i2==2&&buffer.put(strToNum2(data2.substring(i2,i2+2)),7))}};strToNum2=function(s2){var i2,num=0;for(i2=0;i2<s2.length;i2+=1)num=10*num+chatToNum(s2.charAt(i2));return num};chatToNum=function(c3){if("0"<=c3&&c3<="9")return c3.charCodeAt(0)-"0".charCodeAt(0);throw"illegal char :"+c3};return _this};qrAlphaNum=function(data){var getCode,_data2=data,_this={getMode:function(){return 2},getLength:function(buffer){return _data2.length},write:function(buffer){for(var s2=_data2,i2=0;i2+1<s2.length;){buffer.put(45*getCode(s2.charAt(i2))+getCode(s2.charAt(i2+1)),11);i2+=2}i2<s2.length&&buffer.put(getCode(s2.charAt(i2)),6)}};getCode=function(c3){if("0"<=c3&&c3<="9")return c3.charCodeAt(0)-"0".charCodeAt(0);if("A"<=c3&&c3<="Z")return c3.charCodeAt(0)-"A".charCodeAt(0)+10;switch(c3){case" ":return 36;case"$":return 37;case"%":return 38;case"*":return 39;case"+":return 40;case"-":return 41;case".":return 42;case"/":return 43;case":":return 44;default:throw"illegal char :"+c3}};return _this};qr8BitByte=function(data){var _bytes=qrcode3.stringToBytes(data),_this={getMode:function(){return 4},getLength:function(buffer){return _bytes.length},write:function(buffer){for(var i2=0;i2<_bytes.length;i2+=1)buffer.put(_bytes[i2],8)}};return _this};qrKanji=function(data){var _bytes,_this,stringToBytes=qrcode3.stringToBytesFuncs.SJIS;if(!stringToBytes)throw"sjis not supported.";!function(){var test=stringToBytes("友");if(2!=test.length||38726!=(test[0]<<8|test[1]))throw"sjis not supported."}();_bytes=stringToBytes(data);(_this={}).getMode=function(){return 8};_this.getLength=function(buffer){return~~(_bytes.length/2)};_this.write=function(buffer){for(var c3,data2=_bytes,i2=0;i2+1<data2.length;){if(33088<=(c3=(255&data2[i2])<<8|255&data2[i2+1])&&c3<=40956)c3-=33088;else{if(!(57408<=c3&&c3<=60351))throw"illegal char at "+(i2+1)+"/"+c3;c3-=49472}c3=192*(c3>>>8&255)+(255&c3);buffer.put(c3,13);i2+=2}if(i2<data2.length)throw"illegal char at "+(i2+1)};return _this};byteArrayOutputStream=function(){var _bytes=[],_this={writeByte:function(b3){_bytes.push(255&b3)},writeShort:function(i2){_this.writeByte(i2);_this.writeByte(i2>>>8)},writeBytes:function(b3,off,len){off=off||0;len=len||b3.length;for(var i2=0;i2<len;i2+=1)_this.writeByte(b3[i2+off])},writeString:function(s2){for(var i2=0;i2<s2.length;i2+=1)_this.writeByte(s2.charCodeAt(i2))},toByteArray:function(){return _bytes},toString:function(){var i2,s2="";s2+="[";for(i2=0;i2<_bytes.length;i2+=1){i2>0&&(s2+=",");s2+=_bytes[i2]}return s2+"]"}};return _this};base64EncodeOutputStream=function(){var _buffer=0,_buflen=0,_length=0,_base64="",_this={},writeEncoded=function(b3){_base64+=String.fromCharCode(encode(63&b3))},encode=function(n3){if(n3<0);else{if(n3<26)return 65+n3;if(n3<52)return n3-26+97;if(n3<62)return n3-52+48;if(62==n3)return 43;if(63==n3)return 47}throw"n:"+n3};_this.writeByte=function(n3){_buffer=_buffer<<8|255&n3;_buflen+=8;_length+=1;for(;_buflen>=6;){writeEncoded(_buffer>>>_buflen-6);_buflen-=6}};_this.flush=function(){var padlen,i2;if(_buflen>0){writeEncoded(_buffer<<6-_buflen);_buffer=0;_buflen=0}if(_length%3!=0){padlen=3-_length%3;for(i2=0;i2<padlen;i2+=1)_base64+="="}};_this.toString=function(){return _base64};return _this};base64DecodeInputStream=function(str){var decode,_str=str,_pos=0,_buffer=0,_buflen=0,_this={read:function(){for(var c3,n3;_buflen<8;){if(_pos>=_str.length){if(0==_buflen)return-1;throw"unexpected end of file./"+_buflen}c3=_str.charAt(_pos);_pos+=1;if("="==c3){_buflen=0;return-1}if(!c3.match(/^\s$/)){_buffer=_buffer<<6|decode(c3.charCodeAt(0));_buflen+=6}}n3=_buffer>>>_buflen-8&255;_buflen-=8;return n3}};decode=function(c3){if(65<=c3&&c3<=90)return c3-65;if(97<=c3&&c3<=122)return c3-97+26;if(48<=c3&&c3<=57)return c3-48+52;if(43==c3)return 62;if(47==c3)return 63;throw"c:"+c3};return _this};gifImage=function(width,height){var bitOutputStream,getLZWRaster,lzwTable,_width=width,_height=height,_data2=new Array(width*height),_this={setPixel:function(x2,y2,pixel){_data2[y2*_width+x2]=pixel},write:function(out){var raster,offset;out.writeString("GIF87a");out.writeShort(_width);out.writeShort(_height);out.writeByte(128);out.writeByte(0);out.writeByte(0);out.writeByte(0);out.writeByte(0);out.writeByte(0);out.writeByte(255);out.writeByte(255);out.writeByte(255);out.writeString(",");out.writeShort(0);out.writeShort(0);out.writeShort(_width);out.writeShort(_height);out.writeByte(0);raster=getLZWRaster(2);out.writeByte(2);offset=0;for(;raster.length-offset>255;){out.writeByte(255);out.writeBytes(raster,offset,255);offset+=255}out.writeByte(raster.length-offset);out.writeBytes(raster,offset,raster.length-offset);out.writeByte(0);out.writeString(";")}};bitOutputStream=function(out){var _out=out,_bitLength=0,_bitBuffer=0;return{write:function(data,length){if(data>>>length!=0)throw"length over";for(;_bitLength+length>=8;){_out.writeByte(255&(data<<_bitLength|_bitBuffer));length-=8-_bitLength;data>>>=8-_bitLength;_bitBuffer=0;_bitLength=0}_bitBuffer|=data<<_bitLength;_bitLength+=length},flush:function(){_bitLength>0&&_out.writeByte(_bitBuffer)}}};getLZWRaster=function(lzwMinCodeSize){var i2,byteOut,bitOut,dataIndex,s2,c3,clearCode=1<<lzwMinCodeSize,endCode=1+(1<<lzwMinCodeSize),bitLength=lzwMinCodeSize+1,table2=lzwTable();for(i2=0;i2<clearCode;i2+=1)table2.add(String.fromCharCode(i2));table2.add(String.fromCharCode(clearCode));table2.add(String.fromCharCode(endCode));byteOut=byteArrayOutputStream();(bitOut=bitOutputStream(byteOut)).write(clearCode,bitLength);dataIndex=0;s2=String.fromCharCode(_data2[dataIndex]);dataIndex+=1;for(;dataIndex<_data2.length;){c3=String.fromCharCode(_data2[dataIndex]);dataIndex+=1;if(table2.contains(s2+c3))s2+=c3;else{bitOut.write(table2.indexOf(s2),bitLength);if(table2.size()<4095){table2.size()==1<<bitLength&&(bitLength+=1);table2.add(s2+c3)}s2=c3}}bitOut.write(table2.indexOf(s2),bitLength);bitOut.write(endCode,bitLength);bitOut.flush();return byteOut.toByteArray()};lzwTable=function(){var _map={},_size=0,_this2={add:function(key3){if(_this2.contains(key3))throw"dup key:"+key3;_map[key3]=_size;_size+=1},size:function(){return _size},indexOf:function(key3){return _map[key3]},contains:function(key3){return void 0!==_map[key3]}};return _this2};return _this};createDataURL=function(width,height,getPixel){var y2,x2,b3,base64,bytes,i2,gif=gifImage(width,height);for(y2=0;y2<height;y2+=1)for(x2=0;x2<width;x2+=1)gif.setPixel(x2,y2,getPixel(x2,y2));b3=byteArrayOutputStream();gif.write(b3);base64=base64EncodeOutputStream();bytes=b3.toByteArray();for(i2=0;i2<bytes.length;i2+=1)base64.writeByte(bytes[i2]);base64.flush();return"data:image/gif;base64,"+base64};return qrcode3}();!function(){qrcode2.stringToBytesFuncs["UTF-8"]=function(s2){return function toUTF8Array(str){var i2,charcode,utf8=[];for(i2=0;i2<str.length;i2++)if((charcode=str.charCodeAt(i2))<128)utf8.push(charcode);else if(charcode<2048)utf8.push(192|charcode>>6,128|63&charcode);else if(charcode<55296||charcode>=57344)utf8.push(224|charcode>>12,128|charcode>>6&63,128|63&charcode);else{i2++;charcode=65536+((1023&charcode)<<10|1023&str.charCodeAt(i2));utf8.push(240|charcode>>18,128|charcode>>12&63,128|charcode>>6&63,128|63&charcode)}return utf8}(s2)}}();(function(factory){"function"==typeof define&&define.amd?define([],factory):"object"==typeof exports&&(module2.exports=factory())})((function(){return qrcode2}))}}),main_exports={};
/*! Bundled license information:
octagonal-wheels/dist/encoding/encodeobject.js:
(* istanbul ignore if -- @preserve *)
@noble/secp256k1/index.js:
(*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
octagonal-wheels/dist/encryption/hkdf.js:
(* istanbul ignore if -- @preserve *)
(* istanbul ignore next -- @preserve *)
*/__export(main_exports,{default:()=>ObsidianLiveSyncPlugin});module.exports=__toCommonJS(main_exports);LOG_KIND_ERROR=8;LOG_LEVEL_DEBUG=-1;LEVEL_INFO=LOG_LEVEL_INFO=32;LEVEL_NOTICE=LOG_LEVEL_NOTICE=64;LOG_LEVEL_VERBOSE=16;defaultLoggerEnv_minLogLevel=LOG_LEVEL_INFO;_logger=function defaultLogger2(message,level=LEVEL_INFO,key3){if(level<defaultLoggerEnv_minLogLevel)return;const newMessage=`${(new Date).toLocaleString()}\t${level}\t${"string"==typeof message?message:message instanceof Error?`${message.name}:${message.message}`:JSON.stringify(message,null,2)}`;1&level?console.debug(newMessage):4&level?console.warn(newMessage):level&LOG_KIND_ERROR?console.error(newMessage):2&level?console.info(newMessage):console.log(newMessage);message instanceof Error&&console.dir(message.stack)};RESULT_TIMED_OUT=Symbol("timed out");Symbol("NotFound");CANCELLED=Symbol("cancelled");AUTO_MERGED=Symbol("auto_merged");NOT_CONFLICTED=Symbol("not_conflicted");MISSING_OR_ERROR=Symbol("missing_or_error");LEAVE_TO_SUBSEQUENT=Symbol("leave_to_subsequent_proc");Symbol("infinity");MILESTONE_DOCID="_local/obsydian_livesync_milestone";NODEINFO_DOCID="_local/obsydian_livesync_nodeinfo";MODE_SELECTIVE=0;MODE_AUTOMATIC=1;MODE_PAUSED=2;MODE_SHINY=3;REMOTE_COUCHDB=RemoteTypes_REMOTE_COUCHDB="";REMOTE_MINIO=RemoteTypes_REMOTE_MINIO="MINIO";REMOTE_P2P=RemoteTypes_REMOTE_P2P="ONLY_P2P";AutoAccepting=(AutoAccepting2=>{AutoAccepting2[AutoAccepting2.NONE=0]="NONE";AutoAccepting2[AutoAccepting2.ALL=1]="ALL";return AutoAccepting2})(AutoAccepting||{});P2P_DEFAULT_SETTINGS={P2P_Enabled:!1,P2P_AutoAccepting:0,P2P_AppID:"self-hosted-livesync",P2P_roomID:"",P2P_passphrase:"",P2P_relays:"wss://exp-relay.vrtmrz.net/",P2P_AutoBroadcast:!1,P2P_AutoStart:!1,P2P_AutoSyncPeers:"",P2P_AutoWatchPeers:"",P2P_SyncOnReplication:"",P2P_RebuildFrom:"",P2P_AutoAcceptingPeers:"",P2P_AutoDenyingPeers:"",P2P_IsHeadless:!1,P2P_DevicePeerName:"",P2P_turnServers:"",P2P_turnUsername:"",P2P_turnCredential:""};E2EEAlgorithmNames={"":"V1: Legacy",v2:"V2: AES-256-GCM With HKDF",forceV1:"Force-V1: Force Legacy (Not recommended)"};E2EEAlgorithms={V1:"",V2:"v2",ForceV1:"forceV1"};ChunkAlgorithmNames={v1:"V1: Legacy",v2:"V2: Simple (Default)","v2-segmenter":"V2.5: Lexical chunks","v3-rabin-karp":"V3: Fine deduplication"};DEFAULT_SETTINGS={remoteType:REMOTE_COUCHDB,useCustomRequestHandler:!1,couchDB_URI:"",couchDB_USER:"",couchDB_PASSWORD:"",couchDB_DBNAME:"",liveSync:!1,syncOnSave:!1,syncOnStart:!1,savingDelay:200,lessInformationInLog:!1,gcDelay:300,versionUpFlash:"",minimumChunkSize:20,longLineThreshold:250,showVerboseLog:!1,suspendFileWatching:!1,trashInsteadDelete:!0,periodicReplication:!1,periodicReplicationInterval:60,syncOnFileOpen:!1,encrypt:!1,passphrase:"",usePathObfuscation:!1,doNotDeleteFolder:!1,resolveConflictsByNewerFile:!1,batchSave:!1,batchSaveMinimumDelay:5,batchSaveMaximumDelay:60,deviceAndVaultName:"",usePluginSettings:!1,showOwnPlugins:!1,showStatusOnEditor:!0,showStatusOnStatusbar:!0,showOnlyIconsOnEditor:!1,hideFileWarningNotice:!1,usePluginSync:!1,autoSweepPlugins:!1,autoSweepPluginsPeriodic:!1,notifyPluginOrSettingUpdated:!1,checkIntegrityOnSave:!1,batch_size:25,batches_limit:25,useHistory:!1,disableRequestURI:!1,skipOlderFilesOnSync:!0,checkConflictOnlyOnOpen:!1,showMergeDialogOnlyOnActive:!1,syncInternalFiles:!1,syncInternalFilesBeforeReplication:!1,syncInternalFilesIgnorePatterns:"\\/node_modules\\/, \\/\\.git\\/, \\/obsidian-livesync\\/",syncInternalFilesTargetPatterns:"",syncInternalFilesInterval:60,additionalSuffixOfDatabaseName:"",ignoreVersionCheck:!1,lastReadUpdates:0,deleteMetadataOfDeletedFiles:!1,syncIgnoreRegEx:"",syncOnlyRegEx:"",customChunkSize:0,readChunksOnline:!0,watchInternalFileChanges:!0,automaticallyDeleteMetadataOfDeletedFiles:0,disableMarkdownAutoMerge:!1,writeDocumentsIfConflicted:!1,useDynamicIterationCount:!1,syncAfterMerge:!1,configPassphraseStore:"",encryptedPassphrase:"",encryptedCouchDBConnection:"",permitEmptyPassphrase:!1,useIndexedDBAdapter:!1,useTimeouts:!1,writeLogToTheFile:!1,doNotPaceReplication:!1,hashCacheMaxCount:300,hashCacheMaxAmount:50,concurrencyOfReadChunksOnline:40,minimumIntervalOfReadChunksOnline:50,hashAlg:"xxhash64",suspendParseReplicationResult:!1,doNotSuspendOnFetching:!1,useIgnoreFiles:!1,ignoreFiles:".gitignore",syncOnEditorSave:!1,pluginSyncExtendedSetting:{},syncMaxSizeInMB:50,settingSyncFile:"",writeCredentialsForSettingSync:!1,notifyAllSettingSyncFile:!1,isConfigured:void 0,settingVersion:10,enableCompression:!1,accessKey:"",bucket:"",endpoint:"",region:"auto",secretKey:"",useEden:!1,maxChunksInEden:10,maxTotalLengthInEden:1024,maxAgeInEden:10,disableCheckingConfigMismatch:!1,displayLanguage:"",enableChunkSplitterV2:!1,disableWorkerForGeneratingChunks:!1,processSmallFilesInUIThread:!1,notifyThresholdOfRemoteStorageSize:-1,usePluginSyncV2:!1,usePluginEtc:!1,handleFilenameCaseSensitive:void 0,doNotUseFixedRevisionForChunks:!0,showLongerLogInsideEditor:!1,sendChunksBulk:!1,sendChunksBulkMaxSize:1,useSegmenter:!1,useAdvancedMode:!1,usePowerUserMode:!1,useEdgeCaseMode:!1,enableDebugTools:!1,suppressNotifyHiddenFilesChange:!1,syncMinimumInterval:2e3,...P2P_DEFAULT_SETTINGS,doctorProcessedVersion:"",bucketCustomHeaders:"",couchDB_CustomHeaders:"",useJWT:!1,jwtAlgorithm:"",jwtKey:"",jwtKid:"",jwtSub:"",jwtExpDuration:5,useRequestAPI:!1,bucketPrefix:"",chunkSplitterVersion:"",E2EEAlgorithm:E2EEAlgorithms.V2,processSizeMismatchedFiles:!1,forcePathStyle:!0,syncInternalFileOverwritePatterns:"",useOnlyLocalChunk:!1};KeyIndexOfSettings={remoteType:0,useCustomRequestHandler:1,couchDB_URI:2,couchDB_USER:3,couchDB_PASSWORD:4,couchDB_DBNAME:5,minimumChunkSize:6,longLineThreshold:7,encrypt:8,passphrase:9,usePathObfuscation:10,checkIntegrityOnSave:11,batch_size:12,batches_limit:13,useHistory:14,disableRequestURI:15,checkConflictOnlyOnOpen:16,showMergeDialogOnlyOnActive:17,additionalSuffixOfDatabaseName:18,ignoreVersionCheck:19,deleteMetadataOfDeletedFiles:20,customChunkSize:21,readChunksOnline:22,automaticallyDeleteMetadataOfDeletedFiles:23,useDynamicIterationCount:24,permitEmptyPassphrase:25,useTimeouts:26,doNotPaceReplication:27,hashCacheMaxCount:28,hashCacheMaxAmount:29,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:31,hashAlg:32,enableCompression:33,accessKey:34,bucket:35,endpoint:36,region:37,secretKey:38,useEden:39,maxChunksInEden:40,maxTotalLengthInEden:41,maxAgeInEden:42,disableCheckingConfigMismatch:43,handleFilenameCaseSensitive:44,doNotUseFixedRevisionForChunks:45,sendChunksBulk:46,sendChunksBulkMaxSize:47,useSegmenter:48,liveSync:49,syncOnSave:50,syncOnStart:51,syncOnFileOpen:52,syncOnEditorSave:53,syncMinimumInterval:54,showVerboseLog:55,lessInformationInLog:56,showLongerLogInsideEditor:57,showStatusOnEditor:58,showStatusOnStatusbar:59,showOnlyIconsOnEditor:60,displayLanguage:61,trashInsteadDelete:62,doNotDeleteFolder:63,batchSave:64,batchSaveMinimumDelay:64,batchSaveMaximumDelay:65,syncMaxSizeInMB:66,useIgnoreFiles:67,ignoreFiles:68,syncOnlyRegEx:69,syncIgnoreRegEx:70,syncAfterMerge:71,resolveConflictsByNewerFile:72,writeDocumentsIfConflicted:73,disableMarkdownAutoMerge:74,configPassphraseStore:75,encryptedPassphrase:76,encryptedCouchDBConnection:77,periodicReplication:78,periodicReplicationInterval:79,syncInternalFiles:80,syncInternalFilesBeforeReplication:81,syncInternalFilesInterval:82,syncInternalFilesIgnorePatterns:83,watchInternalFileChanges:84,suppressNotifyHiddenFilesChange:85,usePluginSync:86,usePluginSettings:87,showOwnPlugins:88,autoSweepPlugins:89,autoSweepPluginsPeriodic:90,notifyPluginOrSettingUpdated:91,deviceAndVaultName:92,usePluginSyncV2:93,usePluginEtc:94,pluginSyncExtendedSetting:95,useAdvancedMode:96,usePowerUserMode:97,useEdgeCaseMode:98,notifyThresholdOfRemoteStorageSize:99,disableWorkerForGeneratingChunks:100,processSmallFilesInUIThread:101,enableChunkSplitterV2:102,savingDelay:103,gcDelay:104,skipOlderFilesOnSync:105,useIndexedDBAdapter:106,enableDebugTools:107,writeLogToTheFile:108,settingSyncFile:109,writeCredentialsForSettingSync:110,notifyAllSettingSyncFile:111,suspendFileWatching:112,suspendParseReplicationResult:113,doNotSuspendOnFetching:114,versionUpFlash:115,settingVersion:116,isConfigured:117,lastReadUpdates:118,doctorProcessedVersion:119,P2P_Enabled:120,P2P_relays:121,P2P_roomID:122,P2P_passphrase:123,P2P_AutoAccepting:124,P2P_AutoStart:125,P2P_AutoBroadcast:126,P2P_AutoSyncPeers:127,P2P_AutoWatchPeers:128,P2P_SyncOnReplication:129,P2P_AppID:130,P2P_RebuildFrom:131,bucketCustomHeaders:132,couchDB_CustomHeaders:133,useJWT:134,jwtAlgorithm:135,jwtKey:136,jwtKid:137,jwtSub:138,jwtExpDuration:139,P2P_AutoAcceptingPeers:140,P2P_AutoDenyingPeers:141,P2P_IsHeadless:-1,syncInternalFilesTargetPatterns:142,useRequestAPI:143,hideFileWarningNotice:144,bucketPrefix:145,chunkSplitterVersion:146,E2EEAlgorithm:147,processSizeMismatchedFiles:148,forcePathStyle:149,P2P_DevicePeerName:-1,P2P_turnServers:150,P2P_turnUsername:151,P2P_turnCredential:152,syncInternalFileOverwritePatterns:153,useOnlyLocalChunk:154};PREFERRED_BASE={syncMaxSizeInMB:50,chunkSplitterVersion:"v3-rabin-karp",doNotUseFixedRevisionForChunks:!1,usePluginSyncV2:!0,handleFilenameCaseSensitive:!1,E2EEAlgorithm:E2EEAlgorithms.V2};PREFERRED_SETTING_CLOUDANT={...PREFERRED_BASE,customChunkSize:0,sendChunksBulkMaxSize:1,concurrencyOfReadChunksOnline:100,minimumIntervalOfReadChunksOnline:333};PREFERRED_SETTING_SELF_HOSTED={...PREFERRED_BASE,customChunkSize:50,sendChunksBulkMaxSize:1,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:25};PREFERRED_JOURNAL_SYNC={...PREFERRED_BASE,customChunkSize:10,concurrencyOfReadChunksOnline:30,minimumIntervalOfReadChunksOnline:25};TweakValuesShouldMatchedTemplate={minimumChunkSize:20,longLineThreshold:250,encrypt:!1,usePathObfuscation:!1,enableCompression:!1,useEden:!1,customChunkSize:0,useDynamicIterationCount:!1,hashAlg:"xxhash64",enableChunkSplitterV2:!1,maxChunksInEden:10,maxTotalLengthInEden:1024,maxAgeInEden:10,usePluginSyncV2:!1,handleFilenameCaseSensitive:!1,doNotUseFixedRevisionForChunks:!0,useSegmenter:!1,E2EEAlgorithm:E2EEAlgorithms.V2,chunkSplitterVersion:"v3-rabin-karp"};IncompatibleChanges=["encrypt","usePathObfuscation","useDynamicIterationCount","handleFilenameCaseSensitive"];CompatibleButLossyChanges=["hashAlg"];IncompatibleChangesInSpecificPattern=[{key:"doNotUseFixedRevisionForChunks",from:!0,to:!1,isRecommendation:!0},{key:"doNotUseFixedRevisionForChunks",to:!0,isRecommendation:!1}];TweakValuesRecommendedTemplate={useIgnoreFiles:!1,useCustomRequestHandler:!1,batch_size:25,batches_limit:25,useTimeouts:!1,readChunksOnline:!0,hashCacheMaxCount:300,hashCacheMaxAmount:50,concurrencyOfReadChunksOnline:40,minimumIntervalOfReadChunksOnline:50,ignoreFiles:".gitignore",syncMaxSizeInMB:50,enableChunkSplitterV2:!1,usePluginSyncV2:!0,handleFilenameCaseSensitive:!1,doNotUseFixedRevisionForChunks:!1,E2EEAlgorithm:E2EEAlgorithms.V2,chunkSplitterVersion:"v3-rabin-karp"};TweakValuesDefault={usePluginSyncV2:!1,E2EEAlgorithm:DEFAULT_SETTINGS.E2EEAlgorithm,chunkSplitterVersion:DEFAULT_SETTINGS.chunkSplitterVersion};configurationNames={minimumChunkSize:{name:"Minimum Chunk Size (Not Configurable from the UI Now)."},longLineThreshold:{name:"Longest chunk line threshold value (Not Configurable from the UI Now)."},encrypt:{name:"End-to-End Encryption",desc:"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended."},usePathObfuscation:{name:"Property Encryption",desc:"If enabled, the file properties will be encrypted in the remote database. This is useful for protecting sensitive information in file paths, sizes, and IDs of its chunks. If you are using V1 E2EE, this only obfuscates the file path."},enableCompression:{name:"Data Compression",status:"EXPERIMENTAL"},useEden:{name:"Incubate Chunks in Document",desc:"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.",status:"BETA"},customChunkSize:{name:"Enhance chunk size"},useDynamicIterationCount:{name:"Use dynamic iteration count",status:"EXPERIMENTAL"},hashAlg:{name:"The Hash algorithm for chunk IDs",status:"EXPERIMENTAL"},enableChunkSplitterV2:{name:"Use splitting-limit-capped chunk splitter",desc:"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker."},maxChunksInEden:{name:"Maximum Incubating Chunks",desc:"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks."},maxTotalLengthInEden:{name:"Maximum Incubating Chunk Size",desc:"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks."},maxAgeInEden:{name:"Maximum Incubation Period",desc:"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks."},usePluginSyncV2:{name:"Per-file-saved customization sync",desc:"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions."},handleFilenameCaseSensitive:{name:"Handle files as Case-Sensitive",desc:"If this enabled, All files are handled as case-Sensitive (Previous behaviour)."},doNotUseFixedRevisionForChunks:{name:"Compute revisions for chunks (Previous behaviour)",desc:"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)"},useSegmenter:{name:"Use Segmented-splitter",desc:"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature."},useJWT:{name:"Use JWT instead of Basic Authentication",desc:"If this enabled, JWT will be used for authentication.",isAdvanced:!0},jwtAlgorithm:{name:"JWT Algorithm",desc:"The algorithm used for JWT authentication.",isAdvanced:!0},jwtKey:{name:"Keypair or pre-shared key",desc:"The key (PSK in HSxxx in base64, or private key in ESxxx in PEM) used for JWT authentication.",isAdvanced:!0,isHidden:!0},jwtKid:{name:"Key ID",desc:"The key ID. this should be matched with CouchDB->jwt_keys->ALG:_`kid`.",isAdvanced:!0},jwtExpDuration:{name:"Rotation Duration",desc:"The Rotation duration of token in minutes. Each generated tokens will be valid only within this duration.",isAdvanced:!0},jwtSub:{name:"Subject (whoami)",desc:"The subject for JWT authentication. Mostly username.",isAdvanced:!0},bucketCustomHeaders:{name:"Custom Headers",desc:"Custom headers for requesting the bucket. e.g. `x-custom-header1: value1\n x-custom-header2: value2`",placeHolder:"x-custom-header1: value1\n x-custom-header2: value2"},couchDB_CustomHeaders:{name:"Custom Headers",desc:"Custom headers for requesting the CouchDB. e.g. `x-custom-header1: value1\n x-custom-header2: value2`",placeHolder:"x-custom-header1: value1\n x-custom-header2: value2"},chunkSplitterVersion:{name:"Chunk Splitter",desc:"Now we can choose how to split the chunks; V3 is the most efficient. If you have troubled, please make this Default or Legacy."},E2EEAlgorithm:{name:"End-to-End Encryption Algorithm",desc:"Please use V2, V1 is deprecated and will be removed in the future, It was not a very appropriate algorithm. Only for compatibility V1 is kept.",isAdvanced:!0},P2P_AppID:{name:"Application ID",desc:"The Application ID for P2P connection. This should be same among your devices. Default is 'self-hosted-livesync' and could not be modified from the UI.",isAdvanced:!0},P2P_relays:{name:"Signalling Relays",desc:"The Nostr relay servers to establish connections for P2P connections. Multiple servers can be separated by commas.",placeHolder:"wss://relay1.example.com,wss://relay2.example.com"},P2P_roomID:{name:"Room ID",desc:"The Room ID for P2P connection. This should be same among your devices."},P2P_passphrase:{name:"Passphrase",desc:"The Passphrase for P2P connection. This should be same among your devices.",isHidden:!0},P2P_turnServers:{name:"TURN Servers",desc:"The TURN servers to use for P2P connections. Multiple servers can be separated by commas.",placeHolder:"turn:turn1.example.com,turn:turn2.example.com"},P2P_turnUsername:{name:"TURN Username",desc:"The username for the TURN servers."},P2P_turnCredential:{name:"TURN Credential",desc:"The credential/password for the TURN servers.",isHidden:!0},useOnlyLocalChunk:{name:"Use Only Local Chunks",desc:"If enabled, the plugin will not attempt to connect to the remote database even if the chunk was not found locally.",isAdvanced:!0}};LEVEL_ADVANCED="ADVANCED";LEVEL_POWER_USER="POWER_USER";LEVEL_EDGE_CASE="EDGE_CASE";TweakValuesTemplate={...TweakValuesRecommendedTemplate,...TweakValuesShouldMatchedTemplate};DEVICE_ID_PREFERRED="PREFERRED";PREFIXMD_LOGFILE="livesync_log_";PREFIXMD_LOGFILE_UC="LIVESYNC_LOG_";FLAGMD_REDFLAG="redflag.md";FLAGMD_REDFLAG2="redflag2.md";FLAGMD_REDFLAG2_HR=FlagFilesHumanReadable_REBUILD_ALL="flag_rebuild.md";FLAGMD_REDFLAG3="redflag3.md";FLAGMD_REDFLAG3_HR=FlagFilesHumanReadable_FETCH_ALL="flag_fetch.md";SYNCINFO_ID="syncinfo";PREFIX_OBFUSCATED="f:";PREFIX_ENCRYPTED_CHUNK="h:+";DEFAULT_SYNC_PARAMETERS={_id:"_local/obsidian_livesync_sync_parameters",type:"sync-parameters",protocolVersion:2,pbkdf2salt:""};SETTING_KEY_P2P_DEVICE_NAME="p2p_device_name";configURIBase="obsidian://setuplivesync?settings=";configURIBaseQR="obsidian://setuplivesync?settingsQR=";SuffixDatabaseName="-livesync-v2";ExtraSuffixIndexedDB="-indexeddb";import_obsidian=require("obsidian");import_obsidian2=require("obsidian");import_diff_match_patch=__toESM(require_diff_match_patch(),1);normalizePath=import_obsidian2.normalizePath;LRUCache=class{constructor(maxCache,maxCacheLength,forwardOnly=!1){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map([])});Object.defineProperty(this,"revCache",{enumerable:!0,configurable:!0,writable:!0,value:new Map([])});Object.defineProperty(this,"maxCache",{enumerable:!0,configurable:!0,writable:!0,value:200});Object.defineProperty(this,"maxCachedLength",{enumerable:!0,configurable:!0,writable:!0,value:5e7});Object.defineProperty(this,"cachedLength",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"enableReversed",{enumerable:!0,configurable:!0,writable:!0,value:!0});this.maxCache=maxCache||200;this.maxCachedLength=1e6*(maxCacheLength||1);this.enableReversed=!forwardOnly;Logger(`Cache initialized ${this.maxCache} / ${this.maxCachedLength}`,LOG_LEVEL_VERBOSE)}clear(){this.cache.clear();this.revCache.clear()}has(key3){return this.cache.has(key3)}get(key3){const v2=this.cache.get(key3);if(v2){this.cache.delete(key3);this.cache.set(key3,v2);if(this.enableReversed){this.revCache.delete(v2);this.revCache.set(v2,key3)}}return v2}revGet(value){const key3=this.revCache.get(value);if(key3){this.cache.delete(key3);this.revCache.delete(value);this.cache.set(key3,value);this.revCache.set(value,key3)}return key3}set(key3,value){this.cache.set(key3,value);this.enableReversed&&this.revCache.set(value,key3);this.cachedLength+=`${value}`.length;if(this.cache.size>this.maxCache||this.cachedLength>this.maxCachedLength)for(const[key4,value2]of this.cache){this.cache.delete(key4);this.enableReversed&&this.revCache.delete(value2);this.cachedLength-=`${value2}`.length;if(this.cache.size<=this.maxCache&&this.cachedLength<=this.maxCachedLength)break}}};balanced=(a2,b3,str)=>{const ma=a2 instanceof RegExp?maybeMatch(a2,str):a2,mb=b3 instanceof RegExp?maybeMatch(b3,str):b3,r4=null!==ma&&null!=mb&&range(ma,mb,str);return r4&&{start:r4[0],end:r4[1],pre:str.slice(0,r4[0]),body:str.slice(r4[0]+ma.length,r4[1]),post:str.slice(r4[1]+mb.length)}};maybeMatch=(reg,str)=>{const m3=str.match(reg);return m3?m3[0]:null};range=(a2,b3,str)=>{let begs,beg,left,right,result,ai2=str.indexOf(a2),bi2=str.indexOf(b3,ai2+1),i2=ai2;if(ai2>=0&&bi2>0){if(a2===b3)return[ai2,bi2];begs=[];left=str.length;for(;i2>=0&&!result;){if(i2===ai2){begs.push(i2);ai2=str.indexOf(a2,i2+1)}else if(1===begs.length){const r4=begs.pop();void 0!==r4&&(result=[r4,bi2])}else{beg=begs.pop();if(void 0!==beg&&beg<left){left=beg;right=bi2}bi2=str.indexOf(b3,i2+1)}i2=ai2<bi2&&ai2>=0?ai2:bi2}begs.length&&void 0!==right&&(result=[left,right])}return result};escSlash="\0SLASH"+Math.random()+"\0";escOpen="\0OPEN"+Math.random()+"\0";escClose="\0CLOSE"+Math.random()+"\0";escComma="\0COMMA"+Math.random()+"\0";escPeriod="\0PERIOD"+Math.random()+"\0";escSlashPattern=new RegExp(escSlash,"g");escOpenPattern=new RegExp(escOpen,"g");escClosePattern=new RegExp(escClose,"g");escCommaPattern=new RegExp(escComma,"g");escPeriodPattern=new RegExp(escPeriod,"g");slashPattern=/\\\\/g;openPattern=/\\{/g;closePattern=/\\}/g;commaPattern=/\\,/g;periodPattern=/\\./g;assertValidPattern=pattern=>{if("string"!=typeof pattern)throw new TypeError("invalid pattern");if(pattern.length>65536)throw new TypeError("pattern is too long")};posixClasses={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]};braceEscape=s2=>s2.replace(/[[\]\\-]/g,"\\$&");regexpEscape=s2=>s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");rangesToString=ranges=>ranges.join("");parseClass=(glob,position)=>{const pos=position;if("["!==glob.charAt(pos))throw new Error("not in a brace expression");const ranges=[],negs=[];let i2=pos+1,sawStart=!1,uflag=!1,escaping=!1,negate3=!1,endPos=pos,rangeStart="";WHILE:for(;i2<glob.length;){const c3=glob.charAt(i2);if("!"!==c3&&"^"!==c3||i2!==pos+1){if("]"===c3&&sawStart&&!escaping){endPos=i2+1;break}sawStart=!0;if("\\"!==c3||escaping){if("["===c3&&!escaping)for(const[cls,[unip,u2,neg]]of Object.entries(posixClasses))if(glob.startsWith(cls,i2)){if(rangeStart)return["$.",!1,glob.length-pos,!0];i2+=cls.length;neg?negs.push(unip):ranges.push(unip);uflag=uflag||u2;continue WHILE}escaping=!1;if(rangeStart){c3>rangeStart?ranges.push(braceEscape(rangeStart)+"-"+braceEscape(c3)):c3===rangeStart&&ranges.push(braceEscape(c3));rangeStart="";i2++}else if(glob.startsWith("-]",i2+1)){ranges.push(braceEscape(c3+"-"));i2+=2}else if(glob.startsWith("-",i2+1)){rangeStart=c3;i2+=2}else{ranges.push(braceEscape(c3));i2++}}else{escaping=!0;i2++}}else{negate3=!0;i2++}}if(endPos<i2)return["",!1,0,!1];if(!ranges.length&&!negs.length)return["$.",!1,glob.length-pos,!0];if(0===negs.length&&1===ranges.length&&/^\\?.$/.test(ranges[0])&&!negate3){const r4=2===ranges[0].length?ranges[0].slice(-1):ranges[0];return[regexpEscape(r4),!1,endPos-pos,!1]}const sranges="["+(negate3?"^":"")+rangesToString(ranges)+"]",snegs="["+(negate3?"":"^")+rangesToString(negs)+"]";return[ranges.length&&negs.length?"("+sranges+"|"+snegs+")":ranges.length?sranges:snegs,uflag,endPos-pos,!0]};unescape2=(s2,{windowsPathsNoEscape=!1,magicalBraces=!0}={})=>magicalBraces?windowsPathsNoEscape?s2.replace(/\[([^\/\\])\]/g,"$1"):s2.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1"):windowsPathsNoEscape?s2.replace(/\[([^\/\\{}])\]/g,"$1"):s2.replace(/((?!\\).|^)\[([^\/\\{}])\]/g,"$1$2").replace(/\\([^\/{}])/g,"$1");types=new Set(["!","?","+","*","@"]);isExtglobType=c3=>types.has(c3);addPatternStart=new Set(["[","."]);justDots=new Set(["..","."]);reSpecials=new Set("().*{}+?[]^$\\!");regExpEscape=s2=>s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");_AST=class _AST{constructor(type,parent,options={}){__privateAdd(this,_AST_instances);__publicField(this,"type");__privateAdd(this,_root);__privateAdd(this,_hasMagic);__privateAdd(this,_uflag,!1);__privateAdd(this,_parts,[]);__privateAdd(this,_parent);__privateAdd(this,_parentIndex);__privateAdd(this,_negs);__privateAdd(this,_filledNegs,!1);__privateAdd(this,_options);__privateAdd(this,_toString);__privateAdd(this,_emptyExt,!1);this.type=type;type&&__privateSet(this,_hasMagic,!0);__privateSet(this,_parent,parent);__privateSet(this,_root,__privateGet(this,_parent)?__privateGet(__privateGet(this,_parent),_root):this);__privateSet(this,_options,__privateGet(this,_root)===this?options:__privateGet(__privateGet(this,_root),_options));__privateSet(this,_negs,__privateGet(this,_root)===this?[]:__privateGet(__privateGet(this,_root),_negs));"!"!==type||__privateGet(__privateGet(this,_root),_filledNegs)||__privateGet(this,_negs).push(this);__privateSet(this,_parentIndex,__privateGet(this,_parent)?__privateGet(__privateGet(this,_parent),_parts).length:0)}get hasMagic(){if(void 0!==__privateGet(this,_hasMagic))return __privateGet(this,_hasMagic);for(const p4 of __privateGet(this,_parts))if("string"!=typeof p4&&(p4.type||p4.hasMagic))return __privateSet(this,_hasMagic,!0);return __privateGet(this,_hasMagic)}toString(){return void 0!==__privateGet(this,_toString)?__privateGet(this,_toString):this.type?__privateSet(this,_toString,this.type+"("+__privateGet(this,_parts).map((p4=>String(p4))).join("|")+")"):__privateSet(this,_toString,__privateGet(this,_parts).map((p4=>String(p4))).join(""))}push(...parts){for(const p4 of parts)if(""!==p4){if("string"!=typeof p4&&!(p4 instanceof _AST&&__privateGet(p4,_parent)===this))throw new Error("invalid part: "+p4);__privateGet(this,_parts).push(p4)}}toJSON(){var _a8;const ret=null===this.type?__privateGet(this,_parts).slice().map((p4=>"string"==typeof p4?p4:p4.toJSON())):[this.type,...__privateGet(this,_parts).map((p4=>p4.toJSON()))];this.isStart()&&!this.type&&ret.unshift([]);this.isEnd()&&(this===__privateGet(this,_root)||__privateGet(__privateGet(this,_root),_filledNegs)&&"!"===(null==(_a8=__privateGet(this,_parent))?void 0:_a8.type))&&ret.push({});return ret}isStart(){var _a8;if(__privateGet(this,_root)===this)return!0;if(!(null==(_a8=__privateGet(this,_parent))?void 0:_a8.isStart()))return!1;if(0===__privateGet(this,_parentIndex))return!0;const p4=__privateGet(this,_parent);for(let i2=0;i2<__privateGet(this,_parentIndex);i2++){const pp=__privateGet(p4,_parts)[i2];if(!(pp instanceof _AST&&"!"===pp.type))return!1}return!0}isEnd(){var _a8,_b5,_c3;if(__privateGet(this,_root)===this)return!0;if("!"===(null==(_a8=__privateGet(this,_parent))?void 0:_a8.type))return!0;if(!(null==(_b5=__privateGet(this,_parent))?void 0:_b5.isEnd()))return!1;if(!this.type)return null==(_c3=__privateGet(this,_parent))?void 0:_c3.isEnd();const pl=__privateGet(this,_parent)?__privateGet(__privateGet(this,_parent),_parts).length:0;return __privateGet(this,_parentIndex)===pl-1}copyIn(part){"string"==typeof part?this.push(part):this.push(part.clone(this))}clone(parent){const c3=new _AST(this.type,parent);for(const p4 of __privateGet(this,_parts))c3.copyIn(p4);return c3}static fromGlob(pattern,options={}){var _a8;const ast=new _AST(null,void 0,options);__privateMethod(_a8=_AST,_AST_static,parseAST_fn).call(_a8,pattern,ast,0,options);return ast}toMMPattern(){if(this!==__privateGet(this,_root))return __privateGet(this,_root).toMMPattern();const glob=this.toString(),[re,body,hasMagic,uflag]=this.toRegExpSource();if(!(hasMagic||__privateGet(this,_hasMagic)||__privateGet(this,_options).nocase&&!__privateGet(this,_options).nocaseMagicOnly&&glob.toUpperCase()!==glob.toLowerCase()))return body;const flags2=(__privateGet(this,_options).nocase?"i":"")+(uflag?"u":"");return Object.assign(new RegExp(`^${re}$`,flags2),{_src:re,_glob:glob})}get options(){return __privateGet(this,_options)}toRegExpSource(allowDot){var _a8;const dot=null!=allowDot?allowDot:!!__privateGet(this,_options).dot;__privateGet(this,_root)===this&&__privateMethod(this,_AST_instances,fillNegs_fn).call(this);if(!this.type){const noEmpty=this.isStart()&&this.isEnd()&&!__privateGet(this,_parts).some((s2=>"string"!=typeof s2)),src=__privateGet(this,_parts).map((p4=>{var _a9;const[re,_,hasMagic,uflag]="string"==typeof p4?__privateMethod(_a9=_AST,_AST_static,parseGlob_fn).call(_a9,p4,__privateGet(this,_hasMagic),noEmpty):p4.toRegExpSource(allowDot);__privateSet(this,_hasMagic,__privateGet(this,_hasMagic)||hasMagic);__privateSet(this,_uflag,__privateGet(this,_uflag)||uflag);return re})).join("");let start2="";if(this.isStart()&&"string"==typeof __privateGet(this,_parts)[0]&&(1!==__privateGet(this,_parts).length||!justDots.has(__privateGet(this,_parts)[0]))){const aps=addPatternStart,needNoTrav=dot&&aps.has(src.charAt(0))||src.startsWith("\\.")&&aps.has(src.charAt(2))||src.startsWith("\\.\\.")&&aps.has(src.charAt(4)),needNoDot=!dot&&!allowDot&&aps.has(src.charAt(0));start2=needNoTrav?"(?!(?:^|/)\\.\\.?(?:$|/))":needNoDot?"(?!\\.)":""}let end="";this.isEnd()&&__privateGet(__privateGet(this,_root),_filledNegs)&&"!"===(null==(_a8=__privateGet(this,_parent))?void 0:_a8.type)&&(end="(?:$|\\/)");return[start2+src+end,unescape2(src),__privateSet(this,_hasMagic,!!__privateGet(this,_hasMagic)),__privateGet(this,_uflag)]}const repeated="*"===this.type||"+"===this.type,start="!"===this.type?"(?:(?!(?:":"(?:";let body=__privateMethod(this,_AST_instances,partsToRegExp_fn).call(this,dot);if(this.isStart()&&this.isEnd()&&!body&&"!"!==this.type){const s2=this.toString();__privateSet(this,_parts,[s2]);this.type=null;__privateSet(this,_hasMagic,void 0);return[s2,unescape2(this.toString()),!1,!1]}let bodyDotAllowed=!repeated||allowDot||dot?"":__privateMethod(this,_AST_instances,partsToRegExp_fn).call(this,!0);bodyDotAllowed===body&&(bodyDotAllowed="");bodyDotAllowed&&(body=`(?:${body})(?:${bodyDotAllowed})*?`);let final="";final="!"===this.type&&__privateGet(this,_emptyExt)?(this.isStart()&&!dot?"(?!\\.)":"")+"[^/]+?":start+body+("!"===this.type?"))"+(!this.isStart()||dot||allowDot?"":"(?!\\.)")+"[^/]*?)":"@"===this.type?")":"?"===this.type?")?":"+"===this.type&&bodyDotAllowed?")":"*"===this.type&&bodyDotAllowed?")?":`)${this.type}`);return[final,unescape2(body),__privateSet(this,_hasMagic,!!__privateGet(this,_hasMagic)),__privateGet(this,_uflag)]}};_root=new WeakMap;_hasMagic=new WeakMap;_uflag=new WeakMap;_parts=new WeakMap;_parent=new WeakMap;_parentIndex=new WeakMap;_negs=new WeakMap;_filledNegs=new WeakMap;_options=new WeakMap;_toString=new WeakMap;_emptyExt=new WeakMap;_AST_instances=new WeakSet;fillNegs_fn=function(){if(this!==__privateGet(this,_root))throw new Error("should only call on root");if(__privateGet(this,_filledNegs))return this;this.toString();__privateSet(this,_filledNegs,!0);let n3;for(;n3=__privateGet(this,_negs).pop();){if("!"!==n3.type)continue;let p4=n3,pp=__privateGet(p4,_parent);for(;pp;){for(let i2=__privateGet(p4,_parentIndex)+1;!pp.type&&i2<__privateGet(pp,_parts).length;i2++)for(const part of __privateGet(n3,_parts)){if("string"==typeof part)throw new Error("string part in extglob AST??");part.copyIn(__privateGet(pp,_parts)[i2])}p4=pp;pp=__privateGet(p4,_parent)}}return this};_AST_static=new WeakSet;parseAST_fn=function(str,ast,pos,opt){var _a8,_b5;let escaping=!1,inBrace=!1,braceStart=-1,braceNeg=!1;if(null===ast.type){let i3=pos,acc2="";for(;i3<str.length;){const c3=str.charAt(i3++);if(escaping||"\\"===c3){escaping=!escaping;acc2+=c3}else if(inBrace){i3===braceStart+1?"^"!==c3&&"!"!==c3||(braceNeg=!0):"]"!==c3||i3===braceStart+2&&braceNeg||(inBrace=!1);acc2+=c3}else if("["!==c3)if(opt.noext||!isExtglobType(c3)||"("!==str.charAt(i3))acc2+=c3;else{ast.push(acc2);acc2="";const ext2=new _AST(c3,ast);i3=__privateMethod(_a8=_AST,_AST_static,parseAST_fn).call(_a8,str,ext2,i3,opt);ast.push(ext2)}else{inBrace=!0;braceStart=i3;braceNeg=!1;acc2+=c3}}ast.push(acc2);return i3}let i2=pos+1,part=new _AST(null,ast);const parts=[];let acc="";for(;i2<str.length;){const c3=str.charAt(i2++);if(escaping||"\\"===c3){escaping=!escaping;acc+=c3}else if(inBrace){i2===braceStart+1?"^"!==c3&&"!"!==c3||(braceNeg=!0):"]"!==c3||i2===braceStart+2&&braceNeg||(inBrace=!1);acc+=c3}else if("["!==c3)if(isExtglobType(c3)&&"("===str.charAt(i2)){part.push(acc);acc="";const ext2=new _AST(c3,part);part.push(ext2);i2=__privateMethod(_b5=_AST,_AST_static,parseAST_fn).call(_b5,str,ext2,i2,opt)}else if("|"!==c3){if(")"===c3){""===acc&&0===__privateGet(ast,_parts).length&&__privateSet(ast,_emptyExt,!0);part.push(acc);acc="";ast.push(...parts,part);return i2}acc+=c3}else{part.push(acc);acc="";parts.push(part);part=new _AST(null,ast)}else{inBrace=!0;braceStart=i2;braceNeg=!1;acc+=c3}}ast.type=null;__privateSet(ast,_hasMagic,void 0);__privateSet(ast,_parts,[str.substring(pos-1)]);return i2};partsToRegExp_fn=function(dot){return __privateGet(this,_parts).map((p4=>{if("string"==typeof p4)throw new Error("string type in extglob ast??");const[re,_,_hasMagic2,uflag]=p4.toRegExpSource(dot);__privateSet(this,_uflag,__privateGet(this,_uflag)||uflag);return re})).filter((p4=>!(this.isStart()&&this.isEnd()&&!p4))).join("|")};parseGlob_fn=function(glob,hasMagic,noEmpty=!1){let escaping=!1,re="",uflag=!1;for(let i2=0;i2<glob.length;i2++){const c3=glob.charAt(i2);if(escaping){escaping=!1;re+=(reSpecials.has(c3)?"\\":"")+c3}else if("\\"!==c3){if("["===c3){const[src,needUflag,consumed,magic]=parseClass(glob,i2);if(consumed){re+=src;uflag=uflag||needUflag;i2+=consumed-1;hasMagic=hasMagic||magic;continue}}if("*"!==c3)if("?"!==c3)re+=regExpEscape(c3);else{re+="[^/]";hasMagic=!0}else{re+=noEmpty&&"*"===glob?"[^/]+?":"[^/]*?";hasMagic=!0}}else i2===glob.length-1?re+="\\\\":escaping=!0}return[re,unescape2(glob),!!hasMagic,uflag]};__privateAdd(_AST,_AST_static);AST=_AST;escape=(s2,{windowsPathsNoEscape=!1,magicalBraces=!1}={})=>magicalBraces?windowsPathsNoEscape?s2.replace(/[?*()[\]{}]/g,"[$&]"):s2.replace(/[?*()[\]\\{}]/g,"\\$&"):windowsPathsNoEscape?s2.replace(/[?*()[\]]/g,"[$&]"):s2.replace(/[?*()[\]\\]/g,"\\$&");minimatch=(p4,pattern,options={})=>{assertValidPattern(pattern);return!(!options.nocomment&&"#"===pattern.charAt(0))&&new Minimatch(pattern,options).match(p4)};starDotExtRE=/^\*+([^+@!?\*\[\(]*)$/;starDotExtTest=ext2=>f4=>!f4.startsWith(".")&&f4.endsWith(ext2);starDotExtTestDot=ext2=>f4=>f4.endsWith(ext2);starDotExtTestNocase=ext2=>{ext2=ext2.toLowerCase();return f4=>!f4.startsWith(".")&&f4.toLowerCase().endsWith(ext2)};starDotExtTestNocaseDot=ext2=>{ext2=ext2.toLowerCase();return f4=>f4.toLowerCase().endsWith(ext2)};starDotStarRE=/^\*+\.\*+$/;starDotStarTest=f4=>!f4.startsWith(".")&&f4.includes(".");starDotStarTestDot=f4=>"."!==f4&&".."!==f4&&f4.includes(".");dotStarRE=/^\.\*+$/;dotStarTest=f4=>"."!==f4&&".."!==f4&&f4.startsWith(".");starRE=/^\*+$/;starTest=f4=>0!==f4.length&&!f4.startsWith(".");starTestDot=f4=>0!==f4.length&&"."!==f4&&".."!==f4;qmarksRE=/^\?+([^+@!?\*\[\(]*)?$/;qmarksTestNocase=([$0,ext2=""])=>{const noext=qmarksTestNoExt([$0]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f4=>noext(f4)&&f4.toLowerCase().endsWith(ext2)};qmarksTestNocaseDot=([$0,ext2=""])=>{const noext=qmarksTestNoExtDot([$0]);if(!ext2)return noext;ext2=ext2.toLowerCase();return f4=>noext(f4)&&f4.toLowerCase().endsWith(ext2)};qmarksTestDot=([$0,ext2=""])=>{const noext=qmarksTestNoExtDot([$0]);return ext2?f4=>noext(f4)&&f4.endsWith(ext2):noext};qmarksTest=([$0,ext2=""])=>{const noext=qmarksTestNoExt([$0]);return ext2?f4=>noext(f4)&&f4.endsWith(ext2):noext};qmarksTestNoExt=([$0])=>{const len=$0.length;return f4=>f4.length===len&&!f4.startsWith(".")};qmarksTestNoExtDot=([$0])=>{const len=$0.length;return f4=>f4.length===len&&"."!==f4&&".."!==f4};path_posix={sep:"/"};sep="win32"===(defaultPlatform="object"==typeof process&&process?"object"==typeof process.env&&process.env&&process.env.__MINIMATCH_TESTING_PLATFORM__||process.platform:"posix")?"\\":path_posix.sep;minimatch.sep=sep;GLOBSTAR=Symbol("globstar **");minimatch.GLOBSTAR=GLOBSTAR;filter=(pattern,options={})=>p4=>minimatch(p4,pattern,options);minimatch.filter=filter;ext=(a2,b3={})=>Object.assign({},a2,b3);defaults=def=>{if(!def||"object"!=typeof def||!Object.keys(def).length)return minimatch;const orig=minimatch;return Object.assign(((p4,pattern,options={})=>orig(p4,pattern,ext(def,options))),{Minimatch:class Minimatch extends orig.Minimatch{constructor(pattern,options={}){super(pattern,ext(def,options))}static defaults(options){return orig.defaults(ext(def,options)).Minimatch}},AST:class AST extends orig.AST{constructor(type,parent,options={}){super(type,parent,ext(def,options))}static fromGlob(pattern,options={}){return orig.AST.fromGlob(pattern,ext(def,options))}},unescape:(s2,options={})=>orig.unescape(s2,ext(def,options)),escape:(s2,options={})=>orig.escape(s2,ext(def,options)),filter:(pattern,options={})=>orig.filter(pattern,ext(def,options)),defaults:options=>orig.defaults(ext(def,options)),makeRe:(pattern,options={})=>orig.makeRe(pattern,ext(def,options)),braceExpand:(pattern,options={})=>orig.braceExpand(pattern,ext(def,options)),match:(list,pattern,options={})=>orig.match(list,pattern,ext(def,options)),sep:orig.sep,GLOBSTAR})};minimatch.defaults=defaults;braceExpand=(pattern,options={})=>{assertValidPattern(pattern);return options.nobrace||!/\{(?:(?!\{).)*\}/.test(pattern)?[pattern]:expand(pattern)};minimatch.braceExpand=braceExpand;makeRe=(pattern,options={})=>new Minimatch(pattern,options).makeRe();minimatch.makeRe=makeRe;match=(list,pattern,options={})=>{const mm=new Minimatch(pattern,options);list=list.filter((f4=>mm.match(f4)));mm.options.nonull&&!list.length&&list.push(pattern);return list};minimatch.match=match;globMagic=/[?*]|[+@!]\(.*?\)|\[|\]/;regExpEscape2=s2=>s2.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");Minimatch=class{constructor(pattern,options={}){__publicField(this,"options");__publicField(this,"set");__publicField(this,"pattern");__publicField(this,"windowsPathsNoEscape");__publicField(this,"nonegate");__publicField(this,"negate");__publicField(this,"comment");__publicField(this,"empty");__publicField(this,"preserveMultipleSlashes");__publicField(this,"partial");__publicField(this,"globSet");__publicField(this,"globParts");__publicField(this,"nocase");__publicField(this,"isWindows");__publicField(this,"platform");__publicField(this,"windowsNoMagicRoot");__publicField(this,"regexp");assertValidPattern(pattern);options=options||{};this.options=options;this.pattern=pattern;this.platform=options.platform||defaultPlatform;this.isWindows="win32"===this.platform;this.windowsPathsNoEscape=!!options.windowsPathsNoEscape||!1===options.allowWindowsEscape;this.windowsPathsNoEscape&&(this.pattern=this.pattern.replace(/\\/g,"/"));this.preserveMultipleSlashes=!!options.preserveMultipleSlashes;this.regexp=null;this.negate=!1;this.nonegate=!!options.nonegate;this.comment=!1;this.empty=!1;this.partial=!!options.partial;this.nocase=!!this.options.nocase;this.windowsNoMagicRoot=void 0!==options.windowsNoMagicRoot?options.windowsNoMagicRoot:!(!this.isWindows||!this.nocase);this.globSet=[];this.globParts=[];this.set=[];this.make()}hasMagic(){if(this.options.magicalBraces&&this.set.length>1)return!0;for(const pattern of this.set)for(const part of pattern)if("string"!=typeof part)return!0;return!1}debug(..._){}make(){const pattern=this.pattern,options=this.options;if(!options.nocomment&&"#"===pattern.charAt(0)){this.comment=!0;return}if(!pattern){this.empty=!0;return}this.parseNegate();this.globSet=[...new Set(this.braceExpand())];options.debug&&(this.debug=(...args)=>console.error(...args));this.debug(this.pattern,this.globSet);const rawGlobParts=this.globSet.map((s2=>this.slashSplit(s2)));this.globParts=this.preprocess(rawGlobParts);this.debug(this.pattern,this.globParts);let set2=this.globParts.map(((s2,_,__)=>{if(this.isWindows&&this.windowsNoMagicRoot){const isUNC=!(""!==s2[0]||""!==s2[1]||"?"!==s2[2]&&globMagic.test(s2[2])||globMagic.test(s2[3])),isDrive=/^[a-z]:/i.test(s2[0]);if(isUNC)return[...s2.slice(0,4),...s2.slice(4).map((ss=>this.parse(ss)))];if(isDrive)return[s2[0],...s2.slice(1).map((ss=>this.parse(ss)))]}return s2.map((ss=>this.parse(ss)))}));this.debug(this.pattern,set2);this.set=set2.filter((s2=>-1===s2.indexOf(!1)));if(this.isWindows)for(let i2=0;i2<this.set.length;i2++){const p4=this.set[i2];""===p4[0]&&""===p4[1]&&"?"===this.globParts[i2][2]&&"string"==typeof p4[3]&&/^[a-z]:$/i.test(p4[3])&&(p4[2]="?")}this.debug(this.pattern,this.set)}preprocess(globParts){if(this.options.noglobstar)for(let i2=0;i2<globParts.length;i2++)for(let j2=0;j2<globParts[i2].length;j2++)"**"===globParts[i2][j2]&&(globParts[i2][j2]="*");const{optimizationLevel=1}=this.options;if(optimizationLevel>=2){globParts=this.firstPhasePreProcess(globParts);globParts=this.secondPhasePreProcess(globParts)}else globParts=optimizationLevel>=1?this.levelOneOptimize(globParts):this.adjascentGlobstarOptimize(globParts);return globParts}adjascentGlobstarOptimize(globParts){return globParts.map((parts=>{let gs=-1;for(;-1!==(gs=parts.indexOf("**",gs+1));){let i2=gs;for(;"**"===parts[i2+1];)i2++;i2!==gs&&parts.splice(gs,i2-gs)}return parts}))}levelOneOptimize(globParts){return globParts.map((parts=>0===(parts=parts.reduce(((set2,part)=>{const prev=set2[set2.length-1];if("**"===part&&"**"===prev)return set2;if(".."===part&&prev&&".."!==prev&&"."!==prev&&"**"!==prev){set2.pop();return set2}set2.push(part);return set2}),[])).length?[""]:parts))}levelTwoFileOptimize(parts){Array.isArray(parts)||(parts=this.slashSplit(parts));let didSomething=!1;do{didSomething=!1;if(!this.preserveMultipleSlashes){for(let i2=1;i2<parts.length-1;i2++){const p4=parts[i2];if(!(1===i2&&""===p4&&""===parts[0]||"."!==p4&&""!==p4)){didSomething=!0;parts.splice(i2,1);i2--}}if("."===parts[0]&&2===parts.length&&("."===parts[1]||""===parts[1])){didSomething=!0;parts.pop()}}let dd=0;for(;-1!==(dd=parts.indexOf("..",dd+1));){const p4=parts[dd-1];if(p4&&"."!==p4&&".."!==p4&&"**"!==p4){didSomething=!0;parts.splice(dd-1,2);dd-=2}}}while(didSomething);return 0===parts.length?[""]:parts}firstPhasePreProcess(globParts){let didSomething=!1;do{didSomething=!1;for(let parts of globParts){let gs=-1;for(;-1!==(gs=parts.indexOf("**",gs+1));){let gss=gs;for(;"**"===parts[gss+1];)gss++;gss>gs&&parts.splice(gs+1,gss-gs);let next2=parts[gs+1];const p4=parts[gs+2],p22=parts[gs+3];if(".."!==next2)continue;if(!p4||"."===p4||".."===p4||!p22||"."===p22||".."===p22)continue;didSomething=!0;parts.splice(gs,1);const other=parts.slice(0);other[gs]="**";globParts.push(other);gs--}if(!this.preserveMultipleSlashes){for(let i2=1;i2<parts.length-1;i2++){const p4=parts[i2];if(!(1===i2&&""===p4&&""===parts[0]||"."!==p4&&""!==p4)){didSomething=!0;parts.splice(i2,1);i2--}}if("."===parts[0]&&2===parts.length&&("."===parts[1]||""===parts[1])){didSomething=!0;parts.pop()}}let dd=0;for(;-1!==(dd=parts.indexOf("..",dd+1));){const p4=parts[dd-1];if(p4&&"."!==p4&&".."!==p4&&"**"!==p4){didSomething=!0;const splin=1===dd&&"**"===parts[dd+1]?["."]:[];parts.splice(dd-1,2,...splin);0===parts.length&&parts.push("");dd-=2}}}}while(didSomething);return globParts}secondPhasePreProcess(globParts){for(let i2=0;i2<globParts.length-1;i2++)for(let j2=i2+1;j2<globParts.length;j2++){const matched=this.partsMatch(globParts[i2],globParts[j2],!this.preserveMultipleSlashes);if(matched){globParts[i2]=[];globParts[j2]=matched;break}}return globParts.filter((gs=>gs.length))}partsMatch(a2,b3,emptyGSMatch=!1){let ai2=0,bi2=0,result=[],which="";for(;ai2<a2.length&&bi2<b3.length;)if(a2[ai2]===b3[bi2]){result.push("b"===which?b3[bi2]:a2[ai2]);ai2++;bi2++}else if(emptyGSMatch&&"**"===a2[ai2]&&b3[bi2]===a2[ai2+1]){result.push(a2[ai2]);ai2++}else if(emptyGSMatch&&"**"===b3[bi2]&&a2[ai2]===b3[bi2+1]){result.push(b3[bi2]);bi2++}else if("*"!==a2[ai2]||!b3[bi2]||!this.options.dot&&b3[bi2].startsWith(".")||"**"===b3[bi2]){if("*"!==b3[bi2]||!a2[ai2]||!this.options.dot&&a2[ai2].startsWith(".")||"**"===a2[ai2])return!1;if("a"===which)return!1;which="b";result.push(b3[bi2]);ai2++;bi2++}else{if("b"===which)return!1;which="a";result.push(a2[ai2]);ai2++;bi2++}return a2.length===b3.length&&result}parseNegate(){if(this.nonegate)return;const pattern=this.pattern;let negate3=!1,negateOffset=0;for(let i2=0;i2<pattern.length&&"!"===pattern.charAt(i2);i2++){negate3=!negate3;negateOffset++}negateOffset&&(this.pattern=pattern.slice(negateOffset));this.negate=negate3}matchOne(file,pattern,partial=!1){var fi,pi,fl2,pl,p4,f4,fr,pr,swallowee;const options=this.options;if(this.isWindows){const fileDrive="string"==typeof file[0]&&/^[a-z]:$/i.test(file[0]),fileUNC=!fileDrive&&""===file[0]&&""===file[1]&&"?"===file[2]&&/^[a-z]:$/i.test(file[3]),patternDrive="string"==typeof pattern[0]&&/^[a-z]:$/i.test(pattern[0]),fdi=fileUNC?3:fileDrive?0:void 0,pdi=!patternDrive&&""===pattern[0]&&""===pattern[1]&&"?"===pattern[2]&&"string"==typeof pattern[3]&&/^[a-z]:$/i.test(pattern[3])?3:patternDrive?0:void 0;if("number"==typeof fdi&&"number"==typeof pdi){const[fd2,pd]=[file[fdi],pattern[pdi]];if(fd2.toLowerCase()===pd.toLowerCase()){pattern[pdi]=fd2;pdi>fdi?pattern=pattern.slice(pdi):fdi>pdi&&(file=file.slice(fdi))}}}const{optimizationLevel=1}=this.options;optimizationLevel>=2&&(file=this.levelTwoFileOptimize(file));this.debug("matchOne",this,{file,pattern});this.debug("matchOne",file.length,pattern.length);for(fi=0,pi=0,fl2=file.length,pl=pattern.length;fi<fl2&&pi<pl;fi++,pi++){this.debug("matchOne loop");p4=pattern[pi];f4=file[fi];this.debug(pattern,p4,f4);if(!1===p4)return!1;if(p4===GLOBSTAR){this.debug("GLOBSTAR",[pattern,p4,f4]);fr=fi;if((pr=pi+1)===pl){this.debug("** at the end");for(;fi<fl2;fi++)if("."===file[fi]||".."===file[fi]||!options.dot&&"."===file[fi].charAt(0))return!1;return!0}for(;fr<fl2;){swallowee=file[fr];this.debug("\nglobstar while",file,fr,pattern,pr,swallowee);if(this.matchOne(file.slice(fr),pattern.slice(pr),partial)){this.debug("globstar found match!",fr,fl2,swallowee);return!0}if("."===swallowee||".."===swallowee||!options.dot&&"."===swallowee.charAt(0)){this.debug("dot detected!",file,fr,pattern,pr);break}this.debug("globstar swallow a segment, and continue");fr++}if(partial){this.debug("\n>>> no match, partial?",file,fr,pattern,pr);if(fr===fl2)return!0}return!1}let hit;if("string"==typeof p4){hit=f4===p4;this.debug("string match",p4,f4,hit)}else{hit=p4.test(f4);this.debug("pattern match",p4,f4,hit)}if(!hit)return!1}if(fi===fl2&&pi===pl)return!0;if(fi===fl2)return partial;if(pi===pl)return fi===fl2-1&&""===file[fi];throw new Error("wtf?")}braceExpand(){return braceExpand(this.pattern,this.options)}parse(pattern){assertValidPattern(pattern);const options=this.options;if("**"===pattern)return GLOBSTAR;if(""===pattern)return"";let m3,fastTest=null;(m3=pattern.match(starRE))?fastTest=options.dot?starTestDot:starTest:(m3=pattern.match(starDotExtRE))?fastTest=(options.nocase?options.dot?starDotExtTestNocaseDot:starDotExtTestNocase:options.dot?starDotExtTestDot:starDotExtTest)(m3[1]):(m3=pattern.match(qmarksRE))?fastTest=(options.nocase?options.dot?qmarksTestNocaseDot:qmarksTestNocase:options.dot?qmarksTestDot:qmarksTest)(m3):(m3=pattern.match(starDotStarRE))?fastTest=options.dot?starDotStarTestDot:starDotStarTest:(m3=pattern.match(dotStarRE))&&(fastTest=dotStarTest);const re=AST.fromGlob(pattern,this.options).toMMPattern();fastTest&&"object"==typeof re&&Reflect.defineProperty(re,"test",{value:fastTest});return re}makeRe(){if(this.regexp||!1===this.regexp)return this.regexp;const set2=this.set;if(!set2.length){this.regexp=!1;return this.regexp}const options=this.options,twoStar=options.noglobstar?"[^/]*?":options.dot?"(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?":"(?:(?!(?:\\/|^)\\.).)*?",flags2=new Set(options.nocase?["i"]:[]);let re=set2.map((pattern=>{const pp=pattern.map((p4=>{if(p4 instanceof RegExp)for(const f4 of p4.flags.split(""))flags2.add(f4);return"string"==typeof p4?regExpEscape2(p4):p4===GLOBSTAR?GLOBSTAR:p4._src}));pp.forEach(((p4,i2)=>{const next2=pp[i2+1],prev=pp[i2-1];if(p4===GLOBSTAR&&prev!==GLOBSTAR)if(void 0===prev)void 0!==next2&&next2!==GLOBSTAR?pp[i2+1]="(?:\\/|"+twoStar+"\\/)?"+next2:pp[i2]=twoStar;else if(void 0===next2)pp[i2-1]=prev+"(?:\\/|\\/"+twoStar+")?";else if(next2!==GLOBSTAR){pp[i2-1]=prev+"(?:\\/|\\/"+twoStar+"\\/)"+next2;pp[i2+1]=GLOBSTAR}}));const filtered=pp.filter((p4=>p4!==GLOBSTAR));if(this.partial&&filtered.length>=1){const prefixes=[];for(let i2=1;i2<=filtered.length;i2++)prefixes.push(filtered.slice(0,i2).join("/"));return"(?:"+prefixes.join("|")+")"}return filtered.join("/")})).join("|");const[open,close]=set2.length>1?["(?:",")"]:["",""];re="^"+open+re+close+"$";this.partial&&(re="^(?:\\/|"+open+re.slice(1,-1)+close+")$");this.negate&&(re="^(?!"+re+").+$");try{this.regexp=new RegExp(re,[...flags2].join(""))}catch(ex){this.regexp=!1}return this.regexp}slashSplit(p4){return this.preserveMultipleSlashes?p4.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(p4)?["",...p4.split(/\/+/)]:p4.split(/\/+/)}match(f4,partial=this.partial){this.debug("match",f4,this.pattern);if(this.comment)return!1;if(this.empty)return""===f4;if("/"===f4&&partial)return!0;const options=this.options;this.isWindows&&(f4=f4.split("\\").join("/"));const ff2=this.slashSplit(f4);this.debug(this.pattern,"split",ff2);const set2=this.set;this.debug(this.pattern,"set",set2);let filename=ff2[ff2.length-1];if(!filename)for(let i2=ff2.length-2;!filename&&i2>=0;i2--)filename=ff2[i2];for(let i2=0;i2<set2.length;i2++){const pattern=set2[i2];let file=ff2;options.matchBase&&1===pattern.length&&(file=[filename]);if(this.matchOne(file,pattern,partial))return!!options.flipNegate||!this.negate}return!options.flipNegate&&this.negate}static defaults(def){return minimatch.defaults(def).Minimatch}};minimatch.AST=AST;minimatch.Minimatch=Minimatch;minimatch.escape=escape;minimatch.unescape=unescape2;isProposalArrayBufferBase64Available="undefined"!=typeof Uint8Array&&"function"==typeof Uint8Array.prototype.toBase64&&"function"==typeof Uint8Array.fromBase64;base64ToArrayBuffer=isProposalArrayBufferBase64Available?base64ToArrayBufferNative:function base64ToArrayBufferBrowser(base64){if("string"==typeof base64)return base64ToArrayBufferInternalBrowser(base64);const bufItems=base64.map((e3=>base64ToArrayBufferInternalBrowser(e3))),len=bufItems.reduce(((p4,c3)=>p4+c3.byteLength),0),joinedArray=new Uint8Array(len);let offset=0;bufItems.forEach((e3=>{joinedArray.set(new Uint8Array(e3),offset);offset+=e3.byteLength}));return joinedArray.buffer};arrayBufferToBase64Single=isProposalArrayBufferBase64Available?function arrayBufferToBase64SingleNative(buffer){const buf=buffer instanceof Uint8Array?buffer:new Uint8Array(buffer);return Promise.resolve(buf.toBase64())}:async function arrayBufferToBase64SingleBrowser(buffer){const buf=buffer instanceof Uint8Array?buffer:new Uint8Array(buffer);return buf.byteLength<QUANTUM?btoa(String.fromCharCode.apply(null,[...buf])):await arrayBufferToBase64internalBrowser(buf)};arrayBufferToBase64=isProposalArrayBufferBase64Available?function arrayBufferToBase64Native(buffer){const result=(buffer instanceof Uint8Array?buffer:new Uint8Array(buffer)).toBase64();return Promise.resolve([result])}:async function arrayBufferToBase64Browser(buffer){const buf=buffer instanceof Uint8Array?buffer:new Uint8Array(buffer);if(buf.byteLength<QUANTUM)return[btoa(String.fromCharCode.apply(null,[...buf]))];const bufLen=buf.byteLength,pieces=[];let idx2=0;do{const offset=15e7*idx2,pBuf=new DataView(buf.buffer,offset,Math.min(15e7,buf.byteLength-offset));pieces.push(await arrayBufferToBase64internalBrowser(pBuf));idx2++}while(15e7*idx2<bufLen);return pieces};QUANTUM=32768;te=new TextEncoder;td=new TextDecoder;base64ToString=isProposalArrayBufferBase64Available?function base64ToStringNative(base64){try{if("string"!=typeof base64)return base64.map((e3=>base64ToStringNative(e3))).join("");const buffer=base64ToArrayBufferNative(base64),bytes=new Uint8Array(buffer);if(0===bytes.length&&base64.length>0)throw new TypeError("Could not parse the encoded string");return readString(bytes)}catch(ex){Logger("Base64 To String error",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);return"string"!=typeof base64?base64.join(""):base64}}:function base64ToStringBrowser(base64){try{if("string"!=typeof base64)return base64.map((e3=>base64ToStringBrowser(e3))).join("");const binary_string=atob(base64),len=binary_string.length,bytes=new Uint8Array(len);for(let i2=0;i2<len;i2++)bytes[i2]=binary_string.charCodeAt(i2);return readString(bytes)}catch(ex){Logger("Base64 To String error",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);return"string"!=typeof base64?base64.join(""):base64}};regexpBase64=/^[A-Za-z0-9+/]+=*$/;tryConvertBase64ToArrayBuffer=isProposalArrayBufferBase64Available?function tryConvertBase64ToArrayBufferNative(base64){try{const b64F=base64.replace(/\r|\n/g,"");if(!regexpBase64.test(b64F))return!1;const buf=Uint8Array.fromBase64(b64F);return buf.toBase64()===b64F&&buf.byteLength>0&&buf.buffer}catch(e3){return!1}}:function tryConvertBase64ToArrayBufferBrowser(base64){try{const b64F=base64.replace(/\r|\n/g,"");if(!regexpBase64.test(b64F))return!1;const binary_string=globalThis.atob(b64F);if(globalThis.btoa(binary_string)!==b64F)return!1;const len=binary_string.length,bytes=new Uint8Array(len);for(let i2=0;i2<len;i2++)bytes[i2]=binary_string.charCodeAt(i2);return bytes.buffer}catch(e3){return!1}};table={};revTable={};[...function*range2(from,to){for(let i2=from;i2<=to;i2++)yield i2}(192,447)].forEach(((e3,i2)=>{table[i2]=e3;revTable[e3]=i2}));revMap={};numMap={};for(let i2=0;i2<256;i2++){revMap[`00${i2.toString(16)}`.slice(-2)]=i2;numMap[i2]=`00${i2.toString(16)}`.slice(-2)}isProposalArrayBufferBase64Available2="undefined"!=typeof Uint8Array&&"function"==typeof Uint8Array.prototype.toBase64&&"function"==typeof Uint8Array.fromBase64;hexStringToUint8Array=isProposalArrayBufferBase64Available2?function hexStringToUint8ArrayNative(src){return Uint8Array.fromHex(src)}:function hexStringToUint8ArrayBrowser(src){const len=src.length/2,ret=new Uint8Array(len);for(let i2=0;i2<len;i2++)ret[i2]=revMap[src[2*i2]+src[2*i2+1]];return ret};uint8ArrayToHexString=isProposalArrayBufferBase64Available2?function uint8ArrayToHexStringNative(src){return src.toHex()}:function uint8ArrayToHexStringBrowser(src){return[...src].map((e3=>numMap[e3])).join("")};_hashString=function memorizeFuncWithLRUCache(func){const cache2=new LRUCache(100,1e5,!0);return key3=>{if(cache2.has(key3))return cache2.get(key3);const value=func(key3);cache2.set(key3,value);return value}}((async key3=>{const buff=writeString(key3),webcrypto7=await getWebCrypto();let digest=await webcrypto7.subtle.digest("SHA-256",buff);const len=key3.length;for(let i2=0;i2<len;i2++)digest=await webcrypto7.subtle.digest("SHA-256",buff);return uint8ArrayToHexString(new Uint8Array(digest))}));matchOpts={platform:"linux",dot:!0,flipNegate:!0,nocase:!0};delay=(ms,result)=>new Promise((res2=>{setTimeout((()=>{res2(result)}),ms)}));UNRESOLVED=Symbol("UNRESOLVED");promiseWithResolvers=polyfilledFunc="withResolvers"in Promise?function nativePromiseWithResolvers(){const p4=Promise.withResolvers(),{promise,resolve,reject}=p4;return{promise,resolve,reject}}:function polyfillPromiseWithResolvers(){let resolve,reject;return{promise:new Promise(((res2,rej)=>{resolve=res2;reject=rej})),resolve,reject}};promiseWithResolver=polyfilledFunc;noop=()=>{};TIMED_OUT_SIGNAL=Symbol("timed out");isValidRemoteCouchDBURI=uri=>!!uri.startsWith("https://")||!!uri.startsWith("http://");_requestToCouchDBFetch=async(baseUri,username,password,path2,body,method)=>{const utf8str=String.fromCharCode.apply(null,[...writeString(`${username}:${password}`)]),encoded=globalThis.btoa(utf8str),uri=`${baseUri}/${path2}`,requestParam={url:uri,method:method||(body?"PUT":"GET"),headers:new Headers({authorization:"Basic "+encoded,"content-type":"application/json"}),contentType:"application/json",body:JSON.stringify(body)};return await fetch(uri,requestParam)};prefixMapObject={s:{1:"V",2:"W",3:"X",4:"Y",5:"Z"},o:{1:"v",2:"w",3:"x",4:"y",5:"z"}};decodePrefixMapObject=Object.fromEntries(Object.entries(prefixMapObject).flatMap((([prefix,map4])=>Object.entries(map4).map((([len,char])=>[char,{prefix,len:parseInt(len)}])))));prefixMapNumber={n:{1:"a",2:"b",3:"c",4:"d",5:"e"},N:{1:"A",2:"B",3:"C",4:"D",5:"E"}};decodePrefixMapNumber=Object.fromEntries(Object.entries(prefixMapNumber).flatMap((([prefix,map4])=>Object.entries(map4).map((([len,char])=>[char,{prefix,len:parseInt(len)}])))));ARRAY_MARKER="_";OBJECT_MARKER="^";decodeMapConstant={u:void 0,n:null,f:!1,t:!0};SYMBOL_A=Symbol("a");SYMBOL_B=Symbol("b");GENERIC_COMPATIBILITY_VALUE="x-compatibility-value";GENERIC_COMPATIBILITY_SIGNAL="x-compatibility-signal";globalSlipBoard=new class{constructor(){Object.defineProperty(this,"_clip",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}isAwaiting(type,key3){return this._clip.has(`${String(type)}:${key3}`)}issueAndProceed(type,key3="",opt){this.isAwaiting(type,key3)||fireAndForget((async()=>{try{const ret=await opt.callback();this.submit(type,key3,ret)}catch(ex){opt.submitAsSuccess?this.submit(type,key3,opt.transformError?opt.transformError(ex):ex):opt.dropSlipWithRisks?this._clip.delete(type):this.reject(type,key3,ex)}}));return this.awaitNext(type,key3)}async awaitNext(type,key3="",{timeout,onNotAwaited}={timeout:void 0,onNotAwaited:void 0}){let taskPromise=this._clip.get(`${String(type)}:${key3}`);if(!taskPromise){taskPromise=promiseWithResolvers();taskPromise.promise=taskPromise.promise.then((ret=>ret)).finally((()=>{this._clip.delete(`${String(type)}:${key3}`)}));this._clip.set(`${String(type)}:${key3}`,taskPromise);onNotAwaited&&fireAndForget((async()=>(await yieldMicrotask(),onNotAwaited())))}if(timeout){const cDelay=cancelableDelay(timeout);return Promise.race([cDelay.promise,taskPromise.promise.then((ret=>ret)).finally((()=>cDelay.cancel()))])}return await taskPromise.promise}submit(type,key3,data){const taskPromise=this._clip.get(`${String(type)}:${key3}`);taskPromise&&taskPromise.resolve(data)}submitToAll(type,prefix,data){for(const[key3,taskPromise]of this._clip.entries())`${String(key3)}`.startsWith(`${String(type)}:${prefix}`)&&taskPromise.resolve(data)}reject(type,key3="",reason){const taskPromise=this._clip.get(`${String(type)}:${key3}`);taskPromise&&taskPromise.reject(reason)}};throttle=(func,timeout)=>{let timer,lastTime=0;return(...args)=>{if(lastTime){clearTimeout(timer);const delayTime=timeout-(Date.now()-lastTime);timer=setTimeout((()=>{func(...args);lastTime=Date.now()}),delayTime)}else{func(...args);lastTime=Date.now()}}};isIndexDBCmpExist=void 0!==(null==(_a=null==globalThis?void 0:globalThis.indexedDB)?void 0:_a.cmp);globalConcurrencyController=Semaphore(50);map={"\n":"\\n","\r":"\\r","\\":"\\\\"};revMap2={"\\n":"\n","\\r":"\r","\\\\":"\\"};previousValues=new Map;MARK_DELETED="__DELETED";MARK_ISARRAY="__ARRAY";MARK_SWAPPED="__SWAP";CustomRegExp=class{constructor(regexp,flags2){const[negate3,exp]=parseCustomRegExp(regexp);this.pattern=exp;this.regexp=new RegExp(exp,flags2);this.negate=negate3}test(str){return this.negate?!this.regexp.test(str):this.regexp.test(str)}};FallbackWeakRef="WeakRef"in globalThis?globalThis.WeakRef:(_a2=class WeakRef{constructor(target){Object.defineProperty(this,"__target",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this.__target=target}deref(){return this.__target}},Object.defineProperty(_a2,"__",{enumerable:!0,configurable:!0,writable:!0,value:console.warn("WeakRef is not supported in this environment. Using a fallback implementation. This may cause memory leaks. Please consider upgrading your browser or Node.js version. If you are on Android, please consider changing your WebView engine to a newer version. It is on the Developer Settings.")}),_a2);"FinalizationRegistry"in globalThis&&globalThis.FinalizationRegistry;LiveSyncError=class _LiveSyncError extends Error{constructor(message,options){super(message);this.name=this.constructor.name;(null==options?void 0:options.cause)&&(this.cause=options.cause instanceof Error?options.cause:new Error(`${options.cause}`));void 0!==(null==options?void 0:options.status)&&(this.overrideStatus=options.status)}get status(){return void 0!==this.overrideStatus?this.overrideStatus:this.cause&&"status"in this.cause?this.cause.status:500}static isCausedBy(error,errorClass){return!!error&&(error instanceof errorClass||!!error.cause&&_LiveSyncError.isCausedBy(error.cause,errorClass))}static fromError(error){if(error instanceof this)return error;const instance3=new this(`${this.name}: ${null==error?void 0:error.message}`,{cause:error});(null==error?void 0:error.stack)?instance3.stack=error.stack:instance3.stack=(new Error).stack;return instance3}};LiveSyncFatalError=class extends LiveSyncError{};ChunkFetcher=class{constructor(options){this.queue=[];this.abort=new AbortController;this.onEventHandler=this.onEvent.bind(this);this.currentProcessing=0;this.previousRequestTime=0;this.options=options;this.chunkManager.addListener("missingChunks",this.onEventHandler,{signal:this.abort.signal})}get chunkManager(){return this.options.chunkManager}get interval(){return this.options.settings.minimumIntervalOfReadChunksOnline||DEFAULT_SETTINGS.minimumIntervalOfReadChunksOnline}get concurrency(){return this.options.settings.concurrencyOfReadChunksOnline||DEFAULT_SETTINGS.concurrencyOfReadChunksOnline}destroy(){this.abort.abort();this.queue=[]}onEvent(ids){this.queue=unique([...this.queue,...ids]);this.canRequestMore()&&setTimeout((()=>{this.requestMissingChunks()}),1)}canRequestMore(){return this.currentProcessing<this.concurrency&&this.queue.length>0}async requestMissingChunks(){if(this.canRequestMore())try{let isValidChunk2=function(chunk){return chunk&&"string"==typeof(null==chunk?void 0:chunk._id)&&"string"==typeof(null==chunk?void 0:chunk.data)};this.currentProcessing++;const requestIDs=this.queue.splice(0,100),now3=Date.now(),timeSinceLastRequest=now3-this.previousRequestTime;this.previousRequestTime=now3;const timeToWait=Math.max(this.interval-timeSinceLastRequest,0);timeToWait>0&&await delay(timeToWait);const replicator=this.options.getActiveReplicator();if(!replicator){Logger("No active replicator was found to request missing chunks.");return}const fetched=await replicator.fetchRemoteChunks(requestIDs,!1);if(!fetched){Logger(`No chunks were found for the following IDs: ${requestIDs.join(", ")}`);for(const chunkID of requestIDs)this.chunkManager.emitEvent("missingChunkRemote",chunkID);return}const chunks=fetched.filter((chunk=>isValidChunk2(chunk)));if(chunks.length!==fetched.length){Logger(`Some fetched chunks are invalid and will be ignored: (${fetched.length-chunks.length} / ${fetched.length}).`,LOG_LEVEL_VERBOSE);for(const chunk of fetched)isValidChunk2(chunk)||Logger(`Invalid chunk: ${JSON.stringify(chunk)}`,LOG_LEVEL_VERBOSE)}0===chunks.length&&Logger(`No valid chunks were found for the following IDs: ${requestIDs.join(", ")}`);const missingIDs=requestIDs.filter((id=>!chunks.some((chunk=>chunk._id===id))));try{if(0===chunks.length)return;Logger(`Writing fetched chunks (${chunks.length}) to the database...`);!0===(await this.chunkManager.write(chunks,{skipCache:!0,force:!0},"ChunkFetcher")).result?Logger(`Fetched chunks were stored successfully: ${chunks.length}`,LOG_LEVEL_VERBOSE):Logger(`Fetched chunks could not be stored: ${chunks.map((chunk=>chunk._id)).join(", ")}`,LOG_LEVEL_VERBOSE)}catch(error){Logger(`An error occurred while storing fetched chunks: ${error}`,LOG_LEVEL_VERBOSE)}finally{for(const chunk of chunks)this.chunkManager.emitEvent(EVENT_CHUNK_FETCHED,chunk);for(const chunkID of missingIDs)this.chunkManager.emitEvent("missingChunkRemote",chunkID)}}finally{this.currentProcessing--;this.previousRequestTime=Date.now();this.queue.length>0&&setTimeout((()=>{this.requestMissingChunks()}),0)}}};Symbol("fallback");EVENT_CHUNK_FETCHED="chunkFetched";ChunkManager=class{constructor(options){this.eventTarget=new EventTarget;this.maxCacheSize=1e5;this.caches=new Map;this.waitingMap=new Map;this.allocCount=0;this.derefCount=0;this.onChunkArrivedHandler=this.onChunkArrived.bind(this);this.onChangeHandler=this.onChange.bind(this);this.onMissingChunkRemoteHandler=this.onMissingChunkRemote.bind(this);this.abort=new AbortController;this.initialised=Promise.resolve();this.concurrentTransactions=0;this.stabilised=Promise.resolve();this.options=options;this.caches=new Map;this.changeHandler=this.changeManager.addCallback(this.onChangeHandler);this.addListener(EVENT_CHUNK_FETCHED,this.onChunkArrivedHandler,{signal:this.abort.signal});this.addListener("missingChunkRemote",this.onMissingChunkRemoteHandler,{signal:this.abort.signal});this.initialised=this._initialise()}get changeManager(){return this.options.changeManager}get database(){return this.options.database}addListener(type,listener,options){const callback=ev=>{listener.call(this,ev.detail)};this.eventTarget.addEventListener(type,callback,options);return()=>{this.eventTarget.removeEventListener(type,callback,options)}}emitEvent(type,detail){const event2=new CustomEvent(type,{detail});this.eventTarget.dispatchEvent(event2)}clearCaches(){this.caches.clear();this.allocCount=0;this.derefCount=0}getCachedChunk(id){if(!this.caches.has(id))return!1;const weakRef=this.caches.get(id);if(weakRef){const cachedChunk=weakRef.deref();if(cachedChunk)return cachedChunk;this.derefCount++;this.deleteCachedChunk(id);return!1}return!1}getChunkIDFromCache(data){for(const[id,weakRef]of this.caches){const chunk=weakRef.deref();if(chunk){if(chunk.data===data)return id}else{this.derefCount++;this.deleteCachedChunk(id)}}return!1}cacheChunk(chunk){var _a8;if(this.getCachedChunk(chunk._id)){this.reorderChunk(chunk._id);return}this.caches.set(chunk._id,new FallbackWeakRef(chunk));this.allocCount++;const maxCacheSize=null!=(_a8=this.maxCacheSize)?_a8:1e5;if(this.caches.size>maxCacheSize)do{const firstKey=this.caches.keys().next().value;firstKey&&this.caches.delete(firstKey)}while(this.caches.size>maxCacheSize)}reorderChunk(id){const chunk=this.getCachedChunk(id);if(chunk){this.caches.delete(id);this.caches.set(id,new FallbackWeakRef(chunk))}}deleteCachedChunk(id){this.caches.has(id)&&this.caches.delete(id)}_enqueueWaiting(id,timeout){const previous=this.waitingMap.get(id);if(previous)return previous.resolver.promise;const resolver2=promiseWithResolver();this.waitingMap.set(id,{resolver:resolver2});return withTimeout(resolver2.promise,timeout,(()=>{const current=this.waitingMap.get(id);current&&current.resolver===resolver2&&this.waitingMap.delete(id);return!1}))}onChunkArrived(doc,deleted=!1){const id=doc._id;if(this.waitingMap.has(id)){const queue2=this.waitingMap.get(id);this.waitingMap.delete(id);if(doc._deleted||deleted)queue2.resolver.resolve(!1);else{queue2.resolver.resolve(doc);this.cacheChunk(doc)}}}onChange(change){const doc=change.doc;doc&&doc._id&&"leaf"===doc.type&&this.onChunkArrived(doc,change.deleted)}onMissingChunkRemote(id){if(this.waitingMap.has(id)){const queue2=this.waitingMap.get(id);this.waitingMap.delete(id);queue2.resolver.resolve(!1)}}async _initialise(){Logger("ChunkManager initialised",LOG_LEVEL_VERBOSE);return await Promise.resolve()}destroy(){this.abort.abort();this.changeHandler();this.caches.clear();this.waitingMap.clear()}async readSingle(id,options){var _a8;if(!options.skipCache){const cachedChunk=this.getCachedChunk(id);if(cachedChunk){this.reorderChunk(id);return cachedChunk}}try{const result=await this.database.get(id);if(result&&isChunkDoc(result)){this.cacheChunk(result);return result}}catch(error){if(!isMissingError(error))throw new LiveSyncError(`Failed to read chunk ${id}`,{status:404,cause:error})}const timeout=null!=(_a8=options.timeout)?_a8:15e3;if(timeout>0){const ret=this._enqueueWaiting(id,timeout);options.preventRemoteRequest||this.emitEvent("missingChunks",[id]);return ret}return!1}_readFromCache(readIds,resultMap){const cachedChunks=[...readIds].map((id=>this.getCachedChunk(id))).filter((chunk=>!1!==chunk));for(const chunk of cachedChunks){this.reorderChunk(chunk._id);resultMap.set(chunk._id,chunk);readIds.delete(chunk._id)}}async _readFromDatabase(readIds,resultMap){const results=await this.database.allDocs({keys:[...readIds],include_docs:!0});for(const row of results.rows)if("doc"in row&&row.doc){const chunk=row.doc;resultMap.set(chunk._id,chunk);readIds.delete(chunk._id);this.cacheChunk(chunk)}else if(!isMissingError(row))throw new LiveSyncError(`Failed to read chunk ${row.key}`,{status:404,cause:getError(row)})}async _waitForArrival(options,readIds,resultMap){var _a8;const timeout=null!=(_a8=options.timeout)?_a8:15e3;if(timeout>0){const tasks3=[...readIds].map((id=>this._enqueueWaiting(id,timeout)));options.preventRemoteRequest||this.emitEvent("missingChunks",[...readIds]);const results=await Promise.all(tasks3);for(const chunk of results)if(chunk){resultMap.set(chunk._id,chunk);readIds.delete(chunk._id);this.cacheChunk(chunk)}}}_readPreloadedChunks(preloadedChunks,readIds,resultMap){for(const[id,chunk]of Object.entries(preloadedChunks))if(isChunkDoc(chunk)){this.cacheChunk(chunk);resultMap.set(id,chunk);readIds.delete(id)}}async read(ids,options,preloadedChunks){const order=[...ids],resultMap=new Map(ids.map((id=>[id,!1]))),readIds=new Set([...resultMap.keys()]);preloadedChunks&&this._readPreloadedChunks(preloadedChunks,readIds,resultMap);options.skipCache||this._readFromCache(readIds,resultMap);readIds.size>0&&await this._readFromDatabase(readIds,resultMap);readIds.size>0&&await this._waitForArrival(options,readIds,resultMap);return order.map((id=>resultMap.get(id)||!1))}async write(chunks,options,origin2){let storeChunks=chunks;const writeResult={result:!0,processed:{cached:0,hotPack:0,written:0,duplicated:0}},total=storeChunks.length;options.skipCache||(storeChunks=storeChunks.filter((chunk=>{if(this.getCachedChunk(chunk._id)){this.reorderChunk(chunk._id);return!1}return!0})));const afterPhase1=storeChunks.length;writeResult.processed.cached=total-afterPhase1;if(0===storeChunks.length)return writeResult;const result=await this.database.bulkDocs(storeChunks,{new_edits:!(null==options?void 0:options.force)}),failed2=result.filter((res2=>"error"in res2));if(failed2.some((res2=>409!==res2.status)))throw new LiveSyncError(`Failed to write chunks: ${failed2.map((res2=>res2.error)).join(", ")}`,{status:500});const conflictedChunkIDs=failed2.filter((res2=>"string"==typeof res2.id)).map((res2=>res2.id));if(conflictedChunkIDs.length>0){writeResult.processed.duplicated=conflictedChunkIDs.length;const conflictedChunks=(await this.read(conflictedChunkIDs,{skipCache:!1,timeout:0})).filter((chunk=>!1!==chunk)),originalChunks=buildChunkMap(chunks);for(const chunk of conflictedChunks){const originalChunk=originalChunks.get(chunk._id);if(!originalChunk||originalChunk.data!==chunk.data){this.deleteCachedChunk(chunk._id);throw new LiveSyncFatalError(`Inconsistent chunk data for ${chunk._id}: local data differs from remote data. This is a fatal error.`)}this.cacheChunk(chunk)}}const writeCount=result.length-failed2.length;writeResult.processed.written=writeCount;for(const chunk of storeChunks)this.cacheChunk(chunk);return writeResult}async transaction(callback){await this.initialised;await this.stabilised;this.concurrentTransactions++;try{return await callback()}finally{this.concurrentTransactions--;if(0===this.concurrentTransactions){Logger("All transactions completed. Performing stabilisation.",LOG_LEVEL_VERBOSE);await this._stabilise()}else Logger(`Transaction completed. Remaining: ${this.concurrentTransactions}`,LOG_LEVEL_VERBOSE)}}async _stabilise(){const pr=promiseWithResolver();this.stabilised=pr.promise;try{await this.__stabilise()}finally{pr.resolve()}}__stabilise(){return Promise.resolve()}};EventHub=class{constructor(emitter){Object.defineProperty(this,"_emitter",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_assigned",{enumerable:!0,configurable:!0,writable:!0,value:new Map});Object.defineProperty(this,"_allAssigned",{enumerable:!0,configurable:!0,writable:!0,value:new Map});this._emitter=null!=emitter?emitter:new EventTarget}_issueSignal(key3,callback){var _a8;let assigned=this._assigned.get(key3);void 0===assigned&&(assigned=new WeakMap);const controllerRef=assigned.get(callback);let controller=null==controllerRef?void 0:controllerRef.deref();if(!controller||controller.signal.aborted){controller=new AbortController;const refController=new FallbackWeakRef(controller);controller.signal.addEventListener("abort",(()=>{var _a9,_b5;null==(_a9=this._assigned.get(key3))||_a9.delete(callback);null==(_b5=this._allAssigned.get(key3))||_b5.delete(refController)}),{once:!0});assigned.set(callback,refController);this._assigned.set(key3,assigned);const allAssigned=null!=(_a8=this._allAssigned.get(key3))?_a8:new Set;allAssigned.add(refController);this._allAssigned.set(key3,allAssigned);return controller}return controller}emitEvent(event2,data){this._emitter.dispatchEvent(new CustomEvent(`${event2.toString()}`,{detail:null!=data?data:void 0}))}on(event2,callback,options){const key3=event2,controller=this._issueSignal(key3,callback);this._emitter.addEventListener(key3,(e3=>{callback(e3,e3 instanceof CustomEvent?null==e3?void 0:e3.detail:void 0)}),{...options,signal:controller.signal});return()=>this.off(event2,callback)}off(event2,callback){var _a8,_b5;const key3=event2;if(callback){const w2=null==(_a8=this._assigned.get(key3))?void 0:_a8.get(callback),controller=null==w2?void 0:w2.deref();null==controller||controller.abort()}else null==(_b5=this._allAssigned.get(key3))||_b5.forEach((w2=>{const controller=w2.deref();null==controller||controller.abort()}))}offAll(){for(const[key3]of this._allAssigned)this.off(key3)}onEvent(event2,callback,options){const key3=event2,controller=this._issueSignal(key3,callback);this._emitter.addEventListener(key3,(e3=>{callback(e3 instanceof CustomEvent?null==e3?void 0:e3.detail:void 0)}),{...options,signal:controller.signal});return()=>this.off(event2,callback)}once(event2,callback){return this.on(event2,callback,{once:!0})}onceEvent(event2,callback){return this.on(event2,((_,data)=>callback(data)),{once:!0})}waitFor(event2){return new Promise((resolve=>{this.onceEvent(event2,(data=>{resolve(data)}))}))}};InterceptiveEventTarget=class extends EventTarget{constructor(onBeforeDispatch,onAfterDispatch){super();Object.defineProperty(this,"_onBeforeDispatch",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_onAfterDispatch",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this._onBeforeDispatch=onBeforeDispatch;this._onAfterDispatch=onAfterDispatch}dispatchEvent(event2){if(!event2.cancelable)return super.dispatchEvent(event2);if(this._onBeforeDispatch&&!this._onBeforeDispatch(event2))return!1;const result=super.dispatchEvent(event2);return result&&this._onAfterDispatch?this._onAfterDispatch(event2):result}};WrappedEvent=class extends CustomEvent{constructor(event2){super("wrappedEvent.event.globalChannel",{detail:{originalEvent:event2}})}};new class extends InterceptiveEventTarget{constructor(){super();globalThis.addEventListener("wrappedEvent.event.globalChannel",(event2=>{this.dispatchEvent(event2)}),{once:!0});this._onAfterDispatch=event2=>{event2 instanceof WrappedEvent?super.dispatchEvent(event2.detail.originalEvent):globalThis.dispatchEvent(new WrappedEvent(event2));return!0}}};eventHub=new EventHub;LiveSyncLocalDB=class{constructor(dbname,env){this.isReady=!1;this.needScanning=!1;this.auth={username:"",password:""};this.dbname=dbname;this.env=env;this.refreshSettings()}get managers(){return this.env.managers}clearCaches(){this.managers.clearCaches()}async _prepareHashFunctions(){var _a8;await(null==(_a8=this.managers)?void 0:_a8.prepareHashFunction())}onunload(){this.env.services.databaseEvents.onUnloadDatabase(this);this.localDatabase.removeAllListeners()}refreshSettings(){const settings=this.env.getSettings();this.settings=settings;this._prepareHashFunctions()}async close(){var _a8;Logger("Database closed (by close)");this.isReady=!1;null==(_a8=this.offRemoteChunkFetchedHandler)||_a8.call(this);null!=this.localDatabase&&await this.localDatabase.close();await this.env.services.databaseEvents.onUnloadDatabase(this)}onNewLeaf(chunk){var _a8;null==(_a8=this.managers.chunkManager)||_a8.emitEvent(EVENT_CHUNK_FETCHED,chunk)}async initializeDatabase(){await this._prepareHashFunctions();null!=this.localDatabase&&await this.localDatabase.close();this.localDatabase=null;this.localDatabase=this.env.services.database.createPouchDBInstance(this.dbname+SuffixDatabaseName,{auto_compaction:!1,revs_limit:100,deterministic_revs:!0});await this.env.services.databaseEvents.onDatabaseInitialisation(this)||Logger("Initializing Database has been failed on some module",LOG_LEVEL_NOTICE);Logger("Opening Database...");Logger("Database info",LOG_LEVEL_VERBOSE);Logger(JSON.stringify(await this.localDatabase.info(),null,2),LOG_LEVEL_VERBOSE);await this.managers.initManagers();this.localDatabase.on("close",(()=>{var _a8;Logger("Database closed.");this.isReady=!1;this.localDatabase.removeAllListeners();null==(_a8=this.env.services.replicator.getActiveReplicator())||_a8.closeReplication();this.managers.teardownManagers()}));const _instance2=new FallbackWeakRef(this),unload=eventHub.onEvent("remote-chunk-fetched",(chunk=>{var _a8;null==_instance2.deref()&&unload();null==(_a8=_instance2.deref())||_a8.onNewLeaf(chunk)}));this.offRemoteChunkFetchedHandler=unload;this.isReady=!0;Logger("Database is now ready.");return!0}async allChunks(includeDeleted=!1){const used=new Set,existing=new Map;let since=0;for(;;){const changes3=await this.localDatabase.changes({since,limit:100,include_docs:!0,conflicts:!0,style:includeDeleted?"all_docs":"main_only"});if(0==changes3.results.length)break;for(const change of changes3.results){const doc=change.doc;if("leaf"==doc.type){if(doc._deleted&&!includeDeleted)continue;existing.set(doc._id,doc)}if("children"in doc){if(change.deleted&&(!doc._conflicts||0==doc._conflicts.length))continue;doc.children.forEach((e3=>used.add(e3)));if(doc._conflicts){const mineRevInfo=(await this.localDatabase.get(doc._id,{revs:!0,revs_info:!0}))._revs_info||[],keepRevs=new Set;for(const conflict of doc._conflicts){const conflictedRevInfo=(await this.localDatabase.get(doc._id,{rev:conflict,revs:!0,revs_info:!0}))._revs_info||[],diffRevs=mineRevInfo.filter((e3=>!conflictedRevInfo.some((f4=>f4.rev==e3.rev&&f4.status==e3.status)))),diffRevs2=conflictedRevInfo.filter((e3=>!mineRevInfo.some((f4=>f4.rev==e3.rev&&f4.status==e3.status)))),diffRevs3=diffRevs.concat(diffRevs2),sameRevs=mineRevInfo.filter((e3=>conflictedRevInfo.some((f4=>f4.rev==e3.rev&&f4.status==e3.status)))).filter((e3=>"available"==e3.status)).sort(((a2,b3)=>getNoFromRev(b3.rev)-getNoFromRev(a2.rev))),sameRevsTop=sameRevs.length>0?[sameRevs[0].rev]:[];[...diffRevs3.filter((e3=>"available"==e3.status)).map((e3=>e3.rev)),...sameRevsTop].forEach((e3=>keepRevs.add(e3)))}const detail=await this.localDatabase.bulkGet({docs:[...keepRevs.values()].map((e3=>({id:doc._id,rev:e3})))});for(const e3 of detail.results)if("docs"in e3){const docs=e3.docs;for(const doc2 of docs)"ok"in doc2&&"children"in doc2.ok&&doc2.ok.children.forEach((e4=>used.add(e4)))}}}}since=changes3.results[changes3.results.length-1].seq}return{used,existing}}async resetDatabase(){var _a8;await this.managers.teardownManagers();null==(_a8=this.env.services.replicator.getActiveReplicator())||_a8.closeReplication();if(!await this.env.services.databaseEvents.onResetDatabase(this)){Logger("Database reset has been prevented or failed on some modules.",LOG_LEVEL_NOTICE);return!1}Logger("Database closed for reset Database.");this.isReady=!1;await this.localDatabase.destroy();this.localDatabase=null;await this.initializeDatabase();Logger("Local Database Reset",LOG_LEVEL_NOTICE);return!0}async*findEntries(startKey,endKey,opt){let nextKey=startKey;""==endKey&&(endKey="􏿿");let req=this.allDocsRaw({limit:100,startkey:nextKey,endkey:endKey,include_docs:!0,...opt});do{const docs=await req;if(0===docs.rows.length)break;nextKey=`${docs.rows[docs.rows.length-1].id}`;req=this.allDocsRaw({limit:100,skip:1,startkey:nextKey,endkey:endKey,include_docs:!0,...opt});for(const row of docs.rows){const doc=row.doc;"type"in doc&&("newnote"!=doc.type&&"plain"!=doc.type||(yield doc))}}while(""!=nextKey)}async*findAllDocs(opt){const targets=[()=>this.findEntries("","_",null!=opt?opt:{}),()=>this.findEntries("_􏿿","h:",null!=opt?opt:{}),()=>this.findEntries("h:􏿿","",null!=opt?opt:{})];for(const targetFun of targets)yield*targetFun()}async*findEntryNames(startKey,endKey,opt){let nextKey=startKey;""==endKey&&(endKey="􏿿");let req=this.allDocsRaw({limit:100,startkey:nextKey,endkey:endKey,...opt});do{const docs=await req;if(0==docs.rows.length){nextKey="";break}nextKey=`${docs.rows[docs.rows.length-1].key}`;req=this.allDocsRaw({limit:100,skip:1,startkey:nextKey,endkey:endKey,...opt});for(const row of docs.rows)yield row.id}while(""!=nextKey)}async*findAllDocNames(opt){const targets=[()=>this.findEntryNames("","_",null!=opt?opt:{}),()=>this.findEntryNames("_􏿿","h:",null!=opt?opt:{}),()=>this.findEntryNames("h:􏿿","i:",null!=opt?opt:{}),()=>this.findEntryNames("i:􏿿","ix:",null!=opt?opt:{}),()=>this.findEntryNames("ix:􏿿","ps:",null!=opt?opt:{}),()=>this.findEntryNames("ps:􏿿","",null!=opt?opt:{})];for(const targetFun of targets){const target=targetFun();for await(const f4 of target)f4.startsWith("_")||"obsydian_livesync_version"!=f4&&(yield f4)}}async*findAllNormalDocs(opt){const targets=[()=>this.findEntries("","_",null!=opt?opt:{}),()=>this.findEntries("_􏿿","h:",null!=opt?opt:{}),()=>this.findEntries("h:􏿿","i:",null!=opt?opt:{}),()=>this.findEntries("i:􏿿","ix:",null!=opt?opt:{}),()=>this.findEntries("ix:􏿿","ps:",null!=opt?opt:{}),()=>this.findEntries("ps:􏿿","",null!=opt?opt:{})];for(const targetFun of targets){const target=targetFun();for await(const f4 of target)f4._id.startsWith("_")||"newnote"!=f4.type&&"plain"!=f4.type||(yield f4)}}async removeRevision(docId,revision){try{const doc=await this.localDatabase.get(docId,{rev:revision});doc._deleted=!0;await this.localDatabase.put(doc);return!0}catch(ex){isErrorOfMissingDoc(ex)&&Logger(`Remove revision: Missing target revision, ${docId}-${revision}`,LOG_LEVEL_VERBOSE)}return!1}getRaw(docId,options){return this.localDatabase.get(docId,options||{})}removeRaw(docId,revision,options){return this.localDatabase.remove(docId,revision,options||{})}putRaw(doc,options){return this.localDatabase.put(doc,options||{})}allDocsRaw(options){return this.localDatabase.allDocs(options)}bulkDocsRaw(docs,options){return this.localDatabase.bulkDocs(docs,options||{})}isTargetFile(filenameSrc){return this.managers.entryManager.isTargetFile(filenameSrc)}async getDBEntryMeta(path2,opt,includeDeleted=!1){return await this.managers.entryManager.getDBEntryMeta(path2,opt,includeDeleted)}async getDBEntry(path2,opt,dump=!1,waitForReady=!0,includeDeleted=!1){return await this.managers.entryManager.getDBEntry(path2,opt,dump,waitForReady,includeDeleted)}async getDBEntryFromMeta(meta,dump=!1,waitForReady=!0){return await this.managers.entryManager.getDBEntryFromMeta(meta,dump,waitForReady)}async deleteDBEntry(path2,opt){return await this.managers.entryManager.deleteDBEntry(path2,opt)}async putDBEntry(note,onlyChunks){return await this.managers.entryManager.putDBEntry(note,onlyChunks)}async getConflictedDoc(path2,rev3){return await this.managers.conflictManager.getConflictedDoc(path2,rev3)}async tryAutoMerge(path2,enableMarkdownAutoMerge){return await this.managers.conflictManager.tryAutoMerge(path2,enableMarkdownAutoMerge)}};LiveSyncAbstractReplicator=class{constructor(env){this.syncStatus="NOT_CONNECTED";this.docArrived=0;this.docSent=0;this.lastSyncPullSeq=0;this.maxPullSeq=0;this.lastSyncPushSeq=0;this.maxPushSeq=0;this.nodeid="";this.remoteLocked=!1;this.remoteCleaned=!1;this.remoteLockedAndDeviceNotAccepted=!1;this.tweakSettingsMismatched=!1;this.updateInfo=()=>{this.env.replicationStat.value={sent:this.docSent,arrived:this.docArrived,maxPullSeq:this.maxPullSeq,maxPushSeq:this.maxPushSeq,lastSyncPullSeq:this.lastSyncPullSeq,lastSyncPushSeq:this.lastSyncPushSeq,syncStatus:this.syncStatus}};this.env=env}async ensurePBKDF2Salt(setting,showMessage=!1,useCache=!0){try{const hash3=await this.getReplicationPBKDF2Salt(setting,!useCache);if(0==hash3.length)throw new Error("PBKDF2 salt (Security Seed) is empty");Logger(`PBKDF2 salt (Security Seed): ${await arrayBufferToBase64Single(hash3)}`,LOG_LEVEL_VERBOSE);return!0}catch(ex){Logger("Failed to obtain PBKDF2 salt (Security Seed) for replication",showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async initializeDatabaseForReplication(){const db=this.env.getDatabase();try{const nodeinfo=await resolveWithIgnoreKnownError(db.get(NODEINFO_DOCID),{_id:NODEINFO_DOCID,type:"nodeinfo",nodeid:"",v20220607:!0});if(""==nodeinfo.nodeid){nodeinfo.nodeid=Math.random().toString(36).slice(-10);await db.put(nodeinfo)}this.nodeid=nodeinfo.nodeid;return!0}catch(ex){Logger(ex)}return!1}};CHeader="h:";PSCHeader="ps:";ICHeaderLength=(ICHeader="i:").length;ICXHeader="ix:";serializedMap=new Map;queueCount=new Map;waitingProcessMap=new Map;shareSerializedMap=new Map;skipDuplicatedMap=new Map;Symbol("SKIPPED");Symbol("skipped");tasks=new Map;intervals={};waitingItems=new Set;PersistentMap=class{flush(){this._save()}_save(){localStorage.setItem(this._key,JSON.stringify([...this._map.entries()]))}_load(suppliedEntries=[]){var _a8;try{const savedSource=null!=(_a8=localStorage.getItem(this._key))?_a8:"",sourceToParse=""===savedSource?"[]":savedSource,obj=JSON.parse(sourceToParse);this._map=new Map([...obj,...suppliedEntries])}catch(ex){console.log(`Map read error : ${this._key}`);console.dir(ex);this._map=new Map([...suppliedEntries])}return Promise.resolve()}_queueSave(){this._setCount--;if(this._setCount<0){this._setCount=100;scheduleTask(`save-map-${this._key}`,0,(()=>this._save()))}scheduleTask(`save-map-${this._key}`,150,(()=>this._save()))}delete(key3){const ret=this._map.delete(key3);this._queueSave();return ret}has(key3){return this._map.has(key3)}set(key3,value){this._map.set(key3,value);this._queueSave();return this}clear(){this._map=new Map;this._save()}get(key3,defValue){const v2=this._map.get(key3);return void 0===v2?defValue:v2}constructor(key3,entries2){Object.defineProperty(this,"_setCount",{enumerable:!0,configurable:!0,writable:!0,value:100});Object.defineProperty(this,"_map",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_key",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this._key=key3;this._map=new Map(null!=entries2?entries2:[]);this._load(entries2)}};EVENT_LAYOUT_READY="layout-ready";EVENT_SETTING_SAVED="setting-saved";EVENT_DATABASE_REBUILT="database-rebuilt";EVENT_REQUEST_OPEN_SETUP_URI2="request-open-setup-uri";EVENT_REQUEST_COPY_SETUP_URI2="request-copy-setup-uri";EVENT_REQUEST_SHOW_SETUP_QR="request-show-setup-qr";EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG2="request-open-plugin-sync-dialog";EVENT_REQUEST_RUN_DOCTOR="request-run-doctor";EVENT_REQUEST_RUN_FIX_INCOMPLETE="request-run-fix-incomplete";EVENT_ANALYSE_DB_USAGE="analyse-db-usage";EVENT_REQUEST_PERFORM_GC_V3="request-perform-gc-v3";EVENT_REQUEST_CHECK_REMOTE_SIZE="request-check-remote-size";Computed=class{constructor(params){Object.defineProperty(this,"_previousArgs",{enumerable:!0,configurable:!0,writable:!0,value:null});Object.defineProperty(this,"_previousResult",{enumerable:!0,configurable:!0,writable:!0,value:null});Object.defineProperty(this,"_evaluation",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_isEqual",{enumerable:!0,configurable:!0,writable:!0,value:(a2,b3)=>this._areArgsEqual(a2,b3)});Object.defineProperty(this,"_shouldForceUpdate",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_updating",{enumerable:!0,configurable:!0,writable:!0,value:Promise.resolve()});this._evaluation=params.evaluation;this._shouldForceUpdate=params.requiresUpdate||(()=>!1);params.isEqual&&(this._isEqual=params.isEqual)}updateValue(...args){return new Promise(((resolve,reject)=>{this._updating=this._updating.then((async()=>{try{if(!await this._shouldForceUpdate(args,this._previousArgs,this._previousResult)&&this._previousArgs&&this._isEqual(args,this._previousArgs))return resolve(!1);try{this._previousResult=await this._evaluation(...args)}catch(error){const err3=error instanceof Error?error:new Error(String(error));this._previousResult=err3}finally{this._previousArgs=args}return resolve(!0)}catch(error){return reject(error)}}))}))}reset(){this._previousArgs=null;this._previousResult=null}async update(...args){await this.updateValue(...args);return this}get value(){if(this._previousResult instanceof Error)throw this._previousResult;return this._previousResult}_areArgsEqual(args1,args2){return JSON.stringify(args1)===JSON.stringify(args2)}};BasicHeaderGenerator=class{constructor(){this._header=new Computed({evaluation:source2=>{if("username"in source2){const userNameAndPassword=source2.username&&source2.password?`${source2.username}:${source2.password}`:"";return`Basic ${btoa(userNameAndPassword)}`}return""}})}async getBasicHeader(auth){return(await this._header.update(auth)).value}};JWTTokenGenerator=class{constructor(){this._currentCryptoKey=new Computed({evaluation:async auth=>await this._importKey(auth)});this._jwt=new Computed({evaluation:async params=>{const buff=`${btoa(JSON.stringify(params.header))}.${btoa(JSON.stringify(params.payload))}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,""),key3=(await this._currentCryptoKey.update(params.credentials)).value;let token="";if("ES256"==params.header.alg||"ES512"==params.header.alg){const digestAlg="ES256"==params.header.alg?"SHA-256":"SHA-512",jwt=await crypto.subtle.sign({name:"ECDSA",hash:{name:digestAlg}},key3,writeString(buff));token=(await arrayBufferToBase64Single(jwt)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}else{if("HS256"!=params.header.alg&&"HS512"!=params.header.alg)throw new Error("JWT algorithm is not supported.");{const jwt=await crypto.subtle.sign({name:"HMAC",hash:{name:params.header.alg}},key3,writeString(buff));token=(await arrayBufferToBase64Single(jwt)).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}}return{...params,token:`${buff}.${token}`}}});this._jwtParams=new Computed({evaluation(source2){const kid=source2.jwtKid||void 0;if(""==(source2.jwtSub||"").trim())throw new Error("JWT sub is empty");const algorithm=source2.jwtAlgorithm||"";if(!algorithm)throw new Error("JWT algorithm is not configured.");if("HS256"!=algorithm&&"HS512"!=algorithm&&"ES256"!=algorithm&&"ES512"!=algorithm)throw new Error("JWT algorithm is not supported.");const header={alg:source2.jwtAlgorithm||"HS256",typ:"JWT",kid},iat=~~((new Date).getTime()/1e3);return{header,payload:{exp:iat+60*(source2.jwtExpDuration||5),iat,sub:source2.jwtSub||"","_couchdb.roles":["_admin"]},credentials:source2}},requiresUpdate(args,previousArgs,previous){if(!previous||previous instanceof Error)return!0;const margin20p=.1*(previous.payload.exp-previous.payload.iat),margin=Math.min(10,Math.max(margin20p,60)),d4=~~((new Date).getTime()/1e3)+margin;return previous.payload.exp<d4}})}_importKey(auth){if("HS256"==auth.jwtAlgorithm||"HS512"==auth.jwtAlgorithm){const key3=(auth.jwtKey||"").trim();if(""==key3)throw new Error("JWT key is empty");const binaryDerString=window.atob(key3),binaryDer=new Uint8Array(binaryDerString.length);for(let i2=0;i2<binaryDerString.length;i2++)binaryDer[i2]=binaryDerString.charCodeAt(i2);const hashName="HS256"==auth.jwtAlgorithm?"SHA-256":"SHA-512";return crypto.subtle.importKey("raw",binaryDer,{name:"HMAC",hash:{name:hashName}},!0,["sign"])}if("ES256"==auth.jwtAlgorithm||"ES512"==auth.jwtAlgorithm){const pem=auth.jwtKey.replace(/-----BEGIN [^-]+-----/,"").replace(/-----END [^-]+-----/,"").replace(/\s+/g,""),binaryDerString=window.atob(pem),binaryDer=new Uint8Array(binaryDerString.length);for(let i2=0;i2<binaryDerString.length;i2++)binaryDer[i2]=binaryDerString.charCodeAt(i2);const param={name:"ECDSA",namedCurve:"ES256"==auth.jwtAlgorithm?"P-256":"P-521"};return crypto.subtle.importKey("pkcs8",binaryDer,param,!0,["sign"])}throw new Error("Supplied JWT algorithm is not supported.")}async getJWT(auth){const params=(await this._jwtParams.update(auth)).value;return(await this._jwt.update(params)).value}async getBearerToken(auth){return`Bearer ${(await this.getJWT(auth)).token}`}};AuthorizationHeaderGenerator=class{constructor(){this._basicHeader=new BasicHeaderGenerator;this._jwtHeader=new JWTTokenGenerator}async getAuthorizationHeader(auth){return"username"in auth?await this._basicHeader.getBasicHeader(auth):"jwtAlgorithm"in auth?await this._jwtHeader.getBearerToken(auth):""}};memos={};PeriodicProcessor=class{constructor(plugin3,process2){this._timer=void 0;this._plugin=plugin3;this._process=process2;eventHub.onceEvent("plugin-unloaded",(()=>{this.disable()}))}async process(){try{await this._process()}catch(ex){Logger(ex)}}enable(interval){this.disable();if(0!=interval){this._timer=window.setInterval((()=>fireAndForget((async()=>{var _a8,_b5;await this.process();(null==(_b5=null==(_a8=this._plugin.services)?void 0:_a8.appLifecycle)?void 0:_b5.hasUnloaded())&&this.disable()}))),interval);this._plugin.registerInterval(this._timer)}}disable(){if(void 0!==this._timer){window.clearInterval(this._timer);this._timer=void 0}}};_requestToCouchDB=async(baseUri,credentials,origin2,path2,body,method,customHeaders)=>{const authHeaderGen=new AuthorizationHeaderGenerator,requestParam={url:`${baseUri}/${path2}`,method:method||(body?"PUT":"GET"),headers:{authorization:await authHeaderGen.getAuthorizationHeader(credentials),origin:origin2,...customHeaders},contentType:"application/json",body:body?JSON.stringify(body):void 0};return await(0,import_obsidian.requestUrl)(requestParam)};BASE_IS_NEW=Symbol("base");TARGET_IS_NEW=Symbol("target");EVEN=Symbol("even");resolution=2e3;_cached=new Map;waitingTasks={};topologicalSortCache=new Map;_reactiveSourceId=0;reactiveSource({pending:[],running:[],count:0});collectingChunks=reactiveSource(0);pluginScanningCount=reactiveSource(0);hiddenFilesProcessingCount=reactiveSource(0);hiddenFilesEventCount=reactiveSource(0);logMessages=reactiveSource([]);AbstractModule=class{constructor(core){this.core=core;this._log=(msg,level=LOG_LEVEL_INFO,key3)=>{"string"==typeof msg&&level!==LOG_LEVEL_NOTICE&&(msg=`[${this.constructor.name}] ${msg}`);Logger(msg,level,key3)};this.saveSettings=this.core.saveSettings.bind(this.core);this.onBindFunction(core,core.services);Logger(`[${this.constructor.name}] Loaded`,LOG_LEVEL_VERBOSE);__$checkInstanceBinding(this)}get localDatabase(){return this.core.localDatabase}get settings(){return this.core.settings}set settings(value){this.core.settings=value}onBindFunction(core,services){}addTestResult(key3,value,summary,message){this.services.test.addTestResult(`${this.constructor.name}`,key3,value,summary,message)}testDone(result=!0){return Promise.resolve(result)}testFail(message){this._log(message,LOG_LEVEL_NOTICE);return this.testDone(!1)}async _test(key3,process2){this._log(`Testing ${key3}`,LOG_LEVEL_VERBOSE);try{const ret=await process2();if(!0!==ret){this.addTestResult(key3,!1,ret.toString());return this.testFail(`${key3} failed: ${ret}`)}this.addTestResult(key3,!0,"")}catch(ex){this.addTestResult(key3,!1,"Failed by Exception",ex.toString());return this.testFail(`${key3} failed: ${ex}`)}return this.testDone()}get services(){return this.core._services}};AbstractObsidianModule=class extends AbstractModule{constructor(plugin3,core){super(core);this.plugin=plugin3;this.core=core;this.addCommand=this.plugin.addCommand.bind(this.plugin);this.registerView=this.plugin.registerView.bind(this.plugin);this.addRibbonIcon=this.plugin.addRibbonIcon.bind(this.plugin);this.registerObsidianProtocolHandler=this.plugin.registerObsidianProtocolHandler.bind(this.plugin);this.saveSettings=this.plugin.saveSettings.bind(this.plugin)}get localDatabase(){return this.plugin.localDatabase}get settings(){return this.plugin.settings}set settings(value){this.plugin.settings=value}get app(){return this.plugin.app}isMainReady(){return this.services.appLifecycle.isReady()}isMainSuspended(){return this.services.appLifecycle.isSuspended()}isDatabaseReady(){return this.services.database.isDatabaseReady()}isThisModuleEnabled(){return!0}};"undefined"!=typeof window&&(null!=(_c=(_b=null!=(_a3=window.__svelte)?_a3:window.__svelte={}).v)?_c:_b.v=new Set).add("5");EACH_ITEM_REACTIVE=1;EACH_INDEX_REACTIVE=2;EACH_IS_CONTROLLED=4;EACH_IS_ANIMATED=8;EACH_ITEM_IMMUTABLE=16;PROPS_IS_IMMUTABLE=1;PROPS_IS_RUNES=2;PROPS_IS_UPDATED=4;PROPS_IS_BINDABLE=8;PROPS_IS_LAZY_INITIAL=16;TEMPLATE_FRAGMENT=1;TEMPLATE_USE_IMPORT_NODE=2;HYDRATION_START="[";HYDRATION_START_ELSE="[!";HYDRATION_END="]";HYDRATION_ERROR={};UNINITIALIZED=Symbol();FILENAME=Symbol("filename");Symbol("hmr");NAMESPACE_HTML="http://www.w3.org/1999/xhtml";node_env=null==(_b2=null==(_a4=globalThis.process)?void 0:_a4.env)?void 0:_b2.NODE_ENV;dev_fallback_default=node_env&&!node_env.toLowerCase().startsWith("prod");is_array=Array.isArray;index_of=Array.prototype.indexOf;array_from=Array.from;Object.keys;define_property=Object.defineProperty;get_descriptor=Object.getOwnPropertyDescriptor;get_descriptors=Object.getOwnPropertyDescriptors;object_prototype=Object.prototype;array_prototype=Array.prototype;get_prototype_of=Object.getPrototypeOf;is_extensible=Object.isExtensible;noop2=()=>{};DERIVED=2;EFFECT=4;RENDER_EFFECT=8;BLOCK_EFFECT=16;BRANCH_EFFECT=32;ROOT_EFFECT=64;BOUNDARY_EFFECT=128;UNOWNED=256;DISCONNECTED=512;CLEAN=1024;DIRTY=2048;MAYBE_DIRTY=4096;INERT=8192;DESTROYED=16384;EFFECT_RAN=32768;EFFECT_TRANSPARENT=65536;INSPECT_EFFECT=1<<17;HEAD_EFFECT=1<<18;EFFECT_PRESERVED=1<<19;USER_EFFECT=1<<20;REACTION_IS_UPDATING=1<<21;ASYNC=1<<22;ERROR_VALUE=1<<23;STATE_SYMBOL=Symbol("$state");LEGACY_PROPS=Symbol("legacy props");LOADING_ATTR_SYMBOL=Symbol("");PROXY_PATH_SYMBOL=Symbol("proxy path");STALE_REACTION=new class StaleReactionError extends Error{constructor(){super(...arguments);__publicField(this,"name","StaleReactionError");__publicField(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}};TEXT_NODE=3;COMMENT_NODE=8;bold="font-weight: bold";normal="font-weight: normal";hydrating=!1;async_mode_flag=!1;legacy_mode_flag=!1;tracing_mode_flag=!1;tracing_expressions=null;component_context=null;dev_stack=null;dev_current_component_function=null;micro_tasks=[];adjustments=new WeakMap;batches=new Set;current_batch=null;previous_batch=null;batch_values=null;effect_pending_updates=new Set;queued_root_effects=[];last_scheduled_effect=null;is_flushing=!1;is_flushing_sync=!1;_Batch=class _Batch{constructor(){__privateAdd(this,_Batch_instances);__publicField(this,"current",new Map);__privateAdd(this,_previous,new Map);__privateAdd(this,_callbacks,new Set);__privateAdd(this,_pending,0);__privateAdd(this,_deferred,null);__privateAdd(this,_render_effects,[]);__privateAdd(this,_effects,[]);__privateAdd(this,_block_effects,[]);__privateAdd(this,_dirty_effects,[]);__privateAdd(this,_maybe_dirty_effects,[]);__publicField(this,"skipped_effects",new Set)}process(root_effects){var _a8,previous_batch_sources,render_effects,effects;queued_root_effects=[];previous_batch=null;this.apply();for(const root40 of root_effects)__privateMethod(this,_Batch_instances,traverse_effect_tree_fn).call(this,root40);if(0===__privateGet(this,_pending)){previous_batch_sources=batch_values;__privateMethod(this,_Batch_instances,commit_fn).call(this);render_effects=__privateGet(this,_render_effects);effects=__privateGet(this,_effects);__privateSet(this,_render_effects,[]);__privateSet(this,_effects,[]);__privateSet(this,_block_effects,[]);previous_batch=this;current_batch=null;batch_values=previous_batch_sources;flush_queued_effects(render_effects);flush_queued_effects(effects);previous_batch=null;null==(_a8=__privateGet(this,_deferred))||_a8.resolve()}else{__privateMethod(this,_Batch_instances,defer_effects_fn).call(this,__privateGet(this,_render_effects));__privateMethod(this,_Batch_instances,defer_effects_fn).call(this,__privateGet(this,_effects));__privateMethod(this,_Batch_instances,defer_effects_fn).call(this,__privateGet(this,_block_effects))}batch_values=null}capture(source2,value){__privateGet(this,_previous).has(source2)||__privateGet(this,_previous).set(source2,value);this.current.set(source2,source2.v);null==batch_values||batch_values.set(source2,source2.v)}activate(){current_batch=this}deactivate(){current_batch=null;batch_values=null}flush(){if(queued_root_effects.length>0){this.activate();flush_effects();if(null!==current_batch&&current_batch!==this)return}else 0===__privateGet(this,_pending)&&__privateMethod(this,_Batch_instances,commit_fn).call(this);this.deactivate();for(const update2 of effect_pending_updates){effect_pending_updates.delete(update2);update2();if(null!==current_batch)break}}increment(){__privateSet(this,_pending,__privateGet(this,_pending)+1)}decrement(){__privateSet(this,_pending,__privateGet(this,_pending)-1);for(const e3 of __privateGet(this,_dirty_effects)){set_signal_status(e3,DIRTY);schedule_effect(e3)}for(const e3 of __privateGet(this,_maybe_dirty_effects)){set_signal_status(e3,MAYBE_DIRTY);schedule_effect(e3)}this.flush()}add_callback(fn){__privateGet(this,_callbacks).add(fn)}settled(){var _a8;return(null!=(_a8=__privateGet(this,_deferred))?_a8:__privateSet(this,_deferred,deferred())).promise}static ensure(){if(null===current_batch){const batch=current_batch=new _Batch;batches.add(current_batch);is_flushing_sync||_Batch.enqueue((()=>{current_batch===batch&&batch.flush()}))}return current_batch}static enqueue(task){queue_micro_task(task)}apply(){if(async_mode_flag&&1!==batches.size){batch_values=new Map(this.current);for(const batch of batches)if(batch!==this)for(const[source2,previous]of __privateGet(batch,_previous))batch_values.has(source2)||batch_values.set(source2,previous)}}};_previous=new WeakMap;_callbacks=new WeakMap;_pending=new WeakMap;_deferred=new WeakMap;_render_effects=new WeakMap;_effects=new WeakMap;_block_effects=new WeakMap;_dirty_effects=new WeakMap;_maybe_dirty_effects=new WeakMap;_Batch_instances=new WeakSet;traverse_effect_tree_fn=function(root40){var effect2,flags2,is_branch,child2,parent;root40.f^=CLEAN;effect2=root40.first;for(;null!==effect2;){if(!((is_branch=!!((flags2=effect2.f)&(BRANCH_EFFECT|ROOT_EFFECT)))&&flags2&CLEAN||flags2&INERT||this.skipped_effects.has(effect2))&&null!==effect2.fn){if(is_branch)effect2.f^=CLEAN;else if(flags2&EFFECT)__privateGet(this,_effects).push(effect2);else if(async_mode_flag&&flags2&RENDER_EFFECT)__privateGet(this,_render_effects).push(effect2);else if(is_dirty(effect2)){effect2.f&BLOCK_EFFECT&&__privateGet(this,_block_effects).push(effect2);update_effect(effect2)}if(null!==(child2=effect2.first)){effect2=child2;continue}}parent=effect2.parent;effect2=effect2.next;for(;null===effect2&&null!==parent;){effect2=parent.next;parent=parent.parent}}};defer_effects_fn=function(effects){for(const e3 of effects){(e3.f&DIRTY?__privateGet(this,_dirty_effects):__privateGet(this,_maybe_dirty_effects)).push(e3);set_signal_status(e3,CLEAN)}effects.length=0};commit_fn=function(){var _a8;for(const fn of __privateGet(this,_callbacks))fn();__privateGet(this,_callbacks).clear();if(batches.size>1){__privateGet(this,_previous).clear();let is_earlier=!0;for(const batch of batches){if(batch===this){is_earlier=!1;continue}const sources=[];for(const[source2,value]of this.current){if(batch.current.has(source2)){if(!is_earlier||value===batch.current.get(source2))continue;batch.current.set(source2,value)}sources.push(source2)}if(0===sources.length)continue;const others=[...batch.current.keys()].filter((s2=>!this.current.has(s2)));if(others.length>0){for(const source2 of sources)mark_effects(source2,others);if(queued_root_effects.length>0){current_batch=batch;batch.apply();for(const root40 of queued_root_effects)__privateMethod(_a8=batch,_Batch_instances,traverse_effect_tree_fn).call(_a8,root40);queued_root_effects=[];batch.deactivate()}}}current_batch=null}batches.delete(this)};Batch=_Batch;eager_block_effects=null;flags=EFFECT_TRANSPARENT|EFFECT_PRESERVED|BOUNDARY_EFFECT;Boundary=class{constructor(node,props,children){__privateAdd(this,_Boundary_instances);__publicField(this,"parent");__privateAdd(this,_pending2,!1);__privateAdd(this,_anchor);__privateAdd(this,_hydrate_open,hydrating?hydrate_node:null);__privateAdd(this,_props);__privateAdd(this,_children);__privateAdd(this,_effect);__privateAdd(this,_main_effect,null);__privateAdd(this,_pending_effect,null);__privateAdd(this,_failed_effect,null);__privateAdd(this,_offscreen_fragment,null);__privateAdd(this,_local_pending_count,0);__privateAdd(this,_pending_count,0);__privateAdd(this,_is_creating_fallback,!1);__privateAdd(this,_effect_pending,null);__privateAdd(this,_effect_pending_update,(()=>{__privateGet(this,_effect_pending)&&internal_set(__privateGet(this,_effect_pending),__privateGet(this,_local_pending_count))}));__privateAdd(this,_effect_pending_subscriber,createSubscriber((()=>{__privateSet(this,_effect_pending,source(__privateGet(this,_local_pending_count)));dev_fallback_default&&tag(__privateGet(this,_effect_pending),"$effect.pending()");return()=>{__privateSet(this,_effect_pending,null)}})));__privateSet(this,_anchor,node);__privateSet(this,_props,props);__privateSet(this,_children,children);this.parent=active_effect.b;__privateSet(this,_pending2,!!__privateGet(this,_props).pending);__privateSet(this,_effect,block((()=>{active_effect.b=this;if(hydrating){const comment2=__privateGet(this,_hydrate_open);hydrate_next();comment2.nodeType===COMMENT_NODE&&comment2.data===HYDRATION_START_ELSE?__privateMethod(this,_Boundary_instances,hydrate_pending_content_fn).call(this):__privateMethod(this,_Boundary_instances,hydrate_resolved_content_fn).call(this)}else{try{__privateSet(this,_main_effect,branch((()=>children(__privateGet(this,_anchor)))))}catch(error){this.error(error)}__privateGet(this,_pending_count)>0?__privateMethod(this,_Boundary_instances,show_pending_snippet_fn).call(this):__privateSet(this,_pending2,!1)}}),flags));hydrating&&__privateSet(this,_anchor,hydrate_node)}is_pending(){return __privateGet(this,_pending2)||!!this.parent&&this.parent.is_pending()}has_pending_snippet(){return!!__privateGet(this,_props).pending}update_pending_count(d4){__privateMethod(this,_Boundary_instances,update_pending_count_fn).call(this,d4);__privateSet(this,_local_pending_count,__privateGet(this,_local_pending_count)+d4);effect_pending_updates.add(__privateGet(this,_effect_pending_update))}get_effect_pending(){__privateGet(this,_effect_pending_subscriber).call(this);return get(__privateGet(this,_effect_pending))}error(error){var did_reset,calling_on_error,previous_reaction,onerror=__privateGet(this,_props).onerror;let failed2=__privateGet(this,_props).failed;if(__privateGet(this,_is_creating_fallback)||!onerror&&!failed2)throw error;if(__privateGet(this,_main_effect)){destroy_effect(__privateGet(this,_main_effect));__privateSet(this,_main_effect,null)}if(__privateGet(this,_pending_effect)){destroy_effect(__privateGet(this,_pending_effect));__privateSet(this,_pending_effect,null)}if(__privateGet(this,_failed_effect)){destroy_effect(__privateGet(this,_failed_effect));__privateSet(this,_failed_effect,null)}if(hydrating){set_hydrate_node(__privateGet(this,_hydrate_open));next();set_hydrate_node(skip_nodes())}did_reset=!1;calling_on_error=!1;const reset2=()=>{if(did_reset)svelte_boundary_reset_noop();else{did_reset=!0;calling_on_error&&svelte_boundary_reset_onerror();Batch.ensure();__privateSet(this,_local_pending_count,0);null!==__privateGet(this,_failed_effect)&&pause_effect(__privateGet(this,_failed_effect),(()=>{__privateSet(this,_failed_effect,null)}));__privateSet(this,_pending2,this.has_pending_snippet());__privateSet(this,_main_effect,__privateMethod(this,_Boundary_instances,run_fn).call(this,(()=>{__privateSet(this,_is_creating_fallback,!1);return branch((()=>__privateGet(this,_children).call(this,__privateGet(this,_anchor))))})));__privateGet(this,_pending_count)>0?__privateMethod(this,_Boundary_instances,show_pending_snippet_fn).call(this):__privateSet(this,_pending2,!1)}};previous_reaction=active_reaction;try{set_active_reaction(null);calling_on_error=!0;null==onerror||onerror(error,reset2);calling_on_error=!1}catch(error2){invoke_error_boundary(error2,__privateGet(this,_effect)&&__privateGet(this,_effect).parent)}finally{set_active_reaction(previous_reaction)}failed2&&queue_micro_task((()=>{__privateSet(this,_failed_effect,__privateMethod(this,_Boundary_instances,run_fn).call(this,(()=>{__privateSet(this,_is_creating_fallback,!0);try{return branch((()=>{failed2(__privateGet(this,_anchor),(()=>error),(()=>reset2))}))}catch(error2){invoke_error_boundary(error2,__privateGet(this,_effect).parent);return null}finally{__privateSet(this,_is_creating_fallback,!1)}})))}))}};_pending2=new WeakMap;_anchor=new WeakMap;_hydrate_open=new WeakMap;_props=new WeakMap;_children=new WeakMap;_effect=new WeakMap;_main_effect=new WeakMap;_pending_effect=new WeakMap;_failed_effect=new WeakMap;_offscreen_fragment=new WeakMap;_local_pending_count=new WeakMap;_pending_count=new WeakMap;_is_creating_fallback=new WeakMap;_effect_pending=new WeakMap;_effect_pending_update=new WeakMap;_effect_pending_subscriber=new WeakMap;_Boundary_instances=new WeakSet;hydrate_resolved_content_fn=function(){try{__privateSet(this,_main_effect,branch((()=>__privateGet(this,_children).call(this,__privateGet(this,_anchor)))))}catch(error){this.error(error)}__privateSet(this,_pending2,!1)};hydrate_pending_content_fn=function(){const pending3=__privateGet(this,_props).pending;if(pending3){__privateSet(this,_pending_effect,branch((()=>pending3(__privateGet(this,_anchor)))));Batch.enqueue((()=>{__privateSet(this,_main_effect,__privateMethod(this,_Boundary_instances,run_fn).call(this,(()=>{Batch.ensure();return branch((()=>__privateGet(this,_children).call(this,__privateGet(this,_anchor))))})));if(__privateGet(this,_pending_count)>0)__privateMethod(this,_Boundary_instances,show_pending_snippet_fn).call(this);else{pause_effect(__privateGet(this,_pending_effect),(()=>{__privateSet(this,_pending_effect,null)}));__privateSet(this,_pending2,!1)}}))}};run_fn=function(fn){var previous_effect=active_effect,previous_reaction=active_reaction,previous_ctx=component_context;set_active_effect(__privateGet(this,_effect));set_active_reaction(__privateGet(this,_effect));set_component_context(__privateGet(this,_effect).ctx);try{return fn()}catch(e3){handle_error(e3);return null}finally{set_active_effect(previous_effect);set_active_reaction(previous_reaction);set_component_context(previous_ctx)}};show_pending_snippet_fn=function(){const pending3=__privateGet(this,_props).pending;if(null!==__privateGet(this,_main_effect)){__privateSet(this,_offscreen_fragment,document.createDocumentFragment());move_effect(__privateGet(this,_main_effect),__privateGet(this,_offscreen_fragment))}null===__privateGet(this,_pending_effect)&&__privateSet(this,_pending_effect,branch((()=>pending3(__privateGet(this,_anchor)))))};update_pending_count_fn=function(d4){var _a8;if(this.has_pending_snippet()){__privateSet(this,_pending_count,__privateGet(this,_pending_count)+d4);if(0===__privateGet(this,_pending_count)){__privateSet(this,_pending2,!1);__privateGet(this,_pending_effect)&&pause_effect(__privateGet(this,_pending_effect),(()=>{__privateSet(this,_pending_effect,null)}));if(__privateGet(this,_offscreen_fragment)){__privateGet(this,_anchor).before(__privateGet(this,_offscreen_fragment));__privateSet(this,_offscreen_fragment,null)}queue_micro_task((()=>{Batch.ensure().flush()}))}}else this.parent&&__privateMethod(_a8=this.parent,_Boundary_instances,update_pending_count_fn).call(_a8,d4)};current_async_effect=null;recent_async_deriveds=new Set;stack=[];inspect_effects=new Set;old_values=new Map;inspect_effects_deferred=!1;regex_is_valid_identifier=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;ARRAY_MUTATING_METHODS=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);listening_to_form_reset=!1;captured_signals=null;is_updating_effect=!1;is_destroying_effect=!1;active_reaction=null;untracking=!1;active_effect=null;current_sources=null;new_deps=null;skipped_deps=0;untracked_writes=null;write_version=1;update_version=read_version=0;skip_reaction=!1;STATUS_MASK=~(DIRTY|MAYBE_DIRTY|CLEAN);all_registered_events=new Set;root_event_handles=new Set;PASSIVE_EVENTS=["touchstart","touchmove"];document_listeners=new Map;mounted_components=new WeakMap;BranchManager=class{constructor(anchor,transition2=!0){__publicField(this,"anchor");__privateAdd(this,_batches,new Map);__privateAdd(this,_onscreen,new Map);__privateAdd(this,_offscreen,new Map);__privateAdd(this,_transition,!0);__privateAdd(this,_commit,(()=>{var key3,onscreen,offscreen,batch=current_batch;if(__privateGet(this,_batches).has(batch)){key3=__privateGet(this,_batches).get(batch);if(onscreen=__privateGet(this,_onscreen).get(key3))resume_effect(onscreen);else if(offscreen=__privateGet(this,_offscreen).get(key3)){__privateGet(this,_onscreen).set(key3,offscreen.effect);__privateGet(this,_offscreen).delete(key3);offscreen.fragment.lastChild.remove();this.anchor.before(offscreen.fragment);onscreen=offscreen.effect}for(const[b3,k2]of __privateGet(this,_batches)){__privateGet(this,_batches).delete(b3);if(b3===batch)break;const offscreen2=__privateGet(this,_offscreen).get(k2);if(offscreen2){destroy_effect(offscreen2.effect);__privateGet(this,_offscreen).delete(k2)}}for(const[k2,effect2]of __privateGet(this,_onscreen)){if(k2===key3)continue;const on_destroy=()=>{if(Array.from(__privateGet(this,_batches).values()).includes(k2)){var fragment=document.createDocumentFragment();move_effect(effect2,fragment);fragment.append(create_text());__privateGet(this,_offscreen).set(k2,{effect:effect2,fragment})}else destroy_effect(effect2);__privateGet(this,_onscreen).delete(k2)};__privateGet(this,_transition)||!onscreen?pause_effect(effect2,on_destroy,!1):on_destroy()}}}));this.anchor=anchor;__privateSet(this,_transition,transition2)}ensure(key3,fn){var fragment,target,batch=current_batch,defer=should_defer_append();if(fn&&!__privateGet(this,_onscreen).has(key3)&&!__privateGet(this,_offscreen).has(key3))if(defer){fragment=document.createDocumentFragment();target=create_text();fragment.append(target);__privateGet(this,_offscreen).set(key3,{effect:branch((()=>fn(target))),fragment})}else __privateGet(this,_onscreen).set(key3,branch((()=>fn(this.anchor))));__privateGet(this,_batches).set(batch,key3);if(defer){for(const[k2,effect2]of __privateGet(this,_onscreen))k2===key3?batch.skipped_effects.delete(effect2):batch.skipped_effects.add(effect2);for(const[k2,branch2]of __privateGet(this,_offscreen))k2===key3?batch.skipped_effects.delete(branch2.effect):batch.skipped_effects.add(branch2.effect);batch.add_callback(__privateGet(this,_commit))}else{hydrating&&(this.anchor=hydrate_node);__privateGet(this,_commit).call(this)}}};_batches=new WeakMap;_onscreen=new WeakMap;_offscreen=new WeakMap;_transition=new WeakMap;_commit=new WeakMap;if(dev_fallback_default){let throw_rune_error=function(rune){if(!(rune in globalThis)){let value;Object.defineProperty(globalThis,rune,{configurable:!0,get:()=>{if(void 0!==value)return value;rune_outside_svelte(rune)},set:v2=>{value=v2}})}};throw_rune_error("$state");throw_rune_error("$effect");throw_rune_error("$derived");throw_rune_error("$inspect");throw_rune_error("$props");throw_rune_error("$bindable")}all_styles=new Map;current_each_item=null;whitespace=[..." \t\n\r\f \v\ufeff"];Symbol("class");Symbol("style");IS_CUSTOM_ELEMENT=Symbol("is custom element");IS_HTML=Symbol("is html");setters_cache=new Map;pending2=new Set;_ResizeObserverSingleton=class _ResizeObserverSingleton{constructor(options){__privateAdd(this,_ResizeObserverSingleton_instances);__privateAdd(this,_listeners,new WeakMap);__privateAdd(this,_observer);__privateAdd(this,_options2);__privateSet(this,_options2,options)}observe(element2,listener){var listeners=__privateGet(this,_listeners).get(element2)||new Set;listeners.add(listener);__privateGet(this,_listeners).set(element2,listeners);__privateMethod(this,_ResizeObserverSingleton_instances,getObserver_fn).call(this).observe(element2,__privateGet(this,_options2));return()=>{var listeners2=__privateGet(this,_listeners).get(element2);listeners2.delete(listener);if(0===listeners2.size){__privateGet(this,_listeners).delete(element2);__privateGet(this,_observer).unobserve(element2)}}}};_listeners=new WeakMap;_observer=new WeakMap;_options2=new WeakMap;_ResizeObserverSingleton_instances=new WeakSet;getObserver_fn=function(){var _a8;return null!=(_a8=__privateGet(this,_observer))?_a8:__privateSet(this,_observer,new ResizeObserver((entries2=>{var entry,listener;for(entry of entries2){_ResizeObserverSingleton.entries.set(entry.target,entry);for(listener of __privateGet(this,_listeners).get(entry.target)||[])listener(entry)}})))};__publicField(_ResizeObserverSingleton,"entries",new WeakMap);subscriber_queue=[];is_store_binding=!1;IS_UNMOUNTED=Symbol();spread_props_handler={get(target,key3){let i2=target.props.length;for(;i2--;){let p4=target.props[i2];is_function(p4)&&(p4=p4());if("object"==typeof p4&&null!==p4&&key3 in p4)return p4[key3]}},set(target,key3,value){let i2=target.props.length;for(;i2--;){let p4=target.props[i2];is_function(p4)&&(p4=p4());const desc=get_descriptor(p4,key3);if(desc&&desc.set){desc.set(value);return!0}}return!1},getOwnPropertyDescriptor(target,key3){let i2=target.props.length;for(;i2--;){let p4=target.props[i2];is_function(p4)&&(p4=p4());if("object"==typeof p4&&null!==p4&&key3 in p4){const descriptor=get_descriptor(p4,key3);descriptor&&!descriptor.configurable&&(descriptor.configurable=!0);return descriptor}}},has(target,key3){if(key3===STATE_SYMBOL||key3===LEGACY_PROPS)return!1;for(let p4 of target.props){is_function(p4)&&(p4=p4());if(null!=p4&&key3 in p4)return!0}return!1},ownKeys(target){const keys3=[];for(let p4 of target.props){is_function(p4)&&(p4=p4());if(p4){for(const key3 in p4)keys3.includes(key3)||keys3.push(key3);for(const key3 of Object.getOwnPropertySymbols(p4))keys3.includes(key3)||keys3.push(key3)}}return keys3}};new WeakMap;new WeakMap;"function"==typeof HTMLElement&&HTMLElement;SUPPORTED_I18N_LANGS=["def","de","es","ja","ko","ru","zh","zh-tw"];expandedMessage={...expandKeywords(_allMessages={"(BETA) Always overwrite with a newer file":{def:"(BETA) Always overwrite with a newer file",es:"(BETA) Sobrescribir siempre con archivo más nuevo",ja:"(ベータ機能) 常に新しいファイルで上書きする",ko:"(베타) 항상 새로운 파일로 덮어쓰기",zh:"始终使用更新的文件覆盖(测试版)"},"(Beta) Use ignore files":{def:"(Beta) Use ignore files",es:"(Beta) Usar archivos de ignorar",ja:"(ベータ機能) 無視ファイル(ignore)の使用",ko:"(베타) 제외 규칙 파일 사용",zh:"(测试版)使用忽略文件"},"(Days passed, 0 to disable automatic-deletion)":{def:"(Days passed, 0 to disable automatic-deletion)",es:"(Días transcurridos, 0 para desactivar)",ko:"(지난 일수, 0으로 설정하면 자동 삭제 비활성화)",zh:"已过天数0为禁用自动删除"},"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.":{def:"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended.",es:"(Ej: Leer chunks online) Lee chunks directamente en línea. Aumente tamaño de chunks personalizados",ko:"(예: 청크를 원격에서 읽음) 이 옵션을 활성화하면, LiveSync는 청크를 로컬에 복제하지 않고 원격에서 직접 읽습니다. 커스텀 청크 크기를 키우는 것을 권장합니다.",zh:"例如在线读取块如果启用此选项LiveSync 将直接在线读取块,而不是在本地复制块。建议增加自定义块大小"},"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.":{def:"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used.",es:"(MB) Saltar cambios en archivos locales/remotos mayores a este tamaño. Si se reduce, se usará versión nueva",ko:"(MB) 이 값이 설정되면, 이보다 큰 로컬 및 원격 파일의 변경 사항은 건너뜁니다. 파일이 다시 작아지면 더 새로운 파일이 사용됩니다.",zh:"MB如果设置了此项大于此大小的本地和远程文件的更改将被跳过。如果文件再次变小将使用更新的文件"},"(Mega chars)":{def:"(Mega chars)",es:"(Millones de caracteres)",ko:"(메가 문자)",zh:"(百万字符)"},"(Not recommended) If set, credentials will be stored in the file.":{def:"(Not recommended) If set, credentials will be stored in the file.",es:"(No recomendado) Almacena credenciales en el archivo",ko:"(권장하지 않음) 설정한 경우 자격 증명이 파일에 저장됩니다.",zh:"(不建议)如果设置,凭据将存储在文件中。"},"(Obsolete) Use an old adapter for compatibility":{def:"(Obsolete) Use an old adapter for compatibility",es:"(Obsoleto) Usar adaptador antiguo",ja:"古いアダプターを利用(互換性重視)",ko:"(사용 중단) 호환성을 위해 이전 어댑터 사용",zh:"(已弃用)为兼容性使用旧适配器"},"Access Key":{def:"Access Key",es:"Clave de acceso",ja:"アクセスキー",ko:"액세스 키",zh:"Access Key"},"Always prompt merge conflicts":{def:"Always prompt merge conflicts",es:"Siempre preguntar en conflictos",ja:"常に競合は手動で解決する",ko:"항상 병합 충돌 알림",zh:"始终提示合并冲突"},"Apply Latest Change if Conflicting":{def:"Apply Latest Change if Conflicting",es:"Aplicar último cambio en conflictos",ja:"書類内に競合が発生しても、常に同期内容を反映する",ko:"충돌 시 최신 변경 사항 적용",zh:"如果冲突则应用最新更改"},"Apply preset configuration":{def:"Apply preset configuration",es:"Aplicar configuración predefinida",ja:"初期設定値に戻す",ko:"프리셋 구성 적용",zh:"应用预设配置"},"Automatically Sync all files when opening Obsidian.":{def:"Automatically Sync all files when opening Obsidian.",es:"Sincronizar automáticamente todos los archivos al abrir Obsidian",ko:"Obsidian을 열 때 모든 파일을 자동으로 동기화합니다.",zh:"打开 Obsidian 时自动同步所有文件。"},"Batch database update":{def:"Batch database update",es:"Actualización por lotes de BD",ja:"データベースのバッチ更新",ko:"일괄 데이터베이스 업데이트",zh:"批量数据库更新"},"Batch limit":{def:"Batch limit",es:"Límite de lotes",ja:"バッチの上限",ko:"일괄 제한",zh:"批量限制"},"Batch size":{def:"Batch size",es:"Tamaño de lote",ja:"バッチ容量",ko:"일괄 크기",zh:"批量大小"},"Batch size of on-demand fetching":{def:"Batch size of on-demand fetching",es:"Tamaño de lote para obtención bajo demanda",ko:"필요 시 가져올 청크 묶음 크기",zh:"按需获取的批量大小"},"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.":{def:"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.",es:"Antes de v0.17.16 usábamos adaptador antiguo. Nuevo adaptador requiere reconstruir BD local. Desactive cuando pueda",ja:"v0.17.6までは、古いアダプターをローカル用のデータベースに使用していました。現在は新しいアダプターを推奨しています。しかし、古いデータベースを再構築するためには必要です。有効のままにしておくと、リモートデータベースからフェッチする場合に、この設定を無効にするか質問があります。",ko:"v0.17.16 이전에는 로컬 데이터베이스에 이전 어댑터를 사용했습니다. 이제는 새로운 어댑터를 권장합니다. 하지만 로컬 데이터베이스 재구축이 필요합니다. 충분한 시간이 있을 때 이 토글을 비활성화해 주세요. 활성화된 상태로 두면 원격 데이터베이스에서 가져올 때도 이를 비활성화하라는 메시지가 나타납니다.",zh:"在 v0.17.16 之前,我们使用旧适配器作为本地数据库。现在首选新适配器。但是,它需要重建本地数据库。请在有足够时间时禁用此开关。如果保持启用状态,并且在从远程数据库获取时,系统将要求您禁用此开关。"},"Bucket Name":{def:"Bucket Name",es:"Nombre del bucket",ja:"バケット名",ko:"버킷 이름",zh:"Bucket Name"},"cmdConfigSync.showCustomizationSync":{def:"Show Customization sync",es:"Mostrar sincronización de personalización",ko:"사용자 설정 동기화 표시"},"Comma separated `.gitignore, .dockerignore`":{def:"Comma separated `.gitignore, .dockerignore`",es:"Separados por comas: `.gitignore, .dockerignore`",ko:"쉼표로 구분된 `.gitignore, .dockerignore`",zh:"用逗号分隔,例如 `.gitignore, .dockerignore`"},"Compute revisions for chunks":{def:"Compute revisions for chunks",ko:"청크에 대한 리비전 계산"},"Data Compression":{def:"Data Compression",es:"Compresión de datos",ja:"データ圧縮",ko:"데이터 압축",zh:"数据压缩(实验性)"},"Database Name":{def:"Database Name",es:"Nombre de la base de datos",ja:"データベース名",ko:"데이터베이스 이름",zh:"数据库名称"},"Database suffix":{def:"Database suffix",es:"Sufijo de base de datos",ja:"データベースの接尾詞(サフィックス)",ko:"데이터베이스 접미사",zh:"数据库后缀"},"Delay conflict resolution of inactive files":{def:"Delay conflict resolution of inactive files",es:"Retrasar resolución de conflictos en archivos inactivos",ja:"無効なファイルは、競合解決を先送りする",ko:"비활성 파일의 충돌 해결 지연",zh:"推迟解决不活动文件"},"Delay merge conflict prompt for inactive files.":{def:"Delay merge conflict prompt for inactive files.",es:"Retrasar aviso de fusión para archivos inactivos",ja:"手動で無効なファイルの競合を解決する",ko:"비활성 파일의 병합 충돌 프롬프트 지연.",zh:"推迟手动解决不活动文件"},"Delete old metadata of deleted files on start-up":{def:"Delete old metadata of deleted files on start-up",es:"Borrar metadatos viejos al iniciar",ja:"削除済みデータのメタデータをクリーンナップする",ko:"시작 시 삭제된 파일의 오래된 메타데이터 삭제",zh:"启动时删除已删除文件的旧元数据"},"Device name":{def:"Device name",es:"Nombre del dispositivo",ja:"デバイスネーム",ko:"기기 이름",zh:"设备名称"},"dialog.yourLanguageAvailable":{def:"Self-hosted LiveSync had translations for your language, so the %{Display language} setting was enabled.\n\nNote: Not all messages are translated. We are waiting for your contributions!\nNote 2: If you create an Issue, **please revert to %{lang-def}** and then take screenshots, messages and logs. This can be done in the setting dialogue.\nMay you find it easy to use!",ja:"Self-hosted LiveSync にご利用の言語の翻訳がありましたので、%{Display Language}が適用されました。\n\nご注意 すべてのメッセージは翻訳されていません。あなたのコントリビューションをお待ちしています!\nその Issueを作成する際には、 %{Display Language} を一旦 %{lang-def} に戻してから、キャプチャやメッセージ、ログを収集してください。これは設定ダイアログから変更できます。\n\nこれで便利に使用できれば幸いです。",ko:"Self-hosted LiveSync에서 귀하의 언어로 번역을 제공하므로 %{Display language} 설정이 활성화되었습니다.\n\n참고: 모든 메시지가 번역되지는 않습니다. 귀하의 기여를 기다리고 있습니다!\n참고 2: 이슈를 생성하는 경우 **%{lang-def}로 되돌린 후** 스크린샷, 메시지, 로그를 가져와 주세요. 이는 설정 대화 상자에서 할 수 있습니다.\n간편하게 사용하실 수 있었으면 좋겠습니다!"},"dialog.yourLanguageAvailable.btnRevertToDefault":{def:"Keep %{lang-def}",ko:"%{lang-def} 유지"},"dialog.yourLanguageAvailable.Title":{def:" Translation is available!",ko:" 번역을 사용할 수 있습니다!"},"Disables logging, only shows notifications. Please disable if you report an issue.":{def:"Disables logging, only shows notifications. Please disable if you report an issue.",es:"Desactiva registros, solo muestra notificaciones. Desactívelo si reporta un problema.",ko:"로깅을 비활성화하고 알림만 표시합니다. 문제를 신고하는 경우 비활성화해 주세요.",zh:"禁用日志记录,仅显示通知。如果您报告问题,请禁用此选项。"},"Display Language":{def:"Display Language",es:"Idioma de visualización",ja:"インターフェースの表示言語",ko:"표시 언어",zh:"显示语言"},"Do not check configuration mismatch before replication":{def:"Do not check configuration mismatch before replication",es:"No verificar incompatibilidades antes de replicar",ko:"복제 전 구성 불일치 확인 안 함",zh:"在复制前不检查配置不匹配"},"Do not keep metadata of deleted files.":{def:"Do not keep metadata of deleted files.",es:"No conservar metadatos de archivos borrados",ja:"削除済みファイルのメタデータを保持しない",ko:"삭제된 파일의 메타데이터를 보관하지 않습니다.",zh:"不保留已删除文件的元数据。"},"Do not split chunks in the background":{def:"Do not split chunks in the background",es:"No dividir chunks en segundo plano",ko:"백그라운드에서 청크 분할 안 함",zh:"不在后台分割 chunks"},"Do not use internal API":{def:"Do not use internal API",es:"No usar API interna",ja:"内部APIを使用しない",ko:"내부 API 사용 안 함",zh:"不使用内部 API"},"Doctor.Button.DismissThisVersion":{def:"No, and do not ask again until the next release",ko:"아니요, 다음 릴리스까지 다시 묻지 않음"},"Doctor.Button.Fix":{def:"Fix it",ko:"수정"},"Doctor.Button.FixButNoRebuild":{def:"Fix it but no rebuild",ko:"수정하지만 재구축하지 않음"},"Doctor.Button.No":{def:"No",ko:"아니요"},"Doctor.Button.Skip":{def:"Leave it as is",ko:"그대로 두기"},"Doctor.Button.Yes":{def:"Yes",ko:"예"},"Doctor.Dialogue.Main":{def:"Hi! Config Doctor has been activated because of ${activateReason}!\nAnd, unfortunately some configurations were detected as potential problems.\nPlease be assured. Let's solve them one by one.\n\nTo let you know ahead of time, we will ask you about the following items.\n\n${issues}\n\nShall we get started?",ko:"안녕하세요! ${activateReason} 로 인해 구성 진단 마법사가 활성화되었습니다!\n그리고 일부 구성이 잠재적인 문제로 감지되었습니다.\n안심하세요. 하나씩 해결해 봅시다.\n\n대상 항목은 다음과 같습니다.\n\n${issues}\n\n시작하시겠습니까?"},"Doctor.Dialogue.MainFix":{def:"\n## ${name}\n\n| Current | Ideal |\n|:---:|:---:|\n| ${current} | ${ideal} |\n\n**Recommendation Level:** ${level}\n\n### Why this has been detected?\n\n${reason}\n\n${note}\n\nFix this to the ideal value?",ko:"**구성 이름:** `${name}`\n**현재 값:** `${current}`, **이상적인 값:** `${ideal}`\n**권장 수준:** ${level}\n**왜 이것이 감지되었나요?**\n${reason}\n\n\n${note}\n\n이상적인 값으로 수정하시겠습니까?"},"Doctor.Dialogue.Title":{def:"Self-hosted LiveSync Config Doctor",ko:"Self-hosted LiveSync 구성 진단 마법사"},"Doctor.Dialogue.TitleAlmostDone":{def:"Almost done!",ko:"거의 완료되었습니다!"},"Doctor.Dialogue.TitleFix":{def:"Fix issue ${current}/${total}",ko:"문제 해결 ${current}/${total}"},"Doctor.Level.Must":{def:"Must",ko:"필수"},"Doctor.Level.Necessary":{def:"Necessary",ko:"필수"},"Doctor.Level.Optional":{def:"Optional",ko:"선택사항"},"Doctor.Level.Recommended":{def:"Recommended",ko:"권장"},"Doctor.Message.NoIssues":{def:"No issues detected!",ko:"문제가 감지되지 않았습니다!"},"Doctor.Message.RebuildLocalRequired":{def:"Attention! A local database rebuild is required to apply this!",ko:"주의! 이를 적용하려면 로컬 데이터베이스 재구축이 필요합니다!"},"Doctor.Message.RebuildRequired":{def:"Attention! A rebuild is required to apply this!",ko:"주의! 이를 적용하려면 재구축이 필요합니다!"},"Doctor.Message.SomeSkipped":{def:"We left some issues as is. Shall I ask you again on next startup?",ko:"일부 문제를 그대로 두었습니다. 다음 시작 시 다시 질문할까요?"},"Doctor.RULES.E2EE_V02500.REASON":{def:"The End-to-End Encryption has got now more robust and faster. Also because, the previous E2EE was found to be compromised in a re-conducted code review. It should be applied as soon as possible. Really apologises for your inconvenience. And, this setting is not forward compatible. All synchronised devices must be updated to v0.25.0 or higher. Rebuilds are not required and will be converted from the new transfer to the new format, However, it is recommended to rebuild whenever possible."},"Enable advanced features":{def:"Enable advanced features",es:"Habilitar características avanzadas",ko:"고급 기능 활성화",zh:"启用高级功能"},"Enable customization sync":{def:"Enable customization sync",es:"Habilitar sincronización de personalización",ja:"カスタマイズ同期を有効",ko:"사용자 설정 동기화 활성화",zh:"启用自定义同步"},"Enable Developers' Debug Tools.":{def:"Enable Developers' Debug Tools.",es:"Habilitar herramientas de depuración",ko:"개발자 디버그 도구 활성화",zh:"启用开发者调试工具。"},"Enable edge case treatment features":{def:"Enable edge case treatment features",es:"Habilitar manejo de casos límite",ko:"특수 사례 처리 기능 활성화",zh:"启用边缘情况处理功能"},"Enable poweruser features":{def:"Enable poweruser features",es:"Habilitar funciones para usuarios avanzados",ko:"파워 유저 기능 활성화",zh:"启用高级用户功能"},"Enable this if your Object Storage doesn't support CORS":{def:"Enable this if your Object Storage doesn't support CORS",es:"Habilitar si su almacenamiento no soporta CORS",ko:"객체 스토리지가 CORS를 지원하지 않는 경우 활성화하세요",zh:"如果您的对象存储不支持 CORS请启用此功能。"},"Enable this option to automatically apply the most recent change to documents even when it conflicts":{def:"Enable this option to automatically apply the most recent change to documents even when it conflicts",es:"Aplicar cambios recientes automáticamente aunque generen conflictos",ko:"이 옵션을 활성화하면 충돌이 있어도 문서에 가장 최근 변경 사항을 자동으로 적용합니다",zh:"启用此选项可在文档冲突时自动应用最新的更改"},"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended.":{def:"Encrypt contents on the remote database. If you use the plugin's synchronization feature, enabling this is recommended.",es:"Cifrar contenido en la base de datos remota. Se recomienda habilitar si usa la sincronización del plugin.",ja:"リモートデータベースの暗号化(オンにすることをお勧めします)",ko:"원격 데이터베이스의 내용을 암호화합니다. 플러그인의 동기화 기능을 사용하는 경우 활성화를 권장합니다.",zh:"加密远程数据库中的内容。如果您使用插件的同步功能,则建议启用此功能。"},"Encrypting sensitive configuration items":{def:"Encrypting sensitive configuration items",es:"Cifrando elementos sensibles",ja:"機微設定項目の暗号化",ko:"민감한 구성 항목 암호화",zh:"加密敏感配置项"},"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files.":{def:"Encryption phassphrase. If changed, you should overwrite the server's database with the new (encrypted) files.",es:"Frase de cifrado. Si la cambia, sobrescriba la base del servidor con los nuevos archivos cifrados.",ko:"패스프레이즈는 암호화에 사용되는 긴 암호 문구입니다. 변경한 경우, 암호화된 새 파일로 서버의 데이터베이스를 덮어써야 합니다.",zh:"加密密码。如果更改,您应该用新的(加密的)文件覆盖服务器的数据库。"},"End-to-End Encryption":{def:"End-to-End Encryption",es:"Cifrado de extremo a extremo",ja:"E2E暗号化",ko:"종단간 암호화",zh:"端到端加密"},"Endpoint URL":{def:"Endpoint URL",es:"URL del endpoint",ja:"エンドポイントURL",ko:"엔드포인트 URL",zh:"Endpoint URL"},"Enhance chunk size":{def:"Enhance chunk size",es:"Mejorar tamaño de chunks",ja:"チャンクサイズを最新にする",ko:"청크 크기 향상",zh:"增强块大小"},"Fetch chunks on demand":{def:"Fetch chunks on demand",es:"Obtener chunks bajo demanda",ja:"ユーザーのタイミングでチャンクの更新を確認する",ko:"필요 시 청크 원격 가져오기",zh:"按需获取块"},"Fetch database with previous behaviour":{def:"Fetch database with previous behaviour",es:"Obtener BD con comportamiento anterior",ja:"以前の手法でデータベースを取得",ko:"이전 동작으로 데이터베이스 가져오기",zh:"使用以前的行为获取数据库"},Filename:{def:"Filename",es:"Nombre de archivo",ja:"ファイル名",ko:"파일명",zh:"文件名"},"Forces the file to be synced when opened.":{def:"Forces the file to be synced when opened.",es:"Forzar sincronización al abrir archivo",ko:"파일을 열 때 강제로 동기화합니다.",zh:"打开文件时强制同步该文件。"},"Handle files as Case-Sensitive":{def:"Handle files as Case-Sensitive",es:"Manejar archivos como sensibles a mayúsculas",ko:"파일을 대소문자 구분으로 처리",zh:"将文件视为区分大小写"},"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).":{def:"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour).",es:"Si se desactiva, chunks se dividen en hilo UI (comportamiento anterior)",ko:"비활성화(토글)되면 청크는 UI 스레드에서 분할됩니다 (이전 동작).",zh:"如果禁用切换chunks 将在 UI 线程上分割(以前的行为)。"},"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions.":{def:"If enabled per-filed efficient customization sync will be used. We need a small migration when enabling this. And all devices should be updated to v0.23.18. Once we enabled this, we lost a compatibility with old versions.",es:"Habilita sincronización eficiente por archivo. Requiere migración y actualizar todos dispositivos a v0.23.18. Pierde compatibilidad con versiones antiguas",ko:"활성화하면 파일별 효율적인 사용자 설정 동기화가 사용됩니다. 이를 활성화할 때 소규모 데이터 구조 전환이 필요합니다. 모든 기기를 v0.23.18로 업데이트해야 합니다. 이를 활성화하면 이전 버전과의 호환성이 사라집니다.",zh:"如果启用,将使用基于文件的、高效的自定义同步。启用此功能需要进行一次小的迁移。所有设备都应更新到 v0.23.18。一旦启用此功能,我们将失去与旧版本的兼容性。"},"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.":{def:"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker.",es:"Divide chunks en máximo 100 ítems. Menos eficiente en deduplicación",ko:"활성화하면 청크는 최대 100개 항목으로 분할됩니다. 하지만 중복 제거 기능이 약간 약해집니다.",zh:"如果启用,数据块将被分割成不超过 100 项。但是,去重效果会稍弱。"},"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.":{def:"If enabled, newly created chunks are temporarily kept within the document, and graduated to become independent chunks once stabilised.",es:"Chunks nuevos se mantienen temporalmente en el documento hasta estabilizarse",ko:"활성화하면 새로 생성된 변경 기록(청크)은 문서 안에 임시로 보관되며, 일정 조건을 만족하면 자동으로 문서 밖으로 분리되어 저장됩니다.",zh:"如果启用,新创建的数据块将暂时保留在文档中,并在稳定后成为独立数据块。"},"If enabled, the file under 1kb will be processed in the UI thread.":{def:"If enabled, the file under 1kb will be processed in the UI thread.",es:"Archivos <1kb se procesan en hilo UI",ko:"활성화하면 1kb 미만의 파일은 UI 스레드에서 처리됩니다.",zh:"如果启用,小于 1kb 的文件将在 UI 线程中处理。"},"If enabled, the notification of hidden files change will be suppressed.":{def:"If enabled, the notification of hidden files change will be suppressed.",es:"Si se habilita, se suprimirá la notificación de cambios en archivos ocultos.",ko:"활성화하면 숨겨진 파일 변경 알림이 억제됩니다.",zh:"如果启用,隐藏文件更改的通知将被抑制。"},"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)":{def:"If this enabled, all chunks will be stored with the revision made from its content. (Previous behaviour)",es:"Si se habilita, todos los chunks se almacenan con la revisión hecha desde su contenido. (comportamiento anterior)",ko:"이 옵션이 활성화되면 모든 청크는 콘텐츠에서 생성된 리비전과 함께 저장됩니다. (이전 동작)",zh:"如果启用,所有 chunks 将使用根据其内容生成的修订版本存储。(以前的行为)"},"If this enabled, All files are handled as case-Sensitive (Previous behaviour).":{def:"If this enabled, All files are handled as case-Sensitive (Previous behaviour).",es:"Si se habilita, todos los archivos se manejan como sensibles a mayúsculas (comportamiento anterior)",ko:"이 옵션이 활성화되면 모든 파일이 대소문자를 구분하여 처리됩니다 (이전 동작).",zh:"如果启用,所有文件都将视为区分大小写(以前的行为)。"},"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature.":{def:"If this enabled, chunks will be split into semantically meaningful segments. Not all platforms support this feature.",es:"Divide chunks en segmentos semánticos. No todos los sistemas lo soportan",ko:"이 옵션을 활성화하면 청크가 문단이나 의미 단위로 나뉘어 저장됩니다. 단, 이 기능은 일부 플랫폼에서는 지원되지 않을 수 있습니다.",zh:"如果启用此功能,数据块将被分割成具有语义意义的段落。并非所有平台都支持此功能。"},"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.":{def:"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files.",es:"Saltar cambios en archivos locales que coincidan con ignore files. Cambios remotos usan ignore files locales",ko:"이 옵션을 활성화하면, 제외 규칙 파일에 일치하는 로컬 파일의 변경 사항은 건너뜁니다. 원격 변경 여부 또한 로컬의 제외 규칙 파일에 따라 판단됩니다.",zh:"如果设置了此项,与忽略文件匹配的本地文件的更改将被跳过。远程更改使用本地忽略文件确定"},"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.":{def:"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage.",es:"Mantiene conexión 60s. Si no hay cambios, reinicia socket. Útil con proxies limitantes",ja:"PouchDBの接続を60秒間維持し、その間に変更がない場合、接続を切断してソケットを再び開きます。プロキシによるリクエスト時間制限があり、なおかつリソースの使用量が増える可能性がある場合に便利です。",ko:"이 옵션이 활성화되면 PouchDB는 연결을 더이상 무한히 열어두지 않고 60초 동안 유지합니다. 그 시간 내에 변경 사항이 없으면 소켓을 닫고 다시 엽니다. 프록시가 요청 지속 시간을 제한할 때 유용하지만 리소스 사용량이 증가할 수 있습니다.",zh:"如果启用此选项PouchDB 将保持连接打开 60 秒,如果在此时间内没有更改到达,则关闭并重新打开套接字,而不是无限期保持打开。当代理限制请求持续时间时有用,但可能会增加资源使用。"},"Ignore files":{def:"Ignore files",es:"Archivos a ignorar",ja:"無視ファイル",ko:"제외 규칙 파일",zh:"忽略文件"},"Incubate Chunks in Document":{def:"Incubate Chunks in Document",es:"Incubar chunks en documento",ja:"ドキュメント内でハッチングを行う",ko:"문서 내 변경 기록 임시 보관",zh:"在文档中孵化块(测试版)"},"Interval (sec)":{def:"Interval (sec)",es:"Intervalo (segundos)",ja:"秒",ko:"간격 (초)",zh:"间隔(秒)"},"K.exp":{def:"Experimental",ko:"실험 기능"},"K.long_p2p_sync":{def:"%{title_p2p_sync} (%{exp})",ko:"%{title_p2p_sync} (%{exp})"},"K.P2P":{def:"%{Peer}-to-%{Peer}",ko:"%{Peer}-to-%{Peer}"},"K.Peer":{def:"Peer",ko:"피어"},"K.ScanCustomization":{def:"Scan customization",ko:"사용자 설정 검색"},"K.short_p2p_sync":{def:"P2P Sync (%{exp})",ko:"P2P 동기화 (%{exp})"},"K.title_p2p_sync":{def:"Peer-to-Peer Sync",ko:"피어 투 피어(P2P) 동기화"},"Keep empty folder":{def:"Keep empty folder",es:"Mantener carpetas vacías",ja:"空フォルダの維持",ko:"빈 폴더 유지",zh:"保留空文件夹"},lang_def:{def:"Default",ko:"Default"},"lang-de":{def:"Deutsche",es:"Alemán",ko:"Deutsche",zh:"德语"},"lang-def":{def:"%{lang_def}",ko:"%{lang_def}"},"lang-es":{def:"Español",es:"Español",ko:"Español",zh:"西班牙语"},"lang-ja":{def:"日本語",es:"Japonés",ko:"日本語",zh:"日语"},"lang-ko":{def:"한국어",ko:"한국어"},"lang-ru":{def:"Русский",es:"Ruso",ko:"Русский",zh:"俄语"},"lang-zh":{def:"简体中文",es:"Chino simplificado",ko:"简体中文",zh:"简体中文"},"lang-zh-tw":{def:"繁體中文",es:"Chino tradicional",ko:"繁體中文",zh:"繁體中文"},"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.":{def:"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured.",es:"LiveSync no puede manejar múltiples bóvedas con mismo nombre sin prefijo. Se configura automáticamente",ja:"LiveSyncは、接頭詞のない同名の保管庫を扱うことができません。この設定は、自動的に設定されます。",ko:"LiveSync는 서로 다른 접두사 없이 동일한 이름을 가진 여러 볼트를 처리할 수 없습니다. 이는 자동으로 구성되어야 합니다.",zh:"LiveSync 无法处理具有相同名称但没有不同前缀的多个库。这应该自动配置。"},"liveSyncReplicator.beforeLiveSync":{def:"Before LiveSync, start OneShot once...",es:"Antes de LiveSync, inicia OneShot...",ko:"LiveSync 전에 OneShot을 먼저 시작합니다..."},"liveSyncReplicator.cantReplicateLowerValue":{def:"We can't replicate more lower value.",es:"No podemos replicar un valor más bajo.",ko:"더 낮은 값으로 복제할 수 없습니다."},"liveSyncReplicator.checkingLastSyncPoint":{def:"Looking for the point last synchronized point.",es:"Buscando el último punto sincronizado.",ko:"마지막으로 동기화된 지점을 찾고 있습니다."},"liveSyncReplicator.couldNotConnectTo":{def:"Could not connect to ${uri} : ${name}\n(${db})",es:"No se pudo conectar a ${uri} : ${name} \n(${db})",ko:"${uri}에 연결할 수 없습니다: ${name} \n(${db})"},"liveSyncReplicator.couldNotConnectToRemoteDb":{def:"Could not connect to remote database: ${d}",es:"No se pudo conectar a base de datos remota: ${d}",ko:"원격 데이터베이스에 연결할 수 없습니다: ${d}"},"liveSyncReplicator.couldNotConnectToServer":{def:"Could not connect to server.",es:"No se pudo conectar al servidor.",ko:"서버에 연결할 수 없습니다."},"liveSyncReplicator.couldNotConnectToURI":{def:"Could not connect to ${uri}:${dbRet}",es:"No se pudo conectar a ${uri}:${dbRet}",ko:"${uri}에 연결할 수 없습니다: ${dbRet}"},"liveSyncReplicator.couldNotMarkResolveRemoteDb":{def:"Could not mark resolve remote database.",es:"No se pudo marcar como resuelta la base de datos remota.",ko:"원격 데이터베이스를 해결됨으로 표시할 수 없습니다."},"liveSyncReplicator.liveSyncBegin":{def:"LiveSync begin...",es:"Inicio de LiveSync...",ko:"LiveSync 시작..."},"liveSyncReplicator.lockRemoteDb":{def:"Lock remote database to prevent data corruption",es:"Bloquear base de datos remota para prevenir corrupción de datos",ko:"데이터 손상을 방지하기 위해 원격 데이터베이스를 잠급니다"},"liveSyncReplicator.markDeviceResolved":{def:"Mark this device as 'resolved'.",es:"Marcar este dispositivo como 'resuelto'.",ko:"이 기기를 '해결됨'으로 표시합니다."},"liveSyncReplicator.oneShotSyncBegin":{def:"OneShot Sync begin... (${syncMode})",es:"Inicio de sincronización OneShot... (${syncMode})",ko:"OneShot 동기화 시작... (${syncMode})"},"liveSyncReplicator.remoteDbCorrupted":{def:"Remote database is newer or corrupted, make sure to latest version of self-hosted-livesync installed",es:"La base de datos remota es más nueva o está dañada, asegúrese de tener la última versión de self-hosted-livesync instalada",ko:"원격 데이터베이스가 더 최신이거나 손상되었습니다. 최신 버전의 self-hosted-livesync가 설치되어 있는지 확인하세요"},"liveSyncReplicator.remoteDbCreatedOrConnected":{def:"Remote Database Created or Connected",es:"Base de datos remota creada o conectada",ko:"원격 데이터베이스가 생성되거나 연결되었습니다"},"liveSyncReplicator.remoteDbDestroyed":{def:"Remote Database Destroyed",es:"Base de datos remota destruida",ko:"원격 데이터베이스가 삭제되었습니다"},"liveSyncReplicator.remoteDbDestroyError":{def:"Something happened on Remote Database Destroy:",es:"Algo ocurrió al destruir base de datos remota:",ko:"원격 데이터베이스 삭제 중 오류가 발생했습니다:"},"liveSyncReplicator.remoteDbMarkedResolved":{def:"Remote database has been marked resolved.",es:"Base de datos remota marcada como resuelta.",ko:"원격 데이터베이스가 해결됨으로 표시되었습니다."},"liveSyncReplicator.replicationClosed":{def:"Replication closed",es:"Replicación cerrada",ko:"복제가 종료되었습니다"},"liveSyncReplicator.replicationInProgress":{def:"Replication is already in progress",es:"Replicación en curso",ko:"복제가 이미 진행 중입니다"},"liveSyncReplicator.retryLowerBatchSize":{def:"Retry with lower batch size:${batch_size}/${batches_limit}",es:"Reintentar con tamaño de lote más bajo:${batch_size}/${batches_limit}",ko:"더 낮은 일괄 크기로 재시도: ${batch_size}/${batches_limit}"},"liveSyncReplicator.unlockRemoteDb":{def:"Unlock remote database to prevent data corruption",es:"Desbloquear base de datos remota para prevenir corrupción de datos",ko:"데이터 손상을 방지하기 위해 원격 데이터베이스를 잠금 해제합니다"},"liveSyncSetting.errorNoSuchSettingItem":{def:"No such setting item: ${key}",es:"No existe el ajuste: ${key}",ko:"해당 설정 항목이 없습니다: ${key}"},"liveSyncSetting.originalValue":{def:"Original: ${value}",es:"Original: ${value}",ko:"원본: ${value}"},"liveSyncSetting.valueShouldBeInRange":{def:"The value should ${min} < value < ${max}",es:"El valor debe estar entre ${min} y ${max}",ko:"값은 ${min} < 값 < ${max} 범위에 있어야 합니다"},"liveSyncSettings.btnApply":{def:"Apply",es:"Aplicar",ko:"적용"},"logPane.autoScroll":{def:"Auto scroll",es:"Autodesplazamiento",ko:"자동 스크롤",zh:"自动滚动"},"logPane.logWindowOpened":{def:"Log window opened",es:"Ventana de registro abierta",ko:"로그 창이 열렸습니다"},"logPane.pause":{def:"Pause",es:"Pausar",ko:"일시 중단",zh:"暂停"},"logPane.title":{def:"Self-hosted LiveSync Log",es:"Registro de Self-hosted LiveSync",ko:"Self-hosted LiveSync 로그",zh:"Self-hosted LiveSync 日志"},"logPane.wrap":{def:"Wrap",es:"Ajustar",ko:"줄 바꿈",zh:"自动换行"},"Maximum delay for batch database updating":{def:"Maximum delay for batch database updating",es:"Retraso máximo para actualización por lotes",ko:"일괄 데이터베이스 업데이트 최대 지연",zh:"批量数据库更新的最大延迟"},"Maximum file size":{def:"Maximum file size",es:"Tamaño máximo de archivo",ja:"最大ファイル容量",ko:"최대 파일 크기",zh:"最大文件大小"},"Maximum Incubating Chunk Size":{def:"Maximum Incubating Chunk Size",es:"Tamaño máximo de chunks incubados",ja:"保持するチャンクの最大サイズ",ko:"임시 보관 변경 기록의 최대 크기",zh:"最大孵化块大小"},"Maximum Incubating Chunks":{def:"Maximum Incubating Chunks",es:"Máximo de chunks incubados",ja:"最大ハッチング数",ko:"임시 보관 중인 변경 기록 최대 수",zh:"最大孵化块数"},"Maximum Incubation Period":{def:"Maximum Incubation Period",es:"Periodo máximo de incubación",ja:"最大保持期限",ko:"변경 기록 임시 보관 최대 시간",zh:"最大孵化期"},"MB (0 to disable).":{def:"MB (0 to disable).",es:"MB (0 para desactivar)",ko:"MB (0으로 설정하면 비활성화).",zh:"MB0为禁用。"},"Memory cache size (by total characters)":{def:"Memory cache size (by total characters)",es:"Tamaño caché memoria (por caracteres)",ja:"全体でキャッシュする文字数",ko:"메모리 캐시 크기 (총 문자 수)",zh:"内存缓存大小(按总字符数)"},"Memory cache size (by total items)":{def:"Memory cache size (by total items)",es:"Tamaño caché memoria (por ítems)",ja:"全体のキャッシュサイズ",ko:"메모리 캐시 크기 (총 항목 수)",zh:"内存缓存大小(按总项目数)"},"Minimum delay for batch database updating":{def:"Minimum delay for batch database updating",es:"Retraso mínimo para actualización por lotes",ko:"일괄 데이터베이스 업데이트 최소 지연",zh:"批量数据库更新的最小延迟"},"moduleCheckRemoteSize.logCheckingStorageSizes":{def:"Checking storage sizes",es:"Comprobando tamaños de almacenamiento",ko:"스토리지 크기 확인 중",zh:"正在检查存储大小"},"moduleCheckRemoteSize.logCurrentStorageSize":{def:"Remote storage size: ${measuredSize}",es:"Tamaño del almacenamiento remoto: ${measuredSize}",ko:"원격 스토리지 크기: ${measuredSize}",zh:"远程存储大小:${measuredSize}"},"moduleCheckRemoteSize.logExceededWarning":{def:"Remote storage size: ${measuredSize} exceeded ${notifySize}",es:"Tamaño del almacenamiento remoto: ${measuredSize} superó ${notifySize}",ko:"원격 스토리지 크기: ${measuredSize}가 ${notifySize}를 초과했습니다",zh:"远程存储大小:${measuredSize} 超过 ${notifySize}"},"moduleCheckRemoteSize.logThresholdEnlarged":{def:"Threshold has been enlarged to ${size}MB",es:"El umbral se ha ampliado a ${size}MB",ko:"임계값이 ${size}MB로 증가되었습니다",zh:"阈值已扩大到 ${size}MB"},"moduleCheckRemoteSize.msgConfirmRebuild":{def:"This may take a bit of a long time. Do you really want to rebuild everything now?",es:"Esto puede llevar un poco de tiempo. ¿Realmente quieres reconstruir todo ahora?",ko:"시간이 꽤 오래 걸릴 수 있습니다. 정말 지금 모든 것을 재구축하시겠습니까?",zh:"这可能需要一些时间。您真的想现在重建所有内容吗?"},"moduleCheckRemoteSize.msgDatabaseGrowing":{def:"**Your database is getting larger!** But do not worry, we can address it now. The time before running out of space on the remote storage.\n\n| Measured size | Configured size |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> If you have been using it for many years, there may be unreferenced chunks - that is, garbage - accumulating in the database. Therefore, we recommend rebuilding everything. It will probably become much smaller.\n>\n> If the volume of your vault is simply increasing, it is better to rebuild everything after organizing the files. Self-hosted LiveSync does not delete the actual data even if you delete it to speed up the process. It is roughly [documented](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md).\n>\n> If you don't mind the increase, you can increase the notification limit by 100MB. This is the case if you are running it on your own server. However, it is better to rebuild everything from time to time.\n>\n\n> [!WARNING]\n> If you perform rebuild everything, make sure all devices are synchronised. The plug-in will merge as much as possible, though.\n",es:"**¡Tu base de datos está creciendo!** Pero no te preocupes, podemos abordarlo ahora. El tiempo antes de quedarse sin espacio en el almacenamiento remoto.\n\n| Tamaño medido | Tamaño configurado |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> Si lo has estado utilizando durante muchos años, puede haber fragmentos no referenciados - es decir, basura - acumulándose en la base de datos. Por lo tanto, recomendamos reconstruir todo. Probablemente se volverá mucho más pequeño.\n>\n> Si el volumen de tu bóveda simplemente está aumentando, es mejor reconstruir todo después de organizar los archivos. Self-hosted LiveSync no elimina los datos reales incluso si los eliminas para acelerar el proceso. Está aproximadamente [documentado](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md).\n>\n> Si no te importa el aumento, puedes aumentar el límite de notificación en 100 MB. Este es el caso si lo estás ejecutando en tu propio servidor. Sin embargo, es mejor reconstruir todo de vez en cuando.\n>\n\n> [!WARNING]\n> Si realizas la reconstrucción completa, asegúrate de que todos los dispositivos estén sincronizados. El complemento fusionará tanto como sea posible, sin embargo.\n",ko:"**데이터베이스 용량이 점점 커지고 있습니다!** 하지만 걱정하지 마세요. 아직 원격 스토리지 공간이 완전히 부족해진 건 아닙니다.\n\n| 측정된 크기 | 설정된 한도 |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> 오랜 기간 사용했다면 참조되지 않는 청크, 즉 '쓰레기 데이터'가 쌓였을 수 있습니다. 이 경우 전체 재구성을 권장합니다. 용량이 훨씬 줄어들 수 있습니다.\n> \n> 단순히 볼트 자체 용량이 커지고 있는 것이라면, 먼저 파일을 정리한 후 전체를 재구성하는 것이 좋습니다. Self-hosted LiveSync는 처리 속도를 위해 삭제해도 실제 데이터를 바로 지우지 않습니다. 이 내용은 [기술 문서](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md)에 간략히 정리되어 있습니다.\n> \n> 용량 증가가 괜찮다면 알림 임계치를 100MB 단위로 높일 수 있습니다. 직접 서버를 운영하는 경우에 적합한 방법입니다. 다만, 가끔은 전체 재구성을 해주는 것이 바람직합니다.\n\n> [!WARNING]\n> 전체 재구성을 실행할 경우, 모든 기기가 반드시 동기화되어 있어야 합니다. 플러그인이 최대한 병합하려고 시도하긴 하지만 완전하지 않을 수 있습니다.",zh:"**您的数据库正在变大!** 但别担心,我们现在可以解决它。在远程存储空间用完之前还有时间。\n\n| 测量大小 | 配置大小 |\n| --- | --- |\n| ${estimatedSize} | ${maxSize} |\n\n> [!MORE]-\n> 如果您已经使用了很多年,数据库中可能会积累未引用的 chunks——也就是垃圾。因此我们建议重建所有内容。它可能会变得小得多。\n> \n> 如果您的库容量只是在增加最好在整理文件后重建所有内容。即使您为了加速过程删除了文件Self-hosted LiveSync 也不会删除实际数据。这大致[有文档记录](https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/tech_info.md)。\n> \n> 如果您不介意增加,可以将通知限制增加 100MB。如果您在自己的服务器上运行就是这种情况。但是最好还是不时地重建所有内容。\n> \n\n> [!WARNING]\n> 如果您执行重建所有内容,请确保所有设备都已同步。尽管如此,插件会尽可能地合并。\n"},"moduleCheckRemoteSize.msgSetDBCapacity":{def:"We can set a maximum database capacity warning, **to take action before running out of space on the remote storage**.\nDo you want to enable this?\n\n> [!MORE]-\n> - 0: Do not warn about storage size.\n> This is recommended if you have enough space on the remote storage especially you have self-hosted. And you can check the storage size and rebuild manually.\n> - 800: Warn if the remote storage size exceeds 800MB.\n> This is recommended if you are using fly.io with 1GB limit or IBM Cloudant.\n> - 2000: Warn if the remote storage size exceeds 2GB.\n\nIf we have reached the limit, we will be asked to enlarge the limit step by step.\n",es:"Podemos configurar una advertencia de capacidad máxima de base de datos, **para tomar medidas antes de quedarse sin espacio en el almacenamiento remoto**.\n¿Quieres habilitar esto?\n\n> [!MORE]-\n> - 0: No advertir sobre el tamaño del almacenamiento.\n> Esto es recomendado si tienes suficiente espacio en el almacenamiento remoto, especialmente si lo tienes autoalojado. Y puedes comprobar el tamaño del almacenamiento y reconstruir manualmente.\n> - 800: Advertir si el tamaño del almacenamiento remoto supera los 800 MB.\n> Esto es recomendado si estás usando fly.io con un límite de 1 GB o IBM Cloudant.\n> - 2000: Advertir si el tamaño del almacenamiento remoto supera los 2 GB.\n\nSi hemos alcanzado el límite, se nos pedirá que aumentemos el límite paso a paso.\n",ko:"**원격 스토리지 공간이 부족해지기 전에 미리 조치할 수 있도록** 데이터베이스 용량 경고를 설정할 수 있습니다.\n이 기능을 활성화하시겠습니까?\n\n> [!MORE]-\n> - 0: 스토리지 용량에 대한 경고 없음\n> 자체 서버를 사용하는 등 여유 공간이 충분한 경우에 권장됩니다. 스토리지 용량을 직접 확인하고 수동으로 재구성할 수 있습니다.\n> - 800: 원격 스토리지 용량이 800MB를 초과하면 경고\n> 1GB 제한이 있는 fly.io나 IBM Cloudant 사용 시 권장됩니다.\n> - 2000: 원격 스토리지 용량이 2GB를 초과하면 경고\n\n설정한 용량 한도에 도달하면, 단계적으로 경고 한도를 늘릴지 여부를 묻게 됩니다.\n",zh:"我们可以设置一个最大数据库容量警告,**以便在远程存储空间耗尽前采取行动**。\n您想启用这个功能吗\n\n> [!MORE]-\n> - 0: 不警告存储大小。\n> 如果您在远程存储(尤其是自托管)上有足够的空间,则推荐此选项。您可以手动检查存储大小并重建。\n> - 800: 如果远程存储大小超过 800MB 则发出警告。\n> 如果您使用的是 fly.io1GB 限制)或 IBM Cloudant则推荐此选项。\n> - 2000: 如果远程存储大小超过 2GB 则发出警告。\n\n如果达到限制系统会要求我们逐步增大限制。\n"},"moduleCheckRemoteSize.option2GB":{def:"2GB (Standard)",es:"2GB (Estándar)",ko:"2GB (표준)",zh:"2GB (标准)"},"moduleCheckRemoteSize.option800MB":{def:"800MB (Cloudant, fly.io)",es:"800MB (Cloudant, fly.io)",ko:"800MB (Cloudant, fly.io)",zh:"800MB (Cloudant, fly.io)"},"moduleCheckRemoteSize.optionAskMeLater":{def:"Ask me later",es:"Pregúntame más tarde",ko:"나중에 물어보기",zh:"稍后问我"},"moduleCheckRemoteSize.optionDismiss":{def:"Dismiss",es:"Descartar",ko:"무시",zh:"忽略"},"moduleCheckRemoteSize.optionIncreaseLimit":{def:"increase to ${newMax}MB",es:"aumentar a ${newMax}MB",ko:"${newMax}MB로 증가",zh:"增加到 ${newMax}MB"},"moduleCheckRemoteSize.optionNoWarn":{def:"No, never warn please",es:"No, nunca advertir por favor",ko:"아니요, 경고하지 마세요",zh:"不,请永远不要警告"},"moduleCheckRemoteSize.optionRebuildAll":{def:"Rebuild Everything Now",es:"Reconstruir todo ahora",ko:"지금 모든 것 재구축",zh:"立即重建所有内容"},"moduleCheckRemoteSize.titleDatabaseSizeLimitExceeded":{def:"Remote storage size exceeded the limit",es:"El tamaño del almacenamiento remoto superó el límite",ko:"원격 스토리지 크기가 제한을 초과했습니다",zh:"远程存储大小超出限制"},"moduleCheckRemoteSize.titleDatabaseSizeNotify":{def:"Setting up database size notification",es:"Configuración de notificación de tamaño de base de datos",ko:"데이터베이스 크기 알림 설정",zh:"设置数据库大小通知"},"moduleInputUIObsidian.defaultTitleConfirmation":{def:"Confirmation",es:"Confirmación",ko:"확인",zh:"确认"},"moduleInputUIObsidian.defaultTitleSelect":{def:"Select",es:"Seleccionar",ko:"선택",zh:"选择"},"moduleInputUIObsidian.optionNo":{def:"No",es:"No",ko:"아니요",zh:"否"},"moduleInputUIObsidian.optionYes":{def:"Yes",es:"Sí",ko:"예",zh:"是"},"moduleLiveSyncMain.logAdditionalSafetyScan":{def:"Additional safety scan...",es:"Escanéo de seguridad adicional...",ko:"추가 안전 검사 중...",zh:"额外的安全扫描..."},"moduleLiveSyncMain.logLoadingPlugin":{def:"Loading plugin...",es:"Cargando complemento...",ko:"플러그인 로딩 중...",zh:"正在加载插件..."},"moduleLiveSyncMain.logPluginInitCancelled":{def:"Plugin initialisation was cancelled by a module",es:"La inicialización del complemento fue cancelada por un módulo",ko:"모듈에 의해 플러그인 초기화가 취소되었습니다",zh:"插件初始化被某个模块取消"},"moduleLiveSyncMain.logPluginVersion":{def:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}",es:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}",ko:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}",zh:"Self-hosted LiveSync v${manifestVersion} ${packageVersion}"},"moduleLiveSyncMain.logReadChangelog":{def:"LiveSync has updated, please read the changelog!",es:"LiveSync se ha actualizado, ¡por favor lee el registro de cambios!",ko:"LiveSync가 업데이트되었습니다. 변경사항을 읽어보세요!",zh:"LiveSync 已更新,请阅读更新日志!"},"moduleLiveSyncMain.logSafetyScanCompleted":{def:"Additional safety scan completed",es:"Escanéo de seguridad adicional completado",ko:"추가 안전 검사가 완료되었습니다",zh:"额外的安全扫描完成"},"moduleLiveSyncMain.logSafetyScanFailed":{def:"Additional safety scan has failed on a module",es:"El escaneo de seguridad adicional ha fallado en un módulo",ko:"모듈에서 추가 안전 검사가 실패했습니다",zh:"额外的安全扫描在某个模块上失败"},"moduleLiveSyncMain.logUnloadingPlugin":{def:"Unloading plugin...",es:"Descargando complemento...",ko:"플러그인 언로딩 중...",zh:"正在卸载插件..."},"moduleLiveSyncMain.logVersionUpdate":{def:"LiveSync has been updated, In case of breaking updates, all automatic synchronization has been temporarily disabled. Ensure that all devices are up to date before enabling.",es:"LiveSync se ha actualizado, en caso de actualizaciones que rompan, toda la sincronización automática se ha desactivado temporalmente. Asegúrate de que todos los dispositivos estén actualizados antes de habilitar.",ko:"LiveSync가 업데이트되었습니다. 호환성 문제가 있는 업데이트의 경우 모든 자동 동기화가 일시적으로 비활성화되었습니다. 활성화하기 전에 모든 기기가 최신 상태인지 확인하세요.",zh:"LiveSync 已更新,如果存在破坏性更新,所有自动同步已暂时禁用。请确保所有设备都更新到最新版本后再启用。"},"moduleLiveSyncMain.msgScramEnabled":{def:"Self-hosted LiveSync has been configured to ignore some events. Is this correct?\n\n| Type | Status | Note |\n|:---:|:---:|---|\n| Storage Events | ${fileWatchingStatus} | Every modification will be ignored |\n| Database Events | ${parseReplicationStatus} | Every synchronised change will be postponed |\n\nDo you want to resume them and restart Obsidian?\n\n> [!DETAILS]-\n> These flags are set by the plug-in while rebuilding, or fetching. If the process ends abnormally, it may be kept unintended.\n> If you are not sure, you can try to rerun these processes. Make sure to back your vault up.\n",es:"Self-hosted LiveSync se ha configurado para ignorar algunos eventos. ¿Es esto correcto?\n\n| Tipo | Estado | Nota |\n|:---:|:---:|---|\n| Eventos de almacenamiento | ${fileWatchingStatus} | Se ignorará cada modificación |\n| Eventos de base de datos | ${parseReplicationStatus} | Cada cambio sincronizado se pospondrá |\n\n¿Quieres reanudarlos y reiniciar Obsidian?\n\n> [!DETAILS]-\n> Estas banderas son establecidas por el complemento mientras se reconstruye o se obtiene. Si el proceso termina de forma anormal, puede mantenerse sin querer.\n> Si no estás seguro, puedes intentar volver a ejecutar estos procesos. Asegúrate de hacer una copia de seguridad de tu bóveda.\n",ko:"Self-hosted LiveSync가 일부 이벤트를 무시하도록 설정되어 있습니다. 이 설정이 맞습니까?\n\n| 유형 | 상태 | 설명 |\n|:---:|:---:|---|\n| 스토리지 이벤트 | ${fileWatchingStatus} | 모든 수정 사항이 무시됩니다 |\n| 데이터베이스 이벤트 | ${parseReplicationStatus} | 모든 동기화 변경이 지연됩니다 |\n\n이벤트 감지를 다시 활성화하고 Obsidian을 재시작하시겠습니까?\n\n> [!DETAILS]-\n> 이러한 설정은 플러그인이 재구성 또는 데이터 가져오기 중에 자동으로 설정한 것입니다. 프로세스가 비정상적으로 종료되면 이 상태가 의도치 않게 유지될 수 있습니다.\n> 상태가 확실하지 않다면 이 과정을 다시 실행해 보세요. 재시작 전에 반드시 볼트를 백업해 주세요.",zh:"Self-hosted LiveSync 已被配置为忽略某些事件。这样对吗?\n\n| 类型 | 状态 | 说明 |\n|:---:|:---:|---|\n| 存储事件 | ${fileWatchingStatus} | 所有修改都将被忽略 |\n| 数据库事件 | ${parseReplicationStatus} | 所有同步的更改都将被推迟 |\n\n您想恢复它们并重启 Obsidian 吗?\n\n> [!DETAILS]-\n> 这些标志是在重建或获取时由插件设置的。如果过程异常结束,它们可能会被无意中保留。\n> 如果您不确定,可以尝试重新运行这些过程。请确保备份您的库。\n"},"moduleLiveSyncMain.optionKeepLiveSyncDisabled":{def:"Keep LiveSync disabled",es:"Mantener LiveSync desactivado",ko:"LiveSync 비활성화 유지",zh:"保持 LiveSync 禁用"},"moduleLiveSyncMain.optionResumeAndRestart":{def:"Resume and restart Obsidian",es:"Reanudar y reiniciar Obsidian",ko:"재개 후 Obsidian 재시작",zh:"恢复并重启 Obsidian"},"moduleLiveSyncMain.titleScramEnabled":{def:"Scram Enabled",es:"Scram habilitado",ko:"Scram 활성화됨",zh:"紧急停止已启用"},"moduleLocalDatabase.logWaitingForReady":{def:"Waiting for ready...",es:"Esperando a que la base de datos esté lista...",ja:"しばらくお待ちください...",ko:"준비 대기 중...",zh:"等待就绪..."},"moduleLog.showLog":{def:"Show Log",es:"Mostrar registro",ko:"로그 표시"},"moduleMigration.docUri":{def:"https://github.com/vrtmrz/obsidian-livesync/blob/main/README.md#how-to-use",es:"https://github.com/vrtmrz/obsidian-livesync/blob/main/README_ES.md#how-to-use",ko:"https://github.com/vrtmrz/obsidian-livesync/blob/main/README.md#how-to-use",zh:"https://github.com/vrtmrz/obsidian-livesync/blob/main/docs/zh/README_zh.md#%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8"},"moduleMigration.fix0256.buttons.checkItLater":{def:"Check it later"},"moduleMigration.fix0256.buttons.DismissForever":{def:"I have fixed it, and do not ask again"},"moduleMigration.fix0256.buttons.fix":{def:"Fix"},"moduleMigration.fix0256.message":{def:'Due to a recent bug (in v0.25.6), some files may not have been saved correctly in the sync database.\nWe have scanned our files and found some that need to be fixed.\n\n**Files ready to be fixed:**\n\n${files}\n\nThese files have size-matched original file on the storage, and are likely to be recoverable.\nWe can use them to fix the database, please click the "Fix" button below to fix them.\n\n${messageUnrecoverable}\n\nIf you want to run it again, you can do so from Hatch.\n'},"moduleMigration.fix0256.messageUnrecoverable":{def:"**Files cannot be fixed on this device:**\n\n${filesNotRecoverable}\n\nThese files have inconsistent metadata, and cannot be fixed on this device (mostly we cannot determine which is correct).\nTo restore them, please check your other devices (also by this feature) or restore them manually from a backup.\n"},"moduleMigration.fix0256.title":{def:"Broken files has been detected"},"moduleMigration.insecureChunkExist.buttons.fetch":{def:"I already rebuilt the remote. Fetch from the remote"},"moduleMigration.insecureChunkExist.buttons.later":{def:"I will do it later"},"moduleMigration.insecureChunkExist.buttons.rebuild":{def:"Rebuild Everything"},"moduleMigration.insecureChunkExist.laterMessage":{def:"We strongly recommend to treat this as soon as possible!"},"moduleMigration.insecureChunkExist.message":{def:"Some chunks are not securely stored and are not encrypted in databases.\n**Please rebuild the database to fix this issue**.\n\nIf your Remote Database is not configured with SSL, or using less-secure credentials, **you are at risk of exposing sensitive data**.\n\nNote: Please upgrade your Self-hosted LiveSync v0.25.6 or higher on all your devices, and back your vault up surely.\nNote2: Rebuild Everything and Fetch consumes a bit of time and traffic, please do it in off-peak hours and ensure a stable network connection.\n"},"moduleMigration.insecureChunkExist.title":{def:"Insecure chunks found!"},"moduleMigration.logBulkSendCorrupted":{def:"Send chunks in bulk has been enabled, however, this feature had been corrupted. Sorry for your inconvenience. Automatically disabled.",es:"El envío de fragmentos en bloque se ha habilitado, sin embargo, esta función se ha corrompido. Disculpe las molestias. Deshabilitado automáticamente.",ko:"청크 일괄 전송이 활성화되었지만, 이 기능에 문제가 있었습니다. 불편을 드려 죄송합니다. 자동으로 비활성화되었습니다.",zh:"已启用批量发送 chunks但此功能已损坏。给您带来不便我们深表歉意。已自动禁用。"},"moduleMigration.logFetchRemoteTweakFailed":{def:"Failed to fetch remote tweak values",es:"Error al obtener los valores de ajuste remoto",ko:"원격 조정 값을 가져오는데 실패했습니다",zh:"获取远程调整值失败"},"moduleMigration.logLocalDatabaseNotReady":{def:"Something went wrong! The local database is not ready",es:"¡Algo salió mal! La base de datos local no está lista",ko:"문제가 발생했습니다! 로컬 데이터베이스가 준비되지 않았습니다",zh:"出错了!本地数据库尚未准备好"},"moduleMigration.logMigratedSameBehaviour":{def:"Migrated to db:${current} with the same behaviour as before",es:"Migrado a db:${current} con el mismo comportamiento que antes",ko:"이전과 같은 방식으로 동작하도록 db:${current}로 데이터 구조 전환이 완료되었습니다",zh:"已迁移到 db:${current},行为与之前相同"},"moduleMigration.logMigrationFailed":{def:"Migration failed or cancelled from ${old} to ${current}",es:"La migración falló o se canceló de ${old} a ${current}",ko:"${old}에서 ${current}로의 데이터 구조 전환이 실패했거나 중단되었습니다",zh:"从 ${old} 到 ${current} 的迁移失败或已取消"},"moduleMigration.logRedflag2CreationFail":{def:"Failed to create redflag2",es:"Error al crear redflag2",ko:"redflag2 생성에 실패했습니다",zh:"创建 redflag2 失败"},"moduleMigration.logRemoteTweakUnavailable":{def:"Could not get remote tweak values",es:"No se pudieron obtener los valores de ajuste remoto",ko:"원격 조정 값을 가져올 수 없습니다",zh:"无法获取远程调整值"},"moduleMigration.logSetupCancelled":{def:"The setup has been cancelled, Self-hosted LiveSync waiting for your setup!",es:"La configuración ha sido cancelada, ¡Self-hosted LiveSync está esperando tu configuración!",ko:"설정이 취소되었습니다. Self-hosted LiveSync가 설정을 기다리고 있습니다!",zh:"设置已取消Self-hosted LiveSync 正在等待您的设置!"},"moduleMigration.msgFetchRemoteAgain":{def:"As you may already know, the self-hosted LiveSync has changed its default behaviour and database structure.\n\nAnd thankfully, with your time and efforts, the remote database appears to have already been migrated. Congratulations!\n\nHowever, we need a bit more. The configuration of this device is not compatible with the remote database. We will need to fetch the remote database again. Should we fetch from the remote again now?\n\n___Note: We cannot synchronise until the configuration has been changed and the database has been fetched again.___\n___Note2: The chunks are completely immutable, we can fetch only the metadata and difference.___",es:"Como ya sabrás, Self-hosted LiveSync ha cambiado su comportamiento predeterminado y la estructura de la base de datos.\n\nAfortunadamente, con tu tiempo y esfuerzo, la base de datos remota parece haber sido ya migrada. ¡Felicidades!\n\nSin embargo, necesitamos un poco más. La configuración de este dispositivo no es compatible con la base de datos remota. Necesitaremos volver a obtener la base de datos remota. ¿Debemos obtenerla nuevamente ahora?\n\n___Nota: No podemos sincronizar hasta que la configuración haya sido cambiada y la base de datos haya sido obtenida nuevamente.___\n___Nota2: Los fragmentos son completamente inmutables, solo podemos obtener los metadatos y diferencias.___",ko:"이미 알고 계시겠지만, Self-hosted LiveSync의 기본 동작 방식과 데이터베이스 구조가 변경되었습니다.\n\n다행히도 여러분의 노력 덕분에 원격 데이터베이스는 이미 성공적으로 데이터 구조 전환이 완료된 것으로 보입니다. 축하드립니다!\n\n하지만 아직 일부 추가 작업이 필요합니다. 이 기기의 설정이 원격 데이터베이스와 호환되지 않으므로, 원격 데이터를 다시 가져와야 합니다. 지금 원격 데이터베이스를 다시 가져오시겠습니까?\n\n___참고: 설정이 변경되고 데이터베이스를 다시 불러오기 전까지는 동기화가 불가능합니다.___\n___참고2: 청크는 변경이 불가능한 구조이므로, 메타데이터와 차이점만 가져올 수 있습니다.___",zh:"您可能已经知道Self-hosted LiveSync 更改了其默认行为和数据库结构。\n\n值得庆幸的是在您的时间和努力下远程数据库似乎已经迁移完成。恭喜\n\n但是我们还需要一点点操作。此设备的配置与远程数据库不兼容。我们需要再次从远程数据库获取。我们现在应该再次从远程获取吗\n\n___注意在更改配置并再次获取数据库之前我们无法进行同步。___\n___注意2chunks 是完全不可变的我们只能获取元数据和差异。___"},"moduleMigration.msgInitialSetup":{def:"Your device has **not been set up yet**. Let me guide you through the setup process.\n\nPlease keep in mind that every dialogue content can be copied to the clipboard. If you need to refer to it later, you can paste it into a note in Obsidian. You can also translate it into your language using a translation tool.\n\nFirst, do you have **Setup URI**?\n\nNote: If you do not know what it is, please refer to the [documentation](${URI_DOC}).",es:"Tu dispositivo **aún no ha sido configurado**. Permíteme guiarte a través del proceso de configuración.\n\nTen en cuenta que todo el contenido del diálogo se puede copiar al portapapeles. Si necesitas consultarlo más tarde, puedes pegarlo en una nota en Obsidian. También puedes traducirlo a tu idioma utilizando una herramienta de traducción.\n\nPrimero, ¿tienes **URI de configuración**?\n\nNota: Si no sabes qué es, consulta la [documentación](${URI_DOC}).",ko:"이 기기는 **아직 초기 설정이 완료되지 않았습니다**. 지금부터 설정 과정을 안내해 드리겠습니다.\n\n모든 대화 내용은 클립보드에 복사할 수 있습니다. 나중에 참고하려면 Obsidian 노트에 붙여넣거나 번역 도구를 활용해 번역하셔도 됩니다.\n\n먼저, **Setup URI**를 가지고 계신가요?\n\n참고: Setup URI가 무엇인지 잘 모르시겠다면 [문서](${URI_DOC})를 참고해 주세요.",zh:"您的设备**尚未设置**。让我引导您完成设置过程。\n\n请记住每个对话框内容都可以复制到剪贴板。如果以后需要参考可以将其粘贴到 Obsidian 的笔记中。您也可以使用翻译工具将其翻译成您的语言。\n\n首先您有**设置 URI** 吗?\n\n注意如果您不知道这是什么请参阅[文档](${URI_DOC})。"},"moduleMigration.msgRecommendSetupUri":{def:"We strongly recommend that you generate a set-up URI and use it.\nIf you do not have knowledge about it, please refer to the [documentation](${URI_DOC}) (Sorry again, but it is important).\n\nHow do you want to set it up manually?",es:"Te recomendamos encarecidamente que generes una URI de configuración y la utilices.\nSi no tienes conocimientos al respecto, consulta la [documentación](${URI_DOC}) (Lo siento de nuevo, pero es importante).\n\n¿Cómo quieres configurarlo manualmente?",ko:"Setup URI를 생성해 사용하는 것을 강력히 권장합니다.\nSetup URI가 무엇인지 잘 모르시겠다면 [문서](${URI_DOC})를 참고해 주세요. 중요한 내용이니 꼭 확인하시기 바랍니다.\n\n직접 수동 설정을 진행하시겠습니까?",zh:"我们强烈建议您生成一个设置 URI 并使用它。\n如果您对此不了解请参阅[文档](${URI_DOC})(再次抱歉,但这很重要)。\n\n您想如何手动设置"},"moduleMigration.msgSinceV02321":{def:"Since v0.23.21, the self-hosted LiveSync has changed the default behaviour and database structure. The following changes have been made:\n\n1. **Case sensitivity of filenames**\n The handling of filenames is now case-insensitive. This is a beneficial change for most platforms, other than Linux and iOS, which do not manage filename case sensitivity effectively.\n (On These, a warning will be displayed for files with the same name but different cases).\n\n2. **Revision handling of the chunks**\n Chunks are immutable, which allows their revisions to be fixed. This change will enhance the performance of file saving.\n\n___However, to enable either of these changes, both remote and local databases need to be rebuilt. This process takes a few minutes, and we recommend doing it when you have ample time.___\n\n- If you wish to maintain the previous behaviour, you can skip this process by using `${KEEP}`.\n- If you do not have enough time, please choose `${DISMISS}`. You will be prompted again later.\n- If you have rebuilt the database on another device, please select `${DISMISS}` and try synchronizing again. Since a difference has been detected, you will be prompted again.",es:"Desde la versión v0.23.21, Self-hosted LiveSync ha cambiado el comportamiento predeterminado y la estructura de la base de datos. Se han realizado los siguientes cambios:\n\n1. **Sensibilidad a mayúsculas de los nombres de archivo**\n El manejo de los nombres de archivo ahora no distingue entre mayúsculas y minúsculas. Este cambio es beneficioso para la mayoría de las plataformas, excepto Linux y iOS, que no gestionan efectivamente la sensibilidad a mayúsculas de los nombres de archivo.\n (En estos, se mostrará una advertencia para archivos con el mismo nombre pero diferentes mayúsculas).\n\n2. **Manejo de revisiones de los fragmentos**\n Los fragmentos son inmutables, lo que permite que sus revisiones sean fijas. Este cambio mejorará el rendimiento al guardar archivos.\n\n___Sin embargo, para habilitar cualquiera de estos cambios, es necesario reconstruir tanto las bases de datos remota como la local. Este proceso toma unos minutos, y recomendamos hacerlo cuando tengas tiempo suficiente.___\n\n- Si deseas mantener el comportamiento anterior, puedes omitir este proceso usando `${KEEP}`.\n- Si no tienes suficiente tiempo, por favor elige `${DISMISS}`. Se te pedirá nuevamente más tarde.\n- Si has reconstruido la base de datos en otro dispositivo, selecciona `${DISMISS}` e intenta sincronizar nuevamente. Dado que se ha detectado una diferencia, se te solicitará nuevamente.",ko:"v0.23.21부터 Self-hosted LiveSync의 기본 동작 방식과 데이터베이스 구조가 변경되었습니다. 주요 변경사항은 다음과 같습니다:\n\n1. **파일명 대소문자 구분 처리**\n 이제 파일명은 대소문자를 구분하지 않고 처리됩니다. 이는 파일명 구분을 제대로 지원하지 않는 Linux 및 iOS를 제외한 대부분의 플랫폼에서 유리한 변화입니다.\n (Linux나 iOS에서는 대소문자만 다른 파일이 존재할 경우 경고가 표시됩니다)\n\n2. **청크 리비전 관리 방식 개선**\n 청크는 변경 불가능한(immutable) 구조로 고정되며, 이를 통해 리비전 처리가 안정화되고 파일 저장 성능이 향상됩니다.\n\n___단, 위 기능을 활성화하려면 원격 및 로컬 데이터베이스를 모두 재구성해야 합니다. 이 과정은 수 분이 소요되므로 여유가 있을 때 실행하시는 것을 권장합니다.___\n\n- 기존 방식대로 유지하려면 `${KEEP}`을 선택해 이 과정을 건너뛸 수 있습니다.\n- 시간이 부족하다면 `${DISMISS}`를 눌러주시면 나중에 다시 안내드리겠습니다.\n- 이미 다른 기기에서 데이터베이스를 재구성하셨다면 `${DISMISS}`를 선택한 뒤 다시 동기화해 보세요. 차이점이 감지되면 다시 안내드리겠습니다.",zh:"自 v0.23.21 起Self-hosted LiveSync 更改了默认行为和数据库结构。进行了以下更改:\n\n1. **文件名的区分大小写** \n现在处理文件名时不区分大小写。这对于大多数平台来说是一个有益的更改除了 Linux 和 iOS它们不能有效地管理文件名的大小写敏感性。\n在这些平台上对于名称相同但大小写不同的文件将显示警告。\n\n2. **chunks 的版本处理** \nchunks 是不可变的,这使得它们的版本可以固定。此更改将提高文件保存的性能。\n\n___然而要启用这些更改中的任何一个都需要重建远程和本地数据库。这个过程需要几分钟我们建议您在有充足时间时进行。___\n\n- 如果您希望保持以前的行为,可以使用 `${KEEP}` 跳过此过程。\n- 如果您没有足够的时间,请选择 `${DISMISS}`。稍后会再次提示您。\n- 如果您已在另一台设备上重建了数据库,请选择 `${DISMISS}` 并尝试再次同步。由于检测到差异,系统会再次提示您。"},"moduleMigration.optionAdjustRemote":{def:"Adjust to remote",es:"Ajustar al remoto",ko:"원격에 맞추기",zh:"调整到远程设置"},"moduleMigration.optionDecideLater":{def:"Decide it later",es:"Decidirlo más tarde",ko:"나중에 결정하기",zh:"稍后决定"},"moduleMigration.optionEnableBoth":{def:"Enable both",es:"Habilitar ambos",ko:"둘 다 활성화",zh:"启用两者"},"moduleMigration.optionEnableFilenameCaseInsensitive":{def:"Enable only #1",es:"Habilitar solo #1",ko:"#1만 활성화",zh:"仅启用 #1"},"moduleMigration.optionEnableFixedRevisionForChunks":{def:"Enable only #2",es:"Habilitar solo #2",ko:"#2만 활성화",zh:"仅启用 #2"},"moduleMigration.optionHaveSetupUri":{def:"Yes, I have",es:"Sí, tengo",ko:"예, 있습니다",zh:"是的,我有"},"moduleMigration.optionKeepPreviousBehaviour":{def:"Keep previous behaviour",es:"Mantener comportamiento anterior",ko:"이전 동작 유지",zh:"保持以前的行为"},"moduleMigration.optionManualSetup":{def:"Set it up all manually",es:"Configurarlo todo manualmente",ko:"모든 것을 수동으로 설정",zh:"全部手动设置"},"moduleMigration.optionNoAskAgain":{def:"No, please ask again",es:"No, por favor pregúntame de nuevo",ko:"아니요 (나중에 다시 물어보기)",zh:"不,请稍后再次询问"},"moduleMigration.optionNoSetupUri":{def:"No, I do not have",es:"No, no tengo",ko:"아니요, 없습니다",zh:"不,我没有"},"moduleMigration.optionRemindNextLaunch":{def:"Remind me at the next launch",es:"Recordármelo en el próximo inicio",ko:"다음 시작 시 알림",zh:"下次启动时提醒我"},"moduleMigration.optionSetupViaP2P":{def:"Use %{short_p2p_sync} to set up",ko:"%{short_p2p_sync}를 사용하여 설정"},"moduleMigration.optionSetupWizard":{def:"Take me into the setup wizard",es:"Llévame al asistente de configuración",ko:"설정 마법사로 안내",zh:"带我进入设置向导"},"moduleMigration.optionYesFetchAgain":{def:"Yes, fetch again",es:"Sí, obtener nuevamente",ko:"예 (다시 가져오기)",zh:"是的,再次获取"},"moduleMigration.titleCaseSensitivity":{def:"Case Sensitivity",es:"Sensibilidad a mayúsculas",ko:"대소문자 구분",zh:"大小写敏感性"},"moduleMigration.titleRecommendSetupUri":{def:"Recommendation to use Setup URI",es:"Recomendación de uso de URI de configuración",ko:"Setup URI 사용 권장",zh:"推荐使用设置 URI"},"moduleMigration.titleWelcome":{def:"Welcome to Self-hosted LiveSync",es:"Bienvenido a Self-hosted LiveSync",ko:"Self-hosted LiveSync에 오신 것을 환영합니다",zh:"欢迎使用 Self-hosted LiveSync"},"moduleObsidianMenu.replicate":{def:"Replicate",es:"Replicar",ko:"복제"},"Move remotely deleted files to the trash, instead of deleting.":{def:"Move remotely deleted files to the trash, instead of deleting.",es:"Mover archivos borrados remotos a papelera en lugar de eliminarlos",ko:"원격에서 삭제된 파일을 삭제하는 대신 휴지통으로 이동합니다.",zh:"将远程删除的文件移至回收站,而不是直接删除。"},'Not all messages have been translated. And, please revert to "Default" when reporting errors.':{def:'Not all messages have been translated. And, please revert to "Default" when reporting errors.',es:'No todos los mensajes están traducidos. Por favor, vuelva a "Predeterminado" al reportar errores.',ja:'すべてのメッセージが翻訳されているわけではありません。また、Issue報告の際にはいったん"Default"に戻してください',ko:'모든 메시지가 번역되지 않았습니다. 오류 신고 시 "기본값"으로 되돌려 주세요.',zh:'并非所有消息都已翻译。请在报告错误时恢复为"Default"'},"Notify all setting files":{def:"Notify all setting files",es:"Notificar todos los archivos de configuración",ja:"すべての設定を通知",ko:"모든 설정 파일 알림",zh:"通知所有设置文件"},"Notify customized":{def:"Notify customized",es:"Notificar personalizaciones",ja:"カスタマイズが行われたら通知する",ko:"사용자 설정 알림",zh:"通知自定义设置"},"Notify when other device has newly customized.":{def:"Notify when other device has newly customized.",es:"Notificar cuando otro dispositivo personalice",ja:"別の端末がカスタマイズを行なったら通知する",ko:"다른 기기에서 새로운 사용자 설정이 있을 때 알림을 받습니다.",zh:"当其他设备有新的自定义设置时通知。"},"Notify when the estimated remote storage size exceeds on start up":{def:"Notify when the estimated remote storage size exceeds on start up",es:"Notificar cuando el tamaño estimado del almacenamiento remoto exceda al iniciar",ko:"시작 시 예상 원격 스토리지 크기가 초과되면 알림",zh:"启动时当估计的远程存储大小超出时通知"},"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.":{def:"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time.",es:"Número de lotes a procesar. Default 40, mínimo 2. Controla documentos en memoria",ja:"1度に処理するバッチの数。デフォルトは40、最小は2。この数値は、どれだけの容量の書類がメモリに保存されるかも定義します。",ko:"한 번에 처리할 일괄 처리 수입니다. 기본값은 40입니다. 최소값은 2입니다. 이는 일괄 크기와 함께 메모리에 보관되는 문서 수를 제어합니다.",zh:"一次处理的批量数量。默认为 40。最小为 2。此设置与批量大小一起控制一次在内存中保留多少文档。"},"Number of changes to sync at a time. Defaults to 50. Minimum is 2.":{def:"Number of changes to sync at a time. Defaults to 50. Minimum is 2.",es:"Número de cambios a sincronizar simultáneamente. Default 50, mínimo 2",ko:"한 번에 동기화할 변경 사항의 수입니다. 기본값은 50입니다. 최소값은 2입니다.",zh:"一次同步的更改数量。默认为 50。最小为 2。"},"obsidianLiveSyncSettingTab.btnApply":{def:"Apply",es:"Aplicar",ko:"적용",zh:"应用"},"obsidianLiveSyncSettingTab.btnCheck":{def:"Check",es:"Verificar",ko:"확인",zh:"检查"},"obsidianLiveSyncSettingTab.btnCopy":{def:"Copy",es:"Copiar",ko:"복사",zh:"复制"},"obsidianLiveSyncSettingTab.btnDisable":{def:"Disable",es:"Desactivar",ko:"비활성화",zh:"禁用"},"obsidianLiveSyncSettingTab.btnDiscard":{def:"Discard",es:"Descartar",ko:"삭제",zh:"丢弃"},"obsidianLiveSyncSettingTab.btnEnable":{def:"Enable",es:"Activar",ko:"활성화",zh:"启用"},"obsidianLiveSyncSettingTab.btnFix":{def:"Fix",es:"Corregir",ko:"수정",zh:"修复"},"obsidianLiveSyncSettingTab.btnGotItAndUpdated":{def:"I got it and updated.",es:"Lo entendí y actualicé.",ko:"알겠습니다. 업데이트했습니다.",zh:"我明白了并且已更新。"},"obsidianLiveSyncSettingTab.btnNext":{def:"Next",es:"Siguiente",ko:"다음",zh:"下一步"},"obsidianLiveSyncSettingTab.btnStart":{def:"Start",es:"Iniciar",ko:"시작",zh:"开始"},"obsidianLiveSyncSettingTab.btnTest":{def:"Test",es:"Probar",ko:"테스트",zh:"测试"},"obsidianLiveSyncSettingTab.btnUse":{def:"Use",es:"Usar",ko:"사용",zh:"使用"},"obsidianLiveSyncSettingTab.buttonFetch":{def:"Fetch",es:"Obtener",ko:"가져오기",zh:"获取"},"obsidianLiveSyncSettingTab.buttonNext":{def:"Next",es:"Siguiente",ko:"다음",zh:"下一步"},"obsidianLiveSyncSettingTab.defaultLanguage":{def:"Default",es:"Predeterminado",ko:"기본값",zh:"默认"},"obsidianLiveSyncSettingTab.descConnectSetupURI":{def:"This is the recommended method to set up Self-hosted LiveSync with a Setup URI.",es:"Este es el método recomendado para configurar Self-hosted LiveSync con una URI de configuración.",ko:"이것은 Setup URI로 Self-hosted LiveSync를 설정하는 권장 방법입니다.",zh:"这是使用设置 URI 设置 Self-hosted LiveSync 的推荐方法。"},"obsidianLiveSyncSettingTab.descCopySetupURI":{def:"Perfect for setting up a new device!",es:"¡Perfecto para configurar un nuevo dispositivo!",ko:"새 기기 설정에 완벽합니다!",zh:"非常适合设置新设备!"},"obsidianLiveSyncSettingTab.descEnableLiveSync":{def:"Only enable this after configuring either of the above two options or completing all configuration manually.",es:"Solo habilita esto después de configurar cualquiera de las dos opciones anteriores o completar toda la configuración manualmente.",ko:"위의 두 옵션 중 하나를 구성하거나 모든 구성을 수동으로 완료한 후에만 활성화하세요.",zh:"仅在配置了上述两个选项之一或手动完成所有配置后启用此选项。"},"obsidianLiveSyncSettingTab.descFetchConfigFromRemote":{def:"Fetch necessary settings from already configured remote server.",es:"Obtener las configuraciones necesarias del servidor remoto ya configurado.",ko:"이미 구성된 원격 서버에서 필요한 설정을 가져옵니다.",zh:"从已配置的远程服务器获取必要的设置。"},"obsidianLiveSyncSettingTab.descManualSetup":{def:"Not recommended, but useful if you don't have a Setup URI",es:"No recomendado, pero útil si no tienes una URI de configuración",ko:"권장하지 않지만 Setup URI가 없는 경우에 유용합니다",zh:"不推荐,但如果您没有设置 URI 则很有用"},"obsidianLiveSyncSettingTab.descTestDatabaseConnection":{def:"Open database connection. If the remote database is not found and you have permission to create a database, the database will be created.",es:"Abrir conexión a la base de datos. Si no se encuentra la base de datos remota y tienes permiso para crear una base de datos, se creará la base de datos.",ko:"데이터베이스 연결을 엽니다. 원격 데이터베이스를 찾을 수 없고 데이터베이스 생성 권한이 있는 경우, 데이터베이스가 생성됩니다.",zh:"打开数据库连接。如果未找到远程数据库并且您有创建数据库的权限,则将创建数据库。"},"obsidianLiveSyncSettingTab.descValidateDatabaseConfig":{def:"Checks and fixes any potential issues with the database config.",es:"Verifica y soluciona cualquier problema potencial con la configuración de la base de datos.",ko:"데이터베이스 구성의 잠재적 문제를 확인하고 수정합니다.",zh:"检查并修复数据库配置中的任何潜在问题。"},"obsidianLiveSyncSettingTab.errAccessForbidden":{def:"❗ Access forbidden.",es:"Acceso prohibido.",ko:"❗ 액세스가 금지되었습니다.",zh:"❗ 访问被禁止。"},"obsidianLiveSyncSettingTab.errCannotContinueTest":{def:"We could not continue the test.",es:"No se pudo continuar con la prueba.",ko:"테스트를 계속할 수 없습니다.",zh:"我们无法继续测试。"},"obsidianLiveSyncSettingTab.errCorsCredentials":{def:"❗ cors.credentials is wrong",es:"❗ cors.credentials es incorrecto",ko:"❗ cors.credentials가 잘못되었습니다",zh:"❗ cors.credentials 设置错误"},"obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials":{def:"❗ CORS is not allowing credentials",es:"CORS no permite credenciales",ko:"❗ CORS에서 자격 증명을 허용하지 않습니다",zh:"❗ CORS 不允许凭据"},"obsidianLiveSyncSettingTab.errCorsOrigins":{def:"❗ cors.origins is wrong",es:"❗ cors.origins es incorrecto",ko:"❗ cors.origins가 잘못되었습니다",zh:"❗ cors.origins 设置错误"},"obsidianLiveSyncSettingTab.errEnableCors":{def:"❗ httpd.enable_cors is wrong",es:"❗ httpd.enable_cors es incorrecto",ko:"❗ httpd.enable_cors가 잘못되었습니다",zh:"❗ httpd.enable_cors 设置错误"},"obsidianLiveSyncSettingTab.errEnableCorsChttpd":{def:"❗ chttpd.enable_cors is wrong"},"obsidianLiveSyncSettingTab.errMaxDocumentSize":{def:"❗ couchdb.max_document_size is low)",es:"❗ couchdb.max_document_size es bajo)",ko:"❗ couchdb.max_document_size가 낮습니다)",zh:"❗ couchdb.max_document_size 设置过低)"},"obsidianLiveSyncSettingTab.errMaxRequestSize":{def:"❗ chttpd.max_http_request_size is low)",es:"❗ chttpd.max_http_request_size es bajo)",ko:"❗ chttpd.max_http_request_size가 낮습니다)",zh:"❗ chttpd.max_http_request_size 设置过低)"},"obsidianLiveSyncSettingTab.errMissingWwwAuth":{def:"❗ httpd.WWW-Authenticate is missing",es:"❗ httpd.WWW-Authenticate falta",ko:"❗ httpd.WWW-Authenticate가 누락되었습니다",zh:"❗ 缺少 httpd.WWW-Authenticate 设置"},"obsidianLiveSyncSettingTab.errRequireValidUser":{def:"❗ chttpd.require_valid_user is wrong.",es:"❗ chttpd.require_valid_user es incorrecto.",ko:"❗ chttpd.require_valid_user가 잘못되었습니다.",zh:"❗ chttpd.require_valid_user 设置错误。"},"obsidianLiveSyncSettingTab.errRequireValidUserAuth":{def:"❗ chttpd_auth.require_valid_user is wrong.",es:"❗ chttpd_auth.require_valid_user es incorrecto.",ko:"❗ chttpd_auth.require_valid_user가 잘못되었습니다.",zh:"❗ chttpd_auth.require_valid_user 设置错误。"},"obsidianLiveSyncSettingTab.labelDisabled":{def:"⏹️ : Disabled",es:"⏹️ : Desactivado",ko:"⏹️ : 비활성화됨",zh:"⏹️ : 已禁用"},"obsidianLiveSyncSettingTab.labelEnabled":{def:"🔁 : Enabled",es:"🔁 : Activado",ko:"🔁 : 활성화됨",zh:"🔁 : 已启用"},"obsidianLiveSyncSettingTab.levelAdvanced":{def:" (Advanced)",es:" (avanzado)",ko:" (고급)",zh:"(进阶)"},"obsidianLiveSyncSettingTab.levelEdgeCase":{def:" (Edge Case)",es:" (excepción)",ko:" (특수 사례)",zh:"(边缘情况)"},"obsidianLiveSyncSettingTab.levelPowerUser":{def:" (Power User)",es:" (experto)",ko:" (파워 유저)",zh:"(高级用户)"},"obsidianLiveSyncSettingTab.linkOpenInBrowser":{def:"Open in browser",es:"Abrir en el navegador",ko:"브라우저에서 열기",zh:"在浏览器中打开"},"obsidianLiveSyncSettingTab.linkPageTop":{def:"Page Top",es:"Ir arriba",ko:"페이지 상단",zh:"页面顶部"},"obsidianLiveSyncSettingTab.linkTipsAndTroubleshooting":{def:"Tips and Troubleshooting",es:"Consejos y solución de problemas",ko:"팁 및 문제 해결",zh:"提示和故障排除"},"obsidianLiveSyncSettingTab.linkTroubleshooting":{def:"/docs/troubleshooting.md",es:"/docs/es/troubleshooting.md",ko:"/docs/troubleshooting.md",zh:"/docs/troubleshooting.md"},"obsidianLiveSyncSettingTab.logCannotUseCloudant":{def:"This feature cannot be used with IBM Cloudant.",es:"Esta función no se puede utilizar con IBM Cloudant.",ko:"이 기능은 IBM Cloudant와 함께 사용할 수 없습니다.",zh:"此功能不能与 IBM Cloudant 一起使用。"},"obsidianLiveSyncSettingTab.logCheckingConfigDone":{def:"Checking configuration done",es:"Verificación de configuración completada",ko:"구성 확인 완료",zh:"配置检查完成"},"obsidianLiveSyncSettingTab.logCheckingConfigFailed":{def:"Checking configuration failed",es:"La verificación de configuración falló",ko:"구성 확인 실패",zh:"配置检查失败"},"obsidianLiveSyncSettingTab.logCheckingDbConfig":{def:"Checking database configuration",es:"Verificando la configuración de la base de datos",ko:"데이터베이스 구성 확인 중",zh:"正在检查数据库配置"},"obsidianLiveSyncSettingTab.logCheckPassphraseFailed":{def:"ERROR: Failed to check passphrase with the remote server:\n${db}.",es:"ERROR: Error al comprobar la frase de contraseña con el servidor remoto: \n${db}.",ko:"오류: 원격 서버와 패스프레이즈 확인에 실패했습니다: \n${db}.",zh:"错误:无法使用远程服务器检查密码:\n${db}。"},"obsidianLiveSyncSettingTab.logConfiguredDisabled":{def:"Configured synchronization mode: DISABLED",es:"Modo de sincronización configurado: DESACTIVADO",ko:"구성된 동기화 모드: 비활성화됨",zh:"配置的同步模式:已禁用"},"obsidianLiveSyncSettingTab.logConfiguredLiveSync":{def:"Configured synchronization mode: LiveSync",es:"Modo de sincronización configurado: Sincronización en Vivo",ko:"구성된 동기화 모드: LiveSync",zh:"配置的同步模式LiveSync"},"obsidianLiveSyncSettingTab.logConfiguredPeriodic":{def:"Configured synchronization mode: Periodic",es:"Modo de sincronización configurado: Periódico",ko:"구성된 동기화 모드: 주기적",zh:"配置的同步模式:定期"},"obsidianLiveSyncSettingTab.logCouchDbConfigFail":{def:"CouchDB Configuration: ${title} failed",es:"Configuración de CouchDB: ${title} falló",ko:"CouchDB 구성: ${title} 실패",zh:"CouchDB 配置:${title} 失败"},"obsidianLiveSyncSettingTab.logCouchDbConfigSet":{def:"CouchDB Configuration: ${title} -> Set ${key} to ${value}",es:"Configuración de CouchDB: ${title} -> Establecer ${key} en ${value}",ko:"CouchDB 구성: ${title} -> ${key}를 ${value}로 설정",zh:"CouchDB 配置:${title} -> 设置 ${key} 为 ${value}"},"obsidianLiveSyncSettingTab.logCouchDbConfigUpdated":{def:"CouchDB Configuration: ${title} successfully updated",es:"Configuración de CouchDB: ${title} actualizado correctamente",ko:"CouchDB 구성: ${title} 성공적으로 업데이트됨",zh:"CouchDB 配置:${title} 成功更新"},"obsidianLiveSyncSettingTab.logDatabaseConnected":{def:"Database connected",es:"Base de datos conectada",ko:"데이터베이스 연결됨",zh:"数据库已连接"},"obsidianLiveSyncSettingTab.logEncryptionNoPassphrase":{def:"You cannot enable encryption without a passphrase",es:"No puedes habilitar el cifrado sin una frase de contraseña",ko:"패스프레이즈 없이는 암호화를 활성화할 수 없습니다",zh:"没有密码无法启用加密"},"obsidianLiveSyncSettingTab.logEncryptionNoSupport":{def:"Your device does not support encryption.",es:"Tu dispositivo no admite el cifrado.",ko:"기기가 암호화를 지원하지 않습니다.",zh:"您的设备不支持加密。"},"obsidianLiveSyncSettingTab.logErrorOccurred":{def:"An error occurred!!",es:"¡Ocurrió un error!",ko:"오류가 발생했습니다!",zh:"发生错误!!"},"obsidianLiveSyncSettingTab.logEstimatedSize":{def:"Estimated size: ${size}",es:"Tamaño estimado: ${size}",ko:"예상 크기: ${size}",zh:"估计大小:${size}"},"obsidianLiveSyncSettingTab.logPassphraseInvalid":{def:"Passphrase is not valid, please fix it.",es:"La frase de contraseña no es válida, por favor corrígela.",ko:"패스프레이즈가 유효하지 않습니다. 수정해 주세요.",zh:"密码无效,请修正。"},"obsidianLiveSyncSettingTab.logPassphraseNotCompatible":{def:"ERROR: Passphrase is not compatible with the remote server! Please check it again!",es:"ERROR: ¡La frase de contraseña no es compatible con el servidor remoto! ¡Por favor, revísala de nuevo!",ko:"오류: 패스프레이즈가 원격 서버와 호환되지 않습니다! 다시 확인해 주세요!",zh:"错误:密码与远程服务器不兼容!请再次检查!"},"obsidianLiveSyncSettingTab.logRebuildNote":{def:"Syncing has been disabled, fetch and re-enabled if desired.",es:"La sincronización ha sido desactivada, obtén y vuelve a activar si lo deseas.",ko:"동기화가 비활성화되었습니다. 원하는 경우 가져오기 후 다시 활성화하세요.",zh:"同步已禁用,如果需要,请获取并重新启用。"},"obsidianLiveSyncSettingTab.logSelectAnyPreset":{def:"Select any preset.",es:"Selecciona cualquier preestablecido.",ko:"프리셋을 선택하세요.",zh:"选择任何预设。"},"obsidianLiveSyncSettingTab.msgAreYouSureProceed":{def:"Are you sure to proceed?",es:"¿Estás seguro de proceder?",ko:"정말로 진행하시겠습니까?",zh:"您确定要继续吗?"},"obsidianLiveSyncSettingTab.msgChangesNeedToBeApplied":{def:"Changes need to be applied!",es:"¡Los cambios deben aplicarse!",ko:"변경사항을 적용해야 합니다!",zh:"需要应用更改!"},"obsidianLiveSyncSettingTab.msgConfigCheck":{def:"--Config check--",es:"--Verificación de configuración--",ko:"--구성 확인--",zh:"--配置检查--"},"obsidianLiveSyncSettingTab.msgConfigCheckFailed":{def:"The configuration check has failed. Do you want to continue anyway?",es:"La verificación de configuración ha fallado. ¿Quieres continuar de todos modos?",ko:"구성 확인에 실패했습니다. 그래도 계속하시겠습니까?",zh:"配置检查失败。您仍要继续吗?"},"obsidianLiveSyncSettingTab.msgConnectionCheck":{def:"--Connection check--",es:"--Verificación de conexión--",ko:"--연결 확인--",zh:"--连接检查--"},"obsidianLiveSyncSettingTab.msgConnectionProxyNote":{def:"If you're having trouble with the Connection-check (even after checking config), please check your reverse proxy configuration.",es:"Si tienes problemas con la verificación de conexión (incluso después de verificar la configuración), por favor verifica la configuración de tu proxy reverso.",ko:"구성 확인 후에도 연결 확인에 문제가 있는 경우, 리버스 프록시 구성을 확인해 주세요.",zh:"如果您在连接检查时遇到问题(即使检查了配置后),请检查您的反向代理配置。"},"obsidianLiveSyncSettingTab.msgCurrentOrigin":{def:"Current origin: ${origin}",es:"Origen actual: {origin}",ko:"현재 원점: {origin}",zh:"当前源: {origin}"},"obsidianLiveSyncSettingTab.msgDiscardConfirmation":{def:"Do you really want to discard existing settings and databases?",es:"¿Realmente deseas descartar las configuraciones y bases de datos existentes?",ko:"정말로 기존 설정과 데이터베이스를 삭제하시겠습니까?",zh:"您真的要丢弃现有的设置和数据库吗?"},"obsidianLiveSyncSettingTab.msgDone":{def:"--Done--",es:"--Hecho--",ko:"--완료--",zh:"--完成--"},"obsidianLiveSyncSettingTab.msgEnableCors":{def:"Set httpd.enable_cors",es:"Configurar httpd.enable_cors",ko:"httpd.enable_cors 설정",zh:"设置 httpd.enable_cors"},"obsidianLiveSyncSettingTab.msgEnableCorsChttpd":{def:"Set chttpd.enable_cors"},"obsidianLiveSyncSettingTab.msgEnableEncryptionRecommendation":{def:"We recommend enabling End-To-End Encryption, and Path Obfuscation. Are you sure you want to continue without encryption?",es:"Recomendamos habilitar el cifrado de extremo a extremo y la obfuscación de ruta. ¿Estás seguro de querer continuar sin cifrado?",ko:"종단간 암호화와 경로 난독화를 활성화하는 것을 권장합니다. 정말로 암호화 없이 계속하시겠습니까?",zh:"我们建议启用端到端加密和路径混淆。您确定要在没有加密的情况下继续吗?"},"obsidianLiveSyncSettingTab.msgFetchConfigFromRemote":{def:"Do you want to fetch the config from the remote server?",es:"¿Quieres obtener la configuración del servidor remoto?",ko:"원격 서버에서 구성을 가져오시겠습니까?",zh:"您想从远程服务器获取配置吗?"},"obsidianLiveSyncSettingTab.msgGenerateSetupURI":{def:"All done! Do you want to generate a setup URI to set up other devices?",es:"¡Todo listo! ¿Quieres generar un URI de configuración para configurar otros dispositivos?",ko:"모든 작업이 완료되었습니다! 다른 기기를 설정하기 위해 Setup URI를 생성하시겠습니까?",zh:"全部完成!您想生成一个设置 URI 来设置其他设备吗?"},"obsidianLiveSyncSettingTab.msgIfConfigNotPersistent":{def:"If the server configuration is not persistent (e.g., running on docker), the values here may change. Once you are able to connect, please update the settings in the server's local.ini.",es:"Si la configuración del servidor no es persistente (por ejemplo, ejecutándose en docker), los valores aquí pueden cambiar. Una vez que puedas conectarte, por favor actualiza las configuraciones en el local.ini del servidor.",ko:"서버 설정이 영구적으로 저장되지 않는 환경(예: Docker에서 실행 중)에서는 이곳의 값들이 변경될 수 있습니다. 연결이 가능해지면 서버의 local.ini 파일에서 설정을 수동으로 업데이트해 주세요.",zh:"如果服务器配置不是持久的(例如,在 docker 上运行),此处的值可能会更改。一旦能够连接,请更新服务器 local.ini 中的设置。"},"obsidianLiveSyncSettingTab.msgInvalidPassphrase":{def:"Your encryption passphrase might be invalid. Are you sure you want to continue?",es:"Tu frase de contraseña de cifrado podría ser inválida. ¿Estás seguro de querer continuar?",ko:"암호화 패스프레이즈가 유효하지 않을 수 있습니다. 정말로 계속하시겠습니까?",zh:"您的加密密码可能无效。您确定要继续吗?"},"obsidianLiveSyncSettingTab.msgNewVersionNote":{def:"Here due to an upgrade notification? Please review the version history. If you're satisfied, click the button. A new update will prompt this again.",es:"¿Aquí debido a una notificación de actualización? Por favor, revise el historial de versiones. Si está satisfecho, haga clic en el botón. Una nueva actualización volverá a mostrar esto.",ko:"업그레이드 알림으로 여기에 오셨나요? 버전 기록을 검토해 주세요. 만족하신다면 버튼을 클릭하세요. 새로운 업데이트 시 다시 안내됩니다.",zh:"因为升级通知来到这里?请查看版本历史。如果您满意,请点击按钮。新的更新将再次提示此信息。"},"obsidianLiveSyncSettingTab.msgNonHTTPSInfo":{def:"Configured as non-HTTPS URI. Be warned that this may not work on mobile devices.",es:"Configurado como URI que no es HTTPS. Ten en cuenta que esto puede no funcionar en dispositivos móviles.",ko:"비 HTTPS URI로 구성되었습니다. 모바일 기기에서는 작동하지 않을 수 있으니 주의하세요.",zh:"配置为非 HTTPS URI。请注意这可能在移动设备上无法工作。"},"obsidianLiveSyncSettingTab.msgNonHTTPSWarning":{def:"Cannot connect to non-HTTPS URI. Please update your config and try again.",es:"No se puede conectar a URI que no sean HTTPS. Por favor, actualiza tu configuración y vuelve a intentarlo.",ko:"비 HTTPS URI에 연결할 수 없습니다. 구성을 업데이트하고 다시 시도해 주세요.",zh:"无法连接到非 HTTPS URI。请更新您的配置并重试。"},"obsidianLiveSyncSettingTab.msgNotice":{def:"---Notice---",es:"---Aviso---",ko:"---공지사항---",zh:"---注意---"},"obsidianLiveSyncSettingTab.msgObjectStorageWarning":{def:"WARNING: This feature is a Work In Progress, so please keep in mind the following:\n- Append only architecture. A rebuild is required to shrink the storage.\n- A bit fragile.\n- When first syncing, all history will be transferred from the remote. Be mindful of data caps and slow speeds.\n- Only differences are synced live.\n\nIf you run into any issues, or have ideas about this feature, please create a issue on GitHub.\nI appreciate you for your great dedication.",es:"ADVERTENCIA: Esta característica está en desarrollo, así que por favor ten en cuenta lo siguiente:\n- Arquitectura de solo anexado. Se requiere una reconstrucción para reducir el almacenamiento.\n- Un poco frágil.\n- Al sincronizar por primera vez, todo el historial será transferido desde el remoto. Ten en cuenta los límites de datos y las velocidades lentas.\n- Solo las diferencias se sincronizan en vivo.\n\nSi encuentras algún problema o tienes ideas sobre esta característica, por favor crea un issue en GitHub.\nAprecio mucho tu gran dedicación.",ko:"⚠️ 주의: 이 기능은 아직 개발 중(WIP)입니다. 다음 사항을 유의해 주세요:\n- 추가 전용 구조(append-only)로 동작합니다. 저장 용량을 줄이려면 데이터 재구성이 필요합니다.\n- 기능이 다소 불안정할 수 있습니다.\n- 최초 동기화 시, 전체 히스토리가 원격 서버에서 전송됩니다. 데이터 용량 제한 및 느린 속도에 유의해 주세요.\n- 실시간 동기화는 변경된 부분만 처리됩니다.\n\n문제가 발생했거나 개선 아이디어가 있으시면 GitHub에 이슈를 등록해 주세요.\n기여에 깊이 감사드립니다.",zh:"警告:此功能仍在开发中,请注意以下几点:\n- 仅追加架构。需要重建才能缩小存储空间。\n- 有点脆弱。\n- 首次同步时,所有历史记录将从远程传输。注意数据上限和慢速。\n- 只有差异会实时同步。\n\n如果您遇到任何问题或对此功能有任何想法请在 GitHub 上创建 issue。\n感谢您的巨大贡献。"},"obsidianLiveSyncSettingTab.msgOriginCheck":{def:"Origin check: ${org}",es:"Verificación de origen: {org}",ko:"원점 확인: {org}",zh:"源检查: {org}"},"obsidianLiveSyncSettingTab.msgRebuildRequired":{def:"Rebuilding Databases are required to apply the changes.. Please select the method to apply the changes.\n\n<details>\n<summary>Legends</summary>\n\n| Symbol | Meaning |\n|: ------ :| ------- |\n| ⇔ | Up to Date |\n| ⇄ | Synchronise to balance |\n| ⇐,⇒ | Transfer to overwrite |\n| ⇠,⇢ | Transfer to overwrite from other side |\n\n</details>\n\n## ${OPTION_REBUILD_BOTH}\nAt a glance: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\nReconstruct both the local and remote databases using existing files from this device.\nThis causes a lockout other devices, and they need to perform fetching.\n## ${OPTION_FETCH}\nAt a glance: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\nInitialise the local database and reconstruct it using data fetched from the remote database.\nThis case includes the case which you have rebuilt the remote database.\n## ${OPTION_ONLY_SETTING}\nStore only the settings. **Caution: This may lead to data corruption**; database reconstruction is generally necessary.",es:"Es necesario reconstruir las bases de datos para aplicar los cambios. Por favor selecciona el método para aplicar los cambios.\n\n<details>\n<summary>Legendas</summary>\n\n| Símbolo | Significado |\n|: ------ :| ------- |\n| ⇔ | Actualizado |\n| ⇄ | Sincronizar para equilibrar |\n| ⇐,⇒ | Transferir para sobrescribir |\n| ⇠,⇢ | Transferir para sobrescribir desde otro lado |\n\n</details>\n\n## ${OPTION_REBUILD_BOTH}\nA simple vista: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\nReconstruir tanto la base de datos local como la remota utilizando los archivos existentes de este dispositivo.\nEsto bloquea a otros dispositivos, y necesitan realizar la obtención.\n## ${OPTION_FETCH}\nA simple vista: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\nInicializa la base de datos local y la reconstruye utilizando los datos obtenidos de la base de datos remota.\nEste caso incluye el caso en el que has reconstruido la base de datos remota.\n## ${OPTION_ONLY_SETTING}\nAlmacena solo la configuración. **Precaución: esto puede provocar corrupción de datos**; generalmente es necesario reconstruir la base de datos.",ko:"변경사항을 적용하려면 데이터베이스를 재구축해야 합니다. 아래 중 한 가지 방법을 선택해 주세요.\n\n<details>\n<summary>범례</summary>\n\n| 기호 | 의미 |\n|: ------ :| ------- |\n| ⇔ | 최신 상태 |\n| ⇄ | 동기화 균형 유지 |\n| ⇐,⇒ | 덮어쓰기 방식의 전송 |\n| ⇠,⇢ | 상대편에서 가져와 덮어쓰기 |\n\n</details>\n\n## ${OPTION_REBUILD_BOTH}\n개요: 📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\n이 기기의 기존 파일을 기반으로 로컬과 원격 데이터베이스를 모두 재구축합니다.\n이 과정에서 다른 기기는 일시적으로 접근이 제한되며, 가져오기 작업을 별도로 수행해야 합니다.\n\n## ${OPTION_FETCH}\n개요: 📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\n로컬 데이터베이스를 초기화한 후, 원격 데이터베이스에서 데이터를 가져와 재구축합니다.\n이는 원격 측에서 데이터베이스를 먼저 재구축한 경우에도 해당됩니다.\n\n## ${OPTION_ONLY_SETTING}\n설정만 저장합니다. **⚠️ 주의: 이 방법은 데이터 손상을 일으킬 수 있습니다.** 일반적으로는 전체 데이터베이스 재구축이 필요합니다.",zh:"需要重建数据库以应用更改。请选择应用更改的方法。\n\n<details>\n<summary>图例</summary>\n\n| 符号 | 含义 |\n|: ------ :| ------- |\n| ⇔ | 最新 |\n| ⇄ | 同步以平衡 |\n| ⇐,⇒ | 传输以覆盖 |\n| ⇠,⇢ | 从另一侧传输以覆盖 |\n\n</details>\n\n## ${OPTION_REBUILD_BOTH}\n概览📄 ⇒¹ 💻 ⇒² 🛰️ ⇢ⁿ 💻 ⇄ⁿ⁺¹ 📄\n使用此设备的现有文件重建本地和远程数据库。\n这将导致其他设备被锁定并且它们需要执行获取操作。\n## ${OPTION_FETCH}\n概览📄 ⇄² 💻 ⇐¹ 🛰️ ⇔ 💻 ⇔ 📄\n初始化本地数据库并使用从远程数据库获取的数据重建它。\n这种情况包括您已经重建了远程数据库的情况。\n## ${OPTION_ONLY_SETTING}\n仅存储设置。**注意:这可能导致数据损坏**;通常需要重建数据库。"},"obsidianLiveSyncSettingTab.msgSelectAndApplyPreset":{def:"Please select and apply any preset item to complete the wizard.",es:"Por favor, selecciona y aplica cualquier elemento preestablecido para completar el asistente.",ko:"마법사를 완료하려면 프리셋 항목을 선택하고 적용해 주세요.",zh:"请选择并应用任何预设项以完成向导。"},"obsidianLiveSyncSettingTab.msgSetCorsCredentials":{def:"Set cors.credentials",es:"Configurar cors.credentials",ko:"cors.credentials 설정",zh:"设置 cors.credentials"},"obsidianLiveSyncSettingTab.msgSetCorsOrigins":{def:"Set cors.origins",es:"Configurar cors.origins",ko:"cors.origins 설정",zh:"设置 cors.origins"},"obsidianLiveSyncSettingTab.msgSetMaxDocSize":{def:"Set couchdb.max_document_size",es:"Configurar couchdb.max_document_size",ko:"couchdb.max_document_size 설정",zh:"设置 couchdb.max_document_size"},"obsidianLiveSyncSettingTab.msgSetMaxRequestSize":{def:"Set chttpd.max_http_request_size",es:"Configurar chttpd.max_http_request_size",ko:"chttpd.max_http_request_size 설정",zh:"设置 chttpd.max_http_request_size"},"obsidianLiveSyncSettingTab.msgSetRequireValidUser":{def:"Set chttpd.require_valid_user = true",es:"Configurar chttpd.require_valid_user = true",ko:"chttpd.require_valid_user = true로 설정",zh:"设置 chttpd.require_valid_user = true"},"obsidianLiveSyncSettingTab.msgSetRequireValidUserAuth":{def:"Set chttpd_auth.require_valid_user = true",es:"Configurar chttpd_auth.require_valid_user = true",ko:"chttpd_auth.require_valid_user = true로 설정",zh:"设置 chttpd_auth.require_valid_user = true"},"obsidianLiveSyncSettingTab.msgSettingModified":{def:'The setting "${setting}" was modified from another device. Click {HERE} to reload settings. Click elsewhere to ignore changes.',es:'La configuración "${setting}" fue modificada desde otro dispositivo. Haz clic {HERE} para recargar la configuración. Haz clic en otro lugar para ignorar los cambios.',ko:'"${setting}" 설정이 다른 기기에서 수정되었습니다. 설정을 다시 로드하려면 {HERE}를 클릭하세요. 변경사항을 무시하려면 다른 곳을 클릭하세요.',zh:'设置 "${setting}" 已从另一台设备修改。点击 {HERE} 重新加载设置。点击其他地方忽略更改。'},"obsidianLiveSyncSettingTab.msgSettingsUnchangeableDuringSync":{def:'These settings are unable to be changed during synchronization. Please disable all syncing in the "Sync Settings" to unlock.',es:'Estas configuraciones no se pueden cambiar durante la sincronización. Por favor, deshabilita toda la sincronización en las "Configuraciones de Sincronización" para desbloquear.',ko:'동기화 중에는 이 설정들을 변경할 수 없습니다. 잠금을 해제하려면 "동기화 설정"에서 모든 동기화를 비활성화해 주세요.',zh:"这些设置在同步期间无法更改。请在“同步设置”中禁用所有同步以解锁。"},"obsidianLiveSyncSettingTab.msgSetWwwAuth":{def:"Set httpd.WWW-Authenticate",es:"Configurar httpd.WWW-Authenticate",ko:"httpd.WWW-Authenticate 설정",zh:"设置 httpd.WWW-Authenticate"},"obsidianLiveSyncSettingTab.nameApplySettings":{def:"Apply Settings",es:"Aplicar configuraciones",ko:"설정 적용",zh:"应用设置"},"obsidianLiveSyncSettingTab.nameConnectSetupURI":{def:"Connect with Setup URI",es:"Conectar con URI de configuración",ko:"Setup URI로 연결",zh:"使用设置 URI 连接"},"obsidianLiveSyncSettingTab.nameCopySetupURI":{def:"Copy the current settings to a Setup URI",es:"Copiar la configuración actual a una URI de configuración",ko:"현재 설정을 Setup URI로 복사",zh:"将当前设置复制为设置 URI"},"obsidianLiveSyncSettingTab.nameDisableHiddenFileSync":{def:"Disable Hidden files sync",es:"Desactivar sincronización de archivos ocultos",ko:"숨김 파일 동기화 비활성화",zh:"禁用隐藏文件同步"},"obsidianLiveSyncSettingTab.nameDiscardSettings":{def:"Discard existing settings and databases",es:"Descartar configuraciones y bases de datos existentes",ko:"기존 설정 및 데이터베이스 삭제",zh:"丢弃现有设置和数据库"},"obsidianLiveSyncSettingTab.nameEnableHiddenFileSync":{def:"Enable Hidden files sync",es:"Activar sincronización de archivos ocultos",ko:"숨김 파일 동기화 활성화",zh:"启用隐藏文件同步"},"obsidianLiveSyncSettingTab.nameEnableLiveSync":{def:"Enable LiveSync",es:"Activar LiveSync",ko:"LiveSync 활성화",zh:"启用 LiveSync"},"obsidianLiveSyncSettingTab.nameHiddenFileSynchronization":{def:"Hidden file synchronization",es:"Sincronización de archivos ocultos",ko:"숨김 파일 동기화",zh:"隐藏文件同步"},"obsidianLiveSyncSettingTab.nameManualSetup":{def:"Manual Setup",es:"Configuración manual",ko:"수동 설정",zh:"手动设置"},"obsidianLiveSyncSettingTab.nameTestConnection":{def:"Test Connection",es:"Probar conexión",ko:"연결 테스트",zh:"测试连接"},"obsidianLiveSyncSettingTab.nameTestDatabaseConnection":{def:"Test Database Connection",es:"Probar Conexión de Base de Datos",ko:"데이터베이스 연결 테스트",zh:"测试数据库连接"},"obsidianLiveSyncSettingTab.nameValidateDatabaseConfig":{def:"Validate Database Configuration",es:"Validar Configuración de la Base de Datos",ko:"데이터베이스 구성 검증",zh:"验证数据库配置"},"obsidianLiveSyncSettingTab.okAdminPrivileges":{def:"✔ You have administrator privileges.",es:"✔ Tienes privilegios de administrador.",ko:"✔ 관리자 권한이 있습니다.",zh:"✔ 您拥有管理员权限。"},"obsidianLiveSyncSettingTab.okCorsCredentials":{def:"✔ cors.credentials is ok.",es:"✔ cors.credentials está correcto.",ko:"✔ cors.credentials가 정상입니다.",zh:"✔ cors.credentials 设置正确。"},"obsidianLiveSyncSettingTab.okCorsCredentialsForOrigin":{def:"CORS credentials OK",es:"CORS credenciales OK",ko:"CORS 자격 증명 정상",zh:"CORS 凭据正常"},"obsidianLiveSyncSettingTab.okCorsOriginMatched":{def:"✔ CORS origin OK",es:"✔ Origen de CORS correcto",ko:"✔ CORS 원점 정상",zh:"✔ CORS 源正常"},"obsidianLiveSyncSettingTab.okCorsOrigins":{def:"✔ cors.origins is ok.",es:"✔ cors.origins está correcto.",ko:"✔ cors.origins가 정상입니다.",zh:"✔ cors.origins 设置正确。"},"obsidianLiveSyncSettingTab.okEnableCors":{def:"✔ httpd.enable_cors is ok.",es:"✔ httpd.enable_cors está correcto.",ko:"✔ httpd.enable_cors가 정상입니다.",zh:"✔ httpd.enable_cors 设置正确。"},"obsidianLiveSyncSettingTab.okEnableCorsChttpd":{def:"✔ chttpd.enable_cors is ok."},"obsidianLiveSyncSettingTab.okMaxDocumentSize":{def:"✔ couchdb.max_document_size is ok.",es:"✔ couchdb.max_document_size está correcto.",ko:"✔ couchdb.max_document_size가 정상입니다.",zh:"✔ couchdb.max_document_size 设置正确。"},"obsidianLiveSyncSettingTab.okMaxRequestSize":{def:"✔ chttpd.max_http_request_size is ok.",es:"✔ chttpd.max_http_request_size está correcto.",ko:"✔ chttpd.max_http_request_size가 정상입니다.",zh:"✔ chttpd.max_http_request_size 设置正确。"},"obsidianLiveSyncSettingTab.okRequireValidUser":{def:"✔ chttpd.require_valid_user is ok.",es:"✔ chttpd.require_valid_user está correcto.",ko:"✔ chttpd.require_valid_user가 정상입니다.",zh:"✔ chttpd.require_valid_user 设置正确。"},"obsidianLiveSyncSettingTab.okRequireValidUserAuth":{def:"✔ chttpd_auth.require_valid_user is ok.",es:"✔ chttpd_auth.require_valid_user está correcto.",ko:"✔ chttpd_auth.require_valid_user가 정상입니다.",zh:"✔ chttpd_auth.require_valid_user 设置正确。"},"obsidianLiveSyncSettingTab.okWwwAuth":{def:"✔ httpd.WWW-Authenticate is ok.",es:"✔ httpd.WWW-Authenticate está correcto.",ko:"✔ httpd.WWW-Authenticate가 정상입니다.",zh:"✔ httpd.WWW-Authenticate 设置正确。"},"obsidianLiveSyncSettingTab.optionApply":{def:"Apply",es:"Aplicar",ko:"적용",zh:"应用"},"obsidianLiveSyncSettingTab.optionCancel":{def:"Cancel",es:"Cancelar",ko:"취소",zh:"取消"},"obsidianLiveSyncSettingTab.optionCouchDB":{def:"CouchDB",es:"CouchDB",ko:"CouchDB",zh:"CouchDB"},"obsidianLiveSyncSettingTab.optionDisableAllAutomatic":{def:"Disable all automatic",es:"Desactivar lo automático",ko:"모든 자동 비활성화",zh:"禁用所有自动同步"},"obsidianLiveSyncSettingTab.optionFetchFromRemote":{def:"Fetch from Remote",es:"Obtener del remoto",ko:"원격에서 가져오기",zh:"从远程获取"},"obsidianLiveSyncSettingTab.optionHere":{def:"HERE",es:"AQUÍ",ko:"여기",zh:"这里"},"obsidianLiveSyncSettingTab.optionLiveSync":{def:"LiveSync",es:"LiveSync",ko:"LiveSync",zh:"LiveSync"},"obsidianLiveSyncSettingTab.optionMinioS3R2":{def:"Minio,S3,R2",es:"Minio,S3,R2",ko:"Minio,S3,R2",zh:"Minio, S3, R2"},"obsidianLiveSyncSettingTab.optionOkReadEverything":{def:"OK, I have read everything.",es:"OK, he leído todo.",ko:"네, 모든 것을 읽었습니다.",zh:"好的,我已经阅读了所有内容。"},"obsidianLiveSyncSettingTab.optionOnEvents":{def:"On events",es:"En eventos",ko:"이벤트 시",zh:"基于事件"},"obsidianLiveSyncSettingTab.optionPeriodicAndEvents":{def:"Periodic and on events",es:"Periódico y en eventos",ko:"주기적 및 이벤트 시",zh:"定期和基于事件"},"obsidianLiveSyncSettingTab.optionPeriodicWithBatch":{def:"Periodic w/ batch",es:"Periódico con lote",ko:"주기적 w/ 일괄",zh:"定期与批量"},"obsidianLiveSyncSettingTab.optionRebuildBoth":{def:"Rebuild Both from This Device",es:"Reconstructuir ambos desde este dispositivo",ko:"이 기기에서 둘 다 재구축",zh:"从此设备重建两者"},"obsidianLiveSyncSettingTab.optionSaveOnlySettings":{def:"(Danger) Save Only Settings",es:"(Peligro) Guardar solo configuración",ko:"(위험) 설정만 저장",zh:"(危险)仅保存设置"},"obsidianLiveSyncSettingTab.panelChangeLog":{def:"Change Log",es:"Registro de cambios",ko:"변경 로그",zh:"更新日志"},"obsidianLiveSyncSettingTab.panelGeneralSettings":{def:"General Settings",es:"Configuraciones Generales",ko:"일반 설정",zh:"常规设置"},"obsidianLiveSyncSettingTab.panelPrivacyEncryption":{def:"Privacy & Encryption",es:"Privacidad y Cifrado",ko:"개인정보 보호 및 암호화",zh:"隐私与加密"},"obsidianLiveSyncSettingTab.panelRemoteConfiguration":{def:"Remote Configuration",es:"Configuración remota",ko:"원격 구성",zh:"远程配置"},"obsidianLiveSyncSettingTab.panelSetup":{def:"Setup",es:"Configuración",ko:"설정",zh:"设置"},"obsidianLiveSyncSettingTab.serverVersion":{def:"Server info: ${info}"},"obsidianLiveSyncSettingTab.titleActiveRemoteServer":{def:"Active Remote Server"},"obsidianLiveSyncSettingTab.titleAppearance":{def:"Appearance",es:"Apariencia",ko:"외관",zh:"外观"},"obsidianLiveSyncSettingTab.titleConflictResolution":{def:"Conflict resolution",es:"Resolución de conflictos",ko:"충돌 해결",zh:"冲突解决"},"obsidianLiveSyncSettingTab.titleCongratulations":{def:"Congratulations!",es:"¡Felicidades!",ko:"축하합니다!",zh:"恭喜!"},"obsidianLiveSyncSettingTab.titleCouchDB":{def:"CouchDB",es:"CouchDB",ko:"CouchDB",zh:"CouchDB"},"obsidianLiveSyncSettingTab.titleDeletionPropagation":{def:"Deletion Propagation",es:"Propagación de eliminación",ko:"삭제 전파",zh:"删除传播"},"obsidianLiveSyncSettingTab.titleEncryptionNotEnabled":{def:"Encryption is not enabled",es:"El cifrado no está habilitado",ko:"암호화가 활성화되지 않음",zh:"未启用加密"},"obsidianLiveSyncSettingTab.titleEncryptionPassphraseInvalid":{def:"Encryption Passphrase Invalid",es:"La frase de contraseña de cifrado es inválida",ko:"암호화 패스프레이즈 유효하지 않음",zh:"加密密码无效"},"obsidianLiveSyncSettingTab.titleExtraFeatures":{def:"Enable extra and advanced features",es:"Habilitar funciones extras y avanzadas",ko:"추가 및 고급 기능 활성화",zh:"启用额外和高级功能"},"obsidianLiveSyncSettingTab.titleFetchConfig":{def:"Fetch Config",es:"Obtener configuración",ko:"구성 가져오기",zh:"获取配置"},"obsidianLiveSyncSettingTab.titleFetchConfigFromRemote":{def:"Fetch config from remote server",es:"Obtener configuración del servidor remoto",ko:"원격 서버에서 구성 가져오기",zh:"从远程服务器获取配置"},"obsidianLiveSyncSettingTab.titleFetchSettings":{def:"Fetch Settings",es:"Obtener configuraciones",ko:"설정 가져오기",zh:"获取设置"},"obsidianLiveSyncSettingTab.titleHiddenFiles":{def:"Hidden Files",es:"Archivos ocultos",ko:"숨김 파일",zh:"隐藏文件"},"obsidianLiveSyncSettingTab.titleLogging":{def:"Logging",es:"Registro",ko:"로깅",zh:"日志记录"},"obsidianLiveSyncSettingTab.titleMinioS3R2":{def:"Minio,S3,R2",es:"Minio,S3,R2",ko:"Minio,S3,R2",zh:"Minio, S3, R2"},"obsidianLiveSyncSettingTab.titleNotification":{def:"Notification",es:"Notificación",ko:"알림",zh:"通知"},"obsidianLiveSyncSettingTab.titleOnlineTips":{def:"Online Tips",es:"Consejos en línea",ko:"온라인 팁",zh:"在线提示"},"obsidianLiveSyncSettingTab.titleQuickSetup":{def:"Quick Setup",es:"Configuración rápida",ko:"빠른 설정",zh:"快速设置"},"obsidianLiveSyncSettingTab.titleRebuildRequired":{def:"Rebuild Required",es:"Reconstrucción necesaria",ko:"재구축 필요",zh:"需要重建"},"obsidianLiveSyncSettingTab.titleRemoteConfigCheckFailed":{def:"Remote Configuration Check Failed",es:"La verificación de configuración remota falló",ko:"원격 구성 확인 실패",zh:"远程配置检查失败"},"obsidianLiveSyncSettingTab.titleRemoteServer":{def:"Remote Server",es:"Servidor remoto",ko:"원격 서버",zh:"远程服务器"},"obsidianLiveSyncSettingTab.titleReset":{def:"Reset",es:"Reiniciar",ko:"리셋",zh:"重置"},"obsidianLiveSyncSettingTab.titleSetupOtherDevices":{def:"To setup other devices",es:"Para configurar otros dispositivos",ko:"다른 기기 설정",zh:"设置其他设备"},"obsidianLiveSyncSettingTab.titleSynchronizationMethod":{def:"Synchronization Method",es:"Método de sincronización",ko:"동기화 방법",zh:"同步方法"},"obsidianLiveSyncSettingTab.titleSynchronizationPreset":{def:"Synchronization Preset",es:"Preestablecimiento de sincronización",ko:"동기화 프리셋",zh:"同步预设"},"obsidianLiveSyncSettingTab.titleSyncSettings":{def:"Sync Settings",es:"Configuraciones de Sincronización",ko:"동기화 설정",zh:"同步设置"},"obsidianLiveSyncSettingTab.titleSyncSettingsViaMarkdown":{def:"Sync Settings via Markdown",es:"Configuración de sincronización a través de Markdown",ko:"마크다운을 통한 동기화 설정",zh:"通过 Markdown 同步设置"},"obsidianLiveSyncSettingTab.titleUpdateThinning":{def:"Update Thinning",es:"Actualización de adelgazamiento",ko:"업데이트 솎아내기",zh:"更新频率限制"},"obsidianLiveSyncSettingTab.warnCorsOriginUnmatched":{def:"⚠ CORS Origin is unmatched ${from}->${to}",es:"⚠ El origen de CORS no coincide: {from}->{to}",ko:"⚠ CORS 원점이 일치하지 않습니다 {from}->{to}",zh:"⚠ CORS 源不匹配 {from}->{to}"},"obsidianLiveSyncSettingTab.warnNoAdmin":{def:"⚠ You do not have administrator privileges.",es:"⚠ No tienes privilegios de administrador.",ko:"⚠ 관리자 권한이 없습니다.",zh:"⚠ 您没有管理员权限。"},"P2P.AskPassphraseForDecrypt":{def:"The remote peer shared the configuration. Please input the passphrase to decrypt the configuration.",ko:"원격 피어가 구성을 공유했습니다. 구성을 복호화하려면 패스프레이즈를 입력해 주세요."},"P2P.AskPassphraseForShare":{def:"The remote peer requested this device configuration. Please input the passphrase to share the configuration. You can ignore the request by cancelling this dialogue.",ko:"원격 피어가 이 기기의 구성을 요청했습니다. 구성을 공유하려면 패스프레이즈를 입력해 주세요. 이 대화상자를 취소하여 요청을 무시할 수 있습니다."},"P2P.DisabledButNeed":{def:"%{title_p2p_sync} is disabled. Do you really want to enable it?",ko:"%{title_p2p_sync}가 비활성화되어 있습니다. 정말로 활성화하시겠습니까?"},"P2P.FailedToOpen":{def:"Failed to open P2P connection to the signaling server.",ko:"시그널링 서버에 P2P 연결을 열 수 없습니다."},"P2P.NoAutoSyncPeers":{def:"No auto-sync peers found. Please set peers on the %{long_p2p_sync} pane.",ko:"자동 동기화 피어를 찾을 수 없습니다. %{long_p2p_sync} 창에서 피어를 설정해 주세요."},"P2P.NoKnownPeers":{def:"No peers has been detected, waiting incoming other peers...",ko:"피어가 감지되지 않았습니다. 다른 피어의 접속을 기다리고 있습니다..."},"P2P.Note.description":{def:" This replicator allows us to synchronise our vault with other devices\nusing a peer-to-peer connection. We can use this to synchronise our vault with our other devices without using a cloud service.\nThis replicator is based on Trystero. It also uses a signaling server to establish a connection between devices. The signaling server is used to exchange connection information between devices. It does (or,should) not know or store any of our data.\n\nThe signaling server can be hosted by anyone. This is just a Nostr relay. For the sake of simplicity and checking the behaviour of the replicator, an instance of the signaling server is hosted by vrtmrz. You can use the experimental server provided by vrtmrz, or you can use any other server.\n\nBy the way, even if the signaling server does not store our data, it can see the connection information of some of our devices. Please be aware of this. Also, be cautious when using the server provided by someone else.",ko:"이 복제기는 피어 투 피어(P2P) 연결을 통해 다른 기기들과 볼트를 동기화할 수 있도록 합니다. 클라우드 서비스를 거치지 않고도 기기간 동기화를 구현할 수 있습니다.\n\n이 복제기는 Trystero를 기반으로 하며, 기기 간 연결을 설정하기 위해 시그널링 서버를 사용합니다. 시그널링 서버는 단순히 연결 정보를 교환하는 용도로만 사용되며, 사용자 데이터를 저장하거나 접근하지 않습니다 (또는 그래야만 합니다).\n\n시그널링 서버는 누구나 운영할 수 있으며, 이는 단순한 Nostr 릴레이입니다. 편의성과 복제기의 작동 확인을 위해 `vrtmrz`가 자체적으로 시그널링 서버 인스턴스를 운영 중입니다. 사용자는 `vrtmrz`가 제공하는 실험용 서버를 사용할 수도 있고, 별도로 자신만의 서버를 설정할 수도 있습니다.\n\n참고로, 시그널링 서버는 사용자 데이터를 저장하지 않더라도 일부 기기의 연결 정보는 볼 수 있습니다. 이 점을 유의해 주세요. 특히 타인이 운영하는 서버를 사용할 경우 주의가 필요합니다."},"P2P.Note.important_note":{def:"The Experimental Implementation of the Peer-to-Peer Replicator.",ko:"피어 투 피어(P2P) 복제기의 실험적 구현입니다."},"P2P.Note.important_note_sub":{def:"This feature is still in the experimental stage. Please be aware that this feature may not work as expected. Furthermore, it may have some bugs, security issues, and other issues. Please use this feature at your own risk. Please contribute to the development of this feature.",ko:"이 기능은 아직 실험 단계에 있습니다. 이 기능이 예상대로 작동하지 않을 수 있음을 알아주세요. 또한 버그, 보안 문제 및 기타 문제가 있을 수 있습니다. 이 기능을 사용할 때는 본인의 책임 하에 사용하세요. 이 기능의 개발에 기여해 주세요."},"P2P.Note.Summary":{def:"What is this feature? (and some important notes, please read once)",ko:"이 기능은 무엇인가요? (설명과 참고사항이 적혀있습니다. 한 번 읽어보세요!)"},"P2P.NotEnabled":{def:"%{title_p2p_sync} is not enabled. We cannot open a new connection.",ko:"%{title_p2p_sync}가 활성화되지 않았습니다. 새로운 연결을 열 수 없습니다."},"P2P.P2PReplication":{def:"%{P2P} Replication",ko:"%{P2P} 복제"},"P2P.PaneTitle":{def:"%{long_p2p_sync}",ko:"%{long_p2p_sync}"},"P2P.ReplicatorInstanceMissing":{def:"P2P Sync replicator is not found, possibly not have been configured or enabled.",ko:"P2P 동기화 복제기를 찾을 수 없습니다. 구성되지 않았거나 활성화되지 않았을 수 있습니다."},"P2P.SeemsOffline":{def:"Peer ${name} seems offline, skipped.",ko:"피어 ${name}이(가) 오프라인인 것 같습니다. 건너뜁니다."},"P2P.SyncAlreadyRunning":{def:"P2P Sync is already running.",ko:"P2P 동기화가 이미 실행 중입니다."},"P2P.SyncCompleted":{def:"P2P Sync completed.",ko:"P2P 동기화가 완료되었습니다."},"P2P.SyncStartedWith":{def:"P2P Sync with ${name} have been started.",ko:"${name}과의 P2P 동기화가 시작되었습니다."},Passphrase:{def:"Passphrase",es:"Frase de contraseña",ja:"パスフレーズ",ko:"패스프레이즈",zh:"密码"},"Passphrase of sensitive configuration items":{def:"Passphrase of sensitive configuration items",es:"Frase para elementos sensibles",ja:"機微設定項目にパスフレーズを使用",ko:"민감한 구성 항목의 패스프레이즈",zh:"敏感配置项的密码"},password:{def:"password",es:"contraseña",ja:"パスワード",ko:"비밀번호",zh:"密码"},Password:{def:"Password",es:"Contraseña",ja:"パスワード",ko:"비밀번호",zh:"密码"},"Path Obfuscation":{def:"Path Obfuscation",es:"Ofuscación de rutas",ja:"パスの難読化",ko:"경로 난독화",zh:"路径混淆"},"Per-file-saved customization sync":{def:"Per-file-saved customization sync",es:"Sincronización de personalización por archivo",ko:"파일별 저장 사용자 설정 동기화",zh:"按文件保存的自定义同步"},"Periodic Sync interval":{def:"Periodic Sync interval",es:"Intervalo de sincronización periódica",ja:"定時同期の感覚",ko:"주기적 동기화 간격",zh:"定期同步间隔"},Presets:{def:"Presets",es:"Preconfiguraciones",ja:"プリセット",ko:"프리셋",zh:"预设"},"Process small files in the foreground":{def:"Process small files in the foreground",es:"Procesar archivos pequeños en primer plano",ko:"포그라운드에서 작은 파일 처리",zh:"在前台处理小文件"},"RedFlag.Fetch.Method.Desc":{def:"How do you want to fetch?\n- %{RedFlag.Fetch.Method.FetchSafer}.\n **Low Traffic**, **High CPU**, **Low Risk**\n Recommended if ...\n - Files possibly inconsistent\n - Files were not so much\n- %{RedFlag.Fetch.Method.FetchSmoother}.\n **Low Traffic**, **Moderate CPU**, **Low to Moderate Risk**\n Recommended if ...\n - Files probably consistent\n - You have a lot of files.\n- %{RedFlag.Fetch.Method.FetchTraditional}.\n **High Traffic**, **Low CPU**, **Low to Moderate Risk**\n\n>[!INFO]- Details\n> ## %{RedFlag.Fetch.Method.FetchSafer}.\n> **Low Traffic**, **High CPU**, **Low Risk**\n> This option first creates a local database using existing local files before fetching data from the remote source.\n> If matching files exist both locally and remotely, only the differences between them will be transferred.\n> However, files present in both locations will initially be handled as conflicted files. They will be resolved automatically if they are not actually conflicted, but this process may take time.\n> This is generally the safest method, minimizing data loss risk.\n> ## %{RedFlag.Fetch.Method.FetchSmoother}.\n> **Low Traffic**, **Moderate CPU**, **Low to Moderate Risk** (depending operation)\n> This option first creates chunks from local files for the database, then fetches data. Consequently, only chunks missing locally are transferred. However, all metadata is taken from the remote source.\n> Local files are then compared against this metadata at launch. The content considered newer will overwrite the older one (by modified time). This outcome is then synchronised back to the remote database.\n> This is generally safe if local files are genuinely the latest timestamp. However, it can cause problems if a file has a newer timestamp but older content (like the initial `welcome.md`).\n> This uses less CPU and faster than \"%{RedFlag.Fetch.Method.FetchSafer}\", but it may lead to data loss if not used carefully.\n> ## %{RedFlag.Fetch.Method.FetchTraditional}.\n> **High Traffic**, **Low CPU**, **Low to Moderate Risk** (depending operation)\n> All things will be fetched from the remote.\n> Similar to the %{RedFlag.Fetch.Method.FetchSmoother}, but all chunks are fetched from the remote source.\n> This is the most traditional way to fetch, typically consuming the most network traffic and time. It also carries a similar risk of overwriting remote files to the '%{RedFlag.Fetch.Method.FetchSmoother}' option.\n> However, it is often considered the most stable method because it is the longest-established and most straightforward approach.",ko:"어떻게 가져오시겠습니까?\n- %{RedFlag.Fetch.Method.FetchSafer}. (권장)\n **낮은 트래픽**, **높은 CPU**, **낮은 위험**\n- %{RedFlag.Fetch.Method.FetchSmoother}.\n **낮은 트래픽**, **보통 CPU**, **낮음에서 보통 위험**\n- %{RedFlag.Fetch.Method.FetchTraditional}.\n **높은 트래픽**, **낮은 CPU**, **낮음에서 보통 위험**\n\n>[!INFO]- 세부 사항\n> ## %{RedFlag.Fetch.Method.FetchSafer}. (권장)\n> **낮은 트래픽**, **높은 CPU**, **낮은 위험**\n> 이 옵션은 원격 소스에서 데이터를 가져오기 전에 기존 로컬 파일을 사용하여 로컬 데이터베이스를 먼저 생성합니다.\n> 로컬과 원격 모두에 일치하는 파일이 있으면 둘 사이의 차이점만 전송됩니다.\n> 하지만 두 위치 모두에 있는 파일은 초기에 충돌 파일로 처리됩니다. 실제로 충돌하지 않는다면 자동으로 해결되지만 이 과정은 시간이 걸릴 수 있습니다.\n> 이는 일반적으로 가장 안전한 방법으로 데이터 손실 위험을 최소화합니다.\n> ## %{RedFlag.Fetch.Method.FetchSmoother}.\n> **낮은 트래픽**, **보통 CPU**, **낮음에서 보통 위험** (작업에 따라)\n> 이 옵션은 먼저 로컬 파일에서 데이터베이스용 청크를 생성한 다음 데이터를 가져옵니다. 따라서 로컬에 없는 청크만 전송됩니다. 하지만 모든 메타데이터는 원격 소스에서 가져옵니다.\n> 그런 다음 로컬 파일이 시작 시 이 메타데이터와 비교됩니다. 더 새로운 것으로 간주되는 콘텐츠가 오래된 것을 덮어씁니다(수정 시간 기준). 이 결과는 원격 데이터베이스에 다시 동기화됩니다.\n> 로컬 파일이 실제로 최신 타임스탬프라면 일반적으로 안전합니다. 하지만 파일이 더 새로운 타임스탬프를 가지고 있지만 더 오래된 콘텐츠를 가지고 있다면(초기 `welcome.md`처럼) 문제가 발생할 수 있습니다.\n> 이는 \"%{RedFlag.Fetch.Method.FetchSafer}\"보다 CPU를 덜 사용하고 더 빠르지만 주의 깊게 사용하지 않으면 데이터 손실로 이어질 수 있습니다.\n> ## %{RedFlag.Fetch.Method.FetchTraditional}.\n> **높은 트래픽**, **낮은 CPU**, **낮음에서 보통 위험** (작업에 따라)\n> 모든 것이 원격에서 가져와집니다.\n> %{RedFlag.Fetch.Method.FetchSmoother}와 유사하지만 모든 청크가 원격 소스에서 가져와집니다.\n> 이는 가장 전통적인 가져오기 방법으로 일반적으로 가장 많은 네트워크 트래픽과 시간을 소모합니다. 또한 '%{RedFlag.Fetch.Method.FetchSmoother}' 옵션과 유사하게 원격 파일을 덮어쓸 위험이 있습니다.\n> 하지만 가장 오래되고 가장 직접적인 접근 방식이기 때문에 종종 가장 안정적인 방법으로 간주됩니다."},"RedFlag.Fetch.Method.FetchSafer":{def:"Create a local database once before fetching",ko:"가져오기 전에 로컬 데이터베이스를 한 번 생성"},"RedFlag.Fetch.Method.FetchSmoother":{def:"Create local file chunks before fetching",ko:"가져오기 전에 로컬 파일 청크 생성"},"RedFlag.Fetch.Method.FetchTraditional":{def:"Fetch everything from the remote",ko:"원격에서 모든 것 가져오기"},"RedFlag.Fetch.Method.Title":{def:"How do you want to fetch?",ko:"어떻게 가져오시겠습니까?"},"RedFlag.FetchRemoteConfig.Buttons.Cancel":{def:"No, use local settings"},"RedFlag.FetchRemoteConfig.Buttons.Fetch":{def:"Yes, fetch and apply remote settings"},"RedFlag.FetchRemoteConfig.Message":{def:"Do you want to fetch and apply remotely stored preference settings to the device?"},"RedFlag.FetchRemoteConfig.Title":{def:"Fetch Remote Configuration"},"Reducing the frequency with which on-disk changes are reflected into the DB":{def:"Reducing the frequency with which on-disk changes are reflected into the DB",es:"Reducir frecuencia de actualizaciones de disco a BD",ko:"디스크 변경 사항이 데이터베이스에 반영되는 빈도를 줄입니다",zh:"降低将磁盘上的更改反映到数据库中的频率"},Region:{def:"Region",es:"Región",ja:"リージョン",ko:"지역",zh:"Region"},"Remote server type":{def:"Remote server type",es:"Tipo de servidor remoto",ja:"リモートの種別",ko:"원격 서버 유형",zh:"远程服务器类型"},"Remote Type":{def:"Remote Type",es:"Tipo de remoto",ja:"同期方式",ko:"원격 유형",zh:"远程类型"},"Replicator.Dialogue.Locked.Action.Dismiss":{def:"Cancel for reconfirmation",ko:"재확인을 위해 취소"},"Replicator.Dialogue.Locked.Action.Fetch":{def:"Reset Synchronisation on This Device",ko:"원격 데이터베이스에서 모든 것을 다시 가져오기"},"Replicator.Dialogue.Locked.Action.Unlock":{def:"Unlock the remote database",ko:"원격 데이터베이스 잠금 해제"},"Replicator.Dialogue.Locked.Message":{def:"Remote database is locked. This is due to a rebuild on one of the terminals.\nThe device is therefore asked to withhold the connection to avoid database corruption.\n\nThere are three options that we can do:\n\n- %{Replicator.Dialogue.Locked.Action.Fetch}\n The most preferred and reliable way. This will dispose the local database once, and reset all synchronisation information from the remote database again, In most case, we can perform this safely. However, it takes some time and should be done in stable network.\n- %{Replicator.Dialogue.Locked.Action.Unlock}\n This method can only be used if we are already reliably synchronised by other replication methods. This does not simply mean that we have the same files. If you are not sure, you should avoid it.\n- %{Replicator.Dialogue.Locked.Action.Dismiss}\n This will cancel the operation. And we will asked again on next request.\n",ko:"원격 데이터베이스가 잠겨 있습니다. 이는 일부 터미널에서 데이터베이스를 재구축했기 때문입니다.\n따라서 현재 기기는 데이터베이스 손상을 방지하기 위해 연결을 일시적으로 보류해야 합니다.\n\n선택할 수 있는 세 가지 방법이 있습니다:\n\n- %{Replicator.Dialogue.Locked.Action.Fetch}\n 가장 권장되고 신뢰할 수 있는 방법입니다. 로컬 데이터베이스를 초기화한 뒤, 원격 데이터베이스의 전체 데이터를 다시 가져옵니다. 대부분의 경우 안전하게 수행할 수 있으나, 시간이 다소 걸리며 안정적인 네트워크 환경에서 진행해야 합니다.\n- %{Replicator.Dialogue.Locked.Action.Unlock}\n 이 방법은 다른 동기화 방식으로 이미 완전하고 안정적으로 동기화된 경우에만 사용할 수 있습니다. 단순히 파일이 같다는 의미가 아니므로, 확신이 없다면 사용을 피하는 것이 좋습니다.\n- %{Replicator.Dialogue.Locked.Action.Dismiss}\n 이번 작업을 취소하고, 다음 요청 시 다시 안내받습니다.\n"},"Replicator.Dialogue.Locked.Message.Fetch":{def:"Fetch all has been scheduled. Plug-in will be restarted to perform it.",ko:"모든 것 가져오기가 예약되었습니다. 이를 수행하기 위해 플러그인이 재시작됩니다."},"Replicator.Dialogue.Locked.Message.Unlocked":{def:"The remote database has been unlocked. Please retry the operation.",ko:"원격 데이터베이스 잠금이 해제되었습니다. 작업을 다시 시도해 주세요."},"Replicator.Dialogue.Locked.Title":{def:"Locked",ko:"잠김"},"Replicator.Message.Cleaned":{def:"Database cleaning up is in process. replication has been cancelled",ko:"데이터베이스 정리가 진행 중입니다. 복제가 취소되었습니다"},"Replicator.Message.InitialiseFatalError":{def:"No replicator is available, this is the fatal error.",ko:"사용 가능한 복제기가 없습니다. 치명적인 오류입니다."},"Replicator.Message.Pending":{def:"Some file events are pending. Replication has been cancelled.",ko:"일부 파일 이벤트가 대기 중입니다. 복제가 취소되었습니다."},"Replicator.Message.SomeModuleFailed":{def:"Replication has been cancelled by some module failure",ko:"일부 모듈 실패로 복제가 취소되었습니다"},"Replicator.Message.VersionUpFlash":{def:"An update has been detected. Please open the Settings dialogue and check the Change Log. Replication has been cancelled.",ko:"설정을 열고 메시지를 확인해 주세요. 복제가 취소되었습니다."},"Requires restart of Obsidian":{def:"Requires restart of Obsidian",es:"Requiere reiniciar Obsidian",ko:"Obsidian 재시작 필요",zh:"需要重启 Obsidian"},"Requires restart of Obsidian.":{def:"Requires restart of Obsidian.",es:"Requiere reiniciar Obsidian",ko:"Obsidian 재시작이 필요합니다.",zh:"需要重启 Obsidian。"},"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.":{def:"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform.",es:"Guardar configuración en archivo markdown. Se notificarán nuevos ajustes. Puede definir diferentes archivos por plataforma",ko:"설정을 마크다운 파일에 저장합니다. 새로운 설정이 도착하면 알림을 받게 됩니다. 플랫폼별로 다른 파일을 설정할 수 있습니다.",zh:"将设置保存到一个 Markdown 文件中。当新设置到达时,您将收到通知。您可以根据平台设置不同的文件。"},"Saving will be performed forcefully after this number of seconds.":{def:"Saving will be performed forcefully after this number of seconds.",es:"Guardado forzado tras esta cantidad de segundos",ko:"이 시간(초) 후에 강제로 저장이 수행됩니다.",zh:"在此秒数后将强制执行保存。"},"Scan changes on customization sync":{def:"Scan changes on customization sync",es:"Escanear cambios en sincronización de personalización",ja:"カスタマイズされた同期時に、変更をスキャンする",ko:"사용자 설정 동기화 시 변경 사항 검색",zh:"在自定义同步时扫描更改"},"Scan customization automatically":{def:"Scan customization automatically",es:"Escanear personalización automáticamente",ja:"自動的にカスタマイズをスキャン",ko:"사용자 설정 자동 검색",zh:"自动扫描自定义设置"},"Scan customization before replicating.":{def:"Scan customization before replicating.",es:"Escanear personalización antes de replicar",ja:"レプリケーション前に、カスタマイズをスキャン",ko:"복제하기 전에 사용자 설정을 검색합니다.",zh:"在复制前扫描自定义设置。"},"Scan customization every 1 minute.":{def:"Scan customization every 1 minute.",es:"Escanear personalización cada 1 minuto",ja:"カスタマイズのスキャンを1分ごとに行う",ko:"1분마다 사용자 설정을 검색합니다.",zh:"每1分钟扫描自定义设置。"},"Scan customization periodically":{def:"Scan customization periodically",es:"Escanear personalización periódicamente",ja:"定期的にカスタマイズをスキャン",ko:"주기적으로 사용자 설정 검색",zh:"定期扫描自定义设置"},"Scan for hidden files before replication":{def:"Scan for hidden files before replication",es:"Escanear archivos ocultos antes de replicar",ja:"レプリケーション開始前に、隠しファイルのスキャンを行う",ko:"복제 전 숨겨진 파일 검색",zh:"复制前扫描隐藏文件"},"Scan hidden files periodically":{def:"Scan hidden files periodically",es:"Escanear archivos ocultos periódicamente",ja:"定期的に隠しファイルのスキャンを行う",ko:"주기적으로 숨겨진 파일 검색",zh:"定期扫描隐藏文件"},"Seconds, 0 to disable":{def:"Seconds, 0 to disable",es:"Segundos, 0 para desactivar",ko:"초 단위, 0으로 설정하면 비활성화",zh:"秒0为禁用"},"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.":{def:"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving.",es:"Segundos. Guardado en BD local se retrasará hasta este valor tras dejar de escribir/guardar",ko:"초 단위입니다. 타이핑이나 저장을 중단한 후 이 시간동안 로컬 데이터베이스 저장이 지연됩니다.",zh:"秒。在我们停止输入或保存后,保存到本地数据库将延迟此值。"},"Secret Key":{def:"Secret Key",es:"Clave secreta",ja:"シークレットキー",ko:"시크릿 키",zh:"Secret Key"},"Server URI":{def:"Server URI",es:"URI del servidor",ja:"URI",ko:"서버 URI",zh:"服务器 URI"},"Setting.GenerateKeyPair.Desc":{def:'We have generated a key pair!\n\nNote: This key pair will never be shown again. Please save it in a safe place. If you have lost it, you need to generate a new key pair.\nNote 2: The public key is in spki format, and the Private key is in pkcs8 format. For the sake of convenience, newlines are converted to `\\n` in public key.\nNote 3: The public key should be configured in the remote database, and the private key should be configured in local devices.\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-keypair">\n>\n> ### Public Key\n> ```\n${public_key}\n> ```\n>\n> ### Private Key\n> ```\n${private_key}\n> ```\n>\n> </div>\n\n>[!Both for copying]-\n>\n> <div class="sls-keypair">\n>\n> ```\n${public_key}\n${private_key}\n> ```\n>\n> </div>\n\n',ko:'키 페어를 생성했습니다!\n\n참고: 이 키 페어는 다시 표시되지 않습니다. 안전한 곳에 저장해 주세요. 분실하면 새 키 페어를 생성해야 합니다.\n참고 2: 공개 키는 spki 형식이고, 개인 키는 pkcs8 형식입니다. 편의상 공개 키의 줄 바꿈은 `\\n`으로 변환됩니다.\n참고 3: 공개 키는 원격 데이터베이스에서 구성되어야 하고, 개인 키는 로컬 기기에서 구성되어야 합니다.\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-keypair">\n>\n> ### 공개 키\n> ```\n${public_key}\n> ```\n>\n> ### 개인 키\n> ```\n${private_key}\n> ```\n>\n> </div>\n\n>[!Both for copying]-\n>\n> <div class="sls-keypair">\n>\n> ```\n${public_key}\n${private_key}\n> ```\n>\n> </div>\n\n\n'},"Setting.GenerateKeyPair.Title":{def:"New key pair has been generated!",ko:"새 키 페어가 생성되었습니다!"},"Setting.TroubleShooting":{def:"TroubleShooting",ko:"문제 해결"},"Setting.TroubleShooting.Doctor":{def:"Setting Doctor",ko:"설정 진단 마법사"},"Setting.TroubleShooting.Doctor.Desc":{def:"Detects non optimal settings. (Same as during migration)",ko:"최적화되지 않은 설정을 감지합니다. (데이터 구조 전환 시와 동일)"},"Setting.TroubleShooting.ScanBrokenFiles":{def:"Scan for broken files"},"Setting.TroubleShooting.ScanBrokenFiles.Desc":{def:"Scans for files that are not stored correctly in the database."},"SettingTab.Message.AskRebuild":{def:"Your changes require fetching from the remote database. Do you want to proceed?",ko:"변경 사항을 적용하려면 원격 데이터베이스에서 가져와야 합니다. 계속 진행하시겠습니까?"},"Setup.Apply.Buttons.ApplyAndFetch":{def:"Apply and Fetch"},"Setup.Apply.Buttons.ApplyAndMerge":{def:"Apply and Merge"},"Setup.Apply.Buttons.ApplyAndRebuild":{def:"Apply and Rebuild"},"Setup.Apply.Buttons.Cancel":{def:"Discard and Cancel"},"Setup.Apply.Buttons.OnlyApply":{def:"Only Apply"},"Setup.Apply.Message":{def:"The new configuration is ready. Let us proceed to apply it.\nThere are several ways to apply this:\n\n- Apply and Fetch\n Configure this device as a new client. After applying, synchronise from the remote server.\n- Apply and Merge\n Configure on a device that already has the file. It processes the local files and transfers the differences. Conflicts may arise.\n- Apply and Rebuild\n Rebuild the remote using local files. This is typically done if the server becomes corrupted or we wish to start from scratch.\n Other devices will be locked and required to re-fetch.\n- Only Apply\n Apply only. Conflicts may arise if a rebuild is required."},"Setup.Apply.Title":{def:"Apply new configuration from the ${method}"},"Setup.Apply.WarningRebuildRecommended":{def:"NOTE: after adjusting the settings, it has been determined that a rebuild is required; Just Import is not recommended."},"Setup.Doctor.Buttons.No":{def:"No, please use the settings in the URI as is"},"Setup.Doctor.Buttons.Yes":{def:"Yes, please consult the doctor"},"Setup.Doctor.Message":{def:"Self-hosted LiveSync has gradually become longer in history and some recommended settings have changed.\n\nNow, setup is a very good time to do this.\n\nDo you want to run Doctor to check if the imported settings are optimal compared to the latest state?"},"Setup.Doctor.Title":{def:"Do you want to consult the doctor?"},"Setup.FetchRemoteConf.Buttons.Fetch":{def:"Yes, please fetch the configuration"},"Setup.FetchRemoteConf.Buttons.Skip":{def:"No, please use the settings in the URI"},"Setup.FetchRemoteConf.Message":{def:"If we have already synchronised once with another device, the remote database stores the suitable configuration values between the synchronised devices. The plug-in would like to retrieve them for robust configuration.\n\nHowever, we have to make sure the one thing. Are we currently in a situation where we can access the network safely and retrieve the settings?\n\nNote: Mostly, you are safe to do this, that your remote database is hosted with a SSL certificate, and your network is not compromised."},"Setup.FetchRemoteConf.Title":{def:"Fetch configuration from remote database?"},"Setup.QRCode":{def:'We have generated a QR code to transfer the settings. Please scan the QR code with your phone or other device.\nNote: The QR code is not encrypted, so be careful to open this.\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-qr">${qr_image}</div>',ko:'설정을 전송하기 위한 QR 코드를 생성했습니다. 휴대폰이나 다른 기기로 QR 코드를 스캔해 주세요.\n참고: QR 코드는 암호화되지 않았으므로 열 때 주의하세요.\n\n>[!FOR YOUR EYES ONLY]-\n> <div class="sls-qr">${qr_image}</div>'},"Setup.ShowQRCode":{def:"Show QR code",ko:"QR 코드 표시"},"Setup.ShowQRCode.Desc":{def:"Show QR code to transfer the settings.",ko:"설정을 전송하기 위한 QR 코드를 표시합니다."},"Should we keep folders that don't have any files inside?":{def:"Should we keep folders that don't have any files inside?",es:"¿Mantener carpetas vacías?",ko:"내부에 파일이 없는 폴더를 유지하시겠습니까?",zh:"我们是否应该保留内部没有任何文件的文件夹?"},"Should we only check for conflicts when a file is opened?":{def:"Should we only check for conflicts when a file is opened?",es:"¿Solo comprobar conflictos al abrir archivo?",ko:"파일을 열 때만 충돌을 확인하시겠습니까?",zh:"我们是否应该仅在文件打开时检查冲突?"},"Should we prompt you about conflicting files when a file is opened?":{def:"Should we prompt you about conflicting files when a file is opened?",es:"¿Notificar sobre conflictos al abrir archivo?",ko:"파일을 열 때 충돌하는 파일에 대해 알림을 표시하시겠습니까?",zh:"当文件打开时,是否提示冲突文件?"},"Should we prompt you for every single merge, even if we can safely merge automatcially?":{def:"Should we prompt you for every single merge, even if we can safely merge automatcially?",es:"¿Preguntar en cada fusión aunque sea automática?",ko:"안전하게 자동 병합할 수 있는 경우에도 모든 병합에 대해 알림을 받으시겠습니까?",zh:"即使我们可以安全地自动合并,是否也应该为每一次合并提示您?"},"Show only notifications":{def:"Show only notifications",es:"Mostrar solo notificaciones",ja:"通知のみ表示",ko:"알림만 표시",zh:"仅显示通知"},"Show status as icons only":{def:"Show status as icons only",es:"Mostrar estado solo con íconos",ja:"ステータス表示をアイコンのみにする",ko:"아이콘으로만 상태 표시",zh:"仅以图标显示状态"},"Show status inside the editor":{def:"Show status inside the editor",es:"Mostrar estado dentro del editor",ja:"ステータスをエディタ内に表示",ko:"편집기 내부에 상태 표시",zh:"在编辑器内显示状态"},"Show status on the status bar":{def:"Show status on the status bar",es:"Mostrar estado en la barra de estado",ja:"ステータスバーに、ステータスを表示",ko:"상태 바에 상태 표시",zh:"在状态栏上显示状态"},"Show verbose log. Please enable if you report an issue.":{def:"Show verbose log. Please enable if you report an issue.",es:"Mostrar registro detallado. Actívelo si reporta un problema.",ja:"エラー以外の詳細ログ項目も表示する。問題が発生した場合は有効にしてください。",ko:"자세한 로그를 표시합니다. 문제를 신고하는 경우 활성화해 주세요.",zh:"显示详细日志。如果您报告问题,请启用此选项。"},"Starts synchronisation when a file is saved.":{def:"Starts synchronisation when a file is saved.",es:"Inicia sincronización al guardar un archivo",ko:"파일이 저장될 때 동기화를 시작합니다.",zh:"当文件保存时启动同步。"},"Stop reflecting database changes to storage files.":{def:"Stop reflecting database changes to storage files.",es:"Dejar de reflejar cambios de BD en archivos",ja:"データベースの変更をストレージファイルに反映させない",ko:"데이터베이스 변경 사항을 스토리지 파일에 반영하는 것을 중단합니다.",zh:"停止将数据库更改反映到存储文件。"},"Stop watching for file changes.":{def:"Stop watching for file changes.",es:"Dejar de monitorear cambios en archivos",ja:"監視の停止",ko:"파일 변경 사항 감시를 중단합니다.",zh:"停止监视文件更改。"},"Suppress notification of hidden files change":{def:"Suppress notification of hidden files change",es:"Suprimir notificaciones de cambios en archivos ocultos",ko:"숨겨진 파일 변경 알림 억제",zh:"抑制隐藏文件更改的通知"},"Suspend database reflecting":{def:"Suspend database reflecting",es:"Suspender reflejo de base de datos",ja:"データベース反映の一時停止",ko:"데이터베이스 반영 일시 중단",zh:"暂停数据库反映"},"Suspend file watching":{def:"Suspend file watching",es:"Suspender monitorización de archivos",ja:"監視の一時停止",ko:"파일 감시 일시 중단",zh:"暂停文件监视"},"Sync after merging file":{def:"Sync after merging file",es:"Sincronizar tras fusionar archivo",ja:"ファイルがマージ(統合)された時に同期",ko:"파일 병합 후 동기화",zh:"合并文件后同步"},"Sync automatically after merging files":{def:"Sync automatically after merging files",es:"Sincronizar automáticamente tras fusionar archivos",ko:"파일 병합 후 자동으로 동기화",zh:"合并文件后自动同步"},"Sync Mode":{def:"Sync Mode",es:"Modo de sincronización",ja:"同期モード",ko:"동기화 모드",zh:"同步模式"},"Sync on Editor Save":{def:"Sync on Editor Save",es:"Sincronizar al guardar en editor",ja:"エディタでの保存時に、同期されます",ko:"편집기 저장 시 동기화",zh:"编辑器保存时同步"},"Sync on File Open":{def:"Sync on File Open",es:"Sincronizar al abrir archivo",ja:"ファイルを開いた時に同期",ko:"파일 열기 시 동기화",zh:"打开文件时同步"},"Sync on Save":{def:"Sync on Save",es:"Sincronizar al guardar",ja:"保存時に同期",ko:"저장 시 동기화",zh:"保存时同步"},"Sync on Startup":{def:"Sync on Startup",es:"Sincronizar al iniciar",ja:"起動時同期",ko:"시작 시 동기화",zh:"启动时同步"},"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.":{def:"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned.",es:"Solo pruebas - Resolver conflictos sincronizando copias nuevas (puede sobrescribir modificaciones)",ko:"테스트 전용 - 파일의 새로운 사본을 동기화하여 파일 충돌을 해결하며, 수정된 파일을 덮어쓸 수 있습니다. 주의하세요.",zh:"仅供测试 - 通过同步文件的较新副本来解决文件冲突,这可能会覆盖修改过的文件。请注意。"},"The delay for consecutive on-demand fetches":{def:"The delay for consecutive on-demand fetches",es:"Retraso entre obtenciones consecutivas",ko:"연속 청크 요청 간 대기 시간",zh:"连续按需获取的延迟"},"The Hash algorithm for chunk IDs":{def:"The Hash algorithm for chunk IDs",es:"Algoritmo hash para IDs de chunks",ja:"チャンクIDのハッシュアルゴリズム",ko:"청크 ID용 해시 알고리즘",zh:"块 ID 的哈希算法(实验性)"},"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.":{def:"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks.",es:"Duración máxima para incubar chunks. Excedentes se independizan",ko:"변경 기록이 문서에 함께 보관될 수 있는 최대 시간입니다. 초과 시 문서에서 분리되어 개별로 저장됩니다.",zh:"文档中可以孵化的数据块的最大持续时间。超过此时间的数据块将成为独立数据块。"},"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.":{def:"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks.",es:"Número máximo de chunks que pueden incubarse en el documento. Excedentes se independizan",ko:"문서 안에 임시로 보관할 수 있는 변경 기록의 최대 개수입니다. 이 수를 초과하면 즉시 독립된 청크로 분리되어 저장됩니다.",zh:"文档中可以孵化的数据块的最大数量。超过此数量的数据块将立即成为独立数据块。"},"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.":{def:"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks.",es:"Tamaño total máximo de chunks incubados. Excedentes se independizan",ko:"문서 안에 임시로 보관할 수 있는 변경 기록의 전체 크기 제한입니다. 초과 시 자동으로 분리됩니다.",zh:"文档中可以孵化的数据块的最大总大小。超过此大小的数据块将立即成为独立数据块。"},"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.":{def:"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again.",es:"Esta frase no se copia a otros dispositivos. Usará `Default` hasta reconfigurar",ko:"이 패스프레이즈는 다른 기기로 복사되지 않습니다. 다시 구성할 때까지 `기본값`으로 설정됩니다.",zh:"此密码不会复制到另一台设备。在您再次配置之前,它将设置为 `Default`。"},"TweakMismatchResolve.Action.Dismiss":{def:"Dismiss",ko:"무시"},"TweakMismatchResolve.Action.UseConfigured":{def:"Use configured settings",ko:"구성된 설정 사용"},"TweakMismatchResolve.Action.UseMine":{def:"Update remote database settings",ko:"원격 데이터베이스 설정 업데이트"},"TweakMismatchResolve.Action.UseMineAcceptIncompatible":{def:"Update remote database settings but keep as is",ko:"원격 데이터베이스 설정 업데이트하지만 그대로 유지"},"TweakMismatchResolve.Action.UseMineWithRebuild":{def:"Update remote database settings and rebuild again",ko:"원격 데이터베이스 설정 업데이트하고 다시 재구축"},"TweakMismatchResolve.Action.UseRemote":{def:"Apply settings to this device",ko:"이 기기에 설정 적용"},"TweakMismatchResolve.Action.UseRemoteAcceptIncompatible":{def:"Apply settings to this device, but and ignore incompatibility",ko:"이 기기에 설정 적용하지만 호환성 문제 무시"},"TweakMismatchResolve.Action.UseRemoteWithRebuild":{def:"Apply settings to this device, and fetch again",ko:"이 기기에 설정 적용하고 다시 가져오기"},"TweakMismatchResolve.Message.Main":{def:"\nThe settings in the remote database are as follows. These values are configured by other devices, which are synchronised with this device at least once.\n\nIf you want to use these settings, please select %{TweakMismatchResolve.Action.UseConfigured}.\nIf you want to keep the settings of this device, please select %{TweakMismatchResolve.Action.Dismiss}.\n\n${table}\n\n>[!TIP]\n> If you want to synchronise all settings, please use `Sync settings via markdown` after applying minimal configuration with this feature.\n\n${additionalMessage}",ko:"\n원격 데이터베이스의 설정은 다음과 같습니다. 이 값들은 이 기기와 최소 한 번 동기화된 다른 기기에서 구성된 것입니다.\n\n이 설정을 사용하려면 %{TweakMismatchResolve.Action.UseConfigured}를 선택해 주세요.\n이 기기의 설정을 유지하려면 %{TweakMismatchResolve.Action.Dismiss}를 선택해 주세요.\n\n${table}\n\n>[!TIP]\n> 모든 설정을 동기화하려면 이 기능으로 최소 구성을 적용한 후 `마크다운을 통한 설정 동기화`를 사용해 주세요.\n\n${additionalMessage}"},"TweakMismatchResolve.Message.MainTweakResolving":{def:"Your configuration has not been matched with the one on the remote server.\n\nFollowing configuration should be matched:\n\n${table}\n\nLet us know your decision.\n\n${additionalMessage}",ko:"구성이 원격 서버의 것과 일치하지 않습니다.\n\n다음 구성이 일치해야 합니다:\n\n${table}\n\n결정을 알려주세요.\n\n${additionalMessage}"},"TweakMismatchResolve.Message.UseRemote.WarningRebuildRecommended":{def:"\n>[!NOTICE]\n> Some changes are compatible but may consume extra storage and transfer volumes. A rebuild is recommended. However, a rebuild may not be performed at present, but may be implemented in future maintenance.\n> ***Please ensure that you have time and are connected to a stable network to apply!***",ko:"\n>[!NOTICE]\n> 일부 변경사항은 호환 가능하지만 추가 스토리지 및 전송량을 소모할 수 있습니다. 재구축을 권장합니다. 하지만 현재 재구축을 수행하지 않더라도 향후 유지보수에서 구현될 수 있습니다.\n> ***시간적 여유가 있고 안정적인 네트워크에 연결된 상태에서 적용해 주세요!***"},"TweakMismatchResolve.Message.UseRemote.WarningRebuildRequired":{def:"\n>[!WARNING]\n> Some remote configurations are not compatible with the local database of this device. Rebuilding the local database will be required.\n> ***Please ensure that you have time and are connected to a stable network to apply!***",ko:"\n>[!WARNING]\n> 일부 원격 구성이 이 기기의 로컬 데이터베이스와 호환되지 않습니다. 로컬 데이터베이스 재구축이 필요합니다.\n> ***시간적 여유가 있고 안정적인 네트워크에 연결된 상태에서 적용해 주세요!***"},"TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended":{def:"\n>[!NOTICE]\n> We have detected that some of the values are different to make incompatible the local database with the remote database.\n> Some changes are compatible but may consume extra storage and transfer volumes. A rebuild is recommended. However, a rebuild may not be performed at present, but may be implemented in future maintenance.\n> If you want to rebuild, it takes a few minutes or more. **Make sure it is safe to perform it now.**",ko:"\n>[!NOTICE]\n> 로컬 데이터베이스와 원격 데이터베이스가 호환되지 않도록 만드는 값들이 다른 것을 감지했습니다.\n> 일부 변경사항은 호환 가능하지만 추가 스토리지 및 전송량을 소모할 수 있습니다. 재구축을 권장합니다. 하지만 현재 재구축을 수행하지 않더라도 향후 유지보수에서 구현될 수 있습니다.\n> 재구축을 원한다면 몇 분 이상 소요됩니다. **지금 수행해도 안전한지 확인해 주세요.**"},"TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired":{def:"\n>[!WARNING]\n> We have detected that some of the values are different to make incompatible the local database with the remote database.\n> Either local or remote rebuilds are required. Both of them takes a few minutes or more. **Make sure it is safe to perform it now.**",ko:"\n>[!WARNING]\n> 로컬 데이터베이스와 원격 데이터베이스가 호환되지 않도록 만드는 값들이 다른 것을 감지했습니다.\n> 로컬 또는 원격 재구축이 필요합니다. 둘 다 몇 분 이상 소요됩니다. **지금 수행해도 안전한지 확인해 주세요.**"},"TweakMismatchResolve.Table":{def:"| Value name | This device | On Remote |\n|: --- |: ---- :|: ---- :|\n${rows}\n\n",ko:"| 값 이름 | 이 기기 | 원격 |\n|: --- |: ---- :|: ---- :|\n${rows}\n\n"},"TweakMismatchResolve.Table.Row":{def:"| ${name} | ${self} | ${remote} |",ko:"| ${name} | ${self} | ${remote} |"},"TweakMismatchResolve.Title":{def:"Configuration Mismatch Detected",ko:"구성 불일치 감지"},"TweakMismatchResolve.Title.TweakResolving":{def:"Configuration Mismatch Detected",ko:"구성 불일치 감지"},"TweakMismatchResolve.Title.UseRemoteConfig":{def:"Use Remote Configuration",ko:"원격 구성 사용"},"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.":{def:"Unique name between all synchronized devices. To edit this setting, please disable customization sync once.",es:"Nombre único entre dispositivos sincronizados. Para editarlo, desactive sincronización de personalización",ja:"一意の名称を、すべての端末に設定します。この設定を変更した場合、カスタマイズ同期機能を無効にしてください。",ko:"모든 동기화된 기기 간 고유 이름입니다. 이 설정을 편집하려면 사용자 설정 동기화를 한 번 비활성화해 주세요.",zh:"所有同步设备之间的唯一名称。要编辑此设置,请首先禁用自定义同步"},"Use Custom HTTP Handler":{def:"Use Custom HTTP Handler",es:"Usar manejador HTTP personalizado",ja:"カスタムHTTPハンドラーの利用",ko:"커스텀 HTTP 핸들러 사용",zh:"使用自定义 HTTP 处理程序"},"Use dynamic iteration count":{def:"Use dynamic iteration count",es:"Usar conteo de iteraciones dinámico",ja:"動的な繰り返し回数",ko:"동적 반복 횟수 사용",zh:"使用动态迭代次数"},"Use Segmented-splitter":{def:"Use Segmented-splitter",es:"Usar divisor segmentado",ko:"의미 기반 분할 사용",zh:"使用分段分割器"},"Use splitting-limit-capped chunk splitter":{def:"Use splitting-limit-capped chunk splitter",es:"Usar divisor de chunks con límite",ko:"분할 제한 상한 청크 분할기 사용",zh:"使用分割限制上限的块分割器"},"Use the trash bin":{def:"Use the trash bin",es:"Usar papelera",ja:"ゴミ箱を使用",ko:"휴지통 사용",zh:"使用回收站"},"Use timeouts instead of heartbeats":{def:"Use timeouts instead of heartbeats",es:"Usar timeouts en lugar de latidos",ja:"ハートビートの代わりにタイムアウトを使用",ko:"하트비트 대신 타임아웃 사용",zh:"使用超时而不是心跳"},username:{def:"username",es:"nombre de usuario",ja:"ユーザー名",ko:"사용자명",zh:"用户名"},Username:{def:"Username",es:"Usuario",ja:"ユーザー名",ko:"사용자명",zh:"用户名"},"Verbose Log":{def:"Verbose Log",es:"Registro detallado",ja:"エラー以外のログ項目",ko:"자세한 로그",zh:"详细日志"},"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.":{def:"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information.",es:"¡Advertencia! Impacta rendimiento. Los logs no se sincronizan con nombre predeterminado. Contienen información confidencial",ko:"경고! 이는 성능에 심각한 영향을 미칩니다. 로그는 기본 이름으로 동기화되지 않습니다. 로그에는 종종 기밀 정보가 포함되어 있으므로 주의해 주세요.",zh:"警告!这将严重影响性能。并且日志不会以默认名称同步。请小心处理日志;它们通常包含您的敏感信息。"},"When you save a file in the editor, start a sync automatically":{def:"When you save a file in the editor, start a sync automatically",es:"Iniciar sincronización automática al guardar en editor",ja:"エディタでファイルを保存すると、自動的に同期を開始します",ko:"편집기에서 파일을 저장할 때 자동으로 동기화를 시작합니다",zh:"当您在编辑器中保存文件时,自动开始同步"},"Write credentials in the file":{def:"Write credentials in the file",es:"Escribir credenciales en archivo",ja:"クレデンシャルのファイル内保存",ko:"파일에 자격 증명 저장",zh:"将凭据写入文件"},"Write logs into the file":{def:"Write logs into the file",es:"Escribir logs en archivo",ja:"ファイルにログを記録",ko:"파일에 로그 기록",zh:"将日志写入文件"},"Compute revisions for chunks (Previous behaviour)":{es:"Calcular revisiones para chunks (comportamiento anterior)",zh:"为 chunks 计算修订版本(以前的行为)"}},"def"),...expandKeywords(_allMessages,"es"),...expandKeywords(_allMessages,"ja"),...expandKeywords(_allMessages,"ko"),...expandKeywords(_allMessages,"ru"),...expandKeywords(_allMessages,"zh"),...expandKeywords(_allMessages,"zh-tw")};allMessages=expandedMessage;currentLang="";missingTranslations=[];__onMissingTranslations=key3=>console.warn(key3);msgCache=new Map;on_click=(_,closeDialogue)=>closeDialogue();root_1=from_html("<pre> </pre>");root=from_html('<div class="logpane svelte-o3lsbg"><div class="control svelte-o3lsbg"><div class="row svelte-o3lsbg"><label class="svelte-o3lsbg"><input type="checkbox" class="svelte-o3lsbg"/> <span class="svelte-o3lsbg"> </span></label> <label class="svelte-o3lsbg"><input type="checkbox" class="svelte-o3lsbg"/> <span class="svelte-o3lsbg"> </span></label> <label class="svelte-o3lsbg"><input type="checkbox" class="svelte-o3lsbg"/> <span class="svelte-o3lsbg"> </span></label> <span class="spacer svelte-o3lsbg"></span> <button class="svelte-o3lsbg">Close</button></div></div> <div class="log svelte-o3lsbg"></div></div>');$$css={hash:"svelte-o3lsbg",code:".svelte-o3lsbg {box-sizing:border-box;}.logpane.svelte-o3lsbg {display:flex;height:100%;flex-direction:column;}.log.svelte-o3lsbg {overflow-y:scroll;user-select:text;-webkit-user-select:text;padding-bottom:2em;}.log.svelte-o3lsbg > pre:where(.svelte-o3lsbg) {margin:0;}.log.svelte-o3lsbg > pre.wrap-right:where(.svelte-o3lsbg) {word-break:break-all;max-width:100%;width:100%;white-space:normal;}.row.svelte-o3lsbg {display:flex;flex-direction:row;justify-content:flex-end;}.row.svelte-o3lsbg > label:where(.svelte-o3lsbg) {display:flex;align-items:center;min-width:5em;margin-right:1em;}"};delegate(["click"]);SvelteItemView=class extends import_obsidian.ItemView{async onOpen(){await super.onOpen();this.contentEl.empty();await this._dismountComponent();this.component=await this.instantiateComponent(this.contentEl)}async _dismountComponent(){if(this.component){await unmount(this.component);this.component=void 0}}async onClose(){await super.onClose();if(this.component){await unmount(this.component);this.component=void 0}}};LogPaneView=class extends SvelteItemView{constructor(leaf,plugin3){super(leaf);this.icon="view-log";this.title="";this.navigation=!1;this.plugin=plugin3}instantiateComponent(target){return mount(LogPane,{target,props:{close:()=>{this.leaf.detach()}}})}getIcon(){return"view-log"}getViewType(){return"log-log"}getDisplayText(){return $msg("logPane.title")}};EVENT_PLATFORM_UNLOADED="platform-unloaded";APIBase=class{constructor(){this._isReady=!1;this._isDisposed=!1}get isReady(){return this._isReady}get isDisposed(){return this._isDisposed}async applyOptions(options){var _a8,_b5,_c3,_d2;if(this.isDisposed)throw new Error("Cannot apply options to a disposed API");this.isReady&&await(null==(_a8=this.__teardownCurrentOptions)?void 0:_a8.call(this));await(null==(_b5=this.onApplyOptions)?void 0:_b5.call(this,options));this._options?this._options={...this._options,...options}:this._options=options;await(null==(_c3=this.onOptionsApplied)?void 0:_c3.call(this));await(null==(_d2=this.onReady)?void 0:_d2.call(this))}async init(options){var _a8;await this.applyOptions(options);await(null==(_a8=this.onInit)?void 0:_a8.call(this));return this}async __teardownCurrentOptions(){var _a8,_b5;await(null==(_a8=this.onDisposeCurrentOptions)?void 0:_a8.call(this));await(null==(_b5=this.tearDownCurrentOptions)?void 0:_b5.call(this))}reload(options){return this.applyOptions(options)}async dispose(){var _a8,_b5;await(null==(_a8=this.onDisposeCurrentOptions)?void 0:_a8.call(this));await(null==(_b5=this.onDisposed)?void 0:_b5.call(this))}};secp256k1_CURVE={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt("1"),a:BigInt("0"),b:BigInt("7"),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")};var{p:P,n:N,Gx,Gy,b:_b3}=secp256k1_CURVE;lengths={publicKey:1+(L=32),publicKeyUncompressed:65,signature:64,seed:48};captureTrace=(...args)=>{"captureStackTrace"in Error&&"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(...args)};err=(message="")=>{const e3=new Error(message);captureTrace(e3,err);throw e3};isBig=n3=>"bigint"==typeof n3;isStr=s2=>"string"==typeof s2;isBytes=a2=>a2 instanceof Uint8Array||ArrayBuffer.isView(a2)&&"Uint8Array"===a2.constructor.name;abytes=(value,length,title="")=>{const bytes=isBytes(value),len=null==value?void 0:value.length,needsLen=void 0!==length;(!bytes||needsLen&&len!==length)&&err((title&&`"${title}" `)+"expected Uint8Array"+(needsLen?` of length ${length}`:"")+", got "+(bytes?`length=${len}`:"type="+typeof value));return value};u8n=len=>new Uint8Array(len);padh=(n3,pad2)=>n3.toString(16).padStart(pad2,"0");bytesToHex=b3=>Array.from(abytes(b3)).map((e3=>padh(e3,2))).join("");_ch=ch4=>ch4>=48&&ch4<=57?ch4-48:ch4>=65&&ch4<=70?ch4-55:ch4>=97&&ch4<=102?ch4-87:void 0;hexToBytes=hex=>{const e3="hex invalid";if(!isStr(hex))return err(e3);const hl=hex.length,al2=hl/2;if(hl%2)return err(e3);const array=u8n(al2);for(let ai2=0,hi=0;ai2<al2;ai2++,hi+=2){const n1=_ch(hex.charCodeAt(hi)),n22=_ch(hex.charCodeAt(hi+1));if(void 0===n1||void 0===n22)return err(e3);array[ai2]=16*n1+n22}return array};cr=()=>null==globalThis?void 0:globalThis.crypto;subtle=()=>{var _a8,_b5;return null!=(_b5=null==(_a8=cr())?void 0:_a8.subtle)?_b5:err("crypto.subtle must be defined, consider polyfill")};concatBytes=(...arrs)=>{const r4=u8n(arrs.reduce(((sum2,a2)=>sum2+abytes(a2).length),0));let pad2=0;arrs.forEach((a2=>{r4.set(a2,pad2);pad2+=a2.length}));return r4};randomBytes=(len=L)=>cr().getRandomValues(u8n(len));big=BigInt;arange=(n3,min,max3,msg="bad number: out of range")=>isBig(n3)&&min<=n3&&n3<max3?n3:err(msg);M=(a2,b3=P)=>{const r4=a2%b3;return r4>=BigInt("0")?r4:b3+r4};modN=a2=>M(a2,N);invert=(num,md)=>{(num===BigInt("0")||md<=BigInt("0"))&&err("no inverse n="+num+" mod="+md);let a2=M(num,md),b3=md,x2=BigInt("0"),y2=BigInt("1"),u2=BigInt("1"),v2=BigInt("0");for(;a2!==BigInt("0");){const q2=b3/a2,r4=b3%a2,m3=x2-u2*q2,n3=y2-v2*q2;b3=a2,a2=r4,x2=u2,y2=v2,u2=m3,v2=n3}return b3===BigInt("1")?M(x2,md):err("no inverse")};callHash=name=>{const fn=hashes[name];"function"!=typeof fn&&err("hashes."+name+" not set");return fn};apoint=p4=>p4 instanceof Point?p4:err("Point expected");koblitz=x2=>M(M(x2*x2)*x2+_b3);FpIsValid=n3=>arange(n3,BigInt("0"),P);FpIsValidNot0=n3=>arange(n3,BigInt("1"),P);FnIsValidNot0=n3=>arange(n3,BigInt("1"),N);isEven=y2=>(y2&BigInt("1"))===BigInt("0");u8of=n3=>Uint8Array.of(n3);getPrefix=y2=>u8of(isEven(y2)?2:3);lift_x=x2=>{const c3=koblitz(FpIsValidNot0(x2));let r4=BigInt("1");for(let num=c3,e3=(P+BigInt("1"))/BigInt("4");e3>BigInt("0");e3>>=BigInt("1")){e3&BigInt("1")&&(r4=r4*num%P);num=num*num%P}return M(r4*r4)===c3?r4:err("sqrt invalid")};_Point=class _Point{constructor(X2,Y2,Z2){__publicField(this,"X");__publicField(this,"Y");__publicField(this,"Z");this.X=FpIsValid(X2);this.Y=FpIsValidNot0(Y2);this.Z=FpIsValid(Z2);Object.freeze(this)}static CURVE(){return secp256k1_CURVE}static fromAffine(ap2){const{x:x2,y:y2}=ap2;return x2===BigInt("0")&&y2===BigInt("0")?I:new _Point(x2,y2,BigInt("1"))}static fromBytes(bytes){abytes(bytes);const{publicKey:comp,publicKeyUncompressed:uncomp}=lengths;let p4;const length=bytes.length,head2=bytes[0],tail=bytes.subarray(1),x2=sliceBytesNumBE(tail,0,L);if(length===comp&&(2===head2||3===head2)){let y2=lift_x(x2);const evenY=isEven(y2);isEven(big(head2))!==evenY&&(y2=M(-y2));p4=new _Point(x2,y2,BigInt("1"))}length===uncomp&&4===head2&&(p4=new _Point(x2,sliceBytesNumBE(tail,L,64),BigInt("1")));return p4?p4.assertValidity():err("bad point: not on curve")}static fromHex(hex){return _Point.fromBytes(hexToBytes(hex))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}equals(other){const{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=apoint(other),X1Z2=M(X1*Z2),X2Z1=M(X2*Z1),Y1Z2=M(Y1*Z2),Y2Z1=M(Y2*Z1);return X1Z2===X2Z1&&Y1Z2===Y2Z1}is0(){return this.equals(I)}negate(){return new _Point(this.X,M(-this.Y),this.Z)}double(){return this.add(this)}add(other){const{X:X1,Y:Y1,Z:Z1}=this,{X:X2,Y:Y2,Z:Z2}=apoint(other),a2=BigInt("0"),b3=_b3;let X3=BigInt("0"),Y3=BigInt("0"),Z3=BigInt("0");const b32=M(b3*BigInt("3"));let t0=M(X1*X2),t1=M(Y1*Y2),t22=M(Z1*Z2),t3=M(X1+Y1),t4=M(X2+Y2);t3=M(t3*t4);t4=M(t0+t1);t3=M(t3-t4);t4=M(X1+Z1);let t5=M(X2+Z2);t4=M(t4*t5);t5=M(t0+t22);t4=M(t4-t5);t5=M(Y1+Z1);X3=M(Y2+Z2);t5=M(t5*X3);X3=M(t1+t22);t5=M(t5-X3);Z3=M(a2*t4);X3=M(b32*t22);Z3=M(X3+Z3);X3=M(t1-Z3);Z3=M(t1+Z3);Y3=M(X3*Z3);t1=M(t0+t0);t1=M(t1+t0);t22=M(a2*t22);t4=M(b32*t4);t1=M(t1+t22);t22=M(t0-t22);t22=M(a2*t22);t4=M(t4+t22);t0=M(t1*t4);Y3=M(Y3+t0);t0=M(t5*t4);X3=M(t3*X3);X3=M(X3-t0);t0=M(t3*t1);Z3=M(t5*Z3);Z3=M(Z3+t0);return new _Point(X3,Y3,Z3)}subtract(other){return this.add(apoint(other).negate())}multiply(n3,safe=!0){if(!safe&&n3===BigInt("0"))return I;FnIsValidNot0(n3);if(n3===BigInt("1"))return this;if(this.equals(G))return wNAF(n3).p;let p4=I,f4=G;for(let d4=this;n3>BigInt("0");d4=d4.double(),n3>>=BigInt("1"))n3&BigInt("1")?p4=p4.add(d4):safe&&(f4=f4.add(d4));return p4}multiplyUnsafe(scalar){return this.multiply(scalar,!1)}toAffine(){const{X:x2,Y:y2,Z:z2}=this;if(this.equals(I))return{x:BigInt("0"),y:BigInt("0")};if(z2===BigInt("1"))return{x:x2,y:y2};const iz=invert(z2,P);M(z2*iz)!==BigInt("1")&&err("inverse invalid");return{x:M(x2*iz),y:M(y2*iz)}}assertValidity(){const{x:x2,y:y2}=this.toAffine();FpIsValidNot0(x2);FpIsValidNot0(y2);return M(y2*y2)===koblitz(x2)?this:err("bad point: not on curve")}toBytes(isCompressed=!0){const{x:x2,y:y2}=this.assertValidity().toAffine(),x32b=numTo32b(x2);return isCompressed?concatBytes(getPrefix(y2),x32b):concatBytes(u8of(4),x32b,numTo32b(y2))}toHex(isCompressed){return bytesToHex(this.toBytes(isCompressed))}};__publicField(_Point,"BASE");__publicField(_Point,"ZERO");G=new(Point=_Point)(Gx,Gy,BigInt("1"));I=new Point(BigInt("0"),BigInt("1"),BigInt("0"));Point.BASE=G;Point.ZERO=I;doubleScalarMulUns=(R2,u1,u2)=>G.multiply(u1,!1).add(R2.multiply(u2,!1)).assertValidity();bytesToNumBE=b3=>big("0x"+(bytesToHex(b3)||"0"));sliceBytesNumBE=(b3,from,to)=>bytesToNumBE(b3.subarray(from,to));B256=BigInt("2")**BigInt("256");numTo32b=num=>hexToBytes(padh(arange(num,BigInt("0"),B256),64));secretKeyToScalar=secretKey2=>{const num=bytesToNumBE(abytes(secretKey2,L,"secret key"));return arange(num,BigInt("1"),N,"invalid secret key: outside of range")};0;getPublicKey=(privKey,isCompressed=!0)=>G.multiply(secretKeyToScalar(privKey)).toBytes(isCompressed);0;assertSigFormat=format=>{null==format||ALL_SIG.includes(format)||err(`Signature format must be one of: ${ALL_SIG.join(", ")}`);format===SIG_DER&&err('Signature format "der" is not supported: switch to noble-curves')};0;0;ALL_SIG=[SIG_COMPACT="compact",SIG_RECOVERED="recovered",SIG_DER="der"];hashes={hmacSha256Async:async(key3,message)=>{const s2=subtle(),k2=await s2.importKey("raw",key3,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return u8n(await s2.sign("HMAC",k2,message))},hmacSha256:void 0,sha256Async:async msg=>u8n(await subtle().digest("SHA-256",msg)),sha256:void 0};u8n(0);u8of(0);u8of(1);randomSecretKey=(seed=randomBytes(lengths.seed))=>{abytes(seed);(seed.length<lengths.seed||seed.length>1024)&&err("expected 40-1024b");const num=M(bytesToNumBE(seed),N-BigInt("1"));return numTo32b(num+BigInt("1"))};(createKeygen=getPublicKey2=>seed=>{const secretKey2=randomSecretKey(seed);return{secretKey:secretKey2,publicKey:getPublicKey2(secretKey2)}})(getPublicKey);getTag=tag3=>Uint8Array.from("BIP0340/"+tag3,(c3=>c3.charCodeAt(0)));taggedHash=(tag3,...messages)=>{const fn=callHash("sha256"),tagH=fn(getTag(tag3));return fn(concatBytes(tagH,tagH,...messages))};taggedHashAsync=async(tag3,...messages)=>{const fn=hashes.sha256Async,tagH=await fn(getTag(tag3));return await fn(concatBytes(tagH,tagH,...messages))};extpubSchnorr=priv=>{const d_=secretKeyToScalar(priv),p4=G.multiply(d_),{x:x2,y:y2}=p4.assertValidity().toAffine();return{d:isEven(y2)?d_:modN(-d_),px:numTo32b(x2)}};bytesModN=bytes=>modN(bytesToNumBE(bytes));challenge=(...args)=>bytesModN(taggedHash("challenge",...args));challengeAsync=async(...args)=>bytesModN(await taggedHashAsync("challenge",...args));keygenSchnorr=createKeygen(pubSchnorr=secretKey2=>extpubSchnorr(secretKey2).px);prepSigSchnorr=(message,secretKey2,auxRand)=>{const{px,d:d4}=extpubSchnorr(secretKey2);return{m:abytes(message),px,d:d4,a:abytes(auxRand,L)}};extractK=rand=>{const k_=bytesModN(rand);k_===BigInt("0")&&err("sign failed: k is zero");const{px,d:d4}=extpubSchnorr(numTo32b(k_));return{rx:px,k:d4}};createSigSchnorr=(k2,px,e3,d4)=>concatBytes(px,numTo32b(modN(k2+e3*d4)));E_INVSIG="invalid signature produced";callSyncAsyncFn=(res2,later)=>res2 instanceof Promise?res2.then(later):later(res2);_verifSchnorr=(signature,message,publicKey2,challengeFn)=>{const sig=abytes(signature,64,"signature"),msg=abytes(message,void 0,"message"),pub=abytes(publicKey2,L,"publicKey");try{const x2=bytesToNumBE(pub),y2=lift_x(x2),y_=isEven(y2)?y2:M(-y2),P_=new Point(x2,y_,BigInt("1")).assertValidity(),px=numTo32b(P_.toAffine().x),r4=sliceBytesNumBE(sig,0,L);arange(r4,BigInt("1"),P);const s2=sliceBytesNumBE(sig,L,64);arange(s2,BigInt("1"),N);const i2=concatBytes(numTo32b(r4),px,msg);return callSyncAsyncFn(challengeFn(i2),(e3=>{const{x:x3,y:y3}=doubleScalarMulUns(P_,s2,modN(-e3)).toAffine();return!(!isEven(y3)||x3!==r4)}))}catch(error){return!1}};schnorr={keygen:keygenSchnorr,getPublicKey:pubSchnorr,sign:(message,secretKey2,auxRand=randomBytes(L))=>{const{m:m3,px,d:d4,a:a2}=prepSigSchnorr(message,secretKey2,auxRand),aux=taggedHash("aux",a2),t3=numTo32b(d4^bytesToNumBE(aux)),rand=taggedHash("nonce",t3,px,m3),{rx,k:k2}=extractK(rand),e3=challenge(rx,px,m3),sig=createSigSchnorr(k2,rx,e3,d4);verifySchnorr(sig,m3,px)||err(E_INVSIG);return sig},verify:verifySchnorr=(s2,m3,p4)=>_verifSchnorr(s2,m3,p4,challenge),signAsync:async(message,secretKey2,auxRand=randomBytes(L))=>{const{m:m3,px,d:d4,a:a2}=prepSigSchnorr(message,secretKey2,auxRand),aux=await taggedHashAsync("aux",a2),t3=numTo32b(d4^bytesToNumBE(aux)),rand=await taggedHashAsync("nonce",t3,px,m3),{rx,k:k2}=extractK(rand),e3=await challengeAsync(rx,px,m3),sig=createSigSchnorr(k2,rx,e3,d4);await verifySchnorrAsync(sig,m3,px)||err(E_INVSIG);return sig},verifyAsync:verifySchnorrAsync=async(s2,m3,p4)=>_verifSchnorr(s2,m3,p4,challengeAsync)};pwindows=Math.ceil(32)+1;precompute=()=>{const points=[];let p4=G,b3=p4;for(let w2=0;w2<pwindows;w2++){b3=p4;points.push(b3);for(let i2=1;i2<128;i2++){b3=b3.add(p4);points.push(b3)}p4=b3.double()}return points};Gpows=void 0;ctneg=(cnd,p4)=>{const n3=p4.negate();return cnd?n3:p4};wNAF=n3=>{const comp=Gpows||(Gpows=precompute());let p4=I,f4=G;const mask=big(255),shiftBy=big(8);for(let w2=0;w2<pwindows;w2++){let wbits2=Number(n3&mask);n3>>=shiftBy;if(wbits2>128){wbits2-=256;n3+=BigInt("1")}const off=128*w2,offF=off,offP=off+Math.abs(wbits2)-1,isEven2=w2%2!=0,isNeg=wbits2<0;0===wbits2?f4=f4.add(ctneg(isEven2,comp[offF])):p4=p4.add(ctneg(isNeg,comp[offP]))}n3!==BigInt("0")&&err("invalid wnaf");return{p:p4,f:f4}};var{floor,random,sin}=Math;alloc=(n3,f4)=>Array(n3).fill().map(f4);selfId=(genId=n3=>alloc(n3,(()=>"0123456789AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"[floor(62*random())])).join(""))(20);all=Promise.all.bind(Promise);isBrowser="undefined"!=typeof window;var{entries,fromEntries,keys}=Object;noOp=()=>{};mkErr=msg=>new Error(`Trystero: ${msg}`);encoder=new TextEncoder;decoder=new TextDecoder;encodeBytes=txt=>encoder.encode(txt);decodeBytes=buffer=>decoder.decode(buffer);toHex=buffer=>buffer.reduce(((a2,c3)=>a2+c3.toString(16).padStart(2,"0")),"");topicPath=(...parts)=>parts.join("@");shuffle=(xs,seed)=>{const a2=[...xs],rand=()=>{const x2=1e4*sin(seed++);return x2-floor(x2)};let i2=a2.length;for(;i2;){const j2=floor(rand()*i2--);[a2[i2],a2[j2]]=[a2[j2],a2[i2]]}return a2};getRelays=(config,defaults2,defaultN,deriveFromAppId)=>(config.relayUrls||(deriveFromAppId?shuffle(defaults2,strToNum(config.appId)):defaults2)).slice(0,config.relayUrls?config.relayUrls.length:config.relayRedundancy||defaultN);toJson=JSON.stringify;fromJson=JSON.parse;strToNum=(str,limit=Number.MAX_SAFE_INTEGER)=>str.split("").reduce(((a2,c3)=>a2+c3.charCodeAt(0)),0)%limit;socketRetryPeriods={};reconnectionLockingPromise=null;resolver=null;pauseRelayReconnection=()=>{reconnectionLockingPromise||(reconnectionLockingPromise=new Promise((resolve=>{resolver=resolve})).finally((()=>{resolver=null;reconnectionLockingPromise=null})))};resumeRelayReconnection=()=>null==resolver?void 0:resolver();makeSocket=(url,onMessage)=>{const client={},init3=()=>{const socket=new WebSocket(url);socket.onclose=()=>{if(reconnectionLockingPromise)reconnectionLockingPromise.then(init3);else{null!=socketRetryPeriods[url]||(socketRetryPeriods[url]=3333);setTimeout(init3,socketRetryPeriods[url]);socketRetryPeriods[url]*=2}};socket.onmessage=e3=>onMessage(e3.data);client.socket=socket;client.url=socket.url;client.ready=new Promise((res2=>socket.onopen=()=>{res2(client);socketRetryPeriods[url]=3333}));client.send=data=>{1===socket.readyState&&socket.send(data)}};init3();return client};socketGetter=clientMap=>()=>fromEntries(entries(clientMap).map((([url,client])=>[url,client.socket])));watchOnline=()=>{if(isBrowser){const controller=new AbortController;addEventListener("online",resumeRelayReconnection,{signal:controller.signal});addEventListener("offline",pauseRelayReconnection,{signal:controller.signal});return()=>controller.abort()}return noOp};strToSha1={};pack=buff=>btoa(String.fromCharCode.apply(null,new Uint8Array(buff)));unpack=packed=>{const str=atob(packed);return new Uint8Array(str.length).map(((_,i2)=>str.charCodeAt(i2))).buffer};hashWith=async(algo2,str)=>new Uint8Array(await crypto.subtle.digest(algo2,encodeBytes(str)));sha1=async str=>strToSha1[str]||(strToSha1[str]=Array.from(await hashWith("SHA-1",str)).map((b3=>b3.toString(36))).join(""));genKey=async(secret,appId,roomId)=>crypto.subtle.importKey("raw",await crypto.subtle.digest({name:"SHA-256"},encodeBytes(`${secret}:${appId}:${roomId}`)),{name:"AES-GCM"},!1,["encrypt","decrypt"]);encrypt=async(keyP,plaintext)=>{const iv=crypto.getRandomValues(new Uint8Array(16));return iv.join(",")+"$"+pack(await crypto.subtle.encrypt({name:"AES-GCM",iv},await keyP,encodeBytes(plaintext)))};decrypt=async(keyP,raw)=>{const[iv,c3]=raw.split("$");return decodeBytes(await crypto.subtle.decrypt({name:"AES-GCM",iv:new Uint8Array(iv.split(","))},await keyP,unpack(c3)))};peer_default=(initiator,{rtcConfig,rtcPolyfill,turnConfig})=>{const pc=new(rtcPolyfill||RTCPeerConnection)({iceServers:defaultIceServers.concat(turnConfig||[]),...rtcConfig}),handlers2={};let makingOffer=!1,isSettingRemoteAnswerPending=!1,dataChannel=null;const setupDataChannel=channel=>{channel.binaryType="arraybuffer";channel.bufferedAmountLowThreshold=65535;channel.onmessage=e3=>{var _a8;return null==(_a8=handlers2.data)?void 0:_a8.call(handlers2,e3.data)};channel.onopen=()=>{var _a8;return null==(_a8=handlers2.connect)?void 0:_a8.call(handlers2)};channel.onclose=()=>{var _a8;return null==(_a8=handlers2.close)?void 0:_a8.call(handlers2)};channel.onerror=err3=>{var _a8;return null==(_a8=handlers2.error)?void 0:_a8.call(handlers2,err3)}},waitForIceGathering=pc2=>Promise.race([new Promise((res2=>{const checkState=()=>{if("complete"===pc2.iceGatheringState){pc2.removeEventListener("icegatheringstatechange",checkState);res2()}};pc2.addEventListener("icegatheringstatechange",checkState);checkState()})),new Promise((res2=>setTimeout(res2,5e3)))]).then((()=>({type:pc2.localDescription.type,sdp:pc2.localDescription.sdp.replace(/a=ice-options:trickle\s\n/g,"")})));if(initiator){dataChannel=pc.createDataChannel("data");setupDataChannel(dataChannel)}else pc.ondatachannel=({channel})=>{dataChannel=channel;setupDataChannel(channel)};pc.onnegotiationneeded=async()=>{var _a8,_b5;try{makingOffer=!0;await pc.setLocalDescription();const offer=await waitForIceGathering(pc);null==(_a8=handlers2.signal)||_a8.call(handlers2,offer)}catch(err3){null==(_b5=handlers2.error)||_b5.call(handlers2,err3)}finally{makingOffer=!1}};pc.onconnectionstatechange=()=>{var _a8;["disconnected","failed","closed"].includes(pc.connectionState)&&(null==(_a8=handlers2.close)||_a8.call(handlers2))};pc.ontrack=e3=>{var _a8,_b5;null==(_a8=handlers2.track)||_a8.call(handlers2,e3.track,e3.streams[0]);null==(_b5=handlers2.stream)||_b5.call(handlers2,e3.streams[0])};pc.onremovestream=e3=>{var _a8;return null==(_a8=handlers2.stream)?void 0:_a8.call(handlers2,e3.stream)};initiator&&(pc.canTrickleIceCandidates||pc.onnegotiationneeded());return{created:Date.now(),connection:pc,get channel(){return dataChannel},get isDead(){return"closed"===pc.connectionState},async signal(sdp){var _a8,_b5,_c3;if("open"!==(null==dataChannel?void 0:dataChannel.readyState)||(null==(_a8=sdp.sdp)?void 0:_a8.includes("a=rtpmap")))try{if("offer"===sdp.type){if(makingOffer||"stable"!==pc.signalingState&&!isSettingRemoteAnswerPending){if(initiator)return;await all([pc.setLocalDescription({type:"rollback"}),pc.setRemoteDescription(sdp)])}else await pc.setRemoteDescription(sdp);await pc.setLocalDescription();const answer=await waitForIceGathering(pc);null==(_b5=handlers2.signal)||_b5.call(handlers2,answer);return answer}if("answer"===sdp.type){isSettingRemoteAnswerPending=!0;try{await pc.setRemoteDescription(sdp)}finally{isSettingRemoteAnswerPending=!1}}}catch(err3){null==(_c3=handlers2.error)||_c3.call(handlers2,err3)}},sendData:data=>dataChannel.send(data),destroy:()=>{null==dataChannel||dataChannel.close();pc.close();makingOffer=!1;isSettingRemoteAnswerPending=!1},setHandlers:newHandlers=>Object.assign(handlers2,newHandlers),offerPromise:initiator?new Promise((res2=>handlers2.signal=sdp=>{"offer"===sdp.type&&res2(sdp)})):Promise.resolve(),addStream:stream=>stream.getTracks().forEach((track=>pc.addTrack(track,stream))),removeStream:stream=>pc.getSenders().filter((sender=>stream.getTracks().includes(sender.track))).forEach((sender=>pc.removeTrack(sender))),addTrack:(track,stream)=>pc.addTrack(track,stream),removeTrack:track=>{const sender=pc.getSenders().find((s2=>s2.track===track));sender&&pc.removeTrack(sender)},replaceTrack:(oldTrack,newTrack)=>{const sender=pc.getSenders().find((s2=>s2.track===oldTrack));if(sender)return sender.replaceTrack(newTrack)}}};defaultIceServers=[...alloc(3,((_,i2)=>`stun:stun${i2||""}.l.google.com:19302`)),"stun:stun.cloudflare.com:3478"].map((url=>({urls:url})));TypedArray=Object.getPrototypeOf(Uint8Array);chunkSize=16384-(payloadIndex=1+(progressIndex=1+13));internalNs=ns=>"@_"+ns;room_default=(onPeer,onPeerLeave,onSelfLeave)=>{const peerMap={},actions={},actionsCache={},pendingTransmissions={},pendingPongs={},pendingStreamMetas={},pendingTrackMetas={},listeners={onPeerJoin:noOp,onPeerLeave:noOp,onPeerStream:noOp,onPeerTrack:noOp},iterate2=(targets,f4)=>(targets?Array.isArray(targets)?targets:[targets]:keys(peerMap)).flatMap((id=>{const peer=peerMap[id];if(!peer){console.warn(`Trystero: no peer with id ${id} found`);return[]}return f4(id,peer)})),exitPeer=id=>{if(peerMap[id]){peerMap[id].destroy();delete peerMap[id];delete pendingTransmissions[id];delete pendingPongs[id];listeners.onPeerLeave(id);onPeerLeave(id)}},makeAction=type=>{if(actions[type])return actionsCache[type];if(!type)throw mkErr("action type argument is required");const typeBytes=encodeBytes(type);if(typeBytes.byteLength>12)throw mkErr(`action type string "${type}" (${typeBytes.byteLength}b) exceeds byte limit (12). Hint: choose a shorter name.`);const typeBytesPadded=new Uint8Array(12);typeBytesPadded.set(typeBytes);let nonce=0;actions[type]={onComplete:noOp,onProgress:noOp,setOnComplete:f4=>actions[type]={...actions[type],onComplete:f4},setOnProgress:f4=>actions[type]={...actions[type],onProgress:f4},send:async(data,targets,meta,onProgress)=>{if(meta&&"object"!=typeof meta)throw mkErr("action meta argument must be an object");const dataType=typeof data;if("undefined"===dataType)throw mkErr("action data cannot be undefined");const isJson="string"!==dataType,isBlob2=data instanceof Blob,isBinary=isBlob2||data instanceof ArrayBuffer||data instanceof TypedArray;if(meta&&!isBinary)throw mkErr("action meta argument can only be used with binary data");const buffer=isBinary?new Uint8Array(isBlob2?await data.arrayBuffer():data):encodeBytes(isJson?toJson(data):data),metaEncoded=meta?encodeBytes(toJson(meta)):null,chunkTotal=Math.ceil(buffer.byteLength/chunkSize)+(meta?1:0)||1,chunks=alloc(chunkTotal,((_,i2)=>{const isLast=i2===chunkTotal-1,isMeta=meta&&0===i2,chunk=new Uint8Array(payloadIndex+(isMeta?metaEncoded.byteLength:isLast?buffer.byteLength-chunkSize*(chunkTotal-(meta?2:1)):chunkSize));chunk.set(typeBytesPadded);chunk.set([nonce],12);chunk.set([isLast|isMeta<<1|isBinary<<2|isJson<<3],13);chunk.set([Math.round((i2+1)/chunkTotal*255)],progressIndex);chunk.set(meta?isMeta?metaEncoded:buffer.subarray((i2-1)*chunkSize,i2*chunkSize):buffer.subarray(i2*chunkSize,(i2+1)*chunkSize),payloadIndex);return chunk}));nonce=nonce+1&255;return all(iterate2(targets,(async(id,peer)=>{const{channel}=peer;let chunkN=0;for(;chunkN<chunkTotal;){const chunk=chunks[chunkN];channel.bufferedAmount>channel.bufferedAmountLowThreshold&&await new Promise((res2=>{const next2=()=>{channel.removeEventListener("bufferedamountlow",next2);res2()};channel.addEventListener("bufferedamountlow",next2)}));if(!peerMap[id])break;peer.sendData(chunk);chunkN++;null==onProgress||onProgress(chunk[progressIndex]/255,id,meta)}})))}};return actionsCache[type]||(actionsCache[type]=[actions[type].send,actions[type].setOnComplete,actions[type].setOnProgress])},handleData=(id,data)=>{var _a8,_b5;const buffer=new Uint8Array(data),type=decodeBytes(buffer.subarray(0,12)).replaceAll("\0",""),[nonce]=buffer.subarray(12,13),[tag3]=buffer.subarray(13,progressIndex),[progress]=buffer.subarray(progressIndex,payloadIndex),payload=buffer.subarray(payloadIndex),isLast=!!(1&tag3),isMeta=!!(2&tag3),isBinary=!!(4&tag3),isJson=!!(8&tag3);if(!actions[type]){console.warn(`Trystero: received message with unregistered type (${type})`);return}pendingTransmissions[id]||(pendingTransmissions[id]={});(_a8=pendingTransmissions[id])[type]||(_a8[type]={});const target=(_b5=pendingTransmissions[id][type])[nonce]||(_b5[nonce]={chunks:[]});isMeta?target.meta=fromJson(decodeBytes(payload)):target.chunks.push(payload);actions[type].onProgress(progress/255,id,target.meta);if(!isLast)return;const full=new Uint8Array(target.chunks.reduce(((a2,c3)=>a2+c3.byteLength),0));target.chunks.reduce(((a2,c3)=>{full.set(c3,a2);return a2+c3.byteLength}),0);delete pendingTransmissions[id][type][nonce];if(isBinary)actions[type].onComplete(full,id,target.meta);else{const text2=decodeBytes(full);actions[type].onComplete(isJson?fromJson(text2):text2,id)}},leave=async()=>{await sendLeave("");await new Promise((res2=>setTimeout(res2,99)));entries(peerMap).forEach((([id,peer])=>{peer.destroy();delete peerMap[id]}));onSelfLeave()},[sendPing,getPing]=makeAction(internalNs("ping")),[sendPong,getPong]=makeAction(internalNs("pong")),[sendSignal2,getSignal]=makeAction(internalNs("signal")),[sendStreamMeta,getStreamMeta]=makeAction(internalNs("stream")),[sendTrackMeta,getTrackMeta]=makeAction(internalNs("track")),[sendLeave,getLeave]=makeAction(internalNs("leave"));onPeer(((peer,id)=>{if(!peerMap[id]){peerMap[id]=peer;peer.setHandlers({data:d4=>handleData(id,d4),stream:stream=>{listeners.onPeerStream(stream,id,pendingStreamMetas[id]);delete pendingStreamMetas[id]},track:(track,stream)=>{listeners.onPeerTrack(track,stream,id,pendingTrackMetas[id]);delete pendingTrackMetas[id]},signal:sdp=>sendSignal2(sdp,id),close:()=>exitPeer(id),error:err3=>{console.error(err3);exitPeer(id)}});listeners.onPeerJoin(id)}}));getPing(((_,id)=>sendPong("",id)));getPong(((_,id)=>{var _a8;null==(_a8=pendingPongs[id])||_a8.call(pendingPongs);delete pendingPongs[id]}));getSignal(((sdp,id)=>{var _a8;return null==(_a8=peerMap[id])?void 0:_a8.signal(sdp)}));getStreamMeta(((meta,id)=>pendingStreamMetas[id]=meta));getTrackMeta(((meta,id)=>pendingTrackMetas[id]=meta));getLeave(((_,id)=>exitPeer(id)));isBrowser&&addEventListener("beforeunload",leave);return{makeAction,leave,ping:async id=>{if(!id)throw mkErr("ping() must be called with target peer ID");const start=Date.now();sendPing("",id);await new Promise((res2=>pendingPongs[id]=res2));return Date.now()-start},getPeers:()=>fromEntries(entries(peerMap).map((([id,peer])=>[id,peer.connection]))),addStream:(stream,targets,meta)=>iterate2(targets,(async(id,peer)=>{meta&&await sendStreamMeta(meta,id);peer.addStream(stream)})),removeStream:(stream,targets)=>iterate2(targets,((_,peer)=>peer.removeStream(stream))),addTrack:(track,stream,targets,meta)=>iterate2(targets,(async(id,peer)=>{meta&&await sendTrackMeta(meta,id);peer.addTrack(track,stream)})),removeTrack:(track,targets)=>iterate2(targets,((_,peer)=>peer.removeTrack(track))),replaceTrack:(oldTrack,newTrack,targets,meta)=>iterate2(targets,(async(id,peer)=>{meta&&await sendTrackMeta(meta,id);peer.replaceTrack(oldTrack,newTrack)})),onPeerJoin:f4=>listeners.onPeerJoin=f4,onPeerLeave:f4=>listeners.onPeerLeave=f4,onPeerStream:f4=>listeners.onPeerStream=f4,onPeerTrack:f4=>listeners.onPeerTrack=f4}};strategy_default=({init:init3,subscribe:subscribe2,announce})=>{const occupiedRooms={};let initPromises,offerPool,offerCleanupTimer,cleanupWatchOnline,didInit=!1;return(config,roomId,onJoinError)=>{var _a8;const{appId}=config;if(null==(_a8=occupiedRooms[appId])?void 0:_a8[roomId])return occupiedRooms[appId][roomId];const pendingOffers={},connectedPeers={},rootTopicPlaintext=topicPath("Trystero",appId,roomId),rootTopicP=sha1(rootTopicPlaintext),selfTopicP=sha1(topicPath(rootTopicPlaintext,selfId)),key3=genKey(config.password||"",appId,roomId),withKey=f4=>async signal=>({type:signal.type,sdp:await f4(key3,signal.sdp)}),toPlain=withKey(decrypt),toCipher=withKey(encrypt),makeOffer=()=>peer_default(!0,config),connectPeer=(peer,peerId,relayId)=>{var _a9;if(connectedPeers[peerId])connectedPeers[peerId]!==peer&&peer.destroy();else{connectedPeers[peerId]=peer;onPeerConnect(peer,peerId);null==(_a9=pendingOffers[peerId])||_a9.forEach(((peer2,i2)=>{i2!==relayId&&peer2.destroy()}));delete pendingOffers[peerId]}},disconnectPeer=(peer,peerId)=>{connectedPeers[peerId]===peer&&delete connectedPeers[peerId]},prunePendingOffer=(peerId,relayId)=>{var _a9;if(connectedPeers[peerId])return;const offer=null==(_a9=pendingOffers[peerId])?void 0:_a9[relayId];if(offer){delete pendingOffers[peerId][relayId];offer.destroy()}},getOffers=n3=>{offerPool.push(...alloc(n3,makeOffer));return all(offerPool.splice(0,n3).map((peer=>peer.offerPromise.then(toCipher).then((offer=>({peer,offer}))))))},handleJoinError=(peerId,sdpType)=>null==onJoinError?void 0:onJoinError({error:`incorrect password (${config.password}) when decrypting ${sdpType}`,appId,peerId,roomId}),handleMessage=relayId=>async(topic,msg,signalPeer)=>{var _a9,_b5,_c3;const[rootTopic,selfTopic]=await all([rootTopicP,selfTopicP]);if(topic!==rootTopic&&topic!==selfTopic)return;const{peerId,offer,answer,peer}="string"==typeof msg?fromJson(msg):msg;if(peerId!==selfId&&!connectedPeers[peerId])if(!peerId||offer||answer){if(offer){if((null==(_b5=pendingOffers[peerId])?void 0:_b5[relayId])&&selfId>peerId)return;const peer2=peer_default(!1,config);peer2.setHandlers({connect:()=>connectPeer(peer2,peerId,relayId),close:()=>disconnectPeer(peer2,peerId)});let plainOffer;try{plainOffer=await toPlain(offer)}catch(e3){handleJoinError(peerId,"offer");return}if(peer2.isDead)return;const[topic2,answer2]=await all([sha1(topicPath(rootTopicPlaintext,peerId)),peer2.signal(plainOffer)]);signalPeer(topic2,toJson({peerId:selfId,answer:await toCipher(answer2)}))}else if(answer){let plainAnswer;try{plainAnswer=await toPlain(answer)}catch(e3){handleJoinError(peerId,"answer");return}if(peer){peer.setHandlers({connect:()=>connectPeer(peer,peerId,relayId),close:()=>disconnectPeer(peer,peerId)});peer.signal(plainAnswer)}else{const peer2=null==(_c3=pendingOffers[peerId])?void 0:_c3[relayId];peer2&&!peer2.isDead&&peer2.signal(plainAnswer)}}}else{if(null==(_a9=pendingOffers[peerId])?void 0:_a9[relayId])return;const[[{peer:peer2,offer:offer2}],topic2]=await all([getOffers(1),sha1(topicPath(rootTopicPlaintext,peerId))]);pendingOffers[peerId]||(pendingOffers[peerId]=[]);pendingOffers[peerId][relayId]=peer2;setTimeout((()=>prunePendingOffer(peerId,relayId)),.9*announceIntervals[relayId]);peer2.setHandlers({connect:()=>connectPeer(peer2,peerId,relayId),close:()=>disconnectPeer(peer2,peerId)});signalPeer(topic2,toJson({peerId:selfId,offer:offer2}))}};if(!config)throw mkErr("requires a config map as the first argument");if(!appId&&!config.firebaseApp)throw mkErr("config map is missing appId field");if(!roomId)throw mkErr("roomId argument required");if(!didInit){const initRes=init3(config);offerPool=alloc(20,makeOffer);initPromises=Array.isArray(initRes)?initRes:[initRes];didInit=!0;offerCleanupTimer=setInterval((()=>offerPool=offerPool.filter((peer=>{const shouldLive=Date.now()-peer.created<57333;shouldLive||peer.destroy();return shouldLive}))),59052.99);cleanupWatchOnline=config.manualRelayReconnection?noOp:watchOnline()}const announceIntervals=initPromises.map((()=>5333)),announceTimeouts=[],unsubFns=initPromises.map((async(relayP,i2)=>subscribe2(await relayP,await rootTopicP,await selfTopicP,handleMessage(i2),getOffers)));all([rootTopicP,selfTopicP]).then((([rootTopic,selfTopic])=>{const queueAnnounce=async(relay,i2)=>{const ms=await announce(relay,rootTopic,selfTopic);"number"==typeof ms&&(announceIntervals[i2]=ms);announceTimeouts[i2]=setTimeout((()=>queueAnnounce(relay,i2)),announceIntervals[i2])};unsubFns.forEach((async(didSub,i2)=>{await didSub;queueAnnounce(await initPromises[i2],i2)}))}));let onPeerConnect=noOp;occupiedRooms[appId]||(occupiedRooms[appId]={});return occupiedRooms[appId][roomId]=room_default((f4=>onPeerConnect=f4),(id=>delete connectedPeers[id]),(()=>{delete occupiedRooms[appId][roomId];announceTimeouts.forEach(clearTimeout);unsubFns.forEach((async f4=>(await f4)()));clearInterval(offerCleanupTimer);cleanupWatchOnline();didInit=!1}))}};clients={};var{secretKey,publicKey}=schnorr.keygen();pubkey=toHex(publicKey);subIdToTopic={};msgHandlers={};kindCache={};now2=()=>Math.floor(Date.now()/1e3);topicToKind=topic=>{var _a8;return null!=(_a8=kindCache[topic])?_a8:kindCache[topic]=strToNum(topic,1e4)+2e4};createEvent=async(topic,content)=>{const payload={kind:topicToKind(topic),tags:[["x",topic]],created_at:now2(),content,pubkey},id=await hashWith("SHA-256",toJson([0,payload.pubkey,payload.created_at,payload.kind,payload.tags,payload.content]));return toJson(["EVENT",{...payload,id:toHex(id),sig:toHex(await schnorr.signAsync(id,secretKey))}])};subscribe=(subId,topic)=>{subIdToTopic[subId]=topic;return toJson(["REQ",subId,{kinds:[topicToKind(topic)],since:now2(),["#x"]:[topic]}])};unsubscribe=subId=>{delete subIdToTopic[subId];return toJson(["CLOSE",subId])};joinRoom=strategy_default({init:config=>getRelays(config,defaultRelayUrls,5,!0).map((url=>{const client=makeSocket(url,(data=>{var _a8;const[msgType,subId,payload,relayMsg]=fromJson(data);if("EVENT"===msgType)null==(_a8=msgHandlers[subId])||_a8.call(msgHandlers,subIdToTopic[subId],payload.content);else{const prefix=`Trystero: relay failure from ${client.url} - `;"NOTICE"===msgType?console.warn(prefix+subId):"OK"!==msgType||payload||console.warn(prefix+relayMsg)}}));clients[url]=client;return client.ready})),subscribe:(client,rootTopic,selfTopic,onMessage)=>{const rootSubId=genId(64),selfSubId=genId(64);msgHandlers[rootSubId]=msgHandlers[selfSubId]=(topic,data)=>onMessage(topic,data,(async(peerTopic,signal)=>client.send(await createEvent(peerTopic,signal))));client.send(subscribe(rootSubId,rootTopic));client.send(subscribe(selfSubId,selfTopic));return()=>{client.send(unsubscribe(rootSubId));client.send(unsubscribe(selfSubId));delete msgHandlers[rootSubId];delete msgHandlers[selfSubId]}},announce:async(client,rootTopic)=>client.send(await createEvent(rootTopic,toJson({peerId:selfId})))});getRelaySockets=socketGetter(clients);defaultRelayUrls=["black.nostrcity.club","ftp.halifax.rwth-aachen.de/nostr","nos.lol","nostr.cool110.xyz","nostr.data.haus","nostr.sathoarder.com","nostr.vulpem.com","relay.agorist.space","relay.binaryrobot.com","relay.damus.io","relay.fountain.fm","relay.mostro.network","relay.nostraddress.com","relay.nostrdice.com","relay.nostromo.social","relay.oldenburg.cool","relay.verified-nostr.com","yabu.me/v2"].map((url=>"wss://"+url));ResponsePreventedError=class extends Error{constructor(message){super(`Response prevented: ${message}`)}};DeviceDecisions=(DeviceDecisions2=>{DeviceDecisions2.ACCEPT="accepted";DeviceDecisions2.REJECT="rejected";DeviceDecisions2.IGNORE="ignore";return DeviceDecisions2})(DeviceDecisions||{});StoredMapLike=class{constructor(store,prefix=""){this._cache=new Map;this._prefix="";this._store=store}addPrefix(key3){return`${this._prefix}-${key3}`}async get(key3){if(this._cache.has(key3))return this._cache.get(key3);const value=await this._store.get(this.addPrefix(key3));void 0!==value&&this._cache.set(key3,value);return value}async set(key3,value){try{const ret=await this._store.set(this.addPrefix(key3),value);this._cache.set(key3,value);return ret}catch(e3){this._cache.delete(key3);throw e3}}async delete(key3){try{const ret=await this._store.delete(this.addPrefix(key3));this._cache.delete(key3);return ret}catch(e3){this._cache.delete(key3);throw e3}}async has(key3){return!!this._cache.has(key3)||(await this._store.keys(this.addPrefix(key3),key3)).length>0}};TrysteroReplicatorP2PClient=class{constructor(server,connectedPeerId){this._prevSeq=0;this.waitingInvocations=new Map;this.invocationTimeouts=new Map;this._server=server;this._connectedPeerId=connectedPeerId;this._remoteDB=this._bindRemoteDB()}get remoteDB(){return this._remoteDB}_bindRemoteDB(){return{info:this.bindRemoteFunction("info"),changes:this.bindRemoteFunction("changes"),revsDiff:this.bindRemoteFunction("revsDiff"),bulkDocs:this.bindRemoteFunction("bulkDocs"),bulkGet:this.bindRemoteFunction("bulkGet"),put:this.bindRemoteFunction("put"),get:this.bindRemoteFunction("get")}}get __send(){var _a8;return null==(_a8=this._server)?void 0:_a8.__send.bind(this._server)}generateNewSeq(){const seq=Math.floor(115*Math.random())+1+this._prevSeq;if(!this.waitingInvocations.has(seq)){this._prevSeq=seq%~~(Number.MAX_SAFE_INTEGER/2);return seq}return this.generateNewSeq()}_sendRPC(type,args,timeout=3e4){if(!this.__send)throw new Error("Not connected to any room");const seq=this.generateNewSeq(),p4=promiseWithResolver();this.waitingInvocations.set(seq,p4);const request2={type,direction:"request",seq,args};timeout&&timeout>0&&this.invocationTimeouts.set(seq,setTimeout((()=>{if(this.waitingInvocations.has(seq)){this.waitingInvocations.delete(seq);p4.reject(new Error(`Invocation Timed out: ${type} (${seq}) (Timeout: ${timeout}ms)`))}this.invocationTimeouts.delete(seq)}),timeout));this.__send(request2,this._connectedPeerId);return p4.promise}__onResponse(data){const seq=data.seq,type=data.type;if(this.invocationTimeouts.has(seq)){clearTimeout(this.invocationTimeouts.get(seq));this.invocationTimeouts.delete(seq)}const p4=this.waitingInvocations.get(seq);if(p4){this.waitingInvocations.delete(seq);if(data.error){p4.reject(data.error);Logger(`Invoking remote function [ DONE] : ${type} (${seq}) : (Error)`,LOG_LEVEL_VERBOSE)}else p4.resolve(data.data)}else Logger(`Invoking remote function [ERROR] : ${type} (${seq}) : No Handler left. Possibly timed out`,LOG_LEVEL_VERBOSE)}bindRemoteFunction(type,timeout=3e4){return async(...args)=>{if(!this.__send)throw new Error("Not connected to any room");return await this._sendRPC(type,args,timeout)}}async invokeRemoteFunction(type,args,timeout=3e4){if(!this.__send)throw new Error("Not connected to any room");return await this._sendRPC(type,args,timeout)}bindRemoteObjectFunctions(key3,timeout=3e4){return async(...args)=>{if(!this.__send)throw new Error("Not connected to any room");return await this._sendRPC(`${key3.toString()}`,args,timeout)}}async invokeRemoteObjectFunction(key3,args,timeout=3e4){if(!this.__send)throw new Error("Not connected to any room");return await this._sendRPC(`${key3.toString()}`,args,timeout)}close(){this._remoteDB=void 0;this._server=void 0}};epochFNV1a=2166136261;c1=3432918353;c2=461845907;r1=15;r2=13;m=5;n=3864292196;new TextEncoder;EVENT_SERVER_STATUS="p2p-server-status";EVENT_ADVERTISEMENT_RECEIVED="p2p-advertisement-received";EVENT_DEVICE_LEAVED="p2p-device-leaved";EVENT_REQUEST_STATUS="p2p-request-status";EVENT_P2P_REQUEST_FORCE_OPEN="p2p-request-force-open";EVENT_P2P_REPLICATOR_STATUS="p2p-replicator-status";TrysteroReplicatorP2PServer=class{constructor(env,_serverPeerId=selfId){this.assignedFunctions=new Map;this.clients=new Map;this._bindingObjects=[];this._knownAdvertisements=new Map;this.temporaryAcceptedPeers=new Map;this._acceptablePeers=new Computed({evaluation:settings=>{var _a8;return`${null!=(_a8=null==settings?void 0:settings.P2P_AutoAcceptingPeers)?_a8:""}`.split(",").map((e3=>e3.trim())).filter((e3=>!!e3)).map((e3=>e3.startsWith("~")?new RegExp(e3.substring(1),"i"):new RegExp(`^${e3}$`,"i")))}});this._shouldDenyPeers=new Computed({evaluation:settings=>{var _a8;return`${null!=(_a8=null==settings?void 0:settings.P2P_AutoDenyingPeers)?_a8:""}`.split(",").map((e3=>e3.trim())).filter((e3=>!!e3)).map((e3=>e3.startsWith("~")?new RegExp(e3.substring(1),"i"):new RegExp(`^${e3}$`,"i")))}});this.activePeer=new Map;this._env=env;this._serverPeerId=_serverPeerId;eventHub.onEvent(EVENT_PLATFORM_UNLOADED,(()=>{this.shutdown()}));this.acceptedPeers=new StoredMapLike(this._env.simpleStore,"p2p-device-decisions")}get isDisposed(){return!this._room}get isServing(){return void 0!==this._room}async ensureLeaved(){var _a8;if(this._room){try{await(null==(_a8=this._room)?void 0:_a8.leave())}catch(ex){Logger("Some error has been occurred while leaving the room, but possibly can be ignored",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE)}this._room=void 0;eventHub.emitEvent("p2p-disconnected")}}async setRoom(room){var _a8;await(null==(_a8=this._room)?void 0:_a8.leave());this._room=room}async shutdown(){try{await this.close();await this.ensureLeaved()}catch(ex){Logger("Some error has been occurred while shutting down the server",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE)}}async dispatchConnectionStatus(){const adsTasks=[...this.knownAdvertisements].map((async e3=>{const isAccepted2=await this.acceptedPeers.get(e3.name),isTemporaryAccepted=this.temporaryAcceptedPeers.get(e3.peerId);return{...e3,isAccepted:isAccepted2,isTemporaryAccepted}})),ads=await Promise.all(adsTasks);eventHub.emitEvent(EVENT_SERVER_STATUS,{isConnected:this.isServing,knownAdvertisements:ads,serverPeerId:this.serverPeerId})}async makeDecision(decision){decision.decision?decision.isTemporary?this.temporaryAcceptedPeers.set(decision.peerId,!0):await this.acceptedPeers.set(decision.name,!0):decision.isTemporary?this.temporaryAcceptedPeers.set(decision.peerId,!1):await this.acceptedPeers.set(decision.name,!1);await this.dispatchConnectionStatus()}async revokeDecision(decision){this.temporaryAcceptedPeers.delete(decision.peerId);await this.acceptedPeers.delete(decision.name);await this.dispatchConnectionStatus()}get room(){return this._room}get serverPeerId(){return this._serverPeerId}get db(){return this._env.db}get confirm(){return this._env.confirm}get settings(){return this._env.settings}get isEnabled(){return this.settings.P2P_Enabled}get deviceInfo(){return{currentPeerId:this._serverPeerId,name:this._env.deviceName,platform:this._env.platform,version:"0.0.0"}}sendAdvertisement(peerId){if(!this.isEnabled)return;const devInfo=this.deviceInfo,data={peerId:devInfo.currentPeerId,name:devInfo.name,platform:devInfo.platform};if(this._sendAdvertisement){Logger(`peerId: ${this.serverPeerId} Sending Advertisement to ${null!=peerId?peerId:"All"}`,LOG_LEVEL_VERBOSE);this._sendAdvertisement(data,peerId)}}get knownAdvertisements(){return[...this._knownAdvertisements.values()]}onAdvertisement(data,peerId){if(this.isEnabled){Logger(`Advertisement from ${peerId}`,LOG_LEVEL_VERBOSE);if(peerId!==this.serverPeerId&&data.peerId!==this.serverPeerId&&data.name!==this.deviceInfo.name&&data.peerId===peerId){this._knownAdvertisements.set(peerId,data);this.dispatchConnectionStatus();eventHub.emitEvent(EVENT_ADVERTISEMENT_RECEIVED,data)}}}confirmUserToAccept(peerId){return shareRunningResult(`confirmUserToAccept-${peerId}`,(()=>this._confirmUserToAccept(peerId)))}_confirmUserToAccept(peerId){const peerInfo=this._knownAdvertisements.get(peerId);if(!peerInfo)throw new Error("Unknown Peer");const peerName=peerInfo.name,message=`Are you sure to establish connection to ${peerName} (${peerId})?\nYou can chose as follows:\n- Accept: Accept all connections from this peer.\n- Ignore: Reject all connections from this peer.\n- Accept Temporarily: Accept the connection for this session only.\n- Ignore Temporarily: Reject the connection for this session only.\n\n>[!INFO] You can revoke your decision from the Peer-to-Peer Replicator Pane.`;return this.confirm.askSelectStringDialogue(message,["Accept","Ignore","Accept Temporarily","Ignore Temporarily"],{title:"P2P Connection Request",defaultAction:"Ignore Temporarily",timeout:30}).then((decision=>{if("Accept Temporarily"===decision){this.temporaryAcceptedPeers.set(peerId,!0);this.dispatchConnectionStatus();return!0}if("Ignore Temporarily"===decision){this.temporaryAcceptedPeers.set(peerId,!1);this.dispatchConnectionStatus();return!1}if("Accept"===decision){this.temporaryAcceptedPeers.delete(peerId);this.acceptedPeers.set(peerName,!0);this.dispatchConnectionStatus();return!0}if("Ignore"===decision){this.temporaryAcceptedPeers.delete(peerId);this.acceptedPeers.set(peerName,!1);this.dispatchConnectionStatus();return!1}throw new ResponsePreventedError("User Accepting failed")}))}async isAcceptablePeer(peerId){if(!this.isEnabled)return;const peerInfo=this._knownAdvertisements.get(peerId);if(!peerInfo)return!1;const peerName=peerInfo.name;if(this.temporaryAcceptedPeers.has(peerId))return this.temporaryAcceptedPeers.get(peerId);const accepted=await this.acceptedPeers.get(peerName);if(null!=accepted)return accepted;const isAcceptable=(await this._acceptablePeers.update(this.settings)).value.some((e3=>e3.test(peerName))),isDeny=(await this._shouldDenyPeers.update(this.settings)).value.some((e3=>e3.test(peerName)));if(isAcceptable){if(isDeny)return!1;this.temporaryAcceptedPeers.set(peerId,!0);this.dispatchConnectionStatus();return!0}return!this.settings.P2P_IsHeadless&&await this.confirmUserToAccept(peerId)}async __send(data,peerId){if(this.isEnabled)if(await this.isAcceptablePeer(peerId)){if(this.___send)return await this.___send(data,peerId);Logger("Cannot send response, no send function")}else{Logger(`Invalid Message to ${peerId}`,LOG_LEVEL_VERBOSE);Logger(data,LOG_LEVEL_VERBOSE)}}async processArrivedRPC(data,peerId){if(this.isEnabled){if(!data.type.startsWith("!")&&!await this.isAcceptablePeer(peerId))throw new Error(`Not acceptable peer ${peerId}`);if("response"===data.direction)this.__onResponse(data,peerId);else{if("request"!==data.direction)throw new Error(`Invalid Message from ${peerId}`);await this.__onRequest(data,peerId)}}}onAfterJoinRoom(){Logger("Initializing...",LOG_LEVEL_VERBOSE);const room=this.room;if(!room)throw new Error("This server has been already disconnected");const[send,arrived]=room.makeAction("rpc");this.___send=send;arrived(((data,peerId)=>{this.processArrivedRPC(data,peerId).catch((e3=>{Logger(e3.message,LOG_LEVEL_INFO);Logger(e3,LOG_LEVEL_VERBOSE)}))}));const[adSend,adArrived]=room.makeAction("ad");this._sendAdvertisement=adSend;adArrived(((data,peerId)=>{this.onAdvertisement(data,peerId)}));room.onPeerJoin((peerId=>{const peer=room.getPeers()[peerId];this.activePeer.set(peerId,peer);this.sendAdvertisement(peerId)}));room.onPeerLeave((peerId=>{this._knownAdvertisements.delete(peerId);const peerConn=this.activePeer.get(peerId);if(peerConn){peerConn.close();this.activePeer.delete(peerId)}eventHub.emitEvent(EVENT_DEVICE_LEAVED,peerId);this.dispatchConnectionStatus()}));eventHub.emitEvent("p2p-connected");this.dispatchConnectionStatus()}async startService(bindings=[]){if(!this.isEnabled){Logger($msg("P2P.NotEnabled"),LOG_LEVEL_NOTICE);return}const servingDB=createHostingDB(this._env);this._bindingObjects=[...bindings,servingDB];this._bindingObjects.forEach((b3=>{this.serveObject(b3)}));await this.sendAdvertisement()}async start(bindings=[]){const passphraseNumbers=mixedHash(this.settings.P2P_passphrase,0),passphrase=passphraseNumbers[0].toString(36)+passphraseNumbers[1].toString(36);await this.shutdown();if(!this.settings.P2P_Enabled){Logger($msg("P2P.NotEnabled"),LOG_LEVEL_NOTICE);return}const relays=this.settings.P2P_relays.split(",").filter((e3=>e3.trim().length>0)),turnServers=this.settings.P2P_turnServers.split(",").map((e3=>e3.trim())).filter((e3=>e3.length>0)),options={relayUrls:relays,appId:this.settings.P2P_AppID,password:passphrase,turnConfig:turnServers.length>0?[{urls:turnServers,username:this.settings.P2P_turnUsername,credential:this.settings.P2P_turnCredential}]:[]},room=joinRoom(options,this.settings.P2P_roomID,!0);await this.setRoom(room);this.onAfterJoinRoom();this.dispatchConnectionStatus();await this.startService(bindings)}serveFunction(type,func){this.assignedFunctions.set(type,func)}serveObject(obj){Object.keys(obj).forEach((key3=>{if(key3.toString().startsWith("_"))return;const func=obj[key3].bind(obj);this.assignedFunctions.set(key3.toString(),func)}))}__onResponse(data,peerId){const peer=this.clients.get(peerId);peer?peer.__onResponse(data):Logger(`Response from unknown peer ${peerId}`,LOG_LEVEL_VERBOSE)}async __onRequest(data,peerId){try{const func=this.assignedFunctions.get(data.type);if("function"!=typeof func)throw new Error(`Cannot serve function ${data.type}, no function provided or I am only a client`);const r4=await Promise.resolve(func.apply(this,data.args));await this.__send({type:data.type,seq:data.seq,direction:"response",data:r4},peerId)}catch(e3){if(e3 instanceof ResponsePreventedError){Logger(`Serving function: [FAILED] ${data.type}: Response prevented.`,LOG_LEVEL_VERBOSE);return}Logger(`Serving function: [FAILED] ${data.type} sending back the failure information`,LOG_LEVEL_VERBOSE);Logger(e3 instanceof Error?e3.message:e3,LOG_LEVEL_VERBOSE);await this.__send({type:data.type,seq:data.seq,direction:"response",data:void 0,error:e3},peerId)}}async close(){var _a8,_b5;this.assignedFunctions.clear();const peers=null!=(_b5=null==(_a8=this.room)?void 0:_a8.getPeers())?_b5:{};this.clients.forEach((client=>client.close()));this.clients.clear();for(const[,peer]of Object.entries(peers))peer.close();await this.ensureLeaved();this._knownAdvertisements.clear();await this.dispatchConnectionStatus()}getConnection(peerId){if(this.clients.has(peerId))return this.clients.get(peerId);if(!this._knownAdvertisements.has(peerId))throw new Error(`Unknown Peer ${peerId}`);const client=new TrysteroReplicatorP2PClient(this,peerId);this.clients.set(peerId,client);return client}};p=promiseWithResolver();instance=void 0;eventHub.onceEvent(EVENT_PLATFORM_UNLOADED,(()=>{instance=void 0;p.resolve(void 0)}));replicatorInstanceGetter=()=>{};LiveSyncTrysteroReplicator=class extends LiveSyncAbstractReplicator{getReplicationPBKDF2Salt(setting,refresh){return Promise.resolve(new Uint8Array(32))}terminateSync(){}async openReplication(setting,keepAlive,showResult,ignoreCleanLock){const logLevel=showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,r4=await this.getP2PConnection(logLevel);if(!r4)return!1;await r4.replicateFromCommand(showResult)}tryConnectRemote(setting,showResult){return Promise.resolve(!1)}replicateAllToServer(setting,showingNotice,sendChunksInBulkDisabled){return Promise.resolve(!1)}async openP2P(logLevel){const r4=getReplicatorInstance();if(!r4){Logger($msg("P2P.ReplicatorInstanceMissing"),logLevel);return!1}await r4.open();return r4}async getP2PConnection(logLevel){const r4=getReplicatorInstance();if(!r4){Logger($msg("P2P.ReplicatorInstanceMissing"),logLevel);return!1}await r4.makeSureOpened();return r4}async selectPeer(settingPeerName,r4,logLevel){var _a8,_b5,_c3,_d2,_e2;const knownPeersOrg=null!=(_b5=null==(_a8=r4.server)?void 0:_a8.knownAdvertisements)?_b5:[];let knownPeers;if(0!=knownPeersOrg.length)knownPeers=knownPeersOrg;else{Logger($msg("P2P.NoKnownPeers"),logLevel);await Promise.race([delay(5e3),eventHub.waitFor(EVENT_ADVERTISEMENT_RECEIVED)]);knownPeers=null!=(_d2=null==(_c3=r4.server)?void 0:_c3.knownAdvertisements)?_d2:[]}const message="Rebuild from which peer?"+(settingPeerName?"\n [*] indicates the peer you have selected before.":""),confirm=await getConfirmInstance(),options=[...knownPeers.map((e3=>`${e3.name}${e3.name==settingPeerName?"[*]":""} (${e3.peerId})`)),"Refresh List","Cancel"],selected=await confirm.askSelectStringDialogue(message,options,{title:"Select a peer to fetch from",defaultAction:"Refresh List"});if(!selected||"Cancel"==selected)return!1;if("Refresh List"==selected){await Promise.race([delay(1e3),eventHub.waitFor(EVENT_ADVERTISEMENT_RECEIVED)]);return this.selectPeer(settingPeerName,r4,logLevel)}const selectedPeerName=selected.split("")[0],peerId=null==(_e2=knownPeers.find((e3=>e3.name==selectedPeerName)))?void 0:_e2.peerId;if(!peerId){Logger(`Failed to find peerId for ${selectedPeerName}`,logLevel);return!1}return peerId}async tryUntilSuccess(func,repeat,logLevel){if(!await getConfirmInstance()){Logger("Cannot find confirm instance.",logLevel);return Promise.reject("Cannot find confirm instance.")}let result;for(;!result;)for(let i2=0;i2<repeat;i2++){try{result=await func();if(result)break}catch(e3){Logger(`Error: ${e3}`,logLevel);result=!1}await delay(1e3)}return result}async replicateAllFromServer(setting,showingNotice){const logLevel=showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;if(0==setting.P2P_Enabled){const confirm=await getConfirmInstance();"yes"!=await confirm.askYesNoDialog($msg("P2P.DisabledButNeed"),{})&&Logger($msg("P2P.NotEnabled"),logLevel);setting.P2P_Enabled=!0;this.env.settings.P2P_Enabled=!0;await this.env.services.setting.saveSettingData();await delay(100);return this.replicateAllFromServer(setting,showingNotice)}eventHub.emitEvent(EVENT_P2P_REQUEST_FORCE_OPEN);await eventHub.waitFor("p2p-connected");const peerFrom=setting.P2P_RebuildFrom,instance3=getReplicatorInstance();if(!instance3){Logger("Failed to get replicator instance.",logLevel);return!1}instance3.setOnSetup();try{const r4=await this.tryUntilSuccess((()=>this.openP2P(logLevel)),10,logLevel);if(!1===r4){Logger("Failed to open P2P connection.",logLevel);return!1}const peerId=await this.selectPeer(peerFrom,r4,logLevel);if(!1===peerId){Logger("Failed to connect peer.",logLevel);return!1}this.env.settings.P2P_RebuildFrom="";Logger(`Fetching from peer ${peerId}.`,logLevel);const rep=await r4.replicateFrom(peerId,showingNotice);if(rep.ok){Logger(`P2P Fetching has been succeed from ${peerId}.`,logLevel);return!0}Logger(`Failed to fetch from peer ${peerId}.`,logLevel);Logger(rep.error,LOG_LEVEL_VERBOSE);return!1}finally{instance3.clearOnSetup()}}closeReplication(){const r4=getReplicatorInstance();null==r4||r4.disconnectFromServer()}tryResetRemoteDatabase(setting){throw new Error("P2P replication does not support database reset.")}tryCreateRemoteDatabase(setting){throw new Error("P2P replication does not support database reset.")}markRemoteLocked(setting,locked,lockByClean){throw new Error("P2P replication does not support database lock.")}markRemoteResolved(setting){Logger("Trying resolving remote-database-lock but P2P replication does not support database lock. This operation has been ignored",LOG_LEVEL_INFO);return Promise.resolve()}resetRemoteTweakSettings(setting){throw new Error("P2P replication does not support resetting tweaks.")}setPreferredRemoteTweakSettings(setting){Logger("Trying setting tweak values but P2P replication does not support to do this. This operation has been ignored",LOG_LEVEL_INFO);return Promise.resolve()}fetchRemoteChunks(missingChunks,showResult){return Promise.resolve(!1)}getRemoteStatus(setting){Logger("Trying to get remote status but P2P replication does not support to do this. This operation has been ignored",LOG_LEVEL_INFO);return Promise.resolve(!1)}getRemotePreferredTweakValues(setting){Logger("Trying to get tweak values but P2P replication does not support to do this. This operation has been ignored",LOG_LEVEL_INFO);return Promise.resolve(!1)}countCompromisedChunks(){Logger("P2P Replicator cannot count compromised chunks",LOG_LEVEL_VERBOSE);return Promise.resolve(0)}getConnectedDeviceList(setting){Logger("Trying to get connected device list but P2P replication does not support to do this. This operation has been ignored",LOG_LEVEL_INFO);return Promise.resolve(!1)}constructor(env){super(env);this.env=env}};UNDEFINED=Symbol("undefined");webcrypto2=globalThis.crypto;IV_LENGTH=12;HKDF_SALT_LENGTH=32;PBKDF2_SALT_LENGTH=32;gcmTagLength=128;HKDF_ENCRYPTED_PREFIX="%=";HKDF_SALTED_ENCRYPTED_PREFIX="%$";deriveMasterKey=function memoWithMap(bufferLength,fn,keyFunction){if(bufferLength<=0)throw new Error("Buffer length must be greater than 0");const cache2=new Map,getKey3=args=>args.length>0&&"string"==typeof args[0]?args[0]:JSON.stringify(args,((key3,value)=>void 0===value?UNDEFINED:value));return function(...args){const key3=keyFunction?keyFunction(args):getKey3(args);if(cache2.has(key3)){const hitPromise=cache2.get(key3);cache2.delete(key3);cache2.set(key3,hitPromise);return hitPromise}const newPromise=fn(...args);cache2.set(key3,newPromise);newPromise.catch((()=>{cache2.get(key3)===newPromise&&cache2.delete(key3)}));if(cache2.size>bufferLength){const oldestKey=cache2.keys().next().value;oldestKey&&cache2.delete(oldestKey)}return newPromise}}(10,(async(passphrase,pbkdf2Salt)=>{const binaryPassphrase=writeString(passphrase),keyMaterial=await webcrypto2.subtle.importKey("raw",binaryPassphrase,{name:"PBKDF2",length:256},!1,["deriveKey"]),masterKeyRaw=await webcrypto2.subtle.deriveKey({name:"PBKDF2",salt:pbkdf2Salt,iterations:31e4,hash:"SHA-256"},keyMaterial,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"]),masterKeyBuffer=await webcrypto2.subtle.exportKey("raw",masterKeyRaw);return await webcrypto2.subtle.importKey("raw",masterKeyBuffer,{name:"HKDF"},!1,["deriveKey"])}),(([passphrase,salt])=>`${passphrase}-${uint8ArrayToHexString(salt)}`));TrysteroReplicator=class{constructor(env){this._onSetup=!1;this.lastSeq="";this._isBroadcasting=!1;this.availableReplicationPairs=new Set;this._replicateToPeers=new Set;this._replicateFromPeers=new Set;this._watchingPeers=new Set;this._env=env;try{if(!this.settings.P2P_Enabled){Logger("P2P is not enabled",LOG_LEVEL_VERBOSE);return}if(!this.settings.P2P_AppID)throw new Error("P2P App ID is not provided. We need it to establish the P2P connection");if(!this.settings.P2P_roomID||!this.settings.P2P_passphrase)throw new Error("Room ID and/or P2P Passphrase have not provided. We need them to establish the P2P connection");if(!this.settings.P2P_relays||0===this.settings.P2P_relays.length)throw new Error("No relay URIs provided. We need them to establish the P2P connection");this.server=new TrysteroReplicatorP2PServer(env)}catch(e3){Logger(e3 instanceof Error?e3.message:"Error while creating TrysteroReplicator",LOG_LEVEL_NOTICE);Logger(e3,LOG_LEVEL_VERBOSE);throw e3}}replicationStatus(){return{}}get settings(){return this._env.settings}get db(){return this._env.db}get deviceName(){return this._env.deviceName}get platform(){return this._env.platform}get confirm(){return this._env.confirm}async close(){var _a8;this.requestStatus();await(null==(_a8=this.server)?void 0:_a8.shutdown());this._replicateFromPeers.clear();this._replicateToPeers.clear();this._watchingPeers.clear();this.requestStatus();this.disconnectFromServer()}async open(){var _a8;this.allowReconnection();await(null==(_a8=this.server)?void 0:_a8.start([this.getCommands()]));this.dispatchStatus();this.settings.P2P_AutoBroadcast&&this.enableBroadcastChanges()}async makeSureOpened(){var _a8;(null==(_a8=this.server)?void 0:_a8.isServing)||await this.open()}get autoSyncPeers(){return this.settings.P2P_AutoSyncPeers.split(",").map((e3=>e3.trim())).filter((e3=>e3.length>0)).map((e3=>e3.startsWith("~")?new RegExp(e3.substring(1),"i"):new RegExp(`^${e3}$`,"i")))}get autoWatchPeers(){return this.settings.P2P_AutoWatchPeers.split(",").map((e3=>e3.trim())).filter((e3=>e3.length>0)).map((e3=>e3.startsWith("~")?new RegExp(e3.substring(1),"i"):new RegExp(`^${e3}$`,"i")))}async onNewPeer(peer){const peerName=peer.name;this.autoSyncPeers.some((e3=>e3.test(peerName)))&&await this.sync(peer.peerId);this.autoWatchPeers.some((e3=>e3.test(peerName)))&&this.watchPeer(peer.peerId)}onPeerLeaved(peerId){this.unwatchPeer(peerId)}setOnSetup(){this._onSetup=!0}clearOnSetup(){this._onSetup=!1}async getTweakSettings(fromPeerId){var _a8;const allSettings=JSON.parse(JSON.stringify(this.settings));for(const key3 in allSettings)"encrypt"!=key3&&("passphrase"!=key3?key3 in TweakValuesShouldMatchedTemplate||delete allSettings[key3]:allSettings[key3]=await getHashedStringWithCurrentTime(null!=(_a8=allSettings[key3])?_a8:""));return allSettings}getCommands(){return{reqSync:async fromPeerId=>this._onSetup?{error:new Error("The setup is in progress")}:await this.replicateFrom(fromPeerId),"!reqAuth":async fromPeerId=>{var _a8;return await(null==(_a8=this.server)?void 0:_a8.isAcceptablePeer(fromPeerId))},getTweakSettings:async fromPeerId=>await this.getTweakSettings(fromPeerId),onProgress:async fromPeerId=>{if(this._onSetup)return{error:new Error("The setup is in progress")};await this.onUpdateDatabase(fromPeerId)},getAllConfig:async fromPeerId=>{if(this._onSetup)return{error:new Error("The setup is in progress")};const passphrase=await skipIfDuplicated(`getAllConfig-${fromPeerId}`,(async()=>await this.confirm.askString("Passphrase required",$msg("P2P.AskPassphraseForShare"),"something you only know",!0))),setting={...this.settings,configPassphraseStore:"",encryptedCouchDBConnection:"",encryptedPassphrase:"",pluginSyncExtendedSetting:{}};if(!passphrase||""==passphrase.trim()){Logger("Passphrase is required to transfer the configuration. The peer cannot be decrypt the config\nIf you repeatedly receive unintended configuration-sharing requests, change the RPC channel immediately. It allows you to leave the connection and disappear, while they are trying brute force attack for the decoy on their local.",LOG_LEVEL_NOTICE);return encrypt3(JSON.stringify(Object.fromEntries(Object.entries(setting).map((([key3,value])=>[key3,"******".repeat(Math.ceil(10*Math.random())+2)])))),Math.random().toString(36).substring(7))}return encrypt3(JSON.stringify(setting),passphrase.trim())},onProgressAcknowledged:async(fromPeerId,info3)=>{try{await this.onProgressAcknowledged(fromPeerId,info3)}catch(e3){Logger("Error while acknowledging the progress",LOG_LEVEL_VERBOSE);Logger(e3,LOG_LEVEL_VERBOSE)}},getIsBroadcasting:()=>Promise.resolve(this._isBroadcasting),requestBroadcasting:async peerId=>{if(this._onSetup)return{error:new Error("The setup is in progress")};if(this._isBroadcasting)return!0;"yes"===await skipIfDuplicated(`requested-${peerId}`,(async()=>await this.confirm.askYesNoDialog("The remote peer requested to broadcast the changes. Do you want to allow it?",{defaultOption:"No"})))&&this.enableBroadcastChanges()}}}async requestAuthenticate(peerId){if(!this.server)return!1;try{const connection=this.server.getConnection(peerId),selfPeerId=this.server.serverPeerId;return await connection.invokeRemoteObjectFunction("!reqAuth",[selfPeerId],2e4)}catch(e3){Logger("Error while requesting authentication",LOG_LEVEL_VERBOSE);Logger(e3,LOG_LEVEL_VERBOSE);return!1}}async selectPeer(){if(!this.server)return!1;const knownPeers=this.server.knownAdvertisements;if(0===knownPeers.length){Logger("No known peers",LOG_LEVEL_VERBOSE);return!1}const peers=[...Object.entries(knownPeers)].map((([peerId,info3])=>`${info3.peerId}: (${info3.name})`)),selectedPeer=await this.confirm.askSelectString("Select a peer to replicate",peers);return!!selectedPeer&&selectedPeer.split("")[0]}async requestSynchroniseToPeer(peerId){await delay(25);if(!this.server)throw new Error("Server is not available");const conn=this.server.getConnection(peerId);return await conn.invokeRemoteFunction("reqSync",[this.server.serverPeerId],0)}async requestSynchroniseToAllAvailablePeers(){await scheduleOnceIfDuplicated("requestSynchroniseToAllAvailablePeers",(async()=>{await delay(25);const replications=[...this.availableReplicationPairs].map((peerId=>this.requestSynchroniseToPeer(peerId)));await Promise.all(replications)}))}dispatchStatus(){eventHub.emitEvent(EVENT_P2P_REPLICATOR_STATUS,{isBroadcasting:this._isBroadcasting,replicatingTo:[...this._replicateToPeers],replicatingFrom:[...this._replicateFromPeers],watchingPeers:[...this._watchingPeers]})}requestStatus(){var _a8;this.dispatchStatus();null==(_a8=this.server)||_a8.dispatchConnectionStatus()}disableBroadcastChanges(){var _a8;null==(_a8=this.changes)||_a8.cancel();this._isBroadcasting=!1;this.dispatchStatus()}enableBroadcastChanges(){if(this._isBroadcasting)return;this._isBroadcasting=!0;this.dispatchStatus();if(this.changes){this.changes.cancel();this.changes.removeAllListeners()}this.changes=this.db.changes({since:"now",live:!0,include_docs:!1,selector:{_id:{$gt:"_local/"}}});this.changes.on("change",(async change=>{this.lastSeq=change.seq;await this.notifyProgress()}));const closeChanges=reason=>{var _a8,_b5;if(reason)if(reason instanceof Error){Logger("Error while broadcasting the changes",LOG_LEVEL_INFO);Logger(reason,LOG_LEVEL_VERBOSE)}else{Logger("Broadcasting the changes has been finished",LOG_LEVEL_INFO);Logger(reason,LOG_LEVEL_VERBOSE)}null==(_a8=this.changes)||_a8.cancel();null==(_b5=this.changes)||_b5.removeAllListeners();this.changes=void 0;this._isBroadcasting=!1;this.dispatchStatus()};this.changes.on("error",closeChanges);this.changes.on("complete",closeChanges);fireAndForget((async()=>await this.notifyProgress()))}get knownAdvertisements(){var _a8,_b5;return null!=(_b5=null==(_a8=this.server)?void 0:_a8.knownAdvertisements)?_b5:[]}async sync(remotePeer,showNotice=!1){const from=await this.replicateFrom(remotePeer,showNotice);if(!from||from.error){Logger("Error while replicating from the remote",LOG_LEVEL_VERBOSE);Logger(from.error,LOG_LEVEL_VERBOSE);return from}const logLevel=showNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;Logger(`P2P Replication has been requested to ${remotePeer}`,logLevel,"p2p-replicator");const res2=await this.requestSynchroniseToPeer(remotePeer);res2.ok&&Logger("P2P Replication has been done",logLevel,"p2p-replicator");if(res2.error){Logger("Error while syncing from the remote",logLevel,"p2p-replicator");Logger(res2.error,LOG_LEVEL_VERBOSE)}}async replicateTo(){await this.makeSureOpened();const remotePeer=await this.selectPeer();if(remotePeer){Logger(`P2P Replicating to ${remotePeer}`,LOG_LEVEL_INFO);try{if(this._replicateToPeers.has(remotePeer)){Logger(`Replication to ${remotePeer} is already in progress`,LOG_LEVEL_VERBOSE);return}this._replicateToPeers.add(remotePeer);this.dispatchStatus();return await this.requestSynchroniseToPeer(remotePeer)}finally{this._replicateToPeers.delete(remotePeer);this.dispatchStatus()}}else Logger("No peer selected",LOG_LEVEL_VERBOSE)}dispatchReplicationProgress(peerId,info3){this.onReplicationProgress(peerId,info3)}onReplicationProgress(peerId,info3){var _a8,_b5;const stat={peerId,peerName:(null==(_b5=null==(_a8=this.server)?void 0:_a8._knownAdvertisements.get(peerId))?void 0:_b5.name)||peerId,fetching:{max:0,current:0,isActive:!1}};info3&&(stat.fetching={max:info3.maxSeqInBatch,current:info3.lastSeq,isActive:!0});eventHub.emitEvent("p2p-replicator-progress",stat);return!0}onProgressAcknowledged(peerId,info3){var _a8,_b5;const ack={peerId,peerName:(null==(_b5=null==(_a8=this.server)?void 0:_a8._knownAdvertisements.get(peerId))?void 0:_b5.name)||peerId,sending:{max:0,current:0,isActive:!1}};info3&&(ack.sending={max:info3.maxSeqInBatch,current:info3.lastSeq,isActive:!0});eventHub.emitEvent("p2p-replicator-progress",ack);return!0}acknowledgeProgress(remotePeerId,info3){if(!this.server)return;const connection=this.server.getConnection(remotePeerId);try{connection.invokeRemoteFunction("onProgressAcknowledged",[this.server.serverPeerId,info3],500)}catch(ex){Logger("Error while acknowledging the progress",LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE)}}async replicateFrom(remotePeer,showNotice=!1,fromStart=!1){const logLevel=showNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;Logger(`P2P Requesting Authentication to ${remotePeer}`,logLevel,"p2p-replicator");if(!0!==await this.requestAuthenticate(remotePeer)){Logger("Peer rejected the connection",LOG_LEVEL_NOTICE,"p2p-replicator");return{error:new Error("Peer rejected the connection")}}if(!0!==await this.checkTweakValues(remotePeer)){Logger("Tweak values are not matched",LOG_LEVEL_NOTICE,"p2p-replicator");return{error:new Error("Tweak values are not matched")}}Logger(`P2P Replicating from ${remotePeer}`,logLevel,"p2p-replicator");if(this._replicateFromPeers.has(remotePeer)){Logger(`Replication from ${remotePeer} is already in progress`,LOG_LEVEL_NOTICE,"p2p-replicator");return{error:new Error("Replication from this peer is already in progress")}}this._replicateFromPeers.add(remotePeer);this.dispatchStatus();try{if(!this.server)throw new Error("Server is not available");const remoteDB=this.server.getConnection(remotePeer).remoteDB;await replicateShim(this.db,remoteDB,(async(docs,info3)=>{await this._env.processReplicatedDocs(docs);this.dispatchReplicationProgress(remotePeer,info3);this.acknowledgeProgress(remotePeer,info3);this.notifyProgress(remotePeer);Logger(`P2P Replication from ${remotePeer}\n${info3.lastSeq} / ${info3.maxSeqInBatch})`,logLevel,"p2p-replicator")}),{live:!1,rewind:fromStart});this.acknowledgeProgress(remotePeer,void 0);Logger(`P2P Replication from ${remotePeer} has been completed`,logLevel,"p2p-replicator")}catch(e3){Logger("Error while P2P replicating",logLevel,"p2p-replicator");Logger(e3,LOG_LEVEL_VERBOSE);return{error:e3}}finally{this._replicateFromPeers.delete(remotePeer);this.dispatchStatus()}return{ok:!0}}notifyProgress(excludePeerId){if(this._isBroadcasting&&this.server){for(const peer of this.server.knownAdvertisements){const peerId=peer.peerId;peerId!==excludePeerId&&serialized(`notifyProgress-${peerId}`,(async()=>{var _a8,_b5,_c3;if(await(null==(_a8=this.server)?void 0:_a8.isAcceptablePeer(peerId)))try{return await(null==(_c3=this.server)?void 0:_c3.getConnection(peerId).invokeRemoteFunction("onProgress",[null==(_b5=this.server)?void 0:_b5.serverPeerId],0))}catch(e3){Logger(`Error while notifying progress to ${peerId}`,LOG_LEVEL_VERBOSE);Logger(e3,LOG_LEVEL_VERBOSE)}else Logger(`Peer ${peerId} is not acceptable to notify progress`,LOG_LEVEL_VERBOSE)}))}return Promise.resolve()}}async requestBroadcastChanges(peerId){var _a8;return await(null==(_a8=this.server)?void 0:_a8.getConnection(peerId).invokeRemoteFunction("requestBroadcasting",[this.server.serverPeerId],0))}async getRemoteIsBroadcasting(peerId){var _a8;try{return await(null==(_a8=this.server)?void 0:_a8.getConnection(peerId).invokeRemoteFunction("getIsBroadcasting",[],0))}catch(e3){Logger("Error while getting remote is broadcasting",LOG_LEVEL_VERBOSE);Logger(e3,LOG_LEVEL_VERBOSE)}}watchPeer(peerId){this._watchingPeers.add(peerId);this.dispatchStatus()}unwatchPeer(peerId){this._watchingPeers.delete(peerId);this.dispatchStatus()}async onUpdateDatabase(fromPeerId){if(this._watchingPeers.has(fromPeerId)){Logger(`Progress notification from ${fromPeerId}`,LOG_LEVEL_VERBOSE);return await serialized(`onProgress-${fromPeerId}`,(async()=>await this.replicateFrom(fromPeerId)))}return!1}async getRemoteConfig(peerId){if(!this.server){Logger("Server is not available",LOG_LEVEL_NOTICE);return!1}const connection=this.server.getConnection(peerId),encryptedConfig=await connection.invokeRemoteFunction("getAllConfig",[this.server.serverPeerId],0),passphrase=await this.confirm.askString("Passphrase required",$msg("P2P.AskPassphraseForDecrypt"),"something you only know",!0);if(!passphrase||""==passphrase.trim()){Logger("Passphrase is required to decrypt the configuration. The config cannot be decrypted",LOG_LEVEL_NOTICE);return!1}try{return JSON.parse(await decrypt3(encryptedConfig,passphrase))}catch(e3){Logger("Error while decrypting the configuration",LOG_LEVEL_NOTICE);Logger(e3,LOG_LEVEL_VERBOSE);return!1}}async checkTweakValues(peerId){var _a8;if(!this.server){Logger("Server is not available",LOG_LEVEL_NOTICE);return!1}const peerPlatform=null==(_a8=this.server.knownAdvertisements.find((e3=>e3.peerId==peerId)))?void 0:_a8.platform;if(null==peerPlatform){Logger("Peer is not found",LOG_LEVEL_NOTICE);return!1}if("pseudo-replicator"===this.platform)return!0;if("pseudo-replicator"===peerPlatform)return!0;const connection=this.server.getConnection(peerId),tweakValues=await connection.invokeRemoteObjectFunction("getTweakSettings",[this.server.serverPeerId],5e3),thisTweakValues=await this.getTweakSettings("");if(!isObjectDifferent(thisTweakValues,tweakValues))return!0;if(thisTweakValues.passphrase!==tweakValues.passphrase){Logger("Replication cancelled: Passphrase is not matched\nCannot replicate to a remote database until the problem is resolved.",LOG_LEVEL_NOTICE);return!1}Logger("Some mismatched configuration have been detected... Please check settings for efficient replication.",LOG_LEVEL_NOTICE);return!0}async replicateFromCommand(showResult=!1){null===await skipIfDuplicated("replicateFromCommand",(async()=>{var _a8;const logLevel=showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;if(!this._env.settings.P2P_Enabled){Logger($msg("P2P.NotEnabled"),logLevel);return Promise.resolve(!1)}const peers=this._env.settings.P2P_SyncOnReplication.split(",").map((e3=>e3.trim())).filter((e3=>e3));if(0==peers.length){Logger($msg("P2P.NoAutoSyncPeers"),logLevel);return Promise.resolve(!1)}for(const peer of peers){const peerId=null==(_a8=this.knownAdvertisements.find((e3=>e3.name==peer)))?void 0:_a8.peerId;if(peerId){Logger($msg("P2P.SyncStartedWith",{name:peer}),logLevel);await this.sync(peerId,showResult)}else Logger($msg("P2P.SeemsOffline",{name:peer}),logLevel)}Logger($msg("P2P.SyncCompleted"),logLevel);return Promise.resolve(!0)}))&&Logger($msg("P2P.SyncAlreadyRunning"),LOG_LEVEL_NOTICE)}disconnectFromServer(){const connections=getRelaySockets(),sockets=Object.entries(connections);pauseRelayReconnection();sockets.forEach((([,s2])=>{s2.close();s2.onclose=()=>{var _a8;null==(_a8=this.server)||_a8.dispatchConnectionStatus()}}));this.pauseServe()}async pauseServe(){var _a8,_b5;await(null==(_a8=this.server)?void 0:_a8.close());await(null==(_b5=this.server)?void 0:_b5.dispatchConnectionStatus())}allowReconnection(){resumeRelayReconnection()}};P2PLogCollector=class{constructor(){this.p2pReplicationResult=new Map;this.p2pReplicationLine=reactiveSource("");eventHub.onEvent(EVENT_ADVERTISEMENT_RECEIVED,(data=>{this.p2pReplicationResult.set(data.peerId,{peerId:data.peerId,peerName:data.name,fetching:{current:0,max:0,isActive:!1},sending:{current:0,max:0,isActive:!1}});this.updateP2PReplicationLine()}));eventHub.onEvent("p2p-connected",(()=>{this.p2pReplicationResult.clear();this.updateP2PReplicationLine()}));eventHub.onEvent("p2p-disconnected",(()=>{this.p2pReplicationResult.clear();this.updateP2PReplicationLine()}));eventHub.onEvent(EVENT_DEVICE_LEAVED,(peerId=>{this.p2pReplicationResult.delete(peerId);this.updateP2PReplicationLine()}));eventHub.onEvent("p2p-replicator-progress",(data=>{const prev=this.p2pReplicationResult.get(data.peerId)||{peerId:data.peerId,peerName:data.peerName,fetching:{current:0,max:0,isActive:!1},sending:{current:0,max:0,isActive:!1}};"fetching"in data&&(data.fetching.isActive?prev.fetching=data.fetching:prev.fetching.isActive=!1);"sending"in data&&(data.sending.isActive?prev.sending=data.sending:prev.sending.isActive=!1);this.p2pReplicationResult.set(data.peerId,prev);this.updateP2PReplicationLine()}))}updateP2PReplicationLine(){const p2pReplicationResultX=[...this.p2pReplicationResult.values()].sort(((a2,b3)=>a2.peerId.localeCompare(b3.peerId))),renderProgress=(current,max3)=>current==max3?`${current}`:`${current} (${max3})`,line=p2pReplicationResultX.map((e3=>`${e3.fetching.isActive||e3.sending.isActive?"⚡":"💤"} ${e3.peerName} ↑ ${renderProgress(e3.sending.current,e3.sending.max)} ↓ ${renderProgress(e3.fetching.current,e3.fetching.max)} `)).join("\n");this.p2pReplicationLine.value=line}};recentLogEntries=reactiveSource([]);(function setGlobalLogFunction(logger2){_logger=logger2})(((message,level,key3)=>{const entry={message:message instanceof Error?new LiveSyncError("[Error Logged]: "+message.message,{cause:message}):message,level,key:key3};recentLogEntries.value=[...recentLogEntries.value,entry]}));recentLogs=[];ModuleLog=class extends AbstractObsidianModule{constructor(){super(...arguments);this.registerView=this.plugin.registerView.bind(this.plugin);this.statusLog=reactiveSource("");this.activeFileStatus=reactiveSource("");this.notifies={};this.p2pLogCollector=new P2PLogCollector;this.nextFrameQueue=void 0;this.logLines=[]}observeForLogs(){function padLeftSpComputed(numI,mark){const formatted=reactiveSource("");let timer,maxLen=1;numI.onChanged((numX=>{const num=numX.value,numLen=`${Math.abs(num)}`.length+1;maxLen=maxLen<numLen?numLen:maxLen;timer&&clearTimeout(timer);0==num&&(timer=setTimeout((()=>{formatted.value="";maxLen=1}),3e3));formatted.value=` ${mark}${`${padSpaces}${num}`.slice(-maxLen)}`}));return computed((()=>formatted.value))}const padSpaces="".repeat(10),labelReplication=padLeftSpComputed(this.core.replicationResultCount,"📥"),labelDBCount=padLeftSpComputed(this.core.databaseQueueCount,"📄"),labelStorageCount=padLeftSpComputed(this.core.storageApplyingCount,"💾"),labelChunkCount=padLeftSpComputed(collectingChunks,"🧩"),labelPluginScanCount=padLeftSpComputed(pluginScanningCount,"🔌"),labelConflictProcessCount=padLeftSpComputed(this.core.conflictProcessQueueCount,"🔩"),labelHiddenFilesCount=padLeftSpComputed(reactive((()=>hiddenFilesEventCount.value-hiddenFilesProcessingCount.value)),"⚙️"),queueCountLabelX=reactive((()=>`${labelReplication()}${labelDBCount()}${labelStorageCount()}${labelChunkCount()}${labelPluginScanCount()}${labelHiddenFilesCount()}${labelConflictProcessCount()}`)),queueCountLabel=()=>queueCountLabelX.value,requestingStatLabel=computed((()=>0!=this.core.requestCount.value-this.core.responseCount.value?"📲 ":"")),replicationStatLabel=computed((()=>{const e3=this.core.replicationStat.value,sent=e3.sent,arrived=e3.arrived,maxPullSeq=e3.maxPullSeq,maxPushSeq=e3.maxPushSeq,lastSyncPullSeq=e3.lastSyncPullSeq,lastSyncPushSeq=e3.lastSyncPushSeq;let pushLast="",pullLast="",w2="";const labels={CONNECTED:"⚡",JOURNAL_SEND:"📦↑",JOURNAL_RECEIVE:"📦↓"};switch(e3.syncStatus){case"CLOSED":case"COMPLETED":case"NOT_CONNECTED":w2="⏹";break;case"STARTED":w2="🌀";break;case"PAUSED":w2="💤";break;case"CONNECTED":case"JOURNAL_SEND":case"JOURNAL_RECEIVE":w2=labels[e3.syncStatus]||"⚡";pushLast=0==lastSyncPushSeq?"":lastSyncPushSeq>=maxPushSeq?" (LIVE)":` (${maxPushSeq-lastSyncPushSeq})`;pullLast=0==lastSyncPullSeq?"":lastSyncPullSeq>=maxPullSeq?" (LIVE)":` (${maxPullSeq-lastSyncPullSeq})`;break;case"ERRORED":w2="⚠";break;default:w2="?"}return{w:w2,sent,pushLast,arrived,pullLast}})),labelProc=padLeftSpComputed(this.core.processing,"⏳"),labelPend=padLeftSpComputed(this.core.totalQueued,"🛫"),labelInBatchDelay=padLeftSpComputed(this.core.batched,"📬"),waitingLabel=computed((()=>`${labelProc()}${labelPend()}${labelInBatchDelay()}`)),statusLineLabel=computed((()=>{const{w:w2,sent,pushLast,arrived,pullLast}=replicationStatLabel(),queued=queueCountLabel(),waiting=waitingLabel(),networkActivity=requestingStatLabel(),p2p=this.p2pLogCollector.p2pReplicationLine.value;return{message:`${networkActivity}Sync: ${w2} ↑ ${sent}${pushLast} ↓ ${arrived}${pullLast}${waiting}${queued}${""==p2p?"":"\n"+p2p}`}})),statusBarLabels=reactive((()=>{const scheduleMessage=this.services.appLifecycle.isReloadingScheduled()?"WARNING! RESTARTING OBSIDIAN IS SCHEDULED!\n":"",{message}=statusLineLabel(),fileStatus=this.activeFileStatus.value,status=scheduleMessage+this.statusLog.value;return{message:`${message}${fileStatus&&this.settings.hideFileWarningNotice?" ⛔ SKIP":""}`,status}}));this.statusBarLabels=statusBarLabels;const applyToDisplay=throttle((label2=>{this.applyStatusBarText()}),20);statusBarLabels.onChanged((label2=>applyToDisplay(label2.value)));this.activeFileStatus.onChanged((()=>this.updateMessageArea()))}_everyOnload(){eventHub.onEvent("leaf-active-changed",(()=>this.onActiveLeafChange()));eventHub.onceEvent(EVENT_LAYOUT_READY,(()=>this.onActiveLeafChange()));eventHub.onEvent("on-unresolved-error",(()=>this.updateMessageArea()));return Promise.resolve(!0)}adjustStatusDivPosition(){const mdv=this.app.workspace.getMostRecentLeaf();if(mdv&&this.statusDiv){this.statusDiv.remove();const container=mdv.view.containerEl;container.insertBefore(this.statusDiv,container.lastChild)}}async getActiveFileStatus(){const reason=[],reasonWarn=[],thisFile=this.app.workspace.getActiveFile();if(!thisFile)return"";if(isValidPath(thisFile.path)){const validOnWindows=isValidFilenameInWidows(thisFile.name),validOnDarwin=isValidFilenameInDarwin(thisFile.name),validOnAndroid=isValidFilenameInAndroid(thisFile.name),labels=[];validOnWindows||labels.push("🪟");validOnDarwin||labels.push("🍎");validOnAndroid||labels.push("🤖");labels.length>0&&reasonWarn.push("Some platforms may be unable to process this file correctly: "+labels.join(" "))}else reason.push("This file has an invalid path under the current settings");this.services.setting.shouldCheckCaseInsensitively()&&this.core.storageAccess.getFiles().map((e3=>e3.path)).filter((e3=>e3.toLowerCase()==thisFile.path.toLowerCase())).length>1&&reason.push("There are multiple files with the same name (case-insensitive match)");await this.services.vault.isTargetFile(thisFile.path)||reason.push("This file is ignored by the ignore rules");this.services.vault.isFileSizeTooLarge(thisFile.stat.size)&&reason.push("This file size exceeds the configured limit");return[reason.length>0?"Not synchronised: "+reason.join(", "):"",reasonWarn.length>0?"Warning: "+reasonWarn.join(", "):""].filter((e3=>e3)).join("\n")}async setFileStatus(){const fileStatus=await this.getActiveFileStatus();this.activeFileStatus.value=fileStatus}async updateMessageArea(){if(this.messageArea){const messageLines=[],fileStatus=this.activeFileStatus.value;fileStatus&&!this.settings.hideFileWarningNotice&&messageLines.push(fileStatus);const messages=(await this.services.appLifecycle.getUnresolvedMessages()).flat().filter((e3=>e3));messageLines.push(...messages);this.messageArea.innerText=messageLines.map((e3=>`⚠️ ${e3}`)).join("\n")}}onActiveLeafChange(){fireAndForget((async()=>{this.adjustStatusDivPosition();await this.setFileStatus()}))}applyStatusBarText(){if(!this.nextFrameQueue){this.nextFrameQueue=requestAnimationFrame((()=>{var _a8,_b5,_c3;this.nextFrameQueue=void 0;const{message,status}=this.statusBarLabels.value,newMsg=message;let newLog=(null==(_a8=this.settings)?void 0:_a8.showOnlyIconsOnEditor)?"":status;const moduleTagEnd=newLog.indexOf("]");-1!=moduleTagEnd&&(newLog=newLog.substring(moduleTagEnd+2));null==(_b5=this.statusBar)||_b5.setText(newMsg.split("\n")[0]);if((null==(_c3=this.settings)?void 0:_c3.showStatusOnEditor)&&this.statusDiv){if(this.settings.showLongerLogInsideEditor){const now3=(new Date).getTime();this.logLines=this.logLines.filter((e3=>e3.ttl>now3));const minimumNext=this.logLines.reduce(((a2,b3)=>a2<b3.ttl?a2:b3.ttl),Number.MAX_SAFE_INTEGER);this.logLines.length>0&&setTimeout((()=>this.applyStatusBarText()),minimumNext-now3);const recentLogs2=this.logLines.map((e3=>e3.message)).reverse().join("\n");isDirty("recentLogs",recentLogs2)&&(this.logHistory.innerText=recentLogs2)}isDirty("newMsg",newMsg)&&(this.statusLine.innerText=newMsg);isDirty("newLog",newLog)&&(this.logMessage.innerText=newLog)}}));scheduleTask("log-hide",3e3,(()=>{this.statusLog.value=""}))}}_allStartOnUnload(){var _a8;this.statusDiv&&this.statusDiv.remove();null==(_a8=document.querySelectorAll(".livesync-status"))||_a8.forEach((e3=>e3.remove()));return Promise.resolve(!0)}_everyOnloadStart(){(0,import_obsidian.addIcon)("view-log",'<g transform="matrix(1.28 0 0 1.28 -131 -411)" fill="currentColor" fill-rule="evenodd">\n <path d="m103 330h76v12h-76z"/>\n <path d="m106 346v44h70v-44zm45 16h-20v-8h20z"/>\n </g>');this.addRibbonIcon("view-log",$msg("moduleLog.showLog"),(()=>{this.services.API.showWindow("log-log")})).addClass("livesync-ribbon-showlog");this.addCommand({id:"view-log",name:"Show log",callback:()=>{this.services.API.showWindow("log-log")}});this.registerView("log-log",(leaf=>new LogPaneView(leaf,this.plugin)));return Promise.resolve(!0)}_everyOnloadAfterLoadSettings(){var _a8;recentLogEntries.onChanged((entries2=>{if(0===entries2.value.length)return;const newEntries=[...entries2.value];recentLogEntries.value=[];newEntries.forEach((e3=>this.__addLog(e3.message,e3.level,e3.key)))}));eventHub.onEvent("file-renamed",(data=>{this.setFileStatus()}));document.querySelectorAll(".livesync-status").forEach((e3=>e3.remove()));this.observeForLogs();this.statusDiv=this.app.workspace.containerEl.createDiv({cls:"livesync-status"});this.statusLine=this.statusDiv.createDiv({cls:"livesync-status-statusline"});this.messageArea=this.statusDiv.createDiv({cls:"livesync-status-messagearea"});this.logMessage=this.statusDiv.createDiv({cls:"livesync-status-logmessage"});this.logHistory=this.statusDiv.createDiv({cls:"livesync-status-loghistory"});eventHub.onEvent(EVENT_LAYOUT_READY,(()=>this.adjustStatusDivPosition()));if(null==(_a8=this.settings)?void 0:_a8.showStatusOnStatusbar){this.statusBar=this.core.addStatusBarItem();this.statusBar.addClass("syncstatusbar")}this.adjustStatusDivPosition();return Promise.resolve(!0)}writeLogToTheFile(now3,vaultName,newMessage){fireAndForget((()=>serialized("writeLog",(async()=>{const time=now3.toISOString().split("T")[0],logDate=`${PREFIXMD_LOGFILE}${time}.md`;await this.core.storageAccess.isExists(normalizePath(logDate))||await this.core.storageAccess.appendHiddenFile(normalizePath(logDate),"```\n");await this.core.storageAccess.appendHiddenFile(normalizePath(logDate),vaultName+":"+newMessage+"\n")}))))}__addLog(message,level=LOG_LEVEL_INFO,key3=""){var _a8,_b5,_c3,_d2,_e2,_f;if(level==LOG_LEVEL_DEBUG)return;if(level<=LOG_LEVEL_INFO&&this.settings&&this.settings.lessInformationInLog)return;if(this.settings&&!this.settings.showVerboseLog&&level==LOG_LEVEL_VERBOSE)return;const vaultName=this.services.vault.getVaultName(),now3=new Date,timestamp=now3.toLocaleString();let errorInfo="";if(message instanceof Error)if(message instanceof LiveSyncError)errorInfo=`${null==(_a8=message.cause)?void 0:_a8.name}:${null==(_b5=message.cause)?void 0:_b5.message}\n[StackTrace]: ${message.stack}\n[CausedBy]: ${null==(_c3=message.cause)?void 0:_c3.stack}`;else{const thisStack=(new Error).stack;errorInfo=`${message.name}:${message.message}\n[StackTrace]: ${message.stack}\n[LogCallStack]: ${thisStack}`}const messageContent="string"==typeof message?message:message instanceof Error?`${errorInfo}`:JSON.stringify(message,null,2),newMessage=timestamp+"->"+messageContent;message instanceof Error?console.error(vaultName+":"+newMessage):level>=LOG_LEVEL_INFO?console.log(vaultName+":"+newMessage):console.debug(vaultName+":"+newMessage);(null==(_d2=this.settings)?void 0:_d2.showOnlyIconsOnEditor)||(this.statusLog.value=messageContent);(null==(_e2=this.settings)?void 0:_e2.writeLogToTheFile)&&this.writeLogToTheFile(now3,vaultName,newMessage);addLog(newMessage);this.logLines.push({ttl:now3.getTime()+3e3,message:newMessage});if(level>=LOG_LEVEL_NOTICE){key3||(key3=messageContent);if(key3 in this.notifies){(null==(_f=this.notifies[key3].notice.noticeEl)?void 0:_f.isShown())||(this.notifies[key3].notice=new import_obsidian.Notice(messageContent,0));cancelTask(`notify-${key3}`);if(key3==messageContent){this.notifies[key3].count++;this.notifies[key3].notice.setMessage(`(${this.notifies[key3].count}):${messageContent}`)}else this.notifies[key3].notice.setMessage(`${messageContent}`)}else{const notify=new import_obsidian.Notice(messageContent,0);this.notifies[key3]={count:0,notice:notify}}const timeout=5e3;key3.startsWith("keepalive-")&&-1===messageContent.indexOf("")||scheduleTask(`notify-${key3}`,timeout,(()=>{const notify=this.notifies[key3].notice;delete this.notifies[key3];try{notify.hide()}catch(e3){}}))}}onBindFunction(core,services){services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this));services.appLifecycle.handleOnSettingLoaded(this._everyOnloadAfterLoadSettings.bind(this));services.appLifecycle.handleOnLoaded(this._everyOnload.bind(this));services.appLifecycle.handleOnBeforeUnload(this._allStartOnUnload.bind(this))}};noticeIndex=0;LiveSyncCommands=class{constructor(plugin3){this._log=(msg,level=LOG_LEVEL_INFO,key3)=>{"string"==typeof msg&&level!==LOG_LEVEL_NOTICE&&(msg=`[${this.constructor.name}] ${msg}`);Logger(msg,level,key3)};this._verbose=(msg,key3)=>{this._log(msg,LOG_LEVEL_VERBOSE,key3)};this._info=(msg,key3)=>{this._log(msg,LOG_LEVEL_INFO,key3)};this._notice=(msg,key3)=>{this._log(msg,LOG_LEVEL_NOTICE,key3)};this._progress=(prefix="",level=LOG_LEVEL_NOTICE)=>{const key3="keepalive-progress-"+noticeIndex++;return{log:msg=>{this._log(prefix+msg,level,key3)},once:msg=>{this._log(prefix+msg,level)},done:(msg="Done")=>{this._log(prefix+msg+"",level,key3)}}};this._debug=(msg,key3)=>{this._log(msg,LOG_LEVEL_VERBOSE,key3)};this.plugin=plugin3;this.onBindFunction(plugin3,plugin3.services);__$checkInstanceBinding(this)}get app(){return this.plugin.app}get settings(){return this.plugin.settings}get localDatabase(){return this.plugin.localDatabase}get services(){return this.plugin.services}async path2id(filename,prefix){return await this.services.path.path2id(filename,prefix)}getPath(entry){return getPath2(entry)}_isMainReady(){return this.plugin.services.appLifecycle.isReady()}_isMainSuspended(){return this.services.appLifecycle.isSuspended()}_isDatabaseReady(){return this.services.database.isDatabaseReady()}onBindFunction(core,services){}};root_12=from_html('<div class="message svelte-1ah3y1j">Just for a minute, please!</div> <div class="buttons svelte-1ah3y1j"><button class="svelte-1ah3y1j">Dismiss</button></div>',1);root_4=from_html('<label><input type="radio" name="disp" class="sls-setting-tab svelte-1ah3y1j"/> <div class="sls-setting-menu-btn svelte-1ah3y1j"> </div></label>');root_6=from_html("<span> </span>");root_5=from_html('<div class="op-scrollable json-source svelte-1ah3y1j"></div>');root_10=from_html('<button class="svelte-1ah3y1j">Cancel</button>');root_2=from_html('<div class="options svelte-1ah3y1j"></div> <!> <div class="infos svelte-1ah3y1j"><table class="svelte-1ah3y1j"><tbody class="svelte-1ah3y1j"><tr class="svelte-1ah3y1j"><th class="svelte-1ah3y1j"> </th><td class="svelte-1ah3y1j"><!> </td><td class="svelte-1ah3y1j"> </td></tr><tr class="svelte-1ah3y1j"><th class="svelte-1ah3y1j"> </th><td class="svelte-1ah3y1j"><!> </td><td class="svelte-1ah3y1j"> </td></tr></tbody></table></div> <div class="buttons svelte-1ah3y1j"><!> <button class="svelte-1ah3y1j">Apply</button></div>',1);root2=from_html('<h2 class="svelte-1ah3y1j"> </h2> <!>',1);$$css2={hash:"svelte-1ah3y1j",code:".spacer.svelte-1ah3y1j {flex-grow:1;}.infos.svelte-1ah3y1j {display:flex;justify-content:space-between;margin:4px 0.5em;}.deleted.svelte-1ah3y1j {text-decoration:line-through;}.svelte-1ah3y1j {box-sizing:border-box;}.scroller.svelte-1ah3y1j {display:flex;flex-direction:column;overflow-y:scroll;max-height:60vh;user-select:text;-webkit-user-select:text;}.json-source.svelte-1ah3y1j {white-space:pre;height:auto;overflow:auto;min-height:var(--font-ui-medium);flex-grow:1;}"};delegate(["click"]);JsonResolveModal=class extends import_obsidian.Modal{constructor(app,filename,docs,callback,nameA,nameB,defaultSelect,keepOrder,hideLocal,title="Conflicted Setting"){super(app);this.title="Conflicted Setting";this.callback=callback;this.filename=filename;this.docs=docs;this.nameA=nameA||"";this.nameB=nameB||"";this.keepOrder=keepOrder||!1;this.defaultSelect=defaultSelect||"";this.title=title;this.hideLocal=null!=hideLocal&&hideLocal;waitForSignal(`cancel-internal-conflict:${filename}`).then((()=>this.close()))}async UICallback(keepRev,mergedStr){this.callback&&await this.callback(keepRev,mergedStr);this.close();this.callback=void 0}onOpen(){const{contentEl}=this;this.titleEl.setText(this.title);contentEl.empty();null==this.component&&(this.component=mount(JsonResolvePane,{target:contentEl,props:{docs:this.docs,filename:this.filename,nameA:this.nameA,nameB:this.nameB,defaultSelect:this.defaultSelect,keepOrder:this.keepOrder,hideLocal:this.hideLocal,callback:(keepRev,mergedStr)=>this.UICallback(keepRev,mergedStr)}}))}onClose(){const{contentEl}=this;contentEl.empty();null!=this.callback&&this.callback(void 0);if(null!=this.component){unmount(this.component);this.component=void 0}}};PaceMaker=class{constructor(interval){Object.defineProperty(this,"_interval",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_minimumNext",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this._interval=interval}changeInterval(interval){if(interval!==this._interval){this._interval=interval;this._minimumNext=void 0}}mark(now3=Date.now()){void 0===this._minimumNext?this._minimumNext=now3+this._interval:this._minimumNext=Math.max(this._minimumNext+this._interval,now3+this._interval)}_getPaced(doMark){const now3=Date.now(),prevMinimum=this._minimumNext;doMark&&this.mark(now3);if(void 0!==prevMinimum){const shouldWait=prevMinimum-now3;if(shouldWait>0)return new Promise((resolve=>setTimeout((()=>{resolve()}),shouldWait)))}return Promise.resolve()}get paced(){return this._getPaced(!0)}get pacedSinceMark(){return this._getPaced(!1)}};NOT_AVAILABLE=Symbol("NotAvailable");READY_PICK_SIGNAL=Symbol("lockReady");READY_POST_SIGNAL=Symbol("lockFull");DISPOSE_ERROR="Inbox has been disposed";SyncInbox=class{constructor(capacity){Object.defineProperty(this,"_capacity",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_buffer",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_writeIdx",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_readIdx",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_wrapAroundCount",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_isDisposed",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_disposedPromise",{enumerable:!0,configurable:!0,writable:!0,value:promiseWithResolvers()});if(capacity<=0)throw new Error("Capacity must be greater than 0");this._capacity=~~capacity;let i2=256;for(;i2<capacity+1;)i2*=2;i2--;this._wrapAroundCount=i2;this._buffer=new Array(i2);this._writeIdx=0;this._readIdx=0}get size(){return this._writeIdx-this._readIdx}get free(){return this._capacity-this.size}get isRunningOut(){return this._writeIdx==this._readIdx}get isFull(){return 0==this.free}get isReady(){return this.free>0}get isDisposed(){return this._isDisposed}get onDisposed(){return this._disposedPromise.promise}__fixIdx(){if(this._readIdx>this._wrapAroundCount){this._readIdx=this._readIdx&this._wrapAroundCount;this._writeIdx=this._writeIdx&this._wrapAroundCount}}get state(){return{processed:this._writeIdx,size:this.size,free:this.free,isFull:this.isFull,isRunningOut:this.isRunningOut,isReady:this.isReady}}dispose(){this._readIdx=0;this._writeIdx=0;this._capacity=0;this._buffer.length=1;this._buffer[0]=void 0;this._wrapAroundCount=1;this._isDisposed=!0;this._disposedPromise.resolve()}__onPosted(){this.__onProgress()}__onPicked(){this.__onProgress()}__onProgress(){this.__fixIdx()}tryPost(item){if(this.isFull)return!1;this._writeIdx++;this._buffer[this._writeIdx&this._wrapAroundCount]=item;this.__onPosted();return!0}tryCancelPost(){if(0==this.size)return NOT_AVAILABLE;const pointingIdx=this._writeIdx&this._wrapAroundCount,item=this._buffer[pointingIdx];this._buffer[pointingIdx]=void 0;this._writeIdx--;this.__fixIdx();return item}tryPick(){if(this.isRunningOut)return NOT_AVAILABLE;this._readIdx++;const pointingIdx=this._readIdx&this._wrapAroundCount,item=this._buffer[pointingIdx];this._buffer[pointingIdx]=void 0;this.__onPicked();return item}};Inbox=class extends SyncInbox{constructor(capacity){super(capacity);Object.defineProperty(this,"_lockFull",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_lockReady",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}async _waitForFree(){for(;0==this.free;){this._lockFull||(this._lockFull=promiseWithResolvers());return await this._lockFull.promise}return READY_POST_SIGNAL}_notifyFree(){var _a8;null==(_a8=this._lockFull)||_a8.resolve(READY_POST_SIGNAL);this._lockFull=void 0}async _waitForReady(){for(;this.isRunningOut;){this._lockReady||(this._lockReady=promiseWithResolvers());return await this._lockReady.promise}return READY_PICK_SIGNAL}_notifyReady(){var _a8;null==(_a8=this._lockReady)||_a8.resolve(READY_PICK_SIGNAL);this._lockReady=void 0}__onPosted(){super.__onPosted();this._notifyReady()}__onPicked(){super.__onPicked();this._notifyFree()}dispose(){super.dispose();if(this._lockFull){this._lockFull.reject(new Error(DISPOSE_ERROR));this._lockFull=void 0}if(this._lockReady){this._lockReady.reject(new Error(DISPOSE_ERROR));this._lockReady=void 0}}async post(item,timeout,cancellation){if(this._isDisposed)throw new Error(DISPOSE_ERROR);do{if(cancellation&&cancellation.length>0&&await isSomeResolved(cancellation))return!1;if(this.tryPost(item))return!0;let p4;const tasks3=[this._waitForFree(),...timeout?[(p4=cancelableDelay(timeout)).promise]:[],...cancellation||[]],r4=await Promise.race(tasks3);null==p4||p4.cancel();if(r4!==READY_POST_SIGNAL)return!1}while(!this._isDisposed);return!1}async pick(timeout,cancellation){if(this._isDisposed)throw new Error(DISPOSE_ERROR);do{if(cancellation&&cancellation.length>0&&await isSomeResolved(cancellation))return NOT_AVAILABLE;const item=this.tryPick();if(item!==NOT_AVAILABLE)return item;let p4;const tasks3=[this._waitForReady(),...timeout?[(p4=cancelableDelay(timeout)).promise]:[],...cancellation||[]],r4=await Promise.race(tasks3);null==p4||p4.cancel();if(r4!==READY_PICK_SIGNAL)return NOT_AVAILABLE}while(!this.isDisposed);return NOT_AVAILABLE}};(function(ClerkState2){ClerkState2.IDLE="idle";ClerkState2.DISPOSED="disposed";ClerkState2.WORKING="working";ClerkState2.STALLED="not-started"})(ClerkState||(ClerkState={}));SENTINEL_FINISHED=Symbol("finished");SENTINEL_FLUSH=Symbol("flush");ClerkBase=class{get state(){return this._state}constructor(params){Object.defineProperty(this,"_inbox",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_state",{enumerable:!0,configurable:!0,writable:!0,value:ClerkState.STALLED});Object.defineProperty(this,"_totalProcessed",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_totalSuccess",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_totalFailed",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_totalFetched",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_disposed",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_disposePromise",{enumerable:!0,configurable:!0,writable:!0,value:promiseWithResolvers()});Object.defineProperty(this,"_onProgress",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const{name,assigned}=params;this._inbox=assigned;this._name=null!=name?name:this.constructor.name;yieldMicrotask().then((()=>this._mainLoop()));this._inbox.onDisposed.then((()=>this.dispose()))}get stateDetail(){const hasStarted=0!=this._totalFetched,hasAnyUnprocessed=this._totalFetched!=this._totalProcessed,isBusy=0!=this._inbox.state.size||hasAnyUnprocessed;return{totalFetched:this._totalFetched,inboxDetail:this._inbox.state,totalProcessed:this._totalProcessed,state:this._state,hasStarted,isBusy}}onProgress(){var _a8;try{null==(_a8=this._onProgress)||_a8.call(this,this.stateDetail)}catch(e3){}}setOnProgress(callback){this._onProgress=callback}async _mainLoop(){var _a8;this._state=ClerkState.STALLED;this.onProgress();await yieldMicrotask();do{this._state=ClerkState.IDLE;this.onProgress();try{const item=await this._inbox.pick(void 0,[this._disposePromise.promise]);if(item===SENTINEL_FLUSH||item===SENTINEL_FINISHED){await(null==(_a8=this._onSentinel)?void 0:_a8.call(this,item));continue}if(item===NOT_AVAILABLE){if(this._inbox.isDisposed){this._state=ClerkState.DISPOSED;break}continue}this._totalFetched++;this._state=ClerkState.WORKING;this.onProgress();try{await this._onPick(item);this._totalSuccess++}catch(ex){this._totalFailed++;Logger("Error on processing job on clerk");Logger(ex,LOG_LEVEL_VERBOSE)}this._totalProcessed++;this.onProgress()}catch(ex){if(ex instanceof Error&&ex.message!==DISPOSE_ERROR){Logger("Error on picking item on clerk");Logger(ex,LOG_LEVEL_VERBOSE)}}}while(!this._inbox.isDisposed&&!this._disposed);this._state=ClerkState.IDLE;this._disposed?this._state=ClerkState.DISPOSED:this.dispose();this.onProgress()}dispose(){this._disposePromise.resolve();this._disposed=!0;this._state=ClerkState.DISPOSED}get onDisposed(){return this._disposePromise.promise}};Clerk=class extends ClerkBase{async _onPick(item){return await this._job(item)}constructor(params){super(params);Object.defineProperty(this,"_job",{enumerable:!0,configurable:!0,writable:!0,value:void 0});this._job=params.job}};ClerkGroup=class{constructor(params){var _a8;Object.defineProperty(this,"_clerks",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_nameBase",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_assigned",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_hiredCount",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_job",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_instantiate",{enumerable:!0,configurable:!0,writable:!0,value:void 0});const{assigned,job,instantiate,initialMemberCount}=params;this._assigned=assigned;this._instantiate=instantiate;this._job=job;this._nameBase=null!=(_a8=params.name)?_a8:this.constructor.name;this._clerks=[];for(let i2=0;i2<initialMemberCount;i2++)this.hireMember({assigned,job})}hireMember(params){const name=`${this._nameBase}-${this._hiredCount++}`,clerk=this._instantiate({name,assigned:params.assigned,job:params.job});this._clerks.push(clerk)}fireMember(){const clerk=this._clerks.pop();null==clerk||clerk.dispose()}adjustMemberCount(count){const diff=count-this._clerks.length;if(diff>0)for(let i2=0;i2<diff;i2++)this.hireMember({assigned:this._assigned,job:this._job});else if(diff<0)for(let i2=0;i2<-diff;i2++)this.fireMember()}get stateDetail(){const states=this._clerks.map((clerk=>clerk.stateDetail)),totalFetched=states.reduce(((acc,state2)=>acc+state2.totalFetched),0),totalProcessed=states.reduce(((acc,state2)=>acc+state2.totalProcessed),0),isBusy=states.some((state2=>state2.isBusy)),hasStarted=states.some((state2=>state2.hasStarted));return{totalFetched,totalProcessed,inboxDetail:this._assigned.state,isBusy,hasStarted,state:ClerkState.IDLE}}get freeMembers(){return this._clerks.filter((clerk=>clerk.state===ClerkState.IDLE)).length}dispose(){this._clerks.forEach((clerk=>clerk.dispose()))}};Notifier=class{constructor(){Object.defineProperty(this,"_p",{enumerable:!0,configurable:!0,writable:!0,value:promiseWithResolvers()});Object.defineProperty(this,"isUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1})}notify(){if(this.isUsed){this.isUsed=!1;this._p.promise.finally(noop);this._p.resolve();this._p=promiseWithResolvers()}}get nextNotify(){this.isUsed=!0;return this._p.promise}};allRunningProcessors=new Set([]);QueueProcessor=class{get nowProcessing(){return this.processingEntities}get totalNowProcessing(){var _a8;return this.nowProcessing+((null==(_a8=this._pipeTo)?void 0:_a8.totalNowProcessing)||0)}get remaining(){return this._queue.length+this.processingEntities+this.waitingEntries}get totalRemaining(){var _a8;return this.remaining+((null==(_a8=this._pipeTo)?void 0:_a8.totalRemaining)||0)}updateStatus(setFunc){setFunc();this._updateReactiveSource()}suspend(){this._isSuspended=!0;this._hub.emitEvent("tickSuspended");return this}resume(){this._isSuspended=!1;this._hub.emitEvent("tickResumed");return this}resumePipeLine(){var _a8;null==(_a8=this._pipeTo)||_a8.resumePipeLine();this.resume();return this}startPipeline(){this.root.resumePipeLine();return this}get root(){return void 0===this._root?this:this._root}_initEventHub(){this._hub.onEvent("tickResumed",(()=>this._run()))}async _waitFor(keys3,timeout){const items=keys3.map((key3=>{const p4=promiseWithResolvers(),releaser=this._hub.onEvent(key3,(()=>{p4.resolve(key3)}));p4.promise=p4.promise.finally((()=>{releaser()}));return p4})),timer=timeout?cancelableDelay(timeout):void 0,tasks3=[...items.map((i2=>i2.promise)),...timer?[timer.promise]:[]],ret=await Promise.race(tasks3);items.forEach((i2=>i2.resolve(void 0)));return ret}_triggerTickDelay(){this._delayTimer||(this._delayTimer=setTimeout((()=>{this._hub.emitEvent("tickDelayTimeout");this._delayTimer=void 0})))}_clearTickDelay(){if(this._delayTimer){clearTimeout(this._delayTimer);this._delayTimer=void 0}}_notifyIfIdle(){return this.root.__notifyIfIdle()}__notifyIfIdle(){0!=this._processCount||this._canCollectBatch()||this._hub.emitEvent("idle");this._pipeTo&&this._pipeTo.__notifyIfIdle()}_onTick(){if(this._canCollectBatch())if(this._nextProcessNeedsImmediate){this._clearTickDelay();this._nextProcessNeedsImmediate=!1;this._hub.emitEvent("tickImmediate")}else if(this._queue.length>this.yieldThreshold){this._clearTickDelay();this._hub.emitEvent("yielded")}else{if(!this.delay){this._clearTickDelay();this._hub.emitEvent("tickDelayTimeout");return}this._delayTimer||this._triggerTickDelay()}else{this._notifyIfIdle();this._clearTickDelay();this._hub.emitEvent("tickEmpty")}}constructor(processor,params,items,enqueueProcessor){var _a8,_b5,_c3,_d2,_e2,_f,_g;Object.defineProperty(this,"_queue",{enumerable:!0,configurable:!0,writable:!0,value:[]});Object.defineProperty(this,"_processor",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_enqueueProcessor",{enumerable:!0,configurable:!0,writable:!0,value:(queue2,entity)=>(queue2.push(entity),queue2)});Object.defineProperty(this,"_isSuspended",{enumerable:!0,configurable:!0,writable:!0,value:!0});Object.defineProperty(this,"_nextProcessNeedsImmediate",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_pipeTo",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_root",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_remainingReactiveSource",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_totalRemainingReactiveSource",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_processingEntitiesReactiveSource",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_keepResultUntilDownstreamConnected",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_keptResult",{enumerable:!0,configurable:!0,writable:!0,value:[]});Object.defineProperty(this,"_runOnUpdateBatch",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}});Object.defineProperty(this,"concurrentLimit",{enumerable:!0,configurable:!0,writable:!0,value:1});Object.defineProperty(this,"batchSize",{enumerable:!0,configurable:!0,writable:!0,value:1});Object.defineProperty(this,"yieldThreshold",{enumerable:!0,configurable:!0,writable:!0,value:1});Object.defineProperty(this,"delay",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"maintainDelay",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"interval",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"processingEntities",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"waitingEntries",{enumerable:!0,configurable:!0,writable:!0,value:0});Object.defineProperty(this,"_hub",{enumerable:!0,configurable:!0,writable:!0,value:new EventHub});Object.defineProperty(this,"_delayTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_intervalPaceMaker",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_processingBatches",{enumerable:!0,configurable:!0,writable:!0,value:new Set});Object.defineProperty(this,"addProcessingBatch",{enumerable:!0,configurable:!0,writable:!0,value:value=>{const r4=this._processingBatches.add(value);this._updateBatchProcessStatus();return r4}});Object.defineProperty(this,"deleteProcessingBatch",{enumerable:!0,configurable:!0,writable:!0,value:value=>{const r4=this._processingBatches.delete(value);this._updateBatchProcessStatus();return r4}});Object.defineProperty(this,"_processing",{enumerable:!0,configurable:!0,writable:!0,value:!1});Object.defineProperty(this,"_collected",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_clerks",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_processCount",{enumerable:!0,configurable:!0,writable:!0,value:0});this._root=this;this._processor=processor;this.batchSize=null!=(_a8=null==params?void 0:params.batchSize)?_a8:1;this.yieldThreshold=null!=(_c3=null!=(_b5=null==params?void 0:params.yieldThreshold)?_b5:null==params?void 0:params.batchSize)?_c3:0;this.concurrentLimit=null!=(_d2=null==params?void 0:params.concurrentLimit)?_d2:1;this.delay=null!=(_e2=null==params?void 0:params.delay)?_e2:0;this.maintainDelay=null!=(_f=null==params?void 0:params.maintainDelay)&&_f;this.interval=null!=(_g=null==params?void 0:params.interval)?_g:0;(null==params?void 0:params.keepResultUntilDownstreamConnected)&&(this._keepResultUntilDownstreamConnected=params.keepResultUntilDownstreamConnected);(null==params?void 0:params.remainingReactiveSource)&&(this._remainingReactiveSource=null==params?void 0:params.remainingReactiveSource);(null==params?void 0:params.totalRemainingReactiveSource)&&(this._totalRemainingReactiveSource=null==params?void 0:params.totalRemainingReactiveSource);(null==params?void 0:params.processingEntitiesReactiveSource)&&(this._processingEntitiesReactiveSource=null==params?void 0:params.processingEntitiesReactiveSource);void 0!==(null==params?void 0:params.suspended)&&(this._isSuspended=null==params?void 0:params.suspended);enqueueProcessor&&this.replaceEnqueueProcessor(enqueueProcessor);void 0!==(null==params?void 0:params.pipeTo)&&this.pipeTo(params.pipeTo);this._intervalPaceMaker=new PaceMaker(this.interval);items&&this.enqueueAll(items);allRunningProcessors.add(this);this._initClerks();this._initEventHub();this.resume()}replaceEnqueueProcessor(processor){this._enqueueProcessor=processor;return this}modifyQueue(processor){this._queue=processor(this._queue);this._onTick()}clearQueue(){this._queue=[];this._onTick()}onUpdateProgress(proc){this._runOnUpdateBatch=proc;return this}pipeTo(pipeTo){this._pipeTo=pipeTo;this._pipeTo._root=this.root;if(this._keptResult.length>0){const temp=[...this._keptResult];this._keptResult=[];this._pipeTo.enqueueAll(temp)}return pipeTo}isIdle(){return this._isIdle()&&(!this._pipeTo||this._pipeTo.isIdle())}_isIdle(){return 0==this.totalRemaining}async _waitForIdle(){if(this._isSuspended)return Promise.resolve();if(this._isIdle())return Promise.resolve();do{const r4=await this._waitFor(["tickEmpty","tick","tickSuspended","suspended","idle"]);if("tickSuspended"===r4)break;if("suspended"==r4)break;if("tickEmpty"==r4)break;if("idle"==r4)break}while(!this._isIdle());return Promise.resolve()}idleDetectors(){const thisPromise=this._waitForIdle();return this._pipeTo?[thisPromise,...this._pipeTo.idleDetectors()]:[thisPromise]}get isSuspended(){var _a8;return this._isSuspended||(null==(_a8=this._pipeTo)?void 0:_a8.isSuspended)||!1}_updateReactiveSource(){this.root.updateReactiveSource()}updateReactiveSource(){this._pipeTo&&this._pipeTo.updateReactiveSource();this._remainingReactiveSource&&(this._remainingReactiveSource.value=this.remaining);this._totalRemainingReactiveSource&&(this._totalRemainingReactiveSource.value=this.totalRemaining);this._processingEntitiesReactiveSource&&(this._processingEntitiesReactiveSource.value=this.nowProcessing)}_updateBatchProcessStatus(){this._updateReactiveSource();this._runOnUpdateBatch()}_collectBatch(){return this._queue.splice(0,this.batchSize)}_canCollectBatch(){return 0!==this._queue.length}enqueue(entity){this._queue=this._enqueueProcessor(this._queue,entity);this._updateBatchProcessStatus();this._onTick();return this}enqueueAll(entities){let queue2=this._queue;for(const v2 of entities)queue2=this._enqueueProcessor(queue2,v2);this._queue=queue2;this._updateBatchProcessStatus();this._onTick();return this}requestNextFlush(){this._nextProcessNeedsImmediate=!0;this._onTick()}async _waitForSuspended(){}flush(){if(this._isSuspended)return Promise.resolve(!1);this.requestNextFlush();return this.waitForAllDownstream()}async waitForAllDownstream(timeout){const baseTasks=[];timeout&&baseTasks.push(delay(timeout,RESULT_TIMED_OUT));do{const idleTasks=this.idleDetectors(),tasks3=[...baseTasks,Promise.all(idleTasks)];if(await Promise.race(tasks3)===RESULT_TIMED_OUT)return!1}while(!this.isIdle());return!0}waitForAllProcessed(timeout){this.root.startPipeline();return this.root.waitForAllDownstream(timeout)}async waitForAllDoneAndTerminate(timeout){this.root.startPipeline();const r4=await this.root.waitForAllDownstream(timeout);this.terminateAll();return r4}async _runProcessor(items){const ret=await this._processor(items);ret&&(this._pipeTo?this._pipeTo.enqueueAll(ret):this._keepResultUntilDownstreamConnected&&this._keptResult.push(...ret))}async*pump(){do{const ticked=await this._waitFor(["tickImmediate","yielded","tickSuspended","tickDelayTimeout","tickSuspended"]);L2:do{const items=this._collectBatch();if(0==items.length)break L2;yield items}while(this._canCollectBatch());if("tickSuspended"==ticked)break}while(!this._isSuspended)}_initClerks(){this._collected=new Inbox(2*this.concurrentLimit);this._clerks=new ClerkGroup({assigned:this._collected,job:async items=>{const batchLength=items.length;this.updateStatus((()=>{this.processingEntities+=batchLength;this.waitingEntries-=batchLength}));await this._intervalPaceMaker.paced;this._processCount++;try{await this._runProcessor(items)}catch(ex){Logger("Processor error!");Logger(ex,LOG_LEVEL_VERBOSE)}this.updateStatus((()=>{this.processingEntities-=batchLength}));this._processCount--;0==this._processCount&&this._notifyIfIdle()},initialMemberCount:this.concurrentLimit,instantiate:params=>new Clerk(params)})}async _process(){if(!this._processing&&!this._isSuspended)try{this._processing=!0;do{const batchPump=this.pump();for await(const batch of batchPump){if(!batch||0===batch.length){this._hub.emitEvent("tickEmpty");continue}const batchLength=batch.length;this.updateStatus((()=>{this.waitingEntries+=batchLength}));await this._collected.post(batch)}}while(!this._isSuspended);this._hub.emitEvent("suspended")}finally{this._processing=!1}}_run(){this._isSuspended||this._processing||fireAndForget((()=>this._process()))}terminateAll(){this.root.terminate()}terminate(){if(this._pipeTo){this._pipeTo.terminate();this._pipeTo=void 0}this._isSuspended=!0;this._enqueueProcessor=()=>[];this._processor=()=>Promise.resolve([]);this.clearQueue();this._hub.emitEvent("tickSuspended");this._hub.emitEvent("tickSuspended");this._hub.emitEvent("tickSuspended");this._collected.dispose();this._clerks.dispose();this._queue.length=0;allRunningProcessors.delete(this)}};HiddenFileSync=class extends LiveSyncCommands{constructor(){super(...arguments);this.periodicInternalFileScanProcessor=new PeriodicProcessor(this.plugin,(async()=>this.isThisModuleEnabled()&&this._isDatabaseReady()&&await this.scanAllStorageChanges(!1)));this.semaphore=Semaphore(10);this.conflictResolutionProcessor=new QueueProcessor((async paths=>{var _a8,_b5,_c3;const path2=paths[0];sendSignal(`cancel-internal-conflict:${path2}`);try{const id=await this.path2id(path2,ICHeader),doc=await this.localDatabase.getRaw(id,{conflicts:!0});if(void 0===doc._conflicts)return[];if(0==doc._conflicts.length)return[];this._log(`Hidden file conflicted:${path2}`);const conflicts=doc._conflicts.sort(((a2,b3)=>Number(a2.split("-")[0])-Number(b3.split("-")[0]))),revA=doc._rev,revB=conflicts[0];if(path2.endsWith(".json")){const conflictedRev=conflicts[0],conflictedRevNo=Number(conflictedRev.split("-")[0]),commonBase=null!=(_c3=null==(_b5=null==(_a8=(await this.localDatabase.getRaw(id,{revs_info:!0}))._revs_info)?void 0:_a8.filter((e3=>"available"==e3.status&&Number(e3.rev.split("-")[0])<conflictedRevNo)).first())?void 0:_b5.rev)?_c3:"",result=await this.plugin.managers.conflictManager.mergeObject(doc.path,commonBase,doc._rev,conflictedRev);if(result){this._log(`Object merge:${path2}`,LOG_LEVEL_INFO);const filename=stripAllPrefixes(path2);await this.ensureDir(filename);const stat=await this.writeFile(filename,result);if(!stat)throw new Error(`conflictResolutionProcessor: Failed to stat file ${filename}`);await this.storeInternalFileToDatabase({path:filename,...stat});await this.extractInternalFileFromDatabase(filename);await this.localDatabase.removeRevision(id,revB);this.conflictResolutionProcessor.enqueue(path2);return[]}this._log("Object merge is not applicable.",LOG_LEVEL_VERBOSE);if(getFileRegExp(this.settings,"syncInternalFileOverwritePatterns").some((r4=>r4.test(stripAllPrefixes(path2))))){this._log(`Overwrite rule applied for conflicted hidden file: ${path2}`,LOG_LEVEL_INFO);await this.resolveByNewerEntry(id,path2,doc,revA,revB);return[]}return[{path:path2,revA,revB,id,doc}]}await this.resolveByNewerEntry(id,path2,doc,revA,revB);return[]}catch(ex){this._log(`Failed to resolve conflict (Hidden): ${path2}`);this._log(ex,LOG_LEVEL_VERBOSE);return[]}}),{suspended:!1,batchSize:1,concurrentLimit:5,delay:10,keepResultUntilDownstreamConnected:!0,yieldThreshold:10,pipeTo:new QueueProcessor((async results=>{const{id,doc,path:path2,revA,revB}=results[0],prefixedPath=addPrefix(path2,ICHeader),docAMerge=await this.localDatabase.getDBEntry(prefixedPath,{rev:revA}),docBMerge=await this.localDatabase.getDBEntry(prefixedPath,{rev:revB});0==docAMerge||0==docBMerge?await this.resolveByNewerEntry(id,path2,doc,revA,revB):await this.showJSONMergeDialogAndMerge(docAMerge,docBMerge)&&this.conflictResolutionProcessor.enqueue(path2)}),{suspended:!1,batchSize:1,concurrentLimit:1,delay:10,keepResultUntilDownstreamConnected:!1,yieldThreshold:10})});this.cacheFileRegExps=new Map;this.cacheCustomisationSyncIgnoredFiles=new Map;this.queuedNotificationFiles=new Set}isThisModuleEnabled(){return this.plugin.settings.syncInternalFiles}get kvDB(){return this.plugin.kvDB}getConflictedDoc(path2,rev3){return this.plugin.managers.conflictManager.getConflictedDoc(path2,rev3)}onunload(){var _a8;null==(_a8=this.periodicInternalFileScanProcessor)||_a8.disable()}onload(){this.plugin.addCommand({id:"livesync-sync-internal",name:"(re)initialise hidden files between storage and database",callback:()=>{this.isReady()&&this.initialiseInternalFileSync("safe",!0)}});this.plugin.addCommand({id:"livesync-scaninternal-storage",name:"Scan hidden file changes on the storage",callback:()=>{this.isReady()&&this.scanAllStorageChanges(!0)}});this.plugin.addCommand({id:"livesync-scaninternal-database",name:"Scan hidden file changes on the local database",callback:()=>{this.isReady()&&this.scanAllDatabaseChanges(!0)}});this.plugin.addCommand({id:"livesync-internal-scan-offline-changes",name:"Scan and apply all offline hidden-file changes",callback:()=>{this.isReady()&&this.applyOfflineChanges(!0)}});eventHub.onEvent(EVENT_SETTING_SAVED,(()=>{this.updateSettingCache()}))}async _everyOnDatabaseInitialized(showNotice){this._fileInfoLastProcessed=await autosaveCache(this.kvDB,"hidden-file-lastProcessed");this._databaseInfoLastProcessed=await autosaveCache(this.kvDB,"hidden-file-lastProcessed-database");this._fileInfoLastKnown=await autosaveCache(this.kvDB,"hidden-file-lastKnown");if(this.isThisModuleEnabled())if(0==this._fileInfoLastProcessed.size&&0==this._fileInfoLastProcessed.size){this._log("No cache found. Performing startup scan.",LOG_LEVEL_VERBOSE);await this.performStartupScan(!0)}else await this.performStartupScan(showNotice);return!0}async _everyBeforeReplicate(showNotice){this.isThisModuleEnabled()&&this._isDatabaseReady()&&this.settings.syncInternalFilesBeforeReplication&&!this.settings.watchInternalFileChanges&&await this.scanAllStorageChanges(showNotice);return!0}_everyOnloadAfterLoadSettings(){this.updateSettingCache();return Promise.resolve(!0)}updateSettingCache(){this.cacheCustomisationSyncIgnoredFiles.clear();this.cacheFileRegExps.clear()}isReady(){return!!this._isMainReady&&!this._isMainSuspended()&&!!this.isThisModuleEnabled()}async performStartupScan(showNotice){await this.applyOfflineChanges(showNotice)}async _everyOnResumeProcess(){var _a8;null==(_a8=this.periodicInternalFileScanProcessor)||_a8.disable();if(this._isMainSuspended())return!0;this.isThisModuleEnabled()&&await this.performStartupScan(!1);this.periodicInternalFileScanProcessor.enable(this.isThisModuleEnabled()&&this.settings.syncInternalFilesInterval?1e3*this.settings.syncInternalFilesInterval:0);return!0}_everyRealizeSettingSyncMode(){var _a8;null==(_a8=this.periodicInternalFileScanProcessor)||_a8.disable();if(this._isMainSuspended())return Promise.resolve(!0);if(!this.services.appLifecycle.isReady())return Promise.resolve(!0);this.periodicInternalFileScanProcessor.enable(this.isThisModuleEnabled()&&this.settings.syncInternalFilesInterval?1e3*this.settings.syncInternalFilesInterval:0);this.cacheFileRegExps.clear();return Promise.resolve(!0)}async _anyProcessOptionalFileEvent(path2){return this.isReady()&&await this.trackStorageFileModification(path2)||!1}_anyGetOptionalConflictCheckMethod(path2){if(isInternalMetadata(path2)){this.queueConflictCheck(path2);return Promise.resolve(!0)}return Promise.resolve(!1)}async _anyProcessOptionalSyncFiles(doc){if(isInternalMetadata(doc._id)){if(this.isThisModuleEnabled()){const filename=getPath2(doc);if(await this.services.vault.isTargetFile(filename)){await this.processReplicationResult(doc);return!0}this._log(`Skipped (Not target:${filename})`,LOG_LEVEL_VERBOSE);return!1}return!0}return!1}async loadFileWithInfo(path2){var _a8,_b5;const stat=await this.plugin.storageAccess.statHidden(path2);if(!stat)return{name:null!=(_a8=path2.split("/").pop())?_a8:"",path:path2,stat:{size:0,mtime:0,ctime:0,type:"file"},isInternal:!0,deleted:!0,body:createBlob(new Uint8Array(0))};const content=await this.plugin.storageAccess.readHiddenFileAuto(path2);return{name:null!=(_b5=path2.split("/").pop())?_b5:"",path:path2,stat,isInternal:!0,deleted:!1,body:createBlob(content)}}statToKey(stat){var _a8,_b5;return`${null!=(_a8=null==stat?void 0:stat.mtime)?_a8:0}-${null!=(_b5=null==stat?void 0:stat.size)?_b5:0}`}docToKey(doc){return`${doc.mtime}-${doc.size}-${doc._rev}-${doc._deleted||doc.deleted?"-0":"-1"}`}async fileToStatKey(file,stat=null){stat||(stat=await this.plugin.storageAccess.statHidden(file));return this.statToKey(stat)}updateLastProcessedFile(file,keySrc){const key3="string"==typeof keySrc?keySrc:this.statToKey(keySrc),splitted=key3.split("-");"0"!=splitted[0]&&this._fileInfoLastKnown.set(file,Number(splitted[0]));this._fileInfoLastProcessed.set(file,key3)}async updateLastProcessedAsActualFile(file,stat){stat||(stat=await this.plugin.storageAccess.statHidden(file));this._fileInfoLastProcessed.set(file,this.statToKey(stat))}resetLastProcessedFile(targetFiles){if(targetFiles)for(const key3 of targetFiles)this._fileInfoLastProcessed.delete(key3);else{this._log("Delete all processed mark.",LOG_LEVEL_VERBOSE);this._fileInfoLastProcessed.clear()}}getLastProcessedFileMTime(file){return this._fileInfoLastKnown.get(file)||0}getLastProcessedFileKey(file){return this._fileInfoLastProcessed.get(file)}getLastProcessedDatabaseKey(file){return this._databaseInfoLastProcessed.get(file)}updateLastProcessedDatabase(file,keySrc){const key3="string"==typeof keySrc?keySrc:this.docToKey(keySrc);this._databaseInfoLastProcessed.set(file,key3)}updateLastProcessed(path2,db,stat){this.updateLastProcessedDatabase(path2,db);this.updateLastProcessedFile(path2,this.statToKey(stat));const dbMTime=getComparingMTime(db),storageMTime=getComparingMTime(stat);0==dbMTime||0==storageMTime?unmarkChanges(path2):markChangesAreSame(path2,getComparingMTime(db),getComparingMTime(stat))}updateLastProcessedDeletion(path2,db){unmarkChanges(path2);db&&this.updateLastProcessedDatabase(path2,db);this.updateLastProcessedFile(path2,this.statToKey(null))}async ensureDir(path2){await this.plugin.storageAccess.isExistsIncludeHidden(path2)||await this.plugin.storageAccess.ensureDir(path2)}async writeFile(path2,data,opt){await this.plugin.storageAccess.writeHiddenFileAuto(path2,data,opt);return await this.plugin.storageAccess.statHidden(path2)}async __removeFile(path2){try{if(!await this.plugin.storageAccess.isExistsIncludeHidden(path2))return"ALREADY";if(await this.plugin.storageAccess.removeHidden(path2))return"OK"}catch(ex){this._log(`Failed to remove file:${path2}`);this._log(ex,LOG_LEVEL_VERBOSE)}return!1}async triggerEvent(path2){try{await this.plugin.storageAccess.triggerHiddenFile(path2)}catch(ex){this._log("Failed to call internal API(reconcileInternalFile)",LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}}async updateLastProcessedAsActualDatabase(file,doc){const dbPath=addPrefix(file,ICHeader);doc||(doc=await this.localDatabase.getDBEntryMeta(dbPath));doc&&this._databaseInfoLastProcessed.set(file,this.docToKey(doc))}resetLastProcessedDatabase(targetFiles){if(targetFiles)for(const key3 of targetFiles)this._databaseInfoLastProcessed.delete(key3);else{this._log("Delete all processed mark.",LOG_LEVEL_VERBOSE);this._databaseInfoLastProcessed.clear()}}async adoptCurrentStorageFilesAsProcessed(targetFiles){const allFiles=await this.scanInternalFileNames(),files=targetFiles?allFiles.filter((e3=>targetFiles.some((t3=>-1!==e3.indexOf(t3))))):allFiles;for(const file of files)await this.updateLastProcessedAsActualFile(file)}async adoptCurrentDatabaseFilesAsProcessed(targetFiles){const allFiles=await this.getAllDatabaseFiles(),files=targetFiles?allFiles.filter((e3=>targetFiles.some((t3=>-1!==e3.path.indexOf(t3))))):allFiles;for(const file of files){const path2=stripAllPrefixes(this.getPath(file));await this.updateLastProcessedAsActualDatabase(path2,file)}}async serializedForEvent(file,fn){hiddenFilesEventCount.value++;const rel=await this.semaphore.acquire();try{return await serialized(`hidden-file-event:${file}`,(async()=>{hiddenFilesProcessingCount.value++;try{return await fn()}finally{hiddenFilesProcessingCount.value--}}))}finally{rel();hiddenFilesEventCount.value--}}async useStorageFiles(files,showNotice=!1,onlyNew=!1){return await this.trackScannedStorageChanges(files,showNotice,onlyNew,!0)}async trackScannedStorageChanges(processFiles,showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeleted=!0){const logLevel=getLogLevel(showNotice),p4=this._progress("[⚙ Storage -> DB ]\n",logLevel),notifyProgress=onlyInNTimes(100,(progress=>p4.log(`${progress}/${processFiles.length}`))),processes=processFiles.map((async(file,i2)=>{try{await this.trackStorageFileModification(file,onlyNew,forceWriteAll,includeDeleted);notifyProgress()}catch(ex){p4.once(`Failed to process storage change file:${file}`);this._log(ex,LOG_LEVEL_VERBOSE)}}));await Promise.all(processes);p4.done()}async scanAllStorageChanges(showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeleted=!0){return await skipIfDuplicated("scanAllStorageChanges",(async()=>{const logLevel=getLogLevel(showNotice),p4=this._progress("[⚙ Scanning Storage -> DB ]\n",logLevel);p4.log("Scanning storage files...");const knownNames=[...this._fileInfoLastProcessed.keys()],existNames=await this.scanInternalFileNames(),files=new Set([...knownNames,...existNames]);this._log(`Known/Exist ${knownNames.length}/${existNames.length}, Totally ${files.size} files.`,LOG_LEVEL_VERBOSE);const taskNameAndMeta=[...files].map((async e3=>[e3,await this.plugin.storageAccess.statHidden(e3)])),processFiles=(await Promise.all(taskNameAndMeta)).filter((([path2,stat])=>!!forceWriteAll||this.getLastProcessedFileKey(path2)!=this.statToKey(stat))).map((([path2,stat])=>path2)),staticsMessage=`[Storage hidden file statics]\nKnown files: ${knownNames.length}\nActual files: ${existNames.length}\nAll files: ${files.size}\nOffline Changed files: ${processFiles.length}`;p4.once(staticsMessage);await this.trackScannedStorageChanges(processFiles,showNotice,onlyNew,forceWriteAll,includeDeleted);p4.done()}))}async trackStorageFileModification(path2,onlyNew=!1,forceWrite=!1,includeDeleted=!0){if(!await this.isTargetFile(path2)){this._log(`Storage file tracking: Hidden file skipped: ${path2} is filtered out by the defined patterns.`,LOG_LEVEL_VERBOSE);return!1}try{return await this.serializedForEvent(path2,(async()=>{let stat=await this.plugin.storageAccess.statHidden(path2);if(null!=stat&&"file"!=stat.type)return!1;const key3=await this.fileToStatKey(path2,stat),lastKey=this.getLastProcessedFileKey(path2);if(lastKey==key3){this._log(`${path2} Already processed.`,LOG_LEVEL_DEBUG);return!0}const cache2=await this.loadFileWithInfo(path2);if(getComparingMTime(cache2.stat)!=getComparingMTime(stat)){this._log(`Hidden file:${path2} is changed.`,LOG_LEVEL_VERBOSE);stat=cache2.stat}this.updateLastProcessedFile(path2,stat);const lastIsNotFound=!lastKey||lastKey.endsWith("-0-0"),nowIsNotFound=cache2.deleted,type=lastIsNotFound&&nowIsNotFound?"invalid":nowIsNotFound?"delete":"modified";if("invalid"==type)return!1;const storageMTimeActual=getComparingMTime(stat),storageMTime=0==storageMTimeActual?this.getLastProcessedFileMTime(path2):storageMTimeActual;if(onlyNew){const prefixedFileName=addPrefix(path2,ICHeader),filesOnDB=await this.localDatabase.getDBEntryMeta(prefixedFileName);if(compareMTime(storageMTime,getComparingMTime(filesOnDB,includeDeleted))!=TARGET_IS_NEW){this._log(`Hidden file:${path2} is not new.`,LOG_LEVEL_VERBOSE);filesOnDB&&stat&&this.updateLastProcessed(path2,filesOnDB,stat);return!0}}if("delete"==type){this._log(`Deletion detected: ${path2}`);return await this.deleteInternalFileOnDatabase(path2,forceWrite)}if("modified"==type){this._log(`Modification detected:${path2}`,LOG_LEVEL_VERBOSE);const result=await this.storeInternalFileToDatabase(cache2,forceWrite),resultText=void 0===result?"Nothing changed":result?"Updated":"Failed";this._log(`${resultText}: ${path2} ${resultText}`,LOG_LEVEL_VERBOSE);return result}}))}catch(ex){this._log(`Failed to process hidden file:${path2}`);this._log(ex,LOG_LEVEL_VERBOSE)}return!0}queueConflictCheck(path2){this.conflictResolutionProcessor.enqueue(path2)}async resolveConflictOnInternalFiles(){const conflicted=this.localDatabase.findEntries(ICHeader,"i;",{conflicts:!0});this.conflictResolutionProcessor.suspend();try{for await(const doc of conflicted)"_conflicts"in doc&&isInternalMetadata(doc._id)&&this.conflictResolutionProcessor.enqueue(doc.path)}catch(ex){this._log("something went wrong on resolving all conflicted internal files");this._log(ex,LOG_LEVEL_VERBOSE)}await this.conflictResolutionProcessor.startPipeline().waitForAllProcessed()}async resolveByNewerEntry(id,path2,currentDoc,currentRev,conflictedRev){var _a8;const conflictedDoc=await this.localDatabase.getRaw(id,{rev:conflictedRev}),delRev=getComparingMTime(currentDoc,!0)<getComparingMTime(conflictedDoc,!0)?currentRev:conflictedRev;await this.localDatabase.removeRevision(id,delRev);this._log(`Older one has been deleted:${path2}`);0===(null==(_a8=(await this.localDatabase.getRaw(id,{conflicts:!0}))._conflicts)?void 0:_a8.length)?await this.extractInternalFileFromDatabase(stripAllPrefixes(path2)):this.conflictResolutionProcessor.enqueue(path2)}showJSONMergeDialogAndMerge(docA,docB){return new Promise((res2=>{this._log("Opening data-merging dialog",LOG_LEVEL_VERBOSE);const docs=[docA,docB],strippedPath=stripAllPrefixes(docA.path),storageFilePath=strippedPath,storeFilePath=strippedPath,displayFilename=`${storeFilePath}`;new JsonResolveModal(this.app,storageFilePath,[docA,docB],(async(keep,result)=>{var _a8,_b5;try{let needFlush=!1;if(!result&&!keep){this._log(`Skipped merging: ${displayFilename}`);res2(!1);return}if(result||keep)for(const doc of docs)if(doc._rev!=keep&&await this.localDatabase.deleteDBEntry(this.getPath(doc),{rev:doc._rev})){this._log(`Conflicted revision has been deleted: ${displayFilename}`);needFlush=!0}if(!keep&&result){await this.plugin.storageAccess.isExistsIncludeHidden(storageFilePath)||await this.plugin.storageAccess.ensureDir(storageFilePath);const stat=await this.writeFile(storageFilePath,result);if(!stat)throw new Error("Stat failed");const mtime=getComparingMTime(stat);await this.storeInternalFileToDatabase({path:storageFilePath,mtime,ctime:null!=(_a8=null==stat?void 0:stat.ctime)?_a8:mtime,size:null!=(_b5=null==stat?void 0:stat.size)?_b5:0},!0);await this.triggerEvent(storageFilePath);this._log(`STORAGE <-- DB:${displayFilename}: written (hidden,merged)`)}needFlush&&(await this.extractInternalFileFromDatabase(storeFilePath,!1)?this._log(`STORAGE --\x3e DB:${displayFilename}: extracted (hidden,merged)`):this._log(`STORAGE --\x3e DB:${displayFilename}: extracted (hidden,merged) Failed`));res2(!0)}catch(ex){this._log("Could not merge conflicted json");this._log(ex,LOG_LEVEL_VERBOSE);res2(!1)}})).open()}))}async processReplicationResult(doc){const info3=getDocProps(doc),path2=info3.path,headerLine=`Tracking DB ${info3.path} (${info3.revDisplay}) :`,ret=await this.trackDatabaseFileModification(path2,headerLine);this._log(`${headerLine} Done: ${info3.shortenedId})`,LOG_LEVEL_VERBOSE);return ret}parseRegExpSettings(){const regExpKey=`${this.plugin.settings.syncInternalFilesTargetPatterns}||${this.plugin.settings.syncInternalFilesIgnorePatterns}`;let ignoreFilter,targetFilter;if(this.cacheFileRegExps.has(regExpKey)){const cached=this.cacheFileRegExps.get(regExpKey);ignoreFilter=cached[1];targetFilter=cached[0]}else{ignoreFilter=getFileRegExp(this.plugin.settings,"syncInternalFilesIgnorePatterns");targetFilter=getFileRegExp(this.plugin.settings,"syncInternalFilesTargetPatterns");this.cacheFileRegExps.clear();this.cacheFileRegExps.set(regExpKey,[targetFilter,ignoreFilter])}return{ignoreFilter,targetFilter}}isTargetFileInPatterns(path2){const{ignoreFilter,targetFilter}=this.parseRegExpSettings();if(ignoreFilter&&ignoreFilter.length>0)for(const pattern of ignoreFilter)if(pattern.test(path2))return!1;if(targetFilter&&targetFilter.length>0){for(const pattern of targetFilter)if(pattern.test(path2))return!0;return!1}return!0}getCustomisationSynchronizationIgnoredFiles(){const configDir=this.plugin.app.vault.configDir,key3=JSON.stringify(this.settings.pluginSyncExtendedSetting)+`||${this.settings.usePluginSync}||${configDir}`;if(this.cacheCustomisationSyncIgnoredFiles.has(key3))return this.cacheCustomisationSyncIgnoredFiles.get(key3);this.cacheCustomisationSyncIgnoredFiles.clear();const synchronisedInConfigSync=this.settings.usePluginSync?Object.values(this.settings.pluginSyncExtendedSetting).filter((e3=>e3.mode==MODE_SELECTIVE||e3.mode==MODE_PAUSED)).map((e3=>e3.files)).flat().map((e3=>`${configDir}/${e3}`.toLowerCase())):[];this.cacheCustomisationSyncIgnoredFiles.set(key3,synchronisedInConfigSync);return synchronisedInConfigSync}isNotIgnoredByCustomisationSync(path2){return!this.getCustomisationSynchronizationIgnoredFiles().some((e3=>path2.startsWith(e3)))}isHiddenFileSyncHandlingPath(path2){return path2.startsWith(".")&&!path2.startsWith(".trash")}async isTargetFile(path2){return!!(this.isTargetFileInPatterns(path2)&&this.isNotIgnoredByCustomisationSync(path2)&&this.isHiddenFileSyncHandlingPath(path2))&&!await this.services.vault.isIgnoredByIgnoreFile(path2)}async trackScannedDatabaseChange(processFiles,showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeletion=!0){const logLevel=getLogLevel(showNotice),p4=this._progress("[⚙ DB -> Storage ]\n",logLevel),notifyProgress=onlyInNTimes(100,(progress=>p4.log(`${progress}/${processFiles.length}`))),processes=processFiles.map((async file=>{try{const path2=stripAllPrefixes(this.getPath(file));await this.isTargetFile(path2)?await this.trackDatabaseFileModification(path2,"[Hidden file scan]",!forceWriteAll,onlyNew,file,includeDeletion):this._log(`Database file tracking: Hidden file skipped: ${path2} is filtered out by the defined patterns.`,LOG_LEVEL_VERBOSE);notifyProgress()}catch(ex){this._log(`Failed to process storage change file:${file}`,logLevel);this._log(ex,LOG_LEVEL_VERBOSE)}}));await Promise.all(processes);p4.done()}async applyOfflineChanges(showNotice){const logLevel=getLogLevel(showNotice);return await serialized("applyOfflineChanges",(async()=>{const p4=this._progress("[⚙ Apply untracked changes ]\n",logLevel);this._log("Track changes.",logLevel);p4.log("Enumerating local files...");const currentStorageFiles=await this.scanInternalFileNames();p4.log("Enumerating database files...");const currentDatabaseFiles=await this.getAllDatabaseFiles(),allDatabaseMap=Object.fromEntries(currentDatabaseFiles.map((e3=>[stripAllPrefixes(getPath2(e3)),e3]))),currentDatabaseFileNames=[...Object.keys(allDatabaseMap)],untrackedLocal=currentStorageFiles.filter((e3=>!this._fileInfoLastProcessed.has(e3))),untrackedDatabase=currentDatabaseFileNames.filter((e3=>!this._databaseInfoLastProcessed.has(e3))),bothUntracked=untrackedLocal.filter((e3=>-1!==untrackedDatabase.indexOf(e3)));p4.log("Applying untracked changes...");const stat=`Tracking statics:\nLocal files: ${currentStorageFiles.length}\nDatabase files: ${currentDatabaseFileNames.length}\nUntracked local files: ${untrackedLocal.length}\nUntracked database files: ${untrackedDatabase.length}\nCommon untracked files: ${bothUntracked.length}`;p4.once(stat);const semaphores2=Semaphore(10),notifyProgress=onlyInNTimes(25,(progress=>p4.log(`${progress}/${bothUntracked.length}`))),allProcesses=bothUntracked.map((async file=>{notifyProgress();const rel=await semaphores2.acquire();try{const fileStat=await this.plugin.storageAccess.statHidden(file);if(null==fileStat){this._log(`Unexpected error: Failed to stat file during applyOfflineChange :${file}`);return}const dbInfo=allDatabaseMap[file];if(dbInfo.deleted||dbInfo._deleted)return;const diff=compareMTime(getComparingMTime(fileStat),getComparingMTime(dbInfo));diff==BASE_IS_NEW?await this.trackStorageFileModification(file,!0):diff==TARGET_IS_NEW?await this.trackDatabaseFileModification(file,"[Apply]",!0,!0,dbInfo):diff==EVEN&&this.updateLastProcessed(file,dbInfo,fileStat)}finally{rel()}}));await Promise.all(allProcesses);await this.scanAllStorageChanges(showNotice);await this.scanAllDatabaseChanges(showNotice);p4.done()}))}async scanAllDatabaseChanges(showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeletion=!0){return await skipIfDuplicated("scanAllDatabaseChanges",(async()=>{const databaseFiles=await this.getAllDatabaseFiles(),files=databaseFiles.filter((e3=>{const doc=e3,key3=this.docToKey(doc),path2=stripAllPrefixes(this.getPath(doc));return this.getLastProcessedDatabaseKey(path2)!=key3})),logLevel=getLogLevel(showNotice),staticsMessage=`[Database hidden file statics]\nAll files: ${databaseFiles.length}\nOffline Changed files: ${files.length}`;this._log(staticsMessage,logLevel,"scan-changes");return await this.trackScannedDatabaseChange(files,showNotice,onlyNew,forceWriteAll,includeDeletion)}))}async useDatabaseFiles(files,showNotice=!1,onlyNew=!1){const logLevel=getLogLevel(showNotice),p4=this._progress("[⚙ Scanning DB -> Storage ]\n",logLevel);p4.log("Scanning database files...");const notifyProgress=onlyInNTimes(25,(progress=>p4.log(`${progress}/${files.length}`))),processFiles=files.map((async file=>{try{const path2=stripAllPrefixes(this.getPath(file));await this.trackDatabaseFileModification(path2,"[Scanning]",!0,onlyNew,file);notifyProgress()}catch(ex){this._log(`Failed to process database changes:${file}`);this._log(ex,LOG_LEVEL_VERBOSE)}}));await Promise.all(processFiles);p4.done();return!0}async trackDatabaseFileModification(path2,headerLine,preventDoubleProcess=!1,onlyNew=!1,meta=!1,includeDeletion=!0){return await this.serializedForEvent(path2,(async()=>{try{const prefixedPath=addPrefix(path2,ICHeader),docMeta=meta||await this.localDatabase.getDBEntryMeta(prefixedPath,{conflicts:!0},!0);if(!1===docMeta){this._log(`${headerLine}: Failed to read detail of ${path2}`);throw new Error(`Failed to read detail ${path2}`)}if(docMeta._conflicts&&docMeta._conflicts.length>0){this.conflictResolutionProcessor.enqueue(path2);this._log(`${headerLine} Hidden file conflicted, enqueued to resolve`);return!0}await this.extractInternalFileFromDatabase(path2,!1,docMeta,preventDoubleProcess,onlyNew,includeDeletion)&&this._log(`${headerLine} Hidden file processed`)}catch(ex){this._log(`${headerLine} Failed to process hidden file`);this._log(ex,LOG_LEVEL_VERBOSE)}return!0}))}notifyConfigChange(){const updatedFolders=[...this.queuedNotificationFiles];this.queuedNotificationFiles.clear();try{const manifests=Object.values(this.app.plugins.manifests),enabledPlugins=this.app.plugins.enabledPlugins,modifiedManifests=manifests.filter((e3=>enabledPlugins.has(e3.id))).filter((e3=>{var _a8;return updatedFolders.indexOf(null!=(_a8=null==e3?void 0:e3.dir)?_a8:"")>=0}));for(const manifest of modifiedManifests){const updatePluginId=manifest.id,updatePluginName=manifest.name;this.plugin.confirm.askInPopup(`updated-${updatePluginId}`,`Files in ${updatePluginName} has been updated!\nPress {HERE} to reload ${updatePluginName}, or press elsewhere to dismiss this message.`,(anchor=>{anchor.text="HERE";anchor.addEventListener("click",(()=>{fireAndForget((async()=>{this._log(`Unloading plugin: ${updatePluginName}`,LOG_LEVEL_NOTICE,"plugin-reload-"+updatePluginId);await this.app.plugins.unloadPlugin(updatePluginId);await this.app.plugins.loadPlugin(updatePluginId);this._log(`Plugin reloaded: ${updatePluginName}`,LOG_LEVEL_NOTICE,"plugin-reload-"+updatePluginId)}))}))}))}}catch(ex){this._log("Error on checking plugin status.");this._log(ex,LOG_LEVEL_VERBOSE)}updatedFolders.indexOf(this.plugin.app.vault.configDir)>=0&&(this.services.appLifecycle.isReloadingScheduled()||this.plugin.confirm.askInPopup("updated-any-hidden","Some setting files have been modified\nPress {HERE} to schedule a reload of Obsidian, or press elsewhere to dismiss this message.",(anchor=>{anchor.text="HERE";anchor.addEventListener("click",(()=>{this.services.appLifecycle.scheduleRestart()}))})))}queueNotification(key3){if(this.settings.suppressNotifyHiddenFilesChange)return;const configDir=this.plugin.app.vault.configDir;if(!key3.startsWith(configDir))return;const dirName=key3.split("/").slice(0,-1).join("/");this.queuedNotificationFiles.add(dirName);scheduleTask("notify-config-change",1e3,(()=>{this.notifyConfigChange()}))}async rebuildMerging(showNotice,targetFiles=!1){const logLevel=getLogLevel(showNotice),p4=this._progress("[⚙ Rebuild by Merge ]\n",logLevel);this._log("Rebuilding hidden files from the storage and the local database.",logLevel);p4.log("Enumerating local files...");const currentStorageFilesAll=await this.scanInternalFileNames(),currentStorageFiles=targetFiles?currentStorageFilesAll.filter((e3=>targetFiles.some((f4=>f4==e3)))):currentStorageFilesAll;p4.log("Enumerating database files...");const allDatabaseFiles=await this.getAllDatabaseFiles(),allDatabaseMap=new Map(allDatabaseFiles.map((e3=>[stripAllPrefixes(getPath2(e3)),e3]))),currentDatabaseFiles=targetFiles?allDatabaseFiles.filter((e3=>targetFiles.some((f4=>f4==stripAllPrefixes(getPath2(e3)))))):allDatabaseFiles,allFileNames=new Set([...currentStorageFiles,...currentDatabaseFiles.map((e3=>stripAllPrefixes(getPath2(e3))))]),storageToDatabase=[],databaseToStorage=[],eachProgress=onlyInNTimes(100,(progress=>p4.log(`Checking ${progress}/${allFileNames.size}`)));for(const file of allFileNames){eachProgress();const mtimeStorage=getComparingMTime(await this.plugin.storageAccess.statHidden(file)),dbEntry=allDatabaseMap.get(file),diff=compareMTime(mtimeStorage,getComparingMTime(dbEntry));diff==BASE_IS_NEW?storageToDatabase.push(file):diff==TARGET_IS_NEW?databaseToStorage.push(dbEntry):diff==EVEN&&storageToDatabase.push(file)}p4.once(`Storage to Database: ${storageToDatabase.length} files\n Database to Storage: ${databaseToStorage.length} files`);this.resetLastProcessedDatabase(targetFiles);this.resetLastProcessedFile(targetFiles);const processes=[this.useStorageFiles(storageToDatabase,showNotice,!1),this.useDatabaseFiles(databaseToStorage,showNotice,!1)];p4.log("Start processing...");await Promise.all(processes);p4.done();return[...allFileNames]}async rebuildFromStorage(showNotice,targetFiles=!1,onlyNew=!1){const logLevel=getLogLevel(showNotice);this._verbose("Rebuilding hidden files from the storage.");this._log("Rebuilding hidden files from the storage.",logLevel);const p4=this._progress("[⚙ Rebuild by Storage ]\n",logLevel);p4.log("Enumerating local files...");const currentFilesAll=await this.scanInternalFileNames(),currentFiles=targetFiles?currentFilesAll.filter((e3=>targetFiles.some((f4=>f4==e3)))):currentFilesAll;p4.once(`Storage to Database: ${currentFiles.length} files.`);p4.log("Start processing...");this.resetLastProcessedFile(targetFiles);await this.useStorageFiles(currentFiles,showNotice,onlyNew);p4.done();return currentFiles}async getAllDatabaseFiles(){const allFiles=(await this.localDatabase.allDocsRaw({startkey:ICHeader,endkey:"i;",include_docs:!0})).rows.filter((e3=>isInternalMetadata(e3.id))).map((e3=>e3.doc)),files=[];for(const file of allFiles)await this.isTargetFile(stripAllPrefixes(this.getPath(file)))&&files.push(file);return files}async rebuildFromDatabase(showNotice,targetFiles=!1,onlyNew=!1){const logLevel=getLogLevel(showNotice);this._verbose("Rebuilding hidden files from the local database.");const p4=this._progress("[⚙ Rebuild by Database ]\n",logLevel);p4.log("Enumerating database files...");const allFiles=await this.getAllDatabaseFiles(),currentFiles=targetFiles?allFiles.filter((e3=>targetFiles.some((f4=>f4==stripAllPrefixes(getPath2(e3)))))):allFiles;p4.once(`Database to Storage: ${currentFiles.length} files.`);this.resetLastProcessedDatabase(targetFiles);p4.log("Start processing...");await this.useDatabaseFiles(currentFiles,showNotice,onlyNew);p4.done();return currentFiles}async initialiseInternalFileSync(direction,showMessage,targetFilesSrc=!1){const logLevel=showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,p4=this._progress("[⚙ Initialise]\n",logLevel);p4.log("Initialising hidden files sync...");const targetFiles=!!targetFilesSrc&&targetFilesSrc.map((e3=>stripAllPrefixes(e3)));if("pushForce"==direction||"push"==direction){const onlyNew="push"==direction;p4.log("Started: Storage --\x3e Database "+(onlyNew?"(Only New)":""));const updatedFiles=await this.rebuildFromStorage(showMessage,targetFiles,onlyNew);await this.adoptCurrentStorageFilesAsProcessed(updatedFiles);await this.adoptCurrentDatabaseFilesAsProcessed(updatedFiles);await this.scanAllStorageChanges(showMessage,!0,!1);await this.scanAllDatabaseChanges(showMessage,!0,!1)}if("pullForce"==direction||"pull"==direction){const onlyNew="pull"==direction;p4.log("Started: Database --\x3e Storage "+(onlyNew?"(Only New)":""));const updatedFiles=(await this.rebuildFromDatabase(showMessage,targetFiles,onlyNew)).map((e3=>stripAllPrefixes(getPath2(e3))));await this.adoptCurrentStorageFilesAsProcessed(updatedFiles);await this.adoptCurrentDatabaseFilesAsProcessed(updatedFiles);await this.scanAllDatabaseChanges(showMessage,!0,!1);await this.scanAllStorageChanges(showMessage,!0,!1)}if("safe"==direction){p4.log("Started: Database <--\x3e Storage (by modified date)");const updatedFiles=await this.rebuildMerging(showMessage,targetFiles);await this.adoptCurrentStorageFilesAsProcessed(updatedFiles);await this.adoptCurrentDatabaseFilesAsProcessed(updatedFiles);await this.scanAllStorageChanges(showMessage,!0,!1);await this.scanAllDatabaseChanges(showMessage,!0,!1)}p4.done()}async __loadBaseSaveData(file,includeContent=!0){const prefixedFileName=addPrefix(file,ICHeader),id=await this.path2id(prefixedFileName,ICHeader);try{const old=includeContent?await this.localDatabase.getDBEntry(prefixedFileName,void 0,!1,!0):await this.localDatabase.getDBEntryMeta(prefixedFileName,{conflicts:!0},!0);return!1===old?{_id:id,data:[],path:prefixedFileName,mtime:0,ctime:0,datatype:"newnote",children:[],size:0,deleted:!1,type:"newnote",eden:{}}:old}catch(ex){this._log("Getting base save data failed");this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async storeInternalFileToDatabase(file,forceWrite=!1){const storeFilePath=stripAllPrefixes(file.path),storageFilePath=file.path;if(await this.services.vault.isIgnoredByIgnoreFile(storageFilePath))return;const prefixedFileName=addPrefix(storeFilePath,ICHeader);return await serialized("file-"+prefixedFileName,(async()=>{try{const fileInfo="stat"in file&&"body"in file?file:await this.loadFileWithInfo(storeFilePath);if(fileInfo.deleted)throw new Error(`Hidden file:${storeFilePath} is deleted. This should not be occurred.`);const baseData=await this.__loadBaseSaveData(storeFilePath,!0);if(!1===baseData)throw new Error("Failed to load base data");if(baseData._rev&&!forceWrite&&await isDocContentSame(readAsBlob(baseData),fileInfo.body)){this.updateLastProcessed(storeFilePath,baseData,fileInfo.stat);return}const saveData={...baseData,data:fileInfo.body,mtime:fileInfo.stat.mtime,size:fileInfo.stat.size,children:[],deleted:!1,type:baseData.datatype},ret=await this.localDatabase.putDBEntry(saveData);if(ret&&ret.ok){saveData._rev=ret.rev;this.updateLastProcessed(storeFilePath,saveData,fileInfo.stat)}const success=ret&&ret.ok;this._log(`STORAGE --\x3e DB:${storageFilePath}: (hidden) ${success?"Done":"Failed"}`);return success}catch(ex){this._log(`STORAGE --\x3e DB:${storageFilePath}: (hidden) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}))}async deleteInternalFileOnDatabase(filenameSrc,forceWrite=!1){const storeFilePath=filenameSrc,storageFilePath=filenameSrc,displayFileName=filenameSrc,prefixedFileName=addPrefix(storeFilePath,ICHeader),mtime=(new Date).getTime();if(!await this.services.vault.isIgnoredByIgnoreFile(storageFilePath))return await serialized("file-"+prefixedFileName,(async()=>{try{const baseData=await this.__loadBaseSaveData(storeFilePath,!1);if(!1===baseData)throw new Error("Failed to load base data during deleting");if(void 0!==baseData._conflicts)for(const conflictRev of baseData._conflicts){await this.localDatabase.removeRevision(baseData._id,conflictRev);this._log(`STORAGE -x> DB: ${displayFileName}: (hidden) conflict removed ${baseData._rev} => ${conflictRev}`,LOG_LEVEL_VERBOSE)}if(baseData.deleted){this._log(`STORAGE -x> DB: ${displayFileName}: (hidden) already deleted`,LOG_LEVEL_VERBOSE);this.updateLastProcessedDeletion(storeFilePath,baseData);return!0}const saveData={...baseData,mtime,size:0,children:[],deleted:!0,type:baseData.datatype},ret=await this.localDatabase.putRaw(saveData);if(ret&&ret.ok){this._log(`STORAGE -x> DB: ${displayFileName}: (hidden) Done`);saveData._rev=ret.rev;this.updateLastProcessedDeletion(storeFilePath,saveData);return!0}this._log(`STORAGE -x> DB: ${displayFileName}: (hidden) Failed`);return!1}catch(ex){this._log(`STORAGE -x> DB: ${displayFileName}: (hidden) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}))}async extractInternalFileFromDatabase(storageFilePath,force=!1,metaEntry,preventDoubleProcess=!0,onlyNew=!1,includeDeletion=!0){const prefixedFileName=addPrefix(storageFilePath,ICHeader);if(!await this.services.vault.isIgnoredByIgnoreFile(storageFilePath))return await serialized("file-"+prefixedFileName,(async()=>{var _a8,_b5;try{const metaOnDB=metaEntry||await this.localDatabase.getDBEntryMeta(prefixedFileName,{conflicts:!0},!0);if(!1===metaOnDB)throw new Error(`File not found on database.:${storageFilePath}`);if(null==(_a8=null==metaOnDB?void 0:metaOnDB._conflicts)?void 0:_a8.length){this._log(`Hidden file ${storageFilePath} has conflicted revisions, to keep in safe, writing to storage has been prevented`,LOG_LEVEL_INFO);return!1}if(preventDoubleProcess){const key3=this.docToKey(metaOnDB);if(this.getLastProcessedDatabaseKey(storageFilePath)==key3&&!force){this._log(`STORAGE <-- DB: ${storageFilePath}: skipped (hidden, overwrite${force?", force":""}) (Previously processed)`);return}}if(onlyNew){const dbMTime=getComparingMTime(metaOnDB,includeDeletion),storageStat=await this.plugin.storageAccess.statHidden(storageFilePath),storageMTimeActual=null!=(_b5=null==storageStat?void 0:storageStat.mtime)?_b5:0;if(compareMTime(0==storageMTimeActual?this.getLastProcessedFileMTime(storageFilePath):storageMTimeActual,dbMTime)!=TARGET_IS_NEW){this._log(`STORAGE <-- DB: ${storageFilePath}: skipped (hidden, overwrite${force?", force":""}) (Not new)`);this.updateLastProcessedDatabase(storageFilePath,metaOnDB);storageStat&&this.updateLastProcessedFile(storageFilePath,storageStat);return}}if(metaOnDB.deleted||metaOnDB._deleted){const result=await this.__deleteFile(storageFilePath);if("OK"==result){this.updateLastProcessedDeletion(storageFilePath,metaOnDB);return!0}if("ALREADY"==result){this.updateLastProcessedDatabase(storageFilePath,metaOnDB);return!0}return!1}{const fileOnDB=await this.localDatabase.getDBEntryFromMeta(metaOnDB,!1,!0);if(!1===fileOnDB)throw new Error(`Failed to read file from database:${storageFilePath}`);const resultStat=await this.__writeFile(storageFilePath,fileOnDB,force);if(resultStat){this.updateLastProcessed(storageFilePath,metaOnDB,resultStat);this.queueNotification(storageFilePath);this._log(`STORAGE <-- DB: ${storageFilePath}: written (hidden, overwrite${force?", force":""}) Done`);return!0}}return!1}catch(ex){this._log(`STORAGE <-- DB: ${storageFilePath}: written (hidden, overwrite${force?", force":""}) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}))}async __checkIsNeedToWriteFile(storageFilePath,content){try{const storageContent=await this.plugin.storageAccess.readHiddenFileAuto(storageFilePath);return!await isDocContentSame(storageContent,content)}catch(ex){this._log(`Cannot check the content of ${storageFilePath}`);this._log(ex,LOG_LEVEL_VERBOSE);return!0}}async __writeFile(storageFilePath,fileOnDB,force){try{const statBefore=await this.plugin.storageAccess.statHidden(storageFilePath),isExist=null!=statBefore,writeContent=readContent(fileOnDB);await this.ensureDir(storageFilePath);if(!(force||!isExist||isExist&&await this.__checkIsNeedToWriteFile(storageFilePath,writeContent))){this._log(`STORAGE <-- DB: ${storageFilePath}: skipped (hidden) Not changed`,LOG_LEVEL_DEBUG);return statBefore}const writeResultStat=await this.writeFile(storageFilePath,writeContent,{mtime:fileOnDB.mtime,ctime:fileOnDB.ctime});if(null==writeResultStat){this._log(`STORAGE <-- DB: ${storageFilePath}: written (hidden,new${force?", force":""}) Failed (writeResult)`);return!1}this._log(`STORAGE <-- DB: ${storageFilePath}: written (hidden, overwrite${force?", force":""})`);return writeResultStat}catch(ex){this._log(`STORAGE <-- DB: ${storageFilePath}: written (hidden, overwrite${force?", force":""}) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async __deleteFile(storageFilePath){const result=await this.__removeFile(storageFilePath);if(!1===result){this._log(`STORAGE <x- DB: ${storageFilePath}: deleting (hidden) Failed`);return!1}"OK"===result&&await this.triggerEvent(storageFilePath);this._log(`STORAGE <x- DB: ${storageFilePath}: deleting (hidden) ${"OK"==result?"Done":"Already not found"}`);return result}async _allAskUsingOptionalSyncFeature(opt){await this.__askHiddenFileConfiguration(opt);return!0}async __askHiddenFileConfiguration(opt){const message=`Would you like to enable **Hidden File Synchronization**?\n\n> [!DETAILS]-\n> This feature allows you to synchronize all hidden files without any user interaction.\n> To enable this feature, you should choose one of the following options:\n${opt.enableFetch?"> - Fetch: Use the files stored from other devices. Choose this option if you have already configured hidden file synchronization on those devices and wish to accept their files.\n":""}${opt.enableOverwrite?"> - Overwrite: Use the files from this device. Select this option if you want to overwrite the files stored on other devices.\n":""}> - Merge: Merge the files from this device with those on other devices. Choose this option if you wish to combine files from multiple sources.\n> However, please be reminded that merging may cause conflicts if the files are not identical. Additionally, this process may occur within the same folder, potentially breaking your plug-in or theme settings that comprise multiple files.\n\n\n> [!IMPORTANT]\n> Please keep in mind that enabling this feature alongside customisation sync may override certain behaviors.`,choices=[];(null==opt?void 0:opt.enableFetch)&&choices.push("Fetch");(null==opt?void 0:opt.enableOverwrite)&&choices.push("Overwrite");choices.push("Merge");choices.push("Disable");const ret=await this.plugin.confirm.confirmWithMessage("Hidden file sync",message,choices,"Disable",40);"Fetch"==ret?await this.configureHiddenFileSync("FETCH"):"Overwrite"==ret?await this.configureHiddenFileSync("OVERWRITE"):"Merge"==ret?await this.configureHiddenFileSync("MERGE"):"Disable"==ret&&await this.configureHiddenFileSync("DISABLE_HIDDEN")}_allSuspendExtraSync(){if(this.plugin.settings.syncInternalFiles){this._log("Hidden file synchronization have been temporarily disabled. Please enable them after the fetching, if you need them.",LOG_LEVEL_NOTICE);this.plugin.settings.syncInternalFiles=!1}return Promise.resolve(!0)}async _allConfigureOptionalSyncFeature(mode){await this.configureHiddenFileSync(mode);return!0}async configureHiddenFileSync(mode){if("FETCH"==mode||"OVERWRITE"==mode||"MERGE"==mode||"DISABLE"==mode||"DISABLE_HIDDEN"==mode)if("DISABLE"!=mode&&"DISABLE_HIDDEN"!=mode){this._log("Gathering files for enabling Hidden File Sync",LOG_LEVEL_NOTICE);"FETCH"==mode?await this.initialiseInternalFileSync("pullForce",!0):"OVERWRITE"==mode?await this.initialiseInternalFileSync("pushForce",!0):"MERGE"==mode&&await this.initialiseInternalFileSync("safe",!0);this.plugin.settings.useAdvancedMode=!0;this.plugin.settings.syncInternalFiles=!0;await this.plugin.saveSettings();this._log("Done! Restarting the app is strongly recommended!",LOG_LEVEL_NOTICE)}else{this.plugin.settings.syncInternalFiles=!1;await this.plugin.saveSettings()}}async scanInternalFileNames(){const findRoot=this.app.vault.getRoot().path;return await this.getFiles(findRoot,(path2=>this.isTargetFile(path2)))}async scanInternalFiles(){var _a8,_b5,_c3,_d2,_e2,_f;const files=(await this.scanInternalFileNames()).map((async e3=>({path:e3,stat:await this.plugin.storageAccess.statHidden(e3)}))),result=[];for(const f4 of files){const w2=await f4;if(await this.services.vault.isIgnoredByIgnoreFile(w2.path))continue;const mtime=null!=(_b5=null==(_a8=w2.stat)?void 0:_a8.mtime)?_b5:0,ctime=null!=(_d2=null==(_c3=w2.stat)?void 0:_c3.ctime)?_d2:mtime,size=null!=(_f=null==(_e2=w2.stat)?void 0:_e2.size)?_f:0;result.push({...w2,mtime,ctime,size})}return result}async getFiles(path2,checkFunction){let w2;try{w2=await this.app.vault.adapter.list(path2)}catch(ex){this._log(`Could not traverse(HiddenSync):${path2}`,LOG_LEVEL_INFO);this._log(ex,LOG_LEVEL_VERBOSE);return[]}let files=[];for(const file of w2.files)await checkFunction(file)&&files.push(file);for(const v2 of w2.folders)await checkFunction(v2)&&(files=files.concat(await this.getFiles(v2,checkFunction)));return files}onBindFunction(core,services){services.appLifecycle.handleOnSettingLoaded(this._everyOnloadAfterLoadSettings.bind(this));services.fileProcessing.handleOptionalFileEvent(this._anyProcessOptionalFileEvent.bind(this));services.conflict.handleGetOptionalConflictCheckMethod(this._anyGetOptionalConflictCheckMethod.bind(this));services.replication.handleProcessOptionalSynchroniseResult(this._anyProcessOptionalSyncFiles.bind(this));services.setting.handleOnRealiseSetting(this._everyRealizeSettingSyncMode.bind(this));services.appLifecycle.handleOnResuming(this._everyOnResumeProcess.bind(this));services.replication.handleBeforeReplicate(this._everyBeforeReplicate.bind(this));services.databaseEvents.handleDatabaseInitialised(this._everyOnDatabaseInitialized.bind(this));services.setting.handleSuspendExtraSync(this._allSuspendExtraSync.bind(this));services.setting.handleSuggestOptionalFeatures(this._allAskUsingOptionalSyncFeature.bind(this));services.setting.handleEnableOptionalFeature(this._allConfigureOptionalSyncFeature.bind(this))}};t=new Uint8Array([0,97,115,109,1,0,0,0,1,48,8,96,3,127,127,127,0,96,3,127,127,127,1,127,96,2,127,127,0,96,2,127,126,0,96,1,127,1,127,96,1,127,1,126,96,3,127,127,126,1,126,96,3,126,127,127,1,126,3,11,10,1,1,2,0,4,6,7,3,0,5,5,3,1,0,1,7,85,9,3,109,101,109,2,0,5,120,120,104,51,50,0,0,6,105,110,105,116,51,50,0,2,8,117,112,100,97,116,101,51,50,0,3,8,100,105,103,101,115,116,51,50,0,4,5,120,120,104,54,52,0,5,6,105,110,105,116,54,52,0,7,8,117,112,100,97,116,101,54,52,0,8,8,100,105,103,101,115,116,54,52,0,9,10,211,23,10,242,1,1,4,127,32,0,32,1,106,33,3,32,1,65,16,79,4,127,32,3,65,16,107,33,6,32,2,65,168,136,141,161,2,106,33,3,32,2,65,247,148,175,175,120,106,33,4,32,2,65,177,243,221,241,121,107,33,5,3,64,32,0,40,2,0,65,247,148,175,175,120,108,32,3,106,65,13,119,65,177,243,221,241,121,108,33,3,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,32,4,106,65,13,119,65,177,243,221,241,121,108,33,4,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,32,2,106,65,13,119,65,177,243,221,241,121,108,33,2,32,0,65,4,106,34,0,40,2,0,65,247,148,175,175,120,108,32,5,106,65,13,119,65,177,243,221,241,121,108,33,5,32,0,65,4,106,34,0,32,6,77,13,0,11,32,2,65,12,119,32,5,65,18,119,106,32,4,65,7,119,106,32,3,65,1,119,106,5,32,2,65,177,207,217,178,1,106,11,32,1,106,32,0,32,1,65,15,113,16,1,11,146,1,0,32,1,32,2,106,33,2,3,64,32,1,65,4,106,32,2,75,69,4,64,32,1,40,2,0,65,189,220,202,149,124,108,32,0,106,65,17,119,65,175,214,211,190,2,108,33,0,32,1,65,4,106,33,1,12,1,11,11,3,64,32,1,32,2,79,69,4,64,32,1,45,0,0,65,177,207,217,178,1,108,32,0,106,65,11,119,65,177,243,221,241,121,108,33,0,32,1,65,1,106,33,1,12,1,11,11,32,0,65,15,118,32,0,115,65,247,148,175,175,120,108,34,0,32,0,65,13,118,115,65,189,220,202,149,124,108,34,0,32,0,65,16,118,115,11,63,0,32,0,65,8,106,32,1,65,168,136,141,161,2,106,54,2,0,32,0,65,12,106,32,1,65,247,148,175,175,120,106,54,2,0,32,0,65,16,106,32,1,54,2,0,32,0,65,20,106,32,1,65,177,243,221,241,121,107,54,2,0,11,211,4,1,6,127,32,1,32,2,106,33,6,32,0,65,24,106,33,5,32,0,65,40,106,40,2,0,33,3,32,0,32,0,40,2,0,32,2,106,54,2,0,32,0,65,4,106,34,4,32,4,40,2,0,32,2,65,16,79,32,0,40,2,0,65,16,79,114,114,54,2,0,32,2,32,3,106,65,16,73,4,64,32,3,32,5,106,32,1,32,2,252,10,0,0,32,0,65,40,106,32,2,32,3,106,54,2,0,15,11,32,3,4,64,32,3,32,5,106,32,1,65,16,32,3,107,34,2,252,10,0,0,32,0,65,8,106,34,3,40,2,0,32,5,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,4,32,3,32,4,54,2,0,32,0,65,12,106,34,3,40,2,0,32,5,65,4,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,4,32,3,32,4,54,2,0,32,0,65,16,106,34,3,40,2,0,32,5,65,8,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,4,32,3,32,4,54,2,0,32,0,65,20,106,34,3,40,2,0,32,5,65,12,106,40,2,0,65,247,148,175,175,120,108,106,65,13,119,65,177,243,221,241,121,108,33,4,32,3,32,4,54,2,0,32,0,65,40,106,65,0,54,2,0,32,1,32,2,106,33,1,11,32,1,32,6,65,16,107,77,4,64,32,6,65,16,107,33,8,32,0,65,8,106,40,2,0,33,2,32,0,65,12,106,40,2,0,33,3,32,0,65,16,106,40,2,0,33,4,32,0,65,20,106,40,2,0,33,7,3,64,32,1,40,2,0,65,247,148,175,175,120,108,32,2,106,65,13,119,65,177,243,221,241,121,108,33,2,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,32,3,106,65,13,119,65,177,243,221,241,121,108,33,3,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,32,4,106,65,13,119,65,177,243,221,241,121,108,33,4,32,1,65,4,106,34,1,40,2,0,65,247,148,175,175,120,108,32,7,106,65,13,119,65,177,243,221,241,121,108,33,7,32,1,65,4,106,34,1,32,8,77,13,0,11,32,0,65,8,106,32,2,54,2,0,32,0,65,12,106,32,3,54,2,0,32,0,65,16,106,32,4,54,2,0,32,0,65,20,106,32,7,54,2,0,11,32,1,32,6,73,4,64,32,5,32,1,32,6,32,1,107,34,1,252,10,0,0,32,0,65,40,106,32,1,54,2,0,11,11,97,1,1,127,32,0,65,16,106,40,2,0,33,1,32,0,65,4,106,40,2,0,4,127,32,1,65,12,119,32,0,65,20,106,40,2,0,65,18,119,106,32,0,65,12,106,40,2,0,65,7,119,106,32,0,65,8,106,40,2,0,65,1,119,106,5,32,1,65,177,207,217,178,1,106,11,32,0,40,2,0,106,32,0,65,24,106,32,0,65,40,106,40,2,0,16,1,11,157,4,2,1,127,3,126,32,0,32,1,106,33,3,32,1,65,32,79,4,126,32,3,65,32,107,33,3,32,2,66,135,149,175,175,152,182,222,155,158,127,124,66,207,214,211,190,210,199,171,217,66,124,33,4,32,2,66,207,214,211,190,210,199,171,217,66,124,33,5,32,2,66,0,124,33,6,32,2,66,135,149,175,175,152,182,222,155,158,127,125,33,2,3,64,32,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,4,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,4,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,5,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,5,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,6,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,0,65,8,106,34,0,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,2,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,2,32,0,65,8,106,34,0,32,3,77,13,0,11,32,6,66,12,137,32,2,66,18,137,124,32,5,66,7,137,124,32,4,66,1,137,124,32,4,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,32,5,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,32,6,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,32,2,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,5,32,2,66,197,207,217,178,241,229,186,234,39,124,11,32,1,173,124,32,0,32,1,65,31,113,16,6,11,137,2,0,32,1,32,2,106,33,2,3,64,32,1,65,8,106,32,2,77,4,64,32,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,32,0,133,66,27,137,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,33,0,32,1,65,8,106,33,1,12,1,11,11,32,1,65,4,106,32,2,77,4,64,32,1,53,2,0,66,135,149,175,175,152,182,222,155,158,127,126,32,0,133,66,23,137,66,207,214,211,190,210,199,171,217,66,126,66,249,243,221,241,153,246,153,171,22,124,33,0,32,1,65,4,106,33,1,11,3,64,32,1,32,2,73,4,64,32,1,49,0,0,66,197,207,217,178,241,229,186,234,39,126,32,0,133,66,11,137,66,135,149,175,175,152,182,222,155,158,127,126,33,0,32,1,65,1,106,33,1,12,1,11,11,32,0,66,33,136,32,0,133,66,207,214,211,190,210,199,171,217,66,126,34,0,32,0,66,29,136,133,66,249,243,221,241,153,246,153,171,22,126,34,0,32,0,66,32,136,133,11,88,0,32,0,65,8,106,32,1,66,135,149,175,175,152,182,222,155,158,127,124,66,207,214,211,190,210,199,171,217,66,124,55,3,0,32,0,65,16,106,32,1,66,207,214,211,190,210,199,171,217,66,124,55,3,0,32,0,65,24,106,32,1,55,3,0,32,0,65,32,106,32,1,66,135,149,175,175,152,182,222,155,158,127,125,55,3,0,11,132,5,2,3,127,4,126,32,1,32,2,106,33,5,32,0,65,40,106,33,4,32,0,65,200,0,106,40,2,0,33,3,32,0,32,0,41,3,0,32,2,173,124,55,3,0,32,2,32,3,106,65,32,73,4,64,32,3,32,4,106,32,1,32,2,252,10,0,0,32,0,65,200,0,106,32,2,32,3,106,54,2,0,15,11,32,3,4,64,32,3,32,4,106,32,1,65,32,32,3,107,34,2,252,10,0,0,32,0,65,8,106,34,3,41,3,0,32,4,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,3,32,6,55,3,0,32,0,65,16,106,34,3,41,3,0,32,4,65,8,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,3,32,6,55,3,0,32,0,65,24,106,34,3,41,3,0,32,4,65,16,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,3,32,6,55,3,0,32,0,65,32,106,34,3,41,3,0,32,4,65,24,106,41,3,0,66,207,214,211,190,210,199,171,217,66,126,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,3,32,6,55,3,0,32,0,65,200,0,106,65,0,54,2,0,32,1,32,2,106,33,1,11,32,1,65,32,106,32,5,77,4,64,32,5,65,32,107,33,2,32,0,65,8,106,41,3,0,33,6,32,0,65,16,106,41,3,0,33,7,32,0,65,24,106,41,3,0,33,8,32,0,65,32,106,41,3,0,33,9,3,64,32,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,6,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,6,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,7,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,7,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,8,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,8,32,1,65,8,106,34,1,41,3,0,66,207,214,211,190,210,199,171,217,66,126,32,9,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,33,9,32,1,65,8,106,34,1,32,2,77,13,0,11,32,0,65,8,106,32,6,55,3,0,32,0,65,16,106,32,7,55,3,0,32,0,65,24,106,32,8,55,3,0,32,0,65,32,106,32,9,55,3,0,11,32,1,32,5,73,4,64,32,4,32,1,32,5,32,1,107,34,1,252,10,0,0,32,0,65,200,0,106,32,1,54,2,0,11,11,200,2,1,5,126,32,0,65,24,106,41,3,0,33,1,32,0,41,3,0,34,2,66,32,90,4,126,32,0,65,8,106,41,3,0,34,3,66,1,137,32,0,65,16,106,41,3,0,34,4,66,7,137,124,32,1,66,12,137,32,0,65,32,106,41,3,0,34,5,66,18,137,124,124,32,3,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,32,4,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,32,1,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,32,5,66,207,214,211,190,210,199,171,217,66,126,66,0,124,66,31,137,66,135,149,175,175,152,182,222,155,158,127,126,133,66,135,149,175,175,152,182,222,155,158,127,126,66,227,220,202,149,252,206,242,245,133,127,124,5,32,1,66,197,207,217,178,241,229,186,234,39,124,11,32,2,124,32,0,65,40,106,32,2,66,31,131,167,16,6,11]);hashFunc=str=>fallbackMixedHashEach(str);!async function initHashFunc(){try{const{h32ToString}=await e();hashFunc=h32ToString;Logger("xxhash for plugin initialised",LOG_LEVEL_VERBOSE)}catch(ex){Logger("Could not initialise xxhash. fallback...",LOG_LEVEL_VERBOSE);Logger(ex);hashFunc=str=>fallbackMixedHashEach(str)}}();globalSlipBoard2=globalSlipBoard;import_diff_match_patch2=__toESM(require_diff_match_patch(),1);ConflictResolveModal=class extends import_obsidian.Modal{constructor(app,filename,diff,pluginPickMode,remoteName){super(app);this.response=CANCELLED;this.isClosed=!1;this.consumed=!1;this.title="Conflicting changes";this.pluginPickMode=!1;this.localName="Base";this.remoteName="Conflicted";this.result=diff;this.filename=filename;this.pluginPickMode=pluginPickMode||!1;if(this.pluginPickMode){this.title="Pick a version";this.remoteName=`${remoteName||"Remote"}`;this.localName="Local"}}onOpen(){const{contentEl}=this;globalSlipBoard2.submit("conflict-resolved",this.filename,CANCELLED);this.offEvent&&this.offEvent();this.offEvent=eventHub.onEvent("conflict-cancelled",(path2=>{path2===this.filename&&this.sendResponse(CANCELLED)}));this.titleEl.setText(this.title);contentEl.empty();contentEl.createEl("span",{text:this.filename});const div=contentEl.createDiv("");div.addClass("op-scrollable");let diff="";for(const v2 of this.result.diff){const x1=v2[0],x2=v2[1];x1==import_diff_match_patch2.DIFF_DELETE?diff+="<span class='deleted'>"+escapeStringToHTML(x2).replace(/\n/g,"<span class='ls-mark-cr'></span>\n")+"</span>":x1==import_diff_match_patch2.DIFF_EQUAL?diff+="<span class='normal'>"+escapeStringToHTML(x2).replace(/\n/g,"<span class='ls-mark-cr'></span>\n")+"</span>":x1==import_diff_match_patch2.DIFF_INSERT&&(diff+="<span class='added'>"+escapeStringToHTML(x2).replace(/\n/g,"<span class='ls-mark-cr'></span>\n")+"</span>")}const div2=contentEl.createDiv(""),date1=new Date(this.result.left.mtime).toLocaleString()+(this.result.left.deleted?" (Deleted)":""),date2=new Date(this.result.right.mtime).toLocaleString()+(this.result.right.deleted?" (Deleted)":"");div2.innerHTML=`<span class='deleted'><span class='conflict-dev-name'>${this.localName}</span>: ${date1}</span><br>\n<span class='added'><span class='conflict-dev-name'>${this.remoteName}</span>: ${date2}</span><br>`;contentEl.createEl("button",{text:`Use ${this.localName}`},(e3=>e3.addEventListener("click",(()=>this.sendResponse(this.result.right.rev))))).style.marginRight="4px";contentEl.createEl("button",{text:`Use ${this.remoteName}`},(e3=>e3.addEventListener("click",(()=>this.sendResponse(this.result.left.rev))))).style.marginRight="4px";this.pluginPickMode||(contentEl.createEl("button",{text:"Concat both"},(e3=>e3.addEventListener("click",(()=>this.sendResponse(LEAVE_TO_SUBSEQUENT))))).style.marginRight="4px");contentEl.createEl("button",{text:this.pluginPickMode?"Cancel":"Not now"},(e3=>e3.addEventListener("click",(()=>this.sendResponse(CANCELLED))))).style.marginRight="4px";diff=diff.replace(/\n/g,"<br>");diff.length>102400?div.innerText="(Too large diff to display)":div.innerHTML=diff}sendResponse(result){this.response=result;this.close()}onClose(){const{contentEl}=this;contentEl.empty();this.offEvent&&this.offEvent();if(!this.consumed){this.consumed=!0;globalSlipBoard2.submit("conflict-resolved",this.filename,this.response)}}async waitForResult(){await delay(100);return await globalSlipBoard2.awaitNext("conflict-resolved",this.filename)}};(function enable_legacy_mode_flag(){legacy_mode_flag=!0})();root_3=from_html("<option> </option>");root_62=from_html('<button class="svelte-14nm4oc">🗃️</button>');root_7=from_html('<button class="svelte-14nm4oc">⮂</button>');root_8=from_html('<button disabled class="svelte-14nm4oc"></button>');root_42=from_html('<!> <button class="svelte-14nm4oc">✓</button>',1);root_9=from_html('<button disabled class="svelte-14nm4oc"></button> <button disabled class="svelte-14nm4oc"></button>',1);root_11=from_html('<button class="svelte-14nm4oc">🗑️</button>');root_122=from_html('<button class="svelte-14nm4oc">📑</button>');root_22=from_html('<span class="chip-wrap svelte-14nm4oc"><span class="chip modified svelte-14nm4oc"> </span> <span class="chip content svelte-14nm4oc"> </span> <span class="chip version svelte-14nm4oc"> </span></span> <select><option>-</option><!></select> <!> <!>',1);root_13=from_html('<span class="spacer svelte-14nm4oc"></span> <!>',1);root_132=from_html('<span class="spacer svelte-14nm4oc"></span> <span class="message even svelte-14nm4oc">All the same or non-existent</span> <button disabled class="svelte-14nm4oc"></button> <button disabled class="svelte-14nm4oc"></button>',1);$$css3={hash:"svelte-14nm4oc",code:'.spacer.svelte-14nm4oc {min-width:1px;flex-grow:1;}button.svelte-14nm4oc {margin:2px 4px;min-width:3em;max-width:4em;}button.svelte-14nm4oc:disabled {border:none;box-shadow:none;background-color:transparent;visibility:collapse;}button.svelte-14nm4oc:disabled:hover {border:none;box-shadow:none;background-color:transparent;visibility:collapse;}span.message.svelte-14nm4oc {color:var(--text-muted);font-size:var(--font-ui-smaller);padding:0 1em;line-height:var(--line-height-tight);}\n /* span.messages {\n display: flex;\n flex-direction: column;\n align-items: center;\n } */.is-mobile .spacer.svelte-14nm4oc {margin-left:auto;}.chip-wrap.svelte-14nm4oc {display:flex;gap:2px;flex-direction:column;justify-content:center;align-items:flex-start;}.chip.svelte-14nm4oc {display:inline-block;border-radius:2px;font-size:0.8em;padding:0 4px;margin:0 2px;border-color:var(--tag-border-color);background-color:var(--tag-background);color:var(--tag-color);}.chip.svelte-14nm4oc:empty {display:none;}.chip.svelte-14nm4oc:not(:empty)::before {min-width:1.8em;display:inline-block;}.chip.content.svelte-14nm4oc:not(:empty)::before {content:"📄: ";}.chip.version.svelte-14nm4oc:not(:empty)::before {content:"🏷️: ";}.chip.modified.svelte-14nm4oc:not(:empty)::before {content:"📅: ";}'};root_14=from_html('<button class="svelte-10jah2g">Reload</button>');root_23=from_html("<span> </span>");root_32=from_html('<div class="center svelte-10jah2g">No Items.</div>');root_82=from_html('<div class="statusnote svelte-10jah2g"> </div>');root_63=from_html('<div><div class="title svelte-10jah2g"><button class="status svelte-10jah2g"> </button> <span class="name"> </span></div> <div class="body svelte-10jah2g"><!></div></div>');root_52=from_html('<div><h3 class="svelte-10jah2g"> </h3> <!></div>');root_133=from_html('<div class="statusnote svelte-10jah2g"> </div>');root_15=from_html('<div class="statusnote svelte-10jah2g"> </div>');root_18=from_html('<div class="statusnote svelte-10jah2g"> </div>');root_16=from_html('<div><div class="filetitle svelte-10jah2g"><button class="status svelte-10jah2g"> </button> <span class="name">Other files</span></div> <div class="body svelte-10jah2g"><!></div></div>');root_112=from_html('<div><div class="filetitle svelte-10jah2g"><button class="status svelte-10jah2g"> </button> <span class="name">MAIN</span></div> <div class="body svelte-10jah2g"><!></div></div> <div><div class="filetitle svelte-10jah2g"><button class="status svelte-10jah2g"> </button> <span class="name">DATA</span></div> <div class="body svelte-10jah2g"><!></div></div> <!>',1);root_19=from_html('<div class="noterow svelte-10jah2g"><div class="statusnote svelte-10jah2g"> </div></div>');root_92=from_html('<div><div class="title svelte-10jah2g"><button class="status svelte-10jah2g"> </button> <span class="name"> </span></div> <div class="body svelte-10jah2g"><!></div></div> <!>',1);root_43=from_html('<!> <div><h3 class="svelte-10jah2g">Plugins</h3> <!></div>',1);root_21=from_html("<option> </option>");root_20=from_html('<div class="buttons svelte-10jah2g"><div><h3 class="svelte-10jah2g">Maintenance Commands</h3> <div class="maintenancerow svelte-10jah2g"><label for="" class="svelte-10jah2g">Delete All of</label> <select></select> <button class="status svelte-10jah2g">🗑️</button></div></div></div>');root3=from_html('<div class="buttonsWrap svelte-10jah2g"><div class="buttons svelte-10jah2g"><button class="svelte-10jah2g">Scan changes</button> <button class="svelte-10jah2g">Sync once</button> <button class="svelte-10jah2g">Refresh</button> <!></div> <div class="buttons svelte-10jah2g"><button class="svelte-10jah2g">Select All Shiny</button> <button class="svelte-10jah2g"></button> <button class="svelte-10jah2g">Deselect all</button> <button class="mod-cta svelte-10jah2g">Apply All Selected</button></div></div> <div class="loading svelte-10jah2g"><!></div> <div class="list svelte-10jah2g"><!></div> <!> <div class="buttons svelte-10jah2g"><label class="svelte-10jah2g"><span class="svelte-10jah2g">Hide not applicable items</span><input type="checkbox"/></label></div> <div class="buttons svelte-10jah2g"><label class="svelte-10jah2g"><span class="svelte-10jah2g">Maintenance mode</span><input type="checkbox"/></label></div>',1);$$css4={hash:"svelte-10jah2g",code:".buttonsWrap.svelte-10jah2g {padding-bottom:4px;}h3.svelte-10jah2g {position:sticky;top:0;background-color:var(--modal-background);}.labelrow.svelte-10jah2g {margin-left:0.4em;display:flex;justify-content:flex-start;align-items:center;border-top:1px solid var(--background-modifier-border);padding:4px;flex-wrap:wrap;}.filerow.svelte-10jah2g {margin-left:1.25em;display:flex;justify-content:flex-start;align-items:center;padding-right:4px;flex-wrap:wrap;}.filerow.hideeven.svelte-10jah2g:has(.even),\n .labelrow.hideeven.svelte-10jah2g:has(.even) {display:none;}.noterow.svelte-10jah2g {min-height:2em;display:flex;}button.status.svelte-10jah2g {flex-grow:0;margin:2px 4px;min-width:3em;max-width:4em;}.statusnote.svelte-10jah2g {display:flex;justify-content:flex-end;padding-right:var(--size-4-12);align-items:center;min-width:10em;flex-grow:1;}.list.svelte-10jah2g {overflow-y:auto;}.title.svelte-10jah2g {color:var(--text-normal);font-size:var(--font-ui-medium);line-height:var(--line-height-tight);margin-right:auto;}.body.svelte-10jah2g {\n /* margin-left: 0.4em; */margin-left:auto;display:flex;justify-content:flex-start;align-items:center;\n /* flex-wrap: wrap; */}.filetitle.svelte-10jah2g {color:var(--text-normal);font-size:var(--font-ui-medium);line-height:var(--line-height-tight);margin-right:auto;}.buttons.svelte-10jah2g {display:flex;flex-direction:row;justify-content:flex-end;margin-top:8px;flex-wrap:wrap;}.buttons.svelte-10jah2g > button:where(.svelte-10jah2g) {margin-left:4px;width:auto;}label.svelte-10jah2g {display:flex;justify-content:center;align-items:center;}label.svelte-10jah2g > span:where(.svelte-10jah2g) {margin-right:0.25em;}.is-mobile .title.svelte-10jah2g,\n .is-mobile .filetitle.svelte-10jah2g {width:100%;}.center.svelte-10jah2g {display:flex;justify-content:center;align-items:center;min-height:3em;}.maintenancerow.svelte-10jah2g {display:flex;justify-content:flex-end;align-items:center;}.maintenancerow.svelte-10jah2g label:where(.svelte-10jah2g) {margin-right:0.5em;margin-left:0.5em;}.loading.svelte-10jah2g {transition:height 0.25s ease-in-out;transition-delay:4ms;overflow-y:hidden;flex-shrink:0;display:flex;justify-content:flex-start;align-items:center;}.loading.svelte-10jah2g:empty {height:0px;transition:height 0.25s ease-in-out;transition-delay:1s;}.loading.svelte-10jah2g:not(:empty) {height:2em;transition:height 0.25s ease-in-out;transition-delay:0;}"};PluginDialogModal=class extends import_obsidian.Modal{isOpened(){return null!=this.component}constructor(app,plugin3){super(app);this.plugin=plugin3}onOpen(){const{contentEl}=this;this.contentEl.style.overflow="auto";this.contentEl.style.display="flex";this.contentEl.style.flexDirection="column";this.titleEl.setText("Customization Sync (Beta3)");this.component||(this.component=mount(PluginPane,{target:contentEl,props:{plugin:this.plugin}}))}onClose(){if(this.component){unmount(this.component);this.component=void 0}}};d="";d2="\n";DUMMY_HEAD=serialize({category:"CONFIG",name:"migrated",files:[],mtime:0,term:"-",displayName:"MIRAGED"});DUMMY_END=d+d2+"";pluginList=writable([]);pluginIsEnumerating=writable(!1);pluginV2Progress=writable(0);pluginManifestStore=writable(pluginManifests=new Map);PluginDataExDisplayV2=class{constructor(data){this.files=[];this.documentPath=`${data.documentPath}`;this.category=`${data.category}`;this.name=`${data.name}`;this.term=`${data.term}`;this.files=[...data.files];this.confKey=`${categoryToFolder(this.category,this.term)}${this.name}`;this.applyLoadedManifest()}async setFile(file){const old=this.files.find((e3=>e3.filename==file.filename));if(old){if(old.mtime==file.mtime&&await isDocContentSame(old.data,file.data))return;this.files=this.files.filter((e3=>e3.filename!=file.filename))}this.files.push(file);"manifest.json"==file.filename&&this.applyLoadedManifest()}deleteFile(filename){this.files=this.files.filter((e3=>e3.filename!=filename))}applyLoadedManifest(){const manifest=pluginManifests.get(this.confKey);if(manifest){this._displayName=manifest.name;"PLUGIN_MAIN"!=this.category&&"THEME"!=this.category||(this._version=null==manifest?void 0:manifest.version)}}get displayName(){return this._displayName||this.name}get version(){return this._version}get mtime(){return~~this.files.reduce(((a2,b3)=>a2+b3.mtime),0)/this.files.length}};ConfigSync=class extends LiveSyncCommands{constructor(plugin3){super(plugin3);this.pluginDialog=void 0;this.periodicPluginSweepProcessor=new PeriodicProcessor(this.plugin,(async()=>await this.scanAllConfigFiles(!1)));this.pluginList=[];this.addRibbonIcon=this.plugin.addRibbonIcon.bind(this.plugin);this.pluginScanProcessor=new QueueProcessor((async v2=>{const plugin3=v2[0];if(this.useV2){await this.migrateV1ToV2(!1,plugin3);return[]}const path2=plugin3.path||this.getPath(plugin3),oldEntry=this.pluginList.find((e3=>e3.documentPath==path2));if(oldEntry&&oldEntry.mtime==plugin3.mtime)return[];try{const pluginData=await this.loadPluginData(path2);if(pluginData){let newList=[...this.pluginList];newList=newList.filter((x2=>x2.documentPath!=pluginData.documentPath));newList.push(pluginData);this.pluginList=newList;pluginList.set(newList)}return[]}catch(ex){this._log(`Something happened at enumerating customization :${path2}`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}return[]}),{suspended:!1,batchSize:1,concurrentLimit:10,delay:100,yieldThreshold:10,maintainDelay:!1,totalRemainingReactiveSource:pluginScanningCount}).startPipeline();this.pluginScanProcessorV2=new QueueProcessor((async v2=>{const plugin3=v2[0],path2=plugin3.path||this.getPath(plugin3),oldEntry=this.pluginList.find((e3=>e3.documentPath==path2));if(oldEntry&&oldEntry.mtime==plugin3.mtime)return[];try{const pluginData=await this.loadPluginData(path2);if(pluginData){let newList=[...this.pluginList];newList=newList.filter((x2=>x2.documentPath!=pluginData.documentPath));newList.push(pluginData);this.pluginList=newList;pluginList.set(newList)}return[]}catch(ex){this._log(`Something happened at enumerating customization :${path2}`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}return[]}),{suspended:!1,batchSize:1,concurrentLimit:10,delay:100,yieldThreshold:10,maintainDelay:!1,totalRemainingReactiveSource:pluginScanningCount}).startPipeline();this.loadedManifest_mTime=new Map;this.updatingV2Count=0;this.recentProcessedInternalFiles=[];pluginScanningCount.onChanged((e3=>{const total=e3.value;pluginIsEnumerating.set(0!=total)}))}get kvDB(){return this.plugin.kvDB}get useV2(){return this.plugin.settings.usePluginSyncV2}get useSyncPluginEtc(){return this.plugin.settings.usePluginEtc}isThisModuleEnabled(){return this.plugin.settings.usePluginSync}showPluginSyncModal(){if(this.isThisModuleEnabled())if(this.pluginDialog)this.pluginDialog.open();else{this.pluginDialog=new PluginDialogModal(this.app,this.plugin);this.pluginDialog.open()}}hidePluginSyncModal(){if(null!=this.pluginDialog){this.pluginDialog.close();this.pluginDialog=void 0}}onunload(){var _a8;this.hidePluginSyncModal();null==(_a8=this.periodicPluginSweepProcessor)||_a8.disable()}onload(){(0,import_obsidian.addIcon)("custom-sync",'<g transform="rotate(-90 75 218)" fill="currentColor" fill-rule="evenodd">\n <path d="m272 166-9.38 9.38 9.38 9.38 9.38-9.38c1.96-1.93 5.11-1.9 7.03 0.058 1.91 1.94 1.91 5.04 0 6.98l-9.38 9.38 5.86 5.86-11.7 11.7c-8.34 8.35-21.4 9.68-31.3 3.19l-3.84 3.98c-8.45 8.7-20.1 13.6-32.2 13.6h-5.55v-9.95h5.55c9.43-0.0182 18.5-3.84 25-10.6l3.95-4.09c-6.54-9.86-5.23-23 3.14-31.3l11.7-11.7 5.86 5.86 9.38-9.38c1.96-1.93 5.11-1.9 7.03 0.0564 1.91 1.93 1.91 5.04 2e-3 6.98z"/>\n </g>');this.plugin.addCommand({id:"livesync-plugin-dialog-ex",name:"Show customization sync dialog",callback:()=>{this.showPluginSyncModal()}});this.addRibbonIcon("custom-sync",$msg("cmdConfigSync.showCustomizationSync"),(()=>{this.showPluginSyncModal()})).addClass("livesync-ribbon-showcustom");eventHub.onEvent(EVENT_REQUEST_OPEN_PLUGIN_SYNC_DIALOG2,(()=>this.showPluginSyncModal()))}getFileCategory(filePath){return 2==filePath.split("/").length&&filePath.endsWith(".json")?"CONFIG":4==filePath.split("/").length&&filePath.startsWith(`${this.app.vault.configDir}/themes/`)?"THEME":filePath.startsWith(`${this.app.vault.configDir}/snippets/`)&&filePath.endsWith(".css")?"SNIPPET":filePath.startsWith(`${this.app.vault.configDir}/plugins/`)?filePath.endsWith("/styles.css")||filePath.endsWith("/manifest.json")||filePath.endsWith("/main.js")?"PLUGIN_MAIN":filePath.endsWith("/data.json")?"PLUGIN_DATA":this.useV2&&this.useSyncPluginEtc?"PLUGIN_ETC":"":""}isTargetPath(filePath){return!!filePath.startsWith(this.app.vault.configDir)&&""!=this.getFileCategory(filePath)}async _everyOnDatabaseInitialized(showNotice){if(!this.isThisModuleEnabled())return!0;try{this._log("Scanning customizations...");await this.scanAllConfigFiles(showNotice);this._log("Scanning customizations : done")}catch(ex){this._log("Scanning customizations : failed");this._log(ex,LOG_LEVEL_VERBOSE)}return!0}async _everyBeforeReplicate(showNotice){if(!this.isThisModuleEnabled())return!0;if(this.settings.autoSweepPlugins){await this.scanAllConfigFiles(showNotice);return!0}return!0}async _everyOnResumeProcess(){if(!this.isThisModuleEnabled())return!0;if(this._isMainSuspended())return!0;this.settings.autoSweepPlugins&&await this.scanAllConfigFiles(!1);this.periodicPluginSweepProcessor.enable(this.settings.autoSweepPluginsPeriodic&&!this.settings.watchInternalFileChanges?6e4:0);return!0}_everyAfterResumeProcess(){const q2=activeDocument.querySelector(".livesync-ribbon-showcustom");null==q2||q2.toggleClass("sls-hidden",!this.isThisModuleEnabled());return Promise.resolve(!0)}async reloadPluginList(showMessage){this.pluginList=[];this.loadedManifest_mTime.clear();pluginList.set(this.pluginList);await this.updatePluginList(showMessage)}async loadPluginData(path2){const wx=await this.localDatabase.getDBEntry(path2,void 0,!1,!1);if(wx){const data=deserialize(getDocDataAsArray(wx.data),{}),xFiles=[];let missingHash=!1;for(const file of data.files){const work={...file,data:[]};if(!file.hash){const hash3=digestHash(getDocDataAsArray(work.data));file.hash=hash3;missingHash=!0}work.data=[file.hash];xFiles.push(work)}if(missingHash){this._log(`Digest created for ${path2} to improve checking`,LOG_LEVEL_VERBOSE);wx.data=serialize(data);fireAndForget((()=>this.localDatabase.putDBEntry(createSavingEntryFromLoadedEntry(wx))))}return{...data,documentPath:this.getPath(wx),files:xFiles}}return!1}filenameToUnifiedKey(path2,termOverRide){const term=termOverRide||this.services.setting.getDeviceAndVaultName(),category=this.getFileCategory(path2),name="CONFIG"==category||"SNIPPET"==category?path2.split("/").slice(-1)[0]:"PLUGIN_ETC"==category?path2.split("/").slice(-2).join("/"):path2.split("/").slice(-2)[0];return`${ICXHeader}${term}/${category}/${name}.md`}filenameWithUnifiedKey(path2,termOverRide){const term=termOverRide||this.services.setting.getDeviceAndVaultName(),category=this.getFileCategory(path2),name="CONFIG"==category||"SNIPPET"==category?path2.split("/").slice(-1)[0]:path2.split("/").slice(-2)[0],baseName="CONFIG"==category||"SNIPPET"==category?name:path2.split("/").slice(3).join("/");return`${ICXHeader}${term}/${category}/${name}%${baseName}`}unifiedKeyPrefixOfTerminal(termOverRide){const term=termOverRide||this.services.setting.getDeviceAndVaultName();return`${ICXHeader}${term}/`}parseUnifiedPath(unifiedPath){const[device,category,...rest]=stripAllPrefixes(unifiedPath).split("/"),relativePath=rest.join("/"),[key3,filename]=relativePath.split("%");return{device,category,key:key3,filename,pathV1:unifiedPath.split("%")[0]+".md"}}async createPluginDataExFileV2(unifiedPathV2,loaded){const{category,key:key3,filename,device}=this.parseUnifiedPath(unifiedPathV2);if(!loaded){const d4=await this.localDatabase.getDBEntry(unifiedPathV2);if(!d4){this._log(`The file ${unifiedPathV2} is not found`,LOG_LEVEL_VERBOSE);return!1}if(!isLoadedEntry(d4)){this._log(`The file ${unifiedPathV2} is not a note`,LOG_LEVEL_VERBOSE);return!1}loaded=d4}const confKey=`${categoryToFolder(category,device)}${key3}`,relativeFilename=`${categoryToFolder(category,"")}${"CONFIG"==category||"SNIPPET"==category?"":key3+"/"}${filename}`.substring(1),dataSrc=getDocData(loaded.data),dataStart=dataSrc.indexOf(DUMMY_END),data=dataSrc.substring(dataStart+DUMMY_END.length),file={...loaded,hash:"",data:[base64ToString(data)],filename:relativeFilename,displayName:filename};if("manifest.json"==filename)if(this.loadedManifest_mTime.get(confKey)!=file.mtime&&null==pluginManifests.get(confKey)){try{const parsedManifest=JSON.parse(base64ToString(data));setManifest(confKey,parsedManifest);this.pluginList.filter((e3=>e3 instanceof PluginDataExDisplayV2&&e3.confKey==confKey)).forEach((e3=>e3.applyLoadedManifest()));pluginList.set(this.pluginList)}catch(ex){this._log(`The file ${loaded.path} seems to manifest, but could not be decoded as JSON`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}this.loadedManifest_mTime.set(confKey,file.mtime)}else{this.pluginList.filter((e3=>e3 instanceof PluginDataExDisplayV2&&e3.confKey==confKey)).forEach((e3=>e3.applyLoadedManifest()));pluginList.set(this.pluginList)}return file}createPluginDataFromV2(unifiedPathV2){const{category,device,key:key3,pathV1}=this.parseUnifiedPath(unifiedPathV2);if(""!=category)return new PluginDataExDisplayV2({documentPath:pathV1,category,name:key3,term:`${device}`,files:[],mtime:0})}async updatePluginListV2(showMessage,unifiedFilenameWithKey){try{this.updatingV2Count++;pluginV2Progress.set(this.updatingV2Count);const{pathV1}=this.parseUnifiedPath(unifiedFilenameWithKey),oldEntry=this.pluginList.find((e3=>e3.documentPath==pathV1));let entry;if(oldEntry&&oldEntry instanceof PluginDataExDisplayV2)oldEntry instanceof PluginDataExDisplayV2&&(entry=oldEntry);else{const newEntry=this.createPluginDataFromV2(unifiedFilenameWithKey);newEntry&&(entry=newEntry)}if(!entry)return;const file=await this.createPluginDataExFileV2(unifiedFilenameWithKey);if(file)await entry.setFile(file);else{entry.deleteFile(unifiedFilenameWithKey);0==entry.files.length&&(this.pluginList=this.pluginList.filter((e3=>e3.documentPath!=pathV1)))}const newList=this.pluginList.filter((e3=>e3.documentPath!=entry.documentPath));newList.push(entry);this.pluginList=newList;scheduleTask("updatePluginListV2",100,(()=>{pluginList.set(this.pluginList)}))}finally{this.updatingV2Count--;pluginV2Progress.set(this.updatingV2Count)}}async migrateV1ToV2(showMessage,entry){var _a8;const v1Path=entry.path;this._log(`Migrating ${entry.path} to V2`,showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);if(entry.deleted){this._log(`The entry ${v1Path} is already deleted`,LOG_LEVEL_VERBOSE);return}if(!v1Path.endsWith(".md")&&!v1Path.startsWith(ICXHeader)){this._log(`The entry ${v1Path} is not a customisation sync binder`,LOG_LEVEL_VERBOSE);return}if(-1!==v1Path.indexOf("%")){this._log(`The entry ${v1Path} is already migrated`,LOG_LEVEL_VERBOSE);return}const loadedEntry=await this.localDatabase.getDBEntry(v1Path);if(!loadedEntry){this._log(`The entry ${v1Path} is not found`,LOG_LEVEL_VERBOSE);return}const pluginData=deserialize(getDocDataAsArray(loadedEntry.data),{}),prefixPath=v1Path.slice(0,-3)+"%",category=pluginData.category;for(const f4 of pluginData.files){const stripTable={CONFIG:0,THEME:2,SNIPPET:1,PLUGIN_MAIN:2,PLUGIN_DATA:2,PLUGIN_ETC:2},deletePrefixCount=null!=(_a8=null==stripTable?void 0:stripTable[category])?_a8:1,relativeFilename=f4.filename.split("/").slice(deletePrefixCount).join("/"),v2Path=prefixPath+relativeFilename;this._log(`Migrating ${v1Path} / ${relativeFilename} to ${v2Path}`,LOG_LEVEL_VERBOSE);const newId=await this.services.path.path2id(v2Path),data=createBlob([DUMMY_HEAD,DUMMY_END,...getDocDataAsArray(f4.data)]),saving={...loadedEntry,_rev:void 0,_id:newId,path:v2Path,data,datatype:"plain",type:"plain",children:[],eden:{}},r4=await this.plugin.localDatabase.putDBEntry(saving);if(r4&&r4.ok){this._log(`Migrated ${v1Path} / ${f4.filename} to ${v2Path}`,LOG_LEVEL_INFO);await this.deleteConfigOnDatabase(v1Path)?this._log(`Deleted ${v1Path} successfully`,LOG_LEVEL_INFO):this._log(`Failed to delete ${v1Path}`,LOG_LEVEL_NOTICE)}}}async updatePluginList(showMessage,updatedDocumentPath){if(this.isThisModuleEnabled()){try{this.updatingV2Count++;pluginV2Progress.set(this.updatingV2Count);const updatedDocumentId=updatedDocumentPath?await this.path2id(updatedDocumentPath):"",plugins=updatedDocumentPath?this.localDatabase.findEntries(updatedDocumentId,updatedDocumentId+"􏿿",{include_docs:!0,key:updatedDocumentId,limit:1}):this.localDatabase.findEntries(ICXHeader+"",`${ICXHeader}􏿿`,{include_docs:!0});for await(const v2 of plugins){if(v2.deleted||v2._deleted)continue;if(-1!==v2.path.indexOf("%")){fireAndForget((()=>this.updatePluginListV2(showMessage,v2.path)));continue}const path2=v2.path||this.getPath(v2);updatedDocumentPath&&updatedDocumentPath!=path2||this.pluginScanProcessor.enqueue(v2)}}finally{pluginIsEnumerating.set(!1);this.updatingV2Count--;pluginV2Progress.set(this.updatingV2Count)}pluginIsEnumerating.set(!1)}else{this.pluginScanProcessor.clearQueue();this.pluginList=[];pluginList.set(this.pluginList)}}async compareUsingDisplayData(dataA,dataB,compareEach=!1){const loadFile=async data=>{if(data instanceof PluginDataExDisplayV2||compareEach)return data.files[0];const loadDoc=await this.localDatabase.getDBEntry(data.documentPath);if(!loadDoc)return!1;const pluginData=deserialize(getDocDataAsArray(loadDoc.data),{});pluginData.documentPath=data.documentPath;const file=pluginData.files[0];return{...loadDoc,...file,datatype:"newnote"}},fileA=await loadFile(dataA),fileB=await loadFile(dataB);this._log(`Comparing: ${dataA.documentPath} <-> ${dataB.documentPath}`,LOG_LEVEL_VERBOSE);if(!fileA||!fileB){this._log(`Could not load ${dataA.name} for comparison: ${fileA?"":dataA.term}${fileB?"":dataB.term}`,LOG_LEVEL_NOTICE);return!1}let path2=stripAllPrefixes(fileA.path.split("/").slice(-1).join("/"));-1!==path2.indexOf("%")&&(path2=path2.split("%")[1]);if(fileA.path.endsWith(".json"))return serialized("config:merge-data",(()=>new Promise((res2=>{this._log("Opening data-merging dialog",LOG_LEVEL_VERBOSE);new JsonResolveModal(this.app,path2,[fileA,fileB],(async(keep,result)=>{if(null==result)return res2(!1);try{res2(await this.applyData(dataA,result))}catch(ex){this._log("Could not apply merged file");this._log(ex,LOG_LEVEL_VERBOSE);res2(!1)}}),"Local",`${dataB.term}`,"B",!0,!0,"Difference between local and remote").open()}))));{const dmp=new import_diff_match_patch.diff_match_patch;let docAData=getDocData(fileA.data),docBData=getDocData(fileB.data);"plain"!=(null==fileA?void 0:fileA.datatype)&&(docAData=base64ToString(docAData));"plain"!=(null==fileB?void 0:fileB.datatype)&&(docBData=base64ToString(docBData));const diffMap=dmp.diff_linesToChars_(docAData,docBData),diff=dmp.diff_main(diffMap.chars1,diffMap.chars2,!1);dmp.diff_charsToLines_(diff,diffMap.lineArray);dmp.diff_cleanupSemantic(diff);const diffResult={left:{rev:"A",...fileA,data:docAData},right:{rev:"B",...fileB,data:docBData},diff},d4=new ConflictResolveModal(this.app,path2,diffResult,!0,dataB.term);d4.open();const ret=await d4.waitForResult();if(ret===CANCELLED)return!1;if(ret===LEAVE_TO_SUBSEQUENT)return!1;const resultContent="A"==ret?docAData:"B"==ret?docBData:void 0;return!!resultContent&&await this.applyData(dataA,resultContent)}}async applyDataV2(data,content){const baseDir=this.app.vault.configDir;try{if(content){const filename=data.files[0].filename;this._log(`Applying ${filename} of ${data.displayName||data.name}..`);const path2=`${baseDir}/${filename}`;await this.plugin.storageAccess.ensureDir(path2);await this.plugin.storageAccess.writeHiddenFileAuto(path2,content);await this.storeCustomisationFileV2(path2,this.services.setting.getDeviceAndVaultName())}else{const files=data.files;for(const f4 of files){const stat={mtime:f4.mtime,ctime:f4.ctime},path2=`${baseDir}/${f4.filename}`;this._log(`Applying ${f4.filename} of ${data.displayName||data.name}..`);await this.plugin.storageAccess.ensureDir(path2);if("newnote"==f4.datatype){let oldData;try{oldData=await this.plugin.storageAccess.readHiddenFileBinary(path2)}catch(ex){this._log(`Could not read the file ${f4.filename}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE);oldData=new ArrayBuffer(0)}const content2=base64ToArrayBuffer(f4.data);if(await isDocContentSame(oldData,content2)){this._log(`The file ${f4.filename} is already up-to-date`,LOG_LEVEL_VERBOSE);continue}await this.plugin.storageAccess.writeHiddenFileAuto(path2,content2,stat)}else{let oldData;try{oldData=await this.plugin.storageAccess.readHiddenFileText(path2)}catch(ex){this._log(`Could not read the file ${f4.filename}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE);oldData=""}const content2=getDocData(f4.data);if(await isDocContentSame(oldData,content2)){this._log(`The file ${f4.filename} is already up-to-date`,LOG_LEVEL_VERBOSE);continue}await this.plugin.storageAccess.writeHiddenFileAuto(path2,content2,stat)}this._log(`Applied ${f4.filename} of ${data.displayName||data.name}..`);await this.storeCustomisationFileV2(path2,this.services.setting.getDeviceAndVaultName())}}}catch(ex){this._log(`Applying ${data.displayName||data.name}.. Failed`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE);return!1}return!0}async applyData(data,content){this._log(`Applying ${data.displayName||data.name}..`);if(data instanceof PluginDataExDisplayV2)return this.applyDataV2(data,content);const baseDir=this.app.vault.configDir;try{if(!data.documentPath)throw"InternalError: Document path not exist";const dx=await this.localDatabase.getDBEntry(data.documentPath);if(0==dx)throw"Not found on database";const loadedData=deserialize(getDocDataAsArray(dx.data),{});for(const f4 of loadedData.files){this._log(`Applying ${f4.filename} of ${data.displayName||data.name}..`);try{const path2=`${baseDir}/${f4.filename}`;await this.plugin.storageAccess.ensureDir(path2);if(content)await this.plugin.storageAccess.writeHiddenFileAuto(path2,content);else{const dt=decodeBinary(f4.data);await this.plugin.storageAccess.writeHiddenFileAuto(path2,dt)}this._log(`Applying ${f4.filename} of ${data.displayName||data.name}.. Done`)}catch(ex){this._log(`Applying ${f4.filename} of ${data.displayName||data.name}.. Failed`);this._log(ex,LOG_LEVEL_VERBOSE)}}const uPath=`${baseDir}/${loadedData.files[0].filename}`;await this.storeCustomizationFiles(uPath);await this.updatePluginList(!0,uPath);await delay(100);this._log(`Config ${data.displayName||data.name} has been applied`,LOG_LEVEL_NOTICE);if("PLUGIN_DATA"==data.category||"PLUGIN_MAIN"==data.category){const manifests=Object.values(this.app.plugins.manifests),enabledPlugins=this.app.plugins.enabledPlugins,pluginManifest=manifests.find((manifest=>enabledPlugins.has(manifest.id)&&manifest.dir==`${baseDir}/plugins/${data.name}`));if(pluginManifest){this._log(`Unloading plugin: ${pluginManifest.name}`,LOG_LEVEL_NOTICE,"plugin-reload-"+pluginManifest.id);await this.app.plugins.unloadPlugin(pluginManifest.id);await this.app.plugins.loadPlugin(pluginManifest.id);this._log(`Plugin reloaded: ${pluginManifest.name}`,LOG_LEVEL_NOTICE,"plugin-reload-"+pluginManifest.id)}}else"CONFIG"==data.category&&this.services.appLifecycle.askRestart();return!0}catch(ex){this._log(`Applying ${data.displayName||data.name}.. Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async deleteData(data){try{if(data.documentPath){const delList=[];if(this.useV2){const deleteList=this.pluginList.filter((e3=>e3.documentPath==data.documentPath)).filter((e3=>e3 instanceof PluginDataExDisplayV2)).map((e3=>e3.files)).flat();for(const e3 of deleteList)delList.push(e3.path)}delList.push(data.documentPath);const p4=delList.map((async e3=>{await this.deleteConfigOnDatabase(e3);await this.updatePluginList(!1,e3)}));await Promise.allSettled(p4);this._log(`Deleted: ${data.category}/${data.name} of ${data.category} (${delList.length} items)`,LOG_LEVEL_NOTICE)}return!0}catch(ex){this._log(`Failed to delete: ${data.documentPath}`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async _anyModuleParsedReplicationResultItem(docs){if(!docs._id.startsWith(ICXHeader))return!1;this.isThisModuleEnabled()&&await this.updatePluginList(!1,docs.path?docs.path:this.getPath(docs));if(this.isThisModuleEnabled()&&this.plugin.settings.notifyPluginOrSettingUpdated&&(!this.pluginDialog||this.pluginDialog&&!this.pluginDialog.isOpened())){const fragment=createFragment((doc=>{doc.createEl("span",void 0,(a2=>{a2.appendText("Some configuration has been arrived, Press ");a2.appendChild(a2.createEl("a",void 0,(anchor=>{anchor.text="HERE";anchor.addEventListener("click",(()=>{this.showPluginSyncModal()}))})));a2.appendText(" to open the config sync dialog , or press elsewhere to dismiss this message.")}))})),updatedPluginKey="popupUpdated-plugins";scheduleTask(updatedPluginKey,1e3,(async()=>{var _a8;const popup=await memoIfNotExist(updatedPluginKey,(()=>new import_obsidian.Notice(fragment,0)));(null==(_a8=null==popup?void 0:popup.noticeEl)?void 0:_a8.isShown())||memoObject(updatedPluginKey,new import_obsidian.Notice(fragment,0));scheduleTask(updatedPluginKey+"-close",2e4,(()=>{var _a9;const popup2=retrieveMemoObject(updatedPluginKey);if(popup2){(null==(_a9=null==popup2?void 0:popup2.noticeEl)?void 0:_a9.isShown())&&popup2.hide();disposeMemoObject(updatedPluginKey)}}))}))}return!0}async _everyRealizeSettingSyncMode(){var _a8;null==(_a8=this.periodicPluginSweepProcessor)||_a8.disable();if(!this._isMainReady)return!0;if(!this._isMainSuspended())return!0;if(!this.isThisModuleEnabled())return!0;this.settings.autoSweepPlugins&&await this.scanAllConfigFiles(!1);this.periodicPluginSweepProcessor.enable(this.settings.autoSweepPluginsPeriodic&&!this.settings.watchInternalFileChanges?6e4:0);return!0}async makeEntryFromFile(path2){const stat=await this.plugin.storageAccess.statHidden(path2);let version2,displayName;if(!stat)return!1;const contentBin=await this.plugin.storageAccess.readHiddenFileBinary(path2);let content;try{content=await arrayBufferToBase64(contentBin);if(path2.toLowerCase().endsWith("/manifest.json")){const v2=readString(new Uint8Array(contentBin));try{const json=JSON.parse(v2);"version"in json&&(version2=`${json.version}`);"name"in json&&(displayName=`${json.name}`)}catch(ex){this._log(`Configuration sync data: ${path2} looks like manifest, but could not read the version`,LOG_LEVEL_INFO);this._log(ex,LOG_LEVEL_VERBOSE)}}}catch(ex){this._log(`The file ${path2} could not be encoded`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}const mtime=stat.mtime;return{filename:path2.substring(this.app.vault.configDir.length+1),data:content,mtime,size:stat.size,version:version2,displayName}}async storeCustomisationFileV2(path2,term,force=!1){const vf=this.filenameWithUnifiedKey(path2,term);return await serialized(`plugin-${vf}`,(async()=>{const prefixedFileName=vf,id=await this.path2id(prefixedFileName),stat=await this.plugin.storageAccess.statHidden(path2);if(!stat)return!1;const mtime=stat.mtime,content=await this.plugin.storageAccess.readHiddenFileBinary(path2),contentBlob=createBlob([DUMMY_HEAD,DUMMY_END,...await arrayBufferToBase64(content)]);try{const old=await this.localDatabase.getDBEntryMeta(prefixedFileName,void 0,!1);let saveData;if(!1===old)saveData={_id:id,path:prefixedFileName,data:contentBlob,mtime,ctime:mtime,datatype:"plain",size:contentBlob.size,children:[],deleted:!1,type:"plain",eden:{}};else{if(isMarkedAsSameChanges(prefixedFileName,[old.mtime,mtime+1])==EVEN){this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Skipped (Already checked the same)`,LOG_LEVEL_DEBUG);return}const docXDoc=await this.localDatabase.getDBEntryFromMeta(old,!1,!1);if(0==docXDoc)throw"Could not load the document";const dataSrc=getDocData(docXDoc.data),dataStart=dataSrc.indexOf(DUMMY_END),oldContent=dataSrc.substring(dataStart+DUMMY_END.length),oldContentArray=base64ToArrayBuffer(oldContent);if(await isDocContentSame(oldContentArray,content)){this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Skipped (the same content)`,LOG_LEVEL_VERBOSE);markChangesAreSame(prefixedFileName,old.mtime,mtime+1);return!0}saveData={...old,data:contentBlob,mtime,size:contentBlob.size,datatype:"plain",children:[],deleted:!1,type:"plain"}}const ret=await this.localDatabase.putDBEntry(saveData);this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Done`);fireAndForget((()=>this.updatePluginListV2(!1,this.filenameWithUnifiedKey(path2))));return ret}catch(ex){this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}))}async storeCustomizationFiles(path2,termOverRide){const term=termOverRide||this.services.setting.getDeviceAndVaultName();if(""==term){this._log("We have to configure the device name",LOG_LEVEL_NOTICE);return}if(this.useV2)return await this.storeCustomisationFileV2(path2,term);const vf=this.filenameToUnifiedKey(path2,term);return await serialized(`plugin-${vf}`,(async()=>{const category=this.getFileCategory(path2);let mtime=0,fileTargets=[];const name="CONFIG"==category||"SNIPPET"==category?path2.split("/").reverse()[0]:path2.split("/").reverse()[1],parentPath=path2.split("/").slice(0,-1).join("/"),prefixedFileName=this.filenameToUnifiedKey(path2,term),id=await this.path2id(prefixedFileName),dt={category,files:[],name,mtime:0,term};if("CONFIG"==category||"SNIPPET"==category||"PLUGIN_ETC"==category||"PLUGIN_DATA"==category){fileTargets=[path2];"PLUGIN_ETC"==category&&(dt.displayName=path2.split("/").slice(-1).join("/"))}else"PLUGIN_MAIN"==category?fileTargets=["manifest.json","main.js","styles.css"].map((e3=>`${parentPath}/${e3}`)):"THEME"==category&&(fileTargets=["manifest.json","theme.css"].map((e3=>`${parentPath}/${e3}`)));for(const target of fileTargets){const data=await this.makeEntryFromFile(target);if(0!=data){data.version&&(dt.version=data.version);data.displayName&&(dt.displayName=data.displayName);mtime=0==mtime?data.mtime:(data.mtime+mtime)/2;dt.files.push(data)}else this._log(`Config: skipped (Possibly is not exist): ${target} `,LOG_LEVEL_VERBOSE)}dt.mtime=mtime;if(0==dt.files.length){this._log(`Nothing left: deleting.. ${path2}`);await this.deleteConfigOnDatabase(prefixedFileName);await this.updatePluginList(!1,prefixedFileName);return}const content=createTextBlob(serialize(dt));try{const old=await this.localDatabase.getDBEntryMeta(prefixedFileName,void 0,!1);let saveData;if(!1===old)saveData={_id:id,path:prefixedFileName,data:content,mtime,ctime:mtime,datatype:"newnote",size:content.size,children:[],deleted:!1,type:"newnote",eden:{}};else{if(old.mtime==mtime)return!0;const oldC=await this.localDatabase.getDBEntryFromMeta(old,!1,!1);if(oldC){const d4=await deserialize(getDocDataAsArray(oldC.data),{});if(d4.files.length==dt.files.length){const diffs=d4.files.map((previous=>({prev:previous,curr:dt.files.find((e3=>e3.filename==previous.filename))}))).map((async e3=>{var _a8,_b5;try{return await isDocContentSame(null!=(_b5=null==(_a8=e3.curr)?void 0:_a8.data)?_b5:[],e3.prev.data)}catch(e4){return!1}}));if((await Promise.all(diffs)).every((e3=>1==e3))){this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Skipped (Same content)`,LOG_LEVEL_VERBOSE);return!0}}}saveData={...old,data:content,mtime,size:content.size,datatype:"newnote",children:[],deleted:!1,type:"newnote"}}const ret=await this.localDatabase.putDBEntry(saveData);await this.updatePluginList(!1,saveData.path);this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Done`);return ret}catch(ex){this._log(`STORAGE --\x3e DB:${prefixedFileName}: (config) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}))}async _anyProcessOptionalFileEvent(path2){return await this.watchVaultRawEventsAsync(path2)}async watchVaultRawEventsAsync(path2){if(!this._isMainReady)return!1;if(this._isMainSuspended())return!1;if(!this.isThisModuleEnabled())return!1;const stat=await this.plugin.storageAccess.statHidden(path2);if(stat&&"file"!=stat.type)return!1;const configDir=normalizePath(this.app.vault.configDir);if(Object.values(this.settings.pluginSyncExtendedSetting).filter((e3=>e3.mode!=MODE_SELECTIVE&&e3.mode!=MODE_SHINY)).map((e3=>e3.files)).flat().map((e3=>`${configDir}/${e3}`.toLowerCase())).some((e3=>e3.startsWith(path2.toLowerCase())))){this._log(`Customization file skipped: ${path2}`,LOG_LEVEL_VERBOSE);return!1}const storageMTime=~~((stat&&stat.mtime||0)/1e3),key3=`${path2}-${storageMTime}`;if(this.recentProcessedInternalFiles.contains(key3))return!0;this.recentProcessedInternalFiles=[key3,...this.recentProcessedInternalFiles].slice(0,100);scheduleTask(this.filenameToUnifiedKey(path2),100,(async()=>{await this.storeCustomizationFiles(path2)}));return!0}async scanAllConfigFiles(showMessage){await shareRunningResult("scanAllConfigFiles",(async()=>{var _a8;const logLevel=showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;this._log("Scanning customizing files.",logLevel,"scan-all-config");const term=this.services.setting.getDeviceAndVaultName();if(""==term){this._log("We have to configure the device name",LOG_LEVEL_NOTICE);return}const filesAll=await this.scanInternalFiles();if(this.useV2){const filesAllUnified=filesAll.filter((e3=>this.isTargetPath(e3))).map((e3=>[this.filenameWithUnifiedKey(e3,term),e3])),localFileMap=new Map(filesAllUnified.map((e3=>[e3[0],e3[1]]))),prefix=this.unifiedKeyPrefixOfTerminal(term),entries2=this.localDatabase.findEntries(prefix+"",`${prefix}􏿿`,{include_docs:!0}),tasks3=[],semaphore=Semaphore(10);for await(const item of entries2)-1===item.path.indexOf("%")&&tasks3.push((async()=>{const releaser=await semaphore.acquire();try{const unifiedFilenameWithKey=`${item._id}`,localPath=localFileMap.get(unifiedFilenameWithKey);if(localPath){await this.storeCustomisationFileV2(localPath,term);localFileMap.delete(unifiedFilenameWithKey)}else await this.deleteConfigOnDatabase(unifiedFilenameWithKey)}catch(ex){this._log(`scanAllConfigFiles - Error: ${item._id}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}finally{releaser()}}));await Promise.all(tasks3.map((e3=>e3())));const taskExtra=[];for(const[,filePath]of localFileMap)taskExtra.push((async()=>{const releaser=await semaphore.acquire();try{await this.storeCustomisationFileV2(filePath,term)}catch(ex){this._log(`scanAllConfigFiles - Error: ${filePath}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}finally{releaser()}}));await Promise.all(taskExtra.map((e3=>e3())));fireAndForget((()=>this.updatePluginList(!1)))}else{const files=filesAll.filter((e3=>this.isTargetPath(e3))).map((e3=>({key:this.filenameToUnifiedKey(e3),file:e3}))),virtualPathsOfLocalFiles=[...new Set(files.map((e3=>e3.key)))];let deleteCandidate=(await this.localDatabase.allDocsRaw({startkey:ICXHeader+"",endkey:`${ICXHeader}􏿿`,include_docs:!0})).rows.map((e3=>e3.doc)).filter((e3=>!e3.deleted)).map((e3=>this.getPath(e3))).filter((e3=>e3.startsWith(`${ICXHeader}${term}/`)));for(const vp of virtualPathsOfLocalFiles){const p4=null==(_a8=files.find((e3=>e3.key==vp)))?void 0:_a8.file;if(p4){await this.storeCustomizationFiles(p4);deleteCandidate=deleteCandidate.filter((e3=>e3!=vp))}else this._log(`scanAllConfigFiles - File not found: ${vp}`,LOG_LEVEL_VERBOSE)}for(const vp of deleteCandidate)await this.deleteConfigOnDatabase(vp);fireAndForget((()=>this.updatePluginList(!1)))}}))}async deleteConfigOnDatabase(prefixedFileName,forceWrite=!1){const mtime=(new Date).getTime();return await serialized("file-x-"+prefixedFileName,(async()=>{try{const old=await this.localDatabase.getDBEntryMeta(prefixedFileName,void 0,!1);let saveData;if(!1===old){this._log(`STORAGE -x> DB:${prefixedFileName}: (config) already deleted (Not found on database)`);return!0}if(old.deleted){this._log(`STORAGE -x> DB:${prefixedFileName}: (config) already deleted`);return!0}saveData={...old,mtime,size:0,children:[],deleted:!0,type:"newnote"};await this.localDatabase.putRaw(saveData);await this.updatePluginList(!1,prefixedFileName);this._log(`STORAGE -x> DB:${prefixedFileName}: (config) Done`);return!0}catch(ex){this._log(`STORAGE -x> DB:${prefixedFileName}: (config) Failed`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}))}async scanInternalFiles(){return(await this.getFiles(this.app.vault.configDir,2)).filter((e3=>e3.startsWith("."))).filter((e3=>!e3.startsWith(".trash")))}async _allAskUsingOptionalSyncFeature(opt){await this.__askHiddenFileConfiguration(opt);return!0}async __askHiddenFileConfiguration(opt){const choices=[];choices.push("Yes, Enable it");choices.push("No, Disable it");choices.push("Later");const ret=await this.plugin.confirm.askSelectStringDialogue("Would you like to enable **Customization sync**?\n\n> [!DETAILS]-\n> This feature allows you to sync your customisations -- such as configurations, themes, snippets, and plugins -- across your devices in a fully controlled manner, unlike the fully automatic behaviour of hidden file synchronisation.\n> \n> You may use this feature alongside hidden file synchronisation. When both features are enabled, items configured as `Automatic` in this feature will be managed by **hidden file synchronisation**.\n> Do not worry, you will be prompted to enable or keep disabled **hidden file synchronisation** after this dialogue.\n",choices,{defaultAction:"Later",timeout:40,title:"Customisation sync"});"Yes, Enable it"==ret?await this.configureHiddenFileSync("CUSTOMIZE"):"No, Disable it"==ret&&await this.configureHiddenFileSync("DISABLE_CUSTOM")}_anyGetOptionalConflictCheckMethod(path2){return isPluginMetadata(path2)||isCustomisationSyncMetadata(path2)?Promise.resolve("newer"):Promise.resolve(!1)}_allSuspendExtraSync(){if(this.plugin.settings.usePluginSync||this.plugin.settings.autoSweepPlugins){this._log("Customisation sync have been temporarily disabled. Please enable them after the fetching, if you need them.",LOG_LEVEL_NOTICE);this.plugin.settings.usePluginSync=!1;this.plugin.settings.autoSweepPlugins=!1}return Promise.resolve(!0)}async _allConfigureOptionalSyncFeature(mode){await this.configureHiddenFileSync(mode);return!0}async configureHiddenFileSync(mode){if("DISABLE"!=mode){if("CUSTOMIZE"==mode){if(!this.services.setting.getDeviceAndVaultName()){let name=await this.plugin.confirm.askString("Device name","Please set this device name","desktop");if(!name){name=import_obsidian.Platform.isAndroidApp?"android-app":import_obsidian.Platform.isIosApp?"ios":import_obsidian.Platform.isMacOS?"macos":import_obsidian.Platform.isMobileApp?"mobile-app":import_obsidian.Platform.isMobile?"mobile":import_obsidian.Platform.isSafari?"safari":import_obsidian.Platform.isDesktop?"desktop":import_obsidian.Platform.isDesktopApp?"desktop-app":"unknown";name+=Math.random().toString(36).slice(-4)}this.services.setting.setDeviceAndVaultName(name)}this.plugin.settings.usePluginSync=!0;this.plugin.settings.useAdvancedMode=!0;await this.plugin.saveSettings();await this.scanAllConfigFiles(!0)}}else{this.plugin.settings.usePluginSync=!1;await this.plugin.saveSettings()}}async getFiles(path2,lastDepth){if(-1==lastDepth)return[];let w2;try{w2=await this.app.vault.adapter.list(path2)}catch(ex){this._log(`Could not traverse(ConfigSync):${path2}`,LOG_LEVEL_INFO);this._log(ex,LOG_LEVEL_VERBOSE);return[]}let files=[...w2.files];for(const v2 of w2.folders)files=files.concat(await this.getFiles(v2,lastDepth-1));return files}onBindFunction(core,services){services.fileProcessing.handleOptionalFileEvent(this._anyProcessOptionalFileEvent.bind(this));services.conflict.handleGetOptionalConflictCheckMethod(this._anyGetOptionalConflictCheckMethod.bind(this));services.replication.handleProcessVirtualDocuments(this._anyModuleParsedReplicationResultItem.bind(this));services.setting.handleOnRealiseSetting(this._everyRealizeSettingSyncMode.bind(this));services.appLifecycle.handleOnResuming(this._everyOnResumeProcess.bind(this));services.appLifecycle.handleOnResumed(this._everyAfterResumeProcess.bind(this));services.replication.handleBeforeReplicate(this._everyBeforeReplicate.bind(this));services.databaseEvents.handleDatabaseInitialised(this._everyOnDatabaseInitialized.bind(this));services.setting.handleSuspendExtraSync(this._allSuspendExtraSync.bind(this));services.setting.handleSuggestOptionalFeatures(this._allAskUsingOptionalSyncFeature.bind(this));services.setting.handleEnableOptionalFeature(this._allConfigureOptionalSyncFeature.bind(this))}};getHttpHandlerExtensionConfiguration=runtimeConfig=>({setHttpHandler(handler){runtimeConfig.httpHandler=handler},httpHandler:()=>runtimeConfig.httpHandler,updateHttpClientConfig(key3,value){var _a8;null==(_a8=runtimeConfig.httpHandler)||_a8.updateHttpClientConfig(key3,value)},httpHandlerConfigs:()=>runtimeConfig.httpHandler.httpHandlerConfigs()});resolveHttpHandlerRuntimeConfig=httpHandlerExtensionConfiguration=>({httpHandler:httpHandlerExtensionConfiguration.httpHandler()});(function(HttpAuthLocation2){HttpAuthLocation2.HEADER="header";HttpAuthLocation2.QUERY="query"})(HttpAuthLocation||(HttpAuthLocation={}));(function(HttpApiKeyAuthLocation2){HttpApiKeyAuthLocation2.HEADER="header";HttpApiKeyAuthLocation2.QUERY="query"})(HttpApiKeyAuthLocation||(HttpApiKeyAuthLocation={}));(function(EndpointURLScheme2){EndpointURLScheme2.HTTP="http";EndpointURLScheme2.HTTPS="https"})(EndpointURLScheme||(EndpointURLScheme={}));(function(AlgorithmId2){AlgorithmId2.MD5="md5";AlgorithmId2.CRC32="crc32";AlgorithmId2.CRC32C="crc32c";AlgorithmId2.SHA1="sha1";AlgorithmId2.SHA256="sha256"})(AlgorithmId||(AlgorithmId={}));(function(FieldPosition2){FieldPosition2[FieldPosition2.HEADER=0]="HEADER";FieldPosition2[FieldPosition2.TRAILER=1]="TRAILER"})(FieldPosition||(FieldPosition={}));SMITHY_CONTEXT_KEY="__smithy_context";(function(IniSectionType2){IniSectionType2.PROFILE="profile";IniSectionType2.SSO_SESSION="sso-session";IniSectionType2.SERVICES="services"})(IniSectionType||(IniSectionType={}));(function(RequestHandlerProtocol2){RequestHandlerProtocol2.HTTP_0_9="http/0.9";RequestHandlerProtocol2.HTTP_1_0="http/1.0";RequestHandlerProtocol2.TDS_8_0="tds/8.0"})(RequestHandlerProtocol||(RequestHandlerProtocol={}));HttpRequest=class _HttpRequest{constructor(options){this.method=options.method||"GET";this.hostname=options.hostname||"localhost";this.port=options.port;this.query=options.query||{};this.headers=options.headers||{};this.body=options.body;this.protocol=options.protocol?":"!==options.protocol.slice(-1)?`${options.protocol}:`:options.protocol:"https:";this.path=options.path?"/"!==options.path.charAt(0)?`/${options.path}`:options.path:"/";this.username=options.username;this.password=options.password;this.fragment=options.fragment}static clone(request2){const cloned=new _HttpRequest({...request2,headers:{...request2.headers}});cloned.query&&(cloned.query=cloneQuery(cloned.query));return cloned}static isInstance(request2){if(!request2)return!1;const req=request2;return"method"in req&&"protocol"in req&&"hostname"in req&&"path"in req&&"object"==typeof req.query&&"object"==typeof req.headers}clone(){return _HttpRequest.clone(this)}};HttpResponse=class{constructor(options){this.statusCode=options.statusCode;this.reason=options.reason;this.headers=options.headers||{};this.body=options.body}static isInstance(response){if(!response)return!1;const resp=response;return"number"==typeof resp.statusCode&&"object"==typeof resp.headers}};addExpectContinueMiddlewareOptions={step:"build",tags:["SET_EXPECT_HEADER","EXPECT_HEADER"],name:"addExpectContinueMiddleware",override:!0};getAddExpectContinuePlugin=options=>({applyToStack:clientStack=>{clientStack.add(addExpectContinueMiddleware(options),addExpectContinueMiddlewareOptions)}});DEFAULT_REQUEST_CHECKSUM_CALCULATION=(RequestChecksumCalculation={WHEN_SUPPORTED:"WHEN_SUPPORTED",WHEN_REQUIRED:"WHEN_REQUIRED"}).WHEN_SUPPORTED;ResponseChecksumValidation={WHEN_SUPPORTED:"WHEN_SUPPORTED",WHEN_REQUIRED:"WHEN_REQUIRED"};DEFAULT_RESPONSE_CHECKSUM_VALIDATION=RequestChecksumCalculation.WHEN_SUPPORTED;(function(ChecksumAlgorithm3){ChecksumAlgorithm3.MD5="MD5";ChecksumAlgorithm3.CRC32="CRC32";ChecksumAlgorithm3.CRC32C="CRC32C";ChecksumAlgorithm3.CRC64NVME="CRC64NVME";ChecksumAlgorithm3.SHA1="SHA1";ChecksumAlgorithm3.SHA256="SHA256"})(ChecksumAlgorithm||(ChecksumAlgorithm={}));(function(ChecksumLocation2){ChecksumLocation2.HEADER="header";ChecksumLocation2.TRAILER="trailer"})(ChecksumLocation||(ChecksumLocation={}));DEFAULT_CHECKSUM_ALGORITHM=ChecksumAlgorithm.CRC32;(function(SelectorType3){SelectorType3.ENV="env";SelectorType3.CONFIG="shared config entry"})(SelectorType||(SelectorType={}));getDateHeader=response=>{var _a8,_b5,_c3;return HttpResponse.isInstance(response)?null!=(_c3=null==(_a8=response.headers)?void 0:_a8.date)?_c3:null==(_b5=response.headers)?void 0:_b5.Date:void 0};getSkewCorrectedDate=systemClockOffset=>new Date(Date.now()+systemClockOffset);isClockSkewed=(clockTime,systemClockOffset)=>Math.abs(getSkewCorrectedDate(systemClockOffset).getTime()-clockTime)>=3e5;getUpdatedSystemClockOffset=(clockTime,currentSystemClockOffset)=>{const clockTimeInMs=Date.parse(clockTime);return isClockSkewed(clockTimeInMs,currentSystemClockOffset)?clockTimeInMs-Date.now():currentSystemClockOffset};throwSigningPropertyError=(name,property)=>{if(!property)throw new Error(`Property \`${name}\` is not resolved for AWS SDK SigV4Auth`);return property};validateSigningProperties=async signingProperties=>{var _a8,_b5,_c3;const context2=throwSigningPropertyError("context",signingProperties.context),config=throwSigningPropertyError("config",signingProperties.config),authScheme=null==(_c3=null==(_b5=null==(_a8=context2.endpointV2)?void 0:_a8.properties)?void 0:_b5.authSchemes)?void 0:_c3[0],signerFunction=throwSigningPropertyError("signer",config.signer);return{config,signer:await signerFunction(authScheme),signingRegion:null==signingProperties?void 0:signingProperties.signingRegion,signingRegionSet:null==signingProperties?void 0:signingProperties.signingRegionSet,signingName:null==signingProperties?void 0:signingProperties.signingName}};AwsSdkSigV4Signer=class{async sign(httpRequest,identity,signingProperties){var _a8,_b5,_c3,_d2;if(!HttpRequest.isInstance(httpRequest))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const validatedProps=await validateSigningProperties(signingProperties),{config,signer}=validatedProps;let{signingRegion,signingName}=validatedProps;const handlerExecutionContext=signingProperties.context;if(null!=(_b5=null==(_a8=null==handlerExecutionContext?void 0:handlerExecutionContext.authSchemes)?void 0:_a8.length)&&_b5){const[first,second]=handlerExecutionContext.authSchemes;if("sigv4a"===(null==first?void 0:first.name)&&"sigv4"===(null==second?void 0:second.name)){signingRegion=null!=(_c3=null==second?void 0:second.signingRegion)?_c3:signingRegion;signingName=null!=(_d2=null==second?void 0:second.signingName)?_d2:signingName}}return await signer.sign(httpRequest,{signingDate:getSkewCorrectedDate(config.systemClockOffset),signingRegion,signingService:signingName})}errorHandler(signingProperties){return error=>{var _a8;const serverTime=null!=(_a8=error.ServerTime)?_a8:getDateHeader(error.$response);if(serverTime){const config=throwSigningPropertyError("config",signingProperties.config),initialSystemClockOffset=config.systemClockOffset;config.systemClockOffset=getUpdatedSystemClockOffset(serverTime,config.systemClockOffset);config.systemClockOffset!==initialSystemClockOffset&&error.$metadata&&(error.$metadata.clockSkewCorrected=!0)}throw error}}successHandler(httpResponse,signingProperties){const dateHeader=getDateHeader(httpResponse);if(dateHeader){const config=throwSigningPropertyError("config",signingProperties.config);config.systemClockOffset=getUpdatedSystemClockOffset(dateHeader,config.systemClockOffset)}}};AwsSdkSigV4ASigner=class extends AwsSdkSigV4Signer{async sign(httpRequest,identity,signingProperties){var _a8,_b5;if(!HttpRequest.isInstance(httpRequest))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const{config,signer,signingRegion,signingRegionSet,signingName}=await validateSigningProperties(signingProperties),configResolvedSigningRegionSet=await(null==(_a8=config.sigv4aSigningRegionSet)?void 0:_a8.call(config)),multiRegionOverride=(null!=(_b5=null!=configResolvedSigningRegionSet?configResolvedSigningRegionSet:signingRegionSet)?_b5:[signingRegion]).join(",");return await signer.sign(httpRequest,{signingDate:getSkewCorrectedDate(config.systemClockOffset),signingRegion:multiRegionOverride,signingService:signingName})}};getSmithyContext2=context2=>context2.__smithy_context||(context2.__smithy_context={});normalizeProvider=input=>{if("function"==typeof input)return input;const promisified=Promise.resolve(input);return()=>promisified};resolveAuthOptions=(candidateAuthOptions,authSchemePreference)=>{if(!authSchemePreference||0===authSchemePreference.length)return candidateAuthOptions;const preferredAuthOptions=[];for(const preferredSchemeName of authSchemePreference)for(const candidateAuthOption of candidateAuthOptions)candidateAuthOption.schemeId.split("#")[1]===preferredSchemeName&&preferredAuthOptions.push(candidateAuthOption);for(const candidateAuthOption of candidateAuthOptions)preferredAuthOptions.find((({schemeId})=>schemeId===candidateAuthOption.schemeId))||preferredAuthOptions.push(candidateAuthOption);return preferredAuthOptions};httpAuthSchemeMiddleware=(config,mwOptions)=>(next2,context2)=>async args=>{var _a8;const options=config.httpAuthSchemeProvider(await mwOptions.httpAuthSchemeParametersProvider(config,context2,args.input)),authSchemePreference=config.authSchemePreference?await config.authSchemePreference():[],resolvedOptions=resolveAuthOptions(options,authSchemePreference),authSchemes=convertHttpAuthSchemesToMap(config.httpAuthSchemes),smithyContext=getSmithyContext2(context2),failureReasons=[];for(const option of resolvedOptions){const scheme=authSchemes.get(option.schemeId);if(!scheme){failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` was not enabled for this service.`);continue}const identityProvider=scheme.identityProvider(await mwOptions.identityProviderConfigProvider(config));if(!identityProvider){failureReasons.push(`HttpAuthScheme \`${option.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties={},signingProperties={}}=(null==(_a8=option.propertiesExtractor)?void 0:_a8.call(option,config,context2))||{};option.identityProperties=Object.assign(option.identityProperties||{},identityProperties);option.signingProperties=Object.assign(option.signingProperties||{},signingProperties);smithyContext.selectedHttpAuthScheme={httpAuthOption:option,identity:await identityProvider(option.identityProperties),signer:scheme.signer};break}if(!smithyContext.selectedHttpAuthScheme)throw new Error(failureReasons.join("\n"));return next2(args)};httpAuthSchemeEndpointRuleSetMiddlewareOptions={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"};getHttpAuthSchemeEndpointRuleSetPlugin=(config,{httpAuthSchemeParametersProvider,identityProviderConfigProvider})=>({applyToStack:clientStack=>{clientStack.addRelativeTo(httpAuthSchemeMiddleware(config,{httpAuthSchemeParametersProvider,identityProviderConfigProvider}),httpAuthSchemeEndpointRuleSetMiddlewareOptions)}});deserializerMiddleware=(options,deserializer)=>(next2,context2)=>async args=>{var _a8,_b5,_c3,_d2;const{response}=await next2(args);try{return{response,output:await deserializer(response,options)}}catch(error){Object.defineProperty(error,"$response",{value:response});if(!("$metadata"in error)){const hint="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{error.message+="\n "+hint}catch(e3){context2.logger&&"NoOpLogger"!==(null==(_b5=null==(_a8=context2.logger)?void 0:_a8.constructor)?void 0:_b5.name)?null==(_d2=null==(_c3=context2.logger)?void 0:_c3.warn)||_d2.call(_c3,hint):console.warn(hint)}void 0!==error.$responseBodyText&&error.$response&&(error.$response.body=error.$responseBodyText);try{if(HttpResponse.isInstance(response)){const{headers={}}=response,headerEntries=Object.entries(headers);error.$metadata={httpStatusCode:response.statusCode,requestId:findHeader(/^x-[\w-]+-request-?id$/,headerEntries),extendedRequestId:findHeader(/^x-[\w-]+-id-2$/,headerEntries),cfId:findHeader(/^x-[\w-]+-cf-id$/,headerEntries)}}}catch(e3){}}throw error}};findHeader=(pattern,headers)=>(headers.find((([k2])=>k2.match(pattern)))||[void 0,void 0])[1];serializerMiddleware=(options,serializer)=>(next2,context2)=>async args=>{var _a8;const endpoint=(null==(_a8=context2.endpointV2)?void 0:_a8.url)&&options.urlParser?async()=>options.urlParser(context2.endpointV2.url):options.endpoint;if(!endpoint)throw new Error("No valid endpoint provider available.");const request2=await serializer(args.input,{...options,endpoint});return next2({...args,request:request2})};deserializerMiddlewareOption={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0};(serializerMiddlewareOption={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0}).name;defaultErrorHandler=signingProperties=>error=>{throw error};defaultSuccessHandler=(httpResponse,signingProperties)=>{};httpSigningMiddleware=config=>(next2,context2)=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);const scheme=getSmithyContext2(context2).selectedHttpAuthScheme;if(!scheme)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties={}},identity,signer}=scheme,output=await next2({...args,request:await signer.sign(args.request,identity,signingProperties)}).catch((signer.errorHandler||defaultErrorHandler)(signingProperties));(signer.successHandler||defaultSuccessHandler)(output.response,signingProperties);return output};httpSigningMiddlewareOptions={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"};getHttpSigningPlugin=config=>({applyToStack:clientStack=>{clientStack.addRelativeTo(httpSigningMiddleware(),httpSigningMiddlewareOptions)}});normalizeProvider2=input=>{if("function"==typeof input)return input;const promisified=Promise.resolve(input);return()=>promisified};alphabetByEncoding={};alphabetByValue=new Array(64);for(let i2=0,start="A".charCodeAt(0),limit="Z".charCodeAt(0);i2+start<=limit;i2++){const char=String.fromCharCode(i2+start);alphabetByEncoding[char]=i2;alphabetByValue[i2]=char}for(let i2=0,start="a".charCodeAt(0),limit="z".charCodeAt(0);i2+start<=limit;i2++){const char=String.fromCharCode(i2+start),index6=i2+26;alphabetByEncoding[char]=index6;alphabetByValue[index6]=char}for(let i2=0;i2<10;i2++){alphabetByEncoding[i2.toString(10)]=i2+52;const char=i2.toString(10),index6=i2+52;alphabetByEncoding[char]=index6;alphabetByValue[index6]=char}alphabetByEncoding["+"]=62;alphabetByValue[62]="+";alphabetByEncoding["/"]=63;alphabetByValue[63]="/";bitsPerLetter=6;bitsPerByte=8;maxLetterValue=63;fromBase64=input=>{let totalByteLength=input.length/4*3;"=="===input.slice(-2)?totalByteLength-=2:"="===input.slice(-1)&&totalByteLength--;const out=new ArrayBuffer(totalByteLength),dataView=new DataView(out);for(let i2=0;i2<input.length;i2+=4){let bits2=0,bitLength=0;for(let j2=i2,limit=i2+3;j2<=limit;j2++)if("="!==input[j2]){if(!(input[j2]in alphabetByEncoding))throw new TypeError(`Invalid character ${input[j2]} in base64 string.`);bits2|=alphabetByEncoding[input[j2]]<<(limit-j2)*bitsPerLetter;bitLength+=bitsPerLetter}else bits2>>=bitsPerLetter;const chunkOffset=i2/4*3;bits2>>=bitLength%bitsPerByte;const byteLength=Math.floor(bitLength/bitsPerByte);for(let k2=0;k2<byteLength;k2++){const offset=(byteLength-k2-1)*bitsPerByte;dataView.setUint8(chunkOffset+k2,(bits2&255<<offset)>>offset)}}return new Uint8Array(out)};fromUtf8=input=>(new TextEncoder).encode(input);toUint8Array=data=>"string"==typeof data?fromUtf8(data):ArrayBuffer.isView(data)?new Uint8Array(data.buffer,data.byteOffset,data.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(data);toUtf8=input=>{if("string"==typeof input)return input;if("object"!=typeof input||"number"!=typeof input.byteOffset||"number"!=typeof input.byteLength)throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(input)};Uint8ArrayBlobAdapter=class _Uint8ArrayBlobAdapter extends Uint8Array{static fromString(source2,encoding="utf-8"){switch(typeof source2){case"string":return transformFromString(source2,encoding);default:throw new Error(`Unsupported conversion from ${typeof source2} to Uint8ArrayBlobAdapter.`)}}static mutate(source2){Object.setPrototypeOf(source2,_Uint8ArrayBlobAdapter.prototype);return source2}transformToString(encoding="utf-8"){return transformToString(this,encoding)}};ReadableStreamRef="function"==typeof ReadableStream?ReadableStream:function(){};ChecksumStream=class extends ReadableStreamRef{};isReadableStream=stream=>{var _a8;return"function"==typeof ReadableStream&&((null==(_a8=null==stream?void 0:stream.constructor)?void 0:_a8.name)===ReadableStream.name||stream instanceof ReadableStream)};createChecksumStream=({expectedChecksum,checksum,source:source2,checksumSourceLocation,base64Encoder})=>{var _a8,_b5;if(!isReadableStream(source2))throw new Error(`@smithy/util-stream: unsupported source type ${null!=(_b5=null==(_a8=null==source2?void 0:source2.constructor)?void 0:_a8.name)?_b5:source2} in ChecksumStream.`);const encoder2=null!=base64Encoder?base64Encoder:toBase64;if("function"!=typeof TransformStream)throw new Error("@smithy/util-stream: unable to instantiate ChecksumStream because API unavailable: ReadableStream/TransformStream.");const transform2=new TransformStream({start(){},async transform(chunk,controller){checksum.update(chunk);controller.enqueue(chunk)},async flush(controller){const digest=await checksum.digest(),received=encoder2(digest);if(expectedChecksum!==received){const error=new Error(`Checksum mismatch: expected "${expectedChecksum}" but received "${received}" in response header "${checksumSourceLocation}".`);controller.error(error)}else controller.terminate()}});source2.pipeThrough(transform2);const readable2=transform2.readable;Object.setPrototypeOf(readable2,ChecksumStream.prototype);return readable2};ByteArrayCollector=class{constructor(allocByteArray){this.allocByteArray=allocByteArray;this.byteLength=0;this.byteArrays=[]}push(byteArray){this.byteArrays.push(byteArray);this.byteLength+=byteArray.byteLength}flush(){if(1===this.byteArrays.length){const bytes=this.byteArrays[0];this.reset();return bytes}const aggregation=this.allocByteArray(this.byteLength);let cursor=0;for(let i2=0;i2<this.byteArrays.length;++i2){const bytes=this.byteArrays[i2];aggregation.set(bytes,cursor);cursor+=bytes.byteLength}this.reset();return aggregation}reset(){this.byteArrays=[];this.byteLength=0}};createBufferedReadable=function createBufferedReadableStream(upstream,size,logger2){const reader=upstream.getReader();let streamBufferingLoggedWarning=!1,bytesSeen=0;const buffers=["",new ByteArrayCollector((size2=>new Uint8Array(size2)))];let mode=-1;const pull=async controller=>{const{value,done}=await reader.read(),chunk=value;if(done){if(-1!==mode){const remainder=flush(buffers,mode);sizeOf(remainder)>0&&controller.enqueue(remainder)}controller.close()}else{const chunkMode=modeOf(chunk,!1);if(mode!==chunkMode){mode>=0&&controller.enqueue(flush(buffers,mode));mode=chunkMode}if(-1===mode){controller.enqueue(chunk);return}const chunkSize2=sizeOf(chunk);bytesSeen+=chunkSize2;const bufferSize=sizeOf(buffers[mode]);if(chunkSize2>=size&&0===bufferSize)controller.enqueue(chunk);else{const newSize=merge(buffers,mode,chunk);if(!streamBufferingLoggedWarning&&bytesSeen>2*size){streamBufferingLoggedWarning=!0;null==logger2||logger2.warn(`@smithy/util-stream - stream chunk size ${chunkSize2} is below threshold of ${size}, automatically buffering.`)}newSize>=size?controller.enqueue(flush(buffers,mode)):await pull(controller)}}};return new ReadableStream({pull})};getAwsChunkedEncodingStream=(readableStream,options)=>{const{base64Encoder,bodyLengthChecker,checksumAlgorithmFn,checksumLocationName,streamHasher}=options,checksumRequired=void 0!==base64Encoder&&void 0!==bodyLengthChecker&&void 0!==checksumAlgorithmFn&&void 0!==checksumLocationName&&void 0!==streamHasher,digest=checksumRequired?streamHasher(checksumAlgorithmFn,readableStream):void 0,reader=readableStream.getReader();return new ReadableStream({async pull(controller){const{value,done}=await reader.read();if(done){controller.enqueue("0\r\n");if(checksumRequired){const checksum=base64Encoder(await digest);controller.enqueue(`${checksumLocationName}:${checksum}\r\n`);controller.enqueue("\r\n")}controller.close()}else controller.enqueue(`${(bodyLengthChecker(value)||0).toString(16)}\r\n${value}\r\n`)}})};escapeUri=uri=>encodeURIComponent(uri).replace(/[!'()*]/g,hexEncode);hexEncode=c3=>`%${c3.charCodeAt(0).toString(16).toUpperCase()}`;keepAliveSupport={supported:void 0};FetchHttpHandler=class _FetchHttpHandler{static create(instanceOrOptions){return"function"==typeof(null==instanceOrOptions?void 0:instanceOrOptions.handle)?instanceOrOptions:new _FetchHttpHandler(instanceOrOptions)}constructor(options){if("function"==typeof options)this.configProvider=options().then((opts=>opts||{}));else{this.config=null!=options?options:{};this.configProvider=Promise.resolve(this.config)}void 0===keepAliveSupport.supported&&(keepAliveSupport.supported=Boolean("undefined"!=typeof Request&&"keepalive"in createRequest("https://[::1]")))}destroy(){}async handle(request2,{abortSignal}={}){var _a8,_b5,_c3;this.config||(this.config=await this.configProvider);const requestTimeoutInMs=this.config.requestTimeout,keepAlive=!0===this.config.keepAlive,credentials=this.config.credentials;if(null==abortSignal?void 0:abortSignal.aborted){const abortError=new Error("Request aborted");abortError.name="AbortError";return Promise.reject(abortError)}let path2=request2.path;const queryString=buildQueryString(request2.query||{});queryString&&(path2+=`?${queryString}`);request2.fragment&&(path2+=`#${request2.fragment}`);let auth="";null==request2.username&&null==request2.password||(auth=`${null!=(_a8=request2.username)?_a8:""}:${null!=(_b5=request2.password)?_b5:""}@`);const{port,method}=request2,url=`${request2.protocol}//${auth}${request2.hostname}${port?`:${port}`:""}${path2}`,body="GET"===method||"HEAD"===method?void 0:request2.body,requestOptions={body,headers:new Headers(request2.headers),method,credentials};(null==(_c3=this.config)?void 0:_c3.cache)&&(requestOptions.cache=this.config.cache);body&&(requestOptions.duplex="half");"undefined"!=typeof AbortController&&(requestOptions.signal=abortSignal);keepAliveSupport.supported&&(requestOptions.keepalive=keepAlive);"function"==typeof this.config.requestInit&&Object.assign(requestOptions,this.config.requestInit(request2));let removeSignalEventListener=()=>{};const fetchRequest=createRequest(url,requestOptions),raceOfPromises=[fetch(fetchRequest).then((response=>{const fetchHeaders=response.headers,transformedHeaders={};for(const pair of fetchHeaders.entries())transformedHeaders[pair[0]]=pair[1];return null!=response.body?{response:new HttpResponse({headers:transformedHeaders,reason:response.statusText,statusCode:response.status,body:response.body})}:response.blob().then((body2=>({response:new HttpResponse({headers:transformedHeaders,reason:response.statusText,statusCode:response.status,body:body2})})))})),requestTimeout(requestTimeoutInMs)];abortSignal&&raceOfPromises.push(new Promise(((resolve,reject)=>{const onAbort=()=>{const abortError=new Error("Request aborted");abortError.name="AbortError";reject(abortError)};if("function"==typeof abortSignal.addEventListener){const signal=abortSignal;signal.addEventListener("abort",onAbort,{once:!0});removeSignalEventListener=()=>signal.removeEventListener("abort",onAbort)}else abortSignal.onabort=onAbort})));return Promise.race(raceOfPromises).finally(removeSignalEventListener)}updateHttpClientConfig(key3,value){this.config=void 0;this.configProvider=this.configProvider.then((config=>{config[key3]=value;return config}))}httpHandlerConfigs(){var _a8;return null!=(_a8=this.config)?_a8:{}}};streamCollector=async stream=>{var _a8;return"function"==typeof Blob&&stream instanceof Blob||"Blob"===(null==(_a8=stream.constructor)?void 0:_a8.name)?void 0!==Blob.prototype.arrayBuffer?new Uint8Array(await stream.arrayBuffer()):collectBlob(stream):collectStream(stream)};SHORT_TO_HEX={};HEX_TO_SHORT={};for(let i2=0;i2<256;i2++){let encodedByte=i2.toString(16).toLowerCase();1===encodedByte.length&&(encodedByte=`0${encodedByte}`);SHORT_TO_HEX[i2]=encodedByte;HEX_TO_SHORT[encodedByte]=i2}sdkStreamMixin=stream=>{var _a8,_b5;if(!isBlobInstance(stream)&&!isReadableStream(stream)){const name=(null==(_b5=null==(_a8=null==stream?void 0:stream.__proto__)?void 0:_a8.constructor)?void 0:_b5.name)||stream;throw new Error(`Unexpected stream implementation, expect Blob or ReadableStream, got ${name}`)}let transformed=!1;const transformToByteArray=async()=>{if(transformed)throw new Error("The stream has already been transformed.");transformed=!0;return await streamCollector(stream)},blobToWebStream=blob=>{if("function"!=typeof blob.stream)throw new Error("Cannot transform payload Blob to web stream. Please make sure the Blob.stream() is polyfilled.\nIf you are using React Native, this API is not yet supported, see: https://react-native.canny.io/feature-requests/p/fetch-streaming-body");return blob.stream()};return Object.assign(stream,{transformToByteArray,transformToString:async encoding=>{const buf=await transformToByteArray();if("base64"===encoding)return toBase64(buf);if("hex"===encoding)return toHex2(buf);if(void 0===encoding||"utf8"===encoding||"utf-8"===encoding)return toUtf8(buf);if("function"==typeof TextDecoder)return new TextDecoder(encoding).decode(buf);throw new Error("TextDecoder is not available, please make sure polyfill is provided.")},transformToWebStream:()=>{if(transformed)throw new Error("The stream has already been transformed.");transformed=!0;if(isBlobInstance(stream))return blobToWebStream(stream);if(isReadableStream(stream))return stream;throw new Error(`Cannot transform payload to web stream, got ${stream}`)}})};isBlobInstance=stream=>"function"==typeof Blob&&stream instanceof Blob;collectBody=async(streamBody=new Uint8Array,context2)=>{if(streamBody instanceof Uint8Array)return Uint8ArrayBlobAdapter.mutate(streamBody);if(!streamBody)return Uint8ArrayBlobAdapter.mutate(new Uint8Array);const fromContext=context2.streamCollector(streamBody);return Uint8ArrayBlobAdapter.mutate(await fromContext)};resolvedPath=(resolvedPath2,input,memberName,labelValueProvider,uriLabel,isGreedyLabel)=>{if(null==input||void 0===input[memberName])throw new Error("No value provided for input HTTP label: "+memberName+".");{const labelValue=labelValueProvider();if(labelValue.length<=0)throw new Error("Empty value provided for input HTTP label: "+memberName+".");resolvedPath2=resolvedPath2.replace(uriLabel,isGreedyLabel?labelValue.split("/").map((segment=>extendedEncodeURIComponent(segment))).join("/"):extendedEncodeURIComponent(labelValue))}return resolvedPath2};RequestBuilder=class{constructor(input,context2){this.input=input;this.context=context2;this.query={};this.method="";this.headers={};this.path="";this.body=null;this.hostname="";this.resolvePathStack=[]}async build(){const{hostname,protocol="https",port,path:basePath}=await this.context.endpoint();this.path=basePath;for(const resolvePath of this.resolvePathStack)resolvePath(this.path);return new HttpRequest({protocol,hostname:this.hostname||hostname,port,method:this.method,path:this.path,query:this.query,body:this.body,headers:this.headers})}hn(hostname){this.hostname=hostname;return this}bp(uriLabel){this.resolvePathStack.push((basePath=>{this.path=`${(null==basePath?void 0:basePath.endsWith("/"))?basePath.slice(0,-1):basePath||""}`+uriLabel}));return this}p(memberName,labelValueProvider,uriLabel,isGreedyLabel){this.resolvePathStack.push((path2=>{this.path=resolvedPath(path2,this.input,memberName,labelValueProvider,uriLabel,isGreedyLabel)}));return this}h(headers){this.headers=headers;return this}q(query3){this.query=query3;return this}b(body){this.body=body;return this}m(method){this.method=method;return this}};DefaultIdentityProviderConfig=class{constructor(config){this.authSchemes=new Map;for(const[key3,value]of Object.entries(config))void 0!==value&&this.authSchemes.set(key3,value)}getIdentityProvider(schemeId){return this.authSchemes.get(schemeId)}};isIdentityExpired=(()=>identity=>doesIdentityRequireRefresh(identity)&&identity.expiration.getTime()-Date.now()<3e5)();doesIdentityRequireRefresh=identity=>void 0!==identity.expiration;memoizeIdentityProvider=(provider,isExpired,requiresRefresh)=>{if(void 0===provider)return;const normalizedProvider="function"!=typeof provider?async()=>Promise.resolve(provider):provider;let resolved,pending3,hasResult,isConstant=!1;const coalesceProvider=async options=>{pending3||(pending3=normalizedProvider(options));try{resolved=await pending3;hasResult=!0;isConstant=!1}finally{pending3=void 0}return resolved};return void 0===isExpired?async options=>{hasResult&&!(null==options?void 0:options.forceRefresh)||(resolved=await coalesceProvider(options));return resolved}:async options=>{hasResult&&!(null==options?void 0:options.forceRefresh)||(resolved=await coalesceProvider(options));if(isConstant)return resolved;if(!requiresRefresh(resolved)){isConstant=!0;return resolved}if(isExpired(resolved)){await coalesceProvider(options);return resolved}return resolved}};Error;memoize=(provider,isExpired,requiresRefresh)=>{let resolved,pending3,hasResult,isConstant=!1;const coalesceProvider=async()=>{pending3||(pending3=provider());try{resolved=await pending3;hasResult=!0;isConstant=!1}finally{pending3=void 0}return resolved};return void 0===isExpired?async options=>{hasResult&&!(null==options?void 0:options.forceRefresh)||(resolved=await coalesceProvider());return resolved}:async options=>{hasResult&&!(null==options?void 0:options.forceRefresh)||(resolved=await coalesceProvider());if(isConstant)return resolved;if(requiresRefresh&&!requiresRefresh(resolved)){isConstant=!0;return resolved}if(isExpired(resolved)){await coalesceProvider();return resolved}return resolved}};resolveAwsSdkSigV4AConfig=config=>{config.sigv4aSigningRegionSet=normalizeProvider2(config.sigv4aSigningRegionSet);return config};AMZ_DATE_HEADER=(AMZ_DATE_QUERY_PARAM="X-Amz-Date").toLowerCase();GENERATED_HEADERS=["authorization",AMZ_DATE_HEADER,"date"];SIGNATURE_HEADER="X-Amz-Signature".toLowerCase();TOKEN_HEADER="X-Amz-Security-Token".toLowerCase();ALWAYS_UNSIGNABLE_HEADERS={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0};PROXY_HEADER_PATTERN=/^proxy-/;SEC_HEADER_PATTERN=/^sec-/;EVENT_ALGORITHM_IDENTIFIER="AWS4-HMAC-SHA256-PAYLOAD";signingKeyCache={};cacheQueue=[];createScope=(shortDate,region,service)=>`${shortDate}/${region}/${service}/aws4_request`;getSigningKey=async(sha256Constructor,credentials,shortDate,region,service)=>{const cacheKey=`${shortDate}:${region}:${service}:${toHex2(await hmac(sha256Constructor,credentials.secretAccessKey,credentials.accessKeyId))}:${credentials.sessionToken}`;if(cacheKey in signingKeyCache)return signingKeyCache[cacheKey];cacheQueue.push(cacheKey);for(;cacheQueue.length>50;)delete signingKeyCache[cacheQueue.shift()];let key3=`AWS4${credentials.secretAccessKey}`;for(const signable of[shortDate,region,service,"aws4_request"])key3=await hmac(sha256Constructor,key3,signable);return signingKeyCache[cacheKey]=key3};hmac=(ctor,secret,data)=>{const hash3=new ctor(secret);hash3.update(toUint8Array(data));return hash3.digest()};getCanonicalHeaders=({headers},unsignableHeaders,signableHeaders)=>{const canonical={};for(const headerName of Object.keys(headers).sort()){if(null==headers[headerName])continue;const canonicalHeaderName=headerName.toLowerCase();(canonicalHeaderName in ALWAYS_UNSIGNABLE_HEADERS||(null==unsignableHeaders?void 0:unsignableHeaders.has(canonicalHeaderName))||PROXY_HEADER_PATTERN.test(canonicalHeaderName)||SEC_HEADER_PATTERN.test(canonicalHeaderName))&&(!signableHeaders||signableHeaders&&!signableHeaders.has(canonicalHeaderName))||(canonical[canonicalHeaderName]=headers[headerName].trim().replace(/\s+/g," "))}return canonical};isArrayBuffer=arg=>"function"==typeof ArrayBuffer&&arg instanceof ArrayBuffer||"[object ArrayBuffer]"===Object.prototype.toString.call(arg);getPayloadHash=async({headers,body},hashConstructor)=>{for(const headerName of Object.keys(headers))if("x-amz-content-sha256"===headerName.toLowerCase())return headers[headerName];if(null==body)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if("string"==typeof body||ArrayBuffer.isView(body)||isArrayBuffer(body)){const hashCtor=new hashConstructor;hashCtor.update(toUint8Array(body));return toHex2(await hashCtor.digest())}return"UNSIGNED-PAYLOAD"};HeaderFormatter=class{format(headers){const chunks=[];for(const headerName of Object.keys(headers)){const bytes=fromUtf8(headerName);chunks.push(Uint8Array.from([bytes.byteLength]),bytes,this.formatHeaderValue(headers[headerName]))}const out=new Uint8Array(chunks.reduce(((carry,bytes)=>carry+bytes.byteLength),0));let position=0;for(const chunk of chunks){out.set(chunk,position);position+=chunk.byteLength}return out}formatHeaderValue(header){switch(header.type){case"boolean":return Uint8Array.from([header.value?0:1]);case"byte":return Uint8Array.from([2,header.value]);case"short":const shortView=new DataView(new ArrayBuffer(3));shortView.setUint8(0,3);shortView.setInt16(1,header.value,!1);return new Uint8Array(shortView.buffer);case"integer":const intView=new DataView(new ArrayBuffer(5));intView.setUint8(0,4);intView.setInt32(1,header.value,!1);return new Uint8Array(intView.buffer);case"long":const longBytes=new Uint8Array(9);longBytes[0]=5;longBytes.set(header.value.bytes,1);return longBytes;case"binary":const binView=new DataView(new ArrayBuffer(3+header.value.byteLength));binView.setUint8(0,6);binView.setUint16(1,header.value.byteLength,!1);const binBytes=new Uint8Array(binView.buffer);binBytes.set(header.value,3);return binBytes;case"string":const utf8Bytes=fromUtf8(header.value),strView=new DataView(new ArrayBuffer(3+utf8Bytes.byteLength));strView.setUint8(0,7);strView.setUint16(1,utf8Bytes.byteLength,!1);const strBytes=new Uint8Array(strView.buffer);strBytes.set(utf8Bytes,3);return strBytes;case"timestamp":const tsBytes=new Uint8Array(9);tsBytes[0]=8;tsBytes.set(Int64.fromNumber(header.value.valueOf()).bytes,1);return tsBytes;case"uuid":if(!UUID_PATTERN.test(header.value))throw new Error(`Invalid UUID received: ${header.value}`);const uuidBytes=new Uint8Array(17);uuidBytes[0]=9;uuidBytes.set(fromHex(header.value.replace(/\-/g,"")),1);return uuidBytes}}};(function(HEADER_VALUE_TYPE3){HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.boolTrue=0]="boolTrue";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.boolFalse=1]="boolFalse";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.byte=2]="byte";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.short=3]="short";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.integer=4]="integer";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.long=5]="long";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.byteArray=6]="byteArray";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.string=7]="string";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.timestamp=8]="timestamp";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.uuid=9]="uuid"})(HEADER_VALUE_TYPE||(HEADER_VALUE_TYPE={}));UUID_PATTERN=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;Int64=class _Int64{constructor(bytes){this.bytes=bytes;if(8!==bytes.byteLength)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(number){if(number>0x8000000000000000||number<-0x8000000000000000)throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);const bytes=new Uint8Array(8);for(let i2=7,remaining=Math.abs(Math.round(number));i2>-1&&remaining>0;i2--,remaining/=256)bytes[i2]=remaining;number<0&&negate(bytes);return new _Int64(bytes)}valueOf(){const bytes=this.bytes.slice(0),negative=128&bytes[0];negative&&negate(bytes);return parseInt(toHex2(bytes),16)*(negative?-1:1)}toString(){return String(this.valueOf())}};hasHeader=(soughtHeader,headers)=>{soughtHeader=soughtHeader.toLowerCase();for(const headerName of Object.keys(headers))if(soughtHeader===headerName.toLowerCase())return!0;return!1};moveHeadersToQuery=(request2,options={})=>{var _a8,_b5;const{headers,query:query3={}}=HttpRequest.clone(request2);for(const name of Object.keys(headers)){const lname=name.toLowerCase();if("x-amz-"===lname.slice(0,6)&&!(null==(_a8=options.unhoistableHeaders)?void 0:_a8.has(lname))||(null==(_b5=options.hoistableHeaders)?void 0:_b5.has(lname))){query3[name]=headers[name];delete headers[name]}}return{...request2,headers,query:query3}};prepareRequest=request2=>{request2=HttpRequest.clone(request2);for(const headerName of Object.keys(request2.headers))GENERATED_HEADERS.indexOf(headerName.toLowerCase())>-1&&delete request2.headers[headerName];return request2};getCanonicalQuery=({query:query3={}})=>{const keys3=[],serialized2={};for(const key3 of Object.keys(query3)){if(key3.toLowerCase()===SIGNATURE_HEADER)continue;const encodedKey=escapeUri(key3);keys3.push(encodedKey);const value=query3[key3];"string"==typeof value?serialized2[encodedKey]=`${encodedKey}=${escapeUri(value)}`:Array.isArray(value)&&(serialized2[encodedKey]=value.slice(0).reduce(((encoded,value2)=>encoded.concat([`${encodedKey}=${escapeUri(value2)}`])),[]).sort().join("&"))}return keys3.sort().map((key3=>serialized2[key3])).filter((serialized3=>serialized3)).join("&")};iso8601=time=>toDate(time).toISOString().replace(/\.\d{3}Z$/,"Z");toDate=time=>"number"==typeof time?new Date(1e3*time):"string"==typeof time?Number(time)?new Date(1e3*Number(time)):new Date(time):time;SignatureV4Base=class{constructor({applyChecksum,credentials,region,service,sha256,uriEscapePath=!0}){this.service=service;this.sha256=sha256;this.uriEscapePath=uriEscapePath;this.applyChecksum="boolean"!=typeof applyChecksum||applyChecksum;this.regionProvider=normalizeProvider(region);this.credentialProvider=normalizeProvider(credentials)}createCanonicalRequest(request2,canonicalHeaders,payloadHash){const sortedHeaders=Object.keys(canonicalHeaders).sort();return`${request2.method}\n${this.getCanonicalPath(request2)}\n${getCanonicalQuery(request2)}\n${sortedHeaders.map((name=>`${name}:${canonicalHeaders[name]}`)).join("\n")}\n\n${sortedHeaders.join(";")}\n${payloadHash}`}async createStringToSign(longDate,credentialScope,canonicalRequest,algorithmIdentifier){const hash3=new this.sha256;hash3.update(toUint8Array(canonicalRequest));return`${algorithmIdentifier}\n${longDate}\n${credentialScope}\n${toHex2(await hash3.digest())}`}getCanonicalPath({path:path2}){if(this.uriEscapePath){const normalizedPathSegments=[];for(const pathSegment of path2.split("/"))0!==(null==pathSegment?void 0:pathSegment.length)&&"."!==pathSegment&&(".."===pathSegment?normalizedPathSegments.pop():normalizedPathSegments.push(pathSegment));const normalizedPath=`${(null==path2?void 0:path2.startsWith("/"))?"/":""}${normalizedPathSegments.join("/")}${normalizedPathSegments.length>0&&(null==path2?void 0:path2.endsWith("/"))?"/":""}`;return escapeUri(normalizedPath).replace(/%2F/g,"/")}return path2}validateResolvedCredentials(credentials){if("object"!=typeof credentials||"string"!=typeof credentials.accessKeyId||"string"!=typeof credentials.secretAccessKey)throw new Error("Resolved credential object is not valid")}formatDate(now3){const longDate=iso8601(now3).replace(/[\-:]/g,"");return{longDate,shortDate:longDate.slice(0,8)}}getCanonicalHeaderList(headers){return Object.keys(headers).sort().join(";")}};SignatureV4=class extends SignatureV4Base{constructor({applyChecksum,credentials,region,service,sha256,uriEscapePath=!0}){super({applyChecksum,credentials,region,service,sha256,uriEscapePath});this.headerFormatter=new HeaderFormatter}async presign(originalRequest,options={}){const{signingDate=new Date,expiresIn=3600,unsignableHeaders,unhoistableHeaders,signableHeaders,hoistableHeaders,signingRegion,signingService}=options,credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=null!=signingRegion?signingRegion:await this.regionProvider(),{longDate,shortDate}=this.formatDate(signingDate);if(expiresIn>604800)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const scope=createScope(shortDate,region,null!=signingService?signingService:this.service),request2=moveHeadersToQuery(prepareRequest(originalRequest),{unhoistableHeaders,hoistableHeaders});credentials.sessionToken&&(request2.query["X-Amz-Security-Token"]=credentials.sessionToken);request2.query["X-Amz-Algorithm"]="AWS4-HMAC-SHA256";request2.query["X-Amz-Credential"]=`${credentials.accessKeyId}/${scope}`;request2.query[AMZ_DATE_QUERY_PARAM]=longDate;request2.query["X-Amz-Expires"]=expiresIn.toString(10);const canonicalHeaders=getCanonicalHeaders(request2,unsignableHeaders,signableHeaders);request2.query["X-Amz-SignedHeaders"]=this.getCanonicalHeaderList(canonicalHeaders);request2.query["X-Amz-Signature"]=await this.getSignature(longDate,scope,this.getSigningKey(credentials,region,shortDate,signingService),this.createCanonicalRequest(request2,canonicalHeaders,await getPayloadHash(originalRequest,this.sha256)));return request2}async sign(toSign,options){return"string"==typeof toSign?this.signString(toSign,options):toSign.headers&&toSign.payload?this.signEvent(toSign,options):toSign.message?this.signMessage(toSign,options):this.signRequest(toSign,options)}async signEvent({headers,payload},{signingDate=new Date,priorSignature,signingRegion,signingService}){const region=null!=signingRegion?signingRegion:await this.regionProvider(),{shortDate,longDate}=this.formatDate(signingDate),scope=createScope(shortDate,region,null!=signingService?signingService:this.service),hashedPayload=await getPayloadHash({headers:{},body:payload},this.sha256),hash3=new this.sha256;hash3.update(headers);const hashedHeaders=toHex2(await hash3.digest()),stringToSign=[EVENT_ALGORITHM_IDENTIFIER,longDate,scope,priorSignature,hashedHeaders,hashedPayload].join("\n");return this.signString(stringToSign,{signingDate,signingRegion:region,signingService})}async signMessage(signableMessage,{signingDate=new Date,signingRegion,signingService}){return this.signEvent({headers:this.headerFormatter.format(signableMessage.message.headers),payload:signableMessage.message.body},{signingDate,signingRegion,signingService,priorSignature:signableMessage.priorSignature}).then((signature=>({message:signableMessage.message,signature})))}async signString(stringToSign,{signingDate=new Date,signingRegion,signingService}={}){const credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=null!=signingRegion?signingRegion:await this.regionProvider(),{shortDate}=this.formatDate(signingDate),hash3=new this.sha256(await this.getSigningKey(credentials,region,shortDate,signingService));hash3.update(toUint8Array(stringToSign));return toHex2(await hash3.digest())}async signRequest(requestToSign,{signingDate=new Date,signableHeaders,unsignableHeaders,signingRegion,signingService}={}){const credentials=await this.credentialProvider();this.validateResolvedCredentials(credentials);const region=null!=signingRegion?signingRegion:await this.regionProvider(),request2=prepareRequest(requestToSign),{longDate,shortDate}=this.formatDate(signingDate),scope=createScope(shortDate,region,null!=signingService?signingService:this.service);request2.headers[AMZ_DATE_HEADER]=longDate;credentials.sessionToken&&(request2.headers[TOKEN_HEADER]=credentials.sessionToken);const payloadHash=await getPayloadHash(request2,this.sha256);!hasHeader("x-amz-content-sha256",request2.headers)&&this.applyChecksum&&(request2.headers["x-amz-content-sha256"]=payloadHash);const canonicalHeaders=getCanonicalHeaders(request2,unsignableHeaders,signableHeaders),signature=await this.getSignature(longDate,scope,this.getSigningKey(credentials,region,shortDate,signingService),this.createCanonicalRequest(request2,canonicalHeaders,payloadHash));request2.headers.authorization=`AWS4-HMAC-SHA256 Credential=${credentials.accessKeyId}/${scope}, SignedHeaders=${this.getCanonicalHeaderList(canonicalHeaders)}, Signature=${signature}`;return request2}async getSignature(longDate,credentialScope,keyPromise,canonicalRequest){const stringToSign=await this.createStringToSign(longDate,credentialScope,canonicalRequest,"AWS4-HMAC-SHA256"),hash3=new this.sha256(await keyPromise);hash3.update(toUint8Array(stringToSign));return toHex2(await hash3.digest())}getSigningKey(credentials,region,shortDate,service){return getSigningKey(this.sha256,credentials,shortDate,region,service||this.service)}};resolveAwsSdkSigV4Config=config=>{let resolvedCredentials,inputCredentials=config.credentials,isUserSupplied=!!config.credentials;Object.defineProperty(config,"credentials",{set(credentials){credentials&&credentials!==inputCredentials&&credentials!==resolvedCredentials&&(isUserSupplied=!0);inputCredentials=credentials;const memoizedProvider=normalizeCredentialProvider(config,{credentials:inputCredentials,credentialDefaultProvider:config.credentialDefaultProvider}),boundProvider=bindCallerConfig(config,memoizedProvider);if(isUserSupplied&&!boundProvider.attributed){resolvedCredentials=async options=>boundProvider(options).then((creds=>setCredentialFeature(creds,"CREDENTIALS_CODE","e")));resolvedCredentials.memoized=boundProvider.memoized;resolvedCredentials.configBound=boundProvider.configBound;resolvedCredentials.attributed=!0}else resolvedCredentials=boundProvider},get:()=>resolvedCredentials,enumerable:!0,configurable:!0});config.credentials=inputCredentials;const{signingEscapePath=!0,systemClockOffset=config.systemClockOffset||0,sha256}=config;let signer;signer=config.signer?normalizeProvider2(config.signer):config.regionInfoProvider?()=>normalizeProvider2(config.region)().then((async region=>[await config.regionInfoProvider(region,{useFipsEndpoint:await config.useFipsEndpoint(),useDualstackEndpoint:await config.useDualstackEndpoint()})||{},region])).then((([regionInfo,region])=>{const{signingRegion,signingService}=regionInfo;config.signingRegion=config.signingRegion||signingRegion||region;config.signingName=config.signingName||signingService||config.serviceId;const params={...config,credentials:config.credentials,region:config.signingRegion,service:config.signingName,sha256,uriEscapePath:signingEscapePath};return new(config.signerConstructor||SignatureV4)(params)})):async authScheme=>{const signingRegion=(authScheme=Object.assign({},{name:"sigv4",signingName:config.signingName||config.defaultSigningName,signingRegion:await normalizeProvider2(config.region)(),properties:{}},authScheme)).signingRegion,signingService=authScheme.signingName;config.signingRegion=config.signingRegion||signingRegion;config.signingName=config.signingName||signingService||config.serviceId;const params={...config,credentials:config.credentials,region:config.signingRegion,service:config.signingName,sha256,uriEscapePath:signingEscapePath};return new(config.signerConstructor||SignatureV4)(params)};return Object.assign(config,{systemClockOffset,signingEscapePath,signer})};getAllAliases=(name,aliases)=>{const _aliases=[];name&&_aliases.push(name);if(aliases)for(const alias of aliases)_aliases.push(alias);return _aliases};getMiddlewareNameWithAliases=(name,aliases)=>`${name||"anonymous"}${aliases&&aliases.length>0?` (a.k.a. ${aliases.join(",")})`:""}`;constructStack=()=>{let absoluteEntries=[],relativeEntries=[],identifyOnResolve=!1;const entriesNameSet=new Set,sort=entries2=>entries2.sort(((a2,b3)=>stepWeights[b3.step]-stepWeights[a2.step]||priorityWeights[b3.priority||"normal"]-priorityWeights[a2.priority||"normal"])),removeByName=toRemove=>{let isRemoved=!1;const filterCb=entry=>{const aliases=getAllAliases(entry.name,entry.aliases);if(aliases.includes(toRemove)){isRemoved=!0;for(const alias of aliases)entriesNameSet.delete(alias);return!1}return!0};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved},removeByReference=toRemove=>{let isRemoved=!1;const filterCb=entry=>{if(entry.middleware===toRemove){isRemoved=!0;for(const alias of getAllAliases(entry.name,entry.aliases))entriesNameSet.delete(alias);return!1}return!0};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved},cloneTo=toStack=>{var _a8;absoluteEntries.forEach((entry=>{toStack.add(entry.middleware,{...entry})}));relativeEntries.forEach((entry=>{toStack.addRelativeTo(entry.middleware,{...entry})}));null==(_a8=toStack.identifyOnResolve)||_a8.call(toStack,stack2.identifyOnResolve());return toStack},expandRelativeMiddlewareList=from=>{const expandedMiddlewareList=[];from.before.forEach((entry=>{0===entry.before.length&&0===entry.after.length?expandedMiddlewareList.push(entry):expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry))}));expandedMiddlewareList.push(from);from.after.reverse().forEach((entry=>{0===entry.before.length&&0===entry.after.length?expandedMiddlewareList.push(entry):expandedMiddlewareList.push(...expandRelativeMiddlewareList(entry))}));return expandedMiddlewareList},getMiddlewareList=(debug2=!1)=>{const normalizedAbsoluteEntries=[],normalizedRelativeEntries=[],normalizedEntriesNameMap={};absoluteEntries.forEach((entry=>{const normalizedEntry={...entry,before:[],after:[]};for(const alias of getAllAliases(normalizedEntry.name,normalizedEntry.aliases))normalizedEntriesNameMap[alias]=normalizedEntry;normalizedAbsoluteEntries.push(normalizedEntry)}));relativeEntries.forEach((entry=>{const normalizedEntry={...entry,before:[],after:[]};for(const alias of getAllAliases(normalizedEntry.name,normalizedEntry.aliases))normalizedEntriesNameMap[alias]=normalizedEntry;normalizedRelativeEntries.push(normalizedEntry)}));normalizedRelativeEntries.forEach((entry=>{if(entry.toMiddleware){const toMiddleware=normalizedEntriesNameMap[entry.toMiddleware];if(void 0===toMiddleware){if(debug2)return;throw new Error(`${entry.toMiddleware} is not found when adding ${getMiddlewareNameWithAliases(entry.name,entry.aliases)} middleware ${entry.relation} ${entry.toMiddleware}`)}"after"===entry.relation&&toMiddleware.after.push(entry);"before"===entry.relation&&toMiddleware.before.push(entry)}}));return sort(normalizedAbsoluteEntries).map(expandRelativeMiddlewareList).reduce(((wholeList,expandedMiddlewareList)=>{wholeList.push(...expandedMiddlewareList);return wholeList}),[])},stack2={add:(middleware,options={})=>{const{name,override,aliases:_aliases}=options,entry={step:"initialize",priority:"normal",middleware,...options},aliases=getAllAliases(name,_aliases);if(aliases.length>0){if(aliases.some((alias=>entriesNameSet.has(alias)))){if(!override)throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name,_aliases)}'`);for(const alias of aliases){const toOverrideIndex=absoluteEntries.findIndex((entry2=>{var _a8;return entry2.name===alias||(null==(_a8=entry2.aliases)?void 0:_a8.some((a2=>a2===alias)))}));if(-1===toOverrideIndex)continue;const toOverride=absoluteEntries[toOverrideIndex];if(toOverride.step!==entry.step||entry.priority!==toOverride.priority)throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name,toOverride.aliases)}" middleware with ${toOverride.priority} priority in ${toOverride.step} step cannot be overridden by "${getMiddlewareNameWithAliases(name,_aliases)}" middleware with ${entry.priority} priority in ${entry.step} step.`);absoluteEntries.splice(toOverrideIndex,1)}}for(const alias of aliases)entriesNameSet.add(alias)}absoluteEntries.push(entry)},addRelativeTo:(middleware,options)=>{const{name,override,aliases:_aliases}=options,entry={middleware,...options},aliases=getAllAliases(name,_aliases);if(aliases.length>0){if(aliases.some((alias=>entriesNameSet.has(alias)))){if(!override)throw new Error(`Duplicate middleware name '${getMiddlewareNameWithAliases(name,_aliases)}'`);for(const alias of aliases){const toOverrideIndex=relativeEntries.findIndex((entry2=>{var _a8;return entry2.name===alias||(null==(_a8=entry2.aliases)?void 0:_a8.some((a2=>a2===alias)))}));if(-1===toOverrideIndex)continue;const toOverride=relativeEntries[toOverrideIndex];if(toOverride.toMiddleware!==entry.toMiddleware||toOverride.relation!==entry.relation)throw new Error(`"${getMiddlewareNameWithAliases(toOverride.name,toOverride.aliases)}" middleware ${toOverride.relation} "${toOverride.toMiddleware}" middleware cannot be overridden by "${getMiddlewareNameWithAliases(name,_aliases)}" middleware ${entry.relation} "${entry.toMiddleware}" middleware.`);relativeEntries.splice(toOverrideIndex,1)}}for(const alias of aliases)entriesNameSet.add(alias)}relativeEntries.push(entry)},clone:()=>cloneTo(constructStack()),use:plugin3=>{plugin3.applyToStack(stack2)},remove:toRemove=>"string"==typeof toRemove?removeByName(toRemove):removeByReference(toRemove),removeByTag:toRemove=>{let isRemoved=!1;const filterCb=entry=>{const{tags,name,aliases:_aliases}=entry;if(tags&&tags.includes(toRemove)){const aliases=getAllAliases(name,_aliases);for(const alias of aliases)entriesNameSet.delete(alias);isRemoved=!0;return!1}return!0};absoluteEntries=absoluteEntries.filter(filterCb);relativeEntries=relativeEntries.filter(filterCb);return isRemoved},concat:from=>{var _a8,_b5;const cloned=cloneTo(constructStack());cloned.use(from);cloned.identifyOnResolve(identifyOnResolve||cloned.identifyOnResolve()||null!=(_b5=null==(_a8=from.identifyOnResolve)?void 0:_a8.call(from))&&_b5);return cloned},applyToStack:cloneTo,identify:()=>getMiddlewareList(!0).map((mw=>{var _a8;const step=null!=(_a8=mw.step)?_a8:mw.relation+" "+mw.toMiddleware;return getMiddlewareNameWithAliases(mw.name,mw.aliases)+" - "+step})),identifyOnResolve(toggle){"boolean"==typeof toggle&&(identifyOnResolve=toggle);return identifyOnResolve},resolve:(handler,context2)=>{for(const middleware of getMiddlewareList().map((entry=>entry.middleware)).reverse())handler=middleware(handler,context2);identifyOnResolve&&console.log(stack2.identify());return handler}};return stack2};stepWeights={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1};priorityWeights={high:3,normal:2,low:1};Client=class{constructor(config){this.config=config;this.middlewareStack=constructStack()}send(command,optionsOrCb,cb2){const options="function"!=typeof optionsOrCb?optionsOrCb:void 0,callback="function"==typeof optionsOrCb?optionsOrCb:cb2;let handler;if(void 0===options&&!0===this.config.cacheMiddleware){this.handlers||(this.handlers=new WeakMap);const handlers2=this.handlers;if(handlers2.has(command.constructor))handler=handlers2.get(command.constructor);else{handler=command.resolveMiddleware(this.middlewareStack,this.config,options);handlers2.set(command.constructor,handler)}}else{delete this.handlers;handler=command.resolveMiddleware(this.middlewareStack,this.config,options)}if(!callback)return handler(command).then((result=>result.output));handler(command).then((result=>callback(null,result.output)),(err3=>callback(err3))).catch((()=>{}))}destroy(){var _a8,_b5,_c3;null==(_c3=null==(_b5=null==(_a8=this.config)?void 0:_a8.requestHandler)?void 0:_b5.destroy)||_c3.call(_b5);delete this.handlers}};Command=class{constructor(){this.middlewareStack=constructStack()}static classBuilder(){return new ClassBuilder}resolveMiddlewareWithContext(clientStack,configuration,options,{middlewareFn,clientName,commandName,inputFilterSensitiveLog,outputFilterSensitiveLog,smithyContext,additionalContext,CommandCtor}){for(const mw of middlewareFn.bind(this)(CommandCtor,clientStack,configuration,options))this.middlewareStack.use(mw);const stack2=clientStack.concat(this.middlewareStack),{logger:logger2}=configuration,handlerExecutionContext={logger:logger2,clientName,commandName,inputFilterSensitiveLog,outputFilterSensitiveLog,[SMITHY_CONTEXT_KEY]:{commandInstance:this,...smithyContext},...additionalContext},{requestHandler}=configuration;return stack2.resolve((request2=>requestHandler.handle(request2.request,options||{})),handlerExecutionContext)}};ClassBuilder=class{constructor(){this._init=()=>{};this._ep={};this._middlewareFn=()=>[];this._commandName="";this._clientName="";this._additionalContext={};this._smithyContext={};this._inputFilterSensitiveLog=_=>_;this._outputFilterSensitiveLog=_=>_;this._serializer=null;this._deserializer=null}init(cb2){this._init=cb2}ep(endpointParameterInstructions){this._ep=endpointParameterInstructions;return this}m(middlewareSupplier){this._middlewareFn=middlewareSupplier;return this}s(service,operation,smithyContext={}){this._smithyContext={service,operation,...smithyContext};return this}c(additionalContext={}){this._additionalContext=additionalContext;return this}n(clientName,commandName){this._clientName=clientName;this._commandName=commandName;return this}f(inputFilter=_=>_,outputFilter=_=>_){this._inputFilterSensitiveLog=inputFilter;this._outputFilterSensitiveLog=outputFilter;return this}ser(serializer){this._serializer=serializer;return this}de(deserializer){this._deserializer=deserializer;return this}build(){const closure=this;let CommandRef;return CommandRef=class extends Command{static getEndpointParameterInstructions(){return closure._ep}constructor(...[input]){super();this.serialize=closure._serializer;this.deserialize=closure._deserializer;this.input=null!=input?input:{};closure._init(this)}resolveMiddleware(stack2,configuration,options){return this.resolveMiddlewareWithContext(stack2,configuration,options,{CommandCtor:CommandRef,middlewareFn:closure._middlewareFn,clientName:closure._clientName,commandName:closure._commandName,inputFilterSensitiveLog:closure._inputFilterSensitiveLog,outputFilterSensitiveLog:closure._outputFilterSensitiveLog,smithyContext:closure._smithyContext,additionalContext:closure._additionalContext})}}}};SENSITIVE_STRING="***SensitiveInformation***";createAggregatedClient=(commands2,Client2)=>{for(const command of Object.keys(commands2)){const CommandCtor=commands2[command],methodImpl=async function(args,optionsOrCb,cb2){const command2=new CommandCtor(args);if("function"==typeof optionsOrCb)this.send(command2,optionsOrCb);else{if("function"!=typeof cb2)return this.send(command2,optionsOrCb);if("object"!=typeof optionsOrCb)throw new Error("Expected http options but got "+typeof optionsOrCb);this.send(command2,optionsOrCb||{},cb2)}},methodName=(command[0].toLowerCase()+command.slice(1)).replace(/Command$/,"");Client2.prototype[methodName]=methodImpl}};parseBoolean=value=>{switch(value){case"true":return!0;case"false":return!1;default:throw new Error(`Unable to parse boolean value "${value}"`)}};expectNumber=value=>{if(null!=value){if("string"==typeof value){const parsed=parseFloat(value);if(!Number.isNaN(parsed)){String(parsed)!==String(value)&&logger.warn(stackTraceWarning(`Expected number but observed string: ${value}`));return parsed}}if("number"==typeof value)return value;throw new TypeError(`Expected number, got ${typeof value}: ${value}`)}};MAX_FLOAT=Math.ceil(2**127*(2-2**-23));expectFloat32=value=>{const expected=expectNumber(value);if(void 0!==expected&&!Number.isNaN(expected)&&expected!==1/0&&expected!==-1/0&&Math.abs(expected)>MAX_FLOAT)throw new TypeError(`Expected 32-bit float, got ${value}`);return expected};expectLong=value=>{if(null!=value){if(Number.isInteger(value)&&!Number.isNaN(value))return value;throw new TypeError(`Expected integer, got ${typeof value}: ${value}`)}};expectInt32=value=>expectSizedInt(value,32);expectShort=value=>expectSizedInt(value,16);expectByte=value=>expectSizedInt(value,8);expectSizedInt=(value,size)=>{const expected=expectLong(value);if(void 0!==expected&&castInt(expected,size)!==expected)throw new TypeError(`Expected ${size}-bit integer, got ${value}`);return expected};castInt=(value,size)=>{switch(size){case 32:return Int32Array.of(value)[0];case 16:return Int16Array.of(value)[0];case 8:return Int8Array.of(value)[0]}};expectNonNull=(value,location)=>{if(null==value){if(location)throw new TypeError(`Expected a non-null value for ${location}`);throw new TypeError("Expected a non-null value")}return value};expectObject=value=>{if(null==value)return;if("object"==typeof value&&!Array.isArray(value))return value;const receivedType=Array.isArray(value)?"array":typeof value;throw new TypeError(`Expected object, got ${receivedType}: ${value}`)};expectString=value=>{if(null!=value){if("string"==typeof value)return value;if(["boolean","number","bigint"].includes(typeof value)){logger.warn(stackTraceWarning(`Expected string, got ${typeof value}: ${value}`));return String(value)}throw new TypeError(`Expected string, got ${typeof value}: ${value}`)}};expectUnion=value=>{if(null==value)return;const asObject=expectObject(value),setKeys=Object.entries(asObject).filter((([,v2])=>null!=v2)).map((([k2])=>k2));if(0===setKeys.length)throw new TypeError("Unions must have exactly one non-null member. None were found.");if(setKeys.length>1)throw new TypeError(`Unions must have exactly one non-null member. Keys ${setKeys} were not null.`);return asObject};strictParseFloat32=value=>expectFloat32("string"==typeof value?parseNumber(value):value);NUMBER_REGEX=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g;parseNumber=value=>{const matches=value.match(NUMBER_REGEX);if(null===matches||matches[0].length!==value.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(value)};strictParseLong=value=>expectLong("string"==typeof value?parseNumber(value):value);strictParseInt32=value=>expectInt32("string"==typeof value?parseNumber(value):value);strictParseShort=value=>expectShort("string"==typeof value?parseNumber(value):value);strictParseByte=value=>expectByte("string"==typeof value?parseNumber(value):value);stackTraceWarning=message=>String(new TypeError(message).stack||message).split("\n").slice(0,5).filter((s2=>!s2.includes("stackTraceWarning"))).join("\n");logger={warn:console.warn};DAYS=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];MONTHS=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?[zZ]$/);RFC3339_WITH_OFFSET=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);parseRfc3339DateTimeWithOffset=value=>{if(null==value)return;if("string"!=typeof value)throw new TypeError("RFC-3339 date-times must be expressed as strings");const match3=RFC3339_WITH_OFFSET.exec(value);if(!match3)throw new TypeError("Invalid RFC-3339 date-time value");const[_,yearStr,monthStr,dayStr,hours,minutes,seconds,fractionalMilliseconds,offsetStr]=match3,year=strictParseShort(stripLeadingZeroes(yearStr)),month=parseDateValue(monthStr,"month",1,12),day=parseDateValue(dayStr,"day",1,31),date=buildDate(year,month,day,{hours,minutes,seconds,fractionalMilliseconds});"Z"!=offsetStr.toUpperCase()&&date.setTime(date.getTime()-parseOffsetToMilliseconds(offsetStr));return date};IMF_FIXDATE=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);RFC_850_DATE=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/);ASC_TIME=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/);parseRfc7231DateTime=value=>{if(null==value)return;if("string"!=typeof value)throw new TypeError("RFC-7231 date-times must be expressed as strings");let match3=IMF_FIXDATE.exec(value);if(match3){const[_,dayStr,monthStr,yearStr,hours,minutes,seconds,fractionalMilliseconds]=match3;return buildDate(strictParseShort(stripLeadingZeroes(yearStr)),parseMonthByShortName(monthStr),parseDateValue(dayStr,"day",1,31),{hours,minutes,seconds,fractionalMilliseconds})}match3=RFC_850_DATE.exec(value);if(match3){const[_,dayStr,monthStr,yearStr,hours,minutes,seconds,fractionalMilliseconds]=match3;return adjustRfc850Year(buildDate(parseTwoDigitYear(yearStr),parseMonthByShortName(monthStr),parseDateValue(dayStr,"day",1,31),{hours,minutes,seconds,fractionalMilliseconds}))}match3=ASC_TIME.exec(value);if(match3){const[_,monthStr,dayStr,hours,minutes,seconds,fractionalMilliseconds,yearStr]=match3;return buildDate(strictParseShort(stripLeadingZeroes(yearStr)),parseMonthByShortName(monthStr),parseDateValue(dayStr.trimLeft(),"day",1,31),{hours,minutes,seconds,fractionalMilliseconds})}throw new TypeError("Invalid RFC-7231 date-time value")};buildDate=(year,month,day,time)=>{const adjustedMonth=month-1;validateDayOfMonth(year,adjustedMonth,day);return new Date(Date.UTC(year,adjustedMonth,day,parseDateValue(time.hours,"hour",0,23),parseDateValue(time.minutes,"minute",0,59),parseDateValue(time.seconds,"seconds",0,60),parseMilliseconds(time.fractionalMilliseconds)))};parseTwoDigitYear=value=>{const thisYear=(new Date).getUTCFullYear(),valueInThisCentury=100*Math.floor(thisYear/100)+strictParseShort(stripLeadingZeroes(value));return valueInThisCentury<thisYear?valueInThisCentury+100:valueInThisCentury};adjustRfc850Year=input=>input.getTime()-(new Date).getTime()>15768e8?new Date(Date.UTC(input.getUTCFullYear()-100,input.getUTCMonth(),input.getUTCDate(),input.getUTCHours(),input.getUTCMinutes(),input.getUTCSeconds(),input.getUTCMilliseconds())):input;parseMonthByShortName=value=>{const monthIdx=MONTHS.indexOf(value);if(monthIdx<0)throw new TypeError(`Invalid month: ${value}`);return monthIdx+1};DAYS_IN_MONTH=[31,28,31,30,31,30,31,31,30,31,30,31];validateDayOfMonth=(year,month,day)=>{let maxDays=DAYS_IN_MONTH[month];1===month&&isLeapYear(year)&&(maxDays=29);if(day>maxDays)throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year}: ${day}`)};isLeapYear=year=>year%4==0&&(year%100!=0||year%400==0);parseDateValue=(value,type,lower,upper)=>{const dateVal=strictParseByte(stripLeadingZeroes(value));if(dateVal<lower||dateVal>upper)throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`);return dateVal};parseMilliseconds=value=>null==value?0:1e3*strictParseFloat32("0."+value);parseOffsetToMilliseconds=value=>{const directionStr=value[0];let direction=1;if("+"==directionStr)direction=1;else{if("-"!=directionStr)throw new TypeError(`Offset direction, ${directionStr}, must be "+" or "-"`);direction=-1}return direction*(60*Number(value.substring(1,3))+Number(value.substring(4,6)))*60*1e3};stripLeadingZeroes=value=>{let idx2=0;for(;idx2<value.length-1&&"0"===value.charAt(idx2);)idx2++;return 0===idx2?value:value.slice(idx2)};ServiceException=class _ServiceException extends Error{constructor(options){super(options.message);Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype);this.name=options.name;this.$fault=options.$fault;this.$metadata=options.$metadata}static isInstance(value){if(!value)return!1;const candidate=value;return _ServiceException.prototype.isPrototypeOf(candidate)||Boolean(candidate.$fault)&&Boolean(candidate.$metadata)&&("client"===candidate.$fault||"server"===candidate.$fault)}static[Symbol.hasInstance](instance3){if(!instance3)return!1;const candidate=instance3;return this===_ServiceException?_ServiceException.isInstance(instance3):!!_ServiceException.isInstance(instance3)&&(candidate.name&&this.name?this.prototype.isPrototypeOf(instance3)||candidate.name===this.name:this.prototype.isPrototypeOf(instance3))}};decorateServiceException=(exception,additions={})=>{Object.entries(additions).filter((([,v2])=>void 0!==v2)).forEach((([k2,v2])=>{null!=exception[k2]&&""!==exception[k2]||(exception[k2]=v2)}));const message=exception.message||exception.Message||"UnknownError";exception.message=message;delete exception.Message;return exception};throwDefaultError=({output,parsedBody,exceptionCtor,errorCode})=>{const $metadata=deserializeMetadata(output),statusCode=$metadata.httpStatusCode?$metadata.httpStatusCode+"":void 0,response=new exceptionCtor({name:(null==parsedBody?void 0:parsedBody.code)||(null==parsedBody?void 0:parsedBody.Code)||errorCode||statusCode||"UnknownError",$fault:"client",$metadata});throw decorateServiceException(response,parsedBody)};withBaseException=ExceptionCtor=>({output,parsedBody,errorCode})=>{throwDefaultError({output,parsedBody,exceptionCtor:ExceptionCtor,errorCode})};deserializeMetadata=output=>{var _a8,_b5;return{httpStatusCode:output.statusCode,requestId:null!=(_b5=null!=(_a8=output.headers["x-amzn-requestid"])?_a8:output.headers["x-amzn-request-id"])?_b5:output.headers["x-amz-request-id"],extendedRequestId:output.headers["x-amz-id-2"],cfId:output.headers["x-amz-cf-id"]}};loadConfigsForDefaultMode=mode=>{switch(mode){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}};getChecksumConfiguration2=runtimeConfig=>{const checksumAlgorithms=[];for(const id in AlgorithmId){const algorithmId=AlgorithmId[id];void 0!==runtimeConfig[algorithmId]&&checksumAlgorithms.push({algorithmId:()=>algorithmId,checksumConstructor:()=>runtimeConfig[algorithmId]})}return{addChecksumAlgorithm(algo2){checksumAlgorithms.push(algo2)},checksumAlgorithms:()=>checksumAlgorithms}};resolveChecksumRuntimeConfig2=clientConfig=>{const runtimeConfig={};clientConfig.checksumAlgorithms().forEach((checksumAlgorithm=>{runtimeConfig[checksumAlgorithm.algorithmId()]=checksumAlgorithm.checksumConstructor()}));return runtimeConfig};getRetryConfiguration=runtimeConfig=>({setRetryStrategy(retryStrategy){runtimeConfig.retryStrategy=retryStrategy},retryStrategy:()=>runtimeConfig.retryStrategy});resolveRetryRuntimeConfig=retryStrategyConfiguration=>{const runtimeConfig={};runtimeConfig.retryStrategy=retryStrategyConfiguration.retryStrategy();return runtimeConfig};getDefaultExtensionConfiguration=runtimeConfig=>Object.assign(getChecksumConfiguration2(runtimeConfig),getRetryConfiguration(runtimeConfig));resolveDefaultRuntimeConfig2=config=>Object.assign(resolveChecksumRuntimeConfig2(config),resolveRetryRuntimeConfig(config));getArrayIfSingleItem=mayBeArray=>Array.isArray(mayBeArray)?mayBeArray:[mayBeArray];getValueFromTextNode=obj=>{for(const key3 in obj)obj.hasOwnProperty(key3)&&void 0!==obj[key3]["#text"]?obj[key3]=obj[key3]["#text"]:"object"==typeof obj[key3]&&null!==obj[key3]&&(obj[key3]=getValueFromTextNode(obj[key3]));return obj};isSerializableHeaderValue=value=>null!=value;(LazyJsonString=function LazyJsonString2(val2){return Object.assign(new String(val2),{deserializeJSON:()=>JSON.parse(String(val2)),toString:()=>String(val2),toJSON:()=>String(val2)})}).from=object=>object&&"object"==typeof object&&(object instanceof LazyJsonString||"deserializeJSON"in object)?object:"string"==typeof object||Object.getPrototypeOf(object)===String.prototype?LazyJsonString(String(object)):LazyJsonString(JSON.stringify(object));LazyJsonString.fromObject=LazyJsonString.from;NoOpLogger=class{trace(){}debug(){}info(){}warn(){}error(){}};mapWithFilter=(target,filter4,instructions)=>map2(target,Object.entries(instructions).reduce(((_instructions,[key3,value])=>{Array.isArray(value)?_instructions[key3]=value:_instructions[key3]="function"==typeof value?[filter4,value()]:[filter4,value];return _instructions}),{}));applyInstruction=(target,source2,instructions,targetKey)=>{if(null!==source2){let instruction=instructions[targetKey];"function"==typeof instruction&&(instruction=[,instruction]);const[filter5=nonNullish,valueFn=pass,sourceKey=targetKey]=instruction;("function"==typeof filter5&&filter5(source2[sourceKey])||"function"!=typeof filter5&&filter5)&&(target[targetKey]=valueFn(source2[sourceKey]));return}let[filter4,value]=instructions[targetKey];if("function"==typeof value){let _value;const defaultFilterPassed=void 0===filter4&&null!=(_value=value()),customFilterPassed="function"==typeof filter4&&!!filter4(void 0)||"function"!=typeof filter4&&!!filter4;defaultFilterPassed?target[targetKey]=_value:customFilterPassed&&(target[targetKey]=value())}else{const defaultFilterPassed=void 0===filter4&&null!=value,customFilterPassed="function"==typeof filter4&&!!filter4(value)||"function"!=typeof filter4&&!!filter4;(defaultFilterPassed||customFilterPassed)&&(target[targetKey]=value)}};nonNullish=_=>null!=_;pass=_=>_;serializeDateTime=date=>date.toISOString().replace(".000Z","Z");collectBodyString=(streamBody,context2)=>collectBody(streamBody,context2).then((body=>context2.utf8Encoder(body)));import_fast_xml_parser=__toESM(require_fxp());parseXmlBody=(streamBody,context2)=>collectBodyString(streamBody,context2).then((encoded=>{if(encoded.length){const parser2=new import_fast_xml_parser.XMLParser({attributeNamePrefix:"",htmlEntities:!0,ignoreAttributes:!1,ignoreDeclaration:!0,parseTagValue:!1,trimValues:!1,tagValueProcessor:(_,val2)=>""===val2.trim()&&val2.includes("\n")?"":void 0});parser2.addEntity("#xD","\r");parser2.addEntity("#10","\n");let parsedObj;try{parsedObj=parser2.parse(encoded,!0)}catch(e3){e3&&"object"==typeof e3&&Object.defineProperty(e3,"$responseBodyText",{value:encoded});throw e3}const textNodeName="#text",key3=Object.keys(parsedObj)[0],parsedObjToReturn=parsedObj[key3];if(parsedObjToReturn[textNodeName]){parsedObjToReturn[key3]=parsedObjToReturn[textNodeName];delete parsedObjToReturn[textNodeName]}return getValueFromTextNode(parsedObjToReturn)}return{}}));parseXmlErrorBody=async(errorBody,context2)=>{var _a8;const value=await parseXmlBody(errorBody,context2);value.Error&&(value.Error.message=null!=(_a8=value.Error.message)?_a8:value.Error.Message);return value};loadRestXmlErrorCode=(output,data)=>{var _a8;return void 0!==(null==(_a8=null==data?void 0:data.Error)?void 0:_a8.Code)?data.Error.Code:void 0!==(null==data?void 0:data.Code)?data.Code:404==output.statusCode?"NotFound":void 0};CLIENT_SUPPORTED_ALGORITHMS=[ChecksumAlgorithm.CRC32,ChecksumAlgorithm.CRC32C,ChecksumAlgorithm.CRC64NVME,ChecksumAlgorithm.SHA1,ChecksumAlgorithm.SHA256];PRIORITY_ORDER_ALGORITHMS=[ChecksumAlgorithm.SHA256,ChecksumAlgorithm.SHA1,ChecksumAlgorithm.CRC32,ChecksumAlgorithm.CRC32C,ChecksumAlgorithm.CRC64NVME];getChecksumAlgorithmForRequest=(input,{requestChecksumRequired,requestAlgorithmMember,requestChecksumCalculation})=>{if(!requestAlgorithmMember)return requestChecksumCalculation===RequestChecksumCalculation.WHEN_SUPPORTED||requestChecksumRequired?DEFAULT_CHECKSUM_ALGORITHM:void 0;if(!input[requestAlgorithmMember])return;const checksumAlgorithm=input[requestAlgorithmMember];if(!CLIENT_SUPPORTED_ALGORITHMS.includes(checksumAlgorithm))throw new Error(`The checksum algorithm "${checksumAlgorithm}" is not supported by the client. Select one of ${CLIENT_SUPPORTED_ALGORITHMS}.`);return checksumAlgorithm};getChecksumLocationName=algorithm=>algorithm===ChecksumAlgorithm.MD5?"content-md5":`x-amz-checksum-${algorithm.toLowerCase()}`;hasHeader2=(header,headers)=>{const soughtHeader=header.toLowerCase();for(const headerName of Object.keys(headers))if(soughtHeader===headerName.toLowerCase())return!0;return!1};hasHeaderWithPrefix=(headerPrefix,headers)=>{const soughtHeaderPrefix=headerPrefix.toLowerCase();for(const headerName of Object.keys(headers))if(headerName.toLowerCase().startsWith(soughtHeaderPrefix))return!0;return!1};isStreaming=body=>void 0!==body&&"string"!=typeof body&&!ArrayBuffer.isView(body)&&!isArrayBuffer(body);__assign=function(){__assign=Object.assign||function __assign2(t3){var s2,i2,n3,p4;for(i2=1,n3=arguments.length;i2<n3;i2++){s2=arguments[i2];for(p4 in s2)Object.prototype.hasOwnProperty.call(s2,p4)&&(t3[p4]=s2[p4])}return t3};return __assign.apply(this,arguments)};Object.create;Object.create;"function"==typeof SuppressedError&&SuppressedError;fromUtf82=input=>(new TextEncoder).encode(input);fromUtf83="undefined"!=typeof Buffer&&Buffer.from?function(input){return Buffer.from(input,"utf8")}:fromUtf82;AwsCrc32c=function(){function AwsCrc32c2(){this.crc32c=new Crc32c}AwsCrc32c2.prototype.update=function(toHash){isEmptyData(toHash)||this.crc32c.update(convertToBuffer(toHash))};AwsCrc32c2.prototype.digest=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(_a8){return[2,numToUint8(this.crc32c.digest())]}))}))};AwsCrc32c2.prototype.reset=function(){this.crc32c=new Crc32c};return AwsCrc32c2}();Crc32c=function(){function Crc32c2(){this.checksum=4294967295}Crc32c2.prototype.update=function(data){var e_1,_a8,data_1,data_1_1,byte;try{for(data_1_1=(data_1=__values(data)).next();!data_1_1.done;data_1_1=data_1.next()){byte=data_1_1.value;this.checksum=this.checksum>>>8^lookupTable[255&(this.checksum^byte)]}}catch(e_1_1){e_1={error:e_1_1}}finally{try{data_1_1&&!data_1_1.done&&(_a8=data_1.return)&&_a8.call(data_1)}finally{if(e_1)throw e_1.error}}return this};Crc32c2.prototype.digest=function(){return(4294967295^this.checksum)>>>0};return Crc32c2}();lookupTable=uint32ArrayFrom([0,4067132163,3778769143,324072436,3348797215,904991772,648144872,3570033899,2329499855,2024987596,1809983544,2575936315,1296289744,3207089363,2893594407,1578318884,274646895,3795141740,4049975192,51262619,3619967088,632279923,922689671,3298075524,2592579488,1760304291,2075979607,2312596564,1562183871,2943781820,3156637768,1313733451,549293790,3537243613,3246849577,871202090,3878099393,357341890,102525238,4101499445,2858735121,1477399826,1264559846,3107202533,1845379342,2677391885,2361733625,2125378298,820201905,3263744690,3520608582,598981189,4151959214,85089709,373468761,3827903834,3124367742,1213305469,1526817161,2842354314,2107672161,2412447074,2627466902,1861252501,1098587580,3004210879,2688576843,1378610760,2262928035,1955203488,1742404180,2511436119,3416409459,969524848,714683780,3639785095,205050476,4266873199,3976438427,526918040,1361435347,2739821008,2954799652,1114974503,2529119692,1691668175,2005155131,2247081528,3690758684,697762079,986182379,3366744552,476452099,3993867776,4250756596,255256311,1640403810,2477592673,2164122517,1922457750,2791048317,1412925310,1197962378,3037525897,3944729517,427051182,170179418,4165941337,746937522,3740196785,3451792453,1070968646,1905808397,2213795598,2426610938,1657317369,3053634322,1147748369,1463399397,2773627110,4215344322,153784257,444234805,3893493558,1021025245,3467647198,3722505002,797665321,2197175160,1889384571,1674398607,2443626636,1164749927,3070701412,2757221520,1446797203,137323447,4198817972,3910406976,461344835,3484808360,1037989803,781091935,3705997148,2460548119,1623424788,1939049696,2180517859,1429367560,2807687179,3020495871,1180866812,410100952,3927582683,4182430767,186734380,3756733383,763408580,1053836080,3434856499,2722870694,1344288421,1131464017,2971354706,1708204729,2545590714,2229949006,1988219213,680717673,3673779818,3383336350,1002577565,4010310262,493091189,238226049,4233660802,2987750089,1082061258,1395524158,2705686845,1972364758,2279892693,2494862625,1725896226,952904198,3399985413,3656866545,731699698,4283874585,222117402,510512622,3959836397,3280807620,837199303,582374963,3504198960,68661723,4135334616,3844915500,390545967,1230274059,3141532936,2825850620,1510247935,2395924756,2091215383,1878366691,2644384480,3553878443,565732008,854102364,3229815391,340358836,3861050807,4117890627,119113024,1493875044,2875275879,3090270611,1247431312,2660249211,1828433272,2141937292,2378227087,3811616794,291187481,34330861,4032846830,615137029,3603020806,3314634738,939183345,1776939221,2609017814,2295496738,2058945313,2926798794,1545135305,1330124605,3173225534,4084100981,17165430,307568514,3762199681,888469610,3332340585,3587147933,665062302,2042050490,2346497209,2559330125,1793573966,3190661285,1279665062,1595330642,2910671697]);AwsCrc32=function(){function AwsCrc322(){this.crc32=new Crc32}AwsCrc322.prototype.update=function(toHash){isEmptyData(toHash)||this.crc32.update(convertToBuffer(toHash))};AwsCrc322.prototype.digest=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(_a8){return[2,numToUint8(this.crc32.digest())]}))}))};AwsCrc322.prototype.reset=function(){this.crc32=new Crc32};return AwsCrc322}();Crc32=function(){function Crc322(){this.checksum=4294967295}Crc322.prototype.update=function(data){var e_1,_a8,data_1,data_1_1,byte;try{for(data_1_1=(data_1=__values(data)).next();!data_1_1.done;data_1_1=data_1.next()){byte=data_1_1.value;this.checksum=this.checksum>>>8^lookupTable2[255&(this.checksum^byte)]}}catch(e_1_1){e_1={error:e_1_1}}finally{try{data_1_1&&!data_1_1.done&&(_a8=data_1.return)&&_a8.call(data_1)}finally{if(e_1)throw e_1.error}}return this};Crc322.prototype.digest=function(){return(4294967295^this.checksum)>>>0};return Crc322}();lookupTable2=uint32ArrayFrom([0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117]);getCrc32ChecksumAlgorithmFunction=()=>AwsCrc32;selectChecksumAlgorithmFunction=(checksumAlgorithm,config)=>{switch(checksumAlgorithm){case ChecksumAlgorithm.MD5:return config.md5;case ChecksumAlgorithm.CRC32:return getCrc32ChecksumAlgorithmFunction();case ChecksumAlgorithm.CRC32C:return AwsCrc32c;case ChecksumAlgorithm.CRC64NVME:throw new Error('Please check whether you have installed the "@aws-sdk/crc64-nvme-crt" package explicitly. \nYou must also register the package by calling [require("@aws-sdk/crc64-nvme-crt");] or an ESM equivalent such as [import "@aws-sdk/crc64-nvme-crt";]. \nFor more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt');case ChecksumAlgorithm.SHA1:return config.sha1;case ChecksumAlgorithm.SHA256:return config.sha256;default:throw new Error(`Unsupported checksum algorithm: ${checksumAlgorithm}`)}};stringHasher=(checksumAlgorithmFn,body)=>{const hash3=new checksumAlgorithmFn;hash3.update(toUint8Array(body||""));return hash3.digest()};flexibleChecksumsMiddlewareOptions={name:"flexibleChecksumsMiddleware",step:"build",tags:["BODY_CHECKSUM"],override:!0};flexibleChecksumsMiddleware=(config,middlewareConfig)=>(next2,context2)=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);if(hasHeaderWithPrefix("x-amz-checksum-",args.request.headers))return next2(args);const{request:request2,input}=args,{body:requestBody,headers}=request2,{base64Encoder,streamHasher}=config,{requestChecksumRequired,requestAlgorithmMember}=middlewareConfig,requestChecksumCalculation=await config.requestChecksumCalculation(),requestAlgorithmMemberName=null==requestAlgorithmMember?void 0:requestAlgorithmMember.name,requestAlgorithmMemberHttpHeader=null==requestAlgorithmMember?void 0:requestAlgorithmMember.httpHeader;if(requestAlgorithmMemberName&&!input[requestAlgorithmMemberName]&&(requestChecksumCalculation===RequestChecksumCalculation.WHEN_SUPPORTED||requestChecksumRequired)){input[requestAlgorithmMemberName]=DEFAULT_CHECKSUM_ALGORITHM;requestAlgorithmMemberHttpHeader&&(headers[requestAlgorithmMemberHttpHeader]=DEFAULT_CHECKSUM_ALGORITHM)}const checksumAlgorithm=getChecksumAlgorithmForRequest(input,{requestChecksumRequired,requestAlgorithmMember:null==requestAlgorithmMember?void 0:requestAlgorithmMember.name,requestChecksumCalculation});let updatedBody=requestBody,updatedHeaders=headers;if(checksumAlgorithm){switch(checksumAlgorithm){case ChecksumAlgorithm.CRC32:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_CRC32","U");break;case ChecksumAlgorithm.CRC32C:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_CRC32C","V");break;case ChecksumAlgorithm.CRC64NVME:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_CRC64","W");break;case ChecksumAlgorithm.SHA1:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_SHA1","X");break;case ChecksumAlgorithm.SHA256:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_SHA256","Y");break}const checksumLocationName=getChecksumLocationName(checksumAlgorithm),checksumAlgorithmFn=selectChecksumAlgorithmFunction(checksumAlgorithm,config);if(isStreaming(requestBody)){const{getAwsChunkedEncodingStream:getAwsChunkedEncodingStream2,bodyLengthChecker}=config;updatedBody=getAwsChunkedEncodingStream2("number"==typeof config.requestStreamBufferSize&&config.requestStreamBufferSize>=8192?createBufferedReadable(requestBody,config.requestStreamBufferSize,context2.logger):requestBody,{base64Encoder,bodyLengthChecker,checksumLocationName,checksumAlgorithmFn,streamHasher});updatedHeaders={...headers,"content-encoding":headers["content-encoding"]?`${headers["content-encoding"]},aws-chunked`:"aws-chunked","transfer-encoding":"chunked","x-amz-decoded-content-length":headers["content-length"],"x-amz-content-sha256":"STREAMING-UNSIGNED-PAYLOAD-TRAILER","x-amz-trailer":checksumLocationName};delete updatedHeaders["content-length"]}else if(!hasHeader2(checksumLocationName,headers)){const rawChecksum=await stringHasher(checksumAlgorithmFn,requestBody);updatedHeaders={...headers,[checksumLocationName]:base64Encoder(rawChecksum)}}}return await next2({...args,request:{...request2,headers:updatedHeaders,body:updatedBody}})};flexibleChecksumsInputMiddlewareOptions={name:"flexibleChecksumsInputMiddleware",toMiddleware:"serializerMiddleware",relation:"before",tags:["BODY_CHECKSUM"],override:!0};flexibleChecksumsInputMiddleware=(config,middlewareConfig)=>(next2,context2)=>async args=>{const input=args.input,{requestValidationModeMember}=middlewareConfig,requestChecksumCalculation=await config.requestChecksumCalculation(),responseChecksumValidation=await config.responseChecksumValidation();switch(requestChecksumCalculation){case RequestChecksumCalculation.WHEN_REQUIRED:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED","a");break;case RequestChecksumCalculation.WHEN_SUPPORTED:setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED","Z");break}switch(responseChecksumValidation){case ResponseChecksumValidation.WHEN_REQUIRED:setFeature(context2,"FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED","c");break;case ResponseChecksumValidation.WHEN_SUPPORTED:setFeature(context2,"FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED","b");break}requestValidationModeMember&&!input[requestValidationModeMember]&&responseChecksumValidation===ResponseChecksumValidation.WHEN_SUPPORTED&&(input[requestValidationModeMember]="ENABLED");return next2(args)};getChecksumAlgorithmListForResponse=(responseAlgorithms=[])=>{const validChecksumAlgorithms=[];for(const algorithm of PRIORITY_ORDER_ALGORITHMS)responseAlgorithms.includes(algorithm)&&CLIENT_SUPPORTED_ALGORITHMS.includes(algorithm)&&validChecksumAlgorithms.push(algorithm);return validChecksumAlgorithms};isChecksumWithPartNumber=checksum=>{const lastHyphenIndex=checksum.lastIndexOf("-");if(-1!==lastHyphenIndex){const numberPart=checksum.slice(lastHyphenIndex+1);if(!numberPart.startsWith("0")){const number=parseInt(numberPart,10);if(!isNaN(number)&&number>=1&&number<=1e4)return!0}}return!1};getChecksum=async(body,{checksumAlgorithmFn,base64Encoder})=>base64Encoder(await stringHasher(checksumAlgorithmFn,body));validateChecksumFromResponse=async(response,{config,responseAlgorithms,logger:logger2})=>{const checksumAlgorithms=getChecksumAlgorithmListForResponse(responseAlgorithms),{body:responseBody,headers:responseHeaders}=response;for(const algorithm of checksumAlgorithms){const responseHeader=getChecksumLocationName(algorithm),checksumFromResponse=responseHeaders[responseHeader];if(checksumFromResponse){let checksumAlgorithmFn;try{checksumAlgorithmFn=selectChecksumAlgorithmFunction(algorithm,config)}catch(error){if(algorithm===ChecksumAlgorithm.CRC64NVME){null==logger2||logger2.warn(`Skipping ${ChecksumAlgorithm.CRC64NVME} checksum validation: ${error.message}`);continue}throw error}const{base64Encoder}=config;if(isStreaming(responseBody)){response.body=createChecksumStream({expectedChecksum:checksumFromResponse,checksumSourceLocation:responseHeader,checksum:new checksumAlgorithmFn,source:responseBody,base64Encoder});return}const checksum=await getChecksum(responseBody,{checksumAlgorithmFn,base64Encoder});if(checksum===checksumFromResponse)break;throw new Error(`Checksum mismatch: expected "${checksum}" but received "${checksumFromResponse}" in response header "${responseHeader}".`)}}};flexibleChecksumsResponseMiddlewareOptions={name:"flexibleChecksumsResponseMiddleware",toMiddleware:"deserializerMiddleware",relation:"after",tags:["BODY_CHECKSUM"],override:!0};flexibleChecksumsResponseMiddleware=(config,middlewareConfig)=>(next2,context2)=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);const input=args.input,result=await next2(args),response=result.response,{requestValidationModeMember,responseAlgorithms}=middlewareConfig;if(requestValidationModeMember&&"ENABLED"===input[requestValidationModeMember]){const{clientName,commandName}=context2;if("S3Client"===clientName&&"GetObjectCommand"===commandName&&getChecksumAlgorithmListForResponse(responseAlgorithms).every((algorithm=>{const responseHeader=getChecksumLocationName(algorithm),checksumFromResponse=response.headers[responseHeader];return!checksumFromResponse||isChecksumWithPartNumber(checksumFromResponse)})))return result;await validateChecksumFromResponse(response,{config,responseAlgorithms,logger:context2.logger})}return result};getFlexibleChecksumsPlugin=(config,middlewareConfig)=>({applyToStack:clientStack=>{clientStack.add(flexibleChecksumsMiddleware(config,middlewareConfig),flexibleChecksumsMiddlewareOptions);clientStack.addRelativeTo(flexibleChecksumsInputMiddleware(config,middlewareConfig),flexibleChecksumsInputMiddlewareOptions);clientStack.addRelativeTo(flexibleChecksumsResponseMiddleware(config,middlewareConfig),flexibleChecksumsResponseMiddlewareOptions)}});resolveFlexibleChecksumsConfig=input=>{const{requestChecksumCalculation,responseChecksumValidation,requestStreamBufferSize}=input;return Object.assign(input,{requestChecksumCalculation:normalizeProvider(null!=requestChecksumCalculation?requestChecksumCalculation:DEFAULT_REQUEST_CHECKSUM_CALCULATION),responseChecksumValidation:normalizeProvider(null!=responseChecksumValidation?responseChecksumValidation:DEFAULT_RESPONSE_CHECKSUM_VALIDATION),requestStreamBufferSize:Number(null!=requestStreamBufferSize?requestStreamBufferSize:0)})};hostHeaderMiddleware=options=>next2=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);const{request:request2}=args,{handlerProtocol=""}=options.requestHandler.metadata||{};if(handlerProtocol.indexOf("h2")>=0&&!request2.headers[":authority"]){delete request2.headers.host;request2.headers[":authority"]=request2.hostname+(request2.port?":"+request2.port:"")}else if(!request2.headers.host){let host=request2.hostname;null!=request2.port&&(host+=`:${request2.port}`);request2.headers.host=host}return next2(args)};hostHeaderMiddlewareOptions={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0};getHostHeaderPlugin=options=>({applyToStack:clientStack=>{clientStack.add(hostHeaderMiddleware(options),hostHeaderMiddlewareOptions)}});loggerMiddleware=()=>(next2,context2)=>async args=>{var _a8,_b5;try{const response=await next2(args),{clientName,commandName,logger:logger2,dynamoDbDocumentClientOptions={}}=context2,{overrideInputFilterSensitiveLog,overrideOutputFilterSensitiveLog}=dynamoDbDocumentClientOptions,inputFilterSensitiveLog=null!=overrideInputFilterSensitiveLog?overrideInputFilterSensitiveLog:context2.inputFilterSensitiveLog,outputFilterSensitiveLog=null!=overrideOutputFilterSensitiveLog?overrideOutputFilterSensitiveLog:context2.outputFilterSensitiveLog,{$metadata,...outputWithoutMetadata}=response.output;null==(_a8=null==logger2?void 0:logger2.info)||_a8.call(logger2,{clientName,commandName,input:inputFilterSensitiveLog(args.input),output:outputFilterSensitiveLog(outputWithoutMetadata),metadata:$metadata});return response}catch(error){const{clientName,commandName,logger:logger2,dynamoDbDocumentClientOptions={}}=context2,{overrideInputFilterSensitiveLog}=dynamoDbDocumentClientOptions,inputFilterSensitiveLog=null!=overrideInputFilterSensitiveLog?overrideInputFilterSensitiveLog:context2.inputFilterSensitiveLog;null==(_b5=null==logger2?void 0:logger2.error)||_b5.call(logger2,{clientName,commandName,input:inputFilterSensitiveLog(args.input),error,metadata:error.$metadata});throw error}};loggerMiddlewareOptions={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0};getLoggerPlugin=options=>({applyToStack:clientStack=>{clientStack.add(loggerMiddleware(),loggerMiddlewareOptions)}});recursionDetectionMiddleware=options=>next2=>async args=>{var _a8,_b5;const{request:request2}=args;if(!HttpRequest.isInstance(request2)||"node"!==options.runtime)return next2(args);const traceIdHeader=null!=(_b5=Object.keys(null!=(_a8=request2.headers)?_a8:{}).find((h3=>h3.toLowerCase()==="X-Amzn-Trace-Id".toLowerCase())))?_b5:"X-Amzn-Trace-Id";if(request2.headers.hasOwnProperty(traceIdHeader))return next2(args);const functionName=process.env.AWS_LAMBDA_FUNCTION_NAME,traceId=process.env._X_AMZN_TRACE_ID,nonEmptyString=str=>"string"==typeof str&&str.length>0;nonEmptyString(functionName)&&nonEmptyString(traceId)&&(request2.headers["X-Amzn-Trace-Id"]=traceId);return next2({...args,request:request2})};addRecursionDetectionMiddlewareOptions={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"};getRecursionDetectionPlugin=options=>({applyToStack:clientStack=>{clientStack.add(recursionDetectionMiddleware(options),addRecursionDetectionMiddlewareOptions)}});CONTENT_LENGTH_HEADER="content-length";DECODED_CONTENT_LENGTH_HEADER="x-amz-decoded-content-length";checkContentLengthHeaderMiddlewareOptions={step:"finalizeRequest",tags:["CHECK_CONTENT_LENGTH_HEADER"],name:"getCheckContentLengthHeaderPlugin",override:!0};getCheckContentLengthHeaderPlugin=unused=>({applyToStack:clientStack=>{clientStack.add(checkContentLengthHeader(),checkContentLengthHeaderMiddlewareOptions)}});regionRedirectEndpointMiddleware=config=>(next2,context2)=>async args=>{const originalRegion=await config.region(),regionProviderRef=config.region;let unlock=()=>{};if(context2.__s3RegionRedirect){Object.defineProperty(config,"region",{writable:!1,value:async()=>context2.__s3RegionRedirect});unlock=()=>Object.defineProperty(config,"region",{writable:!0,value:regionProviderRef})}try{const result=await next2(args);if(context2.__s3RegionRedirect){unlock();if(originalRegion!==await config.region())throw new Error("Region was not restored following S3 region redirect.")}return result}catch(e3){unlock();throw e3}};regionRedirectEndpointMiddlewareOptions={tags:["REGION_REDIRECT","S3"],name:"regionRedirectEndpointMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"};regionRedirectMiddlewareOptions={step:"initialize",tags:["REGION_REDIRECT","S3"],name:"regionRedirectMiddleware",override:!0};getRegionRedirectMiddlewarePlugin=clientConfig=>({applyToStack:clientStack=>{clientStack.add(regionRedirectMiddleware(clientConfig),regionRedirectMiddlewareOptions);clientStack.addRelativeTo(regionRedirectEndpointMiddleware(clientConfig),regionRedirectEndpointMiddlewareOptions)}});s3ExpiresMiddleware=config=>(next2,context2)=>async args=>{var _a8;const result=await next2(args),{response}=result;if(HttpResponse.isInstance(response)&&response.headers.expires){response.headers.expiresstring=response.headers.expires;try{parseRfc7231DateTime(response.headers.expires)}catch(e3){null==(_a8=context2.logger)||_a8.warn(`AWS SDK Warning for ${context2.clientName}::${context2.commandName} response parsing (${response.headers.expires}): ${e3}`);delete response.headers.expires}}return result};s3ExpiresMiddlewareOptions={tags:["S3"],name:"s3ExpiresMiddleware",override:!0,relation:"after",toMiddleware:"deserializerMiddleware"};getS3ExpiresMiddlewarePlugin=clientConfig=>({applyToStack:clientStack=>{clientStack.addRelativeTo(s3ExpiresMiddleware(),s3ExpiresMiddlewareOptions)}});_S3ExpressIdentityCache=class _S3ExpressIdentityCache{constructor(data={}){__publicField(this,"data");__publicField(this,"lastPurgeTime",Date.now());this.data=data}get(key3){const entry=this.data[key3];if(entry)return entry}set(key3,entry){this.data[key3]=entry;return entry}delete(key3){delete this.data[key3]}async purgeExpired(){const now3=Date.now();if(!(this.lastPurgeTime+_S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS>now3))for(const key3 in this.data){const entry=this.data[key3];if(!entry.isRefreshing){const credential=await entry.identity;credential.expiration&&credential.expiration.getTime()<now3&&delete this.data[key3]}}}};__publicField(_S3ExpressIdentityCache,"EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS",3e4);S3ExpressIdentityCache=_S3ExpressIdentityCache;S3ExpressIdentityCacheEntry=class{constructor(_identity,isRefreshing=!1,accessed=Date.now()){__publicField(this,"_identity");__publicField(this,"isRefreshing");__publicField(this,"accessed");this._identity=_identity;this.isRefreshing=isRefreshing;this.accessed=accessed}get identity(){this.accessed=Date.now();return this._identity}};_S3ExpressIdentityProviderImpl=class _S3ExpressIdentityProviderImpl{constructor(createSessionFn,cache2=new S3ExpressIdentityCache){__publicField(this,"createSessionFn");__publicField(this,"cache");this.createSessionFn=createSessionFn;this.cache=cache2}async getS3ExpressIdentity(awsIdentity,identityProperties){const key3=identityProperties.Bucket,{cache:cache2}=this,entry=cache2.get(key3);return entry?entry.identity.then((identity=>{var _a8,_b5,_c3,_d2;if((null!=(_b5=null==(_a8=identity.expiration)?void 0:_a8.getTime())?_b5:0)<Date.now())return cache2.set(key3,new S3ExpressIdentityCacheEntry(this.getIdentity(key3))).identity;if((null!=(_d2=null==(_c3=identity.expiration)?void 0:_c3.getTime())?_d2:0)<Date.now()+_S3ExpressIdentityProviderImpl.REFRESH_WINDOW_MS&&!entry.isRefreshing){entry.isRefreshing=!0;this.getIdentity(key3).then((id=>{cache2.set(key3,new S3ExpressIdentityCacheEntry(Promise.resolve(id)))}))}return identity})):cache2.set(key3,new S3ExpressIdentityCacheEntry(this.getIdentity(key3))).identity}async getIdentity(key3){var _a8,_b5;await this.cache.purgeExpired().catch((error=>{console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n"+error)}));const session=await this.createSessionFn(key3);if(!(null==(_a8=session.Credentials)?void 0:_a8.AccessKeyId)||!(null==(_b5=session.Credentials)?void 0:_b5.SecretAccessKey))throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey.");return{accessKeyId:session.Credentials.AccessKeyId,secretAccessKey:session.Credentials.SecretAccessKey,sessionToken:session.Credentials.SessionToken,expiration:session.Credentials.Expiration?new Date(session.Credentials.Expiration):void 0}}};__publicField(_S3ExpressIdentityProviderImpl,"REFRESH_WINDOW_MS",6e4);S3ExpressIdentityProviderImpl=_S3ExpressIdentityProviderImpl;(function(SelectorType3){SelectorType3.ENV="env";SelectorType3.CONFIG="shared config entry"})(SelectorType2||(SelectorType2={}));SESSION_TOKEN_HEADER=(SESSION_TOKEN_QUERY_PARAM="X-Amz-S3session-Token").toLowerCase();SignatureV4S3Express=class extends SignatureV4{async signWithCredentials(requestToSign,credentials,options){const credentialsWithoutSessionToken=getCredentialsWithoutSessionToken(credentials);requestToSign.headers[SESSION_TOKEN_HEADER]=credentials.sessionToken;setSingleOverride(this,credentialsWithoutSessionToken);return this.signRequest(requestToSign,null!=options?options:{})}async presignWithCredentials(requestToSign,credentials,options){var _a8;const credentialsWithoutSessionToken=getCredentialsWithoutSessionToken(credentials);delete requestToSign.headers[SESSION_TOKEN_HEADER];requestToSign.headers[SESSION_TOKEN_QUERY_PARAM]=credentials.sessionToken;requestToSign.query=null!=(_a8=requestToSign.query)?_a8:{};requestToSign.query[SESSION_TOKEN_QUERY_PARAM]=credentials.sessionToken;setSingleOverride(this,credentialsWithoutSessionToken);return this.presign(requestToSign,options)}};s3ExpressMiddleware=options=>(next2,context2)=>async args=>{var _a8,_b5,_c3,_d2,_e2;if(context2.endpointV2){const endpoint=context2.endpointV2,isS3ExpressAuth="sigv4-s3express"===(null==(_c3=null==(_b5=null==(_a8=endpoint.properties)?void 0:_a8.authSchemes)?void 0:_b5[0])?void 0:_c3.name);if("S3Express"===(null==(_d2=endpoint.properties)?void 0:_d2.backend)||"Directory"===(null==(_e2=endpoint.properties)?void 0:_e2.bucketType)){setFeature(context2,"S3_EXPRESS_BUCKET","J");context2.isS3ExpressBucket=!0}if(isS3ExpressAuth){const requestBucket=args.input.Bucket;if(requestBucket){const s3ExpressIdentity=await options.s3ExpressIdentityProvider.getS3ExpressIdentity(await options.credentials(),{Bucket:requestBucket});context2.s3ExpressIdentity=s3ExpressIdentity;HttpRequest.isInstance(args.request)&&s3ExpressIdentity.sessionToken&&(args.request.headers[SESSION_TOKEN_HEADER]=s3ExpressIdentity.sessionToken)}}}return next2(args)};s3ExpressMiddlewareOptions={name:"s3ExpressMiddleware",step:"build",tags:["S3","S3_EXPRESS"],override:!0};getS3ExpressPlugin=options=>({applyToStack:clientStack=>{clientStack.add(s3ExpressMiddleware(options),s3ExpressMiddlewareOptions)}});signS3Express=async(s3ExpressIdentity,signingOptions,request2,sigV4MultiRegionSigner)=>{const signedRequest=await sigV4MultiRegionSigner.signWithCredentials(request2,s3ExpressIdentity,{});if(signedRequest.headers["X-Amz-Security-Token"]||signedRequest.headers["x-amz-security-token"])throw new Error("X-Amz-Security-Token must not be set for s3-express requests.");return signedRequest};defaultErrorHandler2=signingProperties=>error=>{throw error};defaultSuccessHandler2=(httpResponse,signingProperties)=>{};s3ExpressHttpSigningMiddleware=config=>(next2,context2)=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);const scheme=getSmithyContext2(context2).selectedHttpAuthScheme;if(!scheme)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties={}},identity,signer}=scheme;let request2;request2=context2.s3ExpressIdentity?await signS3Express(context2.s3ExpressIdentity,0,args.request,await config.signer()):await signer.sign(args.request,identity,signingProperties);const output=await next2({...args,request:request2}).catch((signer.errorHandler||defaultErrorHandler2)(signingProperties));(signer.successHandler||defaultSuccessHandler2)(output.response,signingProperties);return output};getS3ExpressHttpSigningPlugin=config=>({applyToStack:clientStack=>{clientStack.addRelativeTo(s3ExpressHttpSigningMiddleware(config),httpSigningMiddlewareOptions)}});resolveS3Config=(input,{session})=>{const[s3ClientProvider,CreateSessionCommandCtor]=session,{forcePathStyle,useAccelerateEndpoint,disableMultiregionAccessPoints,followRegionRedirects,s3ExpressIdentityProvider,bucketEndpoint}=input;return Object.assign(input,{forcePathStyle:null!=forcePathStyle&&forcePathStyle,useAccelerateEndpoint:null!=useAccelerateEndpoint&&useAccelerateEndpoint,disableMultiregionAccessPoints:null!=disableMultiregionAccessPoints&&disableMultiregionAccessPoints,followRegionRedirects:null!=followRegionRedirects&&followRegionRedirects,s3ExpressIdentityProvider:null!=s3ExpressIdentityProvider?s3ExpressIdentityProvider:new S3ExpressIdentityProviderImpl((async key3=>s3ClientProvider().send(new CreateSessionCommandCtor({Bucket:key3})))),bucketEndpoint:null!=bucketEndpoint&&bucketEndpoint})};THROW_IF_EMPTY_BODY={CopyObjectCommand:!0,UploadPartCopyCommand:!0,CompleteMultipartUploadCommand:!0};throw200ExceptionsMiddleware=config=>(next2,context2)=>async args=>{const result=await next2(args),{response}=result;if(!HttpResponse.isInstance(response))return result;const{statusCode,body:sourceBody}=response;if(statusCode<200||statusCode>=300)return result;if("function"!=typeof(null==sourceBody?void 0:sourceBody.stream)&&"function"!=typeof(null==sourceBody?void 0:sourceBody.pipe)&&"function"!=typeof(null==sourceBody?void 0:sourceBody.tee))return result;let bodyCopy=sourceBody,body=sourceBody;!sourceBody||"object"!=typeof sourceBody||sourceBody instanceof Uint8Array||([bodyCopy,body]=await splitStream(sourceBody));response.body=body;const bodyBytes=await collectBody2(bodyCopy,{streamCollector:async stream=>headStream(stream,3e3)});"function"==typeof(null==bodyCopy?void 0:bodyCopy.destroy)&&bodyCopy.destroy();const bodyStringTail=config.utf8Encoder(bodyBytes.subarray(bodyBytes.length-16));if(0===bodyBytes.length&&THROW_IF_EMPTY_BODY[context2.commandName]){const err3=new Error("S3 aborted request");err3.name="InternalError";throw err3}bodyStringTail&&bodyStringTail.endsWith("</Error>")&&(response.statusCode=400);return result};collectBody2=(streamBody=new Uint8Array,context2)=>streamBody instanceof Uint8Array?Promise.resolve(streamBody):context2.streamCollector(streamBody)||Promise.resolve(new Uint8Array);throw200ExceptionsMiddlewareOptions={relation:"after",toMiddleware:"deserializerMiddleware",tags:["THROW_200_EXCEPTIONS","S3"],name:"throw200ExceptionsMiddleware",override:!0};getThrow200ExceptionsPlugin=config=>({applyToStack:clientStack=>{clientStack.addRelativeTo(throw200ExceptionsMiddleware(config),throw200ExceptionsMiddlewareOptions)}});validate=str=>"string"==typeof str&&0===str.indexOf("arn:")&&str.split(":").length>=6;bucketEndpointMiddlewareOptions={name:"bucketEndpointMiddleware",override:!0,relation:"after",toMiddleware:"endpointV2Middleware"};validateBucketNameMiddlewareOptions={step:"initialize",tags:["VALIDATE_BUCKET_NAME"],name:"validateBucketNameMiddleware",override:!0};getValidateBucketNamePlugin=options=>({applyToStack:clientStack=>{clientStack.add(validateBucketNameMiddleware(options),validateBucketNameMiddlewareOptions);clientStack.addRelativeTo(bucketEndpointMiddleware(options),bucketEndpointMiddlewareOptions)}});DEFAULT_UA_APP_ID=void 0;EndpointCache=class{constructor({size,params}){this.data=new Map;this.parameters=[];this.capacity=null!=size?size:50;params&&(this.parameters=params)}get(endpointParams,resolver2){const key3=this.hash(endpointParams);if(!1===key3)return resolver2();if(!this.data.has(key3)){if(this.data.size>this.capacity+10){const keys3=this.data.keys();let i2=0;for(;;){const{value,done}=keys3.next();this.data.delete(value);if(done||++i2>10)break}}this.data.set(key3,resolver2())}return this.data.get(key3)}size(){return this.data.size}hash(endpointParams){var _a8;let buffer="";const{parameters}=this;if(0===parameters.length)return!1;for(const param of parameters){const val2=String(null!=(_a8=endpointParams[param])?_a8:"");if(val2.includes("|;"))return!1;buffer+=val2+"|;"}return buffer}};IP_V4_REGEX=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$");isIpAddress=value=>IP_V4_REGEX.test(value)||value.startsWith("[")&&value.endsWith("]");VALID_HOST_LABEL_REGEX=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$");isValidHostLabel=(value,allowSubDomains=!1)=>{if(!allowSubDomains)return VALID_HOST_LABEL_REGEX.test(value);const labels=value.split(".");for(const label2 of labels)if(!isValidHostLabel(label2))return!1;return!0};customEndpointFunctions={};EndpointError=class extends Error{constructor(message){super(message);this.name="EndpointError"}};booleanEquals=(value1,value2)=>value1===value2;getAttrPathList=path2=>{const parts=path2.split("."),pathList=[];for(const part of parts){const squareBracketIndex=part.indexOf("[");if(-1!==squareBracketIndex){if(part.indexOf("]")!==part.length-1)throw new EndpointError(`Path: '${path2}' does not end with ']'`);const arrayIndex=part.slice(squareBracketIndex+1,-1);if(Number.isNaN(parseInt(arrayIndex)))throw new EndpointError(`Invalid array index: '${arrayIndex}' in path: '${path2}'`);0!==squareBracketIndex&&pathList.push(part.slice(0,squareBracketIndex));pathList.push(arrayIndex)}else pathList.push(part)}return pathList};getAttr=(value,path2)=>getAttrPathList(path2).reduce(((acc,index6)=>{if("object"!=typeof acc)throw new EndpointError(`Index '${index6}' in '${path2}' not found in '${JSON.stringify(value)}'`);return Array.isArray(acc)?acc[parseInt(index6)]:acc[index6]}),value);isSet=value=>null!=value;not=value=>!value;DEFAULT_PORTS={[EndpointURLScheme.HTTP]:80,[EndpointURLScheme.HTTPS]:443};endpointFunctions={booleanEquals,getAttr,isSet,isValidHostLabel,not,parseURL:value=>{const whatwgURL=(()=>{try{if(value instanceof URL)return value;if("object"==typeof value&&"hostname"in value){const{hostname:hostname2,port,protocol:protocol2="",path:path2="",query:query3={}}=value,url=new URL(`${protocol2}//${hostname2}${port?`:${port}`:""}${path2}`);url.search=Object.entries(query3).map((([k2,v2])=>`${k2}=${v2}`)).join("&");return url}return new URL(value)}catch(error){return null}})();if(!whatwgURL){console.error(`Unable to parse ${JSON.stringify(value)} as a whatwg URL.`);return null}const urlString=whatwgURL.href,{host,hostname,pathname,protocol,search}=whatwgURL;if(search)return null;const scheme=protocol.slice(0,-1);if(!Object.values(EndpointURLScheme).includes(scheme))return null;const isIp=isIpAddress(hostname);return{scheme,authority:`${host}${urlString.includes(`${host}:${DEFAULT_PORTS[scheme]}`)||"string"==typeof value&&value.includes(`${host}:${DEFAULT_PORTS[scheme]}`)?`:${DEFAULT_PORTS[scheme]}`:""}`,path:pathname,normalizedPath:pathname.endsWith("/")?pathname:`${pathname}/`,isIp}},stringEquals:(value1,value2)=>value1===value2,substring:(input,start,stop,reverse)=>start>=stop||input.length<stop?null:reverse?input.substring(input.length-stop,input.length-start):input.substring(start,stop),uriEncode:value=>encodeURIComponent(value).replace(/[!*'()]/g,(c3=>`%${c3.charCodeAt(0).toString(16).toUpperCase()}`))};evaluateTemplate=(template,options)=>{const evaluatedTemplateArr=[],templateContext={...options.endpointParams,...options.referenceRecord};let currentIndex=0;for(;currentIndex<template.length;){const openingBraceIndex=template.indexOf("{",currentIndex);if(-1===openingBraceIndex){evaluatedTemplateArr.push(template.slice(currentIndex));break}evaluatedTemplateArr.push(template.slice(currentIndex,openingBraceIndex));const closingBraceIndex=template.indexOf("}",openingBraceIndex);if(-1===closingBraceIndex){evaluatedTemplateArr.push(template.slice(openingBraceIndex));break}if("{"===template[openingBraceIndex+1]&&"}"===template[closingBraceIndex+1]){evaluatedTemplateArr.push(template.slice(openingBraceIndex+1,closingBraceIndex));currentIndex=closingBraceIndex+2}const parameterName=template.substring(openingBraceIndex+1,closingBraceIndex);if(parameterName.includes("#")){const[refName,attrName]=parameterName.split("#");evaluatedTemplateArr.push(getAttr(templateContext[refName],attrName))}else evaluatedTemplateArr.push(templateContext[parameterName]);currentIndex=closingBraceIndex+1}return evaluatedTemplateArr.join("")};getReferenceValue=({ref},options)=>({...options.endpointParams,...options.referenceRecord}[ref]);evaluateExpression=(obj,keyName,options)=>{if("string"==typeof obj)return evaluateTemplate(obj,options);if(obj.fn)return callFunction(obj,options);if(obj.ref)return getReferenceValue(obj,options);throw new EndpointError(`'${keyName}': ${String(obj)} is not a string, function or reference.`)};callFunction=({fn,argv},options)=>{const evaluatedArgs=argv.map((arg=>["boolean","number"].includes(typeof arg)?arg:evaluateExpression(arg,"arg",options))),fnSegments=fn.split(".");return fnSegments[0]in customEndpointFunctions&&null!=fnSegments[1]?customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs):endpointFunctions[fn](...evaluatedArgs)};evaluateCondition=({assign:assign2,...fnArgs},options)=>{var _a8,_b5;if(assign2&&assign2 in options.referenceRecord)throw new EndpointError(`'${assign2}' is already defined in Reference Record.`);const value=callFunction(fnArgs,options);null==(_b5=null==(_a8=options.logger)?void 0:_a8.debug)||_b5.call(_a8,`endpoints evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);return{result:""===value||!!value,...null!=assign2&&{toAssign:{name:assign2,value}}}};evaluateConditions=(conditions=[],options)=>{var _a8,_b5;const conditionsReferenceRecord={};for(const condition of conditions){const{result,toAssign}=evaluateCondition(condition,{...options,referenceRecord:{...options.referenceRecord,...conditionsReferenceRecord}});if(!result)return{result};if(toAssign){conditionsReferenceRecord[toAssign.name]=toAssign.value;null==(_b5=null==(_a8=options.logger)?void 0:_a8.debug)||_b5.call(_a8,`endpoints assign: ${toAssign.name} := ${toDebugString(toAssign.value)}`)}}return{result:!0,referenceRecord:conditionsReferenceRecord}};getEndpointHeaders=(headers,options)=>Object.entries(headers).reduce(((acc,[headerKey,headerVal])=>({...acc,[headerKey]:headerVal.map((headerValEntry=>{const processedExpr=evaluateExpression(headerValEntry,"Header value entry",options);if("string"!=typeof processedExpr)throw new EndpointError(`Header '${headerKey}' value '${processedExpr}' is not a string`);return processedExpr}))})),{});getEndpointProperty=(property,options)=>{if(Array.isArray(property))return property.map((propertyEntry=>getEndpointProperty(propertyEntry,options)));switch(typeof property){case"string":return evaluateTemplate(property,options);case"object":if(null===property)throw new EndpointError(`Unexpected endpoint property: ${property}`);return getEndpointProperties(property,options);case"boolean":return property;default:throw new EndpointError("Unexpected endpoint property type: "+typeof property)}};getEndpointProperties=(properties,options)=>Object.entries(properties).reduce(((acc,[propertyKey,propertyVal])=>({...acc,[propertyKey]:getEndpointProperty(propertyVal,options)})),{});getEndpointUrl=(endpointUrl,options)=>{const expression=evaluateExpression(endpointUrl,"Endpoint URL",options);if("string"==typeof expression)try{return new URL(expression)}catch(error){console.error(`Failed to construct URL with ${expression}`,error);throw error}throw new EndpointError("Endpoint URL must be a string, got "+typeof expression)};evaluateEndpointRule=(endpointRule,options)=>{var _a8,_b5;const{conditions,endpoint}=endpointRule,{result,referenceRecord}=evaluateConditions(conditions,options);if(!result)return;const endpointRuleOptions={...options,referenceRecord:{...options.referenceRecord,...referenceRecord}},{url,properties,headers}=endpoint;null==(_b5=null==(_a8=options.logger)?void 0:_a8.debug)||_b5.call(_a8,`endpoints Resolving endpoint from template: ${toDebugString(endpoint)}`);return{...null!=headers&&{headers:getEndpointHeaders(headers,endpointRuleOptions)},...null!=properties&&{properties:getEndpointProperties(properties,endpointRuleOptions)},url:getEndpointUrl(url,endpointRuleOptions)}};evaluateErrorRule=(errorRule,options)=>{const{conditions,error}=errorRule,{result,referenceRecord}=evaluateConditions(conditions,options);if(result)throw new EndpointError(evaluateExpression(error,"Error",{...options,referenceRecord:{...options.referenceRecord,...referenceRecord}}))};evaluateTreeRule=(treeRule,options)=>{const{conditions,rules}=treeRule,{result,referenceRecord}=evaluateConditions(conditions,options);if(result)return evaluateRules(rules,{...options,referenceRecord:{...options.referenceRecord,...referenceRecord}})};evaluateRules=(rules,options)=>{for(const rule of rules)if("endpoint"===rule.type){const endpointOrUndefined=evaluateEndpointRule(rule,options);if(endpointOrUndefined)return endpointOrUndefined}else if("error"===rule.type)evaluateErrorRule(rule,options);else{if("tree"!==rule.type)throw new EndpointError(`Unknown endpoint rule: ${rule}`);{const endpointOrUndefined=evaluateTreeRule(rule,options);if(endpointOrUndefined)return endpointOrUndefined}}throw new EndpointError("Rules evaluation failed")};resolveEndpoint=(ruleSetObject,options)=>{var _a8,_b5,_c3,_d2,_e2;const{endpointParams,logger:logger2}=options,{parameters,rules}=ruleSetObject;null==(_b5=null==(_a8=options.logger)?void 0:_a8.debug)||_b5.call(_a8,`endpoints Initial EndpointParams: ${toDebugString(endpointParams)}`);const paramsWithDefault=Object.entries(parameters).filter((([,v2])=>null!=v2.default)).map((([k2,v2])=>[k2,v2.default]));if(paramsWithDefault.length>0)for(const[paramKey,paramDefaultValue]of paramsWithDefault)endpointParams[paramKey]=null!=(_c3=endpointParams[paramKey])?_c3:paramDefaultValue;const requiredParams=Object.entries(parameters).filter((([,v2])=>v2.required)).map((([k2])=>k2));for(const requiredParam of requiredParams)if(null==endpointParams[requiredParam])throw new EndpointError(`Missing required parameter: '${requiredParam}'`);const endpoint=evaluateRules(rules,{endpointParams,logger:logger2,referenceRecord:{}});null==(_e2=null==(_d2=options.logger)?void 0:_d2.debug)||_e2.call(_d2,`endpoints Resolved endpoint: ${toDebugString(endpoint)}`);return endpoint};selectedPartitionsInfo={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"AWS Standard global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"AWS China global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"AWS GovCloud (US) global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"c2s.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"AWS ISO (US) global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"sc2s.sgov.gov",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"AWS ISOB (US) global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"cloud.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"AWS ISOE (Europe) global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"csp.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"AWS ISOF global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"amazonaws.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!1,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"EU (Germany)"}}}],version:"1.1"};getUserAgentPrefix=()=>"";awsEndpointFunctions={isVirtualHostableS3Bucket:isVirtualHostableS3Bucket=(value,allowSubDomains=!1)=>{if(allowSubDomains){for(const label2 of value.split("."))if(!isVirtualHostableS3Bucket(label2))return!1;return!0}return!(!isValidHostLabel(value)||value.length<3||value.length>63||value!==value.toLowerCase()||isIpAddress(value))},parseArn:value=>{const segments=value.split(":");if(segments.length<6)return null;const[arn,partition2,service,region,accountId,...resourcePath]=segments;return"arn"!==arn||""===partition2||""===service||""===resourcePath.join(":")?null:{partition:partition2,service,region,accountId,resourceId:resourcePath.map((resource=>resource.split("/"))).flat()}},partition:value=>{const{partitions}=selectedPartitionsInfo;for(const partition2 of partitions){const{regions,outputs}=partition2;for(const[region,regionData]of Object.entries(regions))if(region===value)return{...outputs,...regionData}}for(const partition2 of partitions){const{regionRegex,outputs}=partition2;if(new RegExp(regionRegex).test(value))return{...outputs}}const DEFAULT_PARTITION=partitions.find((partition2=>"aws"===partition2.id));if(!DEFAULT_PARTITION)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...DEFAULT_PARTITION.outputs}}};customEndpointFunctions.aws=awsEndpointFunctions;ACCOUNT_ID_ENDPOINT_REGEX=/\d{12}\.ddb/;UA_NAME_ESCAPE_REGEX=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w]/g;UA_VALUE_ESCAPE_REGEX=/[^\!\$\%\&\'\*\+\-\.\^\_\`\|\~\d\w\#]/g;BYTE_LIMIT=1024;userAgentMiddleware=options=>(next2,context2)=>async args=>{var _a8,_b5,_c3,_d2;const{request:request2}=args;if(!HttpRequest.isInstance(request2))return next2(args);const{headers}=request2,userAgent=(null==(_a8=null==context2?void 0:context2.userAgent)?void 0:_a8.map(escapeUserAgent))||[],defaultUserAgent2=(await options.defaultUserAgentProvider()).map(escapeUserAgent);await checkFeatures(context2,options,args);const awsContext=context2;defaultUserAgent2.push(`m/${encodeFeatures(Object.assign({},null==(_b5=context2.__smithy_context)?void 0:_b5.features,null==(_c3=awsContext.__aws_sdk_context)?void 0:_c3.features))}`);const customUserAgent=(null==(_d2=null==options?void 0:options.customUserAgent)?void 0:_d2.map(escapeUserAgent))||[],appId=await options.userAgentAppId();appId&&defaultUserAgent2.push(escapeUserAgent([`app/${appId}`]));const prefix=getUserAgentPrefix(),sdkUserAgentValue=(prefix?[prefix]:[]).concat([...defaultUserAgent2,...userAgent,...customUserAgent]).join(" "),normalUAValue=[...defaultUserAgent2.filter((section=>section.startsWith("aws-sdk-"))),...customUserAgent].join(" ");if("browser"!==options.runtime){normalUAValue&&(headers["x-amz-user-agent"]=headers["x-amz-user-agent"]?`${headers["user-agent"]} ${normalUAValue}`:normalUAValue);headers["user-agent"]=sdkUserAgentValue}else headers["x-amz-user-agent"]=sdkUserAgentValue;return next2({...args,request:request2})};escapeUserAgent=userAgentPair=>{var _a8;const name=userAgentPair[0].split("/").map((part=>part.replace(UA_NAME_ESCAPE_REGEX,"-"))).join("/"),version2=null==(_a8=userAgentPair[1])?void 0:_a8.replace(UA_VALUE_ESCAPE_REGEX,"-"),prefixSeparatorIndex=name.indexOf("/"),prefix=name.substring(0,prefixSeparatorIndex);let uaName=name.substring(prefixSeparatorIndex+1);"api"===prefix&&(uaName=uaName.toLowerCase());return[prefix,uaName,version2].filter((item=>item&&item.length>0)).reduce(((acc,item,index6)=>{switch(index6){case 0:return item;case 1:return`${acc}/${item}`;default:return`${acc}#${item}`}}),"")};getUserAgentMiddlewareOptions={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0};getUserAgentPlugin=config=>({applyToStack:clientStack=>{clientStack.add(userAgentMiddleware(config),getUserAgentMiddlewareOptions)}});isFipsRegion=region=>"string"==typeof region&&(region.startsWith("fips-")||region.endsWith("-fips"));getRealRegion=region=>isFipsRegion(region)?["fips-aws-global","aws-fips"].includes(region)?"us-east-1":region.replace(/fips-(dkr-|prod-)?|-fips/,""):region;resolveRegionConfig=input=>{const{region,useFipsEndpoint}=input;if(!region)throw new Error("Region is missing");return Object.assign(input,{region:async()=>{if("string"==typeof region)return getRealRegion(region);const providedRegion=await region();return getRealRegion(providedRegion)},useFipsEndpoint:async()=>{const providedRegion="string"==typeof region?region:await region();return!!isFipsRegion(providedRegion)||("function"!=typeof useFipsEndpoint?Promise.resolve(!!useFipsEndpoint):useFipsEndpoint())}})};resolveEventStreamSerdeConfig=input=>Object.assign(input,{eventStreamMarshaller:input.eventStreamSerdeProvider(input)});CONTENT_LENGTH_HEADER2="content-length";contentLengthMiddlewareOptions={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0};getContentLengthPlugin=options=>({applyToStack:clientStack=>{clientStack.add(contentLengthMiddleware(options.bodyLengthChecker),contentLengthMiddlewareOptions)}});resolveParamsForS3=async endpointParams=>{const bucket=(null==endpointParams?void 0:endpointParams.Bucket)||"";"string"==typeof endpointParams.Bucket&&(endpointParams.Bucket=bucket.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?")));if(isArnBucketName(bucket)){if(!0===endpointParams.ForcePathStyle)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!isDnsCompatibleBucketName(bucket)||-1!==bucket.indexOf(".")&&!String(endpointParams.Endpoint).startsWith("http:")||bucket.toLowerCase()!==bucket||bucket.length<3)&&(endpointParams.ForcePathStyle=!0);if(endpointParams.DisableMultiRegionAccessPoints){endpointParams.disableMultiRegionAccessPoints=!0;endpointParams.DisableMRAP=!0}return endpointParams};DOMAIN_PATTERN=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/;IP_ADDRESS_PATTERN=/(\d+\.){3}\d+/;DOTS_PATTERN=/\.\./;isDnsCompatibleBucketName=bucketName=>DOMAIN_PATTERN.test(bucketName)&&!IP_ADDRESS_PATTERN.test(bucketName)&&!DOTS_PATTERN.test(bucketName);isArnBucketName=bucketName=>{const[arn,partition2,service,,,bucket]=bucketName.split(":"),isArn="arn"===arn&&bucketName.split(":").length>=6,isValidArn=Boolean(isArn&&partition2&&service&&bucket);if(isArn&&!isValidArn)throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);return isValidArn};createConfigValueProvider=(configKey,canonicalEndpointParamKey,config)=>{const configProvider=async()=>{var _a8;const configValue=null!=(_a8=config[configKey])?_a8:config[canonicalEndpointParamKey];return"function"==typeof configValue?configValue():configValue};return"credentialScope"===configKey||"CredentialScope"===canonicalEndpointParamKey?async()=>{var _a8;const credentials="function"==typeof config.credentials?await config.credentials():config.credentials;return null!=(_a8=null==credentials?void 0:credentials.credentialScope)?_a8:null==credentials?void 0:credentials.CredentialScope}:"accountId"===configKey||"AccountId"===canonicalEndpointParamKey?async()=>{var _a8;const credentials="function"==typeof config.credentials?await config.credentials():config.credentials;return null!=(_a8=null==credentials?void 0:credentials.accountId)?_a8:null==credentials?void 0:credentials.AccountId}:"endpoint"===configKey||"endpoint"===canonicalEndpointParamKey?async()=>{const endpoint=await configProvider();if(endpoint&&"object"==typeof endpoint){if("url"in endpoint)return endpoint.url.href;if("hostname"in endpoint){const{protocol,hostname,port,path:path2}=endpoint;return`${protocol}//${hostname}${port?":"+port:""}${path2}`}}return endpoint}:configProvider};getEndpointFromConfig=async serviceId=>{};parseUrl=url=>{if("string"==typeof url)return parseUrl(new URL(url));const{hostname,pathname,port,protocol,search}=url;let query3;search&&(query3=parseQueryString(search));return{hostname,port:port?parseInt(port):void 0,protocol,path:pathname,query:query3}};toEndpointV1=endpoint=>"object"==typeof endpoint?"url"in endpoint?parseUrl(endpoint.url):endpoint:parseUrl(endpoint);getEndpointFromInstructions=async(commandInput,instructionsSupplier,clientConfig,context2)=>{if(!clientConfig.endpoint){let endpointFromConfig;endpointFromConfig=clientConfig.serviceConfiguredEndpoint?await clientConfig.serviceConfiguredEndpoint():await getEndpointFromConfig(clientConfig.serviceId);endpointFromConfig&&(clientConfig.endpoint=()=>Promise.resolve(toEndpointV1(endpointFromConfig)))}const endpointParams=await resolveParams(commandInput,instructionsSupplier,clientConfig);if("function"!=typeof clientConfig.endpointProvider)throw new Error("config.endpointProvider is not set.");return clientConfig.endpointProvider(endpointParams,context2)};resolveParams=async(commandInput,instructionsSupplier,clientConfig)=>{var _a8;const endpointParams={},instructions=(null==(_a8=null==instructionsSupplier?void 0:instructionsSupplier.getEndpointParameterInstructions)?void 0:_a8.call(instructionsSupplier))||{};for(const[name,instruction]of Object.entries(instructions))switch(instruction.type){case"staticContextParams":endpointParams[name]=instruction.value;break;case"contextParams":endpointParams[name]=commandInput[instruction.name];break;case"clientContextParams":case"builtInParams":endpointParams[name]=await createConfigValueProvider(instruction.name,name,clientConfig)();break;case"operationContextParams":endpointParams[name]=instruction.get(commandInput);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(instruction))}0===Object.keys(instructions).length&&Object.assign(endpointParams,clientConfig);"s3"===String(clientConfig.serviceId).toLowerCase()&&await resolveParamsForS3(endpointParams);return endpointParams};endpointMiddleware=({config,instructions})=>(next2,context2)=>async args=>{var _a8,_b5,_c3;config.endpoint&&setFeature2(context2,"ENDPOINT_OVERRIDE","N");const endpoint=await getEndpointFromInstructions(args.input,{getEndpointParameterInstructions:()=>instructions},{...config},context2);context2.endpointV2=endpoint;context2.authSchemes=null==(_a8=endpoint.properties)?void 0:_a8.authSchemes;const authScheme=null==(_b5=context2.authSchemes)?void 0:_b5[0];if(authScheme){context2.signing_region=authScheme.signingRegion;context2.signing_service=authScheme.signingName;const smithyContext=getSmithyContext2(context2),httpAuthOption=null==(_c3=null==smithyContext?void 0:smithyContext.selectedHttpAuthScheme)?void 0:_c3.httpAuthOption;httpAuthOption&&(httpAuthOption.signingProperties=Object.assign(httpAuthOption.signingProperties||{},{signing_region:authScheme.signingRegion,signingRegion:authScheme.signingRegion,signing_service:authScheme.signingName,signingName:authScheme.signingName,signingRegionSet:authScheme.signingRegionSet},authScheme.properties))}return next2({...args})};endpointMiddlewareOptions={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:serializerMiddlewareOption.name};getEndpointPlugin=(config,instructions)=>({applyToStack:clientStack=>{clientStack.addRelativeTo(endpointMiddleware({config,instructions}),endpointMiddlewareOptions)}});resolveEndpointConfig=input=>{var _a8;const tls=null==(_a8=input.tls)||_a8,{endpoint,useDualstackEndpoint,useFipsEndpoint}=input,customEndpointProvider=null!=endpoint?async()=>toEndpointV1(await normalizeProvider(endpoint)()):void 0,isCustomEndpoint=!!endpoint,resolvedConfig=Object.assign(input,{endpoint:customEndpointProvider,tls,isCustomEndpoint,useDualstackEndpoint:normalizeProvider(null!=useDualstackEndpoint&&useDualstackEndpoint),useFipsEndpoint:normalizeProvider(null!=useFipsEndpoint&&useFipsEndpoint)});let configuredEndpointPromise;resolvedConfig.serviceConfiguredEndpoint=async()=>{input.serviceId&&!configuredEndpointPromise&&(configuredEndpointPromise=getEndpointFromConfig(input.serviceId));return configuredEndpointPromise};return resolvedConfig};(function(RETRY_MODES2){RETRY_MODES2.STANDARD="standard";RETRY_MODES2.ADAPTIVE="adaptive"})(RETRY_MODES||(RETRY_MODES={}));DEFAULT_RETRY_MODE=RETRY_MODES.STANDARD;CLOCK_SKEW_ERROR_CODES=["AuthFailure","InvalidSignatureException","RequestExpired","RequestInTheFuture","RequestTimeTooSkewed","SignatureDoesNotMatch"];THROTTLING_ERROR_CODES=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"];TRANSIENT_ERROR_CODES=["TimeoutError","RequestTimeout","RequestTimeoutException"];TRANSIENT_ERROR_STATUS_CODES=[500,502,503,504];NODEJS_TIMEOUT_ERROR_CODES=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"];0;0;isClockSkewCorrectedError=error=>{var _a8;return null==(_a8=error.$metadata)?void 0:_a8.clockSkewCorrected};isBrowserNetworkError=error=>!!(error&&error instanceof TypeError)&&new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]).has(error.message);isThrottlingError=error=>{var _a8,_b5;return 429===(null==(_a8=error.$metadata)?void 0:_a8.httpStatusCode)||THROTTLING_ERROR_CODES.includes(error.name)||1==(null==(_b5=error.$retryable)?void 0:_b5.throttling)};isTransientError=(error,depth=0)=>{var _a8;return isClockSkewCorrectedError(error)||TRANSIENT_ERROR_CODES.includes(error.name)||NODEJS_TIMEOUT_ERROR_CODES.includes((null==error?void 0:error.code)||"")||TRANSIENT_ERROR_STATUS_CODES.includes((null==(_a8=error.$metadata)?void 0:_a8.httpStatusCode)||0)||isBrowserNetworkError(error)||void 0!==error.cause&&depth<=10&&isTransientError(error.cause,depth+1)};isServerError=error=>{var _a8;if(void 0!==(null==(_a8=error.$metadata)?void 0:_a8.httpStatusCode)){const statusCode=error.$metadata.httpStatusCode;return 500<=statusCode&&statusCode<=599&&!isTransientError(error)}return!1};(DefaultRateLimiter=class _DefaultRateLimiter{constructor(options){var _a8,_b5,_c3,_d2,_e2;this.currentCapacity=0;this.enabled=!1;this.lastMaxRate=0;this.measuredTxRate=0;this.requestCount=0;this.lastTimestamp=0;this.timeWindow=0;this.beta=null!=(_a8=null==options?void 0:options.beta)?_a8:.7;this.minCapacity=null!=(_b5=null==options?void 0:options.minCapacity)?_b5:1;this.minFillRate=null!=(_c3=null==options?void 0:options.minFillRate)?_c3:.5;this.scaleConstant=null!=(_d2=null==options?void 0:options.scaleConstant)?_d2:.4;this.smooth=null!=(_e2=null==options?void 0:options.smooth)?_e2:.8;const currentTimeInSeconds=this.getCurrentTimeInSeconds();this.lastThrottleTime=currentTimeInSeconds;this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds());this.fillRate=this.minFillRate;this.maxCapacity=this.minCapacity}getCurrentTimeInSeconds(){return Date.now()/1e3}async getSendToken(){return this.acquireTokenBucket(1)}async acquireTokenBucket(amount){if(this.enabled){this.refillTokenBucket();if(amount>this.currentCapacity){const delay2=(amount-this.currentCapacity)/this.fillRate*1e3;await new Promise((resolve=>_DefaultRateLimiter.setTimeoutFn(resolve,delay2)))}this.currentCapacity=this.currentCapacity-amount}}refillTokenBucket(){const timestamp=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=timestamp;return}const fillAmount=(timestamp-this.lastTimestamp)*this.fillRate;this.currentCapacity=Math.min(this.maxCapacity,this.currentCapacity+fillAmount);this.lastTimestamp=timestamp}updateClientSendingRate(response){let calculatedRate;this.updateMeasuredRate();if(isThrottlingError(response)){const rateToUse=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=rateToUse;this.calculateTimeWindow();this.lastThrottleTime=this.getCurrentTimeInSeconds();calculatedRate=this.cubicThrottle(rateToUse);this.enableTokenBucket()}else{this.calculateTimeWindow();calculatedRate=this.cubicSuccess(this.getCurrentTimeInSeconds())}const newRate=Math.min(calculatedRate,2*this.measuredTxRate);this.updateTokenBucketRate(newRate)}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(rateToUse){return this.getPrecise(rateToUse*this.beta)}cubicSuccess(timestamp){return this.getPrecise(this.scaleConstant*Math.pow(timestamp-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(newRate){this.refillTokenBucket();this.fillRate=Math.max(newRate,this.minFillRate);this.maxCapacity=Math.max(newRate,this.minCapacity);this.currentCapacity=Math.min(this.currentCapacity,this.maxCapacity)}updateMeasuredRate(){const t3=this.getCurrentTimeInSeconds(),timeBucket=Math.floor(2*t3)/2;this.requestCount++;if(timeBucket>this.lastTxRateBucket){const currentRate=this.requestCount/(timeBucket-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(currentRate*this.smooth+this.measuredTxRate*(1-this.smooth));this.requestCount=0;this.lastTxRateBucket=timeBucket}}getPrecise(num){return parseFloat(num.toFixed(8))}}).setTimeoutFn=setTimeout;getDefaultRetryBackoffStrategy=()=>{let delayBase=100;return{computeNextBackoffDelay:attempts=>Math.floor(Math.min(2e4,Math.random()*2**attempts*delayBase)),setDelayBase:delay2=>{delayBase=delay2}}};createDefaultRetryToken=({retryDelay,retryCount,retryCost})=>({getRetryCount:()=>retryCount,getRetryDelay:()=>Math.min(2e4,retryDelay),getRetryCost:()=>retryCost});StandardRetryStrategy=class{constructor(maxAttempts){this.maxAttempts=maxAttempts;this.mode=RETRY_MODES.STANDARD;this.capacity=500;this.retryBackoffStrategy=getDefaultRetryBackoffStrategy();this.maxAttemptsProvider="function"==typeof maxAttempts?maxAttempts:async()=>maxAttempts}async acquireInitialRetryToken(retryTokenScope){return createDefaultRetryToken({retryDelay:100,retryCount:0})}async refreshRetryTokenForRetry(token,errorInfo){const maxAttempts=await this.getMaxAttempts();if(this.shouldRetry(token,errorInfo,maxAttempts)){const errorType=errorInfo.errorType;this.retryBackoffStrategy.setDelayBase("THROTTLING"===errorType?500:100);const delayFromErrorType=this.retryBackoffStrategy.computeNextBackoffDelay(token.getRetryCount()),retryDelay=errorInfo.retryAfterHint?Math.max(errorInfo.retryAfterHint.getTime()-Date.now()||0,delayFromErrorType):delayFromErrorType,capacityCost=this.getCapacityCost(errorType);this.capacity-=capacityCost;return createDefaultRetryToken({retryDelay,retryCount:token.getRetryCount()+1,retryCost:capacityCost})}throw new Error("No retry token available")}recordSuccess(token){var _a8;this.capacity=Math.max(500,this.capacity+(null!=(_a8=token.getRetryCost())?_a8:1))}getCapacity(){return this.capacity}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch(error){console.warn("Max attempts provider could not resolve. Using default of 3");return 3}}shouldRetry(tokenToRenew,errorInfo,maxAttempts){return tokenToRenew.getRetryCount()+1<maxAttempts&&this.capacity>=this.getCapacityCost(errorInfo.errorType)&&this.isRetryableError(errorInfo.errorType)}getCapacityCost(errorType){return"TRANSIENT"===errorType?10:5}isRetryableError(errorType){return"THROTTLING"===errorType||"TRANSIENT"===errorType}};AdaptiveRetryStrategy=class{constructor(maxAttemptsProvider,options){this.maxAttemptsProvider=maxAttemptsProvider;this.mode=RETRY_MODES.ADAPTIVE;const{rateLimiter}=null!=options?options:{};this.rateLimiter=null!=rateLimiter?rateLimiter:new DefaultRateLimiter;this.standardRetryStrategy=new StandardRetryStrategy(maxAttemptsProvider)}async acquireInitialRetryToken(retryTokenScope){await this.rateLimiter.getSendToken();return this.standardRetryStrategy.acquireInitialRetryToken(retryTokenScope)}async refreshRetryTokenForRetry(tokenToRenew,errorInfo){this.rateLimiter.updateClientSendingRate(errorInfo);return this.standardRetryStrategy.refreshRetryTokenForRetry(tokenToRenew,errorInfo)}recordSuccess(token){this.rateLimiter.updateClientSendingRate({});this.standardRetryStrategy.recordSuccess(token)}};ConfiguredRetryStrategy=class extends StandardRetryStrategy{constructor(maxAttempts,computeNextBackoffDelay=100){super("function"==typeof maxAttempts?maxAttempts:async()=>maxAttempts);this.computeNextBackoffDelay="number"==typeof computeNextBackoffDelay?()=>computeNextBackoffDelay:computeNextBackoffDelay}async refreshRetryTokenForRetry(tokenToRenew,errorInfo){const token=await super.refreshRetryTokenForRetry(tokenToRenew,errorInfo);token.getRetryDelay=()=>this.computeNextBackoffDelay(token.getRetryCount());return token}};rnds8=new Uint8Array(16);byteToHex=[];for(let i2=0;i2<256;++i2)byteToHex.push((i2+256).toString(16).slice(1));randomUUID="undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);native_default={randomUUID};v4_default=function v4(options,buf,offset){if(native_default.randomUUID&&!buf&&!options)return native_default.randomUUID();const rnds=(options=options||{}).random||(options.rng||rng)();rnds[6]=15&rnds[6]|64;rnds[8]=63&rnds[8]|128;if(buf){offset=offset||0;for(let i2=0;i2<16;++i2)buf[offset+i2]=rnds[i2];return buf}return unsafeStringify(rnds)};asSdkError=error=>error instanceof Error?error:error instanceof Object?Object.assign(new Error,error):"string"==typeof error?new Error(error):new Error(`AWS SDK error wrapper for ${error}`);resolveRetryConfig=input=>{const{retryStrategy,retryMode:_retryMode,maxAttempts:_maxAttempts}=input,maxAttempts=normalizeProvider(null!=_maxAttempts?_maxAttempts:3);return Object.assign(input,{maxAttempts,retryStrategy:async()=>retryStrategy||(await normalizeProvider(_retryMode)()===RETRY_MODES.ADAPTIVE?new AdaptiveRetryStrategy(maxAttempts):new StandardRetryStrategy(maxAttempts))})};isStreamingPayload=request2=>(null==request2?void 0:request2.body)instanceof ReadableStream;retryMiddleware=options=>(next2,context2)=>async args=>{var _a8;let retryStrategy=await options.retryStrategy();const maxAttempts=await options.maxAttempts();if(!isRetryStrategyV2(retryStrategy)){(null==retryStrategy?void 0:retryStrategy.mode)&&(context2.userAgent=[...context2.userAgent||[],["cfg/retry-mode",retryStrategy.mode]]);return retryStrategy.retry(next2,args)}{let retryToken=await retryStrategy.acquireInitialRetryToken(context2.partition_id),lastError=new Error,attempts=0,totalRetryDelay=0;const{request:request2}=args,isRequest=HttpRequest.isInstance(request2);isRequest&&(request2.headers["amz-sdk-invocation-id"]=v4_default());for(;;)try{isRequest&&(request2.headers["amz-sdk-request"]=`attempt=${attempts+1}; max=${maxAttempts}`);const{response,output}=await next2(args);retryStrategy.recordSuccess(retryToken);output.$metadata.attempts=attempts+1;output.$metadata.totalRetryDelay=totalRetryDelay;return{response,output}}catch(e3){const retryErrorInfo=getRetryErrorInfo(e3);lastError=asSdkError(e3);if(isRequest&&isStreamingPayload(request2)){null==(_a8=context2.logger instanceof NoOpLogger?console:context2.logger)||_a8.warn("An error was encountered in a non-retryable streaming request.");throw lastError}try{retryToken=await retryStrategy.refreshRetryTokenForRetry(retryToken,retryErrorInfo)}catch(refreshError){lastError.$metadata||(lastError.$metadata={});lastError.$metadata.attempts=attempts+1;lastError.$metadata.totalRetryDelay=totalRetryDelay;throw lastError}attempts=retryToken.getRetryCount();const delay2=retryToken.getRetryDelay();totalRetryDelay+=delay2;await new Promise((resolve=>setTimeout(resolve,delay2)))}}};isRetryStrategyV2=retryStrategy=>void 0!==retryStrategy.acquireInitialRetryToken&&void 0!==retryStrategy.refreshRetryTokenForRetry&&void 0!==retryStrategy.recordSuccess;getRetryErrorInfo=error=>{const errorInfo={error,errorType:getRetryErrorType(error)},retryAfterHint=getRetryAfterHint(error.$response);retryAfterHint&&(errorInfo.retryAfterHint=retryAfterHint);return errorInfo};getRetryErrorType=error=>isThrottlingError(error)?"THROTTLING":isTransientError(error)?"TRANSIENT":isServerError(error)?"SERVER_ERROR":"CLIENT_ERROR";retryMiddlewareOptions={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};getRetryPlugin=options=>({applyToStack:clientStack=>{clientStack.add(retryMiddleware(options),retryMiddlewareOptions)}});getRetryAfterHint=response=>{if(!HttpResponse.isInstance(response))return;const retryAfterHeaderName=Object.keys(response.headers).find((key3=>"retry-after"===key3.toLowerCase()));if(!retryAfterHeaderName)return;const retryAfter=response.headers[retryAfterHeaderName],retryAfterSeconds=Number(retryAfter);return Number.isNaN(retryAfterSeconds)?new Date(retryAfter):new Date(1e3*retryAfterSeconds)};SignatureV4MultiRegion=class{constructor(options){__publicField(this,"sigv4aSigner");__publicField(this,"sigv4Signer");__publicField(this,"signerOptions");this.sigv4Signer=new SignatureV4S3Express(options);this.signerOptions=options}async sign(requestToSign,options={}){return"*"===options.signingRegion?this.getSigv4aSigner().sign(requestToSign,options):this.sigv4Signer.sign(requestToSign,options)}async signWithCredentials(requestToSign,credentials,options={}){if("*"===options.signingRegion){this.getSigv4aSigner();throw new Error('signWithCredentials with signingRegion \'*\' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt')}return this.sigv4Signer.signWithCredentials(requestToSign,credentials,options)}async presign(originalRequest,options={}){if("*"===options.signingRegion){this.getSigv4aSigner();throw new Error('presign with signingRegion \'*\' is only supported when using the CRT dependency @aws-sdk/signature-v4-crt. Please check whether you have installed the "@aws-sdk/signature-v4-crt" package explicitly. You must also register the package by calling [require("@aws-sdk/signature-v4-crt");] or an ESM equivalent such as [import "@aws-sdk/signature-v4-crt";]. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt')}return this.sigv4Signer.presign(originalRequest,options)}async presignWithCredentials(originalRequest,credentials,options={}){if("*"===options.signingRegion)throw new Error("Method presignWithCredentials is not supported for [signingRegion=*].");return this.sigv4Signer.presignWithCredentials(originalRequest,credentials,options)}getSigv4aSigner(){if(!this.sigv4aSigner){const CrtSignerV4=null,JsSigV4aSigner=null;if("node"===this.signerOptions.runtime){if(!CrtSignerV4&&!JsSigV4aSigner)throw new Error("Neither CRT nor JS SigV4a implementation is available. Please load either @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a. For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");if(CrtSignerV4&&"function"==typeof CrtSignerV4)this.sigv4aSigner=new CrtSignerV4({...this.signerOptions,signingAlgorithm:1});else{if(!JsSigV4aSigner||"function"!=typeof JsSigV4aSigner)throw new Error("Available SigV4a implementation is not a valid constructor. Please ensure you've properly imported @aws-sdk/signature-v4-crt or @aws-sdk/signature-v4a.For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");this.sigv4aSigner=new JsSigV4aSigner({...this.signerOptions})}}else{if(!JsSigV4aSigner||"function"!=typeof JsSigV4aSigner)throw new Error("JS SigV4a implementation is not available or not a valid constructor. Please check whether you have installed the @aws-sdk/signature-v4a package explicitly. The CRT implementation is not available for browsers. You must also register the package by calling [require('@aws-sdk/signature-v4a');] or an ESM equivalent such as [import '@aws-sdk/signature-v4a';]. For more information please go to https://github.com/aws/aws-sdk-js-v3#using-javascript-non-crt-implementation-of-sigv4a");this.sigv4aSigner=new JsSigV4aSigner({...this.signerOptions})}}return this.sigv4aSigner}};cp="required",cq="type",cr2="rules",cs="conditions",ct="fn",cu="argv",cv="ref",cw="assign",cx="url",cy="properties",cz="backend",cA="authSchemes",cB="disableDoubleEncoding",cC="signingName",cD="signingRegion",cE="headers",cF="signingRegionSet";c=!0,d3="isSet",e2="booleanEquals",f="error",g="aws.partition",h="stringEquals",i="getAttr",j="name",k="substring",l="bucketSuffix",m2="parseURL",n2="endpoint",o="tree",p2="aws.isVirtualHostableS3Bucket",q="{url#scheme}://{Bucket}.{url#authority}{url#path}",r3="not",s="accessPointSuffix",t2="{url#scheme}://{url#authority}{url#path}",u="hardwareType",v="regionPrefix",w="bucketAliasSuffix",x="outpostId",y="isValidHostLabel",z="sigv4a",A="s3-outposts",B="s3",C2="{url#scheme}://{url#authority}{url#normalizedPath}{Bucket}",D="https://{Bucket}.s3-accelerate.{partitionResult#dnsSuffix}",E="https://{Bucket}.s3.{partitionResult#dnsSuffix}",F="aws.parseArn",G2="bucketArn",H="arnType",J="s3-object-lambda",K="accesspoint",L3="accessPointName",M2="{url#scheme}://{accessPointName}-{bucketArn#accountId}.{url#authority}{url#path}",N2="mrapPartition",O="outpostType",P2="arnPrefix",Q="{url#scheme}://{url#authority}{url#normalizedPath}{uri_encoded_bucket}",R="https://s3.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",S="https://s3.{partitionResult#dnsSuffix}",T={[cp]:!1,[cq]:"String"},U={[cp]:!0,default:!1,[cq]:"Boolean"},V={[cp]:!1,[cq]:"Boolean"},W2={[ct]:e2,[cu]:[{[cv]:"Accelerate"},!0]},X={[ct]:e2,[cu]:[{[cv]:"UseFIPS"},!0]},Y={[ct]:e2,[cu]:[{[cv]:"UseDualStack"},!0]},Z={[ct]:d3,[cu]:[{[cv]:"Endpoint"}]},aa={[ct]:g,[cu]:[{[cv]:"Region"}],[cw]:"partitionResult"},ab={[ct]:h,[cu]:[{[ct]:i,[cu]:[{[cv]:"partitionResult"},j]},"aws-cn"]},ac={[ct]:d3,[cu]:[{[cv]:"Bucket"}]},ad={[cv]:"Bucket"},ae={[cs]:[Y],[f]:"S3Express does not support Dual-stack.",[cq]:f},af={[cs]:[W2],[f]:"S3Express does not support S3 Accelerate.",[cq]:f},ag={[cs]:[Z,{[ct]:m2,[cu]:[{[cv]:"Endpoint"}],[cw]:"url"}],[cr2]:[{[cs]:[{[ct]:d3,[cu]:[{[cv]:"DisableS3ExpressSessionAuth"}]},{[ct]:e2,[cu]:[{[cv]:"DisableS3ExpressSessionAuth"},!0]}],[cr2]:[{[cs]:[{[ct]:e2,[cu]:[{[ct]:i,[cu]:[{[cv]:"url"},"isIp"]},!0]}],[cr2]:[{[cs]:[{[ct]:"uriEncode",[cu]:[ad],[cw]:"uri_encoded_bucket"}],[cr2]:[{[n2]:{[cx]:"{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",[cy]:{[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:"s3express",[cD]:"{Region}"}]},[cE]:{}},[cq]:n2}],[cq]:o}],[cq]:o},{[cs]:[{[ct]:p2,[cu]:[ad,!1]}],[cr2]:[{[n2]:{[cx]:q,[cy]:{[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:"s3express",[cD]:"{Region}"}]},[cE]:{}},[cq]:n2}],[cq]:o},{[f]:"S3Express bucket name is not a valid virtual hostable name.",[cq]:f}],[cq]:o},{[cs]:[{[ct]:e2,[cu]:[{[ct]:i,[cu]:[{[cv]:"url"},"isIp"]},!0]}],[cr2]:[{[cs]:[{[ct]:"uriEncode",[cu]:[ad],[cw]:"uri_encoded_bucket"}],[cr2]:[{[n2]:{[cx]:"{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",[cy]:{[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4-s3express",[cC]:"s3express",[cD]:"{Region}"}]},[cE]:{}},[cq]:n2}],[cq]:o}],[cq]:o},{[cs]:[{[ct]:p2,[cu]:[ad,!1]}],[cr2]:[{[n2]:{[cx]:q,[cy]:{[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4-s3express",[cC]:"s3express",[cD]:"{Region}"}]},[cE]:{}},[cq]:n2}],[cq]:o},{[f]:"S3Express bucket name is not a valid virtual hostable name.",[cq]:f}],[cq]:o},ah={[ct]:m2,[cu]:[{[cv]:"Endpoint"}],[cw]:"url"},ai={[ct]:e2,[cu]:[{[ct]:i,[cu]:[{[cv]:"url"},"isIp"]},!0]},aj={[cv]:"url"},ak={[ct]:"uriEncode",[cu]:[ad],[cw]:"uri_encoded_bucket"},al={[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:"s3express",[cD]:"{Region}"}]},am={},an={[ct]:p2,[cu]:[ad,!1]},ao={[f]:"S3Express bucket name is not a valid virtual hostable name.",[cq]:f},ap={[ct]:d3,[cu]:[{[cv]:"UseS3ExpressControlEndpoint"}]},aq={[ct]:e2,[cu]:[{[cv]:"UseS3ExpressControlEndpoint"},!0]},ar={[ct]:r3,[cu]:[Z]},as={[f]:"Unrecognized S3Express bucket name format.",[cq]:f},at={[ct]:r3,[cu]:[ac]},au={[cv]:u},av={[cs]:[ar],[f]:"Expected a endpoint to be specified but no endpoint was found",[cq]:f},aw={[cA]:[{[cB]:!0,[j]:z,[cC]:A,[cF]:["*"]},{[cB]:!0,[j]:"sigv4",[cC]:A,[cD]:"{Region}"}]},ax={[ct]:e2,[cu]:[{[cv]:"ForcePathStyle"},!1]},ay={[cv]:"ForcePathStyle"},az={[ct]:e2,[cu]:[{[cv]:"Accelerate"},!1]},aA={[ct]:h,[cu]:[{[cv]:"Region"},"aws-global"]},aB={[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:B,[cD]:"us-east-1"}]},aC={[ct]:r3,[cu]:[aA]},aD={[ct]:e2,[cu]:[{[cv]:"UseGlobalEndpoint"},!0]},aE={[cx]:"https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[cy]:{[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:B,[cD]:"{Region}"}]},[cE]:{}},aF={[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:B,[cD]:"{Region}"}]},aG={[ct]:e2,[cu]:[{[cv]:"UseGlobalEndpoint"},!1]},aH={[ct]:e2,[cu]:[{[cv]:"UseDualStack"},!1]},aI={[cx]:"https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},aJ={[ct]:e2,[cu]:[{[cv]:"UseFIPS"},!1]},aK={[cx]:"https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},aL={[cx]:"https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},aM={[ct]:e2,[cu]:[{[ct]:i,[cu]:[aj,"isIp"]},!1]},aN={[cx]:C2,[cy]:aF,[cE]:{}},aO={[cx]:q,[cy]:aF,[cE]:{}},aP={[n2]:aO,[cq]:n2},aQ={[cx]:D,[cy]:aF,[cE]:{}},aR={[cx]:"https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},aS={[f]:"Invalid region: region was not a valid DNS name.",[cq]:f},aT={[cv]:G2},aU={[cv]:H},aV={[ct]:i,[cu]:[aT,"service"]},aW={[cv]:L3},aX={[cs]:[Y],[f]:"S3 Object Lambda does not support Dual-stack",[cq]:f},aY={[cs]:[W2],[f]:"S3 Object Lambda does not support S3 Accelerate",[cq]:f},aZ={[cs]:[{[ct]:d3,[cu]:[{[cv]:"DisableAccessPoints"}]},{[ct]:e2,[cu]:[{[cv]:"DisableAccessPoints"},!0]}],[f]:"Access points are not supported for this operation",[cq]:f},ba={[cs]:[{[ct]:d3,[cu]:[{[cv]:"UseArnRegion"}]},{[ct]:e2,[cu]:[{[cv]:"UseArnRegion"},!1]},{[ct]:r3,[cu]:[{[ct]:h,[cu]:[{[ct]:i,[cu]:[aT,"region"]},"{Region}"]}]}],[f]:"Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`",[cq]:f},bb={[ct]:i,[cu]:[{[cv]:"bucketPartition"},j]},bc={[ct]:i,[cu]:[aT,"accountId"]},bd={[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:J,[cD]:"{bucketArn#region}"}]},be={[f]:"Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`",[cq]:f},bf={[f]:"Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`",[cq]:f},bg={[f]:"Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)",[cq]:f},bh={[f]:"Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`",[cq]:f},bi={[f]:"Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.",[cq]:f},bj={[f]:"Invalid ARN: Expected a resource of the format `accesspoint:<accesspoint name>` but no name was provided",[cq]:f},bk={[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:B,[cD]:"{bucketArn#region}"}]},bl={[cA]:[{[cB]:!0,[j]:z,[cC]:A,[cF]:["*"]},{[cB]:!0,[j]:"sigv4",[cC]:A,[cD]:"{bucketArn#region}"}]},bm={[ct]:F,[cu]:[ad]},bn={[cx]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aF,[cE]:{}},bo={[cx]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aF,[cE]:{}},bp={[cx]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aF,[cE]:{}},bq={[cx]:Q,[cy]:aF,[cE]:{}},br={[cx]:"https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aF,[cE]:{}},bs={[cv]:"UseObjectLambdaEndpoint"},bt={[cA]:[{[cB]:!0,[j]:"sigv4",[cC]:J,[cD]:"{Region}"}]},bu={[cx]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},bv={[cx]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},bw={[cx]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},bx={[cx]:t2,[cy]:aF,[cE]:{}},by={[cx]:"https://s3.{Region}.{partitionResult#dnsSuffix}",[cy]:aF,[cE]:{}},bz=[{[cv]:"Region"}],bA=[{[cv]:"Endpoint"}],bB=[ad],bC=[Y],bD=[W2],bE=[Z,ah],bF=[{[ct]:d3,[cu]:[{[cv]:"DisableS3ExpressSessionAuth"}]},{[ct]:e2,[cu]:[{[cv]:"DisableS3ExpressSessionAuth"},!0]}],bG=[ak],bH=[an],bI=[aa],bJ=[X],bK=[{[ct]:k,[cu]:[ad,6,14,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,14,16,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bL=[{[cs]:[X],[n2]:{[cx]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cy]:al,[cE]:{}},[cq]:n2},{[n2]:{[cx]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cy]:al,[cE]:{}},[cq]:n2}],bM=[{[ct]:k,[cu]:[ad,6,15,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,15,17,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bN=[{[ct]:k,[cu]:[ad,6,19,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,19,21,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bO=[{[ct]:k,[cu]:[ad,6,20,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,20,22,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bP=[{[ct]:k,[cu]:[ad,6,26,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,26,28,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bQ=[{[cs]:[X],[n2]:{[cx]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cy]:{[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4-s3express",[cC]:"s3express",[cD]:"{Region}"}]},[cE]:{}},[cq]:n2},{[n2]:{[cx]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cy]:{[cz]:"S3Express",[cA]:[{[cB]:!0,[j]:"sigv4-s3express",[cC]:"s3express",[cD]:"{Region}"}]},[cE]:{}},[cq]:n2}],bR=[ad,0,7,!0],bS=[{[ct]:k,[cu]:[ad,7,15,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,15,17,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bT=[{[ct]:k,[cu]:[ad,7,16,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,16,18,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bU=[{[ct]:k,[cu]:[ad,7,20,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,20,22,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bV=[{[ct]:k,[cu]:[ad,7,21,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,21,23,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bW=[{[ct]:k,[cu]:[ad,7,27,!0],[cw]:"s3expressAvailabilityZoneId"},{[ct]:k,[cu]:[ad,27,29,!0],[cw]:"s3expressAvailabilityZoneDelim"},{[ct]:h,[cu]:[{[cv]:"s3expressAvailabilityZoneDelim"},"--"]}],bX=[ac],bY=[{[ct]:y,[cu]:[{[cv]:x},!1]}],bZ=[{[ct]:h,[cu]:[{[cv]:v},"beta"]}],ca=["*"],cb=[{[ct]:y,[cu]:[{[cv]:"Region"},!1]}],cc=[{[ct]:h,[cu]:[{[cv]:"Region"},"us-east-1"]}],cd=[{[ct]:h,[cu]:[aU,K]}],ce=[{[ct]:i,[cu]:[aT,"resourceId[1]"],[cw]:L3},{[ct]:r3,[cu]:[{[ct]:h,[cu]:[aW,""]}]}],cf=[aT,"resourceId[1]"],cg=[{[ct]:r3,[cu]:[{[ct]:h,[cu]:[{[ct]:i,[cu]:[aT,"region"]},""]}]}],ch=[{[ct]:r3,[cu]:[{[ct]:d3,[cu]:[{[ct]:i,[cu]:[aT,"resourceId[2]"]}]}]}],ci=[aT,"resourceId[2]"],cj=[{[ct]:g,[cu]:[{[ct]:i,[cu]:[aT,"region"]}],[cw]:"bucketPartition"}],ck=[{[ct]:h,[cu]:[bb,{[ct]:i,[cu]:[{[cv]:"partitionResult"},j]}]}],cl=[{[ct]:y,[cu]:[{[ct]:i,[cu]:[aT,"region"]},!0]}],cm=[{[ct]:y,[cu]:[bc,!1]}],cn=[{[ct]:y,[cu]:[aW,!1]}],co=[{[ct]:y,[cu]:[{[cv]:"Region"},!0]}];ruleSet={version:"1.0",parameters:{Bucket:T,Region:T,UseFIPS:U,UseDualStack:U,Endpoint:T,ForcePathStyle:U,Accelerate:U,UseGlobalEndpoint:U,UseObjectLambdaEndpoint:V,Key:T,Prefix:T,CopySource:T,DisableAccessPoints:V,DisableMultiRegionAccessPoints:U,UseArnRegion:V,UseS3ExpressControlEndpoint:V,DisableS3ExpressSessionAuth:V},[cr2]:[{[cs]:[{[ct]:d3,[cu]:bz}],[cr2]:[{[cs]:[W2,X],error:"Accelerate cannot be used with FIPS",[cq]:f},{[cs]:[Y,Z],error:"Cannot set dual-stack in combination with a custom endpoint.",[cq]:f},{[cs]:[Z,X],error:"A custom endpoint cannot be combined with FIPS",[cq]:f},{[cs]:[Z,W2],error:"A custom endpoint cannot be combined with S3 Accelerate",[cq]:f},{[cs]:[X,aa,ab],error:"Partition does not support FIPS",[cq]:f},{[cs]:[ac,{[ct]:k,[cu]:[ad,0,6,c],[cw]:l},{[ct]:h,[cu]:[{[cv]:l},"--x-s3"]}],[cr2]:[ae,af,ag,{[cs]:[ap,aq],[cr2]:[{[cs]:bI,[cr2]:[{[cs]:[ak,ar],[cr2]:[{[cs]:bJ,endpoint:{[cx]:"https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:al,[cE]:am},[cq]:n2},{endpoint:{[cx]:"https://s3express-control.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:al,[cE]:am},[cq]:n2}],[cq]:o}],[cq]:o}],[cq]:o},{[cs]:bH,[cr2]:[{[cs]:bI,[cr2]:[{[cs]:bF,[cr2]:[{[cs]:bK,[cr2]:bL,[cq]:o},{[cs]:bM,[cr2]:bL,[cq]:o},{[cs]:bN,[cr2]:bL,[cq]:o},{[cs]:bO,[cr2]:bL,[cq]:o},{[cs]:bP,[cr2]:bL,[cq]:o},as],[cq]:o},{[cs]:bK,[cr2]:bQ,[cq]:o},{[cs]:bM,[cr2]:bQ,[cq]:o},{[cs]:bN,[cr2]:bQ,[cq]:o},{[cs]:bO,[cr2]:bQ,[cq]:o},{[cs]:bP,[cr2]:bQ,[cq]:o},as],[cq]:o}],[cq]:o},ao],[cq]:o},{[cs]:[ac,{[ct]:k,[cu]:bR,[cw]:s},{[ct]:h,[cu]:[{[cv]:s},"--xa-s3"]}],[cr2]:[ae,af,ag,{[cs]:bH,[cr2]:[{[cs]:bI,[cr2]:[{[cs]:bF,[cr2]:[{[cs]:bS,[cr2]:bL,[cq]:o},{[cs]:bT,[cr2]:bL,[cq]:o},{[cs]:bU,[cr2]:bL,[cq]:o},{[cs]:bV,[cr2]:bL,[cq]:o},{[cs]:bW,[cr2]:bL,[cq]:o},as],[cq]:o},{[cs]:bS,[cr2]:bQ,[cq]:o},{[cs]:bT,[cr2]:bQ,[cq]:o},{[cs]:bU,[cr2]:bQ,[cq]:o},{[cs]:bV,[cr2]:bQ,[cq]:o},{[cs]:bW,[cr2]:bQ,[cq]:o},as],[cq]:o}],[cq]:o},ao],[cq]:o},{[cs]:[at,ap,aq],[cr2]:[{[cs]:bI,[cr2]:[{[cs]:bE,endpoint:{[cx]:t2,[cy]:al,[cE]:am},[cq]:n2},{[cs]:bJ,endpoint:{[cx]:"https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}",[cy]:al,[cE]:am},[cq]:n2},{endpoint:{[cx]:"https://s3express-control.{Region}.{partitionResult#dnsSuffix}",[cy]:al,[cE]:am},[cq]:n2}],[cq]:o}],[cq]:o},{[cs]:[ac,{[ct]:k,[cu]:[ad,49,50,c],[cw]:u},{[ct]:k,[cu]:[ad,8,12,c],[cw]:v},{[ct]:k,[cu]:bR,[cw]:w},{[ct]:k,[cu]:[ad,32,49,c],[cw]:x},{[ct]:g,[cu]:bz,[cw]:"regionPartition"},{[ct]:h,[cu]:[{[cv]:w},"--op-s3"]}],[cr2]:[{[cs]:bY,[cr2]:[{[cs]:[{[ct]:h,[cu]:[au,"e"]}],[cr2]:[{[cs]:bZ,[cr2]:[av,{[cs]:bE,endpoint:{[cx]:"https://{Bucket}.ec2.{url#authority}",[cy]:aw,[cE]:am},[cq]:n2}],[cq]:o},{endpoint:{[cx]:"https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[cy]:aw,[cE]:am},[cq]:n2}],[cq]:o},{[cs]:[{[ct]:h,[cu]:[au,"o"]}],[cr2]:[{[cs]:bZ,[cr2]:[av,{[cs]:bE,endpoint:{[cx]:"https://{Bucket}.op-{outpostId}.{url#authority}",[cy]:aw,[cE]:am},[cq]:n2}],[cq]:o},{endpoint:{[cx]:"https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[cy]:aw,[cE]:am},[cq]:n2}],[cq]:o},{error:'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"',[cq]:f}],[cq]:o},{error:"Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.",[cq]:f}],[cq]:o},{[cs]:bX,[cr2]:[{[cs]:[Z,{[ct]:r3,[cu]:[{[ct]:d3,[cu]:[{[ct]:m2,[cu]:bA}]}]}],error:"Custom endpoint `{Endpoint}` was not a valid URI",[cq]:f},{[cs]:[ax,an],[cr2]:[{[cs]:bI,[cr2]:[{[cs]:cb,[cr2]:[{[cs]:[W2,ab],error:"S3 Accelerate cannot be used in this region",[cq]:f},{[cs]:[Y,X,az,ar,aA],endpoint:{[cx]:"https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[Y,X,az,ar,aC,aD],[cr2]:[{endpoint:aE,[cq]:n2}],[cq]:o},{[cs]:[Y,X,az,ar,aC,aG],endpoint:aE,[cq]:n2},{[cs]:[aH,X,az,ar,aA],endpoint:{[cx]:"https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,X,az,ar,aC,aD],[cr2]:[{endpoint:aI,[cq]:n2}],[cq]:o},{[cs]:[aH,X,az,ar,aC,aG],endpoint:aI,[cq]:n2},{[cs]:[Y,aJ,W2,ar,aA],endpoint:{[cx]:"https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[Y,aJ,W2,ar,aC,aD],[cr2]:[{endpoint:aK,[cq]:n2}],[cq]:o},{[cs]:[Y,aJ,W2,ar,aC,aG],endpoint:aK,[cq]:n2},{[cs]:[Y,aJ,az,ar,aA],endpoint:{[cx]:"https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[Y,aJ,az,ar,aC,aD],[cr2]:[{endpoint:aL,[cq]:n2}],[cq]:o},{[cs]:[Y,aJ,az,ar,aC,aG],endpoint:aL,[cq]:n2},{[cs]:[aH,aJ,az,Z,ah,ai,aA],endpoint:{[cx]:C2,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,aJ,az,Z,ah,aM,aA],endpoint:{[cx]:q,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,aJ,az,Z,ah,ai,aC,aD],[cr2]:[{[cs]:cc,endpoint:aN,[cq]:n2},{endpoint:aN,[cq]:n2}],[cq]:o},{[cs]:[aH,aJ,az,Z,ah,aM,aC,aD],[cr2]:[{[cs]:cc,endpoint:aO,[cq]:n2},aP],[cq]:o},{[cs]:[aH,aJ,az,Z,ah,ai,aC,aG],endpoint:aN,[cq]:n2},{[cs]:[aH,aJ,az,Z,ah,aM,aC,aG],endpoint:aO,[cq]:n2},{[cs]:[aH,aJ,W2,ar,aA],endpoint:{[cx]:D,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,aJ,W2,ar,aC,aD],[cr2]:[{[cs]:cc,endpoint:aQ,[cq]:n2},{endpoint:aQ,[cq]:n2}],[cq]:o},{[cs]:[aH,aJ,W2,ar,aC,aG],endpoint:aQ,[cq]:n2},{[cs]:[aH,aJ,az,ar,aA],endpoint:{[cx]:E,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,aJ,az,ar,aC,aD],[cr2]:[{[cs]:cc,endpoint:{[cx]:E,[cy]:aF,[cE]:am},[cq]:n2},{endpoint:aR,[cq]:n2}],[cq]:o},{[cs]:[aH,aJ,az,ar,aC,aG],endpoint:aR,[cq]:n2}],[cq]:o},aS],[cq]:o}],[cq]:o},{[cs]:[Z,ah,{[ct]:h,[cu]:[{[ct]:i,[cu]:[aj,"scheme"]},"http"]},{[ct]:p2,[cu]:[ad,c]},ax,aJ,aH,az],[cr2]:[{[cs]:bI,[cr2]:[{[cs]:cb,[cr2]:[aP],[cq]:o},aS],[cq]:o}],[cq]:o},{[cs]:[ax,{[ct]:F,[cu]:bB,[cw]:G2}],[cr2]:[{[cs]:[{[ct]:i,[cu]:[aT,"resourceId[0]"],[cw]:H},{[ct]:r3,[cu]:[{[ct]:h,[cu]:[aU,""]}]}],[cr2]:[{[cs]:[{[ct]:h,[cu]:[aV,J]}],[cr2]:[{[cs]:cd,[cr2]:[{[cs]:ce,[cr2]:[aX,aY,{[cs]:cg,[cr2]:[aZ,{[cs]:ch,[cr2]:[ba,{[cs]:cj,[cr2]:[{[cs]:bI,[cr2]:[{[cs]:ck,[cr2]:[{[cs]:cl,[cr2]:[{[cs]:[{[ct]:h,[cu]:[bc,""]}],error:"Invalid ARN: Missing account id",[cq]:f},{[cs]:cm,[cr2]:[{[cs]:cn,[cr2]:[{[cs]:bE,endpoint:{[cx]:M2,[cy]:bd,[cE]:am},[cq]:n2},{[cs]:bJ,endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bd,[cE]:am},[cq]:n2},{endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bd,[cE]:am},[cq]:n2}],[cq]:o},be],[cq]:o},bf],[cq]:o},bg],[cq]:o},bh],[cq]:o}],[cq]:o}],[cq]:o},bi],[cq]:o},{error:"Invalid ARN: bucket ARN is missing a region",[cq]:f}],[cq]:o},bj],[cq]:o},{error:"Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`",[cq]:f}],[cq]:o},{[cs]:cd,[cr2]:[{[cs]:ce,[cr2]:[{[cs]:cg,[cr2]:[{[cs]:cd,[cr2]:[{[cs]:cg,[cr2]:[aZ,{[cs]:ch,[cr2]:[ba,{[cs]:cj,[cr2]:[{[cs]:bI,[cr2]:[{[cs]:[{[ct]:h,[cu]:[bb,"{partitionResult#name}"]}],[cr2]:[{[cs]:cl,[cr2]:[{[cs]:[{[ct]:h,[cu]:[aV,B]}],[cr2]:[{[cs]:cm,[cr2]:[{[cs]:cn,[cr2]:[{[cs]:bD,error:"Access Points do not support S3 Accelerate",[cq]:f},{[cs]:[X,Y],endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bk,[cE]:am},[cq]:n2},{[cs]:[X,aH],endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bk,[cE]:am},[cq]:n2},{[cs]:[aJ,Y],endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bk,[cE]:am},[cq]:n2},{[cs]:[aJ,aH,Z,ah],endpoint:{[cx]:M2,[cy]:bk,[cE]:am},[cq]:n2},{[cs]:[aJ,aH],endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bk,[cE]:am},[cq]:n2}],[cq]:o},be],[cq]:o},bf],[cq]:o},{error:"Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}",[cq]:f}],[cq]:o},bg],[cq]:o},bh],[cq]:o}],[cq]:o}],[cq]:o},bi],[cq]:o}],[cq]:o}],[cq]:o},{[cs]:[{[ct]:y,[cu]:[aW,c]}],[cr2]:[{[cs]:bC,error:"S3 MRAP does not support dual-stack",[cq]:f},{[cs]:bJ,error:"S3 MRAP does not support FIPS",[cq]:f},{[cs]:bD,error:"S3 MRAP does not support S3 Accelerate",[cq]:f},{[cs]:[{[ct]:e2,[cu]:[{[cv]:"DisableMultiRegionAccessPoints"},c]}],error:"Invalid configuration: Multi-Region Access Point ARNs are disabled.",[cq]:f},{[cs]:[{[ct]:g,[cu]:bz,[cw]:N2}],[cr2]:[{[cs]:[{[ct]:h,[cu]:[{[ct]:i,[cu]:[{[cv]:N2},j]},{[ct]:i,[cu]:[aT,"partition"]}]}],[cr2]:[{endpoint:{[cx]:"https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}",[cy]:{[cA]:[{[cB]:c,name:z,[cC]:B,[cF]:ca}]},[cE]:am},[cq]:n2}],[cq]:o},{error:"Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`",[cq]:f}],[cq]:o}],[cq]:o},{error:"Invalid Access Point Name",[cq]:f}],[cq]:o},bj],[cq]:o},{[cs]:[{[ct]:h,[cu]:[aV,A]}],[cr2]:[{[cs]:bC,error:"S3 Outposts does not support Dual-stack",[cq]:f},{[cs]:bJ,error:"S3 Outposts does not support FIPS",[cq]:f},{[cs]:bD,error:"S3 Outposts does not support S3 Accelerate",[cq]:f},{[cs]:[{[ct]:d3,[cu]:[{[ct]:i,[cu]:[aT,"resourceId[4]"]}]}],error:"Invalid Arn: Outpost Access Point ARN contains sub resources",[cq]:f},{[cs]:[{[ct]:i,[cu]:cf,[cw]:x}],[cr2]:[{[cs]:bY,[cr2]:[ba,{[cs]:cj,[cr2]:[{[cs]:bI,[cr2]:[{[cs]:ck,[cr2]:[{[cs]:cl,[cr2]:[{[cs]:cm,[cr2]:[{[cs]:[{[ct]:i,[cu]:ci,[cw]:O}],[cr2]:[{[cs]:[{[ct]:i,[cu]:[aT,"resourceId[3]"],[cw]:L3}],[cr2]:[{[cs]:[{[ct]:h,[cu]:[{[cv]:O},K]}],[cr2]:[{[cs]:bE,endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}",[cy]:bl,[cE]:am},[cq]:n2},{endpoint:{[cx]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cy]:bl,[cE]:am},[cq]:n2}],[cq]:o},{error:"Expected an outpost type `accesspoint`, found {outpostType}",[cq]:f}],[cq]:o},{error:"Invalid ARN: expected an access point name",[cq]:f}],[cq]:o},{error:"Invalid ARN: Expected a 4-component resource",[cq]:f}],[cq]:o},bf],[cq]:o},bg],[cq]:o},bh],[cq]:o}],[cq]:o}],[cq]:o},{error:"Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`",[cq]:f}],[cq]:o},{error:"Invalid ARN: The Outpost Id was not set",[cq]:f}],[cq]:o},{error:"Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})",[cq]:f}],[cq]:o},{error:"Invalid ARN: No ARN type specified",[cq]:f}],[cq]:o},{[cs]:[{[ct]:k,[cu]:[ad,0,4,!1],[cw]:P2},{[ct]:h,[cu]:[{[cv]:P2},"arn:"]},{[ct]:r3,[cu]:[{[ct]:d3,[cu]:[bm]}]}],error:"Invalid ARN: `{Bucket}` was not a valid ARN",[cq]:f},{[cs]:[{[ct]:e2,[cu]:[ay,c]},bm],error:"Path-style addressing cannot be used with ARN buckets",[cq]:f},{[cs]:bG,[cr2]:[{[cs]:bI,[cr2]:[{[cs]:[az],[cr2]:[{[cs]:[Y,ar,X,aA],endpoint:{[cx]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[Y,ar,X,aC,aD],[cr2]:[{endpoint:bn,[cq]:n2}],[cq]:o},{[cs]:[Y,ar,X,aC,aG],endpoint:bn,[cq]:n2},{[cs]:[aH,ar,X,aA],endpoint:{[cx]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,ar,X,aC,aD],[cr2]:[{endpoint:bo,[cq]:n2}],[cq]:o},{[cs]:[aH,ar,X,aC,aG],endpoint:bo,[cq]:n2},{[cs]:[Y,ar,aJ,aA],endpoint:{[cx]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[Y,ar,aJ,aC,aD],[cr2]:[{endpoint:bp,[cq]:n2}],[cq]:o},{[cs]:[Y,ar,aJ,aC,aG],endpoint:bp,[cq]:n2},{[cs]:[aH,Z,ah,aJ,aA],endpoint:{[cx]:Q,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,Z,ah,aJ,aC,aD],[cr2]:[{[cs]:cc,endpoint:bq,[cq]:n2},{endpoint:bq,[cq]:n2}],[cq]:o},{[cs]:[aH,Z,ah,aJ,aC,aG],endpoint:bq,[cq]:n2},{[cs]:[aH,ar,aJ,aA],endpoint:{[cx]:R,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aH,ar,aJ,aC,aD],[cr2]:[{[cs]:cc,endpoint:{[cx]:R,[cy]:aF,[cE]:am},[cq]:n2},{endpoint:br,[cq]:n2}],[cq]:o},{[cs]:[aH,ar,aJ,aC,aG],endpoint:br,[cq]:n2}],[cq]:o},{error:"Path-style addressing cannot be used with S3 Accelerate",[cq]:f}],[cq]:o}],[cq]:o}],[cq]:o},{[cs]:[{[ct]:d3,[cu]:[bs]},{[ct]:e2,[cu]:[bs,c]}],[cr2]:[{[cs]:bI,[cr2]:[{[cs]:co,[cr2]:[aX,aY,{[cs]:bE,endpoint:{[cx]:t2,[cy]:bt,[cE]:am},[cq]:n2},{[cs]:bJ,endpoint:{[cx]:"https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}",[cy]:bt,[cE]:am},[cq]:n2},{endpoint:{[cx]:"https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}",[cy]:bt,[cE]:am},[cq]:n2}],[cq]:o},aS],[cq]:o}],[cq]:o},{[cs]:[at],[cr2]:[{[cs]:bI,[cr2]:[{[cs]:co,[cr2]:[{[cs]:[X,Y,ar,aA],endpoint:{[cx]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[X,Y,ar,aC,aD],[cr2]:[{endpoint:bu,[cq]:n2}],[cq]:o},{[cs]:[X,Y,ar,aC,aG],endpoint:bu,[cq]:n2},{[cs]:[X,aH,ar,aA],endpoint:{[cx]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[X,aH,ar,aC,aD],[cr2]:[{endpoint:bv,[cq]:n2}],[cq]:o},{[cs]:[X,aH,ar,aC,aG],endpoint:bv,[cq]:n2},{[cs]:[aJ,Y,ar,aA],endpoint:{[cx]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aJ,Y,ar,aC,aD],[cr2]:[{endpoint:bw,[cq]:n2}],[cq]:o},{[cs]:[aJ,Y,ar,aC,aG],endpoint:bw,[cq]:n2},{[cs]:[aJ,aH,Z,ah,aA],endpoint:{[cx]:t2,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aJ,aH,Z,ah,aC,aD],[cr2]:[{[cs]:cc,endpoint:bx,[cq]:n2},{endpoint:bx,[cq]:n2}],[cq]:o},{[cs]:[aJ,aH,Z,ah,aC,aG],endpoint:bx,[cq]:n2},{[cs]:[aJ,aH,ar,aA],endpoint:{[cx]:S,[cy]:aB,[cE]:am},[cq]:n2},{[cs]:[aJ,aH,ar,aC,aD],[cr2]:[{[cs]:cc,endpoint:{[cx]:S,[cy]:aF,[cE]:am},[cq]:n2},{endpoint:by,[cq]:n2}],[cq]:o},{[cs]:[aJ,aH,ar,aC,aG],endpoint:by,[cq]:n2}],[cq]:o},aS],[cq]:o}],[cq]:o}],[cq]:o},{error:"A region must be set when sending requests to S3.",[cq]:f}]};cache=new EndpointCache({size:50,params:["Accelerate","Bucket","DisableAccessPoints","DisableMultiRegionAccessPoints","DisableS3ExpressSessionAuth","Endpoint","ForcePathStyle","Region","UseArnRegion","UseDualStack","UseFIPS","UseGlobalEndpoint","UseObjectLambdaEndpoint","UseS3ExpressControlEndpoint"]});defaultEndpointResolver=(endpointParams,context2={})=>cache.get(endpointParams,(()=>resolveEndpoint(ruleSet,{endpointParams,logger:context2.logger})));customEndpointFunctions.aws=awsEndpointFunctions;defaultS3HttpAuthSchemeParametersProvider=(defaultHttpAuthSchemeParametersProvider=>async(config,context2,input)=>{var _a8,_b5,_c3;if(!input)throw new Error("Could not find `input` for `defaultEndpointRuleSetHttpAuthSchemeParametersProvider`");const defaultParameters=await defaultHttpAuthSchemeParametersProvider(config,context2),instructionsFn=null==(_c3=null==(_b5=null==(_a8=getSmithyContext2(context2))?void 0:_a8.commandInstance)?void 0:_b5.constructor)?void 0:_c3.getEndpointParameterInstructions;if(!instructionsFn)throw new Error(`getEndpointParameterInstructions() is not defined on \`${context2.commandName}\``);const endpointParameters=await resolveParams(input,{getEndpointParameterInstructions:instructionsFn},config);return Object.assign(defaultParameters,endpointParameters)})((async(config,context2,input)=>({operation:getSmithyContext2(context2).operation,region:await normalizeProvider(config.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()})));defaultS3HttpAuthSchemeProvider=((defaultEndpointResolver2,defaultHttpAuthSchemeResolver,createHttpAuthOptionFunctions)=>authParameters=>{var _a8;const authSchemes=null==(_a8=defaultEndpointResolver2(authParameters).properties)?void 0:_a8.authSchemes;if(!authSchemes)return defaultHttpAuthSchemeResolver(authParameters);const options=[];for(const scheme of authSchemes){const{name:resolvedName,properties={},...rest}=scheme,name=resolvedName.toLowerCase();resolvedName!==name&&console.warn(`HttpAuthScheme has been normalized with lowercasing: \`${resolvedName}\` to \`${name}\``);let schemeId;if("sigv4a"===name){schemeId="aws.auth#sigv4a";if(authSchemes.find((s2=>{const name2=s2.name.toLowerCase();return"sigv4a"!==name2&&name2.startsWith("sigv4")})))continue}else{if(!name.startsWith("sigv4"))throw new Error(`Unknown HttpAuthScheme found in \`@smithy.rules#endpointRuleSet\`: \`${name}\``);schemeId="aws.auth#sigv4"}const createOption=createHttpAuthOptionFunctions[schemeId];if(!createOption)throw new Error(`Could not find HttpAuthOption create function for \`${schemeId}\``);const option=createOption(authParameters);option.schemeId=schemeId;option.signingProperties={...option.signingProperties||{},...rest,...properties};options.push(option)}return options})(defaultEndpointResolver,(authParameters=>{const options=[];switch(authParameters.operation){default:options.push(createAwsAuthSigv4HttpAuthOption(authParameters));options.push(createAwsAuthSigv4aHttpAuthOption(authParameters))}return options}),{"aws.auth#sigv4":createAwsAuthSigv4HttpAuthOption,"aws.auth#sigv4a":createAwsAuthSigv4aHttpAuthOption});resolveHttpAuthSchemeConfig=config=>{var _a8;const config_0=resolveAwsSdkSigV4Config(config),config_1=resolveAwsSdkSigV4AConfig(config_0);return Object.assign(config_1,{authSchemePreference:normalizeProvider(null!=(_a8=config.authSchemePreference)?_a8:[])})};resolveClientEndpointParameters=options=>{var _a8,_b5,_c3,_d2,_e2,_f;return Object.assign(options,{useFipsEndpoint:null!=(_a8=options.useFipsEndpoint)&&_a8,useDualstackEndpoint:null!=(_b5=options.useDualstackEndpoint)&&_b5,forcePathStyle:null!=(_c3=options.forcePathStyle)&&_c3,useAccelerateEndpoint:null!=(_d2=options.useAccelerateEndpoint)&&_d2,useGlobalEndpoint:null!=(_e2=options.useGlobalEndpoint)&&_e2,disableMultiregionAccessPoints:null!=(_f=options.disableMultiregionAccessPoints)&&_f,defaultSigningName:"s3"})};commonParams={ForcePathStyle:{type:"clientContextParams",name:"forcePathStyle"},UseArnRegion:{type:"clientContextParams",name:"useArnRegion"},DisableMultiRegionAccessPoints:{type:"clientContextParams",name:"disableMultiregionAccessPoints"},Accelerate:{type:"clientContextParams",name:"useAccelerateEndpoint"},DisableS3ExpressSessionAuth:{type:"clientContextParams",name:"disableS3ExpressSessionAuth"},UseGlobalEndpoint:{type:"builtInParams",name:"useGlobalEndpoint"},UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}};S3ServiceException=class _S3ServiceException extends ServiceException{constructor(options){super(options);Object.setPrototypeOf(this,_S3ServiceException.prototype)}};NoSuchUpload=class _NoSuchUpload extends S3ServiceException{constructor(opts){super({name:"NoSuchUpload",$fault:"client",...opts});__publicField(this,"name","NoSuchUpload");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_NoSuchUpload.prototype)}};ObjectNotInActiveTierError=class _ObjectNotInActiveTierError extends S3ServiceException{constructor(opts){super({name:"ObjectNotInActiveTierError",$fault:"client",...opts});__publicField(this,"name","ObjectNotInActiveTierError");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_ObjectNotInActiveTierError.prototype)}};BucketAlreadyExists=class _BucketAlreadyExists extends S3ServiceException{constructor(opts){super({name:"BucketAlreadyExists",$fault:"client",...opts});__publicField(this,"name","BucketAlreadyExists");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_BucketAlreadyExists.prototype)}};BucketAlreadyOwnedByYou=class _BucketAlreadyOwnedByYou extends S3ServiceException{constructor(opts){super({name:"BucketAlreadyOwnedByYou",$fault:"client",...opts});__publicField(this,"name","BucketAlreadyOwnedByYou");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_BucketAlreadyOwnedByYou.prototype)}};NoSuchBucket=class _NoSuchBucket extends S3ServiceException{constructor(opts){super({name:"NoSuchBucket",$fault:"client",...opts});__publicField(this,"name","NoSuchBucket");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_NoSuchBucket.prototype)}};(function(){(AnalyticsFilter||(AnalyticsFilter={})).visit=(value,visitor)=>void 0!==value.Prefix?visitor.Prefix(value.Prefix):void 0!==value.Tag?visitor.Tag(value.Tag):void 0!==value.And?visitor.And(value.And):visitor._(value.$unknown[0],value.$unknown[1])})();(function(){(MetricsFilter||(MetricsFilter={})).visit=(value,visitor)=>void 0!==value.Prefix?visitor.Prefix(value.Prefix):void 0!==value.Tag?visitor.Tag(value.Tag):void 0!==value.AccessPointArn?visitor.AccessPointArn(value.AccessPointArn):void 0!==value.And?visitor.And(value.And):visitor._(value.$unknown[0],value.$unknown[1])})();InvalidObjectState=class _InvalidObjectState extends S3ServiceException{constructor(opts){super({name:"InvalidObjectState",$fault:"client",...opts});__publicField(this,"name","InvalidObjectState");__publicField(this,"$fault","client");__publicField(this,"StorageClass");__publicField(this,"AccessTier");Object.setPrototypeOf(this,_InvalidObjectState.prototype);this.StorageClass=opts.StorageClass;this.AccessTier=opts.AccessTier}};NoSuchKey=class _NoSuchKey extends S3ServiceException{constructor(opts){super({name:"NoSuchKey",$fault:"client",...opts});__publicField(this,"name","NoSuchKey");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_NoSuchKey.prototype)}};NotFound=class _NotFound extends S3ServiceException{constructor(opts){super({name:"NotFound",$fault:"client",...opts});__publicField(this,"name","NotFound");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_NotFound.prototype)}};CompleteMultipartUploadOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING}});CompleteMultipartUploadRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});CopyObjectOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING}});CopyObjectRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING},...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING},...obj.CopySourceSSECustomerKey&&{CopySourceSSECustomerKey:SENSITIVE_STRING}});CreateMultipartUploadOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING}});CreateMultipartUploadRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING},...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING}});SessionCredentialsFilterSensitiveLog=obj=>({...obj,...obj.SecretAccessKey&&{SecretAccessKey:SENSITIVE_STRING},...obj.SessionToken&&{SessionToken:SENSITIVE_STRING}});CreateSessionOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING},...obj.Credentials&&{Credentials:SessionCredentialsFilterSensitiveLog(obj.Credentials)}});CreateSessionRequestFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING}});ServerSideEncryptionByDefaultFilterSensitiveLog=obj=>({...obj,...obj.KMSMasterKeyID&&{KMSMasterKeyID:SENSITIVE_STRING}});ServerSideEncryptionRuleFilterSensitiveLog=obj=>({...obj,...obj.ApplyServerSideEncryptionByDefault&&{ApplyServerSideEncryptionByDefault:ServerSideEncryptionByDefaultFilterSensitiveLog(obj.ApplyServerSideEncryptionByDefault)}});ServerSideEncryptionConfigurationFilterSensitiveLog=obj=>({...obj,...obj.Rules&&{Rules:obj.Rules.map((item=>ServerSideEncryptionRuleFilterSensitiveLog(item)))}});GetBucketEncryptionOutputFilterSensitiveLog=obj=>({...obj,...obj.ServerSideEncryptionConfiguration&&{ServerSideEncryptionConfiguration:ServerSideEncryptionConfigurationFilterSensitiveLog(obj.ServerSideEncryptionConfiguration)}});SSEKMSFilterSensitiveLog=obj=>({...obj,...obj.KeyId&&{KeyId:SENSITIVE_STRING}});InventoryEncryptionFilterSensitiveLog=obj=>({...obj,...obj.SSEKMS&&{SSEKMS:SSEKMSFilterSensitiveLog(obj.SSEKMS)}});InventoryS3BucketDestinationFilterSensitiveLog=obj=>({...obj,...obj.Encryption&&{Encryption:InventoryEncryptionFilterSensitiveLog(obj.Encryption)}});InventoryDestinationFilterSensitiveLog=obj=>({...obj,...obj.S3BucketDestination&&{S3BucketDestination:InventoryS3BucketDestinationFilterSensitiveLog(obj.S3BucketDestination)}});InventoryConfigurationFilterSensitiveLog=obj=>({...obj,...obj.Destination&&{Destination:InventoryDestinationFilterSensitiveLog(obj.Destination)}});GetBucketInventoryConfigurationOutputFilterSensitiveLog=obj=>({...obj,...obj.InventoryConfiguration&&{InventoryConfiguration:InventoryConfigurationFilterSensitiveLog(obj.InventoryConfiguration)}});GetObjectOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING}});GetObjectRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});GetObjectAttributesRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});GetObjectTorrentOutputFilterSensitiveLog=obj=>({...obj});HeadObjectOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING}});HeadObjectRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});ListBucketInventoryConfigurationsOutputFilterSensitiveLog=obj=>({...obj,...obj.InventoryConfigurationList&&{InventoryConfigurationList:obj.InventoryConfigurationList.map((item=>InventoryConfigurationFilterSensitiveLog(item)))}});ListPartsRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});XmlText=class{constructor(value){__publicField(this,"value");this.value=value}toString(){return escapeElement(""+this.value)}};XmlNode=class _XmlNode{constructor(name,children=[]){__publicField(this,"name");__publicField(this,"children");__publicField(this,"attributes",{});this.name=name;this.children=children}static of(name,childText,withName){const node=new _XmlNode(name);void 0!==childText&&node.addChildNode(new XmlText(childText));void 0!==withName&&node.withName(withName);return node}withName(name){this.name=name;return this}addAttribute(name,value){this.attributes[name]=value;return this}addChildNode(child2){this.children.push(child2);return this}removeAttribute(name){delete this.attributes[name];return this}n(name){this.name=name;return this}c(child2){this.children.push(child2);return this}a(name,value){null!=value&&(this.attributes[name]=value);return this}cc(input,field,withName=field){if(null!=input[field]){const node=_XmlNode.of(field,input[field]).withName(withName);this.c(node)}}l(input,listName,memberName,valueProvider){null!=input[listName]&&valueProvider().map((node=>{node.withName(memberName);this.c(node)}))}lc(input,listName,memberName,valueProvider){if(null!=input[listName]){const nodes=valueProvider(),containerNode=new _XmlNode(memberName);nodes.map((node=>{containerNode.c(node)}));this.c(containerNode)}}toString(){const hasChildren=Boolean(this.children.length);let xmlText=`<${this.name}`;const attributes=this.attributes;for(const attributeName of Object.keys(attributes)){const attribute=attributes[attributeName];null!=attribute&&(xmlText+=` ${attributeName}="${escapeAttribute(""+attribute)}"`)}return xmlText+(hasChildren?`>${this.children.map((c3=>c3.toString())).join("")}</${this.name}>`:"/>")}};EncryptionTypeMismatch=class _EncryptionTypeMismatch extends S3ServiceException{constructor(opts){super({name:"EncryptionTypeMismatch",$fault:"client",...opts});__publicField(this,"name","EncryptionTypeMismatch");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_EncryptionTypeMismatch.prototype)}};InvalidRequest=class _InvalidRequest extends S3ServiceException{constructor(opts){super({name:"InvalidRequest",$fault:"client",...opts});__publicField(this,"name","InvalidRequest");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_InvalidRequest.prototype)}};InvalidWriteOffset=class _InvalidWriteOffset extends S3ServiceException{constructor(opts){super({name:"InvalidWriteOffset",$fault:"client",...opts});__publicField(this,"name","InvalidWriteOffset");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_InvalidWriteOffset.prototype)}};TooManyParts=class _TooManyParts extends S3ServiceException{constructor(opts){super({name:"TooManyParts",$fault:"client",...opts});__publicField(this,"name","TooManyParts");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_TooManyParts.prototype)}};ObjectAlreadyInActiveTierError=class _ObjectAlreadyInActiveTierError extends S3ServiceException{constructor(opts){super({name:"ObjectAlreadyInActiveTierError",$fault:"client",...opts});__publicField(this,"name","ObjectAlreadyInActiveTierError");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_ObjectAlreadyInActiveTierError.prototype)}};(function(){(SelectObjectContentEventStream||(SelectObjectContentEventStream={})).visit=(value,visitor)=>void 0!==value.Records?visitor.Records(value.Records):void 0!==value.Stats?visitor.Stats(value.Stats):void 0!==value.Progress?visitor.Progress(value.Progress):void 0!==value.Cont?visitor.Cont(value.Cont):void 0!==value.End?visitor.End(value.End):visitor._(value.$unknown[0],value.$unknown[1])})();PutBucketEncryptionRequestFilterSensitiveLog=obj=>({...obj,...obj.ServerSideEncryptionConfiguration&&{ServerSideEncryptionConfiguration:ServerSideEncryptionConfigurationFilterSensitiveLog(obj.ServerSideEncryptionConfiguration)}});PutBucketInventoryConfigurationRequestFilterSensitiveLog=obj=>({...obj,...obj.InventoryConfiguration&&{InventoryConfiguration:InventoryConfigurationFilterSensitiveLog(obj.InventoryConfiguration)}});PutObjectOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING}});PutObjectRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING},...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING},...obj.SSEKMSEncryptionContext&&{SSEKMSEncryptionContext:SENSITIVE_STRING}});EncryptionFilterSensitiveLog=obj=>({...obj,...obj.KMSKeyId&&{KMSKeyId:SENSITIVE_STRING}});S3LocationFilterSensitiveLog=obj=>({...obj,...obj.Encryption&&{Encryption:EncryptionFilterSensitiveLog(obj.Encryption)}});OutputLocationFilterSensitiveLog=obj=>({...obj,...obj.S3&&{S3:S3LocationFilterSensitiveLog(obj.S3)}});RestoreRequestFilterSensitiveLog=obj=>({...obj,...obj.OutputLocation&&{OutputLocation:OutputLocationFilterSensitiveLog(obj.OutputLocation)}});RestoreObjectRequestFilterSensitiveLog=obj=>({...obj,...obj.RestoreRequest&&{RestoreRequest:RestoreRequestFilterSensitiveLog(obj.RestoreRequest)}});SelectObjectContentOutputFilterSensitiveLog=obj=>({...obj,...obj.Payload&&{Payload:"STREAMING_CONTENT"}});SelectObjectContentRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});UploadPartOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING}});UploadPartRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING}});UploadPartCopyOutputFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING}});UploadPartCopyRequestFilterSensitiveLog=obj=>({...obj,...obj.SSECustomerKey&&{SSECustomerKey:SENSITIVE_STRING},...obj.CopySourceSSECustomerKey&&{CopySourceSSECustomerKey:SENSITIVE_STRING}});WriteGetObjectResponseRequestFilterSensitiveLog=obj=>({...obj,...obj.SSEKMSKeyId&&{SSEKMSKeyId:SENSITIVE_STRING}});se_AbortMultipartUploadCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xaimit]:[()=>isSerializableHeaderValue(input[_IMIT]),()=>dateToUtcString(input[_IMIT]).toString()]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"AbortMultipartUpload"],[_uI]:[,expectNonNull(input[_UI],"UploadId")]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_CompleteMultipartUploadCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xacc]:input[_CCRC],[_xacc_]:input[_CCRCC],[_xacc__]:input[_CCRCNVME],[_xacs]:input[_CSHA],[_xacs_]:input[_CSHAh],[_xact]:input[_CT],[_xamos]:[()=>isSerializableHeaderValue(input[_MOS]),()=>input[_MOS].toString()],[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_im]:input[_IM],[_inm]:input[_INM],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_uI]:[,expectNonNull(input[_UI],"UploadId")]});let body,contents;if(void 0!==input.MultipartUpload){contents=se_CompletedMultipartUpload(input.MultipartUpload,context2);contents=contents.n("CompleteMultipartUpload");body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("POST").h(headers).q(query3).b(body);return b3.build()};se_CopyObjectCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{...void 0!==input.Metadata&&Object.keys(input.Metadata).reduce(((acc,suffix)=>{acc[`x-amz-meta-${suffix.toLowerCase()}`]=input.Metadata[suffix];return acc}),{}),[_xaa]:input[_ACL],[_cc]:input[_CC],[_xaca]:input[_CA],[_cd]:input[_CD],[_ce]:input[_CE],[_cl]:input[_CL],[_ct]:input[_CTo],[_xacs__]:input[_CS],[_xacsim]:input[_CSIM],[_xacsims]:[()=>isSerializableHeaderValue(input[_CSIMS]),()=>dateToUtcString(input[_CSIMS]).toString()],[_xacsinm]:input[_CSINM],[_xacsius]:[()=>isSerializableHeaderValue(input[_CSIUS]),()=>dateToUtcString(input[_CSIUS]).toString()],[_e]:[()=>isSerializableHeaderValue(input[_E]),()=>dateToUtcString(input[_E]).toString()],[_xagfc]:input[_GFC],[_xagr]:input[_GR],[_xagra]:input[_GRACP],[_xagwa]:input[_GWACP],[_xamd]:input[_MD],[_xatd]:input[_TD],[_xasse]:input[_SSE],[_xasc]:input[_SC],[_xawrl]:input[_WRL],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xasseakki]:input[_SSEKMSKI],[_xassec]:input[_SSEKMSEC],[_xassebke]:[()=>isSerializableHeaderValue(input[_BKE]),()=>input[_BKE].toString()],[_xacssseca]:input[_CSSSECA],[_xacssseck]:input[_CSSSECK],[_xacssseckm]:input[_CSSSECKMD],[_xarp]:input[_RP],[_xat]:input[_T],[_xaolm]:input[_OLM],[_xaolrud]:[()=>isSerializableHeaderValue(input[_OLRUD]),()=>serializeDateTime(input[_OLRUD]).toString()],[_xaollh]:input[_OLLHS],[_xaebo]:input[_EBO],[_xasebo]:input[_ESBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"CopyObject"]});b3.m("PUT").h(headers).q(query3).b(void 0);return b3.build()};se_CreateBucketCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaa]:input[_ACL],[_xagfc]:input[_GFC],[_xagr]:input[_GR],[_xagra]:input[_GRACP],[_xagw]:input[_GW],[_xagwa]:input[_GWACP],[_xabole]:[()=>isSerializableHeaderValue(input[_OLEFB]),()=>input[_OLEFB].toString()],[_xaoo]:input[_OO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);let body,contents;if(void 0!==input.CreateBucketConfiguration){contents=se_CreateBucketConfiguration(input.CreateBucketConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).b(body);return b3.build()};se_CreateBucketMetadataTableConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_mT]:[,""]});let body,contents;if(void 0!==input.MetadataTableConfiguration){contents=se_MetadataTableConfiguration(input.MetadataTableConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("POST").h(headers).q(query3).b(body);return b3.build()};se_CreateMultipartUploadCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{...void 0!==input.Metadata&&Object.keys(input.Metadata).reduce(((acc,suffix)=>{acc[`x-amz-meta-${suffix.toLowerCase()}`]=input.Metadata[suffix];return acc}),{}),[_xaa]:input[_ACL],[_cc]:input[_CC],[_cd]:input[_CD],[_ce]:input[_CE],[_cl]:input[_CL],[_ct]:input[_CTo],[_e]:[()=>isSerializableHeaderValue(input[_E]),()=>dateToUtcString(input[_E]).toString()],[_xagfc]:input[_GFC],[_xagr]:input[_GR],[_xagra]:input[_GRACP],[_xagwa]:input[_GWACP],[_xasse]:input[_SSE],[_xasc]:input[_SC],[_xawrl]:input[_WRL],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xasseakki]:input[_SSEKMSKI],[_xassec]:input[_SSEKMSEC],[_xassebke]:[()=>isSerializableHeaderValue(input[_BKE]),()=>input[_BKE].toString()],[_xarp]:input[_RP],[_xat]:input[_T],[_xaolm]:input[_OLM],[_xaolrud]:[()=>isSerializableHeaderValue(input[_OLRUD]),()=>serializeDateTime(input[_OLRUD]).toString()],[_xaollh]:input[_OLLHS],[_xaebo]:input[_EBO],[_xaca]:input[_CA],[_xact]:input[_CT]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_u]:[,""]});b3.m("POST").h(headers).q(query3).b(void 0);return b3.build()};se_CreateSessionCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xacsm]:input[_SM],[_xasse]:input[_SSE],[_xasseakki]:input[_SSEKMSKI],[_xassec]:input[_SSEKMSEC],[_xassebke]:[()=>isSerializableHeaderValue(input[_BKE]),()=>input[_BKE].toString()]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_s]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.m("DELETE").h(headers).b(void 0);return b3.build()};se_DeleteBucketAnalyticsConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_a5]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketCorsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_c2]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketEncryptionCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_en]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketIntelligentTieringConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2);b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_it]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("DELETE").h({}).q(query3).b(void 0);return b3.build()};se_DeleteBucketInventoryConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_in]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketLifecycleCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_l]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketMetadataTableConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_mT]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketMetricsConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_m]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketOwnershipControlsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_oC]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketPolicyCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_p]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketReplicationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_r]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketTaggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_t]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteBucketWebsiteCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_w]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteObjectCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xam]:input[_MFA],[_xarp]:input[_RP],[_xabgr]:[()=>isSerializableHeaderValue(input[_BGR]),()=>input[_BGR].toString()],[_xaebo]:input[_EBO],[_im]:input[_IM],[_xaimlmt]:[()=>isSerializableHeaderValue(input[_IMLMT]),()=>dateToUtcString(input[_IMLMT]).toString()],[_xaims]:[()=>isSerializableHeaderValue(input[_IMS]),()=>input[_IMS].toString()]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"DeleteObject"],[_vI]:[,input[_VI]]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeleteObjectsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xam]:input[_MFA],[_xarp]:input[_RP],[_xabgr]:[()=>isSerializableHeaderValue(input[_BGR]),()=>input[_BGR].toString()],[_xaebo]:input[_EBO],[_xasca]:input[_CA]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_d]:[,""]});let body,contents;if(void 0!==input.Delete){contents=se_Delete(input.Delete,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("POST").h(headers).q(query3).b(body);return b3.build()};se_DeleteObjectTaggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_t]:[,""],[_vI]:[,input[_VI]]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_DeletePublicAccessBlockCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_pAB]:[,""]});b3.m("DELETE").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketAccelerateConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO],[_xarp]:input[_RP]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_ac]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketAclCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_acl]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketAnalyticsConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_a5]:[,""],[_xi]:[,"GetBucketAnalyticsConfiguration"],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketCorsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_c2]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketEncryptionCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_en]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketIntelligentTieringConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2);b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_it]:[,""],[_xi]:[,"GetBucketIntelligentTieringConfiguration"],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("GET").h({}).q(query3).b(void 0);return b3.build()};se_GetBucketInventoryConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_in]:[,""],[_xi]:[,"GetBucketInventoryConfiguration"],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketLifecycleConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_l]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketLocationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_lo]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketLoggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_log]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketMetadataTableConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_mT]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketMetricsConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_m]:[,""],[_xi]:[,"GetBucketMetricsConfiguration"],[_i]:[,expectNonNull(input[_I],"Id")]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketNotificationConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_n]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketOwnershipControlsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_oC]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketPolicyCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_p]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketPolicyStatusCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_pS]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketReplicationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_r]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketRequestPaymentCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_rP]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketTaggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_t]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketVersioningCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_v]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetBucketWebsiteCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_w]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_im]:input[_IM],[_ims]:[()=>isSerializableHeaderValue(input[_IMSf]),()=>dateToUtcString(input[_IMSf]).toString()],[_inm]:input[_INM],[_ius]:[()=>isSerializableHeaderValue(input[_IUS]),()=>dateToUtcString(input[_IUS]).toString()],[_ra]:input[_R],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xacm]:input[_CM]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"GetObject"],[_rcc]:[,input[_RCC]],[_rcd]:[,input[_RCD]],[_rce]:[,input[_RCE]],[_rcl]:[,input[_RCL]],[_rct]:[,input[_RCT]],[_re]:[()=>void 0!==input.ResponseExpires,()=>dateToUtcString(input[_RE]).toString()],[_vI]:[,input[_VI]],[_pN]:[()=>void 0!==input.PartNumber,()=>input[_PN].toString()]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectAclCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_acl]:[,""],[_vI]:[,input[_VI]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectAttributesCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xamp]:[()=>isSerializableHeaderValue(input[_MP]),()=>input[_MP].toString()],[_xapnm]:input[_PNM],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xaoa]:[()=>isSerializableHeaderValue(input[_OA]),()=>(input[_OA]||[]).map(quoteHeader).join(", ")]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_at]:[,""],[_vI]:[,input[_VI]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectLegalHoldCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_lh]:[,""],[_vI]:[,input[_VI]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectLockConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_ol]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectRetentionCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_ret]:[,""],[_vI]:[,input[_VI]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectTaggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO],[_xarp]:input[_RP]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_t]:[,""],[_vI]:[,input[_VI]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetObjectTorrentCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_to]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_GetPublicAccessBlockCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_pAB]:[,""]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_HeadBucketCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.m("HEAD").h(headers).b(void 0);return b3.build()};se_HeadObjectCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_im]:input[_IM],[_ims]:[()=>isSerializableHeaderValue(input[_IMSf]),()=>dateToUtcString(input[_IMSf]).toString()],[_inm]:input[_INM],[_ius]:[()=>isSerializableHeaderValue(input[_IUS]),()=>dateToUtcString(input[_IUS]).toString()],[_ra]:input[_R],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xacm]:input[_CM]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_rcc]:[,input[_RCC]],[_rcd]:[,input[_RCD]],[_rce]:[,input[_RCE]],[_rcl]:[,input[_RCL]],[_rct]:[,input[_RCT]],[_re]:[()=>void 0!==input.ResponseExpires,()=>dateToUtcString(input[_RE]).toString()],[_vI]:[,input[_VI]],[_pN]:[()=>void 0!==input.PartNumber,()=>input[_PN].toString()]});b3.m("HEAD").h(headers).q(query3).b(void 0);return b3.build()};se_ListBucketAnalyticsConfigurationsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_a5]:[,""],[_xi]:[,"ListBucketAnalyticsConfigurations"],[_ct_]:[,input[_CTon]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListBucketIntelligentTieringConfigurationsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2);b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_it]:[,""],[_xi]:[,"ListBucketIntelligentTieringConfigurations"],[_ct_]:[,input[_CTon]]});b3.m("GET").h({}).q(query3).b(void 0);return b3.build()};se_ListBucketInventoryConfigurationsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_in]:[,""],[_xi]:[,"ListBucketInventoryConfigurations"],[_ct_]:[,input[_CTon]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListBucketMetricsConfigurationsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_m]:[,""],[_xi]:[,"ListBucketMetricsConfigurations"],[_ct_]:[,input[_CTon]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListBucketsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2);b3.bp("/");const query3=map2({[_xi]:[,"ListBuckets"],[_mb]:[()=>void 0!==input.MaxBuckets,()=>input[_MB].toString()],[_ct_]:[,input[_CTon]],[_pr]:[,input[_P]],[_br]:[,input[_BR]]});b3.m("GET").h({}).q(query3).b(void 0);return b3.build()};se_ListDirectoryBucketsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2);b3.bp("/");const query3=map2({[_xi]:[,"ListDirectoryBuckets"],[_ct_]:[,input[_CTon]],[_mdb]:[()=>void 0!==input.MaxDirectoryBuckets,()=>input[_MDB].toString()]});b3.m("GET").h({}).q(query3).b(void 0);return b3.build()};se_ListMultipartUploadsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO],[_xarp]:input[_RP]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_u]:[,""],[_de]:[,input[_D]],[_et]:[,input[_ET]],[_km]:[,input[_KM]],[_mu]:[()=>void 0!==input.MaxUploads,()=>input[_MU].toString()],[_pr]:[,input[_P]],[_uim]:[,input[_UIM]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListObjectsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xaooa]:[()=>isSerializableHeaderValue(input[_OOA]),()=>(input[_OOA]||[]).map(quoteHeader).join(", ")]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_de]:[,input[_D]],[_et]:[,input[_ET]],[_ma]:[,input[_M]],[_mk]:[()=>void 0!==input.MaxKeys,()=>input[_MK].toString()],[_pr]:[,input[_P]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListObjectsV2Command=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xaooa]:[()=>isSerializableHeaderValue(input[_OOA]),()=>(input[_OOA]||[]).map(quoteHeader).join(", ")]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_lt]:[,"2"],[_de]:[,input[_D]],[_et]:[,input[_ET]],[_mk]:[()=>void 0!==input.MaxKeys,()=>input[_MK].toString()],[_pr]:[,input[_P]],[_ct_]:[,input[_CTon]],[_fo]:[()=>void 0!==input.FetchOwner,()=>input[_FO].toString()],[_sa]:[,input[_SA]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListObjectVersionsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xaebo]:input[_EBO],[_xarp]:input[_RP],[_xaooa]:[()=>isSerializableHeaderValue(input[_OOA]),()=>(input[_OOA]||[]).map(quoteHeader).join(", ")]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_ver]:[,""],[_de]:[,input[_D]],[_et]:[,input[_ET]],[_km]:[,input[_KM]],[_mk]:[()=>void 0!==input.MaxKeys,()=>input[_MK].toString()],[_pr]:[,input[_P]],[_vim]:[,input[_VIM]]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_ListPartsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"ListParts"],[_mp]:[()=>void 0!==input.MaxParts,()=>input[_MP].toString()],[_pnm]:[,input[_PNM]],[_uI]:[,expectNonNull(input[_UI],"UploadId")]});b3.m("GET").h(headers).q(query3).b(void 0);return b3.build()};se_PutBucketAccelerateConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaebo]:input[_EBO],[_xasca]:input[_CA]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_ac]:[,""]});let body,contents;if(void 0!==input.AccelerateConfiguration){contents=se_AccelerateConfiguration(input.AccelerateConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketAclCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaa]:input[_ACL],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xagfc]:input[_GFC],[_xagr]:input[_GR],[_xagra]:input[_GRACP],[_xagw]:input[_GW],[_xagwa]:input[_GWACP],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_acl]:[,""]});let body,contents;if(void 0!==input.AccessControlPolicy){contents=se_AccessControlPolicy(input.AccessControlPolicy,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketAnalyticsConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_a5]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});let body,contents;if(void 0!==input.AnalyticsConfiguration){contents=se_AnalyticsConfiguration(input.AnalyticsConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketCorsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_c2]:[,""]});let body,contents;if(void 0!==input.CORSConfiguration){contents=se_CORSConfiguration(input.CORSConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketEncryptionCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_en]:[,""]});let body,contents;if(void 0!==input.ServerSideEncryptionConfiguration){contents=se_ServerSideEncryptionConfiguration(input.ServerSideEncryptionConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketIntelligentTieringConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2);b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_it]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});let body,contents;if(void 0!==input.IntelligentTieringConfiguration){contents=se_IntelligentTieringConfiguration(input.IntelligentTieringConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h({"content-type":"application/xml"}).q(query3).b(body);return b3.build()};se_PutBucketInventoryConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_in]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});let body,contents;if(void 0!==input.InventoryConfiguration){contents=se_InventoryConfiguration(input.InventoryConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketLifecycleConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xasca]:input[_CA],[_xaebo]:input[_EBO],[_xatdmos]:input[_TDMOS]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_l]:[,""]});let body,contents;if(void 0!==input.LifecycleConfiguration){contents=se_BucketLifecycleConfiguration(input.LifecycleConfiguration,context2);contents=contents.n("LifecycleConfiguration");body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketLoggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_log]:[,""]});let body,contents;if(void 0!==input.BucketLoggingStatus){contents=se_BucketLoggingStatus(input.BucketLoggingStatus,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketMetricsConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_m]:[,""],[_i]:[,expectNonNull(input[_I],"Id")]});let body,contents;if(void 0!==input.MetricsConfiguration){contents=se_MetricsConfiguration(input.MetricsConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketNotificationConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaebo]:input[_EBO],[_xasdv]:[()=>isSerializableHeaderValue(input[_SDV]),()=>input[_SDV].toString()]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_n]:[,""]});let body,contents;if(void 0!==input.NotificationConfiguration){contents=se_NotificationConfiguration(input.NotificationConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketOwnershipControlsCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_oC]:[,""]});let body,contents;if(void 0!==input.OwnershipControls){contents=se_OwnershipControls(input.OwnershipControls,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketPolicyCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"text/plain",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xacrsba]:[()=>isSerializableHeaderValue(input[_CRSBA]),()=>input[_CRSBA].toString()],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_p]:[,""]});let body,contents;if(void 0!==input.Policy){contents=input.Policy;body=contents}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketReplicationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xabolt]:input[_To],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_r]:[,""]});let body,contents;if(void 0!==input.ReplicationConfiguration){contents=se_ReplicationConfiguration(input.ReplicationConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketRequestPaymentCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_rP]:[,""]});let body,contents;if(void 0!==input.RequestPaymentConfiguration){contents=se_RequestPaymentConfiguration(input.RequestPaymentConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketTaggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_t]:[,""]});let body,contents;if(void 0!==input.Tagging){contents=se_Tagging(input.Tagging,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketVersioningCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xam]:input[_MFA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_v]:[,""]});let body,contents;if(void 0!==input.VersioningConfiguration){contents=se_VersioningConfiguration(input.VersioningConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutBucketWebsiteCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_w]:[,""]});let body,contents;if(void 0!==input.WebsiteConfiguration){contents=se_WebsiteConfiguration(input.WebsiteConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutObjectCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{...void 0!==input.Metadata&&Object.keys(input.Metadata).reduce(((acc,suffix)=>{acc[`x-amz-meta-${suffix.toLowerCase()}`]=input.Metadata[suffix];return acc}),{}),[_ct]:input[_CTo]||"application/octet-stream",[_xaa]:input[_ACL],[_cc]:input[_CC],[_cd]:input[_CD],[_ce]:input[_CE],[_cl]:input[_CL],[_cl_]:[()=>isSerializableHeaderValue(input[_CLo]),()=>input[_CLo].toString()],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xacc]:input[_CCRC],[_xacc_]:input[_CCRCC],[_xacc__]:input[_CCRCNVME],[_xacs]:input[_CSHA],[_xacs_]:input[_CSHAh],[_e]:[()=>isSerializableHeaderValue(input[_E]),()=>dateToUtcString(input[_E]).toString()],[_im]:input[_IM],[_inm]:input[_INM],[_xagfc]:input[_GFC],[_xagr]:input[_GR],[_xagra]:input[_GRACP],[_xagwa]:input[_GWACP],[_xawob]:[()=>isSerializableHeaderValue(input[_WOB]),()=>input[_WOB].toString()],[_xasse]:input[_SSE],[_xasc]:input[_SC],[_xawrl]:input[_WRL],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xasseakki]:input[_SSEKMSKI],[_xassec]:input[_SSEKMSEC],[_xassebke]:[()=>isSerializableHeaderValue(input[_BKE]),()=>input[_BKE].toString()],[_xarp]:input[_RP],[_xat]:input[_T],[_xaolm]:input[_OLM],[_xaolrud]:[()=>isSerializableHeaderValue(input[_OLRUD]),()=>serializeDateTime(input[_OLRUD]).toString()],[_xaollh]:input[_OLLHS],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"PutObject"]});let body,contents;if(void 0!==input.Body){contents=input.Body;body=contents}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutObjectAclCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xaa]:input[_ACL],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xagfc]:input[_GFC],[_xagr]:input[_GR],[_xagra]:input[_GRACP],[_xagw]:input[_GW],[_xagwa]:input[_GWACP],[_xarp]:input[_RP],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_acl]:[,""],[_vI]:[,input[_VI]]});let body,contents;if(void 0!==input.AccessControlPolicy){contents=se_AccessControlPolicy(input.AccessControlPolicy,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutObjectLegalHoldCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xarp]:input[_RP],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_lh]:[,""],[_vI]:[,input[_VI]]});let body,contents;if(void 0!==input.LegalHold){contents=se_ObjectLockLegalHold(input.LegalHold,context2);contents=contents.n("LegalHold");body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutObjectLockConfigurationCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xarp]:input[_RP],[_xabolt]:input[_To],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_ol]:[,""]});let body,contents;if(void 0!==input.ObjectLockConfiguration){contents=se_ObjectLockConfiguration(input.ObjectLockConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutObjectRetentionCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xarp]:input[_RP],[_xabgr]:[()=>isSerializableHeaderValue(input[_BGR]),()=>input[_BGR].toString()],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_ret]:[,""],[_vI]:[,input[_VI]]});let body,contents;if(void 0!==input.Retention){contents=se_ObjectLockRetention(input.Retention,context2);contents=contents.n("Retention");body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutObjectTaggingCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO],[_xarp]:input[_RP]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_t]:[,""],[_vI]:[,input[_VI]]});let body,contents;if(void 0!==input.Tagging){contents=se_Tagging(input.Tagging,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_PutPublicAccessBlockCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_cm]:input[_CMD],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);const query3=map2({[_pAB]:[,""]});let body,contents;if(void 0!==input.PublicAccessBlockConfiguration){contents=se_PublicAccessBlockConfiguration(input.PublicAccessBlockConfiguration,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_RestoreObjectCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xarp]:input[_RP],[_xasca]:input[_CA],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_res]:[,""],[_vI]:[,input[_VI]]});let body,contents;if(void 0!==input.RestoreRequest){contents=se_RestoreRequest(input.RestoreRequest,context2);body=_ve;contents.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");body+=contents.toString()}b3.m("POST").h(headers).q(query3).b(body);return b3.build()};se_SelectObjectContentCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/xml",[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_se]:[,""],[_st]:[,"2"]});let body;body=_ve;const bn2=new XmlNode(_SOCR);bn2.a("xmlns","http://s3.amazonaws.com/doc/2006-03-01/");bn2.cc(input,_Ex);bn2.cc(input,_ETx);null!=input[_IS]&&bn2.c(se_InputSerialization(input[_IS],context2).n(_IS));null!=input[_OS]&&bn2.c(se_OutputSerialization(input[_OS],context2).n(_OS));null!=input[_RPe]&&bn2.c(se_RequestProgress(input[_RPe],context2).n(_RPe));null!=input[_SR]&&bn2.c(se_ScanRange(input[_SR],context2).n(_SR));body+=bn2.toString();b3.m("POST").h(headers).q(query3).b(body);return b3.build()};se_UploadPartCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"content-type":"application/octet-stream",[_cl_]:[()=>isSerializableHeaderValue(input[_CLo]),()=>input[_CLo].toString()],[_cm]:input[_CMD],[_xasca]:input[_CA],[_xacc]:input[_CCRC],[_xacc_]:input[_CCRCC],[_xacc__]:input[_CCRCNVME],[_xacs]:input[_CSHA],[_xacs_]:input[_CSHAh],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xarp]:input[_RP],[_xaebo]:input[_EBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"UploadPart"],[_pN]:[null!=expectNonNull(input.PartNumber,"PartNumber"),()=>input[_PN].toString()],[_uI]:[,expectNonNull(input[_UI],"UploadId")]});let body,contents;if(void 0!==input.Body){contents=input.Body;body=contents}b3.m("PUT").h(headers).q(query3).b(body);return b3.build()};se_UploadPartCopyCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{[_xacs__]:input[_CS],[_xacsim]:input[_CSIM],[_xacsims]:[()=>isSerializableHeaderValue(input[_CSIMS]),()=>dateToUtcString(input[_CSIMS]).toString()],[_xacsinm]:input[_CSINM],[_xacsius]:[()=>isSerializableHeaderValue(input[_CSIUS]),()=>dateToUtcString(input[_CSIUS]).toString()],[_xacsr]:input[_CSR],[_xasseca]:input[_SSECA],[_xasseck]:input[_SSECK],[_xasseckm]:input[_SSECKMD],[_xacssseca]:input[_CSSSECA],[_xacssseck]:input[_CSSSECK],[_xacssseckm]:input[_CSSSECKMD],[_xarp]:input[_RP],[_xaebo]:input[_EBO],[_xasebo]:input[_ESBO]});b3.bp("/{Key+}");b3.p("Bucket",(()=>input.Bucket),"{Bucket}",!1);b3.p("Key",(()=>input.Key),"{Key+}",!0);const query3=map2({[_xi]:[,"UploadPartCopy"],[_pN]:[null!=expectNonNull(input.PartNumber,"PartNumber"),()=>input[_PN].toString()],[_uI]:[,expectNonNull(input[_UI],"UploadId")]});b3.m("PUT").h(headers).q(query3).b(void 0);return b3.build()};se_WriteGetObjectResponseCommand=async(input,context2)=>{const b3=requestBuilder(input,context2),headers=map2({},isSerializableHeaderValue,{"x-amz-content-sha256":"UNSIGNED-PAYLOAD",...void 0!==input.Metadata&&Object.keys(input.Metadata).reduce(((acc,suffix)=>{acc[`x-amz-meta-${suffix.toLowerCase()}`]=input.Metadata[suffix];return acc}),{}),"content-type":"application/octet-stream",[_xarr]:input[_RR],[_xart]:input[_RT],[_xafs]:[()=>isSerializableHeaderValue(input[_SCt]),()=>input[_SCt].toString()],[_xafec]:input[_EC],[_xafem]:input[_EM],[_xafhar]:input[_AR],[_xafhcc]:input[_CC],[_xafhcd]:input[_CD],[_xafhce]:input[_CE],[_xafhcl]:input[_CL],[_cl_]:[()=>isSerializableHeaderValue(input[_CLo]),()=>input[_CLo].toString()],[_xafhcr]:input[_CR],[_xafhct]:input[_CTo],[_xafhxacc]:input[_CCRC],[_xafhxacc_]:input[_CCRCC],[_xafhxacc__]:input[_CCRCNVME],[_xafhxacs]:input[_CSHA],[_xafhxacs_]:input[_CSHAh],[_xafhxadm]:[()=>isSerializableHeaderValue(input[_DM]),()=>input[_DM].toString()],[_xafhe]:input[_ETa],[_xafhe_]:[()=>isSerializableHeaderValue(input[_E]),()=>dateToUtcString(input[_E]).toString()],[_xafhxae]:input[_Exp],[_xafhlm]:[()=>isSerializableHeaderValue(input[_LM]),()=>dateToUtcString(input[_LM]).toString()],[_xafhxamm]:[()=>isSerializableHeaderValue(input[_MM]),()=>input[_MM].toString()],[_xafhxaolm]:input[_OLM],[_xafhxaollh]:input[_OLLHS],[_xafhxaolrud]:[()=>isSerializableHeaderValue(input[_OLRUD]),()=>serializeDateTime(input[_OLRUD]).toString()],[_xafhxampc]:[()=>isSerializableHeaderValue(input[_PC]),()=>input[_PC].toString()],[_xafhxars]:input[_RS],[_xafhxarc]:input[_RC],[_xafhxar]:input[_Re],[_xafhxasse]:input[_SSE],[_xafhxasseca]:input[_SSECA],[_xafhxasseakki]:input[_SSEKMSKI],[_xafhxasseckm]:input[_SSECKMD],[_xafhxasc]:input[_SC],[_xafhxatc]:[()=>isSerializableHeaderValue(input[_TC]),()=>input[_TC].toString()],[_xafhxavi]:input[_VI],[_xafhxassebke]:[()=>isSerializableHeaderValue(input[_BKE]),()=>input[_BKE].toString()]});b3.bp("/WriteGetObjectResponse");let body,contents;if(void 0!==input.Body){contents=input.Body;body=contents}let{hostname:resolvedHostname}=await context2.endpoint();if(!0!==context2.disableHostPrefix){resolvedHostname="{RequestRoute}."+resolvedHostname;if(void 0===input.RequestRoute)throw new Error("Empty value provided for input host prefix: RequestRoute.");resolvedHostname=resolvedHostname.replace("{RequestRoute}",input.RequestRoute);if(!isValidHostname(resolvedHostname))throw new Error("ValidationError: prefixed hostname must be hostname compatible.")}b3.hn(resolvedHostname);b3.m("POST").h(headers).b(body);return b3.build()};de_AbortMultipartUploadCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_CompleteMultipartUploadCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_Exp]:[,output.headers[_xae]],[_SSE]:[,output.headers[_xasse]],[_VI]:[,output.headers[_xavi]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_B]&&(contents[_B]=expectString(data[_B]));null!=data[_CCRC]&&(contents[_CCRC]=expectString(data[_CCRC]));null!=data[_CCRCC]&&(contents[_CCRCC]=expectString(data[_CCRCC]));null!=data[_CCRCNVME]&&(contents[_CCRCNVME]=expectString(data[_CCRCNVME]));null!=data[_CSHA]&&(contents[_CSHA]=expectString(data[_CSHA]));null!=data[_CSHAh]&&(contents[_CSHAh]=expectString(data[_CSHAh]));null!=data[_CT]&&(contents[_CT]=expectString(data[_CT]));null!=data[_ETa]&&(contents[_ETa]=expectString(data[_ETa]));null!=data[_K]&&(contents[_K]=expectString(data[_K]));null!=data[_L]&&(contents[_L]=expectString(data[_L]));return contents};de_CopyObjectCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_Exp]:[,output.headers[_xae]],[_CSVI]:[,output.headers[_xacsvi]],[_VI]:[,output.headers[_xavi]],[_SSE]:[,output.headers[_xasse]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_SSEKMSEC]:[,output.headers[_xassec]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_RC]:[,output.headers[_xarc]]}),data=expectObject(await parseXmlBody(output.body,context2));contents.CopyObjectResult=de_CopyObjectResult(data,context2);return contents};de_CreateBucketCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_L]:[,output.headers[_lo]]});await collectBody(output.body,context2);return contents};de_CreateBucketMetadataTableConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_CreateMultipartUploadCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_AD]:[()=>void 0!==output.headers[_xaad],()=>expectNonNull(parseRfc7231DateTime(output.headers[_xaad]))],[_ARI]:[,output.headers[_xaari]],[_SSE]:[,output.headers[_xasse]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_SSEKMSEC]:[,output.headers[_xassec]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_RC]:[,output.headers[_xarc]],[_CA]:[,output.headers[_xaca]],[_CT]:[,output.headers[_xact]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_B]&&(contents[_B]=expectString(data[_B]));null!=data[_K]&&(contents[_K]=expectString(data[_K]));null!=data[_UI]&&(contents[_UI]=expectString(data[_UI]));return contents};de_CreateSessionCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_SSE]:[,output.headers[_xasse]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_SSEKMSEC]:[,output.headers[_xassec]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_C]&&(contents[_C]=de_SessionCredentials(data[_C],context2));return contents};de_DeleteBucketCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketAnalyticsConfigurationCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketCorsCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketEncryptionCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketIntelligentTieringConfigurationCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketInventoryConfigurationCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketLifecycleCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketMetadataTableConfigurationCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketMetricsConfigurationCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketOwnershipControlsCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketPolicyCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketReplicationCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketTaggingCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteBucketWebsiteCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_DeleteObjectCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_DM]:[()=>void 0!==output.headers[_xadm],()=>parseBoolean(output.headers[_xadm])],[_VI]:[,output.headers[_xavi]],[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_DeleteObjectsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.Deleted?contents[_De]=[]:null!=data[_De]&&(contents[_De]=de_DeletedObjects(getArrayIfSingleItem(data[_De]),context2));""===data.Error?contents[_Err]=[]:null!=data[_Er]&&(contents[_Err]=de_Errors(getArrayIfSingleItem(data[_Er]),context2));return contents};de_DeleteObjectTaggingCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_VI]:[,output.headers[_xavi]]});await collectBody(output.body,context2);return contents};de_DeletePublicAccessBlockCommand=async(output,context2)=>{if(204!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_GetBucketAccelerateConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_S]&&(contents[_S]=expectString(data[_S]));return contents};de_GetBucketAclCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.AccessControlList?contents[_Gr]=[]:null!=data[_ACLc]&&null!=data[_ACLc][_G]&&(contents[_Gr]=de_Grants(getArrayIfSingleItem(data[_ACLc][_G]),context2));null!=data[_O]&&(contents[_O]=de_Owner(data[_O],context2));return contents};de_GetBucketAnalyticsConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.AnalyticsConfiguration=de_AnalyticsConfiguration(data,context2);return contents};de_GetBucketCorsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.CORSRule?contents[_CORSRu]=[]:null!=data[_CORSR]&&(contents[_CORSRu]=de_CORSRules(getArrayIfSingleItem(data[_CORSR]),context2));return contents};de_GetBucketEncryptionCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.ServerSideEncryptionConfiguration=de_ServerSideEncryptionConfiguration(data,context2);return contents};de_GetBucketIntelligentTieringConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.IntelligentTieringConfiguration=de_IntelligentTieringConfiguration(data,context2);return contents};de_GetBucketInventoryConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.InventoryConfiguration=de_InventoryConfiguration(data,context2);return contents};de_GetBucketLifecycleConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_TDMOS]:[,output.headers[_xatdmos]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.Rule?contents[_Rul]=[]:null!=data[_Ru]&&(contents[_Rul]=de_LifecycleRules(getArrayIfSingleItem(data[_Ru]),context2));return contents};de_GetBucketLocationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_LC]&&(contents[_LC]=expectString(data[_LC]));return contents};de_GetBucketLoggingCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_LE]&&(contents[_LE]=de_LoggingEnabled(data[_LE],context2));return contents};de_GetBucketMetadataTableConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.GetBucketMetadataTableConfigurationResult=de_GetBucketMetadataTableConfigurationResult(data,context2);return contents};de_GetBucketMetricsConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.MetricsConfiguration=de_MetricsConfiguration(data,context2);return contents};de_GetBucketNotificationConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_EBC]&&(contents[_EBC]=de_EventBridgeConfiguration(data[_EBC],context2));""===data.CloudFunctionConfiguration?contents[_LFC]=[]:null!=data[_CFC]&&(contents[_LFC]=de_LambdaFunctionConfigurationList(getArrayIfSingleItem(data[_CFC]),context2));""===data.QueueConfiguration?contents[_QCu]=[]:null!=data[_QC]&&(contents[_QCu]=de_QueueConfigurationList(getArrayIfSingleItem(data[_QC]),context2));""===data.TopicConfiguration?contents[_TCop]=[]:null!=data[_TCo]&&(contents[_TCop]=de_TopicConfigurationList(getArrayIfSingleItem(data[_TCo]),context2));return contents};de_GetBucketOwnershipControlsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.OwnershipControls=de_OwnershipControls(data,context2);return contents};de_GetBucketPolicyCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=await collectBodyString2(output.body,context2);contents.Policy=expectString(data);return contents};de_GetBucketPolicyStatusCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.PolicyStatus=de_PolicyStatus(data,context2);return contents};de_GetBucketReplicationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.ReplicationConfiguration=de_ReplicationConfiguration(data,context2);return contents};de_GetBucketRequestPaymentCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_Pa]&&(contents[_Pa]=expectString(data[_Pa]));return contents};de_GetBucketTaggingCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.TagSet?contents[_TS]=[]:null!=data[_TS]&&null!=data[_TS][_Ta]&&(contents[_TS]=de_TagSet(getArrayIfSingleItem(data[_TS][_Ta]),context2));return contents};de_GetBucketVersioningCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_MDf]&&(contents[_MFAD]=expectString(data[_MDf]));null!=data[_S]&&(contents[_S]=expectString(data[_S]));return contents};de_GetBucketWebsiteCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_ED]&&(contents[_ED]=de_ErrorDocument(data[_ED],context2));null!=data[_ID]&&(contents[_ID]=de_IndexDocument(data[_ID],context2));null!=data[_RART]&&(contents[_RART]=de_RedirectAllRequestsTo(data[_RART],context2));""===data.RoutingRules?contents[_RRo]=[]:null!=data[_RRo]&&null!=data[_RRo][_RRou]&&(contents[_RRo]=de_RoutingRules(getArrayIfSingleItem(data[_RRo][_RRou]),context2));return contents};de_GetObjectCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_DM]:[()=>void 0!==output.headers[_xadm],()=>parseBoolean(output.headers[_xadm])],[_AR]:[,output.headers[_ar]],[_Exp]:[,output.headers[_xae]],[_Re]:[,output.headers[_xar]],[_LM]:[()=>void 0!==output.headers[_lm],()=>expectNonNull(parseRfc7231DateTime(output.headers[_lm]))],[_CLo]:[()=>void 0!==output.headers[_cl_],()=>strictParseLong(output.headers[_cl_])],[_ETa]:[,output.headers[_eta]],[_CCRC]:[,output.headers[_xacc]],[_CCRCC]:[,output.headers[_xacc_]],[_CCRCNVME]:[,output.headers[_xacc__]],[_CSHA]:[,output.headers[_xacs]],[_CSHAh]:[,output.headers[_xacs_]],[_CT]:[,output.headers[_xact]],[_MM]:[()=>void 0!==output.headers[_xamm],()=>strictParseInt32(output.headers[_xamm])],[_VI]:[,output.headers[_xavi]],[_CC]:[,output.headers[_cc]],[_CD]:[,output.headers[_cd]],[_CE]:[,output.headers[_ce]],[_CL]:[,output.headers[_cl]],[_CR]:[,output.headers[_cr]],[_CTo]:[,output.headers[_ct]],[_E]:[()=>void 0!==output.headers[_e],()=>expectNonNull(parseRfc7231DateTime(output.headers[_e]))],[_ES]:[,output.headers[_ex]],[_WRL]:[,output.headers[_xawrl]],[_SSE]:[,output.headers[_xasse]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_SC]:[,output.headers[_xasc]],[_RC]:[,output.headers[_xarc]],[_RS]:[,output.headers[_xars]],[_PC]:[()=>void 0!==output.headers[_xampc],()=>strictParseInt32(output.headers[_xampc])],[_TC]:[()=>void 0!==output.headers[_xatc],()=>strictParseInt32(output.headers[_xatc])],[_OLM]:[,output.headers[_xaolm]],[_OLRUD]:[()=>void 0!==output.headers[_xaolrud],()=>expectNonNull(parseRfc3339DateTimeWithOffset(output.headers[_xaolrud]))],[_OLLHS]:[,output.headers[_xaollh]],Metadata:[,Object.keys(output.headers).filter((header=>header.startsWith("x-amz-meta-"))).reduce(((acc,header)=>{acc[header.substring(11)]=output.headers[header];return acc}),{})]}),data=output.body;context2.sdkStreamMixin(data);contents.Body=data;return contents};de_GetObjectAclCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.AccessControlList?contents[_Gr]=[]:null!=data[_ACLc]&&null!=data[_ACLc][_G]&&(contents[_Gr]=de_Grants(getArrayIfSingleItem(data[_ACLc][_G]),context2));null!=data[_O]&&(contents[_O]=de_Owner(data[_O],context2));return contents};de_GetObjectAttributesCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_DM]:[()=>void 0!==output.headers[_xadm],()=>parseBoolean(output.headers[_xadm])],[_LM]:[()=>void 0!==output.headers[_lm],()=>expectNonNull(parseRfc7231DateTime(output.headers[_lm]))],[_VI]:[,output.headers[_xavi]],[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_Ch]&&(contents[_Ch]=de_Checksum(data[_Ch],context2));null!=data[_ETa]&&(contents[_ETa]=expectString(data[_ETa]));null!=data[_OP]&&(contents[_OP]=de_GetObjectAttributesParts(data[_OP],context2));null!=data[_OSb]&&(contents[_OSb]=strictParseLong(data[_OSb]));null!=data[_SC]&&(contents[_SC]=expectString(data[_SC]));return contents};de_GetObjectLegalHoldCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.LegalHold=de_ObjectLockLegalHold(data,context2);return contents};de_GetObjectLockConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.ObjectLockConfiguration=de_ObjectLockConfiguration(data,context2);return contents};de_GetObjectRetentionCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.Retention=de_ObjectLockRetention(data,context2);return contents};de_GetObjectTaggingCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_VI]:[,output.headers[_xavi]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.TagSet?contents[_TS]=[]:null!=data[_TS]&&null!=data[_TS][_Ta]&&(contents[_TS]=de_TagSet(getArrayIfSingleItem(data[_TS][_Ta]),context2));return contents};de_GetObjectTorrentCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=output.body;context2.sdkStreamMixin(data);contents.Body=data;return contents};de_GetPublicAccessBlockCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectObject(await parseXmlBody(output.body,context2));contents.PublicAccessBlockConfiguration=de_PublicAccessBlockConfiguration(data,context2);return contents};de_HeadBucketCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_BLT]:[,output.headers[_xablt]],[_BLN]:[,output.headers[_xabln]],[_BR]:[,output.headers[_xabr]],[_APA]:[()=>void 0!==output.headers[_xaapa],()=>parseBoolean(output.headers[_xaapa])]});await collectBody(output.body,context2);return contents};de_HeadObjectCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_DM]:[()=>void 0!==output.headers[_xadm],()=>parseBoolean(output.headers[_xadm])],[_AR]:[,output.headers[_ar]],[_Exp]:[,output.headers[_xae]],[_Re]:[,output.headers[_xar]],[_AS]:[,output.headers[_xaas]],[_LM]:[()=>void 0!==output.headers[_lm],()=>expectNonNull(parseRfc7231DateTime(output.headers[_lm]))],[_CLo]:[()=>void 0!==output.headers[_cl_],()=>strictParseLong(output.headers[_cl_])],[_CCRC]:[,output.headers[_xacc]],[_CCRCC]:[,output.headers[_xacc_]],[_CCRCNVME]:[,output.headers[_xacc__]],[_CSHA]:[,output.headers[_xacs]],[_CSHAh]:[,output.headers[_xacs_]],[_CT]:[,output.headers[_xact]],[_ETa]:[,output.headers[_eta]],[_MM]:[()=>void 0!==output.headers[_xamm],()=>strictParseInt32(output.headers[_xamm])],[_VI]:[,output.headers[_xavi]],[_CC]:[,output.headers[_cc]],[_CD]:[,output.headers[_cd]],[_CE]:[,output.headers[_ce]],[_CL]:[,output.headers[_cl]],[_CTo]:[,output.headers[_ct]],[_CR]:[,output.headers[_cr]],[_E]:[()=>void 0!==output.headers[_e],()=>expectNonNull(parseRfc7231DateTime(output.headers[_e]))],[_ES]:[,output.headers[_ex]],[_WRL]:[,output.headers[_xawrl]],[_SSE]:[,output.headers[_xasse]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_SC]:[,output.headers[_xasc]],[_RC]:[,output.headers[_xarc]],[_RS]:[,output.headers[_xars]],[_PC]:[()=>void 0!==output.headers[_xampc],()=>strictParseInt32(output.headers[_xampc])],[_OLM]:[,output.headers[_xaolm]],[_OLRUD]:[()=>void 0!==output.headers[_xaolrud],()=>expectNonNull(parseRfc3339DateTimeWithOffset(output.headers[_xaolrud]))],[_OLLHS]:[,output.headers[_xaollh]],Metadata:[,Object.keys(output.headers).filter((header=>header.startsWith("x-amz-meta-"))).reduce(((acc,header)=>{acc[header.substring(11)]=output.headers[header];return acc}),{})]});await collectBody(output.body,context2);return contents};de_ListBucketAnalyticsConfigurationsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.AnalyticsConfiguration?contents[_ACLn]=[]:null!=data[_AC]&&(contents[_ACLn]=de_AnalyticsConfigurationList(getArrayIfSingleItem(data[_AC]),context2));null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_NCT]&&(contents[_NCT]=expectString(data[_NCT]));return contents};de_ListBucketIntelligentTieringConfigurationsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));""===data.IntelligentTieringConfiguration?contents[_ITCL]=[]:null!=data[_ITC]&&(contents[_ITCL]=de_IntelligentTieringConfigurationList(getArrayIfSingleItem(data[_ITC]),context2));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_NCT]&&(contents[_NCT]=expectString(data[_NCT]));return contents};de_ListBucketInventoryConfigurationsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));""===data.InventoryConfiguration?contents[_ICL]=[]:null!=data[_IC]&&(contents[_ICL]=de_InventoryConfigurationList(getArrayIfSingleItem(data[_IC]),context2));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_NCT]&&(contents[_NCT]=expectString(data[_NCT]));return contents};de_ListBucketMetricsConfigurationsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));""===data.MetricsConfiguration?contents[_MCL]=[]:null!=data[_MC]&&(contents[_MCL]=de_MetricsConfigurationList(getArrayIfSingleItem(data[_MC]),context2));null!=data[_NCT]&&(contents[_NCT]=expectString(data[_NCT]));return contents};de_ListBucketsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.Buckets?contents[_Bu]=[]:null!=data[_Bu]&&null!=data[_Bu][_B]&&(contents[_Bu]=de_Buckets(getArrayIfSingleItem(data[_Bu][_B]),context2));null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));null!=data[_O]&&(contents[_O]=de_Owner(data[_O],context2));null!=data[_P]&&(contents[_P]=expectString(data[_P]));return contents};de_ListDirectoryBucketsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.Buckets?contents[_Bu]=[]:null!=data[_Bu]&&null!=data[_Bu][_B]&&(contents[_Bu]=de_Buckets(getArrayIfSingleItem(data[_Bu][_B]),context2));null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));return contents};de_ListMultipartUploadsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_B]&&(contents[_B]=expectString(data[_B]));""===data.CommonPrefixes?contents[_CP]=[]:null!=data[_CP]&&(contents[_CP]=de_CommonPrefixList(getArrayIfSingleItem(data[_CP]),context2));null!=data[_D]&&(contents[_D]=expectString(data[_D]));null!=data[_ET]&&(contents[_ET]=expectString(data[_ET]));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_KM]&&(contents[_KM]=expectString(data[_KM]));null!=data[_MU]&&(contents[_MU]=strictParseInt32(data[_MU]));null!=data[_NKM]&&(contents[_NKM]=expectString(data[_NKM]));null!=data[_NUIM]&&(contents[_NUIM]=expectString(data[_NUIM]));null!=data[_P]&&(contents[_P]=expectString(data[_P]));null!=data[_UIM]&&(contents[_UIM]=expectString(data[_UIM]));""===data.Upload?contents[_Up]=[]:null!=data[_U]&&(contents[_Up]=de_MultipartUploadList(getArrayIfSingleItem(data[_U]),context2));return contents};de_ListObjectsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.CommonPrefixes?contents[_CP]=[]:null!=data[_CP]&&(contents[_CP]=de_CommonPrefixList(getArrayIfSingleItem(data[_CP]),context2));""===data.Contents?contents[_Co]=[]:null!=data[_Co]&&(contents[_Co]=de_ObjectList(getArrayIfSingleItem(data[_Co]),context2));null!=data[_D]&&(contents[_D]=expectString(data[_D]));null!=data[_ET]&&(contents[_ET]=expectString(data[_ET]));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_M]&&(contents[_M]=expectString(data[_M]));null!=data[_MK]&&(contents[_MK]=strictParseInt32(data[_MK]));null!=data[_N]&&(contents[_N]=expectString(data[_N]));null!=data[_NM]&&(contents[_NM]=expectString(data[_NM]));null!=data[_P]&&(contents[_P]=expectString(data[_P]));return contents};de_ListObjectsV2Command=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.CommonPrefixes?contents[_CP]=[]:null!=data[_CP]&&(contents[_CP]=de_CommonPrefixList(getArrayIfSingleItem(data[_CP]),context2));""===data.Contents?contents[_Co]=[]:null!=data[_Co]&&(contents[_Co]=de_ObjectList(getArrayIfSingleItem(data[_Co]),context2));null!=data[_CTon]&&(contents[_CTon]=expectString(data[_CTon]));null!=data[_D]&&(contents[_D]=expectString(data[_D]));null!=data[_ET]&&(contents[_ET]=expectString(data[_ET]));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_KC]&&(contents[_KC]=strictParseInt32(data[_KC]));null!=data[_MK]&&(contents[_MK]=strictParseInt32(data[_MK]));null!=data[_N]&&(contents[_N]=expectString(data[_N]));null!=data[_NCT]&&(contents[_NCT]=expectString(data[_NCT]));null!=data[_P]&&(contents[_P]=expectString(data[_P]));null!=data[_SA]&&(contents[_SA]=expectString(data[_SA]));return contents};de_ListObjectVersionsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");""===data.CommonPrefixes?contents[_CP]=[]:null!=data[_CP]&&(contents[_CP]=de_CommonPrefixList(getArrayIfSingleItem(data[_CP]),context2));""===data.DeleteMarker?contents[_DMe]=[]:null!=data[_DM]&&(contents[_DMe]=de_DeleteMarkers(getArrayIfSingleItem(data[_DM]),context2));null!=data[_D]&&(contents[_D]=expectString(data[_D]));null!=data[_ET]&&(contents[_ET]=expectString(data[_ET]));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_KM]&&(contents[_KM]=expectString(data[_KM]));null!=data[_MK]&&(contents[_MK]=strictParseInt32(data[_MK]));null!=data[_N]&&(contents[_N]=expectString(data[_N]));null!=data[_NKM]&&(contents[_NKM]=expectString(data[_NKM]));null!=data[_NVIM]&&(contents[_NVIM]=expectString(data[_NVIM]));null!=data[_P]&&(contents[_P]=expectString(data[_P]));null!=data[_VIM]&&(contents[_VIM]=expectString(data[_VIM]));""===data.Version?contents[_Ve]=[]:null!=data[_V]&&(contents[_Ve]=de_ObjectVersionList(getArrayIfSingleItem(data[_V]),context2));return contents};de_ListPartsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_AD]:[()=>void 0!==output.headers[_xaad],()=>expectNonNull(parseRfc7231DateTime(output.headers[_xaad]))],[_ARI]:[,output.headers[_xaari]],[_RC]:[,output.headers[_xarc]]}),data=expectNonNull(expectObject(await parseXmlBody(output.body,context2)),"body");null!=data[_B]&&(contents[_B]=expectString(data[_B]));null!=data[_CA]&&(contents[_CA]=expectString(data[_CA]));null!=data[_CT]&&(contents[_CT]=expectString(data[_CT]));null!=data[_In]&&(contents[_In]=de_Initiator(data[_In],context2));null!=data[_IT]&&(contents[_IT]=parseBoolean(data[_IT]));null!=data[_K]&&(contents[_K]=expectString(data[_K]));null!=data[_MP]&&(contents[_MP]=strictParseInt32(data[_MP]));null!=data[_NPNM]&&(contents[_NPNM]=expectString(data[_NPNM]));null!=data[_O]&&(contents[_O]=de_Owner(data[_O],context2));null!=data[_PNM]&&(contents[_PNM]=expectString(data[_PNM]));""===data.Part?contents[_Part]=[]:null!=data[_Par]&&(contents[_Part]=de_Parts(getArrayIfSingleItem(data[_Par]),context2));null!=data[_SC]&&(contents[_SC]=expectString(data[_SC]));null!=data[_UI]&&(contents[_UI]=expectString(data[_UI]));return contents};de_PutBucketAccelerateConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketAclCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketAnalyticsConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketCorsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketEncryptionCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketIntelligentTieringConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketInventoryConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketLifecycleConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_TDMOS]:[,output.headers[_xatdmos]]});await collectBody(output.body,context2);return contents};de_PutBucketLoggingCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketMetricsConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketNotificationConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketOwnershipControlsCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketPolicyCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketReplicationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketRequestPaymentCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketTaggingCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketVersioningCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutBucketWebsiteCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_PutObjectCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_Exp]:[,output.headers[_xae]],[_ETa]:[,output.headers[_eta]],[_CCRC]:[,output.headers[_xacc]],[_CCRCC]:[,output.headers[_xacc_]],[_CCRCNVME]:[,output.headers[_xacc__]],[_CSHA]:[,output.headers[_xacs]],[_CSHAh]:[,output.headers[_xacs_]],[_CT]:[,output.headers[_xact]],[_SSE]:[,output.headers[_xasse]],[_VI]:[,output.headers[_xavi]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_SSEKMSEC]:[,output.headers[_xassec]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_Si]:[()=>void 0!==output.headers[_xaos],()=>strictParseLong(output.headers[_xaos])],[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_PutObjectAclCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_PutObjectLegalHoldCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_PutObjectLockConfigurationCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_PutObjectRetentionCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_PutObjectTaggingCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_VI]:[,output.headers[_xavi]]});await collectBody(output.body,context2);return contents};de_PutPublicAccessBlockCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_RestoreObjectCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_RC]:[,output.headers[_xarc]],[_ROP]:[,output.headers[_xarop]]});await collectBody(output.body,context2);return contents};de_SelectObjectContentCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)}),data=output.body;contents.Payload=de_SelectObjectContentEventStream(data,context2);return contents};de_UploadPartCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_SSE]:[,output.headers[_xasse]],[_ETa]:[,output.headers[_eta]],[_CCRC]:[,output.headers[_xacc]],[_CCRCC]:[,output.headers[_xacc_]],[_CCRCNVME]:[,output.headers[_xacc__]],[_CSHA]:[,output.headers[_xacs]],[_CSHAh]:[,output.headers[_xacs_]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_RC]:[,output.headers[_xarc]]});await collectBody(output.body,context2);return contents};de_UploadPartCopyCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output),[_CSVI]:[,output.headers[_xacsvi]],[_SSE]:[,output.headers[_xasse]],[_SSECA]:[,output.headers[_xasseca]],[_SSECKMD]:[,output.headers[_xasseckm]],[_SSEKMSKI]:[,output.headers[_xasseakki]],[_BKE]:[()=>void 0!==output.headers[_xassebke],()=>parseBoolean(output.headers[_xassebke])],[_RC]:[,output.headers[_xarc]]}),data=expectObject(await parseXmlBody(output.body,context2));contents.CopyPartResult=de_CopyPartResult(data,context2);return contents};de_WriteGetObjectResponseCommand=async(output,context2)=>{if(200!==output.statusCode&&output.statusCode>=300)return de_CommandError(output,context2);const contents=map2({$metadata:deserializeMetadata2(output)});await collectBody(output.body,context2);return contents};de_CommandError=async(output,context2)=>{const parsedOutput={...output,body:await parseXmlErrorBody(output.body,context2)},errorCode=loadRestXmlErrorCode(output,parsedOutput.body);switch(errorCode){case"NoSuchUpload":case"com.amazonaws.s3#NoSuchUpload":throw await de_NoSuchUploadRes(parsedOutput,context2);case"ObjectNotInActiveTierError":case"com.amazonaws.s3#ObjectNotInActiveTierError":throw await de_ObjectNotInActiveTierErrorRes(parsedOutput,context2);case"BucketAlreadyExists":case"com.amazonaws.s3#BucketAlreadyExists":throw await de_BucketAlreadyExistsRes(parsedOutput,context2);case"BucketAlreadyOwnedByYou":case"com.amazonaws.s3#BucketAlreadyOwnedByYou":throw await de_BucketAlreadyOwnedByYouRes(parsedOutput,context2);case"NoSuchBucket":case"com.amazonaws.s3#NoSuchBucket":throw await de_NoSuchBucketRes(parsedOutput,context2);case"InvalidObjectState":case"com.amazonaws.s3#InvalidObjectState":throw await de_InvalidObjectStateRes(parsedOutput,context2);case"NoSuchKey":case"com.amazonaws.s3#NoSuchKey":throw await de_NoSuchKeyRes(parsedOutput,context2);case"NotFound":case"com.amazonaws.s3#NotFound":throw await de_NotFoundRes(parsedOutput,context2);case"EncryptionTypeMismatch":case"com.amazonaws.s3#EncryptionTypeMismatch":throw await de_EncryptionTypeMismatchRes(parsedOutput,context2);case"InvalidRequest":case"com.amazonaws.s3#InvalidRequest":throw await de_InvalidRequestRes(parsedOutput,context2);case"InvalidWriteOffset":case"com.amazonaws.s3#InvalidWriteOffset":throw await de_InvalidWriteOffsetRes(parsedOutput,context2);case"TooManyParts":case"com.amazonaws.s3#TooManyParts":throw await de_TooManyPartsRes(parsedOutput,context2);case"ObjectAlreadyInActiveTierError":case"com.amazonaws.s3#ObjectAlreadyInActiveTierError":throw await de_ObjectAlreadyInActiveTierErrorRes(parsedOutput,context2);default:const parsedBody=parsedOutput.body;return throwDefaultError2({output,parsedBody,errorCode})}};throwDefaultError2=withBaseException(S3ServiceException);de_BucketAlreadyExistsRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new BucketAlreadyExists({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_BucketAlreadyOwnedByYouRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new BucketAlreadyOwnedByYou({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_EncryptionTypeMismatchRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new EncryptionTypeMismatch({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_InvalidObjectStateRes=async(parsedOutput,context2)=>{const contents=map2({}),data=parsedOutput.body;null!=data[_AT]&&(contents[_AT]=expectString(data[_AT]));null!=data[_SC]&&(contents[_SC]=expectString(data[_SC]));const exception=new InvalidObjectState({$metadata:deserializeMetadata2(parsedOutput),...contents});return decorateServiceException(exception,parsedOutput.body)};de_InvalidRequestRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new InvalidRequest({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_InvalidWriteOffsetRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new InvalidWriteOffset({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_NoSuchBucketRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new NoSuchBucket({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_NoSuchKeyRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new NoSuchKey({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_NoSuchUploadRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new NoSuchUpload({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_NotFoundRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new NotFound({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_ObjectAlreadyInActiveTierErrorRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new ObjectAlreadyInActiveTierError({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_ObjectNotInActiveTierErrorRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new ObjectNotInActiveTierError({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_TooManyPartsRes=async(parsedOutput,context2)=>{const contents=map2({}),exception=(parsedOutput.body,new TooManyParts({$metadata:deserializeMetadata2(parsedOutput),...contents}));return decorateServiceException(exception,parsedOutput.body)};de_SelectObjectContentEventStream=(output,context2)=>context2.eventStreamMarshaller.deserialize(output,(async event2=>null!=event2.Records?{Records:await de_RecordsEvent_event(event2.Records,context2)}:null!=event2.Stats?{Stats:await de_StatsEvent_event(event2.Stats,context2)}:null!=event2.Progress?{Progress:await de_ProgressEvent_event(event2.Progress,context2)}:null!=event2.Cont?{Cont:await de_ContinuationEvent_event(event2.Cont,context2)}:null!=event2.End?{End:await de_EndEvent_event(event2.End,context2)}:{$unknown:output}));de_ContinuationEvent_event=async(output,context2)=>{const contents={},data=await parseXmlBody(output.body,context2);Object.assign(contents,de_ContinuationEvent(data,context2));return contents};de_EndEvent_event=async(output,context2)=>{const contents={},data=await parseXmlBody(output.body,context2);Object.assign(contents,de_EndEvent(data,context2));return contents};de_ProgressEvent_event=async(output,context2)=>{const contents={},data=await parseXmlBody(output.body,context2);contents.Details=de_Progress(data,context2);return contents};de_RecordsEvent_event=async(output,context2)=>{const contents={};contents.Payload=output.body;return contents};de_StatsEvent_event=async(output,context2)=>{const contents={},data=await parseXmlBody(output.body,context2);contents.Details=de_Stats(data,context2);return contents};se_AbortIncompleteMultipartUpload=(input,context2)=>{const bn2=new XmlNode(_AIMU);null!=input[_DAI]&&bn2.c(XmlNode.of(_DAI,String(input[_DAI])).n(_DAI));return bn2};se_AccelerateConfiguration=(input,context2)=>{const bn2=new XmlNode(_ACc);null!=input[_S]&&bn2.c(XmlNode.of(_BAS,input[_S]).n(_S));return bn2};se_AccessControlPolicy=(input,context2)=>{const bn2=new XmlNode(_ACP);bn2.lc(input,"Grants","AccessControlList",(()=>se_Grants(input[_Gr],context2)));null!=input[_O]&&bn2.c(se_Owner(input[_O],context2).n(_O));return bn2};se_AccessControlTranslation=(input,context2)=>{const bn2=new XmlNode(_ACT);null!=input[_O]&&bn2.c(XmlNode.of(_OOw,input[_O]).n(_O));return bn2};se_AllowedHeaders=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>XmlNode.of(_AH,entry).n(_me)));se_AllowedMethods=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>XmlNode.of(_AM,entry).n(_me)));se_AllowedOrigins=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>XmlNode.of(_AO,entry).n(_me)));se_AnalyticsAndOperator=(input,context2)=>{const bn2=new XmlNode(_AAO);bn2.cc(input,_P);bn2.l(input,"Tags","Tag",(()=>se_TagSet(input[_Tag],context2)));return bn2};se_AnalyticsConfiguration=(input,context2)=>{const bn2=new XmlNode(_AC);null!=input[_I]&&bn2.c(XmlNode.of(_AI,input[_I]).n(_I));null!=input[_F]&&bn2.c(se_AnalyticsFilter(input[_F],context2).n(_F));null!=input[_SCA]&&bn2.c(se_StorageClassAnalysis(input[_SCA],context2).n(_SCA));return bn2};se_AnalyticsExportDestination=(input,context2)=>{const bn2=new XmlNode(_AED);null!=input[_SBD]&&bn2.c(se_AnalyticsS3BucketDestination(input[_SBD],context2).n(_SBD));return bn2};se_AnalyticsFilter=(input,context2)=>{const bn2=new XmlNode(_AF);AnalyticsFilter.visit(input,{Prefix:value=>{null!=input[_P]&&bn2.c(XmlNode.of(_P,value).n(_P))},Tag:value=>{null!=input[_Ta]&&bn2.c(se_Tag(value,context2).n(_Ta))},And:value=>{null!=input[_A]&&bn2.c(se_AnalyticsAndOperator(value,context2).n(_A))},_:(name,value)=>{if(!(value instanceof XmlNode||value instanceof XmlText))throw new Error("Unable to serialize unknown union members in XML.");bn2.c(new XmlNode(name).c(value))}});return bn2};se_AnalyticsS3BucketDestination=(input,context2)=>{const bn2=new XmlNode(_ASBD);null!=input[_Fo]&&bn2.c(XmlNode.of(_ASEFF,input[_Fo]).n(_Fo));null!=input[_BAI]&&bn2.c(XmlNode.of(_AIc,input[_BAI]).n(_BAI));null!=input[_B]&&bn2.c(XmlNode.of(_BN,input[_B]).n(_B));bn2.cc(input,_P);return bn2};se_BucketInfo=(input,context2)=>{const bn2=new XmlNode(_BI);bn2.cc(input,_DR);null!=input[_Ty]&&bn2.c(XmlNode.of(_BT,input[_Ty]).n(_Ty));return bn2};se_BucketLifecycleConfiguration=(input,context2)=>{const bn2=new XmlNode(_BLC);bn2.l(input,"Rules","Rule",(()=>se_LifecycleRules(input[_Rul],context2)));return bn2};se_BucketLoggingStatus=(input,context2)=>{const bn2=new XmlNode(_BLS);null!=input[_LE]&&bn2.c(se_LoggingEnabled(input[_LE],context2).n(_LE));return bn2};se_CompletedMultipartUpload=(input,context2)=>{const bn2=new XmlNode(_CMU);bn2.l(input,"Parts","Part",(()=>se_CompletedPartList(input[_Part],context2)));return bn2};se_CompletedPart=(input,context2)=>{const bn2=new XmlNode(_CPo);bn2.cc(input,_ETa);bn2.cc(input,_CCRC);bn2.cc(input,_CCRCC);bn2.cc(input,_CCRCNVME);bn2.cc(input,_CSHA);bn2.cc(input,_CSHAh);null!=input[_PN]&&bn2.c(XmlNode.of(_PN,String(input[_PN])).n(_PN));return bn2};se_CompletedPartList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_CompletedPart(entry).n(_me)));se_Condition=(input,context2)=>{const bn2=new XmlNode(_Con);bn2.cc(input,_HECRE);bn2.cc(input,_KPE);return bn2};se_CORSConfiguration=(input,context2)=>{const bn2=new XmlNode(_CORSC);bn2.l(input,"CORSRules","CORSRule",(()=>se_CORSRules(input[_CORSRu],context2)));return bn2};se_CORSRule=(input,context2)=>{const bn2=new XmlNode(_CORSR);bn2.cc(input,_ID_);bn2.l(input,"AllowedHeaders","AllowedHeader",(()=>se_AllowedHeaders(input[_AHl])));bn2.l(input,"AllowedMethods","AllowedMethod",(()=>se_AllowedMethods(input[_AMl])));bn2.l(input,"AllowedOrigins","AllowedOrigin",(()=>se_AllowedOrigins(input[_AOl])));bn2.l(input,"ExposeHeaders","ExposeHeader",(()=>se_ExposeHeaders(input[_EH],context2)));null!=input[_MAS]&&bn2.c(XmlNode.of(_MAS,String(input[_MAS])).n(_MAS));return bn2};se_CORSRules=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_CORSRule(entry,context2).n(_me)));se_CreateBucketConfiguration=(input,context2)=>{const bn2=new XmlNode(_CBC);null!=input[_LC]&&bn2.c(XmlNode.of(_BLCu,input[_LC]).n(_LC));null!=input[_L]&&bn2.c(se_LocationInfo(input[_L],context2).n(_L));null!=input[_B]&&bn2.c(se_BucketInfo(input[_B]).n(_B));return bn2};se_CSVInput=(input,context2)=>{const bn2=new XmlNode(_CSVIn);bn2.cc(input,_FHI);bn2.cc(input,_Com);bn2.cc(input,_QEC);bn2.cc(input,_RD);bn2.cc(input,_FD);bn2.cc(input,_QCuo);null!=input[_AQRD]&&bn2.c(XmlNode.of(_AQRD,String(input[_AQRD])).n(_AQRD));return bn2};se_CSVOutput=(input,context2)=>{const bn2=new XmlNode(_CSVO);bn2.cc(input,_QF);bn2.cc(input,_QEC);bn2.cc(input,_RD);bn2.cc(input,_FD);bn2.cc(input,_QCuo);return bn2};se_DefaultRetention=(input,context2)=>{const bn2=new XmlNode(_DRe);null!=input[_Mo]&&bn2.c(XmlNode.of(_OLRM,input[_Mo]).n(_Mo));null!=input[_Da]&&bn2.c(XmlNode.of(_Da,String(input[_Da])).n(_Da));null!=input[_Y]&&bn2.c(XmlNode.of(_Y,String(input[_Y])).n(_Y));return bn2};se_Delete=(input,context2)=>{const bn2=new XmlNode(_Del);bn2.l(input,"Objects","Object",(()=>se_ObjectIdentifierList(input[_Ob],context2)));null!=input[_Q]&&bn2.c(XmlNode.of(_Q,String(input[_Q])).n(_Q));return bn2};se_DeleteMarkerReplication=(input,context2)=>{const bn2=new XmlNode(_DMR);null!=input[_S]&&bn2.c(XmlNode.of(_DMRS,input[_S]).n(_S));return bn2};se_Destination=(input,context2)=>{const bn2=new XmlNode(_Des);null!=input[_B]&&bn2.c(XmlNode.of(_BN,input[_B]).n(_B));null!=input[_Ac]&&bn2.c(XmlNode.of(_AIc,input[_Ac]).n(_Ac));bn2.cc(input,_SC);null!=input[_ACT]&&bn2.c(se_AccessControlTranslation(input[_ACT]).n(_ACT));null!=input[_ECn]&&bn2.c(se_EncryptionConfiguration(input[_ECn],context2).n(_ECn));null!=input[_RTe]&&bn2.c(se_ReplicationTime(input[_RTe],context2).n(_RTe));null!=input[_Me]&&bn2.c(se_Metrics(input[_Me],context2).n(_Me));return bn2};se_Encryption=(input,context2)=>{const bn2=new XmlNode(_En);null!=input[_ETn]&&bn2.c(XmlNode.of(_SSE,input[_ETn]).n(_ETn));null!=input[_KMSKI]&&bn2.c(XmlNode.of(_SSEKMSKI,input[_KMSKI]).n(_KMSKI));bn2.cc(input,_KMSC);return bn2};se_EncryptionConfiguration=(input,context2)=>{const bn2=new XmlNode(_ECn);bn2.cc(input,_RKKID);return bn2};se_ErrorDocument=(input,context2)=>{const bn2=new XmlNode(_ED);null!=input[_K]&&bn2.c(XmlNode.of(_OK,input[_K]).n(_K));return bn2};se_EventBridgeConfiguration=(input,context2)=>new XmlNode(_EBC);se_EventList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>XmlNode.of(_Ev,entry).n(_me)));se_ExistingObjectReplication=(input,context2)=>{const bn2=new XmlNode(_EOR);null!=input[_S]&&bn2.c(XmlNode.of(_EORS,input[_S]).n(_S));return bn2};se_ExposeHeaders=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>XmlNode.of(_EHx,entry).n(_me)));se_FilterRule=(input,context2)=>{const bn2=new XmlNode(_FR);null!=input[_N]&&bn2.c(XmlNode.of(_FRN,input[_N]).n(_N));null!=input[_Va]&&bn2.c(XmlNode.of(_FRV,input[_Va]).n(_Va));return bn2};se_FilterRuleList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_FilterRule(entry).n(_me)));se_GlacierJobParameters=(input,context2)=>{const bn2=new XmlNode(_GJP);bn2.cc(input,_Ti);return bn2};se_Grant=(input,context2)=>{const bn2=new XmlNode(_G);if(null!=input[_Gra]){const n3=se_Grantee(input[_Gra],context2).n(_Gra);n3.a("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");bn2.c(n3)}bn2.cc(input,_Pe);return bn2};se_Grantee=(input,context2)=>{const bn2=new XmlNode(_Gra);bn2.cc(input,_DN);bn2.cc(input,_EA);bn2.cc(input,_ID_);bn2.cc(input,_URI);bn2.a("xsi:type",input[_Ty]);return bn2};se_Grants=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_Grant(entry,context2).n(_G)));se_IndexDocument=(input,context2)=>{const bn2=new XmlNode(_ID);bn2.cc(input,_Su);return bn2};se_InputSerialization=(input,context2)=>{const bn2=new XmlNode(_IS);null!=input[_CSV]&&bn2.c(se_CSVInput(input[_CSV]).n(_CSV));bn2.cc(input,_CTom);null!=input[_JSON]&&bn2.c(se_JSONInput(input[_JSON],context2).n(_JSON));null!=input[_Parq]&&bn2.c(se_ParquetInput(input[_Parq],context2).n(_Parq));return bn2};se_IntelligentTieringAndOperator=(input,context2)=>{const bn2=new XmlNode(_ITAO);bn2.cc(input,_P);bn2.l(input,"Tags","Tag",(()=>se_TagSet(input[_Tag],context2)));return bn2};se_IntelligentTieringConfiguration=(input,context2)=>{const bn2=new XmlNode(_ITC);null!=input[_I]&&bn2.c(XmlNode.of(_ITI,input[_I]).n(_I));null!=input[_F]&&bn2.c(se_IntelligentTieringFilter(input[_F],context2).n(_F));null!=input[_S]&&bn2.c(XmlNode.of(_ITS,input[_S]).n(_S));bn2.l(input,"Tierings","Tiering",(()=>se_TieringList(input[_Tie],context2)));return bn2};se_IntelligentTieringFilter=(input,context2)=>{const bn2=new XmlNode(_ITF);bn2.cc(input,_P);null!=input[_Ta]&&bn2.c(se_Tag(input[_Ta],context2).n(_Ta));null!=input[_A]&&bn2.c(se_IntelligentTieringAndOperator(input[_A],context2).n(_A));return bn2};se_InventoryConfiguration=(input,context2)=>{const bn2=new XmlNode(_IC);null!=input[_Des]&&bn2.c(se_InventoryDestination(input[_Des],context2).n(_Des));null!=input[_IE]&&bn2.c(XmlNode.of(_IE,String(input[_IE])).n(_IE));null!=input[_F]&&bn2.c(se_InventoryFilter(input[_F],context2).n(_F));null!=input[_I]&&bn2.c(XmlNode.of(_II,input[_I]).n(_I));null!=input[_IOV]&&bn2.c(XmlNode.of(_IIOV,input[_IOV]).n(_IOV));bn2.lc(input,"OptionalFields","OptionalFields",(()=>se_InventoryOptionalFields(input[_OF],context2)));null!=input[_Sc]&&bn2.c(se_InventorySchedule(input[_Sc],context2).n(_Sc));return bn2};se_InventoryDestination=(input,context2)=>{const bn2=new XmlNode(_IDn);null!=input[_SBD]&&bn2.c(se_InventoryS3BucketDestination(input[_SBD],context2).n(_SBD));return bn2};se_InventoryEncryption=(input,context2)=>{const bn2=new XmlNode(_IEn);null!=input[_SSES]&&bn2.c(se_SSES3(input[_SSES],context2).n(_SS));null!=input[_SSEKMS]&&bn2.c(se_SSEKMS(input[_SSEKMS],context2).n(_SK));return bn2};se_InventoryFilter=(input,context2)=>{const bn2=new XmlNode(_IF);bn2.cc(input,_P);return bn2};se_InventoryOptionalFields=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>XmlNode.of(_IOF,entry).n(_Fi)));se_InventoryS3BucketDestination=(input,context2)=>{const bn2=new XmlNode(_ISBD);bn2.cc(input,_AIc);null!=input[_B]&&bn2.c(XmlNode.of(_BN,input[_B]).n(_B));null!=input[_Fo]&&bn2.c(XmlNode.of(_IFn,input[_Fo]).n(_Fo));bn2.cc(input,_P);null!=input[_En]&&bn2.c(se_InventoryEncryption(input[_En],context2).n(_En));return bn2};se_InventorySchedule=(input,context2)=>{const bn2=new XmlNode(_ISn);null!=input[_Fr]&&bn2.c(XmlNode.of(_IFnv,input[_Fr]).n(_Fr));return bn2};se_JSONInput=(input,context2)=>{const bn2=new XmlNode(_JSONI);null!=input[_Ty]&&bn2.c(XmlNode.of(_JSONT,input[_Ty]).n(_Ty));return bn2};se_JSONOutput=(input,context2)=>{const bn2=new XmlNode(_JSONO);bn2.cc(input,_RD);return bn2};se_LambdaFunctionConfiguration=(input,context2)=>{const bn2=new XmlNode(_LFCa);null!=input[_I]&&bn2.c(XmlNode.of(_NI,input[_I]).n(_I));null!=input[_LFA]&&bn2.c(XmlNode.of(_LFA,input[_LFA]).n(_CF));bn2.l(input,"Events","Event",(()=>se_EventList(input[_Eve])));null!=input[_F]&&bn2.c(se_NotificationConfigurationFilter(input[_F],context2).n(_F));return bn2};se_LambdaFunctionConfigurationList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_LambdaFunctionConfiguration(entry,context2).n(_me)));se_LifecycleExpiration=(input,context2)=>{const bn2=new XmlNode(_LEi);null!=input[_Dat]&&bn2.c(XmlNode.of(_Dat,serializeDateTime(input[_Dat]).toString()).n(_Dat));null!=input[_Da]&&bn2.c(XmlNode.of(_Da,String(input[_Da])).n(_Da));null!=input[_EODM]&&bn2.c(XmlNode.of(_EODM,String(input[_EODM])).n(_EODM));return bn2};se_LifecycleRule=(input,context2)=>{const bn2=new XmlNode(_LR);null!=input[_Exp]&&bn2.c(se_LifecycleExpiration(input[_Exp]).n(_Exp));bn2.cc(input,_ID_);bn2.cc(input,_P);null!=input[_F]&&bn2.c(se_LifecycleRuleFilter(input[_F],context2).n(_F));null!=input[_S]&&bn2.c(XmlNode.of(_ESx,input[_S]).n(_S));bn2.l(input,"Transitions","Transition",(()=>se_TransitionList(input[_Tr],context2)));bn2.l(input,"NoncurrentVersionTransitions","NoncurrentVersionTransition",(()=>se_NoncurrentVersionTransitionList(input[_NVT],context2)));null!=input[_NVE]&&bn2.c(se_NoncurrentVersionExpiration(input[_NVE],context2).n(_NVE));null!=input[_AIMU]&&bn2.c(se_AbortIncompleteMultipartUpload(input[_AIMU]).n(_AIMU));return bn2};se_LifecycleRuleAndOperator=(input,context2)=>{const bn2=new XmlNode(_LRAO);bn2.cc(input,_P);bn2.l(input,"Tags","Tag",(()=>se_TagSet(input[_Tag],context2)));null!=input[_OSGT]&&bn2.c(XmlNode.of(_OSGTB,String(input[_OSGT])).n(_OSGT));null!=input[_OSLT]&&bn2.c(XmlNode.of(_OSLTB,String(input[_OSLT])).n(_OSLT));return bn2};se_LifecycleRuleFilter=(input,context2)=>{const bn2=new XmlNode(_LRF);bn2.cc(input,_P);null!=input[_Ta]&&bn2.c(se_Tag(input[_Ta],context2).n(_Ta));null!=input[_OSGT]&&bn2.c(XmlNode.of(_OSGTB,String(input[_OSGT])).n(_OSGT));null!=input[_OSLT]&&bn2.c(XmlNode.of(_OSLTB,String(input[_OSLT])).n(_OSLT));null!=input[_A]&&bn2.c(se_LifecycleRuleAndOperator(input[_A],context2).n(_A));return bn2};se_LifecycleRules=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_LifecycleRule(entry,context2).n(_me)));se_LocationInfo=(input,context2)=>{const bn2=new XmlNode(_LI);null!=input[_Ty]&&bn2.c(XmlNode.of(_LT,input[_Ty]).n(_Ty));null!=input[_N]&&bn2.c(XmlNode.of(_LNAS,input[_N]).n(_N));return bn2};se_LoggingEnabled=(input,context2)=>{const bn2=new XmlNode(_LE);bn2.cc(input,_TB);bn2.lc(input,"TargetGrants","TargetGrants",(()=>se_TargetGrants(input[_TG],context2)));bn2.cc(input,_TP);null!=input[_TOKF]&&bn2.c(se_TargetObjectKeyFormat(input[_TOKF],context2).n(_TOKF));return bn2};se_MetadataEntry=(input,context2)=>{const bn2=new XmlNode(_ME);null!=input[_N]&&bn2.c(XmlNode.of(_MKe,input[_N]).n(_N));null!=input[_Va]&&bn2.c(XmlNode.of(_MV,input[_Va]).n(_Va));return bn2};se_MetadataTableConfiguration=(input,context2)=>{const bn2=new XmlNode(_MTC);null!=input[_STD]&&bn2.c(se_S3TablesDestination(input[_STD],context2).n(_STD));return bn2};se_Metrics=(input,context2)=>{const bn2=new XmlNode(_Me);null!=input[_S]&&bn2.c(XmlNode.of(_MS,input[_S]).n(_S));null!=input[_ETv]&&bn2.c(se_ReplicationTimeValue(input[_ETv],context2).n(_ETv));return bn2};se_MetricsAndOperator=(input,context2)=>{const bn2=new XmlNode(_MAO);bn2.cc(input,_P);bn2.l(input,"Tags","Tag",(()=>se_TagSet(input[_Tag],context2)));bn2.cc(input,_APAc);return bn2};se_MetricsConfiguration=(input,context2)=>{const bn2=new XmlNode(_MC);null!=input[_I]&&bn2.c(XmlNode.of(_MI,input[_I]).n(_I));null!=input[_F]&&bn2.c(se_MetricsFilter(input[_F],context2).n(_F));return bn2};se_MetricsFilter=(input,context2)=>{const bn2=new XmlNode(_MF);MetricsFilter.visit(input,{Prefix:value=>{null!=input[_P]&&bn2.c(XmlNode.of(_P,value).n(_P))},Tag:value=>{null!=input[_Ta]&&bn2.c(se_Tag(value,context2).n(_Ta))},AccessPointArn:value=>{null!=input[_APAc]&&bn2.c(XmlNode.of(_APAc,value).n(_APAc))},And:value=>{null!=input[_A]&&bn2.c(se_MetricsAndOperator(value,context2).n(_A))},_:(name,value)=>{if(!(value instanceof XmlNode||value instanceof XmlText))throw new Error("Unable to serialize unknown union members in XML.");bn2.c(new XmlNode(name).c(value))}});return bn2};se_NoncurrentVersionExpiration=(input,context2)=>{const bn2=new XmlNode(_NVE);null!=input[_ND]&&bn2.c(XmlNode.of(_Da,String(input[_ND])).n(_ND));null!=input[_NNV]&&bn2.c(XmlNode.of(_VC,String(input[_NNV])).n(_NNV));return bn2};se_NoncurrentVersionTransition=(input,context2)=>{const bn2=new XmlNode(_NVTo);null!=input[_ND]&&bn2.c(XmlNode.of(_Da,String(input[_ND])).n(_ND));null!=input[_SC]&&bn2.c(XmlNode.of(_TSC,input[_SC]).n(_SC));null!=input[_NNV]&&bn2.c(XmlNode.of(_VC,String(input[_NNV])).n(_NNV));return bn2};se_NoncurrentVersionTransitionList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_NoncurrentVersionTransition(entry).n(_me)));se_NotificationConfiguration=(input,context2)=>{const bn2=new XmlNode(_NC);bn2.l(input,"TopicConfigurations","TopicConfiguration",(()=>se_TopicConfigurationList(input[_TCop],context2)));bn2.l(input,"QueueConfigurations","QueueConfiguration",(()=>se_QueueConfigurationList(input[_QCu],context2)));bn2.l(input,"LambdaFunctionConfigurations","CloudFunctionConfiguration",(()=>se_LambdaFunctionConfigurationList(input[_LFC],context2)));null!=input[_EBC]&&bn2.c(se_EventBridgeConfiguration(input[_EBC]).n(_EBC));return bn2};se_NotificationConfigurationFilter=(input,context2)=>{const bn2=new XmlNode(_NCF);null!=input[_K]&&bn2.c(se_S3KeyFilter(input[_K],context2).n(_SKe));return bn2};se_ObjectIdentifier=(input,context2)=>{const bn2=new XmlNode(_OI);null!=input[_K]&&bn2.c(XmlNode.of(_OK,input[_K]).n(_K));null!=input[_VI]&&bn2.c(XmlNode.of(_OVI,input[_VI]).n(_VI));bn2.cc(input,_ETa);null!=input[_LMT]&&bn2.c(XmlNode.of(_LMT,dateToUtcString(input[_LMT]).toString()).n(_LMT));null!=input[_Si]&&bn2.c(XmlNode.of(_Si,String(input[_Si])).n(_Si));return bn2};se_ObjectIdentifierList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_ObjectIdentifier(entry).n(_me)));se_ObjectLockConfiguration=(input,context2)=>{const bn2=new XmlNode(_OLC);bn2.cc(input,_OLE);null!=input[_Ru]&&bn2.c(se_ObjectLockRule(input[_Ru],context2).n(_Ru));return bn2};se_ObjectLockLegalHold=(input,context2)=>{const bn2=new XmlNode(_OLLH);null!=input[_S]&&bn2.c(XmlNode.of(_OLLHS,input[_S]).n(_S));return bn2};se_ObjectLockRetention=(input,context2)=>{const bn2=new XmlNode(_OLR);null!=input[_Mo]&&bn2.c(XmlNode.of(_OLRM,input[_Mo]).n(_Mo));null!=input[_RUD]&&bn2.c(XmlNode.of(_Dat,serializeDateTime(input[_RUD]).toString()).n(_RUD));return bn2};se_ObjectLockRule=(input,context2)=>{const bn2=new XmlNode(_OLRb);null!=input[_DRe]&&bn2.c(se_DefaultRetention(input[_DRe]).n(_DRe));return bn2};se_OutputLocation=(input,context2)=>{const bn2=new XmlNode(_OL);null!=input[_S_]&&bn2.c(se_S3Location(input[_S_],context2).n(_S_));return bn2};se_OutputSerialization=(input,context2)=>{const bn2=new XmlNode(_OS);null!=input[_CSV]&&bn2.c(se_CSVOutput(input[_CSV]).n(_CSV));null!=input[_JSON]&&bn2.c(se_JSONOutput(input[_JSON]).n(_JSON));return bn2};se_Owner=(input,context2)=>{const bn2=new XmlNode(_O);bn2.cc(input,_DN);bn2.cc(input,_ID_);return bn2};se_OwnershipControls=(input,context2)=>{const bn2=new XmlNode(_OC);bn2.l(input,"Rules","Rule",(()=>se_OwnershipControlsRules(input[_Rul],context2)));return bn2};se_OwnershipControlsRule=(input,context2)=>{const bn2=new XmlNode(_OCR);bn2.cc(input,_OO);return bn2};se_OwnershipControlsRules=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_OwnershipControlsRule(entry).n(_me)));se_ParquetInput=(input,context2)=>new XmlNode(_PI);se_PartitionedPrefix=(input,context2)=>{const bn2=new XmlNode(_PP);bn2.cc(input,_PDS);return bn2};se_PublicAccessBlockConfiguration=(input,context2)=>{const bn2=new XmlNode(_PABC);null!=input[_BPA]&&bn2.c(XmlNode.of(_Se,String(input[_BPA])).n(_BPA));null!=input[_IPA]&&bn2.c(XmlNode.of(_Se,String(input[_IPA])).n(_IPA));null!=input[_BPP]&&bn2.c(XmlNode.of(_Se,String(input[_BPP])).n(_BPP));null!=input[_RPB]&&bn2.c(XmlNode.of(_Se,String(input[_RPB])).n(_RPB));return bn2};se_QueueConfiguration=(input,context2)=>{const bn2=new XmlNode(_QC);null!=input[_I]&&bn2.c(XmlNode.of(_NI,input[_I]).n(_I));null!=input[_QA]&&bn2.c(XmlNode.of(_QA,input[_QA]).n(_Qu));bn2.l(input,"Events","Event",(()=>se_EventList(input[_Eve])));null!=input[_F]&&bn2.c(se_NotificationConfigurationFilter(input[_F],context2).n(_F));return bn2};se_QueueConfigurationList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_QueueConfiguration(entry,context2).n(_me)));se_Redirect=(input,context2)=>{const bn2=new XmlNode(_Red);bn2.cc(input,_HN);bn2.cc(input,_HRC);bn2.cc(input,_Pr);bn2.cc(input,_RKPW);bn2.cc(input,_RKW);return bn2};se_RedirectAllRequestsTo=(input,context2)=>{const bn2=new XmlNode(_RART);bn2.cc(input,_HN);bn2.cc(input,_Pr);return bn2};se_ReplicaModifications=(input,context2)=>{const bn2=new XmlNode(_RM);null!=input[_S]&&bn2.c(XmlNode.of(_RMS,input[_S]).n(_S));return bn2};se_ReplicationConfiguration=(input,context2)=>{const bn2=new XmlNode(_RCe);bn2.cc(input,_Ro);bn2.l(input,"Rules","Rule",(()=>se_ReplicationRules(input[_Rul],context2)));return bn2};se_ReplicationRule=(input,context2)=>{const bn2=new XmlNode(_RRe);bn2.cc(input,_ID_);null!=input[_Pri]&&bn2.c(XmlNode.of(_Pri,String(input[_Pri])).n(_Pri));bn2.cc(input,_P);null!=input[_F]&&bn2.c(se_ReplicationRuleFilter(input[_F],context2).n(_F));null!=input[_S]&&bn2.c(XmlNode.of(_RRS,input[_S]).n(_S));null!=input[_SSC]&&bn2.c(se_SourceSelectionCriteria(input[_SSC],context2).n(_SSC));null!=input[_EOR]&&bn2.c(se_ExistingObjectReplication(input[_EOR]).n(_EOR));null!=input[_Des]&&bn2.c(se_Destination(input[_Des],context2).n(_Des));null!=input[_DMR]&&bn2.c(se_DeleteMarkerReplication(input[_DMR]).n(_DMR));return bn2};se_ReplicationRuleAndOperator=(input,context2)=>{const bn2=new XmlNode(_RRAO);bn2.cc(input,_P);bn2.l(input,"Tags","Tag",(()=>se_TagSet(input[_Tag],context2)));return bn2};se_ReplicationRuleFilter=(input,context2)=>{const bn2=new XmlNode(_RRF);bn2.cc(input,_P);null!=input[_Ta]&&bn2.c(se_Tag(input[_Ta],context2).n(_Ta));null!=input[_A]&&bn2.c(se_ReplicationRuleAndOperator(input[_A],context2).n(_A));return bn2};se_ReplicationRules=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_ReplicationRule(entry,context2).n(_me)));se_ReplicationTime=(input,context2)=>{const bn2=new XmlNode(_RTe);null!=input[_S]&&bn2.c(XmlNode.of(_RTS,input[_S]).n(_S));null!=input[_Tim]&&bn2.c(se_ReplicationTimeValue(input[_Tim],context2).n(_Tim));return bn2};se_ReplicationTimeValue=(input,context2)=>{const bn2=new XmlNode(_RTV);null!=input[_Mi]&&bn2.c(XmlNode.of(_Mi,String(input[_Mi])).n(_Mi));return bn2};se_RequestPaymentConfiguration=(input,context2)=>{const bn2=new XmlNode(_RPC);bn2.cc(input,_Pa);return bn2};se_RequestProgress=(input,context2)=>{const bn2=new XmlNode(_RPe);null!=input[_Ena]&&bn2.c(XmlNode.of(_ERP,String(input[_Ena])).n(_Ena));return bn2};se_RestoreRequest=(input,context2)=>{const bn2=new XmlNode(_RRes);null!=input[_Da]&&bn2.c(XmlNode.of(_Da,String(input[_Da])).n(_Da));null!=input[_GJP]&&bn2.c(se_GlacierJobParameters(input[_GJP]).n(_GJP));null!=input[_Ty]&&bn2.c(XmlNode.of(_RRT,input[_Ty]).n(_Ty));bn2.cc(input,_Ti);bn2.cc(input,_Desc);null!=input[_SP]&&bn2.c(se_SelectParameters(input[_SP],context2).n(_SP));null!=input[_OL]&&bn2.c(se_OutputLocation(input[_OL],context2).n(_OL));return bn2};se_RoutingRule=(input,context2)=>{const bn2=new XmlNode(_RRou);null!=input[_Con]&&bn2.c(se_Condition(input[_Con]).n(_Con));null!=input[_Red]&&bn2.c(se_Redirect(input[_Red]).n(_Red));return bn2};se_RoutingRules=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_RoutingRule(entry).n(_RRou)));se_S3KeyFilter=(input,context2)=>{const bn2=new XmlNode(_SKF);bn2.l(input,"FilterRules","FilterRule",(()=>se_FilterRuleList(input[_FRi])));return bn2};se_S3Location=(input,context2)=>{const bn2=new XmlNode(_SL);bn2.cc(input,_BN);null!=input[_P]&&bn2.c(XmlNode.of(_LP,input[_P]).n(_P));null!=input[_En]&&bn2.c(se_Encryption(input[_En]).n(_En));null!=input[_CACL]&&bn2.c(XmlNode.of(_OCACL,input[_CACL]).n(_CACL));bn2.lc(input,"AccessControlList","AccessControlList",(()=>se_Grants(input[_ACLc],context2)));null!=input[_T]&&bn2.c(se_Tagging(input[_T],context2).n(_T));bn2.lc(input,"UserMetadata","UserMetadata",(()=>se_UserMetadata(input[_UM],context2)));bn2.cc(input,_SC);return bn2};se_S3TablesDestination=(input,context2)=>{const bn2=new XmlNode(_STD);null!=input[_TBA]&&bn2.c(XmlNode.of(_STBA,input[_TBA]).n(_TBA));null!=input[_TN]&&bn2.c(XmlNode.of(_STN,input[_TN]).n(_TN));return bn2};se_ScanRange=(input,context2)=>{const bn2=new XmlNode(_SR);null!=input[_St]&&bn2.c(XmlNode.of(_St,String(input[_St])).n(_St));null!=input[_End]&&bn2.c(XmlNode.of(_End,String(input[_End])).n(_End));return bn2};se_SelectParameters=(input,context2)=>{const bn2=new XmlNode(_SP);null!=input[_IS]&&bn2.c(se_InputSerialization(input[_IS],context2).n(_IS));bn2.cc(input,_ETx);bn2.cc(input,_Ex);null!=input[_OS]&&bn2.c(se_OutputSerialization(input[_OS],context2).n(_OS));return bn2};se_ServerSideEncryptionByDefault=(input,context2)=>{const bn2=new XmlNode(_SSEBD);null!=input[_SSEA]&&bn2.c(XmlNode.of(_SSE,input[_SSEA]).n(_SSEA));null!=input[_KMSMKID]&&bn2.c(XmlNode.of(_SSEKMSKI,input[_KMSMKID]).n(_KMSMKID));return bn2};se_ServerSideEncryptionConfiguration=(input,context2)=>{const bn2=new XmlNode(_SSEC);bn2.l(input,"Rules","Rule",(()=>se_ServerSideEncryptionRules(input[_Rul],context2)));return bn2};se_ServerSideEncryptionRule=(input,context2)=>{const bn2=new XmlNode(_SSER);null!=input[_ASSEBD]&&bn2.c(se_ServerSideEncryptionByDefault(input[_ASSEBD]).n(_ASSEBD));null!=input[_BKE]&&bn2.c(XmlNode.of(_BKE,String(input[_BKE])).n(_BKE));return bn2};se_ServerSideEncryptionRules=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_ServerSideEncryptionRule(entry).n(_me)));se_SimplePrefix=(input,context2)=>new XmlNode(_SPi);se_SourceSelectionCriteria=(input,context2)=>{const bn2=new XmlNode(_SSC);null!=input[_SKEO]&&bn2.c(se_SseKmsEncryptedObjects(input[_SKEO],context2).n(_SKEO));null!=input[_RM]&&bn2.c(se_ReplicaModifications(input[_RM]).n(_RM));return bn2};se_SSEKMS=(input,context2)=>{const bn2=new XmlNode(_SK);null!=input[_KI]&&bn2.c(XmlNode.of(_SSEKMSKI,input[_KI]).n(_KI));return bn2};se_SseKmsEncryptedObjects=(input,context2)=>{const bn2=new XmlNode(_SKEO);null!=input[_S]&&bn2.c(XmlNode.of(_SKEOS,input[_S]).n(_S));return bn2};se_SSES3=(input,context2)=>new XmlNode(_SS);se_StorageClassAnalysis=(input,context2)=>{const bn2=new XmlNode(_SCA);null!=input[_DE]&&bn2.c(se_StorageClassAnalysisDataExport(input[_DE],context2).n(_DE));return bn2};se_StorageClassAnalysisDataExport=(input,context2)=>{const bn2=new XmlNode(_SCADE);null!=input[_OSV]&&bn2.c(XmlNode.of(_SCASV,input[_OSV]).n(_OSV));null!=input[_Des]&&bn2.c(se_AnalyticsExportDestination(input[_Des],context2).n(_Des));return bn2};se_Tag=(input,context2)=>{const bn2=new XmlNode(_Ta);null!=input[_K]&&bn2.c(XmlNode.of(_OK,input[_K]).n(_K));bn2.cc(input,_Va);return bn2};se_Tagging=(input,context2)=>{const bn2=new XmlNode(_T);bn2.lc(input,"TagSet","TagSet",(()=>se_TagSet(input[_TS],context2)));return bn2};se_TagSet=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_Tag(entry,context2).n(_Ta)));se_TargetGrant=(input,context2)=>{const bn2=new XmlNode(_TGa);if(null!=input[_Gra]){const n3=se_Grantee(input[_Gra],context2).n(_Gra);n3.a("xmlns:xsi","http://www.w3.org/2001/XMLSchema-instance");bn2.c(n3)}null!=input[_Pe]&&bn2.c(XmlNode.of(_BLP,input[_Pe]).n(_Pe));return bn2};se_TargetGrants=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_TargetGrant(entry,context2).n(_G)));se_TargetObjectKeyFormat=(input,context2)=>{const bn2=new XmlNode(_TOKF);null!=input[_SPi]&&bn2.c(se_SimplePrefix(input[_SPi]).n(_SPi));null!=input[_PP]&&bn2.c(se_PartitionedPrefix(input[_PP]).n(_PP));return bn2};se_Tiering=(input,context2)=>{const bn2=new XmlNode(_Tier);null!=input[_Da]&&bn2.c(XmlNode.of(_ITD,String(input[_Da])).n(_Da));null!=input[_AT]&&bn2.c(XmlNode.of(_ITAT,input[_AT]).n(_AT));return bn2};se_TieringList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_Tiering(entry).n(_me)));se_TopicConfiguration=(input,context2)=>{const bn2=new XmlNode(_TCo);null!=input[_I]&&bn2.c(XmlNode.of(_NI,input[_I]).n(_I));null!=input[_TA]&&bn2.c(XmlNode.of(_TA,input[_TA]).n(_Top));bn2.l(input,"Events","Event",(()=>se_EventList(input[_Eve])));null!=input[_F]&&bn2.c(se_NotificationConfigurationFilter(input[_F],context2).n(_F));return bn2};se_TopicConfigurationList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_TopicConfiguration(entry,context2).n(_me)));se_Transition=(input,context2)=>{const bn2=new XmlNode(_Tra);null!=input[_Dat]&&bn2.c(XmlNode.of(_Dat,serializeDateTime(input[_Dat]).toString()).n(_Dat));null!=input[_Da]&&bn2.c(XmlNode.of(_Da,String(input[_Da])).n(_Da));null!=input[_SC]&&bn2.c(XmlNode.of(_TSC,input[_SC]).n(_SC));return bn2};se_TransitionList=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_Transition(entry).n(_me)));se_UserMetadata=(input,context2)=>input.filter((e3=>null!=e3)).map((entry=>se_MetadataEntry(entry).n(_ME)));se_VersioningConfiguration=(input,context2)=>{const bn2=new XmlNode(_VCe);null!=input[_MFAD]&&bn2.c(XmlNode.of(_MFAD,input[_MFAD]).n(_MDf));null!=input[_S]&&bn2.c(XmlNode.of(_BVS,input[_S]).n(_S));return bn2};se_WebsiteConfiguration=(input,context2)=>{const bn2=new XmlNode(_WC);null!=input[_ED]&&bn2.c(se_ErrorDocument(input[_ED]).n(_ED));null!=input[_ID]&&bn2.c(se_IndexDocument(input[_ID]).n(_ID));null!=input[_RART]&&bn2.c(se_RedirectAllRequestsTo(input[_RART]).n(_RART));bn2.lc(input,"RoutingRules","RoutingRules",(()=>se_RoutingRules(input[_RRo])));return bn2};de_AbortIncompleteMultipartUpload=(output,context2)=>{const contents={};null!=output[_DAI]&&(contents[_DAI]=strictParseInt32(output[_DAI]));return contents};de_AccessControlTranslation=(output,context2)=>{const contents={};null!=output[_O]&&(contents[_O]=expectString(output[_O]));return contents};de_AllowedHeaders=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_AllowedMethods=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_AllowedOrigins=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_AnalyticsAndOperator=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));""===output.Tag?contents[_Tag]=[]:null!=output[_Ta]&&(contents[_Tag]=de_TagSet(getArrayIfSingleItem(output[_Ta]),context2));return contents};de_AnalyticsConfiguration=(output,context2)=>{const contents={};null!=output[_I]&&(contents[_I]=expectString(output[_I]));""===output.Filter||null!=output[_F]&&(contents[_F]=de_AnalyticsFilter(expectUnion(output[_F]),context2));null!=output[_SCA]&&(contents[_SCA]=de_StorageClassAnalysis(output[_SCA],context2));return contents};de_AnalyticsConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_AnalyticsConfiguration(entry,context2)));de_AnalyticsExportDestination=(output,context2)=>{const contents={};null!=output[_SBD]&&(contents[_SBD]=de_AnalyticsS3BucketDestination(output[_SBD],context2));return contents};de_AnalyticsFilter=(output,context2)=>null!=output[_P]?{Prefix:expectString(output[_P])}:null!=output[_Ta]?{Tag:de_Tag(output[_Ta],context2)}:null!=output[_A]?{And:de_AnalyticsAndOperator(output[_A],context2)}:{$unknown:Object.entries(output)[0]};de_AnalyticsS3BucketDestination=(output,context2)=>{const contents={};null!=output[_Fo]&&(contents[_Fo]=expectString(output[_Fo]));null!=output[_BAI]&&(contents[_BAI]=expectString(output[_BAI]));null!=output[_B]&&(contents[_B]=expectString(output[_B]));null!=output[_P]&&(contents[_P]=expectString(output[_P]));return contents};de_Bucket=(output,context2)=>{const contents={};null!=output[_N]&&(contents[_N]=expectString(output[_N]));null!=output[_CDr]&&(contents[_CDr]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_CDr])));null!=output[_BR]&&(contents[_BR]=expectString(output[_BR]));return contents};de_Buckets=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_Bucket(entry)));de_Checksum=(output,context2)=>{const contents={};null!=output[_CCRC]&&(contents[_CCRC]=expectString(output[_CCRC]));null!=output[_CCRCC]&&(contents[_CCRCC]=expectString(output[_CCRCC]));null!=output[_CCRCNVME]&&(contents[_CCRCNVME]=expectString(output[_CCRCNVME]));null!=output[_CSHA]&&(contents[_CSHA]=expectString(output[_CSHA]));null!=output[_CSHAh]&&(contents[_CSHAh]=expectString(output[_CSHAh]));null!=output[_CT]&&(contents[_CT]=expectString(output[_CT]));return contents};de_ChecksumAlgorithmList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_CommonPrefix=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));return contents};de_CommonPrefixList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_CommonPrefix(entry)));de_Condition=(output,context2)=>{const contents={};null!=output[_HECRE]&&(contents[_HECRE]=expectString(output[_HECRE]));null!=output[_KPE]&&(contents[_KPE]=expectString(output[_KPE]));return contents};de_ContinuationEvent=(output,context2)=>({});de_CopyObjectResult=(output,context2)=>{const contents={};null!=output[_ETa]&&(contents[_ETa]=expectString(output[_ETa]));null!=output[_LM]&&(contents[_LM]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM])));null!=output[_CT]&&(contents[_CT]=expectString(output[_CT]));null!=output[_CCRC]&&(contents[_CCRC]=expectString(output[_CCRC]));null!=output[_CCRCC]&&(contents[_CCRCC]=expectString(output[_CCRCC]));null!=output[_CCRCNVME]&&(contents[_CCRCNVME]=expectString(output[_CCRCNVME]));null!=output[_CSHA]&&(contents[_CSHA]=expectString(output[_CSHA]));null!=output[_CSHAh]&&(contents[_CSHAh]=expectString(output[_CSHAh]));return contents};de_CopyPartResult=(output,context2)=>{const contents={};null!=output[_ETa]&&(contents[_ETa]=expectString(output[_ETa]));null!=output[_LM]&&(contents[_LM]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM])));null!=output[_CCRC]&&(contents[_CCRC]=expectString(output[_CCRC]));null!=output[_CCRCC]&&(contents[_CCRCC]=expectString(output[_CCRCC]));null!=output[_CCRCNVME]&&(contents[_CCRCNVME]=expectString(output[_CCRCNVME]));null!=output[_CSHA]&&(contents[_CSHA]=expectString(output[_CSHA]));null!=output[_CSHAh]&&(contents[_CSHAh]=expectString(output[_CSHAh]));return contents};de_CORSRule=(output,context2)=>{const contents={};null!=output[_ID_]&&(contents[_ID_]=expectString(output[_ID_]));""===output.AllowedHeader?contents[_AHl]=[]:null!=output[_AH]&&(contents[_AHl]=de_AllowedHeaders(getArrayIfSingleItem(output[_AH])));""===output.AllowedMethod?contents[_AMl]=[]:null!=output[_AM]&&(contents[_AMl]=de_AllowedMethods(getArrayIfSingleItem(output[_AM])));""===output.AllowedOrigin?contents[_AOl]=[]:null!=output[_AO]&&(contents[_AOl]=de_AllowedOrigins(getArrayIfSingleItem(output[_AO])));""===output.ExposeHeader?contents[_EH]=[]:null!=output[_EHx]&&(contents[_EH]=de_ExposeHeaders(getArrayIfSingleItem(output[_EHx]),context2));null!=output[_MAS]&&(contents[_MAS]=strictParseInt32(output[_MAS]));return contents};de_CORSRules=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_CORSRule(entry,context2)));de_DefaultRetention=(output,context2)=>{const contents={};null!=output[_Mo]&&(contents[_Mo]=expectString(output[_Mo]));null!=output[_Da]&&(contents[_Da]=strictParseInt32(output[_Da]));null!=output[_Y]&&(contents[_Y]=strictParseInt32(output[_Y]));return contents};de_DeletedObject=(output,context2)=>{const contents={};null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_VI]&&(contents[_VI]=expectString(output[_VI]));null!=output[_DM]&&(contents[_DM]=parseBoolean(output[_DM]));null!=output[_DMVI]&&(contents[_DMVI]=expectString(output[_DMVI]));return contents};de_DeletedObjects=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_DeletedObject(entry)));de_DeleteMarkerEntry=(output,context2)=>{const contents={};null!=output[_O]&&(contents[_O]=de_Owner(output[_O],context2));null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_VI]&&(contents[_VI]=expectString(output[_VI]));null!=output[_IL]&&(contents[_IL]=parseBoolean(output[_IL]));null!=output[_LM]&&(contents[_LM]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM])));return contents};de_DeleteMarkerReplication=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));return contents};de_DeleteMarkers=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_DeleteMarkerEntry(entry,context2)));de_Destination=(output,context2)=>{const contents={};null!=output[_B]&&(contents[_B]=expectString(output[_B]));null!=output[_Ac]&&(contents[_Ac]=expectString(output[_Ac]));null!=output[_SC]&&(contents[_SC]=expectString(output[_SC]));null!=output[_ACT]&&(contents[_ACT]=de_AccessControlTranslation(output[_ACT]));null!=output[_ECn]&&(contents[_ECn]=de_EncryptionConfiguration(output[_ECn],context2));null!=output[_RTe]&&(contents[_RTe]=de_ReplicationTime(output[_RTe],context2));null!=output[_Me]&&(contents[_Me]=de_Metrics(output[_Me],context2));return contents};de_EncryptionConfiguration=(output,context2)=>{const contents={};null!=output[_RKKID]&&(contents[_RKKID]=expectString(output[_RKKID]));return contents};de_EndEvent=(output,context2)=>({});de__Error=(output,context2)=>{const contents={};null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_VI]&&(contents[_VI]=expectString(output[_VI]));null!=output[_Cod]&&(contents[_Cod]=expectString(output[_Cod]));null!=output[_Mes]&&(contents[_Mes]=expectString(output[_Mes]));return contents};de_ErrorDetails=(output,context2)=>{const contents={};null!=output[_EC]&&(contents[_EC]=expectString(output[_EC]));null!=output[_EM]&&(contents[_EM]=expectString(output[_EM]));return contents};de_ErrorDocument=(output,context2)=>{const contents={};null!=output[_K]&&(contents[_K]=expectString(output[_K]));return contents};de_Errors=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de__Error(entry)));de_EventBridgeConfiguration=(output,context2)=>({});de_EventList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_ExistingObjectReplication=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));return contents};de_ExposeHeaders=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_FilterRule=(output,context2)=>{const contents={};null!=output[_N]&&(contents[_N]=expectString(output[_N]));null!=output[_Va]&&(contents[_Va]=expectString(output[_Va]));return contents};de_FilterRuleList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_FilterRule(entry)));de_GetBucketMetadataTableConfigurationResult=(output,context2)=>{const contents={};null!=output[_MTCR]&&(contents[_MTCR]=de_MetadataTableConfigurationResult(output[_MTCR],context2));null!=output[_S]&&(contents[_S]=expectString(output[_S]));null!=output[_Er]&&(contents[_Er]=de_ErrorDetails(output[_Er]));return contents};de_GetObjectAttributesParts=(output,context2)=>{const contents={};null!=output[_PC]&&(contents[_TPC]=strictParseInt32(output[_PC]));null!=output[_PNM]&&(contents[_PNM]=expectString(output[_PNM]));null!=output[_NPNM]&&(contents[_NPNM]=expectString(output[_NPNM]));null!=output[_MP]&&(contents[_MP]=strictParseInt32(output[_MP]));null!=output[_IT]&&(contents[_IT]=parseBoolean(output[_IT]));""===output.Part?contents[_Part]=[]:null!=output[_Par]&&(contents[_Part]=de_PartsList(getArrayIfSingleItem(output[_Par]),context2));return contents};de_Grant=(output,context2)=>{const contents={};null!=output[_Gra]&&(contents[_Gra]=de_Grantee(output[_Gra],context2));null!=output[_Pe]&&(contents[_Pe]=expectString(output[_Pe]));return contents};de_Grantee=(output,context2)=>{const contents={};null!=output[_DN]&&(contents[_DN]=expectString(output[_DN]));null!=output[_EA]&&(contents[_EA]=expectString(output[_EA]));null!=output[_ID_]&&(contents[_ID_]=expectString(output[_ID_]));null!=output[_URI]&&(contents[_URI]=expectString(output[_URI]));null!=output[_x]&&(contents[_Ty]=expectString(output[_x]));return contents};de_Grants=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_Grant(entry,context2)));de_IndexDocument=(output,context2)=>{const contents={};null!=output[_Su]&&(contents[_Su]=expectString(output[_Su]));return contents};de_Initiator=(output,context2)=>{const contents={};null!=output[_ID_]&&(contents[_ID_]=expectString(output[_ID_]));null!=output[_DN]&&(contents[_DN]=expectString(output[_DN]));return contents};de_IntelligentTieringAndOperator=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));""===output.Tag?contents[_Tag]=[]:null!=output[_Ta]&&(contents[_Tag]=de_TagSet(getArrayIfSingleItem(output[_Ta]),context2));return contents};de_IntelligentTieringConfiguration=(output,context2)=>{const contents={};null!=output[_I]&&(contents[_I]=expectString(output[_I]));null!=output[_F]&&(contents[_F]=de_IntelligentTieringFilter(output[_F],context2));null!=output[_S]&&(contents[_S]=expectString(output[_S]));""===output.Tiering?contents[_Tie]=[]:null!=output[_Tier]&&(contents[_Tie]=de_TieringList(getArrayIfSingleItem(output[_Tier]),context2));return contents};de_IntelligentTieringConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_IntelligentTieringConfiguration(entry,context2)));de_IntelligentTieringFilter=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));null!=output[_Ta]&&(contents[_Ta]=de_Tag(output[_Ta],context2));null!=output[_A]&&(contents[_A]=de_IntelligentTieringAndOperator(output[_A],context2));return contents};de_InventoryConfiguration=(output,context2)=>{const contents={};null!=output[_Des]&&(contents[_Des]=de_InventoryDestination(output[_Des],context2));null!=output[_IE]&&(contents[_IE]=parseBoolean(output[_IE]));null!=output[_F]&&(contents[_F]=de_InventoryFilter(output[_F],context2));null!=output[_I]&&(contents[_I]=expectString(output[_I]));null!=output[_IOV]&&(contents[_IOV]=expectString(output[_IOV]));""===output.OptionalFields?contents[_OF]=[]:null!=output[_OF]&&null!=output[_OF][_Fi]&&(contents[_OF]=de_InventoryOptionalFields(getArrayIfSingleItem(output[_OF][_Fi]),context2));null!=output[_Sc]&&(contents[_Sc]=de_InventorySchedule(output[_Sc],context2));return contents};de_InventoryConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_InventoryConfiguration(entry,context2)));de_InventoryDestination=(output,context2)=>{const contents={};null!=output[_SBD]&&(contents[_SBD]=de_InventoryS3BucketDestination(output[_SBD],context2));return contents};de_InventoryEncryption=(output,context2)=>{const contents={};null!=output[_SS]&&(contents[_SSES]=de_SSES3(output[_SS],context2));null!=output[_SK]&&(contents[_SSEKMS]=de_SSEKMS(output[_SK],context2));return contents};de_InventoryFilter=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));return contents};de_InventoryOptionalFields=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>expectString(entry)));de_InventoryS3BucketDestination=(output,context2)=>{const contents={};null!=output[_AIc]&&(contents[_AIc]=expectString(output[_AIc]));null!=output[_B]&&(contents[_B]=expectString(output[_B]));null!=output[_Fo]&&(contents[_Fo]=expectString(output[_Fo]));null!=output[_P]&&(contents[_P]=expectString(output[_P]));null!=output[_En]&&(contents[_En]=de_InventoryEncryption(output[_En],context2));return contents};de_InventorySchedule=(output,context2)=>{const contents={};null!=output[_Fr]&&(contents[_Fr]=expectString(output[_Fr]));return contents};de_LambdaFunctionConfiguration=(output,context2)=>{const contents={};null!=output[_I]&&(contents[_I]=expectString(output[_I]));null!=output[_CF]&&(contents[_LFA]=expectString(output[_CF]));""===output.Event?contents[_Eve]=[]:null!=output[_Ev]&&(contents[_Eve]=de_EventList(getArrayIfSingleItem(output[_Ev])));null!=output[_F]&&(contents[_F]=de_NotificationConfigurationFilter(output[_F],context2));return contents};de_LambdaFunctionConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_LambdaFunctionConfiguration(entry,context2)));de_LifecycleExpiration=(output,context2)=>{const contents={};null!=output[_Dat]&&(contents[_Dat]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_Dat])));null!=output[_Da]&&(contents[_Da]=strictParseInt32(output[_Da]));null!=output[_EODM]&&(contents[_EODM]=parseBoolean(output[_EODM]));return contents};de_LifecycleRule=(output,context2)=>{const contents={};null!=output[_Exp]&&(contents[_Exp]=de_LifecycleExpiration(output[_Exp]));null!=output[_ID_]&&(contents[_ID_]=expectString(output[_ID_]));null!=output[_P]&&(contents[_P]=expectString(output[_P]));null!=output[_F]&&(contents[_F]=de_LifecycleRuleFilter(output[_F],context2));null!=output[_S]&&(contents[_S]=expectString(output[_S]));""===output.Transition?contents[_Tr]=[]:null!=output[_Tra]&&(contents[_Tr]=de_TransitionList(getArrayIfSingleItem(output[_Tra]),context2));""===output.NoncurrentVersionTransition?contents[_NVT]=[]:null!=output[_NVTo]&&(contents[_NVT]=de_NoncurrentVersionTransitionList(getArrayIfSingleItem(output[_NVTo]),context2));null!=output[_NVE]&&(contents[_NVE]=de_NoncurrentVersionExpiration(output[_NVE],context2));null!=output[_AIMU]&&(contents[_AIMU]=de_AbortIncompleteMultipartUpload(output[_AIMU]));return contents};de_LifecycleRuleAndOperator=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));""===output.Tag?contents[_Tag]=[]:null!=output[_Ta]&&(contents[_Tag]=de_TagSet(getArrayIfSingleItem(output[_Ta]),context2));null!=output[_OSGT]&&(contents[_OSGT]=strictParseLong(output[_OSGT]));null!=output[_OSLT]&&(contents[_OSLT]=strictParseLong(output[_OSLT]));return contents};de_LifecycleRuleFilter=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));null!=output[_Ta]&&(contents[_Ta]=de_Tag(output[_Ta],context2));null!=output[_OSGT]&&(contents[_OSGT]=strictParseLong(output[_OSGT]));null!=output[_OSLT]&&(contents[_OSLT]=strictParseLong(output[_OSLT]));null!=output[_A]&&(contents[_A]=de_LifecycleRuleAndOperator(output[_A],context2));return contents};de_LifecycleRules=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_LifecycleRule(entry,context2)));de_LoggingEnabled=(output,context2)=>{const contents={};null!=output[_TB]&&(contents[_TB]=expectString(output[_TB]));""===output.TargetGrants?contents[_TG]=[]:null!=output[_TG]&&null!=output[_TG][_G]&&(contents[_TG]=de_TargetGrants(getArrayIfSingleItem(output[_TG][_G]),context2));null!=output[_TP]&&(contents[_TP]=expectString(output[_TP]));null!=output[_TOKF]&&(contents[_TOKF]=de_TargetObjectKeyFormat(output[_TOKF],context2));return contents};de_MetadataTableConfigurationResult=(output,context2)=>{const contents={};null!=output[_STDR]&&(contents[_STDR]=de_S3TablesDestinationResult(output[_STDR],context2));return contents};de_Metrics=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));null!=output[_ETv]&&(contents[_ETv]=de_ReplicationTimeValue(output[_ETv],context2));return contents};de_MetricsAndOperator=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));""===output.Tag?contents[_Tag]=[]:null!=output[_Ta]&&(contents[_Tag]=de_TagSet(getArrayIfSingleItem(output[_Ta]),context2));null!=output[_APAc]&&(contents[_APAc]=expectString(output[_APAc]));return contents};de_MetricsConfiguration=(output,context2)=>{const contents={};null!=output[_I]&&(contents[_I]=expectString(output[_I]));""===output.Filter||null!=output[_F]&&(contents[_F]=de_MetricsFilter(expectUnion(output[_F]),context2));return contents};de_MetricsConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_MetricsConfiguration(entry,context2)));de_MetricsFilter=(output,context2)=>null!=output[_P]?{Prefix:expectString(output[_P])}:null!=output[_Ta]?{Tag:de_Tag(output[_Ta],context2)}:null!=output[_APAc]?{AccessPointArn:expectString(output[_APAc])}:null!=output[_A]?{And:de_MetricsAndOperator(output[_A],context2)}:{$unknown:Object.entries(output)[0]};de_MultipartUpload=(output,context2)=>{const contents={};null!=output[_UI]&&(contents[_UI]=expectString(output[_UI]));null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_Ini]&&(contents[_Ini]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_Ini])));null!=output[_SC]&&(contents[_SC]=expectString(output[_SC]));null!=output[_O]&&(contents[_O]=de_Owner(output[_O],context2));null!=output[_In]&&(contents[_In]=de_Initiator(output[_In],context2));null!=output[_CA]&&(contents[_CA]=expectString(output[_CA]));null!=output[_CT]&&(contents[_CT]=expectString(output[_CT]));return contents};de_MultipartUploadList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_MultipartUpload(entry,context2)));de_NoncurrentVersionExpiration=(output,context2)=>{const contents={};null!=output[_ND]&&(contents[_ND]=strictParseInt32(output[_ND]));null!=output[_NNV]&&(contents[_NNV]=strictParseInt32(output[_NNV]));return contents};de_NoncurrentVersionTransition=(output,context2)=>{const contents={};null!=output[_ND]&&(contents[_ND]=strictParseInt32(output[_ND]));null!=output[_SC]&&(contents[_SC]=expectString(output[_SC]));null!=output[_NNV]&&(contents[_NNV]=strictParseInt32(output[_NNV]));return contents};de_NoncurrentVersionTransitionList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_NoncurrentVersionTransition(entry)));de_NotificationConfigurationFilter=(output,context2)=>{const contents={};null!=output[_SKe]&&(contents[_K]=de_S3KeyFilter(output[_SKe],context2));return contents};de__Object=(output,context2)=>{const contents={};null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_LM]&&(contents[_LM]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM])));null!=output[_ETa]&&(contents[_ETa]=expectString(output[_ETa]));""===output.ChecksumAlgorithm?contents[_CA]=[]:null!=output[_CA]&&(contents[_CA]=de_ChecksumAlgorithmList(getArrayIfSingleItem(output[_CA])));null!=output[_CT]&&(contents[_CT]=expectString(output[_CT]));null!=output[_Si]&&(contents[_Si]=strictParseLong(output[_Si]));null!=output[_SC]&&(contents[_SC]=expectString(output[_SC]));null!=output[_O]&&(contents[_O]=de_Owner(output[_O],context2));null!=output[_RSe]&&(contents[_RSe]=de_RestoreStatus(output[_RSe],context2));return contents};de_ObjectList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de__Object(entry,context2)));de_ObjectLockConfiguration=(output,context2)=>{const contents={};null!=output[_OLE]&&(contents[_OLE]=expectString(output[_OLE]));null!=output[_Ru]&&(contents[_Ru]=de_ObjectLockRule(output[_Ru],context2));return contents};de_ObjectLockLegalHold=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));return contents};de_ObjectLockRetention=(output,context2)=>{const contents={};null!=output[_Mo]&&(contents[_Mo]=expectString(output[_Mo]));null!=output[_RUD]&&(contents[_RUD]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_RUD])));return contents};de_ObjectLockRule=(output,context2)=>{const contents={};null!=output[_DRe]&&(contents[_DRe]=de_DefaultRetention(output[_DRe]));return contents};de_ObjectPart=(output,context2)=>{const contents={};null!=output[_PN]&&(contents[_PN]=strictParseInt32(output[_PN]));null!=output[_Si]&&(contents[_Si]=strictParseLong(output[_Si]));null!=output[_CCRC]&&(contents[_CCRC]=expectString(output[_CCRC]));null!=output[_CCRCC]&&(contents[_CCRCC]=expectString(output[_CCRCC]));null!=output[_CCRCNVME]&&(contents[_CCRCNVME]=expectString(output[_CCRCNVME]));null!=output[_CSHA]&&(contents[_CSHA]=expectString(output[_CSHA]));null!=output[_CSHAh]&&(contents[_CSHAh]=expectString(output[_CSHAh]));return contents};de_ObjectVersion=(output,context2)=>{const contents={};null!=output[_ETa]&&(contents[_ETa]=expectString(output[_ETa]));""===output.ChecksumAlgorithm?contents[_CA]=[]:null!=output[_CA]&&(contents[_CA]=de_ChecksumAlgorithmList(getArrayIfSingleItem(output[_CA])));null!=output[_CT]&&(contents[_CT]=expectString(output[_CT]));null!=output[_Si]&&(contents[_Si]=strictParseLong(output[_Si]));null!=output[_SC]&&(contents[_SC]=expectString(output[_SC]));null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_VI]&&(contents[_VI]=expectString(output[_VI]));null!=output[_IL]&&(contents[_IL]=parseBoolean(output[_IL]));null!=output[_LM]&&(contents[_LM]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM])));null!=output[_O]&&(contents[_O]=de_Owner(output[_O],context2));null!=output[_RSe]&&(contents[_RSe]=de_RestoreStatus(output[_RSe],context2));return contents};de_ObjectVersionList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_ObjectVersion(entry,context2)));de_Owner=(output,context2)=>{const contents={};null!=output[_DN]&&(contents[_DN]=expectString(output[_DN]));null!=output[_ID_]&&(contents[_ID_]=expectString(output[_ID_]));return contents};de_OwnershipControls=(output,context2)=>{const contents={};""===output.Rule?contents[_Rul]=[]:null!=output[_Ru]&&(contents[_Rul]=de_OwnershipControlsRules(getArrayIfSingleItem(output[_Ru]),context2));return contents};de_OwnershipControlsRule=(output,context2)=>{const contents={};null!=output[_OO]&&(contents[_OO]=expectString(output[_OO]));return contents};de_OwnershipControlsRules=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_OwnershipControlsRule(entry)));de_Part=(output,context2)=>{const contents={};null!=output[_PN]&&(contents[_PN]=strictParseInt32(output[_PN]));null!=output[_LM]&&(contents[_LM]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_LM])));null!=output[_ETa]&&(contents[_ETa]=expectString(output[_ETa]));null!=output[_Si]&&(contents[_Si]=strictParseLong(output[_Si]));null!=output[_CCRC]&&(contents[_CCRC]=expectString(output[_CCRC]));null!=output[_CCRCC]&&(contents[_CCRCC]=expectString(output[_CCRCC]));null!=output[_CCRCNVME]&&(contents[_CCRCNVME]=expectString(output[_CCRCNVME]));null!=output[_CSHA]&&(contents[_CSHA]=expectString(output[_CSHA]));null!=output[_CSHAh]&&(contents[_CSHAh]=expectString(output[_CSHAh]));return contents};de_PartitionedPrefix=(output,context2)=>{const contents={};null!=output[_PDS]&&(contents[_PDS]=expectString(output[_PDS]));return contents};de_Parts=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_Part(entry)));de_PartsList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_ObjectPart(entry)));de_PolicyStatus=(output,context2)=>{const contents={};null!=output[_IP]&&(contents[_IP]=parseBoolean(output[_IP]));return contents};de_Progress=(output,context2)=>{const contents={};null!=output[_BS]&&(contents[_BS]=strictParseLong(output[_BS]));null!=output[_BP]&&(contents[_BP]=strictParseLong(output[_BP]));null!=output[_BRy]&&(contents[_BRy]=strictParseLong(output[_BRy]));return contents};de_PublicAccessBlockConfiguration=(output,context2)=>{const contents={};null!=output[_BPA]&&(contents[_BPA]=parseBoolean(output[_BPA]));null!=output[_IPA]&&(contents[_IPA]=parseBoolean(output[_IPA]));null!=output[_BPP]&&(contents[_BPP]=parseBoolean(output[_BPP]));null!=output[_RPB]&&(contents[_RPB]=parseBoolean(output[_RPB]));return contents};de_QueueConfiguration=(output,context2)=>{const contents={};null!=output[_I]&&(contents[_I]=expectString(output[_I]));null!=output[_Qu]&&(contents[_QA]=expectString(output[_Qu]));""===output.Event?contents[_Eve]=[]:null!=output[_Ev]&&(contents[_Eve]=de_EventList(getArrayIfSingleItem(output[_Ev])));null!=output[_F]&&(contents[_F]=de_NotificationConfigurationFilter(output[_F],context2));return contents};de_QueueConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_QueueConfiguration(entry,context2)));de_Redirect=(output,context2)=>{const contents={};null!=output[_HN]&&(contents[_HN]=expectString(output[_HN]));null!=output[_HRC]&&(contents[_HRC]=expectString(output[_HRC]));null!=output[_Pr]&&(contents[_Pr]=expectString(output[_Pr]));null!=output[_RKPW]&&(contents[_RKPW]=expectString(output[_RKPW]));null!=output[_RKW]&&(contents[_RKW]=expectString(output[_RKW]));return contents};de_RedirectAllRequestsTo=(output,context2)=>{const contents={};null!=output[_HN]&&(contents[_HN]=expectString(output[_HN]));null!=output[_Pr]&&(contents[_Pr]=expectString(output[_Pr]));return contents};de_ReplicaModifications=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));return contents};de_ReplicationConfiguration=(output,context2)=>{const contents={};null!=output[_Ro]&&(contents[_Ro]=expectString(output[_Ro]));""===output.Rule?contents[_Rul]=[]:null!=output[_Ru]&&(contents[_Rul]=de_ReplicationRules(getArrayIfSingleItem(output[_Ru]),context2));return contents};de_ReplicationRule=(output,context2)=>{const contents={};null!=output[_ID_]&&(contents[_ID_]=expectString(output[_ID_]));null!=output[_Pri]&&(contents[_Pri]=strictParseInt32(output[_Pri]));null!=output[_P]&&(contents[_P]=expectString(output[_P]));null!=output[_F]&&(contents[_F]=de_ReplicationRuleFilter(output[_F],context2));null!=output[_S]&&(contents[_S]=expectString(output[_S]));null!=output[_SSC]&&(contents[_SSC]=de_SourceSelectionCriteria(output[_SSC],context2));null!=output[_EOR]&&(contents[_EOR]=de_ExistingObjectReplication(output[_EOR]));null!=output[_Des]&&(contents[_Des]=de_Destination(output[_Des],context2));null!=output[_DMR]&&(contents[_DMR]=de_DeleteMarkerReplication(output[_DMR]));return contents};de_ReplicationRuleAndOperator=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));""===output.Tag?contents[_Tag]=[]:null!=output[_Ta]&&(contents[_Tag]=de_TagSet(getArrayIfSingleItem(output[_Ta]),context2));return contents};de_ReplicationRuleFilter=(output,context2)=>{const contents={};null!=output[_P]&&(contents[_P]=expectString(output[_P]));null!=output[_Ta]&&(contents[_Ta]=de_Tag(output[_Ta],context2));null!=output[_A]&&(contents[_A]=de_ReplicationRuleAndOperator(output[_A],context2));return contents};de_ReplicationRules=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_ReplicationRule(entry,context2)));de_ReplicationTime=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));null!=output[_Tim]&&(contents[_Tim]=de_ReplicationTimeValue(output[_Tim],context2));return contents};de_ReplicationTimeValue=(output,context2)=>{const contents={};null!=output[_Mi]&&(contents[_Mi]=strictParseInt32(output[_Mi]));return contents};de_RestoreStatus=(output,context2)=>{const contents={};null!=output[_IRIP]&&(contents[_IRIP]=parseBoolean(output[_IRIP]));null!=output[_RED]&&(contents[_RED]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_RED])));return contents};de_RoutingRule=(output,context2)=>{const contents={};null!=output[_Con]&&(contents[_Con]=de_Condition(output[_Con]));null!=output[_Red]&&(contents[_Red]=de_Redirect(output[_Red]));return contents};de_RoutingRules=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_RoutingRule(entry)));de_S3KeyFilter=(output,context2)=>{const contents={};""===output.FilterRule?contents[_FRi]=[]:null!=output[_FR]&&(contents[_FRi]=de_FilterRuleList(getArrayIfSingleItem(output[_FR])));return contents};de_S3TablesDestinationResult=(output,context2)=>{const contents={};null!=output[_TBA]&&(contents[_TBA]=expectString(output[_TBA]));null!=output[_TN]&&(contents[_TN]=expectString(output[_TN]));null!=output[_TAa]&&(contents[_TAa]=expectString(output[_TAa]));null!=output[_TNa]&&(contents[_TNa]=expectString(output[_TNa]));return contents};de_ServerSideEncryptionByDefault=(output,context2)=>{const contents={};null!=output[_SSEA]&&(contents[_SSEA]=expectString(output[_SSEA]));null!=output[_KMSMKID]&&(contents[_KMSMKID]=expectString(output[_KMSMKID]));return contents};de_ServerSideEncryptionConfiguration=(output,context2)=>{const contents={};""===output.Rule?contents[_Rul]=[]:null!=output[_Ru]&&(contents[_Rul]=de_ServerSideEncryptionRules(getArrayIfSingleItem(output[_Ru]),context2));return contents};de_ServerSideEncryptionRule=(output,context2)=>{const contents={};null!=output[_ASSEBD]&&(contents[_ASSEBD]=de_ServerSideEncryptionByDefault(output[_ASSEBD]));null!=output[_BKE]&&(contents[_BKE]=parseBoolean(output[_BKE]));return contents};de_ServerSideEncryptionRules=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_ServerSideEncryptionRule(entry)));de_SessionCredentials=(output,context2)=>{const contents={};null!=output[_AKI]&&(contents[_AKI]=expectString(output[_AKI]));null!=output[_SAK]&&(contents[_SAK]=expectString(output[_SAK]));null!=output[_ST]&&(contents[_ST]=expectString(output[_ST]));null!=output[_Exp]&&(contents[_Exp]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_Exp])));return contents};de_SimplePrefix=(output,context2)=>({});de_SourceSelectionCriteria=(output,context2)=>{const contents={};null!=output[_SKEO]&&(contents[_SKEO]=de_SseKmsEncryptedObjects(output[_SKEO],context2));null!=output[_RM]&&(contents[_RM]=de_ReplicaModifications(output[_RM]));return contents};de_SSEKMS=(output,context2)=>{const contents={};null!=output[_KI]&&(contents[_KI]=expectString(output[_KI]));return contents};de_SseKmsEncryptedObjects=(output,context2)=>{const contents={};null!=output[_S]&&(contents[_S]=expectString(output[_S]));return contents};de_SSES3=(output,context2)=>({});de_Stats=(output,context2)=>{const contents={};null!=output[_BS]&&(contents[_BS]=strictParseLong(output[_BS]));null!=output[_BP]&&(contents[_BP]=strictParseLong(output[_BP]));null!=output[_BRy]&&(contents[_BRy]=strictParseLong(output[_BRy]));return contents};de_StorageClassAnalysis=(output,context2)=>{const contents={};null!=output[_DE]&&(contents[_DE]=de_StorageClassAnalysisDataExport(output[_DE],context2));return contents};de_StorageClassAnalysisDataExport=(output,context2)=>{const contents={};null!=output[_OSV]&&(contents[_OSV]=expectString(output[_OSV]));null!=output[_Des]&&(contents[_Des]=de_AnalyticsExportDestination(output[_Des],context2));return contents};de_Tag=(output,context2)=>{const contents={};null!=output[_K]&&(contents[_K]=expectString(output[_K]));null!=output[_Va]&&(contents[_Va]=expectString(output[_Va]));return contents};de_TagSet=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_Tag(entry,context2)));de_TargetGrant=(output,context2)=>{const contents={};null!=output[_Gra]&&(contents[_Gra]=de_Grantee(output[_Gra],context2));null!=output[_Pe]&&(contents[_Pe]=expectString(output[_Pe]));return contents};de_TargetGrants=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_TargetGrant(entry,context2)));de_TargetObjectKeyFormat=(output,context2)=>{const contents={};null!=output[_SPi]&&(contents[_SPi]=de_SimplePrefix(output[_SPi]));null!=output[_PP]&&(contents[_PP]=de_PartitionedPrefix(output[_PP]));return contents};de_Tiering=(output,context2)=>{const contents={};null!=output[_Da]&&(contents[_Da]=strictParseInt32(output[_Da]));null!=output[_AT]&&(contents[_AT]=expectString(output[_AT]));return contents};de_TieringList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_Tiering(entry)));de_TopicConfiguration=(output,context2)=>{const contents={};null!=output[_I]&&(contents[_I]=expectString(output[_I]));null!=output[_Top]&&(contents[_TA]=expectString(output[_Top]));""===output.Event?contents[_Eve]=[]:null!=output[_Ev]&&(contents[_Eve]=de_EventList(getArrayIfSingleItem(output[_Ev])));null!=output[_F]&&(contents[_F]=de_NotificationConfigurationFilter(output[_F],context2));return contents};de_TopicConfigurationList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_TopicConfiguration(entry,context2)));de_Transition=(output,context2)=>{const contents={};null!=output[_Dat]&&(contents[_Dat]=expectNonNull(parseRfc3339DateTimeWithOffset(output[_Dat])));null!=output[_Da]&&(contents[_Da]=strictParseInt32(output[_Da]));null!=output[_SC]&&(contents[_SC]=expectString(output[_SC]));return contents};de_TransitionList=(output,context2)=>(output||[]).filter((e3=>null!=e3)).map((entry=>de_Transition(entry)));deserializeMetadata2=output=>{var _a8,_b5;return{httpStatusCode:output.statusCode,requestId:null!=(_b5=null!=(_a8=output.headers["x-amzn-requestid"])?_a8:output.headers["x-amzn-request-id"])?_b5:output.headers["x-amz-request-id"],extendedRequestId:output.headers["x-amz-id-2"],cfId:output.headers["x-amz-cf-id"]}};collectBodyString2=(streamBody,context2)=>collectBody(streamBody,context2).then((body=>context2.utf8Encoder(body)));_A="And";_AAO="AnalyticsAndOperator";_AC="AnalyticsConfiguration";_ACL="ACL";_ACLc="AccessControlList";_ACLn="AnalyticsConfigurationList";_ACP="AccessControlPolicy";_ACT="AccessControlTranslation";_ACc="AccelerateConfiguration";_AD="AbortDate";_AED="AnalyticsExportDestination";_AF="AnalyticsFilter";_AH="AllowedHeader";_AHl="AllowedHeaders";_AI="AnalyticsId";_AIMU="AbortIncompleteMultipartUpload";_AIc="AccountId";_AKI="AccessKeyId";_AM="AllowedMethod";_AMl="AllowedMethods";_AO="AllowedOrigin";_AOl="AllowedOrigins";_APA="AccessPointAlias";_APAc="AccessPointArn";_AQRD="AllowQuotedRecordDelimiter";_AR="AcceptRanges";_ARI="AbortRuleId";_AS="ArchiveStatus";_ASBD="AnalyticsS3BucketDestination";_ASEFF="AnalyticsS3ExportFileFormat";_ASSEBD="ApplyServerSideEncryptionByDefault";_AT="AccessTier";_Ac="Account";_B="Bucket";_BAI="BucketAccountId";_BAS="BucketAccelerateStatus";_BGR="BypassGovernanceRetention";_BI="BucketInfo";_BKE="BucketKeyEnabled";_BLC="BucketLifecycleConfiguration";_BLCu="BucketLocationConstraint";_BLN="BucketLocationName";_BLP="BucketLogsPermission";_BLS="BucketLoggingStatus";_BLT="BucketLocationType";_BN="BucketName";_BP="BytesProcessed";_BPA="BlockPublicAcls";_BPP="BlockPublicPolicy";_BR="BucketRegion";_BRy="BytesReturned";_BS="BytesScanned";_BT="BucketType";_BVS="BucketVersioningStatus";_Bu="Buckets";_C="Credentials";_CA="ChecksumAlgorithm";_CACL="CannedACL";_CBC="CreateBucketConfiguration";_CC="CacheControl";_CCRC="ChecksumCRC32";_CCRCC="ChecksumCRC32C";_CCRCNVME="ChecksumCRC64NVME";_CD="ContentDisposition";_CDr="CreationDate";_CE="ContentEncoding";_CF="CloudFunction";_CFC="CloudFunctionConfiguration";_CL="ContentLanguage";_CLo="ContentLength";_CM="ChecksumMode";_CMD="ContentMD5";_CMU="CompletedMultipartUpload";_CORSC="CORSConfiguration";_CORSR="CORSRule";_CORSRu="CORSRules";_CP="CommonPrefixes";_CPo="CompletedPart";_CR="ContentRange";_CRSBA="ConfirmRemoveSelfBucketAccess";_CS="CopySource";_CSHA="ChecksumSHA1";_CSHAh="ChecksumSHA256";_CSIM="CopySourceIfMatch";_CSIMS="CopySourceIfModifiedSince";_CSINM="CopySourceIfNoneMatch";_CSIUS="CopySourceIfUnmodifiedSince";_CSR="CopySourceRange";_CSSSECA="CopySourceSSECustomerAlgorithm";_CSSSECK="CopySourceSSECustomerKey";_CSSSECKMD="CopySourceSSECustomerKeyMD5";_CSV="CSV";_CSVI="CopySourceVersionId";_CSVIn="CSVInput";_CSVO="CSVOutput";_CT="ChecksumType";_CTo="ContentType";_CTom="CompressionType";_CTon="ContinuationToken";_Ch="Checksum";_Co="Contents";_Cod="Code";_Com="Comments";_Con="Condition";_D="Delimiter";_DAI="DaysAfterInitiation";_DE="DataExport";_DM="DeleteMarker";_DMR="DeleteMarkerReplication";_DMRS="DeleteMarkerReplicationStatus";_DMVI="DeleteMarkerVersionId";_DMe="DeleteMarkers";_DN="DisplayName";_DR="DataRedundancy";_DRe="DefaultRetention";_Da="Days";_Dat="Date";_De="Deleted";_Del="Delete";_Des="Destination";_Desc="Description";_E="Expires";_EA="EmailAddress";_EBC="EventBridgeConfiguration";_EBO="ExpectedBucketOwner";_EC="ErrorCode";_ECn="EncryptionConfiguration";_ED="ErrorDocument";_EH="ExposeHeaders";_EHx="ExposeHeader";_EM="ErrorMessage";_EODM="ExpiredObjectDeleteMarker";_EOR="ExistingObjectReplication";_EORS="ExistingObjectReplicationStatus";_ERP="EnableRequestProgress";_ES="ExpiresString";_ESBO="ExpectedSourceBucketOwner";_ESx="ExpirationStatus";_ET="EncodingType";_ETa="ETag";_ETn="EncryptionType";_ETv="EventThreshold";_ETx="ExpressionType";_En="Encryption";_Ena="Enabled";_End="End";_Er="Error";_Err="Errors";_Ev="Event";_Eve="Events";_Ex="Expression";_Exp="Expiration";_F="Filter";_FD="FieldDelimiter";_FHI="FileHeaderInfo";_FO="FetchOwner";_FR="FilterRule";_FRN="FilterRuleName";_FRV="FilterRuleValue";_FRi="FilterRules";_Fi="Field";_Fo="Format";_Fr="Frequency";_G="Grant";_GFC="GrantFullControl";_GJP="GlacierJobParameters";_GR="GrantRead";_GRACP="GrantReadACP";_GW="GrantWrite";_GWACP="GrantWriteACP";_Gr="Grants";_Gra="Grantee";_HECRE="HttpErrorCodeReturnedEquals";_HN="HostName";_HRC="HttpRedirectCode";_I="Id";_IC="InventoryConfiguration";_ICL="InventoryConfigurationList";_ID="IndexDocument";_ID_="ID";_IDn="InventoryDestination";_IE="IsEnabled";_IEn="InventoryEncryption";_IF="InventoryFilter";_IFn="InventoryFormat";_IFnv="InventoryFrequency";_II="InventoryId";_IIOV="InventoryIncludedObjectVersions";_IL="IsLatest";_IM="IfMatch";_IMIT="IfMatchInitiatedTime";_IMLMT="IfMatchLastModifiedTime";_IMS="IfMatchSize";_IMSf="IfModifiedSince";_INM="IfNoneMatch";_IOF="InventoryOptionalField";_IOV="IncludedObjectVersions";_IP="IsPublic";_IPA="IgnorePublicAcls";_IRIP="IsRestoreInProgress";_IS="InputSerialization";_ISBD="InventoryS3BucketDestination";_ISn="InventorySchedule";_IT="IsTruncated";_ITAO="IntelligentTieringAndOperator";_ITAT="IntelligentTieringAccessTier";_ITC="IntelligentTieringConfiguration";_ITCL="IntelligentTieringConfigurationList";_ITD="IntelligentTieringDays";_ITF="IntelligentTieringFilter";_ITI="IntelligentTieringId";_ITS="IntelligentTieringStatus";_IUS="IfUnmodifiedSince";_In="Initiator";_Ini="Initiated";_JSON="JSON";_JSONI="JSONInput";_JSONO="JSONOutput";_JSONT="JSONType";_K="Key";_KC="KeyCount";_KI="KeyId";_KM="KeyMarker";_KMSC="KMSContext";_KMSKI="KMSKeyId";_KMSMKID="KMSMasterKeyID";_KPE="KeyPrefixEquals";_L="Location";_LC="LocationConstraint";_LE="LoggingEnabled";_LEi="LifecycleExpiration";_LFA="LambdaFunctionArn";_LFC="LambdaFunctionConfigurations";_LFCa="LambdaFunctionConfiguration";_LI="LocationInfo";_LM="LastModified";_LMT="LastModifiedTime";_LNAS="LocationNameAsString";_LP="LocationPrefix";_LR="LifecycleRule";_LRAO="LifecycleRuleAndOperator";_LRF="LifecycleRuleFilter";_LT="LocationType";_M="Marker";_MAO="MetricsAndOperator";_MAS="MaxAgeSeconds";_MB="MaxBuckets";_MC="MetricsConfiguration";_MCL="MetricsConfigurationList";_MD="MetadataDirective";_MDB="MaxDirectoryBuckets";_MDf="MfaDelete";_ME="MetadataEntry";_MF="MetricsFilter";_MFA="MFA";_MFAD="MFADelete";_MI="MetricsId";_MK="MaxKeys";_MKe="MetadataKey";_MM="MissingMeta";_MOS="MpuObjectSize";_MP="MaxParts";_MS="MetricsStatus";_MTC="MetadataTableConfiguration";_MTCR="MetadataTableConfigurationResult";_MU="MaxUploads";_MV="MetadataValue";_Me="Metrics";_Mes="Message";_Mi="Minutes";_Mo="Mode";_N="Name";_NC="NotificationConfiguration";_NCF="NotificationConfigurationFilter";_NCT="NextContinuationToken";_ND="NoncurrentDays";_NI="NotificationId";_NKM="NextKeyMarker";_NM="NextMarker";_NNV="NewerNoncurrentVersions";_NPNM="NextPartNumberMarker";_NUIM="NextUploadIdMarker";_NVE="NoncurrentVersionExpiration";_NVIM="NextVersionIdMarker";_NVT="NoncurrentVersionTransitions";_NVTo="NoncurrentVersionTransition";_O="Owner";_OA="ObjectAttributes";_OC="OwnershipControls";_OCACL="ObjectCannedACL";_OCR="OwnershipControlsRule";_OF="OptionalFields";_OI="ObjectIdentifier";_OK="ObjectKey";_OL="OutputLocation";_OLC="ObjectLockConfiguration";_OLE="ObjectLockEnabled";_OLEFB="ObjectLockEnabledForBucket";_OLLH="ObjectLockLegalHold";_OLLHS="ObjectLockLegalHoldStatus";_OLM="ObjectLockMode";_OLR="ObjectLockRetention";_OLRM="ObjectLockRetentionMode";_OLRUD="ObjectLockRetainUntilDate";_OLRb="ObjectLockRule";_OO="ObjectOwnership";_OOA="OptionalObjectAttributes";_OOw="OwnerOverride";_OP="ObjectParts";_OS="OutputSerialization";_OSGT="ObjectSizeGreaterThan";_OSGTB="ObjectSizeGreaterThanBytes";_OSLT="ObjectSizeLessThan";_OSLTB="ObjectSizeLessThanBytes";_OSV="OutputSchemaVersion";_OSb="ObjectSize";_OVI="ObjectVersionId";_Ob="Objects";_P="Prefix";_PABC="PublicAccessBlockConfiguration";_PC="PartsCount";_PDS="PartitionDateSource";_PI="ParquetInput";_PN="PartNumber";_PNM="PartNumberMarker";_PP="PartitionedPrefix";_Pa="Payer";_Par="Part";_Parq="Parquet";_Part="Parts";_Pe="Permission";_Pr="Protocol";_Pri="Priority";_Q="Quiet";_QA="QueueArn";_QC="QueueConfiguration";_QCu="QueueConfigurations";_QCuo="QuoteCharacter";_QEC="QuoteEscapeCharacter";_QF="QuoteFields";_Qu="Queue";_R="Range";_RART="RedirectAllRequestsTo";_RC="RequestCharged";_RCC="ResponseCacheControl";_RCD="ResponseContentDisposition";_RCE="ResponseContentEncoding";_RCL="ResponseContentLanguage";_RCT="ResponseContentType";_RCe="ReplicationConfiguration";_RD="RecordDelimiter";_RE="ResponseExpires";_RED="RestoreExpiryDate";_RKKID="ReplicaKmsKeyID";_RKPW="ReplaceKeyPrefixWith";_RKW="ReplaceKeyWith";_RM="ReplicaModifications";_RMS="ReplicaModificationsStatus";_ROP="RestoreOutputPath";_RP="RequestPayer";_RPB="RestrictPublicBuckets";_RPC="RequestPaymentConfiguration";_RPe="RequestProgress";_RR="RequestRoute";_RRAO="ReplicationRuleAndOperator";_RRF="ReplicationRuleFilter";_RRS="ReplicationRuleStatus";_RRT="RestoreRequestType";_RRe="ReplicationRule";_RRes="RestoreRequest";_RRo="RoutingRules";_RRou="RoutingRule";_RS="ReplicationStatus";_RSe="RestoreStatus";_RT="RequestToken";_RTS="ReplicationTimeStatus";_RTV="ReplicationTimeValue";_RTe="ReplicationTime";_RUD="RetainUntilDate";_Re="Restore";_Red="Redirect";_Ro="Role";_Ru="Rule";_Rul="Rules";_S="Status";_SA="StartAfter";_SAK="SecretAccessKey";_SBD="S3BucketDestination";_SC="StorageClass";_SCA="StorageClassAnalysis";_SCADE="StorageClassAnalysisDataExport";_SCASV="StorageClassAnalysisSchemaVersion";_SCt="StatusCode";_SDV="SkipDestinationValidation";_SK="SSE-KMS";_SKEO="SseKmsEncryptedObjects";_SKEOS="SseKmsEncryptedObjectsStatus";_SKF="S3KeyFilter";_SKe="S3Key";_SL="S3Location";_SM="SessionMode";_SOCR="SelectObjectContentRequest";_SP="SelectParameters";_SPi="SimplePrefix";_SR="ScanRange";_SS="SSE-S3";_SSC="SourceSelectionCriteria";_SSE="ServerSideEncryption";_SSEA="SSEAlgorithm";_SSEBD="ServerSideEncryptionByDefault";_SSEC="ServerSideEncryptionConfiguration";_SSECA="SSECustomerAlgorithm";_SSECK="SSECustomerKey";_SSECKMD="SSECustomerKeyMD5";_SSEKMS="SSEKMS";_SSEKMSEC="SSEKMSEncryptionContext";_SSEKMSKI="SSEKMSKeyId";_SSER="ServerSideEncryptionRule";_SSES="SSES3";_ST="SessionToken";_STBA="S3TablesBucketArn";_STD="S3TablesDestination";_STDR="S3TablesDestinationResult";_STN="S3TablesName";_S_="S3";_Sc="Schedule";_Se="Setting";_Si="Size";_St="Start";_Su="Suffix";_T="Tagging";_TA="TopicArn";_TAa="TableArn";_TB="TargetBucket";_TBA="TableBucketArn";_TC="TagCount";_TCo="TopicConfiguration";_TCop="TopicConfigurations";_TD="TaggingDirective";_TDMOS="TransitionDefaultMinimumObjectSize";_TG="TargetGrants";_TGa="TargetGrant";_TN="TableName";_TNa="TableNamespace";_TOKF="TargetObjectKeyFormat";_TP="TargetPrefix";_TPC="TotalPartsCount";_TS="TagSet";_TSC="TransitionStorageClass";_Ta="Tag";_Tag="Tags";_Ti="Tier";_Tie="Tierings";_Tier="Tiering";_Tim="Time";_To="Token";_Top="Topic";_Tr="Transitions";_Tra="Transition";_Ty="Type";_U="Upload";_UI="UploadId";_UIM="UploadIdMarker";_UM="UserMetadata";_URI="URI";_Up="Uploads";_V="Version";_VC="VersionCount";_VCe="VersioningConfiguration";_VI="VersionId";_VIM="VersionIdMarker";_Va="Value";_Ve="Versions";_WC="WebsiteConfiguration";_WOB="WriteOffsetBytes";_WRL="WebsiteRedirectLocation";_Y="Years";_a5="analytics";_ac="accelerate";_acl="acl";_ar="accept-ranges";_at="attributes";_br="bucket-region";_c2="cors";_cc="cache-control";_cd="content-disposition";_ce="content-encoding";_cl="content-language";_cl_="content-length";_cm="content-md5";_cr="content-range";_ct="content-type";_ct_="continuation-token";_d="delete";_de="delimiter";_e="expires";_en="encryption";_et="encoding-type";_eta="etag";_ex="expiresstring";_fo="fetch-owner";_i="id";_im="if-match";_ims="if-modified-since";_in="inventory";_inm="if-none-match";_it="intelligent-tiering";_ius="if-unmodified-since";_km="key-marker";_l="lifecycle";_lh="legal-hold";_lm="last-modified";_lo="location";_log="logging";_lt="list-type";_m="metrics";_mT="metadataTable";_ma="marker";_mb="max-buckets";_mdb="max-directory-buckets";_me="member";_mk="max-keys";_mp="max-parts";_mu="max-uploads";_n="notification";_oC="ownershipControls";_ol="object-lock";_p="policy";_pAB="publicAccessBlock";_pN="partNumber";_pS="policyStatus";_pnm="part-number-marker";_pr="prefix";_r="replication";_rP="requestPayment";_ra="range";_rcc="response-cache-control";_rcd="response-content-disposition";_rce="response-content-encoding";_rcl="response-content-language";_rct="response-content-type";_re="response-expires";_res="restore";_ret="retention";_s="session";_sa="start-after";_se="select";_st="select-type";_t="tagging";_to="torrent";_u="uploads";_uI="uploadId";_uim="upload-id-marker";_v="versioning";_vI="versionId";_ve='<?xml version="1.0" encoding="UTF-8"?>';_ver="versions";_vim="version-id-marker";_w="website";_x="xsi:type";_xaa="x-amz-acl";_xaad="x-amz-abort-date";_xaapa="x-amz-access-point-alias";_xaari="x-amz-abort-rule-id";_xaas="x-amz-archive-status";_xabgr="x-amz-bypass-governance-retention";_xabln="x-amz-bucket-location-name";_xablt="x-amz-bucket-location-type";_xabole="x-amz-bucket-object-lock-enabled";_xabolt="x-amz-bucket-object-lock-token";_xabr="x-amz-bucket-region";_xaca="x-amz-checksum-algorithm";_xacc="x-amz-checksum-crc32";_xacc_="x-amz-checksum-crc32c";_xacc__="x-amz-checksum-crc64nvme";_xacm="x-amz-checksum-mode";_xacrsba="x-amz-confirm-remove-self-bucket-access";_xacs="x-amz-checksum-sha1";_xacs_="x-amz-checksum-sha256";_xacs__="x-amz-copy-source";_xacsim="x-amz-copy-source-if-match";_xacsims="x-amz-copy-source-if-modified-since";_xacsinm="x-amz-copy-source-if-none-match";_xacsius="x-amz-copy-source-if-unmodified-since";_xacsm="x-amz-create-session-mode";_xacsr="x-amz-copy-source-range";_xacssseca="x-amz-copy-source-server-side-encryption-customer-algorithm";_xacssseck="x-amz-copy-source-server-side-encryption-customer-key";_xacssseckm="x-amz-copy-source-server-side-encryption-customer-key-md5";_xacsvi="x-amz-copy-source-version-id";_xact="x-amz-checksum-type";_xadm="x-amz-delete-marker";_xae="x-amz-expiration";_xaebo="x-amz-expected-bucket-owner";_xafec="x-amz-fwd-error-code";_xafem="x-amz-fwd-error-message";_xafhar="x-amz-fwd-header-accept-ranges";_xafhcc="x-amz-fwd-header-cache-control";_xafhcd="x-amz-fwd-header-content-disposition";_xafhce="x-amz-fwd-header-content-encoding";_xafhcl="x-amz-fwd-header-content-language";_xafhcr="x-amz-fwd-header-content-range";_xafhct="x-amz-fwd-header-content-type";_xafhe="x-amz-fwd-header-etag";_xafhe_="x-amz-fwd-header-expires";_xafhlm="x-amz-fwd-header-last-modified";_xafhxacc="x-amz-fwd-header-x-amz-checksum-crc32";_xafhxacc_="x-amz-fwd-header-x-amz-checksum-crc32c";_xafhxacc__="x-amz-fwd-header-x-amz-checksum-crc64nvme";_xafhxacs="x-amz-fwd-header-x-amz-checksum-sha1";_xafhxacs_="x-amz-fwd-header-x-amz-checksum-sha256";_xafhxadm="x-amz-fwd-header-x-amz-delete-marker";_xafhxae="x-amz-fwd-header-x-amz-expiration";_xafhxamm="x-amz-fwd-header-x-amz-missing-meta";_xafhxampc="x-amz-fwd-header-x-amz-mp-parts-count";_xafhxaollh="x-amz-fwd-header-x-amz-object-lock-legal-hold";_xafhxaolm="x-amz-fwd-header-x-amz-object-lock-mode";_xafhxaolrud="x-amz-fwd-header-x-amz-object-lock-retain-until-date";_xafhxar="x-amz-fwd-header-x-amz-restore";_xafhxarc="x-amz-fwd-header-x-amz-request-charged";_xafhxars="x-amz-fwd-header-x-amz-replication-status";_xafhxasc="x-amz-fwd-header-x-amz-storage-class";_xafhxasse="x-amz-fwd-header-x-amz-server-side-encryption";_xafhxasseakki="x-amz-fwd-header-x-amz-server-side-encryption-aws-kms-key-id";_xafhxassebke="x-amz-fwd-header-x-amz-server-side-encryption-bucket-key-enabled";_xafhxasseca="x-amz-fwd-header-x-amz-server-side-encryption-customer-algorithm";_xafhxasseckm="x-amz-fwd-header-x-amz-server-side-encryption-customer-key-md5";_xafhxatc="x-amz-fwd-header-x-amz-tagging-count";_xafhxavi="x-amz-fwd-header-x-amz-version-id";_xafs="x-amz-fwd-status";_xagfc="x-amz-grant-full-control";_xagr="x-amz-grant-read";_xagra="x-amz-grant-read-acp";_xagw="x-amz-grant-write";_xagwa="x-amz-grant-write-acp";_xaimit="x-amz-if-match-initiated-time";_xaimlmt="x-amz-if-match-last-modified-time";_xaims="x-amz-if-match-size";_xam="x-amz-mfa";_xamd="x-amz-metadata-directive";_xamm="x-amz-missing-meta";_xamos="x-amz-mp-object-size";_xamp="x-amz-max-parts";_xampc="x-amz-mp-parts-count";_xaoa="x-amz-object-attributes";_xaollh="x-amz-object-lock-legal-hold";_xaolm="x-amz-object-lock-mode";_xaolrud="x-amz-object-lock-retain-until-date";_xaoo="x-amz-object-ownership";_xaooa="x-amz-optional-object-attributes";_xaos="x-amz-object-size";_xapnm="x-amz-part-number-marker";_xar="x-amz-restore";_xarc="x-amz-request-charged";_xarop="x-amz-restore-output-path";_xarp="x-amz-request-payer";_xarr="x-amz-request-route";_xars="x-amz-replication-status";_xart="x-amz-request-token";_xasc="x-amz-storage-class";_xasca="x-amz-sdk-checksum-algorithm";_xasdv="x-amz-skip-destination-validation";_xasebo="x-amz-source-expected-bucket-owner";_xasse="x-amz-server-side-encryption";_xasseakki="x-amz-server-side-encryption-aws-kms-key-id";_xassebke="x-amz-server-side-encryption-bucket-key-enabled";_xassec="x-amz-server-side-encryption-context";_xasseca="x-amz-server-side-encryption-customer-algorithm";_xasseck="x-amz-server-side-encryption-customer-key";_xasseckm="x-amz-server-side-encryption-customer-key-md5";_xat="x-amz-tagging";_xatc="x-amz-tagging-count";_xatd="x-amz-tagging-directive";_xatdmos="x-amz-transition-default-minimum-object-size";_xavi="x-amz-version-id";_xawob="x-amz-write-offset-bytes";_xawrl="x-amz-website-redirect-location";_xi="x-id";CreateSessionCommand=class extends(Command.classBuilder().ep({...commonParams,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","CreateSession",{}).n("S3Client","CreateSessionCommand").f(CreateSessionRequestFilterSensitiveLog,CreateSessionOutputFilterSensitiveLog).ser(se_CreateSessionCommand).de(de_CreateSessionCommand).build()){};fromUtf84=input=>(new TextEncoder).encode(input);SHA_1_HMAC_ALGO={name:"HMAC",hash:SHA_1_HASH={name:"SHA-1"}};EMPTY_DATA_SHA_1=new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]);fallbackWindow={};Sha1=function(){function Sha13(secret){this.toHash=new Uint8Array(0);if(void 0!==secret){this.key=new Promise((function(resolve,reject){locateWindow().crypto.subtle.importKey("raw",convertToBuffer2(secret),SHA_1_HMAC_ALGO,!1,["sign"]).then(resolve,reject)}));this.key.catch((function(){}))}}Sha13.prototype.update=function(data){var update2,typedArray;if(!isEmptyData2(data)){update2=convertToBuffer2(data);(typedArray=new Uint8Array(this.toHash.byteLength+update2.byteLength)).set(this.toHash,0);typedArray.set(update2,this.toHash.byteLength);this.toHash=typedArray}};Sha13.prototype.digest=function(){var _this=this;return this.key?this.key.then((function(key3){return locateWindow().crypto.subtle.sign(SHA_1_HMAC_ALGO,key3,_this.toHash).then((function(data){return new Uint8Array(data)}))})):isEmptyData2(this.toHash)?Promise.resolve(EMPTY_DATA_SHA_1):Promise.resolve().then((function(){return locateWindow().crypto.subtle.digest(SHA_1_HASH,_this.toHash)})).then((function(data){return Promise.resolve(new Uint8Array(data))}))};Sha13.prototype.reset=function(){this.toHash=new Uint8Array(0)};return Sha13}();subtleCryptoMethods=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];Sha12=function(){function Sha13(secret){if(!supportsWebCrypto(locateWindow()))throw new Error("SHA1 not supported");this.hash=new Sha1(secret)}Sha13.prototype.update=function(data,encoding){this.hash.update(convertToBuffer(data))};Sha13.prototype.digest=function(){return this.hash.digest()};Sha13.prototype.reset=function(){this.hash.reset()};return Sha13}();SHA_256_HMAC_ALGO={name:"HMAC",hash:SHA_256_HASH={name:"SHA-256"}};EMPTY_DATA_SHA_256=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]);Sha256=function(){function Sha2564(secret){this.toHash=new Uint8Array(0);this.secret=secret;this.reset()}Sha2564.prototype.update=function(data){var update2,typedArray;if(!isEmptyData(data)){update2=convertToBuffer(data);(typedArray=new Uint8Array(this.toHash.byteLength+update2.byteLength)).set(this.toHash,0);typedArray.set(update2,this.toHash.byteLength);this.toHash=typedArray}};Sha2564.prototype.digest=function(){var _this=this;return this.key?this.key.then((function(key3){return locateWindow().crypto.subtle.sign(SHA_256_HMAC_ALGO,key3,_this.toHash).then((function(data){return new Uint8Array(data)}))})):isEmptyData(this.toHash)?Promise.resolve(EMPTY_DATA_SHA_256):Promise.resolve().then((function(){return locateWindow().crypto.subtle.digest(SHA_256_HASH,_this.toHash)})).then((function(data){return Promise.resolve(new Uint8Array(data))}))};Sha2564.prototype.reset=function(){var _this=this;this.toHash=new Uint8Array(0);if(this.secret&&void 0!==this.secret){this.key=new Promise((function(resolve,reject){locateWindow().crypto.subtle.importKey("raw",convertToBuffer(_this.secret),SHA_256_HMAC_ALGO,!1,["sign"]).then(resolve,reject)}));this.key.catch((function(){}))}};return Sha2564}();BLOCK_SIZE=64;KEY=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]);INIT=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];MAX_HASHABLE_LENGTH=Math.pow(2,53)-1;RawSha256=function(){function RawSha2562(){this.state=Int32Array.from(INIT);this.temp=new Int32Array(64);this.buffer=new Uint8Array(64);this.bufferLength=0;this.bytesHashed=0;this.finished=!1}RawSha2562.prototype.update=function(data){var position,byteLength;if(this.finished)throw new Error("Attempted to update an already finished hash.");position=0;byteLength=data.byteLength;this.bytesHashed+=byteLength;if(8*this.bytesHashed>MAX_HASHABLE_LENGTH)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;byteLength>0;){this.buffer[this.bufferLength++]=data[position++];byteLength--;if(this.bufferLength===BLOCK_SIZE){this.hashBuffer();this.bufferLength=0}}};RawSha2562.prototype.digest=function(){var bitsHashed,bufferView,undecoratedLength,i2,out;if(!this.finished){bitsHashed=8*this.bytesHashed;bufferView=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength);undecoratedLength=this.bufferLength;bufferView.setUint8(this.bufferLength++,128);if(undecoratedLength%BLOCK_SIZE>=BLOCK_SIZE-8){for(i2=this.bufferLength;i2<BLOCK_SIZE;i2++)bufferView.setUint8(i2,0);this.hashBuffer();this.bufferLength=0}for(i2=this.bufferLength;i2<BLOCK_SIZE-8;i2++)bufferView.setUint8(i2,0);bufferView.setUint32(BLOCK_SIZE-8,Math.floor(bitsHashed/4294967296),!0);bufferView.setUint32(BLOCK_SIZE-4,bitsHashed);this.hashBuffer();this.finished=!0}out=new Uint8Array(32);for(i2=0;i2<8;i2++){out[4*i2]=this.state[i2]>>>24&255;out[4*i2+1]=this.state[i2]>>>16&255;out[4*i2+2]=this.state[i2]>>>8&255;out[4*i2+3]=this.state[i2]>>>0&255}return out};RawSha2562.prototype.hashBuffer=function(){var i2,u2,t1_1,t2_1,t1,t22,buffer=this.buffer,state2=this.state,state0=state2[0],state1=state2[1],state22=state2[2],state3=state2[3],state4=state2[4],state5=state2[5],state6=state2[6],state7=state2[7];for(i2=0;i2<BLOCK_SIZE;i2++){if(i2<16)this.temp[i2]=(255&buffer[4*i2])<<24|(255&buffer[4*i2+1])<<16|(255&buffer[4*i2+2])<<8|255&buffer[4*i2+3];else{t1_1=((u2=this.temp[i2-2])>>>17|u2<<15)^(u2>>>19|u2<<13)^u2>>>10;t2_1=((u2=this.temp[i2-15])>>>7|u2<<25)^(u2>>>18|u2<<14)^u2>>>3;this.temp[i2]=(t1_1+this.temp[i2-7]|0)+(t2_1+this.temp[i2-16]|0)}t1=(((state4>>>6|state4<<26)^(state4>>>11|state4<<21)^(state4>>>25|state4<<7))+(state4&state5^~state4&state6)|0)+(state7+(KEY[i2]+this.temp[i2]|0)|0)|0;t22=((state0>>>2|state0<<30)^(state0>>>13|state0<<19)^(state0>>>22|state0<<10))+(state0&state1^state0&state22^state1&state22)|0;state7=state6;state6=state5;state5=state4;state4=state3+t1|0;state3=state22;state22=state1;state1=state0;state0=t1+t22|0}state2[0]+=state0;state2[1]+=state1;state2[2]+=state22;state2[3]+=state3;state2[4]+=state4;state2[5]+=state5;state2[6]+=state6;state2[7]+=state7};return RawSha2562}();Sha2562=function(){function Sha2564(secret){this.secret=secret;this.hash=new RawSha256;this.reset()}Sha2564.prototype.update=function(toHash){if(!isEmptyData(toHash)&&!this.error)try{this.hash.update(convertToBuffer(toHash))}catch(e3){this.error=e3}};Sha2564.prototype.digestSync=function(){if(this.error)throw this.error;if(this.outer){this.outer.finished||this.outer.update(this.hash.digest());return this.outer.digest()}return this.hash.digest()};Sha2564.prototype.digest=function(){return __awaiter(this,void 0,void 0,(function(){return __generator(this,(function(_a8){return[2,this.digestSync()]}))}))};Sha2564.prototype.reset=function(){var inner,outer,i2;this.hash=new RawSha256;if(this.secret){this.outer=new RawSha256;inner=bufferFromSecret(this.secret);(outer=new Uint8Array(BLOCK_SIZE)).set(inner);for(i2=0;i2<BLOCK_SIZE;i2++){inner[i2]^=54;outer[i2]^=92}this.hash.update(inner);this.outer.update(outer);for(i2=0;i2<inner.byteLength;i2++)inner[i2]=0}};return Sha2564}();Sha2563=function(){function Sha2564(secret){supportsWebCrypto(locateWindow())?this.hash=new Sha256(secret):this.hash=new Sha2562(secret)}Sha2564.prototype.update=function(data,encoding){this.hash.update(convertToBuffer(data))};Sha2564.prototype.digest=function(){return this.hash.digest()};Sha2564.prototype.reset=function(){this.hash.reset()};return Sha2564}();import_bowser=__toESM(require_es5());createDefaultUserAgentProvider=({serviceId,clientVersion})=>async config=>{var _a8,_b5,_c3,_d2,_e2,_f,_g,_h;const parsedUA="undefined"!=typeof window&&(null==(_a8=null==window?void 0:window.navigator)?void 0:_a8.userAgent)?import_bowser.default.parse(window.navigator.userAgent):void 0,sections=[["aws-sdk-js",clientVersion],["ua","2.1"],[`os/${(null==(_b5=null==parsedUA?void 0:parsedUA.os)?void 0:_b5.name)||"other"}`,null==(_c3=null==parsedUA?void 0:parsedUA.os)?void 0:_c3.version],["lang/js"],["md/browser",`${null!=(_e2=null==(_d2=null==parsedUA?void 0:parsedUA.browser)?void 0:_d2.name)?_e2:"unknown"}_${null!=(_g=null==(_f=null==parsedUA?void 0:parsedUA.browser)?void 0:_f.version)?_g:"unknown"}`]];serviceId&&sections.push([`api/${serviceId}`,clientVersion]);const appId=await(null==(_h=null==config?void 0:config.userAgentAppId)?void 0:_h.call(config));appId&&sections.push([`app/${appId}`]);return sections};Int642=class _Int64{constructor(bytes){this.bytes=bytes;if(8!==bytes.byteLength)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(number){if(number>0x8000000000000000||number<-0x8000000000000000)throw new Error(`${number} is too large (or, if negative, too small) to represent as an Int64`);const bytes=new Uint8Array(8);for(let i2=7,remaining=Math.abs(Math.round(number));i2>-1&&remaining>0;i2--,remaining/=256)bytes[i2]=remaining;number<0&&negate2(bytes);return new _Int64(bytes)}valueOf(){const bytes=this.bytes.slice(0),negative=128&bytes[0];negative&&negate2(bytes);return parseInt(toHex2(bytes),16)*(negative?-1:1)}toString(){return String(this.valueOf())}};HeaderMarshaller=class{constructor(toUtf82,fromUtf85){this.toUtf8=toUtf82;this.fromUtf8=fromUtf85}format(headers){const chunks=[];for(const headerName of Object.keys(headers)){const bytes=this.fromUtf8(headerName);chunks.push(Uint8Array.from([bytes.byteLength]),bytes,this.formatHeaderValue(headers[headerName]))}const out=new Uint8Array(chunks.reduce(((carry,bytes)=>carry+bytes.byteLength),0));let position=0;for(const chunk of chunks){out.set(chunk,position);position+=chunk.byteLength}return out}formatHeaderValue(header){switch(header.type){case"boolean":return Uint8Array.from([header.value?0:1]);case"byte":return Uint8Array.from([2,header.value]);case"short":const shortView=new DataView(new ArrayBuffer(3));shortView.setUint8(0,3);shortView.setInt16(1,header.value,!1);return new Uint8Array(shortView.buffer);case"integer":const intView=new DataView(new ArrayBuffer(5));intView.setUint8(0,4);intView.setInt32(1,header.value,!1);return new Uint8Array(intView.buffer);case"long":const longBytes=new Uint8Array(9);longBytes[0]=5;longBytes.set(header.value.bytes,1);return longBytes;case"binary":const binView=new DataView(new ArrayBuffer(3+header.value.byteLength));binView.setUint8(0,6);binView.setUint16(1,header.value.byteLength,!1);const binBytes=new Uint8Array(binView.buffer);binBytes.set(header.value,3);return binBytes;case"string":const utf8Bytes=this.fromUtf8(header.value),strView=new DataView(new ArrayBuffer(3+utf8Bytes.byteLength));strView.setUint8(0,7);strView.setUint16(1,utf8Bytes.byteLength,!1);const strBytes=new Uint8Array(strView.buffer);strBytes.set(utf8Bytes,3);return strBytes;case"timestamp":const tsBytes=new Uint8Array(9);tsBytes[0]=8;tsBytes.set(Int642.fromNumber(header.value.valueOf()).bytes,1);return tsBytes;case"uuid":if(!UUID_PATTERN2.test(header.value))throw new Error(`Invalid UUID received: ${header.value}`);const uuidBytes=new Uint8Array(17);uuidBytes[0]=9;uuidBytes.set(fromHex(header.value.replace(/\-/g,"")),1);return uuidBytes}}parse(headers){const out={};let position=0;for(;position<headers.byteLength;){const nameLength=headers.getUint8(position++),name=this.toUtf8(new Uint8Array(headers.buffer,headers.byteOffset+position,nameLength));position+=nameLength;switch(headers.getUint8(position++)){case 0:out[name]={type:BOOLEAN_TAG,value:!0};break;case 1:out[name]={type:BOOLEAN_TAG,value:!1};break;case 2:out[name]={type:BYTE_TAG,value:headers.getInt8(position++)};break;case 3:out[name]={type:SHORT_TAG,value:headers.getInt16(position,!1)};position+=2;break;case 4:out[name]={type:INT_TAG,value:headers.getInt32(position,!1)};position+=4;break;case 5:out[name]={type:LONG_TAG,value:new Int642(new Uint8Array(headers.buffer,headers.byteOffset+position,8))};position+=8;break;case 6:const binaryLength=headers.getUint16(position,!1);position+=2;out[name]={type:BINARY_TAG,value:new Uint8Array(headers.buffer,headers.byteOffset+position,binaryLength)};position+=binaryLength;break;case 7:const stringLength=headers.getUint16(position,!1);position+=2;out[name]={type:STRING_TAG,value:this.toUtf8(new Uint8Array(headers.buffer,headers.byteOffset+position,stringLength))};position+=stringLength;break;case 8:out[name]={type:TIMESTAMP_TAG,value:new Date(new Int642(new Uint8Array(headers.buffer,headers.byteOffset+position,8)).valueOf())};position+=8;break;case 9:const uuidBytes=new Uint8Array(headers.buffer,headers.byteOffset+position,16);position+=16;out[name]={type:UUID_TAG,value:`${toHex2(uuidBytes.subarray(0,4))}-${toHex2(uuidBytes.subarray(4,6))}-${toHex2(uuidBytes.subarray(6,8))}-${toHex2(uuidBytes.subarray(8,10))}-${toHex2(uuidBytes.subarray(10))}`};break;default:throw new Error("Unrecognized header type tag")}}return out}};(function(HEADER_VALUE_TYPE3){HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.boolTrue=0]="boolTrue";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.boolFalse=1]="boolFalse";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.byte=2]="byte";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.short=3]="short";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.integer=4]="integer";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.long=5]="long";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.byteArray=6]="byteArray";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.string=7]="string";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.timestamp=8]="timestamp";HEADER_VALUE_TYPE3[HEADER_VALUE_TYPE3.uuid=9]="uuid"})(HEADER_VALUE_TYPE2||(HEADER_VALUE_TYPE2={}));BOOLEAN_TAG="boolean";BYTE_TAG="byte";SHORT_TAG="short";INT_TAG="integer";LONG_TAG="long";BINARY_TAG="binary";STRING_TAG="string";TIMESTAMP_TAG="timestamp";UUID_TAG="uuid";UUID_PATTERN2=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;MINIMUM_MESSAGE_LENGTH=(PRELUDE_LENGTH=2*(PRELUDE_MEMBER_LENGTH=4))+2*(CHECKSUM_LENGTH=4);EventStreamCodec=class{constructor(toUtf82,fromUtf85){this.headerMarshaller=new HeaderMarshaller(toUtf82,fromUtf85);this.messageBuffer=[];this.isEndOfStream=!1}feed(message){this.messageBuffer.push(this.decode(message))}endOfStream(){this.isEndOfStream=!0}getMessage(){const message=this.messageBuffer.pop(),isEndOfStream=this.isEndOfStream;return{getMessage:()=>message,isEndOfStream:()=>isEndOfStream}}getAvailableMessages(){const messages=this.messageBuffer;this.messageBuffer=[];const isEndOfStream=this.isEndOfStream;return{getMessages:()=>messages,isEndOfStream:()=>isEndOfStream}}encode({headers:rawHeaders,body}){const headers=this.headerMarshaller.format(rawHeaders),length=headers.byteLength+body.byteLength+16,out=new Uint8Array(length),view=new DataView(out.buffer,out.byteOffset,out.byteLength),checksum=new Crc32;view.setUint32(0,length,!1);view.setUint32(4,headers.byteLength,!1);view.setUint32(8,checksum.update(out.subarray(0,8)).digest(),!1);out.set(headers,12);out.set(body,headers.byteLength+12);view.setUint32(length-4,checksum.update(out.subarray(8,length-4)).digest(),!1);return out}decode(message){const{headers,body}=splitMessage(message);return{headers:this.headerMarshaller.parse(headers),body}}formatHeaders(rawHeaders){return this.headerMarshaller.format(rawHeaders)}};MessageDecoderStream=class{constructor(options){this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const bytes of this.options.inputStream){const decoded=this.options.decoder.decode(bytes);yield decoded}}};MessageEncoderStream=class{constructor(options){this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const msg of this.options.messageStream){const encoded=this.options.encoder.encode(msg);yield encoded}this.options.includeEndFrame&&(yield new Uint8Array(0))}};SmithyMessageDecoderStream=class{constructor(options){this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const message of this.options.messageStream){const deserialized=await this.options.deserializer(message);void 0!==deserialized&&(yield deserialized)}}};SmithyMessageEncoderStream=class{constructor(options){this.options=options}[Symbol.asyncIterator](){return this.asyncIterator()}async*asyncIterator(){for await(const chunk of this.options.inputStream){const payloadBuf=this.options.serializer(chunk);yield payloadBuf}}};EventStreamMarshaller=class{constructor({utf8Encoder,utf8Decoder}){this.eventStreamCodec=new EventStreamCodec(utf8Encoder,utf8Decoder);this.utfEncoder=utf8Encoder}deserialize(body,deserializer){const inputStream=getChunkedStream(body);return new SmithyMessageDecoderStream({messageStream:new MessageDecoderStream({inputStream,decoder:this.eventStreamCodec}),deserializer:getMessageUnmarshaller(deserializer,this.utfEncoder)})}serialize(inputStream,serializer){return new MessageEncoderStream({messageStream:new SmithyMessageEncoderStream({inputStream,serializer}),encoder:this.eventStreamCodec,includeEndFrame:!0})}};readableStreamtoIterable=readableStream=>({[Symbol.asyncIterator]:async function*(){const reader=readableStream.getReader();try{for(;;){const{done,value}=await reader.read();if(done)return;yield value}}finally{reader.releaseLock()}}});iterableToReadableStream=asyncIterable=>{const iterator=asyncIterable[Symbol.asyncIterator]();return new ReadableStream({async pull(controller){const{done,value}=await iterator.next();if(done)return controller.close();controller.enqueue(value)}})};EventStreamMarshaller2=class{constructor({utf8Encoder,utf8Decoder}){this.universalMarshaller=new EventStreamMarshaller({utf8Decoder,utf8Encoder})}deserialize(body,deserializer){const bodyIterable=isReadableStream2(body)?readableStreamtoIterable(body):body;return this.universalMarshaller.deserialize(bodyIterable,deserializer)}serialize(input,serializer){const serialziedIterable=this.universalMarshaller.serialize(input,serializer);return"function"==typeof ReadableStream?iterableToReadableStream(serialziedIterable):serialziedIterable}};isReadableStream2=body=>"function"==typeof ReadableStream&&body instanceof ReadableStream;eventStreamSerdeProvider2=options=>new EventStreamMarshaller2(options);blobHasher=async function blobHasher2(hashCtor,blob){const hash3=new hashCtor;await blobReader(blob,(chunk=>{hash3.update(chunk)}));return hash3.digest()};invalidProvider=message=>()=>Promise.reject(message);INIT2=[1732584193,4023233417,2562383102,271733878];Md5=class{constructor(){this.reset()}update(sourceData){if(isEmptyData3(sourceData))return;if(this.finished)throw new Error("Attempted to update an already finished hash.");const data=convertToBuffer3(sourceData);let position=0,{byteLength}=data;this.bytesHashed+=byteLength;for(;byteLength>0;){this.buffer.setUint8(this.bufferLength++,data[position++]);byteLength--;if(64===this.bufferLength){this.hashBuffer();this.bufferLength=0}}}async digest(){if(!this.finished){const{buffer,bufferLength:undecoratedLength,bytesHashed}=this,bitsHashed=8*bytesHashed;buffer.setUint8(this.bufferLength++,128);if(undecoratedLength%64>=56){for(let i2=this.bufferLength;i2<64;i2++)buffer.setUint8(i2,0);this.hashBuffer();this.bufferLength=0}for(let i2=this.bufferLength;i2<56;i2++)buffer.setUint8(i2,0);buffer.setUint32(56,bitsHashed>>>0,!0);buffer.setUint32(60,Math.floor(bitsHashed/4294967296),!0);this.hashBuffer();this.finished=!0}const out=new DataView(new ArrayBuffer(16));for(let i2=0;i2<4;i2++)out.setUint32(4*i2,this.state[i2],!0);return new Uint8Array(out.buffer,out.byteOffset,out.byteLength)}hashBuffer(){const{buffer,state:state2}=this;let a2=state2[0],b3=state2[1],c3=state2[2],d4=state2[3];a2=ff(a2,b3,c3,d4,buffer.getUint32(0,!0),7,3614090360);d4=ff(d4,a2,b3,c3,buffer.getUint32(4,!0),12,3905402710);c3=ff(c3,d4,a2,b3,buffer.getUint32(8,!0),17,606105819);b3=ff(b3,c3,d4,a2,buffer.getUint32(12,!0),22,3250441966);a2=ff(a2,b3,c3,d4,buffer.getUint32(16,!0),7,4118548399);d4=ff(d4,a2,b3,c3,buffer.getUint32(20,!0),12,1200080426);c3=ff(c3,d4,a2,b3,buffer.getUint32(24,!0),17,2821735955);b3=ff(b3,c3,d4,a2,buffer.getUint32(28,!0),22,4249261313);a2=ff(a2,b3,c3,d4,buffer.getUint32(32,!0),7,1770035416);d4=ff(d4,a2,b3,c3,buffer.getUint32(36,!0),12,2336552879);c3=ff(c3,d4,a2,b3,buffer.getUint32(40,!0),17,4294925233);b3=ff(b3,c3,d4,a2,buffer.getUint32(44,!0),22,2304563134);a2=ff(a2,b3,c3,d4,buffer.getUint32(48,!0),7,1804603682);d4=ff(d4,a2,b3,c3,buffer.getUint32(52,!0),12,4254626195);c3=ff(c3,d4,a2,b3,buffer.getUint32(56,!0),17,2792965006);b3=ff(b3,c3,d4,a2,buffer.getUint32(60,!0),22,1236535329);a2=gg(a2,b3,c3,d4,buffer.getUint32(4,!0),5,4129170786);d4=gg(d4,a2,b3,c3,buffer.getUint32(24,!0),9,3225465664);c3=gg(c3,d4,a2,b3,buffer.getUint32(44,!0),14,643717713);b3=gg(b3,c3,d4,a2,buffer.getUint32(0,!0),20,3921069994);a2=gg(a2,b3,c3,d4,buffer.getUint32(20,!0),5,3593408605);d4=gg(d4,a2,b3,c3,buffer.getUint32(40,!0),9,38016083);c3=gg(c3,d4,a2,b3,buffer.getUint32(60,!0),14,3634488961);b3=gg(b3,c3,d4,a2,buffer.getUint32(16,!0),20,3889429448);a2=gg(a2,b3,c3,d4,buffer.getUint32(36,!0),5,568446438);d4=gg(d4,a2,b3,c3,buffer.getUint32(56,!0),9,3275163606);c3=gg(c3,d4,a2,b3,buffer.getUint32(12,!0),14,4107603335);b3=gg(b3,c3,d4,a2,buffer.getUint32(32,!0),20,1163531501);a2=gg(a2,b3,c3,d4,buffer.getUint32(52,!0),5,2850285829);d4=gg(d4,a2,b3,c3,buffer.getUint32(8,!0),9,4243563512);c3=gg(c3,d4,a2,b3,buffer.getUint32(28,!0),14,1735328473);b3=gg(b3,c3,d4,a2,buffer.getUint32(48,!0),20,2368359562);a2=hh(a2,b3,c3,d4,buffer.getUint32(20,!0),4,4294588738);d4=hh(d4,a2,b3,c3,buffer.getUint32(32,!0),11,2272392833);c3=hh(c3,d4,a2,b3,buffer.getUint32(44,!0),16,1839030562);b3=hh(b3,c3,d4,a2,buffer.getUint32(56,!0),23,4259657740);a2=hh(a2,b3,c3,d4,buffer.getUint32(4,!0),4,2763975236);d4=hh(d4,a2,b3,c3,buffer.getUint32(16,!0),11,1272893353);c3=hh(c3,d4,a2,b3,buffer.getUint32(28,!0),16,4139469664);b3=hh(b3,c3,d4,a2,buffer.getUint32(40,!0),23,3200236656);a2=hh(a2,b3,c3,d4,buffer.getUint32(52,!0),4,681279174);d4=hh(d4,a2,b3,c3,buffer.getUint32(0,!0),11,3936430074);c3=hh(c3,d4,a2,b3,buffer.getUint32(12,!0),16,3572445317);b3=hh(b3,c3,d4,a2,buffer.getUint32(24,!0),23,76029189);a2=hh(a2,b3,c3,d4,buffer.getUint32(36,!0),4,3654602809);d4=hh(d4,a2,b3,c3,buffer.getUint32(48,!0),11,3873151461);c3=hh(c3,d4,a2,b3,buffer.getUint32(60,!0),16,530742520);b3=hh(b3,c3,d4,a2,buffer.getUint32(8,!0),23,3299628645);a2=ii(a2,b3,c3,d4,buffer.getUint32(0,!0),6,4096336452);d4=ii(d4,a2,b3,c3,buffer.getUint32(28,!0),10,1126891415);c3=ii(c3,d4,a2,b3,buffer.getUint32(56,!0),15,2878612391);b3=ii(b3,c3,d4,a2,buffer.getUint32(20,!0),21,4237533241);a2=ii(a2,b3,c3,d4,buffer.getUint32(48,!0),6,1700485571);d4=ii(d4,a2,b3,c3,buffer.getUint32(12,!0),10,2399980690);c3=ii(c3,d4,a2,b3,buffer.getUint32(40,!0),15,4293915773);b3=ii(b3,c3,d4,a2,buffer.getUint32(4,!0),21,2240044497);a2=ii(a2,b3,c3,d4,buffer.getUint32(32,!0),6,1873313359);d4=ii(d4,a2,b3,c3,buffer.getUint32(60,!0),10,4264355552);c3=ii(c3,d4,a2,b3,buffer.getUint32(24,!0),15,2734768916);b3=ii(b3,c3,d4,a2,buffer.getUint32(52,!0),21,1309151649);a2=ii(a2,b3,c3,d4,buffer.getUint32(16,!0),6,4149444226);d4=ii(d4,a2,b3,c3,buffer.getUint32(44,!0),10,3174756917);c3=ii(c3,d4,a2,b3,buffer.getUint32(8,!0),15,718787259);b3=ii(b3,c3,d4,a2,buffer.getUint32(36,!0),21,3951481745);state2[0]=a2+state2[0]&4294967295;state2[1]=b3+state2[1]&4294967295;state2[2]=c3+state2[2]&4294967295;state2[3]=d4+state2[3]&4294967295}reset(){this.state=Uint32Array.from(INIT2);this.buffer=new DataView(new ArrayBuffer(64));this.bufferLength=0;this.bytesHashed=0;this.finished=!1}};TEXT_ENCODER="function"==typeof TextEncoder?new TextEncoder:null;calculateBodyLength=body=>{if("string"==typeof body){if(TEXT_ENCODER)return TEXT_ENCODER.encode(body).byteLength;let len=body.length;for(let i2=len-1;i2>=0;i2--){const code=body.charCodeAt(i2);code>127&&code<=2047?len++:code>2047&&code<=65535&&(len+=2);code>=56320&&code<=57343&&i2--}return len}if("number"==typeof body.byteLength)return body.byteLength;if("number"==typeof body.size)return body.size;throw new Error(`Body Length computation failed for ${body}`)};getRuntimeConfig=config=>{var _a8,_b5,_c3,_d2,_e2,_f,_g,_h,_i2,_j,_k,_l2,_m2,_n2,_o,_p2,_q;return{apiVersion:"2006-03-01",base64Decoder:null!=(_a8=null==config?void 0:config.base64Decoder)?_a8:fromBase64,base64Encoder:null!=(_b5=null==config?void 0:config.base64Encoder)?_b5:toBase64,disableHostPrefix:null!=(_c3=null==config?void 0:config.disableHostPrefix)&&_c3,endpointProvider:null!=(_d2=null==config?void 0:config.endpointProvider)?_d2:defaultEndpointResolver,extensions:null!=(_e2=null==config?void 0:config.extensions)?_e2:[],getAwsChunkedEncodingStream:null!=(_f=null==config?void 0:config.getAwsChunkedEncodingStream)?_f:getAwsChunkedEncodingStream,httpAuthSchemeProvider:null!=(_g=null==config?void 0:config.httpAuthSchemeProvider)?_g:defaultS3HttpAuthSchemeProvider,httpAuthSchemes:null!=(_h=null==config?void 0:config.httpAuthSchemes)?_h:[{schemeId:"aws.auth#sigv4",identityProvider:ipc=>ipc.getIdentityProvider("aws.auth#sigv4"),signer:new AwsSdkSigV4Signer},{schemeId:"aws.auth#sigv4a",identityProvider:ipc=>ipc.getIdentityProvider("aws.auth#sigv4a"),signer:new AwsSdkSigV4ASigner}],logger:null!=(_i2=null==config?void 0:config.logger)?_i2:new NoOpLogger,sdkStreamMixin:null!=(_j=null==config?void 0:config.sdkStreamMixin)?_j:sdkStreamMixin,serviceId:null!=(_k=null==config?void 0:config.serviceId)?_k:"S3",signerConstructor:null!=(_l2=null==config?void 0:config.signerConstructor)?_l2:SignatureV4MultiRegion,signingEscapePath:null!=(_m2=null==config?void 0:config.signingEscapePath)&&_m2,urlParser:null!=(_n2=null==config?void 0:config.urlParser)?_n2:parseUrl,useArnRegion:null!=(_o=null==config?void 0:config.useArnRegion)&&_o,utf8Decoder:null!=(_p2=null==config?void 0:config.utf8Decoder)?_p2:fromUtf8,utf8Encoder:null!=(_q=null==config?void 0:config.utf8Encoder)?_q:toUtf8}};DEFAULTS_MODE_OPTIONS=["in-region","cross-region","mobile","standard","legacy"];import_bowser2=__toESM(require_es5());resolveDefaultsModeConfig=({defaultsMode}={})=>memoize((async()=>{const mode="function"==typeof defaultsMode?await defaultsMode():defaultsMode;switch(null==mode?void 0:mode.toLowerCase()){case"auto":return Promise.resolve(isMobileBrowser()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(null==mode?void 0:mode.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${DEFAULTS_MODE_OPTIONS.join(", ")}, got ${mode}`)}}));isMobileBrowser=()=>{var _a8,_b5;const parsedUA="undefined"!=typeof window&&(null==(_a8=null==window?void 0:window.navigator)?void 0:_a8.userAgent)?import_bowser2.default.parse(window.navigator.userAgent):void 0,platform=null==(_b5=null==parsedUA?void 0:parsedUA.platform)?void 0:_b5.type;return"tablet"===platform||"mobile"===platform};getRuntimeConfig2=config=>{var _a8,_b5,_c3,_d2,_e2,_f,_g,_h,_i2,_j,_k,_l2,_m2,_n2,_o;const defaultsMode=resolveDefaultsModeConfig(config),defaultConfigProvider=()=>defaultsMode().then(loadConfigsForDefaultMode),clientSharedValues=getRuntimeConfig(config);return{...clientSharedValues,...config,runtime:"browser",defaultsMode,bodyLengthChecker:null!=(_a8=null==config?void 0:config.bodyLengthChecker)?_a8:calculateBodyLength,credentialDefaultProvider:null!=(_b5=null==config?void 0:config.credentialDefaultProvider)?_b5:_=>()=>Promise.reject(new Error("Credential is missing")),defaultUserAgentProvider:null!=(_c3=null==config?void 0:config.defaultUserAgentProvider)?_c3:createDefaultUserAgentProvider({serviceId:clientSharedValues.serviceId,clientVersion:"3.808.0"}),eventStreamSerdeProvider:null!=(_d2=null==config?void 0:config.eventStreamSerdeProvider)?_d2:eventStreamSerdeProvider2,maxAttempts:null!=(_e2=null==config?void 0:config.maxAttempts)?_e2:3,md5:null!=(_f=null==config?void 0:config.md5)?_f:Md5,region:null!=(_g=null==config?void 0:config.region)?_g:invalidProvider("Region is missing"),requestHandler:FetchHttpHandler.create(null!=(_h=null==config?void 0:config.requestHandler)?_h:defaultConfigProvider),retryMode:null!=(_i2=null==config?void 0:config.retryMode)?_i2:async()=>(await defaultConfigProvider()).retryMode||DEFAULT_RETRY_MODE,sha1:null!=(_j=null==config?void 0:config.sha1)?_j:Sha12,sha256:null!=(_k=null==config?void 0:config.sha256)?_k:Sha2563,streamCollector:null!=(_l2=null==config?void 0:config.streamCollector)?_l2:streamCollector,streamHasher:null!=(_m2=null==config?void 0:config.streamHasher)?_m2:blobHasher,useDualstackEndpoint:null!=(_n2=null==config?void 0:config.useDualstackEndpoint)?_n2:()=>Promise.resolve(!1),useFipsEndpoint:null!=(_o=null==config?void 0:config.useFipsEndpoint)?_o:()=>Promise.resolve(!1)}};getAwsRegionExtensionConfiguration=runtimeConfig=>({setRegion(region){runtimeConfig.region=region},region:()=>runtimeConfig.region});resolveAwsRegionExtensionConfiguration=awsRegionExtensionConfiguration=>({region:awsRegionExtensionConfiguration.region()});getHttpAuthExtensionConfiguration=runtimeConfig=>{const _httpAuthSchemes=runtimeConfig.httpAuthSchemes;let _httpAuthSchemeProvider=runtimeConfig.httpAuthSchemeProvider,_credentials=runtimeConfig.credentials;return{setHttpAuthScheme(httpAuthScheme){const index6=_httpAuthSchemes.findIndex((scheme=>scheme.schemeId===httpAuthScheme.schemeId));-1===index6?_httpAuthSchemes.push(httpAuthScheme):_httpAuthSchemes.splice(index6,1,httpAuthScheme)},httpAuthSchemes:()=>_httpAuthSchemes,setHttpAuthSchemeProvider(httpAuthSchemeProvider){_httpAuthSchemeProvider=httpAuthSchemeProvider},httpAuthSchemeProvider:()=>_httpAuthSchemeProvider,setCredentials(credentials){_credentials=credentials},credentials:()=>_credentials}};resolveHttpAuthRuntimeConfig=config=>({httpAuthSchemes:config.httpAuthSchemes(),httpAuthSchemeProvider:config.httpAuthSchemeProvider(),credentials:config.credentials()});resolveRuntimeExtensions=(runtimeConfig,extensions)=>{const extensionConfiguration=Object.assign(getAwsRegionExtensionConfiguration(runtimeConfig),getDefaultExtensionConfiguration(runtimeConfig),getHttpHandlerExtensionConfiguration(runtimeConfig),getHttpAuthExtensionConfiguration(runtimeConfig));extensions.forEach((extension=>extension.configure(extensionConfiguration)));return Object.assign(runtimeConfig,resolveAwsRegionExtensionConfiguration(extensionConfiguration),resolveDefaultRuntimeConfig2(extensionConfiguration),resolveHttpHandlerRuntimeConfig(extensionConfiguration),resolveHttpAuthRuntimeConfig(extensionConfiguration))};S3Client=class extends Client{constructor(...[configuration]){const _config_0=getRuntimeConfig2(configuration||{});super(_config_0);__publicField(this,"config");this.initConfig=_config_0;const _config_2=resolveUserAgentConfig(resolveClientEndpointParameters(_config_0)),_config_3=resolveFlexibleChecksumsConfig(_config_2),_config_4=resolveRetryConfig(_config_3),_config_6=resolveHostHeaderConfig(resolveRegionConfig(_config_4)),_config_7=resolveEndpointConfig(_config_6),_config_8=resolveEventStreamSerdeConfig(_config_7),_config_9=resolveHttpAuthSchemeConfig(_config_8),_config_10=resolveS3Config(_config_9,{session:[()=>this,CreateSessionCommand]}),_config_11=resolveRuntimeExtensions(_config_10,(null==configuration?void 0:configuration.extensions)||[]);this.config=_config_11;this.middlewareStack.use(getUserAgentPlugin(this.config));this.middlewareStack.use(getRetryPlugin(this.config));this.middlewareStack.use(getContentLengthPlugin(this.config));this.middlewareStack.use(getHostHeaderPlugin(this.config));this.middlewareStack.use(getLoggerPlugin(this.config));this.middlewareStack.use(getRecursionDetectionPlugin(this.config));this.middlewareStack.use(getHttpAuthSchemeEndpointRuleSetPlugin(this.config,{httpAuthSchemeParametersProvider:defaultS3HttpAuthSchemeParametersProvider,identityProviderConfigProvider:async config=>new DefaultIdentityProviderConfig({"aws.auth#sigv4":config.credentials,"aws.auth#sigv4a":config.credentials})}));this.middlewareStack.use(getHttpSigningPlugin(this.config));this.middlewareStack.use(getValidateBucketNamePlugin(this.config));this.middlewareStack.use(getAddExpectContinuePlugin(this.config));this.middlewareStack.use(getRegionRedirectMiddlewarePlugin(this.config));this.middlewareStack.use(getS3ExpressPlugin(this.config));this.middlewareStack.use(getS3ExpressHttpSigningPlugin(this.config))}destroy(){super.destroy()}};AbortMultipartUploadCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","AbortMultipartUpload",{}).n("S3Client","AbortMultipartUploadCommand").f(void 0,void 0).ser(se_AbortMultipartUploadCommand).de(de_AbortMultipartUploadCommand).build()){};ssecMiddlewareOptions={name:"ssecMiddleware",step:"initialize",tags:["SSE"],override:!0};getSsecPlugin=config=>({applyToStack:clientStack=>{clientStack.add(ssecMiddleware(config),ssecMiddlewareOptions)}});CompleteMultipartUploadCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","CompleteMultipartUpload",{}).n("S3Client","CompleteMultipartUploadCommand").f(CompleteMultipartUploadRequestFilterSensitiveLog,CompleteMultipartUploadOutputFilterSensitiveLog).ser(se_CompleteMultipartUploadCommand).de(de_CompleteMultipartUploadCommand).build()){};CopyObjectCommand=class extends(Command.classBuilder().ep({...commonParams,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"},CopySource:{type:"contextParams",name:"CopySource"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","CopyObject",{}).n("S3Client","CopyObjectCommand").f(CopyObjectRequestFilterSensitiveLog,CopyObjectOutputFilterSensitiveLog).ser(se_CopyObjectCommand).de(de_CopyObjectCommand).build()){};locationConstraintMiddlewareOptions={step:"initialize",tags:["LOCATION_CONSTRAINT","CREATE_BUCKET_CONFIGURATION"],name:"locationConstraintMiddleware",override:!0};getLocationConstraintPlugin=config=>({applyToStack:clientStack=>{clientStack.add(locationConstraintMiddleware(config),locationConstraintMiddlewareOptions)}});CreateBucketCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},DisableAccessPoints:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getLocationConstraintPlugin(config)]})).s("AmazonS3","CreateBucket",{}).n("S3Client","CreateBucketCommand").f(void 0,void 0).ser(se_CreateBucketCommand).de(de_CreateBucketCommand).build()){};CreateBucketMetadataTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","CreateBucketMetadataTableConfiguration",{}).n("S3Client","CreateBucketMetadataTableConfigurationCommand").f(void 0,void 0).ser(se_CreateBucketMetadataTableConfigurationCommand).de(de_CreateBucketMetadataTableConfigurationCommand).build()){};CreateMultipartUploadCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","CreateMultipartUpload",{}).n("S3Client","CreateMultipartUploadCommand").f(CreateMultipartUploadRequestFilterSensitiveLog,CreateMultipartUploadOutputFilterSensitiveLog).ser(se_CreateMultipartUploadCommand).de(de_CreateMultipartUploadCommand).build()){};DeleteBucketAnalyticsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketAnalyticsConfiguration",{}).n("S3Client","DeleteBucketAnalyticsConfigurationCommand").f(void 0,void 0).ser(se_DeleteBucketAnalyticsConfigurationCommand).de(de_DeleteBucketAnalyticsConfigurationCommand).build()){};DeleteBucketCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucket",{}).n("S3Client","DeleteBucketCommand").f(void 0,void 0).ser(se_DeleteBucketCommand).de(de_DeleteBucketCommand).build()){};DeleteBucketCorsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketCors",{}).n("S3Client","DeleteBucketCorsCommand").f(void 0,void 0).ser(se_DeleteBucketCorsCommand).de(de_DeleteBucketCorsCommand).build()){};DeleteBucketEncryptionCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketEncryption",{}).n("S3Client","DeleteBucketEncryptionCommand").f(void 0,void 0).ser(se_DeleteBucketEncryptionCommand).de(de_DeleteBucketEncryptionCommand).build()){};DeleteBucketIntelligentTieringConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketIntelligentTieringConfiguration",{}).n("S3Client","DeleteBucketIntelligentTieringConfigurationCommand").f(void 0,void 0).ser(se_DeleteBucketIntelligentTieringConfigurationCommand).de(de_DeleteBucketIntelligentTieringConfigurationCommand).build()){};DeleteBucketInventoryConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketInventoryConfiguration",{}).n("S3Client","DeleteBucketInventoryConfigurationCommand").f(void 0,void 0).ser(se_DeleteBucketInventoryConfigurationCommand).de(de_DeleteBucketInventoryConfigurationCommand).build()){};DeleteBucketLifecycleCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketLifecycle",{}).n("S3Client","DeleteBucketLifecycleCommand").f(void 0,void 0).ser(se_DeleteBucketLifecycleCommand).de(de_DeleteBucketLifecycleCommand).build()){};DeleteBucketMetadataTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketMetadataTableConfiguration",{}).n("S3Client","DeleteBucketMetadataTableConfigurationCommand").f(void 0,void 0).ser(se_DeleteBucketMetadataTableConfigurationCommand).de(de_DeleteBucketMetadataTableConfigurationCommand).build()){};DeleteBucketMetricsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketMetricsConfiguration",{}).n("S3Client","DeleteBucketMetricsConfigurationCommand").f(void 0,void 0).ser(se_DeleteBucketMetricsConfigurationCommand).de(de_DeleteBucketMetricsConfigurationCommand).build()){};DeleteBucketOwnershipControlsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketOwnershipControls",{}).n("S3Client","DeleteBucketOwnershipControlsCommand").f(void 0,void 0).ser(se_DeleteBucketOwnershipControlsCommand).de(de_DeleteBucketOwnershipControlsCommand).build()){};DeleteBucketPolicyCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketPolicy",{}).n("S3Client","DeleteBucketPolicyCommand").f(void 0,void 0).ser(se_DeleteBucketPolicyCommand).de(de_DeleteBucketPolicyCommand).build()){};DeleteBucketReplicationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketReplication",{}).n("S3Client","DeleteBucketReplicationCommand").f(void 0,void 0).ser(se_DeleteBucketReplicationCommand).de(de_DeleteBucketReplicationCommand).build()){};DeleteBucketTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketTagging",{}).n("S3Client","DeleteBucketTaggingCommand").f(void 0,void 0).ser(se_DeleteBucketTaggingCommand).de(de_DeleteBucketTaggingCommand).build()){};DeleteBucketWebsiteCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketWebsite",{}).n("S3Client","DeleteBucketWebsiteCommand").f(void 0,void 0).ser(se_DeleteBucketWebsiteCommand).de(de_DeleteBucketWebsiteCommand).build()){};DeleteObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","DeleteObject",{}).n("S3Client","DeleteObjectCommand").f(void 0,void 0).ser(se_DeleteObjectCommand).de(de_DeleteObjectCommand).build()){};DeleteObjectsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","DeleteObjects",{}).n("S3Client","DeleteObjectsCommand").f(void 0,void 0).ser(se_DeleteObjectsCommand).de(de_DeleteObjectsCommand).build()){};DeleteObjectTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","DeleteObjectTagging",{}).n("S3Client","DeleteObjectTaggingCommand").f(void 0,void 0).ser(se_DeleteObjectTaggingCommand).de(de_DeleteObjectTaggingCommand).build()){};DeletePublicAccessBlockCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeletePublicAccessBlock",{}).n("S3Client","DeletePublicAccessBlockCommand").f(void 0,void 0).ser(se_DeletePublicAccessBlockCommand).de(de_DeletePublicAccessBlockCommand).build()){};GetBucketAccelerateConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketAccelerateConfiguration",{}).n("S3Client","GetBucketAccelerateConfigurationCommand").f(void 0,void 0).ser(se_GetBucketAccelerateConfigurationCommand).de(de_GetBucketAccelerateConfigurationCommand).build()){};GetBucketAclCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketAcl",{}).n("S3Client","GetBucketAclCommand").f(void 0,void 0).ser(se_GetBucketAclCommand).de(de_GetBucketAclCommand).build()){};GetBucketAnalyticsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketAnalyticsConfiguration",{}).n("S3Client","GetBucketAnalyticsConfigurationCommand").f(void 0,void 0).ser(se_GetBucketAnalyticsConfigurationCommand).de(de_GetBucketAnalyticsConfigurationCommand).build()){};GetBucketCorsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketCors",{}).n("S3Client","GetBucketCorsCommand").f(void 0,void 0).ser(se_GetBucketCorsCommand).de(de_GetBucketCorsCommand).build()){};GetBucketEncryptionCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketEncryption",{}).n("S3Client","GetBucketEncryptionCommand").f(void 0,GetBucketEncryptionOutputFilterSensitiveLog).ser(se_GetBucketEncryptionCommand).de(de_GetBucketEncryptionCommand).build()){};GetBucketIntelligentTieringConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketIntelligentTieringConfiguration",{}).n("S3Client","GetBucketIntelligentTieringConfigurationCommand").f(void 0,void 0).ser(se_GetBucketIntelligentTieringConfigurationCommand).de(de_GetBucketIntelligentTieringConfigurationCommand).build()){};GetBucketInventoryConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketInventoryConfiguration",{}).n("S3Client","GetBucketInventoryConfigurationCommand").f(void 0,GetBucketInventoryConfigurationOutputFilterSensitiveLog).ser(se_GetBucketInventoryConfigurationCommand).de(de_GetBucketInventoryConfigurationCommand).build()){};GetBucketLifecycleConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketLifecycleConfiguration",{}).n("S3Client","GetBucketLifecycleConfigurationCommand").f(void 0,void 0).ser(se_GetBucketLifecycleConfigurationCommand).de(de_GetBucketLifecycleConfigurationCommand).build()){};GetBucketLocationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketLocation",{}).n("S3Client","GetBucketLocationCommand").f(void 0,void 0).ser(se_GetBucketLocationCommand).de(de_GetBucketLocationCommand).build()){};GetBucketLoggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketLogging",{}).n("S3Client","GetBucketLoggingCommand").f(void 0,void 0).ser(se_GetBucketLoggingCommand).de(de_GetBucketLoggingCommand).build()){};GetBucketMetadataTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketMetadataTableConfiguration",{}).n("S3Client","GetBucketMetadataTableConfigurationCommand").f(void 0,void 0).ser(se_GetBucketMetadataTableConfigurationCommand).de(de_GetBucketMetadataTableConfigurationCommand).build()){};GetBucketMetricsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketMetricsConfiguration",{}).n("S3Client","GetBucketMetricsConfigurationCommand").f(void 0,void 0).ser(se_GetBucketMetricsConfigurationCommand).de(de_GetBucketMetricsConfigurationCommand).build()){};GetBucketNotificationConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketNotificationConfiguration",{}).n("S3Client","GetBucketNotificationConfigurationCommand").f(void 0,void 0).ser(se_GetBucketNotificationConfigurationCommand).de(de_GetBucketNotificationConfigurationCommand).build()){};GetBucketOwnershipControlsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketOwnershipControls",{}).n("S3Client","GetBucketOwnershipControlsCommand").f(void 0,void 0).ser(se_GetBucketOwnershipControlsCommand).de(de_GetBucketOwnershipControlsCommand).build()){};GetBucketPolicyCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketPolicy",{}).n("S3Client","GetBucketPolicyCommand").f(void 0,void 0).ser(se_GetBucketPolicyCommand).de(de_GetBucketPolicyCommand).build()){};GetBucketPolicyStatusCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketPolicyStatus",{}).n("S3Client","GetBucketPolicyStatusCommand").f(void 0,void 0).ser(se_GetBucketPolicyStatusCommand).de(de_GetBucketPolicyStatusCommand).build()){};GetBucketReplicationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketReplication",{}).n("S3Client","GetBucketReplicationCommand").f(void 0,void 0).ser(se_GetBucketReplicationCommand).de(de_GetBucketReplicationCommand).build()){};GetBucketRequestPaymentCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketRequestPayment",{}).n("S3Client","GetBucketRequestPaymentCommand").f(void 0,void 0).ser(se_GetBucketRequestPaymentCommand).de(de_GetBucketRequestPaymentCommand).build()){};GetBucketTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketTagging",{}).n("S3Client","GetBucketTaggingCommand").f(void 0,void 0).ser(se_GetBucketTaggingCommand).de(de_GetBucketTaggingCommand).build()){};GetBucketVersioningCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketVersioning",{}).n("S3Client","GetBucketVersioningCommand").f(void 0,void 0).ser(se_GetBucketVersioningCommand).de(de_GetBucketVersioningCommand).build()){};GetBucketWebsiteCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketWebsite",{}).n("S3Client","GetBucketWebsiteCommand").f(void 0,void 0).ser(se_GetBucketWebsiteCommand).de(de_GetBucketWebsiteCommand).build()){};GetObjectAclCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectAcl",{}).n("S3Client","GetObjectAclCommand").f(void 0,void 0).ser(se_GetObjectAclCommand).de(de_GetObjectAclCommand).build()){};GetObjectAttributesCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","GetObjectAttributes",{}).n("S3Client","GetObjectAttributesCommand").f(GetObjectAttributesRequestFilterSensitiveLog,void 0).ser(se_GetObjectAttributesCommand).de(de_GetObjectAttributesCommand).build()){};GetObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestChecksumRequired:!1,requestValidationModeMember:"ChecksumMode",responseAlgorithms:["CRC64NVME","CRC32","CRC32C","SHA256","SHA1"]}),getSsecPlugin(config),getS3ExpiresMiddlewarePlugin()]})).s("AmazonS3","GetObject",{}).n("S3Client","GetObjectCommand").f(GetObjectRequestFilterSensitiveLog,GetObjectOutputFilterSensitiveLog).ser(se_GetObjectCommand).de(de_GetObjectCommand).build()){};GetObjectLegalHoldCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectLegalHold",{}).n("S3Client","GetObjectLegalHoldCommand").f(void 0,void 0).ser(se_GetObjectLegalHoldCommand).de(de_GetObjectLegalHoldCommand).build()){};GetObjectLockConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectLockConfiguration",{}).n("S3Client","GetObjectLockConfigurationCommand").f(void 0,void 0).ser(se_GetObjectLockConfigurationCommand).de(de_GetObjectLockConfigurationCommand).build()){};GetObjectRetentionCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectRetention",{}).n("S3Client","GetObjectRetentionCommand").f(void 0,void 0).ser(se_GetObjectRetentionCommand).de(de_GetObjectRetentionCommand).build()){};GetObjectTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectTagging",{}).n("S3Client","GetObjectTaggingCommand").f(void 0,void 0).ser(se_GetObjectTaggingCommand).de(de_GetObjectTaggingCommand).build()){};GetObjectTorrentCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","GetObjectTorrent",{}).n("S3Client","GetObjectTorrentCommand").f(void 0,GetObjectTorrentOutputFilterSensitiveLog).ser(se_GetObjectTorrentCommand).de(de_GetObjectTorrentCommand).build()){};GetPublicAccessBlockCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetPublicAccessBlock",{}).n("S3Client","GetPublicAccessBlockCommand").f(void 0,void 0).ser(se_GetPublicAccessBlockCommand).de(de_GetPublicAccessBlockCommand).build()){};HeadBucketCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","HeadBucket",{}).n("S3Client","HeadBucketCommand").f(void 0,void 0).ser(se_HeadBucketCommand).de(de_HeadBucketCommand).build()){};HeadObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config),getS3ExpiresMiddlewarePlugin()]})).s("AmazonS3","HeadObject",{}).n("S3Client","HeadObjectCommand").f(HeadObjectRequestFilterSensitiveLog,HeadObjectOutputFilterSensitiveLog).ser(se_HeadObjectCommand).de(de_HeadObjectCommand).build()){};ListBucketAnalyticsConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBucketAnalyticsConfigurations",{}).n("S3Client","ListBucketAnalyticsConfigurationsCommand").f(void 0,void 0).ser(se_ListBucketAnalyticsConfigurationsCommand).de(de_ListBucketAnalyticsConfigurationsCommand).build()){};ListBucketIntelligentTieringConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBucketIntelligentTieringConfigurations",{}).n("S3Client","ListBucketIntelligentTieringConfigurationsCommand").f(void 0,void 0).ser(se_ListBucketIntelligentTieringConfigurationsCommand).de(de_ListBucketIntelligentTieringConfigurationsCommand).build()){};ListBucketInventoryConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBucketInventoryConfigurations",{}).n("S3Client","ListBucketInventoryConfigurationsCommand").f(void 0,ListBucketInventoryConfigurationsOutputFilterSensitiveLog).ser(se_ListBucketInventoryConfigurationsCommand).de(de_ListBucketInventoryConfigurationsCommand).build()){};ListBucketMetricsConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBucketMetricsConfigurations",{}).n("S3Client","ListBucketMetricsConfigurationsCommand").f(void 0,void 0).ser(se_ListBucketMetricsConfigurationsCommand).de(de_ListBucketMetricsConfigurationsCommand).build()){};ListBucketsCommand=class extends(Command.classBuilder().ep(commonParams).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBuckets",{}).n("S3Client","ListBucketsCommand").f(void 0,void 0).ser(se_ListBucketsCommand).de(de_ListBucketsCommand).build()){};ListDirectoryBucketsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListDirectoryBuckets",{}).n("S3Client","ListDirectoryBucketsCommand").f(void 0,void 0).ser(se_ListDirectoryBucketsCommand).de(de_ListDirectoryBucketsCommand).build()){};ListMultipartUploadsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListMultipartUploads",{}).n("S3Client","ListMultipartUploadsCommand").f(void 0,void 0).ser(se_ListMultipartUploadsCommand).de(de_ListMultipartUploadsCommand).build()){};ListObjectsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListObjects",{}).n("S3Client","ListObjectsCommand").f(void 0,void 0).ser(se_ListObjectsCommand).de(de_ListObjectsCommand).build()){};ListObjectsV2Command=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").f(void 0,void 0).ser(se_ListObjectsV2Command).de(de_ListObjectsV2Command).build()){};ListObjectVersionsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Prefix:{type:"contextParams",name:"Prefix"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListObjectVersions",{}).n("S3Client","ListObjectVersionsCommand").f(void 0,void 0).ser(se_ListObjectVersionsCommand).de(de_ListObjectVersionsCommand).build()){};ListPartsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","ListParts",{}).n("S3Client","ListPartsCommand").f(ListPartsRequestFilterSensitiveLog,void 0).ser(se_ListPartsCommand).de(de_ListPartsCommand).build()){};PutBucketAccelerateConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1})]})).s("AmazonS3","PutBucketAccelerateConfiguration",{}).n("S3Client","PutBucketAccelerateConfigurationCommand").f(void 0,void 0).ser(se_PutBucketAccelerateConfigurationCommand).de(de_PutBucketAccelerateConfigurationCommand).build()){};PutBucketAclCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketAcl",{}).n("S3Client","PutBucketAclCommand").f(void 0,void 0).ser(se_PutBucketAclCommand).de(de_PutBucketAclCommand).build()){};PutBucketAnalyticsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketAnalyticsConfiguration",{}).n("S3Client","PutBucketAnalyticsConfigurationCommand").f(void 0,void 0).ser(se_PutBucketAnalyticsConfigurationCommand).de(de_PutBucketAnalyticsConfigurationCommand).build()){};PutBucketCorsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketCors",{}).n("S3Client","PutBucketCorsCommand").f(void 0,void 0).ser(se_PutBucketCorsCommand).de(de_PutBucketCorsCommand).build()){};PutBucketEncryptionCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketEncryption",{}).n("S3Client","PutBucketEncryptionCommand").f(PutBucketEncryptionRequestFilterSensitiveLog,void 0).ser(se_PutBucketEncryptionCommand).de(de_PutBucketEncryptionCommand).build()){};PutBucketIntelligentTieringConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketIntelligentTieringConfiguration",{}).n("S3Client","PutBucketIntelligentTieringConfigurationCommand").f(void 0,void 0).ser(se_PutBucketIntelligentTieringConfigurationCommand).de(de_PutBucketIntelligentTieringConfigurationCommand).build()){};PutBucketInventoryConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketInventoryConfiguration",{}).n("S3Client","PutBucketInventoryConfigurationCommand").f(PutBucketInventoryConfigurationRequestFilterSensitiveLog,void 0).ser(se_PutBucketInventoryConfigurationCommand).de(de_PutBucketInventoryConfigurationCommand).build()){};PutBucketLifecycleConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","PutBucketLifecycleConfiguration",{}).n("S3Client","PutBucketLifecycleConfigurationCommand").f(void 0,void 0).ser(se_PutBucketLifecycleConfigurationCommand).de(de_PutBucketLifecycleConfigurationCommand).build()){};PutBucketLoggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketLogging",{}).n("S3Client","PutBucketLoggingCommand").f(void 0,void 0).ser(se_PutBucketLoggingCommand).de(de_PutBucketLoggingCommand).build()){};PutBucketMetricsConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketMetricsConfiguration",{}).n("S3Client","PutBucketMetricsConfigurationCommand").f(void 0,void 0).ser(se_PutBucketMetricsConfigurationCommand).de(de_PutBucketMetricsConfigurationCommand).build()){};PutBucketNotificationConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketNotificationConfiguration",{}).n("S3Client","PutBucketNotificationConfigurationCommand").f(void 0,void 0).ser(se_PutBucketNotificationConfigurationCommand).de(de_PutBucketNotificationConfigurationCommand).build()){};PutBucketOwnershipControlsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketOwnershipControls",{}).n("S3Client","PutBucketOwnershipControlsCommand").f(void 0,void 0).ser(se_PutBucketOwnershipControlsCommand).de(de_PutBucketOwnershipControlsCommand).build()){};PutBucketPolicyCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketPolicy",{}).n("S3Client","PutBucketPolicyCommand").f(void 0,void 0).ser(se_PutBucketPolicyCommand).de(de_PutBucketPolicyCommand).build()){};PutBucketReplicationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketReplication",{}).n("S3Client","PutBucketReplicationCommand").f(void 0,void 0).ser(se_PutBucketReplicationCommand).de(de_PutBucketReplicationCommand).build()){};PutBucketRequestPaymentCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketRequestPayment",{}).n("S3Client","PutBucketRequestPaymentCommand").f(void 0,void 0).ser(se_PutBucketRequestPaymentCommand).de(de_PutBucketRequestPaymentCommand).build()){};PutBucketTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketTagging",{}).n("S3Client","PutBucketTaggingCommand").f(void 0,void 0).ser(se_PutBucketTaggingCommand).de(de_PutBucketTaggingCommand).build()){};PutBucketVersioningCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketVersioning",{}).n("S3Client","PutBucketVersioningCommand").f(void 0,void 0).ser(se_PutBucketVersioningCommand).de(de_PutBucketVersioningCommand).build()){};PutBucketWebsiteCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketWebsite",{}).n("S3Client","PutBucketWebsiteCommand").f(void 0,void 0).ser(se_PutBucketWebsiteCommand).de(de_PutBucketWebsiteCommand).build()){};PutObjectAclCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","PutObjectAcl",{}).n("S3Client","PutObjectAclCommand").f(void 0,void 0).ser(se_PutObjectAclCommand).de(de_PutObjectAclCommand).build()){};PutObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),getCheckContentLengthHeaderPlugin(),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","PutObject",{}).n("S3Client","PutObjectCommand").f(PutObjectRequestFilterSensitiveLog,PutObjectOutputFilterSensitiveLog).ser(se_PutObjectCommand).de(de_PutObjectCommand).build()){};PutObjectLegalHoldCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","PutObjectLegalHold",{}).n("S3Client","PutObjectLegalHoldCommand").f(void 0,void 0).ser(se_PutObjectLegalHoldCommand).de(de_PutObjectLegalHoldCommand).build()){};PutObjectLockConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","PutObjectLockConfiguration",{}).n("S3Client","PutObjectLockConfigurationCommand").f(void 0,void 0).ser(se_PutObjectLockConfigurationCommand).de(de_PutObjectLockConfigurationCommand).build()){};PutObjectRetentionCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","PutObjectRetention",{}).n("S3Client","PutObjectRetentionCommand").f(void 0,void 0).ser(se_PutObjectRetentionCommand).de(de_PutObjectRetentionCommand).build()){};PutObjectTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","PutObjectTagging",{}).n("S3Client","PutObjectTaggingCommand").f(void 0,void 0).ser(se_PutObjectTaggingCommand).de(de_PutObjectTaggingCommand).build()){};PutPublicAccessBlockCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutPublicAccessBlock",{}).n("S3Client","PutPublicAccessBlockCommand").f(void 0,void 0).ser(se_PutPublicAccessBlockCommand).de(de_PutPublicAccessBlockCommand).build()){};RestoreObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","RestoreObject",{}).n("S3Client","RestoreObjectCommand").f(RestoreObjectRequestFilterSensitiveLog,void 0).ser(se_RestoreObjectCommand).de(de_RestoreObjectCommand).build()){};SelectObjectContentCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","SelectObjectContent",{eventStream:{output:!0}}).n("S3Client","SelectObjectContentCommand").f(SelectObjectContentRequestFilterSensitiveLog,SelectObjectContentOutputFilterSensitiveLog).ser(se_SelectObjectContentCommand).de(de_SelectObjectContentCommand).build()){};UploadPartCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1}),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","UploadPart",{}).n("S3Client","UploadPartCommand").f(UploadPartRequestFilterSensitiveLog,UploadPartOutputFilterSensitiveLog).ser(se_UploadPartCommand).de(de_UploadPartCommand).build()){};UploadPartCopyCommand=class extends(Command.classBuilder().ep({...commonParams,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","UploadPartCopy",{}).n("S3Client","UploadPartCopyCommand").f(UploadPartCopyRequestFilterSensitiveLog,UploadPartCopyOutputFilterSensitiveLog).ser(se_UploadPartCopyCommand).de(de_UploadPartCopyCommand).build()){};WriteGetObjectResponseCommand=class extends(Command.classBuilder().ep({...commonParams,UseObjectLambdaEndpoint:{type:"staticContextParams",value:!0}}).m((function(Command2,cs2,config,o2){return[getSerdePlugin(config,this.serialize,this.deserialize),getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","WriteGetObjectResponse",{}).n("S3Client","WriteGetObjectResponseCommand").f(WriteGetObjectResponseRequestFilterSensitiveLog,void 0).ser(se_WriteGetObjectResponseCommand).de(de_WriteGetObjectResponseCommand).build()){};createAggregatedClient({AbortMultipartUploadCommand,CompleteMultipartUploadCommand,CopyObjectCommand,CreateBucketCommand,CreateBucketMetadataTableConfigurationCommand,CreateMultipartUploadCommand,CreateSessionCommand,DeleteBucketCommand,DeleteBucketAnalyticsConfigurationCommand,DeleteBucketCorsCommand,DeleteBucketEncryptionCommand,DeleteBucketIntelligentTieringConfigurationCommand,DeleteBucketInventoryConfigurationCommand,DeleteBucketLifecycleCommand,DeleteBucketMetadataTableConfigurationCommand,DeleteBucketMetricsConfigurationCommand,DeleteBucketOwnershipControlsCommand,DeleteBucketPolicyCommand,DeleteBucketReplicationCommand,DeleteBucketTaggingCommand,DeleteBucketWebsiteCommand,DeleteObjectCommand,DeleteObjectsCommand,DeleteObjectTaggingCommand,DeletePublicAccessBlockCommand,GetBucketAccelerateConfigurationCommand,GetBucketAclCommand,GetBucketAnalyticsConfigurationCommand,GetBucketCorsCommand,GetBucketEncryptionCommand,GetBucketIntelligentTieringConfigurationCommand,GetBucketInventoryConfigurationCommand,GetBucketLifecycleConfigurationCommand,GetBucketLocationCommand,GetBucketLoggingCommand,GetBucketMetadataTableConfigurationCommand,GetBucketMetricsConfigurationCommand,GetBucketNotificationConfigurationCommand,GetBucketOwnershipControlsCommand,GetBucketPolicyCommand,GetBucketPolicyStatusCommand,GetBucketReplicationCommand,GetBucketRequestPaymentCommand,GetBucketTaggingCommand,GetBucketVersioningCommand,GetBucketWebsiteCommand,GetObjectCommand,GetObjectAclCommand,GetObjectAttributesCommand,GetObjectLegalHoldCommand,GetObjectLockConfigurationCommand,GetObjectRetentionCommand,GetObjectTaggingCommand,GetObjectTorrentCommand,GetPublicAccessBlockCommand,HeadBucketCommand,HeadObjectCommand,ListBucketAnalyticsConfigurationsCommand,ListBucketIntelligentTieringConfigurationsCommand,ListBucketInventoryConfigurationsCommand,ListBucketMetricsConfigurationsCommand,ListBucketsCommand,ListDirectoryBucketsCommand,ListMultipartUploadsCommand,ListObjectsCommand,ListObjectsV2Command,ListObjectVersionsCommand,ListPartsCommand,PutBucketAccelerateConfigurationCommand,PutBucketAclCommand,PutBucketAnalyticsConfigurationCommand,PutBucketCorsCommand,PutBucketEncryptionCommand,PutBucketIntelligentTieringConfigurationCommand,PutBucketInventoryConfigurationCommand,PutBucketLifecycleConfigurationCommand,PutBucketLoggingCommand,PutBucketMetricsConfigurationCommand,PutBucketNotificationConfigurationCommand,PutBucketOwnershipControlsCommand,PutBucketPolicyCommand,PutBucketReplicationCommand,PutBucketRequestPaymentCommand,PutBucketTaggingCommand,PutBucketVersioningCommand,PutBucketWebsiteCommand,PutObjectCommand,PutObjectAclCommand,PutObjectLegalHoldCommand,PutObjectLockConfigurationCommand,PutObjectRetentionCommand,PutObjectTaggingCommand,PutPublicAccessBlockCommand,RestoreObjectCommand,SelectObjectContentCommand,UploadPartCommand,UploadPartCopyCommand,WriteGetObjectResponseCommand},S3=class extends S3Client{});applyMd5BodyChecksumMiddleware=options=>next2=>async args=>{const{request:request2}=args;if(HttpRequest.isInstance(request2)){const{body,headers}=request2;if(!hasHeader3("content-md5",headers)){let digest;if(void 0===body||"string"==typeof body||ArrayBuffer.isView(body)||isArrayBuffer(body)){const hash3=new options.md5;hash3.update(body||"");digest=hash3.digest()}else digest=options.streamHasher(options.md5,body);const cloned=HttpRequest.clone(request2);cloned.headers={...headers,"content-md5":options.base64Encoder(await digest)};return next2({...args,request:cloned})}}return next2(args)};hasHeader3=(soughtHeader,headers)=>{soughtHeader=soughtHeader.toLowerCase();for(const headerName of Object.keys(headers))if(soughtHeader===headerName.toLowerCase())return!0;return!1};ch2={};wk=function(c3,id,msg,transfer,cb2){var w2=new Worker(ch2[id]||(ch2[id]=URL.createObjectURL(new Blob([c3+';addEventListener("error",function(e){e=e.error;postMessage({$e$:[e.message,e.code,e.stack]})})'],{type:"text/javascript"}))));w2.onmessage=function(e3){var err3,d4=e3.data,ed=d4.$e$;if(ed){(err3=new Error(ed[0])).code=ed[1];err3.stack=ed[2];cb2(err3,null)}else cb2(null,d4)};w2.postMessage(msg,transfer);return w2};u8=Uint8Array,u16=Uint16Array,i32=Int32Array;fleb=new u8([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]);fdeb=new u8([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]);clim=new u8([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);freb=function(eb,start){var i2,r4,j2,b3=new u16(31);for(i2=0;i2<31;++i2)b3[i2]=start+=1<<eb[i2-1];r4=new i32(b3[30]);for(i2=1;i2<30;++i2)for(j2=b3[i2];j2<b3[i2+1];++j2)r4[j2]=j2-b3[i2]<<5|i2;return{b:b3,r:r4}};_a6=freb(fleb,2),fl=_a6.b,revfl=_a6.r;fl[28]=258,revfl[258]=28;_b4=freb(fdeb,0),fd=_b4.b,revfd=_b4.r;rev=new u16(32768);for(i2=0;i2<32768;++i2){x2=(61680&(x2=(52428&(x2=(43690&i2)>>1|(21845&i2)<<1))>>2|(13107&x2)<<2))>>4|(3855&x2)<<4;rev[i2]=((65280&x2)>>8|(255&x2)<<8)>>1}hMap=function(cd2,mb,r4){for(var le,co2,rvb,sv,r_1,v2,m3,s2=cd2.length,i2=0,l2=new u16(mb);i2<s2;++i2)cd2[i2]&&++l2[cd2[i2]-1];le=new u16(mb);for(i2=1;i2<mb;++i2)le[i2]=le[i2-1]+l2[i2-1]<<1;if(r4){co2=new u16(1<<mb);rvb=15-mb;for(i2=0;i2<s2;++i2)if(cd2[i2]){sv=i2<<4|cd2[i2];r_1=mb-cd2[i2];for(m3=(v2=le[cd2[i2]-1]++<<r_1)|(1<<r_1)-1;v2<=m3;++v2)co2[rev[v2]>>rvb]=sv}}else{co2=new u16(s2);for(i2=0;i2<s2;++i2)cd2[i2]&&(co2[i2]=rev[le[cd2[i2]-1]++]>>15-cd2[i2])}return co2};flt=new u8(288);for(i2=0;i2<144;++i2)flt[i2]=8;for(i2=144;i2<256;++i2)flt[i2]=9;for(i2=256;i2<280;++i2)flt[i2]=7;for(i2=280;i2<288;++i2)flt[i2]=8;fdt=new u8(32);for(i2=0;i2<32;++i2)fdt[i2]=5;flm=hMap(flt,9,0),flrm=hMap(flt,9,1);fdm=hMap(fdt,5,0),fdrm=hMap(fdt,5,1);max=function(a2){var i2,m3=a2[0];for(i2=1;i2<a2.length;++i2)a2[i2]>m3&&(m3=a2[i2]);return m3};bits=function(d4,p4,m3){var o2=p4/8|0;return(d4[o2]|d4[o2+1]<<8)>>(7&p4)&m3};bits16=function(d4,p4){var o2=p4/8|0;return(d4[o2]|d4[o2+1]<<8|d4[o2+2]<<16)>>(7&p4)};shft=function(p4){return(p4+7)/8|0};slc=function(v2,s2,e3){(null==s2||s2<0)&&(s2=0);(null==e3||e3>v2.length)&&(e3=v2.length);return new u8(v2.subarray(s2,e3))};ec=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"];err2=function(ind,msg,nt){var e3=new Error(msg||ec[ind]);e3.code=ind;Error.captureStackTrace&&Error.captureStackTrace(e3,err2);if(!nt)throw e3;return e3};inflt=function(dat,st,buf,dict){var noBuf,resize,noSt,cbuf,final,pos,bt2,lm,dm,lbt,dbt,tbts,type,s2,l2,t3,hLit,hcLen,tl,ldt,clt,i2,clb,clbmsk,clm,r4,c3,n3,lt,dt,lms,dms,lpos,sym,add,b3,d4,dsym,end,shift,dend,sl=dat.length,dl=dict?dict.length:0;if(!sl||st.f&&!st.l)return buf||new u8(0);resize=(noBuf=!buf)||2!=st.i;noSt=st.i;noBuf&&(buf=new u8(3*sl));cbuf=function(l3){var nbuf,bl2=buf.length;if(l3>bl2){(nbuf=new u8(Math.max(2*bl2,l3))).set(buf);buf=nbuf}};final=st.f||0,pos=st.p||0,bt2=st.b||0,lm=st.l,dm=st.d,lbt=st.m,dbt=st.n;tbts=8*sl;do{if(!lm){final=bits(dat,pos,1);type=bits(dat,pos+1,3);pos+=3;if(!type){if((t3=(s2=shft(pos)+4)+(l2=dat[s2-4]|dat[s2-3]<<8))>sl){noSt&&err2(0);break}resize&&cbuf(bt2+l2);buf.set(dat.subarray(s2,t3),bt2);st.b=bt2+=l2,st.p=pos=8*t3,st.f=final;continue}if(1==type)lm=flrm,dm=fdrm,lbt=9,dbt=5;else if(2==type){hLit=bits(dat,pos,31)+257,hcLen=bits(dat,pos+10,15)+4;tl=hLit+bits(dat,pos+5,31)+1;pos+=14;ldt=new u8(tl);clt=new u8(19);for(i2=0;i2<hcLen;++i2)clt[clim[i2]]=bits(dat,pos+3*i2,7);pos+=3*hcLen;clbmsk=(1<<(clb=max(clt)))-1;clm=hMap(clt,clb,1);for(i2=0;i2<tl;){pos+=15&(r4=clm[bits(dat,pos,clbmsk)]);if((s2=r4>>4)<16)ldt[i2++]=s2;else{c3=0,n3=0;16==s2?(n3=3+bits(dat,pos,3),pos+=2,c3=ldt[i2-1]):17==s2?(n3=3+bits(dat,pos,7),pos+=3):18==s2&&(n3=11+bits(dat,pos,127),pos+=7);for(;n3--;)ldt[i2++]=c3}}lt=ldt.subarray(0,hLit),dt=ldt.subarray(hLit);lbt=max(lt);dbt=max(dt);lm=hMap(lt,lbt,1);dm=hMap(dt,dbt,1)}else err2(1);if(pos>tbts){noSt&&err2(0);break}}resize&&cbuf(bt2+131072);lms=(1<<lbt)-1,dms=(1<<dbt)-1;lpos=pos;for(;;lpos=pos){sym=(c3=lm[bits16(dat,pos)&lms])>>4;if((pos+=15&c3)>tbts){noSt&&err2(0);break}c3||err2(2);if(sym<256)buf[bt2++]=sym;else{if(256==sym){lpos=pos,lm=null;break}add=sym-254;if(sym>264){b3=fleb[i2=sym-257];add=bits(dat,pos,(1<<b3)-1)+fl[i2];pos+=b3}dsym=(d4=dm[bits16(dat,pos)&dms])>>4;d4||err2(3);pos+=15&d4;dt=fd[dsym];if(dsym>3){b3=fdeb[dsym];dt+=bits16(dat,pos)&(1<<b3)-1,pos+=b3}if(pos>tbts){noSt&&err2(0);break}resize&&cbuf(bt2+131072);end=bt2+add;if(bt2<dt){shift=dl-dt,dend=Math.min(dt,end);shift+bt2<0&&err2(3);for(;bt2<dend;++bt2)buf[bt2]=dict[shift+bt2]}for(;bt2<end;++bt2)buf[bt2]=buf[bt2-dt]}}st.l=lm,st.p=lpos,st.b=bt2,st.f=final;lm&&(final=1,st.m=lbt,st.d=dm,st.n=dbt)}while(!final);return bt2!=buf.length&&noBuf?slc(buf,0,bt2):buf.subarray(0,bt2)};wbits=function(d4,p4,v2){v2<<=7&p4;var o2=p4/8|0;d4[o2]|=v2;d4[o2+1]|=v2>>8};wbits16=function(d4,p4,v2){v2<<=7&p4;var o2=p4/8|0;d4[o2]|=v2;d4[o2+1]|=v2>>8;d4[o2+2]|=v2>>16};hTree=function(d4,mb){var i2,s2,t22,v2,l2,r4,i0,i1,i22,maxSym,tr,mbt,dt,lft,cst,i2_1,i2_2,i2_3,t3=[];for(i2=0;i2<d4.length;++i2)d4[i2]&&t3.push({s:i2,f:d4[i2]});s2=t3.length;t22=t3.slice();if(!s2)return{t:et,l:0};if(1==s2){(v2=new u8(t3[0].s+1))[t3[0].s]=1;return{t:v2,l:1}}t3.sort((function(a2,b3){return a2.f-b3.f}));t3.push({s:-1,f:25001});l2=t3[0],r4=t3[1],i0=0,i1=1,i22=2;t3[0]={s:-1,f:l2.f+r4.f,l:l2,r:r4};for(;i1!=s2-1;){l2=t3[t3[i0].f<t3[i22].f?i0++:i22++];r4=t3[i0!=i1&&t3[i0].f<t3[i22].f?i0++:i22++];t3[i1++]={s:-1,f:l2.f+r4.f,l:l2,r:r4}}maxSym=t22[0].s;for(i2=1;i2<s2;++i2)t22[i2].s>maxSym&&(maxSym=t22[i2].s);tr=new u16(maxSym+1);if((mbt=ln(t3[i1-1],tr,0))>mb){i2=0,dt=0;cst=1<<(lft=mbt-mb);t22.sort((function(a2,b3){return tr[b3.s]-tr[a2.s]||a2.f-b3.f}));for(;i2<s2;++i2){i2_1=t22[i2].s;if(!(tr[i2_1]>mb))break;dt+=cst-(1<<mbt-tr[i2_1]);tr[i2_1]=mb}dt>>=lft;for(;dt>0;){i2_2=t22[i2].s;tr[i2_2]<mb?dt-=1<<mb-tr[i2_2]++-1:++i2}for(;i2>=0&&dt;--i2){i2_3=t22[i2].s;if(tr[i2_3]==mb){--tr[i2_3];++dt}}mbt=mb}return{t:new u8(tr),l:mbt}};ln=function(n3,l2,d4){return-1==n3.s?Math.max(ln(n3.l,l2,d4+1),ln(n3.r,l2,d4+1)):l2[n3.s]=d4};lc=function(c3){for(var cl2,cli,cln,cls,w2,i2,s2=c3.length;s2&&!c3[--s2];);cl2=new u16(++s2);cli=0,cln=c3[0],cls=1;w2=function(v2){cl2[cli++]=v2};for(i2=1;i2<=s2;++i2)if(c3[i2]==cln&&i2!=s2)++cls;else{if(!cln&&cls>2){for(;cls>138;cls-=138)w2(32754);if(cls>2){w2(cls>10?cls-11<<5|28690:cls-3<<5|12305);cls=0}}else if(cls>3){w2(cln),--cls;for(;cls>6;cls-=6)w2(8304);cls>2&&(w2(cls-3<<5|8208),cls=0)}for(;cls--;)w2(cln);cls=1;cln=c3[i2]}return{c:cl2.subarray(0,cli),n:s2}};clen=function(cf2,cl2){var i2,l2=0;for(i2=0;i2<cl2.length;++i2)l2+=cf2[i2]*cl2[i2];return l2};wfblk=function(out,pos,dat){var i2,s2=dat.length,o2=shft(pos+2);out[o2]=255&s2;out[o2+1]=s2>>8;out[o2+2]=255^out[o2];out[o2+3]=255^out[o2+1];for(i2=0;i2<s2;++i2)out[o2+i2+4]=dat[i2];return 8*(o2+4+s2)};wblk=function(dat,out,final,syms,lf,df,eb,li,bs2,bl2,p4){var _a8,dlt,mlb,_b5,ddt,mdb,_c3,lclt,nlc,_d2,lcdt,ndc,lcfreq,i2,_e2,lct,mlcb,nlcc,flen,ftlen,dtlen,lm,ll,dm,dl,llm,lcts,it,clct,len,sym,dst;wbits(out,p4++,final);++lf[256];dlt=(_a8=hTree(lf,15)).t,mlb=_a8.l;ddt=(_b5=hTree(df,15)).t,mdb=_b5.l;lclt=(_c3=lc(dlt)).c,nlc=_c3.n;lcdt=(_d2=lc(ddt)).c,ndc=_d2.n;lcfreq=new u16(19);for(i2=0;i2<lclt.length;++i2)++lcfreq[31&lclt[i2]];for(i2=0;i2<lcdt.length;++i2)++lcfreq[31&lcdt[i2]];lct=(_e2=hTree(lcfreq,7)).t,mlcb=_e2.l;nlcc=19;for(;nlcc>4&&!lct[clim[nlcc-1]];--nlcc);flen=bl2+5<<3;ftlen=clen(lf,flt)+clen(df,fdt)+eb;dtlen=clen(lf,dlt)+clen(df,ddt)+eb+14+3*nlcc+clen(lcfreq,lct)+2*lcfreq[16]+3*lcfreq[17]+7*lcfreq[18];if(bs2>=0&&flen<=ftlen&&flen<=dtlen)return wfblk(out,p4,dat.subarray(bs2,bs2+bl2));wbits(out,p4,1+(dtlen<ftlen)),p4+=2;if(dtlen<ftlen){lm=hMap(dlt,mlb,0),ll=dlt,dm=hMap(ddt,mdb,0),dl=ddt;llm=hMap(lct,mlcb,0);wbits(out,p4,nlc-257);wbits(out,p4+5,ndc-1);wbits(out,p4+10,nlcc-4);p4+=14;for(i2=0;i2<nlcc;++i2)wbits(out,p4+3*i2,lct[clim[i2]]);p4+=3*nlcc;lcts=[lclt,lcdt];for(it=0;it<2;++it){clct=lcts[it];for(i2=0;i2<clct.length;++i2){len=31&clct[i2];wbits(out,p4,llm[len]),p4+=lct[len];len>15&&(wbits(out,p4,clct[i2]>>5&127),p4+=clct[i2]>>12)}}}else lm=flm,ll=flt,dm=fdm,dl=fdt;for(i2=0;i2<li;++i2)if((sym=syms[i2])>255){wbits16(out,p4,lm[257+(len=sym>>18&31)]),p4+=ll[len+257];len>7&&(wbits(out,p4,sym>>23&31),p4+=fleb[len]);wbits16(out,p4,dm[dst=31&sym]),p4+=dl[dst];dst>3&&(wbits16(out,p4,sym>>5&8191),p4+=fdeb[dst])}else wbits16(out,p4,lm[sym]),p4+=ll[sym];wbits16(out,p4,lm[256]);return p4+ll[256]};deo=new i32([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]);et=new u8(0);dflt=function(dat,lvl,plvl,pre,post,st){var opt,n3,c3,msk_1,prev,head2,bs1_1,bs2_1,hsh,syms,lf,df,lc_1,eb,i2,li,wi,bs2,hv,imod,pimod,rem,j2,l2,d4,ch_1,dif,maxn,maxd,ml,nl,mmd,md,ti,cd2,lin,din,e3,s2=st.z||dat.length,o2=new u8(pre+s2+5*(1+Math.ceil(s2/7e3))+post),w2=o2.subarray(pre,o2.length-post),lst=st.l,pos=7&(st.r||0);if(lvl){pos&&(w2[0]=st.r>>3);n3=(opt=deo[lvl-1])>>13,c3=8191&opt;msk_1=(1<<plvl)-1;prev=st.p||new u16(32768),head2=st.h||new u16(msk_1+1);bs1_1=Math.ceil(plvl/3),bs2_1=2*bs1_1;hsh=function(i3){return(dat[i3]^dat[i3+1]<<bs1_1^dat[i3+2]<<bs2_1)&msk_1};syms=new i32(25e3);lf=new u16(288),df=new u16(32);lc_1=0,eb=0,i2=st.i||0,li=0,wi=st.w||0,bs2=0;for(;i2+2<s2;++i2){imod=32767&i2,pimod=head2[hv=hsh(i2)];prev[imod]=pimod;head2[hv]=imod;if(wi<=i2){rem=s2-i2;if((lc_1>7e3||li>24576)&&(rem>423||!lst)){pos=wblk(dat,w2,0,syms,lf,df,eb,li,bs2,i2-bs2,pos);li=lc_1=eb=0,bs2=i2;for(j2=0;j2<286;++j2)lf[j2]=0;for(j2=0;j2<30;++j2)df[j2]=0}l2=2,d4=0,ch_1=c3,dif=imod-pimod&32767;if(rem>2&&hv==hsh(i2-dif)){maxn=Math.min(n3,rem)-1;maxd=Math.min(32767,i2);ml=Math.min(258,rem);for(;dif<=maxd&&--ch_1&&imod!=pimod;){if(dat[i2+l2]==dat[i2+l2-dif]){nl=0;for(;nl<ml&&dat[i2+nl]==dat[i2+nl-dif];++nl);if(nl>l2){l2=nl,d4=dif;if(nl>maxn)break;mmd=Math.min(dif,nl-2);md=0;for(j2=0;j2<mmd;++j2)(cd2=(ti=i2-dif+j2&32767)-prev[ti]&32767)>md&&(md=cd2,pimod=ti)}}dif+=(imod=pimod)-(pimod=prev[imod])&32767}}if(d4){syms[li++]=268435456|revfl[l2]<<18|revfd[d4];lin=31&revfl[l2],din=31&revfd[d4];eb+=fleb[lin]+fdeb[din];++lf[257+lin];++df[din];wi=i2+l2;++lc_1}else{syms[li++]=dat[i2];++lf[dat[i2]]}}}for(i2=Math.max(i2,wi);i2<s2;++i2){syms[li++]=dat[i2];++lf[dat[i2]]}pos=wblk(dat,w2,lst,syms,lf,df,eb,li,bs2,i2-bs2,pos);if(!lst){st.r=7&pos|w2[pos/8|0]<<3;pos-=7;st.h=head2,st.p=prev,st.i=i2,st.w=wi}}else{for(i2=st.w||0;i2<s2+lst;i2+=65535){if((e3=i2+65535)>=s2){w2[pos/8|0]=lst;e3=s2}pos=wfblk(w2,pos+1,dat.subarray(i2,e3))}st.i=s2}return slc(o2,0,pre+shft(pos)+post)};0;0;dopt=function(dat,opt,pre,post,st){var dict,newDat;if(!st){st={l:1};if(opt.dictionary){dict=opt.dictionary.subarray(-32768);(newDat=new u8(dict.length+dat.length)).set(dict);newDat.set(dat,dict.length);dat=newDat;st.w=dict.length}}return dflt(dat,null==opt.level?6:opt.level,null==opt.mem?st.l?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(dat.length)))):20:12+opt.mem,pre,post,st)};mrg=function(a2,b3){var k2,o2={};for(k2 in a2)o2[k2]=a2[k2];for(k2 in b3)o2[k2]=b3[k2];return o2};wcln=function(fn,fnStr,td3){var i2,v2,k2,st_1,spInd,t3,dt=fn(),st=fn.toString(),ks=st.slice(st.indexOf("[")+1,st.lastIndexOf("]")).replace(/\s+/g,"").split(",");for(i2=0;i2<dt.length;++i2){v2=dt[i2],k2=ks[i2];if("function"==typeof v2){fnStr+=";"+k2+"=";st_1=v2.toString();if(v2.prototype)if(-1!=st_1.indexOf("[native code]")){spInd=st_1.indexOf(" ",8)+1;fnStr+=st_1.slice(spInd,st_1.indexOf("(",spInd))}else{fnStr+=st_1;for(t3 in v2.prototype)fnStr+=";"+k2+".prototype."+t3+"="+v2.prototype[t3].toString()}else fnStr+=st_1}else td3[k2]=v2}return fnStr};ch3=[];cbfs=function(v2){var k2,tl=[];for(k2 in v2)v2[k2].buffer&&tl.push((v2[k2]=new v2[k2].constructor(v2[k2])).buffer);return tl};wrkr=function(fns,init3,id,cb2){var fnStr,td_1,m3,i2,td3;if(!ch3[id]){fnStr="",td_1={},m3=fns.length-1;for(i2=0;i2<m3;++i2)fnStr=wcln(fns[i2],fnStr,td_1);ch3[id]={c:wcln(fns[m3],fnStr,td_1),e:td_1}}td3=mrg({},ch3[id].e);return wk(ch3[id].c+";onmessage=function(e){for(var k in e.data)self[k]=e.data[k];onmessage="+init3.toString()+"}",id,td3,cbfs(td3),cb2)};bInflt=function(){return[u8,u16,i32,fleb,fdeb,clim,fl,fd,flrm,fdrm,rev,ec,hMap,max,bits,bits16,shft,slc,err2,inflt,inflateSync,pbf,gopt]};bDflt=function(){return[u8,u16,i32,fleb,fdeb,clim,revfl,revfd,flm,flt,fdm,fdt,rev,deo,et,hMap,wbits,wbits16,hTree,ln,lc,clen,wfblk,wblk,shft,slc,dflt,dopt,deflateSync,pbf]};pbf=function(msg){return postMessage(msg,[msg.buffer])};gopt=function(o2){return o2&&{out:o2.size&&new u8(o2.size),dictionary:o2.dictionary}};cbify=function(dat,opts,fns,init3,id,cb2){var w2=wrkr(fns,init3,id,(function(err3,dat2){w2.terminate();cb2(err3,dat2)}));w2.postMessage([dat,opts],opts.consume?[dat.buffer]:[]);return function(){w2.terminate()}};0;0;0;0;0;0;fltn=function(d4,p4,t3,o2){var k2,val2,n3,op;for(k2 in d4){val2=d4[k2],n3=p4+k2,op=o2;Array.isArray(val2)&&(op=mrg(o2,val2[1]),val2=val2[0]);if(val2 instanceof u8)t3[n3]=[val2,op];else{t3[n3+="/"]=[new u8(0),op];fltn(val2,n3,t3,o2)}}};td2="undefined"!=typeof TextDecoder&&new TextDecoder;try{td2.decode(et,{stream:!0})}catch(e3){}"function"==typeof queueMicrotask?queueMicrotask:"function"==typeof setTimeout&&setTimeout;wrappedInflate=wrapFflateFunc((function inflate(data,opts,cb2){cb2||(cb2=opts,opts={});"function"!=typeof cb2&&err2(7);return cbify(data,opts,[bInflt],(function(ev){return pbf(inflateSync(ev.data[0],gopt(ev.data[1])))}),1,cb2)}));wrappedDeflate=wrapFflateFunc((function deflate(data,opts,cb2){cb2||(cb2=opts,opts={});"function"!=typeof cb2&&err2(7);return cbify(data,opts,[bDflt],(function(ev){return pbf(deflateSync(ev.data[0],ev.data[1]))}),0,cb2)}));replicationFilter=(db,compress)=>{db.transform({incoming:async doc=>compress?await compressDoc(doc):doc,outgoing:async doc=>await decompressDoc(doc)})};MARK_SHIFT_COMPRESSED="LZ";CheckPointInfoDefault={lastLocalSeq:0,knownIDs:new Set,sentIDs:new Set,receivedFiles:new Set,sentFiles:new Set};PREFIX_TRENCH="trench";idx=0;series=`${Date.now()}`;indexes=new Map;inProgress=new Set;failed=new Map;Trench=class{constructor(db,flushExistItems=!0){Object.defineProperty(this,"_db",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"_flushTask",{enumerable:!0,configurable:!0,writable:!0,value:void 0});Object.defineProperty(this,"concealing",{enumerable:!0,configurable:!0,writable:!0,value:new Map});this._db=db;flushExistItems&&(this._flushTask=(async()=>{const keys3=await db.keys(`${PREFIX_TRENCH}-ephemeral`,`${PREFIX_TRENCH}-ephemeral.`);for(const key3 of keys3)await db.delete(key3)})())}async eraseAllEphemerals(){const keys3=await this._db.keys(`${PREFIX_TRENCH}-ephemeral`,`${PREFIX_TRENCH}-ephemeral.`);for(const key3 of keys3)await this._db.delete(key3)}async eraseAllPermanences(){const keys3=await this._db.keys(`${PREFIX_TRENCH}-permanent`,`${PREFIX_TRENCH}-permanent.`);for(const key3 of keys3)await this._db.delete(key3)}conceal(obj){const key3=generateId("ephemeral");this.concealing.set(key3,obj);this._db.set(key3,obj).then((async e3=>{this.concealing.has(key3)?this.concealing.delete(key3):await this._db.delete(key3)}));return key3}async bury(key3){this.concealing.has(key3)&&this.concealing.delete(key3);await this._db.delete(key3)}async expose(key3){if(this.concealing.has(key3)){const value=this.concealing.get(key3);this.concealing.delete(key3);return value}const obj=await this._db.get(key3);await this._db.delete(key3);return obj}_evacuate(storeTask,key3){return async()=>{if(this._flushTask){await this._flushTask;this._flushTask=void 0}await storeTask;const item=await this._db.get(key3);await this._db.delete(key3);return item}}evacuatePromise(task){const key3=generateId("ephemeral"),storeTask=(async()=>{const data=await task;await this._db.set(key3,data)})();return this._evacuate(storeTask,key3)}evacuate(obj){if(obj instanceof Promise)return this.evacuatePromise(obj);const key3=generateId("ephemeral"),storeTask=this._db.set(key3,obj);return this._evacuate(storeTask,key3)}async _queue(type,key3,obj,index6){var _a8;if(void 0===index6){index6=null!=(_a8=indexes.get(key3))?_a8:0;indexes.set(key3,index6+1)}const storeKey=createId(type,key3,index6);await this._db.set(storeKey,obj)}async _dequeue(type,key3){const range3=createRange(type,key3),keys3=(await this._db.keys(range3[0],range3[1])).filter((e3=>!inProgress.has(e3)));if(0!==keys3.length)return await this.expose(keys3[0])}async _dequeueWithCommit(type,key3){const range3=createRange(type,key3),keysAll=await this._db.keys(range3[0],range3[1]),keys3=keysAll.filter((e3=>!inProgress.has(e3)));if(0===keys3.length)return;const storeKey=keys3[0];inProgress.add(storeKey);const previousFailed=failed.get(storeKey)||0,value=await this._db.get(storeKey);return{key:storeKey,value,cancelCount:previousFailed,pendingItems:keysAll.length-1,commit:async()=>{await this._db.delete(storeKey);failed.delete(storeKey);inProgress.delete(storeKey)},cancel:()=>{failed.set(storeKey,(failed.get(storeKey)||0)+1);inProgress.delete(storeKey)}}}queue(key3,obj,index6){return this._queue("ephemeral",key3,obj,index6)}dequeue(key3){return this._dequeue("ephemeral",key3)}dequeueWithCommit(key3){return this._dequeueWithCommit("ephemeral",key3)}queuePermanent(key3,obj,index6){return this._queue("permanent",key3,obj,index6)}dequeuePermanent(key3){return this._dequeue("permanent",key3)}dequeuePermanentWithCommit(key3){return this._dequeueWithCommit("permanent",key3)}};_handlers=new Map;SyncParamsHandlerError=class extends LiveSyncError{};SyncParamsFetchError=class extends SyncParamsHandlerError{};SyncParamsNotFoundError=class extends SyncParamsHandlerError{};SyncParamsUpdateError=class extends SyncParamsHandlerError{};RECORD_SPLIT="\n";UNIT_SPLIT="";te4=new TextEncoder;JournalSyncAbstract=class{constructor(settings,store,env){this.hash="";this.batchSize=100;this.requestedStop=!1;this.notifier=new Notifier;this._currentCheckPointInfo={...CheckPointInfoDefault};this.isPacking=!1;this.isDownloading=!1;this._settings=settings;this.db=env.getDatabase();this.env=env;this.processReplication=async docs=>await env.services.replication.parseSynchroniseResult(docs);this.store=store;this.hash=this.getHash(settings);this.trench=new Trench(store);clearHandlers()}get id(){return this._settings.accessKey}get key(){return this._settings.secretKey}get bucket(){return this._settings.bucket}get endpoint(){return this._settings.endpoint}get prefix(){return this._settings.bucketPrefix}get region(){return this._settings.region}get forcePathStyle(){return this._settings.forcePathStyle}get useCustomRequestHandler(){return this._settings.useCustomRequestHandler}get customHeaders(){return 0==this._settings.bucketCustomHeaders.length?[]:Object.entries(parseHeaderValues(this._settings.bucketCustomHeaders))}getInitialSyncParameters(){return Promise.resolve({...DEFAULT_SYNC_PARAMETERS,protocolVersion:2,pbkdf2salt:""})}async getSyncParameters(){try{const downloadedSyncParams=await this.downloadJson("_obsidian_livesync_journal_sync_parameters.json");if(!downloadedSyncParams)throw new SyncParamsNotFoundError("Missing sync parameters");return downloadedSyncParams}catch(ex){Logger("Could not retrieve remote sync parameters",LOG_LEVEL_INFO);throw SyncParamsFetchError.fromError(ex)}}async putSyncParameters(params){try{if(await this.uploadJson("_obsidian_livesync_journal_sync_parameters.json",params))return!0;throw new SyncParamsUpdateError("Could not store remote sync parameters")}catch(ex){Logger("Could not upload sync parameters",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE);throw SyncParamsUpdateError.fromError(ex)}}getHash(settings){return btoa(encodeURI([settings.endpoint,`${settings.bucket}${settings.bucketPrefix}`,settings.region].join()))}applyNewConfig(settings,store,env){this._settings=settings;this.db=env.getDatabase();this.env=env;this.processReplication=async docs=>await env.services.replication.parseSynchroniseResult(docs);this.store=store;this.hash=this.getHash(settings);clearHandlers()}updateInfo(info3){var _a8,_b5,_c3,_d2,_e2,_f,_g;const old=this.env.replicationStat.value;this.env.replicationStat.value={sent:null!=(_a8=info3.sent)?_a8:old.sent,arrived:null!=(_b5=info3.arrived)?_b5:old.arrived,maxPullSeq:null!=(_c3=info3.maxPullSeq)?_c3:old.maxPullSeq,maxPushSeq:null!=(_d2=info3.maxPushSeq)?_d2:old.maxPushSeq,lastSyncPullSeq:null!=(_e2=info3.lastSyncPullSeq)?_e2:old.lastSyncPullSeq,lastSyncPushSeq:null!=(_f=info3.lastSyncPushSeq)?_f:old.lastSyncPushSeq,syncStatus:null!=(_g=info3.syncStatus)?_g:old.syncStatus}}async updateCheckPointInfo(func){const checkPointKey=`bucketsync-checkpoint-${this.hash}`,newInfo=func(await this.getCheckpointInfo());this._currentCheckPointInfo=newInfo;await this.store.set(checkPointKey,newInfo);return newInfo}async getCheckpointInfo(){const checkPointKey=`bucketsync-checkpoint-${this.hash}`,old=await this.store.get(checkPointKey)||{},items=["knownIDs","sentIDs","receivedFiles","sentFiles"];for(const key3 of items)key3 in old&&(Array.isArray(old[key3]),1)&&(old[key3]=new Set(old[key3]));this._currentCheckPointInfo={...CheckPointInfoDefault,...old};return this._currentCheckPointInfo}async resetAllCaches(){await this.trench.eraseAllPermanences();clearHandlers()}async resetCheckpointInfo(){await this.updateCheckPointInfo((info3=>({...CheckPointInfoDefault})));clearHandlers()}async _createJournalPack(override){const checkPointInfo=await this.getCheckpointInfo(),from=override||checkPointInfo.lastLocalSeq;Logger(`Journal reading from seq:${from}`,LOG_LEVEL_VERBOSE);let knownKeyCount=0,sendKeyCount=0;const allChangesTask=this.db.changes({live:!1,since:override||from,conflicts:!0,limit:this.batchSize,return_docs:!0,attachments:!1,style:"all_docs",filter:doc=>{const key3=this.getDocKey(doc);if(this._currentCheckPointInfo.knownIDs.has(key3)){knownKeyCount++;return!1}if(this._currentCheckPointInfo.sentIDs.has(key3)){knownKeyCount++;return!1}sendKeyCount++;return!0}}),allChanges=await allChangesTask;if(0==allChanges.results.length)return{changes:[],hasNext:!1,packLastSeq:allChanges.last_seq};Logger(`${sendKeyCount} items possibly needs to be sent (${knownKeyCount} keys has been received before)`,LOG_LEVEL_DEBUG);const bd2=await this.db.bulkGet({docs:allChanges.results.map((e3=>e3.changes.map((change=>({id:e3.id,rev:change.rev}))))).flat(),revs:!0}),packLastSeq=allChanges.last_seq,hasNext=packLastSeq<(await this.db.info()).update_seq;return{changes:bd2.results.map((e3=>e3.docs)).flat().filter((e3=>"ok"in e3)).map((e3=>e3.ok)).filter((doc=>{const key3=this.getDocKey(doc);if(this._currentCheckPointInfo.knownIDs.has(key3)){knownKeyCount++;return!1}if(this._currentCheckPointInfo.sentIDs.has(key3)){knownKeyCount++;return!1}return!0})),hasNext,packLastSeq}}getDocKey(doc){return doc&&doc._id.startsWith("h:")?doc._id:doc._id+"-"+doc._rev}async uploadQueued(showMessage=!1,wrapUp=!1){return await shareRunningResult("upload_queue",(async()=>{const TASK_TITLE="Uploading journal:",logLevel=showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;let uploaded=0;do{const queued=await this.trench.dequeuePermanentWithCommit("upload_queue");if(!queued){if(this.isPacking){Logger(`${TASK_TITLE} Queue run out, but process is running. wait for the next.`,LOG_LEVEL_VERBOSE);await Promise.race([this.notifier.nextNotify,delay(3e3)]);continue}uploaded?Logger(`${TASK_TITLE}: ${uploaded} files have been uploaded!`,logLevel,"send_journal"):wrapUp||Logger("No files needs to be uploaded!",logLevel,"send_journal");return!0}const{key:key3,value,commit,cancel:cancel2,cancelCount,pendingItems}=queued;this.updateInfo({sent:uploaded,maxPushSeq:pendingItems+uploaded,lastSyncPushSeq:1});Logger(`${TASK_TITLE} ${uploaded} / ${pendingItems+uploaded}${0!=cancelCount?`\nRETRY:${cancelCount}`:""}`,logLevel,"send_journal");Logger(`${TASK_TITLE} ${key3} ${0!=cancelCount?`TRY:${cancelCount}`:""} ${pendingItems} left`,LOG_LEVEL_VERBOSE);if(cancelCount>3){Logger(`${TASK_TITLE} Something went wrong on processing queue ${key3}.`,LOG_LEVEL_NOTICE);return!1}const filename=`${Date.now()}-docs.jsonl.gz`,mime="application/octet-stream",blob=new Blob([value],{type:mime});try{if(!await this.uploadFile(filename,blob,mime))throw new Error("Could not send journalPack to the bucket");await commit();uploaded++;await this.updateCheckPointInfo((info3=>({...info3,sentFiles:info3.sentFiles.add(filename)})));Logger(`${TASK_TITLE}: Uploaded ${key3} as ${filename}`,LOG_LEVEL_INFO)}catch(ex){Logger(`${TASK_TITLE} Could not send journalPack to the bucket (${key3} as ${filename})`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);Logger(`${TASK_TITLE} Uploading ${key3} cancelled for retry`,LOG_LEVEL_VERBOSE);cancel2();await delay(1e3);continue}}while(0==this.requestedStop)}))}async packAndCompress(showMessage=!1){return await shareRunningResult("create_send_data",(async()=>{try{this.isPacking=!0;const MSG_KEY="pack_journal",logLevel=showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;this.requestedStop=!1;const checkPointInfo=await this.getCheckpointInfo(),max3=(await this.db.info()).update_seq,sentIDs=checkPointInfo.sentIDs,maxOutBufLength=250,maxBinarySize=10485760;let currentLastSeq=checkPointInfo.lastLocalSeq,binarySize=0;const outBuf=[];let isFinished=!1;const startSeq=checkPointInfo.lastLocalSeq,seqToProcess=max3-startSeq;Logger("Packing Journal: Start sending",logLevel,MSG_KEY);do{if(this.requestedStop){Logger("Packing Journal : Stop requested",logLevel,MSG_KEY);isFinished=!0;break}const{changes:changes3,hasNext,packLastSeq}=await this._createJournalPack(currentLastSeq),currentSeq=packLastSeq-startSeq;if(0==changes3.length)isFinished=!0;else{Logger(`Packing Journal: ${currentSeq} / ${seqToProcess}`,logLevel,MSG_KEY);for(const row of changes3){const serialized2=serializeDoc(row);sentIDs.add(this.getDocKey(row));binarySize+=serialized2.length;outBuf.push(serialized2);if(outBuf.length>maxOutBufLength||binarySize>maxBinarySize){const sendBuf=concatUInt8Array2(outBuf),orgLen=sendBuf.byteLength,bin=await wrappedDeflate(sendBuf,{consume:!0,level:8});Logger(`Packing Journal: Compressed ${orgLen} bytes to ${bin.byteLength} bytes (${0!=orgLen?Math.ceil(bin.byteLength/orgLen*100):"--"}%)`,LOG_LEVEL_VERBOSE);await this.trench.queuePermanent("upload_queue",bin);this.notifier.notify();outBuf.length=0;binarySize=0}}}if(outBuf.length>0){const sendBuf=concatUInt8Array2(outBuf),orgLen=sendBuf.byteLength,bin=await wrappedDeflate(sendBuf,{consume:!0,level:8});Logger(`Packing Journal: Compressed ${orgLen} bytes to ${bin.byteLength} bytes (${0!=orgLen?Math.ceil(bin.byteLength/orgLen*100):"--"}%)`,LOG_LEVEL_VERBOSE);await this.trench.queuePermanent("upload_queue",bin);this.notifier.notify()}await this.updateCheckPointInfo((info3=>({...info3,lastLocalSeq:packLastSeq,sentIDs})));currentLastSeq=packLastSeq;if(!hasNext){isFinished=!0;break}}while(0==this.requestedStop&&!isFinished);Logger(0!=seqToProcess?`Packing Journal: Packaging ${seqToProcess}`:"Packing Journal: No journals to be packed!",logLevel,MSG_KEY);this.notifier.notify();return!0}finally{this.isPacking=!1;this.notifier.notify()}}))}async sendLocalJournal(showMessage=!1){this.updateInfo({syncStatus:"JOURNAL_SEND"});if((await Promise.all([this.packAndCompress(showMessage),this.uploadQueued(showMessage)])).every((e3=>e3))&&await this.uploadQueued(showMessage,!0)){this.updateInfo({syncStatus:"COMPLETED"});return!0}this.updateInfo({syncStatus:"ERRORED"});return!1}async _getRemoteJournals(){const StartAfter=[...(await this.getCheckpointInfo()).receivedFiles.keys()].sort(((a2,b3)=>b3.localeCompare(a2,void 0,{numeric:!0})))[0],files=(await this.listFiles(StartAfter)).filter((e3=>!e3.startsWith("_")));return files?files.sort(((a2,b3)=>a2.localeCompare(b3,void 0,{numeric:!0}))):[]}async processDocuments(allDocs2){let applyTotal=0,wholeItems=0;try{const chunks=[],docs=[];allDocs2.forEach((e3=>{e3._id.startsWith("h:")?chunks.push(e3):docs.push(e3)}));try{const e22=(await this.db.allDocs({include_docs:!0,keys:[...chunks.map((e3=>e3._id))]})).rows.map((e3=>{var _a8;return null!=(_a8=e3.id)?_a8:void 0})),existChunks=new Set(e22.filter((e3=>void 0!==e3))),saveChunks=chunks.filter((e3=>!existChunks.has(e3._id))).map((e3=>({...e3,_rev:void 0}))),ret=await this.db.bulkDocs(saveChunks,{new_edits:!0}),saveError=ret.filter((e3=>"error"in e3)).map((e3=>e3.id));saveChunks.filter((e3=>-1===saveError.indexOf(e3._id))).forEach((doc=>eventHub.emitEvent("remote-chunk-fetched",doc)));await this.updateCheckPointInfo((info3=>({...info3,knownIDs:setAllItems(info3.knownIDs,chunks.map((e3=>this.getDocKey(e3))))})));Logger(`Saved ${ret.length} chunks in transferred ${chunks.length} chunks (Error:${saveError.length})`,LOG_LEVEL_VERBOSE)}catch(ex){Logger("Applying chunks failed",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE)}const docsRevs=docs.map((e3=>[e3._id,[e3._rev]])).reduce(((acc,[id,revs])=>{var _a8;return{...acc,[id]:[...null!=(_a8=acc[id])?_a8:[],...revs]}}),{}),diffRevs=await this.db.revsDiff(docsRevs),saveDocs=docs.filter((e3=>{var _a8,_b5;return e3._id in diffRevs&&"missing"in diffRevs[e3._id]&&-1!==(null!=(_b5=null==(_a8=diffRevs[e3._id].missing)?void 0:_a8.indexOf(e3._rev))?_b5:0)}));Logger(`Applying ${saveDocs.length} docs (Total transferred:${docs.length}, docs:${allDocs2.length})`,LOG_LEVEL_VERBOSE);await this.db.bulkDocs(saveDocs,{new_edits:!1});await this.processReplication(saveDocs);await this.updateCheckPointInfo((info3=>({...info3,knownIDs:setAllItems(info3.knownIDs,docs.map((e3=>this.getDocKey(e3))))})));applyTotal+=saveDocs.length;wholeItems+=docs.length;Logger(`Applied ${applyTotal} of ${wholeItems} docs (${wholeItems-applyTotal} skipped)`,LOG_LEVEL_VERBOSE);return!0}catch(ex){Logger("Applying journal failed",LOG_LEVEL_INFO);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async processDownloadedJournals(showMessage=!1,wrapUp=!1){return await shareRunningResult("process_downloaded_journals",(async()=>{const logLevel=showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,TASK_TITLE="Processing journal:";let downloaded=0;do{const queued=await this.trench.dequeuePermanentWithCommit("parse_file");if(!queued){if(this.isDownloading){Logger(`${TASK_TITLE} Queue run out, but process is running. wait for the next.`,LOG_LEVEL_VERBOSE);await Promise.race([this.notifier.nextNotify,delay(3e3)]);continue}downloaded?Logger(`${TASK_TITLE} ${downloaded} files have been uploaded!`,logLevel,"send_journal"):wrapUp||Logger(`${TASK_TITLE} No files needs to be processed!`,logLevel,"send_journal");return!0}const{key:key3,value,commit,cancel:cancel2,cancelCount,pendingItems}=queued;this.updateInfo({arrived:downloaded,maxPullSeq:pendingItems+downloaded,lastSyncPullSeq:1});Logger(`${TASK_TITLE} ${downloaded} / ${pendingItems+downloaded}${0!=cancelCount?`\nRETRY:${cancelCount}`:""}`,logLevel,"processjournal");if(cancelCount>3){Logger(`${TASK_TITLE} Something went wrong on processing queue ${key3}.`,LOG_LEVEL_NOTICE);return!1}const decompressed=await wrappedInflate(value,{consume:!0});if(0==decompressed.length){await commit();downloaded++;Logger(`${TASK_TITLE}: ${key3} has been processed`,LOG_LEVEL_INFO);continue}let idxFrom=0,idxTo=0;const d4=new TextDecoder,result=[];do{idxTo=decompressed.indexOf(10,idxFrom);if(-1==idxTo)break;const piece=decompressed.slice(idxFrom,idxTo),strPiece=d4.decode(piece);if(strPiece.startsWith("~")){const[key4,data]=strPiece.substring(1).split(UNIT_SPLIT);result.push({_id:key4,data:unescapeNewLineFromString(data),type:"leaf",_rev:""})}else result.push(JSON.parse(strPiece));idxFrom=idxTo+1}while(idxTo>0);try{if(!await this.processDocuments(result))throw new Error("Could not process downloaded journals");await commit();downloaded++;Logger(`${TASK_TITLE}: ${key3} has been processed`,LOG_LEVEL_INFO)}catch(ex){Logger(`${TASK_TITLE}: Could not process downloaded journals`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);Logger(`${TASK_TITLE}: ${key3} cancelled for retry`,LOG_LEVEL_VERBOSE);cancel2();await delay(1e3);continue}}while(0==this.requestedStop);return!0}))}async downloadRemoteJournals(showMessage=!1){return await shareRunningResult("downloadRemoteJournals",(async()=>{try{this.isDownloading=!0;const logLevel=showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;Logger("Receiving Journal: Getting list of remote journal",logLevel,"receivejournal");const files=await this._getRemoteJournals();if(0==files.length){Logger("Receiving Journal: No journals needs to be downloaded",logLevel,"receivejournal");return!0}let count=0;for(const key3 of files){count++;Logger(`Receiving Journal: ${count} / ${files.length}`,logLevel,"receivejournal");if(this.requestedStop){Logger(`Receiving canceled: ${key3}`,logLevel);return!1}if(this._currentCheckPointInfo.sentFiles.has(key3)){Logger(`Receiving Journal: ${key3} is own sent file`,LOG_LEVEL_VERBOSE);await this.updateCheckPointInfo((info3=>({...info3,receivedFiles:info3.receivedFiles.add(key3)})))}else try{const data=await this.downloadFile(key3);if(!1===data)throw new Error("Download Error");await this.trench.queuePermanent("parse_file",data);await this.updateCheckPointInfo((info3=>({...info3,receivedFiles:info3.receivedFiles.add(key3)})));this.notifier.notify()}catch(ex){Logger(`Could not download ${key3}`,logLevel);Logger(ex,LOG_LEVEL_DEBUG);return!1}}}finally{this.isDownloading=!1;this.notifier.notify()}this.notifier.notify();return!0}))}async receiveRemoteJournal(showMessage=!1){this.updateInfo({syncStatus:"JOURNAL_RECEIVE"});this.requestedStop=!1;if((await Promise.all([this.downloadRemoteJournals(showMessage),this.processDownloadedJournals(showMessage)])).every((e3=>e3))&&await this.processDownloadedJournals(showMessage,!0)){this.updateInfo({syncStatus:"COMPLETED"});return!0}this.updateInfo({syncStatus:"ERRORED"});return!1}async sync(showResult=!1){var _a8;return null!=(_a8=await shareRunningResult("replicate",(async()=>{this.requestedStop=!1;const receiveResult=await this.receiveRemoteJournal(showResult);if(!this.requestedStop){if(receiveResult)return await this.sendLocalJournal(showResult);Logger("Could not receive remote journal, so we prevent sending local journals to prevent unwanted mass transfers",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO)}})))&&_a8}requestStop(){this.requestedStop=!0}};webcrypto3=globalThis.crypto;SALT=(new TextEncoder).encode("fancySyncForYou!");previousPassphrase="";_nonceV3=new Uint32Array(1);bufV3=new Uint8Array(12);previousDecryptionPassphrase="";webcrypto4=globalThis.crypto;ENCRYPT_V1_PREFIX_PROBABLY="[";ENCRYPT_V2_PREFIX="%";ENCRYPT_V3_PREFIX="%~";KeyBuffs=new Map;decKeyBuffs=new Map;KEY_RECYCLE_COUNT=100;nonceBuffer=new Uint32Array(1);webcrypto5=globalThis.crypto;keyGCCount=5*KEY_RECYCLE_COUNT;decKeyIdx=0;decKeyMin=0;JournalSyncMinio=class extends JournalSyncAbstract{getRemoteKey(){return this.getHash(this._settings)}async getReplicationPBKDF2Salt(refresh){const manager=createSyncParamsHanderForServer(this.getRemoteKey(),{put:params=>this.putSyncParameters(params),get:()=>this.getSyncParameters(),create:()=>this.getInitialSyncParameters()});return await manager.getPBKDF2Salt(refresh)}isEncryptionPrevented(fileName){return!!fileName.endsWith("_obsidian_livesync_journal_sync_parameters.json")}_getClient(){if(this._instance)return this._instance;const ep=this.endpoint?{endpoint:this.endpoint,forcePathStyle:this.forcePathStyle}:{};this._instance=new S3({region:this.region,...ep,credentials:{accessKeyId:this.id,secretAccessKey:this.key},maxAttempts:4,retryStrategy:new ConfiguredRetryStrategy(4,(attempt=>100+1e3*attempt)),requestHandler:this.useCustomRequestHandler?this.env.services.API.getCustomFetchHandler():void 0,requestChecksumCalculation:"WHEN_REQUIRED",responseChecksumValidation:"WHEN_REQUIRED"});const bucketCustomHeaders=this.customHeaders;this._instance.middlewareStack.add(((next2,context2)=>args=>{bucketCustomHeaders.forEach((([key3,value])=>{key3&&value&&(args.request.headers[key3]=value)}));return next2(args)}),{name:"addBucketCustomHeadersMiddleware",step:"build"});const arrayBufferToBase64Sync=buffer=>btoa(String.fromCharCode(...new Uint8Array(buffer)));this._instance.middlewareStack.add(applyMd5BodyChecksumMiddleware({md5:Md5,base64Encoder:data=>arrayBufferToBase64Sync(data.buffer),streamHasher:(hashConstructor,stream)=>{const result=promiseWithResolver(),hash3=new hashConstructor;stream.on("data",(chunk=>{hash3.update(chunk)}));stream.on("end",(()=>{result.resolve(hash3.digest())}));return result.promise}}),{step:"build",name:"applyMd5BodyChecksumMiddlewareForDeleteObjects"});clearHandlers();return this._instance}async resetBucket(){var _a8;const client=this._getClient();let files=[],deleteCount=0,errorCount=0;try{do{files=await this.listFiles("",100);if(0==files.length)break;const cmd2=new DeleteObjectsCommand({Bucket:this.bucket,Delete:{Objects:files.map((e3=>({Key:`${this.prefix}${e3}`})))}}),r5=await client.send(cmd2),{Deleted,Errors}=r5;deleteCount+=(null==Deleted?void 0:Deleted.length)||0;errorCount+=(null==Errors?void 0:Errors.length)||0;Logger(`${deleteCount} items has been deleted!${0!=errorCount?` (${errorCount} items failed to delete)`:""}`,LOG_LEVEL_NOTICE,"reset-bucket")}while(0!=files.length);clearHandlers()}catch(ex){Logger("WARNING! Could not delete files. you should try it once or remake the bucket manually",LOG_LEVEL_NOTICE,"reset-bucket");Logger(ex,LOG_LEVEL_VERBOSE)}const journals=await this._getRemoteJournals();if(0==journals.length){Logger("Nothing to delete!",LOG_LEVEL_NOTICE);return!0}const cmd=new DeleteObjectsCommand({Bucket:this.bucket,Delete:{Objects:journals.map((e3=>({Key:e3})))}}),r4=await client.send(cmd);Logger(`${(null==(_a8=null==r4?void 0:r4.Deleted)?void 0:_a8.length)||0} items has been deleted!`,LOG_LEVEL_NOTICE);await this.resetCheckpointInfo();return!0}async uploadJson(key3,body){try{return await this.uploadFile(key3,new Blob([JSON.stringify(body)]),"application/json")}catch(ex){Logger(`Could not upload json ${key3}`);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async downloadJson(key3){try{const ret=await this.downloadFile(key3,!0);return!!ret&&JSON.parse((new TextDecoder).decode(ret))}catch(ex){Logger(`Could not download json ${key3}`);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async uploadFile(key3,blob,mime){try{let u2=new Uint8Array(await blob.arrayBuffer());const set2=this.env.getSettings();if(set2.encrypt&&""!=set2.passphrase&&!this.isEncryptionPrevented(key3))if(set2.E2EEAlgorithm===E2EEAlgorithms.V2){const salt=await this.getReplicationPBKDF2Salt();u2=await encryptBinary(u2,set2.passphrase,salt)}else u2=await encryptBinary2(u2,set2.passphrase,set2.useDynamicIterationCount);const client=this._getClient(),cmd=new PutObjectCommand({Bucket:this.bucket,Key:`${this.prefix}${key3}`,Body:u2,ContentType:mime});if(await client.send(cmd))return!0}catch(ex){Logger(`Could not upload ${key3}`);Logger(ex,LOG_LEVEL_VERBOSE)}return!1}async downloadFile(key3,ignoreCache=!1){const client=this._getClient(),cmd=new GetObjectCommand({Bucket:this.bucket,Key:`${this.prefix}${key3}`,...ignoreCache?{ResponseCacheControl:"no-cache"}:{}}),r4=await client.send(cmd),set2=this.env.getSettings();try{if(r4.Body){let u2=new Uint8Array(await r4.Body.transformToByteArray());if(set2.encrypt&&""!=set2.passphrase&&!this.isEncryptionPrevented(key3))if(set2.E2EEAlgorithm===E2EEAlgorithms.V2){const salt=await this.getReplicationPBKDF2Salt();u2=await decryptBinary(u2,set2.passphrase,salt)}else if(set2.E2EEAlgorithm===E2EEAlgorithms.V1)try{const salt=await this.getReplicationPBKDF2Salt();u2=await decryptBinary(u2,set2.passphrase,salt)}catch(ex){Logger(`Could not decrypt ${key3} in v2`,LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);u2=new Uint8Array(await decryptBinary2(u2,set2.passphrase,set2.useDynamicIterationCount))}else set2.E2EEAlgorithm===E2EEAlgorithms.ForceV1&&(u2=new Uint8Array(await decryptBinary2(u2,set2.passphrase,set2.useDynamicIterationCount)));return u2}}catch(ex){Logger(`Could not download ${key3}`);Logger(ex,LOG_LEVEL_VERBOSE)}return!1}async listFiles(from,limit){const client=this._getClient(),objects=await client.listObjectsV2({Bucket:this.bucket,Prefix:this.prefix,StartAfter:`${this.prefix||""}${from||""}`,...limit?{MaxKeys:limit}:{}});return objects.Contents?objects.Contents.filter((e3=>{var _a8;return null==(_a8=e3.Key)?void 0:_a8.startsWith(this.prefix)})).map((e3=>{var _a8;return null==(_a8=e3.Key)?void 0:_a8.substring(this.prefix.length)})):[]}async isAvailable(){const client=this._getClient(),cmd=new HeadBucketCommand({Bucket:this.bucket});try{await client.send(cmd);return!0}catch(ex){Logger("Could not connected to the remote bucket",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async getUsage(){const client=this._getClient();try{const objects=await client.listObjectsV2({Bucket:this.bucket});return objects.Contents?{estimatedSize:objects.Contents.reduce(((acc,e3)=>acc+(e3.Size||0)),0)}:{}}catch(ex){Logger("Could not get status of the remote bucket",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}};MILSTONE_DOCID="_00000000-milestone.json";currentVersionRange={min:0,max:2,current:2};LiveSyncJournalReplicator=class extends LiveSyncAbstractReplicator{constructor(env){super(env);this.syncStatus="NOT_CONNECTED";this.docArrived=0;this.docSent=0;this.lastSyncPullSeq=0;this.maxPullSeq=0;this.lastSyncPushSeq=0;this.maxPushSeq=0;this.nodeid="";this.remoteLocked=!1;this.remoteCleaned=!1;this.remoteLockedAndDeviceNotAccepted=!1;this.updateInfo=()=>{this.env.replicationStat.value={sent:this.docSent,arrived:this.docArrived,maxPullSeq:this.maxPullSeq,maxPushSeq:this.maxPushSeq,lastSyncPullSeq:this.lastSyncPullSeq,lastSyncPushSeq:this.lastSyncPushSeq,syncStatus:this.syncStatus}};this.env=env;fireAndForget((()=>this.initializeDatabaseForReplication()));this.env.getDatabase().on("close",(()=>{this.closeReplication()}))}get client(){return this.setupJournalSyncClient()}async getReplicationPBKDF2Salt(setting,refresh){return await this.client.getReplicationPBKDF2Salt(refresh)}setupJournalSyncClient(){const settings=this.env.getSettings();this._client?this._client.applyNewConfig(settings,this.env.simpleStore,this.env):this._client=new JournalSyncMinio(settings,this.env.simpleStore,this.env);return this._client}async ensureBucketIsCompatible(deviceNodeID,currentVersionRange3){const downloadedMilestone=await this.client.downloadJson(MILSTONE_DOCID),cPointInfo=await this.client.getCheckpointInfo(),progress=[...(null==cPointInfo?void 0:cPointInfo.receivedFiles)||[]].sort().pop()||"";return await ensureRemoteIsCompatible(downloadedMilestone,this.env.getSettings(),deviceNodeID,currentVersionRange3,{app_version:this.env.services.API.getAppVersion(),plugin_version:this.env.services.API.getPluginVersion(),vault_name:this.env.services.vault.vaultName(),device_name:this.env.services.vault.getVaultName(),progress},(async info3=>{await this.client.uploadJson(MILSTONE_DOCID,info3)}))}async migrate(from,to){Logger(`Database updated from ${from} to ${to}`,LOG_LEVEL_NOTICE);return Promise.resolve(!0)}terminateSync(){this.client.requestStop()}async openReplication(setting,_,showResult,ignoreCleanLock=!1){if(!await this.checkReplicationConnectivity(!1,ignoreCleanLock))return!1;await this.client.sync(showResult)}async replicateAllToServer(setting,showingNotice){return!!await this.checkReplicationConnectivity(!1)&&await this.client.sendLocalJournal(showingNotice)}async replicateAllFromServer(setting,showingNotice){return!!await this.checkReplicationConnectivity(!1)&&await this.client.receiveRemoteJournal(showingNotice)}async checkReplicationConnectivity(skipCheck,ignoreCleanLock=!1){if(!await this.client.isAvailable())return!1;if(!skipCheck){this.remoteCleaned=!1;this.remoteLocked=!1;this.remoteLockedAndDeviceNotAccepted=!1;this.tweakSettingsMismatched=!1;const ensure=await this.ensureBucketIsCompatible(this.nodeid,currentVersionRange);if("INCOMPATIBLE"==ensure){Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.",LOG_LEVEL_NOTICE);return!1}if("NODE_LOCKED"==ensure){Logger("The remote database has been rebuilt or corrupted since we have synchronized last time. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.",LOG_LEVEL_NOTICE);this.remoteLockedAndDeviceNotAccepted=!0;this.remoteLocked=!0;return!1}if("LOCKED"==ensure)this.remoteLocked=!0;else if("NODE_CLEANED"==ensure){if(!ignoreCleanLock){Logger("The remote database has been cleaned up. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.",LOG_LEVEL_NOTICE);this.remoteLockedAndDeviceNotAccepted=!0;this.remoteLocked=!0;this.remoteCleaned=!0;return!1}this.remoteLocked=!0}else if("OK"==ensure);else if("MISMATCHED"==ensure[0]){Logger("Configuration mismatching between the clients has been detected. This can be harmful or extra capacity consumption. We have to make these value unified.",LOG_LEVEL_NOTICE);this.tweakSettingsMismatched=!0;this.preferredTweakValue=ensure[1];return!1}}return!0}async fetchRemoteChunks(missingChunks,showResult){return Promise.resolve([])}closeReplication(){this.client.requestStop();this.syncStatus="CLOSED";Logger("Replication closed");this.updateInfo()}async tryResetRemoteDatabase(setting){this.closeReplication();try{await this.client.resetBucket();clearHandlers();Logger("Remote Bucket Cleared",LOG_LEVEL_NOTICE);await this.tryCreateRemoteDatabase(setting)}catch(ex){Logger("Something happened on Remote Bucket Clear",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_NOTICE)}}async tryCreateRemoteDatabase(setting){this.closeReplication();Logger("Remote Database Created or Connected",LOG_LEVEL_NOTICE);clearHandlers();await this.ensurePBKDF2Salt(setting,!0,!1);return await Promise.resolve()}async markRemoteLocked(setting,locked,lockByClean){const defInitPoint={_id:MILSTONE_DOCID,type:"milestoneinfo",created:new Date/1,locked,cleaned:lockByClean,accepted_nodes:[this.nodeid],node_chunk_info:{[this.nodeid]:currentVersionRange},node_info:{},tweak_values:{}},remoteMilestone={...defInitPoint,...await this.client.downloadJson(MILSTONE_DOCID)||{}};remoteMilestone.node_chunk_info={...defInitPoint.node_chunk_info,...remoteMilestone.node_chunk_info};remoteMilestone.accepted_nodes=[this.nodeid];remoteMilestone.locked=locked;remoteMilestone.cleaned=remoteMilestone.cleaned||lockByClean;Logger(locked?"Lock remote bucket to prevent data corruption":"Unlock remote bucket to prevent data corruption",LOG_LEVEL_NOTICE);await this.client.uploadJson(MILSTONE_DOCID,remoteMilestone)}async markRemoteResolved(setting){const defInitPoint={_id:MILSTONE_DOCID,type:"milestoneinfo",created:new Date/1,locked:!1,accepted_nodes:[this.nodeid],node_chunk_info:{[this.nodeid]:currentVersionRange},node_info:{},tweak_values:{}},remoteMilestone={...defInitPoint,...await this.client.downloadJson(MILSTONE_DOCID)||{}};remoteMilestone.node_chunk_info={...defInitPoint.node_chunk_info,...remoteMilestone.node_chunk_info};remoteMilestone.accepted_nodes=Array.from(new Set([...remoteMilestone.accepted_nodes,this.nodeid]));Logger("Mark this device as 'resolved'.",LOG_LEVEL_NOTICE);await this.client.uploadJson(MILSTONE_DOCID,remoteMilestone)}async tryConnectRemote(setting,showResult=!0){const endpoint=setting.endpoint,testClient=new JournalSyncMinio(setting,this.env.simpleStore,this.env);try{await testClient.listFiles("",1);Logger(`Connected to ${endpoint} successfully!`,LOG_LEVEL_NOTICE);return!0}catch(ex){Logger(`Error! Could not connected to ${endpoint}\n${ex.message}`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_NOTICE);return!1}}async resetRemoteTweakSettings(setting){try{const remoteMilestone=await this.client.downloadJson(MILSTONE_DOCID);if(!remoteMilestone)throw new Error("Missing remote milestone");remoteMilestone.tweak_values={};Logger("tweak values on the remote database have been cleared",LOG_LEVEL_VERBOSE);await this.client.uploadJson(MILSTONE_DOCID,remoteMilestone)}catch(ex){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);throw ex}}async setPreferredRemoteTweakSettings(setting){try{const remoteMilestone=await this.client.downloadJson(MILSTONE_DOCID);if(!remoteMilestone)throw new Error("Missing remote milestone");remoteMilestone.tweak_values[DEVICE_ID_PREFERRED]=extractObject(TweakValuesTemplate,{...setting});Logger("tweak values on the remote database have been cleared",LOG_LEVEL_VERBOSE);await this.client.uploadJson(MILSTONE_DOCID,remoteMilestone)}catch(ex){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);throw ex}}async getRemotePreferredTweakValues(setting){var _a8;try{const remoteMilestone=await this.client.downloadJson(MILSTONE_DOCID);if(!remoteMilestone)throw new Error("Missing remote milestone");return(null==(_a8=null==remoteMilestone?void 0:remoteMilestone.tweak_values)?void 0:_a8[DEVICE_ID_PREFERRED])||!1}catch(ex){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async getRemoteStatus(setting){const testClient=new JournalSyncMinio(setting,this.env.simpleStore,this.env);return await testClient.getUsage()}countCompromisedChunks(){Logger("Bucket Sync Replicator cannot count compromised chunks",LOG_LEVEL_VERBOSE);return Promise.resolve(0)}getConnectedDeviceList(setting){return Promise.resolve(!1)}};checkRemoteVersion=async(db,migrate,barrier=12)=>{try{const versionInfo=await db.get("obsydian_livesync_version");if("versioninfo"!=versionInfo.type)return!1;const version2=versionInfo.version;if(version2<barrier&&await migrate(version2,barrier)){await bumpRemoteVersion(db);return!0}return version2==barrier}catch(ex){if(isErrorOfMissingDoc(ex))return!!await bumpRemoteVersion(db);throw ex}};bumpRemoteVersion=async(db,barrier=12)=>{const vi={_id:"obsydian_livesync_version",version:barrier,type:"versioninfo"},versionInfo=await resolveWithIgnoreKnownError(db.get("obsydian_livesync_version"),vi);if("versioninfo"!=versionInfo.type)return!1;vi._rev=versionInfo._rev;await db.put(vi);return!0};checkSyncInfo=async db=>{try{const syncinfo=await db.get(SYNCINFO_ID);console.log(syncinfo);return!0}catch(ex){if(isErrorOfMissingDoc(ex)){const randomStrSrc="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",temp=[...Array(30)].map((_e2=>Math.floor(Math.random()*randomStrSrc.length))).map((e3=>randomStrSrc[e3])).join(""),newSyncInfo={_id:SYNCINFO_ID,type:"syncinfo",data:temp};return!!await db.put(newSyncInfo)}console.dir(ex);return!1}};SELECTOR_COMPROMISED_CHUNK_1={selector:{_id:{$lt:"h:"},type:"leaf"}};SELECTOR_COMPROMISED_CHUNK_2={selector:{_id:{$gt:"h;"},type:"leaf"}};SYMBOL_USED=Symbol("used");SYMBOL_END_OF_DATA=Symbol("endOfData");workerStreams=new Map;writers=new Map;responseBuf=new Map;writerPromise=Promise.resolve();tasks2=new Map;workers=[];key2=0;roundRobinIdx=0;initialiseWorkerModule();encrypt5=function encryptWorker(input,passphrase,autoCalculateIterations){return encryptionOnWorker({type:"encrypt",input,passphrase,autoCalculateIterations})};decrypt5=function decryptWorker(input,passphrase,autoCalculateIterations){return encryptionOnWorker({type:"decrypt",input,passphrase,autoCalculateIterations})};encryptHKDF=encryptHKDFWorker;decryptHKDF=function decryptHKDFWorker(input,passphrase,pbkdf2Salt){return encryptionHKDFOnWorker({type:"decryptHKDF",input,passphrase,pbkdf2Salt})};Encrypt_HKDF_Header="%=";Encrypt_OLD_Header="%";EncryptionVersions_UNENCRYPTED=0,EncryptionVersions_ENCRYPTED=1,EncryptionVersions_HKDF=2,EncryptionVersions_UNKNOWN=99;ENCRYPTED_META_PREFIX="/\\:";MESSAGE_FALLBACK_DECRYPT_FAILED="Failed to decrypt the data with V1 method. Cannot encrypt with HKDF.";ENCRYPTION_HKDF_FAILED="Encryption with HKDF failed.";DECRYPTION_HKDF_FAILED="Decryption with HKDF failed.";DECRYPTION_FALLBACK_FAILED="Decryption with fallback failed.";preprocessOutgoing=async doc=>await Promise.resolve(doc);enableEncryption=(db,passphrase,useDynamicIterationCount,migrationDecrypt,getPBKDF2Salt,algorithm)=>{const decrypted=new Map,incoming=doc=>algorithm===E2EEAlgorithms.V2?incomingEncryptHKDF(doc,passphrase,useDynamicIterationCount,getPBKDF2Salt):incomingEncryptV1(doc,passphrase,useDynamicIterationCount);preprocessOutgoing=incoming;db.transform({incoming,outgoing:doc=>algorithm!==E2EEAlgorithms.ForceV1?outgoingDecryptHKDF(doc,0,0,passphrase,useDynamicIterationCount,getPBKDF2Salt):outgoingDecryptV1(doc,migrationDecrypt,decrypted,passphrase,useDynamicIterationCount)})};EDEN_ENCRYPTED_KEY="h:++encrypted";EDEN_ENCRYPTED_KEY_HKDF="h:++encrypted-hkdf";currentVersionRange2={min:0,max:2400,current:2};selectorOnDemandPull={selector:{type:{$ne:"leaf"}}};LiveSyncCouchDBReplicator=class extends LiveSyncAbstractReplicator{constructor(env){super(env);this.syncStatus="NOT_CONNECTED";this.docArrived=0;this.docSent=0;this.lastSyncPullSeq=0;this.maxPullSeq=0;this.lastSyncPushSeq=0;this.maxPushSeq=0;this.nodeid="";this.remoteLocked=!1;this.remoteCleaned=!1;this.remoteLockedAndDeviceNotAccepted=!1;this.updateInfo=()=>{this.env.replicationStat.value={sent:this.docSent,arrived:this.docArrived,maxPullSeq:this.maxPullSeq,maxPushSeq:this.maxPushSeq,lastSyncPullSeq:this.lastSyncPullSeq,lastSyncPushSeq:this.lastSyncPushSeq,syncStatus:this.syncStatus}};this.env=env;this.initializeDatabaseForReplication();this.env.getDatabase().on("close",(()=>{this.closeReplication()}))}isMobile(){return this.env.services.API.isMobile()}getInitialSyncParameters(setting){return Promise.resolve({...DEFAULT_SYNC_PARAMETERS,protocolVersion:2})}async getSyncParameters(setting){try{const downloadedSyncParams=await this.fetchRemoteDocument(setting,"_local/obsidian_livesync_sync_parameters");if(!downloadedSyncParams)throw new SyncParamsNotFoundError("Sync parameters not found on remote server");return downloadedSyncParams}catch(ex){Logger("Could not retrieve remote sync parameters",LOG_LEVEL_INFO);throw SyncParamsFetchError.fromError(ex)}}async putSyncParameters(setting,params){try{const ret=await this.putRemoteDocument(setting,params);if(ret.ok)return!0;throw new SyncParamsUpdateError(`Could not store remote sync parameters: ${JSON.stringify(ret)}`)}catch(ex){Logger("Could not store remote sync parameters",LOG_LEVEL_INFO);throw SyncParamsUpdateError.fromError(ex)}}async getReplicationPBKDF2Salt(setting,refresh){const manager=createSyncParamsHanderForServer(`${setting.couchDB_URI}/${setting.couchDB_DBNAME}`,{put:params=>this.putSyncParameters(setting,params),get:()=>this.getSyncParameters(setting),create:()=>this.getInitialSyncParameters(setting)});return await manager.getPBKDF2Salt(refresh)}async migrate(from,to){Logger(`Database updated from ${from} to ${to}`,LOG_LEVEL_NOTICE);return Promise.resolve(!0)}terminateSync(){if(this.controller){this.controller.abort();this.controller=void 0}}async openReplication(setting,keepAlive,showResult,ignoreCleanLock){await this.initializeDatabaseForReplication();if(!keepAlive)return this.openOneShotReplication(setting,showResult,!1,"sync",ignoreCleanLock);this.openContinuousReplication(setting,showResult,!1)}replicationActivated(showResult){this.syncStatus="CONNECTED";this.updateInfo();Logger("Replication activated",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"sync")}async replicationChangeDetected(e3,showResult,docSentOnStart,docArrivedOnStart){try{if("pull"==e3.direction){await this.env.services.replication.parseSynchroniseResult(e3.change.docs);this.docArrived+=e3.change.docs.length}else this.docSent+=e3.change.docs.length;if(showResult){const maxPullSeq=this.maxPullSeq,maxPushSeq=this.maxPushSeq,lastSyncPullSeq=this.lastSyncPullSeq,lastSyncPushSeq=this.lastSyncPushSeq,pushLast=0==lastSyncPushSeq?"":lastSyncPushSeq>=maxPushSeq?" (LIVE)":` (${maxPushSeq-lastSyncPushSeq})`,pullLast=0==lastSyncPullSeq?"":lastSyncPullSeq>=maxPullSeq?" (LIVE)":` (${maxPullSeq-lastSyncPullSeq})`;Logger(`↑${this.docSent-docSentOnStart}${pushLast} ↓${this.docArrived-docArrivedOnStart}${pullLast}`,LOG_LEVEL_NOTICE,"sync")}this.updateInfo()}catch(ex){Logger("Replication callback error",LOG_LEVEL_NOTICE,"sync");Logger(ex,LOG_LEVEL_VERBOSE)}}replicationCompleted(showResult){this.syncStatus="COMPLETED";this.updateInfo();Logger("Replication completed",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,showResult?"sync":"");this.terminateSync()}replicationDenied(e3){this.syncStatus="ERRORED";this.updateInfo();this.terminateSync();Logger("Replication denied",LOG_LEVEL_NOTICE,"sync");Logger(e3,LOG_LEVEL_VERBOSE)}replicationErrored(e3){this.syncStatus="ERRORED";this.terminateSync();this.updateInfo();Logger("Replication error",LOG_LEVEL_NOTICE,"sync");Logger(e3,LOG_LEVEL_VERBOSE)}replicationPaused(){this.syncStatus="PAUSED";this.updateInfo();Logger("Replication paused",LOG_LEVEL_VERBOSE,"sync")}async processSync(syncHandler,showResult,docSentOnStart,docArrivedOnStart,syncMode,retrying,reportCancelledAsDone=!0){const controller=new AbortController;this.controller&&this.controller.abort();this.controller=controller;const gen=genReplication(syncHandler,controller.signal);try{for await(const[type,e3]of gen){const releaser=await globalConcurrencyController.tryAcquire(1,3e6);if(!1===releaser){Logger("Replication stopped for busy.",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"sync");return"FAILED"}releaser();switch(type){case"change":if("direction"in e3){"pull"==e3.direction?this.lastSyncPullSeq=Number(`${e3.change.last_seq}`.split("-")[0]):this.lastSyncPushSeq=Number(`${e3.change.last_seq}`.split("-")[0]);await this.replicationChangeDetected(e3,showResult,docSentOnStart,docArrivedOnStart)}else if("pullOnly"==syncMode){this.lastSyncPullSeq=Number(`${e3.last_seq}`.split("-")[0]);await this.replicationChangeDetected({direction:"pull",change:e3},showResult,docSentOnStart,docArrivedOnStart)}else if("pushOnly"==syncMode){this.lastSyncPushSeq=Number(`${e3.last_seq}`.split("-")[0]);this.updateInfo();await this.replicationChangeDetected({direction:"push",change:e3},showResult,docSentOnStart,docArrivedOnStart)}if(retrying&&this.docSent-docSentOnStart+(this.docArrived-docArrivedOnStart)>2*this.originalSetting.batch_size)return"NEED_RESURRECT";break;case"complete":this.replicationCompleted(showResult);return"DONE";case"active":this.replicationActivated(showResult);break;case"denied":this.replicationDenied(e3);return"FAILED";case"error":this.replicationErrored(e3);Logger("Replication stopped.",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"sync");if(this.env.services.API.isLastPostFailedDueToPayloadSize()){if(e3&&413==(null==e3?void 0:e3.status)){Logger("Something went wrong during synchronisation. Please check the log!",LOG_LEVEL_NOTICE);return"FAILED"}return"NEED_RETRY"}Logger("Replication error",LOG_LEVEL_NOTICE,"sync");Logger(e3,LOG_LEVEL_VERBOSE);return"FAILED";case"paused":this.replicationPaused();break;case"finally":break;default:Logger(`Unexpected synchronization status:${JSON.stringify(e3)}`)}}return reportCancelledAsDone?"DONE":"CANCELLED"}catch(ex){Logger("Unexpected synchronization exception");Logger(ex,LOG_LEVEL_VERBOSE);return"FAILED"}finally{this.terminateSync();this.controller=void 0}}getEmptyMaxEntry(remoteID){return{_id:`_local/max_seq_on_chunk-${remoteID}`,maxSeq:0,remoteID,seqStatusMap:{},_rev:void 0}}async getLastTransferredSeqOfChunks(localDB,remoteID){const prevMax={_id:`_local/max_seq_on_chunk-${remoteID}`,maxSeq:0,remoteID,seqStatusMap:{},_rev:void 0},previous_max_seq_on_chunk=await wrapException((()=>localDB.get(prevMax._id)));return previous_max_seq_on_chunk instanceof Error?prevMax:previous_max_seq_on_chunk}async updateMaxTransferredSeqOnChunks(localDB,remoteID,seqStatusMap){const newMax={_id:"_local/max_seq_on_chunk",maxSeq:0,remoteID,seqStatusMap,_rev:void 0},seqs=Object.keys(seqStatusMap).map((e3=>Number(e3)));let maxSeq=0;for(const seq of seqs){if(!seqStatusMap[seq])break;maxSeq=seq}Logger(`Updating max seq on chunk to ${maxSeq}`,LOG_LEVEL_VERBOSE);newMax.maxSeq=maxSeq;const previous_max_seq_on_chunk=await wrapException((()=>localDB.get(newMax._id)));if(previous_max_seq_on_chunk instanceof Error)delete newMax._rev;else{newMax._rev=previous_max_seq_on_chunk._rev;newMax.seqStatusMap={...previous_max_seq_on_chunk.seqStatusMap,...seqStatusMap}}await wrapException((()=>localDB.put(newMax)));return newMax}async sendChunks(setting,remoteDB,showResult,fromSeq){const trench=new Trench(this.env.services.database.openSimpleStore("sc-"),!1);await trench.eraseAllEphemerals();if(!remoteDB){const d4=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof d4){Logger($msg("liveSyncReplicator.couldNotConnectToRemoteDb",{d:d4}),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"fetch");return!1}remoteDB=d4.db}await this.checkReplicationConnectivity(setting,!1,!1,!1,!1);Logger("Bulk sending chunks to remote database...",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"fetch");const remoteMilestone=await remoteDB.get(MILESTONE_DOCID),remoteID=null==remoteMilestone?void 0:remoteMilestone.created,localDB=this.env.getDatabase(),te5=new TextEncoder;Logger($msg("liveSyncReplicator.checkingLastSyncPoint"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"fetch");this.syncStatus="CONNECTED";const prev=await this.getLastTransferredSeqOfChunks(localDB,remoteID),seq=null!=fromSeq?fromSeq:prev.maxSeq,localScannedDocs=[],sentMap={},diffChunks=localDB.changes({since:seq,live:!1,include_docs:!0,return_docs:!1,selector:{type:"leaf"}}).on("change",(e3=>{const numSeq=Number(e3.seq);prev.seqStatusMap[numSeq]||localScannedDocs.push({id:e3.id,seq:Number(e3.seq)})}));await diffChunks;localScannedDocs.sort(((a2,b3)=>a2.seq-b3.seq));const idSeqMap=Object.fromEntries(localScannedDocs.map((e3=>[e3.id,e3.seq])));for(const checkDocs of arrayToChunkedArray(localScannedDocs,250)){const remoteDocs=await remoteDB.allDocs({keys:checkDocs.map((e3=>e3.id)),include_docs:!1}),remoteDocMap=Object.fromEntries(remoteDocs.rows.map((e3=>[e3.key,"error"in e3?e3.error:e3.value]))),sendDocs=checkDocs.filter((e3=>"not_found"==remoteDocMap[e3.id])),sentDocs=checkDocs.filter((e3=>"not_found"!=remoteDocMap[e3.id]));sendDocs.forEach((e3=>sentMap[e3.seq]=!1));sentDocs.forEach((e3=>sentMap[e3.seq]=!0));const sendDocsMap=Object.fromEntries(sendDocs.map((e3=>[e3.id,e3.seq])));if(sendDocs.length>0){const localDocs=await localDB.allDocs({keys:sendDocs.map((e3=>e3.id)),include_docs:!0});await trench.queue("send-chunks",localDocs.rows.filter((e3=>"id"in e3)).map((e3=>({seq:sendDocsMap[e3.id],doc:e3.doc,id:e3.id}))))}}let bulkDocs2=[],bulkDocsSizeBytes=0,bulkDocsSizeCount=0,maxSeq=0;const maxBatchSizeBytes=1024*setting.sendChunksBulkMaxSize*1024,semaphore=Semaphore(4);let sendingDocs=0,sentDocsCount=0;const sendChunks=async(bulkDocs3,bulkDocsSize,seq2)=>{Logger(`Sending ${bulkDocs3.length} (${bulkDocsSize} => ${sizeToHumanReadable(bulkDocsSize)} in plain) chunks to remote database...`,LOG_LEVEL_VERBOSE);const releaser=await semaphore.acquire(1);sendingDocs+=bulkDocs3.length;Logger(`↑ Uploading chunks \n${sendingDocs}/(${sentDocsCount} done)`,showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"send");try{const uploadBulkDocTasks=bulkDocs3.map((e3=>preprocessOutgoing(e3))),uploadBulkDocs=await Promise.all(uploadBulkDocTasks);await remoteDB.bulkDocs(uploadBulkDocs,{new_edits:!1});uploadBulkDocs.forEach((e3=>sentMap[idSeqMap[e3._id]]=!0));await this.updateMaxTransferredSeqOnChunks(localDB,remoteID,sentMap);sentDocsCount+=bulkDocs3.length;Logger(`↑ Uploading chunks \n${sendingDocs}/(${sentDocsCount} done)`,showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"send")}catch(ex){Logger("Bulk sending failed.",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"send");Logger(ex,LOG_LEVEL_VERBOSE);return!1}finally{releaser()}return!0},tasks3=[];for(;;){const nowSendChunks=await trench.dequeue("send-chunks");if(!nowSendChunks||0==nowSendChunks.length)break;for(const chunk of nowSendChunks){const jsonLength=te5.encode(JSON.stringify(chunk.doc)).byteLength+32;if((bulkDocsSizeBytes+jsonLength>maxBatchSizeBytes||bulkDocsSizeCount+1>200)&&bulkDocs2.length>0){tasks3.push(sendChunks([...bulkDocs2],bulkDocsSizeBytes));bulkDocs2=[];bulkDocsSizeBytes=0;bulkDocsSizeCount=0}bulkDocs2.push(chunk.doc);maxSeq=chunk.seq;bulkDocsSizeBytes+=jsonLength;bulkDocsSizeCount+=1}bulkDocs2.length>0&&tasks3.push(sendChunks([...bulkDocs2],bulkDocsSizeBytes));if((await Promise.all(tasks3.map((async e3=>{try{await e3}catch(ex){Logger("Bulk sending failed.",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"send");Logger(ex,LOG_LEVEL_VERBOSE);return!1}})))).some((e3=>!1===e3)))return!1}return!0}async openOneShotReplication(setting,showResult,retrying,syncMode,ignoreCleanLock=!1){if(!1===await this.ensurePBKDF2Salt(setting,showResult,!retrying))return!1;const next2=await shareRunningResult("oneShotReplication",(async()=>{if(this.controller){Logger($msg("liveSyncReplicator.replicationInProgress"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"sync");return!1}const localDB=this.env.getDatabase();Logger($msg("liveSyncReplicator.oneShotSyncBegin",{syncMode}));const ret=await this.checkReplicationConnectivity(setting,!1,retrying,showResult,ignoreCleanLock);if(!1===ret){Logger($msg("liveSyncReplicator.couldNotConnectToServer"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"sync");return!1}this.maxPullSeq=Number(`${ret.info.update_seq}`.split("-")[0]);this.maxPushSeq=Number(`${(await localDB.info()).update_seq}`.split("-")[0]);showResult&&Logger($msg("liveSyncReplicator.checkingLastSyncPoint"),LOG_LEVEL_NOTICE,"sync");const{db,syncOptionBase}=ret;this.syncStatus="STARTED";this.updateInfo();const docArrivedOnStart=this.docArrived,docSentOnStart=this.docSent;retrying||(this.originalSetting=setting);this.terminateSync();const syncHandler="sync"==syncMode?localDB.sync(db,{...syncOptionBase}):"pullOnly"==syncMode?localDB.replicate.from(db,{...syncOptionBase,...setting.readChunksOnline?selectorOnDemandPull:{}}):"pushOnly"==syncMode?localDB.replicate.to(db,{...syncOptionBase}):void 0,syncResult=await this.processSync(syncHandler,showResult,docSentOnStart,docArrivedOnStart,syncMode,retrying,!1);if("DONE"==syncResult)return!0;if("CANCELLED"==syncResult)return!1;if("FAILED"==syncResult)return!1;if("NEED_RESURRECT"==syncResult){this.terminateSync();return async()=>await this.openOneShotReplication(this.originalSetting,showResult,!1,syncMode,ignoreCleanLock)}if("NEED_RETRY"==syncResult){const tempSetting=JSON.parse(JSON.stringify(setting));tempSetting.batch_size=Math.ceil(tempSetting.batch_size/2)+2;tempSetting.batches_limit=Math.ceil(tempSetting.batches_limit/2)+2;if(tempSetting.batch_size<=5&&tempSetting.batches_limit<=5){Logger($msg("liveSyncReplicator.cantReplicateLowerValue"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}Logger($msg("liveSyncReplicator.retryLowerBatchSize",{batch_size:tempSetting.batch_size.toString(),batches_limit:tempSetting.batches_limit.toString()}),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return async()=>await this.openOneShotReplication(tempSetting,showResult,!0,syncMode,ignoreCleanLock)}return!1}));return"boolean"==typeof next2?next2:await next2()}replicateAllToServer(setting,showingNotice){return this.openOneShotReplication(setting,null!=showingNotice&&showingNotice,!1,"pushOnly")}replicateAllFromServer(setting,showingNotice){return this.openOneShotReplication(setting,null!=showingNotice&&showingNotice,!1,"pullOnly")}async checkReplicationConnectivity(setting,keepAlive,skipCheck,showResult,ignoreCleanLock=!1){if(""!=setting.versionUpFlash){Logger($msg("Replicator.Message.VersionUpFlash"),LOG_LEVEL_NOTICE);return!1}const uri=setting.couchDB_URI+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME);if(this.controller){Logger("Another replication running.");return!1}const dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof dbRet){Logger($msg("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}if(!skipCheck){if(!await checkRemoteVersion(dbRet.db,this.migrate.bind(this),12)){Logger($msg("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE);return!1}this.remoteCleaned=!1;this.remoteLocked=!1;this.remoteLockedAndDeviceNotAccepted=!1;this.tweakSettingsMismatched=!1;this.preferredTweakValue=void 0;const progress=`${dbRet.info.update_seq}`,info3={app_version:this.env.services.API.getAppVersion(),plugin_version:this.env.services.API.getPluginVersion(),vault_name:this.env.services.vault.vaultName(),device_name:this.env.services.vault.getVaultName(),progress},ensure=await ensureDatabaseIsCompatible(dbRet.db,setting,this.nodeid,currentVersionRange2,info3);if("INCOMPATIBLE"==ensure){Logger("The remote database has no compatibility with the running version. Please upgrade the plugin.",LOG_LEVEL_NOTICE);return!1}if("NODE_LOCKED"==ensure){Logger("The remote database has been rebuilt or corrupted since we have synchronized last time. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.",LOG_LEVEL_NOTICE);this.remoteLockedAndDeviceNotAccepted=!0;this.remoteLocked=!0;return!1}if("LOCKED"==ensure)this.remoteLocked=!0;else if("NODE_CLEANED"==ensure){if(!ignoreCleanLock){Logger("The remote database has been cleaned up. Fetch rebuilt DB, explicit unlocking or chunk clean-up is required.",LOG_LEVEL_NOTICE);this.remoteLockedAndDeviceNotAccepted=!0;this.remoteLocked=!0;this.remoteCleaned=!0;return!1}this.remoteLocked=!0}else if("OK"==ensure);else if("MISMATCHED"==ensure[0]){Logger("Configuration mismatching between the clients has been detected. This can be harmful or extra capacity consumption. We have to make these value unified.",LOG_LEVEL_NOTICE);this.tweakSettingsMismatched=!0;this.preferredTweakValue=ensure[1];return!1}}const syncOptionBase={batches_limit:setting.batches_limit,batch_size:setting.batch_size,push:{}};setting.readChunksOnline&&(syncOptionBase.pull={...selectorOnDemandPull});const syncOption=keepAlive?{live:!0,retry:!0,heartbeat:!setting.useTimeouts&&3e4,...syncOptionBase}:{...syncOptionBase};return{db:dbRet.db,info:dbRet.info,syncOptionBase,syncOption}}async openContinuousReplication(setting,showResult,retrying){const next2=await shareRunningResult("continuousReplication",(async()=>{if(this.controller){Logger($msg("liveSyncReplicator.replicationInProgress"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}const localDB=this.env.getDatabase();Logger($msg("liveSyncReplicator.beforeLiveSync"));if(await this.openOneShotReplication(setting,showResult,!1,"pullOnly")){Logger($msg("liveSyncReplicator.liveSyncBegin"));const ret=await this.checkReplicationConnectivity(setting,!0,!0,showResult);if(!1===ret){Logger($msg("liveSyncReplicator.couldNotConnectToServer"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}showResult&&Logger($msg("liveSyncReplicator.checkingLastSyncPoint"),LOG_LEVEL_NOTICE,"sync");const{db,syncOption}=ret;this.syncStatus="STARTED";this.maxPullSeq=Number(`${ret.info.update_seq}`.split("-")[0]);this.maxPushSeq=Number(`${(await localDB.info()).update_seq}`.split("-")[0]);this.updateInfo();const docArrivedOnStart=this.docArrived,docSentOnStart=this.docSent;retrying||(this.originalSetting=setting);this.terminateSync();const syncHandler=localDB.sync(db,{...syncOption}),syncMode="sync",syncResult=await this.processSync(syncHandler,showResult,docSentOnStart,docArrivedOnStart,syncMode,retrying);if("DONE"==syncResult)return!0;if("FAILED"==syncResult)return!1;if("NEED_RESURRECT"==syncResult){this.terminateSync();return async()=>await this.openContinuousReplication(this.originalSetting,showResult,!1)}if("NEED_RETRY"==syncResult){const tempSetting=JSON.parse(JSON.stringify(setting));tempSetting.batch_size=Math.ceil(tempSetting.batch_size/2)+2;tempSetting.batches_limit=Math.ceil(tempSetting.batches_limit/2)+2;if(tempSetting.batch_size<=5&&tempSetting.batches_limit<=5){Logger($msg("liveSyncReplicator.cantReplicateLowerValue"),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}Logger($msg("liveSyncReplicator.retryLowerBatchSize",{batch_size:tempSetting.batch_size.toString(),batches_limit:tempSetting.batches_limit.toString()}),showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return async()=>await this.openContinuousReplication(tempSetting,showResult,!0)}}return!1}));return"boolean"==typeof next2?next2:await next2()}closeReplication(){if(this.controller){this.controller.abort();this.controller=void 0;this.syncStatus="CLOSED";Logger($msg("liveSyncReplicator.replicationClosed"));this.updateInfo()}}async tryResetRemoteDatabase(setting){this.closeReplication();const con=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"!=typeof con){try{await con.db.destroy();Logger($msg("liveSyncReplicator.remoteDbDestroyed"),LOG_LEVEL_NOTICE);await this.tryCreateRemoteDatabase(setting)}catch(ex){Logger($msg("liveSyncReplicator.remoteDbDestroyError"),LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_NOTICE)}clearHandlers();await this.ensurePBKDF2Salt(setting,!0,!1)}}async tryCreateRemoteDatabase(setting){this.closeReplication();if("string"!=typeof await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0)){clearHandlers();await this.ensurePBKDF2Salt(setting,!0,!1);Logger($msg("liveSyncReplicator.remoteDbCreatedOrConnected"),LOG_LEVEL_NOTICE)}}async markRemoteLocked(setting,locked,lockByClean){const uri=setting.couchDB_URI+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof dbRet){Logger($msg("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE);return}if(!await checkRemoteVersion(dbRet.db,this.migrate.bind(this),12)){Logger($msg("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE);return}const defInitPoint={_id:MILESTONE_DOCID,type:"milestoneinfo",created:new Date/1,locked,cleaned:lockByClean,accepted_nodes:[this.nodeid],node_chunk_info:{[this.nodeid]:currentVersionRange2},node_info:{},tweak_values:{}},remoteMilestone={...defInitPoint,...await resolveWithIgnoreKnownError(dbRet.db.get(MILESTONE_DOCID),defInitPoint)};remoteMilestone.node_chunk_info={...defInitPoint.node_chunk_info,...remoteMilestone.node_chunk_info};remoteMilestone.accepted_nodes=[this.nodeid];remoteMilestone.locked=locked;remoteMilestone.cleaned=remoteMilestone.cleaned||lockByClean;Logger($msg(locked?"liveSyncReplicator.lockRemoteDb":"liveSyncReplicator.unlockRemoteDb"),LOG_LEVEL_NOTICE);await dbRet.db.put(remoteMilestone)}async markRemoteResolved(setting){const uri=setting.couchDB_URI+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof dbRet){Logger($msg("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE);return}if(!await checkRemoteVersion(dbRet.db,this.migrate.bind(this),12)){Logger($msg("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE);return}const defInitPoint={_id:MILESTONE_DOCID,type:"milestoneinfo",created:new Date/1,locked:!1,accepted_nodes:[this.nodeid],node_info:{},node_chunk_info:{[this.nodeid]:currentVersionRange2},tweak_values:{}},remoteMilestone={...defInitPoint,...await resolveWithIgnoreKnownError(dbRet.db.get(MILESTONE_DOCID),defInitPoint)};remoteMilestone.node_chunk_info={...defInitPoint.node_chunk_info,...remoteMilestone.node_chunk_info};remoteMilestone.accepted_nodes=Array.from(new Set([...remoteMilestone.accepted_nodes,this.nodeid]));Logger($msg("liveSyncReplicator.markDeviceResolved"),LOG_LEVEL_NOTICE);(await dbRet.db.put(remoteMilestone)).ok?Logger($msg("liveSyncReplicator.remoteDbMarkedResolved"),LOG_LEVEL_VERBOSE):Logger($msg("liveSyncReplicator.couldNotMarkResolveRemoteDb"),LOG_LEVEL_NOTICE)}connectRemoteCouchDBWithSetting(settings,isMobile,performSetup=!1,skipInfo=!1){if(settings.encrypt&&""==settings.passphrase&&!settings.permitEmptyPassphrase)return"Empty passphrases cannot be used without explicit permission";const customHeaders=parseHeaderValues(settings.couchDB_CustomHeaders),auth=settings.useJWT?{jwtAlgorithm:settings.jwtAlgorithm,jwtKey:settings.jwtKey,jwtExpDuration:settings.jwtExpDuration,jwtKid:settings.jwtKid,jwtSub:settings.jwtSub,type:"jwt"}:{username:settings.couchDB_USER,password:settings.couchDB_PASSWORD,type:"basic"};return this.env.services.remote.connect(settings.couchDB_URI+(""==settings.couchDB_DBNAME?"":"/"+settings.couchDB_DBNAME),auth,settings.disableRequestURI||isMobile,settings.encrypt?settings.passphrase:settings.encrypt,settings.useDynamicIterationCount,performSetup,skipInfo,settings.enableCompression,customHeaders,settings.useRequestAPI,(async()=>await this.getReplicationPBKDF2Salt(settings)))}async _ensureConnection(settings){const ret=await this.connectRemoteCouchDBWithSetting(settings,this.isMobile(),!1,!0);if("string"==typeof ret)throw new Error(`${$msg("liveSyncReplicator.couldNotConnectToServer")}:${ret}`);return ret.db}async fetchRemoteDocument(settings,id,db){try{const connDB=null!=db?db:await this._ensureConnection(settings);return await connDB.get(id)}catch(ex){if("status"in ex&&404==ex.status)return!1;throw ex}}async putRemoteDocument(settings,doc,db){const connDB=null!=db?db:await this._ensureConnection(settings);return await connDB.put(doc)}async fetchRemoteChunks(missingChunks,showResult){const ret=await this.connectRemoteCouchDBWithSetting(this.env.getSettings(),this.isMobile(),!1,!0);if("string"==typeof ret){Logger(`${$msg("liveSyncReplicator.couldNotConnectToServer")} ${ret} `,showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"fetch");return!1}const remoteChunks=await ret.db.allDocs({keys:missingChunks,include_docs:!0});if(remoteChunks.rows.some((e3=>"error"in e3))){Logger("Some chunks are not exists both on remote and local database.",showResult?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"fetch");Logger(`Missing chunks: ${missingChunks.join(",")}`,LOG_LEVEL_VERBOSE);Logger(`Error chunks: ${remoteChunks.rows.filter((e3=>"error"in e3)).map((e3=>e3.key)).join(",")}`,LOG_LEVEL_VERBOSE);return!1}return remoteChunks.rows.map((e3=>e3.doc))}async tryConnectRemote(setting,showResult=!0){const db=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof db){Logger($msg("liveSyncReplicator.couldNotConnectTo",{uri:setting.couchDB_URI,name:setting.couchDB_DBNAME,db}),LOG_LEVEL_NOTICE);return!1}Logger(`Connected to ${db.info.db_name} successfully`,LOG_LEVEL_NOTICE);return!0}async resetRemoteTweakSettings(setting){const uri=setting.couchDB_URI+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"!=typeof dbRet)if(await checkRemoteVersion(dbRet.db,this.migrate.bind(this),12))try{const remoteMilestone=await dbRet.db.get(MILESTONE_DOCID);remoteMilestone.tweak_values={};await dbRet.db.put(remoteMilestone);Logger("tweak values on the remote database have been cleared",LOG_LEVEL_VERBOSE)}catch(ex){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);throw ex}else Logger($msg("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE);else Logger($msg("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE)}async setPreferredRemoteTweakSettings(setting){const uri=setting.couchDB_URI+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"!=typeof dbRet)if(await checkRemoteVersion(dbRet.db,this.migrate.bind(this),12))try{const remoteMilestone=await dbRet.db.get(MILESTONE_DOCID);remoteMilestone.tweak_values[DEVICE_ID_PREFERRED]=extractObject(TweakValuesTemplate,{...setting});await dbRet.db.put(remoteMilestone);Logger("Preferred tweak values has been registered",LOG_LEVEL_VERBOSE)}catch(ex){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);throw ex}else Logger($msg("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE);else Logger($msg("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE)}async getRemotePreferredTweakValues(setting){var _a8;const uri=setting.couchDB_URI+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof dbRet){Logger($msg("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE);return!1}if(!await checkRemoteVersion(dbRet.db,this.migrate.bind(this),12)){Logger($msg("liveSyncReplicator.remoteDbCorrupted"),LOG_LEVEL_NOTICE);return!1}try{const remoteMilestone=await dbRet.db.get(MILESTONE_DOCID);if(!remoteMilestone)throw new Error("Remote milestone not found");return(null==(_a8=null==remoteMilestone?void 0:remoteMilestone.tweak_values)?void 0:_a8[DEVICE_ID_PREFERRED])||!1}catch(ex){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async compactRemote(setting){const uri=setting.couchDB_URI+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof dbRet){Logger($msg("liveSyncReplicator.couldNotConnectToURI",{uri,dbRet}),LOG_LEVEL_NOTICE);return!1}return(await dbRet.db.compact({interval:1e3})).ok}async getRemoteStatus(setting){var _a8;const dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof dbRet){Logger($msg("liveSyncReplicator.couldNotConnectToURI",{uri:setting.couchDB_URI+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet}),LOG_LEVEL_NOTICE);return!1}const info3=await dbRet.db.info();return{...info3,estimatedSize:(null==(_a8=null==info3?void 0:info3.sizes)?void 0:_a8.file)||0}}async countCompromisedChunks(setting=this.env.getSettings()){const dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof dbRet){Logger($msg("liveSyncReplicator.couldNotConnectToURI",{uri:setting.couchDB_URI+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet}),LOG_LEVEL_NOTICE);return!1}return await countCompromisedChunks(dbRet.db)}async getConnectedDeviceList(setting=this.env.getSettings()){const dbRet=await this.connectRemoteCouchDBWithSetting(setting,this.isMobile(),!0);if("string"==typeof dbRet){Logger($msg("liveSyncReplicator.couldNotConnectToURI",{uri:setting.couchDB_URI+(""==setting.couchDB_DBNAME?"":"/"+setting.couchDB_DBNAME),dbRet}),LOG_LEVEL_NOTICE);return!1}const milestoneDoc=await dbRet.db.get(MILESTONE_DOCID);if(!milestoneDoc){Logger("Could not retrieve remote milestone",LOG_LEVEL_NOTICE);return!1}return{node_info:milestoneDoc.node_info,accepted_nodes:milestoneDoc.accepted_nodes||[]}}};measures=new Map;root_17=from_html('<details class="svelte-fa4ppj"><summary class="svelte-fa4ppj"> </summary> <pre class="svelte-fa4ppj"> </pre></details>');root4=from_html('<h2 class="svelte-fa4ppj">TESTING BENCH: Self-hosted LiveSync</h2> <h3 class="svelte-fa4ppj">Module Checks</h3> <button class="svelte-fa4ppj">MultiDevice Test</button> <button class="svelte-fa4ppj">SingleDevice Test</button> <button class="svelte-fa4ppj">All Test</button> <button class="svelte-fa4ppj">Clear</button> <!> <h3 class="svelte-fa4ppj">Synchronisation Result Status</h3> <pre class="svelte-fa4ppj"> </pre> <h3 class="svelte-fa4ppj">Performance test</h3> <button class="svelte-fa4ppj">Test!</button> <button class="svelte-fa4ppj">Clear</button> <div class="svelte-fa4ppj"></div>',1);$$css5={hash:"svelte-fa4ppj",code:".svelte-fa4ppj {box-sizing:border-box;}"};TestPaneView=class extends import_obsidian.ItemView{constructor(leaf,plugin3,moduleDev){super(leaf);this.icon="view-log";this.title="Self-hosted LiveSync Test and Results";this.navigation=!0;this.plugin=plugin3;this.moduleDev=moduleDev}getIcon(){return"view-log"}getViewType(){return"ols-pane-test"}getDisplayText(){return"Self-hosted LiveSync Test and Results"}async onOpen(){this.component=new TestPane({target:this.contentEl,props:{plugin:this.plugin,moduleDev:this.moduleDev}});await Promise.resolve()}async onClose(){var _a8;null==(_a8=this.component)||_a8.$destroy();await Promise.resolve()}};ModuleDev=class extends AbstractObsidianModule{constructor(){super(...arguments);this.testResults=writable([])}_everyOnloadStart(){__onMissingTranslation((()=>{}));return Promise.resolve(!0)}async onMissingTranslation(key3){const outFile=`missing-translation-${(new Date).toISOString().split("T")[0]}.jsonl`,piece=JSON.stringify({[key3]:{}}),writePiece=piece.substring(1,piece.length-1)+",";try{await this.core.storageAccess.ensureDir(this.app.vault.configDir+"/ls-debug/");await this.core.storageAccess.appendHiddenFile(this.app.vault.configDir+"/ls-debug/"+outFile,writePiece+"\n")}catch(ex){this._log(`Could not write ${outFile}`,LOG_LEVEL_VERBOSE);this._log(`Missing translation: ${writePiece}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}}_everyOnloadAfterLoadSettings(){if(!this.settings.enableDebugTools)return Promise.resolve(!0);this.onMissingTranslation=this.onMissingTranslation.bind(this);__onMissingTranslation((key3=>{this.onMissingTranslation(key3)}));eventHub.onEvent("document-stub-created",(detail=>{fireAndForget((async()=>{const stub=detail.stub,toc2=detail.toc,stubDocX=Object.entries(stub).map((([key3,value])=>[`## ${key3}`,Object.entries(value).map((([key22,value2])=>[`### ${key22}`,[...value2.entries()].map((([key32,value3])=>{var _a8;const isObsolete=value3.is_obsolete?" (obsolete)":"",desc=null!=(_a8=value3.desc)?_a8:"";return`#### ${key32}${isObsolete}\n${value3.key?"Setting key: "+value3.key+"\n":""}${desc}\n`}))].flat())).flat()].flat())).flat(),stubDocMD="\n| Icon | Description |\n| :---: | ----------------------------------------------------------------- |\n"+[...toc2.values()].map((e3=>`${e3}`)).join("\n")+"\n\n"+stubDocX.join("\n");await this.core.storageAccess.writeHiddenFileAuto(this.app.vault.configDir+"/ls-debug/stub-doc.md",stubDocMD)}))}));this.plugin;this.registerView("ols-pane-test",(leaf=>new TestPaneView(leaf,this.plugin,this)));this.addCommand({id:"view-test",name:"Open Test dialogue",callback:()=>{this.services.API.showWindow("ols-pane-test")}});return Promise.resolve(!0)}async _everyOnLayoutReady(){if(!this.settings.enableDebugTools)return Promise.resolve(!0);this.addCommand({id:"test-create-conflict",name:"Create conflict",callback:async()=>{const filename="test-create-conflict.md";if(await this.core.databaseFileAccess.store({name:filename,path:filename,body:new Blob(["# Test create conflict\n\n"],{type:"text/markdown"}),stat:{ctime:(new Date).getTime(),mtime:(new Date).getTime(),size:24,type:"file"}})){const id=await this.services.path.path2id(filename),f4=await this.core.localDatabase.getRaw(id);console.log(f4);console.log(f4._rev);const revConflict=f4._rev.split("-")[0]+"-"+(parseInt(f4._rev.split("-")[1])+1).toString();console.log(await this.core.localDatabase.bulkDocsRaw([f4],{new_edits:!1}));console.log(await this.core.localDatabase.bulkDocsRaw([{...f4,_rev:revConflict}],{new_edits:!1}))}}});await delay(1);return!0}_addTestResult(name,key3,result,summary,message){const logLine=`${name}: ${key3} ${null!=summary?summary:""}`;this.testResults.update((results=>{results.push([result,logLine,null!=message?message:""]);return results}))}_everyModuleTest(){return this.settings.enableDebugTools?this.testDone():Promise.resolve(!0)}onBindFunction(core,services){services.appLifecycle.handleLayoutReady(this._everyOnLayoutReady.bind(this));services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this));services.appLifecycle.handleOnSettingLoaded(this._everyOnloadAfterLoadSettings.bind(this));services.test.handleTest(this._everyModuleTest.bind(this));services.test.handleAddTestResult(this._addTestResult.bind(this))}};SerializedFileAccess=class{constructor(app,plugin3,storageAccess){this.touchedFiles=[];this.app=app;this.plugin=plugin3;this.storageAccess=storageAccess}async tryAdapterStat(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return await this.storageAccess.processReadFile(path2,(async()=>await this.app.vault.adapter.exists(path2)?this.app.vault.adapter.stat(path2):null))}async adapterStat(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return await this.storageAccess.processReadFile(path2,(()=>this.app.vault.adapter.stat(path2)))}async adapterExists(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return await this.storageAccess.processReadFile(path2,(()=>this.app.vault.adapter.exists(path2)))}async adapterRemove(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return await this.storageAccess.processReadFile(path2,(()=>this.app.vault.adapter.remove(path2)))}async adapterRead(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return await this.storageAccess.processReadFile(path2,(()=>this.app.vault.adapter.read(path2)))}async adapterReadBinary(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return await this.storageAccess.processReadFile(path2,(()=>this.app.vault.adapter.readBinary(path2)))}async adapterReadAuto(file){const path2=file instanceof import_obsidian.TFile?file.path:file;return isPlainText(path2)?await this.storageAccess.processReadFile(path2,(()=>this.app.vault.adapter.read(path2))):await this.storageAccess.processReadFile(path2,(()=>this.app.vault.adapter.readBinary(path2)))}async adapterWrite(file,data,options){const path2=file instanceof import_obsidian.TFile?file.path:file;return"string"==typeof data?await this.storageAccess.processWriteFile(path2,(()=>this.app.vault.adapter.write(path2,data,options))):await this.storageAccess.processWriteFile(path2,(()=>this.app.vault.adapter.writeBinary(path2,toArrayBuffer(data),options)))}async vaultCacheRead(file){return await this.storageAccess.processReadFile(file.path,(()=>this.app.vault.cachedRead(file)))}async vaultRead(file){return await this.storageAccess.processReadFile(file.path,(()=>this.app.vault.read(file)))}async vaultReadBinary(file){return await this.storageAccess.processReadFile(file.path,(()=>this.app.vault.readBinary(file)))}async vaultReadAuto(file){const path2=file.path;return isPlainText(path2)?await this.storageAccess.processReadFile(path2,(()=>this.app.vault.read(file))):await this.storageAccess.processReadFile(path2,(()=>this.app.vault.readBinary(file)))}async vaultModify(file,data,options){return"string"==typeof data?await this.storageAccess.processWriteFile(file.path,(async()=>{const oldData=await this.app.vault.read(file);if(data===oldData){options&&options.mtime&&markChangesAreSame(file.path,file.stat.mtime,options.mtime);return!0}await this.app.vault.modify(file,data,options);return!0})):await this.storageAccess.processWriteFile(file.path,(async()=>{const oldData=await this.app.vault.readBinary(file);if(await isDocContentSame(createBinaryBlob(oldData),createBinaryBlob(data))){options&&options.mtime&&markChangesAreSame(file.path,file.stat.mtime,options.mtime);return!0}await this.app.vault.modifyBinary(file,toArrayBuffer(data),options);return!0}))}async vaultCreate(path2,data,options){return"string"==typeof data?await this.storageAccess.processWriteFile(path2,(()=>this.app.vault.create(path2,data,options))):await this.storageAccess.processWriteFile(path2,(()=>this.app.vault.createBinary(path2,toArrayBuffer(data),options)))}trigger(name,...data){return this.app.vault.trigger(name,...data)}async adapterAppend(normalizedPath,data,options){return await this.app.vault.adapter.append(normalizedPath,data,options)}async delete(file,force=!1){return await this.storageAccess.processWriteFile(file.path,(()=>this.app.vault.delete(file,force)))}async trash(file,force=!1){return await this.storageAccess.processWriteFile(file.path,(()=>this.app.vault.trash(file,force)))}isStorageInsensitive(){var _a8;return null==(_a8=this.app.vault.adapter.insensitive)||_a8}getAbstractFileByPathInsensitive(path2){return this.app.vault.getAbstractFileByPathInsensitive(path2)}getAbstractFileByPath(path2){return!this.plugin.settings.handleFilenameCaseSensitive||this.isStorageInsensitive()?this.getAbstractFileByPathInsensitive(path2):this.app.vault.getAbstractFileByPath(path2)}getFiles(){return this.app.vault.getFiles()}async ensureDirectory(fullPath){const pathElements=fullPath.split("/");pathElements.pop();let c3="";for(const v2 of pathElements){c3+=v2;try{await this.app.vault.adapter.mkdir(c3)}catch(ex){if("Folder already exists."==(null==ex?void 0:ex.message));else{Logger("Folder Create Error");Logger(ex)}}c3+="/"}}_statInternal(file){return this.app.vault.adapter.stat(file)}async touch(file){const path2=file instanceof import_obsidian.TFile?file.path:file,stat=(file instanceof import_obsidian.TFile?file.stat:await this._statInternal(path2))||{mtime:0,size:0},key3=`${path2}-${stat.mtime}-${stat.size}`;this.touchedFiles.unshift(key3);this.touchedFiles=this.touchedFiles.slice(0,100)}recentlyTouched(file){const key3="stat"in file?`${file.path}-${file.stat.mtime}-${file.stat.size}`:`${file.path}-${file.mtime}-${file.size}`;return-1!=this.touchedFiles.indexOf(key3)}clearTouched(){this.touchedFiles=[]}};StorageEventManager=class{};StorageEventManagerObsidian=class extends StorageEventManager{constructor(plugin3,core,storageAccess){super();this.snapShotRestored=null;this.bufferedQueuedItems=[];this.triggerTakeSnapshot=throttle((()=>this._triggerTakeSnapshot()),100);this.concurrentProcessing=Semaphore(5);this._waitingMap=new Map;this._waitForIdle=null;this.processingCount=0;this.storageAccess=storageAccess;this.plugin=plugin3;this.core=core;this.cmdHiddenFileSync=this.plugin.getAddOn(HiddenFileSync.name)}get services(){return this.core.services}get shouldBatchSave(){var _a8,_b5;return(null==(_a8=this.core.settings)?void 0:_a8.batchSave)&&1!=(null==(_b5=this.core.settings)?void 0:_b5.liveSync)}get batchSaveMinimumDelay(){var _a8,_b5;return null!=(_b5=null==(_a8=this.core.settings)?void 0:_a8.batchSaveMinimumDelay)?_b5:DEFAULT_SETTINGS.batchSaveMinimumDelay}get batchSaveMaximumDelay(){var _a8,_b5;return null!=(_b5=null==(_a8=this.core.settings)?void 0:_a8.batchSaveMaximumDelay)?_b5:DEFAULT_SETTINGS.batchSaveMaximumDelay}restoreState(){this.snapShotRestored=this._restoreFromSnapshot();return this.snapShotRestored}async beginWatch(){await this.snapShotRestored;const plugin3=this.plugin;this.watchVaultChange=this.watchVaultChange.bind(this);this.watchVaultCreate=this.watchVaultCreate.bind(this);this.watchVaultDelete=this.watchVaultDelete.bind(this);this.watchVaultRename=this.watchVaultRename.bind(this);this.watchVaultRawEvents=this.watchVaultRawEvents.bind(this);this.watchEditorChange=this.watchEditorChange.bind(this);plugin3.registerEvent(plugin3.app.vault.on("modify",this.watchVaultChange));plugin3.registerEvent(plugin3.app.vault.on("delete",this.watchVaultDelete));plugin3.registerEvent(plugin3.app.vault.on("rename",this.watchVaultRename));plugin3.registerEvent(plugin3.app.vault.on("create",this.watchVaultCreate));plugin3.registerEvent(plugin3.app.vault.on("raw",this.watchVaultRawEvents));plugin3.registerEvent(plugin3.app.workspace.on("editor-change",this.watchEditorChange))}watchEditorChange(editor,info3){if(!("path"in info3))return;if(!this.shouldBatchSave)return;const file=null==info3?void 0:info3.file;if(!file)return;if(this.storageAccess.isFileProcessing(file.path))return;if(!this.isWaiting(file.path))return;const data=null==info3?void 0:info3.data,fi={type:"CHANGED",file:TFileToUXFileInfoStub(file),cachedData:data};this.appendQueue([fi])}watchVaultCreate(file,ctx){if(file instanceof import_obsidian.TFolder)return;if(this.storageAccess.isFileProcessing(file.path))return;const fileInfo=TFileToUXFileInfoStub(file);this.appendQueue([{type:"CREATE",file:fileInfo}],ctx)}watchVaultChange(file,ctx){if(file instanceof import_obsidian.TFolder)return;if(this.storageAccess.isFileProcessing(file.path))return;const fileInfo=TFileToUXFileInfoStub(file);this.appendQueue([{type:"CHANGED",file:fileInfo}],ctx)}watchVaultDelete(file,ctx){if(file instanceof import_obsidian.TFolder)return;if(this.storageAccess.isFileProcessing(file.path))return;const fileInfo=TFileToUXFileInfoStub(file,!0);this.appendQueue([{type:"DELETE",file:fileInfo}],ctx)}watchVaultRename(file,oldFile,ctx){if(file instanceof import_obsidian.TFile){const fileInfo=TFileToUXFileInfoStub(file);this.appendQueue([{type:"DELETE",file:{path:oldFile,name:file.name,stat:{mtime:file.stat.mtime,ctime:file.stat.ctime,size:file.stat.size,type:"file"},deleted:!0},skipBatchWait:!0},{type:"CREATE",file:fileInfo,skipBatchWait:!0}],ctx)}}watchVaultRawEvents(path2){this.storageAccess.isFileProcessing(path2)||this.plugin.settings&&(this.plugin.settings.useIgnoreFiles?this.services.vault.isTargetFile(path2).then((()=>this._watchVaultRawEvents(path2))):this._watchVaultRawEvents(path2))}async _watchVaultRawEvents(path2){(this.plugin.settings.syncInternalFiles||this.plugin.settings.usePluginSync)&&this.plugin.settings.watchInternalFileChanges&&path2.startsWith(this.plugin.app.vault.configDir)&&(path2.endsWith("/")||await this.cmdHiddenFileSync.isTargetFile(path2)&&this.appendQueue([{type:"INTERNAL",file:InternalFileToUXFileInfoStub(path2),skipBatchWait:!0}],null))}async appendQueue(params,ctx){if(this.core.settings.isConfigured&&!this.core.settings.suspendFileWatching){this.core.services.vault.markFileListPossiblyChanged();for(const param of params){if(shouldBeIgnored(param.file.path))continue;const atomicKey=[0,0,0,0,0,0].map((e3=>`${Math.floor(1e5*Math.random())}`)).join("-"),type=param.type,file=param.file,oldPath=param.oldPath;if("INTERNAL"!==type){const size=file.stat.size;if(this.services.vault.isFileSizeTooLarge(size)&&("CREATE"==type||"CHANGED"==type)){Logger(`The storage file has been changed but exceeds the maximum size. Skipping: ${param.file.path}`,LOG_LEVEL_NOTICE);continue}}if(file instanceof import_obsidian.TFolder)continue;if(!await this.services.vault.isTargetFile(file.path))continue;if((file instanceof import_obsidian.TFile||!file.isFolder)&&("CREATE"==type||"CHANGED"==type)){await delay(10);if(this.core.storageAccess.recentlyTouched(file.path))continue}let cache2;param.cachedData&&(cache2=param.cachedData);this.enqueue({type,args:{file,oldPath,cache:cache2,ctx},skipBatchWait:param.skipBatchWait,key:atomicKey})}}}_triggerTakeSnapshot(){this._takeSnapshot()}enqueue(newItem){"DELETE"==newItem.type&&this.bufferedQueuedItems.push({type:"SENTINEL_FLUSH"});this.updateStatus();this.bufferedQueuedItems.push(newItem);fireAndForget((()=>this._takeSnapshot().then((()=>this.runQueuedEvents()))))}waitForIdle(){if(0===this._waitingMap.size)return Promise.resolve();if(this._waitForIdle)return this._waitForIdle;const promises=[...this._waitingMap.entries()].map((([key3,waitInfo])=>new Promise((resolve=>{waitInfo.canProceed.promise.then((()=>{Logger(`Processing ${key3}: Wait for idle completed`,LOG_LEVEL_DEBUG)})).catch((e3=>{Logger(`Processing ${key3}: Wait for idle error`,LOG_LEVEL_INFO);Logger(e3,LOG_LEVEL_VERBOSE)})).finally((()=>{resolve()}));this._proceedWaiting(key3)})))),waitPromise=Promise.all(promises).then((()=>{this._waitForIdle=null;Logger("All wait for idle completed",LOG_LEVEL_VERBOSE)}));this._waitForIdle=waitPromise;return waitPromise}_proceedWaiting(key3){const waitInfo=this._waitingMap.get(key3);if(waitInfo){waitInfo.canProceed.resolve(!0);clearTimeout(waitInfo.timerHandler);this._waitingMap.delete(key3)}this.triggerTakeSnapshot()}_cancelWaiting(key3){const waitInfo=this._waitingMap.get(key3);if(waitInfo){waitInfo.canProceed.resolve(!1);clearTimeout(waitInfo.timerHandler);this._waitingMap.delete(key3)}this.triggerTakeSnapshot()}_addWaiting(key3,event2,waitedSince){if(this._waitingMap.has(key3))throw new Error(`Already waiting for key: ${key3}`);const resolver2=promiseWithResolvers(),now3=Date.now(),since=null!=waitedSince?waitedSince:now3,elapsed=now3-since,maxDelay=1e3*this.batchSaveMaximumDelay,remainingDelay=Math.max(0,maxDelay-elapsed),nextDelay=Math.min(remainingDelay,1e3*this.batchSaveMinimumDelay);Logger(elapsed>=maxDelay?`Processing ${key3}: Batch save maximum delay already exceeded: ${event2.type}`:`Processing ${key3}: Adding waiting for batch save: ${event2.type} (${nextDelay}ms)`,LOG_LEVEL_DEBUG);const waitInfo={since,type:event2.type,event:event2,canProceed:resolver2,timerHandler:setTimeout((()=>{Logger(`Processing ${key3}: Batch save timeout reached: ${event2.type}`,LOG_LEVEL_DEBUG);this._proceedWaiting(key3)}),nextDelay)};this._waitingMap.set(key3,waitInfo);this.triggerTakeSnapshot();return waitInfo}async processFileEvent(fei){const releaser=await this.concurrentProcessing.acquire();try{this.updateStatus();const filename=fei.args.file.path,waitingKey=`${filename}`,previous=this._waitingMap.get(waitingKey);let isShouldBeCancelled=fei.skipBatchWait||!1,previousPromise=Promise.resolve(!0),waitPromise=Promise.resolve(!0);if(previous){previousPromise=previous.canProceed.promise;isShouldBeCancelled&&Logger(`Processing ${filename}: Requested to perform immediately, cancelling previous waiting: ${fei.type}`,LOG_LEVEL_DEBUG);if(!isShouldBeCancelled&&"DELETE"===fei.type){Logger(`Processing ${filename}: DELETE requested, cancelling previous waiting: ${fei.type}`,LOG_LEVEL_DEBUG);isShouldBeCancelled=!0}if(!isShouldBeCancelled&&previous.type===fei.type){Logger(`Processing ${filename}: Cancelling previous waiting: ${fei.type}`,LOG_LEVEL_DEBUG);isShouldBeCancelled=!0}if(isShouldBeCancelled){this._cancelWaiting(waitingKey);Logger(`Processing ${filename}: Previous cancelled: ${fei.type}`,LOG_LEVEL_DEBUG);isShouldBeCancelled=!0}if(!isShouldBeCancelled){Logger(`Processing ${filename}: Waiting for previous to complete: ${fei.type}`,LOG_LEVEL_DEBUG);this._proceedWaiting(waitingKey);Logger(`Processing ${filename}: Previous completed: ${fei.type}`,LOG_LEVEL_DEBUG)}}await previousPromise;if(this.shouldBatchSave&&!fei.skipBatchWait){"CREATE"==fei.type||"CHANGED"==fei.type?waitPromise=this._addWaiting(waitingKey,fei,null==previous?void 0:previous.since).canProceed.promise:fei.type;Logger(`Processing ${filename}: Waiting for batch save: ${fei.type}`,LOG_LEVEL_DEBUG);if(!await waitPromise){Logger(`Processing ${filename}: Cancelled by new queue: ${fei.type}`,LOG_LEVEL_DEBUG);return}}await this.requestProcessQueue(fei)}finally{await this._takeSnapshot();releaser()}}async _takeSnapshot(){const snapShot=[...[...this._waitingMap.values()].map((e3=>e3.event)),...this.bufferedQueuedItems];await this.core.kvDB.set("storage-event-manager-snapshot",snapShot);Logger(`Storage operation snapshot taken: ${snapShot.length} items`,LOG_LEVEL_DEBUG);this.updateStatus()}async _restoreFromSnapshot(){const snapShot=await this.core.kvDB.get("storage-event-manager-snapshot");if(snapShot&&Array.isArray(snapShot)&&snapShot.length>0){Logger(`Restoring storage operation snapshot: ${snapShot.length} items`,LOG_LEVEL_VERBOSE);this.bufferedQueuedItems=snapShot.map((e3=>({...e3,skipBatchWait:!0})));this.updateStatus();await this.runQueuedEvents()}else Logger("No snapshot to restore",LOG_LEVEL_VERBOSE)}runQueuedEvents(){return skipIfDuplicated("storage-event-manager-run-queued-events",(async()=>{do{if(0===this.bufferedQueuedItems.length)break;const fei=this.bufferedQueuedItems.shift();await this._takeSnapshot();this.updateStatus();(await this.concurrentProcessing.acquire())();this.updateStatus();if("SENTINEL_FLUSH"!==fei.type)fireAndForget((()=>this.processFileEvent(fei)));else{Logger("Waiting for idle",LOG_LEVEL_VERBOSE);await this.waitForIdle();this.updateStatus()}}while(this.bufferedQueuedItems.length>0)}))}async requestProcessQueue(fei){try{this.processingCount++;this.updateStatus();await this.handleFileEvent(fei);await this._takeSnapshot()}finally{this.processingCount--;this.updateStatus()}}isWaiting(filename){return isWaitingForTimeout(`storage-event-manager-batchsave-${filename}`)}updateStatus(){const totalItems=this.bufferedQueuedItems.filter((e3=>"args"in e3)).filter((e3=>!e3.cancelled)).length+this.concurrentProcessing.waiting,processing=this.processingCount,batchedCount=this._waitingMap.size;this.core.batched.value=batchedCount;this.core.processing.value=processing;this.core.totalQueued.value=totalItems+batchedCount+processing}async handleFileEvent(queue2){const file=queue2.args.file,lockKey=`handleFile:${file.path}`,ret=await serialized(lockKey,(async()=>{if(queue2.cancelled)Logger(`File event cancelled before processing: ${file.path}`,LOG_LEVEL_INFO);else if("INTERNAL"==queue2.type||file.isInternal)await this.core.services.fileProcessing.processOptionalFileEvent(file.path);else{const key3=`file-last-proc-${queue2.type}-${file.path}`,last=Number(await this.core.kvDB.get(key3)||0);if("DELETE"==queue2.type)await this.core.services.fileProcessing.processFileEvent(queue2);else{if(file.stat.mtime==last){Logger(`File has been already scanned on ${queue2.type}, skip: ${file.path}`,LOG_LEVEL_VERBOSE);return}if(!await this.core.services.fileProcessing.processFileEvent(queue2)){Logger(`STORAGE -> DB: Handler failed, cancel the relative operations: ${file.path}`,LOG_LEVEL_INFO);this.cancelRelativeEvent(queue2);return}}}}));this.updateStatus();return ret}cancelRelativeEvent(item){this._cancelWaiting(item.args.file.path)}};ModuleFileAccessObsidian=class extends AbstractObsidianModule{constructor(plugin3,core){super(plugin3,core);this.processingFiles=new Set;this.vaultManager=new StorageEventManagerObsidian(this.plugin,this.core,this)}processWriteFile(file,proc){const path2="string"==typeof file?file:file.path;return serialized(`file-lock:${path2}`,(async()=>{try{this.processingFiles.add(path2);return await proc()}finally{this.processingFiles.delete(path2)}}))}processReadFile(file,proc){const path2="string"==typeof file?file:file.path;return serialized(`file-lock:${path2}`,(async()=>{try{this.processingFiles.add(path2);return await proc()}finally{this.processingFiles.delete(path2)}}))}isFileProcessing(file){const path2="string"==typeof file?file:file.path;return this.processingFiles.has(path2)}restoreState(){return this.vaultManager.restoreState()}_everyOnload(){this.core.storageAccess=this;return Promise.resolve(!0)}async _everyOnFirstInitialize(){await this.vaultManager.beginWatch();return Promise.resolve(!0)}async _everyCommitPendingFileEvent(){await this.vaultManager.waitForIdle();return Promise.resolve(!0)}_everyOnloadStart(){this.vaultAccess=new SerializedFileAccess(this.app,this.plugin,this);return Promise.resolve(!0)}_isStorageInsensitive(){return this.vaultAccess.isStorageInsensitive()}_shouldCheckCaseInsensitive(){return!this.services.vault.isStorageInsensitive()&&!this.settings.handleFilenameCaseSensitive}async writeFileAuto(path2,data,opt){const file=this.vaultAccess.getAbstractFileByPath(path2);if(file instanceof import_obsidian.TFile)return this.vaultAccess.vaultModify(file,data,opt);if(null===file){if(path2.endsWith(".md"))return await this.vaultAccess.vaultCreate(path2,data,opt)instanceof import_obsidian.TFile;await this.vaultAccess.adapterWrite(path2,data,opt);return await this.vaultAccess.adapterExists(path2)}this._log(`Could not write file (Possibly already exists as a folder): ${path2}`,LOG_LEVEL_VERBOSE);return!1}readFileAuto(path2){const file=this.vaultAccess.getAbstractFileByPath(path2);if(file instanceof import_obsidian.TFile)return this.vaultAccess.vaultRead(file);throw new Error(`Could not read file (Possibly does not exist): ${path2}`)}readFileText(path2){const file=this.vaultAccess.getAbstractFileByPath(path2);if(file instanceof import_obsidian.TFile)return this.vaultAccess.vaultRead(file);throw new Error(`Could not read file (Possibly does not exist): ${path2}`)}isExists(path2){return Promise.resolve(this.vaultAccess.getAbstractFileByPath(path2)instanceof import_obsidian.TFile)}async writeHiddenFileAuto(path2,data,opt){try{await this.vaultAccess.adapterWrite(path2,data,opt);return!0}catch(e3){this._log(`Could not write hidden file: ${path2}`,LOG_LEVEL_VERBOSE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}}async appendHiddenFile(path2,data,opt){try{await this.vaultAccess.adapterAppend(path2,data,opt);return!0}catch(e3){this._log(`Could not append hidden file: ${path2}`,LOG_LEVEL_VERBOSE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}}stat(path2){const file=this.vaultAccess.getAbstractFileByPath(path2);if(null===file)return Promise.resolve(null);if(file instanceof import_obsidian.TFile)return Promise.resolve({ctime:file.stat.ctime,mtime:file.stat.mtime,size:file.stat.size,type:"file"});throw new Error(`Could not stat file (Possibly does not exist): ${path2}`)}statHidden(path2){return this.vaultAccess.tryAdapterStat(path2)}async removeHidden(path2){try{await this.vaultAccess.adapterRemove(path2);return null===this.vaultAccess.tryAdapterStat(path2)}catch(e3){this._log(`Could not remove hidden file: ${path2}`,LOG_LEVEL_VERBOSE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}}async readHiddenFileAuto(path2){return await this.vaultAccess.adapterReadAuto(path2)}async readHiddenFileText(path2){return await this.vaultAccess.adapterRead(path2)}async readHiddenFileBinary(path2){return await this.vaultAccess.adapterReadBinary(path2)}async isExistsIncludeHidden(path2){return null!==await this.vaultAccess.tryAdapterStat(path2)}async ensureDir(path2){try{await this.vaultAccess.ensureDirectory(path2);return!0}catch(e3){this._log(`Could not ensure directory: ${path2}`,LOG_LEVEL_VERBOSE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}}triggerFileEvent(event2,path2){const file=this.vaultAccess.getAbstractFileByPath(path2);null!==file&&this.vaultAccess.trigger(event2,file)}async triggerHiddenFile(path2){await this.app.vault.adapter.reconcileInternalFile(path2)}getFileStub(path2){const file=this.vaultAccess.getAbstractFileByPath(path2);return file instanceof import_obsidian.TFile?TFileToUXFileInfoStub(file):null}async readStubContent(stub){const file=this.vaultAccess.getAbstractFileByPath(stub.path);if(!(file instanceof import_obsidian.TFile)){this._log(`Could not read file (Possibly does not exist or a folder): ${stub.path}`,LOG_LEVEL_VERBOSE);return!1}const data=await this.vaultAccess.vaultReadAuto(file);return{...stub,...TFileToUXFileInfoStub(file),body:createBlob(data)}}getStub(path2){const file=this.vaultAccess.getAbstractFileByPath(path2);return file instanceof import_obsidian.TFile?TFileToUXFileInfoStub(file):file instanceof import_obsidian.TFolder?TFolderToUXFileInfoStub(file):null}getFiles(){return this.vaultAccess.getFiles().map((f4=>TFileToUXFileInfoStub(f4)))}getFileNames(){return this.vaultAccess.getFiles().map((f4=>f4.path))}async getFilesIncludeHidden(basePath,includeFilter,excludeFilter,skipFolder=[".git",".trash","node_modules"]){var _a8;let w2;try{w2=await this.app.vault.adapter.list(basePath)}catch(ex){this._log(`Could not traverse(getFilesIncludeHidden):${basePath}`,LOG_LEVEL_INFO);this._log(ex,LOG_LEVEL_VERBOSE);return[]}skipFolder=skipFolder.map((e3=>e3.toLowerCase()));let files=[];for(const file of w2.files)includeFilter&&includeFilter.length>0&&!includeFilter.some((e3=>e3.test(file)))||excludeFilter&&excludeFilter.some((ee=>ee.test(file)))||await this.services.vault.isIgnoredByIgnoreFile(file)||files.push(file);for(const v2 of w2.folders){const folderName=(null!=(_a8=v2.split("/").pop())?_a8:"").toLowerCase();skipFolder.some((e3=>folderName===e3))||excludeFilter&&excludeFilter.some((e3=>e3.test(v2)))||await this.services.vault.isIgnoredByIgnoreFile(v2)||(files=files.concat(await this.getFilesIncludeHidden(v2,includeFilter,excludeFilter,skipFolder)))}return files}async touched(file){const path2="string"==typeof file?file:file.path;await this.vaultAccess.touch(path2)}recentlyTouched(file){const xFile="string"==typeof file?this.vaultAccess.getAbstractFileByPath(file):file;return null!==xFile&&!(xFile instanceof import_obsidian.TFolder)&&this.vaultAccess.recentlyTouched(xFile)}clearTouched(){this.vaultAccess.clearTouched()}delete(file,force){const xPath="string"==typeof file?file:file.path,xFile=this.vaultAccess.getAbstractFileByPath(xPath);return null===xFile?Promise.resolve():xFile instanceof import_obsidian.TFile||xFile instanceof import_obsidian.TFolder?this.vaultAccess.delete(xFile,force):Promise.resolve()}trash(file,system){const xPath="string"==typeof file?file:file.path,xFile=this.vaultAccess.getAbstractFileByPath(xPath);return null===xFile?Promise.resolve():xFile instanceof import_obsidian.TFile||xFile instanceof import_obsidian.TFolder?this.vaultAccess.trash(xFile,system):Promise.resolve()}async __deleteVaultItem(file){if(file instanceof import_obsidian.TFile&&!await this.services.vault.isTargetFile(file.path))return;const dir=file.parent;this.settings.trashInsteadDelete?await this.vaultAccess.trash(file,!1):await this.vaultAccess.delete(file,!0);this._log(`xxx <- STORAGE (deleted) ${file.path}`);if(dir){this._log(`files: ${dir.children.length}`);if(0==dir.children.length&&!this.settings.doNotDeleteFolder){this._log(`All files under the parent directory (${dir.path}) have been deleted, so delete this one.`);await this.__deleteVaultItem(dir)}}}async deleteVaultItem(fileSrc){const path2="string"==typeof fileSrc?fileSrc:fileSrc.path,file=this.vaultAccess.getAbstractFileByPath(path2);if(null!==file)return file instanceof import_obsidian.TFile||file instanceof import_obsidian.TFolder?await this.__deleteVaultItem(file):void 0}onBindFunction(core,services){services.vault.handleIsStorageInsensitive(this._isStorageInsensitive.bind(this));services.setting.handleShouldCheckCaseInsensitively(this._shouldCheckCaseInsensitive.bind(this));services.appLifecycle.handleFirstInitialise(this._everyOnFirstInitialize.bind(this));services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this));services.appLifecycle.handleOnLoaded(this._everyOnload.bind(this));services.fileProcessing.handleCommitPendingFileEvents(this._everyCommitPendingFileEvent.bind(this))}};AutoClosableModal=class extends import_obsidian.Modal{_closeByUnload(){eventHub.off("plugin-unloaded",this._closeByUnload);this.close()}constructor(app){super(app);this._closeByUnload=this._closeByUnload.bind(this);eventHub.once("plugin-unloaded",this._closeByUnload)}onClose(){eventHub.off("plugin-unloaded",this._closeByUnload)}};InputStringDialog=class extends AutoClosableModal{constructor(app,title,key3,placeholder,isPassword,onSubmit){super(app);this.result=!1;this.isManuallyClosed=!1;this.isPassword=!1;this.onSubmit=onSubmit;this.title=title;this.placeholder=placeholder;this.key=key3;this.isPassword=isPassword}onOpen(){const{contentEl}=this;this.titleEl.setText(this.title);const formEl=contentEl.createDiv();new import_obsidian.Setting(formEl).setName(this.key).setClass(this.isPassword?"password-input":"normal-input").addText((text2=>text2.onChange((value=>{this.result=value}))));new import_obsidian.Setting(formEl).addButton((btn=>btn.setButtonText("Ok").setCta().onClick((()=>{this.isManuallyClosed=!0;this.close()})))).addButton((btn=>btn.setButtonText("Cancel").setCta().onClick((()=>{this.close()}))))}onClose(){super.onClose();const{contentEl}=this;contentEl.empty();this.isManuallyClosed?this.onSubmit(this.result):this.onSubmit(!1)}};PopoverSelectString=class extends import_obsidian.FuzzySuggestModal{constructor(app,note,placeholder,getItemsFun,callback){super(app);this.callback=()=>{};this.getItemsFun=()=>["yes","no"];this.app=app;this.setPlaceholder((null!=placeholder?placeholder:"y/n) ")+note);getItemsFun&&(this.getItemsFun=getItemsFun);this.callback=callback}getItems(){return this.getItemsFun()}getItemText(item){return item}onChooseItem(item,evt){var _a8;null==(_a8=this.callback)||_a8.call(this,item);this.callback=void 0}onClose(){setTimeout((()=>{if(this.callback){this.callback("");this.callback=void 0}}),100)}};MessageBox=class extends AutoClosableModal{constructor(plugin3,title,contentMd,buttons,defaultAction,timeout,wideButton,onSubmit){super(plugin3.app);this.result=!1;this.isManuallyClosed=!1;this.timer=void 0;this.plugin=plugin3;this.title=title;this.contentMd=contentMd;this.buttons=buttons;this.onSubmit=onSubmit;this.defaultAction=defaultAction;this.timeout=timeout;this.wideButton=wideButton;this.timeout&&(this.timer=setInterval((()=>{var _a8,_b5;if(void 0!==this.timeout){this.timeout--;if(this.timeout<0){if(this.timer){clearInterval(this.timer);null==(_a8=this.defaultButtonComponent)||_a8.setButtonText(`${defaultAction}`);this.timer=void 0}this.result=defaultAction;this.isManuallyClosed=!0;this.close()}else null==(_b5=this.defaultButtonComponent)||_b5.setButtonText(`( ${this.timeout} ) ${defaultAction}`)}}),1e3))}onOpen(){const{contentEl}=this;this.titleEl.setText(this.title);const div=contentEl.createDiv();div.style.userSelect="text";div.style.webkitUserSelect="text";import_obsidian.MarkdownRenderer.render(this.plugin.app,this.contentMd,div,"/",this.plugin);const buttonSetting=new import_obsidian.Setting(contentEl),labelWrapper=contentEl.createDiv();labelWrapper.addClass("sls-dialogue-note-wrapper");labelWrapper.createEl("label",{text:"To stop the countdown, tap anywhere on the dialogue"}).addClass("sls-dialogue-note-countdown");if(!this.timeout||!this.timer){labelWrapper.empty();labelWrapper.style.display="none"}buttonSetting.infoEl.style.display="none";buttonSetting.controlEl.style.flexWrap="wrap";if(this.wideButton){buttonSetting.controlEl.style.flexDirection="column";buttonSetting.controlEl.style.alignItems="center";buttonSetting.controlEl.style.justifyContent="center";buttonSetting.controlEl.style.flexGrow="1"}contentEl.addEventListener("click",(()=>{var _a8;if(this.timer){labelWrapper.empty();labelWrapper.style.display="none";clearInterval(this.timer);this.timer=void 0;null==(_a8=this.defaultButtonComponent)||_a8.setButtonText(`${this.defaultAction}`)}}));for(const button of this.buttons)buttonSetting.addButton((btn=>{btn.setButtonText(button).onClick((()=>{this.isManuallyClosed=!0;this.result=button;if(this.timer){clearInterval(this.timer);this.timer=void 0}this.close()}));if(button==this.defaultAction){this.defaultButtonComponent=btn;btn.setCta()}if(this.wideButton){btn.buttonEl.style.flexGrow="1";btn.buttonEl.style.width="100%"}return btn}))}onClose(){super.onClose();const{contentEl}=this;contentEl.empty();if(this.timer){clearInterval(this.timer);this.timer=void 0}this.isManuallyClosed?this.onSubmit(this.result):this.onSubmit(!1)}};askYesNo=(app,message)=>new Promise((res2=>{new PopoverSelectString(app,message,void 0,void 0,(result=>res2(result))).open()}));askSelectString=(app,message,items)=>{const getItemsFun=()=>items;return new Promise((res2=>{new PopoverSelectString(app,message,"",getItemsFun,(result=>res2(result))).open()}))};askString=(app,title,key3,placeholder,isPassword=!1)=>new Promise((res2=>{new InputStringDialog(app,title,key3,placeholder,isPassword,(result=>res2(result))).open()}));ModuleInputUIObsidian=class extends AbstractObsidianModule{_everyOnload(){this.core.confirm=this;setConfirmInstance(this);return Promise.resolve(!0)}askYesNo(message){return askYesNo(this.app,message)}askString(title,key3,placeholder,isPassword=!1){return askString(this.app,title,key3,placeholder,isPassword)}async askYesNoDialog(message,opt={title:"Confirmation"}){const defaultTitle=$msg("moduleInputUIObsidian.defaultTitleConfirmation"),yesLabel=$msg("moduleInputUIObsidian.optionYes"),noLabel=$msg("moduleInputUIObsidian.optionNo"),defaultOption="Yes"===opt.defaultOption?yesLabel:noLabel;return await confirmWithMessageWithWideButton(this.plugin,opt.title||defaultTitle,message,[yesLabel,noLabel],defaultOption,opt.timeout)===yesLabel?"yes":"no"}askSelectString(message,items){return askSelectString(this.app,message,items)}askSelectStringDialogue(message,buttons,opt){const defaultTitle=$msg("moduleInputUIObsidian.defaultTitleSelect");return confirmWithMessageWithWideButton(this.plugin,opt.title||defaultTitle,message,buttons,opt.defaultAction,opt.timeout)}askInPopup(key3,dialogText,anchorCallback){const fragment=createFragment((doc=>{const[beforeText,afterText]=dialogText.split("{HERE}",2);doc.createEl("span",void 0,(a2=>{a2.appendText(beforeText);a2.appendChild(a2.createEl("a",void 0,(anchor=>{anchorCallback(anchor)})));a2.appendText(afterText)}))})),popupKey="popup-"+key3;scheduleTask(popupKey,1e3,(async()=>{var _a8;const popup=await memoIfNotExist(popupKey,(()=>new import_obsidian.Notice(fragment,0)));(null==(_a8=null==popup?void 0:popup.noticeEl)?void 0:_a8.isShown())||memoObject(popupKey,new import_obsidian.Notice(fragment,0));scheduleTask(popupKey+"-close",2e4,(()=>{var _a9;const popup2=retrieveMemoObject(popupKey);if(popup2){(null==(_a9=null==popup2?void 0:popup2.noticeEl)?void 0:_a9.isShown())&&popup2.hide();disposeMemoObject(popupKey)}}))}))}confirmWithMessage(title,contentMd,buttons,defaultAction,timeout){return confirmWithMessage(this.plugin,title,contentMd,buttons,defaultAction,timeout)}onBindFunction(core,services){services.appLifecycle.handleOnLoaded(this._everyOnload.bind(this))}};OnDialogSettingsDefault={configPassphrase:"",preset:"",syncMode:"ONEVENTS",dummy:0,deviceAndVaultName:""};SettingInformation={liveSync:{name:"Sync Mode"},couchDB_URI:{name:"Server URI",placeHolder:"https://........"},couchDB_USER:{name:"Username",desc:"username"},couchDB_PASSWORD:{name:"Password",desc:"password",isHidden:!0},couchDB_DBNAME:{name:"Database Name"},passphrase:{name:"Passphrase",desc:"Encryption passphrase. If changed, you should overwrite the server's database with the new (encrypted) files.",isHidden:!0},showStatusOnEditor:{name:"Show status inside the editor",desc:"Requires restart of Obsidian."},showOnlyIconsOnEditor:{name:"Show status as icons only"},showStatusOnStatusbar:{name:"Show status on the status bar",desc:"Requires restart of Obsidian."},lessInformationInLog:{name:"Show only notifications",desc:"Disables logging, only shows notifications. Please disable if you report an issue."},showVerboseLog:{name:"Verbose Log",desc:"Show verbose log. Please enable if you report an issue."},hashCacheMaxCount:{name:"Memory cache size (by total items)"},hashCacheMaxAmount:{name:"Memory cache size (by total characters)",desc:"(Mega chars)"},writeCredentialsForSettingSync:{name:"Write credentials in the file",desc:"(Not recommended) If set, credentials will be stored in the file."},notifyAllSettingSyncFile:{name:"Notify all setting files"},configPassphrase:{name:"Passphrase of sensitive configuration items",desc:"This passphrase will not be copied to another device. It will be set to `Default` until you configure it again."},configPassphraseStore:{name:"Encrypting sensitive configuration items"},syncOnSave:{name:"Sync on Save",desc:"Starts synchronisation when a file is saved."},syncOnEditorSave:{name:"Sync on Editor Save",desc:"When you save a file in the editor, start a sync automatically"},syncOnFileOpen:{name:"Sync on File Open",desc:"Forces the file to be synced when opened."},syncOnStart:{name:"Sync on Startup",desc:"Automatically Sync all files when opening Obsidian."},syncAfterMerge:{name:"Sync after merging file",desc:"Sync automatically after merging files"},trashInsteadDelete:{name:"Use the trash bin",desc:"Move remotely deleted files to the trash, instead of deleting."},doNotDeleteFolder:{name:"Keep empty folder",desc:"Should we keep folders that don't have any files inside?"},resolveConflictsByNewerFile:{name:"(BETA) Always overwrite with a newer file",desc:"Testing only - Resolve file conflicts by syncing newer copies of the file, this can overwrite modified files. Be Warned."},checkConflictOnlyOnOpen:{name:"Delay conflict resolution of inactive files",desc:"Should we only check for conflicts when a file is opened?"},showMergeDialogOnlyOnActive:{name:"Delay merge conflict prompt for inactive files.",desc:"Should we prompt you about conflicting files when a file is opened?"},disableMarkdownAutoMerge:{name:"Always prompt merge conflicts",desc:"Should we prompt you for every single merge, even if we can safely merge automatcially?"},writeDocumentsIfConflicted:{name:"Apply Latest Change if Conflicting",desc:"Enable this option to automatically apply the most recent change to documents even when it conflicts"},syncInternalFilesInterval:{name:"Scan hidden files periodically",desc:"Seconds, 0 to disable"},batchSave:{name:"Batch database update",desc:"Reducing the frequency with which on-disk changes are reflected into the DB"},readChunksOnline:{name:"Fetch chunks on demand",desc:"(ex. Read chunks online) If this option is enabled, LiveSync reads chunks online directly instead of replicating them locally. Increasing Custom chunk size is recommended."},syncMaxSizeInMB:{name:"Maximum file size",desc:"(MB) If this is set, changes to local and remote files that are larger than this will be skipped. If the file becomes smaller again, a newer one will be used."},useIgnoreFiles:{name:"(Beta) Use ignore files",desc:"If this is set, changes to local files which are matched by the ignore files will be skipped. Remote changes are determined using local ignore files."},ignoreFiles:{name:"Ignore files",desc:"Comma separated `.gitignore, .dockerignore`"},batch_size:{name:"Batch size",desc:"Number of changes to sync at a time. Defaults to 50. Minimum is 2."},batches_limit:{name:"Batch limit",desc:"Number of batches to process at a time. Defaults to 40. Minimum is 2. This along with batch size controls how many docs are kept in memory at a time."},useTimeouts:{name:"Use timeouts instead of heartbeats",desc:"If this option is enabled, PouchDB will hold the connection open for 60 seconds, and if no change arrives in that time, close and reopen the socket, instead of holding it open indefinitely. Useful when a proxy limits request duration but can increase resource usage."},concurrencyOfReadChunksOnline:{name:"Batch size of on-demand fetching"},minimumIntervalOfReadChunksOnline:{name:"The delay for consecutive on-demand fetches"},suspendFileWatching:{name:"Suspend file watching",desc:"Stop watching for file changes."},suspendParseReplicationResult:{name:"Suspend database reflecting",desc:"Stop reflecting database changes to storage files."},writeLogToTheFile:{name:"Write logs into the file",desc:"Warning! This will have a serious impact on performance. And the logs will not be synchronised under the default name. Please be careful with logs; they often contain your confidential information."},deleteMetadataOfDeletedFiles:{name:"Do not keep metadata of deleted files."},useIndexedDBAdapter:{name:"(Obsolete) Use an old adapter for compatibility",desc:"Before v0.17.16, we used an old adapter for the local database. Now the new adapter is preferred. However, it needs local database rebuilding. Please disable this toggle when you have enough time. If leave it enabled, also while fetching from the remote database, you will be asked to disable this.",obsolete:!0},watchInternalFileChanges:{name:"Scan changes on customization sync",desc:"Do not use internal API"},doNotSuspendOnFetching:{name:"Fetch database with previous behaviour"},disableCheckingConfigMismatch:{name:"Do not check configuration mismatch before replication"},usePluginSync:{name:"Enable customization sync"},autoSweepPlugins:{name:"Scan customization automatically",desc:"Scan customization before replicating."},autoSweepPluginsPeriodic:{name:"Scan customization periodically",desc:"Scan customization every 1 minute."},notifyPluginOrSettingUpdated:{name:"Notify customized",desc:"Notify when other device has newly customized."},remoteType:{name:"Active Remote Type",desc:"Remote server type"},endpoint:{name:"Endpoint URL",placeHolder:"https://........"},accessKey:{name:"Access Key"},secretKey:{name:"Secret Key",isHidden:!0},region:{name:"Region",placeHolder:"auto"},bucket:{name:"Bucket Name"},useCustomRequestHandler:{name:"Use Custom HTTP Handler",desc:"Enable this if your Object Storage doesn't support CORS"},maxChunksInEden:{name:"Maximum Incubating Chunks",desc:"The maximum number of chunks that can be incubated within the document. Chunks exceeding this number will immediately graduate to independent chunks."},maxTotalLengthInEden:{name:"Maximum Incubating Chunk Size",desc:"The maximum total size of chunks that can be incubated within the document. Chunks exceeding this size will immediately graduate to independent chunks."},maxAgeInEden:{name:"Maximum Incubation Period",desc:"The maximum duration for which chunks can be incubated within the document. Chunks exceeding this period will graduate to independent chunks."},settingSyncFile:{name:"Filename",desc:"Save settings to a markdown file. You will be notified when new settings arrive. You can set different files by the platform."},preset:{name:"Presets",desc:"Apply preset configuration"},syncMode:{name:"Sync Mode"},periodicReplicationInterval:{name:"Periodic Sync interval",desc:"Interval (sec)"},syncInternalFilesBeforeReplication:{name:"Scan for hidden files before replication"},automaticallyDeleteMetadataOfDeletedFiles:{name:"Delete old metadata of deleted files on start-up",desc:"(Days passed, 0 to disable automatic-deletion)"},additionalSuffixOfDatabaseName:{name:"Database suffix",desc:"LiveSync could not handle multiple vaults which have same name without different prefix, This should be automatically configured."},hashAlg:{name:(null==(_a7=configurationNames.hashAlg)?void 0:_a7.name)||"",desc:"xxhash64 is the current default."},deviceAndVaultName:{name:"Device name",desc:"Unique name between all synchronized devices. To edit this setting, please disable customization sync once."},displayLanguage:{name:"Display Language",desc:'Not all messages have been translated. And, please revert to "Default" when reporting errors.'},enableChunkSplitterV2:{name:"Use splitting-limit-capped chunk splitter",desc:"If enabled, chunks will be split into no more than 100 items. However, dedupe is slightly weaker."},disableWorkerForGeneratingChunks:{name:"Do not split chunks in the background",desc:"If disabled(toggled), chunks will be split on the UI thread (Previous behaviour)."},processSmallFilesInUIThread:{name:"Process small files in the foreground",desc:"If enabled, the file under 1kb will be processed in the UI thread."},batchSaveMinimumDelay:{name:"Minimum delay for batch database updating",desc:"Seconds. Saving to the local database will be delayed until this value after we stop typing or saving."},batchSaveMaximumDelay:{name:"Maximum delay for batch database updating",desc:"Saving will be performed forcefully after this number of seconds."},notifyThresholdOfRemoteStorageSize:{name:"Notify when the estimated remote storage size exceeds on start up",desc:"MB (0 to disable)."},usePluginSyncV2:{name:"Enable per-file customization sync",desc:"If enabled, efficient per-file customization sync will be used. A minor migration is required when enabling this feature, and all devices must be updated to v0.23.18. Enabling this feature will result in losing compatibility with older versions."},handleFilenameCaseSensitive:{name:"Handle files as Case-Sensitive",desc:"If this enabled, All files are handled as case-Sensitive (Previous behaviour)."},doNotUseFixedRevisionForChunks:{name:"Compute revisions for chunks",desc:"If this enabled, all chunks will be stored with the revision made from its content."},sendChunksBulkMaxSize:{name:"Maximum size of chunks to send in one request",desc:"MB"},useAdvancedMode:{name:"Enable advanced features"},usePowerUserMode:{name:"Enable poweruser features"},useEdgeCaseMode:{name:"Enable edge case treatment features"},enableDebugTools:{name:"Enable Developers' Debug Tools.",desc:"While enabled, it causes very performance impact but debugging replication testing and other features will be enabled. Please disable this if you have not read the source code. Requires restart of Obsidian."},suppressNotifyHiddenFilesChange:{name:"Suppress notification of hidden files change",desc:"If enabled, the notification of hidden files change will be suppressed."},syncMinimumInterval:{name:"Minimum interval for syncing",desc:"The minimum interval for automatic synchronisation on event."},useRequestAPI:{name:"Use Request API to avoid `inevitable` CORS problem",desc:"If enabled, the request API will be used to avoid `inevitable` CORS problems. This is a workaround and may not work in all cases. PLEASE READ THE DOCUMENTATION BEFORE USING THIS OPTION. This is a less-secure option."},hideFileWarningNotice:{name:"Show status icon instead of file warnings banner",desc:"If enabled, the ⛔ icon will be shown inside the status instead of the file warnings banner. No details will be shown."},bucketPrefix:{name:"File prefix on the bucket",desc:"Effectively a directory. Should end with `/`. e.g., `vault-name/`."},chunkSplitterVersion:{name:"Chunk Splitter",desc:"Now we can choose how to split the chunks; V3 is the most efficient. If you have troubled, please make this Default or Legacy."},processSizeMismatchedFiles:{name:"Process files even if seems to be corrupted",desc:"You can enable this setting to process the files with size mismatches, these files can be created by some APIs or integrations."},forcePathStyle:{name:"Enable forcePathStyle",desc:"If enabled, the forcePathStyle option will be used for bucket operations."},P2P_AutoBroadcast:{name:"Automatically broadcast changes to connected peers",desc:"If enabled, changes will be automatically broadcasted to all connected peers. Notified peers will start fetching the changes."},P2P_AutoStart:{name:"Automatically start P2P connection on launch",desc:"If enabled, the P2P connection will be automatically started when the application launches."},P2P_Enabled:{name:"Enable P2P Synchronization"}};ConditionType=(ConditionType2=>{ConditionType2.PLATFORM_CASE_INSENSITIVE="platform-case-insensitive";ConditionType2.PLATFORM_CASE_SENSITIVE="platform-case-sensitive";ConditionType2.REMOTE_CASE_SENSITIVE="remote-case-sensitive";return ConditionType2})(ConditionType||{});RuleLevel=(RuleLevel2=>{RuleLevel2[RuleLevel2.Must=0]="Must";RuleLevel2[RuleLevel2.Necessary=1]="Necessary";RuleLevel2[RuleLevel2.Recommended=2]="Recommended";RuleLevel2[RuleLevel2.Optional=3]="Optional";return RuleLevel2})(RuleLevel||{});DoctorRegulationV0_25_27={version:"0.25.27",rules:{sendChunksBulk:{value:!1,reason:"This is an obsolete setting and we should not enable this no more",level:0},sendChunksBulkMaxSize:{value:1,reason:"This is an obsolete setting and we should not enable this no more",level:0},doNotUseFixedRevisionForChunks:{value:!0,reason:"This value has been reverted at v0.24.16 for garbage collection of chunks.",level:2},handleFilenameCaseSensitive:{value:!1,reason:"If Self-hosted LiveSync is Case-Sensitive, unexpected file operations may occur when synchronising with Windows, Android or other devices. This value should only be enabled if all devices have a Case-Sensitive file system.",requireRebuild:!0,level:2},useIndexedDBAdapter:{value:!0,requireRebuildLocal:!0,level:3,reason:"The old option is active. This is not a performance-appropriate setting."},useEden:{reason:"This option is no longer recommended.",level:3,value:!1},hashAlg:{obsoleteValues:["sha1","xxhash32",""],value:"xxhash64",level:1,reason:"The hash function is set to the old fallback. This should be retried. This may result in a change to the new fallback."},disableCheckingConfigMismatch:{value:!1,level:2,reason:"If you disabled an older version of the dialogue because it was hard to understand, try it once in the latest version."},enableCompression:{value:!1,level:2,requireRebuild:!0,reason:"This option will be sunset soon."},usePluginSyncV2:{value:!0,level:2,reason:"This option is now enabled by default. If you have problems with the new plugin, please report them."},chunkSplitterVersion:{value:"v3-rabin-karp",valueDisplay:ChunkAlgorithmNames["v3-rabin-karp"],level:2,reason:"Chunk splitting has been optimised for more effective de-duplication. This is the new default value."},customChunkSize:{min:55,value:60,valueDisplay:"60 (detected on if less than 55)",level:2,detectionFunc:settings=>"v3-rabin-karp"===(null==settings?void 0:settings.chunkSplitterVersion)&&!isCloudantURI((null==settings?void 0:settings.couchDB_URI)||""),reason:"With the V3 Rabin-Karp chunk splitter and Self-hosted CouchDB, the chunk size is set to 60 (means around 6MB) by default. This is in effect the maximum chunk size, which in practice is divided more finely."},E2EEAlgorithm:{value:E2EEAlgorithms.V2,valueDisplay:E2EEAlgorithmNames[E2EEAlgorithms.V2],level:2,reasonFunc:_=>$msg("Doctor.RULES.E2EE_V02500.REASON")},useIndexedDBAdapter:void 0}};DoctorRegulation=DoctorRegulationV0_25_27;RebuildOptions_AutomaticAcceptable=0,RebuildOptions_ConfirmIfRequired=1,RebuildOptions_SkipEvenIfRequired=2;CONTEXT_DIALOG_CONTROLS="svelte-dialog-controls";root5=from_html('<div class="dialog-host svelte-3n2ufb"><!></div>');$$css6={hash:"svelte-3n2ufb",code:'.dialog-host.svelte-3n2ufb {padding:20px;gap:0.5em;display:flex;flex-direction:column;padding-bottom:var(--keyboard-height, 0px);}.dialog-host.svelte-3n2ufb button {margin-left:10px;}.dialog-host.svelte-3n2ufb .button-group {display:flex;flex-direction:column;gap:10px;margin-top:20px;}.dialog-host.svelte-3n2ufb .row {display:flex;flex-direction:row;justify-items:center;align-items:center;flex-wrap:wrap;}.dialog-host.svelte-3n2ufb .row > input[type="text"],\n .dialog-host.svelte-3n2ufb .row > input[type="password"],\n .dialog-host.svelte-3n2ufb .row > textarea,\n .dialog-host.svelte-3n2ufb .row > select {flex:1;margin-left:10px;min-width:10em;}.dialog-host.svelte-3n2ufb .row > input[type="password"] {-webkit-text-security:disc;}.dialog-host.svelte-3n2ufb .row > input[type="checkbox"] {margin-left:10px;margin-right:10px;}.dialog-host.svelte-3n2ufb label > span {display:block;width:8em;}.dialog-host.svelte-3n2ufb .note,\n .dialog-host.svelte-3n2ufb .note-important,\n .dialog-host.svelte-3n2ufb .note-error {padding:10px;margin-top:4px;margin-bottom:0.5lh;border-left:4px solid;}.dialog-host.svelte-3n2ufb .note {background-color:var(--interactive-hover);border-left-color:var(--interactive-accent);}.dialog-host.svelte-3n2ufb .note-important {background-color:var(--interactive-hover);border-left-color:var(--text-warning);}.dialog-host.svelte-3n2ufb .note-error {background-color:var(--interactive-hover);border-left-color:var(--text-error);}.dialog-host.svelte-3n2ufb hr {margin:0.7lh 0;}.dialog-host.svelte-3n2ufb details {gap:0.5em;padding-left:0.5em;border-left:2px solid var(--interactive-accent);}.dialog-host.svelte-3n2ufb summary::marker {display:none;content:"";}.dialog-host.svelte-3n2ufb summary {border-left:4px solid var(--interactive-accent);padding-left:0.5em;cursor:pointer;outline:none;}.dialog-host.svelte-3n2ufb details > summary::after {content:"⏷";float:right;margin-right:0.5em;}.dialog-host.svelte-3n2ufb details[open] > summary::after {content:"⏶";float:right;margin-right:0.5em;}.dialog-host.svelte-3n2ufb input:invalid,\n .dialog-host.svelte-3n2ufb textarea:invalid {border-color:var(--background-modifier-error);}.dialog-host.svelte-3n2ufb .sub-section {margin-left:1em;display:flex;flex-direction:column;gap:0.5em;}.dialog-host.svelte-3n2ufb .row > input[type="text"]:disabled,\n .dialog-host.svelte-3n2ufb .row > input[type="password"]:disabled,\n .dialog-host.svelte-3n2ufb .row > textarea:disabled,\n .dialog-host.svelte-3n2ufb .row > select:disabled {background-color:var(--background-secondary);}'};SvelteDialog=class extends import_obsidian.Modal{constructor(plugin3,component2,initialData){super(plugin3.app);this.title="Obsidian LiveSync - Setup Wizard";this.plugin=plugin3;this.component=component2;this.initialData=initialData}resolveResult(){var _a8;null==(_a8=this.resultPromiseWithResolvers)||_a8.resolve(this.result);this.resultPromiseWithResolvers=void 0}onOpen(){const{contentEl}=this;contentEl.empty();const dialog=this;this.resultPromiseWithResolvers&&this.resultPromiseWithResolvers.reject("Dialog opened again");const pr=promiseWithResolvers();eventHub.once("plugin-unloaded",(()=>{if(this.resultPromiseWithResolvers===pr){pr.reject("Plugin unloaded");this.close()}}));this.resultPromiseWithResolvers=pr;this.mountedComponent=mount(DialogHost,{target:contentEl,props:{onSetupContext:props=>{setupDialogContext({...props,plugin:this.plugin,services:this.plugin.services})},setTitle:title=>{dialog.setTitle(title)},closeDialog:()=>{dialog.close()},setResult:result=>{this.result=result},getInitialData:()=>this.initialData,mountComponent:this.component}})}waitForClose(){if(!this.resultPromiseWithResolvers)throw new Error("Dialog not opened yet");return this.resultPromiseWithResolvers.promise}onClose(){this.resolveResult();fireAndForget((async()=>{this.mountedComponent&&await unmount(this.mountedComponent)}))}};SvelteDialogManager=class{constructor(plugin3){this.plugin=plugin3}async open(component2,initialData){return await openSvelteDialog(this.plugin,component2,initialData)}async openWithExplicitCancel(component2,initialData){for(let i2=0;i2<10;i2++){const ret=await openSvelteDialog(this.plugin,component2,initialData);if(void 0!==ret)return ret;if(this.plugin.services.appLifecycle.hasUnloaded())throw new Error("Operation cancelled due to app shutdown.");Logger("Please select 'Cancel' explicitly to cancel this operation.",LOG_LEVEL_NOTICE)}throw new Error("Operation Forcibly cancelled by user.")}};root_110=from_html("<h4> </h4>");root6=from_html('<div class="dialog-header svelte-1gf4irx"><h2> </h2> <!></div>');$$css7={hash:"svelte-1gf4irx",code:".dialog-header.svelte-1gf4irx {display:none;}"};root_111=from_html("<h3> </h3>");root7=from_html("<div><!> <!></div>");root8=from_html("<button> </button>");delegate(["click"]);root_113=from_html("<h3><!></h3>");root9=from_html('<div class="question-container svelte-o7k4lc"><!> <div class="question-content"><!></div></div>');$$css8={hash:"svelte-o7k4lc",code:".question-container.svelte-o7k4lc {border-bottom:2px solid var(--interactive-accent);margin-bottom:0.5lh;padding-bottom:0.5lh;}"};root10=from_html('<div><label><div class="choice-row svelte-1h8m5at"><input type="radio" class="svelte-1h8m5at"/> <span class="choice-title svelte-1h8m5at"> </span></div> <div class="choice-notes svelte-1h8m5at"><!> <!></div></label></div>');$$css9={hash:"svelte-1h8m5at",code:'.option-container.svelte-1h8m5at {border:1px solid transparent;border-radius:0.25lh;padding:0.5rem;}.option-container.selected.svelte-1h8m5at {border-color:var(--interactive-accent);}.choice-row.svelte-1h8m5at {display:flex;align-items:center;gap:0.5rem;\n /* margin-top: 1rem; */cursor:pointer;}.choice-row.svelte-1h8m5at span.choice-title:where(.svelte-1h8m5at) {width:auto;}.choice-row.svelte-1h8m5at input[type="radio"]:where(.svelte-1h8m5at) {\n /* width: 1.2rem;\n height: 1.2rem; */cursor:pointer;}.choice-notes.svelte-1h8m5at {margin-left:2rem;margin-top:0.25rem;color:var(--text-muted);font-size:0.9rem;}.option-container.selected.svelte-1h8m5at .choice-notes:where(.svelte-1h8m5at) {color:var(--text-normal);}'};root11=from_html('<div class="options-container"><!></div>');root12=from_html('<div class="question-container"><!></div>');root13=from_html('<div class="button-group"><!></div>');root_44=from_html("<!> <!>",1);root_24=from_html("<!> <!>",1);root_72=from_html("<!> <!>",1);root14=from_html("<!> <!> <!> <!>",1);root_25=from_html("<h3> </h3>");root_114=from_html("<div><!> <!></div>");root15=from_html('<details><summary> </summary> <div class="sub-section"><!></div></details>');root16=from_html('<label class="choice-row svelte-2n6uv8"><input type="checkbox" class="svelte-2n6uv8"/> <span class="choice-title svelte-2n6uv8"> </span></label> <div class="choice-notes svelte-2n6uv8"><!> <!></div>',1);$$css10={hash:"svelte-2n6uv8",code:'.choice-row.svelte-2n6uv8 {display:flex;align-items:center;gap:0.5rem;margin-top:1rem;cursor:pointer;}.choice-row.svelte-2n6uv8 span.choice-title:where(.svelte-2n6uv8) {width:auto;}.choice-row.svelte-2n6uv8 input[type="checkbox"]:where(.svelte-2n6uv8) {\n /* width: 1.2rem;\n height: 1.2rem; */cursor:pointer;}.choice-notes.svelte-2n6uv8 {margin-left:2rem;margin-top:0.25rem;color:var(--text-muted);font-size:0.9rem;}'};root_45=from_html("<!> <!>",1);root_26=from_html("<!> <!>",1);root_73=from_html("<!> <!>",1);root17=from_html("<!> <!> <!> <!>",1);root_46=from_html("<!> <!> <!>",1);root_27=from_html("<!> <!>",1);root_83=from_html("<!> <!>",1);root18=from_html("<!> <!> <!> <!>",1);root_28=from_html("<ol><li>On this device, please keep this Vault open.</li> <li>On the source device, open Obsidian.</li> <li>On the source device, from the command palette, run the 'Show settings as a QR code' command.</li> <li>On this device, switch to the camera app or use a QR code scanner to scan the displayed QR code.</li></ol>");root19=from_html("<!> <!> <!> <!>",1);root20=from_html('<label class="row"><span> </span> <!></label>');root21=from_html('<input spellcheck="false" autocorrect="off" autocapitalize="off"/> <input type="checkbox"/>',1);root_115=from_html('Please enter the Setup URI that was generated during server installation or on another device, along with the vault\n passphrase.<br/> Note that you can generate a new Setup URI by running the "Copy settings as a new Setup URI" command in the command palette.',1);root_29=from_html('<input type="text" placeholder="obsidian://setuplivesync?settings=...." autocorrect="off" autocapitalize="off" spellcheck="false" required/>');root_74=from_html("<!> <!>",1);root22=from_html("<!> <!> <!> <!> <!> <!> <!> <!>",1);root_116=from_html("<p>The connection to the server has been configured successfully. As the next step, <strong>the synchronisation data on the server will be built based on the current data on this device.</strong></p> <p><strong>IMPORTANT</strong> <br/> After restarting, the data on this device will be uploaded to the server as the 'master copy'. Please be aware that\n any unintended data currently on the server will be completely overwritten.</p>",1);root_47=from_html("<!> <!>",1);root23=from_html("<!> <!> <!> <!>",1);root_117=from_html("<p>The connection to the server has been configured successfully. As the next step, <strong>the latest synchronisation data will be downloaded from the server to this device.</strong></p> <p><strong>PLEASE NOTE</strong> <br/> After restarting, the database on this device will be rebuilt using data from the server. If there are any unsynchronised\n files in this vault, conflicts may occur with the server data.</p>",1);root_48=from_html("<!> <!>",1);root24=from_html("<!> <!> <!> <!>",1);root_118=from_html("The connection to the server has been configured successfully. As the next step, <strong>the local database, that is to say the synchronisation information, must be reconstituted.</strong>",1);root_210=from_html("<!> <!> <!> <!>",1);root_102=from_html("<!> <!>",1);root25=from_html("<!> <!> <!> <!>",1);root_33=from_html("<!> <!> <!>",1);root_119=from_html("<!> <!>",1);root_75=from_html("<!> <!>",1);root26=from_html("<!> <!> <!>",1);checkConfig=async editingSettings=>{var _a8,_b5,_c3,_d2,_e2,_f,_g,_h,_i2,_j,_k,_l2,_m2,_n2;const result=[],addMessage=(msg,classes=[])=>{result.push({message:msg,classes})},addSuccess=(msg,value)=>{result.push({message:msg,result:"ok",value})},_addError=(message,fixMessage,fix,value)=>{result.push({message,result:"error",fixMessage,fix,value})},addErrorMessage=(msg,classes=[])=>{result.push({message:msg,result:"error",classes})},addError=(message,fixMessage,key3,expected)=>{_addError(message,fixMessage,(async()=>{await updateRemoteSetting(editingSettings,key3,expected)}))};addMessage($msg("obsidianLiveSyncSettingTab.logCheckingDbConfig"));try{if(isCloudantURI(editingSettings.couchDB_URI)){addMessage($msg("obsidianLiveSyncSettingTab.logCannotUseCloudant"));return result}const customHeaders=parseHeaderValues(editingSettings.couchDB_CustomHeaders),credential=generateCredentialObject(editingSettings),r4=await requestToCouchDBWithCredentials(editingSettings.couchDB_URI,credential,window.origin,void 0,void 0,void 0,customHeaders),responseConfig=r4.json;addMessage($msg("obsidianLiveSyncSettingTab.msgNotice"),["ob-btn-config-head"]);addMessage($msg("obsidianLiveSyncSettingTab.msgIfConfigNotPersistent"),["ob-btn-config-info"]);addMessage($msg("obsidianLiveSyncSettingTab.msgConfigCheck"),["ob-btn-config-head"]);const serverBanner=null!=(_b5=null!=(_a8=r4.headers.server)?_a8:r4.headers.Server)?_b5:"unknown";addMessage($msg("obsidianLiveSyncSettingTab.serverVersion",{info:serverBanner}));const versionMatch=serverBanner.match(/CouchDB(\/([0-9.]+))?/),versionStr=versionMatch?versionMatch[2]:"0.0.0";editingSettings.couchDB_USER in responseConfig.admins?addSuccess($msg("obsidianLiveSyncSettingTab.okAdminPrivileges")):addSuccess($msg("obsidianLiveSyncSettingTab.warnNoAdmin"));isGreaterThanOrEqual(versionStr,"3.2.0")?"true"!=(null==(_c3=null==responseConfig?void 0:responseConfig.chttpd)?void 0:_c3.require_valid_user)?addError($msg("obsidianLiveSyncSettingTab.errRequireValidUser"),$msg("obsidianLiveSyncSettingTab.msgSetRequireValidUser"),"chttpd/require_valid_user","true"):addSuccess($msg("obsidianLiveSyncSettingTab.okRequireValidUser")):"true"!=(null==(_d2=null==responseConfig?void 0:responseConfig.chttpd_auth)?void 0:_d2.require_valid_user)?addError($msg("obsidianLiveSyncSettingTab.errRequireValidUserAuth"),$msg("obsidianLiveSyncSettingTab.msgSetRequireValidUserAuth"),"chttpd_auth/require_valid_user","true"):addSuccess($msg("obsidianLiveSyncSettingTab.okRequireValidUserAuth"));(null==responseConfig?void 0:responseConfig.httpd["WWW-Authenticate"])?addSuccess($msg("obsidianLiveSyncSettingTab.okWwwAuth")):addError($msg("obsidianLiveSyncSettingTab.errMissingWwwAuth"),$msg("obsidianLiveSyncSettingTab.msgSetWwwAuth"),"httpd/WWW-Authenticate",'Basic realm="couchdb"');isGreaterThanOrEqual(versionStr,"3.2.0")?"true"!=(null==(_e2=null==responseConfig?void 0:responseConfig.chttpd)?void 0:_e2.enable_cors)?addError($msg("obsidianLiveSyncSettingTab.errEnableCorsChttpd"),$msg("obsidianLiveSyncSettingTab.msgEnableCorsChttpd"),"chttpd/enable_cors","true"):addSuccess($msg("obsidianLiveSyncSettingTab.okEnableCorsChttpd")):"true"!=(null==(_f=null==responseConfig?void 0:responseConfig.httpd)?void 0:_f.enable_cors)?addError($msg("obsidianLiveSyncSettingTab.errEnableCors"),$msg("obsidianLiveSyncSettingTab.msgEnableCors"),"httpd/enable_cors","true"):addSuccess($msg("obsidianLiveSyncSettingTab.okEnableCors"));if(!isCloudantURI(editingSettings.couchDB_URI)){Number(null!=(_h=null==(_g=null==responseConfig?void 0:responseConfig.chttpd)?void 0:_g.max_http_request_size)?_h:0)<4294967296?addError($msg("obsidianLiveSyncSettingTab.errMaxRequestSize"),$msg("obsidianLiveSyncSettingTab.msgSetMaxRequestSize"),"chttpd/max_http_request_size","4294967296"):addSuccess($msg("obsidianLiveSyncSettingTab.okMaxRequestSize"));Number(null!=(_j=null==(_i2=null==responseConfig?void 0:responseConfig.couchdb)?void 0:_i2.max_document_size)?_j:0)<5e7?addError($msg("obsidianLiveSyncSettingTab.errMaxDocumentSize"),$msg("obsidianLiveSyncSettingTab.msgSetMaxDocSize"),"couchdb/max_document_size","50000000"):addSuccess($msg("obsidianLiveSyncSettingTab.okMaxDocumentSize"))}"true"!=(null==(_k=null==responseConfig?void 0:responseConfig.cors)?void 0:_k.credentials)?addError($msg("obsidianLiveSyncSettingTab.errCorsCredentials"),$msg("obsidianLiveSyncSettingTab.msgSetCorsCredentials"),"cors/credentials","true"):addSuccess($msg("obsidianLiveSyncSettingTab.okCorsCredentials"));const ConfiguredOrigins=((null!=(_m2=null==(_l2=null==responseConfig?void 0:responseConfig.cors)?void 0:_l2.origins)?_m2:"")+"").split(",");if("*"==(null==(_n2=null==responseConfig?void 0:responseConfig.cors)?void 0:_n2.origins)||-1!==ConfiguredOrigins.indexOf("app://obsidian.md")&&-1!==ConfiguredOrigins.indexOf("capacitor://localhost")&&-1!==ConfiguredOrigins.indexOf("http://localhost"))addSuccess($msg("obsidianLiveSyncSettingTab.okCorsOrigins"));else{const fixedValue=[...new Set([...ConfiguredOrigins.map((e3=>e3.trim())),"app://obsidian.md","capacitor://localhost","http://localhost"])].join(",");addError($msg("obsidianLiveSyncSettingTab.errCorsOrigins"),$msg("obsidianLiveSyncSettingTab.msgSetCorsOrigins"),"cors/origins",fixedValue)}addMessage($msg("obsidianLiveSyncSettingTab.msgConnectionCheck"),["ob-btn-config-head"]);addMessage($msg("obsidianLiveSyncSettingTab.msgCurrentOrigin",{origin:window.location.origin}));const origins=["app://obsidian.md","capacitor://localhost","http://localhost"];for(const org of origins){const rr=await requestToCouchDBWithCredentials(editingSettings.couchDB_URI,credential,org,void 0,void 0,void 0,customHeaders),responseHeaders=Object.fromEntries(Object.entries(rr.headers).map((e3=>{e3[0]=`${e3[0]}`.toLowerCase();return e3})));addMessage($msg("obsidianLiveSyncSettingTab.msgOriginCheck",{org}));"true"!=responseHeaders["access-control-allow-credentials"]?addErrorMessage($msg("obsidianLiveSyncSettingTab.errCorsNotAllowingCredentials")):addSuccess($msg("obsidianLiveSyncSettingTab.okCorsCredentialsForOrigin"));responseHeaders["access-control-allow-origin"]!=org?addErrorMessage($msg("obsidianLiveSyncSettingTab.warnCorsOriginUnmatched",{from:origin,to:responseHeaders["access-control-allow-origin"]})):addSuccess($msg("obsidianLiveSyncSettingTab.okCorsOriginMatched"))}addMessage($msg("obsidianLiveSyncSettingTab.msgDone"),["ob-btn-config-head"]);addMessage($msg("obsidianLiveSyncSettingTab.msgConnectionProxyNote"),["ob-btn-config-info"]);addMessage($msg("obsidianLiveSyncSettingTab.logCheckingConfigDone"))}catch(ex){if(401==(null==ex?void 0:ex.status)){addErrorMessage($msg("obsidianLiveSyncSettingTab.errAccessForbidden"));addErrorMessage($msg("obsidianLiveSyncSettingTab.errCannotContinueTest"));addMessage($msg("obsidianLiveSyncSettingTab.logCheckingConfigDone"))}else{addErrorMessage($msg("obsidianLiveSyncSettingTab.logCheckingConfigFailed"));Logger(ex)}}return result};on_click2=(_,fixIssue,issue)=>fixIssue(issue());root_211=from_html('<div class="operations svelte-a38xug"><button class="mod-cta">Fix</button></div>');root_120=from_html('<div><div class="message svelte-a38xug"> </div> <!></div>');root_84=from_html("<h3>Issue detection log:</h3> <!>",1);root27=from_html('<!> <div class="check-results svelte-a38xug"><details><summary><!></summary> <!></details></div>',1);$$css11={hash:"svelte-a38xug",code:"\n /* Make .check-result a CSS Grid: let .message expand and keep .operations at minimum width, aligned to the right */.check-results.svelte-a38xug {\n /* Adjust spacing as required */margin-top:0.75rem;}.check-result.svelte-a38xug {display:grid;grid-template-columns:1fr auto; /* message takes remaining space, operations use minimum width */align-items:center; /* vertically centre align */gap:0.5rem 1rem;padding:0rem 0.5rem;border-radius:0;box-shadow:none;border-left:0.5em solid var(--interactive-accent);margin-bottom:0.25lh;}.check-result.error.svelte-a38xug {border-left:0.5em solid var(--text-error);}.check-result.success.svelte-a38xug {border-left:0.5em solid var(--text-success);}.check-result.svelte-a38xug .message:where(.svelte-a38xug) {\n /* Wrap long messages */white-space:normal;word-break:break-word;font-size:0.95rem;color:var(--text-normal);}.check-result.svelte-a38xug .operations:where(.svelte-a38xug) {\n /* Centre the button(s) vertically and align to the right */display:flex;align-items:center;justify-content:flex-end;gap:0.5rem;}\n\n /* For small screens: move .operations below and stack vertically */\n @media (max-width: 520px) {.check-result.svelte-a38xug {grid-template-columns:1fr;grid-auto-rows:auto;}.check-result.svelte-a38xug .operations:where(.svelte-a38xug) {justify-content:flex-start;margin-top:0.5rem;}\n }"};delegate(["click"]);root_212=from_html('<input type="text" name="couchdb-url" placeholder="https://example.com" autocorrect="off" autocapitalize="off" spellcheck="false" required pattern="^https?://.+"/>');root_49=from_html('<input type="text" name="couchdb-username" placeholder="Enter your username" autocorrect="off" autocapitalize="off" spellcheck="false" required/>');root_64=from_html('<input type="text" name="couchdb-database" placeholder="Enter your database name" autocorrect="off" autocapitalize="off" spellcheck="false" required pattern="^[a-z0-9][a-z0-9_]*$"/>');root_85=from_html('<input type="checkbox" name="couchdb-use-internal-api"/>');root_1110=from_html('<textarea name="couchdb-custom-headers" placeholder="e.g., x-example-header: value\\n another-header: value2" autocapitalize="off" spellcheck="false" rows="4"></textarea>');root_134=from_html('<input type="checkbox" name="couchdb-use-jwt"/>');root_142=from_html("<select><option>HS256</option><option>HS512</option><option>ES256</option><option>ES512</option></select>");root_152=from_html('<input type="text" name="couchdb-jwt-exp-duration" placeholder="0"/>');root_162=from_html('<textarea name="couchdb-jwt-key" rows="5" autocapitalize="off" spellcheck="false" placeholder="Enter your JWT secret or private key"></textarea>');root_182=from_html('<input type="text" name="couchdb-jwt-kid" placeholder="Enter your JWT Key ID"/>');root_192=from_html('<input type="text" name="couchdb-jwt-sub" placeholder="Enter your JWT Subject (CouchDB Username)"/>');root_123=from_html("<!> <!> <!> <!> <!> <!> <!> <!>",1);root_242=from_html("<!> <!> <!>",1);root28=from_html("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <hr/> <!> <!>",1);root_213=from_html('<input type="text" name="s3-endpoint" placeholder="https://s3.amazonaws.com" autocorrect="off" autocapitalize="off" spellcheck="false" required pattern="^https?://.+"/>');root_410=from_html('<input type="text" name="s3-access-key-id" placeholder="Enter your Access Key ID" autocorrect="off" autocapitalize="off" spellcheck="false" required/>');root_65=from_html('<input type="text" name="s3-bucket-name" placeholder="Enter your Bucket Name" autocorrect="off" autocapitalize="off" spellcheck="false" required/>');root_76=from_html('<input type="text" name="s3-region" placeholder="Enter your Region (e.g., us-east-1, auto for R2)" autocorrect="off" autocapitalize="off" spellcheck="false"/>');root_86=from_html('<input type="checkbox" name="s3-use-path-style"/>');root_93=from_html('<input type="text" name="s3-folder-prefix" placeholder="Enter a folder prefix (optional)" autocorrect="off" autocapitalize="off" spellcheck="false"/>');root_1111=from_html('<input type="checkbox" name="s3-use-internal-api"/>');root_143=from_html('<textarea name="bucket-custom-headers" placeholder="e.g., x-example-header: value\\n another-header: value2" autocapitalize="off" spellcheck="false" rows="4"></textarea>');root_183=from_html("<!> <!> <!>",1);root29=from_html("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!>",1);new(PouchError=class extends Error{constructor(status,error,reason){super();this.status=status;this.name=error;this.message=reason;this.error=!0}toString(){return JSON.stringify({status:this.status,name:this.name,message:this.message,reason:this.reason})}})(401,"unauthorized","Name or password is incorrect.");MISSING_BULK_DOCS=new PouchError(400,"bad_request","Missing JSON list of 'docs'");MISSING_DOC=new PouchError(404,"not_found","missing");REV_CONFLICT=new PouchError(409,"conflict","Document update conflict");INVALID_ID=new PouchError(400,"bad_request","_id field must contain a string");MISSING_ID=new PouchError(412,"missing_id","_id is required for puts");RESERVED_ID=new PouchError(400,"bad_request","Only reserved document ids may start with underscore.");new PouchError(412,"precondition_failed","Database not open");UNKNOWN_ERROR=new PouchError(500,"unknown_error","Database encountered an unknown error");BAD_ARG=new PouchError(500,"badarg","Some query argument is invalid");new PouchError(400,"invalid_request","Request was invalid");QUERY_PARSE_ERROR=new PouchError(400,"query_parse_error","Some query parameter is invalid");DOC_VALIDATION=new PouchError(500,"doc_validation","Bad special document member");BAD_REQUEST=new PouchError(400,"bad_request","Something wrong with the request");NOT_AN_OBJECT=new PouchError(400,"bad_request","Document must be a JSON object");new PouchError(404,"not_found","Database not found");IDB_ERROR=new PouchError(500,"indexed_db_went_bad","unknown");new PouchError(500,"web_sql_went_bad","unknown");new PouchError(500,"levelDB_went_went_bad","unknown");new PouchError(403,"forbidden","Forbidden by design doc validate_doc_update function");INVALID_REV=new PouchError(400,"bad_request","Invalid rev format");new PouchError(412,"file_exists","The database could not be created, the file already exists.");MISSING_STUB=new PouchError(412,"missing_stub","A pre-existing attachment stub wasn't found");new PouchError(413,"invalid_url","Provided URL is invalid");rnds82=new Uint8Array(16);regex_default2=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;validate_default2=function validate3(uuid2){return"string"==typeof uuid2&&regex_default2.test(uuid2)};byteToHex2=[];for(i2=0;i2<256;++i2)byteToHex2.push((i2+256).toString(16).substr(1));stringify_default2=function stringify2(arr){var offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,uuid2=(byteToHex2[arr[offset+0]]+byteToHex2[arr[offset+1]]+byteToHex2[arr[offset+2]]+byteToHex2[arr[offset+3]]+"-"+byteToHex2[arr[offset+4]]+byteToHex2[arr[offset+5]]+"-"+byteToHex2[arr[offset+6]]+byteToHex2[arr[offset+7]]+"-"+byteToHex2[arr[offset+8]]+byteToHex2[arr[offset+9]]+"-"+byteToHex2[arr[offset+10]]+byteToHex2[arr[offset+11]]+byteToHex2[arr[offset+12]]+byteToHex2[arr[offset+13]]+byteToHex2[arr[offset+14]]+byteToHex2[arr[offset+15]]).toLowerCase();if(!validate_default2(uuid2))throw TypeError("Stringified UUID is invalid");return uuid2};v4_default2=function v42(options,buf,offset){var rnds,i2;(rnds=(options=options||{}).random||(options.rng||rng2)())[6]=15&rnds[6]|64;rnds[8]=63&rnds[8]|128;if(buf){offset=offset||0;for(i2=0;i2<16;++i2)buf[offset+i2]=rnds[i2];return buf}return stringify_default2(rnds)};thisAtob=function(str){return atob(str)};thisBtoa=function(str){return btoa(str)};import_spark_md5=__toESM(require_spark_md5());setImmediateShim=self.setImmediate||self.setTimeout;MD5_CHUNK_SIZE=32768;import_events15=__toESM(require_events());funcToString=Function.prototype.toString;objectCtorString=funcToString.call(Object);MAX_NUM_CONCURRENT_REQUESTS=6;try{localStorage.setItem("_pouch_check_localstorage",1);hasLocal=!!localStorage.getItem("_pouch_check_localstorage")}catch(e3){hasLocal=!1}nextTick="function"==typeof queueMicrotask?queueMicrotask:function nextTick2(fn){Promise.resolve().then(fn)};Changes=class extends import_events15.default{constructor(){super();this._listeners={};hasLocalStorage()&&addEventListener("storage",(e3=>{this.emit(e3.key)}))}addListener(dbName,id,db,opts){function eventFunction(){if(self3._listeners[id])if(inprogress)inprogress="waiting";else{inprogress=!0;var changesOpts=pick(opts,["style","include_docs","attachments","conflicts","filter","doc_ids","view","since","query_params","binary","return_docs"]);db.changes(changesOpts).on("change",(function(c3){if(c3.seq>opts.since&&!opts.cancelled){opts.since=c3.seq;opts.onChange(c3)}})).on("complete",(function(){"waiting"===inprogress&&nextTick(eventFunction);inprogress=!1})).on("error",(function onError(){inprogress=!1}))}}var inprogress,self3;if(!this._listeners[id]){inprogress=!1;self3=this;this._listeners[id]=eventFunction;this.on(dbName,eventFunction)}}removeListener(dbName,id){if(id in this._listeners){super.removeListener(dbName,this._listeners[id]);delete this._listeners[id]}}notifyLocalWindows(dbName){hasLocalStorage()&&(localStorage[dbName]="a"===localStorage[dbName]?"b":"a")}notify(dbName){this.emit(dbName);this.notifyLocalWindows(dbName)}};(function f2(){}).name;keys2=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];qName="queryKey";qParser=/(?:^|&)([^&=]*)=?([^&]*)/g;parser=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;uuid=v4_default2;f3=fetch;h2=Headers;MIN_MAGNITUDE=-324;MAGNITUDE_DIGITS=3;SEP="";combinationFields=["$or","$nor","$not"];matchers={$elemMatch:function(doc,userValue,parsedField,docFieldValue){return!!Array.isArray(docFieldValue)&&0!==docFieldValue.length&&("object"==typeof docFieldValue[0]&&null!==docFieldValue[0]?docFieldValue.some((function(val2){return rowFilter(val2,userValue,Object.keys(userValue))})):docFieldValue.some((function(val2){return matchSelector(userValue,doc,parsedField,val2)})))},$allMatch:function(doc,userValue,parsedField,docFieldValue){return!!Array.isArray(docFieldValue)&&0!==docFieldValue.length&&("object"==typeof docFieldValue[0]&&null!==docFieldValue[0]?docFieldValue.every((function(val2){return rowFilter(val2,userValue,Object.keys(userValue))})):docFieldValue.every((function(val2){return matchSelector(userValue,doc,parsedField,val2)})))},$eq:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&0===collate(docFieldValue,userValue)},$gte:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&collate(docFieldValue,userValue)>=0},$gt:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&collate(docFieldValue,userValue)>0},$lte:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&collate(docFieldValue,userValue)<=0},$lt:function(doc,userValue,parsedField,docFieldValue){return fieldIsNotUndefined(docFieldValue)&&collate(docFieldValue,userValue)<0},$exists:function(doc,userValue,parsedField,docFieldValue){return userValue?fieldIsNotUndefined(docFieldValue):!fieldIsNotUndefined(docFieldValue)},$mod:function(doc,userValue,parsedField,docFieldValue){return fieldExists(docFieldValue)&&modField(docFieldValue,userValue)},$ne:function(doc,userValue,parsedField,docFieldValue){return userValue.every((function(neValue){return 0!==collate(docFieldValue,neValue)}))},$in:function(doc,userValue,parsedField,docFieldValue){return fieldExists(docFieldValue)&&arrayContainsValue(docFieldValue,userValue)},$nin:function(doc,userValue,parsedField,docFieldValue){return fieldExists(docFieldValue)&&!arrayContainsValue(docFieldValue,userValue)},$size:function(doc,userValue,parsedField,docFieldValue){return fieldExists(docFieldValue)&&Array.isArray(docFieldValue)&&arraySize(docFieldValue,userValue)},$all:function(doc,userValue,parsedField,docFieldValue){return Array.isArray(docFieldValue)&&arrayContainsAllValues(docFieldValue,userValue)},$regex:function(doc,userValue,parsedField,docFieldValue){return fieldExists(docFieldValue)&&"string"==typeof docFieldValue&&userValue.every((function(regexValue){return regexMatch(docFieldValue,regexValue)}))},$type:function(doc,userValue,parsedField,docFieldValue){return typeMatch(docFieldValue,userValue)}};index_browser_es_default=function applyChangesFilterPlugin(PouchDB2){PouchDB2._changesFilterPlugin={validate:validate4,normalize,shouldFilter,filter:filter2}};import_events16=__toESM(require_events());Changes2=class extends import_events16.default{constructor(db,opts,callback){var complete,promise;super();this.db=db;opts=opts?clone2(opts):{};complete=opts.complete=once2(((err3,resp)=>{err3?listenerCount(this,"error")>0&&this.emit("error",err3):this.emit("complete",resp);this.removeAllListeners();db.removeListener("destroyed",onDestroy2)}));if(callback){this.on("complete",(function(resp){callback(null,resp)}));this.on("error",callback)}const onDestroy2=()=>{this.cancel()};db.once("destroyed",onDestroy2);opts.onChange=(change,pending3,lastSeq)=>{this.isCancelled||tryCatchInChangeListener(this,change,pending3,lastSeq)};promise=new Promise((function(fulfill,reject){opts.complete=function(err3,res2){err3?reject(err3):fulfill(res2)}}));this.once("cancel",(function(){db.removeListener("destroyed",onDestroy2);opts.complete(null,{status:"cancelled"})}));this.then=promise.then.bind(promise);this.catch=promise.catch.bind(promise);this.then((function(result){complete(null,result)}),complete);db.taskqueue.isReady?this.validateChanges(opts):db.taskqueue.addTask((failed2=>{failed2?opts.complete(failed2):this.isCancelled?this.emit("cancel"):this.validateChanges(opts)}))}cancel(){this.isCancelled=!0;this.db.taskqueue.isReady&&this.emit("cancel")}validateChanges(opts){var callback=opts.complete;PouchDB._changesFilterPlugin?PouchDB._changesFilterPlugin.validate(opts,(err3=>{if(err3)return callback(err3);this.doChanges(opts)})):this.doChanges(opts)}doChanges(opts){var newPromise,callback=opts.complete;"live"in(opts=clone2(opts))&&!("continuous"in opts)&&(opts.continuous=opts.live);opts.processChange=processChange;"latest"===opts.since&&(opts.since="now");opts.since||(opts.since=0);if("now"!==opts.since){if(PouchDB._changesFilterPlugin){PouchDB._changesFilterPlugin.normalize(opts);if(PouchDB._changesFilterPlugin.shouldFilter(this,opts))return PouchDB._changesFilterPlugin.filter(this,opts)}else["doc_ids","filter","selector","view"].forEach((function(key3){key3 in opts&&guardedConsole("warn",'The "'+key3+'" option was passed in to changes/replicate, but pouchdb-changes-filter plugin is not installed, so it was ignored. Please install the plugin to enable filtering.')}));"descending"in opts||(opts.descending=!1);opts.limit=0===opts.limit?1:opts.limit;opts.complete=callback;if((newPromise=this.db._changes(opts))&&"function"==typeof newPromise.cancel){const cancel2=this.cancel;this.cancel=(...args)=>{newPromise.cancel();cancel2.apply(this,args)}}}else this.db.info().then((info3=>{if(this.isCancelled)callback(null,{status:"cancelled"});else{opts.since=info3.update_seq;this.doChanges(opts)}}),callback)}};validRevRegex=/^\d+-[^-]*$/;AbstractPouchDB=class extends import_events16.default{_setup(){this.post=adapterFun("post",(function(doc,opts,callback){if("function"==typeof opts){callback=opts;opts={}}if(isNotSingleDoc(doc))return callback(createError(NOT_AN_OBJECT));this.bulkDocs({docs:[doc]},opts,yankError(callback,doc._id))})).bind(this);this.put=adapterFun("put",(function(doc,opts,cb2){if("function"==typeof opts){cb2=opts;opts={}}if(isNotSingleDoc(doc))return cb2(createError(NOT_AN_OBJECT));invalidIdError(doc._id);if("_rev"in doc&&!isValidRev(doc._rev))return cb2(createError(INVALID_REV));if(isLocalId(doc._id)&&"function"==typeof this._putLocal)return doc._deleted?this._removeLocal(doc,cb2):this._putLocal(doc,cb2);const putDoc=next2=>{"function"==typeof this._put&&!1!==opts.new_edits?this._put(doc,opts,next2):this.bulkDocs({docs:[doc]},opts,yankError(next2,doc._id))};if(opts.force&&doc._rev){(function transformForceOptionToNewEditsOption(){var parts=doc._rev.split("-"),oldRevId=parts[1],newRevNum=parseInt(parts[0],10)+1,newRevId=rev2();doc._revisions={start:newRevNum,ids:[newRevId,oldRevId]};doc._rev=newRevNum+"-"+newRevId;opts.new_edits=!1})();putDoc((function(err3){var result=err3?null:{ok:!0,id:doc._id,rev:doc._rev};cb2(err3,result)}))}else putDoc(cb2)})).bind(this);this.putAttachment=adapterFun("putAttachment",(function(docId,attachmentId,rev$$1,blob,type){function createAttachment(doc){var prevrevpos="_rev"in doc?parseInt(doc._rev,10):0;doc._attachments=doc._attachments||{};doc._attachments[attachmentId]={content_type:type,data:blob,revpos:++prevrevpos};return api.put(doc)}var api=this;if("function"==typeof type){type=blob;blob=rev$$1;rev$$1=null}if(void 0===type){type=blob;blob=rev$$1;rev$$1=null}type||guardedConsole("warn","Attachment",attachmentId,"on document",docId,"is missing content_type");return api.get(docId).then((function(doc){if(doc._rev!==rev$$1)throw createError(REV_CONFLICT);return createAttachment(doc)}),(function(err3){if(err3.reason===MISSING_DOC.message)return createAttachment({_id:docId});throw err3}))})).bind(this);this.removeAttachment=adapterFun("removeAttachment",(function(docId,attachmentId,rev$$1,callback){this.get(docId,((err3,obj)=>{if(err3)callback(err3);else if(obj._rev===rev$$1){if(!obj._attachments)return callback();delete obj._attachments[attachmentId];0===Object.keys(obj._attachments).length&&delete obj._attachments;this.put(obj,callback)}else callback(createError(REV_CONFLICT))}))})).bind(this);this.remove=adapterFun("remove",(function(docOrId,optsOrRev,opts,callback){var doc,newDoc;if("string"==typeof optsOrRev){doc={_id:docOrId,_rev:optsOrRev};if("function"==typeof opts){callback=opts;opts={}}}else{doc=docOrId;if("function"==typeof optsOrRev){callback=optsOrRev;opts={}}else{callback=opts;opts=optsOrRev}}(opts=opts||{}).was_delete=!0;(newDoc={_id:doc._id,_rev:doc._rev||opts.rev})._deleted=!0;if(isLocalId(newDoc._id)&&"function"==typeof this._removeLocal)return this._removeLocal(doc,callback);this.bulkDocs({docs:[newDoc]},opts,yankError(callback,newDoc._id))})).bind(this);this.revsDiff=adapterFun("revsDiff",(function(req,opts,callback){function addToMissing(id,revId){missing.has(id)||missing.set(id,{missing:[]});missing.get(id).missing.push(revId)}function processDoc(id,rev_tree){var missingForId=req[id].slice(0);traverseRevTree(rev_tree,(function(isLeaf,pos,revHash,ctx,opts2){var rev$$1=pos+"-"+revHash,idx2=missingForId.indexOf(rev$$1);if(-1!==idx2){missingForId.splice(idx2,1);"available"!==opts2.status&&addToMissing(id,rev$$1)}}));missingForId.forEach((function(rev$$1){addToMissing(id,rev$$1)}))}var ids,count,missing;if("function"==typeof opts){callback=opts;opts={}}if(!(ids=Object.keys(req)).length)return callback(null,{});count=0;missing=new Map;ids.forEach((function(id){this._getRevisionTree(id,(function(err3,rev_tree){if(err3&&404===err3.status&&"missing"===err3.message)missing.set(id,{missing:req[id]});else{if(err3)return callback(err3);processDoc(id,rev_tree)}if(++count===ids.length){var missingObj={};missing.forEach((function(value,key3){missingObj[key3]=value}));return callback(null,missingObj)}}))}),this)})).bind(this);this.bulkGet=adapterFun("bulkGet",(function(opts,callback){bulkGet(this,opts,callback)})).bind(this);this.compactDocument=adapterFun("compactDocument",(function(docId,maxHeight,callback){this._getRevisionTree(docId,((err3,revTree)=>{var height,candidates,revs;if(err3)return callback(err3);height=computeHeight(revTree);candidates=[];revs=[];Object.keys(height).forEach((function(rev$$1){height[rev$$1]>maxHeight&&candidates.push(rev$$1)}));traverseRevTree(revTree,(function(isLeaf,pos,revHash,ctx,opts){var rev$$1=pos+"-"+revHash;"available"===opts.status&&-1!==candidates.indexOf(rev$$1)&&revs.push(rev$$1)}));this._doCompaction(docId,revs,callback)}))})).bind(this);this.compact=adapterFun("compact",(function(opts,callback){if("function"==typeof opts){callback=opts;opts={}}opts=opts||{};this._compactionQueue=this._compactionQueue||[];this._compactionQueue.push({opts,callback});1===this._compactionQueue.length&&doNextCompaction(this)})).bind(this);this.get=adapterFun("get",(function(id,opts,cb2){var leaves,i2;if("function"==typeof opts){cb2=opts;opts={}}opts=opts||{};if("string"!=typeof id)return cb2(createError(INVALID_ID));if(isLocalId(id)&&"function"==typeof this._getLocal)return this._getLocal(id,cb2);leaves=[];const finishOpenRevs=()=>{var result=[],count=leaves.length;if(!count)return cb2(null,result);leaves.forEach((leaf=>{this.get(id,{rev:leaf,revs:opts.revs,latest:opts.latest,attachments:opts.attachments,binary:opts.binary},(function(err3,doc){var existing,i3,l3;if(err3)result.push({missing:leaf});else{for(i3=0,l3=result.length;i3<l3;i3++)if(result[i3].ok&&result[i3].ok._rev===doc._rev){existing=!0;break}existing||result.push({ok:doc})}--count||cb2(null,result)}))}))};if(!opts.open_revs)return this._get(id,opts,((err3,result)=>{var doc,metadata,ctx,conflicts,splittedRev,revNo,revHash,paths,path2,i3,currentPath,howMany,pos,attachments,count,key3;if(err3){err3.docId=id;return cb2(err3)}doc=result.doc;metadata=result.metadata;ctx=result.ctx;opts.conflicts&&(conflicts=collectConflicts(metadata)).length&&(doc._conflicts=conflicts);isDeleted(metadata,doc._rev)&&(doc._deleted=!0);if(opts.revs||opts.revs_info){splittedRev=doc._rev.split("-");revNo=parseInt(splittedRev[0],10);revHash=splittedRev[1];paths=rootToLeaf(metadata.rev_tree);path2=null;for(i3=0;i3<paths.length;i3++){const hashIndex=(currentPath=paths[i3]).ids.findIndex((x2=>x2.id===revHash));(hashIndex===revNo-1||!path2&&-1!==hashIndex)&&(path2=currentPath)}if(!path2){(err3=new Error("invalid rev tree")).docId=id;return cb2(err3)}const pathId=doc._rev.split("-")[1],indexOfRev=path2.ids.findIndex((x2=>x2.id===pathId))+1;howMany=path2.ids.length-indexOfRev;path2.ids.splice(indexOfRev,howMany);path2.ids.reverse();opts.revs&&(doc._revisions={start:path2.pos+path2.ids.length-1,ids:path2.ids.map((function(rev$$1){return rev$$1.id}))});if(opts.revs_info){pos=path2.pos+path2.ids.length;doc._revs_info=path2.ids.map((function(rev$$1){return{rev:--pos+"-"+rev$$1.id,status:rev$$1.opts.status}}))}}if(opts.attachments&&doc._attachments){attachments=doc._attachments;if(0===(count=Object.keys(attachments).length))return cb2(null,doc);Object.keys(attachments).forEach((key4=>{this._getAttachment(doc._id,key4,attachments[key4],{binary:opts.binary,metadata,ctx},(function(err4,data){var att=doc._attachments[key4];att.data=data;delete att.stub;delete att.length;--count||cb2(null,doc)}))}))}else{if(doc._attachments)for(key3 in doc._attachments)Object.prototype.hasOwnProperty.call(doc._attachments,key3)&&(doc._attachments[key3].stub=!0);cb2(null,doc)}}));if("all"===opts.open_revs)this._getRevisionTree(id,(function(err3,rev_tree){if(err3)return cb2(err3);leaves=collectLeaves(rev_tree).map((function(leaf){return leaf.rev}));finishOpenRevs()}));else{if(!Array.isArray(opts.open_revs))return cb2(createError(UNKNOWN_ERROR,"function_clause"));leaves=opts.open_revs;for(i2=0;i2<leaves.length;i2++)if(!isValidRev(leaves[i2]))return cb2(createError(INVALID_REV));finishOpenRevs()}})).bind(this);this.getAttachment=adapterFun("getAttachment",(function(docId,attachmentId,opts,callback){if(opts instanceof Function){callback=opts;opts={}}this._get(docId,opts,((err3,res2)=>{if(err3)return callback(err3);if(!res2.doc._attachments||!res2.doc._attachments[attachmentId])return callback(createError(MISSING_DOC));opts.ctx=res2.ctx;opts.binary=!0;opts.metadata=res2.metadata;this._getAttachment(docId,attachmentId,res2.doc._attachments[attachmentId],opts,callback)}))})).bind(this);this.allDocs=adapterFun("allDocs",(function(opts,callback){if("function"==typeof opts){callback=opts;opts={}}opts.skip=void 0!==opts.skip?opts.skip:0;opts.start_key&&(opts.startkey=opts.start_key);opts.end_key&&(opts.endkey=opts.end_key);if("keys"in opts){if(!Array.isArray(opts.keys))return callback(new TypeError("options.keys must be an array"));var incompatibleOpt=["startkey","endkey","key"].filter((function(incompatibleOpt2){return incompatibleOpt2 in opts}))[0];if(incompatibleOpt){callback(createError(QUERY_PARSE_ERROR,"Query parameter `"+incompatibleOpt+"` is not compatible with multi-get"));return}if(!isRemote(this)){allDocsKeysParse(opts);if(0===opts.keys.length)return this._allDocs({limit:0},callback)}}return this._allDocs(opts,callback)})).bind(this);this.close=adapterFun("close",(function(callback){this._closed=!0;this.emit("closed");return this._close(callback)})).bind(this);this.info=adapterFun("info",(function(callback){this._info(((err3,info3)=>{if(err3)return callback(err3);info3.db_name=info3.db_name||this.name;info3.auto_compaction=!(!this.auto_compaction||isRemote(this));info3.adapter=this.adapter;callback(null,info3)}))})).bind(this);this.id=adapterFun("id",(function(callback){return this._id(callback)})).bind(this);this.bulkDocs=adapterFun("bulkDocs",(function(req,opts,callback){var i2,attachmentError,adapter,ids;if("function"==typeof opts){callback=opts;opts={}}opts=opts||{};Array.isArray(req)&&(req={docs:req});if(!req||!req.docs||!Array.isArray(req.docs))return callback(createError(MISSING_BULK_DOCS));for(i2=0;i2<req.docs.length;++i2){const doc=req.docs[i2];if(isNotSingleDoc(doc))return callback(createError(NOT_AN_OBJECT));if("_rev"in doc&&!isValidRev(doc._rev))return callback(createError(INVALID_REV))}req.docs.forEach((function(doc){doc._attachments&&Object.keys(doc._attachments).forEach((function(name){attachmentError=attachmentError||attachmentNameError(name);doc._attachments[name].content_type||guardedConsole("warn","Attachment",name,"on document",doc._id,"is missing content_type")}))}));if(attachmentError)return callback(createError(BAD_REQUEST,attachmentError));"new_edits"in opts||(opts.new_edits=!("new_edits"in req)||req.new_edits);adapter=this;opts.new_edits||isRemote(adapter)||req.docs.sort(compareByIdThenRev);cleanDocs(req.docs);ids=req.docs.map((function(doc){return doc._id}));this._bulkDocs(req,opts,(function(err3,res2){if(err3)return callback(err3);opts.new_edits||(res2=res2.filter((function(x2){return x2.error})));if(!isRemote(adapter))for(var i3=0,l2=res2.length;i3<l2;i3++)res2[i3].id=res2[i3].id||ids[i3];callback(null,res2)}))})).bind(this);this.registerDependentDatabase=adapterFun("registerDependentDatabase",(function(dependentDb,callback){var depDB,dbOptions=clone2(this.__opts);this.__opts.view_adapter&&(dbOptions.adapter=this.__opts.view_adapter);depDB=new this.constructor(dependentDb,dbOptions);upsert2(this,"_local/_pouch_dependentDbs",(function diffFun(doc){doc.dependentDbs=doc.dependentDbs||{};if(doc.dependentDbs[dependentDb])return!1;doc.dependentDbs[dependentDb]=!0;return doc})).then((function(){callback(null,{db:depDB})})).catch(callback)})).bind(this);this.destroy=adapterFun("destroy",(function(opts,callback){if("function"==typeof opts){callback=opts;opts={}}var usePrefix=!("use_prefix"in this)||this.use_prefix;const destroyDb=()=>{this._destroy(opts,((err3,resp)=>{if(err3)return callback(err3);this._destroyed=!0;this.emit("destroyed");callback(null,resp||{ok:!0})}))};if(isRemote(this))return destroyDb();this.get("_local/_pouch_dependentDbs",((err3,localDoc)=>{var dependentDbs,PouchDB2,deletedMap;if(err3)return 404!==err3.status?callback(err3):destroyDb();dependentDbs=localDoc.dependentDbs;PouchDB2=this.constructor;deletedMap=Object.keys(dependentDbs).map((name=>{var trueName=usePrefix?name.replace(new RegExp("^"+PouchDB2.prefix),""):name;return new PouchDB2(trueName,this.__opts).destroy()}));Promise.all(deletedMap).then(destroyDb,callback)}))})).bind(this)}_compact(opts,callback){var taskId,changesOpts={return_docs:!1,last_seq:opts.last_seq||0,since:opts.last_seq||0},promises=[],compactedDocs=0;const onChange=row=>{this.activeTasks.update(taskId,{completed_items:++compactedDocs});promises.push(this.compactDocument(row.id,0))},onError=err3=>{this.activeTasks.remove(taskId,err3);callback(err3)},onComplete=resp=>{var lastSeq=resp.last_seq;Promise.all(promises).then((()=>upsert2(this,"_local/compaction",(doc=>{if(!doc.last_seq||doc.last_seq<lastSeq){doc.last_seq=lastSeq;return doc}return!1})))).then((()=>{this.activeTasks.remove(taskId);callback(null,{ok:!0})})).catch(onError)};this.info().then((info3=>{taskId=this.activeTasks.add({name:"database_compaction",total_items:info3.update_seq-changesOpts.last_seq});this.changes(changesOpts).on("change",onChange).on("complete",onComplete).on("error",onError)}))}changes(opts,callback){if("function"==typeof opts){callback=opts;opts={}}(opts=opts||{}).return_docs="return_docs"in opts?opts.return_docs:!opts.live;return new Changes2(this,opts,callback)}type(){return"function"==typeof this._type?this._type():this.adapter}};AbstractPouchDB.prototype.purge=adapterFun("_purge",(function(docId,rev$$1,callback){if(void 0===this._purge)return callback(createError(UNKNOWN_ERROR,"Purge is not implemented in the "+this.adapter+" adapter."));var self3=this;self3._getRevisionTree(docId,((error,revs)=>{if(error)return callback(error);if(!revs)return callback(createError(MISSING_DOC));let path2;try{path2=findPathToLeaf(revs,rev$$1)}catch(error2){return callback(error2.message||error2)}self3._purge(docId,path2,((error2,result)=>{if(error2)return callback(error2);appendPurgeSeq(self3,docId,rev$$1).then((function(){return callback(null,result)}))}))}))}));TaskQueue=class{constructor(){this.isReady=!1;this.failed=!1;this.queue=[]}execute(){var fun;if(this.failed)for(;fun=this.queue.shift();)fun(this.failed);else for(;fun=this.queue.shift();)fun()}fail(err3){this.failed=err3;this.execute()}ready(db){this.isReady=!0;this.db=db;this.execute()}addTask(fun){this.queue.push(fun);this.failed&&this.execute()}};PouchInternal=class extends AbstractPouchDB{constructor(name,opts){super();this._setup(name,opts)}_setup(name,opts){var backend;super._setup();opts=opts||{};if(name&&"object"==typeof name){name=(opts=name).name;delete opts.name}void 0===opts.deterministic_revs&&(opts.deterministic_revs=!0);this.__opts=opts=clone2(opts);this.auto_compaction=opts.auto_compaction;this.purged_infos_limit=opts.purged_infos_limit||1e3;this.prefix=PouchDB.prefix;if("string"!=typeof name)throw new Error("Missing/invalid DB name");backend=parseAdapter((opts.prefix||"")+name,opts);opts.name=backend.name;opts.adapter=opts.adapter||backend.adapter;this.name=name;this._adapter=opts.adapter;PouchDB.emit("debug",["adapter","Picked adapter: ",opts.adapter]);if(!PouchDB.adapters[opts.adapter]||!PouchDB.adapters[opts.adapter].valid())throw new Error("Invalid Adapter: "+opts.adapter);if(opts.view_adapter&&(!PouchDB.adapters[opts.view_adapter]||!PouchDB.adapters[opts.view_adapter].valid()))throw new Error("Invalid View Adapter: "+opts.view_adapter);this.taskqueue=new TaskQueue;this.adapter=opts.adapter;PouchDB.adapters[opts.adapter].call(this,opts,(err3=>{if(err3)return this.taskqueue.fail(err3);prepareForDestruction(this);this.emit("created",this);PouchDB.emit("created",this.name);this.taskqueue.ready(this)}))}};PouchDB=createClass(PouchInternal,(function(name,opts){PouchInternal.prototype._setup.call(this,name,opts)}));ActiveTasks=class{constructor(){this.tasks={}}list(){return Object.values(this.tasks)}add(task){const id=v4_default2();this.tasks[id]={id,name:task.name,total_items:task.total_items,created_at:(new Date).toJSON()};return id}get(id){return this.tasks[id]}remove(id,reason){delete this.tasks[id];return this.tasks}update(id,updatedTask){const task=this.tasks[id];if(void 0!==task){const mergedTask={id:task.id,name:task.name,created_at:task.created_at,total_items:updatedTask.total_items||task.total_items,completed_items:updatedTask.completed_items||task.completed_items,updated_at:(new Date).toJSON()};this.tasks[id]=mergedTask}return this.tasks}};PouchDB.adapters={};PouchDB.preferredAdapters=[];PouchDB.prefix="_pouch_";eventEmitter=new import_events16.default;(function setUpEventEmitter(Pouch){Object.keys(import_events16.default.prototype).forEach((function(key3){"function"==typeof import_events16.default.prototype[key3]&&(Pouch[key3]=eventEmitter[key3].bind(eventEmitter))}));var destructListeners=Pouch._destructionListeners=new Map;Pouch.on("ref",(function onConstructorRef(db){destructListeners.has(db.name)||destructListeners.set(db.name,[]);destructListeners.get(db.name).push(db)}));Pouch.on("unref",(function onConstructorUnref(db){var dbList,pos;if(destructListeners.has(db.name)&&!((pos=(dbList=destructListeners.get(db.name)).indexOf(db))<0)){dbList.splice(pos,1);dbList.length>1?destructListeners.set(db.name,dbList):destructListeners.delete(db.name)}}));Pouch.on("destroyed",(function onConstructorDestroyed(name){if(destructListeners.has(name)){var dbList=destructListeners.get(name);destructListeners.delete(name);dbList.forEach((function(db){db.emit("destroyed",!0)}))}}))})(PouchDB);PouchDB.adapter=function(id,obj,addToPreferredAdapters){if(obj.valid()){PouchDB.adapters[id]=obj;addToPreferredAdapters&&PouchDB.preferredAdapters.push(id)}};PouchDB.plugin=function(obj){if("function"==typeof obj)obj(PouchDB);else{if("object"!=typeof obj||0===Object.keys(obj).length)throw new Error('Invalid plugin: got "'+obj+'", expected an object or a function');Object.keys(obj).forEach((function(id){PouchDB.prototype[id]=obj[id]}))}this.__defaults&&(PouchDB.__defaults=Object.assign({},this.__defaults));return PouchDB};PouchDB.defaults=function(defaultOpts){let PouchWithDefaults=createClass(PouchDB,(function(name,opts){opts=opts||{};if(name&&"object"==typeof name){name=(opts=name).name;delete opts.name}opts=Object.assign({},PouchWithDefaults.__defaults,opts);PouchDB.call(this,name,opts)}));PouchWithDefaults.preferredAdapters=PouchDB.preferredAdapters.slice();Object.keys(PouchDB).forEach((function(key3){key3 in PouchWithDefaults||(PouchWithDefaults[key3]=PouchDB[key3])}));PouchWithDefaults.__defaults=Object.assign({},this.__defaults,defaultOpts);return PouchWithDefaults};PouchDB.fetch=function(url,opts){return f3(url,opts)};PouchDB.prototype.activeTasks=PouchDB.activeTasks=new ActiveTasks;PouchDB.plugin(index_browser_es_default);PouchDB.version="9.0.0";index_es_default=PouchDB;import_vuvuzela=__toESM(require_vuvuzela());reservedWords=toObject(["_id","_rev","_access","_attachments","_deleted","_revisions","_revs_info","_conflicts","_deleted_conflicts","_local_seq","_rev_tree","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats","_removed"]);dataWords=toObject(["_access","_attachments","_replication_id","_replication_state","_replication_state_time","_replication_state_reason","_replication_stats"]);ADAPTER_VERSION=5;DOC_STORE="document-store";BY_SEQ_STORE="by-sequence";ATTACH_STORE="attach-store";ATTACH_AND_SEQ_STORE="attach-seq-store";META_STORE="meta-store";LOCAL_STORE="local-store";DETECT_BLOB_SUPPORT_STORE="detect-blob-support";changesHandler$1=new Changes;running=!1;queue=[];cachedDBs=new Map;openReqList=new Map;IdbPouch.valid=function(){try{return"undefined"!=typeof indexedDB&&"undefined"!=typeof IDBKeyRange}catch(e3){return!1}};index_es_default2=function index2(PouchDB2){PouchDB2.adapter("idb",IdbPouch,!0)};IDB_NULL=Number.MIN_SAFE_INTEGER;IDB_FALSE=Number.MIN_SAFE_INTEGER+1;IDB_TRUE=Number.MIN_SAFE_INTEGER+2;TEST_KEY_INVALID=/^[^a-zA-Z$]|[^a-zA-Z0-9$]+/;TEST_PATH_INVALID=/\\.|(^|\.)[^a-zA-Z$]|[^a-zA-Z0-9$.]+/;KEY_INVALID=new RegExp(TEST_KEY_INVALID.source,"g");PATH_INVALID=new RegExp(TEST_PATH_INVALID.source,"g");SLASH="\\".charCodeAt(0);IS_DOT=".".charCodeAt(0);DOC_STORE2="docs";META_LOCAL_STORE="meta";POUCHDB_IDB_VERSION=2;versionMultiplier=Math.pow(10,13);BINARY_ATTACHMENTS=!1;COUCH_COLLATE_LO=null;COUCH_COLLATE_HI="￿";IDB_COLLATE_LO=Number.NEGATIVE_INFINITY;IDB_COLLATE_HI=[[[[[[[[[[[[]]]]]]]]]]]];ADAPTER_NAME="indexeddb";idbChanges=new Changes;openDatabases={};IndexeddbPouch.valid=function(){return!0};index_es_default3=function index3(PouchDB2){PouchDB2.adapter(ADAPTER_NAME,IndexeddbPouch,!0)};CHANGES_BATCH_SIZE=25;MAX_SIMULTANEOUS_REVS=50;CHANGES_TIMEOUT_BUFFER=5e3;DEFAULT_HEARTBEAT=1e4;supportsBulkGetMap={};HttpPouch.valid=function(){return!0};index_es_default4=function index4(PouchDB2){PouchDB2.adapter("http",HttpPouch,!1);PouchDB2.adapter("https",HttpPouch,!1)};QueryParseError=class _QueryParseError extends Error{constructor(message){super();this.status=400;this.name="query_parse_error";this.message=message;this.error=!0;try{Error.captureStackTrace(this,_QueryParseError)}catch(e3){}}};NotFoundError=class _NotFoundError extends Error{constructor(message){super();this.status=404;this.name="not_found";this.message=message;this.error=!0;try{Error.captureStackTrace(this,_NotFoundError)}catch(e3){}}};BuiltInError=class _BuiltInError extends Error{constructor(message){super();this.status=500;this.name="invalid_value";this.message=message;this.error=!0;try{Error.captureStackTrace(this,_BuiltInError)}catch(e3){}}};persistentQueues={};tempViewQueue=new(TaskQueue2=class{constructor(){this.promise=Promise.resolve()}add(promiseFactory){this.promise=this.promise.catch((()=>{})).then((()=>promiseFactory()));return this.promise}finish(){return this.promise}});index_es_default5=function createAbstractMapReduce(localDocName2,mapper3,reducer3,ddocValidator3){function tryMap(db,fun,doc){try{fun(doc)}catch(e3){emitError(db,e3,{fun,doc})}}function tryReduce(db,fun,keys3,values,rereduce){try{return{output:fun(keys3,values,rereduce)}}catch(e3){emitError(db,e3,{fun,keys:keys3,values,rereduce});return{error:e3}}}function sortByKeyThenValue(x2,y2){const keyCompare=collate(x2.key,y2.key);return 0!==keyCompare?keyCompare:collate(x2.value,y2.value)}function sliceResults(results,limit,skip){skip=skip||0;return"number"==typeof limit?results.slice(skip,limit+skip):skip>0?results.slice(skip):results}function rowToDocId(row){const val2=row.value;return val2&&"object"==typeof val2&&val2._id||row.id}function readAttachmentsAsBlobOrBuffer2(res2){for(const row of res2.rows){const atts=row.doc&&row.doc._attachments;if(atts)for(const filename of Object.keys(atts)){const att=atts[filename];atts[filename].data=b64ToBluffer(att.data,att.content_type)}}}function postprocessAttachments(opts){return function(res2){opts.include_docs&&opts.attachments&&opts.binary&&readAttachmentsAsBlobOrBuffer2(res2);return res2}}function addHttpParam(paramName,opts,params,asJson){let val2=opts[paramName];if(void 0!==val2){asJson&&(val2=encodeURIComponent(JSON.stringify(val2)));params.push(paramName+"="+val2)}}function coerceInteger(integerCandidate){if(void 0!==integerCandidate){const asNumber=Number(integerCandidate);return isNaN(asNumber)||asNumber!==parseInt(integerCandidate,10)?integerCandidate:asNumber}}function coerceOptions(opts){opts.group_level=coerceInteger(opts.group_level);opts.limit=coerceInteger(opts.limit);opts.skip=coerceInteger(opts.skip);return opts}function checkPositiveInteger(number){if(number){if("number"!=typeof number)return new QueryParseError(`Invalid value for integer: "${number}"`);if(number<0)return new QueryParseError(`Invalid value for positive integer: "${number}"`)}}function checkQueryParseError(options,fun){const startkeyName=options.descending?"endkey":"startkey",endkeyName=options.descending?"startkey":"endkey";if(void 0!==options[startkeyName]&&void 0!==options[endkeyName]&&collate(options[startkeyName],options[endkeyName])>0)throw new QueryParseError("No rows can match your key range, reverse your start_key and end_key or set {descending : true}");if(fun.reduce&&!1!==options.reduce){if(options.include_docs)throw new QueryParseError("{include_docs:true} is invalid for reduce");if(options.keys&&options.keys.length>1&&!options.group&&!options.group_level)throw new QueryParseError("Multi-key fetches for reduce views must use {group: true}")}for(const optionName of["group_level","limit","skip"]){const error=checkPositiveInteger(options[optionName]);if(error)throw error}}async function httpQuery(db,fun,opts){let body,ok,params=[],method="GET";addHttpParam("reduce",opts,params);addHttpParam("include_docs",opts,params);addHttpParam("attachments",opts,params);addHttpParam("limit",opts,params);addHttpParam("descending",opts,params);addHttpParam("group",opts,params);addHttpParam("group_level",opts,params);addHttpParam("skip",opts,params);addHttpParam("stale",opts,params);addHttpParam("conflicts",opts,params);addHttpParam("startkey",opts,params,!0);addHttpParam("start_key",opts,params,!0);addHttpParam("endkey",opts,params,!0);addHttpParam("end_key",opts,params,!0);addHttpParam("inclusive_end",opts,params);addHttpParam("key",opts,params,!0);addHttpParam("update_seq",opts,params);params=params.join("&");params=""===params?"":"?"+params;if(void 0!==opts.keys){const MAX_URL_LENGTH=2e3,keysAsString=`keys=${encodeURIComponent(JSON.stringify(opts.keys))}`;if(keysAsString.length+params.length+1<=MAX_URL_LENGTH)params+=("?"===params[0]?"&":"?")+keysAsString;else{method="POST";"string"==typeof fun?body={keys:opts.keys}:fun.keys=opts.keys}}if("string"==typeof fun){const parts=parseViewName(fun),response2=await db.fetch("_design/"+parts[0]+"/_view/"+parts[1]+params,{headers:new h2({"Content-Type":"application/json"}),method,body:JSON.stringify(body)});ok=response2.ok;const result2=await response2.json();if(!ok){result2.status=response2.status;throw generateErrorFromResponse(result2)}for(const row of result2.rows)if(row.value&&row.value.error&&"builtin_reduce_error"===row.value.error)throw new Error(row.reason);return new Promise((function(resolve){resolve(result2)})).then(postprocessAttachments(opts))}body=body||{};for(const key3 of Object.keys(fun))Array.isArray(fun[key3])?body[key3]=fun[key3]:body[key3]=fun[key3].toString();const response=await db.fetch("_temp_view"+params,{headers:new h2({"Content-Type":"application/json"}),method:"POST",body:JSON.stringify(body)});ok=response.ok;const result=await response.json();if(!ok){result.status=response.status;throw generateErrorFromResponse(result)}return new Promise((function(resolve){resolve(result)})).then(postprocessAttachments(opts))}function customQuery(db,fun,opts){return new Promise((function(resolve,reject){db._query(fun,opts,(function(err3,res2){if(err3)return reject(err3);resolve(res2)}))}))}function customViewCleanup(db){return new Promise((function(resolve,reject){db._viewCleanup((function(err3,res2){if(err3)return reject(err3);resolve(res2)}))}))}function defaultsTo(value){return function(reason){if(404===reason.status)return value;throw reason}}async function getDocsToPersist(docId,view,docIdsToChangesAndEmits){const metaDocId="_local/doc_"+docId,defaultMetaDoc={_id:metaDocId,keys:[]},docData=docIdsToChangesAndEmits.get(docId),indexableKeysToKeyValues=docData[0],changes3=docData[1],metaDoc=await function getMetaDoc(){return isGenOne(changes3)?Promise.resolve(defaultMetaDoc):view.db.get(metaDocId).catch(defaultsTo(defaultMetaDoc))}();return function processKeyValueDocs(metaDoc2,kvDocsRes){const kvDocs=[],oldKeys=new Set;for(const row of kvDocsRes.rows){const doc=row.doc;if(doc){kvDocs.push(doc);oldKeys.add(doc._id);doc._deleted=!indexableKeysToKeyValues.has(doc._id);if(!doc._deleted){const keyValue=indexableKeysToKeyValues.get(doc._id);"value"in keyValue&&(doc.value=keyValue.value)}}}const newKeys=mapToKeysArray(indexableKeysToKeyValues);for(const key3 of newKeys)if(!oldKeys.has(key3)){const kvDoc={_id:key3},keyValue=indexableKeysToKeyValues.get(key3);"value"in keyValue&&(kvDoc.value=keyValue.value);kvDocs.push(kvDoc)}metaDoc2.keys=uniq(newKeys.concat(metaDoc2.keys));kvDocs.push(metaDoc2);return kvDocs}(metaDoc,await function getKeyValueDocs(metaDoc2){return metaDoc2.keys.length?view.db.allDocs({keys:metaDoc2.keys,include_docs:!0}):Promise.resolve({rows:[]})}(metaDoc))}function updatePurgeSeq(view){return view.sourceDB.get("_local/purges").then((function(res2){const purgeSeq=res2.purgeSeq;return view.db.get("_local/purgeSeq").then((function(res3){return res3._rev})).catch(defaultsTo(void 0)).then((function(rev3){return view.db.put({_id:"_local/purgeSeq",_rev:rev3,purgeSeq})}))})).catch((function(err3){if(404!==err3.status)throw err3}))}function saveKeyValues(view,docIdsToChangesAndEmits,seq){return view.db.get("_local/lastSeq").catch(defaultsTo({_id:"_local/lastSeq",seq:0})).then((function(lastSeqDoc){var docIds=mapToKeysArray(docIdsToChangesAndEmits);return Promise.all(docIds.map((function(docId){return getDocsToPersist(docId,view,docIdsToChangesAndEmits)}))).then((function(listOfDocsToPersist){var docsToPersist=listOfDocsToPersist.flat();lastSeqDoc.seq=seq;docsToPersist.push(lastSeqDoc);return view.db.bulkDocs({docs:docsToPersist})})).then((()=>updatePurgeSeq(view)))}))}function getQueue(view){const viewName="string"==typeof view?view:view.name;let queue2=persistentQueues[viewName];queue2||(queue2=persistentQueues[viewName]=new TaskQueue2);return queue2}async function updateView(view,opts){return sequentialize(getQueue(view),(function(){return updateViewInQueue(view,opts)}))()}async function updateViewInQueue(view,opts){function processChange2(docIdsToChangesAndEmits,seq){return function(){return saveKeyValues(view,docIdsToChangesAndEmits,seq)}}async function processNextBatch(){return processBatch(await view.sourceDB.changes({return_docs:!0,conflicts:!0,include_docs:!0,style:"all_docs",since:currentSeq,limit:opts.changes_batch_size}),await getRecentPurges())}function getRecentPurges(){return view.db.get("_local/purgeSeq").then((function(res2){return res2.purgeSeq})).catch(defaultsTo(-1)).then((function(purgeSeq){return view.sourceDB.get("_local/purges").then((function(res2){const recentPurges=res2.purges.filter((function(purge2,index6){return index6>purgeSeq})).map((purge2=>purge2.docId)),uniquePurges=recentPurges.filter((function(docId,index6){return recentPurges.indexOf(docId)===index6}));return Promise.all(uniquePurges.map((function(docId){return view.sourceDB.get(docId).then((function(doc2){return{docId,doc:doc2}})).catch(defaultsTo({docId}))})))})).catch(defaultsTo([]))}))}function processBatch(response,purges){const results=response.results;if(!results.length&&!purges.length)return;for(const purge2 of purges)if(results.findIndex((function(change){return change.id===purge2.docId}))<0){const entry={_id:purge2.docId,doc:{_id:purge2.docId,_deleted:1},changes:[]};if(purge2.doc){entry.doc=purge2.doc;entry.changes.push({rev:purge2.doc._rev})}results.push(entry)}const docIdsToChangesAndEmits=createDocIdsToChangesAndEmits(results);queue2.add(processChange2(docIdsToChangesAndEmits,currentSeq));indexed_docs+=results.length;const progress2={view:view.name,last_seq:response.last_seq,results_count:results.length,indexed_docs};view.sourceDB.emit("indexing",progress2);view.sourceDB.activeTasks.update(taskId,{completed_items:indexed_docs});return results.length<opts.changes_batch_size?void 0:processNextBatch()}function createDocIdsToChangesAndEmits(results){const docIdsToChangesAndEmits=new Map;for(const change of results){if("_"!==change.doc._id[0]){mapResults=[];doc=change.doc;doc._deleted||tryMap(view.sourceDB,mapFun,doc);mapResults.sort(sortByKeyThenValue);const indexableKeysToKeyValues=createIndexableKeysToKeyValues(mapResults);docIdsToChangesAndEmits.set(change.doc._id,[indexableKeysToKeyValues,change.changes])}currentSeq=change.seq}return docIdsToChangesAndEmits}function createIndexableKeysToKeyValues(mapResults2){const indexableKeysToKeyValues=new Map;let lastKey;for(let i2=0,len=mapResults2.length;i2<len;i2++){const emittedKeyValue=mapResults2[i2],complexKey=[emittedKeyValue.key,emittedKeyValue.id];i2>0&&0===collate(emittedKeyValue.key,lastKey)&&complexKey.push(i2);indexableKeysToKeyValues.set(toIndexableString(complexKey),emittedKeyValue);lastKey=emittedKeyValue.key}return indexableKeysToKeyValues}let mapResults,doc,taskId;const mapFun=mapper3(view.mapFun,(function emit2(key3,value){const output={id:doc._id,key:normalizeKey(key3)};null!=value&&(output.value=normalizeKey(value));mapResults.push(output)}));let currentSeq=view.seq||0,indexed_docs=0;const progress={view:view.name,indexed_docs};view.sourceDB.emit("indexing",progress);const queue2=new TaskQueue2;try{await function createTask(){return view.sourceDB.info().then((function(info3){taskId=view.sourceDB.activeTasks.add({name:"view_indexing",total_items:info3.update_seq-currentSeq})}))}();await processNextBatch();await queue2.finish();view.seq=currentSeq;view.sourceDB.activeTasks.remove(taskId)}catch(error){view.sourceDB.activeTasks.remove(taskId,error)}}function reduceView(view,results,options){0===options.group_level&&delete options.group_level;const shouldGroup=options.group||options.group_level,reduceFun=reducer3(view.reduceFun),groups=[],lvl=isNaN(options.group_level)?Number.POSITIVE_INFINITY:options.group_level;for(const result of results){const last=groups[groups.length-1];let groupKey=shouldGroup?result.key:null;shouldGroup&&Array.isArray(groupKey)&&(groupKey=groupKey.slice(0,lvl));if(last&&0===collate(last.groupKey,groupKey)){last.keys.push([result.key,result.id]);last.values.push(result.value)}else groups.push({keys:[[result.key,result.id]],values:[result.value],groupKey})}results=[];for(const group of groups){const reduceTry=tryReduce(view.sourceDB,reduceFun,group.keys,group.values,!1);if(reduceTry.error&&reduceTry.error instanceof BuiltInError)throw reduceTry.error;results.push({value:reduceTry.error?null:reduceTry.output,key:group.groupKey})}return{rows:sliceResults(results,options.limit,options.skip)}}function queryView(view,opts){return sequentialize(getQueue(view),(function(){return queryViewInQueue(view,opts)}))()}async function queryViewInQueue(view,opts){async function fetchFromView(viewOpts){viewOpts.include_docs=!0;const res2=await view.db.allDocs(viewOpts);totalRows=res2.total_rows;return res2.rows.map((function(result){if("value"in result.doc&&"object"==typeof result.doc.value&&null!==result.doc.value){const keys3=Object.keys(result.doc.value).sort(),expectedKeys=["id","key","value"];if(!(keys3<expectedKeys||keys3>expectedKeys))return result.doc.value}const parsedKeyAndDocId=parseIndexableString(result.doc._id);return{key:parsedKeyAndDocId[0],id:parsedKeyAndDocId[1],value:"value"in result.doc?result.doc.value:null}}))}async function onMapResultsReady(rows){let finalResults;finalResults=shouldReduce?reduceView(view,rows,opts):void 0===opts.keys?{total_rows:totalRows,offset:skip,rows}:{total_rows:totalRows,offset:skip,rows:sliceResults(rows,opts.limit,opts.skip)};opts.update_seq&&(finalResults.update_seq=view.seq);if(opts.include_docs){const docIds=uniq(rows.map(rowToDocId)),allDocsRes=await view.sourceDB.allDocs({keys:docIds,include_docs:!0,conflicts:opts.conflicts,attachments:opts.attachments,binary:opts.binary}),docIdsToDocs=new Map;for(const row of allDocsRes.rows)docIdsToDocs.set(row.id,row.doc);for(const row of rows){const docId=rowToDocId(row),doc=docIdsToDocs.get(docId);doc&&(row.doc=doc)}}return finalResults}let totalRows;const shouldReduce=view.reduceFun&&!1!==opts.reduce,skip=opts.skip||0;if(void 0!==opts.keys&&!opts.keys.length){opts.limit=0;delete opts.keys}if(void 0!==opts.keys){const fetchPromises=opts.keys.map((function(key3){const viewOpts={startkey:toIndexableString([key3]),endkey:toIndexableString([key3,{}])};opts.update_seq&&(viewOpts.update_seq=!0);return fetchFromView(viewOpts)}));return onMapResultsReady((await Promise.all(fetchPromises)).flat())}{const viewOpts={descending:opts.descending};opts.update_seq&&(viewOpts.update_seq=!0);let startkey,endkey;"start_key"in opts&&(startkey=opts.start_key);"startkey"in opts&&(startkey=opts.startkey);"end_key"in opts&&(endkey=opts.end_key);"endkey"in opts&&(endkey=opts.endkey);void 0!==startkey&&(viewOpts.startkey=opts.descending?toIndexableString([startkey,{}]):toIndexableString([startkey]));if(void 0!==endkey){let inclusiveEnd=!1!==opts.inclusive_end;opts.descending&&(inclusiveEnd=!inclusiveEnd);viewOpts.endkey=toIndexableString(inclusiveEnd?[endkey,{}]:[endkey])}if(void 0!==opts.key){const keyStart=toIndexableString([opts.key]),keyEnd=toIndexableString([opts.key,{}]);if(viewOpts.descending){viewOpts.endkey=keyStart;viewOpts.startkey=keyEnd}else{viewOpts.startkey=keyStart;viewOpts.endkey=keyEnd}}if(!shouldReduce){"number"==typeof opts.limit&&(viewOpts.limit=opts.limit);viewOpts.skip=skip}return onMapResultsReady(await fetchFromView(viewOpts))}}async function httpViewCleanup(db){return(await db.fetch("_view_cleanup",{headers:new h2({"Content-Type":"application/json"}),method:"POST"})).json()}async function localViewCleanup(db){try{const metaDoc=await db.get("_local/"+localDocName2),docsToViews=new Map;for(const fullViewName of Object.keys(metaDoc.views)){const parts=parseViewName(fullViewName),designDocName="_design/"+parts[0],viewName=parts[1];let views=docsToViews.get(designDocName);if(!views){views=new Set;docsToViews.set(designDocName,views)}views.add(viewName)}const opts={keys:mapToKeysArray(docsToViews),include_docs:!0},res2=await db.allDocs(opts),viewsToStatus={};for(const row of res2.rows){const ddocName=row.key.substring(8);for(const viewName of docsToViews.get(row.key)){let fullViewName=ddocName+"/"+viewName;metaDoc.views[fullViewName]||(fullViewName=viewName);const viewDBNames=Object.keys(metaDoc.views[fullViewName]),statusIsGood=row.doc&&row.doc.views&&row.doc.views[viewName];for(const viewDBName of viewDBNames)viewsToStatus[viewDBName]=viewsToStatus[viewDBName]||statusIsGood}}const destroyPromises=Object.keys(viewsToStatus).filter((function(viewDBName){return!viewsToStatus[viewDBName]})).map((function(viewDBName){return sequentialize(getQueue(viewDBName),(function(){return new db.constructor(viewDBName,db.__opts).destroy()}))()}));return Promise.all(destroyPromises).then((function(){return{ok:!0}}))}catch(err3){if(404===err3.status)return{ok:!0};throw err3}}async function queryPromised(db,fun,opts){if("function"==typeof db._query)return customQuery(db,fun,opts);if(isRemote(db))return httpQuery(db,fun,opts);const updateViewOpts={changes_batch_size:db.__opts.view_update_changes_batch_size||50};if("string"!=typeof fun){checkQueryParseError(opts,fun);tempViewQueue.add((async function(){const view=await createView(db,"temp_view/temp_view",fun.map,fun.reduce,!0,localDocName2);return fin(updateView(view,updateViewOpts).then((function(){return queryView(view,opts)})),(function(){return view.db.destroy()}))}));return tempViewQueue.finish()}{const fullViewName=fun,parts=parseViewName(fullViewName),designDocName=parts[0],viewName=parts[1],doc=await db.get("_design/"+designDocName);if(!(fun=doc.views&&doc.views[viewName]))throw new NotFoundError(`ddoc ${doc._id} has no view named ${viewName}`);ddocValidator3(doc,viewName);checkQueryParseError(opts,fun);const view=await createView(db,fullViewName,fun.map,fun.reduce,!1,localDocName2);if("ok"===opts.stale||"update_after"===opts.stale){"update_after"===opts.stale&&nextTick((function(){updateView(view,updateViewOpts)}));return queryView(view,opts)}await updateView(view,updateViewOpts);return queryView(view,opts)}}return{query:function abstractQuery(fun,opts,callback){const db=this;if("function"==typeof opts){callback=opts;opts={}}opts=opts?coerceOptions(opts):{};"function"==typeof fun&&(fun={map:fun});const promise=Promise.resolve().then((function(){return queryPromised(db,fun,opts)}));promisedCallback(promise,callback);return promise},viewCleanup:callbackify((function(){const db=this;return"function"==typeof db._viewCleanup?customViewCleanup(db):isRemote(db)?httpViewCleanup(db):localViewCleanup(db)}))}};log=guardedConsole.bind(null,"log");isArray=Array.isArray;toJSON=JSON.parse;builtInReduce__sum=function(keys3,values){return sum(values)},builtInReduce__count=function(keys3,values){return values.length},builtInReduce__stats=function(keys3,values){return{sum:sum(values),min:Math.min.apply(null,values),max:Math.max.apply(null,values),count:values.length,sumsqr:function sumsqr(values2){var i2,len,num,_sumsqr=0;for(i2=0,len=values2.length;i2<len;i2++)_sumsqr+=(num=values2[i2])*num;return _sumsqr}(values)}};abstract=index_es_default5("mrviews",(function mapper(mapFun,emit2){if("function"==typeof mapFun&&2===mapFun.length){var origMap=mapFun;return function(doc){return origMap(doc,emit2)}}return evalFunctionWithEval(mapFun.toString(),emit2)}),(function reducer(reduceFun){var reduceFunString=reduceFun.toString();return getBuiltIn(reduceFunString)||evalFunctionWithEval(reduceFunString)}),(function ddocValidator(ddoc,viewName){var fun=ddoc.views&&ddoc.views[viewName];if("string"!=typeof fun.map)throw new NotFoundError("ddoc "+ddoc._id+" has no string view named "+viewName+", instead found object of type: "+typeof fun.map)}));index_browser_es_default2={query:function query2(fun,opts,callback){return abstract.query.call(this,fun,opts,callback)},viewCleanup:function viewCleanup2(callback){return abstract.viewCleanup.call(this,callback)}};CHECKPOINT_VERSION=1;REPLICATOR="pouchdb";CHECKPOINT_HISTORY_SIZE=5;LOWEST_SEQ=0;CheckpointerInternal=class{constructor(src,target,id,returnValue,opts={writeSourceCheckpoint:!0,writeTargetCheckpoint:!0}){this.src=src;this.target=target;this.id=id;this.returnValue=returnValue;this.opts=opts;void 0===opts.writeSourceCheckpoint&&(opts.writeSourceCheckpoint=!0);void 0===opts.writeTargetCheckpoint&&(opts.writeTargetCheckpoint=!0)}writeCheckpoint(checkpoint,session){var self3=this;return this.updateTarget(checkpoint,session).then((function(){return self3.updateSource(checkpoint,session)}))}updateTarget(checkpoint,session){return this.opts.writeTargetCheckpoint?updateCheckpoint(this.target,this.id,checkpoint,session,this.returnValue):Promise.resolve(!0)}updateSource(checkpoint,session){if(this.opts.writeSourceCheckpoint){var self3=this;return updateCheckpoint(this.src,this.id,checkpoint,session,this.returnValue).catch((function(err3){if(isForbiddenError(err3)){self3.opts.writeSourceCheckpoint=!1;return!0}throw err3}))}return Promise.resolve(!0)}getCheckpoint(){var self3=this;return self3.opts.writeSourceCheckpoint||self3.opts.writeTargetCheckpoint?self3.opts&&self3.opts.writeSourceCheckpoint&&!self3.opts.writeTargetCheckpoint?self3.src.get(self3.id).then((function(sourceDoc){return sourceDoc.last_seq||LOWEST_SEQ})).catch((function(err3){if(404!==err3.status)throw err3;return LOWEST_SEQ})):self3.target.get(self3.id).then((function(targetDoc){return self3.opts&&self3.opts.writeTargetCheckpoint&&!self3.opts.writeSourceCheckpoint?targetDoc.last_seq||LOWEST_SEQ:self3.src.get(self3.id).then((function(sourceDoc){return targetDoc.version!==sourceDoc.version?LOWEST_SEQ:(version2=targetDoc.version?targetDoc.version.toString():"undefined")in comparisons?comparisons[version2](targetDoc,sourceDoc):LOWEST_SEQ;var version2}),(function(err3){if(404===err3.status&&targetDoc.last_seq)return self3.src.put({_id:self3.id,last_seq:LOWEST_SEQ}).then((function(){return LOWEST_SEQ}),(function(err4){if(isForbiddenError(err4)){self3.opts.writeSourceCheckpoint=!1;return targetDoc.last_seq}return LOWEST_SEQ}));throw err3}))})).catch((function(err3){if(404!==err3.status)throw err3;return LOWEST_SEQ})):Promise.resolve(LOWEST_SEQ)}};comparisons={undefined:function(targetDoc,sourceDoc){return 0===collate(targetDoc.last_seq,sourceDoc.last_seq)?sourceDoc.last_seq:0},1:function(targetDoc,sourceDoc){return compareReplicationLogs(sourceDoc,targetDoc).last_seq}};index_es_default6=function Checkpointer(src,target,id,returnValue,opts){return this instanceof CheckpointerInternal?Checkpointer:new CheckpointerInternal(src,target,id,returnValue,opts)};index_es_default7=function generateReplicationId(src,target,opts){var docIds=opts.doc_ids?opts.doc_ids.sort(collate):"",filterFun=opts.filter?opts.filter.toString():"",queryParams="",filterViewName="",selector="";opts.selector&&(selector=JSON.stringify(opts.selector));opts.filter&&opts.query_params&&(queryParams=JSON.stringify(sortObjectPropertiesByKey(opts.query_params)));opts.filter&&"_view"===opts.filter&&(filterViewName=opts.view.toString());return Promise.all([src.id(),target.id()]).then((function(res2){var queryData=res2[0]+res2[1]+filterFun+filterViewName+queryParams+docIds+selector;return new Promise((function(resolve){binaryMd5(queryData,resolve)}))})).then((function(md5sum){return"_local/"+md5sum.replace(/\//g,".").replace(/\+/g,"_")}))};import_events17=__toESM(require_events());STARTING_BACK_OFF=0;Replication=class extends import_events17.default{constructor(){super();this.cancelled=!1;this.state="pending";const promise=new Promise(((fulfill,reject)=>{this.once("complete",fulfill);this.once("error",reject)}));this.then=function(resolve,reject){return promise.then(resolve,reject)};this.catch=function(reject){return promise.catch(reject)};this.catch((function(){}))}cancel(){this.cancelled=!0;this.state="cancelled";this.emit("cancel")}ready(src,target){function cleanup(){src.removeListener("destroyed",onDestroy2);target.removeListener("destroyed",onDestroy2)}if(this._readyCalled)return;this._readyCalled=!0;const onDestroy2=()=>{this.cancel()};src.once("destroyed",onDestroy2);target.once("destroyed",onDestroy2);this.once("complete",cleanup);this.once("error",cleanup)}};Sync=class extends import_events17.default{constructor(src,target,opts,callback){function addOneListener(ee,event2,listener){-1==ee.listeners(event2).indexOf(listener)&&ee.on(event2,listener)}super();this.canceled=!1;const optsPush=opts.push?Object.assign({},opts,opts.push):opts,optsPull=opts.pull?Object.assign({},opts,opts.pull):opts;this.push=replicateWrapper(src,target,optsPush);this.pull=replicateWrapper(target,src,optsPull);this.pushPaused=!0;this.pullPaused=!0;const pullChange=change=>{this.emit("change",{direction:"pull",change})},pushChange=change=>{this.emit("change",{direction:"push",change})},pushDenied=doc=>{this.emit("denied",{direction:"push",doc})},pullDenied=doc=>{this.emit("denied",{direction:"pull",doc})},pushPaused=()=>{this.pushPaused=!0;this.pullPaused&&this.emit("paused")},pullPaused=()=>{this.pullPaused=!0;this.pushPaused&&this.emit("paused")},pushActive=()=>{this.pushPaused=!1;this.pullPaused&&this.emit("active",{direction:"push"})},pullActive=()=>{this.pullPaused=!1;this.pushPaused&&this.emit("active",{direction:"pull"})};let removed={};const removeAll=type=>(event2,func)=>{if("change"===event2&&(func===pullChange||func===pushChange)||"denied"===event2&&(func===pullDenied||func===pushDenied)||"paused"===event2&&(func===pullPaused||func===pushPaused)||"active"===event2&&(func===pullActive||func===pushActive)){event2 in removed||(removed[event2]={});removed[event2][type]=!0;2===Object.keys(removed[event2]).length&&this.removeAllListeners(event2)}};if(opts.live){this.push.on("complete",this.pull.cancel.bind(this.pull));this.pull.on("complete",this.push.cancel.bind(this.push))}this.on("newListener",(function(event2){if("change"===event2){addOneListener(this.pull,"change",pullChange);addOneListener(this.push,"change",pushChange)}else if("denied"===event2){addOneListener(this.pull,"denied",pullDenied);addOneListener(this.push,"denied",pushDenied)}else if("active"===event2){addOneListener(this.pull,"active",pullActive);addOneListener(this.push,"active",pushActive)}else if("paused"===event2){addOneListener(this.pull,"paused",pullPaused);addOneListener(this.push,"paused",pushPaused)}}));this.on("removeListener",(function(event2){if("change"===event2){this.pull.removeListener("change",pullChange);this.push.removeListener("change",pushChange)}else if("denied"===event2){this.pull.removeListener("denied",pullDenied);this.push.removeListener("denied",pushDenied)}else if("active"===event2){this.pull.removeListener("active",pullActive);this.push.removeListener("active",pushActive)}else if("paused"===event2){this.pull.removeListener("paused",pullPaused);this.push.removeListener("paused",pushPaused)}}));this.pull.on("removeListener",removeAll("pull"));this.push.on("removeListener",removeAll("push"));const promise=Promise.all([this.push,this.pull]).then((resp=>{const out={push:resp[0],pull:resp[1]};this.emit("complete",out);callback&&callback(null,out);this.removeAllListeners();return out}),(err3=>{this.cancel();callback?callback(err3):this.emit("error",err3);this.removeAllListeners();if(callback)throw err3}));this.then=function(success,err3){return promise.then(success,err3)};this.catch=function(err3){return promise.catch(err3)}}cancel(){if(!this.canceled){this.canceled=!0;this.push.cancel();this.pull.cancel()}}};index_es_default8=function replication(PouchDB2){PouchDB2.replicate=replicateWrapper;PouchDB2.sync=sync;Object.defineProperty(PouchDB2.prototype,"replicate",{get:function(){var self3=this;void 0===this.replicateMethods&&(this.replicateMethods={from:function(other,opts,callback){return self3.constructor.replicate(other,self3,opts,callback)},to:function(other,opts,callback){return self3.constructor.replicate(self3,other,opts,callback)}});return this.replicateMethods}});PouchDB2.prototype.sync=function(dbName,opts,callback){return this.constructor.sync(this,dbName,opts,callback)}};nativeFlat=(...args)=>args.flat(1/0);polyFlat=(...args)=>{let res2=[];for(const subArr of args)Array.isArray(subArr)?res2=res2.concat(polyFlat(...subArr)):res2.push(subArr);return res2};flatten2="function"==typeof Array.prototype.flat?nativeFlat:polyFlat;requireValidation=["$all","$allMatch","$and","$elemMatch","$exists","$in","$mod","$nin","$nor","$not","$or","$regex","$size","$type"];arrayTypeComparisonOperators=["$in","$nin","$mod","$all"];equalityOperators=["$eq","$gt","$gte","$lt","$lte"];abstractMapper=index_es_default5("indexes",(function mapper2(mapFunDef,emit2){return createMapper(Object.keys(mapFunDef.fields),emit2,mapFunDef.partial_filter_selector)}),(function reducer2(){throw new Error("reduce not supported")}),(function ddocValidator2(ddoc,viewName){const view=ddoc.views[viewName];if(!view.map||!view.map.fields)throw new Error("ddoc "+ddoc._id+" with view "+viewName+" doesn't have map.fields defined. maybe it wasn't created by this plugin?")}));ddocIdPrefix=/^_design\//;SHORT_CIRCUIT_QUERY={queryOpts:{limit:0,startkey:COLLATE_HI={"￿":{}},endkey:COLLATE_LO=null},inMemoryFields:[]};logicalMatchers=["$eq","$gt","$gte","$lt","$lte"];(plugin2={}).createIndex=resolveToCallback((async function(requestDef){if("object"!=typeof requestDef)throw new Error("you must provide an index to create");return(isRemote(this)?createIndex:createIndex$1)(this,requestDef)}));plugin2.find=resolveToCallback((async function(requestDef){if("object"!=typeof requestDef)throw new Error("you must provide search parameters to find()");return(isRemote(this)?find:find$1)(this,requestDef)}));plugin2.explain=resolveToCallback((async function(requestDef){if("object"!=typeof requestDef)throw new Error("you must provide search parameters to explain()");return(isRemote(this)?explain:explain$1)(this,requestDef)}));plugin2.getIndexes=resolveToCallback((async function(){return(isRemote(this)?getIndexes:getIndexes$1)(this)}));plugin2.deleteIndex=resolveToCallback((async function(indexDef){if("object"!=typeof indexDef)throw new Error("you must provide an index to delete");return(isRemote(this)?deleteIndex:deleteIndex$1)(this,indexDef)}));index_browser_es_default3=plugin2;import_transform_pouch=__toESM(require_transform_pouch(),1);index_es_default.plugin(index_es_default2).plugin(index_es_default3).plugin(index_es_default4).plugin(index_browser_es_default2).plugin(index_es_default8).plugin(index_browser_es_default3).plugin(import_transform_pouch.default);index_es_default.prototype.purgeMulti=adapterFun("_purgeMulti",(function(docs,callback){if(void 0===this._purge)return callback(createError(UNKNOWN_ERROR,"Purge is not implemented in the "+this.adapter+" adapter."));const self3=this,tasks3=docs.map((param=>()=>new Promise(((res2,rej)=>{const[docId,rev$$1]=param;self3._getRevisionTree(docId,((error,revs)=>{if(error)return res2([param,error]);if(!revs)return res2([param,createError(MISSING_DOC)]);let path2;try{path2=findPathToLeaf(revs,rev$$1)}catch(error2){return res2([param,error2.message||error2])}self3._purge(docId,path2,((error2,result)=>res2(error2?[param,error2]:[param,result])))}))}))));(async()=>{const retAll=(await mapAllTasksWithConcurrencyLimit(1,tasks3)).map((e3=>unwrapTaskResult(e3)));await appendPurgeSeqs(self3,retAll.filter((e3=>"ok"in e3[1])).map((e3=>e3[0])));return Object.fromEntries(retAll.map((e3=>[e3[0][0],e3[1]])))})().then((result=>callback(void 0,result))).catch((error=>callback(error)))}));root_214=from_html('<input type="checkbox" name="p2p-enabled"/>');on_click3=(_,setDefaultRelay)=>setDefaultRelay();root_34=from_html('<input type="text" name="p2p-relay-url" placeholder="Enter the Relay URL)" autocorrect="off" autocapitalize="off" spellcheck="false"/> <button class="button">Use vrtmrz\'s relay</button>',1);on_click_1=(__1,generateDefaultGroupId)=>generateDefaultGroupId();root_411=from_html('<input type="text" name="p2p-room-id" placeholder="123-456-789-abc" autocorrect="off" autocapitalize="off" spellcheck="false"/> <button class="button">Generate Random ID</button>',1);root_66=from_html("The Group ID and passphrase are used to identify your group of devices. Make sure to use the same Group ID and\n passphrase on all devices you want to synchronise.<br/> Note that the Group ID is not limited to the generated format; you can use any string as the Group ID.",1);root_77=from_html('<input type="text" name="p2p-device-peer-id" placeholder="main-iphone16" autocorrect="off" autocapitalize="off" spellcheck="false"/>');root_87=from_html('<input type="checkbox" name="p2p-auto-start"/>');root_103=from_html('<input type="checkbox" name="p2p-auto-broadcast"/>');root_153=from_html('<textarea name="p2p-turn-servers" placeholder="turn:turn.example.com:3478,turn:turn.example.com:443" autocapitalize="off" spellcheck="false" rows="5"></textarea>');root_163=from_html('<input type="text" name="p2p-turn-username" placeholder="Enter TURN username" autocorrect="off" autocapitalize="off" spellcheck="false"/>');root_124=from_html("<!> <!> <!> <!> <!>",1);root_215=from_html("<!> <!> <!>",1);root30=from_html("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!> <!>",1);delegate(["click"]);root_216=from_html('<input type="checkbox"/> <!>',1);root_35=from_html("Enabling end-to-end encryption ensures that your data is encrypted on your device before being sent to the remote\n server. This means that even if someone gains access to the server, they won't be able to read your data without the\n passphrase. Make sure to remember your passphrase, as it will be required to decrypt your data on other devices. <br/> Also, please note that if you are using Peer-to-Peer synchronization, this configuration will be used when you switch\n to other methods and connect to a remote server in the future.",1);root_53=from_html('<input type="checkbox"/>');root_94=from_html("<option> </option>");root_88=from_html("<select></select>");root_78=from_html("<!> <!> <!>",1);root_125=from_html("<p>Please be aware that the End-to-End Encryption passphrase is not validated until the synchronisation process\n actually commences. This is a security measure designed to protect your data.</p> <p>Therefore, we ask that you exercise extreme caution when configuring server information manually. If an\n incorrect passphrase is entered, the data on the server will become corrupted. <br/><br/> Please understand that this is intended behaviour.</p>",1);root_135=from_html("<!> <!>",1);root31=from_html("<!> <!> <!> <!> <!> <!> <!> <!> <!> <!>",1);import_qrcode_generator=__toESM(require_qrcode(),1);OutputFormat=(OutputFormat2=>{OutputFormat2[OutputFormat2.SVG=0]="SVG";OutputFormat2[OutputFormat2.ASCII=1]="ASCII";return OutputFormat2})(OutputFormat||{});necessaryErasureProperties=["configPassphraseStore","encryptedCouchDBConnection","encryptedPassphrase"];UserMode=(UserMode2=>{UserMode2.NewUser="new-user";UserMode2.ExistingUser="existing-user";UserMode2.Unknown="unknown";UserMode2.Update="unknown";return UserMode2})(UserMode||{});SetupManager=class extends AbstractObsidianModule{constructor(){super(...arguments);this.dialogManager=new SvelteDialogManager(this.plugin)}async startOnBoarding(){const isUserNewOrExisting=await this.dialogManager.openWithExplicitCancel(Intro);if("new-user"===isUserNewOrExisting)await this.onOnboard("new-user");else if("existing-user"===isUserNewOrExisting)await this.onOnboard("existing-user");else if("cancelled"===isUserNewOrExisting){this._log("Onboarding cancelled by user.",LOG_LEVEL_NOTICE);return!1}return!1}async onOnboard(userMode){const originalSetting="new-user"===userMode?DEFAULT_SETTINGS:this.core.settings;if("new-user"===userMode){const method=await this.dialogManager.openWithExplicitCancel(SelectMethodNewUser);if("use-setup-uri"===method)await this.onUseSetupURI(userMode);else if("configure-manually"===method)await this.onConfigureManually(originalSetting,userMode);else if("cancelled"===method){this._log("Onboarding cancelled by user.",LOG_LEVEL_NOTICE);return!1}}else if("existing-user"===userMode){const method=await this.dialogManager.openWithExplicitCancel(SelectMethodExisting);if("use-setup-uri"===method)await this.onUseSetupURI(userMode);else if("configure-manually"===method)await this.onConfigureManually(originalSetting,userMode);else if("scan-qr-code"===method)await this.onPromptQRCodeInstruction();else if("cancelled"===method){this._log("Onboarding cancelled by user.",LOG_LEVEL_NOTICE);return!1}}return!1}async onUseSetupURI(userMode,setupURI=""){const newSetting=await this.dialogManager.openWithExplicitCancel(UseSetupURI,setupURI);if("cancelled"===newSetting){this._log("Setup URI dialog cancelled.",LOG_LEVEL_NOTICE);return!1}this._log("Setup URI dialog closed.",LOG_LEVEL_VERBOSE);return await this.onConfirmApplySettingsFromWizard(newSetting,userMode)}async onCouchDBManualSetup(userMode,currentSetting,activate=!0){const originalSetting=JSON.parse(JSON.stringify(currentSetting)),baseSetting=JSON.parse(JSON.stringify(originalSetting)),couchConf=await this.dialogManager.openWithExplicitCancel(SetupRemoteCouchDB,originalSetting);if("cancelled"===couchConf){this._log("Manual configuration cancelled.",LOG_LEVEL_NOTICE);return await this.onOnboard(userMode)}const newSetting={...baseSetting,...couchConf};activate&&(newSetting.remoteType=REMOTE_COUCHDB);return await this.onConfirmApplySettingsFromWizard(newSetting,userMode,activate)}async onBucketManualSetup(userMode,currentSetting,activate=!0){const bucketConf=await this.dialogManager.openWithExplicitCancel(SetupRemoteBucket,currentSetting);if("cancelled"===bucketConf){this._log("Manual configuration cancelled.",LOG_LEVEL_NOTICE);return await this.onOnboard(userMode)}const newSetting={...currentSetting,...bucketConf};activate&&(newSetting.remoteType=REMOTE_MINIO);return await this.onConfirmApplySettingsFromWizard(newSetting,userMode,activate)}async onP2PManualSetup(userMode,currentSetting,activate=!0){const p2pConf=await this.dialogManager.openWithExplicitCancel(SetupRemoteP2P,currentSetting);if("cancelled"===p2pConf){this._log("Manual configuration cancelled.",LOG_LEVEL_NOTICE);return await this.onOnboard(userMode)}const newSetting={...currentSetting,...p2pConf};activate&&(newSetting.remoteType=REMOTE_P2P);return await this.onConfirmApplySettingsFromWizard(newSetting,userMode,activate)}async onlyE2EEConfiguration(userMode,currentSetting){const e2eeConf=await this.dialogManager.openWithExplicitCancel(SetupRemoteE2EE,currentSetting);if("cancelled"===e2eeConf){this._log("E2EE configuration cancelled.",LOG_LEVEL_NOTICE);return await!1}const newSetting={...currentSetting,...e2eeConf};return await this.onConfirmApplySettingsFromWizard(newSetting,userMode)}async onConfigureManually(originalSetting,userMode){const e2eeConf=await this.dialogManager.openWithExplicitCancel(SetupRemoteE2EE,originalSetting);if("cancelled"===e2eeConf){this._log("Manual configuration cancelled.",LOG_LEVEL_NOTICE);return await this.onOnboard(userMode)}const currentSetting={...originalSetting,...e2eeConf};return await this.onSelectServer(currentSetting,userMode)}async onSelectServer(currentSetting,userMode){const method=await this.dialogManager.openWithExplicitCancel(SetupRemote);if("couchdb"===method)return await this.onCouchDBManualSetup(userMode,currentSetting,!0);if("bucket"===method)return await this.onBucketManualSetup(userMode,currentSetting,!0);if("p2p"===method)return await this.onP2PManualSetup(userMode,currentSetting,!0);if("cancelled"===method){this._log("Manual configuration cancelled.",LOG_LEVEL_NOTICE);if("unknown"!==userMode)return await this.onOnboard(userMode)}return!1}async onConfirmApplySettingsFromWizard(newConf,_userMode,activate=!0,extra=()=>{}){let userMode=_userMode;if("unknown"===userMode){if(!1===isObjectDifferent(this.settings,newConf,!0)){this._log("No changes in settings detected. Skipping applying settings from wizard.",LOG_LEVEL_NOTICE);return!0}const patch=generatePatchObj(this.settings,newConf);console.log("Changes:");console.dir(patch);if(!activate){extra();await this.applySetting(newConf,"existing-user");this._log("Setting Applied",LOG_LEVEL_NOTICE);return!0}if(!1===isObjectDifferent({...this.settings,P2P_DevicePeerName:""},{...newConf,P2P_DevicePeerName:""},!0)){extra();await this.applySetting(newConf,"existing-user");this._log("Settings from wizard applied.",LOG_LEVEL_NOTICE);return!0}{const userModeResult=await this.dialogManager.openWithExplicitCancel(OutroAskUserMode);if("new-user"===userModeResult)userMode="new-user";else if("existing-user"===userModeResult)userMode="existing-user";else{if("compatible-existing-user"===userModeResult){extra();await this.applySetting(newConf,"existing-user");this._log("Settings from wizard applied.",LOG_LEVEL_NOTICE);return!0}if("cancelled"===userModeResult){this._log("User cancelled applying settings from wizard.",LOG_LEVEL_NOTICE);return!1}}}}const component2="new-user"===userMode?OutroNewUser:OutroExistingUser,confirm=await this.dialogManager.openWithExplicitCancel(component2);if("cancelled"===confirm){this._log("User cancelled applying settings from wizard..",LOG_LEVEL_NOTICE);return!1}if(confirm){extra();await this.applySetting(newConf,userMode);"new-user"===userMode?await this.core.rebuilder.scheduleRebuild():await this.core.rebuilder.scheduleFetch()}return!1}async onPromptQRCodeInstruction(){const qrResult=await this.dialogManager.open(ScanQRCode);this._log("QR Code dialog closed.",LOG_LEVEL_VERBOSE);this._log(`QR Code result: ${qrResult}`,LOG_LEVEL_VERBOSE);return!1}async decodeQR(qr){const newSettings=decodeSettingsFromQRCodeData(qr);return await this.onConfirmApplySettingsFromWizard(newSettings,"unknown")}async applySetting(newConf,userMode){const newSetting={...this.core.settings,...newConf};this.core.settings=newSetting;this.services.setting.clearUsedPassphrase();await this.services.setting.saveSettingData();return!0}};ModuleMigration=class extends AbstractModule{async migrateUsingDoctor(skipRebuild=!1,activateReason="updated",forceRescan=!1){const{shouldRebuild,shouldRebuildLocal,isModified,settings}=await performDoctorConsultation(this.core,this.settings,{localRebuild:skipRebuild?RebuildOptions_SkipEvenIfRequired:RebuildOptions_AutomaticAcceptable,remoteRebuild:skipRebuild?RebuildOptions_SkipEvenIfRequired:RebuildOptions_AutomaticAcceptable,activateReason,forceRescan});if(isModified){this.settings=settings;await this.core.saveSettings()}if(!skipRebuild){if(shouldRebuild){await this.core.rebuilder.scheduleRebuild();this.services.appLifecycle.performRestart();return!1}if(shouldRebuildLocal){await this.core.rebuilder.scheduleFetch();this.services.appLifecycle.performRestart();return!1}}return!0}async migrateDisableBulkSend(){if(this.settings.sendChunksBulk){this._log($msg("moduleMigration.logBulkSendCorrupted"),LOG_LEVEL_NOTICE);this.settings.sendChunksBulk=!1;this.settings.sendChunksBulkMaxSize=1;await this.saveSettings()}}async initialMessage(){const manager=this.core.getModule(SetupManager);return await manager.startOnBoarding()}async askAgainForSetupURI(){const message=$msg("moduleMigration.msgRecommendSetupUri",{URI_DOC:$msg("moduleMigration.docUri")}),USE_MINIMAL=$msg("moduleMigration.optionSetupWizard"),USE_P2P=$msg("moduleMigration.optionSetupViaP2P"),USE_SETUP=$msg("moduleMigration.optionManualSetup"),NEXT=$msg("moduleMigration.optionRemindNextLaunch"),ret=await this.core.confirm.askSelectStringDialogue(message,[USE_MINIMAL,USE_SETUP,USE_P2P,NEXT],{title:$msg("moduleMigration.titleRecommendSetupUri"),defaultAction:USE_MINIMAL});if(ret===USE_MINIMAL){eventHub.emitEvent("request-open-setting-wizard");return!1}if(ret===USE_P2P){eventHub.emitEvent("request-open-p2p");return!1}if(ret===USE_SETUP){eventHub.emitEvent("request-open-settings");return!1}return!1}async hasIncompleteDocs(force=!1){if(await this.core.kvDB.get("checkIncompleteDocs")&&!force){this._log("Incomplete docs check already done, skipping.",LOG_LEVEL_VERBOSE);return Promise.resolve(!0)}this._log("Checking for incomplete documents...",LOG_LEVEL_NOTICE,"check-incomplete");const errorFiles=[];for await(const metaDoc of this.localDatabase.findAllNormalDocs({conflicts:!0})){const path2=getPath2(metaDoc);if(!isValidPath(path2))continue;if(!await this.services.vault.isTargetFile(path2,!0))continue;if(!isMetaEntry(metaDoc))continue;const doc=await this.localDatabase.getDBEntryFromMeta(metaDoc);if(!doc||!isLoadedEntry(doc))continue;if(isDeletedEntry(doc))continue;const isConflicted=(null==metaDoc?void 0:metaDoc._conflicts)&&metaDoc._conflicts.length>0;let storageFileContent;try{storageFileContent=await this.core.storageAccess.readHiddenFileBinary(path2)}catch(e3){Logger(`Failed to read file ${path2}: Possibly unprocessed or missing`);Logger(e3,LOG_LEVEL_VERBOSE);continue}const sizeOnStorage=storageFileContent.byteLength,recordedSize=doc.size,actualSize=readAsBlob(doc).size;if(recordedSize!==actualSize||sizeOnStorage!==actualSize||sizeOnStorage!==recordedSize||isConflicted){const contentMatched=await isDocContentSame(doc.data,storageFileContent);errorFiles.push({path:path2,recordedSize,actualSize,storageSize:sizeOnStorage,contentMatched,isConflicted});Logger(`Size mismatch for ${path2}: ${recordedSize} (DB Recorded) , ${actualSize} (DB Stored) , ${sizeOnStorage} (Storage Stored), ${contentMatched?"Content Matched":"Content Mismatched"} ${isConflicted?"Conflicted":"Not Conflicted"}`)}}if(0==errorFiles.length){Logger("No size mismatches found",LOG_LEVEL_NOTICE);await this.core.kvDB.set("checkIncompleteDocs",!0);return Promise.resolve(!0)}Logger(`Found ${errorFiles.length} size mismatches`,LOG_LEVEL_NOTICE);const recoverable=errorFiles.filter((e3=>e3.recordedSize===e3.storageSize&&!e3.isConflicted)),unrecoverable=errorFiles.filter((e3=>e3.recordedSize!==e3.storageSize||e3.isConflicted)),fileInfo=e3=>`${e3.path} (M: ${e3.recordedSize}, A: ${e3.actualSize}, S: ${e3.storageSize}) ${e3.isConflicted?"(Conflicted)":""}`,messageUnrecoverable=unrecoverable.length>0?$msg("moduleMigration.fix0256.messageUnrecoverable",{filesNotRecoverable:unrecoverable.map((e3=>`- ${fileInfo(e3)}`)).join("\n")}):"",message=$msg("moduleMigration.fix0256.message",{files:recoverable.map((e3=>`- ${fileInfo(e3)}`)).join("\n"),messageUnrecoverable}),CHECK_IT_LATER=$msg("moduleMigration.fix0256.buttons.checkItLater"),FIX=$msg("moduleMigration.fix0256.buttons.fix"),DISMISS=$msg("moduleMigration.fix0256.buttons.DismissForever"),ret=await this.core.confirm.askSelectStringDialogue(message,[CHECK_IT_LATER,FIX,DISMISS],{title:$msg("moduleMigration.fix0256.title"),defaultAction:CHECK_IT_LATER});if(ret==FIX)for(const file of recoverable){const stubFile=this.core.storageAccess.getFileStub(file.path);if(null!=stubFile){stubFile.stat.mtime=Date.now();await this.core.fileHandler.storeFileToDB(stubFile,!0,!1)?Logger(`Successfully restored ${file.path} from storage`):Logger(`Failed to restore ${file.path} from storage`,LOG_LEVEL_NOTICE)}else Logger(`Could not find stub file for ${file.path}`,LOG_LEVEL_NOTICE)}else ret===DISMISS&&await this.core.kvDB.set("checkIncompleteDocs",!0);return Promise.resolve(!0)}async hasCompromisedChunks(){Logger("Checking for compromised chunks...",LOG_LEVEL_VERBOSE);if(!this.settings.encrypt)return!0;const localCompromised=await countCompromisedChunks(this.localDatabase.localDatabase),remote=this.services.replicator.getActiveReplicator(),remoteCompromised=this.core.managers.networkManager.isOnline?await(null==remote?void 0:remote.countCompromisedChunks()):0;if(!1===localCompromised){Logger("Failed to count compromised chunks in local database",LOG_LEVEL_NOTICE);return!1}if(!1===remoteCompromised){Logger("Failed to count compromised chunks in remote database",LOG_LEVEL_NOTICE);return!1}if(0===remoteCompromised&&0===localCompromised)return!0;Logger(`Found compromised chunks : ${localCompromised} in local, ${remoteCompromised} in remote`,LOG_LEVEL_NOTICE);const title=$msg("moduleMigration.insecureChunkExist.title"),msg=$msg("moduleMigration.insecureChunkExist.message"),REBUILD=$msg("moduleMigration.insecureChunkExist.buttons.rebuild"),FETCH=$msg("moduleMigration.insecureChunkExist.buttons.fetch"),DISMISS=$msg("moduleMigration.insecureChunkExist.buttons.later"),buttons=[REBUILD,FETCH,DISMISS];0!=remoteCompromised&&buttons.splice(buttons.indexOf(FETCH),1);const result=await this.core.confirm.askSelectStringDialogue(msg,buttons,{title,defaultAction:DISMISS,timeout:0});if(result===REBUILD){await this.core.rebuilder.scheduleRebuild();this.services.appLifecycle.performRestart();return!1}if(result===FETCH){await this.core.rebuilder.scheduleFetch();this.services.appLifecycle.performRestart();return!1}this._log($msg("moduleMigration.insecureChunkExist.laterMessage"),LOG_LEVEL_NOTICE);return!0}async _everyOnFirstInitialize(){if(!this.localDatabase.isReady){this._log($msg("moduleMigration.logLocalDatabaseNotReady"),LOG_LEVEL_NOTICE);return!1}if(this.settings.isConfigured){if(!await this.hasCompromisedChunks())return!1;if(!await this.hasIncompleteDocs())return!1;if(!await this.migrateUsingDoctor(!1))return!1;await this.migrateDisableBulkSend()}if(!this.settings.isConfigured){if(!await this.initialMessage()){this._log($msg("moduleMigration.logSetupCancelled"),LOG_LEVEL_NOTICE);return!1}if(!await this.migrateUsingDoctor(!0))return!1}return!0}_everyOnLayoutReady(){eventHub.onEvent(EVENT_REQUEST_RUN_DOCTOR,(async reason=>{await this.migrateUsingDoctor(!1,reason,!0)}));eventHub.onEvent(EVENT_REQUEST_RUN_FIX_INCOMPLETE,(async()=>{await this.hasIncompleteDocs(!0)}));return Promise.resolve(!0)}onBindFunction(core,services){super.onBindFunction(core,services);services.appLifecycle.handleLayoutReady(this._everyOnLayoutReady.bind(this));services.appLifecycle.handleFirstInitialise(this._everyOnFirstInitialize.bind(this))}};ModuleCheckRemoteSize=class extends AbstractObsidianModule{checkRemoteSize(){this.settings.notifyThresholdOfRemoteStorageSize=1;return this._allScanStat()}async _allScanStat(){var _a8;if(!1===this.core.managers.networkManager.isOnline){this._log("Network is offline, skipping remote size check.",LOG_LEVEL_INFO);return!0}this._log($msg("moduleCheckRemoteSize.logCheckingStorageSizes"),LOG_LEVEL_VERBOSE);if(this.settings.notifyThresholdOfRemoteStorageSize<0){const message=$msg("moduleCheckRemoteSize.msgSetDBCapacity"),ANSWER_0=$msg("moduleCheckRemoteSize.optionNoWarn"),ANSWER_800=$msg("moduleCheckRemoteSize.option800MB"),ANSWER_2000=$msg("moduleCheckRemoteSize.option2GB"),ASK_ME_NEXT_TIME=$msg("moduleCheckRemoteSize.optionAskMeLater"),ret=await this.core.confirm.askSelectStringDialogue(message,[ANSWER_0,ANSWER_800,ANSWER_2000,ASK_ME_NEXT_TIME],{defaultAction:ASK_ME_NEXT_TIME,title:$msg("moduleCheckRemoteSize.titleDatabaseSizeNotify"),timeout:40});if(ret==ANSWER_0){this.settings.notifyThresholdOfRemoteStorageSize=0;await this.core.saveSettings()}else if(ret==ANSWER_800){this.settings.notifyThresholdOfRemoteStorageSize=800;await this.core.saveSettings()}else if(ret==ANSWER_2000){this.settings.notifyThresholdOfRemoteStorageSize=2e3;await this.core.saveSettings()}}if(this.settings.notifyThresholdOfRemoteStorageSize>0){const remoteStat=await(null==(_a8=this.core.replicator)?void 0:_a8.getRemoteStatus(this.settings));if(remoteStat){const estimatedSize=remoteStat.estimatedSize;if(estimatedSize){const maxSize=1024*this.settings.notifyThresholdOfRemoteStorageSize*1024;if(estimatedSize>maxSize){const message=$msg("moduleCheckRemoteSize.msgDatabaseGrowing",{estimatedSize:sizeToHumanReadable(estimatedSize),maxSize:sizeToHumanReadable(maxSize)}),ANSWER_ENLARGE_LIMIT=$msg("moduleCheckRemoteSize.optionIncreaseLimit",{newMax:(100+~~(estimatedSize/1024/1024)).toString()}),ANSWER_REBUILD=$msg("moduleCheckRemoteSize.optionRebuildAll"),ANSWER_IGNORE=$msg("moduleCheckRemoteSize.optionDismiss"),ret=await this.core.confirm.askSelectStringDialogue(message,[ANSWER_ENLARGE_LIMIT,ANSWER_REBUILD,ANSWER_IGNORE],{defaultAction:ANSWER_IGNORE,title:$msg("moduleCheckRemoteSize.titleDatabaseSizeLimitExceeded"),timeout:60});if(ret==ANSWER_REBUILD){if("yes"==await this.core.confirm.askYesNoDialog($msg("moduleCheckRemoteSize.msgConfirmRebuild"),{defaultOption:"No"})){this.core.settings.notifyThresholdOfRemoteStorageSize=-1;await this.saveSettings();await this.core.rebuilder.scheduleRebuild()}}else if(ret==ANSWER_ENLARGE_LIMIT){this.settings.notifyThresholdOfRemoteStorageSize=100+~~(estimatedSize/1024/1024);this._log($msg("moduleCheckRemoteSize.logThresholdEnlarged",{size:this.settings.notifyThresholdOfRemoteStorageSize.toString()}),LOG_LEVEL_NOTICE);await this.core.saveSettings()}this._log($msg("moduleCheckRemoteSize.logExceededWarning",{measuredSize:sizeToHumanReadable(estimatedSize),notifySize:sizeToHumanReadable(1024*this.settings.notifyThresholdOfRemoteStorageSize*1024)}),LOG_LEVEL_INFO)}else this._log($msg("moduleCheckRemoteSize.logCurrentStorageSize",{measuredSize:sizeToHumanReadable(estimatedSize)}),LOG_LEVEL_INFO)}}}return!0}_everyOnloadStart(){this.addCommand({id:"livesync-reset-remote-size-threshold-and-check",name:"Reset notification threshold and check the remote database usage",callback:async()=>{await this.checkRemoteSize()}});eventHub.onEvent(EVENT_REQUEST_CHECK_REMOTE_SIZE,(()=>this.checkRemoteSize()));return Promise.resolve(!0)}onBindFunction(core,services){services.appLifecycle.handleOnScanningStartupIssues(this._allScanStat.bind(this));services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this))}};import_diff_match_patch3=__toESM(require_diff_match_patch(),1);ModuleConflictResolver=class extends AbstractModule{async _resolveConflictByDeletingRev(path2,deleteRevision,subTitle=""){const title=`Resolving ${subTitle?`[${subTitle}]`:""}:`;if(!await this.core.fileHandler.deleteRevisionFromDB(path2,deleteRevision)){this._log(`${title} Could not delete conflicted revision ${displayRev(deleteRevision)} of ${path2}`,LOG_LEVEL_NOTICE);return MISSING_OR_ERROR}eventHub.emitEvent("conflict-cancelled",path2);this._log(`${title} Conflicted revision has been deleted ${displayRev(deleteRevision)} ${path2}`,LOG_LEVEL_INFO);if(0!=(await this.core.databaseFileAccess.getConflictedRevs(path2)).length){this._log(`${title} some conflicts are left in ${path2}`,LOG_LEVEL_INFO);return AUTO_MERGED}if(isPluginMetadata(path2)||isCustomisationSyncMetadata(path2)){this._log(`${title} ${path2} is a plugin metadata file, no need to write to storage`,LOG_LEVEL_INFO);return AUTO_MERGED}if(!await this.core.fileHandler.dbToStorage(path2,stripAllPrefixes(path2),!0)){this._log(`Could not write the resolved content to the storage: ${path2}`,LOG_LEVEL_NOTICE);return MISSING_OR_ERROR}const level=-1!==subTitle.indexOf("same")?LOG_LEVEL_INFO:LOG_LEVEL_NOTICE;this._log(`${path2} has been merged automatically`,level);return AUTO_MERGED}async checkConflictAndPerformAutoMerge(path2){const ret=await this.localDatabase.tryAutoMerge(path2,!this.settings.disableMarkdownAutoMerge);if("ok"in ret)return ret.ok;if("result"in ret){const p4=ret.result;if(!await this.core.databaseFileAccess.storeContent(path2,p4)){this._log(`Merged content cannot be stored:${path2}`,LOG_LEVEL_NOTICE);return MISSING_OR_ERROR}return await this.services.conflict.resolveByDeletingRevision(path2,ret.conflictedRev,"Sensible")}const{rightRev,leftLeaf,rightLeaf}=ret;if(0==leftLeaf){this._log(`could not get current revisions:${path2}`,LOG_LEVEL_NOTICE);return MISSING_OR_ERROR}if(0==rightLeaf)return await this.services.conflict.resolveByDeletingRevision(path2,rightRev,"MISSING OLD REV");const isSame=leftLeaf.data==rightLeaf.data&&leftLeaf.deleted==rightLeaf.deleted,isBinary=!isPlainText(path2),alwaysNewer=this.settings.resolveConflictsByNewerFile;if(isSame||isBinary||alwaysNewer){let loser=leftLeaf;compareMTime(leftLeaf.mtime,rightLeaf.mtime)!=TARGET_IS_NEW&&(loser=rightLeaf);const subTitle=[isSame?"same":"",isBinary?"binary":"",alwaysNewer?"alwaysNewer":""].filter((e3=>e3.trim())).join(",");return await this.services.conflict.resolveByDeletingRevision(path2,loser.rev,subTitle)}const dmp=new import_diff_match_patch3.default,diff=dmp.diff_main(leftLeaf.data,rightLeaf.data);dmp.diff_cleanupSemantic(diff);this._log(`conflict(s) found:${path2}`);return{left:leftLeaf,right:rightLeaf,diff}}async _resolveConflict(filename){return await serialized(`conflict-resolve:${filename}`,(async()=>{const conflictCheckResult=await this.checkConflictAndPerformAutoMerge(filename);if(conflictCheckResult!==MISSING_OR_ERROR&&conflictCheckResult!==NOT_CONFLICTED&&conflictCheckResult!==CANCELLED)if(conflictCheckResult!==AUTO_MERGED){if(this.settings.showMergeDialogOnlyOnActive){const af2=this.services.vault.getActiveFilePath();if(af2&&af2!=filename){this._log(`[conflict] ${filename} is conflicted. Merging process has been postponed to the file have got opened.`,LOG_LEVEL_NOTICE);return}}this._log("[conflict] Manual merge required!");eventHub.emitEvent("conflict-cancelled",filename);await this.services.conflict.resolveByUserInteraction(filename,conflictCheckResult)}else{this.settings.syncAfterMerge&&!this.services.appLifecycle.isSuspended()&&await this.services.replication.replicateByEvent();this._log("[conflict] Automatically merged, but we have to check it again");await this.services.conflict.queueCheckFor(filename)}else this._log(`[conflict] Not conflicted or cancelled: ${filename}`,LOG_LEVEL_VERBOSE)}))}async _anyResolveConflictByNewest(filename){const currentRev=await this.core.databaseFileAccess.fetchEntryMeta(filename,void 0,!0);if(0==currentRev){this._log(`Could not get current revision of ${filename}`);return Promise.resolve(!1)}const revs=await this.core.databaseFileAccess.getConflictedRevs(filename);if(0==revs.length)return Promise.resolve(!0);const mTimeAndRev=[[currentRev.mtime,currentRev._rev],...await Promise.all(revs.map((async rev3=>{const leaf=await this.core.databaseFileAccess.fetchEntryMeta(filename,rev3);return 0==leaf?[0,rev3]:[leaf.mtime,rev3]})))].sort(((a2,b3)=>{const diff=b3[0]-a2[0];return 0==diff?a2[1].localeCompare(b3[1],"en",{numeric:!0}):diff}));this._log(`Resolving conflict by newest: ${filename} (Newest: ${new Date(mTimeAndRev[0][0]).toLocaleString()}) (${mTimeAndRev.length} revisions exists)`);for(let i2=1;i2<mTimeAndRev.length;i2++){this._log(`conflict: Deleting the older revision ${mTimeAndRev[i2][1]} (${new Date(mTimeAndRev[i2][0]).toLocaleString()}) of ${filename}`);await this.services.conflict.resolveByDeletingRevision(filename,mTimeAndRev[i2][1],"NEWEST")}return!0}onBindFunction(core,services){services.conflict.handleResolveByDeletingRevision(this._resolveConflictByDeletingRev.bind(this));services.conflict.handleResolve(this._resolveConflict.bind(this));services.conflict.handleResolveByNewest(this._anyResolveConflictByNewest.bind(this))}};ModuleInteractiveConflictResolver=class extends AbstractObsidianModule{_everyOnloadStart(){this.addCommand({id:"livesync-conflictcheck",name:"Pick a file to resolve conflict",callback:async()=>{await this.pickFileForResolve()}});this.addCommand({id:"livesync-all-conflictcheck",name:"Resolve all conflicted files",callback:async()=>{await this.allConflictCheck()}});return Promise.resolve(!0)}async _anyResolveConflictByUI(filename,conflictCheckResult){return await serialized("conflict-resolve-ui",(async()=>{this._log("Merge:open conflict dialog",LOG_LEVEL_VERBOSE);const dialog=new ConflictResolveModal(this.app,filename,conflictCheckResult);dialog.open();const selected=await dialog.waitForResult();if(selected===CANCELLED){this._log(`Merge: Cancelled ${filename}`,LOG_LEVEL_INFO);return!1}const testDoc=await this.localDatabase.getDBEntry(filename,{conflicts:!0},!1,!0,!0);if(!1===testDoc){this._log(`Merge: Could not read ${filename} from the local database`,LOG_LEVEL_VERBOSE);return!1}if(!testDoc._conflicts){this._log(`Merge: Nothing to do ${filename}`,LOG_LEVEL_VERBOSE);return!1}const toDelete=selected;if(toDelete===LEAVE_TO_SUBSEQUENT){const p4=conflictCheckResult.diff.map((e3=>e3[1])).join(""),delRev=testDoc._conflicts[0];if(!await this.core.databaseFileAccess.storeContent(filename,p4)){this._log(`Concatenated content cannot be stored:${filename}`,LOG_LEVEL_NOTICE);return!1}if(await this.services.conflict.resolveByDeletingRevision(filename,delRev,"UI Concatenated")==MISSING_OR_ERROR){this._log(`Concatenated saved, but cannot delete conflicted revisions: ${filename}, (${displayRev(delRev)})`,LOG_LEVEL_NOTICE);return!1}}else{if("string"!=typeof toDelete){this._log(`Merge: Something went wrong: ${filename}, (${toDelete})`,LOG_LEVEL_NOTICE);return!1}if(await this.services.conflict.resolveByDeletingRevision(filename,toDelete,"UI Selected")==MISSING_OR_ERROR){this._log(`Merge: Something went wrong: ${filename}, (${toDelete})`,LOG_LEVEL_NOTICE);return!1}}this.settings.syncAfterMerge&&!this.services.appLifecycle.isSuspended()&&await this.services.replication.replicateByEvent();await this.services.conflict.queueCheckFor(filename);return!1}))}async allConflictCheck(){for(;await this.pickFileForResolve(););}async pickFileForResolve(){const notes=[];for await(const doc of this.localDatabase.findAllDocs({conflicts:!0}))"_conflicts"in doc&&notes.push({id:doc._id,path:getPath2(doc),dispPath:getPathWithoutPrefix2(doc),mtime:doc.mtime});notes.sort(((a2,b3)=>b3.mtime-a2.mtime));const notesList=notes.map((e3=>e3.dispPath));if(0==notesList.length){this._log("There are no conflicted documents",LOG_LEVEL_NOTICE);return!1}const target=await this.core.confirm.askSelectString("File to resolve conflict",notesList);if(target){const targetItem=notes.find((e3=>e3.dispPath==target));await this.services.conflict.queueCheckFor(targetItem.path);await this.services.conflict.ensureAllProcessed();return!0}return!1}async _allScanStat(){const notes=[];this._log("Checking conflicted files",LOG_LEVEL_VERBOSE);try{for await(const doc of this.localDatabase.findAllDocs({conflicts:!0}))"_conflicts"in doc&&notes.push({path:getPath2(doc),mtime:doc.mtime});if(notes.length>0){this.core.confirm.askInPopup("conflicting-detected-on-safety",'Some files have been left conflicted! Press {HERE} to resolve them, or you can do it later by "Pick a file to resolve conflict',(anchor=>{anchor.text="HERE";anchor.addEventListener("click",(()=>{fireAndForget((()=>this.allConflictCheck()))}))}));this._log('Some files have been left conflicted! Please resolve them by "Pick a file to resolve conflict". The list is written in the log.',LOG_LEVEL_VERBOSE);for(const note of notes)this._log(`Conflicted: ${note.path}`)}else this._log("There are no conflicting files",LOG_LEVEL_VERBOSE)}catch(e3){this._log(`Error while scanning conflicted files: ${e3}`,LOG_LEVEL_NOTICE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}return!0}onBindFunction(core,services){services.appLifecycle.handleOnScanningStartupIssues(this._allScanStat.bind(this));services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this));services.conflict.handleResolveByUserInteraction(this._anyResolveConflictByUI.bind(this))}};ModuleObsidianSettings=class extends AbstractObsidianModule{constructor(){super(...arguments);this.usedPassphrase=""}async _everyOnLayoutReady(){let isChanged=!1;if(""==this.settings.displayLanguage){const obsidianLanguage=(0,import_obsidian.getLanguage)();if(-1!==SUPPORTED_I18N_LANGS.indexOf(obsidianLanguage)&&obsidianLanguage!=this.settings.displayLanguage){this.settings.displayLanguage=obsidianLanguage;isChanged=!0;setLang(this.settings.displayLanguage)}else if(""==this.settings.displayLanguage){this.settings.displayLanguage="def";setLang(this.settings.displayLanguage);await this.services.setting.saveSettingData()}}if(isChanged){const revert2=$msg("dialog.yourLanguageAvailable.btnRevertToDefault");if(await this.core.confirm.askSelectStringDialogue($msg("dialog.yourLanguageAvailable"),["OK",revert2],{defaultAction:"OK",title:$msg("dialog.yourLanguageAvailable.Title")})==revert2){this.settings.displayLanguage="def";setLang(this.settings.displayLanguage)}await this.services.setting.saveSettingData()}return!0}getPassphrase(settings){const methods={"":()=>Promise.resolve("*"),LOCALSTORAGE:()=>{var _a8;return Promise.resolve(null!=(_a8=localStorage.getItem("ls-setting-passphrase"))&&_a8)},ASK_AT_LAUNCH:()=>this.core.confirm.askString("Passphrase","passphrase","")},method=settings.configPassphraseStore;return(method in methods?methods[method]:methods[""])()}_saveDeviceAndVaultName(){const lsKey="obsidian-live-sync-vaultanddevicename-"+this.services.vault.getVaultName();localStorage.setItem(lsKey,this.services.setting.getDeviceAndVaultName()||"")}_clearUsedPassphrase(){this.usedPassphrase=""}async decryptConfigurationItem(encrypted,passphrase){const dec=await decryptString(encrypted,passphrase+"rHGMPtr6oWw7VSa3W3wpa8fT8U");if(dec){this.usedPassphrase=passphrase;return dec}return!1}async encryptConfigurationItem(src,settings){if(""!=this.usedPassphrase)return await encryptString(src,this.usedPassphrase+"rHGMPtr6oWw7VSa3W3wpa8fT8U");const passphrase=await this.getPassphrase(settings);if(!1===passphrase){this._log("Failed to obtain passphrase when saving data.json! Please verify the configuration.",128);return""}const dec=await encryptString(src,passphrase+"rHGMPtr6oWw7VSa3W3wpa8fT8U");if(dec){this.usedPassphrase=passphrase;return dec}return""}get appId(){return`${"appId"in this.app?this.app.appId:""}`}async _saveSettingData(){this.services.setting.saveDeviceAndVaultName();const settings={...this.settings};settings.deviceAndVaultName="";if(settings.P2P_DevicePeerName&&""!==settings.P2P_DevicePeerName.trim()){console.log("Saving device peer name to small config");this.services.config.setSmallConfig(SETTING_KEY_P2P_DEVICE_NAME,settings.P2P_DevicePeerName.trim());settings.P2P_DevicePeerName=""}if(""!=this.usedPassphrase||await this.getPassphrase(settings)){if(""!=settings.couchDB_PASSWORD||""!=settings.couchDB_URI||""!=settings.couchDB_USER||settings.couchDB_DBNAME){const connectionSetting={couchDB_DBNAME:settings.couchDB_DBNAME,couchDB_PASSWORD:settings.couchDB_PASSWORD,couchDB_URI:settings.couchDB_URI,couchDB_USER:settings.couchDB_USER,accessKey:settings.accessKey,bucket:settings.bucket,endpoint:settings.endpoint,region:settings.region,secretKey:settings.secretKey,useCustomRequestHandler:settings.useCustomRequestHandler,bucketCustomHeaders:settings.bucketCustomHeaders,couchDB_CustomHeaders:settings.couchDB_CustomHeaders,useJWT:settings.useJWT,jwtKey:settings.jwtKey,jwtAlgorithm:settings.jwtAlgorithm,jwtKid:settings.jwtKid,jwtExpDuration:settings.jwtExpDuration,jwtSub:settings.jwtSub,useRequestAPI:settings.useRequestAPI,bucketPrefix:settings.bucketPrefix,forcePathStyle:settings.forcePathStyle};settings.encryptedCouchDBConnection=await this.encryptConfigurationItem(JSON.stringify(connectionSetting),settings);settings.couchDB_PASSWORD="";settings.couchDB_DBNAME="";settings.couchDB_URI="";settings.couchDB_USER="";settings.accessKey="";settings.bucket="";settings.region="";settings.secretKey="";settings.endpoint=""}if(settings.encrypt&&""!=settings.passphrase){settings.encryptedPassphrase=await this.encryptConfigurationItem(settings.passphrase,settings);settings.passphrase=""}}else this._log("Failed to retrieve passphrase. data.json contains unencrypted items!",LOG_LEVEL_NOTICE);await this.core.saveData(settings);eventHub.emitEvent(EVENT_SETTING_SAVED,settings)}tryDecodeJson(encoded){try{return!!encoded&&JSON.parse(encoded)}catch(e3){return!1}}async _decryptSettings(settings){const passphrase=await this.getPassphrase(settings);if(!1===passphrase)this._log("No passphrase found for data.json! Verify configuration before syncing.",128);else{if(settings.encryptedCouchDBConnection){const keys3=["couchDB_URI","couchDB_USER","couchDB_PASSWORD","couchDB_DBNAME","accessKey","bucket","endpoint","region","secretKey"],decrypted=this.tryDecodeJson(await this.decryptConfigurationItem(settings.encryptedCouchDBConnection,passphrase));if(decrypted)for(const key3 of keys3)key3 in decrypted&&(settings[key3]=decrypted[key3]);else{this._log("Failed to decrypt passphrase from data.json! Ensure configuration is correct before syncing with remote.",128);for(const key3 of keys3)settings[key3]=""}}if(settings.encrypt&&settings.encryptedPassphrase){const encrypted=settings.encryptedPassphrase,decrypted=await this.decryptConfigurationItem(encrypted,passphrase);if(decrypted)settings.passphrase=decrypted;else{this._log("Failed to decrypt passphrase from data.json! Ensure configuration is correct before syncing with remote.",128);settings.passphrase=""}}}return settings}_adjustSettings(settings){settings.disableRequestURI=!0;settings.gcDelay=0;settings.useHistory=!0;"workingEncrypt"in settings&&delete settings.workingEncrypt;"workingPassphrase"in settings&&delete settings.workingPassphrase;""==settings.chunkSplitterVersion?settings.enableChunkSplitterV2?settings.useSegmenter?settings.chunkSplitterVersion="v2-segmenter":settings.chunkSplitterVersion="v2":settings.chunkSplitterVersion="":settings.chunkSplitterVersion in ChunkAlgorithmNames||(settings.chunkSplitterVersion="");return Promise.resolve(settings)}async _loadSettings(){const settings=Object.assign({},DEFAULT_SETTINGS,await this.core.loadData());if(void 0===settings.isConfigured)if(JSON.stringify(settings)!==JSON.stringify(DEFAULT_SETTINGS))settings.isConfigured=!0;else{settings.additionalSuffixOfDatabaseName=this.appId;settings.isConfigured=!1}this.settings=await this.services.setting.decryptSettings(settings);setLang(this.settings.displayLanguage);await this.services.setting.adjustSettings(this.settings);const lsKey="obsidian-live-sync-vaultanddevicename-"+this.services.vault.getVaultName();if(""!=this.settings.deviceAndVaultName&&!localStorage.getItem(lsKey)){this.services.setting.setDeviceAndVaultName(this.settings.deviceAndVaultName);this.services.setting.saveDeviceAndVaultName();this.settings.deviceAndVaultName=""}if(isCloudantURI(this.settings.couchDB_URI)&&0!=this.settings.customChunkSize){this._log("Configuration issues detected and automatically resolved. However, unsynchronized data may exist. Consider rebuilding if necessary.",LOG_LEVEL_NOTICE);this.settings.customChunkSize=0}this.services.setting.setDeviceAndVaultName(localStorage.getItem(lsKey)||"");if(""==this.services.setting.getDeviceAndVaultName()&&this.settings.usePluginSync){this._log("Device name missing. Disabling plug-in sync.",LOG_LEVEL_NOTICE);this.settings.usePluginSync=!1}eventHub.emitEvent("reload-setting-tab")}_currentSettings(){return this.settings}onBindFunction(core,services){super.onBindFunction(core,services);services.appLifecycle.handleLayoutReady(this._everyOnLayoutReady.bind(this));services.setting.handleClearUsedPassphrase(this._clearUsedPassphrase.bind(this));services.setting.handleDecryptSettings(this._decryptSettings.bind(this));services.setting.handleAdjustSettings(this._adjustSettings.bind(this));services.setting.handleLoadSettings(this._loadSettings.bind(this));services.setting.handleCurrentSettings(this._currentSettings.bind(this));services.setting.handleSaveDeviceAndVaultName(this._saveDeviceAndVaultName.bind(this));services.setting.handleSaveSettingData(this._saveSettingData.bind(this))}};root_217=from_html("<strong>If you have unsynchronised changes in your Vault on this device, they will likely diverge from the server's\n versions after the reset. This may result in a large number of file conflicts.</strong><br/> Furthermore, if conflicts are already present in the server data, they will be synchronised to this device as they are,\n and you will need to resolve them locally.",1);root_412=from_html("<strong>To minimise the creation of new conflicts</strong>, please select the option that best describes the\n current state of your Vault. The application will then check your files in the most appropriate way based on\n your selection.",1);root_89=from_html("(e.g., after editing many files whilst offline) <!>",1);root_54=from_html("<!> <!> <!>",1);root_36=from_html("<!> <!>",1);root_154=from_html("<strong>It is strongly advised to create a backup before proceeding. Continuing without a backup may lead\n to data loss.</strong> <br/> If you understand the risks and still wish to proceed, select so.",1);root_136=from_html("<!> <!> <!>",1);root_104=from_html("<!> <!> <!>",1);root_184=from_html("<!> <!>",1);root32=from_html("<!> <!> <!> <hr/> <!> <hr/> <!> <!> <!>",1);root_121=from_html("This procedure will first delete all existing synchronisation data from the server. Following this, the server data\n will be completely rebuilt, using the current state of your Vault on this device (including its local database) as <strong>the single, authoritative master copy</strong>.",1);root_413=from_html("<!> <!>",1);root_37=from_html("<!> <!> <!>",1);root_144=from_html("<strong>You should create a new synchronisation destination and rebuild your data there. <br/> After that,\n synchronise to a brand new vault on each other device with the new remote one by one.</strong>");root_126=from_html("<!> <!> <!>",1);root_95=from_html("<!> <!> <!>",1);root_172=from_html("<!> <!>",1);root33=from_html("<!> <!> <!> <!> <hr/> <!> <!> <!>",1);ModuleRedFlag=class extends AbstractModule{constructor(){super(...arguments);this.isSuspendFlagActive=async()=>await this.isFlagFileExist("redflag.md");this.isRebuildFlagActive=async()=>await this.isFlagFileExist("redflag2.md")||await this.isFlagFileExist(FlagFilesHumanReadable_REBUILD_ALL);this.isFetchAllFlagActive=async()=>await this.isFlagFileExist("redflag3.md")||await this.isFlagFileExist(FlagFilesHumanReadable_FETCH_ALL);this.dialogManager=new SvelteDialogManager(this.core)}async isFlagFileExist(path2){return!!await this.core.storageAccess.isExists(normalizePath(path2))}async deleteFlagFile(path2){try{await this.core.storageAccess.isExists(normalizePath(path2))&&await this.core.storageAccess.delete(path2,!0)}catch(ex){this._log(`Could not delete ${path2}`);this._log(ex,LOG_LEVEL_VERBOSE)}}async cleanupRebuildFlag(){await this.deleteFlagFile("redflag2.md");await this.deleteFlagFile(FlagFilesHumanReadable_REBUILD_ALL)}async cleanupFetchAllFlag(){await this.deleteFlagFile("redflag3.md");await this.deleteFlagFile(FlagFilesHumanReadable_FETCH_ALL)}async adjustSettingToRemoteIfNeeded(extra,config){if(!extra||!extra.preventFetchingConfig){await this.adjustSettingToRemote(config)?config=this.core.settings:this._log("Remote configuration not applied.",LOG_LEVEL_NOTICE);console.debug(config)}}async adjustSettingToRemote(config){let canProceed=!1;do{const remoteTweaks=await this.services.tweakValue.fetchRemotePreferred(config);if(remoteTweaks){const necessary=extractObject(TweakValuesShouldMatchedTemplate,remoteTweaks),differentItems=Object.entries(necessary).filter((([key3,value])=>config[key3]!==value));0===differentItems.length?this._log("Remote configuration matches local configuration. No changes applied.",LOG_LEVEL_NOTICE):await this.core.confirm.askSelectStringDialogue("Your settings differed slightly from the server's. The plug-in has supplemented the incompatible parts with the server settings!",["OK"],{defaultAction:"OK",timeout:0});config={...config,...Object.fromEntries(differentItems)};this.core.settings=config;await this.core.services.setting.saveSettingData();this._log("Remote configuration applied.",LOG_LEVEL_NOTICE);canProceed=!0;return this.core.settings}"Skip and proceed"===await this.core.confirm.askSelectStringDialogue("Could not fetch configuration from remote. If you are new to the Self-hosted LiveSync, this might be expected. If not, you should check your network or server settings.",["Skip and proceed","Retry (recommended)"],{defaultAction:"Retry (recommended)",timeout:0,title:"Fetch Remote Configuration Failed"})&&(canProceed=!0)}while(!canProceed)}async processVaultInitialisation(proc,keepSuspending=!1){try{this.settings.batchSave=!1;await this.services.setting.suspendAllSync();await this.services.setting.suspendExtraSync();this.settings.suspendFileWatching=!0;await this.saveSettings();try{return await proc()}catch(ex){this._log("Error during vault initialisation process.",LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}catch(ex){this._log("Error during vault initialisation.",LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE);return!1}finally{if(!keepSuspending){this.settings.suspendFileWatching=!1;await this.saveSettings()}}}async onRebuildEverythingScheduled(){const method=await this.dialogManager.openWithExplicitCancel(RebuildEverything);if("cancelled"===method){this._log("Rebuild everything cancelled by user.",LOG_LEVEL_NOTICE);await this.cleanupRebuildFlag();this.services.appLifecycle.performRestart();return!1}const{extra}=method;await this.adjustSettingToRemoteIfNeeded(extra,this.settings);return await this.processVaultInitialisation((async()=>{await this.core.rebuilder.$rebuildEverything();await this.cleanupRebuildFlag();this._log("Rebuild everything operation completed.",LOG_LEVEL_NOTICE);return!0}))}async onFetchAllScheduled(){const method=await this.dialogManager.openWithExplicitCancel(FetchEverything);if("cancelled"===method){this._log("Fetch everything cancelled by user.",LOG_LEVEL_NOTICE);await this.cleanupFetchAllFlag();this.services.appLifecycle.performRestart();return!1}const{vault,extra}=method,mapVaultStateToAction={identical:{makeLocalChunkBeforeSync:this.settings.remoteType!==REMOTE_MINIO,makeLocalFilesBeforeSync:!1},independent:{makeLocalChunkBeforeSync:!1,makeLocalFilesBeforeSync:!1},unbalanced:{makeLocalChunkBeforeSync:!1,makeLocalFilesBeforeSync:!0},cancelled:{makeLocalChunkBeforeSync:!1,makeLocalFilesBeforeSync:!1}};return await this.processVaultInitialisation((async()=>{await this.adjustSettingToRemoteIfNeeded(extra,this.settings);const{makeLocalChunkBeforeSync,makeLocalFilesBeforeSync}=mapVaultStateToAction[vault];this._log(`Fetching everything with settings: makeLocalChunkBeforeSync=${makeLocalChunkBeforeSync}, makeLocalFilesBeforeSync=${makeLocalFilesBeforeSync}`,LOG_LEVEL_INFO);await this.core.rebuilder.$fetchLocal(makeLocalChunkBeforeSync,!makeLocalFilesBeforeSync);await this.cleanupFetchAllFlag();this._log("Fetch everything operation completed. Vault files will be gradually synced.",LOG_LEVEL_NOTICE);return!0}))}async onSuspendAllScheduled(){this._log("SCRAM is detected. All operations are suspended.",LOG_LEVEL_NOTICE);return await this.processVaultInitialisation((async()=>{this._log("All operations are suspended as per SCRAM.\nLogs will be written to the file. This might be a performance impact.",LOG_LEVEL_NOTICE);this.settings.writeLogToTheFile=!0;await this.core.services.setting.saveSettingData();return Promise.resolve(!1)}),!0)}async verifyAndUnlockSuspension(){if(!this.settings.suspendFileWatching)return!0;if("yes"!=await this.core.confirm.askYesNoDialog("Do you want to resume file and database processing, and restart obsidian now?",{defaultOption:"Yes",timeout:15}))return!0;this.settings.suspendFileWatching=!1;await this.saveSettings();this.services.appLifecycle.performRestart();return!1}async processFlagFilesOnStartup(){const isFlagSuspensionActive=await this.isSuspendFlagActive(),isFlagRebuildActive=await this.isRebuildFlagActive();return await this.isFetchAllFlagActive()?!!await this.onFetchAllScheduled()&&await this.verifyAndUnlockSuspension():isFlagRebuildActive?!!await this.onRebuildEverythingScheduled()&&await this.verifyAndUnlockSuspension():!isFlagSuspensionActive||await this.onSuspendAllScheduled()}async _everyOnLayoutReady(){try{return await this.processFlagFilesOnStartup()}catch(ex){this._log("Something went wrong on FlagFile Handling",LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}return!0}onBindFunction(core,services){super.onBindFunction(core,services);services.appLifecycle.handleLayoutReady(this._everyOnLayoutReady.bind(this))}};ModuleObsidianMenu=class extends AbstractObsidianModule{_everyOnloadStart(){(0,import_obsidian.addIcon)("replicate",'<g transform="matrix(1.15 0 0 1.15 -8.31 -9.52)" fill="currentColor" fill-rule="evenodd">\n <path d="m85 22.2c-0.799-4.74-4.99-8.37-9.88-8.37-0.499 0-1.1 0.101-1.6 0.101-2.4-3.03-6.09-4.94-10.3-4.94-6.09 0-11.2 4.14-12.8 9.79-5.59 1.11-9.78 6.05-9.78 12 0 6.76 5.39 12.2 12 12.2h29.9c5.79 0 10.1-4.74 10.1-10.6 0-4.84-3.29-8.88-7.68-10.2zm-2.99 14.7h-29.5c-2.3-0.202-4.29-1.51-5.29-3.53-0.899-2.12-0.699-4.54 0.698-6.46 1.2-1.61 2.99-2.52 4.89-2.52 0.299 0 0.698 0 0.998 0.101l1.8 0.303v-2.02c0-3.63 2.4-6.76 5.89-7.57 0.599-0.101 1.2-0.202 1.8-0.202 2.89 0 5.49 1.62 6.79 4.24l0.598 1.21 1.3-0.504c0.599-0.202 1.3-0.303 2-0.303 1.3 0 2.5 0.404 3.59 1.11 1.6 1.21 2.6 3.13 2.6 5.15v1.61h2c2.6 0 4.69 2.12 4.69 4.74-0.099 2.52-2.2 4.64-4.79 4.64z"/>\n <path d="m53.2 49.2h-41.6c-1.8 0-3.2 1.4-3.2 3.2v28.6c0 1.8 1.4 3.2 3.2 3.2h15.8v4h-7v6h24v-6h-7v-4h15.8c1.8 0 3.2-1.4 3.2-3.2v-28.6c0-1.8-1.4-3.2-3.2-3.2zm-2.8 29h-36v-23h36z"/>\n <path d="m73 49.2c1.02 1.29 1.53 2.97 1.53 4.56 0 2.97-1.74 5.65-4.39 7.04v-4.06l-7.46 7.33 7.46 7.14v-4.06c7.66-1.98 12.2-9.61 10-17-0.102-0.297-0.205-0.595-0.307-0.892z"/>\n <path d="m24.1 43c-0.817-0.991-1.53-2.97-1.53-4.56 0-2.97 1.74-5.65 4.39-7.04v4.06l7.46-7.33-7.46-7.14v4.06c-7.66 1.98-12.2 9.61-10 17 0.102 0.297 0.205 0.595 0.307 0.892z"/>\n </g>');this.addRibbonIcon("replicate",$msg("moduleObsidianMenu.replicate"),(async()=>{await this.services.replication.replicate(!0)})).addClass("livesync-ribbon-replicate");this.addCommand({id:"livesync-replicate",name:"Replicate now",callback:async()=>{await this.services.replication.replicate()}});this.addCommand({id:"livesync-dump",name:"Dump information of this doc ",callback:()=>{const file=this.services.vault.getActiveFilePath();file&&fireAndForget((()=>this.localDatabase.getDBEntry(file,{},!0,!1)))}});this.addCommand({id:"livesync-checkdoc-conflicted",name:"Resolve if conflicted.",editorCallback:(editor,view)=>{const file=view.file;file&&this.services.conflict.queueCheckForIfOpen(file.path)}});this.addCommand({id:"livesync-toggle",name:"Toggle LiveSync",callback:async()=>{if(this.settings.liveSync){this.settings.liveSync=!1;this._log("LiveSync Disabled.",LOG_LEVEL_NOTICE)}else{this.settings.liveSync=!0;this._log("LiveSync Enabled.",LOG_LEVEL_NOTICE)}await this.services.setting.realiseSetting();await this.services.setting.saveSettingData()}});this.addCommand({id:"livesync-suspendall",name:"Toggle All Sync.",callback:async()=>{if(this.services.appLifecycle.isSuspended()){this.services.appLifecycle.setSuspended(!1);this._log("Self-hosted LiveSync resumed",LOG_LEVEL_NOTICE)}else{this.services.appLifecycle.setSuspended(!0);this._log("Self-hosted LiveSync suspended",LOG_LEVEL_NOTICE)}await this.services.setting.realiseSetting();await this.services.setting.saveSettingData()}});this.addCommand({id:"livesync-scan-files",name:"Scan storage and database again",callback:async()=>{await this.services.vault.scanVault(!0)}});this.addCommand({id:"livesync-runbatch",name:"Run pended batch processes",callback:async()=>{await this.services.fileProcessing.commitPendingFileEvents()}});this.addCommand({id:"livesync-abortsync",name:"Abort synchronization immediately",callback:()=>{this.core.replicator.terminateSync()}});return Promise.resolve(!0)}__onWorkspaceReady(){this.services.appLifecycle.onReady()}_everyOnload(){this.app.workspace.onLayoutReady(this.__onWorkspaceReady.bind(this));return Promise.resolve(!0)}async _showView(viewType){const leaves=this.app.workspace.getLeavesOfType(viewType);0==leaves.length?await this.app.workspace.getLeaf(!0).setViewState({type:viewType,active:!0}):await leaves[0].setViewState({type:viewType,active:!0});leaves.length>0&&await this.app.workspace.revealLeaf(leaves[0])}onBindFunction(core,services){services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this));services.appLifecycle.handleOnLoaded(this._everyOnload.bind(this));services.API.handleShowWindow(this._showView.bind(this))}};ModuleSetupObsidian=class extends AbstractObsidianModule{_everyOnload(){this._setupManager=this.plugin.getModule(SetupManager);this.registerObsidianProtocolHandler("setuplivesync",(async conf=>{conf.settings?await this._setupManager.onUseSetupURI("unknown",`${configURIBase}${encodeURIComponent(conf.settings)}`):conf.settingsQR&&await this._setupManager.decodeQR(conf.settingsQR)}));this.addCommand({id:"livesync-setting-qr",name:"Show settings as a QR code",callback:()=>fireAndForget(this.encodeQR())});this.addCommand({id:"livesync-copysetupuri",name:"Copy settings as a new setup URI",callback:()=>fireAndForget(this.command_copySetupURI())});this.addCommand({id:"livesync-copysetupuri-short",name:"Copy settings as a new setup URI (With customization sync)",callback:()=>fireAndForget(this.command_copySetupURIWithSync())});this.addCommand({id:"livesync-copysetupurifull",name:"Copy settings as a new setup URI (Full)",callback:()=>fireAndForget(this.command_copySetupURIFull())});this.addCommand({id:"livesync-opensetupuri",name:"Use the copied setup URI (Formerly Open setup URI)",callback:()=>fireAndForget(this.command_openSetupURI())});eventHub.onEvent(EVENT_REQUEST_OPEN_SETUP_URI2,(()=>fireAndForget((()=>this.command_openSetupURI()))));eventHub.onEvent(EVENT_REQUEST_COPY_SETUP_URI2,(()=>fireAndForget((()=>this.command_copySetupURI()))));eventHub.onEvent(EVENT_REQUEST_SHOW_SETUP_QR,(()=>fireAndForget((()=>this.encodeQR()))));eventHub.onEvent("request-open-p2p-settings",(()=>fireAndForget((()=>this._setupManager.onP2PManualSetup("unknown",this.settings,!1)))));return Promise.resolve(!0)}async encodeQR(){const codeSVG=encodeQR(encodeSettingsToQRCodeData(this.settings),0);if(""==codeSVG)return"";const msg=$msg("Setup.QRCode",{qr_image:codeSVG});await this.core.confirm.confirmWithMessage("Settings QR Code",msg,["OK"],"OK");return await Promise.resolve(codeSVG)}async askEncryptingPassphrase(){return await this.core.confirm.askString("Encrypt your settings","The passphrase to encrypt the setup URI","",!0)}async command_copySetupURI(stripExtra=!0){const encryptingPassphrase=await this.askEncryptingPassphrase();if(!1===encryptingPassphrase)return;const encryptedURI=await encodeSettingsToSetupURI(this.settings,encryptingPassphrase,[...stripExtra?["pluginSyncExtendedSetting"]:[]],!0);await this.services.UI.promptCopyToClipboard("Setup URI",encryptedURI)&&this._log("Setup URI copied to clipboard",LOG_LEVEL_NOTICE)}async command_copySetupURIFull(){const encryptingPassphrase=await this.askEncryptingPassphrase();if(!1===encryptingPassphrase)return;const encryptedURI=await encodeSettingsToSetupURI(this.settings,encryptingPassphrase,[],!1);await navigator.clipboard.writeText(encryptedURI);this._log("Setup URI copied to clipboard",LOG_LEVEL_NOTICE)}async command_copySetupURIWithSync(){await this.command_copySetupURI(!1)}async command_openSetupURI(){await this._setupManager.onUseSetupURI("unknown")}onBindFunction(core,services){services.appLifecycle.handleOnLoaded(this._everyOnload.bind(this))}};ModuleDatabaseFileAccess=class extends AbstractModule{_everyOnload(){this.core.databaseFileAccess=this;return Promise.resolve(!0)}async _everyModuleTest(){if(!this.settings.enableDebugTools)return Promise.resolve(!0);const testString="Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam nec purus nec nunc",conflicts=await this.getConflictedRevs("autoTest.md");for(const rev3 of conflicts)await this.delete("autoTest.md",rev3);await this.delete("autoTest.md");await this._test("storeContent",(async()=>await this.storeContent("autoTest.md",testString)));this.localDatabase.clearCaches();await this._test("readContent",(async()=>{const content=await this.fetch("autoTest.md");return content?content.deleted?"File is deleted":await content.body.text()==testString||`Content is not same ${await content.body.text()}`:"File not found"}));await this._test("delete",(async()=>await this.delete("autoTest.md")));await this._test("read deleted content",(async()=>{const content=await this.fetch("autoTest.md");return!content||!!content.deleted||`Still exist !:${await content.body.text()},${JSON.stringify(content,void 0,2)}`}));await delay(100);return this.testDone()}async checkIsTargetFile(file){const path2=getStoragePathFromUXFileInfo(file);if(!await this.services.vault.isTargetFile(path2)){this._log(`File is not target: ${path2}`,LOG_LEVEL_VERBOSE);return!1}if(shouldBeIgnored(path2)){this._log(`File should be ignored: ${path2}`,LOG_LEVEL_VERBOSE);return!1}return!0}async delete(file,rev3){if(!await this.checkIsTargetFile(file))return!0;const fullPath=getDatabasePathFromUXFileInfo(file);try{this._log(`deleteDB By path:${fullPath}`);return await this.deleteFromDBbyPath(fullPath,rev3)}catch(ex){this._log(`Failed to delete ${fullPath}`);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}async createChunks(file,force=!1,skipCheck){return await this.__store(file,force,skipCheck,!0)}async store(file,force=!1,skipCheck){return await this.__store(file,force,skipCheck,!1)}async storeContent(path2,content){const blob=createTextBlob(content),bytes=(await blob.arrayBuffer()).byteLength,isInternal=!!path2.startsWith(".")||void 0,dummyUXFileInfo={name:path2.split("/").pop(),path:path2,stat:{size:bytes,ctime:Date.now(),mtime:Date.now(),type:"file"},body:blob,isInternal};return await this.__store(dummyUXFileInfo,!0,!1,!1)}async __store(file,force=!1,skipCheck,onlyChunks){if(!skipCheck&&!await this.checkIsTargetFile(file))return!0;if(!file){this._log("File seems bad",LOG_LEVEL_VERBOSE);return!1}const possiblyLarge=!isPlainText(file.name),content=file.body,datatype=determineTypeFromBlob(content),idPrefix=file.isInternal?ICHeader:"",fullPath=getStoragePathFromUXFileInfo(file),fullPathOnDB=getDatabasePathFromUXFileInfo(file);possiblyLarge&&this._log(`Processing: ${fullPath}`,LOG_LEVEL_VERBOSE);if(file.isInternal)if(file.deleted)file.stat={size:0,ctime:Date.now(),mtime:Date.now(),type:"file"};else if(null==file.stat){const stat=await this.core.storageAccess.statHidden(file.path);if(!stat){this._log(`Internal file not found: ${fullPath}`,LOG_LEVEL_VERBOSE);return!1}file.stat=stat}const d4={_id:idPrefix+await this.services.path.path2id(fullPath),path:fullPathOnDB,data:content,ctime:file.stat.ctime,mtime:file.stat.mtime,size:file.stat.size,children:[],datatype,type:datatype,eden:{}},msg=`STORAGE -> DB (${datatype}) `;if(await serialized("file-"+fullPath,(async()=>{if(force){this._log(msg+"Force writing "+fullPath,LOG_LEVEL_VERBOSE);return!1}try{const old=await this.localDatabase.getDBEntry(d4.path,void 0,!1,!0,!1);if(!1!==old){const oldData={data:old.data,deleted:old._deleted||old.deleted},newData={data:d4.data,deleted:d4._deleted||d4.deleted};if(oldData.deleted!=newData.deleted)return!1;if(!await isDocContentSame(old.data,newData.data))return!1;this._log(msg+"Skipped (not changed) "+fullPath+(d4._deleted||d4.deleted?" (deleted)":""),LOG_LEVEL_VERBOSE);markChangesAreSame(old,d4.mtime,old.mtime);return!0}}catch(ex){this._log(msg+"Error, Could not check the diff for the old one."+(force?"force writing.":"")+fullPath+(d4._deleted||d4.deleted?" (deleted)":""),LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE);return!force}return!1}))){this._log(msg+" Skip "+fullPath,LOG_LEVEL_VERBOSE);return!0}const ret=await this.localDatabase.putDBEntry(d4,onlyChunks);if(!1!==ret){this._log(msg+fullPath);eventHub.emitEvent("file-saved")}return 0!=ret}async getConflictedRevs(file){if(!await this.checkIsTargetFile(file))return[];const filename=getDatabasePathFromUXFileInfo(file),doc=await this.localDatabase.getDBEntryMeta(filename,{conflicts:!0},!0);return!1===doc?[]:doc._conflicts||[]}async fetch(file,rev3,waitForReady,skipCheck=!1){if(skipCheck&&!await this.checkIsTargetFile(file))return!1;const entry=await this.fetchEntry(file,rev3,waitForReady,!0);if(!1===entry)return!1;const data=createBlob(readContent(entry)),path2=stripAllPrefixes(entry.path),fileInfo={name:path2.split("/").pop(),path:path2,stat:{size:entry.size,ctime:entry.ctime,mtime:entry.mtime,type:"file"},body:data,deleted:entry.deleted||entry._deleted};isInternalMetadata(entry.path)&&(fileInfo.isInternal=!0);return fileInfo}async fetchEntryMeta(file,rev3,skipCheck=!1){const dbFileName=getDatabasePathFromUXFileInfo(file);if(skipCheck&&!await this.checkIsTargetFile(file))return!1;const doc=await this.localDatabase.getDBEntryMeta(dbFileName,rev3?{rev:rev3}:void 0,!0);return!1!==doc&&doc}async fetchEntryFromMeta(meta,waitForReady=!0,skipCheck=!1){if(skipCheck&&!await this.checkIsTargetFile(meta.path))return!1;const doc=await this.localDatabase.getDBEntryFromMeta(meta,!1,waitForReady);return!1!==doc&&doc}async fetchEntry(file,rev3,waitForReady=!0,skipCheck=!1){if(skipCheck&&!await this.checkIsTargetFile(file))return!1;const entry=await this.fetchEntryMeta(file,rev3,!0);return!1!==entry&&await this.fetchEntryFromMeta(entry,waitForReady,!0)}async deleteFromDBbyPath(fullPath,rev3){if(!await this.checkIsTargetFile(fullPath)){this._log(`storeFromStorage: File is not target: ${fullPath}`);return!0}const opt=rev3?{rev:rev3}:void 0,ret=await this.localDatabase.deleteDBEntry(fullPath,opt);eventHub.emitEvent("file-saved");return ret}onBindFunction(core,services){services.appLifecycle.handleOnLoaded(this._everyOnload.bind(this));services.test.handleTest(this._everyModuleTest.bind(this))}};ModuleFileHandler=class extends AbstractModule{get db(){return this.core.databaseFileAccess}get storage(){return this.core.storageAccess}_everyOnloadStart(){this.core.fileHandler=this;return Promise.resolve(!0)}async readFileFromStub(file){if("body"in file&&file.body)return file;const readFile=await this.storage.readStubContent(file);if(!readFile)throw new Error(`File ${file.path} is not exist on the storage`);return readFile}async storeFileToDB(info3,force=!1,onlyChunks=!1){const file="string"==typeof info3?this.storage.getFileStub(info3):info3;if(null==file){this._log(`File ${info3} is not exist on the storage`,LOG_LEVEL_VERBOSE);return!1}if(file.isInternal){this._log(`Internal file ${file.path} is not allowed to be processed on processFileEvent`,LOG_LEVEL_VERBOSE);return!1}const entry=await this.db.fetchEntry(file,void 0,!0,!0);if(!entry||entry.deleted||entry._deleted){const readFile=await this.readFileFromStub(file);return onlyChunks?await this.db.createChunks(readFile,!1,!0):await this.db.store(readFile)}let shouldApplied=!1;if(force||onlyChunks){const readFile=await this.readFileFromStub(file);return onlyChunks?await this.db.createChunks(readFile,!0,!0):await this.db.store(readFile,!0,!0)}{compareFileFreshness(file,entry)!==EVEN&&(shouldApplied=!0);let readFile;if(!shouldApplied){readFile=await this.readFileFromStub(file);if(!readFile){this._log(`File ${file.path} is not exist on the storage`,LOG_LEVEL_NOTICE);return!1}await isDocContentSame(getDocDataAsArray(entry.data),readFile.body)?markChangesAreSame(readFile,readFile.stat.mtime,entry.mtime):shouldApplied=!0}if(!shouldApplied){this._log(`File ${file.path} is not changed`,LOG_LEVEL_VERBOSE);return!0}readFile||(readFile=await this.readFileFromStub(file));return onlyChunks?await this.db.createChunks(readFile,!1,!0):await this.db.store(readFile,!1,!0)}}async deleteFileFromDB(info3){const file="string"==typeof info3?this.storage.getFileStub(info3):info3;if(null==file){this._log(`File ${info3} is not exist on the storage`,LOG_LEVEL_VERBOSE);return!1}if(file.isInternal){this._log(`Internal file ${file.path} is not allowed to be processed on processFileEvent`,LOG_LEVEL_VERBOSE);return!1}const entry=await this.db.fetchEntry(file,void 0,!0,!0);if(!entry||entry.deleted||entry._deleted){this._log(`File ${file.path} is not exist or already deleted on the database`,LOG_LEVEL_VERBOSE);return!1}return(await this.db.getConflictedRevs(file)).length>0?await this.db.delete(file,entry._rev):await this.db.delete(file)}async deleteRevisionFromDB(info3,rev3){return await this.db.delete(info3,rev3)}async resolveConflictedByDeletingRevision(info3,rev3){const path2=getStoragePathFromUXFileInfo(info3);if(!await this.deleteRevisionFromDB(info3,rev3)){this._log(`Failed to delete the conflicted revision ${rev3} of ${path2}`,LOG_LEVEL_VERBOSE);return!1}if(!await this.dbToStorageWithSpecificRev(info3,rev3,!0)){this._log(`Failed to apply the resolved revision ${rev3} of ${path2} to the storage`,LOG_LEVEL_VERBOSE);return!1}}async dbToStorageWithSpecificRev(info3,rev3,force){const file="string"==typeof info3?this.storage.getFileStub(info3):info3;if(null==file){this._log(`File ${info3} is not exist on the storage`,LOG_LEVEL_VERBOSE);return!1}const docEntry=await this.db.fetchEntryMeta(file,rev3,!0);if(!docEntry){this._log(`File ${file.path} is not exist on the database`,LOG_LEVEL_VERBOSE);return!1}return await this.dbToStorage(docEntry,file,force)}async dbToStorage(entryInfo,info3,force){const mode=null==("string"==typeof info3?this.storage.getFileStub(info3):info3)?"create":"modify",pathFromEntryInfo="string"==typeof entryInfo?entryInfo:getPath2(entryInfo),docEntry=await this.db.fetchEntryMeta(pathFromEntryInfo,void 0,!0);if(!docEntry){this._log(`File ${pathFromEntryInfo} is not exist on the database`,LOG_LEVEL_VERBOSE);return!1}const path2=getPath2(docEntry);if((await this.db.getConflictedRevs(path2)).length>0&&!this.settings.writeDocumentsIfConflicted){await this.services.conflict.queueCheckForIfOpen(path2);return!0}const existDoc=this.storage.getStub(path2);if(existDoc&&existDoc.isFolder){this._log(`Folder ${path2} is already exist on the storage as a folder`,LOG_LEVEL_VERBOSE);return!0}const existOnDB=!(docEntry._deleted||docEntry.deleted),existOnStorage=null!=existDoc;if(!existOnDB&&!existOnStorage){this._log(`File ${path2} seems to be deleted, but already not on storage`,LOG_LEVEL_VERBOSE);return!0}if(!existOnDB&&existOnStorage){await this.storage.deleteVaultItem(path2);return!0}const docRead=await this.db.fetchEntryFromMeta(docEntry);if(!docRead){this._log(`File ${path2} is not exist on the database`,LOG_LEVEL_VERBOSE);return!1}if(!this.settings.processSizeMismatchedFiles&&0!=docRead.size&&docRead.size!==readAsBlob(docRead).size){this._log(`File ${path2} seems to be corrupted! Writing prevented. (${docRead.size} != ${readAsBlob(docRead).size})`,LOG_LEVEL_NOTICE);return!1}const docData=readContent(docRead);if(existOnStorage&&!force){let shouldApplied=!1;compareFileFreshness(existDoc,docEntry)!==EVEN&&(shouldApplied=!0);if(!shouldApplied){const readFile=await this.readFileFromStub(existDoc);if(await isDocContentSame(docData,readFile.body)){shouldApplied=!1;markChangesAreSame(docRead,docRead.mtime,existDoc.stat.mtime)}else shouldApplied=!0}if(!shouldApplied){this._log(`File ${docRead.path} is not changed`,LOG_LEVEL_VERBOSE);return!0}}else this._log(`File ${docRead.path} ${existOnStorage?"(new) ":""} ${force?" (forced)":""}`,LOG_LEVEL_VERBOSE);await this.storage.ensureDir(path2);const ret=await this.storage.writeFileAuto(path2,docData,{ctime:docRead.ctime,mtime:docRead.mtime});await this.storage.touched(path2);this.storage.triggerFileEvent(mode,path2);return ret}async _anyHandlerProcessesFileEvent(item){const eventItem=item.args,type=item.type,path2=eventItem.file.path;if(!await this.services.vault.isTargetFile(path2)){this._log(`File ${path2} is not the target file`,LOG_LEVEL_VERBOSE);return!1}if(shouldBeIgnored(path2)){this._log(`File ${path2} should be ignored`,LOG_LEVEL_VERBOSE);return!1}const lockKey=`processFileEvent-${path2}`;return await serialized(lockKey,(async()=>{switch(type){case"CREATE":case"CHANGED":return await this.storeFileToDB(item.args.file);case"DELETE":return await this.deleteFileFromDB(item.args.file);case"INTERNAL":return!1;default:this._log(`Unsupported event type: ${type}`,LOG_LEVEL_VERBOSE);return!1}}))}async _anyProcessReplicatedDoc(entry){return await serialized(entry.path,(async()=>{var _a8,_b5;if(!await this.services.vault.isTargetFile(entry.path)){this._log(`File ${entry.path} is not the target file`,LOG_LEVEL_VERBOSE);return!1}if(this.services.vault.isFileSizeTooLarge(entry.size)){this._log(`File ${entry.path} is too large (on database) to be processed`,LOG_LEVEL_VERBOSE);return!1}if(shouldBeIgnored(entry.path)){this._log(`File ${entry.path} should be ignored`,LOG_LEVEL_VERBOSE);return!1}const path2=getPath2(entry),targetFile=this.storage.getStub(getPathWithoutPrefix2(entry));if(targetFile&&targetFile.isFolder){this._log(`${getPath2(entry)} is already exist as the folder`);return!0}{if(targetFile&&this.services.vault.isFileSizeTooLarge(targetFile.stat.size)){this._log(`File ${targetFile.path} is too large (on storage) to be processed`,LOG_LEVEL_VERBOSE);return!1}this._log(`Processing ${path2} (${entry._id.substring(0,8)} :${null==(_a8=entry._rev)?void 0:_a8.substring(0,5)}) : Started...`,LOG_LEVEL_VERBOSE);eventHub.emitEvent("conflict-cancelled",path2);const ret=await this.dbToStorage(entry,targetFile);this._log(`Processing ${path2} (${entry._id.substring(0,8)} :${null==(_b5=entry._rev)?void 0:_b5.substring(0,5)}) : Done`);return ret}}))}async createAllChunks(showingNotice){this._log("Collecting local files on the storage",LOG_LEVEL_VERBOSE);const semaphore=Semaphore(10);let processed=0;const filesStorageSrc=this.storage.getFiles(),incProcessed=()=>{processed++;processed%25==0&&this._log(`Creating missing chunks: ${processed} of ${total} files`,showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"chunkCreation")},total=filesStorageSrc.length,procAllChunks=filesStorageSrc.map((async file=>{if(!await this.services.vault.isTargetFile(file)){incProcessed();return!0}if(this.services.vault.isFileSizeTooLarge(file.stat.size)){incProcessed();return!0}if(shouldBeIgnored(file.path)){incProcessed();return!0}const release=await semaphore.acquire();incProcessed();try{await this.storeFileToDB(file,!1,!0)}catch(ex){this._log(ex,LOG_LEVEL_VERBOSE)}finally{release()}}));await Promise.all(procAllChunks);this._log(`Creating chunks Done: ${processed} of ${total} files`,showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"chunkCreation")}onBindFunction(core,services){services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this));services.fileProcessing.handleProcessFileEvent(this._anyHandlerProcessesFileEvent.bind(this));services.replication.handleProcessSynchroniseResult(this._anyProcessReplicatedDoc.bind(this))}};ObsHttpHandler=class extends FetchHttpHandler{constructor(options,reverseProxyNoSignUrl){super(options);this.requestTimeoutInMs=void 0===options?void 0:options.requestTimeout;this.reverseProxyNoSignUrl=reverseProxyNoSignUrl}async handle(request2,{abortSignal}={}){if(null==abortSignal?void 0:abortSignal.aborted){const abortError=new Error("Request aborted");abortError.name="AbortError";return Promise.reject(abortError)}let path2=request2.path;if(request2.query){const queryString=buildQueryString(request2.query);queryString&&(path2+=`?${queryString}`)}const{port,method}=request2;let url=`${request2.protocol}//${request2.hostname}${port?`:${port}`:""}${path2}`;if(void 0!==this.reverseProxyNoSignUrl&&""!==this.reverseProxyNoSignUrl){const urlObj=new URL(url);urlObj.host=this.reverseProxyNoSignUrl;url=urlObj.href}const body="GET"===method||"HEAD"===method?void 0:request2.body,transformedHeaders={};for(const key3 of Object.keys(request2.headers)){const keyLower=key3.toLowerCase();"host"!==keyLower&&"content-length"!==keyLower&&(transformedHeaders[keyLower]=request2.headers[key3])}let contentType;void 0!==transformedHeaders["content-type"]&&(contentType=transformedHeaders["content-type"]);let transformedBody=body;ArrayBuffer.isView(body)&&(transformedBody=new Uint8Array(body.buffer).buffer);const param={body:transformedBody,headers:transformedHeaders,method,url,contentType},raceOfPromises=[(0,import_obsidian.requestUrl)(param).then((rsp=>{const headers=rsp.headers,headersLower={};for(const key3 of Object.keys(headers))headersLower[key3.toLowerCase()]=headers[key3];const stream=new ReadableStream({start(controller){controller.enqueue(new Uint8Array(rsp.arrayBuffer));controller.close()}});return{response:new HttpResponse({headers:headersLower,statusCode:rsp.status,body:stream})}})),requestTimeout(this.requestTimeoutInMs)];abortSignal&&raceOfPromises.push(new Promise(((resolve,reject)=>{abortSignal.onabort=()=>{const abortError=new Error("Request aborted");abortError.name="AbortError";reject(abortError)}})));return Promise.race(raceOfPromises)}};import_obsidian.Notice;ModuleObsidianAPI=class extends AbstractObsidianModule{constructor(){super(...arguments);this._authHeader=new AuthorizationHeaderGenerator;this._previousErrors=new Set;this.last_successful_post=!1}showError(msg,max_log_level=LEVEL_NOTICE){const level=this._previousErrors.has(msg)?LEVEL_INFO:max_log_level;this._log(msg,level);if(!this._previousErrors.has(msg)){this._previousErrors.add(msg);eventHub.emitEvent("on-unresolved-error")}}clearErrors(){this._previousErrors.clear();eventHub.emitEvent("on-unresolved-error")}_customFetchHandler(){this._customHandler||(this._customHandler=new ObsHttpHandler(void 0,void 0));return this._customHandler}_getLastPostFailedBySize(){return!this.last_successful_post}async __fetchByAPI(url,authHeader,opts){var _a8,_b5;const body=null==opts?void 0:opts.body,optHeaders={};if(opts&&"headers"in opts)if(opts.headers instanceof Headers)opts.headers.forEach(((value,key3)=>{optHeaders[key3]=value}));else for(const[key3,value]of Object.entries(opts.headers))optHeaders[key3]=value;const transformedHeaders={...optHeaders};""!=authHeader&&(transformedHeaders.authorization=authHeader);delete transformedHeaders.host;delete transformedHeaders.Host;delete transformedHeaders["content-length"];delete transformedHeaders["Content-Length"];const requestParam={url,method:null==opts?void 0:opts.method,body,headers:transformedHeaders,contentType:null!=(_b5=null!=(_a8=null==transformedHeaders?void 0:transformedHeaders["content-type"])?_a8:null==transformedHeaders?void 0:transformedHeaders["Content-Type"])?_b5:"application/json"},r4=await fetchByAPI(requestParam,!0);return new Response(r4.arrayBuffer,{headers:r4.headers,status:r4.status,statusText:`${r4.status}`})}async fetchByAPI(url,localURL,method,authHeader,opts){const body=null==opts?void 0:opts.body,size=body?` (${body.length})`:"";try{const r4=await this.__fetchByAPI(url,authHeader,opts);this.plugin.requestCount.value=this.plugin.requestCount.value+1;this.last_successful_post="POST"!=method&&"PUT"!=method||r4.status-r4.status%100==200;this._log(`HTTP:${method}${size} to:${localURL} -> ${r4.status}`,LOG_LEVEL_DEBUG);return r4}catch(ex){this._log(`HTTP:${method}${size} to:${localURL} -> failed`,LOG_LEVEL_VERBOSE);-1!==url.toString().indexOf("_bulk_docs")&&(this.last_successful_post=!1);this._log(ex);throw ex}finally{this.plugin.responseCount.value=this.plugin.responseCount.value+1}}async _connectRemoteCouchDB(uri,auth,disableRequestURI,passphrase,useDynamicIterationCount,performSetup,skipInfo,compression,customHeaders,useRequestAPI,getPBKDF2Salt){if(!isValidRemoteCouchDBURI(uri))return"Remote URI is not valid";if(uri.toLowerCase()!=uri)return"Remote URI and database name could not contain capital letters.";if(-1!==uri.indexOf(" "))return"Remote URI and database name could not contain spaces.";if(!this.core.managers.networkManager.isOnline)return"Network is offline";const db=new index_es_default(uri,{adapter:"http",auth:"username"in auth?auth:void 0,skip_setup:!performSetup,fetch:async(url,opts)=>{var _a8;const authHeader=await this._authHeader.getAuthorizationHeader(auth);let size="";const localURL=url.toString().substring(uri.length),method=null!=(_a8=null==opts?void 0:opts.method)?_a8:"GET";if(null==opts?void 0:opts.body){const opts_length=opts.body.toString().length;if(opts_length>1e7&&isCloudantURI(uri)){this.last_successful_post=!1;this._log("This request should fail on IBM Cloudant.",LOG_LEVEL_VERBOSE);throw new Error("This request should fail on IBM Cloudant.")}size=` (${opts_length})`}try{const headers=new Headers(null==opts?void 0:opts.headers);if(customHeaders)for(const[key3,value]of Object.entries(customHeaders))key3&&value&&headers.append(key3,value);"username"in auth||headers.append("authorization",authHeader);try{this.plugin.requestCount.value=this.plugin.requestCount.value+1;const response=await(useRequestAPI?this.__fetchByAPI(url.toString(),authHeader,{...opts,headers}):fetch(url,{...opts,headers}));this.last_successful_post="POST"!=method&&"PUT"!=method||response.ok;this._log(`HTTP:${method}${size} to:${localURL} -> ${response.status}`,LOG_LEVEL_DEBUG);if(2!==Math.floor(response.status/100))if(404==response.status)"GET"===method&&-1===localURL.indexOf("/_local/")&&this._log("Just checkpoint or some server information has been missing. The 404 error shown above is not an error.",LOG_LEVEL_VERBOSE);else{const r4=response.clone();this._log(`The request may have failed. The reason sent by the server: ${r4.status}: ${r4.statusText}`,LOG_LEVEL_NOTICE);try{const result=await r4.text();this._log(result,LOG_LEVEL_VERBOSE)}catch(_){this._log("Cloud not fetch response body",LOG_LEVEL_VERBOSE);this._log(_,LOG_LEVEL_VERBOSE)}}this.clearErrors();return response}catch(ex){if(ex instanceof TypeError){if(useRequestAPI){this._log("Failed to request by API.");throw ex}this._log("Failed to fetch by native fetch API. Trying to fetch by API to get more information.");const resp2=await this.fetchByAPI(url.toString(),localURL,method,authHeader,{...opts,headers});if(resp2.status/100==2){this.showError("The request was successful by API. But the native fetch API failed! Please check CORS settings on the remote database!. While this condition, you cannot enable LiveSync",LOG_LEVEL_NOTICE);return resp2}const r22=resp2.clone(),msg=await r22.text();this.showError(`Failed to fetch by API. ${resp2.status}: ${msg}`,LOG_LEVEL_NOTICE);return resp2}throw ex}}catch(ex){this._log(`HTTP:${method}${size} to:${localURL} -> failed`,LOG_LEVEL_VERBOSE);const msg=ex instanceof Error?`${null==ex?void 0:ex.name}:${null==ex?void 0:ex.message}`:null==ex?void 0:ex.toString();this.showError(`Failed to fetch: ${msg}`);this._log(ex,LOG_LEVEL_VERBOSE);-1!==url.toString().indexOf("_bulk_docs")&&(this.last_successful_post=!1);this._log(ex);throw ex}finally{this.plugin.responseCount.value=this.plugin.responseCount.value+1}}});replicationFilter(db,compression);disableEncryption();"false"!==passphrase&&"string"==typeof passphrase&&enableEncryption(db,passphrase,useDynamicIterationCount,!1,getPBKDF2Salt,this.settings.E2EEAlgorithm);if(skipInfo)return{db,info:{db_name:"",doc_count:0,update_seq:""}};try{const info3=await db.info();return{db,info:info3}}catch(ex){const msg=`${null==ex?void 0:ex.name}:${null==ex?void 0:ex.message}`;this._log(ex,LOG_LEVEL_VERBOSE);return msg}}_isMobile(){return this.app.isMobile}_vaultName(){return this.app.vault.getName()}_getVaultName(){var _a8;return this.services.vault.vaultName()+((null==(_a8=this.settings)?void 0:_a8.additionalSuffixOfDatabaseName)?"-"+this.settings.additionalSuffixOfDatabaseName:"")}_getActiveFilePath(){const file=this.app.workspace.getActiveFile();if(file)return getPathFromTFile(file)}_anyGetAppId(){return`${"appId"in this.app?this.app.appId:""}`}_reportUnresolvedMessages(){return Promise.resolve([...this._previousErrors])}_getAppVersion(){var _a8,_b5;const match3=(null!=(_b5=null==(_a8=globalThis.navigator)?void 0:_a8.userAgent)?_b5:"").match(/obsidian\/([0-9]+\.[0-9]+\.[0-9]+)/);return match3&&match3.length>=2?match3[1]:"0.0.0"}_getPluginVersion(){return this.plugin.manifest.version}onBindFunction(core,services){services.API.handleGetCustomFetchHandler(this._customFetchHandler.bind(this));services.API.handleIsLastPostFailedDueToPayloadSize(this._getLastPostFailedBySize.bind(this));services.remote.handleConnect(this._connectRemoteCouchDB.bind(this));services.API.handleIsMobile(this._isMobile.bind(this));services.vault.handleGetVaultName(this._getVaultName.bind(this));services.vault.handleVaultName(this._vaultName.bind(this));services.vault.handleGetActiveFilePath(this._getActiveFilePath.bind(this));services.API.handleGetAppID(this._anyGetAppId.bind(this));services.API.handleGetAppVersion(this._getAppVersion.bind(this));services.API.handleGetPluginVersion(this._getPluginVersion.bind(this));services.appLifecycle.reportUnresolvedMessages(this._reportUnresolvedMessages.bind(this))}};ModuleObsidianEvents=class extends AbstractObsidianModule{constructor(){super(...arguments);this.hasFocus=!0;this.isLastHidden=!1}_everyOnloadStart(){this.plugin.registerEvent(this.app.vault.on("rename",((file,oldPath)=>{eventHub.emitEvent("file-renamed",{newPath:file.path,old:oldPath})})));this.plugin.registerEvent(this.app.workspace.on("active-leaf-change",(()=>eventHub.emitEvent("leaf-active-changed"))));return Promise.resolve(!0)}_performRestart(){this.__performAppReload()}__performAppReload(){this.app.commands.executeCommandById("app:reload")}swapSaveCommand(){var _a8,_b5;this._log("Modifying callback of the save command",LOG_LEVEL_VERBOSE);const saveCommandDefinition=null==(_b5=null==(_a8=this.app.commands)?void 0:_a8.commands)?void 0:_b5["editor:save-file"],save2=null==saveCommandDefinition?void 0:saveCommandDefinition.callback;if("function"==typeof save2){this.initialCallback=save2;saveCommandDefinition.callback=()=>{scheduleTask("syncOnEditorSave",250,(()=>{if(this.services.appLifecycle.hasUnloaded()){this._log("Unload and remove the handler.",LOG_LEVEL_VERBOSE);saveCommandDefinition.callback=this.initialCallback;this.initialCallback=void 0}else if(this.settings.syncOnEditorSave){this._log("Sync on Editor Save.",LOG_LEVEL_VERBOSE);fireAndForget((()=>this.services.replication.replicateByEvent()))}}));save2()}}const _this=this;window.CodeMirrorAdapter?window.CodeMirrorAdapter.commands.save=()=>{_this.app.commands.executeCommandById("editor:save-file")}:this._log("CodeMirrorAdapter is not available")}registerWatchEvents(){this.setHasFocus=this.setHasFocus.bind(this);this.watchWindowVisibility=this.watchWindowVisibility.bind(this);this.watchWorkspaceOpen=this.watchWorkspaceOpen.bind(this);this.watchOnline=this.watchOnline.bind(this);this.plugin.registerEvent(this.app.workspace.on("file-open",this.watchWorkspaceOpen));this.plugin.registerDomEvent(document,"visibilitychange",this.watchWindowVisibility);this.plugin.registerDomEvent(window,"focus",(()=>this.setHasFocus(!0)));this.plugin.registerDomEvent(window,"blur",(()=>this.setHasFocus(!1)));this.plugin.registerDomEvent(window,"online",this.watchOnline);this.plugin.registerDomEvent(window,"offline",this.watchOnline)}setHasFocus(hasFocus){this.hasFocus=hasFocus;this.watchWindowVisibility()}watchWindowVisibility(){scheduleTask("watch-window-visibility",100,(()=>fireAndForget((()=>this.watchWindowVisibilityAsync()))))}watchOnline(){scheduleTask("watch-online",500,(()=>fireAndForget((()=>this.watchOnlineAsync()))))}async watchOnlineAsync(){if(navigator.onLine&&this.localDatabase.needScanning){this.localDatabase.needScanning=!1;await this.services.vault.scanVault()}}async watchWindowVisibilityAsync(){if(this.settings.suspendFileWatching)return;if(!this.settings.isConfigured)return;if(!this.services.appLifecycle.isReady())return;if(this.isLastHidden&&!this.hasFocus)return;const isHidden=document.hidden;if(this.isLastHidden!==isHidden){this.isLastHidden=isHidden;await this.services.fileProcessing.commitPendingFileEvents();if(isHidden)await this.services.appLifecycle.onSuspending();else{if(this.services.appLifecycle.isSuspended())return;if(!this.hasFocus)return;await this.services.appLifecycle.onResuming();await this.services.appLifecycle.onResumed()}}}watchWorkspaceOpen(file){this.settings.suspendFileWatching||this.settings.isConfigured&&this.services.appLifecycle.isReady()&&file&&scheduleTask("watch-workspace-open",500,(()=>fireAndForget((()=>this.watchWorkspaceOpenAsync(file)))))}async watchWorkspaceOpenAsync(file){if(!this.settings.suspendFileWatching&&this.settings.isConfigured&&this.services.appLifecycle.isReady()){await this.services.fileProcessing.commitPendingFileEvents();if(null!=file){this.settings.syncOnFileOpen&&!this.services.appLifecycle.isSuspended()&&await this.services.replication.replicateByEvent();await this.services.conflict.queueCheckForIfOpen(file.path)}}}_everyOnLayoutReady(){this.swapSaveCommand();this.registerWatchEvents();return Promise.resolve(!0)}_askReload(message){this.services.appLifecycle.isReloadingScheduled()?this._log("Reloading is already scheduled",LOG_LEVEL_VERBOSE):scheduleTask("configReload",250,(async()=>{const ret=await this.core.confirm.askSelectStringDialogue(message||"Do you want to restart and reload Obsidian now?",["Yes, schedule a restart after stabilisation","Yes, restart immediately","No, Leave it to me"],{defaultAction:"No, Leave it to me"});"Yes, restart immediately"==ret?this.__performAppReload():"Yes, schedule a restart after stabilisation"==ret&&this.services.appLifecycle.scheduleRestart()}))}_scheduleAppReload(){if(!this.core._totalProcessingCount){const __tick=reactiveSource(0);this.core._totalProcessingCount=reactive((()=>{const dbCount=this.core.databaseQueueCount.value,replicationCount=this.core.replicationResultCount.value,storageApplyingCount=this.core.storageApplyingCount.value,chunkCount=collectingChunks.value,pluginScanCount=pluginScanningCount.value,hiddenFilesCount=hiddenFilesEventCount.value+hiddenFilesProcessingCount.value,conflictProcessCount=this.core.conflictProcessQueueCount.value,e3=this.core.pendingFileEventCount.value,proc=this.core.processingFileEventCount.value;__tick.value;return dbCount+replicationCount+storageApplyingCount+chunkCount+pluginScanCount+hiddenFilesCount+conflictProcessCount+e3+proc}));this.plugin.registerInterval(setInterval((()=>{__tick.value++}),1e3));let stableCheck=3;this.core._totalProcessingCount.onChanged((e3=>{if(0==e3.value){stableCheck--<=0&&this.__performAppReload();this._log(`Obsidian will be restarted soon! (Within ${stableCheck} seconds)`,LOG_LEVEL_NOTICE,"restart-notice")}else stableCheck=3}))}}onBindFunction(core,services){services.appLifecycle.handleLayoutReady(this._everyOnLayoutReady.bind(this));services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this));services.appLifecycle.handlePerformRestart(this._performRestart.bind(this));services.appLifecycle.handleAskRestart(this._askReload.bind(this));services.appLifecycle.handleScheduleRestart(this._scheduleAppReload.bind(this))}};setLevelClass=(el,level)=>{switch(level){case LEVEL_POWER_USER:el.addClass("sls-setting-poweruser");break;case LEVEL_ADVANCED:el.addClass("sls-setting-advanced");break;case LEVEL_EDGE_CASE:el.addClass("sls-setting-edgecase");break;default:}};LiveSyncSetting=class _LiveSyncSetting extends import_obsidian.Setting{constructor(containerEl){super(containerEl);this.watchDirtyKeys=[];this.holdValue=!1;this.descBuf="";this.nameBuf="";this.placeHolderBuf="";this.hasPassword=!1;this.updateHandlers=new Set;this.prevStatus={};_LiveSyncSetting.env.settingComponents.push(this)}_createDocStub(key3,value){var _a8,_b5,_c3,_d2;{const paneName=findAttrFromParent(this.settingEl,"data-pane"),panelName=findAttrFromParent(this.settingEl,"data-panel");createStub("string"==typeof this.nameBuf?this.nameBuf:null!=(_b5=null==(_a8=this.nameBuf.textContent)?void 0:_a8.toString())?_b5:"",key3,"string"==typeof value?value:null!=(_d2=null==(_c3=value.textContent)?void 0:_c3.toString())?_d2:"",panelName,paneName)}}setDesc(desc){this.descBuf=desc;this._createDocStub("desc",desc);super.setDesc(desc);return this}setName(name){this.nameBuf=name;this._createDocStub("name",name);super.setName(name);return this}setAuto(key3,opt){this.autoWireSetting(key3,opt);return this}autoWireSetting(key3,opt){const conf=getConfig(key3);if(!conf)return;const name=`${conf.name}${statusDisplay(conf.status)}`;this.setName(name);conf.desc&&this.setDesc(conf.desc);this._createDocStub("key",key3);conf.obsolete&&this._createDocStub("is_obsolete","true");conf.level&&this._createDocStub("level",conf.level);this.holdValue=(null==opt?void 0:opt.holdValue)||this.holdValue;this.selfKey=key3;(conf.obsolete||(null==opt?void 0:opt.obsolete))&&this.settingEl.toggleClass("sls-setting-obsolete",!0);(null==opt?void 0:opt.onUpdate)&&this.addOnUpdate(opt.onUpdate);const stat=this._getComputedStatus();!1===stat.visibility&&this.settingEl.toggleClass("sls-setting-hidden",!stat.visibility);return conf}autoWireComponent(component2,conf,opt){this.placeHolderBuf=(null==conf?void 0:conf.placeHolder)||(null==opt?void 0:opt.placeHolder)||"";(null==conf?void 0:conf.level)==LEVEL_ADVANCED?this.settingEl.toggleClass("sls-setting-advanced",!0):(null==conf?void 0:conf.level)==LEVEL_POWER_USER&&this.settingEl.toggleClass("sls-setting-poweruser",!0);this.placeHolderBuf&&component2 instanceof import_obsidian.TextComponent&&component2.setPlaceholder(this.placeHolderBuf);(null==opt?void 0:opt.onUpdate)&&this.addOnUpdate(opt.onUpdate)}async commitValue(value){const key3=this.selfKey;if(void 0!==key3&&value!=_LiveSyncSetting.env.editingSettings[key3]){_LiveSyncSetting.env.editingSettings[key3]=value;this.holdValue||await _LiveSyncSetting.env.saveSettings([key3])}_LiveSyncSetting.env.requestUpdate()}autoWireText(key3,opt){const conf=this.autoWireSetting(key3,opt);this.addText((text2=>{this.autoWiredComponent=text2;const setValue=wrapMemo((value=>{text2.setValue(value)}));this.invalidateValue=()=>setValue(`${_LiveSyncSetting.env.editingSettings[key3]}`);this.invalidateValue();text2.onChange((async value=>{await this.commitValue(value)}));if(null==opt?void 0:opt.isPassword){text2.inputEl.setAttribute("type","password");this.hasPassword=!0}this.autoWireComponent(this.autoWiredComponent,conf,opt)}));return this}autoWireTextArea(key3,opt){const conf=this.autoWireSetting(key3,opt);this.addTextArea((text2=>{this.autoWiredComponent=text2;const setValue=wrapMemo((value=>{text2.setValue(value)}));this.invalidateValue=()=>setValue(`${_LiveSyncSetting.env.editingSettings[key3]}`);this.invalidateValue();text2.onChange((async value=>{await this.commitValue(value)}));if(null==opt?void 0:opt.isPassword){text2.inputEl.setAttribute("type","password");this.hasPassword=!0}this.autoWireComponent(this.autoWiredComponent,conf,opt)}));return this}autoWireNumeric(key3,opt){const conf=this.autoWireSetting(key3,opt);this.addText((text2=>{this.autoWiredComponent=text2;void 0!==opt.clampMin&&text2.inputEl.setAttribute("min",`${opt.clampMin}`);void 0!==opt.clampMax&&text2.inputEl.setAttribute("max",`${opt.clampMax}`);let lastError=!1;const setValue=wrapMemo((value=>{text2.setValue(value)}));this.invalidateValue=()=>{lastError||setValue(`${_LiveSyncSetting.env.editingSettings[key3]}`)};this.invalidateValue();text2.onChange((async TextValue=>{var _a8,_b5;const value=Number(TextValue);let hasError=!1;isNaN(value)&&(hasError=!0);void 0!==opt.clampMax&&opt.clampMax<value&&(hasError=!0);void 0!==opt.clampMin&&opt.clampMin>value&&(opt.acceptZero&&0==value||(hasError=!0));if(hasError){this.setTooltip($msg("liveSyncSetting.valueShouldBeInRange",{min:(null==(_a8=opt.clampMin)?void 0:_a8.toString())||"~",max:(null==(_b5=opt.clampMax)?void 0:_b5.toString())||"~"}));text2.inputEl.toggleClass("sls-item-invalid-value",!0);lastError=!0;return!1}lastError=!1;this.setTooltip("");text2.inputEl.toggleClass("sls-item-invalid-value",!1);await this.commitValue(value)}));text2.inputEl.setAttr("type","number");this.autoWireComponent(this.autoWiredComponent,conf,opt)}));return this}autoWireToggle(key3,opt){const conf=this.autoWireSetting(key3,opt);this.addToggle((toggle=>{this.autoWiredComponent=toggle;const setValue=wrapMemo((value=>{toggle.setValue((null==opt?void 0:opt.invert)?!value:value)}));this.invalidateValue=()=>{var _a8;return setValue(null!=(_a8=_LiveSyncSetting.env.editingSettings[key3])&&_a8)};this.invalidateValue();toggle.onChange((async value=>{await this.commitValue((null==opt?void 0:opt.invert)?!value:value)}));this.autoWireComponent(this.autoWiredComponent,conf,opt)}));return this}autoWireDropDown(key3,opt){const conf=this.autoWireSetting(key3,opt);this.addDropdown((dropdown=>{this.autoWiredComponent=dropdown;const setValue=wrapMemo((value=>{dropdown.setValue(value)}));dropdown.addOptions(opt.options);this.invalidateValue=()=>setValue(_LiveSyncSetting.env.editingSettings[key3]||"");this.invalidateValue();dropdown.onChange((async value=>{await this.commitValue(value)}));this.autoWireComponent(this.autoWiredComponent,conf,opt)}));return this}addApplyButton(keys3,text2){this.addButton((button=>{this.applyButtonComponent=button;this.watchDirtyKeys=unique([...keys3,...this.watchDirtyKeys]);button.setButtonText(null!=text2?text2:$msg("liveSyncSettings.btnApply"));button.onClick((async()=>{await _LiveSyncSetting.env.saveSettings(keys3);_LiveSyncSetting.env.reloadAllSettings()}));_LiveSyncSetting.env.requestUpdate()}));return this}addOnUpdate(func){this.updateHandlers.add(func);return this}_getComputedStatus(){let newConf={};for(const handler of this.updateHandlers)newConf={...newConf,...handler()};return newConf}_applyOnUpdateHandlers(){if(this.updateHandlers.size>0){const newConf=this._getComputedStatus(),keys3=Object.keys(newConf);for(const k2 of keys3)if(!(k2 in this.prevStatus)||this.prevStatus[k2]!=newConf[k2])switch(k2){case"visibility":this.settingEl.toggleClass("sls-setting-hidden",!newConf[k2]);this.prevStatus[k2]=newConf[k2];break;case"classes":break;case"disabled":this.setDisabled(newConf[k2]||!1);this.settingEl.toggleClass("sls-setting-disabled",newConf[k2]||!1);this.prevStatus[k2]=newConf[k2];break;case"isCta":{const component2=this.autoWiredComponent;component2 instanceof import_obsidian.ButtonComponent&&(newConf[k2]?component2.setCta():component2.removeCta());this.prevStatus[k2]=newConf[k2]}break;case"isWarning":{const component2=this.autoWiredComponent;component2 instanceof import_obsidian.ButtonComponent&&newConf[k2]&&component2.setWarning();this.prevStatus[k2]=newConf[k2]}break}}}_onUpdate(){var _a8,_b5;if(this.applyButtonComponent){const isDirty2=_LiveSyncSetting.env.isSomeDirty(this.watchDirtyKeys);this.applyButtonComponent.setDisabled(!isDirty2);isDirty2?this.applyButtonComponent.setCta():this.applyButtonComponent.removeCta()}this.selfKey&&!_LiveSyncSetting.env.isDirty(this.selfKey)&&this.invalidateValue&&this.invalidateValue();if(this.holdValue&&this.selfKey){const isDirty2=_LiveSyncSetting.env.isDirty(this.selfKey),alt=isDirty2?$msg("liveSyncSetting.originalValue",{value:String(null!=(_b5=null==(_a8=_LiveSyncSetting.env.initialSettings)?void 0:_a8[this.selfKey])?_b5:"")}):"";this.controlEl.toggleClass("sls-item-dirty",isDirty2);if(!this.hasPassword){this.nameEl.toggleClass("sls-item-dirty-help",isDirty2);this.setTooltip(alt,{delay:10,placement:"right"})}}this._applyOnUpdateHandlers()}};updateInformation="# 0.25\nSince 19th July, 2025 (beta1 in 0.25.0-beta1, 13th July, 2025)\n\nThe head note of 0.25 is now in [updates_old.md](https://github.com/vrtmrz/obsidian-livesync/blob/main/updates_old.md). Because 0.25 got a lot of updates, thankfully, compatibility is kept and we do not need breaking changes! In other words, when get enough stabled. The next version will be v1.0.0. Even though it my hope.\n\n## 0.25.38\n\n17th January, 2026\n\n### Fixed\n\n- Fixed an issue where indexedDB would not close correctly on some environments, causing unexpected errors during database operations.\n\n## 0.25.37\n\n15th January, 2026\n\nThank you for your patience until my return!\n\nThis release contains minor changes discovered and fixed during test implementation.\nThere are no changes affecting usage.\n\n### Refactored\n- Logging system has been slightly refactored to improve maintainability.\n- Some import statements have been unified.\n\n## 0.25.36\n\n25th December, 2025\n\n### Improved\n\n- Now the garbage collector (V3) has been implemented. (Beta)\n - This garbage collector ensures that all devices are synchronised to the latest progress to prevent inconsistencies.\n - In other words, it makes sure that no new conflicts would have arisen.\n - This feature requires additional information (via node information), but it should be more reliable.\n - This feature requires all devices have v0.25.36 or later.\n - After the garbage collector runs, the database size may be reduced (Compaction will be run automatically after GC).\n - We should have an administrative privilege on the remote database to run this garbage collector.\n- Now the plug-in and device information is stored in the remote database.\n - This information is used for the garbage collector (V3).\n - Some additional features may be added in the future using this information.\n\n## 0.25.35\n\n24th December, 2025\n\nSorry for a small release! I would like to keep things moving along like this if possible. After all, the holidays seem to be starting soon. I will be doubled by my business until the 27th though, indeed.\n\n### Fixed\n\n- Now the conflict resolution dialogue shows correctly which device only has older APIs (#764).\n\n## 0.25.34\n\n10th December, 2025\n\n### Behaviour change\n\n- The plug-in automatically fetches the missing chunks even if `Fetch chunks on demand` is disabled.\n - This change is to avoid loss of data when receiving a bulk of revisions.\n - This can be prevented by enabling `Use Only Local Chunks` in the settings.\n- Storage application now saved during each event and restored on startup.\n- Synchronisation result application is also now saved during each event and restored on startup.\n - These may avoid some unexpected loss of data when the editor crashes.\n\n### Fixed\n\n- Now the plug-in waits for the application of pended batch changes before the synchronisation starts.\n - This may avoid some unexpected loss or unexpected conflicts.\n Plug-in sends custom headers correctly when RequestAPI is used.\n- No longer causing unexpected chunk creation during `Reset synchronisation on This Device` with bucket sync.\n\n### Refactored\n\n- Synchronisation result application process has been refactored.\n- Storage application process has been refactored.\n - Please report if you find any unexpected behaviour after this update. A bit of large refactoring.\n\n## 0.25.33\n\n05th December, 2025\n\n### New feature\n\n- We can analyse the local database with the `Analyse database usage` command.\n - This command makes a TSV-style report of the database usage, which can be pasted into spreadsheet applications.\n - The report contains the number of unique chunks and shared chunks for each document revision.\n - Unique chunks indicate the actual consumption.\n - Shared chunks indicate the reference counts from other chunks with no consumption.\n - We can find which notes or files are using large amounts of storage in the database. Or which notes cannot share chunks effectively.\n - This command is useful when optimising the database size or investigating an unexpectedly large database size.\n- We can reset the notification threshold and check the remote usage at once with the `Reset notification threshold and check the remote database usage` command.\n- Commands are available from the Command Palette, or `Hatch` pane in the settings dialogue.\n\n### Fixed\n\n- Now the plug-in resets the remote size notification threshold after rebuild.\n\n## 0.25.32\n\n02nd December, 2025\n\nNow I am back from a short (?) break! Thank you all for your patience. (It is nothing major, but the first half of the year has finally come to an end).\nAnyway, I will release the things a bit by bit. I think that we need a rehabilitation or getting gears in again.\n\n### Improved\n\n- Now the plugin warns when we are in several file-related situations that may cause unexpected behaviour (#300).\n - These errors are displayed alongside issues such as file size exceeding limits.\n - Such situations include:\n - When the document has a name which is not supported by some file systems.\n - When the vault has the same file names with different letter cases.\n\n## 0.25.31\n\n18th November, 2025\n\n### Fixed\n\n- Now fetching configuration from the server can handle the empty remote correctly (reported on #756).\n- No longer asking to switch adapters during rebuilding.\n\n## 0.25.30\n\n17th November, 2025\n\nSo sorry for the quick follow-up release, due to a humble mistake in a quick causing a matter.\n\n### Fixed\n\n- Now we can save settings correctly again (#756).\n\n## ~~0.25.28~~ 0.25.29\n\n(0.25.28 was skipped due to a packaging issue.)\n\n17th November, 2025\n\n### New feature\n\n- We can now configure hidden file synchronisation to always overwrite with the latest version (#579).\n\n### Fixed\n\n- Timing dependency issues during initialisation have been mitigated (#714)\n\n### Improved\n\n- Error logs now contain stack-traces for better inspection.\n\n## 0.25.27\n\n12th November, 2025\n\n### Improved\n\n- Now we can switch the database adapter between IndexedDB and IDB without rebuilding (#747).\n - Just a local migration will be required, but faster than a full rebuild.\n- No longer checking for the adapter by `Doctor`.\n\n### Changes\n\n- The default adapter is reverted to IDB to avoid memory leaks (#747).\n\n### Fixed (?)\n\n- Reverted QR code library to v1.4.4 (To make sure #752).\n\nOlder notes are in\n[updates_old.md](https://github.com/vrtmrz/obsidian-livesync/blob/main/updates_old.md).\n";lastVersion=~~(versionNumberString2Number("0.25.38")/1e3);SveltePanel=class{constructor(component2,mountTo,valueStore){this._componentValue=writable(void 0);this._componentValue=null!=valueStore?valueStore:writable(void 0);this._mountedComponent=mount(component2,{target:mountTo,props:{port:this._componentValue}});return this}destroy(){this._mountedComponent&&unmount(this._mountedComponent)}get componentValue(){return get2(this._componentValue)}set componentValue(value){this._componentValue.set(value)}};root_127=from_html('<div class="info-entry info-key svelte-xi83q0" role="listitem"><div class="key"> </div></div> <div class="info-entry info-item svelte-xi83q0" role="listitem"><div class="value svelte-xi83q0"> </div></div>',1);root34=from_html('<div class="info-panel svelte-xi83q0"><div class="info-grid svelte-xi83q0" role="list"></div></div>');$$css12={hash:"svelte-xi83q0",code:'.info-panel.svelte-xi83q0 {padding:0.6rem;flex-grow:1;}\n\n /* Main Grid (Info Items) 120px to 1fr, repeat */.info-grid.svelte-xi83q0 {display:grid;grid-template-columns:minmax(120px, 1fr) 1fr;column-count:2;gap:0.6rem;margin-top:0.5rem;grid-area:"info-key" "info-value";}.info-entry.svelte-xi83q0 {display:grid;gap:0.5rem;border-radius:6px;box-sizing:border-box;min-height:1.2em;}.info-key.svelte-xi83q0 {font-weight:600;align-items:center;border-top:1px solid var(--background-modifier-hover);border-bottom:1px solid var(--background-modifier-hover);grid-area:"info-key";}.info-item.svelte-xi83q0 {align-items:start;padding:0.5rem;background:var(--background-modifier-hover, rgba(0, 0, 0, 0.03));grid-area:"info-value";}.value.svelte-xi83q0 {white-space:pre-wrap;word-break:break-word;color:var(--text-normal, #e6e6e6);min-height:1em;}\n\n @container (max-width: 340px) {.info-grid.svelte-xi83q0 {grid-template-columns:1fr;}.info-item.svelte-xi83q0 {grid-template-columns:1fr;}\n }'};toggleActiveSyncClass=(el,isActive)=>{isActive()?el.addClass("active-pane"):el.removeClass("active-pane");return{}};root_128=from_html('<li class="svelte-9kxeje"><label class="svelte-9kxeje"> </label> <span class="chip svelte-9kxeje"> </span> <input type="text"/> <button class="iconbutton svelte-9kxeje">🗑</button></li>');root35=from_html('<ul class="svelte-9kxeje"><!> <li class="svelte-9kxeje"><label class="svelte-9kxeje"><button>Add</button></label></li> <li class="buttons svelte-9kxeje"><button>Apply</button> <button>Revert</button></li></ul>');$$css13={hash:"svelte-9kxeje",code:"label.svelte-9kxeje {min-width:4em;width:4em;display:inline-flex;flex-direction:row;justify-content:flex-end;}ul.svelte-9kxeje {flex-grow:1;display:inline-flex;flex-direction:column;list-style-type:none;margin-block-start:0;margin-block-end:0;margin-inline-start:0;margin-inline-end:0;padding-inline-start:0;}li.svelte-9kxeje {padding:var(--size-2-1) var(--size-4-1);display:inline-flex;flex-grow:1;align-items:center;justify-content:flex-end;gap:var(--size-4-2);}li.svelte-9kxeje input:where(.svelte-9kxeje) {min-width:10em;}button.iconbutton.svelte-9kxeje {max-width:4em;}.chip.svelte-9kxeje {background-color:var(--tag-background);color:var(--tag-color);padding:var(--size-2-1) var(--size-4-1);border-radius:0.5em;font-size:0.8em;}.chip.svelte-9kxeje:empty {display:none;}"};EVENT_REQUEST_SHOW_HISTORY="show-history";toc=new Set;stubs={};ObsidianLiveSyncSettingTab=class extends import_obsidian.PluginSettingTab{constructor(app,plugin3){super(app,plugin3);this.selectedScreen="";this.settingComponents=[];this.controlledElementFunc=[];this.onSavedHandlers=[];this.inWizard=!1;this.isShown=!1;this.manifestVersion="0.25.38";this.updateInformation="# 0.25\nSince 19th July, 2025 (beta1 in 0.25.0-beta1, 13th July, 2025)\n\nThe head note of 0.25 is now in [updates_old.md](https://github.com/vrtmrz/obsidian-livesync/blob/main/updates_old.md). Because 0.25 got a lot of updates, thankfully, compatibility is kept and we do not need breaking changes! In other words, when get enough stabled. The next version will be v1.0.0. Even though it my hope.\n\n## 0.25.38\n\n17th January, 2026\n\n### Fixed\n\n- Fixed an issue where indexedDB would not close correctly on some environments, causing unexpected errors during database operations.\n\n## 0.25.37\n\n15th January, 2026\n\nThank you for your patience until my return!\n\nThis release contains minor changes discovered and fixed during test implementation.\nThere are no changes affecting usage.\n\n### Refactored\n- Logging system has been slightly refactored to improve maintainability.\n- Some import statements have been unified.\n\n## 0.25.36\n\n25th December, 2025\n\n### Improved\n\n- Now the garbage collector (V3) has been implemented. (Beta)\n - This garbage collector ensures that all devices are synchronised to the latest progress to prevent inconsistencies.\n - In other words, it makes sure that no new conflicts would have arisen.\n - This feature requires additional information (via node information), but it should be more reliable.\n - This feature requires all devices have v0.25.36 or later.\n - After the garbage collector runs, the database size may be reduced (Compaction will be run automatically after GC).\n - We should have an administrative privilege on the remote database to run this garbage collector.\n- Now the plug-in and device information is stored in the remote database.\n - This information is used for the garbage collector (V3).\n - Some additional features may be added in the future using this information.\n\n## 0.25.35\n\n24th December, 2025\n\nSorry for a small release! I would like to keep things moving along like this if possible. After all, the holidays seem to be starting soon. I will be doubled by my business until the 27th though, indeed.\n\n### Fixed\n\n- Now the conflict resolution dialogue shows correctly which device only has older APIs (#764).\n\n## 0.25.34\n\n10th December, 2025\n\n### Behaviour change\n\n- The plug-in automatically fetches the missing chunks even if `Fetch chunks on demand` is disabled.\n - This change is to avoid loss of data when receiving a bulk of revisions.\n - This can be prevented by enabling `Use Only Local Chunks` in the settings.\n- Storage application now saved during each event and restored on startup.\n- Synchronisation result application is also now saved during each event and restored on startup.\n - These may avoid some unexpected loss of data when the editor crashes.\n\n### Fixed\n\n- Now the plug-in waits for the application of pended batch changes before the synchronisation starts.\n - This may avoid some unexpected loss or unexpected conflicts.\n Plug-in sends custom headers correctly when RequestAPI is used.\n- No longer causing unexpected chunk creation during `Reset synchronisation on This Device` with bucket sync.\n\n### Refactored\n\n- Synchronisation result application process has been refactored.\n- Storage application process has been refactored.\n - Please report if you find any unexpected behaviour after this update. A bit of large refactoring.\n\n## 0.25.33\n\n05th December, 2025\n\n### New feature\n\n- We can analyse the local database with the `Analyse database usage` command.\n - This command makes a TSV-style report of the database usage, which can be pasted into spreadsheet applications.\n - The report contains the number of unique chunks and shared chunks for each document revision.\n - Unique chunks indicate the actual consumption.\n - Shared chunks indicate the reference counts from other chunks with no consumption.\n - We can find which notes or files are using large amounts of storage in the database. Or which notes cannot share chunks effectively.\n - This command is useful when optimising the database size or investigating an unexpectedly large database size.\n- We can reset the notification threshold and check the remote usage at once with the `Reset notification threshold and check the remote database usage` command.\n- Commands are available from the Command Palette, or `Hatch` pane in the settings dialogue.\n\n### Fixed\n\n- Now the plug-in resets the remote size notification threshold after rebuild.\n\n## 0.25.32\n\n02nd December, 2025\n\nNow I am back from a short (?) break! Thank you all for your patience. (It is nothing major, but the first half of the year has finally come to an end).\nAnyway, I will release the things a bit by bit. I think that we need a rehabilitation or getting gears in again.\n\n### Improved\n\n- Now the plugin warns when we are in several file-related situations that may cause unexpected behaviour (#300).\n - These errors are displayed alongside issues such as file size exceeding limits.\n - Such situations include:\n - When the document has a name which is not supported by some file systems.\n - When the vault has the same file names with different letter cases.\n\n## 0.25.31\n\n18th November, 2025\n\n### Fixed\n\n- Now fetching configuration from the server can handle the empty remote correctly (reported on #756).\n- No longer asking to switch adapters during rebuilding.\n\n## 0.25.30\n\n17th November, 2025\n\nSo sorry for the quick follow-up release, due to a humble mistake in a quick causing a matter.\n\n### Fixed\n\n- Now we can save settings correctly again (#756).\n\n## ~~0.25.28~~ 0.25.29\n\n(0.25.28 was skipped due to a packaging issue.)\n\n17th November, 2025\n\n### New feature\n\n- We can now configure hidden file synchronisation to always overwrite with the latest version (#579).\n\n### Fixed\n\n- Timing dependency issues during initialisation have been mitigated (#714)\n\n### Improved\n\n- Error logs now contain stack-traces for better inspection.\n\n## 0.25.27\n\n12th November, 2025\n\n### Improved\n\n- Now we can switch the database adapter between IndexedDB and IDB without rebuilding (#747).\n - Just a local migration will be required, but faster than a full rebuild.\n- No longer checking for the adapter by `Doctor`.\n\n### Changes\n\n- The default adapter is reverted to IDB to avoid memory leaks (#747).\n\n### Fixed (?)\n\n- Reverted QR code library to v1.4.4 (To make sure #752).\n\nOlder notes are in\n[updates_old.md](https://github.com/vrtmrz/obsidian-livesync/blob/main/updates_old.md).\n";this.lastVersion=~~(versionNumberString2Number(this.manifestVersion)/1e3);this.screenElements={};this.enableOnlySyncDisabled=enableOnly((()=>!this.isAnySyncEnabled()));this.onlyOnP2POrCouchDB=()=>({visibility:this.isConfiguredAs("remoteType",REMOTE_P2P)||this.isConfiguredAs("remoteType",REMOTE_COUCHDB)});this.onlyOnCouchDB=()=>({visibility:this.isConfiguredAs("remoteType",REMOTE_COUCHDB)});this.onlyOnMinIO=()=>({visibility:this.isConfiguredAs("remoteType",REMOTE_MINIO)});this.onlyOnOnlyP2P=()=>({visibility:this.isConfiguredAs("remoteType",REMOTE_P2P)});this.onlyOnCouchDBOrMinIO=()=>({visibility:this.isConfiguredAs("remoteType",REMOTE_COUCHDB)||this.isConfiguredAs("remoteType",REMOTE_MINIO)});this.checkWorkingPassphrase=async()=>{if(this.editingSettings.remoteType==REMOTE_MINIO)return!0;const settingForCheck={...this.editingSettings},replicator=this.services.replicator.getNewReplicator(settingForCheck);if(!(replicator instanceof LiveSyncCouchDBReplicator))return!0;const db=await replicator.connectRemoteCouchDBWithSetting(settingForCheck,this.services.API.isMobile(),!0);if("string"==typeof db){Logger($msg("obsidianLiveSyncSettingTab.logCheckPassphraseFailed",{db}),LOG_LEVEL_NOTICE);return!1}if(await checkSyncInfo(db.db))return!0;Logger($msg("obsidianLiveSyncSettingTab.logPassphraseNotCompatible"),LOG_LEVEL_NOTICE);return!1};this.isPassphraseValid=async()=>{if(this.editingSettings.encrypt&&""==this.editingSettings.passphrase){Logger($msg("obsidianLiveSyncSettingTab.logEncryptionNoPassphrase"),LOG_LEVEL_NOTICE);return!1}if(this.editingSettings.encrypt&&!await testCrypt()){Logger($msg("obsidianLiveSyncSettingTab.logEncryptionNoSupport"),LOG_LEVEL_NOTICE);return!1}return!0};this.rebuildDB=async method=>{if(this.editingSettings.encrypt&&""==this.editingSettings.passphrase)Logger($msg("obsidianLiveSyncSettingTab.logEncryptionNoPassphrase"),LOG_LEVEL_NOTICE);else if(!this.editingSettings.encrypt||await testCrypt()){this.editingSettings.encrypt||(this.editingSettings.passphrase="");this.applyAllSettings();await this.services.setting.suspendAllSync();await this.services.setting.suspendExtraSync();this.reloadAllSettings();this.editingSettings.isConfigured=!0;Logger($msg("obsidianLiveSyncSettingTab.logRebuildNote"),LOG_LEVEL_NOTICE);await this.saveAllDirtySettings();this.closeSetting();await delay(2e3);await this.plugin.rebuilder.$performRebuildDB(method)}else Logger($msg("obsidianLiveSyncSettingTab.logEncryptionNoSupport"),LOG_LEVEL_NOTICE)};this.plugin=plugin3;LiveSyncSetting.env=this;eventHub.onEvent("reload-setting-tab",(()=>{this.requestReload()}))}get services(){return this.plugin.services}get editingSettings(){this._editingSettings||this.reloadAllSettings();return this._editingSettings}set editingSettings(v2){this._editingSettings||this.reloadAllSettings();this._editingSettings=v2}applySetting(keys3){for(const k2 of keys3)if(this.isDirty(k2)&&!(k2 in OnDialogSettingsDefault)){this.plugin.settings[k2]=this.editingSettings[k2];this.initialSettings[k2]=this.plugin.settings[k2]}keys3.forEach((e3=>this.refreshSetting(e3)))}applyAllSettings(){var _a8;const changedKeys=Object.keys(null!=(_a8=this.editingSettings)?_a8:{}).filter((e3=>this.isDirty(e3)));this.applySetting(changedKeys);this.reloadAllSettings()}async saveLocalSetting(key3){var _a8,_b5,_c3,_d2;if("configPassphrase"==key3){localStorage.setItem("ls-setting-passphrase",null!=(_b5=null==(_a8=this.editingSettings)?void 0:_a8[key3])?_b5:"");return await Promise.resolve()}if("deviceAndVaultName"==key3){this.services.setting.setDeviceAndVaultName(null!=(_d2=null==(_c3=this.editingSettings)?void 0:_c3[key3])?_d2:"");this.services.setting.saveDeviceAndVaultName();return await Promise.resolve()}}async saveSettings(keys3){let hasChanged=!1;const appliedKeys=[];for(const k2 of keys3)if(this.isDirty(k2)){appliedKeys.push(k2);if(k2 in OnDialogSettingsDefault){await this.saveLocalSetting(k2);this.initialSettings[k2]=this.editingSettings[k2]}else{this.plugin.settings[k2]=this.editingSettings[k2];this.initialSettings[k2]=this.plugin.settings[k2];hasChanged=!0}}hasChanged&&await this.plugin.saveSettings();const handlers2=this.onSavedHandlers.filter((e3=>-1!==appliedKeys.indexOf(e3.key))).map((e3=>e3.handler(this.editingSettings[e3.key])));await Promise.all(handlers2);keys3.forEach((e3=>this.refreshSetting(e3)))}async saveAllDirtySettings(){var _a8;const changedKeys=Object.keys(null!=(_a8=this.editingSettings)?_a8:{}).filter((e3=>this.isDirty(e3)));await this.saveSettings(changedKeys);this.reloadAllSettings()}requestUpdate(){scheduleTask("update-setting",10,(()=>{for(const setting of this.settingComponents)setting._onUpdate();for(const func of this.controlledElementFunc)func()}))}reloadAllLocalSettings(){const ret={...OnDialogSettingsDefault};ret.configPassphrase=localStorage.getItem("ls-setting-passphrase")||"";ret.preset="";ret.deviceAndVaultName=this.services.setting.getDeviceAndVaultName();return ret}computeAllLocalSettings(){var _a8,_b5;return{syncMode:(null==(_a8=this.editingSettings)?void 0:_a8.liveSync)?"LIVESYNC":(null==(_b5=this.editingSettings)?void 0:_b5.periodicReplication)?"PERIODIC":"ONEVENTS"}}reloadAllSettings(skipUpdate=!1){const localSetting=this.reloadAllLocalSettings();this._editingSettings={...this.plugin.settings,...localSetting};this._editingSettings={...this.editingSettings,...this.computeAllLocalSettings()};this.initialSettings={...this.editingSettings};skipUpdate||this.requestUpdate()}refreshSetting(key3){const localSetting=this.reloadAllLocalSettings();if(key3 in this.plugin.settings)if(key3 in localSetting){this.initialSettings[key3]=localSetting[key3];this.editingSettings[key3]=localSetting[key3]}else{this.initialSettings[key3]=this.plugin.settings[key3];this.editingSettings[key3]=this.initialSettings[key3]}this.editingSettings={...this.editingSettings,...this.computeAllLocalSettings()};this.requestUpdate()}isDirty(key3){var _a8;return isObjectDifferent(this.editingSettings[key3],null==(_a8=this.initialSettings)?void 0:_a8[key3])}isSomeDirty(keys3){return keys3.some((e3=>this.isDirty(e3)))}isConfiguredAs(key3,value){return!!this.editingSettings&&this.editingSettings[key3]==value}async testConnection(settingOverride={}){const trialSetting={...this.editingSettings,...settingOverride},replicator=await this.services.replicator.getNewReplicator(trialSetting);if(!replicator){Logger("No replicator available for the current settings.",LOG_LEVEL_NOTICE);return}await replicator.tryConnectRemote(trialSetting);const status=await replicator.getRemoteStatus(trialSetting);status&&status.estimatedSize&&Logger($msg("obsidianLiveSyncSettingTab.logEstimatedSize",{size:sizeToHumanReadable(status.estimatedSize)}),LOG_LEVEL_NOTICE)}closeSetting(){this.plugin.app.setting.close()}handleElement(element2,func){const updateFunc=((element3,func2)=>{const prev={};return()=>{const newValue=func2(),keys3=Object.keys(newValue);for(const k2 of keys3)if(prev[k2]!==newValue[k2]){"visibility"==k2&&element3.toggleClass("sls-setting-hidden",!newValue[k2]);prev[k2]=newValue[k2]}}})(element2,func);this.controlledElementFunc.push(updateFunc);updateFunc()}createEl(el,tag3,o2,callback,func){const element2=el.createEl(tag3,o2,callback);func&&this.handleElement(element2,func);return element2}addEl(el,tag3,o2,callback,func){const elm=this.createEl(el,tag3,o2,callback,func);return Promise.resolve(elm)}addOnSaved(key3,func){this.onSavedHandlers.push({key:key3,handler:func})}resetEditingSettings(){this._editingSettings=void 0;this.initialSettings=void 0}hide(){this.isShown=!1}requestReload(){var _a8;if(this.isShown){const newConf=this.plugin.settings,keys3=Object.keys(newConf);let hasLoaded=!1;for(const k2 of keys3)if(isObjectDifferent(newConf[k2],null==(_a8=this.initialSettings)?void 0:_a8[k2]))if(this.isDirty(k2))this.plugin.confirm.askInPopup(`config-reloaded-${k2}`,$msg("obsidianLiveSyncSettingTab.msgSettingModified",{setting:getConfName(k2)}),(anchor=>{anchor.text=$msg("obsidianLiveSyncSettingTab.optionHere");anchor.addEventListener("click",(()=>{this.refreshSetting(k2);this.display()}))}));else{this.refreshSetting(k2);if(k2 in OnDialogSettingsDefault)continue;hasLoaded=!0}hasLoaded?this.display():this.requestUpdate()}else this.reloadAllSettings(!0)}changeDisplay(screen){for(const k2 in this.screenElements)k2==screen?this.screenElements[k2].forEach((element2=>element2.removeClass("setting-collapsed"))):this.screenElements[k2].forEach((element2=>element2.addClass("setting-collapsed")));this.menuEl&&this.menuEl.querySelectorAll(".sls-setting-label").forEach((element2=>{if(element2.hasClass(`c-${screen}`)){element2.addClass("selected");element2.querySelector("input[type=radio]").checked=!0}else{element2.removeClass("selected");element2.querySelector("input[type=radio]").checked=!1}}));this.selectedScreen=screen}async enableMinimalSetup(){this.editingSettings.liveSync=!1;this.editingSettings.periodicReplication=!1;this.editingSettings.syncOnSave=!1;this.editingSettings.syncOnEditorSave=!1;this.editingSettings.syncOnStart=!1;this.editingSettings.syncOnFileOpen=!1;this.editingSettings.syncAfterMerge=!1;this.plugin.replicator.closeReplication();await this.saveAllDirtySettings();this.containerEl.addClass("isWizard");this.inWizard=!0;this.changeDisplay("20")}addScreenElement(key3,element2){key3 in this.screenElements||(this.screenElements[key3]=[]);this.screenElements[key3].push(element2)}selectPane(event2){const target=event2.target;if("INPUT"==target.tagName){const value=target.getAttribute("value");value&&this.selectedScreen!=value&&this.changeDisplay(value)}}isNeedRebuildLocal(){return this.isSomeDirty(["useIndexedDBAdapter","doNotUseFixedRevisionForChunks","handleFilenameCaseSensitive","passphrase","useDynamicIterationCount","usePathObfuscation","encrypt"])}isNeedRebuildRemote(){return this.isSomeDirty(["doNotUseFixedRevisionForChunks","handleFilenameCaseSensitive","passphrase","useDynamicIterationCount","usePathObfuscation","encrypt"])}isAnySyncEnabled(){var _a8,_b5,_c3,_d2;return!(this.isConfiguredAs("isConfigured",!1)||!this.isConfiguredAs("liveSync",!0)&&!this.isConfiguredAs("periodicReplication",!0)&&!this.isConfiguredAs("syncOnFileOpen",!0)&&!this.isConfiguredAs("syncOnSave",!0)&&!this.isConfiguredAs("syncOnEditorSave",!0)&&!this.isConfiguredAs("syncOnStart",!0)&&!this.isConfiguredAs("syncAfterMerge",!0)&&!this.isConfiguredAs("syncOnFileOpen",!0)&&"CONNECTED"!=(null==(_b5=null==(_a8=this.plugin)?void 0:_a8.replicator)?void 0:_b5.syncStatus)&&"PAUSED"!=(null==(_d2=null==(_c3=this.plugin)?void 0:_c3.replicator)?void 0:_d2.syncStatus))}async confirmRebuild(){if(!await this.isPassphraseValid()){Logger("Passphrase is not valid, please fix it.",LOG_LEVEL_NOTICE);return}const OPTION_FETCH=$msg("obsidianLiveSyncSettingTab.optionFetchFromRemote"),OPTION_REBUILD_BOTH=$msg("obsidianLiveSyncSettingTab.optionRebuildBoth"),OPTION_ONLY_SETTING=$msg("obsidianLiveSyncSettingTab.optionSaveOnlySettings"),OPTION_CANCEL=$msg("obsidianLiveSyncSettingTab.optionCancel"),title=$msg("obsidianLiveSyncSettingTab.titleRebuildRequired"),note=$msg("obsidianLiveSyncSettingTab.msgRebuildRequired",{OPTION_REBUILD_BOTH,OPTION_FETCH,OPTION_ONLY_SETTING}),buttons=[OPTION_FETCH,OPTION_REBUILD_BOTH,OPTION_ONLY_SETTING,OPTION_CANCEL],result=await confirmWithMessage(this.plugin,title,note,buttons,OPTION_CANCEL,0);if(result!=OPTION_CANCEL&&(result!=OPTION_FETCH||await this.checkWorkingPassphrase()||"yes"==await this.plugin.confirm.askYesNoDialog($msg("obsidianLiveSyncSettingTab.msgAreYouSureProceed"),{defaultOption:"No"}))){this.editingSettings.encrypt||(this.editingSettings.passphrase="");await this.saveAllDirtySettings();await this.applyAllSettings();if(result==OPTION_FETCH){await this.plugin.storageAccess.writeFileAuto(FLAGMD_REDFLAG3_HR,"");this.services.appLifecycle.scheduleRestart();this.closeSetting()}else if(result==OPTION_REBUILD_BOTH){await this.plugin.storageAccess.writeFileAuto(FLAGMD_REDFLAG2_HR,"");this.services.appLifecycle.scheduleRestart();this.closeSetting()}else result==OPTION_ONLY_SETTING&&await this.plugin.saveSettings()}}display(){const changeDisplay=this.changeDisplay.bind(this),{containerEl}=this;this.settingComponents.length=0;this.controlledElementFunc.length=0;this.onSavedHandlers.length=0;this.screenElements={};null!=this._editingSettings&&null!=this.initialSettings||this.reloadAllSettings();if(void 0===this.editingSettings||null==this.initialSettings)return;this.isShown=!0;containerEl.empty();containerEl.addClass("sls-setting");containerEl.removeClass("isWizard");setStyle(containerEl,"menu-setting-poweruser",(()=>this.isConfiguredAs("usePowerUserMode",!0)));setStyle(containerEl,"menu-setting-advanced",(()=>this.isConfiguredAs("useAdvancedMode",!0)));setStyle(containerEl,"menu-setting-edgecase",(()=>this.isConfiguredAs("useEdgeCaseMode",!0)));const menuWrapper=this.createEl(containerEl,"div",{cls:"sls-setting-menu-wrapper"});this.menuEl&&this.menuEl.remove();this.menuEl=menuWrapper.createDiv("");this.menuEl.addClass("sls-setting-menu");const menuTabs=this.menuEl.querySelectorAll(".sls-setting-label");this.createEl(menuWrapper,"div",{cls:"sls-setting-menu-buttons"},(el=>{el.addClass("wizardHidden");el.createEl("label",{text:$msg("obsidianLiveSyncSettingTab.msgChangesNeedToBeApplied")});this.addEl(el,"button",{text:$msg("obsidianLiveSyncSettingTab.optionApply"),cls:"mod-warning"},(buttonEl=>{buttonEl.addEventListener("click",(()=>fireAndForget((async()=>await this.confirmRebuild()))))}))}),visibleOnly((()=>this.isNeedRebuildLocal()||this.isNeedRebuildRemote())));let paneNo=0;const addPane=(parentEl,title,icon,order,wizardHidden,level)=>{const el=this.createEl(parentEl,"div",{text:""});{const mdTitle=`${paneNo++}. ${title}${getLevelStr(null!=level?level:"")}`;el.setAttribute("data-pane",mdTitle);toc.add(`| ${icon} | [${mdTitle}](#${mdTitle.toLowerCase().replace(/ /g,"-").replace(/[^\w\s-]/g,"")}) | `)}setLevelClass(el,level);el.createEl("h3",{text:title,cls:"sls-setting-pane-title"});this.menuEl&&this.menuEl.createEl("label",{cls:`sls-setting-label c-${order} ${wizardHidden?"wizardHidden":""}`},(el2=>{setLevelClass(el2,level);const inputEl=el2.createEl("input",{type:"radio",name:"disp",value:`${order}`,cls:"sls-setting-tab"});el2.createEl("div",{cls:"sls-setting-menu-btn",text:icon,title});inputEl.addEventListener("change",(evt=>this.selectPane(evt)));inputEl.addEventListener("click",(evt=>this.selectPane(evt)))}));this.addScreenElement(`${order}`,el);return Promise.resolve(el)},panelNoMap={},addPanel=(parentEl,title,callback,func,level)=>{const el=this.createEl(parentEl,"div",{text:""},callback,func);{const paneNo2=findAttrFromParent(parentEl,"data-pane");paneNo2 in panelNoMap||(panelNoMap[paneNo2]=0);panelNoMap[paneNo2]+=1;const panelNo=panelNoMap[paneNo2];el.setAttribute("data-panel",`${panelNo}. ${title}${getLevelStr(null!=level?level:"")}`)}setLevelClass(el,level);this.createEl(el,"h4",{text:title,cls:"sls-setting-panel-title"});return Promise.resolve(el)};menuTabs.forEach((element2=>{const e3=element2.querySelector(".sls-setting-tab");e3&&e3.addEventListener("change",(event2=>{menuTabs.forEach((element3=>element3.removeClass("selected")));this.changeDisplay(event2.currentTarget.value);element2.addClass("selected")}))}));const bindPane=paneFunc=>paneEl=>{paneFunc.call(this,paneEl,{addPane,addPanel})};addPane(containerEl,$msg("obsidianLiveSyncSettingTab.panelChangeLog"),"💬",100,!1).then(bindPane(paneChangeLog));addPane(containerEl,$msg("obsidianLiveSyncSettingTab.panelSetup"),"🧙‍♂️",110,!1).then(bindPane(paneSetup));addPane(containerEl,$msg("obsidianLiveSyncSettingTab.panelGeneralSettings"),"⚙️",20,!1).then(bindPane(paneGeneral));addPane(containerEl,$msg("obsidianLiveSyncSettingTab.panelRemoteConfiguration"),"🛰️",0,!1).then(bindPane(paneRemoteConfig));addPane(containerEl,$msg("obsidianLiveSyncSettingTab.titleSyncSettings"),"🔄",30,!1).then(bindPane(paneSyncSettings));addPane(containerEl,"Selector","🚦",33,!1,LEVEL_ADVANCED).then(bindPane(paneSelector));addPane(containerEl,"Customization sync","🔌",60,!1,LEVEL_ADVANCED).then(bindPane(paneCustomisationSync));addPane(containerEl,"Hatch","🧰",50,!0).then(bindPane(paneHatch));addPane(containerEl,"Advanced","🔧",46,!1,LEVEL_ADVANCED).then(bindPane(paneAdvanced));addPane(containerEl,"Power users","💪",47,!0,LEVEL_POWER_USER).then(bindPane(panePowerUsers));addPane(containerEl,"Patches","🩹",51,!1,LEVEL_EDGE_CASE).then(bindPane(panePatches));addPane(containerEl,"Maintenance","🎛️",70,!0).then(bindPane(paneMaintenance));yieldNextAnimationFrame().then((()=>{""==this.selectedScreen?this.lastVersion!=this.editingSettings.lastReadUpdates?this.editingSettings.isConfigured?changeDisplay("100"):changeDisplay("110"):this.isAnySyncEnabled()?changeDisplay("20"):changeDisplay("110"):changeDisplay(this.selectedScreen);this.requestUpdate()}))}getMinioJournalSyncClient(){return new JournalSyncMinio(this.plugin.settings,this.plugin.simpleStore,this.plugin)}async resetRemoteBucket(){const minioJournal=this.getMinioJournalSyncClient();await minioJournal.resetBucket()}};ModuleObsidianSettingDialogue=class extends AbstractObsidianModule{_everyOnloadStart(){this.settingTab=new ObsidianLiveSyncSettingTab(this.app,this.plugin);this.plugin.addSettingTab(this.settingTab);eventHub.onEvent("request-open-settings",(()=>this.openSetting()));eventHub.onEvent("request-open-setting-wizard",(()=>{this.openSetting();this.settingTab.enableMinimalSetup()}));return Promise.resolve(!0)}openSetting(){this.app.setting.open();this.app.setting.openTabById("obsidian-livesync")}get appId(){return`${"appId"in this.app?this.app.appId:""}`}onBindFunction(core,services){services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this))}};DocumentHistoryModal=class extends import_obsidian.Modal{constructor(app,plugin3,file,id,revision){super(app);this.showDiff=!1;this.revs_info=[];this.currentText="";this.currentDeleted=!1;this.BlobURLs=new Map;this.plugin=plugin3;this.file=file instanceof import_obsidian.TFile?getPathFromTFile(file):file;this.id=id;this.initialRev=revision;!file&&id&&(this.file=this.services.path.id2path(id));"1"==localStorage.getItem("ols-history-highlightdiff")&&(this.showDiff=!0)}get services(){return this.plugin.services}async loadFile(initialRev){var _a8,_b5;this.id||(this.id=await this.services.path.path2id(this.file));const db=this.plugin.localDatabase;try{const w2=await db.getRaw(this.id,{revs_info:!0});this.revs_info=null!=(_b5=null==(_a8=w2._revs_info)?void 0:_a8.filter((e3=>"available"==(null==e3?void 0:e3.status))))?_b5:[];this.range.max=`${Math.max(this.revs_info.length-1,0)}`;this.range.value=this.range.max;this.fileInfo.setText(`${this.file} / ${this.revs_info.length} revisions`);await this.loadRevs(initialRev)}catch(ex){if(isErrorOfMissingDoc(ex)){this.range.max="0";this.range.value="";this.range.disabled=!0;this.contentView.setText("We don't have any history for this note.")}else{this.contentView.setText("Error while loading file.");Logger(ex,LOG_LEVEL_VERBOSE)}}}async loadRevs(initialRev){if(0==this.revs_info.length)return;if(initialRev){const rIndex=this.revs_info.findIndex((e3=>e3.rev==initialRev));rIndex>=0&&(this.range.value=""+(this.revs_info.length-1-rIndex))}const index6=this.revs_info.length-1-this.range.value/1,rev3=this.revs_info[index6];await this.showExactRev(rev3.rev)}revokeURL(key3){const v2=this.BlobURLs.get(key3);v2&&URL.revokeObjectURL(v2);this.BlobURLs.delete(key3)}generateBlobURL(key3,data){this.revokeURL(key3);const v2=URL.createObjectURL(new Blob([data],{endings:"transparent",type:"application/octet-stream"}));this.BlobURLs.set(key3,v2);return v2}async showExactRev(rev3){const db=this.plugin.localDatabase,w2=await db.getDBEntry(this.file,{rev:rev3},!1,!1,!0);this.currentText="";this.currentDeleted=!1;if(!1===w2){this.currentDeleted=!0;this.info.innerHTML="";this.contentView.innerHTML=`Could not read this revision<br>(${rev3})`}else{this.currentDoc=w2;this.info.innerHTML=`Modified:${new Date(w2.mtime).toLocaleString()}`;let result;const w1data=readDocument(w2);this.currentDeleted=!!w2.deleted;if(this.showDiff){const prevRevIdx=this.revs_info.length-1-(this.range.value/1-1);if(prevRevIdx>=0&&prevRevIdx<this.revs_info.length){const oldRev=this.revs_info[prevRevIdx].rev,w22=await db.getDBEntry(this.file,{rev:oldRev},!1,!1,!0);if(0!=w22)if("string"==typeof w1data){result="";const dmp=new import_diff_match_patch.diff_match_patch,w2data=readDocument(w22),diff=dmp.diff_main(w2data,w1data);dmp.diff_cleanupSemantic(diff);for(const v2 of diff){const x1=v2[0],x2=v2[1];x1==import_diff_match_patch.DIFF_DELETE?result+="<span class='history-deleted'>"+escapeStringToHTML(x2)+"</span>":x1==import_diff_match_patch.DIFF_EQUAL?result+="<span class='history-normal'>"+escapeStringToHTML(x2)+"</span>":x1==import_diff_match_patch.DIFF_INSERT&&(result+="<span class='history-added'>"+escapeStringToHTML(x2)+"</span>")}result=result.replace(/\n/g,"<br>")}else if(isImage(this.file)){result=`<div class='ls-imgdiff-wrap'>\n <div class='overlay'>\n <img class='img-base' src="${this.generateBlobURL("base",w1data)}">\n <img class='img-overlay' src='${this.generateBlobURL("overlay",readDocument(w22))}'>\n </div>\n</div>`;this.contentView.removeClass("op-pre")}}}if(null==result)if("string"!=typeof w1data){if(isImage(this.file)){result=`<div class='ls-imgdiff-wrap'>\n<div class='overlay'>\n<img class='img-base' src="${this.generateBlobURL("base",w1data)}">\n</div>\n</div>`;this.contentView.removeClass("op-pre")}}else result=escapeStringToHTML(w1data);null==result&&(result="string"==typeof w1data?escapeStringToHTML(w1data):"Binary file");this.contentView.innerHTML=(this.currentDeleted?"(At this revision, the file has been deleted)\n":"")+result}}onOpen(){const{contentEl}=this;this.titleEl.setText("Document History");contentEl.empty();this.fileInfo=contentEl.createDiv("");this.fileInfo.addClass("op-info");const divView=contentEl.createDiv("");divView.addClass("op-flex");divView.createEl("input",{type:"range"},(e3=>{this.range=e3;e3.addEventListener("change",(e4=>{scheduleOnceIfDuplicated("loadRevs",(()=>this.loadRevs()))}));e3.addEventListener("input",(e4=>{scheduleOnceIfDuplicated("loadRevs",(()=>this.loadRevs()))}))}));contentEl.createDiv("",(e3=>{e3.createEl("label",{},(label2=>{label2.appendChild(createEl("input",{type:"checkbox"},(checkbox=>{this.showDiff&&(checkbox.checked=!0);checkbox.addEventListener("input",(evt=>{this.showDiff=checkbox.checked;localStorage.setItem("ols-history-highlightdiff",1==this.showDiff?"1":"");scheduleOnceIfDuplicated("loadRevs",(()=>this.loadRevs()))}))})));label2.appendText("Highlight diff")}))})).addClass("op-info");this.info=contentEl.createDiv("");this.info.addClass("op-info");fireAndForget((async()=>await this.loadFile(this.initialRev)));const div=contentEl.createDiv({text:"Loading old revisions..."});this.contentView=div;div.addClass("op-scrollable");div.addClass("op-pre");const buttons=contentEl.createDiv("");buttons.createEl("button",{text:"Copy to clipboard"},(e3=>{e3.addClass("mod-cta");e3.addEventListener("click",(()=>{fireAndForget((async()=>{await navigator.clipboard.writeText(this.currentText);Logger("Old content copied to clipboard",LOG_LEVEL_NOTICE)}))}))}));const focusFile=async path2=>{const targetFile=this.plugin.app.vault.getFileByPath(path2);if(targetFile){const leaf=this.plugin.app.workspace.getLeaf(!1);await leaf.openFile(targetFile)}else Logger("Unable to display the file in the editor",LOG_LEVEL_NOTICE)};buttons.createEl("button",{text:"Back to this revision"},(e3=>{e3.addClass("mod-cta");e3.addEventListener("click",(()=>{fireAndForget((async()=>{const pathToWrite=stripPrefix(this.file);if(!isValidPath(pathToWrite)){Logger("Path is not valid to write content.",LOG_LEVEL_INFO);return}if(!this.currentDoc){Logger("No active file loaded.",LOG_LEVEL_INFO);return}const d4=readContent(this.currentDoc);await this.plugin.storageAccess.writeHiddenFileAuto(pathToWrite,d4);await focusFile(pathToWrite);this.close()}))}))}))}onClose(){const{contentEl}=this;contentEl.empty();this.BlobURLs.forEach((value=>{console.log(value);value&&URL.revokeObjectURL(value)}))}};ModuleObsidianDocumentHistory=class extends AbstractObsidianModule{_everyOnloadStart(){this.addCommand({id:"livesync-history",name:"Show history",callback:()=>{const file=this.services.vault.getActiveFilePath();file&&this.showHistory(file,void 0)}});this.addCommand({id:"livesync-filehistory",name:"Pick a file to show history",callback:()=>{fireAndForget((async()=>await this.fileHistory()))}});eventHub.onEvent(EVENT_REQUEST_SHOW_HISTORY,(({file,fileOnDB})=>{this.showHistory(file,fileOnDB._id)}));return Promise.resolve(!0)}showHistory(file,id){new DocumentHistoryModal(this.app,this.plugin,file,id).open()}async fileHistory(){const notes=[];for await(const doc of this.localDatabase.findAllDocs())notes.push({id:doc._id,path:getPath2(doc),dispPath:getPath2(doc),mtime:doc.mtime});notes.sort(((a2,b3)=>b3.mtime-a2.mtime));const notesList=notes.map((e3=>e3.dispPath)),target=await this.core.confirm.askSelectString("File to view History",notesList);if(target){const targetId=notes.find((e3=>e3.dispPath==target));this.showHistory(targetId.path,targetId.id)}}onBindFunction(core,services){services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this))}};root_129=from_html('<div class="svelte-1ddarry">Gathering information...</div>');root_218=from_html('<th class="svelte-1ddarry">Chunks</th>');root_38=from_html('<div class="svelte-1ddarry"></div>');root_414=from_html('<div class="svelte-1ddarry"><button class="svelte-1ddarry">+1 week</button></div>');root_67=from_html('<a class="svelte-1ddarry"> </a>');root_810=from_html('<td class="svelte-1ddarry"> </td>');root_55=from_html('<tr class="svelte-1ddarry"><td class="mtime svelte-1ddarry"> </td><td class="path svelte-1ddarry"><div class="filenames svelte-1ddarry"><span class="path svelte-1ddarry"> </span> <span class="filename svelte-1ddarry"><a class="svelte-1ddarry"> </a></span></div></td><td class="svelte-1ddarry"><span class="rev svelte-1ddarry"><!></span></td><td class="svelte-1ddarry"> </td><!></tr>');root_96=from_html('<div class="svelte-1ddarry"></div>');root_105=from_html('<div class="svelte-1ddarry"><button class="svelte-1ddarry">+1 week</button></div>');root36=from_html('<div class="globalhistory svelte-1ddarry"><h1 class="svelte-1ddarry">Vault history</h1> <div class="control svelte-1ddarry"><div class="row svelte-1ddarry"><label for="" class="svelte-1ddarry">From:</label><input type="date" class="svelte-1ddarry"/></div> <div class="row svelte-1ddarry"><label for="" class="svelte-1ddarry">To:</label><input type="date" class="svelte-1ddarry"/></div> <div class="row svelte-1ddarry"><label for="" class="svelte-1ddarry">Info:</label> <label class="svelte-1ddarry"><input type="checkbox" class="svelte-1ddarry"/><span class="svelte-1ddarry">Diff</span></label> <label class="svelte-1ddarry"><input type="checkbox" class="svelte-1ddarry"/><span class="svelte-1ddarry">Chunks</span></label> <label class="svelte-1ddarry"><input type="checkbox" class="svelte-1ddarry"/><span class="svelte-1ddarry">File integrity</span></label></div></div> <!> <table class="svelte-1ddarry"><tbody class="svelte-1ddarry"><tr class="svelte-1ddarry"><th class="svelte-1ddarry">Date</th><th class="svelte-1ddarry">Path</th><th class="svelte-1ddarry">Rev</th><th class="svelte-1ddarry">Stat</th><!></tr><tr class="svelte-1ddarry"><td colspan="5" class="more svelte-1ddarry"><!></td></tr><!><tr class="svelte-1ddarry"><td colspan="5" class="more svelte-1ddarry"><!></td></tr></tbody></table></div>');$$css14={hash:"svelte-1ddarry",code:".svelte-1ddarry {box-sizing:border-box;}.globalhistory.svelte-1ddarry {margin-bottom:2em;}table.svelte-1ddarry {width:100%;}.more.svelte-1ddarry > div:where(.svelte-1ddarry) {display:flex;}.more.svelte-1ddarry > div:where(.svelte-1ddarry) > button:where(.svelte-1ddarry) {flex-grow:1;}th.svelte-1ddarry {position:sticky;top:0;backdrop-filter:blur(10px);}td.mtime.svelte-1ddarry {white-space:break-spaces;}td.path.svelte-1ddarry {word-break:break-word;}.row.svelte-1ddarry {display:flex;flex-direction:row;flex-wrap:wrap;}.row.svelte-1ddarry > label:where(.svelte-1ddarry) {display:flex;align-items:center;min-width:5em;}.row.svelte-1ddarry > input:where(.svelte-1ddarry) {flex-grow:1;}.filenames.svelte-1ddarry {display:flex;flex-direction:column;}.filenames.svelte-1ddarry > .path:where(.svelte-1ddarry) {font-size:70%;}.rev.svelte-1ddarry {text-overflow:ellipsis;max-width:3em;display:inline-block;overflow:hidden;white-space:nowrap;}"};GlobalHistoryView=class extends SvelteItemView{constructor(leaf,plugin3){super(leaf);this.icon="clock";this.title="";this.navigation=!0;this.plugin=plugin3}instantiateComponent(target){return mount(GlobalHistory,{target,props:{plugin:this.plugin}})}getIcon(){return"clock"}getViewType(){return"global-history"}getDisplayText(){return"Vault history"}};ModuleObsidianGlobalHistory=class extends AbstractObsidianModule{_everyOnloadStart(){this.addCommand({id:"livesync-global-history",name:"Show vault history",callback:()=>{this.showGlobalHistory()}});this.registerView("global-history",(leaf=>new GlobalHistoryView(leaf,this.plugin)));return Promise.resolve(!0)}showGlobalHistory(){this.services.API.showWindow("global-history")}onBindFunction(core,services){services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this))}};SETTING_HEADER="````yaml:livesync-setting\n";ModuleObsidianSettingsAsMarkdown=class extends AbstractObsidianModule{_everyOnloadStart(){this.addCommand({id:"livesync-export-config",name:"Write setting markdown manually",checkCallback:checking=>{if(checking)return""!=this.settings.settingSyncFile;fireAndForget((async()=>{await this.services.setting.saveSettingData()}))}});this.addCommand({id:"livesync-import-config",name:"Parse setting file",editorCheckCallback:(checking,editor,ctx)=>{if(checking){const doc=editor.getValue();return""!=this.extractSettingFromWholeText(doc).body}if(ctx.file){const file=ctx.file;fireAndForget((async()=>await this.checkAndApplySettingFromMarkdown(file.path,!1)))}}});eventHub.onEvent("event-file-changed",(info3=>{fireAndForget((()=>this.checkAndApplySettingFromMarkdown(info3.file,info3.automated)))}));eventHub.onEvent(EVENT_SETTING_SAVED,(settings=>{""!=settings.settingSyncFile&&fireAndForget((()=>this.saveSettingToMarkdown(settings.settingSyncFile)))}));return Promise.resolve(!0)}extractSettingFromWholeText(data){if(-1===data.indexOf(SETTING_HEADER))return{preamble:data,body:"",postscript:""};const startMarkerPos=data.indexOf(SETTING_HEADER),dataStartPos=-1==startMarkerPos?data.length:startMarkerPos,endMarkerPos=-1==startMarkerPos?data.length:data.indexOf("\n````",dataStartPos),dataEndPos=-1==endMarkerPos?data.length:endMarkerPos,body=data.substring(dataStartPos+26,dataEndPos);return{preamble:data.substring(0,dataStartPos),body,postscript:data.substring(dataEndPos+5+1)}}async parseSettingFromMarkdown(filename,data){if(!await this.core.storageAccess.isExists(filename))return{preamble:"",body:"",postscript:""};if(data)return this.extractSettingFromWholeText(data);const parseData=null!=data?data:await this.core.storageAccess.readFileText(filename);return this.extractSettingFromWholeText(parseData)}async checkAndApplySettingFromMarkdown(filename,automated){if(automated&&!this.settings.notifyAllSettingSyncFile&&(!this.settings.settingSyncFile||this.settings.settingSyncFile!=filename)){this._log(`Setting file (${filename}) does not match the current configuration. skipped.`,LOG_LEVEL_DEBUG);return}const{body}=await this.parseSettingFromMarkdown(filename);let newSetting={};try{newSetting=(0,import_obsidian.parseYaml)(body)}catch(ex){this._log("Could not parse YAML",LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE);return}if("settingSyncFile"in newSetting&&newSetting.settingSyncFile!=filename){this._log("This setting file seems to backed up one. Please fix the filename or settingSyncFile value.",automated?LOG_LEVEL_INFO:LOG_LEVEL_NOTICE);return}let settingToApply={...DEFAULT_SETTINGS};settingToApply={...settingToApply,...newSetting};if(!(null==settingToApply?void 0:settingToApply.writeCredentialsForSettingSync)){settingToApply.couchDB_USER=this.settings.couchDB_USER;settingToApply.couchDB_PASSWORD=this.settings.couchDB_PASSWORD;settingToApply.passphrase=this.settings.passphrase}if(!isObjectDifferent(this.generateSettingForMarkdown(this.settings,settingToApply.writeCredentialsForSettingSync),this.generateSettingForMarkdown(settingToApply))){this._log("Setting markdown has been detected, but not changed.",automated?LOG_LEVEL_INFO:LOG_LEVEL_NOTICE);return}const addMsg=this.settings.settingSyncFile!=filename?" (This is not-active file)":"";this.core.confirm.askInPopup("apply-setting-from-md",`Setting markdown ${filename}${addMsg} has been detected. Apply this from {HERE}.`,(anchor=>{anchor.text="HERE";anchor.addEventListener("click",(()=>{fireAndForget((async()=>{const APPLY_AND_RESTART="Apply settings and restart obsidian",APPLY_AND_REBUILD="Apply settings and restart obsidian with red_flag_rebuild.md",APPLY_AND_FETCH="Apply settings and restart obsidian with red_flag_fetch.md",result=await this.core.confirm.askSelectStringDialogue("Ready for apply the setting.",[APPLY_AND_RESTART,"Apply settings",APPLY_AND_FETCH,APPLY_AND_REBUILD,"Cancel"],{defaultAction:APPLY_AND_RESTART});if("Apply settings"==result||result==APPLY_AND_RESTART||result==APPLY_AND_REBUILD||result==APPLY_AND_FETCH){this.core.settings=settingToApply;await this.services.setting.saveSettingData();if("Apply settings"==result){this._log("Loaded settings have been applied!",LOG_LEVEL_NOTICE);return}result==APPLY_AND_REBUILD&&await this.core.rebuilder.scheduleRebuild();result==APPLY_AND_FETCH&&await this.core.rebuilder.scheduleFetch();this.services.appLifecycle.performRestart()}}))}))}))}generateSettingForMarkdown(settings,keepCredential){const saveData={...settings||this.settings};delete saveData.encryptedCouchDBConnection;delete saveData.encryptedPassphrase;delete saveData.additionalSuffixOfDatabaseName;if(!saveData.writeCredentialsForSettingSync&&!keepCredential){delete saveData.couchDB_USER;delete saveData.couchDB_PASSWORD;delete saveData.passphrase;delete saveData.jwtKey;delete saveData.jwtKid;delete saveData.jwtSub;delete saveData.couchDB_CustomHeaders;delete saveData.bucketCustomHeaders}return saveData}async saveSettingToMarkdown(filename){const saveData=this.generateSettingForMarkdown();if(!await this.core.storageAccess.isExists(filename)){await this.core.storageAccess.ensureDir(filename);const initialContent='This file contains Self-hosted LiveSync settings as YAML.\nExcept for the `livesync-setting` code block, we can add a note for free.\n\nIf the name of this file matches the value of the "settingSyncFile" setting inside the `livesync-setting` block, LiveSync will tell us whenever the settings change. We can decide to accept or decline the remote setting. (In other words, we can back up this file by renaming it to another name).\n\nWe can perform a command in this file.\n- `Parse setting file` : load the setting from the file.\n\n**Note** Please handle it with all of your care if you have configured to write credentials in.\n\n\n';await this.core.storageAccess.writeFileAuto(filename,initialContent+SETTING_HEADER+"\n\n````")}const data=await this.core.storageAccess.readFileText(filename),{preamble,body,postscript}=this.extractSettingFromWholeText(data),newBody=(0,import_obsidian.stringifyYaml)(saveData);if(newBody==body)this._log("Markdown setting: Nothing had been changed",LOG_LEVEL_VERBOSE);else{await this.core.storageAccess.writeFileAuto(filename,preamble+SETTING_HEADER+newBody+"\n````"+postscript);this._log(`Markdown setting: ${filename} has been updated!`,LOG_LEVEL_VERBOSE)}}onBindFunction(core,services){services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this))}};ModuleInitializerFile=class extends AbstractModule{async _performFullScan(showingNotice,ignoreSuspending=!1){this._log("Opening the key-value database",LOG_LEVEL_VERBOSE);const isInitialized=await this.core.kvDB.get("initialized")||!1;if(!this.settings.isConfigured){showingNotice&&this._log("LiveSync is not configured yet. Synchronising between the storage and the local database is now prevented.",LOG_LEVEL_NOTICE,"syncAll");return!1}if(!ignoreSuspending&&this.settings.suspendFileWatching){showingNotice&&this._log("Now suspending file watching. Synchronising between the storage and the local database is now prevented.",LOG_LEVEL_NOTICE,"syncAll");return!1}showingNotice&&this._log("Initializing",LOG_LEVEL_NOTICE,"syncAll");if(isInitialized){this._log("Restoring storage state",LOG_LEVEL_VERBOSE);await this.core.storageAccess.restoreState()}this._log("Initialize and checking database files");this._log("Checking deleted files");await this.collectDeletedFiles();this._log("Collecting local files on the storage",LOG_LEVEL_VERBOSE);const filesStorageSrc=this.core.storageAccess.getFiles(),_filesStorage=[];for(const f4 of filesStorageSrc)await this.services.vault.isTargetFile(f4.path,f4!=filesStorageSrc[0])&&_filesStorage.push(f4);const convertCase=path2=>this.settings.handleFilenameCaseSensitive?path2:path2.toLowerCase(),storageFileNameMap=Object.fromEntries(_filesStorage.map((e3=>[e3.path,e3]))),storageFileNames=Object.keys(storageFileNameMap),storageFileNameCapsPair=storageFileNames.map((e3=>[e3,convertCase(e3)])),storageFileNameCI2CS=Object.fromEntries(storageFileNameCapsPair.map((e3=>[e3[1],e3[0]])));this._log("Collecting local files on the DB",LOG_LEVEL_VERBOSE);const _DBEntries=[];let count=0;for await(const doc of this.localDatabase.findAllNormalDocs({conflicts:!0})){count++;count%25==0&&this._log(`Collecting local files on the DB: ${count}`,showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"syncAll");const path2=getPath2(doc);if(isValidPath(path2)&&await this.services.vault.isTargetFile(path2,!0)){if(!isMetaEntry(doc)){this._log(`Invalid entry: ${path2}`,LOG_LEVEL_INFO);continue}_DBEntries.push(doc)}}const databaseFileNameMap=Object.fromEntries(_DBEntries.map((e3=>[getPath2(e3),e3]))),databaseFileNames=Object.keys(databaseFileNameMap),databaseFileNameCapsPair=databaseFileNames.map((e3=>[e3,convertCase(e3)])),databaseFileNameCI2CS=Object.fromEntries(databaseFileNameCapsPair.map((e3=>[e3[1],e3[0]]))),allFiles=unique([...Object.keys(databaseFileNameCI2CS),...Object.keys(storageFileNameCI2CS)]);this._log(`Total files in the database: ${databaseFileNames.length}`,LOG_LEVEL_VERBOSE,"syncAll");this._log(`Total files in the storage: ${storageFileNames.length}`,LOG_LEVEL_VERBOSE,"syncAll");this._log(`Total files: ${allFiles.length}`,LOG_LEVEL_VERBOSE,"syncAll");const filesExistOnlyInStorage=allFiles.filter((e3=>!databaseFileNameCI2CS[e3])),filesExistOnlyInDatabase=allFiles.filter((e3=>!storageFileNameCI2CS[e3])),filesExistBoth=allFiles.filter((e3=>databaseFileNameCI2CS[e3]&&storageFileNameCI2CS[e3]));this._log(`Files exist only in storage: ${filesExistOnlyInStorage.length}`,LOG_LEVEL_VERBOSE,"syncAll");this._log(`Files exist only in database: ${filesExistOnlyInDatabase.length}`,LOG_LEVEL_VERBOSE,"syncAll");this._log(`Files exist both in storage and database: ${filesExistBoth.length}`,LOG_LEVEL_VERBOSE,"syncAll");this._log("Synchronising...");const processStatus={},logLevel=showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,updateLog=throttle(((key3,msg)=>{processStatus[key3]=msg;const log2=Object.values(processStatus).join("\n");this._log(log2,logLevel,"syncAll")}),25),initProcess=[],runAll=async(procedureName,objects,callback)=>{if(0==objects.length){this._log(`${procedureName}: Nothing to do`);return}this._log(procedureName);if(!this.localDatabase.isReady)throw Error("Database is not ready!");let success=0,failed2=0,total=0;for await(const result of withConcurrency(objects,(async e3=>{try{await callback(e3);return!0}catch(ex){this._log(`Error while ${procedureName}`,LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE);return!1}}),10)){result?success++:failed2++;total++;const msg2=`${procedureName}: DONE:${success}, FAILED:${failed2}, LAST:${objects.length-total}`;updateLog(procedureName,msg2)}updateLog(procedureName,`${procedureName} All done: DONE:${success}, FAILED:${failed2}`)};initProcess.push(runAll("UPDATE DATABASE",filesExistOnlyInStorage,(async e3=>{const file=storageFileNameMap[storageFileNameCI2CS[e3]];if(this.services.vault.isFileSizeTooLarge(file.stat.size))this._log(`UPDATE DATABASE: ${e3} has been skipped due to file size exceeding the limit`,logLevel);else{const path2=file.path;await this.core.fileHandler.storeFileToDB(file);eventHub.emitEvent("event-file-changed",{file:path2,automated:!0})}})));initProcess.push(runAll("UPDATE STORAGE",filesExistOnlyInDatabase,(async e3=>{var _a8,_b5,_c3;const w2=databaseFileNameMap[databaseFileNameCI2CS[e3]],path2=null!=(_a8=getPath2(w2))?_a8:e3;if(!w2||w2.deleted||w2._deleted)w2?this._log(`Deletion history skipped: ${path2}`,LOG_LEVEL_VERBOSE):this._log(`entry not found: ${path2}`);else if(this.services.vault.isFileSizeTooLarge(w2.size))this._log(`UPDATE STORAGE: ${path2} has been skipped due to file size exceeding the limit`,logLevel);else{if(null!=(_c3=null==(_b5=w2._conflicts)?void 0:_b5.length)&&_c3){this._log(`UPDATE STORAGE: ${path2} has conflicts. skipped (x)`,LOG_LEVEL_INFO);return}await this.core.fileHandler.dbToStorage(path2,null,!0);eventHub.emitEvent("event-file-changed",{file:e3,automated:!0});this._log(`Check or pull from db:${path2} OK`)}})));const fileMap=filesExistBoth.map((path2=>({file:storageFileNameMap[storageFileNameCI2CS[path2]],doc:databaseFileNameMap[databaseFileNameCI2CS[path2]]})));initProcess.push(runAll("SYNC DATABASE AND STORAGE",fileMap,(async e3=>{var _a8,_b5;const{file,doc}=e3;null!=(_b5=null==(_a8=doc._conflicts)?void 0:_a8.length)&&_b5?this._log(`SYNC DATABASE AND STORAGE: ${file.path} has conflicts. skipped`,LOG_LEVEL_INFO):this.services.vault.isFileSizeTooLarge(file.stat.size)||this.services.vault.isFileSizeTooLarge(doc.size)?this._log(`SYNC DATABASE AND STORAGE: ${getPath2(doc)} has been skipped due to file size exceeding the limit`,logLevel):await this.syncFileBetweenDBandStorage(file,doc)})));await Promise.all(initProcess);this._log("Initialized, NOW TRACKING!");isInitialized||await this.core.kvDB.set("initialized",!0);showingNotice&&this._log("Initialize done!",LOG_LEVEL_NOTICE,"syncAll");return!0}async syncFileBetweenDBandStorage(file,doc){if(!doc)throw new Error(`Missing doc:${file.path}`);if("path"in file){const w2=this.core.storageAccess.getFileStub(file.path);if(!w2)throw new Error(`Missing file:${file.path}`);file=w2}switch(compareFileFreshness(file,doc)){case BASE_IS_NEW:if(this.services.vault.isFileSizeTooLarge(file.stat.size))this._log(`STORAGE -> DB : ${file.path} has been skipped due to file size exceeding the limit`,LOG_LEVEL_NOTICE);else{this._log("STORAGE -> DB :"+file.path);await this.core.fileHandler.storeFileToDB(file)}break;case TARGET_IS_NEW:if(!this.services.vault.isFileSizeTooLarge(doc.size)){this._log("STORAGE <- DB :"+file.path);await this.core.fileHandler.dbToStorage(doc,stripAllPrefixes(file.path),!0)?eventHub.emitEvent("event-file-changed",{file:file.path,automated:!0}):this._log(`STORAGE <- DB : Cloud not read ${file.path}, possibly deleted`,LOG_LEVEL_NOTICE);return caches}this._log(`STORAGE <- DB : ${file.path} has been skipped due to file size exceeding the limit`,LOG_LEVEL_NOTICE);break;case EVEN:this._log("STORAGE == DB :"+file.path,LOG_LEVEL_DEBUG);break;default:this._log("STORAGE ?? DB :"+file.path+" Something got weird")}}async collectDeletedFiles(){const limitDays=this.settings.automaticallyDeleteMetadataOfDeletedFiles;if(limitDays<=0)return;this._log("Checking expired file history");const limit=Date.now()-864e5*limitDays,notes=[];for await(const doc of this.localDatabase.findAllDocs({conflicts:!0}))isAnyNote(doc)&&doc.deleted&&doc.mtime-limit<0&&notes.push({path:getPath2(doc),mtime:doc.mtime,ttl:(doc.mtime-limit)/1e3/86400,doc});if(0!=notes.length){for(const v2 of notes){this._log(`Deletion history expired: ${v2.path}`);const delDoc=v2.doc;delDoc._deleted=!0;await this.localDatabase.putRaw(delDoc)}this._log("Checking expired file history done")}else{this._log("There are no old documents");this._log("Checking expired file history done")}}async _initializeDatabase(showingNotice=!1,reopenDatabase=!0,ignoreSuspending=!1){this.services.appLifecycle.resetIsReady();if(!reopenDatabase||await this.services.database.openDatabase()){this.localDatabase.isReady&&await this.services.vault.scanVault(showingNotice,ignoreSuspending);if(!await this.services.databaseEvents.onDatabaseInitialised(showingNotice)){this._log("Initializing database has been failed on some module!",LOG_LEVEL_NOTICE);return!1}this.services.appLifecycle.markIsReady();await this.services.fileProcessing.commitPendingFileEvents();return!0}this.services.appLifecycle.resetIsReady();return!1}onBindFunction(core,services){services.databaseEvents.handleInitialiseDatabase(this._initializeDatabase.bind(this));services.vault.handleScanVault(this._performFullScan.bind(this))}};instanceOfAny=(object,constructors)=>constructors.some((c3=>object instanceof c3));transactionDoneMap=new WeakMap;transformCache=new WeakMap;reverseTransformCache=new WeakMap;idbProxyTraps={get(target,prop2,receiver){if(target instanceof IDBTransaction){if("done"===prop2)return transactionDoneMap.get(target);if("store"===prop2)return receiver.objectStoreNames[1]?void 0:receiver.objectStore(receiver.objectStoreNames[0])}return wrap(target[prop2])},set(target,prop2,value){target[prop2]=value;return!0},has:(target,prop2)=>target instanceof IDBTransaction&&("done"===prop2||"store"===prop2)||prop2 in target};unwrap=value=>reverseTransformCache.get(value);readMethods=["get","getKey","getAll","getAllKeys","count"];writeMethods=["put","add","delete","clear"];cachedMethods=new Map;replaceTraps((oldTraps=>({...oldTraps,get:(target,prop2,receiver)=>getMethod(target,prop2)||oldTraps.get(target,prop2,receiver),has:(target,prop2)=>!!getMethod(target,prop2)||oldTraps.has(target,prop2)})));advanceMethodProps=["continue","continuePrimaryKey","advance"];methodMap={};advanceResults=new WeakMap;ittrProxiedCursorToOriginalProxy=new WeakMap;cursorIteratorTraps={get(target,prop2){if(!advanceMethodProps.includes(prop2))return target[prop2];let cachedFunc=methodMap[prop2];cachedFunc||(cachedFunc=methodMap[prop2]=function(...args){advanceResults.set(this,ittrProxiedCursorToOriginalProxy.get(this)[prop2](...args))});return cachedFunc}};replaceTraps((oldTraps=>({...oldTraps,get:(target,prop2,receiver)=>isIteratorProp(target,prop2)?iterate:oldTraps.get(target,prop2,receiver),has:(target,prop2)=>isIteratorProp(target,prop2)||oldTraps.has(target,prop2)})));databaseCache=new Map;IDBKeyValueDatabase=class{constructor(dbKey){this._dbPromise=null;this._isDestroyed=!1;this.destroyedPromise=null;this.dbKey=dbKey;this.storeKey=dbKey}get isDestroyed(){return this._isDestroyed}get ensuredDestroyed(){return this.destroyedPromise?this.destroyedPromise:Promise.resolve()}async getIsReady(){await this.ensureDB();return!1===this.isDestroyed}ensureDB(){if(this._isDestroyed)throw new Error("Database is destroyed");if(this._dbPromise)return this._dbPromise;this._dbPromise=openDB(this.dbKey,void 0,{upgrade:(db,_oldVersion,_newVersion,_transaction,_event)=>{if(!db.objectStoreNames.contains(this.storeKey))return db.createObjectStore(this.storeKey)},blocking:(currentVersion,blockedVersion,event2)=>{Logger(`Blocking database open for ${this.dbKey}: currentVersion=${currentVersion}, blockedVersion=${blockedVersion}`,LOG_LEVEL_VERBOSE);this.closeDB(!0)},blocked:(currentVersion,blockedVersion,event2)=>{Logger(`Database open blocked for ${this.dbKey}: currentVersion=${currentVersion}, blockedVersion=${blockedVersion}`,LOG_LEVEL_VERBOSE)},terminated:()=>{Logger(`Database connection terminated for ${this.dbKey}`,LOG_LEVEL_VERBOSE);this._dbPromise=null}}).catch((e3=>{this._dbPromise=null;throw e3}));return this._dbPromise}async closeDB(setDestroyed=!1){if(this._dbPromise){const tempPromise=this._dbPromise;this._dbPromise=null;try{(await tempPromise).close()}catch(e3){Logger("Error closing database");Logger(e3,LOG_LEVEL_VERBOSE)}}this._dbPromise=null;if(setDestroyed){this._isDestroyed=!0;this.destroyedPromise=Promise.resolve()}}get DB(){return this._isDestroyed?Promise.reject(new Error("Database is destroyed")):this.ensureDB()}async get(key3){const db=await this.DB;return await db.get(this.storeKey,key3)}async set(key3,value){const db=await this.DB;await db.put(this.storeKey,value,key3);return key3}async del(key3){const db=await this.DB;return await db.delete(this.storeKey,key3)}async clear(){const db=await this.DB;return await db.clear(this.storeKey)}async keys(query3,count){const db=await this.DB;return await db.getAllKeys(this.storeKey,query3,count)}async close(){await this.closeDB()}async destroy(){this._isDestroyed=!0;this.destroyedPromise=(async()=>{await this.closeDB();await deleteDB(this.dbKey,{blocked:()=>{Logger(`Database delete blocked for ${this.dbKey}`)}})})();await this.destroyedPromise}};ModuleKeyValueDB=class extends AbstractModule{async tryCloseKvDB(){var _a8;try{await(null==(_a8=this.core.kvDB)?void 0:_a8.close());return!0}catch(e3){this._log("Failed to close KeyValueDB",LOG_LEVEL_VERBOSE);this._log(e3);return!1}}async openKeyValueDB(){await delay(10);try{await this.tryCloseKvDB();await delay(10);await yieldMicrotask();this.core.kvDB=await OpenKeyValueDatabase(this.services.vault.getVaultName()+"-livesync-kv");await yieldMicrotask();await delay(100)}catch(e3){this.core.kvDB=void 0;this._log("Failed to open KeyValueDB",LOG_LEVEL_NOTICE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}return!0}async _onDBUnload(db){this.core.kvDB&&await this.core.kvDB.close();return Promise.resolve(!0)}async _onDBClose(db){this.core.kvDB&&await this.core.kvDB.close();return Promise.resolve(!0)}async _everyOnloadAfterLoadSettings(){if(!await this.openKeyValueDB())return!1;this.core.simpleStore=this.services.database.openSimpleStore("os");return Promise.resolve(!0)}_getSimpleStore(kind){const getDB=()=>this.core.kvDB,prefix=`${kind}-`;return{get:async key3=>await getDB().get(`${prefix}${key3}`),set:async(key3,value)=>{await getDB().set(`${prefix}${key3}`,value)},delete:async key3=>{await getDB().del(`${prefix}${key3}`)},keys:async(from,to,count)=>(await getDB().keys(IDBKeyRange.bound(`${prefix}${from||""}`,`${prefix}${to||""}`),count)).map((e3=>e3.toString())).filter((e3=>e3.startsWith(prefix))).map((e3=>e3.substring(prefix.length)))}}_everyOnInitializeDatabase(db){return this.openKeyValueDB()}async _everyOnResetDatabase(db){try{const kvDBKey="queued-files";await this.core.kvDB.del(kvDBKey);await this.core.kvDB.destroy();await yieldMicrotask();this.core.kvDB=await OpenKeyValueDatabase(this.services.vault.getVaultName()+"-livesync-kv");await delay(100)}catch(e3){this.core.kvDB=void 0;this._log("Failed to reset KeyValueDB",LOG_LEVEL_NOTICE);this._log(e3,LOG_LEVEL_VERBOSE);return!1}return!0}onBindFunction(core,services){services.databaseEvents.handleOnUnloadDatabase(this._onDBUnload.bind(this));services.databaseEvents.handleOnCloseDatabase(this._onDBClose.bind(this));services.databaseEvents.handleOnDatabaseInitialisation(this._everyOnInitializeDatabase.bind(this));services.databaseEvents.handleOnResetDatabase(this._everyOnResetDatabase.bind(this));services.database.handleOpenSimpleStore(this._getSimpleStore.bind(this));services.appLifecycle.handleOnSettingLoaded(this._everyOnloadAfterLoadSettings.bind(this))}};ModulePouchDB=class extends AbstractModule{_createPouchDBInstance(name,options){const optionPass=null!=options?options:{};if(this.settings.useIndexedDBAdapter){optionPass.adapter="indexeddb";optionPass.purged_infos_limit=1;return new index_es_default(name+ExtraSuffixIndexedDB,optionPass)}return new index_es_default(name,optionPass)}onBindFunction(core,services){services.database.handleCreatePouchDBInstance(this._createPouchDBInstance.bind(this))}};ReplicateResultProcessor=class{constructor(replicator){this._suspended=!1;this.triggerTakeSnapshot=throttle((()=>this._triggerTakeSnapshot()),50);this._restoreFromSnapshot=void 0;this._queuedChanges=[];this._processingChanges=[];this._semaphore=Semaphore(10);this._isRunningProcessQueue=!1;this.replicator=replicator}log(message,level=LOG_LEVEL_INFO){Logger(`[ReplicateResultProcessor] ${message}`,level)}logError(e3){Logger(e3,LOG_LEVEL_VERBOSE)}get localDatabase(){return this.replicator.core.localDatabase}get services(){return this.replicator.core.services}get core(){return this.replicator.core}suspend(){this._suspended=!0}resume(){this._suspended=!1;fireAndForget((()=>this.runProcessQueue()))}get isSuspended(){return this._suspended||!this.core.services.appLifecycle.isReady||this.replicator.settings.suspendParseReplicationResult||this.core.services.appLifecycle.isSuspended()}async _takeSnapshot(){const snapshot2={queued:this._queuedChanges.slice(),processing:this._processingChanges.slice()};await this.core.kvDB.set("replicationResultProcessorSnapshot",snapshot2);this.log(`Snapshot taken. Queued: ${snapshot2.queued.length}, Processing: ${snapshot2.processing.length}`,LOG_LEVEL_DEBUG);this.reportStatus()}_triggerTakeSnapshot(){fireAndForget((()=>this._takeSnapshot()))}async restoreFromSnapshot(){const snapshot2=await this.core.kvDB.get("replicationResultProcessorSnapshot");if(snapshot2){const newQueue=[...snapshot2.processing,...snapshot2.queued,...this._queuedChanges];this._queuedChanges=[];this.enqueueAll(newQueue);this.log(`Restored from snapshot (${snapshot2.processing.length+snapshot2.queued.length} items)`,LOG_LEVEL_INFO)}}restoreFromSnapshotOnce(){this._restoreFromSnapshot||(this._restoreFromSnapshot=this.restoreFromSnapshot());return this._restoreFromSnapshot}async withCounting(proc,countValue){countValue.value++;try{return await proc()}finally{countValue.value--}}reportStatus(){this.core.replicationResultCount.value=this._queuedChanges.length+this._processingChanges.length}enqueueAll(changes3){for(const change of changes3)this.processIfNonDocumentChange(change)||this.enqueueChange(change)}processIfNonDocumentChange(change){if(!change){this.log("Received empty change",LOG_LEVEL_VERBOSE);return!0}if(isChunk(change._id)){this.localDatabase.onNewLeaf(change);this.log(`Processed chunk: ${shortenId(change._id)}`,LOG_LEVEL_DEBUG);return!0}if("versioninfo"==change.type){this.log(`Version info document received: ${change._id}`,LOG_LEVEL_VERBOSE);if(change.version>12){this.core.replicator.closeReplication();this.log("Remote database updated to incompatible version. update your Self-hosted LiveSync plugin.",LOG_LEVEL_NOTICE)}return!0}if(change._id==SYNCINFO_ID||change._id.startsWith("_design")){this.log(`Skipped system document: ${change._id}`,LOG_LEVEL_VERBOSE);return!0}return!1}enqueueChange(doc){var _a8;const old=this._queuedChanges.find((e3=>e3._id==doc._id)),docNote=`${"path"in doc?getPath2(doc):"<unknown>"} (${shortenId(doc._id)}, ${shortenRev(doc._rev)})`;if(old){if(old._rev==doc._rev){this.log(`[Enqueue] skipped (Already queued): ${docNote}`,LOG_LEVEL_VERBOSE);return}const oldRev=null!=(_a8=old._rev)?_a8:"";if((!0===old._deleted||"deleted"in old&&!0===old.deleted)==(!0===doc._deleted||"deleted"in doc&&!0===doc.deleted)){this._queuedChanges=this._queuedChanges.filter((e3=>e3._id!=doc._id));this.log(`[Enqueue] requeued: ${docNote} (from rev: ${shortenRev(oldRev)})`,LOG_LEVEL_VERBOSE)}}this._queuedChanges.push(doc);this.triggerTakeSnapshot();this.triggerProcessQueue()}triggerProcessQueue(){fireAndForget((()=>this.runProcessQueue()))}async runProcessQueue(){if(!this._isRunningProcessQueue&&!this.isSuspended&&0!=this._queuedChanges.length)try{this._isRunningProcessQueue=!0;for(;this._queuedChanges.length>0;){if(this.isSuspended){this.log(`Processing has got suspended. Remaining items in queue: ${this._queuedChanges.length}`,LOG_LEVEL_INFO);break}(await this._semaphore.acquire())();const doc=this._queuedChanges.shift();if(doc){this._processingChanges.push(doc);this.parseDocumentChange(doc)}this.triggerTakeSnapshot()}}finally{this._isRunningProcessQueue=!1}}async parseDocumentChange(change){try{if(await this.services.replication.processVirtualDocument(change))return;if(isAnyNote(change)){const docPath=getPath2(change);if(!await this.services.vault.isTargetFile(docPath)){this.log(`Skipped: ${docPath}`,LOG_LEVEL_VERBOSE);return}const size=change.size;if(this.services.vault.isFileSizeTooLarge(size)){this.log(`Processing ${docPath} has been skipped due to file size exceeding the limit`,LOG_LEVEL_NOTICE);return}return await this.applyToDatabase(change)}this.log(`Skipped unexpected non-note document: ${change._id}`,LOG_LEVEL_INFO);return}finally{this._processingChanges=this._processingChanges.filter((e3=>e3!==change));this.triggerTakeSnapshot()}}applyToDatabase(doc){return this.withCounting((async()=>{let releaser;try{releaser=await this._semaphore.acquire();await this._applyToDatabase(doc)}catch(e3){this.log("Error while processing replication result",LOG_LEVEL_NOTICE);this.logError(e3)}finally{releaser&&releaser()}}),this.replicator.core.databaseQueueCount)}_applyToDatabase(doc_){const dbDoc=doc_,path2=getPath2(dbDoc);return serialized(`replication-process:${dbDoc._id}`,(async()=>{const docNote=`${path2} (${shortenId(dbDoc._id)}, ${shortenRev(dbDoc._rev)})`;if(!await this.checkIsChangeRequiredForDatabaseProcessing(dbDoc)){this.log(`Skipped (Not latest): ${docNote}`,LOG_LEVEL_VERBOSE);return}const doc=!0===dbDoc._deleted||"deleted"in dbDoc&&!0===dbDoc.deleted?{...dbDoc,data:""}:await this.localDatabase.getDBEntryFromMeta({...dbDoc},!1,!0);if(doc)if(await this.services.replication.processOptionalSynchroniseResult(dbDoc))this.log(`Processed by other processor: ${docNote}`,LOG_LEVEL_DEBUG);else if(isValidPath(getPath2(doc))){await this.applyToStorage(doc);this.log(`Processed: ${docNote}`,LOG_LEVEL_DEBUG)}else this.log(`Unprocessed (Invalid path): ${docNote}`,LOG_LEVEL_VERBOSE);else this.log(`Failed to gather content of ${docNote}`,LOG_LEVEL_NOTICE)}))}applyToStorage(entry){return this.withCounting((async()=>{await this.services.replication.processSynchroniseResult(entry)}),this.replicator.core.storageApplyingCount)}async checkIsChangeRequiredForDatabaseProcessing(dbDoc){var _a8,_b5,_c3,_d2;const path2=getPath2(dbDoc);try{const savedDoc=await this.localDatabase.getRaw(dbDoc._id,{conflicts:!0,revs_info:!0}),newRev=null!=(_a8=dbDoc._rev)?_a8:"",latestRev=null!=(_b5=savedDoc._rev)?_b5:"",revisions=null!=(_d2=null==(_c3=savedDoc._revs_info)?void 0:_c3.map((e3=>e3.rev)))?_d2:[];return!(!(savedDoc._conflicts&&savedDoc._conflicts.length>0)&&newRev!=latestRev&&revisions.indexOf(newRev)>=0)}catch(e3){if("status"in e3&&404==e3.status)return!0;this.log(`Failed to get existing document for ${path2} (${shortenId(dbDoc._id)}, ${shortenRev(dbDoc._rev)}) `,LOG_LEVEL_NOTICE);this.logError(e3);return!1}}};ModuleReplicator=class extends AbstractModule{constructor(){super(...arguments);this._previousErrors=new Set;this.processor=new ReplicateResultProcessor(this)}showError(msg,max_log_level=LEVEL_NOTICE){const level=this._previousErrors.has(msg)?LEVEL_INFO:max_log_level;this._log(msg,level);if(!this._previousErrors.has(msg)){this._previousErrors.add(msg);eventHub.emitEvent("on-unresolved-error")}}clearErrors(){this._previousErrors.clear();eventHub.emitEvent("on-unresolved-error")}_everyOnloadAfterLoadSettings(){eventHub.onEvent("file-saved",(()=>{this.settings.syncOnSave&&!this.core.services.appLifecycle.isSuspended()&&scheduleTask("perform-replicate-after-save",250,(()=>this.services.replication.replicateByEvent()))}));eventHub.onEvent(EVENT_SETTING_SAVED,(setting=>{this._replicatorType!==setting.remoteType&&this.setReplicator();this.core.settings.suspendParseReplicationResult?this.processor.suspend():this.processor.resume()}));return Promise.resolve(!0)}async setReplicator(){const replicator=await this.services.replicator.getNewReplicator();if(!replicator){this.showError($msg("Replicator.Message.InitialiseFatalError"),LOG_LEVEL_NOTICE);return!1}if(this.core.replicator){await this.core.replicator.closeReplication();this._log("Replicator closed for changing",LOG_LEVEL_VERBOSE)}this.core.replicator=replicator;this._replicatorType=this.settings.remoteType;await yieldMicrotask();clearHandlers();return!0}_getReplicator(){return this.core.replicator}_everyOnInitializeDatabase(db){return this.setReplicator()}_everyOnDatabaseInitialized(showNotice){fireAndForget((()=>this.processor.restoreFromSnapshotOnce()));return Promise.resolve(!0)}_everyOnResetDatabase(db){return this.setReplicator()}async ensureReplicatorPBKDF2Salt(showMessage=!1){const replicator=this.services.replicator.getActiveReplicator();if(!replicator){this.showError($msg("Replicator.Message.InitialiseFatalError"),LOG_LEVEL_NOTICE);return!1}return await replicator.ensurePBKDF2Salt(this.settings,showMessage,!0)}async _everyBeforeReplicate(showMessage){if(!this.core.managers.networkManager.isOnline){this.showError("Network is offline",showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}if(!await this.ensureReplicatorPBKDF2Salt(!1)){this.showError("Failed to initialise the encryption key, preventing replication.");return!1}await this.processor.restoreFromSnapshotOnce();this.clearErrors();return!0}async _replicate(showMessage=!1){try{updatePreviousExecutionTime("replicationOnEvent",5e3);return await this.$$_replicate(showMessage)}finally{updatePreviousExecutionTime("replicationOnEvent")}}async cleaned(showMessage){Logger("The remote database has been cleaned.",showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);await skipIfDuplicated("cleanup",(async()=>{var _a8;const message=`The remote database has been cleaned up.\nTo synchronize, this device must be also cleaned up. ${await purgeUnreferencedChunks(this.localDatabase.localDatabase,!0)} chunk(s) will be erased from this device.\nHowever, If there are many chunks to be deleted, maybe fetching again is faster.\nWe will lose the history of this device if we fetch the remote database again.\nEven if you choose to clean up, you will see this option again if you exit Obsidian and then synchronise again.`,ret=await this.core.confirm.confirmWithMessage("Cleaned",message,["Fetch again","Cleanup","Dismiss"],"Dismiss",30);"Fetch again"==ret&&await this.core.rebuilder.$performRebuildDB("localOnly");if("Cleanup"==ret){const replicator=this.services.replicator.getActiveReplicator();if(!(replicator instanceof LiveSyncCouchDBReplicator))return;const remoteDB=await replicator.connectRemoteCouchDBWithSetting(this.settings,this.services.API.isMobile(),!0);if("string"==typeof remoteDB){Logger(remoteDB,LOG_LEVEL_NOTICE);return!1}await purgeUnreferencedChunks(this.localDatabase.localDatabase,!1);this.localDatabase.clearCaches();if(await this.core.replicator.openReplication(this.settings,!1,showMessage,!0)){await balanceChunkPurgedDBs(this.localDatabase.localDatabase,remoteDB.db);await purgeUnreferencedChunks(this.localDatabase.localDatabase,!1);this.localDatabase.clearCaches();await(null==(_a8=this.services.replicator.getActiveReplicator())?void 0:_a8.markRemoteResolved(this.settings));Logger("The local database has been cleaned up.",showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO)}else Logger("Replication has been cancelled. Please try it again.",showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO)}}))}async _canReplicate(showMessage=!1){if(!this.services.appLifecycle.isReady()){Logger("Not ready");return!1}if(isLockAcquired("cleanup")){Logger($msg("Replicator.Message.Cleaned"),LOG_LEVEL_NOTICE);return!1}if(""!=this.settings.versionUpFlash){Logger($msg("Replicator.Message.VersionUpFlash"),LOG_LEVEL_NOTICE);return!1}if(!await this.services.fileProcessing.commitPendingFileEvents()){this.showError($msg("Replicator.Message.Pending"),LOG_LEVEL_NOTICE);return!1}if(!this.core.managers.networkManager.isOnline){this.showError("Network is offline",showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO);return!1}if(!await this.services.replication.onBeforeReplicate(showMessage)){this.showError($msg("Replicator.Message.SomeModuleFailed"),LOG_LEVEL_NOTICE);return!1}this.clearErrors();return!0}async $$_replicate(showMessage=!1){var _a8;if(!await this.services.replication.isReplicationReady(showMessage))return!1;const ret=await this.core.replicator.openReplication(this.settings,!1,showMessage,!1);if(!ret)if(this.core.replicator.tweakSettingsMismatched&&this.core.replicator.preferredTweakValue)await this.services.tweakValue.askResolvingMismatched(this.core.replicator.preferredTweakValue);else if(null==(_a8=this.core.replicator)?void 0:_a8.remoteLockedAndDeviceNotAccepted)if(this.core.replicator.remoteCleaned&&this.settings.useIndexedDBAdapter)await this.cleaned(showMessage);else{const message=$msg("Replicator.Dialogue.Locked.Message"),CHOICE_FETCH=$msg("Replicator.Dialogue.Locked.Action.Fetch"),CHOICE_DISMISS=$msg("Replicator.Dialogue.Locked.Action.Dismiss"),CHOICE_UNLOCK=$msg("Replicator.Dialogue.Locked.Action.Unlock"),ret2=await this.core.confirm.askSelectStringDialogue(message,[CHOICE_FETCH,CHOICE_UNLOCK,CHOICE_DISMISS],{title:$msg("Replicator.Dialogue.Locked.Title"),defaultAction:CHOICE_DISMISS,timeout:60});if(ret2==CHOICE_FETCH){this._log($msg("Replicator.Dialogue.Locked.Message.Fetch"),LOG_LEVEL_NOTICE);await this.core.rebuilder.scheduleFetch();this.services.appLifecycle.scheduleRestart();return}if(ret2==CHOICE_UNLOCK){await this.core.replicator.markRemoteResolved(this.settings);this._log($msg("Replicator.Dialogue.Locked.Message.Unlocked"),LOG_LEVEL_NOTICE);return}}return ret}async _replicateByEvent(){const least=this.settings.syncMinimumInterval;return least>0?rateLimitedSharedExecution("replicationOnEvent",least,(async()=>await this.services.replication.replicate())):await shareRunningResult("replication",(()=>this.services.replication.replicate()))}_parseReplicationResult(docs){this.processor.enqueueAll(docs)}_everyBeforeSuspendProcess(){var _a8;null==(_a8=this.core.replicator)||_a8.closeReplication();return Promise.resolve(!0)}async _replicateAllToServer(showingNotice=!1,sendChunksInBulkDisabled=!1){if(!this.services.appLifecycle.isReady())return!1;if(!await this.services.replication.onBeforeReplicate(showingNotice)){Logger($msg("Replicator.Message.SomeModuleFailed"),LOG_LEVEL_NOTICE);return!1}sendChunksInBulkDisabled||this.core.replicator instanceof LiveSyncCouchDBReplicator&&"yes"==await this.core.confirm.askYesNoDialog("Do you want to send all chunks before replication?",{defaultOption:"No",timeout:20})&&await this.core.replicator.sendChunks(this.core.settings,void 0,!0,0);if(await this.core.replicator.replicateAllToServer(this.settings,showingNotice))return!0;const checkResult=await this.services.replication.checkConnectionFailure();return"CHECKAGAIN"==checkResult?await this.services.remote.replicateAllToRemote(showingNotice):!checkResult}async _replicateAllFromServer(showingNotice=!1){if(!this.services.appLifecycle.isReady())return!1;if(await this.core.replicator.replicateAllFromServer(this.settings,showingNotice))return!0;const checkResult=await this.services.replication.checkConnectionFailure();return"CHECKAGAIN"==checkResult?await this.services.remote.replicateAllFromRemote(showingNotice):!checkResult}_reportUnresolvedMessages(){return Promise.resolve([...this._previousErrors])}onBindFunction(core,services){services.replicator.handleGetActiveReplicator(this._getReplicator.bind(this));services.databaseEvents.handleOnDatabaseInitialisation(this._everyOnInitializeDatabase.bind(this));services.databaseEvents.handleDatabaseInitialised(this._everyOnDatabaseInitialized.bind(this));services.databaseEvents.handleOnResetDatabase(this._everyOnResetDatabase.bind(this));services.appLifecycle.handleOnSettingLoaded(this._everyOnloadAfterLoadSettings.bind(this));services.replication.handleParseSynchroniseResult(this._parseReplicationResult.bind(this));services.appLifecycle.handleOnSuspending(this._everyBeforeSuspendProcess.bind(this));services.replication.handleBeforeReplicate(this._everyBeforeReplicate.bind(this));services.replication.handleIsReplicationReady(this._canReplicate.bind(this));services.replication.handleReplicate(this._replicate.bind(this));services.replication.handleReplicateByEvent(this._replicateByEvent.bind(this));services.remote.handleReplicateAllToRemote(this._replicateAllToServer.bind(this));services.remote.handleReplicateAllFromRemote(this._replicateAllFromServer.bind(this));services.appLifecycle.reportUnresolvedMessages(this._reportUnresolvedMessages.bind(this))}};ModuleReplicatorCouchDB=class extends AbstractModule{_anyNewReplicator(settingOverride={}){const settings={...this.settings,...settingOverride};return settings.remoteType==REMOTE_MINIO||settings.remoteType==REMOTE_P2P?Promise.resolve(!1):Promise.resolve(new LiveSyncCouchDBReplicator(this.core))}_everyAfterResumeProcess(){if(this.services.appLifecycle.isSuspended())return Promise.resolve(!0);if(!this.services.appLifecycle.isReady())return Promise.resolve(!0);if(this.settings.remoteType!=REMOTE_MINIO&&this.settings.remoteType!=REMOTE_P2P){const LiveSyncEnabled=this.settings.liveSync,continuous=LiveSyncEnabled,eventualOnStart=!LiveSyncEnabled&&this.settings.syncOnStart;(LiveSyncEnabled||eventualOnStart)&&fireAndForget((async()=>{await this.services.replication.isReplicationReady(!1)&&this.core.replicator.openReplication(this.settings,continuous,!1,!1)}))}return Promise.resolve(!0)}onBindFunction(core,services){services.replicator.handleGetNewReplicator(this._anyNewReplicator.bind(this));services.appLifecycle.handleOnResumed(this._everyAfterResumeProcess.bind(this))}};ModuleReplicatorMinIO=class extends AbstractModule{_anyNewReplicator(settingOverride={}){return{...this.settings,...settingOverride}.remoteType==REMOTE_MINIO?Promise.resolve(new LiveSyncJournalReplicator(this.core)):Promise.resolve(!1)}onBindFunction(core,services){services.replicator.handleGetNewReplicator(this._anyNewReplicator.bind(this))}};ModuleTargetFilter=class extends AbstractModule{constructor(){super(...arguments);this.totalFileEventCount=0;this.ignoreFileCache=new LRUCache(300,25e4,!0);this.ignoreFiles=[]}reloadIgnoreFiles(){this.ignoreFiles=this.settings.ignoreFiles.split(",").map((e3=>e3.trim()))}_everyOnload(){this.reloadIgnoreFiles();eventHub.onEvent(EVENT_SETTING_SAVED,(evt=>{this.reloadIgnoreFiles()}));eventHub.onEvent("reload-setting-tab",(()=>{this.reloadIgnoreFiles()}));return Promise.resolve(!0)}_id2path(id,entry,stripPrefix2){const tempId=id2path(id,entry);return stripPrefix2&&isInternalMetadata(tempId)?stripInternalMetadataPrefix(tempId):tempId}async _path2id(filename,prefix){const destPath=addPrefix(filename,null!=prefix?prefix:"");return await path2id(destPath,this.settings.usePathObfuscation?this.settings.passphrase:"",!this.settings.handleFilenameCaseSensitive)}_isFileSizeExceeded(size){return this.settings.syncMaxSizeInMB>0&&size>0&&1024*this.settings.syncMaxSizeInMB*1024<size}_markFileListPossiblyChanged(){this.totalFileEventCount++}get fileListPossiblyChanged(){return!!isDirty("totalFileEventCount",this.totalFileEventCount)}async _isTargetFile(file,keepFileCheckList=!1){var _a8,_b5;const fileCount=useMemo({key:"fileCount"},((ctx,prev)=>{var _a9;if(keepFileCheckList&&prev)return prev;if(!keepFileCheckList&&prev&&!this.fileListPossiblyChanged)return prev;const fileList=null!=(_a9=ctx.get("fileList"))?_a9:[],vaultFiles=this.core.storageAccess.getFileNames().sort();if(prev&&vaultFiles.length==fileList.length){const fl3=new Set([...fileList,...vaultFiles]);if(fileList.length==fl3.size&&vaultFiles.length==fl3.size)return prev}ctx.set("fileList",vaultFiles);const fileCount2={};for(const file2 of vaultFiles){const lc3=file2.toLowerCase();fileCount2[lc3]?fileCount2[lc3]++:fileCount2[lc3]=1}return fileCount2})),filepath=getStoragePathFromUXFileInfo(file),lc2=filepath.toLowerCase();if(this.services.setting.shouldCheckCaseInsensitively()&&lc2 in fileCount&&fileCount[lc2]>1)return!1;const fileNameLC=null==(_a8=getStoragePathFromUXFileInfo(file).split("/").pop())?void 0:_a8.toLowerCase();if(this.settings.useIgnoreFiles){this.ignoreFiles.some((e3=>e3.toLowerCase()==fileNameLC))&&await this.readIgnoreFile(filepath);if(await this.services.vault.isIgnoredByIgnoreFile(file))return!1}return!!(null==(_b5=this.localDatabase)?void 0:_b5.isTargetFile(filepath))}async readIgnoreFile(path2){try{if(!await this.core.storageAccess.isExistsIncludeHidden(path2)){this.ignoreFileCache.set(path2,!1);return!1}const gitignore=(await this.core.storageAccess.readHiddenFileText(path2)).split(/\r?\n/g);this.ignoreFileCache.set(path2,gitignore);this._log(`[ignore]Ignore file loaded: ${path2}`,LOG_LEVEL_VERBOSE);return gitignore}catch(ex){this._log(`[ignore]Failed to read ignore file ${path2}`);this._log(ex,LOG_LEVEL_VERBOSE);this.ignoreFileCache.set(path2,!1);return!1}}async getIgnoreFile(path2){var _a8;return this.ignoreFileCache.has(path2)?null!=(_a8=this.ignoreFileCache.get(path2))&&_a8:await this.readIgnoreFile(path2)}async _isIgnoredByIgnoreFiles(file){if(!this.settings.useIgnoreFiles)return!1;const filepath=getStoragePathFromUXFileInfo(file);this.ignoreFileCache.has(filepath)&&await this.readIgnoreFile(filepath);return!await isAcceptedAll(filepath,this.ignoreFiles,(filename=>this.getIgnoreFile(filename)))}onBindFunction(core,services){services.vault.handleMarkFileListPossiblyChanged(this._markFileListPossiblyChanged.bind(this));services.path.handleId2Path(this._id2path.bind(this));services.path.handlePath2Id(this._path2id.bind(this));services.appLifecycle.handleOnLoaded(this._everyOnload.bind(this));services.vault.handleIsFileSizeTooLarge(this._isFileSizeExceeded.bind(this));services.vault.handleIsIgnoredByIgnoreFile(this._isIgnoredByIgnoreFiles.bind(this));services.vault.handleIsTargetFile(this._isTargetFile.bind(this))}};ModulePeriodicProcess=class extends AbstractModule{constructor(){super(...arguments);this.periodicSyncProcessor=new PeriodicProcessor(this.core,(async()=>await this.services.replication.replicate()))}disablePeriodic(){var _a8;null==(_a8=this.periodicSyncProcessor)||_a8.disable();return Promise.resolve(!0)}resumePeriodic(){this.periodicSyncProcessor.enable(this.settings.periodicReplication?1e3*this.settings.periodicReplicationInterval:0);return Promise.resolve(!0)}_allOnUnload(){return this.disablePeriodic()}_everyBeforeRealizeSetting(){return this.disablePeriodic()}_everyBeforeSuspendProcess(){return this.disablePeriodic()}_everyAfterResumeProcess(){return this.resumePeriodic()}_everyAfterRealizeSetting(){return this.resumePeriodic()}onBindFunction(core,services){services.appLifecycle.handleOnUnload(this._allOnUnload.bind(this));services.setting.handleBeforeRealiseSetting(this._everyBeforeRealizeSetting.bind(this));services.setting.handleSettingRealised(this._everyAfterRealizeSetting.bind(this));services.appLifecycle.handleOnSuspending(this._everyBeforeSuspendProcess.bind(this));services.appLifecycle.handleOnResumed(this._everyAfterResumeProcess.bind(this))}};ModuleRemoteGovernor=class extends AbstractModule{async _markRemoteLocked(lockByClean=!1){return await this.core.replicator.markRemoteLocked(this.settings,!0,lockByClean)}async _markRemoteUnlocked(){return await this.core.replicator.markRemoteLocked(this.settings,!1,!1)}async _markRemoteResolved(){return await this.core.replicator.markRemoteResolved(this.settings)}onBindFunction(core,services){services.remote.handleMarkLocked(this._markRemoteLocked.bind(this));services.remote.handleMarkUnlocked(this._markRemoteUnlocked.bind(this));services.remote.handleMarkResolved(this._markRemoteResolved.bind(this))}};ContentSplitterCore=class{constructor(params){this.options=params;this.initialised=this.initialise(params)}};ContentSplitterBase=class extends ContentSplitterCore{initialise(_options3){return Promise.resolve(!0)}static isAvailableFor(setting){return!1}getParamsFor(entry){const pieceSize=Math.floor(102400*(1*(this.options.settings.customChunkSize||0)+1)),minimumChunkSize=this.options.settings.minimumChunkSize,path2=entry.path,plainSplit=shouldSplitAsPlainText(path2),blob=entry.data instanceof Blob?entry.data:createTextBlob(entry.data);let useWorker=!0;this.options.settings.disableWorkerForGeneratingChunks&&(useWorker=!1);useWorker&&this.options.settings.processSmallFilesInUIThread&&blob.size<=1024&&(useWorker=!1);return{blob,path:path2,pieceSize,plainSplit,minimumChunkSize,useWorker,useSegmenter:"v2-segmenter"===this.options.settings.chunkSplitterVersion}}async splitContent(entry){await this.initialised;const options=this.getParamsFor(entry);return await this.processSplit(options)}};charNewLine="\n".charCodeAt(0);segmenter="Segmenter"in Intl?function wrapByDefault(func,onError){try{return func()}catch(ex){return onError(ex)}}((()=>new Intl.Segmenter(navigator.language,{granularity:"sentence"})),(err3=>{Logger(`Failed to create Intl.Segmenter: ${err3.message}`,LOG_LEVEL_VERBOSE)})):void 0;MAX_ITEMS=100;ContentSplitterRabinKarp=class extends ContentSplitterBase{static isAvailableFor(setting){return"v3-rabin-karp"===setting.settings.chunkSplitterVersion}async processSplit(options){return options.useWorker?splitPieces2WorkerRabinKarp(options.blob,options.pieceSize,options.plainSplit,options.minimumChunkSize,options.path)():(await splitPiecesRabinKarp(options.blob,options.pieceSize,options.plainSplit,options.minimumChunkSize,options.path))()}};ContentSplitters=[class extends ContentSplitterBase{static isAvailableFor(setting){return"v1"===setting.settings.chunkSplitterVersion||""===setting.settings.chunkSplitterVersion}async processSplit(options){return options.useWorker?splitPieces2Worker(options.blob,options.pieceSize,options.plainSplit,options.minimumChunkSize,options.path,options.useSegmenter)():(await splitPieces2(options.blob,options.pieceSize,options.plainSplit,options.minimumChunkSize,options.path,options.useSegmenter))()}},class extends ContentSplitterBase{static isAvailableFor(setting){return"v2"===setting.settings.chunkSplitterVersion||"v2-segmenter"===setting.settings.chunkSplitterVersion}async processSplit(options){return options.useWorker?splitPieces2WorkerV2(options.blob,options.pieceSize,options.plainSplit,options.minimumChunkSize,options.path,options.useSegmenter)():(await splitPieces2V2(options.blob,options.pieceSize,options.plainSplit,options.minimumChunkSize,options.path,options.useSegmenter))()}},ContentSplitterRabinKarp];ContentSplitter=class extends ContentSplitterCore{constructor(options){super(options)}initialise(options){for(const Splitter of ContentSplitters)if(Splitter.isAvailableFor(options)){this._activeSplitter=new Splitter(options);break}if(!this._activeSplitter)throw new Error("ContentSplitter: No available splitter for settings!!");return this._activeSplitter.initialise(options)}async splitContent(entry){await this.initialised;return this._activeSplitter.splitContent(entry)}};ChangeManager=class{constructor(options){this._callbacks=[];this._database=options.database;this.setupListener()}addCallback(callback){const callbackHandler=new FallbackWeakRef(callback);this._callbacks.push(callbackHandler);return()=>{this._callbacks=this._callbacks.filter((cb2=>cb2!==callbackHandler))}}removeCallback(callback){this._callbacks=this._callbacks.filter((cb2=>cb2.deref()!==callback))}_onChange(changeResponse){if(this._callbacks.length){this._callbacks=this._callbacks.filter((callback=>void 0!==callback.deref()));for(const callback of this._callbacks){const cb2=callback.deref();cb2&&cb2(changeResponse)}}}setupListener(){var _a8,_b5;if(this._changes){null==(_a8=this._changes)||_a8.removeAllListeners();null==(_b5=this._changes)||_b5.cancel();this._changes=void 0}const changes3=this._database.changes({since:"now",live:!0,include_docs:!0});changes3.on("change",(change=>{this._onChange(change)}));changes3.on("error",(err3=>{Logger("ChangeManager Error watching changes");Logger(err3,LOG_LEVEL_VERBOSE)}));this._changes=changes3}teardown(){var _a8,_b5;null==(_a8=this._changes)||_a8.removeAllListeners();null==(_b5=this._changes)||_b5.cancel();this._changes=void 0}restartWatch(){this.teardown();this.setupListener()}};import_diff_match_patch4=__toESM(require_diff_match_patch(),1);ConflictManager=class{constructor(options){this.options=options}get database(){return this.options.database}async getConflictedDoc(path2,rev3){try{const doc=await this.options.entryManager.getDBEntry(path2,{rev:rev3},!1,!0,!0);if(!1===doc)return!1;let data=getDocData(doc.data);"newnote"==doc.datatype?data=readString(new Uint8Array(decodeBinary(doc.data))):doc.datatype;return{deleted:doc.deleted||doc._deleted,ctime:doc.ctime,mtime:doc.mtime,rev:rev3,data}}catch(ex){if(isErrorOfMissingDoc(ex))return!1}return!1}async mergeSensibly(path2,baseRev,currentRev,conflictedRev){function splitDiffPiece(src){const ret=[];do{const d4=src.shift();if(void 0===d4)return ret;const pieces=d4[1].split(/([^\n]*\n)/).filter((f4=>""!=f4));if(void 0===d4)break;d4[0]!=import_diff_match_patch4.DIFF_DELETE&&ret.push(...pieces.map((e3=>[d4[0],e3])));if(d4[0]==import_diff_match_patch4.DIFF_DELETE){const nd=src.shift();if(void 0!==nd){const piecesPair=nd[1].split(/([^\n]*\n)/).filter((f4=>""!=f4));if(nd[0]==import_diff_match_patch4.DIFF_INSERT){for(const pt of pieces){ret.push([d4[0],pt]);const pairP=piecesPair.shift();void 0!==pairP&&ret.push([import_diff_match_patch4.DIFF_INSERT,pairP])}ret.push(...piecesPair.map((e3=>[nd[0],e3])))}else{ret.push(...pieces.map((e3=>[d4[0],e3])));ret.push(...piecesPair.map((e3=>[nd[0],e3])))}}else ret.push(...pieces.map((e3=>[0,e3])))}}while(src.length>0);return ret}var _a8,_b5,_c3,_d2;const baseLeaf=await this.getConflictedDoc(path2,baseRev),leftLeaf=await this.getConflictedDoc(path2,currentRev),rightLeaf=await this.getConflictedDoc(path2,conflictedRev);let autoMerge=!1;if(0==baseLeaf||0==leftLeaf||0==rightLeaf)return!1;if(leftLeaf.deleted&&rightLeaf.deleted)return!1;const dmp=new import_diff_match_patch4.diff_match_patch,mapLeft=dmp.diff_linesToChars_(baseLeaf.data,leftLeaf.data),diffLeftSrc=dmp.diff_main(mapLeft.chars1,mapLeft.chars2,!1);dmp.diff_charsToLines_(diffLeftSrc,mapLeft.lineArray);const mapRight=dmp.diff_linesToChars_(baseLeaf.data,rightLeaf.data),diffRightSrc=dmp.diff_main(mapRight.chars1,mapRight.chars2,!1);dmp.diff_charsToLines_(diffRightSrc,mapRight.lineArray);const diffLeft=splitDiffPiece(diffLeftSrc),diffRight=splitDiffPiece(diffRightSrc);let rightIdx=0,leftIdx=0;const merged=[];autoMerge=!0;LOOP_MERGE:do{if(leftIdx>=diffLeft.length&&rightIdx>=diffRight.length)break LOOP_MERGE;const leftItem=null!=(_a8=diffLeft[leftIdx])?_a8:[0,""],rightItem=null!=(_b5=diffRight[rightIdx])?_b5:[0,""];leftIdx++;rightIdx++;if(leftItem[0]!=import_diff_match_patch4.DIFF_EQUAL||rightItem[0]!=import_diff_match_patch4.DIFF_EQUAL||leftItem[1]!=rightItem[1])if(leftItem[0]!=import_diff_match_patch4.DIFF_DELETE||rightItem[0]!=import_diff_match_patch4.DIFF_DELETE||leftItem[1]!=rightItem[1])if(leftItem[0]!=import_diff_match_patch4.DIFF_INSERT||rightItem[0]!=import_diff_match_patch4.DIFF_INSERT)if(leftItem[0]!=import_diff_match_patch4.DIFF_INSERT){if(rightItem[0]!=import_diff_match_patch4.DIFF_INSERT){if(rightItem[1]!=leftItem[1]){Logger(`MERGING PANIC:${leftItem[0]},${leftItem[1]} == ${rightItem[0]},${rightItem[1]}`,LOG_LEVEL_VERBOSE);autoMerge=!1;break LOOP_MERGE}if(leftItem[0]==import_diff_match_patch4.DIFF_DELETE){if(rightItem[0]==import_diff_match_patch4.DIFF_EQUAL){merged.push(leftItem);continue}autoMerge=!1;break LOOP_MERGE}if(rightItem[0]==import_diff_match_patch4.DIFF_DELETE){if(leftItem[0]==import_diff_match_patch4.DIFF_EQUAL){merged.push(rightItem);continue}autoMerge=!1;break LOOP_MERGE}Logger(`Weird condition:${leftItem[0]},${leftItem[1]} == ${rightItem[0]},${rightItem[1]}`,LOG_LEVEL_VERBOSE);break LOOP_MERGE}leftIdx--;merged.push(rightItem)}else{rightIdx--;merged.push(leftItem)}else{if(leftItem[1]==rightItem[1]){merged.push(leftItem);continue}if(leftLeaf.mtime<=rightLeaf.mtime){merged.push(leftItem);merged.push(rightItem);continue}merged.push(rightItem);merged.push(leftItem)}else{const nextLeftIdx=leftIdx,nextRightIdx=rightIdx,[nextLeftItem,nextRightItem]=[null!=(_c3=diffLeft[nextLeftIdx])?_c3:[0,""],null!=(_d2=diffRight[nextRightIdx])?_d2:[0,""]];if(nextLeftItem[0]==import_diff_match_patch4.DIFF_INSERT&&nextRightItem[0]==import_diff_match_patch4.DIFF_INSERT&&nextLeftItem[1]!=nextRightItem[1]){autoMerge=!1;break}merged.push(leftItem)}else merged.push(leftItem)}while(leftIdx<diffLeft.length||rightIdx<diffRight.length);if(autoMerge){Logger("Sensibly merge available",LOG_LEVEL_VERBOSE);return merged}return!1}async mergeObject(path2,baseRev,currentRev,conflictedRev){try{const baseLeaf=await this.getConflictedDoc(path2,baseRev),leftLeaf=await this.getConflictedDoc(path2,currentRev),rightLeaf=await this.getConflictedDoc(path2,conflictedRev);if(0==baseLeaf||0==leftLeaf||0==rightLeaf){Logger("Could not load leafs for merge",LOG_LEVEL_VERBOSE);Logger(`${baseLeaf?"base":"missing base"}, ${leftLeaf?"left":"missing left"}, ${rightLeaf?"right":"missing right"} }`,LOG_LEVEL_VERBOSE);return!1}if(leftLeaf.deleted&&rightLeaf.deleted){Logger("Both are deleted",LOG_LEVEL_VERBOSE);return!1}const baseObj={data:tryParseJSON(baseLeaf.data,{})},leftObj={data:tryParseJSON(leftLeaf.data,{})},rightObj={data:tryParseJSON(rightLeaf.data,{})},diffLeft=generatePatchObj(baseObj,leftObj),diffRight=generatePatchObj(baseObj,rightObj),diffSetLeft=new Map(flattenObject(diffLeft)),diffSetRight=new Map(flattenObject(diffRight));for(const[key3,value]of diffSetLeft)diffSetRight.has(key3)&&diffSetRight.get(key3)==value&&diffSetRight.delete(key3);for(const[key3,value]of diffSetRight)if(diffSetLeft.has(key3)&&diffSetLeft.get(key3)!=value){Logger(`Conflicted key:${key3}`,LOG_LEVEL_VERBOSE);return!1}const patches=[{mtime:leftLeaf.mtime,patch:diffLeft},{mtime:rightLeaf.mtime,patch:diffRight}].sort(((a2,b3)=>a2.mtime-b3.mtime));let newObj={...baseObj};for(const patch of patches)newObj=applyPatch(newObj,patch.patch);Logger("Object merge is applicable!",LOG_LEVEL_VERBOSE);return JSON.stringify(newObj.data)}catch(ex){Logger("Could not merge object");Logger(ex,LOG_LEVEL_VERBOSE);return!1}}async tryAutoMergeSensibly(path2,test,conflicts){var _a8,_b5,_c3;const conflictedRev=conflicts[0],conflictedRevNo=Number(conflictedRev.split("-")[0]),commonBase=null!=(_c3=null==(_b5=null==(_a8=((await this.database.get(await this.options.entryManager.path2id(path2),{revs_info:!0}))._revs_info||[]).filter((e3=>"available"==e3.status&&Number(e3.rev.split("-")[0])<conflictedRevNo)))?void 0:_a8[0])?void 0:_b5.rev)?_c3:"";let p4;if(commonBase){if(isSensibleMargeApplicable(path2)){const result=await this.mergeSensibly(path2,commonBase,test._rev,conflictedRev);if(result){p4=result.filter((e3=>e3[0]!=import_diff_match_patch4.DIFF_DELETE)).map((e3=>e3[1])).join("");Logger(`Sensible merge:${path2}`,LOG_LEVEL_INFO)}else Logger("Sensible merge is not applicable.",LOG_LEVEL_VERBOSE)}else if(isObjectMargeApplicable(path2)){const result=await this.mergeObject(path2,commonBase,test._rev,conflictedRev);if(result){Logger(`Object merge:${path2}`,LOG_LEVEL_INFO);p4=result}else Logger("Object merge is not applicable..",LOG_LEVEL_VERBOSE)}if(void 0!==p4)return{result:p4,conflictedRev}}return!1}async tryAutoMerge(path2,enableMarkdownAutoMerge){const test=await this.options.entryManager.getDBEntry(path2,{conflicts:!0,revs_info:!0},!1,!1,!0);if(!1===test)return{ok:MISSING_OR_ERROR};if(null==test)return{ok:MISSING_OR_ERROR};if(!test._conflicts)return{ok:NOT_CONFLICTED};if(0==test._conflicts.length)return{ok:NOT_CONFLICTED};const conflicts=test._conflicts.sort(((a2,b3)=>Number(a2.split("-")[0])-Number(b3.split("-")[0])));if((isSensibleMargeApplicable(path2)||isObjectMargeApplicable(path2))&&enableMarkdownAutoMerge){const autoMergeResult=await this.tryAutoMergeSensibly(path2,test,conflicts);if(!1!==autoMergeResult)return autoMergeResult}const leftLeaf=await this.getConflictedDoc(path2,test._rev),rightLeaf=await this.getConflictedDoc(path2,conflicts[0]);return{leftRev:test._rev,rightRev:conflicts[0],leftLeaf,rightLeaf}}};EntryManager=class{constructor(options){this.options=options}get localDatabase(){return this.options.database}get hashManager(){return this.options.hashManager}get chunkManager(){return this.options.chunkManager}get chunkFetcher(){return this.options.chunkFetcher}get splitter(){return this.options.splitter}get settings(){return this.options.settings}id2path(id,entry,stripPrefix2){return this.options.$$id2path(id,entry,stripPrefix2)}async path2id(filename,prefix){return await this.options.$$path2id(filename,prefix)}get isOnDemandChunkEnabled(){return this.settings.remoteType===REMOTE_COUCHDB&&!this.settings.useOnlyLocalChunk}isTargetFile(filenameSrc){const file=filenameSrc.startsWith("i:")?filenameSrc.substring(2):filenameSrc;if(file.startsWith("ix:"))return!0;if(file.startsWith("ps:"))return!0;if(file.includes(":"))return!1;if(this.settings.syncOnlyRegEx){const syncOnly=getFileRegExp(this.settings,"syncOnlyRegEx");if(syncOnly.length>0&&!syncOnly.some((e3=>e3.test(file))))return!1}return!this.settings.syncIgnoreRegEx||!getFileRegExp(this.settings,"syncIgnoreRegEx").some((e3=>e3.test(file)))}async prepareChunk(piece){const cachedChunkId=this.chunkManager.getChunkIDFromCache(piece);return!1!==cachedChunkId?{isNew:!1,id:cachedChunkId,piece}:{isNew:!0,id:`h:${await this.hashManager.computeHash(piece)}`,piece}}async getDBEntryMeta(path2,opt,includeDeleted=!1){var _a8,_b5;if(!this.isTargetFile(path2))return!1;const id=await this.path2id(path2);try{let obj=null;obj=opt?await this.localDatabase.get(id,opt):await this.localDatabase.get(id);const deleted=null!=(_b5=null!=(_a8=null==obj?void 0:obj.deleted)?_a8:obj._deleted)?_b5:void 0;if(!includeDeleted&&deleted)return!1;if(obj.type&&"leaf"==obj.type)return!1;if(!obj.type||obj.type&&"notes"==obj.type||"newnote"==obj.type||"plain"==obj.type){const note=obj;let children=[],type="plain";if("newnote"==obj.type||"plain"==obj.type){children=obj.children;type=obj.type}return{data:"",_id:note._id,path:path2,ctime:note.ctime,mtime:note.mtime,size:note.size,_rev:obj._rev,_conflicts:obj._conflicts,children,datatype:type,deleted,type,eden:"eden"in obj?obj.eden:{}}}}catch(ex){if(isErrorOfMissingDoc(ex))return!1;throw ex}return!1}async getDBEntry(path2,opt,dump=!1,waitForReady=!0,includeDeleted=!1){const meta=await this.getDBEntryMeta(path2,opt,includeDeleted);return!!meta&&await this.getDBEntryFromMeta(meta,dump,waitForReady)}async getDBEntryFromMeta(meta,dump=!1,waitForReady=!0){var _a8,_b5,_c3;const filename=this.id2path(meta._id,meta);if(!this.isTargetFile(filename))return!1;const dispFilename=stripAllPrefixes(filename),deleted=null!=(_b5=null!=(_a8=meta.deleted)?_a8:meta._deleted)?_b5:void 0;if(!meta.type||meta.type&&"notes"==meta.type){const note=meta,doc={data:note.data,path:note.path,_id:note._id,ctime:note.ctime,mtime:note.mtime,size:note.size,_rev:meta._rev,_conflicts:meta._conflicts,children:[],datatype:"newnote",deleted,type:"newnote",eden:"eden"in meta?meta.eden:{}};if(dump){Logger("--Old fashioned document--");Logger(doc)}return doc}if("newnote"==meta.type||"plain"==meta.type){if(dump){const conflicts=await this.localDatabase.get(meta._id,{rev:meta._rev,conflicts:!0,revs_info:!0});Logger("-- Conflicts --");Logger(null!=(_c3=conflicts._conflicts)?_c3:"No conflicts");Logger("-- Revs info -- ");Logger(conflicts._revs_info)}try{if(dump){Logger("--Bare document--");Logger(meta)}let edenChunks={};if(meta.eden&&Object.keys(meta.eden).length>0){const chunks2=Object.entries(meta.eden).map((([id,data])=>({_id:id,data:data.data,type:"leaf"})));edenChunks=Object.fromEntries(chunks2.map((e3=>[e3._id,e3])))}const isChunksCorrectedIncrementally=this.settings.remoteType!==RemoteTypes_REMOTE_MINIO,isNetworkEnabled=this.isOnDemandChunkEnabled&&this.settings.remoteType!==RemoteTypes_REMOTE_MINIO,timeout=waitForReady?isChunksCorrectedIncrementally?3e4:5e3:isNetworkEnabled?5e3:0,childrenKeys=[...meta.children],chunks=await this.chunkManager.read(childrenKeys,{skipCache:!1,timeout,preventRemoteRequest:!isNetworkEnabled},edenChunks);if(chunks.some((e3=>!1===e3)))throw new Error("Load failed");const doc={data:chunks.map((e3=>e3.data)),path:meta.path,_id:meta._id,ctime:meta.ctime,mtime:meta.mtime,size:meta.size,_rev:meta._rev,children:meta.children,datatype:meta.type,_conflicts:meta._conflicts,eden:meta.eden,deleted,type:meta.type};if(dump){Logger("--Loaded Document--");Logger(doc)}return doc}catch(ex){if(isErrorOfMissingDoc(ex)){Logger(`Missing document content!, could not read ${dispFilename}(${meta._id.substring(0,8)}) from database.`,LOG_LEVEL_NOTICE);return!1}Logger(`Something went wrong on reading ${dispFilename}(${meta._id.substring(0,8)}) from database:`,LOG_LEVEL_NOTICE);Logger(ex)}}return!1}async deleteDBEntry(path2,opt){var _a8;if(!this.isTargetFile(path2))return!1;const id=await this.path2id(path2);try{return null!=(_a8=await serialized("file:"+path2,(async()=>{let obj=null;obj=opt?await this.localDatabase.get(id,opt):await this.localDatabase.get(id);const revDeletion=opt&&""!=("rev"in opt?opt.rev:"");if(obj.type&&"leaf"==obj.type)return!1;if(!obj.type||obj.type&&"notes"==obj.type){obj._deleted=!0;const r4=await this.localDatabase.put(obj,{force:!revDeletion});Logger(`Entry removed:${path2} (${obj._id.substring(0,8)}-${r4.rev})`);return!0}if("newnote"==obj.type||"plain"==obj.type){if(revDeletion)obj._deleted=!0;else{obj.deleted=!0;obj.mtime=Date.now();this.settings.deleteMetadataOfDeletedFiles&&(obj._deleted=!0)}const r4=await this.localDatabase.put(obj,{force:!revDeletion});Logger(`Entry removed:${path2} (${obj._id.substring(0,8)}-${r4.rev})`);return!0}return!1})))&&_a8}catch(ex){if(isErrorOfMissingDoc(ex))return!1;throw ex}}async putDBEntry(note,onlyChunks){const filename=this.id2path(note._id,note),dispFilename=stripAllPrefixes(filename);note.eden||(note.eden={});if(!this.isTargetFile(filename)){Logger(`File skipped:${dispFilename}`,LOG_LEVEL_VERBOSE);return!1}const data=note.data instanceof Blob?note.data:createTextBlob(note.data);note.data=data;note.type=isTextBlob(data)?"plain":"newnote";note.datatype=note.type;await this.splitter.initialised;const result=await this.chunkManager.transaction((async()=>{var _a8;let bufferedChunk=[],bufferedSize=0,writeCount=0,newCount=0,cachedCount=0,resultCachedCount=0,duplicatedCount=0,totalWritingCount=0,createChunkCount=0;const chunks=[];let writeChars=0;const flushBufferedChunks=async()=>{if(0===bufferedChunk.length){Logger(`No chunks to flush for ${dispFilename}`,LOG_LEVEL_VERBOSE);return!0}const writeBuf=[...bufferedChunk];bufferedSize=0;bufferedChunk=[];const result2=await this.chunkManager.write(writeBuf,{skipCache:!1,timeout:0},note._id);if(!1===result2.result){Logger(`Failed to write buffered chunks for ${dispFilename}`,LOG_LEVEL_NOTICE);return!1}totalWritingCount++;writeCount+=result2.processed.written;resultCachedCount+=result2.processed.cached;duplicatedCount+=result2.processed.duplicated;writeChars+=writeBuf.map((e3=>e3.data.length)).reduce(((a2,b3)=>a2+b3),0);Logger(`Flushed ${writeBuf.length} (${writeChars}) chunks for ${dispFilename}`,LOG_LEVEL_VERBOSE);return!0},flushIfNeeded=async()=>{if(bufferedSize>2048e3&&!await flushBufferedChunks()){Logger(`Failed to flush buffered chunks for ${dispFilename}`,LOG_LEVEL_NOTICE);return!1}return!0},addBuffer=async(id,data2)=>{const chunk={_id:id,data:data2,type:"leaf"};bufferedChunk.push(chunk);chunks.push(chunk._id);bufferedSize+=chunk.data.length;return await flushIfNeeded()},pieces=await this.splitter.splitContent(note);let totalChunkCount=0;try{for await(const piece of pieces){totalChunkCount++;if(0===piece.length)continue;createChunkCount++;const chunk=await this.prepareChunk(piece);cachedCount+=chunk.isNew?0:1;newCount+=chunk.isNew?1:0;if(!await addBuffer(chunk.id,chunk.piece))return!1}}catch(ex){Logger(`Error processing pieces for ${dispFilename}`);Logger(ex,LOG_LEVEL_VERBOSE);return!1}if(!await flushBufferedChunks())return!1;const dataSize=note.data.size;Logger(`Chunks processed for ${dispFilename} (${dataSize}): 📚:${totalChunkCount} (${createChunkCount}) , 📥:${totalWritingCount} (✨: ${newCount}, 🗃️: ${cachedCount} (${resultCachedCount}) / 🗄️: ${writeCount}, ♻:${duplicatedCount})`,LOG_LEVEL_VERBOSE);dataSize>0&&0===totalWritingCount&&Logger(`No data to save in ${dispFilename}!! This document may be corrupted in the local database! Please back it up immediately, and report an issue!`,LOG_LEVEL_NOTICE);if(onlyChunks)return{id:note._id,ok:!0,rev:"dummy"};const newDoc={children:chunks,_id:note._id,path:note.path,ctime:note.ctime,mtime:note.mtime,size:note.size,type:note.datatype,eden:{}};return null!=(_a8=await serialized("file:"+filename,(async()=>{try{const old=await this.localDatabase.get(newDoc._id);newDoc._rev=old._rev}catch(ex){if(!isErrorOfMissingDoc(ex))throw ex}const r4=await this.localDatabase.put(newDoc,{force:!0});return!!r4.ok&&r4})))&&_a8}));if(!1===result){Logger(`Failed to write document ${dispFilename}`,LOG_LEVEL_NOTICE);return!1}Logger(`Document saved: ${dispFilename} (${result.id.substring(0,8)}-${result.rev})`,LOG_LEVEL_VERBOSE);return result}};HashManagerCore=class{constructor(options){this.useEncryption=!1;this.hashedPassphrase="";this.hashedPassphrase32=0;this.options=options;this.settings=options.settings;this.applyOptions(options)}applyOptions(options){var _a8;options&&(this.options=options);this.settings=this.options.settings;this.useEncryption=null!=(_a8=this.settings.encrypt)&&_a8;const passphrase=this.settings.passphrase||"",usingLetters=~~(passphrase.length/4*3),passphraseForHash="a83hrf7fy7sa8g31"+passphrase.substring(0,usingLetters);this.hashedPassphrase=fallbackMixedHashEach(passphraseForHash);this.hashedPassphrase32=mixedHash(passphraseForHash,305419896)[0]}initialise(){if(this.initialiseTask)return this.initialiseTask;this.initialiseTask=this.processInitialise();return this.initialiseTask}async computeHash(piece){await this.initialiseTask;return this.useEncryption?"+"+await this.computeHashWithEncryption(piece):await this.computeHashWithoutEncryption(piece)}static isAvailableFor(hashAlg){return!1}};XXHashHashManager=class extends HashManagerCore{constructor(options){super(options)}async processInitialise(){this.xxhash=await e();return!0}};XXHash32RawHashManager=class extends XXHashHashManager{static isAvailableFor(hashAlg){return""===hashAlg}computeHashWithEncryption(piece){return Promise.resolve((this.xxhash.h32Raw((new TextEncoder).encode(piece))^this.hashedPassphrase32^piece.length).toString(36))}computeHashWithoutEncryption(piece){return Promise.resolve((this.xxhash.h32Raw((new TextEncoder).encode(piece))^piece.length).toString(36))}};XXHash64HashManager=class extends XXHashHashManager{static isAvailableFor(hashAlg){return"xxhash64"===hashAlg}computeHashWithEncryption(piece){return Promise.resolve(this.xxhash.h64(`${piece}-${this.hashedPassphrase}-${piece.length}`).toString(36))}computeHashWithoutEncryption(piece){return Promise.resolve(this.xxhash.h64(`${piece}-${piece.length}`).toString(36))}};FallbackWasmHashManager=class extends XXHashHashManager{static isAvailableFor(hashAlg){return!0}computeHashWithEncryption(piece){return Promise.resolve(this.xxhash.h32(`${piece}-${this.hashedPassphrase}-${piece.length}`).toString(36))}computeHashWithoutEncryption(piece){return Promise.resolve(this.xxhash.h32(`${piece}-${piece.length}`).toString(36))}};PureJSHashManager=class extends HashManagerCore{static isAvailableFor(hashAlg){return"mixed-purejs"===hashAlg}processInitialise(){return Promise.resolve(!0)}computeHashWithEncryption(input){return Promise.resolve(fallbackMixedHashEach(`${input}${this.hashedPassphrase}${input.length}`))}computeHashWithoutEncryption(input){return Promise.resolve(fallbackMixedHashEach(`${input}-${input.length}`))}};HashManagers=[XXHash64HashManager,XXHash32RawHashManager,class extends HashManagerCore{static isAvailableFor(hashAlg){return"sha1"===hashAlg}processInitialise(){return Promise.resolve(!0)}computeHashWithEncryption(input){return sha12(`${input}-${this.hashedPassphrase}-${input.length}`)}computeHashWithoutEncryption(input){return sha12(`${input}-${input.length}`)}},PureJSHashManager,FallbackWasmHashManager,class extends PureJSHashManager{static isAvailableFor(_hashAlg){return!0}}];HashManager=class extends HashManagerCore{constructor(options){super(options);this.manager=void 0}static isAvailableFor(hashAlg){return HashManagers.some((manager=>manager.isAvailableFor(hashAlg)))}async setManager(){for(const Manager of HashManagers)if(Manager.isAvailableFor(this.settings.hashAlg)){this.manager=new Manager(this.options);return await this.manager.initialise()}throw new Error(`HashManager for ${this.settings.hashAlg} is not available`)}async processInitialise(){if(await this.setManager()){Logger(`HashManager for ${this.settings.hashAlg} has been initialised`,LOG_LEVEL_VERBOSE);return!0}Logger(`HashManager for ${this.settings.hashAlg} failed to initialise`);throw new Error(`HashManager for ${this.settings.hashAlg} failed to initialise`)}computeHash(piece){return this.manager.computeHash(piece)}computeHashWithoutEncryption(piece){return this.manager.computeHashWithoutEncryption(piece)}computeHashWithEncryption(piece){return this.manager.computeHashWithEncryption(piece)}};NetworkManager=class{};NetworkManagerBrowser=class extends NetworkManager{get isOnline(){return navigator.onLine}};LiveSyncManagers=class{constructor(options){this.options=options;if(options.networkManager)this.networkManager=options.networkManager;else{if(!("navigator"in globalThis))throw new LiveSyncError("No NetworkManager available");this.networkManager=new NetworkManagerBrowser}}get settings(){return this.options.settings}async teardownManagers(){if(this.changeManager){this.changeManager.teardown();this.changeManager=void 0}if(this.chunkFetcher){this.chunkFetcher.destroy();this.chunkFetcher=void 0}if(this.chunkManager){this.chunkManager.destroy();this.chunkManager=void 0}return await Promise.resolve()}getProxy(){const getDB=()=>this.options.database,getChangeManager=()=>this.changeManager,getChunkManager=()=>this.chunkManager,getReplicator=()=>this.options.getActiveReplicator(),getSettings=()=>this.options.settings,getEntryManager=()=>this.entryManager,getHashManager=()=>this.hashManager,getChunkFetcher=()=>this.chunkFetcher,getSplitter=()=>this.splitter;return{get database(){return getDB()},get changeManager(){return getChangeManager()},get chunkManager(){return getChunkManager()},getActiveReplicator:()=>getReplicator(),get settings(){return getSettings()},get entryManager(){return getEntryManager()},get hashManager(){return getHashManager()},$$path2id:(filename,prefix)=>this.options.path2id(filename,prefix),$$id2path:(id,entry,stripPrefix2)=>this.options.id2path(id,entry,stripPrefix2),get chunkFetcher(){return getChunkFetcher()},get splitter(){return getSplitter()}}}async initManagers(){await this.teardownManagers();const proxy2=this.getProxy();this.hashManager=new HashManager({...proxy2});this.splitter=new ContentSplitter({...proxy2});await this.splitter.initialise(proxy2);await this.hashManager.initialise();this.changeManager=new ChangeManager(proxy2);this.chunkManager=new ChunkManager({...proxy2,maxCacheSize:10*this.settings.hashCacheMaxCount});this.chunkFetcher=new ChunkFetcher(proxy2);this.entryManager=new EntryManager({...proxy2});this.conflictManager=new ConflictManager({...proxy2})}clearCaches(){var _a8;null==(_a8=this.chunkManager)||_a8.clearCaches()}async prepareHashFunction(){const proxy2=this.getProxy();this.hashManager=new HashManager(proxy2);await this.hashManager.initialise()}};ModuleLocalDatabaseObsidian=class extends AbstractModule{_everyOnloadStart(){return Promise.resolve(!0)}async _openDatabase(){null!=this.localDatabase&&await this.localDatabase.close();const vaultName=this.services.vault.getVaultName();this._log($msg("moduleLocalDatabase.logWaitingForReady"));const getDB=()=>this.core.localDatabase.localDatabase,getSettings=()=>this.core.settings;this.core.managers=new LiveSyncManagers({get database(){return getDB()},getActiveReplicator:()=>this.core.replicator,id2path:this.services.path.id2path,path2id:this.services.path.path2id,get settings(){return getSettings()}});this.core.localDatabase=new LiveSyncLocalDB(vaultName,this.core);initializeStores(vaultName);return await this.localDatabase.initializeDatabase()}_isDatabaseReady(){return null!=this.localDatabase&&this.localDatabase.isReady}onBindFunction(core,services){services.database.handleIsDatabaseReady(this._isDatabaseReady.bind(this));services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this));services.database.handleOpenDatabase(this._openDatabase.bind(this))}};ModuleConflictChecker=class extends AbstractModule{constructor(){super(...arguments);this.conflictResolveQueue=new QueueProcessor((async filenames=>{const filename=filenames[0];return await this.services.conflict.resolve(filename)}),{suspended:!1,batchSize:1,concurrentLimit:10,delay:0,keepResultUntilDownstreamConnected:!1}).replaceEnqueueProcessor(((queue2,newEntity)=>{sendValue("cancel-resolve-conflict:"+newEntity,!0);return[...[...queue2].filter((e3=>e3!=newEntity)),newEntity]}));this.conflictCheckQueue=new QueueProcessor((files=>{const filename=files[0];return Promise.resolve([filename])}),{suspended:!1,batchSize:1,concurrentLimit:10,delay:0,keepResultUntilDownstreamConnected:!0,pipeTo:this.conflictResolveQueue,totalRemainingReactiveSource:this.core.conflictProcessQueueCount})}async _queueConflictCheckIfOpen(file){const path2=file;if(this.settings.checkConflictOnlyOnOpen){const af2=this.services.vault.getActiveFilePath();if(af2&&af2!=path2){this._log(`${file} is conflicted, merging process has been postponed.`,LOG_LEVEL_NOTICE);return}}await this.services.conflict.queueCheckFor(path2)}async _queueConflictCheck(file){const optionalConflictResult=await this.services.conflict.getOptionalConflictCheckMethod(file);1!=optionalConflictResult&&("newer"===optionalConflictResult?await this.services.conflict.resolveByNewest(file):this.conflictCheckQueue.enqueue(file))}_waitForAllConflictProcessed(){return this.conflictResolveQueue.waitForAllProcessed()}onBindFunction(core,services){services.conflict.handleQueueCheckForIfOpen(this._queueConflictCheckIfOpen.bind(this));services.conflict.handleQueueCheckFor(this._queueConflictCheck.bind(this));services.conflict.handleEnsureAllProcessed(this._waitForAllConflictProcessed.bind(this))}};ModuleResolvingMismatchedTweaks=class extends AbstractModule{async _anyAfterConnectCheckFailed(){if(!this.core.replicator.tweakSettingsMismatched&&!this.core.replicator.preferredTweakValue)return!1;const preferred=this.core.replicator.preferredTweakValue;if(!preferred)return!1;const ret=await this.services.tweakValue.askResolvingMismatched(preferred);return"OK"!=ret&&("CHECKAGAIN"==ret?"CHECKAGAIN":"IGNORE"==ret||void 0)}async _checkAndAskResolvingMismatchedTweaks(preferred){const mine=extractObject(TweakValuesShouldMatchedTemplate,this.settings),items=Object.entries(TweakValuesShouldMatchedTemplate);let rebuildRequired=!1,rebuildRecommended=!1;const tableRows=[];for(const v2 of items){const key3=v2[0],valueMine=escapeMarkdownValue(mine[key3]),valuePreferred=escapeMarkdownValue(preferred[key3]);if(valueMine!=valuePreferred){-1!==IncompatibleChanges.indexOf(key3)&&(rebuildRequired=!0);for(const pattern of IncompatibleChangesInSpecificPattern){if(pattern.key!==key3)continue;const isFromConditionMet="from"in pattern&&pattern.from===mine[key3],isToConditionMet="to"in pattern&&pattern.to===preferred[key3];(isFromConditionMet||isToConditionMet)&&(pattern.isRecommendation?rebuildRecommended=!0:rebuildRequired=!0)}-1!==CompatibleButLossyChanges.indexOf(key3)&&(rebuildRecommended=!0);tableRows.push($msg("TweakMismatchResolve.Table.Row",{name:confName(key3),self:valueMine,remote:valuePreferred}))}}const additionalMessage=rebuildRequired&&this.core.settings.isConfigured?$msg("TweakMismatchResolve.Message.WarningIncompatibleRebuildRequired"):"",additionalMessage2=rebuildRecommended&&this.core.settings.isConfigured?$msg("TweakMismatchResolve.Message.WarningIncompatibleRebuildRecommended"):"",table2=$msg("TweakMismatchResolve.Table",{rows:tableRows.join("\n")}),message=$msg("TweakMismatchResolve.Message.MainTweakResolving",{table:table2,additionalMessage:[additionalMessage,additionalMessage2].filter((v2=>v2)).join("\n")}),CHOICE_USE_REMOTE=$msg("TweakMismatchResolve.Action.UseRemote"),CHOICE_USE_REMOTE_WITH_REBUILD=$msg("TweakMismatchResolve.Action.UseRemoteWithRebuild"),CHOICE_USE_REMOTE_PREVENT_REBUILD=$msg("TweakMismatchResolve.Action.UseRemoteAcceptIncompatible"),CHOICE_USE_MINE=$msg("TweakMismatchResolve.Action.UseMine"),CHOICE_USE_MINE_WITH_REBUILD=$msg("TweakMismatchResolve.Action.UseMineWithRebuild"),CHOICE_USE_MINE_PREVENT_REBUILD=$msg("TweakMismatchResolve.Action.UseMineAcceptIncompatible"),CHOICE_DISMISS=$msg("TweakMismatchResolve.Action.Dismiss"),CHOICE_AND_VALUES=[];if(rebuildRequired){CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE_WITH_REBUILD,[preferred,!0]]);CHOICE_AND_VALUES.push([CHOICE_USE_MINE_WITH_REBUILD,[!0,!0]]);CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE_PREVENT_REBUILD,[preferred,!1]]);CHOICE_AND_VALUES.push([CHOICE_USE_MINE_PREVENT_REBUILD,[!0,!1]])}else if(rebuildRecommended){CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE,[preferred,!1]]);CHOICE_AND_VALUES.push([CHOICE_USE_MINE,[!0,!1]]);CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE_WITH_REBUILD,[!0,!0]]);CHOICE_AND_VALUES.push([CHOICE_USE_MINE_WITH_REBUILD,[!0,!0]])}else{CHOICE_AND_VALUES.push([CHOICE_USE_REMOTE,[preferred,!1]]);CHOICE_AND_VALUES.push([CHOICE_USE_MINE,[!0,!1]])}CHOICE_AND_VALUES.push([CHOICE_DISMISS,[!1,!1]]);const CHOICES=Object.fromEntries(CHOICE_AND_VALUES),retKey=await this.core.confirm.askSelectStringDialogue(message,Object.keys(CHOICES),{title:$msg("TweakMismatchResolve.Title.TweakResolving"),timeout:60,defaultAction:CHOICE_DISMISS});return retKey?CHOICES[retKey]:[!1,!1]}async _askResolvingMismatchedTweaks(){if(!this.core.replicator.tweakSettingsMismatched)return"OK";const tweaks=this.core.replicator.preferredTweakValue;if(!tweaks)return"IGNORE";const preferred=extractObject(TweakValuesShouldMatchedTemplate,tweaks),[conf,rebuildRequired]=await this.services.tweakValue.checkAndAskResolvingMismatched(preferred);if(!conf)return"IGNORE";if(!0===conf){await this.core.replicator.setPreferredRemoteTweakSettings(this.settings);rebuildRequired&&await this.core.rebuilder.$rebuildRemote();Logger("Tweak values on the remote server have been updated. Your other device will see this message.",LOG_LEVEL_NOTICE);return"CHECKAGAIN"}if(conf){this.settings={...this.settings,...conf};await this.core.replicator.setPreferredRemoteTweakSettings(this.settings);await this.services.setting.saveSettingData();rebuildRequired&&await this.core.rebuilder.$fetchLocal();Logger("Configuration has been updated as configured by the other device.",LOG_LEVEL_NOTICE);return"CHECKAGAIN"}return"IGNORE"}async _fetchRemotePreferredTweakValues(trialSetting){const replicator=await this.services.replicator.getNewReplicator(trialSetting);if(!replicator){this._log("The remote type is not supported for fetching preferred tweak values.",LOG_LEVEL_NOTICE);return!1}if(await replicator.tryConnectRemote(trialSetting)){const preferred=await replicator.getRemotePreferredTweakValues(trialSetting);if(preferred)return preferred;this._log("Failed to get the preferred tweak values from the remote server.",LOG_LEVEL_NOTICE);return!1}this._log("Failed to connect to the remote server.",LOG_LEVEL_NOTICE);return!1}async _checkAndAskUseRemoteConfiguration(trialSetting){const preferred=await this.services.tweakValue.fetchRemotePreferred(trialSetting);return preferred?await this.services.tweakValue.askUseRemoteConfiguration(trialSetting,preferred):{result:!1,requireFetch:!1}}async _askUseRemoteConfiguration(trialSetting,preferred){const items=Object.entries(TweakValuesShouldMatchedTemplate);let rebuildRequired=!1,rebuildRecommended=!1,differenceCount=0;const tableRows=[];for(const v2 of items){const key3=v2[0],remoteValueForDisplay=escapeMarkdownValue(preferred[key3]),currentValueForDisplay=`${escapeMarkdownValue(null==trialSetting?void 0:trialSetting[key3])}`;if((null==trialSetting?void 0:trialSetting[key3])!==preferred[key3]){-1!==IncompatibleChanges.indexOf(key3)&&(rebuildRequired=!0);for(const pattern of IncompatibleChangesInSpecificPattern){if(pattern.key!==key3)continue;const isFromConditionMet="from"in pattern&&pattern.from===(null==trialSetting?void 0:trialSetting[key3]),isToConditionMet="to"in pattern&&pattern.to===preferred[key3];(isFromConditionMet||isToConditionMet)&&(pattern.isRecommendation?rebuildRecommended=!0:rebuildRequired=!0)}-1!==CompatibleButLossyChanges.indexOf(key3)&&(rebuildRecommended=!0);tableRows.push($msg("TweakMismatchResolve.Table.Row",{name:confName(key3),self:currentValueForDisplay,remote:remoteValueForDisplay}));differenceCount++}}if(0===differenceCount){this._log("The settings in the remote database are the same as the local database.",LOG_LEVEL_NOTICE);return{result:!1,requireFetch:!1}}const additionalMessage=rebuildRequired&&this.core.settings.isConfigured?$msg("TweakMismatchResolve.Message.UseRemote.WarningRebuildRequired"):"",additionalMessage2=rebuildRecommended&&this.core.settings.isConfigured?$msg("TweakMismatchResolve.Message.UseRemote.WarningRebuildRecommended"):"",table2=$msg("TweakMismatchResolve.Table",{rows:tableRows.join("\n")}),message=$msg("TweakMismatchResolve.Message.Main",{table:table2,additionalMessage:[additionalMessage,additionalMessage2].filter((v2=>v2)).join("\n")}),CHOICE_USE_REMOTE=$msg("TweakMismatchResolve.Action.UseConfigured"),CHOICE_DISMISS=$msg("TweakMismatchResolve.Action.Dismiss"),CHOICES=[CHOICE_USE_REMOTE,CHOICE_DISMISS],retKey=await this.core.confirm.askSelectStringDialogue(message,CHOICES,{title:$msg("TweakMismatchResolve.Title.UseRemoteConfig"),timeout:0,defaultAction:CHOICE_DISMISS});return retKey?retKey===CHOICE_DISMISS?{result:!1,requireFetch:!1}:retKey===CHOICE_USE_REMOTE?{result:{...trialSetting,...preferred},requireFetch:rebuildRequired}:{result:!1,requireFetch:!1}:{result:!1,requireFetch:!1}}onBindFunction(core,services){services.tweakValue.handleFetchRemotePreferred(this._fetchRemotePreferredTweakValues.bind(this));services.tweakValue.handleCheckAndAskResolvingMismatched(this._checkAndAskResolvingMismatchedTweaks.bind(this));services.tweakValue.handleAskResolvingMismatched(this._askResolvingMismatchedTweaks.bind(this));services.tweakValue.handleCheckAndAskUseRemoteConfiguration(this._checkAndAskUseRemoteConfiguration.bind(this));services.tweakValue.handleAskUseRemoteConfiguration(this._askUseRemoteConfiguration.bind(this));services.replication.handleCheckConnectionFailure(this._anyAfterConnectCheckFailed.bind(this))}};ModuleIntegratedTest=class extends AbstractObsidianModule{async waitFor(proc,timeout=1e4){await delay(100);const start=Date.now();for(;!await proc();){if(timeout>0&&Date.now()-start>timeout){this._log("Timeout");return!1}await delay(500)}return!0}waitWithReplicating(proc,timeout=1e4){return this.waitFor((async()=>{await this.tryReplicate();return await proc()}),timeout)}async storageContentIsEqual(file,content){try{return await this.readStorageContent(file)===content}catch(e3){this._log(`Error: ${e3}`);return!1}}async assert(proc){if(!await proc()){this._log("Assertion failed");return!1}return!0}async __orDie(key3,proc){if(!await this._test(key3,proc))throw new Error(`${key3}`);return!0}tryReplicate(){if(!this.settings.liveSync)return shareRunningResult("replicate-test",(async()=>{await this.services.replication.replicate()}))}async readStorageContent(file){if(await this.core.storageAccess.isExistsIncludeHidden(file))return await this.core.storageAccess.readHiddenFileText(file)}async __proceed(no,title){const stepContent=`Step ${no}`;await this.services.conflict.resolveByNewest("_STEP.md");await this.core.storageAccess.writeFileAuto("_STEP.md",stepContent);await this.__orDie(`Wait for acknowledge ${no}`,(async()=>!!await this.waitWithReplicating((async()=>await this.storageContentIsEqual("_STEP_ACK.md",stepContent)),2e4)));return!0}async __join(no,title){const stepContent=`Step ${no}`;await this.__orDie(`Wait for step ${no} (${title})`,(async()=>!!await this.waitWithReplicating((async()=>await this.storageContentIsEqual("_STEP.md",stepContent)),2e4)));await this.services.conflict.resolveByNewest("_STEP_ACK.md");await this.core.storageAccess.writeFileAuto("_STEP_ACK.md",stepContent);await this.tryReplicate();return!0}async performStep({step,title,isGameChanger,proc,check}){if(isGameChanger){await this.__proceed(step,title);try{await proc()}catch(e3){this._log(`Error: ${e3}`);return!1}return await this.__orDie(`Step ${step} - ${title}`,(async()=>await this.waitWithReplicating(check)))}return await this.__join(step,title)}async nonLiveTestRunner(isLeader,testMain){const storage=this.core.storageAccess;let testFileName;this.addTestResult("-------Starting ... ",!0,`Test as ${isLeader?"Leader":"Receiver"} command file IT.md`);isLeader&&await this.__proceed(0,"start");await this.tryReplicate();await this.performStep({step:0,title:"Make sure that command File Not Exists",isGameChanger:isLeader,proc:async()=>await storage.removeHidden("IT.md"),check:async()=>!await storage.isExistsIncludeHidden("IT.md")});await this.performStep({step:1,title:"Make sure that command File Not Exists On Receiver",isGameChanger:!isLeader,proc:async()=>await storage.removeHidden("ITx.md"),check:async()=>!await storage.isExistsIncludeHidden("ITx.md")});await this.performStep({step:2,title:"Decide the test file name",isGameChanger:isLeader,proc:async()=>{testFileName=Date.now()+"-"+Math.ceil(1e3*Math.random())+".md";await storage.writeFileAuto("IT.md",testFileName)},check:()=>Promise.resolve(!0)});await this.performStep({step:3,title:"Wait for the command file to be arrived",isGameChanger:!isLeader,proc:async()=>{},check:async()=>await storage.isExistsIncludeHidden("IT.md")});await this.performStep({step:4,title:"Send the response file",isGameChanger:!isLeader,proc:async()=>{await storage.writeHiddenFileAuto("ITx.md","!")},check:()=>Promise.resolve(!0)});await this.performStep({step:5,title:"Wait for the response file to be arrived",isGameChanger:isLeader,proc:async()=>{},check:async()=>await storage.isExistsIncludeHidden("ITx.md")});await this.performStep({step:6,title:"Proceed to begin the test",isGameChanger:isLeader,proc:async()=>{},check:()=>Promise.resolve(!0)});await this.performStep({step:6,title:"Begin the test",isGameChanger:!0,proc:async()=>{},check:()=>Promise.resolve(!0)});try{this.addTestResult("** Main------",!0,"");if(isLeader)return await testMain(testFileName,!0);{const testFileName2=await this.readStorageContent("IT.md");this.addTestResult("testFileName",!0,`Request client to use :${testFileName2}`);return await testMain(testFileName2,!1)}}finally{this.addTestResult("Teardown",!0,`Deleting ${testFileName}`);await storage.removeHidden(testFileName)}return!0}async testBasic(filename,isLeader){const storage=this.core.storageAccess,database=this.core.databaseFileAccess;await this.addTestResult("---**Starting Basic Test**---",!0,`Test as ${isLeader?"Leader":"Receiver"} command file ${filename}`);await this.performStep({step:0,title:"Make sure that file is not exist",isGameChanger:!isLeader,proc:async()=>{},check:async()=>!await storage.isExists(filename)});await this.performStep({step:1,title:"Write a file",isGameChanger:isLeader,proc:async()=>await storage.writeFileAuto(filename,"Hello World"),check:async()=>await storage.isExists(filename)});await this.performStep({step:2,title:"Make sure the file is arrived",isGameChanger:!isLeader,proc:async()=>{},check:async()=>await storage.isExists(filename)});await this.performStep({step:3,title:"Update to Hello World 2",isGameChanger:isLeader,proc:async()=>await storage.writeFileAuto(filename,"Hello World 2"),check:async()=>await this.storageContentIsEqual(filename,"Hello World 2")});await this.performStep({step:4,title:"Make sure the modified file is arrived",isGameChanger:!isLeader,proc:async()=>{},check:async()=>await this.storageContentIsEqual(filename,"Hello World 2")});await this.performStep({step:5,title:"Update to Hello World 3",isGameChanger:!isLeader,proc:async()=>await storage.writeFileAuto(filename,"Hello World 3"),check:async()=>await this.storageContentIsEqual(filename,"Hello World 3")});await this.performStep({step:6,title:"Make sure the modified file is arrived",isGameChanger:isLeader,proc:async()=>{},check:async()=>await this.storageContentIsEqual(filename,"Hello World 3")});await this.performStep({step:7,title:"Update to Multiline",isGameChanger:isLeader,proc:async()=>await storage.writeFileAuto(filename,"Line1:A\nLine2:B\nLine3:C\nLine4:D"),check:async()=>await this.storageContentIsEqual(filename,"Line1:A\nLine2:B\nLine3:C\nLine4:D")});await this.performStep({step:8,title:"Make sure the modified file is arrived",isGameChanger:!isLeader,proc:async()=>{},check:async()=>await this.storageContentIsEqual(filename,"Line1:A\nLine2:B\nLine3:C\nLine4:D")});if(!this.settings.liveSync){const multiLineContentL="Line1:A\nLine2:B\nLine3:C!\nLine4:D",multiLineContentC="Line1:A\nLine2:bbbbb\nLine3:C\nLine4:D";await this.performStep({step:9,title:"Progress to be conflicted",isGameChanger:isLeader,proc:async()=>{},check:()=>Promise.resolve(!0)});await storage.writeFileAuto(filename,isLeader?multiLineContentL:multiLineContentC);await this.performStep({step:10,title:"Update As Conflicted",isGameChanger:!isLeader,proc:async()=>{},check:()=>Promise.resolve(!0)});await this.performStep({step:10,title:"Make sure Automatically resolved",isGameChanger:isLeader,proc:async()=>{},check:async()=>0===(await database.getConflictedRevs(filename)).length});await this.performStep({step:11,title:"Make sure Automatically resolved",isGameChanger:!isLeader,proc:async()=>{},check:async()=>0===(await database.getConflictedRevs(filename)).length});const sensiblyMergedContent="Line1:A\nLine2:bbbbb\nLine3:C!\nLine4:D";await this.performStep({step:12,title:"Make sure Sensibly Merged on Leader",isGameChanger:isLeader,proc:async()=>{},check:async()=>await this.storageContentIsEqual(filename,sensiblyMergedContent)});await this.performStep({step:13,title:"Make sure Sensibly Merged on Receiver",isGameChanger:!isLeader,proc:async()=>{},check:async()=>await this.storageContentIsEqual(filename,sensiblyMergedContent)})}await this.performStep({step:14,title:"Delete File",isGameChanger:isLeader,proc:async()=>{await storage.removeHidden(filename)},check:async()=>!await storage.isExists(filename)});await this.performStep({step:15,title:"Make sure File is deleted",isGameChanger:!isLeader,proc:async()=>{},check:async()=>!await storage.isExists(filename)});this._log("The Basic Test has been completed",LOG_LEVEL_NOTICE);return!0}async testBasicEvent(isLeader){this.settings.liveSync=!1;await this.saveSettings();await this._test("basic",(async()=>await this.nonLiveTestRunner(isLeader,((t3,l2)=>this.testBasic(t3,l2)))))}async testBasicLive(isLeader){this.settings.liveSync=!0;await this.saveSettings();await this._test("basic",(async()=>await this.nonLiveTestRunner(isLeader,((t3,l2)=>this.testBasic(t3,l2)))))}async _everyModuleTestMultiDevice(){if(!this.settings.enableDebugTools)return Promise.resolve(!0);const isLeader=-1===this.core.services.vault.vaultName().indexOf("recv");this.addTestResult("-------",!0,"Test as "+(isLeader?"Leader":"Receiver"));try{this._log("Starting Test");await this.testBasicEvent(isLeader);this.settings.remoteType==REMOTE_MINIO&&await this.testBasicLive(isLeader)}catch(e3){this._log(e3);this._log(`Error: ${e3}`);return Promise.resolve(!1)}return Promise.resolve(!0)}onBindFunction(core,services){services.test.handleTestMultiDevice(this._everyModuleTestMultiDevice.bind(this))}};ModuleRebuilder=class extends AbstractModule{_everyOnload(){this.core.rebuilder=this;return Promise.resolve(!0)}async $performRebuildDB(method){"localOnly"==method&&await this.$fetchLocal();"localOnlyWithChunks"==method&&await this.$fetchLocal(!0);"remoteOnly"==method&&await this.$rebuildRemote();"rebuildBothByThisDevice"==method&&await this.$rebuildEverything()}async informOptionalFeatures(){await this.core.services.UI.showMarkdownDialog("All optional features are disabled","Customisation Sync and Hidden File Sync will all be disabled.\nPlease enable them from the settings screen after setup is complete.",["OK"])}async askUsingOptionalFeature(opt){"yes"==await this.core.confirm.askYesNoDialog("Do you want to enable extra features? If you are new to Self-hosted LiveSync, try the core feature first!",{title:"Enable extra features",defaultOption:"No",timeout:15})&&await this.services.setting.suggestOptionalFeatures(opt)}async rebuildRemote(){await this.services.setting.suspendExtraSync();this.core.settings.isConfigured=!0;this.core.settings.notifyThresholdOfRemoteStorageSize=DEFAULT_SETTINGS.notifyThresholdOfRemoteStorageSize;await this.services.setting.realiseSetting();await this.services.remote.markLocked();await this.services.remote.tryResetDatabase();await this.services.remote.markLocked();await delay(500);await delay(1e3);await this.services.remote.replicateAllToRemote(!0);await delay(1e3);await this.services.remote.replicateAllToRemote(!0,!0);await this.informOptionalFeatures()}$rebuildRemote(){return this.rebuildRemote()}async rebuildEverything(){await this.services.setting.suspendExtraSync();this.core.settings.isConfigured=!0;this.core.settings.notifyThresholdOfRemoteStorageSize=DEFAULT_SETTINGS.notifyThresholdOfRemoteStorageSize;await this.services.setting.realiseSetting();await this.resetLocalDatabase();await delay(1e3);await this.services.databaseEvents.initialiseDatabase(!0,!0,!0);await this.services.remote.markLocked();await this.services.remote.tryResetDatabase();await this.services.remote.markLocked();await delay(500);await delay(1e3);await this.services.remote.replicateAllToRemote(!0);await delay(1e3);await this.services.remote.replicateAllToRemote(!0,!0);await this.informOptionalFeatures()}$rebuildEverything(){return this.rebuildEverything()}$fetchLocal(makeLocalChunkBeforeSync,preventMakeLocalFilesBeforeSync){return this.fetchLocal(makeLocalChunkBeforeSync,preventMakeLocalFilesBeforeSync)}async scheduleRebuild(){try{await this.core.storageAccess.writeFileAuto(FLAGMD_REDFLAG2_HR,"")}catch(ex){this._log("Could not create red_flag_rebuild.md",LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}this.services.appLifecycle.performRestart()}async scheduleFetch(){try{await this.core.storageAccess.writeFileAuto(FLAGMD_REDFLAG3_HR,"")}catch(ex){this._log("Could not create red_flag_fetch.md",LOG_LEVEL_NOTICE);this._log(ex,LOG_LEVEL_VERBOSE)}this.services.appLifecycle.performRestart()}async _tryResetRemoteDatabase(){await this.core.replicator.tryResetRemoteDatabase(this.settings)}async _tryCreateRemoteDatabase(){await this.core.replicator.tryCreateRemoteDatabase(this.settings)}async _resetLocalDatabase(){this.core.storageAccess.clearTouched();return await this.localDatabase.resetDatabase()}async suspendAllSync(){this.core.settings.liveSync=!1;this.core.settings.periodicReplication=!1;this.core.settings.syncOnSave=!1;this.core.settings.syncOnEditorSave=!1;this.core.settings.syncOnStart=!1;this.core.settings.syncOnFileOpen=!1;this.core.settings.syncAfterMerge=!1;await this.services.setting.suspendExtraSync()}async suspendReflectingDatabase(){if(!this.core.settings.doNotSuspendOnFetching&&this.core.settings.remoteType!=REMOTE_MINIO){this._log("Suspending reflection: Database and storage changes will not be reflected in each other until completely finished the fetching.",LOG_LEVEL_NOTICE);this.core.settings.suspendParseReplicationResult=!0;this.core.settings.suspendFileWatching=!0;await this.core.saveSettings()}}async resumeReflectingDatabase(){if(!this.core.settings.doNotSuspendOnFetching&&this.core.settings.remoteType!=REMOTE_MINIO){this._log("Database and storage reflection has been resumed!",LOG_LEVEL_NOTICE);this.core.settings.suspendParseReplicationResult=!1;this.core.settings.suspendFileWatching=!1;await this.services.vault.scanVault(!0);await this.services.replication.onBeforeReplicate(!1);await this.core.saveSettings()}}async fetchLocal(makeLocalChunkBeforeSync,preventMakeLocalFilesBeforeSync){await this.services.setting.suspendExtraSync();this.core.settings.isConfigured=!0;this.core.settings.notifyThresholdOfRemoteStorageSize=DEFAULT_SETTINGS.notifyThresholdOfRemoteStorageSize;await this.suspendReflectingDatabase();await this.services.setting.realiseSetting();await this.resetLocalDatabase();await delay(1e3);await this.services.database.openDatabase();this.services.appLifecycle.markIsReady();makeLocalChunkBeforeSync?await this.core.fileHandler.createAllChunks(!0):preventMakeLocalFilesBeforeSync||await this.services.databaseEvents.initialiseDatabase(!0,!0,!0);await this.services.remote.markResolved();await delay(500);await this.services.remote.replicateAllFromRemote(!0);await delay(1e3);await this.services.remote.replicateAllFromRemote(!0);await this.resumeReflectingDatabase();await this.informOptionalFeatures()}async fetchLocalWithRebuild(){return await this.fetchLocal(!0)}async _allSuspendAllSync(){await this.suspendAllSync();return!0}async resetLocalDatabase(){this.core.settings.isConfigured&&""==this.core.settings.additionalSuffixOfDatabaseName&&await this.services.database.resetDatabase();const suffix=this.services.API.getAppID()||"";this.core.settings.additionalSuffixOfDatabaseName=suffix;await this.services.database.resetDatabase();eventHub.emitEvent(EVENT_DATABASE_REBUILT)}async fetchRemoteChunks(){if(!this.core.settings.doNotSuspendOnFetching&&!this.core.settings.useOnlyLocalChunk&&this.core.settings.remoteType==REMOTE_COUCHDB){this._log("Fetching chunks",LOG_LEVEL_NOTICE);const replicator=this.services.replicator.getActiveReplicator(),remoteDB=await replicator.connectRemoteCouchDBWithSetting(this.settings,this.services.API.isMobile(),!0);"string"==typeof remoteDB?this._log(remoteDB,LOG_LEVEL_NOTICE):await fetchAllUsedChunks(this.localDatabase.localDatabase,remoteDB.db);this._log("Fetching chunks done",LOG_LEVEL_NOTICE)}}async resolveAllConflictedFilesByNewerOnes(){this._log("Resolving conflicts by newer ones",LOG_LEVEL_NOTICE);const files=this.core.storageAccess.getFileNames();let i2=0;for(const file of files){i2++%10&&this._log(`Check and Processing ${i2} / ${files.length}`,LOG_LEVEL_NOTICE,"resolveAllConflictedFilesByNewerOnes");await this.services.conflict.resolveByNewest(file)}this._log("Done!",LOG_LEVEL_NOTICE,"resolveAllConflictedFilesByNewerOnes")}onBindFunction(core,services){services.appLifecycle.handleOnLoaded(this._everyOnload.bind(this));services.database.handleResetDatabase(this._resetLocalDatabase.bind(this));services.remote.handleTryResetDatabase(this._tryResetRemoteDatabase.bind(this));services.remote.handleTryCreateDatabase(this._tryCreateRemoteDatabase.bind(this));services.setting.handleSuspendAllSync(this._allSuspendAllSync.bind(this))}};ModuleReplicateTest=class extends AbstractObsidianModule{constructor(){super(...arguments);this.testRootPath="_test/";this.testInfoPath="_testinfo/";this.watchIsSynchronised=!1}get isLeader(){return this.services.vault.getVaultName().indexOf("dev")>=0&&this.services.vault.vaultName().indexOf("recv")<0}get nameByKind(){return this.isLeader?this.isLeader?"LEADER":void 0:"RECV"}get pairName(){return this.isLeader?"RECV":this.isLeader?void 0:"LEADER"}async readFileContent(file){try{return await this.core.storageAccess.readHiddenFileText(file)}catch(e3){return""}}async dumpList(){if(this.settings.syncInternalFiles){this._log("Write file list (Include Hidden)");await this.__dumpFileListIncludeHidden("files.md")}else{this._log("Write file list");await this.__dumpFileList("files.md")}}async _everyBeforeReplicate(showMessage){if(!this.settings.enableDebugTools)return Promise.resolve(!0);await this.dumpList();return!0}_everyOnloadAfterLoadSettings(){if(!this.settings.enableDebugTools)return Promise.resolve(!0);this.addCommand({id:"dump-file-structure-normal",name:"Dump Structure (Normal)",callback:()=>{this.__dumpFileList("files.md").finally((()=>{this.refreshSyncStatus()}))}});this.addCommand({id:"dump-file-structure-ih",name:"Dump Structure (Include Hidden)",callback:()=>{this.__dumpFileListIncludeHidden("files.md")}});this.addCommand({id:"dump-file-structure-auto",name:"Dump Structure",callback:()=>{this.dumpList()}});this.addCommand({id:"dump-file-test",name:"Perform Test (Dev) "+(this.isLeader?"(Leader)":"(Recv)"),callback:()=>{this.performTestManually()}});this.addCommand({id:"watch-sync-result",name:"Watch sync result is matched between devices",callback:()=>{this.watchIsSynchronised=!this.watchIsSynchronised;this.refreshSyncStatus()}});this.app.vault.on("modify",(async file=>{file.path.startsWith(this.testInfoPath)?await this.refreshSyncStatus():scheduleTask("dumpStatus",125,(async()=>{await this.dumpList();return!0}))}));this.statusBarSyncStatus=this.plugin.addStatusBarItem();return Promise.resolve(!0)}async getSyncStatusAsText(){const fileMine=this.testInfoPath+this.nameByKind+"/files.md",filePair=this.testInfoPath+this.pairName+"/files.md",mine=(0,import_obsidian.parseYaml)(await this.readFileContent(fileMine)),pair=(0,import_obsidian.parseYaml)(await this.readFileContent(filePair)),result=[];mine.length!=pair.length&&result.push(`File count is different: ${mine.length} vs ${pair.length}`);const filesAll=new Set([...mine.map((e3=>e3.path)),...pair.map((e3=>e3.path))]);for(const file of filesAll){const mineFile=mine.find((e3=>e3.path==file)),pairFile=pair.find((e3=>e3.path==file));if(mineFile&&pairFile){mineFile.size!=pairFile.size&&result.push(`Size is different: ${file} ${mineFile.size} vs ${pairFile.size}`);mineFile.hash!=pairFile.hash&&result.push(`Hash is different: ${file} ${mineFile.hash} vs ${pairFile.hash}`)}else result.push(`File not found: ${file}`)}eventHub.emitEvent("debug-sync-status",result);return result.join("\n")}async refreshSyncStatus(){if(this.watchIsSynchronised){const syncStatus=await this.getSyncStatusAsText();if(syncStatus){this.statusBarSyncStatus.setText("Sync Status: Having Error");this._log(`Sync Status: Having Error\n${syncStatus}`,LOG_LEVEL_INFO)}else this.statusBarSyncStatus.setText("Sync Status: Synchronised")}else this.statusBarSyncStatus.setText("")}async __dumpFileList(outFile){if(!this.core||!this.core.storageAccess){this._log("No storage access",LOG_LEVEL_INFO);return}const files=this.core.storageAccess.getFiles(),out=[],webcrypto7=await getWebCrypto();for(const file of files){if(!await this.services.vault.isTargetFile(file.path))continue;if(file.path.startsWith(this.testInfoPath))continue;const stat=await this.core.storageAccess.stat(file.path);if(stat){const hashSrc=await this.core.storageAccess.readHiddenFileBinary(file.path),hash3=await webcrypto7.subtle.digest("SHA-1",hashSrc),hashStr=uint8ArrayToHexString(new Uint8Array(hash3)),item={path:file.path,name:file.name,size:stat.size,mtime:stat.mtime,hash:hashStr};out.push(item)}}out.sort(((a2,b3)=>a2.path.localeCompare(b3.path)));if(outFile){outFile=this.testInfoPath+this.nameByKind+"/"+outFile;await this.core.storageAccess.ensureDir(outFile);await this.core.storageAccess.writeHiddenFileAuto(outFile,(0,import_obsidian.stringifyYaml)(out))}this._log(`Dumped ${out.length} files`,LOG_LEVEL_INFO)}async __dumpFileListIncludeHidden(outFile){const ignorePatterns=getFileRegExp(this.plugin.settings,"syncInternalFilesIgnorePatterns"),targetPatterns=getFileRegExp(this.plugin.settings,"syncInternalFilesTargetPatterns"),out=[],files=await this.core.storageAccess.getFilesIncludeHidden("",targetPatterns,ignorePatterns),webcrypto7=await getWebCrypto();for(const file of files){if(file.startsWith(this.testInfoPath))continue;const stat=await this.core.storageAccess.statHidden(file);if(stat){const hashSrc=await this.core.storageAccess.readHiddenFileBinary(file),hash3=await webcrypto7.subtle.digest("SHA-1",hashSrc),hashStr=uint8ArrayToHexString(new Uint8Array(hash3)),item={path:file,name:file.split("/").pop(),size:stat.size,mtime:stat.mtime,hash:hashStr};out.push(item)}}out.sort(((a2,b3)=>a2.path.localeCompare(b3.path)));if(outFile){outFile=this.testInfoPath+this.nameByKind+"/"+outFile;await this.core.storageAccess.ensureDir(outFile);await this.core.storageAccess.writeHiddenFileAuto(outFile,(0,import_obsidian.stringifyYaml)(out))}this._log(`Dumped ${out.length} files`,LOG_LEVEL_NOTICE)}async collectTestFiles(){const files=["README.md","docs/adding_translations.md","docs/design_docs_of_journalsync.md","docs/design_docs_of_keep_newborn_chunks.md","docs/design_docs_of_prefixed_hidden_file_sync.md","docs/design_docs_of_sharing_tweak_value.md","docs/quick_setup_cn.md","docs/quick_setup_ja.md","docs/quick_setup.md","docs/settings_ja.md","docs/settings.md","docs/setup_cloudant_ja.md","docs/setup_cloudant.md","docs/setup_flyio.md","docs/setup_own_server_cn.md","docs/setup_own_server_ja.md","docs/setup_own_server.md","docs/tech_info_ja.md","docs/tech_info.md","docs/terms.md","docs/troubleshooting.md","images/1.png","images/2.png","images/corrupted_data.png","images/hatch.png","images/lock_pattern1.png","images/lock_pattern2.png","images/quick_setup_1.png","images/quick_setup_2.png","images/quick_setup_3.png","images/quick_setup_3b.png","images/quick_setup_4.png","images/quick_setup_5.png","images/quick_setup_6.png","images/quick_setup_7.png","images/quick_setup_8.png","images/quick_setup_9_1.png","images/quick_setup_9_2.png","images/quick_setup_10.png","images/remote_db_setting.png","images/write_logs_into_the_file.png"];for(const file of files){const remote="https://raw.githubusercontent.com/vrtmrz/obsidian-livesync/refs/heads/main/"+file,local=this.testRootPath+file;try{const f4=(await(0,import_obsidian.requestUrl)(remote)).arrayBuffer;await this.core.storageAccess.ensureDir(local);await this.core.storageAccess.writeHiddenFileAuto(local,f4)}catch(ex){this._log(`Could not fetch ${remote}`,LOG_LEVEL_VERBOSE);this._log(ex,LOG_LEVEL_VERBOSE)}}await this.dumpList()}async waitFor(proc,timeout=1e4){await delay(100);const start=Date.now();for(;!await proc();){if(timeout>0&&Date.now()-start>timeout){this._log("Timeout");return!1}await delay(500)}return!0}async testConflictedManually1(){await this.services.replication.replicate();this.isLeader&&await this.core.storageAccess.writeHiddenFileAuto(this.testRootPath+"wonka.md","Resolve! \n*****, the amazing chocolatier!!");await this.services.replication.replicate();await this.services.replication.replicate();if("no"==await this.core.confirm.askYesNoDialog("Ready to begin the test conflict Manually 1?",{timeout:30,defaultOption:"Yes"}))return;const fileA="Resolve to KEEP THIS\nWilly Wonka, Willy Wonka, the amazing chocolatier!!";this.isLeader?await this.core.storageAccess.writeHiddenFileAuto(this.testRootPath+"wonka.md",fileA):await this.core.storageAccess.writeHiddenFileAuto(this.testRootPath+"wonka.md","Resolve to DISCARD THIS\nCharlie Bucket, Charlie Bucket, the amazing chocolatier!!");if("no"!=await this.core.confirm.askYesNoDialog("Ready to check the result of Manually 1?",{timeout:30,defaultOption:"Yes"})){await this.services.replication.replicate();await this.services.replication.replicate();return!!await this.waitFor((async()=>{await this.services.replication.replicate();return 1==await this.__assertStorageContent(this.testRootPath+"wonka.md",fileA,!1,!0)}),3e4)||await this.__assertStorageContent(this.testRootPath+"wonka.md",fileA,!1,!0)}}async testConflictedManually2(){await this.services.replication.replicate();this.isLeader&&await this.core.storageAccess.writeHiddenFileAuto(this.testRootPath+"concat.md","Resolve To concatenate\nABCDEFG");await this.services.replication.replicate();await this.services.replication.replicate();if("no"==await this.core.confirm.askYesNoDialog("Ready to begin the test conflict Manually 2?",{timeout:30,defaultOption:"Yes"}))return;const concatenated="Resolve to Concatenate\nABCDEFGHIJKLMNOPQRSTUVWXYZ";this.isLeader?await this.core.storageAccess.writeHiddenFileAuto(this.testRootPath+"concat.md","Resolve to Concatenate\nABCDEFGHIJKLMNOPQRSTYZ"):await this.core.storageAccess.writeHiddenFileAuto(this.testRootPath+"concat.md","Resolve to Concatenate\nAJKLMNOPQRSTUVWXYZ");if("no"!=await this.core.confirm.askYesNoDialog("Ready to test conflict Manually 2?",{timeout:30,defaultOption:"Yes"})){await this.services.replication.replicate();await this.services.replication.replicate();return!!await this.waitFor((async()=>{await this.services.replication.replicate();return 1==await this.__assertStorageContent(this.testRootPath+"concat.md",concatenated,!1,!0)}),3e4)||await this.__assertStorageContent(this.testRootPath+"concat.md",concatenated,!1,!0)}}async testConflictAutomatic(){if(this.isLeader){const baseDoc="Tasks!\n- [ ] Task 1\n- [ ] Task 2\n- [ ] Task 3\n- [ ] Task 4\n";await this.core.storageAccess.writeHiddenFileAuto(this.testRootPath+"task.md",baseDoc)}await delay(100);await this.services.replication.replicate();await this.services.replication.replicate();if("no"!=await this.core.confirm.askYesNoDialog("Ready to test conflict?",{timeout:30,defaultOption:"Yes"})){this.isLeader?await this.core.storageAccess.writeHiddenFileAuto(this.testRootPath+"task.md","Tasks!\n- [ ] Task 1\n- [v] Task 2\n- [ ] Task 3\n- [ ] Task 4\n"):await this.core.storageAccess.writeHiddenFileAuto(this.testRootPath+"task.md","Tasks!\n- [ ] Task 1\n- [ ] Task 2\n- [v] Task 3\n- [ ] Task 4\n");await this.services.replication.replicate();await this.services.replication.replicate();await delay(1e3);if("no"!=await this.core.confirm.askYesNoDialog("Ready to check result?",{timeout:30,defaultOption:"Yes"})){await this.services.replication.replicate();await this.services.replication.replicate();return this.__assertStorageContent(this.testRootPath+"task.md","Tasks!\n- [ ] Task 1\n- [v] Task 2\n- [v] Task 3\n- [ ] Task 4\n",!1,!0)}}}async checkConflictResolution(){this._log("Before testing conflicted files, resolve all once",LOG_LEVEL_NOTICE);await this.core.rebuilder.resolveAllConflictedFilesByNewerOnes();await this.core.rebuilder.resolveAllConflictedFilesByNewerOnes();await this.services.replication.replicate();await delay(1e3);if(!await this.testConflictAutomatic()){this._log("Conflict resolution (Auto) failed",LOG_LEVEL_NOTICE);return!1}if(!await this.testConflictedManually1()){this._log("Conflict resolution (Manual1) failed",LOG_LEVEL_NOTICE);return!1}if(!await this.testConflictedManually2()){this._log("Conflict resolution (Manual2) failed",LOG_LEVEL_NOTICE);return!1}return!0}async __assertStorageContent(fileName,content,inverted=!1,showResult=!1){try{const fileContent=await this.core.storageAccess.readHiddenFileText(fileName);let result=fileContent===content;inverted&&(result=!result);if(result)return!0;showResult&&this._log(`Content is not same \n Expected:${content}\n Actual:${fileContent}`,LOG_LEVEL_VERBOSE);return`Content is not same \n Expected:${content}\n Actual:${fileContent}`}catch(e3){this._log(`Cannot assert storage content: ${e3}`);return!1}}async performTestManually(){if(!this.settings.enableDebugTools)return Promise.resolve(!0);await this.checkConflictResolution()}async _everyModuleTestMultiDevice(){if(!this.settings.enableDebugTools)return Promise.resolve(!0);await this._test("Conflict resolution",(async()=>await this.checkConflictResolution()));return this.testDone()}onBindFunction(core,services){services.appLifecycle.handleOnSettingLoaded(this._everyOnloadAfterLoadSettings.bind(this));services.replication.handleBeforeReplicate(this._everyBeforeReplicate.bind(this));services.test.handleTestMultiDevice(this._everyModuleTestMultiDevice.bind(this))}};ModuleLiveSyncMain=class extends AbstractModule{constructor(){super(...arguments);this.isReady=!1;this._suspended=!1;this._unloaded=!1}async _onLiveSyncReady(){if(!await this.core.services.appLifecycle.onLayoutReady())return!1;eventHub.emitEvent(EVENT_LAYOUT_READY);if(this.settings.suspendFileWatching||this.settings.suspendParseReplicationResult){const ANSWER_KEEP=$msg("moduleLiveSyncMain.optionKeepLiveSyncDisabled"),ANSWER_RESUME=$msg("moduleLiveSyncMain.optionResumeAndRestart"),message=$msg("moduleLiveSyncMain.msgScramEnabled",{fileWatchingStatus:this.settings.suspendFileWatching?"suspended":"active",parseReplicationStatus:this.settings.suspendParseReplicationResult?"suspended":"active"});if(await this.core.confirm.askSelectStringDialogue(message,[ANSWER_KEEP,ANSWER_RESUME],{defaultAction:ANSWER_KEEP,title:$msg("moduleLiveSyncMain.titleScramEnabled")})==ANSWER_RESUME){this.settings.suspendFileWatching=!1;this.settings.suspendParseReplicationResult=!1;await this.saveSettings();this.services.appLifecycle.scheduleRestart();return!1}}if(!await this.services.databaseEvents.initialiseDatabase(!1,!1))return!1;if(!await this.core.services.appLifecycle.onFirstInitialise())return!1;await this.services.setting.realiseSetting();fireAndForget((async()=>{this._log($msg("moduleLiveSyncMain.logAdditionalSafetyScan"),LOG_LEVEL_VERBOSE);await this.services.appLifecycle.onScanningStartupIssues()?this._log($msg("moduleLiveSyncMain.logSafetyScanCompleted"),LOG_LEVEL_VERBOSE):this._log($msg("moduleLiveSyncMain.logSafetyScanFailed"),LOG_LEVEL_NOTICE)}));return!0}_wireUpEvents(){eventHub.onEvent(EVENT_SETTING_SAVED,(settings=>{fireAndForget((async()=>{var _a8,_b5,_c3;try{await this.core.services.setting.realiseSetting();void 0!==(null!=(_b5=null==(_a8=this.core.services.setting.currentSettings())?void 0:_a8.displayLanguage)?_b5:void 0)&&setLang(null==(_c3=this.core.services.setting.currentSettings())?void 0:_c3.displayLanguage);eventHub.emitEvent("reload-setting-tab")}catch(e3){this._log("Error in Setting Save Event",LOG_LEVEL_NOTICE);this._log(e3,LOG_LEVEL_VERBOSE)}}))}));return Promise.resolve(!0)}async _onLiveSyncLoad(){initialiseWorkerModule();await this.services.appLifecycle.onWireUpEvents();eventHub.emitEvent("plugin-loaded",this.core);this._log($msg("moduleLiveSyncMain.logLoadingPlugin"));if(!await this.services.appLifecycle.onInitialise()){this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"),LOG_LEVEL_NOTICE);return!1}this._log($msg("moduleLiveSyncMain.logPluginVersion",{manifestVersion:"0.25.38",packageVersion:"0.25.38"}));await this.services.setting.loadSettings();if(!await this.services.appLifecycle.onSettingLoaded()){this._log($msg("moduleLiveSyncMain.logPluginInitCancelled"),LOG_LEVEL_NOTICE);return!1}const lsKey="obsidian-live-sync-ver"+this.services.vault.getVaultName(),last_version=localStorage.getItem(lsKey);~~(versionNumberString2Number("0.25.38")/1e3)>this.settings.lastReadUpdates&&this.settings.isConfigured&&this._log($msg("moduleLiveSyncMain.logReadChangelog"),LOG_LEVEL_NOTICE);this.isMobile&&(this.settings.disableRequestURI=!0);if(last_version&&Number(last_version)<12){this.settings.liveSync=!1;this.settings.syncOnSave=!1;this.settings.syncOnEditorSave=!1;this.settings.syncOnStart=!1;this.settings.syncOnFileOpen=!1;this.settings.syncAfterMerge=!1;this.settings.periodicReplication=!1;this.settings.versionUpFlash=$msg("moduleLiveSyncMain.logVersionUpdate");await this.saveSettings()}localStorage.setItem(lsKey,"12");await this.services.database.openDatabase();await this.core.services.appLifecycle.onLoaded();await Promise.all(this.core.addOns.map((e3=>e3.onload())));return!0}async _onLiveSyncUnload(){var _a8;eventHub.emitEvent("plugin-unloaded");await this.services.appLifecycle.onBeforeUnload();cancelAllPeriodicTask();cancelAllTasks();stopAllRunningProcessors();await this.services.appLifecycle.onUnload();this._unloaded=!0;for(const addOn of this.core.addOns)addOn.onunload();if(null!=this.localDatabase){this.localDatabase.onunload();this.core.replicator&&(null==(_a8=this.core.replicator)||_a8.closeReplication());await this.localDatabase.close()}eventHub.emitEvent(EVENT_PLATFORM_UNLOADED);eventHub.offAll();this._log($msg("moduleLiveSyncMain.logUnloadingPlugin"))}async _realizeSettingSyncMode(){await this.services.appLifecycle.onSuspending();await this.services.setting.onBeforeRealiseSetting();this.localDatabase.refreshSettings();await this.services.fileProcessing.commitPendingFileEvents();await this.services.setting.onRealiseSetting();if(!this.services.appLifecycle.isSuspended()){await this.services.appLifecycle.onResuming();await this.services.appLifecycle.onResumed();await this.services.setting.onSettingRealised()}}_isReloadingScheduled(){return void 0!==this.core._totalProcessingCount}_isReady(){return this.isReady}_markIsReady(){this.isReady=!0}_resetIsReady(){this.isReady=!1}_isSuspended(){var _a8;return this._suspended||!(null==(_a8=this.settings)?void 0:_a8.isConfigured)}_setSuspended(value){this._suspended=value}_isUnloaded(){return this._unloaded}onBindFunction(core,services){super.onBindFunction(core,services);services.appLifecycle.handleIsSuspended(this._isSuspended.bind(this));services.appLifecycle.handleSetSuspended(this._setSuspended.bind(this));services.appLifecycle.handleIsReady(this._isReady.bind(this));services.appLifecycle.handleMarkIsReady(this._markIsReady.bind(this));services.appLifecycle.handleResetIsReady(this._resetIsReady.bind(this));services.appLifecycle.handleHasUnloaded(this._isUnloaded.bind(this));services.appLifecycle.handleIsReloadingScheduled(this._isReloadingScheduled.bind(this));services.appLifecycle.handleOnReady(this._onLiveSyncReady.bind(this));services.appLifecycle.handleOnWireUpEvents(this._wireUpEvents.bind(this));services.appLifecycle.handleOnLoad(this._onLiveSyncLoad.bind(this));services.appLifecycle.handleOnAppUnload(this._onLiveSyncUnload.bind(this));services.setting.handleRealiseSetting(this._realizeSettingSyncMode.bind(this))}};ModuleExtraSyncObsidian=class extends AbstractObsidianModule{constructor(){super(...arguments);this.deviceAndVaultName=""}_getDeviceAndVaultName(){return this.deviceAndVaultName}_setDeviceAndVaultName(name){this.deviceAndVaultName=name}onBindFunction(core,services){services.setting.handleGetDeviceAndVaultName(this._getDeviceAndVaultName.bind(this));services.setting.handleSetDeviceAndVaultName(this._setDeviceAndVaultName.bind(this))}};LocalDatabaseMaintenance=class extends LiveSyncCommands{onunload(){}onload(){this.plugin.addCommand({id:"analyse-database",name:"Analyse Database Usage (advanced)",icon:"database-search",callback:async()=>{await this.analyseDatabase()}});this.plugin.addCommand({id:"gc-v3",name:"Garbage Collection V3 (advanced, beta)",icon:"trash-2",callback:async()=>{await this.gcv3()}});eventHub.onEvent(EVENT_ANALYSE_DB_USAGE,(()=>this.analyseDatabase()));eventHub.onEvent(EVENT_REQUEST_PERFORM_GC_V3,(()=>this.gcv3()))}async allChunks(includeDeleted=!1){const p4=this._progress("",LOG_LEVEL_NOTICE);p4.log("Retrieving chunks informations..");try{return await this.localDatabase.allChunks(includeDeleted)}finally{p4.done()}}get database(){return this.localDatabase.localDatabase}clearHash(){this.localDatabase.clearCaches()}async confirm(title,message,affirmative="Yes",negative="No"){return await this.plugin.confirm.askSelectStringDialogue(message,[affirmative,negative],{title,defaultAction:affirmative})===affirmative}isAvailable(){if(!this.settings.doNotUseFixedRevisionForChunks){this._notice("Please enable 'Compute revisions for chunks' in settings to use Garbage Collection.");return!1}if(this.settings.readChunksOnline){this._notice("Please disable 'Read chunks online' in settings to use Garbage Collection.");return!1}return!0}async resurrectChunks(){if(!this.isAvailable())return;const{used,existing}=await this.allChunks(!0),excessiveDeletions=[...existing].filter((([key3,e3])=>e3._deleted)).filter((([key3,e3])=>used.has(e3._id))).map((([key3,e3])=>e3)),completelyLostChunks=[],dataLostChunks=[...existing].filter((([key3,e3])=>e3._deleted&&""===e3.data)).map((([key3,e3])=>e3)).filter((e3=>used.has(e3._id)));for(const e3 of dataLostChunks){let resurrected=null;const availableRevs=((await this.database.get(e3._id,{rev:e3._rev,revs:!0,revs_info:!0,conflicts:!0}))._revs_info||[]).filter((e4=>"available"==e4.status)).map((e4=>e4.rev)).sort(((a2,b3)=>getNoFromRev(a2)-getNoFromRev(b3)));for(const rev3 of availableRevs){const revDoc=await this.database.get(e3._id,{rev:rev3});if("leaf"==revDoc.type&&""!==revDoc.data){resurrected=revDoc.data;break}}null!==resurrected?excessiveDeletions.push({...e3,data:resurrected,_deleted:!1}):completelyLostChunks.push(e3._id)}const resurrectChunks=excessiveDeletions.filter((e3=>""!==e3.data)).map((e3=>({...e3,_deleted:!1})));if(0==resurrectChunks.length){this._notice("No chunks are found to be resurrected.");return}const message=`We have following chunks that are deleted but still used in the database.\n\n- Completely lost chunks: ${completelyLostChunks.length}\n- Resurrectable chunks: ${resurrectChunks.length}\n\nDo you want to resurrect these chunks?`;if(await this.confirm("Resurrect Chunks",message,"Resurrect","Cancel")){const result=await this.database.bulkDocs(resurrectChunks);this.clearHash();const resurrectedChunks=result.filter((e3=>"ok"in e3)).map((e3=>e3.id));this._notice(`Resurrected chunks: ${resurrectedChunks.length} / ${resurrectChunks.length}`)}else this._notice("Resurrect operation is cancelled.")}async commitFileDeletion(){if(!this.isAvailable())return;const p4=this._progress("",LOG_LEVEL_NOTICE);p4.log("Searching for deleted files..");const deletedDocs=(await this.database.allDocs({include_docs:!0})).rows.filter((e3=>{var _a8,_b5,_c3;return("newnote"==(null==(_a8=e3.doc)?void 0:_a8.type)||"plain"==(null==(_b5=e3.doc)?void 0:_b5.type))&&(null==(_c3=e3.doc)?void 0:_c3.deleted)}));if(0==deletedDocs.length){p4.done("No deleted files found.");return}p4.log(`Found ${deletedDocs.length} deleted files.`);const message=`We have following files that are marked as deleted.\n\n- Deleted files: ${deletedDocs.length}\n\nAre you sure to delete these files permanently?\n\nNote: **Make sure to synchronise all devices before deletion.**\n\n> [!Note]\n> This operation affects the database permanently. Deleted files will not be recovered after this operation.\n> And, the chunks that are used in the deleted files will be ready for compaction.`,deletingDocs=deletedDocs.map((e3=>({...e3.doc,_deleted:!0})));if(await this.confirm("Delete Files",message,"Delete","Cancel")){const result=await this.database.bulkDocs(deletingDocs);this.clearHash();p4.done(`Deleted ${result.filter((e3=>"ok"in e3)).length} / ${deletedDocs.length} files.`)}else p4.done("Deletion operation is cancelled.")}async commitChunkDeletion(){if(!this.isAvailable())return;const{existing}=await this.allChunks(!0),deletedChunks=[...existing].filter((([key3,e3])=>e3._deleted&&""!==e3.data)).map((([key3,e3])=>e3)),deletedNotVacantChunks=deletedChunks.map((e3=>({...e3,data:"",_deleted:!0}))),humanSize=sizeToHumanReadable(deletedChunks.reduce(((acc,e3)=>acc+e3.data.length),0)),message=`We have following chunks that are marked as deleted.\n\n- Deleted chunks: ${deletedNotVacantChunks.length} (${humanSize})\n\nAre you sure to delete these chunks permanently?\n\nNote: **Make sure to synchronise all devices before deletion.**\n\n> [!Note]\n> This operation finally reduces the capacity of the remote.`;if(0!=deletedNotVacantChunks.length)if(await this.confirm("Delete Chunks",message,"Delete","Cancel")){const result=await this.database.bulkDocs(deletedNotVacantChunks);this.clearHash();this._notice(`Deleted chunks: ${result.filter((e3=>"ok"in e3)).length} / ${deletedNotVacantChunks.length}`)}else this._notice("Deletion operation is cancelled.");else this._notice("No deleted chunks found.")}async markUnusedChunks(){if(!this.isAvailable())return;const{used,existing}=await this.allChunks(),deleteChunks=[...existing].filter((([key3,e3])=>!used.has(e3._id))).map((([key3,e3])=>e3)).map((e3=>({...e3,_deleted:!0}))),humanSize=sizeToHumanReadable(deleteChunks.reduce(((acc,e3)=>acc+e3.data.length),0));if(0==deleteChunks.length){this._notice("No unused chunks found.");return}const message=`We have following chunks that are not used from any files.\n\n- Chunks: ${deleteChunks.length} (${humanSize})\n\nAre you sure to mark these chunks to be deleted?\n\nNote: **Make sure to synchronise all devices before deletion.**\n\n> [!Note]\n> This operation will not reduces the capacity of the remote until permanent deletion.`;if(await this.confirm("Mark unused chunks",message,"Mark","Cancel")){const result=await this.database.bulkDocs(deleteChunks);this.clearHash();this._notice(`Marked chunks: ${result.filter((e3=>"ok"in e3)).length} / ${deleteChunks.length}`)}}async removeUnusedChunks(){const{used,existing}=await this.allChunks(),unusedChunks=[...existing].filter((([key3,e3])=>!used.has(e3._id))).map((([key3,e3])=>e3)),deleteChunks=unusedChunks.map((e3=>({...e3,data:"",_deleted:!0}))),humanSize=sizeToHumanReadable(unusedChunks.reduce(((acc,e3)=>acc+e3.data.length),0));if(0==deleteChunks.length){this._notice("No unused chunks found.");return}const message=`We have following chunks that are not used from any files.\n\n- Chunks: ${deleteChunks.length} (${humanSize})\n\nAre you sure to delete these chunks?\n\nNote: **Make sure to synchronise all devices before deletion.**\n\n> [!Note]\n> Chunks referenced from deleted files are not deleted. Please run "Commit File Deletion" before this operation.`;if(await this.confirm("Mark unused chunks",message,"Mark","Cancel")){const result=await this.database.bulkDocs(deleteChunks);this._notice(`Deleted chunks: ${result.filter((e3=>"ok"in e3)).length} / ${deleteChunks.length}`);this.clearHash()}}async scanUnusedChunks(){const kvDB=this.plugin.kvDB,chunkSet=await kvDB.get("chunk-set")||new Set,chunkUsageMap=await kvDB.get("doc-usage-map")||new Map,unusedSet=new Set([...chunkSet]);for(const[,revIdMap]of chunkUsageMap){const sortedRevId=[...revIdMap.entries()].sort(((a2,b3)=>getNoFromRev(b3[0])-getNoFromRev(a2[0])));sortedRevId.length;sortedRevId.slice(0,10).forEach((e3=>e3[1].forEach((ee=>unusedSet.delete(ee)))))}return{chunkSet,chunkUsageMap,unusedSet}}async trackChanges(fromStart=!1,showNotice=!1){if(!this.isAvailable())return;const logLevel=showNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,kvDB=this.plugin.kvDB,previousSeq=fromStart?"":await kvDB.get("gc-seq"),chunkSet=await kvDB.get("chunk-set")||new Set,chunkUsageMap=await kvDB.get("doc-usage-map")||new Map,db=this.localDatabase.localDatabase,verbose2=msg=>this._verbose(msg),processDoc=async(doc,isDeleted2)=>{if(!("children"in doc))return;const id=doc._id,rev3=doc._rev,deleted=doc._deleted||isDeleted2,softDeleted=doc.deleted,children=doc.children||[];chunkUsageMap.has(id)||chunkUsageMap.set(id,new Map);for(const chunkId of children)deleted?chunkUsageMap.get(id).delete(rev3):chunkUsageMap.get(id).set(rev3,(chunkUsageMap.get(id).get(rev3)||new Set).add(chunkId));verbose2(`Tracking chunk: ${id}/${rev3} (${null==doc?void 0:doc.path}), deleted: ${deleted?"yes":"no"} Soft-Deleted:${softDeleted?"yes":"no"}`);return await Promise.resolve()},saveState=async seq=>{await kvDB.set("gc-seq",seq);await kvDB.set("chunk-set",chunkSet);await kvDB.set("doc-usage-map",chunkUsageMap)},processDocRevisions=async doc=>{var _a8;try{const oldRevisions=await db.get(doc._id,{revs:!0,revs_info:!0,conflicts:!0}),allRevs=(null==(_a8=oldRevisions._revs_info)?void 0:_a8.length)||0,info3=(oldRevisions._revs_info||[]).filter((e3=>"available"==e3.status&&e3.rev!=doc._rev)).filter((info4=>{var _a9;return!(null==(_a9=chunkUsageMap.get(doc._id))?void 0:_a9.has(info4.rev))})),infoLength=info3.length;this._log(`Found ${allRevs} old revisions for ${doc._id} . ${infoLength} items to check `);if(info3.length>0){const oldDocs=await Promise.all(info3.filter((revInfo=>"available"==revInfo.status)).map((revInfo=>db.get(doc._id,{rev:revInfo.rev})))).then((docs=>docs.filter((doc2=>doc2))));for(const oldDoc of oldDocs)await processDoc(oldDoc,!1)}}catch(ex){if(404==(null==ex?void 0:ex.status))this._log(`No revisions found for ${doc._id}`,LOG_LEVEL_VERBOSE);else{this._log(`Error finding revisions for ${doc._id}`);this._verbose(ex)}}},processChange2=async(doc,isDeleted2,seq)=>{if("leaf"===doc.type){if(isDeleted2)return;chunkSet.add(doc._id)}else if("children"in doc){await processDoc(doc,isDeleted2);await serialized("x-process-doc",(async()=>await processDocRevisions(doc)))}};let i2=0;await db.changes({since:previousSeq||"",live:!1,conflicts:!0,include_docs:!0,style:"all_docs",return_docs:!1}).on("change",(async change=>{var _a8;await processChange2(change.doc,null!=(_a8=change.deleted)&&_a8,change.seq);i2++%100==0&&await saveState(change.seq)})).on("complete",(async info3=>{await saveState(info3.last_seq)}));const result=await this.scanUnusedChunks(),message=`Total chunks: ${result.chunkSet.size}\nUnused chunks: ${result.unusedSet.size}`;this._log(message,logLevel)}async performGC(showingNotice=!1){var _a8;if(!this.isAvailable())return;await this.trackChanges(!1,showingNotice);const logLevel=showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO;if("Yes, delete chunks"!==await this.plugin.confirm.askSelectStringDialogue("This function deletes unused chunks from the device. If there are differences between devices, some chunks may be missing when resolving conflicts.\nBe sure to synchronise before executing.\n\nHowever, if you have deleted them, you may be able to recover them by performing Hatch -> Recreate missing chunks for all files.\n\nAre you ready to delete unused chunks?",["Yes, delete chunks","Cancel"],{title:"Are all devices synchronised?",defaultAction:"Cancel"})){this._log("User cancelled chunk deletion",logLevel);return}const{unusedSet,chunkSet}=await this.scanUnusedChunks(),deleteChunks=await this.database.allDocs({keys:[...unusedSet],include_docs:!0});for(const chunk of deleteChunks.rows)(null==(_a8=null==chunk?void 0:chunk.value)?void 0:_a8.deleted)&&chunkSet.delete(chunk.key);const deleteDocs=deleteChunks.rows.filter((e3=>"doc"in e3)).map((e3=>({...e3.doc,_deleted:!0})));this._log(`Deleting chunks: ${deleteDocs.length}`,logLevel);const deleteChunkBatch=arrayToChunkedArray(deleteDocs,100);let successCount=0,errored=0;for(const batch of deleteChunkBatch){const results=await this.database.bulkDocs(batch);for(const result2 of results)if("ok"in result2){chunkSet.delete(result2.id);successCount++}else{this._log(`Failed to delete doc: ${result2.id}`,LOG_LEVEL_VERBOSE);errored++}this._log(`Deleting chunks: ${successCount} `,logLevel,"gc-preforming")}const message=`Garbage Collection completed.\nSuccess: ${successCount}, Errored: ${errored}`;this._log(message,logLevel);const kvDB=this.plugin.kvDB;await kvDB.set("chunk-set",chunkSet)}async analyseDatabase(){if(!this.isAvailable())return;const db=this.localDatabase.localDatabase,chunkMap=new Map,docMap=new Map,info3=await db.info(),maxSeq=new Number(info3.update_seq);let processed=0,read=0,errored=0;const ft=[],fetchRevision=async(id,rev3,seq)=>{try{processed++;const doc=await db.get(id,{rev:rev3});if(doc){if("children"in doc){const id2=doc._id,rev4=doc._rev,children=doc.children||[],set2=docMap.get(id2)||new Set;set2.add({id:id2,rev:rev4,chunks:new Set(children),uniqueChunks:new Set,sharedChunks:new Set,path:doc.path});docMap.set(id2,set2)}else if("leaf"===doc.type){const id2=doc._id;if(chunkMap.has(id2))return;if(doc._deleted)return;const length=doc.data.length,set2=chunkMap.get(id2)||new Set;set2.add({id:id2,length,refCount:0});chunkMap.set(id2,set2)}read++}else{this._log(`Analysing Database: not found: ${id} / ${rev3}`);errored++}}catch(error){this._log(`Error fetching document ${id} / ${rev3}: $`,LOG_LEVEL_NOTICE);this._log(error,LOG_LEVEL_VERBOSE);errored++}processed%100==0&&this._log(`Analysing database: ${read} (${errored}) / ${maxSeq} `,LOG_LEVEL_NOTICE,"db-analyse")},IDs=this.localDatabase.findEntryNames("","",{});for await(const id of IDs){const revInfos=(await this.localDatabase.getRaw(id,{revs:!0,revs_info:!0,conflicts:!0}))._revs_info||[];for(const revInfo of revInfos)"available"==revInfo.status&&ft.push(fetchRevision(id,revInfo.rev))}await Promise.all(ft);for(const[,docRevs]of docMap)for(const docRev of docRevs)for(const chunkId of docRev.chunks){const chunkInfos=chunkMap.get(chunkId);if(chunkInfos)for(const chunkInfo of chunkInfos){0===chunkInfo.refCount?docRev.uniqueChunks.add(chunkId):docRev.sharedChunks.add(chunkId);chunkInfo.refCount++}}const result=[],getTotalSize=ids=>[...ids].reduce(((acc,chunkId)=>{const chunkInfos=chunkMap.get(chunkId);if(chunkInfos)for(const chunkInfo of chunkInfos)acc+=chunkInfo.length;return acc}),0);for(const doc of docMap.values())for(const rev3 of doc){const title=`${rev3.path} (${rev3.rev})`,id=rev3.id,revStr=`${getNoFromRev(rev3.rev)}`,revHash=rev3.rev.split("-")[1].substring(0,6),path2=rev3.path,uniqueChunkCount=rev3.uniqueChunks.size,sharedChunkCount=rev3.sharedChunks.size,uniqueChunkSize=getTotalSize(rev3.uniqueChunks),sharedChunkSize=getTotalSize(rev3.sharedChunks);result.push({title,path:path2,rev:revStr,revHash,id,uniqueChunkCount,sharedChunkCount,uniqueChunkSize,sharedChunkSize})}const orphanChunks=[...chunkMap.entries()].filter((([chunkId,infos])=>0===[...infos].reduce(((acc,info4)=>acc+info4.refCount),0))),orphanChunkSize=orphanChunks.reduce(((acc,[chunkId,infos])=>{for(const info4 of infos)acc+=info4.length;return acc}),0);result.push({title:"__orphan",id:"__orphan",path:"__orphan",rev:"1",revHash:"xxxxx",uniqueChunkCount:orphanChunks.length,sharedChunkCount:0,uniqueChunkSize:orphanChunkSize,sharedChunkSize:0});const csvSrc=result.map((e3=>[`${e3.title.replace(/"/g,'""')}"`,`${e3.id}`,`${e3.path}`,`${e3.rev}`,`${e3.revHash}`,`${e3.uniqueChunkCount}`,`${e3.sharedChunkCount}`,`${e3.uniqueChunkSize}`,`${e3.sharedChunkSize}`].join("\t")));csvSrc.unshift(Object.values({title:"Title",id:"Document ID",path:"Path",rev:"Revision No",revHash:"Revision Hash",uniqueChunkCount:"Unique Chunk Count",sharedChunkCount:"Shared Chunk Count",uniqueChunkSize:"Unique Chunk Size",sharedChunkSize:"Shared Chunk Size"}).join("\t"));const csv=csvSrc.join("\n");await this.services.UI.promptCopyToClipboard("Database Analysis data (TSV):",csv)}async compactDatabase(){const replicator=this.plugin.replicator,remote=await replicator.connectRemoteCouchDBWithSetting(this.settings,!1,!1,!0);if(!remote){this._notice("Failed to connect to remote for compaction.","gc-compact");return}if("string"==typeof remote){this._notice(`Failed to connect to remote for compaction. ${remote}`,"gc-compact");return}const compactResult=await remote.db.compact({interval:1e3});let timeout=12e4;for(;;){const status=await remote.db.info();if(!("compact_running"in status)||!(null==status?void 0:status.compact_running))break;this._notice("Compaction in progress on remote database...","gc-compact");await delay(2e3);timeout-=2e3;if(timeout<=0){this._notice("Compaction on remote database timed out.","gc-compact");break}}compactResult&&"ok"in compactResult?this._notice("Compaction on remote database completed successfully.","gc-compact"):this._notice("Compaction on remote database failed.","gc-compact")}async compactDatabaseWithRevLimit(){return!1}async gcv3(){if(!this.isAvailable())return;const replicator=this.plugin.replicator;if(!await replicator.openOneShotReplication(this.settings,!1,!1,"sync")){this._notice("Failed to start one-shot replication before Garbage Collection. Garbage Collection Cancelled.");return}const OPTION_CANCEL="Cancel Garbage Collection",info3=await this.plugin.replicator.getConnectedDeviceList();if(!info3){this._notice("No connected device information found. Cancelling Garbage Collection.");return}const{accepted_nodes,node_info}=info3,infoMissingNodes=[];for(const node of accepted_nodes)node in node_info||infoMissingNodes.push(node);if(infoMissingNodes.length>0){const message2=`The following accepted nodes are missing its node information:\n- ${infoMissingNodes.join("\n- ")}\n\nThis indicates that they have not been connected for some time or have been left on an older version.\nIt is preferable to update all devices if possible. If you have any devices that are no longer in use, you can clear all accepted nodes by locking the remote once.`,OPTION_IGNORE="Ignore and Proceed",buttons2=[OPTION_CANCEL,OPTION_IGNORE],result2=await this.plugin.confirm.askSelectStringDialogue(message2,buttons2,{title:"Node Information Missing",defaultAction:OPTION_CANCEL});if(result2===OPTION_CANCEL){this._notice("Garbage Collection cancelled by user.");return}result2===OPTION_IGNORE&&this._notice("Proceeding with Garbage Collection, ignoring missing nodes.")}const progressValues=Object.values(node_info).map((e3=>e3.progress.split("-")[0])).map((e3=>parseInt(e3))),maxProgress=Math.max(...progressValues),minProgress=Math.min(...progressValues),progressDifference=maxProgress-minProgress,detail=`> [!INFO]- The connected devices have been detected as follows:\n${Object.entries(node_info).map((([nodeId,nodeData])=>`> - Device: ${nodeData.device_name} (Node ID: ${nodeId})\n> - Obsidian version: ${nodeData.app_version}\n> - Plug-in version: ${nodeData.plugin_version}\n> - Progress: ${nodeData.progress.split("-")[0]}`)).join("\n")}\n`,message=0!=progressDifference?`Some devices have differing progress values (max: ${maxProgress}, min: ${minProgress}).\nThis may indicate that some devices have not completed synchronisation, which could lead to conflicts. Strongly recommend confirming that all devices are synchronised before proceeding.`:`All devices have the same progress value (${maxProgress}). Your devices seem to be synchronised. And be able to proceed with Garbage Collection.`,buttons=["Proceed Garbage Collection",OPTION_CANCEL],defaultAction=0!=progressDifference?OPTION_CANCEL:"Proceed Garbage Collection";if("Proceed Garbage Collection"!==await this.plugin.confirm.askSelectStringDialogue(message+"\n\n"+detail,buttons,{title:"Garbage Collection Confirmation",defaultAction})){this._notice("Garbage Collection cancelled by user.");return}this._notice("Proceeding with Garbage Collection.");const gcStartTime=Date.now(),localDatabase=this.localDatabase.localDatabase,usedChunks=new Set,allChunks=new Map,IDs=this.localDatabase.findEntryNames("","",{});let i2=0;const doc_count=(await localDatabase.info()).doc_count;for await(const id of IDs){const doc=await this.localDatabase.getRaw(id);i2++;i2%100==0&&this._notice(`Garbage Collection: Scanned ${i2} / ~${doc_count} `,"gc-scanning");if(doc)if("children"in doc){const children=doc.children||[];for(const chunkId of children)usedChunks.add(chunkId)}else"leaf"===doc.type&&allChunks.set(doc._id,doc._rev)}this._notice(`Garbage Collection: Scanning completed. Total chunks: ${allChunks.size}, Used chunks: ${usedChunks.size}`,"gc-scanning");const unusedChunks=[...allChunks.keys()].filter((e3=>!usedChunks.has(e3)));this._notice(`Garbage Collection: Found ${unusedChunks.length} unused chunks to delete.`,"gc-scanning");const deleteChunkDocs=unusedChunks.map((chunkId=>({_id:chunkId,_deleted:!0,_rev:allChunks.get(chunkId)}))),deletedCount=(await localDatabase.bulkDocs(deleteChunkDocs)).filter((e3=>"ok"in e3)).length,gcEndTime=Date.now();this._notice(`Garbage Collection completed. Deleted chunks: ${deletedCount} / ${unusedChunks.length}. Time taken: ${(gcEndTime-gcStartTime)/1e3} seconds.`);if(await replicator.openOneShotReplication(this.settings,!1,!1,"pushOnly")){await this.compactDatabase();this.clearHash()}else this._notice("Failed to start replication after Garbage Collection.")}};EVENT_P2P_PEER_SHOW_EXTRA_MENU="p2p-peer-show-extra-menu";AcceptedStatus=(AcceptedStatus2=>{AcceptedStatus2.UNKNOWN="Unknown";AcceptedStatus2.ACCEPTED="Accepted";AcceptedStatus2.DENIED="Denied";AcceptedStatus2.ACCEPTED_IN_SESSION="Accepted in session";AcceptedStatus2.DENIED_IN_SESSION="Denied in session";return AcceptedStatus2})(AcceptedStatus||{});ConnectionStatus=(ConnectionStatus2=>{ConnectionStatus2.CONNECTED="Connected";ConnectionStatus2.CONNECTED_LIVE="Connected(live)";ConnectionStatus2.DISCONNECTED="Disconnected";return ConnectionStatus2})(ConnectionStatus||{});root_219=from_html("<span> </span>");root_130=from_html('<div class="row"></div>');root_39=from_html('<span class="chip attr svelte-8nqxsr"> </span>');on_click4=(__3,makeDecision)=>makeDecision(!0,!0);on_click_12=(__4,makeDecision)=>makeDecision(!0,!1);root_56=from_html('<button class="button svelte-8nqxsr">Accept in session</button> <button class="button mod-cta svelte-8nqxsr">Accept</button>',1);on_click_2=(__5,makeDecision)=>makeDecision(!1,!0);on_click_3=(__6,makeDecision)=>makeDecision(!1,!1);root_68=from_html('<button class="button svelte-8nqxsr">Deny in session</button> <button class="button mod-warning svelte-8nqxsr">Deny</button>',1);root_415=from_html("<!> <!>",1);on_click_4=(__7,revokeDecision)=>revokeDecision();root_79=from_html('<button class="button mod-warning svelte-8nqxsr">Revoke</button>');root_97=from_html('<button class="button svelte-8nqxsr">Stop ⚡</button>');root_106=from_html('<button class="button svelte-8nqxsr" title="live">⚡</button>');root_811=from_html('<div class="buttons svelte-8nqxsr"><div class="row svelte-8nqxsr"><button class="button svelte-8nqxsr">🔄</button> <!> <button class="button svelte-8nqxsr">...</button></div></div>');root37=from_html('<tr class="svelte-8nqxsr"><td><div class="info svelte-8nqxsr"><div class="row name"><span class="peername"> </span></div> <div class="row peer-id svelte-8nqxsr"><span class="peerid"> </span></div></div> <div class="status-chips svelte-8nqxsr"><div class="row"><span> </span></div> <!> <div class="row"></div></div></td><td><div class="buttons svelte-8nqxsr"><div class="row svelte-8nqxsr"><!></div></div></td><td><!></td></tr>');$$css15={hash:"svelte-8nqxsr",code:"tr.svelte-8nqxsr:nth-child(odd) {background-color:var(--background-primary-alt);}.info.svelte-8nqxsr {display:flex;flex-direction:column;justify-content:center;align-items:center;padding:var(--size-4-1) var(--size-4-1);}.peer-id.svelte-8nqxsr {font-size:0.8em;}.status-chips.svelte-8nqxsr {display:flex;flex-direction:column;justify-content:center;align-items:center;\n /* min-width: 10em; */}.buttons.svelte-8nqxsr {display:flex;flex-direction:column;justify-content:center;align-items:center;}.buttons.svelte-8nqxsr .row:where(.svelte-8nqxsr) {display:flex;justify-content:center;align-items:center;flex-wrap:wrap;\n /* padding: var(--size-4-1) var(--size-4-1); */}.chip.svelte-8nqxsr {display:inline-block;padding:4px 8px;margin:4px;border-radius:4px;font-size:0.75em;font-weight:bold;background-color:var(--tag-background);border:var(--tag-border-width) solid var(--tag-border-color);}.chip.connected.svelte-8nqxsr {background-color:var(--background-modifier-success);color:var(--text-normal);}.chip.connected-live.svelte-8nqxsr {background-color:var(--background-modifier-success);border-color:var(--background-modifier-success);color:var(--text-normal);}.chip.accepted.svelte-8nqxsr {background-color:var(--background-modifier-success);color:var(--text-normal);}.chip.waiting.svelte-8nqxsr {background-color:var(--background-secondary);}.chip.unknown.svelte-8nqxsr {background-color:var(--background-primary);color:var(--text-warning);}.chip.denied.svelte-8nqxsr {background-color:var(--background-modifier-error);color:var(--text-error);}.chip.attr.svelte-8nqxsr {background-color:var(--background-secondary);}.button.svelte-8nqxsr {margin:var(--size-4-1);}.button.affirmative.svelte-8nqxsr {background-color:var(--interactive-accent);color:var(--text-normal);}.button.affirmative.svelte-8nqxsr:hover {background-color:var(--interactive-accent-hover);}.button.negative.svelte-8nqxsr {background-color:var(--background-modifier-error);color:var(--text-error);}.button.negative.svelte-8nqxsr:hover {background-color:var(--background-modifier-error-hover);}"};delegate(["click"]);root_131=from_html('<p class="svelte-2cmos"> </p>');on_click5=(__5,useDefaultRelay)=>useDefaultRelay();on_click_13=(__6,chooseRandom)=>chooseRandom();root_310=from_html('<details><summary> </summary> <table class="settings svelte-2cmos"><tbody><tr><th class="svelte-2cmos">Enable P2P Replicator</th><td class="svelte-2cmos"><label><input type="checkbox" class="svelte-2cmos"/></label></td></tr><tr><th class="svelte-2cmos">Relay settings</th><td class="svelte-2cmos"><label><input type="text" placeholder="wss://exp-relay.vrtmrz.net, wss://xxxxx" autocomplete="off" class="svelte-2cmos"/> <button class="svelte-2cmos">Use vrtmrz\'s relay</button></label></td></tr><tr><th class="svelte-2cmos">Room ID</th><td class="svelte-2cmos"><label><input type="text" placeholder="anything-you-like" autocomplete="off" spellcheck="false" autocorrect="off" class="svelte-2cmos"/> <button class="svelte-2cmos">Use Random Number</button></label> <span><small>This can isolate your connections between devices. Use the same Room ID for the same\n devices.</small></span></td></tr><tr><th class="svelte-2cmos">Password</th><td class="svelte-2cmos"><label><input type="password" placeholder="password" class="svelte-2cmos"/></label> <span><small>This password is used to encrypt the connection. Use something long enough.</small></span></td></tr><tr><th class="svelte-2cmos">This device name</th><td class="svelte-2cmos"><label><input type="text" placeholder="iphone-16" autocomplete="off" class="svelte-2cmos"/></label> <span><small>Device name to identify the device. Please use shorter one for the stable peer\n detection, i.e., "iphone-16" or "macbook-2021".</small></span></td></tr><tr><th class="svelte-2cmos">Auto Connect</th><td class="svelte-2cmos"><label><input type="checkbox" class="svelte-2cmos"/></label></td></tr><tr><th class="svelte-2cmos">Start change-broadcasting on Connect</th><td class="svelte-2cmos"><label><input type="checkbox" class="svelte-2cmos"/></label></td></tr></tbody></table> <button class="button mod-cta">Save and Apply</button> <button class="button">Revert changes</button></details>');root_416=from_html('<p class="svelte-2cmos">No Connection</p>');root_57=from_html('<p class="svelte-2cmos"> </p>');root_69=from_html("<button>Connect</button>");root_98=from_html("<button>Stop Broadcasting</button>");root_107=from_html("<button>Start Broadcasting</button>");root_710=from_html('<button>Disconnect</button> <!> <details><summary>Broadcasting?</summary> <p class="svelte-2cmos"><small>If you want to use `LiveSync`, you should broadcast changes. All `watching` peers which\n detects this will start the replication for fetching. <br/> However, This should not be enabled if you want to increase your secrecy more.</small></p></details>',1);root38=from_html('<article class="svelte-2cmos"><h1>Peer to Peer Replicator</h1> <details><summary> </summary> <p class="important svelte-2cmos"> </p> <p class="important-sub svelte-2cmos"> </p> <!></details> <h2 class="svelte-2cmos">Connection Settings</h2> <!> <div><h2 class="svelte-2cmos">Signaling Server Connection</h2> <div><!></div> <div><!></div></div> <div><h2 class="svelte-2cmos">Peers</h2> <table class="peers svelte-2cmos"><thead><tr><th class="svelte-2cmos">Name</th><th class="svelte-2cmos">Action</th><th class="svelte-2cmos">Command</th></tr></thead><tbody></tbody></table></div></article>');$$css16={hash:"svelte-2cmos",code:"article.svelte-2cmos {max-width:100%;}article.svelte-2cmos p:where(.svelte-2cmos) {user-select:text;-webkit-user-select:text;}h2.svelte-2cmos {margin-top:var(--size-4-1);margin-bottom:var(--size-4-1);padding-bottom:var(--size-4-1);border-bottom:1px solid var(--background-modifier-border);}label.is-dirty.svelte-2cmos {background-color:var(--background-modifier-error);}input.svelte-2cmos {background-color:transparent;}th.svelte-2cmos {\n /* display: flex;\n justify-content: center;\n align-items: center; */min-height:var(--input-height);}td.svelte-2cmos {min-height:var(--input-height);}td.svelte-2cmos > label:where(.svelte-2cmos) {display:flex;flex-direction:row;align-items:center;justify-content:flex-start;min-height:var(--input-height);}td.svelte-2cmos > label:where(.svelte-2cmos) > :where(.svelte-2cmos) {margin:auto var(--size-4-1);}table.peers.svelte-2cmos {width:100%;}.important.svelte-2cmos {color:var(--text-error);font-size:1.2em;font-weight:bold;}.important-sub.svelte-2cmos {color:var(--text-warning);}.settings.svelte-2cmos label:where(.svelte-2cmos) {display:flex;flex-direction:row;align-items:center;justify-content:flex-start;flex-wrap:wrap;}"};delegate(["click"]);P2PReplicatorPaneView=class extends SvelteItemView{constructor(leaf,plugin3){super(leaf);this.icon="waypoints";this.title="";this.navigation=!1;this.plugin=plugin3;eventHub.onEvent(EVENT_P2P_PEER_SHOW_EXTRA_MENU,(({peer,event:event2})=>{this.m&&this.m.hide();this.m=(new import_obsidian.Menu).addItem((item=>item.setTitle("📥 Only Fetch").onClick((()=>this.replicateFrom(peer))))).addItem((item=>item.setTitle("📤 Only Send").onClick((()=>this.replicateTo(peer))))).addSeparator().addItem((item=>{item.setTitle("🔧 Get Configuration").onClick((async()=>{await this.getRemoteConfig(peer)}))})).addSeparator().addItem((item=>{const mark=peer.syncOnConnect?"checkmark":null;item.setTitle("Toggle Sync on connect").onClick((async()=>{await this.toggleProp(peer,"syncOnConnect")})).setIcon(mark)})).addItem((item=>{const mark=peer.watchOnConnect?"checkmark":null;item.setTitle("Toggle Watch on connect").onClick((async()=>{await this.toggleProp(peer,"watchOnConnect")})).setIcon(mark)})).addItem((item=>{const mark=peer.syncOnReplicationCommand?"checkmark":null;item.setTitle("Toggle Sync on `Replicate now` command").onClick((async()=>{await this.toggleProp(peer,"syncOnReplicationCommand")})).setIcon(mark)}));this.m.showAtPosition({x:event2.x,y:event2.y})}))}getIcon(){return"waypoints"}get replicator(){const r4=this.plugin.getAddOn(P2PReplicator.name);if(!r4||!r4._replicatorInstance)throw new Error("Replicator not found");return r4._replicatorInstance}async replicateFrom(peer){await this.replicator.replicateFrom(peer.peerId)}async replicateTo(peer){await this.replicator.requestSynchroniseToPeer(peer.peerId)}async getRemoteConfig(peer){Logger(`Requesting remote config for ${peer.name}. Please input the passphrase on the remote device`,LOG_LEVEL_NOTICE);const remoteConfig=await this.replicator.getRemoteConfig(peer.peerId);if(remoteConfig){Logger(`Remote config for ${peer.name} is retrieved successfully`);const DROP="Yes, and drop local database",KEEP="Yes, but keep local database",CANCEL="No, cancel",yn=await this.plugin.confirm.askSelectStringDialogue("Do you really want to apply the remote config? This will overwrite your current config immediately and restart.\nAnd you can also drop the local database to rebuild from the remote device.",[DROP,KEEP,CANCEL],{defaultAction:CANCEL,title:"Apply Remote Config "});if(yn===DROP||yn===KEEP){if(yn===DROP&&remoteConfig.remoteType!==REMOTE_P2P&&"yes"===await this.plugin.confirm.askYesNoDialog('Do you want to set the remote type to "P2P Sync" to rebuild by "P2P replication"?',{title:"Rebuild from remote device"})){remoteConfig.remoteType=REMOTE_P2P;remoteConfig.P2P_RebuildFrom=peer.name}this.plugin.settings=remoteConfig;await this.plugin.saveSettings();yn===DROP?await this.plugin.rebuilder.scheduleFetch():this.plugin.services.appLifecycle.scheduleRestart()}else Logger(`Cancelled\nRemote config for ${peer.name} is not applied`,LOG_LEVEL_NOTICE)}else Logger(`Cannot retrieve remote config for ${peer.peerId}`)}async toggleProp(peer,prop2){const targetSetting={syncOnConnect:"P2P_AutoSyncPeers",watchOnConnect:"P2P_AutoWatchPeers",syncOnReplicationCommand:"P2P_SyncOnReplication"}[prop2];if(peer[prop2]){this.plugin.settings[targetSetting]=removeFromList(peer.name,this.plugin.settings[targetSetting]);await this.plugin.saveSettings()}else{this.plugin.settings[targetSetting]=addToList(peer.name,this.plugin.settings[targetSetting]);await this.plugin.saveSettings()}await this.plugin.saveSettings()}getViewType(){return"p2p-replicator"}getDisplayText(){return"Peer-to-Peer Replicator"}async onClose(){await super.onClose();this.m&&this.m.hide()}instantiateComponent(target){const cmdSync=this.plugin.getAddOn(P2PReplicator.name);if(!cmdSync)throw new Error("Replicator not found");return mount(P2PReplicatorPane,{target,props:{plugin:cmdSync.plugin,cmdSync}})}};require("obsidian");ObsidianAPIBase=class extends APIBase{constructor(options){super();this.app=options.app}};eventHub.onceEvent(EVENT_PLATFORM_UNLOADED,(()=>{instance2=void 0;p3.resolve(void 0)}));instance2=void 0;p3=promiseWithResolver();import_obsidian4=require("obsidian");Environment=class extends ObsidianAPIBase{async onInit(){this.crypto=await getWebCrypto2()}getPlatformName(){return getPlatformName()}getPackageVersion(){return"0.25.38"}getManifestVersion(){return"0.25.38"}getVaultName(){return this.app.vault.getName()}};eventHub.onceEvent("app-supplied",(app=>{const platformAPI=new Environment({app});platformAPI.onInit().then((()=>setEnvironmentInstance(platformAPI)))}));P2PReplicator=class extends LiveSyncCommands{constructor(plugin3){super(plugin3);this.storeP2PStatusLine=reactiveSource("");this.p2pLogCollector=new P2PLogCollector;setReplicatorFunc((()=>this._replicatorInstance));addP2PEventHandlers(this);this.afterConstructor()}getSettings(){return this.plugin.settings}get settings(){return this.plugin.settings}getDB(){return this.plugin.localDatabase.localDatabase}get confirm(){return this.plugin.confirm}simpleStore(){return this._simpleStore}async handleReplicatedDocuments(docs){return await this.services.replication.parseSynchroniseResult(docs)}_anyNewReplicator(settingOverride={}){if({...this.settings,...settingOverride}.remoteType==REMOTE_P2P)return Promise.resolve(new LiveSyncTrysteroReplicator(this.plugin))}afterConstructor(){}async open(){await openP2PReplicator(this)}async close(){await closeP2PReplicator(this)}getConfig(key3){return this.services.config.getSmallConfig(key3)}setConfig(key3,value){return this.services.config.setSmallConfig(key3,value)}enableBroadcastCastings(){var _a8;return null==(_a8=null==this?void 0:this._replicatorInstance)?void 0:_a8.enableBroadcastChanges()}disableBroadcastCastings(){var _a8;return null==(_a8=null==this?void 0:this._replicatorInstance)?void 0:_a8.disableBroadcastChanges()}init(){this._simpleStore=this.services.database.openSimpleStore("p2p-sync");return Promise.resolve(this)}async initialiseP2PReplicator(){await this.init();try{if(this._replicatorInstance){await this._replicatorInstance.close();this._replicatorInstance=void 0}this.settings.P2P_AppID||(this.settings.P2P_AppID=P2P_DEFAULT_SETTINGS.P2P_AppID);const getInitialDeviceName=()=>this.getConfig(SETTING_KEY_P2P_DEVICE_NAME)||this.services.vault.getVaultName(),getSettings=()=>this.settings,store=()=>this.simpleStore(),getDB=()=>this.getDB(),getConfirm=()=>this.confirm,getPlatform=()=>this.getPlatform(),env={get db(){return getDB()},get confirm(){return getConfirm()},get deviceName(){return getInitialDeviceName()},get platform(){return getPlatform()},get settings(){return getSettings()},processReplicatedDocs:async docs=>{await this.handleReplicatedDocuments(docs)},get simpleStore(){return store()}};this._replicatorInstance=new TrysteroReplicator(env);return this._replicatorInstance}catch(e3){this._log(e3 instanceof Error?e3.message:"Something occurred on Initialising P2P Replicator",LOG_LEVEL_INFO);this._log(e3,LOG_LEVEL_VERBOSE);throw e3}}getPlatform(){return getPlatformName()}onunload(){removeP2PReplicatorInstance();this.close()}onload(){eventHub.onEvent("request-open-p2p",(()=>{this.openPane()}));this.p2pLogCollector.p2pReplicationLine.onChanged((line=>{this.storeP2PStatusLine.value=line.value}))}async _everyOnInitializeDatabase(){await this.initialiseP2PReplicator();return Promise.resolve(!0)}async _allSuspendExtraSync(){this.plugin.settings.P2P_Enabled=!1;this.plugin.settings.P2P_AutoAccepting=0;this.plugin.settings.P2P_AutoBroadcast=!1;this.plugin.settings.P2P_AutoStart=!1;this.plugin.settings.P2P_AutoSyncPeers="";this.plugin.settings.P2P_AutoWatchPeers="";return await Promise.resolve(!0)}async openPane(){await this.services.API.showWindow("p2p-replicator")}async _everyOnloadStart(){this.plugin.registerView("p2p-replicator",(leaf=>new P2PReplicatorPaneView(leaf,this.plugin)));this.plugin.addCommand({id:"open-p2p-replicator",name:"P2P Sync : Open P2P Replicator",callback:async()=>{await this.openPane()}});this.plugin.addCommand({id:"p2p-establish-connection",name:"P2P Sync : Connect to the Signalling Server",checkCallback:isChecking=>{var _a8,_b5,_c3;if(isChecking)return!(null!=(_c3=null==(_b5=null==(_a8=this._replicatorInstance)?void 0:_a8.server)?void 0:_b5.isServing)&&_c3);this.open()}});this.plugin.addCommand({id:"p2p-close-connection",name:"P2P Sync : Disconnect from the Signalling Server",checkCallback:isChecking=>{var _a8,_b5,_c3;if(isChecking)return null!=(_c3=null==(_b5=null==(_a8=this._replicatorInstance)?void 0:_a8.server)?void 0:_b5.isServing)&&_c3;Logger("Closing P2P Connection",LOG_LEVEL_NOTICE);this.close()}});this.plugin.addCommand({id:"replicate-now-by-p2p",name:"Replicate now by P2P",checkCallback:isChecking=>{var _a8,_b5,_c3;if(isChecking)return this.settings.remoteType!=REMOTE_P2P&&!!(null==(_b5=null==(_a8=this._replicatorInstance)?void 0:_a8.server)?void 0:_b5.isServing);null==(_c3=this._replicatorInstance)||_c3.replicateFromCommand(!1)}});this.plugin.addRibbonIcon("waypoints","P2P Replicator",(async()=>{await this.openPane()})).addClass("livesync-ribbon-replicate-p2p");return await Promise.resolve(!0)}_everyAfterResumeProcess(){this.settings.P2P_Enabled&&this.settings.P2P_AutoStart&&setTimeout((()=>{this.open()}),100);const rep=this._replicatorInstance;null==rep||rep.allowReconnection();return Promise.resolve(!0)}_everyBeforeSuspendProcess(){const rep=this._replicatorInstance;null==rep||rep.disconnectFromServer();return Promise.resolve(!0)}onBindFunction(core,services){services.replicator.handleGetNewReplicator(this._anyNewReplicator.bind(this));services.databaseEvents.handleOnDatabaseInitialisation(this._everyOnInitializeDatabase.bind(this));services.appLifecycle.handleOnInitialise(this._everyOnloadStart.bind(this));services.appLifecycle.handleOnSuspending(this._everyBeforeSuspendProcess.bind(this));services.appLifecycle.handleOnResumed(this._everyAfterResumeProcess.bind(this));services.setting.handleSuspendExtraSync(this._allSuspendExtraSync.bind(this))}};ServiceHub=class{constructor(services={}){this._injected={};for(const service of Object.values(services))service.setServices(this);this._injected=services}get API(){return this._injected.API||this._api}get path(){return this._injected.path||this._path}get database(){return this._injected.database||this._database}get databaseEvents(){return this._injected.databaseEvents||this._databaseEvents}get replicator(){return this._injected.replicator||this._replicator}get fileProcessing(){return this._injected.fileProcessing||this._fileProcessing}get replication(){return this._injected.replication||this._replication}get remote(){return this._injected.remote||this._remote}get conflict(){return this._injected.conflict||this._conflict}get appLifecycle(){return this._injected.appLifecycle||this._appLifecycle}get setting(){return this._injected.setting||this._setting}get tweakValue(){return this._injected.tweakValue||this._tweakValue}get vault(){return this._injected.vault||this._vault}get test(){return this._injected.test||this._test}get UI(){return this._injected.ui||this._ui}};HubService=class{get services(){return this._services}setServices(services){this._services=services}};ServiceBase=class extends HubService{_all(key3){return this._backend.all(key3)}_first(key3){return this._backend.first(key3)}_firstOrUndefined(key3){return this._backend.firstOrUndefined(key3)}_firstFailure(key3){return this._backend.firstFailure(key3)}_broadcast(key3){return this._backend.broadcast(key3)}_collect(key3){return this._backend.collect(key3)}_collectBatch(key3){return this._backend.collectBatch(key3)}constructor(hub){super();this._backend=hub}};APIService=class extends ServiceBase{};PathService=class extends ServiceBase{};DatabaseService=class extends ServiceBase{};DatabaseEventService=class extends ServiceBase{constructor(hub){super(hub);[this.onUnloadDatabase,this.handleOnUnloadDatabase]=this._all("dbUnload");[this.onCloseDatabase,this.handleOnCloseDatabase]=this._all("dbClose");[this.onDatabaseInitialisation,this.handleOnDatabaseInitialisation]=this._firstFailure("databaseInitialisation");[this.onDatabaseInitialised,this.handleDatabaseInitialised]=this._firstFailure("databaseInitialised");[this.onResetDatabase,this.handleOnResetDatabase]=this._firstFailure("resetDatabase")}};FileProcessingService=class extends ServiceBase{constructor(hub){super(hub);[this.processFileEvent,this.handleProcessFileEvent]=this._first("processFileEvent");[this.processOptionalFileEvent,this.handleOptionalFileEvent]=this._first("processOptionalFileEvent");[this.commitPendingFileEvents,this.handleCommitPendingFileEvents]=this._firstFailure("commitPendingFileEvents")}};ReplicatorService=class extends ServiceBase{constructor(hub){super(hub);[this.getNewReplicator,this.handleGetNewReplicator]=this._firstOrUndefined("getNewReplicator");[this.onCloseActiveReplication,this.handleOnCloseActiveReplication]=this._first("closeActiveReplication")}};ReplicationService=class extends ServiceBase{constructor(hub){super(hub);[this.processOptionalSynchroniseResult,this.handleProcessOptionalSynchroniseResult]=this._first("processOptionalSynchroniseResult");[this.processSynchroniseResult,this.handleProcessSynchroniseResult]=this._first("processSynchroniseResult");[this.processVirtualDocument,this.handleProcessVirtualDocuments]=this._first("processVirtualDocuments");[this.onBeforeReplicate,this.handleBeforeReplicate]=this._firstFailure("beforeReplicate");[this.checkConnectionFailure,this.handleCheckConnectionFailure]=this._first("connectionHasFailure")}};RemoteService=class extends ServiceBase{constructor(hub){super(hub)}};ConflictService=class extends ServiceBase{constructor(hub){super(hub);[this.resolveByUserInteraction,this.handleResolveByUserInteraction]=this._first("resolveByUserInteraction");[this.getOptionalConflictCheckMethod,this.handleGetOptionalConflictCheckMethod]=this._first("getOptionalConflictCheckMethod")}};AppLifecycleService=class extends ServiceBase{constructor(hub){super(hub);[this.onLayoutReady,this.handleLayoutReady]=this._firstFailure("layoutReady");[this.onFirstInitialise,this.handleFirstInitialise]=this._firstFailure("firstInitialise");[this.onReady,this.handleOnReady]=this._firstFailure("appReady");[this.onWireUpEvents,this.handleOnWireUpEvents]=this._firstFailure("wireUpEvents");[this.onLoad,this.handleOnLoad]=this._firstFailure("appLoad");[this.onAppUnload,this.handleOnAppUnload]=this._broadcast("appUnload");[this.onScanningStartupIssues,this.handleOnScanningStartupIssues]=this._all("scanStartupIssues");[this.onInitialise,this.handleOnInitialise]=this._firstFailure("appInitialise");[this.onLoaded,this.handleOnLoaded]=this._firstFailure("appLoaded");[this.onSettingLoaded,this.handleOnSettingLoaded]=this._firstFailure("applyStartupLoaded");[this.onBeforeUnload,this.handleOnBeforeUnload]=this._all("beforeUnload");[this.onUnload,this.handleOnUnload]=this._all("unload");[this.onSuspending,this.handleOnSuspending]=this._firstFailure("beforeSuspendProcess");[this.onResuming,this.handleOnResuming]=this._firstFailure("onResumeProcess");[this.onResumed,this.handleOnResumed]=this._firstFailure("afterResumeProcess");[this.getUnresolvedMessages,this.reportUnresolvedMessages]=this._collectBatch("unresolvedMessages")}};SettingService=class extends ServiceBase{constructor(hub){super(hub);[this.onBeforeRealiseSetting,this.handleBeforeRealiseSetting]=this._firstFailure("beforeRealiseSetting");[this.onSettingRealised,this.handleSettingRealised]=this._firstFailure("afterRealiseSetting");[this.onRealiseSetting,this.handleOnRealiseSetting]=this._firstFailure("realiseSetting");[this.suspendAllSync,this.handleSuspendAllSync]=this._all("suspendAllSync");[this.suspendExtraSync,this.handleSuspendExtraSync]=this._all("suspendExtraSync");[this.suggestOptionalFeatures,this.handleSuggestOptionalFeatures]=this._all("suggestOptionalFeatures");[this.enableOptionalFeature,this.handleEnableOptionalFeature]=this._all("enableOptionalFeature")}};TweakValueService=class extends ServiceBase{};VaultService=class extends ServiceBase{constructor(hub){super(hub)}};TestService=class extends ServiceBase{constructor(hub){super(hub);[this.test,this.handleTest]=this._firstFailure("test");[this.testMultiDevice,this.handleTestMultiDevice]=this._firstFailure("testMultiDevice")}};UIService=class extends HubService{};ConfigService=class extends HubService{};ConfigServiceBrowserCompat=class extends ConfigService{getSmallConfig(key3){const dbKey=`${this.services.vault.getVaultName()}-${key3}`;return localStorage.getItem(dbKey)}setSmallConfig(key3,value){const dbKey=`${this.services.vault.getVaultName()}-${key3}`;localStorage.setItem(dbKey,value)}deleteSmallConfig(key3){const dbKey=`${this.services.vault.getVaultName()}-${key3}`;localStorage.removeItem(dbKey)}};ThroughHole=class{constructor(){this.registeredFunctions=new Map}bindFunction(name,func){this.registeredFunctions.set(name,func)}getFunction(name){let invocation;return(...args)=>{invocation||(invocation=this.registeredFunctions.get(name));if(!invocation)throw new Error(`Function ${name} is not bound in ThroughHole`);return invocation(...args)}}};ChannelBase=class{constructor(name){this.name=name;this.handlers=[];this.handlerNames=new Map}isAlreadyRegistered(handler){const result=this.handlers.indexOf(handler);if(-1===result)return!1;console.error("Handler already registered at index",result);return!0}getHandlerName(handler){return this.handlerNames.get(handler)}register(handler,name){if(this.isAlreadyRegistered(handler))Logger("Handler already registered for "+this.name,LOG_LEVEL_VERBOSE);else{this.handlers.push(handler);this.handlerNames.set(handler,name)}}isSomeHandlerRegistered(){const result=this.handlers.length>0;result||console.warn("No handler registered");return result}};Pipeline=class extends ChannelBase{constructor(name){super(name)}register(handler,name){super.register(handler,name)}async invoke(...args){if(!this.isSomeHandlerRegistered()){Logger("No handler registered for Pipeline "+this.name,LOG_LEVEL_VERBOSE);return!0}for(const handler of this.handlers){const name=this.getHandlerName(handler);try{if(!1===await handler(...args)){Logger(`Handler ${null!=name?name:"unknown"} for Pipeline ${this.name} returned false`,LOG_LEVEL_VERBOSE);const err3=new Error;console.error(err3.stack);return!1}}catch(e3){Logger(`Handler ${null!=name?name:"unknown"} Error in Pipeline handler for ${this.name}`);Logger(e3,LOG_LEVEL_VERBOSE);return!1}}return!0}};Switch=class extends ChannelBase{constructor(name){super(name)}register(handler,name){super.register(handler,name)}async invoke(...args){if(this.isSomeHandlerRegistered())for(const handler of this.handlers)try{const result=await handler(...args);if(!1!==result)return result}catch(e3){Logger("Error in Switch handler for "+this.name);Logger(e3,LOG_LEVEL_VERBOSE)}else Logger("No handler registered for Switch "+this.name,LOG_LEVEL_VERBOSE)}};AN_ERROR_OCCURRED=Symbol("AN_ERROR_OCCURRED");Survey=class extends ChannelBase{constructor(name){super(name)}register(handler,name){super.register(handler,name)}invoke(...args){return this.isSomeHandlerRegistered()?this.handlers.map((async handler=>{try{return await handler(...args)}catch(e3){Logger("Error in Survey handler for "+this.name);Logger(e3,LOG_LEVEL_VERBOSE);return AN_ERROR_OCCURRED}})).filter((result=>result!==AN_ERROR_OCCURRED)):[]}};Broadcaster=class extends ChannelBase{constructor(name){super(name)}register(handler,name){super.register(handler,name)}async invoke(...args){this.isSomeHandlerRegistered()&&await Promise.all(this.handlers.map((async handler=>{try{await handler(...args)}catch(e3){Logger("Error in Broadcaster handler for "+this.name);Logger(e3,LOG_LEVEL_VERBOSE)}})))}};ServiceBackend=class{constructor(){this.pipelines=new Map;this.switches=new Map;this.surveys=new Map;this.broadcasters=new Map}getPipeline(name){if(this.pipelines.has(name))return this.pipelines.get(name);const pipeline=new Pipeline(name);this.pipelines.set(name,pipeline);return pipeline}getSwitch(name){if(this.switches.has(name))return this.switches.get(name);const switchChannel=new Switch(name);this.switches.set(name,switchChannel);return switchChannel}getSurvey(name){if(this.surveys.has(name))return this.surveys.get(name);const survey=new Survey(name);this.surveys.set(name,survey);return survey}getBroadcaster(name){if(this.broadcasters.has(name))return this.broadcasters.get(name);const broadcaster=new Broadcaster(name);this.broadcasters.set(name,broadcaster);return broadcaster}all(name){const pipeline=this.getPipeline(name);return[(...args)=>pipeline.invoke(...args),func=>pipeline.register(func,`${name} for ${func.name}`)]}first(name){const switchChannel=this.getSwitch(name);return[(...args)=>switchChannel.invoke(...args),func=>switchChannel.register(func,`${name} for ${func.name}`)]}firstOrUndefined(name){const switchChannel=this.getSwitch(name);return[async(...args)=>{const result=await switchChannel.invoke(...args);if(result)return result},handler=>{switchChannel.register((async(...args)=>{try{const result=await handler(...args);if(void 0!==result&&!1!==result)return result}catch(e3){Logger("Error in firstOrUndefined handler for "+name);Logger(e3,LOG_LEVEL_VERBOSE)}return!1}),`${name} for ${handler.name}`)}]}firstFailure(name){const survey=this.getSurvey(name);return[async(...args)=>{const resultTasks=survey.invoke(...args);try{return!(await Promise.all(resultTasks)).some((r4=>!1===r4))}catch(e3){Logger("Error in firstFailure handler for survey "+name);Logger(e3,LOG_LEVEL_VERBOSE);return!1}},handler=>{survey.register((async(...args)=>{try{const result=await handler(...args);if(void 0!==result&&!result)return!1}catch(e3){Logger("Error in firstFailure handler for survey "+name);Logger(e3,LOG_LEVEL_VERBOSE)}return!0}),`${name} for ${handler.name}`)}]}broadcast(name){const broadcaster=this.getBroadcaster(name);return[(...args)=>broadcaster.invoke(...args),func=>broadcaster.register(func,`${name} for ${func.name}`)]}collect(name){const survey=this.getSurvey(name);return[(...args)=>survey.invoke(...args),func=>survey.register(func,`${name} for ${func.name}`)]}collectBatch(name){const survey=this.getSurvey(name);return[(...args)=>{const tasks3=survey.invoke(...args);return Promise.all(tasks3)},func=>survey.register(func,`${name} for ${func.name}`)]}};InjectableAPIService=class extends APIService{getPlatform(){return"unknown"}constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.addLog,this.handleAddLog]=bindMethod(this._throughHole,"API.addLog");[this.getCustomFetchHandler,this.handleGetCustomFetchHandler]=bindMethod(this._throughHole,"API.getCustomFetchHandler");[this.isMobile,this.handleIsMobile]=bindMethod(this._throughHole,"API.isMobile");[this.showWindow,this.handleShowWindow]=bindMethod(this._throughHole,"API.showWindow");[this.getAppID,this.handleGetAppID]=bindMethod(this._throughHole,"API.getAppID");[this.isLastPostFailedDueToPayloadSize,this.handleIsLastPostFailedDueToPayloadSize]=bindMethod(this._throughHole,"API.isLastPostFailedDueToPayloadSize");[this.getAppVersion,this.handleGetAppVersion]=bindMethod(this._throughHole,"API.getAppVersion");[this.getPluginVersion,this.handleGetPluginVersion]=bindMethod(this._throughHole,"API.getPluginVersion")}};InjectablePathService=class extends PathService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.id2path,this.handleId2Path]=bindMethod(this._throughHole,"path.id2path");[this.path2id,this.handlePath2Id]=bindMethod(this._throughHole,"path.path2id")}};InjectableDatabaseService=class extends DatabaseService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.createPouchDBInstance,this.handleCreatePouchDBInstance]=bindMethod(this._throughHole,"database.createPouchDBInstance");[this.openSimpleStore,this.handleOpenSimpleStore]=bindMethod(this._throughHole,"database.openSimpleStore");[this.openDatabase,this.handleOpenDatabase]=bindMethod(this._throughHole,"database.openDatabase");[this.resetDatabase,this.handleResetDatabase]=bindMethod(this._throughHole,"database.resetDatabase");[this.isDatabaseReady,this.handleIsDatabaseReady]=bindMethod(this._throughHole,"database.isDatabaseReady")}};InjectableDatabaseEventService=class extends DatabaseEventService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.initialiseDatabase,this.handleInitialiseDatabase]=bindMethod(this._throughHole,"databaseEvents.initialiseDatabase")}};InjectableReplicatorService=class extends ReplicatorService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.getActiveReplicator,this.handleGetActiveReplicator]=bindMethod(this._throughHole,"replicator.getActiveReplicator")}};InjectableFileProcessingService=class extends FileProcessingService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole}};InjectableReplicationService=class extends ReplicationService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.parseSynchroniseResult,this.handleParseSynchroniseResult]=bindMethod(this._throughHole,"replication.parseSynchroniseResult");[this.isReplicationReady,this.handleIsReplicationReady]=bindMethod(this._throughHole,"replication.isReplicationReady");[this.replicate,this.handleReplicate]=bindMethod(this._throughHole,"replication.replicate");[this.replicateByEvent,this.handleReplicateByEvent]=bindMethod(this._throughHole,"replication.replicateByEvent")}};InjectableRemoteService=class extends RemoteService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.replicateAllToRemote,this.handleReplicateAllToRemote]=bindMethod(this._throughHole,"remote.replicateAllToRemote");[this.replicateAllFromRemote,this.handleReplicateAllFromRemote]=bindMethod(this._throughHole,"remote.replicateAllFromRemote");[this.markLocked,this.handleMarkLocked]=bindMethod(this._throughHole,"remote.markLocked");[this.markUnlocked,this.handleMarkUnlocked]=bindMethod(this._throughHole,"remote.markUnlocked");[this.markResolved,this.handleMarkResolved]=bindMethod(this._throughHole,"remote.markResolved");[this.tryResetDatabase,this.handleTryResetDatabase]=bindMethod(this._throughHole,"remote.tryResetDatabase");[this.tryCreateDatabase,this.handleTryCreateDatabase]=bindMethod(this._throughHole,"remote.tryCreateDatabase");[this.connect,this.handleConnect]=bindMethod(this._throughHole,"remote.connect")}};InjectableConflictService=class extends ConflictService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.queueCheckForIfOpen,this.handleQueueCheckForIfOpen]=bindMethod(this._throughHole,"conflict.queueCheckForIfOpen");[this.queueCheckFor,this.handleQueueCheckFor]=bindMethod(this._throughHole,"conflict.queueCheckFor");[this.ensureAllProcessed,this.handleEnsureAllProcessed]=bindMethod(this._throughHole,"conflict.ensureAllProcessed");[this.resolveByDeletingRevision,this.handleResolveByDeletingRevision]=bindMethod(this._throughHole,"conflict.resolveByDeletingRevision");[this.resolve,this.handleResolve]=bindMethod(this._throughHole,"conflict.resolve");[this.resolveByNewest,this.handleResolveByNewest]=bindMethod(this._throughHole,"conflict.resolveByNewest")}};InjectableAppLifecycleService=class extends AppLifecycleService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.performRestart,this.handlePerformRestart]=bindMethod(this._throughHole,"appLifecycle.performRestart");[this.askRestart,this.handleAskRestart]=bindMethod(this._throughHole,"appLifecycle.askRestart");[this.scheduleRestart,this.handleScheduleRestart]=bindMethod(this._throughHole,"appLifecycle.scheduleRestart");[this.isSuspended,this.handleIsSuspended]=bindMethod(this._throughHole,"appLifecycle.isSuspended");[this.setSuspended,this.handleSetSuspended]=bindMethod(this._throughHole,"appLifecycle.setSuspended");[this.isReady,this.handleIsReady]=bindMethod(this._throughHole,"appLifecycle.isReady");[this.markIsReady,this.handleMarkIsReady]=bindMethod(this._throughHole,"appLifecycle.markIsReady");[this.resetIsReady,this.handleResetIsReady]=bindMethod(this._throughHole,"appLifecycle.resetIsReady");[this.hasUnloaded,this.handleHasUnloaded]=bindMethod(this._throughHole,"appLifecycle.hasUnloaded");[this.isReloadingScheduled,this.handleIsReloadingScheduled]=bindMethod(this._throughHole,"appLifecycle.isReloadingScheduled")}};InjectableSettingService=class extends SettingService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.clearUsedPassphrase,this.handleClearUsedPassphrase]=bindMethod(this._throughHole,"setting.clearUsedPassphrase");[this.realiseSetting,this.handleRealiseSetting]=bindMethod(this._throughHole,"setting.realiseSetting");[this.decryptSettings,this.handleDecryptSettings]=bindMethod(this._throughHole,"setting.decryptSettings");[this.adjustSettings,this.handleAdjustSettings]=bindMethod(this._throughHole,"setting.adjustSettings");[this.getDeviceAndVaultName,this.handleGetDeviceAndVaultName]=bindMethod(this._throughHole,"setting.getDeviceAndVaultName");[this.setDeviceAndVaultName,this.handleSetDeviceAndVaultName]=bindMethod(this._throughHole,"setting.setDeviceAndVaultName");[this.saveDeviceAndVaultName,this.handleSaveDeviceAndVaultName]=bindMethod(this._throughHole,"setting.saveDeviceAndVaultName");[this.saveSettingData,this.handleSaveSettingData]=bindMethod(this._throughHole,"setting.saveSettingData");[this.loadSettings,this.handleLoadSettings]=bindMethod(this._throughHole,"setting.loadSettings");[this.currentSettings,this.handleCurrentSettings]=bindMethod(this._throughHole,"setting.currentSettings");[this.shouldCheckCaseInsensitively,this.handleShouldCheckCaseInsensitively]=bindMethod(this._throughHole,"setting.shouldCheckCaseInsensitively");[this.importSettings,this.handleImportSettings]=bindMethod(this._throughHole,"setting.importSettings")}};InjectableTweakValueService=class extends TweakValueService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.fetchRemotePreferred,this.handleFetchRemotePreferred]=bindMethod(this._throughHole,"tweakValue.fetchRemotePreferred");[this.checkAndAskResolvingMismatched,this.handleCheckAndAskResolvingMismatched]=bindMethod(this._throughHole,"tweakValue.checkAndAskResolvingMismatched");[this.askResolvingMismatched,this.handleAskResolvingMismatched]=bindMethod(this._throughHole,"tweakValue.askResolvingMismatched");[this.checkAndAskUseRemoteConfiguration,this.handleCheckAndAskUseRemoteConfiguration]=bindMethod(this._throughHole,"tweakValue.checkAndAskUseRemoteConfiguration");[this.askUseRemoteConfiguration,this.handleAskUseRemoteConfiguration]=bindMethod(this._throughHole,"tweakValue.askUseRemoteConfiguration")}};InjectableVaultService=class extends VaultService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.getVaultName,this.handleGetVaultName]=bindMethod(this._throughHole,"vault.getVaultName");[this.scanVault,this.handleScanVault]=bindMethod(this._throughHole,"vault.scanVault");[this.isIgnoredByIgnoreFile,this.handleIsIgnoredByIgnoreFile]=bindMethod(this._throughHole,"vault.isIgnoredByIgnoreFile");[this.isTargetFile,this.handleIsTargetFile]=bindMethod(this._throughHole,"vault.isTargetFile");[this.isFileSizeTooLarge,this.handleIsFileSizeTooLarge]=bindMethod(this._throughHole,"vault.isFileSizeTooLarge");[this.getActiveFilePath,this.handleGetActiveFilePath]=bindMethod(this._throughHole,"vault.getActiveFilePath");[this.markFileListPossiblyChanged,this.handleMarkFileListPossiblyChanged]=bindMethod(this._throughHole,"vault.markFileListPossiblyChanged");[this.isStorageInsensitive,this.handleIsStorageInsensitive]=bindMethod(this._throughHole,"vault.isStorageInsensitive");[this.vaultName,this.handleVaultName]=bindMethod(this._throughHole,"vault.vaultName")}};InjectableTestService=class extends TestService{constructor(backend,throughHole){super(backend);this._throughHole=throughHole;[this.addTestResult,this.handleAddTestResult]=bindMethod(this._throughHole,"test.addTestResult")}};InjectableServiceHub=class extends ServiceHub{constructor(services){super(services);this._serviceBackend=new ServiceBackend;this._throughHole=new ThroughHole;this._api=new InjectableAPIService(this._serviceBackend,this._throughHole);this._path=new InjectablePathService(this._serviceBackend,this._throughHole);this._database=new InjectableDatabaseService(this._serviceBackend,this._throughHole);this._databaseEvents=new InjectableDatabaseEventService(this._serviceBackend,this._throughHole);this._replicator=new InjectableReplicatorService(this._serviceBackend,this._throughHole);this._fileProcessing=new InjectableFileProcessingService(this._serviceBackend,this._throughHole);this._replication=new InjectableReplicationService(this._serviceBackend,this._throughHole);this._remote=new InjectableRemoteService(this._serviceBackend,this._throughHole);this._conflict=new InjectableConflictService(this._serviceBackend,this._throughHole);this._appLifecycle=new InjectableAppLifecycleService(this._serviceBackend,this._throughHole);this._setting=new InjectableSettingService(this._serviceBackend,this._throughHole);this._tweakValue=new InjectableTweakValueService(this._serviceBackend,this._throughHole);this._vault=new InjectableVaultService(this._serviceBackend,this._throughHole);this._test=new InjectableTestService(this._serviceBackend,this._throughHole);this._ui=services.ui;this._config=services.config}get API(){return this._api}get path(){return this._path}get database(){return this._database}get databaseEvents(){return this._databaseEvents}get replicator(){return this._replicator}get fileProcessing(){return this._fileProcessing}get replication(){return this._replication}get remote(){return this._remote}get conflict(){return this._conflict}get appLifecycle(){return this._appLifecycle}get setting(){return this._setting}get tweakValue(){return this._tweakValue}get vault(){return this._vault}get test(){return this._test}get UI(){return this._ui}get config(){return this._config}};on_click6=(_,copyToClipboard)=>copyToClipboard();root_220=from_html('<textarea readonly="" rows="4" class="svelte-u2ix67"></textarea> <button><!></button>',1);root39=from_html("<!> <!> <!> <!>",1);$$css17={hash:"svelte-u2ix67",code:"textarea.svelte-u2ix67 {resize:none;}"};delegate(["click"]);ObsidianUIService=class extends UIService{get dialogManager(){return this._dialogManager}constructor(plugin3){super();this._dialogManager=new SvelteDialogManager(plugin3);this._plugin=plugin3}async promptCopyToClipboard(title,value){const param={title,dataToCopy:value};return"ok"===await this._dialogManager.open(DialogueToCopy,param)}showMarkdownDialog(title,contentMD,buttons,defaultAction){return this._plugin.confirm.askSelectStringDialogue(contentMD,buttons,{title,defaultAction:null!=defaultAction?defaultAction:buttons[0],timeout:0})}};ObsidianAPIService=class extends InjectableAPIService{getPlatform(){return"obsidian"}};ObsidianPathService=class extends InjectablePathService{};ObsidianDatabaseService=class extends InjectableDatabaseService{};ObsidianReplicatorService=class extends InjectableReplicatorService{};ObsidianFileProcessingService=class extends InjectableFileProcessingService{};ObsidianReplicationService=class extends InjectableReplicationService{};ObsidianRemoteService=class extends InjectableRemoteService{};ObsidianConflictService=class extends InjectableConflictService{};ObsidianAppLifecycleService=class extends InjectableAppLifecycleService{};ObsidianSettingService=class extends InjectableSettingService{};ObsidianTweakValueService=class extends InjectableTweakValueService{};ObsidianVaultService=class extends InjectableVaultService{};ObsidianTestService=class extends InjectableTestService{};ObsidianConfigService=class extends ConfigServiceBrowserCompat{};ObsidianServiceHub=class extends InjectableServiceHub{constructor(plugin3){const config=new ObsidianConfigService;super({ui:new ObsidianUIService(plugin3),config});this._api=new ObsidianAPIService(this._serviceBackend,this._throughHole);this._path=new ObsidianPathService(this._serviceBackend,this._throughHole);this._database=new ObsidianDatabaseService(this._serviceBackend,this._throughHole);this._replicator=new ObsidianReplicatorService(this._serviceBackend,this._throughHole);this._fileProcessing=new ObsidianFileProcessingService(this._serviceBackend,this._throughHole);this._replication=new ObsidianReplicationService(this._serviceBackend,this._throughHole);this._remote=new ObsidianRemoteService(this._serviceBackend,this._throughHole);this._conflict=new ObsidianConflictService(this._serviceBackend,this._throughHole);this._appLifecycle=new ObsidianAppLifecycleService(this._serviceBackend,this._throughHole);this._setting=new ObsidianSettingService(this._serviceBackend,this._throughHole);this._tweakValue=new ObsidianTweakValueService(this._serviceBackend,this._throughHole);this._vault=new ObsidianVaultService(this._serviceBackend,this._throughHole);this._test=new ObsidianTestService(this._serviceBackend,this._throughHole);this._plugin=plugin3}};ObsidianLiveSyncPlugin=class extends import_obsidian.Plugin{constructor(){super(...arguments);this._services=new ObsidianServiceHub(this);this.addOns=[new ConfigSync(this),new HiddenFileSync(this),new LocalDatabaseMaintenance(this),new P2PReplicator(this)];this.modules=[new ModuleLiveSyncMain(this),new ModuleExtraSyncObsidian(this,this),new ModuleDatabaseFileAccess(this),new ModulePouchDB(this),new ModuleConflictChecker(this),new ModuleLocalDatabaseObsidian(this),new ModuleReplicatorMinIO(this),new ModuleReplicatorCouchDB(this),new ModuleReplicator(this),new ModuleFileHandler(this),new ModuleConflictResolver(this),new ModuleRemoteGovernor(this),new ModuleTargetFilter(this),new ModulePeriodicProcess(this),new ModuleKeyValueDB(this),new ModuleInitializerFile(this),new ModuleObsidianAPI(this,this),new ModuleObsidianEvents(this,this),new ModuleFileAccessObsidian(this,this),new ModuleObsidianSettings(this,this),new ModuleResolvingMismatchedTweaks(this),new ModuleObsidianSettingsAsMarkdown(this,this),new ModuleObsidianSettingDialogue(this,this),new ModuleLog(this,this),new ModuleInputUIObsidian(this,this),new ModuleObsidianMenu(this,this),new ModuleRebuilder(this),new ModuleSetupObsidian(this,this),new ModuleObsidianDocumentHistory(this,this),new ModuleMigration(this),new ModuleRedFlag(this),new ModuleInteractiveConflictResolver(this,this),new ModuleObsidianGlobalHistory(this,this),new ModuleCheckRemoteSize(this,this),new ModuleDev(this,this),new ModuleReplicateTest(this,this),new ModuleIntegratedTest(this,this),new SetupManager(this,this)];this.requestCount=reactiveSource(0);this.responseCount=reactiveSource(0);this.totalQueued=reactiveSource(0);this.batched=reactiveSource(0);this.processing=reactiveSource(0);this.databaseQueueCount=reactiveSource(0);this.storageApplyingCount=reactiveSource(0);this.replicationResultCount=reactiveSource(0);this.conflictProcessQueueCount=reactiveSource(0);this.pendingFileEventCount=reactiveSource(0);this.processingFileEventCount=reactiveSource(0);this.replicationStat=reactiveSource({sent:0,arrived:0,maxPullSeq:0,maxPushSeq:0,lastSyncPullSeq:0,lastSyncPushSeq:0,syncStatus:"CLOSED"})}get services(){return this._services}getAddOn(cls){for(const addon of this.addOns)if(addon.constructor.name==cls)return addon}getModule(constructor){for(const module2 of this.modules)if(module2.constructor===constructor)return module2;throw new Error(`Module ${constructor} not found or not loaded.`)}getDatabase(){return this.localDatabase.localDatabase}getSettings(){return this.settings}onload(){this.services.appLifecycle.onLoad()}async saveSettings(){await this.services.setting.saveSettingData()}onunload(){this.services.appLifecycle.onAppUnload()}};
/* nosourcemap */