From 201d9f880b89ee7303217e3dc00a570095573aa9 Mon Sep 17 00:00:00 2001 From: DasOcko Date: Sun, 19 Apr 2026 12:11:26 +0200 Subject: [PATCH] vault backup: 2026-04-19 12:11:26 --- .gitignore | 5 +- Naturaale Zwanzig/.obsidian/app.json | 4 + Naturaale Zwanzig/.obsidian/appearance.json | 1 + .../.obsidian/community-plugins.json | 3 + Naturaale Zwanzig/.obsidian/core-plugins.json | 33 + Naturaale Zwanzig/.obsidian/graph.json | 22 + .../.obsidian/plugins/obsidian-git/data.json | 68 ++ .../.obsidian/plugins/obsidian-git/main.js | 452 +++++++++++ .../plugins/obsidian-git/manifest.json | 10 + .../.obsidian/plugins/obsidian-git/styles.css | 710 ++++++++++++++++++ .../plugins/obsidian-livesync/data.json | 161 ++++ .../plugins/obsidian-livesync/main.js | 19 + .../plugins/obsidian-livesync/manifest.json | 10 + .../plugins/obsidian-livesync/styles.css | 481 ++++++++++++ Naturaale Zwanzig/.obsidian/workspace.json | 248 ++++++ .../Gruppen/Myzenauten.md | 2 +- Naturaale Zwanzig/Orte/Der Kontinent.md | 4 +- Naturaale Zwanzig/Orte/Inseln.md | 2 +- .../{ => Orte/Siedlungen}/erste Stadt.md | 0 .../{ => Orte/Siedlungen}/zweite Stadt.md | 0 Naturaale Zwanzig/Orte/Wald.md | 1 - Naturaale Zwanzig/Orte/Wildnis.md | 19 + .../Die Vier Aspekte/Die vier Aspekte.md | 2 +- .../Phänomene/Die Vier Aspekte/Systematik.md | 2 +- Naturaale Zwanzig/Phänomene/Kataklysmus.md | 2 +- Naturaale Zwanzig/Phänomene/Labyrinth.md | 2 +- Naturaale Zwanzig/Phänomene/Myzel.md | 4 +- Naturaale Zwanzig/Phänomene/Pantheon.md | 2 +- 28 files changed, 2255 insertions(+), 14 deletions(-) create mode 100644 Naturaale Zwanzig/.obsidian/app.json create mode 100644 Naturaale Zwanzig/.obsidian/appearance.json create mode 100644 Naturaale Zwanzig/.obsidian/community-plugins.json create mode 100644 Naturaale Zwanzig/.obsidian/core-plugins.json create mode 100644 Naturaale Zwanzig/.obsidian/graph.json create mode 100644 Naturaale Zwanzig/.obsidian/plugins/obsidian-git/data.json create mode 100644 Naturaale Zwanzig/.obsidian/plugins/obsidian-git/main.js create mode 100644 Naturaale Zwanzig/.obsidian/plugins/obsidian-git/manifest.json create mode 100644 Naturaale Zwanzig/.obsidian/plugins/obsidian-git/styles.css create mode 100644 Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/data.json create mode 100644 Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/main.js create mode 100644 Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/manifest.json create mode 100644 Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/styles.css create mode 100644 Naturaale Zwanzig/.obsidian/workspace.json rename Naturaale Zwanzig/{ => Orte/Siedlungen}/erste Stadt.md (100%) rename Naturaale Zwanzig/{ => Orte/Siedlungen}/zweite Stadt.md (100%) delete mode 100644 Naturaale Zwanzig/Orte/Wald.md create mode 100644 Naturaale Zwanzig/Orte/Wildnis.md diff --git a/.gitignore b/.gitignore index bbedac9..cfa0938 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ -/Naturaale Zwanzig/.obsidian -/Naturaale Zwanzig/.trash \ No newline at end of file +/Naturaale Zwanzig/.trash + +/Naturaale Zwanzig/.obsidian \ No newline at end of file diff --git a/Naturaale Zwanzig/.obsidian/app.json b/Naturaale Zwanzig/.obsidian/app.json new file mode 100644 index 0000000..4d49ab3 --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/app.json @@ -0,0 +1,4 @@ +{ + "promptDelete": false, + "alwaysUpdateLinks": true +} \ No newline at end of file diff --git a/Naturaale Zwanzig/.obsidian/appearance.json b/Naturaale Zwanzig/.obsidian/appearance.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/appearance.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/Naturaale Zwanzig/.obsidian/community-plugins.json b/Naturaale Zwanzig/.obsidian/community-plugins.json new file mode 100644 index 0000000..d3f66fa --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/community-plugins.json @@ -0,0 +1,3 @@ +[ + "obsidian-git" +] \ No newline at end of file diff --git a/Naturaale Zwanzig/.obsidian/core-plugins.json b/Naturaale Zwanzig/.obsidian/core-plugins.json new file mode 100644 index 0000000..639b90d --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/core-plugins.json @@ -0,0 +1,33 @@ +{ + "file-explorer": true, + "global-search": true, + "switcher": true, + "graph": true, + "backlink": true, + "canvas": true, + "outgoing-link": true, + "tag-pane": true, + "footnotes": false, + "properties": true, + "page-preview": true, + "daily-notes": true, + "templates": true, + "note-composer": true, + "command-palette": true, + "slash-command": false, + "editor-status": true, + "bookmarks": true, + "markdown-importer": false, + "zk-prefixer": false, + "random-note": false, + "outline": true, + "word-count": true, + "slides": false, + "audio-recorder": false, + "workspaces": false, + "file-recovery": true, + "publish": false, + "sync": true, + "bases": true, + "webviewer": false +} \ No newline at end of file diff --git a/Naturaale Zwanzig/.obsidian/graph.json b/Naturaale Zwanzig/.obsidian/graph.json new file mode 100644 index 0000000..f84cfeb --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/graph.json @@ -0,0 +1,22 @@ +{ + "collapse-filter": true, + "search": "", + "showTags": false, + "showAttachments": false, + "hideUnresolved": false, + "showOrphans": true, + "collapse-color-groups": true, + "colorGroups": [], + "collapse-display": true, + "showArrow": false, + "textFadeMultiplier": 0, + "nodeSizeMultiplier": 1, + "lineSizeMultiplier": 1, + "collapse-forces": true, + "centerStrength": 0.518713248970312, + "repelStrength": 10, + "linkStrength": 1, + "linkDistance": 250, + "scale": 1.0238257875530357, + "close": true +} \ No newline at end of file diff --git a/Naturaale Zwanzig/.obsidian/plugins/obsidian-git/data.json b/Naturaale Zwanzig/.obsidian/plugins/obsidian-git/data.json new file mode 100644 index 0000000..4031f51 --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/plugins/obsidian-git/data.json @@ -0,0 +1,68 @@ +{ + "commitMessage": "vault backup: {{date}}", + "autoCommitMessage": "vault backup: {{date}}", + "commitMessageScript": "", + "commitDateFormat": "YYYY-MM-DD HH:mm:ss", + "autoSaveInterval": 0, + "autoPushInterval": 0, + "autoPullInterval": 0, + "autoPullOnBoot": false, + "autoCommitOnlyStaged": false, + "disablePush": false, + "pullBeforePush": true, + "disablePopups": false, + "showErrorNotices": true, + "disablePopupsForNoChanges": false, + "listChangedFilesInMessageBody": false, + "showStatusBar": true, + "updateSubmodules": false, + "syncMethod": "merge", + "mergeStrategy": "none", + "customMessageOnAutoBackup": false, + "autoBackupAfterFileChange": false, + "treeStructure": true, + "refreshSourceControl": true, + "basePath": "", + "differentIntervalCommitAndPush": false, + "changedFilesInStatusBar": false, + "showedMobileNotice": true, + "refreshSourceControlTimer": 7000, + "showBranchStatusBar": true, + "setLastSaveToLastCommit": false, + "submoduleRecurseCheckout": false, + "gitDir": "", + "showFileMenu": true, + "authorInHistoryView": "hide", + "dateInHistoryView": false, + "diffStyle": "split", + "hunks": { + "showSigns": false, + "hunkCommands": false, + "statusBar": "disabled" + }, + "lineAuthor": { + "show": false, + "followMovement": "inactive", + "authorDisplay": "initials", + "showCommitHash": false, + "dateTimeFormatOptions": "date", + "dateTimeFormatCustomString": "YYYY-MM-DD HH:mm", + "dateTimeTimezone": "viewer-local", + "coloringMaxAge": "1y", + "colorNew": { + "r": 255, + "g": 150, + "b": 150 + }, + "colorOld": { + "r": 120, + "g": 160, + "b": 255 + }, + "textColorCss": "var(--text-muted)", + "ignoreWhitespace": false, + "gutterSpacingFallbackLength": 5, + "lastShownAuthorDisplay": "initials", + "lastShownDateTimeFormatOptions": "date" + } +} \ No newline at end of file diff --git a/Naturaale Zwanzig/.obsidian/plugins/obsidian-git/main.js b/Naturaale Zwanzig/.obsidian/plugins/obsidian-git/main.js new file mode 100644 index 0000000..6e335cd --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/plugins/obsidian-git/main.js @@ -0,0 +1,452 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source visit the plugins github repository (https://github.com/denolehov/obsidian-git) +*/ + +var VD=Object.create;var bc=Object.defineProperty;var YD=Object.getOwnPropertyDescriptor;var XD=Object.getOwnPropertyNames;var ZD=Object.getPrototypeOf,KD=Object.prototype.hasOwnProperty;var Yb=t=>{throw TypeError(t)};var QD=(t,e,r)=>e in t?bc(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r;var JD=(t,e)=>()=>(t&&(e=t(t=0)),e);var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),eL=(t,e)=>{for(var r in e)bc(t,r,{get:e[r],enumerable:!0})},Xb=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of XD(e))!KD.call(t,i)&&i!==r&&bc(t,i,{get:()=>e[i],enumerable:!(n=YD(e,i))||n.enumerable});return t};var Ct=(t,e,r)=>(r=t!=null?VD(ZD(t)):{},Xb(e||!t||!t.__esModule?bc(r,"default",{value:t,enumerable:!0}):r,t)),tL=t=>Xb(bc({},"__esModule",{value:!0}),t);var qe=(t,e,r)=>QD(t,typeof e!="symbol"?e+"":e,r),Fm=(t,e,r)=>e.has(t)||Yb("Cannot "+r);var $=(t,e,r)=>(Fm(t,e,"read from private field"),r?r.call(t):e.get(t)),me=(t,e,r)=>e.has(t)?Yb("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,r),de=(t,e,r,n)=>(Fm(t,e,"write to private field"),n?n.call(t,r):e.set(t,r),r),wt=(t,e,r)=>(Fm(t,e,"access private method"),r);var Qb=I(Ff=>{"use strict";p();Ff.byteLength=nL;Ff.toByteArray=sL;Ff.fromByteArray=lL;var ri=[],fn=[],rL=typeof Uint8Array!="undefined"?Uint8Array:Array,Om="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(la=0,Zb=Om.length;la0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}function nL(t){var e=Kb(t),r=e[0],n=e[1];return(r+n)*3/4-n}function iL(t,e,r){return(e+r)*3/4-r}function sL(t){var e,r=Kb(t),n=r[0],i=r[1],s=new rL(iL(t,n,i)),a=0,o=i>0?n-4:n,l;for(l=0;l>16&255,s[a++]=e>>8&255,s[a++]=e&255;return i===2&&(e=fn[t.charCodeAt(l)]<<2|fn[t.charCodeAt(l+1)]>>4,s[a++]=e&255),i===1&&(e=fn[t.charCodeAt(l)]<<10|fn[t.charCodeAt(l+1)]<<4|fn[t.charCodeAt(l+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function aL(t){return ri[t>>18&63]+ri[t>>12&63]+ri[t>>6&63]+ri[t&63]}function oL(t,e,r){for(var n,i=[],s=e;so?o:a+s));return n===1?(e=t[r-1],i.push(ri[e>>2]+ri[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(ri[e>>10]+ri[e>>4&63]+ri[e<<2&63]+"=")),i.join("")}});var Jb=I(Mm=>{p();Mm.read=function(t,e,r,n,i){var s,a,o=i*8-n-1,l=(1<>1,u=-7,f=r?i-1:0,d=r?-1:1,h=t[e+f];for(f+=d,s=h&(1<<-u)-1,h>>=-u,u+=o;u>0;s=s*256+t[e+f],f+=d,u-=8);for(a=s&(1<<-u)-1,s>>=-u,u+=n;u>0;a=a*256+t[e+f],f+=d,u-=8);if(s===0)s=1-c;else{if(s===l)return a?NaN:(h?-1:1)*(1/0);a=a+Math.pow(2,n),s=s-c}return(h?-1:1)*a*Math.pow(2,s-n)};Mm.write=function(t,e,r,n,i,s){var a,o,l,c=s*8-i-1,u=(1<>1,d=i===23?Math.pow(2,-24)-Math.pow(2,-77):0,h=n?0:s-1,m=n?1:-1,g=e<0||e===0&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(o=isNaN(e)?1:0,a=u):(a=Math.floor(Math.log(e)/Math.LN2),e*(l=Math.pow(2,-a))<1&&(a--,l*=2),a+f>=1?e+=d/l:e+=d*Math.pow(2,1-f),e*l>=2&&(a++,l/=2),a+f>=u?(o=0,a=u):a+f>=1?(o=(e*l-1)*Math.pow(2,i),a=a+f):(o=e*Math.pow(2,f-1)*Math.pow(2,i),a=0));i>=8;t[r+h]=o&255,h+=m,o/=256,i-=8);for(a=a<0;t[r+h]=a&255,h+=m,a/=256,c-=8);t[r+h-m]|=g*128}});var qm=I(Co=>{"use strict";p();var Dm=Qb(),ko=Jb(),e_=typeof Symbol=="function"&&typeof Symbol.for=="function"?Symbol.for("nodejs.util.inspect.custom"):null;Co.Buffer=F;Co.SlowBuffer=pL;Co.INSPECT_MAX_BYTES=50;var Of=2147483647;Co.kMaxLength=Of;F.TYPED_ARRAY_SUPPORT=cL();!F.TYPED_ARRAY_SUPPORT&&typeof console!="undefined"&&typeof console.error=="function"&&console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support.");function cL(){try{let t=new Uint8Array(1),e={foo:function(){return 42}};return Object.setPrototypeOf(e,Uint8Array.prototype),Object.setPrototypeOf(t,e),t.foo()===42}catch(t){return!1}}Object.defineProperty(F.prototype,"parent",{enumerable:!0,get:function(){if(F.isBuffer(this))return this.buffer}});Object.defineProperty(F.prototype,"offset",{enumerable:!0,get:function(){if(F.isBuffer(this))return this.byteOffset}});function Bi(t){if(t>Of)throw new RangeError('The value "'+t+'" is invalid for option "size"');let e=new Uint8Array(t);return Object.setPrototypeOf(e,F.prototype),e}function F(t,e,r){if(typeof t=="number"){if(typeof e=="string")throw new TypeError('The "string" argument must be of type string. Received type number');return Hm(t)}return i_(t,e,r)}F.poolSize=8192;function i_(t,e,r){if(typeof t=="string")return fL(t,e);if(ArrayBuffer.isView(t))return dL(t);if(t==null)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t);if(ni(t,ArrayBuffer)||t&&ni(t.buffer,ArrayBuffer)||typeof SharedArrayBuffer!="undefined"&&(ni(t,SharedArrayBuffer)||t&&ni(t.buffer,SharedArrayBuffer)))return Nm(t,e,r);if(typeof t=="number")throw new TypeError('The "value" argument must not be of type number. Received type number');let n=t.valueOf&&t.valueOf();if(n!=null&&n!==t)return F.from(n,e,r);let i=hL(t);if(i)return i;if(typeof Symbol!="undefined"&&Symbol.toPrimitive!=null&&typeof t[Symbol.toPrimitive]=="function")return F.from(t[Symbol.toPrimitive]("string"),e,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof t)}F.from=function(t,e,r){return i_(t,e,r)};Object.setPrototypeOf(F.prototype,Uint8Array.prototype);Object.setPrototypeOf(F,Uint8Array);function s_(t){if(typeof t!="number")throw new TypeError('"size" argument must be of type number');if(t<0)throw new RangeError('The value "'+t+'" is invalid for option "size"')}function uL(t,e,r){return s_(t),t<=0?Bi(t):e!==void 0?typeof r=="string"?Bi(t).fill(e,r):Bi(t).fill(e):Bi(t)}F.alloc=function(t,e,r){return uL(t,e,r)};function Hm(t){return s_(t),Bi(t<0?0:Um(t)|0)}F.allocUnsafe=function(t){return Hm(t)};F.allocUnsafeSlow=function(t){return Hm(t)};function fL(t,e){if((typeof e!="string"||e==="")&&(e="utf8"),!F.isEncoding(e))throw new TypeError("Unknown encoding: "+e);let r=a_(t,e)|0,n=Bi(r),i=n.write(t,e);return i!==r&&(n=n.slice(0,i)),n}function Lm(t){let e=t.length<0?0:Um(t.length)|0,r=Bi(e);for(let n=0;n=Of)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+Of.toString(16)+" bytes");return t|0}function pL(t){return+t!=t&&(t=0),F.alloc(+t)}F.isBuffer=function(e){return e!=null&&e._isBuffer===!0&&e!==F.prototype};F.compare=function(e,r){if(ni(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),ni(r,Uint8Array)&&(r=F.from(r,r.offset,r.byteLength)),!F.isBuffer(e)||!F.isBuffer(r))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===r)return 0;let n=e.length,i=r.length;for(let s=0,a=Math.min(n,i);si.length?(F.isBuffer(a)||(a=F.from(a)),a.copy(i,s)):Uint8Array.prototype.set.call(i,a,s);else if(F.isBuffer(a))a.copy(i,s);else throw new TypeError('"list" argument must be an Array of Buffers');s+=a.length}return i};function a_(t,e){if(F.isBuffer(t))return t.length;if(ArrayBuffer.isView(t)||ni(t,ArrayBuffer))return t.byteLength;if(typeof t!="string")throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof t);let r=t.length,n=arguments.length>2&&arguments[2]===!0;if(!n&&r===0)return 0;let i=!1;for(;;)switch(e){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return Bm(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return r*2;case"hex":return r>>>1;case"base64":return m_(t).length;default:if(i)return n?-1:Bm(t).length;e=(""+e).toLowerCase(),i=!0}}F.byteLength=a_;function mL(t,e,r){let n=!1;if((e===void 0||e<0)&&(e=0),e>this.length||((r===void 0||r>this.length)&&(r=this.length),r<=0)||(r>>>=0,e>>>=0,r<=e))return"";for(t||(t="utf8");;)switch(t){case"hex":return kL(this,e,r);case"utf8":case"utf-8":return l_(this,e,r);case"ascii":return SL(this,e,r);case"latin1":case"binary":return EL(this,e,r);case"base64":return _L(this,e,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return AL(this,e,r);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}F.prototype._isBuffer=!0;function ca(t,e,r){let n=t[e];t[e]=t[r],t[r]=n}F.prototype.swap16=function(){let e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let r=0;rr&&(e+=" ... "),""};e_&&(F.prototype[e_]=F.prototype.inspect);F.prototype.compare=function(e,r,n,i,s){if(ni(e,Uint8Array)&&(e=F.from(e,e.offset,e.byteLength)),!F.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(r===void 0&&(r=0),n===void 0&&(n=e?e.length:0),i===void 0&&(i=0),s===void 0&&(s=this.length),r<0||n>e.length||i<0||s>this.length)throw new RangeError("out of range index");if(i>=s&&r>=n)return 0;if(i>=s)return-1;if(r>=n)return 1;if(r>>>=0,n>>>=0,i>>>=0,s>>>=0,this===e)return 0;let a=s-i,o=n-r,l=Math.min(a,o),c=this.slice(i,s),u=e.slice(r,n);for(let f=0;f2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,jm(r)&&(r=i?0:t.length-1),r<0&&(r=t.length+r),r>=t.length){if(i)return-1;r=t.length-1}else if(r<0)if(i)r=0;else return-1;if(typeof e=="string"&&(e=F.from(e,n)),F.isBuffer(e))return e.length===0?-1:t_(t,e,r,n,i);if(typeof e=="number")return e=e&255,typeof Uint8Array.prototype.indexOf=="function"?i?Uint8Array.prototype.indexOf.call(t,e,r):Uint8Array.prototype.lastIndexOf.call(t,e,r):t_(t,[e],r,n,i);throw new TypeError("val must be string, number or Buffer")}function t_(t,e,r,n,i){let s=1,a=t.length,o=e.length;if(n!==void 0&&(n=String(n).toLowerCase(),n==="ucs2"||n==="ucs-2"||n==="utf16le"||n==="utf-16le")){if(t.length<2||e.length<2)return-1;s=2,a/=2,o/=2,r/=2}function l(u,f){return s===1?u[f]:u.readUInt16BE(f*s)}let c;if(i){let u=-1;for(c=r;ca&&(r=a-o),c=r;c>=0;c--){let u=!0;for(let f=0;fi&&(n=i)):n=i;let s=e.length;n>s/2&&(n=s/2);let a;for(a=0;a>>0,isFinite(n)?(n=n>>>0,i===void 0&&(i="utf8")):(i=n,n=void 0);else throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");let s=this.length-r;if((n===void 0||n>s)&&(n=s),e.length>0&&(n<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let a=!1;for(;;)switch(i){case"hex":return gL(this,e,r,n);case"utf8":case"utf-8":return vL(this,e,r,n);case"ascii":case"latin1":case"binary":return wL(this,e,r,n);case"base64":return yL(this,e,r,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return bL(this,e,r,n);default:if(a)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),a=!0}};F.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};function _L(t,e,r){return e===0&&r===t.length?Dm.fromByteArray(t):Dm.fromByteArray(t.slice(e,r))}function l_(t,e,r){r=Math.min(t.length,r);let n=[],i=e;for(;i239?4:s>223?3:s>191?2:1;if(i+o<=r){let l,c,u,f;switch(o){case 1:s<128&&(a=s);break;case 2:l=t[i+1],(l&192)===128&&(f=(s&31)<<6|l&63,f>127&&(a=f));break;case 3:l=t[i+1],c=t[i+2],(l&192)===128&&(c&192)===128&&(f=(s&15)<<12|(l&63)<<6|c&63,f>2047&&(f<55296||f>57343)&&(a=f));break;case 4:l=t[i+1],c=t[i+2],u=t[i+3],(l&192)===128&&(c&192)===128&&(u&192)===128&&(f=(s&15)<<18|(l&63)<<12|(c&63)<<6|u&63,f>65535&&f<1114112&&(a=f))}}a===null?(a=65533,o=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|a&1023),n.push(a),i+=o}return xL(n)}var r_=4096;function xL(t){let e=t.length;if(e<=r_)return String.fromCharCode.apply(String,t);let r="",n=0;for(;nn)&&(r=n);let i="";for(let s=e;sn&&(e=n),r<0?(r+=n,r<0&&(r=0)):r>n&&(r=n),rr)throw new RangeError("Trying to access beyond buffer length")}F.prototype.readUintLE=F.prototype.readUIntLE=function(e,r,n){e=e>>>0,r=r>>>0,n||Mt(e,r,this.length);let i=this[e],s=1,a=0;for(;++a>>0,r=r>>>0,n||Mt(e,r,this.length);let i=this[e+--r],s=1;for(;r>0&&(s*=256);)i+=this[e+--r]*s;return i};F.prototype.readUint8=F.prototype.readUInt8=function(e,r){return e=e>>>0,r||Mt(e,1,this.length),this[e]};F.prototype.readUint16LE=F.prototype.readUInt16LE=function(e,r){return e=e>>>0,r||Mt(e,2,this.length),this[e]|this[e+1]<<8};F.prototype.readUint16BE=F.prototype.readUInt16BE=function(e,r){return e=e>>>0,r||Mt(e,2,this.length),this[e]<<8|this[e+1]};F.prototype.readUint32LE=F.prototype.readUInt32LE=function(e,r){return e=e>>>0,r||Mt(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+this[e+3]*16777216};F.prototype.readUint32BE=F.prototype.readUInt32BE=function(e,r){return e=e>>>0,r||Mt(e,4,this.length),this[e]*16777216+(this[e+1]<<16|this[e+2]<<8|this[e+3])};F.prototype.readBigUInt64LE=ys(function(e){e=e>>>0,Ao(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&_c(e,this.length-8);let i=r+this[++e]*2**8+this[++e]*2**16+this[++e]*2**24,s=this[++e]+this[++e]*2**8+this[++e]*2**16+n*2**24;return BigInt(i)+(BigInt(s)<>>0,Ao(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&_c(e,this.length-8);let i=r*2**24+this[++e]*2**16+this[++e]*2**8+this[++e],s=this[++e]*2**24+this[++e]*2**16+this[++e]*2**8+n;return(BigInt(i)<>>0,r=r>>>0,n||Mt(e,r,this.length);let i=this[e],s=1,a=0;for(;++a=s&&(i-=Math.pow(2,8*r)),i};F.prototype.readIntBE=function(e,r,n){e=e>>>0,r=r>>>0,n||Mt(e,r,this.length);let i=r,s=1,a=this[e+--i];for(;i>0&&(s*=256);)a+=this[e+--i]*s;return s*=128,a>=s&&(a-=Math.pow(2,8*r)),a};F.prototype.readInt8=function(e,r){return e=e>>>0,r||Mt(e,1,this.length),this[e]&128?(255-this[e]+1)*-1:this[e]};F.prototype.readInt16LE=function(e,r){e=e>>>0,r||Mt(e,2,this.length);let n=this[e]|this[e+1]<<8;return n&32768?n|4294901760:n};F.prototype.readInt16BE=function(e,r){e=e>>>0,r||Mt(e,2,this.length);let n=this[e+1]|this[e]<<8;return n&32768?n|4294901760:n};F.prototype.readInt32LE=function(e,r){return e=e>>>0,r||Mt(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24};F.prototype.readInt32BE=function(e,r){return e=e>>>0,r||Mt(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]};F.prototype.readBigInt64LE=ys(function(e){e=e>>>0,Ao(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&_c(e,this.length-8);let i=this[e+4]+this[e+5]*2**8+this[e+6]*2**16+(n<<24);return(BigInt(i)<>>0,Ao(e,"offset");let r=this[e],n=this[e+7];(r===void 0||n===void 0)&&_c(e,this.length-8);let i=(r<<24)+this[++e]*2**16+this[++e]*2**8+this[++e];return(BigInt(i)<>>0,r||Mt(e,4,this.length),ko.read(this,e,!0,23,4)};F.prototype.readFloatBE=function(e,r){return e=e>>>0,r||Mt(e,4,this.length),ko.read(this,e,!1,23,4)};F.prototype.readDoubleLE=function(e,r){return e=e>>>0,r||Mt(e,8,this.length),ko.read(this,e,!0,52,8)};F.prototype.readDoubleBE=function(e,r){return e=e>>>0,r||Mt(e,8,this.length),ko.read(this,e,!1,52,8)};function br(t,e,r,n,i,s){if(!F.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>i||et.length)throw new RangeError("Index out of range")}F.prototype.writeUintLE=F.prototype.writeUIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,n=n>>>0,!i){let o=Math.pow(2,8*n)-1;br(this,e,r,n,o,0)}let s=1,a=0;for(this[r]=e&255;++a>>0,n=n>>>0,!i){let o=Math.pow(2,8*n)-1;br(this,e,r,n,o,0)}let s=n-1,a=1;for(this[r+s]=e&255;--s>=0&&(a*=256);)this[r+s]=e/a&255;return r+n};F.prototype.writeUint8=F.prototype.writeUInt8=function(e,r,n){return e=+e,r=r>>>0,n||br(this,e,r,1,255,0),this[r]=e&255,r+1};F.prototype.writeUint16LE=F.prototype.writeUInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||br(this,e,r,2,65535,0),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeUint16BE=F.prototype.writeUInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||br(this,e,r,2,65535,0),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeUint32LE=F.prototype.writeUInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||br(this,e,r,4,4294967295,0),this[r+3]=e>>>24,this[r+2]=e>>>16,this[r+1]=e>>>8,this[r]=e&255,r+4};F.prototype.writeUint32BE=F.prototype.writeUInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||br(this,e,r,4,4294967295,0),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};function c_(t,e,r,n,i){p_(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s,s=s>>8,t[r++]=s;let a=Number(e>>BigInt(32)&BigInt(4294967295));return t[r++]=a,a=a>>8,t[r++]=a,a=a>>8,t[r++]=a,a=a>>8,t[r++]=a,r}function u_(t,e,r,n,i){p_(e,n,i,t,r,7);let s=Number(e&BigInt(4294967295));t[r+7]=s,s=s>>8,t[r+6]=s,s=s>>8,t[r+5]=s,s=s>>8,t[r+4]=s;let a=Number(e>>BigInt(32)&BigInt(4294967295));return t[r+3]=a,a=a>>8,t[r+2]=a,a=a>>8,t[r+1]=a,a=a>>8,t[r]=a,r+8}F.prototype.writeBigUInt64LE=ys(function(e,r=0){return c_(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});F.prototype.writeBigUInt64BE=ys(function(e,r=0){return u_(this,e,r,BigInt(0),BigInt("0xffffffffffffffff"))});F.prototype.writeIntLE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){let l=Math.pow(2,8*n-1);br(this,e,r,n,l-1,-l)}let s=0,a=1,o=0;for(this[r]=e&255;++s>0)-o&255;return r+n};F.prototype.writeIntBE=function(e,r,n,i){if(e=+e,r=r>>>0,!i){let l=Math.pow(2,8*n-1);br(this,e,r,n,l-1,-l)}let s=n-1,a=1,o=0;for(this[r+s]=e&255;--s>=0&&(a*=256);)e<0&&o===0&&this[r+s+1]!==0&&(o=1),this[r+s]=(e/a>>0)-o&255;return r+n};F.prototype.writeInt8=function(e,r,n){return e=+e,r=r>>>0,n||br(this,e,r,1,127,-128),e<0&&(e=255+e+1),this[r]=e&255,r+1};F.prototype.writeInt16LE=function(e,r,n){return e=+e,r=r>>>0,n||br(this,e,r,2,32767,-32768),this[r]=e&255,this[r+1]=e>>>8,r+2};F.prototype.writeInt16BE=function(e,r,n){return e=+e,r=r>>>0,n||br(this,e,r,2,32767,-32768),this[r]=e>>>8,this[r+1]=e&255,r+2};F.prototype.writeInt32LE=function(e,r,n){return e=+e,r=r>>>0,n||br(this,e,r,4,2147483647,-2147483648),this[r]=e&255,this[r+1]=e>>>8,this[r+2]=e>>>16,this[r+3]=e>>>24,r+4};F.prototype.writeInt32BE=function(e,r,n){return e=+e,r=r>>>0,n||br(this,e,r,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[r]=e>>>24,this[r+1]=e>>>16,this[r+2]=e>>>8,this[r+3]=e&255,r+4};F.prototype.writeBigInt64LE=ys(function(e,r=0){return c_(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});F.prototype.writeBigInt64BE=ys(function(e,r=0){return u_(this,e,r,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))});function f_(t,e,r,n,i,s){if(r+n>t.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function d_(t,e,r,n,i){return e=+e,r=r>>>0,i||f_(t,e,r,4,34028234663852886e22,-34028234663852886e22),ko.write(t,e,r,n,23,4),r+4}F.prototype.writeFloatLE=function(e,r,n){return d_(this,e,r,!0,n)};F.prototype.writeFloatBE=function(e,r,n){return d_(this,e,r,!1,n)};function h_(t,e,r,n,i){return e=+e,r=r>>>0,i||f_(t,e,r,8,17976931348623157e292,-17976931348623157e292),ko.write(t,e,r,n,52,8),r+8}F.prototype.writeDoubleLE=function(e,r,n){return h_(this,e,r,!0,n)};F.prototype.writeDoubleBE=function(e,r,n){return h_(this,e,r,!1,n)};F.prototype.copy=function(e,r,n,i){if(!F.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),!i&&i!==0&&(i=this.length),r>=e.length&&(r=e.length),r||(r=0),i>0&&i=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-r>>0,n=n===void 0?this.length:n>>>0,e||(e=0);let s;if(typeof e=="number")for(s=r;s2**32?i=n_(String(r)):typeof r=="bigint"&&(i=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(i=n_(i)),i+="n"),n+=` It must be ${e}. Received ${i}`,n},RangeError);function n_(t){let e="",r=t.length,n=t[0]==="-"?1:0;for(;r>=n+4;r-=3)e=`_${t.slice(r-3,r)}${e}`;return`${t.slice(0,r)}${e}`}function CL(t,e,r){Ao(e,"offset"),(t[e]===void 0||t[e+r]===void 0)&&_c(e,t.length-(r+1))}function p_(t,e,r,n,i,s){if(t>r||t3?e===0||e===BigInt(0)?o=`>= 0${a} and < 2${a} ** ${(s+1)*8}${a}`:o=`>= -(2${a} ** ${(s+1)*8-1}${a}) and < 2 ** ${(s+1)*8-1}${a}`:o=`>= ${e}${a} and <= ${r}${a}`,new Eo.ERR_OUT_OF_RANGE("value",o,t)}CL(n,i,s)}function Ao(t,e){if(typeof t!="number")throw new Eo.ERR_INVALID_ARG_TYPE(e,"number",t)}function _c(t,e,r){throw Math.floor(t)!==t?(Ao(t,r),new Eo.ERR_OUT_OF_RANGE(r||"offset","an integer",t)):e<0?new Eo.ERR_BUFFER_OUT_OF_BOUNDS:new Eo.ERR_OUT_OF_RANGE(r||"offset",`>= ${r?1:0} and <= ${e}`,t)}var TL=/[^+/0-9A-Za-z-_]/g;function PL(t){if(t=t.split("=")[0],t=t.trim().replace(TL,""),t.length<2)return"";for(;t.length%4!==0;)t=t+"=";return t}function Bm(t,e){e=e||1/0;let r,n=t.length,i=null,s=[];for(let a=0;a55295&&r<57344){if(!i){if(r>56319){(e-=3)>-1&&s.push(239,191,189);continue}else if(a+1===n){(e-=3)>-1&&s.push(239,191,189);continue}i=r;continue}if(r<56320){(e-=3)>-1&&s.push(239,191,189),i=r;continue}r=(i-55296<<10|r-56320)+65536}else i&&(e-=3)>-1&&s.push(239,191,189);if(i=null,r<128){if((e-=1)<0)break;s.push(r)}else if(r<2048){if((e-=2)<0)break;s.push(r>>6|192,r&63|128)}else if(r<65536){if((e-=3)<0)break;s.push(r>>12|224,r>>6&63|128,r&63|128)}else if(r<1114112){if((e-=4)<0)break;s.push(r>>18|240,r>>12&63|128,r>>6&63|128,r&63|128)}else throw new Error("Invalid code point")}return s}function RL(t){let e=[];for(let r=0;r>8,i=r%256,s.push(i),s.push(n);return s}function m_(t){return Dm.toByteArray(PL(t))}function Mf(t,e,r,n){let i;for(i=0;i=e.length||i>=t.length);++i)e[i+r]=t[i];return i}function ni(t,e){return t instanceof e||t!=null&&t.constructor!=null&&t.constructor.name!=null&&t.constructor.name===e.name}function jm(t){return t!==t}var IL=function(){let t="0123456789abcdef",e=new Array(256);for(let r=0;r<16;++r){let n=r*16;for(let i=0;i<16;++i)e[n+i]=t[r]+t[i]}return e}();function ys(t){return typeof BigInt=="undefined"?FL:t}function FL(){throw new Error("BigInt not supported")}});var g_,Wm,Buffer,p=JD(()=>{g_=require("obsidian");g_.Platform.isMobileApp?Wm=qm().Buffer:Wm=global.Buffer;Buffer=Wm});var w_=I((Z7,v_)=>{"use strict";p();var Vr=function(t){if(t=t||{},this.Promise=t.Promise||Promise,this.queues=Object.create(null),this.domainReentrant=t.domainReentrant||!1,this.domainReentrant){if(typeof process=="undefined"||typeof process.domain=="undefined")throw new Error("Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, use a NodeJS version that still implements Domain, or install a browser polyfill.");this.domains=Object.create(null)}this.timeout=t.timeout||Vr.DEFAULT_TIMEOUT,this.maxOccupationTime=t.maxOccupationTime||Vr.DEFAULT_MAX_OCCUPATION_TIME,this.maxExecutionTime=t.maxExecutionTime||Vr.DEFAULT_MAX_EXECUTION_TIME,t.maxPending===1/0||Number.isInteger(t.maxPending)&&t.maxPending>=0?this.maxPending=t.maxPending:this.maxPending=Vr.DEFAULT_MAX_PENDING};Vr.DEFAULT_TIMEOUT=0;Vr.DEFAULT_MAX_OCCUPATION_TIME=0;Vr.DEFAULT_MAX_EXECUTION_TIME=0;Vr.DEFAULT_MAX_PENDING=1e3;Vr.prototype.acquire=function(t,e,r,n){if(Array.isArray(t))return this._acquireBatch(t,e,r,n);if(typeof e!="function")throw new Error("You must pass a function to execute");var i=null,s=null,a=null;typeof r!="function"&&(n=r,r=null,a=new this.Promise(function(b,k){i=b,s=k})),n=n||{};var o=!1,l=null,c=null,u=null,f=this,d=function(b,k,x){c&&(clearTimeout(c),c=null),u&&(clearTimeout(u),u=null),b&&(f.queues[t]&&f.queues[t].length===0&&delete f.queues[t],f.domainReentrant&&delete f.domains[t]),o||(a?k?s(k):i(x):typeof r=="function"&&r(k,x),o=!0),b&&f.queues[t]&&f.queues[t].length>0&&f.queues[t].shift()()},h=function(b){if(o)return d(b);l&&(clearTimeout(l),l=null),f.domainReentrant&&b&&(f.domains[t]=process.domain);var k=n.maxExecutionTime||f.maxExecutionTime;if(k&&(u=setTimeout(function(){f.queues[t]&&d(b,new Error("Maximum execution time is exceeded "+t))},k)),e.length===1){var x=!1;try{e(function(E,A){x||(x=!0,d(b,E,A))})}catch(E){x||(x=!0,d(b,E))}}else f._promiseTry(function(){return e()}).then(function(E){d(b,void 0,E)},function(E){d(b,E)})};f.domainReentrant&&process.domain&&(h=process.domain.bind(h));var m=n.maxPending||f.maxPending;if(!f.queues[t])f.queues[t]=[],h(!0);else if(f.domainReentrant&&process.domain&&process.domain===f.domains[t])h(!1);else if(f.queues[t].length>=m)d(!1,new Error("Too many pending tasks in queue "+t));else{var g=function(){h(!0)};n.skipQueue?f.queues[t].unshift(g):f.queues[t].push(g);var v=n.timeout||f.timeout;v&&(l=setTimeout(function(){l=null,d(!1,new Error("async-lock timed out in queue "+t))},v))}var w=n.maxOccupationTime||f.maxOccupationTime;if(w&&(c=setTimeout(function(){f.queues[t]&&d(!1,new Error("Maximum occupation time is exceeded in queue "+t))},w)),a)return a};Vr.prototype._acquireBatch=function(t,e,r,n){typeof r!="function"&&(n=r,r=null);var i=this,s=function(o,l){return function(c){i.acquire(o,l,c,n)}},a=t.reduceRight(function(o,l){return s(l,o)},e);if(typeof r=="function")a(r);else return new this.Promise(function(o,l){a.length===1?a(function(c,u){c?l(c):o(u)}):o(a())})};Vr.prototype.isBusy=function(t){return t?!!this.queues[t]:Object.keys(this.queues).length>0};Vr.prototype._promiseTry=function(t){try{return this.Promise.resolve(t())}catch(e){return this.Promise.reject(e)}};v_.exports=Vr});var b_=I((Q7,y_)=>{"use strict";p();y_.exports=w_()});var __=I((eY,zm)=>{p();typeof Object.create=="function"?zm.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:zm.exports=function(e,r){if(r){e.super_=r;var n=function(){};n.prototype=r.prototype,e.prototype=new n,e.prototype.constructor=e}}});var Lf=I((Vm,S_)=>{p();var Df=qm(),ii=Df.Buffer;function x_(t,e){for(var r in t)e[r]=t[r]}ii.from&&ii.alloc&&ii.allocUnsafe&&ii.allocUnsafeSlow?S_.exports=Df:(x_(Df,Vm),Vm.Buffer=ua);function ua(t,e,r){return ii(t,e,r)}ua.prototype=Object.create(ii.prototype);x_(ii,ua);ua.from=function(t,e,r){if(typeof t=="number")throw new TypeError("Argument must not be a number");return ii(t,e,r)};ua.alloc=function(t,e,r){if(typeof t!="number")throw new TypeError("Argument must be a number");var n=ii(t);return e!==void 0?typeof r=="string"?n.fill(e,r):n.fill(e):n.fill(0),n};ua.allocUnsafe=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return ii(t)};ua.allocUnsafeSlow=function(t){if(typeof t!="number")throw new TypeError("Argument must be a number");return Df.SlowBuffer(t)}});var Nf=I((nY,E_)=>{p();var OL={}.toString;E_.exports=Array.isArray||function(t){return OL.call(t)=="[object Array]"}});var _r=I((sY,k_)=>{"use strict";p();k_.exports=TypeError});var Bf=I((oY,A_)=>{"use strict";p();A_.exports=Object});var Ym=I((cY,C_)=>{"use strict";p();C_.exports=Error});var P_=I((fY,T_)=>{"use strict";p();T_.exports=EvalError});var $_=I((hY,R_)=>{"use strict";p();R_.exports=RangeError});var F_=I((mY,I_)=>{"use strict";p();I_.exports=ReferenceError});var Hf=I((vY,O_)=>{"use strict";p();O_.exports=SyntaxError});var D_=I((yY,M_)=>{"use strict";p();M_.exports=URIError});var N_=I((_Y,L_)=>{"use strict";p();L_.exports=Math.abs});var H_=I((SY,B_)=>{"use strict";p();B_.exports=Math.floor});var G_=I((kY,U_)=>{"use strict";p();U_.exports=Math.max});var q_=I((CY,j_)=>{"use strict";p();j_.exports=Math.min});var z_=I((PY,W_)=>{"use strict";p();W_.exports=Math.pow});var Y_=I(($Y,V_)=>{"use strict";p();V_.exports=Math.round});var Z_=I((FY,X_)=>{"use strict";p();X_.exports=Number.isNaN||function(e){return e!==e}});var Q_=I((MY,K_)=>{"use strict";p();var ML=Z_();K_.exports=function(e){return ML(e)||e===0?e:e<0?-1:1}});var ex=I((LY,J_)=>{"use strict";p();J_.exports=Object.getOwnPropertyDescriptor});var bs=I((BY,tx)=>{"use strict";p();var Uf=ex();if(Uf)try{Uf([],"length")}catch(t){Uf=null}tx.exports=Uf});var xc=I((UY,rx)=>{"use strict";p();var Gf=Object.defineProperty||!1;if(Gf)try{Gf({},"a",{value:1})}catch(t){Gf=!1}rx.exports=Gf});var Sc=I((jY,nx)=>{"use strict";p();nx.exports=function(){if(typeof Symbol!="function"||typeof Object.getOwnPropertySymbols!="function")return!1;if(typeof Symbol.iterator=="symbol")return!0;var e={},r=Symbol("test"),n=Object(r);if(typeof r=="string"||Object.prototype.toString.call(r)!=="[object Symbol]"||Object.prototype.toString.call(n)!=="[object Symbol]")return!1;var i=42;e[r]=i;for(var s in e)return!1;if(typeof Object.keys=="function"&&Object.keys(e).length!==0||typeof Object.getOwnPropertyNames=="function"&&Object.getOwnPropertyNames(e).length!==0)return!1;var a=Object.getOwnPropertySymbols(e);if(a.length!==1||a[0]!==r||!Object.prototype.propertyIsEnumerable.call(e,r))return!1;if(typeof Object.getOwnPropertyDescriptor=="function"){var o=Object.getOwnPropertyDescriptor(e,r);if(o.value!==i||o.enumerable!==!0)return!1}return!0}});var jf=I((WY,sx)=>{"use strict";p();var ix=typeof Symbol!="undefined"&&Symbol,DL=Sc();sx.exports=function(){return typeof ix!="function"||typeof Symbol!="function"||typeof ix("foo")!="symbol"||typeof Symbol("bar")!="symbol"?!1:DL()}});var Xm=I((VY,ax)=>{"use strict";p();ax.exports=typeof Reflect!="undefined"&&Reflect.getPrototypeOf||null});var Zm=I((XY,ox)=>{"use strict";p();var LL=Bf();ox.exports=LL.getPrototypeOf||null});var ux=I((KY,cx)=>{"use strict";p();var NL="Function.prototype.bind called on incompatible ",BL=Object.prototype.toString,HL=Math.max,UL="[object Function]",lx=function(e,r){for(var n=[],i=0;i{"use strict";p();var qL=ux();fx.exports=Function.prototype.bind||qL});var qf=I((tX,dx)=>{"use strict";p();dx.exports=Function.prototype.call});var Wf=I((nX,hx)=>{"use strict";p();hx.exports=Function.prototype.apply});var mx=I((sX,px)=>{"use strict";p();px.exports=typeof Reflect!="undefined"&&Reflect&&Reflect.apply});var Km=I((oX,gx)=>{"use strict";p();var WL=To(),zL=Wf(),VL=qf(),YL=mx();gx.exports=YL||WL.call(VL,zL)});var zf=I((cX,vx)=>{"use strict";p();var XL=To(),ZL=_r(),KL=qf(),QL=Km();vx.exports=function(e){if(e.length<1||typeof e[0]!="function")throw new ZL("a function is required");return QL(XL,KL,e)}});var Sx=I((fX,xx)=>{"use strict";p();var JL=zf(),wx=bs(),bx;try{bx=[].__proto__===Array.prototype}catch(t){if(!t||typeof t!="object"||!("code"in t)||t.code!=="ERR_PROTO_ACCESS")throw t}var Qm=!!bx&&wx&&wx(Object.prototype,"__proto__"),_x=Object,yx=_x.getPrototypeOf;xx.exports=Qm&&typeof Qm.get=="function"?JL([Qm.get]):typeof yx=="function"?function(e){return yx(e==null?e:_x(e))}:!1});var Vf=I((hX,Cx)=>{"use strict";p();var Ex=Xm(),kx=Zm(),Ax=Sx();Cx.exports=Ex?function(e){return Ex(e)}:kx?function(e){if(!e||typeof e!="object"&&typeof e!="function")throw new TypeError("getProto: not an object");return kx(e)}:Ax?function(e){return Ax(e)}:null});var Yf=I((mX,Tx)=>{"use strict";p();var eN=Function.prototype.call,tN=Object.prototype.hasOwnProperty,rN=To();Tx.exports=rN.call(eN,tN)});var si=I((vX,Ox)=>{"use strict";p();var Ee,nN=Bf(),iN=Ym(),sN=P_(),aN=$_(),oN=F_(),Io=Hf(),$o=_r(),lN=D_(),cN=N_(),uN=H_(),fN=G_(),dN=q_(),hN=z_(),pN=Y_(),mN=Q_(),Ix=Function,Jm=function(t){try{return Ix('"use strict"; return ('+t+").constructor;")()}catch(e){}},Ec=bs(),gN=xc(),eg=function(){throw new $o},vN=Ec?function(){try{return arguments.callee,eg}catch(t){try{return Ec(arguments,"callee").get}catch(e){return eg}}}():eg,Po=jf()(),Dt=Vf(),wN=Zm(),yN=Xm(),Fx=Wf(),kc=qf(),Ro={},bN=typeof Uint8Array=="undefined"||!Dt?Ee:Dt(Uint8Array),fa={__proto__:null,"%AggregateError%":typeof AggregateError=="undefined"?Ee:AggregateError,"%Array%":Array,"%ArrayBuffer%":typeof ArrayBuffer=="undefined"?Ee:ArrayBuffer,"%ArrayIteratorPrototype%":Po&&Dt?Dt([][Symbol.iterator]()):Ee,"%AsyncFromSyncIteratorPrototype%":Ee,"%AsyncFunction%":Ro,"%AsyncGenerator%":Ro,"%AsyncGeneratorFunction%":Ro,"%AsyncIteratorPrototype%":Ro,"%Atomics%":typeof Atomics=="undefined"?Ee:Atomics,"%BigInt%":typeof BigInt=="undefined"?Ee:BigInt,"%BigInt64Array%":typeof BigInt64Array=="undefined"?Ee:BigInt64Array,"%BigUint64Array%":typeof BigUint64Array=="undefined"?Ee:BigUint64Array,"%Boolean%":Boolean,"%DataView%":typeof DataView=="undefined"?Ee:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":iN,"%eval%":eval,"%EvalError%":sN,"%Float16Array%":typeof Float16Array=="undefined"?Ee:Float16Array,"%Float32Array%":typeof Float32Array=="undefined"?Ee:Float32Array,"%Float64Array%":typeof Float64Array=="undefined"?Ee:Float64Array,"%FinalizationRegistry%":typeof FinalizationRegistry=="undefined"?Ee:FinalizationRegistry,"%Function%":Ix,"%GeneratorFunction%":Ro,"%Int8Array%":typeof Int8Array=="undefined"?Ee:Int8Array,"%Int16Array%":typeof Int16Array=="undefined"?Ee:Int16Array,"%Int32Array%":typeof Int32Array=="undefined"?Ee:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":Po&&Dt?Dt(Dt([][Symbol.iterator]())):Ee,"%JSON%":typeof JSON=="object"?JSON:Ee,"%Map%":typeof Map=="undefined"?Ee:Map,"%MapIteratorPrototype%":typeof Map=="undefined"||!Po||!Dt?Ee:Dt(new Map()[Symbol.iterator]()),"%Math%":Math,"%Number%":Number,"%Object%":nN,"%Object.getOwnPropertyDescriptor%":Ec,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":typeof Promise=="undefined"?Ee:Promise,"%Proxy%":typeof Proxy=="undefined"?Ee:Proxy,"%RangeError%":aN,"%ReferenceError%":oN,"%Reflect%":typeof Reflect=="undefined"?Ee:Reflect,"%RegExp%":RegExp,"%Set%":typeof Set=="undefined"?Ee:Set,"%SetIteratorPrototype%":typeof Set=="undefined"||!Po||!Dt?Ee:Dt(new Set()[Symbol.iterator]()),"%SharedArrayBuffer%":typeof SharedArrayBuffer=="undefined"?Ee:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":Po&&Dt?Dt(""[Symbol.iterator]()):Ee,"%Symbol%":Po?Symbol:Ee,"%SyntaxError%":Io,"%ThrowTypeError%":vN,"%TypedArray%":bN,"%TypeError%":$o,"%Uint8Array%":typeof Uint8Array=="undefined"?Ee:Uint8Array,"%Uint8ClampedArray%":typeof Uint8ClampedArray=="undefined"?Ee:Uint8ClampedArray,"%Uint16Array%":typeof Uint16Array=="undefined"?Ee:Uint16Array,"%Uint32Array%":typeof Uint32Array=="undefined"?Ee:Uint32Array,"%URIError%":lN,"%WeakMap%":typeof WeakMap=="undefined"?Ee:WeakMap,"%WeakRef%":typeof WeakRef=="undefined"?Ee:WeakRef,"%WeakSet%":typeof WeakSet=="undefined"?Ee:WeakSet,"%Function.prototype.call%":kc,"%Function.prototype.apply%":Fx,"%Object.defineProperty%":gN,"%Object.getPrototypeOf%":wN,"%Math.abs%":cN,"%Math.floor%":uN,"%Math.max%":fN,"%Math.min%":dN,"%Math.pow%":hN,"%Math.round%":pN,"%Math.sign%":mN,"%Reflect.getPrototypeOf%":yN};if(Dt)try{null.error}catch(t){Px=Dt(Dt(t)),fa["%Error.prototype%"]=Px}var Px,_N=function t(e){var r;if(e==="%AsyncFunction%")r=Jm("async function () {}");else if(e==="%GeneratorFunction%")r=Jm("function* () {}");else if(e==="%AsyncGeneratorFunction%")r=Jm("async function* () {}");else if(e==="%AsyncGenerator%"){var n=t("%AsyncGeneratorFunction%");n&&(r=n.prototype)}else if(e==="%AsyncIteratorPrototype%"){var i=t("%AsyncGenerator%");i&&Dt&&(r=Dt(i.prototype))}return fa[e]=r,r},Rx={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},Ac=To(),Xf=Yf(),xN=Ac.call(kc,Array.prototype.concat),SN=Ac.call(Fx,Array.prototype.splice),$x=Ac.call(kc,String.prototype.replace),Zf=Ac.call(kc,String.prototype.slice),EN=Ac.call(kc,RegExp.prototype.exec),kN=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,AN=/\\(\\)?/g,CN=function(e){var r=Zf(e,0,1),n=Zf(e,-1);if(r==="%"&&n!=="%")throw new Io("invalid intrinsic syntax, expected closing `%`");if(n==="%"&&r!=="%")throw new Io("invalid intrinsic syntax, expected opening `%`");var i=[];return $x(e,kN,function(s,a,o,l){i[i.length]=o?$x(l,AN,"$1"):a||s}),i},TN=function(e,r){var n=e,i;if(Xf(Rx,n)&&(i=Rx[n],n="%"+i[0]+"%"),Xf(fa,n)){var s=fa[n];if(s===Ro&&(s=_N(n)),typeof s=="undefined"&&!r)throw new $o("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:i,name:n,value:s}}throw new Io("intrinsic "+e+" does not exist!")};Ox.exports=function(e,r){if(typeof e!="string"||e.length===0)throw new $o("intrinsic name must be a non-empty string");if(arguments.length>1&&typeof r!="boolean")throw new $o('"allowMissing" argument must be a boolean');if(EN(/^%?[^%]*%?$/,e)===null)throw new Io("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=CN(e),i=n.length>0?n[0]:"",s=TN("%"+i+"%",r),a=s.name,o=s.value,l=!1,c=s.alias;c&&(i=c[0],SN(n,xN([0,1],c)));for(var u=1,f=!0;u=n.length){var g=Ec(o,d);f=!!g,f&&"get"in g&&!("originalValue"in g.get)?o=g.get:o=o[d]}else f=Xf(o,d),o=o[d];f&&!l&&(fa[a]=o)}}return o}});var Lt=I((yX,Lx)=>{"use strict";p();var Mx=si(),Dx=zf(),PN=Dx([Mx("%String.prototype.indexOf%")]);Lx.exports=function(e,r){var n=Mx(e,!!r);return typeof n=="function"&&PN(e,".prototype.")>-1?Dx([n]):n}});var Ux=I((_X,Hx)=>{"use strict";p();var Bx=Function.prototype.toString,Fo=typeof Reflect=="object"&&Reflect!==null&&Reflect.apply,rg,Kf;if(typeof Fo=="function"&&typeof Object.defineProperty=="function")try{rg=Object.defineProperty({},"length",{get:function(){throw Kf}}),Kf={},Fo(function(){throw 42},null,rg)}catch(t){t!==Kf&&(Fo=null)}else Fo=null;var RN=/^\s*class\b/,ng=function(e){try{var r=Bx.call(e);return RN.test(r)}catch(n){return!1}},tg=function(e){try{return ng(e)?!1:(Bx.call(e),!0)}catch(r){return!1}},Qf=Object.prototype.toString,$N="[object Object]",IN="[object Function]",FN="[object GeneratorFunction]",ON="[object HTMLAllCollection]",MN="[object HTML document.all class]",DN="[object HTMLCollection]",LN=typeof Symbol=="function"&&!!Symbol.toStringTag,NN=!(0 in[,]),ig=function(){return!1};typeof document=="object"&&(Nx=document.all,Qf.call(Nx)===Qf.call(document.all)&&(ig=function(e){if((NN||!e)&&(typeof e=="undefined"||typeof e=="object"))try{var r=Qf.call(e);return(r===ON||r===MN||r===DN||r===$N)&&e("")==null}catch(n){}return!1}));var Nx;Hx.exports=Fo?function(e){if(ig(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;try{Fo(e,null,rg)}catch(r){if(r!==Kf)return!1}return!ng(e)&&tg(e)}:function(e){if(ig(e))return!0;if(!e||typeof e!="function"&&typeof e!="object")return!1;if(LN)return tg(e);if(ng(e))return!1;var r=Qf.call(e);return r!==IN&&r!==FN&&!/^\[object HTML/.test(r)?!1:tg(e)}});var qx=I((SX,jx)=>{"use strict";p();var BN=Ux(),HN=Object.prototype.toString,Gx=Object.prototype.hasOwnProperty,UN=function(e,r,n){for(var i=0,s=e.length;i=3&&(i=n),qN(e)?UN(e,r,i):typeof e=="string"?GN(e,r,i):jN(e,r,i)}});var zx=I((kX,Wx)=>{"use strict";p();Wx.exports=["Float16Array","Float32Array","Float64Array","Int8Array","Int16Array","Int32Array","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array"]});var Yx=I((CX,Vx)=>{"use strict";p();var sg=zx(),WN=typeof globalThis=="undefined"?global:globalThis;Vx.exports=function(){for(var e=[],r=0;r{"use strict";p();var Xx=xc(),zN=Hf(),Oo=_r(),Zx=bs();Kx.exports=function(e,r,n){if(!e||typeof e!="object"&&typeof e!="function")throw new Oo("`obj` must be an object or a function`");if(typeof r!="string"&&typeof r!="symbol")throw new Oo("`property` must be a string or a symbol`");if(arguments.length>3&&typeof arguments[3]!="boolean"&&arguments[3]!==null)throw new Oo("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&typeof arguments[4]!="boolean"&&arguments[4]!==null)throw new Oo("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&typeof arguments[5]!="boolean"&&arguments[5]!==null)throw new Oo("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&typeof arguments[6]!="boolean")throw new Oo("`loose`, if provided, must be a boolean");var i=arguments.length>3?arguments[3]:null,s=arguments.length>4?arguments[4]:null,a=arguments.length>5?arguments[5]:null,o=arguments.length>6?arguments[6]:!1,l=!!Zx&&Zx(e,r);if(Xx)Xx(e,r,{configurable:a===null&&l?l.configurable:!a,enumerable:i===null&&l?l.enumerable:!i,value:n,writable:s===null&&l?l.writable:!s});else if(o||!i&&!s&&!a)e[r]=n;else throw new zN("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.")}});var td=I(($X,Jx)=>{"use strict";p();var ag=xc(),Qx=function(){return!!ag};Qx.hasArrayLengthDefineBug=function(){if(!ag)return null;try{return ag([],"length",{value:1}).length!==1}catch(e){return!0}};Jx.exports=Qx});var i1=I((FX,n1)=>{"use strict";p();var VN=si(),e1=Jf(),YN=td()(),t1=bs(),r1=_r(),XN=VN("%Math.floor%");n1.exports=function(e,r){if(typeof e!="function")throw new r1("`fn` is not a function");if(typeof r!="number"||r<0||r>4294967295||XN(r)!==r)throw new r1("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],i=!0,s=!0;if("length"in e&&t1){var a=t1(e,"length");a&&!a.configurable&&(i=!1),a&&!a.writable&&(s=!1)}return(i||s||!n)&&(YN?e1(e,"length",r,!0,!0):e1(e,"length",r)),e}});var a1=I((MX,s1)=>{"use strict";p();var ZN=To(),KN=Wf(),QN=Km();s1.exports=function(){return QN(ZN,KN,arguments)}});var da=I((LX,rd)=>{"use strict";p();var JN=i1(),o1=xc(),eB=zf(),l1=a1();rd.exports=function(e){var r=eB(arguments),n=e.length-(arguments.length-1);return JN(r,1+(n>0?n:0),!0)};o1?o1(rd.exports,"apply",{value:l1}):rd.exports.apply=l1});var _s=I((BX,c1)=>{"use strict";p();var tB=Sc();c1.exports=function(){return tB()&&!!Symbol.toStringTag}});var ug=I((UX,h1)=>{"use strict";p();var sd=qx(),rB=Yx(),u1=da(),lg=Lt(),id=bs(),nd=Vf(),nB=lg("Object.prototype.toString"),d1=_s()(),f1=typeof globalThis=="undefined"?global:globalThis,og=rB(),cg=lg("String.prototype.slice"),iB=lg("Array.prototype.indexOf",!0)||function(e,r){for(var n=0;n-1?r:r!=="Object"?!1:aB(e)}return id?sB(e):null}});var m1=I((jX,p1)=>{"use strict";p();var oB=ug();p1.exports=function(e){return!!oB(e)}});var v1=I((WX,g1)=>{"use strict";p();var lB=_r(),cB=Lt(),uB=cB("TypedArray.prototype.buffer",!0),fB=m1();g1.exports=uB||function(e){if(!fB(e))throw new lB("Not a Typed Array");return e.buffer}});var b1=I((VX,y1)=>{"use strict";p();var In=Lf().Buffer,dB=Nf(),hB=v1(),pB=ArrayBuffer.isView||function(e){try{return hB(e),!0}catch(r){return!1}},mB=typeof Uint8Array!="undefined",w1=typeof ArrayBuffer!="undefined"&&typeof Uint8Array!="undefined",gB=w1&&(In.prototype instanceof Uint8Array||In.TYPED_ARRAY_SUPPORT);y1.exports=function(e,r){if(In.isBuffer(e))return e.constructor&&!("isBuffer"in e)?In.from(e):e;if(typeof e=="string")return In.from(e,r);if(w1&&pB(e)){if(e.byteLength===0)return In.alloc(0);if(gB){var n=In.from(e.buffer,e.byteOffset,e.byteLength);if(n.byteLength===e.byteLength)return n}var i=e instanceof Uint8Array?e:new Uint8Array(e.buffer,e.byteOffset,e.byteLength),s=In.from(i);if(s.length===e.byteLength)return s}if(mB&&e instanceof Uint8Array)return In.from(e);var a=dB(e);if(a)for(var o=0;o255||~~l!==l)throw new RangeError("Array items must be numbers in the range 0-255.")}if(a||In.isBuffer(e)&&e.constructor&&typeof e.constructor.isBuffer=="function"&&e.constructor.isBuffer(e))return In.from(e);throw new TypeError('The "data" argument must be a string, an Array, a Buffer, a Uint8Array, or a DataView.')}});var x1=I((XX,_1)=>{"use strict";p();var vB=Lf().Buffer,wB=b1();function od(t,e){this._block=vB.alloc(t),this._finalSize=e,this._blockSize=t,this._len=0}od.prototype.update=function(t,e){t=wB(t,e||"utf8");for(var r=this._block,n=this._blockSize,i=t.length,s=this._len,a=0;a=this._finalSize&&(this._update(this._block),this._block.fill(0));var r=this._len*8;if(r<=4294967295)this._block.writeUInt32BE(r,this._blockSize-4);else{var n=(r&4294967295)>>>0,i=(r-n)/4294967296;this._block.writeUInt32BE(i,this._blockSize-8),this._block.writeUInt32BE(n,this._blockSize-4)}this._update(this._block);var s=this._hash();return t?s.toString(t):s};od.prototype._update=function(){throw new Error("_update must be implemented by subclass")};_1.exports=od});var k1=I((KX,E1)=>{"use strict";p();var yB=__(),S1=x1(),bB=Lf().Buffer,_B=[1518500249,1859775393,-1894007588,-899497514],xB=new Array(80);function Cc(){this.init(),this._w=xB,S1.call(this,64,56)}yB(Cc,S1);Cc.prototype.init=function(){return this._a=1732584193,this._b=4023233417,this._c=2562383102,this._d=271733878,this._e=3285377520,this};function SB(t){return t<<1|t>>>31}function EB(t){return t<<5|t>>>27}function kB(t){return t<<30|t>>>2}function AB(t,e,r,n){return t===0?e&r|~e&n:t===2?e&r|e&n|r&n:e^r^n}Cc.prototype._update=function(t){for(var e=this._w,r=this._a|0,n=this._b|0,i=this._c|0,s=this._d|0,a=this._e|0,o=0;o<16;++o)e[o]=t.readInt32BE(o*4);for(;o<80;++o)e[o]=SB(e[o-3]^e[o-8]^e[o-14]^e[o-16]);for(var l=0;l<80;++l){var c=~~(l/20),u=EB(r)+AB(c,n,i,s)+a+e[l]+_B[c]|0;a=s,s=i,i=kB(n),n=r,r=u}this._a=r+this._a|0,this._b=n+this._b|0,this._c=i+this._c|0,this._d=s+this._d|0,this._e=a+this._e|0};Cc.prototype._hash=function(){var t=bB.allocUnsafe(20);return t.writeInt32BE(this._a|0,0),t.writeInt32BE(this._b|0,4),t.writeInt32BE(this._c|0,8),t.writeInt32BE(this._d|0,12),t.writeInt32BE(this._e|0,16),t};E1.exports=Cc});var C1=I(fg=>{p();var A1;(function(t){typeof DO_NOT_EXPORT_CRC=="undefined"?typeof fg=="object"?t(fg):typeof define=="function"&&define.amd?define(function(){var e={};return t(e),e}):t(A1={}):t(A1={})})(function(t){t.version="1.2.2";function e(){for(var y=0,S=new Array(256),_=0;_!=256;++_)y=_,y=y&1?-306674912^y>>>1:y>>>1,y=y&1?-306674912^y>>>1:y>>>1,y=y&1?-306674912^y>>>1:y>>>1,y=y&1?-306674912^y>>>1:y>>>1,y=y&1?-306674912^y>>>1:y>>>1,y=y&1?-306674912^y>>>1:y>>>1,y=y&1?-306674912^y>>>1:y>>>1,y=y&1?-306674912^y>>>1:y>>>1,S[_]=y;return typeof Int32Array!="undefined"?new Int32Array(S):S}var r=e();function n(y){var S=0,_=0,C=0,P=typeof Int32Array!="undefined"?new Int32Array(4096):new Array(4096);for(C=0;C!=256;++C)P[C]=y[C];for(C=0;C!=256;++C)for(_=y[C],S=256+C;S<4096;S+=256)_=P[S]=_>>>8^y[_&255];var N=[];for(C=1;C!=16;++C)N[C-1]=typeof Int32Array!="undefined"?P.subarray(C*256,C*256+256):P.slice(C*256,C*256+256);return N}var i=n(r),s=i[0],a=i[1],o=i[2],l=i[3],c=i[4],u=i[5],f=i[6],d=i[7],h=i[8],m=i[9],g=i[10],v=i[11],w=i[12],b=i[13],k=i[14];function x(y,S){for(var _=S^-1,C=0,P=y.length;C>>8^r[(_^y.charCodeAt(C++))&255];return~_}function E(y,S){for(var _=S^-1,C=y.length-15,P=0;P>8&255]^w[y[P++]^_>>16&255]^v[y[P++]^_>>>24]^g[y[P++]]^m[y[P++]]^h[y[P++]]^d[y[P++]]^f[y[P++]]^u[y[P++]]^c[y[P++]]^l[y[P++]]^o[y[P++]]^a[y[P++]]^s[y[P++]]^r[y[P++]];for(C+=15;P>>8^r[(_^y[P++])&255];return~_}function A(y,S){for(var _=S^-1,C=0,P=y.length,N=0,B=0;C>>8^r[(_^N)&255]:N<2048?(_=_>>>8^r[(_^(192|N>>6&31))&255],_=_>>>8^r[(_^(128|N&63))&255]):N>=55296&&N<57344?(N=(N&1023)+64,B=y.charCodeAt(C++)&1023,_=_>>>8^r[(_^(240|N>>8&7))&255],_=_>>>8^r[(_^(128|N>>2&63))&255],_=_>>>8^r[(_^(128|B>>6&15|(N&3)<<4))&255],_=_>>>8^r[(_^(128|B&63))&255]):(_=_>>>8^r[(_^(224|N>>12&15))&255],_=_>>>8^r[(_^(128|N>>6&63))&255],_=_>>>8^r[(_^(128|N&63))&255]);return~_}t.table=r,t.bstr=x,t.buf=E,t.str=A})});var Hi=I(cr=>{"use strict";p();var CB=typeof Uint8Array!="undefined"&&typeof Uint16Array!="undefined"&&typeof Int32Array!="undefined";function TB(t,e){return Object.prototype.hasOwnProperty.call(t,e)}cr.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var r=e.shift();if(r){if(typeof r!="object")throw new TypeError(r+"must be non-object");for(var n in r)TB(r,n)&&(t[n]=r[n])}}return t};cr.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var PB={arraySet:function(t,e,r,n,i){if(e.subarray&&t.subarray){t.set(e.subarray(r,r+n),i);return}for(var s=0;s{"use strict";p();var $B=Hi(),IB=4,T1=0,P1=1,FB=2;function Do(t){for(var e=t.length;--e>=0;)t[e]=0}var OB=0,M1=1,MB=2,DB=3,LB=258,wg=29,Fc=256,Pc=Fc+1+wg,Mo=30,yg=19,D1=2*Pc+1,ha=15,dg=16,NB=7,bg=256,L1=16,N1=17,B1=18,gg=[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],ld=[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],BB=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],H1=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],HB=512,Ui=new Array((Pc+2)*2);Do(Ui);var Tc=new Array(Mo*2);Do(Tc);var Rc=new Array(HB);Do(Rc);var $c=new Array(LB-DB+1);Do($c);var _g=new Array(wg);Do(_g);var cd=new Array(Mo);Do(cd);function hg(t,e,r,n,i){this.static_tree=t,this.extra_bits=e,this.extra_base=r,this.elems=n,this.max_length=i,this.has_stree=t&&t.length}var U1,G1,j1;function pg(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function q1(t){return t<256?Rc[t]:Rc[256+(t>>>7)]}function Ic(t,e){t.pending_buf[t.pending++]=e&255,t.pending_buf[t.pending++]=e>>>8&255}function xr(t,e,r){t.bi_valid>dg-r?(t.bi_buf|=e<>dg-t.bi_valid,t.bi_valid+=r-dg):(t.bi_buf|=e<>>=1,r<<=1;while(--e>0);return r>>>1}function UB(t){t.bi_valid===16?(Ic(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):t.bi_valid>=8&&(t.pending_buf[t.pending++]=t.bi_buf&255,t.bi_buf>>=8,t.bi_valid-=8)}function GB(t,e){var r=e.dyn_tree,n=e.max_code,i=e.stat_desc.static_tree,s=e.stat_desc.has_stree,a=e.stat_desc.extra_bits,o=e.stat_desc.extra_base,l=e.stat_desc.max_length,c,u,f,d,h,m,g=0;for(d=0;d<=ha;d++)t.bl_count[d]=0;for(r[t.heap[t.heap_max]*2+1]=0,c=t.heap_max+1;cl&&(d=l,g++),r[u*2+1]=d,!(u>n)&&(t.bl_count[d]++,h=0,u>=o&&(h=a[u-o]),m=r[u*2],t.opt_len+=m*(d+h),s&&(t.static_len+=m*(i[u*2+1]+h)));if(g!==0){do{for(d=l-1;t.bl_count[d]===0;)d--;t.bl_count[d]--,t.bl_count[d+1]+=2,t.bl_count[l]--,g-=2}while(g>0);for(d=l;d!==0;d--)for(u=t.bl_count[d];u!==0;)f=t.heap[--c],!(f>n)&&(r[f*2+1]!==d&&(t.opt_len+=(d-r[f*2+1])*r[f*2],r[f*2+1]=d),u--)}}function z1(t,e,r){var n=new Array(ha+1),i=0,s,a;for(s=1;s<=ha;s++)n[s]=i=i+r[s-1]<<1;for(a=0;a<=e;a++){var o=t[a*2+1];o!==0&&(t[a*2]=W1(n[o]++,o))}}function jB(){var t,e,r,n,i,s=new Array(ha+1);for(r=0,n=0;n>=7;n8?Ic(t,t.bi_buf):t.bi_valid>0&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function qB(t,e,r,n){Y1(t),n&&(Ic(t,r),Ic(t,~r)),$B.arraySet(t.pending_buf,t.window,e,r,t.pending),t.pending+=r}function R1(t,e,r,n){var i=e*2,s=r*2;return t[i]>1;a>=1;a--)mg(t,r,a);c=s;do a=t.heap[1],t.heap[1]=t.heap[t.heap_len--],mg(t,r,1),o=t.heap[1],t.heap[--t.heap_max]=a,t.heap[--t.heap_max]=o,r[c*2]=r[a*2]+r[o*2],t.depth[c]=(t.depth[a]>=t.depth[o]?t.depth[a]:t.depth[o])+1,r[a*2+1]=r[o*2+1]=c,t.heap[1]=c++,mg(t,r,1);while(t.heap_len>=2);t.heap[--t.heap_max]=t.heap[1],GB(t,e),z1(r,l,t.bl_count)}function I1(t,e,r){var n,i=-1,s,a=e[0*2+1],o=0,l=7,c=4;for(a===0&&(l=138,c=3),e[(r+1)*2+1]=65535,n=0;n<=r;n++)s=a,a=e[(n+1)*2+1],!(++o=3&&t.bl_tree[H1[e]*2+1]===0;e--);return t.opt_len+=3*(e+1)+5+5+4,e}function zB(t,e,r,n){var i;for(xr(t,e-257,5),xr(t,r-1,5),xr(t,n-4,4),i=0;i>>=1)if(e&1&&t.dyn_ltree[r*2]!==0)return T1;if(t.dyn_ltree[9*2]!==0||t.dyn_ltree[10*2]!==0||t.dyn_ltree[13*2]!==0)return P1;for(r=32;r0?(t.strm.data_type===FB&&(t.strm.data_type=VB(t)),vg(t,t.l_desc),vg(t,t.d_desc),a=WB(t),i=t.opt_len+3+7>>>3,s=t.static_len+3+7>>>3,s<=i&&(i=s)):i=s=r+5,r+4<=i&&e!==-1?X1(t,e,r,n):t.strategy===IB||s===i?(xr(t,(M1<<1)+(n?1:0),3),$1(t,Ui,Tc)):(xr(t,(MB<<1)+(n?1:0),3),zB(t,t.l_desc.max_code+1,t.d_desc.max_code+1,a+1),$1(t,t.dyn_ltree,t.dyn_dtree)),V1(t),n&&Y1(t)}function KB(t,e,r){return t.pending_buf[t.d_buf+t.last_lit*2]=e>>>8&255,t.pending_buf[t.d_buf+t.last_lit*2+1]=e&255,t.pending_buf[t.l_buf+t.last_lit]=r&255,t.last_lit++,e===0?t.dyn_ltree[r*2]++:(t.matches++,e--,t.dyn_ltree[($c[r]+Fc+1)*2]++,t.dyn_dtree[q1(e)*2]++),t.last_lit===t.lit_bufsize-1}Lo._tr_init=YB;Lo._tr_stored_block=X1;Lo._tr_flush_block=ZB;Lo._tr_tally=KB;Lo._tr_align=XB});var xg=I((sZ,K1)=>{"use strict";p();function QB(t,e,r,n){for(var i=t&65535|0,s=t>>>16&65535|0,a=0;r!==0;){a=r>2e3?2e3:r,r-=a;do i=i+e[n++]|0,s=s+i|0;while(--a);i%=65521,s%=65521}return i|s<<16|0}K1.exports=QB});var Sg=I((oZ,Q1)=>{"use strict";p();function JB(){for(var t,e=[],r=0;r<256;r++){t=r;for(var n=0;n<8;n++)t=t&1?3988292384^t>>>1:t>>>1;e[r]=t}return e}var eH=JB();function tH(t,e,r,n){var i=eH,s=n+r;t^=-1;for(var a=n;a>>8^i[(t^e[a])&255];return t^-1}Q1.exports=tH});var ud=I((cZ,J1)=>{"use strict";p();J1.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}});var lS=I(ci=>{"use strict";p();var ur=Hi(),dn=Z1(),nS=xg(),xs=Sg(),rH=ud(),va=0,nH=1,iH=3,Cs=4,eS=5,li=0,tS=1,hn=-2,sH=-3,Eg=-5,aH=-1,oH=1,fd=2,lH=3,cH=4,uH=0,fH=2,md=8,dH=9,hH=15,pH=8,mH=29,gH=256,Ag=gH+1+mH,vH=30,wH=19,yH=2*Ag+1,bH=15,Te=3,ks=258,Fn=ks+Te+1,_H=32,gd=42,Cg=69,dd=73,hd=91,pd=103,pa=113,Mc=666,Tt=1,Dc=2,ma=3,Ho=4,xH=3;function As(t,e){return t.msg=rH[e],e}function rS(t){return(t<<1)-(t>4?9:0)}function Es(t){for(var e=t.length;--e>=0;)t[e]=0}function Ss(t){var e=t.state,r=e.pending;r>t.avail_out&&(r=t.avail_out),r!==0&&(ur.arraySet(t.output,e.pending_buf,e.pending_out,r,t.next_out),t.next_out+=r,e.pending_out+=r,t.total_out+=r,t.avail_out-=r,e.pending-=r,e.pending===0&&(e.pending_out=0))}function Gt(t,e){dn._tr_flush_block(t,t.block_start>=0?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,Ss(t.strm)}function Fe(t,e){t.pending_buf[t.pending++]=e}function Oc(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=e&255}function SH(t,e,r,n){var i=t.avail_in;return i>n&&(i=n),i===0?0:(t.avail_in-=i,ur.arraySet(e,t.input,t.next_in,i,r),t.state.wrap===1?t.adler=nS(t.adler,e,i,r):t.state.wrap===2&&(t.adler=xs(t.adler,e,i,r)),t.next_in+=i,t.total_in+=i,i)}function iS(t,e){var r=t.max_chain_length,n=t.strstart,i,s,a=t.prev_length,o=t.nice_match,l=t.strstart>t.w_size-Fn?t.strstart-(t.w_size-Fn):0,c=t.window,u=t.w_mask,f=t.prev,d=t.strstart+ks,h=c[n+a-1],m=c[n+a];t.prev_length>=t.good_match&&(r>>=2),o>t.lookahead&&(o=t.lookahead);do if(i=e,!(c[i+a]!==m||c[i+a-1]!==h||c[i]!==c[n]||c[++i]!==c[n+1])){n+=2,i++;do;while(c[++n]===c[++i]&&c[++n]===c[++i]&&c[++n]===c[++i]&&c[++n]===c[++i]&&c[++n]===c[++i]&&c[++n]===c[++i]&&c[++n]===c[++i]&&c[++n]===c[++i]&&na){if(t.match_start=e,a=s,s>=o)break;h=c[n+a-1],m=c[n+a]}}while((e=f[e&u])>l&&--r!==0);return a<=t.lookahead?a:t.lookahead}function ga(t){var e=t.w_size,r,n,i,s,a;do{if(s=t.window_size-t.lookahead-t.strstart,t.strstart>=e+(e-Fn)){ur.arraySet(t.window,t.window,e,e,0),t.match_start-=e,t.strstart-=e,t.block_start-=e,n=t.hash_size,r=n;do i=t.head[--r],t.head[r]=i>=e?i-e:0;while(--n);n=e,r=n;do i=t.prev[--r],t.prev[r]=i>=e?i-e:0;while(--n);s+=e}if(t.strm.avail_in===0)break;if(n=SH(t.strm,t.window,t.strstart+t.lookahead,s),t.lookahead+=n,t.lookahead+t.insert>=Te)for(a=t.strstart-t.insert,t.ins_h=t.window[a],t.ins_h=(t.ins_h<t.pending_buf_size-5&&(r=t.pending_buf_size-5);;){if(t.lookahead<=1){if(ga(t),t.lookahead===0&&e===va)return Tt;if(t.lookahead===0)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+r;if((t.strstart===0||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,Gt(t,!1),t.strm.avail_out===0)||t.strstart-t.block_start>=t.w_size-Fn&&(Gt(t,!1),t.strm.avail_out===0))return Tt}return t.insert=0,e===Cs?(Gt(t,!0),t.strm.avail_out===0?ma:Ho):(t.strstart>t.block_start&&(Gt(t,!1),t.strm.avail_out===0),Tt)}function kg(t,e){for(var r,n;;){if(t.lookahead=Te&&(t.ins_h=(t.ins_h<=Te)if(n=dn._tr_tally(t,t.strstart-t.match_start,t.match_length-Te),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=Te){t.match_length--;do t.strstart++,t.ins_h=(t.ins_h<=Te&&(t.ins_h=(t.ins_h<4096)&&(t.match_length=Te-1)),t.prev_length>=Te&&t.match_length<=t.prev_length){i=t.strstart+t.lookahead-Te,n=dn._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-Te),t.lookahead-=t.prev_length-1,t.prev_length-=2;do++t.strstart<=i&&(t.ins_h=(t.ins_h<=Te&&t.strstart>0&&(i=t.strstart-1,n=a[i],n===a[++i]&&n===a[++i]&&n===a[++i])){s=t.strstart+ks;do;while(n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&n===a[++i]&&it.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=Te?(r=dn._tr_tally(t,1,t.match_length-Te),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(r=dn._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),r&&(Gt(t,!1),t.strm.avail_out===0))return Tt}return t.insert=0,e===Cs?(Gt(t,!0),t.strm.avail_out===0?ma:Ho):t.last_lit&&(Gt(t,!1),t.strm.avail_out===0)?Tt:Dc}function AH(t,e){for(var r;;){if(t.lookahead===0&&(ga(t),t.lookahead===0)){if(e===va)return Tt;break}if(t.match_length=0,r=dn._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,r&&(Gt(t,!1),t.strm.avail_out===0))return Tt}return t.insert=0,e===Cs?(Gt(t,!0),t.strm.avail_out===0?ma:Ho):t.last_lit&&(Gt(t,!1),t.strm.avail_out===0)?Tt:Dc}function oi(t,e,r,n,i){this.good_length=t,this.max_lazy=e,this.nice_length=r,this.max_chain=n,this.func=i}var Bo;Bo=[new oi(0,0,0,0,EH),new oi(4,4,8,4,kg),new oi(4,5,16,8,kg),new oi(4,6,32,32,kg),new oi(4,4,16,16,No),new oi(8,16,32,32,No),new oi(8,16,128,128,No),new oi(8,32,128,256,No),new oi(32,128,258,1024,No),new oi(32,258,258,4096,No)];function CH(t){t.window_size=2*t.w_size,Es(t.head),t.max_lazy_match=Bo[t.level].max_lazy,t.good_match=Bo[t.level].good_length,t.nice_match=Bo[t.level].nice_length,t.max_chain_length=Bo[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=Te-1,t.match_available=0,t.ins_h=0}function TH(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=md,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new ur.Buf16(yH*2),this.dyn_dtree=new ur.Buf16((2*vH+1)*2),this.bl_tree=new ur.Buf16((2*wH+1)*2),Es(this.dyn_ltree),Es(this.dyn_dtree),Es(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new ur.Buf16(bH+1),this.heap=new ur.Buf16(2*Ag+1),Es(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new ur.Buf16(2*Ag+1),Es(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function sS(t){var e;return!t||!t.state?As(t,hn):(t.total_in=t.total_out=0,t.data_type=fH,e=t.state,e.pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?gd:pa,t.adler=e.wrap===2?0:1,e.last_flush=va,dn._tr_init(e),li)}function aS(t){var e=sS(t);return e===li&&CH(t.state),e}function PH(t,e){return!t||!t.state||t.state.wrap!==2?hn:(t.state.gzhead=e,li)}function oS(t,e,r,n,i,s){if(!t)return hn;var a=1;if(e===aH&&(e=6),n<0?(a=0,n=-n):n>15&&(a=2,n-=16),i<1||i>dH||r!==md||n<8||n>15||e<0||e>9||s<0||s>cH)return As(t,hn);n===8&&(n=9);var o=new TH;return t.state=o,o.strm=t,o.wrap=a,o.gzhead=null,o.w_bits=n,o.w_size=1<eS||e<0)return t?As(t,hn):hn;if(n=t.state,!t.output||!t.input&&t.avail_in!==0||n.status===Mc&&e!==Cs)return As(t,t.avail_out===0?Eg:hn);if(n.strm=t,r=n.last_flush,n.last_flush=e,n.status===gd)if(n.wrap===2)t.adler=0,Fe(n,31),Fe(n,139),Fe(n,8),n.gzhead?(Fe(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),Fe(n,n.gzhead.time&255),Fe(n,n.gzhead.time>>8&255),Fe(n,n.gzhead.time>>16&255),Fe(n,n.gzhead.time>>24&255),Fe(n,n.level===9?2:n.strategy>=fd||n.level<2?4:0),Fe(n,n.gzhead.os&255),n.gzhead.extra&&n.gzhead.extra.length&&(Fe(n,n.gzhead.extra.length&255),Fe(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=xs(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=Cg):(Fe(n,0),Fe(n,0),Fe(n,0),Fe(n,0),Fe(n,0),Fe(n,n.level===9?2:n.strategy>=fd||n.level<2?4:0),Fe(n,xH),n.status=pa);else{var a=md+(n.w_bits-8<<4)<<8,o=-1;n.strategy>=fd||n.level<2?o=0:n.level<6?o=1:n.level===6?o=2:o=3,a|=o<<6,n.strstart!==0&&(a|=_H),a+=31-a%31,n.status=pa,Oc(n,a),n.strstart!==0&&(Oc(n,t.adler>>>16),Oc(n,t.adler&65535)),t.adler=1}if(n.status===Cg)if(n.gzhead.extra){for(i=n.pending;n.gzindex<(n.gzhead.extra.length&65535)&&!(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(t.adler=xs(t.adler,n.pending_buf,n.pending-i,i)),Ss(t),i=n.pending,n.pending===n.pending_buf_size));)Fe(n,n.gzhead.extra[n.gzindex]&255),n.gzindex++;n.gzhead.hcrc&&n.pending>i&&(t.adler=xs(t.adler,n.pending_buf,n.pending-i,i)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=dd)}else n.status=dd;if(n.status===dd)if(n.gzhead.name){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(t.adler=xs(t.adler,n.pending_buf,n.pending-i,i)),Ss(t),i=n.pending,n.pending===n.pending_buf_size)){s=1;break}n.gzindexi&&(t.adler=xs(t.adler,n.pending_buf,n.pending-i,i)),s===0&&(n.gzindex=0,n.status=hd)}else n.status=hd;if(n.status===hd)if(n.gzhead.comment){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(t.adler=xs(t.adler,n.pending_buf,n.pending-i,i)),Ss(t),i=n.pending,n.pending===n.pending_buf_size)){s=1;break}n.gzindexi&&(t.adler=xs(t.adler,n.pending_buf,n.pending-i,i)),s===0&&(n.status=pd)}else n.status=pd;if(n.status===pd&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&Ss(t),n.pending+2<=n.pending_buf_size&&(Fe(n,t.adler&255),Fe(n,t.adler>>8&255),t.adler=0,n.status=pa)):n.status=pa),n.pending!==0){if(Ss(t),t.avail_out===0)return n.last_flush=-1,li}else if(t.avail_in===0&&rS(e)<=rS(r)&&e!==Cs)return As(t,Eg);if(n.status===Mc&&t.avail_in!==0)return As(t,Eg);if(t.avail_in!==0||n.lookahead!==0||e!==va&&n.status!==Mc){var l=n.strategy===fd?AH(n,e):n.strategy===lH?kH(n,e):Bo[n.level].func(n,e);if((l===ma||l===Ho)&&(n.status=Mc),l===Tt||l===ma)return t.avail_out===0&&(n.last_flush=-1),li;if(l===Dc&&(e===nH?dn._tr_align(n):e!==eS&&(dn._tr_stored_block(n,0,0,!1),e===iH&&(Es(n.head),n.lookahead===0&&(n.strstart=0,n.block_start=0,n.insert=0))),Ss(t),t.avail_out===0))return n.last_flush=-1,li}return e!==Cs?li:n.wrap<=0?tS:(n.wrap===2?(Fe(n,t.adler&255),Fe(n,t.adler>>8&255),Fe(n,t.adler>>16&255),Fe(n,t.adler>>24&255),Fe(n,t.total_in&255),Fe(n,t.total_in>>8&255),Fe(n,t.total_in>>16&255),Fe(n,t.total_in>>24&255)):(Oc(n,t.adler>>>16),Oc(n,t.adler&65535)),Ss(t),n.wrap>0&&(n.wrap=-n.wrap),n.pending!==0?li:tS)}function IH(t){var e;return!t||!t.state?hn:(e=t.state.status,e!==gd&&e!==Cg&&e!==dd&&e!==hd&&e!==pd&&e!==pa&&e!==Mc?As(t,hn):(t.state=null,e===pa?As(t,sH):li))}function FH(t,e){var r=e.length,n,i,s,a,o,l,c,u;if(!t||!t.state||(n=t.state,a=n.wrap,a===2||a===1&&n.status!==gd||n.lookahead))return hn;for(a===1&&(t.adler=nS(t.adler,e,r,0)),n.wrap=0,r>=n.w_size&&(a===0&&(Es(n.head),n.strstart=0,n.block_start=0,n.insert=0),u=new ur.Buf8(n.w_size),ur.arraySet(u,e,r-n.w_size,n.w_size,0),e=u,r=n.w_size),o=t.avail_in,l=t.next_in,c=t.input,t.avail_in=r,t.next_in=0,t.input=e,ga(n);n.lookahead>=Te;){i=n.strstart,s=n.lookahead-(Te-1);do n.ins_h=(n.ins_h<{"use strict";p();var vd=Hi(),cS=!0,uS=!0;try{String.fromCharCode.apply(null,[0])}catch(t){cS=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){uS=!1}var Lc=new vd.Buf8(256);for(Gi=0;Gi<256;Gi++)Lc[Gi]=Gi>=252?6:Gi>=248?5:Gi>=240?4:Gi>=224?3:Gi>=192?2:1;var Gi;Lc[254]=Lc[254]=1;Uo.string2buf=function(t){var e,r,n,i,s,a=t.length,o=0;for(i=0;i>>6,e[s++]=128|r&63):r<65536?(e[s++]=224|r>>>12,e[s++]=128|r>>>6&63,e[s++]=128|r&63):(e[s++]=240|r>>>18,e[s++]=128|r>>>12&63,e[s++]=128|r>>>6&63,e[s++]=128|r&63);return e};function fS(t,e){if(e<65534&&(t.subarray&&uS||!t.subarray&&cS))return String.fromCharCode.apply(null,vd.shrinkBuf(t,e));for(var r="",n=0;n4){o[n++]=65533,r+=s-1;continue}for(i&=s===2?31:s===3?15:7;s>1&&r1){o[n++]=65533;continue}i<65536?o[n++]=i:(i-=65536,o[n++]=55296|i>>10&1023,o[n++]=56320|i&1023)}return fS(o,n)};Uo.utf8border=function(t,e){var r;for(e=e||t.length,e>t.length&&(e=t.length),r=e-1;r>=0&&(t[r]&192)===128;)r--;return r<0||r===0?e:r+Lc[t[r]]>e?r:e}});var Pg=I((mZ,dS)=>{"use strict";p();function OH(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}dS.exports=OH});var gS=I(Hc=>{"use strict";p();var Nc=lS(),Bc=Hi(),$g=Tg(),Ig=ud(),MH=Pg(),mS=Object.prototype.toString,DH=0,Rg=4,Go=0,hS=1,pS=2,LH=-1,NH=0,BH=8;function wa(t){if(!(this instanceof wa))return new wa(t);this.options=Bc.assign({level:LH,method:BH,chunkSize:16384,windowBits:15,memLevel:8,strategy:NH,to:""},t||{});var e=this.options;e.raw&&e.windowBits>0?e.windowBits=-e.windowBits:e.gzip&&e.windowBits>0&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new MH,this.strm.avail_out=0;var r=Nc.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(r!==Go)throw new Error(Ig[r]);if(e.header&&Nc.deflateSetHeader(this.strm,e.header),e.dictionary){var n;if(typeof e.dictionary=="string"?n=$g.string2buf(e.dictionary):mS.call(e.dictionary)==="[object ArrayBuffer]"?n=new Uint8Array(e.dictionary):n=e.dictionary,r=Nc.deflateSetDictionary(this.strm,n),r!==Go)throw new Error(Ig[r]);this._dict_set=!0}}wa.prototype.push=function(t,e){var r=this.strm,n=this.options.chunkSize,i,s;if(this.ended)return!1;s=e===~~e?e:e===!0?Rg:DH,typeof t=="string"?r.input=$g.string2buf(t):mS.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new Bc.Buf8(n),r.next_out=0,r.avail_out=n),i=Nc.deflate(r,s),i!==hS&&i!==Go)return this.onEnd(i),this.ended=!0,!1;(r.avail_out===0||r.avail_in===0&&(s===Rg||s===pS))&&(this.options.to==="string"?this.onData($g.buf2binstring(Bc.shrinkBuf(r.output,r.next_out))):this.onData(Bc.shrinkBuf(r.output,r.next_out)))}while((r.avail_in>0||r.avail_out===0)&&i!==hS);return s===Rg?(i=Nc.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===Go):(s===pS&&(this.onEnd(Go),r.avail_out=0),!0)};wa.prototype.onData=function(t){this.chunks.push(t)};wa.prototype.onEnd=function(t){t===Go&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Bc.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Fg(t,e){var r=new wa(e);if(r.push(t,!0),r.err)throw r.msg||Ig[r.err];return r.result}function HH(t,e){return e=e||{},e.raw=!0,Fg(t,e)}function UH(t,e){return e=e||{},e.gzip=!0,Fg(t,e)}Hc.Deflate=wa;Hc.deflate=Fg;Hc.deflateRaw=HH;Hc.gzip=UH});var wS=I((yZ,vS)=>{"use strict";p();var wd=30,GH=12;vS.exports=function(e,r){var n,i,s,a,o,l,c,u,f,d,h,m,g,v,w,b,k,x,E,A,y,S,_,C,P;n=e.state,i=e.next_in,C=e.input,s=i+(e.avail_in-5),a=e.next_out,P=e.output,o=a-(r-e.avail_out),l=a+(e.avail_out-257),c=n.dmax,u=n.wsize,f=n.whave,d=n.wnext,h=n.window,m=n.hold,g=n.bits,v=n.lencode,w=n.distcode,b=(1<>>24,m>>>=E,g-=E,E=x>>>16&255,E===0)P[a++]=x&65535;else if(E&16){A=x&65535,E&=15,E&&(g>>=E,g-=E),g<15&&(m+=C[i++]<>>24,m>>>=E,g-=E,E=x>>>16&255,E&16){if(y=x&65535,E&=15,gc){e.msg="invalid distance too far back",n.mode=wd;break e}if(m>>>=E,g-=E,E=a-o,y>E){if(E=y-E,E>f&&n.sane){e.msg="invalid distance too far back",n.mode=wd;break e}if(S=0,_=h,d===0){if(S+=u-E,E2;)P[a++]=_[S++],P[a++]=_[S++],P[a++]=_[S++],A-=3;A&&(P[a++]=_[S++],A>1&&(P[a++]=_[S++]))}else{S=a-y;do P[a++]=P[S++],P[a++]=P[S++],P[a++]=P[S++],A-=3;while(A>2);A&&(P[a++]=P[S++],A>1&&(P[a++]=P[S++]))}}else if(E&64){e.msg="invalid distance code",n.mode=wd;break e}else{x=w[(x&65535)+(m&(1<>3,i-=A,g-=A<<3,m&=(1<{"use strict";p();var yS=Hi(),jo=15,bS=852,_S=592,xS=0,Og=1,SS=2,jH=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],qH=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],WH=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],zH=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];ES.exports=function(e,r,n,i,s,a,o,l){var c=l.bits,u=0,f=0,d=0,h=0,m=0,g=0,v=0,w=0,b=0,k=0,x,E,A,y,S,_=null,C=0,P,N=new yS.Buf16(jo+1),B=new yS.Buf16(jo+1),H=null,ce=0,Pe,ve,ie;for(u=0;u<=jo;u++)N[u]=0;for(f=0;f=1&&N[h]===0;h--);if(m>h&&(m=h),h===0)return s[a++]=1<<24|64<<16|0,s[a++]=1<<24|64<<16|0,l.bits=1,0;for(d=1;d0&&(e===xS||h!==1))return-1;for(B[1]=0,u=1;ubS||e===SS&&b>_S)return 1;for(;;){Pe=u-v,o[f]P?(ve=H[ce+o[f]],ie=_[C+o[f]]):(ve=96,ie=0),x=1<>v)+E]=Pe<<24|ve<<16|ie|0;while(E!==0);for(x=1<>=1;if(x!==0?(k&=x-1,k+=x):k=0,f++,--N[u]===0){if(u===h)break;u=r[n+o[f]]}if(u>m&&(k&y)!==A){for(v===0&&(v=m),S+=d,g=u-v,w=1<bS||e===SS&&b>_S)return 1;A=k&y,s[A]=m<<24|g<<16|S-a|0}}return k!==0&&(s[S+k]=u-v<<24|64<<16|0),l.bits=m,0}});var aE=I(On=>{"use strict";p();var Yr=Hi(),Hg=xg(),ui=Sg(),VH=wS(),Uc=kS(),YH=0,KS=1,QS=2,AS=4,XH=5,yd=6,ya=0,ZH=1,KH=2,pn=-2,JS=-3,Ug=-4,QH=-5,CS=8,eE=1,TS=2,PS=3,RS=4,$S=5,IS=6,FS=7,OS=8,MS=9,DS=10,xd=11,ji=12,Mg=13,LS=14,Dg=15,NS=16,BS=17,HS=18,US=19,bd=20,_d=21,GS=22,jS=23,qS=24,WS=25,zS=26,Lg=27,VS=28,YS=29,Je=30,Gg=31,JH=32,e3=852,t3=592,r3=15,n3=r3;function XS(t){return(t>>>24&255)+(t>>>8&65280)+((t&65280)<<8)+((t&255)<<24)}function i3(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Yr.Buf16(320),this.work=new Yr.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function tE(t){var e;return!t||!t.state?pn:(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=e.wrap&1),e.mode=eE,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new Yr.Buf32(e3),e.distcode=e.distdyn=new Yr.Buf32(t3),e.sane=1,e.back=-1,ya)}function rE(t){var e;return!t||!t.state?pn:(e=t.state,e.wsize=0,e.whave=0,e.wnext=0,tE(t))}function nE(t,e){var r,n;return!t||!t.state||(n=t.state,e<0?(r=0,e=-e):(r=(e>>4)+1,e<48&&(e&=15)),e&&(e<8||e>15))?pn:(n.window!==null&&n.wbits!==e&&(n.window=null),n.wrap=r,n.wbits=e,rE(t))}function iE(t,e){var r,n;return t?(n=new i3,t.state=n,n.window=null,r=nE(t,e),r!==ya&&(t.state=null),r):pn}function s3(t){return iE(t,n3)}var ZS=!0,Ng,Bg;function a3(t){if(ZS){var e;for(Ng=new Yr.Buf32(512),Bg=new Yr.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(Uc(KS,t.lens,0,288,Ng,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;Uc(QS,t.lens,0,32,Bg,0,t.work,{bits:5}),ZS=!1}t.lencode=Ng,t.lenbits=9,t.distcode=Bg,t.distbits=5}function sE(t,e,r,n){var i,s=t.state;return s.window===null&&(s.wsize=1<=s.wsize?(Yr.arraySet(s.window,e,r-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):(i=s.wsize-s.wnext,i>n&&(i=n),Yr.arraySet(s.window,e,r-n,i,s.wnext),n-=i,n?(Yr.arraySet(s.window,e,r-n,n,0),s.wnext=n,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave>>8&255,r.check=ui(r.check,_,2,0),c=0,u=0,r.mode=TS;break}if(r.flags=0,r.head&&(r.head.done=!1),!(r.wrap&1)||(((c&255)<<8)+(c>>8))%31){t.msg="incorrect header check",r.mode=Je;break}if((c&15)!==CS){t.msg="unknown compression method",r.mode=Je;break}if(c>>>=4,u-=4,y=(c&15)+8,r.wbits===0)r.wbits=y;else if(y>r.wbits){t.msg="invalid window size",r.mode=Je;break}r.dmax=1<>8&1),r.flags&512&&(_[0]=c&255,_[1]=c>>>8&255,r.check=ui(r.check,_,2,0)),c=0,u=0,r.mode=PS;case PS:for(;u<32;){if(o===0)break e;o--,c+=n[s++]<>>8&255,_[2]=c>>>16&255,_[3]=c>>>24&255,r.check=ui(r.check,_,4,0)),c=0,u=0,r.mode=RS;case RS:for(;u<16;){if(o===0)break e;o--,c+=n[s++]<>8),r.flags&512&&(_[0]=c&255,_[1]=c>>>8&255,r.check=ui(r.check,_,2,0)),c=0,u=0,r.mode=$S;case $S:if(r.flags&1024){for(;u<16;){if(o===0)break e;o--,c+=n[s++]<>>8&255,r.check=ui(r.check,_,2,0)),c=0,u=0}else r.head&&(r.head.extra=null);r.mode=IS;case IS:if(r.flags&1024&&(h=r.length,h>o&&(h=o),h&&(r.head&&(y=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),Yr.arraySet(r.head.extra,n,s,h,y)),r.flags&512&&(r.check=ui(r.check,n,h,s)),o-=h,s+=h,r.length-=h),r.length))break e;r.length=0,r.mode=FS;case FS:if(r.flags&2048){if(o===0)break e;h=0;do y=n[s+h++],r.head&&y&&r.length<65536&&(r.head.name+=String.fromCharCode(y));while(y&&h>9&1,r.head.done=!0),t.adler=r.check=0,r.mode=ji;break;case DS:for(;u<32;){if(o===0)break e;o--,c+=n[s++]<>>=u&7,u-=u&7,r.mode=Lg;break}for(;u<3;){if(o===0)break e;o--,c+=n[s++]<>>=1,u-=1,c&3){case 0:r.mode=LS;break;case 1:if(a3(r),r.mode=bd,e===yd){c>>>=2,u-=2;break e}break;case 2:r.mode=BS;break;case 3:t.msg="invalid block type",r.mode=Je}c>>>=2,u-=2;break;case LS:for(c>>>=u&7,u-=u&7;u<32;){if(o===0)break e;o--,c+=n[s++]<>>16^65535)){t.msg="invalid stored block lengths",r.mode=Je;break}if(r.length=c&65535,c=0,u=0,r.mode=Dg,e===yd)break e;case Dg:r.mode=NS;case NS:if(h=r.length,h){if(h>o&&(h=o),h>l&&(h=l),h===0)break e;Yr.arraySet(i,n,s,h,a),o-=h,s+=h,l-=h,a+=h,r.length-=h;break}r.mode=ji;break;case BS:for(;u<14;){if(o===0)break e;o--,c+=n[s++]<>>=5,u-=5,r.ndist=(c&31)+1,c>>>=5,u-=5,r.ncode=(c&15)+4,c>>>=4,u-=4,r.nlen>286||r.ndist>30){t.msg="too many length or distance symbols",r.mode=Je;break}r.have=0,r.mode=HS;case HS:for(;r.have>>=3,u-=3}for(;r.have<19;)r.lens[N[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,C={bits:r.lenbits},S=Uc(YH,r.lens,0,19,r.lencode,0,r.work,C),r.lenbits=C.bits,S){t.msg="invalid code lengths set",r.mode=Je;break}r.have=0,r.mode=US;case US:for(;r.have>>24,b=v>>>16&255,k=v&65535,!(w<=u);){if(o===0)break e;o--,c+=n[s++]<>>=w,u-=w,r.lens[r.have++]=k;else{if(k===16){for(P=w+2;u>>=w,u-=w,r.have===0){t.msg="invalid bit length repeat",r.mode=Je;break}y=r.lens[r.have-1],h=3+(c&3),c>>>=2,u-=2}else if(k===17){for(P=w+3;u>>=w,u-=w,y=0,h=3+(c&7),c>>>=3,u-=3}else{for(P=w+7;u>>=w,u-=w,y=0,h=11+(c&127),c>>>=7,u-=7}if(r.have+h>r.nlen+r.ndist){t.msg="invalid bit length repeat",r.mode=Je;break}for(;h--;)r.lens[r.have++]=y}}if(r.mode===Je)break;if(r.lens[256]===0){t.msg="invalid code -- missing end-of-block",r.mode=Je;break}if(r.lenbits=9,C={bits:r.lenbits},S=Uc(KS,r.lens,0,r.nlen,r.lencode,0,r.work,C),r.lenbits=C.bits,S){t.msg="invalid literal/lengths set",r.mode=Je;break}if(r.distbits=6,r.distcode=r.distdyn,C={bits:r.distbits},S=Uc(QS,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,C),r.distbits=C.bits,S){t.msg="invalid distances set",r.mode=Je;break}if(r.mode=bd,e===yd)break e;case bd:r.mode=_d;case _d:if(o>=6&&l>=258){t.next_out=a,t.avail_out=l,t.next_in=s,t.avail_in=o,r.hold=c,r.bits=u,VH(t,d),a=t.next_out,i=t.output,l=t.avail_out,s=t.next_in,n=t.input,o=t.avail_in,c=r.hold,u=r.bits,r.mode===ji&&(r.back=-1);break}for(r.back=0;v=r.lencode[c&(1<>>24,b=v>>>16&255,k=v&65535,!(w<=u);){if(o===0)break e;o--,c+=n[s++]<>x)],w=v>>>24,b=v>>>16&255,k=v&65535,!(x+w<=u);){if(o===0)break e;o--,c+=n[s++]<>>=x,u-=x,r.back+=x}if(c>>>=w,u-=w,r.back+=w,r.length=k,b===0){r.mode=zS;break}if(b&32){r.back=-1,r.mode=ji;break}if(b&64){t.msg="invalid literal/length code",r.mode=Je;break}r.extra=b&15,r.mode=GS;case GS:if(r.extra){for(P=r.extra;u>>=r.extra,u-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=jS;case jS:for(;v=r.distcode[c&(1<>>24,b=v>>>16&255,k=v&65535,!(w<=u);){if(o===0)break e;o--,c+=n[s++]<>x)],w=v>>>24,b=v>>>16&255,k=v&65535,!(x+w<=u);){if(o===0)break e;o--,c+=n[s++]<>>=x,u-=x,r.back+=x}if(c>>>=w,u-=w,r.back+=w,b&64){t.msg="invalid distance code",r.mode=Je;break}r.offset=k,r.extra=b&15,r.mode=qS;case qS:if(r.extra){for(P=r.extra;u>>=r.extra,u-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){t.msg="invalid distance too far back",r.mode=Je;break}r.mode=WS;case WS:if(l===0)break e;if(h=d-l,r.offset>h){if(h=r.offset-h,h>r.whave&&r.sane){t.msg="invalid distance too far back",r.mode=Je;break}h>r.wnext?(h-=r.wnext,m=r.wsize-h):m=r.wnext-h,h>r.length&&(h=r.length),g=r.window}else g=i,m=a-r.offset,h=r.length;h>l&&(h=l),l-=h,r.length-=h;do i[a++]=g[m++];while(--h);r.length===0&&(r.mode=_d);break;case zS:if(l===0)break e;i[a++]=r.length,l--,r.mode=_d;break;case Lg:if(r.wrap){for(;u<32;){if(o===0)break e;o--,c|=n[s++]<{"use strict";p();oE.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}});var cE=I((CZ,lE)=>{"use strict";p();function f3(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}lE.exports=f3});var fE=I(jc=>{"use strict";p();var qo=aE(),Gc=Hi(),Sd=Tg(),dt=jg(),qg=ud(),d3=Pg(),h3=cE(),uE=Object.prototype.toString;function ba(t){if(!(this instanceof ba))return new ba(t);this.options=Gc.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&e.windowBits>=0&&e.windowBits<16&&(e.windowBits=-e.windowBits,e.windowBits===0&&(e.windowBits=-15)),e.windowBits>=0&&e.windowBits<16&&!(t&&t.windowBits)&&(e.windowBits+=32),e.windowBits>15&&e.windowBits<48&&(e.windowBits&15||(e.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new d3,this.strm.avail_out=0;var r=qo.inflateInit2(this.strm,e.windowBits);if(r!==dt.Z_OK)throw new Error(qg[r]);if(this.header=new h3,qo.inflateGetHeader(this.strm,this.header),e.dictionary&&(typeof e.dictionary=="string"?e.dictionary=Sd.string2buf(e.dictionary):uE.call(e.dictionary)==="[object ArrayBuffer]"&&(e.dictionary=new Uint8Array(e.dictionary)),e.raw&&(r=qo.inflateSetDictionary(this.strm,e.dictionary),r!==dt.Z_OK)))throw new Error(qg[r])}ba.prototype.push=function(t,e){var r=this.strm,n=this.options.chunkSize,i=this.options.dictionary,s,a,o,l,c,u=!1;if(this.ended)return!1;a=e===~~e?e:e===!0?dt.Z_FINISH:dt.Z_NO_FLUSH,typeof t=="string"?r.input=Sd.binstring2buf(t):uE.call(t)==="[object ArrayBuffer]"?r.input=new Uint8Array(t):r.input=t,r.next_in=0,r.avail_in=r.input.length;do{if(r.avail_out===0&&(r.output=new Gc.Buf8(n),r.next_out=0,r.avail_out=n),s=qo.inflate(r,dt.Z_NO_FLUSH),s===dt.Z_NEED_DICT&&i&&(s=qo.inflateSetDictionary(this.strm,i)),s===dt.Z_BUF_ERROR&&u===!0&&(s=dt.Z_OK,u=!1),s!==dt.Z_STREAM_END&&s!==dt.Z_OK)return this.onEnd(s),this.ended=!0,!1;r.next_out&&(r.avail_out===0||s===dt.Z_STREAM_END||r.avail_in===0&&(a===dt.Z_FINISH||a===dt.Z_SYNC_FLUSH))&&(this.options.to==="string"?(o=Sd.utf8border(r.output,r.next_out),l=r.next_out-o,c=Sd.buf2string(r.output,o),r.next_out=l,r.avail_out=n-l,l&&Gc.arraySet(r.output,r.output,o,l,0),this.onData(c)):this.onData(Gc.shrinkBuf(r.output,r.next_out))),r.avail_in===0&&r.avail_out===0&&(u=!0)}while((r.avail_in>0||r.avail_out===0)&&s!==dt.Z_STREAM_END);return s===dt.Z_STREAM_END&&(a=dt.Z_FINISH),a===dt.Z_FINISH?(s=qo.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===dt.Z_OK):(a===dt.Z_SYNC_FLUSH&&(this.onEnd(dt.Z_OK),r.avail_out=0),!0)};ba.prototype.onData=function(t){this.chunks.push(t)};ba.prototype.onEnd=function(t){t===dt.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=Gc.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg};function Wg(t,e){var r=new ba(e);if(r.push(t,!0),r.err)throw r.msg||qg[r.err];return r.result}function p3(t,e){return e=e||{},e.raw=!0,Wg(t,e)}jc.Inflate=ba;jc.inflate=Wg;jc.inflateRaw=p3;jc.ungzip=Wg});var pE=I(($Z,hE)=>{"use strict";p();var m3=Hi().assign,g3=gS(),v3=fE(),w3=jg(),dE={};m3(dE,g3,v3,w3);hE.exports=dE});var vE=I((FZ,gE)=>{"use strict";p();var mE=(t,e)=>function(...r){let n=e.promiseModule;return new n((i,s)=>{e.multiArgs?r.push((...a)=>{e.errorFirst?a[0]?s(a):(a.shift(),i(a)):i(a)}):e.errorFirst?r.push((a,o)=>{a?s(a):i(o)}):r.push(i),t.apply(this,r)})};gE.exports=(t,e)=>{e=Object.assign({exclude:[/.+(Sync|Stream)$/],errorFirst:!0,promiseModule:Promise},e);let r=typeof t;if(!(t!==null&&(r==="object"||r==="function")))throw new TypeError(`Expected \`input\` to be a \`Function\` or \`Object\`, got \`${t===null?"null":r}\``);let n=s=>{let a=o=>typeof o=="string"?s===o:o.test(s);return e.include?e.include.some(a):!e.exclude.some(a)},i;r==="function"?i=function(...s){return e.excludeMain?t(...s):mE(t,e).apply(this,s)}:i=Object.create(Object.getPrototypeOf(t));for(let s in t){let a=t[s];i[s]=typeof a=="function"&&n(s)?mE(a,e):a}return i}});var AE=I((MZ,kE)=>{p();function wE(t){return Array.isArray(t)?t:[t]}var Yg="",yE=" ",zg="\\",y3=/^\s+$/,b3=/(?:[^\\]|^)\\$/,_3=/^\\!/,x3=/^\\#/,S3=/\r?\n/g,E3=/^\.*\/|^\.+$/,Vg="/",xE="node-ignore";typeof Symbol!="undefined"&&(xE=Symbol.for("node-ignore"));var bE=xE,k3=(t,e,r)=>Object.defineProperty(t,e,{value:r}),A3=/([0-z])-([0-z])/g,SE=()=>!1,C3=t=>t.replace(A3,(e,r,n)=>r.charCodeAt(0)<=n.charCodeAt(0)?e:Yg),T3=t=>{let{length:e}=t;return t.slice(0,e-e%2)},P3=[[/^\uFEFF/,()=>Yg],[/((?:\\\\)*?)(\\?\s+)$/,(t,e,r)=>e+(r.indexOf("\\")===0?yE:Yg)],[/(\\+?)\s/g,(t,e)=>{let{length:r}=e;return e.slice(0,r-r%2)+yE}],[/[\\$.|*+(){^]/g,t=>`\\${t}`],[/(?!\\)\?/g,()=>"[^/]"],[/^\//,()=>"^"],[/\//g,()=>"\\/"],[/^\^*\\\*\\\*\\\//,()=>"^(?:.*\\/)?"],[/^(?=[^^])/,function(){return/\/(?!$)/.test(this)?"^":"(?:^|\\/)"}],[/\\\/\\\*\\\*(?=\\\/|$)/g,(t,e,r)=>e+6{let n=r.replace(/\\\*/g,"[^\\/]*");return e+n}],[/\\\\\\(?=[$.|*+(){^])/g,()=>zg],[/\\\\/g,()=>zg],[/(\\)?\[([^\]/]*?)(\\*)($|\])/g,(t,e,r,n,i)=>e===zg?`\\[${r}${T3(n)}${i}`:i==="]"&&n.length%2===0?`[${C3(r)}${n}]`:"[]"],[/(?:[^*])$/,t=>/\/$/.test(t)?`${t}$`:`${t}(?=$|\\/$)`],[/(\^|\\\/)?\\\*$/,(t,e)=>`${e?`${e}[^/]+`:"[^/]*"}(?=$|\\/$)`]],_E=Object.create(null),R3=(t,e)=>{let r=_E[t];return r||(r=P3.reduce((n,[i,s])=>n.replace(i,s.bind(t)),t),_E[t]=r),e?new RegExp(r,"i"):new RegExp(r)},Kg=t=>typeof t=="string",$3=t=>t&&Kg(t)&&!y3.test(t)&&!b3.test(t)&&t.indexOf("#")!==0,I3=t=>t.split(S3),Xg=class{constructor(e,r,n,i){this.origin=e,this.pattern=r,this.negative=n,this.regex=i}},F3=(t,e)=>{let r=t,n=!1;t.indexOf("!")===0&&(n=!0,t=t.substr(1)),t=t.replace(_3,"!").replace(x3,"#");let i=R3(t,e);return new Xg(r,t,n,i)},O3=(t,e)=>{throw new e(t)},qi=(t,e,r)=>Kg(t)?t?qi.isNotRelative(t)?r(`path should be a \`path.relative()\`d string, but got "${e}"`,RangeError):!0:r("path must not be empty",TypeError):r(`path must be a string, but got \`${e}\``,TypeError),EE=t=>E3.test(t);qi.isNotRelative=EE;qi.convert=t=>t;var Zg=class{constructor({ignorecase:e=!0,ignoreCase:r=e,allowRelativePaths:n=!1}={}){k3(this,bE,!0),this._rules=[],this._ignoreCase=r,this._allowRelativePaths=n,this._initCache()}_initCache(){this._ignoreCache=Object.create(null),this._testCache=Object.create(null)}_addPattern(e){if(e&&e[bE]){this._rules=this._rules.concat(e._rules),this._added=!0;return}if($3(e)){let r=F3(e,this._ignoreCase);this._added=!0,this._rules.push(r)}}add(e){return this._added=!1,wE(Kg(e)?I3(e):e).forEach(this._addPattern,this),this._added&&this._initCache(),this}addPattern(e){return this.add(e)}_testOne(e,r){let n=!1,i=!1;return this._rules.forEach(s=>{let{negative:a}=s;if(i===a&&n!==i||a&&!n&&!i&&!r)return;s.regex.test(e)&&(n=!a,i=a)}),{ignored:n,unignored:i}}_test(e,r,n,i){let s=e&&qi.convert(e);return qi(s,e,this._allowRelativePaths?SE:O3),this._t(s,r,n,i)}_t(e,r,n,i){if(e in r)return r[e];if(i||(i=e.split(Vg)),i.pop(),!i.length)return r[e]=this._testOne(e,n);let s=this._t(i.join(Vg)+Vg,r,n,i);return r[e]=s.ignored?s:this._testOne(e,n)}ignores(e){return this._test(e,this._ignoreCache,!1).ignored}createFilter(){return e=>!this.ignores(e)}filter(e){return wE(e).filter(this.createFilter())}test(e){return this._test(e,this._testCache,!0)}},Ed=t=>new Zg(t),M3=t=>qi(t&&qi.convert(t),t,SE);Ed.isPathValid=M3;Ed.default=Ed;kE.exports=Ed;if(typeof process!="undefined"&&(process.env&&process.env.IGNORE_TEST_WIN32||process.platform==="win32")){let t=r=>/^\\\\\?\\/.test(r)||/["<>|\u0000-\u001F]+/u.test(r)?r:r.replace(/\\/g,"/");qi.convert=t;let e=/^[a-z]:\//i;qi.isNotRelative=r=>e.test(r)||EE(r)}});var TE=I((LZ,CE)=>{"use strict";p();function D3(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fi(t,e,r){return e=e instanceof RegExp?e:new RegExp(D3(e),"g"),t.replace(e,r)}var L3={clean:function(e){if(typeof e!="string")throw new Error("Expected a string, received: "+e);return e=fi(e,"./","/"),e=fi(e,"..","."),e=fi(e," ","-"),e=fi(e,/^[~^:?*\\\-]/g,""),e=fi(e,/[~^:?*\\]/g,"-"),e=fi(e,/[~^:?*\\\-]$/g,""),e=fi(e,"@{","-"),e=fi(e,/\.$/g,""),e=fi(e,/\/$/g,""),e=fi(e,/\.lock$/g,""),e}};CE.exports=L3});var RE=I((BZ,PE)=>{p();PE.exports=function(t,e){var r=t,n=e,i=r.length,s=n.length,a=!1,o=null,l=i+1,c=[],u=[],f=[],d="",h=-1,m=0,g=1,v,w,b=function(){i>=s&&(v=r,w=i,r=n,n=v,i=s,s=w,a=!0,l=i+1)},k=function(y,S,_){return{x:y,y:S,k:_}},x=function(y,S){return{elem:y,t:S}},E=function(y,S,_){var C,P,N;for(S>_?C=c[y-1+l]:C=c[y+1+l],N=Math.max(S,_),P=N-y;P=0;--N)for(;CP-C?(a?f[f.length]=new x(n[P],h):f[f.length]=new x(n[P],g),++_,++P):y[N].y-y[N].x=y+1;--H)_[H+l]=E(H,_[H-1+l]+1,_[H+1+l]);_[y+l]=E(y,_[y-1+l]+1,_[y+1+l])}while(_[y+l]!==s);for(o=y+2*C,P=c[y+l],N=[];P!==-1;)N[N.length]=new k(u[P].x,u[P].y,null),P=u[P].k;A(N)}}}});var FE=I((UZ,IE)=>{p();var N3=RE();function B3(t,e){var r=new N3(t,e);r.compose();for(var n=r.getses(),i,s,a=t.length-1,o=e.length-1,l=n.length-1;l>=0;--l)n[l].t===r.SES_COMMON?(s?(s.chain={file1index:a,file2index:o,chain:null},s=s.chain):(i={file1index:a,file2index:o,chain:null},s=i),a--,o--):n[l].t===r.SES_DELETE?a--:n[l].t===r.SES_ADD&&o--;var c={file1index:-1,file2index:-1,chain:null};return s?(s.chain=c,i):c}function $E(t,e){for(var r=[],n=t.length,i=e.length,s=B3(t,e);s!==null;s=s.chain){var a=n-s.file1index-1,o=i-s.file2index-1;n=s.file1index,i=s.file2index,(a||o)&&r.push({file1:[n+1,a],file2:[i+1,o]})}return r.reverse(),r}function H3(t,e,r){var n,i=$E(e,t),s=$E(e,r),a=[];function o(B,H){a.push([B.file1[0],H,B.file1[1],B.file2[0],B.file2[1]])}for(n=0;nc&&(l.push([1,c,B-c]),c=B)}for(var f=0;fg)break;g=Math.max(g,w+v[2]),f++}if(u(m),d==f)h[4]>0&&l.push([h[1],h[3],h[4]]);else{var b={0:[t.length,-1,e.length,-1],2:[r.length,-1,e.length,-1]};for(n=d;n<=f;n++){h=a[n];var k=h[1],x=b[k],E=h[0],A=E+h[2],y=h[3],S=y+h[4];x[0]=Math.min(y,x[0]),x[1]=Math.max(S,x[1]),x[2]=Math.min(E,x[2]),x[3]=Math.max(A,x[3])}var _=b[0][0]+(m-b[0][2]),C=b[0][1]+(g-b[0][3]),P=b[2][0]+(m-b[2][2]),N=b[2][1]+(g-b[2][3]);l.push([-1,_,C-_,m,g-m,P,N-P])}c=g}return u(e.length),l}function U3(t,e,r){var n=[],i=[t,e,r],s=H3(t,e,r),a=[];function o(){a.length&&n.push({ok:a}),a=[]}function l(h){for(var m=0;m{"use strict";p();Object.defineProperty(Y,"__esModule",{value:!0});function Ds(t){return t&&typeof t=="object"&&"default"in t?t.default:t}var Wc=Ds(b_()),rk=Ds(k1()),G3=Ds(C1()),xv=Ds(pE()),kd=Ds(vE()),j3=Ds(AE()),zc=Ds(TE()),q3=Ds(FE()),Re=class t extends Error{constructor(e){super(e),this.caller=""}toJSON(){return{code:this.code,data:this.data,caller:this.caller,message:this.message,stack:this.stack}}fromJSON(e){let r=new t(e.message);return r.code=e.code,r.data=e.data,r.caller=e.caller,r.stack=e.stack,r}get isIsomorphicGitError(){return!0}},Vc=class t extends Re{constructor(e){super(`Modifying the index is not possible because you have unmerged files: ${e.toString}. Fix them up in the work tree, and then use 'git add/rm as appropriate to mark resolution and make a commit.`),this.code=this.name=t.code,this.data={filepaths:e}}};Vc.code="UnmergedPathsError";var he=class t extends Re{constructor(e){super(`An internal error caused this command to fail. + +If you're not a developer, report the bug to the developers of the application you're using. If this is a bug in isomorphic-git then you should create a proper bug yourselves. The bug should include a minimal reproduction and details about the version and environment. + +Please file a bug report at https://github.com/isomorphic-git/isomorphic-git/issues with this error message: ${e}`),this.code=this.name=t.code,this.data={message:e}}};he.code="InternalError";var zo=class t extends Re{constructor(e){super(`The filepath "${e}" contains unsafe character sequences`),this.code=this.name=t.code,this.data={filepath:e}}};zo.code="UnsafeFilepathError";var mn=class{constructor(e){this.buffer=e,this._start=0}eof(){return this._start>=this.buffer.length}tell(){return this._start}seek(e){this._start=e}slice(e){let r=this.buffer.slice(this._start,this._start+e);return this._start+=e,r}toString(e,r){let n=this.buffer.toString(e,this._start,this._start+r);return this._start+=r,n}write(e,r,n){let i=this.buffer.write(e,this._start,r,n);return this._start+=r,i}copy(e,r,n){let i=e.copy(this.buffer,this._start,r,n);return this._start+=i,i}readUInt8(){let e=this.buffer.readUInt8(this._start);return this._start+=1,e}writeUInt8(e){let r=this.buffer.writeUInt8(e,this._start);return this._start+=1,r}readUInt16BE(){let e=this.buffer.readUInt16BE(this._start);return this._start+=2,e}writeUInt16BE(e){let r=this.buffer.writeUInt16BE(e,this._start);return this._start+=2,r}readUInt32BE(){let e=this.buffer.readUInt32BE(this._start);return this._start+=4,e}writeUInt32BE(e){let r=this.buffer.writeUInt32BE(e,this._start);return this._start+=4,r}};function Nd(t,e){return-(te)}function nk(t,e){return Nd(t.path,e.path)}function ik(t){let e=t>0?t>>12:0;e!==4&&e!==8&&e!==10&&e!==14&&(e=8);let r=t&511;return r&73?r=493:r=420,e!==8&&(r=0),(e<<12)+r}var di=2**32;function OE(t,e,r,n){if(t!==void 0&&e!==void 0)return[t,e];r===void 0&&(r=n.valueOf());let i=Math.floor(r/1e3),s=(r-i*1e3)*1e6;return[i,s]}function Vo(t){let[e,r]=OE(t.ctimeSeconds,t.ctimeNanoseconds,t.ctimeMs,t.ctime),[n,i]=OE(t.mtimeSeconds,t.mtimeNanoseconds,t.mtimeMs,t.mtime);return{ctimeSeconds:e%di,ctimeNanoseconds:r%di,mtimeSeconds:n%di,mtimeNanoseconds:i%di,dev:t.dev%di,ino:t.ino%di,mode:ik(t.mode%di),uid:t.uid%di,gid:t.gid%di,size:t.size>-1?t.size%di:0}}function W3(t){let e="";for(let r of new Uint8Array(t))r<16&&(e+="0"),e+=r.toString(16);return e}var Qg=null;async function zi(t){return Qg===null&&(Qg=await V3()),Qg?sk(t):z3(t)}function z3(t){return new rk().update(t).digest("hex")}async function sk(t){let e=await crypto.subtle.digest("SHA-1",t);return W3(e)}async function V3(){try{return await sk(new Uint8Array([]))==="da39a3ee5e6b4b0d3255bfef95601890afd80709"}catch(t){}return!1}function Y3(t){return{assumeValid:!!(t&32768),extended:!!(t&16384),stage:(t&12288)>>12,nameLength:t&4095}}function X3(t){let e=t.flags;return e.extended=!1,e.nameLength=Math.min(Buffer.from(t.path).length,4095),(e.assumeValid?32768:0)+(e.extended?16384:0)+((e.stage&3)<<12)+(e.nameLength&4095)}var uv=class t{constructor(e,r){this._dirty=!1,this._unmergedPaths=r||new Set,this._entries=e||new Map}_addEntry(e){if(e.flags.stage===0)e.stages=[e],this._entries.set(e.path,e),this._unmergedPaths.delete(e.path);else{let r=this._entries.get(e.path);r||(this._entries.set(e.path,e),r=e),r.stages[e.flags.stage]=e,this._unmergedPaths.add(e.path)}}static async from(e){if(Buffer.isBuffer(e))return t.fromBuffer(e);if(e===null)return new t(null);throw new he("invalid type passed to GitIndex.from")}static async fromBuffer(e){if(e.length===0)throw new he("Index file is empty (.git/index)");let r=new t,n=new mn(e),i=n.toString("utf8",4);if(i!=="DIRC")throw new he(`Invalid dircache magic file number: ${i}`);let s=await zi(e.slice(0,-20)),a=e.slice(-20).toString("hex");if(a!==s)throw new he(`Invalid checksum in GitIndex buffer: expected ${a} but saw ${s}`);let o=n.readUInt32BE();if(o!==2)throw new he(`Unsupported dircache version: ${o}`);let l=n.readUInt32BE(),c=0;for(;!n.eof()&&ce.stages.length>1?e.stages.filter(r=>r):e)}*[Symbol.iterator](){for(let e of this.entries)yield e}insert({filepath:e,stats:r,oid:n,stage:i=0}){r||(r={ctimeSeconds:0,ctimeNanoseconds:0,mtimeSeconds:0,mtimeNanoseconds:0,dev:0,ino:0,mode:0,uid:0,gid:0,size:0}),r=Vo(r);let s=Buffer.from(e),a={ctimeSeconds:r.ctimeSeconds,ctimeNanoseconds:r.ctimeNanoseconds,mtimeSeconds:r.mtimeSeconds,mtimeNanoseconds:r.mtimeNanoseconds,dev:r.dev,ino:r.ino,mode:r.mode||33188,uid:r.uid,gid:r.gid,size:r.size,path:e,oid:n,flags:{assumeValid:!1,extended:!1,stage:i,nameLength:s.length<4095?s.length:4095},stages:[]};this._addEntry(a),this._dirty=!0}delete({filepath:e}){if(this._entries.has(e))this._entries.delete(e);else for(let r of this._entries.keys())r.startsWith(e+"/")&&this._entries.delete(r);this._unmergedPaths.has(e)&&this._unmergedPaths.delete(e),this._dirty=!0}clear(){this._entries.clear(),this._dirty=!0}has({filepath:e}){return this._entries.has(e)}render(){return this.entries.map(e=>`${e.mode.toString(8)} ${e.oid} ${e.path}`).join(` +`)}static async _entryToBuffer(e){let r=Buffer.from(e.path),n=Math.ceil((62+r.length+1)/8)*8,i=Buffer.alloc(n),s=new mn(i),a=Vo(e);return s.writeUInt32BE(a.ctimeSeconds),s.writeUInt32BE(a.ctimeNanoseconds),s.writeUInt32BE(a.mtimeSeconds),s.writeUInt32BE(a.mtimeNanoseconds),s.writeUInt32BE(a.dev),s.writeUInt32BE(a.ino),s.writeUInt32BE(a.mode),s.writeUInt32BE(a.uid),s.writeUInt32BE(a.gid),s.writeUInt32BE(a.size),s.write(e.oid,20,"hex"),s.writeUInt16BE(X3(e)),s.write(e.path,r.length,"utf8"),i}async toObject(){let e=Buffer.alloc(12),r=new mn(e);r.write("DIRC",4,"utf8"),r.writeUInt32BE(2),r.writeUInt32BE(this.entriesFlat.length);let n=[];for(let o of this.entries)if(n.push(t._entryToBuffer(o)),o.stages.length>1)for(let l of o.stages)l&&l!==o&&n.push(t._entryToBuffer(l));n=await Promise.all(n);let i=Buffer.concat(n),s=Buffer.concat([e,i]),a=await zi(s);return Buffer.concat([s,Buffer.from(a,"hex")])}};function Td(t,e,r=!0,n=!0){let i=Vo(t),s=Vo(e);return r&&i.mode!==s.mode||i.mtimeSeconds!==s.mtimeSeconds||i.ctimeSeconds!==s.ctimeSeconds||i.uid!==s.uid||i.gid!==s.gid||n&&i.ino!==s.ino||i.size!==s.size}var Jg=null,ev=Symbol("IndexCache");function Z3(){return{map:new Map,stats:new Map}}async function K3(t,e,r){let[n,i]=await Promise.all([t.lstat(e),t.read(e)]),s=await uv.from(i);r.map.set(e,s),r.stats.set(e,n)}async function Q3(t,e,r){let n=r.stats.get(e);if(n===void 0)return!0;if(n===null)return!1;let i=await t.lstat(e);return i===null?!1:Td(n,i)}var ht=class{static async acquire({fs:e,gitdir:r,cache:n,allowUnmerged:i=!0},s){n[ev]||(n[ev]=Z3());let a=`${r}/index`;Jg===null&&(Jg=new Wc({maxPending:1/0}));let o,l=[];return await Jg.acquire(a,async()=>{let c=n[ev];await Q3(e,a,c)&&await K3(e,a,c);let u=c.map.get(a);if(l=u.unmergedPaths,l.length&&!i)throw new Vc(l);if(o=await s(u),u._dirty){let f=await u.toObject();await e.write(a,f),c.stats.set(a,await e.lstat(a)),u._dirty=!1}}),o}};function Pd(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return e>-1&&(t=t.slice(e+1)),t}function Sa(t){let e=Math.max(t.lastIndexOf("/"),t.lastIndexOf("\\"));return e===-1?".":e===0?"/":t.slice(0,e)}function ak(t){let e=new Map,r=function(i){if(!e.has(i)){let s={type:"tree",fullpath:i,basename:Pd(i),metadata:{},children:[]};e.set(i,s),s.parent=r(Sa(i)),s.parent&&s.parent!==s&&s.parent.children.push(s)}return e.get(i)},n=function(i,s){if(!e.has(i)){let a={type:"blob",fullpath:i,basename:Pd(i),metadata:s,parent:r(Sa(i)),children:[]};a.parent&&a.parent.children.push(a),e.set(i,a)}return e.get(i)};r(".");for(let i of t)n(i.path,i);return e}function J3(t){switch(t){case 16384:return"tree";case 33188:return"blob";case 33261:return"blob";case 40960:return"blob";case 57344:return"commit"}throw new he(`Unexpected GitTree entry mode: ${t.toString(8)}`)}var fv=class{constructor({fs:e,gitdir:r,cache:n}){this.treePromise=ht.acquire({fs:e,gitdir:r,cache:n},async function(s){return ak(s.entries)});let i=this;this.ConstructEntry=class{constructor(a){this._fullpath=a,this._type=!1,this._mode=!1,this._stat=!1,this._oid=!1}async type(){return i.type(this)}async mode(){return i.mode(this)}async stat(){return i.stat(this)}async content(){return i.content(this)}async oid(){return i.oid(this)}}}async readdir(e){let r=e._fullpath,i=(await this.treePromise).get(r);if(!i||i.type==="blob")return null;if(i.type!=="tree")throw new Error(`ENOTDIR: not a directory, scandir '${r}'`);let s=i.children.map(a=>a.fullpath);return s.sort(Nd),s}async type(e){return e._type===!1&&await e.stat(),e._type}async mode(e){return e._mode===!1&&await e.stat(),e._mode}async stat(e){if(e._stat===!1){let n=(await this.treePromise).get(e._fullpath);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${e._fullpath}'`);let i=n.type==="tree"?{}:Vo(n.metadata);e._type=n.type==="tree"?"tree":J3(i.mode),e._mode=i.mode,n.type==="tree"?e._stat=void 0:e._stat=i}return e._stat}async content(e){}async oid(e){if(e._oid===!1){let n=(await this.treePromise).get(e._fullpath);e._oid=n.metadata.oid}return e._oid}},Bd=Symbol("GitWalkSymbol");function Ca(){let t=Object.create(null);return Object.defineProperty(t,Bd,{value:function({fs:e,gitdir:r,cache:n}){return new fv({fs:e,gitdir:r,cache:n})}}),Object.freeze(t),t}var Be=class t extends Re{constructor(e){super(`Could not find ${e}.`),this.code=this.name=t.code,this.data={what:e}}};Be.code="NotFoundError";var fr=class t extends Re{constructor(e,r,n,i){super(`Object ${e} ${i?`at ${i}`:""}was anticipated to be a ${n} but it is a ${r}.`),this.code=this.name=t.code,this.data={oid:e,actual:r,expected:n,filepath:i}}};fr.code="ObjectTypeError";var Rs=class t extends Re{constructor(e){super(`Expected a 40-char hex object id but saw "${e}".`),this.code=this.name=t.code,this.data={value:e}}};Rs.code="InvalidOidError";var Yc=class t extends Re{constructor(e){super(`Could not find a fetch refspec for remote "${e}". Make sure the config file has an entry like the following: +[remote "${e}"] + fetch = +refs/heads/*:refs/remotes/origin/* +`),this.code=this.name=t.code,this.data={remote:e}}};Yc.code="NoRefspecError";var Rd=class t{constructor(e){if(this.refs=new Map,this.parsedConfig=[],e){let r=null;this.parsedConfig=e.trim().split(` +`).map(n=>{if(/^\s*#/.test(n))return{line:n,comment:!0};let i=n.indexOf(" ");if(n.startsWith("^")){let s=n.slice(1);return this.refs.set(r+"^{}",s),{line:n,ref:r,peeled:s}}else{let s=n.slice(0,i);return r=n.slice(i+1),this.refs.set(r,s),{line:n,ref:r,oid:s}}})}return this}static from(e){return new t(e)}delete(e){this.parsedConfig=this.parsedConfig.filter(r=>r.ref!==e),this.refs.delete(e)}toString(){return this.parsedConfig.map(({line:e})=>e).join(` +`)+` +`}},$d=class t{constructor({remotePath:e,localPath:r,force:n,matchPrefix:i}){Object.assign(this,{remotePath:e,localPath:r,force:n,matchPrefix:i})}static from(e){let[r,n,i,s,a]=e.match(/^(\+?)(.*?)(\*?):(.*?)(\*?)$/).slice(1),o=r==="+",l=i==="*";if(l!==(a==="*"))throw new he("Invalid refspec");return new t({remotePath:n,localPath:s,force:o,matchPrefix:l})}translate(e){if(this.matchPrefix){if(e.startsWith(this.remotePath))return this.localPath+e.replace(this.remotePath,"")}else if(e===this.remotePath)return this.localPath;return null}reverseTranslate(e){if(this.matchPrefix){if(e.startsWith(this.localPath))return this.remotePath+e.replace(this.localPath,"")}else if(e===this.localPath)return this.remotePath;return null}},dv=class t{constructor(e=[]){this.rules=e}static from(e){let r=[];for(let n of e)r.push($d.from(n));return new t(r)}add(e){let r=$d.from(e);this.rules.push(r)}translate(e){let r=[];for(let n of this.rules)for(let i of e){let s=n.translate(i);s&&r.push([i,s])}return r}translateOne(e){let r=null;for(let n of this.rules){let i=n.translate(e);i&&(r=i)}return r}localNamespaces(){return this.rules.filter(e=>e.matchPrefix).map(e=>e.localPath.replace(/\/$/,""))}};function e8(t,e){let r=t.replace(/\^\{\}$/,""),n=e.replace(/\^\{\}$/,""),i=-(rn);return i===0?t.endsWith("^{}")?1:-1:i}function t8(t,e){let r="",n=0,i=-1,s=0,a="\0";for(let o=0;o<=t.length;++o){if(o2){let l=r.lastIndexOf("/");l===-1?(r="",n=0):(r=r.slice(0,l),n=r.length-1-r.lastIndexOf("/")),i=o,s=0;continue}else if(r.length!==0){r="",n=0,i=o,s=0;continue}}e&&(r+=r.length>0?"/..":"..",n=2)}else r.length>0?r+="/"+t.slice(i+1,o):r=t.slice(i+1,o),n=o-i-1;i=o,s=0}else a==="."&&s!==-1?++s:s=-1}return r}function r8(t){if(!t.length)return".";let e=t[0]==="/",r=t.at(-1)==="/";return t=t8(t,!e),t.length?(r&&(t+="/"),e?`/${t}`:t):e?"/":r?"./":"."}function D(...t){if(t.length===0)return".";let e;for(let r=0;r0&&(e===void 0?e=n:e+="/"+n)}return e===void 0?".":r8(e)}var n8=t=>{if(typeof t=="number")return t;t=t.toLowerCase();let e=parseInt(t);return t.endsWith("k")&&(e*=1024),t.endsWith("m")&&(e*=1024*1024),t.endsWith("g")&&(e*=1024*1024*1024),e},qc=t=>{if(typeof t=="boolean")return t;if(t=t.trim().toLowerCase(),t==="true"||t==="yes"||t==="on")return!0;if(t==="false"||t==="no"||t==="off")return!1;throw Error(`Expected 'true', 'false', 'yes', 'no', 'on', or 'off', but got ${t}`)},ME={core:{filemode:qc,bare:qc,logallrefupdates:qc,symlinks:qc,ignorecase:qc,bigFileThreshold:n8}},i8=/^\[([A-Za-z0-9-.]+)(?: "(.*)")?\]$/,s8=/^[A-Za-z0-9-.]+$/,a8=/^([A-Za-z][A-Za-z-]*)(?: *= *(.*))?$/,o8=/^[A-Za-z][A-Za-z-]*$/,l8=/^(.*?)( *[#;].*)$/,c8=t=>{let e=i8.exec(t);if(e!=null){let[r,n]=e.slice(1);return[r,n]}return null},u8=t=>{let e=a8.exec(t);if(e!=null){let[r,n="true"]=e.slice(1),i=f8(n),s=d8(i);return[r,s]}return null},f8=t=>{let e=l8.exec(t);if(e==null)return t;let[r,n]=e.slice(1);return DE(r)&&DE(n)?`${r}${n}`:r},DE=t=>(t.match(/(?:^|[^\\])"/g)||[]).length%2!==0,d8=t=>t.split("").reduce((e,r,n,i)=>{let s=r==='"'&&i[n-1]!=="\\",a=r==="\\"&&i[n+1]==='"';return s||a?e:e+r},""),LE=t=>t!=null?t.toLowerCase():null,hv=(t,e,r)=>[LE(t),e,LE(r)].filter(n=>n!=null).join("."),NE=t=>{let e=t.split("."),r=e.shift(),n=e.pop(),i=e.length?e.join("."):void 0;return{section:r,subsection:i,name:n,path:hv(r,i,n),sectionPath:hv(r,i,null),isSection:!!r}},h8=(t,e)=>t.reduce((r,n,i)=>e(n)?i:r,-1),pv=class t{constructor(e){let r=null,n=null;this.parsedConfig=e?e.split(` +`).map(i=>{let s=null,a=null,o=i.trim(),l=c8(o),c=l!=null;if(c)[r,n]=l;else{let f=u8(o);f!=null&&([s,a]=f)}let u=hv(r,n,s);return{line:i,isSection:c,section:r,subsection:n,name:s,value:a,path:u}}):[]}static from(e){return new t(e)}async get(e,r=!1){let n=NE(e).path,i=this.parsedConfig.filter(s=>s.path===n).map(({section:s,name:a,value:o})=>{let l=ME[s]&&ME[s][a];return l?l(o):o});return r?i:i.pop()}async getall(e){return this.get(e,!0)}async getSubsections(e){return this.parsedConfig.filter(r=>r.isSection&&r.section===e).map(r=>r.subsection)}async deleteSection(e,r){this.parsedConfig=this.parsedConfig.filter(n=>!(n.section===e&&n.subsection===r))}async append(e,r){return this.set(e,r,!0)}async set(e,r,n=!1){let{section:i,subsection:s,name:a,path:o,sectionPath:l,isSection:c}=NE(e),u=h8(this.parsedConfig,f=>f.path===o);if(r==null)u!==-1&&this.parsedConfig.splice(u,1);else if(u!==-1){let f=this.parsedConfig[u],d=Object.assign({},f,{name:a,value:r,modified:!0});n?this.parsedConfig.splice(u+1,0,d):this.parsedConfig[u]=d}else{let f=this.parsedConfig.findIndex(h=>h.path===l),d={section:i,subsection:s,name:a,value:r,modified:!0,path:o};if(s8.test(i)&&o8.test(a))if(f>=0)this.parsedConfig.splice(f+1,0,d);else{let h={isSection:c,section:i,subsection:s,modified:!0,path:l};this.parsedConfig.push(h,d)}}}toString(){return this.parsedConfig.map(({line:e,section:r,subsection:n,name:i,value:s,modified:a=!1})=>a?i!=null&&s!=null?typeof s=="string"&&/[#;]/.test(s)?` ${i} = "${s}"`:` ${i} = ${s}`:n!=null?`[${r} "${n}"]`:`[${r}]`:e).join(` +`)}},lt=class{static async get({fs:e,gitdir:r}){let n=await e.read(`${r}/config`,{encoding:"utf8"});return pv.from(n)}static async save({fs:e,gitdir:r,config:n}){await e.write(`${r}/config`,n.toString(),{encoding:"utf8"})}},Ad=t=>[`${t}`,`refs/${t}`,`refs/tags/${t}`,`refs/heads/${t}`,`refs/remotes/${t}`,`refs/remotes/${t}/HEAD`],p8=["config","description","index","shallow","commondir"],tv;async function Ts(t,e){return tv===void 0&&(tv=new Wc),tv.acquire(t,e)}var z=class t{static async updateRemoteRefs({fs:e,gitdir:r,remote:n,refs:i,symrefs:s,tags:a,refspecs:o=void 0,prune:l=!1,pruneTags:c=!1}){for(let v of i.values())if(!v.match(/[0-9a-f]{40}/))throw new Rs(v);let u=await lt.get({fs:e,gitdir:r});if(!o){if(o=await u.getall(`remote.${n}.fetch`),o.length===0)throw new Yc(n);o.unshift(`+HEAD:refs/remotes/${n}/HEAD`)}let f=dv.from(o),d=new Map;if(c){let v=await t.listRefs({fs:e,gitdir:r,filepath:"refs/tags"});await t.deleteRefs({fs:e,gitdir:r,refs:v.map(w=>`refs/tags/${w}`)})}if(a){for(let v of i.keys())if(v.startsWith("refs/tags")&&!v.endsWith("^{}")&&!await t.exists({fs:e,gitdir:r,ref:v})){let w=i.get(v);d.set(v,w)}}let h=f.translate([...i.keys()]);for(let[v,w]of h){let b=i.get(v);d.set(w,b)}let m=f.translate([...s.keys()]);for(let[v,w]of m){let b=s.get(v),k=f.translateOne(b);k&&d.set(w,`ref: ${k}`)}let g=[];if(l){for(let v of f.localNamespaces()){let w=(await t.listRefs({fs:e,gitdir:r,filepath:v})).map(b=>`${v}/${b}`);for(let b of w)d.has(b)||g.push(b)}g.length>0&&await t.deleteRefs({fs:e,gitdir:r,refs:g})}for(let[v,w]of d)await Ts(v,async()=>e.write(D(r,v),`${w.trim()} +`,"utf8"));return{pruned:g}}static async writeRef({fs:e,gitdir:r,ref:n,value:i}){if(!i.match(/[0-9a-f]{40}/))throw new Rs(i);await Ts(n,async()=>e.write(D(r,n),`${i.trim()} +`,"utf8"))}static async writeSymbolicRef({fs:e,gitdir:r,ref:n,value:i}){await Ts(n,async()=>e.write(D(r,n),`ref: ${i.trim()} +`,"utf8"))}static async deleteRef({fs:e,gitdir:r,ref:n}){return t.deleteRefs({fs:e,gitdir:r,refs:[n]})}static async deleteRefs({fs:e,gitdir:r,refs:n}){await Promise.all(n.map(o=>e.rm(D(r,o))));let i=await Ts("packed-refs",async()=>e.read(`${r}/packed-refs`,{encoding:"utf8"})),s=Rd.from(i),a=s.refs.size;for(let o of n)s.refs.has(o)&&s.delete(o);s.refs.sizee.write(`${r}/packed-refs`,i,{encoding:"utf8"})))}static async resolve({fs:e,gitdir:r,ref:n,depth:i=void 0}){if(i!==void 0&&(i--,i===-1))return n;if(n.startsWith("ref: "))return n=n.slice(5),t.resolve({fs:e,gitdir:r,ref:n,depth:i});if(n.length===40&&/[0-9a-f]{40}/.test(n))return n;let s=await t.packedRefs({fs:e,gitdir:r}),a=Ad(n).filter(o=>!p8.includes(o));for(let o of a){let l=await Ts(o,async()=>await e.read(`${r}/${o}`,{encoding:"utf8"})||s.get(o));if(l)return t.resolve({fs:e,gitdir:r,ref:l.trim(),depth:i})}throw new Be(n)}static async exists({fs:e,gitdir:r,ref:n}){try{return await t.expand({fs:e,gitdir:r,ref:n}),!0}catch(i){return!1}}static async expand({fs:e,gitdir:r,ref:n}){if(n.length===40&&/[0-9a-f]{40}/.test(n))return n;let i=await t.packedRefs({fs:e,gitdir:r}),s=Ad(n);for(let a of s)if(await Ts(a,async()=>e.exists(`${r}/${a}`))||i.has(a))return a;throw new Be(n)}static async expandAgainstMap({ref:e,map:r}){let n=Ad(e);for(let i of n)if(await r.has(i))return i;throw new Be(e)}static resolveAgainstMap({ref:e,fullref:r=e,depth:n=void 0,map:i}){if(n!==void 0&&(n--,n===-1))return{fullref:r,oid:e};if(e.startsWith("ref: "))return e=e.slice(5),t.resolveAgainstMap({ref:e,fullref:r,depth:n,map:i});if(e.length===40&&/[0-9a-f]{40}/.test(e))return{fullref:r,oid:e};let s=Ad(e);for(let a of s){let o=i.get(a);if(o)return t.resolveAgainstMap({ref:o.trim(),fullref:a,depth:n,map:i})}throw new Be(e)}static async packedRefs({fs:e,gitdir:r}){let n=await Ts("packed-refs",async()=>e.read(`${r}/packed-refs`,{encoding:"utf8"}));return Rd.from(n).refs}static async listRefs({fs:e,gitdir:r,filepath:n}){let i=t.packedRefs({fs:e,gitdir:r}),s=null;try{s=await e.readdirDeep(`${r}/${n}`),s=s.map(a=>a.replace(`${r}/${n}/`,""))}catch(a){s=[]}for(let a of(await i).keys())a.startsWith(n)&&(a=a.replace(n+"/",""),s.includes(a)||s.push(a));return s.sort(e8),s}static async listBranches({fs:e,gitdir:r,remote:n}){return n?t.listRefs({fs:e,gitdir:r,filepath:`refs/remotes/${n}`}):t.listRefs({fs:e,gitdir:r,filepath:"refs/heads"})}static async listTags({fs:e,gitdir:r}){return(await t.listRefs({fs:e,gitdir:r,filepath:"refs/tags"})).filter(i=>!i.endsWith("^{}"))}};function m8(t,e){return Nd(BE(t),BE(e))}function BE(t){return t.mode==="040000"?t.path+"/":t.path}function ok(t){switch(t){case"040000":return"tree";case"100644":return"blob";case"100755":return"blob";case"120000":return"blob";case"160000":return"commit"}throw new he(`Unexpected GitTree entry mode: ${t}`)}function g8(t){let e=[],r=0;for(;r`${e.mode} ${e.type} ${e.oid} ${e.path}`).join(` +`)}toObject(){let e=[...this._entries];return e.sort(m8),Buffer.concat(e.map(r=>{let n=Buffer.from(r.mode.replace(/^0/,"")),i=Buffer.from(" "),s=Buffer.from(r.path,"utf8"),a=Buffer.from([0]),o=Buffer.from(r.oid,"hex");return Buffer.concat([n,i,s,a,o])}))}entries(){return this._entries}*[Symbol.iterator](){for(let e of this._entries)yield e}},$s=class{static wrap({type:e,object:r}){let n=`${e} ${r.length}\0`,i=n.length,s=i+r.length,a=new Uint8Array(s);for(let o=0;o>=1,i+=8;return n}function GE(t,e){let r=t.readUInt8(),n=128,i=15,s=112;if(r&n){let a=UE(t,r&i,4),o=UE(t,(r&s)>>4,3);return o===0&&(o=65536),e.slice(a,a+o)}else return t.slice(r)}function b8(t){let e=[t];return{next(){return Promise.resolve({done:e.length===0,value:e.pop()})},return(){return e=[],{}},[Symbol.asyncIterator](){return this}}}function ck(t){return t[Symbol.asyncIterator]?t[Symbol.asyncIterator]():t[Symbol.iterator]?t[Symbol.iterator]():t.next?t:b8(t)}var Id=class{constructor(e){if(typeof Buffer=="undefined")throw new Error("Missing Buffer dependency");this.stream=ck(e),this.buffer=null,this.cursor=0,this.undoCursor=0,this.started=!1,this._ended=!1,this._discardedBytes=0}eof(){return this._ended&&this.cursor===this.buffer.length}tell(){return this._discardedBytes+this.cursor}async byte(){if(!this.eof()&&(this.started||await this._init(),!(this.cursor===this.buffer.length&&(await this._loadnext(),this._ended))))return this._moveCursor(1),this.buffer[this.undoCursor]}async chunk(){if(!this.eof()&&(this.started||await this._init(),!(this.cursor===this.buffer.length&&(await this._loadnext(),this._ended))))return this._moveCursor(this.buffer.length),this.buffer.slice(this.undoCursor,this.cursor)}async read(e){if(!this.eof())return this.started||await this._init(),this.cursor+e>this.buffer.length&&(this._trim(),await this._accumulate(e)),this._moveCursor(e),this.buffer.slice(this.undoCursor,this.cursor)}async skip(e){this.eof()||(this.started||await this._init(),this.cursor+e>this.buffer.length&&(this._trim(),await this._accumulate(e)),this._moveCursor(e))}async undo(){this.cursor=this.undoCursor}async _next(){this.started=!0;let{done:e,value:r}=await this.stream.next();return e&&(this._ended=!0,!r)?Buffer.alloc(0):(r&&(r=Buffer.from(r)),r)}_trim(){this.buffer=this.buffer.slice(this.undoCursor),this.cursor-=this.undoCursor,this._discardedBytes+=this.undoCursor,this.undoCursor=0}_moveCursor(e){this.undoCursor=this.cursor,this.cursor+=e,this.cursor>this.buffer.length&&(this.cursor=this.buffer.length)}async _accumulate(e){if(this._ended)return;let r=[this.buffer];for(;this.cursor+e>_8(r);){let n=await this._next();if(this._ended)break;r.push(n)}this.buffer=Buffer.concat(r)}async _loadnext(){this._discardedBytes+=this.buffer.length,this.undoCursor=0,this.cursor=0,this.buffer=await this._next()}async _init(){this.buffer=await this._next()}};function _8(t){return t.reduce((e,r)=>e+r.length,0)}async function x8(t,e){let r=new Id(t),n=await r.read(4);if(n=n.toString("utf8"),n!=="PACK")throw new he(`Invalid PACK header '${n}'`);let i=await r.read(4);if(i=i.readUInt32BE(0),i!==2)throw new he(`Invalid packfile version: ${i}`);let s=await r.read(4);if(s=s.readUInt32BE(0),!(s<1))for(;!r.eof()&&s--;){let a=r.tell(),{type:o,length:l,ofs:c,reference:u}=await S8(r),f=new xv.Inflate;for(;!f.result;){let d=await r.chunk();if(!d)break;if(f.push(d,!1),f.err)throw new he(`Pako error: ${f.msg}`);if(f.result){if(f.result.length!==l)throw new he("Inflated object size is different from that stated in packfile.");await r.undo(),await r.read(d.length-f.strm.avail_in);let h=r.tell();await e({data:f.result,type:o,num:s,offset:a,end:h,reference:u,ofs:c})}}}}async function S8(t){let e=await t.byte(),r=e>>4&7,n=e&15;if(e&128){let a=4;do e=await t.byte(),n|=(e&127)<i+1<<7|s,-1)}function C8(t,e){let r=e,n=4,i=null;do i=t.readUInt8(),r|=(i&127)<2048*1024*1024)throw new he("To keep implementation simple, I haven't implemented the layer 5 feature needed to support packfiles > 2GB in size.");n.seek(n.tell()+4*255);let a=n.readUInt32BE(),o=[];for(let u=0;u{u===null&&(u=x);let E=Math.floor((u-x)*100/u);E!==f&&n&&await n({phase:"Receiving objects",loaded:u-x,total:u}),f=E,w=i[w],["commit","tree","blob","tag"].includes(w)?s[k]={type:w,offset:k}:w==="ofs-delta"?s[k]={type:w,offset:k}:w==="ref-delta"&&(s[k]={type:w,offset:k})});let d=Object.keys(s).map(Number);for(let[v,w]of d.entries()){let b=v+1===d.length?e.byteLength-20:d[v+1],k=s[w],x=G3.buf(e.slice(w,b))>>>0;k.end=b,k.crc=x}let h=new t({pack:Promise.resolve(e),packfileSha:a,crcs:l,hashes:o,offsets:c,getExternalRefDelta:r});f=null;let m=0,g=[0,0,0,0,0,0,0,0,0,0,0,0];for(let v in s){v=Number(v);let w=Math.floor(m*100/u);w!==f&&n&&await n({phase:"Resolving deltas",loaded:m,total:u}),m++,f=w;let b=s[v];if(!b.oid)try{h.readDepth=0,h.externalReadDepth=0;let{type:k,object:x}=await h.readSlice({start:v});g[h.readDepth]+=1;let E=await zi($s.wrap({type:k,object:x}));b.oid=E,o.push(E),c.set(E,v),l[E]=b.crc}catch(k){continue}}return o.sort(),h}async toBuffer(){let e=[],r=(c,u)=>{e.push(Buffer.from(c,u))};r("ff744f63","hex"),r("00000002","hex");let n=new mn(Buffer.alloc(256*4));for(let c=0;c<256;c++){let u=0;for(let f of this.hashes)parseInt(f.slice(0,2),16)<=c&&u++;n.writeUInt32BE(u)}e.push(n.buffer);for(let c of this.hashes)r(c,"hex");let i=new mn(Buffer.alloc(this.hashes.length*4));for(let c of this.hashes)i.writeUInt32BE(this.crcs[c]);e.push(i.buffer);let s=new mn(Buffer.alloc(this.hashes.length*4));for(let c of this.hashes)s.writeUInt32BE(this.offsets.get(c));e.push(s.buffer),r(this.packfileSha,"hex");let a=Buffer.concat(e),o=await zi(a),l=Buffer.alloc(20);return l.write(o,"hex"),Buffer.concat([a,l])}async load({pack:e}){this.pack=e}async unload(){this.pack=null}async read({oid:e}){if(!this.offsets.get(e)){if(this.getExternalRefDelta)return this.externalReadDepth++,this.getExternalRefDelta(e);throw new he(`Could not read object ${e} from packfile`)}let r=this.offsets.get(e);return this.readSlice({start:r})}async readSlice({start:e}){if(this.offsetCache[e])return Object.assign({},this.offsetCache[e]);this.readDepth++;let r={16:"commit",32:"tree",48:"blob",64:"tag",96:"ofs_delta",112:"ref_delta"};if(!this.pack)throw new he("Tried to read from a GitPackIndex with no packfile loaded into memory");let n=(await this.pack).slice(e),i=new mn(n),s=i.readUInt8(),a=s&112,o=r[a];if(o===void 0)throw new he("Unrecognized type: 0b"+a.toString(2));let l=s&15,c=l;s&128&&(c=C8(i,l));let f=null,d=null;if(o==="ofs_delta"){let m=A8(i),g=e-m;({object:f,type:o}=await this.readSlice({start:g}))}if(o==="ref_delta"){let m=i.slice(20).toString("hex");({object:f,type:o}=await this.read({oid:m}))}let h=n.slice(i.tell());if(d=Buffer.from(await uk(h)),d.byteLength!==c)throw new he(`Packfile told us object would have length ${c} but it had length ${d.byteLength}`);return f&&(d=Buffer.from(y8(d,f))),this.readDepth>3&&(this.offsetCache[e]={type:o,object:d}),{type:o,format:"content",object:d}}},Cd=Symbol("PackfileCache");async function T8({fs:t,filename:e,getExternalRefDelta:r,emitter:n,emitterPrefix:i}){let s=await t.read(e);return Xc.fromIdx({idx:s,getExternalRefDelta:r})}function Sv({fs:t,cache:e,filename:r,getExternalRefDelta:n,emitter:i,emitterPrefix:s}){e[Cd]||(e[Cd]=new Map);let a=e[Cd].get(r);return a||(a=T8({fs:t,filename:r,getExternalRefDelta:n,emitter:i,emitterPrefix:s}),e[Cd].set(r,a)),a}async function P8({fs:t,cache:e,gitdir:r,oid:n,format:i="content",getExternalRefDelta:s}){let a=await t.readdir(D(r,"objects/pack"));a=a.filter(o=>o.endsWith(".idx"));for(let o of a){let l=`${r}/objects/pack/${o}`,c=await Sv({fs:t,cache:e,filename:l,getExternalRefDelta:s});if(c.error)throw new he(c.error);if(c.offsets.has(n)){if(!c.pack){let f=l.replace(/idx$/,"pack");c.pack=t.read(f)}let u=await c.read({oid:n,getExternalRefDelta:s});return u.format="content",u.source=`objects/pack/${o.replace(/idx$/,"pack")}`,u}}return null}async function Xe({fs:t,cache:e,gitdir:r,oid:n,format:i="content"}){let s=u=>Xe({fs:t,cache:e,gitdir:r,oid:u}),a;if(n==="4b825dc642cb6eb9a060e54bf8d69288fbee4904"&&(a={format:"wrapped",object:Buffer.from("tree 0\0")}),a||(a=await lk({fs:t,gitdir:r,oid:n})),!a){if(a=await P8({fs:t,cache:e,gitdir:r,oid:n,getExternalRefDelta:s}),!a)throw new Be(n);return a}if(i==="deflated"||(a.format==="deflated"&&(a.object=Buffer.from(await uk(a.object)),a.format="wrapped"),i==="wrapped"))return a;let o=await zi(a.object);if(o!==n)throw new he(`SHA check failed! Expected ${n}, computed ${o}`);let{object:l,type:c}=$s.unwrap(a.object);if(a.type=c,a.object=l,a.format="content",i==="content")return a;throw new he(`invalid requested format "${i}"`)}var Mn=class t extends Re{constructor(e,r,n=!0){super(`Failed to create ${e} at ${r} because it already exists.${n?` (Hint: use 'force: true' parameter to overwrite existing ${e}.)`:""}`),this.code=this.name=t.code,this.data={noun:e,where:r,canForce:n}}};Mn.code="AlreadyExistsError";var Zc=class t extends Re{constructor(e,r,n){super(`Found multiple ${e} matching "${r}" (${n.join(", ")}). Use a longer abbreviation length to disambiguate them.`),this.code=this.name=t.code,this.data={nouns:e,short:r,matches:n}}};Zc.code="AmbiguousError";var Kc=class t extends Re{constructor(e){super(`Your local changes to the following files would be overwritten by checkout: ${e.join(", ")}`),this.code=this.name=t.code,this.data={filepaths:e}}};Kc.code="CheckoutConflictError";var Qc=class t extends Re{constructor(e,r){super(`Failed to checkout "${e}" because commit ${r} is not available locally. Do a git fetch to make the branch available locally.`),this.code=this.name=t.code,this.data={ref:e,oid:r}}};Qc.code="CommitNotFetchedError";var Jc=class t extends Re{constructor(){super("Empty response from git server."),this.code=this.name=t.code,this.data={}}};Jc.code="EmptyServerResponseError";var eu=class t extends Re{constructor(){super("A simple fast-forward merge was not possible."),this.code=this.name=t.code,this.data={}}};eu.code="FastForwardError";var tu=class t extends Re{constructor(e,r){super(`One or more branches were not updated: ${e}`),this.code=this.name=t.code,this.data={prettyDetails:e,result:r}}};tu.code="GitPushError";var Yo=class t extends Re{constructor(e,r,n){super(`HTTP Error: ${e} ${r}`),this.code=this.name=t.code,this.data={statusCode:e,statusMessage:r,response:n}}};Yo.code="HttpError";var Is=class t extends Re{constructor(e){let r="invalid filepath";e==="leading-slash"||e==="trailing-slash"?r='"filepath" parameter should not include leading or trailing directory separators because these can cause problems on some platforms.':e==="directory"&&(r='"filepath" should not be a directory.'),super(r),this.code=this.name=t.code,this.data={reason:e}}};Is.code="InvalidFilepathError";var Dn=class t extends Re{constructor(e,r){super(`"${e}" would be an invalid git reference. (Hint: a valid alternative would be "${r}".)`),this.code=this.name=t.code,this.data={ref:e,suggestion:r}}};Dn.code="InvalidRefNameError";var ru=class t extends Re{constructor(e){super(`Maximum search depth of ${e} exceeded.`),this.code=this.name=t.code,this.data={depth:e}}};ru.code="MaxDepthError";var Xo=class t extends Re{constructor(){super("Merges with conflicts are not supported yet."),this.code=this.name=t.code,this.data={}}};Xo.code="MergeNotSupportedError";var Zo=class t extends Re{constructor(e,r,n,i){super(`Automatic merge failed with one or more merge conflicts in the following files: ${e.toString()}. Fix conflicts then commit the result.`),this.code=this.name=t.code,this.data={filepaths:e,bothModified:r,deleteByUs:n,deleteByTheirs:i}}};Zo.code="MergeConflictError";var Kt=class t extends Re{constructor(e){super(`No name was provided for ${e} in the argument or in the .git/config file.`),this.code=this.name=t.code,this.data={role:e}}};Kt.code="MissingNameError";var Sr=class t extends Re{constructor(e){super(`The function requires a "${e}" parameter but none was provided.`),this.code=this.name=t.code,this.data={parameter:e}}};Sr.code="MissingParameterError";var nu=class t extends Re{constructor(e){super('There are multiple errors that were thrown by the method. Please refer to the "errors" property to see more'),this.code=this.name=t.code,this.data={errors:e},this.errors=e}};nu.code="MultipleGitError";var Ea=class t extends Re{constructor(e,r){super(`Expected "${e}" but received "${r}".`),this.code=this.name=t.code,this.data={expected:e,actual:r}}};Ea.code="ParseError";var Ko=class t extends Re{constructor(e){let r="";e==="not-fast-forward"?r=" because it was not a simple fast-forward":e==="tag-exists"&&(r=" because tag already exists"),super(`Push rejected${r}. Use "force: true" to override.`),this.code=this.name=t.code,this.data={reason:e}}};Ko.code="PushRejectedError";var Ps=class t extends Re{constructor(e,r){super(`Remote does not support the "${e}" so the "${r}" parameter cannot be used.`),this.code=this.name=t.code,this.data={capability:e,parameter:r}}};Ps.code="RemoteCapabilityError";var iu=class t extends Re{constructor(e,r){super(`Remote did not reply using the "smart" HTTP protocol. Expected "001e# service=git-upload-pack" but received: ${e}`),this.code=this.name=t.code,this.data={preview:e,response:r}}};iu.code="SmartHttpError";var su=class t extends Re{constructor(e,r,n){super(`Git remote "${e}" uses an unrecognized transport protocol: "${r}"`),this.code=this.name=t.code,this.data={url:e,transport:r,suggestion:n}}};su.code="UnknownTransportError";var au=class t extends Re{constructor(e){super(`Cannot parse remote URL: "${e}"`),this.code=this.name=t.code,this.data={url:e}}};au.code="UrlParseError";var Qo=class t extends Re{constructor(){super("The operation was canceled."),this.code=this.name=t.code,this.data={}}};Qo.code="UserCanceledError";var ou=class t extends Re{constructor(e){super(`Could not merge index: Entry for '${e}' is not up to date. Either reset the index entry to HEAD, or stage your unstaged changes.`),this.code=this.name=t.code,this.data={filepath:e}}};ou.code="IndexResetError";var lu=class t extends Re{constructor(e){super(`"${e}" does not point to any commit. You're maybe working on a repository with no commits yet. `),this.code=this.name=t.code,this.data={ref:e}}};lu.code="NoCommitError";var fk=Object.freeze({__proto__:null,AlreadyExistsError:Mn,AmbiguousError:Zc,CheckoutConflictError:Kc,CommitNotFetchedError:Qc,EmptyServerResponseError:Jc,FastForwardError:eu,GitPushError:tu,HttpError:Yo,InternalError:he,InvalidFilepathError:Is,InvalidOidError:Rs,InvalidRefNameError:Dn,MaxDepthError:ru,MergeNotSupportedError:Xo,MergeConflictError:Zo,MissingNameError:Kt,MissingParameterError:Sr,MultipleGitError:nu,NoRefspecError:Yc,NotFoundError:Be,ObjectTypeError:fr,ParseError:Ea,PushRejectedError:Ko,RemoteCapabilityError:Ps,SmartHttpError:iu,UnknownTransportError:su,UnsafeFilepathError:zo,UrlParseError:au,UserCanceledError:Qo,UnmergedPathsError:Vc,IndexResetError:ou,NoCommitError:lu});function mv({name:t,email:e,timestamp:r,timezoneOffset:n}){return n=R8(n),`${t} <${e}> ${r} ${n}`}function R8(t){let e=$8(I8(t));t=Math.abs(t);let r=Math.floor(t/60);t-=r*60;let n=String(r),i=String(t);return n.length<2&&(n="0"+n),i.length<2&&(i="0"+i),(e===-1?"-":"+")+n+i}function $8(t){return Math.sign(t)||(Object.is(t,-0)?-1:1)}function I8(t){return t===0?t:-t}function Wi(t){return t=t.replace(/\r/g,""),t=t.replace(/^\n+/,""),t=t.replace(/\n+$/,"")+` +`,t}function Fd(t){let[,e,r,n,i]=t.match(/^(.*) <(.*)> (.*) (.*)$/);return{name:e,email:r,timestamp:Number(n),timezoneOffset:F8(i)}}function F8(t){let[,e,r,n]=t.match(/(\+|-)(\d\d)(\d\d)/);return n=(e==="+"?1:-1)*(Number(r)*60+Number(n)),O8(n)}function O8(t){return t===0?t:-t}var Zr=class t{constructor(e){if(typeof e=="string")this._tag=e;else if(Buffer.isBuffer(e))this._tag=e.toString("utf8");else if(typeof e=="object")this._tag=t.render(e);else throw new he("invalid type passed to GitAnnotatedTag constructor")}static from(e){return new t(e)}static render(e){return`object ${e.object} +type ${e.type} +tag ${e.tag} +tagger ${mv(e.tagger)} + +${e.message} +${e.gpgsig?e.gpgsig:""}`}justHeaders(){return this._tag.slice(0,this._tag.indexOf(` + +`))}message(){let e=this.withoutSignature();return e.slice(e.indexOf(` + +`)+2)}parse(){return Object.assign(this.headers(),{message:this.message(),gpgsig:this.gpgsig()})}render(){return this._tag}headers(){let e=this.justHeaders().split(` +`),r=[];for(let i of e)i[0]===" "?r[r.length-1]+=` +`+i.slice(1):r.push(i);let n={};for(let i of r){let s=i.slice(0,i.indexOf(" ")),a=i.slice(i.indexOf(" ")+1);Array.isArray(n[s])?n[s].push(a):n[s]=a}return n.tagger&&(n.tagger=Fd(n.tagger)),n.committer&&(n.committer=Fd(n.committer)),n}withoutSignature(){let e=Wi(this._tag);return e.indexOf(` +-----BEGIN PGP SIGNATURE-----`)===-1?e:e.slice(0,e.lastIndexOf(` +-----BEGIN PGP SIGNATURE-----`))}gpgsig(){if(this._tag.indexOf(` +-----BEGIN PGP SIGNATURE-----`)===-1)return;let e=this._tag.slice(this._tag.indexOf("-----BEGIN PGP SIGNATURE-----"),this._tag.indexOf("-----END PGP SIGNATURE-----")+27);return Wi(e)}payload(){return this.withoutSignature()+` +`}toObject(){return Buffer.from(this._tag,"utf8")}static async sign(e,r,n){let i=e.payload(),{signature:s}=await r({payload:i,secretKey:n});s=Wi(s);let a=i+s;return t.from(a)}};function nv(t){return t.trim().split(` +`).map(e=>" "+e).join(` +`)+` +`}function M8(t){return t.split(` +`).map(e=>e.replace(/^ /,"")).join(` +`)}var kr=class t{constructor(e){if(typeof e=="string")this._commit=e;else if(Buffer.isBuffer(e))this._commit=e.toString("utf8");else if(typeof e=="object")this._commit=t.render(e);else throw new he("invalid type passed to GitCommit constructor")}static fromPayloadSignature({payload:e,signature:r}){let n=t.justHeaders(e),i=t.justMessage(e),s=Wi(n+` +gpgsig`+nv(r)+` +`+i);return new t(s)}static from(e){return new t(e)}toObject(){return Buffer.from(this._commit,"utf8")}headers(){return this.parseHeaders()}message(){return t.justMessage(this._commit)}parse(){return Object.assign({message:this.message()},this.headers())}static justMessage(e){return Wi(e.slice(e.indexOf(` + +`)+2))}static justHeaders(e){return e.slice(0,e.indexOf(` + +`))}parseHeaders(){let e=t.justHeaders(this._commit).split(` +`),r=[];for(let i of e)i[0]===" "?r[r.length-1]+=` +`+i.slice(1):r.push(i);let n={parent:[]};for(let i of r){let s=i.slice(0,i.indexOf(" ")),a=i.slice(i.indexOf(" ")+1);Array.isArray(n[s])?n[s].push(a):n[s]=a}return n.author&&(n.author=Fd(n.author)),n.committer&&(n.committer=Fd(n.committer)),n}static renderHeaders(e){let r="";if(e.tree?r+=`tree ${e.tree} +`:r+=`tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904 +`,e.parent){if(e.parent.length===void 0)throw new he("commit 'parent' property should be an array");for(let s of e.parent)r+=`parent ${s} +`}let n=e.author;r+=`author ${mv(n)} +`;let i=e.committer||e.author;return r+=`committer ${mv(i)} +`,e.gpgsig&&(r+="gpgsig"+nv(e.gpgsig)),r}static render(e){return t.renderHeaders(e)+` +`+Wi(e.message)}render(){return this._commit}withoutSignature(){let e=Wi(this._commit);if(e.indexOf(` +gpgsig`)===-1)return e;let r=e.slice(0,e.indexOf(` +gpgsig`)),n=e.slice(e.indexOf(`-----END PGP SIGNATURE----- +`)+28);return Wi(r+` +`+n)}isolateSignature(){let e=this._commit.slice(this._commit.indexOf("-----BEGIN PGP SIGNATURE-----"),this._commit.indexOf("-----END PGP SIGNATURE-----")+27);return M8(e)}static async sign(e,r,n){let i=e.withoutSignature(),s=t.justMessage(e._commit),{signature:a}=await r({payload:i,secretKey:n});a=Wi(a);let l=t.justHeaders(e._commit)+` +gpgsig`+nv(a)+` +`+s;return t.from(l)}};async function Jo({fs:t,cache:e,gitdir:r,oid:n}){if(n==="4b825dc642cb6eb9a060e54bf8d69288fbee4904")return{tree:Er.from([]),oid:n};let{type:i,object:s}=await Xe({fs:t,cache:e,gitdir:r,oid:n});if(i==="tag")return n=Zr.from(s).parse().object,Jo({fs:t,cache:e,gitdir:r,oid:n});if(i==="commit")return n=kr.from(s).parse().tree,Jo({fs:t,cache:e,gitdir:r,oid:n});if(i!=="tree")throw new fr(n,i,"tree");return{tree:Er.from(s),oid:n}}var gv=class{constructor({fs:e,gitdir:r,ref:n,cache:i}){this.fs=e,this.cache=i,this.gitdir=r,this.mapPromise=(async()=>{let a=new Map,o;try{o=await z.resolve({fs:e,gitdir:r,ref:n})}catch(c){c instanceof Be&&(o="4b825dc642cb6eb9a060e54bf8d69288fbee4904")}let l=await Jo({fs:e,cache:this.cache,gitdir:r,oid:o});return l.type="tree",l.mode="40000",a.set(".",l),a})();let s=this;this.ConstructEntry=class{constructor(o){this._fullpath=o,this._type=!1,this._mode=!1,this._stat=!1,this._content=!1,this._oid=!1}async type(){return s.type(this)}async mode(){return s.mode(this)}async stat(){return s.stat(this)}async content(){return s.content(this)}async oid(){return s.oid(this)}}}async readdir(e){let r=e._fullpath,{fs:n,cache:i,gitdir:s}=this,a=await this.mapPromise,o=a.get(r);if(!o)throw new Error(`No obj for ${r}`);let l=o.oid;if(!l)throw new Error(`No oid for obj ${JSON.stringify(o)}`);if(o.type!=="tree")return null;let{type:c,object:u}=await Xe({fs:n,cache:i,gitdir:s,oid:l});if(c!==o.type)throw new fr(l,c,o.type);let f=Er.from(u);for(let d of f)a.set(D(r,d.path),d);return f.entries().map(d=>D(r,d.path))}async type(e){if(e._type===!1){let r=await this.mapPromise,{type:n}=r.get(e._fullpath);e._type=n}return e._type}async mode(e){if(e._mode===!1){let r=await this.mapPromise,{mode:n}=r.get(e._fullpath);e._mode=ik(parseInt(n,8))}return e._mode}async stat(e){}async content(e){if(e._content===!1){let r=await this.mapPromise,{fs:n,cache:i,gitdir:s}=this,o=r.get(e._fullpath).oid,{type:l,object:c}=await Xe({fs:n,cache:i,gitdir:s,oid:o});l!=="blob"?e._content=void 0:e._content=new Uint8Array(c)}return e._content}async oid(e){if(e._oid===!1){let n=(await this.mapPromise).get(e._fullpath);e._oid=n.oid}return e._oid}};function Xr({ref:t="HEAD"}={}){let e=Object.create(null);return Object.defineProperty(e,Bd,{value:function({fs:r,gitdir:n,cache:i}){return new gv({fs:r,gitdir:n,ref:t,cache:i})}}),Object.freeze(e),e}var vv=class{constructor({fs:e,dir:r,gitdir:n,cache:i}){this.fs=e,this.cache=i,this.dir=r,this.gitdir=n,this.config=null;let s=this;this.ConstructEntry=class{constructor(o){this._fullpath=o,this._type=!1,this._mode=!1,this._stat=!1,this._content=!1,this._oid=!1}async type(){return s.type(this)}async mode(){return s.mode(this)}async stat(){return s.stat(this)}async content(){return s.content(this)}async oid(){return s.oid(this)}}}async readdir(e){let r=e._fullpath,{fs:n,dir:i}=this,s=await n.readdir(D(i,r));return s===null?null:s.map(a=>D(r,a))}async type(e){return e._type===!1&&await e.stat(),e._type}async mode(e){return e._mode===!1&&await e.stat(),e._mode}async stat(e){if(e._stat===!1){let{fs:r,dir:n}=this,i=await r.lstat(`${n}/${e._fullpath}`);if(!i)throw new Error(`ENOENT: no such file or directory, lstat '${e._fullpath}'`);let s=i.isDirectory()?"tree":"blob";s==="blob"&&!i.isFile()&&!i.isSymbolicLink()&&(s="special"),e._type=s,i=Vo(i),e._mode=i.mode,i.size===-1&&e._actualSize&&(i.size=e._actualSize),e._stat=i}return e._stat}async content(e){if(e._content===!1){let{fs:r,dir:n,gitdir:i}=this;if(await e.type()==="tree")e._content=void 0;else{let s;if(await e.mode()>>12===10)s=await r.readlink(`${n}/${e._fullpath}`);else{let o=await(await this._getGitConfig(r,i)).get("core.autocrlf");s=await r.read(`${n}/${e._fullpath}`,{autocrlf:o})}e._actualSize=s.length,e._stat&&e._stat.size===-1&&(e._stat.size=e._actualSize),e._content=new Uint8Array(s)}}return e._content}async oid(e){if(e._oid===!1){let r=this,{fs:n,gitdir:i,cache:s}=this,a;await ht.acquire({fs:n,gitdir:i,cache:s},async function(o){let l=o.entriesMap.get(e._fullpath),c=await e.stat(),f=await(await r._getGitConfig(n,i)).get("core.filemode"),d=typeof process!="undefined"?process.platform!=="win32":!0;if(!l||Td(c,l,f,d)){let h=await e.content();h===void 0?a=void 0:(a=await zi($s.wrap({type:"blob",object:h})),l&&a===l.oid&&(!f||c.mode===l.mode)&&Td(c,l,f,d)&&o.insert({filepath:e._fullpath,stats:c,oid:a}))}else a=l.oid}),e._oid=a}return e._oid}async _getGitConfig(e,r){return this.config?this.config:(this.config=await lt.get({fs:e,gitdir:r}),this.config)}};function sl(){let t=Object.create(null);return Object.defineProperty(t,Bd,{value:function({fs:e,dir:r,gitdir:n,cache:i}){return new vv({fs:e,dir:r,gitdir:n,cache:i})}}),Object.freeze(t),t}function D8(t,e){let r=e-t;return Array.from({length:r},(n,i)=>t+i)}var dk=typeof Array.prototype.flat=="undefined"?t=>t.reduce((e,r)=>e.concat(r),[]):t=>t.flat(),wv=class{constructor(){this.value=null}consider(e){e!=null&&(this.value===null?this.value=e:ec,reduce:a=async(l,c)=>{let u=dk(c);return l!==void 0&&u.unshift(l),u},iterate:o=(l,c)=>Promise.all([...c].map(l))}){let l=i.map(h=>h[Bd]({fs:t,dir:r,gitdir:n,cache:e})),c=new Array(l.length).fill("."),u=D8(0,l.length),f=async h=>{u.forEach(v=>{let w=h[v];h[v]=w&&new l[v].ConstructEntry(w)});let g=(await Promise.all(u.map(v=>{let w=h[v];return w?l[v].readdir(w):[]}))).map(v=>(v===null?[]:v)[Symbol.iterator]());return{entries:h,children:L8(g)}},d=async h=>{let{entries:m,children:g}=await f(h),v=m.find(b=>b&&b._fullpath)._fullpath,w=await s(v,m);if(w!==null){let b=await o(d,g);return b=b.filter(k=>k!==void 0),a(w,b)}};return d(c)}async function yv(t,e){let r=await t.readdir(e);r==null?await t.rm(e):r.length?await Promise.all(r.map(n=>{let i=D(e,n);return t.lstat(i).then(s=>{if(s)return s.isDirectory()?yv(t,i):t.rm(i)})})).then(()=>t.rmdir(e)):await t.rmdir(e)}function N8(t){return B8(t)&&jE(t.then)&&jE(t.catch)}function B8(t){return t&&typeof t=="object"}function jE(t){return typeof t=="function"}function qE(t){return N8((r=>{try{return r.readFile().catch(n=>n)}catch(n){return n}})(t))}var WE=["readFile","writeFile","mkdir","rmdir","unlink","stat","lstat","readdir","readlink","symlink"];function zE(t,e){if(qE(e))for(let r of WE)t[`_${r}`]=e[r].bind(e);else for(let r of WE)t[`_${r}`]=kd(e[r].bind(e));qE(e)?(e.cp&&(t._cp=e.cp.bind(e)),e.rm?t._rm=e.rm.bind(e):e.rmdir.length>1?t._rm=e.rmdir.bind(e):t._rm=yv.bind(null,t)):(e.cp&&(t._cp=kd(e.cp.bind(e))),e.rm?t._rm=kd(e.rm.bind(e)):e.rmdir.length>2?t._rm=kd(e.rmdir.bind(e)):t._rm=yv.bind(null,t))}var Q=class{constructor(e){if(typeof e._original_unwrapped_fs!="undefined")return e;let r=Object.getOwnPropertyDescriptor(e,"promises");r&&r.enumerable?zE(this,e.promises):zE(this,e),this._original_unwrapped_fs=e}async exists(e,r={}){try{return await this._stat(e),!0}catch(n){if(n.code==="ENOENT"||n.code==="ENOTDIR"||(n.code||"").includes("ENS"))return!1;throw console.log('Unhandled error in "FileSystem.exists()" function',n),n}}async read(e,r={}){try{let n=await this._readFile(e,r);if(r.autocrlf==="true")try{n=new TextDecoder("utf8",{fatal:!0}).decode(n),n=n.replace(/\r\n/g,` +`),n=new TextEncoder().encode(n)}catch(i){}return typeof n!="string"&&(n=Buffer.from(n)),n}catch(n){return null}}async write(e,r,n={}){try{await this._writeFile(e,r,n)}catch(i){await this.mkdir(Sa(e)),await this._writeFile(e,r,n)}}async mkdir(e,r=!1){try{await this._mkdir(e)}catch(n){if(n===null||n.code==="EEXIST")return;if(r)throw n;if(n.code==="ENOENT"){let i=Sa(e);if(i==="."||i==="/"||i===e)throw n;await this.mkdir(i),await this.mkdir(e,!0)}}}async rm(e){try{await this._unlink(e)}catch(r){if(r.code!=="ENOENT")throw r}}async rmdir(e,r){try{r&&r.recursive?await this._rm(e,r):await this._rmdir(e)}catch(n){if(n.code!=="ENOENT")throw n}}async readdir(e){try{let r=await this._readdir(e);return r.sort(Nd),r}catch(r){return r.code==="ENOTDIR"?null:[]}}async readdirDeep(e){let r=await this._readdir(e);return(await Promise.all(r.map(async i=>{let s=e+"/"+i;return(await this._stat(s)).isDirectory()?this.readdirDeep(s):s}))).reduce((i,s)=>i.concat(s),[])}async lstat(e){try{return await this._lstat(e)}catch(r){if(r.code==="ENOENT"||(r.code||"").includes("ENS"))return null;throw r}}async readlink(e,r={encoding:"buffer"}){try{let n=await this._readlink(e,r);return Buffer.isBuffer(n)?n:Buffer.from(n)}catch(n){if(n.code==="ENOENT"||(n.code||"").includes("ENS"))return null;throw n}}async writelink(e,r){return this._symlink(r.toString("utf8"),e)}};function T(t,e){if(e===void 0)throw new Sr(t)}async function J({fsp:t,dotgit:e}){T("fsp",t),T("dotgit",e);let r=await t._stat(e).catch(()=>({isFile:()=>!1,isDirectory:()=>!1}));return r.isDirectory()?e:r.isFile()?t._readFile(e,"utf8").then(n=>n.trimRight().substr(8)).then(n=>D(Sa(e),n)):e}async function Od(t,e){return!t&&!e?!1:t&&!e||!t&&e?!0:!(await t.type()==="tree"&&await e.type()==="tree"||await t.type()===await e.type()&&await t.mode()===await e.mode()&&await t.oid()===await e.oid())}async function hk({fs:t,dir:e,gitdir:r=D(e,".git"),commit:n="HEAD",cache:i={}}){try{T("fs",t),T("dir",e),T("gitdir",r);let s=new Q(t),a=[Xr({ref:n}),sl(),Ca()],o=[],l=await J({fsp:s,dotgit:r});await ht.acquire({fs:s,gitdir:l,cache:i},async function(u){o=u.unmergedPaths});let c=await Fs({fs:s,cache:i,dir:e,gitdir:l,trees:a,map:async function(u,[f,d,h]){let m=!await Od(d,h),g=o.includes(u),v=!await Od(h,f);if(m||g)return f?{path:u,mode:await f.mode(),oid:await f.oid(),type:await f.type(),content:await f.content()}:void 0;if(v)return!1;throw new ou(u)}});await ht.acquire({fs:s,gitdir:l,cache:i},async function(u){for(let f of c)if(f!==!1){if(!f){await s.rmdir(`${e}/${f.path}`,{recursive:!0}),u.delete({filepath:f.path});continue}if(f.type==="blob"){let d=new TextDecoder().decode(f.content);await s.write(`${e}/${f.path}`,d,{mode:f.mode}),u.insert({filepath:f.path,oid:f.oid,stage:0})}}})}catch(s){throw s.caller="git.abortMerge",s}}var Os=class{static async isIgnored({fs:e,dir:r,gitdir:n=D(r,".git"),filepath:i}){if(Pd(i)===".git")return!0;if(i===".")return!1;let s="",a=D(n,"info","exclude");await e.exists(a)&&(s=await e.read(a,"utf8"));let o=[{gitignore:D(r,".gitignore"),filepath:i}],l=i.split("/").filter(Boolean);for(let u=1;u{let f=await(await lt.get({fs:o,gitdir:l})).get("core.autocrlf");return bv({dir:e,gitdir:l,fs:o,filepath:n,index:c,force:s,parallel:a,autocrlf:f})})}catch(o){throw o.caller="git.add",o}}async function bv({dir:t,gitdir:e,fs:r,filepath:n,index:i,force:s,parallel:a,autocrlf:o}){n=Array.isArray(n)?n:[n];let l=n.map(async d=>{if(!s&&await Os.isIgnored({fs:r,dir:t,gitdir:e,filepath:d}))return;let h=await r.lstat(D(t,d));if(!h)throw new Be(d);if(h.isDirectory()){let m=await r.readdir(D(t,d));if(a){let g=m.map(v=>bv({dir:t,gitdir:e,fs:r,filepath:[D(d,v)],index:i,force:s,parallel:a,autocrlf:o}));await Promise.all(g)}else for(let g of m)await bv({dir:t,gitdir:e,fs:r,filepath:[D(d,g)],index:i,force:s,parallel:a,autocrlf:o})}else{let m=h.isSymbolicLink()?await r.readlink(D(t,d)).then(mk):await r.read(D(t,d),{autocrlf:o});if(m===null)throw new Be(d);let g=await Ar({fs:r,gitdir:e,type:"blob",object:m});i.insert({filepath:d,stats:h,oid:g})}}),c=await Promise.allSettled(l),u=c.filter(d=>d.status==="rejected").map(d=>d.reason);if(u.length>1)throw new nu(u);if(u.length===1)throw u[0];return c.filter(d=>d.status==="fulfilled"&&d.value).map(d=>d.value)}async function cu({fs:t,gitdir:e,path:r}){return(await lt.get({fs:t,gitdir:e})).get(r)}function vk(t,...e){for(let r of e)if(r)for(let n of Object.keys(r)){let i=r[n];i!==void 0&&(t[n]=i)}return t}async function Ms({fs:t,gitdir:e,author:r,commit:n}){let i=Math.floor(Date.now()/1e3),s={name:await cu({fs:t,gitdir:e,path:"user.name"}),email:await cu({fs:t,gitdir:e,path:"user.email"})||"",timestamp:i,timezoneOffset:new Date(i*1e3).getTimezoneOffset()},a=vk({},s,n?n.author:void 0,r);if(a.name!==void 0)return a}async function el({fs:t,gitdir:e,author:r,committer:n,commit:i}){let s=Math.floor(Date.now()/1e3),a={name:await cu({fs:t,gitdir:e,path:"user.name"}),email:await cu({fs:t,gitdir:e,path:"user.email"})||"",timestamp:s,timezoneOffset:new Date(s*1e3).getTimezoneOffset()},o=vk({},a,i?i.committer:void 0,r,n);if(o.name!==void 0)return o}async function wk({fs:t,cache:e,gitdir:r,oid:n}){let{type:i,object:s}=await Xe({fs:t,cache:e,gitdir:r,oid:n});if(i==="tag")return n=Zr.from(s).parse().object,wk({fs:t,cache:e,gitdir:r,oid:n});if(i!=="commit")throw new fr(n,i,"commit");return{commit:kr.from(s),oid:n}}async function tl({fs:t,cache:e,gitdir:r,oid:n}){let{commit:i,oid:s}=await wk({fs:t,cache:e,gitdir:r,oid:n});return{oid:s,commit:i.parse(),payload:i.withoutSignature()}}async function Hd({fs:t,cache:e,onSign:r,gitdir:n,message:i,author:s,committer:a,signingKey:o,amend:l=!1,dryRun:c=!1,noUpdateBranch:u=!1,ref:f,parent:d,tree:h}){let m=!1,g=!1;f||(g=!(await t.read(`${n}/HEAD`,{encoding:"utf8"})).startsWith("ref:"),f=await z.resolve({fs:t,gitdir:n,ref:"HEAD",depth:2}));let v,w;try{v=await z.resolve({fs:t,gitdir:n,ref:f}),w=await tl({fs:t,gitdir:n,oid:v,cache:{}})}catch(x){m=!0}if(l&&m)throw new lu(f);let b=l?await Ms({fs:t,gitdir:n,author:s,commit:w.commit}):await Ms({fs:t,gitdir:n,author:s});if(!b)throw new Kt("author");let k=l?await el({fs:t,gitdir:n,author:b,committer:a,commit:w.commit}):await el({fs:t,gitdir:n,author:b,committer:a});if(!k)throw new Kt("committer");return ht.acquire({fs:t,gitdir:n,cache:e,allowUnmerged:!1},async function(x){let A=ak(x.entries).get(".");if(h||(h=await yk({fs:t,gitdir:n,inode:A,dryRun:c})),d?d=await Promise.all(d.map(_=>z.resolve({fs:t,gitdir:n,ref:_}))):l?d=w.commit.parent:d=v?[v]:[],!i)if(l)i=w.commit.message;else throw new Sr("message");let y=kr.from({tree:h,parent:d,author:b,committer:k,message:i});o&&(y=await kr.sign(y,r,o));let S=await Ar({fs:t,gitdir:n,type:"commit",object:y.toObject(),dryRun:c});return!u&&!c&&await z.writeRef({fs:t,gitdir:n,ref:g?"HEAD":f,value:S}),S})}async function yk({fs:t,gitdir:e,inode:r,dryRun:n}){let i=r.children;for(let l of i)l.type==="tree"&&(l.metadata.mode="040000",l.metadata.oid=await yk({fs:t,gitdir:e,inode:l,dryRun:n}));let s=i.map(l=>({mode:l.metadata.mode,path:l.basename,oid:l.metadata.oid,type:l.type})),a=Er.from(s);return await Ar({fs:t,gitdir:e,type:"tree",object:a.toObject(),dryRun:n})}async function fu({fs:t,cache:e,gitdir:r,oid:n,filepath:i}){if(i.startsWith("/"))throw new Is("leading-slash");if(i.endsWith("/"))throw new Is("trailing-slash");let s=n,a=await Jo({fs:t,cache:e,gitdir:r,oid:n}),o=a.tree;if(i==="")n=a.oid;else{let l=i.split("/");n=await bk({fs:t,cache:e,gitdir:r,tree:o,pathArray:l,oid:s,filepath:i})}return n}async function bk({fs:t,cache:e,gitdir:r,tree:n,pathArray:i,oid:s,filepath:a}){let o=i.shift();for(let l of n)if(l.path===o){if(i.length===0)return l.oid;{let{type:c,object:u}=await Xe({fs:t,cache:e,gitdir:r,oid:l.oid});if(c!=="tree")throw new fr(s,c,"tree",a);return n=Er.from(u),bk({fs:t,cache:e,gitdir:r,tree:n,pathArray:i,oid:s,filepath:a})}}throw new Be(`file or directory found at "${s}:${a}"`)}async function al({fs:t,cache:e,gitdir:r,oid:n,filepath:i=void 0}){i!==void 0&&(n=await fu({fs:t,cache:e,gitdir:r,oid:n,filepath:i}));let{tree:s,oid:a}=await Jo({fs:t,cache:e,gitdir:r,oid:n});return{oid:a,tree:s.entries()}}async function du({fs:t,gitdir:e,tree:r}){let n=Er.from(r).toObject();return await Ar({fs:t,gitdir:e,type:"tree",object:n,format:"content"})}async function j8({fs:t,cache:e,onSign:r,gitdir:n,ref:i,oid:s,note:a,force:o,author:l,committer:c,signingKey:u}){let f;try{f=await z.resolve({gitdir:n,fs:t,ref:i})}catch(w){if(!(w instanceof Be))throw w}let h=(await al({fs:t,cache:e,gitdir:n,oid:f||"4b825dc642cb6eb9a060e54bf8d69288fbee4904"})).tree;if(o)h=h.filter(w=>w.path!==s);else for(let w of h)if(w.path===s)throw new Mn("note",s);typeof a=="string"&&(a=Buffer.from(a,"utf8"));let m=await Ar({fs:t,gitdir:n,type:"blob",object:a,format:"content"});h.push({mode:"100644",path:s,oid:m,type:"blob"});let g=await du({fs:t,gitdir:n,tree:h});return await Hd({fs:t,cache:e,onSign:r,gitdir:n,ref:i,tree:g,parent:f&&[f],message:`Note added by 'isomorphic-git addNote' +`,author:l,committer:c,signingKey:u})}async function _k({fs:t,onSign:e,dir:r,gitdir:n=D(r,".git"),ref:i="refs/notes/commits",oid:s,note:a,force:o,author:l,committer:c,signingKey:u,cache:f={}}){try{T("fs",t),T("gitdir",n),T("oid",s),T("note",a),u&&T("onSign",e);let d=new Q(t),h=await Ms({fs:d,gitdir:n,author:l});if(!h)throw new Kt("author");let m=await el({fs:d,gitdir:n,author:h,committer:c});if(!m)throw new Kt("committer");let g=await J({fsp:d,dotgit:n});return await j8({fs:d,cache:f,onSign:e,gitdir:g,ref:i,oid:s,note:a,force:o,author:h,committer:m,signingKey:u})}catch(d){throw d.caller="git.addNote",d}}var q8=/(^|[/.])([/.]|$)|^@$|@{|[\x00-\x20\x7f~^:?*[\\]|\.lock(\/|$)/;function uu(t,e){if(typeof t!="string")throw new TypeError("Reference name must be a string");return!q8.test(t)&&(!!e||t.includes("/"))}async function xk({fs:t,gitdir:e,remote:r,url:n,force:i}){if(!uu(r,!0))throw new Dn(r,zc.clean(r));let s=await lt.get({fs:t,gitdir:e});if(!i&&(await s.getSubsections("remote")).includes(r)&&n!==await s.get(`remote.${r}.url`))throw new Mn("remote",r);await s.set(`remote.${r}.url`,n),await s.set(`remote.${r}.fetch`,`+refs/heads/*:refs/remotes/${r}/*`),await lt.save({fs:t,gitdir:e,config:s})}async function Sk({fs:t,dir:e,gitdir:r=D(e,".git"),remote:n,url:i,force:s=!1}){try{T("fs",t),T("gitdir",r),T("remote",n),T("url",i);let a=new Q(t),o=await J({fsp:a,dotgit:r});return await xk({fs:a,gitdir:o,remote:n,url:i,force:s})}catch(a){throw a.caller="git.addRemote",a}}async function W8({fs:t,cache:e,onSign:r,gitdir:n,ref:i,tagger:s,message:a=i,gpgsig:o,object:l,signingKey:c,force:u=!1}){if(i=i.startsWith("refs/tags/")?i:`refs/tags/${i}`,!u&&await z.exists({fs:t,gitdir:n,ref:i}))throw new Mn("tag",i);let f=await z.resolve({fs:t,gitdir:n,ref:l||"HEAD"}),{type:d}=await Xe({fs:t,cache:e,gitdir:n,oid:f}),h=Zr.from({object:f,type:d,tag:i.replace("refs/tags/",""),tagger:s,message:a,gpgsig:o});c&&(h=await Zr.sign(h,r,c));let m=await Ar({fs:t,gitdir:n,type:"tag",object:h.toObject()});await z.writeRef({fs:t,gitdir:n,ref:i,value:m})}async function Ek({fs:t,onSign:e,dir:r,gitdir:n=D(r,".git"),ref:i,tagger:s,message:a=i,gpgsig:o,object:l,signingKey:c,force:u=!1,cache:f={}}){try{T("fs",t),T("gitdir",n),T("ref",i),c&&T("onSign",e);let d=new Q(t),h=await J({fsp:d,dotgit:n}),m=await Ms({fs:d,gitdir:h,author:s});if(!m)throw new Kt("tagger");return await W8({fs:d,cache:f,onSign:e,gitdir:h,ref:i,tagger:m,message:a,gpgsig:o,object:l,signingKey:c,force:u})}catch(d){throw d.caller="git.annotatedTag",d}}async function z8({fs:t,gitdir:e,ref:r,object:n,checkout:i=!1,force:s=!1}){if(!uu(r,!0))throw new Dn(r,zc.clean(r));let a=`refs/heads/${r}`;if(!s&&await z.exists({fs:t,gitdir:e,ref:a}))throw new Mn("branch",r,!1);let o;try{o=await z.resolve({fs:t,gitdir:e,ref:n||"HEAD"})}catch(l){}o&&await z.writeRef({fs:t,gitdir:e,ref:a,value:o}),i&&await z.writeSymbolicRef({fs:t,gitdir:e,ref:"HEAD",value:a})}async function kk({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n,object:i,checkout:s=!1,force:a=!1}){try{T("fs",t),T("gitdir",r),T("ref",n);let o=new Q(t),l=await J({fsp:o,dotgit:r});return await z8({fs:o,gitdir:l,ref:n,object:i,checkout:s,force:a})}catch(o){throw o.caller="git.branch",o}}var Ak=(t,e)=>t==="."||e==null||e.length===0||e==="."?!0:e.length>=t.length?e.startsWith(t):t.startsWith(e);async function Ev({fs:t,cache:e,onProgress:r,onPostCheckout:n,dir:i,gitdir:s,remote:a,ref:o,filepaths:l,noCheckout:c,noUpdateHead:u,dryRun:f,force:d,track:h=!0,nonBlocking:m=!1,batchSize:g=100}){let v;if(n)try{v=await z.resolve({fs:t,gitdir:s,ref:"HEAD"})}catch(b){v="0000000000000000000000000000000000000000"}let w;try{w=await z.resolve({fs:t,gitdir:s,ref:o})}catch(b){if(o==="HEAD")throw b;let k=`${a}/${o}`;if(w=await z.resolve({fs:t,gitdir:s,ref:k}),h){let x=await lt.get({fs:t,gitdir:s});await x.set(`branch.${o}.remote`,a),await x.set(`branch.${o}.merge`,`refs/heads/${o}`),await lt.save({fs:t,gitdir:s,config:x})}await z.writeRef({fs:t,gitdir:s,ref:`refs/heads/${o}`,value:w})}if(!c){let b;try{b=await V8({fs:t,cache:e,onProgress:r,dir:i,gitdir:s,ref:o,force:d,filepaths:l})}catch(y){throw y instanceof Be&&y.data.what===w?new Qc(o,w):y}let k=b.filter(([y])=>y==="conflict").map(([y,S])=>S);if(k.length>0)throw new Kc(k);let x=b.filter(([y])=>y==="error").map(([y,S])=>S);if(x.length>0)throw new he(x.join(", "));if(f){n&&await n({previousHead:v,newHead:w,type:l!=null&&l.length>0?"file":"branch"});return}let E=0,A=b.length;if(await ht.acquire({fs:t,gitdir:s,cache:e},async function(y){await Promise.all(b.filter(([S])=>S==="delete"||S==="delete-index").map(async function([S,_]){let C=`${i}/${_}`;S==="delete"&&await t.rm(C),y.delete({filepath:_}),r&&await r({phase:"Updating workdir",loaded:++E,total:A})}))}),await ht.acquire({fs:t,gitdir:s,cache:e},async function(y){for(let[S,_]of b)if(S==="rmdir"||S==="rmdir-index"){let C=`${i}/${_}`;try{S==="rmdir"&&await t.rmdir(C),y.delete({filepath:_}),r&&await r({phase:"Updating workdir",loaded:++E,total:A})}catch(P){if(P.code==="ENOTEMPTY")console.log(`Did not delete ${_} because directory is not empty`);else throw P}}}),await Promise.all(b.filter(([y])=>y==="mkdir"||y==="mkdir-index").map(async function([y,S]){let _=`${i}/${S}`;await t.mkdir(_),r&&await r({phase:"Updating workdir",loaded:++E,total:A})})),m){let y=b.filter(([_])=>_==="create"||_==="create-index"||_==="update"||_==="mkdir-index"),S=await VE("Update Working Dir",y.map(([_,C,P,N,B])=>()=>X8({fs:t,cache:e,gitdir:s,dir:i},[_,C,P,N,B])),r,g);await ht.acquire({fs:t,gitdir:s,cache:e,allowUnmerged:!0},async function(_){await VE("Update Index",S.map(([C,P,N])=>()=>Y8({index:_,fullpath:C,oid:P,stats:N})),r,g)})}else await ht.acquire({fs:t,gitdir:s,cache:e,allowUnmerged:!0},async function(y){await Promise.all(b.filter(([S])=>S==="create"||S==="create-index"||S==="update"||S==="mkdir-index").map(async function([S,_,C,P,N]){let B=`${i}/${_}`;try{if(S!=="create-index"&&S!=="mkdir-index"){let{object:ce}=await Xe({fs:t,cache:e,gitdir:s,oid:C});if(N&&await t.rm(B),P===33188)await t.write(B,ce);else if(P===33261)await t.write(B,ce,{mode:511});else if(P===40960)await t.writelink(B,ce);else throw new he(`Invalid mode 0o${P.toString(8)} detected in blob ${C}`)}let H=await t.lstat(B);P===33261&&(H.mode=493),S==="mkdir-index"&&(H.mode=57344),y.insert({filepath:_,stats:H,oid:C}),r&&await r({phase:"Updating workdir",loaded:++E,total:A})}catch(H){console.log(H)}}))});n&&await n({previousHead:v,newHead:w,type:l!=null&&l.length>0?"file":"branch"})}if(!u){let b=await z.expand({fs:t,gitdir:s,ref:o});b.startsWith("refs/heads")?await z.writeSymbolicRef({fs:t,gitdir:s,ref:"HEAD",value:b}):await z.writeRef({fs:t,gitdir:s,ref:"HEAD",value:w})}}async function V8({fs:t,cache:e,onProgress:r,dir:n,gitdir:i,ref:s,force:a,filepaths:o}){let l=0;return Fs({fs:t,cache:e,dir:n,gitdir:i,trees:[Xr({ref:s}),sl(),Ca()],map:async function(c,[u,f,d]){if(c===".")return;if(o&&!o.some(m=>Ak(c,m)))return null;switch(r&&await r({phase:"Analyzing workdir",loaded:++l}),[!!d,!!u,!!f].map(Number).join("")){case"000":return;case"001":return a&&o&&o.includes(c)?["delete",c]:void 0;case"010":switch(await u.type()){case"tree":return["mkdir",c];case"blob":return["create",c,await u.oid(),await u.mode()];case"commit":return["mkdir-index",c,await u.oid(),await u.mode()];default:return["error",`new entry Unhandled type ${await u.type()}`]}case"011":switch(`${await u.type()}-${await f.type()}`){case"tree-tree":return;case"tree-blob":case"blob-tree":return["conflict",c];case"blob-blob":return await u.oid()!==await f.oid()?a?["update",c,await u.oid(),await u.mode(),await u.mode()!==await f.mode()]:["conflict",c]:await u.mode()!==await f.mode()?a?["update",c,await u.oid(),await u.mode(),!0]:["conflict",c]:["create-index",c,await u.oid(),await u.mode()];case"commit-tree":return;case"commit-blob":return["conflict",c];default:return["error",`new entry Unhandled type ${u.type}`]}case"100":return["delete-index",c];case"101":switch(await d.type()){case"tree":return["rmdir-index",c];case"blob":return await d.oid()!==await f.oid()?a?["delete",c]:["conflict",c]:["delete",c];case"commit":return["rmdir-index",c];default:return["error",`delete entry Unhandled type ${await d.type()}`]}case"110":case"111":switch(`${await d.type()}-${await u.type()}`){case"tree-tree":return;case"blob-blob":{if(await d.oid()===await u.oid()&&await d.mode()===await u.mode()&&!a)return;if(f){if(await f.oid()!==await d.oid()&&await f.oid()!==await u.oid())return a?["update",c,await u.oid(),await u.mode(),await u.mode()!==await f.mode()]:["conflict",c]}else if(a)return["update",c,await u.oid(),await u.mode(),await u.mode()!==await d.mode()];return await u.mode()!==await d.mode()?["update",c,await u.oid(),await u.mode(),!0]:await u.oid()!==await d.oid()?["update",c,await u.oid(),await u.mode(),!1]:void 0}case"tree-blob":return["update-dir-to-blob",c,await u.oid()];case"blob-tree":return["update-blob-to-tree",c];case"commit-commit":return["mkdir-index",c,await u.oid(),await u.mode()];default:return["error",`update entry Unhandled type ${await d.type()}-${await u.type()}`]}}},reduce:async function(c,u){return u=dk(u),c?c&&c[0]==="rmdir"?(u.push(c),u):(u.unshift(c),u):u}})}async function Y8({index:t,fullpath:e,stats:r,oid:n}){try{t.insert({filepath:e,stats:r,oid:n})}catch(i){console.warn(`Error inserting ${e} into index:`,i)}}async function X8({fs:t,cache:e,gitdir:r,dir:n},[i,s,a,o,l]){let c=`${n}/${s}`;if(i!=="create-index"&&i!=="mkdir-index"){let{object:f}=await Xe({fs:t,cache:e,gitdir:r,oid:a});if(l&&await t.rm(c),o===33188)await t.write(c,f);else if(o===33261)await t.write(c,f,{mode:511});else if(o===40960)await t.writelink(c,f);else throw new he(`Invalid mode 0o${o.toString(8)} detected in blob ${a}`)}let u=await t.lstat(c);return o===33261&&(u.mode=493),i==="mkdir-index"&&(u.mode=57344),[s,a,u]}async function VE(t,e,r,n){let i=[];try{for(let s=0;sl());(await Promise.allSettled(a)).forEach(l=>{l.status==="fulfilled"&&i.push(l.value)}),r&&await r({phase:"Updating workdir",loaded:s+a.length,total:e.length})}return i}catch(s){console.error(`Error during ${t}: ${s}`)}return i}async function kv({fs:t,onProgress:e,onPostCheckout:r,dir:n,gitdir:i=D(n,".git"),remote:s="origin",ref:a,filepaths:o,noCheckout:l=!1,noUpdateHead:c=a===void 0,dryRun:u=!1,force:f=!1,track:d=!0,cache:h={},nonBlocking:m=!1,batchSize:g=100}){try{T("fs",t),T("dir",n),T("gitdir",i);let v=a||"HEAD",w=new Q(t),b=await J({fsp:w,dotgit:i});return await Ev({fs:w,cache:h,onProgress:e,onPostCheckout:r,dir:n,gitdir:b,remote:s,ref:v,filepaths:o,noCheckout:l,noUpdateHead:c,dryRun:u,force:f,track:d,nonBlocking:m,batchSize:g})}catch(v){throw v.caller="git.checkout",v}}var Z8=/^refs\/(heads\/|tags\/|remotes\/)?(.*)/;function xa(t){let e=Z8.exec(t);return e?e[1]==="remotes/"&&t.endsWith("/HEAD")?e[2].slice(0,-5):e[2]:t}async function Ls({fs:t,gitdir:e,fullname:r=!1,test:n=!1}){let i=await z.resolve({fs:t,gitdir:e,ref:"HEAD",depth:2});if(n)try{await z.resolve({fs:t,gitdir:e,ref:i})}catch(s){return}if(i.startsWith("refs/"))return r?i:xa(i)}function K8(t){return t=t.replace(/^git@([^:]+):/,"https://$1/"),t=t.replace(/^ssh:\/\//,"https://"),t}function Ck({username:t="",password:e=""}){return`Basic ${Buffer.from(`${t}:${e}`).toString("base64")}`}async function hu(t,e){let r=ck(t);for(;;){let{value:n,done:i}=await r.next();if(n&&await e(n),i)break}r.return&&r.return()}async function Md(t){let e=0,r=[];await hu(t,s=>{r.push(s),e+=s.byteLength});let n=new Uint8Array(e),i=0;for(let s of r)n.set(s,i),i+=s.byteLength;return n}function YE(t){let e=t.match(/^https?:\/\/([^/]+)@/);if(e==null)return{url:t,auth:{}};e=e[1];let[r,n]=e.split(":");return t=t.replace(`${e}@`,""),{url:t,auth:{username:r,password:n}}}function _v(t,e){let r=e.toString(16);return"0".repeat(t-r.length)+r}var st=class{static flush(){return Buffer.from("0000","utf8")}static delim(){return Buffer.from("0001","utf8")}static encode(e){typeof e=="string"&&(e=Buffer.from(e));let r=e.length+4,n=_v(4,r);return Buffer.concat([Buffer.from(n,"utf8"),e])}static streamReader(e){let r=new Id(e);return async function(){try{let i=await r.read(4);if(i==null)return!0;if(i=parseInt(i.toString("utf8"),16),i===0||i===1)return null;let s=await r.read(i-4);return s==null?!0:s}catch(i){return e.error=i,!0}}}};async function XE(t){let e={},r;for(;r=await t(),r!==!0;){if(r===null)continue;r=r.toString("utf8").replace(/\n$/,"");let n=r.indexOf("=");if(n>-1){let i=r.slice(0,n),s=r.slice(n+1);e[i]=s}else e[r]=!0}return{protocolVersion:2,capabilities2:e}}async function ZE(t,{service:e}){let r=new Set,n=new Map,i=new Map,s=st.streamReader(t),a=await s();for(;a===null;)a=await s();if(a===!0)throw new Jc;if(a.includes("version 2"))return XE(s);if(a.toString("utf8").replace(/\n$/,"")!==`# service=${e}`)throw new Ea(`# service=${e}\\n`,a.toString("utf8"));let o=await s();for(;o===null;)o=await s();if(o===!0)return{capabilities:r,refs:n,symrefs:i};if(o=o.toString("utf8"),o.includes("version 2"))return XE(s);let[l,c]=sv(o,"\0","\\x00");if(c.split(" ").map(u=>r.add(u)),l!=="0000000000000000000000000000000000000000 capabilities^{}"){let[u,f]=sv(l," "," ");for(n.set(f,u);;){let d=await s();if(d===!0)break;if(d!==null){let[h,m]=sv(d.toString("utf8")," "," ");n.set(m,h)}}}for(let u of r)if(u.startsWith("symref=")){let f=u.match(/symref=([^:]+):(.*)/);f.length===3&&i.set(f[1],f[2])}return{protocolVersion:1,capabilities:r,refs:n,symrefs:i}}function sv(t,e,r){let n=t.trim().split(e);if(n.length!==2)throw new Ea(`Two strings separated by '${r}'`,t.toString("utf8"));return n}var KE=(t,e)=>t.endsWith("?")?`${t}${e}`:`${t}/${e.replace(/^https?:\/\//,"")}`,QE=(t,e)=>{(e.username||e.password)&&(t.Authorization=Ck(e)),e.headers&&Object.assign(t,e.headers)},av=async t=>{try{let e=Buffer.from(await Md(t.body)),r=e.toString("utf8");return{preview:r.length<256?r:r.slice(0,256)+"...",response:r,data:e}}catch(e){return{}}},rl=class{static async capabilities(){return["discover","connect"]}static async discover({http:e,onProgress:r,onAuth:n,onAuthSuccess:i,onAuthFailure:s,corsProxy:a,service:o,url:l,headers:c,protocolVersion:u}){let{url:f,auth:d}=YE(l),h=a?KE(a,f):f;(d.username||d.password)&&(c.Authorization=Ck(d)),u===2&&(c["Git-Protocol"]="version=2");let m,g,v=!1;do if(m=await e.request({onProgress:r,method:"GET",url:`${h}/info/refs?service=${o}`,headers:c}),g=!1,m.statusCode===401||m.statusCode===203){let w=v?s:n;if(w){if(d=await w(f,{...d,headers:{...c}}),d&&d.cancel)throw new Qo;d&&(QE(c,d),v=!0,g=!0)}}else m.statusCode===200&&v&&i&&await i(f,d);while(g);if(m.statusCode!==200){let{response:w}=await av(m);throw new Yo(m.statusCode,m.statusMessage,w)}if(m.headers["content-type"]===`application/x-${o}-advertisement`){let w=await ZE(m.body,{service:o});return w.auth=d,w}else{let{preview:w,response:b,data:k}=await av(m);try{let x=await ZE([k],{service:o});return x.auth=d,x}catch(x){throw new iu(w,b)}}}static async connect({http:e,onProgress:r,corsProxy:n,service:i,url:s,auth:a,body:o,headers:l}){let c=YE(s);c&&(s=c.url),n&&(s=KE(n,s)),l["content-type"]=`application/x-${i}-request`,l.accept=`application/x-${i}-result`,QE(l,a);let u=await e.request({onProgress:r,method:"POST",url:`${s}/${i}`,body:o,headers:l});if(u.statusCode!==200){let{response:f}=av(u);throw new Yo(u.statusCode,u.statusMessage,f)}return u}},nl=class{static getRemoteHelperFor({url:e}){let r=new Map;r.set("http",rl),r.set("https",rl);let n=Q8({url:e});if(!n)throw new au(e);if(r.has(n.transport))return r.get(n.transport);throw new su(e,n.transport,n.transport==="ssh"?K8(e):void 0)}};function Q8({url:t}){if(t.startsWith("git@"))return{transport:"ssh",address:t};let e=t.match(/(\w+)(:\/\/|::)(.*)/);if(e!==null){if(e[2]==="://")return{transport:e[1],address:e[0]};if(e[2]==="::")return{transport:e[1],address:e[3]}}}var _a=null,ka=class{static async read({fs:e,gitdir:r}){_a===null&&(_a=new Wc);let n=D(r,"shallow"),i=new Set;return await _a.acquire(n,async function(){let s=await e.read(n,{encoding:"utf8"});if(s===null||s.trim()==="")return i;s.trim().split(` +`).map(a=>i.add(a))}),i}static async write({fs:e,gitdir:r,oids:n}){_a===null&&(_a=new Wc);let i=D(r,"shallow");if(n.size>0){let s=[...n].join(` +`)+` +`;await _a.acquire(i,async function(){await e.write(i,s,{encoding:"utf8"})})}else await _a.acquire(i,async function(){await e.rm(i)})}};async function J8({fs:t,gitdir:e,oid:r}){let n=`objects/${r.slice(0,2)}/${r.slice(2)}`;return t.exists(`${e}/${n}`)}async function e6({fs:t,cache:e,gitdir:r,oid:n,getExternalRefDelta:i}){let s=await t.readdir(D(r,"objects/pack"));s=s.filter(a=>a.endsWith(".idx"));for(let a of s){let o=`${r}/objects/pack/${a}`,l=await Sv({fs:t,cache:e,filename:o,getExternalRefDelta:i});if(l.error)throw new he(l.error);if(l.offsets.has(n))return!0}return!1}async function JE({fs:t,cache:e,gitdir:r,oid:n,format:i="content"}){let s=o=>Xe({fs:t,cache:e,gitdir:r,oid:o}),a=await J8({fs:t,gitdir:r,oid:n});return a||(a=await e6({fs:t,cache:e,gitdir:r,oid:n,getExternalRefDelta:s})),a}function t6(t){let i="5041434b"+"00000002"+"00000000";return t.slice(0,12).toString("hex")===i}function Tk(t,e){let r=t.map(n=>n.split("=",1)[0]);return e.filter(n=>{let i=n.split("=",1)[0];return r.includes(i)})}var Ud={name:"isomorphic-git",version:"1.36.3",agent:"git/isomorphic-git@1.36.3"},Wo=class{constructor(){this._queue=[]}write(e){if(this._ended)throw Error("You cannot write to a FIFO that has already been ended!");if(this._waiting){let r=this._waiting;this._waiting=null,r({value:e})}else this._queue.push(e)}end(){if(this._ended=!0,this._waiting){let e=this._waiting;this._waiting=null,e({done:!0})}}destroy(e){this.error=e,this.end()}async next(){if(this._queue.length>0)return{value:this._queue.shift()};if(this._ended)return{done:!0};if(this._waiting)throw Error("You cannot call read until the previous call to read has returned!");return new Promise(e=>{this._waiting=e})}};function r6(t){let e=t.indexOf("\r"),r=t.indexOf(` +`);return e===-1&&r===-1?-1:e===-1?r+1:r===-1?e+1:r===e+1?r+1:Math.min(e,r)+1}function Pk(t){let e=new Wo,r="";return(async()=>(await hu(t,n=>{for(n=n.toString("utf8"),r+=n;;){let i=r6(r);if(i===-1)break;e.write(r.slice(0,i)),r=r.slice(i)}}),r.length>0&&e.write(r),e.end()))(),e}var Dd=class{static demux(e){let r=st.streamReader(e),n=new Wo,i=new Wo,s=new Wo,a=async function(){let o=await r();if(o===null)return a();if(o===!0){n.end(),s.end(),e.error?i.destroy(e.error):i.end();return}switch(o[0]){case 1:{i.write(o.slice(1));break}case 2:{s.write(o.slice(1));break}case 3:{let l=o.slice(1);s.write(l),n.end(),s.end(),i.destroy(new Error(l.toString("utf8")));return}default:n.write(o)}a()};return a(),{packetlines:n,packfile:i,progress:s}}};async function n6(t){let{packetlines:e,packfile:r,progress:n}=Dd.demux(t),i=[],s=[],a=[],o=!1,l=!1;return new Promise((c,u)=>{hu(e,f=>{let d=f.toString("utf8").trim();if(d.startsWith("shallow")){let h=d.slice(-41).trim();h.length!==40&&u(new Rs(h)),i.push(h)}else if(d.startsWith("unshallow")){let h=d.slice(-41).trim();h.length!==40&&u(new Rs(h)),s.push(h)}else if(d.startsWith("ACK")){let[,h,m]=d.split(" ");a.push({oid:h,status:m}),m||(l=!0)}else d.startsWith("NAK")?(o=!0,l=!0):(l=!0,o=!0);l&&(t.error?u(t.error):c({shallows:i,unshallows:s,acks:a,nak:o,packfile:r,progress:n}))}).finally(()=>{l||(t.error?u(t.error):c({shallows:i,unshallows:s,acks:a,nak:o,packfile:r,progress:n}))})})}function i6({capabilities:t=[],wants:e=[],haves:r=[],shallows:n=[],depth:i=null,since:s=null,exclude:a=[]}){let o=[];e=[...new Set(e)];let l=` ${t.join(" ")}`;for(let c of e)o.push(st.encode(`want ${c}${l} +`)),l="";for(let c of n)o.push(st.encode(`shallow ${c} +`));i!==null&&o.push(st.encode(`deepen ${i} +`)),s!==null&&o.push(st.encode(`deepen-since ${Math.floor(s.valueOf()/1e3)} +`));for(let c of a)o.push(st.encode(`deepen-not ${c} +`));o.push(st.flush());for(let c of r)o.push(st.encode(`have ${c} +`));return o.push(st.encode(`done +`)),o}async function Av({fs:t,cache:e,http:r,onProgress:n,onMessage:i,onAuth:s,onAuthSuccess:a,onAuthFailure:o,gitdir:l,ref:c,remoteRef:u,remote:f,url:d,corsProxy:h,depth:m=null,since:g=null,exclude:v=[],relative:w=!1,tags:b=!1,singleBranch:k=!1,headers:x={},prune:E=!1,pruneTags:A=!1}){let y=c||await Ls({fs:t,gitdir:l,test:!0}),S=await lt.get({fs:t,gitdir:l}),_=f||y&&await S.get(`branch.${y}.remote`)||"origin",C=d||await S.get(`remote.${_}.url`);if(typeof C=="undefined")throw new Sr("remote OR url");let P=u||y&&await S.get(`branch.${y}.merge`)||c||"HEAD";h===void 0&&(h=await S.get("http.corsProxy"));let N=nl.getRemoteHelperFor({url:C}),B=await N.discover({http:r,onAuth:s,onAuthSuccess:a,onAuthFailure:o,corsProxy:h,service:"git-upload-pack",url:C,headers:x,protocolVersion:1}),H=B.auth,ce=B.refs;if(ce.size===0)return{defaultBranch:null,fetchHead:null,fetchHeadDescription:null};if(m!==null&&!B.capabilities.has("shallow"))throw new Ps("shallow","depth");if(g!==null&&!B.capabilities.has("deepen-since"))throw new Ps("deepen-since","since");if(v.length>0&&!B.capabilities.has("deepen-not"))throw new Ps("deepen-not","exclude");if(w===!0&&!B.capabilities.has("deepen-relative"))throw new Ps("deepen-relative","relative");let{oid:Pe,fullref:ve}=z.resolveAgainstMap({ref:P,map:ce});for(let M of ce.keys())M===ve||M==="HEAD"||M.startsWith("refs/heads/")||b&&M.startsWith("refs/tags/")||ce.delete(M);let ie=Tk([...B.capabilities],["multi_ack_detailed","no-done","side-band-64k","ofs-delta",`agent=${Ud.agent}`]);w&&ie.push("deepen-relative");let xe=k?[Pe]:ce.values(),we=k?[y]:await z.listRefs({fs:t,gitdir:l,filepath:"refs"}),W=[];for(let M of we)try{M=await z.expand({fs:t,gitdir:l,ref:M});let O=await z.resolve({fs:t,gitdir:l,ref:M});await JE({fs:t,cache:e,gitdir:l,oid:O})&&W.push(O)}catch(O){}W=[...new Set(W)];let X=await ka.read({fs:t,gitdir:l}),q=B.capabilities.has("shallow")?[...X]:[],De=i6({capabilities:ie,wants:xe,haves:W,shallows:q,depth:m,since:g,exclude:v}),ar=Buffer.from(await Md(De)),Ft=await N.connect({http:r,onProgress:n,corsProxy:h,service:"git-upload-pack",url:C,auth:H,body:[ar],headers:x}),Ie=await n6(Ft.body);Ft.headers&&(Ie.headers=Ft.headers);for(let M of Ie.shallows)if(!X.has(M))try{let{object:O}=await Xe({fs:t,cache:e,gitdir:l,oid:M}),oe=new kr(O),Ce=await Promise.all(oe.headers().parent.map(wr=>JE({fs:t,cache:e,gitdir:l,oid:wr})));Ce.length===0||Ce.every(wr=>wr)||X.add(M)}catch(O){X.add(M)}for(let M of Ie.unshallows)X.delete(M);if(await ka.write({fs:t,gitdir:l,oids:X}),k){let M=new Map([[ve,Pe]]),O=new Map,oe=10,Ce=ve;for(;oe--;){let bo=B.symrefs.get(Ce);if(bo===void 0)break;O.set(Ce,bo),Ce=bo}let Ot=ce.get(Ce);Ot&&M.set(Ce,Ot);let{pruned:wr}=await z.updateRemoteRefs({fs:t,gitdir:l,remote:_,refs:M,symrefs:O,tags:b,prune:E});E&&(Ie.pruned=wr)}else{let{pruned:M}=await z.updateRemoteRefs({fs:t,gitdir:l,remote:_,refs:ce,symrefs:B.symrefs,tags:b,prune:E,pruneTags:A});E&&(Ie.pruned=M)}if(Ie.HEAD=B.symrefs.get("HEAD"),Ie.HEAD===void 0){let{oid:M}=z.resolveAgainstMap({ref:"HEAD",map:ce});for(let[O,oe]of ce.entries())if(O!=="HEAD"&&oe===M){Ie.HEAD=O;break}}let kt=ve.startsWith("refs/tags")?"tag":"branch";if(Ie.FETCH_HEAD={oid:Pe,description:`${kt} '${xa(ve)}' of ${C}`},n||i){let M=Pk(Ie.progress);hu(M,async O=>{if(i&&await i(O),n){let oe=O.match(/([^:]*).*\((\d+?)\/(\d+?)\)/);oe&&await n({phase:oe[1].trim(),loaded:parseInt(oe[2],10),total:parseInt(oe[3],10)})}})}let At=Buffer.from(await Md(Ie.packfile));if(Ft.body.error)throw Ft.body.error;let je=At.slice(-20).toString("hex"),Z={defaultBranch:Ie.HEAD,fetchHead:Ie.FETCH_HEAD.oid,fetchHeadDescription:Ie.FETCH_HEAD.description};if(Ie.headers&&(Z.headers=Ie.headers),E&&(Z.pruned=Ie.pruned),je!==""&&!t6(At)){Z.packfile=`objects/pack/pack-${je}.pack`;let M=D(l,Z.packfile);await t.write(M,At);let O=Ce=>Xe({fs:t,cache:e,gitdir:l,oid:Ce}),oe=await Xc.fromPack({pack:At,getExternalRefDelta:O,onProgress:n});await t.write(M.replace(/\.pack$/,".idx"),await oe.toBuffer())}return Z}async function Rk({fs:t,bare:e=!1,dir:r,gitdir:n=e?r:D(r,".git"),defaultBranch:i="master"}){if(await t.exists(n+"/config"))return;let s=["hooks","info","objects/info","objects/pack","refs/heads","refs/tags"];s=s.map(a=>n+"/"+a);for(let a of s)await t.mkdir(a);await t.write(n+"/config",`[core] + repositoryformatversion = 0 + filemode = false + bare = ${e} +`+(e?"":` logallrefupdates = true +`)+` symlinks = false + ignorecase = true +`),await t.write(n+"/HEAD",`ref: refs/heads/${i} +`)}async function s6({fs:t,cache:e,http:r,onProgress:n,onMessage:i,onAuth:s,onAuthSuccess:a,onAuthFailure:o,onPostCheckout:l,dir:c,gitdir:u,url:f,corsProxy:d,ref:h,remote:m,depth:g,since:v,exclude:w,relative:b,singleBranch:k,noCheckout:x,noTags:E,headers:A,nonBlocking:y,batchSize:S=100}){try{if(await Rk({fs:t,gitdir:u}),await xk({fs:t,gitdir:u,remote:m,url:f,force:!1}),d){let P=await lt.get({fs:t,gitdir:u});await P.set("http.corsProxy",d),await lt.save({fs:t,gitdir:u,config:P})}let{defaultBranch:_,fetchHead:C}=await Av({fs:t,cache:e,http:r,onProgress:n,onMessage:i,onAuth:s,onAuthSuccess:a,onAuthFailure:o,gitdir:u,ref:h,remote:m,corsProxy:d,depth:g,since:v,exclude:w,relative:b,singleBranch:k,headers:A,tags:!E});if(C===null)return;h=h||_,h=h.replace("refs/heads/",""),await Ev({fs:t,cache:e,onProgress:n,onPostCheckout:l,dir:c,gitdir:u,ref:h,remote:m,noCheckout:x,nonBlocking:y,batchSize:S})}catch(_){throw await t.rmdir(u,{recursive:!0,maxRetries:10}).catch(()=>{}),_}}async function $k({fs:t,http:e,onProgress:r,onMessage:n,onAuth:i,onAuthSuccess:s,onAuthFailure:a,onPostCheckout:o,dir:l,gitdir:c=D(l,".git"),url:u,corsProxy:f=void 0,ref:d=void 0,remote:h="origin",depth:m=void 0,since:g=void 0,exclude:v=[],relative:w=!1,singleBranch:b=!1,noCheckout:k=!1,noTags:x=!1,headers:E={},cache:A={},nonBlocking:y=!1,batchSize:S=100}){try{T("fs",t),T("http",e),T("gitdir",c),k||T("dir",l),T("url",u);let _=new Q(t),C=await J({fsp:_,dotgit:c});return await s6({fs:_,cache:A,http:e,onProgress:r,onMessage:n,onAuth:i,onAuthSuccess:s,onAuthFailure:a,onPostCheckout:o,dir:l,gitdir:C,url:u,corsProxy:f,ref:d,remote:h,depth:m,since:g,exclude:v,relative:w,singleBranch:b,noCheckout:k,noTags:x,headers:E,nonBlocking:y,batchSize:S})}catch(_){throw _.caller="git.clone",_}}async function Ik({fs:t,onSign:e,dir:r,gitdir:n=D(r,".git"),message:i,author:s,committer:a,signingKey:o,amend:l=!1,dryRun:c=!1,noUpdateBranch:u=!1,ref:f,parent:d,tree:h,cache:m={}}){try{T("fs",t),l||T("message",i),o&&T("onSign",e);let g=new Q(t),v=await J({fsp:g,dotgit:n});return await Hd({fs:g,cache:m,onSign:e,gitdir:v,message:i,author:s,committer:a,signingKey:o,amend:l,dryRun:c,noUpdateBranch:u,ref:f,parent:d,tree:h})}catch(g){throw g.caller="git.commit",g}}async function Fk({fs:t,dir:e,gitdir:r=D(e,".git"),fullname:n=!1,test:i=!1}){try{T("fs",t),T("gitdir",r);let s=new Q(t),a=await J({fsp:s,dotgit:r});return await Ls({fs:s,gitdir:a,fullname:n,test:i})}catch(s){throw s.caller="git.currentBranch",s}}async function a6({fs:t,gitdir:e,ref:r}){if(r=r.startsWith("refs/heads/")?r:`refs/heads/${r}`,!await z.exists({fs:t,gitdir:e,ref:r}))throw new Be(r);let i=await z.expand({fs:t,gitdir:e,ref:r}),s=await Ls({fs:t,gitdir:e,fullname:!0});if(i===s){let l=await z.resolve({fs:t,gitdir:e,ref:i});await z.writeRef({fs:t,gitdir:e,ref:"HEAD",value:l})}await z.deleteRef({fs:t,gitdir:e,ref:i});let a=xa(r),o=await lt.get({fs:t,gitdir:e});await o.deleteSection("branch",a),await lt.save({fs:t,gitdir:e,config:o})}async function Ok({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n}){try{T("fs",t),T("ref",n);let i=new Q(t),s=await J({fsp:i,dotgit:r});return await a6({fs:i,gitdir:s,ref:n})}catch(i){throw i.caller="git.deleteBranch",i}}async function Mk({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n}){try{T("fs",t),T("ref",n);let i=new Q(t),s=await J({fsp:i,dotgit:r});await z.deleteRef({fs:i,gitdir:s,ref:n})}catch(i){throw i.caller="git.deleteRef",i}}async function o6({fs:t,gitdir:e,remote:r}){let n=await lt.get({fs:t,gitdir:e});await n.deleteSection("remote",r),await lt.save({fs:t,gitdir:e,config:n})}async function Dk({fs:t,dir:e,gitdir:r=D(e,".git"),remote:n}){try{T("fs",t),T("remote",n);let i=new Q(t),s=await J({fsp:i,dotgit:r});return await o6({fs:i,gitdir:s,remote:n})}catch(i){throw i.caller="git.deleteRemote",i}}async function l6({fs:t,gitdir:e,ref:r}){r=r.startsWith("refs/tags/")?r:`refs/tags/${r}`,await z.deleteRef({fs:t,gitdir:e,ref:r})}async function Lk({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n}){try{T("fs",t),T("ref",n);let i=new Q(t),s=await J({fsp:i,dotgit:r});return await l6({fs:i,gitdir:s,ref:n})}catch(i){throw i.caller="git.deleteTag",i}}async function c6({fs:t,gitdir:e,oid:r}){let n=r.slice(0,2);return(await t.readdir(`${e}/objects/${n}`)).map(s=>`${n}${s}`).filter(s=>s.startsWith(r))}async function u6({fs:t,cache:e,gitdir:r,oid:n,getExternalRefDelta:i}){let s=[],a=await t.readdir(D(r,"objects/pack"));a=a.filter(o=>o.endsWith(".idx"));for(let o of a){let l=`${r}/objects/pack/${o}`,c=await Sv({fs:t,cache:e,filename:l,getExternalRefDelta:i});if(c.error)throw new he(c.error);for(let u of c.offsets.keys())u.startsWith(n)&&s.push(u)}return s}async function f6({fs:t,cache:e,gitdir:r,oid:n}){let i=o=>Xe({fs:t,cache:e,gitdir:r,oid:o}),s=await c6({fs:t,gitdir:r,oid:n}),a=await u6({fs:t,cache:e,gitdir:r,oid:n,getExternalRefDelta:i});for(let o of a)s.indexOf(o)===-1&&s.push(o);if(s.length===1)return s[0];throw s.length>1?new Zc("oids",n,s):new Be(`an object matching "${n}"`)}async function Nk({fs:t,dir:e,gitdir:r=D(e,".git"),oid:n,cache:i={}}){try{T("fs",t),T("gitdir",r),T("oid",n);let s=new Q(t),a=await J({fsp:s,dotgit:r});return await f6({fs:s,cache:i,gitdir:a,oid:n})}catch(s){throw s.caller="git.expandOid",s}}async function Bk({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n}){try{T("fs",t),T("gitdir",r),T("ref",n);let i=new Q(t),s=await J({fsp:i,dotgit:r});return await z.expand({fs:i,gitdir:s,ref:n})}catch(i){throw i.caller="git.expandRef",i}}async function Cv({fs:t,cache:e,gitdir:r,oids:n}){let i={},s=n.length,a=n.map((o,l)=>({index:l,oid:o}));for(;a.length;){let o=new Set;for(let{oid:c,index:u}of a)i[c]||(i[c]=new Set),i[c].add(u),i[c].size===s&&o.add(c);if(o.size>0)return[...o];let l=new Map;for(let{oid:c,index:u}of a)try{let{object:f}=await Xe({fs:t,cache:e,gitdir:r,oid:c}),d=kr.from(f),{parent:h}=d.parseHeaders();for(let m of h)(!i[m]||!i[m].has(u))&&l.set(m+":"+u,{oid:m,index:u})}catch(f){}a=Array.from(l.values())}return[]}var ov=/^.*(\r?\n|$)/gm;function d6({branches:t,contents:e}){let r=t[1],n=t[2],i=e[0],s=e[1],a=e[2],o=s.match(ov),l=i.match(ov),c=a.match(ov),u=q3(o,l,c),f=7,d="",h=!0;for(let m of u)m.ok&&(d+=m.ok.join("")),m.conflict&&(h=!1,d+=`${"<".repeat(f)} ${r} +`,d+=m.conflict.a.join(""),d+=`${"=".repeat(f)} +`,d+=m.conflict.b.join(""),d+=`${">".repeat(f)} ${n} +`);return{cleanMerge:h,mergedText:d}}async function h6({fs:t,cache:e,dir:r,gitdir:n=D(r,".git"),index:i,ourOid:s,baseOid:a,theirOid:o,ourName:l="ours",baseName:c="base",theirName:u="theirs",dryRun:f=!1,abortOnConflict:d=!0,mergeDriver:h}){let m=Xr({ref:s}),g=Xr({ref:a}),v=Xr({ref:o}),w=[],b=[],k=[],x=[],E=await Fs({fs:t,cache:e,dir:r,gitdir:n,trees:[m,g,v],map:async function(A,[y,S,_]){let C=Pd(A),P=await Od(y,S),N=await Od(_,S);switch(`${P}-${N}`){case"false-false":return{mode:await S.mode(),path:C,oid:await S.oid(),type:await S.type()};case"false-true":return!_&&await y.type()==="tree"?{mode:await y.mode(),path:C,oid:await y.oid(),type:await y.type()}:_?{mode:await _.mode(),path:C,oid:await _.oid(),type:await _.type()}:void 0;case"true-false":return!y&&await _.type()==="tree"?{mode:await _.mode(),path:C,oid:await _.oid(),type:await _.type()}:y?{mode:await y.mode(),path:C,oid:await y.oid(),type:await y.type()}:void 0;case"true-true":{if(y&&_&&await y.type()==="tree"&&await _.type()==="tree")return{mode:await y.mode(),path:C,oid:await y.oid(),type:"tree"};if(y&&_&&await y.type()==="blob"&&await _.type()==="blob")return p6({fs:t,gitdir:n,path:C,ours:y,base:S,theirs:_,ourName:l,baseName:c,theirName:u,mergeDriver:h}).then(async B=>{if(B.cleanMerge)d||i.insert({filepath:A,oid:B.mergeResult.oid,stage:0});else if(w.push(A),b.push(A),!d){let H="";S&&await S.type()==="blob"&&(H=await S.oid());let ce=await y.oid(),Pe=await _.oid();i.delete({filepath:A}),H&&i.insert({filepath:A,oid:H,stage:1}),i.insert({filepath:A,oid:ce,stage:2}),i.insert({filepath:A,oid:Pe,stage:3})}return B.mergeResult});if(S&&!y&&_&&await S.type()==="blob"&&await _.type()==="blob"){if(w.push(A),k.push(A),!d){let B=await S.oid(),H=await _.oid();i.delete({filepath:A}),i.insert({filepath:A,oid:B,stage:1}),i.insert({filepath:A,oid:H,stage:3})}return{mode:await _.mode(),oid:await _.oid(),type:"blob",path:C}}if(S&&y&&!_&&await S.type()==="blob"&&await y.type()==="blob"){if(w.push(A),x.push(A),!d){let B=await S.oid(),H=await y.oid();i.delete({filepath:A}),i.insert({filepath:A,oid:B,stage:1}),i.insert({filepath:A,oid:H,stage:2})}return{mode:await y.mode(),oid:await y.oid(),type:"blob",path:C}}if(S&&!y&&!_&&(await S.type()==="blob"||await S.type()==="tree"))return;throw new Xo}}},reduce:w.length!==0&&(!r||d)?void 0:async(A,y)=>{let S=y.filter(Boolean);if(A&&!(A&&A.type==="tree"&&S.length===0&&A.path!==".")){if(S.length>0||A.path==="."&&S.length===0){let C=new Er(S).toObject(),P=await Ar({fs:t,gitdir:n,type:"tree",object:C,dryRun:f});A.oid=P}return A}}});return w.length!==0?(r&&!d&&await Fs({fs:t,cache:e,dir:r,gitdir:n,trees:[Xr({ref:E.oid})],map:async function(A,[y]){let S=`${r}/${A}`;if(await y.type()==="blob"){let _=await y.mode(),C=new TextDecoder().decode(await y.content());await t.write(S,C,{mode:_})}return!0}}),new Zo(w,b,k,x)):E.oid}async function p6({fs:t,gitdir:e,path:r,ours:n,base:i,theirs:s,ourName:a,theirName:o,baseName:l,dryRun:c,mergeDriver:u=d6}){let f="blob",d="100755",h="",m="";i&&await i.type()==="blob"&&(d=await i.mode(),h=await i.oid(),m=Buffer.from(await i.content()).toString("utf8"));let g=d===await n.mode()?await s.mode():await n.mode();if(await n.oid()===await s.oid())return{cleanMerge:!0,mergeResult:{mode:g,path:r,oid:await n.oid(),type:f}};if(await n.oid()===h)return{cleanMerge:!0,mergeResult:{mode:g,path:r,oid:await s.oid(),type:f}};if(await s.oid()===h)return{cleanMerge:!0,mergeResult:{mode:g,path:r,oid:await n.oid(),type:f}};let v=Buffer.from(await n.content()).toString("utf8"),w=Buffer.from(await s.content()).toString("utf8"),{mergedText:b,cleanMerge:k}=await u({branches:[l,a,o],contents:[m,v,w],path:r}),x=await Ar({fs:t,gitdir:e,type:"blob",object:Buffer.from(b,"utf8"),dryRun:c});return{cleanMerge:k,mergeResult:{mode:g,path:r,oid:x,type:f}}}async function Hk({fs:t,cache:e,dir:r,gitdir:n,ours:i,theirs:s,fastForward:a=!0,fastForwardOnly:o=!1,dryRun:l=!1,noUpdateBranch:c=!1,abortOnConflict:u=!0,message:f,author:d,committer:h,signingKey:m,onSign:g,mergeDriver:v,allowUnrelatedHistories:w=!1}){i===void 0&&(i=await Ls({fs:t,gitdir:n,fullname:!0})),i=await z.expand({fs:t,gitdir:n,ref:i}),s=await z.expand({fs:t,gitdir:n,ref:s});let b=await z.resolve({fs:t,gitdir:n,ref:i}),k=await z.resolve({fs:t,gitdir:n,ref:s}),x=await Cv({fs:t,cache:e,gitdir:n,oids:[b,k]});if(x.length!==1)if(x.length===0&&w)x.push("4b825dc642cb6eb9a060e54bf8d69288fbee4904");else throw new Xo;let E=x[0];if(E===k)return{oid:b,alreadyMerged:!0};if(a&&E===b)return!l&&!c&&await z.writeRef({fs:t,gitdir:n,ref:i,value:k}),{oid:k,fastForward:!0};{if(o)throw new eu;let A=await ht.acquire({fs:t,gitdir:n,cache:e,allowUnmerged:!1},async S=>h6({fs:t,cache:e,dir:r,gitdir:n,index:S,ourOid:b,theirOid:k,baseOid:E,ourName:xa(i),baseName:"base",theirName:xa(s),dryRun:l,abortOnConflict:u,mergeDriver:v}));if(A instanceof Zo)throw A;return f||(f=`Merge branch '${xa(s)}' into ${xa(i)}`),{oid:await Hd({fs:t,cache:e,gitdir:n,message:f,ref:i,tree:A,parent:[b,k],author:d,committer:h,signingKey:m,onSign:g,dryRun:l,noUpdateBranch:c}),tree:A,mergeCommit:!0}}}async function Uk({fs:t,cache:e,http:r,onProgress:n,onMessage:i,onAuth:s,onAuthSuccess:a,onAuthFailure:o,dir:l,gitdir:c,ref:u,url:f,remote:d,remoteRef:h,prune:m,pruneTags:g,fastForward:v,fastForwardOnly:w,corsProxy:b,singleBranch:k,headers:x,author:E,committer:A,signingKey:y}){try{if(!u){let C=await Ls({fs:t,gitdir:c});if(!C)throw new Sr("ref");u=C}let{fetchHead:S,fetchHeadDescription:_}=await Av({fs:t,cache:e,http:r,onProgress:n,onMessage:i,onAuth:s,onAuthSuccess:a,onAuthFailure:o,gitdir:c,corsProxy:b,ref:u,url:f,remote:d,remoteRef:h,singleBranch:k,headers:x,prune:m,pruneTags:g});await Hk({fs:t,cache:e,gitdir:c,ours:u,theirs:S,fastForward:v,fastForwardOnly:w,message:`Merge ${_}`,author:E,committer:A,signingKey:y,dryRun:!1,noUpdateBranch:!1}),await Ev({fs:t,cache:e,onProgress:n,dir:l,gitdir:c,ref:u,remote:d,noCheckout:!1})}catch(S){throw S.caller="git.pull",S}}async function Gk({fs:t,http:e,onProgress:r,onMessage:n,onAuth:i,onAuthSuccess:s,onAuthFailure:a,dir:o,gitdir:l=D(o,".git"),ref:c,url:u,remote:f,remoteRef:d,corsProxy:h,singleBranch:m,headers:g={},cache:v={}}){try{T("fs",t),T("http",e),T("gitdir",l);let w={name:"",email:"",timestamp:Date.now(),timezoneOffset:0},b=new Q(t),k=await J({fsp:b,dotgit:l});return await Uk({fs:b,cache:v,http:e,onProgress:r,onMessage:n,onAuth:i,onAuthSuccess:s,onAuthFailure:a,dir:o,gitdir:k,ref:c,url:u,remote:f,remoteRef:d,fastForwardOnly:!0,corsProxy:h,singleBranch:m,headers:g,author:w,committer:w})}catch(w){throw w.caller="git.fastForward",w}}async function jk({fs:t,http:e,onProgress:r,onMessage:n,onAuth:i,onAuthSuccess:s,onAuthFailure:a,dir:o,gitdir:l=D(o,".git"),ref:c,remote:u,remoteRef:f,url:d,corsProxy:h,depth:m=null,since:g=null,exclude:v=[],relative:w=!1,tags:b=!1,singleBranch:k=!1,headers:x={},prune:E=!1,pruneTags:A=!1,cache:y={}}){try{T("fs",t),T("http",e),T("gitdir",l);let S=new Q(t),_=await J({fsp:S,dotgit:l});return await Av({fs:S,cache:y,http:e,onProgress:r,onMessage:n,onAuth:i,onAuthSuccess:s,onAuthFailure:a,gitdir:_,ref:c,remote:u,remoteRef:f,url:d,corsProxy:h,depth:m,since:g,exclude:v,relative:w,tags:b,singleBranch:k,headers:x,prune:E,pruneTags:A})}catch(S){throw S.caller="git.fetch",S}}async function qk({fs:t,dir:e,gitdir:r=D(e,".git"),oids:n,cache:i={}}){try{T("fs",t),T("gitdir",r),T("oids",n);let s=new Q(t),a=await J({fsp:s,dotgit:r});return await Cv({fs:s,cache:i,gitdir:a,oids:n})}catch(s){throw s.caller="git.findMergeBase",s}}async function Wk({fs:t,filepath:e}){if(await t.exists(D(e,".git")))return e;{let r=Sa(e);if(r===e)throw new Be(`git root for ${e}`);return Wk({fs:t,filepath:r})}}async function zk({fs:t,filepath:e}){try{return T("fs",t),T("filepath",e),await Wk({fs:new Q(t),filepath:e})}catch(r){throw r.caller="git.findRoot",r}}async function Vk({fs:t,dir:e,gitdir:r=D(e,".git"),path:n}){try{T("fs",t),T("gitdir",r),T("path",n);let i=new Q(t),s=await J({fsp:i,dotgit:r});return await cu({fs:i,gitdir:s,path:n})}catch(i){throw i.caller="git.getConfig",i}}async function m6({fs:t,gitdir:e,path:r}){return(await lt.get({fs:t,gitdir:e})).getall(r)}async function Yk({fs:t,dir:e,gitdir:r=D(e,".git"),path:n}){try{T("fs",t),T("gitdir",r),T("path",n);let i=new Q(t),s=await J({fsp:i,dotgit:r});return await m6({fs:i,gitdir:s,path:n})}catch(i){throw i.caller="git.getConfigAll",i}}async function Xk({http:t,onAuth:e,onAuthSuccess:r,onAuthFailure:n,corsProxy:i,url:s,headers:a={},forPush:o=!1}){try{T("http",t),T("url",s);let c=await nl.getRemoteHelperFor({url:s}).discover({http:t,onAuth:e,onAuthSuccess:r,onAuthFailure:n,corsProxy:i,service:o?"git-receive-pack":"git-upload-pack",url:s,headers:a,protocolVersion:1}),u={capabilities:[...c.capabilities]};for(let[f,d]of c.refs){let h=f.split("/"),m=h.pop(),g=u;for(let v of h)g[v]=g[v]||{},g=g[v];g[m]=d}for(let[f,d]of c.symrefs){let h=f.split("/"),m=h.pop(),g=u;for(let v of h)g[v]=g[v]||{},g=g[v];g[m]=d}return u}catch(l){throw l.caller="git.getRemoteInfo",l}}function Zk(t,e,r,n){let i=[];for(let[s,a]of t.refs){if(e&&!s.startsWith(e))continue;if(s.endsWith("^{}")){if(n){let l=s.replace("^{}",""),c=i[i.length-1],u=c.ref===l?c:i.find(f=>f.ref===l);if(u===void 0)throw new Error("I did not expect this to happen");u.peeled=a}continue}let o={ref:s,oid:a};r&&t.symrefs.has(s)&&(o.target=t.symrefs.get(s)),i.push(o)}return i}async function Kk({http:t,onAuth:e,onAuthSuccess:r,onAuthFailure:n,corsProxy:i,url:s,headers:a={},forPush:o=!1,protocolVersion:l=2}){try{T("http",t),T("url",s);let u=await nl.getRemoteHelperFor({url:s}).discover({http:t,onAuth:e,onAuthSuccess:r,onAuthFailure:n,corsProxy:i,service:o?"git-receive-pack":"git-upload-pack",url:s,headers:a,protocolVersion:l});if(u.protocolVersion===2)return{protocolVersion:u.protocolVersion,capabilities:u.capabilities2};let f={};for(let d of u.capabilities){let[h,m]=d.split("=");m?f[h]=m:f[h]=!0}return{protocolVersion:1,capabilities:f,refs:Zk(u,void 0,!0,!0)}}catch(c){throw c.caller="git.getRemoteInfo2",c}}async function g6({type:t,object:e,format:r="content",oid:n=void 0}){return r!=="deflated"&&(r!=="wrapped"&&(e=$s.wrap({type:t,object:e})),n=await zi(e)),{oid:n,object:e}}async function Qk({object:t}){try{T("object",t),typeof t=="string"?t=Buffer.from(t,"utf8"):t instanceof Uint8Array||(t=new Uint8Array(t));let e="blob",{oid:r,object:n}=await g6({type:e,format:"content",object:t});return{oid:r,type:e,object:n,format:"wrapped"}}catch(e){throw e.caller="git.hashBlob",e}}async function v6({fs:t,cache:e,onProgress:r,dir:n,gitdir:i,filepath:s}){try{s=D(n,s);let a=await t.read(s),o=c=>Xe({fs:t,cache:e,gitdir:i,oid:c}),l=await Xc.fromPack({pack:a,getExternalRefDelta:o,onProgress:r});return await t.write(s.replace(/\.pack$/,".idx"),await l.toBuffer()),{oids:[...l.hashes]}}catch(a){throw a.caller="git.indexPack",a}}async function Jk({fs:t,onProgress:e,dir:r,gitdir:n=D(r,".git"),filepath:i,cache:s={}}){try{T("fs",t),T("dir",r),T("gitdir",r),T("filepath",i);let a=new Q(t),o=await J({fsp:a,dotgit:n});return await v6({fs:a,cache:s,onProgress:e,dir:r,gitdir:o,filepath:i})}catch(a){throw a.caller="git.indexPack",a}}async function eA({fs:t,bare:e=!1,dir:r,gitdir:n=e?r:D(r,".git"),defaultBranch:i="master"}){try{T("fs",t),T("gitdir",n),e||T("dir",r);let s=new Q(t),a=await J({fsp:s,dotgit:n});return await Rk({fs:s,bare:e,dir:r,gitdir:a,defaultBranch:i})}catch(s){throw s.caller="git.init",s}}async function tA({fs:t,cache:e,gitdir:r,oid:n,ancestor:i,depth:s}){let a=await ka.read({fs:t,gitdir:r});if(!n)throw new Sr("oid");if(!i)throw new Sr("ancestor");if(n===i)return!1;let o=[n],l=new Set,c=0;for(;o.length;){if(c++===s)throw new ru(s);let u=o.shift(),{type:f,object:d}=await Xe({fs:t,cache:e,gitdir:r,oid:u});if(f!=="commit")throw new fr(u,f,"commit");let h=kr.from(d).parse();for(let m of h.parent)if(m===i)return!0;if(!a.has(u))for(let m of h.parent)l.has(m)||(o.push(m),l.add(m))}return!1}async function rA({fs:t,dir:e,gitdir:r=D(e,".git"),oid:n,ancestor:i,depth:s=-1,cache:a={}}){try{T("fs",t),T("gitdir",r),T("oid",n),T("ancestor",i);let o=new Q(t),l=await J({fsp:o,dotgit:r});return await tA({fs:o,cache:a,gitdir:l,oid:n,ancestor:i,depth:s})}catch(o){throw o.caller="git.isDescendent",o}}async function nA({fs:t,dir:e,gitdir:r=D(e,".git"),filepath:n}){try{T("fs",t),T("dir",e),T("gitdir",r),T("filepath",n);let i=new Q(t),s=await J({fsp:i,dotgit:r});return Os.isIgnored({fs:i,dir:e,gitdir:s,filepath:n})}catch(i){throw i.caller="git.isIgnored",i}}async function iA({fs:t,dir:e,gitdir:r=D(e,".git"),remote:n}){try{T("fs",t),T("gitdir",r);let i=new Q(t),s=await J({fsp:i,dotgit:r});return z.listBranches({fs:i,gitdir:s,remote:n})}catch(i){throw i.caller="git.listBranches",i}}async function w6({fs:t,gitdir:e,ref:r,cache:n}){if(r){let i=await z.resolve({gitdir:e,fs:t,ref:r}),s=[];return await sA({fs:t,cache:n,gitdir:e,oid:i,filenames:s,prefix:""}),s}else return ht.acquire({fs:t,gitdir:e,cache:n},async function(i){return i.entries.map(s=>s.path)})}async function sA({fs:t,cache:e,gitdir:r,oid:n,filenames:i,prefix:s}){let{tree:a}=await al({fs:t,cache:e,gitdir:r,oid:n});for(let o of a)o.type==="tree"?await sA({fs:t,cache:e,gitdir:r,oid:o.oid,filenames:i,prefix:D(s,o.path)}):i.push(D(s,o.path))}async function aA({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n,cache:i={}}){try{T("fs",t),T("gitdir",r);let s=new Q(t),a=await J({fsp:s,dotgit:r});return await w6({fs:s,cache:i,gitdir:a,ref:n})}catch(s){throw s.caller="git.listFiles",s}}async function y6({fs:t,cache:e,gitdir:r,ref:n}){let i;try{i=await z.resolve({gitdir:r,fs:t,ref:n})}catch(o){if(o instanceof Be)return[]}return(await al({fs:t,cache:e,gitdir:r,oid:i})).tree.map(o=>({target:o.path,note:o.oid}))}async function oA({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n="refs/notes/commits",cache:i={}}){try{T("fs",t),T("gitdir",r),T("ref",n);let s=new Q(t),a=await J({fsp:s,dotgit:r});return await y6({fs:s,cache:i,gitdir:a,ref:n})}catch(s){throw s.caller="git.listNotes",s}}async function lA({fs:t,dir:e,gitdir:r=D(e,".git"),filepath:n}){try{T("fs",t),T("gitdir",r);let i=new Q(t),s=await J({fsp:i,dotgit:r});return z.listRefs({fs:i,gitdir:s,filepath:n})}catch(i){throw i.caller="git.listRefs",i}}async function b6({fs:t,gitdir:e}){let r=await lt.get({fs:t,gitdir:e}),n=await r.getSubsections("remote");return Promise.all(n.map(async s=>{let a=await r.get(`remote.${s}.url`);return{remote:s,url:a}}))}async function cA({fs:t,dir:e,gitdir:r=D(e,".git")}){try{T("fs",t),T("gitdir",r);let n=new Q(t),i=await J({fsp:n,dotgit:r});return await b6({fs:n,gitdir:i})}catch(n){throw n.caller="git.listRemotes",n}}async function _6(t){let e=st.streamReader(t),r=[],n;for(;n=await e(),n!==!0;){if(n===null)continue;n=n.toString("utf8").replace(/\n$/,"");let[i,s,...a]=n.split(" "),o={ref:s,oid:i};for(let l of a){let[c,u]=l.split(":");c==="symref-target"?o.target=u:c==="peeled"&&(o.peeled=u)}r.push(o)}return r}async function x6({prefix:t,symrefs:e,peelTags:r}){let n=[];return n.push(st.encode(`command=ls-refs +`)),n.push(st.encode(`agent=${Ud.agent} +`)),(r||e||t)&&n.push(st.delim()),r&&n.push(st.encode("peel")),e&&n.push(st.encode("symrefs")),t&&n.push(st.encode(`ref-prefix ${t}`)),n.push(st.flush()),n}async function uA({http:t,onAuth:e,onAuthSuccess:r,onAuthFailure:n,corsProxy:i,url:s,headers:a={},forPush:o=!1,protocolVersion:l=2,prefix:c,symrefs:u,peelTags:f}){try{T("http",t),T("url",s);let d=await rl.discover({http:t,onAuth:e,onAuthSuccess:r,onAuthFailure:n,corsProxy:i,service:o?"git-receive-pack":"git-upload-pack",url:s,headers:a,protocolVersion:l});if(d.protocolVersion===1)return Zk(d,c,u,f);let h=await x6({prefix:c,symrefs:u,peelTags:f}),m=await rl.connect({http:t,auth:d.auth,headers:a,corsProxy:i,service:o?"git-receive-pack":"git-upload-pack",url:s,body:h});return _6(m.body)}catch(d){throw d.caller="git.listServerRefs",d}}async function fA({fs:t,dir:e,gitdir:r=D(e,".git")}){try{T("fs",t),T("gitdir",r);let n=new Q(t),i=await J({fsp:n,dotgit:r});return z.listTags({fs:n,gitdir:i})}catch(n){throw n.caller="git.listTags",n}}function S6(t,e){return t.committer.timestamp-e.committer.timestamp}var E6="e69de29bb2d1d6434b8b29ae775ad8c2e48c5391";async function ek({fs:t,cache:e,gitdir:r,oid:n,fileId:i}){if(i===E6)return;let s=n,a,o=await Jo({fs:t,cache:e,gitdir:r,oid:n}),l=o.tree;return i===o.oid?a=o.path:(a=await dA({fs:t,cache:e,gitdir:r,tree:l,fileId:i,oid:s}),Array.isArray(a)&&(a.length===0?a=void 0:a.length===1&&(a=a[0]))),a}async function dA({fs:t,cache:e,gitdir:r,tree:n,fileId:i,oid:s,filepaths:a=[],parentPath:o=""}){let l=n.entries().map(function(c){let u;return c.oid===i?(u=D(o,c.path),a.push(u)):c.type==="tree"&&(u=Xe({fs:t,cache:e,gitdir:r,oid:c.oid}).then(function({object:f}){return dA({fs:t,cache:e,gitdir:r,tree:Er.from(f),fileId:i,oid:s,filepaths:a,parentPath:D(o,c.path)})})),u});return await Promise.all(l),a}async function k6({fs:t,cache:e,gitdir:r,filepath:n,ref:i,depth:s,since:a,force:o,follow:l}){let c=typeof a=="undefined"?void 0:Math.floor(a.valueOf()/1e3),u=[],f=await ka.read({fs:t,gitdir:r}),d=await z.resolve({fs:t,gitdir:r,ref:i}),h=[await tl({fs:t,cache:e,gitdir:r,oid:d})],m,g,v;function w(b){v&&n&&u.push(b)}for(;h.length>0;){let b=h.pop();if(c!==void 0&&b.commit.committer.timestamp<=c)break;if(n){let k;try{k=await fu({fs:t,cache:e,gitdir:r,oid:b.commit.tree,filepath:n}),g&&m!==k&&u.push(g),m=k,g=b,v=!0}catch(x){if(x instanceof Be){let E=l&&m;if(E&&(E=await ek({fs:t,cache:e,gitdir:r,oid:b.commit.tree,fileId:m}),E))if(Array.isArray(E)){if(g){let A=await ek({fs:t,cache:e,gitdir:r,oid:g.commit.tree,fileId:m});if(Array.isArray(A))if(E=E.filter(y=>A.indexOf(y)===-1),E.length===1)E=E[0],n=E,g&&u.push(g);else{E=!1,g&&u.push(g);break}}}else n=E,g&&u.push(g);if(!E){if(v&&m&&(u.push(g),!o))break;if(!o&&!l)throw x}g=b,v=!1}else throw x}}else u.push(b);if(s!==void 0&&u.length===s){w(b);break}if(!f.has(b.oid))for(let k of b.commit.parent){let x=await tl({fs:t,cache:e,gitdir:r,oid:k});h.map(E=>E.oid).includes(x.oid)||h.push(x)}h.length===0&&w(b),h.sort((k,x)=>S6(k.commit,x.commit))}return u}async function hA({fs:t,dir:e,gitdir:r=D(e,".git"),filepath:n,ref:i="HEAD",depth:s,since:a,force:o,follow:l,cache:c={}}){try{T("fs",t),T("gitdir",r),T("ref",i);let u=new Q(t),f=await J({fsp:u,dotgit:r});return await k6({fs:u,cache:c,gitdir:f,filepath:n,ref:i,depth:s,since:a,force:o,follow:l})}catch(u){throw u.caller="git.log",u}}async function pA({fs:t,onSign:e,dir:r,gitdir:n=D(r,".git"),ours:i,theirs:s,fastForward:a=!0,fastForwardOnly:o=!1,dryRun:l=!1,noUpdateBranch:c=!1,abortOnConflict:u=!0,message:f,author:d,committer:h,signingKey:m,cache:g={},mergeDriver:v,allowUnrelatedHistories:w=!1}){try{T("fs",t),m&&T("onSign",e);let b=new Q(t),k=await J({fsp:b,dotgit:n}),x=await Ms({fs:b,gitdir:k,author:d});if(!x&&(!o||!a))throw new Kt("author");let E=await el({fs:b,gitdir:k,author:x,committer:h});if(!E&&(!o||!a))throw new Kt("committer");return await Hk({fs:b,cache:g,dir:r,gitdir:k,ours:i,theirs:s,fastForward:a,fastForwardOnly:o,dryRun:l,noUpdateBranch:c,abortOnConflict:u,message:f,author:x,committer:E,signingKey:m,onSign:e,mergeDriver:v,allowUnrelatedHistories:w})}catch(b){throw b.caller="git.merge",b}}var A6={commit:16,tree:32,blob:48,tag:64,ofs_delta:96,ref_delta:112};async function mA({fs:t,cache:e,dir:r,gitdir:n=D(r,".git"),oids:i}){let s=new rk,a=[];function o(u,f){let d=Buffer.from(u,f);a.push(d),s.update(d)}async function l({stype:u,object:f}){let d=A6[u],h=f.length,m=h>15?128:0,g=h&15;h=h>>>4;let v=(m|d|g).toString(16);for(o(v,"hex");m;)m=h>127?128:0,v=m|h&127,o(_v(2,v),"hex"),h=h>>>7;o(Buffer.from(await pk(f)))}o("PACK"),o("00000002","hex"),o(_v(8,i.length),"hex");for(let u of i){let{type:f,object:d}=await Xe({fs:t,cache:e,gitdir:n,oid:u});await l({write:o,object:d,stype:f})}let c=s.digest();return a.push(c),a}async function C6({fs:t,cache:e,gitdir:r,oids:n,write:i}){let s=await mA({fs:t,cache:e,gitdir:r,oids:n}),a=Buffer.from(await Md(s)),l=`pack-${a.slice(-20).toString("hex")}.pack`;return i?(await t.write(D(r,`objects/pack/${l}`),a),{filename:l}):{filename:l,packfile:new Uint8Array(a)}}async function gA({fs:t,dir:e,gitdir:r=D(e,".git"),oids:n,write:i=!1,cache:s={}}){try{T("fs",t),T("gitdir",r),T("oids",n);let a=new Q(t),o=await J({fsp:a,dotgit:r});return await C6({fs:a,cache:s,gitdir:o,oids:n,write:i})}catch(a){throw a.caller="git.packObjects",a}}async function vA({fs:t,http:e,onProgress:r,onMessage:n,onAuth:i,onAuthSuccess:s,onAuthFailure:a,dir:o,gitdir:l=D(o,".git"),ref:c,url:u,remote:f,remoteRef:d,prune:h=!1,pruneTags:m=!1,fastForward:g=!0,fastForwardOnly:v=!1,corsProxy:w,singleBranch:b,headers:k={},author:x,committer:E,signingKey:A,cache:y={}}){try{T("fs",t),T("gitdir",l);let S=new Q(t),_=await J({fsp:S,dotgit:l}),C=await Ms({fs:S,gitdir:_,author:x});if(!C)throw new Kt("author");let P=await el({fs:S,gitdir:_,author:C,committer:E});if(!P)throw new Kt("committer");return await Uk({fs:S,cache:y,http:e,onProgress:r,onMessage:n,onAuth:i,onAuthSuccess:s,onAuthFailure:a,dir:o,gitdir:_,ref:c,url:u,remote:f,remoteRef:d,fastForward:g,fastForwardOnly:v,corsProxy:w,singleBranch:b,headers:k,author:C,committer:P,signingKey:A,prune:h,pruneTags:m})}catch(S){throw S.caller="git.pull",S}}async function T6({fs:t,cache:e,dir:r,gitdir:n=D(r,".git"),start:i,finish:s}){let a=await ka.read({fs:t,gitdir:n}),o=new Set,l=new Set;for(let f of i)o.add(await z.resolve({fs:t,gitdir:n,ref:f}));for(let f of s)try{let d=await z.resolve({fs:t,gitdir:n,ref:f});l.add(d)}catch(d){}let c=new Set;async function u(f){c.add(f);let{type:d,object:h}=await Xe({fs:t,cache:e,gitdir:n,oid:f});if(d==="tag"){let g=Zr.from(h).headers().object;return u(g)}if(d!=="commit")throw new fr(f,d,"commit");if(!a.has(f)){let g=kr.from(h).headers().parent;for(f of g)!l.has(f)&&!c.has(f)&&await u(f)}}for(let f of o)await u(f);return c}async function lv({fs:t,cache:e,dir:r,gitdir:n=D(r,".git"),oids:i}){let s=new Set;async function a(o){if(s.has(o))return;s.add(o);let{type:l,object:c}=await Xe({fs:t,cache:e,gitdir:n,oid:o});if(l==="tag"){let f=Zr.from(c).headers().object;await a(f)}else if(l==="commit"){let f=kr.from(c).headers().tree;await a(f)}else if(l==="tree"){let u=Er.from(c);for(let f of u)f.type==="blob"&&s.add(f.oid),f.type==="tree"&&await a(f.oid)}}for(let o of i)await a(o);return s}async function P6(t){let e={},r="",n=st.streamReader(t),i=await n();for(;i!==!0;)i!==null&&(r+=i.toString("utf8")+` +`),i=await n();let s=r.toString("utf8").split(` +`);if(i=s.shift(),!i.startsWith("unpack "))throw new Ea('unpack ok" or "unpack [error message]',i);e.ok=i==="unpack ok",e.ok||(e.error=i.slice(7)),e.refs={};for(let a of s){if(a.trim()==="")continue;let o=a.slice(0,2),l=a.slice(3),c=l.indexOf(" ");c===-1&&(c=l.length);let u=l.slice(0,c),f=l.slice(c+1);e.refs[u]={ok:o==="ok",error:f}}return e}async function R6({capabilities:t=[],triplets:e=[]}){let r=[],n=`\0 ${t.join(" ")}`;for(let i of e)r.push(st.encode(`${i.oldoid} ${i.oid} ${i.fullRef}${n} +`)),n="";return r.push(st.flush()),r}async function $6({fs:t,cache:e,http:r,onProgress:n,onMessage:i,onAuth:s,onAuthSuccess:a,onAuthFailure:o,onPrePush:l,gitdir:c,ref:u,remoteRef:f,remote:d,url:h,force:m=!1,delete:g=!1,corsProxy:v,headers:w={}}){let b=u||await Ls({fs:t,gitdir:c});if(typeof b=="undefined")throw new Sr("ref");let k=await lt.get({fs:t,gitdir:c});d=d||await k.get(`branch.${b}.pushRemote`)||await k.get("remote.pushDefault")||await k.get(`branch.${b}.remote`)||"origin";let x=h||await k.get(`remote.${d}.pushurl`)||await k.get(`remote.${d}.url`);if(typeof x=="undefined")throw new Sr("remote OR url");let E=f||await k.get(`branch.${b}.merge`);if(typeof x=="undefined")throw new Sr("remoteRef");v===void 0&&(v=await k.get("http.corsProxy"));let A=await z.expand({fs:t,gitdir:c,ref:b}),y=g?"0000000000000000000000000000000000000000":await z.resolve({fs:t,gitdir:c,ref:A}),S=nl.getRemoteHelperFor({url:x}),_=await S.discover({http:r,onAuth:s,onAuthSuccess:a,onAuthFailure:o,corsProxy:v,service:"git-receive-pack",url:x,headers:w,protocolVersion:1}),C=_.auth,P;if(!E)P=A;else try{P=await z.expandAgainstMap({ref:E,map:_.refs})}catch(X){if(X instanceof Be)P=E.startsWith("refs/")?E:`refs/heads/${E}`;else throw X}let N=_.refs.get(P)||"0000000000000000000000000000000000000000";if(l&&!await l({remote:d,url:x,localRef:{ref:g?"(delete)":A,oid:y},remoteRef:{ref:P,oid:N}}))throw new Qo;let B=!_.capabilities.has("no-thin"),H=new Set;if(!g){let X=[..._.refs.values()],q=new Set;if(N!=="0000000000000000000000000000000000000000"){let De=await Cv({fs:t,cache:e,gitdir:c,oids:[y,N]});for(let ar of De)X.push(ar);B&&(q=await lv({fs:t,cache:e,gitdir:c,oids:De}))}if(!X.includes(y)){let De=await T6({fs:t,cache:e,gitdir:c,start:[y],finish:X});H=await lv({fs:t,cache:e,gitdir:c,oids:De})}if(B){try{let De=await z.resolve({fs:t,gitdir:c,ref:`refs/remotes/${d}/HEAD`,depth:2}),{oid:ar}=await z.resolveAgainstMap({ref:De.replace(`refs/remotes/${d}/`,""),fullref:De,map:_.refs}),Ft=[ar];for(let Ie of await lv({fs:t,cache:e,gitdir:c,oids:Ft}))q.add(Ie)}catch(De){}for(let De of q)H.delete(De)}if(y===N&&(m=!0),!m){if(A.startsWith("refs/tags")&&N!=="0000000000000000000000000000000000000000")throw new Ko("tag-exists");if(y!=="0000000000000000000000000000000000000000"&&N!=="0000000000000000000000000000000000000000"&&!await tA({fs:t,cache:e,gitdir:c,oid:y,ancestor:N,depth:-1}))throw new Ko("not-fast-forward")}}let ce=Tk([..._.capabilities],["report-status","side-band-64k",`agent=${Ud.agent}`]),Pe=await R6({capabilities:ce,triplets:[{oldoid:N,oid:y,fullRef:P}]}),ve=g?[]:await mA({fs:t,cache:e,gitdir:c,oids:[...H]}),ie=await S.connect({http:r,onProgress:n,corsProxy:v,service:"git-receive-pack",url:x,auth:C,headers:w,body:[...Pe,...ve]}),{packfile:xe,progress:we}=await Dd.demux(ie.body);if(i){let X=Pk(we);hu(X,async q=>{await i(q)})}let W=await P6(xe);if(ie.headers&&(W.headers=ie.headers),d&&W.ok&&W.refs[P].ok&&!A.startsWith("refs/tags")){let X=`refs/remotes/${d}/${P.replace("refs/heads","")}`;g?await z.deleteRef({fs:t,gitdir:c,ref:X}):await z.writeRef({fs:t,gitdir:c,ref:X,value:y})}if(W.ok&&Object.values(W.refs).every(X=>X.ok))return W;{let X=Object.entries(W.refs).filter(([q,De])=>!De.ok).map(([q,De])=>` + - ${q}: ${De.error}`).join("");throw new tu(X,W)}}async function wA({fs:t,http:e,onProgress:r,onMessage:n,onAuth:i,onAuthSuccess:s,onAuthFailure:a,onPrePush:o,dir:l,gitdir:c=D(l,".git"),ref:u,remoteRef:f,remote:d="origin",url:h,force:m=!1,delete:g=!1,corsProxy:v,headers:w={},cache:b={}}){try{T("fs",t),T("http",e),T("gitdir",c);let k=new Q(t),x=await J({fsp:k,dotgit:c});return await $6({fs:k,cache:b,http:e,onProgress:r,onMessage:n,onAuth:i,onAuthSuccess:s,onAuthFailure:a,onPrePush:o,gitdir:x,ref:u,remoteRef:f,remote:d,url:h,force:m,delete:g,corsProxy:v,headers:w})}catch(k){throw k.caller="git.push",k}}async function yA({fs:t,cache:e,gitdir:r,oid:n}){let{type:i,object:s}=await Xe({fs:t,cache:e,gitdir:r,oid:n});if(i==="tag")return n=Zr.from(s).parse().object,yA({fs:t,cache:e,gitdir:r,oid:n});if(i!=="blob")throw new fr(n,i,"blob");return{oid:n,blob:new Uint8Array(s)}}async function bA({fs:t,cache:e,gitdir:r,oid:n,filepath:i=void 0}){return i!==void 0&&(n=await fu({fs:t,cache:e,gitdir:r,oid:n,filepath:i})),await yA({fs:t,cache:e,gitdir:r,oid:n})}async function _A({fs:t,dir:e,gitdir:r=D(e,".git"),oid:n,filepath:i,cache:s={}}){try{T("fs",t),T("gitdir",r),T("oid",n);let a=new Q(t),o=await J({fsp:a,dotgit:r});return await bA({fs:a,cache:s,gitdir:o,oid:n,filepath:i})}catch(a){throw a.caller="git.readBlob",a}}async function Tv({fs:t,dir:e,gitdir:r=D(e,".git"),oid:n,cache:i={}}){try{T("fs",t),T("gitdir",r),T("oid",n);let s=new Q(t),a=await J({fsp:s,dotgit:r});return await tl({fs:s,cache:i,gitdir:a,oid:n})}catch(s){throw s.caller="git.readCommit",s}}async function I6({fs:t,cache:e,gitdir:r,ref:n="refs/notes/commits",oid:i}){let s=await z.resolve({gitdir:r,fs:t,ref:n}),{blob:a}=await bA({fs:t,cache:e,gitdir:r,oid:s,filepath:i});return a}async function xA({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n="refs/notes/commits",oid:i,cache:s={}}){try{T("fs",t),T("gitdir",r),T("ref",n),T("oid",i);let a=new Q(t),o=await J({fsp:a,dotgit:r});return await I6({fs:a,cache:s,gitdir:o,ref:n,oid:i})}catch(a){throw a.caller="git.readNote",a}}async function SA({fs:t,dir:e,gitdir:r=D(e,".git"),oid:n,format:i="parsed",filepath:s=void 0,encoding:a=void 0,cache:o={}}){try{T("fs",t),T("gitdir",r),T("oid",n);let l=new Q(t),c=await J({fsp:l,dotgit:r});s!==void 0&&(n=await fu({fs:l,cache:o,gitdir:c,oid:n,filepath:s}));let f=await Xe({fs:l,cache:o,gitdir:c,oid:n,format:i==="parsed"?"content":i});if(f.oid=n,i==="parsed")switch(f.format="parsed",f.type){case"commit":f.object=kr.from(f.object).parse();break;case"tree":f.object=Er.from(f.object).entries();break;case"blob":a?f.object=f.object.toString(a):(f.object=new Uint8Array(f.object),f.format="content");break;case"tag":f.object=Zr.from(f.object).parse();break;default:throw new fr(f.oid,f.type,"blob|commit|tag|tree")}else(f.format==="deflated"||f.format==="wrapped")&&(f.type=f.format);return f}catch(l){throw l.caller="git.readObject",l}}async function F6({fs:t,cache:e,gitdir:r,oid:n}){let{type:i,object:s}=await Xe({fs:t,cache:e,gitdir:r,oid:n,format:"content"});if(i!=="tag")throw new fr(n,i,"tag");let a=Zr.from(s);return{oid:n,tag:a.parse(),payload:a.payload()}}async function EA({fs:t,dir:e,gitdir:r=D(e,".git"),oid:n,cache:i={}}){try{T("fs",t),T("gitdir",r),T("oid",n);let s=new Q(t),a=await J({fsp:s,dotgit:r});return await F6({fs:s,cache:i,gitdir:a,oid:n})}catch(s){throw s.caller="git.readTag",s}}async function kA({fs:t,dir:e,gitdir:r=D(e,".git"),oid:n,filepath:i=void 0,cache:s={}}){try{T("fs",t),T("gitdir",r),T("oid",n);let a=new Q(t),o=await J({fsp:a,dotgit:r});return await al({fs:a,cache:s,gitdir:o,oid:n,filepath:i})}catch(a){throw a.caller="git.readTree",a}}async function AA({fs:t,dir:e,gitdir:r=D(e,".git"),filepath:n,cache:i={}}){try{T("fs",t),T("gitdir",r),T("filepath",n);let s=new Q(t),a=await J({fsp:s,dotgit:r});await ht.acquire({fs:s,gitdir:a,cache:i},async function(o){o.delete({filepath:n})})}catch(s){throw s.caller="git.remove",s}}async function O6({fs:t,cache:e,onSign:r,gitdir:n,ref:i="refs/notes/commits",oid:s,author:a,committer:o,signingKey:l}){let c;try{c=await z.resolve({gitdir:n,fs:t,ref:i})}catch(m){if(!(m instanceof Be))throw m}let f=(await al({fs:t,cache:e,gitdir:n,oid:c||"4b825dc642cb6eb9a060e54bf8d69288fbee4904"})).tree;f=f.filter(m=>m.path!==s);let d=await du({fs:t,gitdir:n,tree:f});return await Hd({fs:t,cache:e,onSign:r,gitdir:n,ref:i,tree:d,parent:c&&[c],message:`Note removed by 'isomorphic-git removeNote' +`,author:a,committer:o,signingKey:l})}async function CA({fs:t,onSign:e,dir:r,gitdir:n=D(r,".git"),ref:i="refs/notes/commits",oid:s,author:a,committer:o,signingKey:l,cache:c={}}){try{T("fs",t),T("gitdir",n),T("oid",s);let u=new Q(t),f=await J({fsp:u,dotgit:n}),d=await Ms({fs:u,gitdir:f,author:a});if(!d)throw new Kt("author");let h=await el({fs:u,gitdir:f,author:d,committer:o});if(!h)throw new Kt("committer");return await O6({fs:u,cache:c,onSign:e,gitdir:f,ref:i,oid:s,author:d,committer:h,signingKey:l})}catch(u){throw u.caller="git.removeNote",u}}async function M6({fs:t,gitdir:e,oldref:r,ref:n,checkout:i=!1}){if(!uu(n,!0))throw new Dn(n,zc.clean(n));if(!uu(r,!0))throw new Dn(r,zc.clean(r));let s=`refs/heads/${r}`,a=`refs/heads/${n}`;if(await z.exists({fs:t,gitdir:e,ref:a}))throw new Mn("branch",n,!1);let l=await z.resolve({fs:t,gitdir:e,ref:s,depth:1});await z.writeRef({fs:t,gitdir:e,ref:a,value:l}),await z.deleteRef({fs:t,gitdir:e,ref:s});let u=await Ls({fs:t,gitdir:e,fullname:!0})===s;(i||u)&&await z.writeSymbolicRef({fs:t,gitdir:e,ref:"HEAD",value:a})}async function TA({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n,oldref:i,checkout:s=!1}){try{T("fs",t),T("gitdir",r),T("ref",n),T("oldref",i);let a=new Q(t),o=await J({fsp:a,dotgit:r});return await M6({fs:a,gitdir:o,ref:n,oldref:i,checkout:s})}catch(a){throw a.caller="git.renameBranch",a}}async function PA({gitdir:t,type:e,object:r}){return zi($s.wrap({type:e,object:r}))}async function RA({fs:t,dir:e,gitdir:r=D(e,".git"),filepath:n,ref:i,cache:s={}}){try{T("fs",t),T("gitdir",r),T("filepath",n);let a=new Q(t),o=await J({fsp:a,dotgit:r}),l,c;try{l=await z.resolve({fs:a,gitdir:o,ref:i||"HEAD"})}catch(d){if(i)throw d}if(l)try{l=await fu({fs:a,cache:s,gitdir:o,oid:l,filepath:n})}catch(d){l=null}let u={ctime:new Date(0),mtime:new Date(0),dev:0,ino:0,mode:0,uid:0,gid:0,size:0},f=e&&await a.read(D(e,n));f&&(c=await PA({gitdir:o,type:"blob",object:f}),l===c&&(u=await a.lstat(D(e,n)))),await ht.acquire({fs:a,gitdir:o,cache:s},async function(d){d.delete({filepath:n}),l&&d.insert({filepath:n,stats:u,oid:l})})}catch(a){throw a.caller="git.reset",a}}async function $A({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n,depth:i}){try{T("fs",t),T("gitdir",r),T("ref",n);let s=new Q(t),a=await J({fsp:s,dotgit:r});return await z.resolve({fs:s,gitdir:a,ref:n,depth:i})}catch(s){throw s.caller="git.resolveRef",s}}async function IA({fs:t,dir:e,gitdir:r=D(e,".git"),path:n,value:i,append:s=!1}){try{T("fs",t),T("gitdir",r),T("path",n);let a=new Q(t),o=await J({fsp:a,dotgit:r}),l=await lt.get({fs:a,gitdir:o});s?await l.append(n,i):await l.set(n,i),await lt.save({fs:a,gitdir:o,config:l})}catch(a){throw a.caller="git.setConfig",a}}async function FA({fs:t,gitdir:e,commit:r}){let n=kr.from(r).toObject();return await Ar({fs:t,gitdir:e,type:"commit",object:n,format:"content"})}var Ld=class t{static get timezoneOffsetForRefLogEntry(){let e=new Date().getTimezoneOffset(),r=Math.abs(Math.floor(e/60)),n=Math.abs(e%60).toString().padStart(2,"0");return`${e>0?"-":"+"}${r.toString().padStart(2,"0")}${n}`}static createStashReflogEntry(e,r,n){let i=e.name.replace(/\s/g,""),s="0000000000000000000000000000000000000000",a=Math.floor(Date.now()/1e3),o=t.timezoneOffsetForRefLogEntry;return`${s} ${r} ${i} ${e.email} ${a} ${o} ${n} +`}static getStashReflogEntry(e,r=!1){return e.split(` +`).filter(s=>s).reverse().map((s,a)=>r?`stash@{${a}}: ${s.split(" ")[1]}`:s)}},D6={stage:Ca,workdir:sl},cv;async function il(t,e){return cv===void 0&&(cv=new Wc),cv.acquire(t,e)}async function L6(t,e,r,n,i=null){let s=D(r,n),a=await t.lstat(s);if(!a)throw new Be(s);if(a.isDirectory())throw new he(`${s}: file expected, but found directory`);let o=i?await lk({fs:t,gitdir:e,oid:i}):void 0,l=o?i:void 0;return o||await il({fs:t,gitdir:e,currentFilepath:s},async()=>{let c=a.isSymbolicLink()?await t.readlink(s).then(mk):await t.read(s);if(c===null)throw new Be(s);l=await Ar({fs:t,gitdir:e,type:"blob",object:c})}),l}async function N6({fs:t,dir:e,gitdir:r,entries:n}){async function i(s){if(s.type==="tree"){if(!s.oid){let a=await Promise.all(s.children.map(i));s.oid=await du({fs:t,gitdir:r,tree:a}),s.mode=16384}}else s.type==="blob"&&(s.oid=await L6(t,r,e,s.path,s.oid),s.mode=33188);return s.path=s.path.split("/").pop(),s}return Promise.all(n.map(i))}async function tk({fs:t,dir:e,gitdir:r,treePair:n}){let i=n[1]==="stage",s=n.map(h=>typeof h=="string"?D6[h]():h),a=[],u=await Fs({fs:t,cache:{},dir:e,gitdir:r,trees:s,map:async(h,[m,g])=>{if(!(h==="."||await Os.isIgnored({fs:t,dir:e,gitdir:r,filepath:h}))&&g)return(!m||await m.oid()!==await g.oid()&&await g.oid()!==void 0)&&a.push([m,g]),{mode:await g.mode(),path:h,oid:await g.oid(),type:await g.type()}},reduce:async(h,m)=>(m=m.filter(Boolean),h?(h.children=m,h):m.length>0?m:void 0),iterate:async(h,m)=>{let g=[];for(let v of m){let[w,b]=v;i?b&&(await t.exists(`${e}/${b.toString()}`)?g.push(v):a.push([null,b])):w&&(b?g.push(v):a.push([w,null]))}return g.length?Promise.all(g.map(h)):[]}});if(a.length===0||u.length===0)return null;let d=(await N6({fs:t,dir:e,gitdir:r,entries:u})).filter(Boolean).map(h=>({mode:h.mode,path:h.path,oid:h.oid,type:h.type}));return du({fs:t,gitdir:r,tree:d})}async function B6({fs:t,dir:e,gitdir:r,stashCommit:n,parentCommit:i,wasStaged:s}){let a=[],o=[],l=await Fs({fs:t,cache:{},dir:e,gitdir:r,trees:[Xr({ref:i}),Xr({ref:n})],map:async(c,[u,f])=>{if(c==="."||await Os.isIgnored({fs:t,dir:e,gitdir:r,filepath:c}))return;let d=f?await f.type():await u.type();if(d!=="tree"&&d!=="blob")return;if(!f&&u){let m=d==="tree"?"rmdir":"rm";return d==="tree"&&a.push(c),d==="blob"&&s&&o.push({filepath:c,oid:await u.oid()}),{method:m,filepath:c}}let h=await f.oid();if(!u||await u.oid()!==h)return d==="tree"?{method:"mkdir",filepath:c}:(s&&o.push({filepath:c,oid:h,stats:await t.lstat(D(e,c))}),{method:"write",filepath:c,oid:h})}});await il({fs:t,gitdir:r,dirRemoved:a,ops:l},async()=>{for(let c of l){let u=D(e,c.filepath);switch(c.method){case"rmdir":await t.rmdir(u);break;case"mkdir":await t.mkdir(u);break;case"rm":await t.rm(u);break;case"write":if(!a.some(f=>u.startsWith(f))){let{object:f}=await Xe({fs:t,cache:{},gitdir:r,oid:c.oid});await t.exists(u)&&await t.rm(u),await t.write(u,f)}break}}}),await ht.acquire({fs:t,gitdir:r,cache:{}},async c=>{o.forEach(({filepath:u,stats:f,oid:d})=>{c.insert({filepath:u,stats:f,oid:d})})})}var Aa=class t{constructor({fs:e,dir:r,gitdir:n=D(r,".git")}){Object.assign(this,{fs:e,dir:r,gitdir:n,_author:null})}static get refStash(){return"refs/stash"}static get refLogsStash(){return"logs/refs/stash"}get refStashPath(){return D(this.gitdir,t.refStash)}get refLogsStashPath(){return D(this.gitdir,t.refLogsStash)}async getAuthor(){if(!this._author&&(this._author=await Ms({fs:this.fs,gitdir:this.gitdir,author:{}}),!this._author))throw new Kt("author");return this._author}async getStashSHA(e,r){return await this.fs.exists(this.refStashPath)?(r||await this.readStashReflogs({parsed:!1}))[e].split(" ")[1]:null}async writeStashCommit({message:e,tree:r,parent:n}){return FA({fs:this.fs,gitdir:this.gitdir,commit:{message:e,tree:r,parent:n,author:await this.getAuthor(),committer:await this.getAuthor()}})}async readStashCommit(e){let r=await this.readStashReflogs({parsed:!1});if(e!==0&&(e<0||e>r.length-1))throw new Dn(`stash@${e}`,"number that is in range of [0, num of stash pushed]");let n=await this.getStashSHA(e,r);return n?tl({fs:this.fs,cache:{},gitdir:this.gitdir,oid:n}):{}}async writeStashRef(e){return z.writeRef({fs:this.fs,gitdir:this.gitdir,ref:t.refStash,value:e})}async writeStashReflogEntry({stashCommit:e,message:r}){let n=await this.getAuthor(),i=Ld.createStashReflogEntry(n,e,r),s=this.refLogsStashPath;await il({filepath:s,entry:i},async()=>{let a=await this.fs.exists(s)?await this.fs.read(s,"utf8"):"";await this.fs.write(s,a+i,"utf8")})}async readStashReflogs({parsed:e=!1}){if(!await this.fs.exists(this.refLogsStashPath))return[];let r=await this.fs.read(this.refLogsStashPath,"utf8");return Ld.getStashReflogEntry(r,e)}};async function OA({fs:t,dir:e,gitdir:r,message:n=""}){let i=new Aa({fs:t,dir:e,gitdir:r});await i.getAuthor();let s=await Ls({fs:t,gitdir:r,fullname:!1}),a=await z.resolve({fs:t,gitdir:r,ref:"HEAD"}),l=(await Tv({fs:t,dir:e,gitdir:r,oid:a})).commit.message,c=[a],u=null,f=Xr({ref:"HEAD"}),d=await tk({fs:t,dir:e,gitdir:r,treePair:[Xr({ref:"HEAD"}),"stage"]});if(d){let v=await i.writeStashCommit({message:`stash-Index: WIP on ${s} - ${new Date().toISOString()}`,tree:d,parent:c});c.push(v),u=d,f=Ca()}let h=await tk({fs:t,dir:e,gitdir:r,treePair:[f,"workdir"]});if(h){let v=await i.writeStashCommit({message:`stash-WorkDir: WIP on ${s} - ${new Date().toISOString()}`,tree:h,parent:[c[c.length-1]]});c.push(v),u=h}if(!u||!d&&!h)throw new Be("changes, nothing to stash");let m=(n.trim()||`WIP on ${s}`)+`: ${a.substring(0,7)} ${l}`;return{stashCommit:await i.writeStashCommit({message:m,tree:u,parent:c}),stashMsg:m,branch:s,stashMgr:i}}async function H6({fs:t,dir:e,gitdir:r,message:n=""}){let{stashCommit:i,stashMsg:s,branch:a,stashMgr:o}=await OA({fs:t,dir:e,gitdir:r,message:n});return await o.writeStashRef(i),await o.writeStashReflogEntry({stashCommit:i,message:s}),await kv({fs:t,dir:e,gitdir:r,ref:a,track:!1,force:!0}),i}async function U6({fs:t,dir:e,gitdir:r,message:n=""}){let{stashCommit:i}=await OA({fs:t,dir:e,gitdir:r,message:n});return i}async function MA({fs:t,dir:e,gitdir:r,refIdx:n=0}){let s=await new Aa({fs:t,dir:e,gitdir:r}).readStashCommit(n),{parent:a=null}=s.commit?s.commit:{};if(!(!a||!Array.isArray(a)))for(let o=0;o{await t.exists(a)&&await t.rm(a)});let o=await i.readStashReflogs({parsed:!1});if(!o.length)return;o.splice(n,1);let l=i.refLogsStashPath;await il({reflogEntries:o,stashReflogPath:l,stashMgr:i},async()=>{if(o.length){await t.write(l,o.reverse().join(` +`)+` +`,"utf8");let c=o[o.length-1].split(" ")[1];await i.writeStashRef(c)}else await t.rm(l)})}async function G6({fs:t,dir:e,gitdir:r}){return new Aa({fs:t,dir:e,gitdir:r}).readStashReflogs({parsed:!0})}async function j6({fs:t,dir:e,gitdir:r}){let n=new Aa({fs:t,dir:e,gitdir:r}),i=[n.refStashPath,n.refLogsStashPath];await il(i,async()=>{await Promise.all(i.map(async s=>{if(await t.exists(s))return t.rm(s)}))})}async function q6({fs:t,dir:e,gitdir:r,refIdx:n=0}){await MA({fs:t,dir:e,gitdir:r,refIdx:n}),await DA({fs:t,dir:e,gitdir:r,refIdx:n})}async function LA({fs:t,dir:e,gitdir:r=D(e,".git"),op:n="push",message:i="",refIdx:s=0}){T("fs",t),T("dir",e),T("gitdir",r),T("op",n);let a={push:H6,apply:MA,drop:DA,list:G6,clear:j6,pop:q6,create:U6},o=["apply","drop","pop"];try{let l=new Q(t),c=await J({fsp:l,dotgit:r});["refs","logs","logs/refs"].map(d=>D(c,d)).forEach(async d=>{await l.exists(d)||await l.mkdir(d)});let f=a[n];if(f){if(o.includes(n)&&s<0)throw new Dn(`stash@${s}`,"number that is in range of [0, num of stash pushed]");return await f({fs:l,dir:e,gitdir:c,message:i,refIdx:s})}throw new Error(`To be implemented: ${n}`)}catch(l){throw l.caller="git.stash",l}}async function NA({fs:t,dir:e,gitdir:r=D(e,".git"),filepath:n,cache:i={}}){try{T("fs",t),T("gitdir",r),T("filepath",n);let s=new Q(t),a=await J({fsp:s,dotgit:r});if(await Os.isIgnored({fs:s,gitdir:a,dir:e,filepath:n}))return"ignored";let l=await W6({fs:s,cache:i,gitdir:a}),c=await BA({fs:s,cache:i,gitdir:a,tree:l,path:n}),u=await ht.acquire({fs:s,gitdir:a,cache:i},async function(v){for(let w of v)if(w.path===n)return w;return null}),f=await s.lstat(D(e,n)),d=c!==null,h=u!==null,m=f!==null,g=async()=>{if(h&&!Td(u,f))return u.oid;{let v=await s.read(D(e,n)),w=await PA({gitdir:a,type:"blob",object:v});return h&&u.oid===w&&f.size!==-1&&ht.acquire({fs:s,gitdir:a,cache:i},async function(b){b.insert({filepath:n,stats:f,oid:w})}),w}};if(!d&&!m&&!h)return"absent";if(!d&&!m&&h)return"*absent";if(!d&&m&&!h)return"*added";if(!d&&m&&h)return await g()===u.oid?"added":"*added";if(d&&!m&&!h)return"deleted";if(d&&!m&&h)return c===u.oid,"*deleted";if(d&&m&&!h)return await g()===c?"*undeleted":"*undeletemodified";if(d&&m&&h){let v=await g();return v===c?v===u.oid?"unmodified":"*unmodified":v===u.oid?"modified":"*modified"}}catch(s){throw s.caller="git.status",s}}async function BA({fs:t,cache:e,gitdir:r,tree:n,path:i}){typeof i=="string"&&(i=i.split("/"));let s=i.shift();for(let a of n)if(a.path===s){if(i.length===0)return a.oid;let{type:o,object:l}=await Xe({fs:t,cache:e,gitdir:r,oid:a.oid});if(o==="tree"){let c=Er.from(l);return BA({fs:t,cache:e,gitdir:r,tree:c,path:i})}if(o==="blob")throw new fr(a.oid,o,"blob",i.join("/"))}return null}async function W6({fs:t,cache:e,gitdir:r}){let n;try{n=await z.resolve({fs:t,gitdir:r,ref:"HEAD"})}catch(s){if(s instanceof Be)return[]}let{tree:i}=await al({fs:t,cache:e,gitdir:r,oid:n});return i}async function HA({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n="HEAD",filepaths:i=["."],filter:s,cache:a={},ignored:o=!1}){try{T("fs",t),T("gitdir",r),T("ref",n);let l=new Q(t),c=await J({fsp:l,dotgit:r});return await Fs({fs:l,cache:a,dir:e,gitdir:c,trees:[Xr({ref:n}),sl(),Ca()],map:async function(u,[f,d,h]){if(!f&&!h&&d&&!o&&await Os.isIgnored({fs:l,dir:e,filepath:u})||!i.some(y=>Ak(u,y)))return null;if(s&&!s(u))return;let[m,g,v]=await Promise.all([f&&f.type(),d&&d.type(),h&&h.type()]),w=[m,g,v].includes("blob");if((m==="tree"||m==="special")&&!w)return;if(m==="commit")return null;if((g==="tree"||g==="special")&&!w)return;if(v==="commit")return null;if((v==="tree"||v==="special")&&!w)return;let b=m==="blob"?await f.oid():void 0,k=v==="blob"?await h.oid():void 0,x;m!=="blob"&&g==="blob"&&v!=="blob"?x="42":g==="blob"&&(x=await d.oid());let E=[void 0,b,x,k],A=E.map(y=>E.indexOf(y));return A.shift(),[u,...A]}})}catch(l){throw l.caller="git.statusMatrix",l}}async function UA({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n,object:i,force:s=!1}){try{T("fs",t),T("gitdir",r),T("ref",n);let a=new Q(t);if(n===void 0)throw new Sr("ref");n=n.startsWith("refs/tags/")?n:`refs/tags/${n}`;let o=await J({fsp:a,dotgit:r}),l=await z.resolve({fs:a,gitdir:o,ref:i||"HEAD"});if(!s&&await z.exists({fs:a,gitdir:o,ref:n}))throw new Mn("tag",n);await z.writeRef({fs:a,gitdir:o,ref:n,value:l})}catch(a){throw a.caller="git.tag",a}}async function GA({fs:t,dir:e,gitdir:r=D(e,".git"),cache:n={},filepath:i,oid:s,mode:a,add:o,remove:l,force:c}){try{T("fs",t),T("gitdir",r),T("filepath",i);let u=new Q(t),f=await J({fsp:u,dotgit:r});if(l)return await ht.acquire({fs:u,gitdir:f,cache:n},async function(h){if(!c){let m=await u.lstat(D(e,i));if(m){if(m.isDirectory())throw new Is("directory");return}}h.has({filepath:i})&&h.delete({filepath:i})});let d;if(!s){if(d=await u.lstat(D(e,i)),!d)throw new Be(`file at "${i}" on disk and "remove" not set`);if(d.isDirectory())throw new Is("directory")}return await ht.acquire({fs:u,gitdir:f,cache:n},async function(h){if(!o&&!h.has({filepath:i}))throw new Be(`file at "${i}" in index and "add" not set`);let m;if(s)m={ctime:new Date(0),mtime:new Date(0),dev:0,ino:0,mode:a,uid:0,gid:0,size:0};else{m=d;let g=m.isSymbolicLink()?await u.readlink(D(e,i)):await u.read(D(e,i));s=await Ar({fs:u,gitdir:f,type:"blob",format:"content",object:g})}return h.insert({filepath:i,oid:s,stats:m}),s})}catch(u){throw u.caller="git.updateIndex",u}}function jA(){try{return Ud.version}catch(t){throw t.caller="git.version",t}}async function qA({fs:t,dir:e,gitdir:r=D(e,".git"),trees:n,map:i,reduce:s,iterate:a,cache:o={}}){try{T("fs",t),T("gitdir",r),T("trees",n);let l=new Q(t),c=await J({fsp:l,dotgit:r});return await Fs({fs:l,cache:o,dir:e,gitdir:c,trees:n,map:i,reduce:s,iterate:a})}catch(l){throw l.caller="git.walk",l}}async function WA({fs:t,dir:e,gitdir:r=D(e,".git"),blob:n}){try{T("fs",t),T("gitdir",r),T("blob",n);let i=new Q(t),s=await J({fsp:i,dotgit:r});return await Ar({fs:i,gitdir:s,type:"blob",object:n,format:"content"})}catch(i){throw i.caller="git.writeBlob",i}}async function zA({fs:t,dir:e,gitdir:r=D(e,".git"),commit:n}){try{T("fs",t),T("gitdir",r),T("commit",n);let i=new Q(t),s=await J({fsp:i,dotgit:r});return await FA({fs:i,gitdir:s,commit:n})}catch(i){throw i.caller="git.writeCommit",i}}async function VA({fs:t,dir:e,gitdir:r=D(e,".git"),type:n,object:i,format:s="parsed",oid:a,encoding:o=void 0}){try{let l=new Q(t),c=await J({fsp:l,dotgit:r});if(s==="parsed"){switch(n){case"commit":i=kr.from(i).toObject();break;case"tree":i=Er.from(i).toObject();break;case"blob":i=Buffer.from(i,o);break;case"tag":i=Zr.from(i).toObject();break;default:throw new fr(a||"",n,"blob|commit|tag|tree")}s="content"}return a=await Ar({fs:l,gitdir:c,type:n,object:i,oid:a,format:s}),a}catch(l){throw l.caller="git.writeObject",l}}async function YA({fs:t,dir:e,gitdir:r=D(e,".git"),ref:n,value:i,force:s=!1,symbolic:a=!1}){try{T("fs",t),T("gitdir",r),T("ref",n),T("value",i);let o=new Q(t);if(!uu(n,!0))throw new Dn(n,zc.clean(n));let l=await J({fsp:o,dotgit:r});if(!s&&await z.exists({fs:o,gitdir:l,ref:n}))throw new Mn("ref",n);a?await z.writeSymbolicRef({fs:o,gitdir:l,ref:n,value:i}):(i=await z.resolve({fs:o,gitdir:l,ref:i}),await z.writeRef({fs:o,gitdir:l,ref:n,value:i}))}catch(o){throw o.caller="git.writeRef",o}}async function z6({fs:t,gitdir:e,tag:r}){let n=Zr.from(r).toObject();return await Ar({fs:t,gitdir:e,type:"tag",object:n,format:"content"})}async function XA({fs:t,dir:e,gitdir:r=D(e,".git"),tag:n}){try{T("fs",t),T("gitdir",r),T("tag",n);let i=new Q(t),s=await J({fsp:i,dotgit:r});return await z6({fs:i,gitdir:s,tag:n})}catch(i){throw i.caller="git.writeTag",i}}async function ZA({fs:t,dir:e,gitdir:r=D(e,".git"),tree:n}){try{T("fs",t),T("gitdir",r),T("tree",n);let i=new Q(t),s=await J({fsp:i,dotgit:r});return await du({fs:i,gitdir:s,tree:n})}catch(i){throw i.caller="git.writeTree",i}}var V6={Errors:fk,STAGE:Ca,TREE:Xr,WORKDIR:sl,add:gk,abortMerge:hk,addNote:_k,addRemote:Sk,annotatedTag:Ek,branch:kk,checkout:kv,clone:$k,commit:Ik,getConfig:Vk,getConfigAll:Yk,setConfig:IA,currentBranch:Fk,deleteBranch:Ok,deleteRef:Mk,deleteRemote:Dk,deleteTag:Lk,expandOid:Nk,expandRef:Bk,fastForward:Gk,fetch:jk,findMergeBase:qk,findRoot:zk,getRemoteInfo:Xk,getRemoteInfo2:Kk,hashBlob:Qk,indexPack:Jk,init:eA,isDescendent:rA,isIgnored:nA,listBranches:iA,listFiles:aA,listNotes:oA,listRefs:lA,listRemotes:cA,listServerRefs:uA,listTags:fA,log:hA,merge:pA,packObjects:gA,pull:vA,push:wA,readBlob:_A,readCommit:Tv,readNote:xA,readObject:SA,readTag:EA,readTree:kA,remove:AA,removeNote:CA,renameBranch:TA,resetIndex:RA,updateIndex:GA,resolveRef:$A,status:NA,statusMatrix:HA,tag:UA,version:jA,walk:qA,writeBlob:WA,writeCommit:zA,writeObject:VA,writeRef:YA,writeTag:XA,writeTree:ZA,stash:LA};Y.Errors=fk;Y.STAGE=Ca;Y.TREE=Xr;Y.WORKDIR=sl;Y.abortMerge=hk;Y.add=gk;Y.addNote=_k;Y.addRemote=Sk;Y.annotatedTag=Ek;Y.branch=kk;Y.checkout=kv;Y.clone=$k;Y.commit=Ik;Y.currentBranch=Fk;Y.default=V6;Y.deleteBranch=Ok;Y.deleteRef=Mk;Y.deleteRemote=Dk;Y.deleteTag=Lk;Y.expandOid=Nk;Y.expandRef=Bk;Y.fastForward=Gk;Y.fetch=jk;Y.findMergeBase=qk;Y.findRoot=zk;Y.getConfig=Vk;Y.getConfigAll=Yk;Y.getRemoteInfo=Xk;Y.getRemoteInfo2=Kk;Y.hashBlob=Qk;Y.indexPack=Jk;Y.init=eA;Y.isDescendent=rA;Y.isIgnored=nA;Y.listBranches=iA;Y.listFiles=aA;Y.listNotes=oA;Y.listRefs=lA;Y.listRemotes=cA;Y.listServerRefs=uA;Y.listTags=fA;Y.log=hA;Y.merge=pA;Y.packObjects=gA;Y.pull=vA;Y.push=wA;Y.readBlob=_A;Y.readCommit=Tv;Y.readNote=xA;Y.readObject=SA;Y.readTag=EA;Y.readTree=kA;Y.remove=AA;Y.removeNote=CA;Y.renameBranch=TA;Y.resetIndex=RA;Y.resolveRef=$A;Y.setConfig=IA;Y.stash=LA;Y.status=NA;Y.statusMatrix=HA;Y.tag=UA;Y.updateIndex=GA;Y.version=jA;Y.walk=qA;Y.writeBlob=WA;Y.writeCommit=zA;Y.writeObject=VA;Y.writeRef=YA;Y.writeTag=XA;Y.writeTree=ZA});var lC=I((TK,oC)=>{"use strict";p();oC.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var uC=I((RK,cC)=>{p();var jv={px:{px:1,cm:37.79527559055118,mm:3.7795275590551185,in:96,pt:1.3333333333333333,pc:16},cm:{px:.026458333333333334,cm:1,mm:.1,in:2.54,pt:.035277777777777776,pc:.42333333333333334},mm:{px:.26458333333333334,cm:10,mm:1,in:25.4,pt:.35277777777777775,pc:4.233333333333333},in:{px:.010416666666666666,cm:.39370078740157477,mm:.03937007874015748,in:1,pt:.013888888888888888,pc:.16666666666666666},pt:{px:.75,cm:28.346456692913385,mm:2.834645669291339,in:72,pt:1,pc:12},pc:{px:.0625,cm:2.3622047244094486,mm:.2362204724409449,in:6,pt:.08333333333333333,pc:1},deg:{deg:1,grad:.9,rad:180/Math.PI,turn:360},grad:{deg:1.1111111111111112,grad:1,rad:200/Math.PI,turn:400},rad:{deg:Math.PI/180,grad:Math.PI/200,rad:1,turn:Math.PI*2},turn:{deg:.002777777777777778,grad:.0025,rad:.5/Math.PI,turn:1},s:{s:1,ms:.001},ms:{s:1e3,ms:1},Hz:{Hz:1,kHz:1e3},kHz:{Hz:.001,kHz:1},dpi:{dpi:1,dpcm:.39370078740157477,dppx:.010416666666666666},dpcm:{dpi:2.54,dpcm:1,dppx:.026458333333333334},dppx:{dpi:96,dpcm:37.79527559055118,dppx:1}};cC.exports=function(t,e,r,n){if(!jv.hasOwnProperty(r))throw new Error("Cannot convert to "+r);if(!jv[r].hasOwnProperty(e))throw new Error("Cannot convert from "+e+" to "+r);var i=jv[r][e]*t;return n!==!1?(n=Math.pow(10,parseInt(n)||5),Math.round(i*n)/n):i}});var EC=I(Yi=>{"use strict";p();Object.defineProperty(Yi,"__esModule",{value:!0});Yi.fromRgba=fl;Yi.fromRgb=qv;Yi.fromHsla=Kd;Yi.fromHsl=xC;Yi.fromString=SC;Yi.default=void 0;var fC=pC(lC()),r5=pC(uC());function pC(t){return t&&t.__esModule?t:{default:t}}function n5(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function dC(t,e){for(var r=0;rt.length)&&(e=t.length);for(var r=0,n=new Array(e);r-1}function c5(t,e,r){var n=t/255,i=e/255,s=r/255,a=Math.max(n,i,s),o=Math.min(n,i,s),l=a-o,c=(a+o)/2;if(l===0)return[0,0,c*100];var u=l/(1-Math.abs(2*c-1)),f=function(){switch(a){case n:return(i-s)/l%6;case i:return(s-n)/l+2;default:return(n-i)/l+4}}();return[f*60,u*100,c*100]}function u5(t,e,r){var n=t/60,i=e/100,s=r/100,a=(1-Math.abs(2*s-1))*i,o=a*(1-Math.abs(n%2-1)),l=s-a/2,c=function(){return n<1?[a,o,0]:n<2?[o,a,0]:n<3?[0,a,o]:n<4?[0,o,a]:n<5?[o,0,a]:[a,0,o]}(),u=dr(c,3),f=u[0],d=u[1],h=u[2];return[(f+l)*255,(d+l)*255,(h+l)*255]}var f5=function(){function t(e){var r=dr(e,4),n=r[0],i=r[1],s=r[2],a=r[3];n5(this,t),this.values=[Math.max(Math.min(parseInt(n,10),255),0),Math.max(Math.min(parseInt(i,10),255),0),Math.max(Math.min(parseInt(s,10),255),0),a==null?1:Math.max(Math.min(parseFloat(a),255),0)]}return i5(t,[{key:"toRgbString",value:function(){var r=dr(this.values,4),n=r[0],i=r[1],s=r[2],a=r[3];return a===1?"rgb(".concat(n,", ").concat(i,", ").concat(s,")"):"rgba(".concat(n,", ").concat(i,", ").concat(s,", ").concat(a,")")}},{key:"toHslString",value:function(){var r=this.toHslaArray(),n=dr(r,4),i=n[0],s=n[1],a=n[2],o=n[3];return o===1?"hsl(".concat(i,", ").concat(s,"%, ").concat(a,"%)"):"hsla(".concat(i,", ").concat(s,"%, ").concat(a,"%, ").concat(o,")")}},{key:"toHexString",value:function(){var r=dr(this.values,4),n=r[0],i=r[1],s=r[2],a=r[3];return n=Number(n).toString(16).padStart(2,"0"),i=Number(i).toString(16).padStart(2,"0"),s=Number(s).toString(16).padStart(2,"0"),a=a<1?parseInt(a*255,10).toString(16).padStart(2,"0"):"","#".concat(n).concat(i).concat(s).concat(a)}},{key:"toRgbaArray",value:function(){return this.values}},{key:"toHslaArray",value:function(){var r=dr(this.values,4),n=r[0],i=r[1],s=r[2],a=r[3],o=c5(n,i,s),l=dr(o,3),c=l[0],u=l[1],f=l[2];return[c,u,f,a]}}]),t}();function fl(t){var e=dr(t,4),r=e[0],n=e[1],i=e[2],s=e[3];return new f5([r,n,i,s])}function qv(t){var e=dr(t,3),r=e[0],n=e[1],i=e[2];return fl([r,n,i,1])}function Kd(t){var e=dr(t,4),r=e[0],n=e[1],i=e[2],s=e[3],a=u5(r,n,i),o=dr(a,3),l=o[0],c=o[1],u=o[2];return fl([l,c,u,s])}function xC(t){var e=dr(t,3),r=e[0],n=e[1],i=e[2];return Kd([r,n,i,1])}function d5(t){var e=mC.exec(t)||gC.exec(t),r=dr(e,5),n=r[1],i=r[2],s=r[3],a=r[4];return n=parseInt(n.length<2?n.repeat(2):n,16),i=parseInt(i.length<2?i.repeat(2):i,16),s=parseInt(s.length<2?s.repeat(2):s,16),a=a&&(parseInt(a.length<2?a.repeat(2):a,16)/255).toPrecision(1)||1,fl([n,i,s,a])}function h5(t){var e=vC.exec(t)||yC.exec(t)||wC.exec(t)||bC.exec(t),r=dr(e,5),n=r[1],i=r[2],s=r[3],a=r[4];return n=gu(n,"%")?parseInt(n,10)*255/100:parseInt(n,10),i=gu(i,"%")?parseInt(i,10)*255/100:parseInt(i,10),s=gu(s,"%")>0?parseInt(s,10)*255/100:parseInt(s,10),a=a===void 0?1:parseFloat(a)/(gu(a,"%")?100:1),fl([n,i,s,a])}function p5(t){var e=_C.exec(t),r=dr(e,6),n=r[1],i=r[2],s=r[3],a=r[4],o=r[5];return i=i||"deg",n=(0,r5.default)(parseFloat(n),i,"deg"),s=parseFloat(s),a=parseFloat(a),o=o===void 0?1:parseFloat(o)/(gu(o,"%")?100:1),Kd([n,s,a,o])}function SC(t){return fC.default[t]?qv(fC.default[t]):mC.test(t)||gC.test(t)?d5(t):vC.test(t)||yC.test(t)||wC.test(t)||bC.test(t)?h5(t):_C.test(t)?p5(t):null}var m5={fromString:SC,fromRgb:qv,fromRgba:fl,fromHsl:xC,fromHsla:Kd};Yi.default=m5});var Wv=I((OK,AC)=>{"use strict";p();var kC=Object.prototype.toString;AC.exports=function(e){var r=kC.call(e),n=r==="[object Arguments]";return n||(n=r!=="[object Array]"&&e!==null&&typeof e=="object"&&typeof e.length=="number"&&e.length>=0&&kC.call(e.callee)==="[object Function]"),n}});var MC=I((DK,OC)=>{"use strict";p();var FC;Object.keys||(vu=Object.prototype.hasOwnProperty,zv=Object.prototype.toString,CC=Wv(),Vv=Object.prototype.propertyIsEnumerable,TC=!Vv.call({toString:null},"toString"),PC=Vv.call(function(){},"prototype"),wu=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],Qd=function(t){var e=t.constructor;return e&&e.prototype===t},RC={$applicationCache:!0,$console:!0,$external:!0,$frame:!0,$frameElement:!0,$frames:!0,$innerHeight:!0,$innerWidth:!0,$onmozfullscreenchange:!0,$onmozfullscreenerror:!0,$outerHeight:!0,$outerWidth:!0,$pageXOffset:!0,$pageYOffset:!0,$parent:!0,$scrollLeft:!0,$scrollTop:!0,$scrollX:!0,$scrollY:!0,$self:!0,$webkitIndexedDB:!0,$webkitStorageInfo:!0,$window:!0},$C=function(){if(typeof window=="undefined")return!1;for(var t in window)try{if(!RC["$"+t]&&vu.call(window,t)&&window[t]!==null&&typeof window[t]=="object")try{Qd(window[t])}catch(e){return!0}}catch(e){return!0}return!1}(),IC=function(t){if(typeof window=="undefined"||!$C)return Qd(t);try{return Qd(t)}catch(e){return!1}},FC=function(e){var r=e!==null&&typeof e=="object",n=zv.call(e)==="[object Function]",i=CC(e),s=r&&zv.call(e)==="[object String]",a=[];if(!r&&!n&&!i)throw new TypeError("Object.keys called on a non-object");var o=PC&&n;if(s&&e.length>0&&!vu.call(e,0))for(var l=0;l0)for(var c=0;c{"use strict";p();var g5=Array.prototype.slice,v5=Wv(),DC=Object.keys,Jd=DC?function(e){return DC(e)}:MC(),LC=Object.keys;Jd.shim=function(){if(Object.keys){var e=function(){var r=Object.keys(arguments);return r&&r.length===arguments.length}(1,2);e||(Object.keys=function(n){return v5(n)?LC(g5.call(n)):LC(n)})}else Object.keys=Jd;return Object.keys||Jd};NC.exports=Jd});var Hs=I((HK,GC)=>{"use strict";p();var w5=eh(),y5=typeof Symbol=="function"&&typeof Symbol("foo")=="symbol",b5=Object.prototype.toString,_5=Array.prototype.concat,BC=Jf(),x5=function(t){return typeof t=="function"&&b5.call(t)==="[object Function]"},HC=td()(),S5=function(t,e,r,n){if(e in t){if(n===!0){if(t[e]===r)return}else if(!x5(n)||!n())return}HC?BC(t,e,r,!0):BC(t,e,r)},UC=function(t,e){var r=arguments.length>2?arguments[2]:{},n=w5(e);y5&&(n=_5.call(n,Object.getOwnPropertySymbols(e)));for(var i=0;i{"use strict";p();var E5=eh(),qC=Sc()(),WC=Lt(),th=Bf(),k5=WC("Array.prototype.push"),jC=WC("Object.prototype.propertyIsEnumerable"),A5=qC?th.getOwnPropertySymbols:null;zC.exports=function(e,r){if(e==null)throw new TypeError("target must be an object");var n=th(e);if(arguments.length===1)return n;for(var i=1;i{"use strict";p();var Xv=Yv(),C5=function(){if(!Object.assign)return!1;for(var t="abcdefghijklmnopqrst",e=t.split(""),r={},n=0;n{"use strict";p();var P5=Hs(),R5=Zv();YC.exports=function(){var e=R5();return P5(Object,{assign:e},{assign:function(){return Object.assign!==e}}),e}});var JC=I((YK,QC)=>{"use strict";p();var $5=Hs(),I5=da(),F5=Yv(),ZC=Zv(),O5=XC(),M5=I5.apply(ZC()),KC=function(e,r){return M5(Object,arguments)};$5(KC,{getPolyfill:ZC,implementation:F5,shim:O5});QC.exports=KC});var Kv=I((ZK,rT)=>{"use strict";p();var eT=si(),tT=da(),D5=tT(eT("String.prototype.indexOf"));rT.exports=function(e,r){var n=eT(e,!!r);return typeof n=="function"&&D5(e,".prototype.")>-1?tT(n):n}});var iT=I((QK,nT)=>{"use strict";p();var bu=function(){return typeof function(){}.name=="string"},yu=Object.getOwnPropertyDescriptor;if(yu)try{yu([],"length")}catch(t){yu=null}bu.functionsHaveConfigurableNames=function(){if(!bu()||!yu)return!1;var e=yu(function(){},"name");return!!e&&!!e.configurable};var L5=Function.prototype.bind;bu.boundFunctionsHaveNames=function(){return bu()&&typeof L5=="function"&&function(){}.bind().name!==""};nT.exports=bu});var oT=I((eQ,aT)=>{"use strict";p();var sT=Jf(),N5=td()(),B5=iT().functionsHaveConfigurableNames(),H5=_r();aT.exports=function(e,r){if(typeof e!="function")throw new H5("`fn` is not a function");var n=arguments.length>2&&!!arguments[2];return(!n||B5)&&(N5?sT(e,"name",r,!0,!0):sT(e,"name",r)),e}});var Qv=I((rQ,lT)=>{"use strict";p();var U5=oT(),G5=_r(),j5=Object;lT.exports=U5(function(){if(this==null||this!==j5(this))throw new G5("RegExp.prototype.flags getter called on non-object");var e="";return this.hasIndices&&(e+="d"),this.global&&(e+="g"),this.ignoreCase&&(e+="i"),this.multiline&&(e+="m"),this.dotAll&&(e+="s"),this.unicode&&(e+="u"),this.unicodeSets&&(e+="v"),this.sticky&&(e+="y"),e},"get flags",!0)});var Jv=I((iQ,cT)=>{"use strict";p();var q5=Qv(),W5=Hs().supportsDescriptors,z5=Object.getOwnPropertyDescriptor;cT.exports=function(){if(W5&&/a/mig.flags==="gim"){var e=z5(RegExp.prototype,"flags");if(e&&typeof e.get=="function"&&"dotAll"in RegExp.prototype&&"hasIndices"in RegExp.prototype){var r="",n={};if(Object.defineProperty(n,"hasIndices",{get:function(){r+="d"}}),Object.defineProperty(n,"sticky",{get:function(){r+="y"}}),e.get.call(n),r==="dy")return e.get}}return q5}});var dT=I((aQ,fT)=>{"use strict";p();var V5=Hs().supportsDescriptors,Y5=Jv(),X5=bs(),Z5=Object.defineProperty,K5=Ym(),uT=Vf(),Q5=/a/;fT.exports=function(){if(!V5||!uT)throw new K5("RegExp.prototype.flags requires a true ES5 environment that supports property descriptors");var e=Y5(),r=uT(Q5),n=X5(r,"flags");return(!n||n.get!==e)&&Z5(r,"flags",{configurable:!0,enumerable:!1,get:e}),e}});var gT=I((lQ,mT)=>{"use strict";p();var J5=Hs(),eU=da(),tU=Qv(),hT=Jv(),rU=dT(),pT=eU(hT());J5(pT,{getPolyfill:hT,implementation:tU,shim:rU});mT.exports=pT});var tw=I((uQ,wT)=>{"use strict";p();var nU=_s()(),iU=Lt(),ew=iU("Object.prototype.toString"),rh=function(e){return nU&&e&&typeof e=="object"&&Symbol.toStringTag in e?!1:ew(e)==="[object Arguments]"},vT=function(e){return rh(e)?!0:e!==null&&typeof e=="object"&&"length"in e&&typeof e.length=="number"&&e.length>=0&&ew(e)!=="[object Array]"&&"callee"in e&&ew(e.callee)==="[object Function]"},sU=function(){return rh(arguments)}();rh.isLegacyArguments=vT;wT.exports=sU?rh:vT});var yT=I(()=>{p()});var ku=I((mQ,BT)=>{p();var fw=typeof Map=="function"&&Map.prototype,rw=Object.getOwnPropertyDescriptor&&fw?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,ih=fw&&rw&&typeof rw.get=="function"?rw.get:null,bT=fw&&Map.prototype.forEach,dw=typeof Set=="function"&&Set.prototype,nw=Object.getOwnPropertyDescriptor&&dw?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,sh=dw&&nw&&typeof nw.get=="function"?nw.get:null,_T=dw&&Set.prototype.forEach,aU=typeof WeakMap=="function"&&WeakMap.prototype,xu=aU?WeakMap.prototype.has:null,oU=typeof WeakSet=="function"&&WeakSet.prototype,Su=oU?WeakSet.prototype.has:null,lU=typeof WeakRef=="function"&&WeakRef.prototype,xT=lU?WeakRef.prototype.deref:null,cU=Boolean.prototype.valueOf,uU=Object.prototype.toString,fU=Function.prototype.toString,dU=String.prototype.match,hw=String.prototype.slice,Us=String.prototype.replace,hU=String.prototype.toUpperCase,ST=String.prototype.toLowerCase,IT=RegExp.prototype.test,ET=Array.prototype.concat,pi=Array.prototype.join,pU=Array.prototype.slice,kT=Math.floor,aw=typeof BigInt=="function"?BigInt.prototype.valueOf:null,iw=Object.getOwnPropertySymbols,ow=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?Symbol.prototype.toString:null,dl=typeof Symbol=="function"&&typeof Symbol.iterator=="object",Eu=typeof Symbol=="function"&&Symbol.toStringTag&&(typeof Symbol.toStringTag===dl||!0)?Symbol.toStringTag:null,FT=Object.prototype.propertyIsEnumerable,AT=(typeof Reflect=="function"?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function CT(t,e){if(t===1/0||t===-1/0||t!==t||t&&t>-1e3&&t<1e3||IT.call(/e/,e))return e;var r=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if(typeof t=="number"){var n=t<0?-kT(-t):kT(t);if(n!==t){var i=String(n),s=hw.call(e,i.length+1);return Us.call(i,r,"$&_")+"."+Us.call(Us.call(s,/([0-9]{3})/g,"$&_"),/_$/,"")}}return Us.call(e,r,"$&_")}var lw=yT(),TT=lw.custom,PT=DT(TT)?TT:null,OT={__proto__:null,double:'"',single:"'"},mU={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};BT.exports=function t(e,r,n,i){var s=r||{};if(Xi(s,"quoteStyle")&&!Xi(OT,s.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(Xi(s,"maxStringLength")&&(typeof s.maxStringLength=="number"?s.maxStringLength<0&&s.maxStringLength!==1/0:s.maxStringLength!==null))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var a=Xi(s,"customInspect")?s.customInspect:!0;if(typeof a!="boolean"&&a!=="symbol")throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(Xi(s,"indent")&&s.indent!==null&&s.indent!==" "&&!(parseInt(s.indent,10)===s.indent&&s.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(Xi(s,"numericSeparator")&&typeof s.numericSeparator!="boolean")throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var o=s.numericSeparator;if(typeof e=="undefined")return"undefined";if(e===null)return"null";if(typeof e=="boolean")return e?"true":"false";if(typeof e=="string")return NT(e,s);if(typeof e=="number"){if(e===0)return 1/0/e>0?"0":"-0";var l=String(e);return o?CT(e,l):l}if(typeof e=="bigint"){var c=String(e)+"n";return o?CT(e,c):c}var u=typeof s.depth=="undefined"?5:s.depth;if(typeof n=="undefined"&&(n=0),n>=u&&u>0&&typeof e=="object")return cw(e)?"[Array]":"[Object]";var f=FU(s,n);if(typeof i=="undefined")i=[];else if(LT(i,e)>=0)return"[Circular]";function d(B,H,ce){if(H&&(i=pU.call(i),i.push(H)),ce){var Pe={depth:s.depth};return Xi(s,"quoteStyle")&&(Pe.quoteStyle=s.quoteStyle),t(B,Pe,n+1,i)}return t(B,s,n+1,i)}if(typeof e=="function"&&!RT(e)){var h=EU(e),m=nh(e,d);return"[Function"+(h?": "+h:" (anonymous)")+"]"+(m.length>0?" { "+pi.call(m,", ")+" }":"")}if(DT(e)){var g=dl?Us.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):ow.call(e);return typeof e=="object"&&!dl?_u(g):g}if(RU(e)){for(var v="<"+ST.call(String(e.nodeName)),w=e.attributes||[],b=0;b",v}if(cw(e)){if(e.length===0)return"[]";var k=nh(e,d);return f&&!IU(k)?"["+uw(k,f)+"]":"[ "+pi.call(k,", ")+" ]"}if(wU(e)){var x=nh(e,d);return!("cause"in Error.prototype)&&"cause"in e&&!FT.call(e,"cause")?"{ ["+String(e)+"] "+pi.call(ET.call("[cause]: "+d(e.cause),x),", ")+" }":x.length===0?"["+String(e)+"]":"{ ["+String(e)+"] "+pi.call(x,", ")+" }"}if(typeof e=="object"&&a){if(PT&&typeof e[PT]=="function"&&lw)return lw(e,{depth:u-n});if(a!=="symbol"&&typeof e.inspect=="function")return e.inspect()}if(kU(e)){var E=[];return bT&&bT.call(e,function(B,H){E.push(d(H,e,!0)+" => "+d(B,e))}),$T("Map",ih.call(e),E,f)}if(TU(e)){var A=[];return _T&&_T.call(e,function(B){A.push(d(B,e))}),$T("Set",sh.call(e),A,f)}if(AU(e))return sw("WeakMap");if(PU(e))return sw("WeakSet");if(CU(e))return sw("WeakRef");if(bU(e))return _u(d(Number(e)));if(xU(e))return _u(d(aw.call(e)));if(_U(e))return _u(cU.call(e));if(yU(e))return _u(d(String(e)));if(typeof window!="undefined"&&e===window)return"{ [object Window] }";if(typeof globalThis!="undefined"&&e===globalThis||typeof global!="undefined"&&e===global)return"{ [object globalThis] }";if(!vU(e)&&!RT(e)){var y=nh(e,d),S=AT?AT(e)===Object.prototype:e instanceof Object||e.constructor===Object,_=e instanceof Object?"":"null prototype",C=!S&&Eu&&Object(e)===e&&Eu in e?hw.call(Gs(e),8,-1):_?"Object":"",P=S||typeof e.constructor!="function"?"":e.constructor.name?e.constructor.name+" ":"",N=P+(C||_?"["+pi.call(ET.call([],C||[],_||[]),": ")+"] ":"");return y.length===0?N+"{}":f?N+"{"+uw(y,f)+"}":N+"{ "+pi.call(y,", ")+" }"}return String(e)};function MT(t,e,r){var n=r.quoteStyle||e,i=OT[n];return i+t+i}function gU(t){return Us.call(String(t),/"/g,""")}function Pa(t){return!Eu||!(typeof t=="object"&&(Eu in t||typeof t[Eu]!="undefined"))}function cw(t){return Gs(t)==="[object Array]"&&Pa(t)}function vU(t){return Gs(t)==="[object Date]"&&Pa(t)}function RT(t){return Gs(t)==="[object RegExp]"&&Pa(t)}function wU(t){return Gs(t)==="[object Error]"&&Pa(t)}function yU(t){return Gs(t)==="[object String]"&&Pa(t)}function bU(t){return Gs(t)==="[object Number]"&&Pa(t)}function _U(t){return Gs(t)==="[object Boolean]"&&Pa(t)}function DT(t){if(dl)return t&&typeof t=="object"&&t instanceof Symbol;if(typeof t=="symbol")return!0;if(!t||typeof t!="object"||!ow)return!1;try{return ow.call(t),!0}catch(e){}return!1}function xU(t){if(!t||typeof t!="object"||!aw)return!1;try{return aw.call(t),!0}catch(e){}return!1}var SU=Object.prototype.hasOwnProperty||function(t){return t in this};function Xi(t,e){return SU.call(t,e)}function Gs(t){return uU.call(t)}function EU(t){if(t.name)return t.name;var e=dU.call(fU.call(t),/^function\s*([\w$]+)/);return e?e[1]:null}function LT(t,e){if(t.indexOf)return t.indexOf(e);for(var r=0,n=t.length;re.maxStringLength){var r=t.length-e.maxStringLength,n="... "+r+" more character"+(r>1?"s":"");return NT(hw.call(t,0,e.maxStringLength),e)+n}var i=mU[e.quoteStyle||"single"];i.lastIndex=0;var s=Us.call(Us.call(t,i,"\\$1"),/[\x00-\x1f]/g,$U);return MT(s,"single",e)}function $U(t){var e=t.charCodeAt(0),r={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return r?"\\"+r:"\\x"+(e<16?"0":"")+hU.call(e.toString(16))}function _u(t){return"Object("+t+")"}function sw(t){return t+" { ? }"}function $T(t,e,r,n){var i=n?uw(r,n):pi.call(r,", ");return t+" ("+e+") {"+i+"}"}function IU(t){for(var e=0;e=0)return!1;return!0}function FU(t,e){var r;if(t.indent===" ")r=" ";else if(typeof t.indent=="number"&&t.indent>0)r=pi.call(Array(t.indent+1)," ");else return null;return{base:r,prev:pi.call(Array(e+1),r)}}function uw(t,e){if(t.length===0)return"";var r=` +`+e.prev+e.base;return r+pi.call(t,","+r)+` +`+e.prev}function nh(t,e){var r=cw(t),n=[];if(r){n.length=t.length;for(var i=0;i{"use strict";p();var OU=ku(),MU=_r(),ah=function(t,e,r){for(var n=t,i;(i=n.next)!=null;n=i)if(i.key===e)return n.next=i.next,r||(i.next=t.next,t.next=i),i},DU=function(t,e){if(t){var r=ah(t,e);return r&&r.value}},LU=function(t,e,r){var n=ah(t,e);n?n.value=r:t.next={key:e,next:t.next,value:r}},NU=function(t,e){return t?!!ah(t,e):!1},BU=function(t,e){if(t)return ah(t,e,!0)};HT.exports=function(){var e,r={assert:function(n){if(!r.has(n))throw new MU("Side channel does not contain "+OU(n))},delete:function(n){var i=e&&e.next,s=BU(e,n);return s&&i&&i===s&&(e=void 0),!!s},get:function(n){return DU(e,n)},has:function(n){return NU(e,n)},set:function(n,i){e||(e={next:void 0}),LU(e,n,i)}};return r}});var pw=I((yQ,jT)=>{"use strict";p();var HU=si(),Au=Lt(),UU=ku(),GU=_r(),GT=HU("%Map%",!0),jU=Au("Map.prototype.get",!0),qU=Au("Map.prototype.set",!0),WU=Au("Map.prototype.has",!0),zU=Au("Map.prototype.delete",!0),VU=Au("Map.prototype.size",!0);jT.exports=!!GT&&function(){var e,r={assert:function(n){if(!r.has(n))throw new GU("Side channel does not contain "+UU(n))},delete:function(n){if(e){var i=zU(e,n);return VU(e)===0&&(e=void 0),i}return!1},get:function(n){if(e)return jU(e,n)},has:function(n){return e?WU(e,n):!1},set:function(n,i){e||(e=new GT),qU(e,n,i)}};return r}});var WT=I((_Q,qT)=>{"use strict";p();var YU=si(),lh=Lt(),XU=ku(),oh=pw(),ZU=_r(),hl=YU("%WeakMap%",!0),KU=lh("WeakMap.prototype.get",!0),QU=lh("WeakMap.prototype.set",!0),JU=lh("WeakMap.prototype.has",!0),e4=lh("WeakMap.prototype.delete",!0);qT.exports=hl?function(){var e,r,n={assert:function(i){if(!n.has(i))throw new ZU("Side channel does not contain "+XU(i))},delete:function(i){if(hl&&i&&(typeof i=="object"||typeof i=="function")){if(e)return e4(e,i)}else if(oh&&r)return r.delete(i);return!1},get:function(i){return hl&&i&&(typeof i=="object"||typeof i=="function")&&e?KU(e,i):r&&r.get(i)},has:function(i){return hl&&i&&(typeof i=="object"||typeof i=="function")&&e?JU(e,i):!!r&&r.has(i)},set:function(i,s){hl&&i&&(typeof i=="object"||typeof i=="function")?(e||(e=new hl),QU(e,i,s)):oh&&(r||(r=oh()),r.set(i,s))}};return n}:oh});var mw=I((SQ,zT)=>{"use strict";p();var t4=_r(),r4=ku(),n4=UT(),i4=pw(),s4=WT(),a4=s4||i4||n4;zT.exports=function(){var e,r={assert:function(n){if(!r.has(n))throw new t4("Side channel does not contain "+r4(n))},delete:function(n){return!!e&&e.delete(n)},get:function(n){return e&&e.get(n)},has:function(n){return!!e&&e.has(n)},set:function(n,i){e||(e=a4()),e.set(n,i)}};return r}});var YT=I((kQ,VT)=>{"use strict";p();var o4=Yf(),Cu=mw()(),Zi=_r(),gw={assert:function(t,e){if(!t||typeof t!="object"&&typeof t!="function")throw new Zi("`O` is not an object");if(typeof e!="string")throw new Zi("`slot` must be a string");if(Cu.assert(t),!gw.has(t,e))throw new Zi("`"+e+"` is not present on `O`")},get:function(t,e){if(!t||typeof t!="object"&&typeof t!="function")throw new Zi("`O` is not an object");if(typeof e!="string")throw new Zi("`slot` must be a string");var r=Cu.get(t);return r&&r["$"+e]},has:function(t,e){if(!t||typeof t!="object"&&typeof t!="function")throw new Zi("`O` is not an object");if(typeof e!="string")throw new Zi("`slot` must be a string");var r=Cu.get(t);return!!r&&o4(r,"$"+e)},set:function(t,e,r){if(!t||typeof t!="object"&&typeof t!="function")throw new Zi("`O` is not an object");if(typeof e!="string")throw new Zi("`slot` must be a string");var n=Cu.get(t);n||(n={},Cu.set(t,n)),n["$"+e]=r}};Object.freeze&&Object.freeze(gw);VT.exports=gw});var KT=I((CQ,ZT)=>{"use strict";p();var Tu=YT(),l4=Hf(),XT=typeof StopIteration=="object"?StopIteration:null;ZT.exports=function(e){if(!XT)throw new l4("this environment lacks StopIteration");Tu.set(e,"[[Done]]",!1);var r={next:function(){var i=Tu.get(this,"[[Iterator]]"),s=!!Tu.get(i,"[[Done]]");try{return{done:s,value:s?void 0:i.next()}}catch(a){if(Tu.set(i,"[[Done]]",!0),a!==XT)throw a;return{done:!0,value:void 0}}}};return Tu.set(r,"[[Iterator]]",e),r}});var vw=I((PQ,JT)=>{"use strict";p();var QT=Lt(),c4=QT("String.prototype.valueOf"),u4=function(e){try{return c4(e),!0}catch(r){return!1}},f4=QT("Object.prototype.toString"),d4="[object String]",h4=_s()();JT.exports=function(e){return typeof e=="string"?!0:!e||typeof e!="object"?!1:h4?u4(e):f4(e)===d4}});var yw=I(($Q,r2)=>{"use strict";p();var ww=typeof Map=="function"&&Map.prototype?Map:null,p4=typeof Set=="function"&&Set.prototype?Set:null,ch;ww||(ch=function(e){return!1});var t2=ww?Map.prototype.has:null,e2=p4?Set.prototype.has:null;!ch&&!t2&&(ch=function(e){return!1});r2.exports=ch||function(e){if(!e||typeof e!="object")return!1;try{if(t2.call(e),e2)try{e2.call(e)}catch(r){return!0}return e instanceof ww}catch(r){}return!1}});var _w=I((FQ,s2)=>{"use strict";p();var m4=typeof Map=="function"&&Map.prototype?Map:null,bw=typeof Set=="function"&&Set.prototype?Set:null,uh;bw||(uh=function(e){return!1});var n2=m4?Map.prototype.has:null,i2=bw?Set.prototype.has:null;!uh&&!i2&&(uh=function(e){return!1});s2.exports=uh||function(e){if(!e||typeof e!="object")return!1;try{if(i2.call(e),n2)try{n2.call(e)}catch(r){return!0}return e instanceof bw}catch(r){}return!1}});var v2=I((MQ,hh)=>{"use strict";p();var a2=tw(),o2=KT();jf()()||Sc()()?(fh=Symbol.iterator,hh.exports=function(e){if(e!=null&&typeof e[fh]!="undefined")return e[fh]();if(a2(e))return Array.prototype[fh].call(e)}):(l2=Nf(),c2=vw(),xw=si(),u2=xw("%Map%",!0),f2=xw("%Set%",!0),vn=Kv(),Sw=vn("Array.prototype.push"),Ew=vn("String.prototype.charCodeAt"),d2=vn("String.prototype.slice"),h2=function(e,r){var n=e.length;if(r+1>=n)return r+1;var i=Ew(e,r);if(i<55296||i>56319)return r+1;var s=Ew(e,r+1);return s<56320||s>57343?r+1:r+2},dh=function(e){var r=0;return{next:function(){var i=r>=e.length,s;return i||(s=e[r],r+=1),{done:i,value:s}}}},kw=function(e,r){if(l2(e)||a2(e))return dh(e);if(c2(e)){var n=0;return{next:function(){var s=h2(e,n),a=d2(e,n,s);return n=s,{done:s>e.length,value:a}}}}if(r&&typeof e["_es6-shim iterator_"]!="undefined")return e["_es6-shim iterator_"]()},!u2&&!f2?hh.exports=function(e){if(e!=null)return kw(e,!0)}:(p2=yw(),m2=_w(),Aw=vn("Map.prototype.forEach",!0),Cw=vn("Set.prototype.forEach",!0),(typeof process=="undefined"||!process.versions||!process.versions.node)&&(Tw=vn("Map.prototype.iterator",!0),Pw=vn("Set.prototype.iterator",!0)),Rw=vn("Map.prototype.@@iterator",!0)||vn("Map.prototype._es6-shim iterator_",!0),$w=vn("Set.prototype.@@iterator",!0)||vn("Set.prototype._es6-shim iterator_",!0),g2=function(e){if(p2(e)){if(Tw)return o2(Tw(e));if(Rw)return Rw(e);if(Aw){var r=[];return Aw(e,function(i,s){Sw(r,[s,i])}),dh(r)}}if(m2(e)){if(Pw)return o2(Pw(e));if($w)return $w(e);if(Cw){var n=[];return Cw(e,function(i){Sw(n,i)}),dh(n)}}},hh.exports=function(e){return g2(e)||kw(e)}));var fh,l2,c2,xw,u2,f2,vn,Sw,Ew,d2,h2,dh,kw,p2,m2,Aw,Cw,Tw,Pw,Rw,$w,g2});var Iw=I((LQ,y2)=>{"use strict";p();var w2=function(t){return t!==t};y2.exports=function(e,r){return e===0&&r===0?1/e===1/r:!!(e===r||w2(e)&&w2(r))}});var Fw=I((BQ,b2)=>{"use strict";p();var g4=Iw();b2.exports=function(){return typeof Object.is=="function"?Object.is:g4}});var x2=I((UQ,_2)=>{"use strict";p();var v4=Fw(),w4=Hs();_2.exports=function(){var e=v4();return w4(Object,{is:e},{is:function(){return Object.is!==e}}),e}});var A2=I((jQ,k2)=>{"use strict";p();var y4=Hs(),b4=da(),_4=Iw(),S2=Fw(),x4=x2(),E2=b4(S2(),Object);y4(E2,{getPolyfill:S2,implementation:_4,shim:x4});k2.exports=E2});var Mw=I((WQ,R2)=>{"use strict";p();var S4=da(),P2=Lt(),E4=si(),Ow=E4("%ArrayBuffer%",!0),ph=P2("ArrayBuffer.prototype.byteLength",!0),k4=P2("Object.prototype.toString"),C2=!!Ow&&!ph&&new Ow(0).slice,T2=!!C2&&S4(C2);R2.exports=ph||T2?function(e){if(!e||typeof e!="object")return!1;try{return ph?ph(e):T2(e,0),!0}catch(r){return!1}}:Ow?function(e){return k4(e)==="[object ArrayBuffer]"}:function(e){return!1}});var F2=I((VQ,I2)=>{"use strict";p();var $2=Lt(),A4=$2("Date.prototype.getDay"),C4=function(e){try{return A4(e),!0}catch(r){return!1}},T4=$2("Object.prototype.toString"),P4="[object Date]",R4=_s()();I2.exports=function(e){return typeof e!="object"||e===null?!1:R4?C4(e):T4(e)===P4}});var Bw=I((XQ,N2)=>{"use strict";p();var O2=Lt(),$4=_s()(),I4=Yf(),F4=bs(),Nw;$4?(M2=O2("RegExp.prototype.exec"),Dw={},mh=function(){throw Dw},Lw={toString:mh,valueOf:mh},typeof Symbol.toPrimitive=="symbol"&&(Lw[Symbol.toPrimitive]=mh),Nw=function(e){if(!e||typeof e!="object")return!1;var r=F4(e,"lastIndex"),n=r&&I4(r,"value");if(!n)return!1;try{M2(e,Lw)}catch(i){return i===Dw}}):(D2=O2("Object.prototype.toString"),L2="[object RegExp]",Nw=function(e){return!e||typeof e!="object"&&typeof e!="function"?!1:D2(e)===L2});var M2,Dw,mh,Lw,D2,L2;N2.exports=Nw});var U2=I((KQ,H2)=>{"use strict";p();var O4=Lt(),B2=O4("SharedArrayBuffer.prototype.byteLength",!0);H2.exports=B2?function(e){if(!e||typeof e!="object")return!1;try{return B2(e),!0}catch(r){return!1}}:function(e){return!1}});var q2=I((JQ,j2)=>{"use strict";p();var G2=Lt(),M4=G2("Number.prototype.toString"),D4=function(e){try{return M4(e),!0}catch(r){return!1}},L4=G2("Object.prototype.toString"),N4="[object Number]",B4=_s()();j2.exports=function(e){return typeof e=="number"?!0:!e||typeof e!="object"?!1:B4?D4(e):L4(e)===N4}});var V2=I((tJ,z2)=>{"use strict";p();var W2=Lt(),H4=W2("Boolean.prototype.toString"),U4=W2("Object.prototype.toString"),G4=function(e){try{return H4(e),!0}catch(r){return!1}},j4="[object Boolean]",q4=_s()();z2.exports=function(e){return typeof e=="boolean"?!0:e===null||typeof e!="object"?!1:q4?G4(e):U4(e)===j4}});var X2=I((nJ,Y2)=>{"use strict";p();var W4=Lt(),z4=Bw(),V4=W4("RegExp.prototype.exec"),Y4=_r();Y2.exports=function(e){if(!z4(e))throw new Y4("`regex` must be a RegExp");return function(n){return V4(e,n)!==null}}});var eP=I((sJ,Hw)=>{"use strict";p();var J2=Lt(),X4=J2("Object.prototype.toString"),Z4=jf()(),K4=X2();Z4?(Z2=J2("Symbol.prototype.toString"),K2=K4(/^Symbol\(.*\)$/),Q2=function(e){return typeof e.valueOf()!="symbol"?!1:K2(Z2(e))},Hw.exports=function(e){if(typeof e=="symbol")return!0;if(!e||typeof e!="object"||X4(e)!=="[object Symbol]")return!1;try{return Q2(e)}catch(r){return!1}}):Hw.exports=function(e){return!1};var Z2,K2,Q2});var nP=I((oJ,rP)=>{"use strict";p();var tP=typeof BigInt!="undefined"&&BigInt;rP.exports=function(){return typeof tP=="function"&&typeof BigInt=="function"&&typeof tP(42)=="bigint"&&typeof BigInt(42)=="bigint"}});var aP=I((cJ,Uw)=>{"use strict";p();var Q4=nP()();Q4?(iP=BigInt.prototype.valueOf,sP=function(e){try{return iP.call(e),!0}catch(r){}return!1},Uw.exports=function(e){return e===null||typeof e=="undefined"||typeof e=="boolean"||typeof e=="string"||typeof e=="number"||typeof e=="symbol"||typeof e=="function"?!1:typeof e=="bigint"?!0:sP(e)}):Uw.exports=function(e){return!1};var iP,sP});var lP=I((fJ,oP)=>{"use strict";p();var J4=vw(),eG=q2(),tG=V2(),rG=eP(),nG=aP();oP.exports=function(e){if(e==null||typeof e!="object"&&typeof e!="function")return null;if(J4(e))return"String";if(eG(e))return"Number";if(tG(e))return"Boolean";if(rG(e))return"Symbol";if(nG(e))return"BigInt"}});var fP=I((hJ,uP)=>{"use strict";p();var gh=typeof WeakMap=="function"&&WeakMap.prototype?WeakMap:null,cP=typeof WeakSet=="function"&&WeakSet.prototype?WeakSet:null,vh;gh||(vh=function(e){return!1});var jw=gh?gh.prototype.has:null,Gw=cP?cP.prototype.has:null;!vh&&!jw&&(vh=function(e){return!1});uP.exports=vh||function(e){if(!e||typeof e!="object")return!1;try{if(jw.call(e,jw),Gw)try{Gw.call(e,Gw)}catch(r){return!0}return e instanceof gh}catch(r){}return!1}});var hP=I((mJ,Ww)=>{"use strict";p();var iG=si(),dP=Lt(),sG=iG("%WeakSet%",!0),qw=dP("WeakSet.prototype.has",!0);qw?(wh=dP("WeakMap.prototype.has",!0),Ww.exports=function(e){if(!e||typeof e!="object")return!1;try{if(qw(e,qw),wh)try{wh(e,wh)}catch(r){return!0}return e instanceof sG}catch(r){}return!1}):Ww.exports=function(e){return!1};var wh});var mP=I((vJ,pP)=>{"use strict";p();var aG=yw(),oG=_w(),lG=fP(),cG=hP();pP.exports=function(e){if(e&&typeof e=="object"){if(aG(e))return"Map";if(oG(e))return"Set";if(lG(e))return"WeakMap";if(cG(e))return"WeakSet"}return!1}});var wP=I((yJ,vP)=>{"use strict";p();var uG=Lt(),gP=uG("ArrayBuffer.prototype.byteLength",!0),fG=Mw();vP.exports=function(e){return fG(e)?gP?gP(e):e.byteLength:NaN}});var jP=I((_J,GP)=>{"use strict";p();var BP=JC(),mi=Kv(),yP=gT(),dG=si(),pl=v2(),hG=mw(),bP=A2(),_P=tw(),xP=Nf(),SP=Mw(),EP=F2(),kP=Bw(),AP=U2(),CP=eh(),TP=lP(),PP=mP(),RP=ug(),$P=wP(),IP=mi("SharedArrayBuffer.prototype.byteLength",!0),FP=mi("Date.prototype.getTime"),zw=Object.getPrototypeOf,OP=mi("Object.prototype.toString"),bh=dG("%Set%",!0),Vw=mi("Map.prototype.has",!0),_h=mi("Map.prototype.get",!0),MP=mi("Map.prototype.size",!0),xh=mi("Set.prototype.add",!0),HP=mi("Set.prototype.delete",!0),Sh=mi("Set.prototype.has",!0),yh=mi("Set.prototype.size",!0);function DP(t,e,r,n){for(var i=pl(t),s;(s=i.next())&&!s.done;)if(Nn(e,s.value,r,n))return HP(t,s.value),!0;return!1}function UP(t){if(typeof t=="undefined")return null;if(typeof t!="object")return typeof t=="symbol"?!1:typeof t=="string"||typeof t=="number"?+t==+t:!0}function pG(t,e,r,n,i,s){var a=UP(r);if(a!=null)return a;var o=_h(e,a),l=BP({},i,{strict:!1});return typeof o=="undefined"&&!Vw(e,a)||!Nn(n,o,l,s)?!1:!Vw(t,a)&&Nn(n,o,l,s)}function mG(t,e,r){var n=UP(r);return n!=null?n:Sh(e,n)&&!Sh(t,n)}function LP(t,e,r,n,i,s){for(var a=pl(t),o,l;(o=a.next())&&!o.done;)if(l=o.value,Nn(r,l,i,s)&&Nn(n,_h(e,l),i,s))return HP(t,l),!0;return!1}function Nn(t,e,r,n){var i=r||{};if(i.strict?bP(t,e):t===e)return!0;var s=TP(t),a=TP(e);if(s!==a)return!1;if(!t||!e||typeof t!="object"&&typeof e!="object")return i.strict?bP(t,e):t==e;var o=n.has(t),l=n.has(e),c;if(o&&l){if(n.get(t)===n.get(e))return!0}else c={};return o||n.set(t,c),l||n.set(e,c),wG(t,e,i,n)}function NP(t){return!t||typeof t!="object"||typeof t.length!="number"||typeof t.copy!="function"||typeof t.slice!="function"||t.length>0&&typeof t[0]!="number"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function gG(t,e,r,n){if(yh(t)!==yh(e))return!1;for(var i=pl(t),s=pl(e),a,o,l;(a=i.next())&&!a.done;)if(a.value&&typeof a.value=="object")l||(l=new bh),xh(l,a.value);else if(!Sh(e,a.value)){if(r.strict||!mG(t,e,a.value))return!1;l||(l=new bh),xh(l,a.value)}if(l){for(;(o=s.next())&&!o.done;)if(o.value&&typeof o.value=="object"){if(!DP(l,o.value,r.strict,n))return!1}else if(!r.strict&&!Sh(t,o.value)&&!DP(l,o.value,r.strict,n))return!1;return yh(l)===0}return!0}function vG(t,e,r,n){if(MP(t)!==MP(e))return!1;for(var i=pl(t),s=pl(e),a,o,l,c,u,f;(a=i.next())&&!a.done;)if(c=a.value[0],u=a.value[1],c&&typeof c=="object")l||(l=new bh),xh(l,c);else if(f=_h(e,c),typeof f=="undefined"&&!Vw(e,c)||!Nn(u,f,r,n)){if(r.strict||!pG(t,e,c,u,r,n))return!1;l||(l=new bh),xh(l,c)}if(l){for(;(o=s.next())&&!o.done;)if(c=o.value[0],f=o.value[1],c&&typeof c=="object"){if(!LP(l,t,c,f,r,n))return!1}else if(!r.strict&&(!t.has(c)||!Nn(_h(t,c),f,r,n))&&!LP(l,t,c,f,BP({},r,{strict:!1}),n))return!1;return yh(l)===0}return!0}function wG(t,e,r,n){var i,s;if(typeof t!=typeof e||t==null||e==null||OP(t)!==OP(e)||_P(t)!==_P(e))return!1;var a=xP(t),o=xP(e);if(a!==o)return!1;var l=t instanceof Error,c=e instanceof Error;if(l!==c||(l||c)&&(t.name!==e.name||t.message!==e.message))return!1;var u=kP(t),f=kP(e);if(u!==f||(u||f)&&(t.source!==e.source||yP(t)!==yP(e)))return!1;var d=EP(t),h=EP(e);if(d!==h||(d||h)&&FP(t)!==FP(e)||r.strict&&zw&&zw(t)!==zw(e))return!1;var m=RP(t),g=RP(e);if(m!==g)return!1;if(m||g){if(t.length!==e.length)return!1;for(i=0;i=0;i--)if(A[i]!=y[i])return!1;for(i=A.length-1;i>=0;i--)if(s=A[i],!Nn(t[s],e[s],r,n))return!1;var S=PP(t),_=PP(e);return S!==_?!1:S==="Set"||_==="Set"?gG(t,e,r,n):S==="Map"?vG(t,e,r,n):!0}GP.exports=function(e,r,n){return Nn(e,r,n,hG())}});var nR=I((RJ,rR)=>{p();rR.exports=function(t,e){var r=t,n=e,i=r.length,s=n.length,a=!1,o=i+1,l=[],c=[],u,f,d=function(){i>=s&&(u=r,f=i,r=n,n=u,i=s,s=f,a=!0,o=i+1)},h=function(g,v,w,b,k){return{startX:g,startY:v,endX:w,endY:b,r:k}},m=function(g,v,w){var b,k,x,E,A;for(v>w?b=l[g-1+o]:b=l[g+1+o],A=x=Math.max(v,w),E=k=x-g;k=g+1;--E)w[E+o]=m(E,w[E-1+o]+1,w[E+1+o]);w[g+o]=m(g,w[g-1+o]+1,w[g+1+o])}while(w[g+o]!==s);for(ed=g+2*b,k=l[g+o],A=i,y=s,S=[];k!==-1;){let _=c[k];(i!=_.endX||s!=_.endY)&&S.push({file1:[a?_.endY:_.endX,a?y-_.endY:A-_.endX],file2:[a?_.endX:_.endY,a?A-_.endX:y-_.endY]}),A=_.startX,y=_.startY,k=c[k].r}return(A!=0||y!=0)&&S.push({file1:[0,a?y:A],file2:[0,a?A:y]}),S.reverse(),S}}}});var aR=I((IJ,sR)=>{p();var iR=nR();function bG(t,e,r){var n,i=new iR(e,t).compose(),s=new iR(e,r).compose(),a=[];function o(B,H){a.push([B.file1[0],H,B.file1[1],B.file2[0],B.file2[1]])}for(n=0;nc&&(l.push([1,c,B-c]),c=B)}for(var f=0;fg)break;g=Math.max(g,w+v[2]),f++}if(u(m),d==f)h[4]>0&&l.push([h[1],h[3],h[4]]);else{var b={0:[t.length,-1,e.length,-1],2:[r.length,-1,e.length,-1]};for(n=d;n<=f;n++){h=a[n];var k=h[1],x=b[k],E=h[0],A=E+h[2],y=h[3],S=y+h[4];x[0]=Math.min(y,x[0]),x[1]=Math.max(S,x[1]),x[2]=Math.min(E,x[2]),x[3]=Math.max(A,x[3])}var _=b[0][0]+(m-b[0][2]),C=b[0][1]+(g-b[0][3]),P=b[2][0]+(m-b[2][2]),N=b[2][1]+(g-b[2][3]);l.push([-1,_,C-_,m,g-m,P,N-P])}c=g}return u(e.length),l}function _G(t,e,r){var n=[],i=[t,e,r],s=bG(t,e,r),a=[];function o(){a.length&&n.push({ok:a}),a=[]}function l(h){for(var m=0;m{p();var yl=1e3,bl=yl*60,_l=bl*60,$a=_l*24,EG=$a*7,kG=$a*365.25;lR.exports=function(t,e){e=e||{};var r=typeof t;if(r==="string"&&t.length>0)return AG(t);if(r==="number"&&isFinite(t))return e.long?TG(t):CG(t);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(t))};function AG(t){if(t=String(t),!(t.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(t);if(e){var r=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*kG;case"weeks":case"week":case"w":return r*EG;case"days":case"day":case"d":return r*$a;case"hours":case"hour":case"hrs":case"hr":case"h":return r*_l;case"minutes":case"minute":case"mins":case"min":case"m":return r*bl;case"seconds":case"second":case"secs":case"sec":case"s":return r*yl;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:return}}}}function CG(t){var e=Math.abs(t);return e>=$a?Math.round(t/$a)+"d":e>=_l?Math.round(t/_l)+"h":e>=bl?Math.round(t/bl)+"m":e>=yl?Math.round(t/yl)+"s":t+"ms"}function TG(t){var e=Math.abs(t);return e>=$a?Ch(t,e,$a,"day"):e>=_l?Ch(t,e,_l,"hour"):e>=bl?Ch(t,e,bl,"minute"):e>=yl?Ch(t,e,yl,"second"):t+" ms"}function Ch(t,e,r,n){var i=e>=r*1.5;return Math.round(t/r)+" "+n+(i?"s":"")}});var fR=I((qJ,uR)=>{p();function PG(t){r.debug=r,r.default=r,r.coerce=l,r.disable=a,r.enable=i,r.enabled=o,r.humanize=cR(),r.destroy=c,Object.keys(t).forEach(u=>{r[u]=t[u]}),r.names=[],r.skips=[],r.formatters={};function e(u){let f=0;for(let d=0;d{if(A==="%%")return"%";x++;let S=r.formatters[y];if(typeof S=="function"){let _=v[x];A=S.call(w,_),v.splice(x,1),x--}return A}),r.formatArgs.call(w,v),(w.log||r.log).apply(w,v)}return g.namespace=u,g.useColors=r.useColors(),g.color=r.selectColor(u),g.extend=n,g.destroy=r.destroy,Object.defineProperty(g,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(h!==r.namespaces&&(h=r.namespaces,m=r.enabled(u)),m),set:v=>{d=v}}),typeof r.init=="function"&&r.init(g),g}function n(u,f){let d=r(this.namespace+(typeof f=="undefined"?":":f)+u);return d.log=this.log,d}function i(u){r.save(u),r.namespaces=u,r.names=[],r.skips=[];let f=(typeof u=="string"?u:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let d of f)d[0]==="-"?r.skips.push(d.slice(1)):r.names.push(d)}function s(u,f){let d=0,h=0,m=-1,g=0;for(;d"-"+f)].join(",");return r.enable(""),u}function o(u){for(let f of r.skips)if(s(u,f))return!1;for(let f of r.names)if(s(u,f))return!0;return!1}function l(u){return u instanceof Error?u.stack||u.message:u}function c(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return r.enable(r.load()),r}uR.exports=PG});var Ph=I((Cr,Th)=>{p();Cr.formatArgs=$G;Cr.save=IG;Cr.load=FG;Cr.useColors=RG;Cr.storage=OG();Cr.destroy=(()=>{let t=!1;return()=>{t||(t=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();Cr.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function RG(){if(typeof window!="undefined"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let t;return typeof document!="undefined"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window!="undefined"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator!="undefined"&&navigator.userAgent&&(t=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(t[1],10)>=31||typeof navigator!="undefined"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function $G(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+Th.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;t.splice(1,0,e,"color: inherit");let r=0,n=0;t[0].replace(/%[a-zA-Z%]/g,i=>{i!=="%%"&&(r++,i==="%c"&&(n=r))}),t.splice(n,0,e)}Cr.log=console.debug||console.log||(()=>{});function IG(t){try{t?Cr.storage.setItem("debug",t):Cr.storage.removeItem("debug")}catch(e){}}function FG(){let t;try{t=Cr.storage.getItem("debug")||Cr.storage.getItem("DEBUG")}catch(e){}return!t&&typeof process!="undefined"&&"env"in process&&(t=process.env.DEBUG),t}function OG(){try{return localStorage}catch(t){}}Th.exports=fR()(Cr);var{formatters:MG}=Th.exports;MG.j=function(t){try{return JSON.stringify(t)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var dR=I(Kr=>{"use strict";p();var DG=Kr&&Kr.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Kr,"__esModule",{value:!0});var LG=require("fs"),NG=DG(Ph()),xl=NG.default("@kwsites/file-exists");function BG(t,e,r){xl("checking %s",t);try{let n=LG.statSync(t);return n.isFile()&&e?(xl("[OK] path represents a file"),!0):n.isDirectory()&&r?(xl("[OK] path represents a directory"),!0):(xl("[FAIL] path represents something other than a file or directory"),!1)}catch(n){if(n.code==="ENOENT")return xl("[FAIL] path is not accessible: %o",n),!1;throw xl("[FATAL] %o",n),n}}function HG(t,e=Kr.READABLE){return BG(t,(e&Kr.FILE)>0,(e&Kr.FOLDER)>0)}Kr.exists=HG;Kr.FILE=1;Kr.FOLDER=2;Kr.READABLE=Kr.FILE+Kr.FOLDER});var hR=I(Rh=>{"use strict";p();function UG(t){for(var e in t)Rh.hasOwnProperty(e)||(Rh[e]=t[e])}Object.defineProperty(Rh,"__esModule",{value:!0});UG(dR())});var t0=I(Ia=>{"use strict";p();Object.defineProperty(Ia,"__esModule",{value:!0});Ia.createDeferred=Ia.deferred=void 0;function e0(){let t,e,r="pending";return{promise:new Promise((i,s)=>{t=i,e=s}),done(i){r==="pending"&&(r="resolved",t(i))},fail(i){r==="pending"&&(r="rejected",e(i))},get fulfilled(){return r!=="pending"},get status(){return r}}}Ia.deferred=e0;Ia.createDeferred=e0;Ia.default=e0});var V0=I((exports,module)=>{p();(function(){"use strict";var ERROR="input is invalid type",WINDOW=typeof window=="object",root=WINDOW?window:{};root.JS_SHA256_NO_WINDOW&&(WINDOW=!1);var WEB_WORKER=!WINDOW&&typeof self=="object",NODE_JS=!root.JS_SHA256_NO_NODE_JS&&typeof process=="object"&&process.versions&&process.versions.node;NODE_JS?root=global:WEB_WORKER&&(root=self);var COMMON_JS=!root.JS_SHA256_NO_COMMON_JS&&typeof module=="object"&&module.exports,AMD=typeof define=="function"&&define.amd,ARRAY_BUFFER=!root.JS_SHA256_NO_ARRAY_BUFFER&&typeof ArrayBuffer!="undefined",HEX_CHARS="0123456789abcdef".split(""),EXTRA=[-2147483648,8388608,32768,128],SHIFT=[24,16,8,0],K=[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],OUTPUT_TYPES=["hex","array","digest","arrayBuffer"],blocks=[];(root.JS_SHA256_NO_NODE_JS||!Array.isArray)&&(Array.isArray=function(t){return Object.prototype.toString.call(t)==="[object Array]"}),ARRAY_BUFFER&&(root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW||!ArrayBuffer.isView)&&(ArrayBuffer.isView=function(t){return typeof t=="object"&&t.buffer&&t.buffer.constructor===ArrayBuffer});var createOutputMethod=function(t,e){return function(r){return new Sha256(e,!0).update(r)[t]()}},createMethod=function(t){var e=createOutputMethod("hex",t);NODE_JS&&(e=nodeWrap(e,t)),e.create=function(){return new Sha256(t)},e.update=function(i){return e.create().update(i)};for(var r=0;r>2]|=t[i]<>2]|=n<>2]|=(192|n>>6)<>2]|=(128|n&63)<=57344?(o[s>>2]|=(224|n>>12)<>2]|=(128|n>>6&63)<>2]|=(128|n&63)<>2]|=(240|n>>18)<>2]|=(128|n>>12&63)<>2]|=(128|n>>6&63)<>2]|=(128|n&63)<=64?(this.block=o[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}},Sha256.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>2]|=EXTRA[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}},Sha256.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,a=this.h6,o=this.h7,l=this.blocks,c,u,f,d,h,m,g,v,w,b,k;for(c=16;c<64;++c)h=l[c-15],u=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,h=l[c-2],f=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,l[c]=l[c-16]+u+l[c-7]+f<<0;for(k=e&r,c=0;c<64;c+=4)this.first?(this.is224?(v=300032,h=l[0]-1413257819,o=h-150054599<<0,n=h+24177077<<0):(v=704751109,h=l[0]-210244248,o=h-1521486534<<0,n=h+143694565<<0),this.first=!1):(u=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),f=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),v=t&e,d=v^t&r^k,g=i&s^~i&a,h=o+f+g+K[c]+l[c],m=u+d,o=n+h<<0,n=h+m<<0),u=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),f=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),w=n&t,d=w^n&e^v,g=o&i^~o&s,h=a+f+g+K[c+1]+l[c+1],m=u+d,a=r+h<<0,r=h+m<<0,u=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),f=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),b=r&n,d=b^r&t^w,g=a&o^~a&i,h=s+f+g+K[c+2]+l[c+2],m=u+d,s=e+h<<0,e=h+m<<0,u=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),f=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),k=e&r,d=k^e&n^b,g=s&a^~s&o,h=i+f+g+K[c+3]+l[c+3],m=u+d,i=t+h<<0,t=h+m<<0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+i<<0,this.h5=this.h5+s<<0,this.h6=this.h6+a<<0,this.h7=this.h7+o<<0},Sha256.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,a=this.h6,o=this.h7,l=HEX_CHARS[t>>28&15]+HEX_CHARS[t>>24&15]+HEX_CHARS[t>>20&15]+HEX_CHARS[t>>16&15]+HEX_CHARS[t>>12&15]+HEX_CHARS[t>>8&15]+HEX_CHARS[t>>4&15]+HEX_CHARS[t&15]+HEX_CHARS[e>>28&15]+HEX_CHARS[e>>24&15]+HEX_CHARS[e>>20&15]+HEX_CHARS[e>>16&15]+HEX_CHARS[e>>12&15]+HEX_CHARS[e>>8&15]+HEX_CHARS[e>>4&15]+HEX_CHARS[e&15]+HEX_CHARS[r>>28&15]+HEX_CHARS[r>>24&15]+HEX_CHARS[r>>20&15]+HEX_CHARS[r>>16&15]+HEX_CHARS[r>>12&15]+HEX_CHARS[r>>8&15]+HEX_CHARS[r>>4&15]+HEX_CHARS[r&15]+HEX_CHARS[n>>28&15]+HEX_CHARS[n>>24&15]+HEX_CHARS[n>>20&15]+HEX_CHARS[n>>16&15]+HEX_CHARS[n>>12&15]+HEX_CHARS[n>>8&15]+HEX_CHARS[n>>4&15]+HEX_CHARS[n&15]+HEX_CHARS[i>>28&15]+HEX_CHARS[i>>24&15]+HEX_CHARS[i>>20&15]+HEX_CHARS[i>>16&15]+HEX_CHARS[i>>12&15]+HEX_CHARS[i>>8&15]+HEX_CHARS[i>>4&15]+HEX_CHARS[i&15]+HEX_CHARS[s>>28&15]+HEX_CHARS[s>>24&15]+HEX_CHARS[s>>20&15]+HEX_CHARS[s>>16&15]+HEX_CHARS[s>>12&15]+HEX_CHARS[s>>8&15]+HEX_CHARS[s>>4&15]+HEX_CHARS[s&15]+HEX_CHARS[a>>28&15]+HEX_CHARS[a>>24&15]+HEX_CHARS[a>>20&15]+HEX_CHARS[a>>16&15]+HEX_CHARS[a>>12&15]+HEX_CHARS[a>>8&15]+HEX_CHARS[a>>4&15]+HEX_CHARS[a&15];return this.is224||(l+=HEX_CHARS[o>>28&15]+HEX_CHARS[o>>24&15]+HEX_CHARS[o>>20&15]+HEX_CHARS[o>>16&15]+HEX_CHARS[o>>12&15]+HEX_CHARS[o>>8&15]+HEX_CHARS[o>>4&15]+HEX_CHARS[o&15]),l},Sha256.prototype.toString=Sha256.prototype.hex,Sha256.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,a=this.h6,o=this.h7,l=[t>>24&255,t>>16&255,t>>8&255,t&255,e>>24&255,e>>16&255,e>>8&255,e&255,r>>24&255,r>>16&255,r>>8&255,r&255,n>>24&255,n>>16&255,n>>8&255,n&255,i>>24&255,i>>16&255,i>>8&255,i&255,s>>24&255,s>>16&255,s>>8&255,s&255,a>>24&255,a>>16&255,a>>8&255,a&255];return this.is224||l.push(o>>24&255,o>>16&255,o>>8&255,o&255),l},Sha256.prototype.array=Sha256.prototype.digest,Sha256.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};function HmacSha256(t,e,r){var n,i=typeof t;if(i==="string"){var s=[],a=t.length,o=0,l;for(n=0;n>6,s[o++]=128|l&63):l<55296||l>=57344?(s[o++]=224|l>>12,s[o++]=128|l>>6&63,s[o++]=128|l&63):(l=65536+((l&1023)<<10|t.charCodeAt(++n)&1023),s[o++]=240|l>>18,s[o++]=128|l>>12&63,s[o++]=128|l>>6&63,s[o++]=128|l&63);t=s}else if(i==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);t.length>64&&(t=new Sha256(e,!0).update(t).array());var c=[],u=[];for(n=0;n<64;++n){var f=t[n]||0;c[n]=92^f,u[n]=54^f}Sha256.call(this,e,r),this.update(u),this.oKeyPad=c,this.inner=!0,this.sharedMemory=r}HmacSha256.prototype=new Sha256,HmacSha256.prototype.finalize=function(){if(Sha256.prototype.finalize.call(this),this.inner){this.inner=!1;var t=this.array();Sha256.call(this,this.is224,this.sharedMemory),this.update(this.oKeyPad),this.update(t),Sha256.prototype.finalize.call(this)}};var exports=createMethod();exports.sha256=exports,exports.sha224=createMethod(!0),exports.sha256.hmac=createHmacMethod(),exports.sha224.hmac=createHmacMethod(!0),COMMON_JS?module.exports=exports:(root.sha256=exports.sha256,root.sha224=exports.sha224,AMD&&define(function(){return exports}))})()});var OO=I(Ay=>{p();(function(t){var e=/\S/,r=/\"/g,n=/\n/g,i=/\r/g,s=/\\/g,a=/\u2028/,o=/\u2029/;t.tags={"#":1,"^":2,"<":3,$:4,"/":5,"!":6,">":7,"=":8,_v:9,"{":10,"&":11,_t:12},t.scan=function(S,_){var C=S.length,P=0,N=1,B=2,H=P,ce=null,Pe=null,ve="",ie=[],xe=!1,we=0,W=0,X="{{",q="}}";function De(){ve.length>0&&(ie.push({tag:"_t",text:new String(ve)}),ve="")}function ar(){for(var kt=!0,At=W;At"&&(Z.indent=ie[je].text.toString()),ie.splice(je,1));else At||ie.push({tag:` +`});xe=!1,W=ie.length}function Ie(kt,At){var je="="+q,Z=kt.indexOf(je,At),M=c(kt.substring(kt.indexOf("=",At)+1,Z)).split(" ");return X=M[0],q=M[M.length-1],Z+je.length-1}for(_&&(_=_.split(" "),X=_[0],q=_[1]),we=0;we0;){if(H=y.shift(),B&&B.tag=="<"&&!(H.tag in f))throw new Error("Illegal content in < super tag.");if(t.tags[H.tag]<=t.tags.$||h(H,C))_.push(H),H.nodes=d(y,H.tag,_,C);else if(H.tag=="/"){if(_.length===0)throw new Error("Closing tag without opener: /"+H.n);if(N=_.pop(),H.n!=N.n&&!m(H.n,N.n,C))throw new Error("Nesting error: "+N.n+" vs. "+H.n);return N.end=H.i,P}else H.tag==` +`&&(H.last=y.length==0||y[0].tag==` +`);P.push(H)}if(_.length>0)throw new Error("missing closing tag: "+_.pop().n);return P}function h(y,S){for(var _=0,C=S.length;_":x,"<":function(y,S){var _={partials:{},code:"",subs:{},inPartial:!0};t.walk(y.nodes,_);var C=S.partials[x(y,S)];C.subs=_.subs,C.partials=_.partials},$:function(y,S){var _={subs:{},code:"",partials:S.partials,prefix:y.n};t.walk(y.nodes,_),S.subs[y.n]=_.code,S.inPartial||(S.code+='t.sub("'+b(y.n)+'",c,p,i);')},"\n":function(y,S){S.code+=A('"\\n"'+(y.last?"":" + i"))},_v:function(y,S){S.code+="t.b(t.v(t."+k(y.n)+'("'+b(y.n)+'",c,p,0)));'},_t:function(y,S){S.code+=A('"'+b(y.text)+'"')},"{":E,"&":E};function E(y,S){S.code+="t.b(t.t(t."+k(y.n)+'("'+b(y.n)+'",c,p,0)));'}function A(y){return"t.b("+y+");"}t.walk=function(y,S){for(var _,C=0,P=y.length;C{p();var PV={};(function(t){t.Template=function(d,h,m,g){d=d||{},this.r=d.code||this.r,this.c=m,this.options=g||{},this.text=h||"",this.partials=d.partials||{},this.subs=d.subs||{},this.buf=""},t.Template.prototype={r:function(d,h,m){return""},v:u,t:c,render:function(h,m,g){return this.ri([h],m||{},g)},ri:function(d,h,m){return this.r(d,h,m)},ep:function(d,h){var m=this.partials[d],g=h[m.name];if(m.instance&&m.base==g)return m.instance;if(typeof g=="string"){if(!this.c)throw new Error("No compiler available.");g=this.c.compile(g,this.options)}if(!g)return null;if(this.partials[d].base=g,m.subs){h.stackText||(h.stackText={});for(key in m.subs)h.stackText[key]||(h.stackText[key]=this.activeSub!==void 0&&h.stackText[this.activeSub]?h.stackText[this.activeSub]:this.text);g=r(g,m.subs,m.partials,this.stackSubs,this.stackPartials,h.stackText)}return this.partials[d].instance=g,g},rp:function(d,h,m,g){var v=this.ep(d,m);return v?v.ri(h,m,g):""},rs:function(d,h,m){var g=d[d.length-1];if(!f(g)){m(d,h,this);return}for(var v=0;v=0;x--)if(w=h[x],v=e(d,w,k),v!==void 0){b=!0;break}return b?(!g&&typeof v=="function"&&(v=this.mv(v,h,m)),v):g?!1:""},ls:function(d,h,m,g,v,w){var b=this.options.delimiters;return this.options.delimiters=w,this.b(this.ct(c(d.call(h,v,m)),h,g)),this.options.delimiters=b,!1},ct:function(d,h,m){if(this.options.disableLambda)throw new Error("Lambda features disabled.");return this.c.compile(d,this.options).render(h,m)},b:function(d){this.buf+=d},fl:function(){var d=this.buf;return this.buf="",d},ms:function(d,h,m,g,v,w,b){var k,x=h[h.length-1],E=d.call(x);return typeof E=="function"?g?!0:(k=this.activeSub&&this.subsText&&this.subsText[this.activeSub]?this.subsText[this.activeSub]:this.text,this.ls(E,x,h,m,k.substring(v,w),b)):E},mv:function(d,h,m){var g=h[h.length-1],v=d.call(g);return typeof v=="function"?this.ct(c(v.call(g)),g,m):v},sub:function(d,h,m,g){var v=this.subs[d];v&&(this.activeSub=d,v(h,m,this,g),this.activeSub=!1)}};function e(d,h,m){var g;return h&&typeof h=="object"&&(h[d]!==void 0?g=h[d]:m&&h.get&&typeof h.get=="function"&&(g=h.get(d))),g}function r(d,h,m,g,v,w){function b(){}b.prototype=d;function k(){}k.prototype=d.subs;var x,E=new b;E.subs=new k,E.subsText={},E.buf="",g=g||{},E.stackSubs=g,E.subsText=w;for(x in h)g[x]||(g[x]=h[x]);for(x in g)E.subs[x]=g[x];v=v||{},E.stackPartials=v;for(x in m)v[x]||(v[x]=m[x]);for(x in v)E.partials[x]=v[x];return E}var n=/&/g,i=//g,a=/\'/g,o=/\"/g,l=/[&<>\"\']/;function c(d){return String(d==null?"":d)}function u(d){return d=c(d),l.test(d)?d.replace(n,"&").replace(i,"<").replace(s,">").replace(a,"'").replace(o,"""):d}var f=Array.isArray||function(d){return Object.prototype.toString.call(d)==="[object Array]"}})(typeof Cy!="undefined"?Cy:PV)});var Ty=I((vne,DO)=>{p();var kp=OO();kp.Template=MO().Template;kp.template=kp.Template;DO.exports=kp});var BO=I(En=>{"use strict";p();Object.defineProperty(En,"__esModule",{value:!0});En.ColorSchemeType=En.DiffStyleType=En.LineMatchingType=En.OutputFormatType=En.LineType=void 0;var LO;(function(t){t.INSERT="insert",t.DELETE="delete",t.CONTEXT="context"})(LO||(En.LineType=LO={}));En.OutputFormatType={LINE_BY_LINE:"line-by-line",SIDE_BY_SIDE:"side-by-side"};En.LineMatchingType={LINES:"lines",WORDS:"words",NONE:"none"};En.DiffStyleType={WORD:"word",CHAR:"char"};var NO;(function(t){t.AUTO="auto",t.DARK="dark",t.LIGHT="light"})(NO||(En.ColorSchemeType=NO={}))});var H7={};eL(H7,{default:()=>Pm});module.exports=tL(H7);p();var ID=Ct(Pv()),be=require("obsidian"),FD=Ct(require("path")),Rm=Ct(require("fs/promises"));p();var Ln={};p();var Gd=class{constructor(e){this.plugin=e;this.tasks=[]}addTask(e,r){this.tasks.push({task:e,onFinished:r!=null?r:()=>{}}),this.tasks.length===1&&this.handleTask()}handleTask(){if(this.tasks.length>0){let e=this.tasks[0];e.task().then(r=>{e.onFinished(r),this.tasks.shift(),this.handleTask()},r=>{this.plugin.displayError(r),e.onFinished(void 0),this.tasks.shift(),this.handleTask()})}}clear(){this.tasks=[]}};p();var U=require("obsidian");p();var KA=require("obsidian"),jd="YYYY-MM-DD",Rv=`${jd} HH:mm`,$v=`${jd} HH:mm:ss`,qd=40,ol="conflict-files-obsidian-git.md",et={commitMessage:"vault backup: {{date}}",autoCommitMessage:"vault backup: {{date}}",commitMessageScript:"",commitDateFormat:$v,autoSaveInterval:0,autoPushInterval:0,autoPullInterval:0,autoPullOnBoot:!1,autoCommitOnlyStaged:!1,disablePush:!1,pullBeforePush:!0,disablePopups:!1,showErrorNotices:!0,disablePopupsForNoChanges:!1,listChangedFilesInMessageBody:!1,showStatusBar:!0,updateSubmodules:!1,syncMethod:"merge",mergeStrategy:"none",customMessageOnAutoBackup:!1,autoBackupAfterFileChange:!1,treeStructure:!1,refreshSourceControl:KA.Platform.isDesktopApp,basePath:"",differentIntervalCommitAndPush:!1,changedFilesInStatusBar:!1,showedMobileNotice:!1,refreshSourceControlTimer:7e3,showBranchStatusBar:!0,setLastSaveToLastCommit:!1,submoduleRecurseCheckout:!1,gitDir:"",showFileMenu:!0,authorInHistoryView:"hide",dateInHistoryView:!1,diffStyle:"split",hunks:{showSigns:!1,hunkCommands:!1,statusBar:"disabled"},lineAuthor:{show:!1,followMovement:"inactive",authorDisplay:"initials",showCommitHash:!1,dateTimeFormatOptions:"date",dateTimeFormatCustomString:Rv,dateTimeTimezone:"viewer-local",coloringMaxAge:"1y",colorNew:{r:255,g:150,b:150},colorOld:{r:120,g:160,b:255},textColorCss:"var(--text-muted)",ignoreWhitespace:!1,gutterSpacingFallbackLength:5}},jt={type:"git-view",name:"Source Control",icon:"git-pull-request"},gn={type:"git-history-view",name:"History",icon:"history"},Ns={type:"split-diff-view",name:"Diff view",icon:"diff"},Bs={type:"diff-view",name:"Diff View",icon:"git-pull-request"},Wd="C:\\Program Files\\Git\\cmd\\git.exe",zd=".git_credentials_input",Ta="obsidian_askpass.sh",QA=`#!/bin/sh + +PROMPT="$1" +TEMP_FILE="$OBSIDIAN_GIT_CREDENTIALS_INPUT" + +cleanup() { + rm -f "$TEMP_FILE" "$TEMP_FILE.response" +} +trap cleanup EXIT + +echo "$PROMPT" > "$TEMP_FILE" + +while [ ! -e "$TEMP_FILE.response" ]; do + if [ ! -e "$TEMP_FILE" ]; then + echo "Trigger file got removed: Abort" >&2 + exit 1 + fi + sleep 0.1 +done + +RESPONSE=$(cat "$TEMP_FILE.response") + +echo "$RESPONSE" +`,JA=["3dm","3ds","3g2","3gp","7z","a","aac","adp","afdesign","afphoto","afpub","ai","aif","aiff","alz","ape","apk","appimage","ar","arj","asf","au","avi","bak","baml","bh","bin","bk","bmp","btif","bz2","bzip2","cab","caf","cgm","class","cmx","cpio","cr2","cur","dat","dcm","deb","dex","djvu","dll","dmg","dng","doc","docm","docx","dot","dotm","dra","DS_Store","dsk","dts","dtshd","dvb","dwg","dxf","ecelp4800","ecelp7470","ecelp9600","egg","eol","eot","epub","exe","f4v","fbs","fh","fla","flac","flatpak","fli","flv","fpx","fst","fvt","g3","gh","gif","graffle","gz","gzip","h261","h263","h264","icns","ico","ief","img","ipa","iso","jar","jpeg","jpg","jpgv","jpm","jxr","key","ktx","lha","lib","lvp","lz","lzh","lzma","lzo","m3u","m4a","m4v","mar","mdi","mht","mid","midi","mj2","mka","mkv","mmr","mng","mobi","mov","movie","mp3","mp4","mp4a","mpeg","mpg","mpga","mxu","nef","npx","numbers","nupkg","o","odp","ods","odt","oga","ogg","ogv","otf","ott","pages","pbm","pcx","pdb","pdf","pea","pgm","pic","png","pnm","pot","potm","potx","ppa","ppam","ppm","pps","ppsm","ppsx","ppt","pptm","pptx","psd","pya","pyc","pyo","pyv","qt","rar","ras","raw","resources","rgb","rip","rlc","rmf","rmvb","rpm","rtf","rz","s3m","s7z","scpt","sgi","shar","snap","sil","sketch","slk","smv","snk","so","stl","suo","sub","swf","tar","tbz","tbz2","tga","tgz","thmx","tif","tiff","tlz","ttc","ttf","txz","udf","uvh","uvi","uvm","uvp","uvs","uvu","viv","vob","war","wav","wax","wbmp","wdp","weba","webm","webp","whl","wim","wm","wma","wmv","wmx","woff","woff2","wrm","wvx","xbm","xif","xla","xlam","xls","xlsb","xlsm","xlsx","xlt","xltm","xltx","xm","xmind","xpi","xpm","xwd","xz","z","zip","zipx"];p();p();p();var hi=class{diff(e,r,n={}){let i;typeof n=="function"?(i=n,n={}):"callback"in n&&(i=n.callback);let s=this.castInput(e,n),a=this.castInput(r,n),o=this.removeEmpty(this.tokenize(s,n)),l=this.removeEmpty(this.tokenize(a,n));return this.diffWithOptionsObj(o,l,n,i)}diffWithOptionsObj(e,r,n,i){var s;let a=b=>{if(b=this.postProcess(b,n),i){setTimeout(function(){i(b)},0);return}else return b},o=r.length,l=e.length,c=1,u=o+l;n.maxEditLength!=null&&(u=Math.min(u,n.maxEditLength));let f=(s=n.timeout)!==null&&s!==void 0?s:1/0,d=Date.now()+f,h=[{oldPos:-1,lastComponent:void 0}],m=this.extractCommon(h[0],r,e,0,n);if(h[0].oldPos+1>=l&&m+1>=o)return a(this.buildValues(h[0].lastComponent,r,e));let g=-1/0,v=1/0,w=()=>{for(let b=Math.max(g,-c);b<=Math.min(v,c);b+=2){let k,x=h[b-1],E=h[b+1];x&&(h[b-1]=void 0);let A=!1;if(E){let S=E.oldPos-b;A=E&&0<=S&&S=l&&m+1>=o)return a(this.buildValues(k.lastComponent,r,e))||!0;h[b]=k,k.oldPos+1>=l&&(v=Math.min(v,b-1)),m+1>=o&&(g=Math.max(g,b+1))}c++};if(i)(function b(){setTimeout(function(){if(c>u||Date.now()>d)return i(void 0);w()||b()},0)})();else for(;c<=u&&Date.now()<=d;){let b=w();if(b)return b}}addToPath(e,r,n,i,s){let a=e.lastComponent;return a&&!s.oneChangePerToken&&a.added===r&&a.removed===n?{oldPos:e.oldPos+i,lastComponent:{count:a.count+1,added:r,removed:n,previousComponent:a.previousComponent}}:{oldPos:e.oldPos+i,lastComponent:{count:1,added:r,removed:n,previousComponent:a}}}extractCommon(e,r,n,i,s){let a=r.length,o=n.length,l=e.oldPos,c=l-i,u=0;for(;c+1d.length?m:d}),u.value=this.join(f)}else u.value=this.join(r.slice(l,l+u.count));l+=u.count,u.added||(c+=u.count)}}return i}};p();var Iv=class extends hi{},eC=new Iv;function Fv(t,e,r){return eC.diff(t,e,r)}p();p();function Ov(t,e){let r;for(r=0;re.length&&(r=t.length-e.length);let n=e.length;t.length0&&e[a]!=e[s];)s=i[s];e[a]==e[s]&&s++}s=0;for(let a=r;a0&&t[a]!=e[s];)s=i[s];t[a]==e[s]&&s++}return s}function cl(t){let e;for(e=t.length-1;e>=0&&t[e].match(/\s/);e--);return t.substring(e+1)}function Vi(t){let e=t.match(/^\s*/);return e?e[0]:""}var Xd="a-zA-Z0-9_\\u{AD}\\u{C0}-\\u{D6}\\u{D8}-\\u{F6}\\u{F8}-\\u{2C6}\\u{2C8}-\\u{2D7}\\u{2DE}-\\u{2FF}\\u{1E00}-\\u{1EFF}",X6=new RegExp(`[${Xd}]+|\\s+|[^${Xd}]`,"ug"),Lv=class extends hi{equals(e,r,n){return n.ignoreCase&&(e=e.toLowerCase(),r=r.toLowerCase()),e.trim()===r.trim()}tokenize(e,r={}){let n;if(r.intlSegmenter){let a=r.intlSegmenter;if(a.resolvedOptions().granularity!="word")throw new Error('The segmenter passed must have a granularity of "word"');n=[];for(let o of Array.from(a.segment(e))){let l=o.segment;n.length&&/\s/.test(n[n.length-1])&&/\s/.test(l)?n[n.length-1]+=l:n.push(l)}}else n=e.match(X6)||[];let i=[],s=null;return n.forEach(a=>{/\s/.test(a)?s==null?i.push(a):i.push(i.pop()+a):s!=null&&/\s/.test(s)?i[i.length-1]==s?i.push(i.pop()+a):i.push(s+a):i.push(a),s=a}),i}join(e){return e.map((r,n)=>n==0?r:r.replace(/^\s+/,"")).join("")}postProcess(e,r){if(!e||r.oneChangePerToken)return e;let n=null,i=null,s=null;return e.forEach(a=>{a.added?i=a:a.removed?s=a:((i||s)&&tC(n,s,i,a),n=a,i=null,s=null)}),(i||s)&&tC(n,s,i,null),e}},Z6=new Lv;function tC(t,e,r,n){if(e&&r){let i=Vi(e.value),s=cl(e.value),a=Vi(r.value),o=cl(r.value);if(t){let l=Ov(i,a);t.value=Yd(t.value,a,l),e.value=ll(e.value,l),r.value=ll(r.value,l)}if(n){let l=Mv(s,o);n.value=Vd(n.value,o,l),e.value=pu(e.value,l),r.value=pu(r.value,l)}}else if(r){if(t){let i=Vi(r.value);r.value=r.value.substring(i.length)}if(n){let i=Vi(n.value);n.value=n.value.substring(i.length)}}else if(t&&n){let i=Vi(n.value),s=Vi(e.value),a=cl(e.value),o=Ov(i,s);e.value=ll(e.value,o);let l=Mv(ll(i,o),a);e.value=pu(e.value,l),n.value=Vd(n.value,i,l),t.value=Yd(t.value,i,i.slice(0,i.length-l.length))}else if(n){let i=Vi(n.value),s=cl(e.value),a=Dv(s,i);e.value=pu(e.value,a)}else if(t){let i=cl(t.value),s=Vi(e.value),a=Dv(i,s);e.value=ll(e.value,a)}}var Nv=class extends hi{tokenize(e){let r=new RegExp(`(\\r?\\n)|[${Xd}]+|[^\\S\\n\\r]+|[^${Xd}]`,"ug");return e.match(r)||[]}},rC=new Nv;function Bv(t,e,r){return rC.diff(t,e,r)}p();var Hv=class extends hi{constructor(){super(...arguments),this.tokenize=Q6}equals(e,r,n){return n.ignoreWhitespace?((!n.newlineIsToken||!e.includes(` +`))&&(e=e.trim()),(!n.newlineIsToken||!r.includes(` +`))&&(r=r.trim())):n.ignoreNewlineAtEof&&!n.newlineIsToken&&(e.endsWith(` +`)&&(e=e.slice(0,-1)),r.endsWith(` +`)&&(r=r.slice(0,-1))),super.equals(e,r,n)}},K6=new Hv;function Uv(t,e,r){return K6.diff(t,e,r)}function Q6(t,e){e.stripTrailingCr&&(t=t.replace(/\r\n/g,` +`));let r=[],n=t.split(/(\n|\r\n)/);n[n.length-1]||n.pop();for(let i=0;i{let d=c(f);u(d)}}))}else return c(Uv(r,n,o));function c(u){if(!u)return;u.push({value:"",lines:[]});function f(b){return b.map(function(k){return" "+k})}let d=[],h=0,m=0,g=[],v=1,w=1;for(let b=0;b0?f(E.lines.slice(-l)):[],h-=g.length,m-=g.length)}for(let E of x)g.push((k.added?"+":"-")+E);k.added?w+=x.length:v+=x.length}else{if(h)if(x.length<=l*2&&b1&&!e.includeFileHeaders)throw new Error("Cannot omit file headers on a multi-file patch. (The result would be unparseable; how would a tool trying to apply the patch know which changes are to which file?)");return t.map(n=>Zd(n,e)).join(` +`)}let r=[];e.includeIndex&&t.oldFileName==t.newFileName&&r.push("Index: "+t.oldFileName),e.includeUnderline&&r.push("==================================================================="),e.includeFileHeaders&&(r.push("--- "+t.oldFileName+(typeof t.oldHeader=="undefined"?"":" "+t.oldHeader)),r.push("+++ "+t.newFileName+(typeof t.newHeader=="undefined"?"":" "+t.newHeader)));for(let n=0;n{o(l?Zd(l,a.headerOptions):void 0)}}))}else{let o=Gv(t,e,r,n,i,s,a);return o?Zd(o,a==null?void 0:a.headerOptions):void 0}}function mu(t,e,r,n,i,s){return iC(t,t,e,r,n,i,s)}function J6(t){let e=t.endsWith(` +`),r=t.split(` +`).map(n=>n+` +`);return e?r.pop():r.push(r.pop().slice(0,-1)),r}var te=Ct(Pv()),Ra=require("obsidian");p();function sC(t,e){let r=Object.assign({},t.lineAuthor,e.lineAuthor);return Object.assign({},t,e,{lineAuthor:r})}var ul=class extends Error{constructor(r){super("No network connection available");this.originalError=r}};p();var aC=require("obsidian"),t5={options:[],placeholder:"",allowEmpty:!1,onlySelection:!1,initialValue:void 0,obscure:!1},Ze=class extends aC.SuggestModal{constructor(e,r){if(super(e.app),this.config={...t5,...r},this.setPlaceholder(this.config.placeholder),this.config.obscure){this.inputEl.type="password";let n=this.containerEl.querySelector(".prompt-input-container");n.addClass("git-obscure-prompt"),n.setAttr("git-is-obscured","true");let i=n==null?void 0:n.createDiv({cls:"search-input-clear-button"});i.style.marginRight="32px",i.id="git-show-password",i.addEventListener("click",()=>{n.getAttr("git-is-obscured")==="true"?(this.inputEl.type="text",n.setAttr("git-is-obscured","false")):(this.inputEl.type="password",n.setAttr("git-is-obscured","true"))})}}openAndGetResult(){return new Promise(e=>{this.resolve=e,this.open(),this.config.initialValue!=null&&(this.inputEl.value=this.config.initialValue,this.inputEl.dispatchEvent(new Event("input")))})}onClose(){new Promise(e=>setTimeout(e,10)).then(()=>{this.resolve&&this.resolve(void 0)})}getSuggestions(e){return this.config.onlySelection?this.config.options:this.config.allowEmpty?[e.length>0?e:" ",...this.config.options]:[e.length>0?e:"...",...this.config.options]}renderSuggestion(e,r){this.config.obscure?r.hide():r.setText(e)}onChooseSuggestion(e,r){if(this.resolve){let n;this.config.allowEmpty&&e===" "?n="":e==="..."?n=void 0:n=e,this.resolve(n)}}};p();var qP=Ct(EC()),WP=require("child_process"),zP=Ct(jP()),Ki=require("obsidian");function Eh(t){throw new Error(`Unexpected object: ${t}`)}function Pu(t,e,r){return t===1?`${t} ${e}`:`${t} ${r!=null?r:e+"s"}`}var Yw=(t,e)=>t==="."||e==null||e.length===0||e==="."?!0:e.length>=t.length?e.startsWith(t):t.startsWith(e);function Bn(t,e){let r;if(e){if(e.button===0||e.button===1){let n=Ki.Keymap.isModEvent(e);r=t.workspace.getLeaf(n)}}else r=t.workspace.getLeaf(!1);return r}function gi(t,e,r,n,i){if(e.button==2){let s=t.vault.getAbstractFileByPath(r);if(s!=null){let a=new Ki.Menu;t.workspace.trigger("file-menu",a,s,i,n),a.showAtPosition({x:e.pageX,y:e.pageY})}else{let a=new Ki.Menu;t.workspace.trigger("obsidian-git:menu",a,r,i,n),a.showAtPosition({x:e.pageX,y:e.pageY})}}}function js(t){throw new Error("Impossible branch: "+t)}function Xw(t){return`rgb(${t.r},${t.g},${t.b})`}function VP(t){var s;let e=(s=qP.fromString(t))==null?void 0:s.toRgbaArray();if(e===void 0)return;let[r,n,i]=e;return{r,g:n,b:i}}function YP(t){return t.diff(Ki.moment.unix(0),"seconds")}function XP(t){if(t.length!==0)return t.slice().sort()[Math.floor(t.length/2)]}function ZP(t,e){return(0,zP.default)(t,e,{strict:!0})}function Ru(t,e){return new Proxy(t,{get(r,n){return n==="length"?Math.min(e,r.length):r[n]}})}function KP(t,e,r){return t.length<=e?new Array(e-t.length).fill(r).join("")+t:t.substring(t.length-e)}function QP(t,e){if(e<=0)return t;let r=new Array(e).fill(" ").join(""),n=t.substring(e,t.length);return r+n}function Zw(t,e,r){return t<=e&&e<=r}function Qi(t){let[e,...r]=t.split("/");return[e,r.length===0?void 0:r.join("/")]}function vi(t){return t.endsWith("/")?t:t.split("/").last().replace(/\.md$/,"")}function JP(t){return t===1?"1 minute":`${t} minutes`}function yG(t){let e=t.lastIndexOf(".");return t.substring(e+1)}function ml(t){if(t.endsWith(".md"))return!1;let e=yG(t);return JA.includes(e)}function Kw(t){return(t.startsWith("https://github.com/")||t.startsWith("https://gitlab.com/"))&&(t.endsWith(".git")||(t=t+".git")),t}function gl(t,e){let r=e.vault.getAbstractFileByPath(t);if(!(r instanceof Ki.TFile))return!1;try{return!!e.viewRegistry.getTypeByExtension(r.extension)}catch(n){return!0}}function eR({isFolder:t,gitRelativePath:e}){let r="/";return r+=e,t&&(r+="/"),r.replace(/([\\!#*?[\]])/g,String.raw`\$1`).replace(/\s(?=\s*$)/g,String.raw`\ `)}function vl(t,e,r,n){let i=e.target;t.workspace.trigger("hover-link",{event:e,source:r.getViewType(),hoverParent:r,targetEl:i,linktext:n})}function $u(t,e,r={}){return new Promise((n,i)=>{let s=(0,WP.spawn)(t,e,r),a="",o="";s.stdout.on("data",l=>{a+=l.toString()}),s.stderr.on("data",l=>{o+=l.toString()}),s.on("error",l=>{n({error:new Error(l.message),stdout:a,stderr:a,code:1})}),s.on("close",l=>{n({stdout:a,stderr:o,code:l!=null?l:1,error:void 0})})})}p();var tR=require("os"),kh=require("obsidian"),wl=class{constructor(e){this.plugin=e,this.app=e.app}getRelativeVaultPath(e){return this.plugin.settings.basePath?this.plugin.settings.basePath+"/"+e:e}getRelativeRepoPath(e,r=!0){return r&&this.plugin.settings.basePath.length>0?e.substring(this.plugin.settings.basePath.length+1):e}unload(){}_getTreeStructure(e,r=0){let n=[];for(e=[...e];e.length>0;){let i=e.first(),s=i.path.substring(r);if(s.contains("/")){let a=s.substring(0,s.indexOf("/")),o=e.filter(c=>c.path.substring(r).startsWith(a+"/"));o.forEach(c=>e.remove(c));let l=i.path.substring(0,s.indexOf("/")+r);n.push({title:a,path:l,vaultPath:this.getRelativeVaultPath(l),children:this._getTreeStructure(o,(r>0?r+a.length:a.length)+1)})}else n.push({title:s,data:i,path:i.path,vaultPath:this.getRelativeVaultPath(i.path)}),e.remove(i)}return n}simplify(e){var r,n,i,s;for(let a of e){for(;;){let o=((r=a.children)==null?void 0:r.length)==1,l=((i=(n=a.children)==null?void 0:n.first())==null?void 0:i.data)==null;if(!(a.children!=null&&o&&l))break;let c=a.children.first();a.title+="/"+c.title,a.data=c.data,a.path=c.path,a.vaultPath=c.vaultPath,a.children=c.children}a.children!=null&&this.simplify(a.children),(s=a.children)==null||s.sort((o,l)=>{let c=(l.data==null?1:0)-(o.data==null?1:0);return c!=0?c:o.title.localeCompare(l.title)})}return e.sort((a,o)=>{let l=(o.data==null?1:0)-(a.data==null?1:0);return l!=0?l:a.title.localeCompare(o.title)})}getTreeStructure(e){let r=this._getTreeStructure(e);return this.simplify(r)}async formatCommitMessage(e){let r;if(e.includes("{{numFiles}}")){r=await this.status();let n=r.staged.length;e=e.replace("{{numFiles}}",String(n))}if(e.includes("{{hostname}}")){let n=this.plugin.localStorage.getHostname()||"";!n&&kh.Platform.isDesktopApp&&(n=(0,tR.hostname)()),e=e.replace("{{hostname}}",n)}if(e.includes("{{files}}")){r=r!=null?r:await this.status();let n={},i="";if(r.staged.length<100){r.staged.forEach(a=>{a.index in n?n[a.index].push(a.path):n[a.index]=[a.path]});let s=[];for(let[a,o]of Object.entries(n))s.push(a+" "+o.join(" "));i=s.join(", ")}else i="Too many files to list";e=e.replace("{{files}}",i)}if(e=e.replace("{{date}}",(0,kh.moment)().format(this.plugin.settings.commitDateFormat)),this.plugin.settings.listChangedFilesInMessageBody){let n=r!=null?r:await this.status(),i="";n.staged.length<100?i=n.staged.map(s=>s.path).join(` +`):i="Too many files to list",e=e+` + +Affected files: +`+i}return e}};p();var qs=require("obsidian"),Ah=class{constructor(e,r){this.plugin=r;this.promises={};this.adapter=e.adapter,this.vault=e,this.lastBasePath=this.plugin.settings.basePath,this.promises.readFile=this.readFile.bind(this),this.promises.writeFile=this.writeFile.bind(this),this.promises.readdir=this.readdir.bind(this),this.promises.mkdir=this.mkdir.bind(this),this.promises.rmdir=this.rmdir.bind(this),this.promises.stat=this.stat.bind(this),this.promises.unlink=this.unlink.bind(this),this.promises.lstat=this.lstat.bind(this),this.promises.readlink=this.readlink.bind(this),this.promises.symlink=this.symlink.bind(this)}async readFile(e,r){var n;if(this.maybeLog("Read: "+e+JSON.stringify(r)),r=="utf8"||r.encoding=="utf8"){let i=this.vault.getAbstractFileByPath(e);return i instanceof qs.TFile?(this.maybeLog("Reuse"),this.vault.read(i)):this.adapter.read(e)}else{if(e.endsWith(this.gitDir+"/index"))return this.plugin.settings.basePath!=this.lastBasePath?(this.clearIndex(),this.lastBasePath=this.plugin.settings.basePath,this.adapter.readBinary(e)):(n=this.index)!=null?n:this.adapter.readBinary(e);let i=this.vault.getAbstractFileByPath(e);return i instanceof qs.TFile?(this.maybeLog("Reuse"),this.vault.readBinary(i)):this.adapter.readBinary(e)}}async writeFile(e,r){if(this.maybeLog("Write: "+e),typeof r=="string"){let n=this.vault.getAbstractFileByPath(e);return n instanceof qs.TFile?this.vault.modify(n,r):this.adapter.write(e,r)}else if(e.endsWith(this.gitDir+"/index"))this.index=r,this.indexmtime=Date.now();else{let n=this.vault.getAbstractFileByPath(e);return n instanceof qs.TFile?this.vault.modifyBinary(n,r):this.adapter.writeBinary(e,r)}}async readdir(e){e==="."&&(e="/");let r=await this.adapter.list(e),n=[...r.files,...r.folders],i;return e!=="/"?i=n.map(s=>(0,qs.normalizePath)(s.substring(e.length))):i=n,i}async mkdir(e){return this.adapter.mkdir(e)}async rmdir(e,r){var n,i;return this.adapter.rmdir(e,(i=(n=r==null?void 0:r.options)==null?void 0:n.recursive)!=null?i:!1)}async stat(e){if(e.endsWith(this.gitDir+"/index")){if(this.index!==void 0&&this.indexctime!=null&&this.indexmtime!=null)return{isFile:()=>!0,isDirectory:()=>!1,isSymbolicLink:()=>!1,size:this.index.byteLength,type:"file",ctimeMs:this.indexctime,mtimeMs:this.indexmtime};{let n=await this.adapter.stat(e);if(n==null)throw{code:"ENOENT"};return this.indexctime=n.ctime,this.indexmtime=n.mtime,{ctimeMs:n.ctime,mtimeMs:n.mtime,size:n.size,type:"file",isFile:()=>!0,isDirectory:()=>!1,isSymbolicLink:()=>!1}}}e==="."&&(e="/");let r=this.vault.getAbstractFileByPath(e);if(this.maybeLog("Stat: "+e),r instanceof qs.TFile)return this.maybeLog("Reuse stat"),{ctimeMs:r.stat.ctime,mtimeMs:r.stat.mtime,size:r.stat.size,type:"file",isFile:()=>!0,isDirectory:()=>!1,isSymbolicLink:()=>!1};{let n=await this.adapter.stat(e);if(n)return{ctimeMs:n.ctime,mtimeMs:n.mtime,size:n.size,type:n.type==="folder"?"directory":n.type,isFile:()=>n.type==="file",isDirectory:()=>n.type==="folder",isSymbolicLink:()=>!1};throw{code:"ENOENT"}}}async unlink(e){return this.adapter.remove(e)}async lstat(e){return this.stat(e)}async readlink(e){throw new Error(`readlink of (${e}) is not implemented.`)}async symlink(e){throw new Error(`symlink of (${e}) is not implemented.`)}async saveAndClear(){this.index!==void 0&&await this.adapter.writeBinary(this.plugin.gitManager.getRelativeVaultPath(this.gitDir+"/index"),this.index,{ctime:this.indexctime,mtime:this.indexmtime}),this.clearIndex()}clearIndex(){this.index=void 0,this.indexctime=void 0,this.indexmtime=void 0}get gitDir(){return this.plugin.settings.gitDir||".git"}maybeLog(e){}};var oR=Ct(aR()),Hn=class extends wl{constructor(r){super(r);this.FILE=0;this.HEAD=1;this.WORKDIR=2;this.STAGE=3;this.status_mapping={"000":" ","003":"AD","020":"??","022":"A ","023":"AM",100:"D ",101:" D",103:"MD",110:"DA",111:" ",113:"MM",120:"DA",121:" M",122:"M ",123:"MM"};this.noticeLength=999999;this.fs=new Ah(this.app.vault,this.plugin)}getRepo(){return{fs:this.fs,dir:this.plugin.settings.basePath,gitdir:this.plugin.settings.gitDir||void 0,onAuth:()=>{var r,n;return{username:(r=this.plugin.localStorage.getUsername())!=null?r:void 0,password:(n=this.plugin.localStorage.getPassword())!=null?n:void 0}},onAuthFailure:async()=>{new Ra.Notice("Authentication failed. Please try with different credentials");let r=await new Ze(this.plugin,{placeholder:"Specify your username"}).openAndGetResult();if(r){let n=await new Ze(this.plugin,{placeholder:"Specify your password/personal access token",obscure:!0}).openAndGetResult();if(n)return this.plugin.localStorage.setUsername(r),this.plugin.localStorage.setPassword(n),{username:r,password:n}}return{cancel:!0}},http:{async request({url:r,method:n,headers:i,body:s}){let a;s&&(a=await SG(s));let o=await(0,Ra.requestUrl)({url:r,method:n,headers:i,body:a,throw:!1});return{url:r,method:n,headers:o.headers,body:xG(o.arrayBuffer),statusCode:o.status,statusMessage:o.status.toString()}}}}}async wrapFS(r){try{let n=await r;return await this.fs.saveAndClear(),n}catch(n){throw await this.fs.saveAndClear(),n}}async status(r){let n,i=window.setTimeout(()=>{n=new Ra.Notice("This takes longer: Getting status",this.noticeLength)},2e4);try{this.plugin.setPluginState({gitAction:1});let s={...this.getRepo()};(r==null?void 0:r.path)!=null&&(s.filepaths=[`${r.path}/`]);let a=(await this.wrapFS(te.default.statusMatrix(s))).map(f=>this.getFileStatusResult(f)),o=[],l=[],c=[];for(let f of a)f.workingDir!==" "&&o.push(f),f.index!==" "&&f.index!=="U"&&l.push(f),(f.index!=" "||f.workingDir!=" ")&&c.push(f);let u=[];return window.clearTimeout(i),n==null||n.hide(),{all:c,changed:o,staged:l,conflicted:u}}catch(s){throw window.clearTimeout(i),n==null||n.hide(),this.plugin.displayError(s),s}}async commitAll({message:r,status:n,unstagedFiles:i}){try{return await this.checkAuthorInfo(),await this.stageAll({status:n,unstagedFiles:i}),this.commit({message:r})}catch(s){throw this.plugin.displayError(s),s}}async commit({message:r}){try{await this.checkAuthorInfo(),this.plugin.setPluginState({gitAction:4});let n=await this.formatCommitMessage(r),i=this.plugin.localStorage.getConflict(),s;if(i){let a=await this.branchInfo();s=[a.current,a.tracking]}await this.wrapFS(te.default.commit({...this.getRepo(),message:n,parent:s})),this.plugin.localStorage.setConflict(!1);return}catch(n){throw this.plugin.displayError(n),n}}async stage(r,n){let i=this.getRelativeRepoPath(r,n),s;n?s=r:s=this.getRelativeVaultPath(r);try{this.plugin.setPluginState({gitAction:3}),await this.app.vault.adapter.exists(s)?await this.wrapFS(te.default.add({...this.getRepo(),filepath:i})):await this.wrapFS(te.default.remove({...this.getRepo(),filepath:i}))}catch(a){throw this.plugin.displayError(a),a}}async stageAll({dir:r,status:n,unstagedFiles:i}){try{if(n)await Promise.all(n.changed.map(s=>s.workingDir!=="D"?this.wrapFS(te.default.add({...this.getRepo(),filepath:s.path})):te.default.remove({...this.getRepo(),filepath:s.path})));else{let s=i!=null?i:await this.getUnstagedFiles(r!=null?r:".");await Promise.all(s.map(({path:a,type:o})=>o=="D"?te.default.remove({...this.getRepo(),filepath:a}):this.wrapFS(te.default.add({...this.getRepo(),filepath:a}))))}}catch(s){throw this.plugin.displayError(s),s}}async unstage(r,n){try{this.plugin.setPluginState({gitAction:3}),r=this.getRelativeRepoPath(r,n),await this.wrapFS(te.default.resetIndex({...this.getRepo(),filepath:r}))}catch(i){throw this.plugin.displayError(i),i}}async unstageAll({dir:r,status:n}){try{let i;n?i=n.staged.map(s=>s.path):i=(await this.getStagedFiles(r!=null?r:".")).map(({path:a})=>a),await this.wrapFS(Promise.all(i.map(s=>te.default.resetIndex({...this.getRepo(),filepath:s}))))}catch(i){throw this.plugin.displayError(i),i}}async discard(r){try{this.plugin.setPluginState({gitAction:3}),await this.wrapFS(te.default.checkout({...this.getRepo(),filepaths:[r],force:!0}))}catch(n){throw this.plugin.displayError(n),n}}async discardAll({dir:r,status:n}){let i=[];n?r!=null?i=n.changed.filter(s=>s.workingDir!="U"&&s.path.startsWith(r)).map(s=>s.path):i=n.changed.filter(s=>s.workingDir!="U").map(s=>s.path):i=(await this.getUnstagedFiles(r)).filter(s=>s.type!="A").map(({path:s})=>s);try{await this.wrapFS(te.default.checkout({...this.getRepo(),filepaths:i,force:!0}))}catch(s){throw this.plugin.displayError(s),s}}async getUntrackedPaths(r){let n=[];if(r.status)for(let i of r.status.changed)i.index=="U"&&i.workingDir==="U"&&i.path.startsWith(r.path!=null?`${r.path}/`:"")&&n.push(i.path);else{let i=await this.status({path:r==null?void 0:r.path});for(let s of i.changed)s.index==="U"&&s.workingDir==="U"&&n.push(s.path)}return n}getProgressText(r,n){let i=`${r} progress:`;return n.phase&&(i=`${i} ${n.phase}:`),n.loaded&&(i=`${i} ${n.loaded}`,n.total&&(i=`${i} of ${n.total}`)),i}resolveRef(r){return this.wrapFS(te.default.resolveRef({...this.getRepo(),ref:r}))}async pull(){let r=this.showNotice("Initializing pull");try{this.plugin.setPluginState({gitAction:2});let n=await this.resolveRef("HEAD");await this.fetch();let i=await this.branchInfo();await this.checkAuthorInfo(),(await this.wrapFS(te.default.merge({...this.getRepo(),ours:i.current,theirs:i.tracking,abortOnConflict:!1,mergeDriver:this.plugin.settings.mergeStrategy!=="none"?({contents:l})=>{var b,k,x;let c=l[0],u=l[1],f=l[2],d=/^.*(\r?\n|$)/gm,h=(b=u.match(d))!=null?b:[],m=(k=c.match(d))!=null?k:[],g=(x=f.match(d))!=null?x:[],v=(0,oR.default)(h,m,g),w="";for(let E of v)E.ok&&(w+=E.ok.join("")),E.conflict&&(w+=this.plugin.settings.mergeStrategy==="ours"?E.conflict.a.join(""):E.conflict.b.join(""));return{cleanMerge:!0,mergedText:w}}:void 0}))).alreadyMerged||await this.wrapFS(te.default.checkout({...this.getRepo(),ref:i.current,onProgress:l=>{r!==void 0&&(r.noticeEl.innerText=this.getProgressText("Checkout",l))},remote:i.remote})),r==null||r.hide();let a=await this.resolveRef("HEAD"),o=await this.getFileChangesCount(n,a);return this.showNotice("Finished pull",!1),o.map(l=>({path:l.path,workingDir:"P",index:"P",vaultPath:this.getRelativeVaultPath(l.path)}))}catch(n){throw r==null||r.hide(),n instanceof te.Errors.MergeConflictError&&await this.plugin.handleConflict(n.data.filepaths.map(i=>this.getRelativeVaultPath(i))),this.plugin.displayError(n),n}}async push(){if(!await this.canPush())return 0;let r=this.showNotice("Initializing push");try{this.plugin.setPluginState({gitAction:1});let n=await this.branchInfo(),i=n.tracking,s=n.current,a=(await this.getFileChangesCount(s,i)).length;this.plugin.setPluginState({gitAction:5});let o=await this.getCurrentRemote();return await this.wrapFS(te.default.push({...this.getRepo(),remote:o,onProgress:l=>{r!==void 0&&(r.noticeEl.innerText=this.getProgressText("Pushing",l))}})),r==null||r.hide(),a}catch(n){throw r==null||r.hide(),this.plugin.displayError(n),n}}async getUnpushedCommits(){let r=await this.branchInfo(),n=r.tracking,i=r.current;if(n==null||i==null)return 0;let s=await this.resolveRef(i),a=await this.resolveRef(n);return(await this.getFileChangesCount(s,a)).length}async canPush(){let r=await this.branchInfo(),n=r.tracking,i=r.current,s=await this.resolveRef(i),a=await this.resolveRef(n);return s!=a}async checkRequirements(){return await this.plugin.app.vault.adapter.exists(`${this.getRepo().dir}/.git/HEAD`)?"valid":"missing-repo"}async branchInfo(){var r,n;try{let i=await te.default.currentBranch(this.getRepo())||"",s=await te.default.listBranches(this.getRepo()),a=(r=await this.getConfig(`branch.${i}.remote`))!=null?r:"origin",o=(n=await this.getConfig(`branch.${i}.merge`))==null?void 0:n.split("refs/heads")[1],l=o?a+o:void 0;return{current:i,tracking:l,branches:s,remote:a}}catch(i){throw this.plugin.displayError(i),i}}async getCurrentRemote(){var i;let r=await te.default.currentBranch(this.getRepo())||"";return(i=await this.getConfig(`branch.${r}.remote`))!=null?i:"origin"}async checkout(r,n){try{return this.wrapFS(te.default.checkout({...this.getRepo(),ref:r,force:!!n,remote:n}))}catch(i){throw this.plugin.displayError(i),i}}async createBranch(r){try{await this.wrapFS(te.default.branch({...this.getRepo(),ref:r,checkout:!0}))}catch(n){throw this.plugin.displayError(n),n}}async deleteBranch(r){try{await this.wrapFS(te.default.deleteBranch({...this.getRepo(),ref:r}))}catch(n){throw this.plugin.displayError(n),n}}branchIsMerged(r){return Promise.resolve(!0)}async init(){try{await this.wrapFS(te.default.init(this.getRepo()))}catch(r){throw this.plugin.displayError(r),r}}async clone(r,n,i){let s=this.showNotice("Initializing clone");try{await this.wrapFS(te.default.clone({...this.getRepo(),dir:n,url:r,depth:i,onProgress:a=>{s!==void 0&&(s.noticeEl.innerText=this.getProgressText("Cloning",a))}})),s==null||s.hide()}catch(a){throw s==null||s.hide(),this.plugin.displayError(a),a}}async setConfig(r,n){try{return this.wrapFS(te.default.setConfig({...this.getRepo(),path:r,value:n}))}catch(i){throw this.plugin.displayError(i),i}}async getConfig(r){try{return this.wrapFS(te.default.getConfig({...this.getRepo(),path:r}))}catch(n){throw this.plugin.displayError(n),n}}async fetch(r){let n=this.showNotice("Initializing fetch");try{let i={...this.getRepo(),onProgress:s=>{n!==void 0&&(n.noticeEl.innerText=this.getProgressText("Fetching",s))},remote:r!=null?r:await this.getCurrentRemote()};await this.wrapFS(te.default.fetch(i)),n==null||n.hide()}catch(i){throw this.plugin.displayError(i),n==null||n.hide(),i}}async setRemote(r,n){try{await this.wrapFS(te.default.addRemote({...this.getRepo(),remote:r,url:n,force:!0}))}catch(i){throw this.plugin.displayError(i),i}}async getRemoteBranches(r){let n=[];return n.push(...await this.wrapFS(te.default.listBranches({...this.getRepo(),remote:r}))),n.remove("HEAD"),n=n.map(i=>`${r}/${i}`),n}async getRemotes(){return(await this.wrapFS(te.default.listRemotes({...this.getRepo()}))).map(r=>r.remote)}async removeRemote(r){await this.wrapFS(te.default.deleteRemote({...this.getRepo(),remote:r}))}async getRemoteUrl(r){var n;return(n=(await this.wrapFS(te.default.listRemotes({...this.getRepo()}))).filter(i=>i.remote==r)[0])==null?void 0:n.url}async log(r,n=!0,i,s){let a=await this.wrapFS(te.default.log({...this.getRepo(),depth:i,ref:s}));return Promise.all(a.map(async o=>{let l=o.commit.message.split(` + +`);return{message:l[0],author:{name:o.commit.author.name,email:o.commit.author.email},body:l.slice(1).join(` + +`),date:new Date(o.commit.committer.timestamp).toDateString(),diff:{changed:0,files:(await this.getFileChangesCount(o.commit.parent.first(),o.oid)).map(c=>({path:c.path,status:c.type,vaultPath:this.getRelativeVaultPath(c.path),hash:o.oid}))},hash:o.oid,refs:[]}}))}updateBasePath(r){return this.getRepo().dir=r,Promise.resolve()}async updateUpstreamBranch(r){let[n,i]=Qi(r),s=await this.branchInfo();await this.wrapFS(te.default.push({...this.getRepo(),remote:n,remoteRef:i})),await this.setConfig(`branch.${s.current}.merge`,`refs/heads/${i}`)}updateGitPath(r){return Promise.resolve()}async getFileChangesCount(r,n){return this.walkDifference({walkers:[te.default.TREE({ref:r}),te.default.TREE({ref:n})]})}async walkDifference({walkers:r,dir:n}){return await this.wrapFS(te.default.walk({...this.getRepo(),trees:r,map:async function(s,[a,o]){if(!Yw(s,n))return null;if(await(a==null?void 0:a.type())==="tree"||await(o==null?void 0:o.type())==="tree")return;let l=await(a==null?void 0:a.oid()),c=await(o==null?void 0:o.oid()),u="equal";if(l!==c&&(u="M"),l===void 0&&(u="A"),c===void 0&&(u="D"),l===void 0&&c===void 0&&(console.log("Something weird happened:"),console.log(a),console.log(o)),u!=="equal")return{path:s,type:u}}}))}async getStagedFiles(r="."){return(await this.walkDifference({walkers:[te.default.TREE({ref:"HEAD"}),te.default.STAGE()],dir:r})).map(i=>({vaultPath:this.getRelativeVaultPath(i.path),path:i.path}))}async getUnstagedFiles(r="."){let n,i=window.setTimeout(()=>{n=new Ra.Notice("This takes longer: Getting status",this.noticeLength)},2e4);try{let s=this.getRepo(),a=await this.wrapFS(te.default.walk({...s,trees:[te.default.WORKDIR(),te.default.STAGE()],map:async function(o,[l,c]){if(!c&&l&&await te.default.isIgnored({...s,filepath:o})||!Yw(o,r))return null;let[u,f]=await Promise.all([l&&l.type(),c&&c.type()]),d=[u,f].includes("blob");if((u==="tree"||u==="special")&&!d)return;if(f==="commit")return null;if((f==="tree"||f==="special")&&!d)return;let h=f==="blob"?await c.oid():void 0,m;return u==="blob"&&f!=="blob"?m="42":u==="blob"&&(m=await l.oid()),m?h?m!==h?{path:o,type:"M"}:null:{path:o,type:"A"}:{path:o,type:"D"}}}));return window.clearTimeout(i),n==null||n.hide(),a}catch(s){throw window.clearTimeout(i),n==null||n.hide(),this.plugin.displayError(s),s}}async getDiffString(r,n=!1,i){let s=this.getRelativeVaultPath(r),a=async(c,[u])=>{if(r==c){let f=await u.oid();return(await te.default.readBlob({...this.getRepo(),oid:f})).blob}};if(i){let c=await(0,te.readBlob)({...this.getRepo(),filepath:r,oid:i}).then(h=>new TextDecoder().decode(h.blob)).catch(h=>{if(!(h instanceof te.default.Errors.NotFoundError))throw h}),u=await te.default.readCommit({...this.getRepo(),oid:i}),f=await(0,te.readBlob)({...this.getRepo(),filepath:r,oid:u.commit.parent.first()}).then(h=>new TextDecoder().decode(h.blob)).catch(h=>{if(!(h instanceof te.default.Errors.NotFoundError))throw h});return mu(s,f!=null?f:"",c!=null?c:"")}let o=(await te.default.walk({...this.getRepo(),trees:[te.default.STAGE()],map:a})).first(),l=new TextDecoder().decode(o);if(n){let c=await this.resolveRef("HEAD").then(f=>(0,te.readBlob)({...this.getRepo(),filepath:r,oid:f})).then(f=>new TextDecoder().decode(f.blob)).catch(f=>{if(!(f instanceof te.default.Errors.NotFoundError))throw f});return mu(s,c!=null?c:"",l)}else{let c;return await this.app.vault.adapter.exists(s)?c=await this.app.vault.adapter.read(s):c="",mu(s,l,c)}}async getLastCommitTime(){let r=this.getRepo(),n=await this.resolveRef("HEAD"),s=(await te.default.readCommit({...r,oid:n})).commit.committer.timestamp;return new Date(s*1e3)}getFileStatusResult(r){let n=this.status_mapping[`${r[this.HEAD]}${r[this.WORKDIR]}${r[this.STAGE]}`];return{index:n[0]=="?"?"U":n[0],workingDir:n[1]=="?"?"U":n[1],path:r[this.FILE],vaultPath:this.getRelativeVaultPath(r[this.FILE])}}async checkAuthorInfo(){let r=await this.getConfig("user.name"),n=await this.getConfig("user.email");if(!r||!n)throw Error("Git author name and email are not set. Please set both fields in the settings.")}showNotice(r,n=!0){if(!this.plugin.settings.disablePopups)return new Ra.Notice(r,n?this.noticeLength:void 0)}};async function*xG(t){yield new Uint8Array(t)}async function SG(t){let e=new ReadableStream({async start(n){for await(let i of t)n.enqueue(i);n.close()}});return await new Response(e).arrayBuffer()}p();var nF=Ct(Ph()),Jr=Ct(require("fs/promises")),Ji=require("obsidian"),Ue=Ct(require("path")),Uu=require("path");p();var Bh=Ct(hR(),1);p();var Jw=new WeakMap;function Sl(...t){let e=new String(t);return Jw.set(e,t),e}function wn(t){return t instanceof String&&Jw.has(t)}function El(t){var e;return(e=Jw.get(t))!=null?e:[]}var Lh=Ct(Ph(),1),j$=require("child_process");var CI=Ct(t0(),1),NI=require("node:path");p();function*pR(t,e){let r=e==="global";for(let n of t)n.isGlobal===r&&(yield n)}var GG=new Set(["--add","--edit","--remove-section","--rename-section","--replace-all","--unset","--unset-all","-e"]),jG=new Set(["--get","--get-all","--get-color","--get-colorbool","--get-regexp","--get-urlmatch","--list","-l"]),qG=new Set(["edit","remove-section","rename-section","set","unset"]),WG=new Set(["get","get-color","get-colorbool","list"]);function zG(t,e){var n;for(let{name:i}of pR(t,"task")){if(GG.has(i))return kl(!0,e);if(jG.has(i))return kl(!1,e)}let r=(n=e.at(0))==null?void 0:n.toLowerCase();return r===void 0?null:qG.has(r)?kl(!0,e.slice(1)):WG.has(r)?kl(!1,e.slice(1)):e.length===1?kl(!1,e):kl(!0,e)}function kl(t=!1,e=[]){var n;let r=(n=e.at(0))==null?void 0:n.toLowerCase();return r===void 0?null:{isWrite:t,isRead:!t,key:r,value:e.at(1)}}function VG(t,e){return e.isWrite&&e.value!==void 0?{key:e.key,value:e.value,scope:t}:{key:e.key,scope:t}}function YG(t){let e=(t==null?void 0:t.indexOf("="))||-1;return!t||e<0?null:{key:t.slice(0,e).trim().toLowerCase(),value:t.slice(e+1)}}function XG(t){for(let{name:e}of pR(t,"task"))switch(e){case"--global":return"global";case"--system":return"system";case"--worktree":return"worktree";case"--local":return"local";case"--file":case"-f":return"file"}return"local"}function ZG({name:t}){if(t==="-c"||t==="--config")return"inline";if(t==="--config-env")return"env"}function*KG(t){for(let e of t){let r=ZG(e),n=r&&YG(e.value);n&&(yield{...n,scope:r})}}function QG(t,e,r){let n={read:[],write:[...KG(e)]};return t==="config"&&JG(n,XG(e),zG(e,r)),n}function JG(t,e,r){if(r===null)return;let n=VG(e,r);r.isWrite?t.write.push(n):t.read.push(n)}var mR={short:new Map([["c",!0]])},ej={short:new Map([["C",!0],["P",!1],["h",!1],["p",!1],["v",!1],...mR.short.entries()]),long:new Set(["attr-source","config-env","exec-path","git-dir","list-cmds","namespace","super-prefix","work-tree"])},tj={clone:{short:new Map([["b",!0],["j",!0],["l",!1],["n",!1],["o",!0],["q",!1],["s",!1],["u",!0]]),long:new Set(["branch","config","jobs","origin","upload-pack","u","template"])},commit:{short:new Map([["C",!0],["F",!0],["c",!0],["m",!0],["t",!0]]),long:new Set(["file","message","reedit-message","reuse-message","template"])},config:{short:new Map([["e",!1],["f",!0],["l",!1]]),long:new Set(["blob","comment","default","file","type","value"])},fetch:{short:new Map,long:new Set(["upload-pack"])},init:{short:new Map,long:new Set(["template"])},pull:{short:new Map,long:new Set(["upload-pack"])},push:{short:new Map,long:new Set(["exec","receive-pack"])}},rj={short:new Map,long:new Set};function nj(t){var r;let e=(r=tj[t!=null?t:""])!=null?r:rj;return{short:new Map([...mR.short.entries(),...e.short.entries()]),long:e.long}}function gR(t,e=ej){if(t.startsWith("--")){let r=t.indexOf("=");if(r>2)return[{name:t.slice(0,r),value:t.slice(r+1),needsNext:!1}];let n=t.slice(2);return[{name:t,needsNext:e.long.has(n)}]}if(t.length===2){let r=t.charAt(1),n=e.short.get(r);return[{name:t,needsNext:n===!0}]}return ij(t,e.short)}function ij(t,e){let r=t.slice(1).split(""),n=[];for(let i=0;ie.has(l)))return n.push({name:`-${s}`,value:o,needsNext:!1}),n}n.push({name:`-${s}`,needsNext:a})}return n}function sj(t,e=[]){let r=0;for(;rfunction(){return t&&(e=(0,t[S0(t)[0]])(t=0)),e},yj=(t,e)=>function(){return e||(0,t[S0(t)[0]])((e={exports:{}}).exports,e),e.exports},yt=(t,e)=>{for(var r in e)x0(t,r,{get:e[r],enumerable:!0})},bj=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of S0(e))!wj.call(t,i)&&i!==r&&x0(t,i,{get:()=>e[i],enumerable:!(n=vj(e,i))||n.enumerable});return t},pt=t=>bj(x0({},"__esModule",{value:!0}),t),Pr,zs=V({"src/lib/errors/git-error.ts"(){"use strict";Pr=class extends Error{constructor(t,e){super(e),this.task=t,Object.setPrototypeOf(this,new.target.prototype)}}}}),Du,Pl=V({"src/lib/errors/git-response-error.ts"(){"use strict";zs(),Du=class extends Pr{constructor(t,e){super(void 0,e||String(t)),this.git=t}}}}),QR,JR=V({"src/lib/errors/task-configuration-error.ts"(){"use strict";zs(),QR=class extends Pr{constructor(t){super(void 0,t)}}}});function e$(t){return typeof t!="function"?Da:t}function t$(t){return typeof t=="function"&&t!==Da}function r$(t,e){let r=t.indexOf(e);return r<=0?[t,""]:[t.substr(0,r),t.substr(r+1)]}function n$(t,e=0){return i$(t)&&t.length>e?t[e]:void 0}function Ma(t,e=0){if(i$(t)&&t.length>e)return t[t.length-1-e]}function i$(t){return jh(t)}function Lu(t="",e=!0,r=` +`){return t.split(r).reduce((n,i)=>{let s=e?i.trim():i;return s&&n.push(s),n},[])}function E0(t,e){return Lu(t,!0).map(r=>e(r))}function k0(t){return(0,Bh.exists)(t,Bh.FOLDER)}function _n(t,e){return Array.isArray(t)?t.includes(e)||t.push(e):t.add(e),e}function s$(t,e){return Array.isArray(t)&&!t.includes(e)&&t.push(e),t}function Hh(t,e){if(Array.isArray(t)){let r=t.indexOf(e);r>=0&&t.splice(r,1)}else t.delete(e);return e}function wi(t){return Array.isArray(t)?t:[t]}function a$(t){return t.replace(/[\s-]+(.)/g,(e,r)=>r.toUpperCase())}function Rl(t){return wi(t).map(e=>e instanceof String?e:String(e))}function We(t,e=0){if(t==null)return e;let r=parseInt(t,10);return Number.isNaN(r)?e:r}function Ou(t,e){let r=[];for(let n=0,i=t.length;n{t[n]!==void 0&&(r[n]=t[n])}),r}function l0(t=0){return new Promise(e=>setTimeout(e,t))}function c0(t){if(t!==!1)return t}var Cl,Da,Nu,Uh=V({"src/lib/utils/util.ts"(){"use strict";A0(),Cl="\0",Da=()=>{},Nu=Object.prototype.toString.call.bind(Object.prototype.toString)}});function Qt(t,e,r){return e(t)?t:arguments.length>2?r:void 0}function u0(t,e){let r=wn(t)?"string":typeof t;return/number|string|boolean/.test(r)&&(!e||!e.includes(r))}function Gh(t){return!!t&&Nu(t)==="[object Object]"}function l$(t){return typeof t=="function"}var Bu,c$,ct,Mh,jh,A0=V({"src/lib/utils/argument-filters.ts"(){"use strict";Uh(),Bu=t=>Array.isArray(t),c$=t=>typeof t=="number",ct=t=>typeof t=="string"||wn(t),Mh=t=>ct(t)||Array.isArray(t)&&t.every(ct),jh=t=>t==null||"number|boolean|function".includes(typeof t)?!1:typeof t.length=="number"}}),f0,_j=V({"src/lib/utils/exit-codes.ts"(){"use strict";f0=(t=>(t[t.SUCCESS=0]="SUCCESS",t[t.ERROR=1]="ERROR",t[t.NOT_FOUND=-2]="NOT_FOUND",t[t.UNCLEAN=128]="UNCLEAN",t))(f0||{})}}),Dh,xj=V({"src/lib/utils/git-output-streams.ts"(){"use strict";Dh=class u${constructor(e,r){this.stdOut=e,this.stdErr=r}asStrings(){return new u$(this.stdOut.toString("utf8"),this.stdErr.toString("utf8"))}}}});function Sj(){throw new Error("LineParser:useMatches not implemented")}var pe,Ws,Ej=V({"src/lib/utils/line-parser.ts"(){"use strict";pe=class{constructor(t,e){this.matches=[],this.useMatches=Sj,this.parse=(r,n)=>(this.resetMatches(),this._regExp.every((i,s)=>this.addMatch(i,s,r(s)))?this.useMatches(n,this.prepareMatches())!==!1:!1),this._regExp=Array.isArray(t)?t:[t],e&&(this.useMatches=e)}resetMatches(){this.matches.length=0}prepareMatches(){return this.matches}addMatch(t,e,r){let n=r&&t.exec(r);return n&&this.pushMatch(e,n),!!n}pushMatch(t,e){this.matches.push(...e.slice(1))}},Ws=class extends pe{addMatch(t,e,r){return/^remote:\s/.test(String(r))&&super.addMatch(t,e,r)}pushMatch(t,e){(t>0||e.length>1)&&super.pushMatch(t,e)}}}});function f$(...t){let e=process.cwd(),r=Object.assign({baseDir:e,...d$},...t.filter(n=>typeof n=="object"&&n));return r.baseDir=r.baseDir||e,r.trimmed=r.trimmed===!0,r}var d$,kj=V({"src/lib/utils/simple-git-options.ts"(){"use strict";d$={binary:"git",maxConcurrentProcesses:5,config:[],trimmed:!1}}});function C0(t,e=[]){return Gh(t)?Object.keys(t).reduce((r,n)=>{let i=t[n];if(wn(i))r.push(i);else if(u0(i,["boolean"]))r.push(n+"="+i);else if(Array.isArray(i))for(let s of i)u0(s,["string","number"])||r.push(n+"="+s);else r.push(n);return r},e):e}function hr(t,e=0,r=!1){let n=[];for(let i=0,s=e<0?t.length:e;i{for(let s=Lu(i,n),a=0,o=s.length;a{if(!(a+c>=o))return s[a+c]};e.some(({parse:c})=>c(l,t))}}),t}var Tj=V({"src/lib/utils/task-parser.ts"(){"use strict";Uh()}}),h$={};yt(h$,{ExitCodes:()=>f0,GitOutputStreams:()=>Dh,LineParser:()=>pe,NOOP:()=>Da,NULL:()=>Cl,RemoteLineParser:()=>Ws,append:()=>_n,appendTaskOptions:()=>C0,asArray:()=>wi,asCamelCase:()=>a$,asFunction:()=>e$,asNumber:()=>We,asStringArray:()=>Rl,bufferToString:()=>Mu,callTaskParser:()=>d0,createInstanceConfig:()=>f$,delay:()=>l0,filterArray:()=>Bu,filterFunction:()=>l$,filterHasLength:()=>jh,filterNumber:()=>c$,filterPlainObject:()=>Gh,filterPrimitives:()=>u0,filterString:()=>ct,filterStringOrStringArray:()=>Mh,filterType:()=>Qt,first:()=>n$,folderExists:()=>k0,forEachLineWithContent:()=>E0,getTrailingOptions:()=>hr,including:()=>s$,isUserFunction:()=>t$,last:()=>Ma,objectToString:()=>Nu,orVoid:()=>c0,parseStringResponse:()=>Rr,pick:()=>o$,prefixedArray:()=>Ou,remove:()=>Hh,splitOn:()=>r$,toLinesWithContent:()=>Lu,trailingFunctionArgument:()=>tt,trailingOptionsArgument:()=>T0});var ue=V({"src/lib/utils/index.ts"(){"use strict";A0(),_j(),xj(),Ej(),kj(),Cj(),Tj(),Uh()}}),p$={};yt(p$,{CheckRepoActions:()=>h0,checkIsBareRepoTask:()=>g$,checkIsRepoRootTask:()=>m$,checkIsRepoTask:()=>Pj});function Pj(t){switch(t){case"bare":return g$();case"root":return m$()}return{commands:["rev-parse","--is-inside-work-tree"],format:"utf-8",onError:qh,parser:P0}}function m$(){return{commands:["rev-parse","--git-dir"],format:"utf-8",onError:qh,parser(e){return/^\.(git)?$/.test(e.trim())}}}function g$(){return{commands:["rev-parse","--is-bare-repository"],format:"utf-8",onError:qh,parser:P0}}function Rj(t){return/(Not a git repository|Kein Git-Repository)/i.test(String(t))}var h0,qh,P0,v$=V({"src/lib/tasks/check-is-repo.ts"(){"use strict";ue(),h0=(t=>(t.BARE="bare",t.IN_TREE="tree",t.IS_REPO_ROOT="root",t))(h0||{}),qh=({exitCode:t},e,r,n)=>{if(t===128&&Rj(e))return r(Buffer.from("false"));n(e)},P0=t=>t.trim()==="true"}});function $j(t,e){let r=new w$(t),n=t?b$:y$;return Lu(e).forEach(i=>{let s=i.replace(n,"");r.paths.push(s),(_$.test(s)?r.folders:r.files).push(s)}),r}var w$,y$,b$,_$,Ij=V({"src/lib/responses/CleanSummary.ts"(){"use strict";ue(),w$=class{constructor(t){this.dryRun=t,this.paths=[],this.files=[],this.folders=[]}},y$=/^[a-z]+\s*/i,b$=/^[a-z]+\s+[a-z]+\s*/i,_$=/\/$/}}),p0={};yt(p0,{EMPTY_COMMANDS:()=>Wh,adhocExecTask:()=>x$,configurationErrorTask:()=>Tr,isBufferTask:()=>E$,isEmptyTask:()=>k$,straightThroughBufferTask:()=>S$,straightThroughStringTask:()=>pr});function x$(t){return{commands:Wh,format:"empty",parser:t}}function Tr(t){return{commands:Wh,format:"empty",parser(){throw typeof t=="string"?new QR(t):t}}}function pr(t,e=!1){return{commands:t,format:"utf-8",parser(r){return e?String(r).trim():r}}}function S$(t){return{commands:t,format:"buffer",parser(e){return e}}}function E$(t){return t.format==="buffer"}function k$(t){return t.format==="empty"||!t.commands.length}var Wh,mt=V({"src/lib/tasks/task.ts"(){"use strict";JR(),Wh=[]}}),A$={};yt(A$,{CONFIG_ERROR_INTERACTIVE_MODE:()=>R0,CONFIG_ERROR_MODE_REQUIRED:()=>$0,CONFIG_ERROR_UNKNOWN_OPTION:()=>I0,CleanOptions:()=>Oa,cleanTask:()=>C$,cleanWithOptionsTask:()=>Fj,isCleanOptionsArray:()=>Oj});function Fj(t,e){let{cleanMode:r,options:n,valid:i}=Mj(t);return r?i.options?(n.push(...e),n.some(Nj)?Tr(R0):C$(r,n)):Tr(I0+JSON.stringify(t)):Tr($0)}function C$(t,e){return{commands:["clean",`-${t}`,...e],format:"utf-8",parser(n){return $j(t==="n",n)}}}function Oj(t){return Array.isArray(t)&&t.every(e=>F0.has(e))}function Mj(t){let e,r=[],n={cleanMode:!1,options:!0};return t.replace(/[^a-z]i/g,"").split("").forEach(i=>{Dj(i)?(e=i,n.cleanMode=!0):n.options=n.options&&Lj(r[r.length]=`-${i}`)}),{cleanMode:e,options:r,valid:n}}function Dj(t){return t==="f"||t==="n"}function Lj(t){return/^-[a-z]$/i.test(t)&&F0.has(t.charAt(1))}function Nj(t){return/^-[^\-]/.test(t)?t.indexOf("i")>0:t==="--interactive"}var R0,$0,I0,Oa,F0,T$=V({"src/lib/tasks/clean.ts"(){"use strict";Ij(),ue(),mt(),R0="Git clean interactive mode is not supported",$0='Git clean mode parameter ("n" or "f") is required',I0="Git clean unknown option found in: ",Oa=(t=>(t.DRY_RUN="n",t.FORCE="f",t.IGNORED_INCLUDED="x",t.IGNORED_ONLY="X",t.EXCLUDING="e",t.QUIET="q",t.RECURSIVE="d",t))(Oa||{}),F0=new Set(["i",...Rl(Object.values(Oa))])}});function Bj(t){let e=new R$;for(let r of P$(t))e.addValue(r.file,String(r.key),r.value);return e}function Hj(t,e){let r=null,n=[],i=new Map;for(let s of P$(t,e))s.key===e&&(n.push(r=s.value),i.has(s.file)||i.set(s.file,[]),i.get(s.file).push(r));return{key:e,paths:Array.from(i.keys()),scopes:i,value:r,values:n}}function Uj(t){return t.replace(/^(file):/,"")}function*P$(t,e=null){let r=t.split("\0");for(let n=0,i=r.length-1;nObject.assign(t,this.values[e]),{})),this._all}addFile(t){if(!(t in this.values)){let e=Ma(this.files);this.values[t]=e?Object.create(this.values[e]):{},this.files.push(t)}return this.values[t]}addValue(t,e,r){let n=this.addFile(t);Object.hasOwn(n,e)?Array.isArray(n[e])?n[e].push(r):n[e]=[n[e],r]:n[e]=r,this._all=void 0}}}});function r0(t,e){return typeof t=="string"&&Object.hasOwn(m0,t)?t:e}function jj(t,e,r,n){let i=["config",`--${n}`];return r&&i.push("--add"),i.push(t,e),{commands:i,format:"utf-8",parser(s){return s}}}function qj(t,e){let r=["config","--null","--show-origin","--get-all",t];return e&&r.splice(1,0,`--${e}`),{commands:r,format:"utf-8",parser(n){return Hj(n,t)}}}function Wj(t){let e=["config","--list","--show-origin","--null"];return t&&e.push(`--${t}`),{commands:e,format:"utf-8",parser(r){return Bj(r)}}}function zj(){return{addConfig(t,e,...r){return this._runTask(jj(t,e,r[0]===!0,r0(r[1],"local")),tt(arguments))},getConfig(t,e){return this._runTask(qj(t,r0(e,void 0)),tt(arguments))},listConfig(...t){return this._runTask(Wj(r0(t[0],void 0)),tt(arguments))}}}var m0,$$=V({"src/lib/tasks/config.ts"(){"use strict";Gj(),ue(),m0=(t=>(t.system="system",t.global="global",t.local="local",t.worktree="worktree",t))(m0||{})}});function Vj(t){return I$.has(t)}var n0,I$,F$=V({"src/lib/tasks/diff-name-status.ts"(){"use strict";n0=(t=>(t.ADDED="A",t.COPIED="C",t.DELETED="D",t.MODIFIED="M",t.RENAMED="R",t.CHANGED="T",t.UNMERGED="U",t.UNKNOWN="X",t.BROKEN="B",t))(n0||{}),I$=new Set(Object.values(n0))}});function Yj(...t){return new M$().param(...t)}function Xj(t){let e=new Set,r={};return E0(t,n=>{let[i,s,a]=n.split(Cl);e.add(i),(r[i]=r[i]||[]).push({line:We(s),path:i,preview:a})}),{paths:e,results:r}}function Zj(){return{grep(t){let e=tt(arguments),r=hr(arguments);for(let i of O$)if(r.includes(i))return this._runTask(Tr(`git.grep: use of "${i}" is not supported.`),e);typeof t=="string"&&(t=Yj().param(t));let n=["grep","--null","-n","--full-name",...r,...t];return this._runTask({commands:n,format:"utf-8",parser(i){return Xj(i)}},e)}}}var O$,Fu,_R,M$,D$=V({"src/lib/tasks/grep.ts"(){"use strict";ue(),mt(),O$=["-h"],Fu=Symbol("grepQuery"),M$=class{constructor(){this[_R]=[]}*[(_R=Fu,Symbol.iterator)](){for(let t of this[Fu])yield t}and(...t){return t.length&&this[Fu].push("--and","(",...Ou(t,"-e"),")"),this}param(...t){return this[Fu].push(...Ou(t,"-e")),this}}}}),L$={};yt(L$,{ResetMode:()=>Ih,getResetMode:()=>Qj,resetTask:()=>Kj});function Kj(t,e){let r=["reset"];return N$(t)&&r.push(`--${t}`),r.push(...e),pr(r)}function Qj(t){if(N$(t))return t;switch(typeof t){case"string":case"undefined":return"soft"}}function N$(t){return typeof t=="string"&&B$.includes(t)}var Ih,B$,H$=V({"src/lib/tasks/reset.ts"(){"use strict";ue(),mt(),Ih=(t=>(t.MIXED="mixed",t.SOFT="soft",t.HARD="hard",t.MERGE="merge",t.KEEP="keep",t))(Ih||{}),B$=Rl(Object.values(Ih))}});function Jj(){return(0,Lh.default)("simple-git")}function xR(t,e,r){return!e||!String(e).replace(/\s*/,"")?r?(n,...i)=>{t(n,...i),r(n,...i)}:t:(n,...i)=>{t(`%s ${n}`,e,...i),r&&r(n,...i)}}function eq(t,e,{namespace:r}){if(typeof t=="string")return t;let n=e&&e.namespace||"";return n.startsWith(r)?n.substr(r.length+1):n||r}function O0(t,e,r,n=Jj()){let i=t&&`[${t}]`||"",s=[],a=typeof e=="string"?n.extend(e):e,o=eq(Qt(e,ct),a,n);return c(r);function l(u,f){return _n(s,O0(t,o.replace(/^[^:]+/,u),f,n))}function c(u){let f=u&&`[${u}]`||"",d=a&&xR(a,f)||Da,h=xR(n,`${i} ${f}`,d);return Object.assign(a?d:h,{label:t,sibling:l,info:h,step:c})}}var U$=V({"src/lib/git-logger.ts"(){"use strict";ue(),Lh.default.formatters.L=t=>String(jh(t)?t.length:"-"),Lh.default.formatters.B=t=>Buffer.isBuffer(t)?t.toString("utf8"):Nu(t)}}),G$,tq=V({"src/lib/runners/tasks-pending-queue.ts"(){"use strict";var t;zs(),U$(),G$=(t=class{constructor(r="GitExecutor"){this.logLabel=r,this._queue=new Map}withProgress(r){return this._queue.get(r)}createProgress(r){let n=t.getName(r.commands[0]),i=O0(this.logLabel,n);return{task:r,logger:i,name:n}}push(r){let n=this.createProgress(r);return n.logger("Adding task to the queue, commands = %o",r.commands),this._queue.set(r,n),n}fatal(r){for(let[n,{logger:i}]of Array.from(this._queue.entries()))n===r.task?(i.info("Failed %o",r),i("Fatal exception, any as-yet un-started tasks run through this executor will not be attempted")):i.info("A fatal exception occurred in a previous task, the queue has been purged: %o",r.message),this.complete(n);if(this._queue.size!==0)throw new Error(`Queue size should be zero after fatal: ${this._queue.size}`)}complete(r){this.withProgress(r)&&this._queue.delete(r)}attempt(r){let n=this.withProgress(r);if(!n)throw new Pr(void 0,"TasksPendingQueue: attempt called for an unknown task");return n.logger("Starting task"),n}static getName(r="empty"){return`task:${r}:${++t.counter}`}},t.counter=0,t)}});function Fa(t,e){return{method:n$(t.commands)||"",commands:e}}function rq(t,e){return r=>{e("[ERROR] child process exception %o",r),t.push(Buffer.from(String(r.stack),"ascii"))}}function SR(t,e,r,n){return i=>{r("%s received %L bytes",e,i),n("%B",i),t.push(i)}}var g0,nq=V({"src/lib/runners/git-executor-chain.ts"(){"use strict";zs(),mt(),ue(),tq(),g0=class{constructor(t,e,r){this._executor=t,this._scheduler=e,this._plugins=r,this._chain=Promise.resolve(),this._queue=new G$}get cwd(){return this._cwd||this._executor.cwd}set cwd(t){this._cwd=t}get env(){return this._executor.env}get outputHandler(){return this._executor.outputHandler}chain(){return this}push(t){return this._queue.push(t),this._chain=this._chain.then(()=>this.attemptTask(t))}async attemptTask(t){let e=await this._scheduler.next(),r=()=>this._queue.complete(t);try{let{logger:n}=this._queue.attempt(t);return await(k$(t)?this.attemptEmptyTask(t,n):this.attemptRemoteTask(t,n))}catch(n){throw this.onFatalException(t,n)}finally{r(),e()}}onFatalException(t,e){let r=e instanceof Pr?Object.assign(e,{task:t}):new Pr(t,e&&String(e));return this._chain=Promise.resolve(),this._queue.fatal(r),r}async attemptRemoteTask(t,e){let r=this._plugins.exec("spawn.binary","",Fa(t,t.commands)),n=this._plugins.exec("spawn.args",[...t.commands],{...Fa(t,t.commands),env:{...this.env}}),i=await this.gitResponse(t,r,n,this.outputHandler,e.step("SPAWN")),s=await this.handleTaskData(t,n,i,e.step("HANDLE"));return e("passing response to task's parser as a %s",t.format),E$(t)?d0(t.parser,s):d0(t.parser,s.asStrings())}async attemptEmptyTask(t,e){return e("empty task bypassing child process to call to task's parser"),t.parser(this)}handleTaskData(t,e,r,n){let{exitCode:i,rejection:s,stdOut:a,stdErr:o}=r;return new Promise((l,c)=>{n("Preparing to handle process response exitCode=%d stdOut=",i);let{error:u}=this._plugins.exec("task.error",{error:s},{...Fa(t,e),...r});if(u&&t.onError)return n.info("exitCode=%s handling with custom error handler"),t.onError(r,u,f=>{n.info("custom error handler treated as success"),n("custom error returned a %s",Nu(f)),l(new Dh(Array.isArray(f)?Buffer.concat(f):f,Buffer.concat(o)))},c);if(u)return n.info("handling as error: exitCode=%s stdErr=%s rejection=%o",i,o.length,s),c(u);n.info("retrieving task output complete"),l(new Dh(Buffer.concat(a),Buffer.concat(o)))})}async gitResponse(t,e,r,n,i){let s=i.sibling("output"),a=this._plugins.exec("spawn.options",{cwd:this.cwd,env:this.env,windowsHide:!0},Fa(t,t.commands));return new Promise(o=>{let l=[],c=[];i.info("%s %o",e,r),i("%O",a);let u=this._beforeSpawn(t,r);if(u)return o({stdOut:l,stdErr:c,exitCode:9901,rejection:u});this._plugins.exec("spawn.before",void 0,{...Fa(t,r),kill(d){u=d||u}});let f=(0,j$.spawn)(e,r,a);f.stdout.on("data",SR(l,"stdOut",i,s.step("stdOut"))),f.stderr.on("data",SR(c,"stdErr",i,s.step("stdErr"))),f.on("error",rq(c,i)),n&&(i("Passing child process stdOut/stdErr to custom outputHandler"),n(e,f.stdout,f.stderr,[...r])),this._plugins.exec("spawn.after",void 0,{...Fa(t,r),spawned:f,close(d,h){o({stdOut:l,stdErr:c,exitCode:d,rejection:u||h})},kill(d){f.killed||(u=d,f.kill("SIGINT"))}})})}_beforeSpawn(t,e){let r;return this._plugins.exec("spawn.before",void 0,{...Fa(t,e),kill(n){r=n||r}}),r}}}}),q$={};yt(q$,{GitExecutor:()=>W$});var W$,iq=V({"src/lib/runners/git-executor.ts"(){"use strict";nq(),W$=class{constructor(t,e,r){this.cwd=t,this._scheduler=e,this._plugins=r,this._chain=new g0(this,this._scheduler,this._plugins)}chain(){return new g0(this,this._scheduler,this._plugins)}push(t){return this._chain.push(t)}}}});function sq(t,e,r=Da){let n=s=>{r(null,s)},i=s=>{(s==null?void 0:s.task)===t&&r(s instanceof Du?aq(s):s,void 0)};e.then(n,i)}function aq(t){let e=n=>{console.warn(`simple-git deprecation notice: accessing GitResponseError.${n} should be GitResponseError.git.${n}, this will no longer be available in version 3`),e=Da};return Object.create(t,Object.getOwnPropertyNames(t.git).reduce(r,{}));function r(n,i){return i in t||(n[i]={enumerable:!1,configurable:!1,get(){return e(i),t.git[i]}}),n}}var oq=V({"src/lib/task-callback.ts"(){"use strict";Pl(),ue()}});function ER(t,e){return x$(r=>{if(!k0(t))throw new Error(`Git.cwd: cannot change to non-directory "${t}"`);return(e||r).cwd=t})}var lq=V({"src/lib/tasks/change-working-directory.ts"(){"use strict";ue(),mt()}});function i0(t){let e=["checkout",...t];return e[1]==="-b"&&e.includes("-B")&&(e[1]=Hh(e,"-B")),pr(e)}function cq(){return{checkout(){return this._runTask(i0(hr(arguments,1)),tt(arguments))},checkoutBranch(t,e){return this._runTask(i0(["-b",t,e,...hr(arguments)]),tt(arguments))},checkoutLocalBranch(t){return this._runTask(i0(["-b",t,...hr(arguments)]),tt(arguments))}}}var uq=V({"src/lib/tasks/checkout.ts"(){"use strict";ue(),mt()}});function fq(){return{count:0,garbage:0,inPack:0,packs:0,prunePackable:0,size:0,sizeGarbage:0,sizePack:0}}function dq(){return{countObjects(){return this._runTask({commands:["count-objects","--verbose"],format:"utf-8",parser(t){return Rr(fq(),[z$],t)}})}}}var z$,hq=V({"src/lib/tasks/count-objects.ts"(){"use strict";ue(),z$=new pe(/([a-z-]+): (\d+)$/,(t,[e,r])=>{let n=a$(e);Object.hasOwn(t,n)&&(t[n]=We(r))})}});function pq(t){return Rr({author:null,branch:"",commit:"",root:!1,summary:{changes:0,insertions:0,deletions:0}},V$,t)}var V$,mq=V({"src/lib/parsers/parse-commit.ts"(){"use strict";ue(),V$=[new pe(/^\[([^\s]+)( \([^)]+\))? ([^\]]+)/,(t,[e,r,n])=>{t.branch=e,t.commit=n,t.root=!!r}),new pe(/\s*Author:\s(.+)/i,(t,[e])=>{let r=e.split("<"),n=r.pop();!n||!n.includes("@")||(t.author={email:n.substr(0,n.length-1),name:r.join("<").trim()})}),new pe(/(\d+)[^,]*(?:,\s*(\d+)[^,]*)(?:,\s*(\d+))/g,(t,[e,r,n])=>{t.summary.changes=parseInt(e,10)||0,t.summary.insertions=parseInt(r,10)||0,t.summary.deletions=parseInt(n,10)||0}),new pe(/^(\d+)[^,]*(?:,\s*(\d+)[^(]+\(([+-]))?/,(t,[e,r,n])=>{t.summary.changes=parseInt(e,10)||0;let i=parseInt(r,10)||0;n==="-"?t.summary.deletions=i:n==="+"&&(t.summary.insertions=i)})]}});function gq(t,e,r){return{commands:["-c","core.abbrev=40","commit",...Ou(t,"-m"),...e,...r],format:"utf-8",parser:pq}}function vq(){return{commit(e,...r){let n=tt(arguments),i=t(e)||gq(wi(e),wi(Qt(r[0],Mh,[])),[...Rl(Qt(r[1],Bu,[])),...hr(arguments,0,!0)]);return this._runTask(i,n)}};function t(e){return!Mh(e)&&Tr("git.commit: requires the commit message to be supplied as a string/string[]")}}var wq=V({"src/lib/tasks/commit.ts"(){"use strict";mq(),ue(),mt()}});function yq(){return{firstCommit(){return this._runTask(pr(["rev-list","--max-parents=0","HEAD"],!0),tt(arguments))}}}var bq=V({"src/lib/tasks/first-commit.ts"(){"use strict";ue(),mt()}});function _q(t,e){let r=["hash-object",t];return e&&r.push("-w"),pr(r,!0)}var xq=V({"src/lib/tasks/hash-object.ts"(){"use strict";mt()}});function Sq(t,e,r){let n=String(r).trim(),i;if(i=Y$.exec(n))return new Fh(t,e,!1,i[1]);if(i=X$.exec(n))return new Fh(t,e,!0,i[1]);let s="",a=n.split(" ");for(;a.length;)if(a.shift()==="in"){s=a.join(" ");break}return new Fh(t,e,/^re/i.test(n),s)}var Fh,Y$,X$,Eq=V({"src/lib/responses/InitSummary.ts"(){"use strict";Fh=class{constructor(t,e,r,n){this.bare=t,this.path=e,this.existing=r,this.gitDir=n}},Y$=/^Init.+ repository in (.+)$/,X$=/^Rein.+ in (.+)$/}});function kq(t){return t.includes(M0)}function Aq(t=!1,e,r){let n=["init",...r];return t&&!kq(n)&&n.splice(1,0,M0),{commands:n,format:"utf-8",parser(i){return Sq(n.includes("--bare"),e,i)}}}var M0,Cq=V({"src/lib/tasks/init.ts"(){"use strict";Eq(),M0="--bare"}});function D0(t){for(let e=0;eRr(new Z$,e,r,!1)}var s0,kR,AR,CR,Q$,J$=V({"src/lib/parsers/parse-diff-summary.ts"(){"use strict";Hu(),Pq(),F$(),ue(),s0=[new pe(/^(.+)\s+\|\s+(\d+)(\s+[+\-]+)?$/,(t,[e,r,n=""])=>{t.files.push({file:e.trim(),changes:We(r),insertions:n.replace(/[^+]/g,"").length,deletions:n.replace(/[^-]/g,"").length,binary:!1})}),new pe(/^(.+) \|\s+Bin ([0-9.]+) -> ([0-9.]+) ([a-z]+)/,(t,[e,r,n])=>{t.files.push({file:e.trim(),before:We(r),after:We(n),binary:!0})}),new pe(/(\d+) files? changed\s*((?:, \d+ [^,]+){0,2})/,(t,[e,r])=>{let n=/(\d+) i/.exec(r),i=/(\d+) d/.exec(r);t.changed=We(e),t.insertions=We(n==null?void 0:n[1]),t.deletions=We(i==null?void 0:i[1])})],kR=[new pe(/(\d+)\t(\d+)\t(.+)$/,(t,[e,r,n])=>{let i=We(e),s=We(r);t.changed++,t.insertions+=i,t.deletions+=s,t.files.push({file:n,changes:i+s,insertions:i,deletions:s,binary:!1})}),new pe(/-\t-\t(.+)$/,(t,[e])=>{t.changed++,t.files.push({file:e,after:0,before:0,binary:!0})})],AR=[new pe(/(.+)$/,(t,[e])=>{t.changed++,t.files.push({file:e,changes:0,insertions:0,deletions:0,binary:!1})})],CR=[new pe(/([ACDMRTUXB])([0-9]{0,3})\t(.[^\t]*)(\t(.[^\t]*))?$/,(t,[e,r,n,i,s])=>{t.changed++,t.files.push({file:s!=null?s:n,changes:0,insertions:0,deletions:0,binary:!1,status:c0(Vj(e)&&e),from:c0(!!s&&n!==s&&n),similarity:We(r)})})],Q$={"":s0,"--stat":s0,"--numstat":kR,"--name-status":CR,"--name-only":AR}}});function Rq(t,e){return e.reduce((r,n,i)=>(r[n]=t[i]||"",r),Object.create({diff:null}))}function eI(t=H0,e=tI,r=""){let n=K$(r);return function(i){let s=Lu(i.trim(),!1,N0).map(function(a){let o=a.split(B0),l=Rq(o[0].split(t),e);return o.length>1&&o[1].trim()&&(l.diff=n(o[1])),l});return{all:s,latest:s.length&&s[0]||null,total:s.length}}}var N0,B0,H0,tI,rI=V({"src/lib/parsers/parse-list-log-summary.ts"(){"use strict";ue(),J$(),Hu(),N0="\xF2\xF2\xF2\xF2\xF2\xF2 ",B0=" \xF2\xF2",H0=" \xF2 ",tI=["hash","date","message","refs","author_name","author_email"]}}),nI={};yt(nI,{diffSummaryTask:()=>$q,validateLogFormatConfig:()=>zh});function $q(t){let e=D0(t),r=["diff"];return e===""&&(e="--stat",r.push("--stat=4096")),r.push(...t),zh(r)||{commands:r,format:"utf-8",parser:K$(e)}}function zh(t){let e=t.filter(Tq);if(e.length>1)return Tr(`Summary flags are mutually exclusive - pick one of ${e.join(",")}`);if(e.length&&t.includes("-z"))return Tr(`Summary flag ${e} parsing is not compatible with null termination option '-z'`)}var U0=V({"src/lib/tasks/diff.ts"(){"use strict";Hu(),J$(),mt()}});function Iq(t,e){let r=[],n=[];return Object.keys(t).forEach(i=>{r.push(i),n.push(String(t[i]))}),[r,n.join(e)]}function Fq(t){return Object.keys(t).reduce((e,r)=>(r in v0||(e[r]=t[r]),e),{})}function iI(t={},e=[]){let r=Qt(t.splitter,ct,H0),n=Gh(t.format)?t.format:{hash:"%H",date:t.strictDate===!1?"%ai":"%aI",message:"%s",refs:"%D",body:t.multiLine?"%B":"%b",author_name:t.mailMap!==!1?"%aN":"%an",author_email:t.mailMap!==!1?"%aE":"%ae"},[i,s]=Iq(n,r),a=[],o=[`--pretty=format:${N0}${s}${B0}`,...e],l=t.n||t["max-count"]||t.maxCount;if(l&&o.push(`--max-count=${l}`),t.from||t.to){let c=t.symmetric!==!1?"...":"..";a.push(`${t.from||""}${c}${t.to||""}`)}return ct(t.file)&&o.push("--follow",Sl(t.file)),C0(Fq(t),o),{fields:i,splitter:r,commands:[...o,...a]}}function Oq(t,e,r){let n=eI(t,e,D0(r));return{commands:["log",...r],format:"utf-8",parser:n}}function Mq(){return{log(...r){let n=tt(arguments),i=iI(T0(arguments),Rl(Qt(arguments[0],Bu,[]))),s=e(...r)||zh(i.commands)||t(i);return this._runTask(s,n)}};function t(r){return Oq(r.splitter,r.fields,r.commands)}function e(r,n){return ct(r)&&ct(n)&&Tr("git.log(string, string) should be replaced with git.log({ from: string, to: string })")}}var v0,sI=V({"src/lib/tasks/log.ts"(){"use strict";Hu(),rI(),ue(),mt(),U0(),v0=(t=>(t[t["--pretty"]=0]="--pretty",t[t["max-count"]=1]="max-count",t[t.maxCount=2]="maxCount",t[t.n=3]="n",t[t.file=4]="file",t[t.format=5]="format",t[t.from=6]="from",t[t.to=7]="to",t[t.splitter=8]="splitter",t[t.symmetric=9]="symmetric",t[t.mailMap=10]="mailMap",t[t.multiLine=11]="multiLine",t[t.strictDate=12]="strictDate",t))(v0||{})}}),Oh,aI,Dq=V({"src/lib/responses/MergeSummary.ts"(){"use strict";Oh=class{constructor(t,e=null,r){this.reason=t,this.file=e,this.meta=r}toString(){return`${this.file}:${this.reason}`}},aI=class{constructor(){this.conflicts=[],this.merges=[],this.result="success"}get failed(){return this.conflicts.length>0}get reason(){return this.result}toString(){return this.conflicts.length?`CONFLICTS: ${this.conflicts.join(", ")}`:"OK"}}}}),w0,oI,Lq=V({"src/lib/responses/PullSummary.ts"(){"use strict";w0=class{constructor(){this.remoteMessages={all:[]},this.created=[],this.deleted=[],this.files=[],this.deletions={},this.insertions={},this.summary={changes:0,deletions:0,insertions:0}}},oI=class{constructor(){this.remote="",this.hash={local:"",remote:""},this.branch={local:"",remote:""},this.message=""}toString(){return this.message}}}});function a0(t){return t.objects=t.objects||{compressing:0,counting:0,enumerating:0,packReused:0,reused:{count:0,delta:0},total:{count:0,delta:0}}}function TR(t){let e=/^\s*(\d+)/.exec(t),r=/delta (\d+)/i.exec(t);return{count:We(e&&e[1]||"0"),delta:We(r&&r[1]||"0")}}var lI,Nq=V({"src/lib/parsers/parse-remote-objects.ts"(){"use strict";ue(),lI=[new Ws(/^remote:\s*(enumerating|counting|compressing) objects: (\d+),/i,(t,[e,r])=>{let n=e.toLowerCase(),i=a0(t.remoteMessages);Object.assign(i,{[n]:We(r)})}),new Ws(/^remote:\s*(enumerating|counting|compressing) objects: \d+% \(\d+\/(\d+)\),/i,(t,[e,r])=>{let n=e.toLowerCase(),i=a0(t.remoteMessages);Object.assign(i,{[n]:We(r)})}),new Ws(/total ([^,]+), reused ([^,]+), pack-reused (\d+)/i,(t,[e,r,n])=>{let i=a0(t.remoteMessages);i.total=TR(e),i.reused=TR(r),i.packReused=We(n)})]}});function cI(t,e){return Rr({remoteMessages:new fI},uI,e)}var uI,fI,dI=V({"src/lib/parsers/parse-remote-messages.ts"(){"use strict";ue(),Nq(),uI=[new Ws(/^remote:\s*(.+)$/,(t,[e])=>(t.remoteMessages.all.push(e.trim()),!1)),...lI,new Ws([/create a (?:pull|merge) request/i,/\s(https?:\/\/\S+)$/],(t,[e])=>{t.remoteMessages.pullRequestUrl=e}),new Ws([/found (\d+) vulnerabilities.+\(([^)]+)\)/i,/\s(https?:\/\/\S+)$/],(t,[e,r,n])=>{t.remoteMessages.vulnerabilities={count:We(e),summary:r,url:n}})],fI=class{constructor(){this.all=[]}}}});function Bq(t,e){let r=Rr(new oI,hI,[t,e]);return r.message&&r}var PR,RR,$R,IR,hI,FR,G0,pI=V({"src/lib/parsers/parse-pull.ts"(){"use strict";Lq(),ue(),dI(),PR=/^\s*(.+?)\s+\|\s+\d+\s*(\+*)(-*)/,RR=/(\d+)\D+((\d+)\D+\(\+\))?(\D+(\d+)\D+\(-\))?/,$R=/^(create|delete) mode \d+ (.+)/,IR=[new pe(PR,(t,[e,r,n])=>{t.files.push(e),r&&(t.insertions[e]=r.length),n&&(t.deletions[e]=n.length)}),new pe(RR,(t,[e,,r,,n])=>r!==void 0||n!==void 0?(t.summary.changes=+e||0,t.summary.insertions=+r||0,t.summary.deletions=+n||0,!0):!1),new pe($R,(t,[e,r])=>{_n(t.files,r),_n(e==="create"?t.created:t.deleted,r)})],hI=[new pe(/^from\s(.+)$/i,(t,[e])=>void(t.remote=e)),new pe(/^fatal:\s(.+)$/,(t,[e])=>void(t.message=e)),new pe(/([a-z0-9]+)\.\.([a-z0-9]+)\s+(\S+)\s+->\s+(\S+)$/,(t,[e,r,n,i])=>{t.branch.local=n,t.hash.local=e,t.branch.remote=i,t.hash.remote=r})],FR=(t,e)=>Rr(new w0,IR,[t,e]),G0=(t,e)=>Object.assign(new w0,FR(t,e),cI(t,e))}}),OR,mI,MR,Hq=V({"src/lib/parsers/parse-merge.ts"(){"use strict";Dq(),ue(),pI(),OR=[new pe(/^Auto-merging\s+(.+)$/,(t,[e])=>{t.merges.push(e)}),new pe(/^CONFLICT\s+\((.+)\): Merge conflict in (.+)$/,(t,[e,r])=>{t.conflicts.push(new Oh(e,r))}),new pe(/^CONFLICT\s+\((.+\/delete)\): (.+) deleted in (.+) and/,(t,[e,r,n])=>{t.conflicts.push(new Oh(e,r,{deleteRef:n}))}),new pe(/^CONFLICT\s+\((.+)\):/,(t,[e])=>{t.conflicts.push(new Oh(e,null))}),new pe(/^Automatic merge failed;\s+(.+)$/,(t,[e])=>{t.result=e})],mI=(t,e)=>Object.assign(MR(t,e),G0(t,e)),MR=t=>Rr(new aI,OR,t)}});function DR(t){return t.length?{commands:["merge",...t],format:"utf-8",parser(e,r){let n=mI(e,r);if(n.failed)throw new Du(n);return n}}:Tr("Git.merge requires at least one option")}var Uq=V({"src/lib/tasks/merge.ts"(){"use strict";Pl(),Hq(),mt()}});function Gq(t,e,r){let n=r.includes("deleted"),i=r.includes("tag")||/^refs\/tags/.test(t),s=!r.includes("new");return{deleted:n,tag:i,branch:!i,new:!s,alreadyUpdated:s,local:t,remote:e}}var LR,gI,NR,jq=V({"src/lib/parsers/parse-push.ts"(){"use strict";ue(),dI(),LR=[new pe(/^Pushing to (.+)$/,(t,[e])=>{t.repo=e}),new pe(/^updating local tracking ref '(.+)'/,(t,[e])=>{t.ref={...t.ref||{},local:e}}),new pe(/^[=*-]\s+([^:]+):(\S+)\s+\[(.+)]$/,(t,[e,r,n])=>{t.pushed.push(Gq(e,r,n))}),new pe(/^Branch '([^']+)' set up to track remote branch '([^']+)' from '([^']+)'/,(t,[e,r,n])=>{t.branch={...t.branch||{},local:e,remote:r,remoteName:n}}),new pe(/^([^:]+):(\S+)\s+([a-z0-9]+)\.\.([a-z0-9]+)$/,(t,[e,r,n,i])=>{t.update={head:{local:e,remote:r},hash:{from:n,to:i}}})],gI=(t,e)=>{let r=NR(t,e),n=cI(t,e);return{...r,...n}},NR=(t,e)=>Rr({pushed:[]},LR,[t,e])}}),vI={};yt(vI,{pushTagsTask:()=>qq,pushTask:()=>j0});function qq(t={},e){return _n(e,"--tags"),j0(t,e)}function j0(t={},e){let r=["push",...e];return t.branch&&r.splice(1,0,t.branch),t.remote&&r.splice(1,0,t.remote),Hh(r,"-v"),_n(r,"--verbose"),_n(r,"--porcelain"),{commands:r,format:"utf-8",parser:gI}}var wI=V({"src/lib/tasks/push.ts"(){"use strict";jq(),ue()}});function Wq(){return{showBuffer(){let t=["show",...hr(arguments,1)];return t.includes("--binary")||t.splice(1,0,"--binary"),this._runTask(S$(t),tt(arguments))},show(){let t=["show",...hr(arguments,1)];return this._runTask(pr(t),tt(arguments))}}}var zq=V({"src/lib/tasks/show.ts"(){"use strict";ue(),mt()}}),BR,yI,Vq=V({"src/lib/responses/FileStatusSummary.ts"(){"use strict";BR=/^(.+)\0(.+)$/,yI=class{constructor(t,e,r){if(this.path=t,this.index=e,this.working_dir=r,e==="R"||r==="R"){let n=BR.exec(t)||[null,t,t];this.from=n[2]||"",this.path=n[1]||""}}}}});function HR(t){let[e,r]=t.split(Cl);return{from:r||e,to:e}}function Qr(t,e,r){return[`${t}${e}`,r]}function o0(t,...e){return e.map(r=>Qr(t,r,(n,i)=>n.conflicted.push(i)))}function Yq(t,e){let r=e.trim();switch(" "){case r.charAt(2):return n(r.charAt(0),r.charAt(1),r.slice(3));case r.charAt(1):return n(" ",r.charAt(0),r.slice(2));default:return}function n(i,s,a){let o=`${i}${s}`,l=bI.get(o);l&&l(t,a),o!=="##"&&o!=="!!"&&t.files.push(new yI(a,i,s))}}var UR,bI,_I,Xq=V({"src/lib/responses/StatusSummary.ts"(){"use strict";ue(),Vq(),UR=class{constructor(){this.not_added=[],this.conflicted=[],this.created=[],this.deleted=[],this.ignored=void 0,this.modified=[],this.renamed=[],this.files=[],this.staged=[],this.ahead=0,this.behind=0,this.current=null,this.tracking=null,this.detached=!1,this.isClean=()=>!this.files.length}},bI=new Map([Qr(" ","A",(t,e)=>t.created.push(e)),Qr(" ","D",(t,e)=>t.deleted.push(e)),Qr(" ","M",(t,e)=>t.modified.push(e)),Qr("A"," ",(t,e)=>{t.created.push(e),t.staged.push(e)}),Qr("A","M",(t,e)=>{t.created.push(e),t.staged.push(e),t.modified.push(e)}),Qr("D"," ",(t,e)=>{t.deleted.push(e),t.staged.push(e)}),Qr("M"," ",(t,e)=>{t.modified.push(e),t.staged.push(e)}),Qr("M","M",(t,e)=>{t.modified.push(e),t.staged.push(e)}),Qr("R"," ",(t,e)=>{t.renamed.push(HR(e))}),Qr("R","M",(t,e)=>{let r=HR(e);t.renamed.push(r),t.modified.push(r.to)}),Qr("!","!",(t,e)=>{(t.ignored=t.ignored||[]).push(e)}),Qr("?","?",(t,e)=>t.not_added.push(e)),...o0("A","A","U"),...o0("D","D","U"),...o0("U","A","D","U"),["##",(t,e)=>{let r=/ahead (\d+)/,n=/behind (\d+)/,i=/^(.+?(?=(?:\.{3}|\s|$)))/,s=/\.{3}(\S*)/,a=/\son\s(\S+?)(?=\.{3}|$)/,o=r.exec(e);t.ahead=o&&+o[1]||0,o=n.exec(e),t.behind=o&&+o[1]||0,o=i.exec(e),t.current=Qt(o==null?void 0:o[1],ct,null),o=s.exec(e),t.tracking=Qt(o==null?void 0:o[1],ct,null),o=a.exec(e),o&&(t.current=Qt(o==null?void 0:o[1],ct,t.current)),t.detached=/\(no branch\)/.test(e)}]]),_I=function(t){let e=t.split(Cl),r=new UR;for(let n=0,i=e.length;n!xI.includes(r))],parser(r){return _I(r)}}}var xI,Kq=V({"src/lib/tasks/status.ts"(){"use strict";Xq(),xI=["--null","-z"]}});function Nh(t=0,e=0,r=0,n="",i=!0){return Object.defineProperty({major:t,minor:e,patch:r,agent:n,installed:i},"toString",{value(){return`${this.major}.${this.minor}.${this.patch}`},configurable:!1,enumerable:!1})}function Qq(){return Nh(0,0,0,"",!1)}function Jq(){return{version(){return this._runTask({commands:["--version"],format:"utf-8",parser:eW,onError(t,e,r,n){if(t.exitCode===-2)return r(Buffer.from(q0));n(e)}})}}}function eW(t){return t===q0?Qq():Rr(Nh(0,0,0,t),SI,t)}var q0,SI,tW=V({"src/lib/tasks/version.ts"(){"use strict";ue(),q0="installed=false",SI=[new pe(/version (\d+)\.(\d+)\.(\d+)(?:\s*\((.+)\))?/,(t,[e,r,n,i=""])=>{Object.assign(t,Nh(We(e),We(r),We(n),i))}),new pe(/version (\d+)\.(\d+)\.(\D+)(.+)?$/,(t,[e,r,n,i=""])=>{Object.assign(t,Nh(We(e),We(r),n,i))})]}});function GR(t,e,r,...n){return ct(r)?e(r,Qt(n[0],ct),hr(arguments)):Tr(`git.${t}() requires a string 'repoPath'`)}function rW(){return{clone(t,...e){return this._runTask(GR("clone",y0,Qt(t,ct),...e),tt(arguments))},mirror(t,...e){return this._runTask(GR("mirror",EI,Qt(t,ct),...e),tt(arguments))}}}var y0,EI,nW=V({"src/lib/tasks/clone.ts"(){"use strict";mt(),ue(),y0=(t,e,r)=>{let n=["clone",...r];return ct(t)&&n.push(Sl(t)),ct(e)&&n.push(Sl(e)),pr(n)},EI=(t,e,r)=>(_n(r,"--mirror"),y0(t,e,r))}}),kI={};yt(kI,{SimpleGitApi:()=>b0});var b0,iW=V({"src/lib/simple-git-api.ts"(){"use strict";oq(),lq(),uq(),hq(),wq(),$$(),bq(),D$(),xq(),Cq(),sI(),Uq(),wI(),zq(),Kq(),mt(),tW(),ue(),nW(),b0=class{constructor(t){this._executor=t}_runTask(t,e){let r=this._executor.chain(),n=r.push(t);return e&&sq(t,n,e),Object.create(this,{then:{value:n.then.bind(n)},catch:{value:n.catch.bind(n)},_executor:{value:r}})}add(t){return this._runTask(pr(["add",...wi(t)]),tt(arguments))}cwd(t){let e=tt(arguments);return typeof t=="string"?this._runTask(ER(t,this._executor),e):typeof(t==null?void 0:t.path)=="string"?this._runTask(ER(t.path,t.root&&this._executor||void 0),e):this._runTask(Tr("Git.cwd: workingDirectory must be supplied as a string"),e)}hashObject(t,e){return this._runTask(_q(t,e===!0),tt(arguments))}init(t){return this._runTask(Aq(t===!0,this._executor.cwd,hr(arguments)),tt(arguments))}merge(){return this._runTask(DR(hr(arguments)),tt(arguments))}mergeFromTo(t,e){return ct(t)&&ct(e)?this._runTask(DR([t,e,...hr(arguments)]),tt(arguments,!1)):this._runTask(Tr("Git.mergeFromTo requires that the 'remote' and 'branch' arguments are supplied as strings"))}outputHandler(t){return this._executor.outputHandler=t,this}push(){let t=j0({remote:Qt(arguments[0],ct),branch:Qt(arguments[1],ct)},hr(arguments));return this._runTask(t,tt(arguments))}stash(){return this._runTask(pr(["stash",...hr(arguments)]),tt(arguments))}status(){return this._runTask(Zq(hr(arguments)),tt(arguments))}},Object.assign(b0.prototype,cq(),rW(),vq(),zj(),dq(),yq(),Zj(),Mq(),Wq(),Jq())}}),AI={};yt(AI,{Scheduler:()=>TI});var jR,TI,sW=V({"src/lib/runners/scheduler.ts"(){"use strict";ue(),U$(),jR=(()=>{let t=0;return()=>{t++;let{promise:e,done:r}=(0,CI.createDeferred)();return{promise:e,done:r,id:t}}})(),TI=class{constructor(t=2){this.concurrency=t,this.logger=O0("","scheduler"),this.pending=[],this.running=[],this.logger("Constructed, concurrency=%s",t)}schedule(){if(!this.pending.length||this.running.length>=this.concurrency){this.logger("Schedule attempt ignored, pending=%s running=%s concurrency=%s",this.pending.length,this.running.length,this.concurrency);return}let t=_n(this.running,this.pending.shift());this.logger("Attempting id=%s",t.id),t.done(()=>{this.logger("Completing id=",t.id),Hh(this.running,t),this.schedule()})}next(){let{promise:t,id:e}=_n(this.pending,jR());return this.logger("Scheduling id=%s",e),this.schedule(),t}}}}),PI={};yt(PI,{applyPatchTask:()=>aW});function aW(t,e){return pr(["apply",...e,...t])}var oW=V({"src/lib/tasks/apply-patch.ts"(){"use strict";mt()}});function lW(t,e){return{branch:t,hash:e,success:!0}}function cW(t){return{branch:t,hash:null,success:!1}}var RI,uW=V({"src/lib/responses/BranchDeleteSummary.ts"(){"use strict";RI=class{constructor(){this.all=[],this.branches={},this.errors=[]}get success(){return!this.errors.length}}}});function $I(t,e){return e===1&&_0.test(t)}var qR,_0,WR,Vh,fW=V({"src/lib/parsers/parse-branch-delete.ts"(){"use strict";uW(),ue(),qR=/(\S+)\s+\(\S+\s([^)]+)\)/,_0=/^error[^']+'([^']+)'/m,WR=[new pe(qR,(t,[e,r])=>{let n=lW(e,r);t.all.push(n),t.branches[e]=n}),new pe(_0,(t,[e])=>{let r=cW(e);t.errors.push(r),t.all.push(r),t.branches[e]=r})],Vh=(t,e)=>Rr(new RI,WR,[t,e])}}),II,dW=V({"src/lib/responses/BranchSummary.ts"(){"use strict";II=class{constructor(){this.all=[],this.branches={},this.current="",this.detached=!1}push(t,e,r,n,i){t==="*"&&(this.detached=e,this.current=r),this.all.push(r),this.branches[r]={current:t==="*",linkedWorkTree:t==="+",name:r,commit:n,label:i}}}}});function zR(t){return t?t.charAt(0):""}function FI(t,e=!1){return Rr(new II,e?[MI]:OI,t)}var OI,MI,hW=V({"src/lib/parsers/parse-branch.ts"(){"use strict";dW(),ue(),OI=[new pe(/^([*+]\s)?\((?:HEAD )?detached (?:from|at) (\S+)\)\s+([a-z0-9]+)\s(.*)$/,(t,[e,r,n,i])=>{t.push(zR(e),!0,r,n,i)}),new pe(/^([*+]\s)?(\S+)\s+([a-z0-9]+)\s?(.*)$/s,(t,[e,r,n,i])=>{t.push(zR(e),!1,r,n,i)})],MI=new pe(/^(\S+)$/s,(t,[e])=>{t.push("*",!1,e,"","")})}}),DI={};yt(DI,{branchLocalTask:()=>mW,branchTask:()=>pW,containsDeleteBranchCommand:()=>LI,deleteBranchTask:()=>vW,deleteBranchesTask:()=>gW});function LI(t){let e=["-d","-D","--delete"];return t.some(r=>e.includes(r))}function pW(t){let e=LI(t),r=t.includes("--show-current"),n=["branch",...t];return n.length===1&&n.push("-a"),n.includes("-v")||n.splice(1,0,"-v"),{format:"utf-8",commands:n,parser(i,s){return e?Vh(i,s).all[0]:FI(i,r)}}}function mW(){return{format:"utf-8",commands:["branch","-v"],parser(t){return FI(t)}}}function gW(t,e=!1){return{format:"utf-8",commands:["branch","-v",e?"-D":"-d",...t],parser(r,n){return Vh(r,n)},onError({exitCode:r,stdOut:n},i,s,a){if(!$I(String(i),r))return a(i);s(n)}}}function vW(t,e=!1){let r={format:"utf-8",commands:["branch","-v",e?"-D":"-d",t],parser(n,i){return Vh(n,i).branches[t]},onError({exitCode:n,stdErr:i,stdOut:s},a,o,l){if(!$I(String(a),n))return l(a);throw new Du(r.parser(Mu(s),Mu(i)),String(a))}};return r}var wW=V({"src/lib/tasks/branch.ts"(){"use strict";Pl(),fW(),hW(),ue()}});function yW(t){let e=t.trim().replace(/^["']|["']$/g,"");return e&&(0,NI.normalize)(e)}var BI,bW=V({"src/lib/responses/CheckIgnore.ts"(){"use strict";BI=t=>t.split(/\n/g).map(yW).filter(Boolean)}}),HI={};yt(HI,{checkIgnoreTask:()=>_W});function _W(t){return{commands:["check-ignore",...t],format:"utf-8",parser:BI}}var xW=V({"src/lib/tasks/check-ignore.ts"(){"use strict";bW()}});function SW(t,e){return Rr({raw:t,remote:null,branches:[],tags:[],updated:[],deleted:[]},UI,[t,e])}var UI,EW=V({"src/lib/parsers/parse-fetch.ts"(){"use strict";ue(),UI=[new pe(/From (.+)$/,(t,[e])=>{t.remote=e}),new pe(/\* \[new branch]\s+(\S+)\s*-> (.+)$/,(t,[e,r])=>{t.branches.push({name:e,tracking:r})}),new pe(/\* \[new tag]\s+(\S+)\s*-> (.+)$/,(t,[e,r])=>{t.tags.push({name:e,tracking:r})}),new pe(/- \[deleted]\s+\S+\s*-> (.+)$/,(t,[e])=>{t.deleted.push({tracking:e})}),new pe(/\s*([^.]+)\.\.(\S+)\s+(\S+)\s*-> (.+)$/,(t,[e,r,n,i])=>{t.updated.push({name:n,tracking:i,to:r,from:e})})]}}),GI={};yt(GI,{fetchTask:()=>AW});function kW(t){return/^--upload-pack(=|$)/.test(t)}function AW(t,e,r){let n=["fetch",...r];return t&&e&&n.push(t,e),n.find(kW)?Tr("git.fetch: potential exploit argument blocked."):{commands:n,format:"utf-8",parser:SW}}var CW=V({"src/lib/tasks/fetch.ts"(){"use strict";EW(),mt()}});function TW(t){return Rr({moves:[]},jI,t)}var jI,PW=V({"src/lib/parsers/parse-move.ts"(){"use strict";ue(),jI=[new pe(/^Renaming (.+) to (.+)$/,(t,[e,r])=>{t.moves.push({from:e,to:r})})]}}),qI={};yt(qI,{moveTask:()=>RW});function RW(t,e){return{commands:["mv","-v",...wi(t),e],format:"utf-8",parser:TW}}var $W=V({"src/lib/tasks/move.ts"(){"use strict";PW(),ue()}}),WI={};yt(WI,{pullTask:()=>IW});function IW(t,e,r){let n=["pull",...r];return t&&e&&n.splice(1,0,t,e),{commands:n,format:"utf-8",parser(i,s){return G0(i,s)},onError(i,s,a,o){let l=Bq(Mu(i.stdOut),Mu(i.stdErr));if(l)return o(new Du(l));o(s)}}}var FW=V({"src/lib/tasks/pull.ts"(){"use strict";Pl(),pI(),ue()}});function OW(t){let e={};return zI(t,([r])=>e[r]={name:r}),Object.values(e)}function MW(t){let e={};return zI(t,([r,n,i])=>{Object.hasOwn(e,r)||(e[r]={name:r,refs:{fetch:"",push:""}}),i&&n&&(e[r].refs[i.replace(/[^a-z]/g,"")]=n)}),Object.values(e)}function zI(t,e){E0(t,r=>e(r.split(/\s+/)))}var DW=V({"src/lib/responses/GetRemoteSummary.ts"(){"use strict";ue()}}),VI={};yt(VI,{addRemoteTask:()=>LW,getRemotesTask:()=>NW,listRemotesTask:()=>BW,remoteTask:()=>HW,removeRemoteTask:()=>UW});function LW(t,e,r){return pr(["remote","add",...r,t,e])}function NW(t){let e=["remote"];return t&&e.push("-v"),{commands:e,format:"utf-8",parser:t?MW:OW}}function BW(t){let e=[...t];return e[0]!=="ls-remote"&&e.unshift("ls-remote"),pr(e)}function HW(t){let e=[...t];return e[0]!=="remote"&&e.unshift("remote"),pr(e)}function UW(t){return pr(["remote","remove",t])}var GW=V({"src/lib/tasks/remote.ts"(){"use strict";DW(),mt()}}),YI={};yt(YI,{stashListTask:()=>jW});function jW(t={},e){let r=iI(t),n=["stash","list",...r.commands,...e],i=eI(r.splitter,r.fields,D0(n));return zh(n)||{commands:n,format:"utf-8",parser:i}}var qW=V({"src/lib/tasks/stash-list.ts"(){"use strict";Hu(),rI(),U0(),sI()}}),XI={};yt(XI,{addSubModuleTask:()=>WW,initSubModuleTask:()=>zW,subModuleTask:()=>Yh,updateSubModuleTask:()=>VW});function WW(t,e){return Yh(["add",t,e])}function zW(t){return Yh(["init",...t])}function Yh(t){let e=[...t];return e[0]!=="submodule"&&e.unshift("submodule"),pr(e)}function VW(t){return Yh(["update",...t])}var YW=V({"src/lib/tasks/sub-module.ts"(){"use strict";mt()}});function XW(t,e){let r=Number.isNaN(t),n=Number.isNaN(e);return r!==n?r?1:-1:r?ZI(t,e):0}function ZI(t,e){return t===e?0:t>e?1:-1}function ZW(t){return t.trim()}function $h(t){return typeof t=="string"&&parseInt(t.replace(/^\D+/g,""),10)||0}var VR,KI,KW=V({"src/lib/responses/TagList.ts"(){"use strict";VR=class{constructor(t,e){this.all=t,this.latest=e}},KI=function(t,e=!1){let r=t.split(` +`).map(ZW).filter(Boolean);e||r.sort(function(i,s){let a=i.split("."),o=s.split(".");if(a.length===1||o.length===1)return XW($h(a[0]),$h(o[0]));for(let l=0,c=Math.max(a.length,o.length);li.indexOf(".")>=0);return new VR(r,n)}}}),QI={};yt(QI,{addAnnotatedTagTask:()=>ez,addTagTask:()=>JW,tagListTask:()=>QW});function QW(t=[]){let e=t.some(r=>/^--sort=/.test(r));return{format:"utf-8",commands:["tag","-l",...t],parser(r){return KI(r,e)}}}function JW(t){return{format:"utf-8",commands:["tag",t],parser(){return{name:t}}}}function ez(t,e){return{format:"utf-8",commands:["tag","-a","-m",e,t],parser(){return{name:t}}}}var tz=V({"src/lib/tasks/tag.ts"(){"use strict";KW()}}),rz=yj({"src/git.js"(t,e){"use strict";var{GitExecutor:r}=(iq(),pt(q$)),{SimpleGitApi:n}=(iW(),pt(kI)),{Scheduler:i}=(sW(),pt(AI)),{adhocExecTask:s,configurationErrorTask:a}=(mt(),pt(p0)),{asArray:o,filterArray:l,filterPrimitives:c,filterString:u,filterStringOrStringArray:f,filterType:d,getTrailingOptions:h,trailingFunctionArgument:m,trailingOptionsArgument:g}=(ue(),pt(h$)),{applyPatchTask:v}=(oW(),pt(PI)),{branchTask:w,branchLocalTask:b,deleteBranchesTask:k,deleteBranchTask:x}=(wW(),pt(DI)),{checkIgnoreTask:E}=(xW(),pt(HI)),{checkIsRepoTask:A}=(v$(),pt(p$)),{cleanWithOptionsTask:y,isCleanOptionsArray:S}=(T$(),pt(A$)),{diffSummaryTask:_}=(U0(),pt(nI)),{fetchTask:C}=(CW(),pt(GI)),{moveTask:P}=($W(),pt(qI)),{pullTask:N}=(FW(),pt(WI)),{pushTagsTask:B}=(wI(),pt(vI)),{addRemoteTask:H,getRemotesTask:ce,listRemotesTask:Pe,remoteTask:ve,removeRemoteTask:ie}=(GW(),pt(VI)),{getResetMode:xe,resetTask:we}=(H$(),pt(L$)),{stashListTask:W}=(qW(),pt(YI)),{addSubModuleTask:X,initSubModuleTask:q,subModuleTask:De,updateSubModuleTask:ar}=(YW(),pt(XI)),{addAnnotatedTagTask:Ft,addTagTask:Ie,tagListTask:kt}=(tz(),pt(QI)),{straightThroughBufferTask:At,straightThroughStringTask:je}=(mt(),pt(p0));function Z(M,O){this._plugins=O,this._executor=new r(M.baseDir,new i(M.maxConcurrentProcesses),O),this._trimmed=M.trimmed}(Z.prototype=Object.create(n.prototype)).constructor=Z,Z.prototype.customBinary=function(M){return this._plugins.reconfigure("binary",M),this},Z.prototype.env=function(M,O){return arguments.length===1&&typeof M=="object"?this._executor.env=M:(this._executor.env=this._executor.env||{})[M]=O,this},Z.prototype.stashList=function(M){return this._runTask(W(g(arguments)||{},l(M)&&M||[]),m(arguments))},Z.prototype.mv=function(M,O){return this._runTask(P(M,O),m(arguments))},Z.prototype.checkoutLatestTag=function(M){var O=this;return this.pull(function(){O.tags(function(oe,Ce){O.checkout(Ce.latest,M)})})},Z.prototype.pull=function(M,O,oe,Ce){return this._runTask(N(d(M,u),d(O,u),h(arguments)),m(arguments))},Z.prototype.fetch=function(M,O){return this._runTask(C(d(M,u),d(O,u),h(arguments)),m(arguments))},Z.prototype.silent=function(M){return this._runTask(s(()=>console.warn("simple-git deprecation notice: git.silent: logging should be configured using the `debug` library / `DEBUG` environment variable, this method will be removed.")))},Z.prototype.tags=function(M,O){return this._runTask(kt(h(arguments)),m(arguments))},Z.prototype.rebase=function(){return this._runTask(je(["rebase",...h(arguments)]),m(arguments))},Z.prototype.reset=function(M){return this._runTask(we(xe(M),h(arguments)),m(arguments))},Z.prototype.revert=function(M){let O=m(arguments);return typeof M!="string"?this._runTask(a("Commit must be a string"),O):this._runTask(je(["revert",...h(arguments,0,!0),M]),O)},Z.prototype.addTag=function(M){let O=typeof M=="string"?Ie(M):a("Git.addTag requires a tag name");return this._runTask(O,m(arguments))},Z.prototype.addAnnotatedTag=function(M,O){return this._runTask(Ft(M,O),m(arguments))},Z.prototype.deleteLocalBranch=function(M,O,oe){return this._runTask(x(M,typeof O=="boolean"?O:!1),m(arguments))},Z.prototype.deleteLocalBranches=function(M,O,oe){return this._runTask(k(M,typeof O=="boolean"?O:!1),m(arguments))},Z.prototype.branch=function(M,O){return this._runTask(w(h(arguments)),m(arguments))},Z.prototype.branchLocal=function(M){return this._runTask(b(),m(arguments))},Z.prototype.raw=function(M){let O=!Array.isArray(M),oe=[].slice.call(O?arguments:M,0);for(let Ot=0;Otconsole.warn("simple-git deprecation notice: clearQueue() is deprecated and will be removed, switch to using the abortPlugin instead.")))},Z.prototype.checkIgnore=function(M,O){return this._runTask(E(o(d(M,f,[]))),m(arguments))},Z.prototype.checkIsRepo=function(M,O){return this._runTask(A(d(M,u)),m(arguments))},e.exports=Z}});zs();var nz=class extends Pr{constructor(t,e){super(void 0,e),this.config=t}};zs();zs();var Tl=class extends Pr{constructor(t,e,r){super(t,r),this.task=t,this.plugin=e,Object.setPrototypeOf(this,new.target.prototype)}};Pl();JR();v$();T$();$$();F$();D$();H$();function iz(t){return t?[{type:"spawn.before",action(n,i){t.aborted&&i.kill(new Tl(void 0,"abort","Abort already signaled"))}},{type:"spawn.after",action(n,i){function s(){i.kill(new Tl(void 0,"abort","Abort signal received"))}t.addEventListener("abort",s),i.spawned.on("close",()=>t.removeEventListener("abort",s))}}]:void 0}function sz(t={}){return{type:"spawn.args",action(e,{env:r}){for(let n of bR(e,r))if(t[n.category]!==!0)throw new Tl(void 0,"unsafe",n.message);return e}}}ue();function az(t){let e=Ou(t,"-c");return{type:"spawn.args",action(r){return[...e,...r]}}}ue();var YR=(0,Al.deferred)().promise;function oz({onClose:t=!0,onExit:e=50}={}){function r(){let i=-1,s={close:(0,Al.deferred)(),closeTimeout:(0,Al.deferred)(),exit:(0,Al.deferred)(),exitTimeout:(0,Al.deferred)()},a=Promise.race([t===!1?YR:s.closeTimeout.promise,e===!1?YR:s.exitTimeout.promise]);return n(t,s.close,s.closeTimeout),n(e,s.exit,s.exitTimeout),{close(o){i=o,s.close.done()},exit(o){i=o,s.exit.done()},get exitCode(){return i},result:a}}function n(i,s,a){i!==!1&&(i===!0?s.promise:s.promise.then(()=>l0(i))).then(a.done)}return{type:"spawn.after",async action(i,{spawned:s,close:a}){var u,f;let o=r(),l=!0,c=()=>void(l=!1);(u=s.stdout)==null||u.on("data",c),(f=s.stderr)==null||f.on("data",c),s.on("error",c),s.on("close",d=>o.close(d)),s.on("exit",d=>o.exit(d));try{await o.result,l&&await l0(50),a(o.exitCode)}catch(d){a(o.exitCode,d)}}}}ue();var lz="Invalid value supplied for custom binary, requires a single string or an array containing either one or two strings",XR="Invalid value supplied for custom binary, restricted characters must be removed or supply the unsafe.allowUnsafeCustomBinary option";function cz(t){return!t||!/^([a-z]:)?([a-z0-9/.\\_~-]+)$/i.test(t)}function ZR(t,e){if(t.length<1||t.length>2)throw new Tl(void 0,"binary",lz);if(t.some(cz))if(e)console.warn(XR);else throw new Tl(void 0,"binary",XR);let[n,i]=t;return{binary:n,prefix:i}}function uz(t,e=["git"],r=!1){let n=ZR(wi(e),r);t.on("binary",i=>{n=ZR(wi(i),r)}),t.append("spawn.binary",()=>n.binary),t.append("spawn.args",i=>n.prefix?[n.prefix,...i]:i)}zs();function fz(t){return!!(t.exitCode&&t.stdErr.length)}function dz(t){return Buffer.concat([...t.stdOut,...t.stdErr])}function hz(t=!1,e=fz,r=dz){return(n,i)=>!t&&n||!e(i)?n:r(i)}function KR(t){return{type:"task.error",action(e,r){let n=t(e.error,{stdErr:r.stdErr,stdOut:r.stdOut,exitCode:r.exitCode});return Buffer.isBuffer(n)?{error:new Pr(void 0,n.toString("utf-8"))}:{error:n}}}}ue();var pz=class{constructor(){this.plugins=new Set,this.events=new JI.EventEmitter}on(t,e){this.events.on(t,e)}reconfigure(t,e){this.events.emit(t,e)}append(t,e){let r=_n(this.plugins,{type:t,action:e});return()=>this.plugins.delete(r)}add(t){let e=[];return wi(t).forEach(r=>r&&this.plugins.add(_n(e,r))),()=>{e.forEach(r=>this.plugins.delete(r))}}exec(t,e,r){let n=e,i=Object.freeze(Object.create(r));for(let s of this.plugins)s.type===t&&(n=s.action(n,i));return n}};ue();function mz(t){let e="--progress",r=["checkout","clone","fetch","pull","push"];return[{type:"spawn.args",action(s,a){return r.includes(a.method)?s$(s,e):s}},{type:"spawn.after",action(s,a){var o;a.commands.includes(e)&&((o=a.spawned.stderr)==null||o.on("data",l=>{let c=/^([\s\S]+?):\s*(\d+)% \((\d+)\/(\d+)\)/.exec(l.toString("utf8"));c&&t({method:a.method,stage:gz(c[1]),progress:We(c[2]),processed:We(c[3]),total:We(c[4])})}))}}]}function gz(t){return String(t.toLowerCase().split(" ",1))||"unknown"}ue();function vz(t){let e=o$(t,["uid","gid"]);return{type:"spawn.options",action(r){return{...e,...r}}}}function wz({block:t,stdErr:e=!0,stdOut:r=!0}){if(t>0)return{type:"spawn.after",action(n,i){var c,u;let s;function a(){s&&clearTimeout(s),s=setTimeout(l,t)}function o(){var f,d;(f=i.spawned.stdout)==null||f.off("data",a),(d=i.spawned.stderr)==null||d.off("data",a),i.spawned.off("exit",o),i.spawned.off("close",o),s&&clearTimeout(s)}function l(){o(),i.kill(new Tl(void 0,"timeout","block timeout reached"))}r&&((c=i.spawned.stdout)==null||c.on("data",a)),e&&((u=i.spawned.stderr)==null||u.on("data",a)),i.spawned.on("exit",o),i.spawned.on("close",o),a()}}}function yz(){return{type:"spawn.args",action(t){let e=[],r;function n(i){(r=r||[]).push(...i)}for(let i=0;iwn(a)&&El(a)||a));break}e.push(s)}return r?[...e,"--",...r.map(String)]:e}}}ue();var bz=rz();function _z(t,e){var i;let r=new pz,n=f$(t&&(typeof t=="string"?{baseDir:t}:t)||{},e);if(!k0(n.baseDir))throw new nz(n,"Cannot use simple-git on a directory that does not exist");return Array.isArray(n.config)&&r.add(az(n.config)),r.add(sz(n.unsafe)),r.add(oz(n.completion)),n.abort&&r.add(iz(n.abort)),n.progress&&r.add(mz(n.progress)),n.timeout&&r.add(wz(n.timeout)),n.spawnOptions&&r.add(vz(n.spawnOptions)),r.add(yz()),r.add(KR(hz(!0))),n.errors&&r.add(KR(n.errors)),uz(r,n.binary,(i=n.unsafe)==null?void 0:i.allowUnsafeCustomBinary),new bz(n,r)}Pl();var eF=_z;var Se=class extends wl{constructor(r){super(r);this.useDefaultWindowsGitPath=!1}async setGitInstance(r=!1){var n;if(await this.isGitInstalled()){let i=this.app.vault.adapter,s=i.getBasePath(),a=s;this.plugin.settings.basePath&&(await i.exists((0,Ji.normalizePath)(this.plugin.settings.basePath))?a=Ue.join(s,this.plugin.settings.basePath):r||new Ji.Notice("ObsidianGit: Base path does not exist")),this.absoluteRepoPath=a,this.git=eF({baseDir:a,binary:this.plugin.localStorage.getGitPath()||(this.useDefaultWindowsGitPath?Wd:void 0),config:["core.quotepath=off"],unsafe:{allowUnsafeCustomBinary:!0,allowUnsafeEditor:!0,allowUnsafeAskPass:!0,allowUnsafeConfigEnvCount:!0,allowUnsafeConfigPaths:!0,allowUnsafeCredentialHelper:!0,allowUnsafeGitProxy:!0,allowUnsafeGpgProgram:!0,allowUnsafeHooksPath:!0,allowUnsafeMergeDriver:!0,allowUnsafeSshCommand:!0,allowUnsafePager:!0}});let o=this.plugin.localStorage.getPATHPaths(),l=this.plugin.localStorage.getEnvVars(),c=this.plugin.settings.gitDir,u={...process.env};if(o.length>0){let w=o.join(":")+":"+u.PATH;u.PATH=w}c&&(u.GIT_DIR=c,u.GIT_WORK_TREE=a);for(let w of l){let[b,k]=w.split("=");u[b]=k}let f="simple-git",d=",",m=((n=localStorage.debug)!=null?n:"").split(d);if(!m.includes(f)&&!m.includes(`-${f}`)&&(m.push(f),nF.default.enable(m.join(d))),await this.git.env(u).checkIsRepo()){let w=await this.git.revparse("--show-cdup"),b=(0,Uu.resolve)(a+Uu.sep+w);this.absoluteRepoPath=b,await this.git.cwd(b)}let g=Ue.join(s,this.app.vault.configDir,"plugins","obsidian-git"),v=Ue.join(g,Ta);u.SSH_ASKPASS==null&&(u.SSH_ASKPASS=v),u.SSH_ASKPASS_REQUIRE="force",u.OBSIDIAN_GIT_CREDENTIALS_INPUT=Ue.join(g,zd),u.SSH_ASKPASS==v&&this.askpass().catch(w=>this.plugin.displayError(w)),u.OBSIDIAN_GIT="1",this.git=this.git.env(u)}}getRelativeVaultPath(r){let i=this.app.vault.adapter.getBasePath(),s=Ue.join(this.absoluteRepoPath,r),a=Ue.relative(i,s);return Ji.Platform.isWin&&(a=a.replace(/\\/g,"/")),a}getRelativeRepoPath(r,n=!0){if(n){let s=this.plugin.app.vault.adapter.getBasePath(),a=this.absoluteRepoPath,o=Ue.join(s,r),l=Ue.relative(a,o);return Ji.Platform.isWin&&(l=l.replace(/\\/g,"/")),l}return r}get absPluginConfigPath(){let n=this.app.vault.adapter.getBasePath();return Ue.join(n,this.app.vault.configDir,"plugins","obsidian-git")}get relPluginConfigPath(){return Ue.join(this.app.vault.configDir,"plugins","obsidian-git")}async askpass(){let r=this.app.vault.adapter,n=this.app.vault.configDir+"/plugins/obsidian-git/";await this.addAskPassScriptToExclude(),await Jr.writeFile(Ue.join(this.absPluginConfigPath,Ta),QA),await Jr.chmod(Ue.join(this.absPluginConfigPath,Ta),493),this.watchAbortController=new AbortController;let{signal:i}=this.watchAbortController;try{let s=Jr.watch(this.absPluginConfigPath,{signal:i});for await(let a of s){if(a.filename!=zd)continue;let o=n+zd;if(await new Promise(d=>setTimeout(d,200)),!await r.exists(o))continue;let l=await r.read(o),c;l.length>60&&(c=new Ji.Notice(l,999999));let u=!0;l.contains("Username for")&&(u=!1);let f=await new Ze(this.plugin,{allowEmpty:!0,obscure:u,placeholder:l.length>60?"Enter a response to the message.":l}).openAndGetResult();c==null||c.hide(),await r.exists(o)&&await r.write(`${o}.response`,f!=null?f:"")}}catch(s){this.plugin.displayError(s),await Jr.rm(Ue.join(this.absPluginConfigPath,Ta),{force:!0}),await Jr.rm(Ue.join(this.absPluginConfigPath,`${Ta}.response`),{force:!0}),await new Promise(a=>setTimeout(a,5e3)),this.plugin.log("Retry watch for ask pass"),await this.askpass()}}async addAskPassScriptToExclude(){try{if(!await this.git.checkIsRepo())return;let r=await this.git.revparse(["--path-format=absolute","--git-path","info/exclude"]),n=Ue.join(this.app.vault.configDir,"plugins","obsidian-git",Ta),i=this.getRelativeRepoPath(n,!0);(await Jr.readFile(r,"utf-8")).split(` +`).some(l=>l.contains(i))||await Jr.appendFile(r,i+` +`)}catch(r){console.error("Error while adding askpass script to exclude file:",r)}}unload(){var r;(r=this.watchAbortController)==null||r.abort()}async status(r){let n=r==null?void 0:r.path;this.plugin.setPluginState({gitAction:1});let i=await this.git.status(n!=null?["--",n]:[]);this.plugin.setPluginState({gitAction:0});let s=i.files.map(a=>{let o=this.formatPath(a);return{path:o.path,from:o.from,index:a.index==="?"?"U":a.index,workingDir:a.working_dir==="?"?"U":a.working_dir,vaultPath:this.getRelativeVaultPath(o.path)}});return{all:s,changed:s.filter(a=>a.workingDir!==" "),staged:s.filter(a=>a.index!==" "&&a.index!="U"),conflicted:i.conflicted.map(a=>this.formatPath({path:a}).path)}}async submoduleAwareHeadRevisonInContainingDirectory(r){let n=this.getRelativeRepoPath(r),s=["-C",Ue.dirname(n),"rev-parse","HEAD"],a=this.git.raw(s);return a.catch(o=>console.warn("obsidian-git: rev-parse error:",o)),(await a).trim()}async getSubmodulePaths(){return new Promise(r=>{this.git.outputHandler((n,i,s,a)=>{if(!(a.contains("submodule")&&a.contains("foreach")))return;let o="",l=this.app.vault.adapter.getBasePath()+(this.plugin.settings.basePath?"/"+this.plugin.settings.basePath:"");i.on("data",c=>{o+=c.toString("utf8")}),i.on("end",()=>{let u=o.split(` +`).map(f=>{let d=f.match(/'([^']*)'/);if(d!=null)return l+"/"+d[1]+Uu.sep}).filter(f=>!!f);u.reverse(),r(u)})}),this.git.subModule(["foreach","--recursive",""]).then(()=>{this.git.outputHandler(()=>{})},n=>this.plugin.displayError(n))})}formatPath(r){function n(i){if(i!=null)return i.startsWith('"')&&i.endsWith('"')?i.substring(1,i.length-1):i}return r.from!=null?{from:n(r.from),path:n(r.path)}:{path:n(r.path)}}async blame(r,n,i){if(r=this.getRelativeRepoPath(r),!await this.isTracked(r))return"untracked";let s=await this.getSubmoduleOfFile(r),a=s?["-C",s.submodule]:[],o=s?s.relativeFilepath:r;a.push("blame","--porcelain"),i&&a.push("-w");let l=`-C${qd}`;switch(n){case"inactive":break;case"same-commit":a.push("-C",l);break;case"all-commits":a.push("-C","-C",l);break;default:js(n)}a.push("--",o);let c=await this.git.raw(a);return xz(c)}async isTracked(r){let n=await this.getSubmoduleOfFile(r),i=n?["-C",n.submodule]:[],s=n?n.relativeFilepath:r;return i.push("ls-files","--",s),this.git.raw(i).then(a=>a.trim()!=="")}async commitAll({message:r}){if(this.plugin.settings.updateSubmodules){this.plugin.setPluginState({gitAction:4});let i=await this.getSubmodulePaths();for(let s of i)await this.git.cwd({path:s,root:!1}).add("-A"),await this.git.cwd({path:s,root:!1}).commit(await this.formatCommitMessage(r))}this.plugin.setPluginState({gitAction:3}),await this.git.add("-A"),this.plugin.setPluginState({gitAction:4});let n=await this.git.commit(await this.formatCommitMessage(r));return this.app.workspace.trigger("obsidian-git:head-change"),n.summary.changes}async commit({message:r,amend:n}){this.plugin.setPluginState({gitAction:4});let i=(await this.git.commit(await this.formatCommitMessage(r),n?["--amend"]:[])).summary.changes;return this.app.workspace.trigger("obsidian-git:head-change"),this.plugin.setPluginState({gitAction:0}),i}async stage(r,n){this.plugin.setPluginState({gitAction:3}),r=this.getRelativeRepoPath(r,n),await this.git.add(["--",r]),this.plugin.setPluginState({gitAction:0})}async stageAll({dir:r}){this.plugin.setPluginState({gitAction:3}),await this.git.add(r!=null?r:"-A"),this.plugin.setPluginState({gitAction:0})}async unstageAll({dir:r}){this.plugin.setPluginState({gitAction:3}),await this.git.reset(r!=null?["--",r]:[]),this.plugin.setPluginState({gitAction:0})}async unstage(r,n){this.plugin.setPluginState({gitAction:3}),r=this.getRelativeRepoPath(r,n),await this.git.reset(["--",r]),this.plugin.setPluginState({gitAction:0})}async discard(r){this.plugin.setPluginState({gitAction:3}),await this.isTracked(r)&&await this.git.checkout(["--",r]),this.plugin.setPluginState({gitAction:0})}async applyPatch(r){let n=Ue.join(this.relPluginConfigPath,"patch");await this.app.vault.adapter.write(n,r),await this.git.applyPatch(n,{"--cached":null,"--unidiff-zero":null,"--whitespace":"nowarn"}),await this.app.vault.adapter.remove(n)}async getUntrackedPaths(r){let n=r==null?void 0:r.path;this.plugin.setPluginState({gitAction:1});let i=[];n!=null&&i.push("--",n);let s=await this.git.clean(Oa.RECURSIVE+Oa.DRY_RUN,i);return this.plugin.setPluginState({gitAction:0}),s.paths}async hashObject(r){r=this.getRelativeRepoPath(r);let n=await this.getSubmoduleOfFile(r),i=n?["-C",n.submodule]:[],s=n?n.relativeFilepath:r;return i.push("hash-object","--",s),this.git.raw(i)}async discardAll({dir:r}){return this.discard(r!=null?r:".")}async pull(){this.plugin.setPluginState({gitAction:2});try{this.plugin.settings.updateSubmodules&&await this.git.subModule(["update","--remote","--merge","--recursive"]);let r=await this.branchInfo(),n=await this.git.revparse([r.current]);if(!r.tracking&&this.plugin.settings.updateSubmodules){this.plugin.log("No tracking branch found. Ignoring pull of main repo and updating submodules only.");return}await this.git.fetch();let i=await this.git.revparse([r.tracking]);if(n!==i){if(this.plugin.settings.syncMethod==="merge"||this.plugin.settings.syncMethod==="rebase")try{let o=[r.tracking];switch(this.plugin.settings.mergeStrategy!=="none"&&o.push(`--strategy-option=${this.plugin.settings.mergeStrategy}`),this.plugin.settings.syncMethod){case"merge":await this.git.merge(o);break;case"rebase":await this.git.rebase(o)}}catch(o){this.plugin.displayError(`Pull failed (${this.plugin.settings.syncMethod}): ${"message"in o?o.message:o}`);return}else if(this.plugin.settings.syncMethod==="reset")try{await this.git.raw(["update-ref",`refs/heads/${r.current}`,i]),await this.unstageAll({})}catch(o){this.plugin.displayError(`Sync failed (${this.plugin.settings.syncMethod}): ${"message"in o?o.message:o}`)}this.app.workspace.trigger("obsidian-git:head-change");let s=await this.git.revparse([r.current]);return(await this.git.diff([`${n}..${s}`,"--name-only"])).split(/\r\n|\r|\n/).filter(o=>o.length>0).map(o=>({path:o,workingDir:"P",vaultPath:this.getRelativeVaultPath(o)}))}else return[]}catch(r){this.convertErrors(r)}}async push(){this.plugin.setPluginState({gitAction:5});try{if(this.plugin.settings.updateSubmodules){let a=await this.git.subModule(["foreach","--recursive",`tracking=$(git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)"); echo $tracking; if [ ! -z "$(git diff --shortstat $tracking)" ]; then git push; fi`]);console.log(a)}let r=await this.git.status(),n=r.tracking,i=r.current;if(!n&&this.plugin.settings.updateSubmodules){this.plugin.log("No tracking branch found. Ignoring push of main repo and updating submodules only.");return}let s=null;return n&&(s=(await this.git.diffSummary([i,n,"--"])).changed),await this.git.push(),s}catch(r){this.convertErrors(r)}}async getUnpushedCommits(){let r=await this.git.status(),n=r.tracking,i=r.current;if(n==null||i==null)return 0;let[s,a]=Qi(n);return(await this.getRemoteBranches(s)).includes(n)?(await this.git.diffSummary([i,n,"--"])).changed:(this.plugin.log(`Tracking branch ${n} does not exist on remote ${s}.`),0)}async canPush(){if(this.plugin.settings.updateSubmodules===!0)return!0;let r=await this.git.status(),n=r.tracking,i=r.current;return n?(await this.git.diffSummary([i,n,"--"])).changed!==0:!1}async checkRequirements(){return await this.isGitInstalled()?await this.git.checkIsRepo()?"valid":"missing-repo":"missing-git"}async branchInfo(){let r=await this.git.status(),n=await this.git.branch(["--no-color"]);return{current:r.current||void 0,tracking:r.tracking||void 0,branches:n.all}}async getRemoteUrl(r){try{return await this.git.remote(["get-url",r])||void 0}catch(n){if(String(n).contains(r))return;throw n}}async log(r,n=!0,i,s){let a;r&&(a=this.getRelativeRepoPath(r,n));let o={file:a,maxCount:i,"--diff-merges":"first-parent","--name-status":null};return s&&(o[s]=null),(await this.git.log(o)).all.map(c=>{var u,f,d,h;return{...c,author:{name:c.author_name,email:c.author_email},refs:c.refs.split(", ").filter(m=>m.length>0),diff:{...c.diff,files:(f=(u=c.diff)==null?void 0:u.files.map(m=>({...m,status:m.status,path:m.file,hash:c.hash,vaultPath:this.getRelativeVaultPath(m.file),fromPath:m.from,fromVaultPath:m.from!=null?this.getRelativeVaultPath(m.from):void 0,binary:m.binary})))!=null?f:[]},fileName:(h=(d=c.diff)==null?void 0:d.files.first())==null?void 0:h.file}})}async show(r,n,i=!0){let s=this.getRelativeRepoPath(n,i);return this.git.show([r+":"+s])}async getLocalBranchUpstream(r){try{let i=(await this.git.raw(["rev-parse","--abbrev-ref",`${r}@{upstream}`])).trim();return i.length>0?i:void 0}catch(n){return}}getAvailableLocalBranchName(r,n,i){let s=r;if(!i.includes(s))return s;let a=`${r}-${n}`,o=a,l=0;for(;i.includes(o);)l+=1,o=`${a}-${l}`;return o}async checkout(r,n){if(n){let i=`${n}/${r}`,s=await this.branchInfo();if(s.branches.includes(r)&&await this.getLocalBranchUpstream(r)===i)await this.git.checkout(r);else{let l=this.getAvailableLocalBranchName(r,n,s.branches);await this.git.checkout(["-b",l,i])}}else await this.git.checkout(r);if(this.plugin.settings.submoduleRecurseCheckout){let i=await this.getSubmodulePaths();for(let s of i){let a=await this.git.cwd({path:s,root:!1}).branch();Object.keys(a.branches).includes(r)&&await this.git.cwd({path:s,root:!1}).checkout(r)}}}async createBranch(r){await this.git.checkout(["-b",r])}async deleteBranch(r,n){await this.git.branch([n?"-D":"-d",r])}async branchIsMerged(r){return!(await this.git.branch(["--no-merged"])).all.contains(r)}async init(){await this.git.init(!1)}async clone(r,n,i){await this.git.clone(r,Ue.join(this.app.vault.adapter.getBasePath(),n),i?["--depth",`${i}`]:[]),await this.setGitInstance()}async setConfig(r,n){n==null?await this.git.raw(["config","--local","--unset",r]):await this.git.addConfig(r,n)}async getConfig(r,n="local"){var s;return(s=(await this.git.getConfig(r.toLowerCase(),n=="all"?void 0:n)).value)!=null?s:void 0}async fetch(r){await this.git.fetch(r!=null?[r]:[])}async setRemote(r,n){(await this.getRemotes()).includes(r)?await this.git.remote(["set-url",r,n]):await this.git.remote(["add",r,n])}async getRemoteBranches(r){let n=await this.git.branch(["-r","--list",`${r}*`]),i=[];for(let s in n.branches)i.push(n.branches[s].name);return i}async getRemotes(){let r=await this.git.remote([]);return r?r.trim().split(` +`):[]}async removeRemote(r){await this.git.removeRemote(r)}async updateUpstreamBranch(r){try{await this.git.branch(["--set-upstream-to",r])}catch(n){try{await this.git.branch(["--set-upstream",r])}catch(i){let[s,a]=Qi(r),o=await this.branchInfo();await this.git.push(["--set-upstream",s,`${o.current}:${a}`])}}}updateGitPath(r){return this.setGitInstance()}updateBasePath(r){return this.setGitInstance(!0)}async getDiffString(r,n=!1,i){return n?await this.git.diff(["--cached","--",r]):i?await this.git.show([`${i}`,"--",r]):await this.git.diff(["--",r])}async diff(r,n,i){return await this.git.diff([`${n}..${i}`,"--",r])}async rawCommand(r){let n=r.split(" ");return await this.git.raw(n[0],...n.slice(1))}async getSubmoduleOfFile(r){if(!await this.app.vault.adapter.exists(Ue.dirname(r)))return;let n=await this.git.raw(["-C",Ue.dirname(r),"rev-parse","--show-toplevel"],l=>l&&console.warn("get-submodule-of-file",l==null?void 0:l.message));if(n=n.trim(),(await this.git.raw(["-C",Ue.dirname(r),"rev-parse","--show-superproject-working-tree"],l=>l&&console.warn("get-submodule-of-file",l==null?void 0:l.message))).trim()==="")return;let a=this.app.vault.adapter.getFullPath(Ue.normalize(r)),o=Ue.relative(n,a);return{submodule:n,relativeFilepath:o}}async getLastCommitTime(){try{let r=await this.git.log({n:1});if(r!=null&&r.latest!=null)return new Date(r.latest.date)}catch(r){if(r instanceof Pr){if(r.message.contains("does not have any commits yet"))return}else throw r}}async isGitInstalled(){let r=this.plugin.localStorage.getGitPath(),n=await $u(r||"git",["--version"],{});if(n.error)if(Ji.Platform.isWin&&!r){this.plugin.log(`Git not found in PATH. Checking standard installation path(${Wd}) of Git for Windows.`);let i=await $u(Wd,["--version"]);if(i.error)return console.error(i.error),!1;this.useDefaultWindowsGitPath=!0}else return console.error(n.error),!1;else this.useDefaultWindowsGitPath=!1;return!0}convertErrors(r){if(r instanceof Pr){let n=String(r.message);if(n.contains("Could not resolve host")||n.contains("Unable to resolve host")||n.contains("Unable to open connection")||n.match(/ssh: connect to host .*? port .*?: Operation timed out/)!=null||n.match(/ssh: connect to host .*? port .*?: Network is unreachable/)!=null||n.match(/ssh: connect to host .*? port .*?: Undefined error: 0/)!=null)throw new ul(n)}throw r}async isFileTrackedByLFS(r){try{return(await this.git.raw(["check-attr","filter",r])).includes("filter: lfs")}catch(n){let i=n instanceof Error?n.message:String(n);return this.plugin.displayError(`Error checking LFS status: ${i}`),!1}}},iF={hash:"000000",isZeroCommit:!0,summary:""};function xz(t){let r=t.replace(`\r +`,` +`).split(` +`),n={commits:new Map,hashPerLine:[void 0],originalFileLineNrPerLine:[void 0],finalFileLineNrPerLine:[void 0],groupSizePerStartingLine:new Map},i=1;for(let s=0;s=4&&r.groupSizePerStartingLine.set(e,parseInt(t[3])),parseInt(t[2])!==e)throw Error(`git-blame output is out of order: ${e} vs ${t[2]}`);return n}function Ez(t,e,r){let n=t[0],i=t.slice(1).join(" "),s=e.hashPerLine[r],a=e.commits.get(s)||{hash:s,author:{},committer:{},previous:{}};switch(n){case"summary":a.summary=i;break;case"author":a.author.name=i;break;case"author-mail":a.author.email=rF(i);break;case"author-time":a.author.epochSeconds=parseInt(i);break;case"author-tz":a.author.tz=i;break;case"committer":a.committer.name=i;break;case"committer-mail":a.committer.email=rF(i);break;case"committer-time":a.committer.epochSeconds=parseInt(i);break;case"committer-tz":a.committer.tz=i;break;case"previous":a.previous.commitHash=i;break;case"filename":a.previous.filename=i;break}e.commits.set(s,a)}function kz(t){if(t.summary===void 0)throw Error(`Summary not provided for commit: ${t.hash}`);W0(t.author)&&(t.author=void 0),W0(t.committer)&&(t.committer=void 0),W0(t.previous)&&(t.previous=void 0),t.isZeroCommit=!!t.hash.match(/^0*$/)}function W0(t){return!t||Object.keys(t).length===0}function tF(t){return t.length>0&&t[0].trim()===t[0]}function rF(t){let e=t.startsWith("<")?t.substring(1):t;return e.endsWith(">")?e.substring(0,e.length-1):e}p();var PF=require("@codemirror/state");p();var z0=class{constructor(){this.eventsPerFilepath=new Map;this.startRemoveStalesSubscribersInterval()}ifFilepathDefinedTransformSubscribers(e,r){if(e)return this.ensureInitialized(e),r(this.eventsPerFilepath.get(e))}forEachSubscriber(e){this.eventsPerFilepath.forEach(r=>r.forEach(e))}ensureInitialized(e){this.eventsPerFilepath.get(e)||this.eventsPerFilepath.set(e,new Set)}startRemoveStalesSubscribersInterval(){this.removeStalesSubscribersTimer=window.setInterval(()=>this==null?void 0:this.forEachSubscriber(e=>e==null?void 0:e.removeIfStale()),6e4)}clear(){window.clearInterval(this.removeStalesSubscribersTimer),this.eventsPerFilepath.clear()}},es=new z0;p();var Zh=require("@codemirror/state"),sF=Ct(V0());function aF(t,e,r){if(!(t===void 0||e===void 0||r===void 0))return`head${t}-obj${e}-path${r}`}var oF=Zh.StateEffect.define();function lF(t,e,r){return r.update({effects:oF.of({key:t,la:e,lineOffsetsFromUnsavedChanges:new Map})})}var $l=Zh.StateField.define({create:t=>{},update:(t,e)=>{for(let r of e.effects)if(r.is(oF))return r.value;return Az(e,t)},compare:(t,e)=>(t==null?void 0:t.key)===(e==null?void 0:e.key)});function Kh(t){var s;let e=sF.sha256.create();if(!t)return e;let{la:r,key:n,lineOffsetsFromUnsavedChanges:i}=t;e.update(r==="untracked"?"t":"f"),e.update(n);for(let[a,o]of(s=i.entries())!=null?s:[])e.update([a,o]);return e}var xn={get:void 0,save:void 0};function cF(t,e){xn.get=t,xn.save=e}function Qh(t){var e,r;return(r=(e=Xh(t.coloringMaxAge))==null?void 0:e.asDays())!=null?r:Xh(et.lineAuthor.coloringMaxAge).asDays()}function Az(t,e){if(e)return t.changes.empty||t.changes.iterChanges((r,n,i,s)=>{var m;let a=t.startState.doc,{newDoc:o}=t,l=a.lineAt(r).number,c=a.lineAt(n).number,u=o.lineAt(i).number,f=o.lineAt(s).number,d=c-l+1,h=f-u+1;for(let g=u;g<=f;g++){let v=(m=e.lineOffsetsFromUnsavedChanges.get(g))!=null?m:0,w=f===g,b=h-d;w&&(v+=b),e.lineOffsetsFromUnsavedChanges.set(g,v)}}),e}p();function uF(){Il=void 0,Y0=[],Jh=0,tp.clear(),rp.clear(),Fl.clear()}var Il,ep=()=>Il;function fF(t,e){var i;let r=e.length;if(r<((i=Il==null?void 0:Il.length)!=null?i:0))return;Il={gutter:t,length:r,text:e};let n=xn.get();r!==n.gutterSpacingFallbackLength&&(n.gutterSpacingFallbackLength=r,xn.save(n))}var Y0=[],Cz=15,Jh=0;function dF(t){Y0[Jh]=t,Jh=(Jh+1)%Cz}function hF(){return XP(Y0)}var tp=new Map,rp=new Map,Fl=new Set;p();var AF=require("@codemirror/state"),CF=require("@codemirror/view");p();var Q0=require("@codemirror/view"),xF=Ct(V0()),Ol=require("obsidian");p();p();var np={x:-10,y:-10};function pF(){np.x===-10&&window.addEventListener("mousedown",t=>{np.x=t.clientX,np.y=t.clientY})}function mF(){for(let t of Fl)if(Tz(t,np))return t}function Tz(t,e){let{x:r,y:n,width:i,height:s}=t.getBoundingClientRect();return r<=e.x&&e.x<=r+i&&n<=e.y&&e.y<=n+s}var gF="data-commit";function vF(t,e,r){if(e.hasFocus())return;let n=mF();if(!n)return;let i=Rz(n);i&&(!i.isZeroCommit&&!i.isWaitingGutter&&Pz(i,t),X0("showCommitHash",t),X0("authorDisplay",t),X0("dateTimeFormatOptions",t))}function Pz(t,e){e.addItem(r=>r.setTitle("Copy commit hash").setIcon("copy").setSection("obs-git-line-author-copy").onClick(n=>navigator.clipboard.writeText(t.hash)))}function X0(t,e){var l,c;let r,n,i=Ln.plugin.settings.lineAuthor,s=i[t],a=typeof s=="boolean"?s:s!=="hide",o=et.lineAuthor[t];if(t==="showCommitHash")r="Show commit hash",n=s;else if(t==="authorDisplay"){let u=(l=i.lastShownAuthorDisplay)!=null?l:o;r="Show author "+(a?s:u),n=a?"hide":u}else if(t==="dateTimeFormatOptions"){let u=(c=i.lastShownDateTimeFormatOptions)!=null?c:o;r="Show "+(a?s:u),r+=r.contains("date")?"":" date",n=a?"hide":u}else js(t);e.addItem(u=>u.setTitle(r).setSection("obs-git-line-author-configure").setChecked(a).onClick(f=>{var d,h;return(h=(d=Ln.plugin)==null?void 0:d.settingsTab)==null?void 0:h.lineAuthorSettingHandler(t,n)}))}function wF(t,e,r){r.setAttr(gF,JSON.stringify({hash:t.hash,isZeroCommit:t.isZeroCommit,isWaitingGutter:e}))}function Rz(t){let e=t.getAttr(gF);return e?JSON.parse(e):void 0}p();function sp(t,e){return t==="oldest"?ip(0,!1,e).color:ip(void 0,!0,e).color}function ip(t,e,r){let n=Qh(r),i=Date.now()/1e3,s=t!=null?t:0,o=(e?0:i-s)/60/60/24,l=Math.pow(Math.clamp(o/n,0,1),1/2.3),c=$z(),u=r.colorNew,f=r.colorOld,d=c?.4:1,h=Z0(u.r,f.r,l)*d,m=Z0(u.g,f.g,l)*d,g=Z0(u.b,f.b,l)*d;return{color:`rgba(${h},${m},${g},${c?.75:.25})`,daysSinceCommit:o}}function Z0(t,e,r){return t+(e-t)*r}function $z(){var t;return((t=window.app)==null?void 0:t.getTheme())==="obsidian"}function yF(t){document.body.style.setProperty("--obs-git-gutter-text",t.textColorCss)}p();function bF(t,e,r){let n;for(let i=e;i<=r;i++){let s=t.hashPerLine[i],a=t.commits.get(s);(!n||a.isZeroCommit||Iz(a,n))&&(n=a)}return n}function Iz(t,e){var i,s,a,o;let r=(s=(i=t.author)==null?void 0:i.epochSeconds)!=null?s:0,n=(o=(a=e.author)==null?void 0:a.epochSeconds)!=null?o:0;return r>n}var _F="-",Fz="+",Oz=3,Mz="*",Dz=/\S/g,Lz="%",Ml=class t extends Q0.GutterMarker{constructor(r){super();this.text=r}eq(r){return r instanceof t&&this.text===r.text}toDOM(){return document.createTextNode(this.text)}destroy(r){}},K0=class extends Q0.GutterMarker{constructor(r,n,i,s,a,o){super();this.lineAuthoring=r;this.startLine=n;this.endLine=i;this.key=s;this.settings=a;this.options=o;this.point=!1;this.elementClass="obs-git-blame-gutter"}eq(r){return this.key===(r==null?void 0:r.key)&&this.startLine===(r==null?void 0:r.startLine)&&this.endLine===(r==null?void 0:r.endLine)&&(this==null?void 0:this.options)===(r==null?void 0:r.options)}toDOM(){var r;return this.precomputedDomProvider=(r=this.precomputedDomProvider)!=null?r:this.computeDom(),this.precomputedDomProvider()}destroy(r){r&&(document.body.contains(r)||Fl.delete(r))}computeDom(){let r=bF(this.lineAuthoring,this.startLine,this.endLine),n=r.isZeroCommit?"":this.renderNonZeroCommit(r);return!r.isZeroCommit&&this.options!=="waiting-for-result"?fF(this,n):n=this.adaptTextForFakeCommit(r,n,this.options),this.createHtmlNode(r,n,this.options==="waiting-for-result")}createHtmlNode(r,n,i){var c,u,f,d,h,m;let s=window.createDiv();s.setText(n);let{color:a,daysSinceCommit:o}=ip((c=r==null?void 0:r.author)==null?void 0:c.epochSeconds,r==null?void 0:r.isZeroCommit,this.settings);s.style.backgroundColor=a,s.setAttribute("data-author",(f=(u=r==null?void 0:r.author)==null?void 0:u.name)!=null?f:""),s.setAttribute("data-author-email",(h=(d=r==null?void 0:r.author)==null?void 0:d.email)!=null?h:""),(0,Ol.setTooltip)(s,(m=r==null?void 0:r.summary)!=null?m:""),wF(r,i,s);function l(){let g=s.cloneNode(!0);return Fl.add(g),i||dF(o),g}return l}renderNonZeroCommit(r){let n=this.settings.showCommitHash?this.renderHash(r):"",i=this.settings.authorDisplay==="hide"?"":`${this.renderAuthorName(r,this.settings.authorDisplay)}`,s=this.settings.dateTimeFormatOptions==="hide"?"":`${this.renderAuthoringDate(r,this.settings.dateTimeFormatOptions,this.settings.dateTimeFormatCustomString,this.settings.dateTimeTimezone)}`;return[n,i,s].filter(o=>o.length>=1).join(" ")}renderHash(r){return r.hash.substring(0,6)}renderAuthorName(r,n){var o,l,c,u;let i=(l=(o=r==null?void 0:r.author)==null?void 0:o.name)!=null?l:"",s=i.split(" ").filter(f=>f.length>=1),a;switch(n){case"initials":a=s.map(f=>f[0].toUpperCase()).join("");break;case"first name":a=(c=s.first())!=null?c:_F;break;case"last name":a=(u=s.last())!=null?u:_F;break;case"full":a=i;break;default:return js(n)}return ZP(r==null?void 0:r.author,r==null?void 0:r.committer)||(a=a+Mz),a}renderAuthoringDate(r,n,i,s){var c;let a="?";if(((c=r==null?void 0:r.author)==null?void 0:c.epochSeconds)===void 0)return a;let o;switch(n){case"date":o=jd;break;case"datetime":o=Rv;break;case"custom":o=i;break;case"natural language":o=u=>{let f=u.diff((0,Ol.moment)());return Ol.moment.duration(f).humanize(!0)};break;default:return js(n)}let l=Ol.moment.unix(r.author.epochSeconds);switch(s){case"viewer-local":break;case"author-local":l=l.utcOffset(r.author.tz),typeof o=="string"&&(o+=" Z");break;case"utc0000":l=l.utc(),typeof o=="string"&&(o+="[Z]");break;default:return js(s)}return typeof o=="string"?l.format(o):o(l)}adaptTextForFakeCommit(r,n,i){var l,c,u,f;let s=(c=(l=ep())==null?void 0:l.text)!=null?c:n,a=i!=="waiting-for-result"&&r.isZeroCommit?Fz:Lz;n=s.replace(Dz,a);let o=(f=(u=xn.get())==null?void 0:u.gutterSpacingFallbackLength)!=null?f:n.length;if(n=KP(n,o,a),i!=="waiting-for-result"&&r.isZeroCommit){let d=Math.min(o,Oz);n=QP(n,o-d)}return n}};function La(t,e,r,n,i,s){let a=xF.sha256.create();a.update(JSON.stringify(i)),a.update(`s${e}-e${r}-k${n}-o${s}`);let o=a.hex(),l=tp.get(o);if(l)return l;let c=new K0(t,e,r,n,i,s);return tp.set(o,c),c}p();var SF=require("obsidian");function J0(){var e,r;let t=(r=(e=xn.get())==null?void 0:e.gutterSpacingFallbackLength)!=null?r:et.lineAuthor.gutterSpacingFallbackLength;return new Ml(Array(t).fill("-").join(""))}function ey(t){let{lineAuthoring:e,ageForInitialRender:r}=Nz(t);return La(e,1,1,"initialGutter"+r,t,"waiting-for-result")}function Nz(t){var s;let e=(s=hF())!=null?s:Qh(t)*.25,r=(0,SF.moment)().add(-e,"days"),n={name:"",epochSeconds:YP(r),tz:"+0000"},i={hash:"waiting-for-result",author:n,committer:n,isZeroCommit:!1};return{lineAuthoring:{hashPerLine:[void 0,"waiting-for-result"],commits:new Map([["waiting-for-result",i]])},ageForInitialRender:e}}p();function EF(t,e){return La({hashPerLine:[void 0,"000000"],commits:new Map([["000000",iF]])},1,1,t,e)}var ty=new Ml(""),TF=(0,CF.gutter)({class:"line-author-gutter-container",markers(t){let e=t.state.field($l,!1);return Bz(t,e)},lineMarkerChange(t){let e=Kh(t.state.field($l));return Kh(t.startState.field($l))!==e},renderEmptyElements:!0,initialSpacer:t=>(kF(t),J0()),updateSpacer:(t,e)=>{var r,n;return kF(e.view),(n=(r=ep())==null?void 0:r.gutter)!=null?n:J0()}});function Bz(t,e){let r=Kh(e),n=t.state.doc,i=new Map;for(let u=1;u<=n.lines;u++){let f=n.line(u).from,d=t.lineBlockAt(f).to;i.set(u,[f,d]),r.update([f,d,0])}let s=xn.get();r.update("s"+Object.values(xn).join(","));let a=r.hex(),o=rp.get(a);if(o)return o;let{result:l,allowCache:c}=Hz(n,i,s,e);return c&&rp.set(a,l),l}function Hz(t,e,r,n){let i=!0,s=t.lines,a=[];function o(f,d,h){return a.push(h.range(f,d))}let l=Uz(s,n),c=t.length===0,u=t.iterLines(s,s+1).next().value==="";for(let f=1;f<=s;f++){let[d,h]=e.get(f),m=t.lineAt(h).number;if(c){o(d,h,ty);continue}if(f===s&&u){o(d,h,ty);continue}if(n===void 0){o(d,h,ey(r)),i=!1;continue}let{key:g,la:v}=n;if(v==="untracked"){o(d,h,EF(v,r));continue}let w=v.hashPerLine.length-1,b=l[f],k=l[m];if(k&&k>w&&o(d,h,ty),b!==void 0&&Zw(1,b,w)&&k!==void 0&&Zw(1,k,w)){o(d,h,La(v,b,k,g,r));continue}if(w<1){o(d,h,ey(r)),i=!1;continue}let x=Math.clamp(b!=null?b:f,1,w),E=Math.clamp(k!=null?k:m,1,w);o(d,h,La(v,x,E,g+"computing",r,"waiting-for-result"))}return{result:AF.RangeSet.of(a,!0),allowCache:i}}function Uz(t,e){if(!(e!=null&&e.lineOffsetsFromUnsavedChanges))return Array.from(new Array(t+1),i=>i);let r=[void 0],n=0;for(let i=1;i<=t;i++){let s=e.lineOffsetsFromUnsavedChanges.get(i);n+=s!=null?s:0,r[i]=s===void 0?i-n:void 0}return r}function kF(t){t.dom.querySelectorAll(".cm-gutters").forEach(r=>{r!=null&&r.style&&(r.style.marginLeft||(r.style.marginLeft="unset"))})}var ap=class{constructor(e){this.plugin=e;this.lineAuthorings=new Map}async trackChanged(e){return this.trackChangedHelper(e).catch(r=>(console.warn("Git: Error in trackChanged."+r),Promise.reject(r)))}async trackChangedHelper(e){if(e){if(e.path===void 0){console.warn("Git: Attempted to track change of undefined filepath. Unforeseen situation.");return}return this.computeLineAuthorInfo(e.path)}}destroy(){this.lineAuthorings.clear(),uF()}async computeLineAuthorInfo(e){let r=this.plugin.editorIntegration.lineAuthoringFeature.isAvailableOnCurrentPlatform().gitManager,n=await r.submoduleAwareHeadRevisonInContainingDirectory(e),i=await r.hashObject(e),s=aF(n,i,e);if(s!==void 0){if(!this.lineAuthorings.has(s)){let a=await r.blame(e,this.plugin.settings.lineAuthor.followMovement,this.plugin.settings.lineAuthor.ignoreWhitespace);this.lineAuthorings.set(s,a)}this.notifyComputationResultToSubscribers(e,s)}}notifyComputationResultToSubscribers(e,r){es.ifFilepathDefinedTransformSubscribers(e,n=>n.forEach(i=>i.notifyLineAuthoring(r,this.lineAuthorings.get(r))))}},RF=PF.Prec.high([$l,TF]);var Gz="https://momentjs.com/docs/#/parsing/string-format/",jz="https://publish.obsidian.md/git-doc/Line+Authoring",op=class extends U.PluginSettingTab{constructor(r,n){super(r,n);this.plugin=n;this.lineAuthorColorSettings=new Map;this.icon="git-pull-request"}get settings(){return this.plugin.settings}display(){let{containerEl:r}=this,n=this.plugin,i;n.settings.differentIntervalCommitAndPush?i="commit":i="commit-and-sync";let s=n.gitReady;r.empty(),s||(r.createEl("p",{text:"Git is not ready. When all settings are correct you can configure commit-sync, etc."}),r.createEl("br"));let a;if(s){new U.Setting(r).setName("Automatic").setHeading(),new U.Setting(r).setName("Split timers for automatic commit and sync").setDesc("Enable to use one interval for commit and another for sync.").addToggle(f=>f.setValue(n.settings.differentIntervalCommitAndPush).onChange(async d=>{n.settings.differentIntervalCommitAndPush=d,await n.saveSettings(),n.automaticsManager.reload("commit","push"),this.refreshDisplayWithDelay()})),new U.Setting(r).setName(`Auto ${i} interval (minutes)`).setDesc(`${n.settings.differentIntervalCommitAndPush?"Commit":"Commit and sync"} changes every X minutes. Set to 0 (default) to disable. (See below setting for further configuration!)`).addText(f=>{f.inputEl.type="number",this.setNonDefaultValue({text:f,settingsProperty:"autoSaveInterval"}),f.setPlaceholder(String(et.autoSaveInterval)),f.onChange(async d=>{d!==""?n.settings.autoSaveInterval=Number(d):n.settings.autoSaveInterval=et.autoSaveInterval,await n.saveSettings(),n.automaticsManager.reload("commit")})}),a=new U.Setting(r).setName(`Auto ${i} after stopping file edits`).setDesc(`Requires the ${i} interval not to be 0. + If turned on, do auto ${i} every ${JP(n.settings.autoSaveInterval)} after stopping file edits. + This also prevents auto ${i} while editing a file. If turned off, it's independent from the last file edit.`).addToggle(f=>f.setValue(n.settings.autoBackupAfterFileChange).onChange(async d=>{n.settings.autoBackupAfterFileChange=d,this.refreshDisplayWithDelay(),await n.saveSettings(),n.automaticsManager.reload("commit")})),this.mayDisableSetting(a,n.settings.setLastSaveToLastCommit),a=new U.Setting(r).setName(`Auto ${i} after latest commit`).setDesc(`If turned on, sets last auto ${i} timestamp to the latest commit timestamp. This reduces the frequency of auto ${i} when doing manual commits.`).addToggle(f=>f.setValue(n.settings.setLastSaveToLastCommit).onChange(async d=>{n.settings.setLastSaveToLastCommit=d,await n.saveSettings(),n.automaticsManager.reload("commit"),this.refreshDisplayWithDelay()})),this.mayDisableSetting(a,n.settings.autoBackupAfterFileChange),a=new U.Setting(r).setName("Auto push interval (minutes)").setDesc("Push commits every X minutes. Set to 0 (default) to disable.").addText(f=>{f.inputEl.type="number",this.setNonDefaultValue({text:f,settingsProperty:"autoPushInterval"}),f.setPlaceholder(String(et.autoPushInterval)),f.onChange(async d=>{d!==""?n.settings.autoPushInterval=Number(d):n.settings.autoPushInterval=et.autoPushInterval,await n.saveSettings(),n.automaticsManager.reload("push")})}),this.mayDisableSetting(a,!n.settings.differentIntervalCommitAndPush),new U.Setting(r).setName("Auto pull interval (minutes)").setDesc("Pull changes every X minutes. Set to 0 (default) to disable.").addText(f=>{f.inputEl.type="number",this.setNonDefaultValue({text:f,settingsProperty:"autoPullInterval"}),f.setPlaceholder(String(et.autoPullInterval)),f.onChange(async d=>{d!==""?n.settings.autoPullInterval=Number(d):n.settings.autoPullInterval=et.autoPullInterval,await n.saveSettings(),n.automaticsManager.reload("pull")})}),new U.Setting(r).setName(`Auto ${i} only staged files`).setDesc(`If turned on, only staged files are committed on ${i}. If turned off, all changed files are committed.`).addToggle(f=>f.setValue(n.settings.autoCommitOnlyStaged).onChange(async d=>{n.settings.autoCommitOnlyStaged=d,await n.saveSettings()})),new U.Setting(r).setName(`Specify custom commit message on auto ${i}`).setDesc("You will get a pop up to specify your message.").addToggle(f=>f.setValue(n.settings.customMessageOnAutoBackup).onChange(async d=>{n.settings.customMessageOnAutoBackup=d,await n.saveSettings(),this.refreshDisplayWithDelay()})),a=new U.Setting(r).setName(`Commit message on auto ${i}`).setDesc("Available placeholders: {{date}} (see below), {{hostname}} (see below), {{numFiles}} (number of changed files in the commit) and {{files}} (changed files in commit message).").addTextArea(f=>{f.setPlaceholder(et.autoCommitMessage).onChange(async d=>{d===""?n.settings.autoCommitMessage=et.autoCommitMessage:n.settings.autoCommitMessage=d,await n.saveSettings()}),this.setNonDefaultValue({text:f,settingsProperty:"autoCommitMessage"})}),this.mayDisableSetting(a,n.settings.customMessageOnAutoBackup),new U.Setting(r).setName("Commit message").setHeading();let c=new U.Setting(r).setName("Commit message on manual commit").setDesc("Available placeholders: {{date}} (see below), {{hostname}} (see below), {{numFiles}} (number of changed files in the commit) and {{files}} (changed files in commit message). Leave empty to require manual input on each commit.");c.addTextArea(f=>{c.addButton(d=>{d.setIcon("reset").setTooltip(`Set to default: "${et.commitMessage}"`).onClick(()=>{f.setValue(et.commitMessage),f.onChanged()})}),f.setValue(n.settings.commitMessage),f.onChange(async d=>{n.settings.commitMessage=d,await n.saveSettings()})}),U.Platform.isDesktopApp&&new U.Setting(r).setName("Commit message script").setDesc("A script that is run using 'sh -c' to generate the commit message. May be used to generate commit messages using AI tools. Available placeholders: {{hostname}}, {{date}}.").addText(f=>{f.onChange(async d=>{d===""?n.settings.commitMessageScript=et.commitMessageScript:n.settings.commitMessageScript=d,await n.saveSettings()}),this.setNonDefaultValue({text:f,settingsProperty:"commitMessageScript"})});let u=new U.Setting(r).setName("{{date}} placeholder format").addMomentFormat(f=>f.setDefaultFormat(n.settings.commitDateFormat).setValue(n.settings.commitDateFormat).onChange(async d=>{n.settings.commitDateFormat=d,await n.saveSettings()}));u.descEl.innerHTML=` + Specify custom date format. E.g. "${$v}. See Moment.js for more formats.`,new U.Setting(r).setName("{{hostname}} placeholder replacement").setDesc("Specify custom hostname for every device. Defaults to the OS hostname if not set on desktop.").addText(f=>{var d;return f.setValue((d=n.localStorage.getHostname())!=null?d:"").onChange(h=>{n.localStorage.setHostname(h)})}),new U.Setting(r).setName("Preview commit message").addButton(f=>f.setButtonText("Preview").onClick(async()=>{let d=await n.gitManager.formatCommitMessage(n.settings.commitMessage);new U.Notice(`${d}`)})),new U.Setting(r).setName("List filenames affected by commit in the commit body").addToggle(f=>f.setValue(n.settings.listChangedFilesInMessageBody).onChange(async d=>{n.settings.listChangedFilesInMessageBody=d,await n.saveSettings()})),new U.Setting(r).setName("Pull").setHeading(),n.gitManager instanceof Se&&new U.Setting(r).setName("Merge strategy").setDesc("Decide how to integrate commits from your remote branch into your local branch.").addDropdown(f=>{let d={merge:"Merge",rebase:"Rebase",reset:"Other sync service (Only updates the HEAD without touching the working directory)"};f.addOptions(d),f.setValue(n.settings.syncMethod),f.onChange(async h=>{n.settings.syncMethod=h,await n.saveSettings()})}),new U.Setting(r).setName("Merge strategy on conflicts").setDesc("Decide how to solve conflicts when pulling remote changes. This can be used to favor your local changes or the remote changes automatically.").addDropdown(f=>{let d={none:"None (git default)",ours:"Our changes",theirs:"Their changes"};f.addOptions(d),f.setValue(n.settings.mergeStrategy),f.onChange(async h=>{n.settings.mergeStrategy=h,await n.saveSettings()})}),new U.Setting(r).setName("Pull on startup").setDesc("Automatically pull commits when Obsidian starts.").addToggle(f=>f.setValue(n.settings.autoPullOnBoot).onChange(async d=>{n.settings.autoPullOnBoot=d,await n.saveSettings()})),new U.Setting(r).setName("Commit-and-sync").setDesc("Commit-and-sync with default settings means staging everything -> committing -> pulling -> pushing. Ideally this is a single action that you do regularly to keep your local and remote repository in sync.").setHeading(),a=new U.Setting(r).setName("Push on commit-and-sync").setDesc(`Most of the time you want to push after committing. Turning this off turns a commit-and-sync action into commit ${n.settings.pullBeforePush?"and pull ":""}only. It will still be called commit-and-sync.`).addToggle(f=>f.setValue(!n.settings.disablePush).onChange(async d=>{n.settings.disablePush=!d,this.refreshDisplayWithDelay(),await n.saveSettings()})),new U.Setting(r).setName("Pull on commit-and-sync").setDesc(`On commit-and-sync, pull commits as well. Turning this off turns a commit-and-sync action into commit ${n.settings.disablePush?"":"and push "}only.`).addToggle(f=>f.setValue(n.settings.pullBeforePush).onChange(async d=>{n.settings.pullBeforePush=d,this.refreshDisplayWithDelay(),await n.saveSettings()})),n.gitManager instanceof Se&&(new U.Setting(r).setName("Hunk management").setDesc("Hunks are sections of grouped line changes right in your editor.").setHeading(),new U.Setting(r).setName("Signs").setDesc("This allows you to see your changes right in your editor via colored markers and stage/reset/preview individual hunks.").addToggle(f=>f.setValue(n.settings.hunks.showSigns).onChange(async d=>{n.settings.hunks.showSigns=d,await n.saveSettings(),n.editorIntegration.refreshSignsSettings()})),new U.Setting(r).setName("Hunk commands").setDesc("Adds commands to stage/reset individual Git diff hunks and navigate between them via 'Go to next/prev hunk' commands.").addToggle(f=>f.setValue(n.settings.hunks.hunkCommands).onChange(async d=>{n.settings.hunks.hunkCommands=d,await n.saveSettings(),n.editorIntegration.refreshSignsSettings()})),new U.Setting(r).setName("Status bar with summary of line changes").addDropdown(f=>f.addOptions({disabled:"Disabled",colored:"Colored",monochrome:"Monochrome"}).setValue(n.settings.hunks.statusBar).onChange(async d=>{n.settings.hunks.statusBar=d,await n.saveSettings(),n.editorIntegration.refreshSignsSettings()})),new U.Setting(r).setName("Line author information").setHeading(),this.addLineAuthorInfoSettings())}new U.Setting(r).setName("History view").setHeading(),new U.Setting(r).setName("Show Author").setDesc("Show the author of the commit in the history view.").addDropdown(c=>{let u={hide:"Hide",full:"Full",initials:"Initials"};c.addOptions(u),c.setValue(n.settings.authorInHistoryView),c.onChange(async f=>{n.settings.authorInHistoryView=f,await n.saveSettings(),await n.refresh()})}),new U.Setting(r).setName("Show Date").setDesc("Show the date of the commit in the history view. The {{date}} placeholder format is used to display the date.").addToggle(c=>c.setValue(n.settings.dateInHistoryView).onChange(async u=>{n.settings.dateInHistoryView=u,await n.saveSettings(),await n.refresh()})),new U.Setting(r).setName("Source control view").setHeading(),new U.Setting(r).setName("Automatically refresh source control view on file changes").setDesc("On slower machines this may cause lags. If so, just disable this option.").addToggle(c=>c.setValue(n.settings.refreshSourceControl).onChange(async u=>{n.settings.refreshSourceControl=u,await n.saveSettings()})),new U.Setting(r).setName("Source control view refresh interval").setDesc("Milliseconds to wait after file change before refreshing the Source Control View.").addText(c=>{c.inputEl.type="number",this.setNonDefaultValue({text:c,settingsProperty:"refreshSourceControlTimer"}),c.setPlaceholder(String(et.refreshSourceControlTimer)),c.onChange(async f=>{f!==""&&Number.isInteger(Number(f))?n.settings.refreshSourceControlTimer=Math.max(Number(f),500):n.settings.refreshSourceControlTimer=et.refreshSourceControlTimer,await n.saveSettings(),n.setRefreshDebouncer()})}),new U.Setting(r).setName("Miscellaneous").setHeading(),n.gitManager instanceof Se&&new U.Setting(r).setName("Diff view style").setDesc('Set the style for the diff view. Note that the actual diff in "Split" mode is not generated by Git, but the editor itself instead so it may differ from the diff generated by Git. One advantage of this is that you can edit the text in that view.').addDropdown(c=>{let u={split:"Split",git_unified:"Unified"};c.addOptions(u),c.setValue(n.settings.diffStyle),c.onChange(async f=>{n.settings.diffStyle=f,await n.saveSettings()})}),new U.Setting(r).setName("Disable informative notifications").setDesc("Disable informative notifications for git operations to minimize distraction (refer to status bar for updates).").addToggle(c=>c.setValue(n.settings.disablePopups).onChange(async u=>{n.settings.disablePopups=u,this.refreshDisplayWithDelay(),await n.saveSettings()})),new U.Setting(r).setName("Disable error notifications").setDesc("Disable error notifications of any kind to minimize distraction (refer to status bar for updates).").addToggle(c=>c.setValue(!n.settings.showErrorNotices).onChange(async u=>{n.settings.showErrorNotices=!u,await n.saveSettings()})),n.settings.disablePopups||new U.Setting(r).setName("Hide notifications for no changes").setDesc("Don't show notifications when there are no changes to commit or push.").addToggle(c=>c.setValue(n.settings.disablePopupsForNoChanges).onChange(async u=>{n.settings.disablePopupsForNoChanges=u,await n.saveSettings()})),new U.Setting(r).setName("Show status bar").setDesc("Obsidian must be restarted for the changes to take affect.").addToggle(c=>c.setValue(n.settings.showStatusBar).onChange(async u=>{n.settings.showStatusBar=u,await n.saveSettings()})),new U.Setting(r).setName("File menu integration").setDesc('Add "Stage", "Unstage" and "Add to .gitignore" actions to the file menu.').addToggle(c=>c.setValue(n.settings.showFileMenu).onChange(async u=>{n.settings.showFileMenu=u,await n.saveSettings()})),new U.Setting(r).setName("Show branch status bar").setDesc("Obsidian must be restarted for the changes to take affect.").addToggle(c=>c.setValue(n.settings.showBranchStatusBar).onChange(async u=>{n.settings.showBranchStatusBar=u,await n.saveSettings()})),new U.Setting(r).setName("Show the count of modified files in the status bar").addToggle(c=>c.setValue(n.settings.changedFilesInStatusBar).onChange(async u=>{n.settings.changedFilesInStatusBar=u,await n.saveSettings()})),n.gitManager instanceof Hn?new U.Setting(r).setName("Authentication/commit author").setHeading():new U.Setting(r).setName("Commit author").setHeading(),n.gitManager instanceof Hn&&new U.Setting(r).setName("Username on your git server. E.g. your username on GitHub").addText(c=>{var u;c.setValue((u=n.localStorage.getUsername())!=null?u:""),c.onChange(f=>{n.localStorage.setUsername(f)})}),n.gitManager instanceof Hn&&new U.Setting(r).setName("Password/Personal access token").setDesc("Type in your password. You won't be able to see it again.").addText(c=>{c.inputEl.autocapitalize="off",c.inputEl.autocomplete="off",c.inputEl.spellcheck=!1,c.onChange(u=>{n.localStorage.setPassword(u)})}),n.gitReady&&new U.Setting(r).setName("Author name for commit").addText(async c=>{var u;c.setValue((u=await n.gitManager.getConfig("user.name"))!=null?u:""),c.onChange(async f=>{await n.gitManager.setConfig("user.name",f==""?void 0:f)})}),n.gitReady&&new U.Setting(r).setName("Author email for commit").addText(async c=>{var u;c.setValue((u=await n.gitManager.getConfig("user.email"))!=null?u:""),c.onChange(async f=>{await n.gitManager.setConfig("user.email",f==""?void 0:f)})}),new U.Setting(r).setName("Advanced").setDesc("These settings usually don't need to be changed, but may be required for special setups.").setHeading(),n.gitManager instanceof Se&&(new U.Setting(r).setName("Update submodules").setDesc('"Commit-and-sync" and "pull" takes care of submodules. Missing features: Conflicted files, count of pulled/pushed/committed files. Tracking branch needs to be set for each submodule.').addToggle(c=>c.setValue(n.settings.updateSubmodules).onChange(async u=>{n.settings.updateSubmodules=u,await n.saveSettings()})),n.settings.updateSubmodules&&new U.Setting(r).setName("Submodule recurse checkout/switch").setDesc("Whenever a checkout happens on the root repository, recurse the checkout on the submodules (if the branches exist).").addToggle(c=>c.setValue(n.settings.submoduleRecurseCheckout).onChange(async u=>{n.settings.submoduleRecurseCheckout=u,await n.saveSettings()}))),n.gitManager instanceof Se&&new U.Setting(r).setName("Custom Git binary path").setDesc("Specify the path to the Git binary/executable. Git should already be in your PATH. Should only be necessary for a custom Git installation.").addText(c=>{var u;c.setValue((u=n.localStorage.getGitPath())!=null?u:""),c.setPlaceholder("git"),c.onChange(f=>{n.localStorage.setGitPath(f),n.gitManager.updateGitPath(f||"git").catch(d=>n.displayError(d))})}),n.gitManager instanceof Se&&new U.Setting(r).setName("Additional environment variables").setDesc("Use each line for a new environment variable in the format KEY=VALUE .").addTextArea(c=>{c.setPlaceholder("GIT_DIR=/path/to/git/dir"),c.setValue(n.localStorage.getEnvVars().join(` +`)),c.onChange(u=>{n.localStorage.setEnvVars(u.split(` +`))})}),n.gitManager instanceof Se&&new U.Setting(r).setName("Additional PATH environment variable paths").setDesc("Use each line for one path").addTextArea(c=>{c.setValue(n.localStorage.getPATHPaths().join(` +`)),c.onChange(u=>{n.localStorage.setPATHPaths(u.split(` +`))})}),n.gitManager instanceof Se&&new U.Setting(r).setName("Reload with new environment variables").setDesc("Removing previously added environment variables will not take effect until Obsidian is restarted.").addButton(c=>{c.setButtonText("Reload"),c.setCta(),c.onClick(async()=>{await n.gitManager.setGitInstance()})}),new U.Setting(r).setName("Custom base path (Git repository path)").setDesc(` + Sets the relative path to the vault from which the Git binary should be executed. + Mostly used to set the path to the Git repository, which is only required if the Git repository is below the vault root directory. Use "\\" instead of "/" on Windows. + `).addText(c=>{c.setValue(n.settings.basePath),c.setPlaceholder("directory/directory-with-git-repo"),c.onChange(async u=>{n.settings.basePath=u,await n.saveSettings(),n.gitManager.updateBasePath(u||"").catch(f=>n.displayError(f))})}),new U.Setting(r).setName("Custom Git directory path (Instead of '.git')").setDesc('Corresponds to the GIT_DIR environment variable. Requires restart of Obsidian to take effect. Use "\\" instead of "/" on Windows.').addText(c=>{c.setValue(n.settings.gitDir),c.setPlaceholder(".git"),c.onChange(async u=>{n.settings.gitDir=u,await n.saveSettings()})}),new U.Setting(r).setName("Disable on this device").setDesc("Disables the plugin on this device. This setting is not synced.").addToggle(c=>c.setValue(n.localStorage.getPluginDisabled()).onChange(u=>{n.localStorage.setPluginDisabled(u),u?n.unloadPlugin():n.init({fromReload:!0}).catch(f=>n.displayError(f)),new U.Notice("Obsidian must be restarted for the changes to take affect.")})),new U.Setting(r).setName("Support").setHeading(),new U.Setting(r).setName("Donate").setDesc("If you like this Plugin, consider donating to support continued development.").addButton(c=>{c.buttonEl.outerHTML="Buy Me a Coffee at ko-fi.com"});let o=r.createDiv();o.setAttr("align","center"),o.setAttr("style","margin: var(--size-4-2)");let l=o.createEl("button");if(l.setText("Copy Debug Information"),l.onclick=async()=>{await window.navigator.clipboard.writeText(JSON.stringify({settings:this.plugin.settings,pluginVersion:this.plugin.manifest.version},null,4)),new U.Notice("Debug information copied to clipboard. May contain sensitive information!")},U.Platform.isDesktopApp){let c=r.createDiv();c.setAttr("align","center"),c.setText(`Debugging and logging: +You can always see the logs of this and every other plugin by opening the console with`);let u=r.createDiv();u.setAttr("align","center"),u.addClass("obsidian-git-shortcuts"),U.Platform.isMacOS===!0?u.createEl("kbd",{text:"CMD (\u2318) + OPTION (\u2325) + I"}):u.createEl("kbd",{text:"CTRL + SHIFT + I"})}}mayDisableSetting(r,n){n&&(r.setDisabled(n),r.setClass("obsidian-git-disabled"))}configureLineAuthorShowStatus(r){this.settings.lineAuthor.show=r,this.plugin.saveSettings(),r?this.plugin.editorIntegration.activateLineAuthoring():this.plugin.editorIntegration.deactiveLineAuthoring()}async lineAuthorSettingHandler(r,n){this.settings.lineAuthor[r]=n,await this.plugin.saveSettings(),this.plugin.editorIntegration.lineAuthoringFeature.refreshLineAuthorViews()}beforeSaveSettings(){let r=this.settings.lineAuthor;r.authorDisplay!=="hide"&&(r.lastShownAuthorDisplay=r.authorDisplay),r.dateTimeFormatOptions!=="hide"&&(r.lastShownDateTimeFormatOptions=r.dateTimeFormatOptions)}addLineAuthorInfoSettings(){let r=new U.Setting(this.containerEl).setName("Show commit authoring information next to each line");if(this.plugin.editorIntegration.lineAuthoringFeature.isAvailableOnCurrentPlatform()||r.setDesc("Only available on desktop currently.").setDisabled(!0),r.descEl.innerHTML=` + Feature guide and quick examples
+ The commit hash, author name and authoring date can all be individually toggled.
Hide everything, to only show the age-colored sidebar.`,r.addToggle(n=>n.setValue(this.settings.lineAuthor.show).onChange(i=>{this.configureLineAuthorShowStatus(i),this.refreshDisplayWithDelay()})),this.settings.lineAuthor.show){let n=new U.Setting(this.containerEl).setName("Follow movement and copies across files and commits").setDesc("").addDropdown(s=>{s.addOptions({inactive:"Do not follow (default)","same-commit":"Follow within same commit","all-commits":"Follow within all commits (maybe slow)"}),s.setValue(this.settings.lineAuthor.followMovement),s.onChange(a=>this.lineAuthorSettingHandler("followMovement",a))});if(n.descEl.innerHTML=` + By default (deactivated), each line only shows the newest commit where it was changed. +
+ With same commit, cut-copy-paste-ing of text is followed within the same commit and the original commit of authoring will be shown. +
+ With all commits, cut-copy-paste-ing text inbetween multiple commits will be detected. +
+ It uses git-blame and + for matches (at least ${qd} characters) within the same (or all) commit(s), the originating commit's information is shown.`,new U.Setting(this.containerEl).setName("Show commit hash").addToggle(s=>{s.setValue(this.settings.lineAuthor.showCommitHash),s.onChange(a=>this.lineAuthorSettingHandler("showCommitHash",a))}),new U.Setting(this.containerEl).setName("Author name display").setDesc("If and how the author is displayed").addDropdown(s=>{let a={hide:"Hide",initials:"Initials (default)","first name":"First name","last name":"Last name",full:"Full name"};s.addOptions(a),s.setValue(this.settings.lineAuthor.authorDisplay),s.onChange(async o=>this.lineAuthorSettingHandler("authorDisplay",o))}),new U.Setting(this.containerEl).setName("Authoring date display").setDesc("If and how the date and time of authoring the line is displayed").addDropdown(s=>{let a={hide:"Hide",date:"Date (default)",datetime:"Date and time","natural language":"Natural language",custom:"Custom"};s.addOptions(a),s.setValue(this.settings.lineAuthor.dateTimeFormatOptions),s.onChange(async o=>{await this.lineAuthorSettingHandler("dateTimeFormatOptions",o),this.refreshDisplayWithDelay()})}),this.settings.lineAuthor.dateTimeFormatOptions==="custom"){let s=new U.Setting(this.containerEl);s.setName("Custom authoring date format").addText(a=>{a.setValue(this.settings.lineAuthor.dateTimeFormatCustomString),a.setPlaceholder("YYYY-MM-DD HH:mm"),a.onChange(async o=>{await this.lineAuthorSettingHandler("dateTimeFormatCustomString",o),s.descEl.innerHTML=this.previewCustomDateTimeDescriptionHtml(o)})}),s.descEl.innerHTML=this.previewCustomDateTimeDescriptionHtml(this.settings.lineAuthor.dateTimeFormatCustomString)}new U.Setting(this.containerEl).setName("Authoring date display timezone").addDropdown(s=>{let a={"viewer-local":"My local (default)","author-local":"Author's local",utc0000:"UTC+0000/Z"};s.addOptions(a),s.setValue(this.settings.lineAuthor.dateTimeTimezone),s.onChange(async o=>this.lineAuthorSettingHandler("dateTimeTimezone",o))}).descEl.innerHTML=` + The time-zone in which the authoring date should be shown. + Either your local time-zone (default), + the author's time-zone during commit creation or + UTC\xB100:00. + `;let i=new U.Setting(this.containerEl).setName("Oldest age in coloring");i.descEl.innerHTML=this.previewOldestAgeDescriptionHtml(this.settings.lineAuthor.coloringMaxAge)[0],i.addText(s=>{s.setPlaceholder("1y"),s.setValue(this.settings.lineAuthor.coloringMaxAge),s.onChange(async a=>{let[o,l]=this.previewOldestAgeDescriptionHtml(a);i.descEl.innerHTML=o,l&&(await this.lineAuthorSettingHandler("coloringMaxAge",a),this.refreshColorSettingsName("oldest"))})}),this.createColorSetting("newest"),this.createColorSetting("oldest"),new U.Setting(this.containerEl).setName("Text color").addText(s=>{s.setValue(this.settings.lineAuthor.textColorCss),s.onChange(async a=>{await this.lineAuthorSettingHandler("textColorCss",a)})}).descEl.innerHTML=` + The CSS color of the gutter text.
+ + It is highly recommended to use + + CSS variables + defined by themes + (e.g.
var(--text-muted)
or +
var(--text-on-accent)
, + because they automatically adapt to theme changes.
+ + See: + List of available CSS variables in Obsidian + + `,new U.Setting(this.containerEl).setName("Ignore whitespace and newlines in changes").addToggle(s=>{s.setValue(this.settings.lineAuthor.ignoreWhitespace),s.onChange(a=>this.lineAuthorSettingHandler("ignoreWhitespace",a))}).descEl.innerHTML=` + Whitespace and newlines are interpreted as + part of the document and in changes + by default (hence not ignored). + This makes the last line being shown as 'changed' + when a new subsequent line is added, + even if the previously last line's text is the same. +
+ If you don't care about purely-whitespace changes + (e.g. list nesting / quote indentation changes), + then activating this will provide more meaningful change detection. + `}}createColorSetting(r){let n=new U.Setting(this.containerEl).setName("").addText(i=>{let s=ry(r,this.settings.lineAuthor),a=ry(r,et.lineAuthor);i.setPlaceholder(Xw(a)),i.setValue(Xw(s)),i.onChange(async o=>{let l=VP(o);if(l!==void 0){let c=r==="newest"?"colorNew":"colorOld";await this.lineAuthorSettingHandler(c,l)}this.refreshColorSettingsDesc(r,l)})});this.lineAuthorColorSettings.set(r,n),this.refreshColorSettingsName(r),this.refreshColorSettingsDesc(r,ry(r,this.settings.lineAuthor))}refreshColorSettingsName(r){let n=this.lineAuthorColorSettings.get(r);if(n){let i=r==="oldest"?`oldest (${this.settings.lineAuthor.coloringMaxAge} or older)`:"newest";n.nameEl.innerText=`Color for ${i} commits`}}refreshColorSettingsDesc(r,n){let i=this.lineAuthorColorSettings.get(r);i&&(i.descEl.innerHTML=this.colorSettingPreviewDescHtml(r,this.settings.lineAuthor,n!==void 0))}colorSettingPreviewDescHtml(r,n,i){let s=i?sp(r,n):"rgba(127,127,127,0.3)",a=U.moment.unix(U.moment.now()/1e3).format("YYYY-MM-DD"),o=i?`abcdef Author Name ${a}`:"invalid color";return`Supports 'rgb(r,g,b)', 'hsl(h,s,l)', hex (#) and + named colors (e.g. 'black', 'purple'). Color preview: ${`
${o}
`}`}previewCustomDateTimeDescriptionHtml(r){let n=(0,U.moment)().format(r);return`
Format string to display the authoring date.
Currently: ${n}`}previewOldestAgeDescriptionHtml(r){let n=Xh(r);return[`The oldest age in the line author coloring. Everything older will have the same color. +
Smallest valid age is "1d". Currently: ${n!==void 0?`${n.asDays()} days`:"invalid!"}`,n]}setNonDefaultValue({settingsProperty:r,text:n}){let i=this.plugin.settings[r];et[r]!==i&&(typeof i=="string"||typeof i=="number"||typeof i=="boolean"?n.setValue(String(i)):n.setValue(JSON.stringify(i)))}refreshDisplayWithDelay(r=80){setTimeout(()=>this.display(),r)}};function ry(t,e){return t==="oldest"?e.colorOld:e.colorNew}function Xh(t){let e=U.moment.duration("P"+t.toUpperCase());return e.isValid()&&e.asDays()&&e.asDays()>=1?e:void 0}p();var en=require("obsidian");var lp=class{constructor(e,r){this.statusBarEl=e;this.plugin=r;this.messages=[];this.base="obsidian-git-statusbar-";this.statusBarEl.setAttribute("data-tooltip-position","top"),r.registerEvent(r.app.workspace.on("obsidian-git:refreshed",()=>{this.refreshCommitTimestamp().catch(console.error)}))}displayMessage(e,r){this.messages.push({message:`Git: ${e.slice(0,100)}`,timeout:r}),this.display()}display(){this.messages.length>0&&!this.currentMessage?(this.currentMessage=this.messages.shift(),this.statusBarEl.addClass(this.base+"message"),this.statusBarEl.ariaLabel="",this.statusBarEl.setText(this.currentMessage.message),this.lastMessageTimestamp=Date.now()):this.currentMessage?Date.now()-this.lastMessageTimestamp>=this.currentMessage.timeout&&(this.currentMessage=null,this.lastMessageTimestamp=null):this.displayState()}displayState(){switch((this.statusBarEl.getText().length>3||!this.statusBarEl.hasChildNodes())&&(this.statusBarEl.empty(),this.conflictEl=this.statusBarEl.createDiv(),this.conflictEl.setAttribute("data-tooltip-position","top"),this.conflictEl.style.float="left",this.pausedEl=this.statusBarEl.createDiv(),this.pausedEl.setAttribute("data-tooltip-position","top"),this.pausedEl.style.float="left",this.iconEl=this.statusBarEl.createDiv(),this.iconEl.style.float="left",this.textEl=this.statusBarEl.createDiv(),this.textEl.style.float="right",this.textEl.style.marginLeft="5px"),this.plugin.localStorage.getConflict()?((0,en.setIcon)(this.conflictEl,"alert-circle"),this.conflictEl.ariaLabel="You have merge conflicts. Resolve them and commit afterwards.",this.conflictEl.style.marginRight="5px",this.conflictEl.addClass(this.base+"conflict")):(this.conflictEl.empty(),this.conflictEl.style.marginRight=""),this.plugin.localStorage.getPausedAutomatics()?((0,en.setIcon)(this.pausedEl,"pause-circle"),this.pausedEl.ariaLabel="Automatic routines are currently paused.",this.pausedEl.style.marginRight="5px",this.pausedEl.addClass(this.base+"paused")):(this.pausedEl.empty(),this.pausedEl.style.marginRight=""),this.plugin.state.gitAction){case 0:this.displayFromNow();break;case 1:this.statusBarEl.ariaLabel="Checking repository status...",(0,en.setIcon)(this.iconEl,"refresh-cw"),this.statusBarEl.addClass(this.base+"status");break;case 3:this.statusBarEl.ariaLabel="Adding files...",(0,en.setIcon)(this.iconEl,"archive"),this.statusBarEl.addClass(this.base+"add");break;case 4:this.statusBarEl.ariaLabel="Committing changes...",(0,en.setIcon)(this.iconEl,"git-commit"),this.statusBarEl.addClass(this.base+"commit");break;case 5:this.statusBarEl.ariaLabel="Pushing changes...",(0,en.setIcon)(this.iconEl,"upload"),this.statusBarEl.addClass(this.base+"push");break;case 2:this.statusBarEl.ariaLabel="Pulling changes...",(0,en.setIcon)(this.iconEl,"download"),this.statusBarEl.addClass(this.base+"pull");break;default:this.statusBarEl.ariaLabel="Failed on initialization!",(0,en.setIcon)(this.iconEl,"alert-triangle"),this.statusBarEl.addClass(this.base+"failed-init");break}}displayFromNow(){var n;let e=this.lastCommitTimestamp,r=this.plugin.state.offlineMode;if(e){let i=(0,en.moment)(e).fromNow();this.statusBarEl.ariaLabel=`${r?"Offline: ":""}Last Commit: ${i}`,(n=this.unPushedCommits)!=null&&n&&(this.statusBarEl.ariaLabel+=` +(${this.unPushedCommits} unpushed commits)`)}else this.statusBarEl.ariaLabel=r?"Git is offline":"Git is ready";r?(0,en.setIcon)(this.iconEl,"globe"):(0,en.setIcon)(this.iconEl,"check"),this.plugin.settings.changedFilesInStatusBar&&this.plugin.cachedStatus&&this.textEl.setText(this.plugin.cachedStatus.changed.length.toString()),this.statusBarEl.addClass(this.base+"idle")}async refreshCommitTimestamp(){this.lastCommitTimestamp=await this.plugin.gitManager.getLastCommitTime(),this.unPushedCommits=await this.plugin.gitManager.getUnpushedCommits()}remove(){this.statusBarEl.remove()}};p();var up=require("obsidian"),cp=class extends up.SuggestModal{constructor(r){super(r.app);this.plugin=r;this.resolve=null;this.setPlaceholder("Type your message and select optional the version with the added date.")}openAndGetResult(){return new Promise(r=>{this.resolve=r,this.open()})}onClose(){new Promise(r=>setTimeout(r,10)).then(()=>{this.resolve&&this.resolve(void 0)})}getSuggestions(r){let n=(0,up.moment)().format(this.plugin.settings.commitDateFormat);return r==""&&(r="..."),[r,`${n}: ${r}`,`${r}: ${n}`]}renderSuggestion(r,n){n.innerText=r}onChooseSuggestion(r,n){this.resolve&&this.resolve(r)}};p();var $F=require("obsidian"),Gu=class{constructor(e){this.plugin=e}saveLastAuto(e,r){r==="backup"?this.plugin.localStorage.setLastAutoBackup(e.toString()):r==="pull"?this.plugin.localStorage.setLastAutoPull(e.toString()):r==="push"&&this.plugin.localStorage.setLastAutoPush(e.toString())}loadLastAuto(){var e,r,n;return{backup:new Date((e=this.plugin.localStorage.getLastAutoBackup())!=null?e:""),pull:new Date((r=this.plugin.localStorage.getLastAutoPull())!=null?r:""),push:new Date((n=this.plugin.localStorage.getLastAutoPush())!=null?n:"")}}async init(){await this.setUpAutoCommitAndSync();let e=this.loadLastAuto();if(this.plugin.settings.differentIntervalCommitAndPush&&this.plugin.settings.autoPushInterval>0){let r=this.diff(this.plugin.settings.autoPushInterval,e.push);this.startAutoPush(r)}if(this.plugin.settings.autoPullInterval>0){let r=this.diff(this.plugin.settings.autoPullInterval,e.pull);this.startAutoPull(r)}}unload(){this.clearAutoPull(),this.clearAutoPush(),this.clearAutoCommitAndSync()}reload(...e){this.plugin.localStorage.getPausedAutomatics()||(e.contains("commit")&&(this.clearAutoCommitAndSync(),this.plugin.settings.autoSaveInterval>0&&this.startAutoCommitAndSync(this.plugin.settings.autoSaveInterval)),e.contains("push")&&(this.clearAutoPush(),this.plugin.settings.differentIntervalCommitAndPush&&this.plugin.settings.autoPushInterval>0&&this.startAutoPush(this.plugin.settings.autoPushInterval)),e.contains("pull")&&(this.clearAutoPull(),this.plugin.settings.autoPullInterval>0&&this.startAutoPull(this.plugin.settings.autoPullInterval)))}async setUpAutoCommitAndSync(){if(this.plugin.settings.setLastSaveToLastCommit){this.clearAutoCommitAndSync();let e=await this.plugin.gitManager.getLastCommitTime();e&&this.saveLastAuto(e,"backup")}if(!this.timeoutIDCommitAndSync&&!this.plugin.autoCommitDebouncer){let e=this.loadLastAuto();if(this.plugin.settings.autoSaveInterval>0){let r=this.diff(this.plugin.settings.autoSaveInterval,e.backup);this.startAutoCommitAndSync(r)}}}startAutoCommitAndSync(e){let r=(e!=null?e:this.plugin.settings.autoSaveInterval)*6e4;this.plugin.settings.autoBackupAfterFileChange?e===0?this.doAutoCommitAndSync():this.plugin.autoCommitDebouncer=(0,$F.debounce)(()=>this.doAutoCommitAndSync(),r,!0):(r>2147483647&&(r=2147483647),this.timeoutIDCommitAndSync=window.setTimeout(()=>this.doAutoCommitAndSync(),r))}doAutoCommitAndSync(){this.plugin.promiseQueue.addTask(async()=>{if(this.plugin.settings.setLastSaveToLastCommit){let r=await this.plugin.gitManager.getLastCommitTime();if(r){this.saveLastAuto(r,"backup");let n=this.diff(this.plugin.settings.autoSaveInterval,r);if(n>0)return this.startAutoCommitAndSync(n),!1}}let e=this.plugin.settings.autoCommitOnlyStaged;return this.plugin.settings.differentIntervalCommitAndPush?await this.plugin.commit({fromAuto:!0,onlyStaged:e}):await this.plugin.commitAndSync({fromAutoBackup:!0,onlyStaged:e}),!0},e=>{e!==!1&&(this.saveLastAuto(new Date,"backup"),this.startAutoCommitAndSync())})}startAutoPull(e){let r=(e!=null?e:this.plugin.settings.autoPullInterval)*6e4;r>2147483647&&(r=2147483647),this.timeoutIDPull=window.setTimeout(()=>this.doAutoPull(),r)}doAutoPull(){this.plugin.promiseQueue.addTask(()=>this.plugin.pullChangesFromRemote(),()=>{this.saveLastAuto(new Date,"pull"),this.startAutoPull()})}startAutoPush(e){let r=(e!=null?e:this.plugin.settings.autoPushInterval)*6e4;r>2147483647&&(r=2147483647),this.timeoutIDPush=window.setTimeout(()=>this.doAutoPush(),r)}doAutoPush(){this.plugin.promiseQueue.addTask(()=>this.plugin.push(),()=>{this.saveLastAuto(new Date,"push"),this.startAutoPush()})}clearAutoCommitAndSync(){var r;let e=!1;return this.timeoutIDCommitAndSync&&(window.clearTimeout(this.timeoutIDCommitAndSync),this.timeoutIDCommitAndSync=void 0,e=!0),this.plugin.autoCommitDebouncer&&((r=this.plugin.autoCommitDebouncer)==null||r.cancel(),this.plugin.autoCommitDebouncer=void 0,e=!0),e}clearAutoPull(){return this.timeoutIDPull?(window.clearTimeout(this.timeoutIDPull),this.timeoutIDPull=void 0,!0):!1}clearAutoPush(){return this.timeoutIDPush?(window.clearTimeout(this.timeoutIDPush),this.timeoutIDPush=void 0,!0):!1}diff(e,r){let i=e-Math.round((new Date().getTime()-r.getTime())/1e3/60);return Math.max(0,i)}};p();var jn=require("obsidian");p();var ju=require("obsidian");async function IF(t,e,r){let n=await OF(e,r);if(n.result==="failure"){new ju.Notice(n.reason);return}let{isGitHub:i,branch:s,repo:a,user:o,filePath:l}=n;if(i){let c=t.getCursor("from").line+1,u=t.getCursor("to").line+1;c===u?window.open(`https://github.com/${o}/${a}/blob/${s}/${l}?plain=1#L${c}`):window.open(`https://github.com/${o}/${a}/blob/${s}/${l}?plain=1#L${c}-L${u}`)}else new ju.Notice("It seems like you are not using GitHub")}async function FF(t,e){let r=await OF(t,e);if(r.result==="failure"){new ju.Notice(r.reason);return}let{isGitHub:n,branch:i,repo:s,user:a,filePath:o}=r;n?window.open(`https://github.com/${a}/${s}/commits/${i}/${o}`):new ju.Notice("It seems like you are not using GitHub")}async function OF(t,e){let r=await e.branchInfo(),n=r.tracking,i=r.current,s,a=e.getRelativeRepoPath(t.path);if(e instanceof Se){let l=await e.getSubmoduleOfFile(e.getRelativeRepoPath(t.path));if(l){a=l.relativeFilepath;let c=await e.git.cwd({path:l.submodule,root:!1}).status();if(n=c.tracking||void 0,i=c.current||void 0,n){let u=n.substring(0,n.indexOf("/")),f=await e.git.cwd({path:l.submodule,root:!1}).getConfig(`remote.${u}.url`,"local");if(f.value!=null)s=f.value;else return{result:"failure",reason:"Failed to get remote url of submodule"}}}}if(n==null)return{result:"failure",reason:"Remote branch is not configured"};if(i==null)return{result:"failure",reason:"Failed to get current branch name"};if(s==null){let l=n.substring(0,n.indexOf("/"));if(s=await e.getConfig(`remote.${l}.url`),s==null)return{result:"failure",reason:"Failed to get remote url"}}let o=s.match(/(?:^https:\/\/github\.com\/(.+)\/(.+?)(?:\.git)?$)|(?:^[a-zA-Z]+@github\.com:(.+)\/(.+?)(?:\.git)?$)/);if(o==null)return{result:"failure",reason:"Could not parse remote url"};{let[l,c,u,f,d]=o;return{result:"success",isGitHub:!!l,repo:u||d,user:c||f,branch:i,filePath:a}}}p();var MF=require("obsidian"),fp=class extends MF.FuzzySuggestModal{constructor(e,r){super(e.app),this.plugin=e,this.changedFiles=r,this.setPlaceholder("Not supported files will be opened by default app!")}getItems(){return this.changedFiles}getItemText(e){if(e.index=="U"&&e.workingDir=="U")return`Untracked | ${e.vaultPath}`;let r="",n="";return e.workingDir!=" "&&(r=`Working Dir: ${e.workingDir} `),e.index!=" "&&(n=`Index: ${e.index}`),`${r}${n} | ${e.vaultPath}`}onChooseItem(e,r){this.plugin.app.metadataCache.getFirstLinkpathDest(e.vaultPath,"")==null?this.app.openWithDefaultApp(e.vaultPath):this.plugin.app.workspace.openLinkText(e.vaultPath,"/")}};p();var DF=require("obsidian"),dp=class extends DF.Modal{constructor(r,n){super(r);this.content=n;this.resolve=null}openAndGetReslt(){return new Promise(r=>{this.resolve=r,this.open()})}onOpen(){let{contentEl:r,titleEl:n}=this;n.setText("Edit .gitignore");let i=r.createDiv(),s=i.createEl("textarea",{text:this.content,cls:["obsidian-git-textarea"],attr:{rows:10,cols:30,wrap:"off"}});i.createEl("button",{cls:["mod-cta","obsidian-git-center-button"],text:"Save"}).addEventListener("click",()=>{this.resolve(s.value),this.close()})}onClose(){let{contentEl:r}=this;r.empty(),this.resolve&&this.resolve(void 0)}};p();var Ju=require("@codemirror/state"),Cp=require("@codemirror/view");p();var Nl=require("@codemirror/state");p();var Nt=class t{static createHunk(e,r,n,i){return{removed:{start:e,count:r,lines:[]},added:{start:n,count:i,lines:[]},head:`@@ -${e}${r>0?`,${r}`:""} +${n}${i>0?`,${i}`:""} @@`,vend:n+Math.max(i-1,0),type:i===0?"delete":r===0?"add":"change"}}static createPartialHunk(e,r,n){let i=r,s=n-r+1,a=0;for(let o of e){let l=o.added.count-o.removed.count,c=0;if(o.added.start>=r&&o.vend<=n)c=l;else{let u=Math.max(0,n+1-(o.added.start+o.removed.count)),f=Math.max(0,r-(o.added.start+o.removed.count));o.added.start>=r&&o.added.start<=n?c=u:o.vend>=r&&o.vend<=n?(c=l-f,i=i-f):o.added.start<=r&&o.vend>=n?(c=u-f,i=i-f):a++,r>o.vend&&(i=i-l)}s=s-c}if(a!==e.length)return s===0&&(i=i-1),this.createHunk(i,s,r,n-r+1)}patchLines(e,r=!1){let n=[];for(let i of e.removed.lines)n.push("-"+i);for(let i of e.added.lines)n.push("+"+i);return r?n.map(i=>i.replace(/\r$/,"")):n}static parseDiffLine(e){let i=e.split("@@")[1].trim().split(" "),s=i[0].substring(1).split(","),a=i[1].substring(1).split(","),o=this.createHunk(parseInt(s[0]),parseInt(s[1]||"1"),parseInt(a[0]),parseInt(a[1]||"1"));return o.head=e,o}static changeEnd(e){return e.added.count===0?e.added.start:e.removed.count===0?e.added.start+e.added.count-1:e.added.start+Math.min(e.added.count,e.removed.count)-1}static calcSigns(e,r,n,i=1,s=1/0,a){if(a&&r.type!=="add")return console.error(`Invalid hunk with untracked=${a} hunk="${r.head}"`),[];i=Math.max(1,i);let{start:o,added:l,removed:c}={start:r.added.start,added:r.added.count,removed:r.removed.count},u=this.changeEnd(r),f=r.type==="delete"&&(o===0||e&&this.changeEnd(e)===o)&&(!n||n.added.start!==o+1);f&&i===1&&(i=0);let d=[];for(let h=Math.max(o,i);h<=Math.min(u,s);h++){let m=r.type==="change"&&(c>l&&h===u||e&&e.added.start===0);d.push({type:f?"topdelete":m?"changedelete":a?"untracked":r.type,count:h===o?r.type==="add"?l:c:void 0,lnum:h+(f?1:0)})}if(r.type==="change"&&l>c&&r.vend>=i&&u<=s)for(let h=Math.max(u,i);h<=Math.min(r.vend,s);h++)d.push({type:"add",count:h===r.vend?l-c:void 0,lnum:h});return d}static createPatch(e,r,n,i=!1){let s=[`diff --git a/${e} b/${e}`,`index 000000..000000 ${n}`,`--- a/${e}`,`+++ b/${e}`],a=0;r=structuredClone(r);for(let o of r){let l=o.removed.start,c=o.removed.count,u=o.added.count;o.type==="add"&&(l=l+1);let f=o.removed.lines,d=o.added.lines;i&&([c,u]=[u,c],[f,d]=[d,f]),s.push(`@@ -${l},${c} +${l+a},${u} @@`);for(let h of f)s.push("-"+h);(i?o.added:o.removed).no_nl_at_eof&&s.push("\\ No newline at end of file");for(let h of d)s.push("+"+h);(i?o.removed:o.added).no_nl_at_eof&&s.push("\\ No newline at end of file"),o.removed.start=l+a,a=a+(u-c)}return s}getSummary(e){let r={added:0,changed:0,removed:0};for(let n of e)if(n.type==="add")r.added+=n.added.count;else if(n.type==="delete")r.removed+=n.removed.count;else if(n.type==="change"){let i=n.added.count,s=n.removed.count,a=Math.min(i,s);r.changed+=a,r.added+=i-a,r.removed+=s-a}return r}static findHunk(e,r){if(!r)return[void 0,void 0];for(let n=0;n=e)return[i,n]}return[void 0,void 0]}static findNearestHunk(e,r,n,i){if(r.length!==0){if(n==="first")return 0;if(n==="last")return r.length-1;if(n==="next"){if(r[0].added.start>e)return 0;for(let s=r.length-1;s>=0;s--)if(r[s].added.start<=e){if(s+1e)return s+1;if(i)return 0}}else if(n==="prev"){if(Math.max(r[r.length-1].vend)0&&Math.max(r[s-1].vend,1)l.added.start?i++:o.added.starta.map(v=>g.replace(/&/,v))).reduce((g,v)=>g.concat(v)),m,l);else if(m&&typeof m=="object"){if(!f)throw new RangeError("The value of a property ("+h+") should be a primitive value.");s(i(h),m,u,d)}else m!=null&&u.push(h.replace(/_.*/,"").replace(/[A-Z]/g,g=>"-"+g.toLowerCase())+": "+m+";")}(u.length||d)&&l.push((n&&!f&&!c?a.map(n):a).join(", ")+" {"+u.join(" ")+"}")}for(let a in e)s(i(a),e[a],this.rules)}getRules(){return this.rules.join(` +`)}static newName(){let e=NF[LF]||1;return NF[LF]=e+1,ny+e.toString(36)}static mount(e,r,n){let i=e[iy],s=n&&n.nonce;i?s&&i.setNonce(s):i=new sy(e,s),i.mount(Array.isArray(r)?r:[r],e)}},BF=new Map,sy=class{constructor(e,r){let n=e.ownerDocument||e,i=n.defaultView;if(!e.head&&e.adoptedStyleSheets&&i.CSSStyleSheet){let s=BF.get(n);if(s)return e[iy]=s;this.sheet=new i.CSSStyleSheet,BF.set(n,this)}else this.styleTag=n.createElement("style"),r&&this.styleTag.setAttribute("nonce",r);this.modules=[],e[iy]=this}mount(e,r){let n=this.sheet,i=0,s=0;for(let a=0;a-1&&(this.modules.splice(l,1),s--,l=-1),l==-1){if(this.modules.splice(s++,0,o),n)for(let c=0;cc){let f=t.slice(e,r).indexOf(n.slice(i,s));if(f>-1)return[new bt(e,e+f,i,i),new bt(e+f+c,r,s,s)]}else if(c>l){let f=n.slice(i,s).indexOf(t.slice(e,r));if(f>-1)return[new bt(e,e,i,i+f),new bt(r,r,i+f+l,s)]}if(l==1||c==1)return[new bt(e,r,i,s)];let u=sO(t,e,r,n,i,s);if(u){let[f,d,h]=u;return Ba(t,e,f,n,i,d).concat(Ba(t,f+h,r,n,d+h,s))}return Wz(t,e,r,n,i,s)}var qu=1e9,Wu=0,dy=!1;function Wz(t,e,r,n,i,s){let a=r-e,o=s-i;if(qu<1e9&&Math.min(a,o)>qu*16||Wu>0&&Date.now()>Wu)return Math.min(a,o)>qu*64?[new bt(e,r,i,s)]:HF(t,e,r,n,i,s);let l=Math.ceil((a+o)/2);ay.reset(l),oy.reset(l);let c=(h,m)=>t.charCodeAt(e+h)==n.charCodeAt(i+m),u=(h,m)=>t.charCodeAt(r-h-1)==n.charCodeAt(s-m-1),f=(a-o)%2!=0?oy:null,d=f?null:ay;for(let h=0;hqu||Wu>0&&!(h&63)&&Date.now()>Wu)return HF(t,e,r,n,i,s);let m=ay.advance(h,a,o,l,f,!1,c)||oy.advance(h,a,o,l,d,!0,u);if(m)return zz(t,e,r,e+m[0],n,i,s,i+m[1])}return[new bt(e,r,i,s)]}var wp=class{constructor(){this.vec=[]}reset(e){this.len=e<<1;for(let r=0;rr)this.end+=2;else if(f>n)this.start+=2;else if(s){let d=i+(r-n)-l;if(d>=0&&d=r-u)return[h,i+h-d]}else{let h=r-s.vec[d];if(u>=h)return[u,f]}}}return null}},ay=new wp,oy=new wp;function zz(t,e,r,n,i,s,a,o){let l=!1;return!Ll(t,n)&&++n==r&&(l=!0),!Ll(i,o)&&++o==a&&(l=!0),l?[new bt(e,r,s,a)]:Ba(t,e,n,i,s,o).concat(Ba(t,n,r,i,o,a))}function iO(t,e){let r=1,n=Math.min(t,e);for(;rr||u>s||t.slice(o,c)!=n.slice(l,u)){if(a==1)return o-e-(Ll(t,o)?0:1);a=a>>1}else{if(c==r||u==s)return c-e;o=c,l=u}}}function py(t,e,r,n,i,s){if(e==r||i==s||t.charCodeAt(r-1)!=n.charCodeAt(s-1))return 0;let a=iO(r-e,s-i);for(let o=r,l=s;;){let c=o-a,u=l-a;if(c>1}else{if(c==e||u==i)return r-c;o=c,l=u}}}function ly(t,e,r,n,i,s,a,o){let l=n.slice(i,s),c=null;for(;;){if(c||a=r)break;let d=t.slice(u,f),h=-1;for(;(h=l.indexOf(d,h+1))!=-1;){let m=hy(t,f,r,n,i+h+d.length,s),g=py(t,e,u,n,i,i+h),v=d.length+m+g;(!c||c[2]>1}}function sO(t,e,r,n,i,s){let a=r-e,o=s-i;if(ai.fromA-e&&n.toB>i.fromB-e&&(t[r-1]=new bt(n.fromA,i.toA,n.fromB,i.toB),t.splice(r--,1))}}function Vz(t,e,r){for(;;){aO(r,1);let n=!1;for(let i=0;i3||o>3){let l=i==t.length-1?e.length:t[i+1].fromA,c=s.fromA-n,u=l-s.toA,f=GF(e,s.fromA,c),d=UF(e,s.toA,u),h=s.fromA-f,m=d-s.toA;if((!a||!o)&&h&&m){let g=Math.max(a,o),[v,w,b]=a?[e,s.fromA,s.toA]:[r,s.fromB,s.toB];g>h&&e.slice(f,s.fromA)==v.slice(b-h,b)?(s=t[i]=new bt(f,f+a,s.fromB-h,s.toB-h),f=s.fromA,d=UF(e,s.toA,l-s.toA)):g>m&&e.slice(s.toA,d)==v.slice(w,w+m)&&(s=t[i]=new bt(d-a,d,s.fromB+m,s.toB+m),d=s.toA,f=GF(e,s.fromA,s.fromA-n)),h=s.fromA-f,m=d-s.toA}if(h||m)s=t[i]=new bt(s.fromA-h,s.toA+m,s.fromB-h,s.toB+m);else if(a){if(!o){let g=qF(e,s.fromA,s.toA),v,w=g<0?-1:jF(e,s.toA,s.fromA);g>-1&&(v=g-s.fromA)<=u&&e.slice(s.fromA,g)==e.slice(s.toA,s.toA+v)?s=t[i]=s.offset(v):w>-1&&(v=s.toA-w)<=c&&e.slice(s.fromA-v,s.fromA)==e.slice(w,s.toA)&&(s=t[i]=s.offset(-v))}}else{let g=qF(r,s.fromB,s.toB),v,w=g<0?-1:jF(r,s.toB,s.fromB);g>-1&&(v=g-s.fromB)<=u&&r.slice(s.fromB,g)==r.slice(s.toB,s.toB+v)?s=t[i]=s.offset(v):w>-1&&(v=s.toB-w)<=c&&r.slice(s.fromB-v,s.fromB)==r.slice(w,s.toB)&&(s=t[i]=s.offset(-v))}}n=s.toA}return aO(t,3),t}var Na;try{Na=new RegExp("[\\p{Alphabetic}\\p{Number}]","u")}catch(t){}function oO(t){return t>48&&t<58||t>64&&t<91||t>96&&t<123}function lO(t,e){if(e==t.length)return 0;let r=t.charCodeAt(e);return r<192?oO(r)?1:0:Na?!fO(r)||e==t.length-1?Na.test(String.fromCharCode(r))?1:0:Na.test(t.slice(e,e+2))?2:0:0}function cO(t,e){if(!e)return 0;let r=t.charCodeAt(e-1);return r<192?oO(r)?1:0:Na?!dO(r)||e==1?Na.test(String.fromCharCode(r))?1:0:Na.test(t.slice(e-2,e))?2:0:0}var uO=8;function UF(t,e,r){if(e==t.length||!cO(t,e))return e;for(let n=e,i=e+r,s=0;si)return n;n+=a}return e}function GF(t,e,r){if(!e||!lO(t,e))return e;for(let n=e,i=e-r,s=0;st>=55296&&t<=56319,dO=t=>t>=56320&&t<=57343;function Ll(t,e){return!e||e==t.length||!fO(t.charCodeAt(e-1))||!dO(t.charCodeAt(e))}function Xz(t,e,r){var n;let i=r==null?void 0:r.override;return i?i(t,e):(qu=((n=r==null?void 0:r.scanLimit)!==null&&n!==void 0?n:1e9)>>1,Wu=r!=null&&r.timeout?Date.now()+r.timeout:0,dy=!1,Vz(t,e,Ba(t,0,t.length,e,0,e.length)))}function hO(){return!dy}function pO(t,e,r){return Yz(Xz(t,e,r),t,e)}var Un=$e.Facet.define({combine:t=>t[0]}),cy=$e.StateEffect.define(),Zz=$e.Facet.define(),Ha=$e.StateField.define({create(t){return null},update(t,e){for(let r of e.effects)r.is(cy)&&(t=r.value);for(let r of e.state.facet(Zz))t=r(t,e);return t}});function my(t){let e=t.field(Ha,!1);if(!e)return null;let r=t.facet(Un);return{chunks:e,side:r?r.side:null}}var ts=class t{constructor(e,r,n,i,s,a=!0){this.changes=e,this.fromA=r,this.toA=n,this.fromB=i,this.toB=s,this.precise=a}offset(e,r){return e||r?new t(this.changes,this.fromA+e,this.toA+e,this.fromB+r,this.toB+r,this.precise):this}get endA(){return Math.max(this.fromA,this.toA-1)}get endB(){return Math.max(this.fromB,this.toB-1)}static build(e,r,n){let i=pO(e.toString(),r.toString(),n);return mO(i,e,r,0,0,hO())}static updateA(e,r,n,i,s){return XF(YF(e,i,!0,n.length),e,r,n,s)}static updateB(e,r,n,i,s){return XF(YF(e,i,!1,r.length),e,r,n,s)}};function WF(t,e,r,n){let i=r.lineAt(t),s=n.lineAt(e);return i.to==t&&s.to==e&&tf+1&&v>d+1)break;h.push(m.offset(-c+n,-u+i)),[f,d]=zF(m.toA+n,m.toB+i,e,r),o++}a.push(new ts(h,c,Math.max(c,f),u,Math.max(u,d),s))}return a}var pp=1e3;function VF(t,e,r,n){let i=0,s=t.length;for(;;){if(i==s){let u=0,f=0;i&&({toA:u,toB:f}=t[i-1]);let d=e-(r?u:f);return[u+d,f+d]}let a=i+s>>1,o=t[a],[l,c]=r?[o.fromA,o.toA]:[o.fromB,o.toB];if(l>e)s=a;else if(c<=e)i=a+1;else return n?[o.fromA,o.fromB]:[o.toA,o.toB]}}function YF(t,e,r,n){let i=[];return e.iterChangedRanges((s,a,o,l)=>{let c=0,u=r?e.length:n,f=0,d=r?n:e.length;s>pp&&([c,f]=VF(t,s-pp,r,!0)),a=c?i[i.length-1]={fromA:m.fromA,fromB:m.fromB,toA:u,toB:d,diffA:m.diffA+g,diffB:m.diffB+v}:i.push({fromA:c,toA:u,fromB:f,toB:d,diffA:g,diffB:v})}),i}function XF(t,e,r,n,i){if(!t.length)return e;let s=[];for(let a=0,o=0,l=0,c=0;;a++){let u=a==t.length?null:t[a],f=u?u.fromA+o:r.length,d=u?u.fromB+l:n.length;for(;cf||v.endB+l>d)break;s.push(v.offset(o,l)),c++}if(!u)break;let h=u.toA+o+u.diffA,m=u.toB+l+u.diffB,g=pO(r.sliceString(f,h),n.sliceString(d,m),i);for(let v of mO(g,r,n,f,d,hO()))s.push(v);for(o+=u.diffA,l+=u.diffB;ch&&v.fromB+l>m)break;c++}}return s}var Kz={scanLimit:500},gO=Oe.ViewPlugin.fromClass(class{constructor(t){({deco:this.deco,gutter:this.gutter}=QF(t))}update(t){(t.docChanged||t.viewportChanged||Qz(t.startState,t.state)||Jz(t.startState,t.state))&&({deco:this.deco,gutter:this.gutter}=QF(t.view))}},{decorations:t=>t.deco}),mp=$e.Prec.low((0,Oe.gutter)({class:"cm-changeGutter",markers:t=>{var e;return((e=t.plugin(gO))===null||e===void 0?void 0:e.gutter)||$e.RangeSet.empty}}));function Qz(t,e){return t.field(Ha,!1)!=e.field(Ha,!1)}function Jz(t,e){return t.facet(Un)!=e.facet(Un)}var ZF=Oe.Decoration.line({class:"cm-changedLine"}),eV=Oe.Decoration.mark({class:"cm-changedText"}),tV=Oe.Decoration.mark({tagName:"ins",class:"cm-insertedLine"}),rV=Oe.Decoration.mark({tagName:"del",class:"cm-deletedLine"}),KF=new class extends Oe.GutterMarker{constructor(){super(...arguments),this.elementClass="cm-changedLineGutter"}};function nV(t,e,r,n,i,s){let a=r?t.fromA:t.fromB,o=r?t.toA:t.toB,l=0;if(a!=o){i.add(a,a,ZF),i.add(a,o,r?rV:tV),s&&s.add(a,a,KF);for(let c=e.iterRange(a,o-1),u=a;!c.next().done;){if(c.lineBreak){u++,i.add(u,u,ZF),s&&s.add(u,u,KF);continue}let f=u+c.value.length;if(n)for(;l=u)break;(a?f.toA:f.toB)>c&&(!s||!s(t.state,f,o,l))&&nV(f,t.state.doc,a,n,o,l)}return{deco:o.finish(),gutter:l&&l.finish()}}var Dl=class extends Oe.WidgetType{constructor(e){super(),this.height=e}eq(e){return this.height==e.height}toDOM(){let e=document.createElement("div");return e.className="cm-mergeSpacer",e.style.height=this.height+"px",e}updateDOM(e){return e.style.height=this.height+"px",!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}},yp=$e.StateEffect.define({map:(t,e)=>t.map(e)}),zu=$e.StateField.define({create:()=>Oe.Decoration.none,update:(t,e)=>{for(let r of e.effects)if(r.is(yp))return r.value;return t.map(e.changes)},provide:t=>Oe.EditorView.decorations.from(t)}),gp=.01;function JF(t,e){if(t.size!=e.size)return!1;let r=t.iter(),n=e.iter();for(;r.value;){if(r.from!=n.from||Math.abs(r.value.spec.widget.height-n.value.spec.widget.height)>1)return!1;r.next(),n.next()}return!0}function iV(t,e,r){let n=new $e.RangeSetBuilder,i=new $e.RangeSetBuilder,s=t.state.field(zu).iter(),a=e.state.field(zu).iter(),o=0,l=0,c=0,u=0,f=t.viewport,d=e.viewport;for(let v=0;;v++){let w=vgp&&(u+=A,i.add(l,l,Oe.Decoration.widget({widget:new Dl(A),block:!0,side:-1})))}if(b>o+1e3&&of.from&&ld.from){let x=Math.min(f.from-o,d.from-l);o+=x,l+=x,v--}else if(w)o=w.toA,l=w.toB;else break;for(;s.value&&s.fromgp&&i.add(e.state.doc.length,e.state.doc.length,Oe.Decoration.widget({widget:new Dl(h),block:!0,side:1}));let m=n.finish(),g=i.finish();JF(m,t.state.field(zu))||t.dispatch({effects:yp.of(m)}),JF(g,e.state.field(zu))||e.dispatch({effects:yp.of(g)})}var uy=$e.StateEffect.define({map:(t,e)=>e.mapPos(t)});var fy=class extends Oe.WidgetType{constructor(e){super(),this.lines=e}eq(e){return this.lines==e.lines}toDOM(e){let r=document.createElement("div");return r.className="cm-collapsedLines",r.textContent=e.state.phrase("$ unchanged lines",this.lines),r.addEventListener("click",n=>{let i=e.posAtDOM(n.target);e.dispatch({effects:uy.of(i)});let{side:s,sibling:a}=e.state.facet(Un);a&&a().dispatch({effects:uy.of(sV(i,e.state.field(Ha),s=="a"))})}),r}ignoreEvent(e){return e instanceof MouseEvent}get estimatedHeight(){return 27}get type(){return"collapsed-unchanged-code"}};function sV(t,e,r){let n=0,i=0;for(let s=0;;s++){let a=s=t)return i+(t-n);[n,i]=r?[a.toA,a.toB]:[a.toB,a.toA]}}var aV=$e.StateField.define({create(t){return Oe.Decoration.none},update(t,e){t=t.map(e.changes);for(let r of e.effects)r.is(uy)&&(t=t.update({filter:n=>n!=r.value}));return t},provide:t=>Oe.EditorView.decorations.from(t)});function eO({margin:t=3,minSize:e=4}){return aV.init(r=>oV(r,t,e))}function oV(t,e,r){let n=new $e.RangeSetBuilder,i=t.facet(Un).side=="a",s=t.field(Ha),a=1;for(let o=0;;o++){let l=o=r&&n.add(t.doc.line(c).from,t.doc.line(u).to,Oe.Decoration.replace({widget:new fy(f),block:!0})),!l)break;a=t.doc.lineAt(Math.min(t.doc.length,i?l.toA:l.toB)).number}return n.finish()}var lV=Oe.EditorView.styleModule.of(new hp({".cm-mergeView":{overflowY:"auto"},".cm-mergeViewEditors":{display:"flex",alignItems:"stretch"},".cm-mergeViewEditor":{flexGrow:1,flexBasis:0,overflow:"hidden"},".cm-merge-revert":{width:"1.6em",flexGrow:0,flexShrink:0,position:"relative"},".cm-merge-revert button":{position:"absolute",display:"block",width:"100%",boxSizing:"border-box",textAlign:"center",background:"none",border:"none",font:"inherit",cursor:"pointer"}})),cV=Oe.EditorView.baseTheme({".cm-mergeView & .cm-scroller, .cm-mergeView &":{height:"auto !important",overflowY:"visible !important"},"&.cm-merge-a .cm-changedLine, .cm-deletedChunk":{backgroundColor:"rgba(160, 128, 100, .08)"},"&.cm-merge-b .cm-changedLine, .cm-inlineChangedLine":{backgroundColor:"rgba(100, 160, 128, .08)"},"&light.cm-merge-a .cm-changedText, &light .cm-deletedChunk .cm-deletedText":{background:"linear-gradient(#ee443366, #ee443366) bottom/100% 2px no-repeat"},"&dark.cm-merge-a .cm-changedText, &dark .cm-deletedChunk .cm-deletedText":{background:"linear-gradient(#ffaa9966, #ffaa9966) bottom/100% 2px no-repeat"},"&light.cm-merge-b .cm-changedText":{background:"linear-gradient(#22bb22aa, #22bb22aa) bottom/100% 2px no-repeat"},"&dark.cm-merge-b .cm-changedText":{background:"linear-gradient(#88ff88aa, #88ff88aa) bottom/100% 2px no-repeat"},"&.cm-merge-b .cm-deletedText":{background:"#ff000033"},".cm-insertedLine, .cm-deletedLine, .cm-deletedLine del":{textDecoration:"none"},".cm-deletedChunk":{paddingLeft:"6px","& .cm-chunkButtons":{position:"absolute",insetInlineEnd:"5px"},"& button":{border:"none",cursor:"pointer",color:"white",margin:"0 2px",borderRadius:"3px","&[name=accept]":{background:"#2a2"},"&[name=reject]":{background:"#d43"}}},".cm-collapsedLines":{padding:"5px 5px 5px 10px",cursor:"pointer","&:before":{content:'"\u299A"',marginInlineEnd:"7px"},"&:after":{content:'"\u299A"',marginInlineStart:"7px"}},"&light .cm-collapsedLines":{color:"#444",background:"linear-gradient(to bottom, transparent 0, #f3f3f3 30%, #f3f3f3 70%, transparent 100%)"},"&dark .cm-collapsedLines":{color:"#ddd",background:"linear-gradient(to bottom, transparent 0, #222 30%, #222 70%, transparent 100%)"},".cm-changeGutter":{width:"3px",paddingLeft:"1px"},"&light.cm-merge-a .cm-changedLineGutter, &light .cm-deletedLineGutter":{background:"#e43"},"&dark.cm-merge-a .cm-changedLineGutter, &dark .cm-deletedLineGutter":{background:"#fa9"},"&light.cm-merge-b .cm-changedLineGutter":{background:"#2b2"},"&dark.cm-merge-b .cm-changedLineGutter":{background:"#8f8"},".cm-inlineChangedLineGutter":{background:"#75d"}}),tO=new $e.Compartment,vp=new $e.Compartment,bp=class{constructor(e){this.revertDOM=null,this.revertToA=!1,this.revertToLeft=!1,this.measuring=-1,this.diffConf=e.diffConfig||Kz;let r=[$e.Prec.low(gO),cV,lV,zu,Oe.EditorView.updateListener.of(f=>{this.measuring<0&&(f.heightChanged||f.viewportChanged)&&!f.transactions.some(d=>d.effects.some(h=>h.is(yp)))&&this.measure()})],n=[Un.of({side:"a",sibling:()=>this.b,highlightChanges:e.highlightChanges!==!1,markGutter:e.gutter!==!1})];e.gutter!==!1&&n.push(mp);let i=$e.EditorState.create({doc:e.a.doc,selection:e.a.selection,extensions:[e.a.extensions||[],Oe.EditorView.editorAttributes.of({class:"cm-merge-a"}),vp.of(n),r]}),s=[Un.of({side:"b",sibling:()=>this.a,highlightChanges:e.highlightChanges!==!1,markGutter:e.gutter!==!1})];e.gutter!==!1&&s.push(mp);let a=$e.EditorState.create({doc:e.b.doc,selection:e.b.selection,extensions:[e.b.extensions||[],Oe.EditorView.editorAttributes.of({class:"cm-merge-b"}),vp.of(s),r]});this.chunks=ts.build(i.doc,a.doc,this.diffConf);let o=[Ha.init(()=>this.chunks),tO.of(e.collapseUnchanged?eO(e.collapseUnchanged):[])];i=i.update({effects:$e.StateEffect.appendConfig.of(o)}).state,a=a.update({effects:$e.StateEffect.appendConfig.of(o)}).state,this.dom=document.createElement("div"),this.dom.className="cm-mergeView",this.editorDOM=this.dom.appendChild(document.createElement("div")),this.editorDOM.className="cm-mergeViewEditors";let l=e.orientation||"a-b",c=document.createElement("div");c.className="cm-mergeViewEditor";let u=document.createElement("div");u.className="cm-mergeViewEditor",this.editorDOM.appendChild(l=="a-b"?c:u),this.editorDOM.appendChild(l=="a-b"?u:c),this.a=new Oe.EditorView({state:i,parent:c,root:e.root,dispatchTransactions:f=>this.dispatch(f,this.a)}),this.b=new Oe.EditorView({state:a,parent:u,root:e.root,dispatchTransactions:f=>this.dispatch(f,this.b)}),this.setupRevertControls(!!e.revertControls,e.revertControls=="b-to-a",e.renderRevertControl),e.parent&&e.parent.appendChild(this.dom),this.scheduleMeasure()}dispatch(e,r){if(e.some(n=>n.docChanged)){let n=e[e.length-1],i=e.reduce((a,o)=>a.compose(o.changes),$e.ChangeSet.empty(e[0].startState.doc.length));this.chunks=r==this.a?ts.updateA(this.chunks,n.newDoc,this.b.state.doc,i,this.diffConf):ts.updateB(this.chunks,this.a.state.doc,n.newDoc,i,this.diffConf),r.update([...e,n.state.update({effects:cy.of(this.chunks)})]);let s=r==this.a?this.b:this.a;s.update([s.state.update({effects:cy.of(this.chunks)})]),this.scheduleMeasure()}else r.update(e)}reconfigure(e){if("diffConfig"in e&&(this.diffConf=e.diffConfig),"orientation"in e){let s=e.orientation!="b-a";if(s!=(this.editorDOM.firstChild==this.a.dom.parentNode)){let a=this.a.dom.parentNode,o=this.b.dom.parentNode;a.remove(),o.remove(),this.editorDOM.insertBefore(s?a:o,this.editorDOM.firstChild),this.editorDOM.appendChild(s?o:a),this.revertToLeft=!this.revertToLeft,this.revertDOM&&(this.revertDOM.textContent="")}}if("revertControls"in e||"renderRevertControl"in e){let s=!!this.revertDOM,a=this.revertToA,o=this.renderRevert;"revertControls"in e&&(s=!!e.revertControls,a=e.revertControls=="b-to-a"),"renderRevertControl"in e&&(o=e.renderRevertControl),this.setupRevertControls(s,a,o)}let r="highlightChanges"in e,n="gutter"in e,i="collapseUnchanged"in e;if(r||n||i){let s=[],a=[];if(r||n){let o=this.a.state.facet(Un),l=n?e.gutter!==!1:o.markGutter,c=r?e.highlightChanges!==!1:o.highlightChanges;s.push(vp.reconfigure([Un.of({side:"a",sibling:()=>this.b,highlightChanges:c,markGutter:l}),l?mp:[]])),a.push(vp.reconfigure([Un.of({side:"b",sibling:()=>this.a,highlightChanges:c,markGutter:l}),l?mp:[]]))}if(i){let o=tO.reconfigure(e.collapseUnchanged?eO(e.collapseUnchanged):[]);s.push(o),a.push(o)}this.a.dispatch({effects:s}),this.b.dispatch({effects:a})}this.scheduleMeasure()}setupRevertControls(e,r,n){this.revertToA=r,this.revertToLeft=this.revertToA==(this.editorDOM.firstChild==this.a.dom.parentNode),this.renderRevert=n,!e&&this.revertDOM?(this.revertDOM.remove(),this.revertDOM=null):e&&!this.revertDOM?(this.revertDOM=this.editorDOM.insertBefore(document.createElement("div"),this.editorDOM.firstChild.nextSibling),this.revertDOM.addEventListener("mousedown",i=>this.revertClicked(i)),this.revertDOM.className="cm-merge-revert"):this.revertDOM&&(this.revertDOM.textContent="")}scheduleMeasure(){if(this.measuring<0){let e=this.dom.ownerDocument.defaultView||window;this.measuring=e.requestAnimationFrame(()=>{this.measuring=-1,this.measure()})}}measure(){iV(this.a,this.b,this.chunks),this.revertDOM&&this.updateRevertButtons()}updateRevertButtons(){let e=this.revertDOM,r=e.firstChild,n=this.a.viewport,i=this.b.viewport;for(let s=0;sn.to||a.fromB>i.to)break;if(a.fromA-1&&(this.dom.ownerDocument.defaultView||window).cancelAnimationFrame(this.measuring),this.dom.remove()}};function rO(t){let e=t.nextSibling;return t.remove(),e}var gy=require("@codemirror/state");function vy(t,e,r){let n=[],i=t.split(` +`),s=e.split(` +`);for(let a of r){let{oldStart:o,oldLines:l,newStart:c,newLines:u}=a,f=Nt.createHunk(o,l,c,u);if(a.oldLines>0){for(let d=o;di.length&&i.last()!=""&&(f.removed.no_nl_at_eof=!0)}if(a.newLines>0){for(let d=c;ds.length&&s.last()!=""&&(f.added.no_nl_at_eof=!0)}n.push(f)}return n}function wy(t,e,r){let n=e.lineAt(t.fromA).number,i=t.fromA==t.toA?0:_p(e,t.endA)-n+1,s=r.lineAt(t.fromB).number,a=t.fromB==t.toB?0:_p(r,t.endB)-s+1,o={oldStart:n,oldLines:i,newStart:s,newLines:a};return o.oldLines==0&&(o.oldStart-=1),o.newLines==0&&(o.newStart-=1),o}var vO={scanLimit:1e3,timeout:200};function uV(t,e,r,n){let i=gy.Text.of(t.split(` +`)),s=gy.Text.of(e.split(` +`)),a=r&&n?ts.updateB(r,i,s,n,vO):ts.build(i,s,vO),o=[];for(let l=0;lh.vend&&(f=f-(h.added.count-h.removed.count)),o>h.vend&&(d=d-(h.added.count-h.removed.count));c.added.lines=u.compareText.split(` +`).slice(f-1,d),u.compareTextHead?c.removed.lines=u.compareTextHead.split(` +`).slice(c.removed.start-1,c.removed.start-1+c.removed.count):c.removed.lines=[]}else c.added.lines=e.doc.toString().split(` +`).slice(a-1,o),o===e.doc.lines&&!e.doc.toString().endsWith(` +`)&&(c.added.no_nl_at_eof=!0),c.removed.lines=u.compareText.split(` +`).slice(c.removed.start-1,c.removed.start-1+c.removed.count),c.removed.start+c.removed.count-1===u.compareText.split(` +`).length&&!u.compareText.endsWith(` +`)&&(c.removed.no_nl_at_eof=!0);return c}},$r=Nl.StateField.define({create:t=>{},update:(t,e)=>{let r=t?{...t}:{maxDiffTimeMs:0,hunks:[],stagedHunks:[],chunks:void 0,isDirty:!1},n=!1;for(let i of e.effects)i.is(Hl)&&(r.compareText=i.value.compareText,r.compareTextHead=i.value.compareTextHead,n=(t==null?void 0:t.compareText)!==i.value.compareText,n&&(r.chunks=void 0)),i.is(Vu)&&yO(r,i.value,e.state);if(r.compareText!==void 0){if(n||e.docChanged){r.isDirty=!0;let i=fV(e,r.compareText,r.chunks,r.maxDiffTimeMs);i&&yO(r,i,e.state)}}else r.compareText=void 0,r.compareTextHead=void 0,r.chunks=void 0,r.hunks=[],r.stagedHunks=[],r.isDirty=!1;return r}});function yO(t,e,r){var i,s;t.hunks=e.hunks,t.chunks=e.chunks,t.isDirty=!1,t.maxDiffTimeMs=Math.max(.95*t.maxDiffTimeMs,e.diffDuration);let n=r.field(Bl.editorInfoField).file;(s=(i=Ln.plugin)==null?void 0:i.editorIntegration.signsFeature.changeStatusBar)==null||s.display(t.hunks,n)}var yy=Nl.StateField.define({create:()=>({debouncer:(0,Bl.debounce)(t=>{let{state:e,compareText:r,previousChunks:n,changeDesc:i}=t,s=bO(e,r,n,i);e.field(Bl.editorEditorField).dispatch({effects:Vu.of(s)})},1e3,!0),maxDiffTimeMs:0}),update:(t,e)=>{var r;for(let n of e.effects)if(n.is(Vu))return t.changeDesc=void 0,t;return!t.changeDesc&&e.changes?t.changeDesc=e.changes:t.changeDesc=(r=t.changeDesc)==null?void 0:r.composeDesc(e.changes),t}});function bO(t,e,r,n){let i=t.doc.toString(),s=performance.now(),{hunks:a,chunks:o}=wO(e,i,r,n),l=performance.now()-s;return{hunks:a,chunks:o,diffDuration:l}}function fV(t,e,r,n){let i=t.state,s=Math.abs(t.changes.length-t.changes.newLength),a=i.field(yy);if(s>1e3||n>16)a.debouncer({state:i,compareText:e,previousChunks:r,changeDesc:a.changeDesc});else return a.changeDesc=void 0,bO(i,e,r,t.changes)}var Hl=Nl.StateEffect.define(),Vu=Nl.StateEffect.define();function _O(t,e){return e.update({effects:Hl.of(t)})}p();p();p();var rt;(function(t){t.INSERT="insert",t.DELETE="delete",t.CONTEXT="context"})(rt||(rt={}));var xO={LINE_BY_LINE:"line-by-line",SIDE_BY_SIDE:"side-by-side"},SO={LINES:"lines",WORDS:"words",NONE:"none"},EO={WORD:"word",CHAR:"char"},Ua;(function(t){t.AUTO="auto",t.DARK="dark",t.LIGHT="light"})(Ua||(Ua={}));p();var dV=["-","[","]","/","{","}","(",")","*","+","?",".","\\","^","$","|"],hV=RegExp("["+dV.join("\\")+"]","g");function kO(t){return t.replace(hV,"\\$&")}function by(t){return t&&t.replace(/\\/g,"/")}function AO(t){let e,r,n,i=0;for(e=0,n=t.length;e1?r[r.length-1]:e}function TO(t,e){return e.reduce((r,n)=>r||t.startsWith(n),!1)}var PO=["a/","b/","i/","w/","c/","o/"];function Vs(t,e,r){let n=r!==void 0?[...PO,r]:PO,i=e?new RegExp(`^${kO(e)} "?(.+?)"?$`):new RegExp('^"?(.+?)"?$'),[,s=""]=i.exec(t)||[],a=n.find(l=>s.indexOf(l)===0);return(a?s.slice(a.length):s).replace(/\s+\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}(?:\.\d+)? [+-]\d{4}.*$/,"")}function pV(t,e){return Vs(t,"---",e)}function mV(t,e){return Vs(t,"+++",e)}function RO(t,e={}){let r=[],n=null,i=null,s=null,a=null,o=null,l=null,c=null,u="--- ",f="+++ ",d="@@",h=/^old mode (\d{6})/,m=/^new mode (\d{6})/,g=/^deleted file mode (\d{6})/,v=/^new file mode (\d{6})/,w=/^copy from "?(.+)"?/,b=/^copy to "?(.+)"?/,k=/^rename from "?(.+)"?/,x=/^rename to "?(.+)"?/,E=/^similarity index (\d+)%/,A=/^dissimilarity index (\d+)%/,y=/^index ([\da-z]+)\.\.([\da-z]+)\s*(\d{6})?/,S=/^Binary files (.*) and (.*) differ/,_=/^GIT binary patch/,C=/^index ([\da-z]+),([\da-z]+)\.\.([\da-z]+)/,P=/^mode (\d{6}),(\d{6})\.\.(\d{6})/,N=/^new file mode (\d{6})/,B=/^deleted file mode (\d{6}),(\d{6})/,H=t.replace(/\\ No newline at end of file/g,"").replace(/\r\n?/g,` +`).split(` +`);function ce(){i!==null&&n!==null&&(n.blocks.push(i),i=null)}function Pe(){n!==null&&(!n.oldName&&l!==null&&(n.oldName=l),!n.newName&&c!==null&&(n.newName=c),n.newName&&(r.push(n),n=null)),l=null,c=null}function ve(){ce(),Pe(),n={blocks:[],deletedLines:0,addedLines:0}}function ie(W){ce();let X;n!==null&&((X=/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@.*/.exec(W))?(n.isCombined=!1,s=parseInt(X[1],10),o=parseInt(X[2],10)):(X=/^@@@ -(\d+)(?:,\d+)? -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@@.*/.exec(W))?(n.isCombined=!0,s=parseInt(X[1],10),a=parseInt(X[2],10),o=parseInt(X[3],10)):(W.startsWith(d)&&console.error("Failed to parse lines, starting in 0!"),s=0,o=0,n.isCombined=!1)),i={lines:[],oldStartLine:s,oldStartLine2:a,newStartLine:o,header:W}}function xe(W){if(n===null||i===null||s===null||o===null)return;let X={content:W},q=n.isCombined?["+ "," +","++"]:["+"],De=n.isCombined?["- "," -","--"]:["-"];TO(W,q)?(n.addedLines++,X.type=rt.INSERT,X.oldNumber=void 0,X.newNumber=o++):TO(W,De)?(n.deletedLines++,X.type=rt.DELETE,X.oldNumber=s++,X.newNumber=void 0):(X.type=rt.CONTEXT,X.oldNumber=s++,X.newNumber=o++),i.lines.push(X)}function we(W,X){let q=X;for(;q{if(!W||W.startsWith("*"))return;let q,De=H[X-1],ar=H[X+1],Ft=H[X+2];if(W.startsWith("diff --git")||W.startsWith("diff --combined")){if(ve(),(q=/^diff --git "?([a-ciow]\/.+)"? "?([a-ciow]\/.+)"?/.exec(W))&&(l=Vs(q[1],void 0,e.dstPrefix),c=Vs(q[2],void 0,e.srcPrefix)),n===null)throw new Error("Where is my file !!!");n.isGitDiff=!0;return}if(W.startsWith("Binary files")&&!(n!=null&&n.isGitDiff)){if(ve(),(q=/^Binary files "?([a-ciow]\/.+)"? and "?([a-ciow]\/.+)"? differ/.exec(W))&&(l=Vs(q[1],void 0,e.dstPrefix),c=Vs(q[2],void 0,e.srcPrefix)),n===null)throw new Error("Where is my file !!!");n.isBinary=!0;return}if((!n||!n.isGitDiff&&n&&W.startsWith(u)&&ar.startsWith(f)&&Ft.startsWith(d))&&ve(),n!=null&&n.isTooBig)return;if(n&&(typeof e.diffMaxChanges=="number"&&n.addedLines+n.deletedLines>e.diffMaxChanges||typeof e.diffMaxLineLength=="number"&&W.length>e.diffMaxLineLength)){n.isTooBig=!0,n.addedLines=0,n.deletedLines=0,n.blocks=[],i=null;let kt=typeof e.diffTooBigMessage=="function"?e.diffTooBigMessage(r.length):"Diff too big to be displayed";ie(kt);return}if(W.startsWith(u)&&ar.startsWith(f)||W.startsWith(f)&&De.startsWith(u)){if(n&&!n.oldName&&W.startsWith("--- ")&&(q=pV(W,e.srcPrefix))){n.oldName=q,n.language=CO(n.oldName,n.language);return}if(n&&!n.newName&&W.startsWith("+++ ")&&(q=mV(W,e.dstPrefix))){n.newName=q,n.language=CO(n.newName,n.language);return}}if(n&&(W.startsWith(d)||n.isGitDiff&&n.oldName&&n.newName&&!i)){ie(W);return}if(i&&(W.startsWith("+")||W.startsWith("-")||W.startsWith(" "))){xe(W);return}let Ie=!we(W,X);if(n===null)throw new Error("Where is my file !!!");(q=h.exec(W))?n.oldMode=q[1]:(q=m.exec(W))?n.newMode=q[1]:(q=g.exec(W))?(n.deletedFileMode=q[1],n.isDeleted=!0):(q=v.exec(W))?(n.newFileMode=q[1],n.isNew=!0):(q=w.exec(W))?(Ie&&(n.oldName=q[1]),n.isCopy=!0):(q=b.exec(W))?(Ie&&(n.newName=q[1]),n.isCopy=!0):(q=k.exec(W))?(Ie&&(n.oldName=q[1]),n.isRename=!0):(q=x.exec(W))?(Ie&&(n.newName=q[1]),n.isRename=!0):(q=S.exec(W))?(n.isBinary=!0,n.oldName=Vs(q[1],void 0,e.srcPrefix),n.newName=Vs(q[2],void 0,e.dstPrefix),ie("Binary file")):_.test(W)?(n.isBinary=!0,ie(W)):(q=E.exec(W))?n.unchangedPercentage=parseInt(q[1],10):(q=A.exec(W))?n.changedPercentage=parseInt(q[1],10):(q=y.exec(W))?(n.checksumBefore=q[1],n.checksumAfter=q[2],q[3]&&(n.mode=q[3])):(q=C.exec(W))?(n.checksumBefore=[q[2],q[3]],n.checksumAfter=q[1]):(q=P.exec(W))?(n.oldMode=[q[2],q[3]],n.newMode=q[1]):(q=N.exec(W))?(n.newFileMode=q[1],n.isNew=!0):(q=B.exec(W))&&(n.deletedFileMode=q[1],n.isDeleted=!0)}),ce(),Pe(),r}p();p();p();function vV(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=[],n;for(n=0;n<=e.length;n++)r[n]=[n];let i;for(i=0;i<=t.length;i++)r[0][i]=i;for(n=1;n<=e.length;n++)for(i=1;i<=t.length;i++)e.charAt(n-1)===t.charAt(i-1)?r[n][i]=r[n-1][i-1]:r[n][i]=Math.min(r[n-1][i-1]+1,Math.min(r[n][i-1]+1,r[n-1][i]+1));return r[e.length][t.length]}function Ul(t){return(e,r)=>{let n=t(e).trim(),i=t(r).trim();return vV(n,i)/(n.length+i.length)}}function Gl(t){function e(n,i,s=new Map){let a=1/0,o;for(let l=0;l0||o.indexB>0)&&(k=v.concat(k)),(n.length>d||i.length>h)&&(k=k.concat(b)),k}return r}var qt={INSERTS:"d2h-ins",DELETES:"d2h-del",CONTEXT:"d2h-cntx",INFO:"d2h-info",INSERT_CHANGES:"d2h-ins d2h-change",DELETE_CHANGES:"d2h-del d2h-change"},Ga={matching:SO.NONE,matchWordsThreshold:.25,maxLineLengthHighlight:1e4,diffStyle:EO.WORD,colorScheme:Ua.LIGHT},yi="/",$O=Ul(t=>t.value),wV=Gl($O);function xy(t){return t.indexOf("dev/null")!==-1}function yV(t){return t.replace(/(]*>((.|\n)*?)<\/ins>)/g,"")}function bV(t){return t.replace(/(]*>((.|\n)*?)<\/del>)/g,"")}function jl(t){switch(t){case rt.CONTEXT:return qt.CONTEXT;case rt.INSERT:return qt.INSERTS;case rt.DELETE:return qt.DELETES}}function ql(t){switch(t){case Ua.DARK:return"d2h-dark-color-scheme";case Ua.AUTO:return"d2h-auto-color-scheme";case Ua.LIGHT:default:return"d2h-light-color-scheme"}}function _V(t){return t?2:1}function Ys(t){return t.slice(0).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")}function Sn(t,e,r=!0){let n=_V(e);return{prefix:t.substring(0,n),content:r?Ys(t.substring(n)):t.substring(n)}}function ja(t){let e=by(t.oldName),r=by(t.newName);if(e!==r&&!xy(e)&&!xy(r)){let n=[],i=[],s=e.split(yi),a=r.split(yi),o=s.length,l=a.length,c=0,u=o-1,f=l-1;for(;cc&&f>c&&s[u]===a[f];)i.unshift(a[f]),u-=1,f-=1;let d=n.join(yi),h=i.join(yi),m=s.slice(c,u+1).join(yi),g=a.slice(c,f+1).join(yi);return d.length&&h.length?d+yi+"{"+m+" \u2192 "+g+"}"+yi+h:d.length?d+yi+"{"+m+" \u2192 "+g+"}":h.length?"{"+m+" \u2192 "+g+"}"+yi+h:e+" \u2192 "+r}else return xy(r)?e:r}function Wl(t){return`d2h-${AO(ja(t)).toString().slice(-6)}`}function zl(t){let e="file-changed";return t.isRename||t.isCopy?e="file-renamed":t.isNew?e="file-added":t.isDeleted?e="file-deleted":t.newName!==t.oldName&&(e="file-renamed"),e}function Sp(t,e,r,n={}){let{matching:i,maxLineLengthHighlight:s,matchWordsThreshold:a,diffStyle:o}=Object.assign(Object.assign({},Ga),n),l=Sn(t,r,!1),c=Sn(e,r,!1);if(l.content.length>s||c.content.length>s)return{oldLine:{prefix:l.prefix,content:Ys(l.content)},newLine:{prefix:c.prefix,content:Ys(c.content)}};let u=o==="char"?Fv(l.content,c.content):Bv(l.content,c.content),f=[];if(o==="word"&&i==="words"){let h=u.filter(v=>v.removed),m=u.filter(v=>v.added);wV(m,h).forEach(v=>{v[0].length===1&&v[1].length===1&&$O(v[0][0],v[1][0]){let g=m.added?"ins":m.removed?"del":null,v=f.indexOf(m)>-1?' class="d2h-change"':"",w=Ys(m.value);return g!==null?`${h}<${g}${v}>${w}`:`${h}${w}`},"");return{oldLine:{prefix:l.prefix,content:yV(d)},newLine:{prefix:c.prefix,content:bV(d)}}}var IO="file-summary",xV="icon",SV={colorScheme:Ga.colorScheme},Ep=class{constructor(e,r={}){this.hoganUtils=e,this.config=Object.assign(Object.assign({},SV),r)}render(e){let r=e.map(n=>this.hoganUtils.render(IO,"line",{fileHtmlId:Wl(n),oldName:n.oldName,newName:n.newName,fileName:ja(n),deletedLines:"-"+n.deletedLines,addedLines:"+"+n.addedLines},{fileIcon:this.hoganUtils.template(xV,zl(n))})).join(` +`);return this.hoganUtils.render(IO,"wrapper",{colorScheme:ql(this.config.colorScheme),filesNumber:e.length,files:r})}};p();var Ey=Object.assign(Object.assign({},Ga),{renderNothingWhenEmpty:!1,matchingMaxComparisons:2500,maxLineSizeInBlockForComparison:200}),Yu="generic",FO="line-by-line",EV="icon",kV="tag",Xu=class{constructor(e,r={}){this.hoganUtils=e,this.config=Object.assign(Object.assign({},Ey),r)}render(e){let r=e.map(n=>{let i;return n.blocks.length?i=this.generateFileHtml(n):i=this.generateEmptyDiff(),this.makeFileDiffHtml(n,i)}).join(` +`);return this.hoganUtils.render(Yu,"wrapper",{colorScheme:ql(this.config.colorScheme),content:r})}makeFileDiffHtml(e,r){if(this.config.renderNothingWhenEmpty&&Array.isArray(e.blocks)&&e.blocks.length===0)return"";let n=this.hoganUtils.template(FO,"file-diff"),i=this.hoganUtils.template(Yu,"file-path"),s=this.hoganUtils.template(EV,"file"),a=this.hoganUtils.template(kV,zl(e));return n.render({file:e,fileHtmlId:Wl(e),diffs:r,filePath:i.render({fileDiffName:ja(e)},{fileIcon:s,fileTag:a})})}generateEmptyDiff(){return this.hoganUtils.render(Yu,"empty-diff",{contentClass:"d2h-code-line",CSSLineClass:qt})}generateFileHtml(e){let r=Gl(Ul(n=>Sn(n.content,e.isCombined).content));return e.blocks.map(n=>{let i=this.hoganUtils.render(Yu,"block-header",{CSSLineClass:qt,blockHeader:e.isTooBig?n.header:Ys(n.header),lineClass:"d2h-code-linenumber",contentClass:"d2h-code-line"});return this.applyLineGroupping(n).forEach(([s,a,o])=>{if(a.length&&o.length&&!s.length)this.applyRematchMatching(a,o,r).map(([l,c])=>{let{left:u,right:f}=this.processChangedLines(e,e.isCombined,l,c);i+=u,i+=f});else if(s.length)s.forEach(l=>{let{prefix:c,content:u}=Sn(l.content,e.isCombined);i+=this.generateSingleLineHtml(e,{type:qt.CONTEXT,prefix:c,content:u,oldNumber:l.oldNumber,newNumber:l.newNumber})});else if(a.length||o.length){let{left:l,right:c}=this.processChangedLines(e,e.isCombined,a,o);i+=l,i+=c}else console.error("Unknown state reached while processing groups of lines",s,a,o)}),i}).join(` +`)}applyLineGroupping(e){let r=[],n=[],i=[];for(let s=0;s0)&&(r.push([[],n,i]),n=[],i=[]),a.type===rt.CONTEXT?r.push([[a],[],[]]):a.type===rt.INSERT&&n.length===0?r.push([[],[],[a]]):a.type===rt.INSERT&&n.length>0?i.push(a):a.type===rt.DELETE&&n.push(a)}return(n.length||i.length)&&(r.push([[],n,i]),n=[],i=[]),r}applyRematchMatching(e,r,n){let i=e.length*r.length,s=xp(e.concat(r).map(o=>o.content.length));return i{let i;return n.blocks.length?i=this.generateFileHtml(n):i=this.generateEmptyDiff(),this.makeFileDiffHtml(n,i)}).join(` +`);return this.hoganUtils.render(Zu,"wrapper",{colorScheme:ql(this.config.colorScheme),content:r})}makeFileDiffHtml(e,r){if(this.config.renderNothingWhenEmpty&&Array.isArray(e.blocks)&&e.blocks.length===0)return"";let n=this.hoganUtils.template(AV,"file-diff"),i=this.hoganUtils.template(Zu,"file-path"),s=this.hoganUtils.template(CV,"file"),a=this.hoganUtils.template(TV,zl(e));return n.render({file:e,fileHtmlId:Wl(e),diffs:r,filePath:i.render({fileDiffName:ja(e)},{fileIcon:s,fileTag:a})})}generateEmptyDiff(){return{right:"",left:this.hoganUtils.render(Zu,"empty-diff",{contentClass:"d2h-code-side-line",CSSLineClass:qt})}}generateFileHtml(e){let r=Gl(Ul(n=>Sn(n.content,e.isCombined).content));return e.blocks.map(n=>{let i={left:this.makeHeaderHtml(n.header,e),right:this.makeHeaderHtml("")};return this.applyLineGroupping(n).forEach(([s,a,o])=>{if(a.length&&o.length&&!s.length)this.applyRematchMatching(a,o,r).map(([l,c])=>{let{left:u,right:f}=this.processChangedLines(e.isCombined,l,c);i.left+=u,i.right+=f});else if(s.length)s.forEach(l=>{let{prefix:c,content:u}=Sn(l.content,e.isCombined),{left:f,right:d}=this.generateLineHtml({type:qt.CONTEXT,prefix:c,content:u,number:l.oldNumber},{type:qt.CONTEXT,prefix:c,content:u,number:l.newNumber});i.left+=f,i.right+=d});else if(a.length||o.length){let{left:l,right:c}=this.processChangedLines(e.isCombined,a,o);i.left+=l,i.right+=c}else console.error("Unknown state reached while processing groups of lines",s,a,o)}),i}).reduce((n,i)=>({left:n.left+i.left,right:n.right+i.right}),{left:"",right:""})}applyLineGroupping(e){let r=[],n=[],i=[];for(let s=0;s0)&&(r.push([[],n,i]),n=[],i=[]),a.type===rt.CONTEXT?r.push([[a],[],[]]):a.type===rt.INSERT&&n.length===0?r.push([[],[],[a]]):a.type===rt.INSERT&&n.length>0?i.push(a):a.type===rt.DELETE&&n.push(a)}return(n.length||i.length)&&(r.push([[],n,i]),n=[],i=[]),r}applyRematchMatching(e,r,n){let i=e.length*r.length,s=xp(e.concat(r).map(o=>o.content.length));return i'),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b(n.rp("'),n.b(n.v(n.f("fileName",t,e,0))),n.b(""),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b(' '),n.b(n.v(n.f("addedLines",t,e,0))),n.b(""),n.b(` +`+r),n.b(' '),n.b(n.v(n.f("deletedLines",t,e,0))),n.b(""),n.b(` +`+r),n.b(" "),n.b(` +`+r),n.b(" "),n.b(` +`+r),n.b(""),n.fl()},partials:{"'),n.b(` +`+r),n.b('
'),n.b(` +`+r),n.b(' Files changed ('),n.b(n.v(n.f("filesNumber",t,e,0))),n.b(")"),n.b(` +`+r),n.b(' hide'),n.b(` +`+r),n.b(' show'),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b('
    '),n.b(` +`+r),n.b(" "),n.b(n.t(n.f("files",t,e,0))),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b(""),n.fl()},partials:{},subs:{}});gt["generic-block-header"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b(""),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b('
'),n.s(n.f("blockHeader",t,e,1),t,e,0,156,173,"{{ }}")&&(n.rs(t,e,function(i,s,a){a.b(a.t(a.f("blockHeader",i,s,0)))}),t.pop()),n.s(n.f("blockHeader",t,e,1),t,e,1,0,0,"")||n.b(" "),n.b("
"),n.b(` +`+r),n.b(" "),n.b(` +`+r),n.b(""),n.fl()},partials:{},subs:{}});gt["generic-empty-diff"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b(""),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b('
'),n.b(` +`+r),n.b(" File without changes"),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b(" "),n.b(` +`+r),n.b(""),n.fl()},partials:{},subs:{}});gt["generic-file-path"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b(''),n.b(` +`+r),n.b(n.rp("'),n.b(n.v(n.f("fileDiffName",t,e,0))),n.b(""),n.b(` +`+r),n.b(n.rp(""),n.b(` +`+r),n.b('"),n.fl()},partials:{""),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b(" "),n.b(n.t(n.f("lineNumber",t,e,0))),n.b(` +`+r),n.b(" "),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b('
'),n.b(` +`+r),n.s(n.f("prefix",t,e,1),t,e,0,162,238,"{{ }}")&&(n.rs(t,e,function(i,s,a){a.b(' '),a.b(a.t(a.f("prefix",i,s,0))),a.b(""),a.b(` +`+r)}),t.pop()),n.s(n.f("prefix",t,e,1),t,e,1,0,0,"")||(n.b('  '),n.b(` +`+r)),n.s(n.f("content",t,e,1),t,e,0,371,445,"{{ }}")&&(n.rs(t,e,function(i,s,a){a.b(' '),a.b(a.t(a.f("content",i,s,0))),a.b(""),a.b(` +`+r)}),t.pop()),n.s(n.f("content",t,e,1),t,e,1,0,0,"")||(n.b('
'),n.b(` +`+r)),n.b("
"),n.b(` +`+r),n.b(" "),n.b(` +`+r),n.b(""),n.fl()},partials:{},subs:{}});gt["generic-wrapper"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('
'),n.b(` +`+r),n.b(" "),n.b(n.t(n.f("content",t,e,0))),n.b(` +`+r),n.b("
"),n.fl()},partials:{},subs:{}});gt["icon-file-added"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('"),n.fl()},partials:{},subs:{}});gt["icon-file-changed"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('"),n.fl()},partials:{},subs:{}});gt["icon-file-deleted"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('"),n.fl()},partials:{},subs:{}});gt["icon-file-renamed"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('"),n.fl()},partials:{},subs:{}});gt["icon-file"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('"),n.fl()},partials:{},subs:{}});gt["line-by-line-file-diff"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('
'),n.b(` +`+r),n.b('
'),n.b(` +`+r),n.b(" "),n.b(n.t(n.f("filePath",t,e,0))),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b('
'),n.b(` +`+r),n.b('
'),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b(" "),n.b(n.t(n.f("diffs",t,e,0))),n.b(` +`+r),n.b(" "),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b("
"),n.fl()},partials:{},subs:{}});gt["line-by-line-numbers"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('
'),n.b(n.v(n.f("oldNumber",t,e,0))),n.b("
"),n.b(` +`+r),n.b('
'),n.b(n.v(n.f("newNumber",t,e,0))),n.b("
"),n.fl()},partials:{},subs:{}});gt["side-by-side-file-diff"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('
'),n.b(` +`+r),n.b('
'),n.b(` +`+r),n.b(" "),n.b(n.t(n.f("filePath",t,e,0))),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b('
'),n.b(` +`+r),n.b('
'),n.b(` +`+r),n.b('
'),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b(" "),n.b(n.t(n.d("diffs.left",t,e,0))),n.b(` +`+r),n.b(" "),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b('
'),n.b(` +`+r),n.b('
'),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b(' '),n.b(` +`+r),n.b(" "),n.b(n.t(n.d("diffs.right",t,e,0))),n.b(` +`+r),n.b(" "),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b("
"),n.b(` +`+r),n.b("
"),n.fl()},partials:{},subs:{}});gt["tag-file-added"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('ADDED'),n.fl()},partials:{},subs:{}});gt["tag-file-changed"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('CHANGED'),n.fl()},partials:{},subs:{}});gt["tag-file-deleted"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('DELETED'),n.fl()},partials:{},subs:{}});gt["tag-file-renamed"]=new _t.Template({code:function(t,e,r){var n=this;return n.b(r=r||""),n.b('RENAMED'),n.fl()},partials:{},subs:{}});var Qu=class{constructor({compiledTemplates:e={},rawTemplates:r={}}){let n=Object.entries(r).reduce((i,[s,a])=>{let o=Py.compile(a,{asString:!1});return Object.assign(Object.assign({},i),{[s]:o})},{});this.preCompiledTemplates=Object.assign(Object.assign(Object.assign({},gt),e),n)}static compile(e){return Py.compile(e,{asString:!1})}render(e,r,n,i,s){let a=this.templateKey(e,r);try{return this.preCompiledTemplates[a].render(n,i,s)}catch(o){throw new Error(`Could not find template to render '${a}'`)}}template(e,r){return this.preCompiledTemplates[this.templateKey(e,r)]}templateKey(e,r){return`${e}-${r}`}};var RV=Object.assign(Object.assign(Object.assign({},Ey),ky),{outputFormat:xO.LINE_BY_LINE,drawFileList:!0});function Ap(t,e={}){let r=Object.assign(Object.assign({},RV),e),n=typeof t=="string"?RO(t,r):t,i=new Qu(r),{colorScheme:s}=r,a={colorScheme:s},o=r.drawFileList?new Ep(i,a).render(n):"",l=r.outputFormat==="side-by-side"?new Ku(i,r).render(n):new Xu(i,r).render(n);return o+l}var UO=Ct(BO());var qa=require("obsidian"),Ry=Ju.StateEffect.define();function Xs(t,e){let r=t.state,n=r.field(Tp),i=r.field($r),s=r.doc.lineAt(e!=null?e:r.selection.main.head).number,a=Nt.findHunk(s,i==null?void 0:i.hunks)[0];if(!a)return;let o=r.doc.line(Math.max(1,a.added.start)).from,l=n.has(o);return r.field(qa.editorEditorField).dispatch({effects:Ry.of({pos:o,add:!l})})}var Tp=Ju.StateField.define({create:()=>new Set,update(t,e){let r=new Set;for(let n of e.effects)n.is(Ry)&&(n.value.add?t.add(n.value.pos):t.delete(n.value.pos));for(let n of t)r.add(e.changes.mapPos(n));return r}}),GO=Ju.StateField.define({create:t=>HO(t),update(t,e){return e.docChanged||e.effects.some(r=>r.is(Hl)||r.is(Ry))?HO(e.state):t},provide:t=>Cp.showTooltip.computeN([t],e=>e.field(t))}),jO=Cp.EditorView.baseTheme({".cm-tooltip.git-diff-tooltip":{"z-index":"var(--layer-popover)",backgroundColor:"var(--background-primary-alt)",border:"var(--border-width) solid var(--background-primary-alt)",borderRadius:"var(--radius-s)"},".cm-tooltip.git-diff-tooltip .tooltip-toolbar":{display:"flex",padding:"var(--size-2-1)"}});function HO(t){let e=t.field($r);return e?[...t.field(Tp)].map(n=>{let i=t.doc.lineAt(n),s=Nt.findHunk(i.number,e.hunks)[0];if(s)return{pos:n,above:!1,arrow:!1,strictSide:!0,clip:!1,create:()=>$V(s,t,n)}}).filter(n=>n!==void 0):[]}function $V(t,e,r){var g,v;let n=Nt.createPatch("file",[t],"10064",!1).join(` +`)+` +`,i=Ap(n,{colorScheme:UO.ColorSchemeType.AUTO,diffStyle:"word",drawFileList:!1}),s=new DOMParser().parseFromString(i,"text/html").querySelector(".d2h-file-diff"),a=document.createElement("div"),o=document.createElement("div");o.addClass("tooltip-toolbar");let l=(w,b)=>{let k=document.createElement("div");return(0,qa.setIcon)(k,w),k.setAttr("aria-label",b),k.addClass("clickable-icon"),k},c=l("x","Close hunk"),u=l("plus","Stage hunk"),f=l("undo","Reset hunk");o.appendChild(c),o.appendChild(u),o.appendChild(f),a.appendChild(o),a.appendChild(s),a.addClass("git-diff-tooltip","git-diff");let d=e.field(qa.editorEditorField);c.onclick=()=>{Xs(d,r)},u.onclick=()=>{let w=Ln.plugin;w&&(w.promiseQueue.addTask(()=>w.hunkActions.stageHunk(r)),Xs(d,r))},f.onclick=()=>{let w=Ln.plugin;w&&(w.hunkActions.resetHunk(r),Xs(d,r))};let h=(v=(g=Ln.plugin)==null?void 0:g.app.workspace.getActiveViewOfType(qa.MarkdownView))==null?void 0:v.scope,m=h==null?void 0:h.register(null,"Escape",(w,b)=>{Xs(d,r)});return{dom:a,destroy:()=>{m&&(h==null||h.unregister(m))},update:w=>{r=w.changes.mapPos(r)}}}function qO(t){let e=t.app;t.addCommand({id:"edit-gitignore",name:"Edit .gitignore",callback:async()=>{let r=t.gitManager.getRelativeVaultPath(".gitignore");await e.vault.adapter.exists(r)||await e.vault.adapter.write(r,"");let n=await e.vault.adapter.read(r),s=await new dp(e,n).openAndGetReslt();s!==void 0&&(await e.vault.adapter.write(r,s),await t.refresh())}}),t.addCommand({id:"open-git-view",name:"Open source control view",callback:async()=>{var i;let r=e.workspace.getLeavesOfType(jt.type),n;r.length===0?(n=(i=e.workspace.getRightLeaf(!1))!=null?i:e.workspace.getLeaf(),await n.setViewState({type:jt.type})):n=r.first(),await e.workspace.revealLeaf(n),e.workspace.trigger("obsidian-git:refresh")}}),t.addCommand({id:"open-history-view",name:"Open history view",callback:async()=>{var i;let r=e.workspace.getLeavesOfType(gn.type),n;r.length===0?(n=(i=e.workspace.getRightLeaf(!1))!=null?i:e.workspace.getLeaf(),await n.setViewState({type:gn.type})):n=r.first(),await e.workspace.revealLeaf(n),e.workspace.trigger("obsidian-git:refresh")}}),t.addCommand({id:"open-diff-view",name:"Open diff view",checkCallback:r=>{let n=e.workspace.getActiveFile();if(r)return n!==null;{let i=t.gitManager.getRelativeRepoPath(n.path,!0);t.tools.openDiff({aFile:i,aRef:""})}}}),t.addCommand({id:"view-file-on-github",name:"Open file on GitHub",editorCallback:(r,{file:n})=>{if(n)return IF(r,n,t.gitManager)}}),t.addCommand({id:"view-history-on-github",name:"Open file history on GitHub",editorCallback:(r,{file:n})=>{if(n)return FF(n,t.gitManager)}}),t.addCommand({id:"pull",name:"Pull",callback:()=>t.promiseQueue.addTask(()=>t.pullChangesFromRemote())}),t.addCommand({id:"fetch",name:"Fetch",callback:()=>t.promiseQueue.addTask(()=>t.fetch())}),t.addCommand({id:"switch-to-remote-branch",name:"Switch to remote branch",callback:()=>t.promiseQueue.addTask(()=>t.switchRemoteBranch())}),t.addCommand({id:"add-to-gitignore",name:"Add file to .gitignore",checkCallback:r=>{let n=e.workspace.getActiveFile();if(r)return n!==null;t.addFileToGitignore(n.path,n instanceof jn.TFolder).catch(i=>t.displayError(i))}}),t.addCommand({id:"push",name:"Commit-and-sync",callback:()=>t.promiseQueue.addTask(()=>t.commitAndSync({fromAutoBackup:!1}))}),t.addCommand({id:"backup-and-close",name:"Commit-and-sync and then close Obsidian",callback:()=>t.promiseQueue.addTask(async()=>{await t.commitAndSync({fromAutoBackup:!1}),window.close()})}),t.addCommand({id:"commit-push-specified-message",name:"Commit-and-sync with specific message",callback:()=>t.promiseQueue.addTask(()=>t.commitAndSync({fromAutoBackup:!1,requestCustomMessage:!0}))}),t.addCommand({id:"commit",name:"Commit all changes",callback:()=>t.promiseQueue.addTask(()=>t.commit({fromAuto:!1}))}),t.addCommand({id:"commit-specified-message",name:"Commit all changes with specific message",callback:()=>t.promiseQueue.addTask(()=>t.commit({fromAuto:!1,requestCustomMessage:!0}))}),t.addCommand({id:"commit-smart",name:"Commit",callback:()=>t.promiseQueue.addTask(async()=>{let n=(await t.updateCachedStatus()).staged.length>0;return t.commit({fromAuto:!1,requestCustomMessage:!1,onlyStaged:n})})}),t.addCommand({id:"commit-staged",name:"Commit staged",checkCallback:function(r){if(r)return!1;t.promiseQueue.addTask(async()=>t.commit({fromAuto:!1,requestCustomMessage:!1}))}}),jn.Platform.isDesktopApp&&t.addCommand({id:"commit-amend-staged-specified-message",name:"Amend staged",callback:()=>t.promiseQueue.addTask(()=>t.commit({fromAuto:!1,requestCustomMessage:!0,onlyStaged:!0,amend:!0}))}),t.addCommand({id:"commit-smart-specified-message",name:"Commit with specific message",callback:()=>t.promiseQueue.addTask(async()=>{let n=(await t.updateCachedStatus()).staged.length>0;return t.commit({fromAuto:!1,requestCustomMessage:!0,onlyStaged:n})})}),t.addCommand({id:"commit-staged-specified-message",name:"Commit staged with specific message",checkCallback:function(r){return r?!1:t.promiseQueue.addTask(()=>t.commit({fromAuto:!1,requestCustomMessage:!0,onlyStaged:!0}))}}),t.addCommand({id:"push2",name:"Push",callback:()=>t.promiseQueue.addTask(()=>t.push())}),t.addCommand({id:"stage-current-file",name:"Stage current file",checkCallback:r=>{let n=e.workspace.getActiveFile();if(r)return n!==null;t.promiseQueue.addTask(()=>t.stageFile(n))}}),t.addCommand({id:"unstage-current-file",name:"Unstage current file",checkCallback:r=>{let n=e.workspace.getActiveFile();if(r)return n!==null;t.promiseQueue.addTask(()=>t.unstageFile(n))}}),t.addCommand({id:"edit-remotes",name:"Edit remotes",callback:()=>t.editRemotes().catch(r=>t.displayError(r))}),t.addCommand({id:"remove-remote",name:"Remove remote",callback:()=>t.removeRemote().catch(r=>t.displayError(r))}),t.addCommand({id:"set-upstream-branch",name:"Set upstream branch",callback:()=>t.setUpstreamBranch().catch(r=>t.displayError(r))}),t.addCommand({id:"delete-repo",name:"CAUTION: Delete repository",callback:async()=>{await e.vault.adapter.exists(`${t.settings.basePath}/.git`)?await new Ze(t,{options:["NO","YES"],placeholder:"Do you really want to delete the repository (.git directory)? plugin action cannot be undone.",onlySelection:!0}).openAndGetResult()==="YES"&&(await e.vault.adapter.rmdir(`${t.settings.basePath}/.git`,!0),new jn.Notice("Successfully deleted repository. Reloading plugin..."),t.unloadPlugin(),await t.init({fromReload:!0})):new jn.Notice("No repository found")}}),t.addCommand({id:"init-repo",name:"Initialize a new repo",callback:()=>t.createNewRepo().catch(r=>t.displayError(r))}),t.addCommand({id:"clone-repo",name:"Clone an existing remote repo",callback:()=>t.cloneNewRepo().catch(r=>t.displayError(r))}),t.addCommand({id:"list-changed-files",name:"List changed files",callback:async()=>{if(await t.isAllInitialized())try{let r=await t.updateCachedStatus();if(r.changed.length+r.staged.length>500){t.displayError("Too many changes to display");return}new fp(t,r.all).open()}catch(r){t.displayError(r)}}}),t.addCommand({id:"switch-branch",name:"Switch branch",callback:()=>{t.switchBranch().catch(r=>t.displayError(r))}}),t.addCommand({id:"create-branch",name:"Create new branch",callback:()=>{t.createBranch().catch(r=>t.displayError(r))}}),t.addCommand({id:"delete-branch",name:"Delete branch",callback:()=>{t.deleteBranch().catch(r=>t.displayError(r))}}),t.addCommand({id:"discard-all",name:"CAUTION: Discard all changes",callback:async()=>{let r=await t.discardAll();switch(r){case"discard":new jn.Notice("Discarded all changes in tracked files.");break;case"delete":new jn.Notice("Discarded all files.");break;case!1:break;default:Eh(r)}}}),t.addCommand({id:"pause-automatic-routines",name:"Pause/Resume automatic routines",callback:()=>{let r=!t.localStorage.getPausedAutomatics();t.localStorage.setPausedAutomatics(r),r?(t.automaticsManager.unload(),new jn.Notice("Paused automatic routines.")):(t.automaticsManager.reload("commit","push","pull"),new jn.Notice("Resumed automatic routines."))}}),t.addCommand({id:"raw-command",name:"Raw command",checkCallback:r=>{let n=t.gitManager;if(r)return n instanceof Se;t.tools.runRawCommand().catch(i=>t.displayError(i))}}),t.addCommand({id:"toggle-line-author-info",name:"Toggle line author information",callback:()=>{var r;return(r=t.settingsTab)==null?void 0:r.configureLineAuthorShowStatus(!t.settings.lineAuthor.show)}}),t.addCommand({id:"reset-hunk",name:"Reset hunk",editorCheckCallback(r,n,i){if(r)return t.settings.hunks.hunkCommands&&t.hunkActions.editor!==void 0;t.hunkActions.resetHunk()}}),t.addCommand({id:"stage-hunk",name:"Stage hunk",editorCheckCallback:(r,n,i)=>{if(r)return t.settings.hunks.hunkCommands&&t.hunkActions.editor!==void 0;t.promiseQueue.addTask(()=>t.hunkActions.stageHunk())}}),t.addCommand({id:"preview-hunk",name:"Preview hunk",editorCheckCallback:(r,n,i)=>{if(r)return t.settings.hunks.hunkCommands&&t.hunkActions.editor!==void 0;let s=t.hunkActions.editor.editor;Xs(s)}}),t.addCommand({id:"next-hunk",name:"Go to next hunk",editorCheckCallback:(r,n,i)=>{if(r)return t.settings.hunks.hunkCommands&&t.hunkActions.editor!==void 0;t.hunkActions.goToHunk("next")}}),t.addCommand({id:"prev-hunk",name:"Go to previous hunk",editorCheckCallback:(r,n,i)=>{if(r)return t.settings.hunks.hunkCommands&&t.hunkActions.editor!==void 0;t.hunkActions.goToHunk("prev")}})}p();var Pp=class{constructor(e){this.plugin=e;this.prefix=this.plugin.manifest.id+":",this.app=e.app}migrate(){let e=["password","hostname","conflict","lastAutoPull","lastAutoBackup","lastAutoPush","gitPath","pluginDisabled"];for(let r of e){let n=localStorage.getItem(this.prefix+r);this.app.loadLocalStorage(this.prefix+r)==null&&n!=null&&n!=null&&(this.app.saveLocalStorage(this.prefix+r,n),localStorage.removeItem(this.prefix+r))}}getPassword(){return this.app.loadLocalStorage(this.prefix+"password")}setPassword(e){return this.app.saveLocalStorage(this.prefix+"password",e)}getUsername(){return this.app.loadLocalStorage(this.prefix+"username")}setUsername(e){return this.app.saveLocalStorage(this.prefix+"username",e)}getHostname(){return this.app.loadLocalStorage(this.prefix+"hostname")}setHostname(e){return this.app.saveLocalStorage(this.prefix+"hostname",e)}getConflict(){return this.app.loadLocalStorage(this.prefix+"conflict")=="true"}setConflict(e){return this.app.saveLocalStorage(this.prefix+"conflict",`${e}`)}getLastAutoPull(){return this.app.loadLocalStorage(this.prefix+"lastAutoPull")}setLastAutoPull(e){return this.app.saveLocalStorage(this.prefix+"lastAutoPull",e)}getLastAutoBackup(){return this.app.loadLocalStorage(this.prefix+"lastAutoBackup")}setLastAutoBackup(e){return this.app.saveLocalStorage(this.prefix+"lastAutoBackup",e)}getLastAutoPush(){return this.app.loadLocalStorage(this.prefix+"lastAutoPush")}setLastAutoPush(e){return this.app.saveLocalStorage(this.prefix+"lastAutoPush",e)}getGitPath(){return this.app.loadLocalStorage(this.prefix+"gitPath")}setGitPath(e){return this.app.saveLocalStorage(this.prefix+"gitPath",e)}getPATHPaths(){var e,r;return(r=(e=this.app.loadLocalStorage(this.prefix+"PATHPaths"))==null?void 0:e.split(":"))!=null?r:[]}setPATHPaths(e){return this.app.saveLocalStorage(this.prefix+"PATHPaths",e.join(":"))}getEnvVars(){var e;return JSON.parse((e=this.app.loadLocalStorage(this.prefix+"envVars"))!=null?e:"[]")}setEnvVars(e){return this.app.saveLocalStorage(this.prefix+"envVars",JSON.stringify(e))}getPluginDisabled(){return this.app.loadLocalStorage(this.prefix+"pluginDisabled")=="true"}setPluginDisabled(e){return this.app.saveLocalStorage(this.prefix+"pluginDisabled",`${e}`)}getPausedAutomatics(){return this.app.loadLocalStorage(this.prefix+"pausedAutomatics")=="true"}setPausedAutomatics(e){return this.app.saveLocalStorage(this.prefix+"pausedAutomatics",`${e}`)}};p();var Vl=require("obsidian");var ef=class{constructor(e){this.plugin=e}async hasTooBigFiles(e){let r=await this.plugin.gitManager.branchInfo(),n=r.tracking?Qi(r.tracking)[0]:null;if(!n)return!1;let i=await this.plugin.gitManager.getRemoteUrl(n);if(i!=null&&i.includes("github.com")){let s=[],a=this.plugin.gitManager;for(let o of e){let l=this.plugin.app.vault.getAbstractFileByPath(o.vaultPath),c=!1;if(l instanceof Vl.TFile)l.stat.size>=1e8&&(c=!0);else{let u=await this.plugin.app.vault.adapter.stat(o.vaultPath);u&&u.size>=1e8&&(c=!0)}if(c){let u=!1;a instanceof Se&&(u=await a.isFileTrackedByLFS(o.path)),u||s.push(o)}}if(s.length>0)return this.plugin.displayError(`Aborted commit, because the following files are too big: +- ${s.map(o=>o.vaultPath).join(` +- `)} +Please remove them or add to .gitignore.`),!0}return!1}async writeAndOpenFile(e){e!==void 0&&await this.plugin.app.vault.adapter.write(ol,e);let r=!1;this.plugin.app.workspace.iterateAllLeaves(n=>{n.getDisplayText()!=""&&ol.startsWith(n.getDisplayText())&&(r=!0)}),r||await this.plugin.app.workspace.openLinkText(ol,"/",!0)}openDiff({aFile:e,bFile:r,aRef:n,bRef:i,event:s}){var l,c;let a=this.plugin.settings.diffStyle;Vl.Platform.isMobileApp&&(a="git_unified");let o={aFile:e,bFile:r!=null?r:e,aRef:n,bRef:i};a=="split"?(l=Bn(this.plugin.app,s))==null||l.setViewState({type:Ns.type,active:!0,state:o}):a=="git_unified"&&((c=Bn(this.plugin.app,s))==null||c.setViewState({type:Bs.type,active:!0,state:o}))}async runRawCommand(){let e=this.plugin.gitManager;if(!(e instanceof Se))return;let n=await new Ze(this.plugin,{placeholder:"push origin master",allowEmpty:!1}).openAndGetResult();n!==void 0&&this.plugin.promiseQueue.addTask(async()=>{let i=new Vl.Notice(`Running '${n}'...`,999999);try{let s=await e.rawCommand(n);s?(i.setMessage(s),window.setTimeout(()=>i.hide(),5e3)):i.hide()}catch(s){throw i.hide(),s}})}};p();var Rp=require("obsidian");var Wa=class extends Rp.ItemView{constructor(r,n){super(r);this.plugin=n;this.gettingDiff=!1;this.parser=new DOMParser,this.navigation=!0,this.contentEl.addClass("git-diff"),this.gitRefreshRef=this.app.workspace.on("obsidian-git:status-changed",()=>{this.refresh().catch(console.error)})}getViewType(){return Bs.type}getDisplayText(){var r;if(((r=this.state)==null?void 0:r.bFile)!=null){let n=this.state.bFile.split("/").last();return n!=null&&n.endsWith(".md")&&(n=n.slice(0,-3)),`Diff: ${n}`}return Bs.name}getIcon(){return Bs.icon}async setState(r,n){this.state=r,Rp.Platform.isMobile&&(this.leaf.view.titleEl.textContent=this.getDisplayText()),await this.refresh()}getState(){return this.state}onClose(){return this.app.workspace.offref(this.gitRefreshRef),this.app.workspace.offref(this.gitViewRefreshRef),super.onClose()}async onOpen(){return await this.refresh(),super.onOpen()}async refresh(){var r;if((r=this.state)!=null&&r.bFile&&!this.gettingDiff&&this.plugin.gitManager){this.gettingDiff=!0;try{let n=await this.plugin.gitManager.getDiffString(this.state.bFile,this.state.aRef=="HEAD",this.state.bRef);this.contentEl.empty();let i=this.plugin.gitManager.getRelativeVaultPath(this.state.bFile);if(!n){if(this.plugin.gitManager instanceof Se&&await this.plugin.gitManager.isTracked(this.state.bFile))n=[`--- ${this.state.aFile}`,`+++ ${this.state.bFile}`,""].join(` +`);else if(await this.app.vault.adapter.exists(i)){let s=await this.app.vault.adapter.read(i);n=[...`--- /dev/null ++++ ${this.state.bFile} +@@ -0,0 +1,${s.split(` +`).length} @@`.split(` +`),...s.split(` +`).map(o=>`+${o}`)].join(` +`)}}if(n){let s=this.parser.parseFromString(Ap(n),"text/html").querySelector(".d2h-file-diff");this.contentEl.append(s)}else{let s=this.contentEl.createDiv({cls:"obsidian-git-center"});s.createSpan({text:"\u26A0\uFE0F",attr:{style:"font-size: 2em"}}),s.createEl("br"),s.createSpan({text:"File not found: "+this.state.bFile})}}finally{this.gettingDiff=!1}}}};p();var rs=require("obsidian");var Xl=require("@codemirror/commands");var $p=require("@codemirror/search"),Yl=require("@codemirror/state"),kn=require("@codemirror/view");var za=class extends rs.ItemView{constructor(r,n){super(r);this.plugin=n;this.refreshing=!1;this.ignoreNextModification=!1;this.navigation=!0,this.registerEvent(this.app.workspace.on("obsidian-git:status-changed",()=>{this.mergeView?this.updateRefEditors().catch(console.error):this.createMergeView().catch(console.error)})),this.intervalRef=window.setInterval(()=>{this.mergeView&&this.updateRefEditors().catch(console.error)},30*1e3),this.registerEvent(this.app.vault.on("modify",i=>{this.state.bRef==null&&i.path===this.state.bFile&&(this.ignoreNextModification?this.ignoreNextModification=!1:this.updateModifiableEditor().catch(console.error))})),this.registerEvent(this.app.vault.on("delete",i=>{this.state.bRef==null&&i.path===this.state.bFile&&this.createMergeView().catch(console.error)})),this.registerEvent(this.app.vault.on("create",i=>{this.state.bRef==null&&i.path===this.state.bFile&&this.createMergeView().catch(console.error)})),this.registerEvent(this.app.vault.on("rename",(i,s)=>{this.state.bRef==null&&(i.path===this.state.bFile||s===this.state.bFile)&&this.createMergeView().catch(console.error)})),this.fileSaveDebouncer=(0,rs.debounce)(i=>{let s=this.state.bFile;s&&(this.ignoreNextModification=!0,this.plugin.app.vault.adapter.write(this.plugin.gitManager.getRelativeVaultPath(s),i).catch(a=>this.plugin.displayError(a)))},1e3,!1)}getViewType(){return Ns.type}getDisplayText(){var r;if(((r=this.state)==null?void 0:r.bFile)!=null){let n=this.state.bFile.split("/").last();n!=null&&n.endsWith(".md")&&(n=n.slice(0,-3));let i;return this.state.bRef==null?i=" (Working Tree)":this.state.bRef==""?i=" (Index)":i="("+this.state.bRef.substring(0,7)+")",`Diff: ${n} ${i}`}return Ns.name}getIcon(){return Ns.icon}async setState(r,n){this.state=r,rs.Platform.isMobile&&(this.leaf.view.titleEl.textContent=this.getDisplayText()),await super.setState(r,n),await this.createMergeView()}getState(){return this.state}onClose(){return window.clearInterval(this.intervalRef),super.onClose()}async onOpen(){return await this.createMergeView(),super.onOpen()}async gitShow(r,n){try{return await this.plugin.gitManager.show(r,n,!1)}catch(i){if(i instanceof Pr&&(i.message.includes("does not exist")||i.message.includes("unknown revision or path")||i.message.includes("exists on disk, but not in")||i.message.includes("fatal: bad object")))return i.message.includes("fatal: bad object")&&this.plugin.displayError(i.message),"";throw i}}async bShouldBeEditable(){if(this.state.bRef!=null)return!1;let r=this.plugin.gitManager.getRelativeVaultPath(this.state.bFile);return await this.app.vault.adapter.exists(r)}async updateModifiableEditor(){if(!this.mergeView||this.refreshing)return;let r=this.mergeView.b;this.refreshing=!0;let n=await this.app.vault.adapter.read(this.state.bFile);if(n!=r.state.doc.toString()){let i=r.state.update({changes:{from:0,to:r.state.doc.length,insert:n},annotations:[Yl.Transaction.remote.of(!0)]});r.dispatch(i)}this.refreshing=!1}async updateRefEditors(){if(!this.mergeView||this.refreshing)return;let r=this.mergeView.a,n=this.mergeView.b;this.refreshing=!0;let i=await this.gitShow(this.state.aRef,this.state.aFile),s;if(this.state.bRef!=null&&(s=await this.gitShow(this.state.bRef,this.state.bFile)),i!=r.state.doc.toString()){let a=r.state.update({changes:{from:0,to:r.state.doc.length,insert:i}});r.dispatch(a)}if(s!=null&&s!=n.state.doc.toString()){let a=n.state.update({changes:{from:0,to:n.state.doc.length,insert:s}});n.dispatch(a)}this.refreshing=!1}renderButtons(){let r=document.createElement("div"),n=r.createDiv();if(n.addClass("clickable-icon"),n.setAttr("aria-label",this.state.bRef==null?"Stage hunk":"Unstage hunk"),(0,rs.setIcon)(n,this.state.bRef==null?"plus":"minus"),n.onmousedown=async i=>{var h;let s=this.mergeView.b,a=this.mergeView.a,o=my(s.state),l=(h=r.parentElement)==null?void 0:h.indexOf(r),c=o.chunks[l],u=wy(c,a.state.doc,s.state.doc),f=vy(this.mergeView.a.state.doc.toString(),this.mergeView.b.state.doc.toString(),[u])[0],d=Nt.createPatch(this.state.bFile,[f],"100644",this.state.bRef!=null).join(` +`)+` +`;await this.plugin.gitManager.applyPatch(d),this.plugin.app.workspace.trigger("obsidian-git:refresh")},this.state.bRef==null){let i=r.createDiv();i.addClass("clickable-icon"),i.setAttr("aria-label","Reset hunk"),(0,rs.setIcon)(i,"undo"),i.onmousedown=s=>{var f;let a=this.mergeView.a,o=this.mergeView.b,l=my(o.state),c=(f=r.parentElement)==null?void 0:f.indexOf(r),u=l.chunks[c];if(u){let d=u.fromA,h=u.toA,m=u.fromB,g=u.toB,v=a.state.sliceDoc(d,Math.max(d,h-1));d!=h&&g<=o.state.doc.length&&(v+=a.state.lineBreak),o.dispatch({changes:{from:m,to:Math.min(o.state.doc.length,g),insert:v},userEvent:"revert"})}}}return r.onmousedown=i=>{i.preventDefault(),i.stopPropagation()},r}async createMergeView(){var r,n,i;if((r=this.state)!=null&&r.aFile&&((n=this.state)!=null&&n.bFile)&&!this.refreshing&&this.plugin.gitManager){this.refreshing=!0,(i=this.mergeView)==null||i.destroy();let s=this.containerEl.children[1];s.empty(),this.contentEl.addClass("git-split-diff-view","git-diff"),this.bIsEditable=await this.bShouldBeEditable();let a=await this.gitShow(this.state.aRef,this.state.aFile),o;if(this.state.bRef!=null)o=await this.gitShow(this.state.bRef,this.state.bFile);else{let g=this.plugin.gitManager.getRelativeVaultPath(this.state.bFile);await this.app.vault.adapter.exists(g)?o=await this.app.vault.adapter.read(g):o=""}let l=[(0,kn.lineNumbers)(),(0,$p.highlightSelectionMatches)(),(0,kn.drawSelection)(),kn.keymap.of([...Xl.standardKeymap,Xl.indentWithTab]),(0,Xl.history)(),(0,$p.search)(),kn.EditorView.lineWrapping],c=this,u=kn.ViewPlugin.define(g=>({update(v){if(v.docChanged&&!v.transactions.some(w=>w.annotation(Yl.Transaction.remote))){let w=g.state.doc.toString();c.fileSaveDebouncer(w)}}})),f={doc:a,extensions:[...l,kn.EditorView.editable.of(!1),Yl.EditorState.readOnly.of(!0)]},d=[...l];this.bIsEditable?d.push(u):d.push(kn.EditorView.editable.of(!1),Yl.EditorState.readOnly.of(!0));let h={doc:o,extensions:d};s.addClasses(["cm-s-obsidian","mod-cm6","markdown-source-view","cm-content"]);let m=this.plugin.gitManager instanceof Se&&(this.state.bRef===void 0||this.state.bRef==="");this.mergeView=new bp({b:h,a:f,collapseUnchanged:{minSize:6,margin:4},renderRevertControl:m?()=>this.renderButtons():void 0,revertControls:m?"a-to-b":void 0,diffConfig:{scanLimit:this.bIsEditable?1e3:1e4},parent:s}),this.refreshing=!1}}};p();var _D=require("obsidian");p();p();p();var WO="5";var zO,VO,YO;typeof window!="undefined"&&((YO=(VO=(zO=window.__svelte)!=null?zO:window.__svelte={}).v)!=null?YO:VO.v=new Set).add(WO);p();p();p();var tf="[",bi="[!",Va="]",ns={};var Ke=Symbol(),An=Symbol("filename"),XO=Symbol("hmr"),ZO="http://www.w3.org/1999/xhtml";p();p();p();p();var Ip=!0;p();var L=!1;p();var is=Array.isArray,KO=Array.prototype.indexOf,qn=Array.prototype.includes,Zl=Array.from,$y=Object.keys,Jt=Object.defineProperty,Ir=Object.getOwnPropertyDescriptor,Iy=Object.getOwnPropertyDescriptors,Fy=Object.prototype,QO=Array.prototype,Kl=Object.getPrototypeOf,Oy=Object.isExtensible;function My(t){return typeof t=="function"}var Fr=()=>{};function Fp(t){for(var e=0;e{t=n,e=i});return{promise:r,resolve:t,reject:e}}p();p();var Wt=Symbol("$state"),rf=Symbol("legacy props"),JO=Symbol(""),Mp=Symbol("proxy path"),_i=new class extends Error{constructor(){super(...arguments);qe(this,"name","StaleReactionError");qe(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}};var Ql=3,Or=8;p();p();function Dp(t){if(L){let e=new Error(`lifecycle_outside_component +\`${t}(...)\` can only be used during component initialisation +https://svelte.dev/e/lifecycle_outside_component`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function eM(){if(L){let t=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");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/async_derived_orphan")}function Dy(){if(L){let t=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");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/bind_invalid_checkbox_value")}function tM(){if(L){let t=new Error(`derived_references_self +A derived value cannot reference itself recursively +https://svelte.dev/e/derived_references_self`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/derived_references_self")}function Ly(t,e,r){if(L){let n=new Error(`each_key_duplicate +${r?`Keyed each block has duplicate key \`${r}\` at indexes ${t} and ${e}`:`Keyed each block has duplicate key at indexes ${t} and ${e}`} +https://svelte.dev/e/each_key_duplicate`);throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/each_key_duplicate")}function rM(t){if(L){let e=new Error(`effect_in_teardown +\`${t}\` cannot be used inside an effect cleanup function +https://svelte.dev/e/effect_in_teardown`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/effect_in_teardown")}function nM(){if(L){let t=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");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function iM(t){if(L){let e=new Error(`effect_orphan +\`${t}\` can only be used inside an effect (e.g. during component initialisation) +https://svelte.dev/e/effect_orphan`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/effect_orphan")}function sM(){if(L){let t=new Error(`effect_update_depth_exceeded +Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state +https://svelte.dev/e/effect_update_depth_exceeded`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function aM(){if(L){let t=new Error(`hydration_failed +Failed to hydrate the application +https://svelte.dev/e/hydration_failed`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/hydration_failed")}function oM(t){if(L){let e=new Error(`props_invalid_value +Cannot do \`bind:${t}={undefined}\` when \`${t}\` has a fallback value +https://svelte.dev/e/props_invalid_value`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/props_invalid_value")}function lM(t){if(L){let e=new Error(`rune_outside_svelte +The \`${t}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files +https://svelte.dev/e/rune_outside_svelte`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/rune_outside_svelte")}function cM(){if(L){let t=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");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function uM(){if(L){let t=new Error("state_prototype_fixed\nCannot set prototype of `$state` object\nhttps://svelte.dev/e/state_prototype_fixed");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/state_prototype_fixed")}function fM(){if(L){let t=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");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function dM(){if(L){let t=new Error("svelte_boundary_reset_onerror\nA `` `reset` function cannot be called while an error is still being handled\nhttps://svelte.dev/e/svelte_boundary_reset_onerror");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}p();p();p();var Zs="font-weight: bold",Ks="font-weight: normal";function hM(t,e){L?console.warn(`%c[svelte] await_waterfall +%cAn async derived, \`${t}\` (${e}) was not read immediately after it resolved. This often indicates an unnecessary waterfall, which can slow down your app +https://svelte.dev/e/await_waterfall`,Zs,Ks):console.warn("https://svelte.dev/e/await_waterfall")}function pM(t,e,r){L?console.warn(`%c[svelte] hydration_attribute_changed +%cThe \`${t}\` attribute on \`${e}\` changed its value between server and client renders. The client value, \`${r}\`, will be ignored in favour of the server value +https://svelte.dev/e/hydration_attribute_changed`,Zs,Ks):console.warn("https://svelte.dev/e/hydration_attribute_changed")}function Ya(t){L?console.warn(`%c[svelte] hydration_mismatch +%c${t?`Hydration failed because the initial UI does not match what was rendered on the server. The error occurred near ${t}`:"Hydration failed because the initial UI does not match what was rendered on the server"} +https://svelte.dev/e/hydration_mismatch`,Zs,Ks):console.warn("https://svelte.dev/e/hydration_mismatch")}function mM(){L?console.warn(`%c[svelte] lifecycle_double_unmount +%cTried to unmount a component that was not mounted +https://svelte.dev/e/lifecycle_double_unmount`,Zs,Ks):console.warn("https://svelte.dev/e/lifecycle_double_unmount")}function Lp(t){L?console.warn(`%c[svelte] state_proxy_equality_mismatch +%cReactive \`$state(...)\` proxies and the values they proxy have different identities. Because of this, comparisons with \`${t}\` will produce unexpected results +https://svelte.dev/e/state_proxy_equality_mismatch`,Zs,Ks):console.warn("https://svelte.dev/e/state_proxy_equality_mismatch")}function gM(){L?console.warn(`%c[svelte] state_proxy_unmount +%cTried to unmount a state proxy, rather than a component +https://svelte.dev/e/state_proxy_unmount`,Zs,Ks):console.warn("https://svelte.dev/e/state_proxy_unmount")}function vM(){L?console.warn("%c[svelte] svelte_boundary_reset_noop\n%cA `` `reset` function only resets the boundary the first time it is called\nhttps://svelte.dev/e/svelte_boundary_reset_noop",Zs,Ks):console.warn("https://svelte.dev/e/svelte_boundary_reset_noop")}function wM(t){L?console.warn(`%c[svelte] transition_slide_display +%cThe \`slide\` transition does not work correctly for elements with \`display: ${t}\` +https://svelte.dev/e/transition_slide_display`,Zs,Ks):console.warn("https://svelte.dev/e/transition_slide_display")}var re=!1;function Bt(t){re=t}var ge;function Ge(t){if(t===null)throw Ya(),ns;return ge=t}function er(){return Ge(Yt(ge))}function G(t){if(re){if(Yt(ge)!==null)throw Ya(),ns;ge=t}}function Xa(t=1){if(re){for(var e=t,r=ge;e--;)r=Yt(r);ge=r}}function ss(t=!0){for(var e=0,r=ge;;){if(r.nodeType===Or){var n=r.data;if(n===Va){if(e===0)return r;e-=1}else(n===tf||n===bi)&&(e+=1)}var i=Yt(r);t&&r.remove(),r=i}}function Np(t){if(!t||t.nodeType!==Or)throw Ya(),ns;return t.data}p();p();p();p();function Bp(t){return t===this.v}function Ny(t,e){return t!=t?e==e:t!==e||t!==null&&typeof t=="object"||typeof t=="function"}function Hp(t){return!Ny(t,this.v)}p();var tr=!1,as=!1,Wn=!1;p();p();p();var nf=null;function Mr(t,e){return t.label=e,Up(t.v,e),t}function Up(t,e){var r;return(r=t==null?void 0:t[Mp])==null||r.call(t,e),t}p();function xi(t){let e=new Error,r=FV();return r.length===0?null:(r.unshift(` +`),Jt(e,"stack",{value:r.join(` +`)}),Jt(e,"name",{value:t}),e)}function FV(){let t=Error.stackTraceLimit;Error.stackTraceLimit=1/0;let e=new Error().stack;if(Error.stackTraceLimit=t,!e)return[];let r=e.split(` +`),n=[];for(let i=0;i{e===Za&&bM()})}Za.push(t)}function _M(){for(;Za.length>0;)bM()}p();var Uy=new WeakMap;function jp(t){var e=ne;if(e===null)return le.f|=8388608,t;if(L&&t instanceof Error&&!Uy.has(t)&&Uy.set(t,OV(t,e)),e.f&32768)Ai(t,e);else{if(!(e.f&128))throw L&&!e.parent&&t instanceof Error&&xM(t),t;e.b.error(t)}}function Ai(t,e){for(;e!==null;){if(e.f&128)try{e.b.error(t);return}catch(r){t=r}e=e.parent}throw L&&t instanceof Error&&xM(t),t}function OV(t,e){var a,o,l;let r=Ir(t,"message");if(!(r&&!r.configurable)){for(var n=sf?" ":" ",i=` +${n}in ${((a=e.fn)==null?void 0:a.name)||""}`,s=e.ctx;s!==null;)i+=` +${n}in ${(o=s.function)==null?void 0:o[An].split("/").pop()}`,s=s.p;return{message:t.message+` +${i} +`,stack:(l=t.stack)==null?void 0:l.split(` +`).filter(c=>!c.includes("svelte/src/internal")).join(` +`)}}}function xM(t){let e=Uy.get(t);e&&(Jt(t,"message",{value:e.message}),Jt(t,"stack",{value:e.stack}))}p();p();var MV=-7169;function Le(t,e){t.f=t.f&MV|e}function tc(t){t.f&512||t.deps===null?Le(t,1024):Le(t,4096)}function SM(t){if(t!==null)for(let e of t)!(e.f&2)||!(e.f&32768)||(e.f^=32768,SM(e.deps))}function qp(t,e,r){t.f&2048?e.add(t):t.f&4096&&r.add(t),SM(t.deps),Le(t,1024)}var rc=new Set,ye=null,lf=null,Rt=null,Lr=[],zp=null,Gy=!1,Ka=!1,nc,ic,Qa,sc,cf,uf,Ja,ls,ac,Ci,jy,qy,kM,zy=class zy{constructor(){me(this,Ci);qe(this,"committed",!1);qe(this,"current",new Map);qe(this,"previous",new Map);me(this,nc,new Set);me(this,ic,new Set);me(this,Qa,0);me(this,sc,0);me(this,cf,null);me(this,uf,new Set);me(this,Ja,new Set);me(this,ls,new Map);qe(this,"is_fork",!1);me(this,ac,!1)}is_deferred(){return this.is_fork||$(this,sc)>0}skip_effect(e){$(this,ls).has(e)||$(this,ls).set(e,{d:[],m:[]})}unskip_effect(e){var r=$(this,ls).get(e);if(r){$(this,ls).delete(e);for(var n of r.d)Le(n,2048),gr(n);for(n of r.m)Le(n,4096),gr(n)}}process(e){var i;Lr=[],this.apply();var r=[],n=[];for(let s of e)wt(this,Ci,jy).call(this,s,r,n);if(this.is_deferred()){wt(this,Ci,qy).call(this,n),wt(this,Ci,qy).call(this,r);for(let[s,a]of $(this,ls))TM(s,a)}else{for(let s of $(this,nc))s();$(this,nc).clear(),$(this,Qa)===0&&wt(this,Ci,kM).call(this),lf=this,ye=null,EM(n),EM(r),lf=null,(i=$(this,cf))==null||i.resolve()}Rt=null}capture(e,r){r!==Ke&&!this.previous.has(e)&&this.previous.set(e,r),e.f&8388608||(this.current.set(e,e.v),Rt==null||Rt.set(e,e.v))}activate(){ye=this,this.apply()}deactivate(){ye===this&&(ye=null,Rt=null)}flush(){if(this.activate(),Lr.length>0){if(Wy(),ye!==null&&ye!==this)return}else $(this,Qa)===0&&this.process([]);this.deactivate()}discard(){for(let e of $(this,ic))e(this);$(this,ic).clear()}increment(e){de(this,Qa,$(this,Qa)+1),e&&de(this,sc,$(this,sc)+1)}decrement(e){de(this,Qa,$(this,Qa)-1),e&&de(this,sc,$(this,sc)-1),!$(this,ac)&&(de(this,ac,!0),vt(()=>{de(this,ac,!1),this.is_deferred()?Lr.length>0&&this.flush():this.revive()}))}revive(){for(let e of $(this,uf))$(this,Ja).delete(e),Le(e,2048),gr(e);for(let e of $(this,Ja))Le(e,4096),gr(e);this.flush()}oncommit(e){$(this,nc).add(e)}ondiscard(e){$(this,ic).add(e)}settled(){var e;return((e=$(this,cf))!=null?e:de(this,cf,Op())).promise}static ensure(){if(ye===null){let e=ye=new zy;rc.add(ye),Ka||vt(()=>{ye===e&&e.flush()})}return ye}apply(){if(!(!tr||!this.is_fork&&rc.size===1)){Rt=new Map(this.current);for(let e of rc)if(e!==this)for(let[r,n]of e.previous)Rt.has(r)||Rt.set(r,n)}}};nc=new WeakMap,ic=new WeakMap,Qa=new WeakMap,sc=new WeakMap,cf=new WeakMap,uf=new WeakMap,Ja=new WeakMap,ls=new WeakMap,ac=new WeakMap,Ci=new WeakSet,jy=function(e,r,n){var d;e.f^=1024;for(var i=e.first,s=null;i!==null;){var a=i.f,o=(a&96)!==0,l=o&&(a&1024)!==0,c=l||(a&8192)!==0||$(this,ls).has(i);if(tr&&s===null&&a&128&&((d=i.b)!=null&&d.is_pending)&&(s=i),!c&&i.fn!==null){o?i.f^=1024:s!==null&&a&16777228?s.b.defer_effect(i):a&4?r.push(i):tr&&a&16777224?n.push(i):ta(i)&&(a&16&&$(this,Ja).add(i),ea(i));var u=i.first;if(u!==null){i=u;continue}}var f=i.parent;for(i=i.next;i===null&&f!==null;)f===s&&(s=null),i=f.next,f=f.parent}},qy=function(e){for(var r=0;r1){this.previous.clear();var e=Rt,r=!0;for(let s of rc){if(s===this){r=!1;continue}let a=[];for(let[l,c]of this.current){if(s.current.has(l))if(r&&c!==s.current.get(l))s.current.set(l,c);else continue;a.push(l)}if(a.length===0)continue;let o=[...s.current.keys()].filter(l=>!this.current.has(l));if(o.length>0){var n=Lr;Lr=[];let l=new Set,c=new Map;for(let u of a)AM(u,o,l,c);if(Lr.length>0){ye=s,s.apply();for(let u of Lr)wt(i=s,Ci,jy).call(i,u,[],[]);s.deactivate()}Lr=n}}ye=null,Rt=e}this.committed=!0,rc.delete(this)};var Br=zy;function eo(t){var e=Ka;Ka=!0;try{var r;for(t&&(ye!==null&&Wy(),r=t());;){if(_M(),Lr.length===0&&(ye==null||ye.flush(),Lr.length===0))return zp=null,r;Wy()}}finally{Ka=e}}function Wy(){var s;Gy=!0;var t=L?new Set:null;try{for(var e=0;Lr.length>0;){var r=Br.ensure();if(e++>1e3){if(L){var n=new Map;for(let a of r.current.keys())for(let[o,l]of(s=a.updated)!=null?s:[]){var i=n.get(o);i||(i={error:l.error,count:0},n.set(o,i)),i.count+=l.count}for(let a of n.values())a.error&&console.error(a.error)}LV()}if(r.process(Lr),Ti.clear(),L)for(let a of r.current.keys())t.add(a)}}finally{if(Lr=[],Gy=!1,zp=null,L)for(let a of t)a.updated=null}}function LV(){try{sM()}catch(t){L&&Jt(t,"stack",{value:""}),Ai(t,zp)}}var Dr=null;function EM(t){var e=t.length;if(e!==0){for(var r=0;r0)){Ti.clear();for(let i of Dr){if(i.f&24576)continue;let s=[i],a=i.parent;for(;a!==null;)Dr.has(a)&&(Dr.delete(a),s.push(a)),a=a.parent;for(let o=s.length-1;o>=0;o--){let l=s[o];l.f&24576||ea(l)}}Dr.clear()}}Dr=null}}function AM(t,e,r,n){if(!r.has(t)&&(r.add(t),t.reactions!==null))for(let i of t.reactions){let s=i.f;s&2?AM(i,e,r,n):s&4194320&&!(s&2048)&&CM(i,e,n)&&(Le(i,2048),gr(i))}}function CM(t,e,r){let n=r.get(t);if(n!==void 0)return n;if(t.deps!==null)for(let i of t.deps){if(qn.call(e,i))return!0;if(i.f&2&&CM(i,e,r))return r.set(i,!0),!0}return r.set(t,!1),!1}function gr(t){for(var e=zp=t;e.parent!==null;){e=e.parent;var r=e.f;if(Gy&&e===ne&&r&16&&!(r&262144))return;if(r&96){if(!(r&1024))return;e.f^=1024}}Lr.push(e)}function TM(t,e){if(!(t.f&32&&t.f&1024)){t.f&2048?e.d.push(t):t.f&4096&&e.m.push(t),Le(t,1024);for(var r=t.first;r!==null;)TM(r,e),r=r.next}}p();p();p();function RM(t){let e=0,r=nr(0),n;return L&&Mr(r,"createSubscriber version"),()=>{Js()&&(R(r),Xt(()=>(e===0&&(n=ze(()=>t(()=>to(r)))),e+=1,()=>{vt(()=>{e-=1,e===0&&(n==null||n(),n=void 0,to(r))})})))}}var BV=589952;function Ky(t,e,r){new Yy(t,e,r)}var tn,ff,Pi,ro,Ri,Cn,Ur,$i,cs,ra,no,us,uc,io,fc,dc,Ii,Kp,xt,$M,IM,Xy,Xp,Zp,Zy,Yy=class{constructor(e,r,n){me(this,xt);qe(this,"parent");qe(this,"is_pending",!1);me(this,tn);me(this,ff,re?ge:null);me(this,Pi);me(this,ro);me(this,Ri);me(this,Cn,null);me(this,Ur,null);me(this,$i,null);me(this,cs,null);me(this,ra,null);me(this,no,0);me(this,us,0);me(this,uc,!1);me(this,io,!1);me(this,fc,new Set);me(this,dc,new Set);me(this,Ii,null);me(this,Kp,RM(()=>(de(this,Ii,nr($(this,no))),L&&Mr($(this,Ii),"$effect.pending()"),()=>{de(this,Ii,null)})));de(this,tn,e),de(this,Pi,r),de(this,ro,n),this.parent=ne.b,this.is_pending=!!$(this,Pi).pending,de(this,Ri,rn(()=>{if(ne.b=this,re){let s=$(this,ff);er(),s.nodeType===Or&&s.data===bi?wt(this,xt,IM).call(this):(wt(this,xt,$M).call(this),$(this,us)===0&&(this.is_pending=!1))}else{var i=wt(this,xt,Xy).call(this);try{de(this,Cn,Ht(()=>n(i)))}catch(s){this.error(s)}$(this,us)>0?wt(this,xt,Zp).call(this):this.is_pending=!1}return()=>{var s;(s=$(this,ra))==null||s.remove()}},BV)),re&&de(this,tn,ge)}defer_effect(e){qp(e,$(this,fc),$(this,dc))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!$(this,Pi).pending}update_pending_count(e){wt(this,xt,Zy).call(this,e),de(this,no,$(this,no)+e),!(!$(this,Ii)||$(this,uc))&&(de(this,uc,!0),vt(()=>{de(this,uc,!1),$(this,Ii)&&Zn($(this,Ii),$(this,no))}))}get_effect_pending(){return $(this,Kp).call(this),R($(this,Ii))}error(e){var r=$(this,Pi).onerror;let n=$(this,Pi).failed;if($(this,io)||!r&&!n)throw e;$(this,Cn)&&(ut($(this,Cn)),de(this,Cn,null)),$(this,Ur)&&(ut($(this,Ur)),de(this,Ur,null)),$(this,$i)&&(ut($(this,$i)),de(this,$i,null)),re&&(Ge($(this,ff)),Xa(),Ge(ss()));var i=!1,s=!1;let a=()=>{if(i){vM();return}i=!0,s&&dM(),Br.ensure(),de(this,no,0),$(this,$i)!==null&&Fi($(this,$i),()=>{de(this,$i,null)}),this.is_pending=this.has_pending_snippet(),de(this,Cn,wt(this,xt,Xp).call(this,()=>(de(this,io,!1),Ht(()=>$(this,ro).call(this,$(this,tn)))))),$(this,us)>0?wt(this,xt,Zp).call(this):this.is_pending=!1};vt(()=>{try{s=!0,r==null||r(e,a),s=!1}catch(o){Ai(o,$(this,Ri)&&$(this,Ri).parent)}n&&de(this,$i,wt(this,xt,Xp).call(this,()=>{Br.ensure(),de(this,io,!0);try{return Ht(()=>{n($(this,tn),()=>e,()=>a)})}catch(o){return Ai(o,$(this,Ri).parent),null}finally{de(this,io,!1)}}))})}};tn=new WeakMap,ff=new WeakMap,Pi=new WeakMap,ro=new WeakMap,Ri=new WeakMap,Cn=new WeakMap,Ur=new WeakMap,$i=new WeakMap,cs=new WeakMap,ra=new WeakMap,no=new WeakMap,us=new WeakMap,uc=new WeakMap,io=new WeakMap,fc=new WeakMap,dc=new WeakMap,Ii=new WeakMap,Kp=new WeakMap,xt=new WeakSet,$M=function(){try{de(this,Cn,Ht(()=>$(this,ro).call(this,$(this,tn))))}catch(e){this.error(e)}},IM=function(){let e=$(this,Pi).pending;e&&(de(this,Ur,Ht(()=>e($(this,tn)))),vt(()=>{var r=wt(this,xt,Xy).call(this);de(this,Cn,wt(this,xt,Xp).call(this,()=>(Br.ensure(),Ht(()=>$(this,ro).call(this,r))))),$(this,us)>0?wt(this,xt,Zp).call(this):(Fi($(this,Ur),()=>{de(this,Ur,null)}),this.is_pending=!1)}))},Xy=function(){var e=$(this,tn);return this.is_pending&&(de(this,ra,It()),$(this,tn).before($(this,ra)),e=$(this,ra)),e},Xp=function(e){var r=ne,n=le,i=ke;Ut($(this,Ri)),$t($(this,Ri)),os($(this,Ri).ctx);try{return e()}catch(s){return jp(s),null}finally{Ut(r),$t(n),os(i)}},Zp=function(){let e=$(this,Pi).pending;$(this,Cn)!==null&&(de(this,cs,document.createDocumentFragment()),$(this,cs).append($(this,ra)),Qp($(this,Cn),$(this,cs))),$(this,Ur)===null&&de(this,Ur,Ht(()=>e($(this,tn))))},Zy=function(e){var r;if(!this.has_pending_snippet()){this.parent&&wt(r=this.parent,xt,Zy).call(r,e);return}if(de(this,us,$(this,us)+e),$(this,us)===0){this.is_pending=!1;for(let n of $(this,fc))Le(n,2048),gr(n);for(let n of $(this,dc))Le(n,4096),gr(n);$(this,fc).clear(),$(this,dc).clear(),$(this,Ur)&&Fi($(this,Ur),()=>{de(this,Ur,null)}),$(this,cs)&&($(this,tn).before($(this,cs)),de(this,cs,null))}};p();function Jp(t,e,r,n){let i=Ei()?so:ao;var s=t.filter(d=>!d.settled);if(r.length===0&&s.length===0){n(e.map(i));return}var a=ye,o=ne,l=FM(),c=s.length===1?s[0].promise:s.length>1?Promise.all(s.map(d=>d.promise)):null;function u(d){l();try{n(d)}catch(h){o.f&16384||Ai(h,o)}a==null||a.deactivate(),df()}if(r.length===0){c.then(()=>u(e.map(i)));return}function f(){l(),Promise.all(r.map(d=>Jy(d))).then(d=>u([...e.map(i),...d])).catch(d=>Ai(d,o))}c?c.then(f):f()}function FM(){var t=ne,e=le,r=ke,n=ye;if(L)var i=Si;return function(a=!0){Ut(t),$t(e),os(r),a&&(n==null||n.activate()),L&&(Qy(null),Jl(i))}}function df(){Ut(null),$t(null),os(null),L&&(Qy(null),Jl(null))}var hf=null;function Qy(t){hf=t}var pf=new Set;function so(t){var e=2050,r=le!==null&&le.f&2?le:null;ne!==null&&(ne.f|=524288);let n={ctx:ke,deps:null,effects:null,equals:Bp,f:e,fn:t,reactions:null,rv:0,v:Ke,wv:0,parent:r!=null?r:ne,ac:null};return L&&Wn&&(n.created=xi("created at")),n}function Jy(t,e,r){let n=ne;n===null&&eM();var i=n.b,s=void 0,a=nr(Ke);L&&(a.label=e);var o=!le,l=new Map;return OM(()=>{var h;L&&(hf=ne);var c=Op();s=c.promise;try{Promise.resolve(t()).then(c.resolve,c.reject).then(()=>{u===ye&&u.committed&&u.deactivate(),df()})}catch(m){c.reject(m),df()}L&&(hf=null);var u=ye;if(o){var f=i.is_rendered();i.update_pending_count(1),u.increment(f),(h=l.get(u))==null||h.reject(_i),l.delete(u),l.set(u,c)}let d=(m,g=void 0)=>{if(hf=null,u.activate(),g)g!==_i&&(a.f|=8388608,Zn(a,g));else{a.f&8388608&&(a.f^=8388608),Zn(a,m);for(let[v,w]of l){if(l.delete(v),v===u)break;w.reject(_i)}L&&r!==void 0&&(pf.add(a),setTimeout(()=>{pf.has(a)&&(hM(a.label,r),pf.delete(a))}))}o&&(i.update_pending_count(-1),u.decrement(f))};c.promise.then(d,m=>d(null,m||"unknown"))}),ir(()=>{for(let c of l.values())c.reject(_i)}),L&&(a.f|=4194304),new Promise(c=>{function u(f){function d(){f===s?c(a):u(s)}f.then(d,d)}u(s)})}function St(t){let e=so(t);return tr||rm(e),e}function ao(t){let e=so(t);return e.equals=Hp,e}function em(t){var e=t.effects;if(e!==null){t.effects=null;for(var r=0;r5){let l=xi("updated at");if(l!==null){let c=t.updated.get(l.stack);c||(c={error:l,count:0},t.updated.set(l.stack,c)),c.count++}}}ne!==null&&(t.set_during_effect=!0)}if(t.f&2){let o=t;t.f&2048&&mf(o),tc(o)}t.wv=cc(),DM(t,2048),Ei()&&ne!==null&&ne.f&1024&&!(ne.f&96)&&(sn===null?LM([t]):sn.push(t)),!n.is_fork&&oo.size>0&&!rb&&Yp()}return e}function Yp(){rb=!1;for(let t of oo)t.f&1024&&Le(t,4096),ta(t)&&ea(t);oo.clear()}function to(t){se(t,t.v+1)}function DM(t,e){var u;var r=t.reactions;if(r!==null)for(var n=Ei(),i=r.length,s=0;s{if(na===a)return f();var d=le,h=na;$t(null),nb(a);var m=f();return $t(d),nb(h),m};n&&(r.set("length",Me(t.length,s)),L&&(t=WV(t)));var l="";let c=!1;function u(f){if(!c){c=!0,l=f,Mr(i,`${l} version`);for(let[d,h]of r)Mr(h,co(l,d));c=!1}}return new Proxy(t,{defineProperty(f,d,h){(!("value"in h)||h.configurable===!1||h.enumerable===!1||h.writable===!1)&&cM();var m=r.get(d);return m===void 0?m=o(()=>{var g=Me(h.value,s);return r.set(d,g),L&&typeof d=="string"&&Mr(g,co(l,d)),g}):se(m,h.value,!0),!0},deleteProperty(f,d){var h=r.get(d);if(h===void 0){if(d in f){let m=o(()=>Me(Ke,s));r.set(d,m),to(i),L&&Mr(m,co(l,d))}}else se(h,Ke),to(i);return!0},get(f,d,h){var w;if(d===Wt)return t;if(L&&d===Mp)return u;var m=r.get(d),g=d in f;if(m===void 0&&(!g||(w=Ir(f,d))!=null&&w.writable)&&(m=o(()=>{var b=Ye(g?f[d]:Ke),k=Me(b,s);return L&&Mr(k,co(l,d)),k}),r.set(d,m)),m!==void 0){var v=R(m);return v===Ke?void 0:v}return Reflect.get(f,d,h)},getOwnPropertyDescriptor(f,d){var h=Reflect.getOwnPropertyDescriptor(f,d);if(h&&"value"in h){var m=r.get(d);m&&(h.value=R(m))}else if(h===void 0){var g=r.get(d),v=g==null?void 0:g.v;if(g!==void 0&&v!==Ke)return{enumerable:!0,configurable:!0,value:v,writable:!0}}return h},has(f,d){var v;if(d===Wt)return!0;var h=r.get(d),m=h!==void 0&&h.v!==Ke||Reflect.has(f,d);if(h!==void 0||ne!==null&&(!m||(v=Ir(f,d))!=null&&v.writable)){h===void 0&&(h=o(()=>{var w=m?Ye(f[d]):Ke,b=Me(w,s);return L&&Mr(b,co(l,d)),b}),r.set(d,h));var g=R(h);if(g===Ke)return!1}return m},set(f,d,h,m){var y;var g=r.get(d),v=d in f;if(n&&d==="length")for(var w=h;wMe(Ke,s)),r.set(w+"",b),L&&Mr(b,co(l,w)))}if(g===void 0)(!v||(y=Ir(f,d))!=null&&y.writable)&&(g=o(()=>Me(void 0,s)),L&&Mr(g,co(l,d)),se(g,Ye(h)),r.set(d,g));else{v=g.v!==Ke;var k=o(()=>Ye(h));se(g,k)}var x=Reflect.getOwnPropertyDescriptor(f,d);if(x!=null&&x.set&&x.set.call(m,h),!v){if(n&&typeof d=="string"){var E=r.get("length"),A=Number(d);Number.isInteger(A)&&A>=E.v&&se(E,A+1)}to(i)}return!0},ownKeys(f){R(i);var d=Reflect.ownKeys(f).filter(g=>{var v=r.get(g);return v===void 0||v.v!==Ke});for(var[h,m]of r)m.v!==Ke&&!(h in f)&&d.push(h);return d},setPrototypeOf(){uM()}})}function co(t,e){var r;return typeof e=="symbol"?`${t}[Symbol(${(r=e.description)!=null?r:""})]`:jV.test(e)?`${t}.${e}`:/^\d+$/.test(e)?`${t}[${e}]`:`${t}['${e}']`}function nm(t){try{if(t!==null&&typeof t=="object"&&Wt in t)return t[Wt]}catch(e){}return t}var qV=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);function WV(t){return new Proxy(t,{get(e,r,n){var i=Reflect.get(e,r,n);return qV.has(r)?function(...s){MM();var a=i.apply(this,s);return Yp(),a}:i}})}function NM(){let t=Array.prototype,e=Array.__svelte_cleanup;e&&e();let{indexOf:r,lastIndexOf:n,includes:i}=t;t.indexOf=function(s,a){let o=r.call(this,s,a);if(o===-1){for(let l=a!=null?a:0;l{t.indexOf=r,t.lastIndexOf=n,t.includes=i}}var ib,BM,sf,HM,UM;function im(){if(ib===void 0){ib=window,BM=document,sf=/Firefox/.test(navigator.userAgent);var t=Element.prototype,e=Node.prototype,r=Text.prototype;HM=Ir(e,"firstChild").get,UM=Ir(e,"nextSibling").get,Oy(t)&&(t.__click=void 0,t.__className=void 0,t.__attributes=null,t.__style=void 0,t.__e=void 0),Oy(r)&&(r.__t=void 0),L&&(t.__svelte_meta=null,NM())}}function It(t=""){return document.createTextNode(t)}function Zt(t){return HM.call(t)}function Yt(t){return UM.call(t)}function j(t,e){if(!re)return Zt(t);var r=Zt(ge);if(r===null)r=ge.appendChild(It());else if(e&&r.nodeType!==Ql){var n=It();return r==null||r.before(n),Ge(n),n}return e&&am(r),Ge(r),r}function qr(t,e=!1){var i,s;if(!re){var r=Zt(t);return r instanceof Comment&&r.data===""?Yt(r):r}if(e){if(((i=ge)==null?void 0:i.nodeType)!==Ql){var n=It();return(s=ge)==null||s.before(n),Ge(n),n}am(ge)}return ge}function ee(t,e=1,r=!1){let n=re?ge:t;for(var i;e--;)i=n,n=Yt(n);if(!re)return n;if(r){if((n==null?void 0:n.nodeType)!==Ql){var s=It();return n===null?i==null||i.after(s):n.before(s),Ge(s),s}am(n)}return Ge(n),n}function hc(t){t.textContent=""}function sm(){if(!tr||Dr!==null)return!1;var t=ne.f;return(t&32768)!==0}function am(t){if(t.nodeValue.length<65536)return;let e=t.nextSibling;for(;e!==null&&e.nodeType===Ql;)e.remove(),t.nodeValue+=e.nodeValue,e=t.nextSibling}p();p();function sb(t){re&&Zt(t)!==null&&hc(t)}var GM=!1;function ab(){GM||(GM=!0,document.addEventListener("reset",t=>{Promise.resolve().then(()=>{var e;if(!t.defaultPrevented)for(let r of t.target.elements)(e=r.__on_r)==null||e.call(r)})},{capture:!0}))}function Kn(t){var e=le,r=ne;$t(null),Ut(null);try{return t()}finally{$t(e),Ut(r)}}function ob(t,e,r,n=r){t.addEventListener(e,()=>Kn(r));let i=t.__on_r;i?t.__on_r=()=>{i(),n(!0)}:t.__on_r=()=>n(!0),ab()}function jM(t){ne===null&&(le===null&&iM(t),nM()),Tn&&rM(t)}function VV(t,e){var r=e.last;r===null?e.last=e.first=t:(r.next=t,t.prev=r,e.last=t)}function Oi(t,e,r){var o;var n=ne;if(L)for(;n!==null&&n.f&131072;)n=n.parent;n!==null&&n.f&8192&&(t|=8192);var i={ctx:ke,deps:null,nodes:null,f:t|2048|512,first:null,fn:e,last:null,next:null,parent:n,b:n&&n.b,prev:null,teardown:null,wv:0,ac:null};if(L&&(i.component_function=zn),r)try{ea(i),i.f|=32768}catch(l){throw ut(i),l}else e!==null&&gr(i);var s=i;if(r&&s.deps===null&&s.teardown===null&&s.nodes===null&&s.first===s.last&&!(s.f&524288)&&(s=s.first,t&16&&t&65536&&s!==null&&(s.f|=65536)),s!==null&&(s.parent=n,n!==null&&VV(s,n),le!==null&&le.f&2&&!(t&64))){var a=le;((o=a.effects)!=null?o:a.effects=[]).push(s)}return i}function Js(){return le!==null&&!jr}function ir(t){let e=Oi(8,null,!1);return Le(e,1024),e.teardown=t,e}function sr(t){var i;jM("$effect"),L&&Jt(t,"name",{value:"$effect"});var e=ne.f,r=!le&&(e&32)!==0&&(e&32768)===0;if(r){var n=ke;((i=n.e)!=null?i:n.e=[]).push(t)}else return Hy(t)}function Hy(t){return Oi(1048580,t,!1)}function cb(t){Br.ensure();let e=Oi(524352,t,!0);return()=>{ut(e)}}function qM(t){Br.ensure();let e=Oi(524352,t,!0);return(r={})=>new Promise(n=>{r.outro?Fi(e,()=>{ut(e),n(void 0)}):(ut(e),n(void 0))})}function Wr(t){return Oi(4,t,!1)}function OM(t){return Oi(4718592,t,!0)}function Xt(t,e=0){return Oi(8|e,t,!0)}function Ne(t,e=[],r=[],n=[]){Jp(n,e,r,i=>{Oi(8,()=>t(...i.map(R)),!0)})}function rn(t,e=0){var r=Oi(16|e,t,!0);return L&&(r.dev_stack=Si),r}function Ht(t){return Oi(524320,t,!0)}function ub(t){var e=t.teardown;if(e!==null){let r=Tn,n=le;lb(!0),$t(null);try{e.call(null)}finally{lb(r),$t(n)}}}function fb(t,e=!1){var r=t.first;for(t.first=t.last=null;r!==null;){let i=r.ac;i!==null&&Kn(()=>{i.abort(_i)});var n=r.next;r.f&64?r.parent=null:ut(r,e),r=n}}function WM(t){for(var e=t.first;e!==null;){var r=e.next;e.f&32||ut(e),e=r}}function ut(t,e=!0){var r=!1;(e||t.f&262144)&&t.nodes!==null&&t.nodes.end!==null&&(zM(t.nodes.start,t.nodes.end),r=!0),fb(t,e&&!r),vf(t,0),Le(t,16384);var n=t.nodes&&t.nodes.t;if(n!==null)for(let s of n)s.stop();ub(t);var i=t.parent;i!==null&&i.first!==null&&Vy(t),L&&(t.component_function=null),t.next=t.prev=t.teardown=t.ctx=t.deps=t.fn=t.nodes=t.ac=null}function zM(t,e){for(;t!==null;){var r=t===e?null:Yt(t);t.remove(),t=r}}function Vy(t){var e=t.parent,r=t.prev,n=t.next;r!==null&&(r.next=n),n!==null&&(n.prev=r),e!==null&&(e.first===t&&(e.first=n),e.last===t&&(e.last=r))}function Fi(t,e,r=!0){var n=[];VM(t,n,!0);var i=()=>{r&&ut(t),e&&e()},s=n.length;if(s>0){var a=()=>--s||i();for(var o of n)o.out(a)}else i()}function VM(t,e,r){if(!(t.f&8192)){t.f^=8192;var n=t.nodes&&t.nodes.t;if(n!==null)for(let o of n)(o.is_global||r)&&e.push(o);for(var i=t.first;i!==null;){var s=i.next,a=(i.f&65536)!==0||(i.f&32)!==0&&(t.f&16)!==0;VM(i,e,a?r:!1),i=s}}}function gf(t){YM(t,!0)}function YM(t,e){if(t.f&8192){t.f^=8192,t.f&1024||(Le(t,2048),gr(t));for(var r=t.first;r!==null;){var n=r.next,i=(r.f&65536)!==0||(r.f&32)!==0;YM(r,i?e:!1),r=n}var s=t.nodes&&t.nodes.t;if(s!==null)for(let a of s)(a.is_global||e)&&a.in()}}function Qp(t,e){if(t.nodes)for(var r=t.nodes.start,n=t.nodes.end;r!==null;){var i=r===n?null:Yt(r);e.append(r),r=i}}p();var XM=null;var om=!1,Tn=!1;function lb(t){Tn=t}var le=null,jr=!1;function $t(t){le=t}var ne=null;function Ut(t){ne=t}var nn=null;function rm(t){le!==null&&(!tr||le.f&2)&&(nn===null?nn=[t]:nn.push(t))}var zr=null,an=0,sn=null;function LM(t){sn=t}var ZM=1,uo=0,na=uo;function nb(t){na=t}function cc(){return++ZM}function ta(t){var e=t.f;if(e&2048)return!0;if(e&2&&(t.f&=-32769),e&4096){for(var r=t.deps,n=r.length,i=0;it.wv)return!0}e&512&&Rt===null&&Le(t,1024)}return!1}function KM(t,e,r=!0){var n=t.reactions;if(n!==null&&!(!tr&&nn!==null&&qn.call(nn,t)))for(var i=0;i{t.ac.abort(_i)}),t.ac=null);try{t.f|=2097152;var u=t.fn,f=u(),d=t.deps,h=(g=ye)==null?void 0:g.is_fork;if(zr!==null){var m;if(h||vf(t,an),d!==null&&an>0)for(d.length=an+zr.length,m=0;m{requestAnimationFrame(()=>t()),setTimeout(()=>t())});await Promise.resolve(),eo()}function R(t){var h,m,g;var e=t.f,r=(e&2)!==0;if((h=XM)==null||h.add(t),le!==null&&!jr){var n=ne!==null&&(ne.f&16384)!==0;if(!n&&(nn===null||!qn.call(nn,t))){var i=le.deps;if(le.f&2097152)t.rvr==null?void 0:r.call(this,s))}return t.startsWith("pointer")||t.startsWith("touch")||t==="wheel"?vt(()=>{e.addEventListener(t,i,n)}):e.addEventListener(t,i,n),i}function on(t,e,r,n,i){var s={capture:n,passive:i},a=tD(t,e,r,s);(e===document.body||e===window||e===document||e instanceof HTMLMediaElement)&&ir(()=>{e.removeEventListener(t,a,s)})}function Et(t){for(var e=0;e{throw w});throw d}}finally{t.__root=e,delete t.currentTarget,$t(u),Ut(f)}}}p();p();function um(t){var e=document.createElement("template");return e.innerHTML=t.replaceAll("",""),e.content}function Mi(t,e){var r=ne;r.nodes===null&&(r.nodes={start:t,end:e,a:null,t:null})}function fe(t,e){var r=(e&1)!==0,n=(e&2)!==0,i,s=!t.startsWith("");return()=>{if(re)return Mi(ge,null),ge;i===void 0&&(i=um(s?t:""+t),r||(i=Zt(i)));var a=n||sf?document.importNode(i,!0):i.cloneNode(!0);if(r){var o=Zt(a),l=a.lastChild;Mi(o,l)}else Mi(a,a);return a}}function ds(){if(re)return Mi(ge,null),ge;var t=document.createDocumentFragment(),e=document.createComment(""),r=It();return t.append(e,r),Mi(e,r),t}function ae(t,e){if(re){var r=ne;(!(r.f&32768)||r.nodes.end===null)&&(r.nodes.end=ge),er();return}t!==null&&t.before(e)}p();var JV=["allowfullscreen","async","autofocus","autoplay","checked","controls","default","disabled","formnovalidate","indeterminate","inert","ismap","loop","multiple","muted","nomodule","novalidate","open","playsinline","readonly","required","reversed","seamless","selected","webkitdirectory","defer","disablepictureinpicture","disableremoteplayback"];var Tce=[...JV,"formNoValidate","isMap","noModule","playsInline","readOnly","value","volume","defaultValue","defaultChecked","srcObject","noValidate","allowFullscreen","disablePictureInPicture","disableRemotePlayback"];var e9=["touchstart","touchmove"];function nD(t){return e9.includes(t)}var t9=["$state","$state.raw","$derived","$derived.by"],Pce=[...t9,"$state.eager","$state.snapshot","$props","$props.id","$bindable","$effect","$effect.pre","$effect.tracking","$effect.root","$effect.pending","$inspect","$inspect().with","$inspect.trace","$host"];var fm=!0;function He(t,e){var n;var r=e==null?"":typeof e=="object"?e+"":e;r!==((n=t.__t)!=null?n:t.__t=t.nodeValue)&&(t.__t=r,t.nodeValue=r+"")}function ia(t,e){return iD(t,e)}function mb(t,e){var a;im(),e.intro=(a=e.intro)!=null?a:!1;let r=e.target,n=re,i=ge;try{for(var s=Zt(r);s&&(s.nodeType!==Or||s.data!==tf);)s=Yt(s);if(!s)throw ns;Bt(!0),Ge(s);let o=iD(t,{...e,anchor:s});return Bt(!1),o}catch(o){if(o instanceof Error&&o.message.split(` +`).some(l=>l.startsWith("https://svelte.dev/e/")))throw o;return o!==ns&&console.warn("Failed to hydrate: ",o),e.recover===!1&&aM(),im(),hc(r),Bt(!1),ia(t,e)}finally{Bt(n),Ge(i)}}var mc=new Map;function iD(t,{target:e,anchor:r,props:n={},events:i,context:s,intro:a=!0}){im();var o=new Set,l=f=>{for(var d=0;d{var f=r!=null?r:e.appendChild(It());return Ky(f,{pending:()=>{}},d=>{at({});var h=ke;if(s&&(h.c=s),i&&(n.$$events=i),re&&Mi(d,null),fm=a,c=t(d,n)||{},fm=!0,re&&(ne.nodes.end=ge,ge===null||ge.nodeType!==Or||ge.data!==Va))throw Ya(),ns;ot()}),()=>{var m;for(var d of o){e.removeEventListener(d,pc);var h=mc.get(d);--h===0?(document.removeEventListener(d,pc),mc.delete(d)):mc.set(d,h)}cm.delete(l),f!==r&&((m=f.parentNode)==null||m.removeChild(f))}});return pb.set(c,u),c}var pb=new WeakMap;function hs(t,e){let r=pb.get(t);return r?(pb.delete(t),r(e)):(L&&(Wt in t?gM():mM()),Promise.resolve())}p();p();p();var Qn,Di,ln,fo,wf,yf,dm,ps=class{constructor(e,r=!0){qe(this,"anchor");me(this,Qn,new Map);me(this,Di,new Map);me(this,ln,new Map);me(this,fo,new Set);me(this,wf,!0);me(this,yf,()=>{var e=ye;if($(this,Qn).has(e)){var r=$(this,Qn).get(e),n=$(this,Di).get(r);if(n)gf(n),$(this,fo).delete(r);else{var i=$(this,ln).get(r);i&&($(this,Di).set(r,i.effect),$(this,ln).delete(r),i.fragment.lastChild.remove(),this.anchor.before(i.fragment),n=i.effect)}for(let[s,a]of $(this,Qn)){if($(this,Qn).delete(s),s===e)break;let o=$(this,ln).get(a);o&&(ut(o.effect),$(this,ln).delete(a))}for(let[s,a]of $(this,Di)){if(s===r||$(this,fo).has(s))continue;let o=()=>{if(Array.from($(this,Qn).values()).includes(s)){var c=document.createDocumentFragment();Qp(a,c),c.append(It()),$(this,ln).set(s,{effect:a,fragment:c})}else ut(a);$(this,fo).delete(s),$(this,Di).delete(s)};$(this,wf)||!n?($(this,fo).add(s),Fi(a,o,!1)):o()}}});me(this,dm,e=>{$(this,Qn).delete(e);let r=Array.from($(this,Qn).values());for(let[n,i]of $(this,ln))r.includes(n)||(ut(i.effect),$(this,ln).delete(n))});this.anchor=e,de(this,wf,r)}ensure(e,r){var n=ye,i=sm();if(r&&!$(this,Di).has(e)&&!$(this,ln).has(e))if(i){var s=document.createDocumentFragment(),a=It();s.append(a),$(this,ln).set(e,{effect:Ht(()=>r(a)),fragment:s})}else $(this,Di).set(e,Ht(()=>r(this.anchor)));if($(this,Qn).set(n,e),i){for(let[o,l]of $(this,Di))o===e?n.unskip_effect(l):n.skip_effect(l);for(let[o,l]of $(this,ln))o===e?n.unskip_effect(l.effect):n.skip_effect(l.effect);n.oncommit($(this,yf)),n.ondiscard($(this,dm))}else re&&(this.anchor=ge),$(this,yf).call(this)}};Qn=new WeakMap,Di=new WeakMap,ln=new WeakMap,fo=new WeakMap,wf=new WeakMap,yf=new WeakMap,dm=new WeakMap;if(L){let t=function(e){if(!(e in globalThis)){let r;Object.defineProperty(globalThis,e,{configurable:!0,get:()=>{if(r!==void 0)return r;lM(e)},set:n=>{r=n}})}};t("$state"),t("$effect"),t("$derived"),t("$inspect"),t("$props"),t("$bindable")}function ho(t){ke===null&&Dp("onMount"),as&&ke.l!==null?i9(ke).m.push(t):sr(()=>{let e=ze(t);if(typeof e=="function")return e})}function i9(t){var r;var e=t.l;return(r=e.u)!=null?r:e.u={a:[],b:[],m:[]}}p();p();var oD=new Map;function lD(t,e){var r=oD.get(t);r||(r=new Set,oD.set(t,r)),r.add(e)}p();p();p();p();p();p();p();p();p();function Ae(t,e,r=!1){re&&er();var n=new ps(t),i=r?65536:0;function s(a,o){if(re){let c=Np(t)===bi;if(a===c){var l=ss();Ge(l),n.anchor=l,Bt(!1),n.ensure(a,o),Bt(!0);return}}n.ensure(a,o)}rn(()=>{var a=!1;e((o,l=!0)=>{a=!0,s(l,o)}),a||s(!1,null)},i)}p();var Cde=Symbol("NaN");p();p();function cn(t,e){return e}function f9(t,e,r){var f;for(var n=[],i=e.length,s,a=e.length,o=0;o{if(s){if(s.pending.delete(d),s.done.add(d),s.pending.size===0){var h=t.outrogroups;gb(Zl(s.done)),h.delete(s),h.size===0&&(t.outrogroups=null)}}else a-=1},!1)}if(a===0){var l=n.length===0&&r!==null;if(l){var c=r,u=c.parentNode;hc(u),u.append(c),t.items.clear()}gb(e,!l)}else s={pending:new Set(e),done:new Set},((f=t.outrogroups)!=null?f:t.outrogroups=new Set).add(s)}function gb(t,e=!0){for(var r=0;r{var w=r();return is(w)?w:w==null?[]:Zl(w)}),d,h=!0;function m(){v.fallback=u,d9(v,d,a,e,n),u!==null&&(d.length===0?u.f&33554432?(u.f^=33554432,_f(u,null,a)):gf(u):Fi(u,()=>{u=null}))}var g=rn(()=>{d=R(f);var w=d.length;let b=!1;if(re){var k=Np(a)===bi;k!==(w===0)&&(a=ss(),Ge(a),Bt(!1),b=!0)}for(var x=new Set,E=ye,A=sm(),y=0;ys(a)):(u=Ht(()=>s(gc!=null?gc:gc=It())),u.f|=33554432)),w>x.size&&(L?p9(d,n):Ly("","","")),re&&w>0&&Ge(ss()),!h)if(A){for(let[P,N]of o)x.has(P)||E.skip_effect(N.e);E.oncommit(m),E.ondiscard(()=>{})}else m();b&&Bt(!0),R(f)}),v={effect:g,flags:e,items:o,outrogroups:null,fallback:u};h=!1,re&&(a=ge)}function bf(t){for(;t!==null&&!(t.f&32);)t=t.next;return t}function d9(t,e,r,n,i){var C,P,N,B,H,ce,Pe,ve,ie;var s=(n&8)!==0,a=e.length,o=t.items,l=bf(t.effect.first),c,u=null,f,d=[],h=[],m,g,v,w;if(s)for(w=0;w0){var _=n&4&&a===0?r:null;if(s){for(w=0;w{var xe,we;if(f!==void 0)for(v of f)(we=(xe=v.nodes)==null?void 0:xe.a)==null||we.apply()})}function h9(t,e,r,n,i,s,a,o){var l=a&1?a&16?nr(r):lo(r,!1,!1):null,c=a&2?nr(i):null;return L&&l&&(l.trace=()=>{var u;o()[(u=c==null?void 0:c.v)!=null?u:i]}),{v:l,i:c,e:Ht(()=>(s(e,l!=null?l:r,c!=null?c:i,o),()=>{t.delete(n)}))}}function _f(t,e,r){if(t.nodes)for(var n=t.nodes.start,i=t.nodes.end,s=e&&!(e.f&33554432)?e.nodes.start:r;n!==null;){var a=Yt(n);if(s.before(n),n===i)return;n=a}}function sa(t,e,r){e===null?t.effect.first=r:e.next=r,r===null?t.effect.last=e:r.prev=e}function p9(t,e){let r=new Map,n=t.length;for(let i=0;iperformance.now():()=>Date.now(),Jn={tick:t=>(Ip?requestAnimationFrame:Fr)(t),now:()=>m9(),tasks:new Set};function uD(){let t=Jn.now();Jn.tasks.forEach(e=>{e.c(t)||(Jn.tasks.delete(e),e.f())}),Jn.tasks.size!==0&&Jn.tick(uD)}function fD(t){let e;return Jn.tasks.size===0&&Jn.tick(uD),{promise:new Promise(r=>{Jn.tasks.add(e={c:t,f:r})}),abort(){Jn.tasks.delete(e)}}}function hm(t,e){Kn(()=>{t.dispatchEvent(new CustomEvent(e))})}function y9(t){if(t==="float")return"cssFloat";if(t==="offset")return"cssOffset";if(t.startsWith("--"))return t;let e=t.split("-");return e.length===1?e[0]:e[0]+e.slice(1).map(r=>r[0].toUpperCase()+r.slice(1)).join("")}function dD(t){let e={},r=t.split(";");for(let n of r){let[i,s]=n.split(":");if(!i||s===void 0)break;let a=y9(i.trim());e[a]=s.trim()}return e}var b9=t=>t;function ei(t,e,r,n){var k,x;var i=(t&1)!==0,s=(t&2)!==0,a=i&&s,o=(t&4)!==0,l=a?"both":i?"in":"out",c,u=e.inert,f=e.style.overflow,d,h;function m(){return Kn(()=>{var E;return c!=null?c:c=r()(e,(E=n==null?void 0:n())!=null?E:{},{direction:l})})}var g={is_global:o,in(){var E;if(e.inert=u,!i){h==null||h.abort(),(E=h==null?void 0:h.reset)==null||E.call(h);return}s||d==null||d.abort(),d=vb(e,m(),h,1,()=>{hm(e,"introend"),d==null||d.abort(),d=c=void 0,e.style.overflow=f})},out(E){if(!s){E==null||E(),c=void 0;return}e.inert=!0,h=vb(e,m(),d,0,()=>{hm(e,"outroend"),E==null||E()})},stop:()=>{d==null||d.abort(),h==null||h.abort()}},v=ne;if(((x=(k=v.nodes).t)!=null?x:k.t=[]).push(g),i&&fm){var w=o;if(!w){for(var b=v.parent;b&&b.f&65536;)for(;(b=b.parent)&&!(b.f&16););w=!b||(b.f&32768)!==0}w&&Wr(()=>{ze(()=>g.in())})}}function vb(t,e,r,n,i){var s=n===1;if(My(e)){var a,o=!1;return vt(()=>{if(!o){var v=e({direction:s?"in":"out"});a=vb(t,v,r,n,i)}}),{abort:()=>{o=!0,a==null||a.abort()},deactivate:()=>a.deactivate(),reset:()=>a.reset(),t:()=>a.t()}}if(r==null||r.deactivate(),!(e!=null&&e.duration)&&!(e!=null&&e.delay))return hm(t,s?"introstart":"outrostart"),i(),{abort:Fr,deactivate:Fr,reset:Fr,t:()=>n};let{delay:l=0,css:c,tick:u,easing:f=b9}=e;var d=[];if(s&&r===void 0&&(u&&u(0,1),c)){var h=dD(c(0,1));d.push(h,h)}var m=()=>1-n,g=t.animate(d,{duration:l,fill:"forwards"});return g.onfinish=()=>{var _;g.cancel(),hm(t,s?"introstart":"outrostart");var v=(_=r==null?void 0:r.t())!=null?_:1-n;r==null||r.abort();var w=n-v,b=e.duration*Math.abs(w),k=[];if(b>0){var x=!1;if(c)for(var E=Math.ceil(b/16.666666666666668),A=0;A<=E;A+=1){var y=v+w*f(A/E),S=dD(c(y,1-y));k.push(S),x||(x=S.overflow==="hidden")}x&&(t.style.overflow="hidden"),m=()=>{var C=g.currentTime;return v+w*f(C/b)},u&&fD(()=>{if(g.playState!=="running")return!1;var C=m();return u(C,1-C),!0})}g=t.animate(k,{duration:b,fill:"forwards"}),g.onfinish=()=>{m=()=>n,u==null||u(n,1-n),i()}},{abort:()=>{g&&(g.cancel(),g.effect=null,g.onfinish=Fr)},deactivate:()=>{i=Fr},reset:()=>{n===0&&(u==null||u(1,0))},t:()=>m()}}p();p();function ti(t,e){Wr(()=>{var i;var r=t.getRootNode(),n=r.host?r:(i=r.head)!=null?i:r.ownerDocument.head;if(!n.querySelector("#"+e.hash)){let s=document.createElement("style");s.id=e.hash,s.textContent=e.code,n.appendChild(s),L&&lD(e.hash,s)}})}p();p();p();p();p();p();var pD=[...` +\r\f\xA0\v\uFEFF`];function mD(t,e,r){var n=t==null?"":""+t;if(e&&(n=n?n+" "+e:e),r){for(var i in r)if(r[i])n=n?n+" "+i:i;else if(n.length)for(var s=i.length,a=0;(a=n.indexOf(i,a))>=0;){var o=a+s;(a===0||pD.includes(n[a-1]))&&(o===n.length||pD.includes(n[o]))?n=(a===0?"":n.substring(0,a))+n.substring(o+1):a=o}}return n===""?null:n}p();function ft(t,e,r,n,i,s){var a=t.__className;if(re||a!==r||a===void 0){var o=mD(r,n,s);(!re||o!==t.getAttribute("class"))&&(o==null?t.removeAttribute("class"):e?t.className=o:t.setAttribute("class",o)),t.__className=r}else if(s&&i!==s)for(var l in s){var c=!!s[l];(i==null||c!==!!i[l])&&t.classList.toggle(l,c)}return s}p();p();var T9=Symbol("class"),P9=Symbol("style"),R9=Symbol("is custom element"),$9=Symbol("is html");function _e(t,e,r,n){var i=I9(t);if(re&&(i[e]=t.getAttribute(e),e==="src"||e==="srcset"||e==="href"&&t.nodeName==="LINK")){n||O9(t,e,r!=null?r:"");return}i[e]!==(i[e]=r)&&(e==="loading"&&(t[JO]=r),r==null?t.removeAttribute(e):typeof r!="string"&&F9(t).includes(e)?t[e]=r:t.setAttribute(e,r))}function I9(t){var e;return(e=t.__attributes)!=null?e:t.__attributes={[R9]:t.nodeName.includes("-"),[$9]:t.namespaceURI===ZO}}var gD=new Map;function F9(t){var e=t.getAttribute("is")||t.nodeName,r=gD.get(e);if(r)return r;gD.set(e,r=[]);for(var n,i=t,s=Element.prototype;s!==i;){n=Iy(i);for(var a in n)n[a].set&&r.push(a);i=Kl(i)}return r}function O9(t,e,r){var n;L&&(e==="srcset"&&M9(t,r)||wb((n=t.getAttribute(e))!=null?n:"",r)||pM(e,t.outerHTML.replace(t.innerHTML,t.innerHTML&&"..."),String(r)))}function wb(t,e){return t===e?!0:new URL(t,document.baseURI).href===new URL(e,document.baseURI).href}function vD(t){return t.split(",").map(e=>e.trim().split(" ").filter(Boolean))}function M9(t,e){var r=vD(t.srcset),n=vD(e);return n.length===r.length&&n.every(([i,s],a)=>s===r[a][1]&&(wb(r[a][0],i)||wb(i,r[a][0])))}p();p();p();function _b(t,e,r=e){var n=new WeakSet;ob(t,"input",async i=>{L&&t.type==="checkbox"&&Dy();var s=i?t.defaultValue:t.value;if(s=yb(t)?bb(s):s,r(s),ye!==null&&n.add(ye),await lm(),s!==(s=e())){var a=t.selectionStart,o=t.selectionEnd,l=t.value.length;if(t.value=s!=null?s:"",o!==null){var c=t.value.length;a===o&&o===l&&c>l?(t.selectionStart=c,t.selectionEnd=c):(t.selectionStart=a,t.selectionEnd=Math.min(o,c))}}}),(re&&t.defaultValue!==t.value||ze(e)==null&&t.value)&&(r(yb(t)?bb(t.value):t.value),ye!==null&&n.add(ye)),Xt(()=>{var a;L&&t.type==="checkbox"&&Dy();var i=e();if(t===document.activeElement){var s=(a=lf)!=null?a:ye;if(n.has(s))return}yb(t)&&i===bb(t.value)||t.type==="date"&&!i&&!t.value||i!==t.value&&(t.value=i!=null?i:"")})}function yb(t){var e=t.type;return e==="number"||e==="range"}function bb(t){return t===""?null:+t}p();p();p();p();p();function yD(t,e){return t===e||(t==null?void 0:t[Wt])===e}function it(t={},e,r,n){return Wr(()=>{var i,s;return Xt(()=>{i=s,s=(n==null?void 0:n())||[],ze(()=>{t!==r(...s)&&(e(t,...s),i&&yD(r(...i),t)&&e(null,...i))})}),()=>{vt(()=>{s&&yD(r(...s),t)&&e(null,...s)})}}),t}p();p();p();p();p();p();p();p();p();var mm=!1,Vge=Symbol();function Sb(t){var e=mm;try{return mm=!1,[t(),mm]}finally{mm=e}}function Pn(t,e,r,n){var k,x;var i=!as||(r&2)!==0,s=(r&8)!==0,a=(r&16)!==0,o=n,l=!0,c=()=>(l&&(l=!1,o=a?ze(n):n),o),u;if(s){var f=Wt in t||rf in t;u=(x=(k=Ir(t,e))==null?void 0:k.set)!=null?x:f&&e in t?E=>t[e]=E:void 0}var d,h=!1;s?[d,h]=Sb(()=>t[e]):d=t[e],d===void 0&&n!==void 0&&(d=c(),u&&(i&&oM(e),u(d)));var m;if(i?m=()=>{var E=t[e];return E===void 0?c():(l=!0,E)}:m=()=>{var E=t[e];return E!==void 0&&(o=void 0),E===void 0?o:E},i&&!(r&4))return m;if(u){var g=t.$$legacy;return function(E,A){return arguments.length>0?((!i||!A||g||h)&&u(A?m():E),E):m()}}var v=!1,w=(r&1?so:ao)(()=>(v=!1,m()));L&&(w.label=e),s&&R(w);var b=ne;return function(E,A){if(arguments.length>0){let y=A?R(w):i&&s?Ye(E):E;return se(w,y),v=!0,o!==void 0&&(o=y),E}return Tn&&v||b.f&16384?w.v:R(w)}}p();p();p();function bD(t){return new Eb(t)}var gs,Rn,Eb=class{constructor(e){me(this,gs);me(this,Rn);var s,a;var r=new Map,n=(o,l)=>{var c=lo(l,!1,!1);return r.set(o,c),c};let i=new Proxy({...e.props||{},$$events:{}},{get(o,l){var c;return R((c=r.get(l))!=null?c:n(l,Reflect.get(o,l)))},has(o,l){var c;return l===rf?!0:(R((c=r.get(l))!=null?c:n(l,Reflect.get(o,l))),Reflect.has(o,l))},set(o,l,c){var u;return se((u=r.get(l))!=null?u:n(l,c),c),Reflect.set(o,l,c)}});de(this,Rn,(e.hydrate?mb:ia)(e.component,{target:e.target,anchor:e.anchor,props:i,context:e.context,intro:(s=e.intro)!=null?s:!1,recover:e.recover})),!tr&&(!((a=e==null?void 0:e.props)!=null&&a.$$host)||e.sync===!1)&&eo(),de(this,gs,i.$$events);for(let o of Object.keys($(this,Rn)))o==="$set"||o==="$destroy"||o==="$on"||Jt(this,o,{get(){return $(this,Rn)[o]},set(l){$(this,Rn)[o]=l},enumerable:!0});$(this,Rn).$set=o=>{Object.assign(i,o)},$(this,Rn).$destroy=()=>{hs($(this,Rn))}}$set(e){$(this,Rn).$set(e)}$on(e,r){$(this,gs)[e]=$(this,gs)[e]||[];let n=(...i)=>r.call(this,...i);return $(this,gs)[e].push(n),()=>{$(this,gs)[e]=$(this,gs)[e].filter(i=>i!==n)}}$destroy(){$(this,Rn).$destroy()}};gs=new WeakMap,Rn=new WeakMap;var X9;typeof HTMLElement=="function"&&(X9=class extends HTMLElement{constructor(e,r,n){super();qe(this,"$$ctor");qe(this,"$$s");qe(this,"$$c");qe(this,"$$cn",!1);qe(this,"$$d",{});qe(this,"$$r",!1);qe(this,"$$p_d",{});qe(this,"$$l",{});qe(this,"$$l_u",new Map);qe(this,"$$me");qe(this,"$$shadowRoot",null);this.$$ctor=e,this.$$s=r,n&&(this.$$shadowRoot=this.attachShadow(n))}addEventListener(e,r,n){if(this.$$l[e]=this.$$l[e]||[],this.$$l[e].push(r),this.$$c){let i=this.$$c.$on(e,r);this.$$l_u.set(r,i)}super.addEventListener(e,r,n)}removeEventListener(e,r,n){if(super.removeEventListener(e,r,n),this.$$c){let i=this.$$l_u.get(r);i&&(i(),this.$$l_u.delete(r))}}async connectedCallback(){if(this.$$cn=!0,!this.$$c){let e=function(i){return s=>{let a=document.createElement("slot");i!=="default"&&(a.name=i),ae(s,a)}};if(await Promise.resolve(),!this.$$cn||this.$$c)return;let r={},n=Z9(this);for(let i of this.$$s)i in n&&(i==="default"&&!this.$$d.children?(this.$$d.children=e(i),r.default=!0):r[i]=e(i));for(let i of this.attributes){let s=this.$$g_p(i.name);s in this.$$d||(this.$$d[s]=kb(s,i.value,this.$$p_d,"toProp"))}for(let i in this.$$p_d)!(i in this.$$d)&&this[i]!==void 0&&(this.$$d[i]=this[i],delete this[i]);this.$$c=bD({component:this.$$ctor,target:this.$$shadowRoot||this,props:{...this.$$d,$$slots:r,$$host:this}}),this.$$me=cb(()=>{Xt(()=>{var i;this.$$r=!0;for(let s of $y(this.$$c)){if(!((i=this.$$p_d[s])!=null&&i.reflect))continue;this.$$d[s]=this.$$c[s];let a=kb(s,this.$$d[s],this.$$p_d,"toAttribute");a==null?this.removeAttribute(this.$$p_d[s].attribute||s):this.setAttribute(this.$$p_d[s].attribute||s,a)}this.$$r=!1})});for(let i in this.$$l)for(let s of this.$$l[i]){let a=this.$$c.$on(i,s);this.$$l_u.set(s,a)}this.$$l={}}}attributeChangedCallback(e,r,n){var i;this.$$r||(e=this.$$g_p(e),this.$$d[e]=kb(e,n,this.$$p_d,"toProp"),(i=this.$$c)==null||i.$set({[e]:this.$$d[e]}))}disconnectedCallback(){this.$$cn=!1,Promise.resolve().then(()=>{!this.$$cn&&this.$$c&&(this.$$c.$destroy(),this.$$me(),this.$$c=void 0)})}$$g_p(e){return $y(this.$$p_d).find(r=>this.$$p_d[r].attribute===e||!this.$$p_d[r].attribute&&r.toLowerCase()===e)||e}});function kb(t,e,r,n){var s;let i=(s=r[t])==null?void 0:s.type;if(e=i==="Boolean"&&typeof e!="boolean"?e!=null:e,!n||!r[t])return e;if(n==="toAttribute")switch(i){case"Object":case"Array":return e==null?null:JSON.stringify(e);case"Boolean":return e?"":null;case"Number":return e==null?null:e;default:return e}else switch(i){case"Object":case"Array":return e&&JSON.parse(e);case"Boolean":return e;case"Number":return e!=null?+e:e;default:return e}}function Z9(t){let e={};return t.childNodes.forEach(r=>{e[r.slot||"default"]=!0}),e}p();p();function po(t,e,r,n){function i(s){return s instanceof r?s:new r(function(a){a(s)})}return new(r||(r=Promise))(function(s,a){function o(u){try{c(n.next(u))}catch(f){a(f)}}function l(u){try{c(n.throw(u))}catch(f){a(f)}}function c(u){u.done?s(u.value):i(u.value).then(o,l)}c((n=n.apply(t,e||[])).next())})}var Pb=require("obsidian");p();var Cb=require("obsidian");p();function K9(t){let e=t-1;return e*e*e+1}var Ab=!1;function Ni(t,{delay:e=0,duration:r=400,easing:n=K9,axis:i="y"}={}){let s=getComputedStyle(t);L&&!Ab&&/(contents|inline|table)/.test(s.display)&&(Ab=!0,Promise.resolve().then(()=>Ab=!1),wM(s.display));let a=+s.opacity,o=i==="y"?"height":"width",l=parseFloat(s[o]),c=i==="y"?["top","bottom"]:["left","right"],u=c.map(w=>`${w[0].toUpperCase()}${w.slice(1)}`),f=parseFloat(s[`padding${u[0]}`]),d=parseFloat(s[`padding${u[1]}`]),h=parseFloat(s[`margin${u[0]}`]),m=parseFloat(s[`margin${u[1]}`]),g=parseFloat(s[`border${u[0]}Width`]),v=parseFloat(s[`border${u[1]}Width`]);return{delay:e,duration:r,easing:n,css:w=>`overflow: hidden;opacity: ${Math.min(w*20,1)*a};${o}: ${w*l}px;padding-${c[0]}: ${w*f}px;padding-${c[1]}: ${w*d}px;margin-${c[0]}: ${w*h}px;margin-${c[1]}: ${w*m}px;border-${c[0]}-width: ${w*g}px;border-${c[1]}-width: ${w*v}px;min-${o}: 0`}}p();var gm=require("obsidian");var Q9=fe('
'),J9=fe('
'),e7={hash:"svelte-1c0jiav",code:"main.svelte-1c0jiav .nav-file-title:where(.svelte-1c0jiav) {align-items:center;}"};function xf(t,e){at(e,!0),ti(t,e7);let r=Ye([]),n=St(()=>e.view.leaf.getRoot().side=="left"?"right":"left");sr(()=>{for(let w of r)w&&(0,gm.setIcon)(w,w.getAttr("data-icon"))});function i(w){w.stopPropagation(),ml(e.diff.path)?s(w):a(w)}function s(w){var b;w.stopPropagation();let k=e.view.app.vault.getAbstractFileByPath(e.diff.vaultPath);k instanceof gm.TFile&&((b=Bn(e.view.app,w))===null||b===void 0||b.openFile(k).catch(x=>e.view.plugin.displayError(x)))}function a(w){var b;e.view.plugin.tools.openDiff({event:w,aFile:(b=e.diff.fromPath)!==null&&b!==void 0?b:e.diff.path,aRef:`${e.diff.hash}^`,bFile:e.diff.path,bRef:e.diff.hash})}var o=J9();o.__click=i;var l=j(o),c=j(l),u=j(c,!0);G(c);var f=ee(c,2),d=j(f),h=j(d);{var m=w=>{var b=Q9();b.__click=s,it(b,k=>r[0]=k,()=>r==null?void 0:r[0]),on("auxclick",b,s),ae(w,b)};Ae(h,w=>{gl(e.diff.vaultPath,e.view.app)&&w(m)})}G(d);var g=ee(d,2),v=j(g,!0);G(g),G(f),G(l),G(o),Ne(w=>{_e(l,"data-path",e.diff.vaultPath),_e(l,"data-tooltip-position",R(n)),_e(l,"aria-label",e.diff.vaultPath),He(u,w),_e(g,"data-type",e.diff.status),He(v,e.diff.status)},[()=>vi(e.diff.vaultPath)]),on("auxclick",o,w=>{w.stopPropagation(),w.button==2?gi(e.view.app,w,e.diff.vaultPath,e.view.leaf,"git-history"):i(w)}),ae(t,o),ot()}Et(["click"]);p();var t7=fe("
"),r7=fe(''),n7=fe('
'),i7=fe("
"),s7={hash:"svelte-d9h7mp",code:"main.svelte-d9h7mp .nav-folder-title-content:where(.svelte-d9h7mp) {display:flex;align-items:center;}"};function Sf(t,e){at(e,!0),ti(t,s7);let r=Pn(e,"topLevel",3,!1),n=Pn(e,"closed",15),i=St(()=>e.view.leaf.getRoot().side=="left"?"right":"left");function s(l,c){l.stopPropagation(),n(n()[c.path]=!n()[c.path],!0)}var a=i7();let o;un(a,21,()=>e.hierarchy.children,cn,(l,c)=>{var u=ds(),f=qr(u);{var d=m=>{var g=t7(),v=j(g);xf(v,{get diff(){return R(c).data},get view(){return e.view}}),G(g),ae(m,g)},h=m=>{var g=n7();let v;var w=j(g);w.__click=S=>s(S,R(c));var b=ee(j(w),2);let k;var x=ee(b,2),E=j(x,!0);G(x),G(w);var A=ee(w,2);{var y=S=>{var _=r7(),C=j(_);Sf(C,{get hierarchy(){return R(c)},get plugin(){return e.plugin},get view(){return e.view},get closed(){return n()},set closed(P){n(P)}}),G(_),ei(3,_,()=>Ni,()=>({duration:150})),ae(S,_)};Ae(A,S=>{n()[R(c).path]||S(y)})}G(g),Ne(()=>{v=ft(g,1,"tree-item nav-folder",null,v,{"is-collapsed":n()[R(c).path]}),_e(w,"data-tooltip-position",R(i)),_e(w,"aria-label",R(c).vaultPath),k=ft(b,1,"tree-item-icon nav-folder-collapse-indicator collapse-icon",null,k,{"is-collapsed":n()[R(c).path]}),He(E,R(c).title)}),ae(m,g)};Ae(f,m=>{R(c).data?m(d):m(h,!1)})}ae(l,u)}),G(a),Ne(()=>o=ft(a,1,"svelte-d9h7mp",null,o,{topLevel:r()})),ae(t,a),ot()}Et(["click"]);var a7=fe('
'),o7=fe('
'),l7=fe('
'),c7=fe(''),u7=fe('
'),f7={hash:"svelte-1edsiy5",code:""};function Tb(t,e){at(e,!0),ti(t,f7);let r=St(()=>({title:"",path:"",vaultPath:"",children:e.plugin.gitManager.getTreeStructure(e.log.diff.files)})),n=St(()=>e.view.leaf.getRoot().side=="left"?"right":"left"),i=Me(!0),s=Me(Ye({}));function a(S){let _=S.author.name;if(e.plugin.settings.authorInHistoryView=="full")return _;if(e.plugin.settings.authorInHistoryView=="initials")return _.split(" ").filter(P=>P.length>0).map(P=>P[0].toUpperCase()).join("")}var o=u7(),l=j(o);let c;var u=j(l);u.__click=()=>se(i,!R(i));var f=j(u);let d;var h=ee(f,2),m=j(h);{var g=S=>{var _=a7(),C=j(_,!0);G(_),Ne(P=>He(C,P),[()=>e.log.refs.join(", ")]),ae(S,_)};Ae(m,S=>{e.log.refs.length>0&&S(g)})}var v=ee(m,2);{var w=S=>{var _=o7(),C=j(_,!0);G(_),Ne(P=>He(C,P),[()=>a(e.log)]),ae(S,_)};Ae(v,S=>{var _;e.plugin.settings.authorInHistoryView!="hide"&&((_=e.log.author)!=null&&_.name)&&S(w)})}var b=ee(v,2);{var k=S=>{var _=l7(),C=j(_,!0);G(_),Ne(P=>He(C,P),[()=>(0,Cb.moment)(e.log.date).format(e.plugin.settings.commitDateFormat)]),ae(S,_)};Ae(b,S=>{e.plugin.settings.dateInHistoryView&&S(k)})}var x=ee(b,2),E=j(x,!0);G(x),G(h),G(u);var A=ee(u,2);{var y=S=>{var _=c7(),C=j(_);{var P=B=>{Sf(B,{get hierarchy(){return R(r)},get plugin(){return e.plugin},get view(){return e.view},topLevel:!0,get closed(){return R(s)},set closed(H){se(s,H,!0)}})},N=B=>{var H=ds(),ce=qr(H);un(ce,17,()=>e.log.diff.files,cn,(Pe,ve)=>{xf(Pe,{get view(){return e.view},get diff(){return R(ve)}})}),ae(B,H)};Ae(C,B=>{e.showTree?B(P):B(N,!1)})}G(_),ei(3,_,()=>Ni,()=>({duration:150})),ae(S,_)};Ae(A,S=>{R(i)||S(y)})}G(l),G(o),Ne(S=>{c=ft(l,1,"tree-item nav-folder",null,c,{"is-collapsed":R(i)}),_e(u,"aria-label",S),_e(u,"data-tooltip-position",R(n)),d=ft(f,1,"tree-item-icon nav-folder-collapse-indicator collapse-icon",null,d,{"is-collapsed":R(i)}),He(E,e.log.message)},[()=>{var S;return`${e.log.refs.length>0?e.log.refs.join(", ")+` +`:""}${(S=e.log.author)==null?void 0:S.name} +${(0,Cb.moment)(e.log.date).format(e.plugin.settings.commitDateFormat)} +${e.log.message}`}]),ae(t,o),ot()}Et(["click"]);var d7=fe(''),h7=fe('
'),p7={hash:"svelte-12n6twc",code:""};function Rb(t,e){at(e,!0),ti(t,p7);let r=Pn(e,"plugin",15),n=Me(!1),i=Ye([]),s=Me(void 0),a=Me(Ye(r().settings.treeStructure)),o;sr(()=>{o&&o.empty()}),ho(()=>{e.view.registerEvent(e.view.app.workspace.on("obsidian-git:head-change",()=>void c().catch(console.error)))}),sr(()=>{i.forEach(x=>(0,Pb.setIcon)(x,x.getAttr("data-icon")))}),ho(()=>{let x=new IntersectionObserver(A=>{A[0].isIntersecting&&!R(n)&&u().catch(console.error)}),E=document.querySelector("#sentinel");return E&&x.observe(E),()=>{x.disconnect()}}),c().catch(console.error);function l(){c().catch(console.error)}function c(){return po(this,void 0,void 0,function*(){var x;if(!r().gitReady){se(s,void 0);return}se(n,!0);let E=r().gitManager instanceof Se,A;((x=R(s)===null||R(s)===void 0?void 0:R(s).length)!==null&&x!==void 0?x:0)==0?A=E?50:10:A=R(s).length,se(s,yield r().gitManager.log(void 0,!1,A),!0),se(n,!1)})}function u(){return po(this,void 0,void 0,function*(){var x;if(!r().gitReady||R(s)===void 0)return;se(n,!0);let A=r().gitManager instanceof Se?50:10,y=yield r().gitManager.log(void 0,!1,A,(x=R(s).last())===null||x===void 0?void 0:x.hash);R(s).push(...y.slice(1)),se(n,!1)})}var f=h7(),d=j(f),h=j(d),m=j(h);m.__click=()=>{se(a,!R(a)),(0,Pb.setIcon)(i[0],R(a)?"list":"folder"),r(r().settings.treeStructure=R(a),!0),r().saveSettings()},it(m,x=>i[0]=x,()=>i==null?void 0:i[0]);var g=ee(m,2);let v;g.__click=l,it(g,x=>i[1]=x,()=>i==null?void 0:i[1]),G(h),G(d);var w=ee(d,2),b=j(w);{var k=x=>{var E=d7();un(E,21,()=>R(s),cn,(A,y)=>{Tb(A,{get view(){return e.view},get showTree(){return R(a)},get log(){return R(y)},get plugin(){return r()}})}),G(E),ae(x,E)};Ae(b,x=>{R(s)&&x(k)})}Xa(4),G(w),G(f),Ne(()=>{_e(m,"data-icon",R(a)?"list":"folder"),v=ft(g,1,"clickable-icon nav-action-button",null,v,{loading:R(n)})}),ae(t,f),ot()}Et(["click"]);var Ef=class extends _D.ItemView{constructor(e,r){super(e),this.plugin=r,this.hoverPopover=null}getViewType(){return gn.type}getDisplayText(){return gn.name}getIcon(){return gn.icon}onClose(){return this._view&&hs(this._view),super.onClose()}reload(){this._view&&hs(this._view),this._view=ia(Rb,{target:this.contentEl,props:{plugin:this.plugin,view:this}})}onOpen(){return this.reload(),super.onOpen()}};p();var xD=require("obsidian"),vm=class extends xD.FuzzySuggestModal{constructor(r,n){super(r.app);this.branches=n;this.setPlaceholder("Select branch to checkout")}getItems(){return this.branches}getItemText(r){return r}onChooseItem(r,n){this.resolve(r)}openAndGetReslt(){return new Promise(r=>{this.resolve=r,this.open()})}onClose(){new Promise(r=>setTimeout(r,10)).then(()=>{this.resolve&&this.resolve(void 0)})}};p();var kD=require("obsidian");p();var vo=require("obsidian");p();var kf=require("obsidian");p();var SD=require("obsidian");var vc=class extends SD.Modal{constructor({app:r,path:n,filesToDeleteCount:i,filesToDiscardCount:s}){super(r);this.resolve=null;this.path=n,this.deleteCount=i,this.discardCount=s}openAndGetResult(){return this.open(),new Promise(r=>{this.resolve=r})}onOpen(){let r=this.deleteCount+this.discardCount,{contentEl:n,titleEl:i}=this,s="";this.path!=""&&(r>1?s=`files in "${this.path}"`:s=`"${this.path}"`),i.setText(`${this.discardCount==0?"Delete":"Discard"} ${s}`),this.deleteCount>0&&n.createEl("p").setText(`Are you sure you want to DELETE the ${Pu(this.deleteCount,"untracked file")}? They are deleted according to your Obsidian trash settting.`),this.discardCount>0&&n.createEl("p").setText(`Are you sure you want to discard ALL changes in ${Pu(this.discardCount,"tracked file")}?`);let a=n.createDiv({cls:"modal-button-container"});if(this.deleteCount>0){let l=a.createEl("button",{cls:"mod-warning",text:`${this.discardCount>0?"Discard":"Delete"} all ${Pu(r,"file")}`});l.addEventListener("click",()=>{this.resolve&&this.resolve("delete"),this.close()}),l.addEventListener("keypress",()=>{this.resolve&&this.resolve("delete"),this.close()})}if(this.discardCount>0){let l=a.createEl("button",{cls:"mod-warning",text:`Discard all ${Pu(this.discardCount,"tracked file")}`});l.addEventListener("click",()=>{this.resolve&&this.resolve("discard"),this.close()}),l.addEventListener("keypress",()=>{this.resolve&&this.resolve("discard"),this.close()})}let o=a.createEl("button",{text:"Cancel"});o.addEventListener("click",()=>(this.resolve&&this.resolve(!1),this.close())),o.addEventListener("keypress",()=>(this.resolve&&this.resolve(!1),this.close()))}onClose(){let{contentEl:r}=this;r.empty()}};var m7=fe('
'),g7=fe('
');function Af(t,e){at(e,!0);let r=Ye([]),n=St(()=>e.view.leaf.getRoot().side=="left"?"right":"left");sr(()=>{for(let A of r)A&&(0,kf.setIcon)(A,A.getAttr("data-icon"))});function i(A){A.stopPropagation(),ml(e.change.path)?a(A):l(A)}function s(A){e.view.app.vault.getAbstractFileByPath(e.change.vaultPath)&&vl(e.view.app,A,e.view,e.change.vaultPath)}function a(A){var y;A.stopPropagation();let S=e.view.app.vault.getAbstractFileByPath(e.change.vaultPath);S instanceof kf.TFile&&((y=Bn(e.view.app,A))===null||y===void 0||y.openFile(S).catch(_=>e.view.plugin.displayError(_)))}function o(A){A.stopPropagation(),e.manager.stage(e.change.path,!1).catch(y=>e.view.plugin.displayError(y)).finally(()=>{e.view.app.workspace.trigger("obsidian-git:refresh")})}function l(A){A.stopPropagation(),e.view.plugin.tools.openDiff({aFile:e.change.path,aRef:"",event:A})}function c(A){A.stopPropagation();let y=e.change.workingDir=="U";new vc({app:e.view.app,filesToDeleteCount:y?1:0,filesToDiscardCount:y?0:1,path:e.change.vaultPath}).openAndGetResult().then(S=>po(this,void 0,void 0,function*(){if(S=="delete"){let _=e.view.app.vault.getAbstractFileByPath(e.change.vaultPath);_ instanceof kf.TFile?yield e.view.app.fileManager.trashFile(_):yield e.view.app.vault.adapter.remove(e.change.vaultPath)}else S=="discard"&&(yield e.manager.discard(e.change.path).finally(()=>{e.view.app.workspace.trigger("obsidian-git:refresh")}));e.view.app.workspace.trigger("obsidian-git:refresh")}),S=>e.view.plugin.displayError(S))}var u=g7();u.__mouseover=s,u.__click=i;var f=j(u),d=j(f),h=j(d,!0);G(d);var m=ee(d,2),g=j(m),v=j(g);{var w=A=>{var y=m7();y.__click=a,it(y,S=>r[0]=S,()=>r==null?void 0:r[0]),on("auxclick",y,a),ae(A,y)};Ae(v,A=>{gl(e.change.vaultPath,e.view.app)&&A(w)})}var b=ee(v,2);b.__click=c,it(b,A=>r[1]=A,()=>r==null?void 0:r[1]);var k=ee(b,2);k.__click=o,it(k,A=>r[2]=A,()=>r==null?void 0:r[2]),G(g);var x=ee(g,2),E=j(x,!0);G(x),G(m),G(f),G(u),Ne(A=>{_e(f,"data-path",e.change.vaultPath),_e(f,"data-tooltip-position",R(n)),_e(f,"aria-label",e.change.vaultPath),He(h,A),_e(x,"data-type",e.change.workingDir),He(E,e.change.workingDir)},[()=>vi(e.change.vaultPath)]),on("auxclick",u,A=>{A.stopPropagation(),A.button==2?gi(e.view.app,A,e.change.vaultPath,e.view.leaf,"git-source-control"):i(A)}),ae(t,u),ot()}Et(["mouseover","click"]);p();var ED=require("obsidian");var v7=fe('
');function Cf(t,e){at(e,!0);let r=St(()=>e.view.leaf.getRoot().side=="left"?"right":"left");function n(d){e.view.app.vault.getAbstractFileByPath(e.change.vaultPath)&&vl(e.view.app,d,e.view,e.change.vaultPath)}function i(d){var h;d.stopPropagation();let m=e.view.app.vault.getAbstractFileByPath(e.change.vaultPath);m instanceof ED.TFile&&((h=Bn(e.view.app,d))===null||h===void 0||h.openFile(m).catch(g=>e.view.plugin.displayError(g)))}var s=v7();s.__mouseover=n,s.__click=i;var a=j(s),o=j(a),l=j(o,!0);G(o);var c=ee(o,2),u=j(c),f=j(u,!0);G(u),G(c),G(a),G(s),Ne(d=>{_e(a,"data-path",e.change.vaultPath),_e(a,"data-tooltip-position",R(r)),_e(a,"aria-label",e.change.vaultPath),He(l,d),_e(u,"data-type",e.change.workingDir),He(f,e.change.workingDir)},[()=>vi(e.change.vaultPath)]),on("auxclick",s,d=>{d.stopPropagation(),d.button==2?gi(e.view.app,d,e.change.vaultPath,e.view.leaf,"git-source-control"):i(d)}),ae(t,s),ot()}Et(["mouseover","click"]);p();var wm=require("obsidian");var w7=fe('
'),y7=fe('
');function Tf(t,e){at(e,!0);let r=Ye([]),n=St(()=>e.view.leaf.getRoot().side=="left"?"right":"left");sr(()=>{for(let x of r)x&&(0,wm.setIcon)(x,x.getAttr("data-icon"))});function i(x){x.stopPropagation(),ml(e.change.path)?a(x):o(x)}function s(x){e.view.app.vault.getFileByPath(e.change.vaultPath)&&vl(e.view.app,x,e.view,e.change.vaultPath)}function a(x){var E;x.stopPropagation();let A=e.view.app.vault.getAbstractFileByPath(e.change.vaultPath);A instanceof wm.TFile&&((E=Bn(e.view.app,x))===null||E===void 0||E.openFile(A).catch(y=>e.view.plugin.displayError(y)))}function o(x){var E;x.stopPropagation(),e.view.plugin.tools.openDiff({aFile:(E=e.change.from)!==null&&E!==void 0?E:e.change.path,bFile:e.change.path,aRef:"HEAD",bRef:"",event:x})}function l(x){x.stopPropagation(),e.manager.unstage(e.change.path,!1).catch(E=>e.view.plugin.displayError(E)).finally(()=>{e.view.app.workspace.trigger("obsidian-git:refresh")})}var c=y7();c.__mouseover=s,c.__click=i;var u=j(c),f=j(u),d=j(f,!0);G(f);var h=ee(f,2),m=j(h),g=j(m);{var v=x=>{var E=w7();E.__click=a,it(E,A=>r[0]=A,()=>r==null?void 0:r[0]),ae(x,E)};Ae(g,x=>{gl(e.change.vaultPath,e.view.app)&&x(v)})}var w=ee(g,2);w.__click=l,it(w,x=>r[1]=x,()=>r==null?void 0:r[1]),G(m);var b=ee(m,2),k=j(b,!0);G(b),G(h),G(u),G(c),Ne(x=>{_e(u,"data-path",e.change.vaultPath),_e(u,"data-tooltip-position",R(n)),_e(u,"aria-label",e.change.vaultPath),He(d,x),_e(b,"data-type",e.change.index),He(k,e.change.index)},[()=>vi(e.change.vaultPath)]),on("auxclick",c,x=>{x.stopPropagation(),x.button==2?gi(e.view.app,x,e.change.vaultPath,e.view.leaf,"git-source-control"):i(x)}),ae(t,c),ot()}Et(["mouseover","click"]);p();p();var b7=fe(''),_7=fe("
");function mo(t,e){at(e,!0);var r=_7(),n=j(r);{var i=s=>{var a=b7(),o=j(a),l=j(o),c=j(l,!0);G(l),G(o),G(a),Ne(()=>{_e(o,"aria-label","And "+(e.files.length-500)+" more files"),He(c,"And "+(e.files.length-500)+" more files")}),ae(s,a)};Ae(n,s=>{e.files.length>500&&s(i)})}G(r),ae(t,r),ot()}var S7=fe("
"),E7=fe('
'),k7=fe('
',1),A7=fe(''),C7=fe('
'),T7=fe("
");function go(t,e){at(e,!0);let r=Pn(e,"topLevel",3,!1),n=Pn(e,"closed",15);ho(()=>{var h,m;for(let g of e.hierarchy.children)((m=(h=g.children)===null||h===void 0?void 0:h.length)!==null&&m!==void 0?m:0)>100&&n(n()[g.title]=!0,!0)});let i=St(()=>e.view.leaf.getRoot().side=="left"?"right":"left");function s(h,m){h.stopPropagation(),e.plugin.gitManager.stageAll({dir:m}).catch(g=>e.plugin.displayError(g)).finally(()=>{e.view.app.workspace.trigger("obsidian-git:refresh")})}function a(h,m){h.stopPropagation(),e.plugin.gitManager.unstageAll({dir:m}).catch(g=>e.plugin.displayError(g)).finally(()=>{e.view.app.workspace.trigger("obsidian-git:refresh")})}function o(h,m){h.stopPropagation(),e.plugin.discardAll(m.vaultPath)}function l(h,m){h.stopPropagation(),n(n()[m.path]=!n()[m.path],!0)}var c=T7();let u;var f=j(c);un(f,17,()=>Ru(e.hierarchy.children,500),cn,(h,m)=>{var g=ds(),v=qr(g);{var w=k=>{var x=S7(),E=j(x);{var A=S=>{Tf(S,{get change(){return R(m).data},get manager(){return e.plugin.gitManager},get view(){return e.view}})},y=S=>{var _=ds(),C=qr(_);{var P=B=>{Af(B,{get change(){return R(m).data},get manager(){return e.plugin.gitManager},get view(){return e.view}})},N=B=>{var H=ds(),ce=qr(H);{var Pe=ve=>{Cf(ve,{get change(){return R(m).data},get view(){return e.view}})};Ae(ce,ve=>{e.fileType==2&&ve(Pe)},!0)}ae(B,H)};Ae(C,B=>{e.fileType==1?B(P):B(N,!1)},!0)}ae(S,_)};Ae(E,S=>{e.fileType==0?S(A):S(y,!1)})}G(x),ae(k,x)},b=k=>{var x=C7();let E;var A=j(x);A.__click=ie=>l(ie,R(m));var y=ee(j(A),2);let S;var _=ee(y,2),C=j(_,!0);G(_);var P=ee(_,2),N=j(P),B=j(N);{var H=ie=>{var xe=E7();xe.__click=we=>a(we,R(m).path),ae(ie,xe)},ce=ie=>{var xe=k7(),we=qr(xe);we.__click=X=>o(X,R(m));var W=ee(we,2);W.__click=X=>s(X,R(m).path),ae(ie,xe)};Ae(B,ie=>{e.fileType==0?ie(H):ie(ce,!1)})}Xa(2),G(N),G(P),G(A);var Pe=ee(A,2);{var ve=ie=>{var xe=A7(),we=j(xe);go(we,{get hierarchy(){return R(m)},get plugin(){return e.plugin},get view(){return e.view},get fileType(){return e.fileType},get closed(){return n()},set closed(W){n(W)}}),G(xe),ei(3,xe,()=>Ni,()=>({duration:150})),ae(ie,xe)};Ae(Pe,ie=>{n()[R(m).path]||ie(ve)})}G(x),Ne(()=>{E=ft(x,1,"tree-item nav-folder",null,E,{"is-collapsed":n()[R(m).path]}),_e(A,"data-tooltip-position",R(i)),_e(A,"aria-label",R(m).vaultPath),S=ft(y,1,"tree-item-icon nav-folder-collapse-indicator collapse-icon",null,S,{"is-collapsed":n()[R(m).path]}),He(C,R(m).title)}),on("auxclick",x,ie=>gi(e.view.app,ie,R(m).vaultPath,e.view.leaf,"git-source-control")),ae(k,x)};Ae(v,k=>{R(m).data?k(w):k(b,!1)})}ae(h,g)});var d=ee(f,2);mo(d,{get files(){return e.hierarchy.children}}),G(c),Ne(()=>u=ft(c,1,"",null,u,{topLevel:r()})),ae(t,c),ot()}Et(["click"]);var P7=fe('
'),R7=fe(" ",1),$7=fe(''),I7=fe(" ",1),F7=fe(''),O7=fe(" ",1),M7=fe(''),D7=fe('
'),L7=fe(''),N7=fe('
'),B7={hash:"svelte-5wq9p",code:`.commit-msg-input.svelte-5wq9p {width:100%;overflow:hidden;resize:none;padding:7px 5px;background-color:var(--background-modifier-form-field);}.git-commit-msg.svelte-5wq9p {position:relative;padding:0;width:calc(100% - var(--size-4-8));margin:4px auto;}main.svelte-5wq9p .git-tools:where(.svelte-5wq9p) .files-count:where(.svelte-5wq9p) {padding-left:var(--size-2-1);width:11px;display:flex;align-items:center;justify-content:center;}.nav-folder-title.svelte-5wq9p {align-items:center;}.git-commit-msg-clear-button.svelte-5wq9p {position:absolute;background:transparent;border-radius:50%;color:var(--search-clear-button-color);cursor:var(--cursor);top:-4px;right:2px;bottom:0px;line-height:0;height:var(--input-height);width:28px;margin:auto;padding:0 0;text-align:center;display:flex;justify-content:center;align-items:center;transition:color 0.15s ease-in-out;}.git-commit-msg-clear-button.svelte-5wq9p:after {content:"";height:var(--search-clear-button-size);width:var(--search-clear-button-size);display:block;background-color:currentColor;mask-image:url("data:image/svg+xml,");mask-repeat:no-repeat;-webkit-mask-image:url("data:image/svg+xml,");-webkit-mask-repeat:no-repeat;}`};function $b(t,e){at(e,!0),ti(t,B7);let r=Pn(e,"plugin",7),n=Pn(e,"view",7),i=Me(!1),s=Me(void 0),a=Me(Ye([])),o=St(()=>r().settings.commitMessage),l=Ye([]),c=Me(void 0),u=Me(void 0),f=Me(void 0),d=Me(!0),h=Me(!0),m=Me(!0),g=Me(0),v=Me(Ye({})),w=Me(Ye({})),b=Me(Ye({})),k=St(()=>r().settings.treeStructure);ho(()=>{n().registerEvent(n().app.workspace.on("obsidian-git:loading-status",()=>se(i,!0))),n().registerEvent(n().app.workspace.on("obsidian-git:status-changed",()=>void A().catch(console.error))),n().plugin.cachedStatus==null?n().plugin.refresh().catch(console.error):A().catch(console.error),n().scope=new vo.Scope(r().app.scope),n().scope.register(["Ctrl"],"Enter",O=>E())}),sr(()=>{l.forEach(O=>(0,vo.setIcon)(O,O.getAttr("data-icon")))}),sr(()=>{l.forEach(O=>{var oe,Ce;!O||O.id!="push"||(vo.Platform.isMobile?(O.removeClass("button-border"),R(g)>0&&O.addClass("button-border")):((oe=O.firstElementChild)===null||oe===void 0||oe.removeAttribute("color"),R(g)>0&&((Ce=O.firstElementChild)===null||Ce===void 0||Ce.setAttr("color","var(--text-accent)"))))})});function x(){if(se(i,!0),R(s)){let O=R(s).staged.length>0;r().promiseQueue.addTask(()=>r().commit({fromAuto:!1,commitMessage:R(o),onlyStaged:O}).then(()=>se(o,r().settings.commitMessage)).finally(y))}}function E(){if(se(i,!0),R(s)){let O=R(s).staged.length>0;r().promiseQueue.addTask(()=>r().commitAndSync({fromAutoBackup:!1,commitMessage:R(o),onlyStaged:O}).then(()=>{se(o,r().settings.commitMessage)}).finally(y))}}function A(){return po(this,void 0,void 0,function*(){if(!r().gitReady){se(s,void 0);return}if(se(g,yield r().gitManager.getUnpushedCommits(),!0),se(s,r().cachedStatus,!0),se(i,!1),r().lastPulledFiles&&r().lastPulledFiles!=R(a)&&(se(a,r().lastPulledFiles,!0),se(f,{title:"",path:"",vaultPath:"",children:r().gitManager.getTreeStructure(R(a))},!0)),R(s)){let O=(oe,Ce)=>oe.vaultPath.split("/").last().localeCompare(vi(Ce.vaultPath));R(s).changed.sort(O),R(s).staged.sort(O),se(c,{title:"",path:"",vaultPath:"",children:r().gitManager.getTreeStructure(R(s).changed)},!0),se(u,{title:"",path:"",vaultPath:"",children:r().gitManager.getTreeStructure(R(s).staged)},!0)}else se(c,void 0),se(u,void 0)})}function y(){n().app.workspace.trigger("obsidian-git:refresh")}function S(O){O.stopPropagation(),se(i,!0),r().promiseQueue.addTask(()=>r().gitManager.stageAll({status:R(s)}).finally(y))}function _(O){O.stopPropagation(),se(i,!0),r().promiseQueue.addTask(()=>r().gitManager.unstageAll({status:R(s)}).finally(y))}function C(){se(i,!0),r().promiseQueue.addTask(()=>r().push().finally(y))}function P(){se(i,!0),r().promiseQueue.addTask(()=>r().pullChangesFromRemote().finally(y))}function N(O){O.stopPropagation(),r().discardAll()}let B=St(()=>(R(o).match(/\n/g)||[]).length+1||1);var H=N7(),ce=j(H),Pe=j(ce),ve=j(Pe);ve.__click=E,it(ve,O=>l[0]=O,()=>l==null?void 0:l[0]);var ie=ee(ve,2);ie.__click=x,it(ie,O=>l[1]=O,()=>l==null?void 0:l[1]);var xe=ee(ie,2);xe.__click=S,it(xe,O=>l[2]=O,()=>l==null?void 0:l[2]);var we=ee(xe,2);we.__click=_,it(we,O=>l[3]=O,()=>l==null?void 0:l[3]);var W=ee(we,2);W.__click=C,it(W,O=>l[4]=O,()=>l==null?void 0:l[4]);var X=ee(W,2);X.__click=P,it(X,O=>l[5]=O,()=>l==null?void 0:l[5]);var q=ee(X,2);q.__click=()=>{se(k,!R(k)),(0,vo.setIcon)(l[6],R(k)?"list":"folder"),r().settings.treeStructure=R(k),r().saveSettings()},it(q,O=>l[6]=O,()=>l==null?void 0:l[6]);var De=ee(q,2);let ar;De.__click=y,it(De,O=>l[7]=O,()=>l==null?void 0:l[7]),G(Pe),G(ce);var Ft=ee(ce,2),Ie=j(Ft);sb(Ie);var kt=ee(Ie,2);{var At=O=>{var oe=P7();oe.__click=()=>se(o,""),_e(oe,"aria-label","Clear"),ae(O,oe)};Ae(kt,O=>{R(o)&&O(At)})}G(Ft);var je=ee(Ft,2),Z=j(je);{var M=O=>{var oe=L7(),Ce=j(oe);let Ot;var wr=j(Ce);wr.__click=()=>se(h,!R(h));var bo=j(wr);let Db;var Lb=ee(bo,4),$m=j(Lb),Nb=j($m);Nb.__click=_,it(Nb,or=>l[8]=or,()=>l==null?void 0:l[8]),G($m);var Bb=ee($m,2),OD=j(Bb,!0);G(Bb),G(Lb),G(wr);var MD=ee(wr,2);{var DD=or=>{var yr=$7(),_o=j(yr);{var vs=lr=>{go(lr,{get hierarchy(){return R(u)},get plugin(){return r()},get view(){return n()},get fileType(){return 0},topLevel:!0,get closed(){return R(v)},set closed($n){se(v,$n,!0)}})},xo=lr=>{var $n=R7(),aa=qr($n);un(aa,17,()=>Ru(R(s).staged,500),cn,(ws,yc)=>{Tf(ws,{get change(){return R(yc)},get view(){return n()},get manager(){return r().gitManager}})});var oa=ee(aa,2);mo(oa,{get files(){return R(s).staged}}),ae(lr,$n)};Ae(_o,lr=>{R(k)?lr(vs):lr(xo,!1)})}G(yr),ei(3,yr,()=>Ni,()=>({duration:150})),ae(or,yr)};Ae(MD,or=>{R(h)&&or(DD)})}G(Ce);var Rf=ee(Ce,2);let Hb;var $f=j(Rf);$f.__click=()=>se(d,!R(d));var Ub=j($f);let Gb;var jb=ee(Ub,4),Im=j(jb),qb=j(Im);qb.__click=N;var Wb=ee(qb,2);Wb.__click=S,it(Wb,or=>l[9]=or,()=>l==null?void 0:l[9]),G(Im);var zb=ee(Im,2),LD=j(zb,!0);G(zb),G(jb),G($f);var ND=ee($f,2);{var BD=or=>{var yr=F7(),_o=j(yr);{var vs=lr=>{go(lr,{get hierarchy(){return R(c)},get plugin(){return r()},get view(){return n()},get fileType(){return 1},topLevel:!0,get closed(){return R(w)},set closed($n){se(w,$n,!0)}})},xo=lr=>{var $n=I7(),aa=qr($n);un(aa,17,()=>Ru(R(s).changed,500),cn,(ws,yc)=>{Af(ws,{get change(){return R(yc)},get view(){return n()},get manager(){return r().gitManager}})});var oa=ee(aa,2);mo(oa,{get files(){return R(s).changed}}),ae(lr,$n)};Ae(_o,lr=>{R(k)?lr(vs):lr(xo,!1)})}G(yr),ei(3,yr,()=>Ni,()=>({duration:150})),ae(or,yr)};Ae(ND,or=>{R(d)&&or(BD)})}G(Rf);var HD=ee(Rf,2);{var UD=or=>{var yr=D7();let _o;var vs=j(yr);vs.__click=()=>se(m,!R(m));var xo=ee(j(vs),4),lr=j(xo,!0);G(xo),G(vs);var $n=ee(vs,2);{var aa=oa=>{var ws=M7(),yc=j(ws);{var GD=So=>{go(So,{get hierarchy(){return R(f)},get plugin(){return r()},get view(){return n()},get fileType(){return 2},topLevel:!0,get closed(){return R(b)},set closed(If){se(b,If,!0)}})},jD=So=>{var If=O7(),Vb=qr(If);un(Vb,17,()=>R(a),cn,(WD,zD)=>{Cf(WD,{get change(){return R(zD)},get view(){return n()}})});var qD=ee(Vb,2);mo(qD,{get files(){return R(a)}}),ae(So,If)};Ae(yc,So=>{R(k)?So(GD):So(jD,!1)})}G(ws),ei(3,ws,()=>Ni,()=>({duration:150})),ae(oa,ws)};Ae($n,oa=>{R(m)&&oa(aa)})}G(yr),Ne(()=>{_o=ft(yr,1,"pulled nav-folder",null,_o,{"is-collapsed":!R(m)}),He(lr,R(a).length)}),ae(or,yr)};Ae(HD,or=>{R(a).length>0&&R(f)&&or(UD)})}G(oe),Ne(()=>{Ot=ft(Ce,1,"staged tree-item nav-folder",null,Ot,{"is-collapsed":!R(h)}),Db=ft(bo,1,"tree-item-icon nav-folder-collapse-indicator collapse-icon",null,Db,{"is-collapsed":!R(h)}),He(OD,R(s).staged.length),Hb=ft(Rf,1,"changes tree-item nav-folder",null,Hb,{"is-collapsed":!R(d)}),Gb=ft(Ub,1,"tree-item-icon nav-folder-collapse-indicator collapse-icon",null,Gb,{"is-collapsed":!R(d)}),He(LD,R(s).changed.length)}),ae(O,oe)};Ae(Z,O=>{R(s)&&R(u)&&R(c)&&O(M)})}G(je),G(H),Ne(()=>{_e(H,"data-type",jt.type),_e(q,"data-icon",R(k)?"list":"folder"),ar=ft(De,1,"clickable-icon nav-action-button",null,ar,{loading:R(i)}),_e(Ie,"rows",R(B))}),_b(Ie,()=>R(o),O=>se(o,O)),ae(t,H),ot()}Et(["click"]);var Pf=class extends kD.ItemView{constructor(e,r){super(e),this.plugin=r,this.hoverPopover=null}getViewType(){return jt.type}getDisplayText(){return jt.name}getIcon(){return jt.icon}onClose(){return this._view&&hs(this._view),super.onClose()}reload(){this._view&&hs(this._view),this._view=ia($b,{target:this.contentEl,props:{plugin:this.plugin,view:this}})}onOpen(){return this.reload(),super.onOpen()}};p();var ym=class{constructor(e,r){this.statusBarEl=e;this.plugin=r;this.statusBarEl.addClass("mod-clickable"),this.statusBarEl.onClickEvent(n=>{this.plugin.switchBranch().catch(i=>r.displayError(i))})}async display(){if(this.plugin.gitReady){let e=await this.plugin.gitManager.branchInfo();e.current!=null?this.statusBarEl.setText(e.current):this.statusBarEl.empty()}else this.statusBarEl.empty()}remove(){this.statusBarEl.remove()}};p();var AD=require("obsidian");var bm=class{constructor(e){this.plugin=e}get editor(){var n;let e=(n=this.plugin.app.workspace.activeEditor)==null?void 0:n.editor,r=e==null?void 0:e.cm;if(!(!e||!Gn.hasHunksData(r.state)))return{editor:r,obEditor:e}}get gitManager(){return this.plugin.gitManager}resetHunk(e){if(!this.editor)return;let{editor:r,obEditor:n}=this.editor,i=Gn.getHunk(r.state,!1,e);if(i){let s,a;i.type==="delete"?(s=i.added.start+1,a=i.added.start+1):(s=i.added.start-0,a=i.added.start-1+i.added.count);let o=r.state.doc.line(s).from,l=i.type==="delete"?r.state.doc.line(a).from:r.state.doc.line(a).to+1,c=i.removed.lines.join(` +`);i.removed.lines.length>0&&!i.removed.no_nl_at_eof&&(c+=` +`),n.replaceRange(c,n.offsetToPos(o),n.offsetToPos(l)),n.setSelection(n.offsetToPos(o))}}async stageHunk(e){if(!await this.plugin.isAllInitialized()||!this.editor)return;let{editor:r}=this.editor,n=Gn.getHunk(r.state,!1,e),i=!1;if(n||(n=Gn.getHunk(r.state,!0,e),i=!0),!n)return;let s=r.state.field(AD.editorInfoField).file.path,a=Nt.createPatch(s,[n],"100644",i).join(` +`)+` +`;await this.gitManager.applyPatch(a),this.plugin.app.workspace.trigger("obsidian-git:refresh")}goToHunk(e){if(!this.editor)return;let{editor:r,obEditor:n}=this.editor,i=Gn.getHunks(r.state,!1),s=n.getCursor().line+1,a=Nt.findNearestHunk(s,i,e,!0);if(a==null)return;let o=i[a];if(o){let l=o.added.start-1;n.setCursor(l,0),n.scrollIntoView({from:{line:l,ch:0},to:{line:l+1,ch:0}},!0)}}};p();p();var wo=require("obsidian");var _m=class{constructor(e){this.plg=e;this.codeMirrorExtensions=[];this.handleWorkspaceLeaf=e=>{if(!this.lineAuthorInfoProvider){console.warn("Git: undefined lineAuthorInfoProvider. Unexpected situation.");return}let r=e==null?void 0:e.view;!(r instanceof wo.MarkdownView)||r.file==null||(r==null?void 0:r.allowNoFile)===!0||this.lineAuthorInfoProvider.trackChanged(r.file).catch(console.error)}}onLoadPlugin(){this.plg.registerEditorExtension(this.codeMirrorExtensions),cF(()=>this.plg.settings.lineAuthor,e=>{this.plg.settings.lineAuthor=e,this.plg.saveSettings()})}conditionallyActivateBySettings(){this.plg.settings.lineAuthor.show&&this.activateFeature()}activateFeature(){try{if(!this.isAvailableOnCurrentPlatform().available)return;yF(this.plg.settings.lineAuthor),this.lineAuthorInfoProvider=new ap(this.plg),this.createEventHandlers(),this.activateCodeMirrorExtensions(),console.log(this.plg.manifest.name+": Enabled line authoring.")}catch(e){console.warn("Git: Error while loading line authoring feature.",e),this.deactivateFeature()}}deactivateFeature(){var e;this.destroyEventHandlers(),this.deactivateCodeMirrorExtensions(),(e=this.lineAuthorInfoProvider)==null||e.destroy(),this.lineAuthorInfoProvider=void 0,console.log(this.plg.manifest.name+": Disabled line authoring.")}isAvailableOnCurrentPlatform(){return{available:this.plg.useSimpleGit&&wo.Platform.isDesktopApp,gitManager:this.plg.gitManager instanceof Se?this.plg.gitManager:void 0}}refreshLineAuthorViews(){this.plg.settings.lineAuthor.show&&(this.deactivateFeature(),this.activateFeature())}activateCodeMirrorExtensions(){this.codeMirrorExtensions.push(RF),this.plg.app.workspace.updateOptions(),this.plg.app.workspace.iterateAllLeaves(this.handleWorkspaceLeaf)}deactivateCodeMirrorExtensions(){for(let e of this.codeMirrorExtensions)this.codeMirrorExtensions.remove(e);this.plg.app.workspace.updateOptions()}createEventHandlers(){this.gutterContextMenuEvent=this.createGutterContextMenuHandler(),this.fileOpenEvent=this.createFileOpenEvent(),this.workspaceLeafChangeEvent=this.createWorkspaceLeafChangeEvent(),this.fileModificationEvent=this.createVaultFileModificationHandler(),this.headChangeEvent=this.createHeadChangeEvent(),this.refreshOnCssChangeEvent=this.createCssRefreshHandler(),this.fileRenameEvent=this.createFileRenameEvent(),pF(),this.plg.registerEvent(this.gutterContextMenuEvent),this.plg.registerEvent(this.refreshOnCssChangeEvent),this.plg.registerEvent(this.fileOpenEvent),this.plg.registerEvent(this.workspaceLeafChangeEvent),this.plg.registerEvent(this.fileModificationEvent),this.plg.registerEvent(this.headChangeEvent),this.plg.registerEvent(this.fileRenameEvent)}destroyEventHandlers(){this.plg.app.workspace.offref(this.gutterContextMenuEvent),this.plg.app.workspace.offref(this.refreshOnCssChangeEvent),this.plg.app.workspace.offref(this.fileOpenEvent),this.plg.app.workspace.offref(this.workspaceLeafChangeEvent),this.plg.app.workspace.offref(this.refreshOnCssChangeEvent),this.plg.app.vault.offref(this.fileModificationEvent),this.plg.app.workspace.offref(this.headChangeEvent),this.plg.app.vault.offref(this.fileRenameEvent)}createFileOpenEvent(){return this.plg.app.workspace.on("file-open",e=>{var r;return void((r=this.lineAuthorInfoProvider)==null?void 0:r.trackChanged(e).catch(console.error))})}createWorkspaceLeafChangeEvent(){return this.plg.app.workspace.on("active-leaf-change",this.handleWorkspaceLeaf)}createFileRenameEvent(){return this.plg.app.vault.on("rename",(e,r)=>{var n;return e instanceof wo.TFile&&((n=this.lineAuthorInfoProvider)==null?void 0:n.trackChanged(e))})}createVaultFileModificationHandler(){return this.plg.app.vault.on("modify",e=>{var r;return e instanceof wo.TFile&&((r=this.lineAuthorInfoProvider)==null?void 0:r.trackChanged(e))})}createHeadChangeEvent(){return this.plg.app.workspace.on("obsidian-git:head-change",()=>{this.refreshLineAuthorViews()})}createCssRefreshHandler(){return this.plg.app.workspace.on("css-change",()=>this.refreshLineAuthorViews())}createGutterContextMenuHandler(){return this.plg.app.workspace.on("editor-menu",vF)}};p();var wc=require("obsidian");p();p();var yo=require("@codemirror/state"),Sm=require("@codemirror/view");var xm=class extends Sm.GutterMarker{constructor(r,n){super();this.type=r;this.staged=n}toDOM(r){let n=document.createElement("div");return n.className=`git-gutter-marker git-${this.type} ${this.staged?"staged":"unstaged"}`,this.type=="changedelete"&&n.setText("~"),n}},Ib=yo.StateField.define({create:()=>yo.RangeSet.empty,update:(t,e)=>{let r=e.state.field($r,!1);if(!r)return yo.RangeSet.empty;let n=e.effects.some(s=>s.is(Vu)),i=e.effects.some(s=>s.is(Hl));if(n||i||(e.docChanged||t.size==0)&&r.isDirty==!1){let s=new Set,a=CD(e,r.hunks,!1,s),o=CD(e,r.stagedHunks,!0,s);return t=yo.RangeSet.of([...a,...o],!0),t}else e.docChanged&&(t=t.map(e.changes));return t}});function CD(t,e,r,n){let i=[];for(let a=0;a0?e[a-1]:void 0,l=a{var e;return(e=t.state.field(Ib,!1))!=null?e:yo.RangeSet.empty},initialSpacer:t=>new xm("delete",!1),domEventHandlers:{click:(t,e,r)=>{var i;return((i=Gn.getHunkAtPos(t.state,e.from,!1))!=null?i:Gn.getHunkAtPos(t.state,e.from,!0))&&(Xs(t,e.from),r.preventDefault()),!1}}});var Em=class{constructor(e){this.plugin=e}async trackChanged(e){return this.trackChangedHelper(e).catch(r=>(console.warn("Git: Error in trackChanged."+r),Promise.reject(r)))}async trackChangedHelper(e){if(e){if(e.path===void 0){console.warn("Git: Attempted to track change of undefined filepath. Unforeseen situation.");return}return this.computeSigns(e.path)}}destroy(){}async computeSigns(e){let n=await this.plugin.editorIntegration.lineAuthoringFeature.isAvailableOnCurrentPlatform().gitManager.show("",e).catch(()=>{});this.notifySignComputationResultToSubscribers(e,{compareText:n,compareTextHead:void 0})}notifySignComputationResultToSubscribers(e,r){es.ifFilepathDefinedTransformSubscribers(e,n=>n.forEach(i=>i.notifyGitCompare(r)))}},PD=[GO,jO,TD,Ib,Tp],RD=[$r,yy];p();var Fb=require("obsidian"),km=class{constructor(e,r){this.statusBarEl=e;this.plugin=r;e.addClass("git-changes-status-bar"),r.settings.hunks.statusBar==="colored"&&e.addClass("git-changes-status-bar-colored"),e.setAttr("aria-label","Git diff of the current editor"),this.statusBarEl.setAttribute("data-tooltip-position","top"),r.app.workspace.on("active-leaf-change",n=>{(!n||n.getRoot()==r.app.workspace.rootSplit&&!(n.view instanceof Fb.MarkdownView))&&this.statusBarEl.empty()})}display(e,r){var o;let n=this.plugin.app.workspace.getActiveViewOfType(Fb.MarkdownView);if(!n||((o=n.file)==null?void 0:o.path)!==(r==null?void 0:r.path))return;let i=0,s=0,a=0;for(let l of e)i+=Math.max(0,l.added.count-l.removed.count),s+=Math.min(l.added.count,l.removed.count),a+=Math.max(0,l.removed.count-l.added.count);this.statusBarEl.empty(),i>0&&this.statusBarEl.createSpan({text:`+${i} `,cls:"git-add"}),s>0&&this.statusBarEl.createSpan({text:`~${s} `,cls:"git-change"}),a>0&&this.statusBarEl.createSpan({text:`-${a}`,cls:"git-delete"})}remove(){this.statusBarEl.remove()}};var Am=class{constructor(e){this.plg=e;this.codeMirrorExtensions=[];this.handleWorkspaceLeaf=e=>{if(!this.signsProvider){console.warn("Git: undefined signsProvider. Unexpected situation.");return}let r=e==null?void 0:e.view;!(r instanceof wc.MarkdownView)||r.file==null||(r==null?void 0:r.allowNoFile)===!0||this.signsProvider.trackChanged(r.file).catch(console.error)}}onLoadPlugin(){this.plg.registerEditorExtension(this.codeMirrorExtensions)}conditionallyActivateBySettings(){(this.plg.settings.hunks.showSigns||this.plg.settings.hunks.statusBar!="disabled"||this.plg.settings.hunks.hunkCommands)&&this.activateFeature()}activateFeature(){try{if(!this.isAvailableOnCurrentPlatform().available)return;if(this.signsProvider=new Em(this.plg),this.createEventHandlers(),this.activateCodeMirrorExtensions(),this.plg.settings.hunks.statusBar!="disabled"){let e=this.plg.addStatusBarItem();this.changeStatusBar=new km(e,this.plg)}}catch(e){console.warn("Git: Error while loading signs feature.",e),this.deactivateFeature()}}deactivateFeature(){var e,r;this.destroyEventHandlers(),this.deactivateCodeMirrorExtensions(),(e=this.signsProvider)==null||e.destroy(),this.signsProvider=void 0,(r=this.changeStatusBar)==null||r.remove(),this.changeStatusBar=void 0}isAvailableOnCurrentPlatform(){return{available:this.plg.useSimpleGit&&wc.Platform.isDesktopApp,gitManager:this.plg.gitManager instanceof Se?this.plg.gitManager:void 0}}refresh(){this.plg.settings.hunks.showSigns&&this.plg.app.workspace.iterateAllLeaves(this.handleWorkspaceLeaf)}activateCodeMirrorExtensions(){this.codeMirrorExtensions.push(RD),this.plg.settings.hunks.showSigns&&this.codeMirrorExtensions.push(...PD),this.plg.app.workspace.updateOptions(),this.plg.app.workspace.iterateAllLeaves(this.handleWorkspaceLeaf)}deactivateCodeMirrorExtensions(){for(let e of this.codeMirrorExtensions)this.codeMirrorExtensions.remove(e);this.plg.app.workspace.updateOptions()}createEventHandlers(){this.workspaceLeafChangeEvent=this.createWorkspaceLeafChangeEvent(),this.fileRenameEvent=this.createFileRenameEvent(),this.pluginRefreshedEvent=this.createPluginRefreshedEvent(),this.intervalRefreshEvent=this.createIntervalRefreshEvent(),this.plg.registerEvent(this.workspaceLeafChangeEvent),this.plg.registerEvent(this.fileRenameEvent),this.plg.registerEvent(this.pluginRefreshedEvent),this.plg.registerInterval(this.intervalRefreshEvent)}destroyEventHandlers(){this.plg.app.workspace.offref(this.workspaceLeafChangeEvent),this.plg.app.vault.offref(this.fileRenameEvent),this.plg.app.workspace.offref(this.pluginRefreshedEvent),this.plg.app.workspace.offref(this.gutterContextMenuEvent),window.clearInterval(this.intervalRefreshEvent)}createWorkspaceLeafChangeEvent(){return this.plg.app.workspace.on("active-leaf-change",this.handleWorkspaceLeaf)}createFileRenameEvent(){return this.plg.app.vault.on("rename",(e,r)=>{var n;return es.ifFilepathDefinedTransformSubscribers(r,i=>i.forEach(s=>{s.changeToNewFilepath(e.path)})),e instanceof wc.TFile&&((n=this.signsProvider)==null?void 0:n.trackChanged(e))})}createPluginRefreshedEvent(){return this.plg.app.workspace.on("obsidian-git:refresh",()=>{this.refresh()})}createIntervalRefreshEvent(){return window.setInterval(()=>{var e,r;(e=this.plg.app.workspace.activeEditor)!=null&&e.file&&((r=this.signsProvider)==null||r.trackChanged(this.plg.app.workspace.activeEditor.file).catch(console.error))},10*1e3)}};p();var $D=require("@codemirror/state"),Cm=require("obsidian");var Ob=class{constructor(e){this.state=e;this.subscribeMe()}notifyLineAuthoring(e,r){if(this.view===void 0){console.warn(`Git: View is not defined for editor cache key. Unforeseen situation. id: ${e}`);return}let n=this.view.state,i=lF(e,r,n);this.view.dispatch(i)}notifyGitCompare(e){if(this.view===void 0){console.warn("Git: View is not defined for editor cache key. Unforeseen situation. id: ");return}if(this.removeIfStale())return;let r=this.view.state,n=r.field($r);if(!n||n.compareText!=e.compareText||n.compareTextHead!=e.compareTextHead){let i=_O(e,r);this.view.dispatch(i)}}updateToNewState(e){return this.state=e,!this.lastSeenPath&&this.filepath&&this.subscribeMe(),this}removeIfStale(){var e;return((e=this.view)==null?void 0:e.state.field(Mb,!1))!=this||this.view.destroyed?(this.unsubscribeMe(this.lastSeenPath),!0):!1}changeToNewFilepath(e){this.unsubscribeMe(this.lastSeenPath),this.subscribeMe(e)}subscribeMe(e){e!=null||(e=this.filepath),e!==void 0&&(es.ifFilepathDefinedTransformSubscribers(e,r=>r.add(this)),this.lastSeenPath=e)}unsubscribeMe(e){es.ifFilepathDefinedTransformSubscribers(e,r=>r.delete(this))}get filepath(){var e,r;return(r=(e=this.state.field(Cm.editorInfoField))==null?void 0:e.file)==null?void 0:r.path}get view(){return this.state.field(Cm.editorEditorField)}},Mb=$D.StateField.define({create:t=>new Ob(t),update:(t,e)=>t.updateToNewState(e.state),compare:(t,e)=>t===e});var Tm=class{constructor(e){this.plg=e;this.lineAuthoringFeature=new _m(this.plg);this.signsFeature=new Am(this.plg)}onUnloadPlugin(){this.lineAuthoringFeature.deactivateFeature(),this.signsFeature.deactivateFeature()}onLoadPlugin(){this.plg.registerEditorExtension(Mb),this.lineAuthoringFeature.onLoadPlugin(),this.signsFeature.onLoadPlugin()}onReady(){this.lineAuthoringFeature.conditionallyActivateBySettings(),this.signsFeature.conditionallyActivateBySettings()}activateLineAuthoring(){this.lineAuthoringFeature.activateFeature()}deactiveLineAuthoring(){this.lineAuthoringFeature.deactivateFeature()}refreshSignsSettings(){let e=this.plg.settings.hunks;e.showSigns||e.statusBar!="disabled"||e.hunkCommands?(this.signsFeature.deactivateFeature(),this.signsFeature.activateFeature()):this.signsFeature.deactivateFeature()}};var Pm=class extends be.Plugin{constructor(){super(...arguments);this.automaticsManager=new Gu(this);this.tools=new ef(this);this.localStorage=new Pp(this);this.state={gitAction:0,offlineMode:!1};this.gitReady=!1;this.promiseQueue=new Gd(this);this.intervalsToClear=[];this.editorIntegration=new Tm(this);this.hunkActions=new bm(this)}setPluginState(r){var n;this.state=Object.assign(this.state,r),(n=this.statusBar)==null||n.display()}async updateCachedStatus(){var r,n;return this.app.workspace.trigger("obsidian-git:loading-status"),this.cachedStatus=await this.gitManager.status(),this.cachedStatus.conflicted.length>0?(this.localStorage.setConflict(!0),await((r=this.branchBar)==null?void 0:r.display())):(this.localStorage.setConflict(!1),await((n=this.branchBar)==null?void 0:n.display())),this.app.workspace.trigger("obsidian-git:status-changed",this.cachedStatus),this.cachedStatus}async refresh(){if(!this.gitReady)return;let r=this.app.workspace.getLeavesOfType(jt.type),n=this.app.workspace.getLeavesOfType(gn.type);(this.settings.changedFilesInStatusBar||r.some(i=>{var s;return!((s=i.isDeferred)!=null&&s)})||n.some(i=>{var s;return!((s=i.isDeferred)!=null&&s)}))&&await this.updateCachedStatus().catch(i=>this.displayError(i)),this.app.workspace.trigger("obsidian-git:refreshed")}refreshUpdatedHead(){}async onload(){console.log("loading "+this.manifest.name+" plugin: v"+this.manifest.version),Ln.plugin=this,this.localStorage.migrate(),await this.loadSettings(),await this.migrateSettings(),this.settingsTab=new op(this.app,this),this.addSettingTab(this.settingsTab),this.localStorage.getPluginDisabled()||(this.registerStuff(),this.app.workspace.onLayoutReady(()=>this.init({fromReload:!1}).catch(r=>this.displayError(r))))}onExternalSettingsChange(){this.reloadSettings().catch(r=>this.displayError(r))}async reloadSettings(){let r=JSON.stringify(this.settings);await this.loadSettings();let n=JSON.stringify(this.settings);r!==n&&(this.log("Reloading settings"),this.unloadPlugin(),await this.init({fromReload:!0}),this.app.workspace.getLeavesOfType(jt.type).forEach(i=>{var s;if(!((s=i.isDeferred)!=null&&s))return i.view.reload()}),this.app.workspace.getLeavesOfType(gn.type).forEach(i=>{var s;if(!((s=i.isDeferred)!=null&&s))return i.view.reload()}))}registerStuff(){this.registerEvent(this.app.workspace.on("obsidian-git:refresh",()=>{this.refresh().catch(r=>this.displayError(r))})),this.registerEvent(this.app.workspace.on("obsidian-git:head-change",()=>{this.refreshUpdatedHead()})),this.registerEvent(this.app.workspace.on("file-menu",(r,n,i)=>{this.handleFileMenu(r,n,i,"file-manu")})),this.registerEvent(this.app.workspace.on("obsidian-git:menu",(r,n,i)=>{this.handleFileMenu(r,n,i,"obsidian-git:menu")})),this.registerEvent(this.app.workspace.on("active-leaf-change",r=>{this.onActiveLeafChange(r)})),this.registerEvent(this.app.vault.on("modify",()=>{var r;this.debRefresh(),(r=this.autoCommitDebouncer)==null||r.call(this)})),this.registerEvent(this.app.vault.on("delete",()=>{var r;this.debRefresh(),(r=this.autoCommitDebouncer)==null||r.call(this)})),this.registerEvent(this.app.vault.on("create",()=>{var r;this.debRefresh(),(r=this.autoCommitDebouncer)==null||r.call(this)})),this.registerEvent(this.app.vault.on("rename",()=>{var r;this.debRefresh(),(r=this.autoCommitDebouncer)==null||r.call(this)})),this.registerView(jt.type,r=>new Pf(r,this)),this.registerView(gn.type,r=>new Ef(r,this)),this.registerView(Bs.type,r=>new Wa(r,this)),this.registerView(Ns.type,r=>new za(r,this)),this.addRibbonIcon("git-pull-request","Open Git source control",async()=>{var i;let r=this.app.workspace.getLeavesOfType(jt.type),n;r.length===0?(n=(i=this.app.workspace.getRightLeaf(!1))!=null?i:this.app.workspace.getLeaf(),await n.setViewState({type:jt.type})):n=r.first(),await this.app.workspace.revealLeaf(n)}),this.registerHoverLinkSource(jt.type,{display:"Git View",defaultMod:!0}),this.editorIntegration.onLoadPlugin(),this.setRefreshDebouncer(),qO(this)}setRefreshDebouncer(){var r;(r=this.debRefresh)==null||r.cancel(),this.debRefresh=(0,be.debounce)(()=>{this.settings.refreshSourceControl&&this.refresh().catch(console.error)},this.settings.refreshSourceControlTimer,!0)}async addFileToGitignore(r,n){let i=this.gitManager.getRelativeRepoPath(r,!0),s=eR({isFolder:n,gitRelativePath:i});await this.app.vault.adapter.append(this.gitManager.getRelativeVaultPath(".gitignore"),` +`+s),this.app.workspace.trigger("obsidian-git:refresh")}handleFileMenu(r,n,i,s){if(!this.gitReady||!this.settings.showFileMenu||!n)return;let a;if(typeof n=="string"?a=n:a=n.path,i=="file-explorer-context-menu"&&(r.addItem(o=>{o.setTitle("Git: Stage").setIcon("plus-circle").setSection("action").onClick(l=>{this.promiseQueue.addTask(async()=>{n instanceof be.TFile?await this.stageFile(n):(await this.gitManager.stageAll({dir:this.gitManager.getRelativeRepoPath(a,!0)}),this.app.workspace.trigger("obsidian-git:refresh"))})})}),r.addItem(o=>{o.setTitle("Git: Unstage").setIcon("minus-circle").setSection("action").onClick(l=>{this.promiseQueue.addTask(async()=>{n instanceof be.TFile?await this.unstageFile(n):(await this.gitManager.unstageAll({dir:this.gitManager.getRelativeRepoPath(a,!0)}),this.app.workspace.trigger("obsidian-git:refresh"))})})}),r.addItem(o=>{o.setTitle("Git: Add to .gitignore").setIcon("file-x").setSection("action").onClick(l=>{this.addFileToGitignore(a,n instanceof be.TFolder).catch(c=>this.displayError(c))})})),i=="git-source-control"){r.addItem(l=>{l.setTitle("Git: Add to .gitignore").setIcon("file-x").setSection("action").onClick(c=>{this.addFileToGitignore(a,n instanceof be.TFolder).catch(u=>this.displayError(u))})});let o=this.app.vault.adapter;s==="obsidian-git:menu"&&o instanceof be.FileSystemAdapter&&(r.addItem(l=>{l.setTitle("Open in default app").setIcon("arrow-up-right").setSection("action").onClick(c=>{this.app.openWithDefaultApp(a)})}),r.addItem(l=>{l.setTitle("Show in system explorer").setIcon("arrow-up-right").setSection("action").onClick(c=>{window.electron.shell.showItemInFolder(FD.join(o.getBasePath(),a))})}))}}async migrateSettings(){this.settings.mergeOnPull!=null&&(this.settings.syncMethod=this.settings.mergeOnPull?"merge":"rebase",this.settings.mergeOnPull=void 0,await this.saveSettings()),this.settings.autoCommitMessage===void 0&&(this.settings.autoCommitMessage=this.settings.commitMessage,await this.saveSettings()),this.settings.gitPath!=null&&(this.localStorage.setGitPath(this.settings.gitPath),this.settings.gitPath=void 0,await this.saveSettings()),this.settings.username!=null&&(this.localStorage.setPassword(this.settings.username),this.settings.username=void 0,await this.saveSettings())}unloadPlugin(){var r,n;this.gitReady=!1,this.editorIntegration.onUnloadPlugin(),this.automaticsManager.unload(),(r=this.branchBar)==null||r.remove(),(n=this.statusBar)==null||n.remove(),this.statusBar=void 0,this.branchBar=void 0,this.gitManager.unload(),this.promiseQueue.clear();for(let i of this.intervalsToClear)window.clearInterval(i);this.intervalsToClear=[],this.debRefresh.cancel()}onunload(){this.unloadPlugin(),console.log("unloading "+this.manifest.name+" plugin")}async loadSettings(){let r=await this.loadData();r==null&&(r={showedMobileNotice:!0}),this.settings=sC(et,r)}async saveSettings(){var r;(r=this.settingsTab)==null||r.beforeSaveSettings(),await this.saveData(this.settings)}get useSimpleGit(){return be.Platform.isDesktopApp}async init({fromReload:r=!1}){var n;if(this.settings.showStatusBar&&!this.statusBar){let i=this.addStatusBarItem();this.statusBar=new lp(i,this),this.intervalsToClear.push(window.setInterval(()=>{var s;return(s=this.statusBar)==null?void 0:s.display()},1e3))}try{this.useSimpleGit?(this.gitManager=new Se(this),await this.gitManager.setGitInstance()):this.gitManager=new Hn(this);let i=await this.gitManager.checkRequirements(),s=this.localStorage.getPausedAutomatics();switch(i){case"missing-git":this.displayError(`Cannot run git command. Trying to run: '${this.localStorage.getGitPath()||"git"}' .`);break;case"missing-repo":new be.Notice("Can't find a valid git repository. Please create one via the given command or clone an existing repo.",1e4);break;case"valid":if(this.gitReady=!0,this.setPluginState({gitAction:0}),be.Platform.isDesktop&&this.settings.showBranchStatusBar&&!this.branchBar){let a=this.addStatusBarItem();this.branchBar=new ym(a,this),this.intervalsToClear.push(window.setInterval(()=>{var o;return void((o=this.branchBar)==null?void 0:o.display().catch(console.error))},6e4))}await((n=this.branchBar)==null?void 0:n.display()),this.editorIntegration.onReady(),this.app.workspace.trigger("obsidian-git:refresh"),this.app.workspace.trigger("obsidian-git:head-change"),!r&&this.settings.autoPullOnBoot&&!s&&this.promiseQueue.addTask(()=>this.pullChangesFromRemote()),s||await this.automaticsManager.init(),s&&new be.Notice("Automatic routines are currently paused.");break;default:this.log("Something weird happened. The 'checkRequirements' result is "+i)}}catch(i){this.displayError(i),console.error(i)}}async createNewRepo(){try{await this.gitManager.init(),new be.Notice("Initialized new repo"),await this.init({fromReload:!0})}catch(r){this.displayError(r)}}async cloneNewRepo(){let n=await new Ze(this,{placeholder:"Enter remote URL"}).openAndGetResult();if(n){let i="Vault Root",s=await new Ze(this,{options:this.gitManager instanceof Hn?[i]:[],placeholder:"Enter directory for clone. It needs to be empty or not existent.",allowEmpty:this.gitManager instanceof Hn}).openAndGetResult();if(s==null)return;if(s===i&&(s="."),s=(0,be.normalizePath)(s),s==="/"&&(s="."),s==="."){let f=await new Ze(this,{options:["NO","YES"],placeholder:`Does your remote repo contain a ${this.app.vault.configDir} directory at the root?`,onlySelection:!0}).openAndGetResult();if(f===void 0){new be.Notice("Aborted clone");return}else if(f==="YES"){let d="DELETE ALL YOUR LOCAL CONFIG AND PLUGINS";if(await new Ze(this,{options:["Abort clone",d],placeholder:`To avoid conflicts, the local ${this.app.vault.configDir} directory needs to be deleted.`,onlySelection:!0}).openAndGetResult()===d)await this.app.vault.adapter.rmdir(this.app.vault.configDir,!0);else{new be.Notice("Aborted clone");return}}}let a=await new Ze(this,{placeholder:"Specify depth of clone. Leave empty for full clone.",allowEmpty:!0}).openAndGetResult(),o;if(a===void 0){new be.Notice("Aborted clone");return}if(a!==""&&(o=parseInt(a),isNaN(o))){new be.Notice("Invalid depth. Aborting clone.");return}new be.Notice(`Cloning new repo into "${s}"`);let l=this.settings.basePath,c=s&&s!==".";c&&(this.settings.basePath=s);try{await this.gitManager.clone(Kw(n),s,o),new be.Notice("Cloned new repo."),new be.Notice("Please restart Obsidian"),c&&await this.saveSettings()}catch(u){this.displayError(u),this.settings.basePath=l,await this.saveSettings()}}}async isAllInitialized(){return this.gitReady||await this.init({fromReload:!0}),this.gitReady}async pullChangesFromRemote(){if(!await this.isAllInitialized())return;let r=await this.pull();if(r!==!1){if(r||this.displayMessage("Pull: Everything is up-to-date"),this.gitManager instanceof Se){let n=await this.updateCachedStatus();n.conflicted.length>0&&(this.displayError(`You have conflicts in ${n.conflicted.length} ${n.conflicted.length==1?"file":"files"}`),await this.handleConflict(n.conflicted))}this.app.workspace.trigger("obsidian-git:refresh"),this.setPluginState({gitAction:0})}}async commitAndSync({fromAutoBackup:r,requestCustomMessage:n=!1,commitMessage:i,onlyStaged:s=!1}){!await this.isAllInitialized()||(this.settings.syncMethod=="reset"&&this.settings.pullBeforePush&&await this.pull(),!await this.commit({fromAuto:r,requestCustomMessage:n,commitMessage:i,onlyStaged:s}))||(this.settings.syncMethod!="reset"&&this.settings.pullBeforePush&&await this.pull(),this.settings.disablePush||(await this.remotesAreSet()&&await this.gitManager.canPush()?await this.push():this.displayMessage("No commits to push")),this.setPluginState({gitAction:0}))}async commit({fromAuto:r,requestCustomMessage:n=!1,onlyStaged:i=!1,commitMessage:s,amend:a=!1}){if(!await this.isAllInitialized())return!1;try{let o=this.localStorage.getConflict(),l,c=[],u=[];if(this.gitManager instanceof Se){if(await this.mayDeleteConflictFile(),l=await this.updateCachedStatus(),l.conflicted.length==0&&(o=!1),r&&l.conflicted.length>0)return this.displayError(`Did not commit, because you have conflicts in ${l.conflicted.length} ${l.conflicted.length==1?"file":"files"}. Please resolve them and commit per command.`),await this.handleConflict(l.conflicted),!1;c=l.staged,u=l.changed}else{if(r&&o)return this.displayError("Did not commit, because you have conflicts. Please resolve them and commit per command."),!1;{o&&await this.mayDeleteConflictFile();let f=this.gitManager;i?c=await f.getStagedFiles():u=(await f.getUnstagedFiles()).map(({path:h,type:m})=>({vaultPath:this.gitManager.getRelativeVaultPath(h),path:h,type:m}))}}if(await this.tools.hasTooBigFiles(i?c:[...c,...u]))return this.setPluginState({gitAction:0}),!1;if(u.length+c.length!==0||o){let f=s!=null?s:s=r?this.settings.autoCommitMessage:this.settings.commitMessage;if(r&&this.settings.customMessageOnAutoBackup||n){!this.settings.disablePopups&&r&&new be.Notice("Auto backup: Please enter a custom commit message. Leave empty to abort");let m=await new cp(this).openAndGetResult();if(m!=null&&m!=""&&m!="...")f=m;else return this.setPluginState({gitAction:0}),!1}else if(this.gitManager instanceof Se&&this.settings.commitMessageScript){let m=this.settings.commitMessageScript,g=this.localStorage.getHostname()||"",v=m.replace("{{hostname}}",g);v=v.replace("{{date}}",(0,be.moment)().format(this.settings.commitDateFormat));let w="sh";if(be.Platform.isWin){w=process.env.PROGRAMFILES+"\\Git\\bin\\sh.exe";let k=!1;try{await Rm.access(w,Rm.constants.X_OK),k=!0}catch(x){k=!1}if(!k)return this.displayError(`Cannot find sh.exe at ${w}. Please make sure Git is properly installed.`),!1}let b=await $u(w,["-c",v],{cwd:this.gitManager.absoluteRepoPath});b.code!=0?this.displayError(b.stderr):b.stdout.trim().length==0?this.displayMessage("Stdout from commit message script is empty. Using default message."):f=b.stdout}if(!f||f.trim()==="")return new be.Notice("Commit aborted: No commit message provided"),this.setPluginState({gitAction:0}),!1;let d;i?d=await this.gitManager.commit({message:f,amend:a}):d=await this.gitManager.commitAll({message:f,status:l,unstagedFiles:u,amend:a}),this.gitManager instanceof Se&&await this.updateCachedStatus();let h=!1;d===void 0&&(h=!0,d=u.length+c.length||0),this.displayMessage(`Committed${h?" approx.":""} ${d} ${d==1?"file":"files"}`)}else this.displayMessage("No changes to commit");return this.app.workspace.trigger("obsidian-git:refresh"),!0}catch(o){return this.displayError(o),!1}}async push(){if(!await this.isAllInitialized()||!await this.remotesAreSet())return!1;let r=this.localStorage.getConflict();try{this.gitManager instanceof Se&&await this.mayDeleteConflictFile();let n;if(this.gitManager instanceof Se&&(n=await this.updateCachedStatus()).conflicted.length>0)return this.displayError(`Cannot push. You have conflicts in ${n.conflicted.length} ${n.conflicted.length==1?"file":"files"}`),await this.handleConflict(n.conflicted),!1;if(this.gitManager instanceof Hn&&r)return this.displayError("Cannot push. You have conflicts"),!1;this.log("Pushing....");let i=await this.gitManager.push();return i!==void 0&&(i===null?this.displayMessage("Pushed to remote"):i>0?this.displayMessage(`Pushed ${i} ${i==1?"file":"files"} to remote`):this.displayMessage("No commits to push")),this.setPluginState({offlineMode:!1}),this.app.workspace.trigger("obsidian-git:refresh"),!0}catch(n){return n instanceof ul?this.handleNoNetworkError(n):this.displayError(n),!1}}async pull(){if(!await this.remotesAreSet())return!1;try{this.log("Pulling....");let r=await this.gitManager.pull()||[];return this.setPluginState({offlineMode:!1}),r.length>0&&(this.displayMessage(`Pulled ${r.length} ${r.length==1?"file":"files"} from remote`),this.lastPulledFiles=r),r.length}catch(r){return this.displayError(r),!1}}async fetch(){if(await this.remotesAreSet())try{await this.gitManager.fetch(),this.displayMessage("Fetched from remote"),this.setPluginState({offlineMode:!1}),this.app.workspace.trigger("obsidian-git:refresh")}catch(r){this.displayError(r)}}async mayDeleteConflictFile(){let r=this.app.vault.getAbstractFileByPath(ol);r&&(this.app.workspace.iterateAllLeaves(n=>{var i;n.view instanceof be.MarkdownView&&((i=n.view.file)==null?void 0:i.path)==r.path&&n.detach()}),await this.app.vault.delete(r))}async stageFile(r){return await this.isAllInitialized()?(await this.gitManager.stage(r.path,!0),this.app.workspace.trigger("obsidian-git:refresh"),this.setPluginState({gitAction:0}),!0):!1}async unstageFile(r){return await this.isAllInitialized()?(await this.gitManager.unstage(r.path,!0),this.app.workspace.trigger("obsidian-git:refresh"),this.setPluginState({gitAction:0}),!0):!1}async switchBranch(){var i;if(!await this.isAllInitialized())return;let r=await this.gitManager.branchInfo(),n=await new vm(this,r.branches).openAndGetReslt();if(n!=null)return await this.gitManager.checkout(n),this.displayMessage(`Switched to ${n}`),this.app.workspace.trigger("obsidian-git:refresh"),await((i=this.branchBar)==null?void 0:i.display()),n}async switchRemoteBranch(){var s;if(!await this.isAllInitialized())return;let r=await this.selectRemoteBranch()||"",[n,i]=Qi(r);if(i!=null&&n!=null)return await this.gitManager.checkout(i,n),this.displayMessage(`Switched to ${r}`),await((s=this.branchBar)==null?void 0:s.display()),r}async createBranch(){var n;if(!await this.isAllInitialized())return;let r=await new Ze(this,{placeholder:"Create new branch"}).openAndGetResult();if(r!=null)return await this.gitManager.createBranch(r),this.displayMessage(`Created new branch ${r}`),await((n=this.branchBar)==null?void 0:n.display()),r}async deleteBranch(){var i;if(!await this.isAllInitialized())return;let r=await this.gitManager.branchInfo();r.current&&r.branches.remove(r.current);let n=await new Ze(this,{options:r.branches,placeholder:"Delete branch",onlySelection:!0}).openAndGetResult();if(n!=null){let s=!1;if(!await this.gitManager.branchIsMerged(n)){let o=await new Ze(this,{options:["YES","NO"],placeholder:"This branch isn't merged into HEAD. Force delete?",onlySelection:!0}).openAndGetResult();if(o!=="YES")return;s=o==="YES"}return await this.gitManager.deleteBranch(n,s),this.displayMessage(`Deleted branch ${n}`),await((i=this.branchBar)==null?void 0:i.display()),n}}async remotesAreSet(){return this.settings.updateSubmodules||this.gitManager instanceof Se&&await this.gitManager.getConfig("push.autoSetupRemote","all")=="true"||(await this.gitManager.branchInfo()).tracking?!0:(new be.Notice("No upstream branch is set. Please select one."),await this.setUpstreamBranch())}async setUpstreamBranch(){let r=await this.selectRemoteBranch();return r==null?(this.displayError("Aborted. No upstream-branch is set!",1e4),this.setPluginState({gitAction:0}),!1):(await this.gitManager.updateUpstreamBranch(r),this.displayMessage(`Set upstream branch to ${r}`),this.setPluginState({gitAction:0}),!0)}async discardAll(r){if(!await this.isAllInitialized())return!1;let n=await this.gitManager.status({path:r}),i=0,s=0;for(let o of n.changed)o.workingDir=="U"?i++:s++;if(i+s==0)return!1;let a=await new vc({app:this.app,filesToDeleteCount:i,filesToDiscardCount:s,path:r!=null?r:""}).openAndGetResult();switch(a){case!1:return a;case"discard":await this.gitManager.discardAll({dir:r,status:this.cachedStatus});break;case"delete":{await this.gitManager.discardAll({dir:r,status:this.cachedStatus});let o=await this.gitManager.getUntrackedPaths({path:r,status:this.cachedStatus});for(let l of o){let c=this.gitManager.getRelativeVaultPath(l),u=this.app.vault.getAbstractFileByPath(c);u?await this.app.fileManager.trashFile(u):l.endsWith("/")?await this.app.vault.adapter.rmdir(c,!0):await this.app.vault.adapter.remove(c)}break}default:Eh(a)}return this.app.workspace.trigger("obsidian-git:refresh"),a}async handleConflict(r){this.localStorage.setConflict(!0);let n;r!==void 0&&(n=["# Conflicts","Please resolve them and commit them using the commands `Git: Commit all changes` followed by `Git: Push`","(This file will automatically be deleted before commit)","[[#Additional Instructions]] available below file list","",...r.map(i=>{let s=this.app.vault.getAbstractFileByPath(i);return s instanceof be.TFile?`- [[${this.app.metadataCache.fileToLinktext(s,"/")}]]`:`- Not a file: ${i}`}),` +# Additional Instructions +I strongly recommend to use "Source mode" for viewing the conflicted files. For simple conflicts, in each file listed above replace every occurrence of the following text blocks with the desired text. + +\`\`\`diff +<<<<<<< HEAD + File changes in local repository +======= + File changes in remote repository +>>>>>>> origin/main +\`\`\``]),await this.tools.writeAndOpenFile(n==null?void 0:n.join(` +`))}async editRemotes(){if(!await this.isAllInitialized())return;let r=await this.gitManager.getRemotes(),i=await new Ze(this,{options:r,placeholder:"Select or create a new remote by typing its name and selecting it"}).openAndGetResult();if(i){let s=await this.gitManager.getRemoteUrl(i),o=await new Ze(this,{initialValue:s,placeholder:"Enter remote URL"}).openAndGetResult();if(o)return await this.gitManager.setRemote(i,Kw(o)),i}}async selectRemoteBranch(){let r=await this.gitManager.getRemotes(),n;r.length===0&&(n=await this.editRemotes(),n==null&&(r=await this.gitManager.getRemotes()));let i=new Ze(this,{options:r,placeholder:"Select or create a new remote by typing its name and selecting it"}),s=n!=null?n:await i.openAndGetResult();if(s){this.displayMessage("Fetching remote branches"),await this.gitManager.fetch(s);let a=await this.gitManager.getRemoteBranches(s),l=await new Ze(this,{options:a,placeholder:"Select or create a new remote branch by typing its name and selecting it"}).openAndGetResult();return l==null?void 0:l.startsWith(s+"/")?l:`${s}/${l}`}}async removeRemote(){if(!await this.isAllInitialized())return;let r=await this.gitManager.getRemotes(),i=await new Ze(this,{options:r,placeholder:"Select a remote"}).openAndGetResult();i&&await this.gitManager.removeRemote(i)}onActiveLeafChange(r){var a,o;let n=r==null?void 0:r.view;if(!(n!=null&&n.getState().file)&&!(n instanceof Wa||n instanceof za))return;let i=this.app.workspace.getLeavesOfType(jt.type).first(),s=this.app.workspace.getLeavesOfType(gn.type).first();if((a=i==null?void 0:i.view.containerEl.querySelector("div.tree-item-self.is-active"))==null||a.removeClass("is-active"),(o=s==null?void 0:s.view.containerEl.querySelector("div.tree-item-self.is-active"))==null||o.removeClass("is-active"),(r==null?void 0:r.view)instanceof Wa||(r==null?void 0:r.view)instanceof za){let c=r.view.state.bFile.replace(/["\\]/g,"\\$&");this.lastDiffViewState=r.view.getState();let u;i&&r.view.state.aRef=="HEAD"?u=i.view.containerEl.querySelector(`div.staged div.tree-item-self[data-path="${c}"]`):i&&r.view.state.aRef==""?u=i.view.containerEl.querySelector(`div.changes div.tree-item-self[data-path="${c}"]`):s&&(u=s.view.containerEl.querySelector(`div.tree-item-self[data-path='${c}']`)),u==null||u.addClass("is-active")}else this.lastDiffViewState=void 0}handleNoNetworkError(r){this.state.offlineMode?this.log("Encountered network error, but already in offline mode"):this.displayError("Git: Going into offline mode. Future network errors will no longer be displayed.",2e3),this.setPluginState({gitAction:0,offlineMode:!0})}displayMessage(r,n=4*1e3){var i;(i=this.statusBar)==null||i.displayMessage(r.toLowerCase(),n),this.settings.disablePopups||(!this.settings.disablePopupsForNoChanges||!r.startsWith("No changes"))&&new be.Notice(r,5*1e3),this.log(r)}displayError(r,n=10*1e3){var s;if(r instanceof ID.Errors.UserCanceledError){new be.Notice("Aborted");return}let i;r instanceof Error?i=r:i=new Error(String(r)),this.setPluginState({gitAction:0}),this.settings.showErrorNotices&&new be.Notice(i.message,n),console.error(`${this.manifest.id}:`,i.stack),(s=this.statusBar)==null||s.displayMessage(i.message.toLowerCase(),n)}log(...r){console.log(`${this.manifest.id}:`,...r)}}; +/*! Bundled license information: + +ieee754/index.js: + (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) + +buffer/index.js: + (*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + *) + +safe-buffer/index.js: + (*! safe-buffer. MIT License. Feross Aboukhadijeh *) + +crc-32/crc32.js: + (*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com *) + +isomorphic-git/index.cjs: + (*! + * This code for `path.join` is directly copied from @zenfs/core/path for bundle size improvements. + * SPDX-License-Identifier: LGPL-3.0-or-later + * Copyright (c) James Prevett and other ZenFS contributors. + *) + +js-sha256/src/sha256.js: + (** + * [js-sha256]{@link https://github.com/emn178/js-sha256} + * + * @version 0.9.0 + * @author Chen, Yi-Cyuan [emn178@gmail.com] + * @copyright Chen, Yi-Cyuan 2014-2017 + * @license MIT + *) +*/ + +/* nosourcemap */ \ No newline at end of file diff --git a/Naturaale Zwanzig/.obsidian/plugins/obsidian-git/manifest.json b/Naturaale Zwanzig/.obsidian/plugins/obsidian-git/manifest.json new file mode 100644 index 0000000..ac443e0 --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/plugins/obsidian-git/manifest.json @@ -0,0 +1,10 @@ +{ + "author": "Vinzent", + "authorUrl": "https://github.com/Vinzent03", + "id": "obsidian-git", + "name": "Git", + "description": "Integrate Git version control with automatic backup and other advanced features.", + "isDesktopOnly": false, + "fundingUrl": "https://ko-fi.com/vinzent", + "version": "2.38.2" +} diff --git a/Naturaale Zwanzig/.obsidian/plugins/obsidian-git/styles.css b/Naturaale Zwanzig/.obsidian/plugins/obsidian-git/styles.css new file mode 100644 index 0000000..305b2f4 --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/plugins/obsidian-git/styles.css @@ -0,0 +1,710 @@ +@keyframes loading { + 0% { + transform: rotate(0deg); + } + + 100% { + transform: rotate(360deg); + } +} + +.git-signs-gutter { + .cm-gutterElement { + /* Needed to align the sign properly for different line heigts. Such as + * when having a heading or list item. + */ + padding-top: 0 !important; + } +} + +.workspace-leaf-content[data-type="git-view"] .button-border { + border: 2px solid var(--interactive-accent); + border-radius: var(--radius-s); +} + +.workspace-leaf-content[data-type="git-view"] .view-content { + padding-left: 0; + padding-top: 0; + padding-right: 0; +} + +.workspace-leaf-content[data-type="git-history-view"] .view-content { + padding-left: 0; + padding-top: 0; + padding-right: 0; +} + +.loading { + overflow: hidden; +} + +.loading > svg { + animation: 2s linear infinite loading; + transform-origin: 50% 50%; + display: inline-block; +} + +.obsidian-git-center { + margin: auto; + text-align: center; + width: 50%; +} + +.obsidian-git-textarea { + display: block; + margin-left: auto; + margin-right: auto; +} + +.obsidian-git-disabled { + opacity: 0.5; +} + +.obsidian-git-center-button { + display: block; + margin: 20px auto; +} + +.tooltip.mod-left { + overflow-wrap: break-word; +} + +.tooltip.mod-right { + overflow-wrap: break-word; +} + +/* Limits the scrollbar to the view body */ +.git-view { + display: flex; + flex-direction: column; + position: relative; + height: 100%; +} + +/* Re-enable wrapping of nav buttns to prevent overflow on smaller screens #*/ +.workspace-drawer .git-view .nav-buttons-container { + flex-wrap: wrap; +} + +.git-tools { + display: flex; + margin-left: auto; +} +.git-tools .type { + padding-left: var(--size-2-1); + display: flex; + align-items: center; + justify-content: center; + width: 11px; +} + +.git-tools .type[data-type="M"] { + color: orange; +} +.git-tools .type[data-type="D"] { + color: red; +} +.git-tools .buttons { + display: flex; +} +.git-tools .buttons > * { + padding: 0 0; + height: auto; +} + +.workspace-leaf-content[data-type="git-view"] .tree-item-self, +.workspace-leaf-content[data-type="git-history-view"] .tree-item-self { + align-items: center; +} + +.workspace-leaf-content[data-type="git-view"] + .tree-item-self:hover + .clickable-icon, +.workspace-leaf-content[data-type="git-history-view"] + .tree-item-self:hover + .clickable-icon { + color: var(--icon-color-hover); +} + +/* Highlight an item as active if it's diff is currently opened */ +.is-active .git-tools .buttons > * { + color: var(--nav-item-color-active); +} + +.git-author { + color: var(--text-accent); +} + +.git-date { + color: var(--text-accent); +} + +.git-ref { + color: var(--text-accent); +} + +/* ====== diff2html ====== +The following styles are adapted from the obsidian-version-history plugin by +@kometenstaub https://github.com/kometenstaub/obsidian-version-history-diff/blob/main/src/styles.scss +which itself is adapted from the diff2html library with the following original license: + + https://github.com/rtfpessoa/diff2html/blob/master/LICENSE.md + + Copyright 2014-2016 Rodrigo Fernandes https://rtfpessoa.github.io/ + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated + documentation files (the "Software"), to deal in the Software without restriction, including without limitation the + rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit + persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the + Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR + COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +*/ + +.theme-dark, +.theme-light { + --git-delete-bg: #ff475040; + --git-delete-hl: #96050a75; + --git-insert-bg: #68d36840; + --git-insert-hl: #23c02350; + --git-change-bg: #ffd55840; + --git-selected: #3572b0; + + --git-delete: #c33; + --git-insert: #399839; + --git-change: #d0b44c; + --git-move: #3572b0; +} + +.git-diff { + .d2h-d-none { + display: none; + } + .d2h-wrapper { + text-align: left; + border-radius: 0.25em; + overflow: auto; + } + .d2h-file-header.d2h-file-header { + background-color: var(--background-secondary); + border-bottom: 1px solid var(--background-modifier-border); + font-family: + Source Sans Pro, + Helvetica Neue, + Helvetica, + Arial, + sans-serif; + height: 35px; + padding: 5px 10px; + } + .d2h-file-header, + .d2h-file-stats { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + } + .d2h-file-header { + display: none; + } + .d2h-file-stats { + font-size: 14px; + margin-left: auto; + } + .d2h-lines-added { + border: 1px solid var(--color-green); + border-radius: 5px 0 0 5px; + color: var(--color-green); + padding: 2px; + text-align: right; + vertical-align: middle; + } + .d2h-lines-deleted { + border: 1px solid var(--color-red); + border-radius: 0 5px 5px 0; + color: var(--color-red); + margin-left: 1px; + padding: 2px; + text-align: left; + vertical-align: middle; + } + .d2h-file-name-wrapper { + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; + display: -webkit-box; + display: -ms-flexbox; + display: flex; + font-size: 15px; + width: 100%; + } + .d2h-file-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--text-normal); + font-size: var(--h5-size); + } + .d2h-file-wrapper { + border: 1px solid var(--background-secondary-alt); + border-radius: 3px; + margin-bottom: 1em; + max-height: 100%; + } + .d2h-file-collapse { + -webkit-box-pack: end; + -ms-flex-pack: end; + -webkit-box-align: center; + -ms-flex-align: center; + align-items: center; + border: 1px solid var(--background-secondary-alt); + border-radius: 3px; + cursor: pointer; + display: none; + font-size: 12px; + justify-content: flex-end; + padding: 4px 8px; + } + .d2h-file-collapse.d2h-selected { + background-color: var(--git-selected); + } + .d2h-file-collapse-input { + margin: 0 4px 0 0; + } + .d2h-diff-table { + border-collapse: collapse; + font-family: var(--font-monospace); + font-size: var(--code-size); + width: 100%; + } + .d2h-files-diff { + width: 100%; + } + .d2h-file-diff { + /* + overflow-y: scroll; + */ + border-radius: 5px; + font-size: var(--font-text-size); + line-height: var(--line-height-normal); + } + .d2h-file-side-diff { + display: inline-block; + margin-bottom: -8px; + margin-right: -4px; + overflow-x: scroll; + overflow-y: hidden; + width: 50%; + } + .d2h-code-line { + padding-left: 6em; + padding-right: 1.5em; + } + .d2h-code-line, + .d2h-code-side-line { + display: inline-block; + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + white-space: nowrap; + width: 100%; + } + .d2h-code-side-line { + /* needed to be changed */ + padding-left: 0.5em; + padding-right: 0.5em; + } + .d2h-code-line-ctn { + word-wrap: normal; + background: none; + display: inline-block; + padding: 0; + -webkit-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + vertical-align: middle; + width: 100%; + /* only works for line-by-line */ + white-space: pre-wrap; + } + .d2h-code-line del, + .d2h-code-side-line del { + background-color: var(--git-delete-hl); + color: var(--text-normal); + } + .d2h-code-line del, + .d2h-code-line ins, + .d2h-code-side-line del, + .d2h-code-side-line ins { + border-radius: 0.2em; + display: inline-block; + margin-top: -1px; + text-decoration: none; + vertical-align: middle; + } + .d2h-code-line ins, + .d2h-code-side-line ins { + background-color: var(--git-insert-hl); + text-align: left; + } + .d2h-code-line-prefix { + word-wrap: normal; + background: none; + display: inline; + padding: 0; + white-space: pre; + } + .line-num1 { + float: left; + } + .line-num1, + .line-num2 { + -webkit-box-sizing: border-box; + box-sizing: border-box; + overflow: hidden; + /* + padding: 0 0.5em; + */ + text-overflow: ellipsis; + width: 2.5em; + padding-left: 0; + } + .line-num2 { + float: right; + } + .d2h-code-linenumber { + background-color: var(--background-primary); + border: solid var(--background-modifier-border); + border-width: 0 1px; + -webkit-box-sizing: border-box; + box-sizing: border-box; + color: var(--text-faint); + cursor: pointer; + display: inline-block; + position: absolute; + text-align: right; + width: 5.5em; + } + .d2h-code-linenumber:after { + content: "\200b"; + } + .d2h-code-side-linenumber { + background-color: var(--background-primary); + border: solid var(--background-modifier-border); + border-width: 0 1px; + -webkit-box-sizing: border-box; + box-sizing: border-box; + color: var(--text-faint); + cursor: pointer; + overflow: hidden; + padding: 0 0.5em; + text-align: right; + text-overflow: ellipsis; + width: 4em; + /* needed to be changed */ + display: table-cell; + position: relative; + } + .d2h-code-side-linenumber:after { + content: "\200b"; + } + .d2h-code-side-emptyplaceholder, + .d2h-emptyplaceholder { + background-color: var(--background-primary); + border-color: var(--background-modifier-border); + } + .d2h-code-line-prefix, + .d2h-code-linenumber, + .d2h-code-side-linenumber, + .d2h-emptyplaceholder { + -webkit-user-select: none; + -moz-user-select: none; + -ms-user-select: none; + user-select: none; + } + .d2h-code-linenumber, + .d2h-code-side-linenumber { + direction: rtl; + } + .d2h-del { + background-color: var(--git-delete-bg); + border-color: var(--git-delete-hl); + } + .d2h-ins { + background-color: var(--git-insert-bg); + border-color: var(--git-insert-hl); + } + .d2h-info { + background-color: var(--background-primary); + border-color: var(--background-modifier-border); + color: var(--text-faint); + } + .d2h-del, + .d2h-ins, + .d2h-file-diff .d2h-change { + color: var(--text-normal); + } + .d2h-file-diff .d2h-del.d2h-change { + background-color: var(--git-change-bg); + } + .d2h-file-diff .d2h-ins.d2h-change { + background-color: var(--git-insert-bg); + } + .d2h-file-list-wrapper { + a { + text-decoration: none; + cursor: default; + -webkit-user-drag: none; + } + + svg { + display: none; + } + } + .d2h-file-list-header { + text-align: left; + } + .d2h-file-list-title { + display: none; + } + .d2h-file-list-line { + display: -webkit-box; + display: -ms-flexbox; + display: flex; + text-align: left; + } + .d2h-file-list { + } + .d2h-file-list > li { + border-bottom: 1px solid var(--background-modifier-border); + margin: 0; + padding: 5px 10px; + } + .d2h-file-list > li:last-child { + border-bottom: none; + } + .d2h-file-switch { + cursor: pointer; + display: none; + font-size: 10px; + } + .d2h-icon { + fill: currentColor; + margin-right: 10px; + vertical-align: middle; + } + .d2h-deleted { + color: var(--git-delete); + } + .d2h-added { + color: var(--git-insert); + } + .d2h-changed { + color: var(--git-change); + } + .d2h-moved { + color: var(--git-move); + } + .d2h-tag { + background-color: var(--background-secondary); + display: -webkit-box; + display: -ms-flexbox; + display: flex; + font-size: 10px; + margin-left: 5px; + padding: 0 2px; + } + .d2h-deleted-tag { + border: 1px solid var(--git-delete); + } + .d2h-added-tag { + border: 1px solid var(--git-insert); + } + .d2h-changed-tag { + border: 1px solid var(--git-change); + } + .d2h-moved-tag { + border: 1px solid var(--git-move); + } + + /* needed for line-by-line*/ + + .d2h-diff-tbody { + position: relative; + } +} + +/* ====================== Line Authoring Information ====================== */ + +.cm-gutterElement.obs-git-blame-gutter { + /* Add background color to spacing inbetween and around the gutter for better aesthetics */ + border-width: 0px 2px 0.2px 2px; + border-style: solid; + border-color: var(--background-secondary); + background-color: var(--background-secondary); +} + +.cm-gutterElement.obs-git-blame-gutter > div, +.line-author-settings-preview { + /* delegate text color to settings */ + color: var(--obs-git-gutter-text); + font-family: monospace; + height: 100%; /* ensure, that age-based background color occupies entire parent */ + text-align: right; + padding: 0px 6px 0px 6px; + white-space: pre; /* Keep spaces and do not collapse them. */ +} + +@media (max-width: 800px) { + /* hide git blame gutter not to superpose text */ + .cm-gutterElement.obs-git-blame-gutter { + display: none; + } +} + +.git-unified-diff-view, +.git-split-diff-view .cm-deletedLine .cm-changedText { + background-color: #ee443330; +} + +.git-unified-diff-view, +.git-split-diff-view .cm-insertedLine .cm-changedText { + background-color: #22bb2230; +} + +.git-obscure-prompt[git-is-obscured="true"] #git-show-password:after { + -webkit-mask-image: url('data:image/svg+xml,'); +} + +.git-obscure-prompt[git-is-obscured="false"] #git-show-password:after { + -webkit-mask-image: url('data:image/svg+xml,'); +} + +/* Override styling of Codemirror merge view "collapsed lines" indicator */ +.git-split-diff-view .ͼ2 .cm-collapsedLines { + background: var(--interactive-normal); + border-radius: var(--radius-m); + color: var(--text-accent); + font-size: var(--font-small); + padding: var(--size-4-1) var(--size-4-1); +} +.git-split-diff-view .ͼ2 .cm-collapsedLines:hover { + background: var(--interactive-hover); + color: var(--text-accent-hover); +} + +.git-signs-gutter { + .cm-gutterElement { + display: grid; + } +} + +.git-gutter-marker:hover { + border-radius: 2px; +} + +.git-gutter-marker.git-add { + background-color: var(--color-green); + justify-self: center; + height: inherit; + width: 0.2rem; +} + +.git-gutter-marker.git-change { + background-color: var(--color-yellow); + justify-self: center; + height: inherit; + width: 0.2rem; +} + +.git-gutter-marker.git-changedelete { + color: var(--color-yellow); + font-weight: var(--font-bold); + font-size: 1rem; + justify-self: center; + height: inherit; +} + +.git-gutter-marker.git-delete { + background-color: var(--color-red); + height: 0.2rem; + width: 0.8rem; + align-self: end; +} + +.git-gutter-marker.git-topdelete { + background-color: var(--color-red); + height: 0.2rem; + width: 0.8rem; + align-self: start; +} + +div:hover > .git-gutter-marker.git-change { + width: 0.6rem; +} + +div:hover > .git-gutter-marker.git-add { + width: 0.6rem; +} + +div:hover > .git-gutter-marker.git-delete { + height: 0.6rem; +} + +div:hover > .git-gutter-marker.git-topdelete { + height: 0.6rem; +} + +div:hover > .git-gutter-marker.git-changedelete { + font-weight: var(--font-bold); +} + +.git-gutter-marker.staged { + opacity: 0.5; +} + +.git-diff { + .cm-merge-revert { + width: 4em; + } + /* Ensure that merge revert markers are positioned correctly */ + .cm-merge-revert > * { + position: absolute; + background-color: var(--background-secondary); + display: flex; + } +} + +/* Prevent shifting of the editor when git signs gutter is the only gutter present */ +.cm-gutters.cm-gutters-before:has(> .git-signs-gutter:only-child) { + margin-inline-end: 0; + .git-signs-gutter { + margin-inline-start: -1rem; + } +} + +.git-changes-status-bar-colored { + .git-add { + color: var(--color-green); + } + .git-change { + color: var(--color-yellow); + } + .git-delete { + color: var(--color-red); + } +} + +.git-changes-status-bar .git-add { + margin-right: 0.3em; +} + +.git-changes-status-bar .git-change { + margin-right: 0.3em; +} diff --git a/Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/data.json b/Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/data.json new file mode 100644 index 0000000..bfd03af --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/data.json @@ -0,0 +1,161 @@ +{ + "remoteType": "", + "useCustomRequestHandler": false, + "couchDB_URI": "", + "couchDB_USER": "", + "couchDB_PASSWORD": "", + "couchDB_DBNAME": "", + "liveSync": true, + "syncOnSave": true, + "syncOnStart": true, + "savingDelay": 200, + "lessInformationInLog": false, + "gcDelay": 0, + "versionUpFlash": "", + "minimumChunkSize": 20, + "longLineThreshold": 250, + "showVerboseLog": false, + "suspendFileWatching": false, + "trashInsteadDelete": true, + "periodicReplication": false, + "periodicReplicationInterval": 60, + "syncOnFileOpen": true, + "encrypt": true, + "passphrase": "", + "usePathObfuscation": true, + "doNotDeleteFolder": false, + "resolveConflictsByNewerFile": false, + "batchSave": false, + "batchSaveMinimumDelay": 5, + "batchSaveMaximumDelay": 60, + "deviceAndVaultName": "", + "usePluginSettings": false, + "showOwnPlugins": false, + "showStatusOnEditor": true, + "showStatusOnStatusbar": true, + "showOnlyIconsOnEditor": false, + "hideFileWarningNotice": false, + "usePluginSync": true, + "autoSweepPlugins": false, + "autoSweepPluginsPeriodic": false, + "notifyPluginOrSettingUpdated": false, + "checkIntegrityOnSave": false, + "batch_size": 50, + "batches_limit": 50, + "useHistory": true, + "disableRequestURI": true, + "skipOlderFilesOnSync": true, + "checkConflictOnlyOnOpen": false, + "showMergeDialogOnlyOnActive": false, + "syncInternalFiles": false, + "syncInternalFilesBeforeReplication": false, + "syncInternalFilesIgnorePatterns": "\\/node_modules\\/, \\/\\.git\\/, \\/obsidian-livesync\\/", + "syncInternalFilesTargetPatterns": "", + "syncInternalFilesInterval": 60, + "additionalSuffixOfDatabaseName": "e179f38ce95b7eed", + "ignoreVersionCheck": false, + "lastReadUpdates": 25, + "deleteMetadataOfDeletedFiles": false, + "syncIgnoreRegEx": "", + "syncOnlyRegEx": "", + "customChunkSize": 50, + "readChunksOnline": true, + "watchInternalFileChanges": true, + "automaticallyDeleteMetadataOfDeletedFiles": 0, + "disableMarkdownAutoMerge": false, + "writeDocumentsIfConflicted": false, + "useDynamicIterationCount": false, + "syncAfterMerge": true, + "configPassphraseStore": "", + "encryptedPassphrase": "%$s+QksMUttph3pELKlhGCPcf6j8XohMB/twWImqCHUoRfp1f4X5zpBaqHjvz0SvmXen0dzvp2Er+paTCHFFnd05lWr0GszSf63UcKXAmNsk1i6G+NY7ghL+tL47qIFy6yrigXasSmovZqNQHp4FIvZJ1lI/kTUPGA+mmtTa4=", + "encryptedCouchDBConnection": "%$s+QksMUttph3pELKlhGCPcf6j8XohMB/twWImqCHUoTQRcRD/47NoB+06PlB2N6EKh/+Q31tLYffv/5DjKDcuDAp/4KAeHY6Z9iFC5/PtS90EcVKitKF9X7/1AQFLPCIL2d9bw6npaM2jCSMv+FYmBLm7HGGQoF7UzLN1x9eTHIZG+TpDbXaWRlTMyT9xbhI9Qo9BsV7kX6a0gES7KuYqSCoG4cL/EW4mgKqde33zQUWXfsbLDFjkoVnTFaZ6CNMS4mkqcDzdJ+AZMOieOiB8v9+BdQceRGc+3PyVn/bqpUG1YFrBMXHAvEFESBoY31Ro/i/cEI5VWMlcEywn7BtgX6FTjois8bcE86lXO0UAY8o+G2kFxr9zZ19sb4mZC8BprWD9hOqupxBBj44FGL7HSEOG56ukyJ9oHlpkAfXEfcsfnjnmFTnOlMsryS+4x0txM+pLk95RLNeCsolbSaYwB/WH8RGksqnnHLa/6Y/uqCNKUdhuIdNs6N1qf8L76GG6tejHjohCElh8tu7QAHEbClkMb0pOhUqteHafBvB0mg5nhwKNekEG+2jOX4HRjrStKqysTUcF5n6jZWydsurVTxRX4kUotTiiEmGJalnfui54AkflFmYMD2TPcZ2YT+PzDsgL2n5V3y/8IMOBEXB+owkKMmFVlpHupStbwaq4aEeEQY7Wl/lPktXKjRTXSPF9BzXBH2Q0JjJMG6L1YWaSgFocw==", + "permitEmptyPassphrase": false, + "useIndexedDBAdapter": false, + "useTimeouts": false, + "writeLogToTheFile": false, + "doNotPaceReplication": false, + "hashCacheMaxCount": 300, + "hashCacheMaxAmount": 50, + "concurrencyOfReadChunksOnline": 100, + "minimumIntervalOfReadChunksOnline": 100, + "hashAlg": "xxhash64", + "suspendParseReplicationResult": false, + "doNotSuspendOnFetching": false, + "useIgnoreFiles": false, + "ignoreFiles": ".gitignore", + "syncOnEditorSave": true, + "pluginSyncExtendedSetting": {}, + "syncMaxSizeInMB": 50, + "settingSyncFile": "", + "writeCredentialsForSettingSync": false, + "notifyAllSettingSyncFile": false, + "isConfigured": true, + "settingVersion": 10, + "enableCompression": false, + "accessKey": "", + "bucket": "", + "endpoint": "", + "region": "", + "secretKey": "", + "useEden": false, + "maxChunksInEden": 10, + "maxTotalLengthInEden": 1024, + "maxAgeInEden": 10, + "disableCheckingConfigMismatch": false, + "displayLanguage": "def", + "enableChunkSplitterV2": false, + "disableWorkerForGeneratingChunks": false, + "processSmallFilesInUIThread": false, + "notifyThresholdOfRemoteStorageSize": 0, + "usePluginSyncV2": true, + "usePluginEtc": false, + "handleFilenameCaseSensitive": false, + "doNotUseFixedRevisionForChunks": false, + "showLongerLogInsideEditor": false, + "sendChunksBulk": false, + "sendChunksBulkMaxSize": 1, + "useSegmenter": false, + "useAdvancedMode": true, + "usePowerUserMode": false, + "useEdgeCaseMode": false, + "enableDebugTools": false, + "suppressNotifyHiddenFilesChange": false, + "syncMinimumInterval": 2000, + "P2P_Enabled": false, + "P2P_AutoAccepting": 0, + "P2P_AppID": "self-hosted-livesync", + "P2P_roomID": "", + "P2P_passphrase": "", + "P2P_relays": "wss://exp-relay.vrtmrz.net/", + "P2P_AutoBroadcast": false, + "P2P_AutoStart": false, + "P2P_AutoSyncPeers": "", + "P2P_AutoWatchPeers": "", + "P2P_SyncOnReplication": "", + "P2P_RebuildFrom": "", + "P2P_AutoAcceptingPeers": "", + "P2P_AutoDenyingPeers": "", + "P2P_IsHeadless": false, + "P2P_DevicePeerName": "", + "P2P_turnServers": "", + "P2P_turnUsername": "", + "P2P_turnCredential": "", + "doctorProcessedVersion": "0.25.27", + "bucketCustomHeaders": "", + "couchDB_CustomHeaders": "", + "useJWT": false, + "jwtAlgorithm": "", + "jwtKey": "", + "jwtKid": "", + "jwtSub": "", + "jwtExpDuration": 5, + "useRequestAPI": false, + "bucketPrefix": "", + "chunkSplitterVersion": "v3-rabin-karp", + "E2EEAlgorithm": "v2", + "processSizeMismatchedFiles": false, + "forcePathStyle": true, + "syncInternalFileOverwritePatterns": "", + "useOnlyLocalChunk": false, + "maxMTimeForReflectEvents": 0 +} \ No newline at end of file diff --git a/Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/main.js b/Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/main.js new file mode 100644 index 0000000..264233d --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/main.js @@ -0,0 +1,19 @@ +/* +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 _a7,_b5;return key3 in configurationNames?`${null==(_a7=configurationNames[key3])?void 0:_a7.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,p2=pre.split(",");p2[p2.length-1]+="{"+body+"}";const postParts=parseCommaParts(post);if(post.length){p2[p2.length-1]+=postParts.shift();p2.push.apply(p2,postParts)}parts.push.apply(parts,p2);return parts}function expand(str,options={}){if(!str)return[];const{max:max3=EXPANSION_MAX}=options;"{}"===str.slice(0,2)&&(str="\\{\\}"+str.slice(2));return expand_(escapeBraces(str),max3,!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,max3,isTop){const expansions=[],m3=balanced("{","}",str);if(!m3)return[str];const pre=m3.pre,post=m3.post.length?expand_(m3.post,max3,!1):[""];if(/\$$/.test(m3.pre))for(let k2=0;k2=0;if(!isSequence&&!isOptions)return m3.post.match(/,(?!,).*\}/)?expand_(str=m3.pre+"{"+m3.body+escClose+m3.post,max3,!0):[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],max3,!1).map(embrace);if(1===n3.length)return post.map((p2=>m3.pre+n3[0]+p2))}}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(y20){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;j2Uint8Array.fromBase64(e3).buffer)),len=bufItems.reduce(((p2,c3)=>p2+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{const blob=new Blob([buffer],{type:"application/octet-binary"}),reader=new FileReader;reader.onload=function(evt){var _a7,_b5;const dataURI=(null==(_b5=null==(_a7=evt.target)?void 0:_a7.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>>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>>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(((p2,c3)=>p2+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=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=>({"<":"<",">":">","&":"&",'"':""","'":"'","`":"`"}[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(((p2,c3)=>[...p2,p2[p2.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(p2){if("function"==typeof p2)return fireAndForget(p2());p2.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),p2=await Promise.race([d4.promise,aq2]);if(p2===TIMED_OUT_SIGNAL){fireAndForget((()=>aq2.then((release=>release()))));return!1}return p2},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{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.lengthvoid 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{p2.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(;i2set2.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(((p2,c3)=>({...p2,...c3})),{})}function objectToUnorderedArray(obj){const entries2=Object.entries(obj);if(entries2.some((e3=>{var _a7;return e3[0]!=(null==(_a7=e3[1])?void 0:_a7.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: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 p2=flattenObject(value,[...path2,key3]);ret.push(...p2)}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 map3=new Map;for(const chunk of chunks)map3.set(chunk._id,chunk);return map3}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 _a7;const prev=serializedMap.get(key3),p2=promiseWithResolvers();queueCount.set(key3,(null!=(_a7=queueCount.get(key3))?_a7:0)+1);const nextTask=async()=>{try{p2.resolve(await proc())}catch(ex){p2.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 p2.promise}function shareRunningResult(key3,proc){const prev=shareSerializedMap.get(key3);if(prev)return prev;const p2=promiseWithResolvers();shareSerializedMap.set(key3,p2.promise);const task=async()=>{try{p2.resolve(await proc())}catch(ex){p2.reject(ex)}finally{shareSerializedMap.delete(key3)}};fireAndForget((()=>task()));return p2.promise}function skipIfDuplicated(key3,proc){if(skipDuplicatedMap.get(key3))return Promise.resolve(null);const p2=promiseWithResolvers();skipDuplicatedMap.set(key3,p2.promise);const task=async()=>{try{p2.resolve(await proc())}catch(ex){p2.reject(ex)}finally{skipDuplicatedMap.delete(key3)}};fireAndForget((()=>task()));return p2.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 _a7;return(null!=(_a7=queueCount.get(key3))?_a7: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.size0;){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(truncatedBaseMTimee3==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 _a7,_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==(_a7=null==baseFile?void 0:baseFile.stat)?void 0:_a7.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 _a7;const savedData=null!=(_a7=await db.get(mapKey))?_a7: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,instance={id,dependants:new Set,_markDirty(){_isDirty||(_isDirty=!0)},markDirty(){topologicalSort(instance).forEach((node=>node._markDirty()))},_rippleChanged(){changeHandlers.forEach((e3=>e3(instance)))},rippleChanged(){topologicalSort(instance).forEach((node=>node._rippleChanged()))},markClean(){_isDirty=!1},get isDirty(){return _isDirty},get value(){if(context&&!instance.dependants.has(context)){instance.dependants.add(context);resetTopologicalSortCacheFor([instance.id,context.id])}if(_isDirty){if(expression){const oldValue=value,newValue=expression();isObjectDifferent(oldValue,newValue)&&(value=newValue)}instance.markClean()}return value},set value(newValue){if(_isDirty&&!expression)value=newValue;else if(isObjectDifferent(value,newValue)){value=newValue;if(!_isDirty){instance.markDirty();instance.rippleChanged()}}},onChanged(handler){changeHandlers.add(handler)},offChanged(handler){changeHandlers.delete(handler)}};value=function initialize(){const previousContext=context;context=instance;const r4=expression?expression(initialValue):initialValue;context=previousContext;return r4}();return instance}function computed(expression){const v2=reactive(expression);return()=>v2.value}function __$checkInstanceBinding(instance){const thisName=instance.constructor.name,functions=[];for(const key3 of Object.getOwnPropertyNames(Object.getPrototypeOf(instance)))key3.startsWith("_")&&!key3.startsWith("__")&&"function"==typeof instance[key3]&&functions.push(`${thisName}.${key3}`);const functionsOnBindFunction=[],functionsOnBindFunctionMatch=instance.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{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 `` `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 `
');$$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")}};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;ai2null==globalThis?void 0:globalThis.crypto;subtle=()=>{var _a7,_b5;return null!=(_b5=null==(_a7=cr())?void 0:_a7.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{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=p2=>p2 instanceof Point?p2: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 p2;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));p2=new _Point(x2,y2,BigInt("1"))}length===uncomp&&4===head2&&(p2=new _Point(x2,sliceBytesNumBE(tail,L,64),BigInt("1")));return p2?p2.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 t02=M(X1*X2),t12=M(Y1*Y2),t22=M(Z1*Z2),t32=M(X1+Y1),t42=M(X2+Y2);t32=M(t32*t42);t42=M(t02+t12);t32=M(t32-t42);t42=M(X1+Z1);let t52=M(X2+Z2);t42=M(t42*t52);t52=M(t02+t22);t42=M(t42-t52);t52=M(Y1+Z1);X3=M(Y2+Z2);t52=M(t52*X3);X3=M(t12+t22);t52=M(t52-X3);Z3=M(a2*t42);X3=M(b32*t22);Z3=M(X3+Z3);X3=M(t12-Z3);Z3=M(t12+Z3);Y3=M(X3*Z3);t12=M(t02+t02);t12=M(t12+t02);t22=M(a2*t22);t42=M(b32*t42);t12=M(t12+t22);t22=M(t02-t22);t22=M(a2*t22);t42=M(t42+t22);t02=M(t12*t42);Y3=M(Y3+t02);t02=M(t52*t42);X3=M(t32*X3);X3=M(X3-t02);t02=M(t32*t12);Z3=M(t52*Z3);Z3=M(Z3+t02);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 p2=I,f4=G;for(let d4=this;n3>BigInt("0");d4=d4.double(),n3>>=BigInt("1"))n3&BigInt("1")?p2=p2.add(d4):safe&&(f4=f4.add(d4));return p2}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=format2=>{null==format2||ALL_SIG.includes(format2)||err(`Signature format must be one of: ${ALL_SIG.join(", ")}`);format2===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.length1024)&&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),p2=G.multiply(d_),{x:x2,y:y2}=p2.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),t9=numTo32b(d4^bytesToNumBE(aux)),rand=taggedHash("nonce",t9,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,p2)=>_verifSchnorr(s2,m3,p2,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),t9=numTo32b(d4^bytesToNumBE(aux)),rand=await taggedHashAsync("nonce",t9,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,p2)=>_verifSchnorr(s2,m3,p2,challengeAsync)};pwindows=Math.ceil(32)+1;precompute=()=>{const points=[];let p2=G,b3=p2;for(let w2=0;w2{const n3=p2.negate();return cnd?n3:p2};wNAF=n3=>{const comp=Gpows||(Gpows=precompute());let p2=I,f4=G;const mask=big(255),shiftBy=big(8);for(let w2=0;w2>=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])):p2=p2.add(ctneg(isNeg,comp[offP]))}n3!==BigInt("0")&&err("invalid wnaf");return{p:p2,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}),handlers3={};let makingOffer=!1,isSettingRemoteAnswerPending=!1,dataChannel=null;const setupDataChannel=channel=>{channel.binaryType="arraybuffer";channel.bufferedAmountLowThreshold=65535;channel.onmessage=e3=>{var _a7;return null==(_a7=handlers3.data)?void 0:_a7.call(handlers3,e3.data)};channel.onopen=()=>{var _a7;return null==(_a7=handlers3.connect)?void 0:_a7.call(handlers3)};channel.onclose=()=>{var _a7;return null==(_a7=handlers3.close)?void 0:_a7.call(handlers3)};channel.onerror=err3=>{var _a7;return null==(_a7=handlers3.error)?void 0:_a7.call(handlers3,err3)}},waitForIceGathering=pc2=>Promise.race([new Promise((res2=>{const checkState5=()=>{if("complete"===pc2.iceGatheringState){pc2.removeEventListener("icegatheringstatechange",checkState5);res2()}};pc2.addEventListener("icegatheringstatechange",checkState5);checkState5()})),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 _a7,_b5;try{makingOffer=!0;await pc.setLocalDescription();const offer=await waitForIceGathering(pc);null==(_a7=handlers3.signal)||_a7.call(handlers3,offer)}catch(err3){null==(_b5=handlers3.error)||_b5.call(handlers3,err3)}finally{makingOffer=!1}};pc.onconnectionstatechange=()=>{var _a7;["disconnected","failed","closed"].includes(pc.connectionState)&&(null==(_a7=handlers3.close)||_a7.call(handlers3))};pc.ontrack=e3=>{var _a7,_b5;null==(_a7=handlers3.track)||_a7.call(handlers3,e3.track,e3.streams[0]);null==(_b5=handlers3.stream)||_b5.call(handlers3,e3.streams[0])};pc.onremovestream=e3=>{var _a7;return null==(_a7=handlers3.stream)?void 0:_a7.call(handlers3,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 _a7,_b5,_c3;if("open"!==(null==dataChannel?void 0:dataChannel.readyState)||(null==(_a7=sdp.sdp)?void 0:_a7.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=handlers3.signal)||_b5.call(handlers3,answer);return answer}if("answer"===sdp.type){isSettingRemoteAnswerPending=!0;try{await pc.setRemoteDescription(sdp)}finally{isSettingRemoteAnswerPending=!1}}}catch(err3){null==(_c3=handlers3.error)||_c3.call(handlers3,err3)}},sendData:data=>dataChannel.send(data),destroy:()=>{null==dataChannel||dataChannel.close();pc.close();makingOffer=!1;isSettingRemoteAnswerPending=!1},setHandlers:newHandlers=>Object.assign(handlers3,newHandlers),offerPromise:initiator?new Promise((res2=>handlers3.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(;chunkNchannel.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 _a7,_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]={});(_a7=pendingTransmissions[id])[type]||(_a7[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 _a7;null==(_a7=pendingPongs[id])||_a7.call(pendingPongs);delete pendingPongs[id]}));getSignal(((sdp,id)=>{var _a7;return null==(_a7=peerMap[id])?void 0:_a7.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 _a7;const{appId}=config;if(null==(_a7=occupiedRooms[appId])?void 0:_a7[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 _a8;if(connectedPeers[peerId])connectedPeers[peerId]!==peer&&peer.destroy();else{connectedPeers[peerId]=peer;onPeerConnect(peer,peerId);null==(_a8=pendingOffers[peerId])||_a8.forEach(((peer2,i2)=>{i2!==relayId&&peer2.destroy()}));delete pendingOffers[peerId]}},disconnectPeer=(peer,peerId)=>{connectedPeers[peerId]===peer&&delete connectedPeers[peerId]},prunePendingOffer=(peerId,relayId)=>{var _a8;if(connectedPeers[peerId])return;const offer=null==(_a8=pendingOffers[peerId])?void 0:_a8[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 _a8,_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==(_a8=pendingOffers[peerId])?void 0:_a8[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 _a7;return null!=(_a7=kindCache[topic])?_a7: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 _a7;const[msgType,subId,payload,relayMsg]=fromJson(data);if("EVENT"===msgType)null==(_a7=msgHandlers[subId])||_a7.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 _a7;return null==(_a7=this._server)?void 0:_a7.__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(),p2=promiseWithResolver();this.waitingInvocations.set(seq,p2);const request2={type,direction:"request",seq,args};timeout&&timeout>0&&this.invocationTimeouts.set(seq,setTimeout((()=>{if(this.waitingInvocations.has(seq)){this.waitingInvocations.delete(seq);p2.reject(new Error(`Invocation Timed out: ${type} (${seq}) (Timeout: ${timeout}ms)`))}this.invocationTimeouts.delete(seq)}),timeout));this.__send(request2,this._connectedPeerId);return p2.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 p2=this.waitingInvocations.get(seq);if(p2){this.waitingInvocations.delete(seq);if(data.error){p2.reject(data.error);Logger(`Invoking remote function [ DONE] : ${type} (${seq}) : (Error)`,LOG_LEVEL_VERBOSE)}else p2.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 _a7;return`${null!=(_a7=null==settings?void 0:settings.P2P_AutoAcceptingPeers)?_a7:""}`.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 _a7;return`${null!=(_a7=null==settings?void 0:settings.P2P_AutoDenyingPeers)?_a7:""}`.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 _a7;if(this._room){try{await(null==(_a7=this._room)?void 0:_a7.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 _a7;await(null==(_a7=this._room)?void 0:_a7.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 _a7,_b5;this.assignedFunctions.clear();const peers=null!=(_b5=null==(_a7=this.room)?void 0:_a7.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}};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 _a7,_b5,_c3,_d2,_e2;const knownPeersOrg=null!=(_b5=null==(_a7=r4.server)?void 0:_a7.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=this.env.services.UI.confirm,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(!this.env.services.UI.confirm){Logger("Cannot find confirm instance.",logLevel);return Promise.reject("Cannot find confirm instance.")}let result;for(;!result;)for(let i2=0;i2this.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{instance.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 _a7;this.requestStatus();await(null==(_a7=this.server)?void 0:_a7.shutdown());this._replicateFromPeers.clear();this._replicateToPeers.clear();this._watchingPeers.clear();this.requestStatus();this.disconnectFromServer()}async open(){var _a7;this.allowReconnection();await(null==(_a7=this.server)?void 0:_a7.start([this.getCommands()]));this.dispatchStatus();this.settings.P2P_AutoBroadcast&&this.enableBroadcastChanges()}async makeSureOpened(){var _a7;(null==(_a7=this.server)?void 0:_a7.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 _a7;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!=(_a7=allSettings[key3])?_a7:""));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 _a7;return await(null==(_a7=this.server)?void 0:_a7.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 _a7;this.dispatchStatus();null==(_a7=this.server)||_a7.dispatchConnectionStatus()}disableBroadcastChanges(){var _a7;null==(_a7=this.changes)||_a7.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 _a7,_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==(_a7=this.changes)||_a7.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 _a7,_b5;return null!=(_b5=null==(_a7=this.server)?void 0:_a7.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 _a7,_b5;const stat={peerId,peerName:(null==(_b5=null==(_a7=this.server)?void 0:_a7._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 _a7,_b5;const ack={peerId,peerName:(null==(_b5=null==(_a7=this.server)?void 0:_a7._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 _a7,_b5,_c3;if(await(null==(_a7=this.server)?void 0:_a7.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 _a7;return await(null==(_a7=this.server)?void 0:_a7.getConnection(peerId).invokeRemoteFunction("requestBroadcasting",[this.server.serverPeerId],0))}async getRemoteIsBroadcasting(peerId){var _a7;try{return await(null==(_a7=this.server)?void 0:_a7.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 _a7;if(!this.server){Logger("Server is not available",LOG_LEVEL_NOTICE);return!1}const peerPlatform=null==(_a7=this.server.knownAdvertisements.find((e3=>e3.peerId==peerId)))?void 0:_a7.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 _a7;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==(_a7=this.knownAdvertisements.find((e3=>e3.name==peer)))?void 0:_a7.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 _a7;null==(_a7=this.server)||_a7.dispatchConnectionStatus()}}));this.pauseServe()}async pauseServe(){var _a7,_b5;await(null==(_a7=this.server)?void 0:_a7.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{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 _a7,_b5,_c3;this.nextFrameQueue=void 0;const{message,status}=this.statusBarLabels.value,newMsg=message;let newLog=(null==(_a7=this.settings)?void 0:_a7.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)=>a20&&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 _a7;this.statusDiv&&this.statusDiv.remove();null==(_a7=document.querySelectorAll(".livesync-status"))||_a7.forEach((e3=>e3.remove()));return Promise.resolve(!0)}_everyOnloadStart(){(0,import_obsidian.addIcon)("view-log",'\n \n \n ');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 _a7;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==(_a7=this.settings)?void 0:_a7.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 time2=now3.toISOString().split("T")[0],logDate=`${PREFIXMD_LOGFILE}${time2}.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 _a7,_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==(_a7=message.cause)?void 0:_a7.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.onInitialise.addHandler(this._everyOnloadStart.bind(this));services.appLifecycle.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this));services.appLifecycle.onLoaded.addHandler(this._everyOnload.bind(this));services.appLifecycle.onBeforeUnload.addHandler(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('
Just for a minute, please!
',1);root_4=from_html('');root_6=from_html(" ");root_5=from_html('
');root_10=from_html('');root_2=from_html('
',1);root2=from_html('

',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(;i20}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 _a7;null==(_a7=this._lockFull)||_a7.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 _a7;null==(_a7=this._lockReady)||_a7.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 p2;const tasks3=[this._waitForFree(),...timeout?[(p2=cancelableDelay(timeout)).promise]:[],...cancellation||[]],r4=await Promise.race(tasks3);null==p2||p2.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 p2;const tasks3=[this._waitForReady(),...timeout?[(p2=cancelableDelay(timeout)).promise]:[],...cancellation||[]],r4=await Promise.race(tasks3);null==p2||p2.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 _a7;try{null==(_a7=this._onProgress)||_a7.call(this,this.stateDetail)}catch(e3){}}setOnProgress(callback){this._onProgress=callback}async _mainLoop(){var _a7;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==(_a7=this._onSentinel)?void 0:_a7.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 _a7;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!=(_a7=params.name)?_a7:this.constructor.name;this._clerks=[];for(let i2=0;i20)for(let i2=0;i2clerk.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 _a7;return this.nowProcessing+((null==(_a7=this._pipeTo)?void 0:_a7.totalNowProcessing)||0)}get remaining(){return this._queue.length+this.processingEntities+this.waitingEntries}get totalRemaining(){var _a7;return this.remaining+((null==(_a7=this._pipeTo)?void 0:_a7.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 _a7;null==(_a7=this._pipeTo)||_a7.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 p2=promiseWithResolvers(),releaser=this._hub.onEvent(key3,(()=>{p2.resolve(key3)}));p2.promise=p2.promise.finally((()=>{releaser()}));return p2})),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 _a7,_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!=(_a7=null==params?void 0:params.batchSize)?_a7: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 _a7;return this._isSuspended||(null==(_a7=this._pipeTo)?void 0:_a7.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 _a7,_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==(_a7=(await this.localDatabase.getRaw(id,{revs_info:!0}))._revs_info)?void 0:_a7.filter((e3=>"available"==e3.status&&Number(e3.rev.split("-")[0])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 _a7;null==(_a7=this.periodicInternalFileScanProcessor)||_a7.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 _a7;null==(_a7=this.periodicInternalFileScanProcessor)||_a7.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 _a7;null==(_a7=this.periodicInternalFileScanProcessor)||_a7.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 _a7,_b5;const stat=await this.plugin.storageAccess.statHidden(path2);if(!stat)return{name:null!=(_a7=path2.split("/").pop())?_a7:"",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 _a7,_b5;return`${null!=(_a7=null==stat?void 0:stat.mtime)?_a7: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((t9=>-1!==e3.indexOf(t9))))):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((t9=>-1!==e3.path.indexOf(t9))))):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),p2=this._progress("[⚙ Storage -> DB ]\n",logLevel),notifyProgress=onlyInNTimes(100,(progress=>p2.log(`${progress}/${processFiles.length}`))),processes=processFiles.map((async(file,i2)=>{try{await this.trackStorageFileModification(file,onlyNew,forceWriteAll,includeDeleted);notifyProgress()}catch(ex){p2.once(`Failed to process storage change file:${file}`);this._log(ex,LOG_LEVEL_VERBOSE)}}));await Promise.all(processes);p2.done()}async scanAllStorageChanges(showNotice=!1,onlyNew=!1,forceWriteAll=!1,includeDeleted=!0){return await skipIfDuplicated("scanAllStorageChanges",(async()=>{const logLevel=getLogLevel(showNotice),p2=this._progress("[⚙ Scanning Storage -> DB ]\n",logLevel);p2.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}`;p2.once(staticsMessage);await this.trackScannedStorageChanges(processFiles,showNotice,onlyNew,forceWriteAll,includeDeleted);p2.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 _a7;const conflictedDoc=await this.localDatabase.getRaw(id,{rev:conflictedRev}),delRev=getComparingMTime(currentDoc,!0){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 _a7,_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!=(_a7=null==stat?void 0:stat.ctime)?_a7: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),p2=this._progress("[⚙ DB -> Storage ]\n",logLevel),notifyProgress=onlyInNTimes(100,(progress=>p2.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);p2.done()}async applyOfflineChanges(showNotice){const logLevel=getLogLevel(showNotice);return await serialized("applyOfflineChanges",(async()=>{const p2=this._progress("[⚙ Apply untracked changes ]\n",logLevel);this._log("Track changes.",logLevel);p2.log("Enumerating local files...");const currentStorageFiles=await this.scanInternalFileNames();p2.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)));p2.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}`;p2.once(stat);const semaphores2=Semaphore(10),notifyProgress=onlyInNTimes(25,(progress=>p2.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);p2.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),p2=this._progress("[⚙ Scanning DB -> Storage ]\n",logLevel);p2.log("Scanning database files...");const notifyProgress=onlyInNTimes(25,(progress=>p2.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);p2.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 _a7;return updatedFolders.indexOf(null!=(_a7=null==e3?void 0:e3.dir)?_a7:"")>=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),p2=this._progress("[⚙ Rebuild by Merge ]\n",logLevel);this._log("Rebuilding hidden files from the storage and the local database.",logLevel);p2.log("Enumerating local files...");const currentStorageFilesAll=await this.scanInternalFileNames(),currentStorageFiles=targetFiles?currentStorageFilesAll.filter((e3=>targetFiles.some((f4=>f4==e3)))):currentStorageFilesAll;p2.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=>p2.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)}p2.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)];p2.log("Start processing...");await Promise.all(processes);p2.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 p2=this._progress("[⚙ Rebuild by Storage ]\n",logLevel);p2.log("Enumerating local files...");const currentFilesAll=await this.scanInternalFileNames(),currentFiles=targetFiles?currentFilesAll.filter((e3=>targetFiles.some((f4=>f4==e3)))):currentFilesAll;p2.once(`Storage to Database: ${currentFiles.length} files.`);p2.log("Start processing...");this.resetLastProcessedFile(targetFiles);await this.useStorageFiles(currentFiles,showNotice,onlyNew);p2.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 p2=this._progress("[⚙ Rebuild by Database ]\n",logLevel);p2.log("Enumerating database files...");const allFiles=await this.getAllDatabaseFiles(),currentFiles=targetFiles?allFiles.filter((e3=>targetFiles.some((f4=>f4==stripAllPrefixes(getPath2(e3)))))):allFiles;p2.once(`Database to Storage: ${currentFiles.length} files.`);this.resetLastProcessedDatabase(targetFiles);p2.log("Start processing...");await this.useDatabaseFiles(currentFiles,showNotice,onlyNew);p2.done();return currentFiles}async initialiseInternalFileSync(direction,showMessage,targetFilesSrc=!1){const logLevel=showMessage?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,p2=this._progress("[⚙ Initialise]\n",logLevel);p2.log("Initialising hidden files sync...");const targetFiles=!!targetFilesSrc&&targetFilesSrc.map((e3=>stripAllPrefixes(e3)));if("pushForce"==direction||"push"==direction){const onlyNew="push"==direction;p2.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;p2.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){p2.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)}p2.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 _a7,_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==(_a7=null==metaOnDB?void 0:metaOnDB._conflicts)?void 0:_a7.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 [!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 _a7,_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==(_a7=w2.stat)?void 0:_a7.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.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this));services.fileProcessing.processOptionalFileEvent.addHandler(this._anyProcessOptionalFileEvent.bind(this));services.conflict.getOptionalConflictCheckMethod.addHandler(this._anyGetOptionalConflictCheckMethod.bind(this));services.replication.processOptionalSynchroniseResult.addHandler(this._anyProcessOptionalSyncFiles.bind(this));services.setting.onRealiseSetting.addHandler(this._everyRealizeSettingSyncMode.bind(this));services.appLifecycle.onResuming.addHandler(this._everyOnResumeProcess.bind(this));services.replication.onBeforeReplicate.addHandler(this._everyBeforeReplicate.bind(this));services.databaseEvents.onDatabaseInitialised.addHandler(this._everyOnDatabaseInitialized.bind(this));services.setting.suspendExtraSync.addHandler(this._allSuspendExtraSync.bind(this));services.setting.suggestOptionalFeatures.addHandler(this._allAskUsingOptionalSyncFeature.bind(this));services.setting.enableOptionalFeature.addHandler(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+=""+escapeStringToHTML(x2).replace(/\n/g,"\n")+"":x1==import_diff_match_patch2.DIFF_EQUAL?diff+=""+escapeStringToHTML(x2).replace(/\n/g,"\n")+"":x1==import_diff_match_patch2.DIFF_INSERT&&(diff+=""+escapeStringToHTML(x2).replace(/\n/g,"\n")+"")}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=`${this.localName}: ${date1}
\n${this.remoteName}: ${date2}
`;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,"
");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("");root_62=from_html('');root_7=from_html('');root_8=from_html('');root_42=from_html(' ',1);root_9=from_html(' ',1);root_11=from_html('');root_122=from_html('');root_22=from_html(' ',1);root_13=from_html(' ',1);root_132=from_html(' All the same or non-existent ',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('');root_23=from_html(" ");root_32=from_html('
No Items.
');root_82=from_html('
');root_63=from_html('
');root_52=from_html('

');root_133=from_html('
');root_15=from_html('
');root_18=from_html('
');root_16=from_html('
Other files
');root_112=from_html('
MAIN
DATA
',1);root_19=from_html('
');root_92=from_html('
',1);root_43=from_html('

Plugins

',1);root_21=from_html("");root_20=from_html('

Maintenance Commands

');root3=from_html('
',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 _a7;this.hidePluginSyncModal();null==(_a7=this.periodicPluginSweepProcessor)||_a7.disable()}onload(){(0,import_obsidian.addIcon)("custom-sync",'\n \n ');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 _a7;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!=(_a7=null==stripTable?void 0:stripTable[category])?_a7: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 p2=delList.map((async e3=>{await this.deleteConfigOnDatabase(e3);await this.updatePluginList(!1,e3)}));await Promise.allSettled(p2);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 _a7;const popup=await memoIfNotExist(updatedPluginKey,(()=>new import_obsidian.Notice(fragment,0)));(null==(_a7=null==popup?void 0:popup.noticeEl)?void 0:_a7.isShown())||memoObject(updatedPluginKey,new import_obsidian.Notice(fragment,0));scheduleTask(updatedPluginKey+"-close",2e4,(()=>{var _a8;const popup2=retrieveMemoObject(updatedPluginKey);if(popup2){(null==(_a8=null==popup2?void 0:popup2.noticeEl)?void 0:_a8.isShown())&&popup2.hide();disposeMemoObject(updatedPluginKey)}}))}))}return!0}async _everyRealizeSettingSyncMode(){var _a7;null==(_a7=this.periodicPluginSweepProcessor)||_a7.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 _a7,_b5;try{return await isDocContentSame(null!=(_b5=null==(_a7=e3.curr)?void 0:_a7.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 _a7;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 p2=null==(_a7=files.find((e3=>e3.key==vp)))?void 0:_a7.file;if(p2){await this.storeCustomizationFiles(p2);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.processOptionalFileEvent.addHandler(this._anyProcessOptionalFileEvent.bind(this));services.conflict.getOptionalConflictCheckMethod.addHandler(this._anyGetOptionalConflictCheckMethod.bind(this));services.replication.processVirtualDocument.addHandler(this._anyModuleParsedReplicationResultItem.bind(this));services.setting.onRealiseSetting.addHandler(this._everyRealizeSettingSyncMode.bind(this));services.appLifecycle.onResuming.addHandler(this._everyOnResumeProcess.bind(this));services.appLifecycle.onResumed.addHandler(this._everyAfterResumeProcess.bind(this));services.replication.onBeforeReplicate.addHandler(this._everyBeforeReplicate.bind(this));services.databaseEvents.onDatabaseInitialised.addHandler(this._everyOnDatabaseInitialized.bind(this));services.setting.suspendExtraSync.addHandler(this._allSuspendExtraSync.bind(this));services.setting.suggestOptionalFeatures.addHandler(this._allAskUsingOptionalSyncFeature.bind(this));services.setting.enableOptionalFeature.addHandler(this._allConfigureOptionalSyncFeature.bind(this))}};getHttpHandlerExtensionConfiguration=runtimeConfig=>({setHttpHandler(handler){runtimeConfig.httpHandler=handler},httpHandler:()=>runtimeConfig.httpHandler,updateHttpClientConfig(key3,value){var _a7;null==(_a7=runtimeConfig.httpHandler)||_a7.updateHttpClientConfig(key3,value)},httpHandlerConfigs:()=>runtimeConfig.httpHandler.httpHandlerConfigs()});resolveHttpHandlerRuntimeConfig=httpHandlerExtensionConfiguration=>({httpHandler:httpHandlerExtensionConfiguration.httpHandler()});(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={}));SMITHY_CONTEXT_KEY="__smithy_context";HttpRequest=class _HttpRequest{constructor(options){__publicField(this,"method");__publicField(this,"protocol");__publicField(this,"hostname");__publicField(this,"port");__publicField(this,"path");__publicField(this,"query");__publicField(this,"headers");__publicField(this,"username");__publicField(this,"password");__publicField(this,"fragment");__publicField(this,"body");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){__publicField(this,"statusCode");__publicField(this,"reason");__publicField(this,"headers");__publicField(this,"body");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)}});(function(ChecksumAlgorithm2){ChecksumAlgorithm2.MD5="MD5";ChecksumAlgorithm2.CRC32="CRC32";ChecksumAlgorithm2.CRC32C="CRC32C";ChecksumAlgorithm2.CRC64NVME="CRC64NVME";ChecksumAlgorithm2.SHA1="SHA1";ChecksumAlgorithm2.SHA256="SHA256"})(ChecksumAlgorithm||(ChecksumAlgorithm={}));(function(ChecksumLocation2){ChecksumLocation2.HEADER="header";ChecksumLocation2.TRAILER="trailer"})(ChecksumLocation||(ChecksumLocation={}));DEFAULT_CHECKSUM_ALGORITHM=ChecksumAlgorithm.CRC32;getDateHeader=response=>{var _a7,_b5,_c3;return HttpResponse.isInstance(response)?null!=(_c3=null==(_a7=response.headers)?void 0:_a7.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 _a7,_b5,_c3;const context2=throwSigningPropertyError("context",signingProperties.context),config=throwSigningPropertyError("config",signingProperties.config),authScheme=null==(_c3=null==(_b5=null==(_a7=context2.endpointV2)?void 0:_a7.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 _a7,_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==(_a7=null==handlerExecutionContext?void 0:handlerExecutionContext.authSchemes)?void 0:_a7.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 _a7;const serverTime=null!=(_a7=error.ServerTime)?_a7: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 _a7,_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==(_a7=config.sigv4aSigningRegionSet)?void 0:_a7.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})}};getSmithyContext=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 _a7;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=getSmithyContext(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==(_a7=option.propertiesExtractor)?void 0:_a7.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)}});serializerMiddlewareOption={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};defaultErrorHandler=signingProperties=>error=>{throw error};defaultSuccessHandler=(httpResponse,signingProperties)=>{};httpSigningMiddleware=config=>(next2,context2)=>async args=>{if(!HttpRequest.isInstance(args.request))return next2(args);const scheme=getSmithyContext(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};makePagedClientRequest=async(CommandCtor,client,input,withCommand=_=>_,...args)=>{var _a7;let command=new CommandCtor(input);command=null!=(_a7=withCommand(command))?_a7:command;return await client.send(command,...args)};get3=(fromObject,path2)=>{let cursor=fromObject;const pathComponents=path2.split(".");for(const step of pathComponents){if(!cursor||"object"!=typeof cursor)return;cursor=cursor[step]}return cursor};chars="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";alphabetByEncoding=Object.entries(chars).reduce(((acc,[i2,c3])=>{acc[c3]=Number(i2);return acc}),{});alphabetByValue=chars.split("");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>=bitsPerLetter;const chunkOffset=i2/4*3;bits2>>=bitLength%bitsPerByte;const byteLength=Math.floor(bitLength/bitsPerByte);for(let k2=0;k2>offset)}}return new Uint8Array(out)};init_dist_es();init_dist_es();Uint8ArrayBlobAdapter=class _Uint8ArrayBlobAdapter extends Uint8Array{static fromString(source2,encoding="utf-8"){if("string"==typeof source2)return"base64"===encoding?_Uint8ArrayBlobAdapter.mutate(fromBase64(source2)):_Uint8ArrayBlobAdapter.mutate(fromUtf8(source2));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"base64"===encoding?toBase64(this):toUtf8(this)}};ReadableStreamRef="function"==typeof ReadableStream?ReadableStream:function(){};ChecksumStream=class extends ReadableStreamRef{};isReadableStream=stream=>{var _a7;return"function"==typeof ReadableStream&&((null==(_a7=null==stream?void 0:stream.constructor)?void 0:_a7.name)===ReadableStream.name||stream instanceof ReadableStream)};createChecksumStream=({expectedChecksum,checksum,source:source2,checksumSourceLocation,base64Encoder})=>{var _a7,_b5;if(!isReadableStream(source2))throw new Error(`@smithy/util-stream: unsupported source type ${null!=(_b5=null==(_a7=null==source2?void 0:source2.constructor)?void 0:_a7.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){__publicField(this,"allocByteArray");__publicField(this,"byteLength",0);__publicField(this,"byteArrays",[]);this.allocByteArray=allocByteArray}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;i2new 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{constructor(options){__publicField(this,"config");__publicField(this,"configProvider");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]")))}static create(instanceOrOptions){return"function"==typeof(null==instanceOrOptions?void 0:instanceOrOptions.handle)?instanceOrOptions:new _FetchHttpHandler(instanceOrOptions)}destroy(){}async handle(request2,{abortSignal,requestTimeout:requestTimeout2}={}){var _a7,_b5,_c3;this.config||(this.config=await this.configProvider);const requestTimeoutInMs=null!=requestTimeout2?requestTimeout2: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!=(_a7=request2.username)?_a7:""}:${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 _a7;return null!=(_a7=this.config)?_a7:{}}};streamCollector=async stream=>{var _a7;return"function"==typeof Blob&&stream instanceof Blob||"Blob"===(null==(_a7=stream.constructor)?void 0:_a7.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}init_dist_es();sdkStreamMixin=stream=>{var _a7,_b5;if(!isBlobInstance(stream)&&!isReadableStream(stream)){const name=(null==(_b5=null==(_a7=null==stream?void 0:stream.__proto__)?void 0:_a7.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)};deref=schemaRef=>"function"==typeof schemaRef?schemaRef():schemaRef;operation=(namespace,name,traits,input,output)=>({name,namespace,traits,input,output});schemaDeserializationMiddleware=config=>(next2,context2)=>async args=>{var _a7,_b5,_c3,_d2;const{response}=await next2(args),{operationSchema}=getSmithyContext(context2),[,ns,n3,t9,i2,o2]=null!=operationSchema?operationSchema:[];try{return{response,output:await config.protocol.deserializeResponse(operation(ns,n3,t9,i2,o2),{...config,...context2},response)}}catch(error){Object.defineProperty(error,"$response",{value:response,enumerable:!1,writable:!1,configurable:!1});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==(_a7=context2.logger)?void 0:_a7.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:findHeader2(/^x-[\w-]+-request-?id$/,headerEntries),extendedRequestId:findHeader2(/^x-[\w-]+-id-2$/,headerEntries),cfId:findHeader2(/^x-[\w-]+-cf-id$/,headerEntries)}}}catch(e3){}}throw error}};findHeader2=(pattern,headers)=>(headers.find((([k2])=>k2.match(pattern)))||[void 0,void 0])[1];schemaSerializationMiddleware=config=>(next2,context2)=>async args=>{var _a7;const{operationSchema}=getSmithyContext(context2),[,ns,n3,t9,i2,o2]=null!=operationSchema?operationSchema:[],endpoint=(null==(_a7=context2.endpointV2)?void 0:_a7.url)&&config.urlParser?async()=>config.urlParser(context2.endpointV2.url):config.endpoint,request2=await config.protocol.serializeRequest(operation(ns,n3,t9,i2,o2),args.input,{...config,...context2,endpoint});return next2({...args,request:request2})};deserializerMiddlewareOption2={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0};serializerMiddlewareOption2={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};anno_it=Symbol.for("@smithy/nor-struct-it");_NormalizedSchema=class _NormalizedSchema{constructor(ref,memberName){__publicField(this,"ref");__publicField(this,"memberName");__publicField(this,"symbol",_NormalizedSchema.symbol);__publicField(this,"name");__publicField(this,"schema");__publicField(this,"_isMemberSchema");__publicField(this,"traits");__publicField(this,"memberTraits");__publicField(this,"normalizedTraits");var _a7;this.ref=ref;this.memberName=memberName;const traitStack=[];let _ref=ref,schema=ref;this._isMemberSchema=!1;for(;isMemberSchema(_ref);){traitStack.push(_ref[1]);_ref=_ref[0];schema=deref(_ref);this._isMemberSchema=!0}if(traitStack.length>0){this.memberTraits={};for(let i2=traitStack.length-1;i2>=0;--i2){const traitSet=traitStack[i2];Object.assign(this.memberTraits,translateTraits(traitSet))}}else this.memberTraits=0;if(schema instanceof _NormalizedSchema){const computedMemberTraits=this.memberTraits;Object.assign(this,schema);this.memberTraits=Object.assign({},computedMemberTraits,schema.getMemberTraits(),this.getMemberTraits());this.normalizedTraits=void 0;this.memberName=null!=memberName?memberName:schema.memberName}else{this.schema=deref(schema);if(isStaticSchema(this.schema)){this.name=`${this.schema[1]}#${this.schema[2]}`;this.traits=this.schema[3]}else{this.name=null!=(_a7=this.memberName)?_a7:String(schema);this.traits=0}if(this._isMemberSchema&&!memberName)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}}static[Symbol.hasInstance](lhs){const isPrototype=this.prototype.isPrototypeOf(lhs);return isPrototype||"object"!=typeof lhs||null===lhs?isPrototype:lhs.symbol===this.symbol}static of(ref){const sc=deref(ref);if(sc instanceof _NormalizedSchema)return sc;if(isMemberSchema(sc)){const[ns,traits]=sc;if(ns instanceof _NormalizedSchema){Object.assign(ns.getMergedTraits(),translateTraits(traits));return ns}throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(ref,null,2)}.`)}return new _NormalizedSchema(sc)}getSchema(){const sc=this.schema;return Array.isArray(sc)&&0===sc[0]?sc[4]:sc}getName(withNamespace=!1){const{name}=this;return!withNamespace&&name&&name.includes("#")?name.split("#")[1]:name||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){const sc=this.getSchema();return"number"==typeof sc?sc>=64&&sc<128:1===sc[0]}isMapSchema(){const sc=this.getSchema();return"number"==typeof sc?sc>=128&&sc<=255:2===sc[0]}isStructSchema(){const sc=this.getSchema();if("object"!=typeof sc)return!1;const id=sc[0];return 3===id||-3===id||4===id}isUnionSchema(){const sc=this.getSchema();return"object"==typeof sc&&4===sc[0]}isBlobSchema(){const sc=this.getSchema();return 21===sc||42===sc}isTimestampSchema(){const sc=this.getSchema();return"number"==typeof sc&&sc>=4&&sc<=7}isUnitSchema(){return"unit"===this.getSchema()}isDocumentSchema(){return 15===this.getSchema()}isStringSchema(){return 0===this.getSchema()}isBooleanSchema(){return 2===this.getSchema()}isNumericSchema(){return 1===this.getSchema()}isBigIntegerSchema(){return 17===this.getSchema()}isBigDecimalSchema(){return 19===this.getSchema()}isStreaming(){const{streaming}=this.getMergedTraits();return!!streaming||42===this.getSchema()}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){var _a7;return null!=(_a7=this.normalizedTraits)?_a7:this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()}}getMemberTraits(){return translateTraits(this.memberTraits)}getOwnTraits(){return translateTraits(this.traits)}getKeySchema(){var _a7;const[isDoc,isMap]=[this.isDocumentSchema(),this.isMapSchema()];if(!isDoc&&!isMap)throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);const schema=this.getSchema();return member([isDoc?15:null!=(_a7=schema[4])?_a7:0,0],"key")}getValueSchema(){const sc=this.getSchema(),[isDoc,isMap,isList]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],memberSchema="number"==typeof sc?63&sc:sc&&"object"==typeof sc&&(isMap||isList)?sc[3+sc[0]]:isDoc?15:void 0;if(null!=memberSchema)return member([memberSchema,0],isMap?"value":"member");throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(memberName){const struct=this.getSchema();if(this.isStructSchema()&&struct[4].includes(memberName)){const i2=struct[4].indexOf(memberName),memberSchema=struct[5][i2];return member(isMemberSchema(memberSchema)?memberSchema:[memberSchema,0],memberName)}if(this.isDocumentSchema())return member([15,0],memberName);throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no no member=${memberName}.`)}getMemberSchemas(){const buffer={};try{for(const[k2,v2]of this.structIterator())buffer[k2]=v2}catch(ignored){}return buffer}getEventStreamMember(){if(this.isStructSchema())for(const[memberName,memberSchema]of this.structIterator())if(memberSchema.isStreaming()&&memberSchema.isStructSchema())return memberName;return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");const struct=this.getSchema(),z2=struct[4].length;let it=struct[anno_it];if(it&&z2===it.length)yield*it;else{it=Array(z2);for(let i2=0;i2Array.isArray(sc)&&2===sc.length;isStaticSchema=sc=>Array.isArray(sc)&&sc.length>=5;_TypeRegistry=class _TypeRegistry{constructor(namespace,schemas=new Map,exceptions=new Map){__publicField(this,"namespace");__publicField(this,"schemas");__publicField(this,"exceptions");this.namespace=namespace;this.schemas=schemas;this.exceptions=exceptions}static for(namespace){_TypeRegistry.registries.has(namespace)||_TypeRegistry.registries.set(namespace,new _TypeRegistry(namespace));return _TypeRegistry.registries.get(namespace)}register(shapeId,schema){const qualifiedName=this.normalizeShapeId(shapeId);_TypeRegistry.for(qualifiedName.split("#")[0]).schemas.set(qualifiedName,schema)}getSchema(shapeId){const id=this.normalizeShapeId(shapeId);if(!this.schemas.has(id))throw new Error(`@smithy/core/schema - schema not found for ${id}`);return this.schemas.get(id)}registerError(es,ctor){const $error=es,registry=_TypeRegistry.for($error[1]);registry.schemas.set($error[1]+"#"+$error[2],$error);registry.exceptions.set($error,ctor)}getErrorCtor(es){const $error=es;return _TypeRegistry.for($error[1]).exceptions.get($error)}getBaseException(){for(const exceptionKey of this.exceptions.keys())if(Array.isArray(exceptionKey)){const[,ns,name]=exceptionKey,id=ns+"#"+name;if(id.startsWith("smithy.ts.sdk.synthetic.")&&id.endsWith("ServiceException"))return exceptionKey}}find(predicate){return[...this.schemas.values()].find(predicate)}clear(){this.schemas.clear();this.exceptions.clear()}normalizeShapeId(shapeId){return shapeId.includes("#")?shapeId:this.namespace+"#"+shapeId}};__publicField(_TypeRegistry,"registries",new Map);TypeRegistry=_TypeRegistry;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}`)}};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]}};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)};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]$/);new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/);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=(year2,month,day,time2)=>{const adjustedMonth=month-1;validateDayOfMonth(year2,adjustedMonth,day);return new Date(Date.UTC(year2,adjustedMonth,day,parseDateValue(time2.hours,"hour",0,23),parseDateValue(time2.minutes,"minute",0,59),parseDateValue(time2.seconds,"seconds",0,60),parseMilliseconds(time2.fractionalMilliseconds)))};parseTwoDigitYear=value=>{const thisYear=(new Date).getUTCFullYear(),valueInThisCentury=100*Math.floor(thisYear/100)+strictParseShort(stripLeadingZeroes(value));return valueInThisCenturyinput.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=(year2,month,day)=>{let maxDays=DAYS_IN_MONTH[month];1===month&&isLeapYear(year2)&&(maxDays=29);if(day>maxDays)throw new TypeError(`Invalid day for ${MONTHS[month]} in ${year2}: ${day}`)};isLeapYear=year2=>year2%4==0&&(year2%100!=0||year2%400==0);parseDateValue=(value,type,lower,upper)=>{const dateVal=strictParseByte(stripLeadingZeroes(value));if(dateValupper)throw new TypeError(`${type} must be between ${lower} and ${upper}, inclusive`);return dateVal};parseMilliseconds=value=>null==value?0:1e3*strictParseFloat32("0."+value);stripLeadingZeroes=value=>{let idx2=0;for(;idx2i2.toString(16).padStart(2,"0")));v4=()=>{if(randomUUID)return randomUUID();const rnds=new Uint8Array(16);crypto.getRandomValues(rnds);rnds[6]=15&rnds[6]|64;rnds[8]=63&rnds[8]|128;return decimalToHex[rnds[0]]+decimalToHex[rnds[1]]+decimalToHex[rnds[2]]+decimalToHex[rnds[3]]+"-"+decimalToHex[rnds[4]]+decimalToHex[rnds[5]]+"-"+decimalToHex[rnds[6]]+decimalToHex[rnds[7]]+"-"+decimalToHex[rnds[8]]+decimalToHex[rnds[9]]+"-"+decimalToHex[rnds[10]]+decimalToHex[rnds[11]]+decimalToHex[rnds[12]]+decimalToHex[rnds[13]]+decimalToHex[rnds[14]]+decimalToHex[rnds[15]]};(LazyJsonString=function LazyJsonString2(val){return Object.assign(new String(val),{deserializeJSON:()=>JSON.parse(String(val)),toString:()=>String(val),toJSON:()=>String(val)})}).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;ddd="(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun)(?:[ne|u?r]?s?day)?";mmm="(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)";time="(\\d?\\d):(\\d{2}):(\\d{2})(?:\\.(\\d+))?";RFC3339_WITH_OFFSET2=new RegExp(/^(\d{4})-(\d\d)-(\d\d)[tT](\d\d):(\d\d):(\d\d)(\.(\d+))?(([-+]\d\d:\d\d)|[zZ])$/);IMF_FIXDATE2=new RegExp(`^${ddd}, (\\d?\\d) ${mmm} (\\d{4}) ${time} GMT$`);RFC_850_DATE2=new RegExp(`^${ddd}, (\\d?\\d)-${mmm}-(\\d\\d) ${time} GMT$`);ASC_TIME2=new RegExp(`^${ddd} ${mmm} ( [1-9]|\\d\\d) ${time} (\\d{4})$`);months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];_parseEpochTimestamp=value=>{if(null==value)return;let num=NaN;if("number"==typeof value)num=value;else if("string"==typeof value){if(!/^-?\d*\.?\d+$/.test(value))throw new TypeError("parseEpochTimestamp - numeric string invalid.");num=Number.parseFloat(value)}else"object"==typeof value&&1===value.tag&&(num=value.value);if(isNaN(num)||Math.abs(num)===1/0)throw new TypeError("Epoch timestamps must be valid finite numbers.");return new Date(Math.round(1e3*num))};_parseRfc3339DateTimeWithOffset=value=>{if(null==value)return;if("string"!=typeof value)throw new TypeError("RFC3339 timestamps must be strings");const matches=RFC3339_WITH_OFFSET2.exec(value);if(!matches)throw new TypeError(`Invalid RFC3339 timestamp format ${value}`);const[,yearStr,monthStr,dayStr,hours,minutes,seconds,,ms,offsetStr]=matches;range3(monthStr,1,12);range3(dayStr,1,31);range3(hours,0,23);range3(minutes,0,59);range3(seconds,0,60);const date2=new Date(Date.UTC(Number(yearStr),Number(monthStr)-1,Number(dayStr),Number(hours),Number(minutes),Number(seconds),Number(ms)?Math.round(1e3*parseFloat(`0.${ms}`)):0));date2.setUTCFullYear(Number(yearStr));if("Z"!=offsetStr.toUpperCase()){const[,sign2,offsetH,offsetM]=/([+-])(\d\d):(\d\d)/.exec(offsetStr)||[void 0,"+",0,0],scalar="-"===sign2?1:-1;date2.setTime(date2.getTime()+scalar*(60*Number(offsetH)*60*1e3+60*Number(offsetM)*1e3))}return date2};_parseRfc7231DateTime=value=>{if(null==value)return;if("string"!=typeof value)throw new TypeError("RFC7231 timestamps must be strings.");let day,month,year2,hour,minute,second,fraction,matches;if(matches=IMF_FIXDATE2.exec(value))[,day,month,year2,hour,minute,second,fraction]=matches;else if(matches=RFC_850_DATE2.exec(value)){[,day,month,year2,hour,minute,second,fraction]=matches;year2=(Number(year2)+1900).toString()}else(matches=ASC_TIME2.exec(value))&&([,month,day,hour,minute,second,fraction,year2]=matches);if(year2&&second){const timestamp=Date.UTC(Number(year2),months.indexOf(month),Number(day),Number(hour),Number(minute),Number(second),fraction?Math.round(1e3*parseFloat(`0.${fraction}`)):0);range3(day,1,31);range3(hour,0,23);range3(minute,0,59);range3(second,0,60);const date2=new Date(timestamp);date2.setUTCFullYear(Number(year2));return date2}throw new TypeError(`Invalid RFC7231 date-time value ${value}.`)};splitHeader=value=>{const z2=value.length,values=[];let prevChar,withinQuotes=!1,anchor=0;for(let i2=0;i2{const z3=(v2=v2.trim()).length;if(z3<2)return v2;'"'===v2[0]&&'"'===v2[z3-1]&&(v2=v2.slice(1,z3-1));return v2.replace(/\\"/g,'"')}))};format=/^-?\d*(\.\d+)?$/;NumericValue=class _NumericValue{constructor(string,type){__publicField(this,"string");__publicField(this,"type");this.string=string;this.type=type;if(!format.test(string))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](object){if(!object||"object"!=typeof object)return!1;const _nv=object;return _NumericValue.prototype.isPrototypeOf(object)||"bigDecimal"===_nv.type&&format.test(_nv.string)}};SerdeContext=class{constructor(){__publicField(this,"serdeContext")}setSerdeContext(serdeContext){this.serdeContext=serdeContext}};HttpProtocol=class extends SerdeContext{constructor(options){super();__publicField(this,"options");this.options=options}getRequestType(){return HttpRequest}getResponseType(){return HttpResponse}setSerdeContext(serdeContext){this.serdeContext=serdeContext;this.serializer.setSerdeContext(serdeContext);this.deserializer.setSerdeContext(serdeContext);this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(serdeContext)}updateServiceEndpoint(request2,endpoint){if("url"in endpoint){request2.protocol=endpoint.url.protocol;request2.hostname=endpoint.url.hostname;request2.port=endpoint.url.port?Number(endpoint.url.port):void 0;request2.path=endpoint.url.pathname;request2.fragment=endpoint.url.hash||void 0;request2.username=endpoint.url.username||void 0;request2.password=endpoint.url.password||void 0;request2.query||(request2.query={});for(const[k2,v2]of endpoint.url.searchParams.entries())request2.query[k2]=v2;return request2}request2.protocol=endpoint.protocol;request2.hostname=endpoint.hostname;request2.port=endpoint.port?Number(endpoint.port):void 0;request2.path=endpoint.path;request2.query={...endpoint.query};return request2}setHostPrefix(request2,operationSchema,input){var _a7,_b5,_c3;if(null==(_a7=this.serdeContext)?void 0:_a7.disableHostPrefix)return;const inputNs=NormalizedSchema.of(operationSchema.input),opTraits=translateTraits(null!=(_b5=operationSchema.traits)?_b5:{});if(opTraits.endpoint){let hostPrefix=null==(_c3=opTraits.endpoint)?void 0:_c3[0];if("string"==typeof hostPrefix){const hostLabelInputs=[...inputNs.structIterator()].filter((([,member2])=>member2.getMergedTraits().hostLabel));for(const[name]of hostLabelInputs){const replacement=input[name];if("string"!=typeof replacement)throw new Error(`@smithy/core/schema - ${name} in input must be a string as hostLabel.`);hostPrefix=hostPrefix.replace(`{${name}}`,replacement)}request2.hostname=hostPrefix+request2.hostname}}}deserializeMetadata(output){var _a7,_b5;return{httpStatusCode:output.statusCode,requestId:null!=(_b5=null!=(_a7=output.headers["x-amzn-requestid"])?_a7: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"]}}async serializeEventStream({eventStream,requestSchema,initialRequest}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream,requestSchema,initialRequest})}async deserializeEventStream({response,responseSchema,initialResponseContainer}){return(await this.loadEventStreamCapability()).deserializeEventStream({response,responseSchema,initialResponseContainer})}async loadEventStreamCapability(){const{EventStreamSerde:EventStreamSerde2}=await Promise.resolve().then((()=>(init_event_streams(),event_streams_exports)));return new EventStreamSerde2({marshaller:this.getEventStreamMarshaller(),serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(schema,context2,response,arg4,arg5){return[]}getEventStreamMarshaller(){const context2=this.serdeContext;if(!context2.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return context2.eventStreamMarshaller}};HttpBindingProtocol=class extends HttpProtocol{async serializeRequest(operationSchema,_input,context2){var _a7;const input={...null!=_input?_input:{}},serializer=this.serializer,query3={},headers={},endpoint=await context2.endpoint(),ns=NormalizedSchema.of(null==operationSchema?void 0:operationSchema.input),schema=ns.getSchema();let payload,hasNonHttpBindingMember=!1;const request2=new HttpRequest({protocol:"",hostname:"",port:void 0,path:"",fragment:void 0,query:query3,headers,body:void 0});if(endpoint){this.updateServiceEndpoint(request2,endpoint);this.setHostPrefix(request2,operationSchema,input);const opTraits=translateTraits(operationSchema.traits);if(opTraits.http){request2.method=opTraits.http[0];const[path2,search]=opTraits.http[1].split("?");"/"==request2.path?request2.path=path2:request2.path+=path2;const traitSearchParams=new URLSearchParams(null!=search?search:"");Object.assign(query3,Object.fromEntries(traitSearchParams))}}for(const[memberName,memberNs]of ns.structIterator()){const memberTraits=null!=(_a7=memberNs.getMergedTraits())?_a7:{},inputMemberValue=input[memberName];if(null!=inputMemberValue||memberNs.isIdempotencyToken())if(memberTraits.httpPayload){if(memberNs.isStreaming())memberNs.isStructSchema()?input[memberName]&&(payload=await this.serializeEventStream({eventStream:input[memberName],requestSchema:ns})):payload=inputMemberValue;else{serializer.write(memberNs,inputMemberValue);payload=serializer.flush()}delete input[memberName]}else if(memberTraits.httpLabel){serializer.write(memberNs,inputMemberValue);const replacement=serializer.flush();request2.path.includes(`{${memberName}+}`)?request2.path=request2.path.replace(`{${memberName}+}`,replacement.split("/").map(extendedEncodeURIComponent).join("/")):request2.path.includes(`{${memberName}}`)&&(request2.path=request2.path.replace(`{${memberName}}`,extendedEncodeURIComponent(replacement)));delete input[memberName]}else if(memberTraits.httpHeader){serializer.write(memberNs,inputMemberValue);headers[memberTraits.httpHeader.toLowerCase()]=String(serializer.flush());delete input[memberName]}else if("string"==typeof memberTraits.httpPrefixHeaders){for(const[key3,val]of Object.entries(inputMemberValue)){const amalgam=memberTraits.httpPrefixHeaders+key3;serializer.write([memberNs.getValueSchema(),{httpHeader:amalgam}],val);headers[amalgam.toLowerCase()]=serializer.flush()}delete input[memberName]}else if(memberTraits.httpQuery||memberTraits.httpQueryParams){this.serializeQuery(memberNs,inputMemberValue,query3);delete input[memberName]}else hasNonHttpBindingMember=!0;else if(memberTraits.httpLabel&&(request2.path.includes(`{${memberName}+}`)||request2.path.includes(`{${memberName}}`)))throw new Error(`No value provided for input HTTP label: ${memberName}.`)}if(hasNonHttpBindingMember&&input){serializer.write(schema,input);payload=serializer.flush()}request2.headers=headers;request2.query=query3;request2.body=payload;return request2}serializeQuery(ns,data,query3){const serializer=this.serializer,traits=ns.getMergedTraits();if(traits.httpQueryParams){for(const[key3,val]of Object.entries(data))if(!(key3 in query3)){const valueSchema=ns.getValueSchema();Object.assign(valueSchema.getMergedTraits(),{...traits,httpQuery:key3,httpQueryParams:void 0});this.serializeQuery(valueSchema,val,query3)}}else if(ns.isListSchema()){const sparse=!!ns.getMergedTraits().sparse,buffer=[];for(const item of data){serializer.write([ns.getValueSchema(),traits],item);const serializable=serializer.flush();(sparse||void 0!==serializable)&&buffer.push(serializable)}query3[traits.httpQuery]=buffer}else{serializer.write([ns,traits],data);query3[traits.httpQuery]=serializer.flush()}}async deserializeResponse(operationSchema,context2,response){const deserializer=this.deserializer,ns=NormalizedSchema.of(operationSchema.output),dataObject={};if(response.statusCode>=300){const bytes=await collectBody(response.body,context2);bytes.byteLength>0&&Object.assign(dataObject,await deserializer.read(15,bytes));await this.handleError(operationSchema,context2,response,dataObject,this.deserializeMetadata(response));throw new Error("@smithy/core/protocols - HTTP Protocol error handler failed to throw.")}for(const header in response.headers){const value=response.headers[header];delete response.headers[header];response.headers[header.toLowerCase()]=value}const nonHttpBindingMembers=await this.deserializeHttpMessage(ns,context2,response,dataObject);if(nonHttpBindingMembers.length){const bytes=await collectBody(response.body,context2);if(bytes.byteLength>0){const dataFromBody=await deserializer.read(ns,bytes);for(const member2 of nonHttpBindingMembers)dataObject[member2]=dataFromBody[member2]}}else nonHttpBindingMembers.discardResponseBody&&await collectBody(response.body,context2);dataObject.$metadata=this.deserializeMetadata(response);return dataObject}async deserializeHttpMessage(schema,context2,response,arg4,arg5){let dataObject;dataObject=arg4 instanceof Set?arg5:arg4;let discardResponseBody=!0;const deserializer=this.deserializer,ns=NormalizedSchema.of(schema),nonHttpBindingMembers=[];for(const[memberName,memberSchema]of ns.structIterator()){const memberTraits=memberSchema.getMemberTraits();if(memberTraits.httpPayload){discardResponseBody=!1;if(memberSchema.isStreaming()){const isEventStream=memberSchema.isStructSchema();dataObject[memberName]=isEventStream?await this.deserializeEventStream({response,responseSchema:ns}):sdkStreamMixin(response.body)}else if(response.body){const bytes=await collectBody(response.body,context2);bytes.byteLength>0&&(dataObject[memberName]=await deserializer.read(memberSchema,bytes))}}else if(memberTraits.httpHeader){const key3=String(memberTraits.httpHeader).toLowerCase(),value=response.headers[key3];if(null!=value)if(memberSchema.isListSchema()){const headerListValueSchema=memberSchema.getValueSchema();headerListValueSchema.getMergedTraits().httpHeader=key3;let sections;sections=headerListValueSchema.isTimestampSchema()&&4===headerListValueSchema.getSchema()?splitEvery(value,",",2):splitHeader(value);const list=[];for(const section of sections)list.push(await deserializer.read(headerListValueSchema,section.trim()));dataObject[memberName]=list}else dataObject[memberName]=await deserializer.read(memberSchema,value)}else if(void 0!==memberTraits.httpPrefixHeaders){dataObject[memberName]={};for(const[header,value]of Object.entries(response.headers))if(header.startsWith(memberTraits.httpPrefixHeaders)){const valueSchema=memberSchema.getValueSchema();valueSchema.getMergedTraits().httpHeader=header;dataObject[memberName][header.slice(memberTraits.httpPrefixHeaders.length)]=await deserializer.read(valueSchema,value)}}else memberTraits.httpResponseCode?dataObject[memberName]=response.statusCode:nonHttpBindingMembers.push(memberName)}nonHttpBindingMembers.discardResponseBody=discardResponseBody;return nonHttpBindingMembers}};init_dist_es();FromStringShapeDeserializer=class extends SerdeContext{constructor(settings){super();__publicField(this,"settings");this.settings=settings}read(_schema,data){var _a7,_b5;const ns=NormalizedSchema.of(_schema);if(ns.isListSchema())return splitHeader(data).map((item=>this.read(ns.getValueSchema(),item)));if(ns.isBlobSchema())return(null!=(_b5=null==(_a7=this.serdeContext)?void 0:_a7.base64Decoder)?_b5:fromBase64)(data);if(ns.isTimestampSchema())switch(determineTimestampFormat(ns,this.settings)){case 5:return _parseRfc3339DateTimeWithOffset(data);case 6:return _parseRfc7231DateTime(data);case 7:return _parseEpochTimestamp(data);default:console.warn("Missing timestamp format, parsing value with Date constructor:",data);return new Date(data)}if(ns.isStringSchema()){const mediaType=ns.getMergedTraits().mediaType;let intermediateValue=data;if(mediaType){ns.getMergedTraits().httpHeader&&(intermediateValue=this.base64ToUtf8(intermediateValue));("application/json"===mediaType||mediaType.endsWith("+json"))&&(intermediateValue=LazyJsonString.from(intermediateValue));return intermediateValue}}return ns.isNumericSchema()?Number(data):ns.isBigIntegerSchema()?BigInt(data):ns.isBigDecimalSchema()?new NumericValue(data,"bigDecimal"):ns.isBooleanSchema()?"true"===String(data).toLowerCase():data}base64ToUtf8(base64String){var _a7,_b5,_c3,_d2;return(null!=(_b5=null==(_a7=this.serdeContext)?void 0:_a7.utf8Encoder)?_b5:toUtf8)((null!=(_d2=null==(_c3=this.serdeContext)?void 0:_c3.base64Decoder)?_d2:fromBase64)(base64String))}};init_dist_es();HttpInterceptingShapeDeserializer=class extends SerdeContext{constructor(codecDeserializer,codecSettings){super();__publicField(this,"codecDeserializer");__publicField(this,"stringDeserializer");this.codecDeserializer=codecDeserializer;this.stringDeserializer=new FromStringShapeDeserializer(codecSettings)}setSerdeContext(serdeContext){this.stringDeserializer.setSerdeContext(serdeContext);this.codecDeserializer.setSerdeContext(serdeContext);this.serdeContext=serdeContext}read(schema,data){var _a7,_b5,_c3,_d2;const ns=NormalizedSchema.of(schema),traits=ns.getMergedTraits(),toString=null!=(_b5=null==(_a7=this.serdeContext)?void 0:_a7.utf8Encoder)?_b5:toUtf8;if(traits.httpHeader||traits.httpResponseCode)return this.stringDeserializer.read(ns,toString(data));if(traits.httpPayload){if(ns.isBlobSchema()){const toBytes=null!=(_d2=null==(_c3=this.serdeContext)?void 0:_c3.utf8Decoder)?_d2:fromUtf8;return"string"==typeof data?toBytes(data):data}if(ns.isStringSchema())return"byteLength"in data?toString(data):data}return this.codecDeserializer.read(ns,data)}};ToStringShapeSerializer=class extends SerdeContext{constructor(settings){super();__publicField(this,"settings");__publicField(this,"stringBuffer","");this.settings=settings}write(schema,value){var _a7,_b5,_c3,_d2;const ns=NormalizedSchema.of(schema);switch(typeof value){case"object":if(null===value){this.stringBuffer="null";return}if(ns.isTimestampSchema()){if(!(value instanceof Date))throw new Error(`@smithy/core/protocols - received non-Date value ${value} when schema expected Date in ${ns.getName(!0)}`);switch(determineTimestampFormat(ns,this.settings)){case 5:this.stringBuffer=value.toISOString().replace(".000Z","Z");break;case 6:this.stringBuffer=dateToUtcString(value);break;case 7:this.stringBuffer=String(value.getTime()/1e3);break;default:console.warn("Missing timestamp format, using epoch seconds",value);this.stringBuffer=String(value.getTime()/1e3)}return}if(ns.isBlobSchema()&&"byteLength"in value){this.stringBuffer=(null!=(_b5=null==(_a7=this.serdeContext)?void 0:_a7.base64Encoder)?_b5:toBase64)(value);return}if(ns.isListSchema()&&Array.isArray(value)){let buffer="";for(const item of value){this.write([ns.getValueSchema(),ns.getMergedTraits()],item);const headerItem=this.flush();""!==buffer&&(buffer+=", ");buffer+=ns.getValueSchema().isTimestampSchema()?headerItem:quoteHeader(headerItem)}this.stringBuffer=buffer;return}this.stringBuffer=JSON.stringify(value,null,2);break;case"string":const mediaType=ns.getMergedTraits().mediaType;let intermediateValue=value;if(mediaType){("application/json"===mediaType||mediaType.endsWith("+json"))&&(intermediateValue=LazyJsonString.from(intermediateValue));if(ns.getMergedTraits().httpHeader){this.stringBuffer=(null!=(_d2=null==(_c3=this.serdeContext)?void 0:_c3.base64Encoder)?_d2:toBase64)(intermediateValue.toString());return}}this.stringBuffer=value;break;default:ns.isIdempotencyToken()?this.stringBuffer=v4():this.stringBuffer=String(value)}}flush(){const buffer=this.stringBuffer;this.stringBuffer="";return buffer}};HttpInterceptingShapeSerializer=class{constructor(codecSerializer,codecSettings,stringSerializer=new ToStringShapeSerializer(codecSettings)){__publicField(this,"codecSerializer");__publicField(this,"stringSerializer");__publicField(this,"buffer");this.codecSerializer=codecSerializer;this.stringSerializer=stringSerializer}setSerdeContext(serdeContext){this.codecSerializer.setSerdeContext(serdeContext);this.stringSerializer.setSerdeContext(serdeContext)}write(schema,value){const ns=NormalizedSchema.of(schema),traits=ns.getMergedTraits();if(!(traits.httpHeader||traits.httpLabel||traits.httpQuery))return this.codecSerializer.write(ns,value);this.stringSerializer.write(ns,value);this.buffer=this.stringSerializer.flush()}flush(){if(void 0!==this.buffer){const buffer=this.buffer;this.buffer=void 0;return buffer}return this.codecSerializer.flush()}};DefaultIdentityProviderConfig=class{constructor(config){__publicField(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=(()=>function isIdentityExpired2(identity){return 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";init_dist_es();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);init_dist_es();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"};init_dist_es();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){__publicField(this,"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 _a7,_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==(_a7=options.unhoistableHeaders)?void 0:_a7.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=time2=>toDate(time2).toISOString().replace(/\.\d{3}Z$/,"Z");toDate=time2=>"number"==typeof time2?new Date(1e3*time2):"string"==typeof time2?Number(time2)?new Date(1e3*Number(time2)):new Date(time2):time2;init_dist_es();SignatureV4Base=class{constructor({applyChecksum,credentials,region,service,sha256,uriEscapePath=!0}){__publicField(this,"service");__publicField(this,"regionProvider");__publicField(this,"credentialProvider");__publicField(this,"sha256");__publicField(this,"uriEscapePath");__publicField(this,"applyChecksum");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(";")}};init_dist_es();SignatureV4=class extends SignatureV4Base{constructor({applyChecksum,credentials,region,service,sha256,uriEscapePath=!0}){super({applyChecksum,credentials,region,service,sha256,uriEscapePath});__publicField(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){const isCredentialObject="object"==typeof inputCredentials&&null!==inputCredentials;resolvedCredentials=async options=>{const attributedCreds=await boundProvider(options);return!isCredentialObject||attributedCreds.$source&&0!==Object.keys(attributedCreds.$source).length?attributedCreds:setCredentialFeature(attributedCreds,"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})};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}`)};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 _a7;absoluteEntries.forEach((entry=>{toStack.add(entry.middleware,{...entry})}));relativeEntries.forEach((entry=>{toStack.addRelativeTo(entry.middleware,{...entry})}));null==(_a7=toStack.identifyOnResolve)||_a7.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 _a7;return entry2.name===alias||(null==(_a7=entry2.aliases)?void 0:_a7.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 _a7;return entry2.name===alias||(null==(_a7=entry2.aliases)?void 0:_a7.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 _a7,_b5;const cloned=cloneTo(constructStack());cloned.use(from);cloned.identifyOnResolve(identifyOnResolve||cloned.identifyOnResolve()||null!=(_b5=null==(_a7=from.identifyOnResolve)?void 0:_a7.call(from))&&_b5);return cloned},applyToStack:cloneTo,identify:()=>getMiddlewareList(!0).map((mw=>{var _a7;const step=null!=(_a7=mw.step)?_a7: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){__publicField(this,"config");__publicField(this,"middlewareStack",constructStack());__publicField(this,"initConfig");__publicField(this,"handlers");this.config=config;const{protocol,protocolSettings}=config;protocolSettings&&"function"==typeof protocol&&(config.protocol=new protocol(protocolSettings))}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 handlers3=this.handlers;if(handlers3.has(command.constructor))handler=handlers3.get(command.constructor);else{handler=command.resolveMiddleware(this.middlewareStack,this.config,options);handlers3.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 _a7,_b5,_c3;null==(_c3=null==(_b5=null==(_a7=this.config)?void 0:_a7.requestHandler)?void 0:_b5.destroy)||_c3.call(_b5);delete this.handlers}};SENSITIVE_STRING="***SensitiveInformation***";Command=class{constructor(){__publicField(this,"middlewareStack",constructStack());__publicField(this,"schema")}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(){__publicField(this,"_init",(()=>{}));__publicField(this,"_ep",{});__publicField(this,"_middlewareFn",(()=>[]));__publicField(this,"_commandName","");__publicField(this,"_clientName","");__publicField(this,"_additionalContext",{});__publicField(this,"_smithyContext",{});__publicField(this,"_inputFilterSensitiveLog");__publicField(this,"_outputFilterSensitiveLog");__publicField(this,"_serializer",null);__publicField(this,"_deserializer",null);__publicField(this,"_operationSchema")}init(cb2){this._init=cb2}ep(endpointParameterInstructions){this._ep=endpointParameterInstructions;return this}m(middlewareSupplier){this._middlewareFn=middlewareSupplier;return this}s(service,operation2,smithyContext={}){this._smithyContext={service,operation:operation2,...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}sc(operation2){this._operationSchema=operation2;this._smithyContext.operationSchema=operation2;return this}build(){const closure=this;let CommandRef;return CommandRef=class extends Command{constructor(...[input]){super();__publicField(this,"input");__publicField(this,"serialize",closure._serializer);__publicField(this,"deserialize",closure._deserializer);this.input=null!=input?input:{};closure._init(this);this.schema=closure._operationSchema}static getEndpointParameterInstructions(){return closure._ep}resolveMiddleware(stack2,configuration,options){var _a7,_b5,_c3,_d2;const op=closure._operationSchema,input=null!=(_a7=null==op?void 0:op[4])?_a7:null==op?void 0:op.input,output=null!=(_b5=null==op?void 0:op[5])?_b5:null==op?void 0:op.output;return this.resolveMiddlewareWithContext(stack2,configuration,options,{CommandCtor:CommandRef,middlewareFn:closure._middlewareFn,clientName:closure._clientName,commandName:closure._commandName,inputFilterSensitiveLog:null!=(_c3=closure._inputFilterSensitiveLog)?_c3:op?schemaLogFilter.bind(null,input):_=>_,outputFilterSensitiveLog:null!=(_d2=closure._outputFilterSensitiveLog)?_d2:op?schemaLogFilter.bind(null,output):_=>_,smithyContext:closure._smithyContext,additionalContext:closure._additionalContext})}}}};createAggregatedClient=(commands2,Client2,options)=>{for(const[command,CommandCtor]of Object.entries(commands2)){const 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}const{paginators:paginators2={},waiters:waiters2={}}=null!=options?options:{};for(const[paginatorName,paginatorFn]of Object.entries(paginators2))void 0===Client2.prototype[paginatorName]&&(Client2.prototype[paginatorName]=function(commandInput={},paginationConfiguration,...rest){return paginatorFn({...paginationConfiguration,client:this},commandInput,...rest)});for(const[waiterName,waiterFn]of Object.entries(waiters2))void 0===Client2.prototype[waiterName]&&(Client2.prototype[waiterName]=async function(commandInput={},waiterConfiguration,...rest){let config=waiterConfiguration;"number"==typeof waiterConfiguration&&(config={maxWaitTime:waiterConfiguration});return waiterFn({...config,client:this},commandInput,...rest)})};ServiceException=class _ServiceException extends Error{constructor(options){super(options.message);__publicField(this,"$fault");__publicField(this,"$response");__publicField(this,"$retryable");__publicField(this,"$metadata");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](instance){if(!instance)return!1;const candidate=instance;return this===_ServiceException?_ServiceException.isInstance(instance):!!_ServiceException.isInstance(instance)&&(candidate.name&&this.name?this.prototype.isPrototypeOf(instance)||candidate.name===this.name:this.prototype.isPrototypeOf(instance))}};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};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));resolveDefaultRuntimeConfig=config=>Object.assign(resolveChecksumRuntimeConfig2(config),resolveRetryRuntimeConfig(config));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};NoOpLogger=class{trace(){}debug(){}info(){}warn(){}error(){}};ProtocolLib=class{constructor(queryCompat=!1){__publicField(this,"queryCompat");this.queryCompat=queryCompat}resolveRestContentType(defaultContentType,inputSchema){const members=inputSchema.getMemberSchemas(),httpPayloadMember=Object.values(members).find((m3=>!!m3.getMergedTraits().httpPayload));return httpPayloadMember?httpPayloadMember.getMergedTraits().mediaType||(httpPayloadMember.isStringSchema()?"text/plain":httpPayloadMember.isBlobSchema()?"application/octet-stream":defaultContentType):!inputSchema.isUnitSchema()&&Object.values(members).find((m3=>{const{httpQuery,httpQueryParams,httpHeader,httpLabel,httpPrefixHeaders}=m3.getMergedTraits();return!(httpQuery||httpQueryParams||httpHeader||httpLabel||void 0!==httpPrefixHeaders)}))?defaultContentType:void 0}async getErrorSchemaOrThrowBaseException(errorIdentifier,defaultNamespace,response,dataObject,metadata,getErrorSchema){var _a7,_b5,_c3,_d2;let namespace=defaultNamespace,errorName=errorIdentifier;errorIdentifier.includes("#")&&([namespace,errorName]=errorIdentifier.split("#"));const errorMetadata={$metadata:metadata,$fault:response.statusCode<500?"client":"server"},registry=TypeRegistry.for(namespace);try{return{errorSchema:null!=(_a7=null==getErrorSchema?void 0:getErrorSchema(registry,errorName))?_a7:registry.getSchema(errorIdentifier),errorMetadata}}catch(e3){dataObject.message=null!=(_c3=null!=(_b5=dataObject.message)?_b5:dataObject.Message)?_c3:"UnknownError";const synthetic=TypeRegistry.for("smithy.ts.sdk.synthetic."+namespace),baseExceptionSchema=synthetic.getBaseException();if(baseExceptionSchema){const ErrorCtor=null!=(_d2=synthetic.getErrorCtor(baseExceptionSchema))?_d2:Error;throw this.decorateServiceException(Object.assign(new ErrorCtor({name:errorName}),errorMetadata),dataObject)}throw this.decorateServiceException(Object.assign(new Error(errorName),errorMetadata),dataObject)}}decorateServiceException(exception,additions={}){var _a7,_b5,_c3;if(this.queryCompat){const msg=null!=(_a7=exception.Message)?_a7:additions.Message,error=decorateServiceException(exception,additions);msg&&(error.message=msg);error.Error={...error.Error,Type:error.Error.Type,Code:error.Error.Code,Message:null!=(_c3=null!=(_b5=error.Error.message)?_b5:error.Error.Message)?_c3:msg};const reqId=error.$metadata.requestId;reqId&&(error.RequestId=reqId);return error}return decorateServiceException(exception,additions)}setQueryCompatError(output,response){var _a7;const queryErrorHeader=null==(_a7=response.headers)?void 0:_a7["x-amzn-query-error"];if(void 0!==output&&null!=queryErrorHeader){const[Code,Type]=queryErrorHeader.split(";"),entries2=Object.entries(output),Error2={Code,Type};Object.assign(output,Error2);for(const[k2,v2]of entries2)Error2["message"===k2?"Message":k2]=v2;delete Error2.__type;output.Error=Error2}}queryCompatOutput(queryCompatErrorData,errorData){queryCompatErrorData.Error&&(errorData.Error=queryCompatErrorData.Error);queryCompatErrorData.Type&&(errorData.Type=queryCompatErrorData.Type);queryCompatErrorData.Code&&(errorData.Code=queryCompatErrorData.Code)}findQueryCompatibleError(registry,errorName){try{return registry.getSchema(errorName)}catch(e3){return registry.find((schema=>{var _a7;return(null==(_a7=NormalizedSchema.of(schema).getMergedTraits().awsQueryError)?void 0:_a7[0])===errorName}))}}};SerdeContextConfig=class{constructor(){__publicField(this,"serdeContext")}setSerdeContext(serdeContext){this.serdeContext=serdeContext}};UnionSerde=class{constructor(from,to){__publicField(this,"from");__publicField(this,"to");__publicField(this,"keys");this.from=from;this.to=to;this.keys=new Set(Object.keys(this.from).filter((k2=>"__type"!==k2)))}mark(key3){this.keys.delete(key3)}hasUnknown(){return 1===this.keys.size&&0===Object.keys(this.to).length}writeUnknown(){if(this.hasUnknown()){const k2=this.keys.values().next().value,v2=this.from[k2];this.to.$unknown=[k2,v2]}}};init_dist_es();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("")}`:"/>")}};init_dist_es();XmlShapeDeserializer=class extends SerdeContextConfig{constructor(settings){super();__publicField(this,"settings");__publicField(this,"stringDeserializer");this.settings=settings;this.stringDeserializer=new FromStringShapeDeserializer(settings)}setSerdeContext(serdeContext){this.serdeContext=serdeContext;this.stringDeserializer.setSerdeContext(serdeContext)}read(schema,bytes,key3){var _a7,_b5;const ns=NormalizedSchema.of(schema),memberSchemas=ns.getMemberSchemas();if(ns.isStructSchema()&&ns.isMemberSchema()&&Object.values(memberSchemas).find((memberNs=>!!memberNs.getMemberTraits().eventPayload))){const output={},memberName=Object.keys(memberSchemas)[0];memberSchemas[memberName].isBlobSchema()?output[memberName]=bytes:output[memberName]=this.read(memberSchemas[memberName],bytes);return output}const xmlString=(null!=(_b5=null==(_a7=this.serdeContext)?void 0:_a7.utf8Encoder)?_b5:toUtf8)(bytes),parsedObject=this.parseXml(xmlString);return this.readSchema(schema,key3?parsedObject[key3]:parsedObject)}readSchema(_schema,value){var _a7,_b5,_c3,_d2,_e2,_f;const ns=NormalizedSchema.of(_schema);if(ns.isUnitSchema())return;const traits=ns.getMergedTraits();if(ns.isListSchema()&&!Array.isArray(value))return this.readSchema(ns,[value]);if(null==value)return value;if("object"==typeof value){const sparse=!!traits.sparse,flat=!!traits.xmlFlattened;if(ns.isListSchema()){const listValue=ns.getValueSchema(),buffer2=[],sourceKey=null!=(_a7=listValue.getMergedTraits().xmlName)?_a7:"member",source2=flat?value:(null!=(_b5=value[0])?_b5:value)[sourceKey],sourceArray=Array.isArray(source2)?source2:[source2];for(const v2 of sourceArray)(null!=v2||sparse)&&buffer2.push(this.readSchema(listValue,v2));return buffer2}const buffer={};if(ns.isMapSchema()){const keyNs=ns.getKeySchema(),memberNs=ns.getValueSchema();let entries2;entries2=flat?Array.isArray(value)?value:[value]:Array.isArray(value.entry)?value.entry:[value.entry];const keyProperty=null!=(_c3=keyNs.getMergedTraits().xmlName)?_c3:"key",valueProperty=null!=(_d2=memberNs.getMergedTraits().xmlName)?_d2:"value";for(const entry of entries2){const key3=entry[keyProperty],value2=entry[valueProperty];(null!=value2||sparse)&&(buffer[key3]=this.readSchema(memberNs,value2))}return buffer}if(ns.isStructSchema()){const union=ns.isUnionSchema();let unionSerde;union&&(unionSerde=new UnionSerde(value,buffer));for(const[memberName,memberSchema]of ns.structIterator()){const memberTraits=memberSchema.getMergedTraits(),xmlObjectKey=memberTraits.httpPayload?null!=(_f=memberTraits.xmlName)?_f:memberSchema.getName():null!=(_e2=memberSchema.getMemberTraits().xmlName)?_e2:memberName;union&&unionSerde.mark(xmlObjectKey);null!=value[xmlObjectKey]&&(buffer[memberName]=this.readSchema(memberSchema,value[xmlObjectKey]))}union&&unionSerde.writeUnknown();return buffer}if(ns.isDocumentSchema())return value;throw new Error(`@aws-sdk/core/protocols - xml deserializer unhandled schema type for ${ns.getName(!0)}`)}return ns.isListSchema()?[]:ns.isMapSchema()||ns.isStructSchema()?{}:this.stringDeserializer.read(ns,value)}parseXml(xml){if(xml.length){let parsedObj;try{parsedObj=parseXML(xml)}catch(e3){e3&&"object"==typeof e3&&Object.defineProperty(e3,"$responseBodyText",{value:xml});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{}}};loadRestXmlErrorCode=(output,data)=>{var _a7;return void 0!==(null==(_a7=null==data?void 0:data.Error)?void 0:_a7.Code)?data.Error.Code:void 0!==(null==data?void 0:data.Code)?data.Code:404==output.statusCode?"NotFound":void 0};XmlShapeSerializer=class extends SerdeContextConfig{constructor(settings){super();__publicField(this,"settings");__publicField(this,"stringBuffer");__publicField(this,"byteBuffer");__publicField(this,"buffer");this.settings=settings}write(schema,value){var _a7,_b5;const ns=NormalizedSchema.of(schema);if(ns.isStringSchema()&&"string"==typeof value)this.stringBuffer=value;else if(ns.isBlobSchema())this.byteBuffer="byteLength"in value?value:(null!=(_b5=null==(_a7=this.serdeContext)?void 0:_a7.base64Decoder)?_b5:fromBase64)(value);else{this.buffer=this.writeStruct(ns,value,void 0);const traits=ns.getMergedTraits();traits.httpPayload&&!traits.xmlName&&this.buffer.withName(ns.getName())}}flush(){var _a7;if(void 0!==this.byteBuffer){const bytes=this.byteBuffer;delete this.byteBuffer;return bytes}if(void 0!==this.stringBuffer){const str=this.stringBuffer;delete this.stringBuffer;return str}const buffer=this.buffer;this.settings.xmlNamespace&&((null==(_a7=null==buffer?void 0:buffer.attributes)?void 0:_a7.xmlns)||buffer.addAttribute("xmlns",this.settings.xmlNamespace));delete this.buffer;return buffer.toString()}writeStruct(ns,value,parentXmlns){var _a7,_b5,_c3,_d2;const traits=ns.getMergedTraits(),name=ns.isMemberSchema()&&!traits.httpPayload?null!=(_a7=ns.getMemberTraits().xmlName)?_a7:ns.getMemberName():null!=(_b5=traits.xmlName)?_b5:ns.getName();if(!name||!ns.isStructSchema())throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write struct with empty name or non-struct, schema=${ns.getName(!0)}.`);const structXmlNode=XmlNode.of(name),[xmlnsAttr,xmlns]=this.getXmlnsAttribute(ns,parentXmlns);for(const[memberName,memberSchema]of ns.structIterator()){const val=value[memberName];if(null!=val||memberSchema.isIdempotencyToken()){if(memberSchema.getMergedTraits().xmlAttribute){structXmlNode.addAttribute(null!=(_c3=memberSchema.getMergedTraits().xmlName)?_c3:memberName,this.writeSimple(memberSchema,val));continue}if(memberSchema.isListSchema())this.writeList(memberSchema,val,structXmlNode,xmlns);else if(memberSchema.isMapSchema())this.writeMap(memberSchema,val,structXmlNode,xmlns);else if(memberSchema.isStructSchema())structXmlNode.addChildNode(this.writeStruct(memberSchema,val,xmlns));else{const memberNode=XmlNode.of(null!=(_d2=memberSchema.getMergedTraits().xmlName)?_d2:memberSchema.getMemberName());this.writeSimpleInto(memberSchema,val,memberNode,xmlns);structXmlNode.addChildNode(memberNode)}}}const{$unknown}=value;if($unknown&&ns.isUnionSchema()&&Array.isArray($unknown)&&1===Object.keys(value).length){const[k2,v2]=$unknown,node=XmlNode.of(k2);if("string"!=typeof v2){if(!(value instanceof XmlNode||value instanceof XmlText))throw new Error("@aws-sdk - $unknown union member in XML requires value of type string, @aws-sdk/xml-builder::XmlNode or XmlText.");structXmlNode.addChildNode(value)}this.writeSimpleInto(0,v2,node,xmlns);structXmlNode.addChildNode(node)}xmlns&&structXmlNode.addAttribute(xmlnsAttr,xmlns);return structXmlNode}writeList(listMember,array,container,parentXmlns){var _a7;if(!listMember.isMemberSchema())throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member list: ${listMember.getName(!0)}`);const listTraits=listMember.getMergedTraits(),listValueSchema=listMember.getValueSchema(),listValueTraits=listValueSchema.getMergedTraits(),sparse=!!listValueTraits.sparse,flat=!!listTraits.xmlFlattened,[xmlnsAttr,xmlns]=this.getXmlnsAttribute(listMember,parentXmlns),writeItem=(container2,value)=>{var _a8,_b5,_c3,_d2;if(listValueSchema.isListSchema())this.writeList(listValueSchema,Array.isArray(value)?value:[value],container2,xmlns);else if(listValueSchema.isMapSchema())this.writeMap(listValueSchema,value,container2,xmlns);else if(listValueSchema.isStructSchema()){const struct=this.writeStruct(listValueSchema,value,xmlns);container2.addChildNode(struct.withName(flat?null!=(_a8=listTraits.xmlName)?_a8:listMember.getMemberName():null!=(_b5=listValueTraits.xmlName)?_b5:"member"))}else{const listItemNode=XmlNode.of(flat?null!=(_c3=listTraits.xmlName)?_c3:listMember.getMemberName():null!=(_d2=listValueTraits.xmlName)?_d2:"member");this.writeSimpleInto(listValueSchema,value,listItemNode,xmlns);container2.addChildNode(listItemNode)}};if(flat)for(const value of array)(sparse||null!=value)&&writeItem(container,value);else{const listNode=XmlNode.of(null!=(_a7=listTraits.xmlName)?_a7:listMember.getMemberName());xmlns&&listNode.addAttribute(xmlnsAttr,xmlns);for(const value of array)(sparse||null!=value)&&writeItem(listNode,value);container.addChildNode(listNode)}}writeMap(mapMember,map3,container,parentXmlns,containerIsMap=!1){var _a7,_b5,_c3,_d2;if(!mapMember.isMemberSchema())throw new Error(`@aws-sdk/core/protocols - xml serializer, cannot write non-member map: ${mapMember.getName(!0)}`);const mapTraits=mapMember.getMergedTraits(),mapKeySchema=mapMember.getKeySchema(),keyTag=null!=(_a7=mapKeySchema.getMergedTraits().xmlName)?_a7:"key",mapValueSchema=mapMember.getValueSchema(),mapValueTraits=mapValueSchema.getMergedTraits(),valueTag=null!=(_b5=mapValueTraits.xmlName)?_b5:"value",sparse=!!mapValueTraits.sparse,flat=!!mapTraits.xmlFlattened,[xmlnsAttr,xmlns]=this.getXmlnsAttribute(mapMember,parentXmlns),addKeyValue=(entry,key3,val)=>{const keyNode=XmlNode.of(keyTag,key3),[keyXmlnsAttr,keyXmlns]=this.getXmlnsAttribute(mapKeySchema,xmlns);keyXmlns&&keyNode.addAttribute(keyXmlnsAttr,keyXmlns);entry.addChildNode(keyNode);let valueNode=XmlNode.of(valueTag);mapValueSchema.isListSchema()?this.writeList(mapValueSchema,val,valueNode,xmlns):mapValueSchema.isMapSchema()?this.writeMap(mapValueSchema,val,valueNode,xmlns,!0):mapValueSchema.isStructSchema()?valueNode=this.writeStruct(mapValueSchema,val,xmlns):this.writeSimpleInto(mapValueSchema,val,valueNode,xmlns);entry.addChildNode(valueNode)};if(flat){for(const[key3,val]of Object.entries(map3))if(sparse||null!=val){const entry=XmlNode.of(null!=(_c3=mapTraits.xmlName)?_c3:mapMember.getMemberName());addKeyValue(entry,key3,val);container.addChildNode(entry)}}else{let mapNode;if(!containerIsMap){mapNode=XmlNode.of(null!=(_d2=mapTraits.xmlName)?_d2:mapMember.getMemberName());xmlns&&mapNode.addAttribute(xmlnsAttr,xmlns);container.addChildNode(mapNode)}for(const[key3,val]of Object.entries(map3))if(sparse||null!=val){const entry=XmlNode.of("entry");addKeyValue(entry,key3,val);(containerIsMap?container:mapNode).addChildNode(entry)}}}writeSimple(_schema,value){var _a7,_b5;if(null===value)throw new Error("@aws-sdk/core/protocols - (XML serializer) cannot write null value.");const ns=NormalizedSchema.of(_schema);let nodeContents=null;if(value&&"object"==typeof value)if(ns.isBlobSchema())nodeContents=(null!=(_b5=null==(_a7=this.serdeContext)?void 0:_a7.base64Encoder)?_b5:toBase64)(value);else{if(!(ns.isTimestampSchema()&&value instanceof Date)){if(ns.isBigDecimalSchema()&&value)return value instanceof NumericValue?value.string:String(value);throw ns.isMapSchema()||ns.isListSchema()?new Error("@aws-sdk/core/protocols - xml serializer, cannot call _write() on List/Map schema, call writeList or writeMap() instead."):new Error(`@aws-sdk/core/protocols - xml serializer, unhandled schema type for object value and schema: ${ns.getName(!0)}`)}switch(determineTimestampFormat(ns,this.settings)){case 5:nodeContents=value.toISOString().replace(".000Z","Z");break;case 6:nodeContents=dateToUtcString(value);break;case 7:nodeContents=String(value.getTime()/1e3);break;default:console.warn("Missing timestamp format, using http date",value);nodeContents=dateToUtcString(value);break}}(ns.isBooleanSchema()||ns.isNumericSchema()||ns.isBigIntegerSchema()||ns.isBigDecimalSchema())&&(nodeContents=String(value));ns.isStringSchema()&&(nodeContents=void 0===value&&ns.isIdempotencyToken()?v4():String(value));if(null===nodeContents)throw new Error(`Unhandled schema-value pair ${ns.getName(!0)}=${value}`);return nodeContents}writeSimpleInto(_schema,value,into,parentXmlns){const nodeContents=this.writeSimple(_schema,value),ns=NormalizedSchema.of(_schema),content=new XmlText(nodeContents),[xmlnsAttr,xmlns]=this.getXmlnsAttribute(ns,parentXmlns);xmlns&&into.addAttribute(xmlnsAttr,xmlns);into.addChildNode(content)}getXmlnsAttribute(ns,parentXmlns){var _a7;const traits=ns.getMergedTraits(),[prefix,xmlns]=null!=(_a7=traits.xmlNamespace)?_a7:[];return xmlns&&xmlns!==parentXmlns?[prefix?`xmlns:${prefix}`:"xmlns",xmlns]:[void 0,void 0]}};XmlCodec=class extends SerdeContextConfig{constructor(settings){super();__publicField(this,"settings");this.settings=settings}createSerializer(){const serializer=new XmlShapeSerializer(this.settings);serializer.setSerdeContext(this.serdeContext);return serializer}createDeserializer(){const deserializer=new XmlShapeDeserializer(this.settings);deserializer.setSerdeContext(this.serdeContext);return deserializer}};AwsRestXmlProtocol=class extends HttpBindingProtocol{constructor(options){super(options);__publicField(this,"codec");__publicField(this,"serializer");__publicField(this,"deserializer");__publicField(this,"mixin",new ProtocolLib);const settings={timestampFormat:{useTrait:!0,default:5},httpBindings:!0,xmlNamespace:options.xmlNamespace,serviceNamespace:options.defaultNamespace};this.codec=new XmlCodec(settings);this.serializer=new HttpInterceptingShapeSerializer(this.codec.createSerializer(),settings);this.deserializer=new HttpInterceptingShapeDeserializer(this.codec.createDeserializer(),settings)}getPayloadCodec(){return this.codec}getShapeId(){return"aws.protocols#restXml"}async serializeRequest(operationSchema,input,context2){const request2=await super.serializeRequest(operationSchema,input,context2),inputSchema=NormalizedSchema.of(operationSchema.input);if(!request2.headers["content-type"]){const contentType=this.mixin.resolveRestContentType(this.getDefaultContentType(),inputSchema);contentType&&(request2.headers["content-type"]=contentType)}"string"!=typeof request2.body||request2.headers["content-type"]!==this.getDefaultContentType()||request2.body.startsWith("'+request2.body);return request2}async deserializeResponse(operationSchema,context2,response){return super.deserializeResponse(operationSchema,context2,response)}async handleError(operationSchema,context2,response,dataObject,metadata){var _a7,_b5,_c3,_d2,_e2,_f,_g,_h2,_i2,_j,_k;const errorIdentifier=null!=(_a7=loadRestXmlErrorCode(response,dataObject))?_a7:"Unknown",{errorSchema,errorMetadata}=await this.mixin.getErrorSchemaOrThrowBaseException(errorIdentifier,this.options.defaultNamespace,response,dataObject,metadata),ns=NormalizedSchema.of(errorSchema),message=null!=(_g=null!=(_f=null!=(_e2=null!=(_d2=null==(_b5=dataObject.Error)?void 0:_b5.message)?_d2:null==(_c3=dataObject.Error)?void 0:_c3.Message)?_e2:dataObject.message)?_f:dataObject.Message)?_g:"Unknown",exception=new(null!=(_h2=TypeRegistry.for(errorSchema[1]).getErrorCtor(errorSchema))?_h2:Error)(message);await this.deserializeHttpMessage(errorSchema,context2,response,dataObject);const output={};for(const[name,member2]of ns.structIterator()){const target=null!=(_i2=member2.getMergedTraits().xmlName)?_i2:name,value=null!=(_k=null==(_j=dataObject.Error)?void 0:_j[target])?_k:dataObject[target];output[name]=this.codec.createDeserializer().readSchema(member2,value)}throw this.mixin.decorateServiceException(Object.assign(exception,errorMetadata,{$fault:ns.getMergedTraits().error,message},output),dataObject)}getDefaultContentType(){return"application/xml"}hasUnstructuredPayloadBinding(ns){for(const[,member2]of ns.structIterator())if(member2.getMergedTraits().httpPayload)return!(member2.isStructSchema()||member2.isMapSchema()||member2.isListSchema());return!1}};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"WHEN_SUPPORTED"===requestChecksumCalculation||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(t9){var s2,i2,n3,p2;for(i2=1,n3=arguments.length;i2(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(_a7){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,_a7,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&&(_a7=data_1.return)&&_a7.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]);generateCRC64NVMETable=()=>{const tables=new Array(8);for(let slice=0;slice<8;slice++){const table2=new Array(512);for(let i2=0;i2<256;i2++){let crc2=BigInt(i2);for(let j2=0;j2<8*(slice+1);j2++)crc2&BigInt("1")?crc2=crc2>>BigInt("1")^BigInt("0x9a6c9329ac4bc9b5"):crc2>>=BigInt("1");table2[2*i2]=Number(crc2>>BigInt("32")&BigInt("0xffffffff"));table2[2*i2+1]=Number(crc2&BigInt("0xffffffff"))}tables[slice]=new Uint32Array(table2)}return tables};ensureTablesInitialized=()=>{if(!CRC64_NVME_REVERSED_TABLE){CRC64_NVME_REVERSED_TABLE=generateCRC64NVMETable();[t0,t1,t2,t3,t4,t5,t6,t7]=CRC64_NVME_REVERSED_TABLE}};Crc64Nvme=class{constructor(){__publicField(this,"c1",0);__publicField(this,"c2",0);ensureTablesInitialized();this.reset()}update(data){const len=data.length;let i2=0,crc1=this.c1,crc2=this.c2;for(;i2+8<=len;){const idx0=(255&(crc2^data[i2++]))<<1,idx1=(255&(crc2>>>8^data[i2++]))<<1,idx2=(255&(crc2>>>16^data[i2++]))<<1,idx3=(255&(crc2>>>24^data[i2++]))<<1,idx4=(255&(crc1^data[i2++]))<<1,idx5=(255&(crc1>>>8^data[i2++]))<<1,idx6=(255&(crc1>>>16^data[i2++]))<<1,idx7=(255&(crc1>>>24^data[i2++]))<<1;crc1=t7[idx0]^t6[idx1]^t5[idx2]^t4[idx3]^t3[idx4]^t2[idx5]^t1[idx6]^t0[idx7];crc2=t7[idx0+1]^t6[idx1+1]^t5[idx2+1]^t4[idx3+1]^t3[idx4+1]^t2[idx5+1]^t1[idx6+1]^t0[idx7+1]}for(;i2>>8|(255&crc1)<<24)>>>0;crc1=crc1>>>8^t0[idx2];crc2^=t0[idx2+1];i2++}this.c1=crc1;this.c2=crc2}async digest(){const c12=4294967295^this.c1,c22=4294967295^this.c2;return new Uint8Array([c12>>>24,c12>>>16&255,c12>>>8&255,255&c12,c22>>>24,c22>>>16&255,c22>>>8&255,255&c22])}reset(){this.c1=4294967295;this.c2=4294967295}};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(_a7){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,_a7,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&&(_a7=data_1.return)&&_a7.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:return Crc64Nvme;case ChecksumAlgorithm.SHA1:return config.sha1;case ChecksumAlgorithm.SHA256:return config.sha256;default:throw new Error(`Unsupported checksum algorithm: ${checksumAlgorithm}`)}};init_dist_es();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]&&("WHEN_SUPPORTED"===requestChecksumCalculation||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)}}}try{return await next2({...args,request:{...request2,headers:updatedHeaders,body:updatedBody}})}catch(e3){if(e3 instanceof Error&&"InvalidChunkSizeError"===e3.name)try{e3.message.endsWith(".")||(e3.message+=".");e3.message+=" Set [requestStreamBufferSize=number e.g. 65_536] in client constructor to instruct AWS SDK to buffer your input stream."}catch(ignored){}throw e3}};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"WHEN_REQUIRED":setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED","a");break;case"WHEN_SUPPORTED":setFeature(context2,"FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED","Z");break}switch(responseChecksumValidation){case"WHEN_REQUIRED":setFeature(context2,"FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED","c");break;case"WHEN_SUPPORTED":setFeature(context2,"FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED","b");break}requestValidationModeMember&&!input[requestValidationModeMember]&&"WHEN_SUPPORTED"===responseChecksumValidation&&(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:"WHEN_SUPPORTED"),responseChecksumValidation:normalizeProvider(null!=responseChecksumValidation?responseChecksumValidation:"WHEN_SUPPORTED"),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 _a7,_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==(_a7=null==logger2?void 0:logger2.info)||_a7.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)}});recursionDetectionMiddlewareOptions={step:"build",tags:["RECURSION_DETECTION"],name:"recursionDetectionMiddleware",override:!0,priority:"low"};recursionDetectionMiddleware=()=>next2=>async args=>next2(args);getRecursionDetectionPlugin=options=>({applyToStack:clientStack=>{clientStack.add(recursionDetectionMiddleware(),recursionDetectionMiddlewareOptions)}});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 _a7;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==(_a7=context2.logger)||_a7.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(){var _a7,_b5,_c3,_d2;if((null!=(_b5=null==(_a7=identity.expiration)?void 0:_a7.getTime())?_b5:0){cache2.set(key3,new S3ExpressIdentityCacheEntry(Promise.resolve(id)))}))}return identity})):cache2.set(key3,new S3ExpressIdentityCacheEntry(this.getIdentity(key3))).identity}async getIdentity(key3){var _a7,_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==(_a7=session.Credentials)?void 0:_a7.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(SelectorType2){SelectorType2.ENV="env";SelectorType2.CONFIG="shared config entry"})(SelectorType||(SelectorType={}));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 _a7;const credentialsWithoutSessionToken=getCredentialsWithoutSessionToken(credentials);delete requestToSign.headers[SESSION_TOKEN_HEADER];requestToSign.headers[SESSION_TOKEN_QUERY_PARAM]=credentials.sessionToken;requestToSign.query=null!=(_a7=requestToSign.query)?_a7:{};requestToSign.query[SESSION_TOKEN_QUERY_PARAM]=credentials.sessionToken;setSingleOverride(this,credentialsWithoutSessionToken);return this.presign(requestToSign,options)}};s3ExpressMiddleware=options=>(next2,context2)=>async args=>{var _a7,_b5,_c3,_d2,_e2;if(context2.endpointV2){const endpoint=context2.endpointV2,isS3ExpressAuth="sigv4-s3express"===(null==(_c3=null==(_b5=null==(_a7=endpoint.properties)?void 0:_a7.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=getSmithyContext(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,expectContinueHeader}=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,expectContinueHeader:null!=expectContinueHeader?expectContinueHeader:2097152})};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("")&&(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}){__publicField(this,"capacity");__publicField(this,"data",new Map);__publicField(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 _a7;let buffer="";const{parameters}=this;if(0===parameters.length)return!1;for(const param of parameters){const val=String(null!=(_a7=endpointParams[param])?_a7:"");if(val.includes("|;"))return!1;buffer+=val+"|;"}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.lengthencodeURIComponent(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({...options.endpointParams,...options.referenceRecord}[ref]);evaluateExpression=(obj,keyName,options)=>{if("string"==typeof obj)return evaluateTemplate(obj,options);if(obj.fn)return group.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:group.evaluateExpression(arg,"arg",options))),fnSegments=fn.split(".");return fnSegments[0]in customEndpointFunctions&&null!=fnSegments[1]?customEndpointFunctions[fnSegments[0]][fnSegments[1]](...evaluatedArgs):endpointFunctions[fn](...evaluatedArgs)};group={evaluateExpression,callFunction};evaluateCondition=({assign:assign2,...fnArgs},options)=>{var _a7,_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==(_a7=options.logger)?void 0:_a7.debug)||_b5.call(_a7,`endpoints evaluateCondition: ${toDebugString(fnArgs)} = ${toDebugString(value)}`);return{result:""===value||!!value,...null!=assign2&&{toAssign:{name:assign2,value}}}};evaluateConditions=(conditions=[],options)=>{var _a7,_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==(_a7=options.logger)?void 0:_a7.debug)||_b5.call(_a7,`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}))})),{});getEndpointProperties=(properties,options)=>Object.entries(properties).reduce(((acc,[propertyKey,propertyVal])=>({...acc,[propertyKey]:group2.getEndpointProperty(propertyVal,options)})),{});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 group2.getEndpointProperties(property,options);case"boolean":return property;default:throw new EndpointError("Unexpected endpoint property type: "+typeof property)}};group2={getEndpointProperty,getEndpointProperties};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 _a7,_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==(_a7=options.logger)?void 0:_a7.debug)||_b5.call(_a7,`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}}))};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=group3.evaluateTreeRule(rule,options);if(endpointOrUndefined)return endpointOrUndefined}}throw new EndpointError("Rules evaluation failed")};evaluateTreeRule=(treeRule,options)=>{const{conditions,rules}=treeRule,{result,referenceRecord}=evaluateConditions(conditions,options);if(result)return group3.evaluateRules(rules,{...options,referenceRecord:{...options.referenceRecord,...referenceRecord}})};group3={evaluateRules,evaluateTreeRule};resolveEndpoint=(ruleSetObject,options)=>{var _a7,_b5,_c3,_d2,_e2;const{endpointParams,logger:logger2}=options,{parameters,rules}=ruleSetObject;null==(_b5=null==(_a7=options.logger)?void 0:_a7.debug)||_b5.call(_a7,`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-east-2":{description:"Asia Pacific (Taipei)"},"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-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws 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-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso 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:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{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-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}],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,partition3,service,region,accountId,...resourcePath]=segments;return"arn"!==arn||""===partition3||""===service||""===resourcePath.join(":")?null:{partition:partition3,service,region,accountId,resourceId:resourcePath.map((resource=>resource.split("/"))).flat()}},partition:value=>{const{partitions}=selectedPartitionsInfo;for(const partition3 of partitions){const{regions,outputs}=partition3;for(const[region,regionData]of Object.entries(regions))if(region===value)return{...outputs,...regionData}}for(const partition3 of partitions){const{regionRegex,outputs}=partition3;if(new RegExp(regionRegex).test(value))return{...outputs}}const DEFAULT_PARTITION=partitions.find((partition3=>"aws"===partition3.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;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}};ACCOUNT_ID_ENDPOINT_REGEX=/\d{12}\.ddb/;UA_NAME_ESCAPE_REGEX=/[^!$%&'*+\-.^_`|~\w]/g;UA_VALUE_ESCAPE_REGEX=/[^!$%&'*+\-.^_`|~\w#]/g;BYTE_LIMIT=1024;userAgentMiddleware=options=>(next2,context2)=>async args=>{var _a7,_b5,_c3,_d2;const{request:request2}=args;if(!HttpRequest.isInstance(request2))return next2(args);const{headers}=request2,userAgent=(null==(_a7=null==context2?void 0:context2.userAgent)?void 0:_a7.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 _a7;const name=userAgentPair[0].split("/").map((part=>part.replace(UA_NAME_ESCAPE_REGEX,"-"))).join("/"),version2=null==(_a7=userAgentPair[1])?void 0:_a7.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)}});validRegions=new Set;checkRegion=(region,check=isValidHostLabel)=>{if(validRegions.has(region)||check(region))validRegions.add(region);else{if("*"!==region)throw new Error(`Region not accepted: region="${region}" is not a valid hostname component.`);console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.')}};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()=>{const providedRegion="function"==typeof region?await region():region,realRegion=getRealRegion(providedRegion);checkRegion(realRegion);return realRegion},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,partition3,service,,,bucket]=bucketName.split(":"),isArn="arn"===arn&&bucketName.split(":").length>=6,isValidArn=Boolean(isArn&&partition3&&service&&bucket);if(isArn&&!isValidArn)throw new Error(`Invalid ARN: ${bucketName} was an invalid ARN.`);return isValidArn};createConfigValueProvider=(configKey,canonicalEndpointParamKey,config,isClientContextParam=!1)=>{const configProvider=async()=>{var _a7,_b5;let configValue;if(isClientContextParam){const clientContextParams=config.clientContextParams,nestedValue=null==clientContextParams?void 0:clientContextParams[configKey];configValue=null!=(_a7=null!=nestedValue?nestedValue:config[configKey])?_a7:config[canonicalEndpointParamKey]}else configValue=null!=(_b5=config[configKey])?_b5:config[canonicalEndpointParamKey];return"function"==typeof configValue?configValue():configValue};return"credentialScope"===configKey||"CredentialScope"===canonicalEndpointParamKey?async()=>{var _a7;const credentials="function"==typeof config.credentials?await config.credentials():config.credentials;return null!=(_a7=null==credentials?void 0:credentials.credentialScope)?_a7:null==credentials?void 0:credentials.CredentialScope}:"accountId"===configKey||"AccountId"===canonicalEndpointParamKey?async()=>{var _a7;const credentials="function"==typeof config.credentials?await config.credentials():config.credentials;return null!=(_a7=null==credentials?void 0:credentials.accountId)?_a7:null==credentials?void 0:credentials.AccountId}:"endpoint"===configKey||"endpoint"===canonicalEndpointParamKey?async()=>{if(!1===config.isCustomEndpoint)return;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=>{};toEndpointV1=endpoint=>"object"==typeof endpoint?"url"in endpoint?parseUrl(endpoint.url):endpoint:parseUrl(endpoint);getEndpointFromInstructions=async(commandInput,instructionsSupplier,clientConfig,context2)=>{if(!clientConfig.isCustomEndpoint){let endpointFromConfig;endpointFromConfig=clientConfig.serviceConfiguredEndpoint?await clientConfig.serviceConfiguredEndpoint():await getEndpointFromConfig(clientConfig.serviceId);if(endpointFromConfig){clientConfig.endpoint=()=>Promise.resolve(toEndpointV1(endpointFromConfig));clientConfig.isCustomEndpoint=!0}}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 _a7;const endpointParams={},instructions=(null==(_a7=null==instructionsSupplier?void 0:instructionsSupplier.getEndpointParameterInstructions)?void 0:_a7.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,"builtInParams"!==instruction.type)();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 _a7,_b5,_c3;config.isCustomEndpoint&&setFeature2(context2,"ENDPOINT_OVERRIDE","N");const endpoint=await getEndpointFromInstructions(args.input,{getEndpointParameterInstructions:()=>instructions},{...config},context2);context2.endpointV2=endpoint;context2.authSchemes=null==(_a7=endpoint.properties)?void 0:_a7.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=getSmithyContext(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 _a7;const tls=null==(_a7=input.tls)||_a7,{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;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"];NODEJS_NETWORK_ERROR_CODES=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND"];isRetryableByTrait=error=>void 0!==(null==error?void 0:error.$retryable);isClockSkewCorrectedError=error=>{var _a7;return null==(_a7=error.$metadata)?void 0:_a7.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 _a7,_b5;return 429===(null==(_a7=error.$metadata)?void 0:_a7.httpStatusCode)||THROTTLING_ERROR_CODES.includes(error.name)||1==(null==(_b5=error.$retryable)?void 0:_b5.throttling)};isTransientError=(error,depth=0)=>{var _a7;return isRetryableByTrait(error)||isClockSkewCorrectedError(error)||TRANSIENT_ERROR_CODES.includes(error.name)||NODEJS_TIMEOUT_ERROR_CODES.includes((null==error?void 0:error.code)||"")||NODEJS_NETWORK_ERROR_CODES.includes((null==error?void 0:error.code)||"")||TRANSIENT_ERROR_STATUS_CODES.includes((null==(_a7=error.$metadata)?void 0:_a7.httpStatusCode)||0)||isBrowserNetworkError(error)||void 0!==error.cause&&depth<=10&&isTransientError(error.cause,depth+1)};isServerError=error=>{var _a7;if(void 0!==(null==(_a7=error.$metadata)?void 0:_a7.httpStatusCode)){const statusCode=error.$metadata.httpStatusCode;return 500<=statusCode&&statusCode<=599&&!isTransientError(error)}return!1};_DefaultRateLimiter=class _DefaultRateLimiter{constructor(options){__publicField(this,"beta");__publicField(this,"minCapacity");__publicField(this,"minFillRate");__publicField(this,"scaleConstant");__publicField(this,"smooth");__publicField(this,"currentCapacity",0);__publicField(this,"enabled",!1);__publicField(this,"lastMaxRate",0);__publicField(this,"measuredTxRate",0);__publicField(this,"requestCount",0);__publicField(this,"fillRate");__publicField(this,"lastThrottleTime");__publicField(this,"lastTimestamp",0);__publicField(this,"lastTxRateBucket");__publicField(this,"maxCapacity");__publicField(this,"timeWindow",0);var _a7,_b5,_c3,_d2,_e2;this.beta=null!=(_a7=null==options?void 0:options.beta)?_a7:.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 t9=this.getCurrentTimeInSeconds(),timeBucket=Math.floor(2*t9)/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))}};__publicField(_DefaultRateLimiter,"setTimeoutFn",setTimeout);DefaultRateLimiter=_DefaultRateLimiter;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){__publicField(this,"maxAttempts");__publicField(this,"mode",RETRY_MODES.STANDARD);__publicField(this,"capacity",500);__publicField(this,"retryBackoffStrategy",getDefaultRetryBackoffStrategy());__publicField(this,"maxAttemptsProvider");this.maxAttempts=maxAttempts;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 _a7;this.capacity=Math.max(500,this.capacity+(null!=(_a7=token.getRetryCost())?_a7: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=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){__publicField(this,"maxAttemptsProvider");__publicField(this,"rateLimiter");__publicField(this,"standardRetryStrategy");__publicField(this,"mode",RETRY_MODES.ADAPTIVE);this.maxAttemptsProvider=maxAttemptsProvider;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);__publicField(this,"computeNextBackoffDelay");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}};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 _a7;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());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==(_a7=context2.logger instanceof NoOpLogger?console:context2.logger)||_a7.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}static sigv4aDependency(){return"none"}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}};selectedPartitionsInfo2={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-east-2":{description:"Asia Pacific (Taipei)"},"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-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws 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-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso 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:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{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-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}],version:"1.1"};awsEndpointFunctions2={isVirtualHostableS3Bucket:isVirtualHostableS3Bucket2=(value,allowSubDomains=!1)=>{if(allowSubDomains){for(const label2 of value.split("."))if(!isVirtualHostableS3Bucket2(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,partition3,service,region,accountId,...resourcePath]=segments;return"arn"!==arn||""===partition3||""===service||""===resourcePath.join(":")?null:{partition:partition3,service,region,accountId,resourceId:resourcePath.map((resource=>resource.split("/"))).flat()}},partition:value=>{const{partitions}=selectedPartitionsInfo2;for(const partition3 of partitions){const{regions,outputs}=partition3;for(const[region,regionData]of Object.entries(regions))if(region===value)return{...outputs,...regionData}}for(const partition3 of partitions){const{regionRegex,outputs}=partition3;if(new RegExp(regionRegex).test(value))return{...outputs}}const DEFAULT_PARTITION=partitions.find((partition3=>"aws"===partition3.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=awsEndpointFunctions2;cs="required",ct="type",cu="rules",cv="conditions",cw="fn",cx="argv",cy="ref",cz="assign",cA="url",cB="properties",cC="backend",cD="authSchemes",cE="disableDoubleEncoding",cF="signingName",cG="signingRegion",cH="headers",cI="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",p="aws.isVirtualHostableS3Bucket",q="{url#scheme}://{Bucket}.{url#authority}{url#path}",r3="not",s="accessPointSuffix",t8="{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={[cs]:!1,[ct]:"string"},U={[cs]:!0,default:!1,[ct]:"boolean"},V={[cs]:!1,[ct]:"boolean"},W2={[cw]:e2,[cx]:[{[cy]:"Accelerate"},!0]},X={[cw]:e2,[cx]:[{[cy]:"UseFIPS"},!0]},Y={[cw]:e2,[cx]:[{[cy]:"UseDualStack"},!0]},Z={[cw]:d3,[cx]:[{[cy]:"Endpoint"}]},aa={[cw]:g,[cx]:[{[cy]:"Region"}],[cz]:"partitionResult"},ab={[cw]:h,[cx]:[{[cw]:i,[cx]:[{[cy]:"partitionResult"},j]},"aws-cn"]},ac={[cw]:d3,[cx]:[{[cy]:"Bucket"}]},ad={[cy]:"Bucket"},ae={[cv]:[W2],[f]:"S3Express does not support S3 Accelerate.",[ct]:f},af={[cv]:[Z,{[cw]:m2,[cx]:[{[cy]:"Endpoint"}],[cz]:"url"}],[cu]:[{[cv]:[{[cw]:d3,[cx]:[{[cy]:"DisableS3ExpressSessionAuth"}]},{[cw]:e2,[cx]:[{[cy]:"DisableS3ExpressSessionAuth"},!0]}],[cu]:[{[cv]:[{[cw]:e2,[cx]:[{[cw]:i,[cx]:[{[cy]:"url"},"isIp"]},!0]}],[cu]:[{[cv]:[{[cw]:"uriEncode",[cx]:[ad],[cz]:"uri_encoded_bucket"}],[cu]:[{[n2]:{[cA]:"{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2}],[ct]:o}],[ct]:o},{[cv]:[{[cw]:p,[cx]:[ad,!1]}],[cu]:[{[n2]:{[cA]:q,[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2}],[ct]:o},{[f]:"S3Express bucket name is not a valid virtual hostable name.",[ct]:f}],[ct]:o},{[cv]:[{[cw]:e2,[cx]:[{[cw]:i,[cx]:[{[cy]:"url"},"isIp"]},!0]}],[cu]:[{[cv]:[{[cw]:"uriEncode",[cx]:[ad],[cz]:"uri_encoded_bucket"}],[cu]:[{[n2]:{[cA]:"{url#scheme}://{url#authority}/{uri_encoded_bucket}{url#path}",[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4-s3express",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2}],[ct]:o}],[ct]:o},{[cv]:[{[cw]:p,[cx]:[ad,!1]}],[cu]:[{[n2]:{[cA]:q,[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4-s3express",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2}],[ct]:o},{[f]:"S3Express bucket name is not a valid virtual hostable name.",[ct]:f}],[ct]:o},ag={[cw]:m2,[cx]:[{[cy]:"Endpoint"}],[cz]:"url"},ah={[cw]:e2,[cx]:[{[cw]:i,[cx]:[{[cy]:"url"},"isIp"]},!0]},ai={[cy]:"url"},aj={[cw]:"uriEncode",[cx]:[ad],[cz]:"uri_encoded_bucket"},ak={[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:"s3express",[cG]:"{Region}"}]},al={},am={[cw]:p,[cx]:[ad,!1]},an={[f]:"S3Express bucket name is not a valid virtual hostable name.",[ct]:f},ao={[cw]:d3,[cx]:[{[cy]:"UseS3ExpressControlEndpoint"}]},ap={[cw]:e2,[cx]:[{[cy]:"UseS3ExpressControlEndpoint"},!0]},aq={[cw]:r3,[cx]:[Z]},ar={[cw]:e2,[cx]:[{[cy]:"UseDualStack"},!1]},as={[cw]:e2,[cx]:[{[cy]:"UseFIPS"},!1]},at={[f]:"Unrecognized S3Express bucket name format.",[ct]:f},au={[cw]:r3,[cx]:[ac]},av={[cy]:u},aw={[cv]:[aq],[f]:"Expected a endpoint to be specified but no endpoint was found",[ct]:f},ax={[cD]:[{[cE]:!0,[j]:z,[cF]:A,[cI]:["*"]},{[cE]:!0,[j]:"sigv4",[cF]:A,[cG]:"{Region}"}]},ay={[cw]:e2,[cx]:[{[cy]:"ForcePathStyle"},!1]},az={[cy]:"ForcePathStyle"},aA={[cw]:e2,[cx]:[{[cy]:"Accelerate"},!1]},aB={[cw]:h,[cx]:[{[cy]:"Region"},"aws-global"]},aC={[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:B,[cG]:"us-east-1"}]},aD={[cw]:r3,[cx]:[aB]},aE={[cw]:e2,[cx]:[{[cy]:"UseGlobalEndpoint"},!0]},aF={[cA]:"https://{Bucket}.s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:{[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:B,[cG]:"{Region}"}]},[cH]:{}},aG={[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:B,[cG]:"{Region}"}]},aH={[cw]:e2,[cx]:[{[cy]:"UseGlobalEndpoint"},!1]},aI={[cA]:"https://{Bucket}.s3-fips.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},aJ={[cA]:"https://{Bucket}.s3-accelerate.dualstack.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},aK={[cA]:"https://{Bucket}.s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},aL={[cw]:e2,[cx]:[{[cw]:i,[cx]:[ai,"isIp"]},!1]},aM={[cA]:C2,[cB]:aG,[cH]:{}},aN={[cA]:q,[cB]:aG,[cH]:{}},aO={[n2]:aN,[ct]:n2},aP={[cA]:D,[cB]:aG,[cH]:{}},aQ={[cA]:"https://{Bucket}.s3.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},aR={[f]:"Invalid region: region was not a valid DNS name.",[ct]:f},aS={[cy]:G2},aT={[cy]:H},aU={[cw]:i,[cx]:[aS,"service"]},aV={[cy]:L3},aW={[cv]:[Y],[f]:"S3 Object Lambda does not support Dual-stack",[ct]:f},aX={[cv]:[W2],[f]:"S3 Object Lambda does not support S3 Accelerate",[ct]:f},aY={[cv]:[{[cw]:d3,[cx]:[{[cy]:"DisableAccessPoints"}]},{[cw]:e2,[cx]:[{[cy]:"DisableAccessPoints"},!0]}],[f]:"Access points are not supported for this operation",[ct]:f},aZ={[cv]:[{[cw]:d3,[cx]:[{[cy]:"UseArnRegion"}]},{[cw]:e2,[cx]:[{[cy]:"UseArnRegion"},!1]},{[cw]:r3,[cx]:[{[cw]:h,[cx]:[{[cw]:i,[cx]:[aS,"region"]},"{Region}"]}]}],[f]:"Invalid configuration: region from ARN `{bucketArn#region}` does not match client region `{Region}` and UseArnRegion is `false`",[ct]:f},ba={[cw]:i,[cx]:[{[cy]:"bucketPartition"},j]},bb={[cw]:i,[cx]:[aS,"accountId"]},bc={[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:J,[cG]:"{bucketArn#region}"}]},bd={[f]:"Invalid ARN: The access point name may only contain a-z, A-Z, 0-9 and `-`. Found: `{accessPointName}`",[ct]:f},be={[f]:"Invalid ARN: The account id may only contain a-z, A-Z, 0-9 and `-`. Found: `{bucketArn#accountId}`",[ct]:f},bf={[f]:"Invalid region in ARN: `{bucketArn#region}` (invalid DNS name)",[ct]:f},bg={[f]:"Client was configured for partition `{partitionResult#name}` but ARN (`{Bucket}`) has `{bucketPartition#name}`",[ct]:f},bh={[f]:"Invalid ARN: The ARN may only contain a single resource component after `accesspoint`.",[ct]:f},bi={[f]:"Invalid ARN: Expected a resource of the format `accesspoint:` but no name was provided",[ct]:f},bj={[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:B,[cG]:"{bucketArn#region}"}]},bk={[cD]:[{[cE]:!0,[j]:z,[cF]:A,[cI]:["*"]},{[cE]:!0,[j]:"sigv4",[cF]:A,[cG]:"{bucketArn#region}"}]},bl={[cw]:F,[cx]:[ad]},bm={[cA]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aG,[cH]:{}},bn={[cA]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aG,[cH]:{}},bo={[cA]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aG,[cH]:{}},bp={[cA]:Q,[cB]:aG,[cH]:{}},bq={[cA]:"https://s3.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aG,[cH]:{}},br={[cy]:"UseObjectLambdaEndpoint"},bs={[cD]:[{[cE]:!0,[j]:"sigv4",[cF]:J,[cG]:"{Region}"}]},bt={[cA]:"https://s3-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},bu={[cA]:"https://s3-fips.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},bv={[cA]:"https://s3.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},bw={[cA]:t8,[cB]:aG,[cH]:{}},bx={[cA]:"https://s3.{Region}.{partitionResult#dnsSuffix}",[cB]:aG,[cH]:{}},by=[{[cy]:"Region"}],bz=[{[cy]:"Endpoint"}],bA=[ad],bB=[W2],bC=[Z,ag],bD=[{[cw]:d3,[cx]:[{[cy]:"DisableS3ExpressSessionAuth"}]},{[cw]:e2,[cx]:[{[cy]:"DisableS3ExpressSessionAuth"},!0]}],bE=[aj],bF=[am],bG=[aa],bH=[X,Y],bI=[X,ar],bJ=[as,Y],bK=[as,ar],bL=[{[cw]:k,[cx]:[ad,6,14,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,14,16,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bM=[{[cv]:[X,Y],[n2]:{[cA]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:{}},[ct]:n2},{[cv]:bI,[n2]:{[cA]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:{}},[ct]:n2},{[cv]:bJ,[n2]:{[cA]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:{}},[ct]:n2},{[cv]:bK,[n2]:{[cA]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:{}},[ct]:n2}],bN=[{[cw]:k,[cx]:[ad,6,15,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,15,17,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bO=[{[cw]:k,[cx]:[ad,6,19,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,19,21,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bP=[{[cw]:k,[cx]:[ad,6,20,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,20,22,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bQ=[{[cw]:k,[cx]:[ad,6,26,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,26,28,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bR=[{[cv]:[X,Y],[n2]:{[cA]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4-s3express",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2},{[cv]:bI,[n2]:{[cA]:"https://{Bucket}.s3express-fips-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4-s3express",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2},{[cv]:bJ,[n2]:{[cA]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4-s3express",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2},{[cv]:bK,[n2]:{[cA]:"https://{Bucket}.s3express-{s3expressAvailabilityZoneId}.{Region}.{partitionResult#dnsSuffix}",[cB]:{[cC]:"S3Express",[cD]:[{[cE]:!0,[j]:"sigv4-s3express",[cF]:"s3express",[cG]:"{Region}"}]},[cH]:{}},[ct]:n2}],bS=[ad,0,7,!0],bT=[{[cw]:k,[cx]:[ad,7,15,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,15,17,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bU=[{[cw]:k,[cx]:[ad,7,16,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,16,18,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bV=[{[cw]:k,[cx]:[ad,7,20,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,20,22,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bW=[{[cw]:k,[cx]:[ad,7,21,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,21,23,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bX=[{[cw]:k,[cx]:[ad,7,27,!0],[cz]:"s3expressAvailabilityZoneId"},{[cw]:k,[cx]:[ad,27,29,!0],[cz]:"s3expressAvailabilityZoneDelim"},{[cw]:h,[cx]:[{[cy]:"s3expressAvailabilityZoneDelim"},"--"]}],bY=[ac],bZ=[{[cw]:y,[cx]:[{[cy]:x},!1]}],ca=[{[cw]:h,[cx]:[{[cy]:v},"beta"]}],cb=["*"],cc=[{[cw]:y,[cx]:[{[cy]:"Region"},!1]}],cd=[{[cw]:h,[cx]:[{[cy]:"Region"},"us-east-1"]}],ce=[{[cw]:h,[cx]:[aT,K]}],cf=[{[cw]:i,[cx]:[aS,"resourceId[1]"],[cz]:L3},{[cw]:r3,[cx]:[{[cw]:h,[cx]:[aV,""]}]}],cg=[aS,"resourceId[1]"],ch=[Y],ci=[{[cw]:r3,[cx]:[{[cw]:h,[cx]:[{[cw]:i,[cx]:[aS,"region"]},""]}]}],cj=[{[cw]:r3,[cx]:[{[cw]:d3,[cx]:[{[cw]:i,[cx]:[aS,"resourceId[2]"]}]}]}],ck=[aS,"resourceId[2]"],cl=[{[cw]:g,[cx]:[{[cw]:i,[cx]:[aS,"region"]}],[cz]:"bucketPartition"}],cm=[{[cw]:h,[cx]:[ba,{[cw]:i,[cx]:[{[cy]:"partitionResult"},j]}]}],cn=[{[cw]:y,[cx]:[{[cw]:i,[cx]:[aS,"region"]},!0]}],co=[{[cw]:y,[cx]:[bb,!1]}],cp=[{[cw]:y,[cx]:[aV,!1]}],cq=[X],cr2=[{[cw]:y,[cx]:[{[cy]:"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},[cu]:[{[cv]:[{[cw]:d3,[cx]:by}],[cu]:[{[cv]:[W2,X],error:"Accelerate cannot be used with FIPS",[ct]:f},{[cv]:[Y,Z],error:"Cannot set dual-stack in combination with a custom endpoint.",[ct]:f},{[cv]:[Z,X],error:"A custom endpoint cannot be combined with FIPS",[ct]:f},{[cv]:[Z,W2],error:"A custom endpoint cannot be combined with S3 Accelerate",[ct]:f},{[cv]:[X,aa,ab],error:"Partition does not support FIPS",[ct]:f},{[cv]:[ac,{[cw]:k,[cx]:[ad,0,6,c],[cz]:l},{[cw]:h,[cx]:[{[cy]:l},"--x-s3"]}],[cu]:[ae,af,{[cv]:[ao,ap],[cu]:[{[cv]:bG,[cu]:[{[cv]:[aj,aq],[cu]:[{[cv]:bH,endpoint:{[cA]:"https://s3express-control-fips.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bI,endpoint:{[cA]:"https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bJ,endpoint:{[cA]:"https://s3express-control.dualstack.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bK,endpoint:{[cA]:"https://s3express-control.{Region}.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:ak,[cH]:al},[ct]:n2}],[ct]:o}],[ct]:o}],[ct]:o},{[cv]:bF,[cu]:[{[cv]:bG,[cu]:[{[cv]:bD,[cu]:[{[cv]:bL,[cu]:bM,[ct]:o},{[cv]:bN,[cu]:bM,[ct]:o},{[cv]:bO,[cu]:bM,[ct]:o},{[cv]:bP,[cu]:bM,[ct]:o},{[cv]:bQ,[cu]:bM,[ct]:o},at],[ct]:o},{[cv]:bL,[cu]:bR,[ct]:o},{[cv]:bN,[cu]:bR,[ct]:o},{[cv]:bO,[cu]:bR,[ct]:o},{[cv]:bP,[cu]:bR,[ct]:o},{[cv]:bQ,[cu]:bR,[ct]:o},at],[ct]:o}],[ct]:o},an],[ct]:o},{[cv]:[ac,{[cw]:k,[cx]:bS,[cz]:s},{[cw]:h,[cx]:[{[cy]:s},"--xa-s3"]}],[cu]:[ae,af,{[cv]:bF,[cu]:[{[cv]:bG,[cu]:[{[cv]:bD,[cu]:[{[cv]:bT,[cu]:bM,[ct]:o},{[cv]:bU,[cu]:bM,[ct]:o},{[cv]:bV,[cu]:bM,[ct]:o},{[cv]:bW,[cu]:bM,[ct]:o},{[cv]:bX,[cu]:bM,[ct]:o},at],[ct]:o},{[cv]:bT,[cu]:bR,[ct]:o},{[cv]:bU,[cu]:bR,[ct]:o},{[cv]:bV,[cu]:bR,[ct]:o},{[cv]:bW,[cu]:bR,[ct]:o},{[cv]:bX,[cu]:bR,[ct]:o},at],[ct]:o}],[ct]:o},an],[ct]:o},{[cv]:[au,ao,ap],[cu]:[{[cv]:bG,[cu]:[{[cv]:bC,endpoint:{[cA]:t8,[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bH,endpoint:{[cA]:"https://s3express-control-fips.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bI,endpoint:{[cA]:"https://s3express-control-fips.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bJ,endpoint:{[cA]:"https://s3express-control.dualstack.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:al},[ct]:n2},{[cv]:bK,endpoint:{[cA]:"https://s3express-control.{Region}.{partitionResult#dnsSuffix}",[cB]:ak,[cH]:al},[ct]:n2}],[ct]:o}],[ct]:o},{[cv]:[ac,{[cw]:k,[cx]:[ad,49,50,c],[cz]:u},{[cw]:k,[cx]:[ad,8,12,c],[cz]:v},{[cw]:k,[cx]:bS,[cz]:w},{[cw]:k,[cx]:[ad,32,49,c],[cz]:x},{[cw]:g,[cx]:by,[cz]:"regionPartition"},{[cw]:h,[cx]:[{[cy]:w},"--op-s3"]}],[cu]:[{[cv]:bZ,[cu]:[{[cv]:bF,[cu]:[{[cv]:[{[cw]:h,[cx]:[av,"e"]}],[cu]:[{[cv]:ca,[cu]:[aw,{[cv]:bC,endpoint:{[cA]:"https://{Bucket}.ec2.{url#authority}",[cB]:ax,[cH]:al},[ct]:n2}],[ct]:o},{endpoint:{[cA]:"https://{Bucket}.ec2.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[cB]:ax,[cH]:al},[ct]:n2}],[ct]:o},{[cv]:[{[cw]:h,[cx]:[av,"o"]}],[cu]:[{[cv]:ca,[cu]:[aw,{[cv]:bC,endpoint:{[cA]:"https://{Bucket}.op-{outpostId}.{url#authority}",[cB]:ax,[cH]:al},[ct]:n2}],[ct]:o},{endpoint:{[cA]:"https://{Bucket}.op-{outpostId}.s3-outposts.{Region}.{regionPartition#dnsSuffix}",[cB]:ax,[cH]:al},[ct]:n2}],[ct]:o},{error:'Unrecognized hardware type: "Expected hardware type o or e but got {hardwareType}"',[ct]:f}],[ct]:o},{error:"Invalid Outposts Bucket alias - it must be a valid bucket name.",[ct]:f}],[ct]:o},{error:"Invalid ARN: The outpost Id must only contain a-z, A-Z, 0-9 and `-`.",[ct]:f}],[ct]:o},{[cv]:bY,[cu]:[{[cv]:[Z,{[cw]:r3,[cx]:[{[cw]:d3,[cx]:[{[cw]:m2,[cx]:bz}]}]}],error:"Custom endpoint `{Endpoint}` was not a valid URI",[ct]:f},{[cv]:[ay,am],[cu]:[{[cv]:bG,[cu]:[{[cv]:cc,[cu]:[{[cv]:[W2,ab],error:"S3 Accelerate cannot be used in this region",[ct]:f},{[cv]:[Y,X,aA,aq,aB],endpoint:{[cA]:"https://{Bucket}.s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[Y,X,aA,aq,aD,aE],[cu]:[{endpoint:aF,[ct]:n2}],[ct]:o},{[cv]:[Y,X,aA,aq,aD,aH],endpoint:aF,[ct]:n2},{[cv]:[ar,X,aA,aq,aB],endpoint:{[cA]:"https://{Bucket}.s3-fips.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,X,aA,aq,aD,aE],[cu]:[{endpoint:aI,[ct]:n2}],[ct]:o},{[cv]:[ar,X,aA,aq,aD,aH],endpoint:aI,[ct]:n2},{[cv]:[Y,as,W2,aq,aB],endpoint:{[cA]:"https://{Bucket}.s3-accelerate.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[Y,as,W2,aq,aD,aE],[cu]:[{endpoint:aJ,[ct]:n2}],[ct]:o},{[cv]:[Y,as,W2,aq,aD,aH],endpoint:aJ,[ct]:n2},{[cv]:[Y,as,aA,aq,aB],endpoint:{[cA]:"https://{Bucket}.s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[Y,as,aA,aq,aD,aE],[cu]:[{endpoint:aK,[ct]:n2}],[ct]:o},{[cv]:[Y,as,aA,aq,aD,aH],endpoint:aK,[ct]:n2},{[cv]:[ar,as,aA,Z,ag,ah,aB],endpoint:{[cA]:C2,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,as,aA,Z,ag,aL,aB],endpoint:{[cA]:q,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,as,aA,Z,ag,ah,aD,aE],[cu]:[{[cv]:cd,endpoint:aM,[ct]:n2},{endpoint:aM,[ct]:n2}],[ct]:o},{[cv]:[ar,as,aA,Z,ag,aL,aD,aE],[cu]:[{[cv]:cd,endpoint:aN,[ct]:n2},aO],[ct]:o},{[cv]:[ar,as,aA,Z,ag,ah,aD,aH],endpoint:aM,[ct]:n2},{[cv]:[ar,as,aA,Z,ag,aL,aD,aH],endpoint:aN,[ct]:n2},{[cv]:[ar,as,W2,aq,aB],endpoint:{[cA]:D,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,as,W2,aq,aD,aE],[cu]:[{[cv]:cd,endpoint:aP,[ct]:n2},{endpoint:aP,[ct]:n2}],[ct]:o},{[cv]:[ar,as,W2,aq,aD,aH],endpoint:aP,[ct]:n2},{[cv]:[ar,as,aA,aq,aB],endpoint:{[cA]:E,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,as,aA,aq,aD,aE],[cu]:[{[cv]:cd,endpoint:{[cA]:E,[cB]:aG,[cH]:al},[ct]:n2},{endpoint:aQ,[ct]:n2}],[ct]:o},{[cv]:[ar,as,aA,aq,aD,aH],endpoint:aQ,[ct]:n2}],[ct]:o},aR],[ct]:o}],[ct]:o},{[cv]:[Z,ag,{[cw]:h,[cx]:[{[cw]:i,[cx]:[ai,"scheme"]},"http"]},{[cw]:p,[cx]:[ad,c]},ay,as,ar,aA],[cu]:[{[cv]:bG,[cu]:[{[cv]:cc,[cu]:[aO],[ct]:o},aR],[ct]:o}],[ct]:o},{[cv]:[ay,{[cw]:F,[cx]:bA,[cz]:G2}],[cu]:[{[cv]:[{[cw]:i,[cx]:[aS,"resourceId[0]"],[cz]:H},{[cw]:r3,[cx]:[{[cw]:h,[cx]:[aT,""]}]}],[cu]:[{[cv]:[{[cw]:h,[cx]:[aU,J]}],[cu]:[{[cv]:ce,[cu]:[{[cv]:cf,[cu]:[aW,aX,{[cv]:ci,[cu]:[aY,{[cv]:cj,[cu]:[aZ,{[cv]:cl,[cu]:[{[cv]:bG,[cu]:[{[cv]:cm,[cu]:[{[cv]:cn,[cu]:[{[cv]:[{[cw]:h,[cx]:[bb,""]}],error:"Invalid ARN: Missing account id",[ct]:f},{[cv]:co,[cu]:[{[cv]:cp,[cu]:[{[cv]:bC,endpoint:{[cA]:M2,[cB]:bc,[cH]:al},[ct]:n2},{[cv]:cq,endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bc,[cH]:al},[ct]:n2},{endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.s3-object-lambda.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bc,[cH]:al},[ct]:n2}],[ct]:o},bd],[ct]:o},be],[ct]:o},bf],[ct]:o},bg],[ct]:o}],[ct]:o}],[ct]:o},bh],[ct]:o},{error:"Invalid ARN: bucket ARN is missing a region",[ct]:f}],[ct]:o},bi],[ct]:o},{error:"Invalid ARN: Object Lambda ARNs only support `accesspoint` arn types, but found: `{arnType}`",[ct]:f}],[ct]:o},{[cv]:ce,[cu]:[{[cv]:cf,[cu]:[{[cv]:ci,[cu]:[{[cv]:ce,[cu]:[{[cv]:ci,[cu]:[aY,{[cv]:cj,[cu]:[aZ,{[cv]:cl,[cu]:[{[cv]:bG,[cu]:[{[cv]:[{[cw]:h,[cx]:[ba,"{partitionResult#name}"]}],[cu]:[{[cv]:cn,[cu]:[{[cv]:[{[cw]:h,[cx]:[aU,B]}],[cu]:[{[cv]:co,[cu]:[{[cv]:cp,[cu]:[{[cv]:bB,error:"Access Points do not support S3 Accelerate",[ct]:f},{[cv]:bH,endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bj,[cH]:al},[ct]:n2},{[cv]:bI,endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint-fips.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bj,[cH]:al},[ct]:n2},{[cv]:bJ,endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.dualstack.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bj,[cH]:al},[ct]:n2},{[cv]:[as,ar,Z,ag],endpoint:{[cA]:M2,[cB]:bj,[cH]:al},[ct]:n2},{[cv]:bK,endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.s3-accesspoint.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bj,[cH]:al},[ct]:n2}],[ct]:o},bd],[ct]:o},be],[ct]:o},{error:"Invalid ARN: The ARN was not for the S3 service, found: {bucketArn#service}",[ct]:f}],[ct]:o},bf],[ct]:o},bg],[ct]:o}],[ct]:o}],[ct]:o},bh],[ct]:o}],[ct]:o}],[ct]:o},{[cv]:[{[cw]:y,[cx]:[aV,c]}],[cu]:[{[cv]:ch,error:"S3 MRAP does not support dual-stack",[ct]:f},{[cv]:cq,error:"S3 MRAP does not support FIPS",[ct]:f},{[cv]:bB,error:"S3 MRAP does not support S3 Accelerate",[ct]:f},{[cv]:[{[cw]:e2,[cx]:[{[cy]:"DisableMultiRegionAccessPoints"},c]}],error:"Invalid configuration: Multi-Region Access Point ARNs are disabled.",[ct]:f},{[cv]:[{[cw]:g,[cx]:by,[cz]:N2}],[cu]:[{[cv]:[{[cw]:h,[cx]:[{[cw]:i,[cx]:[{[cy]:N2},j]},{[cw]:i,[cx]:[aS,"partition"]}]}],[cu]:[{endpoint:{[cA]:"https://{accessPointName}.accesspoint.s3-global.{mrapPartition#dnsSuffix}",[cB]:{[cD]:[{[cE]:c,name:z,[cF]:B,[cI]:cb}]},[cH]:al},[ct]:n2}],[ct]:o},{error:"Client was configured for partition `{mrapPartition#name}` but bucket referred to partition `{bucketArn#partition}`",[ct]:f}],[ct]:o}],[ct]:o},{error:"Invalid Access Point Name",[ct]:f}],[ct]:o},bi],[ct]:o},{[cv]:[{[cw]:h,[cx]:[aU,A]}],[cu]:[{[cv]:ch,error:"S3 Outposts does not support Dual-stack",[ct]:f},{[cv]:cq,error:"S3 Outposts does not support FIPS",[ct]:f},{[cv]:bB,error:"S3 Outposts does not support S3 Accelerate",[ct]:f},{[cv]:[{[cw]:d3,[cx]:[{[cw]:i,[cx]:[aS,"resourceId[4]"]}]}],error:"Invalid Arn: Outpost Access Point ARN contains sub resources",[ct]:f},{[cv]:[{[cw]:i,[cx]:cg,[cz]:x}],[cu]:[{[cv]:bZ,[cu]:[aZ,{[cv]:cl,[cu]:[{[cv]:bG,[cu]:[{[cv]:cm,[cu]:[{[cv]:cn,[cu]:[{[cv]:co,[cu]:[{[cv]:[{[cw]:i,[cx]:ck,[cz]:O}],[cu]:[{[cv]:[{[cw]:i,[cx]:[aS,"resourceId[3]"],[cz]:L3}],[cu]:[{[cv]:[{[cw]:h,[cx]:[{[cy]:O},K]}],[cu]:[{[cv]:bC,endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.{url#authority}",[cB]:bk,[cH]:al},[ct]:n2},{endpoint:{[cA]:"https://{accessPointName}-{bucketArn#accountId}.{outpostId}.s3-outposts.{bucketArn#region}.{bucketPartition#dnsSuffix}",[cB]:bk,[cH]:al},[ct]:n2}],[ct]:o},{error:"Expected an outpost type `accesspoint`, found {outpostType}",[ct]:f}],[ct]:o},{error:"Invalid ARN: expected an access point name",[ct]:f}],[ct]:o},{error:"Invalid ARN: Expected a 4-component resource",[ct]:f}],[ct]:o},be],[ct]:o},bf],[ct]:o},bg],[ct]:o}],[ct]:o}],[ct]:o},{error:"Invalid ARN: The outpost Id may only contain a-z, A-Z, 0-9 and `-`. Found: `{outpostId}`",[ct]:f}],[ct]:o},{error:"Invalid ARN: The Outpost Id was not set",[ct]:f}],[ct]:o},{error:"Invalid ARN: Unrecognized format: {Bucket} (type: {arnType})",[ct]:f}],[ct]:o},{error:"Invalid ARN: No ARN type specified",[ct]:f}],[ct]:o},{[cv]:[{[cw]:k,[cx]:[ad,0,4,!1],[cz]:P2},{[cw]:h,[cx]:[{[cy]:P2},"arn:"]},{[cw]:r3,[cx]:[{[cw]:d3,[cx]:[bl]}]}],error:"Invalid ARN: `{Bucket}` was not a valid ARN",[ct]:f},{[cv]:[{[cw]:e2,[cx]:[az,c]},bl],error:"Path-style addressing cannot be used with ARN buckets",[ct]:f},{[cv]:bE,[cu]:[{[cv]:bG,[cu]:[{[cv]:[aA],[cu]:[{[cv]:[Y,aq,X,aB],endpoint:{[cA]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[Y,aq,X,aD,aE],[cu]:[{endpoint:bm,[ct]:n2}],[ct]:o},{[cv]:[Y,aq,X,aD,aH],endpoint:bm,[ct]:n2},{[cv]:[ar,aq,X,aB],endpoint:{[cA]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,aq,X,aD,aE],[cu]:[{endpoint:bn,[ct]:n2}],[ct]:o},{[cv]:[ar,aq,X,aD,aH],endpoint:bn,[ct]:n2},{[cv]:[Y,aq,as,aB],endpoint:{[cA]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}/{uri_encoded_bucket}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[Y,aq,as,aD,aE],[cu]:[{endpoint:bo,[ct]:n2}],[ct]:o},{[cv]:[Y,aq,as,aD,aH],endpoint:bo,[ct]:n2},{[cv]:[ar,Z,ag,as,aB],endpoint:{[cA]:Q,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,Z,ag,as,aD,aE],[cu]:[{[cv]:cd,endpoint:bp,[ct]:n2},{endpoint:bp,[ct]:n2}],[ct]:o},{[cv]:[ar,Z,ag,as,aD,aH],endpoint:bp,[ct]:n2},{[cv]:[ar,aq,as,aB],endpoint:{[cA]:R,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[ar,aq,as,aD,aE],[cu]:[{[cv]:cd,endpoint:{[cA]:R,[cB]:aG,[cH]:al},[ct]:n2},{endpoint:bq,[ct]:n2}],[ct]:o},{[cv]:[ar,aq,as,aD,aH],endpoint:bq,[ct]:n2}],[ct]:o},{error:"Path-style addressing cannot be used with S3 Accelerate",[ct]:f}],[ct]:o}],[ct]:o}],[ct]:o},{[cv]:[{[cw]:d3,[cx]:[br]},{[cw]:e2,[cx]:[br,c]}],[cu]:[{[cv]:bG,[cu]:[{[cv]:cr2,[cu]:[aW,aX,{[cv]:bC,endpoint:{[cA]:t8,[cB]:bs,[cH]:al},[ct]:n2},{[cv]:cq,endpoint:{[cA]:"https://s3-object-lambda-fips.{Region}.{partitionResult#dnsSuffix}",[cB]:bs,[cH]:al},[ct]:n2},{endpoint:{[cA]:"https://s3-object-lambda.{Region}.{partitionResult#dnsSuffix}",[cB]:bs,[cH]:al},[ct]:n2}],[ct]:o},aR],[ct]:o}],[ct]:o},{[cv]:[au],[cu]:[{[cv]:bG,[cu]:[{[cv]:cr2,[cu]:[{[cv]:[X,Y,aq,aB],endpoint:{[cA]:"https://s3-fips.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[X,Y,aq,aD,aE],[cu]:[{endpoint:bt,[ct]:n2}],[ct]:o},{[cv]:[X,Y,aq,aD,aH],endpoint:bt,[ct]:n2},{[cv]:[X,ar,aq,aB],endpoint:{[cA]:"https://s3-fips.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[X,ar,aq,aD,aE],[cu]:[{endpoint:bu,[ct]:n2}],[ct]:o},{[cv]:[X,ar,aq,aD,aH],endpoint:bu,[ct]:n2},{[cv]:[as,Y,aq,aB],endpoint:{[cA]:"https://s3.dualstack.us-east-1.{partitionResult#dnsSuffix}",[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[as,Y,aq,aD,aE],[cu]:[{endpoint:bv,[ct]:n2}],[ct]:o},{[cv]:[as,Y,aq,aD,aH],endpoint:bv,[ct]:n2},{[cv]:[as,ar,Z,ag,aB],endpoint:{[cA]:t8,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[as,ar,Z,ag,aD,aE],[cu]:[{[cv]:cd,endpoint:bw,[ct]:n2},{endpoint:bw,[ct]:n2}],[ct]:o},{[cv]:[as,ar,Z,ag,aD,aH],endpoint:bw,[ct]:n2},{[cv]:[as,ar,aq,aB],endpoint:{[cA]:S,[cB]:aC,[cH]:al},[ct]:n2},{[cv]:[as,ar,aq,aD,aE],[cu]:[{[cv]:cd,endpoint:{[cA]:S,[cB]:aG,[cH]:al},[ct]:n2},{endpoint:bx,[ct]:n2}],[ct]:o},{[cv]:[as,ar,aq,aD,aH],endpoint:bx,[ct]:n2}],[ct]:o},aR],[ct]:o}],[ct]:o}],[ct]:o},{error:"A region must be set when sending requests to S3.",[ct]: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=awsEndpointFunctions2;defaultS3HttpAuthSchemeParametersProvider=(defaultHttpAuthSchemeParametersProvider=>async(config,context2,input)=>{var _a7,_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==(_a7=getSmithyContext(context2))?void 0:_a7.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:getSmithyContext(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 _a7;const authSchemes=null==(_a7=defaultEndpointResolver2(authParameters).properties)?void 0:_a7.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";const sigv4Present=authSchemes.find((s2=>{const name2=s2.name.toLowerCase();return"sigv4a"!==name2&&name2.startsWith("sigv4")}));if("none"===SignatureV4MultiRegion.sigv4aDependency()&&sigv4Present)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 _a7;const config_0=resolveAwsSdkSigV4Config(config),config_1=resolveAwsSdkSigV4AConfig(config_0);return Object.assign(config_1,{authSchemePreference:normalizeProvider(null!=(_a7=config.authSchemePreference)?_a7:[])})};resolveClientEndpointParameters=options=>{var _a7,_b5,_c3,_d2,_e2,_f,_g;return Object.assign(options,{useFipsEndpoint:null!=(_a7=options.useFipsEndpoint)&&_a7,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",clientContextParams:null!=(_g=options.clientContextParams)?_g:{}})};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)}};AccessDenied=class _AccessDenied extends S3ServiceException{constructor(opts){super({name:"AccessDenied",$fault:"client",...opts});__publicField(this,"name","AccessDenied");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_AccessDenied.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)}};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)}};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)}};IdempotencyParameterMismatch=class _IdempotencyParameterMismatch extends S3ServiceException{constructor(opts){super({name:"IdempotencyParameterMismatch",$fault:"client",...opts});__publicField(this,"name","IdempotencyParameterMismatch");__publicField(this,"$fault","client");Object.setPrototypeOf(this,_IdempotencyParameterMismatch.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)}};_AC="AccelerateConfiguration";_ACL="AccessControlList";_ACLn="AnalyticsConfigurationList";_ACP="AccessControlPolicy";_ACT="AccessControlTranslation";_ACn="AnalyticsConfiguration";_AIMU="AbortIncompleteMultipartUpload";_AR="AcceptRanges";_AS="AbacStatus";_AT="AccessTier";_B="Bucket";_BA="BucketArn";_BET="BlockedEncryptionTypes";_BGR="BypassGovernanceRetention";_BKE="BucketKeyEnabled";_BLS="BucketLoggingStatus";_BP="BytesProcessed";_BPA="BlockPublicAcls";_BPP="BlockPublicPolicy";_BR="BucketRegion";_BRy="BytesReturned";_BS="BytesScanned";_Bo="Body";_Bu="Buckets";_C="Checksum";_CA="ChecksumAlgorithm";_CBC="CreateBucketConfiguration";_CC="CacheControl";_CCRC="ChecksumCRC32";_CCRCC="ChecksumCRC32C";_CCRCNVME="ChecksumCRC64NVME";_CC_="Cache-Control";_CD_="Content-Disposition";_CDo="ContentDisposition";_CE_="Content-Encoding";_CEo="ContentEncoding";_CL="ContentLanguage";_CL_="Content-Language";_CL__="Content-Length";_CLo="ContentLength";_CM="Content-MD5";_CMD="ContentMD5";_CMUo="CompleteMultipartUpload";_COR="CopyObjectResult";_CORSC="CORSConfiguration";_CPR="CopyPartResult";_CPom="CommonPrefixes";_CR="ContentRange";_CR_="Content-Range";_CS="CopySource";_CSHA="ChecksumSHA1";_CSHAh="ChecksumSHA256";_CSIM="CopySourceIfMatch";_CSIMS="CopySourceIfModifiedSince";_CSINM="CopySourceIfNoneMatch";_CSIUS="CopySourceIfUnmodifiedSince";_CSSSECA="CopySourceSSECustomerAlgorithm";_CSVI="CopySourceVersionId";_CSo="ConfigurationState";_CT="ChecksumType";_CT_="Content-Type";_CTo="ContentType";_CTon="ContinuationToken";_Cr="Credentials";_D="Days";_DM="DeleteMarker";_DMR="DeleteMarkerReplication";_DMe="DeleteMarkers";_DN="DisplayName";_DRe="DefaultRetention";_DRes="DestinationResult";_De="Delete";_Deli="Delimiter";_Des="Destination";_E="Expiration";_EBC="EventBridgeConfiguration";_EBO="ExpectedBucketOwner";_EC="EncryptionConfiguration";_EDr="ErrorDocument";_EM="ErrorMessage";_EOR="ExistingObjectReplication";_ES="ExpiresString";_ESBO="ExpectedSourceBucketOwner";_ET="EncryptionType";_ETa="ETag";_ETn="EncodingType";_ETx="ExpressionType";_En="Encryption";_Err="Error";_Ev="Events";_Ex="Expires";_F="Filter";_FD="FieldDelimiter";_FR="FilterRule";_G="Grants";_GBMCR="GetBucketMetadataConfigurationResult";_GBMTCR="GetBucketMetadataTableConfigurationResult";_GFC="GrantFullControl";_GJP="GlacierJobParameters";_GR="GrantRead";_GRACP="GrantReadACP";_GW="GrantWrite";_GWACP="GrantWriteACP";_I="Id";_IC="InventoryConfiguration";_ICL="InventoryConfigurationList";_IDn="IndexDocument";_IM="IfMatch";_IMS_="If-Modified-Since";_IM_="If-Match";_INM="IfNoneMatch";_INM_="If-None-Match";_IPA="IgnorePublicAcls";_IS="InputSerialization";_IT="IsTruncated";_ITC="IntelligentTieringConfiguration";_ITCL="IntelligentTieringConfigurationList";_ITCR="InventoryTableConfigurationResult";_ITCn="InventoryTableConfiguration";_IUS="IfUnmodifiedSince";_IUS_="If-Unmodified-Since";_In="Initiator";_JTC="JournalTableConfiguration";_JTCR="JournalTableConfigurationResult";_K="Key";_KM="KeyMarker";_L="Location";_LBRi="ListBucketResult";_LC="LocationConstraint";_LCi="LifecycleConfiguration";_LE="LoggingEnabled";_LH="LegalHold";_LM="LastModified";_LM_="Last-Modified";_M="Metadata";_MC="MetadataConfiguration";_MCL="MetricsConfigurationList";_MCR="MetadataConfigurationResult";_MCe="MetricsConfiguration";_ME="MetadataEntry";_MK="MaxKeys";_MM="MissingMeta";_MP="MaxParts";_MTC="MetadataTableConfiguration";_MTCR="MetadataTableConfigurationResult";_MU="MultipartUpload";_N="Name";_NC="NotificationConfiguration";_NCT="NextContinuationToken";_ND="NoncurrentDays";_NKM="NextKeyMarker";_NNV="NewerNoncurrentVersions";_NPNM="NextPartNumberMarker";_NVE="NoncurrentVersionExpiration";_NVTo="NoncurrentVersionTransition";_O="Owner";_OC="OwnershipControls";_OE="ObjectEncryption";_OL="OutputLocation";_OLC="ObjectLockConfiguration";_OLLHS="ObjectLockLegalHoldStatus";_OLM="ObjectLockMode";_OLRUD="ObjectLockRetainUntilDate";_OO="ObjectOwnership";_OOA="OptionalObjectAttributes";_OSGT="ObjectSizeGreaterThan";_OSLT="ObjectSizeLessThan";_OSu="OutputSerialization";_P="Prefix";_PABC="PublicAccessBlockConfiguration";_PC="PartsCount";_PN="PartNumber";_PNM="PartNumberMarker";_PP="PartitionedPrefix";_PS="PolicyStatus";_Pa="Parts";_Pe="Permission";_QC="QuoteCharacter";_QCue="QueueConfiguration";_QEC="QuoteEscapeCharacter";_R="Rules";_RART="RedirectAllRequestsTo";_RC="RequestCharged";_RCC="ResponseCacheControl";_RCD="ResponseContentDisposition";_RCE="ResponseContentEncoding";_RCL="ResponseContentLanguage";_RCT="ResponseContentType";_RCe="ReplicationConfiguration";_RD="RecordDelimiter";_RE="ResponseExpires";_REe="RecordExpiration";_RM="ReplicaModifications";_RP="RequestPayer";_RPB="RestrictPublicBuckets";_RPC="RequestPaymentConfiguration";_RPe="RequestProgress";_RR="RoutingRules";_RRes="RestoreRequest";_RS="ReplicationStatus";_RSe="RestoreStatus";_RT="ReplicationTime";_Ra="Range";_Re="Restore";_Ret="Retention";_Ru="Rule";_S="Status";_SA="StartAfter";_SAK="SecretAccessKey";_SBD="S3BucketDestination";_SC="StorageClass";_SCA="StorageClassAnalysis";_SK="SSE-KMS";_SKEO="SseKmsEncryptedObjects";_SP="SelectParameters";_SPi="SimplePrefix";_SSC="SourceSelectionCriteria";_SSE="ServerSideEncryption";_SSEC="ServerSideEncryptionConfiguration";_SSECA="SSECustomerAlgorithm";_SSECKMD="SSECustomerKeyMD5";_ST="SessionToken";_STD="S3TablesDestination";_STDR="S3TablesDestinationResult";_Si="Size";_T="Tags";_TA="TableArn";_TBA="TableBucketArn";_TC="TagCount";_TCop="TopicConfiguration";_TDMOS="TransitionDefaultMinimumObjectSize";_TG="TargetGrants";_TN="TableNamespace";_TNa="TableName";_TOKF="TargetObjectKeyFormat";_TS="TagSet";_Ta="Tag";_Tag="Tagging";_Ty="Type";_UI="UploadId";_UIM="UploadIdMarker";_UM="UserMetadata";_V="Value";_VC="VersioningConfiguration";_VI="VersionId";_VIM="VersionIdMarker";_WC="WebsiteConfiguration";_WRL="WebsiteRedirectLocation";_ar="accept-ranges";_c2="client";_ct="continuation-token";_d="delimiter";_e="error";_eP="eventPayload";_en="endpoint";_et="encoding-type";_h="http";_hC="httpChecksum";_hE="httpError";_hH="httpHeader";_hL="hostLabel";_hP="httpPayload";_hPH="httpPrefixHeaders";_hQ="httpQuery";_hi="http://www.w3.org/2001/XMLSchema-instance";_i="id";_iT="idempotencyToken";_km="key-marker";_mk="max-keys";_p="prefix";_pN="partNumber";_rcc="response-cache-control";_rcd="response-content-disposition";_rce="response-content-encoding";_rcl="response-content-language";_rct="response-content-type";_re="response-expires";_s="streaming";_sm="smithy.ts.sdk.synthetic.com.amazonaws.s3";_uI="uploadId";_vI="versionId";_xA="xmlAttribute";_xF="xmlFlattened";_xN="xmlName";_xNm="xmlNamespace";_xaa="x-amz-acl";_xaad="x-amz-abort-date";_xaari="x-amz-abort-rule-id";_xaba="x-amz-bucket-arn";_xabgr="x-amz-bypass-governance-retention";_xabolt="x-amz-bucket-object-lock-token";_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";_xacs="x-amz-checksum-sha1";_xacs_="x-amz-checksum-sha256";_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";_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";_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";_xam="x-amz-meta-";_xamm="x-amz-missing-meta";_xampc="x-amz-mp-parts-count";_xaollh="x-amz-object-lock-legal-hold";_xaolm="x-amz-object-lock-mode";_xaolrud="x-amz-object-lock-retain-until-date";_xaooa="x-amz-optional-object-attributes";_xar="x-amz-restore";_xarc="x-amz-request-charged";_xarp="x-amz-request-payer";_xars="x-amz-replication-status";_xasc="x-amz-storage-class";_xasca="x-amz-sdk-checksum-algorithm";_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";_xatdmos="x-amz-transition-default-minimum-object-size";_xavi="x-amz-version-id";_xawrl="x-amz-website-redirect-location";CopySourceSSECustomerKey=[0,n0="com.amazonaws.s3","CopySourceSSECustomerKey",8,0];NonEmptyKmsKeyArnString=[0,n0,"NonEmptyKmsKeyArnString",8,0];SessionCredentialValue=[0,n0,"SessionCredentialValue",8,0];SSECustomerKey=[0,n0,_SSECK="SSECustomerKey",8,0];SSEKMSEncryptionContext=[0,n0,_SSEKMSEC="SSEKMSEncryptionContext",8,0];SSEKMSKeyId=[0,n0,_SSEKMSKI="SSEKMSKeyId",8,0];StreamingBlob=[0,n0,"StreamingBlob",{[_s]:1},42];AbacStatus$=[3,n0,_AS,0,[_S],[0]];AbortIncompleteMultipartUpload$=[3,n0,_AIMU,0,["DaysAfterInitiation"],[1]];AbortMultipartUploadOutput$=[3,n0,"AbortMultipartUploadOutput",0,[_RC],[[0,{[_hH]:_xarc}]]];AbortMultipartUploadRequest$=[3,n0,"AbortMultipartUploadRequest",0,[_B,_K,_UI,_RP,_EBO,"IfMatchInitiatedTime"],[[0,1],[0,1],[0,{[_hQ]:_uI}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[6,{[_hH]:"x-amz-if-match-initiated-time"}]],3];AccelerateConfiguration$=[3,n0,_AC,0,[_S],[0]];AccessControlPolicy$=[3,n0,_ACP,0,[_G,_O],[[()=>Grants,{[_xN]:_ACL}],()=>Owner$]];AccessControlTranslation$=[3,n0,_ACT,0,[_O],[0],1];AccessDenied$=[-3,n0,"AccessDenied",{[_e]:_c2,[_hE]:403},[],[]];TypeRegistry.for(n0).registerError(AccessDenied$,AccessDenied);AnalyticsAndOperator$=[3,n0,"AnalyticsAndOperator",0,[_P,_T],[0,[()=>TagSet,{[_xF]:1,[_xN]:_Ta}]]];AnalyticsConfiguration$=[3,n0,_ACn,0,[_I,_SCA,_F],[0,()=>StorageClassAnalysis$,[()=>AnalyticsFilter$,0]],2];AnalyticsExportDestination$=[3,n0,"AnalyticsExportDestination",0,[_SBD],[()=>AnalyticsS3BucketDestination$],1];AnalyticsS3BucketDestination$=[3,n0,"AnalyticsS3BucketDestination",0,["Format",_B,"BucketAccountId",_P],[0,0,0,0],2];BlockedEncryptionTypes$=[3,n0,_BET,0,[_ET],[[()=>EncryptionTypeList,{[_xF]:1}]]];Bucket$=[3,n0,_B,0,[_N,"CreationDate",_BR,_BA],[0,4,0,0]];BucketAlreadyExists$=[-3,n0,"BucketAlreadyExists",{[_e]:_c2,[_hE]:409},[],[]];TypeRegistry.for(n0).registerError(BucketAlreadyExists$,BucketAlreadyExists);BucketAlreadyOwnedByYou$=[-3,n0,"BucketAlreadyOwnedByYou",{[_e]:_c2,[_hE]:409},[],[]];TypeRegistry.for(n0).registerError(BucketAlreadyOwnedByYou$,BucketAlreadyOwnedByYou);BucketInfo$=[3,n0,"BucketInfo",0,["DataRedundancy",_Ty],[0,0]];BucketLifecycleConfiguration$=[3,n0,"BucketLifecycleConfiguration",0,[_R],[[()=>LifecycleRules,{[_xF]:1,[_xN]:_Ru}]],1];BucketLoggingStatus$=[3,n0,_BLS,0,[_LE],[[()=>LoggingEnabled$,0]]];Checksum$=[3,n0,_C,0,[_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_CT],[0,0,0,0,0,0]];CommonPrefix$=[3,n0,"CommonPrefix",0,[_P],[0]];CompletedMultipartUpload$=[3,n0,"CompletedMultipartUpload",0,[_Pa],[[()=>CompletedPartList,{[_xF]:1,[_xN]:"Part"}]]];CompletedPart$=[3,n0,"CompletedPart",0,[_ETa,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_PN],[0,0,0,0,0,0,1]];CompleteMultipartUploadOutput$=[3,n0,"CompleteMultipartUploadOutput",{[_xN]:"CompleteMultipartUploadResult"},[_L,_B,_K,_E,_ETa,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_CT,_SSE,_VI,_SSEKMSKI,_BKE,_RC],[0,0,0,[0,{[_hH]:_xae}],0,0,0,0,0,0,0,[0,{[_hH]:_xasse}],[0,{[_hH]:_xavi}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarc}]]];CompleteMultipartUploadRequest$=[3,n0,"CompleteMultipartUploadRequest",0,[_B,_K,_UI,_MU,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_CT,"MpuObjectSize",_RP,_EBO,_IM,_INM,_SSECA,_SSECK,_SSECKMD],[[0,1],[0,1],[0,{[_hQ]:_uI}],[()=>CompletedMultipartUpload$,{[_hP]:1,[_xN]:_CMUo}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[0,{[_hH]:_xact}],[1,{[_hH]:"x-amz-mp-object-size"}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_IM_}],[0,{[_hH]:_INM_}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}]],3];Condition$=[3,n0,"Condition",0,["HttpErrorCodeReturnedEquals","KeyPrefixEquals"],[0,0]];ContinuationEvent$=[3,n0,"ContinuationEvent",0,[],[]];CopyObjectOutput$=[3,n0,"CopyObjectOutput",0,[_COR,_E,_CSVI,_VI,_SSE,_SSECA,_SSECKMD,_SSEKMSKI,_SSEKMSEC,_BKE,_RC],[[()=>CopyObjectResult$,16],[0,{[_hH]:_xae}],[0,{[_hH]:_xacsvi}],[0,{[_hH]:_xavi}],[0,{[_hH]:_xasse}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarc}]]];CopyObjectRequest$=[3,n0,"CopyObjectRequest",0,[_B,_CS,_K,"ACL",_CC,_CA,_CDo,_CEo,_CL,_CTo,_CSIM,_CSIMS,_CSINM,_CSIUS,_Ex,_GFC,_GR,_GRACP,_GWACP,_IM,_INM,_M,"MetadataDirective","TaggingDirective",_SSE,_SC,_WRL,_SSECA,_SSECK,_SSECKMD,_SSEKMSKI,_SSEKMSEC,_BKE,_CSSSECA,"CopySourceSSECustomerKey","CopySourceSSECustomerKeyMD5",_RP,_Tag,_OLM,_OLRUD,_OLLHS,_EBO,_ESBO],[[0,1],[0,{[_hH]:"x-amz-copy-source"}],[0,1],[0,{[_hH]:_xaa}],[0,{[_hH]:_CC_}],[0,{[_hH]:_xaca}],[0,{[_hH]:_CD_}],[0,{[_hH]:_CE_}],[0,{[_hH]:_CL_}],[0,{[_hH]:_CT_}],[0,{[_hH]:_xacsim}],[4,{[_hH]:_xacsims}],[0,{[_hH]:_xacsinm}],[4,{[_hH]:_xacsius}],[4,{[_hH]:_Ex}],[0,{[_hH]:_xagfc}],[0,{[_hH]:_xagr}],[0,{[_hH]:_xagra}],[0,{[_hH]:_xagwa}],[0,{[_hH]:_IM_}],[0,{[_hH]:_INM_}],[128,{[_hPH]:_xam}],[0,{[_hH]:"x-amz-metadata-directive"}],[0,{[_hH]:"x-amz-tagging-directive"}],[0,{[_hH]:_xasse}],[0,{[_hH]:_xasc}],[0,{[_hH]:_xawrl}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xacssseca}],[()=>CopySourceSSECustomerKey,{[_hH]:_xacssseck}],[0,{[_hH]:_xacssseckM}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xat}],[0,{[_hH]:_xaolm}],[5,{[_hH]:_xaolrud}],[0,{[_hH]:_xaollh}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xasebo}]],3];CopyObjectResult$=[3,n0,_COR,0,[_ETa,_LM,_CT,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh],[0,4,0,0,0,0,0,0]];CopyPartResult$=[3,n0,_CPR,0,[_ETa,_LM,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh],[0,4,0,0,0,0,0]];CORSConfiguration$=[3,n0,_CORSC,0,["CORSRules"],[[()=>CORSRules,{[_xF]:1,[_xN]:"CORSRule"}]],1];CORSRule$=[3,n0,"CORSRule",0,["AllowedMethods","AllowedOrigins","ID","AllowedHeaders","ExposeHeaders","MaxAgeSeconds"],[[64,{[_xF]:1,[_xN]:"AllowedMethod"}],[64,{[_xF]:1,[_xN]:"AllowedOrigin"}],0,[64,{[_xF]:1,[_xN]:"AllowedHeader"}],[64,{[_xF]:1,[_xN]:"ExposeHeader"}],1],2];CreateBucketConfiguration$=[3,n0,_CBC,0,[_LC,_L,_B,_T],[0,()=>LocationInfo$,()=>BucketInfo$,[()=>TagSet,0]]];CreateBucketMetadataConfigurationRequest$=[3,n0,"CreateBucketMetadataConfigurationRequest",0,[_B,_MC,_CMD,_CA,_EBO],[[0,1],[()=>MetadataConfiguration$,{[_hP]:1,[_xN]:_MC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];CreateBucketMetadataTableConfigurationRequest$=[3,n0,"CreateBucketMetadataTableConfigurationRequest",0,[_B,_MTC,_CMD,_CA,_EBO],[[0,1],[()=>MetadataTableConfiguration$,{[_hP]:1,[_xN]:_MTC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];CreateBucketOutput$=[3,n0,"CreateBucketOutput",0,[_L,_BA],[[0,{[_hH]:_L}],[0,{[_hH]:_xaba}]]];CreateBucketRequest$=[3,n0,"CreateBucketRequest",0,[_B,"ACL",_CBC,_GFC,_GR,_GRACP,_GW,_GWACP,"ObjectLockEnabledForBucket",_OO],[[0,1],[0,{[_hH]:_xaa}],[()=>CreateBucketConfiguration$,{[_hP]:1,[_xN]:_CBC}],[0,{[_hH]:_xagfc}],[0,{[_hH]:_xagr}],[0,{[_hH]:_xagra}],[0,{[_hH]:_xagw}],[0,{[_hH]:_xagwa}],[2,{[_hH]:"x-amz-bucket-object-lock-enabled"}],[0,{[_hH]:"x-amz-object-ownership"}]],1];CreateMultipartUploadOutput$=[3,n0,"CreateMultipartUploadOutput",{[_xN]:"InitiateMultipartUploadResult"},["AbortDate","AbortRuleId",_B,_K,_UI,_SSE,_SSECA,_SSECKMD,_SSEKMSKI,_SSEKMSEC,_BKE,_RC,_CA,_CT],[[4,{[_hH]:_xaad}],[0,{[_hH]:_xaari}],[0,{[_xN]:_B}],0,0,[0,{[_hH]:_xasse}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarc}],[0,{[_hH]:_xaca}],[0,{[_hH]:_xact}]]];CreateMultipartUploadRequest$=[3,n0,"CreateMultipartUploadRequest",0,[_B,_K,"ACL",_CC,_CDo,_CEo,_CL,_CTo,_Ex,_GFC,_GR,_GRACP,_GWACP,_M,_SSE,_SC,_WRL,_SSECA,_SSECK,_SSECKMD,_SSEKMSKI,_SSEKMSEC,_BKE,_RP,_Tag,_OLM,_OLRUD,_OLLHS,_EBO,_CA,_CT],[[0,1],[0,1],[0,{[_hH]:_xaa}],[0,{[_hH]:_CC_}],[0,{[_hH]:_CD_}],[0,{[_hH]:_CE_}],[0,{[_hH]:_CL_}],[0,{[_hH]:_CT_}],[4,{[_hH]:_Ex}],[0,{[_hH]:_xagfc}],[0,{[_hH]:_xagr}],[0,{[_hH]:_xagra}],[0,{[_hH]:_xagwa}],[128,{[_hPH]:_xam}],[0,{[_hH]:_xasse}],[0,{[_hH]:_xasc}],[0,{[_hH]:_xawrl}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xat}],[0,{[_hH]:_xaolm}],[5,{[_hH]:_xaolrud}],[0,{[_hH]:_xaollh}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xaca}],[0,{[_hH]:_xact}]],2];CreateSessionOutput$=[3,n0,"CreateSessionOutput",{[_xN]:"CreateSessionResult"},[_Cr,_SSE,_SSEKMSKI,_SSEKMSEC,_BKE],[[()=>SessionCredentials$,{[_xN]:_Cr}],[0,{[_hH]:_xasse}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}]],1];CreateSessionRequest$=[3,n0,"CreateSessionRequest",0,[_B,"SessionMode",_SSE,_SSEKMSKI,_SSEKMSEC,_BKE],[[0,1],[0,{[_hH]:"x-amz-create-session-mode"}],[0,{[_hH]:_xasse}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}]],1];CSVInput$=[3,n0,"CSVInput",0,["FileHeaderInfo","Comments",_QEC,_RD,_FD,_QC,"AllowQuotedRecordDelimiter"],[0,0,0,0,0,0,2]];CSVOutput$=[3,n0,"CSVOutput",0,["QuoteFields",_QEC,_RD,_FD,_QC],[0,0,0,0,0]];DefaultRetention$=[3,n0,_DRe,0,["Mode",_D,"Years"],[0,1,1]];Delete$=[3,n0,_De,0,["Objects","Quiet"],[[()=>ObjectIdentifierList,{[_xF]:1,[_xN]:"Object"}],2],1];DeleteBucketAnalyticsConfigurationRequest$=[3,n0,"DeleteBucketAnalyticsConfigurationRequest",0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];DeleteBucketCorsRequest$=[3,n0,"DeleteBucketCorsRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketEncryptionRequest$=[3,n0,"DeleteBucketEncryptionRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketIntelligentTieringConfigurationRequest$=[3,n0,"DeleteBucketIntelligentTieringConfigurationRequest",0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];DeleteBucketInventoryConfigurationRequest$=[3,n0,"DeleteBucketInventoryConfigurationRequest",0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];DeleteBucketLifecycleRequest$=[3,n0,"DeleteBucketLifecycleRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketMetadataConfigurationRequest$=[3,n0,"DeleteBucketMetadataConfigurationRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketMetadataTableConfigurationRequest$=[3,n0,"DeleteBucketMetadataTableConfigurationRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketMetricsConfigurationRequest$=[3,n0,"DeleteBucketMetricsConfigurationRequest",0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];DeleteBucketOwnershipControlsRequest$=[3,n0,"DeleteBucketOwnershipControlsRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketPolicyRequest$=[3,n0,"DeleteBucketPolicyRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketReplicationRequest$=[3,n0,"DeleteBucketReplicationRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketRequest$=[3,n0,"DeleteBucketRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketTaggingRequest$=[3,n0,"DeleteBucketTaggingRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeleteBucketWebsiteRequest$=[3,n0,"DeleteBucketWebsiteRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];DeletedObject$=[3,n0,"DeletedObject",0,[_K,_VI,_DM,"DeleteMarkerVersionId"],[0,0,2,0]];DeleteMarkerEntry$=[3,n0,"DeleteMarkerEntry",0,[_O,_K,_VI,"IsLatest",_LM],[()=>Owner$,0,0,2,4]];DeleteMarkerReplication$=[3,n0,_DMR,0,[_S],[0]];DeleteObjectOutput$=[3,n0,"DeleteObjectOutput",0,[_DM,_VI,_RC],[[2,{[_hH]:_xadm}],[0,{[_hH]:_xavi}],[0,{[_hH]:_xarc}]]];DeleteObjectRequest$=[3,n0,"DeleteObjectRequest",0,[_B,_K,"MFA",_VI,_RP,_BGR,_EBO,_IM,"IfMatchLastModifiedTime","IfMatchSize"],[[0,1],[0,1],[0,{[_hH]:"x-amz-mfa"}],[0,{[_hQ]:_vI}],[0,{[_hH]:_xarp}],[2,{[_hH]:_xabgr}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_IM_}],[6,{[_hH]:"x-amz-if-match-last-modified-time"}],[1,{[_hH]:"x-amz-if-match-size"}]],2];DeleteObjectsOutput$=[3,n0,"DeleteObjectsOutput",{[_xN]:"DeleteResult"},["Deleted",_RC,"Errors"],[[()=>DeletedObjects,{[_xF]:1}],[0,{[_hH]:_xarc}],[()=>Errors,{[_xF]:1,[_xN]:_Err}]]];DeleteObjectsRequest$=[3,n0,"DeleteObjectsRequest",0,[_B,_De,"MFA",_RP,_BGR,_EBO,_CA],[[0,1],[()=>Delete$,{[_hP]:1,[_xN]:_De}],[0,{[_hH]:"x-amz-mfa"}],[0,{[_hH]:_xarp}],[2,{[_hH]:_xabgr}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xasca}]],2];DeleteObjectTaggingOutput$=[3,n0,"DeleteObjectTaggingOutput",0,[_VI],[[0,{[_hH]:_xavi}]]];DeleteObjectTaggingRequest$=[3,n0,"DeleteObjectTaggingRequest",0,[_B,_K,_VI,_EBO],[[0,1],[0,1],[0,{[_hQ]:_vI}],[0,{[_hH]:_xaebo}]],2];DeletePublicAccessBlockRequest$=[3,n0,"DeletePublicAccessBlockRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];Destination$=[3,n0,_Des,0,[_B,"Account",_SC,_ACT,_EC,_RT,"Metrics"],[0,0,0,()=>AccessControlTranslation$,()=>EncryptionConfiguration$,()=>ReplicationTime$,()=>Metrics$],1];DestinationResult$=[3,n0,_DRes,0,["TableBucketType",_TBA,_TN],[0,0,0]];Encryption$=[3,n0,_En,0,[_ET,"KMSKeyId","KMSContext"],[0,[()=>SSEKMSKeyId,0],0],1];EncryptionConfiguration$=[3,n0,_EC,0,["ReplicaKmsKeyID"],[0]];EncryptionTypeMismatch$=[-3,n0,"EncryptionTypeMismatch",{[_e]:_c2,[_hE]:400},[],[]];TypeRegistry.for(n0).registerError(EncryptionTypeMismatch$,EncryptionTypeMismatch);EndEvent$=[3,n0,"EndEvent",0,[],[]];_Error$=[3,n0,_Err,0,[_K,_VI,"Code","Message"],[0,0,0,0]];ErrorDetails$=[3,n0,"ErrorDetails",0,["ErrorCode",_EM],[0,0]];ErrorDocument$=[3,n0,_EDr,0,[_K],[0],1];EventBridgeConfiguration$=[3,n0,_EBC,0,[],[]];ExistingObjectReplication$=[3,n0,_EOR,0,[_S],[0],1];FilterRule$=[3,n0,_FR,0,[_N,_V],[0,0]];GetBucketAbacOutput$=[3,n0,"GetBucketAbacOutput",0,[_AS],[[()=>AbacStatus$,16]]];GetBucketAbacRequest$=[3,n0,"GetBucketAbacRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketAccelerateConfigurationOutput$=[3,n0,"GetBucketAccelerateConfigurationOutput",{[_xN]:_AC},[_S,_RC],[0,[0,{[_hH]:_xarc}]]];GetBucketAccelerateConfigurationRequest$=[3,n0,"GetBucketAccelerateConfigurationRequest",0,[_B,_EBO,_RP],[[0,1],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xarp}]],1];GetBucketAclOutput$=[3,n0,"GetBucketAclOutput",{[_xN]:_ACP},[_O,_G],[()=>Owner$,[()=>Grants,{[_xN]:_ACL}]]];GetBucketAclRequest$=[3,n0,"GetBucketAclRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketAnalyticsConfigurationOutput$=[3,n0,"GetBucketAnalyticsConfigurationOutput",0,[_ACn],[[()=>AnalyticsConfiguration$,16]]];GetBucketAnalyticsConfigurationRequest$=[3,n0,"GetBucketAnalyticsConfigurationRequest",0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];GetBucketCorsOutput$=[3,n0,"GetBucketCorsOutput",{[_xN]:_CORSC},["CORSRules"],[[()=>CORSRules,{[_xF]:1,[_xN]:"CORSRule"}]]];GetBucketCorsRequest$=[3,n0,"GetBucketCorsRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketEncryptionOutput$=[3,n0,"GetBucketEncryptionOutput",0,[_SSEC],[[()=>ServerSideEncryptionConfiguration$,16]]];GetBucketEncryptionRequest$=[3,n0,"GetBucketEncryptionRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketIntelligentTieringConfigurationOutput$=[3,n0,"GetBucketIntelligentTieringConfigurationOutput",0,[_ITC],[[()=>IntelligentTieringConfiguration$,16]]];GetBucketIntelligentTieringConfigurationRequest$=[3,n0,"GetBucketIntelligentTieringConfigurationRequest",0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];GetBucketInventoryConfigurationOutput$=[3,n0,"GetBucketInventoryConfigurationOutput",0,[_IC],[[()=>InventoryConfiguration$,16]]];GetBucketInventoryConfigurationRequest$=[3,n0,"GetBucketInventoryConfigurationRequest",0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];GetBucketLifecycleConfigurationOutput$=[3,n0,"GetBucketLifecycleConfigurationOutput",{[_xN]:_LCi},[_R,_TDMOS],[[()=>LifecycleRules,{[_xF]:1,[_xN]:_Ru}],[0,{[_hH]:_xatdmos}]]];GetBucketLifecycleConfigurationRequest$=[3,n0,"GetBucketLifecycleConfigurationRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketLocationOutput$=[3,n0,"GetBucketLocationOutput",{[_xN]:_LC},[_LC],[0]];GetBucketLocationRequest$=[3,n0,"GetBucketLocationRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketLoggingOutput$=[3,n0,"GetBucketLoggingOutput",{[_xN]:_BLS},[_LE],[[()=>LoggingEnabled$,0]]];GetBucketLoggingRequest$=[3,n0,"GetBucketLoggingRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketMetadataConfigurationOutput$=[3,n0,"GetBucketMetadataConfigurationOutput",0,[_GBMCR],[[()=>GetBucketMetadataConfigurationResult$,16]]];GetBucketMetadataConfigurationRequest$=[3,n0,"GetBucketMetadataConfigurationRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketMetadataConfigurationResult$=[3,n0,_GBMCR,0,[_MCR],[()=>MetadataConfigurationResult$],1];GetBucketMetadataTableConfigurationOutput$=[3,n0,"GetBucketMetadataTableConfigurationOutput",0,[_GBMTCR],[[()=>GetBucketMetadataTableConfigurationResult$,16]]];GetBucketMetadataTableConfigurationRequest$=[3,n0,"GetBucketMetadataTableConfigurationRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketMetadataTableConfigurationResult$=[3,n0,_GBMTCR,0,[_MTCR,_S,_Err],[()=>MetadataTableConfigurationResult$,0,()=>ErrorDetails$],2];GetBucketMetricsConfigurationOutput$=[3,n0,"GetBucketMetricsConfigurationOutput",0,[_MCe],[[()=>MetricsConfiguration$,16]]];GetBucketMetricsConfigurationRequest$=[3,n0,"GetBucketMetricsConfigurationRequest",0,[_B,_I,_EBO],[[0,1],[0,{[_hQ]:_i}],[0,{[_hH]:_xaebo}]],2];GetBucketNotificationConfigurationRequest$=[3,n0,"GetBucketNotificationConfigurationRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketOwnershipControlsOutput$=[3,n0,"GetBucketOwnershipControlsOutput",0,[_OC],[[()=>OwnershipControls$,16]]];GetBucketOwnershipControlsRequest$=[3,n0,"GetBucketOwnershipControlsRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketPolicyOutput$=[3,n0,"GetBucketPolicyOutput",0,["Policy"],[[0,16]]];GetBucketPolicyRequest$=[3,n0,"GetBucketPolicyRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketPolicyStatusOutput$=[3,n0,"GetBucketPolicyStatusOutput",0,[_PS],[[()=>PolicyStatus$,16]]];GetBucketPolicyStatusRequest$=[3,n0,"GetBucketPolicyStatusRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketReplicationOutput$=[3,n0,"GetBucketReplicationOutput",0,[_RCe],[[()=>ReplicationConfiguration$,16]]];GetBucketReplicationRequest$=[3,n0,"GetBucketReplicationRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketRequestPaymentOutput$=[3,n0,"GetBucketRequestPaymentOutput",{[_xN]:_RPC},["Payer"],[0]];GetBucketRequestPaymentRequest$=[3,n0,"GetBucketRequestPaymentRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketTaggingOutput$=[3,n0,"GetBucketTaggingOutput",{[_xN]:_Tag},[_TS],[[()=>TagSet,0]],1];GetBucketTaggingRequest$=[3,n0,"GetBucketTaggingRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketVersioningOutput$=[3,n0,"GetBucketVersioningOutput",{[_xN]:_VC},[_S,"MFADelete"],[0,[0,{[_xN]:"MfaDelete"}]]];GetBucketVersioningRequest$=[3,n0,"GetBucketVersioningRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetBucketWebsiteOutput$=[3,n0,"GetBucketWebsiteOutput",{[_xN]:_WC},[_RART,_IDn,_EDr,_RR],[()=>RedirectAllRequestsTo$,()=>IndexDocument$,()=>ErrorDocument$,[()=>RoutingRules,0]]];GetBucketWebsiteRequest$=[3,n0,"GetBucketWebsiteRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetObjectAclOutput$=[3,n0,"GetObjectAclOutput",{[_xN]:_ACP},[_O,_G,_RC],[()=>Owner$,[()=>Grants,{[_xN]:_ACL}],[0,{[_hH]:_xarc}]]];GetObjectAclRequest$=[3,n0,"GetObjectAclRequest",0,[_B,_K,_VI,_RP,_EBO],[[0,1],[0,1],[0,{[_hQ]:_vI}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}]],2];GetObjectAttributesOutput$=[3,n0,"GetObjectAttributesOutput",{[_xN]:"GetObjectAttributesResponse"},[_DM,_LM,_VI,_RC,_ETa,_C,"ObjectParts",_SC,"ObjectSize"],[[2,{[_hH]:_xadm}],[4,{[_hH]:_LM_}],[0,{[_hH]:_xavi}],[0,{[_hH]:_xarc}],0,()=>Checksum$,[()=>GetObjectAttributesParts$,0],0,1]];GetObjectAttributesParts$=[3,n0,"GetObjectAttributesParts",0,["TotalPartsCount",_PNM,_NPNM,_MP,_IT,_Pa],[[1,{[_xN]:_PC}],0,0,1,2,[()=>PartsList,{[_xF]:1,[_xN]:"Part"}]]];GetObjectAttributesRequest$=[3,n0,"GetObjectAttributesRequest",0,[_B,_K,"ObjectAttributes",_VI,_MP,_PNM,_SSECA,_SSECK,_SSECKMD,_RP,_EBO],[[0,1],[0,1],[64,{[_hH]:"x-amz-object-attributes"}],[0,{[_hQ]:_vI}],[1,{[_hH]:"x-amz-max-parts"}],[0,{[_hH]:"x-amz-part-number-marker"}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}]],3];GetObjectLegalHoldOutput$=[3,n0,"GetObjectLegalHoldOutput",0,[_LH],[[()=>ObjectLockLegalHold$,{[_hP]:1,[_xN]:_LH}]]];GetObjectLegalHoldRequest$=[3,n0,"GetObjectLegalHoldRequest",0,[_B,_K,_VI,_RP,_EBO],[[0,1],[0,1],[0,{[_hQ]:_vI}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}]],2];GetObjectLockConfigurationOutput$=[3,n0,"GetObjectLockConfigurationOutput",0,[_OLC],[[()=>ObjectLockConfiguration$,16]]];GetObjectLockConfigurationRequest$=[3,n0,"GetObjectLockConfigurationRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GetObjectOutput$=[3,n0,"GetObjectOutput",0,[_Bo,_DM,_AR,_E,_Re,_LM,_CLo,_ETa,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_CT,_MM,_VI,_CC,_CDo,_CEo,_CL,_CR,_CTo,_Ex,_ES,_WRL,_SSE,_M,_SSECA,_SSECKMD,_SSEKMSKI,_BKE,_SC,_RC,_RS,_PC,_TC,_OLM,_OLRUD,_OLLHS],[[()=>StreamingBlob,16],[2,{[_hH]:_xadm}],[0,{[_hH]:_ar}],[0,{[_hH]:_xae}],[0,{[_hH]:_xar}],[4,{[_hH]:_LM_}],[1,{[_hH]:_CL__}],[0,{[_hH]:_ETa}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[0,{[_hH]:_xact}],[1,{[_hH]:_xamm}],[0,{[_hH]:_xavi}],[0,{[_hH]:_CC_}],[0,{[_hH]:_CD_}],[0,{[_hH]:_CE_}],[0,{[_hH]:_CL_}],[0,{[_hH]:_CR_}],[0,{[_hH]:_CT_}],[4,{[_hH]:_Ex}],[0,{[_hH]:_ES}],[0,{[_hH]:_xawrl}],[0,{[_hH]:_xasse}],[128,{[_hPH]:_xam}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xasc}],[0,{[_hH]:_xarc}],[0,{[_hH]:_xars}],[1,{[_hH]:_xampc}],[1,{[_hH]:_xatc}],[0,{[_hH]:_xaolm}],[5,{[_hH]:_xaolrud}],[0,{[_hH]:_xaollh}]]];GetObjectRequest$=[3,n0,"GetObjectRequest",0,[_B,_K,_IM,"IfModifiedSince",_INM,_IUS,_Ra,_RCC,_RCD,_RCE,_RCL,_RCT,_RE,_VI,_SSECA,_SSECK,_SSECKMD,_RP,_PN,_EBO,"ChecksumMode"],[[0,1],[0,1],[0,{[_hH]:_IM_}],[4,{[_hH]:_IMS_}],[0,{[_hH]:_INM_}],[4,{[_hH]:_IUS_}],[0,{[_hH]:_Ra}],[0,{[_hQ]:_rcc}],[0,{[_hQ]:_rcd}],[0,{[_hQ]:_rce}],[0,{[_hQ]:_rcl}],[0,{[_hQ]:_rct}],[6,{[_hQ]:_re}],[0,{[_hQ]:_vI}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[0,{[_hH]:_xarp}],[1,{[_hQ]:_pN}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xacm}]],2];GetObjectRetentionOutput$=[3,n0,"GetObjectRetentionOutput",0,[_Ret],[[()=>ObjectLockRetention$,{[_hP]:1,[_xN]:_Ret}]]];GetObjectRetentionRequest$=[3,n0,"GetObjectRetentionRequest",0,[_B,_K,_VI,_RP,_EBO],[[0,1],[0,1],[0,{[_hQ]:_vI}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}]],2];GetObjectTaggingOutput$=[3,n0,"GetObjectTaggingOutput",{[_xN]:_Tag},[_TS,_VI],[[()=>TagSet,0],[0,{[_hH]:_xavi}]],1];GetObjectTaggingRequest$=[3,n0,"GetObjectTaggingRequest",0,[_B,_K,_VI,_EBO,_RP],[[0,1],[0,1],[0,{[_hQ]:_vI}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xarp}]],2];GetObjectTorrentOutput$=[3,n0,"GetObjectTorrentOutput",0,[_Bo,_RC],[[()=>StreamingBlob,16],[0,{[_hH]:_xarc}]]];GetObjectTorrentRequest$=[3,n0,"GetObjectTorrentRequest",0,[_B,_K,_RP,_EBO],[[0,1],[0,1],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}]],2];GetPublicAccessBlockOutput$=[3,n0,"GetPublicAccessBlockOutput",0,[_PABC],[[()=>PublicAccessBlockConfiguration$,16]]];GetPublicAccessBlockRequest$=[3,n0,"GetPublicAccessBlockRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];GlacierJobParameters$=[3,n0,_GJP,0,["Tier"],[0],1];Grant$=[3,n0,"Grant",0,["Grantee",_Pe],[[()=>Grantee$,{[_xNm]:["xsi",_hi]}],0]];Grantee$=[3,n0,"Grantee",0,[_Ty,_DN,"EmailAddress","ID","URI"],[[0,{[_xA]:1,[_xN]:"xsi:type"}],0,0,0,0],1];HeadBucketOutput$=[3,n0,"HeadBucketOutput",0,[_BA,"BucketLocationType","BucketLocationName",_BR,"AccessPointAlias"],[[0,{[_hH]:_xaba}],[0,{[_hH]:"x-amz-bucket-location-type"}],[0,{[_hH]:"x-amz-bucket-location-name"}],[0,{[_hH]:"x-amz-bucket-region"}],[2,{[_hH]:"x-amz-access-point-alias"}]]];HeadBucketRequest$=[3,n0,"HeadBucketRequest",0,[_B,_EBO],[[0,1],[0,{[_hH]:_xaebo}]],1];HeadObjectOutput$=[3,n0,"HeadObjectOutput",0,[_DM,_AR,_E,_Re,"ArchiveStatus",_LM,_CLo,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_CT,_ETa,_MM,_VI,_CC,_CDo,_CEo,_CL,_CTo,_CR,_Ex,_ES,_WRL,_SSE,_M,_SSECA,_SSECKMD,_SSEKMSKI,_BKE,_SC,_RC,_RS,_PC,_TC,_OLM,_OLRUD,_OLLHS],[[2,{[_hH]:_xadm}],[0,{[_hH]:_ar}],[0,{[_hH]:_xae}],[0,{[_hH]:_xar}],[0,{[_hH]:"x-amz-archive-status"}],[4,{[_hH]:_LM_}],[1,{[_hH]:_CL__}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[0,{[_hH]:_xact}],[0,{[_hH]:_ETa}],[1,{[_hH]:_xamm}],[0,{[_hH]:_xavi}],[0,{[_hH]:_CC_}],[0,{[_hH]:_CD_}],[0,{[_hH]:_CE_}],[0,{[_hH]:_CL_}],[0,{[_hH]:_CT_}],[0,{[_hH]:_CR_}],[4,{[_hH]:_Ex}],[0,{[_hH]:_ES}],[0,{[_hH]:_xawrl}],[0,{[_hH]:_xasse}],[128,{[_hPH]:_xam}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xasc}],[0,{[_hH]:_xarc}],[0,{[_hH]:_xars}],[1,{[_hH]:_xampc}],[1,{[_hH]:_xatc}],[0,{[_hH]:_xaolm}],[5,{[_hH]:_xaolrud}],[0,{[_hH]:_xaollh}]]];HeadObjectRequest$=[3,n0,"HeadObjectRequest",0,[_B,_K,_IM,"IfModifiedSince",_INM,_IUS,_Ra,_RCC,_RCD,_RCE,_RCL,_RCT,_RE,_VI,_SSECA,_SSECK,_SSECKMD,_RP,_PN,_EBO,"ChecksumMode"],[[0,1],[0,1],[0,{[_hH]:_IM_}],[4,{[_hH]:_IMS_}],[0,{[_hH]:_INM_}],[4,{[_hH]:_IUS_}],[0,{[_hH]:_Ra}],[0,{[_hQ]:_rcc}],[0,{[_hQ]:_rcd}],[0,{[_hQ]:_rce}],[0,{[_hQ]:_rcl}],[0,{[_hQ]:_rct}],[6,{[_hQ]:_re}],[0,{[_hQ]:_vI}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[0,{[_hH]:_xarp}],[1,{[_hQ]:_pN}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xacm}]],2];IdempotencyParameterMismatch$=[-3,n0,"IdempotencyParameterMismatch",{[_e]:_c2,[_hE]:400},[],[]];TypeRegistry.for(n0).registerError(IdempotencyParameterMismatch$,IdempotencyParameterMismatch);IndexDocument$=[3,n0,_IDn,0,["Suffix"],[0],1];Initiator$=[3,n0,_In,0,["ID",_DN],[0,0]];InputSerialization$=[3,n0,_IS,0,["CSV","CompressionType","JSON","Parquet"],[()=>CSVInput$,0,()=>JSONInput$,()=>ParquetInput$]];IntelligentTieringAndOperator$=[3,n0,"IntelligentTieringAndOperator",0,[_P,_T],[0,[()=>TagSet,{[_xF]:1,[_xN]:_Ta}]]];IntelligentTieringConfiguration$=[3,n0,_ITC,0,[_I,_S,"Tierings",_F],[0,0,[()=>TieringList,{[_xF]:1,[_xN]:"Tiering"}],[()=>IntelligentTieringFilter$,0]],3];IntelligentTieringFilter$=[3,n0,"IntelligentTieringFilter",0,[_P,_Ta,"And"],[0,()=>Tag$,[()=>IntelligentTieringAndOperator$,0]]];InvalidObjectState$=[-3,n0,"InvalidObjectState",{[_e]:_c2,[_hE]:403},[_SC,_AT],[0,0]];TypeRegistry.for(n0).registerError(InvalidObjectState$,InvalidObjectState);InvalidRequest$=[-3,n0,"InvalidRequest",{[_e]:_c2,[_hE]:400},[],[]];TypeRegistry.for(n0).registerError(InvalidRequest$,InvalidRequest);InvalidWriteOffset$=[-3,n0,"InvalidWriteOffset",{[_e]:_c2,[_hE]:400},[],[]];TypeRegistry.for(n0).registerError(InvalidWriteOffset$,InvalidWriteOffset);InventoryConfiguration$=[3,n0,_IC,0,[_Des,"IsEnabled",_I,"IncludedObjectVersions","Schedule",_F,"OptionalFields"],[[()=>InventoryDestination$,0],2,0,0,()=>InventorySchedule$,()=>InventoryFilter$,[()=>InventoryOptionalFields,0]],5];InventoryDestination$=[3,n0,"InventoryDestination",0,[_SBD],[[()=>InventoryS3BucketDestination$,0]],1];InventoryEncryption$=[3,n0,"InventoryEncryption",0,["SSES3","SSEKMS"],[[()=>SSES3$,{[_xN]:"SSE-S3"}],[()=>SSEKMS$,{[_xN]:_SK}]]];InventoryFilter$=[3,n0,"InventoryFilter",0,[_P],[0],1];InventoryS3BucketDestination$=[3,n0,"InventoryS3BucketDestination",0,[_B,"Format","AccountId",_P,_En],[0,0,0,0,[()=>InventoryEncryption$,0]],2];InventorySchedule$=[3,n0,"InventorySchedule",0,["Frequency"],[0],1];InventoryTableConfiguration$=[3,n0,_ITCn,0,[_CSo,_EC],[0,()=>MetadataTableEncryptionConfiguration$],1];InventoryTableConfigurationResult$=[3,n0,_ITCR,0,[_CSo,"TableStatus",_Err,_TNa,_TA],[0,0,()=>ErrorDetails$,0,0],1];InventoryTableConfigurationUpdates$=[3,n0,"InventoryTableConfigurationUpdates",0,[_CSo,_EC],[0,()=>MetadataTableEncryptionConfiguration$],1];JournalTableConfiguration$=[3,n0,_JTC,0,[_REe,_EC],[()=>RecordExpiration$,()=>MetadataTableEncryptionConfiguration$],1];JournalTableConfigurationResult$=[3,n0,_JTCR,0,["TableStatus",_TNa,_REe,_Err,_TA],[0,0,()=>RecordExpiration$,()=>ErrorDetails$,0],3];JournalTableConfigurationUpdates$=[3,n0,"JournalTableConfigurationUpdates",0,[_REe],[()=>RecordExpiration$],1];JSONInput$=[3,n0,"JSONInput",0,[_Ty],[0]];JSONOutput$=[3,n0,"JSONOutput",0,[_RD],[0]];LambdaFunctionConfiguration$=[3,n0,"LambdaFunctionConfiguration",0,["LambdaFunctionArn",_Ev,_I,_F],[[0,{[_xN]:"CloudFunction"}],[64,{[_xF]:1,[_xN]:"Event"}],0,[()=>NotificationConfigurationFilter$,0]],2];LifecycleExpiration$=[3,n0,"LifecycleExpiration",0,["Date",_D,"ExpiredObjectDeleteMarker"],[5,1,2]];LifecycleRule$=[3,n0,"LifecycleRule",0,[_S,_E,"ID",_P,_F,"Transitions","NoncurrentVersionTransitions",_NVE,_AIMU],[0,()=>LifecycleExpiration$,0,0,[()=>LifecycleRuleFilter$,0],[()=>TransitionList,{[_xF]:1,[_xN]:"Transition"}],[()=>NoncurrentVersionTransitionList,{[_xF]:1,[_xN]:_NVTo}],()=>NoncurrentVersionExpiration$,()=>AbortIncompleteMultipartUpload$],1];LifecycleRuleAndOperator$=[3,n0,"LifecycleRuleAndOperator",0,[_P,_T,_OSGT,_OSLT],[0,[()=>TagSet,{[_xF]:1,[_xN]:_Ta}],1,1]];LifecycleRuleFilter$=[3,n0,"LifecycleRuleFilter",0,[_P,_Ta,_OSGT,_OSLT,"And"],[0,()=>Tag$,1,1,[()=>LifecycleRuleAndOperator$,0]]];ListBucketAnalyticsConfigurationsOutput$=[3,n0,"ListBucketAnalyticsConfigurationsOutput",{[_xN]:"ListBucketAnalyticsConfigurationResult"},[_IT,_CTon,_NCT,_ACLn],[2,0,0,[()=>AnalyticsConfigurationList,{[_xF]:1,[_xN]:_ACn}]]];ListBucketAnalyticsConfigurationsRequest$=[3,n0,"ListBucketAnalyticsConfigurationsRequest",0,[_B,_CTon,_EBO],[[0,1],[0,{[_hQ]:_ct}],[0,{[_hH]:_xaebo}]],1];ListBucketIntelligentTieringConfigurationsOutput$=[3,n0,"ListBucketIntelligentTieringConfigurationsOutput",0,[_IT,_CTon,_NCT,_ITCL],[2,0,0,[()=>IntelligentTieringConfigurationList,{[_xF]:1,[_xN]:_ITC}]]];ListBucketIntelligentTieringConfigurationsRequest$=[3,n0,"ListBucketIntelligentTieringConfigurationsRequest",0,[_B,_CTon,_EBO],[[0,1],[0,{[_hQ]:_ct}],[0,{[_hH]:_xaebo}]],1];ListBucketInventoryConfigurationsOutput$=[3,n0,"ListBucketInventoryConfigurationsOutput",{[_xN]:"ListInventoryConfigurationsResult"},[_CTon,_ICL,_IT,_NCT],[0,[()=>InventoryConfigurationList,{[_xF]:1,[_xN]:_IC}],2,0]];ListBucketInventoryConfigurationsRequest$=[3,n0,"ListBucketInventoryConfigurationsRequest",0,[_B,_CTon,_EBO],[[0,1],[0,{[_hQ]:_ct}],[0,{[_hH]:_xaebo}]],1];ListBucketMetricsConfigurationsOutput$=[3,n0,"ListBucketMetricsConfigurationsOutput",{[_xN]:"ListMetricsConfigurationsResult"},[_IT,_CTon,_NCT,_MCL],[2,0,0,[()=>MetricsConfigurationList,{[_xF]:1,[_xN]:_MCe}]]];ListBucketMetricsConfigurationsRequest$=[3,n0,"ListBucketMetricsConfigurationsRequest",0,[_B,_CTon,_EBO],[[0,1],[0,{[_hQ]:_ct}],[0,{[_hH]:_xaebo}]],1];ListBucketsOutput$=[3,n0,"ListBucketsOutput",{[_xN]:"ListAllMyBucketsResult"},[_Bu,_O,_CTon,_P],[[()=>Buckets,0],()=>Owner$,0,0]];ListBucketsRequest$=[3,n0,"ListBucketsRequest",0,["MaxBuckets",_CTon,_P,_BR],[[1,{[_hQ]:"max-buckets"}],[0,{[_hQ]:_ct}],[0,{[_hQ]:_p}],[0,{[_hQ]:"bucket-region"}]]];ListDirectoryBucketsOutput$=[3,n0,"ListDirectoryBucketsOutput",{[_xN]:"ListAllMyDirectoryBucketsResult"},[_Bu,_CTon],[[()=>Buckets,0],0]];ListDirectoryBucketsRequest$=[3,n0,"ListDirectoryBucketsRequest",0,[_CTon,"MaxDirectoryBuckets"],[[0,{[_hQ]:_ct}],[1,{[_hQ]:"max-directory-buckets"}]]];ListMultipartUploadsOutput$=[3,n0,"ListMultipartUploadsOutput",{[_xN]:"ListMultipartUploadsResult"},[_B,_KM,_UIM,_NKM,_P,_Deli,"NextUploadIdMarker","MaxUploads",_IT,"Uploads",_CPom,_ETn,_RC],[0,0,0,0,0,0,0,1,2,[()=>MultipartUploadList,{[_xF]:1,[_xN]:"Upload"}],[()=>CommonPrefixList,{[_xF]:1}],0,[0,{[_hH]:_xarc}]]];ListMultipartUploadsRequest$=[3,n0,"ListMultipartUploadsRequest",0,[_B,_Deli,_ETn,_KM,"MaxUploads",_P,_UIM,_EBO,_RP],[[0,1],[0,{[_hQ]:_d}],[0,{[_hQ]:_et}],[0,{[_hQ]:_km}],[1,{[_hQ]:"max-uploads"}],[0,{[_hQ]:_p}],[0,{[_hQ]:"upload-id-marker"}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xarp}]],1];ListObjectsOutput$=[3,n0,"ListObjectsOutput",{[_xN]:_LBRi},[_IT,"Marker","NextMarker","Contents",_N,_P,_Deli,_MK,_CPom,_ETn,_RC],[2,0,0,[()=>ObjectList,{[_xF]:1}],0,0,0,1,[()=>CommonPrefixList,{[_xF]:1}],0,[0,{[_hH]:_xarc}]]];ListObjectsRequest$=[3,n0,"ListObjectsRequest",0,[_B,_Deli,_ETn,"Marker",_MK,_P,_RP,_EBO,_OOA],[[0,1],[0,{[_hQ]:_d}],[0,{[_hQ]:_et}],[0,{[_hQ]:"marker"}],[1,{[_hQ]:_mk}],[0,{[_hQ]:_p}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[64,{[_hH]:_xaooa}]],1];ListObjectsV2Output$=[3,n0,"ListObjectsV2Output",{[_xN]:_LBRi},[_IT,"Contents",_N,_P,_Deli,_MK,_CPom,_ETn,"KeyCount",_CTon,_NCT,_SA,_RC],[2,[()=>ObjectList,{[_xF]:1}],0,0,0,1,[()=>CommonPrefixList,{[_xF]:1}],0,1,0,0,0,[0,{[_hH]:_xarc}]]];ListObjectsV2Request$=[3,n0,"ListObjectsV2Request",0,[_B,_Deli,_ETn,_MK,_P,_CTon,"FetchOwner",_SA,_RP,_EBO,_OOA],[[0,1],[0,{[_hQ]:_d}],[0,{[_hQ]:_et}],[1,{[_hQ]:_mk}],[0,{[_hQ]:_p}],[0,{[_hQ]:_ct}],[2,{[_hQ]:"fetch-owner"}],[0,{[_hQ]:"start-after"}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[64,{[_hH]:_xaooa}]],1];ListObjectVersionsOutput$=[3,n0,"ListObjectVersionsOutput",{[_xN]:"ListVersionsResult"},[_IT,_KM,_VIM,_NKM,"NextVersionIdMarker","Versions",_DMe,_N,_P,_Deli,_MK,_CPom,_ETn,_RC],[2,0,0,0,0,[()=>ObjectVersionList,{[_xF]:1,[_xN]:"Version"}],[()=>DeleteMarkers,{[_xF]:1,[_xN]:_DM}],0,0,0,1,[()=>CommonPrefixList,{[_xF]:1}],0,[0,{[_hH]:_xarc}]]];ListObjectVersionsRequest$=[3,n0,"ListObjectVersionsRequest",0,[_B,_Deli,_ETn,_KM,_MK,_P,_VIM,_EBO,_RP,_OOA],[[0,1],[0,{[_hQ]:_d}],[0,{[_hQ]:_et}],[0,{[_hQ]:_km}],[1,{[_hQ]:_mk}],[0,{[_hQ]:_p}],[0,{[_hQ]:"version-id-marker"}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xarp}],[64,{[_hH]:_xaooa}]],1];ListPartsOutput$=[3,n0,"ListPartsOutput",{[_xN]:"ListPartsResult"},["AbortDate","AbortRuleId",_B,_K,_UI,_PNM,_NPNM,_MP,_IT,_Pa,_In,_O,_SC,_RC,_CA,_CT],[[4,{[_hH]:_xaad}],[0,{[_hH]:_xaari}],0,0,0,0,0,1,2,[()=>Parts,{[_xF]:1,[_xN]:"Part"}],()=>Initiator$,()=>Owner$,0,[0,{[_hH]:_xarc}],0,0]];ListPartsRequest$=[3,n0,"ListPartsRequest",0,[_B,_K,_UI,_MP,_PNM,_RP,_EBO,_SSECA,_SSECK,_SSECKMD],[[0,1],[0,1],[0,{[_hQ]:_uI}],[1,{[_hQ]:"max-parts"}],[0,{[_hQ]:"part-number-marker"}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}]],3];LocationInfo$=[3,n0,"LocationInfo",0,[_Ty,_N],[0,0]];LoggingEnabled$=[3,n0,_LE,0,["TargetBucket","TargetPrefix",_TG,_TOKF],[0,0,[()=>TargetGrants,0],[()=>TargetObjectKeyFormat$,0]],2];MetadataConfiguration$=[3,n0,_MC,0,[_JTC,_ITCn],[()=>JournalTableConfiguration$,()=>InventoryTableConfiguration$],1];MetadataConfigurationResult$=[3,n0,_MCR,0,[_DRes,_JTCR,_ITCR],[()=>DestinationResult$,()=>JournalTableConfigurationResult$,()=>InventoryTableConfigurationResult$],1];MetadataEntry$=[3,n0,_ME,0,[_N,_V],[0,0]];MetadataTableConfiguration$=[3,n0,_MTC,0,[_STD],[()=>S3TablesDestination$],1];MetadataTableConfigurationResult$=[3,n0,_MTCR,0,[_STDR],[()=>S3TablesDestinationResult$],1];MetadataTableEncryptionConfiguration$=[3,n0,"MetadataTableEncryptionConfiguration",0,["SseAlgorithm","KmsKeyArn"],[0,0],1];Metrics$=[3,n0,"Metrics",0,[_S,"EventThreshold"],[0,()=>ReplicationTimeValue$],1];MetricsAndOperator$=[3,n0,"MetricsAndOperator",0,[_P,_T,"AccessPointArn"],[0,[()=>TagSet,{[_xF]:1,[_xN]:_Ta}],0]];MetricsConfiguration$=[3,n0,_MCe,0,[_I,_F],[0,[()=>MetricsFilter$,0]],1];MultipartUpload$=[3,n0,_MU,0,[_UI,_K,"Initiated",_SC,_O,_In,_CA,_CT],[0,0,4,0,()=>Owner$,()=>Initiator$,0,0]];NoncurrentVersionExpiration$=[3,n0,_NVE,0,[_ND,_NNV],[1,1]];NoncurrentVersionTransition$=[3,n0,_NVTo,0,[_ND,_SC,_NNV],[1,0,1]];NoSuchBucket$=[-3,n0,"NoSuchBucket",{[_e]:_c2,[_hE]:404},[],[]];TypeRegistry.for(n0).registerError(NoSuchBucket$,NoSuchBucket);NoSuchKey$=[-3,n0,"NoSuchKey",{[_e]:_c2,[_hE]:404},[],[]];TypeRegistry.for(n0).registerError(NoSuchKey$,NoSuchKey);NoSuchUpload$=[-3,n0,"NoSuchUpload",{[_e]:_c2,[_hE]:404},[],[]];TypeRegistry.for(n0).registerError(NoSuchUpload$,NoSuchUpload);NotFound$=[-3,n0,"NotFound",{[_e]:_c2},[],[]];TypeRegistry.for(n0).registerError(NotFound$,NotFound);NotificationConfiguration$=[3,n0,_NC,0,["TopicConfigurations","QueueConfigurations","LambdaFunctionConfigurations",_EBC],[[()=>TopicConfigurationList,{[_xF]:1,[_xN]:_TCop}],[()=>QueueConfigurationList,{[_xF]:1,[_xN]:_QCue}],[()=>LambdaFunctionConfigurationList,{[_xF]:1,[_xN]:"CloudFunctionConfiguration"}],()=>EventBridgeConfiguration$]];NotificationConfigurationFilter$=[3,n0,"NotificationConfigurationFilter",0,[_K],[[()=>S3KeyFilter$,{[_xN]:"S3Key"}]]];_Object$=[3,n0,"Object",0,[_K,_LM,_ETa,_CA,_CT,_Si,_SC,_O,_RSe],[0,4,0,[64,{[_xF]:1}],0,1,0,()=>Owner$,()=>RestoreStatus$]];ObjectAlreadyInActiveTierError$=[-3,n0,"ObjectAlreadyInActiveTierError",{[_e]:_c2,[_hE]:403},[],[]];TypeRegistry.for(n0).registerError(ObjectAlreadyInActiveTierError$,ObjectAlreadyInActiveTierError);ObjectIdentifier$=[3,n0,"ObjectIdentifier",0,[_K,_VI,_ETa,"LastModifiedTime",_Si],[0,0,0,6,1],1];ObjectLockConfiguration$=[3,n0,_OLC,0,["ObjectLockEnabled",_Ru],[0,()=>ObjectLockRule$]];ObjectLockLegalHold$=[3,n0,"ObjectLockLegalHold",0,[_S],[0]];ObjectLockRetention$=[3,n0,"ObjectLockRetention",0,["Mode","RetainUntilDate"],[0,5]];ObjectLockRule$=[3,n0,"ObjectLockRule",0,[_DRe],[()=>DefaultRetention$]];ObjectNotInActiveTierError$=[-3,n0,"ObjectNotInActiveTierError",{[_e]:_c2,[_hE]:403},[],[]];TypeRegistry.for(n0).registerError(ObjectNotInActiveTierError$,ObjectNotInActiveTierError);ObjectPart$=[3,n0,"ObjectPart",0,[_PN,_Si,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh],[1,1,0,0,0,0,0]];ObjectVersion$=[3,n0,"ObjectVersion",0,[_ETa,_CA,_CT,_Si,_SC,_K,_VI,"IsLatest",_LM,_O,_RSe],[0,[64,{[_xF]:1}],0,1,0,0,0,2,4,()=>Owner$,()=>RestoreStatus$]];OutputLocation$=[3,n0,_OL,0,["S3"],[[()=>S3Location$,0]]];OutputSerialization$=[3,n0,_OSu,0,["CSV","JSON"],[()=>CSVOutput$,()=>JSONOutput$]];Owner$=[3,n0,_O,0,[_DN,"ID"],[0,0]];OwnershipControls$=[3,n0,_OC,0,[_R],[[()=>OwnershipControlsRules,{[_xF]:1,[_xN]:_Ru}]],1];OwnershipControlsRule$=[3,n0,"OwnershipControlsRule",0,[_OO],[0],1];ParquetInput$=[3,n0,"ParquetInput",0,[],[]];Part$=[3,n0,"Part",0,[_PN,_LM,_ETa,_Si,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh],[1,4,0,1,0,0,0,0,0]];PartitionedPrefix$=[3,n0,_PP,{[_xN]:_PP},["PartitionDateSource"],[0]];PolicyStatus$=[3,n0,_PS,0,["IsPublic"],[[2,{[_xN]:"IsPublic"}]]];Progress$=[3,n0,"Progress",0,[_BS,_BP,_BRy],[1,1,1]];ProgressEvent$=[3,n0,"ProgressEvent",0,["Details"],[[()=>Progress$,{[_eP]:1}]]];PublicAccessBlockConfiguration$=[3,n0,_PABC,0,[_BPA,_IPA,_BPP,_RPB],[[2,{[_xN]:_BPA}],[2,{[_xN]:_IPA}],[2,{[_xN]:_BPP}],[2,{[_xN]:_RPB}]]];PutBucketAbacRequest$=[3,n0,"PutBucketAbacRequest",0,[_B,_AS,_CMD,_CA,_EBO],[[0,1],[()=>AbacStatus$,{[_hP]:1,[_xN]:_AS}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutBucketAccelerateConfigurationRequest$=[3,n0,"PutBucketAccelerateConfigurationRequest",0,[_B,_AC,_EBO,_CA],[[0,1],[()=>AccelerateConfiguration$,{[_hP]:1,[_xN]:_AC}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xasca}]],2];PutBucketAclRequest$=[3,n0,"PutBucketAclRequest",0,[_B,"ACL",_ACP,_CMD,_CA,_GFC,_GR,_GRACP,_GW,_GWACP,_EBO],[[0,1],[0,{[_hH]:_xaa}],[()=>AccessControlPolicy$,{[_hP]:1,[_xN]:_ACP}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xagfc}],[0,{[_hH]:_xagr}],[0,{[_hH]:_xagra}],[0,{[_hH]:_xagw}],[0,{[_hH]:_xagwa}],[0,{[_hH]:_xaebo}]],1];PutBucketAnalyticsConfigurationRequest$=[3,n0,"PutBucketAnalyticsConfigurationRequest",0,[_B,_I,_ACn,_EBO],[[0,1],[0,{[_hQ]:_i}],[()=>AnalyticsConfiguration$,{[_hP]:1,[_xN]:_ACn}],[0,{[_hH]:_xaebo}]],3];PutBucketCorsRequest$=[3,n0,"PutBucketCorsRequest",0,[_B,_CORSC,_CMD,_CA,_EBO],[[0,1],[()=>CORSConfiguration$,{[_hP]:1,[_xN]:_CORSC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutBucketEncryptionRequest$=[3,n0,"PutBucketEncryptionRequest",0,[_B,_SSEC,_CMD,_CA,_EBO],[[0,1],[()=>ServerSideEncryptionConfiguration$,{[_hP]:1,[_xN]:_SSEC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutBucketIntelligentTieringConfigurationRequest$=[3,n0,"PutBucketIntelligentTieringConfigurationRequest",0,[_B,_I,_ITC,_EBO],[[0,1],[0,{[_hQ]:_i}],[()=>IntelligentTieringConfiguration$,{[_hP]:1,[_xN]:_ITC}],[0,{[_hH]:_xaebo}]],3];PutBucketInventoryConfigurationRequest$=[3,n0,"PutBucketInventoryConfigurationRequest",0,[_B,_I,_IC,_EBO],[[0,1],[0,{[_hQ]:_i}],[()=>InventoryConfiguration$,{[_hP]:1,[_xN]:_IC}],[0,{[_hH]:_xaebo}]],3];PutBucketLifecycleConfigurationOutput$=[3,n0,"PutBucketLifecycleConfigurationOutput",0,[_TDMOS],[[0,{[_hH]:_xatdmos}]]];PutBucketLifecycleConfigurationRequest$=[3,n0,"PutBucketLifecycleConfigurationRequest",0,[_B,_CA,_LCi,_EBO,_TDMOS],[[0,1],[0,{[_hH]:_xasca}],[()=>BucketLifecycleConfiguration$,{[_hP]:1,[_xN]:_LCi}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xatdmos}]],1];PutBucketLoggingRequest$=[3,n0,"PutBucketLoggingRequest",0,[_B,_BLS,_CMD,_CA,_EBO],[[0,1],[()=>BucketLoggingStatus$,{[_hP]:1,[_xN]:_BLS}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutBucketMetricsConfigurationRequest$=[3,n0,"PutBucketMetricsConfigurationRequest",0,[_B,_I,_MCe,_EBO],[[0,1],[0,{[_hQ]:_i}],[()=>MetricsConfiguration$,{[_hP]:1,[_xN]:_MCe}],[0,{[_hH]:_xaebo}]],3];PutBucketNotificationConfigurationRequest$=[3,n0,"PutBucketNotificationConfigurationRequest",0,[_B,_NC,_EBO,"SkipDestinationValidation"],[[0,1],[()=>NotificationConfiguration$,{[_hP]:1,[_xN]:_NC}],[0,{[_hH]:_xaebo}],[2,{[_hH]:"x-amz-skip-destination-validation"}]],2];PutBucketOwnershipControlsRequest$=[3,n0,"PutBucketOwnershipControlsRequest",0,[_B,_OC,_CMD,_EBO,_CA],[[0,1],[()=>OwnershipControls$,{[_hP]:1,[_xN]:_OC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xasca}]],2];PutBucketPolicyRequest$=[3,n0,"PutBucketPolicyRequest",0,[_B,"Policy",_CMD,_CA,"ConfirmRemoveSelfBucketAccess",_EBO],[[0,1],[0,16],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[2,{[_hH]:"x-amz-confirm-remove-self-bucket-access"}],[0,{[_hH]:_xaebo}]],2];PutBucketReplicationRequest$=[3,n0,"PutBucketReplicationRequest",0,[_B,_RCe,_CMD,_CA,"Token",_EBO],[[0,1],[()=>ReplicationConfiguration$,{[_hP]:1,[_xN]:_RCe}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xabolt}],[0,{[_hH]:_xaebo}]],2];PutBucketRequestPaymentRequest$=[3,n0,"PutBucketRequestPaymentRequest",0,[_B,_RPC,_CMD,_CA,_EBO],[[0,1],[()=>RequestPaymentConfiguration$,{[_hP]:1,[_xN]:_RPC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutBucketTaggingRequest$=[3,n0,"PutBucketTaggingRequest",0,[_B,_Tag,_CMD,_CA,_EBO],[[0,1],[()=>Tagging$,{[_hP]:1,[_xN]:_Tag}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutBucketVersioningRequest$=[3,n0,"PutBucketVersioningRequest",0,[_B,_VC,_CMD,_CA,"MFA",_EBO],[[0,1],[()=>VersioningConfiguration$,{[_hP]:1,[_xN]:_VC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:"x-amz-mfa"}],[0,{[_hH]:_xaebo}]],2];PutBucketWebsiteRequest$=[3,n0,"PutBucketWebsiteRequest",0,[_B,_WC,_CMD,_CA,_EBO],[[0,1],[()=>WebsiteConfiguration$,{[_hP]:1,[_xN]:_WC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutObjectAclOutput$=[3,n0,"PutObjectAclOutput",0,[_RC],[[0,{[_hH]:_xarc}]]];PutObjectAclRequest$=[3,n0,"PutObjectAclRequest",0,[_B,_K,"ACL",_ACP,_CMD,_CA,_GFC,_GR,_GRACP,_GW,_GWACP,_RP,_VI,_EBO],[[0,1],[0,1],[0,{[_hH]:_xaa}],[()=>AccessControlPolicy$,{[_hP]:1,[_xN]:_ACP}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xagfc}],[0,{[_hH]:_xagr}],[0,{[_hH]:_xagra}],[0,{[_hH]:_xagw}],[0,{[_hH]:_xagwa}],[0,{[_hH]:_xarp}],[0,{[_hQ]:_vI}],[0,{[_hH]:_xaebo}]],2];PutObjectLegalHoldOutput$=[3,n0,"PutObjectLegalHoldOutput",0,[_RC],[[0,{[_hH]:_xarc}]]];PutObjectLegalHoldRequest$=[3,n0,"PutObjectLegalHoldRequest",0,[_B,_K,_LH,_RP,_VI,_CMD,_CA,_EBO],[[0,1],[0,1],[()=>ObjectLockLegalHold$,{[_hP]:1,[_xN]:_LH}],[0,{[_hH]:_xarp}],[0,{[_hQ]:_vI}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutObjectLockConfigurationOutput$=[3,n0,"PutObjectLockConfigurationOutput",0,[_RC],[[0,{[_hH]:_xarc}]]];PutObjectLockConfigurationRequest$=[3,n0,"PutObjectLockConfigurationRequest",0,[_B,_OLC,_RP,"Token",_CMD,_CA,_EBO],[[0,1],[()=>ObjectLockConfiguration$,{[_hP]:1,[_xN]:_OLC}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xabolt}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],1];PutObjectOutput$=[3,n0,"PutObjectOutput",0,[_E,_ETa,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_CT,_SSE,_VI,_SSECA,_SSECKMD,_SSEKMSKI,_SSEKMSEC,_BKE,_Si,_RC],[[0,{[_hH]:_xae}],[0,{[_hH]:_ETa}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[0,{[_hH]:_xact}],[0,{[_hH]:_xasse}],[0,{[_hH]:_xavi}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}],[1,{[_hH]:"x-amz-object-size"}],[0,{[_hH]:_xarc}]]];PutObjectRequest$=[3,n0,"PutObjectRequest",0,[_B,_K,"ACL",_Bo,_CC,_CDo,_CEo,_CL,_CLo,_CMD,_CTo,_CA,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_Ex,_IM,_INM,_GFC,_GR,_GRACP,_GWACP,"WriteOffsetBytes",_M,_SSE,_SC,_WRL,_SSECA,_SSECK,_SSECKMD,_SSEKMSKI,_SSEKMSEC,_BKE,_RP,_Tag,_OLM,_OLRUD,_OLLHS,_EBO],[[0,1],[0,1],[0,{[_hH]:_xaa}],[()=>StreamingBlob,16],[0,{[_hH]:_CC_}],[0,{[_hH]:_CD_}],[0,{[_hH]:_CE_}],[0,{[_hH]:_CL_}],[1,{[_hH]:_CL__}],[0,{[_hH]:_CM}],[0,{[_hH]:_CT_}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[4,{[_hH]:_Ex}],[0,{[_hH]:_IM_}],[0,{[_hH]:_INM_}],[0,{[_hH]:_xagfc}],[0,{[_hH]:_xagr}],[0,{[_hH]:_xagra}],[0,{[_hH]:_xagwa}],[1,{[_hH]:"x-amz-write-offset-bytes"}],[128,{[_hPH]:_xam}],[0,{[_hH]:_xasse}],[0,{[_hH]:_xasc}],[0,{[_hH]:_xawrl}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[()=>SSEKMSEncryptionContext,{[_hH]:_xassec}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xat}],[0,{[_hH]:_xaolm}],[5,{[_hH]:_xaolrud}],[0,{[_hH]:_xaollh}],[0,{[_hH]:_xaebo}]],2];PutObjectRetentionOutput$=[3,n0,"PutObjectRetentionOutput",0,[_RC],[[0,{[_hH]:_xarc}]]];PutObjectRetentionRequest$=[3,n0,"PutObjectRetentionRequest",0,[_B,_K,_Ret,_RP,_VI,_BGR,_CMD,_CA,_EBO],[[0,1],[0,1],[()=>ObjectLockRetention$,{[_hP]:1,[_xN]:_Ret}],[0,{[_hH]:_xarp}],[0,{[_hQ]:_vI}],[2,{[_hH]:_xabgr}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];PutObjectTaggingOutput$=[3,n0,"PutObjectTaggingOutput",0,[_VI],[[0,{[_hH]:_xavi}]]];PutObjectTaggingRequest$=[3,n0,"PutObjectTaggingRequest",0,[_B,_K,_Tag,_VI,_CMD,_CA,_EBO,_RP],[[0,1],[0,1],[()=>Tagging$,{[_hP]:1,[_xN]:_Tag}],[0,{[_hQ]:_vI}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xarp}]],3];PutPublicAccessBlockRequest$=[3,n0,"PutPublicAccessBlockRequest",0,[_B,_PABC,_CMD,_CA,_EBO],[[0,1],[()=>PublicAccessBlockConfiguration$,{[_hP]:1,[_xN]:_PABC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];QueueConfiguration$=[3,n0,_QCue,0,["QueueArn",_Ev,_I,_F],[[0,{[_xN]:"Queue"}],[64,{[_xF]:1,[_xN]:"Event"}],0,[()=>NotificationConfigurationFilter$,0]],2];RecordExpiration$=[3,n0,_REe,0,[_E,_D],[0,1],1];RecordsEvent$=[3,n0,"RecordsEvent",0,["Payload"],[[21,{[_eP]:1}]]];Redirect$=[3,n0,"Redirect",0,["HostName","HttpRedirectCode","Protocol","ReplaceKeyPrefixWith","ReplaceKeyWith"],[0,0,0,0,0]];RedirectAllRequestsTo$=[3,n0,_RART,0,["HostName","Protocol"],[0,0],1];RenameObjectOutput$=[3,n0,"RenameObjectOutput",0,[],[]];RenameObjectRequest$=[3,n0,"RenameObjectRequest",0,[_B,_K,"RenameSource","DestinationIfMatch","DestinationIfNoneMatch","DestinationIfModifiedSince","DestinationIfUnmodifiedSince","SourceIfMatch","SourceIfNoneMatch","SourceIfModifiedSince","SourceIfUnmodifiedSince","ClientToken"],[[0,1],[0,1],[0,{[_hH]:"x-amz-rename-source"}],[0,{[_hH]:_IM_}],[0,{[_hH]:_INM_}],[4,{[_hH]:_IMS_}],[4,{[_hH]:_IUS_}],[0,{[_hH]:"x-amz-rename-source-if-match"}],[0,{[_hH]:"x-amz-rename-source-if-none-match"}],[6,{[_hH]:"x-amz-rename-source-if-modified-since"}],[6,{[_hH]:"x-amz-rename-source-if-unmodified-since"}],[0,{[_hH]:"x-amz-client-token",[_iT]:1}]],3];ReplicaModifications$=[3,n0,_RM,0,[_S],[0],1];ReplicationConfiguration$=[3,n0,_RCe,0,["Role",_R],[0,[()=>ReplicationRules,{[_xF]:1,[_xN]:_Ru}]],2];ReplicationRule$=[3,n0,"ReplicationRule",0,[_S,_Des,"ID","Priority",_P,_F,_SSC,_EOR,_DMR],[0,()=>Destination$,0,1,0,[()=>ReplicationRuleFilter$,0],()=>SourceSelectionCriteria$,()=>ExistingObjectReplication$,()=>DeleteMarkerReplication$],2];ReplicationRuleAndOperator$=[3,n0,"ReplicationRuleAndOperator",0,[_P,_T],[0,[()=>TagSet,{[_xF]:1,[_xN]:_Ta}]]];ReplicationRuleFilter$=[3,n0,"ReplicationRuleFilter",0,[_P,_Ta,"And"],[0,()=>Tag$,[()=>ReplicationRuleAndOperator$,0]]];ReplicationTime$=[3,n0,_RT,0,[_S,"Time"],[0,()=>ReplicationTimeValue$],2];ReplicationTimeValue$=[3,n0,"ReplicationTimeValue",0,["Minutes"],[1]];RequestPaymentConfiguration$=[3,n0,_RPC,0,["Payer"],[0],1];RequestProgress$=[3,n0,_RPe,0,["Enabled"],[2]];RestoreObjectOutput$=[3,n0,"RestoreObjectOutput",0,[_RC,"RestoreOutputPath"],[[0,{[_hH]:_xarc}],[0,{[_hH]:"x-amz-restore-output-path"}]]];RestoreObjectRequest$=[3,n0,"RestoreObjectRequest",0,[_B,_K,_VI,_RRes,_RP,_CA,_EBO],[[0,1],[0,1],[0,{[_hQ]:_vI}],[()=>RestoreRequest$,{[_hP]:1,[_xN]:_RRes}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];RestoreRequest$=[3,n0,_RRes,0,[_D,_GJP,_Ty,"Tier","Description",_SP,_OL],[1,()=>GlacierJobParameters$,0,0,0,()=>SelectParameters$,[()=>OutputLocation$,0]]];RestoreStatus$=[3,n0,_RSe,0,["IsRestoreInProgress","RestoreExpiryDate"],[2,4]];RoutingRule$=[3,n0,"RoutingRule",0,["Redirect","Condition"],[()=>Redirect$,()=>Condition$],1];S3KeyFilter$=[3,n0,"S3KeyFilter",0,["FilterRules"],[[()=>FilterRuleList,{[_xF]:1,[_xN]:_FR}]]];S3Location$=[3,n0,"S3Location",0,["BucketName",_P,_En,"CannedACL",_ACL,_Tag,_UM,_SC],[0,0,[()=>Encryption$,0],0,[()=>Grants,0],[()=>Tagging$,0],[()=>UserMetadata,0],0],2];S3TablesDestination$=[3,n0,_STD,0,[_TBA,_TNa],[0,0],2];S3TablesDestinationResult$=[3,n0,_STDR,0,[_TBA,_TNa,_TA,_TN],[0,0,0,0],4];ScanRange$=[3,n0,"ScanRange",0,["Start","End"],[1,1]];SelectObjectContentOutput$=[3,n0,"SelectObjectContentOutput",0,["Payload"],[[()=>SelectObjectContentEventStream$,16]]];SelectObjectContentRequest$=[3,n0,"SelectObjectContentRequest",0,[_B,_K,"Expression",_ETx,_IS,_OSu,_SSECA,_SSECK,_SSECKMD,_RPe,"ScanRange",_EBO],[[0,1],[0,1],0,0,()=>InputSerialization$,()=>OutputSerialization$,[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],()=>RequestProgress$,()=>ScanRange$,[0,{[_hH]:_xaebo}]],6];SelectParameters$=[3,n0,_SP,0,[_IS,_ETx,"Expression",_OSu],[()=>InputSerialization$,0,0,()=>OutputSerialization$],4];ServerSideEncryptionByDefault$=[3,n0,"ServerSideEncryptionByDefault",0,["SSEAlgorithm","KMSMasterKeyID"],[0,[()=>SSEKMSKeyId,0]],1];ServerSideEncryptionConfiguration$=[3,n0,_SSEC,0,[_R],[[()=>ServerSideEncryptionRules,{[_xF]:1,[_xN]:_Ru}]],1];ServerSideEncryptionRule$=[3,n0,"ServerSideEncryptionRule",0,["ApplyServerSideEncryptionByDefault",_BKE,_BET],[[()=>ServerSideEncryptionByDefault$,0],2,[()=>BlockedEncryptionTypes$,0]]];SessionCredentials$=[3,n0,"SessionCredentials",0,["AccessKeyId",_SAK,_ST,_E],[[0,{[_xN]:"AccessKeyId"}],[()=>SessionCredentialValue,{[_xN]:_SAK}],[()=>SessionCredentialValue,{[_xN]:_ST}],[4,{[_xN]:_E}]],4];SimplePrefix$=[3,n0,_SPi,{[_xN]:_SPi},[],[]];SourceSelectionCriteria$=[3,n0,_SSC,0,[_SKEO,_RM],[()=>SseKmsEncryptedObjects$,()=>ReplicaModifications$]];SSEKMS$=[3,n0,"SSEKMS",{[_xN]:_SK},["KeyId"],[[()=>SSEKMSKeyId,0]],1];SseKmsEncryptedObjects$=[3,n0,_SKEO,0,[_S],[0],1];SSEKMSEncryption$=[3,n0,"SSEKMSEncryption",{[_xN]:_SK},["KMSKeyArn",_BKE],[[()=>NonEmptyKmsKeyArnString,0],2],1];SSES3$=[3,n0,"SSES3",{[_xN]:"SSE-S3"},[],[]];Stats$=[3,n0,"Stats",0,[_BS,_BP,_BRy],[1,1,1]];StatsEvent$=[3,n0,"StatsEvent",0,["Details"],[[()=>Stats$,{[_eP]:1}]]];StorageClassAnalysis$=[3,n0,_SCA,0,["DataExport"],[()=>StorageClassAnalysisDataExport$]];StorageClassAnalysisDataExport$=[3,n0,"StorageClassAnalysisDataExport",0,["OutputSchemaVersion",_Des],[0,()=>AnalyticsExportDestination$],2];Tag$=[3,n0,_Ta,0,[_K,_V],[0,0],2];Tagging$=[3,n0,_Tag,0,[_TS],[[()=>TagSet,0]],1];TargetGrant$=[3,n0,"TargetGrant",0,["Grantee",_Pe],[[()=>Grantee$,{[_xNm]:["xsi",_hi]}],0]];TargetObjectKeyFormat$=[3,n0,_TOKF,0,[_SPi,_PP],[[()=>SimplePrefix$,{[_xN]:_SPi}],[()=>PartitionedPrefix$,{[_xN]:_PP}]]];Tiering$=[3,n0,"Tiering",0,[_D,_AT],[1,0],2];TooManyParts$=[-3,n0,"TooManyParts",{[_e]:_c2,[_hE]:400},[],[]];TypeRegistry.for(n0).registerError(TooManyParts$,TooManyParts);TopicConfiguration$=[3,n0,_TCop,0,["TopicArn",_Ev,_I,_F],[[0,{[_xN]:"Topic"}],[64,{[_xF]:1,[_xN]:"Event"}],0,[()=>NotificationConfigurationFilter$,0]],2];Transition$=[3,n0,"Transition",0,["Date",_D,_SC],[5,1,0]];UpdateBucketMetadataInventoryTableConfigurationRequest$=[3,n0,"UpdateBucketMetadataInventoryTableConfigurationRequest",0,[_B,_ITCn,_CMD,_CA,_EBO],[[0,1],[()=>InventoryTableConfigurationUpdates$,{[_hP]:1,[_xN]:_ITCn}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];UpdateBucketMetadataJournalTableConfigurationRequest$=[3,n0,"UpdateBucketMetadataJournalTableConfigurationRequest",0,[_B,_JTC,_CMD,_CA,_EBO],[[0,1],[()=>JournalTableConfigurationUpdates$,{[_hP]:1,[_xN]:_JTC}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xaebo}]],2];UpdateObjectEncryptionRequest$=[3,n0,"UpdateObjectEncryptionRequest",0,[_B,_K,_OE,_VI,_RP,_EBO,_CMD,_CA],[[0,1],[0,1],[()=>ObjectEncryption$,16],[0,{[_hQ]:_vI}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}]],3];UpdateObjectEncryptionResponse$=[3,n0,"UpdateObjectEncryptionResponse",0,[_RC],[[0,{[_hH]:_xarc}]]];UploadPartCopyOutput$=[3,n0,"UploadPartCopyOutput",0,[_CSVI,_CPR,_SSE,_SSECA,_SSECKMD,_SSEKMSKI,_BKE,_RC],[[0,{[_hH]:_xacsvi}],[()=>CopyPartResult$,16],[0,{[_hH]:_xasse}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarc}]]];UploadPartCopyRequest$=[3,n0,"UploadPartCopyRequest",0,[_B,_CS,_K,_PN,_UI,_CSIM,_CSIMS,_CSINM,_CSIUS,"CopySourceRange",_SSECA,_SSECK,_SSECKMD,_CSSSECA,"CopySourceSSECustomerKey","CopySourceSSECustomerKeyMD5",_RP,_EBO,_ESBO],[[0,1],[0,{[_hH]:"x-amz-copy-source"}],[0,1],[1,{[_hQ]:_pN}],[0,{[_hQ]:_uI}],[0,{[_hH]:_xacsim}],[4,{[_hH]:_xacsims}],[0,{[_hH]:_xacsinm}],[4,{[_hH]:_xacsius}],[0,{[_hH]:"x-amz-copy-source-range"}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[0,{[_hH]:_xacssseca}],[()=>CopySourceSSECustomerKey,{[_hH]:_xacssseck}],[0,{[_hH]:_xacssseckM}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}],[0,{[_hH]:_xasebo}]],5];UploadPartOutput$=[3,n0,"UploadPartOutput",0,[_SSE,_ETa,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_SSECA,_SSECKMD,_SSEKMSKI,_BKE,_RC],[[0,{[_hH]:_xasse}],[0,{[_hH]:_ETa}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[0,{[_hH]:_xasseca}],[0,{[_hH]:_xasseckM}],[()=>SSEKMSKeyId,{[_hH]:_xasseakki}],[2,{[_hH]:_xassebke}],[0,{[_hH]:_xarc}]]];UploadPartRequest$=[3,n0,"UploadPartRequest",0,[_B,_K,_PN,_UI,_Bo,_CLo,_CMD,_CA,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_SSECA,_SSECK,_SSECKMD,_RP,_EBO],[[0,1],[0,1],[1,{[_hQ]:_pN}],[0,{[_hQ]:_uI}],[()=>StreamingBlob,16],[1,{[_hH]:_CL__}],[0,{[_hH]:_CM}],[0,{[_hH]:_xasca}],[0,{[_hH]:_xacc}],[0,{[_hH]:_xacc_}],[0,{[_hH]:_xacc__}],[0,{[_hH]:_xacs}],[0,{[_hH]:_xacs_}],[0,{[_hH]:_xasseca}],[()=>SSECustomerKey,{[_hH]:_xasseck}],[0,{[_hH]:_xasseckM}],[0,{[_hH]:_xarp}],[0,{[_hH]:_xaebo}]],4];VersioningConfiguration$=[3,n0,_VC,0,["MFADelete",_S],[[0,{[_xN]:"MfaDelete"}],0]];WebsiteConfiguration$=[3,n0,_WC,0,[_EDr,_IDn,_RART,_RR],[()=>ErrorDocument$,()=>IndexDocument$,()=>RedirectAllRequestsTo$,[()=>RoutingRules,0]]];WriteGetObjectResponseRequest$=[3,n0,"WriteGetObjectResponseRequest",0,["RequestRoute","RequestToken",_Bo,"StatusCode","ErrorCode",_EM,_AR,_CC,_CDo,_CEo,_CL,_CLo,_CR,_CTo,_CCRC,_CCRCC,_CCRCNVME,_CSHA,_CSHAh,_DM,_ETa,_Ex,_E,_LM,_MM,_M,_OLM,_OLLHS,_OLRUD,_PC,_RS,_RC,_Re,_SSE,_SSECA,_SSEKMSKI,_SSECKMD,_SC,_TC,_VI,_BKE],[[0,{[_hL]:1,[_hH]:"x-amz-request-route"}],[0,{[_hH]:"x-amz-request-token"}],[()=>StreamingBlob,16],[1,{[_hH]:"x-amz-fwd-status"}],[0,{[_hH]:"x-amz-fwd-error-code"}],[0,{[_hH]:"x-amz-fwd-error-message"}],[0,{[_hH]:"x-amz-fwd-header-accept-ranges"}],[0,{[_hH]:"x-amz-fwd-header-Cache-Control"}],[0,{[_hH]:"x-amz-fwd-header-Content-Disposition"}],[0,{[_hH]:"x-amz-fwd-header-Content-Encoding"}],[0,{[_hH]:"x-amz-fwd-header-Content-Language"}],[1,{[_hH]:_CL__}],[0,{[_hH]:"x-amz-fwd-header-Content-Range"}],[0,{[_hH]:"x-amz-fwd-header-Content-Type"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-checksum-crc32"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-checksum-crc32c"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-checksum-crc64nvme"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-checksum-sha1"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-checksum-sha256"}],[2,{[_hH]:"x-amz-fwd-header-x-amz-delete-marker"}],[0,{[_hH]:"x-amz-fwd-header-ETag"}],[4,{[_hH]:"x-amz-fwd-header-Expires"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-expiration"}],[4,{[_hH]:"x-amz-fwd-header-Last-Modified"}],[1,{[_hH]:"x-amz-fwd-header-x-amz-missing-meta"}],[128,{[_hPH]:_xam}],[0,{[_hH]:"x-amz-fwd-header-x-amz-object-lock-mode"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-object-lock-legal-hold"}],[5,{[_hH]:"x-amz-fwd-header-x-amz-object-lock-retain-until-date"}],[1,{[_hH]:"x-amz-fwd-header-x-amz-mp-parts-count"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-replication-status"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-request-charged"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-restore"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-server-side-encryption"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-server-side-encryption-customer-algorithm"}],[()=>SSEKMSKeyId,{[_hH]:"x-amz-fwd-header-x-amz-server-side-encryption-aws-kms-key-id"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-server-side-encryption-customer-key-MD5"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-storage-class"}],[1,{[_hH]:"x-amz-fwd-header-x-amz-tagging-count"}],[0,{[_hH]:"x-amz-fwd-header-x-amz-version-id"}],[2,{[_hH]:"x-amz-fwd-header-x-amz-server-side-encryption-bucket-key-enabled"}]],2];S3ServiceException$=[-3,_sm,"S3ServiceException",0,[],[]];TypeRegistry.for(_sm).registerError(S3ServiceException$,S3ServiceException);AnalyticsConfigurationList=[1,n0,_ACLn,0,[()=>AnalyticsConfiguration$,0]];Buckets=[1,n0,_Bu,0,[()=>Bucket$,{[_xN]:_B}]];CommonPrefixList=[1,n0,"CommonPrefixList",0,()=>CommonPrefix$];CompletedPartList=[1,n0,"CompletedPartList",0,()=>CompletedPart$];CORSRules=[1,n0,"CORSRules",0,[()=>CORSRule$,0]];DeletedObjects=[1,n0,"DeletedObjects",0,()=>DeletedObject$];DeleteMarkers=[1,n0,_DMe,0,()=>DeleteMarkerEntry$];EncryptionTypeList=[1,n0,"EncryptionTypeList",0,[0,{[_xN]:_ET}]];Errors=[1,n0,"Errors",0,()=>_Error$];FilterRuleList=[1,n0,"FilterRuleList",0,()=>FilterRule$];Grants=[1,n0,_G,0,[()=>Grant$,{[_xN]:"Grant"}]];IntelligentTieringConfigurationList=[1,n0,_ITCL,0,[()=>IntelligentTieringConfiguration$,0]];InventoryConfigurationList=[1,n0,_ICL,0,[()=>InventoryConfiguration$,0]];InventoryOptionalFields=[1,n0,"InventoryOptionalFields",0,[0,{[_xN]:"Field"}]];LambdaFunctionConfigurationList=[1,n0,"LambdaFunctionConfigurationList",0,[()=>LambdaFunctionConfiguration$,0]];LifecycleRules=[1,n0,"LifecycleRules",0,[()=>LifecycleRule$,0]];MetricsConfigurationList=[1,n0,_MCL,0,[()=>MetricsConfiguration$,0]];MultipartUploadList=[1,n0,"MultipartUploadList",0,()=>MultipartUpload$];NoncurrentVersionTransitionList=[1,n0,"NoncurrentVersionTransitionList",0,()=>NoncurrentVersionTransition$];ObjectIdentifierList=[1,n0,"ObjectIdentifierList",0,()=>ObjectIdentifier$];ObjectList=[1,n0,"ObjectList",0,[()=>_Object$,0]];ObjectVersionList=[1,n0,"ObjectVersionList",0,[()=>ObjectVersion$,0]];OwnershipControlsRules=[1,n0,"OwnershipControlsRules",0,()=>OwnershipControlsRule$];Parts=[1,n0,_Pa,0,()=>Part$];PartsList=[1,n0,"PartsList",0,()=>ObjectPart$];QueueConfigurationList=[1,n0,"QueueConfigurationList",0,[()=>QueueConfiguration$,0]];ReplicationRules=[1,n0,"ReplicationRules",0,[()=>ReplicationRule$,0]];RoutingRules=[1,n0,_RR,0,[()=>RoutingRule$,{[_xN]:"RoutingRule"}]];ServerSideEncryptionRules=[1,n0,"ServerSideEncryptionRules",0,[()=>ServerSideEncryptionRule$,0]];TagSet=[1,n0,_TS,0,[()=>Tag$,{[_xN]:_Ta}]];TargetGrants=[1,n0,_TG,0,[()=>TargetGrant$,{[_xN]:"Grant"}]];TieringList=[1,n0,"TieringList",0,()=>Tiering$];TopicConfigurationList=[1,n0,"TopicConfigurationList",0,[()=>TopicConfiguration$,0]];TransitionList=[1,n0,"TransitionList",0,()=>Transition$];UserMetadata=[1,n0,_UM,0,[()=>MetadataEntry$,{[_xN]:_ME}]];AnalyticsFilter$=[4,n0,"AnalyticsFilter",0,[_P,_Ta,"And"],[0,()=>Tag$,[()=>AnalyticsAndOperator$,0]]];MetricsFilter$=[4,n0,"MetricsFilter",0,[_P,_Ta,"AccessPointArn","And"],[0,()=>Tag$,0,[()=>MetricsAndOperator$,0]]];ObjectEncryption$=[4,n0,_OE,0,["SSEKMS"],[[()=>SSEKMSEncryption$,{[_xN]:_SK}]]];SelectObjectContentEventStream$=[4,n0,"SelectObjectContentEventStream",{[_s]:1},["Records","Stats","Progress","Cont","End"],[[()=>RecordsEvent$,0],[()=>StatsEvent$,0],[()=>ProgressEvent$,0],()=>ContinuationEvent$,()=>EndEvent$]];AbortMultipartUpload$=[9,n0,"AbortMultipartUpload",{[_h]:["DELETE","/{Key+}?x-id=AbortMultipartUpload",204]},()=>AbortMultipartUploadRequest$,()=>AbortMultipartUploadOutput$];CompleteMultipartUpload$=[9,n0,_CMUo,{[_h]:["POST","/{Key+}",200]},()=>CompleteMultipartUploadRequest$,()=>CompleteMultipartUploadOutput$];CopyObject$=[9,n0,"CopyObject",{[_h]:["PUT","/{Key+}?x-id=CopyObject",200]},()=>CopyObjectRequest$,()=>CopyObjectOutput$];CreateBucket$=[9,n0,"CreateBucket",{[_h]:["PUT","/",200]},()=>CreateBucketRequest$,()=>CreateBucketOutput$];CreateBucketMetadataConfiguration$=[9,n0,"CreateBucketMetadataConfiguration",{[_hC]:"-",[_h]:["POST","/?metadataConfiguration",200]},()=>CreateBucketMetadataConfigurationRequest$,()=>"unit"];CreateBucketMetadataTableConfiguration$=[9,n0,"CreateBucketMetadataTableConfiguration",{[_hC]:"-",[_h]:["POST","/?metadataTable",200]},()=>CreateBucketMetadataTableConfigurationRequest$,()=>"unit"];CreateMultipartUpload$=[9,n0,"CreateMultipartUpload",{[_h]:["POST","/{Key+}?uploads",200]},()=>CreateMultipartUploadRequest$,()=>CreateMultipartUploadOutput$];CreateSession$=[9,n0,"CreateSession",{[_h]:["GET","/?session",200]},()=>CreateSessionRequest$,()=>CreateSessionOutput$];DeleteBucket$=[9,n0,"DeleteBucket",{[_h]:["DELETE","/",204]},()=>DeleteBucketRequest$,()=>"unit"];DeleteBucketAnalyticsConfiguration$=[9,n0,"DeleteBucketAnalyticsConfiguration",{[_h]:["DELETE","/?analytics",204]},()=>DeleteBucketAnalyticsConfigurationRequest$,()=>"unit"];DeleteBucketCors$=[9,n0,"DeleteBucketCors",{[_h]:["DELETE","/?cors",204]},()=>DeleteBucketCorsRequest$,()=>"unit"];DeleteBucketEncryption$=[9,n0,"DeleteBucketEncryption",{[_h]:["DELETE","/?encryption",204]},()=>DeleteBucketEncryptionRequest$,()=>"unit"];DeleteBucketIntelligentTieringConfiguration$=[9,n0,"DeleteBucketIntelligentTieringConfiguration",{[_h]:["DELETE","/?intelligent-tiering",204]},()=>DeleteBucketIntelligentTieringConfigurationRequest$,()=>"unit"];DeleteBucketInventoryConfiguration$=[9,n0,"DeleteBucketInventoryConfiguration",{[_h]:["DELETE","/?inventory",204]},()=>DeleteBucketInventoryConfigurationRequest$,()=>"unit"];DeleteBucketLifecycle$=[9,n0,"DeleteBucketLifecycle",{[_h]:["DELETE","/?lifecycle",204]},()=>DeleteBucketLifecycleRequest$,()=>"unit"];DeleteBucketMetadataConfiguration$=[9,n0,"DeleteBucketMetadataConfiguration",{[_h]:["DELETE","/?metadataConfiguration",204]},()=>DeleteBucketMetadataConfigurationRequest$,()=>"unit"];DeleteBucketMetadataTableConfiguration$=[9,n0,"DeleteBucketMetadataTableConfiguration",{[_h]:["DELETE","/?metadataTable",204]},()=>DeleteBucketMetadataTableConfigurationRequest$,()=>"unit"];DeleteBucketMetricsConfiguration$=[9,n0,"DeleteBucketMetricsConfiguration",{[_h]:["DELETE","/?metrics",204]},()=>DeleteBucketMetricsConfigurationRequest$,()=>"unit"];DeleteBucketOwnershipControls$=[9,n0,"DeleteBucketOwnershipControls",{[_h]:["DELETE","/?ownershipControls",204]},()=>DeleteBucketOwnershipControlsRequest$,()=>"unit"];DeleteBucketPolicy$=[9,n0,"DeleteBucketPolicy",{[_h]:["DELETE","/?policy",204]},()=>DeleteBucketPolicyRequest$,()=>"unit"];DeleteBucketReplication$=[9,n0,"DeleteBucketReplication",{[_h]:["DELETE","/?replication",204]},()=>DeleteBucketReplicationRequest$,()=>"unit"];DeleteBucketTagging$=[9,n0,"DeleteBucketTagging",{[_h]:["DELETE","/?tagging",204]},()=>DeleteBucketTaggingRequest$,()=>"unit"];DeleteBucketWebsite$=[9,n0,"DeleteBucketWebsite",{[_h]:["DELETE","/?website",204]},()=>DeleteBucketWebsiteRequest$,()=>"unit"];DeleteObject$=[9,n0,"DeleteObject",{[_h]:["DELETE","/{Key+}?x-id=DeleteObject",204]},()=>DeleteObjectRequest$,()=>DeleteObjectOutput$];DeleteObjects$=[9,n0,"DeleteObjects",{[_hC]:"-",[_h]:["POST","/?delete",200]},()=>DeleteObjectsRequest$,()=>DeleteObjectsOutput$];DeleteObjectTagging$=[9,n0,"DeleteObjectTagging",{[_h]:["DELETE","/{Key+}?tagging",204]},()=>DeleteObjectTaggingRequest$,()=>DeleteObjectTaggingOutput$];DeletePublicAccessBlock$=[9,n0,"DeletePublicAccessBlock",{[_h]:["DELETE","/?publicAccessBlock",204]},()=>DeletePublicAccessBlockRequest$,()=>"unit"];GetBucketAbac$=[9,n0,"GetBucketAbac",{[_h]:["GET","/?abac",200]},()=>GetBucketAbacRequest$,()=>GetBucketAbacOutput$];GetBucketAccelerateConfiguration$=[9,n0,"GetBucketAccelerateConfiguration",{[_h]:["GET","/?accelerate",200]},()=>GetBucketAccelerateConfigurationRequest$,()=>GetBucketAccelerateConfigurationOutput$];GetBucketAcl$=[9,n0,"GetBucketAcl",{[_h]:["GET","/?acl",200]},()=>GetBucketAclRequest$,()=>GetBucketAclOutput$];GetBucketAnalyticsConfiguration$=[9,n0,"GetBucketAnalyticsConfiguration",{[_h]:["GET","/?analytics&x-id=GetBucketAnalyticsConfiguration",200]},()=>GetBucketAnalyticsConfigurationRequest$,()=>GetBucketAnalyticsConfigurationOutput$];GetBucketCors$=[9,n0,"GetBucketCors",{[_h]:["GET","/?cors",200]},()=>GetBucketCorsRequest$,()=>GetBucketCorsOutput$];GetBucketEncryption$=[9,n0,"GetBucketEncryption",{[_h]:["GET","/?encryption",200]},()=>GetBucketEncryptionRequest$,()=>GetBucketEncryptionOutput$];GetBucketIntelligentTieringConfiguration$=[9,n0,"GetBucketIntelligentTieringConfiguration",{[_h]:["GET","/?intelligent-tiering&x-id=GetBucketIntelligentTieringConfiguration",200]},()=>GetBucketIntelligentTieringConfigurationRequest$,()=>GetBucketIntelligentTieringConfigurationOutput$];GetBucketInventoryConfiguration$=[9,n0,"GetBucketInventoryConfiguration",{[_h]:["GET","/?inventory&x-id=GetBucketInventoryConfiguration",200]},()=>GetBucketInventoryConfigurationRequest$,()=>GetBucketInventoryConfigurationOutput$];GetBucketLifecycleConfiguration$=[9,n0,"GetBucketLifecycleConfiguration",{[_h]:["GET","/?lifecycle",200]},()=>GetBucketLifecycleConfigurationRequest$,()=>GetBucketLifecycleConfigurationOutput$];GetBucketLocation$=[9,n0,"GetBucketLocation",{[_h]:["GET","/?location",200]},()=>GetBucketLocationRequest$,()=>GetBucketLocationOutput$];GetBucketLogging$=[9,n0,"GetBucketLogging",{[_h]:["GET","/?logging",200]},()=>GetBucketLoggingRequest$,()=>GetBucketLoggingOutput$];GetBucketMetadataConfiguration$=[9,n0,"GetBucketMetadataConfiguration",{[_h]:["GET","/?metadataConfiguration",200]},()=>GetBucketMetadataConfigurationRequest$,()=>GetBucketMetadataConfigurationOutput$];GetBucketMetadataTableConfiguration$=[9,n0,"GetBucketMetadataTableConfiguration",{[_h]:["GET","/?metadataTable",200]},()=>GetBucketMetadataTableConfigurationRequest$,()=>GetBucketMetadataTableConfigurationOutput$];GetBucketMetricsConfiguration$=[9,n0,"GetBucketMetricsConfiguration",{[_h]:["GET","/?metrics&x-id=GetBucketMetricsConfiguration",200]},()=>GetBucketMetricsConfigurationRequest$,()=>GetBucketMetricsConfigurationOutput$];GetBucketNotificationConfiguration$=[9,n0,"GetBucketNotificationConfiguration",{[_h]:["GET","/?notification",200]},()=>GetBucketNotificationConfigurationRequest$,()=>NotificationConfiguration$];GetBucketOwnershipControls$=[9,n0,"GetBucketOwnershipControls",{[_h]:["GET","/?ownershipControls",200]},()=>GetBucketOwnershipControlsRequest$,()=>GetBucketOwnershipControlsOutput$];GetBucketPolicy$=[9,n0,"GetBucketPolicy",{[_h]:["GET","/?policy",200]},()=>GetBucketPolicyRequest$,()=>GetBucketPolicyOutput$];GetBucketPolicyStatus$=[9,n0,"GetBucketPolicyStatus",{[_h]:["GET","/?policyStatus",200]},()=>GetBucketPolicyStatusRequest$,()=>GetBucketPolicyStatusOutput$];GetBucketReplication$=[9,n0,"GetBucketReplication",{[_h]:["GET","/?replication",200]},()=>GetBucketReplicationRequest$,()=>GetBucketReplicationOutput$];GetBucketRequestPayment$=[9,n0,"GetBucketRequestPayment",{[_h]:["GET","/?requestPayment",200]},()=>GetBucketRequestPaymentRequest$,()=>GetBucketRequestPaymentOutput$];GetBucketTagging$=[9,n0,"GetBucketTagging",{[_h]:["GET","/?tagging",200]},()=>GetBucketTaggingRequest$,()=>GetBucketTaggingOutput$];GetBucketVersioning$=[9,n0,"GetBucketVersioning",{[_h]:["GET","/?versioning",200]},()=>GetBucketVersioningRequest$,()=>GetBucketVersioningOutput$];GetBucketWebsite$=[9,n0,"GetBucketWebsite",{[_h]:["GET","/?website",200]},()=>GetBucketWebsiteRequest$,()=>GetBucketWebsiteOutput$];GetObject$=[9,n0,"GetObject",{[_hC]:"-",[_h]:["GET","/{Key+}?x-id=GetObject",200]},()=>GetObjectRequest$,()=>GetObjectOutput$];GetObjectAcl$=[9,n0,"GetObjectAcl",{[_h]:["GET","/{Key+}?acl",200]},()=>GetObjectAclRequest$,()=>GetObjectAclOutput$];GetObjectAttributes$=[9,n0,"GetObjectAttributes",{[_h]:["GET","/{Key+}?attributes",200]},()=>GetObjectAttributesRequest$,()=>GetObjectAttributesOutput$];GetObjectLegalHold$=[9,n0,"GetObjectLegalHold",{[_h]:["GET","/{Key+}?legal-hold",200]},()=>GetObjectLegalHoldRequest$,()=>GetObjectLegalHoldOutput$];GetObjectLockConfiguration$=[9,n0,"GetObjectLockConfiguration",{[_h]:["GET","/?object-lock",200]},()=>GetObjectLockConfigurationRequest$,()=>GetObjectLockConfigurationOutput$];GetObjectRetention$=[9,n0,"GetObjectRetention",{[_h]:["GET","/{Key+}?retention",200]},()=>GetObjectRetentionRequest$,()=>GetObjectRetentionOutput$];GetObjectTagging$=[9,n0,"GetObjectTagging",{[_h]:["GET","/{Key+}?tagging",200]},()=>GetObjectTaggingRequest$,()=>GetObjectTaggingOutput$];GetObjectTorrent$=[9,n0,"GetObjectTorrent",{[_h]:["GET","/{Key+}?torrent",200]},()=>GetObjectTorrentRequest$,()=>GetObjectTorrentOutput$];GetPublicAccessBlock$=[9,n0,"GetPublicAccessBlock",{[_h]:["GET","/?publicAccessBlock",200]},()=>GetPublicAccessBlockRequest$,()=>GetPublicAccessBlockOutput$];HeadBucket$=[9,n0,"HeadBucket",{[_h]:["HEAD","/",200]},()=>HeadBucketRequest$,()=>HeadBucketOutput$];HeadObject$=[9,n0,"HeadObject",{[_h]:["HEAD","/{Key+}",200]},()=>HeadObjectRequest$,()=>HeadObjectOutput$];ListBucketAnalyticsConfigurations$=[9,n0,"ListBucketAnalyticsConfigurations",{[_h]:["GET","/?analytics&x-id=ListBucketAnalyticsConfigurations",200]},()=>ListBucketAnalyticsConfigurationsRequest$,()=>ListBucketAnalyticsConfigurationsOutput$];ListBucketIntelligentTieringConfigurations$=[9,n0,"ListBucketIntelligentTieringConfigurations",{[_h]:["GET","/?intelligent-tiering&x-id=ListBucketIntelligentTieringConfigurations",200]},()=>ListBucketIntelligentTieringConfigurationsRequest$,()=>ListBucketIntelligentTieringConfigurationsOutput$];ListBucketInventoryConfigurations$=[9,n0,"ListBucketInventoryConfigurations",{[_h]:["GET","/?inventory&x-id=ListBucketInventoryConfigurations",200]},()=>ListBucketInventoryConfigurationsRequest$,()=>ListBucketInventoryConfigurationsOutput$];ListBucketMetricsConfigurations$=[9,n0,"ListBucketMetricsConfigurations",{[_h]:["GET","/?metrics&x-id=ListBucketMetricsConfigurations",200]},()=>ListBucketMetricsConfigurationsRequest$,()=>ListBucketMetricsConfigurationsOutput$];ListBuckets$=[9,n0,"ListBuckets",{[_h]:["GET","/?x-id=ListBuckets",200]},()=>ListBucketsRequest$,()=>ListBucketsOutput$];ListDirectoryBuckets$=[9,n0,"ListDirectoryBuckets",{[_h]:["GET","/?x-id=ListDirectoryBuckets",200]},()=>ListDirectoryBucketsRequest$,()=>ListDirectoryBucketsOutput$];ListMultipartUploads$=[9,n0,"ListMultipartUploads",{[_h]:["GET","/?uploads",200]},()=>ListMultipartUploadsRequest$,()=>ListMultipartUploadsOutput$];ListObjects$=[9,n0,"ListObjects",{[_h]:["GET","/",200]},()=>ListObjectsRequest$,()=>ListObjectsOutput$];ListObjectsV2$=[9,n0,"ListObjectsV2",{[_h]:["GET","/?list-type=2",200]},()=>ListObjectsV2Request$,()=>ListObjectsV2Output$];ListObjectVersions$=[9,n0,"ListObjectVersions",{[_h]:["GET","/?versions",200]},()=>ListObjectVersionsRequest$,()=>ListObjectVersionsOutput$];ListParts$=[9,n0,"ListParts",{[_h]:["GET","/{Key+}?x-id=ListParts",200]},()=>ListPartsRequest$,()=>ListPartsOutput$];PutBucketAbac$=[9,n0,"PutBucketAbac",{[_hC]:"-",[_h]:["PUT","/?abac",200]},()=>PutBucketAbacRequest$,()=>"unit"];PutBucketAccelerateConfiguration$=[9,n0,"PutBucketAccelerateConfiguration",{[_hC]:"-",[_h]:["PUT","/?accelerate",200]},()=>PutBucketAccelerateConfigurationRequest$,()=>"unit"];PutBucketAcl$=[9,n0,"PutBucketAcl",{[_hC]:"-",[_h]:["PUT","/?acl",200]},()=>PutBucketAclRequest$,()=>"unit"];PutBucketAnalyticsConfiguration$=[9,n0,"PutBucketAnalyticsConfiguration",{[_h]:["PUT","/?analytics",200]},()=>PutBucketAnalyticsConfigurationRequest$,()=>"unit"];PutBucketCors$=[9,n0,"PutBucketCors",{[_hC]:"-",[_h]:["PUT","/?cors",200]},()=>PutBucketCorsRequest$,()=>"unit"];PutBucketEncryption$=[9,n0,"PutBucketEncryption",{[_hC]:"-",[_h]:["PUT","/?encryption",200]},()=>PutBucketEncryptionRequest$,()=>"unit"];PutBucketIntelligentTieringConfiguration$=[9,n0,"PutBucketIntelligentTieringConfiguration",{[_h]:["PUT","/?intelligent-tiering",200]},()=>PutBucketIntelligentTieringConfigurationRequest$,()=>"unit"];PutBucketInventoryConfiguration$=[9,n0,"PutBucketInventoryConfiguration",{[_h]:["PUT","/?inventory",200]},()=>PutBucketInventoryConfigurationRequest$,()=>"unit"];PutBucketLifecycleConfiguration$=[9,n0,"PutBucketLifecycleConfiguration",{[_hC]:"-",[_h]:["PUT","/?lifecycle",200]},()=>PutBucketLifecycleConfigurationRequest$,()=>PutBucketLifecycleConfigurationOutput$];PutBucketLogging$=[9,n0,"PutBucketLogging",{[_hC]:"-",[_h]:["PUT","/?logging",200]},()=>PutBucketLoggingRequest$,()=>"unit"];PutBucketMetricsConfiguration$=[9,n0,"PutBucketMetricsConfiguration",{[_h]:["PUT","/?metrics",200]},()=>PutBucketMetricsConfigurationRequest$,()=>"unit"];PutBucketNotificationConfiguration$=[9,n0,"PutBucketNotificationConfiguration",{[_h]:["PUT","/?notification",200]},()=>PutBucketNotificationConfigurationRequest$,()=>"unit"];PutBucketOwnershipControls$=[9,n0,"PutBucketOwnershipControls",{[_hC]:"-",[_h]:["PUT","/?ownershipControls",200]},()=>PutBucketOwnershipControlsRequest$,()=>"unit"];PutBucketPolicy$=[9,n0,"PutBucketPolicy",{[_hC]:"-",[_h]:["PUT","/?policy",200]},()=>PutBucketPolicyRequest$,()=>"unit"];PutBucketReplication$=[9,n0,"PutBucketReplication",{[_hC]:"-",[_h]:["PUT","/?replication",200]},()=>PutBucketReplicationRequest$,()=>"unit"];PutBucketRequestPayment$=[9,n0,"PutBucketRequestPayment",{[_hC]:"-",[_h]:["PUT","/?requestPayment",200]},()=>PutBucketRequestPaymentRequest$,()=>"unit"];PutBucketTagging$=[9,n0,"PutBucketTagging",{[_hC]:"-",[_h]:["PUT","/?tagging",200]},()=>PutBucketTaggingRequest$,()=>"unit"];PutBucketVersioning$=[9,n0,"PutBucketVersioning",{[_hC]:"-",[_h]:["PUT","/?versioning",200]},()=>PutBucketVersioningRequest$,()=>"unit"];PutBucketWebsite$=[9,n0,"PutBucketWebsite",{[_hC]:"-",[_h]:["PUT","/?website",200]},()=>PutBucketWebsiteRequest$,()=>"unit"];PutObject$=[9,n0,"PutObject",{[_hC]:"-",[_h]:["PUT","/{Key+}?x-id=PutObject",200]},()=>PutObjectRequest$,()=>PutObjectOutput$];PutObjectAcl$=[9,n0,"PutObjectAcl",{[_hC]:"-",[_h]:["PUT","/{Key+}?acl",200]},()=>PutObjectAclRequest$,()=>PutObjectAclOutput$];PutObjectLegalHold$=[9,n0,"PutObjectLegalHold",{[_hC]:"-",[_h]:["PUT","/{Key+}?legal-hold",200]},()=>PutObjectLegalHoldRequest$,()=>PutObjectLegalHoldOutput$];PutObjectLockConfiguration$=[9,n0,"PutObjectLockConfiguration",{[_hC]:"-",[_h]:["PUT","/?object-lock",200]},()=>PutObjectLockConfigurationRequest$,()=>PutObjectLockConfigurationOutput$];PutObjectRetention$=[9,n0,"PutObjectRetention",{[_hC]:"-",[_h]:["PUT","/{Key+}?retention",200]},()=>PutObjectRetentionRequest$,()=>PutObjectRetentionOutput$];PutObjectTagging$=[9,n0,"PutObjectTagging",{[_hC]:"-",[_h]:["PUT","/{Key+}?tagging",200]},()=>PutObjectTaggingRequest$,()=>PutObjectTaggingOutput$];PutPublicAccessBlock$=[9,n0,"PutPublicAccessBlock",{[_hC]:"-",[_h]:["PUT","/?publicAccessBlock",200]},()=>PutPublicAccessBlockRequest$,()=>"unit"];RenameObject$=[9,n0,"RenameObject",{[_h]:["PUT","/{Key+}?renameObject",200]},()=>RenameObjectRequest$,()=>RenameObjectOutput$];RestoreObject$=[9,n0,"RestoreObject",{[_hC]:"-",[_h]:["POST","/{Key+}?restore",200]},()=>RestoreObjectRequest$,()=>RestoreObjectOutput$];SelectObjectContent$=[9,n0,"SelectObjectContent",{[_h]:["POST","/{Key+}?select&select-type=2",200]},()=>SelectObjectContentRequest$,()=>SelectObjectContentOutput$];UpdateBucketMetadataInventoryTableConfiguration$=[9,n0,"UpdateBucketMetadataInventoryTableConfiguration",{[_hC]:"-",[_h]:["PUT","/?metadataInventoryTable",200]},()=>UpdateBucketMetadataInventoryTableConfigurationRequest$,()=>"unit"];UpdateBucketMetadataJournalTableConfiguration$=[9,n0,"UpdateBucketMetadataJournalTableConfiguration",{[_hC]:"-",[_h]:["PUT","/?metadataJournalTable",200]},()=>UpdateBucketMetadataJournalTableConfigurationRequest$,()=>"unit"];UpdateObjectEncryption$=[9,n0,"UpdateObjectEncryption",{[_hC]:"-",[_h]:["PUT","/{Key+}?encryption",200]},()=>UpdateObjectEncryptionRequest$,()=>UpdateObjectEncryptionResponse$];UploadPart$=[9,n0,"UploadPart",{[_hC]:"-",[_h]:["PUT","/{Key+}?x-id=UploadPart",200]},()=>UploadPartRequest$,()=>UploadPartOutput$];UploadPartCopy$=[9,n0,"UploadPartCopy",{[_h]:["PUT","/{Key+}?x-id=UploadPartCopy",200]},()=>UploadPartCopyRequest$,()=>UploadPartCopyOutput$];WriteGetObjectResponse$=[9,n0,"WriteGetObjectResponse",{[_en]:["{RequestRoute}."],[_h]:["POST","/WriteGetObjectResponse",200]},()=>WriteGetObjectResponseRequest$,()=>"unit"];CreateSessionCommand=class extends(Command.classBuilder().ep({...commonParams,DisableS3ExpressSessionAuth:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","CreateSession",{}).n("S3Client","CreateSessionCommand").sc(CreateSession$).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>>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,t12,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>>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)}t12=(((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+t12|0;state3=state22;state22=state1;state1=state0;state0=t12+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(_a7){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;i2async config=>{var _a7,_b5,_c3,_d2,_e2,_f,_g,_h2,_i2,_j;const navigator2="undefined"!=typeof window?window.navigator:void 0,uaString=null!=(_a7=null==navigator2?void 0:navigator2.userAgent)?_a7:"",osName=null!=(_d2=null!=(_c3=null==(_b5=null==navigator2?void 0:navigator2.userAgentData)?void 0:_b5.platform)?_c3:fallback2.os(uaString))?_d2:"other",brands=null!=(_f=null==(_e2=null==navigator2?void 0:navigator2.userAgentData)?void 0:_e2.brands)?_f:[],brand=brands[brands.length-1],browserName=null!=(_h2=null!=(_g=null==brand?void 0:brand.brand)?_g:fallback2.browser(uaString))?_h2:"unknown",browserVersion=null!=(_i2=null==brand?void 0:brand.version)?_i2:"unknown",sections=[["aws-sdk-js",clientVersion],["ua","2.1"],[`os/${osName}`,void 0],["lang/js"],["md/browser",`${browserName}_${browserVersion}`]];serviceId&§ions.push([`api/${serviceId}`,clientVersion]);const appId=await(null==(_j=null==config?void 0:config.userAgentAppId)?void 0:_j.call(config));appId&§ions.push([`app/${appId}`]);return sections};fallback2={os:ua=>/iPhone|iPad|iPod/.test(ua)?"iOS":/Macintosh|Mac OS X/.test(ua)?"macOS":/Windows NT/.test(ua)?"Windows":/Android/.test(ua)?"Android":/Linux/.test(ua)?"Linux":void 0,browser:ua=>/EdgiOS|EdgA|Edg\//.test(ua)?"Microsoft Edge":/Firefox\//.test(ua)?"Firefox":/Chrome\//.test(ua)?"Chrome":/Safari\//.test(ua)?"Safari":void 0};Int642=class _Int64{constructor(bytes){__publicField(this,"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){__publicField(this,"toUtf8");__publicField(this,"fromUtf8");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(;positionmessage,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){__publicField(this,"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){__publicField(this,"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){__publicField(this,"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){__publicField(this,"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}){__publicField(this,"eventStreamCodec");__publicField(this,"utfEncoder");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}){__publicField(this,"universalMarshaller");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;eventStreamSerdeProvider=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];init_dist_es();Md5=class{constructor(){__publicField(this,"state");__publicField(this,"buffer");__publicField(this,"bufferLength");__publicField(this,"bytesHashed");__publicField(this,"finished");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}};DEFAULTS_MODE_OPTIONS=["in-region","cross-region","mobile","standard","legacy"];resolveDefaultsModeConfig=({defaultsMode}={})=>memoize((async()=>{const mode="function"==typeof defaultsMode?await defaultsMode():defaultsMode;switch(null==mode?void 0:mode.toLowerCase()){case"auto":return Promise.resolve(useMobileConfiguration()?"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}`)}}));useMobileConfiguration=()=>{var _a7;const navigator2=null==window?void 0:window.navigator;if(null==navigator2?void 0:navigator2.connection){const{effectiveType,rtt,downlink}=null==navigator2?void 0:navigator2.connection;if("string"==typeof effectiveType&&"4g"!==effectiveType||Number(rtt)>100||Number(downlink)<10)return!0}return(null==(_a7=null==navigator2?void 0:navigator2.userAgentData)?void 0:_a7.mobile)||"number"==typeof(null==navigator2?void 0:navigator2.maxTouchPoints)&&(null==navigator2?void 0:navigator2.maxTouchPoints)>1};init_dist_es();getRuntimeConfig=config=>{var _a7,_b5,_c3,_d2,_e2,_f,_g,_h2,_i2,_j,_k,_l,_m2,_n,_o,_p2,_q,_r,_s2;return{apiVersion:"2006-03-01",base64Decoder:null!=(_a7=null==config?void 0:config.base64Decoder)?_a7: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!=(_h2=null==config?void 0:config.httpAuthSchemes)?_h2:[{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,protocol:null!=(_j=null==config?void 0:config.protocol)?_j:AwsRestXmlProtocol,protocolSettings:null!=(_k=null==config?void 0:config.protocolSettings)?_k:{defaultNamespace:"com.amazonaws.s3",xmlNamespace:"http://s3.amazonaws.com/doc/2006-03-01/",version:"2006-03-01",serviceTarget:"AmazonS3"},sdkStreamMixin:null!=(_l=null==config?void 0:config.sdkStreamMixin)?_l:sdkStreamMixin,serviceId:null!=(_m2=null==config?void 0:config.serviceId)?_m2:"S3",signerConstructor:null!=(_n=null==config?void 0:config.signerConstructor)?_n:SignatureV4MultiRegion,signingEscapePath:null!=(_o=null==config?void 0:config.signingEscapePath)&&_o,urlParser:null!=(_p2=null==config?void 0:config.urlParser)?_p2:parseUrl,useArnRegion:null!=(_q=null==config?void 0:config.useArnRegion)?_q:void 0,utf8Decoder:null!=(_r=null==config?void 0:config.utf8Decoder)?_r:fromUtf8,utf8Encoder:null!=(_s2=null==config?void 0:config.utf8Encoder)?_s2:toUtf8}};getRuntimeConfig2=config=>{var _a7,_b5,_c3,_d2,_e2,_f,_g,_h2,_i2,_j,_k,_l,_m2,_n,_o;const defaultsMode=resolveDefaultsModeConfig(config),defaultConfigProvider=()=>defaultsMode().then(loadConfigsForDefaultMode),clientSharedValues=getRuntimeConfig(config);return{...clientSharedValues,...config,runtime:"browser",defaultsMode,bodyLengthChecker:null!=(_a7=null==config?void 0:config.bodyLengthChecker)?_a7: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.983.0"}),eventStreamSerdeProvider:null!=(_d2=null==config?void 0:config.eventStreamSerdeProvider)?_d2:eventStreamSerdeProvider,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!=(_h2=null==config?void 0:config.requestHandler)?_h2: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!=(_l=null==config?void 0:config.streamCollector)?_l:streamCollector,streamHasher:null!=(_m2=null==config?void 0:config.streamHasher)?_m2:blobHasher,useDualstackEndpoint:null!=(_n=null==config?void 0:config.useDualstackEndpoint)?_n:()=>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),resolveDefaultRuntimeConfig(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(getSchemaSerdePlugin(this.config));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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","AbortMultipartUpload",{}).n("S3Client","AbortMultipartUploadCommand").sc(AbortMultipartUpload$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","CompleteMultipartUpload",{}).n("S3Client","CompleteMultipartUploadCommand").sc(CompleteMultipartUpload$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","CopyObject",{}).n("S3Client","CopyObjectCommand").sc(CopyObject$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getLocationConstraintPlugin(config)]})).s("AmazonS3","CreateBucket",{}).n("S3Client","CreateBucketCommand").sc(CreateBucket$).build()){};CreateBucketMetadataConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","CreateBucketMetadataConfiguration",{}).n("S3Client","CreateBucketMetadataConfigurationCommand").sc(CreateBucketMetadataConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","CreateBucketMetadataTableConfiguration",{}).n("S3Client","CreateBucketMetadataTableConfigurationCommand").sc(CreateBucketMetadataTableConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","CreateMultipartUpload",{}).n("S3Client","CreateMultipartUploadCommand").sc(CreateMultipartUpload$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketAnalyticsConfiguration",{}).n("S3Client","DeleteBucketAnalyticsConfigurationCommand").sc(DeleteBucketAnalyticsConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucket",{}).n("S3Client","DeleteBucketCommand").sc(DeleteBucket$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketCors",{}).n("S3Client","DeleteBucketCorsCommand").sc(DeleteBucketCors$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketEncryption",{}).n("S3Client","DeleteBucketEncryptionCommand").sc(DeleteBucketEncryption$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketIntelligentTieringConfiguration",{}).n("S3Client","DeleteBucketIntelligentTieringConfigurationCommand").sc(DeleteBucketIntelligentTieringConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketInventoryConfiguration",{}).n("S3Client","DeleteBucketInventoryConfigurationCommand").sc(DeleteBucketInventoryConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketLifecycle",{}).n("S3Client","DeleteBucketLifecycleCommand").sc(DeleteBucketLifecycle$).build()){};DeleteBucketMetadataConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketMetadataConfiguration",{}).n("S3Client","DeleteBucketMetadataConfigurationCommand").sc(DeleteBucketMetadataConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketMetadataTableConfiguration",{}).n("S3Client","DeleteBucketMetadataTableConfigurationCommand").sc(DeleteBucketMetadataTableConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketMetricsConfiguration",{}).n("S3Client","DeleteBucketMetricsConfigurationCommand").sc(DeleteBucketMetricsConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketOwnershipControls",{}).n("S3Client","DeleteBucketOwnershipControlsCommand").sc(DeleteBucketOwnershipControls$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketPolicy",{}).n("S3Client","DeleteBucketPolicyCommand").sc(DeleteBucketPolicy$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketReplication",{}).n("S3Client","DeleteBucketReplicationCommand").sc(DeleteBucketReplication$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketTagging",{}).n("S3Client","DeleteBucketTaggingCommand").sc(DeleteBucketTagging$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeleteBucketWebsite",{}).n("S3Client","DeleteBucketWebsiteCommand").sc(DeleteBucketWebsite$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","DeleteObject",{}).n("S3Client","DeleteObjectCommand").sc(DeleteObject$).build()){};DeleteObjectsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[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").sc(DeleteObjects$).build()){};DeleteObjectTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","DeleteObjectTagging",{}).n("S3Client","DeleteObjectTaggingCommand").sc(DeleteObjectTagging$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","DeletePublicAccessBlock",{}).n("S3Client","DeletePublicAccessBlockCommand").sc(DeletePublicAccessBlock$).build()){};GetBucketAbacCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketAbac",{}).n("S3Client","GetBucketAbacCommand").sc(GetBucketAbac$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketAccelerateConfiguration",{}).n("S3Client","GetBucketAccelerateConfigurationCommand").sc(GetBucketAccelerateConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketAcl",{}).n("S3Client","GetBucketAclCommand").sc(GetBucketAcl$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketAnalyticsConfiguration",{}).n("S3Client","GetBucketAnalyticsConfigurationCommand").sc(GetBucketAnalyticsConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketCors",{}).n("S3Client","GetBucketCorsCommand").sc(GetBucketCors$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketEncryption",{}).n("S3Client","GetBucketEncryptionCommand").sc(GetBucketEncryption$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketIntelligentTieringConfiguration",{}).n("S3Client","GetBucketIntelligentTieringConfigurationCommand").sc(GetBucketIntelligentTieringConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketInventoryConfiguration",{}).n("S3Client","GetBucketInventoryConfigurationCommand").sc(GetBucketInventoryConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketLifecycleConfiguration",{}).n("S3Client","GetBucketLifecycleConfigurationCommand").sc(GetBucketLifecycleConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketLocation",{}).n("S3Client","GetBucketLocationCommand").sc(GetBucketLocation$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketLogging",{}).n("S3Client","GetBucketLoggingCommand").sc(GetBucketLogging$).build()){};GetBucketMetadataConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketMetadataConfiguration",{}).n("S3Client","GetBucketMetadataConfigurationCommand").sc(GetBucketMetadataConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketMetadataTableConfiguration",{}).n("S3Client","GetBucketMetadataTableConfigurationCommand").sc(GetBucketMetadataTableConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketMetricsConfiguration",{}).n("S3Client","GetBucketMetricsConfigurationCommand").sc(GetBucketMetricsConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketNotificationConfiguration",{}).n("S3Client","GetBucketNotificationConfigurationCommand").sc(GetBucketNotificationConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketOwnershipControls",{}).n("S3Client","GetBucketOwnershipControlsCommand").sc(GetBucketOwnershipControls$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketPolicy",{}).n("S3Client","GetBucketPolicyCommand").sc(GetBucketPolicy$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketPolicyStatus",{}).n("S3Client","GetBucketPolicyStatusCommand").sc(GetBucketPolicyStatus$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketReplication",{}).n("S3Client","GetBucketReplicationCommand").sc(GetBucketReplication$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketRequestPayment",{}).n("S3Client","GetBucketRequestPaymentCommand").sc(GetBucketRequestPayment$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketTagging",{}).n("S3Client","GetBucketTaggingCommand").sc(GetBucketTagging$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketVersioning",{}).n("S3Client","GetBucketVersioningCommand").sc(GetBucketVersioning$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetBucketWebsite",{}).n("S3Client","GetBucketWebsiteCommand").sc(GetBucketWebsite$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectAcl",{}).n("S3Client","GetObjectAclCommand").sc(GetObjectAcl$).build()){};GetObjectAttributesCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","GetObjectAttributes",{}).n("S3Client","GetObjectAttributesCommand").sc(GetObjectAttributes$).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[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").sc(GetObject$).build()){};GetObjectLegalHoldCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectLegalHold",{}).n("S3Client","GetObjectLegalHoldCommand").sc(GetObjectLegalHold$).build()){};GetObjectLockConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectLockConfiguration",{}).n("S3Client","GetObjectLockConfigurationCommand").sc(GetObjectLockConfiguration$).build()){};GetObjectRetentionCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectRetention",{}).n("S3Client","GetObjectRetentionCommand").sc(GetObjectRetention$).build()){};GetObjectTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetObjectTagging",{}).n("S3Client","GetObjectTaggingCommand").sc(GetObjectTagging$).build()){};GetObjectTorrentCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","GetObjectTorrent",{}).n("S3Client","GetObjectTorrentCommand").sc(GetObjectTorrent$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","GetPublicAccessBlock",{}).n("S3Client","GetPublicAccessBlockCommand").sc(GetPublicAccessBlock$).build()){};HeadBucketCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","HeadBucket",{}).n("S3Client","HeadBucketCommand").sc(HeadBucket$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config),getS3ExpiresMiddlewarePlugin()]})).s("AmazonS3","HeadObject",{}).n("S3Client","HeadObjectCommand").sc(HeadObject$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBucketAnalyticsConfigurations",{}).n("S3Client","ListBucketAnalyticsConfigurationsCommand").sc(ListBucketAnalyticsConfigurations$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBucketIntelligentTieringConfigurations",{}).n("S3Client","ListBucketIntelligentTieringConfigurationsCommand").sc(ListBucketIntelligentTieringConfigurations$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBucketInventoryConfigurations",{}).n("S3Client","ListBucketInventoryConfigurationsCommand").sc(ListBucketInventoryConfigurations$).build()){};ListBucketMetricsConfigurationsCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBucketMetricsConfigurations",{}).n("S3Client","ListBucketMetricsConfigurationsCommand").sc(ListBucketMetricsConfigurations$).build()){};ListBucketsCommand=class extends(Command.classBuilder().ep(commonParams).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListBuckets",{}).n("S3Client","ListBucketsCommand").sc(ListBuckets$).build()){};ListDirectoryBucketsCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListDirectoryBuckets",{}).n("S3Client","ListDirectoryBucketsCommand").sc(ListDirectoryBuckets$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListMultipartUploads",{}).n("S3Client","ListMultipartUploadsCommand").sc(ListMultipartUploads$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListObjects",{}).n("S3Client","ListObjectsCommand").sc(ListObjects$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListObjectsV2",{}).n("S3Client","ListObjectsV2Command").sc(ListObjectsV2$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","ListObjectVersions",{}).n("S3Client","ListObjectVersionsCommand").sc(ListObjectVersions$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","ListParts",{}).n("S3Client","ListPartsCommand").sc(ListParts$).build()){};PutBucketAbacCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1})]})).s("AmazonS3","PutBucketAbac",{}).n("S3Client","PutBucketAbacCommand").sc(PutBucketAbac$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!1})]})).s("AmazonS3","PutBucketAccelerateConfiguration",{}).n("S3Client","PutBucketAccelerateConfigurationCommand").sc(PutBucketAccelerateConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketAcl",{}).n("S3Client","PutBucketAclCommand").sc(PutBucketAcl$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketAnalyticsConfiguration",{}).n("S3Client","PutBucketAnalyticsConfigurationCommand").sc(PutBucketAnalyticsConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketCors",{}).n("S3Client","PutBucketCorsCommand").sc(PutBucketCors$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketEncryption",{}).n("S3Client","PutBucketEncryptionCommand").sc(PutBucketEncryption$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketIntelligentTieringConfiguration",{}).n("S3Client","PutBucketIntelligentTieringConfigurationCommand").sc(PutBucketIntelligentTieringConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketInventoryConfiguration",{}).n("S3Client","PutBucketInventoryConfigurationCommand").sc(PutBucketInventoryConfiguration$).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[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").sc(PutBucketLifecycleConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketLogging",{}).n("S3Client","PutBucketLoggingCommand").sc(PutBucketLogging$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketMetricsConfiguration",{}).n("S3Client","PutBucketMetricsConfigurationCommand").sc(PutBucketMetricsConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","PutBucketNotificationConfiguration",{}).n("S3Client","PutBucketNotificationConfigurationCommand").sc(PutBucketNotificationConfiguration$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketOwnershipControls",{}).n("S3Client","PutBucketOwnershipControlsCommand").sc(PutBucketOwnershipControls$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketPolicy",{}).n("S3Client","PutBucketPolicyCommand").sc(PutBucketPolicy$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketReplication",{}).n("S3Client","PutBucketReplicationCommand").sc(PutBucketReplication$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketRequestPayment",{}).n("S3Client","PutBucketRequestPaymentCommand").sc(PutBucketRequestPayment$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketTagging",{}).n("S3Client","PutBucketTaggingCommand").sc(PutBucketTagging$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketVersioning",{}).n("S3Client","PutBucketVersioningCommand").sc(PutBucketVersioning$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutBucketWebsite",{}).n("S3Client","PutBucketWebsiteCommand").sc(PutBucketWebsite$).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[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").sc(PutObjectAcl$).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[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").sc(PutObject$).build()){};PutObjectLegalHoldCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[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").sc(PutObjectLegalHold$).build()){};PutObjectLockConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[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").sc(PutObjectLockConfiguration$).build()){};PutObjectRetentionCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[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").sc(PutObjectRetention$).build()){};PutObjectTaggingCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[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").sc(PutObjectTagging$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","PutPublicAccessBlock",{}).n("S3Client","PutPublicAccessBlockCommand").sc(PutPublicAccessBlock$).build()){};RenameObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"},Key:{type:"contextParams",name:"Key"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","RenameObject",{}).n("S3Client","RenameObjectCommand").sc(RenameObject$).build()){};RestoreObjectCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[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").sc(RestoreObject$).build()){};SelectObjectContentCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","SelectObjectContent",{eventStream:{output:!0}}).n("S3Client","SelectObjectContentCommand").sc(SelectObjectContent$).build()){};UpdateBucketMetadataInventoryTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","UpdateBucketMetadataInventoryTableConfiguration",{}).n("S3Client","UpdateBucketMetadataInventoryTableConfigurationCommand").sc(UpdateBucketMetadataInventoryTableConfiguration$).build()){};UpdateBucketMetadataJournalTableConfigurationCommand=class extends(Command.classBuilder().ep({...commonParams,UseS3ExpressControlEndpoint:{type:"staticContextParams",value:!0},Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0})]})).s("AmazonS3","UpdateBucketMetadataJournalTableConfiguration",{}).n("S3Client","UpdateBucketMetadataJournalTableConfigurationCommand").sc(UpdateBucketMetadataJournalTableConfiguration$).build()){};UpdateObjectEncryptionCommand=class extends(Command.classBuilder().ep({...commonParams,Bucket:{type:"contextParams",name:"Bucket"}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getFlexibleChecksumsPlugin(config,{requestAlgorithmMember:{httpHeader:"x-amz-sdk-checksum-algorithm",name:"ChecksumAlgorithm"},requestChecksumRequired:!0}),getThrow200ExceptionsPlugin(config)]})).s("AmazonS3","UpdateObjectEncryption",{}).n("S3Client","UpdateObjectEncryptionCommand").sc(UpdateObjectEncryption$).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[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").sc(UploadPart$).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[getEndpointPlugin(config,Command2.getEndpointParameterInstructions()),getThrow200ExceptionsPlugin(config),getSsecPlugin(config)]})).s("AmazonS3","UploadPartCopy",{}).n("S3Client","UploadPartCopyCommand").sc(UploadPartCopy$).build()){};WriteGetObjectResponseCommand=class extends(Command.classBuilder().ep({...commonParams,UseObjectLambdaEndpoint:{type:"staticContextParams",value:!0}}).m((function(Command2,cs2,config,o2){return[getEndpointPlugin(config,Command2.getEndpointParameterInstructions())]})).s("AmazonS3","WriteGetObjectResponse",{}).n("S3Client","WriteGetObjectResponseCommand").sc(WriteGetObjectResponse$).build()){};paginateListBuckets=createPaginator(S3Client,ListBucketsCommand,"ContinuationToken","ContinuationToken","MaxBuckets");paginateListDirectoryBuckets=createPaginator(S3Client,ListDirectoryBucketsCommand,"ContinuationToken","ContinuationToken","MaxDirectoryBuckets");paginateListObjectsV2=createPaginator(S3Client,ListObjectsV2Command,"ContinuationToken","NextContinuationToken","MaxKeys");paginateListParts=createPaginator(S3Client,ListPartsCommand,"PartNumberMarker","NextPartNumberMarker","MaxParts");getCircularReplacer=()=>{const seen=new WeakSet;return(key3,value)=>{if("object"==typeof value&&null!==value){if(seen.has(value))return"[Circular]";seen.add(value)}return value}};sleep=seconds=>new Promise((resolve=>setTimeout(resolve,1e3*seconds)));waiterServiceDefaults={minDelay:2,maxDelay:120};(function(WaiterState2){WaiterState2.ABORTED="ABORTED";WaiterState2.FAILURE="FAILURE";WaiterState2.SUCCESS="SUCCESS";WaiterState2.RETRY="RETRY";WaiterState2.TIMEOUT="TIMEOUT"})(WaiterState||(WaiterState={}));checkExceptions=result=>{if(result.state===WaiterState.ABORTED){const abortError=new Error(`${JSON.stringify({...result,reason:"Request was aborted"},getCircularReplacer())}`);abortError.name="AbortError";throw abortError}if(result.state===WaiterState.TIMEOUT){const timeoutError=new Error(`${JSON.stringify({...result,reason:"Waiter has timed out"},getCircularReplacer())}`);timeoutError.name="TimeoutError";throw timeoutError}if(result.state!==WaiterState.SUCCESS)throw new Error(`${JSON.stringify(result,getCircularReplacer())}`);return result};exponentialBackoffWithJitter=(minDelay,maxDelay,attemptCeiling,attempt)=>attempt>attemptCeiling?maxDelay:randomInRange(minDelay,minDelay*2**(attempt-1));randomInRange=(min,max3)=>min+Math.random()*(max3-min);runPolling=async({minDelay,maxDelay,maxWaitTime,abortController,client,abortSignal},input,acceptorChecks)=>{var _a7;const observedResponses={},{state:state2,reason}=await acceptorChecks(client,input);if(reason){const message=createMessageFromResponse(reason);observedResponses[message]|=0;observedResponses[message]+=1}if(state2!==WaiterState.RETRY)return{state:state2,reason,observedResponses};let currentAttempt=1;const waitUntil=Date.now()+1e3*maxWaitTime,attemptCeiling=Math.log(maxDelay/minDelay)/Math.log(2)+1;for(;;){if((null==(_a7=null==abortController?void 0:abortController.signal)?void 0:_a7.aborted)||(null==abortSignal?void 0:abortSignal.aborted)){const message="AbortController signal aborted.";observedResponses[message]|=0;observedResponses[message]+=1;return{state:WaiterState.ABORTED,observedResponses}}const delay2=exponentialBackoffWithJitter(minDelay,maxDelay,attemptCeiling,currentAttempt);if(Date.now()+1e3*delay2>waitUntil)return{state:WaiterState.TIMEOUT,observedResponses};await sleep(delay2);const{state:state3,reason:reason2}=await acceptorChecks(client,input);if(reason2){const message=createMessageFromResponse(reason2);observedResponses[message]|=0;observedResponses[message]+=1}if(state3!==WaiterState.RETRY)return{state:state3,reason:reason2,observedResponses};currentAttempt+=1}};createMessageFromResponse=reason=>{var _a7,_b5,_c3,_d2,_e2;return(null==reason?void 0:reason.$responseBodyText)?`Deserialization error for body: ${reason.$responseBodyText}`:(null==(_a7=null==reason?void 0:reason.$metadata)?void 0:_a7.httpStatusCode)?reason.$response||reason.message?`${null!=(_c3=null!=(_b5=reason.$response.statusCode)?_b5:reason.$metadata.httpStatusCode)?_c3:"Unknown"}: ${reason.message}`:`${reason.$metadata.httpStatusCode}: OK`:String(null!=(_e2=null!=(_d2=null==reason?void 0:reason.message)?_d2:JSON.stringify(reason,getCircularReplacer()))?_e2:"Unknown")};validateWaiterOptions=options=>{if(options.maxWaitTime<=0)throw new Error("WaiterConfiguration.maxWaitTime must be greater than 0");if(options.minDelay<=0)throw new Error("WaiterConfiguration.minDelay must be greater than 0");if(options.maxDelay<=0)throw new Error("WaiterConfiguration.maxDelay must be greater than 0");if(options.maxWaitTime<=options.minDelay)throw new Error(`WaiterConfiguration.maxWaitTime [${options.maxWaitTime}] must be greater than WaiterConfiguration.minDelay [${options.minDelay}] for this waiter`);if(options.maxDelay{let onAbort;const promise=new Promise((resolve=>{onAbort=()=>resolve({state:WaiterState.ABORTED});"function"==typeof abortSignal.addEventListener?abortSignal.addEventListener("abort",onAbort):abortSignal.onabort=onAbort}));return{clearListener(){"function"==typeof abortSignal.removeEventListener&&abortSignal.removeEventListener("abort",onAbort)},aborted:promise}};createWaiter=async(options,input,acceptorChecks)=>{var _a7;const params={...waiterServiceDefaults,...options};validateWaiterOptions(params);const exitConditions=[runPolling(params,input,acceptorChecks)],finalize=[];if(options.abortSignal){const{aborted:aborted2,clearListener}=abortTimeout(options.abortSignal);finalize.push(clearListener);exitConditions.push(aborted2)}if(null==(_a7=options.abortController)?void 0:_a7.signal){const{aborted:aborted2,clearListener}=abortTimeout(options.abortController.signal);finalize.push(clearListener);exitConditions.push(aborted2)}return Promise.race(exitConditions).then((result=>{for(const fn of finalize)fn();return result}))};checkState=async(client,input)=>{let reason;try{reason=await client.send(new HeadBucketCommand(input));return{state:WaiterState.SUCCESS,reason}}catch(exception){reason=exception;if(exception.name&&"NotFound"==exception.name)return{state:WaiterState.RETRY,reason}}return{state:WaiterState.RETRY,reason}};checkState2=async(client,input)=>{let reason;try{reason=await client.send(new HeadBucketCommand(input))}catch(exception){reason=exception;if(exception.name&&"NotFound"==exception.name)return{state:WaiterState.SUCCESS,reason}}return{state:WaiterState.RETRY,reason}};checkState3=async(client,input)=>{let reason;try{reason=await client.send(new HeadObjectCommand(input));return{state:WaiterState.SUCCESS,reason}}catch(exception){reason=exception;if(exception.name&&"NotFound"==exception.name)return{state:WaiterState.RETRY,reason}}return{state:WaiterState.RETRY,reason}};checkState4=async(client,input)=>{let reason;try{reason=await client.send(new HeadObjectCommand(input))}catch(exception){reason=exception;if(exception.name&&"NotFound"==exception.name)return{state:WaiterState.SUCCESS,reason}}return{state:WaiterState.RETRY,reason}};paginators={paginateListBuckets,paginateListDirectoryBuckets,paginateListObjectsV2,paginateListParts};waiters={waitUntilBucketExists:async(params,input)=>{const result=await createWaiter({minDelay:5,maxDelay:120,...params},input,checkState);return checkExceptions(result)},waitUntilBucketNotExists:async(params,input)=>{const result=await createWaiter({minDelay:5,maxDelay:120,...params},input,checkState2);return checkExceptions(result)},waitUntilObjectExists:async(params,input)=>{const result=await createWaiter({minDelay:5,maxDelay:120,...params},input,checkState3);return checkExceptions(result)},waitUntilObjectNotExists:async(params,input)=>{const result=await createWaiter({minDelay:5,maxDelay:120,...params},input,checkState4);return checkExceptions(result)}};createAggregatedClient({AbortMultipartUploadCommand,CompleteMultipartUploadCommand,CopyObjectCommand,CreateBucketCommand,CreateBucketMetadataConfigurationCommand,CreateBucketMetadataTableConfigurationCommand,CreateMultipartUploadCommand,CreateSessionCommand,DeleteBucketCommand,DeleteBucketAnalyticsConfigurationCommand,DeleteBucketCorsCommand,DeleteBucketEncryptionCommand,DeleteBucketIntelligentTieringConfigurationCommand,DeleteBucketInventoryConfigurationCommand,DeleteBucketLifecycleCommand,DeleteBucketMetadataConfigurationCommand,DeleteBucketMetadataTableConfigurationCommand,DeleteBucketMetricsConfigurationCommand,DeleteBucketOwnershipControlsCommand,DeleteBucketPolicyCommand,DeleteBucketReplicationCommand,DeleteBucketTaggingCommand,DeleteBucketWebsiteCommand,DeleteObjectCommand,DeleteObjectsCommand,DeleteObjectTaggingCommand,DeletePublicAccessBlockCommand,GetBucketAbacCommand,GetBucketAccelerateConfigurationCommand,GetBucketAclCommand,GetBucketAnalyticsConfigurationCommand,GetBucketCorsCommand,GetBucketEncryptionCommand,GetBucketIntelligentTieringConfigurationCommand,GetBucketInventoryConfigurationCommand,GetBucketLifecycleConfigurationCommand,GetBucketLocationCommand,GetBucketLoggingCommand,GetBucketMetadataConfigurationCommand,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,PutBucketAbacCommand,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,RenameObjectCommand,RestoreObjectCommand,SelectObjectContentCommand,UpdateBucketMetadataInventoryTableConfigurationCommand,UpdateBucketMetadataJournalTableConfigurationCommand,UpdateObjectEncryptionCommand,UploadPartCommand,UploadPartCopyCommand,WriteGetObjectResponseCommand},S3=class extends S3Client{},{paginators,waiters});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<>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>rvb]=sv}}else{co2=new u16(s2);for(i2=0;i2>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;i2m3&&(m3=a2[i2]);return m3};bits=function(d4,p2,m3){var o2=p2/8|0;return(d4[o2]|d4[o2+1]<<8)>>(7&p2)&m3};bits16=function(d4,p2){var o2=p2/8|0;return(d4[o2]|d4[o2+1]<<8|d4[o2+2]<<16)>>(7&p2)};shft=function(p2){return(p2+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,t9,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((t9=(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,t9),bt2);st.b=bt2+=l2,st.p=pos=8*t9,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>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<>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<>4;d4||err2(3);pos+=15&d4;dt=fd[dsym];if(dsym>3){b3=fdeb[dsym];dt+=bits16(dat,pos)&(1<tbts){noSt&&err2(0);break}resize&&cbuf(bt2+131072);end=bt2+add;if(bt2>8};wbits16=function(d4,p2,v2){v2<<=7&p2;var o2=p2/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,t9=[];for(i2=0;i2maxSym&&(maxSym=t22[i2].s);tr=new u16(maxSym+1);if((mbt=ln(t9[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(;i2mb))break;dt+=cst-(1<>=lft;for(;dt>0;){i2_2=t22[i2].s;tr[i2_2]=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>8;out[o2+2]=255^out[o2];out[o2+3]=255^out[o2+1];for(i2=0;i24&&!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,p2,dat.subarray(bs2,bs2+bl2));wbits(out,p2,1+(dtlen15&&(wbits(out,p2,clct[i2]>>5&127),p2+=clct[i2]>>12)}}}else lm=flm,ll=flt,dm=fdm,dl=fdt;for(i2=0;i2255){wbits16(out,p2,lm[257+(len=sym>>18&31)]),p2+=ll[len+257];len>7&&(wbits(out,p2,sym>>23&31),p2+=fleb[len]);wbits16(out,p2,dm[dst=31&sym]),p2+=dl[dst];dst>3&&(wbits16(out,p2,sym>>5&8191),p2+=fdeb[dst])}else wbits16(out,p2,lm[sym]),p2+=ll[sym];wbits16(out,p2,lm[256]);return p2+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<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(;nll2){l2=nl,d4=dif;if(nl>maxn)break;mmd=Math.min(dif,nl-2);md=0;for(j2=0;j2md&&(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){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,t9,dt=fn(),st=fn.toString(),ks=st.slice(st.indexOf("[")+1,st.lastIndexOf("]")).replace(/\s+/g,"").split(",");for(i2=0;i2{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 _a7;if(void 0===index6){index6=null!=(_a7=indexes.get(key3))?_a7:0;indexes.set(key3,index6+1)}const storeKey=createId(type,key3,index6);await this._db.set(storeKey,obj)}async _dequeue(type,key3){const range4=createRange(type,key3),keys3=(await this._db.keys(range4[0],range4[1])).filter((e3=>!inProgress.has(e3)));if(0!==keys3.length)return await this.expose(keys3[0])}async _dequeueWithCommit(type,key3){const range4=createRange(type,key3),keysAll=await this._db.keys(range4[0],range4[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{};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;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 _a7,_b5,_c3,_d2,_e2,_f,_g;const old=this.env.replicationStat.value;this.env.replicationStat.value={sent:null!=(_a7=info3.sent)?_a7: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()}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")}async decryptDataV2(encrypted,set2){const salt=await this.getReplicationPBKDF2Salt();return await decryptBinary(encrypted,set2.passphrase,salt)}async decryptDataV1(encrypted,set2){return await decryptBinary2(encrypted,set2.passphrase,set2.useDynamicIterationCount)}async decryptDownloaded(key3,encrypted,set2){const u2=new Uint8Array(encrypted);try{return!set2.encrypt||""==set2.passphrase||this.isEncryptionPrevented(key3)?u2:set2.E2EEAlgorithm===E2EEAlgorithms.ForceV1?await this.decryptDataV1(u2,set2):await this.decryptDataV2(u2,set2)}catch(ex){Logger(`Failed to decrypt in v2. Falling back to v1: ${key3}`,LOG_LEVEL_INFO);try{const r4=await this.decryptDataV1(u2,set2);Logger(`Decrypted in v1: ${key3}`,LOG_LEVEL_VERBOSE);return r4}catch(ex2){Logger(`Could not decrypt in v1: ${key3}`,LOG_LEVEL_VERBOSE);Logger(ex,LOG_LEVEL_VERBOSE);Logger(ex2,LOG_LEVEL_VERBOSE);throw ex2}}}async encryptForUpload(key3,data,set2){if(!set2.encrypt||""==set2.passphrase||this.isEncryptionPrevented(key3))return data;if(set2.E2EEAlgorithm===E2EEAlgorithms.V2){const salt=await this.getReplicationPBKDF2Salt();return await encryptBinary(data,set2.passphrase,salt)}return await encryptBinary2(data,set2.passphrase,set2.useDynamicIterationCount)}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 _a7;return null!=(_a7=e3.id)?_a7: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 _a7;return{...acc,[id]:[...null!=(_a7=acc[id])?_a7:[],...revs]}}),{}),diffRevs=await this.db.revsDiff(docsRevs),saveDocs=docs.filter((e3=>{var _a7,_b5;return e3._id in diffRevs&&"missing"in diffRevs[e3._id]&&-1!==(null!=(_b5=null==(_a7=diffRevs[e3._id].missing)?void 0:_a7.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 _a7;return null!=(_a7=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)}})))&&_a7}requestStop(){this.requestedStop=!0}};JournalSyncMinio=class extends JournalSyncAbstract{_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 _a7;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:Errors2}=r5;deleteCount+=(null==Deleted?void 0:Deleted.length)||0;errorCount+=(null==Errors2?void 0:Errors2.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==(_a7=null==r4?void 0:r4.Deleted)?void 0:_a7.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{const buf=new Uint8Array(await blob.arrayBuffer()),set2=this.env.getSettings(),u2=await this.encryptForUpload(key3,buf,set2),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){const u2=new Uint8Array(await r4.Body.transformToByteArray());try{return await this.decryptDownloaded(key3,u2,set2)}catch(ex){Logger(`Could not decrypt downloaded file ${key3}`,LOG_LEVEL_NOTICE);Logger(ex,LOG_LEVEL_VERBOSE);return!1}}}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 _a7;return null==(_a7=e3.Key)?void 0:_a7.startsWith(this.prefix)})).map((e3=>{var _a7;return null==(_a7=e3.Key)?void 0:_a7.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 _a7;try{const remoteMilestone=await this.client.downloadJson(MILSTONE_DOCID);if(!remoteMilestone)throw new Error("Missing remote milestone");return(null==(_a7=null==remoteMilestone?void 0:remoteMilestone.tweak_values)?void 0:_a7[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{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 _a7;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==(_a7=null==remoteMilestone?void 0:remoteMilestone.tweak_values)?void 0:_a7[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 _a7;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==(_a7=null==info3?void 0:info3.sizes)?void 0:_a7.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('
 
');root4=from_html('

TESTING BENCH: Self-hosted LiveSync

Module Checks

Synchronisation Result Status

 

Performance test

',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 _a7;null==(_a7=this.component)||_a7.$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 _a7;const isObsolete=value3.is_obsolete?" (obsolete)":"",desc=null!=(_a7=value3.desc)?_a7:"";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.onLayoutReady.addHandler(this._everyOnLayoutReady.bind(this));services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this));services.appLifecycle.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this));services.test.test.addHandler(this._everyModuleTest.bind(this));services.test.addTestResult.setHandler(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 _a7;return null==(_a7=this.app.vault.adapter.insensitive)||_a7}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 _a7,_b5;return(null==(_a7=this.core.settings)?void 0:_a7.batchSave)&&1!=(null==(_b5=this.core.settings)?void 0:_b5.liveSync)}get batchSaveMinimumDelay(){var _a7,_b5;return null!=(_b5=null==(_a7=this.core.settings)?void 0:_a7.batchSaveMinimumDelay)?_b5:DEFAULT_SETTINGS.batchSaveMinimumDelay}get batchSaveMaximumDelay(){var _a7,_b5;return null!=(_b5=null==(_a7=this.core.settings)?void 0:_a7.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.settings.maxMTimeForReflectEvents>0)){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 _a7;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!=(_a7=v2.split("/").pop())?_a7:"").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.isStorageInsensitive.setHandler(this._isStorageInsensitive.bind(this));services.setting.shouldCheckCaseInsensitively.setHandler(this._shouldCheckCaseInsensitive.bind(this));services.appLifecycle.onFirstInitialise.addHandler(this._everyOnFirstInitialize.bind(this));services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this));services.appLifecycle.onLoaded.addHandler(this._everyOnload.bind(this));services.fileProcessing.commitPendingFileEvents.addHandler(this._everyCommitPendingFileEvent.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==(_a6=configurationNames.hashAlg)?void 0:_a6.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"},maxMTimeForReflectEvents:{name:"Maximum file modification time for reflected file events",desc:"Files with modification times greater than this value (in seconds since the Unix epoch) will not have their events reflected. Set to 0 to disable this limit."}};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;root5=from_html('
');$$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);}'};CONTEXT_DIALOG_CONTROLS="svelte-dialog-controls";SvelteDialogManagerBase=class{get context(){return this._context}get dependents(){return this._dependents}constructor(c3,dependents){this._context=c3;this._dependents=dependents}async open(component2,initialData){return await this.openSvelteDialog(component2,initialData)}async openWithExplicitCancel(component2,initialData){for(let i2=0;i2<10;i2++){const ret=await this.openSvelteDialog(component2,initialData);if(void 0!==ret)return ret;if(this.dependents.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("

");root6=from_html('

');$$css7={hash:"svelte-1gf4irx",code:".dialog-header.svelte-1gf4irx {display:none;}"};root_111=from_html("

");root7=from_html("
");root8=from_html("");delegate(["click"]);root_113=from_html("

");root9=from_html('
');$$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('
');$$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('
');root12=from_html('
');root13=from_html('
');root_44=from_html(" ",1);root_24=from_html(" ",1);root_72=from_html(" ",1);root14=from_html(" ",1);root_25=from_html("

");root_114=from_html("
");root15=from_html('
');root16=from_html('
',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("
  1. On this device, please keep this Vault open.
  2. On the source device, open Obsidian.
  3. On the source device, from the command palette, run the 'Show settings as a QR code' command.
  4. On this device, switch to the camera app or use a QR code scanner to scan the displayed QR code.
");root19=from_html(" ",1);root20=from_html('');root21=from_html(' ',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.
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('');root_74=from_html(" ",1);root22=from_html(" ",1);root_116=from_html("

The connection to the server has been configured successfully. As the next step, the synchronisation data on the server will be built based on the current data on this device.

IMPORTANT
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.

",1);root_47=from_html(" ",1);root23=from_html(" ",1);root_117=from_html("

The connection to the server has been configured successfully. As the next step, the latest synchronisation data will be downloaded from the server to this device.

PLEASE NOTE
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.

",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, the local database, that is to say the synchronisation information, must be reconstituted.",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 _a7,_b5,_c3,_d2,_e2,_f,_g,_h2,_i2,_j,_k,_l,_m2,_n;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!=(_a7=r4.headers.server)?_a7: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!=(_h2=null==(_g=null==responseConfig?void 0:responseConfig.chttpd)?void 0:_g.max_http_request_size)?_h2: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==(_l=null==responseConfig?void 0:responseConfig.cors)?void 0:_l.origins)?_m2:"")+"").split(",");if("*"==(null==(_n=null==responseConfig?void 0:responseConfig.cors)?void 0:_n.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('
');root_120=from_html('
');root_84=from_html("

Issue detection log:

",1);root27=from_html('
',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('');root_49=from_html('');root_64=from_html('');root_85=from_html('');root_1110=from_html('');root_134=from_html('');root_142=from_html("");root_152=from_html('');root_162=from_html('');root_182=from_html('');root_192=from_html('');root_123=from_html(" ",1);root_242=from_html(" ",1);root28=from_html("
",1);root_213=from_html('');root_410=from_html('');root_65=from_html('');root_76=from_html('');root_86=from_html('');root_93=from_html('');root_1111=from_html('');root_143=from_html('');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");rnds8=new Uint8Array(16);regex_default=/^(?:[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_default=function validate2(uuid2){return"string"==typeof uuid2&®ex_default.test(uuid2)};byteToHex=[];for(i2=0;i2<256;++i2)byteToHex.push((i2+256).toString(16).substr(1));stringify_default=function stringify(arr){var offset=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,uuid2=(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]]).toLowerCase();if(!validate_default(uuid2))throw TypeError("Stringified UUID is invalid");return uuid2};v4_default=function v42(options,buf,offset){var rnds,i2;(rnds=(options=options||{}).random||(options.rng||rng)())[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_default(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_events13=__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_events13.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;parser2=/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;uuid=v4_default;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(val){return rowFilter(val,userValue,Object.keys(userValue))})):docFieldValue.some((function(val){return matchSelector(userValue,doc,parsedField,val)})))},$allMatch:function(doc,userValue,parsedField,docFieldValue){return!!Array.isArray(docFieldValue)&&0!==docFieldValue.length&&("object"==typeof docFieldValue[0]&&null!==docFieldValue[0]?docFieldValue.every((function(val){return rowFilter(val,userValue,Object.keys(userValue))})):docFieldValue.every((function(val){return matchSelector(userValue,doc,parsedField,val)})))},$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:validate3,normalize,shouldFilter,filter:filter2}};import_events14=__toESM(require_events());Changes2=class extends import_events14.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_events14.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{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;i3x2.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{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{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{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_default();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_events14.default;(function setUpEventEmitter(Pouch){Object.keys(import_events14.default.prototype).forEach((function(key3){"function"==typeof import_events14.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 val=row.value;return val&&"object"==typeof val&&val._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 val=opts[paramName];if(void 0!==val){asJson&&(val=encodeURIComponent(JSON.stringify(val)));params.push(paramName+"="+val)}}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.length0&&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 group4 of groups){const reduceTry=tryReduce(view.sourceDB,reduceFun,group4.keys,group4.values,!1);if(reduceTry.error&&reduceTry.error instanceof BuiltInError)throw reduceTry.error;results.push({value:reduceTry.error?null:reduceTry.output,key:group4.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(!(keys3expectedKeys))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{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_events15.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('');on_click3=(_,setDefaultRelay)=>setDefaultRelay();root_34=from_html(' ',1);on_click_1=(__1,generateDefaultGroupId)=>generateDefaultGroupId();root_411=from_html(' ',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.
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('');root_87=from_html('');root_103=from_html('');root_153=from_html('');root_163=from_html('');root_124=from_html(" ",1);root_215=from_html(" ",1);root30=from_html(" ",1);delegate(["click"]);root_216=from_html(' ',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.
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('');root_94=from_html("");root_88=from_html("");root_78=from_html(" ",1);root_125=from_html("

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.

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.

Please understand that this is intended behaviour.

",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{get dialogManager(){return this.services.UI.dialogManager}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.onLayoutReady.addHandler(this._everyOnLayoutReady.bind(this));services.appLifecycle.onFirstInitialise.addHandler(this._everyOnFirstInitialize.bind(this))}};ModuleCheckRemoteSize=class extends AbstractObsidianModule{checkRemoteSize(){this.settings.notifyThresholdOfRemoteStorageSize=1;return this._allScanStat()}async _allScanStat(){var _a7;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==(_a7=this.core.replicator)?void 0:_a7.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.onScanningStartupIssues.addHandler(this._allScanStat.bind(this));services.appLifecycle.onInitialise.addHandler(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 p2=ret.result;if(!await this.core.databaseFileAccess.storeContent(path2,p2)){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{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 p2=conflictCheckResult.diff.map((e3=>e3[1])).join(""),delRev=testDoc._conflicts[0];if(!await this.core.databaseFileAccess.storeContent(filename,p2)){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&¬es.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&¬es.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.onScanningStartupIssues.addHandler(this._allScanStat.bind(this));services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this));services.conflict.resolveByUserInteraction.addHandler(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 _a7;return Promise.resolve(null!=(_a7=localStorage.getItem("ls-setting-passphrase"))&&_a7)},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.onLayoutReady.addHandler(this._everyOnLayoutReady.bind(this));services.setting.clearUsedPassphrase.setHandler(this._clearUsedPassphrase.bind(this));services.setting.decryptSettings.setHandler(this._decryptSettings.bind(this));services.setting.adjustSettings.setHandler(this._adjustSettings.bind(this));services.setting.loadSettings.setHandler(this._loadSettings.bind(this));services.setting.currentSettings.setHandler(this._currentSettings.bind(this));services.setting.saveDeviceAndVaultName.setHandler(this._saveDeviceAndVaultName.bind(this));services.setting.saveSettingData.setHandler(this._saveSettingData.bind(this))}};root_217=from_html("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.
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("To minimise the creation of new conflicts, 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("It is strongly advised to create a backup before proceeding. Continuing without a backup may lead\n to data loss.
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("

",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 the single, authoritative master copy.",1);root_413=from_html(" ",1);root_37=from_html(" ",1);root_144=from_html("You should create a new synchronisation destination and rebuild your data there.
After that,\n synchronise to a brand new vault on each other device with the new remote one by one.
");root_126=from_html(" ",1);root_95=from_html(" ",1);root_172=from_html(" ",1);root33=from_html("
",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)}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)}get dialogManager(){return this.core.services.UI.dialogManager}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.onLayoutReady.addHandler(this._everyOnLayoutReady.bind(this))}};ModuleObsidianMenu=class extends AbstractObsidianModule{_everyOnloadStart(){(0,import_obsidian.addIcon)("replicate",'\n \n \n \n \n ');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)}onBindFunction(core,services){services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this));services.appLifecycle.onLoaded.addHandler(this._everyOnload.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.onLoaded.addHandler(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.onLoaded.addHandler(this._everyOnload.bind(this));services.test.test.addHandler(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 _a7,_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==(_a7=entry._rev)?void 0:_a7.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.onInitialise.addHandler(this._everyOnloadStart.bind(this));services.fileProcessing.processFileEvent.addHandler(this._anyHandlerProcessesFileEvent.bind(this));services.replication.processSynchroniseResult.addHandler(this._anyProcessReplicatedDoc.bind(this))}};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")}_getLastPostFailedBySize(){return!this.last_successful_post}async __fetchByAPI(url,authHeader,opts){var _a7,_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!=(_a7=null==transformedHeaders?void 0:transformedHeaders["content-type"])?_a7: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 _a7;const authHeader=await this._authHeader.getAuthorizationHeader(auth);let size="";const localURL=url.toString().substring(uri.length),method=null!=(_a7=null==opts?void 0:opts.method)?_a7:"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}}_vaultName(){return this.app.vault.getName()}_getVaultName(){var _a7;return this.services.vault.vaultName()+((null==(_a7=this.settings)?void 0:_a7.additionalSuffixOfDatabaseName)?"-"+this.settings.additionalSuffixOfDatabaseName:"")}_getActiveFilePath(){const file=this.app.workspace.getActiveFile();if(file)return getPathFromTFile(file)}_reportUnresolvedMessages(){return Promise.resolve([...this._previousErrors])}onBindFunction(core,services){services.API.isLastPostFailedDueToPayloadSize.setHandler(this._getLastPostFailedBySize.bind(this));services.remote.connect.setHandler(this._connectRemoteCouchDB.bind(this));services.vault.getVaultName.setHandler(this._getVaultName.bind(this));services.vault.vaultName.setHandler(this._vaultName.bind(this));services.vault.getActiveFilePath.setHandler(this._getActiveFilePath.bind(this));services.appLifecycle.getUnresolvedMessages.addHandler(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 _a7,_b5;this._log("Modifying callback of the save command",LOG_LEVEL_VERBOSE);const saveCommandDefinition=null==(_b5=null==(_a7=this.app.commands)?void 0:_a7.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.onLayoutReady.addHandler(this._everyOnLayoutReady.bind(this));services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this));services.appLifecycle.performRestart.setHandler(this._performRestart.bind(this));services.appLifecycle.askRestart.setHandler(this._askReload.bind(this));services.appLifecycle.scheduleRestart.setHandler(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 _a7,_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==(_a7=this.nameBuf.textContent)?void 0:_a7.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 _a7,_b5;const value=Number(TextValue);let hasError=!1;isNaN(value)&&(hasError=!0);void 0!==opt.clampMax&&opt.clampMaxvalue&&(opt.acceptZero&&0==value||(hasError=!0));if(hasError){this.setTooltip($msg("liveSyncSetting.valueShouldBeInRange",{min:(null==(_a7=opt.clampMin)?void 0:_a7.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 _a7;return setValue(null!=(_a7=_LiveSyncSetting.env.editingSettings[key3])&&_a7)};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 _a7,_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==(_a7=_LiveSyncSetting.env.initialSettings)?void 0:_a7[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()}};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 _a7;null==(_a7=this.callback)||_a7.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 _a7,_b5;if(void 0!==this.timeout){this.timeout--;if(this.timeout<0){if(this.timer){clearInterval(this.timer);null==(_a7=this.defaultButtonComponent)||_a7.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 _a7;if(this.timer){labelWrapper.empty();labelWrapper.style.display="none";clearInterval(this.timer);this.timer=void 0;null==(_a7=this.defaultButtonComponent)||_a7.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()}));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.43\n\n5th, February, 2026\n\n### Fixed\n\n- Encryption/decryption issues when using Object Storage as remote have been fixed.\n - Now the plug-in falls back to V1 encryption/decryption when V2 fails (if not configured as ForceV1).\n - This may fix the issue reported in #772.\n\n### Notice\n\nQuite a few packages have been updated in this release. Please report if you find any unexpected behaviour after this update.\n\n\n## 0.25.42\n\n2nd, February, 2026\n\nThis release is identical to 0.25.41-patched-3, except for the version number.\n\n### Refactored\n\n- Now the service context is `protected` instead of `private` in `ServiceBase`.\n - This change allows derived classes to access the context directly.\n- Some dynamically bound services have been moved to services for better dependency management.\n- `WebPeer` has been moved to the main repository from the sub repository `livesync-commonlib` for correct dependency management.\n- Migrated from the outdated, unstable platform abstraction layer to services.\n - A bit more services will be added in the future for better maintainability.\n\n## 0.25.41\n\n24th January, 2026\n\n### Fixed\n\n- No longer `No available splitter for settings!!` errors occur after fetching old remote settings while rebuilding local database. (#748)\n\n### Improved\n\n- Boot sequence warning is now kept in the in-editor notification area.\n\n### New feature\n\n- We can now set the maximum modified time for reflect events in the settings. (for #754)\n - This setting can be configured from `Patches` -> `Remediation` in the settings dialogue.\n - Enabling this setting will restrict the propagation from the database to storage to only those changes made before the specified date and time.\n - This feature is primarily intended for recovery purposes. After placing `redflag.md` in an empty vault and importing the Self-hosted LiveSync configuration, please perform this configuration, and then fetch the local database from the remote.\n - This feature is useful when we want to prevent recent unwanted changes from being reflected in the local storage.\n\n### Refactored\n\n- Module to service refactoring has been started for better maintainability:\n - UI module has been moved to UI service.\n\n### Behaviour change\n\n- Default chunk splitter version has been changed to `Rabin-Karp` for new installations.\n\n## 0.25.40\n\n23rd January, 2026\n\n### Fixed\n\n- Fixed an issue where some events were not triggered correctly after the refactoring in 0.25.39.\n\n## 0.25.39\n\n23rd January, 2026\n\nAlso no behaviour changes or fixes in this release. Just refactoring for better maintainability. Thank you for your patience! I will address some of the reported issues soon.\nHowever, this is not a minor refactoring, so please be careful. Let me know if you find any unexpected behaviour after this update.\n\n### Refactored\n\n- Rewrite the service's binding/handler assignment systems\n- Removed loopholes that allowed traversal between services to clarify dependencies.\n- Consolidated the hidden state-related state, the handler, and the addition of bindings to the handler into a single object.\n - Currently, functions that can have handlers added implement either addHandler or setHandler directly on the function itself.\n I understand there are differing opinions on this, but for now, this is how it stands.\n- Services now possess a Context. Please ensure each platform has a class that inherits from ServiceContext.\n- To permit services to be dynamically bound, the services themselves are now defined by interfaces.\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\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\nOlder notes are in\n[updates_old.md](https://github.com/vrtmrz/obsidian-livesync/blob/main/updates_old.md).\n";lastVersion=~~(versionNumberString2Number("0.25.43")/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('
',1);root34=from_html('
');$$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('
  • ');root35=from_html('
    ');$$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.43";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.43\n\n5th, February, 2026\n\n### Fixed\n\n- Encryption/decryption issues when using Object Storage as remote have been fixed.\n - Now the plug-in falls back to V1 encryption/decryption when V2 fails (if not configured as ForceV1).\n - This may fix the issue reported in #772.\n\n### Notice\n\nQuite a few packages have been updated in this release. Please report if you find any unexpected behaviour after this update.\n\n\n## 0.25.42\n\n2nd, February, 2026\n\nThis release is identical to 0.25.41-patched-3, except for the version number.\n\n### Refactored\n\n- Now the service context is `protected` instead of `private` in `ServiceBase`.\n - This change allows derived classes to access the context directly.\n- Some dynamically bound services have been moved to services for better dependency management.\n- `WebPeer` has been moved to the main repository from the sub repository `livesync-commonlib` for correct dependency management.\n- Migrated from the outdated, unstable platform abstraction layer to services.\n - A bit more services will be added in the future for better maintainability.\n\n## 0.25.41\n\n24th January, 2026\n\n### Fixed\n\n- No longer `No available splitter for settings!!` errors occur after fetching old remote settings while rebuilding local database. (#748)\n\n### Improved\n\n- Boot sequence warning is now kept in the in-editor notification area.\n\n### New feature\n\n- We can now set the maximum modified time for reflect events in the settings. (for #754)\n - This setting can be configured from `Patches` -> `Remediation` in the settings dialogue.\n - Enabling this setting will restrict the propagation from the database to storage to only those changes made before the specified date and time.\n - This feature is primarily intended for recovery purposes. After placing `redflag.md` in an empty vault and importing the Self-hosted LiveSync configuration, please perform this configuration, and then fetch the local database from the remote.\n - This feature is useful when we want to prevent recent unwanted changes from being reflected in the local storage.\n\n### Refactored\n\n- Module to service refactoring has been started for better maintainability:\n - UI module has been moved to UI service.\n\n### Behaviour change\n\n- Default chunk splitter version has been changed to `Rabin-Karp` for new installations.\n\n## 0.25.40\n\n23rd January, 2026\n\n### Fixed\n\n- Fixed an issue where some events were not triggered correctly after the refactoring in 0.25.39.\n\n## 0.25.39\n\n23rd January, 2026\n\nAlso no behaviour changes or fixes in this release. Just refactoring for better maintainability. Thank you for your patience! I will address some of the reported issues soon.\nHowever, this is not a minor refactoring, so please be careful. Let me know if you find any unexpected behaviour after this update.\n\n### Refactored\n\n- Rewrite the service's binding/handler assignment systems\n- Removed loopholes that allowed traversal between services to clarify dependencies.\n- Consolidated the hidden state-related state, the handler, and the addition of bindings to the handler into a single object.\n - Currently, functions that can have handlers added implement either addHandler or setHandler directly on the function itself.\n I understand there are differing opinions on this, but for now, this is how it stands.\n- Services now possess a Context. Please ensure each platform has a class that inherits from ServiceContext.\n- To permit services to be dynamically bound, the services themselves are now defined by interfaces.\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\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\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 _a7;const changedKeys=Object.keys(null!=(_a7=this.editingSettings)?_a7:{}).filter((e3=>this.isDirty(e3)));this.applySetting(changedKeys);this.reloadAllSettings()}async saveLocalSetting(key3){var _a7,_b5,_c3,_d2;if("configPassphrase"==key3){localStorage.setItem("ls-setting-passphrase",null!=(_b5=null==(_a7=this.editingSettings)?void 0:_a7[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 handlers3=this.onSavedHandlers.filter((e3=>-1!==appliedKeys.indexOf(e3.key))).map((e3=>e3.handler(this.editingSettings[e3.key])));await Promise.all(handlers3);keys3.forEach((e3=>this.refreshSetting(e3)))}async saveAllDirtySettings(){var _a7;const changedKeys=Object.keys(null!=(_a7=this.editingSettings)?_a7:{}).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 _a7,_b5;return{syncMode:(null==(_a7=this.editingSettings)?void 0:_a7.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 _a7;return isObjectDifferent(this.editingSettings[key3],null==(_a7=this.initialSettings)?void 0:_a7[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 _a7;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==(_a7=this.initialSettings)?void 0:_a7[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 _a7,_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==(_a7=this.plugin)?void 0:_a7.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.onInitialise.addHandler(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 _a7,_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==(_a7=w2._revs_info)?void 0:_a7.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
    (${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"+escapeStringToHTML(x2)+"":x1==import_diff_match_patch.DIFF_EQUAL?result+=""+escapeStringToHTML(x2)+"":x1==import_diff_match_patch.DIFF_INSERT&&(result+=""+escapeStringToHTML(x2)+"")}result=result.replace(/\n/g,"
    ")}else if(isImage(this.file)){result=`
    \n
    \n \n \n
    \n
    `;this.contentView.removeClass("op-pre")}}}if(null==result)if("string"!=typeof w1data){if(isImage(this.file)){result=`
    \n
    \n\n
    \n
    `;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.onInitialise.addHandler(this._everyOnloadStart.bind(this))}};root_129=from_html('
    Gathering information...
    ');root_218=from_html('Chunks');root_38=from_html('
    ');root_414=from_html('
    ');root_67=from_html(' ');root_810=from_html(' ');root_55=from_html(' ');root_96=from_html('
    ');root_105=from_html('
    ');root36=from_html('

    Vault history

    DatePathRevStat
    ');$$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.onInitialise.addHandler(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.onInitialise.addHandler(this._everyOnloadStart.bind(this))}};ModuleInitializerFile=class extends AbstractModule{constructor(){super(...arguments);this._detectedErrors=new Set}logDetectedError(message,logLevel=LOG_LEVEL_INFO,key3){this._detectedErrors.add(message);eventHub.emitEvent("on-unresolved-error");this._log(message,logLevel,key3)}resetDetectedError(message){eventHub.emitEvent("on-unresolved-error");this._detectedErrors.delete(message)}async _performFullScan(showingNotice,ignoreSuspending=!1){this._log("Opening the key-value database",LOG_LEVEL_VERBOSE);const isInitialized=await this.core.kvDB.get("initialized")||!1,ERR_NOT_CONFIGURED="LiveSync is not configured yet. Synchronising between the storage and the local database is now prevented.";if(!this.settings.isConfigured){this.logDetectedError(ERR_NOT_CONFIGURED,showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"syncAll");return!1}this.resetDetectedError(ERR_NOT_CONFIGURED);const ERR_SUSPENDING="Now suspending file watching. Synchronising between the storage and the local database is now prevented.";if(!ignoreSuspending&&this.settings.suspendFileWatching){this.logDetectedError(ERR_SUSPENDING,showingNotice?LOG_LEVEL_NOTICE:LOG_LEVEL_INFO,"syncAll");return!1}const MSG_IN_REMEDIATION="Started in remediation Mode! (Max mtime for reflect events is set). Synchronising between the storage and the local database is now prevented.";this.resetDetectedError(ERR_SUSPENDING);if(this.settings.maxMTimeForReflectEvents>0){this.logDetectedError(MSG_IN_REMEDIATION,LOG_LEVEL_NOTICE,"syncAll");return!1}this.resetDetectedError(MSG_IN_REMEDIATION);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 _a7,_b5,_c3;const w2=databaseFileNameMap[databaseFileNameCI2CS[e3]],path2=null!=(_a7=getPath2(w2))?_a7: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 _a7,_b5;const{file,doc}=e3;null!=(_b5=null==(_a7=doc._conflicts)?void 0:_a7.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&¬es.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);const ERR_INITIALISATION_FAILED="Initializing database has been failed on some module!";if(!await this.services.databaseEvents.onDatabaseInitialised(showingNotice)){this.logDetectedError(ERR_INITIALISATION_FAILED,LOG_LEVEL_NOTICE);return!1}this.resetDetectedError(ERR_INITIALISATION_FAILED);this.services.appLifecycle.markIsReady();await this.services.fileProcessing.commitPendingFileEvents();return!0}this.services.appLifecycle.resetIsReady();return!1}_reportDetectedErrors(){return Promise.resolve(Array.from(this._detectedErrors))}onBindFunction(core,services){services.appLifecycle.getUnresolvedMessages.addHandler(this._reportDetectedErrors.bind(this));services.databaseEvents.initialiseDatabase.setHandler(this._initializeDatabase.bind(this));services.vault.scanVault.setHandler(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 _a7;try{await(null==(_a7=this.core.kvDB)?void 0:_a7.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))),db:Promise.resolve(getDB())}}_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.onUnloadDatabase.addHandler(this._onDBUnload.bind(this));services.databaseEvents.onCloseDatabase.addHandler(this._onDBClose.bind(this));services.databaseEvents.onDatabaseInitialisation.addHandler(this._everyOnInitializeDatabase.bind(this));services.databaseEvents.onResetDatabase.addHandler(this._everyOnResetDatabase.bind(this));services.database.openSimpleStore.setHandler(this._getSimpleStore.bind(this));services.appLifecycle.onSettingLoaded.addHandler(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.createPouchDBInstance.setHandler(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 _a7;const old=this._queuedChanges.find((e3=>e3._id==doc._id)),docNote=`${"path"in doc?getPath2(doc):""} (${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!=(_a7=old._rev)?_a7:"";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){var _a7;try{if(isAnyNote(change)){const docMtime=null!=(_a7=change.mtime)?_a7:0,maxMTime=this.replicator.settings.maxMTimeForReflectEvents;if(maxMTime>0&&docMtime>maxMTime){const docPath=getPath2(change);this.log(`Processing ${docPath} has been skipped due to modification time (${new Date(1e3*docMtime).toISOString()}) exceeding the limit`,LOG_LEVEL_INFO);return}}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 _a7,_b5,_c3,_d2;const path2=getPath2(dbDoc);try{const savedDoc=await this.localDatabase.getRaw(dbDoc._id,{conflicts:!0,revs_info:!0}),newRev=null!=(_a7=dbDoc._rev)?_a7:"",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 _a7;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==(_a7=this.services.replicator.getActiveReplicator())?void 0:_a7.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 _a7;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==(_a7=this.core.replicator)?void 0:_a7.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 _a7;null==(_a7=this.core.replicator)||_a7.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.getActiveReplicator.setHandler(this._getReplicator.bind(this));services.databaseEvents.onDatabaseInitialisation.addHandler(this._everyOnInitializeDatabase.bind(this));services.databaseEvents.onDatabaseInitialised.addHandler(this._everyOnDatabaseInitialized.bind(this));services.databaseEvents.onResetDatabase.addHandler(this._everyOnResetDatabase.bind(this));services.appLifecycle.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this));services.replication.parseSynchroniseResult.setHandler(this._parseReplicationResult.bind(this));services.appLifecycle.onSuspending.addHandler(this._everyBeforeSuspendProcess.bind(this));services.replication.onBeforeReplicate.addHandler(this._everyBeforeReplicate.bind(this));services.replication.isReplicationReady.setHandler(this._canReplicate.bind(this));services.replication.replicate.setHandler(this._replicate.bind(this));services.replication.replicateByEvent.setHandler(this._replicateByEvent.bind(this));services.remote.replicateAllToRemote.setHandler(this._replicateAllToServer.bind(this));services.remote.replicateAllFromRemote.setHandler(this._replicateAllFromServer.bind(this));services.appLifecycle.getUnresolvedMessages.addHandler(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.getNewReplicator.addHandler(this._anyNewReplicator.bind(this));services.appLifecycle.onResumed.addHandler(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.getNewReplicator.addHandler(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{var _a8;if(keepFileCheckList&&prev)return prev;if(!keepFileCheckList&&prev&&!this.fileListPossiblyChanged)return prev;const fileList=null!=(_a8=ctx.get("fileList"))?_a8:[],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==(_a7=getStoragePathFromUXFileInfo(file).split("/").pop())?void 0:_a7.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 _a7;return this.ignoreFileCache.has(path2)?null!=(_a7=this.ignoreFileCache.get(path2))&&_a7: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.markFileListPossiblyChanged.setHandler(this._markFileListPossiblyChanged.bind(this));services.path.id2path.setHandler(this._id2path.bind(this));services.path.path2id.setHandler(this._path2id.bind(this));services.appLifecycle.onLoaded.addHandler(this._everyOnload.bind(this));services.vault.isFileSizeTooLarge.setHandler(this._isFileSizeExceeded.bind(this));services.vault.isIgnoredByIgnoreFile.setHandler(this._isIgnoredByIgnoreFiles.bind(this));services.vault.isTargetFile.setHandler(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 _a7;null==(_a7=this.periodicSyncProcessor)||_a7.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.onUnload.addHandler(this._allOnUnload.bind(this));services.setting.onBeforeRealiseSetting.addHandler(this._everyBeforeRealizeSetting.bind(this));services.setting.onSettingRealised.addHandler(this._everyAfterRealizeSetting.bind(this));services.appLifecycle.onSuspending.addHandler(this._everyBeforeSuspendProcess.bind(this));services.appLifecycle.onResumed.addHandler(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.markLocked.setHandler(this._markRemoteLocked.bind(this));services.remote.markUnlocked.setHandler(this._markRemoteUnlocked.bind(this));services.remote.markResolved.setHandler(this._markRemoteResolved.bind(this))}};ContentSplitterCore=class{constructor(params){this.options=params;this.initialised=this.initialise(params)}};ContentSplitterBase=class extends ContentSplitterCore{initialise(_options3){this.options=_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||void 0===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 _a7,_b5;if(this._changes){null==(_a7=this._changes)||_a7.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 _a7,_b5;null==(_a7=this._changes)||_a7.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 _a7,_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!=(_a7=diffLeft[leftIdx])?_a7:[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(leftIdxa2.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 _a7,_b5,_c3;const conflictedRev=conflicts[0],conflictedRevNo=Number(conflictedRev.split("-")[0]),commonBase=null!=(_c3=null==(_b5=null==(_a7=((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])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);p2=result}else Logger("Object merge is not applicable..",LOG_LEVEL_VERBOSE)}if(void 0!==p2)return{result:p2,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 _a7,_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!=(_a7=null==obj?void 0:obj.deleted)?_a7: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 _a7,_b5,_c3;const filename=this.id2path(meta._id,meta);if(!this.isTargetFile(filename))return!1;const dispFilename=stripAllPrefixes(filename),deleted=null!=(_b5=null!=(_a7=meta.deleted)?_a7: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 _a7;if(!this.isTargetFile(path2))return!1;const id=await this.path2id(path2);try{return null!=(_a7=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})))&&_a7}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 _a7;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!=(_a7=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})))&&_a7}));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 _a7;options&&(this.options=options);this.settings=this.options.settings;this.useEncryption=null!=(_a7=this.settings.encrypt)&&_a7;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 _a7;null==(_a7=this.chunkManager)||_a7.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.isDatabaseReady.setHandler(this._isDatabaseReady.bind(this));services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this));services.database.openDatabase.setHandler(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.queueCheckForIfOpen.setHandler(this._queueConflictCheckIfOpen.bind(this));services.conflict.queueCheckFor.setHandler(this._queueConflictCheck.bind(this));services.conflict.ensureAllProcessed.setHandler(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.fetchRemotePreferred.setHandler(this._fetchRemotePreferredTweakValues.bind(this));services.tweakValue.checkAndAskResolvingMismatched.setHandler(this._checkAndAskResolvingMismatchedTweaks.bind(this));services.tweakValue.askResolvingMismatched.setHandler(this._askResolvingMismatchedTweaks.bind(this));services.tweakValue.checkAndAskUseRemoteConfiguration.setHandler(this._checkAndAskUseRemoteConfiguration.bind(this));services.tweakValue.askUseRemoteConfiguration.setHandler(this._askUseRemoteConfiguration.bind(this));services.replication.checkConnectionFailure.addHandler(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,((t9,l2)=>this.testBasic(t9,l2)))))}async testBasicLive(isLeader){this.settings.liveSync=!0;await this.saveSettings();await this._test("basic",(async()=>await this.nonLiveTestRunner(isLeader,((t9,l2)=>this.testBasic(t9,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.testMultiDevice.addHandler(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;if(this.core.settings.maxMTimeForReflectEvents>0){const ask=`Your settings restrict file reflection times to no later than ${new Date(this.core.settings.maxMTimeForReflectEvents)}.\n\n**This is a recovery configuration.**\n\nThis operation should only be performed on an empty vault.\nAre you sure you wish to proceed?`,CANCEL="Cancel operation",CLEARANDPROCEED="Clear restriction and proceed",choices=["I understand, proceed",CLEARANDPROCEED,CANCEL],ret=await this.core.confirm.askSelectStringDialogue(ask,choices,{title:"Confirm restricted fetch",defaultAction:CANCEL,timeout:0});if(ret==CLEARANDPROCEED){this.core.settings.maxMTimeForReflectEvents=0;await this.core.saveSettings()}if(ret==CANCEL)return}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.onLoaded.addHandler(this._everyOnload.bind(this));services.database.resetDatabase.setHandler(this._resetLocalDatabase.bind(this));services.remote.tryResetDatabase.setHandler(this._tryResetRemoteDatabase.bind(this));services.remote.tryCreateDatabase.setHandler(this._tryCreateRemoteDatabase.bind(this));services.setting.suspendAllSync.addHandler(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=[],webcrypto6=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 webcrypto6.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),webcrypto6=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 webcrypto6.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.onSettingLoaded.addHandler(this._everyOnloadAfterLoadSettings.bind(this));services.replication.onBeforeReplicate.addHandler(this._everyBeforeReplicate.bind(this));services.test.testMultiDevice.addHandler(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 _a7,_b5,_c3;try{await this.core.services.setting.realiseSetting();void 0!==(null!=(_b5=null==(_a7=this.core.services.setting.currentSettings())?void 0:_a7.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.43",packageVersion:"0.25.43"}));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.43")/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 _a7;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==(_a7=this.core.replicator)||_a7.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 _a7;return this._suspended||!(null==(_a7=this.settings)?void 0:_a7.isConfigured)}_setSuspended(value){this._suspended=value}_isUnloaded(){return this._unloaded}onBindFunction(core,services){super.onBindFunction(core,services);services.appLifecycle.isSuspended.setHandler(this._isSuspended.bind(this));services.appLifecycle.setSuspended.setHandler(this._setSuspended.bind(this));services.appLifecycle.isReady.setHandler(this._isReady.bind(this));services.appLifecycle.markIsReady.setHandler(this._markIsReady.bind(this));services.appLifecycle.resetIsReady.setHandler(this._resetIsReady.bind(this));services.appLifecycle.hasUnloaded.setHandler(this._isUnloaded.bind(this));services.appLifecycle.isReloadingScheduled.setHandler(this._isReloadingScheduled.bind(this));services.appLifecycle.onReady.addHandler(this._onLiveSyncReady.bind(this));services.appLifecycle.onWireUpEvents.addHandler(this._wireUpEvents.bind(this));services.appLifecycle.onLoad.addHandler(this._onLiveSyncLoad.bind(this));services.appLifecycle.onAppUnload.addHandler(this._onLiveSyncUnload.bind(this));services.setting.realiseSetting.setHandler(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.getDeviceAndVaultName.setHandler(this._getDeviceAndVaultName.bind(this));services.setting.setDeviceAndVaultName.setHandler(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 p2=this._progress("",LOG_LEVEL_NOTICE);p2.log("Retrieving chunks informations..");try{return await this.localDatabase.allChunks(includeDeleted)}finally{p2.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 p2=this._progress("",LOG_LEVEL_NOTICE);p2.log("Searching for deleted files..");const deletedDocs=(await this.database.allDocs({include_docs:!0})).rows.filter((e3=>{var _a7,_b5,_c3;return("newnote"==(null==(_a7=e3.doc)?void 0:_a7.type)||"plain"==(null==(_b5=e3.doc)?void 0:_b5.type))&&(null==(_c3=e3.doc)?void 0:_c3.deleted)}));if(0==deletedDocs.length){p2.done("No deleted files found.");return}p2.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();p2.done(`Deleted ${result.filter((e3=>"ok"in e3)).length} / ${deletedDocs.length} files.`)}else p2.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 _a7;try{const oldRevisions=await db.get(doc._id,{revs:!0,revs_info:!0,conflicts:!0}),allRevs=(null==(_a7=oldRevisions._revs_info)?void 0:_a7.length)||0,info3=(oldRevisions._revs_info||[]).filter((e3=>"available"==e3.status&&e3.rev!=doc._rev)).filter((info4=>{var _a8;return!(null==(_a8=chunkUsageMap.get(doc._id))?void 0:_a8.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 _a7;await processChange2(change.doc,null!=(_a7=change.deleted)&&_a7,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 _a7;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==(_a7=null==chunk?void 0:chunk.value)?void 0:_a7.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(" ");root_130=from_html('
    ');root_39=from_html(' ');on_click4=(__3,makeDecision)=>makeDecision(!0,!0);on_click_12=(__4,makeDecision)=>makeDecision(!0,!1);root_56=from_html(' ',1);on_click_2=(__5,makeDecision)=>makeDecision(!1,!0);on_click_3=(__6,makeDecision)=>makeDecision(!1,!1);root_68=from_html(' ',1);root_415=from_html(" ",1);on_click_4=(__7,revokeDecision)=>revokeDecision();root_79=from_html('');root_97=from_html('');root_106=from_html('');root_811=from_html('
    ');root37=from_html('
    ');$$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('

    ');on_click5=(__5,useDefaultRelay)=>useDefaultRelay();on_click_13=(__6,chooseRandom)=>chooseRandom();root_310=from_html('
    Enable P2P Replicator
    Relay settings
    Room ID This can isolate your connections between devices. Use the same Room ID for the same\n devices.
    Password This password is used to encrypt the connection. Use something long enough.
    This device name Device name to identify the device. Please use shorter one for the stable peer\n detection, i.e., "iphone-16" or "macbook-2021".
    Auto Connect
    Start change-broadcasting on Connect
    ');root_416=from_html('

    No Connection

    ');root_57=from_html('

    ');root_69=from_html("");root_98=from_html("");root_107=from_html("");root_710=from_html('
    Broadcasting?

    If you want to use `LiveSync`, you should broadcast changes. All `watching` peers which\n detects this will start the replication for fetching.
    However, This should not be enabled if you want to increase your secrecy more.

    ',1);root38=from_html('

    Peer to Peer Replicator

    Connection Settings

    Signaling Server Connection

    Peers

    NameActionCommand
    ');$$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}})}};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 _a7;return null==(_a7=null==this?void 0:this._replicatorInstance)?void 0:_a7.enableBroadcastChanges()}disableBroadcastCastings(){var _a7;return null==(_a7=null==this?void 0:this._replicatorInstance)?void 0:_a7.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.services.API.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}}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 _a7,_b5,_c3;if(isChecking)return!(null!=(_c3=null==(_b5=null==(_a7=this._replicatorInstance)?void 0:_a7.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 _a7,_b5,_c3;if(isChecking)return null!=(_c3=null==(_b5=null==(_a7=this._replicatorInstance)?void 0:_a7.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 _a7,_b5,_c3;if(isChecking)return this.settings.remoteType!=REMOTE_P2P&&!!(null==(_b5=null==(_a7=this._replicatorInstance)?void 0:_a7.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.getNewReplicator.addHandler(this._anyNewReplicator.bind(this));services.databaseEvents.onDatabaseInitialisation.addHandler(this._everyOnInitializeDatabase.bind(this));services.appLifecycle.onInitialise.addHandler(this._everyOnloadStart.bind(this));services.appLifecycle.onSuspending.addHandler(this._everyBeforeSuspendProcess.bind(this));services.appLifecycle.onResumed.addHandler(this._everyAfterResumeProcess.bind(this));services.setting.suspendExtraSync.addHandler(this._allSuspendExtraSync.bind(this))}};ServiceHub=class{constructor(context2,services={}){this._injected={};this.context=context2;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}};ServiceContext=class{};ServiceBase=class{constructor(context2){this.context=context2}};APIService=class extends ServiceBase{};Binder=class{constructor(name,initialCallback){this._callback=null;this._name=name;initialCallback&&(this._callback=initialCallback)}assign(callback,override=!1){if(this._callback&&!override)throw new Error(`Handler ${this._name} is already assigned.`);this._callback=callback;return()=>{this._callback=null}}invoke(...args){if(this._callback)return this._callback(...args);throw new Error(`Handler ${this._name} is not assigned.`)}};LazyBinder=class{constructor(name,initialCallback){this._callbackPromise=promiseWithResolvers();this._callback=null;this._name=name;if(initialCallback){this._callback=initialCallback;this._callbackPromise.resolve()}}assign(callback,override=!1){if(this._callback&&!override)throw new Error(`Handler ${this._name} is already assigned.`);this._callback=callback;this._callbackPromise.resolve();return()=>{this._callback=null;this._callbackPromise=promiseWithResolvers()}}async invoke(...args){await this._callbackPromise.promise;if(this._callback)return await this._callback(...args);throw new Error(`Handler ${this._name} is not assigned.`)}};MultiBinder=class{constructor(name){this._callbacks=new Set;this._name=name}addHandler(callback){this._callbacks.add(callback);return()=>{this.removeHandler(callback)}}removeHandler(callback){this._callbacks.delete(callback)}};DispatchParallel=class extends MultiBinder{dispatch(...args){const promises=[...this._callbacks].map((async callback=>{try{return await Promise.resolve(callback(...args))}catch(error){return error instanceof Error?error:new Error(String(error))}}));return Promise.all(promises)}};BooleanHandlerBase=class extends MultiBinder{};AllHandler=class extends BooleanHandlerBase{async invoke(...args){const _callbacks2=[...this._callbacks];for(const callback of _callbacks2)try{if(!1===await Promise.resolve(callback(...args)))return!1}catch(error){Logger(`AllHandler ${this._name} treated error as failure: ${error}`,LOG_LEVEL_VERBOSE);return!1}return!0}};ParallelAllHandler=class extends BooleanHandlerBase{async invoke(...args){const promises=[...this._callbacks].map((async callback=>{try{return await Promise.resolve(callback(...args))}catch(error){Logger(`ParallelAllHandler ${this._name} treated error as failure: ${error}`,LOG_LEVEL_VERBOSE);return!1}}));return(await Promise.all(promises)).every((res2=>!0===res2))}};AnySuccessHandler=class extends BooleanHandlerBase{async invoke(...args){const _callbacks2=[...this._callbacks];for(const callback of _callbacks2)try{if(!0===await Promise.resolve(callback(...args)))return!0}catch(error){Logger(`FirstSuccessHandler ${this._name} ignored error: ${error}`,LOG_LEVEL_VERBOSE)}return!1}};FirstResultHandler=class extends MultiBinder{async invoke(...args){const _callbacks2=[...this._callbacks];for(const callback of _callbacks2)try{const result=await Promise.resolve(callback(...args));if(void 0!==result&&!1!==result)return result}catch(error){Logger(`FirstResultHandler ${this._name} ignored error: ${error}`,LOG_LEVEL_VERBOSE)}return!1}};InjectableAPIService=class extends APIService{constructor(){super(...arguments);this.addLog=handlers2().binder("addLog");this.isLastPostFailedDueToPayloadSize=handlers2().binder("isLastPostFailedDueToPayloadSize")}getPlatform(){return"unknown"}getCrypto(){if("undefined"!=typeof crypto)return crypto;throw new Error("Crypto API is not available in this environment.")}};AppLifecycleService=class extends ServiceBase{constructor(){super(...arguments);this.onLayoutReady=handlers2().bailFirstFailure("onLayoutReady");this.onFirstInitialise=handlers2().bailFirstFailure("onFirstInitialise");this.onReady=handlers2().bailFirstFailure("onReady");this.onWireUpEvents=handlers2().bailFirstFailure("onWireUpEvents");this.onInitialise=handlers2().bailFirstFailure("onInitialise");this.onLoad=handlers2().bailFirstFailure("onLoad");this.onSettingLoaded=handlers2().bailFirstFailure("onSettingLoaded");this.onLoaded=handlers2().bailFirstFailure("onLoaded");this.onScanningStartupIssues=handlers2().all("onScanningStartupIssues");this.onAppUnload=handlers2().dispatchParallel("onAppUnload");this.onBeforeUnload=handlers2().all("onBeforeUnload");this.onUnload=handlers2().all("onUnload");this.onSuspending=handlers2().bailFirstFailure("onSuspending");this.onResuming=handlers2().bailFirstFailure("onResuming");this.onResumed=handlers2().bailFirstFailure("onResumed");this.getUnresolvedMessages=handlers2().dispatchParallel("getUnresolvedMessages")}};InjectableAppLifecycleService=class extends AppLifecycleService{constructor(){super(...arguments);this.performRestart=handlers2().binder("performRestart");this.askRestart=handlers2().binder("askRestart");this.scheduleRestart=handlers2().binder("scheduleRestart");this.isSuspended=handlers2().binder("isSuspended");this.setSuspended=handlers2().binder("setSuspended");this.isReady=handlers2().binder("isReady");this.markIsReady=handlers2().binder("markIsReady");this.resetIsReady=handlers2().binder("resetIsReady");this.hasUnloaded=handlers2().binder("hasUnloaded");this.isReloadingScheduled=handlers2().binder("isReloadingScheduled")}};ConflictService=class extends ServiceBase{constructor(){super(...arguments);this.getOptionalConflictCheckMethod=handlers2().firstResult("getOptionalConflictCheckMethod");this.resolveByUserInteraction=handlers2().firstResult("resolveByUserInteraction")}};InjectableConflictService=class extends ConflictService{constructor(){super(...arguments);this.queueCheckForIfOpen=handlers2().binder("queueCheckForIfOpen");this.queueCheckFor=handlers2().binder("queueCheckFor");this.ensureAllProcessed=handlers2().binder("ensureAllProcessed");this.resolveByDeletingRevision=handlers2().binder("resolveByDeletingRevision");this.resolve=handlers2().binder("resolve");this.resolveByNewest=handlers2().binder("resolveByNewest")}};DatabaseEventService=class extends ServiceBase{constructor(){super(...arguments);this.onUnloadDatabase=handlers2().all("onUnloadDatabase");this.onCloseDatabase=handlers2().all("onCloseDatabase");this.onDatabaseInitialisation=handlers2().bailFirstFailure("onDatabaseInitialisation");this.onDatabaseInitialised=handlers2().bailFirstFailure("onDatabaseInitialised");this.onResetDatabase=handlers2().bailFirstFailure("onResetDatabase")}};InjectableDatabaseEventService=class extends DatabaseEventService{constructor(){super(...arguments);this.initialiseDatabase=handlers2().binder("initialiseDatabase")}};DatabaseService=class extends ServiceBase{};InjectableDatabaseService=class extends DatabaseService{constructor(){super(...arguments);this.createPouchDBInstance=handlers2().binder("createPouchDBInstance");this.openDatabase=handlers2().binder("openDatabase");this.resetDatabase=handlers2().binder("resetDatabase");this.isDatabaseReady=handlers2().binder("isDatabaseReady")}};FileProcessingService=class extends ServiceBase{constructor(){super(...arguments);this.processFileEvent=handlers2().anySuccess("processFileEvent");this.processOptionalFileEvent=handlers2().anySuccess("processOptionalFileEvent");this.commitPendingFileEvents=handlers2().bailFirstFailure("commitPendingFileEvents")}};InjectableFileProcessingService=class extends FileProcessingService{};PathService=class extends ServiceBase{};InjectablePathService=class extends PathService{constructor(){super(...arguments);this.id2path=handlers2().binder("id2path");this.path2id=handlers2().binder("path2id")}};RemoteService=class extends ServiceBase{};InjectableRemoteService=class extends RemoteService{constructor(){super(...arguments);this.replicateAllToRemote=handlers2().binder("replicateAllToRemote");this.replicateAllFromRemote=handlers2().binder("replicateAllFromRemote");this.markLocked=handlers2().binder("markLocked");this.markUnlocked=handlers2().binder("markUnlocked");this.markResolved=handlers2().binder("markResolved");this.tryResetDatabase=handlers2().binder("tryResetDatabase");this.tryCreateDatabase=handlers2().binder("tryCreateDatabase");this.connect=handlers2().binder("connect")}};ReplicationService=class extends ServiceBase{constructor(){super(...arguments);this.processSynchroniseResult=handlers2().anySuccess("processSynchroniseResult");this.processOptionalSynchroniseResult=handlers2().anySuccess("processOptionalSynchroniseResult");this.processVirtualDocument=handlers2().anySuccess("processVirtualDocument");this.onBeforeReplicate=handlers2().bailFirstFailure("onBeforeReplicate");this.checkConnectionFailure=handlers2().firstResult("checkConnectionFailure")}};InjectableReplicationService=class extends ReplicationService{constructor(){super(...arguments);this.parseSynchroniseResult=handlers2().binder("parseSynchroniseResult");this.isReplicationReady=handlers2().binder("isReplicationReady");this.replicate=handlers2().binder("replicate");this.replicateByEvent=handlers2().binder("replicateByEvent")}};ReplicatorService=class extends ServiceBase{constructor(){super(...arguments);this.onCloseActiveReplication=handlers2().anySuccess("onCloseActiveReplication");this.getNewReplicator=handlers2().firstResult("getNewReplicator")}};InjectableReplicatorService=class extends ReplicatorService{constructor(){super(...arguments);this.getActiveReplicator=handlers2().binder("getActiveReplicator")}};SettingService=class extends ServiceBase{constructor(){super(...arguments);this.onBeforeRealiseSetting=handlers2().bailFirstFailure("onBeforeRealiseSetting");this.onSettingRealised=handlers2().bailFirstFailure("onSettingRealised");this.onRealiseSetting=handlers2().bailFirstFailure("onRealiseSetting");this.suspendAllSync=handlers2().all("suspendAllSync");this.suspendExtraSync=handlers2().all("suspendExtraSync");this.suggestOptionalFeatures=handlers2().all("suggestOptionalFeatures");this.enableOptionalFeature=handlers2().all("enableOptionalFeature")}};InjectableSettingService=class extends SettingService{constructor(){super(...arguments);this.clearUsedPassphrase=handlers2().binder("clearUsedPassphrase");this.realiseSetting=handlers2().binder("realiseSetting");this.decryptSettings=handlers2().binder("decryptSettings");this.adjustSettings=handlers2().binder("adjustSettings");this.getDeviceAndVaultName=handlers2().binder("getDeviceAndVaultName");this.setDeviceAndVaultName=handlers2().binder("setDeviceAndVaultName");this.saveDeviceAndVaultName=handlers2().binder("saveDeviceAndVaultName");this.saveSettingData=handlers2().binder("saveSettingData");this.loadSettings=handlers2().binder("loadSettings");this.currentSettings=handlers2().binder("currentSettings");this.shouldCheckCaseInsensitively=handlers2().binder("shouldCheckCaseInsensitively");this.importSettings=handlers2().binder("importSettings")}};TestService=class extends ServiceBase{constructor(){super(...arguments);this.test=handlers2().bailFirstFailure("test");this.testMultiDevice=handlers2().bailFirstFailure("testMultiDevice")}};InjectableTestService=class extends TestService{constructor(){super(...arguments);this.addTestResult=handlers2().binder("addTestResult")}};TweakValueService=class extends ServiceBase{};InjectableTweakValueService=class extends TweakValueService{constructor(){super(...arguments);this.fetchRemotePreferred=handlers2().binder("fetchRemotePreferred");this.checkAndAskResolvingMismatched=handlers2().binder("checkAndAskResolvingMismatched");this.askResolvingMismatched=handlers2().binder("askResolvingMismatched");this.checkAndAskUseRemoteConfiguration=handlers2().binder("checkAndAskUseRemoteConfiguration");this.askUseRemoteConfiguration=handlers2().binder("askUseRemoteConfiguration")}};VaultService=class extends ServiceBase{};InjectableVaultService=class extends VaultService{constructor(){super(...arguments);this.getVaultName=handlers2().binder("getVaultName");this.scanVault=handlers2().binder("scanVault");this.isIgnoredByIgnoreFile=handlers2().binder("isIgnoredByIgnoreFile");this.isTargetFile=handlers2().binder("isTargetFile");this.isFileSizeTooLarge=handlers2().binder("isFileSizeTooLarge");this.getActiveFilePath=handlers2().binder("getActiveFilePath");this.markFileListPossiblyChanged=handlers2().binder("markFileListPossiblyChanged");this.isStorageInsensitive=handlers2().binder("isStorageInsensitive");this.vaultName=handlers2().binder("vaultName")}};InjectableServiceHub=class extends ServiceHub{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}constructor(context2,services){var _a7,_b5,_c3,_d2,_e2,_f,_g,_h2,_i2,_j,_k,_l;super(context2,services);this._api=services.API;this._path=null!=(_a7=services.path)?_a7:new InjectablePathService(context2);this._database=services.database;this._databaseEvents=null!=(_b5=services.databaseEvents)?_b5:new InjectableDatabaseEventService(context2);this._replicator=null!=(_c3=services.replicator)?_c3:new InjectableReplicatorService(context2);this._fileProcessing=null!=(_d2=services.fileProcessing)?_d2:new InjectableFileProcessingService(context2);this._replication=null!=(_e2=services.replication)?_e2:new InjectableReplicationService(context2);this._remote=null!=(_f=services.remote)?_f:new InjectableRemoteService(context2);this._conflict=null!=(_g=services.conflict)?_g:new InjectableConflictService(context2);this._appLifecycle=null!=(_h2=services.appLifecycle)?_h2:new InjectableAppLifecycleService(context2);this._setting=null!=(_i2=services.setting)?_i2:new InjectableSettingService(context2);this._tweakValue=null!=(_j=services.tweakValue)?_j:new InjectableTweakValueService(context2);this._vault=null!=(_k=services.vault)?_k:new InjectableVaultService(context2);this._test=null!=(_l=services.test)?_l:new InjectableTestService(context2);this._ui=services.ui;this._config=services.config}};ObsidianServiceContext=class extends ServiceContext{constructor(app,plugin3,liveSyncPlugin){super();this.app=app;this.plugin=plugin3;this.liveSyncPlugin=liveSyncPlugin}};ConfigService=class extends ServiceBase{};ConfigServiceBrowserCompat=class extends ConfigService{constructor(context2,vaultService){super(context2);this._vaultService=vaultService}getSmallConfig(key3){const dbKey=`${this._vaultService.getVaultName()}-${key3}`;return localStorage.getItem(dbKey)}setSmallConfig(key3,value){const dbKey=`${this._vaultService.getVaultName()}-${key3}`;localStorage.setItem(dbKey,value)}deleteSmallConfig(key3){const dbKey=`${this._vaultService.getVaultName()}-${key3}`;localStorage.removeItem(dbKey)}};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)}};ObsidianAPIService=class extends InjectableAPIService{getCustomFetchHandler(){this._customHandler||(this._customHandler=new ObsHttpHandler(void 0,void 0));return this._customHandler}async showWindow(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])}get app(){return this.context.app}getPlatform(){return 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-obsidian"}isMobile(){return this.app.isMobile}getAppID(){return`${"appId"in this.app?this.app.appId:""}`}getAppVersion(){var _a7,_b5;const match3=(null!=(_b5=null==(_a7=globalThis.navigator)?void 0:_a7.userAgent)?_b5:"").match(/obsidian\/([0-9]+\.[0-9]+\.[0-9]+)/);return match3&&match3.length>=2?match3[1]:"0.0.0"}getPluginVersion(){return this.context.plugin.manifest.version}};ObsidianPathService=class extends InjectablePathService{};ObsidianDatabaseService=class extends InjectableDatabaseService{constructor(){super(...arguments);this.openSimpleStore=handlers2().binder("openSimpleStore")}};ObsidianDatabaseEventService=class extends InjectableDatabaseEventService{};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{};on_click6=(_,copyToClipboard)=>copyToClipboard();root_220=from_html(' ',1);root39=from_html(" ",1);$$css17={hash:"svelte-u2ix67",code:"textarea.svelte-u2ix67 {resize:none;}"};delegate(["click"]);UIService=class extends ServiceBase{constructor(context2,dependents){super(context2);this._confirmInstance=dependents.confirm;this._dialogManager=dependents.dialogManager}get dialogManager(){return this._dialogManager}async promptCopyToClipboard(title,value){const param={title,dataToCopy:value};return"ok"===await this._dialogManager.open(DialogueToCopy,param)}showMarkdownDialog(title,contentMD,buttons,defaultAction){return this._confirmInstance.askSelectStringDialogue(contentMD,buttons,{title,defaultAction:null!=defaultAction?defaultAction:buttons[0],timeout:0})}get confirm(){return this._confirmInstance}};SvelteDialogBase=function SvelteDialogMixIn(TBase){return class SvelteDialog extends TBase{constructor(...args){super(...args);this.title="Obsidian LiveSync - Setup Wizard"}get context(){return this._context}initDialog(context2,dependents,component2,initialData){this._context=context2;this.dependents=dependents;this.component=component2;this.initialData=initialData}resolveResult(){var _a7;null==(_a7=this.resultPromiseWithResolvers)||_a7.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,context:this.context,services:this.dependents})},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)}))}}}(import_obsidian.Modal);SvelteDialogObsidian=class extends SvelteDialogBase{constructor(context2,dependents,component2,initialData){super(context2.app);this.initDialog(context2,dependents,component2,initialData)}};ObsidianSvelteDialogManager=class extends SvelteDialogManagerBase{async openSvelteDialog(component2,initialData){const dialog=new SvelteDialogObsidian(this.context,this.dependents,component2,initialData);dialog.open();return await dialog.waitForClose()}};ObsidianConfirm=class{get _app(){return this._context.app}get _plugin(){return this._context.plugin}constructor(context2){this._context=context2}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 _a7;const popup=await memoIfNotExist(popupKey,(()=>new import_obsidian.Notice(fragment,0)));(null==(_a7=null==popup?void 0:popup.noticeEl)?void 0:_a7.isShown())||memoObject(popupKey,new import_obsidian.Notice(fragment,0));scheduleTask(popupKey+"-close",2e4,(()=>{var _a8;const popup2=retrieveMemoObject(popupKey);if(popup2){(null==(_a8=null==popup2?void 0:popup2.noticeEl)?void 0:_a8.isShown())&&popup2.hide();disposeMemoObject(popupKey)}}))}))}confirmWithMessage(title,contentMd,buttons,defaultAction,timeout){return confirmWithMessage(this._plugin,title,contentMd,buttons,defaultAction,timeout)}};ObsidianUIService=class extends UIService{constructor(context2,dependents){const obsidianConfirm=new ObsidianConfirm(context2),obsidianSvelteDialogManager=new ObsidianSvelteDialogManager(context2,{appLifecycle:dependents.appLifecycle,config:dependents.config,replicator:dependents.replicator,confirm:obsidianConfirm});super(context2,{appLifecycle:dependents.appLifecycle,dialogManager:obsidianSvelteDialogManager,confirm:obsidianConfirm})}};ObsidianServiceHub=class extends InjectableServiceHub{constructor(plugin3){const context2=new ObsidianServiceContext(plugin3.app,plugin3,plugin3),API=new ObsidianAPIService(context2),appLifecycle=new ObsidianAppLifecycleService(context2),conflict=new ObsidianConflictService(context2),database=new ObsidianDatabaseService(context2),fileProcessing=new ObsidianFileProcessingService(context2),replication2=new ObsidianReplicationService(context2),replicator=new ObsidianReplicatorService(context2),remote=new ObsidianRemoteService(context2),setting=new ObsidianSettingService(context2),tweakValue=new ObsidianTweakValueService(context2),vault=new ObsidianVaultService(context2),test=new ObsidianTestService(context2),databaseEvents=new ObsidianDatabaseEventService(context2),path2=new ObsidianPathService(context2),config=new ObsidianConfigService(context2,vault);super(context2,{appLifecycle,conflict,database,databaseEvents,fileProcessing,replication:replication2,replicator,remote,setting,tweakValue,vault,test,ui:new ObsidianUIService(context2,{appLifecycle,config,replicator}),path:path2,API,config})}};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 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.`)}get confirm(){return this.services.UI.confirm}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 */ \ No newline at end of file diff --git a/Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/manifest.json b/Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/manifest.json new file mode 100644 index 0000000..7599247 --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "obsidian-livesync", + "name": "Self-hosted LiveSync", + "version": "0.25.43", + "minAppVersion": "0.9.12", + "description": "Community implementation of self-hosted livesync. Reflect your vault changes to some other devices immediately. Please make sure to disable other synchronize solutions to avoid content corruption or duplication.", + "author": "vorotamoroz", + "authorUrl": "https://github.com/vrtmrz", + "isDesktopOnly": false +} diff --git a/Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/styles.css b/Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/styles.css new file mode 100644 index 0000000..1a51817 --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/plugins/obsidian-livesync/styles.css @@ -0,0 +1,481 @@ +.added { + color: var(--text-on-accent); + background-color: var(--text-accent); +} + +.normal { + color: var(--text-normal); +} + +.deleted { + color: var(--text-on-accent); + background-color: var(--text-muted); +} + +.conflict-dev-name { + display: inline-block; + min-width: 5em; +} + +.op-scrollable { + overflow-y: scroll; + /* min-height: 280px; */ + max-height: 280px; + user-select: text; + -webkit-user-select: text; +} + +.op-pre { + white-space: pre-wrap; +} + +.op-warn { + border: 1px solid salmon; + padding: 2px; + border-radius: 4px; +} + +.op-warn::before { + content: "Warning"; + font-weight: bold; + color: salmon; + position: relative; + display: block; +} + +.op-warn-info { + border: 1px solid rgb(255, 209, 81); + padding: 2px; + border-radius: 4px; +} + +.op-warn-info::before { + content: "Notice"; + font-weight: bold; + color: rgb(255, 209, 81); + position: relative; + display: block; +} + +.syncstatusbar { + -webkit-filter: grayscale(100%); + filter: grayscale(100%); +} + +.tcenter { + text-align: center; +} + +.sls-plugins-wrap { + display: flex; + flex-grow: 1; + max-height: 50vh; + overflow-y: scroll; +} + +.sls-plugins-tbl { + border: 1px solid var(--background-modifier-border); + width: 100%; + max-height: 80%; +} + +.divider th { + border-top: 1px solid var(--background-modifier-border); +} + +.sls-header-button { + margin-left: 2em; +} + +.sls-hidden { + display: none; +} + +:root { + --sls-log-text: ""; +} + +.sls-troubleshoot-preview { + max-width: max-content; +} + +.sls-troubleshoot-preview img { + max-width: 100%; +} + +.sls-setting-tab { + display: none; +} + +div.sls-setting-menu-btn { + color: var(--text-normal); + background-color: var(--background-secondary-alt); + border-radius: 8px; + padding: 6px 10px; + cursor: pointer; + margin-right: 2px; + font-family: "Inter", sans-serif; + outline: none; + user-select: none; + flex-grow: 1; + text-align: center; + flex-shrink: 1; +} + +.sls-setting-label.selected { + /* order: 1; */ + flex-grow: 1; + /* width: 100%; */ +} + +.sls-setting-tab:hover~div.sls-setting-menu-btn, +.sls-setting-label.selected .sls-setting-tab:checked~div.sls-setting-menu-btn { + background-color: var(--interactive-accent); + color: var(--text-on-accent); +} + +.sls-setting-menu-wrapper { + display: flex; + flex-direction: column; + flex-grow: 1; + position: sticky; + top: 0; + backdrop-filter: blur(15px); + padding: 4px; + border-radius: 10px; + z-index: 10; +} + +.sls-setting-menu { + display: flex; + flex-direction: row; + overflow-x: auto; +} + +body { + --sls-col-transparent: transparent; + --sls-col-warn: rgba(var(--background-modifier-error-rgb), 0.1); + --sls-col-warn-stripe1: var(--sls-col-transparent); + --sls-col-warn-stripe2: var(--sls-col-warn); +} + +.sls-setting-menu-buttons { + border: 1px solid var(--sls-col-warn); + padding: 2px; + margin: 1px; + border-radius: 4px; + background-image: linear-gradient(-45deg, + var(--sls-col-warn-stripe1) 25%, var(--sls-col-warn-stripe2) 25%, var(--sls-col-warn-stripe2) 50%, + var(--sls-col-warn-stripe1) 50%, var(--sls-col-warn-stripe1) 75%, var(--sls-col-warn-stripe2) 75%, var(--sls-col-warn-stripe2)); + background-size: 30px 30px; + display: flex; + flex-direction: row; + justify-content: flex-end; + padding: 0.5em 0.25em; + justify-content: center; + align-items: center; + /* transition: background-position 1s; */ + animation: sls-scroll-warn 1s linear 0s infinite; +} + +@keyframes sls-scroll-warn { + 0% { + background-position: 0 0; + } + + 100% { + background-position: 30px 0; + } + +} + +.sls-setting-menu-buttons label { + margin-right: auto; + flex-grow: 1; + color: var(--text-warning); +} + +.sls-setting-label { + flex-grow: 1; + display: inline-flex; + justify-content: center; +} + +.setting-collapsed { + display: none; +} + +.sls-plugins-tbl-buttons { + text-align: right; +} + +.sls-plugins-tbl-buttons button { + flex-grow: 0; + padding: 6px 10px; +} + +.sls-plugins-tbl-device-head { + background-color: var(--background-secondary-alt); + color: var(--text-accent); +} + +.op-flex { + display: flex; +} + +.op-flex input { + display: inline-flex; + flex-grow: 1; + margin-bottom: 8px; +} + +.op-info { + display: inline-flex; + flex-grow: 1; + border-bottom: 1px solid var(--background-modifier-border); + width: 100%; + margin-bottom: 4px; + padding-bottom: 4px; +} + +.history-added { + color: var(--text-on-accent); + background-color: var(--text-accent); +} + +.history-normal { + color: var(--text-normal); +} + +.history-deleted { + color: var(--text-on-accent); + background-color: var(--text-muted); + text-decoration: line-through; +} + +.ob-btn-config-fix label { + margin-right: 40px; +} + +.ob-btn-config-info { + border: 1px solid salmon; + padding: 2px; + margin: 1px; + border-radius: 4px; +} + +.ob-btn-config-head { + padding: 2px; + margin: 1px; + border-radius: 4px; +} + +.isWizard .wizardHidden { + display: none; +} + +.sls-setting:not(.isWizard) .wizardOnly { + display: none; +} + +.sls-item-dirty::before { + content: "✏"; +} + +.sls-item-dirty-help::after { + content: " ❓"; +} + +.sls-item-invalid-value { + background-color: rgba(var(--background-modifier-error-rgb), 0.3) !important; +} + +.sls-setting-disabled input[type=text], +.sls-setting-disabled input[type=number], +.sls-setting-disabled input[type=password] { + filter: brightness(80%); + color: var(--text-muted); + +} + +.sls-setting-hidden { + display: none; +} + + + +.sls-setting-obsolete { + background-image: linear-gradient(-45deg, + var(--sls-col-warn-stripe1) 25%, var(--sls-col-warn-stripe2) 25%, var(--sls-col-warn-stripe2) 50%, + var(--sls-col-warn-stripe1) 50%, var(--sls-col-warn-stripe1) 75%, var(--sls-col-warn-stripe2) 75%, var(--sls-col-warn-stripe2)); + background-image: linear-gradient(-45deg, + transparent 25%, rgba(var(--background-secondary), 0.1) 25%, rgba(var(--background-secondary), 0.1) 50%, transparent 50%, transparent 75%, rgba(var(--background-secondary), 0.1) 75%, rgba(var(--background-secondary), 0.1)); + background-size: 60px 60px; +} + +.password-input>.setting-item-control>input { + -webkit-text-security: disc; +} + +span.ls-mark-cr::after { + user-select: none; + content: "↲"; + color: var(--text-muted); + font-size: 0.8em; +} + +.deleted span.ls-mark-cr::after { + color: var(--text-on-accent); +} + +.ls-imgdiff-wrap { + display: flex; + justify-content: center; + align-items: center; +} + +.ls-imgdiff-wrap .overlay { + position: relative; +} + +.ls-imgdiff-wrap .overlay .img-base { + position: relative; + top: 0; + left: 0; +} + +.ls-imgdiff-wrap .overlay .img-overlay { + -webkit-filter: invert(100%) opacity(50%); + filter: invert(100%) opacity(50%); + position: absolute; + top: 0; + left: 0; + animation: ls-blink-diff 0.5s cubic-bezier(0.4, 0, 1, 1) infinite alternate; +} + +@keyframes ls-blink-diff { + 0% { + opacity: 0; + } + + 50% { + opacity: 0; + } + + 100% { + opacity: 1; + } +} + + +.livesync-status { + user-select: none; + pointer-events: none; + height: auto; + min-height: 1em; + position: absolute; + background-color: transparent; + width: 100%; + padding: 10px; + padding-right: 16px; + top: var(--header-height); + z-index: calc(var(--layer-cover) + 1); + + font-variant-numeric: tabular-nums; + tab-size: 4; + text-align: right; + white-space: pre-wrap; + display: inline-block; + color: var(--text-normal); + font-size: 80%; +} + +div.workspace-leaf-content[data-type=bases] .livesync-status { + top: calc(var(--bases-header-height) + var(--header-height)); + padding: 5px; + padding-right: 18px; +} + +.is-mobile div.workspace-leaf-content[data-type=bases] .livesync-status { + top: calc(var(--bases-header-height) + var(--view-header-height)); + padding: 6px; + padding-right: 18px; +} + +.livesync-status div { + opacity: 0.6; + -webkit-filter: grayscale(100%); + filter: grayscale(100%); +} + +.livesync-status .livesync-status-loghistory { + text-align: left; + opacity: 0.4; + +} + +.livesync-status div.livesync-status-messagearea:empty { + display: none; +} + +.livesync-status div.livesync-status-messagearea:not(:empty) { + opacity: 0.6; + color: var(--text-on-accent); + border: 1px solid var(--background-modifier-error); + background-color: rgba(var(--background-modifier-error-rgb), 0.2); + -webkit-filter: unset; + filter: unset; + width: fit-content; + margin-left: auto; +} + + +.menu-setting-poweruser-disabled .sls-setting-poweruser { + display: none; +} + +.menu-setting-advanced-disabled .sls-setting-advanced { + display: none; +} + +.menu-setting-edgecase-disabled .sls-setting-edgecase { + display: none; +} + +.sls-setting-panel-title { + position: sticky; + font-size: medium; + top: 2.5em; + background-color: var(--background-secondary-alt); + border-radius: 10px; + padding: 0.5em 1.0em; +} + +.active-pane .sls-setting-panel-title { + border: 1px solid var(--interactive-accent); +} + +.sls-dialogue-note-wrapper { + display: flex; + justify-content: flex-end; + align-items: center; +} + +.sls-dialogue-note-countdown { + font-size: 0.8em; +} + +.sls-qr { + display: flex; + justify-content: center; + align-items: center; + max-width: max-content; +} + +.sls-keypair pre { + max-width: 100%; + overflow-x: auto; + white-space: pre-wrap; + word-break: break-all; + +} \ No newline at end of file diff --git a/Naturaale Zwanzig/.obsidian/workspace.json b/Naturaale Zwanzig/.obsidian/workspace.json new file mode 100644 index 0000000..5670af7 --- /dev/null +++ b/Naturaale Zwanzig/.obsidian/workspace.json @@ -0,0 +1,248 @@ +{ + "main": { + "id": "16bad5225a62207b", + "type": "split", + "children": [ + { + "id": "e518aca99020c605", + "type": "tabs", + "children": [ + { + "id": "92bb8ec0bbcdbeb5", + "type": "leaf", + "state": { + "type": "markdown", + "state": { + "file": "Orte/Wildnis.md", + "mode": "source", + "source": false + }, + "icon": "lucide-file", + "title": "Wildnis" + } + } + ] + } + ], + "direction": "vertical" + }, + "left": { + "id": "57167cadad81da4c", + "type": "split", + "children": [ + { + "id": "37ac4941410df2b6", + "type": "tabs", + "children": [ + { + "id": "3665ec7ba01c86b0", + "type": "leaf", + "state": { + "type": "file-explorer", + "state": { + "sortOrder": "alphabetical", + "autoReveal": false + }, + "icon": "lucide-folder-closed", + "title": "Files" + } + }, + { + "id": "dfba905f416d7ac3", + "type": "leaf", + "state": { + "type": "search", + "state": { + "query": "der Wald", + "matchingCase": false, + "explainSearch": false, + "collapseAll": false, + "extraContext": false, + "sortOrder": "alphabetical" + }, + "icon": "lucide-search", + "title": "Search" + } + }, + { + "id": "23c3b028b823a496", + "type": "leaf", + "state": { + "type": "bookmarks", + "state": {}, + "icon": "lucide-bookmark", + "title": "Bookmarks" + } + } + ] + } + ], + "direction": "horizontal", + "width": 300 + }, + "right": { + "id": "79a41f1f05640a42", + "type": "split", + "children": [ + { + "id": "f92838518ac2506f", + "type": "tabs", + "children": [ + { + "id": "445d8b4c6eb7b823", + "type": "leaf", + "state": { + "type": "backlink", + "state": { + "collapseAll": false, + "extraContext": false, + "sortOrder": "alphabetical", + "showSearch": false, + "searchQuery": "", + "backlinkCollapsed": false, + "unlinkedCollapsed": true + }, + "icon": "links-coming-in", + "title": "Backlinks" + } + }, + { + "id": "da66dccf4f9f1770", + "type": "leaf", + "state": { + "type": "outgoing-link", + "state": { + "linksCollapsed": false, + "unlinkedCollapsed": true + }, + "icon": "links-going-out", + "title": "Outgoing links" + } + }, + { + "id": "5540fd651c16a34a", + "type": "leaf", + "state": { + "type": "tag", + "state": { + "sortOrder": "frequency", + "useHierarchy": true, + "showSearch": false, + "searchQuery": "" + }, + "icon": "lucide-tags", + "title": "Tags" + } + }, + { + "id": "a17b32d95305556a", + "type": "leaf", + "state": { + "type": "all-properties", + "state": { + "sortOrder": "frequency", + "showSearch": false, + "searchQuery": "" + }, + "icon": "lucide-archive", + "title": "All properties" + } + }, + { + "id": "68973590f46449f7", + "type": "leaf", + "state": { + "type": "outline", + "state": { + "followCursor": false, + "showSearch": false, + "searchQuery": "" + }, + "icon": "lucide-list", + "title": "Gliederung" + } + }, + { + "id": "79ae27f361516fb9", + "type": "leaf", + "state": { + "type": "git-view", + "state": {}, + "icon": "git-pull-request", + "title": "Source Control" + } + }, + { + "id": "ba0c325185ee8a9f", + "type": "leaf", + "state": { + "type": "git-history-view", + "state": {}, + "icon": "history", + "title": "History" + } + } + ], + "currentTab": 5 + } + ], + "direction": "horizontal", + "width": 616.5 + }, + "left-ribbon": { + "hiddenItems": { + "switcher:Open quick switcher": false, + "graph:Open graph view": false, + "canvas:Create new canvas": false, + "daily-notes:Open today's daily note": false, + "templates:Insert template": false, + "command-palette:Open command palette": false, + "bases:Create new base": false, + "obsidian-livesync:P2P Replicator": false, + "obsidian-livesync:Show Log": false, + "obsidian-livesync:Replicate": false, + "obsidian-git:Open Git source control": false, + "obsidian-livesync:Show Customization sync": false + } + }, + "active": "92bb8ec0bbcdbeb5", + "lastOpenFiles": [ + "Orte/Wildnis.md", + "Orte/Der Kontinent.md", + "Phänomene/Isolatorische Migration.md", + "Phänomene/Myzel.md", + "Timeline.canvas", + "Orte/Siedlungen", + "Orte/Siedlungen/erste Stadt.md", + "Orte/Städte.md", + "Orte/Siedlungen/zweite Stadt.md", + "Orte/Inseln.md", + "Phänomene/Politische Bündnisse.md", + "Daseinsformen/Personen und Gruppen/Gruppen/Myzenauten.md", + "Phänomene/Kataklysmus.md", + "Daseinsformen/Personen und Gruppen/Gruppen/Völker/Die Völker.md", + "Phänomene/Die Vier Aspekte/Kontinuität.md", + "Phänomene/Die Vier Aspekte/Die vier Aspekte.md", + "Phänomene/Magie/Systemischer Magie.md", + "Phänomene/Magie/Magie.md", + "Phänomene/Magie/Resonante Magie.md", + "Phänomene/Neuwelt.md", + "Phänomene/Die Vier Aspekte/Resonanz.md", + "Phänomene/Die Vier Aspekte/Systematik.md", + "Phänomene/Die Vier Aspekte/Anpassung.md", + "Phänomene/Handel.md", + "Phänomene/Magie", + "Phänomene/Altwelt.md", + "Phänomene/Labyrinth.md", + "Phänomene/Odem.md", + "Untitled.base", + "Phänomene/Die Vier Aspekte", + "Wunder", + "Daseinsformen/Personen und Gruppen/Gruppen/Völker", + "Daseinsformen/Personen und Gruppen/Gruppen", + "Daseinsformen/Tierwesen", + "Daseinsformen", + "Phänomene", + "Untitled.canvas" + ] +} \ No newline at end of file diff --git a/Naturaale Zwanzig/Daseinsformen/Personen und Gruppen/Gruppen/Myzenauten.md b/Naturaale Zwanzig/Daseinsformen/Personen und Gruppen/Gruppen/Myzenauten.md index 4aca4d4..4b36b67 100644 --- a/Naturaale Zwanzig/Daseinsformen/Personen und Gruppen/Gruppen/Myzenauten.md +++ b/Naturaale Zwanzig/Daseinsformen/Personen und Gruppen/Gruppen/Myzenauten.md @@ -1,4 +1,4 @@ -[[Myzenauten]] sind die wenigen mutigen Individuen, die sich aus der Sicherheit der [[Städte]] in die vom [[Odem|Odem]] belasteten Untiefen des [[Wald|Waldes]] wagen. +[[Myzenauten]] sind die wenigen mutigen Individuen, die sich aus der Sicherheit der [[Städte]] in die vom [[Odem|Odem]] belasteten Untiefen des [[Wildnis|Waldes]] wagen. Die [[Myzenauten]] sind die Einzige Möglichkeit Information oder Waren zwischen den [[Städte]] zu bewegen. diff --git a/Naturaale Zwanzig/Orte/Der Kontinent.md b/Naturaale Zwanzig/Orte/Der Kontinent.md index 0896b49..8ca605e 100644 --- a/Naturaale Zwanzig/Orte/Der Kontinent.md +++ b/Naturaale Zwanzig/Orte/Der Kontinent.md @@ -1,3 +1,3 @@ -Ein nicht kartografierter Kontinent, der, nach Allgemeinem Wissenstand der [[Die Völker| Völker]] vollständig von einem Dichten [[Wald|Wald]] überwuchert ist, der aufgrund des [[Labyrinth|Labyrinths]] in stetigem Wandel ist. +Ein nicht kartografierter Kontinent, der, nach Allgemeinem Wissenstand der [[Die Völker| Völker]] vollständig von einem Dichten [[Wildnis|Wald]] überwuchert ist, der aufgrund des [[Labyrinth|Labyrinths]] in stetigem Wandel ist. Im inneren des Waldes wächst zudem ein [[Myzel|Myzel]], dass den Bereich unterhalb der Baumkronen mit einem dichten Sporennebel, dem [[Odem|Odem]] flutet. -Die [[Die Völker|Bevölkerung]] siedelt ausschließlich in Gigantischen [[Städte|Städten]], die auf den [[Inseln|Inseln]] Oberhalb des [[Wald|Waldes]] errichtet wurden. \ No newline at end of file +Die [[Die Völker|Bevölkerung]] siedelt ausschließlich in Gigantischen [[Städte|Städten]], die auf den [[Inseln|Inseln]] Oberhalb des [[Wildnis|Waldes]] errichtet wurden. \ No newline at end of file diff --git a/Naturaale Zwanzig/Orte/Inseln.md b/Naturaale Zwanzig/Orte/Inseln.md index b4fd17d..cb3b61b 100644 --- a/Naturaale Zwanzig/Orte/Inseln.md +++ b/Naturaale Zwanzig/Orte/Inseln.md @@ -1,4 +1,4 @@ -Eine Reihe von Felsigen Erhebungen, die sich wie Inseln über die Wipfel des [[Wald|Waldes]] erheben um dem [[Odem|Odem]] zu entkommen. +Eine Reihe von Felsigen Erhebungen, die sich wie Inseln über die Wipfel des [[Wildnis|Waldes]] erheben um dem [[Odem|Odem]] zu entkommen. Die Größeren dieser Erhebungen fungieren als Fundament für Siedlungen, sowie [[Städte]], während kleinere Inseln mit charakteristischen Gravuren und Fresken übersäht sind um im Dickicht des Waldes als Wegmarkierung/Orientierungspunkt zu dienen. An einigen der Kleineren Inseln sind zudem Biwakähnliche Unterkünfte angebracht in denen [[Myzenauten]] nächtigen können, ohne Gefahr zu laufen, dass sich das [[Labyrinth]] mit Ihnen verändert. diff --git a/Naturaale Zwanzig/erste Stadt.md b/Naturaale Zwanzig/Orte/Siedlungen/erste Stadt.md similarity index 100% rename from Naturaale Zwanzig/erste Stadt.md rename to Naturaale Zwanzig/Orte/Siedlungen/erste Stadt.md diff --git a/Naturaale Zwanzig/zweite Stadt.md b/Naturaale Zwanzig/Orte/Siedlungen/zweite Stadt.md similarity index 100% rename from Naturaale Zwanzig/zweite Stadt.md rename to Naturaale Zwanzig/Orte/Siedlungen/zweite Stadt.md diff --git a/Naturaale Zwanzig/Orte/Wald.md b/Naturaale Zwanzig/Orte/Wald.md deleted file mode 100644 index 82601fc..0000000 --- a/Naturaale Zwanzig/Orte/Wald.md +++ /dev/null @@ -1 +0,0 @@ -hallo juno \ No newline at end of file diff --git a/Naturaale Zwanzig/Orte/Wildnis.md b/Naturaale Zwanzig/Orte/Wildnis.md new file mode 100644 index 0000000..41b38fa --- /dev/null +++ b/Naturaale Zwanzig/Orte/Wildnis.md @@ -0,0 +1,19 @@ +Die [[Wildnis]] ist eine durch den [[Kataklysmus]] ausgelöste Superbiosphäre, die den gesamten [[Der Kontinent|Kontinent]] überwuchert und Kommunikation zwischen den [[Städte]]n beinahe unmöglich macht. +Sie ist vor allem durch ihr unnatürlich schnelles Wachstum und ihre Megaflora gekennzeichnet. +Für [[Myzenauten]] ist es nicht unüblich den Himmel kaum, bis garnicht, durch die Baumkronen der ausufernden Gewächse zu sehen, die sich einem Zelt ähnlich über die Wildnis erstrecken. +Ebenso ist es von den [[Inseln]] aus nicht möglich den Boden der [[Wildnis]] einzusehen. + +Dabei ist die [[Wildnis]] keinesfalls als gigantischer Europäischer Mischwald anzusehen, sondern weist in sich eine schier unfassbare Diversität an Biomen auf. +Von klassichen Laub- über Nadel-, oder sogar Regenwald-ähnliche Abschnitten, bis hin zu Sumpfigen oder sogar verwüsteten abschnitten ist fast alles vorhanden. + +Dazu kommt das [[Myzel]], welches die [[Wildnis]] durchzieht und, je nach Stärke des Befalls für Mutationen in Flora und Fauna sorgt, welche sich in Pilz oder Korallenartigen auswüchsen manifestieren. + +Die [[Wildnis]] lässt sich in Ihrem Aufbau grob in 4 von unten nach oben aufeinander aufbauende schichten einteilen: + +- Ruinen (da die [[Wildnis]], aufgrund der Aktivität des [[Labyrinth]]s kaum kartografiert werden kann, ist es möglich auf einer scheinbar bekannten Route auf Ruinen und Überbleibsel der [[Altwelt]], [[Neuwelt]] oder der Zeit der [[Isolatorische Migration]] zu stoßen) + +- Myzel (ist überhaupt Sporenbelastung vorhanden, und wenn ja wie stark, und wie fantastisch hat dies einfluss auf das Biom) + +- Biom (wie hat sich dieses Gelände seit dem Kataklysmus verändert und welche Flora/Fauna hat sich in der Niesche eingefunden) + +- Zugrundeliegendes Gelände (geht es aufwärts, abwärts oder befinden wir uns eventuell in einem ehemaligen Canyon oder dem Grund eines lange versiegten Sees) diff --git a/Naturaale Zwanzig/Phänomene/Die Vier Aspekte/Die vier Aspekte.md b/Naturaale Zwanzig/Phänomene/Die Vier Aspekte/Die vier Aspekte.md index d73902f..057b7ec 100644 --- a/Naturaale Zwanzig/Phänomene/Die Vier Aspekte/Die vier Aspekte.md +++ b/Naturaale Zwanzig/Phänomene/Die Vier Aspekte/Die vier Aspekte.md @@ -1,7 +1,7 @@ Die vier Aspekte stellen den Grundsatz der religiösen bzw. spirituellen ausprägungen auf [[Der Kontinent|dem Kontinent]] . Die Aspekte sind von jeweils einem der [[Die Völker|Völker]] inspirierte Qualitäten die in Form von jeweils 2 Facetten charakterisiert werden: - Die Urbane Facette, die das Verhalten innerhalb der [[Städte]] informiert -- Die Natürliche Facette, die das Verhalten und Überleben innerhalb des [[Wald|Waldes]] informiert. +- Die Natürliche Facette, die das Verhalten und Überleben innerhalb des [[Wildnis|Waldes]] informiert. Wichtig: Diese Facetten und Bezeichnungen sind Ausschließlich OOC zu nutzen. innerhalb der Welt hat jede Stadt/Kommune eigene Charakterisierungen (oft, aber nicht immer, in form von heiligen-figuren, konzepten oder Gottheiten) diff --git a/Naturaale Zwanzig/Phänomene/Die Vier Aspekte/Systematik.md b/Naturaale Zwanzig/Phänomene/Die Vier Aspekte/Systematik.md index ad721cd..1e104ba 100644 --- a/Naturaale Zwanzig/Phänomene/Die Vier Aspekte/Systematik.md +++ b/Naturaale Zwanzig/Phänomene/Die Vier Aspekte/Systematik.md @@ -12,7 +12,7 @@ Die Charakterisierung der urbanen Systematik ist daher oft mit Motiven von Forsc --- -In ihrer natürlichen Facette beschreibt die [[Systematik]] den versuch auch im [[Wald]] Gesetzmäßigkeiten zu erkennen, um sein Verhalten besser Antizipieren zu können. +In ihrer natürlichen Facette beschreibt die [[Systematik]] den versuch auch im [[Wildnis]] Gesetzmäßigkeiten zu erkennen, um sein Verhalten besser Antizipieren zu können. Sie ist die Erkenntnis, dass das komplexe System zu komplex ist um Berechnet werden zu können, aber einzelne Strukturen existieren, die Isoliert und verstanden werden können um wahrscheinliche Vorhersagen treffen zu können. Daher ist die Charakterisierung der natürlichen Systematik oft mit Motiven des Testens, Schätzens und des kalkulierten Risikos verbunden: diff --git a/Naturaale Zwanzig/Phänomene/Kataklysmus.md b/Naturaale Zwanzig/Phänomene/Kataklysmus.md index af58190..0ebc5e3 100644 --- a/Naturaale Zwanzig/Phänomene/Kataklysmus.md +++ b/Naturaale Zwanzig/Phänomene/Kataklysmus.md @@ -1,3 +1,3 @@ -Ein unbestimmter Zeitpunkt, vermutlich in Konsequenz eines Großen Krieges zwischen den [[Die Völker|Völkern]] zu Zeiten der [[Neuwelt]] in folge dessen [[Der Kontinent]] von einem dichten [[Wald]] überwuchert wurde und der Ursprung des [[Myzel|Myzels]] liegt. +Ein unbestimmter Zeitpunkt, vermutlich in Konsequenz eines Großen Krieges zwischen den [[Die Völker|Völkern]] zu Zeiten der [[Neuwelt]] in folge dessen [[Der Kontinent]] von einem dichten [[Wildnis]] überwuchert wurde und der Ursprung des [[Myzel|Myzels]] liegt. Der [[Kataklysmus]] hängt irgendwie mit der Aktivierung des [[Labyrinth]]s zusammen. diff --git a/Naturaale Zwanzig/Phänomene/Labyrinth.md b/Naturaale Zwanzig/Phänomene/Labyrinth.md index 533f145..2fba3ca 100644 --- a/Naturaale Zwanzig/Phänomene/Labyrinth.md +++ b/Naturaale Zwanzig/Phänomene/Labyrinth.md @@ -1,4 +1,4 @@ -Ein Uraltes Labyrinth, das im Zentrum des [[Wald|Waldes]] liegt und sich ab und zu verändert. +Ein Uraltes Labyrinth, das im Zentrum des [[Wildnis|Waldes]] liegt und sich ab und zu verändert. Niemand auf [[Der Kontinent]] weis wer das Labyrinth errichtet hat und welchen Zweck es erfüllt. Alles was bekannt ist, ist, dass Im inneren des Labyrinths der Grund für die Wanderung der [[Die Völker|Völker]] auf [[Inseln]] begründet liegt. diff --git a/Naturaale Zwanzig/Phänomene/Myzel.md b/Naturaale Zwanzig/Phänomene/Myzel.md index dbac3a4..7b15da3 100644 --- a/Naturaale Zwanzig/Phänomene/Myzel.md +++ b/Naturaale Zwanzig/Phänomene/Myzel.md @@ -1,3 +1,3 @@ -Eine Uralte Pilzkolonie, die Große Teile des [[Wald|Waldes]] befallen hat und in einer Symbiose mit ihm lebt. -der Befall variiert von Bereich zu Bereich in seiner Schwere und verläuft Adernartig durch den [[Wald|Wald]]. +Eine Uralte Pilzkolonie, die Große Teile des [[Wildnis|Waldes]] befallen hat und in einer Symbiose mit ihm lebt. +der Befall variiert von Bereich zu Bereich in seiner Schwere und verläuft Adernartig durch den [[Wildnis|Wald]]. Von den Höchsten Konzentrationen des Pilzes geht ein Konstanter Sporendunst aus, [[Odem]]. diff --git a/Naturaale Zwanzig/Phänomene/Pantheon.md b/Naturaale Zwanzig/Phänomene/Pantheon.md index 4927861..b76c84a 100644 --- a/Naturaale Zwanzig/Phänomene/Pantheon.md +++ b/Naturaale Zwanzig/Phänomene/Pantheon.md @@ -12,7 +12,7 @@ Heute werden sie von allen Völkern erzählt, angepasst, widersprochen und weite Jede dieser [[Die vier Aspekte|vier Figuren besitzt]] **zwei Facetten**, die nicht als getrennte Gestalten verstanden werden. - eine Facette, die das Leben in den [[Städte|Städten]] erklärt und strukturiert -- eine Facette, die Hinweise für das Überleben im [[Wald|Wald]] und im [[Odem]] liefert +- eine Facette, die Hinweise für das Überleben im [[Wildnis|Wald]] und im [[Odem]] liefert Diese Facetten sind widerspruchsfrei, jedoch **nicht austauschbar**. Eine Erzählung, die in den Städten Orientierung bietet, kann im Wald irreführend oder tödlich sein.